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-18T21:08:23.296828+00:00 | 2019-11-29T08:57:49 | 6440fc15d508a3a984903e0e53f4dce21e721874 | {
"blob_id": "6440fc15d508a3a984903e0e53f4dce21e721874",
"branch_name": "refs/heads/master",
"committer_date": "2019-11-29T08:57:49",
"content_id": "3f5a06df648357fec4c98893a47e1b68c92a3a4f",
"detected_licenses": [
"MIT"
],
"directory_id": "3be73c3d9d1008a2470659bed323464768996307",
"extension": "c",
"filename": "main.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 209197604,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2753,
"license": "MIT",
"license_type": "permissive",
"path": "/huffman_code/main.c",
"provenance": "stackv2-0069.json.gz:237957",
"repo_name": "Tnze/data_struct_exercises",
"revision_date": "2019-11-29T08:57:49",
"revision_id": "5e730c1c4d86bb744dfe4b4350f6024af878c805",
"snapshot_id": "b322f5c51f0649ba043a724d692c0c246364fe0d",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Tnze/data_struct_exercises/5e730c1c4d86bb744dfe4b4350f6024af878c805/huffman_code/main.c",
"visit_date": "2020-07-27T19:35:52.887256"
} | stackv2 | #include <stdio.h>
#include <stdlib.h>
#include <limits.h>
struct HuffmanNode
{
int value;
struct HuffmanNode *lst, *rst;
};
struct HuffmanForest
{
struct HuffmanNode *tree;
struct HuffmanForest *next;
};
void insert(struct HuffmanForest *forest, struct HuffmanForest *node)
{
for (struct HuffmanForest *i = forest;; i = i->next)
{
if (i->next == NULL || i->next->tree->value > node->tree->value)
{
node->next = i->next;
i->next = node;
break;
}
}
}
void printHuffmanTree(struct HuffmanNode *tree, int deep)
{
if (tree->lst != NULL)
printHuffmanTree(tree->lst, deep + 1);
// 输出缩进
for (int i = 0; i < deep; i++)
printf("\t");
printf("[%4d]\n", tree->value);
if (tree->rst != NULL)
printHuffmanTree(tree->rst, deep + 1);
}
void printHuffmanCode(struct HuffmanNode *tree, int perfix)
{
if (tree->lst == NULL && tree->rst == NULL)
{
printf("%4d -> ", tree->value);
int pre0 = 1;
for (int i = 7; i >= 0; i--)
{
int c = (perfix >> i) & 1;
pre0 = pre0 && !c;
printf("%c", pre0&&i ? ' ' : c ? '1' : '0');
}
printf("\n");
}
if (tree->lst != NULL)
printHuffmanCode(tree->lst, perfix << 1 | 0);
if (tree->rst != NULL)
printHuffmanCode(tree->rst, perfix << 1 | 1);
}
int main()
{
int data[] = {45, 76, 87, 234, 8, 9, 23, 65};
const int data_len = sizeof(data) / sizeof(data[0]);
// 构造森林
struct HuffmanForest forest;
forest.next = NULL;
for (int i = 0; i < data_len; i++)
{
struct HuffmanForest *node = malloc(sizeof(struct HuffmanForest));
node->tree = malloc(sizeof(struct HuffmanNode));
node->tree->lst = node->tree->rst = NULL;
node->tree->value = data[i];
insert(&forest, node);
}
// 输出森林
for (struct HuffmanForest *i = forest.next; i != NULL; i = i->next)
printf("%d\n", i->tree->value);
for (int i = 0; i < data_len - 1; i++)
{
struct HuffmanForest *t1 = forest.next, *t2 = t1->next, *other = t2->next;
struct HuffmanForest *node = malloc(sizeof(struct HuffmanForest));
node->tree = malloc(sizeof(struct HuffmanNode));
node->tree->value = t1->tree->value + t2->tree->value;
node->tree->lst = t1->tree;
node->tree->rst = t2->tree;
free(t1);
free(t2);
forest.next = other; // 此时删去了前两个元素
insert(&forest, node);
}
// 输出哈夫曼树
printHuffmanTree(forest.next->tree, 0);
// 输出哈夫曼编码
printHuffmanCode(forest.next->tree, 0);
return 0;
}
| 3.40625 | 3 |
2024-11-18T21:08:23.380645+00:00 | 2016-04-23T21:05:38 | 3e2508094fbc3acb5178e75364fc626f244e48c7 | {
"blob_id": "3e2508094fbc3acb5178e75364fc626f244e48c7",
"branch_name": "refs/heads/master",
"committer_date": "2016-04-23T21:05:38",
"content_id": "3c646b718d91fe7aa2486832e9221924171622a5",
"detected_licenses": [
"CC0-1.0"
],
"directory_id": "073133f771d7738fbab8d805b52145bcedfdc679",
"extension": "c",
"filename": "Serial.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 56614885,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1616,
"license": "CC0-1.0",
"license_type": "permissive",
"path": "/src/serial/Serial.c",
"provenance": "stackv2-0069.json.gz:238086",
"repo_name": "Hazybot/Robot_Development_2015-2016",
"revision_date": "2016-04-23T21:05:38",
"revision_id": "8dcf6b7937e9d3d7fdfc7cc2077c8ed29a4eb967",
"snapshot_id": "24fe7912ef9af335eecf3e544129c9a518336db8",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Hazybot/Robot_Development_2015-2016/8dcf6b7937e9d3d7fdfc7cc2077c8ed29a4eb967/src/serial/Serial.c",
"visit_date": "2016-09-13T12:13:10.722892"
} | stackv2 | #include "Serial.h"
int open_s(char *name){
struct termios toptions ;
int fd;
#ifdef DEBUG
printf("Open serial : %s\n", name) ;
#endif
if((fd = open(name, O_RDWR))== -1){
printf("Error opening %s\n", name);
return -1;
}
#ifdef DEBUG
printf("wait\n") ;
#endif
usleep(300000) ;
if(tcgetattr(fd, &toptions) == -1){
printf("Error getting attribut from %s\n", name);
return -1;
}
cfsetispeed(&toptions, B9600) ;
cfsetospeed(&toptions, B9600) ;
toptions.c_cflag &= ~PARENB ;
toptions.c_cflag &= ~CSTOPB ;
toptions.c_cflag &= ~CSIZE;
toptions.c_cflag |= CS8 ;
toptions.c_cflag &= ~CRTSCTS;
if(tcsetattr(fd, TCSANOW, &toptions) == -1){
printf("Error setting attribut to %s\n", name);
return -1;
}
usleep(300000);
#ifdef DEBUG
printf("Serial port open\n") ;
#endif
return fd;
}
int close_s(int fd){
#ifdef DEBUG
printf("Close serial : %d\n", fd);
#endif
return close(fd);
}
int write_s(int fd, uint8_t *buffer, int nbyte){
#ifdef DEBUG
printf("Envoie de %s à l'arduino %d\n", buffer, fd);
#endif
int val=0;
val+= write(fd, "#", 1);
val+= write(fd, buffer, nbyte);
val+= write(fd, "!", 1);
return val;
}
int read_s(int fd, uint8_t *buffer, int nbyte){
uint8_t* car = (uint8_t*)malloc(1);
if(read(fd,car,0) == -1){
printf("Erreur reading file");
free(car);
return -1;
}
while(*car != '#'){
read(fd,car,1);
}
int cpt=0;
while(*car != '!' && cpt < nbyte){
if(read(fd, car, 1) == 1){
*(buffer + cpt) = *car;
cpt++;
}
}
free(car);
#ifdef DEBUG
printf("Reception de %s de l'arduino %d\n", buffer, fd);
#endif
return 1;
}
| 2.890625 | 3 |
2024-11-18T21:08:23.643068+00:00 | 2021-08-13T03:13:47 | 491e0445a0dd07b50112f410da3cd472b8abeba4 | {
"blob_id": "491e0445a0dd07b50112f410da3cd472b8abeba4",
"branch_name": "refs/heads/master",
"committer_date": "2021-08-13T03:13:47",
"content_id": "d239952b58de4df4aa08f6cf792534487821c9a2",
"detected_licenses": [
"BSD-3-Clause",
"MIT"
],
"directory_id": "7a8ba610ac92c458e77ac533020e59547c8c06da",
"extension": "c",
"filename": "fontbutton.c",
"fork_events_count": 0,
"gha_created_at": "2018-12-06T22:07:14",
"gha_event_created_at": "2021-08-13T03:13:48",
"gha_language": "C++",
"gha_license_id": "BSD-3-Clause",
"github_id": 160738449,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1889,
"license": "BSD-3-Clause,MIT",
"license_type": "permissive",
"path": "/libui/alpha_4.1/libui/unix/fontbutton.c",
"provenance": "stackv2-0069.json.gz:238343",
"repo_name": "DolbyLaboratories/pmd_tool",
"revision_date": "2021-08-13T03:13:47",
"revision_id": "4c6d27df5f531d488a627f96f489cf213cbf121a",
"snapshot_id": "b29dc50400024f7da3ba651675ced360c7d4b91c",
"src_encoding": "UTF-8",
"star_events_count": 16,
"url": "https://raw.githubusercontent.com/DolbyLaboratories/pmd_tool/4c6d27df5f531d488a627f96f489cf213cbf121a/libui/alpha_4.1/libui/unix/fontbutton.c",
"visit_date": "2022-10-23T19:45:29.418814"
} | stackv2 | // 14 april 2016
#include "uipriv_unix.h"
#include "attrstr.h"
struct uiFontButton {
uiUnixControl c;
GtkWidget *widget;
GtkButton *button;
GtkFontButton *fb;
GtkFontChooser *fc;
void (*onChanged)(uiFontButton *, void *);
void *onChangedData;
};
uiUnixControlAllDefaults(uiFontButton)
// TODO NOTE no need to inhibit the signal; font-set is documented as only being sent when the user changes the font
static void onFontSet(GtkFontButton *button, gpointer data)
{
uiFontButton *b = uiFontButton(data);
(*(b->onChanged))(b, b->onChangedData);
}
static void defaultOnChanged(uiFontButton *b, void *data)
{
// do nothing
}
void uiFontButtonFont(uiFontButton *b, uiFontDescriptor *desc)
{
PangoFontDescription *pdesc;
pdesc = gtk_font_chooser_get_font_desc(b->fc);
uiprivFontDescriptorFromPangoFontDescription(pdesc, desc);
// pdesc is transfer-full and thus is a copy
pango_font_description_free(pdesc);
}
void uiFontButtonOnChanged(uiFontButton *b, void (*f)(uiFontButton *, void *), void *data)
{
b->onChanged = f;
b->onChangedData = data;
}
uiFontButton *uiNewFontButton(void)
{
uiFontButton *b;
uiUnixNewControl(uiFontButton, b);
b->widget = gtk_font_button_new();
b->button = GTK_BUTTON(b->widget);
b->fb = GTK_FONT_BUTTON(b->widget);
b->fc = GTK_FONT_CHOOSER(b->widget);
// match behavior on other platforms
gtk_font_button_set_show_style(b->fb, TRUE);
gtk_font_button_set_show_size(b->fb, TRUE);
gtk_font_button_set_use_font(b->fb, FALSE);
gtk_font_button_set_use_size(b->fb, FALSE);
// other customizations
gtk_font_chooser_set_show_preview_entry(b->fc, TRUE);
g_signal_connect(b->widget, "font-set", G_CALLBACK(onFontSet), b);
uiFontButtonOnChanged(b, defaultOnChanged, NULL);
return b;
}
void uiFreeFontButtonFont(uiFontDescriptor *desc)
{
// TODO ensure this is synchronized with fontmatch.c
uiFreeText((char *) (desc->Family));
}
| 2.3125 | 2 |
2024-11-18T21:08:23.712887+00:00 | 2020-05-16T08:00:30 | 7badce8cfb364cfd24574b3c4768f38864b932b7 | {
"blob_id": "7badce8cfb364cfd24574b3c4768f38864b932b7",
"branch_name": "refs/heads/master",
"committer_date": "2020-05-16T08:00:30",
"content_id": "9f6fe73c191ed71d5f20caf42991d817025b580f",
"detected_licenses": [
"MIT"
],
"directory_id": "506d7910827b44677f181be3eb0054955bc7b391",
"extension": "c",
"filename": "login.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 251221972,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3135,
"license": "MIT",
"license_type": "permissive",
"path": "/definition/login.c",
"provenance": "stackv2-0069.json.gz:238471",
"repo_name": "trychen/Marketing4C",
"revision_date": "2020-05-16T08:00:30",
"revision_id": "95628ad69c2cbb8985efe0f9a86e5556e155ba89",
"snapshot_id": "da03387e11e47d98a00317a0fde1e191579cfbdd",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/trychen/Marketing4C/95628ad69c2cbb8985efe0f9a86e5556e155ba89/definition/login.c",
"visit_date": "2021-05-18T11:11:43.517464"
} | stackv2 | #include "login.h"
char * CURRENT_PASSWORD;
bool initPassword() {
// 创建密码读入缓冲区
char buf[MAX_LENGTH_PASSWORD];
FILE *fp = fopen(PASSWORD_BIN_PATH,"r");
// 文件为空,密码未初始化
if(fp == NULL) {
return true;
}
// 读取数据
if (fgets(buf, MAX_LENGTH_PASSWORD, fp) != NULL) {
size_t length = strlen(buf);
// 解密
for (int i = 0; i < length; ++i) {
buf[i] = buf[i] + i + 3;
}
// 拷贝密码到新的内存空间
char *loadedPassword = calloc(length, sizeof(char));
strcpy(loadedPassword, buf);
// 存储密码变量
CURRENT_PASSWORD = loadedPassword;
fclose(fp);
return true;
}
// 读取失败
fclose(fp);
perror("加载校验文件失败,将重置密码");
return false;
}
void setPassword(const char *input) {
// 拷贝密码到新的内存空间
char *new = calloc(MAX_LENGTH_PASSWORD, sizeof(char));
strcpy(new, input);
// 加密
int len = strlen(input);
for (int i = 0; i < len; ++i) {
*(new + i) = *(new + i) - i - 3;
}
// 写入文件
FILE *fp = fopen(PASSWORD_BIN_PATH,"w");
fputs(new, fp);
fclose(fp);
// 释放已有的密码
if (CURRENT_PASSWORD != NULL) {
free(CURRENT_PASSWORD);
}
CURRENT_PASSWORD = new;
}
void commandResetPassword() {
printf("▧ 修改密码\n");
printf("↳ 请输入原密码:");
char password[20];
scanf("%s", password);
if (strcmp(password, CURRENT_PASSWORD) != 0) {
printf("× 原密码不匹配,设置失败!\n");
return;
}
printf("↳ 请输入新的密码:");
scanf("%s", password);
char confirmPassword[20];
printf("↳ 再次输入新的密码:");
scanf("%s", confirmPassword);
if (strcmp(password, confirmPassword) != 0) {
printf("× 两次输入的密码不一致,设置失败!\n");
return;
}
setPassword(password);
printf("\n◉ 修改密码成功!\n\n");
}
void login() {
if (CURRENT_PASSWORD == NULL) {
// 未设置密码
char password[20];
for (;;) {
printf("↳ 初次使用请先设置密码:");
scanf("%s", password);
char confirmPassword[20];
printf("↳ 再次输入密码以确认:");
scanf("%s", confirmPassword);
if (strcmp(password, confirmPassword) == 0) {
printf("\n◉ 设置成功,已为你自动登录!\n");
break;
}
printf("× 两次输入的密码不一致,请重新输入!\n\n");
}
setPassword(password);
} else {
char password[20];
for (;;) {
printf("↳ 请输入密码登录:");
scanf("%s", password);
if (strcmp(password, CURRENT_PASSWORD) == 0) {
printf("\n◉ 登录成功!\n\n");
break;
}
printf("× 密码错误,请重新输入\n\n");
}
}
} | 3.125 | 3 |
2024-11-18T21:08:23.813015+00:00 | 2020-08-07T05:35:49 | 1d3d59a3bd02423954926c261d03735f3ef97bc7 | {
"blob_id": "1d3d59a3bd02423954926c261d03735f3ef97bc7",
"branch_name": "refs/heads/master",
"committer_date": "2020-08-07T05:35:49",
"content_id": "69582597e6722699ffcd49b0fa42a4674002c978",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "8204ed9f9aee678b0601063ff1df0f3005db5009",
"extension": "c",
"filename": "ngx_http_ndg_subrequest_module.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": 4568,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/ndg_subrequest/ngx_http_ndg_subrequest_module.c",
"provenance": "stackv2-0069.json.gz:238602",
"repo_name": "renz2048/ndg_module_example",
"revision_date": "2020-08-07T05:35:49",
"revision_id": "6e71e5ae1b16abcd6b9cdfa6e7db8b06725461dc",
"snapshot_id": "8ede45d64e3fc7a1d3c6e30a4908046f83547707",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/renz2048/ndg_module_example/6e71e5ae1b16abcd6b9cdfa6e7db8b06725461dc/ndg_subrequest/ngx_http_ndg_subrequest_module.c",
"visit_date": "2022-11-26T20:47:56.747527"
} | stackv2 | #include <ngx_http.h>
#include <nginx.h>
static void *ngx_http_ndg_subrequest_create_loc_conf(ngx_conf_t* cf);
static char *ngx_http_ndg_subrequest_merge_loc_conf(ngx_conf_t*cf, void* parent, void* child);
static ngx_int_t ngx_http_ndg_subrequest_post_handler(ngx_http_request_t *r, void *data, ngx_int_t rc);
static ngx_int_t ngx_http_ndg_subrequest_init(ngx_conf_t *cf);
static ngx_int_t ngx_http_ndg_subrequest_handler(ngx_http_request_t *r);
/**
* 定义模块配置信息
*/
typedef struct {
ngx_str_t uri;
} ngx_http_ndg_subrequest_loc_conf_t;
/**
* 在 ctx 里存储子请求的输出数据
*/
typedef struct {
ngx_http_request_t *sr;
} ngx_http_ndg_subrequest_ctx_t;
static ngx_command_t ngx_http_ndg_subrequest_cmds[] =
{
{
ngx_string("ndg_subrequest"),
NGX_HTTP_LOC_CONF|NGX_CONF_TAKE1,
ngx_conf_set_str_slot,
NGX_HTTP_LOC_CONF_OFFSET,
offsetof(ngx_http_ndg_subrequest_loc_conf_t, uri),
NULL
},
ngx_null_command
};
static ngx_http_module_t ngx_http_ndg_subrequest_module_ctx =
{
NULL,
ngx_http_ndg_subrequest_init,
NULL,
NULL,
NULL,
NULL,
ngx_http_ndg_subrequest_create_loc_conf,
ngx_http_ndg_subrequest_merge_loc_conf,
};
ngx_module_t ngx_http_ndg_subrequest_module =
{
NGX_MODULE_V1,
&ngx_http_ndg_subrequest_module_ctx,
ngx_http_ndg_subrequest_cmds,
NGX_HTTP_MODULE,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NGX_MODULE_V1_PADDING
};
static void *ngx_http_ndg_subrequest_create_loc_conf(
ngx_conf_t* cf)
{
ngx_http_ndg_subrequest_loc_conf_t* conf;
conf = ngx_pcalloc(cf->pool, sizeof(ngx_http_ndg_subrequest_loc_conf_t));
return conf;
}
static char *ngx_http_ndg_subrequest_merge_loc_conf(
ngx_conf_t*cf, void* parent, void* child)
{
ngx_http_ndg_subrequest_loc_conf_t* prev = parent;
ngx_http_ndg_subrequest_loc_conf_t* conf = child;
ngx_conf_merge_str_value(conf->uri, prev->uri, "");
return NGX_CONF_OK;
}
/**
* 子请求回调函数
* 将子请求指针放置在本模块的 ctx 里,回传给父请求
*/
static ngx_int_t
ngx_http_ndg_subrequest_post_handler(
ngx_http_request_t *r, void *data, ngx_int_t rc)
{
ngx_http_request_t *pr;
ngx_http_ndg_subrequest_ctx_t *ctx;
pr = r->parent;//获取父请求
pr->write_event_handler = ngx_http_core_run_phases;//设置付请求的回调函数
ctx = ngx_http_get_module_ctx(
pr, ngx_http_ndg_subrequest_module);
if (ctx == NULL) {
ctx = ngx_pcalloc(pr->pool, sizeof(ngx_http_ndg_subrequest_ctx_t));
ngx_http_set_ctx(pr, ctx, ngx_http_ndg_subrequest_module);
}
ctx->sr = r;
return NGX_OK;
}
/**
* 注册函数
* 为了在 access 阶段工作
* 在 ngx_http_core_module 的 phases 数组添加处理函数
*/
static ngx_int_t ngx_http_ndg_subrequest_init(ngx_conf_t *cf)
{
ngx_http_handler_pt *h;
ngx_http_core_main_conf_t *cmcf;
cmcf = ngx_http_conf_get_module_main_conf(cf, ngx_http_core_module);
h = ngx_array_push(&cmcf->phases[NGX_HTTP_ACCESS_PHASE].handlers);
*h = ngx_http_ndg_subrequest_handler;
return NGX_OK;
}
/**
* 处理函数
* 若 ctx 为空,发起子请求;否则检查子请求结束后返回的数据
*/
static ngx_int_t ngx_http_ndg_subrequest_handler(
ngx_http_request_t *r)
{
ngx_http_ndg_subrequest_loc_conf_t *lcf;
ngx_http_ndg_subrequest_ctx_t *ctx;
ngx_http_post_subrequest_t *psr;
ngx_http_request_t *sr;
ngx_int_t rc;
ngx_str_t str;
lcf = ngx_http_get_module_loc_conf(
r, ngx_http_ndg_subrequest_module);
if (lcf->uri.len == 0) {
return NGX_DECLINED;//空字符串不处理
}
ctx = ngx_http_get_module_ctx(
r, ngx_http_ndg_subrequest_module);
if (ctx == NULL) {//空则需要发起子请求
psr = ngx_pcalloc(
r->pool, sizeof(ngx_http_post_subrequest_t));
//子请求回调函数对象
psr->handler = ngx_http_ndg_subrequest_post_handler;
sr = ctx->sr;
rc = ngx_http_subrequest(r, &lcf->uri, &r->args, &sr, psr, NGX_HTTP_SUBREQUEST_IN_MEMORY);
if (rc != NGX_OK) {
return NGX_ERROR;
}
return NGX_DONE;
}
sr = ctx->sr;
str.data = sr->out->buf->pos;
str.len = ngx_buf_size(sr->out->buf);
ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "ndg_subrequest ok, body is %V", &str);
return sr->headers_out.status == NGX_HTTP_OK ? NGX_OK:NGX_HTTP_FORBIDDEN;
} | 2.5 | 2 |
2024-11-18T21:08:24.108337+00:00 | 2023-08-08T09:39:15 | fcefd2aaf291cad6a51130c00a1507a81636ecc7 | {
"blob_id": "fcefd2aaf291cad6a51130c00a1507a81636ecc7",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-08T09:39:15",
"content_id": "78fb8a140d1d4532cb78a1b30112ee436f020c29",
"detected_licenses": [
"ISC"
],
"directory_id": "f8cc1dd4b1378490386def2e0571561fab10b275",
"extension": "h",
"filename": "bytestr.h",
"fork_events_count": 32,
"gha_created_at": "2015-02-28T12:01:41",
"gha_event_created_at": "2021-04-11T10:10:54",
"gha_language": "C",
"gha_license_id": "ISC",
"github_id": 31461366,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1953,
"license": "ISC",
"license_type": "permissive",
"path": "/src/include/skalibs/bytestr.h",
"provenance": "stackv2-0069.json.gz:238859",
"repo_name": "skarnet/skalibs",
"revision_date": "2023-08-08T09:39:15",
"revision_id": "1f2d5f95684e93f8523e369ef1fed7a75c444082",
"snapshot_id": "b1eb2a0e38663cbfa918ee0a7916f56227bd7c2d",
"src_encoding": "UTF-8",
"star_events_count": 104,
"url": "https://raw.githubusercontent.com/skarnet/skalibs/1f2d5f95684e93f8523e369ef1fed7a75c444082/src/include/skalibs/bytestr.h",
"visit_date": "2023-08-23T07:33:20.996016"
} | stackv2 | /* ISC license. */
#ifndef SKALIBS_BYTESTR_H
#define SKALIBS_BYTESTR_H
/* for Alphas and other archs where char != 8bit */
#define T8(x) ((x) & 0xffU)
#include <string.h>
#include <strings.h>
#include <skalibs/gccattributes.h>
#define byte_copy(to, n, from) memmove(to, (from), n)
#define byte_copyr(to, n, from) memmove(to, (from), n)
#define byte_diff(a, n, b) memcmp(a, (b), n)
#define byte_zero(p, n) memset(p, 0, n)
#define str_len strlen
#define str_nlen strnlen
#define str_diff strcmp
#define str_diffn strncmp
#define str_copy(to, from) strlen(strcpy(to, from))
#define case_diffs strcasecmp
#define case_diffn strncasecmp
extern size_t byte_chr (char const *, size_t, int) gccattr_pure ;
extern size_t byte_rchr (char const *, size_t, int) gccattr_pure ;
extern size_t byte_in (char const *, size_t, char const *, size_t) gccattr_pure ;
#define byte_equal(s, n, t) (!memcmp(s, (t), n))
extern size_t byte_count (char const *, size_t, char) gccattr_pure ;
extern size_t byte_search (char const *, size_t, char const *, size_t) ;
extern void byte_zzero (char *, size_t) ;
#define str_diffb(a, n, b) strncmp(a, (b), n)
extern size_t str_chr (char const *, int) gccattr_pure ;
extern size_t str_rchr (char const *, int) gccattr_pure ;
extern int str_start (char const *, char const *) gccattr_pure ;
#define str_equal(s, t) (!strcmp(s, t))
extern size_t str_strn (char const *, size_t, char const *, size_t) gccattr_pure ;
extern void case_lowers (char *) ;
extern void case_lowerb (char *, size_t) ;
extern void case_uppers (char *) ;
extern void case_upperb (char *, size_t) ;
#define case_diffb(a, n, b) case_diffn(a, (b), n)
#define case_equals(a, b) (!strcasecmp(a, b))
#define case_equalb(a, n, b) (!strncasecmp(a, (b), n))
#define case_starts(s, t) case_startb(s, strlen(s), t)
extern int case_startb (char const *, size_t, char const *) gccattr_pure ;
extern size_t case_str (char const *, char const *) gccattr_pure ;
#endif
| 2.34375 | 2 |
2024-11-18T21:08:24.815440+00:00 | 2021-11-10T18:07:30 | 6ff72d68b42090233e2bd18d16f772379c5515c1 | {
"blob_id": "6ff72d68b42090233e2bd18d16f772379c5515c1",
"branch_name": "refs/heads/main",
"committer_date": "2021-11-10T18:07:30",
"content_id": "3b0bb2f8c28c7e7a223f59b65bfb455d85744b03",
"detected_licenses": [
"MIT"
],
"directory_id": "a60852e1a3e2cbd51244e676874fa30ec937cdea",
"extension": "c",
"filename": "main.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 359796835,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1296,
"license": "MIT",
"license_type": "permissive",
"path": "/main.c",
"provenance": "stackv2-0069.json.gz:239116",
"repo_name": "spratyey/TreeWalker",
"revision_date": "2021-11-10T18:07:30",
"revision_id": "096039ab471a5ed0e458c8e6c006135fc76fb058",
"snapshot_id": "41f7e39251230de6f215797aee379f887d214d6b",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/spratyey/TreeWalker/096039ab471a5ed0e458c8e6c006135fc76fb058/main.c",
"visit_date": "2023-08-27T03:28:02.126391"
} | stackv2 | #include "TSL.h"
#include "TreeRep.h"
int main(int argc, char *argv[])
{
//deal with argc and argv in case the 'ana' parameter is present/absent
strcpy(search_mode, argv[1]);
if(strcmp(search_mode,"ana")==0)
strcpy(search_mode, argv[2]);
long long noofele; //no. of elements
scanf("%lld", &noofele);
if(!(noofele > 0))
{
printf("ERROR: number_of_inputs_must_be_greater_than_0: ABORTED\n\n");
exit(1);
}
//create our two main structures, the priority queue and the adjacency list
ptr *pq = createPQ(noofele+10);
//pq capacity made much larger than noofele, can be EQUAL to noofele
struct node *AdjacencyListArray[noofele];
//initialise adjacency list with all NULLS, then accept all nodes using the input_node method from node.c
for (long long i = 0; i < noofele; i++)
{
AdjacencyListArray[i] = NULL;
}
for (int i = 0; i < noofele; i++)
input_node(AdjacencyListArray, noofele);
//print tree representation and search output table
if(noofele<=20)
{
printTree(AdjacencyListArray,noofele);
}
UnifiedSearch(AdjacencyListArray,pq,noofele);
//if analysis flag is enabled, print analysis table
if(strcmp(argv[1],"ana")==0)
printAnalysis(noofele);
//free malloced memory
deleteAdjacencyList(AdjacencyListArray, noofele);
deletePQ(pq);
return 0;
}
| 2.765625 | 3 |
2024-11-18T21:08:25.559597+00:00 | 2019-06-28T16:18:44 | c606861b41f84f840feb0e8426446477bc006148 | {
"blob_id": "c606861b41f84f840feb0e8426446477bc006148",
"branch_name": "refs/heads/master",
"committer_date": "2019-06-28T16:18:44",
"content_id": "26eb609c16a95b7aeeaf1e9a5748af1114daf883",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "cb44ec9f9fcac054d2bb7687f390d5a82b23563a",
"extension": "c",
"filename": "6_3_cross_referencer.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 194298329,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3853,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/exercises/6_3_cross_referencer.c",
"provenance": "stackv2-0069.json.gz:239244",
"repo_name": "xanpen/exercises",
"revision_date": "2019-06-28T16:18:44",
"revision_id": "bac2b69392659fb5727b6e4a8ac37722e7b1a696",
"snapshot_id": "8295e996eed1c875d7c5d8a2ba0ded8299a744ba",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/xanpen/exercises/bac2b69392659fb5727b6e4a8ac37722e7b1a696/exercises/6_3_cross_referencer.c",
"visit_date": "2020-06-12T12:25:55.480078"
} | stackv2 | //
// 6_3_cross_referencer.c
// c_exercises
//
// Created by 王显朋 on 2019/4/16.
// Copyright © 2019年 wongxp. All rights reserved.
//
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include "calculator.h"
#define MAXWORD 100
struct tnode *talloc(void);
char *strdup_6_2(char *);
struct tnode *addtreex_6_3(struct tnode *, char *, int);
void addlink(struct tnode *, int);
struct linklist *lalloc(void);
void treexprint_6_3(struct tnode *);
int noiseword(char *);
int getword_6_3(char *, int);
// 链表结构
struct linklist {
int linenum;
struct linklist *ptr;
};
// 树结构
struct tnode {
char *word;
struct linklist *lines;
struct tnode *left;
struct tnode *right;
};
int main_6_3(int argc, char *argv[]) {
char word[MAXWORD];
int linenum = 1;
struct tnode *root = NULL;
while (getword_6_3(word, MAXWORD) != EOF) {
if (isalpha(word[0]) && noiseword(word) == -1) {
root = addtreex_6_3(root, word, linenum);
} else if (word[0] == '\n') {
linenum++;
}
}
treexprint_6_3(root);
return 0;
}
// addtreex_6_3: 在p节点或者p节点下面添加一个节点
struct tnode *addtreex_6_3(struct tnode *p, char *word, int linenum) {
int cond;
if (p == NULL) {
p = talloc();
p->word = strdup_6_2(word);
p->lines = lalloc();
p->lines->linenum = linenum;
p->lines->ptr = NULL;
p->left = p->right = NULL;
} else if ((cond = strcmp(word, p->word)) == 0) {
addlink(p, linenum);
} else if (cond < 0) {
p->left = addtreex_6_3(p->left, word, linenum);
} else if (cond > 0) {
p->right = addtreex_6_3(p->right, word, linenum);
}
return p;
}
// 添加一个节点到链表上
// 当新单词已经存在于树上时,需要把该单词的行号加到其链表上(如果行号不同的话)
void addlink(struct tnode *p, int linenum) {
struct linklist *temp = p->lines;
while (temp->ptr != NULL && temp->linenum != linenum) {
temp = temp->ptr;
}
if (temp->linenum != linenum) {
temp->ptr = lalloc();
temp->ptr->linenum = linenum;
temp->ptr->ptr = NULL;
}
}
// 打印树
void treexprint_6_3(struct tnode *p) {
struct linklist *temp;
if (p != NULL) {
treexprint_6_3(p->left);
printf("%10s: ", p->word);
for (temp = p->lines; temp != NULL; temp = temp->ptr) {
printf("%4d ", temp->linenum);
}
printf("\n");
treexprint_6_3(p->right);
}
}
// lalloc: make a linklist node
struct linklist *lalloc(void) {
return (struct linklist *)malloc(sizeof(struct linklist));
}
// 二分查找“噪音词”
int noiseword(char *word) {
static char *nw[] = {
"a",
"an",
"and",
"are",
"in",
"is",
"of",
"or",
"that",
"the",
"this",
"to"
};
int cond;
int low = 0;
int mid;
int high = sizeof(nw) / sizeof(char *) - 1;
while (low <= high) {
mid = (low + high) / 2;
if ((cond = strcmp(word, nw[mid])) < 0) {
high = mid - 1;
} else if (cond > 0) {
low = mid + 1;
} else {
return mid;
}
}
return -1;
}
// get next word or character from input
int getword_6_3(char *word, int lim) {
int c;
char *w = word;
while (isspace(c = getch()) && c != '\n') {
;
}
if (c != EOF) {
*w++ = c;
}
if (!isalpha(c)) {
*w = '\0';
return c;
}
for (; --lim > 0; w++) {
if (!isalnum(*w = getch())) {
ungetch_(*w);
break;
}
}
*w = '\0';
return word[0];
}
| 3.03125 | 3 |
2024-11-18T21:08:26.257095+00:00 | 2021-02-26T09:45:34 | 14b2c38cd484d34b640d0fb76a927e47c3ccd968 | {
"blob_id": "14b2c38cd484d34b640d0fb76a927e47c3ccd968",
"branch_name": "refs/heads/master",
"committer_date": "2021-02-26T09:45:34",
"content_id": "9e9c2f5062f43fd9c1ec7b11e82a3feb5916e3de",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "c428b5b80d6207fc5a5d7aa729591624d702a188",
"extension": "h",
"filename": "stack.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 366327441,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 374,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/inc/stack.h",
"provenance": "stackv2-0069.json.gz:239630",
"repo_name": "bensimner/system-litmus-harness",
"revision_date": "2021-02-26T09:45:34",
"revision_id": "10c296bf89570553df1d087edad6f33da8050613",
"snapshot_id": "eac3ab49753e4c01c6b6288a57b59de963a360e3",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/bensimner/system-litmus-harness/10c296bf89570553df1d087edad6f33da8050613/inc/stack.h",
"visit_date": "2023-04-12T04:34:46.128302"
} | stackv2 | #ifndef STACK_H
#define STACK_H
/** header for a simple stack walker
*
* requires -fno-omit-frame-pointer
*/
#include "lib.h"
typedef struct {
uint64_t next;
uint64_t ret;
} stack_frame_t;
typedef struct {
int no_frames;
stack_frame_t frames[];
} stack_t;
void walk_stack_from(uint64_t* fp, stack_t* buf);
void walk_stack(stack_t* buf);
#endif /* STACK_H */ | 2 | 2 |
2024-11-18T21:08:26.749203+00:00 | 2020-08-18T02:47:53 | 062daea10c3a5c69035a8de0b57478491a896d55 | {
"blob_id": "062daea10c3a5c69035a8de0b57478491a896d55",
"branch_name": "refs/heads/master",
"committer_date": "2020-08-18T02:47:53",
"content_id": "ce3215dfbf00836c2e50c22aca60740d6779f75f",
"detected_licenses": [
"MIT"
],
"directory_id": "4be8b688fbb36c52c7c55ce9eead912812db2549",
"extension": "c",
"filename": "server-mt.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 155927181,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2508,
"license": "MIT",
"license_type": "permissive",
"path": "/redes/tp1/chat/server-mt.c",
"provenance": "stackv2-0069.json.gz:240017",
"repo_name": "brenopoggiali/BCC",
"revision_date": "2020-08-18T02:47:53",
"revision_id": "f1e08fa8a0f9a132f65de7dbca5bf4681f8e10d4",
"snapshot_id": "27466ab0b718bee76771a7da50ef7d56a5ad2253",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/brenopoggiali/BCC/f1e08fa8a0f9a132f65de7dbca5bf4681f8e10d4/redes/tp1/chat/server-mt.c",
"visit_date": "2021-07-04T16:59:25.354118"
} | stackv2 | #include "common.h"
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#define BUFSZ 1024
void usage(int argc, char **argv) {
printf("usage: %s <v4|v6> <server port>\n", argv[0]);
printf("example: %s v4 51511\n", argv[0]);
exit(EXIT_FAILURE);
}
struct client_data {
int csock;
struct sockaddr_storage storage;
};
void * client_thread(void *data) {
struct client_data *cdata = (struct client_data *)data;
struct sockaddr *caddr = (struct sockaddr *)(&cdata->storage);
char caddrstr[BUFSZ];
addrtostr(caddr, caddrstr, BUFSZ);
printf("[log] connection from %s\n", caddrstr);
char buf[BUFSZ];
memset(buf, 0, BUFSZ);
size_t count = recv(cdata->csock, buf, BUFSZ - 1, 0);
printf("[msg] %s, %d bytes: %s\n", caddrstr, (int)count, buf);
sprintf(buf, "remote endpoint: %.1000s\n", caddrstr);
count = send(cdata->csock, buf, strlen(buf) + 1, 0);
if (count != strlen(buf) + 1) {
logexit("send");
}
close(cdata->csock);
pthread_exit(EXIT_SUCCESS);
}
int main(int argc, char **argv) {
if (argc < 3) {
usage(argc, argv);
}
struct sockaddr_storage storage;
if (0 != server_sockaddr_init(argv[1], argv[2], &storage)) {
usage(argc, argv);
}
int s;
s = socket(storage.ss_family, SOCK_STREAM, 0);
if (s == -1) {
logexit("socket");
}
int enable = 1;
if (0 != setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(int))) {
logexit("setsockopt");
}
struct sockaddr *addr = (struct sockaddr *)(&storage);
if (0 != bind(s, addr, sizeof(storage))) {
logexit("bind");
}
if (0 != listen(s, 10)) {
logexit("listen");
}
char addrstr[BUFSZ];
addrtostr(addr, addrstr, BUFSZ);
printf("bound to %s, waiting connections\n", addrstr);
while (1) {
struct sockaddr_storage cstorage;
struct sockaddr *caddr = (struct sockaddr *)(&cstorage);
socklen_t caddrlen = sizeof(cstorage);
int csock = accept(s, caddr, &caddrlen);
if (csock == -1) {
logexit("accept");
}
struct client_data *cdata = malloc(sizeof(*cdata));
if (!cdata) {
logexit("malloc");
}
cdata->csock = csock;
memcpy(&(cdata->storage), &cstorage, sizeof(cstorage));
pthread_t tid;
pthread_create(&tid, NULL, client_thread, cdata);
}
exit(EXIT_SUCCESS);
}
| 2.671875 | 3 |
2024-11-18T21:08:26.887368+00:00 | 2021-12-30T07:46:20 | a1dde7871f8ae196992ba70b1dde9cedb6da3fbe | {
"blob_id": "a1dde7871f8ae196992ba70b1dde9cedb6da3fbe",
"branch_name": "refs/heads/release",
"committer_date": "2021-12-30T07:46:20",
"content_id": "911447cd196bda4b11b7dc2f40a85014a27b894e",
"detected_licenses": [
"MIT"
],
"directory_id": "3c6e1e35f38421273f92dd25055dccc6f632fd93",
"extension": "c",
"filename": "spiffs_nucleus.c",
"fork_events_count": 3888,
"gha_created_at": "2014-11-20T15:06:45",
"gha_event_created_at": "2023-07-25T09:20:45",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 26917568,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 89018,
"license": "MIT",
"license_type": "permissive",
"path": "/app/spiffs/spiffs_nucleus.c",
"provenance": "stackv2-0069.json.gz:240145",
"repo_name": "nodemcu/nodemcu-firmware",
"revision_date": "2021-12-30T07:46:20",
"revision_id": "f25dc56d3c6213b8ac7ce46d1293466137746eae",
"snapshot_id": "fd907ddf01bf17fdc55dd352d6987ee91d8b95e3",
"src_encoding": "UTF-8",
"star_events_count": 8077,
"url": "https://raw.githubusercontent.com/nodemcu/nodemcu-firmware/f25dc56d3c6213b8ac7ce46d1293466137746eae/app/spiffs/spiffs_nucleus.c",
"visit_date": "2023-08-22T21:46:10.995686"
} | stackv2 | #include "spiffs.h"
#include "spiffs_nucleus.h"
static s32_t spiffs_page_data_check(spiffs *fs, spiffs_fd *fd, spiffs_page_ix pix, spiffs_span_ix spix) {
s32_t res = SPIFFS_OK;
if (pix == (spiffs_page_ix)-1) {
// referring to page 0xffff...., bad object index
return SPIFFS_ERR_INDEX_REF_FREE;
}
if (pix % SPIFFS_PAGES_PER_BLOCK(fs) < SPIFFS_OBJ_LOOKUP_PAGES(fs)) {
// referring to an object lookup page, bad object index
return SPIFFS_ERR_INDEX_REF_LU;
}
if (pix > SPIFFS_MAX_PAGES(fs)) {
// referring to a bad page
return SPIFFS_ERR_INDEX_REF_INVALID;
}
#if SPIFFS_PAGE_CHECK
spiffs_page_header ph;
res = _spiffs_rd(
fs, SPIFFS_OP_T_OBJ_DA | SPIFFS_OP_C_READ,
fd->file_nbr,
SPIFFS_PAGE_TO_PADDR(fs, pix),
sizeof(spiffs_page_header),
(u8_t *)&ph);
SPIFFS_CHECK_RES(res);
SPIFFS_VALIDATE_DATA(ph, fd->obj_id & ~SPIFFS_OBJ_ID_IX_FLAG, spix);
#endif
return res;
}
#if !SPIFFS_READ_ONLY
static s32_t spiffs_page_index_check(spiffs *fs, spiffs_fd *fd, spiffs_page_ix pix, spiffs_span_ix spix) {
s32_t res = SPIFFS_OK;
if (pix == (spiffs_page_ix)-1) {
// referring to page 0xffff...., bad object index
return SPIFFS_ERR_INDEX_FREE;
}
if (pix % SPIFFS_PAGES_PER_BLOCK(fs) < SPIFFS_OBJ_LOOKUP_PAGES(fs)) {
// referring to an object lookup page, bad object index
return SPIFFS_ERR_INDEX_LU;
}
if (pix > SPIFFS_MAX_PAGES(fs)) {
// referring to a bad page
return SPIFFS_ERR_INDEX_INVALID;
}
#if SPIFFS_PAGE_CHECK
spiffs_page_header ph;
res = _spiffs_rd(
fs, SPIFFS_OP_T_OBJ_IX | SPIFFS_OP_C_READ,
fd->file_nbr,
SPIFFS_PAGE_TO_PADDR(fs, pix),
sizeof(spiffs_page_header),
(u8_t *)&ph);
SPIFFS_CHECK_RES(res);
SPIFFS_VALIDATE_OBJIX(ph, fd->obj_id, spix);
#endif
return res;
}
#endif // !SPIFFS_READ_ONLY
#if !SPIFFS_CACHE
s32_t spiffs_phys_rd(
spiffs *fs,
u32_t addr,
u32_t len,
u8_t *dst) {
return SPIFFS_HAL_READ(fs, addr, len, dst);
}
s32_t spiffs_phys_wr(
spiffs *fs,
u32_t addr,
u32_t len,
u8_t *src) {
return SPIFFS_HAL_WRITE(fs, addr, len, src);
}
#endif
#if !SPIFFS_READ_ONLY
s32_t spiffs_phys_cpy(
spiffs *fs,
spiffs_file fh,
u32_t dst,
u32_t src,
u32_t len) {
(void)fh;
s32_t res;
u8_t b[SPIFFS_COPY_BUFFER_STACK];
while (len > 0) {
u32_t chunk_size = MIN(SPIFFS_COPY_BUFFER_STACK, len);
res = _spiffs_rd(fs, SPIFFS_OP_T_OBJ_DA | SPIFFS_OP_C_MOVS, fh, src, chunk_size, b);
SPIFFS_CHECK_RES(res);
res = _spiffs_wr(fs, SPIFFS_OP_T_OBJ_DA | SPIFFS_OP_C_MOVD, fh, dst, chunk_size, b);
SPIFFS_CHECK_RES(res);
len -= chunk_size;
src += chunk_size;
dst += chunk_size;
}
return SPIFFS_OK;
}
#endif // !SPIFFS_READ_ONLY
// Find object lookup entry containing given id with visitor.
// Iterate over object lookup pages in each block until a given object id entry is found.
// When found, the visitor function is called with block index, entry index and user data.
// If visitor returns SPIFFS_VIS_CONTINUE, the search goes on. Otherwise, the search will be
// ended and visitor's return code is returned to caller.
// If no visitor is given (0) the search returns on first entry with matching object id.
// If no match is found in all look up, SPIFFS_VIS_END is returned.
// @param fs the file system
// @param starting_block the starting block to start search in
// @param starting_lu_entry the look up index entry to start search in
// @param flags ored combination of SPIFFS_VIS_CHECK_ID, SPIFFS_VIS_CHECK_PH,
// SPIFFS_VIS_NO_WRAP
// @param obj_id argument object id
// @param v visitor callback function
// @param user_const_p any const pointer, passed to the callback visitor function
// @param user_var_p any pointer, passed to the callback visitor function
// @param block_ix reported block index where match was found
// @param lu_entry reported look up index where match was found
s32_t spiffs_obj_lu_find_entry_visitor(
spiffs *fs,
spiffs_block_ix starting_block,
int starting_lu_entry,
u8_t flags,
spiffs_obj_id obj_id,
spiffs_visitor_f v,
const void *user_const_p,
void *user_var_p,
spiffs_block_ix *block_ix,
int *lu_entry) {
s32_t res = SPIFFS_OK;
s32_t entry_count = fs->block_count * SPIFFS_OBJ_LOOKUP_MAX_ENTRIES(fs);
spiffs_block_ix cur_block = starting_block;
u32_t cur_block_addr = starting_block * SPIFFS_CFG_LOG_BLOCK_SZ(fs);
spiffs_obj_id *obj_lu_buf = (spiffs_obj_id *)fs->lu_work;
int cur_entry = starting_lu_entry;
int entries_per_page = (SPIFFS_CFG_LOG_PAGE_SZ(fs) / sizeof(spiffs_obj_id));
// wrap initial
if (cur_entry > (int)SPIFFS_OBJ_LOOKUP_MAX_ENTRIES(fs) - 1) {
cur_entry = 0;
cur_block++;
cur_block_addr = cur_block * SPIFFS_CFG_LOG_BLOCK_SZ(fs);
if (cur_block >= fs->block_count) {
if (flags & SPIFFS_VIS_NO_WRAP) {
return SPIFFS_VIS_END;
} else {
// block wrap
cur_block = 0;
cur_block_addr = 0;
}
}
}
// check each block
while (res == SPIFFS_OK && entry_count > 0) {
int obj_lookup_page = cur_entry / entries_per_page;
// check each object lookup page
while (res == SPIFFS_OK && obj_lookup_page < (int)SPIFFS_OBJ_LOOKUP_PAGES(fs)) {
int entry_offset = obj_lookup_page * entries_per_page;
res = _spiffs_rd(fs, SPIFFS_OP_T_OBJ_LU | SPIFFS_OP_C_READ,
0, cur_block_addr + SPIFFS_PAGE_TO_PADDR(fs, obj_lookup_page), SPIFFS_CFG_LOG_PAGE_SZ(fs), fs->lu_work);
// check each entry
while (res == SPIFFS_OK &&
cur_entry - entry_offset < entries_per_page && // for non-last obj lookup pages
cur_entry < (int)SPIFFS_OBJ_LOOKUP_MAX_ENTRIES(fs)) // for last obj lookup page
{
if ((flags & SPIFFS_VIS_CHECK_ID) == 0 || obj_lu_buf[cur_entry-entry_offset] == obj_id) {
if (block_ix) *block_ix = cur_block;
if (lu_entry) *lu_entry = cur_entry;
if (v) {
res = v(
fs,
(flags & SPIFFS_VIS_CHECK_PH) ? obj_id : obj_lu_buf[cur_entry-entry_offset],
cur_block,
cur_entry,
user_const_p,
user_var_p);
if (res == SPIFFS_VIS_COUNTINUE || res == SPIFFS_VIS_COUNTINUE_RELOAD) {
if (res == SPIFFS_VIS_COUNTINUE_RELOAD) {
res = _spiffs_rd(fs, SPIFFS_OP_T_OBJ_LU | SPIFFS_OP_C_READ,
0, cur_block_addr + SPIFFS_PAGE_TO_PADDR(fs, obj_lookup_page), SPIFFS_CFG_LOG_PAGE_SZ(fs), fs->lu_work);
SPIFFS_CHECK_RES(res);
}
res = SPIFFS_OK;
cur_entry++;
entry_count--;
continue;
} else {
return res;
}
} else {
return SPIFFS_OK;
}
}
entry_count--;
cur_entry++;
} // per entry
obj_lookup_page++;
} // per object lookup page
cur_entry = 0;
cur_block++;
cur_block_addr += SPIFFS_CFG_LOG_BLOCK_SZ(fs);
if (cur_block >= fs->block_count) {
if (flags & SPIFFS_VIS_NO_WRAP) {
return SPIFFS_VIS_END;
} else {
// block wrap
cur_block = 0;
cur_block_addr = 0;
}
}
} // per block
SPIFFS_CHECK_RES(res);
return SPIFFS_VIS_END;
}
#if !SPIFFS_READ_ONLY
s32_t spiffs_erase_block(
spiffs *fs,
spiffs_block_ix bix) {
s32_t res;
u32_t addr = SPIFFS_BLOCK_TO_PADDR(fs, bix);
s32_t size = SPIFFS_CFG_LOG_BLOCK_SZ(fs);
// here we ignore res, just try erasing the block
while (size > 0) {
SPIFFS_DBG("erase "_SPIPRIad":"_SPIPRIi"\n", addr, SPIFFS_CFG_PHYS_ERASE_SZ(fs));
SPIFFS_HAL_ERASE(fs, addr, SPIFFS_CFG_PHYS_ERASE_SZ(fs));
addr += SPIFFS_CFG_PHYS_ERASE_SZ(fs);
size -= SPIFFS_CFG_PHYS_ERASE_SZ(fs);
}
fs->free_blocks++;
// register erase count for this block
res = _spiffs_wr(fs, SPIFFS_OP_C_WRTHRU | SPIFFS_OP_T_OBJ_LU2, 0,
SPIFFS_ERASE_COUNT_PADDR(fs, bix),
sizeof(spiffs_obj_id), (u8_t *)&fs->max_erase_count);
SPIFFS_CHECK_RES(res);
#if SPIFFS_USE_MAGIC
// finally, write magic
spiffs_obj_id magic = SPIFFS_MAGIC(fs, bix);
res = _spiffs_wr(fs, SPIFFS_OP_C_WRTHRU | SPIFFS_OP_T_OBJ_LU2, 0,
SPIFFS_MAGIC_PADDR(fs, bix),
sizeof(spiffs_obj_id), (u8_t *)&magic);
SPIFFS_CHECK_RES(res);
#endif
fs->max_erase_count++;
if (fs->max_erase_count == SPIFFS_OBJ_ID_IX_FLAG) {
fs->max_erase_count = 0;
}
return res;
}
#endif // !SPIFFS_READ_ONLY
#if SPIFFS_USE_MAGIC && SPIFFS_USE_MAGIC_LENGTH && SPIFFS_SINGLETON==0
s32_t spiffs_probe(
spiffs_config *cfg) {
s32_t res;
u32_t paddr;
spiffs dummy_fs; // create a dummy fs struct just to be able to use macros
_SPIFFS_MEMCPY(&dummy_fs.cfg, cfg, sizeof(spiffs_config));
dummy_fs.block_count = 0;
// Read three magics, as one block may be in an aborted erase state.
// At least two of these must contain magic and be in decreasing order.
spiffs_obj_id magic[3];
spiffs_obj_id bix_count[3];
spiffs_block_ix bix;
for (bix = 0; bix < 3; bix++) {
paddr = SPIFFS_MAGIC_PADDR(&dummy_fs, bix);
#if SPIFFS_HAL_CALLBACK_EXTRA
// not any proper fs to report here, so callback with null
// (cross fingers that no-one gets angry)
res = cfg->hal_read_f((void *)0, paddr, sizeof(spiffs_obj_id), (u8_t *)&magic[bix]);
#else
res = cfg->hal_read_f(paddr, sizeof(spiffs_obj_id), (u8_t *)&magic[bix]);
#endif
bix_count[bix] = magic[bix] ^ SPIFFS_MAGIC(&dummy_fs, 0);
SPIFFS_CHECK_RES(res);
}
// check that we have sane number of blocks
if (bix_count[0] < 3) return SPIFFS_ERR_PROBE_TOO_FEW_BLOCKS;
// check that the order is correct, take aborted erases in calculation
// first block aborted erase
if (magic[0] == (spiffs_obj_id)(-1) && bix_count[1] - bix_count[2] == 1) {
return (bix_count[1]+1) * cfg->log_block_size;
}
// second block aborted erase
if (magic[1] == (spiffs_obj_id)(-1) && bix_count[0] - bix_count[2] == 2) {
return bix_count[0] * cfg->log_block_size;
}
// third block aborted erase
if (magic[2] == (spiffs_obj_id)(-1) && bix_count[0] - bix_count[1] == 1) {
return bix_count[0] * cfg->log_block_size;
}
// no block has aborted erase
if (bix_count[0] - bix_count[1] == 1 && bix_count[1] - bix_count[2] == 1) {
return bix_count[0] * cfg->log_block_size;
}
return SPIFFS_ERR_PROBE_NOT_A_FS;
}
#endif // SPIFFS_USE_MAGIC && SPIFFS_USE_MAGIC_LENGTH && SPIFFS_SINGLETON==0
static s32_t spiffs_obj_lu_scan_v(
spiffs *fs,
spiffs_obj_id obj_id,
spiffs_block_ix bix,
int ix_entry,
const void *user_const_p,
void *user_var_p) {
(void)bix;
(void)user_const_p;
(void)user_var_p;
if (obj_id == SPIFFS_OBJ_ID_FREE) {
if (ix_entry == 0) {
fs->free_blocks++;
// todo optimize further, return SPIFFS_NEXT_BLOCK
}
} else if (obj_id == SPIFFS_OBJ_ID_DELETED) {
fs->stats_p_deleted++;
} else {
fs->stats_p_allocated++;
}
return SPIFFS_VIS_COUNTINUE;
}
// Scans thru all obj lu and counts free, deleted and used pages
// Find the maximum block erase count
// Checks magic if enabled
s32_t spiffs_obj_lu_scan(
spiffs *fs) {
s32_t res;
spiffs_block_ix bix;
int entry;
#if SPIFFS_USE_MAGIC
spiffs_block_ix unerased_bix = (spiffs_block_ix)-1;
#endif
// find out erase count
// if enabled, check magic
bix = 0;
spiffs_obj_id erase_count_final;
spiffs_obj_id erase_count_min = SPIFFS_OBJ_ID_FREE;
spiffs_obj_id erase_count_max = 0;
while (bix < fs->block_count) {
#if SPIFFS_USE_MAGIC
spiffs_obj_id magic;
res = _spiffs_rd(fs,
SPIFFS_OP_T_OBJ_LU2 | SPIFFS_OP_C_READ,
0, SPIFFS_MAGIC_PADDR(fs, bix) ,
sizeof(spiffs_obj_id), (u8_t *)&magic);
SPIFFS_CHECK_RES(res);
if (magic != SPIFFS_MAGIC(fs, bix)) {
if (unerased_bix == (spiffs_block_ix)-1) {
// allow one unerased block as it might be powered down during an erase
unerased_bix = bix;
} else {
// more than one unerased block, bail out
SPIFFS_CHECK_RES(SPIFFS_ERR_NOT_A_FS);
}
}
#endif
spiffs_obj_id erase_count;
res = _spiffs_rd(fs,
SPIFFS_OP_T_OBJ_LU2 | SPIFFS_OP_C_READ,
0, SPIFFS_ERASE_COUNT_PADDR(fs, bix) ,
sizeof(spiffs_obj_id), (u8_t *)&erase_count);
SPIFFS_CHECK_RES(res);
if (erase_count != SPIFFS_OBJ_ID_FREE) {
erase_count_min = MIN(erase_count_min, erase_count);
erase_count_max = MAX(erase_count_max, erase_count);
}
bix++;
}
if (erase_count_min == 0 && erase_count_max == SPIFFS_OBJ_ID_FREE) {
// clean system, set counter to zero
erase_count_final = 0;
} else if (erase_count_max - erase_count_min > (SPIFFS_OBJ_ID_FREE)/2) {
// wrap, take min
erase_count_final = erase_count_min+1;
} else {
erase_count_final = erase_count_max+1;
}
fs->max_erase_count = erase_count_final;
#if SPIFFS_USE_MAGIC
if (unerased_bix != (spiffs_block_ix)-1) {
// found one unerased block, remedy
SPIFFS_DBG("mount: erase block "_SPIPRIbl"\n", bix);
#if SPIFFS_READ_ONLY
res = SPIFFS_ERR_RO_ABORTED_OPERATION;
#else
res = spiffs_erase_block(fs, unerased_bix);
#endif // SPIFFS_READ_ONLY
SPIFFS_CHECK_RES(res);
}
#endif
// count blocks
fs->free_blocks = 0;
fs->stats_p_allocated = 0;
fs->stats_p_deleted = 0;
res = spiffs_obj_lu_find_entry_visitor(fs,
0,
0,
0,
0,
spiffs_obj_lu_scan_v,
0,
0,
&bix,
&entry);
if (res == SPIFFS_VIS_END) {
res = SPIFFS_OK;
}
SPIFFS_CHECK_RES(res);
return res;
}
#if !SPIFFS_READ_ONLY
// Find free object lookup entry
// Iterate over object lookup pages in each block until a free object id entry is found
s32_t spiffs_obj_lu_find_free(
spiffs *fs,
spiffs_block_ix starting_block,
int starting_lu_entry,
spiffs_block_ix *block_ix,
int *lu_entry) {
s32_t res;
if (!fs->cleaning && fs->free_blocks < 2) {
res = spiffs_gc_quick(fs, 0);
if (res == SPIFFS_ERR_NO_DELETED_BLOCKS) {
res = SPIFFS_OK;
}
SPIFFS_CHECK_RES(res);
if (fs->free_blocks < 2) {
return SPIFFS_ERR_FULL;
}
}
res = spiffs_obj_lu_find_id(fs, starting_block, starting_lu_entry,
SPIFFS_OBJ_ID_FREE, block_ix, lu_entry);
if (res == SPIFFS_OK) {
fs->free_cursor_block_ix = *block_ix;
fs->free_cursor_obj_lu_entry = (*lu_entry) + 1;
if (*lu_entry == 0) {
fs->free_blocks--;
}
}
if (res == SPIFFS_ERR_FULL) {
SPIFFS_DBG("fs full\n");
}
return res;
}
#endif // !SPIFFS_READ_ONLY
// Find object lookup entry containing given id
// Iterate over object lookup pages in each block until a given object id entry is found
s32_t spiffs_obj_lu_find_id(
spiffs *fs,
spiffs_block_ix starting_block,
int starting_lu_entry,
spiffs_obj_id obj_id,
spiffs_block_ix *block_ix,
int *lu_entry) {
s32_t res = spiffs_obj_lu_find_entry_visitor(
fs, starting_block, starting_lu_entry, SPIFFS_VIS_CHECK_ID, obj_id, 0, 0, 0, block_ix, lu_entry);
if (res == SPIFFS_VIS_END) {
res = SPIFFS_ERR_NOT_FOUND;
}
return res;
}
static s32_t spiffs_obj_lu_find_id_and_span_v(
spiffs *fs,
spiffs_obj_id obj_id,
spiffs_block_ix bix,
int ix_entry,
const void *user_const_p,
void *user_var_p) {
s32_t res;
spiffs_page_header ph;
spiffs_page_ix pix = SPIFFS_OBJ_LOOKUP_ENTRY_TO_PIX(fs, bix, ix_entry);
res = _spiffs_rd(fs, 0, SPIFFS_OP_T_OBJ_LU2 | SPIFFS_OP_C_READ,
SPIFFS_PAGE_TO_PADDR(fs, pix), sizeof(spiffs_page_header), (u8_t *)&ph);
SPIFFS_CHECK_RES(res);
if (ph.obj_id == obj_id &&
ph.span_ix == *((spiffs_span_ix*)user_var_p) &&
(ph.flags & (SPIFFS_PH_FLAG_FINAL | SPIFFS_PH_FLAG_DELET | SPIFFS_PH_FLAG_USED)) == SPIFFS_PH_FLAG_DELET &&
!((obj_id & SPIFFS_OBJ_ID_IX_FLAG) && (ph.flags & SPIFFS_PH_FLAG_IXDELE) == 0 && ph.span_ix == 0) &&
(user_const_p == 0 || *((const spiffs_page_ix*)user_const_p) != pix)) {
return SPIFFS_OK;
} else {
return SPIFFS_VIS_COUNTINUE;
}
}
// Find object lookup entry containing given id and span index
// Iterate over object lookup pages in each block until a given object id entry is found
s32_t spiffs_obj_lu_find_id_and_span(
spiffs *fs,
spiffs_obj_id obj_id,
spiffs_span_ix spix,
spiffs_page_ix exclusion_pix,
spiffs_page_ix *pix) {
s32_t res;
spiffs_block_ix bix;
int entry;
res = spiffs_obj_lu_find_entry_visitor(fs,
fs->cursor_block_ix,
fs->cursor_obj_lu_entry,
SPIFFS_VIS_CHECK_ID,
obj_id,
spiffs_obj_lu_find_id_and_span_v,
exclusion_pix ? &exclusion_pix : 0,
&spix,
&bix,
&entry);
if (res == SPIFFS_VIS_END) {
res = SPIFFS_ERR_NOT_FOUND;
}
SPIFFS_CHECK_RES(res);
if (pix) {
*pix = SPIFFS_OBJ_LOOKUP_ENTRY_TO_PIX(fs, bix, entry);
}
fs->cursor_block_ix = bix;
fs->cursor_obj_lu_entry = entry;
return res;
}
// Find object lookup entry containing given id and span index in page headers only
// Iterate over object lookup pages in each block until a given object id entry is found
s32_t spiffs_obj_lu_find_id_and_span_by_phdr(
spiffs *fs,
spiffs_obj_id obj_id,
spiffs_span_ix spix,
spiffs_page_ix exclusion_pix,
spiffs_page_ix *pix) {
s32_t res;
spiffs_block_ix bix;
int entry;
res = spiffs_obj_lu_find_entry_visitor(fs,
fs->cursor_block_ix,
fs->cursor_obj_lu_entry,
SPIFFS_VIS_CHECK_PH,
obj_id,
spiffs_obj_lu_find_id_and_span_v,
exclusion_pix ? &exclusion_pix : 0,
&spix,
&bix,
&entry);
if (res == SPIFFS_VIS_END) {
res = SPIFFS_ERR_NOT_FOUND;
}
SPIFFS_CHECK_RES(res);
if (pix) {
*pix = SPIFFS_OBJ_LOOKUP_ENTRY_TO_PIX(fs, bix, entry);
}
fs->cursor_block_ix = bix;
fs->cursor_obj_lu_entry = entry;
return res;
}
#if SPIFFS_IX_MAP
// update index map of given fd with given object index data
static void spiffs_update_ix_map(spiffs *fs,
spiffs_fd *fd, spiffs_span_ix objix_spix, spiffs_page_object_ix *objix) {
#if SPIFFS_SINGLETON
(void)fs;
#endif
spiffs_ix_map *map = fd->ix_map;
spiffs_span_ix map_objix_start_spix = SPIFFS_OBJ_IX_ENTRY_SPAN_IX(fs, map->start_spix);
spiffs_span_ix map_objix_end_spix = SPIFFS_OBJ_IX_ENTRY_SPAN_IX(fs, map->end_spix);
// check if updated ix is within map range
if (objix_spix < map_objix_start_spix || objix_spix > map_objix_end_spix) {
return;
}
// update memory mapped page index buffer to new pages
// get range of updated object index map data span indices
spiffs_span_ix objix_data_spix_start =
SPIFFS_DATA_SPAN_IX_FOR_OBJ_IX_SPAN_IX(fs, objix_spix);
spiffs_span_ix objix_data_spix_end = objix_data_spix_start +
(objix_spix == 0 ? SPIFFS_OBJ_HDR_IX_LEN(fs) : SPIFFS_OBJ_IX_LEN(fs));
// calc union of object index range and index map range array
spiffs_span_ix map_spix = MAX(map->start_spix, objix_data_spix_start);
spiffs_span_ix map_spix_end = MIN(map->end_spix + 1, objix_data_spix_end);
while (map_spix < map_spix_end) {
spiffs_page_ix objix_data_pix;
if (objix_spix == 0) {
// get data page from object index header page
objix_data_pix = ((spiffs_page_ix*)((u8_t *)objix + sizeof(spiffs_page_object_ix_header)))[map_spix];
} else {
// get data page from object index page
objix_data_pix = ((spiffs_page_ix*)((u8_t *)objix + sizeof(spiffs_page_object_ix)))[SPIFFS_OBJ_IX_ENTRY(fs, map_spix)];
}
if (objix_data_pix == (spiffs_page_ix)-1) {
// reached end of object, abort
break;
}
map->map_buf[map_spix - map->start_spix] = objix_data_pix;
SPIFFS_DBG("map "_SPIPRIid":"_SPIPRIsp" ("_SPIPRIsp"--"_SPIPRIsp") objix.spix:"_SPIPRIsp" to pix "_SPIPRIpg"\n",
fd->obj_id, map_spix - map->start_spix,
map->start_spix, map->end_spix,
objix->p_hdr.span_ix,
objix_data_pix);
map_spix++;
}
}
typedef struct {
spiffs_fd *fd;
u32_t remaining_objix_pages_to_visit;
spiffs_span_ix map_objix_start_spix;
spiffs_span_ix map_objix_end_spix;
} spiffs_ix_map_populate_state;
static s32_t spiffs_populate_ix_map_v(
spiffs *fs,
spiffs_obj_id obj_id,
spiffs_block_ix bix,
int ix_entry,
const void *user_const_p,
void *user_var_p) {
(void)user_const_p;
s32_t res;
spiffs_ix_map_populate_state *state = (spiffs_ix_map_populate_state *)user_var_p;
spiffs_page_ix pix = SPIFFS_OBJ_LOOKUP_ENTRY_TO_PIX(fs, bix, ix_entry);
// load header to check it
spiffs_page_object_ix *objix = (spiffs_page_object_ix *)fs->work;
res = _spiffs_rd(fs, SPIFFS_OP_T_OBJ_LU2 | SPIFFS_OP_C_READ,
0, SPIFFS_PAGE_TO_PADDR(fs, pix), sizeof(spiffs_page_object_ix), (u8_t *)objix);
SPIFFS_CHECK_RES(res);
SPIFFS_VALIDATE_OBJIX(objix->p_hdr, obj_id, objix->p_hdr.span_ix);
// check if hdr is ok, and if objix range overlap with ix map range
if ((objix->p_hdr.flags & (SPIFFS_PH_FLAG_DELET | SPIFFS_PH_FLAG_FINAL | SPIFFS_PH_FLAG_IXDELE)) ==
(SPIFFS_PH_FLAG_DELET | SPIFFS_PH_FLAG_IXDELE) &&
objix->p_hdr.span_ix >= state->map_objix_start_spix &&
objix->p_hdr.span_ix <= state->map_objix_end_spix) {
// ok, load rest of object index
res = _spiffs_rd(fs, SPIFFS_OP_T_OBJ_LU2 | SPIFFS_OP_C_READ,
0, SPIFFS_PAGE_TO_PADDR(fs, pix) + sizeof(spiffs_page_object_ix),
SPIFFS_CFG_LOG_PAGE_SZ(fs) - sizeof(spiffs_page_object_ix),
(u8_t *)objix + sizeof(spiffs_page_object_ix));
SPIFFS_CHECK_RES(res);
spiffs_update_ix_map(fs, state->fd, objix->p_hdr.span_ix, objix);
state->remaining_objix_pages_to_visit--;
SPIFFS_DBG("map "_SPIPRIid" ("_SPIPRIsp"--"_SPIPRIsp") remaining objix pages "_SPIPRIi"\n",
state->fd->obj_id,
state->fd->ix_map->start_spix, state->fd->ix_map->end_spix,
state->remaining_objix_pages_to_visit);
}
if (res == SPIFFS_OK) {
res = state->remaining_objix_pages_to_visit ? SPIFFS_VIS_COUNTINUE : SPIFFS_VIS_END;
}
return res;
}
// populates index map, from vector entry start to vector entry end, inclusive
s32_t spiffs_populate_ix_map(spiffs *fs, spiffs_fd *fd, u32_t vec_entry_start, u32_t vec_entry_end) {
s32_t res;
spiffs_ix_map *map = fd->ix_map;
spiffs_ix_map_populate_state state;
vec_entry_start = MIN((u32_t)(map->end_spix - map->start_spix), vec_entry_start);
vec_entry_end = MAX((u32_t)(map->end_spix - map->start_spix), vec_entry_end);
if (vec_entry_start > vec_entry_end) {
return SPIFFS_ERR_IX_MAP_BAD_RANGE;
}
state.map_objix_start_spix = SPIFFS_OBJ_IX_ENTRY_SPAN_IX(fs, map->start_spix + vec_entry_start);
state.map_objix_end_spix = SPIFFS_OBJ_IX_ENTRY_SPAN_IX(fs, map->start_spix + vec_entry_end);
state.remaining_objix_pages_to_visit =
state.map_objix_end_spix - state.map_objix_start_spix + 1;
state.fd = fd;
res = spiffs_obj_lu_find_entry_visitor(
fs,
SPIFFS_BLOCK_FOR_PAGE(fs, fd->objix_hdr_pix),
SPIFFS_OBJ_LOOKUP_ENTRY_FOR_PAGE(fs, fd->objix_hdr_pix),
SPIFFS_VIS_CHECK_ID,
fd->obj_id | SPIFFS_OBJ_ID_IX_FLAG,
spiffs_populate_ix_map_v,
0,
&state,
0,
0);
if (res == SPIFFS_VIS_END) {
res = SPIFFS_OK;
}
return res;
}
#endif
#if !SPIFFS_READ_ONLY
// Allocates a free defined page with given obj_id
// Occupies object lookup entry and page
// data may be NULL; where only page header is stored, len and page_offs is ignored
s32_t spiffs_page_allocate_data(
spiffs *fs,
spiffs_obj_id obj_id,
spiffs_page_header *ph,
u8_t *data,
u32_t len,
u32_t page_offs,
u8_t finalize,
spiffs_page_ix *pix) {
s32_t res = SPIFFS_OK;
spiffs_block_ix bix;
int entry;
// find free entry
res = spiffs_obj_lu_find_free(fs, fs->free_cursor_block_ix, fs->free_cursor_obj_lu_entry, &bix, &entry);
SPIFFS_CHECK_RES(res);
// occupy page in object lookup
res = _spiffs_wr(fs, SPIFFS_OP_T_OBJ_LU | SPIFFS_OP_C_UPDT,
0, SPIFFS_BLOCK_TO_PADDR(fs, bix) + entry * sizeof(spiffs_obj_id), sizeof(spiffs_obj_id), (u8_t*)&obj_id);
SPIFFS_CHECK_RES(res);
fs->stats_p_allocated++;
// write page header
ph->flags &= ~SPIFFS_PH_FLAG_USED;
res = _spiffs_wr(fs, SPIFFS_OP_T_OBJ_DA | SPIFFS_OP_C_UPDT,
0, SPIFFS_OBJ_LOOKUP_ENTRY_TO_PADDR(fs, bix, entry), sizeof(spiffs_page_header), (u8_t*)ph);
SPIFFS_CHECK_RES(res);
// write page data
if (data) {
res = _spiffs_wr(fs, SPIFFS_OP_T_OBJ_DA | SPIFFS_OP_C_UPDT,
0,SPIFFS_OBJ_LOOKUP_ENTRY_TO_PADDR(fs, bix, entry) + sizeof(spiffs_page_header) + page_offs, len, data);
SPIFFS_CHECK_RES(res);
}
// finalize header if necessary
if (finalize && (ph->flags & SPIFFS_PH_FLAG_FINAL)) {
ph->flags &= ~SPIFFS_PH_FLAG_FINAL;
res = _spiffs_wr(fs, SPIFFS_OP_T_OBJ_DA | SPIFFS_OP_C_UPDT,
0, SPIFFS_OBJ_LOOKUP_ENTRY_TO_PADDR(fs, bix, entry) + offsetof(spiffs_page_header, flags),
sizeof(u8_t),
(u8_t *)&ph->flags);
SPIFFS_CHECK_RES(res);
}
// return written page
if (pix) {
*pix = SPIFFS_OBJ_LOOKUP_ENTRY_TO_PIX(fs, bix, entry);
}
return res;
}
#endif // !SPIFFS_READ_ONLY
#if !SPIFFS_READ_ONLY
// Moves a page from src to a free page and finalizes it. Updates page index. Page data is given in param page.
// If page data is null, provided header is used for metainfo and page data is physically copied.
s32_t spiffs_page_move(
spiffs *fs,
spiffs_file fh,
u8_t *page_data,
spiffs_obj_id obj_id,
spiffs_page_header *page_hdr,
spiffs_page_ix src_pix,
spiffs_page_ix *dst_pix) {
s32_t res;
u8_t was_final = 0;
spiffs_page_header *p_hdr;
spiffs_block_ix bix;
int entry;
spiffs_page_ix free_pix;
// find free entry
res = spiffs_obj_lu_find_free(fs, fs->free_cursor_block_ix, fs->free_cursor_obj_lu_entry, &bix, &entry);
SPIFFS_CHECK_RES(res);
free_pix = SPIFFS_OBJ_LOOKUP_ENTRY_TO_PIX(fs, bix, entry);
if (dst_pix) *dst_pix = free_pix;
p_hdr = page_data ? (spiffs_page_header *)page_data : page_hdr;
if (page_data) {
// got page data
was_final = (p_hdr->flags & SPIFFS_PH_FLAG_FINAL) == 0;
// write unfinalized page
p_hdr->flags |= SPIFFS_PH_FLAG_FINAL;
p_hdr->flags &= ~SPIFFS_PH_FLAG_USED;
res = _spiffs_wr(fs, SPIFFS_OP_T_OBJ_DA | SPIFFS_OP_C_UPDT,
0, SPIFFS_PAGE_TO_PADDR(fs, free_pix), SPIFFS_CFG_LOG_PAGE_SZ(fs), page_data);
} else {
// copy page data
res = spiffs_phys_cpy(fs, fh, SPIFFS_PAGE_TO_PADDR(fs, free_pix), SPIFFS_PAGE_TO_PADDR(fs, src_pix), SPIFFS_CFG_LOG_PAGE_SZ(fs));
}
SPIFFS_CHECK_RES(res);
// mark entry in destination object lookup
res = _spiffs_wr(fs, SPIFFS_OP_T_OBJ_LU | SPIFFS_OP_C_UPDT,
0, SPIFFS_BLOCK_TO_PADDR(fs, SPIFFS_BLOCK_FOR_PAGE(fs, free_pix)) + SPIFFS_OBJ_LOOKUP_ENTRY_FOR_PAGE(fs, free_pix) * sizeof(spiffs_page_ix),
sizeof(spiffs_obj_id),
(u8_t *)&obj_id);
SPIFFS_CHECK_RES(res);
fs->stats_p_allocated++;
if (was_final) {
// mark finalized in destination page
p_hdr->flags &= ~(SPIFFS_PH_FLAG_FINAL | SPIFFS_PH_FLAG_USED);
res = _spiffs_wr(fs, SPIFFS_OP_T_OBJ_DA | SPIFFS_OP_C_UPDT,
fh,
SPIFFS_PAGE_TO_PADDR(fs, free_pix) + offsetof(spiffs_page_header, flags),
sizeof(u8_t),
(u8_t *)&p_hdr->flags);
SPIFFS_CHECK_RES(res);
}
// mark source deleted
res = spiffs_page_delete(fs, src_pix);
return res;
}
#endif // !SPIFFS_READ_ONLY
#if !SPIFFS_READ_ONLY
// Deletes a page and removes it from object lookup.
s32_t spiffs_page_delete(
spiffs *fs,
spiffs_page_ix pix) {
s32_t res;
// mark deleted entry in source object lookup
spiffs_obj_id d_obj_id = SPIFFS_OBJ_ID_DELETED;
res = _spiffs_wr(fs, SPIFFS_OP_T_OBJ_LU | SPIFFS_OP_C_DELE,
0,
SPIFFS_BLOCK_TO_PADDR(fs, SPIFFS_BLOCK_FOR_PAGE(fs, pix)) + SPIFFS_OBJ_LOOKUP_ENTRY_FOR_PAGE(fs, pix) * sizeof(spiffs_page_ix),
sizeof(spiffs_obj_id),
(u8_t *)&d_obj_id);
SPIFFS_CHECK_RES(res);
fs->stats_p_deleted++;
fs->stats_p_allocated--;
#if SPIFFS_SECURE_ERASE
// Secure erase
unsigned char data[SPIFFS_CFG_LOG_PAGE_SZ(fs) - sizeof(spiffs_page_header)];
bzero(data, sizeof(data));
res = _spiffs_wr(fs, SPIFFS_OP_T_OBJ_DA | SPIFFS_OP_C_DELE,
0,
SPIFFS_PAGE_TO_PADDR(fs, pix) + sizeof(spiffs_page_header), sizeof(data), data);
SPIFFS_CHECK_RES(res);
#endif
// mark deleted in source page
u8_t flags = 0xff;
#if SPIFFS_NO_BLIND_WRITES
res = _spiffs_rd(fs, SPIFFS_OP_T_OBJ_DA | SPIFFS_OP_C_READ,
0, SPIFFS_PAGE_TO_PADDR(fs, pix) + offsetof(spiffs_page_header, flags),
sizeof(flags), &flags);
SPIFFS_CHECK_RES(res);
#endif
flags &= ~(SPIFFS_PH_FLAG_DELET | SPIFFS_PH_FLAG_USED);
res = _spiffs_wr(fs, SPIFFS_OP_T_OBJ_DA | SPIFFS_OP_C_DELE,
0,
SPIFFS_PAGE_TO_PADDR(fs, pix) + offsetof(spiffs_page_header, flags),
sizeof(flags), &flags);
return res;
}
#endif // !SPIFFS_READ_ONLY
#if !SPIFFS_READ_ONLY
// Create an object index header page with empty index and undefined length
s32_t spiffs_object_create(
spiffs *fs,
spiffs_obj_id obj_id,
const u8_t name[],
const u8_t meta[],
spiffs_obj_type type,
spiffs_page_ix *objix_hdr_pix) {
s32_t res = SPIFFS_OK;
spiffs_block_ix bix;
spiffs_page_object_ix_header oix_hdr;
int entry;
res = spiffs_gc_check(fs, SPIFFS_DATA_PAGE_SIZE(fs));
SPIFFS_CHECK_RES(res);
obj_id |= SPIFFS_OBJ_ID_IX_FLAG;
// find free entry
res = spiffs_obj_lu_find_free(fs, fs->free_cursor_block_ix, fs->free_cursor_obj_lu_entry, &bix, &entry);
SPIFFS_CHECK_RES(res);
SPIFFS_DBG("create: found free page @ "_SPIPRIpg" bix:"_SPIPRIbl" entry:"_SPIPRIsp"\n", (spiffs_page_ix)SPIFFS_OBJ_LOOKUP_ENTRY_TO_PIX(fs, bix, entry), bix, entry);
// occupy page in object lookup
res = _spiffs_wr(fs, SPIFFS_OP_T_OBJ_LU | SPIFFS_OP_C_UPDT,
0, SPIFFS_BLOCK_TO_PADDR(fs, bix) + entry * sizeof(spiffs_obj_id), sizeof(spiffs_obj_id), (u8_t*)&obj_id);
SPIFFS_CHECK_RES(res);
fs->stats_p_allocated++;
// write empty object index page
oix_hdr.p_hdr.obj_id = obj_id;
oix_hdr.p_hdr.span_ix = 0;
oix_hdr.p_hdr.flags = 0xff & ~(SPIFFS_PH_FLAG_FINAL | SPIFFS_PH_FLAG_INDEX | SPIFFS_PH_FLAG_USED);
oix_hdr.type = type;
oix_hdr.size = SPIFFS_UNDEFINED_LEN; // keep ones so we can update later without wasting this page
strncpy((char*)oix_hdr.name, (const char*)name, SPIFFS_OBJ_NAME_LEN);
#if SPIFFS_OBJ_META_LEN
if (meta) {
_SPIFFS_MEMCPY(oix_hdr.meta, meta, SPIFFS_OBJ_META_LEN);
} else {
memset(oix_hdr.meta, 0xff, SPIFFS_OBJ_META_LEN);
}
#else
(void) meta;
#endif
// update page
res = _spiffs_wr(fs, SPIFFS_OP_T_OBJ_DA | SPIFFS_OP_C_UPDT,
0, SPIFFS_OBJ_LOOKUP_ENTRY_TO_PADDR(fs, bix, entry), sizeof(spiffs_page_object_ix_header), (u8_t*)&oix_hdr);
SPIFFS_CHECK_RES(res);
spiffs_cb_object_event(fs, (spiffs_page_object_ix *)&oix_hdr,
SPIFFS_EV_IX_NEW, obj_id, 0, SPIFFS_OBJ_LOOKUP_ENTRY_TO_PIX(fs, bix, entry), SPIFFS_UNDEFINED_LEN);
if (objix_hdr_pix) {
*objix_hdr_pix = SPIFFS_OBJ_LOOKUP_ENTRY_TO_PIX(fs, bix, entry);
}
return res;
}
#endif // !SPIFFS_READ_ONLY
#if !SPIFFS_READ_ONLY
// update object index header with any combination of name/size/index
// new_objix_hdr_data may be null, if so the object index header page is loaded
// name may be null, if so name is not changed
// size may be null, if so size is not changed
s32_t spiffs_object_update_index_hdr(
spiffs *fs,
spiffs_fd *fd,
spiffs_obj_id obj_id,
spiffs_page_ix objix_hdr_pix,
u8_t *new_objix_hdr_data,
const u8_t name[],
const u8_t meta[],
u32_t size,
spiffs_page_ix *new_pix) {
s32_t res = SPIFFS_OK;
spiffs_page_object_ix_header *objix_hdr;
spiffs_page_ix new_objix_hdr_pix;
obj_id |= SPIFFS_OBJ_ID_IX_FLAG;
if (new_objix_hdr_data) {
// object index header page already given to us, no need to load it
objix_hdr = (spiffs_page_object_ix_header *)new_objix_hdr_data;
} else {
// read object index header page
res = _spiffs_rd(fs, SPIFFS_OP_T_OBJ_IX | SPIFFS_OP_C_READ,
fd->file_nbr, SPIFFS_PAGE_TO_PADDR(fs, objix_hdr_pix), SPIFFS_CFG_LOG_PAGE_SZ(fs), fs->work);
SPIFFS_CHECK_RES(res);
objix_hdr = (spiffs_page_object_ix_header *)fs->work;
}
SPIFFS_VALIDATE_OBJIX(objix_hdr->p_hdr, obj_id, 0);
// change name
if (name) {
strncpy((char*)objix_hdr->name, (const char*)name, SPIFFS_OBJ_NAME_LEN);
}
#if SPIFFS_OBJ_META_LEN
if (meta) {
_SPIFFS_MEMCPY(objix_hdr->meta, meta, SPIFFS_OBJ_META_LEN);
}
#else
(void) meta;
#endif
if (size) {
objix_hdr->size = size;
}
// move and update page
res = spiffs_page_move(fs, fd == 0 ? 0 : fd->file_nbr, (u8_t*)objix_hdr, obj_id, 0, objix_hdr_pix, &new_objix_hdr_pix);
if (res == SPIFFS_OK) {
if (new_pix) {
*new_pix = new_objix_hdr_pix;
}
// callback on object index update
spiffs_cb_object_event(fs, (spiffs_page_object_ix *)objix_hdr,
new_objix_hdr_data ? SPIFFS_EV_IX_UPD : SPIFFS_EV_IX_UPD_HDR,
obj_id, objix_hdr->p_hdr.span_ix, new_objix_hdr_pix, objix_hdr->size);
if (fd) fd->objix_hdr_pix = new_objix_hdr_pix; // if this is not in the registered cluster
}
return res;
}
#endif // !SPIFFS_READ_ONLY
void spiffs_cb_object_event(
spiffs *fs,
spiffs_page_object_ix *objix,
int ev,
spiffs_obj_id obj_id_raw,
spiffs_span_ix spix,
spiffs_page_ix new_pix,
u32_t new_size) {
#if SPIFFS_IX_MAP == 0
(void)objix;
#endif
// update index caches in all file descriptors
spiffs_obj_id obj_id = obj_id_raw & ~SPIFFS_OBJ_ID_IX_FLAG;
u32_t i;
spiffs_fd *fds = (spiffs_fd *)fs->fd_space;
SPIFFS_DBG(" CALLBACK %s obj_id:"_SPIPRIid" spix:"_SPIPRIsp" npix:"_SPIPRIpg" nsz:"_SPIPRIi"\n", (const char *[]){"UPD", "NEW", "DEL", "MOV", "HUP","???"}[MIN(ev,5)],
obj_id_raw, spix, new_pix, new_size);
for (i = 0; i < fs->fd_count; i++) {
spiffs_fd *cur_fd = &fds[i];
if ((cur_fd->obj_id & ~SPIFFS_OBJ_ID_IX_FLAG) != obj_id) continue; // fd not related to updated file
#if !SPIFFS_TEMPORAL_FD_CACHE
if (cur_fd->file_nbr == 0) continue; // fd closed
#endif
if (spix == 0) { // object index header update
if (ev != SPIFFS_EV_IX_DEL) {
#if SPIFFS_TEMPORAL_FD_CACHE
if (cur_fd->score == 0) continue; // never used fd
#endif
SPIFFS_DBG(" callback: setting fd "_SPIPRIfd":"_SPIPRIid"(fdoffs:"_SPIPRIi" offs:"_SPIPRIi") objix_hdr_pix to "_SPIPRIpg", size:"_SPIPRIi"\n",
SPIFFS_FH_OFFS(fs, cur_fd->file_nbr), cur_fd->obj_id, cur_fd->fdoffset, cur_fd->offset, new_pix, new_size);
cur_fd->objix_hdr_pix = new_pix;
if (new_size != 0) {
// update size and offsets for fds to this file
cur_fd->size = new_size;
u32_t act_new_size = new_size == SPIFFS_UNDEFINED_LEN ? 0 : new_size;
#if SPIFFS_CACHE_WR
if (act_new_size > 0 && cur_fd->cache_page) {
act_new_size = MAX(act_new_size, cur_fd->cache_page->offset + cur_fd->cache_page->size);
}
#endif
if (cur_fd->offset > act_new_size) {
cur_fd->offset = act_new_size;
}
if (cur_fd->fdoffset > act_new_size) {
cur_fd->fdoffset = act_new_size;
}
#if SPIFFS_CACHE_WR
if (cur_fd->cache_page && cur_fd->cache_page->offset > act_new_size+1) {
SPIFFS_CACHE_DBG("CACHE_DROP: file trunced, dropping cache page "_SPIPRIi", no writeback\n", cur_fd->cache_page->ix);
spiffs_cache_fd_release(fs, cur_fd->cache_page);
}
#endif
}
} else {
// removing file
#if SPIFFS_CACHE_WR
if (cur_fd->file_nbr && cur_fd->cache_page) {
SPIFFS_CACHE_DBG("CACHE_DROP: file deleted, dropping cache page "_SPIPRIi", no writeback\n", cur_fd->cache_page->ix);
spiffs_cache_fd_release(fs, cur_fd->cache_page);
}
#endif
SPIFFS_DBG(" callback: release fd "_SPIPRIfd":"_SPIPRIid" span:"_SPIPRIsp" objix_pix to "_SPIPRIpg"\n", SPIFFS_FH_OFFS(fs, cur_fd->file_nbr), cur_fd->obj_id, spix, new_pix);
cur_fd->file_nbr = 0;
cur_fd->obj_id = SPIFFS_OBJ_ID_DELETED;
}
} // object index header update
if (cur_fd->cursor_objix_spix == spix) {
if (ev != SPIFFS_EV_IX_DEL) {
SPIFFS_DBG(" callback: setting fd "_SPIPRIfd":"_SPIPRIid" span:"_SPIPRIsp" objix_pix to "_SPIPRIpg"\n", SPIFFS_FH_OFFS(fs, cur_fd->file_nbr), cur_fd->obj_id, spix, new_pix);
cur_fd->cursor_objix_pix = new_pix;
} else {
cur_fd->cursor_objix_pix = 0;
}
}
} // fd update loop
#if SPIFFS_IX_MAP
// update index maps
if (ev == SPIFFS_EV_IX_UPD || ev == SPIFFS_EV_IX_NEW) {
for (i = 0; i < fs->fd_count; i++) {
spiffs_fd *cur_fd = &fds[i];
// check fd opened, having ix map, match obj id
if (cur_fd->file_nbr == 0 ||
cur_fd->ix_map == 0 ||
(cur_fd->obj_id & ~SPIFFS_OBJ_ID_IX_FLAG) != obj_id) continue;
SPIFFS_DBG(" callback: map ix update fd "_SPIPRIfd":"_SPIPRIid" span:"_SPIPRIsp"\n", SPIFFS_FH_OFFS(fs, cur_fd->file_nbr), cur_fd->obj_id, spix);
spiffs_update_ix_map(fs, cur_fd, spix, objix);
}
}
#endif
// callback to user if object index header
if (fs->file_cb_f && spix == 0 && (obj_id_raw & SPIFFS_OBJ_ID_IX_FLAG)) {
spiffs_fileop_type op;
if (ev == SPIFFS_EV_IX_NEW) {
op = SPIFFS_CB_CREATED;
} else if (ev == SPIFFS_EV_IX_UPD ||
ev == SPIFFS_EV_IX_MOV ||
ev == SPIFFS_EV_IX_UPD_HDR) {
op = SPIFFS_CB_UPDATED;
} else if (ev == SPIFFS_EV_IX_DEL) {
op = SPIFFS_CB_DELETED;
} else {
SPIFFS_DBG(" callback: WARNING unknown callback event "_SPIPRIi"\n", ev);
return; // bail out
}
fs->file_cb_f(fs, op, obj_id, new_pix);
}
}
// Open object by id
s32_t spiffs_object_open_by_id(
spiffs *fs,
spiffs_obj_id obj_id,
spiffs_fd *fd,
spiffs_flags flags,
spiffs_mode mode) {
s32_t res = SPIFFS_OK;
spiffs_page_ix pix;
res = spiffs_obj_lu_find_id_and_span(fs, obj_id | SPIFFS_OBJ_ID_IX_FLAG, 0, 0, &pix);
SPIFFS_CHECK_RES(res);
res = spiffs_object_open_by_page(fs, pix, fd, flags, mode);
return res;
}
// Open object by page index
s32_t spiffs_object_open_by_page(
spiffs *fs,
spiffs_page_ix pix,
spiffs_fd *fd,
spiffs_flags flags,
spiffs_mode mode) {
(void)mode;
s32_t res = SPIFFS_OK;
spiffs_page_object_ix_header oix_hdr;
spiffs_obj_id obj_id;
res = _spiffs_rd(fs, SPIFFS_OP_T_OBJ_IX | SPIFFS_OP_C_READ,
fd->file_nbr, SPIFFS_PAGE_TO_PADDR(fs, pix), sizeof(spiffs_page_object_ix_header), (u8_t *)&oix_hdr);
SPIFFS_CHECK_RES(res);
spiffs_block_ix bix = SPIFFS_BLOCK_FOR_PAGE(fs, pix);
int entry = SPIFFS_OBJ_LOOKUP_ENTRY_FOR_PAGE(fs, pix);
res = _spiffs_rd(fs, SPIFFS_OP_T_OBJ_LU | SPIFFS_OP_C_READ,
0, SPIFFS_BLOCK_TO_PADDR(fs, bix) + entry * sizeof(spiffs_obj_id), sizeof(spiffs_obj_id), (u8_t *)&obj_id);
fd->fs = fs;
fd->objix_hdr_pix = pix;
fd->size = oix_hdr.size;
fd->offset = 0;
fd->cursor_objix_pix = pix;
fd->cursor_objix_spix = 0;
fd->obj_id = obj_id;
fd->flags = flags;
SPIFFS_VALIDATE_OBJIX(oix_hdr.p_hdr, fd->obj_id, 0);
SPIFFS_DBG("open: fd "_SPIPRIfd" is obj id "_SPIPRIid"\n", SPIFFS_FH_OFFS(fs, fd->file_nbr), fd->obj_id);
return res;
}
#if !SPIFFS_READ_ONLY
// Append to object
// keep current object index (header) page in fs->work buffer
s32_t spiffs_object_append(spiffs_fd *fd, u32_t offset, u8_t *data, u32_t len) {
spiffs *fs = fd->fs;
s32_t res = SPIFFS_OK;
u32_t written = 0;
SPIFFS_DBG("append: "_SPIPRIi" bytes @ offs "_SPIPRIi" of size "_SPIPRIi"\n", len, offset, fd->size);
if (offset > fd->size) {
SPIFFS_DBG("append: offset reversed to size\n");
offset = fd->size;
}
res = spiffs_gc_check(fs, len + SPIFFS_DATA_PAGE_SIZE(fs)); // add an extra page of data worth for meta
if (res != SPIFFS_OK) {
SPIFFS_DBG("append: gc check fail "_SPIPRIi"\n", res);
}
SPIFFS_CHECK_RES(res);
spiffs_page_object_ix_header *objix_hdr = (spiffs_page_object_ix_header *)fs->work;
spiffs_page_object_ix *objix = (spiffs_page_object_ix *)fs->work;
spiffs_page_header p_hdr;
spiffs_span_ix cur_objix_spix = 0;
spiffs_span_ix prev_objix_spix = (spiffs_span_ix)-1;
spiffs_page_ix cur_objix_pix = fd->objix_hdr_pix;
spiffs_page_ix new_objix_hdr_page;
spiffs_span_ix data_spix = offset / SPIFFS_DATA_PAGE_SIZE(fs);
spiffs_page_ix data_page;
u32_t page_offs = offset % SPIFFS_DATA_PAGE_SIZE(fs);
// write all data
while (res == SPIFFS_OK && written < len) {
// calculate object index page span index
cur_objix_spix = SPIFFS_OBJ_IX_ENTRY_SPAN_IX(fs, data_spix);
// handle storing and loading of object indices
if (cur_objix_spix != prev_objix_spix) {
// new object index page
// within this clause we return directly if something fails, object index mess-up
if (written > 0) {
// store previous object index page, unless first pass
SPIFFS_DBG("append: "_SPIPRIid" store objix "_SPIPRIpg":"_SPIPRIsp", written "_SPIPRIi"\n", fd->obj_id,
cur_objix_pix, prev_objix_spix, written);
if (prev_objix_spix == 0) {
// this is an update to object index header page
objix_hdr->size = offset+written;
if (offset == 0) {
// was an empty object, update same page (size was 0xffffffff)
res = spiffs_page_index_check(fs, fd, cur_objix_pix, 0);
SPIFFS_CHECK_RES(res);
res = _spiffs_wr(fs, SPIFFS_OP_T_OBJ_IX | SPIFFS_OP_C_UPDT,
fd->file_nbr, SPIFFS_PAGE_TO_PADDR(fs, cur_objix_pix), SPIFFS_CFG_LOG_PAGE_SZ(fs), fs->work);
SPIFFS_CHECK_RES(res);
} else {
// was a nonempty object, update to new page
res = spiffs_object_update_index_hdr(fs, fd, fd->obj_id,
fd->objix_hdr_pix, fs->work, 0, 0, offset+written, &new_objix_hdr_page);
SPIFFS_CHECK_RES(res);
SPIFFS_DBG("append: "_SPIPRIid" store new objix_hdr, "_SPIPRIpg":"_SPIPRIsp", written "_SPIPRIi"\n", fd->obj_id,
new_objix_hdr_page, 0, written);
}
} else {
// this is an update to an object index page
res = spiffs_page_index_check(fs, fd, cur_objix_pix, prev_objix_spix);
SPIFFS_CHECK_RES(res);
res = _spiffs_wr(fs, SPIFFS_OP_T_OBJ_IX | SPIFFS_OP_C_UPDT,
fd->file_nbr, SPIFFS_PAGE_TO_PADDR(fs, cur_objix_pix), SPIFFS_CFG_LOG_PAGE_SZ(fs), fs->work);
SPIFFS_CHECK_RES(res);
spiffs_cb_object_event(fs, (spiffs_page_object_ix *)fs->work,
SPIFFS_EV_IX_UPD,fd->obj_id, objix->p_hdr.span_ix, cur_objix_pix, 0);
// update length in object index header page
res = spiffs_object_update_index_hdr(fs, fd, fd->obj_id,
fd->objix_hdr_pix, 0, 0, 0, offset+written, &new_objix_hdr_page);
SPIFFS_CHECK_RES(res);
SPIFFS_DBG("append: "_SPIPRIid" store new size I "_SPIPRIi" in objix_hdr, "_SPIPRIpg":"_SPIPRIsp", written "_SPIPRIi"\n", fd->obj_id,
offset+written, new_objix_hdr_page, 0, written);
}
fd->size = offset+written;
fd->offset = offset+written;
}
// create or load new object index page
if (cur_objix_spix == 0) {
// load object index header page, must always exist
SPIFFS_DBG("append: "_SPIPRIid" load objixhdr page "_SPIPRIpg":"_SPIPRIsp"\n", fd->obj_id, cur_objix_pix, cur_objix_spix);
res = _spiffs_rd(fs, SPIFFS_OP_T_OBJ_IX | SPIFFS_OP_C_READ,
fd->file_nbr, SPIFFS_PAGE_TO_PADDR(fs, cur_objix_pix), SPIFFS_CFG_LOG_PAGE_SZ(fs), fs->work);
SPIFFS_CHECK_RES(res);
SPIFFS_VALIDATE_OBJIX(objix_hdr->p_hdr, fd->obj_id, cur_objix_spix);
} else {
spiffs_span_ix len_objix_spix = SPIFFS_OBJ_IX_ENTRY_SPAN_IX(fs, (fd->size-1)/SPIFFS_DATA_PAGE_SIZE(fs));
// on subsequent passes, create a new object index page
if (written > 0 || cur_objix_spix > len_objix_spix) {
p_hdr.obj_id = fd->obj_id | SPIFFS_OBJ_ID_IX_FLAG;
p_hdr.span_ix = cur_objix_spix;
p_hdr.flags = 0xff & ~(SPIFFS_PH_FLAG_FINAL | SPIFFS_PH_FLAG_INDEX);
res = spiffs_page_allocate_data(fs, fd->obj_id | SPIFFS_OBJ_ID_IX_FLAG,
&p_hdr, 0, 0, 0, 1, &cur_objix_pix);
SPIFFS_CHECK_RES(res);
// quick "load" of new object index page
memset(fs->work, 0xff, SPIFFS_CFG_LOG_PAGE_SZ(fs));
_SPIFFS_MEMCPY(fs->work, &p_hdr, sizeof(spiffs_page_header));
spiffs_cb_object_event(fs, (spiffs_page_object_ix *)fs->work,
SPIFFS_EV_IX_NEW, fd->obj_id, cur_objix_spix, cur_objix_pix, 0);
SPIFFS_DBG("append: "_SPIPRIid" create objix page, "_SPIPRIpg":"_SPIPRIsp", written "_SPIPRIi"\n", fd->obj_id
, cur_objix_pix, cur_objix_spix, written);
} else {
// on first pass, we load existing object index page
spiffs_page_ix pix;
SPIFFS_DBG("append: "_SPIPRIid" find objix span_ix:"_SPIPRIsp"\n", fd->obj_id, cur_objix_spix);
if (fd->cursor_objix_spix == cur_objix_spix) {
pix = fd->cursor_objix_pix;
} else {
res = spiffs_obj_lu_find_id_and_span(fs, fd->obj_id | SPIFFS_OBJ_ID_IX_FLAG, cur_objix_spix, 0, &pix);
SPIFFS_CHECK_RES(res);
}
SPIFFS_DBG("append: "_SPIPRIid" found object index at page "_SPIPRIpg" [fd size "_SPIPRIi"]\n", fd->obj_id, pix, fd->size);
res = _spiffs_rd(fs, SPIFFS_OP_T_OBJ_IX | SPIFFS_OP_C_READ,
fd->file_nbr, SPIFFS_PAGE_TO_PADDR(fs, pix), SPIFFS_CFG_LOG_PAGE_SZ(fs), fs->work);
SPIFFS_CHECK_RES(res);
SPIFFS_VALIDATE_OBJIX(objix_hdr->p_hdr, fd->obj_id, cur_objix_spix);
cur_objix_pix = pix;
}
fd->cursor_objix_pix = cur_objix_pix;
fd->cursor_objix_spix = cur_objix_spix;
fd->offset = offset+written;
fd->size = offset+written;
}
prev_objix_spix = cur_objix_spix;
}
// write data
u32_t to_write = MIN(len-written, SPIFFS_DATA_PAGE_SIZE(fs) - page_offs);
if (page_offs == 0) {
// at beginning of a page, allocate and write a new page of data
p_hdr.obj_id = fd->obj_id & ~SPIFFS_OBJ_ID_IX_FLAG;
p_hdr.span_ix = data_spix;
p_hdr.flags = 0xff & ~(SPIFFS_PH_FLAG_FINAL); // finalize immediately
res = spiffs_page_allocate_data(fs, fd->obj_id & ~SPIFFS_OBJ_ID_IX_FLAG,
&p_hdr, &data[written], to_write, page_offs, 1, &data_page);
SPIFFS_DBG("append: "_SPIPRIid" store new data page, "_SPIPRIpg":"_SPIPRIsp" offset:"_SPIPRIi", len "_SPIPRIi", written "_SPIPRIi"\n", fd->obj_id,
data_page, data_spix, page_offs, to_write, written);
} else {
// append to existing page, fill out free data in existing page
if (cur_objix_spix == 0) {
// get data page from object index header page
data_page = ((spiffs_page_ix*)((u8_t *)objix_hdr + sizeof(spiffs_page_object_ix_header)))[data_spix];
} else {
// get data page from object index page
data_page = ((spiffs_page_ix*)((u8_t *)objix + sizeof(spiffs_page_object_ix)))[SPIFFS_OBJ_IX_ENTRY(fs, data_spix)];
}
res = spiffs_page_data_check(fs, fd, data_page, data_spix);
SPIFFS_CHECK_RES(res);
res = _spiffs_wr(fs, SPIFFS_OP_T_OBJ_DA | SPIFFS_OP_C_UPDT,
fd->file_nbr, SPIFFS_PAGE_TO_PADDR(fs, data_page) + sizeof(spiffs_page_header) + page_offs, to_write, &data[written]);
SPIFFS_DBG("append: "_SPIPRIid" store to existing data page, "_SPIPRIpg":"_SPIPRIsp" offset:"_SPIPRIi", len "_SPIPRIi", written "_SPIPRIi"\n", fd->obj_id
, data_page, data_spix, page_offs, to_write, written);
}
if (res != SPIFFS_OK) break;
// update memory representation of object index page with new data page
if (cur_objix_spix == 0) {
// update object index header page
((spiffs_page_ix*)((u8_t *)objix_hdr + sizeof(spiffs_page_object_ix_header)))[data_spix] = data_page;
SPIFFS_DBG("append: "_SPIPRIid" wrote page "_SPIPRIpg" to objix_hdr entry "_SPIPRIsp" in mem\n", fd->obj_id
, data_page, data_spix);
objix_hdr->size = offset+written;
} else {
// update object index page
((spiffs_page_ix*)((u8_t *)objix + sizeof(spiffs_page_object_ix)))[SPIFFS_OBJ_IX_ENTRY(fs, data_spix)] = data_page;
SPIFFS_DBG("append: "_SPIPRIid" wrote page "_SPIPRIpg" to objix entry "_SPIPRIsp" in mem\n", fd->obj_id
, data_page, (spiffs_span_ix)SPIFFS_OBJ_IX_ENTRY(fs, data_spix));
}
// update internals
page_offs = 0;
data_spix++;
written += to_write;
} // while all data
fd->size = offset+written;
fd->offset = offset+written;
fd->cursor_objix_pix = cur_objix_pix;
fd->cursor_objix_spix = cur_objix_spix;
// finalize updated object indices
s32_t res2 = SPIFFS_OK;
if (cur_objix_spix != 0) {
// wrote beyond object index header page
// write last modified object index page, unless object header index page
SPIFFS_DBG("append: "_SPIPRIid" store objix page, "_SPIPRIpg":"_SPIPRIsp", written "_SPIPRIi"\n", fd->obj_id,
cur_objix_pix, cur_objix_spix, written);
res2 = spiffs_page_index_check(fs, fd, cur_objix_pix, cur_objix_spix);
SPIFFS_CHECK_RES(res2);
res2 = _spiffs_wr(fs, SPIFFS_OP_T_OBJ_IX | SPIFFS_OP_C_UPDT,
fd->file_nbr, SPIFFS_PAGE_TO_PADDR(fs, cur_objix_pix), SPIFFS_CFG_LOG_PAGE_SZ(fs), fs->work);
SPIFFS_CHECK_RES(res2);
spiffs_cb_object_event(fs, (spiffs_page_object_ix *)fs->work,
SPIFFS_EV_IX_UPD, fd->obj_id, objix->p_hdr.span_ix, cur_objix_pix, 0);
// update size in object header index page
res2 = spiffs_object_update_index_hdr(fs, fd, fd->obj_id,
fd->objix_hdr_pix, 0, 0, 0, offset+written, &new_objix_hdr_page);
SPIFFS_DBG("append: "_SPIPRIid" store new size II "_SPIPRIi" in objix_hdr, "_SPIPRIpg":"_SPIPRIsp", written "_SPIPRIi", res "_SPIPRIi"\n", fd->obj_id
, offset+written, new_objix_hdr_page, 0, written, res2);
SPIFFS_CHECK_RES(res2);
} else {
// wrote within object index header page
if (offset == 0) {
// wrote to empty object - simply update size and write whole page
objix_hdr->size = offset+written;
SPIFFS_DBG("append: "_SPIPRIid" store fresh objix_hdr page, "_SPIPRIpg":"_SPIPRIsp", written "_SPIPRIi"\n", fd->obj_id
, cur_objix_pix, cur_objix_spix, written);
res2 = spiffs_page_index_check(fs, fd, cur_objix_pix, cur_objix_spix);
SPIFFS_CHECK_RES(res2);
res2 = _spiffs_wr(fs, SPIFFS_OP_T_OBJ_IX | SPIFFS_OP_C_UPDT,
fd->file_nbr, SPIFFS_PAGE_TO_PADDR(fs, cur_objix_pix), SPIFFS_CFG_LOG_PAGE_SZ(fs), fs->work);
SPIFFS_CHECK_RES(res2);
// callback on object index update
spiffs_cb_object_event(fs, (spiffs_page_object_ix *)fs->work,
SPIFFS_EV_IX_UPD_HDR, fd->obj_id, objix_hdr->p_hdr.span_ix, cur_objix_pix, objix_hdr->size);
} else {
// modifying object index header page, update size and make new copy
res2 = spiffs_object_update_index_hdr(fs, fd, fd->obj_id,
fd->objix_hdr_pix, fs->work, 0, 0, offset+written, &new_objix_hdr_page);
SPIFFS_DBG("append: "_SPIPRIid" store modified objix_hdr page, "_SPIPRIpg":"_SPIPRIsp", written "_SPIPRIi"\n", fd->obj_id
, new_objix_hdr_page, 0, written);
SPIFFS_CHECK_RES(res2);
}
}
return res;
} // spiffs_object_append
#endif // !SPIFFS_READ_ONLY
#if !SPIFFS_READ_ONLY
// Modify object
// keep current object index (header) page in fs->work buffer
s32_t spiffs_object_modify(spiffs_fd *fd, u32_t offset, u8_t *data, u32_t len) {
spiffs *fs = fd->fs;
s32_t res = SPIFFS_OK;
u32_t written = 0;
res = spiffs_gc_check(fs, len + SPIFFS_DATA_PAGE_SIZE(fs));
SPIFFS_CHECK_RES(res);
spiffs_page_object_ix_header *objix_hdr = (spiffs_page_object_ix_header *)fs->work;
spiffs_page_object_ix *objix = (spiffs_page_object_ix *)fs->work;
spiffs_page_header p_hdr;
spiffs_span_ix cur_objix_spix = 0;
spiffs_span_ix prev_objix_spix = (spiffs_span_ix)-1;
spiffs_page_ix cur_objix_pix = fd->objix_hdr_pix;
spiffs_page_ix new_objix_hdr_pix;
spiffs_span_ix data_spix = offset / SPIFFS_DATA_PAGE_SIZE(fs);
spiffs_page_ix data_pix;
u32_t page_offs = offset % SPIFFS_DATA_PAGE_SIZE(fs);
// write all data
while (res == SPIFFS_OK && written < len) {
// calculate object index page span index
cur_objix_spix = SPIFFS_OBJ_IX_ENTRY_SPAN_IX(fs, data_spix);
// handle storing and loading of object indices
if (cur_objix_spix != prev_objix_spix) {
// new object index page
// within this clause we return directly if something fails, object index mess-up
if (written > 0) {
// store previous object index (header) page, unless first pass
if (prev_objix_spix == 0) {
// store previous object index header page
res = spiffs_object_update_index_hdr(fs, fd, fd->obj_id,
fd->objix_hdr_pix, fs->work, 0, 0, 0, &new_objix_hdr_pix);
SPIFFS_DBG("modify: store modified objix_hdr page, "_SPIPRIpg":"_SPIPRIsp", written "_SPIPRIi"\n", new_objix_hdr_pix, 0, written);
SPIFFS_CHECK_RES(res);
} else {
// store new version of previous object index page
spiffs_page_ix new_objix_pix;
res = spiffs_page_index_check(fs, fd, cur_objix_pix, prev_objix_spix);
SPIFFS_CHECK_RES(res);
res = spiffs_page_move(fs, fd->file_nbr, (u8_t*)objix, fd->obj_id, 0, cur_objix_pix, &new_objix_pix);
SPIFFS_DBG("modify: store previous modified objix page, "_SPIPRIid":"_SPIPRIsp", written "_SPIPRIi"\n", new_objix_pix, objix->p_hdr.span_ix, written);
SPIFFS_CHECK_RES(res);
spiffs_cb_object_event(fs, (spiffs_page_object_ix *)objix,
SPIFFS_EV_IX_UPD, fd->obj_id, objix->p_hdr.span_ix, new_objix_pix, 0);
}
}
// load next object index page
if (cur_objix_spix == 0) {
// load object index header page, must exist
SPIFFS_DBG("modify: load objixhdr page "_SPIPRIpg":"_SPIPRIsp"\n", cur_objix_pix, cur_objix_spix);
res = _spiffs_rd(fs, SPIFFS_OP_T_OBJ_IX | SPIFFS_OP_C_READ,
fd->file_nbr, SPIFFS_PAGE_TO_PADDR(fs, cur_objix_pix), SPIFFS_CFG_LOG_PAGE_SZ(fs), fs->work);
SPIFFS_CHECK_RES(res);
SPIFFS_VALIDATE_OBJIX(objix_hdr->p_hdr, fd->obj_id, cur_objix_spix);
} else {
// load existing object index page on first pass
spiffs_page_ix pix;
SPIFFS_DBG("modify: find objix span_ix:"_SPIPRIsp"\n", cur_objix_spix);
if (fd->cursor_objix_spix == cur_objix_spix) {
pix = fd->cursor_objix_pix;
} else {
res = spiffs_obj_lu_find_id_and_span(fs, fd->obj_id | SPIFFS_OBJ_ID_IX_FLAG, cur_objix_spix, 0, &pix);
SPIFFS_CHECK_RES(res);
}
SPIFFS_DBG("modify: found object index at page "_SPIPRIpg"\n", pix);
res = _spiffs_rd(fs, SPIFFS_OP_T_OBJ_IX | SPIFFS_OP_C_READ,
fd->file_nbr, SPIFFS_PAGE_TO_PADDR(fs, pix), SPIFFS_CFG_LOG_PAGE_SZ(fs), fs->work);
SPIFFS_CHECK_RES(res);
SPIFFS_VALIDATE_OBJIX(objix_hdr->p_hdr, fd->obj_id, cur_objix_spix);
cur_objix_pix = pix;
}
fd->cursor_objix_pix = cur_objix_pix;
fd->cursor_objix_spix = cur_objix_spix;
fd->offset = offset+written;
prev_objix_spix = cur_objix_spix;
}
// write partial data
u32_t to_write = MIN(len-written, SPIFFS_DATA_PAGE_SIZE(fs) - page_offs);
spiffs_page_ix orig_data_pix;
if (cur_objix_spix == 0) {
// get data page from object index header page
orig_data_pix = ((spiffs_page_ix*)((u8_t *)objix_hdr + sizeof(spiffs_page_object_ix_header)))[data_spix];
} else {
// get data page from object index page
orig_data_pix = ((spiffs_page_ix*)((u8_t *)objix + sizeof(spiffs_page_object_ix)))[SPIFFS_OBJ_IX_ENTRY(fs, data_spix)];
}
p_hdr.obj_id = fd->obj_id & ~SPIFFS_OBJ_ID_IX_FLAG;
p_hdr.span_ix = data_spix;
p_hdr.flags = 0xff;
if (page_offs == 0 && to_write == SPIFFS_DATA_PAGE_SIZE(fs)) {
// a full page, allocate and write a new page of data
res = spiffs_page_allocate_data(fs, fd->obj_id & ~SPIFFS_OBJ_ID_IX_FLAG,
&p_hdr, &data[written], to_write, page_offs, 1, &data_pix);
SPIFFS_DBG("modify: store new data page, "_SPIPRIpg":"_SPIPRIsp" offset:"_SPIPRIi", len "_SPIPRIi", written "_SPIPRIi"\n", data_pix, data_spix, page_offs, to_write, written);
} else {
// write to existing page, allocate new and copy unmodified data
res = spiffs_page_data_check(fs, fd, orig_data_pix, data_spix);
SPIFFS_CHECK_RES(res);
res = spiffs_page_allocate_data(fs, fd->obj_id & ~SPIFFS_OBJ_ID_IX_FLAG,
&p_hdr, 0, 0, 0, 0, &data_pix);
if (res != SPIFFS_OK) break;
// copy unmodified data
if (page_offs > 0) {
// before modification
res = spiffs_phys_cpy(fs, fd->file_nbr,
SPIFFS_PAGE_TO_PADDR(fs, data_pix) + sizeof(spiffs_page_header),
SPIFFS_PAGE_TO_PADDR(fs, orig_data_pix) + sizeof(spiffs_page_header),
page_offs);
if (res != SPIFFS_OK) break;
}
if (page_offs + to_write < SPIFFS_DATA_PAGE_SIZE(fs)) {
// after modification
res = spiffs_phys_cpy(fs, fd->file_nbr,
SPIFFS_PAGE_TO_PADDR(fs, data_pix) + sizeof(spiffs_page_header) + page_offs + to_write,
SPIFFS_PAGE_TO_PADDR(fs, orig_data_pix) + sizeof(spiffs_page_header) + page_offs + to_write,
SPIFFS_DATA_PAGE_SIZE(fs) - (page_offs + to_write));
if (res != SPIFFS_OK) break;
}
res = _spiffs_wr(fs, SPIFFS_OP_T_OBJ_DA | SPIFFS_OP_C_UPDT,
fd->file_nbr,
SPIFFS_PAGE_TO_PADDR(fs, data_pix) + sizeof(spiffs_page_header) + page_offs, to_write, &data[written]);
if (res != SPIFFS_OK) break;
p_hdr.flags &= ~SPIFFS_PH_FLAG_FINAL;
res = _spiffs_wr(fs, SPIFFS_OP_T_OBJ_DA | SPIFFS_OP_C_UPDT,
fd->file_nbr,
SPIFFS_PAGE_TO_PADDR(fs, data_pix) + offsetof(spiffs_page_header, flags),
sizeof(u8_t),
(u8_t *)&p_hdr.flags);
if (res != SPIFFS_OK) break;
SPIFFS_DBG("modify: store to existing data page, src:"_SPIPRIpg", dst:"_SPIPRIpg":"_SPIPRIsp" offset:"_SPIPRIi", len "_SPIPRIi", written "_SPIPRIi"\n", orig_data_pix, data_pix, data_spix, page_offs, to_write, written);
}
// delete original data page
res = spiffs_page_delete(fs, orig_data_pix);
if (res != SPIFFS_OK) break;
// update memory representation of object index page with new data page
if (cur_objix_spix == 0) {
// update object index header page
((spiffs_page_ix*)((u8_t *)objix_hdr + sizeof(spiffs_page_object_ix_header)))[data_spix] = data_pix;
SPIFFS_DBG("modify: wrote page "_SPIPRIpg" to objix_hdr entry "_SPIPRIsp" in mem\n", data_pix, data_spix);
} else {
// update object index page
((spiffs_page_ix*)((u8_t *)objix + sizeof(spiffs_page_object_ix)))[SPIFFS_OBJ_IX_ENTRY(fs, data_spix)] = data_pix;
SPIFFS_DBG("modify: wrote page "_SPIPRIpg" to objix entry "_SPIPRIsp" in mem\n", data_pix, (spiffs_span_ix)SPIFFS_OBJ_IX_ENTRY(fs, data_spix));
}
// update internals
page_offs = 0;
data_spix++;
written += to_write;
} // while all data
fd->offset = offset+written;
fd->cursor_objix_pix = cur_objix_pix;
fd->cursor_objix_spix = cur_objix_spix;
// finalize updated object indices
s32_t res2 = SPIFFS_OK;
if (cur_objix_spix != 0) {
// wrote beyond object index header page
// write last modified object index page
// move and update page
spiffs_page_ix new_objix_pix;
res2 = spiffs_page_index_check(fs, fd, cur_objix_pix, cur_objix_spix);
SPIFFS_CHECK_RES(res2);
res2 = spiffs_page_move(fs, fd->file_nbr, (u8_t*)objix, fd->obj_id, 0, cur_objix_pix, &new_objix_pix);
SPIFFS_DBG("modify: store modified objix page, "_SPIPRIpg":"_SPIPRIsp", written "_SPIPRIi"\n", new_objix_pix, cur_objix_spix, written);
fd->cursor_objix_pix = new_objix_pix;
fd->cursor_objix_spix = cur_objix_spix;
SPIFFS_CHECK_RES(res2);
spiffs_cb_object_event(fs, (spiffs_page_object_ix *)objix,
SPIFFS_EV_IX_UPD, fd->obj_id, objix->p_hdr.span_ix, new_objix_pix, 0);
} else {
// wrote within object index header page
res2 = spiffs_object_update_index_hdr(fs, fd, fd->obj_id,
fd->objix_hdr_pix, fs->work, 0, 0, 0, &new_objix_hdr_pix);
SPIFFS_DBG("modify: store modified objix_hdr page, "_SPIPRIpg":"_SPIPRIsp", written "_SPIPRIi"\n", new_objix_hdr_pix, 0, written);
SPIFFS_CHECK_RES(res2);
}
return res;
} // spiffs_object_modify
#endif // !SPIFFS_READ_ONLY
static s32_t spiffs_object_find_object_index_header_by_name_v(
spiffs *fs,
spiffs_obj_id obj_id,
spiffs_block_ix bix,
int ix_entry,
const void *user_const_p,
void *user_var_p) {
(void)user_var_p;
s32_t res;
spiffs_page_object_ix_header objix_hdr;
spiffs_page_ix pix = SPIFFS_OBJ_LOOKUP_ENTRY_TO_PIX(fs, bix, ix_entry);
if (obj_id == SPIFFS_OBJ_ID_FREE || obj_id == SPIFFS_OBJ_ID_DELETED ||
(obj_id & SPIFFS_OBJ_ID_IX_FLAG) == 0) {
return SPIFFS_VIS_COUNTINUE;
}
res = _spiffs_rd(fs, SPIFFS_OP_T_OBJ_LU2 | SPIFFS_OP_C_READ,
0, SPIFFS_PAGE_TO_PADDR(fs, pix), sizeof(spiffs_page_object_ix_header), (u8_t *)&objix_hdr);
SPIFFS_CHECK_RES(res);
if (objix_hdr.p_hdr.span_ix == 0 &&
(objix_hdr.p_hdr.flags & (SPIFFS_PH_FLAG_DELET | SPIFFS_PH_FLAG_FINAL | SPIFFS_PH_FLAG_IXDELE)) ==
(SPIFFS_PH_FLAG_DELET | SPIFFS_PH_FLAG_IXDELE)) {
if (strcmp((const char*)user_const_p, (char*)objix_hdr.name) == 0) {
return SPIFFS_OK;
}
}
return SPIFFS_VIS_COUNTINUE;
}
// Finds object index header page by name
s32_t spiffs_object_find_object_index_header_by_name(
spiffs *fs,
const u8_t name[SPIFFS_OBJ_NAME_LEN],
spiffs_page_ix *pix) {
s32_t res;
spiffs_block_ix bix;
int entry;
res = spiffs_obj_lu_find_entry_visitor(fs,
fs->cursor_block_ix,
fs->cursor_obj_lu_entry,
0,
0,
spiffs_object_find_object_index_header_by_name_v,
name,
0,
&bix,
&entry);
if (res == SPIFFS_VIS_END) {
res = SPIFFS_ERR_NOT_FOUND;
}
SPIFFS_CHECK_RES(res);
if (pix) {
*pix = SPIFFS_OBJ_LOOKUP_ENTRY_TO_PIX(fs, bix, entry);
}
fs->cursor_block_ix = bix;
fs->cursor_obj_lu_entry = entry;
return res;
}
#if !SPIFFS_READ_ONLY
// Truncates object to new size. If new size is null, object may be removed totally
s32_t spiffs_object_truncate(
spiffs_fd *fd,
u32_t new_size,
u8_t remove_full) {
s32_t res = SPIFFS_OK;
spiffs *fs = fd->fs;
if ((fd->size == SPIFFS_UNDEFINED_LEN || fd->size == 0) && !remove_full) {
// no op
return res;
}
// need 2 pages if not removing: object index page + possibly chopped data page
if (remove_full == 0) {
res = spiffs_gc_check(fs, SPIFFS_DATA_PAGE_SIZE(fs) * 2);
SPIFFS_CHECK_RES(res);
}
spiffs_page_ix objix_pix = fd->objix_hdr_pix;
spiffs_span_ix data_spix = (fd->size > 0 ? fd->size-1 : 0) / SPIFFS_DATA_PAGE_SIZE(fs);
u32_t cur_size = fd->size == (u32_t)SPIFFS_UNDEFINED_LEN ? 0 : fd->size ;
spiffs_span_ix cur_objix_spix = 0;
spiffs_span_ix prev_objix_spix = (spiffs_span_ix)-1;
spiffs_page_object_ix_header *objix_hdr = (spiffs_page_object_ix_header *)fs->work;
spiffs_page_object_ix *objix = (spiffs_page_object_ix *)fs->work;
spiffs_page_ix data_pix;
spiffs_page_ix new_objix_hdr_pix;
// before truncating, check if object is to be fully removed and mark this
if (remove_full && new_size == 0) {
u8_t flags = ~( SPIFFS_PH_FLAG_USED | SPIFFS_PH_FLAG_INDEX | SPIFFS_PH_FLAG_FINAL | SPIFFS_PH_FLAG_IXDELE);
res = _spiffs_wr(fs, SPIFFS_OP_T_OBJ_IX | SPIFFS_OP_C_UPDT,
fd->file_nbr, SPIFFS_PAGE_TO_PADDR(fs, fd->objix_hdr_pix) + offsetof(spiffs_page_header, flags),
sizeof(u8_t),
(u8_t *)&flags);
SPIFFS_CHECK_RES(res);
}
// delete from end of object until desired len is reached
while (cur_size > new_size) {
cur_objix_spix = SPIFFS_OBJ_IX_ENTRY_SPAN_IX(fs, data_spix);
// put object index for current data span index in work buffer
if (prev_objix_spix != cur_objix_spix) {
if (prev_objix_spix != (spiffs_span_ix)-1) {
// remove previous object index page
SPIFFS_DBG("truncate: delete objix page "_SPIPRIpg":"_SPIPRIsp"\n", objix_pix, prev_objix_spix);
res = spiffs_page_index_check(fs, fd, objix_pix, prev_objix_spix);
SPIFFS_CHECK_RES(res);
res = spiffs_page_delete(fs, objix_pix);
SPIFFS_CHECK_RES(res);
spiffs_cb_object_event(fs, (spiffs_page_object_ix *)0,
SPIFFS_EV_IX_DEL, fd->obj_id, objix->p_hdr.span_ix, objix_pix, 0);
if (prev_objix_spix > 0) {
// Update object index header page, unless we totally want to remove the file.
// If fully removing, we're not keeping consistency as good as when storing the header between chunks,
// would we be aborted. But when removing full files, a crammed system may otherwise
// report ERR_FULL a la windows. We cannot have that.
// Hence, take the risk - if aborted, a file check would free the lost pages and mend things
// as the file is marked as fully deleted in the beginning.
if (remove_full == 0) {
SPIFFS_DBG("truncate: update objix hdr page "_SPIPRIpg":"_SPIPRIsp" to size "_SPIPRIi"\n", fd->objix_hdr_pix, prev_objix_spix, cur_size);
res = spiffs_object_update_index_hdr(fs, fd, fd->obj_id,
fd->objix_hdr_pix, 0, 0, 0, cur_size, &new_objix_hdr_pix);
SPIFFS_CHECK_RES(res);
}
fd->size = cur_size;
}
}
// load current object index (header) page
if (cur_objix_spix == 0) {
objix_pix = fd->objix_hdr_pix;
} else {
res = spiffs_obj_lu_find_id_and_span(fs, fd->obj_id | SPIFFS_OBJ_ID_IX_FLAG, cur_objix_spix, 0, &objix_pix);
SPIFFS_CHECK_RES(res);
}
SPIFFS_DBG("truncate: load objix page "_SPIPRIpg":"_SPIPRIsp" for data spix:"_SPIPRIsp"\n", objix_pix, cur_objix_spix, data_spix);
res = _spiffs_rd(fs, SPIFFS_OP_T_OBJ_IX | SPIFFS_OP_C_READ,
fd->file_nbr, SPIFFS_PAGE_TO_PADDR(fs, objix_pix), SPIFFS_CFG_LOG_PAGE_SZ(fs), fs->work);
SPIFFS_CHECK_RES(res);
SPIFFS_VALIDATE_OBJIX(objix_hdr->p_hdr, fd->obj_id, cur_objix_spix);
fd->cursor_objix_pix = objix_pix;
fd->cursor_objix_spix = cur_objix_spix;
fd->offset = cur_size;
prev_objix_spix = cur_objix_spix;
}
if (cur_objix_spix == 0) {
// get data page from object index header page
data_pix = ((spiffs_page_ix*)((u8_t *)objix_hdr + sizeof(spiffs_page_object_ix_header)))[data_spix];
((spiffs_page_ix*)((u8_t *)objix_hdr + sizeof(spiffs_page_object_ix_header)))[data_spix] = SPIFFS_OBJ_ID_FREE;
} else {
// get data page from object index page
data_pix = ((spiffs_page_ix*)((u8_t *)objix + sizeof(spiffs_page_object_ix)))[SPIFFS_OBJ_IX_ENTRY(fs, data_spix)];
((spiffs_page_ix*)((u8_t *)objix + sizeof(spiffs_page_object_ix)))[SPIFFS_OBJ_IX_ENTRY(fs, data_spix)] = SPIFFS_OBJ_ID_FREE;
}
SPIFFS_DBG("truncate: got data pix "_SPIPRIpg"\n", data_pix);
if (new_size == 0 || remove_full || cur_size - new_size >= SPIFFS_DATA_PAGE_SIZE(fs)) {
// delete full data page
res = spiffs_page_data_check(fs, fd, data_pix, data_spix);
if (res != SPIFFS_ERR_DELETED && res != SPIFFS_OK && res != SPIFFS_ERR_INDEX_REF_FREE) {
SPIFFS_DBG("truncate: err validating data pix "_SPIPRIi"\n", res);
break;
}
if (res == SPIFFS_OK) {
res = spiffs_page_delete(fs, data_pix);
if (res != SPIFFS_OK) {
SPIFFS_DBG("truncate: err deleting data pix "_SPIPRIi"\n", res);
break;
}
} else if (res == SPIFFS_ERR_DELETED || res == SPIFFS_ERR_INDEX_REF_FREE) {
res = SPIFFS_OK;
}
// update current size
if (cur_size % SPIFFS_DATA_PAGE_SIZE(fs) == 0) {
cur_size -= SPIFFS_DATA_PAGE_SIZE(fs);
} else {
cur_size -= cur_size % SPIFFS_DATA_PAGE_SIZE(fs);
}
fd->size = cur_size;
fd->offset = cur_size;
SPIFFS_DBG("truncate: delete data page "_SPIPRIpg" for data spix:"_SPIPRIsp", cur_size:"_SPIPRIi"\n", data_pix, data_spix, cur_size);
} else {
// delete last page, partially
spiffs_page_header p_hdr;
spiffs_page_ix new_data_pix;
u32_t bytes_to_remove = SPIFFS_DATA_PAGE_SIZE(fs) - (new_size % SPIFFS_DATA_PAGE_SIZE(fs));
SPIFFS_DBG("truncate: delete "_SPIPRIi" bytes from data page "_SPIPRIpg" for data spix:"_SPIPRIsp", cur_size:"_SPIPRIi"\n", bytes_to_remove, data_pix, data_spix, cur_size);
res = spiffs_page_data_check(fs, fd, data_pix, data_spix);
if (res != SPIFFS_OK) break;
p_hdr.obj_id = fd->obj_id & ~SPIFFS_OBJ_ID_IX_FLAG;
p_hdr.span_ix = data_spix;
p_hdr.flags = 0xff;
// allocate new page and copy unmodified data
res = spiffs_page_allocate_data(fs, fd->obj_id & ~SPIFFS_OBJ_ID_IX_FLAG,
&p_hdr, 0, 0, 0, 0, &new_data_pix);
if (res != SPIFFS_OK) break;
res = spiffs_phys_cpy(fs, 0,
SPIFFS_PAGE_TO_PADDR(fs, new_data_pix) + sizeof(spiffs_page_header),
SPIFFS_PAGE_TO_PADDR(fs, data_pix) + sizeof(spiffs_page_header),
SPIFFS_DATA_PAGE_SIZE(fs) - bytes_to_remove);
if (res != SPIFFS_OK) break;
// delete original data page
res = spiffs_page_delete(fs, data_pix);
if (res != SPIFFS_OK) break;
p_hdr.flags &= ~SPIFFS_PH_FLAG_FINAL;
res = _spiffs_wr(fs, SPIFFS_OP_T_OBJ_DA | SPIFFS_OP_C_UPDT,
fd->file_nbr,
SPIFFS_PAGE_TO_PADDR(fs, new_data_pix) + offsetof(spiffs_page_header, flags),
sizeof(u8_t),
(u8_t *)&p_hdr.flags);
if (res != SPIFFS_OK) break;
// update memory representation of object index page with new data page
if (cur_objix_spix == 0) {
// update object index header page
((spiffs_page_ix*)((u8_t *)objix_hdr + sizeof(spiffs_page_object_ix_header)))[data_spix] = new_data_pix;
SPIFFS_DBG("truncate: wrote page "_SPIPRIpg" to objix_hdr entry "_SPIPRIsp" in mem\n", new_data_pix, (spiffs_span_ix)SPIFFS_OBJ_IX_ENTRY(fs, data_spix));
} else {
// update object index page
((spiffs_page_ix*)((u8_t *)objix + sizeof(spiffs_page_object_ix)))[SPIFFS_OBJ_IX_ENTRY(fs, data_spix)] = new_data_pix;
SPIFFS_DBG("truncate: wrote page "_SPIPRIpg" to objix entry "_SPIPRIsp" in mem\n", new_data_pix, (spiffs_span_ix)SPIFFS_OBJ_IX_ENTRY(fs, data_spix));
}
cur_size = new_size;
fd->size = new_size;
fd->offset = cur_size;
break;
}
data_spix--;
} // while all data
// update object indices
if (cur_objix_spix == 0) {
// update object index header page
if (cur_size == 0) {
if (remove_full) {
// remove object altogether
SPIFFS_DBG("truncate: remove object index header page "_SPIPRIpg"\n", objix_pix);
res = spiffs_page_index_check(fs, fd, objix_pix, 0);
SPIFFS_CHECK_RES(res);
res = spiffs_page_delete(fs, objix_pix);
SPIFFS_CHECK_RES(res);
spiffs_cb_object_event(fs, (spiffs_page_object_ix *)0,
SPIFFS_EV_IX_DEL, fd->obj_id, 0, objix_pix, 0);
} else {
// make uninitialized object
SPIFFS_DBG("truncate: reset objix_hdr page "_SPIPRIpg"\n", objix_pix);
memset(fs->work + sizeof(spiffs_page_object_ix_header), 0xff,
SPIFFS_CFG_LOG_PAGE_SZ(fs) - sizeof(spiffs_page_object_ix_header));
res = spiffs_object_update_index_hdr(fs, fd, fd->obj_id,
objix_pix, fs->work, 0, 0, SPIFFS_UNDEFINED_LEN, &new_objix_hdr_pix);
SPIFFS_CHECK_RES(res);
}
} else {
// update object index header page
SPIFFS_DBG("truncate: update object index header page with indices and size\n");
res = spiffs_object_update_index_hdr(fs, fd, fd->obj_id,
objix_pix, fs->work, 0, 0, cur_size, &new_objix_hdr_pix);
SPIFFS_CHECK_RES(res);
}
} else {
// update both current object index page and object index header page
spiffs_page_ix new_objix_pix;
res = spiffs_page_index_check(fs, fd, objix_pix, cur_objix_spix);
SPIFFS_CHECK_RES(res);
// move and update object index page
res = spiffs_page_move(fs, fd->file_nbr, (u8_t*)objix_hdr, fd->obj_id, 0, objix_pix, &new_objix_pix);
SPIFFS_CHECK_RES(res);
spiffs_cb_object_event(fs, (spiffs_page_object_ix *)objix_hdr,
SPIFFS_EV_IX_UPD, fd->obj_id, objix->p_hdr.span_ix, new_objix_pix, 0);
SPIFFS_DBG("truncate: store modified objix page, "_SPIPRIpg":"_SPIPRIsp"\n", new_objix_pix, cur_objix_spix);
fd->cursor_objix_pix = new_objix_pix;
fd->cursor_objix_spix = cur_objix_spix;
fd->offset = cur_size;
// update object index header page with new size
res = spiffs_object_update_index_hdr(fs, fd, fd->obj_id,
fd->objix_hdr_pix, 0, 0, 0, cur_size, &new_objix_hdr_pix);
SPIFFS_CHECK_RES(res);
}
fd->size = cur_size;
return res;
} // spiffs_object_truncate
#endif // !SPIFFS_READ_ONLY
s32_t spiffs_object_read(
spiffs_fd *fd,
u32_t offset,
u32_t len,
u8_t *dst) {
s32_t res = SPIFFS_OK;
spiffs *fs = fd->fs;
spiffs_page_ix objix_pix;
spiffs_page_ix data_pix;
spiffs_span_ix data_spix = offset / SPIFFS_DATA_PAGE_SIZE(fs);
u32_t cur_offset = offset;
spiffs_span_ix cur_objix_spix;
spiffs_span_ix prev_objix_spix = (spiffs_span_ix)-1;
spiffs_page_object_ix_header *objix_hdr = (spiffs_page_object_ix_header *)fs->work;
spiffs_page_object_ix *objix = (spiffs_page_object_ix *)fs->work;
while (cur_offset < offset + len) {
#if SPIFFS_IX_MAP
// check if we have a memory, index map and if so, if we're within index map's range
// and if so, if the entry is populated
if (fd->ix_map && data_spix >= fd->ix_map->start_spix && data_spix <= fd->ix_map->end_spix
&& fd->ix_map->map_buf[data_spix - fd->ix_map->start_spix]) {
data_pix = fd->ix_map->map_buf[data_spix - fd->ix_map->start_spix];
} else {
#endif
cur_objix_spix = SPIFFS_OBJ_IX_ENTRY_SPAN_IX(fs, data_spix);
if (prev_objix_spix != cur_objix_spix) {
// load current object index (header) page
if (cur_objix_spix == 0) {
objix_pix = fd->objix_hdr_pix;
} else {
SPIFFS_DBG("read: find objix "_SPIPRIid":"_SPIPRIsp"\n", fd->obj_id, cur_objix_spix);
if (fd->cursor_objix_spix == cur_objix_spix) {
objix_pix = fd->cursor_objix_pix;
} else {
res = spiffs_obj_lu_find_id_and_span(fs, fd->obj_id | SPIFFS_OBJ_ID_IX_FLAG, cur_objix_spix, 0, &objix_pix);
SPIFFS_CHECK_RES(res);
}
}
SPIFFS_DBG("read: load objix page "_SPIPRIpg":"_SPIPRIsp" for data spix:"_SPIPRIsp"\n", objix_pix, cur_objix_spix, data_spix);
res = _spiffs_rd(fs, SPIFFS_OP_T_OBJ_IX | SPIFFS_OP_C_READ,
fd->file_nbr, SPIFFS_PAGE_TO_PADDR(fs, objix_pix), SPIFFS_CFG_LOG_PAGE_SZ(fs), fs->work);
SPIFFS_CHECK_RES(res);
SPIFFS_VALIDATE_OBJIX(objix->p_hdr, fd->obj_id, cur_objix_spix);
fd->offset = cur_offset;
fd->cursor_objix_pix = objix_pix;
fd->cursor_objix_spix = cur_objix_spix;
prev_objix_spix = cur_objix_spix;
}
if (cur_objix_spix == 0) {
// get data page from object index header page
data_pix = ((spiffs_page_ix*)((u8_t *)objix_hdr + sizeof(spiffs_page_object_ix_header)))[data_spix];
} else {
// get data page from object index page
data_pix = ((spiffs_page_ix*)((u8_t *)objix + sizeof(spiffs_page_object_ix)))[SPIFFS_OBJ_IX_ENTRY(fs, data_spix)];
}
#if SPIFFS_IX_MAP
}
#endif
// all remaining data
u32_t len_to_read = offset + len - cur_offset;
// remaining data in page
len_to_read = MIN(len_to_read, SPIFFS_DATA_PAGE_SIZE(fs) - (cur_offset % SPIFFS_DATA_PAGE_SIZE(fs)));
// remaining data in file
len_to_read = MIN(len_to_read, fd->size - cur_offset);
SPIFFS_DBG("read: offset:"_SPIPRIi" rd:"_SPIPRIi" data spix:"_SPIPRIsp" is data_pix:"_SPIPRIpg" addr:"_SPIPRIad"\n", cur_offset, len_to_read, data_spix, data_pix,
(u32_t)(SPIFFS_PAGE_TO_PADDR(fs, data_pix) + sizeof(spiffs_page_header) + (cur_offset % SPIFFS_DATA_PAGE_SIZE(fs))));
if (len_to_read <= 0) {
res = SPIFFS_ERR_END_OF_OBJECT;
break;
}
res = spiffs_page_data_check(fs, fd, data_pix, data_spix);
SPIFFS_CHECK_RES(res);
res = _spiffs_rd(
fs, SPIFFS_OP_T_OBJ_DA | SPIFFS_OP_C_READ,
fd->file_nbr,
SPIFFS_PAGE_TO_PADDR(fs, data_pix) + sizeof(spiffs_page_header) + (cur_offset % SPIFFS_DATA_PAGE_SIZE(fs)),
len_to_read,
dst);
SPIFFS_CHECK_RES(res);
dst += len_to_read;
cur_offset += len_to_read;
fd->offset = cur_offset;
data_spix++;
}
return res;
}
#if !SPIFFS_READ_ONLY
typedef struct {
spiffs_obj_id min_obj_id;
spiffs_obj_id max_obj_id;
u32_t compaction;
const u8_t *conflicting_name;
} spiffs_free_obj_id_state;
static s32_t spiffs_obj_lu_find_free_obj_id_bitmap_v(spiffs *fs, spiffs_obj_id id, spiffs_block_ix bix, int ix_entry,
const void *user_const_p, void *user_var_p) {
if (id != SPIFFS_OBJ_ID_FREE && id != SPIFFS_OBJ_ID_DELETED) {
spiffs_obj_id min_obj_id = *((spiffs_obj_id*)user_var_p);
const u8_t *conflicting_name = (const u8_t*)user_const_p;
// if conflicting name parameter is given, also check if this name is found in object index hdrs
if (conflicting_name && (id & SPIFFS_OBJ_ID_IX_FLAG)) {
spiffs_page_ix pix = SPIFFS_OBJ_LOOKUP_ENTRY_TO_PIX(fs, bix, ix_entry);
int res;
spiffs_page_object_ix_header objix_hdr;
res = _spiffs_rd(fs, SPIFFS_OP_T_OBJ_LU2 | SPIFFS_OP_C_READ,
0, SPIFFS_PAGE_TO_PADDR(fs, pix), sizeof(spiffs_page_object_ix_header), (u8_t *)&objix_hdr);
SPIFFS_CHECK_RES(res);
if (objix_hdr.p_hdr.span_ix == 0 &&
(objix_hdr.p_hdr.flags & (SPIFFS_PH_FLAG_DELET | SPIFFS_PH_FLAG_FINAL | SPIFFS_PH_FLAG_IXDELE)) ==
(SPIFFS_PH_FLAG_DELET | SPIFFS_PH_FLAG_IXDELE)) {
if (strcmp((const char*)user_const_p, (char*)objix_hdr.name) == 0) {
return SPIFFS_ERR_CONFLICTING_NAME;
}
}
}
id &= ~SPIFFS_OBJ_ID_IX_FLAG;
u32_t bit_ix = (id-min_obj_id) & 7;
int byte_ix = (id-min_obj_id) >> 3;
if (byte_ix >= 0 && (u32_t)byte_ix < SPIFFS_CFG_LOG_PAGE_SZ(fs)) {
fs->work[byte_ix] |= (1<<bit_ix);
}
}
return SPIFFS_VIS_COUNTINUE;
}
static s32_t spiffs_obj_lu_find_free_obj_id_compact_v(spiffs *fs, spiffs_obj_id id, spiffs_block_ix bix, int ix_entry,
const void *user_const_p, void *user_var_p) {
(void)user_var_p;
if (id != SPIFFS_OBJ_ID_FREE && id != SPIFFS_OBJ_ID_DELETED && (id & SPIFFS_OBJ_ID_IX_FLAG)) {
s32_t res;
const spiffs_free_obj_id_state *state = (const spiffs_free_obj_id_state*)user_const_p;
spiffs_page_object_ix_header objix_hdr;
res = _spiffs_rd(fs, SPIFFS_OP_T_OBJ_LU2 | SPIFFS_OP_C_READ,
0, SPIFFS_OBJ_LOOKUP_ENTRY_TO_PADDR(fs, bix, ix_entry), sizeof(spiffs_page_object_ix_header), (u8_t*)&objix_hdr);
if (res == SPIFFS_OK && objix_hdr.p_hdr.span_ix == 0 &&
((objix_hdr.p_hdr.flags & (SPIFFS_PH_FLAG_INDEX | SPIFFS_PH_FLAG_FINAL | SPIFFS_PH_FLAG_DELET)) ==
(SPIFFS_PH_FLAG_DELET))) {
// ok object look up entry
if (state->conflicting_name && strcmp((const char *)state->conflicting_name, (char *)objix_hdr.name) == 0) {
return SPIFFS_ERR_CONFLICTING_NAME;
}
id &= ~SPIFFS_OBJ_ID_IX_FLAG;
if (id >= state->min_obj_id && id <= state->max_obj_id) {
u8_t *map = (u8_t *)fs->work;
int ix = (id - state->min_obj_id) / state->compaction;
//SPIFFS_DBG("free_obj_id: add ix "_SPIPRIi" for id "_SPIPRIid" min"_SPIPRIid" max"_SPIPRIid" comp:"_SPIPRIi"\n", ix, id, state->min_obj_id, state->max_obj_id, state->compaction);
map[ix]++;
}
}
}
return SPIFFS_VIS_COUNTINUE;
}
// Scans thru all object lookup for object index header pages. If total possible number of
// object ids cannot fit into a work buffer, these are grouped. When a group containing free
// object ids is found, the object lu is again scanned for object ids within group and bitmasked.
// Finally, the bitmask is searched for a free id
s32_t spiffs_obj_lu_find_free_obj_id(spiffs *fs, spiffs_obj_id *obj_id, const u8_t *conflicting_name) {
s32_t res = SPIFFS_OK;
u32_t max_objects = (fs->block_count * SPIFFS_OBJ_LOOKUP_MAX_ENTRIES(fs)) / 2;
spiffs_free_obj_id_state state;
spiffs_obj_id free_obj_id = SPIFFS_OBJ_ID_FREE;
state.min_obj_id = 1;
state.max_obj_id = max_objects + 1;
if (state.max_obj_id & SPIFFS_OBJ_ID_IX_FLAG) {
state.max_obj_id = ((spiffs_obj_id)-1) & ~SPIFFS_OBJ_ID_IX_FLAG;
}
state.compaction = 0;
state.conflicting_name = conflicting_name;
while (res == SPIFFS_OK && free_obj_id == SPIFFS_OBJ_ID_FREE) {
if (state.max_obj_id - state.min_obj_id <= (spiffs_obj_id)SPIFFS_CFG_LOG_PAGE_SZ(fs)*8) {
// possible to represent in bitmap
u32_t i, j;
SPIFFS_DBG("free_obj_id: BITM min:"_SPIPRIid" max:"_SPIPRIid"\n", state.min_obj_id, state.max_obj_id);
memset(fs->work, 0, SPIFFS_CFG_LOG_PAGE_SZ(fs));
res = spiffs_obj_lu_find_entry_visitor(fs, 0, 0, 0, 0, spiffs_obj_lu_find_free_obj_id_bitmap_v,
conflicting_name, &state.min_obj_id, 0, 0);
if (res == SPIFFS_VIS_END) res = SPIFFS_OK;
SPIFFS_CHECK_RES(res);
// traverse bitmask until found free obj_id
for (i = 0; i < SPIFFS_CFG_LOG_PAGE_SZ(fs); i++) {
u8_t mask = fs->work[i];
if (mask == 0xff) {
continue;
}
for (j = 0; j < 8; j++) {
if ((mask & (1<<j)) == 0) {
*obj_id = (i<<3)+j+state.min_obj_id;
return SPIFFS_OK;
}
}
}
return SPIFFS_ERR_FULL;
} else {
// not possible to represent all ids in range in a bitmap, compact and count
if (state.compaction != 0) {
// select element in compacted table, decrease range and recompact
u32_t i, min_i = 0;
u8_t *map = (u8_t *)fs->work;
u8_t min_count = 0xff;
for (i = 0; i < SPIFFS_CFG_LOG_PAGE_SZ(fs)/sizeof(u8_t); i++) {
if (map[i] < min_count) {
min_count = map[i];
min_i = i;
if (min_count == 0) {
break;
}
}
}
if (min_count == state.compaction) {
// there are no free objids!
SPIFFS_DBG("free_obj_id: compacted table is full\n");
return SPIFFS_ERR_FULL;
}
SPIFFS_DBG("free_obj_id: COMP select index:"_SPIPRIi" min_count:"_SPIPRIi" min:"_SPIPRIid" max:"_SPIPRIid" compact:"_SPIPRIi"\n", min_i, min_count, state.min_obj_id, state.max_obj_id, state.compaction);
if (min_count == 0) {
// no id in this range, skip compacting and use directly
*obj_id = min_i * state.compaction + state.min_obj_id;
return SPIFFS_OK;
} else {
SPIFFS_DBG("free_obj_id: COMP SEL chunk:"_SPIPRIi" min:"_SPIPRIid" -> "_SPIPRIid"\n", state.compaction, state.min_obj_id, state.min_obj_id + min_i * state.compaction);
state.min_obj_id += min_i * state.compaction;
state.max_obj_id = state.min_obj_id + state.compaction;
// decrease compaction
}
if ((state.max_obj_id - state.min_obj_id <= (spiffs_obj_id)SPIFFS_CFG_LOG_PAGE_SZ(fs)*8)) {
// no need for compacting, use bitmap
continue;
}
}
// in a work memory of log_page_size bytes, we may fit in log_page_size ids
// todo what if compaction is > 255 - then we cannot fit it in a byte
state.compaction = (state.max_obj_id-state.min_obj_id) / ((SPIFFS_CFG_LOG_PAGE_SZ(fs) / sizeof(u8_t)));
SPIFFS_DBG("free_obj_id: COMP min:"_SPIPRIid" max:"_SPIPRIid" compact:"_SPIPRIi"\n", state.min_obj_id, state.max_obj_id, state.compaction);
memset(fs->work, 0, SPIFFS_CFG_LOG_PAGE_SZ(fs));
res = spiffs_obj_lu_find_entry_visitor(fs, 0, 0, 0, 0, spiffs_obj_lu_find_free_obj_id_compact_v, &state, 0, 0, 0);
if (res == SPIFFS_VIS_END) res = SPIFFS_OK;
SPIFFS_CHECK_RES(res);
state.conflicting_name = 0; // searched for conflicting name once, no need to do it again
}
}
return res;
}
#endif // !SPIFFS_READ_ONLY
#if SPIFFS_TEMPORAL_FD_CACHE
// djb2 hash
static u32_t spiffs_hash(spiffs *fs, const u8_t *name) {
(void)fs;
u32_t hash = 5381;
u8_t c;
int i = 0;
while ((c = name[i++]) && i < SPIFFS_OBJ_NAME_LEN) {
hash = (hash * 33) ^ c;
}
return hash;
}
#endif
s32_t spiffs_fd_find_new(spiffs *fs, spiffs_fd **fd, const char *name) {
#if SPIFFS_TEMPORAL_FD_CACHE
u32_t i;
u16_t min_score = 0xffff;
u32_t cand_ix = (u32_t)-1;
u32_t name_hash = name ? spiffs_hash(fs, (const u8_t *)name) : 0;
spiffs_fd *fds = (spiffs_fd *)fs->fd_space;
if (name) {
// first, decrease score of all closed descriptors
for (i = 0; i < fs->fd_count; i++) {
spiffs_fd *cur_fd = &fds[i];
if (cur_fd->file_nbr == 0) {
if (cur_fd->score > 1) { // score == 0 indicates never used fd
cur_fd->score--;
}
}
}
}
// find the free fd with least score or name match
for (i = 0; i < fs->fd_count; i++) {
spiffs_fd *cur_fd = &fds[i];
if (cur_fd->file_nbr == 0) {
if (name && cur_fd->name_hash == name_hash) {
cand_ix = i;
break;
}
if (cur_fd->score < min_score) {
min_score = cur_fd->score;
cand_ix = i;
}
}
}
if (cand_ix != (u32_t)-1) {
spiffs_fd *cur_fd = &fds[cand_ix];
if (name) {
if (cur_fd->name_hash == name_hash && cur_fd->score > 0) {
// opened an fd with same name hash, assume same file
// set search point to saved obj index page and hope we have a correct match directly
// when start searching - if not, we will just keep searching until it is found
fs->cursor_block_ix = SPIFFS_BLOCK_FOR_PAGE(fs, cur_fd->objix_hdr_pix);
fs->cursor_obj_lu_entry = SPIFFS_OBJ_LOOKUP_ENTRY_FOR_PAGE(fs, cur_fd->objix_hdr_pix);
// update score
if (cur_fd->score < 0xffff-SPIFFS_TEMPORAL_CACHE_HIT_SCORE) {
cur_fd->score += SPIFFS_TEMPORAL_CACHE_HIT_SCORE;
} else {
cur_fd->score = 0xffff;
}
} else {
// no hash hit, restore this fd to initial state
cur_fd->score = SPIFFS_TEMPORAL_CACHE_HIT_SCORE;
cur_fd->name_hash = name_hash;
}
}
cur_fd->file_nbr = cand_ix+1;
*fd = cur_fd;
return SPIFFS_OK;
} else {
return SPIFFS_ERR_OUT_OF_FILE_DESCS;
}
#else
(void)name;
u32_t i;
spiffs_fd *fds = (spiffs_fd *)fs->fd_space;
for (i = 0; i < fs->fd_count; i++) {
spiffs_fd *cur_fd = &fds[i];
if (cur_fd->file_nbr == 0) {
cur_fd->file_nbr = i+1;
*fd = cur_fd;
return SPIFFS_OK;
}
}
return SPIFFS_ERR_OUT_OF_FILE_DESCS;
#endif
}
s32_t spiffs_fd_return(spiffs *fs, spiffs_file f) {
if (f <= 0 || f > (s16_t)fs->fd_count) {
return SPIFFS_ERR_BAD_DESCRIPTOR;
}
spiffs_fd *fds = (spiffs_fd *)fs->fd_space;
spiffs_fd *fd = &fds[f-1];
if (fd->file_nbr == 0) {
return SPIFFS_ERR_FILE_CLOSED;
}
fd->file_nbr = 0;
#if SPIFFS_IX_MAP
fd->ix_map = 0;
#endif
return SPIFFS_OK;
}
s32_t spiffs_fd_get(spiffs *fs, spiffs_file f, spiffs_fd **fd) {
if (f <= 0 || f > (s16_t)fs->fd_count) {
return SPIFFS_ERR_BAD_DESCRIPTOR;
}
spiffs_fd *fds = (spiffs_fd *)fs->fd_space;
*fd = &fds[f-1];
if ((*fd)->file_nbr == 0) {
return SPIFFS_ERR_FILE_CLOSED;
}
return SPIFFS_OK;
}
#if SPIFFS_TEMPORAL_FD_CACHE
void spiffs_fd_temporal_cache_rehash(
spiffs *fs,
const char *old_path,
const char *new_path) {
u32_t i;
u32_t old_hash = spiffs_hash(fs, (const u8_t *)old_path);
u32_t new_hash = spiffs_hash(fs, (const u8_t *)new_path);
spiffs_fd *fds = (spiffs_fd *)fs->fd_space;
for (i = 0; i < fs->fd_count; i++) {
spiffs_fd *cur_fd = &fds[i];
if (cur_fd->score > 0 && cur_fd->name_hash == old_hash) {
cur_fd->name_hash = new_hash;
}
}
}
#endif
| 2.21875 | 2 |
2024-11-18T22:10:58.342441+00:00 | 2023-07-10T16:06:35 | b33e247c0b08cd847309f40b10faf5b3a48291b7 | {
"blob_id": "b33e247c0b08cd847309f40b10faf5b3a48291b7",
"branch_name": "refs/heads/master",
"committer_date": "2023-07-10T16:06:35",
"content_id": "600756fdf7c00f26adb38ebd9e143b1d9a56ba02",
"detected_licenses": [
"ISC",
"MIT"
],
"directory_id": "d2e0fb3fdad7fc2cb70894591d358f40d8db13d2",
"extension": "c",
"filename": "ubsan.c",
"fork_events_count": 15,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 55073371,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 7309,
"license": "ISC,MIT",
"license_type": "permissive",
"path": "/libc/src/misc/ubsan.c",
"provenance": "stackv2-0072.json.gz:36298",
"repo_name": "dennis95/dennix",
"revision_date": "2023-07-10T16:06:35",
"revision_id": "f898bb2d27346f6257df1650a002ee929e66e7fa",
"snapshot_id": "54c568485862a0799664033eb0717abb028d3924",
"src_encoding": "UTF-8",
"star_events_count": 168,
"url": "https://raw.githubusercontent.com/dennis95/dennix/f898bb2d27346f6257df1650a002ee929e66e7fa/libc/src/misc/ubsan.c",
"visit_date": "2023-08-17T06:54:17.274650"
} | stackv2 | /* Copyright (c) 2022 Dennis Wölfing
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
/* libc/src/misc/ubsan.c
* Undefined behavior sanitizer.
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdnoreturn.h>
#define ABORT_ALIAS(name) \
extern __typeof(name) name ## _abort __attribute__((alias(#name)))
struct SourceLocation {
const char* filename;
uint32_t line;
uint32_t column;
};
static noreturn void handleUndefinedBahavior(
const struct SourceLocation* location, const char* message) {
const char* filename = location->filename;
if (!filename) filename = "(unknown)";
#ifdef __is_dennix_libc
fprintf(stderr, "Undefined behavior at %s:%w32u:%w32u: %s\n",
location->filename, location->line, location->column, message);
abort();
#else
extern noreturn void __handleUbsan(const char*, uint32_t, uint32_t,
const char*);
__handleUbsan(filename, location->line, location->column, message);
#endif
}
struct TypeMismatchData {
struct SourceLocation loc;
const void* type;
unsigned char logAlignment;
unsigned char typeCheckKind;
};
void __ubsan_handle_type_mismatch_v1(struct TypeMismatchData* data,
uintptr_t ptr) {
const char* message = "type mismatch";
if (!ptr) {
message = "null pointer access";
} else if (ptr & (data->logAlignment - 1)) {
message = "misaligned memory access";
}
handleUndefinedBahavior(&data->loc, message);
}
ABORT_ALIAS(__ubsan_handle_type_mismatch_v1);
struct OverflowData {
struct SourceLocation loc;
const void* type;
};
void __ubsan_handle_add_overflow(struct OverflowData* data, uintptr_t lhs,
uintptr_t rhs) {
(void) lhs; (void) rhs;
handleUndefinedBahavior(&data->loc, "addition overflow");
}
ABORT_ALIAS(__ubsan_handle_add_overflow);
void __ubsan_handle_sub_overflow(struct OverflowData* data, uintptr_t lhs,
uintptr_t rhs) {
(void) lhs; (void) rhs;
handleUndefinedBahavior(&data->loc, "subtraction overflow");
}
ABORT_ALIAS(__ubsan_handle_sub_overflow);
void __ubsan_handle_mul_overflow(struct OverflowData* data, uintptr_t lhs,
uintptr_t rhs) {
(void) lhs; (void) rhs;
handleUndefinedBahavior(&data->loc, "multiplication overflow");
}
ABORT_ALIAS(__ubsan_handle_mul_overflow);
void __ubsan_handle_negate_overflow(struct OverflowData* data, uintptr_t val) {
(void) val;
handleUndefinedBahavior(&data->loc, "negation overflow");
}
ABORT_ALIAS(__ubsan_handle_negate_overflow);
void __ubsan_handle_divrem_overflow(struct OverflowData* data, uintptr_t lhs,
uintptr_t rhs) {
(void) lhs; (void) rhs;
handleUndefinedBahavior(&data->loc, "division remainder overflow");
}
ABORT_ALIAS(__ubsan_handle_divrem_overflow);
struct ShiftOutOfBoundsData {
struct SourceLocation loc;
const void* lhsType;
const void* rhsType;
};
void __ubsan_handle_shift_out_of_bounds(struct ShiftOutOfBoundsData* data,
uintptr_t lhs, uintptr_t rhs) {
(void) lhs; (void) rhs;
handleUndefinedBahavior(&data->loc, "shift out of bounds");
}
ABORT_ALIAS(__ubsan_handle_shift_out_of_bounds);
struct OutOfBoundsData {
struct SourceLocation loc;
const void* arrayType;
const void* indexType;
};
void __ubsan_handle_out_of_bounds(struct OutOfBoundsData* data,
uintptr_t index) {
(void) index;
handleUndefinedBahavior(&data->loc, "Array access out of bounds");
}
ABORT_ALIAS(__ubsan_handle_out_of_bounds);
struct UnreachableData {
struct SourceLocation loc;
};
void __ubsan_handle_builtin_unreachable(struct UnreachableData* data) {
handleUndefinedBahavior(&data->loc, "unreachable code reached");
}
void __ubsan_handle_missing_return(struct UnreachableData* data) {
handleUndefinedBahavior(&data->loc,
"reached end of function without return");
}
struct VlaBoundData {
struct SourceLocation loc;
const void* type;
};
void __ubsan_handle_vla_bound_not_positive(struct VlaBoundData* data,
uintptr_t bound) {
(void) bound;
handleUndefinedBahavior(&data->loc,
"variable length array bound not positive");
}
ABORT_ALIAS(__ubsan_handle_vla_bound_not_positive);
struct FloatCastOverflowDataV2 {
struct SourceLocation loc;
const void* fromType;
const void* toType;
};
void __ubsan_handle_float_cast_overflow(struct FloatCastOverflowDataV2* data,
uintptr_t from) {
(void) from;
handleUndefinedBahavior(&data->loc, "float cast overflow");
}
ABORT_ALIAS(__ubsan_handle_float_cast_overflow);
struct InvalidValueData {
struct SourceLocation loc;
const void* type;
};
void __ubsan_handle_load_invalid_value(struct InvalidValueData* data,
uintptr_t val) {
(void) val;
handleUndefinedBahavior(&data->loc, "invalid value loaded");
}
ABORT_ALIAS(__ubsan_handle_load_invalid_value);
struct InvalidBuiltinData {
struct SourceLocation loc;
unsigned char kind;
};
void __ubsan_handle_invalid_builtin(struct InvalidBuiltinData* data) {
handleUndefinedBahavior(&data->loc, "invalid value passed to builtin");
}
ABORT_ALIAS(__ubsan_handle_invalid_builtin);
struct NonNullReturnData {
struct SourceLocation attrLoc;
};
void __ubsan_handle_nonnull_return_v1(struct NonNullReturnData* data,
struct SourceLocation* locPtr) {
(void) data;
handleUndefinedBahavior(locPtr, "Nonnull function returned null");
}
ABORT_ALIAS(__ubsan_handle_nonnull_return_v1);
struct NonNullArgData {
struct SourceLocation loc;
struct SourceLocation attrLoc;
int argIndex;
};
void __ubsan_handle_nonnull_arg(struct NonNullArgData* data) {
handleUndefinedBahavior(&data->loc, "Nonnull argument was null");
}
ABORT_ALIAS(__ubsan_handle_nonnull_arg);
struct PointerOverflowData {
struct SourceLocation loc;
};
void __ubsan_handle_pointer_overflow(struct PointerOverflowData* data,
uintptr_t base, uintptr_t result) {
(void) base; (void) result;
handleUndefinedBahavior(&data->loc, "pointer overflow");
}
ABORT_ALIAS(__ubsan_handle_pointer_overflow);
struct DynamicTypeCacheMissData {
struct SourceLocation loc;
const void* type;
void* typeInfo;
unsigned char typeCheckKind;
};
void __ubsan_handle_dynamic_type_cache_miss(
struct DynamicTypeCacheMissData* data, uintptr_t ptr, uintptr_t hash) {
(void) data; (void) ptr; (void) hash;
// Ubsan expects us to perform dynamic type checking to check whether this
// is really undefined behavior. We do not implement this check and thus
// ignore this call.
}
ABORT_ALIAS(__ubsan_handle_dynamic_type_cache_miss);
| 2.171875 | 2 |
2024-11-18T22:10:58.425816+00:00 | 2018-12-22T12:39:44 | de968b5b1370dcc143d1f648a7642aa9852aae1b | {
"blob_id": "de968b5b1370dcc143d1f648a7642aa9852aae1b",
"branch_name": "refs/heads/master",
"committer_date": "2018-12-22T12:39:44",
"content_id": "cb4a6c1258f217d556cb2f32fefb72b2c8429044",
"detected_licenses": [
"MIT"
],
"directory_id": "7388979e0c7f7a4d29dd23114c847c1fb2e9e56c",
"extension": "c",
"filename": "aac.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 162809530,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4201,
"license": "MIT",
"license_type": "permissive",
"path": "/aac.c",
"provenance": "stackv2-0072.json.gz:36428",
"repo_name": "sipirsipirmin/ParallelArtificialAnt",
"revision_date": "2018-12-22T12:39:44",
"revision_id": "f3fa0f6135bc96a83882df1ad0a3558b04808f67",
"snapshot_id": "b6d2368f54f7838be2e1276c9bc4ecab20b20a3f",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/sipirsipirmin/ParallelArtificialAnt/f3fa0f6135bc96a83882df1ad0a3558b04808f67/aac.c",
"visit_date": "2020-04-12T23:07:44.577938"
} | stackv2 | #include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include<math.h>
#include<unistd.h>
#include<omp.h>
#define NODE_SAYISI 5
#define HEDEF_DUGUM 4
#define BASLANGIC_DURUMU 0
#define FEROMON_ESIGI 1
#define FEROMON_SALGI_MIKTARI 0.2
#define KARINCA_SAYISI 100
#define MAX_YOL_UZUNLUGU 30
#define TRUE 1
#define FALSE 0
#define NO_WAY 999
#define NO_CHOOSEN_WAY 99
_Bool komsuluk_matrisi[NODE_SAYISI][NODE_SAYISI];
int agirlik_matrisi[NODE_SAYISI][NODE_SAYISI];
float feromon_matrisi[NODE_SAYISI][NODE_SAYISI];
int yol[KARINCA_SAYISI][MAX_YOL_UZUNLUGU];
void create_graph(){
for(int i=0;i<NODE_SAYISI;i++)
for(int j=0; j<NODE_SAYISI; j++)
feromon_matrisi[i][j] = 0;
komsuluk_matrisi[0][1] = TRUE;
agirlik_matrisi[0][1] = 5;
komsuluk_matrisi[0][2] = TRUE;
agirlik_matrisi[0][2] = 6;
komsuluk_matrisi[1][3] = TRUE;
agirlik_matrisi[1][3] = 5;
komsuluk_matrisi[2][1] = TRUE;
agirlik_matrisi[2][1] = 2;
komsuluk_matrisi[3][4] = TRUE;
agirlik_matrisi[3][4] = 10;
komsuluk_matrisi[2][3] = TRUE;
agirlik_matrisi[2][3] = 1;
komsuluk_matrisi[1][2] = TRUE;
agirlik_matrisi[1][2] = 2;
}
void print_feromon_matrisi(){
for (int i = 0; i < NODE_SAYISI; i++)
for(int j = 0; j<NODE_SAYISI; j++)
printf("%d'den %d'ye: %f\n", i,j,feromon_matrisi[i][j]);
}
void print_ant_way(int karinca_no){
printf("karinca no: %d, yol: ", karinca_no);
int temp_uzunluk = 0;
for(int i = 0; i<MAX_YOL_UZUNLUGU; i++){
if(yol[karinca_no][i+1] != NO_WAY){
printf(" %d ->", yol[karinca_no][i]);
temp_uzunluk += agirlik_matrisi[yol[karinca_no][i]][yol[karinca_no][i+1]];
}else{
printf("%d, toplam uzunluk: %d\n", yol[karinca_no][i], temp_uzunluk);
break;
}
}
}
int find_possible_ways_and_get_counts(int durum, int *gidilebilecek_olasi_yollar){
int temp_sayac = 0;
for(int i = 0; i < NODE_SAYISI; i++){
if(komsuluk_matrisi[durum][i]){
gidilebilecek_olasi_yollar[temp_sayac] = i;
temp_sayac++;
}
}
return temp_sayac;
}
int smell_ways_and_get_feromon(int durum, int *gidilebilecek_olasi_yollar, int temp_sayac){
int secilen_yol = NO_CHOOSEN_WAY;
for(int i = 0; i<temp_sayac; i++){
if(feromon_matrisi[durum][gidilebilecek_olasi_yollar[i]] > FEROMON_ESIGI){
secilen_yol = gidilebilecek_olasi_yollar[i];
// printf("ferr seçildi, %d->%d\n", durum,secilen_yol);
}
}
return secilen_yol;
}
int get_random_way(int *gidilebilecek_olasi_yollar, int temp_sayac){
sleep(0.2); // for more randomizing
return gidilebilecek_olasi_yollar[abs(rand()%temp_sayac)];
}
int main(int argc, char const *argv[]) {
create_graph();
int durum;
srand(time(NULL));
int temp_sayac;
int gidilebilecek_olasi_yollar[NODE_SAYISI];
int iterasyon_no;
int secilen_yol;
#pragma omp parallel for num_threads(4) private(durum, iterasyon_no, secilen_yol, temp_sayac, gidilebilecek_olasi_yollar)
for(int karinca_no = 0; karinca_no < KARINCA_SAYISI; karinca_no++){
durum = BASLANGIC_DURUMU;
yol[karinca_no][0] = durum;
iterasyon_no = 1; // Başlangıç durumuna gelmiş olması da bir iterasyon
secilen_yol = NO_CHOOSEN_WAY;
for(int i = 1; i<MAX_YOL_UZUNLUGU; i++)
yol[karinca_no][i] = NO_WAY;
while(durum != HEDEF_DUGUM && iterasyon_no < MAX_YOL_UZUNLUGU){
temp_sayac = find_possible_ways_and_get_counts(durum, gidilebilecek_olasi_yollar);
secilen_yol = smell_ways_and_get_feromon(durum, gidilebilecek_olasi_yollar, temp_sayac);
if(secilen_yol == NO_CHOOSEN_WAY)
secilen_yol = get_random_way(gidilebilecek_olasi_yollar, temp_sayac);
#pragma omp critical
feromon_matrisi[durum][secilen_yol] += FEROMON_SALGI_MIKTARI/agirlik_matrisi[durum][secilen_yol];
durum = secilen_yol;
yol[karinca_no][iterasyon_no] = secilen_yol;
iterasyon_no++;
}
}
for(int i=0; i<KARINCA_SAYISI;i++)
print_ant_way(i);
return 0;
}
| 2.03125 | 2 |
2024-11-18T22:10:58.560361+00:00 | 2020-05-24T13:55:07 | 68f407c8c038817f337ceccad8dfcc654c6611d6 | {
"blob_id": "68f407c8c038817f337ceccad8dfcc654c6611d6",
"branch_name": "refs/heads/master",
"committer_date": "2020-05-24T14:05:08",
"content_id": "0266978d871e0dd66df2a987b00ef2360833f52e",
"detected_licenses": [
"ISC"
],
"directory_id": "c236aebc30a3a9128da2a18a441e4c8d33e4d2ae",
"extension": "c",
"filename": "vode_report.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": 3199,
"license": "ISC",
"license_type": "permissive",
"path": "/modules/vode/vode_report.c",
"provenance": "stackv2-0072.json.gz:36686",
"repo_name": "curiousTauseef/mpt-solver",
"revision_date": "2020-05-24T13:55:07",
"revision_id": "8a3ca31b12b96c3184ba4bc6ad607ed01cc1ea73",
"snapshot_id": "19cb57e58cc172b8f153c4032886df388f420092",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/curiousTauseef/mpt-solver/8a3ca31b12b96c3184ba4bc6ad607ed01cc1ea73/modules/vode/vode_report.c",
"visit_date": "2022-08-09T04:04:41.518169"
} | stackv2 | /*!
* prepare/finalize VODE solver,
* get status information.
*/
#include "vode.h"
#include "module_functions.h"
extern int mpt_vode_report(const MPT_SOLVER_STRUCT(vode) *vd, int show, MPT_TYPE(property_handler) out, void *usr)
{
MPT_STRUCT(property) pr;
size_t li = vd->iwork.iov_len / sizeof(int);
size_t lr = vd->rwork.iov_len / sizeof(double);
int *iwk = vd->iwork.iov_base;
double *rwk = vd->rwork.iov_base;
int line = 0;
if (show & MPT_SOLVER_ENUM(Header)) {
static const uint8_t fmt_ss[] = "ss";
static const uint8_t fmt_band[] = "siis";
struct { const char *type; int32_t ml, mu; const char *jac; } d;
const char *val[2];
pr.name = "method";
pr.desc = MPT_tr("method for solver step");
pr.val.fmt = fmt_ss;
pr.val.ptr = val;
val[0] = (vd->meth == 2) ? "BDF" : "Adams";
val[1] = MPT_tr("saved");
if (!vd->miter || vd->jsv < 0) {
pr.val.fmt = 0;
pr.val.ptr = val[0];
}
out(usr, &pr);
++line;
pr.name = "jacobian";
pr.desc = MPT_tr("type of jacobian");
pr.val.fmt = fmt_ss;
val[0] = "Full";
val[1] = "user";
d.type = "Banded";
if (li > 1) {
d.ml = iwk[0];
d.mu = iwk[1];
} else {
d.ml = d.mu = -1;
}
d.jac = val[1];
switch (vd->miter) {
case 1:
if (vd->jac) {
break;
}
case 2:
val[0] = "full";
val[1] = "numerical";
break;
case 3:
pr.val.fmt = 0;
pr.val.ptr = "diagonal";
break;
case 4:
pr.val.fmt = fmt_band;
if (vd->jac) {
pr.val.ptr = &d;
break;
}
case 5:
d.type = "banded";
d.jac = "numerical";
pr.val.fmt = fmt_band;
pr.val.ptr = &d;
break;
default:
pr.val.fmt = 0;
pr.val.ptr = "none";
}
out(usr, &pr);
++line;
}
if (show & MPT_SOLVER_ENUM(Values)) {
MPT_SOLVER_MODULE_FCN(ivp_values)(&vd->ivp, vd->t, vd->y, MPT_tr("dVode solver state"), out, usr);
}
if (show & MPT_SOLVER_ENUM(Status)) {
pr.name = "t";
pr.desc = MPT_tr("value of independent variable");
if (lr > 12) {
mpt_solver_module_value_double(&pr.val, &rwk[12]);
} else {
mpt_solver_module_value_double(&pr.val, &vd->t);
}
out(usr, &pr);
++line;
}
if (show & (MPT_SOLVER_ENUM(Status) | MPT_SOLVER_ENUM(Report)) && li > 10) {
pr.name = "n";
pr.desc = MPT_tr("integration steps");
mpt_solver_module_value_int(&pr.val, &iwk[10]);
out(usr, &pr);
++line;
}
if (show & MPT_SOLVER_ENUM(Status) && lr > 10) {
pr.name = "h";
pr.desc = MPT_tr("current step size");
mpt_solver_module_value_double(&pr.val, &rwk[10]);
out(usr, &pr);
++line;
}
if ((show & MPT_SOLVER_ENUM(Report)) && li > 11) {
pr.name = "feval";
pr.desc = MPT_tr("f evaluations");
mpt_solver_module_value_int(&pr.val, &iwk[11]);
out(usr, &pr);
++line;
if (li > 12 && iwk[12]) {
pr.name = "jeval";
pr.desc = MPT_tr("jacobian evaluations");
mpt_solver_module_value_int(&pr.val, &iwk[12]);
out(usr, &pr);
++line;
}
if (li > 18 && iwk[18]) {
pr.name = "ludec";
pr.desc = MPT_tr("LU decompositions");
mpt_solver_module_value_int(&pr.val, &iwk[18]);
out(usr, &pr);
++line;
}
if (li > 19 && iwk[19]) {
pr.name = "niter";
pr.desc = MPT_tr("nonlinear (Newton) iterations");
mpt_solver_module_value_int(&pr.val, &iwk[19]);
out(usr, &pr);
++line;
}
}
return line;
}
| 2.078125 | 2 |
2024-11-18T22:10:59.003439+00:00 | 2019-10-07T20:03:15 | 6540f0f9719351c046cea0977aa7b317f3da54fb | {
"blob_id": "6540f0f9719351c046cea0977aa7b317f3da54fb",
"branch_name": "refs/heads/master",
"committer_date": "2019-10-07T20:03:15",
"content_id": "f23e41b32d58d12dd41cbe1a3a730982eed5b35b",
"detected_licenses": [
"MIT"
],
"directory_id": "7c85ea90335facb910a084ad1826b34cdc45361b",
"extension": "c",
"filename": "fscanf.c",
"fork_events_count": 0,
"gha_created_at": "2019-10-03T19:09:47",
"gha_event_created_at": "2019-10-03T19:09:47",
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 212658562,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 345,
"license": "MIT",
"license_type": "permissive",
"path": "/files/read/fscanf.c",
"provenance": "stackv2-0072.json.gz:36942",
"repo_name": "Mauc1201/C",
"revision_date": "2019-10-07T20:03:15",
"revision_id": "f823e46312758b57e10f112b9cba9c11dde3df60",
"snapshot_id": "cd05e8d6d66592d282eac78ea6d38d96b6775380",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Mauc1201/C/f823e46312758b57e10f112b9cba9c11dde3df60/files/read/fscanf.c",
"visit_date": "2020-08-05T18:37:06.888365"
} | stackv2 | /*int fscanf(FILE *fichero, const char *formato, argumento, ...);*/
#include <stdio.h>
int main ( int argc, char **argv )
{
FILE *fp;
char buffer1[100];
char buffer2[100];
fp = fopen ( "../gente.txt", "r" );
fscanf(fp, "%s\n%s" ,buffer1, buffer2);
printf("%s\n%s",buffer1, buffer2);
fclose ( fp );
return 0;
}
| 2.6875 | 3 |
2024-11-18T22:10:59.161962+00:00 | 2013-11-18T23:30:07 | 013efd713be9f26bc5a2a60495de3d370e28b916 | {
"blob_id": "013efd713be9f26bc5a2a60495de3d370e28b916",
"branch_name": "refs/heads/master",
"committer_date": "2013-11-18T23:30:07",
"content_id": "d1c2bd7a62bffa4902a234bb12d1a666d4556472",
"detected_licenses": [
"BSD-3-Clause",
"BSD-2-Clause"
],
"directory_id": "953aa193a15ee0e783ac68c9bf90d7db4d747004",
"extension": "c",
"filename": "module2.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 12580696,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1681,
"license": "BSD-3-Clause,BSD-2-Clause",
"license_type": "permissive",
"path": "/cSnmpCron/modules/module2.c",
"provenance": "stackv2-0072.json.gz:37199",
"repo_name": "hazraa/samples",
"revision_date": "2013-11-18T23:30:07",
"revision_id": "79a8c5392558607f532aff326ca004bb1b2631dd",
"snapshot_id": "95e0f71e2313d0a28ce9cd7ce4d50995f3ef17a6",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/hazraa/samples/79a8c5392558607f532aff326ca004bb1b2631dd/cSnmpCron/modules/module2.c",
"visit_date": "2021-01-19T13:00:02.356359"
} | stackv2 | /*
*
*/
#ifndef _REENTRANT
#define _REENTRANT
#endif
#include <stdio.h>
#include <stdlib.h>
#include <net-snmp/net-snmp-config.h>
#include <net-snmp/net-snmp-includes.h>
#include <module.h>
void printer(config_t *config, joblist_t *job, char *target, char *fred);
int module2_run(char *target, config_t *config, joblist_t *job, taskresult_t *taskresult)
{
FILE *f;
char *localname="testmodule";
unsigned int seed, i;
static unsigned int n=0;
char msg[1024];
if (!target) return(0);
if (!config) return(0);
if (!job) return(0);
seed = time(NULL) % 65535;
srand(seed + n);
n= rand() % 10;
if (! config->logfile) fprintf(stderr, "logfile is null\n");
if (! config->datadir) fprintf(stderr, "datadir is null\n");
fprintf(stderr, " -- [module2_run(), sleep(%d), target=%s, datadir=%s, logfile=%s] --\n",
n,target,
(config->datadir ? config->datadir : "null"),
(config->logfile ? config->logfile : "null"));
taskresult->status=0;
sprintf(msg,"success. target=%s, sleep(%d)", target, n);
strncpy(taskresult->message,strdup(msg), sizeof(taskresult->message)-1);
printer(config, job, target, NULL);
fprintf(stderr, " ----\n");
sleep(n);
return(-1);
}
void printer(config_t *config, joblist_t *job, char *target, char *fred)
{
FILE *f;
char fname[1024];
char fpath[1024];
if (config->datadir && job->prefix) {
sprintf(fpath,"%s/%d", config->datadir, job->timestamp);
sprintf(fname,"%s.%s.log",job->prefix, target);
fprintf(stderr, " -- [outfile=%s/%s] --\n", fpath, fname);
} else
fprintf(stderr, " -- error --\n");
}
| 2.140625 | 2 |
2024-11-18T22:10:59.589748+00:00 | 2012-06-06T08:51:57 | 7d95624006fee639c2f9f53c42b0f72e4e890fd0 | {
"blob_id": "7d95624006fee639c2f9f53c42b0f72e4e890fd0",
"branch_name": "refs/heads/master",
"committer_date": "2012-06-06T08:51:57",
"content_id": "a416ee46dcbf3bbc20056f4c9944877e19fd69ef",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "190d7ec83b1c59f3663bf735059968fa8158ab3f",
"extension": "c",
"filename": "luacontext.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": 1878,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/Source/luacontext.c",
"provenance": "stackv2-0072.json.gz:37458",
"repo_name": "long-nguyen/Dynamo",
"revision_date": "2012-06-06T08:51:57",
"revision_id": "c5214474414e25b775471e6e681a28ae7c33fdc7",
"snapshot_id": "d43f83986da067b4d9033cd3b3fe8917e7c86c03",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/long-nguyen/Dynamo/c5214474414e25b775471e6e681a28ae7c33fdc7/Source/luacontext.c",
"visit_date": "2020-12-25T13:44:50.973756"
} | stackv2 | #include "luacontext.h"
#include "util.h"
#include <string.h>
#include <stdlib.h>
static void luaCtx_destroy(LuaContext_t *aCtx);
Class_t Class_LuaContext = {
"LuaContext",
sizeof(LuaContext_t),
(Obj_destructor_t)&luaCtx_destroy
};
LuaContext_t *luaCtx_createContext()
{
LuaContext_t *out = obj_create_autoreleased(&Class_LuaContext);
out->luaState = lua_open();
luaL_openlibs(out->luaState);
return out;
}
static void luaCtx_destroy(LuaContext_t *aCtx)
{
lua_close(aCtx->luaState);
}
bool luaCtx_pcall(LuaContext_t *aCtx, int nargs, int nresults, int errfunc)
{
int err = lua_pcall(aCtx->luaState, nargs, nresults, errfunc);
if(err) {
dynamo_log("Lua error: %s", (char*)lua_tostring(aCtx->luaState, -1));
lua_pop(aCtx->luaState, 1);
return false;
}
return true;
}
bool luaCtx_executeFile(LuaContext_t *aCtx, const char *aPath)
{
int err = 0;
err = luaL_loadfile(aCtx->luaState, aPath);
if(err) {
dynamo_log("Lua error: %s", (char*)lua_tostring(aCtx->luaState, -1));
lua_pop(aCtx->luaState, 1);
return false;
}
return luaCtx_pcall(aCtx, 0, 0, 0);
}
bool luaCtx_executeString(LuaContext_t *aCtx, const char *aScript)
{
int err = 0;
err = luaL_loadstring(aCtx->luaState, aScript);
if(err) {
dynamo_log("Lua error: %s", (char*)lua_tostring(aCtx->luaState, -1));
lua_pop(aCtx->luaState, 1);
return false;
}
return luaCtx_pcall(aCtx, 0, 0, 0);
}
bool luaCtx_addSearchPath(LuaContext_t *aCtx, const char *aPath)
{
lua_State *ls = aCtx->luaState;
lua_getglobal(ls, "package");
lua_getfield(ls, -1, "path");
lua_pushfstring(ls, ";%s/?.lua;%s/?/init.lua", aPath, aPath);
lua_concat(ls, 2);
lua_setfield(ls, -2, "path");
lua_pop(ls, 1);
return true;
}
| 2.09375 | 2 |
2024-11-18T22:10:59.712189+00:00 | 2019-03-18T02:14:55 | 38c4966841d037687562313d297d155a9bf53c8f | {
"blob_id": "38c4966841d037687562313d297d155a9bf53c8f",
"branch_name": "refs/heads/master",
"committer_date": "2019-03-18T02:14:55",
"content_id": "8606f8dbf036ffbfa556120b5f6e2a8561e900b7",
"detected_licenses": [
"CC0-1.0"
],
"directory_id": "81ee58d95bc3e14c0b9f10e4ec13bc1d2fd9972f",
"extension": "h",
"filename": "Mat33.h",
"fork_events_count": 0,
"gha_created_at": "2019-03-18T02:13:13",
"gha_event_created_at": "2019-03-18T02:13:13",
"gha_language": null,
"gha_license_id": "NOASSERTION",
"github_id": 176188401,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 645,
"license": "CC0-1.0",
"license_type": "permissive",
"path": "/Core/Mat33.h",
"provenance": "stackv2-0072.json.gz:37587",
"repo_name": "ericoporto/fw-public",
"revision_date": "2019-03-18T02:14:55",
"revision_id": "90bd713cf40604118176883e5aef3c067373bb87",
"snapshot_id": "a49af2fed9cb63e5af628cc7a68f60ce7058eff4",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ericoporto/fw-public/90bd713cf40604118176883e5aef3c067373bb87/Core/Mat33.h",
"visit_date": "2020-04-29T14:10:10.766225"
} | stackv2 | #ifndef _MAT_3X3_H_
#define _MAT_3X3_H_
#include "CoreHelpers.h"
#include "Vec3.h"
struct Mat33
{
Mat33();
Mat33(const float srcData[9]);
Mat33(const float srcData[3][3]);
void InitZero();
void InitIdentity();
float Determinant() const;
static Mat33 Inverse(const Mat33 & src);
static Mat33 RotationAroundAxisL(Vec3 N, float cosA, float sinA);
static Mat33 RotationAroundAxisR(Vec3 N, float cosA, float sinA);
static Mat33 Transpose(const Mat33 & src);
float m_data[9];
};
inline Vec3 operator*(const Mat33 & lhs, const Vec3 & rhs);
inline Mat33 operator*(const Mat33 & lhs, const Mat33 & rhs);
#include "Mat33.inl"
#endif
| 2 | 2 |
2024-11-18T22:10:59.939598+00:00 | 2020-11-23T09:09:37 | 748189ef3f4e90b22915392f53a72e2cfc6ce970 | {
"blob_id": "748189ef3f4e90b22915392f53a72e2cfc6ce970",
"branch_name": "refs/heads/main",
"committer_date": "2020-11-23T09:13:33",
"content_id": "4f7510fdf77f7fb5703b0432931a74145ae2f252",
"detected_licenses": [
"MIT"
],
"directory_id": "713f07b9417703ea4eb8d20cfb6472f526fdcf43",
"extension": "c",
"filename": "overflow2.c",
"fork_events_count": 0,
"gha_created_at": "2020-11-03T06:06:04",
"gha_event_created_at": "2020-11-23T09:13:36",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 309590158,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 903,
"license": "MIT",
"license_type": "permissive",
"path": "/test2_overflow/overflow2.c",
"provenance": "stackv2-0072.json.gz:37716",
"repo_name": "cowerman/expolit_course",
"revision_date": "2020-11-23T09:09:37",
"revision_id": "56c1c01b245939e45237c193d40ed959367b386e",
"snapshot_id": "22d4408492c532f3ff0f42d3c5d3d5536b5fea17",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/cowerman/expolit_course/56c1c01b245939e45237c193d40ed959367b386e/test2_overflow/overflow2.c",
"visit_date": "2023-01-15T11:00:48.437685"
} | stackv2 | /*************************************************************************
> File Name: overflow2.c
> Author:
> Mail:
> Created Time: Wed 02 Sep 2020 11:28:28 PM CST
************************************************************************/
/* Stack overflow the internel flag variable */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define PASSWD "1234567"
enum {
false,
true,
};
void usage()
{
printf("Usage: ./a.out passwd\n");
}
int verify_passwd(char *passwd_str)
{
char auther = false;
char buff[8];
if(!strcmp(PASSWD, passwd_str)) {
auther = true;
}
strcpy(buff, passwd_str);
return auther;
}
int main(int argc, char *argv[])
{
int pass = false;
if (argc != 2) {
usage();
exit(0);
}
pass = verify_passwd(argv[1]);
if (pass) {
printf("Got the right passwd!\n");
} else {
printf("Wrong passwd, try again...\n");
}
return 0;
}
| 3.21875 | 3 |
2024-11-18T22:11:00.601261+00:00 | 2022-04-07T14:51:28 | 417e78bff458e58bcf88726c235176dcba5b33dd | {
"blob_id": "417e78bff458e58bcf88726c235176dcba5b33dd",
"branch_name": "refs/heads/master",
"committer_date": "2022-04-07T14:51:28",
"content_id": "3e65fbdb2104f452f60672c5a5fdb2c6bcc33172",
"detected_licenses": [
"Unlicense"
],
"directory_id": "dd623ebf382e25dd6148d2dd7c5b3e576da88e49",
"extension": "c",
"filename": "wordlines.c",
"fork_events_count": 9,
"gha_created_at": "2018-03-06T20:23:23",
"gha_event_created_at": "2022-04-07T14:51:30",
"gha_language": "HTML",
"gha_license_id": "Unlicense",
"github_id": 124133881,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 434,
"license": "Unlicense",
"license_type": "permissive",
"path": "/collections/yaeger-al4ai/ngrams/_unused/wordlines.c",
"provenance": "stackv2-0072.json.gz:37845",
"repo_name": "isal-alife/artificial-life-teaching-materials",
"revision_date": "2022-04-07T14:51:28",
"revision_id": "a2e0ef11c0dbfccfcf7ac27946db7b3cac2f18e8",
"snapshot_id": "2902cb809bebc6025cda3568770c3ed58b459457",
"src_encoding": "UTF-8",
"star_events_count": 43,
"url": "https://raw.githubusercontent.com/isal-alife/artificial-life-teaching-materials/a2e0ef11c0dbfccfcf7ac27946db7b3cac2f18e8/collections/yaeger-al4ai/ngrams/_unused/wordlines.c",
"visit_date": "2022-05-01T00:35:52.022347"
} | stackv2 |
#include <stdio.h>
/*
* Read from stdin, replacing space with newline
* previous char was also a space (i.e. \n\n = end of paragraph).
*/
int main(int argc, char **argv)
{
char prev, current;
prev = current = '\0';
while ((current = getc(stdin)) != EOF)
{
if (current == ' ')
fprintf(stdout, (prev == ' ' ? "" : "\n"));
else if (!(current == ' '))
putc(current,stdout);
prev = current;
}
}
| 3.171875 | 3 |
2024-11-18T22:11:00.757311+00:00 | 2021-03-25T18:50:43 | dcab2f0cf1935616dc49dc30f50a53e94718f8b4 | {
"blob_id": "dcab2f0cf1935616dc49dc30f50a53e94718f8b4",
"branch_name": "refs/heads/main",
"committer_date": "2021-03-25T18:50:43",
"content_id": "06102ac97b52792e435a6db2951a81ab8123edc3",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "b0164a49ee08c8620277db928be398c6e55b8b9e",
"extension": "h",
"filename": "pads_bank0.h",
"fork_events_count": 1,
"gha_created_at": "2021-03-19T17:08:47",
"gha_event_created_at": "2021-03-25T18:00:49",
"gha_language": "C",
"gha_license_id": "Apache-2.0",
"github_id": 349498435,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 110256,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/cores/pico/sdk/include/hardware/regs/pads_bank0.h",
"provenance": "stackv2-0072.json.gz:37974",
"repo_name": "Wiz-IO/wizio-arduino-pico",
"revision_date": "2021-03-25T18:50:43",
"revision_id": "ed0191ac88b68ced5b5b3e52fba37de682770b64",
"snapshot_id": "fea06468923f3dc583466558a1a1fab68c5e3469",
"src_encoding": "UTF-8",
"star_events_count": 8,
"url": "https://raw.githubusercontent.com/Wiz-IO/wizio-arduino-pico/ed0191ac88b68ced5b5b3e52fba37de682770b64/cores/pico/sdk/include/hardware/regs/pads_bank0.h",
"visit_date": "2023-03-27T10:55:19.888866"
} | stackv2 | /**
* Copyright (c) 2021 Raspberry Pi (Trading) Ltd.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
// =============================================================================
// Register block : PADS_BANK0
// Version : 1
// Bus type : apb
// Description : None
// =============================================================================
#ifndef HARDWARE_REGS_PADS_BANK0_DEFINED
#define HARDWARE_REGS_PADS_BANK0_DEFINED
// =============================================================================
// Register : PADS_BANK0_VOLTAGE_SELECT
// Description : Voltage select. Per bank control
// 0x0 -> Set voltage to 3.3V (DVDD >= 2V5)
// 0x1 -> Set voltage to 1.8V (DVDD <= 1V8)
#define PADS_BANK0_VOLTAGE_SELECT_OFFSET _u(0x00000000)
#define PADS_BANK0_VOLTAGE_SELECT_BITS _u(0x00000001)
#define PADS_BANK0_VOLTAGE_SELECT_RESET _u(0x00000000)
#define PADS_BANK0_VOLTAGE_SELECT_MSB _u(0)
#define PADS_BANK0_VOLTAGE_SELECT_LSB _u(0)
#define PADS_BANK0_VOLTAGE_SELECT_ACCESS "RW"
#define PADS_BANK0_VOLTAGE_SELECT_VALUE_3V3 _u(0x0)
#define PADS_BANK0_VOLTAGE_SELECT_VALUE_1V8 _u(0x1)
// =============================================================================
// Register : PADS_BANK0_GPIO0
// Description : Pad control register
#define PADS_BANK0_GPIO0_OFFSET _u(0x00000004)
#define PADS_BANK0_GPIO0_BITS _u(0x000000ff)
#define PADS_BANK0_GPIO0_RESET _u(0x00000056)
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO0_OD
// Description : Output disable. Has priority over output enable from
// peripherals
#define PADS_BANK0_GPIO0_OD_RESET _u(0x0)
#define PADS_BANK0_GPIO0_OD_BITS _u(0x00000080)
#define PADS_BANK0_GPIO0_OD_MSB _u(7)
#define PADS_BANK0_GPIO0_OD_LSB _u(7)
#define PADS_BANK0_GPIO0_OD_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO0_IE
// Description : Input enable
#define PADS_BANK0_GPIO0_IE_RESET _u(0x1)
#define PADS_BANK0_GPIO0_IE_BITS _u(0x00000040)
#define PADS_BANK0_GPIO0_IE_MSB _u(6)
#define PADS_BANK0_GPIO0_IE_LSB _u(6)
#define PADS_BANK0_GPIO0_IE_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO0_DRIVE
// Description : Drive strength.
// 0x0 -> 2mA
// 0x1 -> 4mA
// 0x2 -> 8mA
// 0x3 -> 12mA
#define PADS_BANK0_GPIO0_DRIVE_RESET _u(0x1)
#define PADS_BANK0_GPIO0_DRIVE_BITS _u(0x00000030)
#define PADS_BANK0_GPIO0_DRIVE_MSB _u(5)
#define PADS_BANK0_GPIO0_DRIVE_LSB _u(4)
#define PADS_BANK0_GPIO0_DRIVE_ACCESS "RW"
#define PADS_BANK0_GPIO0_DRIVE_VALUE_2MA _u(0x0)
#define PADS_BANK0_GPIO0_DRIVE_VALUE_4MA _u(0x1)
#define PADS_BANK0_GPIO0_DRIVE_VALUE_8MA _u(0x2)
#define PADS_BANK0_GPIO0_DRIVE_VALUE_12MA _u(0x3)
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO0_PUE
// Description : Pull up enable
#define PADS_BANK0_GPIO0_PUE_RESET _u(0x0)
#define PADS_BANK0_GPIO0_PUE_BITS _u(0x00000008)
#define PADS_BANK0_GPIO0_PUE_MSB _u(3)
#define PADS_BANK0_GPIO0_PUE_LSB _u(3)
#define PADS_BANK0_GPIO0_PUE_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO0_PDE
// Description : Pull down enable
#define PADS_BANK0_GPIO0_PDE_RESET _u(0x1)
#define PADS_BANK0_GPIO0_PDE_BITS _u(0x00000004)
#define PADS_BANK0_GPIO0_PDE_MSB _u(2)
#define PADS_BANK0_GPIO0_PDE_LSB _u(2)
#define PADS_BANK0_GPIO0_PDE_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO0_SCHMITT
// Description : Enable schmitt trigger
#define PADS_BANK0_GPIO0_SCHMITT_RESET _u(0x1)
#define PADS_BANK0_GPIO0_SCHMITT_BITS _u(0x00000002)
#define PADS_BANK0_GPIO0_SCHMITT_MSB _u(1)
#define PADS_BANK0_GPIO0_SCHMITT_LSB _u(1)
#define PADS_BANK0_GPIO0_SCHMITT_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO0_SLEWFAST
// Description : Slew rate control. 1 = Fast, 0 = Slow
#define PADS_BANK0_GPIO0_SLEWFAST_RESET _u(0x0)
#define PADS_BANK0_GPIO0_SLEWFAST_BITS _u(0x00000001)
#define PADS_BANK0_GPIO0_SLEWFAST_MSB _u(0)
#define PADS_BANK0_GPIO0_SLEWFAST_LSB _u(0)
#define PADS_BANK0_GPIO0_SLEWFAST_ACCESS "RW"
// =============================================================================
// Register : PADS_BANK0_GPIO1
// Description : Pad control register
#define PADS_BANK0_GPIO1_OFFSET _u(0x00000008)
#define PADS_BANK0_GPIO1_BITS _u(0x000000ff)
#define PADS_BANK0_GPIO1_RESET _u(0x00000056)
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO1_OD
// Description : Output disable. Has priority over output enable from
// peripherals
#define PADS_BANK0_GPIO1_OD_RESET _u(0x0)
#define PADS_BANK0_GPIO1_OD_BITS _u(0x00000080)
#define PADS_BANK0_GPIO1_OD_MSB _u(7)
#define PADS_BANK0_GPIO1_OD_LSB _u(7)
#define PADS_BANK0_GPIO1_OD_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO1_IE
// Description : Input enable
#define PADS_BANK0_GPIO1_IE_RESET _u(0x1)
#define PADS_BANK0_GPIO1_IE_BITS _u(0x00000040)
#define PADS_BANK0_GPIO1_IE_MSB _u(6)
#define PADS_BANK0_GPIO1_IE_LSB _u(6)
#define PADS_BANK0_GPIO1_IE_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO1_DRIVE
// Description : Drive strength.
// 0x0 -> 2mA
// 0x1 -> 4mA
// 0x2 -> 8mA
// 0x3 -> 12mA
#define PADS_BANK0_GPIO1_DRIVE_RESET _u(0x1)
#define PADS_BANK0_GPIO1_DRIVE_BITS _u(0x00000030)
#define PADS_BANK0_GPIO1_DRIVE_MSB _u(5)
#define PADS_BANK0_GPIO1_DRIVE_LSB _u(4)
#define PADS_BANK0_GPIO1_DRIVE_ACCESS "RW"
#define PADS_BANK0_GPIO1_DRIVE_VALUE_2MA _u(0x0)
#define PADS_BANK0_GPIO1_DRIVE_VALUE_4MA _u(0x1)
#define PADS_BANK0_GPIO1_DRIVE_VALUE_8MA _u(0x2)
#define PADS_BANK0_GPIO1_DRIVE_VALUE_12MA _u(0x3)
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO1_PUE
// Description : Pull up enable
#define PADS_BANK0_GPIO1_PUE_RESET _u(0x0)
#define PADS_BANK0_GPIO1_PUE_BITS _u(0x00000008)
#define PADS_BANK0_GPIO1_PUE_MSB _u(3)
#define PADS_BANK0_GPIO1_PUE_LSB _u(3)
#define PADS_BANK0_GPIO1_PUE_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO1_PDE
// Description : Pull down enable
#define PADS_BANK0_GPIO1_PDE_RESET _u(0x1)
#define PADS_BANK0_GPIO1_PDE_BITS _u(0x00000004)
#define PADS_BANK0_GPIO1_PDE_MSB _u(2)
#define PADS_BANK0_GPIO1_PDE_LSB _u(2)
#define PADS_BANK0_GPIO1_PDE_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO1_SCHMITT
// Description : Enable schmitt trigger
#define PADS_BANK0_GPIO1_SCHMITT_RESET _u(0x1)
#define PADS_BANK0_GPIO1_SCHMITT_BITS _u(0x00000002)
#define PADS_BANK0_GPIO1_SCHMITT_MSB _u(1)
#define PADS_BANK0_GPIO1_SCHMITT_LSB _u(1)
#define PADS_BANK0_GPIO1_SCHMITT_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO1_SLEWFAST
// Description : Slew rate control. 1 = Fast, 0 = Slow
#define PADS_BANK0_GPIO1_SLEWFAST_RESET _u(0x0)
#define PADS_BANK0_GPIO1_SLEWFAST_BITS _u(0x00000001)
#define PADS_BANK0_GPIO1_SLEWFAST_MSB _u(0)
#define PADS_BANK0_GPIO1_SLEWFAST_LSB _u(0)
#define PADS_BANK0_GPIO1_SLEWFAST_ACCESS "RW"
// =============================================================================
// Register : PADS_BANK0_GPIO2
// Description : Pad control register
#define PADS_BANK0_GPIO2_OFFSET _u(0x0000000c)
#define PADS_BANK0_GPIO2_BITS _u(0x000000ff)
#define PADS_BANK0_GPIO2_RESET _u(0x00000056)
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO2_OD
// Description : Output disable. Has priority over output enable from
// peripherals
#define PADS_BANK0_GPIO2_OD_RESET _u(0x0)
#define PADS_BANK0_GPIO2_OD_BITS _u(0x00000080)
#define PADS_BANK0_GPIO2_OD_MSB _u(7)
#define PADS_BANK0_GPIO2_OD_LSB _u(7)
#define PADS_BANK0_GPIO2_OD_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO2_IE
// Description : Input enable
#define PADS_BANK0_GPIO2_IE_RESET _u(0x1)
#define PADS_BANK0_GPIO2_IE_BITS _u(0x00000040)
#define PADS_BANK0_GPIO2_IE_MSB _u(6)
#define PADS_BANK0_GPIO2_IE_LSB _u(6)
#define PADS_BANK0_GPIO2_IE_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO2_DRIVE
// Description : Drive strength.
// 0x0 -> 2mA
// 0x1 -> 4mA
// 0x2 -> 8mA
// 0x3 -> 12mA
#define PADS_BANK0_GPIO2_DRIVE_RESET _u(0x1)
#define PADS_BANK0_GPIO2_DRIVE_BITS _u(0x00000030)
#define PADS_BANK0_GPIO2_DRIVE_MSB _u(5)
#define PADS_BANK0_GPIO2_DRIVE_LSB _u(4)
#define PADS_BANK0_GPIO2_DRIVE_ACCESS "RW"
#define PADS_BANK0_GPIO2_DRIVE_VALUE_2MA _u(0x0)
#define PADS_BANK0_GPIO2_DRIVE_VALUE_4MA _u(0x1)
#define PADS_BANK0_GPIO2_DRIVE_VALUE_8MA _u(0x2)
#define PADS_BANK0_GPIO2_DRIVE_VALUE_12MA _u(0x3)
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO2_PUE
// Description : Pull up enable
#define PADS_BANK0_GPIO2_PUE_RESET _u(0x0)
#define PADS_BANK0_GPIO2_PUE_BITS _u(0x00000008)
#define PADS_BANK0_GPIO2_PUE_MSB _u(3)
#define PADS_BANK0_GPIO2_PUE_LSB _u(3)
#define PADS_BANK0_GPIO2_PUE_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO2_PDE
// Description : Pull down enable
#define PADS_BANK0_GPIO2_PDE_RESET _u(0x1)
#define PADS_BANK0_GPIO2_PDE_BITS _u(0x00000004)
#define PADS_BANK0_GPIO2_PDE_MSB _u(2)
#define PADS_BANK0_GPIO2_PDE_LSB _u(2)
#define PADS_BANK0_GPIO2_PDE_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO2_SCHMITT
// Description : Enable schmitt trigger
#define PADS_BANK0_GPIO2_SCHMITT_RESET _u(0x1)
#define PADS_BANK0_GPIO2_SCHMITT_BITS _u(0x00000002)
#define PADS_BANK0_GPIO2_SCHMITT_MSB _u(1)
#define PADS_BANK0_GPIO2_SCHMITT_LSB _u(1)
#define PADS_BANK0_GPIO2_SCHMITT_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO2_SLEWFAST
// Description : Slew rate control. 1 = Fast, 0 = Slow
#define PADS_BANK0_GPIO2_SLEWFAST_RESET _u(0x0)
#define PADS_BANK0_GPIO2_SLEWFAST_BITS _u(0x00000001)
#define PADS_BANK0_GPIO2_SLEWFAST_MSB _u(0)
#define PADS_BANK0_GPIO2_SLEWFAST_LSB _u(0)
#define PADS_BANK0_GPIO2_SLEWFAST_ACCESS "RW"
// =============================================================================
// Register : PADS_BANK0_GPIO3
// Description : Pad control register
#define PADS_BANK0_GPIO3_OFFSET _u(0x00000010)
#define PADS_BANK0_GPIO3_BITS _u(0x000000ff)
#define PADS_BANK0_GPIO3_RESET _u(0x00000056)
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO3_OD
// Description : Output disable. Has priority over output enable from
// peripherals
#define PADS_BANK0_GPIO3_OD_RESET _u(0x0)
#define PADS_BANK0_GPIO3_OD_BITS _u(0x00000080)
#define PADS_BANK0_GPIO3_OD_MSB _u(7)
#define PADS_BANK0_GPIO3_OD_LSB _u(7)
#define PADS_BANK0_GPIO3_OD_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO3_IE
// Description : Input enable
#define PADS_BANK0_GPIO3_IE_RESET _u(0x1)
#define PADS_BANK0_GPIO3_IE_BITS _u(0x00000040)
#define PADS_BANK0_GPIO3_IE_MSB _u(6)
#define PADS_BANK0_GPIO3_IE_LSB _u(6)
#define PADS_BANK0_GPIO3_IE_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO3_DRIVE
// Description : Drive strength.
// 0x0 -> 2mA
// 0x1 -> 4mA
// 0x2 -> 8mA
// 0x3 -> 12mA
#define PADS_BANK0_GPIO3_DRIVE_RESET _u(0x1)
#define PADS_BANK0_GPIO3_DRIVE_BITS _u(0x00000030)
#define PADS_BANK0_GPIO3_DRIVE_MSB _u(5)
#define PADS_BANK0_GPIO3_DRIVE_LSB _u(4)
#define PADS_BANK0_GPIO3_DRIVE_ACCESS "RW"
#define PADS_BANK0_GPIO3_DRIVE_VALUE_2MA _u(0x0)
#define PADS_BANK0_GPIO3_DRIVE_VALUE_4MA _u(0x1)
#define PADS_BANK0_GPIO3_DRIVE_VALUE_8MA _u(0x2)
#define PADS_BANK0_GPIO3_DRIVE_VALUE_12MA _u(0x3)
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO3_PUE
// Description : Pull up enable
#define PADS_BANK0_GPIO3_PUE_RESET _u(0x0)
#define PADS_BANK0_GPIO3_PUE_BITS _u(0x00000008)
#define PADS_BANK0_GPIO3_PUE_MSB _u(3)
#define PADS_BANK0_GPIO3_PUE_LSB _u(3)
#define PADS_BANK0_GPIO3_PUE_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO3_PDE
// Description : Pull down enable
#define PADS_BANK0_GPIO3_PDE_RESET _u(0x1)
#define PADS_BANK0_GPIO3_PDE_BITS _u(0x00000004)
#define PADS_BANK0_GPIO3_PDE_MSB _u(2)
#define PADS_BANK0_GPIO3_PDE_LSB _u(2)
#define PADS_BANK0_GPIO3_PDE_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO3_SCHMITT
// Description : Enable schmitt trigger
#define PADS_BANK0_GPIO3_SCHMITT_RESET _u(0x1)
#define PADS_BANK0_GPIO3_SCHMITT_BITS _u(0x00000002)
#define PADS_BANK0_GPIO3_SCHMITT_MSB _u(1)
#define PADS_BANK0_GPIO3_SCHMITT_LSB _u(1)
#define PADS_BANK0_GPIO3_SCHMITT_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO3_SLEWFAST
// Description : Slew rate control. 1 = Fast, 0 = Slow
#define PADS_BANK0_GPIO3_SLEWFAST_RESET _u(0x0)
#define PADS_BANK0_GPIO3_SLEWFAST_BITS _u(0x00000001)
#define PADS_BANK0_GPIO3_SLEWFAST_MSB _u(0)
#define PADS_BANK0_GPIO3_SLEWFAST_LSB _u(0)
#define PADS_BANK0_GPIO3_SLEWFAST_ACCESS "RW"
// =============================================================================
// Register : PADS_BANK0_GPIO4
// Description : Pad control register
#define PADS_BANK0_GPIO4_OFFSET _u(0x00000014)
#define PADS_BANK0_GPIO4_BITS _u(0x000000ff)
#define PADS_BANK0_GPIO4_RESET _u(0x00000056)
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO4_OD
// Description : Output disable. Has priority over output enable from
// peripherals
#define PADS_BANK0_GPIO4_OD_RESET _u(0x0)
#define PADS_BANK0_GPIO4_OD_BITS _u(0x00000080)
#define PADS_BANK0_GPIO4_OD_MSB _u(7)
#define PADS_BANK0_GPIO4_OD_LSB _u(7)
#define PADS_BANK0_GPIO4_OD_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO4_IE
// Description : Input enable
#define PADS_BANK0_GPIO4_IE_RESET _u(0x1)
#define PADS_BANK0_GPIO4_IE_BITS _u(0x00000040)
#define PADS_BANK0_GPIO4_IE_MSB _u(6)
#define PADS_BANK0_GPIO4_IE_LSB _u(6)
#define PADS_BANK0_GPIO4_IE_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO4_DRIVE
// Description : Drive strength.
// 0x0 -> 2mA
// 0x1 -> 4mA
// 0x2 -> 8mA
// 0x3 -> 12mA
#define PADS_BANK0_GPIO4_DRIVE_RESET _u(0x1)
#define PADS_BANK0_GPIO4_DRIVE_BITS _u(0x00000030)
#define PADS_BANK0_GPIO4_DRIVE_MSB _u(5)
#define PADS_BANK0_GPIO4_DRIVE_LSB _u(4)
#define PADS_BANK0_GPIO4_DRIVE_ACCESS "RW"
#define PADS_BANK0_GPIO4_DRIVE_VALUE_2MA _u(0x0)
#define PADS_BANK0_GPIO4_DRIVE_VALUE_4MA _u(0x1)
#define PADS_BANK0_GPIO4_DRIVE_VALUE_8MA _u(0x2)
#define PADS_BANK0_GPIO4_DRIVE_VALUE_12MA _u(0x3)
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO4_PUE
// Description : Pull up enable
#define PADS_BANK0_GPIO4_PUE_RESET _u(0x0)
#define PADS_BANK0_GPIO4_PUE_BITS _u(0x00000008)
#define PADS_BANK0_GPIO4_PUE_MSB _u(3)
#define PADS_BANK0_GPIO4_PUE_LSB _u(3)
#define PADS_BANK0_GPIO4_PUE_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO4_PDE
// Description : Pull down enable
#define PADS_BANK0_GPIO4_PDE_RESET _u(0x1)
#define PADS_BANK0_GPIO4_PDE_BITS _u(0x00000004)
#define PADS_BANK0_GPIO4_PDE_MSB _u(2)
#define PADS_BANK0_GPIO4_PDE_LSB _u(2)
#define PADS_BANK0_GPIO4_PDE_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO4_SCHMITT
// Description : Enable schmitt trigger
#define PADS_BANK0_GPIO4_SCHMITT_RESET _u(0x1)
#define PADS_BANK0_GPIO4_SCHMITT_BITS _u(0x00000002)
#define PADS_BANK0_GPIO4_SCHMITT_MSB _u(1)
#define PADS_BANK0_GPIO4_SCHMITT_LSB _u(1)
#define PADS_BANK0_GPIO4_SCHMITT_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO4_SLEWFAST
// Description : Slew rate control. 1 = Fast, 0 = Slow
#define PADS_BANK0_GPIO4_SLEWFAST_RESET _u(0x0)
#define PADS_BANK0_GPIO4_SLEWFAST_BITS _u(0x00000001)
#define PADS_BANK0_GPIO4_SLEWFAST_MSB _u(0)
#define PADS_BANK0_GPIO4_SLEWFAST_LSB _u(0)
#define PADS_BANK0_GPIO4_SLEWFAST_ACCESS "RW"
// =============================================================================
// Register : PADS_BANK0_GPIO5
// Description : Pad control register
#define PADS_BANK0_GPIO5_OFFSET _u(0x00000018)
#define PADS_BANK0_GPIO5_BITS _u(0x000000ff)
#define PADS_BANK0_GPIO5_RESET _u(0x00000056)
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO5_OD
// Description : Output disable. Has priority over output enable from
// peripherals
#define PADS_BANK0_GPIO5_OD_RESET _u(0x0)
#define PADS_BANK0_GPIO5_OD_BITS _u(0x00000080)
#define PADS_BANK0_GPIO5_OD_MSB _u(7)
#define PADS_BANK0_GPIO5_OD_LSB _u(7)
#define PADS_BANK0_GPIO5_OD_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO5_IE
// Description : Input enable
#define PADS_BANK0_GPIO5_IE_RESET _u(0x1)
#define PADS_BANK0_GPIO5_IE_BITS _u(0x00000040)
#define PADS_BANK0_GPIO5_IE_MSB _u(6)
#define PADS_BANK0_GPIO5_IE_LSB _u(6)
#define PADS_BANK0_GPIO5_IE_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO5_DRIVE
// Description : Drive strength.
// 0x0 -> 2mA
// 0x1 -> 4mA
// 0x2 -> 8mA
// 0x3 -> 12mA
#define PADS_BANK0_GPIO5_DRIVE_RESET _u(0x1)
#define PADS_BANK0_GPIO5_DRIVE_BITS _u(0x00000030)
#define PADS_BANK0_GPIO5_DRIVE_MSB _u(5)
#define PADS_BANK0_GPIO5_DRIVE_LSB _u(4)
#define PADS_BANK0_GPIO5_DRIVE_ACCESS "RW"
#define PADS_BANK0_GPIO5_DRIVE_VALUE_2MA _u(0x0)
#define PADS_BANK0_GPIO5_DRIVE_VALUE_4MA _u(0x1)
#define PADS_BANK0_GPIO5_DRIVE_VALUE_8MA _u(0x2)
#define PADS_BANK0_GPIO5_DRIVE_VALUE_12MA _u(0x3)
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO5_PUE
// Description : Pull up enable
#define PADS_BANK0_GPIO5_PUE_RESET _u(0x0)
#define PADS_BANK0_GPIO5_PUE_BITS _u(0x00000008)
#define PADS_BANK0_GPIO5_PUE_MSB _u(3)
#define PADS_BANK0_GPIO5_PUE_LSB _u(3)
#define PADS_BANK0_GPIO5_PUE_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO5_PDE
// Description : Pull down enable
#define PADS_BANK0_GPIO5_PDE_RESET _u(0x1)
#define PADS_BANK0_GPIO5_PDE_BITS _u(0x00000004)
#define PADS_BANK0_GPIO5_PDE_MSB _u(2)
#define PADS_BANK0_GPIO5_PDE_LSB _u(2)
#define PADS_BANK0_GPIO5_PDE_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO5_SCHMITT
// Description : Enable schmitt trigger
#define PADS_BANK0_GPIO5_SCHMITT_RESET _u(0x1)
#define PADS_BANK0_GPIO5_SCHMITT_BITS _u(0x00000002)
#define PADS_BANK0_GPIO5_SCHMITT_MSB _u(1)
#define PADS_BANK0_GPIO5_SCHMITT_LSB _u(1)
#define PADS_BANK0_GPIO5_SCHMITT_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO5_SLEWFAST
// Description : Slew rate control. 1 = Fast, 0 = Slow
#define PADS_BANK0_GPIO5_SLEWFAST_RESET _u(0x0)
#define PADS_BANK0_GPIO5_SLEWFAST_BITS _u(0x00000001)
#define PADS_BANK0_GPIO5_SLEWFAST_MSB _u(0)
#define PADS_BANK0_GPIO5_SLEWFAST_LSB _u(0)
#define PADS_BANK0_GPIO5_SLEWFAST_ACCESS "RW"
// =============================================================================
// Register : PADS_BANK0_GPIO6
// Description : Pad control register
#define PADS_BANK0_GPIO6_OFFSET _u(0x0000001c)
#define PADS_BANK0_GPIO6_BITS _u(0x000000ff)
#define PADS_BANK0_GPIO6_RESET _u(0x00000056)
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO6_OD
// Description : Output disable. Has priority over output enable from
// peripherals
#define PADS_BANK0_GPIO6_OD_RESET _u(0x0)
#define PADS_BANK0_GPIO6_OD_BITS _u(0x00000080)
#define PADS_BANK0_GPIO6_OD_MSB _u(7)
#define PADS_BANK0_GPIO6_OD_LSB _u(7)
#define PADS_BANK0_GPIO6_OD_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO6_IE
// Description : Input enable
#define PADS_BANK0_GPIO6_IE_RESET _u(0x1)
#define PADS_BANK0_GPIO6_IE_BITS _u(0x00000040)
#define PADS_BANK0_GPIO6_IE_MSB _u(6)
#define PADS_BANK0_GPIO6_IE_LSB _u(6)
#define PADS_BANK0_GPIO6_IE_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO6_DRIVE
// Description : Drive strength.
// 0x0 -> 2mA
// 0x1 -> 4mA
// 0x2 -> 8mA
// 0x3 -> 12mA
#define PADS_BANK0_GPIO6_DRIVE_RESET _u(0x1)
#define PADS_BANK0_GPIO6_DRIVE_BITS _u(0x00000030)
#define PADS_BANK0_GPIO6_DRIVE_MSB _u(5)
#define PADS_BANK0_GPIO6_DRIVE_LSB _u(4)
#define PADS_BANK0_GPIO6_DRIVE_ACCESS "RW"
#define PADS_BANK0_GPIO6_DRIVE_VALUE_2MA _u(0x0)
#define PADS_BANK0_GPIO6_DRIVE_VALUE_4MA _u(0x1)
#define PADS_BANK0_GPIO6_DRIVE_VALUE_8MA _u(0x2)
#define PADS_BANK0_GPIO6_DRIVE_VALUE_12MA _u(0x3)
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO6_PUE
// Description : Pull up enable
#define PADS_BANK0_GPIO6_PUE_RESET _u(0x0)
#define PADS_BANK0_GPIO6_PUE_BITS _u(0x00000008)
#define PADS_BANK0_GPIO6_PUE_MSB _u(3)
#define PADS_BANK0_GPIO6_PUE_LSB _u(3)
#define PADS_BANK0_GPIO6_PUE_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO6_PDE
// Description : Pull down enable
#define PADS_BANK0_GPIO6_PDE_RESET _u(0x1)
#define PADS_BANK0_GPIO6_PDE_BITS _u(0x00000004)
#define PADS_BANK0_GPIO6_PDE_MSB _u(2)
#define PADS_BANK0_GPIO6_PDE_LSB _u(2)
#define PADS_BANK0_GPIO6_PDE_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO6_SCHMITT
// Description : Enable schmitt trigger
#define PADS_BANK0_GPIO6_SCHMITT_RESET _u(0x1)
#define PADS_BANK0_GPIO6_SCHMITT_BITS _u(0x00000002)
#define PADS_BANK0_GPIO6_SCHMITT_MSB _u(1)
#define PADS_BANK0_GPIO6_SCHMITT_LSB _u(1)
#define PADS_BANK0_GPIO6_SCHMITT_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO6_SLEWFAST
// Description : Slew rate control. 1 = Fast, 0 = Slow
#define PADS_BANK0_GPIO6_SLEWFAST_RESET _u(0x0)
#define PADS_BANK0_GPIO6_SLEWFAST_BITS _u(0x00000001)
#define PADS_BANK0_GPIO6_SLEWFAST_MSB _u(0)
#define PADS_BANK0_GPIO6_SLEWFAST_LSB _u(0)
#define PADS_BANK0_GPIO6_SLEWFAST_ACCESS "RW"
// =============================================================================
// Register : PADS_BANK0_GPIO7
// Description : Pad control register
#define PADS_BANK0_GPIO7_OFFSET _u(0x00000020)
#define PADS_BANK0_GPIO7_BITS _u(0x000000ff)
#define PADS_BANK0_GPIO7_RESET _u(0x00000056)
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO7_OD
// Description : Output disable. Has priority over output enable from
// peripherals
#define PADS_BANK0_GPIO7_OD_RESET _u(0x0)
#define PADS_BANK0_GPIO7_OD_BITS _u(0x00000080)
#define PADS_BANK0_GPIO7_OD_MSB _u(7)
#define PADS_BANK0_GPIO7_OD_LSB _u(7)
#define PADS_BANK0_GPIO7_OD_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO7_IE
// Description : Input enable
#define PADS_BANK0_GPIO7_IE_RESET _u(0x1)
#define PADS_BANK0_GPIO7_IE_BITS _u(0x00000040)
#define PADS_BANK0_GPIO7_IE_MSB _u(6)
#define PADS_BANK0_GPIO7_IE_LSB _u(6)
#define PADS_BANK0_GPIO7_IE_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO7_DRIVE
// Description : Drive strength.
// 0x0 -> 2mA
// 0x1 -> 4mA
// 0x2 -> 8mA
// 0x3 -> 12mA
#define PADS_BANK0_GPIO7_DRIVE_RESET _u(0x1)
#define PADS_BANK0_GPIO7_DRIVE_BITS _u(0x00000030)
#define PADS_BANK0_GPIO7_DRIVE_MSB _u(5)
#define PADS_BANK0_GPIO7_DRIVE_LSB _u(4)
#define PADS_BANK0_GPIO7_DRIVE_ACCESS "RW"
#define PADS_BANK0_GPIO7_DRIVE_VALUE_2MA _u(0x0)
#define PADS_BANK0_GPIO7_DRIVE_VALUE_4MA _u(0x1)
#define PADS_BANK0_GPIO7_DRIVE_VALUE_8MA _u(0x2)
#define PADS_BANK0_GPIO7_DRIVE_VALUE_12MA _u(0x3)
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO7_PUE
// Description : Pull up enable
#define PADS_BANK0_GPIO7_PUE_RESET _u(0x0)
#define PADS_BANK0_GPIO7_PUE_BITS _u(0x00000008)
#define PADS_BANK0_GPIO7_PUE_MSB _u(3)
#define PADS_BANK0_GPIO7_PUE_LSB _u(3)
#define PADS_BANK0_GPIO7_PUE_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO7_PDE
// Description : Pull down enable
#define PADS_BANK0_GPIO7_PDE_RESET _u(0x1)
#define PADS_BANK0_GPIO7_PDE_BITS _u(0x00000004)
#define PADS_BANK0_GPIO7_PDE_MSB _u(2)
#define PADS_BANK0_GPIO7_PDE_LSB _u(2)
#define PADS_BANK0_GPIO7_PDE_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO7_SCHMITT
// Description : Enable schmitt trigger
#define PADS_BANK0_GPIO7_SCHMITT_RESET _u(0x1)
#define PADS_BANK0_GPIO7_SCHMITT_BITS _u(0x00000002)
#define PADS_BANK0_GPIO7_SCHMITT_MSB _u(1)
#define PADS_BANK0_GPIO7_SCHMITT_LSB _u(1)
#define PADS_BANK0_GPIO7_SCHMITT_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO7_SLEWFAST
// Description : Slew rate control. 1 = Fast, 0 = Slow
#define PADS_BANK0_GPIO7_SLEWFAST_RESET _u(0x0)
#define PADS_BANK0_GPIO7_SLEWFAST_BITS _u(0x00000001)
#define PADS_BANK0_GPIO7_SLEWFAST_MSB _u(0)
#define PADS_BANK0_GPIO7_SLEWFAST_LSB _u(0)
#define PADS_BANK0_GPIO7_SLEWFAST_ACCESS "RW"
// =============================================================================
// Register : PADS_BANK0_GPIO8
// Description : Pad control register
#define PADS_BANK0_GPIO8_OFFSET _u(0x00000024)
#define PADS_BANK0_GPIO8_BITS _u(0x000000ff)
#define PADS_BANK0_GPIO8_RESET _u(0x00000056)
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO8_OD
// Description : Output disable. Has priority over output enable from
// peripherals
#define PADS_BANK0_GPIO8_OD_RESET _u(0x0)
#define PADS_BANK0_GPIO8_OD_BITS _u(0x00000080)
#define PADS_BANK0_GPIO8_OD_MSB _u(7)
#define PADS_BANK0_GPIO8_OD_LSB _u(7)
#define PADS_BANK0_GPIO8_OD_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO8_IE
// Description : Input enable
#define PADS_BANK0_GPIO8_IE_RESET _u(0x1)
#define PADS_BANK0_GPIO8_IE_BITS _u(0x00000040)
#define PADS_BANK0_GPIO8_IE_MSB _u(6)
#define PADS_BANK0_GPIO8_IE_LSB _u(6)
#define PADS_BANK0_GPIO8_IE_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO8_DRIVE
// Description : Drive strength.
// 0x0 -> 2mA
// 0x1 -> 4mA
// 0x2 -> 8mA
// 0x3 -> 12mA
#define PADS_BANK0_GPIO8_DRIVE_RESET _u(0x1)
#define PADS_BANK0_GPIO8_DRIVE_BITS _u(0x00000030)
#define PADS_BANK0_GPIO8_DRIVE_MSB _u(5)
#define PADS_BANK0_GPIO8_DRIVE_LSB _u(4)
#define PADS_BANK0_GPIO8_DRIVE_ACCESS "RW"
#define PADS_BANK0_GPIO8_DRIVE_VALUE_2MA _u(0x0)
#define PADS_BANK0_GPIO8_DRIVE_VALUE_4MA _u(0x1)
#define PADS_BANK0_GPIO8_DRIVE_VALUE_8MA _u(0x2)
#define PADS_BANK0_GPIO8_DRIVE_VALUE_12MA _u(0x3)
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO8_PUE
// Description : Pull up enable
#define PADS_BANK0_GPIO8_PUE_RESET _u(0x0)
#define PADS_BANK0_GPIO8_PUE_BITS _u(0x00000008)
#define PADS_BANK0_GPIO8_PUE_MSB _u(3)
#define PADS_BANK0_GPIO8_PUE_LSB _u(3)
#define PADS_BANK0_GPIO8_PUE_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO8_PDE
// Description : Pull down enable
#define PADS_BANK0_GPIO8_PDE_RESET _u(0x1)
#define PADS_BANK0_GPIO8_PDE_BITS _u(0x00000004)
#define PADS_BANK0_GPIO8_PDE_MSB _u(2)
#define PADS_BANK0_GPIO8_PDE_LSB _u(2)
#define PADS_BANK0_GPIO8_PDE_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO8_SCHMITT
// Description : Enable schmitt trigger
#define PADS_BANK0_GPIO8_SCHMITT_RESET _u(0x1)
#define PADS_BANK0_GPIO8_SCHMITT_BITS _u(0x00000002)
#define PADS_BANK0_GPIO8_SCHMITT_MSB _u(1)
#define PADS_BANK0_GPIO8_SCHMITT_LSB _u(1)
#define PADS_BANK0_GPIO8_SCHMITT_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO8_SLEWFAST
// Description : Slew rate control. 1 = Fast, 0 = Slow
#define PADS_BANK0_GPIO8_SLEWFAST_RESET _u(0x0)
#define PADS_BANK0_GPIO8_SLEWFAST_BITS _u(0x00000001)
#define PADS_BANK0_GPIO8_SLEWFAST_MSB _u(0)
#define PADS_BANK0_GPIO8_SLEWFAST_LSB _u(0)
#define PADS_BANK0_GPIO8_SLEWFAST_ACCESS "RW"
// =============================================================================
// Register : PADS_BANK0_GPIO9
// Description : Pad control register
#define PADS_BANK0_GPIO9_OFFSET _u(0x00000028)
#define PADS_BANK0_GPIO9_BITS _u(0x000000ff)
#define PADS_BANK0_GPIO9_RESET _u(0x00000056)
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO9_OD
// Description : Output disable. Has priority over output enable from
// peripherals
#define PADS_BANK0_GPIO9_OD_RESET _u(0x0)
#define PADS_BANK0_GPIO9_OD_BITS _u(0x00000080)
#define PADS_BANK0_GPIO9_OD_MSB _u(7)
#define PADS_BANK0_GPIO9_OD_LSB _u(7)
#define PADS_BANK0_GPIO9_OD_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO9_IE
// Description : Input enable
#define PADS_BANK0_GPIO9_IE_RESET _u(0x1)
#define PADS_BANK0_GPIO9_IE_BITS _u(0x00000040)
#define PADS_BANK0_GPIO9_IE_MSB _u(6)
#define PADS_BANK0_GPIO9_IE_LSB _u(6)
#define PADS_BANK0_GPIO9_IE_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO9_DRIVE
// Description : Drive strength.
// 0x0 -> 2mA
// 0x1 -> 4mA
// 0x2 -> 8mA
// 0x3 -> 12mA
#define PADS_BANK0_GPIO9_DRIVE_RESET _u(0x1)
#define PADS_BANK0_GPIO9_DRIVE_BITS _u(0x00000030)
#define PADS_BANK0_GPIO9_DRIVE_MSB _u(5)
#define PADS_BANK0_GPIO9_DRIVE_LSB _u(4)
#define PADS_BANK0_GPIO9_DRIVE_ACCESS "RW"
#define PADS_BANK0_GPIO9_DRIVE_VALUE_2MA _u(0x0)
#define PADS_BANK0_GPIO9_DRIVE_VALUE_4MA _u(0x1)
#define PADS_BANK0_GPIO9_DRIVE_VALUE_8MA _u(0x2)
#define PADS_BANK0_GPIO9_DRIVE_VALUE_12MA _u(0x3)
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO9_PUE
// Description : Pull up enable
#define PADS_BANK0_GPIO9_PUE_RESET _u(0x0)
#define PADS_BANK0_GPIO9_PUE_BITS _u(0x00000008)
#define PADS_BANK0_GPIO9_PUE_MSB _u(3)
#define PADS_BANK0_GPIO9_PUE_LSB _u(3)
#define PADS_BANK0_GPIO9_PUE_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO9_PDE
// Description : Pull down enable
#define PADS_BANK0_GPIO9_PDE_RESET _u(0x1)
#define PADS_BANK0_GPIO9_PDE_BITS _u(0x00000004)
#define PADS_BANK0_GPIO9_PDE_MSB _u(2)
#define PADS_BANK0_GPIO9_PDE_LSB _u(2)
#define PADS_BANK0_GPIO9_PDE_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO9_SCHMITT
// Description : Enable schmitt trigger
#define PADS_BANK0_GPIO9_SCHMITT_RESET _u(0x1)
#define PADS_BANK0_GPIO9_SCHMITT_BITS _u(0x00000002)
#define PADS_BANK0_GPIO9_SCHMITT_MSB _u(1)
#define PADS_BANK0_GPIO9_SCHMITT_LSB _u(1)
#define PADS_BANK0_GPIO9_SCHMITT_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO9_SLEWFAST
// Description : Slew rate control. 1 = Fast, 0 = Slow
#define PADS_BANK0_GPIO9_SLEWFAST_RESET _u(0x0)
#define PADS_BANK0_GPIO9_SLEWFAST_BITS _u(0x00000001)
#define PADS_BANK0_GPIO9_SLEWFAST_MSB _u(0)
#define PADS_BANK0_GPIO9_SLEWFAST_LSB _u(0)
#define PADS_BANK0_GPIO9_SLEWFAST_ACCESS "RW"
// =============================================================================
// Register : PADS_BANK0_GPIO10
// Description : Pad control register
#define PADS_BANK0_GPIO10_OFFSET _u(0x0000002c)
#define PADS_BANK0_GPIO10_BITS _u(0x000000ff)
#define PADS_BANK0_GPIO10_RESET _u(0x00000056)
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO10_OD
// Description : Output disable. Has priority over output enable from
// peripherals
#define PADS_BANK0_GPIO10_OD_RESET _u(0x0)
#define PADS_BANK0_GPIO10_OD_BITS _u(0x00000080)
#define PADS_BANK0_GPIO10_OD_MSB _u(7)
#define PADS_BANK0_GPIO10_OD_LSB _u(7)
#define PADS_BANK0_GPIO10_OD_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO10_IE
// Description : Input enable
#define PADS_BANK0_GPIO10_IE_RESET _u(0x1)
#define PADS_BANK0_GPIO10_IE_BITS _u(0x00000040)
#define PADS_BANK0_GPIO10_IE_MSB _u(6)
#define PADS_BANK0_GPIO10_IE_LSB _u(6)
#define PADS_BANK0_GPIO10_IE_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO10_DRIVE
// Description : Drive strength.
// 0x0 -> 2mA
// 0x1 -> 4mA
// 0x2 -> 8mA
// 0x3 -> 12mA
#define PADS_BANK0_GPIO10_DRIVE_RESET _u(0x1)
#define PADS_BANK0_GPIO10_DRIVE_BITS _u(0x00000030)
#define PADS_BANK0_GPIO10_DRIVE_MSB _u(5)
#define PADS_BANK0_GPIO10_DRIVE_LSB _u(4)
#define PADS_BANK0_GPIO10_DRIVE_ACCESS "RW"
#define PADS_BANK0_GPIO10_DRIVE_VALUE_2MA _u(0x0)
#define PADS_BANK0_GPIO10_DRIVE_VALUE_4MA _u(0x1)
#define PADS_BANK0_GPIO10_DRIVE_VALUE_8MA _u(0x2)
#define PADS_BANK0_GPIO10_DRIVE_VALUE_12MA _u(0x3)
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO10_PUE
// Description : Pull up enable
#define PADS_BANK0_GPIO10_PUE_RESET _u(0x0)
#define PADS_BANK0_GPIO10_PUE_BITS _u(0x00000008)
#define PADS_BANK0_GPIO10_PUE_MSB _u(3)
#define PADS_BANK0_GPIO10_PUE_LSB _u(3)
#define PADS_BANK0_GPIO10_PUE_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO10_PDE
// Description : Pull down enable
#define PADS_BANK0_GPIO10_PDE_RESET _u(0x1)
#define PADS_BANK0_GPIO10_PDE_BITS _u(0x00000004)
#define PADS_BANK0_GPIO10_PDE_MSB _u(2)
#define PADS_BANK0_GPIO10_PDE_LSB _u(2)
#define PADS_BANK0_GPIO10_PDE_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO10_SCHMITT
// Description : Enable schmitt trigger
#define PADS_BANK0_GPIO10_SCHMITT_RESET _u(0x1)
#define PADS_BANK0_GPIO10_SCHMITT_BITS _u(0x00000002)
#define PADS_BANK0_GPIO10_SCHMITT_MSB _u(1)
#define PADS_BANK0_GPIO10_SCHMITT_LSB _u(1)
#define PADS_BANK0_GPIO10_SCHMITT_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO10_SLEWFAST
// Description : Slew rate control. 1 = Fast, 0 = Slow
#define PADS_BANK0_GPIO10_SLEWFAST_RESET _u(0x0)
#define PADS_BANK0_GPIO10_SLEWFAST_BITS _u(0x00000001)
#define PADS_BANK0_GPIO10_SLEWFAST_MSB _u(0)
#define PADS_BANK0_GPIO10_SLEWFAST_LSB _u(0)
#define PADS_BANK0_GPIO10_SLEWFAST_ACCESS "RW"
// =============================================================================
// Register : PADS_BANK0_GPIO11
// Description : Pad control register
#define PADS_BANK0_GPIO11_OFFSET _u(0x00000030)
#define PADS_BANK0_GPIO11_BITS _u(0x000000ff)
#define PADS_BANK0_GPIO11_RESET _u(0x00000056)
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO11_OD
// Description : Output disable. Has priority over output enable from
// peripherals
#define PADS_BANK0_GPIO11_OD_RESET _u(0x0)
#define PADS_BANK0_GPIO11_OD_BITS _u(0x00000080)
#define PADS_BANK0_GPIO11_OD_MSB _u(7)
#define PADS_BANK0_GPIO11_OD_LSB _u(7)
#define PADS_BANK0_GPIO11_OD_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO11_IE
// Description : Input enable
#define PADS_BANK0_GPIO11_IE_RESET _u(0x1)
#define PADS_BANK0_GPIO11_IE_BITS _u(0x00000040)
#define PADS_BANK0_GPIO11_IE_MSB _u(6)
#define PADS_BANK0_GPIO11_IE_LSB _u(6)
#define PADS_BANK0_GPIO11_IE_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO11_DRIVE
// Description : Drive strength.
// 0x0 -> 2mA
// 0x1 -> 4mA
// 0x2 -> 8mA
// 0x3 -> 12mA
#define PADS_BANK0_GPIO11_DRIVE_RESET _u(0x1)
#define PADS_BANK0_GPIO11_DRIVE_BITS _u(0x00000030)
#define PADS_BANK0_GPIO11_DRIVE_MSB _u(5)
#define PADS_BANK0_GPIO11_DRIVE_LSB _u(4)
#define PADS_BANK0_GPIO11_DRIVE_ACCESS "RW"
#define PADS_BANK0_GPIO11_DRIVE_VALUE_2MA _u(0x0)
#define PADS_BANK0_GPIO11_DRIVE_VALUE_4MA _u(0x1)
#define PADS_BANK0_GPIO11_DRIVE_VALUE_8MA _u(0x2)
#define PADS_BANK0_GPIO11_DRIVE_VALUE_12MA _u(0x3)
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO11_PUE
// Description : Pull up enable
#define PADS_BANK0_GPIO11_PUE_RESET _u(0x0)
#define PADS_BANK0_GPIO11_PUE_BITS _u(0x00000008)
#define PADS_BANK0_GPIO11_PUE_MSB _u(3)
#define PADS_BANK0_GPIO11_PUE_LSB _u(3)
#define PADS_BANK0_GPIO11_PUE_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO11_PDE
// Description : Pull down enable
#define PADS_BANK0_GPIO11_PDE_RESET _u(0x1)
#define PADS_BANK0_GPIO11_PDE_BITS _u(0x00000004)
#define PADS_BANK0_GPIO11_PDE_MSB _u(2)
#define PADS_BANK0_GPIO11_PDE_LSB _u(2)
#define PADS_BANK0_GPIO11_PDE_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO11_SCHMITT
// Description : Enable schmitt trigger
#define PADS_BANK0_GPIO11_SCHMITT_RESET _u(0x1)
#define PADS_BANK0_GPIO11_SCHMITT_BITS _u(0x00000002)
#define PADS_BANK0_GPIO11_SCHMITT_MSB _u(1)
#define PADS_BANK0_GPIO11_SCHMITT_LSB _u(1)
#define PADS_BANK0_GPIO11_SCHMITT_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO11_SLEWFAST
// Description : Slew rate control. 1 = Fast, 0 = Slow
#define PADS_BANK0_GPIO11_SLEWFAST_RESET _u(0x0)
#define PADS_BANK0_GPIO11_SLEWFAST_BITS _u(0x00000001)
#define PADS_BANK0_GPIO11_SLEWFAST_MSB _u(0)
#define PADS_BANK0_GPIO11_SLEWFAST_LSB _u(0)
#define PADS_BANK0_GPIO11_SLEWFAST_ACCESS "RW"
// =============================================================================
// Register : PADS_BANK0_GPIO12
// Description : Pad control register
#define PADS_BANK0_GPIO12_OFFSET _u(0x00000034)
#define PADS_BANK0_GPIO12_BITS _u(0x000000ff)
#define PADS_BANK0_GPIO12_RESET _u(0x00000056)
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO12_OD
// Description : Output disable. Has priority over output enable from
// peripherals
#define PADS_BANK0_GPIO12_OD_RESET _u(0x0)
#define PADS_BANK0_GPIO12_OD_BITS _u(0x00000080)
#define PADS_BANK0_GPIO12_OD_MSB _u(7)
#define PADS_BANK0_GPIO12_OD_LSB _u(7)
#define PADS_BANK0_GPIO12_OD_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO12_IE
// Description : Input enable
#define PADS_BANK0_GPIO12_IE_RESET _u(0x1)
#define PADS_BANK0_GPIO12_IE_BITS _u(0x00000040)
#define PADS_BANK0_GPIO12_IE_MSB _u(6)
#define PADS_BANK0_GPIO12_IE_LSB _u(6)
#define PADS_BANK0_GPIO12_IE_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO12_DRIVE
// Description : Drive strength.
// 0x0 -> 2mA
// 0x1 -> 4mA
// 0x2 -> 8mA
// 0x3 -> 12mA
#define PADS_BANK0_GPIO12_DRIVE_RESET _u(0x1)
#define PADS_BANK0_GPIO12_DRIVE_BITS _u(0x00000030)
#define PADS_BANK0_GPIO12_DRIVE_MSB _u(5)
#define PADS_BANK0_GPIO12_DRIVE_LSB _u(4)
#define PADS_BANK0_GPIO12_DRIVE_ACCESS "RW"
#define PADS_BANK0_GPIO12_DRIVE_VALUE_2MA _u(0x0)
#define PADS_BANK0_GPIO12_DRIVE_VALUE_4MA _u(0x1)
#define PADS_BANK0_GPIO12_DRIVE_VALUE_8MA _u(0x2)
#define PADS_BANK0_GPIO12_DRIVE_VALUE_12MA _u(0x3)
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO12_PUE
// Description : Pull up enable
#define PADS_BANK0_GPIO12_PUE_RESET _u(0x0)
#define PADS_BANK0_GPIO12_PUE_BITS _u(0x00000008)
#define PADS_BANK0_GPIO12_PUE_MSB _u(3)
#define PADS_BANK0_GPIO12_PUE_LSB _u(3)
#define PADS_BANK0_GPIO12_PUE_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO12_PDE
// Description : Pull down enable
#define PADS_BANK0_GPIO12_PDE_RESET _u(0x1)
#define PADS_BANK0_GPIO12_PDE_BITS _u(0x00000004)
#define PADS_BANK0_GPIO12_PDE_MSB _u(2)
#define PADS_BANK0_GPIO12_PDE_LSB _u(2)
#define PADS_BANK0_GPIO12_PDE_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO12_SCHMITT
// Description : Enable schmitt trigger
#define PADS_BANK0_GPIO12_SCHMITT_RESET _u(0x1)
#define PADS_BANK0_GPIO12_SCHMITT_BITS _u(0x00000002)
#define PADS_BANK0_GPIO12_SCHMITT_MSB _u(1)
#define PADS_BANK0_GPIO12_SCHMITT_LSB _u(1)
#define PADS_BANK0_GPIO12_SCHMITT_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO12_SLEWFAST
// Description : Slew rate control. 1 = Fast, 0 = Slow
#define PADS_BANK0_GPIO12_SLEWFAST_RESET _u(0x0)
#define PADS_BANK0_GPIO12_SLEWFAST_BITS _u(0x00000001)
#define PADS_BANK0_GPIO12_SLEWFAST_MSB _u(0)
#define PADS_BANK0_GPIO12_SLEWFAST_LSB _u(0)
#define PADS_BANK0_GPIO12_SLEWFAST_ACCESS "RW"
// =============================================================================
// Register : PADS_BANK0_GPIO13
// Description : Pad control register
#define PADS_BANK0_GPIO13_OFFSET _u(0x00000038)
#define PADS_BANK0_GPIO13_BITS _u(0x000000ff)
#define PADS_BANK0_GPIO13_RESET _u(0x00000056)
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO13_OD
// Description : Output disable. Has priority over output enable from
// peripherals
#define PADS_BANK0_GPIO13_OD_RESET _u(0x0)
#define PADS_BANK0_GPIO13_OD_BITS _u(0x00000080)
#define PADS_BANK0_GPIO13_OD_MSB _u(7)
#define PADS_BANK0_GPIO13_OD_LSB _u(7)
#define PADS_BANK0_GPIO13_OD_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO13_IE
// Description : Input enable
#define PADS_BANK0_GPIO13_IE_RESET _u(0x1)
#define PADS_BANK0_GPIO13_IE_BITS _u(0x00000040)
#define PADS_BANK0_GPIO13_IE_MSB _u(6)
#define PADS_BANK0_GPIO13_IE_LSB _u(6)
#define PADS_BANK0_GPIO13_IE_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO13_DRIVE
// Description : Drive strength.
// 0x0 -> 2mA
// 0x1 -> 4mA
// 0x2 -> 8mA
// 0x3 -> 12mA
#define PADS_BANK0_GPIO13_DRIVE_RESET _u(0x1)
#define PADS_BANK0_GPIO13_DRIVE_BITS _u(0x00000030)
#define PADS_BANK0_GPIO13_DRIVE_MSB _u(5)
#define PADS_BANK0_GPIO13_DRIVE_LSB _u(4)
#define PADS_BANK0_GPIO13_DRIVE_ACCESS "RW"
#define PADS_BANK0_GPIO13_DRIVE_VALUE_2MA _u(0x0)
#define PADS_BANK0_GPIO13_DRIVE_VALUE_4MA _u(0x1)
#define PADS_BANK0_GPIO13_DRIVE_VALUE_8MA _u(0x2)
#define PADS_BANK0_GPIO13_DRIVE_VALUE_12MA _u(0x3)
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO13_PUE
// Description : Pull up enable
#define PADS_BANK0_GPIO13_PUE_RESET _u(0x0)
#define PADS_BANK0_GPIO13_PUE_BITS _u(0x00000008)
#define PADS_BANK0_GPIO13_PUE_MSB _u(3)
#define PADS_BANK0_GPIO13_PUE_LSB _u(3)
#define PADS_BANK0_GPIO13_PUE_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO13_PDE
// Description : Pull down enable
#define PADS_BANK0_GPIO13_PDE_RESET _u(0x1)
#define PADS_BANK0_GPIO13_PDE_BITS _u(0x00000004)
#define PADS_BANK0_GPIO13_PDE_MSB _u(2)
#define PADS_BANK0_GPIO13_PDE_LSB _u(2)
#define PADS_BANK0_GPIO13_PDE_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO13_SCHMITT
// Description : Enable schmitt trigger
#define PADS_BANK0_GPIO13_SCHMITT_RESET _u(0x1)
#define PADS_BANK0_GPIO13_SCHMITT_BITS _u(0x00000002)
#define PADS_BANK0_GPIO13_SCHMITT_MSB _u(1)
#define PADS_BANK0_GPIO13_SCHMITT_LSB _u(1)
#define PADS_BANK0_GPIO13_SCHMITT_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO13_SLEWFAST
// Description : Slew rate control. 1 = Fast, 0 = Slow
#define PADS_BANK0_GPIO13_SLEWFAST_RESET _u(0x0)
#define PADS_BANK0_GPIO13_SLEWFAST_BITS _u(0x00000001)
#define PADS_BANK0_GPIO13_SLEWFAST_MSB _u(0)
#define PADS_BANK0_GPIO13_SLEWFAST_LSB _u(0)
#define PADS_BANK0_GPIO13_SLEWFAST_ACCESS "RW"
// =============================================================================
// Register : PADS_BANK0_GPIO14
// Description : Pad control register
#define PADS_BANK0_GPIO14_OFFSET _u(0x0000003c)
#define PADS_BANK0_GPIO14_BITS _u(0x000000ff)
#define PADS_BANK0_GPIO14_RESET _u(0x00000056)
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO14_OD
// Description : Output disable. Has priority over output enable from
// peripherals
#define PADS_BANK0_GPIO14_OD_RESET _u(0x0)
#define PADS_BANK0_GPIO14_OD_BITS _u(0x00000080)
#define PADS_BANK0_GPIO14_OD_MSB _u(7)
#define PADS_BANK0_GPIO14_OD_LSB _u(7)
#define PADS_BANK0_GPIO14_OD_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO14_IE
// Description : Input enable
#define PADS_BANK0_GPIO14_IE_RESET _u(0x1)
#define PADS_BANK0_GPIO14_IE_BITS _u(0x00000040)
#define PADS_BANK0_GPIO14_IE_MSB _u(6)
#define PADS_BANK0_GPIO14_IE_LSB _u(6)
#define PADS_BANK0_GPIO14_IE_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO14_DRIVE
// Description : Drive strength.
// 0x0 -> 2mA
// 0x1 -> 4mA
// 0x2 -> 8mA
// 0x3 -> 12mA
#define PADS_BANK0_GPIO14_DRIVE_RESET _u(0x1)
#define PADS_BANK0_GPIO14_DRIVE_BITS _u(0x00000030)
#define PADS_BANK0_GPIO14_DRIVE_MSB _u(5)
#define PADS_BANK0_GPIO14_DRIVE_LSB _u(4)
#define PADS_BANK0_GPIO14_DRIVE_ACCESS "RW"
#define PADS_BANK0_GPIO14_DRIVE_VALUE_2MA _u(0x0)
#define PADS_BANK0_GPIO14_DRIVE_VALUE_4MA _u(0x1)
#define PADS_BANK0_GPIO14_DRIVE_VALUE_8MA _u(0x2)
#define PADS_BANK0_GPIO14_DRIVE_VALUE_12MA _u(0x3)
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO14_PUE
// Description : Pull up enable
#define PADS_BANK0_GPIO14_PUE_RESET _u(0x0)
#define PADS_BANK0_GPIO14_PUE_BITS _u(0x00000008)
#define PADS_BANK0_GPIO14_PUE_MSB _u(3)
#define PADS_BANK0_GPIO14_PUE_LSB _u(3)
#define PADS_BANK0_GPIO14_PUE_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO14_PDE
// Description : Pull down enable
#define PADS_BANK0_GPIO14_PDE_RESET _u(0x1)
#define PADS_BANK0_GPIO14_PDE_BITS _u(0x00000004)
#define PADS_BANK0_GPIO14_PDE_MSB _u(2)
#define PADS_BANK0_GPIO14_PDE_LSB _u(2)
#define PADS_BANK0_GPIO14_PDE_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO14_SCHMITT
// Description : Enable schmitt trigger
#define PADS_BANK0_GPIO14_SCHMITT_RESET _u(0x1)
#define PADS_BANK0_GPIO14_SCHMITT_BITS _u(0x00000002)
#define PADS_BANK0_GPIO14_SCHMITT_MSB _u(1)
#define PADS_BANK0_GPIO14_SCHMITT_LSB _u(1)
#define PADS_BANK0_GPIO14_SCHMITT_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO14_SLEWFAST
// Description : Slew rate control. 1 = Fast, 0 = Slow
#define PADS_BANK0_GPIO14_SLEWFAST_RESET _u(0x0)
#define PADS_BANK0_GPIO14_SLEWFAST_BITS _u(0x00000001)
#define PADS_BANK0_GPIO14_SLEWFAST_MSB _u(0)
#define PADS_BANK0_GPIO14_SLEWFAST_LSB _u(0)
#define PADS_BANK0_GPIO14_SLEWFAST_ACCESS "RW"
// =============================================================================
// Register : PADS_BANK0_GPIO15
// Description : Pad control register
#define PADS_BANK0_GPIO15_OFFSET _u(0x00000040)
#define PADS_BANK0_GPIO15_BITS _u(0x000000ff)
#define PADS_BANK0_GPIO15_RESET _u(0x00000056)
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO15_OD
// Description : Output disable. Has priority over output enable from
// peripherals
#define PADS_BANK0_GPIO15_OD_RESET _u(0x0)
#define PADS_BANK0_GPIO15_OD_BITS _u(0x00000080)
#define PADS_BANK0_GPIO15_OD_MSB _u(7)
#define PADS_BANK0_GPIO15_OD_LSB _u(7)
#define PADS_BANK0_GPIO15_OD_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO15_IE
// Description : Input enable
#define PADS_BANK0_GPIO15_IE_RESET _u(0x1)
#define PADS_BANK0_GPIO15_IE_BITS _u(0x00000040)
#define PADS_BANK0_GPIO15_IE_MSB _u(6)
#define PADS_BANK0_GPIO15_IE_LSB _u(6)
#define PADS_BANK0_GPIO15_IE_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO15_DRIVE
// Description : Drive strength.
// 0x0 -> 2mA
// 0x1 -> 4mA
// 0x2 -> 8mA
// 0x3 -> 12mA
#define PADS_BANK0_GPIO15_DRIVE_RESET _u(0x1)
#define PADS_BANK0_GPIO15_DRIVE_BITS _u(0x00000030)
#define PADS_BANK0_GPIO15_DRIVE_MSB _u(5)
#define PADS_BANK0_GPIO15_DRIVE_LSB _u(4)
#define PADS_BANK0_GPIO15_DRIVE_ACCESS "RW"
#define PADS_BANK0_GPIO15_DRIVE_VALUE_2MA _u(0x0)
#define PADS_BANK0_GPIO15_DRIVE_VALUE_4MA _u(0x1)
#define PADS_BANK0_GPIO15_DRIVE_VALUE_8MA _u(0x2)
#define PADS_BANK0_GPIO15_DRIVE_VALUE_12MA _u(0x3)
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO15_PUE
// Description : Pull up enable
#define PADS_BANK0_GPIO15_PUE_RESET _u(0x0)
#define PADS_BANK0_GPIO15_PUE_BITS _u(0x00000008)
#define PADS_BANK0_GPIO15_PUE_MSB _u(3)
#define PADS_BANK0_GPIO15_PUE_LSB _u(3)
#define PADS_BANK0_GPIO15_PUE_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO15_PDE
// Description : Pull down enable
#define PADS_BANK0_GPIO15_PDE_RESET _u(0x1)
#define PADS_BANK0_GPIO15_PDE_BITS _u(0x00000004)
#define PADS_BANK0_GPIO15_PDE_MSB _u(2)
#define PADS_BANK0_GPIO15_PDE_LSB _u(2)
#define PADS_BANK0_GPIO15_PDE_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO15_SCHMITT
// Description : Enable schmitt trigger
#define PADS_BANK0_GPIO15_SCHMITT_RESET _u(0x1)
#define PADS_BANK0_GPIO15_SCHMITT_BITS _u(0x00000002)
#define PADS_BANK0_GPIO15_SCHMITT_MSB _u(1)
#define PADS_BANK0_GPIO15_SCHMITT_LSB _u(1)
#define PADS_BANK0_GPIO15_SCHMITT_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO15_SLEWFAST
// Description : Slew rate control. 1 = Fast, 0 = Slow
#define PADS_BANK0_GPIO15_SLEWFAST_RESET _u(0x0)
#define PADS_BANK0_GPIO15_SLEWFAST_BITS _u(0x00000001)
#define PADS_BANK0_GPIO15_SLEWFAST_MSB _u(0)
#define PADS_BANK0_GPIO15_SLEWFAST_LSB _u(0)
#define PADS_BANK0_GPIO15_SLEWFAST_ACCESS "RW"
// =============================================================================
// Register : PADS_BANK0_GPIO16
// Description : Pad control register
#define PADS_BANK0_GPIO16_OFFSET _u(0x00000044)
#define PADS_BANK0_GPIO16_BITS _u(0x000000ff)
#define PADS_BANK0_GPIO16_RESET _u(0x00000056)
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO16_OD
// Description : Output disable. Has priority over output enable from
// peripherals
#define PADS_BANK0_GPIO16_OD_RESET _u(0x0)
#define PADS_BANK0_GPIO16_OD_BITS _u(0x00000080)
#define PADS_BANK0_GPIO16_OD_MSB _u(7)
#define PADS_BANK0_GPIO16_OD_LSB _u(7)
#define PADS_BANK0_GPIO16_OD_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO16_IE
// Description : Input enable
#define PADS_BANK0_GPIO16_IE_RESET _u(0x1)
#define PADS_BANK0_GPIO16_IE_BITS _u(0x00000040)
#define PADS_BANK0_GPIO16_IE_MSB _u(6)
#define PADS_BANK0_GPIO16_IE_LSB _u(6)
#define PADS_BANK0_GPIO16_IE_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO16_DRIVE
// Description : Drive strength.
// 0x0 -> 2mA
// 0x1 -> 4mA
// 0x2 -> 8mA
// 0x3 -> 12mA
#define PADS_BANK0_GPIO16_DRIVE_RESET _u(0x1)
#define PADS_BANK0_GPIO16_DRIVE_BITS _u(0x00000030)
#define PADS_BANK0_GPIO16_DRIVE_MSB _u(5)
#define PADS_BANK0_GPIO16_DRIVE_LSB _u(4)
#define PADS_BANK0_GPIO16_DRIVE_ACCESS "RW"
#define PADS_BANK0_GPIO16_DRIVE_VALUE_2MA _u(0x0)
#define PADS_BANK0_GPIO16_DRIVE_VALUE_4MA _u(0x1)
#define PADS_BANK0_GPIO16_DRIVE_VALUE_8MA _u(0x2)
#define PADS_BANK0_GPIO16_DRIVE_VALUE_12MA _u(0x3)
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO16_PUE
// Description : Pull up enable
#define PADS_BANK0_GPIO16_PUE_RESET _u(0x0)
#define PADS_BANK0_GPIO16_PUE_BITS _u(0x00000008)
#define PADS_BANK0_GPIO16_PUE_MSB _u(3)
#define PADS_BANK0_GPIO16_PUE_LSB _u(3)
#define PADS_BANK0_GPIO16_PUE_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO16_PDE
// Description : Pull down enable
#define PADS_BANK0_GPIO16_PDE_RESET _u(0x1)
#define PADS_BANK0_GPIO16_PDE_BITS _u(0x00000004)
#define PADS_BANK0_GPIO16_PDE_MSB _u(2)
#define PADS_BANK0_GPIO16_PDE_LSB _u(2)
#define PADS_BANK0_GPIO16_PDE_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO16_SCHMITT
// Description : Enable schmitt trigger
#define PADS_BANK0_GPIO16_SCHMITT_RESET _u(0x1)
#define PADS_BANK0_GPIO16_SCHMITT_BITS _u(0x00000002)
#define PADS_BANK0_GPIO16_SCHMITT_MSB _u(1)
#define PADS_BANK0_GPIO16_SCHMITT_LSB _u(1)
#define PADS_BANK0_GPIO16_SCHMITT_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO16_SLEWFAST
// Description : Slew rate control. 1 = Fast, 0 = Slow
#define PADS_BANK0_GPIO16_SLEWFAST_RESET _u(0x0)
#define PADS_BANK0_GPIO16_SLEWFAST_BITS _u(0x00000001)
#define PADS_BANK0_GPIO16_SLEWFAST_MSB _u(0)
#define PADS_BANK0_GPIO16_SLEWFAST_LSB _u(0)
#define PADS_BANK0_GPIO16_SLEWFAST_ACCESS "RW"
// =============================================================================
// Register : PADS_BANK0_GPIO17
// Description : Pad control register
#define PADS_BANK0_GPIO17_OFFSET _u(0x00000048)
#define PADS_BANK0_GPIO17_BITS _u(0x000000ff)
#define PADS_BANK0_GPIO17_RESET _u(0x00000056)
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO17_OD
// Description : Output disable. Has priority over output enable from
// peripherals
#define PADS_BANK0_GPIO17_OD_RESET _u(0x0)
#define PADS_BANK0_GPIO17_OD_BITS _u(0x00000080)
#define PADS_BANK0_GPIO17_OD_MSB _u(7)
#define PADS_BANK0_GPIO17_OD_LSB _u(7)
#define PADS_BANK0_GPIO17_OD_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO17_IE
// Description : Input enable
#define PADS_BANK0_GPIO17_IE_RESET _u(0x1)
#define PADS_BANK0_GPIO17_IE_BITS _u(0x00000040)
#define PADS_BANK0_GPIO17_IE_MSB _u(6)
#define PADS_BANK0_GPIO17_IE_LSB _u(6)
#define PADS_BANK0_GPIO17_IE_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO17_DRIVE
// Description : Drive strength.
// 0x0 -> 2mA
// 0x1 -> 4mA
// 0x2 -> 8mA
// 0x3 -> 12mA
#define PADS_BANK0_GPIO17_DRIVE_RESET _u(0x1)
#define PADS_BANK0_GPIO17_DRIVE_BITS _u(0x00000030)
#define PADS_BANK0_GPIO17_DRIVE_MSB _u(5)
#define PADS_BANK0_GPIO17_DRIVE_LSB _u(4)
#define PADS_BANK0_GPIO17_DRIVE_ACCESS "RW"
#define PADS_BANK0_GPIO17_DRIVE_VALUE_2MA _u(0x0)
#define PADS_BANK0_GPIO17_DRIVE_VALUE_4MA _u(0x1)
#define PADS_BANK0_GPIO17_DRIVE_VALUE_8MA _u(0x2)
#define PADS_BANK0_GPIO17_DRIVE_VALUE_12MA _u(0x3)
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO17_PUE
// Description : Pull up enable
#define PADS_BANK0_GPIO17_PUE_RESET _u(0x0)
#define PADS_BANK0_GPIO17_PUE_BITS _u(0x00000008)
#define PADS_BANK0_GPIO17_PUE_MSB _u(3)
#define PADS_BANK0_GPIO17_PUE_LSB _u(3)
#define PADS_BANK0_GPIO17_PUE_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO17_PDE
// Description : Pull down enable
#define PADS_BANK0_GPIO17_PDE_RESET _u(0x1)
#define PADS_BANK0_GPIO17_PDE_BITS _u(0x00000004)
#define PADS_BANK0_GPIO17_PDE_MSB _u(2)
#define PADS_BANK0_GPIO17_PDE_LSB _u(2)
#define PADS_BANK0_GPIO17_PDE_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO17_SCHMITT
// Description : Enable schmitt trigger
#define PADS_BANK0_GPIO17_SCHMITT_RESET _u(0x1)
#define PADS_BANK0_GPIO17_SCHMITT_BITS _u(0x00000002)
#define PADS_BANK0_GPIO17_SCHMITT_MSB _u(1)
#define PADS_BANK0_GPIO17_SCHMITT_LSB _u(1)
#define PADS_BANK0_GPIO17_SCHMITT_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO17_SLEWFAST
// Description : Slew rate control. 1 = Fast, 0 = Slow
#define PADS_BANK0_GPIO17_SLEWFAST_RESET _u(0x0)
#define PADS_BANK0_GPIO17_SLEWFAST_BITS _u(0x00000001)
#define PADS_BANK0_GPIO17_SLEWFAST_MSB _u(0)
#define PADS_BANK0_GPIO17_SLEWFAST_LSB _u(0)
#define PADS_BANK0_GPIO17_SLEWFAST_ACCESS "RW"
// =============================================================================
// Register : PADS_BANK0_GPIO18
// Description : Pad control register
#define PADS_BANK0_GPIO18_OFFSET _u(0x0000004c)
#define PADS_BANK0_GPIO18_BITS _u(0x000000ff)
#define PADS_BANK0_GPIO18_RESET _u(0x00000056)
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO18_OD
// Description : Output disable. Has priority over output enable from
// peripherals
#define PADS_BANK0_GPIO18_OD_RESET _u(0x0)
#define PADS_BANK0_GPIO18_OD_BITS _u(0x00000080)
#define PADS_BANK0_GPIO18_OD_MSB _u(7)
#define PADS_BANK0_GPIO18_OD_LSB _u(7)
#define PADS_BANK0_GPIO18_OD_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO18_IE
// Description : Input enable
#define PADS_BANK0_GPIO18_IE_RESET _u(0x1)
#define PADS_BANK0_GPIO18_IE_BITS _u(0x00000040)
#define PADS_BANK0_GPIO18_IE_MSB _u(6)
#define PADS_BANK0_GPIO18_IE_LSB _u(6)
#define PADS_BANK0_GPIO18_IE_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO18_DRIVE
// Description : Drive strength.
// 0x0 -> 2mA
// 0x1 -> 4mA
// 0x2 -> 8mA
// 0x3 -> 12mA
#define PADS_BANK0_GPIO18_DRIVE_RESET _u(0x1)
#define PADS_BANK0_GPIO18_DRIVE_BITS _u(0x00000030)
#define PADS_BANK0_GPIO18_DRIVE_MSB _u(5)
#define PADS_BANK0_GPIO18_DRIVE_LSB _u(4)
#define PADS_BANK0_GPIO18_DRIVE_ACCESS "RW"
#define PADS_BANK0_GPIO18_DRIVE_VALUE_2MA _u(0x0)
#define PADS_BANK0_GPIO18_DRIVE_VALUE_4MA _u(0x1)
#define PADS_BANK0_GPIO18_DRIVE_VALUE_8MA _u(0x2)
#define PADS_BANK0_GPIO18_DRIVE_VALUE_12MA _u(0x3)
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO18_PUE
// Description : Pull up enable
#define PADS_BANK0_GPIO18_PUE_RESET _u(0x0)
#define PADS_BANK0_GPIO18_PUE_BITS _u(0x00000008)
#define PADS_BANK0_GPIO18_PUE_MSB _u(3)
#define PADS_BANK0_GPIO18_PUE_LSB _u(3)
#define PADS_BANK0_GPIO18_PUE_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO18_PDE
// Description : Pull down enable
#define PADS_BANK0_GPIO18_PDE_RESET _u(0x1)
#define PADS_BANK0_GPIO18_PDE_BITS _u(0x00000004)
#define PADS_BANK0_GPIO18_PDE_MSB _u(2)
#define PADS_BANK0_GPIO18_PDE_LSB _u(2)
#define PADS_BANK0_GPIO18_PDE_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO18_SCHMITT
// Description : Enable schmitt trigger
#define PADS_BANK0_GPIO18_SCHMITT_RESET _u(0x1)
#define PADS_BANK0_GPIO18_SCHMITT_BITS _u(0x00000002)
#define PADS_BANK0_GPIO18_SCHMITT_MSB _u(1)
#define PADS_BANK0_GPIO18_SCHMITT_LSB _u(1)
#define PADS_BANK0_GPIO18_SCHMITT_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO18_SLEWFAST
// Description : Slew rate control. 1 = Fast, 0 = Slow
#define PADS_BANK0_GPIO18_SLEWFAST_RESET _u(0x0)
#define PADS_BANK0_GPIO18_SLEWFAST_BITS _u(0x00000001)
#define PADS_BANK0_GPIO18_SLEWFAST_MSB _u(0)
#define PADS_BANK0_GPIO18_SLEWFAST_LSB _u(0)
#define PADS_BANK0_GPIO18_SLEWFAST_ACCESS "RW"
// =============================================================================
// Register : PADS_BANK0_GPIO19
// Description : Pad control register
#define PADS_BANK0_GPIO19_OFFSET _u(0x00000050)
#define PADS_BANK0_GPIO19_BITS _u(0x000000ff)
#define PADS_BANK0_GPIO19_RESET _u(0x00000056)
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO19_OD
// Description : Output disable. Has priority over output enable from
// peripherals
#define PADS_BANK0_GPIO19_OD_RESET _u(0x0)
#define PADS_BANK0_GPIO19_OD_BITS _u(0x00000080)
#define PADS_BANK0_GPIO19_OD_MSB _u(7)
#define PADS_BANK0_GPIO19_OD_LSB _u(7)
#define PADS_BANK0_GPIO19_OD_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO19_IE
// Description : Input enable
#define PADS_BANK0_GPIO19_IE_RESET _u(0x1)
#define PADS_BANK0_GPIO19_IE_BITS _u(0x00000040)
#define PADS_BANK0_GPIO19_IE_MSB _u(6)
#define PADS_BANK0_GPIO19_IE_LSB _u(6)
#define PADS_BANK0_GPIO19_IE_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO19_DRIVE
// Description : Drive strength.
// 0x0 -> 2mA
// 0x1 -> 4mA
// 0x2 -> 8mA
// 0x3 -> 12mA
#define PADS_BANK0_GPIO19_DRIVE_RESET _u(0x1)
#define PADS_BANK0_GPIO19_DRIVE_BITS _u(0x00000030)
#define PADS_BANK0_GPIO19_DRIVE_MSB _u(5)
#define PADS_BANK0_GPIO19_DRIVE_LSB _u(4)
#define PADS_BANK0_GPIO19_DRIVE_ACCESS "RW"
#define PADS_BANK0_GPIO19_DRIVE_VALUE_2MA _u(0x0)
#define PADS_BANK0_GPIO19_DRIVE_VALUE_4MA _u(0x1)
#define PADS_BANK0_GPIO19_DRIVE_VALUE_8MA _u(0x2)
#define PADS_BANK0_GPIO19_DRIVE_VALUE_12MA _u(0x3)
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO19_PUE
// Description : Pull up enable
#define PADS_BANK0_GPIO19_PUE_RESET _u(0x0)
#define PADS_BANK0_GPIO19_PUE_BITS _u(0x00000008)
#define PADS_BANK0_GPIO19_PUE_MSB _u(3)
#define PADS_BANK0_GPIO19_PUE_LSB _u(3)
#define PADS_BANK0_GPIO19_PUE_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO19_PDE
// Description : Pull down enable
#define PADS_BANK0_GPIO19_PDE_RESET _u(0x1)
#define PADS_BANK0_GPIO19_PDE_BITS _u(0x00000004)
#define PADS_BANK0_GPIO19_PDE_MSB _u(2)
#define PADS_BANK0_GPIO19_PDE_LSB _u(2)
#define PADS_BANK0_GPIO19_PDE_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO19_SCHMITT
// Description : Enable schmitt trigger
#define PADS_BANK0_GPIO19_SCHMITT_RESET _u(0x1)
#define PADS_BANK0_GPIO19_SCHMITT_BITS _u(0x00000002)
#define PADS_BANK0_GPIO19_SCHMITT_MSB _u(1)
#define PADS_BANK0_GPIO19_SCHMITT_LSB _u(1)
#define PADS_BANK0_GPIO19_SCHMITT_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO19_SLEWFAST
// Description : Slew rate control. 1 = Fast, 0 = Slow
#define PADS_BANK0_GPIO19_SLEWFAST_RESET _u(0x0)
#define PADS_BANK0_GPIO19_SLEWFAST_BITS _u(0x00000001)
#define PADS_BANK0_GPIO19_SLEWFAST_MSB _u(0)
#define PADS_BANK0_GPIO19_SLEWFAST_LSB _u(0)
#define PADS_BANK0_GPIO19_SLEWFAST_ACCESS "RW"
// =============================================================================
// Register : PADS_BANK0_GPIO20
// Description : Pad control register
#define PADS_BANK0_GPIO20_OFFSET _u(0x00000054)
#define PADS_BANK0_GPIO20_BITS _u(0x000000ff)
#define PADS_BANK0_GPIO20_RESET _u(0x00000056)
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO20_OD
// Description : Output disable. Has priority over output enable from
// peripherals
#define PADS_BANK0_GPIO20_OD_RESET _u(0x0)
#define PADS_BANK0_GPIO20_OD_BITS _u(0x00000080)
#define PADS_BANK0_GPIO20_OD_MSB _u(7)
#define PADS_BANK0_GPIO20_OD_LSB _u(7)
#define PADS_BANK0_GPIO20_OD_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO20_IE
// Description : Input enable
#define PADS_BANK0_GPIO20_IE_RESET _u(0x1)
#define PADS_BANK0_GPIO20_IE_BITS _u(0x00000040)
#define PADS_BANK0_GPIO20_IE_MSB _u(6)
#define PADS_BANK0_GPIO20_IE_LSB _u(6)
#define PADS_BANK0_GPIO20_IE_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO20_DRIVE
// Description : Drive strength.
// 0x0 -> 2mA
// 0x1 -> 4mA
// 0x2 -> 8mA
// 0x3 -> 12mA
#define PADS_BANK0_GPIO20_DRIVE_RESET _u(0x1)
#define PADS_BANK0_GPIO20_DRIVE_BITS _u(0x00000030)
#define PADS_BANK0_GPIO20_DRIVE_MSB _u(5)
#define PADS_BANK0_GPIO20_DRIVE_LSB _u(4)
#define PADS_BANK0_GPIO20_DRIVE_ACCESS "RW"
#define PADS_BANK0_GPIO20_DRIVE_VALUE_2MA _u(0x0)
#define PADS_BANK0_GPIO20_DRIVE_VALUE_4MA _u(0x1)
#define PADS_BANK0_GPIO20_DRIVE_VALUE_8MA _u(0x2)
#define PADS_BANK0_GPIO20_DRIVE_VALUE_12MA _u(0x3)
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO20_PUE
// Description : Pull up enable
#define PADS_BANK0_GPIO20_PUE_RESET _u(0x0)
#define PADS_BANK0_GPIO20_PUE_BITS _u(0x00000008)
#define PADS_BANK0_GPIO20_PUE_MSB _u(3)
#define PADS_BANK0_GPIO20_PUE_LSB _u(3)
#define PADS_BANK0_GPIO20_PUE_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO20_PDE
// Description : Pull down enable
#define PADS_BANK0_GPIO20_PDE_RESET _u(0x1)
#define PADS_BANK0_GPIO20_PDE_BITS _u(0x00000004)
#define PADS_BANK0_GPIO20_PDE_MSB _u(2)
#define PADS_BANK0_GPIO20_PDE_LSB _u(2)
#define PADS_BANK0_GPIO20_PDE_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO20_SCHMITT
// Description : Enable schmitt trigger
#define PADS_BANK0_GPIO20_SCHMITT_RESET _u(0x1)
#define PADS_BANK0_GPIO20_SCHMITT_BITS _u(0x00000002)
#define PADS_BANK0_GPIO20_SCHMITT_MSB _u(1)
#define PADS_BANK0_GPIO20_SCHMITT_LSB _u(1)
#define PADS_BANK0_GPIO20_SCHMITT_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO20_SLEWFAST
// Description : Slew rate control. 1 = Fast, 0 = Slow
#define PADS_BANK0_GPIO20_SLEWFAST_RESET _u(0x0)
#define PADS_BANK0_GPIO20_SLEWFAST_BITS _u(0x00000001)
#define PADS_BANK0_GPIO20_SLEWFAST_MSB _u(0)
#define PADS_BANK0_GPIO20_SLEWFAST_LSB _u(0)
#define PADS_BANK0_GPIO20_SLEWFAST_ACCESS "RW"
// =============================================================================
// Register : PADS_BANK0_GPIO21
// Description : Pad control register
#define PADS_BANK0_GPIO21_OFFSET _u(0x00000058)
#define PADS_BANK0_GPIO21_BITS _u(0x000000ff)
#define PADS_BANK0_GPIO21_RESET _u(0x00000056)
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO21_OD
// Description : Output disable. Has priority over output enable from
// peripherals
#define PADS_BANK0_GPIO21_OD_RESET _u(0x0)
#define PADS_BANK0_GPIO21_OD_BITS _u(0x00000080)
#define PADS_BANK0_GPIO21_OD_MSB _u(7)
#define PADS_BANK0_GPIO21_OD_LSB _u(7)
#define PADS_BANK0_GPIO21_OD_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO21_IE
// Description : Input enable
#define PADS_BANK0_GPIO21_IE_RESET _u(0x1)
#define PADS_BANK0_GPIO21_IE_BITS _u(0x00000040)
#define PADS_BANK0_GPIO21_IE_MSB _u(6)
#define PADS_BANK0_GPIO21_IE_LSB _u(6)
#define PADS_BANK0_GPIO21_IE_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO21_DRIVE
// Description : Drive strength.
// 0x0 -> 2mA
// 0x1 -> 4mA
// 0x2 -> 8mA
// 0x3 -> 12mA
#define PADS_BANK0_GPIO21_DRIVE_RESET _u(0x1)
#define PADS_BANK0_GPIO21_DRIVE_BITS _u(0x00000030)
#define PADS_BANK0_GPIO21_DRIVE_MSB _u(5)
#define PADS_BANK0_GPIO21_DRIVE_LSB _u(4)
#define PADS_BANK0_GPIO21_DRIVE_ACCESS "RW"
#define PADS_BANK0_GPIO21_DRIVE_VALUE_2MA _u(0x0)
#define PADS_BANK0_GPIO21_DRIVE_VALUE_4MA _u(0x1)
#define PADS_BANK0_GPIO21_DRIVE_VALUE_8MA _u(0x2)
#define PADS_BANK0_GPIO21_DRIVE_VALUE_12MA _u(0x3)
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO21_PUE
// Description : Pull up enable
#define PADS_BANK0_GPIO21_PUE_RESET _u(0x0)
#define PADS_BANK0_GPIO21_PUE_BITS _u(0x00000008)
#define PADS_BANK0_GPIO21_PUE_MSB _u(3)
#define PADS_BANK0_GPIO21_PUE_LSB _u(3)
#define PADS_BANK0_GPIO21_PUE_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO21_PDE
// Description : Pull down enable
#define PADS_BANK0_GPIO21_PDE_RESET _u(0x1)
#define PADS_BANK0_GPIO21_PDE_BITS _u(0x00000004)
#define PADS_BANK0_GPIO21_PDE_MSB _u(2)
#define PADS_BANK0_GPIO21_PDE_LSB _u(2)
#define PADS_BANK0_GPIO21_PDE_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO21_SCHMITT
// Description : Enable schmitt trigger
#define PADS_BANK0_GPIO21_SCHMITT_RESET _u(0x1)
#define PADS_BANK0_GPIO21_SCHMITT_BITS _u(0x00000002)
#define PADS_BANK0_GPIO21_SCHMITT_MSB _u(1)
#define PADS_BANK0_GPIO21_SCHMITT_LSB _u(1)
#define PADS_BANK0_GPIO21_SCHMITT_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO21_SLEWFAST
// Description : Slew rate control. 1 = Fast, 0 = Slow
#define PADS_BANK0_GPIO21_SLEWFAST_RESET _u(0x0)
#define PADS_BANK0_GPIO21_SLEWFAST_BITS _u(0x00000001)
#define PADS_BANK0_GPIO21_SLEWFAST_MSB _u(0)
#define PADS_BANK0_GPIO21_SLEWFAST_LSB _u(0)
#define PADS_BANK0_GPIO21_SLEWFAST_ACCESS "RW"
// =============================================================================
// Register : PADS_BANK0_GPIO22
// Description : Pad control register
#define PADS_BANK0_GPIO22_OFFSET _u(0x0000005c)
#define PADS_BANK0_GPIO22_BITS _u(0x000000ff)
#define PADS_BANK0_GPIO22_RESET _u(0x00000056)
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO22_OD
// Description : Output disable. Has priority over output enable from
// peripherals
#define PADS_BANK0_GPIO22_OD_RESET _u(0x0)
#define PADS_BANK0_GPIO22_OD_BITS _u(0x00000080)
#define PADS_BANK0_GPIO22_OD_MSB _u(7)
#define PADS_BANK0_GPIO22_OD_LSB _u(7)
#define PADS_BANK0_GPIO22_OD_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO22_IE
// Description : Input enable
#define PADS_BANK0_GPIO22_IE_RESET _u(0x1)
#define PADS_BANK0_GPIO22_IE_BITS _u(0x00000040)
#define PADS_BANK0_GPIO22_IE_MSB _u(6)
#define PADS_BANK0_GPIO22_IE_LSB _u(6)
#define PADS_BANK0_GPIO22_IE_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO22_DRIVE
// Description : Drive strength.
// 0x0 -> 2mA
// 0x1 -> 4mA
// 0x2 -> 8mA
// 0x3 -> 12mA
#define PADS_BANK0_GPIO22_DRIVE_RESET _u(0x1)
#define PADS_BANK0_GPIO22_DRIVE_BITS _u(0x00000030)
#define PADS_BANK0_GPIO22_DRIVE_MSB _u(5)
#define PADS_BANK0_GPIO22_DRIVE_LSB _u(4)
#define PADS_BANK0_GPIO22_DRIVE_ACCESS "RW"
#define PADS_BANK0_GPIO22_DRIVE_VALUE_2MA _u(0x0)
#define PADS_BANK0_GPIO22_DRIVE_VALUE_4MA _u(0x1)
#define PADS_BANK0_GPIO22_DRIVE_VALUE_8MA _u(0x2)
#define PADS_BANK0_GPIO22_DRIVE_VALUE_12MA _u(0x3)
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO22_PUE
// Description : Pull up enable
#define PADS_BANK0_GPIO22_PUE_RESET _u(0x0)
#define PADS_BANK0_GPIO22_PUE_BITS _u(0x00000008)
#define PADS_BANK0_GPIO22_PUE_MSB _u(3)
#define PADS_BANK0_GPIO22_PUE_LSB _u(3)
#define PADS_BANK0_GPIO22_PUE_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO22_PDE
// Description : Pull down enable
#define PADS_BANK0_GPIO22_PDE_RESET _u(0x1)
#define PADS_BANK0_GPIO22_PDE_BITS _u(0x00000004)
#define PADS_BANK0_GPIO22_PDE_MSB _u(2)
#define PADS_BANK0_GPIO22_PDE_LSB _u(2)
#define PADS_BANK0_GPIO22_PDE_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO22_SCHMITT
// Description : Enable schmitt trigger
#define PADS_BANK0_GPIO22_SCHMITT_RESET _u(0x1)
#define PADS_BANK0_GPIO22_SCHMITT_BITS _u(0x00000002)
#define PADS_BANK0_GPIO22_SCHMITT_MSB _u(1)
#define PADS_BANK0_GPIO22_SCHMITT_LSB _u(1)
#define PADS_BANK0_GPIO22_SCHMITT_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO22_SLEWFAST
// Description : Slew rate control. 1 = Fast, 0 = Slow
#define PADS_BANK0_GPIO22_SLEWFAST_RESET _u(0x0)
#define PADS_BANK0_GPIO22_SLEWFAST_BITS _u(0x00000001)
#define PADS_BANK0_GPIO22_SLEWFAST_MSB _u(0)
#define PADS_BANK0_GPIO22_SLEWFAST_LSB _u(0)
#define PADS_BANK0_GPIO22_SLEWFAST_ACCESS "RW"
// =============================================================================
// Register : PADS_BANK0_GPIO23
// Description : Pad control register
#define PADS_BANK0_GPIO23_OFFSET _u(0x00000060)
#define PADS_BANK0_GPIO23_BITS _u(0x000000ff)
#define PADS_BANK0_GPIO23_RESET _u(0x00000056)
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO23_OD
// Description : Output disable. Has priority over output enable from
// peripherals
#define PADS_BANK0_GPIO23_OD_RESET _u(0x0)
#define PADS_BANK0_GPIO23_OD_BITS _u(0x00000080)
#define PADS_BANK0_GPIO23_OD_MSB _u(7)
#define PADS_BANK0_GPIO23_OD_LSB _u(7)
#define PADS_BANK0_GPIO23_OD_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO23_IE
// Description : Input enable
#define PADS_BANK0_GPIO23_IE_RESET _u(0x1)
#define PADS_BANK0_GPIO23_IE_BITS _u(0x00000040)
#define PADS_BANK0_GPIO23_IE_MSB _u(6)
#define PADS_BANK0_GPIO23_IE_LSB _u(6)
#define PADS_BANK0_GPIO23_IE_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO23_DRIVE
// Description : Drive strength.
// 0x0 -> 2mA
// 0x1 -> 4mA
// 0x2 -> 8mA
// 0x3 -> 12mA
#define PADS_BANK0_GPIO23_DRIVE_RESET _u(0x1)
#define PADS_BANK0_GPIO23_DRIVE_BITS _u(0x00000030)
#define PADS_BANK0_GPIO23_DRIVE_MSB _u(5)
#define PADS_BANK0_GPIO23_DRIVE_LSB _u(4)
#define PADS_BANK0_GPIO23_DRIVE_ACCESS "RW"
#define PADS_BANK0_GPIO23_DRIVE_VALUE_2MA _u(0x0)
#define PADS_BANK0_GPIO23_DRIVE_VALUE_4MA _u(0x1)
#define PADS_BANK0_GPIO23_DRIVE_VALUE_8MA _u(0x2)
#define PADS_BANK0_GPIO23_DRIVE_VALUE_12MA _u(0x3)
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO23_PUE
// Description : Pull up enable
#define PADS_BANK0_GPIO23_PUE_RESET _u(0x0)
#define PADS_BANK0_GPIO23_PUE_BITS _u(0x00000008)
#define PADS_BANK0_GPIO23_PUE_MSB _u(3)
#define PADS_BANK0_GPIO23_PUE_LSB _u(3)
#define PADS_BANK0_GPIO23_PUE_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO23_PDE
// Description : Pull down enable
#define PADS_BANK0_GPIO23_PDE_RESET _u(0x1)
#define PADS_BANK0_GPIO23_PDE_BITS _u(0x00000004)
#define PADS_BANK0_GPIO23_PDE_MSB _u(2)
#define PADS_BANK0_GPIO23_PDE_LSB _u(2)
#define PADS_BANK0_GPIO23_PDE_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO23_SCHMITT
// Description : Enable schmitt trigger
#define PADS_BANK0_GPIO23_SCHMITT_RESET _u(0x1)
#define PADS_BANK0_GPIO23_SCHMITT_BITS _u(0x00000002)
#define PADS_BANK0_GPIO23_SCHMITT_MSB _u(1)
#define PADS_BANK0_GPIO23_SCHMITT_LSB _u(1)
#define PADS_BANK0_GPIO23_SCHMITT_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO23_SLEWFAST
// Description : Slew rate control. 1 = Fast, 0 = Slow
#define PADS_BANK0_GPIO23_SLEWFAST_RESET _u(0x0)
#define PADS_BANK0_GPIO23_SLEWFAST_BITS _u(0x00000001)
#define PADS_BANK0_GPIO23_SLEWFAST_MSB _u(0)
#define PADS_BANK0_GPIO23_SLEWFAST_LSB _u(0)
#define PADS_BANK0_GPIO23_SLEWFAST_ACCESS "RW"
// =============================================================================
// Register : PADS_BANK0_GPIO24
// Description : Pad control register
#define PADS_BANK0_GPIO24_OFFSET _u(0x00000064)
#define PADS_BANK0_GPIO24_BITS _u(0x000000ff)
#define PADS_BANK0_GPIO24_RESET _u(0x00000056)
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO24_OD
// Description : Output disable. Has priority over output enable from
// peripherals
#define PADS_BANK0_GPIO24_OD_RESET _u(0x0)
#define PADS_BANK0_GPIO24_OD_BITS _u(0x00000080)
#define PADS_BANK0_GPIO24_OD_MSB _u(7)
#define PADS_BANK0_GPIO24_OD_LSB _u(7)
#define PADS_BANK0_GPIO24_OD_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO24_IE
// Description : Input enable
#define PADS_BANK0_GPIO24_IE_RESET _u(0x1)
#define PADS_BANK0_GPIO24_IE_BITS _u(0x00000040)
#define PADS_BANK0_GPIO24_IE_MSB _u(6)
#define PADS_BANK0_GPIO24_IE_LSB _u(6)
#define PADS_BANK0_GPIO24_IE_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO24_DRIVE
// Description : Drive strength.
// 0x0 -> 2mA
// 0x1 -> 4mA
// 0x2 -> 8mA
// 0x3 -> 12mA
#define PADS_BANK0_GPIO24_DRIVE_RESET _u(0x1)
#define PADS_BANK0_GPIO24_DRIVE_BITS _u(0x00000030)
#define PADS_BANK0_GPIO24_DRIVE_MSB _u(5)
#define PADS_BANK0_GPIO24_DRIVE_LSB _u(4)
#define PADS_BANK0_GPIO24_DRIVE_ACCESS "RW"
#define PADS_BANK0_GPIO24_DRIVE_VALUE_2MA _u(0x0)
#define PADS_BANK0_GPIO24_DRIVE_VALUE_4MA _u(0x1)
#define PADS_BANK0_GPIO24_DRIVE_VALUE_8MA _u(0x2)
#define PADS_BANK0_GPIO24_DRIVE_VALUE_12MA _u(0x3)
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO24_PUE
// Description : Pull up enable
#define PADS_BANK0_GPIO24_PUE_RESET _u(0x0)
#define PADS_BANK0_GPIO24_PUE_BITS _u(0x00000008)
#define PADS_BANK0_GPIO24_PUE_MSB _u(3)
#define PADS_BANK0_GPIO24_PUE_LSB _u(3)
#define PADS_BANK0_GPIO24_PUE_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO24_PDE
// Description : Pull down enable
#define PADS_BANK0_GPIO24_PDE_RESET _u(0x1)
#define PADS_BANK0_GPIO24_PDE_BITS _u(0x00000004)
#define PADS_BANK0_GPIO24_PDE_MSB _u(2)
#define PADS_BANK0_GPIO24_PDE_LSB _u(2)
#define PADS_BANK0_GPIO24_PDE_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO24_SCHMITT
// Description : Enable schmitt trigger
#define PADS_BANK0_GPIO24_SCHMITT_RESET _u(0x1)
#define PADS_BANK0_GPIO24_SCHMITT_BITS _u(0x00000002)
#define PADS_BANK0_GPIO24_SCHMITT_MSB _u(1)
#define PADS_BANK0_GPIO24_SCHMITT_LSB _u(1)
#define PADS_BANK0_GPIO24_SCHMITT_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO24_SLEWFAST
// Description : Slew rate control. 1 = Fast, 0 = Slow
#define PADS_BANK0_GPIO24_SLEWFAST_RESET _u(0x0)
#define PADS_BANK0_GPIO24_SLEWFAST_BITS _u(0x00000001)
#define PADS_BANK0_GPIO24_SLEWFAST_MSB _u(0)
#define PADS_BANK0_GPIO24_SLEWFAST_LSB _u(0)
#define PADS_BANK0_GPIO24_SLEWFAST_ACCESS "RW"
// =============================================================================
// Register : PADS_BANK0_GPIO25
// Description : Pad control register
#define PADS_BANK0_GPIO25_OFFSET _u(0x00000068)
#define PADS_BANK0_GPIO25_BITS _u(0x000000ff)
#define PADS_BANK0_GPIO25_RESET _u(0x00000056)
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO25_OD
// Description : Output disable. Has priority over output enable from
// peripherals
#define PADS_BANK0_GPIO25_OD_RESET _u(0x0)
#define PADS_BANK0_GPIO25_OD_BITS _u(0x00000080)
#define PADS_BANK0_GPIO25_OD_MSB _u(7)
#define PADS_BANK0_GPIO25_OD_LSB _u(7)
#define PADS_BANK0_GPIO25_OD_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO25_IE
// Description : Input enable
#define PADS_BANK0_GPIO25_IE_RESET _u(0x1)
#define PADS_BANK0_GPIO25_IE_BITS _u(0x00000040)
#define PADS_BANK0_GPIO25_IE_MSB _u(6)
#define PADS_BANK0_GPIO25_IE_LSB _u(6)
#define PADS_BANK0_GPIO25_IE_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO25_DRIVE
// Description : Drive strength.
// 0x0 -> 2mA
// 0x1 -> 4mA
// 0x2 -> 8mA
// 0x3 -> 12mA
#define PADS_BANK0_GPIO25_DRIVE_RESET _u(0x1)
#define PADS_BANK0_GPIO25_DRIVE_BITS _u(0x00000030)
#define PADS_BANK0_GPIO25_DRIVE_MSB _u(5)
#define PADS_BANK0_GPIO25_DRIVE_LSB _u(4)
#define PADS_BANK0_GPIO25_DRIVE_ACCESS "RW"
#define PADS_BANK0_GPIO25_DRIVE_VALUE_2MA _u(0x0)
#define PADS_BANK0_GPIO25_DRIVE_VALUE_4MA _u(0x1)
#define PADS_BANK0_GPIO25_DRIVE_VALUE_8MA _u(0x2)
#define PADS_BANK0_GPIO25_DRIVE_VALUE_12MA _u(0x3)
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO25_PUE
// Description : Pull up enable
#define PADS_BANK0_GPIO25_PUE_RESET _u(0x0)
#define PADS_BANK0_GPIO25_PUE_BITS _u(0x00000008)
#define PADS_BANK0_GPIO25_PUE_MSB _u(3)
#define PADS_BANK0_GPIO25_PUE_LSB _u(3)
#define PADS_BANK0_GPIO25_PUE_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO25_PDE
// Description : Pull down enable
#define PADS_BANK0_GPIO25_PDE_RESET _u(0x1)
#define PADS_BANK0_GPIO25_PDE_BITS _u(0x00000004)
#define PADS_BANK0_GPIO25_PDE_MSB _u(2)
#define PADS_BANK0_GPIO25_PDE_LSB _u(2)
#define PADS_BANK0_GPIO25_PDE_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO25_SCHMITT
// Description : Enable schmitt trigger
#define PADS_BANK0_GPIO25_SCHMITT_RESET _u(0x1)
#define PADS_BANK0_GPIO25_SCHMITT_BITS _u(0x00000002)
#define PADS_BANK0_GPIO25_SCHMITT_MSB _u(1)
#define PADS_BANK0_GPIO25_SCHMITT_LSB _u(1)
#define PADS_BANK0_GPIO25_SCHMITT_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO25_SLEWFAST
// Description : Slew rate control. 1 = Fast, 0 = Slow
#define PADS_BANK0_GPIO25_SLEWFAST_RESET _u(0x0)
#define PADS_BANK0_GPIO25_SLEWFAST_BITS _u(0x00000001)
#define PADS_BANK0_GPIO25_SLEWFAST_MSB _u(0)
#define PADS_BANK0_GPIO25_SLEWFAST_LSB _u(0)
#define PADS_BANK0_GPIO25_SLEWFAST_ACCESS "RW"
// =============================================================================
// Register : PADS_BANK0_GPIO26
// Description : Pad control register
#define PADS_BANK0_GPIO26_OFFSET _u(0x0000006c)
#define PADS_BANK0_GPIO26_BITS _u(0x000000ff)
#define PADS_BANK0_GPIO26_RESET _u(0x00000056)
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO26_OD
// Description : Output disable. Has priority over output enable from
// peripherals
#define PADS_BANK0_GPIO26_OD_RESET _u(0x0)
#define PADS_BANK0_GPIO26_OD_BITS _u(0x00000080)
#define PADS_BANK0_GPIO26_OD_MSB _u(7)
#define PADS_BANK0_GPIO26_OD_LSB _u(7)
#define PADS_BANK0_GPIO26_OD_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO26_IE
// Description : Input enable
#define PADS_BANK0_GPIO26_IE_RESET _u(0x1)
#define PADS_BANK0_GPIO26_IE_BITS _u(0x00000040)
#define PADS_BANK0_GPIO26_IE_MSB _u(6)
#define PADS_BANK0_GPIO26_IE_LSB _u(6)
#define PADS_BANK0_GPIO26_IE_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO26_DRIVE
// Description : Drive strength.
// 0x0 -> 2mA
// 0x1 -> 4mA
// 0x2 -> 8mA
// 0x3 -> 12mA
#define PADS_BANK0_GPIO26_DRIVE_RESET _u(0x1)
#define PADS_BANK0_GPIO26_DRIVE_BITS _u(0x00000030)
#define PADS_BANK0_GPIO26_DRIVE_MSB _u(5)
#define PADS_BANK0_GPIO26_DRIVE_LSB _u(4)
#define PADS_BANK0_GPIO26_DRIVE_ACCESS "RW"
#define PADS_BANK0_GPIO26_DRIVE_VALUE_2MA _u(0x0)
#define PADS_BANK0_GPIO26_DRIVE_VALUE_4MA _u(0x1)
#define PADS_BANK0_GPIO26_DRIVE_VALUE_8MA _u(0x2)
#define PADS_BANK0_GPIO26_DRIVE_VALUE_12MA _u(0x3)
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO26_PUE
// Description : Pull up enable
#define PADS_BANK0_GPIO26_PUE_RESET _u(0x0)
#define PADS_BANK0_GPIO26_PUE_BITS _u(0x00000008)
#define PADS_BANK0_GPIO26_PUE_MSB _u(3)
#define PADS_BANK0_GPIO26_PUE_LSB _u(3)
#define PADS_BANK0_GPIO26_PUE_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO26_PDE
// Description : Pull down enable
#define PADS_BANK0_GPIO26_PDE_RESET _u(0x1)
#define PADS_BANK0_GPIO26_PDE_BITS _u(0x00000004)
#define PADS_BANK0_GPIO26_PDE_MSB _u(2)
#define PADS_BANK0_GPIO26_PDE_LSB _u(2)
#define PADS_BANK0_GPIO26_PDE_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO26_SCHMITT
// Description : Enable schmitt trigger
#define PADS_BANK0_GPIO26_SCHMITT_RESET _u(0x1)
#define PADS_BANK0_GPIO26_SCHMITT_BITS _u(0x00000002)
#define PADS_BANK0_GPIO26_SCHMITT_MSB _u(1)
#define PADS_BANK0_GPIO26_SCHMITT_LSB _u(1)
#define PADS_BANK0_GPIO26_SCHMITT_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO26_SLEWFAST
// Description : Slew rate control. 1 = Fast, 0 = Slow
#define PADS_BANK0_GPIO26_SLEWFAST_RESET _u(0x0)
#define PADS_BANK0_GPIO26_SLEWFAST_BITS _u(0x00000001)
#define PADS_BANK0_GPIO26_SLEWFAST_MSB _u(0)
#define PADS_BANK0_GPIO26_SLEWFAST_LSB _u(0)
#define PADS_BANK0_GPIO26_SLEWFAST_ACCESS "RW"
// =============================================================================
// Register : PADS_BANK0_GPIO27
// Description : Pad control register
#define PADS_BANK0_GPIO27_OFFSET _u(0x00000070)
#define PADS_BANK0_GPIO27_BITS _u(0x000000ff)
#define PADS_BANK0_GPIO27_RESET _u(0x00000056)
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO27_OD
// Description : Output disable. Has priority over output enable from
// peripherals
#define PADS_BANK0_GPIO27_OD_RESET _u(0x0)
#define PADS_BANK0_GPIO27_OD_BITS _u(0x00000080)
#define PADS_BANK0_GPIO27_OD_MSB _u(7)
#define PADS_BANK0_GPIO27_OD_LSB _u(7)
#define PADS_BANK0_GPIO27_OD_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO27_IE
// Description : Input enable
#define PADS_BANK0_GPIO27_IE_RESET _u(0x1)
#define PADS_BANK0_GPIO27_IE_BITS _u(0x00000040)
#define PADS_BANK0_GPIO27_IE_MSB _u(6)
#define PADS_BANK0_GPIO27_IE_LSB _u(6)
#define PADS_BANK0_GPIO27_IE_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO27_DRIVE
// Description : Drive strength.
// 0x0 -> 2mA
// 0x1 -> 4mA
// 0x2 -> 8mA
// 0x3 -> 12mA
#define PADS_BANK0_GPIO27_DRIVE_RESET _u(0x1)
#define PADS_BANK0_GPIO27_DRIVE_BITS _u(0x00000030)
#define PADS_BANK0_GPIO27_DRIVE_MSB _u(5)
#define PADS_BANK0_GPIO27_DRIVE_LSB _u(4)
#define PADS_BANK0_GPIO27_DRIVE_ACCESS "RW"
#define PADS_BANK0_GPIO27_DRIVE_VALUE_2MA _u(0x0)
#define PADS_BANK0_GPIO27_DRIVE_VALUE_4MA _u(0x1)
#define PADS_BANK0_GPIO27_DRIVE_VALUE_8MA _u(0x2)
#define PADS_BANK0_GPIO27_DRIVE_VALUE_12MA _u(0x3)
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO27_PUE
// Description : Pull up enable
#define PADS_BANK0_GPIO27_PUE_RESET _u(0x0)
#define PADS_BANK0_GPIO27_PUE_BITS _u(0x00000008)
#define PADS_BANK0_GPIO27_PUE_MSB _u(3)
#define PADS_BANK0_GPIO27_PUE_LSB _u(3)
#define PADS_BANK0_GPIO27_PUE_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO27_PDE
// Description : Pull down enable
#define PADS_BANK0_GPIO27_PDE_RESET _u(0x1)
#define PADS_BANK0_GPIO27_PDE_BITS _u(0x00000004)
#define PADS_BANK0_GPIO27_PDE_MSB _u(2)
#define PADS_BANK0_GPIO27_PDE_LSB _u(2)
#define PADS_BANK0_GPIO27_PDE_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO27_SCHMITT
// Description : Enable schmitt trigger
#define PADS_BANK0_GPIO27_SCHMITT_RESET _u(0x1)
#define PADS_BANK0_GPIO27_SCHMITT_BITS _u(0x00000002)
#define PADS_BANK0_GPIO27_SCHMITT_MSB _u(1)
#define PADS_BANK0_GPIO27_SCHMITT_LSB _u(1)
#define PADS_BANK0_GPIO27_SCHMITT_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO27_SLEWFAST
// Description : Slew rate control. 1 = Fast, 0 = Slow
#define PADS_BANK0_GPIO27_SLEWFAST_RESET _u(0x0)
#define PADS_BANK0_GPIO27_SLEWFAST_BITS _u(0x00000001)
#define PADS_BANK0_GPIO27_SLEWFAST_MSB _u(0)
#define PADS_BANK0_GPIO27_SLEWFAST_LSB _u(0)
#define PADS_BANK0_GPIO27_SLEWFAST_ACCESS "RW"
// =============================================================================
// Register : PADS_BANK0_GPIO28
// Description : Pad control register
#define PADS_BANK0_GPIO28_OFFSET _u(0x00000074)
#define PADS_BANK0_GPIO28_BITS _u(0x000000ff)
#define PADS_BANK0_GPIO28_RESET _u(0x00000056)
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO28_OD
// Description : Output disable. Has priority over output enable from
// peripherals
#define PADS_BANK0_GPIO28_OD_RESET _u(0x0)
#define PADS_BANK0_GPIO28_OD_BITS _u(0x00000080)
#define PADS_BANK0_GPIO28_OD_MSB _u(7)
#define PADS_BANK0_GPIO28_OD_LSB _u(7)
#define PADS_BANK0_GPIO28_OD_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO28_IE
// Description : Input enable
#define PADS_BANK0_GPIO28_IE_RESET _u(0x1)
#define PADS_BANK0_GPIO28_IE_BITS _u(0x00000040)
#define PADS_BANK0_GPIO28_IE_MSB _u(6)
#define PADS_BANK0_GPIO28_IE_LSB _u(6)
#define PADS_BANK0_GPIO28_IE_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO28_DRIVE
// Description : Drive strength.
// 0x0 -> 2mA
// 0x1 -> 4mA
// 0x2 -> 8mA
// 0x3 -> 12mA
#define PADS_BANK0_GPIO28_DRIVE_RESET _u(0x1)
#define PADS_BANK0_GPIO28_DRIVE_BITS _u(0x00000030)
#define PADS_BANK0_GPIO28_DRIVE_MSB _u(5)
#define PADS_BANK0_GPIO28_DRIVE_LSB _u(4)
#define PADS_BANK0_GPIO28_DRIVE_ACCESS "RW"
#define PADS_BANK0_GPIO28_DRIVE_VALUE_2MA _u(0x0)
#define PADS_BANK0_GPIO28_DRIVE_VALUE_4MA _u(0x1)
#define PADS_BANK0_GPIO28_DRIVE_VALUE_8MA _u(0x2)
#define PADS_BANK0_GPIO28_DRIVE_VALUE_12MA _u(0x3)
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO28_PUE
// Description : Pull up enable
#define PADS_BANK0_GPIO28_PUE_RESET _u(0x0)
#define PADS_BANK0_GPIO28_PUE_BITS _u(0x00000008)
#define PADS_BANK0_GPIO28_PUE_MSB _u(3)
#define PADS_BANK0_GPIO28_PUE_LSB _u(3)
#define PADS_BANK0_GPIO28_PUE_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO28_PDE
// Description : Pull down enable
#define PADS_BANK0_GPIO28_PDE_RESET _u(0x1)
#define PADS_BANK0_GPIO28_PDE_BITS _u(0x00000004)
#define PADS_BANK0_GPIO28_PDE_MSB _u(2)
#define PADS_BANK0_GPIO28_PDE_LSB _u(2)
#define PADS_BANK0_GPIO28_PDE_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO28_SCHMITT
// Description : Enable schmitt trigger
#define PADS_BANK0_GPIO28_SCHMITT_RESET _u(0x1)
#define PADS_BANK0_GPIO28_SCHMITT_BITS _u(0x00000002)
#define PADS_BANK0_GPIO28_SCHMITT_MSB _u(1)
#define PADS_BANK0_GPIO28_SCHMITT_LSB _u(1)
#define PADS_BANK0_GPIO28_SCHMITT_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO28_SLEWFAST
// Description : Slew rate control. 1 = Fast, 0 = Slow
#define PADS_BANK0_GPIO28_SLEWFAST_RESET _u(0x0)
#define PADS_BANK0_GPIO28_SLEWFAST_BITS _u(0x00000001)
#define PADS_BANK0_GPIO28_SLEWFAST_MSB _u(0)
#define PADS_BANK0_GPIO28_SLEWFAST_LSB _u(0)
#define PADS_BANK0_GPIO28_SLEWFAST_ACCESS "RW"
// =============================================================================
// Register : PADS_BANK0_GPIO29
// Description : Pad control register
#define PADS_BANK0_GPIO29_OFFSET _u(0x00000078)
#define PADS_BANK0_GPIO29_BITS _u(0x000000ff)
#define PADS_BANK0_GPIO29_RESET _u(0x00000056)
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO29_OD
// Description : Output disable. Has priority over output enable from
// peripherals
#define PADS_BANK0_GPIO29_OD_RESET _u(0x0)
#define PADS_BANK0_GPIO29_OD_BITS _u(0x00000080)
#define PADS_BANK0_GPIO29_OD_MSB _u(7)
#define PADS_BANK0_GPIO29_OD_LSB _u(7)
#define PADS_BANK0_GPIO29_OD_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO29_IE
// Description : Input enable
#define PADS_BANK0_GPIO29_IE_RESET _u(0x1)
#define PADS_BANK0_GPIO29_IE_BITS _u(0x00000040)
#define PADS_BANK0_GPIO29_IE_MSB _u(6)
#define PADS_BANK0_GPIO29_IE_LSB _u(6)
#define PADS_BANK0_GPIO29_IE_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO29_DRIVE
// Description : Drive strength.
// 0x0 -> 2mA
// 0x1 -> 4mA
// 0x2 -> 8mA
// 0x3 -> 12mA
#define PADS_BANK0_GPIO29_DRIVE_RESET _u(0x1)
#define PADS_BANK0_GPIO29_DRIVE_BITS _u(0x00000030)
#define PADS_BANK0_GPIO29_DRIVE_MSB _u(5)
#define PADS_BANK0_GPIO29_DRIVE_LSB _u(4)
#define PADS_BANK0_GPIO29_DRIVE_ACCESS "RW"
#define PADS_BANK0_GPIO29_DRIVE_VALUE_2MA _u(0x0)
#define PADS_BANK0_GPIO29_DRIVE_VALUE_4MA _u(0x1)
#define PADS_BANK0_GPIO29_DRIVE_VALUE_8MA _u(0x2)
#define PADS_BANK0_GPIO29_DRIVE_VALUE_12MA _u(0x3)
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO29_PUE
// Description : Pull up enable
#define PADS_BANK0_GPIO29_PUE_RESET _u(0x0)
#define PADS_BANK0_GPIO29_PUE_BITS _u(0x00000008)
#define PADS_BANK0_GPIO29_PUE_MSB _u(3)
#define PADS_BANK0_GPIO29_PUE_LSB _u(3)
#define PADS_BANK0_GPIO29_PUE_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO29_PDE
// Description : Pull down enable
#define PADS_BANK0_GPIO29_PDE_RESET _u(0x1)
#define PADS_BANK0_GPIO29_PDE_BITS _u(0x00000004)
#define PADS_BANK0_GPIO29_PDE_MSB _u(2)
#define PADS_BANK0_GPIO29_PDE_LSB _u(2)
#define PADS_BANK0_GPIO29_PDE_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO29_SCHMITT
// Description : Enable schmitt trigger
#define PADS_BANK0_GPIO29_SCHMITT_RESET _u(0x1)
#define PADS_BANK0_GPIO29_SCHMITT_BITS _u(0x00000002)
#define PADS_BANK0_GPIO29_SCHMITT_MSB _u(1)
#define PADS_BANK0_GPIO29_SCHMITT_LSB _u(1)
#define PADS_BANK0_GPIO29_SCHMITT_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_GPIO29_SLEWFAST
// Description : Slew rate control. 1 = Fast, 0 = Slow
#define PADS_BANK0_GPIO29_SLEWFAST_RESET _u(0x0)
#define PADS_BANK0_GPIO29_SLEWFAST_BITS _u(0x00000001)
#define PADS_BANK0_GPIO29_SLEWFAST_MSB _u(0)
#define PADS_BANK0_GPIO29_SLEWFAST_LSB _u(0)
#define PADS_BANK0_GPIO29_SLEWFAST_ACCESS "RW"
// =============================================================================
// Register : PADS_BANK0_SWCLK
// Description : Pad control register
#define PADS_BANK0_SWCLK_OFFSET _u(0x0000007c)
#define PADS_BANK0_SWCLK_BITS _u(0x000000ff)
#define PADS_BANK0_SWCLK_RESET _u(0x000000da)
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_SWCLK_OD
// Description : Output disable. Has priority over output enable from
// peripherals
#define PADS_BANK0_SWCLK_OD_RESET _u(0x1)
#define PADS_BANK0_SWCLK_OD_BITS _u(0x00000080)
#define PADS_BANK0_SWCLK_OD_MSB _u(7)
#define PADS_BANK0_SWCLK_OD_LSB _u(7)
#define PADS_BANK0_SWCLK_OD_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_SWCLK_IE
// Description : Input enable
#define PADS_BANK0_SWCLK_IE_RESET _u(0x1)
#define PADS_BANK0_SWCLK_IE_BITS _u(0x00000040)
#define PADS_BANK0_SWCLK_IE_MSB _u(6)
#define PADS_BANK0_SWCLK_IE_LSB _u(6)
#define PADS_BANK0_SWCLK_IE_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_SWCLK_DRIVE
// Description : Drive strength.
// 0x0 -> 2mA
// 0x1 -> 4mA
// 0x2 -> 8mA
// 0x3 -> 12mA
#define PADS_BANK0_SWCLK_DRIVE_RESET _u(0x1)
#define PADS_BANK0_SWCLK_DRIVE_BITS _u(0x00000030)
#define PADS_BANK0_SWCLK_DRIVE_MSB _u(5)
#define PADS_BANK0_SWCLK_DRIVE_LSB _u(4)
#define PADS_BANK0_SWCLK_DRIVE_ACCESS "RW"
#define PADS_BANK0_SWCLK_DRIVE_VALUE_2MA _u(0x0)
#define PADS_BANK0_SWCLK_DRIVE_VALUE_4MA _u(0x1)
#define PADS_BANK0_SWCLK_DRIVE_VALUE_8MA _u(0x2)
#define PADS_BANK0_SWCLK_DRIVE_VALUE_12MA _u(0x3)
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_SWCLK_PUE
// Description : Pull up enable
#define PADS_BANK0_SWCLK_PUE_RESET _u(0x1)
#define PADS_BANK0_SWCLK_PUE_BITS _u(0x00000008)
#define PADS_BANK0_SWCLK_PUE_MSB _u(3)
#define PADS_BANK0_SWCLK_PUE_LSB _u(3)
#define PADS_BANK0_SWCLK_PUE_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_SWCLK_PDE
// Description : Pull down enable
#define PADS_BANK0_SWCLK_PDE_RESET _u(0x0)
#define PADS_BANK0_SWCLK_PDE_BITS _u(0x00000004)
#define PADS_BANK0_SWCLK_PDE_MSB _u(2)
#define PADS_BANK0_SWCLK_PDE_LSB _u(2)
#define PADS_BANK0_SWCLK_PDE_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_SWCLK_SCHMITT
// Description : Enable schmitt trigger
#define PADS_BANK0_SWCLK_SCHMITT_RESET _u(0x1)
#define PADS_BANK0_SWCLK_SCHMITT_BITS _u(0x00000002)
#define PADS_BANK0_SWCLK_SCHMITT_MSB _u(1)
#define PADS_BANK0_SWCLK_SCHMITT_LSB _u(1)
#define PADS_BANK0_SWCLK_SCHMITT_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_SWCLK_SLEWFAST
// Description : Slew rate control. 1 = Fast, 0 = Slow
#define PADS_BANK0_SWCLK_SLEWFAST_RESET _u(0x0)
#define PADS_BANK0_SWCLK_SLEWFAST_BITS _u(0x00000001)
#define PADS_BANK0_SWCLK_SLEWFAST_MSB _u(0)
#define PADS_BANK0_SWCLK_SLEWFAST_LSB _u(0)
#define PADS_BANK0_SWCLK_SLEWFAST_ACCESS "RW"
// =============================================================================
// Register : PADS_BANK0_SWD
// Description : Pad control register
#define PADS_BANK0_SWD_OFFSET _u(0x00000080)
#define PADS_BANK0_SWD_BITS _u(0x000000ff)
#define PADS_BANK0_SWD_RESET _u(0x0000005a)
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_SWD_OD
// Description : Output disable. Has priority over output enable from
// peripherals
#define PADS_BANK0_SWD_OD_RESET _u(0x0)
#define PADS_BANK0_SWD_OD_BITS _u(0x00000080)
#define PADS_BANK0_SWD_OD_MSB _u(7)
#define PADS_BANK0_SWD_OD_LSB _u(7)
#define PADS_BANK0_SWD_OD_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_SWD_IE
// Description : Input enable
#define PADS_BANK0_SWD_IE_RESET _u(0x1)
#define PADS_BANK0_SWD_IE_BITS _u(0x00000040)
#define PADS_BANK0_SWD_IE_MSB _u(6)
#define PADS_BANK0_SWD_IE_LSB _u(6)
#define PADS_BANK0_SWD_IE_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_SWD_DRIVE
// Description : Drive strength.
// 0x0 -> 2mA
// 0x1 -> 4mA
// 0x2 -> 8mA
// 0x3 -> 12mA
#define PADS_BANK0_SWD_DRIVE_RESET _u(0x1)
#define PADS_BANK0_SWD_DRIVE_BITS _u(0x00000030)
#define PADS_BANK0_SWD_DRIVE_MSB _u(5)
#define PADS_BANK0_SWD_DRIVE_LSB _u(4)
#define PADS_BANK0_SWD_DRIVE_ACCESS "RW"
#define PADS_BANK0_SWD_DRIVE_VALUE_2MA _u(0x0)
#define PADS_BANK0_SWD_DRIVE_VALUE_4MA _u(0x1)
#define PADS_BANK0_SWD_DRIVE_VALUE_8MA _u(0x2)
#define PADS_BANK0_SWD_DRIVE_VALUE_12MA _u(0x3)
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_SWD_PUE
// Description : Pull up enable
#define PADS_BANK0_SWD_PUE_RESET _u(0x1)
#define PADS_BANK0_SWD_PUE_BITS _u(0x00000008)
#define PADS_BANK0_SWD_PUE_MSB _u(3)
#define PADS_BANK0_SWD_PUE_LSB _u(3)
#define PADS_BANK0_SWD_PUE_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_SWD_PDE
// Description : Pull down enable
#define PADS_BANK0_SWD_PDE_RESET _u(0x0)
#define PADS_BANK0_SWD_PDE_BITS _u(0x00000004)
#define PADS_BANK0_SWD_PDE_MSB _u(2)
#define PADS_BANK0_SWD_PDE_LSB _u(2)
#define PADS_BANK0_SWD_PDE_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_SWD_SCHMITT
// Description : Enable schmitt trigger
#define PADS_BANK0_SWD_SCHMITT_RESET _u(0x1)
#define PADS_BANK0_SWD_SCHMITT_BITS _u(0x00000002)
#define PADS_BANK0_SWD_SCHMITT_MSB _u(1)
#define PADS_BANK0_SWD_SCHMITT_LSB _u(1)
#define PADS_BANK0_SWD_SCHMITT_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : PADS_BANK0_SWD_SLEWFAST
// Description : Slew rate control. 1 = Fast, 0 = Slow
#define PADS_BANK0_SWD_SLEWFAST_RESET _u(0x0)
#define PADS_BANK0_SWD_SLEWFAST_BITS _u(0x00000001)
#define PADS_BANK0_SWD_SLEWFAST_MSB _u(0)
#define PADS_BANK0_SWD_SLEWFAST_LSB _u(0)
#define PADS_BANK0_SWD_SLEWFAST_ACCESS "RW"
// =============================================================================
#endif // HARDWARE_REGS_PADS_BANK0_DEFINED
| 2.15625 | 2 |
2024-11-18T22:11:00.886339+00:00 | 2018-09-09T08:58:43 | 265ce65d726f6a1d392086543ab41221f904cdb1 | {
"blob_id": "265ce65d726f6a1d392086543ab41221f904cdb1",
"branch_name": "refs/heads/master",
"committer_date": "2018-09-09T08:58:43",
"content_id": "9a8711de16640b505e449ae634d297a4bc83c7c0",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "8137bbe71db5bbf153731c76d65b960a8ba5a902",
"extension": "c",
"filename": "test_acl.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 121995855,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 16396,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/libsecurity/src/acl/test/test_acl.c",
"provenance": "stackv2-0072.json.gz:38103",
"repo_name": "savchyn/sec-c",
"revision_date": "2018-09-09T08:58:43",
"revision_id": "44c3c866f82fdd83507542a49fdd81befcb96224",
"snapshot_id": "8851a7e27375301ade89c140aba08e94491ed68e",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/savchyn/sec-c/44c3c866f82fdd83507542a49fdd81befcb96224/libsecurity/src/acl/test/test_acl.c",
"visit_date": "2021-09-22T11:24:51.463960"
} | stackv2 | #include "libsecurity/acl/acl_int.h"
#define ACL_ENTRY_NAME "try-entry"
#define BOTH_ENTRY_NAME "both"
#define ALL_PERMISSION "All can user it"
#define ENTRY_PERMISSION "p1"
#define BOTH_PERMISSION "both"
#define DEFAULT_SALT ((unsigned char *)"salt-a1b2c3d")
#define SECRET ((unsigned char *)"a!@#%^&*(()__+_)(}{|PPO?>O2:~`12")
const char *AclName = "Test-Acl";
const char *AclResourceName = "Camera-1";
// Verify that only permissions with value can be added to entty
STATIC bool testAddPermission() {
int16_t i, len = MAX_PERMISSION_NAME_LEN + 2;
bool pass = true, ret;
AclPermissionsS *aclEntry, *aclEntryRef;
char name[len * 2 + 1];
EntityManager e1, *entityManager = NULL;
EntityManager_New(&e1);
entityManager = &e1;
Acl_NewPermissionsList("test", &aclEntry);
Acl_NewPermissionsList("test", &aclEntryRef);
strcpy(name, "");
for (i = 0; i < len; i++) {
ret = addPermissionToEntry(aclEntry, name);
if (!ret && strlen(name) > 0 && strlen(name) <= MAX_PERMISSION_NAME_LEN) {
printf("testAddPermission fail: permission with legal name '%s' was not "
"added to ACL entry "
"'%s', error: %s\n",
name, ALL_ACL_NAME, errStr);
pass = false;
} else if (ret && (strlen(name) == 0 || strlen(name) > MAX_PERMISSION_NAME_LEN)) {
printf("testAddAclEntry fail: permission with illegal name '%s' (length "
"%d), length must be "
"%d-%d was added to ACL entry '%s'\n",
name, (int16_t)strlen(name), 1, MAX_PERMISSION_NAME_LEN, ALL_ACL_NAME);
pass = false;
}
strcat(name, "a");
if (!isEqualEntry(aclEntry, aclEntry) ) {
printf("testAddAclEntry fail: equal ACL entries did not found equal\n");
Acl_PrintPermissionsList(stdout, "", aclEntry);
pass = false;
}
ret = addPermissionToEntry(aclEntryRef, name);
if (ret && isEqualEntry(aclEntry, aclEntryRef)) {
printf("testAddAclEntry fail: unequal ACL entries found equal\n");
Acl_PrintPermissionsList(stdout, "", aclEntry);
Acl_PrintPermissionsList(stdout, "", aclEntryRef);
pass = false;
}
}
Acl_FreePermissionsList(aclEntry);
Acl_FreePermissionsList(aclEntryRef);
EntityManager_FreeAll(entityManager);
return pass;
}
STATIC bool setup(EntityManager *entityManager, int16_t len, char **names) {
int16_t i = 0;
AclPermissionsS *aclEntry[len];
AclS *acl;
EntityManager_AddResource(entityManager, AclResourceName);
EntityManager_GetProperty(entityManager, AclResourceName, ACL_PROPERTY_NAME, (void **)(&acl));
for (i = 0; i < len; i++) {
EntityManager_AddUser(entityManager, names[i]);
addEntry(acl, names[i], &(aclEntry[i]));
}
EntityManager_RegisterProperty(entityManager, AclResourceName, ACL_PROPERTY_NAME, (void *)acl);
return true;
}
// Verify that a permission can be added/removed only once
// Verify that true is return only for set permissions
// Verify that if ALL permission was set, the entity will recieve true
// Verify that if the permission was set to an entity the check entity is member
// of, a true will be
// recieved
// Verify that if a permission was not set, a false to check is received
STATIC bool testAddRemoveCheckPermission() {
int16_t i = 0, j = 0;
bool ret = false, ret0, ret1, ret2, pass = true;
char *permission[2] = { "add", "no added" };
char *names[3] = { ALL_ACL_NAME, ACL_ENTRY_NAME, BOTH_ENTRY_NAME };
EntityManager e1, *entityManager = NULL;
bool exp[] = { false, true, false, true, false };
bool exp1[] = { false, true, true, false, false };
int16_t testLen = -1, namesLen = -1;
int16_t addRemove[] = { 'r', 'a', 'a', 'r', 'r' };
AclS *acl = NULL;
testLen = sizeof(exp) / sizeof(bool);
namesLen = sizeof(names) / sizeof(char *);
EntityManager_New(&e1);
entityManager = &e1;
EntityManager_AddGroup(entityManager, BOTH_ENTRY_NAME);
setup(entityManager, namesLen, names);
// add ACL_ENTRY_NAME as member of BOTH_ENTRY_NAME
if (!EntityManager_AddUserToGroup(entityManager, BOTH_ENTRY_NAME, ACL_ENTRY_NAME) ) {
printf("The user '%s' was not added to group '%s', error %s\n", ACL_ENTRY_NAME, BOTH_ENTRY_NAME, errStr);
}
if (!EntityManager_GetProperty(entityManager, AclResourceName, ACL_PROPERTY_NAME, (void **)(&acl)) ) {
printf("Error: Can't get ACL property from '%s'\n", names[i]);
return false;
}
for (i = 0; i < namesLen; i++) {
for (j = 0; j < testLen; j++) {
if (addRemove[j] == 'r') {
ret = Acl_RemovePermissionFromResource(entityManager, AclResourceName, names[i], permission[0]);
ret1 = Acl_CheckEntityPermission(entityManager, AclResourceName, names[i], permission[0]);
} else {
ret = Acl_AddPermissionToResource(entityManager, AclResourceName, names[i], permission[0]);
ret1 = Acl_CheckEntityPermission(entityManager, AclResourceName, names[i], permission[0]);
ret2 = Acl_CheckEntityPermission(entityManager, AclResourceName, ACL_ENTRY_NAME, permission[0]);
}
ret0 = Acl_CheckEntityPermission(entityManager, AclResourceName, names[i], permission[1]);
if (ret != exp[j]) {
printf("testAddRemoveCheckPermission fail: i=%d, j=%d, action %c, "
"permission '%s' entry "
"'%s', exp %d, ret %d\n",
i, j, addRemove[j], permission[0], names[i], exp[j], ret);
pass = false;
}
if (ret1 != exp1[j]) {
printf("testAddRemoveCheckPermission fail for ret1: i=%d, j=%d, action "
"%c, permission '%s' "
"entry '%s', exp1 %d, ret1 %d\n",
i, j, addRemove[j], permission[0], names[i], exp1[j], ret1);
pass = false;
}
if (addRemove[j] == 'a' && !ret2 ) {
printf("testAddRemoveCheckPermission fail for ret2: permission must be "
"set i=%d, j=%d, "
"action %c, permission '%s' entry '%s', exp2 %d, ret2 %d\n",
i, j, addRemove[j], permission[0], ACL_ENTRY_NAME, true, ret2);
pass = false;
}
if (ret0) {
printf("testAddRemoveCheckPermission fail for ret0: permission was "
"never set for entry "
"'%s', permission '%s'\n",
names[i], permission[1]);
pass = false;
}
}
}
EntityManager_FreeAll(entityManager);
return pass;
}
// Verify that an entity permission returns all its permission (including the
// permissions of entity
// it is a member of and the all permission)
// Verify that true is return only for set permissions
// Verify that all permissions return the full list of permissions
// Verify that who uses a permission return the relevant entity list
STATIC bool testGetCheckWhoUseGetAllPermissions() {
int16_t i = 0, len = 0;
bool pass = true;
char *names[4] = { ALL_ACL_NAME, ACL_ENTRY_NAME, BOTH_ENTRY_NAME, "none" };
char *permissions[4] = { ALL_PERMISSION, ENTRY_PERMISSION, BOTH_PERMISSION, NULL };
htab *expectedUsersName[4]; // must be the same order as in permissions
int16_t exp[] = { 1, 3, 2, 1 }; // ACL_ENTRY is also in the BOTH_ENTRY
int16_t namesLen = -1;
AclPermissionsS *permissionsVec = NULL;
htab *whoUses = NULL;
EntityManager e1, *entityManager = NULL;
void *a = NULL;
AclS *acl = NULL;
namesLen = sizeof(names) / sizeof(char *);
EntityManager_New(&e1);
entityManager = &e1;
EntityManager_AddGroup(entityManager, BOTH_ENTRY_NAME);
setup(entityManager, namesLen, names);
// add ACL_ENTRY_NAME as member of BOTH_ENTRY_NAME
if (!EntityManager_AddUserToGroup(entityManager, BOTH_ENTRY_NAME, ACL_ENTRY_NAME) ) {
printf("The user '%s' was not added to group '%s', error %s\n", ACL_ENTRY_NAME, BOTH_ENTRY_NAME, errStr);
}
if (!EntityManager_GetProperty(entityManager, AclResourceName, ACL_PROPERTY_NAME, &a) ) {
printf("Error: Can't get ACL property from '%s'\n", names[i]);
return false;
}
acl = (AclS *)a;
for (i = 0; i < namesLen; i++)
expectedUsersName[i] = hcreate(H_TAB_SIZE);
for (i = 0; i < namesLen; i++) {
if (permissions[i] != NULL) Acl_AddPermissionToResource(entityManager, AclResourceName, names[i], permissions[i]);
Utils_AddToHash(expectedUsersName[0], (unsigned char *)names[i], strlen(names[i]), "");
if (strcmp(names[i], ACL_ENTRY_NAME) == 0) Utils_AddToHash(expectedUsersName[1], (unsigned char *)names[i], strlen(names[i]), "");
if (strcmp(names[i], ACL_ENTRY_NAME) == 0 || strcmp(names[i], BOTH_ENTRY_NAME) == 0)
Utils_AddToHash(expectedUsersName[2], (unsigned char *)names[i], strlen(names[i]), "");
}
// add the ROOT_USER_NAME to all
Utils_AddToHash(expectedUsersName[0], (unsigned char *)ROOT_USER_NAME, strlen(ROOT_USER_NAME), "");
for (i = 0; i < namesLen; i++) {
Acl_NewPermissionsList("test-whoUses", &permissionsVec);
Acl_GetUserPermissions(entityManager, AclResourceName, names[i], &permissionsVec);
len = hcount(permissionsVec->Permissions);
if (exp[i] != len) {
printf("testGetCheckWhoUseGetAllPermissions fail number of permission "
"expected for '%s' was "
"%d, found: %d\n",
names[i], exp[i], len);
Acl_PrintPermissionsList(stdout, "", permissionsVec);
pass = false;
}
Acl_FreePermissionsList(permissionsVec);
whoUses = hcreate(H_TAB_SIZE);
Acl_WhoUseAPermission(entityManager, permissions[i], whoUses);
if (!Utils_IsEqualHash(whoUses, expectedUsersName[i]) ) {
printf("testGetCheckWhoUseGetAllPermissions fail expected entity names "
"for who use the "
"permission '%s' was not matched\n",
permissions[i]);
Utils_PrintHash("Expected:", expectedUsersName[i]);
Utils_PrintHash("Found:", whoUses);
pass = false;
}
hdestroy(whoUses); // its a shellow duplication
}
Acl_NewPermissionsList("test", &permissionsVec);
Acl_GetAllPermissions(entityManager, AclResourceName, permissionsVec);
len = hcount(permissionsVec->Permissions);
if (len != namesLen - 1) { // the none entry doesnt have permission
printf("testGetCheckWhoUseGetAllPermissions fail number of permissions %d "
"is not as expected %d\n",
len, namesLen - 1);
Acl_PrintPermissionsList(stdout, "Full permissions list:", permissionsVec);
pass = false;
}
for (i = 0; i < namesLen; i++) {
if (permissions[i] != NULL && !checkPermissionOfEntry(permissionsVec, permissions[i]) ) {
printf("testGetCheckWhoUseGetAllPermissions fail permission '%s' was set "
"but not found in "
"the full list permissions\n",
permissions[i]);
Acl_PrintPermissionsList(stdout, "Full permissions list:", permissionsVec);
pass = false;
}
}
#ifndef MBED_OS
FILE *devNull = fopen("/dev/null", "w");
Acl_Print(devNull, "Test acl:", acl);
fclose(devNull);
#endif
Acl_FreePermissionsList(permissionsVec);
for (i = 0; i < namesLen; i++) {
Utils_FreeHashKeys(expectedUsersName[i]);
}
EntityManager_FreeAll(entityManager);
return pass;
}
STATIC bool testAclCorners() {
int16_t i = 0, namesLen = -1;
bool pass = true;
char *names[3] = { ALL_ACL_NAME, ACL_ENTRY_NAME, BOTH_ENTRY_NAME }, *permission = "add";
AclPermissionsS *aclEntry;
AclS *acl;
void *a;
EntityManager e1, *entityManager = NULL;
namesLen = sizeof(names) / sizeof(char *);
Acl_NewPermissionsList("test", &aclEntry);
if (updateEntryPermissions(aclEntry, NULL) || updateEntryPermissions(NULL, &aclEntry)) {
printf("testAclCorners fail updateEntryPermissions with NULL return successfully\n");
pass = false;
}
EntityManager_New(&e1);
entityManager = &e1;
setup(entityManager, namesLen, names);
EntityManager_GetProperty(entityManager, AclResourceName, ACL_PROPERTY_NAME, &a);
acl = (AclS *)a;
for (i = 0; i < namesLen; i++) {
if (!Acl_RemoveEntry(a, names[i]) ) {
printf("testAclCorners fail testAclCorners failed to removed entry '%s' from ACL\n", names[i]);
pass = false;
}
if (Acl_RemoveEntry(a, names[i]) || Acl_RemoveEntry(a, NULL)) {
printf("testAclCorners fail testAclCorners removed successfully already removed entry '%s' from ACL\n", names[i]);
pass = false;
}
}
if (addEntry(acl, NULL, &aclEntry)) {
printf("testAclCorners fail testAclCorners: Successfully add entry to NULL entry name\n");
pass = false;
}
if (Acl_AddPermissionToResource(entityManager, NULL, AclResourceName, permission) ||
Acl_AddPermissionToResource(NULL, AclResourceName, NULL, permission)) {
printf("testAclCorners fail testAclCorners: Successfully add permission to NULL ACL or resource name\n");
pass = false;
}
EntityManager_AddGroup(entityManager, names[1]);
if (!Acl_AddPermissionToResource(entityManager, AclResourceName, names[1], permission) ) {
printf("testAclCorners fail testAclCorners: error while add permission to resource, error: %s\n", errStr);
pass = false;
}
if (Acl_RemovePermissionFromResource(entityManager, NULL, AclResourceName, permission) ||
Acl_RemovePermissionFromResource(NULL, AclResourceName, names[0], permission)) {
printf("testAclCorners fail testAclCorners: Successfully remove permission from NULL ACL or resource "
"name\n");
pass = false;
}
EntityManager_FreeAll(entityManager);
Acl_FreePermissionsList(aclEntry);
Acl_Free(NULL);
Acl_FreePermissionsList(NULL);
return pass;
}
// Verify that stored ACL is equal to the loaded one
STATIC bool testStoreLoadAcl() {
bool pass = true;
char *prefix = "test-acl", *tName = NULL;
SecureStorageS storage;
int16_t i = 0, namesLen = -1;
char *names[3] = { ALL_ACL_NAME, ACL_ENTRY_NAME, BOTH_ENTRY_NAME };
char *permission = "add";
EntityManager e1, *entityManager = NULL;
void *a = NULL, *a1 = NULL;
AclS *acl = NULL;
namesLen = sizeof(names) / sizeof(char *);
if (!SecureStorage_NewStorage(SECRET, DEFAULT_SALT, &storage) ) {
printf("testStoreLoadAcl failed: Error when try to create new storage, "
"error: %s\n",
errStr);
return false;
}
EntityManager_New(&e1);
entityManager = &e1;
EntityManager_AddGroup(entityManager, BOTH_ENTRY_NAME);
setup(entityManager, namesLen, names);
EntityManager_AddUserToGroup(entityManager, BOTH_ENTRY_NAME, ACL_ENTRY_NAME);
if (!EntityManager_GetProperty(entityManager, AclResourceName, ACL_PROPERTY_NAME, &a) ) {
printf("Error: Can't get ACL property from '%s'\n", names[i]);
return false;
}
acl = (AclS *)a;
for (i = 0; i < namesLen; i++) {
addPermissionToResource(acl, names[i], permission);
}
if (!Acl_Store(acl, &storage, prefix) ) {
printf("testStoreLoadAcl failed: Error when try to store ACL to "
"storage, error: %s\n",
errStr);
pass = false;
}
if (Acl_Load((void **)(&a1), NULL, prefix, &tName)) {
printf("testStoreLoadAcl failed: successfully load from NULL strorage\n");
pass = false;
}
if (!Acl_Load((void **)(&a1), &storage, prefix, &tName) ) {
printf("testStoreLoadAcl failed: Error when try to load ACL from "
"storage, error: %s\n",
errStr);
pass = false;
} else if (!Acl_IsEqual(a, a1) ) {
printf("testStoreLoadAcl failed: stored and loaded ACLs are not equal, error: %s\n", errStr);
Acl_Print(stdout, "Acl1:\n", a);
Acl_Print(stdout, "Acl2:\n", a1);
pass = false;
}
SecureStorage_FreeStorage(&storage);
EntityManager_FreeAll(&e1);
Acl_Free(a1);
return pass;
}
#ifdef MBED_OS
int16_t testAcl()
#else
int main()
#endif
{
bool pass = true;
int16_t i = 0, len = 0;
char *res = NULL;
Utils_TestFuncS callFunc[] = { { "testAddPermission", testAddPermission },
{ "testAddRemoveCheckPermission", testAddRemoveCheckPermission },
{ "testGetCheckWhoUseGetAllPermissions", testGetCheckWhoUseGetAllPermissions },
{ "testStoreLoadAcl", testStoreLoadAcl },
{ "testAclCorners", testAclCorners } };
len = sizeof(callFunc) / sizeof(Utils_TestFuncS);
for (i = 0; i < len; i++) {
if (!(callFunc[i]).testFunc() ) {
res = "fail";
pass = false;
} else
res = "pass";
printf("Test %s:'%s' %s\n", __FILE__, callFunc[i].name, res);
}
EntityManager_RemoveRegisteredPropertyList();
return pass;
}
| 2.171875 | 2 |
2024-11-18T22:11:03.397662+00:00 | 2015-04-15T17:19:54 | 8b79a0a8b990bf69a9a5a16ddf00eac608d461ab | {
"blob_id": "8b79a0a8b990bf69a9a5a16ddf00eac608d461ab",
"branch_name": "refs/heads/master",
"committer_date": "2015-04-15T17:24:07",
"content_id": "45d1f53295efecba1a78ff1dd94316eaa74f7910",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "93de7999d11432b7ecaa8383df63310afa9f62b3",
"extension": "c",
"filename": "gbmj2k.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": 39070,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/OS2/Shared/libs/GBM/gbmj2k.c",
"provenance": "stackv2-0072.json.gz:38360",
"repo_name": "haizzus/SYSTEM-OS-OSFree",
"revision_date": "2015-04-15T17:19:54",
"revision_id": "20d79864a58cb7f1abe1622dfb259b99750dbeff",
"snapshot_id": "bc5745cf4192f3d8d8a59c7369c9a029fd071f3f",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/haizzus/SYSTEM-OS-OSFree/20d79864a58cb7f1abe1622dfb259b99750dbeff/OS2/Shared/libs/GBM/gbmj2k.c",
"visit_date": "2023-07-25T00:57:10.812543"
} | stackv2 | /*************************************************************************
gbmj2k.c - JPEG2000 Format support (JP2, J2K, J2C, JPC, JPT)
Credit for writing this module must go to Heiko Nitzsche.
This file is just as public domain as the rest of GBM.
This code is a mainly a wrapper around the OpenJPEG library and
supports most features of the actual version. Supported are
YUV, sRGB and Graylevel images.
Supported formats and options:
------------------------------
JPEG2000 : JPEG2000 Graphics Format : .JP2 .J2C .J2K .JPC .JPT
(YUV, sRGB, Gray)
Standard formats (backward compatible):
Reads 8 bpp gray level files and presents them as 8 bpp.
Reads 16 bpp gray level files and presents them as 8 bpp.
Reads 24 bpp colour files and presents them as 24 bpp.
Reads 48 bpp colour files and presents them as 24 bpp.
Extended formats (not backward compatible, import option ext_bpp required):
Reads 16 bpp gray level files and presents them as 48 bpp.
Reads 48 bpp colour files and presents them as 48 bpp.
Writes 8 bpp gray level files (colour palette bitmaps are converted).
Writes 24 and 48 bpp bpp colour files.
Can specify the colour channel the output grey values are based on
Output option: r,g,b,k (default: k, combine color channels and write grey equivalent)
Write additonal comment
Output option: comment=text
History:
--------
28-Aug-2008 Initial version
TODO: JPWL support not yet included
******************************************************************************/
#ifdef ENABLE_J2K
/* Includes */
#include <stdio.h>
#include <ctype.h>
#include <limits.h>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include "gbm.h"
#include "gbmdesc.h"
#include "gbmhelp.h"
#include "gbmmap.h"
#include "gbmmem.h"
#include "openjpeg.h"
/* ----------------------------------------------------------- */
#define GBM_ERR_J2K ((GBM_ERR) 6100)
#define GBM_ERR_J2K_BPP ((GBM_ERR) 6101)
#define GBM_ERR_J2K_HEADER ((GBM_ERR) 6102)
#define GBM_ERR_J2K_BAD_COMMENT ((GBM_ERR) 6103)
#define CVT(x) (((x) * 255) / ((1L << 16) - 1))
/* ----------------------------------------------------------- */
typedef struct
{
GBM_ERR rc;
const char *error_message;
} J2K_GBMERR_MSG;
static J2K_GBMERR_MSG j2k_errmsg[] =
{
{ GBM_ERR_J2K_BPP , "bad bits per pixel" },
{ GBM_ERR_J2K_HEADER , "bad header" },
{ GBM_ERR_J2K_BAD_COMMENT, "comment could not be parsed" },
{ -1 , NULL }
};
static GBMFT j2k_jp2_gbmft =
{
GBM_FMT_DESC_SHORT_JP2,
GBM_FMT_DESC_LONG_JP2,
GBM_FMT_DESC_EXT_JP2,
GBM_FT_R8 | GBM_FT_R24 | GBM_FT_R48 |
GBM_FT_W8 | GBM_FT_W24 | GBM_FT_W48
};
static GBMFT j2k_j2k_gbmft =
{
GBM_FMT_DESC_SHORT_J2K,
GBM_FMT_DESC_LONG_J2K,
GBM_FMT_DESC_EXT_J2K,
GBM_FT_R8 | GBM_FT_R24 | GBM_FT_R48 |
GBM_FT_W8 | GBM_FT_W24 | GBM_FT_W48
};
static GBMFT j2k_jpt_gbmft =
{
GBM_FMT_DESC_SHORT_JPT,
GBM_FMT_DESC_LONG_JPT,
GBM_FMT_DESC_EXT_JPT,
GBM_FT_R8 | GBM_FT_R24 | GBM_FT_R48 /* JPT can only be read */
};
typedef struct
{
gbm_boolean errok; /* GBM_FALSE if an error during file decoding happened */
opj_image_t *image; /* Pointer to the decoded image */
OPJ_CODEC_FORMAT codec; /* the codec to be used for reading */
int bpp; /* bpp of source image */
/* This entry will store the options provided during first header read.
* It will keep the options for the case the header has to be reread.
*/
char read_options[PRIV_SIZE
- sizeof(gbm_boolean)
- sizeof(opj_image_t *)
- sizeof(OPJ_CODEC_FORMAT)
- 20 /* space for structure element padding */ ];
} J2K_PRIV_READ;
/* ----------------------------------------------------------- */
/* ----------------------------------------------------------- */
/* ----------------------------------------------------------- */
/*
* Divide an integer by a power of 2 and round upwards.
*
* a divided by 2^b
*/
static int int_ceildivpow2(int a, int b)
{
return (a + (1 << b) - 1) >> b;
}
/* ----------------------------------------------------------- */
/* ----------------------------------------------------------- */
/* ----------------------------------------------------------- */
/* Replace standard OpenJPEG error functions by our own that prevent
output to stdout and fatal handling.
The replacement will be used temporarily during file I/O and sets
an error code to the private IO struct.
*/
/* error callback expecting a valid J2K_PRIV_READ pointer */
static void j2k_gbm_error_callback(const char *error_msg, void *client_data)
{
if (client_data != NULL)
{
J2K_PRIV_READ *j2k_priv = (J2K_PRIV_READ *) client_data;
j2k_priv->errok = GBM_FALSE; /* error occured */
}
#if DEBUG
printf("ERROR: %s", error_msg);
#else
error_msg = error_msg; /* prevent compiler warning */
#endif
}
/* ----------------------------------------------------------- */
/* warning callback expecting a valid J2K_PRIV_READ pointer */
static void j2k_gbm_warning_callback(const char *warning_msg, void *client_data)
{
#if DEBUG
printf("WARNING: %s", warning_msg);
#else
warning_msg = warning_msg; /* prevent compiler warning */
#endif
}
/* ----------------------------------------------------------- */
/* info callback expecting a valid J2K_PRIV_READ pointer */
static void j2k_gbm_info_callback(const char *info_msg, void *client_data)
{
#if DEBUG
printf("INFO: %s", info_msg);
#else
info_msg = info_msg; /* prevent compiler warning */
#endif
}
/* ----------------------------------------------------------- */
/* Initialize structures for reading
Returns GBM_TRUE on success, else GBM_FALSE
*/
static gbm_boolean j2k_read_init(J2K_PRIV_READ *j2k_priv)
{
j2k_priv->errok = GBM_TRUE;
j2k_priv->image = NULL;
j2k_priv->bpp = 0;
return GBM_TRUE;
}
/* Cleanup structs for reading. */
static void j2k_read_deinit(J2K_PRIV_READ *j2k_priv)
{
if (j2k_priv->image != NULL)
{
opj_image_destroy(j2k_priv->image);
j2k_priv->image = NULL;
j2k_priv->bpp = 0;
}
}
/* ----------------------------------------------------------- */
/* ----------------------------------------------------------- */
/* ----------------------------------------------------------- */
/* j2k_jp2_qft - Query format informations */
GBM_ERR j2k_jp2_qft(GBMFT *gbmft)
{
*gbmft = j2k_jp2_gbmft;
return GBM_ERR_OK;
}
/* j2k_j2k_qft - Query format informations */
GBM_ERR j2k_j2k_qft(GBMFT *gbmft)
{
*gbmft = j2k_j2k_gbmft;
return GBM_ERR_OK;
}
/* j2k_jpt_qft - Query format informations */
GBM_ERR j2k_jpt_qft(GBMFT *gbmft)
{
*gbmft = j2k_jpt_gbmft;
return GBM_ERR_OK;
}
/* ----------------------------------------------------------- */
/* ----------------------------------------------------------- */
/* ----------------------------------------------------------- */
static GBM_ERR internal_j2k_decode(J2K_PRIV_READ * j2k_read,
opj_dparameters_t * parameters,
opj_event_mgr_t * event_mgr,
opj_dinfo_t * dinfo,
const gbm_u8 * src_data,
const int src_data_len)
{
opj_cio_t *cio = NULL;
/* catch events using our callbacks and give a local context */
opj_set_event_mgr((opj_common_ptr)dinfo, event_mgr, j2k_read);
/* setup the decoder decoding parameters using user parameters */
opj_setup_decoder(dinfo, parameters);
/* open a byte stream */
cio = opj_cio_open((opj_common_ptr)dinfo, (unsigned char *)src_data, src_data_len);
if (cio == NULL)
{
return GBM_ERR_MEM;
}
/* decode the stream and fill the image structure */
j2k_read->errok = GBM_TRUE;
j2k_read->image = opj_decode(dinfo, cio);
opj_cio_close(cio);
cio = NULL;
if ((j2k_read->image != NULL) && (j2k_read->errok))
{
return GBM_ERR_OK;
}
/* reset the image info for the next format test */
if (j2k_read->image != NULL)
{
opj_image_destroy(j2k_read->image);
j2k_read->image = NULL;
}
j2k_read->errok = GBM_FALSE;
return GBM_ERR_J2K_HEADER;
}
/* ----------------------------------------------------------- */
static GBM_ERR internal_j2k_checkStreamFormat(const gbm_u8 *src_data,
const int src_data_len,
const gbm_boolean decodeHeaderOnly,
J2K_PRIV_READ *j2k_read)
{
opj_dparameters_t *parameters = NULL; /* decompression parameters */
opj_dinfo_t *dinfo = NULL;
opj_event_mgr_t event_mgr; /* event manager */
GBM_ERR rc = GBM_ERR_OK;
/* configure the event callbacks */
memset(&event_mgr, 0, sizeof(opj_event_mgr_t));
event_mgr.error_handler = j2k_gbm_error_callback;
event_mgr.warning_handler = j2k_gbm_warning_callback;
event_mgr.info_handler = j2k_gbm_info_callback;
/* set decoding parameters to default values */
parameters = gbmmem_malloc(sizeof(opj_dparameters_t));
if (parameters == NULL)
{
return GBM_ERR_MEM;
}
opj_set_default_decoder_parameters(parameters);
/* prepare parameters */
parameters->cp_limit_decoding = decodeHeaderOnly ? LIMIT_TO_MAIN_HEADER : NO_LIMITATION;
/* create the decompression scheme */
dinfo = opj_create_decompress(j2k_read->codec);
rc = internal_j2k_decode(j2k_read, parameters, &event_mgr, dinfo,
src_data, src_data_len);
opj_destroy_decompress(dinfo); dinfo = NULL;
gbmmem_free(parameters);
return rc;
}
/* ----------------------------------------------------------- */
/* internal_j2k_rhdr - Read file header to init GBM struct */
static GBM_ERR internal_j2k_rhdr(const int fd,
GBM *gbm,
const gbm_boolean decodeHeaderOnly)
{
J2K_PRIV_READ *j2k_read = (J2K_PRIV_READ *) gbm->priv;
GBM_ERR rc = GBM_ERR_READ;
gbm_u8 *src_data = NULL;
long src_data_len = 0L;
/* find length of the stream */
src_data_len = gbm_file_lseek(fd, 0L, GBM_SEEK_END);
/* set file pointer to start. */
if (gbm_file_lseek(fd, 0L, GBM_SEEK_SET) != 0)
{
return GBM_ERR_READ;
}
/* allocate buffer */
src_data = (gbm_u8 *) gbmmem_malloc(src_data_len);
if (src_data == NULL)
{
return GBM_ERR_MEM;
}
/* get data */
if (gbm_file_read(fd, src_data, src_data_len) != src_data_len)
{
gbmmem_free(src_data);
return GBM_ERR_READ;
}
/* set file pointer to start. */
if (gbm_file_lseek(fd, 0L, GBM_SEEK_SET) != 0)
{
gbmmem_free(src_data);
return GBM_ERR_READ;
}
/* init the read info struct */
if (! j2k_read_init(j2k_read))
{
gbmmem_free(src_data);
return GBM_ERR_MEM;
}
/* Detect the file format */
rc = internal_j2k_checkStreamFormat(src_data, src_data_len,
decodeHeaderOnly, j2k_read);
if (rc != GBM_ERR_OK)
{
j2k_read_deinit(j2k_read);
gbmmem_free(src_data);
return rc;
}
gbmmem_free(src_data); src_data = NULL;
gbm->w = 0;
gbm->h = 0;
gbm->bpp = 0;
switch(j2k_read->image->color_space)
{
case 0: /* This seems to always RGB as well. It is a bug in OpenJPEG 1.3 (color space not always set). */
case CLRSPC_SRGB:
if ((j2k_read->image->numcomps != 1) &&
(j2k_read->image->numcomps != 3))
{
j2k_read_deinit(j2k_read);
return GBM_ERR_J2K_BPP;
}
break;
case CLRSPC_GRAY: /* grayscale */
/* only support for 8bit per component */
if (j2k_read->image->numcomps != 1)
{
j2k_read_deinit(j2k_read);
return GBM_ERR_J2K_BPP;
}
break;
case CLRSPC_SYCC: /* YUV */
if (j2k_read->image->numcomps != 3)
{
j2k_read_deinit(j2k_read);
return GBM_ERR_J2K_BPP;
}
break;
case CLRSPC_UNKNOWN:
default:
j2k_read_deinit(j2k_read);
return GBM_ERR_NOT_SUPP;
}
/* check that all components have the same color depth */
{
int i, j;
for (i = 0; i < j2k_read->image->numcomps; i++)
{
/* only support for 8/16bit per component */
const int prec = j2k_read->image->comps[i].prec;
if ((prec != 8) && (prec != 16))
{
j2k_read_deinit(j2k_read);
return GBM_ERR_J2K_BPP;
}
for (j = 0; j < j2k_read->image->numcomps; j++)
{
if (prec != j2k_read->image->comps[j].prec)
{
j2k_read_deinit(j2k_read);
return GBM_ERR_J2K_BPP;
}
}
}
}
/* use the reference grid size */
gbm->w = j2k_read->image->x1;
gbm->h = j2k_read->image->y1;
gbm->bpp = j2k_read->image->numcomps * j2k_read->image->comps[0].prec;
j2k_read->bpp = gbm->bpp;
switch(gbm->bpp)
{
case 8:
case 24:
break;
case 16:
/* check if extended color depths are requested */
if (gbm_find_word(j2k_read->read_options, "ext_bpp") == NULL)
{
/* downsample to 8bpp */
gbm->bpp = 8;
}
else
{
/* upsample to 48bpp */
gbm->bpp = 48;
}
break;
case 48:
/* check if extended color depths are requested */
if (gbm_find_word(j2k_read->read_options, "ext_bpp") == NULL)
{
/* downsample to 24bpp */
gbm->bpp = 24;
}
break;
default:
return GBM_ERR_J2K_BPP;
}
return GBM_ERR_OK;
}
/* ----------------------------------------------------------- */
/* ----------------------------------------------------------- */
/* j2k_rhdr - Read file header to init GBM struct */
static GBM_ERR j2k_rhdr(const OPJ_CODEC_FORMAT codec,
const char *fn, int fd, GBM *gbm, const char *opt)
{
J2K_PRIV_READ *j2k_read = (J2K_PRIV_READ *) gbm->priv;
GBM_ERR rc;
fn = fn; /* prevent compiler warning */
/* init options buffer */
memset(j2k_read->read_options, 0, sizeof(j2k_read->read_options));
/* copy possible options */
if (strlen(opt) >= sizeof(j2k_read->read_options))
{
return GBM_ERR_BAD_OPTION;
}
strcpy(j2k_read->read_options, opt);
j2k_read->codec = codec;
rc = internal_j2k_rhdr(fd, gbm, GBM_TRUE);
if (rc != GBM_ERR_OK)
{
return rc;
}
/* We cannot expect the client calls rhdr,rpal,rdata in order.
* The client might just read the header and stop then.
*
* There is no other choice than freeing the structs
* and reread them in the rdata function.
*/
j2k_read_deinit(j2k_read);
/* Don't override the read_options buffer as it will be
* readout by internal_j2k_rhdr().
*/
return GBM_ERR_OK;
}
/* ----------------------------------------------------------- */
/* JP2: JPEG-2000 file format */
/* j2k_jp2_rhdr - Read file header to init GBM struct */
GBM_ERR j2k_jp2_rhdr(const char *fn, int fd, GBM *gbm, const char *opt)
{
return j2k_rhdr(CODEC_JP2, fn, fd, gbm, opt);
}
/* ----------------------------------------------------------- */
/* J2K: JPEG-2000 codestream */
/* j2k_j2k_rhdr - Read file header to init GBM struct */
GBM_ERR j2k_j2k_rhdr(const char *fn, int fd, GBM *gbm, const char *opt)
{
return j2k_rhdr(CODEC_J2K, fn, fd, gbm, opt);
}
/* ----------------------------------------------------------- */
/* JPT: JPT-stream (JPEG 2000, JPIP) */
/* j2k_jpt_rhdr - Read file header to init GBM struct */
GBM_ERR j2k_jpt_rhdr(const char *fn, int fd, GBM *gbm, const char *opt)
{
return j2k_rhdr(CODEC_JPT, fn, fd, gbm, opt);
}
/* ----------------------------------------------------------- */
/* ----------------------------------------------------------- */
/* ----------------------------------------------------------- */
/* j2k_rpal() - Read palette */
GBM_ERR j2k_rpal(int fd, GBM *gbm, GBMRGB *gbmrgb)
{
J2K_PRIV_READ *j2k_read = (J2K_PRIV_READ *) gbm->priv;
/* read the header again */
GBM_ERR rc = internal_j2k_rhdr(fd, gbm, GBM_TRUE);
if (rc != GBM_ERR_OK)
{
/* cleanup is done in the called function already */
return rc;
}
if (gbm->bpp == 8) /* these are always grayscale bitmaps */
{
/* get the palette information */
const int palette_entries = 256;
/* init palette */
int i;
for (i = 0; i < palette_entries; i++)
{
gbmrgb[i].r = gbmrgb[i].g = gbmrgb[i].b = i;
}
}
/* We cannot expect the client calls rhdr,rpal,rdata in order.
* The client might just read the header and stop then.
*
* There is no other choice than freeing the structs
* and reread them in the rdata function.
*/
j2k_read_deinit(j2k_read);
return GBM_ERR_OK;
}
/* ----------------------------------------------------------- */
/* ----------------------------------------------------------- */
/* ----------------------------------------------------------- */
/* j2k_rdata() - Read data */
GBM_ERR j2k_rdata(int fd, GBM *gbm, gbm_u8 *data)
{
/* read the header again but with full data decoding */
GBM_ERR rc = internal_j2k_rhdr(fd, gbm, GBM_FALSE);
if (rc != GBM_ERR_OK)
{
/* cleanup is done in the called function already */
return rc;
}
else
{
J2K_PRIV_READ *j2k_read = (J2K_PRIV_READ *) gbm->priv;
const opj_image_t *image = j2k_read->image;
const int w = image->comps[0].w;
const int h = image->comps[0].h;
const int wr = int_ceildivpow2(w, image->comps[0].factor);
const int hr = int_ceildivpow2(h, image->comps[0].factor);
if ((w != gbm->w) || (h != gbm->h))
{
j2k_read_deinit(j2k_read);
return GBM_ERR_NOT_SUPP;
}
switch(j2k_read->image->numcomps)
{
case 1:
{
const int *pGray = image->comps[0].data;
const int sOffsetGray = image->comps[0].sgnd ? (1 << (image->comps[0].prec - 1)) : 0;
const int indices = wr * hr;
gbm_u16 *data16 = (gbm_u16 *) data;
int i, pad;
switch(j2k_read->bpp)
{
case 8:
if (gbm->bpp != 8)
{
j2k_read_deinit(j2k_read);
return GBM_ERR_NOT_SUPP;
}
for (i = 0; i < indices; i++)
{
const int index = w * hr - ((i) / (wr) + 1) * w + (i) % (wr);
*data++ = (gbm_u8)(pGray[index] + sOffsetGray);
if ((i + 1) % wr == 0)
{
for (pad = wr % 4 ? 4 - wr % 4 : 0; pad > 0; pad--) /* add padding */
{
*data++ = 0;
}
}
}
break;
/* ---------------- */
case 16:
switch(gbm->bpp)
{
case 8: /* via downsampling */
for (i = 0; i < indices; i++)
{
const int index = w * hr - ((i) / (wr) + 1) * w + (i) % (wr);
*data++ = (gbm_u8) CVT(pGray[index] + sOffsetGray);
if ((i + 1) % wr == 0)
{
for (pad = wr % 4 ? 4 - wr % 4 : 0; pad > 0; pad--) /* add padding */
{
*data++ = 0;
}
}
}
break;
case 48: /* via upsampling gray -> RGB */
for (i = 0; i < indices; i++)
{
const int index = w * hr - ((i) / (wr) + 1) * w + (i) % (wr);
const gbm_u16 g = pGray[index] + sOffsetGray;
*data16++ = g;
*data16++ = g;
*data16++ = g;
data += 6;
if ((i + 1) % wr == 0)
{
for (pad = (6 * wr) % 4 ? 4 - (6 * wr) % 4 : 0; pad > 0; pad--) /* add padding */
{
*data++ = 0;
}
data16 = (gbm_u16 *) data;
}
}
break;
default:
j2k_read_deinit(j2k_read);
return GBM_ERR_NOT_SUPP;
}
break;
/* ---------------- */
default:
j2k_read_deinit(j2k_read);
return GBM_ERR_NOT_SUPP;
}
}
break;
/* ---------------- */
case 3:
{
const int *p0 = image->comps[0].data;
const int *p1 = image->comps[1].data;
const int *p2 = image->comps[2].data;
const int sOffset0 = image->comps[0].sgnd ? (1 << (image->comps[0].prec - 1)) : 0;
const int sOffset1 = image->comps[1].sgnd ? (1 << (image->comps[1].prec - 1)) : 0;
const int sOffset2 = image->comps[2].sgnd ? (1 << (image->comps[2].prec - 1)) : 0;
const int indices = wr * hr;
gbm_u16 *data16 = (gbm_u16 *) data;
int i, pad;
switch(j2k_read->bpp)
{
case 24:
if (gbm->bpp != 24)
{
j2k_read_deinit(j2k_read);
return GBM_ERR_NOT_SUPP;
}
if (image->color_space == CLRSPC_SYCC) /* YUV ? */
{
for (i = 0; i < indices; i++)
{
const int index = w * hr - ((i) / (wr) + 1) * w + (i) % (wr);
const int y = p0[index] + sOffset0;
const int u = p1[index] + sOffset1;
const int v = p2[index] + sOffset2;
/* convert to BGR */
*data++ = y + (gbm_u8)((float)u / 0.493); /* B */
*data++ = y - (gbm_u8)((float)u * 0.39466) - (gbm_u8)((float)v * 0.5806); /* G */
*data++ = y + (gbm_u8)((float)v / 0.877); /* R */
if ((i + 1) % wr == 0)
{
for (pad = (3 * wr) % 4 ? 4 - (3 * wr) % 4 : 0; pad > 0; pad--) /* add padding */
{
*data++ = 0;
}
}
}
}
else /* RGB */
{
for (i = 0; i < indices; i++)
{
const int index = w * hr - ((i) / (wr) + 1) * w + (i) % (wr);
*data++ = p2[index] + sOffset2;
*data++ = p1[index] + sOffset1;
*data++ = p0[index] + sOffset0;
if ((i + 1) % wr == 0)
{
for (pad = (3 * wr) % 4 ? 4 - (3 * wr) % 4 : 0; pad > 0; pad--) /* add padding */
{
*data++ = 0;
}
}
}
}
break;
/* ---------------- */
case 48:
switch(gbm->bpp)
{
case 24: /* via downsampling */
if (image->color_space == CLRSPC_SYCC) /* YUV ? */
{
for (i = 0; i < indices; i++)
{
const int index = w * hr - ((i) / (wr) + 1) * w + (i) % (wr);
const int y = p0[index] + sOffset0;
const int u = p1[index] + sOffset1;
const int v = p2[index] + sOffset2;
/* convert to BGR */
*data++ = (gbm_u8) CVT(y + (gbm_u8)((float)u / 0.493)); /* B */
*data++ = (gbm_u8) CVT(y - (gbm_u8)((float)u * 0.39466) - (gbm_u8)((float)v * 0.5806)); /* G */
*data++ = (gbm_u8) CVT(y + (gbm_u8)((float)v / 0.877)); /* R */
if ((i + 1) % wr == 0)
{
for (pad = (3 * wr) % 4 ? 4 - (3 * wr) % 4 : 0; pad > 0; pad--) /* add padding */
{
*data++ = 0;
}
}
}
}
else /* RGB */
{
for (i = 0; i < indices; i++)
{
const int index = w * hr - ((i) / (wr) + 1) * w + (i) % (wr);
*data++ = (gbm_u8) CVT(p2[index] + sOffset2);
*data++ = (gbm_u8) CVT(p1[index] + sOffset1);
*data++ = (gbm_u8) CVT(p0[index] + sOffset0);
if ((i + 1) % wr == 0)
{
for (pad = (3 * wr) % 4 ? 4 - (3 * wr) % 4 : 0; pad > 0; pad--) /* add padding */
{
*data++ = 0;
}
}
}
}
break;
/* ---------------- */
case 48:
if (image->color_space == CLRSPC_SYCC) /* YUV ? */
{
for (i = 0; i < indices; i++)
{
const int index = w * hr - ((i) / (wr) + 1) * w + (i) % (wr);
const int y = p0[index] + sOffset0;
const int u = p1[index] + sOffset1;
const int v = p2[index] + sOffset2;
/* convert to BGR */
*data16++ = y + (gbm_u8)((float)u / 0.493); /* B */
*data16++ = y - (gbm_u8)((float)u * 0.39466) - (gbm_u8)((float)v * 0.5806); /* G */
*data16++ = y + (gbm_u8)((float)v / 0.877); /* R */
data += 6;
if ((i + 1) % wr == 0)
{
for (pad = (6 * wr) % 4 ? 4 - (6 * wr) % 4 : 0; pad > 0; pad--) /* add padding */
{
*data++ = 0;
}
data16 = (gbm_u16 *) data;
}
}
}
else /* RGB */
{
for (i = 0; i < indices; i++)
{
const int index = w * hr - ((i) / (wr) + 1) * w + (i) % (wr);
*data16++ = p2[index] + sOffset2;
*data16++ = p1[index] + sOffset1;
*data16++ = p0[index] + sOffset0;
data += 6;
if ((i + 1) % wr == 0)
{
for (pad = (6 * wr) % 4 ? 4 - (6 * wr) % 4 : 0; pad > 0; pad--) /* add padding */
{
*data++ = 0;
}
data16 = (gbm_u16 *) data;
}
}
}
break;
/* ---------------- */
default:
j2k_read_deinit(j2k_read);
return GBM_ERR_NOT_SUPP;
}
break;
/* ---------------- */
default:
j2k_read_deinit(j2k_read);
return GBM_ERR_NOT_SUPP;
}
}
break;
default:
j2k_read_deinit(j2k_read);
return GBM_ERR_NOT_SUPP;
}
/* cleanup */
j2k_read_deinit(j2k_read);
}
return GBM_ERR_OK;
}
/* ----------------------------------------------------------- */
/* ----------------------------------------------------------- */
/* ----------------------------------------------------------- */
static gbm_boolean make_output_palette(const GBMRGB gbmrgb[], gbm_u8 grey[], const char *opt)
{
const gbm_boolean k = ( gbm_find_word(opt, "k") != NULL );
const gbm_boolean r = ( gbm_find_word(opt, "r") != NULL );
const gbm_boolean g = ( gbm_find_word(opt, "g") != NULL );
const gbm_boolean b = ( gbm_find_word(opt, "b") != NULL );
int i;
#define SW4(a,b,c,d) ((a)*8+(b)*4+(c)*2+(d))
switch ( SW4(k,r,g,b) )
{
case SW4(0,0,0,0):
/* Default is the same as "k" */
case SW4(1,0,0,0):
for ( i = 0; i < 0x100; i++ )
{
grey[i] = (gbm_u8) ( ((gbm_u16) gbmrgb[i].r * 77U +
(gbm_u16) gbmrgb[i].g * 150U +
(gbm_u16) gbmrgb[i].b * 29U) >> 8 );
}
return GBM_TRUE;
case SW4(0,1,0,0):
for ( i = 0; i < 0x100; i++ )
{
grey[i] = gbmrgb[i].r;
}
return GBM_TRUE;
case SW4(0,0,1,0):
for ( i = 0; i < 0x100; i++ )
{
grey[i] = gbmrgb[i].g;
}
return GBM_TRUE;
case SW4(0,0,0,1):
for ( i = 0; i < 0x100; i++ )
{
grey[i] = gbmrgb[i].b;
}
return GBM_TRUE;
}
return GBM_FALSE;
}
/* ---------------------------------------- */
/* j2k_w() - Write bitmap file */
static GBM_ERR j2k_w(const OPJ_CODEC_FORMAT codec_format,
const char *fn, int fd, const GBM *gbm,
const GBMRGB *gbmrgb, const gbm_u8 *data, const char *opt)
{
opj_image_cmptparm_t cmptparms[3]; /* component parameters */
opj_event_mgr_t event_mgr; /* event manager */
opj_cparameters_t *parameters = NULL; /* compression parameters */
opj_image_t *image = NULL;
opj_cinfo_t *cinfo = NULL;
opj_cio_t *cio = NULL;
gbm_u8 grey[0x100] = { 0 };
const char *s = NULL;
int write_length = 0;
const int subsampling_dx = 1;
const int subsampling_dy = 1;
const int stride_src = ((gbm->w * gbm->bpp + 31) / 32) * 4;
int x, y, i_dst;
/* prepare the image */
memset(&cmptparms[0], 0, 3 * sizeof(opj_image_cmptparm_t));
cmptparms[0].dx = subsampling_dx;
cmptparms[0].dy = subsampling_dy;
cmptparms[0].w = gbm->w;
cmptparms[0].h = gbm->h;
cmptparms[0].sgnd = 0;
switch(gbm->bpp)
{
case 8: /* 1 component */
cmptparms[0].prec = 8;
cmptparms[0].bpp = 8;
if (! make_output_palette(gbmrgb, grey, opt))
{
return GBM_ERR_BAD_OPTION;
}
image = opj_image_create(1, &cmptparms[0], CLRSPC_GRAY);
if (image == NULL)
{
return GBM_ERR_MEM;
}
/* set the color component */
i_dst = 0;
for (y = 0; y < gbm->h; y++)
{
const gbm_u8 *data_src = data + ((gbm->h - y - 1) * stride_src);
for (x = 0; x < gbm->w; x++)
{
image->comps[0].data[i_dst] = grey[*data_src];
data_src++;
i_dst++;
}
}
break;
/* ------------------ */
case 24: /* 3 components 8bit */
cmptparms[0].prec = 8;
cmptparms[0].bpp = 8;
cmptparms[1] = cmptparms[0];
cmptparms[2] = cmptparms[0];
image = opj_image_create(3, &cmptparms[0], CLRSPC_SRGB);
if (image == NULL)
{
return GBM_ERR_MEM;
}
/* set the color component */
i_dst = 0;
for (y = 0; y < gbm->h; y++)
{
const gbm_u8 *data_src = data + ((gbm->h - y - 1) * stride_src);
for (x = 0; x < gbm->w; x++)
{
image->comps[2].data[i_dst] = *data_src++; /* B -> R */
image->comps[1].data[i_dst] = *data_src++; /* G -> G */
image->comps[0].data[i_dst] = *data_src++; /* R -> B */
i_dst++;
}
}
break;
/* ------------------ */
case 48: /* 3 components 16bit */
cmptparms[0].prec = 16;
cmptparms[0].bpp = 16;
cmptparms[1] = cmptparms[0];
cmptparms[2] = cmptparms[0];
image = opj_image_create(3, &cmptparms[0], CLRSPC_SRGB);
if (image == NULL)
{
return GBM_ERR_MEM;
}
/* set the color component */
i_dst = 0;
for (y = 0; y < gbm->h; y++)
{
const gbm_u16 *data16_src = (gbm_u16 *)(data + ((gbm->h - y - 1) * stride_src));
for (x = 0; x < gbm->w; x++)
{
image->comps[2].data[i_dst] = *data16_src++; /* B -> R */
image->comps[1].data[i_dst] = *data16_src++; /* G -> G */
image->comps[0].data[i_dst] = *data16_src++; /* R -> B */
i_dst++;
}
}
break;
default:
return GBM_ERR_NOT_SUPP;
}
/* set image offset and reference grid */
image->x0 = 0;
image->y0 = 0;
image->x1 = (gbm->w - 1) * subsampling_dy + 1;
image->y1 = (gbm->h - 1) * subsampling_dy + 1;
/* configure the event callbacks */
memset(&event_mgr, 0, sizeof(opj_event_mgr_t));
event_mgr.error_handler = j2k_gbm_error_callback;
event_mgr.warning_handler = j2k_gbm_warning_callback;
event_mgr.info_handler = j2k_gbm_info_callback;
/* set encoding parameters to default values */
parameters = gbmmem_malloc(sizeof(opj_cparameters_t));
if (parameters == NULL)
{
opj_image_destroy(image);
return GBM_ERR_MEM;
}
opj_set_default_encoder_parameters(parameters);
if (parameters->tcp_numlayers == 0)
{
parameters->tcp_rates[0] = 0; /* lossless bug */
parameters->tcp_numlayers++;
parameters->cp_disto_alloc = 1;
}
/* Decide if MCT should be used */
parameters->tcp_mct = (image->numcomps == 3) ? 1 : 0;
/* Write a comment */
parameters->cp_comment = NULL;
if ((s = gbm_find_word_prefix(opt, "comment=")) != NULL)
{
parameters->cp_comment = gbmmem_malloc(strlen(s)+1);
if (sscanf(s + 8, "%[^\"]", parameters->cp_comment) != 1)
{
if (sscanf(s + 8, "%[^ ]", parameters->cp_comment) != 1)
{
opj_image_destroy(image);
gbmmem_free(parameters->cp_comment);
gbmmem_free(parameters);
return GBM_ERR_J2K_BAD_COMMENT;
}
}
}
/* create the decompression scheme */
cinfo = opj_create_compress(codec_format);
if (cinfo == NULL)
{
opj_image_destroy(image);
gbmmem_free(parameters->cp_comment);
gbmmem_free(parameters);
return GBM_ERR_MEM;
}
/* catch events using our callbacks and give a local context */
opj_set_event_mgr((opj_common_ptr)cinfo, &event_mgr, NULL);
/* setup the decoder decoding parameters using user parameters */
opj_setup_encoder(cinfo, parameters, image);
/* open a byte stream */
cio = opj_cio_open((opj_common_ptr)cinfo, NULL, 0);
if (cio == NULL)
{
opj_destroy_compress(cinfo);
opj_image_destroy(image);
gbmmem_free(parameters->cp_comment);
gbmmem_free(parameters);
return GBM_ERR_MEM;
}
/* encode the image */
if (! opj_encode(cinfo, cio, image, NULL))
{
opj_cio_close(cio);
opj_destroy_compress(cinfo);
opj_image_destroy(image);
gbmmem_free(parameters->cp_comment);
gbmmem_free(parameters);
return GBM_ERR_NOT_SUPP;
}
write_length = cio_tell(cio);
/* write the encoded buffer to the file system */
if (gbm_file_write(fd, cio->buffer, write_length) != write_length)
{
opj_cio_close(cio);
opj_destroy_compress(cinfo);
opj_image_destroy(image);
gbmmem_free(parameters->cp_comment);
gbmmem_free(parameters);
return GBM_ERR_WRITE;
}
opj_cio_close(cio);
opj_destroy_compress(cinfo);
opj_image_destroy(image);
gbmmem_free(parameters->cp_comment);
gbmmem_free(parameters);
return GBM_ERR_OK;
}
/* ------------ */
/* JP2: JPEG-2000 file format */
/* j2k_jp2_w() - Write bitmap file */
GBM_ERR j2k_jp2_w(const char *fn, int fd, const GBM *gbm, const GBMRGB *gbmrgb, const gbm_u8 *data, const char *opt)
{
return j2k_w(CODEC_JP2, fn, fd, gbm, gbmrgb, data, opt);
}
/* ----------------------------------------------------------- */
/* J2K: JPEG-2000 codestream */
/* j2k_j2k_w() - Write bitmap file */
GBM_ERR j2k_j2k_w(const char *fn, int fd, const GBM *gbm, const GBMRGB *gbmrgb, const gbm_u8 *data, const char *opt)
{
return j2k_w(CODEC_J2K, fn, fd, gbm, gbmrgb, data, opt);
}
/* ----------------------------------------------------------- */
/* ----------------------------------------------------------- */
/* ----------------------------------------------------------- */
/* j2k_err - map error code to error message */
const char *j2k_err(GBM_ERR rc)
{
J2K_GBMERR_MSG *j2k_errmsg_p = j2k_errmsg;
while (j2k_errmsg_p->error_message)
{
if (j2k_errmsg_p->rc == rc)
{
return j2k_errmsg_p->error_message;
}
j2k_errmsg_p++;
}
return NULL;
}
#endif
| 2.03125 | 2 |
2024-11-18T22:11:03.959717+00:00 | 2022-11-29T09:15:52 | 35190f341e0ea9ae3f681d825cd874e4906984f7 | {
"blob_id": "35190f341e0ea9ae3f681d825cd874e4906984f7",
"branch_name": "refs/heads/master",
"committer_date": "2022-11-29T09:15:52",
"content_id": "bdb40d4ab9e990e3b778602ad80238978f8bd3b1",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "7d88fbcee18031d4e472977ecce32e0b463e20fe",
"extension": "c",
"filename": "arguments_util.c",
"fork_events_count": 5,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 1179755,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 9678,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/viriatum_commons/util/arguments_util.c",
"provenance": "stackv2-0072.json.gz:38873",
"repo_name": "hivesolutions/viriatum",
"revision_date": "2022-11-29T09:15:52",
"revision_id": "969810a94a18181bc45388cc33a060e9f71bf928",
"snapshot_id": "5e08e108083d527ba77379fcb6d4c4274205727a",
"src_encoding": "UTF-8",
"star_events_count": 7,
"url": "https://raw.githubusercontent.com/hivesolutions/viriatum/969810a94a18181bc45388cc33a060e9f71bf928/src/viriatum_commons/util/arguments_util.c",
"visit_date": "2022-12-01T18:29:20.180895"
} | stackv2 | /*
Hive Viriatum Commons
Copyright (c) 2008-2020 Hive Solutions Lda.
This file is part of Hive Viriatum Commons.
Hive Viriatum Commons is free software: you can redistribute it and/or modify
it under the terms of the Apache License as published by the Apache
Foundation, either version 2.0 of the License, or (at your option) any
later version.
Hive Viriatum Commons is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
Apache License for more details.
You should have received a copy of the Apache License along with
Hive Viriatum Commons. If not, see <http://www.apache.org/licenses/>.
__author__ = João Magalhães <[email protected]>
__version__ = 1.0.0
__revision__ = $LastChangedRevision$
__date__ = $LastChangedDate$
__copyright__ = Copyright (c) 2008-2020 Hive Solutions Lda.
__license__ = Apache License, Version 2.0
*/
#include "stdafx.h"
#include "arguments_util.h"
ERROR_CODE process_arguments(int argc, char *argv[], struct hash_map_t **arguments_pointer) {
/* allocates space for the index counter */
unsigned int index;
/* allocates the space for the current argument string
in the iteration */
char *current_argument;
/* allocates space for both the argument holder, to
be created every iteration of the argument retrieval */
struct argument_t *argument;
struct hash_map_t *arguments;
/* creates the hash map that will hold the various
arguments */
create_hash_map(&arguments, 0);
/* iterates over all the argument except the
first (file name value) */
for(index = 1; index < (unsigned int) argc; index++) {
/* allocates space for the "new" argument to be parsed */
argument = (struct argument_t *) MALLOC(sizeof(struct argument_t));
/* retrievs the current argument, then processes it
using the default (simple) parser and sets it in
the arguments map */
current_argument = argv[index];
_process_argument(current_argument, argument);
set_value_string_hash_map(
arguments,
(unsigned char *) argument->key,
(void *) argument
);
}
/* sets the hash map of arguments as the value pointed
by the arguments pointer */
*arguments_pointer = arguments;
/* raises no error */
RAISE_NO_ERROR;
}
ERROR_CODE delete_arguments(struct hash_map_t *arguments) {
/* allocates space for the pointer to the element and
for the argument to be retrieved */
struct hash_map_element_t *element;
struct argument_t *argument;
/* allocates space for the iterator for the arguments */
struct iterator_t *arguments_iterator;
/* creates an iterator for the arguments hash map */
create_element_iterator_hash_map(arguments, &arguments_iterator);
/* iterates continuously */
while(TRUE) {
/* retrieves the next value from the arguments iterator */
get_next_iterator(arguments_iterator, (void **) &element);
/* in case the current module is null (end of iterator)
must break the current loop */
if(element == NULL) { break; }
/* retrieves the hash map value for the key, in order to
be used in the releasing of the memory */
get_value_hash_map(
arguments,
element->key,
element->key_string,
(void **) &argument
);
/* releases the argument memory */
FREE(argument);
}
/* deletes the iterator for the arguments hash map */
delete_iterator_hash_map(arguments, arguments_iterator);
/* deletes the hash map that holds the arguments */
delete_hash_map(arguments);
/* raises no error */
RAISE_NO_ERROR;
}
ERROR_CODE print_arguments(struct hash_map_t *arguments) {
/* allocates space for the pointer to the element and
for the argument to be retrieved */
struct hash_map_element_t *element;
struct argument_t *argument;
/* allocates space for the iterator for the arguments */
struct iterator_t *arguments_iterator;
/* creates an iterator for the arguments hash map */
create_iterator_hash_map(arguments, &arguments_iterator);
/* prints the initial arguments header */
PRINTF("Arguments\n");
/* iterates continuously */
while(TRUE) {
/* retrieves the next value from the arguments iterator */
get_next_iterator(arguments_iterator, (void **) &element);
/* in case the current module is null (end of iterator) */
if(element == NULL) {
/* breaks the loop */
break;
}
/* retrievs the hash map value for the key */
get_value_hash_map(
arguments,
element->key,
element->key_string,
(void **) &argument
);
/* in case the argument is of type value */
if(argument->type == VALUE_ARGUMENT) {
/* prints the value with the key and argument */
PRINTF_F(" %s => %s\n", argument->key, argument->value);
}
/* otherwise it must be a key only argument */
else {
/* prints just the key and a null reference */
PRINTF_F(" %s => NULL\n", argument->key);
}
}
/* deletes the iterator for the arguments hash map */
delete_iterator_hash_map(arguments, arguments_iterator);
/* raises no error */
RAISE_NO_ERROR;
}
ERROR_CODE _process_argument(char *argument_value, struct argument_t *argument) {
/* allocates space for the index counter */
unsigned int index;
/* allocates space for the current value in the
parsing loop (iteration item) */
char current;
/* starts the state value with the initial value */
unsigned int state = ARGUMENT_INITIAL;
/* starts the mark value wth the base index */
size_t mark = 0;
/* retrieves the argument size for processing */
size_t argument_size = strlen(argument_value);
/* sets the argument to type key (just a name) */
argument->type = SINGLE_ARGUMENT;
/* iterates over all the characters present in
the argument string to parse the argument */
for(index = 0; index < argument_size; index++) {
/* retrieves the current iteration values, the
current character of the argument */
current = argument_value[index];
/* switch over the current (parsing) state */
switch(state) {
case ARGUMENT_INITIAL:
/* in case the current character is not a
separator character there is an error */
if(current != '-') {
/* raises an error */
RAISE_ERROR_M(RUNTIME_EXCEPTION_ERROR_CODE, (unsigned char *) "Problem parsing option");
}
/* changes the state to the first */
state = ARGUMENT_FIRST;
/* breaks the switch */
break;
case ARGUMENT_FIRST:
if(current == '-') {
/* marks the next index as the start point
for the key string */
mark = index + 1;
/* changes the state to the second */
state = ARGUMENT_SECOND;
} else {
/* marks the current index as the start point
for the key string */
mark = index;
/* changes the state to the key (parsing) */
state = ARGUMENT_KEY;
}
/* breaks the switch */
break;
case ARGUMENT_SECOND:
case ARGUMENT_KEY:
if(current == '=') {
/* sets the argument to type key and value */
argument->type = VALUE_ARGUMENT;
/* copies the key value into the appropriate variable
in the argument */
memcpy(argument->key, argument_value + mark, index - mark);
argument->key[index - mark] = '\0';
/* marks the current index as the start point
for the value string */
mark = index + 1;
/* changes the state to the value (parsing) */
state = ARGUMENT_VALUE;
} else {
}
/* breaks the switch */
break;
}
}
/* switches one final time over the state to close
the pending values */
switch(state) {
case ARGUMENT_SECOND:
case ARGUMENT_KEY:
/* copies the key value into the appropriate variable
in the argument */
memcpy(argument->key, argument_value + mark, index - mark);
argument->key[index - mark] = '\0';
/* breaks the switch */
break;
case ARGUMENT_VALUE:
/* copies the value value into the appropriate variable
in the argument */
memcpy(argument->value, argument_value + mark, index - mark);
argument->value[index - mark] = '\0';
/* breaks the switch */
break;
}
/* raises no error */
RAISE_NO_ERROR;
}
| 2.515625 | 3 |
2024-11-18T22:11:04.088125+00:00 | 2020-05-25T00:19:13 | e3a5f30e08436f89a16087af832d426376e6b83d | {
"blob_id": "e3a5f30e08436f89a16087af832d426376e6b83d",
"branch_name": "refs/heads/master",
"committer_date": "2020-05-25T00:19:13",
"content_id": "6ef33fec7a31e230f860916e25d9d46f107c67fe",
"detected_licenses": [
"MIT"
],
"directory_id": "d9c7993a02bbd35895652aa0bb24b3f70a73c215",
"extension": "c",
"filename": "Q4_2.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 246442642,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1406,
"license": "MIT",
"license_type": "permissive",
"path": "/parallel/hw4/Q4_2.c",
"provenance": "stackv2-0072.json.gz:39130",
"repo_name": "JinhuaSu/homework",
"revision_date": "2020-05-25T00:19:13",
"revision_id": "1a76af16cdbcdd038b6a4134f3b596ce2b1897d2",
"snapshot_id": "7d05449f03f3ad70dcd57f7a54f4ee354e5b5f05",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/JinhuaSu/homework/1a76af16cdbcdd038b6a4134f3b596ce2b1897d2/parallel/hw4/Q4_2.c",
"visit_date": "2021-03-10T09:29:56.926254"
} | stackv2 | #include<mpi.h>
#include<stdio.h>
#include<stdlib.h>
int main(){
MPI_Init(NULL,NULL);
int world_rank, world_size;
MPI_Comm_size(MPI_COMM_WORLD, &world_size);
MPI_Comm_rank(MPI_COMM_WORLD, &world_rank);
int *send_data, *recv_data;
int total_number = 10000;
int recv_num = total_number / world_size;
if(world_rank == 1){
send_data = (int *)malloc(sizeof(int)*total_number);
for(int i=0;i<total_number;i++){
send_data[i] = i+1;
}
}
recv_data = (int *)malloc(sizeof(int)*recv_num);
MPI_Scatter(send_data,recv_num,MPI_INT,recv_data,recv_num,MPI_INT,1,MPI_COMM_WORLD);
MPI_Barrier(MPI_COMM_WORLD);
if(world_rank == 1){
free(send_data);
}
long* sum_array;
if(world_rank == 0){
sum_array = (long*)malloc(sizeof(long)*world_size);
}
long sum_data=0;
for(int i=0;i<recv_num;i++){
sum_data += (long)recv_data[i];
}
free(recv_data);
MPI_Gather(&sum_data,1,MPI_LONG,sum_array,1,MPI_LONG,0,MPI_COMM_WORLD);
if(world_rank == 0){
long final_sum = 0;
for(int i = 0; i<world_size; i++){
printf("Processor 0 received sub-sum result from processor %d: %ld\n" , i,sum_array[i]);
final_sum += sum_array[i];
}
free(sum_array);
printf("Total sum is %ld\n", final_sum);
}
MPI_Finalize();
} | 2.96875 | 3 |
2024-11-18T22:11:04.422991+00:00 | 2023-04-28T11:57:35 | d9216b11af8d451e841882dea5b8bb6eb9e93e3b | {
"blob_id": "d9216b11af8d451e841882dea5b8bb6eb9e93e3b",
"branch_name": "refs/heads/main",
"committer_date": "2023-04-28T11:57:35",
"content_id": "c08ca06bab1d1aa9ce5d6c50efe424c3ad9fe260",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "e659e7e3d19b602e47b6414abcdb48b99a67a7bf",
"extension": "c",
"filename": "test_retention.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 610082520,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3544,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/prime_store_attack/src/experiments/test_retention.c",
"provenance": "stackv2-0072.json.gz:39259",
"repo_name": "0xADE1A1DE/GoT",
"revision_date": "2023-04-28T11:57:35",
"revision_id": "5bac7ece92f61025b7c1942c59b95e8a999ec231",
"snapshot_id": "8dd8878ce8acc12f805ad2a8583755f6cb36388f",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/0xADE1A1DE/GoT/5bac7ece92f61025b7c1942c59b95e8a999ec231/prime_store_attack/src/experiments/test_retention.c",
"visit_date": "2023-08-04T11:17:16.207184"
} | stackv2 | #include <assert.h>
#include <stdint.h>
#include <stddef.h>
#include <unistd.h>
#include "measure/measure.h"
#include "amplification/tree_amplification.h"
#include "retention/retention.h"
#include "util.h"
#include "consts.h"
void parse_retention_cmdline(int argc, char *argv[], int *pages, int *per_ev, int *shrink_factor, int *interleave);
amplification_metadata * const retention_amplification = &tree_amplification_100us;
const measure_metadata * const retention_conforming_measure = &tree_amplification_100us_measure_metadata;
int test_retention(int argc, char *argv[]) {
int pages = 0;
int per_ev = 0;
int shrink_factor = 3;
int interleave = 3;
parse_retention_cmdline(argc, argv, &pages, &per_ev, &shrink_factor, &interleave);
if (pages == 0 || per_ev == 0) {
printf("Usage: %s %s [-p] [pages] [-e] [per_ev] [-s] [shrink_factor] [-i] [interleave]\n", argv[0], argv[1]);
return 0;
}
initialize_clear_cache_allocation();
uintptr_t trash = retention_amplification->initialize(retention_amplification, trash);
if (!retention_amplification->verify(retention_amplification))
return 0;
eviction_set *eviction_sets = find_eviction_sets(100);
assert(eviction_sets != NULL);
retention_metadata __attribute__ ((aligned (PAGE_SIZE))) metadata = {.allowed_double_cache_lines={0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, .pages=pages, .per_ev=per_ev, .shrink_factor=shrink_factor, .interleave=interleave};
retention_scheme __attribute__ ((aligned (PAGE_SIZE))) scheme = initialize_retention_scheme(metadata, eviction_sets);
int retention_bank_size = total_retention_entries(scheme.metadata);
int measure_size = total_measure_entries(scheme.metadata);
int decayed = 0;
char *measurements = malloc(measure_size);
char *pattern = malloc(retention_bank_size);
for (int i = 0; i < retention_bank_size; i++)
pattern[i] = 1;
trash = clear_all_caches(0);
for (int i = 0; i < retention_bank_size; i++) {
asm volatile("mfence\nlfence");
if (pattern[i])
fetch_address(retention_get_entry(&scheme, i), LLC);
asm volatile("mfence\nlfence");
}
for (int i = 0; i < measure_size; i++) {
uint64_t result = retention_measure(&scheme, i, retention_conforming_measure, trash);
trash += result;
measurements[i] = !retention_conforming_measure->is_in_cache(result);
decayed += (measurements[i] != pattern[i]);
}
printf("Decays: %d/%d\n", decayed, measure_size);
for (int i = 0; i < measure_size; i++) {
printf("%01x", measurements[i]);
}
printf("\n");
return 0;
}
void parse_retention_cmdline(int argc, char *argv[], int *pages, int *per_ev, int *shrink_factor, int *interleave) {
int opt;
while ((opt = getopt(argc, argv, "p:e:s:i:h")) != -1) {
switch (opt) {
case 'p':
*pages = atoi(optarg);
break;
case 'e':
*per_ev = atoi(optarg);
break;
case 's':
*shrink_factor = atoi(optarg);
break;
case 'i':
*interleave = atoi(optarg);
break;
case 'h':
printf("Usage: %s %s [-p] [pages] [-e] [per_ev] [-s] [shrink_factor] [-i] [interleave]\n", argv[0], argv[1]);
default:
exit(EXIT_FAILURE);
}
}
} | 2.109375 | 2 |
2024-11-18T22:11:04.828650+00:00 | 2015-07-19T19:32:30 | fda6c7a88d7f55c49e5840a2f0f6cb39b469cd95 | {
"blob_id": "fda6c7a88d7f55c49e5840a2f0f6cb39b469cd95",
"branch_name": "refs/heads/master",
"committer_date": "2015-07-19T19:32:30",
"content_id": "1c8ca812482f51aea3b3a8a2919d0c57ae97f050",
"detected_licenses": [
"MIT"
],
"directory_id": "41c89d197d19130d115cd3c0a1934e7eb9ad794e",
"extension": "h",
"filename": "globals.h",
"fork_events_count": 2,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 35299038,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1169,
"license": "MIT",
"license_type": "permissive",
"path": "/src/globals.h",
"provenance": "stackv2-0072.json.gz:39645",
"repo_name": "ddaygold/speed_servo",
"revision_date": "2015-07-19T19:32:30",
"revision_id": "281bb5a734f276c90fff38bbdc7685f44d34fb01",
"snapshot_id": "fa8172a5e8d6fce5c76ecc0e060d4611d63a6716",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/ddaygold/speed_servo/281bb5a734f276c90fff38bbdc7685f44d34fb01/src/globals.h",
"visit_date": "2020-05-20T15:40:39.693772"
} | stackv2 | #include <Wire.h>
#include <Servo.h>
#include <PID_v1.h>
#include <EEPROM.h>
//Pins for the Quad encoder
#define PINA 2
#define PINB 3
//Pin to specify the i2c address
//High is address 1, low is address 0
#define ADDRESS_PIN 13
volatile double speed = 0;
volatile double pterm = 0.0;
volatile double iterm = 0.0;
volatile double dterm = 0.0;
enum command{
SPEED = 0,
PTERM = 1,
ITERM = 2,
DTERM = 3,
VOLTAGE = 4,
ESTOP = 5
};
#define VOLTAGE_PIN A0
#define VICTOR_PIN 5
Servo victor;
volatile double ticks = 0;
int last_ticks = 0;
/*
If the Victor motor controller PWM width extremes are 870 microsecond and 2140 microseconds, with
a center at 1510 microseconds, we have a width of 635 microseconds
*/
#define PWM_CENTER 1510
#define PWM_WIDTH 635
int current_speed = 0;
double controller_output = PWM_CENTER;
PID controller(&ticks, &controller_output, &speed,
pterm,iterm,dterm,
DIRECT);
long last_tuning_update = 0;
void processPID();
void receive(int incoming);
void writeTicks();
void setParam(int incoming, volatile double * dest);
void setParam(int incoming, volatile int * dest);
void spin();
void printDebug();
| 2.15625 | 2 |
2024-11-18T22:11:04.998750+00:00 | 2016-01-06T06:54:21 | 5ab7e5960a7a0f54bcb260ae29a756cd43b6bb05 | {
"blob_id": "5ab7e5960a7a0f54bcb260ae29a756cd43b6bb05",
"branch_name": "refs/heads/master",
"committer_date": "2016-01-06T06:54:21",
"content_id": "1d73cb8ccbf94b5b6cb7f216d05fb19cd4004db4",
"detected_licenses": [
"MIT"
],
"directory_id": "19c1612ec9be41e8b0e339194883783114d33be3",
"extension": "c",
"filename": "reader.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": 669,
"license": "MIT",
"license_type": "permissive",
"path": "/PySeis/segd/reader.c",
"provenance": "stackv2-0072.json.gz:39774",
"repo_name": "iceseismic/PySeis",
"revision_date": "2016-01-06T06:54:21",
"revision_id": "7e7b6cc464f0f9735eab514e5a7e8cd8f8086a9c",
"snapshot_id": "2d48d9757dedaf7f9e221a1a8b024f05c0d8b10e",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/iceseismic/PySeis/7e7b6cc464f0f9735eab514e5a7e8cd8f8086a9c/PySeis/segd/reader.c",
"visit_date": "2021-01-18T00:09:48.975029"
} | stackv2 | #include <Python.h>
static PyObject* read_header(PyObject* self, PyObject* args)
{
const char *filename;
unsigned char header[32];
int i;
if (!PyArg_ParseTuple(args, "s", &filename))
return NULL;
printf("Open %s\n", filename);
FILE *fp;
fp=fopen(filename, "rb");
fread(header, 32, 1, fp);
for(i=0; i<32; i++)
printf("%d\n", header[i]);
Py_RETURN_NONE;
}
static PyMethodDef ReadMethods[] =
{
{"read_header", read_header, METH_VARARGS, "Reader SEGD file header"},
{NULL, NULL, 0, NULL}
};
PyMODINIT_FUNC
initreader(void)
{
(void) Py_InitModule("reader", ReadMethods);
} | 2.1875 | 2 |
2024-11-18T22:11:05.468914+00:00 | 2020-11-06T01:25:21 | c14ff3ddbac4988d4dec2587e3535b400cc2d0e4 | {
"blob_id": "c14ff3ddbac4988d4dec2587e3535b400cc2d0e4",
"branch_name": "refs/heads/main",
"committer_date": "2020-11-06T01:25:21",
"content_id": "2ec02843fabe39942c7fdcf3d391b614f47a2905",
"detected_licenses": [
"MIT"
],
"directory_id": "50fb6964978ec432939d75b8d989e01360bfa063",
"extension": "c",
"filename": "main.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": 11154,
"license": "MIT",
"license_type": "permissive",
"path": "/main.c",
"provenance": "stackv2-0072.json.gz:40288",
"repo_name": "kpez/CEEshell",
"revision_date": "2020-11-06T01:25:21",
"revision_id": "ff35c89a48366e7c0b5bc75fcf5aa359320de088",
"snapshot_id": "4525fd36e17b9d19db911e21e1586febc30a3bf5",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/kpez/CEEshell/ff35c89a48366e7c0b5bc75fcf5aa359320de088/main.c",
"visit_date": "2023-01-05T15:49:11.523330"
} | stackv2 | /*
* main.c
* Kia Pezesh V00845475
* CSC360 Summer 2020, Assignment 1
* A simple program to illustrate the use of the GNU Readline library
* Readline library is applied to a simple shell program
*
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>
#include <readline/readline.h>
#include <readline/history.h>
#define MAX_INPUT 15
#define MAX_SIZE 256
#define MAX_BG_JOBS 5
//struct to keep track of bg jobs
struct bg_job {
char command[MAX_SIZE];
pid_t pid;
int status; //-1 = stopped, 0 = NULL, 1 = running
};
//initialize array of background job slots
struct bg_job bg_jobs[MAX_BG_JOBS];
//list information regarding bg job slots (and whatever bg jobs they may contain)
void bg_list(){
int i;
int count = 0; //initialize as 0 in case all slots are empty
char s; //status char for printing
printf("Printing background jobs: \n");
//check every bg job slot
for (i=0;i<MAX_BG_JOBS;i++){
//convert int status to char s for printing
if (bg_jobs[i].status > 0) s = 'R';
else if (bg_jobs[i].status < 0) s = 'S';
else {//s = '\0';
printf("%d : Empty\n", i);
continue;
}
//print info and increment count
printf("%d [%c]: command '%s', pid %x\n",i, s, bg_jobs[i].command, bg_jobs[i].pid);
if (bg_jobs[i].pid) count++;
}
printf("Total Background Jobs: %d\n", count);
}
//sends SIGSTOP to specified bg job
void bg_stop(char* args[]){
if(!args[1] || (args[1] && strlen(args[1])>1)){
printf("Invalid input. Please specify which job to stop. eg. 'stop 1' to stop the process in slot 1.\n");
return;
}
//convert char input to int
int j = atoi(args[1]);
if (j>4){
printf("Invalid input. Background jobs comprise only of slots 0 to 4.\n");
}else{
if (bg_jobs[j].status < 0){
printf("Background process in slot %d is already stopped.\n",j);
return;
}
if (!bg_jobs[j].pid){
printf("Slot %d is empty.\n", j);
return;
}
kill(bg_jobs[j].pid, SIGSTOP);
printf("Stop signal sent to background job slot %d\n", j);
bg_jobs[j].status = -1;
}
}
//sends SIGCONT to specified bg job
void bg_start(char* args[]){
if(!args[1] || (args[1] && strlen(args[1])>1)){
printf("Invalid input. Please specify which job to start. eg. 'start 1' to start the process in slot 1.\n");
return;
}
int j = atoi(args[1]);
if (j>4){
printf("Invalid input. Background jobs comprise only of slots 0 to 4.\n");
}else{
if (bg_jobs[j].status > 0){
printf("Background process in slot %d is already running.\n",j);
return;
}
if (!bg_jobs[j].pid){
printf("Slot %d is empty.\n", j);
return;
}
kill(bg_jobs[j].pid, SIGCONT);
printf("Start signal sent to background job slot %d\n", j);
bg_jobs[j].status = 1;
}
}
//sends SIGTERM to specified bg job
void bg_kill(char* args[]){
if(!args[1] || (args[1] && strlen(args[1])>1)){
printf("Invalid input. Please specify which job to kill. eg. 'bgkill 1' to kill the process in slot 1.\n");
return;
}
int j = atoi(args[1]);
if (j>4){
printf("Invalid input. Background jobs comprise only of slots 0 to 4.\n");
}else{
if (!bg_jobs[j].status){
printf("No process is currently running in background slot %d.\n",j);
return;
}
if (!bg_jobs[j].pid){
printf("Slot %d is empty.\n", j);
return;
}
//if process in slot j is stopped, start it before sending kill signal.
//Otherwise leaves a pseudo-zombie (the process is still exited upon closing the shell but is no longer kept track of in bglist)
if (bg_jobs[j].status < 0) {
kill(bg_jobs[j].pid, SIGCONT);
bg_jobs[j].status = 1;
}
kill(bg_jobs[j].pid, SIGTERM);
bg_jobs[j].status = 0;
printf("Kill signal sent to background job slot %d\n", j);
}
}
//child process clean-up upon exiting parent process (ensure no zombies).
void bgkill(int n){
kill(bg_jobs[n].pid, SIGTERM);
}
//execute specified command in the foreground
void fgexec (char* args[]){
pid_t pid = fork();
if (pid < 0) { //this should never be reached
printf("fork() FAILED. \n");
}
if (pid == 0) { //child process
/** for debugging
* printf("Child process started. About to exec...");
* int rc = execvp(args[0], args);
*/
execvp(args[0], args);
//only reaches this point upon failed execution
printf("Invalid input. Specified command not found.\n");
/** for debugging
*printf("execvp returned. ERROR in execvp execution: %d.\n", rc);
*printf("Sending kill signal. \n");
*/
kill(getpid(),SIGTERM); //NOTE: waitpid() w/ WNOHANG on the SIGTERM terminated process returns status 'f'
printf("ERROR: kill signal failed.\n");
} else { //pid > 0 ~~ parent process
int status;
wait(&status); //stuck here until child terminates
/** for debugging
* id_t cpid = wait(&status); //stuck here until child terminates
* printf("Child pid: %x\n", pid);
* printf("Child finished: status: %x cpid:%x\n", status, cpid);
*/
}
}
//execute specified command in the background
void bgexec (char* args[]){
pid_t pid = fork();
if (pid < 0) { //this should never be reached
printf("BG: fork() FAILED. \n");
}
if (pid == 0) { //child process
/** for debugging
* printf("BG: Child process started. About to exec...\n");
* int rc = execvp(args[0], args);
*/
execvp(args[0], args);
//only reaches thi point upon failed execution
printf("Invalid input. Specified command not found.\n");
/** for debugging
* printf("BG: execvp returned. ERROR in execvp execution: execvp() returns %d.\n", rc);
* printf("Sending kill signal. \n");
*/
kill(getpid(),SIGTERM);
printf("ERROR: kill signal failed.\n");
} else { //pid > 0 ~~ parent process
int i;
//printf("child id: %x\n", pid);
for (i=0;i<MAX_BG_JOBS; i++){
if (!bg_jobs[i].pid){
bg_jobs[i].pid = pid;
bg_jobs[i].status = 1;
int j=1;
strcpy(bg_jobs[i].command, args[0]); //copy first args token into bg_jobs[].command
while(args[j]){ //copy remaining tokens into bg_jobs[].command
strcat(bg_jobs[i].command, " ");
strcat(bg_jobs[i].command, args[j]);
j++;
}
break; //exit for loop once open slot was found
}
}
}
}
/**checks user input args for built in commands.
* return 1 if shell is to continue to next iteration of its for loop.
* return 0 if user did not invoke a built in command.
*/
int built_in_check(char* args[]){
//built in 'cd' command
if (!strcmp(args[0],"cd")) {
if (args[2]) {
printf("Incorrect input arguments for command: cd \n");
return 1;
}
if (chdir(args[1]) != 0) printf("cd to '%s' failed.\n", args[1]);
return 1;
}
//list bg jobs
if (!strcmp(args[0],"bglist")){
bg_list();
return 1;
}
//kill specified bg job
if(!strcmp(args[0], "bgkill")){
bg_kill(args);
return 1;
}
//pause specified bg job
if(!strcmp(args[0], "stop")){
bg_stop(args);
return 1;
}
//continue specified bg job
if(!strcmp(args[0], "start")){
bg_start(args);
return 1;
}
//user input error handling:
if(!strcmp(args[0], "bgstop")){
printf("Unknown command. Try 'stop' instead.\n");
return 1;
}
if(!strcmp(args[0], "bgstart")){
printf("Unknown command. Try 'start' instead.\n");
return 1;
}
if(!strcmp(args[0], "kill")){
printf("Opertation not permitted. Try 'bgkill' instead.\n");
return 1;
}
if(!strcmp(args[0], "list")){
printf("Unknown command. Try 'bglist' instead.\n");
return 1;
}
return 0;
}
/** parse method takes tokenized user input from cmd
* and copies only the first 15 items into a new char* variable
* before returning.
*/
void parse (char* input, char* args[]) {
int i=0;
while(input){
args[i]=input;
input = strtok(NULL, " "); //move input to next token
//printf("%s, ",args[i]); //DEBUG
i++;
if (i == 15 ) break; //ASSUMPTION: MAX 14 PARAMETERS IN A COMMAND
}
args[i] = (char *)0; //end with NULL
}
int main (int argc, char * argv[]){
for (;;) {
sleep(0.2); //avoids some instances of child processes printing after ">"
char cwd[MAX_SIZE]; //'cwd'=='current working directory'
getcwd(cwd, (size_t)MAX_SIZE);
printf ("%s", cwd);
char *cmd = readline (">");
//printf ("Got: [%s]\n", cmd);
//auto-clearing terminated background job slots
int i, rc, status;
for (i=0;i<MAX_BG_JOBS; i++){
rc = waitpid(bg_jobs[i].pid, &status, WNOHANG);
if (bg_jobs[i].pid && (!bg_jobs[i].status || rc == -1)){
printf("Background process in slot %d has terminated.\n", i); //assignment pdf specifies user must be updated upon bg process terminating
bg_jobs[i].pid = 0;
bg_jobs[i].status = 0;
strcpy(bg_jobs[i].command, "");
}
}
//tokenize input
char *input = strtok(cmd, " ");
char *args[MAX_INPUT];
//check if input is empty; if so, continue loop
if (!input) continue;
//assume fg execution unless...
int bg = 0;
if (!strcmp(input, "bg")) {
bg = 1;
input = strtok(NULL, " "); //increment to next token (preparation for parse() to limit input to 15 args)
if (!input) {
printf("Error: missing arguments for command 'bg'\n");
free (cmd);
continue;
}
}
//parse tokenized input and uphold MAX_INPUT constraint. Copy result into args
parse(input, args);
//if bg==1, execute specified command in the background ()perform necessary logic beforehand to check if slots are available)
if (bg){
//printf("BACKGROUND EXECUTION\n");
int count=0;
for(int i=0;i<MAX_BG_JOBS;i++){
if(bg_jobs[i].pid) count++;
}
if (count>4) {
printf("Background job slots are full. Use 'kill n' command to free slot n.\n");
free(cmd);
continue;
}
bgexec(args);
free(cmd);
continue;
}
//built in 'exit' command
if (!strcmp(args[0],"exit")){
for(int i=0;i<MAX_BG_JOBS;i++){ //kill every child process before exiting the shell
if (bg_jobs[i].pid) bgkill(i);
}
free(cmd);
break;//exit for loop, return 0;
}
//built in 'pwd' command. (Unnecessary b/c execvp() can do this but included as per a1 part II desc.)
if (!strcmp(args[0],"pwd")) { //didn't put this into built_in_check() so I wouldn't have to re-obtain cwd
printf("%s\n", cwd);
free(cmd);
continue;
}
//check for rest of built in commands (just to clean up main() a little)
if (built_in_check(args)){
free(cmd);
continue;
}
//if user input was not a built in command nor set for background execution, execute in the foreground.
//printf("FG execution starting...\n");
fgexec(args);
free (cmd);
}
return 0;
}
/** BUG: if user inputs an invalid command to run in the background, eg. 'bg asda', the command will still show as a process upon calling bglist for the next iteration of the shell.
* tried using waitpid() with WNOHANG to detect a failed execution in its child process and stop the command from being placed into bglist, but upon immediate execution of waitpid() in the parent,
* it is returning 0 (which is the same as a regular, successfully executed process).
* I think this could be fixed if I were to allocate some shared memory to have a shared variable between child/parent to flag whether this is the case or not, but I believe that is beyond the scope of this assignment.
*/
| 3.4375 | 3 |
2024-11-18T22:11:06.304116+00:00 | 2021-07-22T03:39:42 | 8c9e25490bba8e9899abeb2edbe1d5e738d5f814 | {
"blob_id": "8c9e25490bba8e9899abeb2edbe1d5e738d5f814",
"branch_name": "refs/heads/main",
"committer_date": "2021-07-22T03:39:42",
"content_id": "528e339a63a0a4523305361681781e38e12bf735",
"detected_licenses": [
"MIT"
],
"directory_id": "8d1274250366a9e9a854b70c3d3f149c299a0f58",
"extension": "c",
"filename": "11_funcao.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 351842105,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1273,
"license": "MIT",
"license_type": "permissive",
"path": "/Prog_estruturada/11_funcao.c",
"provenance": "stackv2-0072.json.gz:40675",
"repo_name": "Caioviniciusb/UFPB_prog_est",
"revision_date": "2021-07-22T03:39:42",
"revision_id": "3bf90df9b704dfd70efcb05f51fdb37716a90dd0",
"snapshot_id": "8f5250cba804808e672801086f0b8e42f1ba14b0",
"src_encoding": "ISO-8859-1",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Caioviniciusb/UFPB_prog_est/3bf90df9b704dfd70efcb05f51fdb37716a90dd0/Prog_estruturada/11_funcao.c",
"visit_date": "2023-06-27T18:04:34.640604"
} | stackv2 | /******************************************
*Programa diz qual é o número do dia do ano
*******************************************/
#include <stdio.h>
int dia_do_ano(int dia, int mes, int ano){
int cont = 0;
int bissexto(int ano){ //Função para checar se o ano é bissexto.
if (ano % 400 == 0){
return 1;}
else{
if (ano % 4 == 0 && ano % 100 != 0){
return 1;}
else{
return 0;}
}}
if (mes == 1){
cont == dia;}
switch (mes){ //Somando a quantidade de dias que já se passaram em cada mês.
case 2: cont+= 31; break;
case 3: cont+= 59; break;
case 4: cont+= 90; break;
case 5: cont+= 120; break;
case 6: cont+= 151; break;
case 7: cont+= 181; break;
case 8: cont+= 212; break;
case 9: cont+= 243; break;
case 10: cont+= 273; break;
case 11: cont+= 304; break;
case 12: cont+= 334; break;
}
cont += dia; //Somando os dias.
if (bissexto(ano) == 1){ //Checando se o ano é bissexto para somar + 1 dia.
cont++;}
return cont;
}
int main (void){
printf("%d\n", dia_do_ano(31,12,2020));
return 0;
}
| 3.8125 | 4 |
2024-11-18T22:11:06.574309+00:00 | 2014-02-04T02:01:44 | a81eea1f85bc00e7b58d2fd333863eda4ad6a3d1 | {
"blob_id": "a81eea1f85bc00e7b58d2fd333863eda4ad6a3d1",
"branch_name": "refs/heads/master",
"committer_date": "2014-02-04T02:01:44",
"content_id": "b71c91695cb949039ce789198fdc70792b09d6b9",
"detected_licenses": [
"MIT"
],
"directory_id": "409f45e8f2bc07e7ff3af87b0fdffaf7961d7e1a",
"extension": "c",
"filename": "serial.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 15348965,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2904,
"license": "MIT",
"license_type": "permissive",
"path": "/serial.c",
"provenance": "stackv2-0072.json.gz:41060",
"repo_name": "evmaus/laughing-tribble-os",
"revision_date": "2014-02-04T02:01:44",
"revision_id": "faefd5a591aed2c8fdb6438dca8a181a468541a9",
"snapshot_id": "27057ce631c7b032d78886d41c148f74e95f126e",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/evmaus/laughing-tribble-os/faefd5a591aed2c8fdb6438dca8a181a468541a9/serial.c",
"visit_date": "2020-04-06T04:31:51.052004"
} | stackv2 | /*
* Serial.c: wraps the UART driver; provides basic io along the serial line.
* This is mostly temporary/for use in debugging, but I think the UART should
* be wrapped up.
* Includes stuff for sending numbers as well as characters.
*/
#include <devices/uart.h>
#include <serial.h>
const uint8_t interactive=1;
uint8_t serial_initialized=0;
void serial_init(){
uart_init();
serial_initialized=1;
}
uint8_t serial_state(){
return serial_initialized;
}
char serial_getc(){
// if(!serial_initialized) serial_init();
return uart_getc();
}
// Reads up to (len-1) characters into str (or up to the terminating character).
void serial_gets(char * str, uint32_t len, char term){
int i;
char c=255;
if(!serial_initialized) serial_init(); //safety
// Read in buffer length-1 characters, or up to the terminator, or null.
for(i=0; (i<len-1 && c!=term && c); i++){
c = uart_getc();
uart_putc(c);
str[i]=c;
}
// Null terminate it.
str[i]=0;
}
// Converts character c from lower to upper case.
// No effect if c is not a lowercase letter.
char toUpcase(char c){
if((c > 96) && (c<123)){
return (c-32);
} else
return c;
}
//Minimum helper function.
uint8_t min(uint8_t a, uint8_t b){
if(a > b) return b;
return a;
}
// Takes in c as a number or upper case character, returns it as a base 10 int.
// returns 0 if c is not a valid character.
// A=10, B=11, etc.
uint32_t toDec(char c, uint8_t base){
if(c>47 && c<min(58, 48+base)) //numbers
return (c-48);
else if(c>64 && base > 10 && c < min(91, 65+(base-10))) //letters
return (c-55);
else
return 0;
}
uint32_t serial_getInt(uint8_t base){
char str[33]; // Lowest base taken is 2, and we're dealing with 32 bit integers.
char* ptr=str;
uint32_t ret=0;
if(base>36) return 0;
if(!serial_initialized) serial_init(); //safety
serial_gets(str, 33, '\r');
while(*ptr){
*ptr = toUpcase(*ptr);
if((*ptr > 47 && *ptr < 58) || (*ptr > 64 && *ptr < 91))
ret=toDec(*ptr, base)+ret*base;
ptr++;
}
return ret;
}
void serial_putc(const char c){
//if(!serial_initialized) serial_init();
uart_putc(c);
}
void serial_puts(const char* c){
//if(!serial_initialized) serial_init();
uart_puts(c);
uart_putc('\r');
uart_putc('\n');
}
char convIntToC(uint32_t i){
if(i > 16) return 0; //ERROR.
if(i < 10) return i+48;
if(i > 9) return i+55;
return 0;
}
void serial_putIntHex(const uint32_t i){
uint32_t temp=i;
uint8_t shift=0;
if(!serial_initialized) serial_init();
uart_putc('0');
uart_putc('x');
for(shift=0; shift<32; shift+=4){
uart_putc(convIntToC( (temp << shift & (1 << 31 | 1 << 30 | 1 << 29 | 1 << 28)) >> 28));
}
uart_putc('\r'); uart_putc('\n');
}
| 3.140625 | 3 |
2024-11-18T22:11:06.669336+00:00 | 2021-05-23T06:30:51 | ae93c876a0c9fc57bb3319e7e00f397d9bcc3889 | {
"blob_id": "ae93c876a0c9fc57bb3319e7e00f397d9bcc3889",
"branch_name": "refs/heads/main",
"committer_date": "2021-05-23T06:30:51",
"content_id": "e9e31a69b478557538aef295e5cc0f0dd72355be",
"detected_licenses": [
"MIT"
],
"directory_id": "4b5a60ec4b462271f26eff1231d7aed67a65b64f",
"extension": "c",
"filename": "DynMemGetBegin.c",
"fork_events_count": 0,
"gha_created_at": "2021-01-16T08:20:36",
"gha_event_created_at": "2021-05-02T11:34:58",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 330116693,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1816,
"license": "MIT",
"license_type": "permissive",
"path": "/Tests/dynmem/DynMemGetBegin.c",
"provenance": "stackv2-0072.json.gz:41188",
"repo_name": "KumarjitDas/Dynamic-Memory-Library",
"revision_date": "2021-05-23T06:30:51",
"revision_id": "fb8859b053cab7405bad849ecea9fbee2fd72cf3",
"snapshot_id": "81406ddce042552754c044359f8fc8709461b24f",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/KumarjitDas/Dynamic-Memory-Library/fb8859b053cab7405bad849ecea9fbee2fd72cf3/Tests/dynmem/DynMemGetBegin.c",
"visit_date": "2023-04-28T15:02:21.662056"
} | stackv2 | #include "check.h"
#include "dynmem/dynmem.h"
START_TEST(null_dynmem) {
int *pointer;
ck_assert_int_eq(DynMemGetBegin(NULL, NULL), DYNMEM_FAILED);
ck_assert_int_eq(DynMemGetBegin(NULL, &pointer), DYNMEM_FAILED);
ck_assert_ptr_null(pointer);
}
END_TEST
START_TEST(nonnull_dynmem) {
dynmem_t dynmem;
int *pointer;
ck_assert_int_eq(DynMemAllocate(&dynmem, 4, 5, NULL), DYNMEM_SUCCEED);
ck_assert_int_eq(DynMemGetBegin(&dynmem, NULL), DYNMEM_FAILED);
ck_assert_int_eq(DynMemGetBegin(&dynmem, &pointer), DYNMEM_FAILED);
ck_assert_ptr_null(pointer);
for (int i = 0; i < 5; i++)
ck_assert_int_eq(DynMemPrepend(&dynmem, &i), DYNMEM_SUCCEED);
ck_assert_int_eq(DynMemGetBegin(&dynmem, &pointer), DYNMEM_SUCCEED);
ck_assert_ptr_eq(pointer, dynmem.m);
for (int i = 0; i < 5; i++)
ck_assert_int_eq(DynMemPrepend(&dynmem, &i), DYNMEM_SUCCEED);
ck_assert_int_eq(DynMemGetBegin(&dynmem, &pointer), DYNMEM_SUCCEED);
ck_assert_ptr_eq(pointer, dynmem.m + 20);
for (int i = 0; i < 10; i++)
ck_assert_int_eq(DynMemPrepend(&dynmem, &i), DYNMEM_SUCCEED);
ck_assert_int_eq(DynMemGetBegin(&dynmem, &pointer), DYNMEM_SUCCEED);
ck_assert_ptr_eq(pointer, dynmem.m + 60);
ck_assert_int_eq(DynMemDeallocate(&dynmem), DYNMEM_SUCCEED);
}
END_TEST
int main() {
Suite *suite = suite_create("Test suite for \"DynMemGetBegin\" function");
TCase *test_cases = tcase_create("Test case");
tcase_add_test(test_cases, null_dynmem);
tcase_add_test(test_cases, nonnull_dynmem);
suite_add_tcase(suite, test_cases);
SRunner *suite_runner = srunner_create(suite);
srunner_run_all(suite_runner, CK_VERBOSE);
int failed_test_case_numbers = srunner_ntests_failed(suite_runner);
srunner_free(suite_runner);
return failed_test_case_numbers;
}
| 2.5625 | 3 |
2024-11-18T22:11:07.091382+00:00 | 2019-08-23T00:53:35 | 89982dbf020164c12bbcb9ee0f0a241dcb79c63d | {
"blob_id": "89982dbf020164c12bbcb9ee0f0a241dcb79c63d",
"branch_name": "refs/heads/master",
"committer_date": "2019-08-23T00:53:35",
"content_id": "c71a616e3ab0b4a22c324f713332376b233027b0",
"detected_licenses": [
"MIT"
],
"directory_id": "09884947c578015a250e41dd8b7c694685490b66",
"extension": "h",
"filename": "scanned-sequence.h",
"fork_events_count": 1,
"gha_created_at": "2018-12-05T01:46:43",
"gha_event_created_at": "2019-08-23T00:53:36",
"gha_language": "Python",
"gha_license_id": "MIT",
"github_id": 160443764,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1437,
"license": "MIT",
"license_type": "permissive",
"path": "/deps/kb_meme/meme-5.0.1/src/scanned-sequence.h",
"provenance": "stackv2-0072.json.gz:41316",
"repo_name": "kbasecollaborations/MotifFinderGibbs",
"revision_date": "2019-08-23T00:53:35",
"revision_id": "a428a71716b3c0040bd7825dcbea3fc7fbb6823b",
"snapshot_id": "51e85369656795ead6d41653aea13c0e3ad72cdb",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/kbasecollaborations/MotifFinderGibbs/a428a71716b3c0040bd7825dcbea3fc7fbb6823b/deps/kb_meme/meme-5.0.1/src/scanned-sequence.h",
"visit_date": "2020-04-09T16:06:02.547790"
} | stackv2 |
#ifndef SCANNED_SEQUENCE_H
#define SCANNED_SEQUENCE_H
typedef struct scanned_site SCANNED_SITE_T;
struct scanned_site {
int m_num;
char strand;
long position;
double pvalue;
};
typedef struct scanned_seq SCANNED_SEQ_T;
struct scanned_seq {
char *seq_id;
long length;
double pvalue;
long site_count;
SCANNED_SITE_T *sites;
};
/*
* Create a scanned sequence structure.
* The seq_id is copied.
*/
SCANNED_SEQ_T* sseq_create(const char *seq_id, long length, double pvalue,
long site_count);
/*
* Create a scanned sequence structure.
* The seq_id is used (not copied). The length is initially set to
* zero as are the number of allocated sites. This is intended
* to be used with the sseq_add_site and sseq_add_spacer methods
* to build up the correct length and sites
*/
SCANNED_SEQ_T* sseq_create2(char *seq_id, double pvalue);
/*
* Destroy the scanned sequence structure and all included scanned
* site structures.
*/
void sseq_destroy(void *sseq);
/*
* Set the scanned site at a offset.
*/
void sseq_set(SCANNED_SEQ_T *sseq, int index, int m_num,
char strand, long position, double pvalue);
/*
* Add a scanned site. Intended to be used with sseq_create2
*/
void sseq_add_site(SCANNED_SEQ_T *sseq, int motif_num, int motif_len, char strand, double pvalue);
/*
* Add a spacer. Intended to be used with sseq_create2
*/
void sseq_add_spacer(SCANNED_SEQ_T *sseq, int spacer_len);
#endif
| 2.46875 | 2 |
2024-11-18T22:11:08.548122+00:00 | 2020-04-13T16:32:35 | 1e3c6e3593c908239f01d582f037307fdeabf452 | {
"blob_id": "1e3c6e3593c908239f01d582f037307fdeabf452",
"branch_name": "refs/heads/master",
"committer_date": "2020-04-13T16:32:35",
"content_id": "82bb88d183a81379df8e577af0d4b2bd62932f66",
"detected_licenses": [
"MIT"
],
"directory_id": "44972cfc17c63c6fba9e78427b80cb6e45e13685",
"extension": "c",
"filename": "base64.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 122915642,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2441,
"license": "MIT",
"license_type": "permissive",
"path": "/base64.c",
"provenance": "stackv2-0072.json.gz:41704",
"repo_name": "pillash/base64",
"revision_date": "2020-04-13T16:32:35",
"revision_id": "86eac8c6d4e993c9847b4440a4462bc6f35afb55",
"snapshot_id": "0c4697926f51e4fdb7d8de08cc64f8b984cfb746",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/pillash/base64/86eac8c6d4e993c9847b4440a4462bc6f35afb55/base64.c",
"visit_date": "2021-01-24T03:58:22.977342"
} | stackv2 | #include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include "base64.h"
int parseArguments(int argc, char **argv, char **mode, char **filename);
uint8_t *readFileBinary(char *filename, unsigned long *size);
int main(int argc, char ** argv) {
char *mode;
char *filename;
if (parseArguments(argc, argv, &mode, &filename) == 0) {
printf("Format: base64 [-e|-d] filename\n");
return 0;
}
if (strcmp(mode, "-e") == 0) {
unsigned long size;
uint8_t *input = readFileBinary(filename, &size);
unsigned long eSize;
char *output = base64encode(input, size, &eSize);
printf("%s", output);
free(input);
return 0;
} else if (strcmp(mode, "-d") == 0) {
unsigned long size;
char *input = (char *)readFileBinary(filename, &size);
unsigned long ds;
uint8_t *output = base64decode(input, size, &ds);
if (output == NULL) {
printf("Error decoding\n");
return 1;
}
for (unsigned int i = 0; i < ds; i++) {
printf("%c", (char)output[i]);
}
free(input);
return 0;
} else {
printf("Format: base64 [-e|-d] filename\n");
return 1;
}
}
uint8_t *readFileBinary(char *filename, unsigned long *size) {
FILE *filePtr;
long fileSize;
filePtr = fopen(filename, "rb");
if (filePtr == NULL) {
return NULL;
}
fseek(filePtr, 0, SEEK_END);
fileSize = ftell(filePtr);
if (fileSize == -1) {
return NULL;
}
rewind(filePtr);
uint8_t *fileBuf = malloc((unsigned long)fileSize);
if (fileBuf == NULL) {
return NULL;
}
if (fread(fileBuf, 1, (unsigned long)fileSize, filePtr) != (unsigned long)fileSize) {
printf("Didn't read expected number of bytes\n");
return NULL;
}
fclose(filePtr);
*size = (unsigned long)fileSize;
return fileBuf;
}
int parseArguments(int argc, char **argv, char **mode, char **filename) {
if (argc != 3) {
return 0;
}
char *arg1 = argv[1];
char *arg2 = argv[2];
if (strcmp(arg1, "-e") == 0 || strcmp(arg1, "-d") == 0) {
*mode = arg1;
*filename = arg2;
return 1;
}
if (strcmp(arg2, "-e") == 0 || strcmp(arg2, "-d") == 0) {
*mode = arg2;
*filename = arg1;
return 1;
}
return 0;
}
| 2.890625 | 3 |
2024-11-18T22:11:12.765553+00:00 | 2021-11-15T16:12:02 | 5ffa6bda5e4ad5d28e85aa669ee76ee0ecf39282 | {
"blob_id": "5ffa6bda5e4ad5d28e85aa669ee76ee0ecf39282",
"branch_name": "refs/heads/main",
"committer_date": "2021-11-15T16:12:02",
"content_id": "77f60dcb5b1b148f6f4f7cdc2e2874aad79b59c6",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "3b44eed9f892c0d72444d8532a3b873af8eb2450",
"extension": "c",
"filename": "util.c",
"fork_events_count": 2,
"gha_created_at": "2021-07-06T12:11:08",
"gha_event_created_at": "2021-11-18T02:42:33",
"gha_language": "C",
"gha_license_id": "Apache-2.0",
"github_id": 383456175,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1896,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/libzazen/util.c",
"provenance": "stackv2-0072.json.gz:42605",
"repo_name": "gray-armor/z11",
"revision_date": "2021-11-15T16:12:02",
"revision_id": "4ad94513a61413428210972e0f09fa87242c1152",
"snapshot_id": "4d4cf08a7d338c48e3c23632ab76e5d7114b4f93",
"src_encoding": "UTF-8",
"star_events_count": 11,
"url": "https://raw.githubusercontent.com/gray-armor/z11/4ad94513a61413428210972e0f09fa87242c1152/libzazen/util.c",
"visit_date": "2023-09-06T07:21:26.857127"
} | stackv2 | #define _GNU_SOURCE 1
#include "util.h"
#include <stdio.h>
#include <string.h>
#include <sys/mman.h>
#include <unistd.h>
#include <wayland-server.h>
int create_shared_file(off_t size, void* content)
{
const char* name = "zazen-shared";
int fd;
void* data;
fd = memfd_create(name, MFD_CLOEXEC | MFD_ALLOW_SEALING);
if (fd < 0) return fd;
unlink(name);
if (ftruncate(fd, size) < 0) {
close(fd);
return -1;
}
data = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if (data == MAP_FAILED) {
close(fd);
return -1;
}
memcpy(data, content, size);
munmap(data, size);
return fd;
}
static void zazen_weak_pointer_handle_destroy_signal_handler(
struct wl_listener* listener, void* data)
{
UNUSED(data);
struct zazen_weak_ref* ref;
ref = wl_container_of(listener, ref, destroy_listener);
if (ref->destroy_func) ref->destroy_func(ref->data);
wl_list_remove(&ref->destroy_listener.link);
wl_list_init(&ref->destroy_listener.link);
ref->data = NULL;
ref->destroy_func = NULL;
}
void zazen_weak_ref_init(struct zazen_weak_ref* ref)
{
wl_list_init(&ref->destroy_listener.link);
ref->destroy_listener.notify =
zazen_weak_pointer_handle_destroy_signal_handler;
ref->data = NULL;
ref->destroy_func = NULL;
}
void zazen_weak_ref_destroy(struct zazen_weak_ref* ref)
{
wl_list_remove(&ref->destroy_listener.link);
}
void zazen_weak_ref_set_data(struct zazen_weak_ref* ref, void* data,
struct wl_signal* destroy_signal,
zazen_weak_ref_destroy_func_t on_destroy)
{
wl_list_remove(&ref->destroy_listener.link);
wl_signal_add(destroy_signal, &ref->destroy_listener);
ref->data = data;
ref->destroy_func = on_destroy;
}
void zazen_log(const char* fmt, ...)
{
va_list argp;
va_start(argp, fmt);
vfprintf(stderr, fmt, argp);
va_end(argp);
}
| 2.40625 | 2 |
2024-11-18T22:11:12.836359+00:00 | 2023-08-31T14:51:12 | d83c315a3c69ff8e457298a1453c00525a32ff43 | {
"blob_id": "d83c315a3c69ff8e457298a1453c00525a32ff43",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-31T14:51:12",
"content_id": "b46ae896668a9af9fe610659e10d12beec9b630e",
"detected_licenses": [],
"directory_id": "9de0cec678bc4a3bec2b4adabef9f39ff5b4afac",
"extension": "c",
"filename": "MakeFlowTrain.C",
"fork_events_count": 1150,
"gha_created_at": "2016-06-21T19:31:29",
"gha_event_created_at": "2023-09-14T18:48:45",
"gha_language": "C++",
"gha_license_id": "BSD-3-Clause",
"github_id": 61661378,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 8235,
"license": "",
"license_type": "permissive",
"path": "/PWGLF/FORWARD/analysis2/trains/MakeFlowTrain.C",
"provenance": "stackv2-0072.json.gz:42733",
"repo_name": "alisw/AliPhysics",
"revision_date": "2023-08-31T14:51:12",
"revision_id": "5df28b2b415e78e81273b0d9bf5c1b99feda3348",
"snapshot_id": "91bf1bd01ab2af656a25ff10b25e618a63667d3e",
"src_encoding": "UTF-8",
"star_events_count": 129,
"url": "https://raw.githubusercontent.com/alisw/AliPhysics/5df28b2b415e78e81273b0d9bf5c1b99feda3348/PWGLF/FORWARD/analysis2/trains/MakeFlowTrain.C",
"visit_date": "2023-08-31T20:41:44.927176"
} | stackv2 | /**
* @file MakeFlowTrain.C
* @author Alexander Hansen
*
* @brief
*
* @ingroup pwglf_forward_trains
*
*/
#include "TrainSetup.C"
//====================================================================
/**
* Analysis train to make flow
*
*
* @ingroup pwglf_forward_flow
*/
class MakeFlowTrain : public TrainSetup
{
public:
/**
* Constructor.
*
* @param name Name of train (free form)
*/
MakeFlowTrain(const char* name)
: TrainSetup(name)
{
// General options
fOptions.Add("sys", "SYSTEM", "1:pp, 2:PbPb, 3:pPb", "");
fOptions.Add("mc", "Do MC analysis");
fOptions.Add("max-mom", "2|3|4|5", "Max flow moment to analyse", "5");
fOptions.Add("use-cent", "Whether to use the impact parameter "
"for centrality");
fOptions.Add("mc-vtx", "Whether to get the vertex from the MC header");
fOptions.Add("fwd-dets", "[fmd,vzero]", "Forward detectors", "fmd+vzero");
fOptions.Add("afterburner", "Whether to afterburn");
fOptions.Set("type", "AOD");
fOptions.Show(std::cout);
// QC specific options
fOptions.Add("QC", "Add QC tasks (requires AODs with FMD and SPD objects)");
fOptions.Add("qc-type", "[std,eta-gap,3cor,all]",
"Which types of QC's to do", "all");
fOptions.Add("eg-value", "EGVALUE",
"Set value in |eta| of the eta gap", "2.0");
fOptions.Add("tracks", "[tpc,hybrid,only]",
"Whether or only to use tracks for reference flow",
"tpc+hybrid");
fOptions.Add("sat-vtx", "Whether to use satellite interactions");
fOptions.Add("outlier-fmd", "NSIGMA", "Outlier cut for FMD", "4.0");
fOptions.Add("outlier-spd", "NSIGMA", "Outlier cut for SPD", "4.0");
// EP specific options
fOptions.Add("EP", "Add EP tasks (requires VZERO AOD objects)");
}
protected:
//__________________________________________________________________
/**
* Create the tasks
*
*/
void CreateTasks(AliAnalysisManager*)
{
// --- Output file name ------------------------------------------
AliAnalysisManager::SetCommonFileName("forward_flow.root");
// --- Load libraries/pars ---------------------------------------
fRailway->LoadLibrary("PWGLFforward2");
// --- Set load path ---------------------------------------------
gROOT->SetMacroPath(Form("%s:$(ALICE_PHYSICS)/PWGLF/FORWARD/analysis2",
gROOT->GetMacroPath()));
gROOT->SetMacroPath(Form("%s:$(ALICE_ROOT)/ANALYSIS/macros",
gROOT->GetMacroPath()));
// --- Add the tasks ---------------------------------------------
Bool_t doQC = fOptions.AsBool("QC");
Bool_t doEP = fOptions.AsBool("EP");
if (doQC) AddQCTasks();
if (doEP) AddEPTasks();
if (!doQC && !doEP) Fatal("CreateTasks", "No flow tasks were added");
}
//__________________________________________________________________
/**
* Add the QC task(s)
*/
void AddQCTasks()
{
// --- Get the parameters ----------------------------------------
UShort_t sys = fOptions.AsInt("sys", 0);
Int_t moment = fOptions.AsInt("max-mom");
TString fwdDets = fOptions.Get("fwd-dets");
TString types = fOptions.Get("qc-type");
Double_t egValue = fOptions.AsDouble("eg-value");
TString tracks = fOptions.Get("tracks");
Bool_t useCent = fOptions.AsBool("use-cent");
Bool_t useMCVtx = fOptions.AsBool("mc-vtx");
Bool_t addFlow = fOptions.AsBool("afterburner");
Bool_t satVtx = fOptions.AsBool("sat-vtx");
Double_t fmdCut = fOptions.AsDouble("outlier-fmd");
Double_t spdCut = fOptions.AsDouble("outlier-spd");
Bool_t mc = fOptions.AsBool("mc");
types.ToLower();
fwdDets.ToUpper();
Bool_t doFMD = fwdDets.Contains("FMD");
Bool_t doVZERO = fwdDets.Contains("VZERO");
tracks.ToLower();
Bool_t onlyTr = tracks.Contains("only");
Bool_t tpcTr = tracks.Contains("tpc");
Bool_t hybridTr = tracks.Contains("hybrid");
Bool_t ispA = (sys == 3 ? kTRUE : kFALSE);
// Notice the place holders at arg=2,3,4, and 9, These are
//
// 2: Detector to use (FMD/VZERO)
// 3: Whether to use eta gap (true/false)
// 4: Do 3-subevent correlations (true/false)
// 9: Use tracks for referernce flow (true/false)
TString args;
args = TString::Format("%d,\"%%s\",%%d,%%d,%d,%f,%f,%f,%%d,%d,%d,%d,%d,%d",
moment,
mc,
fmdCut,
spdCut,
egValue,
useCent,
ispA,
useMCVtx,
satVtx,
addFlow);
// --- Add the task ----------------------------------------------
const char* mac = "AddTaskForwardFlowQC.C";
if (doFMD) {
if (types.Contains("std") || types.Contains("all")) {
if (!onlyTr)
CoupleCar(mac, Form(args.Data(), "FMD", false, false, 0));
if (tpcTr)
CoupleCar(mac, Form(args.Data(), "FMD", false, false, 1));
if (hybridTr)
CoupleCar(mac, Form(args.Data(), "FMD", false, false, 2));
}
if (types.Contains("eta-gap") || types.Contains("all")) {
if (!onlyTr)
CoupleCar(mac, Form(args.Data(), "FMD", true, false, 0));
if (tpcTr)
CoupleCar(mac, Form(args.Data(), "FMD", true, false, 1));
if (hybridTr)
CoupleCar(mac, Form(args.Data(), "FMD", true, false, 2));
}
if (types.Contains("3cor") || types.Contains("all")) {
if (!onlyTr)
CoupleCar(mac, Form(args.Data(), "FMD", false, true, 0));
}
}
if (doVZERO) {
if (types.Contains("std") || types.Contains("all")) {
if (!onlyTr)
CoupleCar(mac, Form(args.Data(), "VZERO", false, false, 0));
if (tpcTr)
CoupleCar(mac, Form(args.Data(), "VZERO", false, false, 1));
if (hybridTr)
CoupleCar(mac, Form(args.Data(), "VZERO", false, false, 2));
}
if (types.Contains("eta-gap") || types.Contains("all")) {
if (!onlyTr)
CoupleCar(mac, Form(args.Data(), "VZERO", true, false, 0));
if (tpcTr)
CoupleCar(mac, Form(args.Data(), "VZERO", true, false, 1));
if (hybridTr)
CoupleCar(mac, Form(args.Data(), "VZERO", true, false, 2));
}
if (types.Contains("3cor") || types.Contains("all")) {
if (!onlyTr)
CoupleCar(mac, Form(args.Data(), "VZERO", false, true, 0));
}
}
}
//__________________________________________________________________
/**
* Add the EP task(s)
*/
void AddEPTasks()
{
// --- Get the parameters ----------------------------------------
Int_t moment = fOptions.AsInt("max-mom");
TString etaGap = fOptions.Get("eta-gap");
TString addFlow = fOptions.Get("afterburner");
Bool_t mc = fOptions.AsBool("mc");
TString fwdDets = fOptions.Get("fwd-dets");
// --- Add the task ----------------------------------------------
CoupleCar("AddTaskEventplane.C","");
CoupleCar("AddTaskForwardFlowEP.C",
Form("%d, %d, \"%s\"", mc, moment, fwdDets.Data()));
}
//__________________________________________________________________
/**
* Do not the centrality selection
*/
void CreateCentralitySelection(Bool_t) {}
//__________________________________________________________________
/**
* Crete output handler - we don't want one here.
*
* @return 0
*/
AliVEventHandler* CreateOutputHandler(UShort_t) { return 0; }
//__________________________________________________________________
/**
* Create MC input handler. Since this train does not use the MC
* information from @c galice.root, @c Kinematics.root, and @c
* TrackRefs.root directly, we define this member function to return
* null even when doing MC analysis. This train _only_ looks at the
* AOD object of the _processed_ MC data.
*
* @return Always 0
*/
AliVEventHandler* CreateMCHandler(UShort_t, bool)
{
return 0;
}
//__________________________________________________________________
/**
* Get the class name of the train setup
*
* @return Class name
*/
const char* ClassName() const { return "MakeFlowTrain"; }
//__________________________________________________________________
};
//
// EOF
//
| 2 | 2 |
2024-11-18T22:11:12.952750+00:00 | 2021-04-09T09:37:16 | 3bdc4f274cb942633a6d6799a3c8d81e265a2ebd | {
"blob_id": "3bdc4f274cb942633a6d6799a3c8d81e265a2ebd",
"branch_name": "refs/heads/master",
"committer_date": "2021-04-09T09:37:16",
"content_id": "ffcf88497daeb464e0956e8aef0b452619940a66",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "d2dd8e3497e1852b15ac449af47d44fe3c0abda9",
"extension": "c",
"filename": "opc_n3.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": 9720,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/Firmware/src/opc_n3.c",
"provenance": "stackv2-0072.json.gz:42862",
"repo_name": "MuhammedEALAN/air-quality-sensor-node",
"revision_date": "2021-04-09T09:37:16",
"revision_id": "f92ee099e032b53a54bdad65ca93fc537f00a4a6",
"snapshot_id": "7e81597c4e434328977ddd41666bc3cd382f9e3b",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/MuhammedEALAN/air-quality-sensor-node/f92ee099e032b53a54bdad65ca93fc537f00a4a6/Firmware/src/opc_n3.c",
"visit_date": "2023-04-09T08:12:15.856184"
} | stackv2 | /*
** Copyright 2020 Telenor Digital AS
**
** 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 <zephyr.h>
#include "opc_n3.h"
#include "gpio.h"
#include "pinout.h"
#include <spi.h>
#include "spi_config.h"
#include <math.h>
#define LOG_LEVEL CONFIG_OPCN3_LOG_LEVEL
#include <logging/log.h>
LOG_MODULE_REGISTER(OPC_N3);
// Note:
// 1) The first histogram must be discarded, since it doesn't contain PM-data (although it has temperature,
// humidity data and a correct checksum).
// 2) Option 0x05 is frequently set in examples on github, but this seems to prevent sampling without resetting the OPC.
// The documentation mentions that the Autogain toggle will cease until the next reset, but it is rather vague
// regarding the effects of the gain settings and autogain.
struct spi_config OPC_config;
//struct spi_cs_control OPC_control;
struct spi_buf OPC_buf_tx;
struct spi_buf_set OPC_buf_set_tx;
struct spi_buf OPC_buf_rx;
struct spi_buf_set OPC_buf_set_rx;
struct device *OPC_spi_dev;
u8_t OPC_spi_tx_buffer[SPI_BUF_SIZE];
u8_t OPC_spi_rx_buffer[SPI_BUF_SIZE];
u8_t histogram[OPC_HISTOGRAM_SIZE];
#define INFORMATION_STRING_LENGTH 60
void OPC_selectDeviceCSLow(void)
{
digitalWrite(CS_OPC, LOW);
}
void OPC_releaseChipSelect(void)
{
digitalWrite(CS_OPC, HIGH);
}
void opc_init()
{
// LOG_INF("OPC_N3 - Init.");
OPC_spi_dev = get_SPI_device();
OPC_config.cs = NULL;
OPC_config.frequency = 500000;
OPC_config.operation = SPI_OP_MODE_MASTER | SPI_WORD_SET(8) | SPI_TRANSFER_MSB | SPI_MODE_CPHA;
OPC_config.slave = 0;
// LOG_INF("OPC_config cs: %d", (int)OPC_config.cs);
// LOG_INF("OPC_config frequency: %d", (int)OPC_config.frequency);
// LOG_INF("OPC_config operation: %d", (int)OPC_config.operation);
// LOG_INF("OPC_config slave: %d", (int)OPC_config.slave);
}
OPC_N3_RESULT OPC_command(uint8_t command_byte, uint8_t option_byte, uint8_t *buffer, int rxBytes)
{
OPC_spi_tx_buffer[0] = command_byte;
OPC_spi_rx_buffer[0] = 0x00;
OPC_buf_tx.buf = &OPC_spi_tx_buffer;
OPC_buf_tx.len = 1;
OPC_buf_set_tx.buffers = &OPC_buf_tx;
OPC_buf_set_tx.count = 1;
OPC_buf_rx.buf = &OPC_spi_rx_buffer;
OPC_buf_rx.len = 1;
OPC_buf_set_rx.buffers = &OPC_buf_rx;
OPC_buf_set_rx.count = 1;
int err;
int bufferIndex = 0;
OPC_selectDeviceCSLow();
err = spi_transceive(OPC_spi_dev, &OPC_config, &OPC_buf_set_tx, &OPC_buf_set_rx);
if (err)
{
LOG_ERR("OPC read information string failed (1) with error: %d ", err);
}
if (OPC_spi_rx_buffer[0] != OPC_BUSY)
{
LOG_ERR("Unexpected response byte 1 (%02X)from OPC-N3 when sending command : %02X", OPC_spi_rx_buffer[0], command_byte);
}
k_sleep(10); // TODO: Make constant
int retryCount = 0;
while (true)
{
int err = spi_transceive(OPC_spi_dev, &OPC_config, &OPC_buf_set_tx, &OPC_buf_set_rx);
if (err)
{
LOG_ERR("OPC_command failed (2) with error: %d, Retry count: %d", err, retryCount);
}
if (OPC_spi_rx_buffer[0] == OPC_N3_DATA_READY)
{
break;
}
if (retryCount++ > 20)
{
OPC_releaseChipSelect();
LOG_ERR("Giving up. Too many retries...");
return OPC_UNEXPECTED_OPC_RESPONSE;
}
k_sleep(OPC_N3_SPI_BUFFER_RESET_WAIT);
}
k_usleep(10); // TODO: Make constant
if (option_byte != OPC_OPTION_NONE)
{
OPC_spi_tx_buffer[0] = option_byte;
OPC_spi_rx_buffer[0] = 0x00;
err = spi_transceive(OPC_spi_dev, &OPC_config, &OPC_buf_set_tx, &OPC_buf_set_rx);
if (err)
{
LOG_ERR("OPC read information string failed (1) with error: %d ", err);
}
if (OPC_spi_rx_buffer[0] != 0x03)
{
LOG_ERR("OPC unexpected response (%d) to option byte: %d ", OPC_spi_rx_buffer[0], option_byte);
}
}
if (rxBytes != 0)
{
memset(OPC_spi_tx_buffer, command_byte, SPI_BUF_SIZE);
memset(OPC_spi_rx_buffer, 0x00, SPI_BUF_SIZE);
for (int i = 0; i < rxBytes; i++)
{
err = spi_transceive(OPC_spi_dev, &OPC_config, &OPC_buf_set_tx, &OPC_buf_set_rx);
if (err)
{
LOG_ERR("spi_transceive failed with error: %d", err);
}
if ((NULL != buffer) & (bufferIndex < SPI_BUF_SIZE))
{
buffer[bufferIndex] = OPC_spi_rx_buffer[0];
bufferIndex++;
}
}
}
k_sleep(10); // TODO: Make constant
OPC_releaseChipSelect();
return OPC_OK;
}
uint16_t get_uint16_value(uint8_t *buffer)
{
union histogram_t {
uint8_t b[2];
uint16_t value;
} h;
h.b[0] = *(uint8_t *)buffer;
h.b[1] = *(uint8_t *)(buffer + 1);
return h.value;
}
float get_float_value(uint8_t *buffer)
{
union histogram_t {
uint8_t b[4];
float value;
} h;
h.b[0] = *(uint8_t *)buffer;
h.b[1] = *(uint8_t *)(buffer + 1);
h.b[2] = *(uint8_t *)(buffer + 2);
h.b[3] = *(uint8_t *)(buffer + 3);
return h.value;
}
uint16_t OPC_calcCRC(uint8_t data[], uint8_t number_of_bytes)
{
#define PLYNOMIAL 0xA001
#define InitCRCval 0xFFFF
uint8_t bit;
uint16_t crc = InitCRCval;
uint8_t byteCounter;
for (byteCounter = 0; byteCounter < number_of_bytes; byteCounter++)
{
crc ^= (uint16_t)data[byteCounter];
for (bit = 0; bit < 8; bit++)
{
if (crc & 0b00000001)
{
crc >>= 1;
crc ^= PLYNOMIAL;
}
else
{
crc >>= 1;
}
}
}
return crc;
}
void Read_DAC_and_power_status()
{
LOG_INF("Reading DAC and power status");
uint8_t status[6];
OPC_command(OPC_N3_READ_DAC_AND_POWER_STATUS, OPC_OPTION_NONE, &status[0], 6);
LOG_INF("---------- STATUS -------");
LOG_INF("FAN_ON: %d", status[0]);
LOG_INF("LASER_DAC_ON: %d", status[1]);
LOG_INF("FAN_DAC_ON: %d", status[2]);
LOG_INF("LASER_DAC_VAL: %d", status[3]);
LOG_INF("LASER_SWITCH: %d", status[4]);
LOG_INF("Gain toggle: %d", status[5]);
LOG_INF("---------- STATUS -------");
}
void peripeherals_power_on()
{
// LOG_INF("Switching fan - ON");
OPC_command(OPC_N3_WRITE_PERIPHERAL_POWER_STATUS, OPC_OPTION_FAN_ON, NULL, 0);
k_sleep(FAN_SETTLING_TIME_MS);
// LOG_INF("Switching laser - ON");
OPC_command(OPC_N3_WRITE_PERIPHERAL_POWER_STATUS, OPC_OPTION_LASER_ON, NULL, 0);
k_sleep(LASER_SETTLING_TIME_MS);
}
void peripherals_power_off()
{
// LOG_INF("Switching laser - OFF");
OPC_command(OPC_N3_WRITE_PERIPHERAL_POWER_STATUS, OPC_OPTION_LASER_OFF, NULL, 0);
k_sleep(LASER_SETTLING_TIME_MS);
// LOG_INF("Switching fan - OFF");
OPC_command(OPC_N3_WRITE_PERIPHERAL_POWER_STATUS, OPC_OPTION_FAN_OFF, NULL, 0);
k_sleep(FAN_SETTLING_TIME_MS);
}
static bool opc_sample()
{
LOG_DBG("Sampling OPC N3");
peripeherals_power_on();
k_sleep(OPC_SAMPLING_TIME_MS);
memset(histogram, 0, OPC_HISTOGRAM_SIZE);
OPC_command(OPC_N3_READ_HISTOGRAM_DATA_AND_RESET_HISTOGRAM, OPC_OPTION_NONE, &histogram[0], OPC_HISTOGRAM_SIZE);
// NOTE: For some arcane reason, it seems that it is necessary with a delay _after_ we have read the histogram,
// but _before_ we switch off the peripherals.
k_sleep(OPC_SAMPLING_TIME_MS);
peripherals_power_off();
// Sanity check
uint16_t checksum = get_uint16_value(&histogram[OPC_HISTOGRAM_CHECKSUM_INDEX]);
if (checksum != OPC_calcCRC(histogram, OPC_HISTOGRAM_SIZE - 2))
{
LOG_ERR("CRC Checksum error in histogram! (%04X)", checksum);
LOG_INF("CRC byte 1 : %02X", histogram[OPC_HISTOGRAM_CHECKSUM_INDEX]);
LOG_INF("CRC byte 2 : %02X", histogram[OPC_HISTOGRAM_CHECKSUM_INDEX + 1]);
return false;
}
return true;
}
static OPC_SAMPLE current;
void decode_historgram(bool valid)
{
for (int i = 0; i < OPC_BINS; i++)
{
current.bin[i] = get_uint16_value(&histogram[i * 2]);
}
current.period = get_uint16_value(&histogram[OPC_SAMPLING_PERIOD_INDEX]);
current.flowrate = get_uint16_value(&histogram[OPC_SAMPLE_FLOWRATE_INDEX]);
uint16_t raw_sample_temp = get_uint16_value(&histogram[OPC_TEMPERATURE_INDEX]);
current.temperature = -45 + 175 * raw_sample_temp / 65535;
uint16_t raw_sample_humidity = get_uint16_value(&histogram[OPC_HUMIDITY_INDEX]);
current.humidity = 100 * raw_sample_humidity / 65535;
current.pm_a = get_float_value(&histogram[OPC_PM_A_INDEX]);
current.pm_b = get_float_value(&histogram[OPC_PM_B_INDEX]);
current.pm_c = get_float_value(&histogram[OPC_PM_C_INDEX]);
current.fan_rev_count = get_uint16_value(&histogram[OPC_FAN_REV_COUNT_INDEX]);
current.laser_status = get_uint16_value(&histogram[OPC_LASER_STATUS_INDEX]);
current.valid = valid;
}
void opc_n3_sample_data()
{
decode_historgram(OPC_OK == opc_sample());
}
void opc_n3_get_sample(OPC_SAMPLE *msg)
{
memcpy(msg, ¤t, sizeof(current));
}
| 2.109375 | 2 |
2024-11-18T22:11:16.021547+00:00 | 2023-06-08T15:43:05 | f3d5bf6cbf098593c2bebfafb112687899232fac | {
"blob_id": "f3d5bf6cbf098593c2bebfafb112687899232fac",
"branch_name": "refs/heads/master",
"committer_date": "2023-06-08T15:43:05",
"content_id": "868dc5deb7b041ee6b8c85902edc000f287fe432",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "1deb5a41ceff80755587fea8b4eae455dcd54ecd",
"extension": "c",
"filename": "ngx_crypt.c",
"fork_events_count": 25,
"gha_created_at": "2019-12-20T08:21:50",
"gha_event_created_at": "2020-05-30T18:48:17",
"gha_language": "C",
"gha_license_id": "BSD-2-Clause",
"github_id": 229221885,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 6777,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/src/core/ngx_crypt.c",
"provenance": "stackv2-0072.json.gz:43377",
"repo_name": "jntass/Nginx_Tassl",
"revision_date": "2023-06-08T15:43:05",
"revision_id": "5faec722cc4411ee2a83eec9bb74fa854acf14d1",
"snapshot_id": "46ca8fed80ca8bc469da775f05a4325ff7f5eff0",
"src_encoding": "UTF-8",
"star_events_count": 56,
"url": "https://raw.githubusercontent.com/jntass/Nginx_Tassl/5faec722cc4411ee2a83eec9bb74fa854acf14d1/src/core/ngx_crypt.c",
"visit_date": "2023-08-21T19:46:44.602491"
} | stackv2 |
/*
* Copyright (C) Maxim Dounin
*/
#include <ngx_config.h>
#include <ngx_core.h>
#include <ngx_crypt.h>
#include <ngx_md5.h>
#include <ngx_sha1.h>
#if (NGX_CRYPT)
static ngx_int_t ngx_crypt_apr1(ngx_pool_t *pool, u_char *key, u_char *salt,
u_char **encrypted);
static ngx_int_t ngx_crypt_plain(ngx_pool_t *pool, u_char *key, u_char *salt,
u_char **encrypted);
static ngx_int_t ngx_crypt_ssha(ngx_pool_t *pool, u_char *key, u_char *salt,
u_char **encrypted);
static ngx_int_t ngx_crypt_sha(ngx_pool_t *pool, u_char *key, u_char *salt,
u_char **encrypted);
static u_char *ngx_crypt_to64(u_char *p, uint32_t v, size_t n);
ngx_int_t
ngx_crypt(ngx_pool_t *pool, u_char *key, u_char *salt, u_char **encrypted)
{
if (ngx_strncmp(salt, "$apr1$", sizeof("$apr1$") - 1) == 0) {
return ngx_crypt_apr1(pool, key, salt, encrypted);
} else if (ngx_strncmp(salt, "{PLAIN}", sizeof("{PLAIN}") - 1) == 0) {
return ngx_crypt_plain(pool, key, salt, encrypted);
} else if (ngx_strncmp(salt, "{SSHA}", sizeof("{SSHA}") - 1) == 0) {
return ngx_crypt_ssha(pool, key, salt, encrypted);
} else if (ngx_strncmp(salt, "{SHA}", sizeof("{SHA}") - 1) == 0) {
return ngx_crypt_sha(pool, key, salt, encrypted);
}
/* fallback to libc crypt() */
return ngx_libc_crypt(pool, key, salt, encrypted);
}
static ngx_int_t
ngx_crypt_apr1(ngx_pool_t *pool, u_char *key, u_char *salt, u_char **encrypted)
{
ngx_int_t n;
ngx_uint_t i;
u_char *p, *last, final[16];
size_t saltlen, keylen;
ngx_md5_t md5, ctx1;
/* Apache's apr1 crypt is Poul-Henning Kamp's md5 crypt with $apr1$ magic */
keylen = ngx_strlen(key);
/* true salt: no magic, max 8 chars, stop at first $ */
salt += sizeof("$apr1$") - 1;
last = salt + 8;
for (p = salt; *p && *p != '$' && p < last; p++) { /* void */ }
saltlen = p - salt;
/* hash key and salt */
ngx_md5_init(&md5);
ngx_md5_update(&md5, key, keylen);
ngx_md5_update(&md5, (u_char *) "$apr1$", sizeof("$apr1$") - 1);
ngx_md5_update(&md5, salt, saltlen);
ngx_md5_init(&ctx1);
ngx_md5_update(&ctx1, key, keylen);
ngx_md5_update(&ctx1, salt, saltlen);
ngx_md5_update(&ctx1, key, keylen);
ngx_md5_final(final, &ctx1);
for (n = keylen; n > 0; n -= 16) {
ngx_md5_update(&md5, final, n > 16 ? 16 : n);
}
ngx_memzero(final, sizeof(final));
for (i = keylen; i; i >>= 1) {
if (i & 1) {
ngx_md5_update(&md5, final, 1);
} else {
ngx_md5_update(&md5, key, 1);
}
}
ngx_md5_final(final, &md5);
for (i = 0; i < 1000; i++) {
ngx_md5_init(&ctx1);
if (i & 1) {
ngx_md5_update(&ctx1, key, keylen);
} else {
ngx_md5_update(&ctx1, final, 16);
}
if (i % 3) {
ngx_md5_update(&ctx1, salt, saltlen);
}
if (i % 7) {
ngx_md5_update(&ctx1, key, keylen);
}
if (i & 1) {
ngx_md5_update(&ctx1, final, 16);
} else {
ngx_md5_update(&ctx1, key, keylen);
}
ngx_md5_final(final, &ctx1);
}
/* output */
*encrypted = ngx_pnalloc(pool, sizeof("$apr1$") - 1 + saltlen + 1 + 22 + 1);
if (*encrypted == NULL) {
return NGX_ERROR;
}
p = ngx_cpymem(*encrypted, "$apr1$", sizeof("$apr1$") - 1);
p = ngx_copy(p, salt, saltlen);
*p++ = '$';
p = ngx_crypt_to64(p, (final[ 0]<<16) | (final[ 6]<<8) | final[12], 4);
p = ngx_crypt_to64(p, (final[ 1]<<16) | (final[ 7]<<8) | final[13], 4);
p = ngx_crypt_to64(p, (final[ 2]<<16) | (final[ 8]<<8) | final[14], 4);
p = ngx_crypt_to64(p, (final[ 3]<<16) | (final[ 9]<<8) | final[15], 4);
p = ngx_crypt_to64(p, (final[ 4]<<16) | (final[10]<<8) | final[ 5], 4);
p = ngx_crypt_to64(p, final[11], 2);
*p = '\0';
return NGX_OK;
}
static u_char *
ngx_crypt_to64(u_char *p, uint32_t v, size_t n)
{
static u_char itoa64[] =
"./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
while (n--) {
*p++ = itoa64[v & 0x3f];
v >>= 6;
}
return p;
}
static ngx_int_t
ngx_crypt_plain(ngx_pool_t *pool, u_char *key, u_char *salt, u_char **encrypted)
{
size_t len;
u_char *p;
len = ngx_strlen(key);
*encrypted = ngx_pnalloc(pool, sizeof("{PLAIN}") - 1 + len + 1);
if (*encrypted == NULL) {
return NGX_ERROR;
}
p = ngx_cpymem(*encrypted, "{PLAIN}", sizeof("{PLAIN}") - 1);
ngx_memcpy(p, key, len + 1);
return NGX_OK;
}
static ngx_int_t
ngx_crypt_ssha(ngx_pool_t *pool, u_char *key, u_char *salt, u_char **encrypted)
{
size_t len;
ngx_int_t rc;
ngx_str_t encoded, decoded;
ngx_sha1_t sha1;
/* "{SSHA}" base64(SHA1(key salt) salt) */
/* decode base64 salt to find out true salt */
encoded.data = salt + sizeof("{SSHA}") - 1;
encoded.len = ngx_strlen(encoded.data);
len = ngx_max(ngx_base64_decoded_length(encoded.len), 20);
decoded.data = ngx_pnalloc(pool, len);
if (decoded.data == NULL) {
return NGX_ERROR;
}
rc = ngx_decode_base64(&decoded, &encoded);
if (rc != NGX_OK || decoded.len < 20) {
decoded.len = 20;
}
/* update SHA1 from key and salt */
ngx_sha1_init(&sha1);
ngx_sha1_update(&sha1, key, ngx_strlen(key));
ngx_sha1_update(&sha1, decoded.data + 20, decoded.len - 20);
ngx_sha1_final(decoded.data, &sha1);
/* encode it back to base64 */
len = sizeof("{SSHA}") - 1 + ngx_base64_encoded_length(decoded.len) + 1;
*encrypted = ngx_pnalloc(pool, len);
if (*encrypted == NULL) {
return NGX_ERROR;
}
encoded.data = ngx_cpymem(*encrypted, "{SSHA}", sizeof("{SSHA}") - 1);
ngx_encode_base64(&encoded, &decoded);
encoded.data[encoded.len] = '\0';
return NGX_OK;
}
static ngx_int_t
ngx_crypt_sha(ngx_pool_t *pool, u_char *key, u_char *salt, u_char **encrypted)
{
size_t len;
ngx_str_t encoded, decoded;
ngx_sha1_t sha1;
u_char digest[20];
/* "{SHA}" base64(SHA1(key)) */
decoded.len = sizeof(digest);
decoded.data = digest;
ngx_sha1_init(&sha1);
ngx_sha1_update(&sha1, key, ngx_strlen(key));
ngx_sha1_final(digest, &sha1);
len = sizeof("{SHA}") - 1 + ngx_base64_encoded_length(decoded.len) + 1;
*encrypted = ngx_pnalloc(pool, len);
if (*encrypted == NULL) {
return NGX_ERROR;
}
encoded.data = ngx_cpymem(*encrypted, "{SHA}", sizeof("{SHA}") - 1);
ngx_encode_base64(&encoded, &decoded);
encoded.data[encoded.len] = '\0';
return NGX_OK;
}
#endif /* NGX_CRYPT */
| 2.375 | 2 |
2024-11-18T22:11:16.287381+00:00 | 2020-05-07T17:58:12 | c3dfb761ddd57963c7f259d7a0706783d0daf2fd | {
"blob_id": "c3dfb761ddd57963c7f259d7a0706783d0daf2fd",
"branch_name": "refs/heads/master",
"committer_date": "2020-05-07T17:58:12",
"content_id": "6facb490440f2c77b067c49ff71eda9a2dda582c",
"detected_licenses": [
"CC0-1.0"
],
"directory_id": "29bc4d9f953cdf7aec9ebfdafc94607dbc014e3d",
"extension": "c",
"filename": "main.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 257636180,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 189,
"license": "CC0-1.0",
"license_type": "permissive",
"path": "/string4/main.c",
"provenance": "stackv2-0072.json.gz:43634",
"repo_name": "wrench1815/C-Programs-repo",
"revision_date": "2020-05-07T17:58:12",
"revision_id": "874ce59c21a9ea04c74f94b232284e0f75170b26",
"snapshot_id": "933b65e7fc5f0a0ca50c03936f4c5bc2ccfa40bd",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/wrench1815/C-Programs-repo/874ce59c21a9ea04c74f94b232284e0f75170b26/string4/main.c",
"visit_date": "2022-06-23T22:05:23.826564"
} | stackv2 | #include <stdio.h>
#include <stdlib.h>
int main()
{
char str[99];
printf("Enter Full Name\n");
scanf("%[^\n]s",str);
printf("Hello %s",str);
return 0;
}
| 2.765625 | 3 |
2024-11-18T22:11:16.674932+00:00 | 2022-11-04T15:40:34 | c2de6f2ef1b0ab24debc57035a44a2744d7d0adb | {
"blob_id": "c2de6f2ef1b0ab24debc57035a44a2744d7d0adb",
"branch_name": "refs/heads/master",
"committer_date": "2022-11-04T15:40:34",
"content_id": "42bb48caf0e1fc61dae427a133e1b81959ac2659",
"detected_licenses": [
"Unlicense"
],
"directory_id": "ad72a007df18d5daba067ebff17b096808cb29b7",
"extension": "c",
"filename": "01-02-hello.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 150706585,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 166,
"license": "Unlicense",
"license_type": "permissive",
"path": "/progr/c/the-c-progr-language/exercises/01-02-hello.c",
"provenance": "stackv2-0072.json.gz:43762",
"repo_name": "catalingheorghe/learning-activities",
"revision_date": "2022-11-04T15:40:34",
"revision_id": "fafb0cc112fdaae11d2245260fe9ede37997fb28",
"snapshot_id": "9e73c9c37eb2e948d46e61183ff96fd7e12bc49f",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/catalingheorghe/learning-activities/fafb0cc112fdaae11d2245260fe9ede37997fb28/progr/c/the-c-progr-language/exercises/01-02-hello.c",
"visit_date": "2022-11-26T08:27:45.156153"
} | stackv2 | #include <stdio.h>
int main()
{
printf("hello, world\n");
printf("alert '\a'\n");
printf("octal 101 hex 41 - dec 65, ascii A -: '\101' '\x41'\n");
return 0;
}
| 2.609375 | 3 |
2024-11-18T22:11:16.786672+00:00 | 2020-12-08T06:18:58 | 38c643e74b1f56a3119e892f9d58a6b52ce26577 | {
"blob_id": "38c643e74b1f56a3119e892f9d58a6b52ce26577",
"branch_name": "refs/heads/main",
"committer_date": "2020-12-08T06:18:58",
"content_id": "f0923e047a951610fe7daec0289f91596d45e13c",
"detected_licenses": [
"Unlicense"
],
"directory_id": "911044fc525ca6e2ca7e5ac2205e62b830c00a76",
"extension": "h",
"filename": "CV.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 319529975,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 941,
"license": "Unlicense",
"license_type": "permissive",
"path": "/iface/CV.h",
"provenance": "stackv2-0072.json.gz:44018",
"repo_name": "s53g4z/CVector",
"revision_date": "2020-12-08T06:18:58",
"revision_id": "418b52dab0ed974fbaa0f746b8f3762d828a12e9",
"snapshot_id": "278b5be33113713ce590854b7d83788a4b3eee74",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/s53g4z/CVector/418b52dab0ed974fbaa0f746b8f3762d828a12e9/iface/CV.h",
"visit_date": "2023-02-01T17:31:15.931277"
} | stackv2 | #ifndef CVHCVH
#define CVHCVH
#include <stdlib.h>
#include <string.h>
#include <stdio.h> // for CV_check() internal array printing
#define nullptr ((void *)0)
typedef unsigned char bool;
#define true 1
#define false 0
typedef long long unsigned llu;
#define LLU_MAX ~0llu
struct CVector;
typedef struct CVector CV;
// The user interface consists of the functions below.
CV *CV_new(llu nelem_req, llu nelem_sz); // Return a new CV.
void CV_delete(CV *cv); // Delete the CV.
CV *CV_push_back(CV *cv, void *ep); // Append to the CV.
void *CV_at(CV *cv, llu index); // Return a ptr to a CV element.
llu CV_size(CV *cv); // Return the number of elements.
void CV_clear(CV *cv); // Delete all elements.
void *CV_insert(CV *cv, const llu index, const void *const ep); // Insert elem.
void *CV_erase(CV *const cv, const llu index); // Erase elem.
void CV_check(CV *cv, bool quiet); // Run basic self-checks on CV.
#endif
| 2.40625 | 2 |
2024-11-18T22:11:17.057561+00:00 | 2018-05-06T05:15:37 | b267fff67e6e7354a0d3fdacfa05ed57d1fc7136 | {
"blob_id": "b267fff67e6e7354a0d3fdacfa05ed57d1fc7136",
"branch_name": "refs/heads/master",
"committer_date": "2018-05-06T05:15:37",
"content_id": "f0d0dd786f8a4e85e626f86d70ddff9df8c5e22c",
"detected_licenses": [
"MIT"
],
"directory_id": "3b29fe203a16fcca5e1f68c717a22c515f68a731",
"extension": "c",
"filename": "challenge_9.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 114080581,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 504,
"license": "MIT",
"license_type": "permissive",
"path": "/src/set_2/challenge_9.c",
"provenance": "stackv2-0072.json.gz:44275",
"repo_name": "JohnAgapeyev/Cryptopals",
"revision_date": "2018-05-06T05:15:37",
"revision_id": "b36584c4ede6cd421ad467fbb1035c22373294f6",
"snapshot_id": "ffd95ae5de9fc82a3a7be6a996e698f1ff20c934",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/JohnAgapeyev/Cryptopals/b36584c4ede6cd421ad467fbb1035c22373294f6/src/set_2/challenge_9.c",
"visit_date": "2021-05-06T09:35:51.698769"
} | stackv2 | #include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "../common.h"
int main(void) {
const char *mesg = "YELLOW SUBMARINE";
unsigned char *padded = pkcs7_pad((const unsigned char *) mesg, strlen(mesg), 20);
printf("Set 2 Challenge 9 Padded Message: ");
for (size_t i = 0; i < strlen(mesg); ++i) {
printf("%c", padded[i]);
}
for (size_t i = 0; i < padded[19]; ++i) {
printf("%02x", padded[i + 16]);
}
printf("\n");
return EXIT_SUCCESS;
}
| 2.6875 | 3 |
2024-11-18T22:11:17.120471+00:00 | 2017-10-02T23:12:40 | ce9d67ed0937c87c3c4b4772948bf897f5e7afef | {
"blob_id": "ce9d67ed0937c87c3c4b4772948bf897f5e7afef",
"branch_name": "refs/heads/master",
"committer_date": "2017-10-02T23:12:40",
"content_id": "c465f1a4a33f1a8568a1da3bf6411602c6ef5cd4",
"detected_licenses": [
"Zlib"
],
"directory_id": "aebf2fa2eea05024d8d843d7029107e51d5d9383",
"extension": "c",
"filename": "linkedlist.c",
"fork_events_count": 2,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 34886887,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 843,
"license": "Zlib",
"license_type": "permissive",
"path": "/src/linkedlist.c",
"provenance": "stackv2-0072.json.gz:44406",
"repo_name": "goodpaul6/mint-lang",
"revision_date": "2017-10-02T23:12:40",
"revision_id": "138e66b786301f772387a268727a9d6489f12380",
"snapshot_id": "604331e8de5500c24758f12bcb608a3ddc24a2ee",
"src_encoding": "UTF-8",
"star_events_count": 20,
"url": "https://raw.githubusercontent.com/goodpaul6/mint-lang/138e66b786301f772387a268727a9d6489f12380/src/linkedlist.c",
"visit_date": "2018-10-10T11:39:53.354801"
} | stackv2 | #include <stdlib.h>
#include <stdio.h>
#include "linkedlist.h"
void InitList(LinkedList* list)
{
list->head = list->tail = NULL;
list->length = 0;
}
int AddNode(LinkedList* list, void* data)
{
LinkedListNode* newNode = malloc(sizeof(LinkedListNode));
if(!newNode)
{
fprintf(stderr, "Out of memory\n");
exit(1);
}
newNode->next = NULL;
newNode->data = data;
if(!list->length)
list->head = list->tail = newNode;
else
{
list->tail->next = newNode;
list->tail = newNode;
}
++list->length;
return list->length - 1;
}
void FreeList(LinkedList* list)
{
if(!list) return;
if(list->length)
{
LinkedListNode* curr;
LinkedListNode* next;
curr = list->head;
while(curr)
{
next = curr->next;
if(curr->data)
free(curr->data);
free(curr);
curr = next;
}
}
free(list);
}
| 3.234375 | 3 |
2024-11-18T22:11:17.180034+00:00 | 2023-08-27T20:08:08 | bf8a8444755a6a5d5688ac989746b47866750f15 | {
"blob_id": "bf8a8444755a6a5d5688ac989746b47866750f15",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-27T20:08:08",
"content_id": "b96e62677c7425402d74ff4821f1159690ab4805",
"detected_licenses": [
"MIT"
],
"directory_id": "1af43c4ba32d78c60f007a4d068136ce575d917f",
"extension": "c",
"filename": "hid_app.c",
"fork_events_count": 69,
"gha_created_at": "2018-11-01T03:54:21",
"gha_event_created_at": "2023-08-17T08:44:32",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 155659451,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2595,
"license": "MIT",
"license_type": "permissive",
"path": "/system/apps_usb/test25_hid/usb/hid_app.c",
"provenance": "stackv2-0072.json.gz:44534",
"repo_name": "gabonator/LA104",
"revision_date": "2023-08-27T20:08:08",
"revision_id": "27d0eece7302c479da2cf86e881b6a51a535f93d",
"snapshot_id": "a4f1cdf2b3e513300d61c50fff091c5717abda9e",
"src_encoding": "UTF-8",
"star_events_count": 500,
"url": "https://raw.githubusercontent.com/gabonator/LA104/27d0eece7302c479da2cf86e881b6a51a535f93d/system/apps_usb/test25_hid/usb/hid_app.c",
"visit_date": "2023-08-31T22:09:36.272616"
} | stackv2 | #include "hid_app.h"
#include "hid_desc.h"
#include "hid_conf.h"
volatile uint8_t kb_tx_complete = 1;
volatile uint8_t mouse_tx_complete = 1;
volatile uint8_t joy1_tx_complete = 1;
volatile uint8_t joy2_tx_complete = 1;
usb_joy_report_ready_cb_f joy_report_ready_cb = NULL;
usb_kb_report_ready_cb_f kb_report_ready_cb = NULL;
usb_mouse_report_ready_cb_f mouse_report_ready_cb = NULL;
uint8_t kb_led_state = 0;
DEVICE_STATE bDeviceState;
void USB_ARC_set_kb_callback(usb_kb_report_ready_cb_f cb) {
kb_report_ready_cb = cb;
}
void USB_ARC_set_mouse_callback(usb_mouse_report_ready_cb_f cb) {
mouse_report_ready_cb = cb;
}
void USB_ARC_set_joystick_callback(usb_joy_report_ready_cb_f cb) {
joy_report_ready_cb = cb;
}
bool USB_ARC_KB_tx(usb_kb_report *report)
{
// byte 0: modifiers
// byte 1: reserved (0x00)
// byte 2-x: keypresses
report->reserved = 0;
uint32_t spoon_guard = 1000000;
while(kb_tx_complete==0 && --spoon_guard);
if (spoon_guard <= 0)
return false;
//ASSERT(spoon_guard > 0);
/* Reset the control token to inform upper layer that a transfer is ongoing */
kb_tx_complete = 0;
/* Copy keyboard vector info in ENDP1 Tx Packet Memory Area*/
USB_SIL_Write(EP1_IN, report->raw, sizeof(report->raw));
/* Enable endpoint for transmission */
SetEPTxValid(ENDP1);
return true;
}
bool USB_ARC_MOUSE_tx(usb_mouse_report *report)
{
uint32_t spoon_guard = 1000000;
while(mouse_tx_complete==0 && --spoon_guard);
if (spoon_guard <= 0)
return false;
//ASSERT(spoon_guard > 0);
/* Reset the control token to inform upper layer that a transfer is ongoing */
mouse_tx_complete = 0;
/* Copy mouse position info in ENDP2 Tx Packet Memory Area*/
USB_SIL_Write(EP2_IN, report->raw, sizeof(report->raw));
/* Enable endpoint for transmission */
SetEPTxValid(ENDP2);
return true;
}
bool USB_ARC_JOYSTICK_tx(usb_joystick j, usb_joystick_report *report)
{
uint32_t spoon_guard = 1000000;
if (j == JOYSTICK1) {
while(joy1_tx_complete==0 && --spoon_guard);
} else {
while(joy2_tx_complete==0 && --spoon_guard);
}
if (spoon_guard <= 0)
return false;
//ASSERT(spoon_guard > 0);
/* Reset the control token to inform upper layer that a transfer is ongoing */
if (j == JOYSTICK1) {
joy1_tx_complete= 0;
} else {
joy2_tx_complete = 0;
}
/* Copy joystick info in ENDP3/4 Tx Packet Memory Area*/
USB_SIL_Write(j == JOYSTICK1 ? EP3_IN : EP4_IN, report->raw, sizeof(report->raw));
/* Enable endpoint for transmission */
SetEPTxValid(j == JOYSTICK1 ? ENDP3 : ENDP4);
return true;
}
| 2.296875 | 2 |
2024-11-18T22:11:17.254830+00:00 | 2018-10-03T09:38:27 | 1bdb589058399da2046382b160e93f933eb8238f | {
"blob_id": "1bdb589058399da2046382b160e93f933eb8238f",
"branch_name": "refs/heads/master",
"committer_date": "2018-10-03T09:38:27",
"content_id": "8ddc7e557908aa9b0905448d77701e4ff4f8d916",
"detected_licenses": [
"MIT"
],
"directory_id": "fd7c8ac90af5ea2cacd9decac67ddb4eba64976f",
"extension": "c",
"filename": "test_strx.c",
"fork_events_count": 0,
"gha_created_at": "2018-10-04T07:09:11",
"gha_event_created_at": "2018-10-04T07:09:11",
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 151532281,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 528,
"license": "MIT",
"license_type": "permissive",
"path": "/test/test_strx/test_strx.c",
"provenance": "stackv2-0072.json.gz:44663",
"repo_name": "Svedrin/siridb-server",
"revision_date": "2018-10-03T09:38:27",
"revision_id": "27d64bbfd401243a304566a8108aac745be1260c",
"snapshot_id": "ab257e8bed51606411ea8113794ff23d5c57ed4e",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Svedrin/siridb-server/27d64bbfd401243a304566a8108aac745be1260c/test/test_strx/test_strx.c",
"visit_date": "2020-03-30T19:11:03.940788"
} | stackv2 | #include "../test.h"
#include <strextra/strextra.h>
int main()
{
test_start("strx");
/* strx_to_double */
{
_assert (strx_to_double("0.5", 3) == 0.5);
_assert (strx_to_double("0.55", 3) == 0.5);
_assert (strx_to_double("123.456", 7) == 123.456);
_assert (strx_to_double("123", 3) == 123);
_assert (strx_to_double("123.", 4) == 123);
_assert (strx_to_double("123456.", 3) == 123);
_assert (strx_to_double("-0.5", 3) == -0.5);
}
return test_end();
}
| 2.171875 | 2 |
2024-11-18T22:11:18.066216+00:00 | 2020-05-29T23:17:25 | 042dc1477157a818132c179ab04ef89a5fdc2620 | {
"blob_id": "042dc1477157a818132c179ab04ef89a5fdc2620",
"branch_name": "refs/heads/master",
"committer_date": "2020-05-29T23:17:25",
"content_id": "650a90908b29afec0e5a0adc95c17118a9a46a4c",
"detected_licenses": [
"MIT"
],
"directory_id": "b23a1df284e683a571de19ee19e11eb5a5bb5e46",
"extension": "h",
"filename": "discharge.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 256028275,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3284,
"license": "MIT",
"license_type": "permissive",
"path": "/IRLKTANE/discharge.h",
"provenance": "stackv2-0072.json.gz:44920",
"repo_name": "AziDesigns/IRLKTANE",
"revision_date": "2020-05-29T23:17:25",
"revision_id": "f1105498c6a2ff91f9d61bfff9525ce2c191e0fb",
"snapshot_id": "0e46df362584f4796b9c3c5ff4c67fed2ded3f0b",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/AziDesigns/IRLKTANE/f1105498c6a2ff91f9d61bfff9525ce2c191e0fb/IRLKTANE/discharge.h",
"visit_date": "2022-10-02T20:24:55.580996"
} | stackv2 | // On the Subject of Discharge
/*
KNOWN ISSUES:
MODULE FULLY FUNCTIONS FROM A BUTTON, LED, AND INCREASING TIME STANDPOINT,
HOWEVER THE LEVER IS JUST A BUTTON, NO LEVER INSTALLED. WILL STILL BE A SWITCH OF SOME KIND BUT NEEDS DESIGNED.
*/
#define PIN_DISCHARGE_LED_1 2,0,7 // turns on when button pressed
#define PIN_DISCHARGE_BUTTON_1 A9 // discharge button
#define DISCHARGE_DEFAULT_TIME 45 // default time per rotation
unsigned long dischargeSeconds = 0;
byte dischargeSec = DISCHARGE_DEFAULT_TIME + 1;
byte dischargeButtonState = 0; // current state of the button
byte lastDischargeButtonState = 0; // previous state of the button
byte addOrSubtractTime = 0; //0=subtract,1=add
void dischargeSetup()
{
if (DEBUG_LEVEL >= 3) {
Serial.println (__func__);
}
pinMode(PIN_DISCHARGE_BUTTON_1, INPUT);
};
void dischargeDisplayTime() // function that displays the time on the clock
{
if (DEBUG_LEVEL >= 3) {
Serial.println (__func__);
}
if (addOrSubtractTime==0) {
if (dischargeSeconds < millis()) {
dischargeSeconds += 1000;
dischargeSec--;
}
} else if ((addOrSubtractTime==1) && (dischargeSec<DISCHARGE_DEFAULT_TIME)) {
if (dischargeSeconds < millis()) {
dischargeSeconds += 200;
dischargeSec++;
}
} else if ((addOrSubtractTime==1) && (dischargeSec>=DISCHARGE_DEFAULT_TIME)) {
if (dischargeSeconds < millis()) {
dischargeSeconds += 1000;
dischargeSec=DISCHARGE_DEFAULT_TIME;
}
}
if (dischargeSec == -1) {
addStrike(); // if the time hits zero the bomb will go off
}
needyDigitDisplay(1, 2, 3, dischargeSec);
}
void dischargeLoop()
{
if (DEBUG_LEVEL >= 3) {
Serial.println (__func__);
}
if (!defused && !exploded) {
dischargeDisplayTime();
dischargeButtonState = digitalRead(PIN_DISCHARGE_BUTTON_1);
// compare the dischargeButtonState to its previous state
if (dischargeButtonState != lastDischargeButtonState) {
if (dischargeButtonState == HIGH) {
if (DEBUG_LEVEL >= 1) {
Serial.println(F("dischargeButtonOn"));
}
addOrSubtractTime=1; //this is what adds the time back
lc.setLed(PIN_DISCHARGE_LED_1,true);
} else {
if (DEBUG_LEVEL >= 1) {
Serial.println(F("dischargeButtonOff"));
}
addOrSubtractTime=0; //reduces time when not pressed
lc.setLed(PIN_DISCHARGE_LED_1,false);
}
}
// save the current state as the last state, for next time through the loop
lastDischargeButtonState = dischargeButtonState;
}
}
void dischargeBombDefused()
{
if (DEBUG_LEVEL >= 2) {
Serial.println (__func__);
}
lc.setDigit(1,3,' ',false);
lc.setDigit(1,2,' ',false);
lc.setLed(PIN_DISCHARGE_LED_1,false);
}
void dischargeModuleBoom()
{
if (DEBUG_LEVEL >= 2) {
Serial.println (__func__);
}
// when the bomb explodes the LED and so should countdown timer above module
if (explodedFromStrikes) {
//NEED TO PRINT TO LC.... TO SAY DISPLAY TIME REMAINING //RIGHT NOW IT SHOWS ' '
lc.setDigit(1,3,' ',false);
lc.setDigit(1,2,' ',false);
}
else {
//NEED TO PRINT TO LC.... TO SAY DISPLAY NOTHING
lc.setDigit(1,3,' ',false);
lc.setDigit(1,2,' ',false);
}
lc.setLed(PIN_DISCHARGE_LED_1,false);
}
| 2.40625 | 2 |
2024-11-18T22:11:18.576553+00:00 | 2023-04-29T08:15:24 | 8e46222678a8b56831c950ec8e74bffbd6c39c41 | {
"blob_id": "8e46222678a8b56831c950ec8e74bffbd6c39c41",
"branch_name": "refs/heads/master",
"committer_date": "2023-04-29T08:15:24",
"content_id": "b3a4acd92ec0c2b3481e38aa60ad0fb1d3a51199",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "e3c0499cc58c9fbec887a2e85672d5e29588f9e0",
"extension": "c",
"filename": "cutf.c",
"fork_events_count": 19,
"gha_created_at": "2015-08-05T12:02:52",
"gha_event_created_at": "2023-09-08T08:04:04",
"gha_language": "C++",
"gha_license_id": "NOASSERTION",
"github_id": 40242945,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4525,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/dex/clibs/basic/arch/common/utf/cutf.c",
"provenance": "stackv2-0072.json.gz:45178",
"repo_name": "stevenknown/xoc",
"revision_date": "2023-04-29T08:15:24",
"revision_id": "3514aaf0d742e7c1bff956f5a5e96a92102abe8a",
"snapshot_id": "bf19fba2a7851f0c91d62846b61f12000993fa94",
"src_encoding": "UTF-8",
"star_events_count": 132,
"url": "https://raw.githubusercontent.com/stevenknown/xoc/3514aaf0d742e7c1bff956f5a5e96a92102abe8a/dex/clibs/basic/arch/common/utf/cutf.c",
"visit_date": "2023-05-14T10:18:34.851859"
} | stackv2 | /*Copyright 2011 Alibaba Group*/
/*
* cutf.c
* madagascar
*
* Created by Misa.Z on 2/28/09.
* Copyright 2009 Virtualnology. All rights reserved.
*
*/
#include "utf/cutf.h"
#include "std/cstd.h"
#include "mem/cmemport.h"
static const BYTE _utf8_bytes_map[] = {
1,1,1,1,1,1,1,1,
1,1,1,1,2,2,3,4
};//error encoding char as 1 byte char
#define get_utf8_char_len(c) (_utf8_bytes_map[((UInt8)(c))>>4])
//#ifdef __SYMBIAN32__
// static const BYTE _specialBytes[] = {0xEF,0xBF,0xBD,0xEF,0xBF,0xBD};
//#endif
UInt32 cUtf8Chars(const char* p, UInt32 size) {
UInt32 len,count;
const char* end;
if(p == NULL) {
return 0;
}
count = 0;
end = p + size;
while(p < end) {
len = get_utf8_char_len(*p);
//TODO: aaron patch this temporary for opera mini plug bug, fix this
//#ifdef __SYMBIAN32__
// if(*p == 0xEF && p+6 < end) {
// if(cMemcmp(p, _specialBytes, 6) == 0) {//got /u0000 in unicode for opera mini plugin
// len = 6;
// }
// }
//#endif
count++;
p+=len;
}
return count;
}
UInt32 cUtf8LengthOfUtf16(const UInt16* p, UInt32 size) {
const UInt16* end;
UInt32 len;
UInt16 c;
if(p == NULL) {
return 0;
}
end = p + size;
len = 0;
while(p < end) {
c = *p;
if(c == 0x0) // for 'modified UTF-8', '\0' is 2 bytes. added by liucj
len += 2;
else if(c < 0x80) //1byte
len += 1;
else if(c < 0x800) //2bytes
len += 2;
else //3bytes
len += 3;
++p;
}
return len;
}
UInt32 cUtf8ToUtf16(const char* utf8, UInt32 utf8Size, UInt16* utf16, UInt32 utf16Size) {
UInt32 c,len,pos,idx;
if(utf8 == NULL || utf16 == NULL)
return 0;
len = pos = idx = 0;
while(idx < utf8Size && pos < utf16Size) {
//TODO: aaron patch this temporary for opera mini plug bug, fix this
//#ifdef __SYMBIAN32__
// if(*utf8 == 0xEF && idx+6 < utf8Size) {
// if(cMemcmp(utf8, _specialBytes, 6) == 0) {//got /u0000 in unicode for opera mini plugin
// idx += 6;
// utf16[pos] = 0;
// utf16[pos+1] = 0;
// pos += 2;
// continue;
// }
// }
//#endif
len = get_utf8_char_len(*utf8);
c = (0xFF>>(len)) & (*utf8++);
idx++;
len--;
while(len) {
c <<= 6;
c |= (*utf8++)&0x3F;
++idx;
--len;
}
utf16[pos] = c & 0xffff;
++pos;
}
return pos;
}
UInt32 cUtf16ToUtf8(const UInt16* utf16, UInt32 utf16Size, char* utf8, UInt32 utf8Size) {
UInt32 len,pos,limit,idx,size;
UInt32 c;
if(utf16 == NULL || utf8 == NULL)
return 0;
len = pos = idx = 0;
while(idx < utf16Size) {
c = utf16[idx];
if(c == 0x0) // for 'modified UTF-8', '\0' is 2 bytes. added by liucj
len = 2;
else if(c < 0x80) //1byte
len = 1;
else if(c < 0x800) //2bytes
len = 2;
else //3bytes
len = 3;
if(pos + len > utf8Size)
break;
switch(len) {
case 3: utf8[pos+2] = 0x80 | (c & 0x3f); c = (c >> 6) | 0x800;
case 2: utf8[pos+1] = 0x80 | (c & 0x3f); c = (c >> 6) | 0xc0;
case 1: utf8[pos] = (BYTE)c;
}
idx++;
pos += len;
}
return pos;
}
UInt16* cUtf16FromUtf8(const char* utf8, UInt32 utf8Size, Int32 *len) {
UInt16 *ret;
Int32 sz;
*len = 0;
if(utf8 == NULL || utf8Size == 0)
return NULL;
sz = cUtf8Chars(utf8, utf8Size);
if(sz <= 0)
return NULL;
ret = (UInt16*)cMallocPort(2*sz);
if(ret == NULL)
return NULL;
sz = cUtf8ToUtf16(utf8, utf8Size, ret, sz*2);
if(sz <= 0) {
cFreePort(ret);
*len = 0;
return NULL;
}
*len = sz/2;
return ret;
}
// need free with cFree
char* cUtf8FromUtf16(const UInt16* utf16, UInt32 utf16Size, Int32 *len) {
char* ret;
Int32 sz;
*len = 0;
if(utf16 == NULL || utf16Size == 0)
return NULL;
sz = cUtf8LengthOfUtf16(utf16, utf16Size);
if(sz <= 0)
return NULL;
ret = (char*)cMallocPort(sz);
if(ret == NULL)
return NULL;
sz = cUtf16ToUtf8(utf16, utf16Size, ret, sz);
if(sz <= 0) {
cFreePort(ret);
*len = 0;
return NULL;
}
*len = sz;
return ret;
}
| 2.328125 | 2 |
2024-11-18T22:11:18.735453+00:00 | 2023-04-02T05:01:06 | 910afd7d47fe85db1938a783e1e7c4cd5dd942fd | {
"blob_id": "910afd7d47fe85db1938a783e1e7c4cd5dd942fd",
"branch_name": "refs/heads/master",
"committer_date": "2023-04-12T11:10:39",
"content_id": "520d81c6dca10784d9523a75d49520a75840ee97",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "9f275713fcb7930ddd22aa14123d1e3bb8da793d",
"extension": "h",
"filename": "emul.h",
"fork_events_count": 10,
"gha_created_at": "2017-05-17T18:55:26",
"gha_event_created_at": "2020-12-22T16:15:48",
"gha_language": "C",
"gha_license_id": "Apache-2.0",
"github_id": 91610223,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 976,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/tests/drivers/smbus/smbus_emul/src/emul.h",
"provenance": "stackv2-0072.json.gz:45435",
"repo_name": "antmicro/zephyr",
"revision_date": "2023-04-02T05:01:06",
"revision_id": "51a7de2beb13249804200164610358158088588e",
"snapshot_id": "5f2bd515507057fb34efe40ba3b756584e9749e7",
"src_encoding": "UTF-8",
"star_events_count": 10,
"url": "https://raw.githubusercontent.com/antmicro/zephyr/51a7de2beb13249804200164610358158088588e/tests/drivers/smbus/smbus_emul/src/emul.h",
"visit_date": "2023-08-30T21:44:04.126331"
} | stackv2 | /*
* Copyright (c) 2022 Intel Corporation
*
* SPDX-License-Identifier: Apache-2.0
*/
/* Read from PCI configuration space */
uint32_t emul_pci_read(unsigned int reg);
/* Write to PCI configuration space */
void emul_pci_write(pcie_bdf_t bdf, unsigned int reg, uint32_t value);
void emul_out8(uint8_t data, io_port_t addr);
uint8_t emul_in8(io_port_t addr);
void emul_set_io(uint8_t value, io_port_t addr);
uint8_t emul_get_io(io_port_t addr);
enum emul_isr_type {
EMUL_SMBUS_INTR,
EMUL_SMBUS_SMBALERT,
EMUL_SMBUS_HOST_NOTIFY,
};
void run_isr(enum emul_isr_type);
struct smbus_peripheral {
sys_snode_t node;
uint8_t raw_data[256];
uint8_t offset;
uint8_t addr;
bool smbalert;
bool smbalert_handled;
bool host_notify;
};
bool peripheral_handle_host_notify(void);
static inline void peripheral_clear_smbalert(struct smbus_peripheral *periph)
{
periph->smbalert_handled = false;
}
void emul_register_smbus_peripheral(struct smbus_peripheral *peripheral);
| 2.09375 | 2 |
2024-11-18T22:11:19.699964+00:00 | 2019-03-12T07:55:03 | b862d606d8bcaf02151c671f4a3e1bd948e573f1 | {
"blob_id": "b862d606d8bcaf02151c671f4a3e1bd948e573f1",
"branch_name": "refs/heads/master",
"committer_date": "2019-03-12T07:55:03",
"content_id": "74fa15fddbcfe926e9c891ba84ef34491cea80db",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "f76584d0d3faab1825d4f475a7e0502a5f8083c9",
"extension": "c",
"filename": "tkt.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 175131015,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 44138,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/src/tkt.c",
"provenance": "stackv2-0072.json.gz:46204",
"repo_name": "wilsoncrespo/fossil_scm",
"revision_date": "2019-03-12T07:55:03",
"revision_id": "d6266793a0e28044520c1074e56bb9ae9b509553",
"snapshot_id": "e0bd3fb284b6fc1aa3f406f68ae33b5ebec56dcf",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/wilsoncrespo/fossil_scm/d6266793a0e28044520c1074e56bb9ae9b509553/src/tkt.c",
"visit_date": "2020-04-28T08:31:41.105345"
} | stackv2 | /*
** Copyright (c) 2007 D. Richard Hipp
**
** This program is free software; you can redistribute it and/or
** modify it under the terms of the Simplified BSD License (also
** known as the "2-Clause License" or "FreeBSD License".)
** This program is distributed in the hope that it will be useful,
** but without any warranty; without even the implied warranty of
** merchantability or fitness for a particular purpose.
**
** Author contact information:
** [email protected]
** http://www.hwaci.com/drh/
**
*******************************************************************************
**
** This file contains code used render and control ticket entry
** and display pages.
*/
#include "config.h"
#include "tkt.h"
#include <assert.h>
/*
** The list of database user-defined fields in the TICKET table.
** The real table also contains some addition fields for internal
** used. The internal-use fields begin with "tkt_".
*/
static int nField = 0;
static struct tktFieldInfo {
char *zName; /* Name of the database field */
char *zValue; /* Value to store */
char *zAppend; /* Value to append */
unsigned mUsed; /* 01: TICKET 02: TICKETCHNG */
} *aField;
#define USEDBY_TICKET 01
#define USEDBY_TICKETCHNG 02
#define USEDBY_BOTH 03
static u8 haveTicket = 0; /* True if the TICKET table exists */
static u8 haveTicketCTime = 0; /* True if TICKET.TKT_CTIME exists */
static u8 haveTicketChng = 0; /* True if the TICKETCHNG table exists */
static u8 haveTicketChngRid = 0; /* True if TICKETCHNG.TKT_RID exists */
/*
** Compare two entries in aField[] for sorting purposes
*/
static int nameCmpr(const void *a, const void *b){
return fossil_strcmp(((const struct tktFieldInfo*)a)->zName,
((const struct tktFieldInfo*)b)->zName);
}
/*
** Return the index into aField[] of the given field name.
** Return -1 if zFieldName is not in aField[].
*/
static int fieldId(const char *zFieldName){
int i;
for(i=0; i<nField; i++){
if( fossil_strcmp(aField[i].zName, zFieldName)==0 ) return i;
}
return -1;
}
/*
** Obtain a list of all fields of the TICKET and TICKETCHNG tables. Put them
** in sorted order in aField[].
**
** The haveTicket and haveTicketChng variables are set to 1 if the TICKET and
** TICKETCHANGE tables exist, respectively.
*/
static void getAllTicketFields(void){
Stmt q;
int i;
static int once = 0;
if( once ) return;
once = 1;
db_prepare(&q, "PRAGMA table_info(ticket)");
while( db_step(&q)==SQLITE_ROW ){
const char *zFieldName = db_column_text(&q, 1);
haveTicket = 1;
if( memcmp(zFieldName,"tkt_",4)==0 ){
if( strcmp(zFieldName, "tkt_ctime")==0 ) haveTicketCTime = 1;
continue;
}
if( nField%10==0 ){
aField = fossil_realloc(aField, sizeof(aField[0])*(nField+10) );
}
aField[nField].zName = mprintf("%s", zFieldName);
aField[nField].mUsed = USEDBY_TICKET;
nField++;
}
db_finalize(&q);
db_prepare(&q, "PRAGMA table_info(ticketchng)");
while( db_step(&q)==SQLITE_ROW ){
const char *zFieldName = db_column_text(&q, 1);
haveTicketChng = 1;
if( memcmp(zFieldName,"tkt_",4)==0 ){
if( strcmp(zFieldName,"tkt_rid")==0 ) haveTicketChngRid = 1;
continue;
}
if( (i = fieldId(zFieldName))>=0 ){
aField[i].mUsed |= USEDBY_TICKETCHNG;
continue;
}
if( nField%10==0 ){
aField = fossil_realloc(aField, sizeof(aField[0])*(nField+10) );
}
aField[nField].zName = mprintf("%s", zFieldName);
aField[nField].mUsed = USEDBY_TICKETCHNG;
nField++;
}
db_finalize(&q);
qsort(aField, nField, sizeof(aField[0]), nameCmpr);
for(i=0; i<nField; i++){
aField[i].zValue = "";
aField[i].zAppend = 0;
}
}
/*
** Query the database for all TICKET fields for the specific
** ticket whose name is given by the "name" CGI parameter.
** Load the values for all fields into the interpreter.
**
** Only load those fields which do not already exist as
** variables.
**
** Fields of the TICKET table that begin with "private_" are
** expanded using the db_reveal() function. If g.perm.RdAddr is
** true, then the db_reveal() function will decode the content
** using the CONCEALED table so that the content legible.
** Otherwise, db_reveal() is a no-op and the content remains
** obscured.
*/
static void initializeVariablesFromDb(void){
const char *zName;
Stmt q;
int i, n, size, j;
zName = PD("name","-none-");
db_prepare(&q, "SELECT datetime(tkt_mtime,toLocal()) AS tkt_datetime, *"
" FROM ticket WHERE tkt_uuid GLOB '%q*'",
zName);
if( db_step(&q)==SQLITE_ROW ){
n = db_column_count(&q);
for(i=0; i<n; i++){
const char *zVal = db_column_text(&q, i);
const char *zName = db_column_name(&q, i);
char *zRevealed = 0;
if( zVal==0 ){
zVal = "";
}else if( strncmp(zName, "private_", 8)==0 ){
zVal = zRevealed = db_reveal(zVal);
}
if( (j = fieldId(zName))>=0 ){
aField[j].zValue = mprintf("%s", zVal);
}else if( memcmp(zName, "tkt_", 4)==0 && Th_Fetch(zName, &size)==0 ){
Th_Store(zName, zVal);
}
free(zRevealed);
}
}
db_finalize(&q);
for(i=0; i<nField; i++){
if( Th_Fetch(aField[i].zName, &size)==0 ){
Th_Store(aField[i].zName, aField[i].zValue);
}
}
}
/*
** Transfer all CGI parameters to variables in the interpreter.
*/
static void initializeVariablesFromCGI(void){
int i;
const char *z;
for(i=0; (z = cgi_parameter_name(i))!=0; i++){
Th_Store(z, P(z));
}
}
/*
** Update an entry of the TICKET and TICKETCHNG tables according to the
** information in the ticket artifact given in p. Attempt to create
** the appropriate TICKET table entry if tktid is zero. If tktid is nonzero
** then it will be the ROWID of an existing TICKET entry.
**
** Parameter rid is the recordID for the ticket artifact in the BLOB table.
**
** Return the new rowid of the TICKET table entry.
*/
static int ticket_insert(const Manifest *p, int rid, int tktid){
Blob sql1, sql2, sql3;
Stmt q;
int i, j;
char *aUsed;
if( tktid==0 ){
db_multi_exec("INSERT INTO ticket(tkt_uuid, tkt_mtime) "
"VALUES(%Q, 0)", p->zTicketUuid);
tktid = db_last_insert_rowid();
}
blob_zero(&sql1);
blob_zero(&sql2);
blob_zero(&sql3);
blob_append_sql(&sql1, "UPDATE OR REPLACE ticket SET tkt_mtime=:mtime");
if( haveTicketCTime ){
blob_append_sql(&sql1, ", tkt_ctime=coalesce(tkt_ctime,:mtime)");
}
aUsed = fossil_malloc( nField );
memset(aUsed, 0, nField);
for(i=0; i<p->nField; i++){
const char *zName = p->aField[i].zName;
const char *zBaseName = zName[0]=='+' ? zName+1 : zName;
j = fieldId(zBaseName);
if( j<0 ) continue;
aUsed[j] = 1;
if( aField[j].mUsed & USEDBY_TICKET ){
const char *zUsedByName = zName;
if( zUsedByName[0]=='+' ){
zUsedByName++;
blob_append_sql(&sql1,", \"%w\"=coalesce(\"%w\",'') || %Q",
zUsedByName, zUsedByName, p->aField[i].zValue);
}else{
blob_append_sql(&sql1,", \"%w\"=%Q", zUsedByName, p->aField[i].zValue);
}
}
if( aField[j].mUsed & USEDBY_TICKETCHNG ){
const char *zUsedByName = zName;
if( zUsedByName[0]=='+' ){
zUsedByName++;
}
blob_append_sql(&sql2, ",\"%w\"", zUsedByName);
blob_append_sql(&sql3, ",%Q", p->aField[i].zValue);
}
if( rid>0 ){
wiki_extract_links(p->aField[i].zValue, rid, 1, p->rDate, i==0, 0);
}
}
blob_append_sql(&sql1, " WHERE tkt_id=%d", tktid);
db_prepare(&q, "%s", blob_sql_text(&sql1));
db_bind_double(&q, ":mtime", p->rDate);
db_step(&q);
db_finalize(&q);
blob_reset(&sql1);
if( blob_size(&sql2)>0 || haveTicketChngRid ){
int fromTkt = 0;
if( haveTicketChngRid ){
blob_append(&sql2, ",tkt_rid", -1);
blob_append_sql(&sql3, ",%d", rid);
}
for(i=0; i<nField; i++){
if( aUsed[i]==0
&& (aField[i].mUsed & USEDBY_BOTH)==USEDBY_BOTH
){
const char *z = aField[i].zName;
if( z[0]=='+' ) z++;
fromTkt = 1;
blob_append_sql(&sql2, ",\"%w\"", z);
blob_append_sql(&sql3, ",\"%w\"", z);
}
}
if( fromTkt ){
db_prepare(&q, "INSERT INTO ticketchng(tkt_id,tkt_mtime%s)"
"SELECT %d,:mtime%s FROM ticket WHERE tkt_id=%d",
blob_sql_text(&sql2), tktid,
blob_sql_text(&sql3), tktid);
}else{
db_prepare(&q, "INSERT INTO ticketchng(tkt_id,tkt_mtime%s)"
"VALUES(%d,:mtime%s)",
blob_sql_text(&sql2), tktid, blob_sql_text(&sql3));
}
db_bind_double(&q, ":mtime", p->rDate);
db_step(&q);
db_finalize(&q);
}
blob_reset(&sql2);
blob_reset(&sql3);
fossil_free(aUsed);
return tktid;
}
/*
** Returns non-zero if moderation is required for ticket changes and ticket
** attachments.
*/
int ticket_need_moderation(
int localUser /* Are we being called for a local interactive user? */
){
/*
** If the FOSSIL_FORCE_TICKET_MODERATION variable is set, *ALL* changes for
** tickets will be required to go through moderation (even those performed
** by the local interactive user via the command line). This can be useful
** for local (or remote) testing of the moderation subsystem and its impact
** on the contents and status of tickets.
*/
if( fossil_getenv("FOSSIL_FORCE_TICKET_MODERATION")!=0 ){
return 1;
}
if( localUser ){
return 0;
}
return g.perm.ModTkt==0 && db_get_boolean("modreq-tkt",0)==1;
}
/*
** Rebuild an entire entry in the TICKET table
*/
void ticket_rebuild_entry(const char *zTktUuid){
char *zTag = mprintf("tkt-%s", zTktUuid);
int tagid = tag_findid(zTag, 1);
Stmt q;
Manifest *pTicket;
int tktid;
int createFlag = 1;
fossil_free(zTag);
getAllTicketFields();
if( haveTicket==0 ) return;
tktid = db_int(0, "SELECT tkt_id FROM ticket WHERE tkt_uuid=%Q", zTktUuid);
search_doc_touch('t', tktid, 0);
if( haveTicketChng ){
db_multi_exec("DELETE FROM ticketchng WHERE tkt_id=%d;", tktid);
}
db_multi_exec("DELETE FROM ticket WHERE tkt_id=%d", tktid);
tktid = 0;
db_prepare(&q, "SELECT rid FROM tagxref WHERE tagid=%d ORDER BY mtime",tagid);
while( db_step(&q)==SQLITE_ROW ){
int rid = db_column_int(&q, 0);
pTicket = manifest_get(rid, CFTYPE_TICKET, 0);
if( pTicket ){
tktid = ticket_insert(pTicket, rid, tktid);
manifest_ticket_event(rid, pTicket, createFlag, tagid);
manifest_destroy(pTicket);
}
createFlag = 0;
}
db_finalize(&q);
}
/*
** Create the TH1 interpreter and load the "common" code.
*/
void ticket_init(void){
const char *zConfig;
Th_FossilInit(TH_INIT_DEFAULT);
zConfig = ticket_common_code();
Th_Eval(g.interp, 0, zConfig, -1);
}
/*
** Create the TH1 interpreter and load the "change" code.
*/
int ticket_change(const char *zUuid){
const char *zConfig;
Th_FossilInit(TH_INIT_DEFAULT);
Th_Store("uuid", zUuid);
zConfig = ticket_change_code();
return Th_Eval(g.interp, 0, zConfig, -1);
}
/*
** Recreate the TICKET and TICKETCHNG tables.
*/
void ticket_create_table(int separateConnection){
const char *zSql;
db_multi_exec(
"DROP TABLE IF EXISTS ticket;"
"DROP TABLE IF EXISTS ticketchng;"
);
zSql = ticket_table_schema();
if( separateConnection ){
if( db_transaction_nesting_depth() ) db_end_transaction(0);
db_init_database(g.zRepositoryName, zSql, 0);
}else{
db_multi_exec("%s", zSql/*safe-for-%s*/);
}
}
/*
** Repopulate the TICKET and TICKETCHNG tables from scratch using all
** available ticket artifacts.
*/
void ticket_rebuild(void){
Stmt q;
ticket_create_table(1);
db_begin_transaction();
db_prepare(&q,"SELECT tagname FROM tag WHERE tagname GLOB 'tkt-*'");
while( db_step(&q)==SQLITE_ROW ){
const char *zName = db_column_text(&q, 0);
int len;
zName += 4;
len = strlen(zName);
if( len<20 || !validate16(zName, len) ) continue;
ticket_rebuild_entry(zName);
}
db_finalize(&q);
db_end_transaction(0);
}
/*
** COMMAND: test-ticket-rebuild
**
** Usage: %fossil test-ticket-rebuild TICKETID|all
**
** Rebuild the TICKET and TICKETCHNG tables for the given ticket ID
** or for ALL.
*/
void test_ticket_rebuild(void){
db_find_and_open_repository(0, 0);
if( g.argc!=3 ) usage("TICKETID|all");
if( fossil_strcmp(g.argv[2], "all")==0 ){
ticket_rebuild();
}else{
const char *zUuid;
zUuid = db_text(0, "SELECT substr(tagname,5) FROM tag"
" WHERE tagname GLOB 'tkt-%q*'", g.argv[2]);
if( zUuid==0 ) fossil_fatal("no such ticket: %s", g.argv[2]);
ticket_rebuild_entry(zUuid);
}
}
/*
** For trouble-shooting purposes, render a dump of the aField[] table to
** the webpage currently under construction.
*/
static void showAllFields(void){
int i;
@ <div style="color:blue">
@ <p>Database fields:</p><ul>
for(i=0; i<nField; i++){
@ <li>aField[%d(i)].zName = "%h(aField[i].zName)";
@ originally = "%h(aField[i].zValue)";
@ currently = "%h(PD(aField[i].zName,""))";
if( aField[i].zAppend ){
@ zAppend = "%h(aField[i].zAppend)";
}
@ mUsed = %d(aField[i].mUsed);
}
@ </ul></div>
}
/*
** WEBPAGE: tktview
** URL: tktview?name=UUID
**
** View a ticket identified by the name= query parameter.
*/
void tktview_page(void){
const char *zScript;
char *zFullName;
const char *zUuid = PD("name","");
login_check_credentials();
if( !g.perm.RdTkt ){ login_needed(g.anon.RdTkt); return; }
if( g.anon.WrTkt || g.anon.ApndTkt ){
style_submenu_element("Edit", "%s/tktedit?name=%T", g.zTop, PD("name",""));
}
if( g.perm.Hyperlink ){
style_submenu_element("History", "%s/tkthistory/%T", g.zTop, zUuid);
style_submenu_element("Timeline", "%s/tkttimeline/%T", g.zTop, zUuid);
style_submenu_element("Check-ins", "%s/tkttimeline/%T?y=ci", g.zTop, zUuid);
}
if( g.anon.NewTkt ){
style_submenu_element("New Ticket", "%s/tktnew", g.zTop);
}
if( g.anon.ApndTkt && g.anon.Attach ){
style_submenu_element("Attach", "%s/attachadd?tkt=%T&from=%s/tktview/%t",
g.zTop, zUuid, g.zTop, zUuid);
}
if( P("plaintext") ){
style_submenu_element("Formatted", "%R/tktview/%s", zUuid);
}else{
style_submenu_element("Plaintext", "%R/tktview/%s?plaintext", zUuid);
}
style_header("View Ticket");
if( g.thTrace ) Th_Trace("BEGIN_TKTVIEW<br />\n", -1);
ticket_init();
initializeVariablesFromCGI();
getAllTicketFields();
initializeVariablesFromDb();
zScript = ticket_viewpage_code();
if( P("showfields")!=0 ) showAllFields();
if( g.thTrace ) Th_Trace("BEGIN_TKTVIEW_SCRIPT<br />\n", -1);
Th_Render(zScript);
if( g.thTrace ) Th_Trace("END_TKTVIEW<br />\n", -1);
zFullName = db_text(0,
"SELECT tkt_uuid FROM ticket"
" WHERE tkt_uuid GLOB '%q*'", zUuid);
if( zFullName ){
attachment_list(zFullName, "<hr /><h2>Attachments:</h2><ul>");
}
style_footer();
}
/*
** TH1 command: append_field FIELD STRING
**
** FIELD is the name of a database column to which we might want
** to append text. STRING is the text to be appended to that
** column. The append does not actually occur until the
** submit_ticket command is run.
*/
static int appendRemarkCmd(
Th_Interp *interp,
void *p,
int argc,
const char **argv,
int *argl
){
int idx;
if( argc!=3 ){
return Th_WrongNumArgs(interp, "append_field FIELD STRING");
}
if( g.thTrace ){
Th_Trace("append_field %#h {%#h}<br />\n",
argl[1], argv[1], argl[2], argv[2]);
}
for(idx=0; idx<nField; idx++){
if( memcmp(aField[idx].zName, argv[1], argl[1])==0
&& aField[idx].zName[argl[1]]==0 ){
break;
}
}
if( idx>=nField ){
Th_ErrorMessage(g.interp, "no such TICKET column: ", argv[1], argl[1]);
return TH_ERROR;
}
aField[idx].zAppend = mprintf("%.*s", argl[2], argv[2]);
return TH_OK;
}
/*
** Write a ticket into the repository.
*/
static int ticket_put(
Blob *pTicket, /* The text of the ticket change record */
const char *zTktId, /* The ticket to which this change is applied */
int needMod /* True if moderation is needed */
){
int result;
int rid;
manifest_crosslink_begin();
rid = content_put_ex(pTicket, 0, 0, 0, needMod);
if( rid==0 ){
fossil_fatal("trouble committing ticket: %s", g.zErrMsg);
}
if( needMod ){
moderation_table_create();
db_multi_exec(
"INSERT INTO modreq(objid, tktid) VALUES(%d,%Q)",
rid, zTktId
);
}else{
db_multi_exec("INSERT OR IGNORE INTO unsent VALUES(%d);", rid);
db_multi_exec("INSERT OR IGNORE INTO unclustered VALUES(%d);", rid);
}
result = (manifest_crosslink(rid, pTicket, MC_NONE)==0);
assert( blob_is_reset(pTicket) );
if( !result ){
result = manifest_crosslink_end(MC_PERMIT_HOOKS);
}else{
manifest_crosslink_end(MC_NONE);
}
return result;
}
/*
** Subscript command: submit_ticket
**
** Construct and submit a new ticket artifact. The fields of the artifact
** are the names of the columns in the TICKET table. The content is
** taken from TH variables. If the content is unchanged, the field is
** omitted from the artifact. Fields whose names begin with "private_"
** are concealed using the db_conceal() function.
*/
static int submitTicketCmd(
Th_Interp *interp,
void *pUuid,
int argc,
const char **argv,
int *argl
){
char *zDate;
const char *zUuid;
int i;
int nJ = 0;
Blob tktchng, cksum;
int needMod;
login_verify_csrf_secret();
if( !captcha_is_correct(0) ){
@ <p class="generalError">Error: Incorrect security code.</p>
return TH_OK;
}
zUuid = (const char *)pUuid;
blob_zero(&tktchng);
zDate = date_in_standard_format("now");
blob_appendf(&tktchng, "D %s\n", zDate);
free(zDate);
for(i=0; i<nField; i++){
if( aField[i].zAppend ){
blob_appendf(&tktchng, "J +%s %z\n", aField[i].zName,
fossilize(aField[i].zAppend, -1));
++nJ;
}
}
for(i=0; i<nField; i++){
const char *zValue;
int nValue;
if( aField[i].zAppend ) continue;
zValue = Th_Fetch(aField[i].zName, &nValue);
if( zValue ){
while( nValue>0 && fossil_isspace(zValue[nValue-1]) ){ nValue--; }
if( ((aField[i].mUsed & USEDBY_TICKETCHNG)!=0 && nValue>0)
|| memcmp(zValue, aField[i].zValue, nValue)!=0
|| strlen(aField[i].zValue)!=nValue
){
if( memcmp(aField[i].zName, "private_", 8)==0 ){
zValue = db_conceal(zValue, nValue);
blob_appendf(&tktchng, "J %s %s\n", aField[i].zName, zValue);
}else{
blob_appendf(&tktchng, "J %s %#F\n", aField[i].zName, nValue, zValue);
}
nJ++;
}
}
}
if( *(char**)pUuid ){
zUuid = db_text(0,
"SELECT tkt_uuid FROM ticket WHERE tkt_uuid GLOB '%q*'", P("name")
);
}else{
zUuid = db_text(0, "SELECT lower(hex(randomblob(20)))");
}
*(const char**)pUuid = zUuid;
blob_appendf(&tktchng, "K %s\n", zUuid);
blob_appendf(&tktchng, "U %F\n", login_name());
md5sum_blob(&tktchng, &cksum);
blob_appendf(&tktchng, "Z %b\n", &cksum);
if( nJ==0 ){
blob_reset(&tktchng);
return TH_OK;
}
needMod = ticket_need_moderation(0);
if( g.zPath[0]=='d' ){
const char *zNeedMod = needMod ? "required" : "skipped";
/* If called from /debug_tktnew or /debug_tktedit... */
@ <div style="color:blue">
@ <p>Ticket artifact that would have been submitted:</p>
@ <blockquote><pre>%h(blob_str(&tktchng))</pre></blockquote>
@ <blockquote><pre>Moderation would be %h(zNeedMod).</pre></blockquote>
@ </div>
@ <hr />
return TH_OK;
}else{
if( g.thTrace ){
Th_Trace("submit_ticket {\n<blockquote><pre>\n%h\n</pre></blockquote>\n"
"}<br />\n",
blob_str(&tktchng));
}
ticket_put(&tktchng, zUuid, needMod);
}
return ticket_change(zUuid);
}
/*
** WEBPAGE: tktnew
** WEBPAGE: debug_tktnew
**
** Enter a new ticket. The tktnew_template script in the ticket
** configuration is used. The /tktnew page is the official ticket
** entry page. The /debug_tktnew page is used for debugging the
** tktnew_template in the ticket configuration. /debug_tktnew works
** just like /tktnew except that it does not really save the new ticket
** when you press submit - it just prints the ticket artifact at the
** top of the screen.
*/
void tktnew_page(void){
const char *zScript;
char *zNewUuid = 0;
login_check_credentials();
if( !g.perm.NewTkt ){ login_needed(g.anon.NewTkt); return; }
if( P("cancel") ){
cgi_redirect("home");
}
style_header("New Ticket");
ticket_standard_submenu(T_ALL_BUT(T_NEW));
if( g.thTrace ) Th_Trace("BEGIN_TKTNEW<br />\n", -1);
ticket_init();
initializeVariablesFromCGI();
getAllTicketFields();
initializeVariablesFromDb();
if( g.zPath[0]=='d' ) showAllFields();
form_begin(0, "%R/%s", g.zPath);
login_insert_csrf_secret();
if( P("date_override") && g.perm.Setup ){
@ <input type="hidden" name="date_override" value="%h(P("date_override"))">
}
zScript = ticket_newpage_code();
Th_Store("login", login_name());
Th_Store("date", db_text(0, "SELECT datetime('now')"));
Th_CreateCommand(g.interp, "submit_ticket", submitTicketCmd,
(void*)&zNewUuid, 0);
if( g.thTrace ) Th_Trace("BEGIN_TKTNEW_SCRIPT<br />\n", -1);
if( Th_Render(zScript)==TH_RETURN && !g.thTrace && zNewUuid ){
cgi_redirect(mprintf("%s/tktview/%s", g.zTop, zNewUuid));
return;
}
captcha_generate(0);
@ </form>
if( g.thTrace ) Th_Trace("END_TKTVIEW<br />\n", -1);
style_footer();
}
/*
** WEBPAGE: tktedit
** WEBPAGE: debug_tktedit
**
** Edit a ticket. The ticket is identified by the name CGI parameter.
** /tktedit is the official page. The /debug_tktedit page does the same
** thing except that it does not save the ticket change record when you
** press submit - it instead prints the ticket change record at the top
** of the page. The /debug_tktedit page is intended to be used when
** debugging ticket configurations.
*/
void tktedit_page(void){
const char *zScript;
int nName;
const char *zName;
int nRec;
login_check_credentials();
if( !g.perm.ApndTkt && !g.perm.WrTkt ){
login_needed(g.anon.ApndTkt || g.anon.WrTkt);
return;
}
zName = P("name");
if( P("cancel") ){
cgi_redirectf("tktview?name=%T", zName);
}
style_header("Edit Ticket");
if( zName==0 || (nName = strlen(zName))<4 || nName>HNAME_LEN_SHA1
|| !validate16(zName,nName) ){
@ <span class="tktError">Not a valid ticket id: "%h(zName)"</span>
style_footer();
return;
}
nRec = db_int(0, "SELECT count(*) FROM ticket WHERE tkt_uuid GLOB '%q*'",
zName);
if( nRec==0 ){
@ <span class="tktError">No such ticket: "%h(zName)"</span>
style_footer();
return;
}
if( nRec>1 ){
@ <span class="tktError">%d(nRec) tickets begin with:
@ "%h(zName)"</span>
style_footer();
return;
}
if( g.thTrace ) Th_Trace("BEGIN_TKTEDIT<br />\n", -1);
ticket_init();
getAllTicketFields();
initializeVariablesFromCGI();
initializeVariablesFromDb();
if( g.zPath[0]=='d' ) showAllFields();
form_begin(0, "%R/%s", g.zPath);
@ <input type="hidden" name="name" value="%s(zName)" />
login_insert_csrf_secret();
zScript = ticket_editpage_code();
Th_Store("login", login_name());
Th_Store("date", db_text(0, "SELECT datetime('now')"));
Th_CreateCommand(g.interp, "append_field", appendRemarkCmd, 0, 0);
Th_CreateCommand(g.interp, "submit_ticket", submitTicketCmd, (void*)&zName,0);
if( g.thTrace ) Th_Trace("BEGIN_TKTEDIT_SCRIPT<br />\n", -1);
if( Th_Render(zScript)==TH_RETURN && !g.thTrace && zName ){
cgi_redirect(mprintf("%s/tktview/%s", g.zTop, zName));
return;
}
captcha_generate(0);
@ </form>
if( g.thTrace ) Th_Trace("BEGIN_TKTEDIT<br />\n", -1);
style_footer();
}
/*
** Check the ticket table schema in zSchema to see if it appears to
** be well-formed. If everything is OK, return NULL. If something is
** amiss, then return a pointer to a string (obtained from malloc) that
** describes the problem.
*/
char *ticket_schema_check(const char *zSchema){
char *zErr = 0;
int rc;
sqlite3 *db;
rc = sqlite3_open(":memory:", &db);
if( rc==SQLITE_OK ){
rc = sqlite3_exec(db, zSchema, 0, 0, &zErr);
if( rc!=SQLITE_OK ){
sqlite3_close(db);
return zErr;
}
rc = sqlite3_exec(db, "SELECT tkt_id, tkt_uuid, tkt_mtime FROM ticket",
0, 0, 0);
if( rc!=SQLITE_OK ){
zErr = mprintf("schema fails to define valid a TICKET "
"table containing all required fields");
}else{
rc = sqlite3_exec(db, "SELECT tkt_id, tkt_mtime FROM ticketchng", 0,0,0);
if( rc!=SQLITE_OK ){
zErr = mprintf("schema fails to define valid a TICKETCHNG "
"table containing all required fields");
}
}
sqlite3_close(db);
}
return zErr;
}
/*
** WEBPAGE: tkttimeline
** URL: /tkttimeline?name=TICKETUUID&y=TYPE
**
** Show the change history for a single ticket in timeline format.
*/
void tkttimeline_page(void){
Stmt q;
char *zTitle;
char *zSQL;
const char *zUuid;
char *zFullUuid;
int tagid;
char zGlobPattern[50];
const char *zType;
login_check_credentials();
if( !g.perm.Hyperlink || !g.perm.RdTkt ){
login_needed(g.anon.Hyperlink && g.anon.RdTkt);
return;
}
zUuid = PD("name","");
zType = PD("y","a");
if( zType[0]!='c' ){
style_submenu_element("Check-ins", "%s/tkttimeline?name=%T&y=ci",
g.zTop, zUuid);
}else{
style_submenu_element("Timeline", "%s/tkttimeline?name=%T", g.zTop, zUuid);
}
style_submenu_element("History", "%s/tkthistory/%s", g.zTop, zUuid);
style_submenu_element("Status", "%s/info/%s", g.zTop, zUuid);
if( zType[0]=='c' ){
zTitle = mprintf("Check-ins Associated With Ticket %h", zUuid);
}else{
zTitle = mprintf("Timeline Of Ticket %h", zUuid);
}
style_header("%z", zTitle);
sqlite3_snprintf(6, zGlobPattern, "%s", zUuid);
canonical16(zGlobPattern, strlen(zGlobPattern));
tagid = db_int(0, "SELECT tagid FROM tag WHERE tagname GLOB 'tkt-%q*'",zUuid);
if( tagid==0 ){
@ No such ticket: %h(zUuid)
style_footer();
return;
}
zFullUuid = db_text(0, "SELECT substr(tagname, 5) FROM tag WHERE tagid=%d",
tagid);
if( zType[0]=='c' ){
zSQL = mprintf(
"%s AND event.objid IN "
" (SELECT srcid FROM backlink WHERE target GLOB '%.4s*' "
"AND '%s' GLOB (target||'*')) "
"ORDER BY mtime DESC",
timeline_query_for_www(), zFullUuid, zFullUuid
);
}else{
zSQL = mprintf(
"%s AND event.objid IN "
" (SELECT rid FROM tagxref WHERE tagid=%d"
" UNION SELECT srcid FROM backlink"
" WHERE target GLOB '%.4s*'"
" AND '%s' GLOB (target||'*')"
" UNION SELECT attachid FROM attachment"
" WHERE target=%Q) "
"ORDER BY mtime DESC",
timeline_query_for_www(), tagid, zFullUuid, zFullUuid, zFullUuid
);
}
db_prepare(&q, "%z", zSQL/*safe-for-%s*/);
www_print_timeline(&q, TIMELINE_ARTID|TIMELINE_DISJOINT|TIMELINE_GRAPH,
0, 0, 0, 0);
db_finalize(&q);
style_footer();
}
/*
** WEBPAGE: tkthistory
** URL: /tkthistory?name=TICKETUUID
**
** Show the complete change history for a single ticket
*/
void tkthistory_page(void){
Stmt q;
char *zTitle;
const char *zUuid;
int tagid;
int nChng = 0;
login_check_credentials();
if( !g.perm.Hyperlink || !g.perm.RdTkt ){
login_needed(g.anon.Hyperlink && g.anon.RdTkt);
return;
}
zUuid = PD("name","");
zTitle = mprintf("History Of Ticket %h", zUuid);
style_submenu_element("Status", "%s/info/%s", g.zTop, zUuid);
style_submenu_element("Check-ins", "%s/tkttimeline?name=%s&y=ci",
g.zTop, zUuid);
style_submenu_element("Timeline", "%s/tkttimeline?name=%s", g.zTop, zUuid);
if( P("plaintext")!=0 ){
style_submenu_element("Formatted", "%R/tkthistory/%s", zUuid);
}else{
style_submenu_element("Plaintext", "%R/tkthistory/%s?plaintext", zUuid);
}
style_header("%z", zTitle);
tagid = db_int(0, "SELECT tagid FROM tag WHERE tagname GLOB 'tkt-%q*'",zUuid);
if( tagid==0 ){
@ No such ticket: %h(zUuid)
style_footer();
return;
}
db_prepare(&q,
"SELECT datetime(mtime,toLocal()), objid, uuid, NULL, NULL, NULL"
" FROM event, blob"
" WHERE objid IN (SELECT rid FROM tagxref WHERE tagid=%d)"
" AND blob.rid=event.objid"
" UNION "
"SELECT datetime(mtime,toLocal()), attachid, uuid, src, filename, user"
" FROM attachment, blob"
" WHERE target=(SELECT substr(tagname,5) FROM tag WHERE tagid=%d)"
" AND blob.rid=attachid"
" ORDER BY 1",
tagid, tagid
);
while( db_step(&q)==SQLITE_ROW ){
Manifest *pTicket;
const char *zDate = db_column_text(&q, 0);
int rid = db_column_int(&q, 1);
const char *zChngUuid = db_column_text(&q, 2);
const char *zFile = db_column_text(&q, 4);
if( nChng==0 ){
@ <ol>
}
nChng++;
if( zFile!=0 ){
const char *zSrc = db_column_text(&q, 3);
const char *zUser = db_column_text(&q, 5);
if( zSrc==0 || zSrc[0]==0 ){
@
@ <li><p>Delete attachment "%h(zFile)"
}else{
@
@ <li><p>Add attachment
@ "%z(href("%R/artifact/%!S",zSrc))%s(zFile)</a>"
}
@ [%z(href("%R/artifact/%!S",zChngUuid))%S(zChngUuid)</a>]
@ (rid %d(rid)) by
hyperlink_to_user(zUser,zDate," on");
hyperlink_to_date(zDate, ".</p>");
}else{
pTicket = manifest_get(rid, CFTYPE_TICKET, 0);
if( pTicket ){
@
@ <li><p>Ticket change
@ [%z(href("%R/artifact/%!S",zChngUuid))%S(zChngUuid)</a>]
@ (rid %d(rid)) by
hyperlink_to_user(pTicket->zUser,zDate," on");
hyperlink_to_date(zDate, ":");
@ </p>
ticket_output_change_artifact(pTicket, "a");
}
manifest_destroy(pTicket);
}
}
db_finalize(&q);
if( nChng ){
@ </ol>
}
style_footer();
}
/*
** Return TRUE if the given BLOB contains a newline character.
*/
static int contains_newline(Blob *p){
const char *z = blob_str(p);
while( *z ){
if( *z=='\n' ) return 1;
z++;
}
return 0;
}
/*
** The pTkt object is a ticket change artifact. Output a detailed
** description of this object.
*/
void ticket_output_change_artifact(Manifest *pTkt, const char *zListType){
int i;
int wikiFlags = WIKI_NOBADLINKS;
const char *zBlock = "<blockquote>";
const char *zEnd = "</blockquote>";
if( P("plaintext")!=0 ){
wikiFlags |= WIKI_LINKSONLY;
zBlock = "<blockquote><pre class='verbatim'>";
zEnd = "</pre></blockquote>";
}
if( zListType==0 ) zListType = "1";
@ <ol type="%s(zListType)">
for(i=0; i<pTkt->nField; i++){
Blob val;
const char *z;
z = pTkt->aField[i].zName;
blob_set(&val, pTkt->aField[i].zValue);
if( z[0]=='+' ){
@ <li>Appended to %h(&z[1]):%s(zBlock)
wiki_convert(&val, 0, wikiFlags);
@ %s(zEnd)</li>
}else if( blob_size(&val)>50 || contains_newline(&val) ){
@ <li>Change %h(z) to:%s(zBlock)
wiki_convert(&val, 0, wikiFlags);
@ %s(zEnd)</li>
}else{
@ <li>Change %h(z) to "%h(blob_str(&val))"</li>
}
blob_reset(&val);
}
@ </ol>
}
/*
** COMMAND: ticket*
**
** Usage: %fossil ticket SUBCOMMAND ...
**
** Run various subcommands to control tickets
**
** %fossil ticket show (REPORTTITLE|REPORTNR) ?TICKETFILTER? ?OPTIONS?
**
** Options:
** -l|--limit LIMITCHAR
** -q|--quote
** -R|--repository FILE
**
** Run the ticket report, identified by the report format title
** used in the GUI. The data is written as flat file on stdout,
** using TAB as separator. The separator can be changed using
** the -l or --limit option.
**
** If TICKETFILTER is given on the commandline, the query is
** limited with a new WHERE-condition.
** example: Report lists a column # with the uuid
** TICKETFILTER may be [#]='uuuuuuuuu'
** example: Report only lists rows with status not open
** TICKETFILTER: status != 'open'
**
** If --quote is used, the tickets are encoded by quoting special
** chars (space -> \\s, tab -> \\t, newline -> \\n, cr -> \\r,
** formfeed -> \\f, vtab -> \\v, nul -> \\0, \\ -> \\\\).
** Otherwise, the simplified encoding as on the show report raw page
** in the GUI is used. This has no effect in JSON mode.
**
** Instead of the report title it's possible to use the report
** number; the special report number 0 lists all columns defined in
** the ticket table.
**
** %fossil ticket list fields
** %fossil ticket ls fields
**
** List all fields defined for ticket in the fossil repository.
**
** %fossil ticket list reports
** %fossil ticket ls reports
**
** List all ticket reports defined in the fossil repository.
**
** %fossil ticket set TICKETUUID (FIELD VALUE)+ ?-q|--quote?
** %fossil ticket change TICKETUUID (FIELD VALUE)+ ?-q|--quote?
**
** Change ticket identified by TICKETUUID to set the values of
** each field FIELD to VALUE.
**
** Field names as defined in the TICKET table. By default, these
** names include: type, status, subsystem, priority, severity, foundin,
** resolution, title, and comment, but other field names can be added
** or substituted in customized installations.
**
** If you use +FIELD, the VALUE is appended to the field FIELD. You
** can use more than one field/value pair on the commandline. Using
** --quote enables the special character decoding as in "ticket
** show", which allows setting multiline text or text with special
** characters.
**
** %fossil ticket add FIELD VALUE ?FIELD VALUE .. ? ?-q|--quote?
**
** Like set, but create a new ticket with the given values.
**
** %fossil ticket history TICKETUUID
**
** Show the complete change history for the ticket
**
** Note that the values in set|add are not validated against the
** definitions given in "Ticket Common Script".
*/
void ticket_cmd(void){
int n;
const char *zUser;
const char *zDate;
const char *zTktUuid;
/* do some ints, we want to be inside a checkout */
db_find_and_open_repository(0, 0);
user_select();
zUser = find_option("user-override",0,1);
if( zUser==0 ) zUser = login_name();
zDate = find_option("date-override",0,1);
if( zDate==0 ) zDate = "now";
zDate = date_in_standard_format(zDate);
zTktUuid = find_option("uuid-override",0,1);
if( zTktUuid && (strlen(zTktUuid)!=40 || !validate16(zTktUuid,40)) ){
fossil_fatal("invalid --uuid-override: must be 40 characters of hex");
}
/*
** Check that the user exists.
*/
if( !db_exists("SELECT 1 FROM user WHERE login=%Q", zUser) ){
fossil_fatal("no such user: %s", zUser);
}
if( g.argc<3 ){
usage("add|change|list|set|show|history");
}
n = strlen(g.argv[2]);
if( n==1 && g.argv[2][0]=='s' ){
/* set/show cannot be distinguished, so show the usage */
usage("add|change|list|set|show|history");
}
if(( strncmp(g.argv[2],"list",n)==0 ) || ( strncmp(g.argv[2],"ls",n)==0 )){
if( g.argc==3 ){
usage("list fields|reports");
}else{
n = strlen(g.argv[3]);
if( !strncmp(g.argv[3],"fields",n) ){
/* simply show all field names */
int i;
/* read all available ticket fields */
getAllTicketFields();
for(i=0; i<nField; i++){
printf("%s\n",aField[i].zName);
}
}else if( !strncmp(g.argv[3],"reports",n) ){
rpt_list_reports();
}else{
fossil_fatal("unknown ticket list option '%s'!",g.argv[3]);
}
}
}else{
/* add a new ticket or set fields on existing tickets */
tTktShowEncoding tktEncoding;
tktEncoding = find_option("quote","q",0) ? tktFossilize : tktNoTab;
if( strncmp(g.argv[2],"show",n)==0 ){
if( g.argc==3 ){
usage("show REPORTNR");
}else{
const char *zRep = 0;
const char *zSep = 0;
const char *zFilterUuid = 0;
zSep = find_option("limit","l",1);
zRep = g.argv[3];
if( !strcmp(zRep,"0") ){
zRep = 0;
}
if( g.argc>4 ){
zFilterUuid = g.argv[4];
}
rptshow( zRep, zSep, zFilterUuid, tktEncoding );
}
}else{
/* add a new ticket or update an existing ticket */
enum { set,add,history,err } eCmd = err;
int i = 0;
Blob tktchng, cksum;
/* get command type (set/add) and get uuid, if needed for set */
if( strncmp(g.argv[2],"set",n)==0 || strncmp(g.argv[2],"change",n)==0 ||
strncmp(g.argv[2],"history",n)==0 ){
if( strncmp(g.argv[2],"history",n)==0 ){
eCmd = history;
}else{
eCmd = set;
}
if( g.argc==3 ){
usage("set|change|history TICKETUUID");
}
zTktUuid = db_text(0,
"SELECT tkt_uuid FROM ticket WHERE tkt_uuid GLOB '%q*'", g.argv[3]
);
if( !zTktUuid ){
fossil_fatal("unknown ticket: '%s'!",g.argv[3]);
}
i=4;
}else if( strncmp(g.argv[2],"add",n)==0 ){
eCmd = add;
i = 3;
if( zTktUuid==0 ){
zTktUuid = db_text(0, "SELECT lower(hex(randomblob(20)))");
}
}
/* none of set/add, so show the usage! */
if( eCmd==err ){
usage("add|fieldlist|set|show|history");
}
/* we just handle history separately here, does not get out */
if( eCmd==history ){
Stmt q;
int tagid;
if( i != g.argc ){
fossil_fatal("no other parameters expected to %s!",g.argv[2]);
}
tagid = db_int(0, "SELECT tagid FROM tag WHERE tagname GLOB 'tkt-%q*'",
zTktUuid);
if( tagid==0 ){
fossil_fatal("no such ticket %h", zTktUuid);
}
db_prepare(&q,
"SELECT datetime(mtime,toLocal()), objid, NULL, NULL, NULL"
" FROM event, blob"
" WHERE objid IN (SELECT rid FROM tagxref WHERE tagid=%d)"
" AND blob.rid=event.objid"
" UNION "
"SELECT datetime(mtime,toLocal()), attachid, filename, "
" src, user"
" FROM attachment, blob"
" WHERE target=(SELECT substr(tagname,5) FROM tag WHERE tagid=%d)"
" AND blob.rid=attachid"
" ORDER BY 1 DESC",
tagid, tagid
);
while( db_step(&q)==SQLITE_ROW ){
Manifest *pTicket;
const char *zDate = db_column_text(&q, 0);
int rid = db_column_int(&q, 1);
const char *zFile = db_column_text(&q, 2);
if( zFile!=0 ){
const char *zSrc = db_column_text(&q, 3);
const char *zUser = db_column_text(&q, 4);
if( zSrc==0 || zSrc[0]==0 ){
fossil_print("Delete attachment %s\n", zFile);
}else{
fossil_print("Add attachment %s\n", zFile);
}
fossil_print(" by %s on %s\n", zUser, zDate);
}else{
pTicket = manifest_get(rid, CFTYPE_TICKET, 0);
if( pTicket ){
int i;
fossil_print("Ticket Change by %s on %s:\n",
pTicket->zUser, zDate);
for(i=0; i<pTicket->nField; i++){
Blob val;
const char *z;
z = pTicket->aField[i].zName;
blob_set(&val, pTicket->aField[i].zValue);
if( z[0]=='+' ){
fossil_print(" Append to ");
z++;
}else{
fossil_print(" Change ");
}
fossil_print("%h: ",z);
if( blob_size(&val)>50 || contains_newline(&val)) {
fossil_print("\n ");
comment_print(blob_str(&val),0,4,-1,get_comment_format());
}else{
fossil_print("%s\n",blob_str(&val));
}
blob_reset(&val);
}
}
manifest_destroy(pTicket);
}
}
db_finalize(&q);
return;
}
/* read all given ticket field/value pairs from command line */
if( i==g.argc ){
fossil_fatal("empty %s command aborted!",g.argv[2]);
}
getAllTicketFields();
/* read commandline and assign fields in the aField[].zValue array */
while( i<g.argc ){
char *zFName;
char *zFValue;
int j;
int append = 0;
zFName = g.argv[i++];
if( i==g.argc ){
fossil_fatal("missing value for '%s'!",zFName);
}
zFValue = g.argv[i++];
if( tktEncoding == tktFossilize ){
zFValue=mprintf("%s",zFValue);
defossilize(zFValue);
}
append = (zFName[0] == '+');
if( append ){
zFName++;
}
j = fieldId(zFName);
if( j == -1 ){
fossil_fatal("unknown field name '%s'!",zFName);
}else{
if( append ){
aField[j].zAppend = zFValue;
}else{
aField[j].zValue = zFValue;
}
}
}
/* now add the needed artifacts to the repository */
blob_zero(&tktchng);
/* add the time to the ticket manifest */
blob_appendf(&tktchng, "D %s\n", zDate);
/* append defined elements */
for(i=0; i<nField; i++){
char *zValue = 0;
char *zPfx;
if( aField[i].zAppend && aField[i].zAppend[0] ){
zPfx = " +";
zValue = aField[i].zAppend;
}else if( aField[i].zValue && aField[i].zValue[0] ){
zPfx = " ";
zValue = aField[i].zValue;
}else{
continue;
}
if( memcmp(aField[i].zName, "private_", 8)==0 ){
zValue = db_conceal(zValue, strlen(zValue));
blob_appendf(&tktchng, "J%s%s %s\n", zPfx, aField[i].zName, zValue);
}else{
blob_appendf(&tktchng, "J%s%s %#F\n", zPfx,
aField[i].zName, strlen(zValue), zValue);
}
}
blob_appendf(&tktchng, "K %s\n", zTktUuid);
blob_appendf(&tktchng, "U %F\n", zUser);
md5sum_blob(&tktchng, &cksum);
blob_appendf(&tktchng, "Z %b\n", &cksum);
if( ticket_put(&tktchng, zTktUuid, ticket_need_moderation(1))==0 ){
fossil_fatal("%s", g.zErrMsg);
}else{
fossil_print("ticket %s succeeded for %s\n",
(eCmd==set?"set":"add"),zTktUuid);
}
}
}
}
#if INTERFACE
/* Standard submenu items for wiki pages */
#define T_SRCH 0x00001
#define T_REPLIST 0x00002
#define T_NEW 0x00004
#define T_ALL 0x00007
#define T_ALL_BUT(x) (T_ALL&~(x))
#endif
/*
** Add some standard submenu elements for ticket screens.
*/
void ticket_standard_submenu(unsigned int ok){
if( (ok & T_SRCH)!=0 && search_restrict(SRCH_TKT)!=0 ){
style_submenu_element("Search", "%R/tktsrch");
}
if( (ok & T_REPLIST)!=0 ){
style_submenu_element("Reports", "%R/reportlist");
}
if( (ok & T_NEW)!=0 && g.anon.NewTkt ){
style_submenu_element("New", "%R/tktnew");
}
}
/*
** WEBPAGE: ticket
**
** This is intended to be the primary "Ticket" page. Render as
** either ticket-search (if search is enabled) or as the
** /reportlist page (if ticket search is disabled).
*/
void tkt_home_page(void){
login_check_credentials();
if( search_restrict(SRCH_TKT)!=0 ){
tkt_srchpage();
}else{
view_list();
}
}
/*
** WEBPAGE: tktsrch
** Usage: /tktsrch?s=PATTERN
**
** Full-text search of all current tickets
*/
void tkt_srchpage(void){
login_check_credentials();
style_header("Ticket Search");
ticket_standard_submenu(T_ALL_BUT(T_SRCH));
search_screen(SRCH_TKT, 0);
style_footer();
}
| 2.40625 | 2 |
2024-11-18T22:11:19.857733+00:00 | 2019-02-13T12:01:39 | 1fabf4b4e013bf50240985ad31ecc6705953012f | {
"blob_id": "1fabf4b4e013bf50240985ad31ecc6705953012f",
"branch_name": "refs/heads/master",
"committer_date": "2019-02-13T12:01:39",
"content_id": "28b26f941fa9eb7a28f2f8e0f0d043f7f7a36772",
"detected_licenses": [
"MIT"
],
"directory_id": "9b449a0dcd9cedc35971105a57a2e176f9c8bb5c",
"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": 170497946,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1107,
"license": "MIT",
"license_type": "permissive",
"path": "/src/sort/sort.c",
"provenance": "stackv2-0072.json.gz:46461",
"repo_name": "FlorianMarcon/PSU_my_ls",
"revision_date": "2019-02-13T12:01:39",
"revision_id": "141a115c4c860cf5bad4023f65bf1f298a375844",
"snapshot_id": "69a89791e18d71530f4ed988aa6103265be7201c",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/FlorianMarcon/PSU_my_ls/141a115c4c860cf5bad4023f65bf1f298a375844/src/sort/sort.c",
"visit_date": "2020-04-22T16:06:58.517548"
} | stackv2 | /*
** EPITECH PROJECT, 2017
** bootstrap my _ls
** File description:
** create list
*/
#include "my.h"
#include "header_LS.h"
#include <stdio.h>
int comparaison(linked_list_t *buffer, linked_list_t *list);
linked_list_t *search_greater(linked_list_t *list)
{
linked_list_t *buffer;
buffer = list;
list = list->next;
while (list != NULL){
if (comparaison(buffer, list) == 2)
buffer = list;
list = list->next;
}
return (buffer);
}
void stock_new_list(linked_list_t **listt, linked_list_t *new,
linked_list_t *buffer)
{
linked_list_t *list = *listt;
while (new->next != NULL)
new = new->next;
if (list == buffer) {
list = list->next;
buffer->next = NULL;
new->next = buffer;
*listt = list;
} else {
while (list->next != buffer)
list = list->next;
list->next = list->next->next;
new->next = buffer;
buffer->next = NULL;
}
}
linked_list_t *sort_list_alpha(linked_list_t *list)
{
linked_list_t *new = init_new_list(&list);
linked_list_t *buffer;
while (list != NULL) {
buffer = search_greater(list);
stock_new_list(&list, new, buffer);
}
return (new);
}
| 2.90625 | 3 |
2024-11-18T22:11:20.131113+00:00 | 2021-08-15T12:04:02 | 84ad46ee0321c501f867dff767900a54c1269d6d | {
"blob_id": "84ad46ee0321c501f867dff767900a54c1269d6d",
"branch_name": "refs/heads/main",
"committer_date": "2021-08-15T12:04:02",
"content_id": "3a4f6b391fea186db997bfb8b41339d2b00aaf97",
"detected_licenses": [
"MIT"
],
"directory_id": "eae74156f3172a176b5a667db44a02057a5d5f04",
"extension": "c",
"filename": "main.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 396334218,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2356,
"license": "MIT",
"license_type": "permissive",
"path": "/More Tiva Codes/DS3231 RTC Driver Development/main.c",
"provenance": "stackv2-0072.json.gz:46719",
"repo_name": "MUDAL/TM4C123-Codes",
"revision_date": "2021-08-15T12:04:02",
"revision_id": "f55fc15279ef59ee6dbf365e6078b6d681708078",
"snapshot_id": "094b057689f1a7b1793e14cf4c076fae551ea2c3",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/MUDAL/TM4C123-Codes/f55fc15279ef59ee6dbf365e6078b6d681708078/More Tiva Codes/DS3231 RTC Driver Development/main.c",
"visit_date": "2023-07-08T17:44:02.938471"
} | stackv2 | #include "TM4C123.h" // Device header
#include <stdint.h>
//DATE:: 06-02-2020
//Driver development for DS3231 Real-Time Clock Module
//I2C communication between the DS3231 module and the Tiva C microcontroller
//STEPS
//1.) I2C configuration
//2.) Register and Command Definitions
//INTERNAL REGISTER ADDRESSES
#define SLAVE_ADDRESS 0x68
#define SECONDS 0x00
#define MINUTES 0x01
#define HOURS 0x02
#define DAY 0x03
#define DATE 0x04
#define MONTH 0x05
#define YEAR 0x06
//I2C command sequences
#define READ_MODE 0x01
#define WRITE_MODE 0x00
#define START 0x03
#define STOP 0x04
void set_slaveAddress(uint16_t address, uint16_t mode);
void sendByte(uint16_t byte, uint16_t bus_condition);
void I2C_Init(void);
void testDelay(void);
int main(){
I2C_Init();
//REPEATED START condition
/*
1.) send START condition
2.) send slave address with RW = 0
3.) send internal register address
4.) send START sequence again
5.) send slave address with RW = 1
6.) Read data byte (read from the I2CMDR)
7.) send STOP condition
*/
//==========================================
while(1){
set_slaveAddress(SLAVE_ADDRESS,WRITE_MODE);
sendByte(MINUTES,START);
testDelay();
set_slaveAddress(SLAVE_ADDRESS,READ_MODE);
I2C0->MCS = START;
testDelay();
I2C0->MCS = STOP;
}
}
void I2C_Init(){
//SYSTEM CLOCK = 20MHz
SYSCTL->RCC &= ~0x7000000;
SYSCTL->RCC |= 0x4000000;
//=======================
SYSCTL->RCGCI2C |= 0x01;//clock for I2C0
SYSCTL->RCGCGPIO |= 0x02; //clock for port B
//PB2->SCL(don't configure as open drain) PB3->SDA (open drain)
GPIOB->AFSEL |= 0x0C; //alternate function for PB2 and PB3
GPIOB->ODR |= 0x08; //PB3 as open drain
GPIOB->DEN |= 0x0C; //digital function for PB2 and PB3
//GPIOB->PCTL |= 0x3300; //assign I2C signals to PB2 and PB3
I2C0->MCR = 0x10; //enable I2C0 Master mode
I2C0->MTPR = 0x09; //SCL clock speed = 100kbps
}
void set_slaveAddress(uint16_t address, uint16_t mode){
I2C0->MSA = (address << 1); //set slave address
I2C0->MSA |= (mode << 0);
}
void sendByte(uint16_t byte, uint16_t bus_condition){
I2C0->MDR = byte; //data or internal register address
while ((I2C0->MCS & 0x01) != 0){} //wait for BUSY bit to be 0
I2C0->MCS = bus_condition;
}
void testDelay(void){
for (int i = 0; i < 1000; i++){}
}
| 2.671875 | 3 |
2024-11-18T22:11:24.064481+00:00 | 2015-10-23T16:51:59 | 6aba6b7831a713c88ae1f09dfc64bc86f3c3db7f | {
"blob_id": "6aba6b7831a713c88ae1f09dfc64bc86f3c3db7f",
"branch_name": "refs/heads/master",
"committer_date": "2015-10-23T16:51:59",
"content_id": "cf4d14be8033253ac2a01f7df8e9e143f0a12d9a",
"detected_licenses": [
"MIT",
"BSD-3-Clause"
],
"directory_id": "711e468a2b511790820253283a989cc6884b9a35",
"extension": "c",
"filename": "notify_self.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 44825932,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 7416,
"license": "MIT,BSD-3-Clause",
"license_type": "permissive",
"path": "/src/libpfm-2.x/examples/notify_self.c",
"provenance": "stackv2-0072.json.gz:47363",
"repo_name": "tcreech/papi-4.0.0-64-solaris11.2",
"revision_date": "2015-10-23T16:51:59",
"revision_id": "b5e66422fb31bc4017b7728e16e4953f3c5ec9d7",
"snapshot_id": "0f54a73cff57c74d4eb59c859bf5fe730bc02086",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/tcreech/papi-4.0.0-64-solaris11.2/b5e66422fb31bc4017b7728e16e4953f3c5ec9d7/src/libpfm-2.x/examples/notify_self.c",
"visit_date": "2021-01-10T02:48:12.369160"
} | stackv2 | /*
* notify_self.c - example of how you can use overflow notifications
*
* Copyright (C) 2002 Hewlett-Packard Co
* Contributed by Stephane Eranian <[email protected]>
*
* 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.
*
* This file is part of libpfm, a performance monitoring support library for
* applications on Linux/ia64.
*/
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <errno.h>
#include <unistd.h>
#include <string.h>
#include <signal.h>
#include <perfmon/pfmlib.h>
#define SMPL_PERIOD 1000000000UL
/*
* This array cannot contain more than 2 events for
* this example
*/
#define N_EVENTS 2
static char *event_list[N_EVENTS]={
"cpu_cycles",
"IA64_INST_RETIRED",
};
static volatile int notification_received;
#define NUM_PMCS PMU_MAX_PMCS
#define NUM_PMDS PMU_MAX_PMDS
static pfarg_reg_t pd[NUM_PMDS];
static pfmlib_param_t evt;
/*
* infinite loop waiting for notification to get out
*/
void
busyloop(void)
{
/*
* busy loop to burn CPU cycles
*/
for(;notification_received < 3;) ;
}
static void fatal_error(char *fmt,...) __attribute__((noreturn));
static void
fatal_error(char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
vfprintf(stderr, fmt, ap);
va_end(ap);
exit(1);
}
static void
overflow_handler(int n, struct pfm_siginfo *info, struct sigcontext *sc)
{
unsigned long mask =info->sy_pfm_ovfl[0];
pfarg_reg_t pd[1];
/*
* Check to see if we received a spurious SIGPROF, i.e., one not
* generated by the perfmon subsystem.
*/
if (info->sy_code != PROF_OVFL) {
printf("Received spurious SIGPROF si_code=%d\n", info->sy_code);
return;
}
/*
* Each bit set in the overflow mask represents an overflowed counter.
*
* Here we check that the overflow was caused by our first counter.
*/
if ((mask & (1UL<< evt.pfp_pc[0].reg_num)) == 0) {
printf("Something is wrong, unexpected mask 0x%lx\n", mask);
exit(1);
}
/*
* Read the value of the second counter
*/
memset(pd, 0, sizeof(pd));
pd[0].reg_num = evt.pfp_pc[1].reg_num;
if (perfmonctl(getpid(), PFM_READ_PMDS, pd, 1) == -1) {
perror("PFM_READ_PMDS");
exit(1);
}
printf("Notification %d: %ld %s\n",
notification_received,
pd[0].reg_value,
event_list[1]);
/*
* At this point, the counter used for the sampling period has already
* be reset by the kernel because we are in non-blocking mode, self-monitoring.
*/
/*
* increment our notification counter
*/
notification_received++;
/*
* And resume monitoring
*/
if (perfmonctl(getpid(), PFM_RESTART,NULL, 0) == -1) {
perror("PFM_RESTART");
exit(1);
}
}
int
main(int argc, char **argv)
{
char **p;
int i, ret;
pid_t pid = getpid();
pfarg_context_t ctx[1];
pfmlib_options_t pfmlib_options;
struct sigaction act;
/*
* Initialize pfm library (required before we can use it)
*/
if (pfm_initialize() != PFMLIB_SUCCESS) {
printf("Can't initialize library\n");
exit(1);
}
/*
* Install the overflow handler (SIGPROF)
*/
memset(&act, 0, sizeof(act));
act.sa_handler = (sig_t)overflow_handler;
sigaction (SIGPROF, &act, 0);
/*
* pass options to library (optional)
*/
memset(&pfmlib_options, 0, sizeof(pfmlib_options));
pfmlib_options.pfm_debug = 0; /* set to 1 for debug */
pfm_set_options(&pfmlib_options);
memset(pd, 0, sizeof(pd));
memset(ctx, 0, sizeof(ctx));
/*
* prepare parameters to library. we don't use any Itanium
* specific features here. so the pfp_model is NULL.
*/
memset(&evt,0, sizeof(evt));
p = event_list;
for (i=0; i < N_EVENTS ; i++, p++) {
if (pfm_find_event(*p, &evt.pfp_events[i].event) != PFMLIB_SUCCESS) {
fatal_error("Cannot find %s event\n", *p);
}
}
/*
* set the default privilege mode for all counters:
* PFM_PLM3 : user level only
*/
evt.pfp_dfl_plm = PFM_PLM3;
/*
* how many counters we use
*/
evt.pfp_event_count = i;
/*
* let the library figure out the values for the PMCS
*/
if ((ret=pfm_dispatch_events(&evt)) != PFMLIB_SUCCESS) {
fatal_error("Cannot configure events: %s\n", pfm_strerror(ret));
}
/*
* For this example, we want to be notified on counter overflows.
*/
ctx[0].ctx_flags = PFM_FL_INHERIT_NONE;
ctx[0].ctx_notify_pid = getpid();
/*
* now create the context for self monitoring/per-task
*/
if (perfmonctl(pid, PFM_CREATE_CONTEXT, ctx, 1) == -1 ) {
if (errno == ENOSYS) {
fatal_error("Your kernel does not have performance monitoring support!\n");
}
fatal_error("Can't create PFM context %s\n", strerror(errno));
}
/*
* Must be done before any PMD/PMD calls (unfreeze PMU). Initialize
* PMC/PMD to safe values. psr.up is cleared.
*/
if (perfmonctl(pid, PFM_ENABLE, NULL, 0) == -1) {
fatal_error("perfmonctl error PFM_ENABLE errno %d\n",errno);
}
/*
* We want to get notified when the counter used for our first
* event overflows
*/
evt.pfp_pc[0].reg_flags |= PFM_REGFL_OVFL_NOTIFY;
evt.pfp_pc[0].reg_reset_pmds[0] |= 1UL << evt.pfp_pc[1].reg_num;
/*
* Now prepare the argument to initialize the PMDs.
* the memset(pd) initialized the entire array to zero already, so
* we just have to fill in the register numbers from the pc[] array.
*
* The reset values are set to 0 and will be used on restart.
*/
for (i=0; i < evt.pfp_event_count; i++) {
pd[i].reg_num = evt.pfp_pc[i].reg_num;
}
/*
* we arm the first counter, such that it will overflow
* after SMPL_PERIOD events have been observed
*/
pd[0].reg_value = (~0UL) - SMPL_PERIOD + 1;
pd[0].reg_long_reset = (~0UL) - SMPL_PERIOD + 1;
/*
* Now program the registers
*
* We don't use the save variable to indicate the number of elements passed to
* the kernel because, as we said earlier, pc may contain more elements than
* the number of events we specified, i.e., contains more than counting monitors.
*/
if (perfmonctl(pid, PFM_WRITE_PMCS, evt.pfp_pc, evt.pfp_pc_count) == -1) {
fatal_error("perfmonctl error PFM_WRITE_PMCS errno %d\n",errno);
}
if (perfmonctl(pid, PFM_WRITE_PMDS, pd, evt.pfp_event_count) == -1) {
fatal_error("perfmonctl error PFM_WRITE_PMDS errno %d\n",errno);
}
/*
* Let's roll now
*/
pfm_start();
busyloop();
pfm_stop();
/*
* let's stop this now
*/
if (perfmonctl(pid, PFM_DESTROY_CONTEXT, NULL, 0) == -1) {
fatal_error("perfmonctl error PFM_DESTROY errno %d\n",errno);
}
return 0;
}
| 2.3125 | 2 |
2024-11-18T22:11:24.158651+00:00 | 2016-08-17T08:19:31 | f38e8611940b758d240af09a90388412e7ca0db0 | {
"blob_id": "f38e8611940b758d240af09a90388412e7ca0db0",
"branch_name": "refs/heads/master",
"committer_date": "2016-08-17T08:19:31",
"content_id": "97294ebd04a51df88288bc1854781a00d258ee17",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "7ee8e0ee4443e5d1f15eed1d0c15f544ac47b75a",
"extension": "c",
"filename": "trusty-irq.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": 17102,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/Linux_common-android-trusty-3.18-drivers/trusty/trusty-irq.c",
"provenance": "stackv2-0072.json.gz:47491",
"repo_name": "yeban207/TrustyOS",
"revision_date": "2016-08-17T08:19:31",
"revision_id": "40ad09911aa12dd774fefcab9747c30da802d2c8",
"snapshot_id": "46e6c59ef9d65febe54bde0aa5d0f64141574b7a",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/yeban207/TrustyOS/40ad09911aa12dd774fefcab9747c30da802d2c8/Linux_common-android-trusty-3.18-drivers/trusty/trusty-irq.c",
"visit_date": "2020-12-05T20:24:21.140869"
} | stackv2 | /*
* Copyright (C) 2013 Google, Inc.
*
* This software is licensed under the terms of the GNU General Public
* License version 2, as published by the Free Software Foundation, and
* may be copied, distributed, and modified under those terms.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
#include <linux/cpu.h>
#include <linux/interrupt.h>
#include <linux/irq.h>
#include <linux/irqdomain.h>
#include <linux/of.h>
#include <linux/of_irq.h>
#include <linux/platform_device.h>
#include <linux/slab.h>
#include <linux/string.h>
#include <linux/trusty/smcall.h>
#include <linux/trusty/sm_err.h>
#include <linux/trusty/trusty.h>
struct trusty_irq {
struct trusty_irq_state *is;
struct hlist_node node;
unsigned int irq;
bool percpu;
bool enable;
struct trusty_irq __percpu *percpu_ptr;
};
struct trusty_irq_work {
struct trusty_irq_state *is;
struct work_struct work;
};
struct trusty_irq_irqset {
struct hlist_head pending;
struct hlist_head inactive;
};
struct trusty_irq_state {
struct device *dev;
struct device *trusty_dev;
struct trusty_irq_work __percpu *irq_work;
struct trusty_irq_irqset normal_irqs;
spinlock_t normal_irqs_lock;
struct trusty_irq_irqset __percpu *percpu_irqs;
struct notifier_block trusty_call_notifier;
struct notifier_block cpu_notifier;
};
static void trusty_irq_enable_pending_irqs(struct trusty_irq_state *is,
struct trusty_irq_irqset *irqset,
bool percpu)
{
struct hlist_node *n;
struct trusty_irq *trusty_irq;
hlist_for_each_entry_safe(trusty_irq, n, &irqset->pending, node) {
dev_dbg(is->dev,
"%s: enable pending irq %d, percpu %d, cpu %d\n",
__func__, trusty_irq->irq, percpu, smp_processor_id());
if (percpu)
enable_percpu_irq(trusty_irq->irq, 0);
else
enable_irq(trusty_irq->irq);
hlist_del(&trusty_irq->node);
hlist_add_head(&trusty_irq->node, &irqset->inactive);
}
}
static void trusty_irq_enable_irqset(struct trusty_irq_state *is,
struct trusty_irq_irqset *irqset)
{
struct trusty_irq *trusty_irq;
hlist_for_each_entry(trusty_irq, &irqset->inactive, node) {
if (trusty_irq->enable) {
dev_warn(is->dev,
"%s: percpu irq %d already enabled, cpu %d\n",
__func__, trusty_irq->irq, smp_processor_id());
continue;
}
dev_dbg(is->dev, "%s: enable percpu irq %d, cpu %d\n",
__func__, trusty_irq->irq, smp_processor_id());
enable_percpu_irq(trusty_irq->irq, 0);
trusty_irq->enable = true;
}
}
static void trusty_irq_disable_irqset(struct trusty_irq_state *is,
struct trusty_irq_irqset *irqset)
{
struct hlist_node *n;
struct trusty_irq *trusty_irq;
hlist_for_each_entry(trusty_irq, &irqset->inactive, node) {
if (!trusty_irq->enable) {
dev_warn(is->dev,
"irq %d already disabled, percpu %d, cpu %d\n",
trusty_irq->irq, trusty_irq->percpu,
smp_processor_id());
continue;
}
dev_dbg(is->dev, "%s: disable irq %d, percpu %d, cpu %d\n",
__func__, trusty_irq->irq, trusty_irq->percpu,
smp_processor_id());
trusty_irq->enable = false;
if (trusty_irq->percpu)
disable_percpu_irq(trusty_irq->irq);
else
disable_irq_nosync(trusty_irq->irq);
}
hlist_for_each_entry_safe(trusty_irq, n, &irqset->pending, node) {
if (!trusty_irq->enable) {
dev_warn(is->dev,
"pending irq %d already disabled, percpu %d, cpu %d\n",
trusty_irq->irq, trusty_irq->percpu,
smp_processor_id());
}
dev_dbg(is->dev,
"%s: disable pending irq %d, percpu %d, cpu %d\n",
__func__, trusty_irq->irq, trusty_irq->percpu,
smp_processor_id());
trusty_irq->enable = false;
hlist_del(&trusty_irq->node);
hlist_add_head(&trusty_irq->node, &irqset->inactive);
}
}
static int trusty_irq_call_notify(struct notifier_block *nb,
unsigned long action, void *data)
{
struct trusty_irq_state *is;
BUG_ON(!irqs_disabled());
if (action != TRUSTY_CALL_PREPARE)
return NOTIFY_DONE;
is = container_of(nb, struct trusty_irq_state, trusty_call_notifier);
spin_lock(&is->normal_irqs_lock);
trusty_irq_enable_pending_irqs(is, &is->normal_irqs, false);
spin_unlock(&is->normal_irqs_lock);
trusty_irq_enable_pending_irqs(is, this_cpu_ptr(is->percpu_irqs), true);
return NOTIFY_OK;
}
static void trusty_irq_work_func_locked_nop(struct work_struct *work)
{
int ret;
struct trusty_irq_state *is =
container_of(work, struct trusty_irq_work, work)->is;
dev_dbg(is->dev, "%s\n", __func__);
ret = trusty_std_call32(is->trusty_dev, SMC_SC_LOCKED_NOP, 0, 0, 0);
if (ret != 0)
dev_err(is->dev, "%s: SMC_SC_LOCKED_NOP failed %d",
__func__, ret);
dev_dbg(is->dev, "%s: done\n", __func__);
}
static void trusty_irq_work_func(struct work_struct *work)
{
int ret;
struct trusty_irq_state *is =
container_of(work, struct trusty_irq_work, work)->is;
dev_dbg(is->dev, "%s\n", __func__);
do {
ret = trusty_std_call32(is->trusty_dev, SMC_SC_NOP, 0, 0, 0);
} while (ret == SM_ERR_NOP_INTERRUPTED);
if (ret != SM_ERR_NOP_DONE)
dev_err(is->dev, "%s: SMC_SC_NOP failed %d", __func__, ret);
dev_dbg(is->dev, "%s: done\n", __func__);
}
irqreturn_t trusty_irq_handler(int irq, void *data)
{
struct trusty_irq *trusty_irq = data;
struct trusty_irq_state *is = trusty_irq->is;
struct trusty_irq_work *trusty_irq_work = this_cpu_ptr(is->irq_work);
struct trusty_irq_irqset *irqset;
dev_dbg(is->dev, "%s: irq %d, percpu %d, cpu %d, enable %d\n",
__func__, irq, trusty_irq->irq, smp_processor_id(),
trusty_irq->enable);
if (trusty_irq->percpu) {
disable_percpu_irq(irq);
irqset = this_cpu_ptr(is->percpu_irqs);
} else {
disable_irq_nosync(irq);
irqset = &is->normal_irqs;
}
spin_lock(&is->normal_irqs_lock);
if (trusty_irq->enable) {
hlist_del(&trusty_irq->node);
hlist_add_head(&trusty_irq->node, &irqset->pending);
}
spin_unlock(&is->normal_irqs_lock);
schedule_work_on(raw_smp_processor_id(), &trusty_irq_work->work);
dev_dbg(is->dev, "%s: irq %d done\n", __func__, irq);
return IRQ_HANDLED;
}
static void trusty_irq_cpu_up(void *info)
{
unsigned long irq_flags;
struct trusty_irq_state *is = info;
dev_dbg(is->dev, "%s: cpu %d\n", __func__, smp_processor_id());
local_irq_save(irq_flags);
trusty_irq_enable_irqset(is, this_cpu_ptr(is->percpu_irqs));
local_irq_restore(irq_flags);
}
static void trusty_irq_cpu_down(void *info)
{
unsigned long irq_flags;
struct trusty_irq_state *is = info;
dev_dbg(is->dev, "%s: cpu %d\n", __func__, smp_processor_id());
local_irq_save(irq_flags);
trusty_irq_disable_irqset(is, this_cpu_ptr(is->percpu_irqs));
local_irq_restore(irq_flags);
}
static int trusty_irq_cpu_notify(struct notifier_block *nb,
unsigned long action, void *hcpu)
{
struct trusty_irq_state *is;
is = container_of(nb, struct trusty_irq_state, cpu_notifier);
dev_dbg(is->dev, "%s: 0x%lx\n", __func__, action);
switch (action & ~CPU_TASKS_FROZEN) {
case CPU_STARTING:
trusty_irq_cpu_up(is);
break;
case CPU_DYING:
trusty_irq_cpu_down(is);
break;
}
return NOTIFY_OK;
}
static int trusty_irq_create_irq_mapping(struct trusty_irq_state *is, int irq)
{
int ret;
int index;
u32 irq_pos;
u32 templ_idx;
u32 range_base;
u32 range_end;
struct of_phandle_args oirq;
/* check if "interrupt-ranges" property is present */
if (!of_find_property(is->dev->of_node, "interrupt-ranges", NULL)) {
/* fallback to old behavior to be backward compatible with
* systems that do not need IRQ domains.
*/
return irq;
}
/* find irq range */
for (index = 0;; index += 3) {
ret = of_property_read_u32_index(is->dev->of_node,
"interrupt-ranges",
index, &range_base);
if (ret)
return ret;
ret = of_property_read_u32_index(is->dev->of_node,
"interrupt-ranges",
index + 1, &range_end);
if (ret)
return ret;
if (irq >= range_base && irq <= range_end)
break;
}
/* read the rest of range entry: template index and irq_pos */
ret = of_property_read_u32_index(is->dev->of_node,
"interrupt-ranges",
index + 2, &templ_idx);
if (ret)
return ret;
/* read irq template */
ret = of_parse_phandle_with_args(is->dev->of_node,
"interrupt-templates",
"#interrupt-cells",
templ_idx, &oirq);
if (ret)
return ret;
WARN_ON(!oirq.np);
WARN_ON(!oirq.args_count);
/*
* An IRQ template is a non empty array of u32 values describing group
* of interrupts having common properties. The u32 entry with index
* zero contains the position of irq_id in interrupt specifier array
* followed by data representing interrupt specifier array with irq id
* field omitted, so to convert irq template to interrupt specifier
* array we have to move down one slot the first irq_pos entries and
* replace the resulting gap with real irq id.
*/
irq_pos = oirq.args[0];
if (irq_pos >= oirq.args_count) {
dev_err(is->dev, "irq pos is out of range: %d\n", irq_pos);
return -EINVAL;
}
for (index = 1; index <= irq_pos; index++)
oirq.args[index - 1] = oirq.args[index];
oirq.args[irq_pos] = irq - range_base;
ret = irq_create_of_mapping(&oirq);
return (!ret) ? -EINVAL : ret;
}
static int trusty_irq_init_normal_irq(struct trusty_irq_state *is, int tirq)
{
int ret;
int irq;
unsigned long irq_flags;
struct trusty_irq *trusty_irq;
dev_dbg(is->dev, "%s: irq %d\n", __func__, tirq);
irq = trusty_irq_create_irq_mapping(is, tirq);
if (irq < 0) {
dev_err(is->dev,
"trusty_irq_create_irq_mapping failed (%d)\n", irq);
return irq;
}
trusty_irq = kzalloc(sizeof(*trusty_irq), GFP_KERNEL);
if (!trusty_irq)
return -ENOMEM;
trusty_irq->is = is;
trusty_irq->irq = irq;
trusty_irq->enable = true;
spin_lock_irqsave(&is->normal_irqs_lock, irq_flags);
hlist_add_head(&trusty_irq->node, &is->normal_irqs.inactive);
spin_unlock_irqrestore(&is->normal_irqs_lock, irq_flags);
ret = request_irq(irq, trusty_irq_handler, IRQF_NO_THREAD,
"trusty", trusty_irq);
if (ret) {
dev_err(is->dev, "request_irq failed %d\n", ret);
goto err_request_irq;
}
return 0;
err_request_irq:
spin_lock_irqsave(&is->normal_irqs_lock, irq_flags);
hlist_del(&trusty_irq->node);
spin_unlock_irqrestore(&is->normal_irqs_lock, irq_flags);
kfree(trusty_irq);
return ret;
}
static int trusty_irq_init_per_cpu_irq(struct trusty_irq_state *is, int tirq)
{
int ret;
int irq;
unsigned int cpu;
struct trusty_irq __percpu *trusty_irq_handler_data;
dev_dbg(is->dev, "%s: irq %d\n", __func__, tirq);
irq = trusty_irq_create_irq_mapping(is, tirq);
if (irq <= 0) {
dev_err(is->dev,
"trusty_irq_create_irq_mapping failed (%d)\n", irq);
return irq;
}
trusty_irq_handler_data = alloc_percpu(struct trusty_irq);
if (!trusty_irq_handler_data)
return -ENOMEM;
for_each_possible_cpu(cpu) {
struct trusty_irq *trusty_irq;
struct trusty_irq_irqset *irqset;
trusty_irq = per_cpu_ptr(trusty_irq_handler_data, cpu);
irqset = per_cpu_ptr(is->percpu_irqs, cpu);
trusty_irq->is = is;
hlist_add_head(&trusty_irq->node, &irqset->inactive);
trusty_irq->irq = irq;
trusty_irq->percpu = true;
trusty_irq->percpu_ptr = trusty_irq_handler_data;
}
ret = request_percpu_irq(irq, trusty_irq_handler, "trusty",
trusty_irq_handler_data);
if (ret) {
dev_err(is->dev, "request_percpu_irq failed %d\n", ret);
goto err_request_percpu_irq;
}
return 0;
err_request_percpu_irq:
for_each_possible_cpu(cpu) {
struct trusty_irq *trusty_irq;
trusty_irq = per_cpu_ptr(trusty_irq_handler_data, cpu);
hlist_del(&trusty_irq->node);
}
free_percpu(trusty_irq_handler_data);
return ret;
}
static int trusty_smc_get_next_irq(struct trusty_irq_state *is,
unsigned long min_irq, bool per_cpu)
{
return trusty_fast_call32(is->trusty_dev, SMC_FC_GET_NEXT_IRQ,
min_irq, per_cpu, 0);
}
static int trusty_irq_init_one(struct trusty_irq_state *is,
int irq, bool per_cpu)
{
int ret;
irq = trusty_smc_get_next_irq(is, irq, per_cpu);
if (irq < 0)
return irq;
if (per_cpu)
ret = trusty_irq_init_per_cpu_irq(is, irq);
else
ret = trusty_irq_init_normal_irq(is, irq);
if (ret) {
dev_warn(is->dev,
"failed to initialize irq %d, irq will be ignored\n",
irq);
}
return irq + 1;
}
static void trusty_irq_free_irqs(struct trusty_irq_state *is)
{
struct trusty_irq *irq;
struct hlist_node *n;
unsigned int cpu;
hlist_for_each_entry_safe(irq, n, &is->normal_irqs.inactive, node) {
dev_dbg(is->dev, "%s: irq %d\n", __func__, irq->irq);
free_irq(irq->irq, irq);
hlist_del(&irq->node);
kfree(irq);
}
hlist_for_each_entry_safe(irq, n,
&this_cpu_ptr(is->percpu_irqs)->inactive,
node) {
struct trusty_irq __percpu *trusty_irq_handler_data;
dev_dbg(is->dev, "%s: percpu irq %d\n", __func__, irq->irq);
trusty_irq_handler_data = irq->percpu_ptr;
free_percpu_irq(irq->irq, trusty_irq_handler_data);
for_each_possible_cpu(cpu) {
struct trusty_irq *irq_tmp;
irq_tmp = per_cpu_ptr(trusty_irq_handler_data, cpu);
hlist_del(&irq_tmp->node);
}
free_percpu(trusty_irq_handler_data);
}
}
static int trusty_irq_probe(struct platform_device *pdev)
{
int ret;
int irq;
unsigned int cpu;
unsigned long irq_flags;
struct trusty_irq_state *is;
work_func_t work_func;
dev_dbg(&pdev->dev, "%s\n", __func__);
is = kzalloc(sizeof(*is), GFP_KERNEL);
if (!is) {
ret = -ENOMEM;
goto err_alloc_is;
}
is->dev = &pdev->dev;
is->trusty_dev = is->dev->parent;
is->irq_work = alloc_percpu(struct trusty_irq_work);
if (!is->irq_work) {
ret = -ENOMEM;
goto err_alloc_irq_work;
}
spin_lock_init(&is->normal_irqs_lock);
is->percpu_irqs = alloc_percpu(struct trusty_irq_irqset);
if (!is->percpu_irqs) {
ret = -ENOMEM;
goto err_alloc_pending_percpu_irqs;
}
platform_set_drvdata(pdev, is);
is->trusty_call_notifier.notifier_call = trusty_irq_call_notify;
ret = trusty_call_notifier_register(is->trusty_dev,
&is->trusty_call_notifier);
if (ret) {
dev_err(&pdev->dev,
"failed to register trusty call notifier\n");
goto err_trusty_call_notifier_register;
}
if (trusty_get_api_version(is->trusty_dev) < TRUSTY_API_VERSION_SMP)
work_func = trusty_irq_work_func_locked_nop;
else
work_func = trusty_irq_work_func;
for_each_possible_cpu(cpu) {
struct trusty_irq_work *trusty_irq_work;
trusty_irq_work = per_cpu_ptr(is->irq_work, cpu);
trusty_irq_work->is = is;
INIT_WORK(&trusty_irq_work->work, work_func);
}
for (irq = 0; irq >= 0;)
irq = trusty_irq_init_one(is, irq, true);
for (irq = 0; irq >= 0;)
irq = trusty_irq_init_one(is, irq, false);
is->cpu_notifier.notifier_call = trusty_irq_cpu_notify;
ret = register_hotcpu_notifier(&is->cpu_notifier);
if (ret) {
dev_err(&pdev->dev, "register_cpu_notifier failed %d\n", ret);
goto err_register_hotcpu_notifier;
}
ret = on_each_cpu(trusty_irq_cpu_up, is, 0);
if (ret) {
dev_err(&pdev->dev, "register_cpu_notifier failed %d\n", ret);
goto err_on_each_cpu;
}
return 0;
err_on_each_cpu:
unregister_hotcpu_notifier(&is->cpu_notifier);
on_each_cpu(trusty_irq_cpu_down, is, 1);
err_register_hotcpu_notifier:
spin_lock_irqsave(&is->normal_irqs_lock, irq_flags);
trusty_irq_disable_irqset(is, &is->normal_irqs);
spin_unlock_irqrestore(&is->normal_irqs_lock, irq_flags);
trusty_irq_free_irqs(is);
trusty_call_notifier_unregister(is->trusty_dev,
&is->trusty_call_notifier);
err_trusty_call_notifier_register:
free_percpu(is->percpu_irqs);
err_alloc_pending_percpu_irqs:
for_each_possible_cpu(cpu) {
struct trusty_irq_work *trusty_irq_work;
trusty_irq_work = per_cpu_ptr(is->irq_work, cpu);
flush_work(&trusty_irq_work->work);
}
free_percpu(is->irq_work);
err_alloc_irq_work:
kfree(is);
err_alloc_is:
return ret;
}
static int trusty_irq_remove(struct platform_device *pdev)
{
int ret;
unsigned int cpu;
unsigned long irq_flags;
struct trusty_irq_state *is = platform_get_drvdata(pdev);
dev_dbg(&pdev->dev, "%s\n", __func__);
unregister_hotcpu_notifier(&is->cpu_notifier);
ret = on_each_cpu(trusty_irq_cpu_down, is, 1);
if (ret)
dev_err(&pdev->dev, "on_each_cpu failed %d\n", ret);
spin_lock_irqsave(&is->normal_irqs_lock, irq_flags);
trusty_irq_disable_irqset(is, &is->normal_irqs);
spin_unlock_irqrestore(&is->normal_irqs_lock, irq_flags);
trusty_irq_free_irqs(is);
trusty_call_notifier_unregister(is->trusty_dev,
&is->trusty_call_notifier);
free_percpu(is->percpu_irqs);
for_each_possible_cpu(cpu) {
struct trusty_irq_work *trusty_irq_work;
trusty_irq_work = per_cpu_ptr(is->irq_work, cpu);
flush_work(&trusty_irq_work->work);
}
free_percpu(is->irq_work);
kfree(is);
return 0;
}
static const struct of_device_id trusty_test_of_match[] = {
{ .compatible = "android,trusty-irq-v1", },
{},
};
static struct platform_driver trusty_irq_driver = {
.probe = trusty_irq_probe,
.remove = trusty_irq_remove,
.driver = {
.name = "trusty-irq",
.owner = THIS_MODULE,
.of_match_table = trusty_test_of_match,
},
};
module_platform_driver(trusty_irq_driver);
| 2.125 | 2 |
2024-11-18T22:11:26.076485+00:00 | 2020-03-17T21:23:53 | 65765eddefe789fcf10fcd12b4386b1f6947a14f | {
"blob_id": "65765eddefe789fcf10fcd12b4386b1f6947a14f",
"branch_name": "refs/heads/master",
"committer_date": "2020-03-17T21:23:53",
"content_id": "b84458e3a944f6789395b9f48484f62e393b5171",
"detected_licenses": [
"MIT"
],
"directory_id": "5be7389c2621d1fcba8de29339caf607a8f46113",
"extension": "c",
"filename": "OrionComm.c",
"fork_events_count": 0,
"gha_created_at": "2019-08-31T06:25:51",
"gha_event_created_at": "2019-08-31T06:25:51",
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 205505434,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 528,
"license": "MIT",
"license_type": "permissive",
"path": "/Communications/OrionComm.c",
"provenance": "stackv2-0072.json.gz:48265",
"repo_name": "SpektreWorks/orion-sdk",
"revision_date": "2020-03-17T21:23:53",
"revision_id": "643c7a0c8dc67c3f630b07de8996a849d9bc0957",
"snapshot_id": "9cae308bd70e47009da468a69ae0ef9c9fbe8b7d",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/SpektreWorks/orion-sdk/643c7a0c8dc67c3f630b07de8996a849d9bc0957/Communications/OrionComm.c",
"visit_date": "2020-07-15T06:56:40.859090"
} | stackv2 | #include "OrionComm.h"
BOOL OrionCommOpen(int *pArgc, char ***pArgv)
{
// If there are at least two arguments, and the first looks like a serial port or IP
if (*pArgc >= 2)
{
// IP address...?
if (OrionCommIpStringValid((*pArgv)[1]))
{
// Try connecting to a gimbal at this IP
return OrionCommOpenNetworkIp((*pArgv)[1]);
}
}
// If we haven't connected any other way, try using network broadcast
return OrionCommOpenNetwork();
}// OrionCommOpen
| 2.046875 | 2 |
2024-11-18T22:11:27.668007+00:00 | 2021-07-24T01:57:02 | 765ddee5bc358a61ae7e616611543343a27229bb | {
"blob_id": "765ddee5bc358a61ae7e616611543343a27229bb",
"branch_name": "refs/heads/main",
"committer_date": "2021-07-24T01:57:02",
"content_id": "fd1b03bfa69b28d0a7d21a6072a0335f140c32a5",
"detected_licenses": [
"MIT"
],
"directory_id": "2d5af4db494305a7a8a588eed771e370678ef1e3",
"extension": "c",
"filename": "exec04.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 304198538,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 288,
"license": "MIT",
"license_type": "permissive",
"path": "/cap-04/exec04.c",
"provenance": "stackv2-0072.json.gz:49168",
"repo_name": "imsouza/c-backes",
"revision_date": "2021-07-24T01:57:02",
"revision_id": "476ec28622f4c48a09d5949da2f47010ea26ef20",
"snapshot_id": "457f8989971b406321b93c74de7afa0fe6b69f7c",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/imsouza/c-backes/476ec28622f4c48a09d5949da2f47010ea26ef20/cap-04/exec04.c",
"visit_date": "2023-06-26T00:51:45.795902"
} | stackv2 | #include <stdio.h>
void main () {
float sal, prestacao, sal20;
printf("Sal. | Prestação ?\b");
scanf("%f %f", &sal, &prestacao);
sal20 = sal*0.20;
if (prestacao > sal20) {
printf("Empréstimo não concedido.\n");
} else {
printf("Empréstimo concedido.\n");
}
} | 3.078125 | 3 |
2024-11-18T22:11:27.864204+00:00 | 2023-03-21T23:49:44 | 68126cc4af1f1a84267e8d28184719acf55e119e | {
"blob_id": "68126cc4af1f1a84267e8d28184719acf55e119e",
"branch_name": "refs/heads/master",
"committer_date": "2023-03-21T23:49:44",
"content_id": "467c57b0a71d5bc7397e59dc17fd44b21a099593",
"detected_licenses": [
"MIT"
],
"directory_id": "b452bbb87214f174122f425f6f98f4c3890c3cca",
"extension": "c",
"filename": "apply.c",
"fork_events_count": 66,
"gha_created_at": "2020-01-28T13:24:09",
"gha_event_created_at": "2023-07-07T13:53:28",
"gha_language": "Go",
"gha_license_id": "MIT",
"github_id": 236740615,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2514,
"license": "MIT",
"license_type": "permissive",
"path": "/internal/ccall/cgraph/apply.c",
"provenance": "stackv2-0072.json.gz:49426",
"repo_name": "goccy/go-graphviz",
"revision_date": "2023-03-21T23:49:44",
"revision_id": "865af036ddbb745c4424bbd2fdaa9a75668cf0d4",
"snapshot_id": "bea9bc86b42734aff7ffae283aeae71702ca588a",
"src_encoding": "UTF-8",
"star_events_count": 511,
"url": "https://raw.githubusercontent.com/goccy/go-graphviz/865af036ddbb745c4424bbd2fdaa9a75668cf0d4/internal/ccall/cgraph/apply.c",
"visit_date": "2023-07-20T08:05:39.868377"
} | stackv2 | /* $Id$ $Revision$ */
/* vim:set shiftwidth=4 ts=8: */
/*************************************************************************
* Copyright (c) 2011 AT&T Intellectual Property
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors: See CVS logs. Details at http://www.graphviz.org/
*************************************************************************/
#include <cghdr.h>
/* The following functions take a graph and a template (node/edge/graph)
* and return the object representing the template within the local graph.
*/
static Agobj_t *subnode_search(Agraph_t * sub, Agobj_t * n)
{
if (agraphof(n) == sub)
return n;
return (Agobj_t *) agsubnode(sub, (Agnode_t *) n, FALSE);
}
static Agobj_t *subedge_search(Agraph_t * sub, Agobj_t * e)
{
if (agraphof(e) == sub)
return e;
return (Agobj_t *) agsubedge(sub, (Agedge_t *) e, FALSE);
}
static Agobj_t *subgraph_search(Agraph_t * sub, Agobj_t * g)
{
NOTUSED(g);
return (Agobj_t *) sub;
}
/* recursively apply objfn within the hierarchy of a graph.
* if obj is a node or edge, it and its images in every subg are visited.
* if obj is a graph, then it and its subgs are visited.
*/
static void rec_apply(Agraph_t * g, Agobj_t * obj, agobjfn_t fn, void *arg,
agobjsearchfn_t objsearch, int preorder)
{
Agraph_t *sub;
Agobj_t *subobj;
if (preorder)
fn(g, obj, arg);
for (sub = agfstsubg(g); sub; sub = agnxtsubg(sub)) {
if ((subobj = objsearch(sub, obj)))
rec_apply(sub, subobj, fn, arg, objsearch, preorder);
}
if (NOT(preorder))
fn(g, obj, arg);
}
/* external entry point (this seems to be one of those ineffective
* comments censured in books on programming style) */
int agapply(Agraph_t * g, Agobj_t * obj, agobjfn_t fn, void *arg,
int preorder)
{
Agobj_t *subobj;
agobjsearchfn_t objsearch;
switch (AGTYPE(obj)) {
case AGRAPH:
objsearch = subgraph_search;
break;
case AGNODE:
objsearch = subnode_search;
break;
case AGOUTEDGE:
case AGINEDGE:
objsearch = subedge_search;
break;
default:
agerr(AGERR, "agapply: unknown object type %d\n", AGTYPE(obj));
return FAILURE;
break;
}
if ((subobj = objsearch(g, obj))) {
rec_apply(g, subobj, fn, arg, objsearch, preorder);
return SUCCESS;
} else
return FAILURE;
}
| 2.609375 | 3 |
2024-11-18T22:11:30.342666+00:00 | 2018-11-23T03:19:29 | 5e9033635a1b0d9882ce7d23e244e26dff619237 | {
"blob_id": "5e9033635a1b0d9882ce7d23e244e26dff619237",
"branch_name": "refs/heads/master",
"committer_date": "2018-11-23T03:19:29",
"content_id": "8e1beb3d7854065b4afe3b39ddc42869f72813f6",
"detected_licenses": [
"MIT"
],
"directory_id": "8149c2bcbe581564d15eda15ec6c57ad06742923",
"extension": "c",
"filename": "p46_permutations.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 145794003,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2521,
"license": "MIT",
"license_type": "permissive",
"path": "/leetcode/p46_permutations.c",
"provenance": "stackv2-0072.json.gz:50067",
"repo_name": "fed-xie/foo",
"revision_date": "2018-11-23T03:19:29",
"revision_id": "87714bef576a8a612447b162e69d9ef63dc70b76",
"snapshot_id": "01da43ab2472403b22de2b61167616fdc061ae61",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/fed-xie/foo/87714bef576a8a612447b162e69d9ef63dc70b76/leetcode/p46_permutations.c",
"visit_date": "2020-03-27T02:29:10.748772"
} | stackv2 | /**
* Return an array of arrays of size *returnSize.
* Note: The returned array must be malloced, assume caller calls free().
*/
#include <stdlib.h>
typedef int* data_t;
struct vector_t {
size_t size;
size_t used;
int max_depth;
data_t* data;
};
static void init_vector(struct vector_t* v, size_t size)
{
if (0 == size)
size = 4;
v->size = size;
v->used = 0;
v->data = malloc(size * sizeof(data_t));
if (NULL == v->data)
exit(-1);
}
static struct vector_t* realloc_vector(struct vector_t* v, size_t next)
{
if (0 == next) {
if (v->data)
free(v->data);
v->data = NULL;
v->size = 0;
v->used = 0;
return v;
}
//realloc is better, but leetcode not supported
data_t* new_v = malloc(next * sizeof(data_t));
int count = v->used < next ? v->used : next;
for (int i=0; i<count; ++i)
new_v[i] = v->data[i];
if (v->data)
free(v->data);
v->data = new_v;
v->used = count;
v->size = next;
return v;
}
static void push_back_vector(struct vector_t* vec, data_t value)
{
if (vec->used >= vec->size)
vec = realloc_vector(vec, vec->size ? vec->size << 1 : 4);
vec->data[vec->used++] = value;
}
static int fill_permutations(int* nums, int depth, struct vector_t* vec)
{
if (depth == vec->max_depth) {
int* arr = malloc(sizeof(int)*(depth+1));
arr[depth] = *nums;
push_back_vector(vec, arr);
return 1;
}
int base = vec->used;
int total = 0;
int size = vec->max_depth - depth + 1;
int val;
for (int i=0; i<size; ++i) {
val = nums[i];
nums[i] = nums[0];
int num = fill_permutations(nums+1, depth+1, vec);
for (int j=0; j<num; ++j)
vec->data[base+total+j][depth] = val;
nums[i] = val;
total += num;
}
return total;
}
int** permute(int* nums, int numsSize, int* returnSize)
{
if (0 == numsSize) {
*returnSize = 0;
return NULL;
}
*returnSize = 1;
for (int i=2; i<=numsSize; ++i)
*returnSize *= i;
struct vector_t res;
init_vector(&res, *returnSize);
res.max_depth = numsSize - 1;
fill_permutations(nums, 0, &res);
//realloc_vector(&res, res.size);
return res.data;
}
#include <stdio.h>
int main(int argc, char** argv)
{
int nums[] = {1,2,3};
int n = sizeof(nums)/sizeof(*nums);
int ret_size;
int** res = permute(nums, n, &ret_size);
for (int i=0; i<ret_size; ++i) {
printf("%d. ", i);
for(int j=0; j<n; ++j)
printf("%d ", res[i][j]);
printf("\n");
free(res[i]);
}
if (res)
free(res);
return 0;
} | 3.671875 | 4 |
2024-11-18T22:11:31.052671+00:00 | 2018-05-10T09:28:08 | e12d25bbefee737e3cddc4da5c6baa9aad87e624 | {
"blob_id": "e12d25bbefee737e3cddc4da5c6baa9aad87e624",
"branch_name": "refs/heads/master",
"committer_date": "2018-05-10T09:28:08",
"content_id": "6837cece91697a6ea7a7a547ccd86f2b61836748",
"detected_licenses": [
"MIT"
],
"directory_id": "3d10ffd0575084acf4cc12f4be6610b86f2ef8e6",
"extension": "c",
"filename": "LINKEDLI.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 50276605,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2935,
"license": "MIT",
"license_type": "permissive",
"path": "/data-structure/linked-list/LINKEDLI.c",
"provenance": "stackv2-0072.json.gz:50451",
"repo_name": "rrishabhj/ALGORITHM",
"revision_date": "2018-05-10T09:28:08",
"revision_id": "a5204575b2e7417b5f5e1243687179294fdca290",
"snapshot_id": "447dec033aba0e6ae34f005012ff4a7a4adca712",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/rrishabhj/ALGORITHM/a5204575b2e7417b5f5e1243687179294fdca290/data-structure/linked-list/LINKEDLI.c",
"visit_date": "2021-01-19T06:59:05.331420"
} | stackv2 | /* ## (c) 2017, Arkadiusz Drabczyk, [email protected] */
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node *next;
};
int init(struct node **head, int data)
{
*head = malloc(sizeof(struct node));
if (!*head) {
fprintf(stderr, "Failed to init a linked list\n");
return 1;
}
(*head)->data = data;
(*head)->next = NULL;
return 0;
}
int insert(struct node **head, int data)
{
struct node *current = *head;
struct node *tmp;
do {
tmp = current;
current = current->next;
} while (current);
/* create a new node after tmp */
struct node *new = malloc(sizeof(struct node));
if (!new) {
fprintf(stderr, "Failed to insert a new element\n");
return 1;
}
new->next = NULL;
new->data = data;
tmp->next = new;
return 0;
}
void delete(struct node **head, int data)
{
struct node *current = *head;
struct node *prev = NULL;
do {
if (current->data == data) {
break;
}
prev = current;
current = current->next;
} while (current);
/* if the first element */
if (current == *head) {
/* reuse prev */
prev = *head;
*head = current->next;
free(prev);
return;
}
/* if the last element */
if (current->next == NULL) {
prev->next = NULL;
free(current);
return;
}
prev->next = current->next;
free(current);
return;
}
void print(struct node **head)
{
struct node *current = *head;
while (current) {
printf("current data: %d, address: %p\n", current->data,
current);
current = current->next;
}
}
void reverse(struct node **head)
{
struct node *current = *head, *newnext = NULL, *tmp;
do {
tmp = current->next;
current->next = newnext;
newnext = current;
current = tmp;
} while (current);
*head = newnext;
return;
}
void deinit(struct node **head)
{
struct node *node = *head;
do {
struct node *tmp;
tmp = node;
node = node->next;
free(tmp);
} while (node);
}
int main(void)
{
struct node *head;
if (init(&head, 25) != 0) {
fprintf(stderr, "Failed to init a new linked list");
return EXIT_FAILURE;
}
insert(&head, 30);
insert(&head, 55);
insert(&head, 210);
insert(&head, 1000000);
puts("Print the linked list:");
print(&head);
puts("\nDelete first element.");
delete(&head, 25);
puts("Print the linked list:");
print(&head);
puts("\nDelete last element.");
delete(&head, 1000000);
puts("Print the linked list:");
print(&head);
puts("\nDelete middle element.");
delete(&head, 55);
puts("Print the linked list:");
print(&head);
puts("\nAdd more elements.");
insert(&head, 1);
insert(&head, 2);
insert(&head, 3);
puts("Print the linked list:");
print(&head);
puts("\nReverse the linked list");
reverse(&head);
puts("Print the linked list:");
print(&head);
deinit(&head);
return EXIT_SUCCESS;
}
| 3.984375 | 4 |
2024-11-18T22:11:31.993122+00:00 | 2020-08-14T19:31:36 | 0976c51b2b5a81af59496a472c02cd1afa4eaf28 | {
"blob_id": "0976c51b2b5a81af59496a472c02cd1afa4eaf28",
"branch_name": "refs/heads/master",
"committer_date": "2020-08-14T19:31:36",
"content_id": "3273355902920550861c33fac58d900449c92ea0",
"detected_licenses": [
"MIT"
],
"directory_id": "f328c545b57ddeca9b936d43c71656dd54aebb82",
"extension": "c",
"filename": "fork.c",
"fork_events_count": 3,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 106639410,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 355,
"license": "MIT",
"license_type": "permissive",
"path": "/course/OperatingSystemCourseWork/g1/fork.c",
"provenance": "stackv2-0072.json.gz:50581",
"repo_name": "FredericDT/ExploratoryResearchOnC-Cpp",
"revision_date": "2020-08-14T19:31:36",
"revision_id": "47a28a41bac0de9a0557c5b7842611bd85c5f98a",
"snapshot_id": "3ddd62fc10390e3da3380b541d8b0b7c47492666",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/FredericDT/ExploratoryResearchOnC-Cpp/47a28a41bac0de9a0557c5b7842611bd85c5f98a/course/OperatingSystemCourseWork/g1/fork.c",
"visit_date": "2021-06-01T22:37:54.449319"
} | stackv2 | #include<stdio.h>
#include<sys/types.h>
#include<unistd.h>
#include<stdlib.h>
int main(int argc, char** argv) {
pid_t pid;
if ((pid = fork()) == 0) {
printf("hello from the child\n");
} else if (pid > 0) {
printf("hello from the parent\n");
} else {
printf("fork error\n");
exit(0);
}
return 0;
}
| 2.46875 | 2 |
2024-11-18T22:11:32.554781+00:00 | 2015-10-23T06:42:21 | a93c247e18e8c59ac26ae22f82bfc35914b64588 | {
"blob_id": "a93c247e18e8c59ac26ae22f82bfc35914b64588",
"branch_name": "refs/heads/master",
"committer_date": "2015-10-23T06:42:21",
"content_id": "7d8e97f7692441e0f3b33a08b5683af576efe0b4",
"detected_licenses": [
"MIT"
],
"directory_id": "8dd2c2c7a16c4630577ed78806e0c3e9c06b25d9",
"extension": "c",
"filename": "ssp-delay.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 39171088,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1107,
"license": "MIT",
"license_type": "permissive",
"path": "/gcctestb/gcctestb/gr_mruby/mruby-1.1.0/mrbgems/mruby-ssp-delay/src/ssp-delay.c",
"provenance": "stackv2-0072.json.gz:51223",
"repo_name": "alvstakahashi/GR-SAKURA-MRUBY-CAR",
"revision_date": "2015-10-23T06:42:21",
"revision_id": "946c78f9ed678b82ccbe0ebe41e85d8857c3937f",
"snapshot_id": "e3bba1c4507418d66808396b2e22a36362a29c19",
"src_encoding": "SHIFT_JIS",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/alvstakahashi/GR-SAKURA-MRUBY-CAR/946c78f9ed678b82ccbe0ebe41e85d8857c3937f/gcctestb/gcctestb/gr_mruby/mruby-1.1.0/mrbgems/mruby-ssp-delay/src/ssp-delay.c",
"visit_date": "2021-01-10T01:01:17.527347"
} | stackv2 | #include "mruby.h"
#include "mruby/string.h"
#include <stdio.h>
#include <string.h>
#include <kernel.h>
mrb_value
mrb_ssp_delay_delay(mrb_state *mrb, mrb_value self)
{
ER retval;
mrb_int tout;
mrb_value argv;
SYSTIM startTime;
SYSTIM targetTime;
SYSTIM currentTime;
mrb_get_args(mrb, "o", &argv);
tout = mrb_fixnum(argv);
#if 1
printf("mrb_ssp_delay tout = %d\n",tout);
#endif
// int ai = mrb_gc_arena_save(mrb);
get_tim(&startTime);
targetTime = startTime + tout*100;
if (targetTime < startTime) // オーバーフロー
{
while(1)
{
get_tim(¤tTime);
if (startTime > currentTime) //オーバーフロー
{
break;
}
}
}
while(1)
{
get_tim(¤tTime);
if (currentTime >= targetTime)
{
break;
}
}
// retval = dly_tsk(tout);
// mrb_gc_arena_restore(mrb, ai);
return argv;
}
void
mrb_mruby_ssp_delay_gem_init(mrb_state* mrb)
{
struct RClass *krn;
krn = mrb->kernel_module;
mrb_define_method(mrb, krn, "Ssp_Delay", mrb_ssp_delay_delay, MRB_ARGS_REQ(1));
}
void
mrb_mruby_ssp_delay_gem_final(mrb_state* mrb)
{
}
| 2.15625 | 2 |
2024-11-18T22:11:32.672356+00:00 | 2019-07-05T02:13:28 | 004b7de13b067e9c5c32de84ecb4149190cf5955 | {
"blob_id": "004b7de13b067e9c5c32de84ecb4149190cf5955",
"branch_name": "refs/heads/master",
"committer_date": "2019-07-05T02:13:28",
"content_id": "91ec32fde07471d5835b70e464e8bf69626f0596",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "983e3137e09ea9ad51331faa084369b119597f98",
"extension": "c",
"filename": "mx_led.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 197570388,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 8138,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/lib/mx_led.c",
"provenance": "stackv2-0072.json.gz:51351",
"repo_name": "Moxa-Linux/moxa-led-control",
"revision_date": "2019-07-05T02:13:28",
"revision_id": "5cd8c32536def20681604dfefbafd60c9df71e8b",
"snapshot_id": "ccccf8f36f98b76c7886af4c98fc95abfd324d03",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/Moxa-Linux/moxa-led-control/5cd8c32536def20681604dfefbafd60c9df71e8b/lib/mx_led.c",
"visit_date": "2021-06-25T12:59:44.508109"
} | stackv2 | /*
* SPDX-License-Identifier: Apache-2.0
*
* Name:
* MOXA LED Library
*
* Description:
* Library for controling LED to off, on, or blink.
*
* Authors:
* 2014 SZ Lin <[email protected]>
* 2017 Harry YJ Jhou <[email protected]>
* 2018 Ken CJ Chou <[email protected]>
*/
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <json-c/json.h>
#include <mx_led.h>
#define CONF_FILE "/etc/moxa-configs/moxa-led-control.json"
#define CONF_VER_SUPPORTED "1.1.*"
#define LED_BASEPATH "/sys/class/leds"
#define MAX_FILEPATH_LEN 256 /* reserved length for file path */
struct led_state_struct {
const char *file_written;
const char *data_written;
};
static int lib_initialized;
static struct json_object *config;
static struct led_state_struct led_states[3] = {
{
.file_written = "brightness",
.data_written = "0"
},
{
.file_written = "brightness",
.data_written = "1"
},
{
.file_written = "trigger",
.data_written = "heartbeat"
}
};
/*
* json-c utilities
*/
static inline int obj_get_obj(struct json_object *obj, char *key, struct json_object **val)
{
if (!json_object_object_get_ex(obj, key, val))
return -1;
return 0;
}
static int obj_get_int(struct json_object *obj, char *key, int *val)
{
struct json_object *tmp;
if (obj_get_obj(obj, key, &tmp) < 0)
return -1;
*val = json_object_get_int(tmp);
return 0;
}
static int obj_get_str(struct json_object *obj, char *key, const char **val)
{
struct json_object *tmp;
if (obj_get_obj(obj, key, &tmp) < 0)
return -1;
*val = json_object_get_string(tmp);
return 0;
}
static int obj_get_arr(struct json_object *obj, char *key, struct array_list **val)
{
struct json_object *tmp;
if (obj_get_obj(obj, key, &tmp) < 0)
return -1;
*val = json_object_get_array(tmp);
return 0;
}
static int arr_get_obj(struct array_list *arr, int idx, struct json_object **val)
{
if (arr == NULL || idx >= arr->length)
return -1;
*val = array_list_get_idx(arr, idx);
return 0;
}
static int arr_get_int(struct array_list *arr, int idx, int *val)
{
struct json_object *tmp;
if (arr_get_obj(arr, idx, &tmp) < 0)
return -1;
*val = json_object_get_int(tmp);
return 0;
}
static int arr_get_str(struct array_list *arr, int idx, const char **val)
{
struct json_object *tmp;
if (arr_get_obj(arr, idx, &tmp) < 0)
return -1;
*val = json_object_get_string(tmp);
return 0;
}
static int arr_get_arr(struct array_list *arr, int idx, struct array_list **val)
{
struct json_object *tmp;
if (arr_get_obj(arr, idx, &tmp) < 0)
return -1;
*val = json_object_get_array(tmp);
return 0;
}
/*
* static functions
*/
static int check_config_version_supported(const char *conf_ver)
{
int cv[2], sv[2];
if (sscanf(conf_ver, "%d.%d.%*s", &cv[0], &cv[1]) < 0)
return -1; /* E_SYSFUNCERR */
if (sscanf(CONF_VER_SUPPORTED, "%d.%d.%*s", &sv[0], &sv[1]) < 0)
return -1; /* E_SYSFUNCERR */
if (cv[0] != sv[0] || cv[1] != sv[1])
return -4; /* E_UNSUPCONFVER */
return 0;
}
static int get_led_type_info(int led_type, struct json_object **led_type_info)
{
struct array_list *led_types;
if (led_type != LED_TYPE_SIGNAL && led_type != LED_TYPE_PROGRAMMABLE)
return -2; /* E_INVAL */
if (obj_get_arr(config, "LED_TYPES", &led_types) < 0)
return -5; /* E_CONFERR */
if (arr_get_obj(led_types, led_type, led_type_info) < 0)
return -5; /* E_CONFERR */
return 0;
}
static int get_led_state_info(int led_state, struct led_state_struct **state)
{
if (led_state != LED_STATE_OFF && led_state != LED_STATE_ON &&
led_state != LED_STATE_BLINK)
return -2; /* E_INVAL */
*state = &led_states[led_state];
return 0;
}
static int get_led_path(int led_type, int group, int index, const char **path)
{
struct json_object *led_type_info;
struct array_list *group_paths, *led_paths;
int ret, num_of_groups, num_of_leds_per_group;
ret = get_led_type_info(led_type, &led_type_info);
if (ret < 0)
return ret;
if (obj_get_int(led_type_info, "NUM_OF_GROUPS", &num_of_groups) < 0)
return -5; /* E_CONFERR */
if (obj_get_int(led_type_info, "NUM_OF_LEDS_PER_GROUP", &num_of_leds_per_group) < 0)
return -5; /* E_CONFERR */
if (group < 1 || group > num_of_groups)
return -2; /* E_INVAL */
if (index < 1 || index > num_of_leds_per_group)
return -2; /* E_INVAL */
if (obj_get_arr(led_type_info, "PATHS", &group_paths) < 0)
return -5; /* E_CONFERR */
if (arr_get_arr(group_paths, group - 1, &led_paths) < 0)
return -5; /* E_CONFERR */
if (arr_get_str(led_paths, index - 1, path) < 0)
return -5; /* E_CONFERR */
return 0;
}
static int write_file(char *filepath, const char *data)
{
int fd;
fd = open(filepath, O_WRONLY);
if (fd < 0)
return -1; /* E_SYSFUNCERR */
if (write(fd, data, strlen(data)) < 0) {
close(fd);
return -1; /* E_SYSFUNCERR */
}
close(fd);
return 0;
}
static int set_led(int led_type, int group, int index, int led_state)
{
struct led_state_struct *led_state_info;
const char *led_path;
char filepath[MAX_FILEPATH_LEN];
int ret;
/* set led off first before set led on */
if (led_state == LED_STATE_ON) {
ret = set_led(led_type, group, index, LED_STATE_OFF);
if (ret < 0)
return ret;
}
ret = get_led_path(led_type, group, index, &led_path);
if (ret < 0)
return ret;
ret = get_led_state_info(led_state, &led_state_info);
if (ret < 0)
return ret;
sprintf(filepath, "%s/%s/%s", LED_BASEPATH, led_path, led_state_info->file_written);
return write_file(filepath, led_state_info->data_written);
}
/*
* APIs
*/
int mx_led_init(void)
{
int ret;
const char *conf_ver;
if (lib_initialized)
return 0;
config = json_object_from_file(CONF_FILE);
if (config == NULL)
return -5; /* E_CONFERR */
if (obj_get_str(config, "CONFIG_VERSION", &conf_ver) < 0)
return -5; /* E_CONFERR */
ret = check_config_version_supported(conf_ver);
if (ret < 0)
return ret;
lib_initialized = 1;
return 0;
}
int mx_led_get_num_of_groups(int led_type, int *num_of_groups)
{
struct json_object *led_type_info;
int ret;
if (!lib_initialized)
return -3; /* E_LIBNOTINIT */
ret = get_led_type_info(led_type, &led_type_info);
if (ret < 0)
return ret;
if (obj_get_int(led_type_info, "NUM_OF_GROUPS", num_of_groups) < 0)
return -5; /* E_CONFERR */
return 0;
}
int mx_led_get_num_of_leds_per_group(int led_type, int *num_of_leds_per_group)
{
struct json_object *led_type_info;
int ret;
if (!lib_initialized)
return -3; /* E_LIBNOTINIT */
ret = get_led_type_info(led_type, &led_type_info);
if (ret < 0)
return ret;
if (obj_get_int(led_type_info, "NUM_OF_LEDS_PER_GROUP", num_of_leds_per_group) < 0)
return -5; /* E_CONFERR */
return 0;
}
int mx_led_set_brightness(int led_type, int group, int index, int state)
{
if (!lib_initialized)
return -3; /* E_LIBNOTINIT */
return set_led(led_type, group, index, state);
}
int mx_led_set_type_all(int led_type, int led_state)
{
struct json_object *led_type_info;
int ret, num_of_groups, num_of_leds_per_group, i, j;
if (!lib_initialized)
return -3; /* E_LIBNOTINIT */
ret = get_led_type_info(led_type, &led_type_info);
if (ret < 0)
return ret;
if (obj_get_int(led_type_info, "NUM_OF_GROUPS", &num_of_groups) < 0)
return -5; /* E_CONFERR */
if (obj_get_int(led_type_info, "NUM_OF_LEDS_PER_GROUP", &num_of_leds_per_group) < 0)
return -5; /* E_CONFERR */
for (i = 1; i <= num_of_groups; i++) {
for (j = 1; j <= num_of_leds_per_group; j++) {
ret = set_led(led_type, i, j, led_state);
if (ret < 0)
return ret;
}
}
return 0;
}
int mx_led_set_all_off(void)
{
int ret;
if (!lib_initialized)
return -3; /* E_LIBNOTINIT */
ret = mx_led_set_type_all(LED_TYPE_SIGNAL, LED_STATE_OFF);
if (ret < 0)
return ret;
ret = mx_led_set_type_all(LED_TYPE_PROGRAMMABLE, LED_STATE_OFF);
if (ret < 0)
return ret;
return 0;
}
int mx_led_set_all_on(void)
{
int ret;
if (!lib_initialized)
return -3; /* E_LIBNOTINIT */
ret = mx_led_set_type_all(LED_TYPE_SIGNAL, LED_STATE_ON);
if (ret < 0)
return ret;
ret = mx_led_set_type_all(LED_TYPE_PROGRAMMABLE, LED_STATE_ON);
if (ret < 0)
return ret;
return 0;
}
| 2.359375 | 2 |
2024-11-18T22:11:33.047879+00:00 | 2015-12-23T13:08:41 | 18f3b0837c480ae587f8b59b898ff326acd8880c | {
"blob_id": "18f3b0837c480ae587f8b59b898ff326acd8880c",
"branch_name": "refs/heads/master",
"committer_date": "2015-12-23T13:08:41",
"content_id": "5b1a0491053ab6541eeb764bf91680ccc37894f8",
"detected_licenses": [
"MIT"
],
"directory_id": "ee06b643e3263a2a91b5c9d5b6be8f3e30e32f77",
"extension": "c",
"filename": "example.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 47140123,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 695,
"license": "MIT",
"license_type": "permissive",
"path": "/example.c",
"provenance": "stackv2-0072.json.gz:51737",
"repo_name": "philippludwig/liblistmisc",
"revision_date": "2015-12-23T13:08:41",
"revision_id": "320527c0ee54f140df793991a402c3a2eefd1586",
"snapshot_id": "621105d5e8054e400851e6358d48e54f6bf4242d",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/philippludwig/liblistmisc/320527c0ee54f140df793991a402c3a2eefd1586/example.c",
"visit_date": "2021-01-10T05:31:47.022479"
} | stackv2 | // Compile me with: gcc -std=c99 example.c liblistmisc.a -o example -D_GNU_SOURCE
// (_GNU_SOURCE is only needed for strdup)
#include <stdio.h>
#include <string.h>
#include "listmisc.h"
int main() {
// Create a new, empty list.
list_t *list = list_create();
// Fill the list with some strings
list_add(list, strdup("Item 1"));
list_add(list, strdup("Item 2"));
list_add(list, strdup("Item 3"));
// Iterate over all items in the list.
// Note: C99 support is required for the list_foreach macro.
list_foreach(list, it) {
char *data = (char*)it->d;
printf("%s\n", data);
}
// Free all memory. Note that list_free also frees every data element.
list_free(list);
return 0;
}
| 3.234375 | 3 |
2024-11-18T22:11:33.111286+00:00 | 2021-04-19T08:59:42 | 7a50c7a964b23b1fbf9f5b69d99a4360818fc6f5 | {
"blob_id": "7a50c7a964b23b1fbf9f5b69d99a4360818fc6f5",
"branch_name": "refs/heads/main",
"committer_date": "2021-04-19T08:59:42",
"content_id": "9297ec514b580588b96f32b128dc74ece6e8b9dc",
"detected_licenses": [
"MIT"
],
"directory_id": "90e5d28f5d4cbd874bc5be69344d3d765be13573",
"extension": "c",
"filename": "test_sem_ipc_jobqueue.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 344741141,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 9227,
"license": "MIT",
"license_type": "permissive",
"path": "/csc2035-assignment1-init/test/test_sem_ipc_jobqueue.c",
"provenance": "stackv2-0072.json.gz:51865",
"repo_name": "MohitKAgnihotri/bookish-bassoon-prdconntwrk",
"revision_date": "2021-04-19T08:59:42",
"revision_id": "90ea4dfccdf25d6e70faefd6b1816d3cd2c9023b",
"snapshot_id": "fceb974954085f8a5c4e1f0e4fe7421c083612b5",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/MohitKAgnihotri/bookish-bassoon-prdconntwrk/90ea4dfccdf25d6e70faefd6b1816d3cd2c9023b/csc2035-assignment1-init/test/test_sem_ipc_jobqueue.c",
"visit_date": "2023-04-08T14:07:55.364315"
} | stackv2 | /******** DO NOT EDIT THIS FILE ********/
#include <unistd.h>
#include <sys/wait.h>
#include <stdio.h>
#include <errno.h>
#include "test_jobqueue_common.h"
#include "test_sem_ipc_jobqueue.h"
#include "../sem_ipc_jobqueue.h"
#include "procs4tests.h"
int main(int argc, char** argv) {
return munit_suite_main(&suite, NULL, argc, argv);
}
static void* test_setup(const MunitParameter params[], void* user_data) {
test_jqueue_t* test_jq = (test_jqueue_t*) malloc(sizeof(test_jqueue_t));
sem_ipc_jobqueue_t* q = sem_ijq_new(new_init_proc());
test_jq->q = q;
jobqueue_t* jq = (jobqueue_t*) q->ijq->addr;
test_jq->head = &jq->head;
test_jq->tail = &jq->tail;
test_jq->buf_size = &jq->buf_size;
test_jq->jobs = jq->jobs;
test_jq->capacity = (size_t (*)(void*)) sem_ijq_capacity;
test_jq->is_full = (bool (*)(void*)) sem_ijq_is_full;
test_jq->is_empty = (bool (*)(void*)) sem_ijq_is_empty;
test_jq->enqueue = (void (*)(void*, job_t)) sem_ijq_enqueue;
test_jq->dequeue = (job_t (*)(void*)) sem_ijq_dequeue;
test_jq->peekhead = (job_t (*)(void*)) sem_ijq_peekhead;
test_jq->peektail = (job_t (*)(void*)) sem_ijq_peektail;
return test_jq;
}
static void test_tear_down(void* fixture) {
test_jqueue_t* test_jq = (test_jqueue_t*) fixture;
sem_ipc_jobqueue_t* q = (sem_ipc_jobqueue_t*) test_jq->q;
proc_t* p = q->ijq->proc;
sem_ijq_delete(q);
proc_delete(p);
free(test_jq);
}
static sem_ipc_jobqueue_t* assert_sem_ijq_new(proc_t* p) {
sem_ipc_jobqueue_t* sijq = sem_ijq_new(p);
assert_not_null(sijq);
assert_not_null(sijq->ijq);
assert_not_null(sijq->mutex);
assert_not_null(sijq->full);
assert_not_null(sijq->empty);
assert_false(ipc_jq_is_full(sijq->ijq));
assert_true(ipc_jq_is_empty(sijq->ijq));
#ifndef __APPLE__
int val;
(void) sem_getvalue(sijq->mutex, &val);
assert_int(val, ==, 1);
(void) sem_getvalue(sijq->full, &val);
assert_int(val, ==, 0);
(void) sem_getvalue(sijq->empty, &val);
assert_int(val, ==, ipc_jq_capacity(sijq->ijq));
assert_int(val, ==, JOBQ_BUF_SIZE - 1);
#endif
assert_init_jobqueue_state((jobqueue_t*) sijq->ijq->addr);
return sijq;
}
static MunitResult test_sem_ijq_new_delete(const MunitParameter params[],
void* fixture) {
test_procs_t* tp = new_test_procs();
sem_ipc_jobqueue_t* qin = assert_sem_ijq_new(tp->pin);
sem_ipc_jobqueue_t* qni = assert_sem_ijq_new(tp->pni);
sem_ijq_delete(qni);
sem_ijq_delete(qin);
delete_test_procs(tp);
return MUNIT_OK;
}
static MunitResult test_no_semfailure(MunitResult result) {
if (result == MUNIT_OK)
assert_int(errno, ==, 0);
return result;
}
static MunitResult test_sem_ijq_capacity(const MunitParameter params[],
void* fixture) {
return test_jqueue_capacity((test_jqueue_t*) fixture);
}
static MunitResult test_sem_ijq_is_full(const MunitParameter params[],
void* fixture) {
errno = 0;
return test_no_semfailure(test_jqueue_is_full((test_jqueue_t*) fixture));
}
static MunitResult test_sem_ijq_is_empty(const MunitParameter params[],
void* fixture) {
errno = 0;
return test_no_semfailure(test_jqueue_is_empty((test_jqueue_t*) fixture));
}
static MunitResult test_sem_ijq_peekhead(const MunitParameter params[],
void* fixture) {
errno = 0;
return test_no_semfailure(test_jqueue_peekhead((test_jqueue_t*) fixture));
}
static MunitResult test_sem_ijq_peektail(const MunitParameter params[],
void* fixture) {
errno = 0;
return test_no_semfailure(test_jqueue_peektail((test_jqueue_t*) fixture));
}
static MunitResult test_sem_ijq_2proc_enqueue_dequeue(
const MunitParameter params[], void* fixture) {
pid_t pid = fork();
if (pid < -1)
return MUNIT_FAIL;
if (pid == 0) {
// in child
proc_t* cp = new_init_proc();
sem_ipc_jobqueue_t* sijq = sem_ijq_new(cp);
assert_not_null(sijq);
for (int i = 0; i < sem_ijq_capacity(sijq) * 2; i++) {
job_t j = { i, i + 1 };
errno = 0;
assert_true(job_is_equal(sem_ijq_dequeue(sijq), j));
assert_int(errno, ==, 0);
}
sem_ijq_delete(sijq);
proc_delete(cp);
exit(EXIT_SUCCESS);
} else {
// in parent
int child_stat;
proc_t* pp = new_noninit_proc();
sem_ipc_jobqueue_t* sijq = sem_ijq_new(pp);
assert_not_null(sijq);
for (int i = 0; i < sem_ijq_capacity(sijq) * 2; i++) {
job_t j = { i, i+1 };
errno = 0;
sem_ijq_enqueue(sijq, j);
assert_int(errno, ==, 0);
}
waitpid(pid, &child_stat, 0);
assert_false(sem_ijq_is_full(sijq));
assert_true(sem_ijq_is_empty(sijq));
sem_ijq_delete(sijq);
proc_delete(pp);
assert_int(WEXITSTATUS(child_stat), ==, EXIT_SUCCESS);
}
return MUNIT_OK;
}
static MunitResult test_sem_ijq_2proc_peekhead(const MunitParameter params[],
void* fixture) {
pid_t pid = fork();
if (pid < -1)
return MUNIT_FAIL;
if (pid == 0) {
// in child
proc_t* cp = new_init_proc();
sem_ipc_jobqueue_t* sijq = sem_ijq_new(cp);
assert_not_null(sijq);
for (int i = 0; i < sem_ijq_capacity(sijq); i++) {
job_t j = { i, i + 1 };
sem_ijq_enqueue(sijq, j);
errno = 0;
assert_true(job_is_equal(sem_ijq_peektail(sijq), j));
assert_int(errno, ==, 0);
printf(".");
fflush(stdout);
delay_ms(50);
}
printf("\n");
delay_ms(500);
sem_ijq_delete(sijq);
proc_delete(cp);
exit(EXIT_SUCCESS);
} else {
// in parent
int child_stat;
proc_t* pp = new_noninit_proc();
sem_ipc_jobqueue_t* sijq = sem_ijq_new(pp);
assert_not_null(sijq);
int i = 0;
int count = 0;
while (i < sem_ijq_capacity(sijq)) {
errno = 0;
job_t h = sem_ijq_peekhead(sijq);
assert_int(errno, ==, 0);
if (job_is_equal(h, UNUSED_ENTRY))
delay_ms(10);
else {
job_t expected_j = { i, i + 1 };
assert_true(job_is_equal(h, expected_j));
errno = 0;
assert_true(job_is_equal(sem_ijq_dequeue(sijq), expected_j));
assert_int(errno, ==, 0);
i++;
count++;
}
}
assert_int(count, ==, sem_ijq_capacity(sijq));
assert_false(sem_ijq_is_full(sijq));
assert_true(sem_ijq_is_empty(sijq));
jobqueue_t* jq = (jobqueue_t*) sijq->ijq->addr;
for (int i = 0; i < jq->buf_size; i++)
assert_true(job_is_equal(jq->jobs[i], UNUSED_ENTRY));
waitpid(pid, &child_stat, 0);
sem_ijq_delete(sijq);
proc_delete(pp);
assert_int(WEXITSTATUS(child_stat), ==, EXIT_SUCCESS);
}
return MUNIT_OK;
}
static MunitResult test_sem_ijq_2proc_peektail(const MunitParameter params[],
void* fixture) {
pid_t pid = fork();
if (pid < -1)
return MUNIT_FAIL;
if (pid == 0) {
// in child
proc_t* cp = new_init_proc();
sem_ipc_jobqueue_t* sijq = sem_ijq_new(cp);
assert_not_null(sijq);
for (int i = 0; i < sem_ijq_capacity(sijq); i++) {
job_t j = {i, i + 1};
errno = 0;
sem_ijq_enqueue(sijq, j);
assert_int(errno, ==, 0);
printf(".");
fflush(stdout);
delay_ms(20);
}
printf("\n");
sem_ijq_delete(sijq);
proc_delete(cp);
exit(EXIT_SUCCESS);
} else {
// in parent
int child_stat;
proc_t* pp = new_noninit_proc();
sem_ipc_jobqueue_t* sijq = sem_ijq_new(pp);
assert_not_null(sijq);
waitpid(pid, &child_stat, 0);
assert_true(sem_ijq_is_full(sijq));
assert_false(sem_ijq_is_empty(sijq));
int i = 0;
int capacity = sem_ijq_capacity(sijq);
job_t expected_j = { capacity - 1, capacity};
while (i < sem_ijq_capacity(sijq)) {
errno = 0;
job_t jt = sem_ijq_peektail(sijq);
assert_int(errno, ==, 0);
assert_true(job_is_equal(jt, expected_j));
errno = 0;
job_t j = { i, i + 1 };
assert_true(job_is_equal(sem_ijq_dequeue(sijq), j));
assert_int(errno, ==, 0);
i++;
}
assert_false(sem_ijq_is_full(sijq));
assert_true(sem_ijq_is_empty(sijq));
sem_ijq_delete(sijq);
proc_delete(pp);
assert_int(WEXITSTATUS(child_stat), ==, EXIT_SUCCESS);
}
return MUNIT_OK;
}
| 2.21875 | 2 |
2024-11-18T22:11:33.224025+00:00 | 2017-09-29T18:11:47 | 69d747871185556e6d3a401b2b3ad873e9de4c40 | {
"blob_id": "69d747871185556e6d3a401b2b3ad873e9de4c40",
"branch_name": "refs/heads/master",
"committer_date": "2017-09-29T18:11:47",
"content_id": "0ff77b192e725f206ed8ed9c286f617524d6432e",
"detected_licenses": [
"MIT"
],
"directory_id": "c8680091ab8376b149ab2d86bf3eb8641726bd36",
"extension": "c",
"filename": "Lseek.c",
"fork_events_count": 0,
"gha_created_at": "2017-09-12T05:51:54",
"gha_event_created_at": "2017-09-18T16:31:06",
"gha_language": "C",
"gha_license_id": null,
"github_id": 103227946,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1690,
"license": "MIT",
"license_type": "permissive",
"path": "/Lseek.c",
"provenance": "stackv2-0072.json.gz:51994",
"repo_name": "gcsadovy/theCProgrammingLanguage",
"revision_date": "2017-09-29T18:11:47",
"revision_id": "70867c481b8af41042744fb104a43fcd55474739",
"snapshot_id": "5adeba9c4477c1c89043ec1c764efcc6eb3e1373",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/gcsadovy/theCProgrammingLanguage/70867c481b8af41042744fb104a43fcd55474739/Lseek.c",
"visit_date": "2021-07-06T05:42:03.368819"
} | stackv2 | //random access
//input and output are normally sequential; each read or write takes place at a position in the file right after the previous one ;
//when necessary, a file can be read or written in any arbitrary order; the system call lseek provides a way to move around in a file without reading or writing any data
long lseek(int fd, long offset, int origin);
//sets the current position of the file whos descriptor is fd to offset, which is taken relative to the location specified by origin; subsequent reading or writing will begin at that position;
//origin can be 0, 1, 2 to specify that offset is to be measured from the beginning, from the current position, or from the end of file respectively
//for example, to append a file, the redirection >> in unix shell or "a" for fopen, seek to the end before writing
lseek(fd, 0L, 2);
//to get back to the beginning
lseek(fd, 0L, 0)
//the 0L argument could have been written as (long) 0 or just as 0 if lseek is properly declared
//with lseek it is possible to treat files more or less like arrays, at the peice of slower access; for example, the following function reads any number of bytes for any arbitrary place in a file; it returns the number read, or -1 on error:
#include "syscalls.h"
//get: read n bytes from position pos
int get(int fd, long pos, char *buf, int n)
{
if (lseek(fd, pos, 0) >= 0) //to get to pos
return read(fd, buf, n);
else
return -1;
}
//the return value from lseek is a long that gives the new position in the file or -1 if an error occurs
//the stdlib function fseek is similar to lseek except that the first argument is a FILE * and the return is non-zero is an error occurred
| 2.90625 | 3 |
2024-11-18T22:11:33.309761+00:00 | 2022-10-22T17:08:10 | ff6c87acb55a9124372c5dbdcfc35ebcc18a976e | {
"blob_id": "ff6c87acb55a9124372c5dbdcfc35ebcc18a976e",
"branch_name": "refs/heads/master",
"committer_date": "2022-10-22T17:08:10",
"content_id": "5d75d772a8a011285d65c9d7c9d9493ee592cdaf",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "417b35db3cead540fe13a417b01d32c9d3d7fb48",
"extension": "c",
"filename": "perm.c",
"fork_events_count": 8,
"gha_created_at": "2011-06-15T19:26:31",
"gha_event_created_at": "2022-12-09T20:23:20",
"gha_language": "HTML",
"gha_license_id": "BSD-3-Clause",
"github_id": 1902106,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 16697,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/src/perm.c",
"provenance": "stackv2-0072.json.gz:52123",
"repo_name": "olytag/Olympia--The-Age-of-Gods-PBEM",
"revision_date": "2022-10-22T17:08:10",
"revision_id": "c2716b36e4a87b7999a349618f0d7e9866f6ad2b",
"snapshot_id": "cac83b5e505ec1a95088f8a8198b46b36388aa55",
"src_encoding": "UTF-8",
"star_events_count": 6,
"url": "https://raw.githubusercontent.com/olytag/Olympia--The-Age-of-Gods-PBEM/c2716b36e4a87b7999a349618f0d7e9866f6ad2b/src/perm.c",
"visit_date": "2022-11-05T19:02:54.355825"
} | stackv2 |
#include <stdio.h>
#include <string.h>
#include "z.h"
#include "oly.h"
static struct admit *
rp_admit(int pl, int targ) {
int i;
struct entity_player *p;
assert(kind(pl) == T_player);
p = p_player(pl);
for (i = 0; i < ilist_len(p->admits); i++) {
if (p->admits[i]->targ == targ) {
return p->admits[i];
}
}
return NULL;
}
static struct admit *
p_admit(int pl, int targ) {
int i;
struct entity_player *p;
struct admit *new;
assert(kind(pl) == T_player);
p = p_player(pl);
for (i = 0; i < ilist_len(p->admits); i++) {
if (p->admits[i]->targ == targ) {
return p->admits[i];
}
}
new = my_malloc(sizeof(*new));
new->targ = targ;
ilist_append((ilist *) &p->admits, (int) new);
return new;
}
/*
* Will pl admit who into targ?
*/
int
will_admit(int pl, int who, int targ) {
struct admit *p;
int found;
int found_pl;
int found_nation;
/*
* Fri Nov 5 13:02:00 1999 -- Scott Turner
*
* For purposes of admission, a garrison is treated as if it were
* the ruler of the castle, e.g., the garrison will admit you if the
* ruler of the castle would admit you. This is a little odd, perhaps,
* but that's the way the rules are currently written.
*
*/
if (subkind(targ) == sub_garrison) {
targ = province_admin(targ);
pl = targ;
if (!valid_box(targ)) { return FALSE; }
};
pl = player(pl);
if (player(who) == pl) {
return TRUE;
}
p = rp_admit(pl, targ);
if (p == NULL) {
return FALSE;
}
found = ilist_lookup(p->l, who) >= 0;
found_pl = ilist_lookup(p->l, player(who)) >= 0;
found_nation = ilist_lookup(p->l, nation(who)) >= 0;
/*
* Wed Jan 20 12:59:51 1999 -- Scott Turner
*
* If p->sense is true, then we have unit and player
* exclusion, e.g., if the unit or player is true, then
* don't admit them!.
*
*/
if (p->sense) {
if (found || found_pl || found_nation) { return FALSE; }
return TRUE;
} else {
if (found || found_pl || found_nation) {
return TRUE;
}
return FALSE;
}
}
/*
* Wed Jan 20 12:23:16 1999 -- Scott Turner
*
* Add nation admits.
*
*/
int
v_admit(struct command *c) {
int targ = c->a;
int pl = player(c->who);
struct admit *p;
if (!valid_box(targ)) {
wout(c->who, "Must specify an entity for admit.");
return FALSE;
}
cmd_shift(c);
p = p_admit(pl, targ);
if (numargs(c) == 0) {
p->sense = FALSE;
ilist_clear(&p->l);
}
while (numargs(c) > 0) {
if (i_strcmp(c->parse[1], "all") == 0) {
p->sense = TRUE;
} else if (find_nation(c->parse[1])) {
/*
* We can stick the nation # on there because we
* can't have a box number that low (hopefully!).
*
*/
ilist_add(&p->l, find_nation(c->parse[1]));
wout(c->who, "Admitting '%s' to %s.",
rp_nation(find_nation(c->parse[1]))->name,
box_code_less(targ));
} else if (kind(c->a) == T_char ||
kind(c->a) == T_player ||
kind(c->a) == T_unform) {
ilist_add(&p->l, c->a);
} else {
wout(c->who, "%s isn't a valid entity to admit.",
c->parse[1]);
}
cmd_shift(c);
}
return TRUE;
}
static int
admit_comp(a, b)
struct admit **a;
struct admit **b;
{
return (*a)->targ - (*b)->targ;
}
static void
print_admit_sup(int pl, struct admit *p) {
char buf[LEN];
int i;
int count = 0;
sprintf(buf, "admit %4s", box_code_less(p->targ));
if (p->sense) {
strcat(buf, " all");
count++;
}
for (i = 0; i < ilist_len(p->l); i++) {
if (!valid_box(p->l[i])) {
continue;
}
if (++count >= 12) {
out(pl, "%s", buf);
#if 0
sprintf(buf, "admit %4s", p->targ);
#else
strcpy(buf, " ");
#endif
count = 1;
}
if (kind(p->l[i]) == T_nation) {
strcat(buf, sout(" %s", rp_nation(p->l[i])->name));
} else {
strcat(buf, sout(" %4s", box_code_less(p->l[i])));
};
}
if (count) {
out(pl, "%s", buf);
}
}
void
print_admit(int pl) {
struct entity_player *p;
int i;
int first = TRUE;
assert(kind(pl) == T_player);
p = p_player(pl);
if (ilist_len(p->admits) > 0) {
qsort(p->admits, ilist_len(p->admits), sizeof(int), admit_comp);
}
for (i = 0; i < ilist_len(p->admits); i++) {
if (valid_box(p->admits[i]->targ)) {
if (first) {
tagout(pl, "<tag type=header>");
out(pl, "");
tagout(pl, "</tag type=header>");
out(pl, "Admit permissions:");
out(pl, "");
indent += 3;
first = FALSE;
}
print_admit_sup(pl, p->admits[i]);
}
}
if (!first) {
indent -= 3;
}
}
void
clear_all_att(int who) {
struct att_ent *p;
p = rp_disp(who);
if (p == NULL) {
return;
}
ilist_clear(&p->neutral);
ilist_clear(&p->hostile);
ilist_clear(&p->defend);
}
void
clear_att(int who, int disp) {
struct att_ent *p;
p = rp_disp(who);
if (p == NULL) {
return;
}
switch (disp) {
case NEUTRAL:
ilist_clear(&p->neutral);
break;
case HOSTILE:
ilist_clear(&p->hostile);
break;
case DEFEND:
ilist_clear(&p->defend);
break;
case ATT_NONE:
break;
default:
assert(FALSE);
}
}
void
set_att(int who, int targ, int disp) {
struct att_ent *p;
extern int int_comp();
p = p_disp(who);
ilist_rem_value(&p->neutral, targ);
ilist_rem_value(&p->hostile, targ);
ilist_rem_value(&p->defend, targ);
switch (disp) {
case NEUTRAL:
ilist_append(&p->neutral, targ);
qsort(p->neutral, ilist_len(p->neutral), sizeof(int), int_comp);
break;
case HOSTILE:
ilist_append(&p->hostile, targ);
qsort(p->hostile, ilist_len(p->hostile), sizeof(int), int_comp);
break;
case DEFEND:
ilist_append(&p->defend, targ);
qsort(p->defend, ilist_len(p->defend), sizeof(int), int_comp);
break;
case ATT_NONE:
break;
default:
assert(FALSE);
}
}
/*
* Mon May 18 19:07:03 1998 -- Scott Turner
*
* Macro doesn't work because of conceal_nation_ef...
*
#define nation(n) (n && player(n) && rp_player(player(n)) ?
rp_player(player(n))->nation : 0)
*
*/
int
nation(int who) {
int n, pl;
/*
* Sanity checks.
*
*/
if (!valid_box(who)) { return 0; }
/*
* Return the phony nation, if any!
*
*/
n = get_effect(who, ef_conceal_nation, 0, 0);
if (n) {
assert(kind(n) == T_nation);
return n;
};
/*
* A garrison ought to be considered to be of the nation
* of its lord.
*
*/
if (subkind(who) == sub_garrison) {
int ruler = province_admin(who);
if (ruler && rp_player(player(ruler))) {
return rp_player(player(ruler))->nation;
};
};
/*
* A deserted noble ought to be considered still of the nation
* of his old lord, if he has one.
*
*/
pl = player(who);
if (is_real_npc(pl) && body_old_lord(who) &&
rp_player(player(body_old_lord(who)))) {
return rp_player(player(body_old_lord(who)))->nation;
};
/*
* Otherwise...
*
*/
if (pl && rp_player(pl)) {
return rp_player(pl)->nation;
}
return 0;
}
/*
* Try to find a nation.
*
*/
int
find_nation(char *name) {
int i;
loop_nation(i)
{
if (fuzzy_strcmp(rp_nation(i)->name, name) ||
strncasecmp(rp_nation(i)->name, name, strlen(name)) == 0) {
return i;
}
}next_nation;
return 0;
};
/*
* Tue Jan 12 12:11:32 1999 -- Scott Turner
*
* Added support for hostile to monsters.
*
*/
int
is_hostile(who, targ)
int who;
int targ;
{
struct att_ent *p;
if (player(who) == player(targ)) {
return FALSE;
}
if (subkind(who) == sub_garrison) {
struct entity_misc *p;
p = rp_misc(who);
if (p && ilist_lookup(p->garr_host, targ) >= 0) {
return TRUE;
}
}
if (p = rp_disp(who)) {
if (ilist_lookup(p->hostile, targ) >= 0) {
return TRUE;
}
/*
* Mon May 18 19:04:22 1998 -- Scott Turner
*
* Might be a nation...
*
*/
if (nation(targ) && ilist_lookup(p->hostile, nation(targ)) >= 0) {
return TRUE;
};
/*
* Tue Jan 12 12:09:53 1999 -- Scott Turner
*
* Might be a "monster"
*
*/
if (!is_real_npc(who) &&
is_real_npc(targ) &&
kind(targ) == T_char &&
subkind(targ) == sub_ni &&
ilist_lookup(p->hostile, MONSTER_ATT) >= 0) {
return TRUE;
}
}
if (p = rp_disp(player(who))) {
if (ilist_lookup(p->hostile, targ) >= 0) {
return TRUE;
}
/*
* Mon May 18 19:04:22 1998 -- Scott Turner
*
* Might be a nation...
*
*/
if (nation(targ) && ilist_lookup(p->hostile, nation(targ)) >= 0) {
return TRUE;
};
/*
* Tue Jan 12 12:09:53 1999 -- Scott Turner
*
* Might be a "monster"
*
*/
if (!is_real_npc(who) &&
is_real_npc(targ) &&
kind(targ) == T_char &&
subkind(targ) == sub_ni &&
ilist_lookup(p->hostile, MONSTER_ATT) >= 0) {
return TRUE;
}
}
return FALSE;
}
int
is_defend(who, targ)
int who;
int targ;
{
struct att_ent *p;
int pl;
/*
* Mon Mar 3 13:24:58 1997 -- Scott Turner
*
* All npcs defend each other!
*
* Sun Mar 9 20:57:06 1997 -- Scott Turner
*
* A little simplistic. But we should have all intelligent
* NPCs defend each other, and all animals of the same type.
*
*/
if (is_real_npc(who) && is_real_npc(targ) &&
npc_program(who) &&
npc_program(who) != PROG_dumb_monster &&
npc_program(targ) == npc_program(who)) {
wout(who, "Smart enough to help %s in battle.",
box_name(targ));
return TRUE;
};
if (is_real_npc(who) && is_real_npc(targ) &&
subkind(who) == sub_ni &&
subkind(targ) == sub_ni &&
noble_item(who) == noble_item(targ)) {
wout(who, "Rushing to the defense of similar beast %s.",
box_name(targ));
return TRUE;
};
if (is_hostile(who, targ)) {
return FALSE;
}
if (p = rp_disp(who)) {
if (ilist_lookup(p->defend, targ) >= 0) {
return TRUE;
}
if (ilist_lookup(p->neutral, targ) >= 0) {
return FALSE;
}
if (ilist_lookup(p->defend, player(targ)) >= 0) {
return TRUE;
}
if (ilist_lookup(p->neutral, player(targ)) >= 0) {
return FALSE;
}
/*
* Mon May 18 19:04:22 1998 -- Scott Turner
*
* Might be a nation...
*
*/
if (nation(targ) &&
ilist_lookup(p->defend, nation(targ)) >= 0) {
return TRUE;
};
if (nation(targ) &&
ilist_lookup(p->neutral, nation(targ)) >= 0) {
return FALSE;
};
}
pl = player(who);
if (p = rp_disp(pl)) {
if (ilist_lookup(p->defend, targ) >= 0) {
return TRUE;
}
if (ilist_lookup(p->neutral, targ) >= 0) {
return FALSE;
}
if (ilist_lookup(p->defend, player(targ)) >= 0) {
return TRUE;
}
if (ilist_lookup(p->neutral, player(targ)) >= 0) {
return FALSE;
}
/*
* Mon May 18 19:04:22 1998 -- Scott Turner
*
* Might be a nation...
*
*/
if (nation(targ) &&
ilist_lookup(p->defend, nation(targ)) >= 0) {
return TRUE;
};
if (nation(targ) &&
ilist_lookup(p->neutral, nation(targ)) >= 0) {
return FALSE;
};
}
if (pl == player(targ) && pl != indep_player) {
if (cloak_lord(who)) {
return FALSE;
}
return TRUE;
}
return FALSE;
}
/*
* Mon May 18 18:47:41 1998 -- Scott Turner
*
* Accept nation names as well.
*
* Tue Jan 12 11:58:09 1999 -- Scott Turner
*
* Accept "monster" as well?
*
*/
static char *verbs[] = {
"no attitude",
"neutral",
"hostile",
"defend"
};
static int
v_set_att(struct command *c, int k) {
int n;
if (numargs(c) == 0) {
/*
* Clear a list.
*
*/
wout(c->who, "Cleared %s list.", verbs[k]);
clear_att(c->who, k);
return TRUE;
};
while (numargs(c) > 0) {
if (!valid_box(c->a)) {
/*
* Look for a nation name.
*
*/
n = find_nation(c->parse[1]);
if (n) {
set_att(c->who, n, k);
wout(c->who, "Declared %s toward nation %s.",
verbs[k], rp_nation(n)->name);
} else {
/*
* Might be "monster"
*
*/
if (fuzzy_strcmp(c->parse[1], "monster") ||
fuzzy_strcmp(c->parse[1], "monsters")) {
set_att(c->who, MONSTER_ATT, k);
} else {
wout(c->who, "%s is not a valid entity.", c->parse[1]);
};
};
} else if (k == HOSTILE && player(c->who) == player(c->a) &&
player(c->who) != indep_player) {
wout(c->who, "Can't be hostile to a unit in the "
"same faction.");
} else {
set_att(c->who, c->a, k);
wout(c->who, "Declared %s towards %s.",
verbs[k], box_code(c->a));
}
cmd_shift(c);
}
return TRUE;
}
int
v_hostile(struct command *c) {
return v_set_att(c, HOSTILE);
}
int
v_defend(struct command *c) {
return v_set_att(c, DEFEND);
}
int
v_neutral(struct command *c) {
return v_set_att(c, NEUTRAL);
}
int
v_att_clear(struct command *c) {
return v_set_att(c, ATT_NONE);
}
static void
print_att_sup(int who, ilist l, char *header, int *first) {
int i;
int count = 0;
char buf[LEN];
extern int int_comp();
if (ilist_len(l) == 0) {
return;
}
strcpy(buf, header);
qsort(l, ilist_len(l), sizeof(int), int_comp);
for (i = 0; i < ilist_len(l); i++) {
if (l[i] != MONSTER_ATT && !valid_box(l[i])) {
continue;
}
if (*first) {
out(who, "");
out(who, "Declared attitudes:");
out(who, "");
indent += 3;
*first = FALSE;
}
if (++count >= 12) {
out(who, "%s", buf);
sprintf(buf, "%s",
&spaces[spaces_len - strlen(header)]);
count = 1;
}
if (l[i] == MONSTER_ATT) {
strcat(buf, " Monsters ");
} else if (kind(l[i]) == T_nation) {
strcat(buf, sout(" %s", rp_nation(l[i])->name));
} else {
strcat(buf, sout(" %4s", box_code_less(l[i])));
};
}
if (count) {
out(who, "%s", buf);
}
}
void
print_att(int who, int n) {
int first = TRUE;
struct att_ent *p;
p = rp_disp(n);
if (p == NULL) {
return;
}
print_att_sup(who, p->hostile, "hostile", &first);
print_att_sup(who, p->neutral, "neutral", &first);
print_att_sup(who, p->defend, "defend ", &first);
if (!first) {
indent -= 3;
}
}
| 2.5625 | 3 |
2024-11-18T22:11:34.002898+00:00 | 2023-04-04T03:02:47 | 6761349c146fcd21d5ca74f6e204393a18c1f32d | {
"blob_id": "6761349c146fcd21d5ca74f6e204393a18c1f32d",
"branch_name": "refs/heads/master",
"committer_date": "2023-04-04T03:02:47",
"content_id": "e20ab442b5694e16d10c20ddb932d0de19fde2cc",
"detected_licenses": [
"MIT"
],
"directory_id": "fe8942af9cb004c7d91c12845fc7c08c9087aee6",
"extension": "h",
"filename": "IO.h",
"fork_events_count": 0,
"gha_created_at": "2019-08-22T02:18:39",
"gha_event_created_at": "2023-04-09T01:57:22",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 203698016,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 643,
"license": "MIT",
"license_type": "permissive",
"path": "/util/IO.h",
"provenance": "stackv2-0072.json.gz:52379",
"repo_name": "ryco117/yasl",
"revision_date": "2023-04-04T03:02:47",
"revision_id": "25f5bdca4ba6568ba7b25f249ddbb82280f2f85e",
"snapshot_id": "ec278145d7ca5e5896d7f99b70327a290a8d060c",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ryco117/yasl/25f5bdca4ba6568ba7b25f249ddbb82280f2f85e/util/IO.h",
"visit_date": "2023-04-15T11:44:16.505811"
} | stackv2 | #ifndef YASL_IO_H_
#define YASL_IO_H_
#include <stdio.h>
#define NEW_IO(f) ((struct IO) {\
.print = io_print_file,\
.file = (f),\
.string = NULL,\
.len = 0\
})
struct IO {
void (*print)(struct IO *const, const char *const, va_list);
FILE *file;
char *string;
size_t len;
};
void io_cleanup(struct IO *const io);
void io_print_none(struct IO *const io, const char *const format, va_list args);
void io_print_file(struct IO *const io, const char *const format, va_list);
void io_print_string(struct IO *const io, const char *const format, va_list);
size_t io_str_strip_char(char *dest, const char *src, size_t n, char rem);
#endif
| 2 | 2 |
2024-11-18T22:11:40.903215+00:00 | 2020-01-27T14:15:31 | 3b280d70f58614eac52ec9ae54ee919bc64bfc4d | {
"blob_id": "3b280d70f58614eac52ec9ae54ee919bc64bfc4d",
"branch_name": "refs/heads/master",
"committer_date": "2020-01-27T14:15:31",
"content_id": "e81b86c680a71cf39cf44095eb2ee74ef9201a94",
"detected_licenses": [
"MIT"
],
"directory_id": "5f5bda04cb8997a04f2d5ed6d17f5b0bbb78a9bd",
"extension": "h",
"filename": "asc16.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 94961337,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2062,
"license": "MIT",
"license_type": "permissive",
"path": "/test/asc16.h",
"provenance": "stackv2-0072.json.gz:53021",
"repo_name": "GangZhuo/rbtree",
"revision_date": "2020-01-27T14:15:31",
"revision_id": "32bdbe60132098be1bed41b2c6087ad6ec063192",
"snapshot_id": "588a7ba0e117224f9fdb2ef23820b33da79ab89f",
"src_encoding": "GB18030",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/GangZhuo/rbtree/32bdbe60132098be1bed41b2c6087ad6ec063192/test/asc16.h",
"visit_date": "2021-05-23T05:49:50.899505"
} | stackv2 | /*
* MIT License
*
* Copyright (c) 2017 Gang Zhuo <[email protected]>
*
* 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.
*/
#ifndef ASC16_H_
#define ASC16_H_
#ifdef __cplusplus
extern "C" {
#endif
#define ASC16_GYLPH_WIDTH 8 /* 字符的宽度 */
#define ASC16_GYLPH_HEIGHT 16 /* 字符的高度 */
#define ASC16_GYLPH_SIZE 16 /* 单个字符占用的点阵数据字节数 */
#define ASC16_ADVANCE 8 /* 单个字符前进宽度。例如,画出 A 后,后移 10 像素后,画下一个字符 B */
typedef struct asc16_t {
char *data;
int size;
} asc16_t;
#define ASC16_INIT() {0}
#define asc16_init(asc16) \
do { \
(asc16)->data = NULL; \
(asc16)->size = 0; \
} while (0)
#define asc16_is_setpixel(d, i) ((*d) & (0x80 >> i))
#define asc16_gylph_count(asc16) ((asc16)->size / ASC16_GYLPH_SIZE)
#define asc16_gylph_data(asc16, ch) ((asc16)->data + (ASC16_GYLPH_SIZE * (ch)))
void asc16_free(asc16_t *asc16);
int asc16_load(asc16_t *asc16, const char *filename);
void asc16_gylph_print(char *d);
#ifdef __cplusplus
}
#endif
#endif
| 2.234375 | 2 |
2024-11-18T22:11:41.496758+00:00 | 2023-07-24T15:23:29 | 6ca9c241d0edcd2568f5c16d791f1dd31b5e0d87 | {
"blob_id": "6ca9c241d0edcd2568f5c16d791f1dd31b5e0d87",
"branch_name": "refs/heads/devel",
"committer_date": "2023-07-24T15:23:29",
"content_id": "5ab6e94aedc6cc8638ae4fcea29842a69204f735",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "4a1b388fc7254e7f8fa2b72df9d61999bf7df341",
"extension": "c",
"filename": "model_coefficients__functions.c",
"fork_events_count": 17,
"gha_created_at": "2021-02-01T03:29:17",
"gha_event_created_at": "2023-09-06T02:34:56",
"gha_language": "C++",
"gha_license_id": "Apache-2.0",
"github_id": 334819367,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 7278,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/ThirdParty/ros/include/pcl_msgs/msg/detail/model_coefficients__functions.c",
"provenance": "stackv2-0072.json.gz:53277",
"repo_name": "rapyuta-robotics/rclUE",
"revision_date": "2023-07-24T15:23:29",
"revision_id": "7613773cd4c1226957603d705d68a2d2b4a69166",
"snapshot_id": "a2055cf772d7ca4d7c36e991ee9c8920e0475fd2",
"src_encoding": "UTF-8",
"star_events_count": 75,
"url": "https://raw.githubusercontent.com/rapyuta-robotics/rclUE/7613773cd4c1226957603d705d68a2d2b4a69166/ThirdParty/ros/include/pcl_msgs/msg/detail/model_coefficients__functions.c",
"visit_date": "2023-08-19T04:06:31.306109"
} | stackv2 | // generated from rosidl_generator_c/resource/idl__functions.c.em
// with input from pcl_msgs:msg/ModelCoefficients.idl
// generated code does not contain a copyright notice
#include "pcl_msgs/msg/detail/model_coefficients__functions.h"
#include <assert.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include "rcutils/allocator.h"
// Include directives for member types
// Member `header`
#include "std_msgs/msg/detail/header__functions.h"
// Member `values`
#include "rosidl_runtime_c/primitives_sequence_functions.h"
bool
pcl_msgs__msg__ModelCoefficients__init(pcl_msgs__msg__ModelCoefficients * msg)
{
if (!msg) {
return false;
}
// header
if (!std_msgs__msg__Header__init(&msg->header)) {
pcl_msgs__msg__ModelCoefficients__fini(msg);
return false;
}
// values
if (!rosidl_runtime_c__float__Sequence__init(&msg->values, 0)) {
pcl_msgs__msg__ModelCoefficients__fini(msg);
return false;
}
return true;
}
void
pcl_msgs__msg__ModelCoefficients__fini(pcl_msgs__msg__ModelCoefficients * msg)
{
if (!msg) {
return;
}
// header
std_msgs__msg__Header__fini(&msg->header);
// values
rosidl_runtime_c__float__Sequence__fini(&msg->values);
}
bool
pcl_msgs__msg__ModelCoefficients__are_equal(const pcl_msgs__msg__ModelCoefficients * lhs, const pcl_msgs__msg__ModelCoefficients * rhs)
{
if (!lhs || !rhs) {
return false;
}
// header
if (!std_msgs__msg__Header__are_equal(
&(lhs->header), &(rhs->header)))
{
return false;
}
// values
if (!rosidl_runtime_c__float__Sequence__are_equal(
&(lhs->values), &(rhs->values)))
{
return false;
}
return true;
}
bool
pcl_msgs__msg__ModelCoefficients__copy(
const pcl_msgs__msg__ModelCoefficients * input,
pcl_msgs__msg__ModelCoefficients * output)
{
if (!input || !output) {
return false;
}
// header
if (!std_msgs__msg__Header__copy(
&(input->header), &(output->header)))
{
return false;
}
// values
if (!rosidl_runtime_c__float__Sequence__copy(
&(input->values), &(output->values)))
{
return false;
}
return true;
}
pcl_msgs__msg__ModelCoefficients *
pcl_msgs__msg__ModelCoefficients__create()
{
rcutils_allocator_t allocator = rcutils_get_default_allocator();
pcl_msgs__msg__ModelCoefficients * msg = (pcl_msgs__msg__ModelCoefficients *)allocator.allocate(sizeof(pcl_msgs__msg__ModelCoefficients), allocator.state);
if (!msg) {
return NULL;
}
memset(msg, 0, sizeof(pcl_msgs__msg__ModelCoefficients));
bool success = pcl_msgs__msg__ModelCoefficients__init(msg);
if (!success) {
allocator.deallocate(msg, allocator.state);
return NULL;
}
return msg;
}
void
pcl_msgs__msg__ModelCoefficients__destroy(pcl_msgs__msg__ModelCoefficients * msg)
{
rcutils_allocator_t allocator = rcutils_get_default_allocator();
if (msg) {
pcl_msgs__msg__ModelCoefficients__fini(msg);
}
allocator.deallocate(msg, allocator.state);
}
bool
pcl_msgs__msg__ModelCoefficients__Sequence__init(pcl_msgs__msg__ModelCoefficients__Sequence * array, size_t size)
{
if (!array) {
return false;
}
rcutils_allocator_t allocator = rcutils_get_default_allocator();
pcl_msgs__msg__ModelCoefficients * data = NULL;
if (size) {
data = (pcl_msgs__msg__ModelCoefficients *)allocator.zero_allocate(size, sizeof(pcl_msgs__msg__ModelCoefficients), allocator.state);
if (!data) {
return false;
}
// initialize all array elements
size_t i;
for (i = 0; i < size; ++i) {
bool success = pcl_msgs__msg__ModelCoefficients__init(&data[i]);
if (!success) {
break;
}
}
if (i < size) {
// if initialization failed finalize the already initialized array elements
for (; i > 0; --i) {
pcl_msgs__msg__ModelCoefficients__fini(&data[i - 1]);
}
allocator.deallocate(data, allocator.state);
return false;
}
}
array->data = data;
array->size = size;
array->capacity = size;
return true;
}
void
pcl_msgs__msg__ModelCoefficients__Sequence__fini(pcl_msgs__msg__ModelCoefficients__Sequence * array)
{
if (!array) {
return;
}
rcutils_allocator_t allocator = rcutils_get_default_allocator();
if (array->data) {
// ensure that data and capacity values are consistent
assert(array->capacity > 0);
// finalize all array elements
for (size_t i = 0; i < array->capacity; ++i) {
pcl_msgs__msg__ModelCoefficients__fini(&array->data[i]);
}
allocator.deallocate(array->data, allocator.state);
array->data = NULL;
array->size = 0;
array->capacity = 0;
} else {
// ensure that data, size, and capacity values are consistent
assert(0 == array->size);
assert(0 == array->capacity);
}
}
pcl_msgs__msg__ModelCoefficients__Sequence *
pcl_msgs__msg__ModelCoefficients__Sequence__create(size_t size)
{
rcutils_allocator_t allocator = rcutils_get_default_allocator();
pcl_msgs__msg__ModelCoefficients__Sequence * array = (pcl_msgs__msg__ModelCoefficients__Sequence *)allocator.allocate(sizeof(pcl_msgs__msg__ModelCoefficients__Sequence), allocator.state);
if (!array) {
return NULL;
}
bool success = pcl_msgs__msg__ModelCoefficients__Sequence__init(array, size);
if (!success) {
allocator.deallocate(array, allocator.state);
return NULL;
}
return array;
}
void
pcl_msgs__msg__ModelCoefficients__Sequence__destroy(pcl_msgs__msg__ModelCoefficients__Sequence * array)
{
rcutils_allocator_t allocator = rcutils_get_default_allocator();
if (array) {
pcl_msgs__msg__ModelCoefficients__Sequence__fini(array);
}
allocator.deallocate(array, allocator.state);
}
bool
pcl_msgs__msg__ModelCoefficients__Sequence__are_equal(const pcl_msgs__msg__ModelCoefficients__Sequence * lhs, const pcl_msgs__msg__ModelCoefficients__Sequence * rhs)
{
if (!lhs || !rhs) {
return false;
}
if (lhs->size != rhs->size) {
return false;
}
for (size_t i = 0; i < lhs->size; ++i) {
if (!pcl_msgs__msg__ModelCoefficients__are_equal(&(lhs->data[i]), &(rhs->data[i]))) {
return false;
}
}
return true;
}
bool
pcl_msgs__msg__ModelCoefficients__Sequence__copy(
const pcl_msgs__msg__ModelCoefficients__Sequence * input,
pcl_msgs__msg__ModelCoefficients__Sequence * output)
{
if (!input || !output) {
return false;
}
if (output->capacity < input->size) {
const size_t allocation_size =
input->size * sizeof(pcl_msgs__msg__ModelCoefficients);
pcl_msgs__msg__ModelCoefficients * data =
(pcl_msgs__msg__ModelCoefficients *)realloc(output->data, allocation_size);
if (!data) {
return false;
}
for (size_t i = output->capacity; i < input->size; ++i) {
if (!pcl_msgs__msg__ModelCoefficients__init(&data[i])) {
/* free currently allocated and return false */
for (; i-- > output->capacity; ) {
pcl_msgs__msg__ModelCoefficients__fini(&data[i]);
}
free(data);
return false;
}
}
output->data = data;
output->capacity = input->size;
}
output->size = input->size;
for (size_t i = 0; i < input->size; ++i) {
if (!pcl_msgs__msg__ModelCoefficients__copy(
&(input->data[i]), &(output->data[i])))
{
return false;
}
}
return true;
}
| 2.0625 | 2 |
2024-11-18T22:11:41.912665+00:00 | 2023-06-17T17:46:23 | ff0ca80bd1d58d236b6ad48bb5f2d25ac88901d8 | {
"blob_id": "ff0ca80bd1d58d236b6ad48bb5f2d25ac88901d8",
"branch_name": "refs/heads/master",
"committer_date": "2023-07-11T12:25:31",
"content_id": "3c758a42ed038a8247eb0e670c7a08699a6ce112",
"detected_licenses": [
"Unlicense"
],
"directory_id": "01ace0f357a25a895df67b2fe60020a9e9713766",
"extension": "c",
"filename": "test_borrow.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 147276452,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4048,
"license": "Unlicense",
"license_type": "permissive",
"path": "/libhttp/test_borrow.c",
"provenance": "stackv2-0072.json.gz:53663",
"repo_name": "Splintermail/splintermail-client",
"revision_date": "2023-06-17T17:46:23",
"revision_id": "029757f727e338d7c9fa251ea71a894097426146",
"snapshot_id": "10e7f370b6859e1ae5d75bdaa89f4f1d24e9bb81",
"src_encoding": "UTF-8",
"star_events_count": 4,
"url": "https://raw.githubusercontent.com/Splintermail/splintermail-client/029757f727e338d7c9fa251ea71a894097426146/libhttp/test_borrow.c",
"visit_date": "2023-07-21T15:36:03.409326"
} | stackv2 | #include "libdstr/libdstr.h"
#include "libduv/libduv.h"
#include "libhttp/libhttp.h"
#include "test/test_utils.h"
static derr_t E = {0};
static bool finished = false;
static void write_cb(stream_i *stream, stream_write_t *write){
(void)stream;
(void)write;
}
static void await_cb(rstream_i *rstream, derr_t e, link_t *reads){
(void)rstream;
KEEP_FIRST_IF_NOT_CANCELED_VAR(&E, &e);
finished = true;
if(!link_list_isempty(reads)){
TRACE_ORIG(&E, E_VALUE, "unfinished reads");
}
}
static void read_cb3(rstream_i *rstream, rstream_read_t *read, dstr_t buf){
(void)read;
// expect eof
EXPECT_D_GO(&E, "buf", buf, DSTR_LIT(""), fail);
return;
fail:
rstream->cancel(rstream);
}
static void read_cb2(rstream_i *rstream, rstream_read_t *read, dstr_t buf){
(void)read;
EXPECT_D_GO(&E, "buf", buf, DSTR_LIT("world!"), fail);
// trigger the final read
buf.len = 0;
stream_must_read(rstream, read, buf, read_cb3);
return;
fail:
rstream->cancel(rstream);
}
static void read_cb1(rstream_i *rstream, rstream_read_t *read, dstr_t buf){
(void)read;
EXPECT_D_GO(&E, "buf", buf, DSTR_LIT("hello "), fail);
return;
fail:
rstream->cancel(rstream);
}
static derr_t test_borrow(void){
derr_t e = E_OK;
manual_scheduler_t scheduler;
scheduler_i *sched = manual_scheduler(&scheduler);
dstr_stream_t dstr_s;
DSTR_STATIC(rbase, "hello world!");
DSTR_VAR(wbase, 1);
borrow_rstream_t borrow;
stream_i *base = dstr_stream(&dstr_s, sched, rbase, &wbase);
rstream_i *r = borrow_rstream(&borrow, sched, base);
stream_must_await_first(r, await_cb);
rstream_read_t read1, read2;
DSTR_VAR(rbuf1, 6);
DSTR_VAR(rbuf2, 6);
// start first two reads
stream_must_read(r, &read1, rbuf1, read_cb1);
stream_must_read(r, &read2, rbuf2, read_cb2);
// run to completion
manual_scheduler_run(&scheduler);
PROP_VAR(&e, &E);
if(!finished) ORIG(&e, E_VALUE, "borrow did not finish");
// when base is eof, it must also be canceled and awaited
EXPECT_B(&e, "base->eof", base->eof, true);
EXPECT_B(&e, "base->canceled", base->canceled, true);
EXPECT_B(&e, "base->awaited", base->awaited, true);
// reset, then cancel the borrow stream
finished = false;
base = dstr_stream(&dstr_s, sched, rbase, &wbase);
r = borrow_rstream(&borrow, sched, base);
stream_must_await_first(r, await_cb);
r->cancel(r);
manual_scheduler_run(&scheduler);
EXPECT_E_VAR(&e, "E", &E, E_CANCELED);
if(!finished) ORIG(&e, E_VALUE, "borrow did not finish");
EXPECT_B(&e, "base->canceled", base->canceled, true);
EXPECT_B(&e, "base->awaited", base->awaited, true);
// reset, then cancel the underlying stream
finished = false;
base = dstr_stream(&dstr_s, sched, rbase, &wbase);
r = borrow_rstream(&borrow, sched, base);
stream_must_await_first(r, await_cb);
base->cancel(base);
manual_scheduler_run(&scheduler);
EXPECT_E_VAR(&e, "E", &E, E_INTERNAL);
if(!finished) ORIG(&e, E_VALUE, "borrow did not finish");
EXPECT_B(&e, "base->awaited", base->awaited, true);
// reset, then cause a failure in the underlying stream
finished = false;
base = dstr_stream(&dstr_s, sched, rbase, &wbase);
r = borrow_rstream(&borrow, sched, base);
stream_must_await_first(r, await_cb);
stream_write_t write;
stream_must_write(base, &write, &DSTR_LIT("abc"), 1, write_cb);
manual_scheduler_run(&scheduler);
EXPECT_E_VAR(&e, "E", &E, E_FIXEDSIZE);
if(!finished) ORIG(&e, E_VALUE, "borrow did not finish");
EXPECT_B(&e, "base->awaited", base->awaited, true);
return e;
}
int main(int argc, char **argv){
derr_t e = E_OK;
// parse options and set default log level
PARSE_TEST_OPTIONS(argc, argv, NULL, LOG_LVL_INFO);
PROP_GO(&e, test_borrow(), test_fail);
LOG_ERROR("PASS\n");
return 0;
test_fail:
DUMP(e);
DROP_VAR(&e);
LOG_ERROR("FAIL\n");
return 1;
}
| 2.1875 | 2 |
2024-11-18T20:14:01.782638+00:00 | 2017-10-08T21:26:01 | 426c8b60741a2fc8240ca6f178cbf7a6be84b114 | {
"blob_id": "426c8b60741a2fc8240ca6f178cbf7a6be84b114",
"branch_name": "refs/heads/master",
"committer_date": "2017-10-08T21:26:01",
"content_id": "0dd1be841a1057521ec862cb7b14c81de6a42b29",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "6818bd4c663a5aa7941bdbbfd51940c64d5d8e6d",
"extension": "c",
"filename": "matrix.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 105932434,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 13836,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/matrix.c",
"provenance": "stackv2-0072.json.gz:302654",
"repo_name": "nottu/metNum",
"revision_date": "2017-10-08T21:26:01",
"revision_id": "eb25bd0586910eafeec8590d0dc09525f7b415f7",
"snapshot_id": "f66311c1ab293bd37ae0b3fb113d6f4be59a3e54",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/nottu/metNum/eb25bd0586910eafeec8590d0dc09525f7b415f7/matrix.c",
"visit_date": "2021-07-09T10:55:10.701396"
} | stackv2 | //
// Created by Javier Peralta on 9/16/17.
//
#include "matrix.h"
//#include <omp.h>
void vectorScalar (double *v, double d, int size){
for(int i = 0; i < size; ++i ){
v[i] *= d;
}
}
void restaVector(double *v1, double *v2, double* out, int size){
//#pragma omp parallel for
for(int i = 0; i < size; ++i ){
out[i] = v1[i] - v2[i];
}
}
void sumaVector(double *v1, double *v2, double* out, int size){
//#pragma omp parallel for
for(int i = 0; i < size; ++i ){
out[i] = v1[i] + v2[i];
}
}
void multVector(double *vec1, double *vec2, double* out, int size){
//#pragma omp parallel for
for (int i = 0; i < size; i++) {
out[i] = vec1[i] * vec2[i];
}
}
double productoPunto(double *vec1, double *vec2, int size){
double c = 0;
for (int i = 0; i < size; i++) {
c += vec1[i] * vec2[i];
}
return c;
}
void productoPuntoA(double *vec1, double *vec2, double* vec3, int size){
//#pragma omp parallel for
for (int i = 0; i < size; i++) {
vec3[i] = vec1[i] * vec2[i];
}
}
void multMatriz(double **mat1, double **mat2, int n, int m, int p, int q, double **res){
//fila * columna
if (m != p) {
perror("Numero de filas de la primera matriz debe ser igual numero de columnas de la segunda\n");
return;
}
//#pragma omp parallel for
for (int i = 0; i < n; ++i) {
double *fila = res[i];
//#pragma omp parallel for
for (int j = 0; j < q; ++j) {
double c = 0;
//#pragma omp parallel for reduction(+:c)
for (int k = 0; k < m; ++k) {
c += mat1[i][k] * mat2[k][j];
}
fila[j] = c;
}
}
}
void multMatrizVect(double **mat, double *vec, int n, int m, double* res){
for (int i = 0; i < n; i++) {
res[i] = productoPunto(mat[i], vec, m);
}
}
//other
void printVect(double * a, int n){
for (int i = 0; i < n; ++i) {
if(a[i] >= 0) printf(" ");
printf("%3.3lf ", a[i]);
}
printf("\n");
}
void printMtx(double**a, int nr, int nc){
for (int i = 0; i < nr; ++i) {
printVect(a[i], nc);
}
}
void printMtxT(double**a, int nr, int nc){
for (int i = 0; i < nc; ++i) {
for (int j = 0; j < nr; ++j) {
if(a[j][i] >= 0) printf(" ");
printf("%3.3lf ", a[j][i]);
}
printf("\n");
}
}
double *readVector(char* name, int* sz){
FILE *f = fopen(name, "rb");
if (!f) return NULL;
fread(sz, sizeof(int), 1, f);
double *vect = malloc(sizeof(double) * *sz);
for (int i = 0; i < *sz; ++i) {
fread(vect, sizeof(double), *sz, f);
}
fclose(f);
return vect;
}
double **readMtx(char* name, int* nr, int* nc){
FILE *f = fopen(name, "rb");
if (!f) return NULL;
fread(nr, sizeof(int), 1, f);
fread(nc, sizeof(int), 1, f);
double **mtx = allocMtx(*nr, *nc);
for (int i = 0; i < *nr; ++i) {
fread(mtx[i], sizeof(double), (unsigned int)*nc, f);
}
fclose(f);
return mtx;
}
double **allocMtx(int nr, int nc){
double **mtx = malloc((sizeof(double*)*nr) + sizeof(int));
int *indi = (int*)mtx;
mtx = (void*)indi+ sizeof(int);
if(nr * nc * sizeof(double) < MTXMAXSIZE) {
indi[0] = 0; //indicate 1 block
mtx[0] = malloc(sizeof(double) * nr*nc);
for (int i = 1; i < nr; ++i) {
mtx[i] = mtx[i-1] + nc;
}
} else {
indi[0] = nr; //indicate nr block
for (int i = 0; i < nr; ++i) {
mtx[i] = malloc(sizeof(double) * nc);
}
}
return mtx;
}
double** allocMtxI(int n){
double ** mtx = allocMtx(n, n);
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
mtx[i][j] = j == i ? 1 : 0;
}
}
return mtx;
}
void freeMtx(double**a){
if(a == NULL) return; //nothing to free...
void *indi = (void*)a - sizeof(int);
int nr = ((int*)indi)[0];
if(nr){
for (int i = 0; i < nr; ++i) free(a[i]);
}
else free(a[0]);
free(indi);
}
//
double norma2Vect(double* v, int size){
return sqrt(norma2VectSq(v, size));
}
double norma2VectSq(double* v, int size){
double c = 0;
//#pragma omp parallel for reduction(+:c)
for (int i = 0; i < size; i++) {
double val = v[i];
c += val * val;
}
return c;
}
void normalizaVect(double *v, int size){
double norm = sqrt(norma2VectSq(v, size));
for (int i = 0; i < size; i++) v[i] /= norm;
}
double diffVectSq(double* v1, double* v2, int size){
double c = 0;
//#pragma omp parallel for reduction(+:c)
for (int i = 0; i < size; i++) {
double val = v1[i] - v2[i];
c += val * val;
}
return c;
}
double diffMatrizSq(double** m1, double** m2, int nr, int nc){
//#pragma omp parallel for reduction(+:c)
double c = 0;
int sz = nr*nc;
for (int i = 0; i < sz; ++i) {
double dif = m1[0][i] - m2[0][i];
c += dif* dif;
}
return c;
}
double* diagSol(double*a , double*b, int n){
double *vect = malloc(sizeof(double) * n);
//#pragma omp parallel
for (int i = 0; i < n; ++i) {
if (a[i] == 0){
if (b[i] != 0){
printf("Sin solución, X%d no tiene valor\n", i);
return NULL;
}
printf("Multiples Soluciones, X%d puede tener cualquier valor\n", i);
vect[i] = 0;
continue;
}
vect[i] = b[i]/a[i];
}
return vect;
}
double* upperSol(double**a , double*b, int nr, int nc){
double *vect = malloc(sizeof(double) * nc);
for (int i = nr -1; i >= 0; i--) {
double tmp = b[i];
for (int j = i+1; j < nc; ++j) {
tmp -= vect[j] * a[i][j];
}
vect[i] = tmp / a[i][i];
}
return vect;
}
double* lowerSol(double**a , double*b, int nr, int nc){
double *vect = malloc(sizeof(double) * nc);
for (int i = 0; i < nr; ++i) {
double tmp = b[i];
for (int j = 0; j < i && j < nc; ++j) {
tmp -= vect[j] * a[i][j];
}
tmp /= a[i][i];
vect[i] = tmp;
}
return vect;
}
int luFactor(double** a, double **l, double **u, int nr, int nc){
for (int i = 0; i < nr; ++i) {
u[i][i] = 1;
for (int j = 0; j <= i && j <nc; ++j) {
double lij = a[i][j];
for (int k = 0; k < j; ++k) {
lij -= l[i][k]*u[k][j];
}
l[i][j] = lij;
}
for (int j = i+1; j < nc; ++j) {
double lij = a[i][j];
if(fabs(l[i][i]) < ZERO)
return 0;
for (int k = 0; k < i; ++k) {
lij -= l[i][k]*u[k][j];
}
lij /= l[i][i];
u[i][j] = lij;
}
}
return 1;
}
double* luSolver(double **l, double **u, double *b, int nr, int nc){
double* sol = lowerSol(l, b, nr, nc);
double* sol2 = upperSol(u, sol, nr, nc);
free(sol);
return sol2;
}
//same as lu factor, but in 1 matrix
int luFactor2(double **a, int nr, int nc){
for (int i = 0; i < nr; ++i) {
for (int j = 0; j <= i && j <nc; ++j) {
double lij = a[i][j];
for (int k = 0; k < j; ++k) {
lij -= a[i][k]*a[k][j];
}
a[i][j] = lij;
}
for (int j = i+1; j < nc; ++j) {
double lij = a[i][j];
if(fabs(a[i][i]) < ZERO)
return 0;
for (int k = 0; k < i; ++k) {
lij -= a[i][k]*a[k][j];
}
lij /= a[i][i];
a[i][j] = lij;
}
}
return 1;
}
double* luSolver2(double **a, double *b, int nr, int nc){
double* sol = lowerSol(a, b, nr, nc);
//need to do upper sol with upper a and 1 in diagonal
for (int i = nr -1; i >= 0; i--) {
double tmp = sol[i];
for (int j = i+1; j < nc; ++j) {
tmp -= sol[j] * a[i][j];
}
sol[i] = tmp;
}
return sol;
}
double* triDiagSol(double **a, double *d, int nr, int nc){
double *xi = malloc(sizeof(double) * nr);
double *ax = a[0], *bx = a[1], *cx = a[2];
cx[0] /= bx[0];
d[0] /= bx[0];
for (int i = 1; i < nc; ++i) {
double ptemp = bx[i] - (ax[i] * cx[i-1]);
cx[i] /= ptemp;
d[i] = (d[i] - ax[i] * d[i-1])/ptemp;
}
xi[nr-1] = d[nr-1];
for (int i = nr-2; i >= 0; --i) {
xi[i] = d[i] - cx[i] * xi[i+1];
}
return xi;
}
double potencia(double **mat, double *eigvec, int nr, int nc, int maxIter, double toler){
double error;
for (int i = 0; i < nr; ++i) eigvec[i] = 1;
double *y = malloc(sizeof(double) * nr);
double *vt = malloc(sizeof(double) * nr);
double eigV = 0;
int i = 0;
do {
multMatrizVect(mat, eigvec, nr, nc, y);
memcpy(eigvec, y, nr * sizeof(double));
normalizaVect(eigvec, nr);
multMatrizVect(mat, eigvec, nr, nc, vt);
eigV = productoPunto(eigvec, vt, nr);
memcpy(vt, eigvec, nr * sizeof(double));
vectorScalar(vt, eigV, nr);
restaVector(y, vt, vt, nr);
error = norma2Vect(vt, nr);
}
while(++i < maxIter && error > toler);
free(y); free(vt);
// printf("Matriz tam %d x %d\n", nr, nc);
// printf("Valor lambda %lf\n", eigV);
// printf("Iteraciones realizadas %d\n", i);
// printf("Error %g\n", error);
return eigV;
}
double smallestEigv(double **mat, double *eigvec, int n, int m, int maxIter, double toler){
double **inv = allocMtx(m, n);
inverseMtx(mat, inv, n, m);
double lam = potencia(inv, eigvec, m, n, 1000, 0.0001);
freeMtx(inv);
return fabs(lam) > ZERO ? 1/lam : lam;
}
double nearestEigv(double **mat, double *eigvec, double val, int n, int m, int maxIter, double toler){
for (int i = 0; i < n; ++i) {
mat[i][i] -= val;
}
double l = smallestEigv(mat, eigvec, n, m, maxIter, toler);
for (int i = 0; i < n; ++i) {
mat[i][i] += val;
}
return val + l;
}
double potenciaInv(double **mat, double *eigvec, double val, int n, int m, int maxIter, double toler, int *k, double *err){
for (int i = 0; i < n; ++i) {
mat[i][i] -= val;
}
double **inv = allocMtx(m, n);
inverseMtx(mat, inv, n, m);
for (int i = 0; i < n; ++i) eigvec[i] = 1;
double *y = malloc(sizeof(double) * n);
double *px = malloc(sizeof(double) * n);
double mu = 0;
do {
multMatrizVect(inv, eigvec, n, m, y);
double norm = norma2Vect(y, n);
vectorScalar(y, 1/norm, n); //x^
vectorScalar(eigvec, 1/norm, n); //w
mu = productoPunto(y, eigvec, n);
memcpy(px, y, sizeof(double) * n);
vectorScalar(px, mu, n);
mu += val;
restaVector(eigvec, px, px, n);
memcpy(eigvec, y, sizeof(double) *n);
*k += 1;
*err = norma2Vect(px, n);
} while(*err > toler && maxIter > *k);
for (int i = 0; i < n; ++i) {
mat[i][i] += val;
}
free(px);
free(y);
freeMtx(inv);
return mu;
}
double* allEigv(double **mat, int n, int m, int maxIter, double toler, int sections){
double d = normaInf(mat, n, m);
double delta = 2*d/sections;
double *eigvals = malloc(sizeof(double) * n);
for (int i = 0; i < n; ++i) eigvals[i] = NAN;
double *eigVect = malloc(sizeof(double) * n);
int i = 0;
int k;
double err;
for (int t = 0; t <= sections; ++t) {
k = 0;
double aprox = -d + t*delta;
double val = potenciaInv(mat, eigVect, aprox, n, m, maxIter, toler, &k, &err);
if((i==0 || fabs(val - eigvals[i-1]) > 0.0001) && err < toler){
eigvals[i++] = val;
printf("----------------\nValor mu %lf\n", val);
printf("Iteraciones realizadas %d\n", k);
printf("||r|| %g\n----------------\n", err);
}
}
free(eigVect);
return eigvals;
}
double normaInf(double **m1, int n, int m){
double max = 0;
for (int i = 0; i < n; ++i) {
double sum = 0;
for (int j = 0; j < m; ++j) {
sum += fabs(m1[i][j]);
}
if(sum > max) max = sum;
}
return max;
}
void inverseMtx(double **mat, double **inv, int n, int m){
double **l = allocMtx(n, m);
double **u = allocMtx(n, m);
if (luFactor(mat, l, u, n, m)){
double *b = malloc(sizeof(double) * m);
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
b[j] = j == i;
}
double *sol = luSolver(l, u, b, n, m);
for (int j = 0; j < n; ++j) {
inv[j][i] = sol[j];
}
free(sol);
}
free(b);
}
freeMtx(l); freeMtx(u);
}
//jacobi
double valMayor(double **mat, int n, int m, int *x, int *y){
double mayor = 0;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
if (i == j) continue;
if(mayor < fabs(mat[i][j])){
mayor = fabs(mat[i][j]);
*x = i; *y = j;
}
}
}
return mayor;
}
//GT * A * G
void givensRotate(double **mat, int n, int m, int mi, int mj, double c, double s){
for (int i = 0; i < m; ++i) {
double matimi = mat[i][mi];
mat[i][mi] = matimi * c - s*mat[i][mj];
mat[i][mj] = matimi * s + c*mat[i][mj];
}
for (int i = 0; i < n; ++i) {
double matmii = mat[mi][i];
mat[mi][i] = mat[mi][i] * c - s*mat[mj][i];
mat[mj][i] = matmii * s + c*mat[mj][i];
}
}
void givensM(double **mat, int n, int m, int mi, int mj, double c, double s){
for (int i = 0; i < m; ++i) {
double matimi = mat[i][mi];
mat[i][mi] = matimi * c - s*mat[i][mj];
mat[i][mj] = matimi * s + c*mat[i][mj];
}
}
double* jacobiEig(double **mat, double**eigVec, int n, int m, int maxIter, double toler){
int x, y;
double max = valMayor(mat, n, m, &x, &y);
if(max < toler) return NULL; //eigvs in diag
double **eigvalsM = allocMtx(n, m);
for (int i = 0; i < n; ++i) memcpy(eigvalsM[i], mat[i], sizeof(double) * m);
int iter = 0;
while (max > toler && ++iter < maxIter){
double d = (eigvalsM[y][y] - eigvalsM[x][x])/(2 * eigvalsM[x][y]);
double t = 1 / (fabs(d) + sqrt(1 + d*d));
t = d > 0 ? t : -t;
double c = 1/(sqrt(1 + t * t));
double s = c * t;
givensRotate(eigvalsM, n, m, x, y, c, s);
givensM(eigVec, n, n, x, y, c, s);
max = valMayor(eigvalsM, n, m, &x, &y);
}
//printf("--------\n");printMtx(eigvalsM, n, m);
//printf("--------\n");printMtx(eigVec, n, m);
printf("Iteraciones: %d\n", iter);
double **AV = allocMtx(n, m);
multMatriz(mat, eigVec, n, m, m, n, AV);
double **VD = allocMtx(n, m);
multMatriz(eigVec, eigvalsM, n, m, m, n, VD);
printf("||AV - VD|| = %g\n", sqrt(diffMatrizSq(AV, VD, n, m)));
freeMtx(VD); freeMtx(AV);
double *eigvals = malloc(sizeof(double) * n);
for (int i = 0; i < n; ++i) {
eigvals[i] = eigvalsM[i][i];
}
freeMtx(eigvalsM);
return eigvals;
} | 2.953125 | 3 |
2024-11-18T20:14:02.047759+00:00 | 2018-08-14T12:52:18 | 716971c09804d1cf97cabecc1cae0c0dca873b1a | {
"blob_id": "716971c09804d1cf97cabecc1cae0c0dca873b1a",
"branch_name": "refs/heads/master",
"committer_date": "2018-08-14T12:52:18",
"content_id": "f571ace70d63a90e255588eb8446cf23d49f9846",
"detected_licenses": [
"MIT"
],
"directory_id": "8fcf62cb9f1b7191083a5f9322b4a7eb81e2647f",
"extension": "c",
"filename": "LSQueue.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 128032683,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1188,
"license": "MIT",
"license_type": "permissive",
"path": "/c/unit3/unit3/LSQueue.c",
"provenance": "stackv2-0072.json.gz:302783",
"repo_name": "cnzht/grit",
"revision_date": "2018-08-14T12:52:18",
"revision_id": "eab457a0a9b216f5a6026669095b8126bf8a9e1d",
"snapshot_id": "0b5b0d3f137530ed0cac246a0de314807632e6af",
"src_encoding": "GB18030",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/cnzht/grit/eab457a0a9b216f5a6026669095b8126bf8a9e1d/c/unit3/unit3/LSQueue.c",
"visit_date": "2020-03-08T08:52:18.583920"
} | stackv2 | #include "LSQueue.h"
/*
void QueueInitiate(SeqQueue *);//初始化队列;
int QueueNoEmpty(SeqQueue);//判断队列是否为空;
int QueueAppend(SeqQueue *, DataType x);//入队;
int QueueDelete(SeqQueue *, DataType *x);//出队;
int QueueGet(SeqQueue, DataType *x);//取队头;
*/
void QueueInitiate(SeqQueue * Q)//初始化队列;
{
Q->front = 0;
Q->rear = 0;
Q->count = 0;
}
int QueueNoEmpty(SeqQueue Q)//判断队列是否为空;
{
if (Q.count==0)
{
return 0;
}
else
{
return 1;
}
}
int QueueAppend(SeqQueue * Q, DataType x)//入队;
{
if (Q->count>0&&Q->rear==Q->front)
{
printf("队列已满!");
return 0;
}
else
{
Q->queue[Q->rear]= x;
Q->rear=(Q->rear+1)%MaxQueueSize ;//关键!!1~maxqueuesize;
Q->count++;
return 1;
}
}
int QueueDelete(SeqQueue * Q, DataType *x)//出队;
{
if (Q->count==0)
{
printf("队列已空!");
return 0;
}
else
{
*x = Q->queue[Q->front];
Q->front = (Q->front + 1) % MaxQueueSize;
Q->count--;
return 1;
}
}
int QueueGet(SeqQueue Q, DataType *x)//取队头;
{
if (Q.count == 0)
{
printf("队列已空!");
return 0;
}
else
{
*x = Q.queue[Q.front];
return 1;
}
} | 3.1875 | 3 |
2024-11-18T20:14:02.271754+00:00 | 2020-12-22T15:50:14 | e82eb1d655aa309baa01c13bd2915c390eb7a01d | {
"blob_id": "e82eb1d655aa309baa01c13bd2915c390eb7a01d",
"branch_name": "refs/heads/master",
"committer_date": "2020-12-22T15:50:14",
"content_id": "b6f45348362f2e3d4038e1d11f4bee10a35c5cd3",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "eb38fbdbc62b332a549b28fe346d5dbd07f03645",
"extension": "c",
"filename": "edgex-base.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": 1949,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/c/edgex-base.c",
"provenance": "stackv2-0072.json.gz:303040",
"repo_name": "wendaoji/device-sdk-c",
"revision_date": "2020-12-22T15:50:14",
"revision_id": "f0de00cff149ffe86b90fb2b2675cd2706e94b93",
"snapshot_id": "177e1e24936829151b1966601128cd8de233ee8f",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/wendaoji/device-sdk-c/f0de00cff149ffe86b90fb2b2675cd2706e94b93/src/c/edgex-base.c",
"visit_date": "2023-02-04T16:41:19.928107"
} | stackv2 | /*
* Copyright (c) 2019
* IoTech Ltd
*
* SPDX-License-Identifier: Apache-2.0
*
*/
#include <errno.h>
#include "edgex/edgex-base.h"
#include "iot/typecode.h"
static edgex_propertytype typeForArray[] =
{
Edgex_Int8Array, Edgex_Uint8Array, Edgex_Int16Array, Edgex_Uint16Array, Edgex_Int32Array, Edgex_Uint32Array,
Edgex_Int64Array, Edgex_Uint64Array, Edgex_Float32Array, Edgex_Float64Array, Edgex_BoolArray
};
edgex_propertytype edgex_propertytype_data (const iot_data_t *data)
{
edgex_propertytype res = iot_data_type (data);
if (res == Edgex_Binary && iot_data_get_metadata (data) == NULL)
{
iot_data_type_t at = iot_data_array_type (data);
res = (at <= IOT_DATA_BOOL) ? typeForArray [at] : Edgex_Unused1;
}
return res;
}
edgex_propertytype edgex_propertytype_typecode (const iot_typecode_t *tc)
{
edgex_propertytype res = iot_typecode_type (tc);
if (res == Edgex_Binary)
{
iot_data_type_t at = iot_typecode_type (iot_typecode_element_type (tc));
res = (at <= IOT_DATA_BOOL) ? typeForArray [at] : Edgex_Unused1;
}
return res;
}
edgex_nvpairs *edgex_nvpairs_new (const char *name, const char *value, edgex_nvpairs *list)
{
return devsdk_nvpairs_new (name, value, list);
}
const char *edgex_nvpairs_value (const edgex_nvpairs *nvp, const char *name)
{
return devsdk_nvpairs_value (nvp, name);
}
bool edgex_nvpairs_long_value (const edgex_nvpairs *nvp, const char *name, long *val)
{
return devsdk_nvpairs_long_value (nvp, name, val);
}
bool edgex_nvpairs_ulong_value (const edgex_nvpairs *nvp, const char *name, unsigned long *val)
{
return devsdk_nvpairs_ulong_value (nvp, name, val);
}
bool edgex_nvpairs_float_value (const edgex_nvpairs *nvp, const char *name, float *val)
{
return devsdk_nvpairs_float_value (nvp, name, val);
}
const edgex_nvpairs *edgex_protocols_properties (const devsdk_protocols *prots, const char *name)
{
return devsdk_protocols_properties (prots, name);
}
| 2.09375 | 2 |
2024-11-18T20:14:02.442810+00:00 | 2021-10-29T19:33:34 | c3bc1b16035336d9ba17afa0dce9656dfff9e792 | {
"blob_id": "c3bc1b16035336d9ba17afa0dce9656dfff9e792",
"branch_name": "refs/heads/main",
"committer_date": "2021-10-29T19:33:34",
"content_id": "df8fe72f85c3b750ae5b3dcefd22d680942fa614",
"detected_licenses": [
"MIT"
],
"directory_id": "d6f4245de8d48703508b9b1430b042867625de68",
"extension": "c",
"filename": "sigma_false-unreach-call.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": 838,
"license": "MIT",
"license_type": "permissive",
"path": "/test/c/pthread_extras/sigma_false-unreach-call.c",
"provenance": "stackv2-0072.json.gz:303296",
"repo_name": "songfu1983/smack",
"revision_date": "2021-10-29T19:33:34",
"revision_id": "c7d0694f08cefb422ebcc67c23824727b06b370e",
"snapshot_id": "7d6193a89aeda544638ef1f6b5cdddf6a7a1f910",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/songfu1983/smack/c7d0694f08cefb422ebcc67c23824727b06b370e/test/c/pthread_extras/sigma_false-unreach-call.c",
"visit_date": "2023-08-23T03:11:27.907783"
} | stackv2 | #include "pthread.h"
#include "smack.h"
#include <assert.h>
#include <stdlib.h>
#include <string.h>
// @expect error
// @flag --unroll=6
const int SIGMA = 5;
int *array;
int array_index = 0;
void *thread(void *arg) {
array[array_index] = 1;
return 0;
}
int main() {
int tid, sum;
pthread_t *t;
t = (pthread_t *)malloc(sizeof(pthread_t) * SIGMA);
array = (int *)malloc(sizeof(int) * SIGMA);
// assume(t);
// assume(array);
for (tid = 0; tid < SIGMA; tid++) {
pthread_create(&t[tid], 0, thread, 0);
array_index++;
}
for (tid = 0; tid < SIGMA; tid++) {
pthread_join(t[tid], 0);
}
for (tid = sum = 0; tid < SIGMA; tid++) {
sum += array[tid];
}
assert(sum == SIGMA); // <-- wrong, different threads might use the same array
// offset when writing
return 0;
}
| 2.8125 | 3 |
2024-11-18T20:41:22.218495+00:00 | 2016-11-23T20:47:39 | 15f2b4a5460c2d6f7ec627a9939f4b6adcfa8a30 | {
"blob_id": "15f2b4a5460c2d6f7ec627a9939f4b6adcfa8a30",
"branch_name": "refs/heads/master",
"committer_date": "2016-11-23T20:47:39",
"content_id": "7f6efdd35babdc949b5441f421a1869a3f927efa",
"detected_licenses": [
"MIT"
],
"directory_id": "9bd94e148e4ddaece3f96847c63fbcbc16db9db6",
"extension": "c",
"filename": "timer.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 74610502,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 966,
"license": "MIT",
"license_type": "permissive",
"path": "/interrupt-master/src/timer.c",
"provenance": "stackv2-0074.json.gz:64764",
"repo_name": "Jraylward0/interrupt-master",
"revision_date": "2016-11-23T20:47:39",
"revision_id": "5d74b51ae213ab28efb7c389c13eedee62df022a",
"snapshot_id": "8f657ace8c99e897b8bb70202d79eb9f82131e8a",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Jraylward0/interrupt-master/5d74b51ae213ab28efb7c389c13eedee62df022a/interrupt-master/src/timer.c",
"visit_date": "2020-01-23T22:06:36.348500"
} | stackv2 | #include <LPC407x_8x_177x_8x.h>
#include "timer.h"
static void (*timer0UserDefinedHandler)();
void timer0Init(uint32_t tickHz, void (*handler)()) {
LPC_SC->PCONP |= (1UL << 1); /* ensure power to TIMER0 */
LPC_TIM0->TCR = 0; /* disable the timer during configuration */
LPC_TIM0->PR = 0; /* don't scale peripheral clock */
LPC_TIM0->CTCR = 0; /* select timer mode, not counter mode */
LPC_TIM0->MR0 = PeripheralClock / tickHz - 1; /* set match register for required rate */
LPC_TIM0->MCR = 0x03UL; /* interrupt and reset on match */
timer0UserDefinedHandler = handler; /* install the user-defined handler */
LPC_TIM0->IR = 0x3F; /* reset all TIMER0 interrupts */
NVIC_EnableIRQ(TIMER0_IRQn); /* enable the TIMER0 interrupt in the NVIC */
LPC_TIM0->TCR |= (1UL << 0); /* enable the timer */
}
void TIMER0_IRQHandler(void) {
timer0UserDefinedHandler(); /* call the user-defined handler */
LPC_TIM0->IR |= (1UL << 0); /* clear the interrupt on MR0 */
}
| 2.359375 | 2 |
2024-11-18T20:41:23.190754+00:00 | 2020-01-27T07:08:38 | 0d5e7b6c84b98bc304ee14524479e478a5fc371b | {
"blob_id": "0d5e7b6c84b98bc304ee14524479e478a5fc371b",
"branch_name": "refs/heads/master",
"committer_date": "2020-01-27T07:08:38",
"content_id": "180b41f35103617aaefdb498127dc1a8a1211384",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "ce982295d56cfd6f42de94eb8149f7adec7707c5",
"extension": "c",
"filename": "sender.c",
"fork_events_count": 1,
"gha_created_at": "2019-05-01T20:25:09",
"gha_event_created_at": "2020-01-27T07:08:40",
"gha_language": "C",
"gha_license_id": "NOASSERTION",
"github_id": 184476975,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2830,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/apps/aadl-eventdata-virtqueue/components/Sender/src/sender.c",
"provenance": "stackv2-0074.json.gz:65020",
"repo_name": "ikuz/camkes",
"revision_date": "2020-01-27T07:08:38",
"revision_id": "a0f3d0d15a99cd18f308dbffc9fc857754ad7872",
"snapshot_id": "6421a333e9a8e19c5598e71f3dc8087834757273",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ikuz/camkes/a0f3d0d15a99cd18f308dbffc9fc857754ad7872/apps/aadl-eventdata-virtqueue/components/Sender/src/sender.c",
"visit_date": "2021-09-24T07:28:00.751816"
} | stackv2 | /*
* Copyright 2019, Data61
* Commonwealth Scientific and Industrial Research Organisation (CSIRO)
* ABN 41 687 119 230.
*
* This software may be distributed and modified according to the terms of
* the BSD 2-Clause license. Note that NO WARRANTY is provided.
* See "LICENSE_BSD2.txt" for details.
*
* @TAG(DATA61_BSD)
*/
#include <camkes.h>
#include <stdio.h>
#include <string.h>
#include <virtqueue.h>
#include <camkes/virtqueue.h>
virtqueue_driver_t * vq1;
void handle_vq_callback(virtqueue_driver_t *vq);
int vq_send(char *s, int len) {
volatile void *alloc_buffer = NULL;
/* Check if there is data still waiting in the virtqueue */
int poll_res = virtqueue_driver_poll(vq1);
if (poll_res) {
handle_vq_callback(vq1);
}
int err = camkes_virtqueue_buffer_alloc(vq1, &alloc_buffer, len);
if (err) {
ZF_LOGE("Sender: vq1 buffer alloc failed");
return 1;
}
char *buffer_data = (char *)alloc_buffer;
memcpy(buffer_data, s, len);
err = virtqueue_driver_enqueue(vq1, alloc_buffer, len);
if (err != 0) {
ZF_LOGE("Sender: vq1 enqueue failed");
camkes_virtqueue_buffer_free(vq1, alloc_buffer);
return 1;
}
err = virtqueue_driver_signal(vq1);
if (err != 0) {
ZF_LOGE("Sender: vq1 signal failed");
return 1;
}
return 0;
}
void handle_vq_callback(virtqueue_driver_t *vq) {
volatile void* buf = NULL;
size_t buf_size = 0;
int err = virtqueue_driver_dequeue(vq, &buf, &buf_size);
if (err) {
ZF_LOGE("Sender: virtqueue dequeue failed");
return;
}
/* Clean up and free the buffer we allocated */
camkes_virtqueue_buffer_free(vq, buf);
}
void vq_wait_callback(void) {
// printf("Sender: vq_wait_callback\n");
int err;
int vq1_poll_res = virtqueue_driver_poll(vq1);
if (vq1_poll_res) {
handle_vq_callback(vq1);
}
if (vq1_poll_res == -1) {
ZF_LOGF("Sender: vq1 poll failed");
}
}
int virtqueue_init(void) {
/* Initialise virtqueue vq1 */
int err = camkes_virtqueue_driver_init(&vq1, 0);
if (err) {
ZF_LOGE("Sender: Unable to initialise vq1");
return 1;
} else {
return 0;
}
}
int aadl_raise_event_data(void *data, size_t len) {
return vq_send(data, len);
}
#define BUF_SIZE 1024
char buf[BUF_SIZE];
int run(void) {
virtqueue_init();
int i = 0;
int err = 0;
while (1) {
sprintf(buf, "%s: this is my messsage %d", get_instance_name(), i++);
// printf("%s: writing \"%s\"\n", get_instance_name(), buf);
err = aadl_raise_event_data(buf, strlen(buf));
/*
if (!err) {
printf("%s: wrote message \"%s\"\n", get_instance_name(), buf);
}
*/
if (err) {
ZF_LOGE("Sender: failed to raise event");
}
}
}
| 2.609375 | 3 |
2024-11-18T21:31:52.766220+00:00 | 2017-07-19T02:35:32 | 6ed5db8bb1c9a7826060379211bb7503e2030507 | {
"blob_id": "6ed5db8bb1c9a7826060379211bb7503e2030507",
"branch_name": "refs/heads/simple-encoding",
"committer_date": "2017-07-19T02:35:32",
"content_id": "599d835b434819765ca204995db16aa31bd67922",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "55f286eae977b11c2341f3e0c8fad8bbe98a4da3",
"extension": "c",
"filename": "bench.c",
"fork_events_count": 2,
"gha_created_at": "2015-04-16T19:56:29",
"gha_event_created_at": "2023-01-12T10:10:32",
"gha_language": "C",
"gha_license_id": "NOASSERTION",
"github_id": 34077358,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1121,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/bench.c",
"provenance": "stackv2-0077.json.gz:126",
"repo_name": "janding/lzfx",
"revision_date": "2017-07-19T02:35:32",
"revision_id": "448017fb83a4b8cc5593f68eeb2e8f5d92cc2266",
"snapshot_id": "5afad6a01763c62994e3608fd8a66a448d59e83c",
"src_encoding": "UTF-8",
"star_events_count": 21,
"url": "https://raw.githubusercontent.com/janding/lzfx/448017fb83a4b8cc5593f68eeb2e8f5d92cc2266/bench.c",
"visit_date": "2023-01-24T11:59:13.816159"
} | stackv2 | #include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#if USE_LZF
#include "lzf.h"
#else
#include "lzfx.h"
#endif
typedef unsigned char u8;
#define BLOCKSIZE (1024*1024)
#define NITER 100
int main(int argc, char* argv[]){
int ifd, rc, i;
u8* data = NULL;
u8* obuf = NULL;
unsigned int olen;
unsigned int count=0;
ifd = open(argv[1], O_RDONLY);
if(ifd<0){
return 1;
}
do {
data = realloc(data, count+BLOCKSIZE);
rc = read(ifd, data, BLOCKSIZE);
if(rc<0){
return -1;
}
count += rc;
} while(rc > 0);
fprintf(stderr, "read %u bytes\n", count);
olen = count*2;
obuf = (u8*)malloc(olen);
for(i=0;i<NITER;i++){
#if USE_LZF
rc = lzf_compress(data, count, obuf, olen);
if(rc==0){
fprintf(stderr, "fail\n");
return 1;
}
#else
rc = lzfx_compress(data, count, obuf, &olen);
if(rc<0){
fprintf(stderr, "fail\n");
return -rc;
}
#endif
olen = count*2;
}
return 0;
}
| 2.53125 | 3 |
2024-11-18T21:31:52.850435+00:00 | 2023-03-29T01:11:21 | 8a7daa42a73b412ef1027a2c2432a99717d527a8 | {
"blob_id": "8a7daa42a73b412ef1027a2c2432a99717d527a8",
"branch_name": "refs/heads/master",
"committer_date": "2023-03-29T01:11:21",
"content_id": "cb4a236d753d10e071f0ea56e8efa260e407c81b",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "02147e3367d4a8aa3a40df188dc815ef3c734952",
"extension": "c",
"filename": "bitfifo-test.c",
"fork_events_count": 3,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 27767031,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2924,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/libraries/datastruct/bitfifo/test/bitfifo-test.c",
"provenance": "stackv2-0077.json.gz:254",
"repo_name": "dpt/DPTLib",
"revision_date": "2023-03-29T01:11:21",
"revision_id": "85299361e35a38830c56c8b4437800ed31f08256",
"snapshot_id": "d6c620c88d2592ae101f6643f31d32f1eca2d7a4",
"src_encoding": "UTF-8",
"star_events_count": 21,
"url": "https://raw.githubusercontent.com/dpt/DPTLib/85299361e35a38830c56c8b4437800ed31f08256/libraries/datastruct/bitfifo/test/bitfifo-test.c",
"visit_date": "2023-04-08T20:50:27.523611"
} | stackv2 |
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef FORTIFY
#include "fortify/fortify.h"
#endif
#include "base/result.h"
#include "datastruct/bitfifo.h"
#include "test/all-tests.h"
#define MAXSIZE 32
static const struct
{
int length; /* in bits */
unsigned int after_dequeue;
}
expected[] =
{
{ 1, 0x00000001 },
{ 2, 0x00000003 },
{ 3, 0x00000007 },
{ 4, 0x0000000F },
{ 31, 0x7FFFFFFF },
{ 32, 0xFFFFFFFF },
};
#define NELEMS(a) (int)(sizeof(a) / sizeof((a)[0]))
/* shows changes from previous stats */
static void dump(const bitfifo_t *fifo)
{
static size_t previous_used = (size_t) -1; /* aka SIZE_MAX */
static int previous_full = INT_MAX;
static int previous_empty = INT_MAX;
size_t used;
int full;
int empty;
used = bitfifo_used(fifo);
full = bitfifo_full(fifo);
empty = bitfifo_empty(fifo);
printf("{");
if (used != previous_used)
printf("used=%zu ", used);
if (full != previous_full)
printf("full=%d ", full);
if (empty != previous_empty)
printf("empty=%d ", empty);
printf("}\n");
previous_used = used;
previous_full = full;
previous_empty = empty;
}
result_t bitfifo_test(const char *resources)
{
const unsigned int all_ones = ~0;
result_t err;
bitfifo_t *fifo;
int i;
unsigned int outbits;
fifo = bitfifo_create(MAXSIZE);
if (fifo == NULL)
return result_OOM;
dump(fifo);
printf("test: enqueue/dequeue...\n");
for (i = 0; i < NELEMS(expected); i++)
{
int length;
length = expected[i].length;
printf("%d bits\n", length);
/* put 'size_to_try' 1 bits into the queue */
err = bitfifo_enqueue(fifo, &all_ones, 0, length);
if (err)
goto Failure;
dump(fifo);
/* pull the bits back out */
outbits = 0;
err = bitfifo_dequeue(fifo, &outbits, length);
if (err)
goto Failure;
dump(fifo);
if (outbits != expected[i].after_dequeue)
printf("*** difference: %.8x <> %.8x\n",
outbits,
expected[i].after_dequeue);
}
printf("...done\n");
printf("test: completely fill up the fifo\n");
err = bitfifo_enqueue(fifo, &all_ones, 0, MAXSIZE);
if (err)
goto Failure;
dump(fifo);
printf("test: enqueue another bit (should error)\n");
err = bitfifo_enqueue(fifo, &all_ones, 0, 1);
if (err != result_BITFIFO_FULL)
goto Failure;
dump(fifo);
printf("test: do 32 dequeue-enqueue ops...\n");
for (i = 0; i < MAXSIZE; i++)
{
printf("dequeue a single bit\n");
err = bitfifo_dequeue(fifo, &outbits, 1);
if (err)
goto Failure;
dump(fifo);
printf("enqueue a single bit\n");
err = bitfifo_enqueue(fifo, &all_ones, 0, 1);
if (err)
goto Failure;
dump(fifo);
}
printf("...done\n");
bitfifo_destroy(fifo);
return result_TEST_PASSED;
Failure:
return result_TEST_FAILED;
}
| 2.875 | 3 |
2024-11-18T21:31:53.563756+00:00 | 2018-09-16T08:56:40 | e67a6cb3fdb392a606736df7737df803b4805b5b | {
"blob_id": "e67a6cb3fdb392a606736df7737df803b4805b5b",
"branch_name": "refs/heads/master",
"committer_date": "2018-09-16T08:56:40",
"content_id": "025dc899e0da8488db7e23fed0ba07c691ab6069",
"detected_licenses": [
"MIT"
],
"directory_id": "aa39a3c5e34e2f6af8e97913e10d44ba50f1bd13",
"extension": "c",
"filename": "main.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 68037139,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 16699,
"license": "MIT",
"license_type": "permissive",
"path": "/Assignment 2/main.c",
"provenance": "stackv2-0077.json.gz:512",
"repo_name": "IosifDobos/Programming",
"revision_date": "2018-09-16T08:56:40",
"revision_id": "b39e7abf0c53c732ee48a52de6546a33992f878c",
"snapshot_id": "8bfbb40a463f34b5814486441aed94748b12486f",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/IosifDobos/Programming/b39e7abf0c53c732ee48a52de6546a33992f878c/Assignment 2/main.c",
"visit_date": "2018-12-19T14:49:59.529018"
} | stackv2 | /** CA Assignment Programming Semester II */
/**
* Programming Semester II Assignment 2
*
* In this assignment need to create a program in C language that will perform some security
authorisation based on user access code input, encrypt user input access code make some assignment operation.
Check if user input is correct, display numbers of time user entered the code successfully and incorrectly.
* A menu is displayed to the screen which allow user to chose on task one at a time from the respective menu
and then an action is perform based on the user input
1. for task one is to ask user to enter a code more exactly 4 numbers from 0 - 9 which are stored into an array
2. for task to two encrypt the user code and verify if match with the default access code which is 4523
3. for task three decrypt user code
4. for task four track all the user access code inputs and when task four is required by the user display to the
screen how many time the user entered the code correctly or incorrectly
5. when the button five is press by the user program terminates.
* All these tasks are passed to a different function by reference and there perform the work required to accomplish the task
In this program all functions are passed trough by reference and use pointer notation only
* Created by Iosif Dobos, C16735789 @copyright all rights are reserved.
* Starting date: 22/02/2017
End date:
* Hours spend it: 2-hours on 22/02/2017
2-hours on 23/02/2017
2-hours on 24/02/2017
3-hours on 27/02/2017
3-hours on 03/03/2017
* Compiler used: CodeBlocks 16.01
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
//define my symbolic name and set name to be equal to 4
#define SIZE 4
#define LENT 1
//declare my function prototype
int display_menu ( char [] );
void function_task1(int [], int *);
void function_task2(int [], int *, int *, int *, int *, int *);
void function_task3(int [], int *, int *, int *);
void function_task4( int *, int *, int *, int * );
void function_task5( void );
//main function
int main()
{
/**
creating my local variables used for this function
*/
int input_code[SIZE]; //create the access code array for user input
char user_option[LENT];//used for menu, this variable is used to check the user input from the menu
int rtn_option;
//create 3 variables that are used
int option1_first;
int option2_second;
int option3_third;
//set variables to zero
option1_first = 0;
option2_second = 0;
option3_third = 0;
//create 2 static variables that are used to counter number of times user entered the code successfully and unsuccessfully
//this static variables will keep the data during the program execution
static int counter1;
static int counter2;
//set my static variables to zero
counter1 = 0;
counter2 = 0;
/**
create a do while loop
set the condition != 5
and the do-while loop will run the program until user enter number 5
*/
do
{
//call function which display the menu and ask user to enter his option from 1 - 5 and returns an integer value
//used for switch statement
rtn_option = display_menu( user_option);
/**
create a switch case that perform a specific task depending on user input
for e.g. if user press number 1 do case 1 and so on
if user press other number rather from 1 - 5 display a "default" message in switch case
*/
switch ( rtn_option )
{
//if user enter number 1 from the menu do case 1
case 1:
{
printf("Option 1. Enter code:\n");
//call function task 1 and within that function check if user code is correct and return 1 if it is
//else return 0
function_task1( input_code, &option1_first );
break;
}// end case 1
case 2:
{
// For option two encrypt the user access code and check if match with the correct
// access code setted by default which is 4523
// call function_task2 and display a message whatever the code was encrypted
// correctlly or incorrectlly
//encrypt_code =
function_task2( input_code, &option1_first, &option2_second, &option3_third, &counter1, &counter2);
break;
}//end case 2
case 3:
{
/**
If user press 3 decrypt the code
Do that only if the code was encrypted
Otherwise display a message said cannot decrypt code
*/
function_task3( input_code, &option1_first, &option2_second, &option3_third );
break;
}//end case 3
case 4:
{
/**
if user enter number 4 display how many times user enter the code successfully or unsuccessfully
pass this into different function which are passing two integers parameters and return a integer type
rtn_times = function_task4(successfully, unsuccessfully);
*/
function_task4( &option1_first, &option2_second, &counter1, &counter2 );
break;
}//end case 4
case 5:
{
//call function_task5 and in a separate function
//display a message with program ends
function_task5();
break;
}
//if a different option is press rather then between 1-5 a feedback message is displayed to the screen
default:
{
printf("Sorry invalid input. Choose any option from 1 - 5.\nPlease try again!!!\n\n\n");
break;
}//end default
}//end of switch case
}//end of while loop
while ( rtn_option != 5 ); //this do while loop will run until the condition is meet
return 0;
}//end function main()
//implement function display_menu
/**
Call function menu and then display the menu to the screen when the function its called
After each task is finished call function again and display the menu
This function is pass by reference and returns a integer parameter
*/
int display_menu( char usr_option[LENT])
{
int rtn_option;
//display the menu to the screen
//after an action is performed the menu is displayed on the screen again
printf("\n\t\t\t************************** MENU ***************************\n");
printf("\t\t\t***** Option 1. Enter Code\t\t\t\t*****\n");
printf("\t\t\t***** Option 2. Encrypt code and verify if correct\t*****\n");
printf("\t\t\t***** Option 3. Decrypt code\t\t\t\t*****\n");
printf("\t\t\t***** Option 4. Display number of times code was enter\t*****\n");
printf("\t\t\t*****\t\t(i) Successfully\t\t\t*****\n");
printf("\t\t\t*****\t\t(i) Unsuccessfully\t\t\t*****\n");
printf("\t\t\t***** Option 5. Exit Program\t\t\t\t*****\n");
printf("\t\t\t*************************************************************\n");
//asking user to enter an option from 1 to 5
printf("Please enter your option 1 - 5: ");
scanf("%s", usr_option);
//if character are entered use (atoi) convert the ASCII value to integer
rtn_option = atoi( usr_option);
//while ( *usr_option = getchar() != '\n' && *usr_option != EOF );
//print to the screen what option user entered then perform the specific option
printf("\n*******************************************************************");
printf("\n\tYou entered option %d\n", rtn_option);
printf("*******************************************************************\n");
//return user option to the main function
return rtn_option;
}//end function display_menu
/**
Implement function_task1() which ask user to enter a 4 digits code number from 0 - 9
An array of integers is passing trough this function and inside the function user is asked
to enter four digits access code from 0 - 9 and error checking is implement to check if user input is
between 0 - 9 if its not return an error message, exit the function and the menu is displayed again
*/
void function_task1( int cpy_code[SIZE], int *option1 )
{
//create a index variable
int i;
//display a message to the screen asking user to enter a 4 single digit access code
printf("\nPlease enter your access code 0 - 9: \n");
//create a for loop that read data from the user
for ( i = 0; i < SIZE; i++)
{
//create a while loop for error checking if user enter other number from 0 - 9 then display a feedback message
while (( scanf("%d", &*(cpy_code + i)) < 0 ) || *(cpy_code + i) > 9 )
{
//
while ( getchar() != '\n' );
//display the error message to the screen
printf("Invalid input. Try again !!!\n");
}//end while loop
}//end for loop
//print the new access code to the screen
printf("\nYour access code is: ");
//use the foor loop to display the content of the array
for ( i = 0; i < SIZE; i++)
{
printf("%d ", *(cpy_code + i));
}
printf("\n");
/**
if function 1 finished successfully change option1_first = 1
so that user can have the access to the other options
*/
*option1 = 1;
} // end function_task1()
/**
implement function_task2() which will encrypt the user access code and check if match with the
default code 4523 then display a message to the user either the code was correct or incorrect
*/
void function_task2(int c_code[SIZE], int *option1, int *option2, int *option3, int *cnt1, int *cnt2)
{
if ( *option1 == 1)
{
//declare my variables
int i = 0;
int temp1,temp2;
int check = 0;
const int access_code[SIZE] = { 4, 5, 2, 3};
//display the access code to the screen and then display the user code
printf("***** Default access code is: ");
for ( i = 0; i < SIZE; i++ )
{
printf("%d ", *(access_code + i));
}
printf(" *****\n");
printf("*****************************************\n");
//swap the elements of the array to encrypt the user code
temp1 = *( c_code + 0 );
*( c_code + 0 ) = *( c_code + 2 );
*( c_code + 2 ) = temp1;
temp1 = *( c_code + 1 );
*( c_code + 1 ) = *( c_code + 3 );
*( c_code + 3 ) = temp1;
//print the new access code to the screen
printf("\nYour new access code is: ");
//create a for loop, that for every element in the array add 1 then printed to the screen
for ( i = 0; i < SIZE; i++)
{
//add one to every element
*(c_code + i ) = *(c_code + i) + 1;
//store the new array into a temporarily variables and if that has value 10 change it to 0
temp1 = *(c_code + i);
//make a condition if any element from the array have value 10 change it to 0
if ( temp1 == 10)
{
*(c_code + i) = 0;
}
//print the new access code to the screen
printf("%d ", *(c_code + i));
}
printf("\n");
//create another for loop that will compare the user code with the default access code
for (i=0; i<SIZE; i++)
{
//store the two arrays in a separate variables then check if both are matching
temp1 = *(c_code + i);
temp2 = *(access_code +i);
/**
if the array are not equal increment the check variable and then if check is greater than 0
display error code otherwise display correct code
*/
if (temp1 != temp2 )
{
check++;
}
}//end for loop
//create condition to check if the user code match with the default code and if check is greater to 0 or not then display the message
if ( check > 0)
{
//is check is greater than 0 display error code
printf("\nERROR CODE\n");
//increment times user entered the code unsuccessfully
*cnt2 = *cnt2 + 1;
//set option2 to 1, user can have access to see times entered the code
*option2 = 1;
}//end if statement
else
{
//otherwise display correct code
printf("\nCORRECT CODE\n");
//increment times user entered the code successfully
*cnt1 = *cnt1 + 1;
//print to the screen if the user code has been encrypted successfully
printf("\n***** Code has been encrypted successfully!!! *****\n");
/**
set the option2 equal to 1, user to be able the decrypt the code and display number of
times entered the code successfully and incorrectly
*/
*option2 = 1;
}//end else statement
}//end if statement
else
{
printf("\nSorry can`t perform this option as you have to enter option 1 first\nOr access code has been encrypted already\n");
printf("\nThank You!!!\n");
}
}//end function_task_2()
/**
Implement function task3 which will decrypt the user code
This function can be use only if user encrypted the code otherwise display
an appropriate message saying code must be encrypted first.
This function is passing an array of integers as parameter
*/
void function_task3( int acs_code[], int *option1, int *option2, int *option3 )
{
if ( *option1 == 1 && *option2 == 1 && *option3 == 1 )
{
/**
if the access code has been encrypted successfully and user want to decrypt the code
do the following to decrypt the code
*/
//create my index variables
int i;
//create a temporary variables to swap the elements of the array
int temp1;
temp1 = acs_code[2] - 1;
acs_code[2] = acs_code[0] - 1;
acs_code[0] = temp1;
temp1 = acs_code[3] - 1;
acs_code[3] = acs_code[1] - 1;
acs_code[1] = temp1;
//create a for loop then display the decrypted code to the screen
printf("\nThe decrypted code is: ");
for ( i = 0; i < SIZE; i++)
{
//make a condition if a element from the array have value -1 change the value to 9
if ( *(acs_code + i) == -1 )
{
*(acs_code + i) = 9;
}
//print the decrypted code
printf(" %d ", *(acs_code + i));
}
printf("\n\nThe access code has been decrypted successfully.\n\n");
//if code has been decrypted change all the options back to 0, that user cannot access the function again
//until entered new code
//*option1 = 0;
//*option2 = 0;
*option3 = 0;
}//end if statement
else
{
printf("\nSorry can`t perform this option,access code must be encrypted first\nOr maybe this option has been accessed already.\n");
printf("Thank You!!!\n");
}//end else statement
}
/**
implement the function_task4() which will return an integer type and display how many times the user entered
the code successfully and unsuccessfully
*/
void function_task4( int *option1, int *option2, int *successfully, int *unsuccessfully )
{
//change option2 to 1 to have access this function
//only if access code has been encrypted successfully
*option2 = 1;
if ( *option1 == 1 && *option2 == 1 )
{
printf("\nAccess code entered successfully: %d\n", *successfully);
printf("\nAccess code entered incorrectly: %d\n", *unsuccessfully );
//after function complete change option1 to 0 so user cannot access encrypt function
//until another code is entered again and will be encrypted successfully
*option1 = 0;
}
else
{
printf("\nSorry can`t access this option.\nAccess code need to encrypted first in order to access this option.\nThank You!!!\n");
}
}
//function task five is user press five the program ends
void function_task5()
{
printf("Program Ends!!!\nThank you for your time\n");
}
| 3.359375 | 3 |
2024-11-18T22:07:57.074332+00:00 | 2019-04-22T18:02:25 | ef819e9f196cc0d241ead33fdfa4d56aa6df1528 | {
"blob_id": "ef819e9f196cc0d241ead33fdfa4d56aa6df1528",
"branch_name": "refs/heads/master",
"committer_date": "2019-04-22T18:02:25",
"content_id": "8063d81fe8690437c8ccdde57840c97a6ea86710",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "68fb520f4123d871c1edb6b88b5868c535f30730",
"extension": "c",
"filename": "mrpdp_key.c",
"fork_events_count": 0,
"gha_created_at": "2018-12-25T13:15:52",
"gha_event_created_at": "2019-04-22T11:08:24",
"gha_language": "C",
"gha_license_id": "BSD-2-Clause",
"github_id": 163084205,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 20896,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/libpdp/src/mrpdp/mrpdp_key.c",
"provenance": "stackv2-0078.json.gz:237900",
"repo_name": "proximax-storage/libpdp",
"revision_date": "2019-04-22T18:02:25",
"revision_id": "2644e3c9f768f80b2997aca701fcfef0a0f123e1",
"snapshot_id": "db91802ba597fe051f63024ec87925c2b598c49f",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/proximax-storage/libpdp/2644e3c9f768f80b2997aca701fcfef0a0f123e1/libpdp/src/mrpdp/mrpdp_key.c",
"visit_date": "2020-04-13T08:33:14.503615"
} | stackv2 | /**
* @file
* Implementation of the MR-PDP module for libpdp.
*
* @author Copyright (c) 2012, Mark Gondree
* @author Copyright (c) 2012, Alric Althoff
* @author Copyright (c) 2008, Zachary N J Peterson
* @date 2008-2013
* @copyright BSD 2-Clause License,
* See http://opensource.org/licenses/BSD-2-Clause
**/
/** @addtogroup MRPDP
* @{
*/
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <sys/param.h>
#include <sys/stat.h>
#include <openssl/evp.h>
#include <openssl/pem.h>
#include <openssl/rand.h>
#include <openssl/sha.h>
#include <openssl/hmac.h>
#include <pdp/mrpdp.h>
#include "pdp_misc.h"
/**
* @brief Finds a generator of the quadratic residues
* subgroup of \f$ Z^*_N \f$.
*
* @param[in] n the RSA modulus N
* @param[out] gen the generator
* @return 0 on success, non-zero on error
**/
static int pick_pdp_generator(BIGNUM **gen, BIGNUM *n)
{
int status = -1;
BIGNUM *a = NULL; // random value
BIGNUM *r0 = NULL; // temp value
BIGNUM *r1 = NULL; // temp value
BN_CTX *bctx = NULL; // bignum context
BIGNUM *g = NULL; // generator
int found_g = 0;
if (!gen || !n)
return -1;
if ((g = BN_new()) == NULL) goto cleanup;
if ((a = BN_new()) == NULL) goto cleanup;
if ((r0 = BN_new()) == NULL) goto cleanup;
if ((r1 = BN_new()) == NULL) goto cleanup;
if ((bctx = BN_CTX_new()) == NULL) goto cleanup;
while (!found_g) {
// Pick a random a < N
if (!BN_rand_range(a, n)) goto cleanup;
// Check to see if a is relatively prime to N, i.e.
// gcd(a, N) = 1
if (!BN_gcd(r0, a, n, bctx)) goto cleanup;
if (!BN_is_one(r0))
continue;
// Check to see if a-1 is relatively prime to N, i.e.
// gcd(a-1, N) = 1
if (!BN_sub(r0, a, BN_value_one())) goto cleanup;
if (!BN_gcd(r1, r0, n, bctx)) goto cleanup;
if (!BN_is_one(r1))
continue;
// Check to see if a+1 is relatively prime to N, i.e.
// gcd(a+1, N) = 1
if (!BN_add(r0, a, BN_value_one())) goto cleanup;
if (!BN_gcd(r1, r0, n, bctx)) goto cleanup;
if (!BN_is_one(r1))
continue;
found_g = 1;
}
// Square a to get a generator of the quadratic residues
if (!BN_sqr(g, a, bctx)) goto cleanup;
*gen = g;
status = 0;
cleanup:
if (bctx) BN_CTX_free(bctx);
if (a) BN_clear_free(a);
if (r0) BN_clear_free(r0);
if (r1) BN_clear_free(r1);
if (status && g) BN_clear_free(g);
return status;
}
/**
* @brief Generate key material.
*
* Generates:
* - the RSA key pair k->rsa
* - the generator k->g
* - the symmetric key k->v for the PRF
*
* @param[in] ctx ptr to context
* @param[out] k keydata
* @param[out] pub public keydata (optional)
* @return 0 on success, non-zero on error
**/
int mrpdp_key_gen(const pdp_ctx_t *ctx, pdp_key_t *k, pdp_key_t *pub)
{
int status = -1;
unsigned short use_safe_primes;
BN_CTX *bctx = NULL;
BIGNUM *r1 = NULL;
BIGNUM *r2 = NULL;
BIGNUM *phi = NULL;
pdp_mrpdp_ctx_t *p = NULL;
pdp_mrpdp_key_t *key = NULL;
pdp_mrpdp_key_t *pk = NULL;
if (!is_mrpdp(ctx) || !k) return -1;
p = ctx->mrpdp_param;
use_safe_primes = (p->opts & MRPDP_NO_SAFE_PRIMES) ? 0 : 1;
if ((key = malloc(sizeof(pdp_mrpdp_key_t))) == NULL) goto cleanup;
memset(key, 0, sizeof(pdp_mrpdp_key_t));
k->mrpdp = key;
// Allocate memory
if ((r1=BN_new()) == NULL) goto cleanup;
if ((r2=BN_new()) == NULL) goto cleanup;
if ((bctx=BN_CTX_new()) == NULL) goto cleanup;
if ((phi=BN_new()) == NULL) goto cleanup;
if (use_safe_primes) {
if ((key->rsa=RSA_new()) == NULL) goto cleanup;
if ((key->rsa->n=BN_new()) == NULL) goto cleanup;
if ((key->rsa->d=BN_new()) == NULL) goto cleanup;
if ((key->rsa->e=BN_new()) == NULL) goto cleanup;
if ((key->rsa->p=BN_new()) == NULL) goto cleanup;
if ((key->rsa->q=BN_new()) == NULL) goto cleanup;
if ((key->rsa->dmp1=BN_new()) == NULL) goto cleanup;
if ((key->rsa->dmq1=BN_new()) == NULL) goto cleanup;
if ((key->rsa->iqmp=BN_new()) == NULL) goto cleanup;
}
if ((key->v = malloc(p->prf_key_size)) == NULL) goto cleanup;
memset(key->v, 0, p->prf_key_size);
// Generate the RSA key pair
if (!use_safe_primes) {
key->rsa = RSA_generate_key(p->rsa_key_size, MRPDP_DEFAULT_RSA_PUB_EXP,
NULL, NULL);
if (!key->rsa) goto cleanup;
} else {
// Generate two different, safe primes p and q
if (!BN_generate_prime(key->rsa->p, (p->rsa_key_size/2), 1,
NULL, NULL, NULL, NULL))
goto cleanup;
if (!BN_is_prime(key->rsa->p, BN_prime_checks, NULL, bctx, NULL))
goto cleanup;
if (!BN_generate_prime(key->rsa->q, (p->rsa_key_size/2), 1,
NULL, NULL, NULL, NULL))
goto cleanup;
if (!BN_is_prime(key->rsa->q, BN_prime_checks, NULL, bctx, NULL))
goto cleanup;
if (BN_cmp(key->rsa->p, key->rsa->q) == 0)
goto cleanup;
// Create RSA modulus N
if (!BN_mul(key->rsa->n, key->rsa->p, key->rsa->q, bctx))
goto cleanup;
// Set e
if (!BN_set_word(key->rsa->e, MRPDP_DEFAULT_RSA_PUB_EXP))
goto cleanup;
// Generate phi and d
if (!BN_sub(r1, key->rsa->p, BN_value_one())) // = p-1
goto cleanup;
if (!BN_sub(r2, key->rsa->q, BN_value_one())) // = q-1
goto cleanup;
if (!BN_mul(phi, r1, r2, bctx)) // phi = (p-1)(q-1)
goto cleanup;
if (!BN_mod_inverse(key->rsa->d, key->rsa->e, phi, bctx)) // = d
goto cleanup;
// Calculate d mod (p-1)
if (!BN_mod(key->rsa->dmp1, key->rsa->d, r1, bctx))
goto cleanup;
// Calculate d mod (q-1)
if (!BN_mod(key->rsa->dmq1, key->rsa->d, r2, bctx))
goto cleanup;
// Calculate the inverse of q mod p
if (!BN_mod_inverse(key->rsa->iqmp, key->rsa->q, key->rsa->p, bctx))
goto cleanup;
}
// Check the RSA key pair
if (!RSA_check_key(key->rsa)) goto cleanup;
// Pick a PDP generator, using the RSA modulus N
if (pick_pdp_generator(&(key->g), key->rsa->n)) goto cleanup;
// Generate v, the symmetric key for the PRF
if (!RAND_bytes(key->v, p->prf_key_size)) goto cleanup;
// if we don't need to output pk, we are done
if (pub == NULL) {
status = 0;
goto cleanup;
} else {
status = -1;
}
// Copy public components into pk
if ((pk = malloc(sizeof(pdp_mrpdp_key_t))) == NULL) goto cleanup;
memset(pk, 0, sizeof(pdp_mrpdp_key_t));
pub->mrpdp = pk;
if ((pk->rsa=RSA_new()) == NULL) goto cleanup;
if ((pk->rsa->n = BN_dup(key->rsa->n)) == NULL) goto cleanup;
if ((pk->rsa->e = BN_dup(key->rsa->e)) == NULL) goto cleanup;
pk->rsa->d = pk->rsa->p = pk->rsa->q = NULL;
pk->rsa->dmp1 = pk->rsa->dmq1 = pk->rsa->iqmp = NULL;
if ((pk->g = BN_dup(key->g)) == NULL) goto cleanup;
pk->v = NULL;
status = 0;
cleanup:
if (r1) BN_clear_free(r1);
if (r2) BN_clear_free(r2);
if (phi) BN_clear_free(phi);
if (bctx) BN_CTX_free(bctx);
if (status) {
PDP_ERR("Could not generate keys");
mrpdp_key_free(ctx, k);
mrpdp_key_free(ctx, pub);
}
return status;
}
/**
* @brief Store key data to files.
*
* Serializes and stores key data, protecting private key data
* using a password-based key.
*
* @todo serialize the data in ASN.1
*
* @param[in] ctx ptr to context
* @param[in] k keydata
* @param[in] path path to directory to use to store keydata
* @return 0 on success, non-zero on error
**/
int mrpdp_key_store(const pdp_ctx_t *ctx, const pdp_key_t *k, const char *path)
{
int err, status = -1;
size_t gen_len, enc_len;
char passwd[1024]; // password to use in PBKD
char pri_keypath[MAXPATHLEN]; // path to pri key data
char pub_keypath[MAXPATHLEN]; // path to pub key data
FILE *pub_key = NULL;
FILE *pri_key = NULL;
EVP_PKEY *pkey = NULL; // EVP key for the RSA key data
unsigned char *salt = NULL; // PBKD password salt
unsigned char *dk = NULL; // PBKD derived key, used as KEK
unsigned char key_v[32]; // 256-bit buffer to hold v
unsigned char *enc_v = NULL; // buffer for encrypted v
unsigned char *gen = NULL; // buffer to hold serialized g
pdp_mrpdp_key_t *key = NULL;
pdp_mrpdp_ctx_t *p = NULL;
if (!is_mrpdp(ctx) || !k || !path || (strlen(path) > MAXPATHLEN))
return -1;
p = ctx->mrpdp_param;
key = k->mrpdp;
if (p->prf_key_size > sizeof(key_v)) {
PDP_ERR("Buffer for PRF key 'v' is not large enough.");
return -1;
}
// Allocate memory
if ((pkey = EVP_PKEY_new()) == NULL) goto cleanup;
if ((salt = malloc(p->prf_key_size)) == NULL) goto cleanup;
memset(salt, 0, p->prf_key_size);
memset(key_v, 0, sizeof(key_v));
// Check 'path' exists and derive names for key data files to store there
err = get_key_paths(pri_keypath, sizeof(pri_keypath),
pub_keypath, sizeof(pub_keypath), path, "mrpdp");
if (err) goto cleanup;
if ((access(pri_keypath, F_OK) == 0) || (access(pub_keypath, F_OK) == 0)) {
// keys already exist --- we don't need to store them
status = 0;
goto cleanup;
}
// Open, create and truncate the key files
if ((pri_key = fopen(pri_keypath, "w")) == NULL) goto cleanup;
if ((pub_key = fopen(pub_keypath, "w")) == NULL) goto cleanup;
// Get a passphrase to protect the stored key material
if (pdp_get_passphrase(ctx, (char *) passwd, sizeof(passwd)) != 0)
goto cleanup;
// Turn our RSA key into an EVP key
if (!EVP_PKEY_set1_RSA(pkey, key->rsa)) goto cleanup;
// Write the EVP key in PKCS8 password-protected format
err = PEM_write_PKCS8PrivateKey(pri_key, pkey, EVP_aes_256_cbc(),
NULL, 0, 0, passwd);
if (!err) goto cleanup;
// Generate random bytes for a salt
if (!RAND_bytes(salt, p->prf_key_size)) goto cleanup;
// Generate an AES key via PBKDF, to use for key wrapping
// This allocates space for dk
err = PBKDF2(&dk, p->prp_key_size, (unsigned char *) passwd,
strlen(passwd), salt, p->prf_key_size, 10000);
if (err) goto cleanup;
// Pad and NIST-wrap the PRF symetric key, v
// This allocates space for enc_v
memcpy(key_v, key->v, p->prf_key_size);
err = pdp_key_wrap(&enc_v, &enc_len, key_v, sizeof(key_v),
dk, p->prp_key_size);
if (err) goto cleanup;
if (enc_len != (sizeof(key_v) + 8)) goto cleanup; // buffer + 8 bytes
// Write the salt
fwrite(salt, p->prf_key_size, 1, pri_key);
if (ferror(pri_key)) goto cleanup;
// Write the encypted value of v
fwrite(enc_v, enc_len, 1, pri_key);
if (ferror(pri_key)) goto cleanup;
// Write the public key
if (!PEM_write_RSAPublicKey(pub_key, key->rsa)) goto cleanup;
// Write the length of g
gen_len = BN_num_bytes(key->g);
fwrite(&gen_len, sizeof(gen_len), 1, pub_key);
if (ferror(pub_key)) goto cleanup;
// Convert g to binary and write it
if ((gen = malloc(gen_len)) == NULL) goto cleanup;
memset(gen, 0, gen_len);
if (!BN_bn2bin(key->g, gen)) goto cleanup;
fwrite(gen, gen_len, 1, pub_key);
if (ferror(pub_key)) goto cleanup;
status = 0;
cleanup:
memset(passwd, 0, sizeof(passwd));
if (pri_key) fclose(pri_key);
if (pub_key) fclose(pub_key);
if (pkey) EVP_PKEY_free(pkey);
sfree(dk, p->prp_key_size);
sfree(salt, p->prf_key_size);
sfree(enc_v, enc_len);
sfree(gen, gen_len);
if (status != 0) {
PDP_ERR("Did not write key pair successfully.");
if (access(pub_keypath, F_OK) == 0) unlink(pub_keypath);
if (access(pri_keypath, F_OK) == 0) unlink(pri_keypath);
}
return status;
}
/**
* @brief Reads key files and populates the key structure.
*
* Un-serializes and retrieves key data, opening private key data
* using a password-based key.
*
* @param[in] ctx context
* @param[out] k public key data
* @param[in] pub_keypath path to public key data
* @return 0 on success, non-zero on error
**/
static int mrpdp_pub_key_open(const pdp_ctx_t *ctx, pdp_key_t *k,
const char* pub_keypath)
{
int status = -1;
size_t gen_len;
FILE *pub_key = NULL;
unsigned char *gen = NULL; // buffer to hold serialized rep of g
pdp_mrpdp_key_t *key = NULL;
if (!is_mrpdp(ctx) || !k || !pub_keypath) return -1;
if (strlen(pub_keypath) > MAXPATHLEN) return -1;
if ((key = malloc(sizeof(pdp_mrpdp_key_t))) == NULL) goto cleanup;
memset(key, 0, sizeof(pdp_mrpdp_key_t));
k->mrpdp = key;
// Allocate space for key data
if ((key->g = BN_new()) == NULL) goto cleanup;
// Open the key files
if ((pub_key = fopen(pub_keypath, "r")) == NULL) goto cleanup;
// Read in the public key
key->rsa = PEM_read_RSAPublicKey(pub_key, NULL, NULL, NULL);
if (key->rsa == NULL) goto cleanup;
if (!key->rsa->n || !key->rsa->e) goto cleanup;
// Read g data length and then binary g data
fread(&gen_len, sizeof(gen_len), 1, pub_key);
if (ferror(pub_key)) goto cleanup;
if ((gen = malloc(gen_len)) == NULL) goto cleanup;
fread(gen, gen_len, 1, pub_key);
if (ferror(pub_key)) goto cleanup;
// Read g from its buffer into 'key'
if (!BN_bin2bn(gen, gen_len, key->g)) goto cleanup;
status = 0;
cleanup:
CRYPTO_cleanup_all_ex_data();
if (pub_key) fclose(pub_key);
sfree(gen, gen_len);
if (status) {
PDP_ERR("Couldn't open key file.");
mrpdp_key_free(ctx, k);
}
return status;
}
/**
* @brief Reads key files and populates the key structure.
*
* Un-serializes and retrieves key data, opening private key data
* using a password-based key.
*
* @param[in] ctx context
* @param[out] k private key data
* @param[in] pri_keypath path to private key data
* @param[in] pub_keypath path to public key data
* @return 0 on success, non-zero on error
**/
static int mrpdp_pri_key_open(const pdp_ctx_t *ctx, pdp_key_t *k,
const char* pri_keypath, const char* pub_keypath)
{
int err, status = -1;
size_t key_v_len, gen_len;
char passwd[1024]; // password to use in PBKD
FILE *pri_key = NULL;
FILE *pub_key = NULL;
EVP_PKEY *pkey = NULL; // EVP key for the RSA key data
unsigned char *salt = NULL; // PBKD password salt
unsigned char *dk = NULL; // PBKD derived key
unsigned char *enc_v = NULL; // v, encryted using the KEK
size_t enc_v_len = 32 + 8; // 256-bit buffer + 8 bytes
unsigned char *key_v = NULL; // 256-bit buffer to store serialized v
unsigned char *gen = NULL; // buffer to hold serialized rep of g
RSA *rsa = NULL;
BN_CTX *bctx = NULL;
BIGNUM *r1 = NULL;
BIGNUM *r2 = NULL;
pdp_mrpdp_key_t *key = NULL;
pdp_mrpdp_ctx_t *p = NULL;
if (!is_mrpdp(ctx) || !k || !pri_keypath || !pub_keypath)
return -1;
if (strlen(pri_keypath) > MAXPATHLEN) return -1;
if (strlen(pub_keypath) > MAXPATHLEN) return -1;
p = ctx->mrpdp_param;
if ((key = malloc(sizeof(pdp_mrpdp_key_t))) == NULL) goto cleanup;
memset(key, 0, sizeof(pdp_mrpdp_key_t));
k->mrpdp = key;
// Allocate space for key data
if ((key->g = BN_new()) == NULL) goto cleanup;
if ((key->v = malloc(p->prf_key_size)) == NULL) goto cleanup;
if ((r1 = BN_new()) == NULL) goto cleanup;
if ((r2 = BN_new()) == NULL) goto cleanup;
if ((bctx = BN_CTX_new()) == NULL) goto cleanup;
if ((salt = malloc(p->prf_key_size)) == NULL) goto cleanup;
if ((enc_v = malloc(enc_v_len)) == NULL) goto cleanup;
memset(key->v, 0, p->prf_key_size);
memset(enc_v, 0, enc_v_len);
memset(salt, 0, p->prf_key_size);
// Open the key files
if ((pri_key = fopen(pri_keypath, "r")) == NULL) goto cleanup;
if ((pub_key = fopen(pub_keypath, "r")) == NULL) goto cleanup;
// Get passphrase to access the private key material
if (pdp_get_passphrase(ctx, (char *) passwd, sizeof(passwd)) != 0)
goto cleanup;
// Use passwd to read out private RSA EVP data
if ((pkey = PEM_read_PrivateKey(pri_key, NULL, NULL, passwd)) == NULL)
goto cleanup;
// Read RSA EVP into 'key' and check it
if ((key->rsa = EVP_PKEY_get1_RSA(pkey)) == NULL) goto cleanup;
if (!RSA_check_key(key->rsa)) goto cleanup;
// Get the salt and the encrypted PRF key v
fread(salt, p->prf_key_size, 1, pri_key);
if (ferror(pri_key)) goto cleanup;
fread(enc_v, enc_v_len, 1, pri_key);
if (ferror(pri_key)) goto cleanup;
// Generate a password-based key
err = PBKDF2(&dk, p->prp_key_size, (unsigned char *) passwd,
strlen(passwd), salt, p->prf_key_size, 10000);
if (err) goto cleanup;
// We no longer need passwd
memset(passwd, 0, sizeof(passwd));
// Unwrap and strip the padding from the key v
err = pdp_key_unwrap(&key_v, &key_v_len, enc_v, enc_v_len,
dk, p->prp_key_size);
if (err) goto cleanup;
if (key_v_len < p->prf_key_size) goto cleanup; // should be a padded key
// Read v from its buffer into 'key'
memcpy(key->v, key_v, p->prf_key_size);
// Skip over the public key
rsa = PEM_read_RSAPublicKey(pub_key, NULL, NULL, NULL);
if (!rsa) goto cleanup;
// Read g data length and then binary g data
fread(&gen_len, sizeof(gen_len), 1, pub_key);
if (ferror(pub_key)) goto cleanup;
if ((gen = malloc(gen_len)) == NULL) goto cleanup;
fread(gen, gen_len, 1, pub_key);
if (ferror(pub_key)) goto cleanup;
// Read g from its buffer into 'key'
if (!BN_bin2bn(gen, gen_len, key->g)) goto cleanup;
status = 0;
cleanup:
memset(passwd, 0, sizeof(passwd));
CRYPTO_cleanup_all_ex_data();
if (pri_key) fclose(pri_key);
if (pub_key) fclose(pub_key);
if (r1) BN_clear_free(r1);
if (r2) BN_clear_free(r2);
if (bctx) BN_CTX_free(bctx);
if (pkey) EVP_PKEY_free(pkey);
if (rsa) RSA_free(rsa);
sfree(key_v, key_v_len);
sfree(dk, p->prp_key_size);
sfree(salt, p->prf_key_size);
sfree(enc_v, enc_v_len);
sfree(gen, gen_len);
if (status) {
PDP_ERR("Couldn't open key files.");
mrpdp_key_free(ctx, k);
}
return status;
}
/**
* @brief Reads key files and populates the key structure.
*
* @param[in] ctx context
* @param[out] k private key data (NULL, if not desired)
* @param[out] pub public key data (NULL, if not desired)
* @param[in] path path to directory used to store keydata
* @return 0 on success, non-zero on error
**/
int mrpdp_key_open(const pdp_ctx_t *ctx, pdp_key_t *k, pdp_key_t *pub,
const char* path)
{
char pri_keypath[MAXPATHLEN]; // path to pri key data
char pub_keypath[MAXPATHLEN]; // path to pub key data
int err = -1;
if (!is_mrpdp(ctx) || !path || (strlen(path) > MAXPATHLEN))
return -1;
// Check 'path' exists and derive names for key data files
err = get_key_paths(pri_keypath, sizeof(pri_keypath),
pub_keypath, sizeof(pub_keypath), path, "mrpdp");
if (err) goto cleanup;
if (access(pri_keypath, F_OK) && access(pub_keypath, F_OK)) goto cleanup;
if (k) {
err = mrpdp_pri_key_open(ctx, k, pri_keypath, pub_keypath);
if (err) goto cleanup;
}
if (pub) {
err = mrpdp_pub_key_open(ctx, pub, pub_keypath);
if (err) goto cleanup;
}
return 0;
cleanup:
mrpdp_key_free(ctx, k);
mrpdp_key_free(ctx, pub);
return -1;
}
/**
* @brief Destroy and free key material.
* @param[in] ctx context
* @param[in,out] k keydata
* @return 0 on success, non-zero on error
**/
int mrpdp_key_free(const pdp_ctx_t *ctx, pdp_key_t *k)
{
pdp_mrpdp_key_t *key = NULL;
pdp_mrpdp_ctx_t *p = NULL;
if (!k || !k->mrpdp)
return -1;
p = ctx->mrpdp_param;
key = k->mrpdp;
if (key->rsa) RSA_free(key->rsa);
if (key->g) BN_clear_free(key->g);
sfree(key->v, p->prf_key_size);
sfree(key, sizeof(pdp_mrpdp_key_t));
CRYPTO_cleanup_all_ex_data();
return 0;
}
/** @} */
| 2.359375 | 2 |
2024-11-18T22:07:57.125844+00:00 | 2021-01-18T04:11:43 | d0a87248872e6e8fb0e4b847fce6a85bd5fa8543 | {
"blob_id": "d0a87248872e6e8fb0e4b847fce6a85bd5fa8543",
"branch_name": "refs/heads/main",
"committer_date": "2021-01-18T04:11:43",
"content_id": "3ed6341b99fc8843c4b5e81cda81c5f2ddad5247",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "8fe07cf177969a9d1b43f1c462ba5e3007259de6",
"extension": "c",
"filename": "03_kilometers.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 328441639,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 338,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/ABC4/ch13/03_kilometers.c",
"provenance": "stackv2-0078.json.gz:238032",
"repo_name": "ethanqtle/C_4_Everyone_Fund",
"revision_date": "2021-01-18T04:11:43",
"revision_id": "4f5fca4493b25d7ebaed430fb1147024c4e6eb1f",
"snapshot_id": "2504e0f546b13250a1c406c439ec96a8a3fac6a7",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ethanqtle/C_4_Everyone_Fund/4f5fca4493b25d7ebaed430fb1147024c4e6eb1f/ABC4/ch13/03_kilometers.c",
"visit_date": "2023-02-17T04:05:42.643409"
} | stackv2 | // The distance to the moon converted to kilometers.
//
// Title: moon
#include <iostream.h>
int main()
{
const int moon = 238857;
cout << "The moon's distance from Earth is " << moon;
cout << " miles." << endl;
int moon_kilo = moon * 1.609;
cout << "In kilometers this is " << moon_kilo;
cout << " km." << endl;
}
| 2.859375 | 3 |
2024-11-18T22:07:57.198422+00:00 | 2009-12-19T14:24:42 | 584cce35b158adaac44fc40d8a4cb9286d668b0b | {
"blob_id": "584cce35b158adaac44fc40d8a4cb9286d668b0b",
"branch_name": "refs/heads/master",
"committer_date": "2009-12-19T14:36:56",
"content_id": "aa14e5995bec191684364fdd858bb748e2305499",
"detected_licenses": [
"MIT"
],
"directory_id": "e77961473fca3c0cc2c4bcdf0d8fff43eeb720dd",
"extension": "c",
"filename": "proto_cmd.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": 22247,
"license": "MIT",
"license_type": "permissive",
"path": "/proto_cmd.c",
"provenance": "stackv2-0078.json.gz:238161",
"repo_name": "rclasen/dudld",
"revision_date": "2009-12-19T14:24:42",
"revision_id": "0796c05aa1fbabbf85a478675ce5c36a6ac3eb4d",
"snapshot_id": "11f4eeb1c972a9bf4b833fa9b3f63f3fe598283f",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/rclasen/dudld/0796c05aa1fbabbf85a478675ce5c36a6ac3eb4d/proto_cmd.c",
"visit_date": "2021-01-18T14:03:03.570684"
} | stackv2 | /*
* Copyright (c) 2008 Rainer Clasen
*
* This program is free software; you can redistribute it and/or modify
* it under the terms described in the file LICENSE included in this
* distribution.
*
*/
#include <string.h>
#include <syslog.h>
#include "sleep.h"
#include "proto_helper.h"
#include "proto_cmd.h"
#include "proto_args.h"
#include "proto_fmt.h"
#include "proto_bcast.h"
void cmd_quit( t_client *client, char *code, void **argv )
{
(void)argv;
proto_rlast( client, code, "bye");
client_close( client );
}
void cmd_user( t_client *client, char *code, void **argv )
{
t_arg_name user = (t_arg_name)argv[0];
if( client->pdata )
free(client->pdata);
client->pdata = strdup( user );
client->pstate = p_user;
proto_rlast( client, code, "user ok, use PASS for password");
}
void cmd_pass( t_client *client, char *code, void **argv )
{
t_arg_pass pass = (t_arg_pass)argv[0];
if( NULL == (client->user = user_getn( client->pdata )))
goto clean1;
if( ! user_ok( client->user, pass ))
goto clean2;
client->pstate = p_idle;
syslog( LOG_INFO, "con #%d: user %s logged in",
client->id, client->user->name );
proto_rlast( client, code, "successfully logged in" );
proto_bcast_login( client );
goto final;
clean2:
user_free( client->user );
client->user = NULL;
clean1:
client->pstate = p_open;
syslog( LOG_NOTICE, "con #%d: login failed", client->id );
proto_rlast( client, "501", "login failed" );
final:
free( client->pdata );
client->pdata = NULL;
}
void cmd_clientlist( t_client *client, char *code, void **argv )
{
it_client *it;
(void)argv;
it = clients_list();
dump_clients(client,code,it);
it_client_done(it);
}
void cmd_clientclose( t_client *client, char *code, void **argv )
{
t_arg_id id = (t_arg_id)argv[0];
t_client *c;
if( NULL == (c = client_get( id ))){
proto_rlast( client, "501", "session not found");
return;
}
proto_rlast( c, "632", "disconnected" );
client_close( c );
client_delref( c );
proto_rlast( client, code, "disconnected" );
}
void cmd_clientcloseuser( t_client *client, char *code, void **argv )
{
t_arg_id id = (t_arg_id)argv[0];
it_client *it;
t_client *t;
int found = 0;
if( NULL == (it = clients_uid(id))){
proto_rlast(client, "501", "failed to get session list" );
return;
}
for( t=it_client_begin(it); t; t=it_client_next(it)){
proto_rlast(t, "632", "kicked" );
client_close(t);
client_delref(t);
found++;
}
it_client_done(it);
if( found )
proto_rlast(client, code, "kicked");
else
proto_rlast(client, "501", "user not found");
}
void cmd_userlist( t_client *client, char *code, void **argv )
{
it_user *it;
(void)argv;
it = users_list();
dump_users( client, code, it );
it_user_done( it );
}
void cmd_userget( t_client *client, char *code, void **argv )
{
t_arg_id id = (t_arg_id)argv[0];
t_user *u;
if( NULL == (u = user_get(id))){
proto_rlast(client, "501", "user not found" );
return;
}
dump_user(client, code, u);
user_free(u);
}
void cmd_user2id( t_client *client, char *code, void **argv )
{
t_arg_name user = (t_arg_name)argv[0];
int uid;
if( 0 > ( uid = user_id(user))){
proto_rlast(client,"501","no such user");
return;
}
proto_rlast(client, code, "%d", uid);
}
void cmd_useradd( t_client *client, char *code, void **argv )
{
t_arg_name user = (t_arg_name)argv[0];
int uid;
if( 0 > ( uid = user_add(user, 1, ""))){
proto_rlast(client, "530", "failed" );
return;
}
proto_rlast(client, code, "%d", uid );
}
void cmd_usersetpass( t_client *client, char *code, void **argv )
{
t_arg_id id = (t_arg_id)argv[0];
t_arg_pass pass = (t_arg_pass)argv[1];
if( 0 > user_setpass(id, pass) ){
proto_rlast(client, "530", "failed");
} else {
proto_rlast(client, code, "password changed" );
}
}
void cmd_usersetright( t_client *client, char *code, void **argv )
{
t_arg_id id = (t_arg_id)argv[0];
t_arg_right right = (t_arg_right)argv[1];
if( 0 > user_setright(id, right) ){
proto_rlast(client, "530", "failed");
} else {
proto_rlast(client, code, "right changed" );
}
}
void cmd_userdel( t_client *client, char *code, void **argv )
{
t_arg_id id = (t_arg_id)argv[0];
if( 0 > user_del(id)){
proto_rlast(client, "530", "failed" );
return;
}
proto_rlast(client, code, "deleted");
}
void cmd_play( t_client *client, char *code, void **argv )
{
(void)argv;
proto_player_reply( client, player_start(), code, "playing");
}
void cmd_stop( t_client *client, char *code, void **argv )
{
(void)argv;
proto_player_reply( client, player_stop(), code, "stopped");
}
void cmd_next( t_client *client, char *code, void **argv )
{
(void)argv;
proto_player_reply( client, player_next(), code, "playing next");
}
void cmd_prev( t_client *client, char *code, void **argv )
{
(void)argv;
proto_player_reply( client, player_prev(), code, "playing previous");
}
void cmd_pause( t_client *client, char *code, void **argv )
{
(void)argv;
proto_player_reply( client, player_pause(), code, "paused");
}
void cmd_elapsed( t_client *client, char *code, void **argv )
{
(void)argv;
proto_rlast(client, code, "%d", player_elapsed());
}
void cmd_jump( t_client *client, char *code, void **argv )
{
t_arg_sec sec = (t_arg_sec)argv[0];
proto_player_reply( client, player_jump(sec), code, "jumped");
}
void cmd_status( t_client *client, char *code, void **argv )
{
(void)argv;
proto_rlast(client, code, "%d", player_status() );
}
void cmd_curtrack( t_client *client, char *code, void **argv )
{
t_track *t;
(void)argv;
if( NULL == (t = player_track())){
proto_rlast(client,"541", "nothing playing (maybe in a gap?)" );
return;
}
dump_track(client,code,t);
track_free(t);
}
void cmd_gap( t_client *client, char *code, void **argv )
{
(void)argv;
proto_rlast(client, code, "%d", player_gap() );
}
void cmd_gapset( t_client *client, char *code, void **argv )
{
t_arg_sec gap = (t_arg_sec)argv[0];
player_setgap( gap );
proto_rlast(client, code, "gap adjusted" );
}
void cmd_cut( t_client *client, char *code, void **argv )
{
(void)argv;
proto_rlast(client, code, "%d", player_cut() );
}
void cmd_cutset( t_client *client, char *code, void **argv )
{
t_arg_bool arg0 = (t_arg_bool)argv[0];
player_setcut( arg0 );
proto_rlast(client, code, "cutting adjusted" );
}
void cmd_replaygain( t_client *client, char *code, void **argv )
{
(void)argv;
proto_rlast(client, code, "%d", player_rgtype() );
}
void cmd_replaygainset( t_client *client, char *code, void **argv )
{
t_arg_replaygain arg0 = (t_arg_replaygain)argv[0];
player_setrgtype( arg0 );
proto_rlast(client, code, "replaygain type adjusted" );
}
void cmd_rgpreamp( t_client *client, char *code, void **argv )
{
(void)argv;
proto_rlast(client, code, "%f", player_rgpreamp() );
}
void cmd_rgpreampset( t_client *client, char *code, void **argv )
{
t_arg_decibel arg0 = (t_arg_decibel)argv[0];
player_setrgpreamp( *arg0 );
proto_rlast(client, code, "replaygain preamplification adjusted" );
}
void cmd_random( t_client *client, char *code, void **argv )
{
(void)argv;
proto_rlast(client, code, "%d", player_random() );
}
void cmd_randomset( t_client *client, char *code, void **argv )
{
t_arg_bool arg0 = (t_arg_bool)argv[0];
player_setrandom( arg0 );
proto_rlast(client, code, "random adjusted" );
}
void cmd_sleep( t_client *client, char *code, void **argv )
{
(void)argv;
proto_rlast(client, code, "%d", sleep_remain() );
}
void cmd_sleepset( t_client *client, char *code, void **argv )
{
t_arg_sec sec = (t_arg_sec)argv[0];
sleep_in( sec );
proto_rlast(client, code, "ok, will stop in %d seconds", sec);
}
void cmd_trackcount( t_client *client, char *code, void **argv )
{
int matches;
(void)argv;
if( 0 > ( matches = tracks())){
proto_rlast(client, "510", "internal error" );
return;
}
proto_rlast(client, code, "%d", matches );
}
void cmd_tracksearch( t_client *client, char *code, void **argv )
{
t_arg_string pat = (t_arg_string)argv[0];
it_track *it;
it = tracks_search(pat);
dump_tracks( client, code, it );
it_track_done(it);
}
void cmd_tracksearchf( t_client *client, char *code, void **argv )
{
t_arg_filter filter = (t_arg_filter)argv[0];
expr *e = NULL;
char *msg;
int pos;
it_track *it;
if( NULL == (e = expr_parse_str( &pos, &msg, filter ))){
proto_rlast(client, "511", "error at pos %d in filter: %s", pos, msg );
return;
}
it = tracks_searchf( e );
dump_tracks( client, code, it );
it_track_done(it);
expr_free(e);
}
void cmd_tracksalbum( t_client *client, char *code, void **argv )
{
t_arg_id id = (t_arg_id)argv[0];
it_track *it;
it = tracks_albumid(id);
dump_tracks( client, code, it );
it_track_done(it);
}
void cmd_tracksartist( t_client *client, char *code, void **argv )
{
t_arg_id id = (t_arg_id)argv[0];
it_track *it;
it = tracks_artistid(id);
dump_tracks( client, code, it );
it_track_done(it);
}
void cmd_trackget( t_client *client, char *code, void **argv )
{
t_arg_id id = (t_arg_id)argv[0];
t_track *t;
if( NULL == (t = track_get( id ))){
proto_rlast(client,"511", "no such track" );
return;
}
dump_track(client,code,t);
track_free(t);
}
void cmd_track2id( t_client *client, char *code, void **argv )
{
t_arg_id id = (t_arg_id)argv[0];
t_arg_id pos = (t_arg_id)argv[1];
if( 0 > (id = track_id( id, pos))){
proto_rlast(client,"501", "no such track found" );
return;
}
proto_rlast(client, code, "%d", id );
}
void cmd_tracksetname( t_client *client, char *code, void **argv )
{
t_arg_id id = (t_arg_id)argv[0];
t_arg_string name = (t_arg_string)argv[1];
if( track_setname(id, name )){
proto_rlast(client,"511", "failed" );
return;
}
proto_rlast(client,code, "name changed" );
}
void cmd_tracksetartist( t_client *client, char *code, void **argv )
{
t_arg_id track = (t_arg_id)argv[0];
t_arg_id artist = (t_arg_id)argv[1];
if( track_setartist(track, artist)){
proto_rlast(client,"511", "failed" );
return;
}
proto_rlast(client,code, "artist changed" );
}
void cmd_filter( t_client *client, char *code, void **argv )
{
char buf[1024];
expr *e;
(void)argv;
e = random_filter();
if( e )
expr_fmt( buf, 1024, e );
proto_rlast(client, code, "%s", e ? buf : "" );
}
void cmd_filterset( t_client *client, char *code, void **argv )
{
t_arg_filter filter = (t_arg_filter)argv[0];
expr *e = NULL;
char *msg;
int pos;
if( NULL == (e = expr_parse_str( &pos, &msg, filter ))){
proto_rlast(client, "511", "error at pos %d in filter: %s",
pos, msg );
return;
}
/* at least initialize with an empty filter */
if( random_setfilter(e)){
proto_rlast(client, "511", "failed to apply (correct) filter" );
} else {
proto_rlast(client, code, "filter changed" );
}
expr_free(e);
}
void cmd_filterstat( t_client *client, char *code, void **argv )
{
int matches;
(void)argv;
if( 0 > ( matches = random_filterstat())){
proto_rlast(client, "511", "filter error" );
return;
}
proto_rlast(client, code, "%d", matches );
}
void cmd_filtertop( t_client *client, char *code, void **argv )
{
t_arg_num num = (t_arg_num)argv[0];
it_track *it;
it = random_top(num);
dump_tracks( client, code, it );
it_track_done(it);
}
void cmd_history( t_client *client, char *code, void **argv )
{
t_arg_num num = (t_arg_num)argv[0];
it_history *it;
it = history_list( num );
dump_history( client, code, it );
it_history_done(it);
}
void cmd_historytrack( t_client *client, char *code, void **argv )
{
t_arg_id id = (t_arg_id)argv[0];
t_arg_num num = (t_arg_num)argv[1];
it_history *it;
it = history_tracklist( id, num );
dump_history( client, code, it );
it_history_done(it);
}
void cmd_queuelist( t_client *client, char *code, void **argv )
{
it_queue *it;
(void)argv;
it = queue_list();
dump_queues( client, code, it );
it_queue_done(it);
}
void cmd_queueget( t_client *client, char *code, void **argv )
{
t_arg_id id = (t_arg_id)argv[0];
t_queue *q;
if( NULL == (q = queue_get(id))){
proto_rlast(client,"501", "queue entry not found" );
return;
}
dump_queue(client,code,q);
queue_free(q);
}
void cmd_queueadd( t_client *client, char *code, void **argv )
{
t_arg_id id = (t_arg_id)argv[0];
int qid;
if( -1 == (qid = queue_add(id, client->user->id))){
proto_rlast(client, "561", "failed to add track to queue" );
return;
}
proto_rlast(client, code, "%d", qid );
}
void cmd_queuedel( t_client *client, char *code, void **argv )
{
t_arg_id id = (t_arg_id)argv[0];
int uid;
uid = client->user->id;
if( client->user->right == r_master )
uid = 0;
if( queue_del( id, uid )){
proto_rlast(client,"562", "failed to delete from queue" );
return;
}
proto_rlast(client,code, "track removed from queue" );
}
void cmd_queueclear( t_client *client, char *code, void **argv )
{
(void)argv;
if( queue_clear() ){
proto_rlast(client,"563", "failed to clear queue" );
return;
}
proto_rlast(client,code, "queue cleared" );
}
void cmd_queuesum( t_client *client, char *code, void **argv )
{
int sum;
(void)argv;
if( 0 > ( sum = queue_sum())){
proto_rlast(client, "510", "internal error" );
return;
}
proto_rlast(client, code, "%d", sum );
}
void cmd_taglist( t_client *client, char *code, void **argv )
{
it_tag *it;
(void)argv;
it = tags_list();
dump_tags( client, code, it );
it_tag_done(it );
}
void cmd_tagget( t_client *client, char *code, void **argv )
{
t_arg_id id = (t_arg_id)argv[0];
t_tag *t;
if( NULL == (t = tag_get( id ))){
proto_rlast(client,"511", "no such tag" );
return;
}
dump_tag(client, code, t);
tag_free(t);
}
void cmd_tagsartist( t_client *client, char *code, void **argv )
{
t_arg_id aid = (t_arg_id)argv[0];
it_tag *it;
it = tags_artist(aid);
dump_tags( client, code, it );
it_tag_done(it );
}
void cmd_tag2id( t_client *client, char *code, void **argv )
{
t_arg_name name = (t_arg_name)argv[0];
int t;
if( 0 > (t = tag_id( name ))){
proto_rlast(client,"511", "no such tag" );
return;
}
proto_rlast(client,code, "%d", t);
}
void cmd_tagadd( t_client *client, char *code, void **argv )
{
t_arg_name name = (t_arg_name)argv[0];
int id;
if( 0 > (id = tag_add( name ))){
proto_rlast(client,"511", "failed" );
return;
}
proto_rlast(client, code, "%d", id );
}
void cmd_tagsetname( t_client *client, char *code, void **argv )
{
t_arg_id id = (t_arg_id)argv[0];
t_arg_name name = (t_arg_name)argv[1];
if( tag_setname(id, name )){
proto_rlast(client,"511", "failed" );
return;
}
proto_rlast(client,code, "name changed" );
}
void cmd_tagsetdesc( t_client *client, char *code, void **argv )
{
t_arg_id id = (t_arg_id)argv[0];
t_arg_string desc = (t_arg_string)argv[1];
if( tag_setdesc(id, desc )){
proto_rlast(client,"511", "failed" );
return;
}
proto_rlast(client,code, "desc changed" );
}
void cmd_tagdel( t_client *client, char *code, void **argv )
{
t_arg_id id = (t_arg_id)argv[0];
if( tag_del( id )){
proto_rlast(client,"511", "failed" );
return;
}
proto_rlast(client,code, "deleted" );
}
void cmd_tracktaglist( t_client *client, char *code, void **argv )
{
t_arg_id id = (t_arg_id)argv[0];
it_tag *it;
it = track_tags(id);
dump_tags( client, code, it );
it_tag_done(it );
}
void cmd_tracktagadd( t_client *client, char *code, void **argv )
{
t_arg_id trackid = (t_arg_id)argv[0];
t_arg_id tagid = (t_arg_id)argv[1];
if( track_tagadd(trackid,tagid)){
proto_rlast(client,"511", "failed" );
return;
}
proto_rlast(client,code, "tag added to track (or already exists)" );
}
void cmd_tracktagdel( t_client *client, char *code, void **argv )
{
t_arg_id trackid = (t_arg_id)argv[0];
t_arg_id tagid = (t_arg_id)argv[1];
if( track_tagdel(trackid,tagid)){
proto_rlast(client,"511", "failed" );
return;
}
proto_rlast(client,code, "tag deleted from track" );
}
void cmd_tracktagged( t_client *client, char *code, void **argv )
{
t_arg_id trackid = (t_arg_id)argv[0];
t_arg_id tagid = (t_arg_id)argv[1];
int r;
if( 0 > (r = track_tagged(trackid,tagid))){
proto_rlast(client,"511", "failed" );
return;
}
proto_rlast(client,code, "%d", r );
}
void cmd_albumlist( t_client *client, char *code, void **argv )
{
it_album *it;
(void)argv;
it = albums_list( );
dump_albums( client, code, it );
it_album_done(it);
}
void cmd_albumsartist( t_client *client, char *code, void **argv )
{
t_arg_id id = (t_arg_id)argv[0];
it_album *it;
it = albums_artistid(id);
dump_albums( client, code, it );
it_album_done(it);
}
void cmd_albumstag( t_client *client, char *code, void **argv )
{
t_arg_id tid = (t_arg_id)argv[0];
it_album *it;
it = albums_tag(tid);
dump_albums( client, code, it );
it_album_done(it);
}
void cmd_albumsearch( t_client *client, char *code, void **argv )
{
t_arg_string pat = (t_arg_string)argv[0];
it_album *it;
it = albums_search(pat);
dump_albums( client, code, it );
it_album_done(it);
}
void cmd_albumget( t_client *client, char *code, void **argv )
{
t_arg_id id = (t_arg_id)argv[0];
t_album *t;
if( NULL == (t = album_get(id))){
proto_rlast(client, "580", "failed" );
return;
}
dump_album(client,code, t);
album_free(t);
}
void cmd_albumsetname( t_client *client, char *code, void **argv )
{
t_arg_id id = (t_arg_id)argv[0];
t_arg_string name = (t_arg_string)argv[1];
if( album_setname(id, name )){
proto_rlast(client,"511", "failed" );
return;
}
proto_rlast(client,code, "name changed" );
}
void cmd_albumsetartist( t_client *client, char *code, void **argv )
{
t_arg_id album = (t_arg_id)argv[0];
t_arg_id artist = (t_arg_id)argv[1];
if( album_setartist(album, artist)){
proto_rlast(client,"511", "failed" );
return;
}
proto_rlast(client,code, "artist changed" );
}
void cmd_albumsetyear( t_client *client, char *code, void **argv )
{
t_arg_id album = (t_arg_id)argv[0];
t_arg_num year = (t_arg_num)argv[1];
if( album_setyear(album, year)){
proto_rlast(client,"511", "failed" );
return;
}
proto_rlast(client,code, "year changed" );
}
void cmd_artistlist( t_client *client, char *code, void **argv )
{
it_artist *it;
(void)argv;
it = artists_list( );
dump_artists( client, code, it );
it_artist_done(it);
}
void cmd_artistsearch( t_client *client, char *code, void **argv )
{
t_arg_string pat = (t_arg_string)argv[0];
it_artist *it;
it = artists_search( pat );
dump_artists( client, code, it );
it_artist_done(it);
}
void cmd_artiststag( t_client *client, char *code, void **argv )
{
t_arg_id tid = (t_arg_id)argv[0];
it_artist *it;
it = artists_tag( tid );
dump_artists( client, code, it );
it_artist_done(it);
}
void cmd_artistget( t_client *client, char *code, void **argv )
{
t_arg_id id = (t_arg_id)argv[0];
t_artist *a;
if( NULL == (a = artist_get(id))){
proto_rlast(client, "590", "failed" );
return;
}
dump_artist(client,code,a);
artist_free(a);
}
void cmd_artistadd( t_client *client, char *code, void **argv )
{
t_arg_string name = (t_arg_string)argv[0];
int id;
if( 0 > (id = artist_add( name ))){
proto_rlast(client,"511", "failed" );
return;
}
proto_rlast(client, code, "%d", id );
}
void cmd_artistsetname( t_client *client, char *code, void **argv )
{
t_arg_id id = (t_arg_id)argv[0];
t_arg_string name = (t_arg_string)argv[1];
if( artist_setname(id, name )){
proto_rlast(client,"511", "failed" );
return;
}
proto_rlast(client,code, "name changed" );
}
void cmd_artistmerge( t_client *client, char *code, void **argv )
{
t_arg_id from = (t_arg_id)argv[0];
t_arg_id to = (t_arg_id)argv[1];
if( artist_merge(from, to )){
proto_rlast(client,"511", "failed" );
return;
}
proto_rlast(client,code, "merged artist %d into %d", from, to );
}
void cmd_artistdel( t_client *client, char *code, void **argv )
{
t_arg_id id = (t_arg_id)argv[0];
if( artist_del(id)){
proto_rlast(client,"511", "failed" );
return;
}
proto_rlast(client,code, "artist deleted" );
}
void cmd_sfilterlist( t_client *client, char *code, void **argv )
{
it_sfilter *it;
(void)argv;
it = sfilters_list();
dump_sfilters( client, code, it );
it_sfilter_done(it );
}
void cmd_sfilterget( t_client *client, char *code, void **argv )
{
t_arg_id id = (t_arg_id)argv[0];
t_sfilter *t;
if( NULL == (t = sfilter_get( id ))){
proto_rlast(client,"511", "no such sfilter" );
return;
}
dump_sfilter(client,code, t);
sfilter_free(t);
}
void cmd_sfilter2id( t_client *client, char *code, void **argv )
{
t_arg_name name = (t_arg_name)argv[0];
int t;
if( 0 > (t = sfilter_id( name ))){
proto_rlast(client,"511", "no such sfilter" );
return;
}
proto_rlast(client,code, "%d", t);
}
void cmd_sfilteradd( t_client *client, char *code, void **argv )
{
t_arg_name name = (t_arg_name)argv[0];
int id;
if( 0 > (id = sfilter_add( name ))){
proto_rlast(client,"511", "failed" );
return;
}
proto_rlast(client, code, "%d", id );
}
void cmd_sfiltersetname( t_client *client, char *code, void **argv )
{
t_arg_id id = (t_arg_id)argv[0];
t_arg_name name = (t_arg_name)argv[1];
if( sfilter_setname(id, name )){
proto_rlast(client,"511", "failed" );
return;
}
proto_rlast(client,code, "name changed" );
}
void cmd_sfiltersetfilter( t_client *client, char *code, void **argv )
{
t_arg_id id = (t_arg_id)argv[0];
t_arg_filter filter = (t_arg_filter)argv[1];
expr *e = NULL;
char *msg;
int pos;
if( NULL == (e = expr_parse_str( &pos, &msg, filter ))){
proto_rlast(client, "511", "error at pos %d in filter: %s", pos, msg );
return;
}
expr_free(e);
if( sfilter_setfilter(id, filter )){
proto_rlast(client,"511", "failed" );
} else {
proto_rlast(client,code, "filter changed" );
}
}
void cmd_sfilterdel( t_client *client, char *code, void **argv )
{
t_arg_id id = (t_arg_id)argv[0];
if( sfilter_del( id )){
proto_rlast(client,"511", "failed" );
return;
}
proto_rlast(client,code, "deleted" );
}
void cmd_help( t_client *client, char *code, void **argv )
{
t_cmd *cmd;
t_rights perm;
(void)argv;
perm = client->user ? client->user->right : r_any;
for( cmd = proto_cmds; cmd && cmd->name; cmd++ ){
if( cmd->context != p_any && cmd->context != client->pstate )
continue;
if( cmd->perm > perm )
continue;
proto_rline(client,code,cmd->name);
}
proto_rlast(client,code,"");
}
| 2.40625 | 2 |
2024-11-18T22:07:57.287370+00:00 | 2016-12-22T13:46:17 | 795d881f67ad690be3c3ee93f8f92b13260136d1 | {
"blob_id": "795d881f67ad690be3c3ee93f8f92b13260136d1",
"branch_name": "refs/heads/master",
"committer_date": "2016-12-22T13:46:17",
"content_id": "ef359c431a2ba61db7bd61b28d32e1d2d2b930f1",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "c1270100282cf9409f9f41f1d1e6b7a838bbfbff",
"extension": "c",
"filename": "test.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 67863934,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1820,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/c_compiler/main/test.c",
"provenance": "stackv2-0078.json.gz:238289",
"repo_name": "uncertainmove/CompilerDesign",
"revision_date": "2016-12-22T13:46:17",
"revision_id": "4df8e7f45d578e51b1b222d87927d26c14cc9970",
"snapshot_id": "03ae654183c94de95ac921003ce3704b425ed46b",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/uncertainmove/CompilerDesign/4df8e7f45d578e51b1b222d87927d26c14cc9970/c_compiler/main/test.c",
"visit_date": "2021-03-30T16:11:22.782902"
} | stackv2 | float cc[10][11];
struct Position
{
float x, y;
};
// Redefine field "x"
struct Pos {
float x, y;
// int x;
};
// Duplicated name "Position1"
struct Position1 {
float x;
};
// struct Position1 {
// int x;
// };
// Undefine variable "j"
int func1(int i) {
// int i = 0;
// j = i + 1;
}
// Undifine function "inc"
int func2(){
int i = 0;
int j[5];
// inc(i);
}
// Redefine variable "i"
int func3() {
int i, j;
// int i;
}
// Redefine function "func"
int func(int i) {
return i;
}
// int func() {
// return 0;
// }
// Type mismatched for assignment
int func4() {
int i;
// i = 3.7;
}
// The left-hand side of an assignment must be a variable
int func5() {
int i;
// 10 = i;
}
// Type mismatched for operands
int func6() {
float j;
// 10 + j;
}
// Type mismatched for return
int func7() {
float j = 1.7;
// return j;
}
// Function "func8(int)" is not applicable for arguments "(int, int)"
int func8(int i) {
return i;
}
int func9() {
// func8(1, 2);
}
// "i" is not an array
int func10() {
int i;
// i[0];
}
// "i" is not a function
int func11() {
int i;
// i(10);
}
// "1.5" is not an integer
int func12() {
int i[10];
// i[1.5] = 10;
}
// Illegal use of "."
int func13() {
int i;
// i.x;
}
// Non-exitent field "n"
int func14() {
struct Position p;
int s = 0;
if(p.x == 3.7)
return 0;
else {
int s = 1;
if(s == 0) {
int s=3;
if(s) {
s=0;
}
else{
int d=4;
s=3;
}
}
}
}
// Undefined structure "Position2"
int func15() {
// struct Position2 i;
}
/*
* choose to do
*/
// Incomplete definition of function "func"
| 2.640625 | 3 |
2024-11-18T22:07:57.389673+00:00 | 2020-11-14T12:44:59 | cc8fb636599c6ac7f1e2dbb5b8352c818af22325 | {
"blob_id": "cc8fb636599c6ac7f1e2dbb5b8352c818af22325",
"branch_name": "refs/heads/master",
"committer_date": "2020-11-14T12:44:59",
"content_id": "19386163ab4beb39d39cec8bc3e3e1fd61f5a64e",
"detected_licenses": [
"MIT"
],
"directory_id": "f118e2efca8c5d98b2d40a5e3f2ab04dc402da73",
"extension": "c",
"filename": "main.c",
"fork_events_count": 0,
"gha_created_at": "2020-10-12T06:49:01",
"gha_event_created_at": "2020-11-14T12:45:01",
"gha_language": "Python",
"gha_license_id": "MIT",
"github_id": 303302557,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 954,
"license": "MIT",
"license_type": "permissive",
"path": "/Assignments/Assignment1/part3/main.c",
"provenance": "stackv2-0078.json.gz:238418",
"repo_name": "RealDyllon/cz1103-coursework",
"revision_date": "2020-11-14T12:44:59",
"revision_id": "d43fbaa1e98b50dfec35756aff227980a5461ccf",
"snapshot_id": "30b74d1a1d77f4025ff2978d57604a1052904834",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/RealDyllon/cz1103-coursework/d43fbaa1e98b50dfec35756aff227980a5461ccf/Assignments/Assignment1/part3/main.c",
"visit_date": "2023-01-12T21:37:18.135703"
} | stackv2 | #include <stdio.h>
void swapMinMax1D(int ar[], int size);
int main()
{
int ar[50], i, size;
printf("Enter array size: \n");
scanf("%d", &size);
printf("Enter %d data: \n", size);
for (i = 0; i < size; i++)
scanf("%d", ar + i);
swapMinMax1D(ar, size);
printf("swapMinMax1D(): ");
for (i = 0; i < size; i++)
printf("%d ", *(ar + i));
return 0;
}
void swapMinMax1D(int ar[], int size)
{
/* Write your code here */
int min = -1, max = -1; // define as sentinel value
int minIndex, maxIndex;
int current = 0;
for (int i = 0; i < size; i++)
{
current = ar[i];
if (min == -1 || current <= min)
{
min = current;
minIndex = i;
}
if (max == -1 || current >= max)
{
max = current;
maxIndex = i;
}
}
int temp = ar[minIndex];
ar[minIndex] = max;
ar[maxIndex] = min;
} | 3.703125 | 4 |
2024-11-18T22:07:57.811608+00:00 | 2020-05-04T04:32:25 | 4183f7d30afb2f5c248cdeb60faee9ec408dfd57 | {
"blob_id": "4183f7d30afb2f5c248cdeb60faee9ec408dfd57",
"branch_name": "refs/heads/master",
"committer_date": "2020-05-04T04:32:25",
"content_id": "11de227759fb92db929f22ec50e82b8a4adb5ff7",
"detected_licenses": [
"MIT"
],
"directory_id": "1929c33f96719af6ce62da7d76e5cba6d361eea8",
"extension": "c",
"filename": "1Q_d.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 261061115,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 498,
"license": "MIT",
"license_type": "permissive",
"path": "/estruturaDeDecisao/Lista1/1Q_d.c",
"provenance": "stackv2-0078.json.gz:238548",
"repo_name": "RuthMaria/algoritmo",
"revision_date": "2020-05-04T04:32:25",
"revision_id": "ec9ebf629598dd75a05e33861706f1a6bc956cd5",
"snapshot_id": "b863a6d3610fbce4e29a3fcf3641f2179b7df818",
"src_encoding": "ISO-8859-1",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/RuthMaria/algoritmo/ec9ebf629598dd75a05e33861706f1a6bc956cd5/estruturaDeDecisao/Lista1/1Q_d.c",
"visit_date": "2022-06-26T09:50:28.224747"
} | stackv2 | /*
d.Determinar o maior de três números dados.
*/
#include<stdio.h>
#include<conio.h>
main(){
int num1, num2, num3, maior;
printf("\n 3 Numero: ");
scanf("%d%d%d", &num1, &num2, &num3);
maior = num1;
if(num2 > maior)
maior = num2;
if(num3 > maior)
maior = num3;
printf("\n o maior eh: %d", maior);
getch();
}
| 3.53125 | 4 |
2024-11-18T22:07:57.903615+00:00 | 2021-01-15T16:17:22 | 5826d07f24e862382fe1b94d20b4399e403200e3 | {
"blob_id": "5826d07f24e862382fe1b94d20b4399e403200e3",
"branch_name": "refs/heads/main",
"committer_date": "2021-01-15T16:17:22",
"content_id": "81f036ff20d496fe9ebfccb332db503b0ebc3085",
"detected_licenses": [
"MIT"
],
"directory_id": "47d836bebfe480cba4a7f43e9eea9f014c17345b",
"extension": "c",
"filename": "ee101.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 329368808,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 14427,
"license": "MIT",
"license_type": "permissive",
"path": "/ee101.c",
"provenance": "stackv2-0078.json.gz:238676",
"repo_name": "tge96/ee101-macOS-c",
"revision_date": "2021-01-15T16:17:22",
"revision_id": "9352cff2fc9d0ec3653aa489247b80bf04a88fb3",
"snapshot_id": "49eb60938383a8cd3b0197ecaf3543f07028e34f",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/tge96/ee101-macOS-c/9352cff2fc9d0ec3653aa489247b80bf04a88fb3/ee101.c",
"visit_date": "2023-02-12T09:14:26.163994"
} | stackv2 | /* =============================================================
EE101 Embedded Firmware Debugger
Firmware Library
Provided by EE101.com
This file is to be included in your embedded firmware project to
send debug information to the EE101 Embedded Firmware Debugger.
It can operate in a 1-wire (UART) mode, or a 2-wire (GPIO) mode.
In 1-wire mode, you will use your onboard Async UART set to N,8,1 at any
baud rate up to 3MBaud.
In 2-wire mode, it uses 2 signals (a clock and data line).
The EE101 Insight-Pro™ autoselects the correct polarity. The 2
signals are General Purpose I/O pins (GPIO) which are
available on most microprocessors. Only output is required.
The output high voltage level can be anywhere from 1V to 5V.
You must modify this file in a few places to specify how to set
and clear the GPIO and how to enable/disable interrupts (if you
need to).
ONLY MODIFY THE CODE BELOW BETWEEN THE FLAGS.
If you have any questions or issues, please email us at
[email protected].
===============================================================*/
//************** MAKE YOUR CHANGES BELOW ONLY *************************
// These defines are an example using the Cypress PSoC5LP Microcontroller
#define EE101_DEBUG_ON // Comment this line out to turn off the EE101 Debug outputs
// Change #1 - Add any includes that you need for the below defines
//#include "project.h" // PSoC Creator PSoC 4,5,6
//#include "cy_pdl.h" // ModusToolbox PSoC 6
//#include "cyhal.h" // ModusToolbox PSoC 6
//#include "cybsp.h" // ModusToolbox PSoC 6
//#include "cy_retarget_io.h" // ModusToolbox PSoC 6
//#include "resource_map.h" // ModusToolbox PSoC 6
//extern cyhal_uart_t uart_obj; // ModusToolbox PSoC 6
//#include <wiringPi.h> // Raspberry Pi
//#include "wiringSerial.h" // Raspberry Pi
#include "serial.h" // macOS
extern int fd; // Raspberry Pi & macOS
// CHANGE #2 - How to disable Interrupts. Only needed if you have debug
// output in interrupts. Make sure if you do disable interrupts that it
// is done in a way that does not lose the interrupts (keeps the interrupt
// flags active) so that when the interrupt is re-enabled the interrupt will
// be serviced.
#define EE101IntDisable ; // No Interrupt Debugging
#define EE101IntEnable ;
//#define EE101IntDisable __disable_irq(); // ModusToolbox Interrupt Debugging
//#define EE101IntEnable __enable_irq(); // ModusToolbox Interrupt Debugging
//#define EE101IntDisable CyGlobalIntDisable; // PSoC Creator Interrupt Debugging
//#define EE101IntEnable CyGlobalIntEnable; // PSoC Creator Interrupt Debugging
// CHANGE #3 - Choose if you're using 2 wire (GPIO) or 1 wire (UART) EE101 interface
#define EE101_ONE_WIRE // Uncomment this line if you are using a single signal UART interface for EE101 debug data
//#define EE101_TWO_WIRE // Uncomment this if you are using 2 wire sync interface for EE101 debug data
// CHANGE #4 - FOR 2-wire EE101 Mode: Defines that set the GPIO pins to High and Low levels and Toggles
// These should be as fast as possible, but not faster than 50ns (20MHz)
// These two GPIO are a Clock and a Data line. They must be setup as outputs
// elsewhere in your firmware during system initialization.
// The Data line toggle must invert the current state of the GPIO line
//#define EE101ClockLow EE101_CLOCK_DR &= ~(1 << EE101_CLOCK_SHIFT); // PSoC Version
//#define EE101ClockHigh EE101_CLOCK_DR |= (1 << EE101_CLOCK_SHIFT); // PSoC Version
//#define EE101DataLow EE101_DATA_DR &= ~(1 << EE101_DATA_SHIFT); // PSoC Version
//#define EE101DataHigh EE101_DATA_DR |= (1 << EE101_DATA_SHIFT); // PSoC Version
//#define EE101DataToggle EE101_DATA_DR ^= (1 << EE101_DATA_SHIFT); // PSoC Version
//#define EE101ClockLow cyhal_gpio_write(CYBSP_D10, 0u); // ModusToolbox PSoC 6 Version P12.2[D13] and P12.3 [D10]
//#define EE101ClockHigh cyhal_gpio_write(CYBSP_D10, 1u); // ModusToolbox PSoC 6 Version
//#define EE101DataLow cyhal_gpio_write(CYBSP_D13, 0u); // ModusToolbox PSoC 6 Version
//#define EE101DataHigh cyhal_gpio_write(CYBSP_D13, 1u); // ModusToolbox PSoC 6 Version
//#define EE101DataToggle cyhal_gpio_write(CYBSP_D13, ~cyhal_gpio_read(CYBSP_D13)); // ModusToolbox PSoC 6 Version
#define EE101ClockLow digitalWrite(7, LOW); // Raspberry Pi Version, using wiringPi library numbering
#define EE101ClockHigh digitalWrite(7, HIGH); // Raspberry Pi Version, using wiringPi library numbering
#define EE101DataLow digitalWrite(0, LOW); // Raspberry Pi Version, using wiringPi library numbering
#define EE101DataHigh digitalWrite(0, HIGH); // Raspberry Pi Version, using wiringPi library numbering
#define EE101DataToggle digitalWrite(0, !digitalRead(0)); // Raspberry Pi Version, using wiringPi library numbering
//#define EE101ClockLow digitalWrite(10, LOW); // Arduino Version
//#define EE101ClockHigh digitalWrite(10, HIGH); // Arduino Version
//#define EE101DataLow digitalWrite(11, LOW); // Arduino Version
//#define EE101DataHigh digitalWrite(11, HIGH); // Arduino Version
//#define EE101DataToggle digitalWrite(11, !digitalRead(11)); // Arduino Version
//#define EE101ClockLow GPIO_PinOutClear(EE101_CLOCK_PORT, EE101_CLOCK_PIN) // STM EFM32 Version
//#define EE101ClockHigh GPIO_PinOutSet(EE101_CLOCK_PORT, EE101_CLOCK_PIN) // STM EFM32 Version
//#define EE101DataLow GPIO_PinOutClear(EE101_DATA_PORT, EE101_DATA_PIN) // STM EFM32 Version
//#define EE101DataHigh GPIO_PinOutSet(EE101_DATA_PORT, EE101_DATA_PIN) // STM EFM32 Version
//#define EE101DataToggle GPIO_PinOutToggle(EE101_DATA_PORT, EE101_DATA_PIN) // STM EFM32 Version
//#define EE101ClockLow PORTCbits.RC12 = 0; // PIC X32 Version
//#define EE101ClockHigh PORTCbits.RC12 = 1; // PIC X32 Version
//#define EE101DataLow PORTCbits.RC13 = 0; // PIC X32 Version
//#define EE101DataHigh PORTCbits.RC13 = 1; // PIC X32 Version
//#define EE101DataToggle PORTCbits.RC13 = !PORTCbits.RC13; // PIC X32 Version
// CHANGE #5 - FOR 1-wire EE101 Mode: Defines your routine name to send a single byte to the UART
// The UART must be configured and enabled elsewhere in your firmware.
//#define EE101UartTx(x) UART_PutChar(x) // PSoC Creator
//#define EE101UartTx(x) cyhal_uart_putc(&uart_obj, x) // ModusToolBox PSoC 6 P12.1 [D12]
#define EE101UartTx(x) serialPutchar(fd, x) // Raspberry Pi
// CHANGE #6 - Enable/Disable Variable Argument support for SendEE101printf
#define VARIABLE_ARGUMENT_SUPPORT // Comment out this line if your compiler does not
// have va_list, va_start, vsprintf, and va_end support
// as defined in stdarg.h
#define MAX_STRING_LENGTH 250 // How much RAM to use for the SendEE101printf buffer
// This must not be greater than 250
// This defines the maximum length of any debug text message
#ifdef VARIABLE_ARGUMENT_SUPPORT // Includes required by the va_list, va_start, vsprintf, and va_end
#include <stdio.h> // vsprintf
#include <stdarg.h> // va_list, va_start, and va_end
#endif
// CHANGE #7 - Type defines for your platform
// Copy these defines and function prototypes to your header files to define the API
#define euint8 unsigned char // unsigned 8 bit value
#define eint8 signed char // signed 8 bit value
#define eint32 signed long // signed 32 bit value
#define echar char // bytes within a string
void EE101Value( euint8 channel, eint32 value ); // Output a Value for this channel
void EE101Text( euint8 channel, echar *string ); // Output Text for this channel
void EE101ValueLabel( euint8 channel, echar *string ); // Set the label for this Value Channel (sent every 256 times)
void EE101TextLabel( euint8 channel, echar *string ); // Set the label for this Text Channel (sent every 256 times)
#ifdef VARIABLE_ARGUMENT_SUPPORT
void EE101printf( euint8 channel, echar *format, ... ); // printf-like function with variable argument list
#endif
//************** MAKE YOUR CHANGES ABOVE ONLY *************************
#define EE101_SYNC 0x50
#define EE101_VALUE_TYPE 0x80
#define EE101_TEXT_TYPE 0x00
#define EE101_LABEL 0x08
#ifdef EE101_ONE_WIRE // This is a 1-wire interface
void SendEE101Byte( euint8 value )
{
EE101UartTx( value );
}
void EE101Value( euint8 channel, eint32 value )
{
#ifdef EE101_DEBUG_ON
EE101IntDisable;
SendEE101Byte( (channel & 0x07) | EE101_VALUE_TYPE | EE101_SYNC);
SendEE101Byte( value >> 24);
SendEE101Byte( value >> 16);
SendEE101Byte( value >> 8);
SendEE101Byte( value );
EE101IntEnable;
#endif
};
void EE101Text( euint8 channel, echar *string )
{
#ifdef EE101_DEBUG_ON
euint8 bytes = 1;
EE101IntDisable;
SendEE101Byte( (channel&0x07) | EE101_SYNC | EE101_TEXT_TYPE);
while(*string)
{
if (bytes++ > MAX_STRING_LENGTH)
break;
SendEE101Byte( *string++ );
}
SendEE101Byte( 0 );
EE101IntEnable;
#endif
};
void EE101TextLabel( euint8 channel, echar *string )
{
#ifdef EE101_DEBUG_ON
static euint8 timeout[8] = {0,0,0,0,0,0,0,0};
euint8 bytes = 1;
channel &= 0x07;
timeout[channel]++;
if ( timeout[channel] != 1 ) return;
EE101IntDisable;
SendEE101Byte( channel | EE101_SYNC | EE101_TEXT_TYPE | EE101_LABEL);
while(*string)
{
if (bytes++ > MAX_STRING_LENGTH)
break;
SendEE101Byte( *string++ );
}
SendEE101Byte( 0 );
EE101IntEnable;
#endif
};
void EE101ValueLabel( euint8 channel, echar *string )
{
#ifdef EE101_DEBUG_ON
static euint8 timeout[8] = {0,0,0,0,0,0,0,0};
euint8 bytes = 1;
channel &= 0x07;
timeout[channel]++;
if ( timeout[channel] != 1 ) return;
EE101IntDisable;
SendEE101Byte( channel | EE101_SYNC | EE101_VALUE_TYPE | EE101_LABEL);
while(*string)
{
if (bytes++ > MAX_STRING_LENGTH)
break;
SendEE101Byte( *string++ );
}
SendEE101Byte( 0 );
EE101IntEnable;
#endif
};
#else // Otherwise it is a 2-wire interface
void SendEE101Byte( euint8 value )
{
if (value & 0x80) {EE101DataHigh;} else {EE101DataLow;} EE101ClockHigh; EE101ClockLow;
if (value & 0x40) {EE101DataHigh;} else {EE101DataLow;} EE101ClockHigh; EE101ClockLow;
if (value & 0x20) {EE101DataHigh;} else {EE101DataLow;} EE101ClockHigh; EE101ClockLow;
if (value & 0x10) {EE101DataHigh;} else {EE101DataLow;} EE101ClockHigh; EE101ClockLow;
if (value & 0x08) {EE101DataHigh;} else {EE101DataLow;} EE101ClockHigh; EE101ClockLow;
if (value & 0x04) {EE101DataHigh;} else {EE101DataLow;} EE101ClockHigh; EE101ClockLow;
if (value & 0x02) {EE101DataHigh;} else {EE101DataLow;} EE101ClockHigh; EE101ClockLow;
if (value & 0x01) {EE101DataHigh;} else {EE101DataLow;} EE101ClockHigh; EE101ClockLow;
}
void EE101Value( euint8 channel, eint32 value )
{
#ifdef EE101_DEBUG_ON
EE101IntDisable;
SendEE101Byte( (channel & 0x07) | EE101_VALUE_TYPE | EE101_SYNC);
if ((value > 32767L) || (value < -32768L))
{
SendEE101Byte( value >> 24);
SendEE101Byte( value >> 16);
}
if ((value > 127L) || (value < -128L))
SendEE101Byte( value >> 8);
SendEE101Byte( value );
EE101DataToggle;EE101DataToggle;
EE101IntEnable;
#endif
};
void EE101Text( euint8 channel, echar *string )
{
#ifdef EE101_DEBUG_ON
euint8 bytes = 1;
EE101IntDisable;
SendEE101Byte( (channel&0x07) | EE101_SYNC | EE101_TEXT_TYPE);
while(*string)
{
if (bytes++ > MAX_STRING_LENGTH)
break;
SendEE101Byte( *string++ );
}
EE101DataToggle;EE101DataToggle;
EE101IntEnable;
#endif
};
void EE101TextLabel( euint8 channel, echar *string )
{
#ifdef EE101_DEBUG_ON
static euint8 timeout[8] = {0,0,0,0,0,0,0,0};
euint8 bytes = 1;
channel &= 0x07;
timeout[channel]++;
if ( timeout[channel] != 1 ) return;
EE101IntDisable;
SendEE101Byte( channel | EE101_SYNC | EE101_TEXT_TYPE | EE101_LABEL);
while(*string)
{
if (bytes++ > MAX_STRING_LENGTH)
break;
SendEE101Byte( *string++ );
}
EE101DataToggle;EE101DataToggle;
EE101IntEnable;
#endif
};
void EE101ValueLabel( euint8 channel, echar *string )
{
#ifdef EE101_DEBUG_ON
static euint8 timeout[8] = {0,0,0,0,0,0,0,0};
euint8 bytes = 1;
channel &= 0x07;
timeout[channel]++;
if ( timeout[channel] != 1 ) return;
EE101IntDisable;
SendEE101Byte( channel | EE101_SYNC | EE101_VALUE_TYPE | EE101_LABEL);
while(*string)
{
if (bytes++ > MAX_STRING_LENGTH)
break;
SendEE101Byte( *string++ );
}
EE101DataToggle;EE101DataToggle;
EE101IntEnable;
#endif
};
#endif
#ifdef VARIABLE_ARGUMENT_SUPPORT
echar EE101str[MAX_STRING_LENGTH];
void EE101printf( euint8 channel, echar *format, ... )
{
#ifdef EE101_DEBUG_ON
va_list arglist;
va_start( arglist, format );
vsprintf( EE101str, format, arglist );
va_end( arglist );
EE101Text( channel, EE101str );
#endif
};
#endif
| 2.203125 | 2 |
2024-11-18T22:07:57.982007+00:00 | 2021-09-27T14:40:59 | 837b6210708c94162c89c443bf1d1140b229bd24 | {
"blob_id": "837b6210708c94162c89c443bf1d1140b229bd24",
"branch_name": "refs/heads/master",
"committer_date": "2021-09-27T14:40:59",
"content_id": "2baeb31326d2757b1a6fc8f4dcde2975fca75b13",
"detected_licenses": [
"MIT"
],
"directory_id": "61f9fb96401e7bca1093e47eda64f998006001d2",
"extension": "c",
"filename": "StepperA.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 319625680,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 9008,
"license": "MIT",
"license_type": "permissive",
"path": "/Code/DualStepperController/DualStepperController/StepperA.c",
"provenance": "stackv2-0078.json.gz:238805",
"repo_name": "michaelloose/DualStepperController",
"revision_date": "2021-09-27T14:40:59",
"revision_id": "a18e280ac4612b8b787a3f5217ff0b33215ad7db",
"snapshot_id": "151f0309337082baf55b4d301d950e75f41c76e6",
"src_encoding": "ISO-8859-1",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/michaelloose/DualStepperController/a18e280ac4612b8b787a3f5217ff0b33215ad7db/Code/DualStepperController/DualStepperController/StepperA.c",
"visit_date": "2023-07-31T03:07:33.407668"
} | stackv2 | /*
* StepperA.c
*
* Created: 05.07.2021 11:06:45
* Author: Waxrek
*/
#include "headers.h"
void stepper_a_init(){
eeprom_read_block(&stepper_a_settings, (void*)STEPPER_A_SETTINGS_START_ADDR, sizeof(stepper_a_settings));
stepper_a_moving = 0;
stepper_a_direction = 0;
stepper_a_hasPreviouslyMoved = 0;
stepper_a_hasPreviouslyHomed = 0;
stepper_a_referencing = 0;
stepper_a_prescalerFactor = 0;
stepper_a_setpoint = 0;
stepper_a_position = 0;
//Ausgänge definieren
STEPPER_A_STEP_DDR |= (1 << STEPPER_A_STEP_N);
STEPPER_A_DIRECTION_DDR |= (1 << STEPPER_A_DIRECTION_N);
STEPPER_A_ENABLE_DDR |= (1 << STEPPER_A_ENABLE_N);
//Eingang definieren
STEPPER_A_REFERENCE_DDR &= ~(1 << STEPPER_A_REFERENCE_N);
//Enable auf HIGH setzen
STEPPER_A_ENABLE_PORT &= ~(1<<STEPPER_A_ENABLE_N);
//Register fuer Timer setzen
//Interrupts deaktivieren
cli();
// Register mit 0 initialisieren
STEPPER_A_TIMER_TCCRA = 0b00000000; //Register für PWM
STEPPER_A_TIMER_TCCRB = 0b00011000;//Register für Prescaler: //WGM12 setzen, WGM13 setzen. Aus Irgend einem Grund Behebt das Setzen von WGM13 das Problem, dass nur das Low Byte vom OCRA Register beschrieben wird
STEPPER_A_TIMER_TCNT = 0b00000000; //Counter Register
STEPPER_A_TIMER_TIMSK = 0b00000010;
sei();
stepper_a_setSpeed(stepper_a_settings.speed_default);
}
void stepper_a_loop(USB_ClassInfo_CDC_Device_t* pInterface){
// if (stepper_a_settings.polarity_reference_switch != ((STEPPER_A_REFERENCE_PIN & (1 << STEPPER_A_REFERENCE_N)) == (1 << STEPPER_A_REFERENCE_N)))
// PORTD &= ~(1<<5); //Bit setzen, LED AN
//
// else
// PORTD |= (1<<5); //Bit setzen, LED AUS
//In welchem Zustand befindet sich der Referenzierungsvorgang?
switch (stepper_a_referencing)
{
case 1:
//Antrieb bei aufgerufener Referenzierung ausserhalb des Fangbereiches des Endschalters
//Überprüfe ob Istwert = Sollwert
if(stepper_a_position != stepper_a_setpoint){
stepper_a_setMotionState((stepper_a_position < stepper_a_setpoint)? 1: -1);
}
else{
stepper_a_setMotionState(0);
stepper_a_referencing = 0;
}
break;
case 2:
//Antrieb bei aufgerufener Referenzierung ausserhalb des Fangbereiches des Endschalters
if (stepper_a_settings.polarity_reference_switch != ((STEPPER_A_REFERENCE_PIN & (1 << STEPPER_A_REFERENCE_N)) == (1 << STEPPER_A_REFERENCE_N)))
{
stepper_a_referencing = 1;
stepper_a_position = stepper_a_settings.reference_offset * stepper_a_settings.steps_per_unit;
stepper_a_setpoint = 0;
}
else
{
stepper_a_setMotionState(-1);
}
break;
case 3:
//Befand sich der antrieb bei aufgerufener Referenzierung im Fangbereich des Endschalters?
//Ist der Endschalter noch aktiv?
if (stepper_a_settings.polarity_reference_switch != ((STEPPER_A_REFERENCE_PIN & (1 << STEPPER_A_REFERENCE_N)) == (1 << STEPPER_A_REFERENCE_N)))
{
stepper_a_setMotionState(1);
}
else
{
stepper_a_setMotionState(0);
stepper_a_referencing = 2;
}
break;
default:
//Überprüfe ob Istwert = Sollwert
if(stepper_a_position != stepper_a_setpoint){
stepper_a_setMotionState((stepper_a_position < stepper_a_setpoint)? 1: -1);
}
else{
stepper_a_setMotionState(0);
}
break;
}
if ((stepper_a_moving == 0) && (stepper_a_hasPreviouslyMoved == 1))
{
if (stepper_a_hasPreviouslyHomed && !stepper_a_referencing)
{
stepper_a_hasPreviouslyMoved = 0;
stepper_a_hasPreviouslyHomed = 0;
CDC_Device_SendString(pInterface, "AR!\r");
}
else if(!stepper_a_hasPreviouslyHomed)
{
stepper_a_hasPreviouslyMoved = 0;
CDC_Device_SendString(pInterface, "AP!\r");
}
}
}
void stepper_a_home(){
stepper_a_hasPreviouslyMoved = 1;
stepper_a_hasPreviouslyHomed = 1;
if (stepper_a_settings.polarity_reference_switch != ((STEPPER_A_REFERENCE_PIN & (1 << STEPPER_A_REFERENCE_N)) == (1 << STEPPER_A_REFERENCE_N)))
{
//Status2: Antrieb befindet sich im Fangbereich des Endschalters
stepper_a_referencing = 3;
}
else{
//Status 1: Antrieb befindet sich nicht im Fangbereich des Endschalters
stepper_a_referencing = 2;
}
}
void stepper_a_zero(){
stepper_a_setpoint = 0;
stepper_a_position = 0;
}
void stepper_a_halt(){
stepper_a_referencing = 0;
stepper_a_setpoint = stepper_a_position;
}
uint8_t stepper_a_setSetPoint(double value){
//Prüfen ob Wert in erlaubtem Bereich falls Positionsbegrenzung aktiviert
if(stepper_a_settings.position_limit_enabled && ((value > stepper_a_settings.position_max)||(value < stepper_a_settings.position_min)))
return 1;
else
{
stepper_a_hasPreviouslyMoved = 1;
stepper_a_setpoint = value * stepper_a_settings.steps_per_unit;
}
return 0;
}
double stepper_a_getPosition()
{
return (double)stepper_a_position / stepper_a_settings.steps_per_unit;
}
uint8_t stepper_a_setSpeed(double value){
//Befehl nur akzeptieren wenn Wer
if (value > 0 && ((value <= stepper_a_settings.speed_max)||stepper_a_settings.speed_max_enabled))
{
if ((value * stepper_a_settings.steps_per_unit) > 245)
{
//No Prescaler
stepper_a_prescalerFactor = 1;
}
else if ((value * stepper_a_settings.steps_per_unit) > 31)
{
//Prescaler=8
stepper_a_prescalerFactor = 8;
}
//Die Fälle ab hier sind eigentlich uninteressant, da sich das Teil eh nie so langsam bewegen wird, aber der Vollständigkeit halber nehm ichs mal auf
else if ((value * stepper_a_settings.steps_per_unit) > 4)
{
//Prescaler=64
stepper_a_prescalerFactor = 64;
}
else
{
//Prescaler=256
stepper_a_prescalerFactor = 256;
}
stepper_a_speed_factor = (double)F_CPU / ((double)stepper_a_settings.steps_per_unit * (double)stepper_a_prescalerFactor);
//Subtracting the Length of one Output Pulse (~2.9us per Step) in TimerRegister Units: Used to compensate the Length of the Pulse, so the Speed is accurate
//uint16_t ocr = (uint16_t)(stepper_a_speed_factor / value);
uint16_t ocr = (uint16_t)((stepper_a_speed_factor / value)-((double)PULSE_LEN * ((double)F_CPU / (double)stepper_a_prescalerFactor)));
//_SFR_MEM16(OCRA) = (uint16_t)ocr;
//Disable Interrupts
cli();
//_SFR_MEM8(OCRA+1) = (uint8_t)(ocr>>8);
//_SFR_MEM8(OCRA) = (uint8_t)ocr;
STEPPER_A_TIMER_TCNT = 0;
STEPPER_A_TIMER_OCRA = ocr;
//Enable Interrupts
sei();
return 0;
}
else
{
return 1;
}
}
double stepper_a_getSpeed(){
return (stepper_a_speed_factor/((double)STEPPER_A_TIMER_OCRA + ((double)PULSE_LEN * ((double)F_CPU / (double)stepper_a_prescalerFactor))));
//return (stepper_a_speed_factor / (double)STEPPER_A_TIMER_OCRA);
}
void stepper_a_setMotionState(int8_t state){
if(state < 0 && (!stepper_a_moving || stepper_a_direction)){
stepper_a_direction = 0;
if(stepper_a_settings.invert_direction)
STEPPER_A_DIRECTION_PORT |= (1<<STEPPER_A_DIRECTION_N); //Direction Pin High
else
STEPPER_A_DIRECTION_PORT &= ~(1<<STEPPER_A_DIRECTION_N); //Direction Pin Low
stepper_a_setPrescaler(stepper_a_prescalerFactor);
stepper_a_moving = 1;
}
else if(state > 0 && (!stepper_a_moving || !stepper_a_direction)){
stepper_a_direction = 1;
if(stepper_a_settings.invert_direction)
STEPPER_A_DIRECTION_PORT &= ~(1<<STEPPER_A_DIRECTION_N); //Direction Pin Low
else
STEPPER_A_DIRECTION_PORT |= (1<<STEPPER_A_DIRECTION_N); //Direction Pin High
stepper_a_setPrescaler(stepper_a_prescalerFactor);
stepper_a_moving = 1;
}
else if(state == 0 && stepper_a_moving){
stepper_a_setPrescaler(0);
stepper_a_moving = 0;
}
}
void stepper_a_setPrescaler(int16_t state){
//Disable Interrupts
cli();
switch(state){
case 1:
//No Prescaler
//CS10
STEPPER_A_TIMER_TCCRB |= (1 << 0);//1
//CS11
STEPPER_A_TIMER_TCCRB &=~(1 << 1);//0
//CS12
STEPPER_A_TIMER_TCCRB &=~(1 << 2);//0
break;
case 8:
//Prescaler=8
//CS10
STEPPER_A_TIMER_TCCRB &=~(1 << 0);
//CS11
STEPPER_A_TIMER_TCCRB |= (1 << 1);
//CS12
STEPPER_A_TIMER_TCCRB &=~(1 << 2);
break;
case 64:
//Prescaler=64
//CS10
STEPPER_A_TIMER_TCCRB |= (1 << 0);
//CS11
STEPPER_A_TIMER_TCCRB |= (1 << 1);
//CS12
STEPPER_A_TIMER_TCCRB &=~(1 << 2);
break;
case 256:
//Prescaler=256
//CS10
STEPPER_A_TIMER_TCCRB &=~(1 << 0);
//CS11
STEPPER_A_TIMER_TCCRB &=~(1 << 1);
//CS12
STEPPER_A_TIMER_TCCRB |= (1 << 2);
break;
default:
//Disable Timer, dont dave prescaler State
//CS10
STEPPER_A_TIMER_TCCRB &=~(1 << 0);//0
//CS11
STEPPER_A_TIMER_TCCRB &=~(1 << 1);//0
//CS12
STEPPER_A_TIMER_TCCRB &=~(1 << 2);//0
break;
}
//Enable Interrupts
sei();
}
ISR(STEPPER_A_TIMER_COMPA_vect){
//PORTB ^= (1<<0); //Bit setzen, LED TOGGLE
//PORTD ^= (1<<5); //Bit loeschen, LED TOGGLE
STEPPER_A_TIMER_TCNT = 0;
STEPPER_A_STEP_PORT |= (1<<STEPPER_A_STEP_N); //Step Pin High
if(stepper_a_position == stepper_a_setpoint){
//stepper_a_moving = 1;
stepper_a_setMotionState(0);
}
stepper_a_position += stepper_a_direction ? 1 : -1;
STEPPER_A_STEP_PORT &= ~(1<<STEPPER_A_STEP_N); //Step Pin Low
} | 2.421875 | 2 |
2024-11-18T22:07:58.286942+00:00 | 2018-10-24T10:07:15 | d3187cbff19771676b4d670cc09c2076802e383e | {
"blob_id": "d3187cbff19771676b4d670cc09c2076802e383e",
"branch_name": "refs/heads/master",
"committer_date": "2018-10-24T10:07:15",
"content_id": "d6dc760926bb750c737aec83a76a7818e07f3bf5",
"detected_licenses": [
"MIT"
],
"directory_id": "039fa0aa4d2e18ca32b5a7de21d7e792740e11c9",
"extension": "h",
"filename": "server.h",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 24529884,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2983,
"license": "MIT",
"license_type": "permissive",
"path": "/include/server.h",
"provenance": "stackv2-0078.json.gz:239193",
"repo_name": "pawanpraka1/load_balancer",
"revision_date": "2018-10-24T10:07:15",
"revision_id": "52a5c1a94c2d6f74c91befb6ae34c6d853a4c52f",
"snapshot_id": "dc7d4d5c304d619921602ab8a6f4cd04612dcd69",
"src_encoding": "UTF-8",
"star_events_count": 4,
"url": "https://raw.githubusercontent.com/pawanpraka1/load_balancer/52a5c1a94c2d6f74c91befb6ae34c6d853a4c52f/include/server.h",
"visit_date": "2021-01-01T19:43:21.279171"
} | stackv2 | #ifndef __SERVER
#define __SERVER
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/epoll.h>
#include <fcntl.h>
#include <malloc.h>
#include <assert.h>
#include <unistd.h>
#include <arpa/inet.h>
#define MAX_CLIENT 100
#define BUF_LEN 65536
#define MAX_EVENTS 10
#define true 1
#define false 0
typedef unsigned short int u16bits;
typedef unsigned int u32bits;
#define ERROR_EXIT(str) \
do { \
perror(str); \
exit(-1); \
}while(0);
#define ASSERT(cond) assert((cond))
#define STATIC_ASSERT(a, b) do { switch (0) case 0: case (a): ; } while (0)
#define LB_SERVER 0x1
#define STATS_SERVER 0x2
#define STATS_CONN 0x4
#define BACKEND_SERVER 0x8
#define CONN_CLOSED 0x10
typedef struct session_info {
int buf_len;
int buf_read;
int buf_size;
char buf[BUF_LEN];
struct server_info *server;
} session_info_t;
#define session_info_s sizeof(session_info_t)
typedef struct server_info {
int fd;
u32bits read_events;
u32bits write_events;
u32bits cur_conn;
u32bits tot_unhandled_conn;
u32bits server_flags;
u32bits usage_flags;
struct server_info *next;
struct server_info **prev;
session_info_t *session;
} server_info_t;
#define server_info_s sizeof(server_info_t)
typedef struct bserver_info {
u16bits port;
u16bits cur_conn;
char *ip_str;
struct bserver_info *bnext;
server_info_t *bserver;
} bserver_info_t;
#define bserver_info_s sizeof(bserver_info_t)
extern int read_event_handler(server_info_t *server, int efd);
extern int write_event_handler(server_info_t *server);
extern int init_listening_socket(u16bits port);
extern server_info_t *create_server_info(int fd);
extern server_info_t *create_backend_server();
extern server_info_t *create_client_info(int efd, int fd);
extern bserver_info_t *create_bserver_info(char *ip, u16bits port);
extern void init_backend_server(int efd);
extern void init_epoll_events(server_info_t *server, int efd);
extern int attach_backend_lbserver(int efd, server_info_t *client_info);
extern bserver_info_t *get_next_lbserver();
extern void insert_client_info(server_info_t *client_info);
extern void remove_server_info(server_info_t *client_info);
extern void insert_into_cpool(server_info_t *client_info);
extern void remove_server_cpool(server_info_t *client_info);
extern void remove_form_cpool(server_info_t *client_info);
extern void close_server_conn(int efd, server_info_t *server);
extern void close_client_conn(server_info_t *client);
extern void close_client_pconn(server_info_t *client);
extern void close_conn(int efd, server_info_t *server);
extern void insert_backend_server(server_info_t *server);
extern void mark_pending_event_invalid(void *sptr);
extern server_info_t *lb_server;
extern server_info_t *stats_server;
extern server_info_t *client_info_head;
extern bserver_info_t *bserver_head;
extern struct epoll_event cur_events[MAX_EVENTS];
extern int event_count;
#endif
| 2.0625 | 2 |
2024-11-18T22:07:58.784462+00:00 | 2022-03-10T17:59:49 | 6031adde9bde6a75b9db8655718ca51c9e02f485 | {
"blob_id": "6031adde9bde6a75b9db8655718ca51c9e02f485",
"branch_name": "refs/heads/master",
"committer_date": "2022-03-10T17:59:49",
"content_id": "39c369e8028c3f1c3e5961bacbaa416e9e462a8f",
"detected_licenses": [
"MIT"
],
"directory_id": "37a494ad71a75df0c5113bbc3c06f94eccaf8e57",
"extension": "c",
"filename": "range_sum.c",
"fork_events_count": 2,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 216613841,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 540,
"license": "MIT",
"license_type": "permissive",
"path": "/src/tree/binary-search-tree/range_sum.c",
"provenance": "stackv2-0078.json.gz:239450",
"repo_name": "Jannchie/algorithm-c",
"revision_date": "2022-03-10T17:59:49",
"revision_id": "59983b61b29ff7fc653ffc7ecdfb7e23842ee375",
"snapshot_id": "14c5ba76dce44da670365429c80ccb8070a49578",
"src_encoding": "UTF-8",
"star_events_count": 11,
"url": "https://raw.githubusercontent.com/Jannchie/algorithm-c/59983b61b29ff7fc653ffc7ecdfb7e23842ee375/src/tree/binary-search-tree/range_sum.c",
"visit_date": "2022-05-04T21:15:21.237247"
} | stackv2 | #include "tree.h"
int rangeSumBST(struct TreeNode *root, int L, int R)
{
if (root == 0)
{
return 0;
}
if (root->val <= R && root->val >= L)
{
return root->val + rangeSumBST(root->left, L, R) + rangeSumBST(root->right, L, R);
}
else if (root->val < L)
{
return rangeSumBST(root->right, L, R);
}
else
{
return rangeSumBST(root->left, L, R);
}
}
int main(int argc, char const *argv[])
{
struct TreeNode *root = create_binary_search_tree(10);
return 0;
}
| 2.75 | 3 |
2024-11-18T20:41:30.900219+00:00 | 2021-07-23T20:02:23 | 13c77d6010cdfbf8f5c293e39da46a171ac39487 | {
"blob_id": "13c77d6010cdfbf8f5c293e39da46a171ac39487",
"branch_name": "refs/heads/master",
"committer_date": "2021-07-23T20:02:23",
"content_id": "0a9e53289081dc963be4ecaf0f0360dff2a1de42",
"detected_licenses": [
"MIT"
],
"directory_id": "88886d17f78d3d09675b5aa6b656d8617d411d55",
"extension": "h",
"filename": "mb704x.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": 1467,
"license": "MIT",
"license_type": "permissive",
"path": "/src/mb704x/mb704x.h",
"provenance": "stackv2-0082.json.gz:31135",
"repo_name": "vscherbo/upm",
"revision_date": "2021-07-23T20:02:23",
"revision_id": "d6f76ff8c231417666594214679c49399513112e",
"snapshot_id": "e031a90b925072c474b7855dee084fb36a8c7fee",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/vscherbo/upm/d6f76ff8c231417666594214679c49399513112e/src/mb704x/mb704x.h",
"visit_date": "2023-06-18T21:50:14.692887"
} | stackv2 | /*
* Author: Jon Trulson <[email protected]>
* Copyright (c) 2016 Intel Corporation.
*
* This program and the accompanying materials are made available under the
* terms of the The MIT License which is available at
* https://opensource.org/licenses/MIT.
*
* SPDX-License-Identifier: MIT
*/
#pragma once
#include <stdint.h>
#include <upm.h>
#include <mraa/i2c.h>
#include <mraa/gpio.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* @file mb704x.h
* @library mb704x
* @brief C API for the MB704x MaxSonar-WR Ultrasonic Ranger
*
* @include mb704x.c
*/
/**
* Device context
*/
typedef struct _mb704x_context {
mraa_i2c_context i2c;
} *mb704x_context;
/**
* MB704X Initializer
*
* @param bus Specify which the I2C bus to use.
* @param addr Specify the I2C address to use. The default is 112.
* @return an initialized device context on success, NULL on error.
*/
mb704x_context mb704x_init(unsigned int bus, int addr);
/**
* MB704X sensor close function
*/
void mb704x_close(mb704x_context dev);
/**
* Query the device for a range reading. The range will be
* reported in centimeters (cm).
*
* @param dev Device context
* @return Measured range, -1 on error. The range is reported in
* centimeters (cm).
*/
int mb704x_get_range(const mb704x_context dev);
#ifdef __cplusplus
}
#endif
| 2.03125 | 2 |
2024-11-18T20:41:31.002219+00:00 | 2021-01-15T16:51:19 | 88ebea7d85309f4664f6be19badea230352f02b9 | {
"blob_id": "88ebea7d85309f4664f6be19badea230352f02b9",
"branch_name": "refs/heads/master",
"committer_date": "2021-01-15T16:51:19",
"content_id": "8db5c77c07efc87f80538f7a51f0fc0f263186df",
"detected_licenses": [
"MIT"
],
"directory_id": "9d271d667bb9058babb61370c4cdb0569bb23cc7",
"extension": "c",
"filename": "drv_cs4322.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": 5499,
"license": "MIT",
"license_type": "permissive",
"path": "/test/Backup/TASKING_STM32F4DISC_Audio_Service/SoftwarePlatform/platform/external/drivers/cs4322/src/drv_cs4322.c",
"provenance": "stackv2-0082.json.gz:31263",
"repo_name": "Ever-Never/trice",
"revision_date": "2021-01-15T16:51:19",
"revision_id": "afbdaf03e918b0092d8621d7e15abb1ffc395bca",
"snapshot_id": "2f6d5e10f0bf1a1b985c052d77463c8bf52f21f7",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Ever-Never/trice/afbdaf03e918b0092d8621d7e15abb1ffc395bca/test/Backup/TASKING_STM32F4DISC_Audio_Service/SoftwarePlatform/platform/external/drivers/cs4322/src/drv_cs4322.c",
"visit_date": "2023-02-17T23:17:42.191251"
} | stackv2 | /* ------------------------------------------------------------
**
** Copyright (c) 2013-2015 Altium Limited
**
** This software is the proprietary, copyrighted property of
** Altium Ltd. All Right Reserved.
**
** SVN revision information:
** $Rev: 14907 $:
** $Date: 2015-01-19 13:30:51 +0100 (Mon, 19 Jan 2015) $:
**
** ------------------------------------------------------------
*/
/**
* @file
* Device driver for CS4322 24-bit, 192 kHz Stereo Audio CODEC
*/
#include <stdlib.h>
#include <stdint.h>
#include <assert.h>
#include <drv_i2cm.h>
#include <drv_cs4322.h>
#include <drv_cs4322_cfg_instance.h>
struct cs4322_s
{
uint8_t i2c_address;
i2cm_t * i2cm;
uint8_t if_ctrl1;
} ;
static cs4322_t drv_table[DRV_CS4322_INSTANCE_COUNT];
/**
* @brief Open an instance of the device driver and initialize
*
* This function initializes an instance of both, the device driver and the underlying
* hardware. You should call this function only once per instance.
*
* Note: you must make sure the device is properly reset before you call this function.
* On the STM3210C-EVAL evaluation board, the reset is tied to pin IN2 from the second
* I/O expander (I2C address 0x88). You must raise this pin before calling cs4322_open()!
*
* @param id Device driver instance number
*
* @return Pointer to device driver context structure or NULL on failure
*/
cs4322_t * cs4322_open( unsigned int id )
{
assert( id < DRV_CS4322_INSTANCE_COUNT );
cs4322_t * restrict drv = &drv_table[id];
const drv_cs4322_cfg_instance_t * restrict drv_cfg = &drv_cs4322_instance_table[id];
i2cm_t * i2cm;
uint8_t val;
if ( !drv->i2cm )
{
drv->i2c_address = drv_cfg->i2c_address;
drv->if_ctrl1 = drv_cfg->i2s_standard | drv_cfg->i2s_dataformat | drv_cfg->i2s_cpol;
if (i2cm = i2cm_open( drv_cfg->drv_i2cm ), !i2cm )
{
drv = NULL;
}
else if ( (i2cm_read_reg8( i2cm, drv->i2c_address, CS4322_REG_ID, &val ) != 1) || (val & 0xF8) != 0xE0 )
{
drv = NULL;
}
else
{
drv->i2cm = i2cm;
}
if ( drv )
{
cs4322_init( drv );
}
}
return drv;
}
/**
* @brief Initialize the CS43L22
*
* This function initializes the CODEC to something useful. You must reset CODEC first through
* it's RESET line to make sure the initialization is correct.
*
* Initialization sequence: power down, auto detect headphone & speakers, I2S standard Phillips,
* master volume 0 dB and power up
*
* @param drv Pointer to device driver context as returned from cs4322_open()
*/
void cs4322_init( cs4322_t * restrict drv )
{
i2cm_write_reg8( drv->i2cm, drv->i2c_address, CS4322_REG_PWR_CTRL1, 0x01 ); // Power down
i2cm_write_reg8( drv->i2cm, drv->i2c_address, CS4322_REG_PWR_CTRL2, 0x05 ); // Detect headphone & speaker channels automagically
i2cm_write_reg8( drv->i2cm, drv->i2c_address, CS4322_REG_CLK_CTRL, 0x81 ); // Speed auto detect
i2cm_write_reg8( drv->i2cm, drv->i2c_address, CS4322_REG_IF_CTRL1, drv->if_ctrl1 );
cs4322_set_volume( drv, 208 ); // Set master volume to 0 dB
i2cm_write_reg8( drv->i2cm, drv->i2c_address, CS4322_REG_PWR_CTRL1, 0x9E ); // Power up
}
/**
* @brief This function is an empty stub, the CS43L22 uses automatic speed detection through MCLK
*
* @param drv Pointer to device driver context as returned from cs4322_open()
*/
void cs4322_set_speed( cs4322_t * restrict drv, unsigned int clockspeed )
{
}
/**
* @brief Set I2S data format. To be implemented.
*
* @param drv Pointer to device driver context as returned from cs4322_open()
* @param format I2S data format
*/
void cs4322_set_format( cs4322_t * restrict drv, uint8_t format )
{
}
/**
* @brief Controls the master volume
*
* Master volume can be set from +12dB to -102dB in steps of 0.5dB. 0xFF = +12dB, 0x00 = -120dB.
*
* @param drv Pointer to device driver context as returned from cs4322_open()
* @param volume Volume to be set
*/
void cs4322_set_volume( cs4322_t * restrict drv, uint8_t volume )
{
/* Set the Master volume */
volume += 0x18 - 0xFF;
i2cm_write_reg8( drv->i2cm, drv->i2c_address, CS4322_REG_MASTER_VOL_A, volume );
i2cm_write_reg8( drv->i2cm, drv->i2c_address, CS4322_REG_MASTER_VOL_B, volume );
}
/**
* @brief Start playing
*
* This function un-mutes the CODEC
*
* @param drv Pointer to device driver context as returned from cs4322_open()
*/
void cs4322_play( cs4322_t * restrict drv )
{
// Unmute
i2cm_write_reg8( drv->i2cm, drv->i2c_address, CS4322_REG_PLAY_CTRL1, 0x60 );
i2cm_write_reg8( drv->i2cm, drv->i2c_address, CS4322_REG_PLAY_CTRL2, 0x08 );
}
/**
* @brief This function is a stub, the CS43L22 does not provide audio input
*
* @param drv Pointer to device driver context as returned from cs4322_open()
*/
void cs4322_record( cs4322_t * restrict drv )
{
// Not implemented
}
/**
* @brief Stop playing
*
* This function mutes the CODEC by muting master playback in the playback control registers
*
* @param drv Pointer to device driver context as returned from cs4322_open()
*/
void cs4322_stop( cs4322_t * restrict drv )
{
// Play control "Mute"
i2cm_write_reg8( drv->i2cm, drv->i2c_address, CS4322_REG_PLAY_CTRL1, 0x63 );
i2cm_write_reg8( drv->i2cm, drv->i2c_address, CS4322_REG_PLAY_CTRL2, 0xF8 );
}
| 2.609375 | 3 |
2024-11-18T20:56:19.265674+00:00 | 2018-11-19T22:01:36 | e0af8fe417b37885cc78c312a2db4a2b32e15799 | {
"blob_id": "e0af8fe417b37885cc78c312a2db4a2b32e15799",
"branch_name": "refs/heads/master",
"committer_date": "2018-11-19T22:01:36",
"content_id": "43504a63da6ae35d22b858929c9edcaf3cd5bb6e",
"detected_licenses": [
"CC0-1.0"
],
"directory_id": "31781f54eb4eb8e3554b6133d1d32a9ae6ecbd71",
"extension": "c",
"filename": "bignum-mul.c",
"fork_events_count": 2,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 31087445,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2322,
"license": "CC0-1.0",
"license_type": "permissive",
"path": "/bignum-mul.c",
"provenance": "stackv2-0082.json.gz:226044",
"repo_name": "ctz/bignum",
"revision_date": "2018-11-19T22:01:36",
"revision_id": "88e680d29a7ccddef4bc8c57b48854c0527a550a",
"snapshot_id": "3291046b82abf0dc0a6d98341c274148ff022b42",
"src_encoding": "UTF-8",
"star_events_count": 11,
"url": "https://raw.githubusercontent.com/ctz/bignum/88e680d29a7ccddef4bc8c57b48854c0527a550a/bignum-mul.c",
"visit_date": "2023-03-23T15:57:54.012552"
} | stackv2 |
#include <assert.h>
#include <string.h>
#include <stdio.h>
#include "bignum.h"
#include "bignum-math.h"
#include "handy.h"
error bignum_mul(bignum *r, const bignum *a, const bignum *b)
{
assert(!bignum_check_mutable(r));
assert(!bignum_check(a));
assert(!bignum_check(b));
size_t sza = bignum_len_bits(a);
size_t szb = bignum_len_bits(b);
/* Shortcuts? */
/* x * 0 -> 0 */
if (bignum_eq32(a, 0) || bignum_eq32(b, 0))
{
bignum_set(r, 0);
return OK;
}
/* 1 * b -> b */
if (bignum_eq32(a, 1))
return bignum_dup(r, b);
/* a * 1 -> a */
if (bignum_eq32(b, 1))
return bignum_dup(r, a);
if (bignum_capacity_bits(r) < sza + szb)
return error_bignum_sz;
/* Ensure a <= b. */
if (sza > szb)
{
SWAP(a, b);
SWAP(sza, szb);
}
/* We cannot alias. */
assert(r != a && r != b);
bignum_set(r, 0);
ER(bignum_cleartop(r, (sza + szb + 31) / 32));
size_t nb = bignum_len_words(b);
for (uint32_t *wr = r->v, *wa = a->v, *wb = b->v;
wa <= a->vtop;
wa++, wr++)
{
bignum_math_mul_accum(wr, wb, nb, *wa);
}
unsigned nega = bignum_is_negative(a),
negb = bignum_is_negative(b);
bignum_setsign(r, (nega ^ negb) ? -1 : 1);
bignum_canon(r);
return OK;
}
error bignum_mulw(bignum *r, const bignum *a, uint32_t b)
{
if (b == 0)
{
bignum_set(r, 0);
return OK;
} else if (b == 1) {
return bignum_dup(r, a);
}
assert(!bignum_check_mutable(r));
assert(!bignum_check(a));
assert(r != a);
uint8_t sza = bignum_len_bits(a);
uint8_t szb = bignum_math_uint32_fls(b);
if (bignum_capacity_bits(r) < sza + szb)
return error_bignum_sz;
size_t words = bignum_len_words(a);
bignum_set(r, 0);
ER(bignum_cleartop(r, words + 1));
bignum_math_mul_accum(r->v, a->v, words, b);
bignum_canon(r);
return OK;
}
error bignum_mult(bignum *tmp, bignum *r, const bignum *a, const bignum *b)
{
if (r == a || r == b)
{
error err = bignum_mul(tmp, a, b);
if (err)
return err;
return bignum_dup(r, tmp);
}
return bignum_mul(r, a, b);
}
error bignum_multw(bignum *tmp, bignum *r, const bignum *a, uint32_t w)
{
if (r == a)
{
error err = bignum_mulw(tmp, a, w);
if (err)
return err;
return bignum_dup(r, tmp);
}
return bignum_mulw(r, a, w);
}
| 2.890625 | 3 |
2024-11-18T20:56:19.526508+00:00 | 2020-12-12T10:00:30 | 1665fb3a1ab23bd16f7aaca1766da4e0f06abc31 | {
"blob_id": "1665fb3a1ab23bd16f7aaca1766da4e0f06abc31",
"branch_name": "refs/heads/master",
"committer_date": "2020-12-14T15:18:01",
"content_id": "5f3499b63d8725c520c669758bd1cc37a264f848",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "b0e1dc5376b0b0d4812ac77ceec82c69c7bfb9d0",
"extension": "h",
"filename": "caam_utils_mem.h",
"fork_events_count": 0,
"gha_created_at": "2019-10-06T18:07:41",
"gha_event_created_at": "2019-10-06T18:07:41",
"gha_language": null,
"gha_license_id": "NOASSERTION",
"github_id": 213218431,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3781,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/core/drivers/crypto/caam/include/caam_utils_mem.h",
"provenance": "stackv2-0082.json.gz:226300",
"repo_name": "mmind/optee_os",
"revision_date": "2020-12-12T10:00:30",
"revision_id": "0d016aff429d1a7579cf6577b99dd627379c5800",
"snapshot_id": "d9b7fc8d8c8ba9c3cf564b0666fff453457ba467",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/mmind/optee_os/0d016aff429d1a7579cf6577b99dd627379c5800/core/drivers/crypto/caam/include/caam_utils_mem.h",
"visit_date": "2021-07-06T09:06:31.722533"
} | stackv2 | /* SPDX-License-Identifier: BSD-2-Clause */
/*
* Copyright 2018-2020 NXP
*
* Brief Memory management utilities.
* Primitive to allocate, free memory.
*/
#ifndef __CAAM_UTILS_MEM_H__
#define __CAAM_UTILS_MEM_H__
#include <caam_common.h>
/*
* Allocate normal memory and initialize it to 0's.
*
* @size size in bytes of the memory to allocate
*/
void *caam_calloc(size_t size);
/*
* Allocate memory aligned with a cache line and initialize it to 0's.
*
* @size size in bytes of the memory to allocate
*/
void *caam_calloc_align(size_t size);
/*
* Free allocated memory
*
* @ptr reference to the object to free
*/
void caam_free(void *ptr);
/*
* Allocate Job descriptor and initialize it to 0's.
*
* @nbentries Number of descriptor entries
*/
uint32_t *caam_calloc_desc(uint8_t nbentries);
/*
* Free descriptor
*
* @ptr Reference to the descriptor to free
*/
void caam_free_desc(uint32_t **ptr);
/*
* Allocate internal driver buffer and initialize it with 0s.
*
* @buf [out] buffer allocated
* @size size in bytes of the memory to allocate
*/
enum caam_status caam_calloc_buf(struct caambuf *buf, size_t size);
/*
* Allocate internal driver buffer aligned with a cache line and initialize
* if with 0's.
*
* @buf [out] buffer allocated
* @size size in bytes of the memory to allocate
*/
enum caam_status caam_calloc_align_buf(struct caambuf *buf, size_t size);
/*
* Allocate internal driver buffer aligned with a cache line.
*
* @buf [out] buffer allocated
* @size size in bytes of the memory to allocate
*/
enum caam_status caam_alloc_align_buf(struct caambuf *buf, size_t size);
/*
* Free internal driver buffer allocated memory
*
* @buf Driver buffer to free
*/
void caam_free_buf(struct caambuf *buf);
/*
* Free data of type struct caamsgtbuf
*
* @data Data object to free
*/
void caam_sgtbuf_free(struct caamsgtbuf *data);
/*
* Allocate data of type struct caamsgtbuf
*
* @data [out] Data object allocated
*/
enum caam_status caam_sgtbuf_alloc(struct caamsgtbuf *data);
/*
* Initialize struct caambuf with buffer reference, eventually
* reallocating the buffer if not matching cache line alignment.
*
* @orig Buffer origin
* @dst [out] CAAM Buffer object with origin or reallocated buffer
* @size Size in bytes of the buffer
* @realloc [out] true if buffer has been reallocated
*/
enum caam_status caam_set_or_alloc_align_buf(void *orig, struct caambuf *dst,
size_t size, bool *realloc);
/*
* Copy source data into the block buffer. Allocate block buffer if
* it's not defined.
*
* @block [in/out] Block buffer information. Return buffer filled.
* @src Source to copy
* @offset Source offset to start
*/
enum caam_status caam_cpy_block_src(struct caamblock *block,
struct caambuf *src, size_t offset);
/*
* Return the number of Physical Areas used by the buffer @buf.
* If @pabufs is not NULL, function fills it with the Physical Areas used
* to map the buffer @buf.
*
* @buf Data buffer to analyze
* @pabufs[out] If not NULL, list the Physical Areas of the @buf
*
* Returns:
* Number of physical area used
* (-1) if error
*/
int caam_mem_get_pa_area(struct caambuf *buf, struct caambuf **pabufs);
/*
* Return if the buffer @buf is cacheable or not
*
* @buf Buffer address
* @size Buffer size
*/
bool caam_mem_is_cached_buf(void *buf, size_t size);
/*
* Copy source data into the destination buffer removing non-significant
* first zeros (left zeros).
* If all source @src buffer is zero, left only one zero in the destination.
*
* @dst [out] Destination buffer
* @src Source to copy
*/
void caam_mem_cpy_ltrim_buf(struct caambuf *dst, struct caambuf *src);
#endif /* __CAAM_UTILS_MEM_H__ */
| 2.65625 | 3 |
2024-11-18T21:05:50.867140+00:00 | 2019-04-17T10:18:20 | 452798b07c671c52c821363be9d345733177a0f1 | {
"blob_id": "452798b07c671c52c821363be9d345733177a0f1",
"branch_name": "refs/heads/master",
"committer_date": "2019-04-17T10:18:20",
"content_id": "cbabf3a041c13e4800883069112e789c760c7997",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "6e0e3fc995f11b0aecd2d06fc542f13a4cfe4edf",
"extension": "c",
"filename": "adx_rbtree.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": 10301,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/nginx-1.12.2/src/adx_com_libs/adx_rbtree.c",
"provenance": "stackv2-0083.json.gz:559",
"repo_name": "bellmit/adx-dsp",
"revision_date": "2019-04-17T10:18:20",
"revision_id": "eabcb76dfcb72ac21717b7804a38969a6c2779ce",
"snapshot_id": "82891b039522517639da3cf5e7ff5a3f64f7de79",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/bellmit/adx-dsp/eabcb76dfcb72ac21717b7804a38969a6c2779ce/nginx-1.12.2/src/adx_com_libs/adx_rbtree.c",
"visit_date": "2022-04-13T15:10:52.573758"
} | stackv2 |
#include "adx_rbtree.h"
void adx_rbtree_set_parent(adx_rbtree_node *rb, adx_rbtree_node *p)
{
rb->rb_parent_color = (rb->rb_parent_color & 3) | (unsigned long)p;
}
void adx_rbtree_set_color(adx_rbtree_node *rb, int color)
{
rb->rb_parent_color = (rb->rb_parent_color & ~1) | color;
}
void adx_rbtree_link_node(adx_rbtree_node *node, adx_rbtree_node *parent, adx_rbtree_node **rb_link)
{
node->rb_parent_color = (unsigned long )parent;
node->rb_left = node->rb_right = NULL;
*rb_link = node;
}
void adx_rbtree_rotate_left(adx_rbtree_node *node, adx_rbtree_head *head)
{
adx_rbtree_node *right = node->rb_right;
adx_rbtree_node *parent = rb_parent(node);
if ((node->rb_right = right->rb_left))
adx_rbtree_set_parent(right->rb_left, node);
right->rb_left = node;
adx_rbtree_set_parent(right, parent);
if (parent) {
if (node == parent->rb_left)
parent->rb_left = right;
else
parent->rb_right = right;
} else {
head->rb_node = right;
}
adx_rbtree_set_parent(node, right);
}
void adx_rbtree_rotate_right(adx_rbtree_node *node, adx_rbtree_head *head)
{
adx_rbtree_node *left = node->rb_left;
adx_rbtree_node *parent = rb_parent(node);
if ((node->rb_left = left->rb_right))
adx_rbtree_set_parent(left->rb_right, node);
left->rb_right = node;
adx_rbtree_set_parent(left, parent);
if (parent) {
if (node == parent->rb_right)
parent->rb_right = left;
else
parent->rb_left = left;
} else {
head->rb_node = left;
}
adx_rbtree_set_parent(node, left);
}
void adx_rbtree_insert_color(adx_rbtree_node *node, adx_rbtree_head *head)
{
adx_rbtree_node *parent, *gparent;
while ((parent = rb_parent(node)) && rb_is_red(parent)) {
gparent = rb_parent(parent);
if (parent == gparent->rb_left) {
register adx_rbtree_node *uncle = gparent->rb_right;
if (uncle && rb_is_red(uncle)) {
rb_set_black(uncle);
rb_set_black(parent);
rb_set_red(gparent);
node = gparent;
continue;
}
if (parent->rb_right == node) {
register adx_rbtree_node *tmp;
adx_rbtree_rotate_left(parent, head);
tmp = parent;
parent = node;
node = tmp;
}
rb_set_black(parent);
rb_set_red(gparent);
adx_rbtree_rotate_right(gparent, head);
} else {
register adx_rbtree_node *uncle = gparent->rb_left;
if (uncle && rb_is_red(uncle)) {
rb_set_black(uncle);
rb_set_black(parent);
rb_set_red(gparent);
node = gparent;
continue;
}
if (parent->rb_left == node) {
register adx_rbtree_node *tmp;
adx_rbtree_rotate_right(parent, head);
tmp = parent;
parent = node;
node = tmp;
}
rb_set_black(parent);
rb_set_red(gparent);
adx_rbtree_rotate_left(gparent, head);
}
}
rb_set_black(head->rb_node);
}
void adx_rbtree_delete_color(adx_rbtree_node *node, adx_rbtree_node *parent, adx_rbtree_head *head)
{
adx_rbtree_node *other = NULL;
while ((!node || rb_is_black(node)) && node != head->rb_node) {
if (parent->rb_left == node) {
other = parent->rb_right;
if (rb_is_red(other)) {
rb_set_black(other);
rb_set_red(parent);
adx_rbtree_rotate_left(parent, head);
other = parent->rb_right;
}
if ((!other->rb_left || rb_is_black(other->rb_left)) &&
(!other->rb_right || rb_is_black(other->rb_right))) {
rb_set_red(other);
node = parent;
parent = rb_parent(node);
} else {
if (!other->rb_right || rb_is_black(other->rb_right)) {
rb_set_black(other->rb_left);
rb_set_red(other);
adx_rbtree_rotate_right(other, head);
other = parent->rb_right;
}
adx_rbtree_set_color(other, rb_color(parent));
rb_set_black(parent);
rb_set_black(other->rb_right);
adx_rbtree_rotate_left(parent, head);
node = head->rb_node;
break;
}
} else {
other = parent->rb_left;
if (rb_is_red(other)) {
rb_set_black(other);
rb_set_red(parent);
adx_rbtree_rotate_right(parent, head);
other = parent->rb_left;
}
if ((!other->rb_left || rb_is_black(other->rb_left)) &&
(!other->rb_right || rb_is_black(other->rb_right))) {
rb_set_red(other);
node = parent;
parent = rb_parent(node);
} else {
if (!other->rb_left || rb_is_black(other->rb_left)) {
rb_set_black(other->rb_right);
rb_set_red(other);
adx_rbtree_rotate_left(other, head);
other = parent->rb_left;
}
adx_rbtree_set_color(other, rb_color(parent));
rb_set_black(parent);
rb_set_black(other->rb_left);
adx_rbtree_rotate_right(parent, head);
node = head->rb_node;
break;
}
}
}
if (node)rb_set_black(node);
}
void adx_rbtree_delete(adx_rbtree_head *head, adx_rbtree_node *node)
{
int color;
adx_rbtree_node *child, *parent;
if (!node->rb_left) {
child = node->rb_right;
} else if (!node->rb_right) {
child = node->rb_left;
} else {
adx_rbtree_node *old = node, *left;
node = node->rb_right;
while ((left = node->rb_left) != NULL)
node = left;
if (rb_parent(old)) {
if (rb_parent(old)->rb_left == old)
rb_parent(old)->rb_left = node;
else
rb_parent(old)->rb_right = node;
} else {
head->rb_node = node;
}
child = node->rb_right;
parent = rb_parent(node);
color = rb_color(node);
if (parent == old) {
parent = node;
} else {
if (child)adx_rbtree_set_parent(child, parent);
parent->rb_left = child;
node->rb_right = old->rb_right;
adx_rbtree_set_parent(old->rb_right, node);
}
node->rb_parent_color = old->rb_parent_color;
node->rb_left = old->rb_left;
adx_rbtree_set_parent(old->rb_left, node);
if (color == 1)adx_rbtree_delete_color(child, parent, head);
return;
}
parent = rb_parent(node);
color = rb_color(node);
if (child)adx_rbtree_set_parent(child, parent);
if (parent) {
if (parent->rb_left == node)
parent->rb_left = child;
else
parent->rb_right = child;
} else {
head->rb_node = child;
}
if (color == 1)adx_rbtree_delete_color(child, parent, head);
}
/* string */
adx_rbtree_node *adx_rbtree_string_add(adx_rbtree_head *head, adx_rbtree_node *new_node)
{
adx_rbtree_node *parent = NULL;
adx_rbtree_node **p = &head->rb_node;
adx_rbtree_node *node = NULL;
if (new_node->string == NULL)
return NULL;
while (*p) {
parent = *p;
node = (adx_rbtree_node *)parent;
if (node->string == NULL)
return NULL;
int retval = strcmp(new_node->string, node->string);
if (retval < 0) {
p = &(*p)->rb_left;
} else if (retval > 0) {
p = &(*p)->rb_right;
} else {
return NULL;
}
}
adx_rbtree_link_node(new_node, parent, p);
adx_rbtree_insert_color(new_node, head);
return node;
}
adx_rbtree_node *adx_rbtree_string_find(adx_rbtree_head *head, const char *key)
{
adx_rbtree_node *p = head->rb_node;
adx_rbtree_node *node = NULL;
if (key == NULL)
return NULL;
while (p) {
node = (adx_rbtree_node *)p;
if (node->string == NULL)
return NULL;
int retval = strcmp(key, node->string);
if (retval < 0) {
p = p->rb_left;
} else if (retval > 0) {
p = p->rb_right;
} else {
return node;
}
}
return NULL;
}
/* number */
adx_rbtree_node *adx_rbtree_number_add(adx_rbtree_head *head, adx_rbtree_node *new_node)
{
adx_rbtree_node *parent = NULL;
adx_rbtree_node **p = &head->rb_node;
adx_rbtree_node *node = NULL;
while (*p) {
parent = *p;
node = (adx_rbtree_node *)parent;
if (new_node->number < node->number) {
p = &(*p)->rb_left;
} else if (new_node->number > node->number) {
p = &(*p)->rb_right;
} else {
return NULL;
}
}
adx_rbtree_link_node(new_node, parent, p);
adx_rbtree_insert_color(new_node, head);
return node;
}
adx_rbtree_node *adx_rbtree_number_find(adx_rbtree_head *head, int key)
{
adx_rbtree_node *p = head->rb_node;
adx_rbtree_node *node = NULL;
while (p) {
node = (adx_rbtree_node *)p;
if (key < node->number) {
p = p->rb_left;
} else if (key > node->number) {
p = p->rb_right;
} else {
return node;
}
}
return NULL;
}
void _adx_rbtree_print(adx_rbtree_node *p)
{
// adx_rbtree_node *node = (adx_rbtree_node *)p;
// fprintf(stdout, "[tree][%d][%s]\n", node->number, node->string);
if (p->rb_left) _adx_rbtree_print(p->rb_left);
if (p->rb_right)_adx_rbtree_print(p->rb_right);
}
void adx_rbtree_print(adx_rbtree_head *head)
{
if (!head->rb_node) return;
_adx_rbtree_print(head->rb_node);
}
| 2.90625 | 3 |
2024-11-18T21:05:51.232618+00:00 | 2010-03-10T17:29:38 | 4a8ef6af1d5ab66494c076fe94b42bbef67c7794 | {
"blob_id": "4a8ef6af1d5ab66494c076fe94b42bbef67c7794",
"branch_name": "refs/heads/eclair",
"committer_date": "2010-03-10T17:29:38",
"content_id": "a642d0bb281e9dbb87293f40ba4f7985a45694b3",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "6b115e4281f3c9113f7a5e65d607767e6cfffe82",
"extension": "c",
"filename": "permissions.c",
"fork_events_count": 1,
"gha_created_at": "2010-02-28T22:14:02",
"gha_event_created_at": "2019-04-15T20:10:53",
"gha_language": "C",
"gha_license_id": null,
"github_id": 540375,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 7012,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/amend/permissions.c",
"provenance": "stackv2-0083.json.gz:1074",
"repo_name": "packetlss/android_bootable_recovery",
"revision_date": "2010-03-10T17:29:38",
"revision_id": "d42f1a7b1683371f2f0d5e45a6e09ab37ed9ce80",
"snapshot_id": "1c8dc49e24f391411bd08081852848e41c7d88fa",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/packetlss/android_bootable_recovery/d42f1a7b1683371f2f0d5e45a6e09ab37ed9ce80/amend/permissions.c",
"visit_date": "2021-01-01T17:57:39.687031"
} | 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 <stdlib.h>
#include <string.h>
#include "permissions.h"
int
initPermissionRequestList(PermissionRequestList *list)
{
if (list != NULL) {
list->requests = NULL;
list->numRequests = 0;
list->requestsAllocated = 0;
return 0;
}
return -1;
}
int
addPermissionRequestToList(PermissionRequestList *list,
const char *path, bool recursive, unsigned int permissions)
{
if (list == NULL || list->numRequests < 0 ||
list->requestsAllocated < list->numRequests || path == NULL)
{
return -1;
}
if (list->numRequests == list->requestsAllocated) {
int newSize;
PermissionRequest *newRequests;
newSize = list->requestsAllocated * 2;
if (newSize < 16) {
newSize = 16;
}
newRequests = (PermissionRequest *)realloc(list->requests,
newSize * sizeof(PermissionRequest));
if (newRequests == NULL) {
return -2;
}
list->requests = newRequests;
list->requestsAllocated = newSize;
}
PermissionRequest *req;
req = &list->requests[list->numRequests++];
req->path = strdup(path);
if (req->path == NULL) {
list->numRequests--;
return -3;
}
req->recursive = recursive;
req->requested = permissions;
req->allowed = 0;
return 0;
}
void
freePermissionRequestListElements(PermissionRequestList *list)
{
if (list != NULL && list->numRequests >= 0 &&
list->requestsAllocated >= list->numRequests)
{
int i;
for (i = 0; i < list->numRequests; i++) {
free((void *)list->requests[i].path);
}
free(list->requests);
initPermissionRequestList(list);
}
}
/*
* Global permission table
*/
static struct {
Permission *permissions;
int numPermissionEntries;
int allocatedPermissionEntries;
bool permissionStateInitialized;
} gPermissionState = {
#if 1
NULL, 0, 0, false
#else
.permissions = NULL,
.numPermissionEntries = 0,
.allocatedPermissionEntries = 0,
.permissionStateInitialized = false
#endif
};
int
permissionInit()
{
if (gPermissionState.permissionStateInitialized) {
return -1;
}
gPermissionState.permissions = NULL;
gPermissionState.numPermissionEntries = 0;
gPermissionState.allocatedPermissionEntries = 0;
gPermissionState.permissionStateInitialized = true;
//xxx maybe add an "namespace root gets no permissions" fallback by default
return 0;
}
void
permissionCleanup()
{
if (gPermissionState.permissionStateInitialized) {
gPermissionState.permissionStateInitialized = false;
if (gPermissionState.permissions != NULL) {
int i;
for (i = 0; i < gPermissionState.numPermissionEntries; i++) {
free((void *)gPermissionState.permissions[i].path);
}
free(gPermissionState.permissions);
}
}
}
int
getPermissionCount()
{
if (gPermissionState.permissionStateInitialized) {
return gPermissionState.numPermissionEntries;
}
return -1;
}
const Permission *
getPermissionAt(int index)
{
if (!gPermissionState.permissionStateInitialized) {
return NULL;
}
if (index < 0 || index >= gPermissionState.numPermissionEntries) {
return NULL;
}
return &gPermissionState.permissions[index];
}
int
getAllowedPermissions(const char *path, bool recursive,
unsigned int *outAllowed)
{
if (!gPermissionState.permissionStateInitialized) {
return -2;
}
if (outAllowed == NULL) {
return -1;
}
*outAllowed = 0;
if (path == NULL) {
return -1;
}
//TODO: implement this for real.
recursive = false;
*outAllowed = PERMSET_ALL;
return 0;
}
int
countPermissionConflicts(PermissionRequestList *requests, bool updateAllowed)
{
if (!gPermissionState.permissionStateInitialized) {
return -2;
}
if (requests == NULL || requests->requests == NULL ||
requests->numRequests < 0 ||
requests->requestsAllocated < requests->numRequests)
{
return -1;
}
int conflicts = 0;
int i;
for (i = 0; i < requests->numRequests; i++) {
PermissionRequest *req;
unsigned int allowed;
int ret;
req = &requests->requests[i];
ret = getAllowedPermissions(req->path, req->recursive, &allowed);
if (ret < 0) {
return ret;
}
if ((req->requested & ~allowed) != 0) {
conflicts++;
}
if (updateAllowed) {
req->allowed = allowed;
}
}
return conflicts;
}
int
registerPermissionSet(int count, Permission *set)
{
if (!gPermissionState.permissionStateInitialized) {
return -2;
}
if (count < 0 || (count > 0 && set == NULL)) {
return -1;
}
if (count == 0) {
return 0;
}
if (gPermissionState.numPermissionEntries + count >=
gPermissionState.allocatedPermissionEntries)
{
Permission *newList;
int newSize;
newSize = (gPermissionState.allocatedPermissionEntries + count) * 2;
if (newSize < 16) {
newSize = 16;
}
newList = (Permission *)realloc(gPermissionState.permissions,
newSize * sizeof(Permission));
if (newList == NULL) {
return -3;
}
gPermissionState.permissions = newList;
gPermissionState.allocatedPermissionEntries = newSize;
}
Permission *p = &gPermissionState.permissions[
gPermissionState.numPermissionEntries];
int i;
for (i = 0; i < count; i++) {
*p = set[i];
//TODO: cache the strlen of the path
//TODO: normalize; strip off trailing /
p->path = strdup(p->path);
if (p->path == NULL) {
/* If we can't add all of the entries, we don't
* add any of them.
*/
Permission *pp = &gPermissionState.permissions[
gPermissionState.numPermissionEntries];
while (pp != p) {
free((void *)pp->path);
pp++;
}
return -4;
}
p++;
}
gPermissionState.numPermissionEntries += count;
return 0;
}
| 2.484375 | 2 |
2024-11-18T21:05:51.306868+00:00 | 2018-06-01T13:17:56 | 8608250ac0da6edcb638e9ac7b4755e883e2f282 | {
"blob_id": "8608250ac0da6edcb638e9ac7b4755e883e2f282",
"branch_name": "refs/heads/master",
"committer_date": "2018-06-01T13:17:56",
"content_id": "082db9456aba486aa832241f9780dcae859d0f74",
"detected_licenses": [
"MIT"
],
"directory_id": "1c8b11974f9c2b9bedc33485cb8d40b92c3f4cc0",
"extension": "c",
"filename": "bai4.c",
"fork_events_count": 2,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 127435679,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 401,
"license": "MIT",
"license_type": "permissive",
"path": "/Bai tap cuoi ki/Cau truc lap/bai4.c",
"provenance": "stackv2-0083.json.gz:1203",
"repo_name": "lamhoangtung/Bai-tap-Lap-trinh-can-ban",
"revision_date": "2018-06-01T13:17:56",
"revision_id": "27edc95a08981351449bc308706c9d7c804a18b7",
"snapshot_id": "071af6d49b20414d3bea7e62e628428aa9f7cbcf",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/lamhoangtung/Bai-tap-Lap-trinh-can-ban/27edc95a08981351449bc308706c9d7c804a18b7/Bai tap cuoi ki/Cau truc lap/bai4.c",
"visit_date": "2020-03-07T10:36:05.481050"
} | stackv2 | //Tim uoc chung lon nhat cua hai so
#include <stdio.h>
int main(){
int a,b;
printf("Moi ban nhap vao so nguyen dau tien: ");
scanf("%i",&a);
printf("Moi ban nhap vao so nguyen thu hai: ");
scanf("%i",&b);
int aa=a,bb=b;
while(a!=b){
if (a>b){
a-=b;
}
else{
b-=a;
}
}
printf("Uoc so chung lon nhat cua hai so %i va %i la %i\n",aa,bb,a);
return 0;
}
| 3.171875 | 3 |
2024-11-18T21:05:51.449885+00:00 | 2012-01-04T10:36:57 | 35ec78da658849c4571951922eb3c99e311b6bbe | {
"blob_id": "35ec78da658849c4571951922eb3c99e311b6bbe",
"branch_name": "refs/heads/master",
"committer_date": "2012-01-04T10:36:57",
"content_id": "ffd1277ba40c7f15263fe6d526ac09fd08764411",
"detected_licenses": [
"MIT"
],
"directory_id": "b451de712a41a00983fc9e253a0a5b57211c4e53",
"extension": "h",
"filename": "list.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 2275079,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1305,
"license": "MIT",
"license_type": "permissive",
"path": "/list.h",
"provenance": "stackv2-0083.json.gz:1331",
"repo_name": "ozkriff/fantasy-wargame",
"revision_date": "2012-01-04T10:36:57",
"revision_id": "9672c14478a19fd2c2fbc142dd63fe8508e356bc",
"snapshot_id": "5b89af55afc443955a61c81599791588da7b482b",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ozkriff/fantasy-wargame/9672c14478a19fd2c2fbc142dd63fe8508e356bc/list.h",
"visit_date": "2016-09-09T23:46:51.678676"
} | stackv2 | /* See LICENSE file for copyright and license details. */
/* Double-linked list, stack, queue. */
typedef struct Node Node;
struct Node {
Node *n; /* pointer to [n]ext node or NULL */
Node *p; /* pointer to [p]revious node or NULL */
void *d; /* pointer to [d]ata */
};
typedef struct List List;
struct List {
Node *h; /* pointer to first ([h]ead) node */
Node *t; /* pointer to last ([t]ail) node */
int count; /* number of nodes in list */
};
void insert_node (List *list_p, void *data, Node *after);
Node *extruct_node(List *list_p, Node *old);
void delete_node (List *list_p, Node *old);
void *extruct_data(List *list_p, Node *old);
Node *data2node (List l, void *d);
#define add_node_to_head(list_p, node_p) \
insert_node(list_p, node_p, NULL)
#define add_node_after(list_p, node_p, after_p) \
insert_node(list_p, node_p, after_p)
#define add_node_to_tail(list_p, node_p) \
insert_node(list_p, node_p, (list_p)->t)
#define Stack List
#define push_node add_node_to_head
#define pop_node(list_p) extruct_data(list_p, (list_p)->t)
#define Queue List
#define enq_node add_node_to_tail
#define deq_node(list_p) extruct_data(list_p, (list_p)->h)
#define FOR_EACH_NODE(list, node_p) \
for(node_p=(list).h; node_p; node_p=node_p->n)
| 3.046875 | 3 |
2024-11-18T21:05:52.642373+00:00 | 2018-07-28T13:09:19 | d879c31add454c67e6c3d245410c4af5bc00aef0 | {
"blob_id": "d879c31add454c67e6c3d245410c4af5bc00aef0",
"branch_name": "refs/heads/master",
"committer_date": "2018-07-28T13:09:19",
"content_id": "8ad1e81b746886d4b9616a61063078e45dfd5ed3",
"detected_licenses": [
"Apache-2.0",
"BSL-1.0"
],
"directory_id": "7b8a8081df5b11fa7f04a3b94b925a69c531777f",
"extension": "h",
"filename": "mulshift128.h",
"fork_events_count": 0,
"gha_created_at": "2018-07-28T15:31:37",
"gha_event_created_at": "2018-07-28T15:31:37",
"gha_language": null,
"gha_license_id": null,
"github_id": 142688517,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2716,
"license": "Apache-2.0,BSL-1.0",
"license_type": "permissive",
"path": "/ryu/mulshift128.h",
"provenance": "stackv2-0083.json.gz:2360",
"repo_name": "watmough/ryu",
"revision_date": "2018-07-28T13:09:19",
"revision_id": "1162decc5dcc1582ce359cfd1392612198c605fa",
"snapshot_id": "d3dbc46d5fc5f80433e4086c430cc60d6915bb5d",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/watmough/ryu/1162decc5dcc1582ce359cfd1392612198c605fa/ryu/mulshift128.h",
"visit_date": "2020-03-24T11:32:57.155131"
} | stackv2 | // Copyright 2018 Ulf Adams
//
// The contents of this file may be used under the terms of the Apache License,
// Version 2.0.
//
// (See accompanying file LICENSE-Apache or copy at
// http://www.apache.org/licenses/LICENSE-2.0)
//
// Alternatively, the contents of this file may be used under the terms of
// the Boost Software License, Version 1.0.
// (See accompanying file LICENSE-Boost or copy at
// https://www.boost.org/LICENSE_1_0.txt)
//
// Unless required by applicable law or agreed to in writing, this software
// is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.
#ifndef RYU_MULSHIFT128_H
#define RYU_MULSHIFT128_H
#include <assert.h>
#include <stdint.h>
#if defined(HAS_64_BIT_INTRINSICS)
#include <intrin.h>
static inline uint64_t umul128(const uint64_t a, const uint64_t b, uint64_t* const productHi) {
return _umul128(a, b, productHi);
}
static inline uint64_t shiftright128(const uint64_t lo, const uint64_t hi, const uint32_t dist) {
// For the __shiftright128 intrinsic, the shift value is always
// modulo 64.
// In the current implementation of the double-precision version
// of Ryu, the shift value is always < 64. (In the case
// RYU_OPTIMIZE_SIZE == 0, the shift value is in the range [50,58].
// Otherwise in the range [2,59].)
// Check this here in case a future change requires larger shift
// values. In this case this function needs to be adjusted.
assert(dist < 64);
return __shiftright128(lo, hi, (unsigned char) dist);
}
#else // defined(HAS_64_BIT_INTRINSICS)
static inline uint64_t umul128(const uint64_t a, const uint64_t b, uint64_t* const productHi) {
// The casts here help MSVC to avoid calls to the __allmul library function.
const uint32_t aLo = (uint32_t)a;
const uint32_t aHi = (uint32_t)(a >> 32);
const uint32_t bLo = (uint32_t)b;
const uint32_t bHi = (uint32_t)(b >> 32);
const uint64_t b00 = (uint64_t)aLo * bLo;
const uint64_t b01 = (uint64_t)aLo * bHi;
const uint64_t b10 = (uint64_t)aHi * bLo;
const uint64_t b11 = (uint64_t)aHi * bHi;
const uint64_t midSum = b01 + b10;
const uint64_t midCarry = midSum < b01;
const uint64_t productLo = b00 + (midSum << 32);
const uint64_t productLoCarry = productLo < b00;
*productHi = b11 + (midSum >> 32) + (midCarry << 32) + productLoCarry;
return productLo;
}
static inline uint64_t shiftright128(const uint64_t lo, const uint64_t hi, const uint32_t dist) {
// We don't need to handle the case dist >= 64 here (see above).
assert(dist > 0);
assert(dist < 64);
return (hi << (64 - dist)) | (lo >> dist);
}
#endif // defined(HAS_64_BIT_INTRINSICS)
#endif // RYU_MULSHIFT128_H
| 2.34375 | 2 |
2024-11-18T21:05:52.720148+00:00 | 2022-11-14T13:13:45 | 42b5645ba29e168121b82cf2dd6f2672b08a98cc | {
"blob_id": "42b5645ba29e168121b82cf2dd6f2672b08a98cc",
"branch_name": "refs/heads/master",
"committer_date": "2022-11-14T13:13:45",
"content_id": "3d66d81140c277594f2d8a824c579d1810a0fc9d",
"detected_licenses": [
"MIT"
],
"directory_id": "2cfe9b278948a29c58a153dc8446405bfdd37419",
"extension": "h",
"filename": "StrParser_private.h",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 49395648,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 552,
"license": "MIT",
"license_type": "permissive",
"path": "/includes/StrParser_private.h",
"provenance": "stackv2-0083.json.gz:2489",
"repo_name": "acs9307/alib-c",
"revision_date": "2022-11-14T13:13:45",
"revision_id": "4c689756fa1a760127d710ee64cac204ed9304f1",
"snapshot_id": "17ce6e0d80ab0a60d87b30617bca6dfbf802442b",
"src_encoding": "UTF-8",
"star_events_count": 4,
"url": "https://raw.githubusercontent.com/acs9307/alib-c/4c689756fa1a760127d710ee64cac204ed9304f1/includes/StrParser_private.h",
"visit_date": "2022-11-21T21:11:08.808725"
} | stackv2 | #ifndef ALIB_C_STR_PARSER_PRIVATE_IS_DEFINED
#define ALIB_C_STR_PARSER_PRIVATE_IS_DEFINED
#include "StrParser.h"
#include "StrRef_private.h"
/* Structs */
/* String parser is designed to be a base interface for parsers each string may need to be
* parsed differently. */
struct StrParser
{
/* Pointer to the entire string being parsed. */
StrRef str;
/* Pointer to the beginning of an iterator segment of the string being parsed.
* If 'it.begin' is NULL, then the iterator has not been initialized yet. */
StrRef it;
};
/***********/
#endif
| 2.15625 | 2 |
2024-11-18T21:05:52.815611+00:00 | 2020-08-12T08:03:00 | 520b7e25b8dc337b33c214ef0794650674fe27e4 | {
"blob_id": "520b7e25b8dc337b33c214ef0794650674fe27e4",
"branch_name": "refs/heads/master",
"committer_date": "2020-08-12T08:03:00",
"content_id": "23e1aa329543c8fd98c978a53c3dace2f840952c",
"detected_licenses": [
"MIT"
],
"directory_id": "f08c6e2a4bae01c10cb9ac4b882a6807d5ec3c51",
"extension": "c",
"filename": "DS18B20.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 286526488,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5485,
"license": "MIT",
"license_type": "permissive",
"path": "/User/Main/DS18B20.c",
"provenance": "stackv2-0083.json.gz:2618",
"repo_name": "NUAA-WatchDog/CARe-stm32-embedded-system",
"revision_date": "2020-08-12T08:03:00",
"revision_id": "ed47f997ba570323d27b076e6e773433fec35154",
"snapshot_id": "799689ff429cb5f2901316fc58932cf365e1ec5f",
"src_encoding": "GB18030",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/NUAA-WatchDog/CARe-stm32-embedded-system/ed47f997ba570323d27b076e6e773433fec35154/User/Main/DS18B20.c",
"visit_date": "2022-11-28T10:00:32.789476"
} | stackv2 | /******************************************************************
** NUAA_CM3_107实验开发板(V2.0)
** 读取18b20温度值,并在3.2吋屏上显示
** 作 者:NUAA
** 完成日期: 2016.8.25
********************************************************************/
#include "DS18B20.h"
#include "delay.h"
/**************************************************
*函数名称:void DS18B20_Rst(void)
*
*入口参数:无
*
*出口参数:无
*
*功能说明:复位DS18B20 (每次读写均要先复位)
***************************************************/
void DS18B20_Rst(void)
{
DS18B20_DQ_OUT_LOW(); // 拉低DQ
Delay_us(750); // 延时750us
DS18B20_DQ_OUT_HIGH(); // 拉高DQ
Delay_us(15); // 延时15US
}
/**************************************************
*函数名称:uint8_t DS18B20_Init(void)
*
*入口参数:无
*
*出口参数:1,未检到DS18B20的存在 0,存在
*
*功能说明:等待DS18B20的回应
***************************************************/
u8 DS18B20_Check(void)
{
u8 retry=0;
while (DS18B20_DQ_IN()&&retry<200)
{
retry++;
Delay_us(1);
};
if(retry>=200)return 1;
else retry=0;
while (!DS18B20_DQ_IN()&&retry<240)
{
retry++;
Delay_us(1);
};
if(retry>=240)return 1;
return 0;
}
/**************************************************
*函数名称:uint8_t DS18B20_Init(void)
*
*入口参数:无
*
*出口参数:1,未检到DS18B20的存在 0,存在
*
*功能说明:初始化18b20
***************************************************/
uint8_t DS18B20_Init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB | RCC_APB2Periph_AFIO, ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; //管脚频率50MHz
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_OD; //开漏输出
GPIO_Init(GPIOB, &GPIO_InitStructure);
DS18B20_Rst(); //复位
return DS18B20_Check(); //0 存在; 1 未检测到DS18B20的存在
}
/**************************************************
*函数名称:void DS18B20_Write_Byte(u8 dat)
*
*入口参数:无
*
*出口参数:无
*
*功能说明:写一个字节
***************************************************/
void DS18B20_Write_Byte(u8 dat)
{
u8 j;
u8 testb;
for (j=1;j<=8;j++)
{
testb=dat&0x01;
dat=dat>>1;
if (testb)
{
DS18B20_DQ_OUT_LOW();
Delay_us(2);
DS18B20_DQ_OUT_HIGH();
Delay_us(60);
}
else
{
DS18B20_DQ_OUT_LOW();
Delay_us(60);
DS18B20_DQ_OUT_HIGH();
Delay_us(2);
}
}
}
/**************************************************
*函数名称:void DS18B20_Start(void)
*
*入口参数:无
*
*出口参数:无
*
*功能说明:开始温度转换
***************************************************/
void DS18B20_Start(void)
{
DS18B20_Rst(); //复位DS18B20
DS18B20_Check(); //等待DS18B20的回应
//Delay_ms(500);
DS18B20_Write_Byte(0xcc); //跳过ROM
DS18B20_Write_Byte(0x44); //发送开始转换命令
}
/**************************************************
*函数名称:u8 DS18B20_Read_Bit(void)
*
*入口参数:无
*
*出口参数:1/0
*
*功能说明:从DS18B20读取一个位
***************************************************/
u8 DS18B20_Read_Bit(void)
{
u8 data;
DS18B20_DQ_OUT_LOW();
Delay_us(2);
DS18B20_DQ_OUT_HIGH();
Delay_us(12);
if(DS18B20_DQ_IN())data=1;
else data=0;
Delay_us(50);
return data;
}
/**************************************************
*函数名称:u8 DS18B20_Read_Bit(void)
*
*入口参数:无
*
*出口参数:读取的数据dat
*
*功能说明:从DS18B20读取一个字节
***************************************************/
u8 DS18B20_Read_Byte(void)
{
u8 i,j,dat;
dat=0;
for (i=1;i<=8;i++)
{
j=DS18B20_Read_Bit();
dat=(j<<7)|(dat>>1);
}
return dat;
}
/**************************************************
*函数名称:short DS18B20_Get_Temp(void)
*
*入口参数:无
*
*出口参数:温度值(-550~1250)
*
*功能说明:从ds18b20获取温度值 精度0.1C
***************************************************/
short DS18B20_Get_Temp(void)
{
u8 temp;
u8 TL,TH;
short tem;
DS18B20_Start (); // 开始转换
DS18B20_Rst(); //复位18b20
DS18B20_Check(); //检测18b20是否存在
DS18B20_Write_Byte(0xcc); //跳过ROM
DS18B20_Write_Byte(0xbe); //读寄存器,共九字节,前两字节为转换值
TL=DS18B20_Read_Byte(); // LSB
TH=DS18B20_Read_Byte(); // MSB
if(TH>7)
{
TH=~TH;
TL=~TL;
temp=0; //温度为负
}else temp=1; //温度为正
tem=TH; //获得高八位
tem<<=8;
tem+=TL; //获得低八位
tem=(float)tem*0.625; //转换
if(temp)return tem; //返回温度值
else return -tem;
}
| 2.90625 | 3 |
2024-11-18T21:05:53.033018+00:00 | 2021-05-25T08:29:01 | af49f993e4aea3d10ef4f271ffcc56de05850029 | {
"blob_id": "af49f993e4aea3d10ef4f271ffcc56de05850029",
"branch_name": "refs/heads/master",
"committer_date": "2021-05-25T08:29:01",
"content_id": "b736a8f4ca799e8b0d071ce31ef001beea6eb223",
"detected_licenses": [
"MIT"
],
"directory_id": "82873b85f33c88a9a717394296a4a658f6903493",
"extension": "c",
"filename": "utf8per.c",
"fork_events_count": 0,
"gha_created_at": "2020-09-01T12:45:02",
"gha_event_created_at": "2020-09-01T12:45:03",
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 291995472,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1726,
"license": "MIT",
"license_type": "permissive",
"path": "/nlp/sources/ogm_uni/lib/utf8per.c",
"provenance": "stackv2-0083.json.gz:2875",
"repo_name": "odespesse/viky-ai",
"revision_date": "2021-05-25T08:29:01",
"revision_id": "de617b2798e49698e756eec0e0d6add89b57d0e0",
"snapshot_id": "c191a88cb44f2e99288c7472b23ffc5b609482f3",
"src_encoding": "WINDOWS-1250",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/odespesse/viky-ai/de617b2798e49698e756eec0e0d6add89b57d0e0/nlp/sources/ogm_uni/lib/utf8per.c",
"visit_date": "2023-08-17T23:09:42.982666"
} | stackv2 | /*
* Handling UTF8-Percent transformations.
* Copyright (c) 2005-2007 Pertimm by Patrick Constant
* Dev : September 2005, November 2007
* Version 1.1
*/
#include <loguni.h>
#include <loggen.h>
/*
* Encoding an UTF8 string into %xx string
* example: été -> %C3%A9t%C3%A9
* According to RFC 2279 rules are:
* UCS-4 range (hex.) UTF-8 octet sequence (binary)
* 0000 0000-0000 007F 0xxxxxxx
* 0000 0080-0000 07FF 110xxxxx 10xxxxxx
* 0000 0800-0000 FFFF 1110xxxx 10xxxxxx 10xxxxxx
*/
PUBLIC(int) OgCpToPercent(icode,code,spercent,ipercent,percent,truncated)
int icode; unsigned char *code;
int spercent,*ipercent; unsigned char *percent;
int *truncated;
{
int i,j,c;
if (truncated) *truncated=0;
for (i=j=0; i<icode; i++) {
c = code[i];
if (c <= 0x7f) {
percent[j++]=c;
}
else {
sprintf(percent+j,"%%%2X",c); j += strlen(percent+j);
}
if (j+3>=spercent) {
if (i+1<icode) { if (truncated) *truncated=1; }
break;
}
}
percent[j]=0;
*ipercent=j;
DONE;
}
PUBLIC(int) OgPercentToCp(ipercent,percent,scode,icode,code,truncated)
int ipercent; unsigned char *percent;
int scode,*icode; unsigned char *code;
int *truncated;
{
unsigned char *nil,sx[3];
int i,j,c,x;
if (truncated) *truncated=0;
for (i=j=0; i<ipercent; i++) {
c = percent[i];
if (i+2<ipercent && c=='%' && isxdigit(percent[i+1]) && isxdigit(percent[i+2])) {
memcpy(sx,percent+i+1,2); sx[2]=0;
x=strtol(sx,&nil,16);
code[j++]=x;
i+=2;
}
else {
code[j++]=c;
}
if (j+1>=scode) {
if (truncated) *truncated=1;
break;
}
}
code[j]=0;
*icode=j;
DONE;
}
| 2.359375 | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.