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-18T20:55:54.500520+00:00 | 2018-05-23T22:16:54 | b1764122e75594216770d40b3dbc3cc1786d7ad5 | {
"blob_id": "b1764122e75594216770d40b3dbc3cc1786d7ad5",
"branch_name": "refs/heads/master",
"committer_date": "2018-05-23T22:16:54",
"content_id": "6d086795499eb09da226eafb75829e8b534132ad",
"detected_licenses": [
"MIT"
],
"directory_id": "551d26d520f3d4ddfc852add32eb647f3b02ebcf",
"extension": "h",
"filename": "minPQ.h",
"fork_events_count": 3,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 56641103,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1090,
"license": "MIT",
"license_type": "permissive",
"path": "/cmps101/asg3/minPQ.h",
"provenance": "stackv2-0092.json.gz:54047",
"repo_name": "isaiah-solo/classwork",
"revision_date": "2018-05-23T22:16:54",
"revision_id": "a3e834ee26822827f7ea4977707ecf7e42e1b0c9",
"snapshot_id": "99d116fd67e935bf7593cff1bf1dbd8fcab40259",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/isaiah-solo/classwork/a3e834ee26822827f7ea4977707ecf7e42e1b0c9/cmps101/asg3/minPQ.h",
"visit_date": "2021-09-15T01:57:26.061628"
} | stackv2 | /* minPQ.h (what is the purpose of this file?)
*/
#ifndef C101MinPQ
#define C101MinPQ
/* Multiple typedefs for the same type are an error in C. */
typedef struct MinPQNode * MinPQ;
struct MinPQNode
{
int n, numPQ, minVertex;
double oo;
int* status;
double* priority;
int* parent;
};
#define UNSEEN ('u')
#define FRINGE ('f')
#define INTREE ('t')
/* Access functions (what are the preconditions?)
*/
/** isEmpty
*/
int isEmptyPQ(MinPQ pq);
/** getMin
*/
int getMin(MinPQ pq);
/** getStatus
*/
int getStatus(MinPQ pq, int id);
/** getParent
*/
int getParent(MinPQ pq, int id);
/** getPriority
*/
double getPriority(MinPQ pq, int id);
/* Manipulation procedures (what are the preconditions and postconditions?)
*/
/** delMin
*/
void delMin(MinPQ pq);
/** insertPQ
*/
void insertPQ(MinPQ pq, int id, double priority, int par);
/** decreaseKey
*/
void decreaseKey(MinPQ pq, int id, double priority, int par);
/* Constructors (what are the preconditions and postconditions?)
*/
/**
*/
MinPQ createPQ(int n, int status[], double priority[], int parent[]);
#endif
| 2.59375 | 3 |
2024-11-18T20:55:55.061738+00:00 | 2021-09-04T12:05:43 | 8621a467550529ec86781ea3576311d75054feeb | {
"blob_id": "8621a467550529ec86781ea3576311d75054feeb",
"branch_name": "refs/heads/main",
"committer_date": "2021-09-04T12:05:43",
"content_id": "1b27aa7e838d99dd5240e96538514401808b0b86",
"detected_licenses": [
"MIT"
],
"directory_id": "e675df4b539ad6206e1b426d22ba0b20e5aa8ced",
"extension": "c",
"filename": "apl_key_menu.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": 14596,
"license": "MIT",
"license_type": "permissive",
"path": "/firmware/Project/APL/apl_key_menu.c",
"provenance": "stackv2-0092.json.gz:54824",
"repo_name": "pjdu/TinyMatrix",
"revision_date": "2021-09-04T12:05:43",
"revision_id": "216e57a7efb27216a9e687393441683a5ae886cb",
"snapshot_id": "8098e66a1721e44f021024af3cee26f36db63b86",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/pjdu/TinyMatrix/216e57a7efb27216a9e687393441683a5ae886cb/firmware/Project/APL/apl_key_menu.c",
"visit_date": "2023-08-15T14:31:37.350815"
} | stackv2 | #include "includes.h"
Menu_StateTypeDef menu_state = Menu_R;
uint8_t menu_item = 1;
uint8_t key_value = 0;
void apl_menu_init(void)
{
apl_menu_r_display((menu_item-1)/3);
}
void apl_menu_handle(void)
{
key_value = bsp_key_read();
if(key_value)
{
switch(menu_state)
{
case Menu_R:
apl_menu_r_callback();
break;
case Menu_M:
apl_menu_m_callback();
break;
case Menu_1:
apl_menu_1_callback();
break;
case Menu_2:
apl_menu_2_callback();
break;
case Menu_3:
break;
case Menu_4:
apl_menu_4_callback();
break;
case Menu_1_1:
apl_menu_1_1_callback();
break;
case Menu_4_1:
apl_menu_4_1_callback();
break;
case Menu_4_2:
apl_menu_4_2_callback();
break;
default:
break;
}
}
}
void apl_menu_r_callback(void)
{
switch(key_value)
{
case KEY1_SHORT:
break;
case KEY1_LONG:
break;
case KEY2_SHORT:
break;
case KEY2_LONG:
break;
case KEY3_SHORT:
break;
case KEY3_LONG:
menu_state = Menu_M;
menu_item = 1;
apl_menu_m_display((menu_item-1)/3);
api_task_delete(Task_MatrixShift);
break;
case KEY4_SHORT:
break;
case KEY4_LONG:
break;
default:
break;
}
}
void apl_menu_r_display(uint8_t page)
{
apl_font_init();
apl_font_display(0, 0, HUB75_PANEL_WIDTH, 16, " ", 16, 0);
apl_font_display(0, 16, HUB75_PANEL_WIDTH, 16, " ", 16, 0);
apl_font_display(0, 32, HUB75_PANEL_WIDTH, 16, " ", 16, 0);
apl_font_display(0, 48, HUB75_PANEL_WIDTH, 16, " ", 16, 0);
}
void apl_menu_m_callback(void)
{
switch(key_value)
{
case KEY1_SHORT:
if(menu_item-- == 1)
menu_item = 4;
apl_menu_m_display((menu_item-1)/3);
break;
case KEY1_LONG:
break;
case KEY2_SHORT:
if(menu_item++ == 4)
menu_item = 1;
apl_menu_m_display((menu_item-1)/3);
break;
case KEY2_LONG:
break;
case KEY3_SHORT:
if(menu_item == 1)
{
menu_state = Menu_1;
menu_item = 1;
apl_menu_1_display((menu_item-1)/3);
}
else if(menu_item == 2)
{
menu_state = Menu_2;
menu_item = 1;
apl_menu_2_display((menu_item-1)/3);
}
else if(menu_item == 3)
{
}
else if(menu_item == 4)
{
menu_state = Menu_4;
menu_item = 1;
apl_menu_4_display((menu_item-1)/3);
}
break;
case KEY3_LONG:
break;
case KEY4_SHORT:
break;
case KEY4_LONG:
menu_state = Menu_R;
menu_item = 1;
apl_menu_r_display((menu_item-1)/3);
api_task_create(Task_MatrixShift, sys_data.shift_period);
break;
default:
break;
}
}
void apl_menu_m_display(uint8_t page)
{
apl_font_display(0, 0, HUB75_PANEL_WIDTH, 16, " SET UP ", 16, 0);
if(page == 0)
{
apl_font_display(0, 16, HUB75_PANEL_WIDTH, 16, "1.Font ", 16, 0);
apl_font_display(0, 32, HUB75_PANEL_WIDTH, 16, "2.Color ", 16, 0);
apl_font_display(0, 48, HUB75_PANEL_WIDTH, 16, "3.Lang ", 16, 0);
apl_font_reverse(0, menu_item*16, HUB75_PANEL_WIDTH, 16);
}
else if(page == 1)
{
apl_font_display(0, 16, HUB75_PANEL_WIDTH, 16, "4.Freq ", 16, 0);
apl_font_display(0, 32, HUB75_PANEL_WIDTH, 16, " ", 16, 0);
apl_font_display(0, 48, HUB75_PANEL_WIDTH, 16, " ", 16, 0);
apl_font_reverse(0, (menu_item-3)*16, HUB75_PANEL_WIDTH, 16);
}
}
void apl_menu_1_callback(void)
{
switch(key_value)
{
case KEY1_SHORT:
if(menu_item-- == 1)
menu_item = 3;
apl_menu_1_display((menu_item-1)/3);
break;
case KEY1_LONG:
break;
case KEY2_SHORT:
if(menu_item++ == 3)
menu_item = 1;
apl_menu_1_display((menu_item-1)/3);
break;
case KEY2_LONG:
break;
case KEY3_SHORT:
if(menu_item == 1)
{
font_size = 12;
}
else if(menu_item == 2)
{
font_size = 16;
}
else if(menu_item == 3)
{
font_size = 24;
}
menu_state = Menu_1_1;
menu_item = 1;
apl_menu_1_1_display((menu_item-1)/3);
break;
case KEY3_LONG:
break;
case KEY4_SHORT:
menu_state = Menu_M;
menu_item = 1;
apl_menu_m_display((menu_item-1)/3);
font_mode = 0;
break;
case KEY4_LONG:
break;
default:
break;
}
}
void apl_menu_1_display(uint8_t page)
{
apl_font_display(0, 0, HUB75_PANEL_WIDTH, 16, " FONT ", 16, 0);
if(page == 0)
{
apl_font_display(0, 16, HUB75_PANEL_WIDTH, 16, "1.Font12", 16, 0);
apl_font_display(0, 32, HUB75_PANEL_WIDTH, 16, "2.Font16", 16, 0);
apl_font_display(0, 48, HUB75_PANEL_WIDTH, 16, "3.Font24", 16, 0);
apl_font_reverse(0, menu_item*16, HUB75_PANEL_WIDTH, 16);
}
}
void apl_menu_2_callback(void)
{
switch(key_value)
{
case KEY1_SHORT:
if(menu_item-- == 1)
menu_item = 9;
apl_menu_2_display((menu_item-1)/3);
break;
case KEY1_LONG:
break;
case KEY2_SHORT:
if(menu_item++ == 9)
menu_item = 1;
apl_menu_2_display((menu_item-1)/3);
break;
case KEY2_LONG:
break;
case KEY3_SHORT:
if(menu_item == 1)
{
hub75_color = HUB75_Color_Red;
hub75_blink = 0;
}
else if(menu_item == 2)
{
hub75_color = HUB75_Color_Green;
hub75_blink = 0;
}
else if(menu_item == 3)
{
hub75_color = HUB75_Color_Yellow;
hub75_blink = 0;
}
else if(menu_item == 4)
{
hub75_color = HUB75_Color_Blue;
hub75_blink = 0;
}
else if(menu_item == 5)
{
hub75_color = HUB75_Color_Pink;
hub75_blink = 0;
}
else if(menu_item == 6)
{
hub75_color = HUB75_Color_Cyan;
hub75_blink = 0;
}
else if(menu_item == 7)
{
hub75_color = HUB75_Color_White;
hub75_blink = 0;
}
else if(menu_item == 8)
{
hub75_color = HUB75_Color_Black;
hub75_blink = 1;
}
else if(menu_item == 9)
{
apl_font_display(0, 0, HUB75_PANEL_WIDTH, 12, "Spark Zheng", 12, 0);
apl_font_display(0, 12, HUB75_PANEL_WIDTH, 12, "Led Matrix", 12, 0);
apl_font_display(0, 24, HUB75_PANEL_WIDTH, 16, "WellDone", 16, 0);
apl_font_display(0, 40, HUB75_PANEL_WIDTH, 24, "Fight!", 24, 0);
}
sys_data.display_color = hub75_color;
break;
case KEY3_LONG:
break;
case KEY4_SHORT:
menu_state = Menu_M;
menu_item = 1;
apl_menu_m_display((menu_item-1)/3);
break;
case KEY4_LONG:
break;
default:
break;
}
}
void apl_menu_2_display(uint8_t page)
{
apl_font_display(0, 0, HUB75_PANEL_WIDTH, 16, " COLOR ", 16, 0);
if(page == 0)
{
apl_font_display(0, 16, HUB75_PANEL_WIDTH, 16, "1.Red ", 16, 0);
apl_font_display(0, 32, HUB75_PANEL_WIDTH, 16, "2.Green ", 16, 0);
apl_font_display(0, 48, HUB75_PANEL_WIDTH, 16, "3.Yellow", 16, 0);
apl_font_reverse(0, (menu_item)*16, HUB75_PANEL_WIDTH, 16);
}
else if(page == 1)
{
apl_font_display(0, 16, HUB75_PANEL_WIDTH, 16, "4.Blue ", 16, 0);
apl_font_display(0, 32, HUB75_PANEL_WIDTH, 16, "5.Pink ", 16, 0);
apl_font_display(0, 48, HUB75_PANEL_WIDTH, 16, "6.Cyan ", 16, 0);
apl_font_reverse(0, (menu_item-3)*16, HUB75_PANEL_WIDTH, 16);
}
else if(page == 2)
{
apl_font_display(0, 16, HUB75_PANEL_WIDTH, 16, "7.White ", 16, 0);
apl_font_display(0, 32, HUB75_PANEL_WIDTH, 16, "8.Auto ", 16, 0);
apl_font_display(0, 48, HUB75_PANEL_WIDTH, 16, " ", 16, 0);
apl_font_reverse(0, (menu_item-6)*16, HUB75_PANEL_WIDTH, 16);
}
}
void apl_menu_4_callback(void)
{
switch(key_value)
{
case KEY1_SHORT:
if(menu_item-- == 1)
menu_item = 2;
apl_menu_4_display((menu_item-1)/3);
break;
case KEY1_LONG:
break;
case KEY2_SHORT:
if(menu_item++ == 2)
menu_item = 1;
apl_menu_4_display((menu_item-1)/3);
break;
case KEY2_LONG:
break;
case KEY3_SHORT:
if(menu_item == 1)
{
menu_state = Menu_4_1;
menu_item = 1;
apl_menu_4_1_display((menu_item-1)/3);
}
else if(menu_item == 2)
{
menu_state = Menu_4_2;
menu_item = 1;
apl_menu_4_2_display((menu_item-1)/3);
}
break;
case KEY3_LONG:
break;
case KEY4_SHORT:
menu_state = Menu_M;
menu_item = 1;
apl_menu_m_display((menu_item-1)/3);
font_mode = 0;
break;
case KEY4_LONG:
break;
default:
break;
}
}
void apl_menu_4_display(uint8_t page)
{
apl_font_display(0, 0, HUB75_PANEL_WIDTH, 16, " FREQ ", 16, 0);
if(page == 0)
{
apl_font_display(0, 16, HUB75_PANEL_WIDTH, 16, "1.D_freq", 16, 0);
apl_font_display(0, 32, HUB75_PANEL_WIDTH, 16, "2.S_peri", 16, 0);
apl_font_display(0, 48, HUB75_PANEL_WIDTH, 16, " ", 16, 0);
apl_font_reverse(0, menu_item*16, HUB75_PANEL_WIDTH, 16);
}
}
void apl_menu_1_1_callback(void)
{
switch(key_value)
{
case KEY1_SHORT:
if(menu_item-- == 1)
menu_item = 3;
apl_menu_1_1_display((menu_item-1)/3);
break;
case KEY1_LONG:
break;
case KEY2_SHORT:
if(menu_item++ == 3)
menu_item = 1;
apl_menu_1_1_display((menu_item-1)/3);
break;
case KEY2_LONG:
break;
case KEY3_SHORT:
if(menu_item == 1)
{
font_mode = 0;
apl_font_display(0, 16, HUB75_PANEL_WIDTH, 16, "< < Dis ", 16, 0);
sys_data.font_size = font_size;
}
else if(menu_item == 2)
{
font_mode = 1;
apl_font_display(0, 32, HUB75_PANEL_WIDTH, 16, " Upg > >", 16, 0);
}
else if(menu_item == 3)
{
font_mode = 2;
apl_font_display(0, 48, HUB75_PANEL_WIDTH, 16, "Erasing.", 16, 0);
if(font_size == 12)
apl_font_erase(0);
else if(font_size == 16)
apl_font_erase(1);
else if(font_size == 24)
apl_font_erase(2);
apl_font_display(0, 48, HUB75_PANEL_WIDTH, 16, "Era Done", 16, 0);
}
break;
case KEY3_LONG:
break;
case KEY4_SHORT:
menu_state = Menu_1;
menu_item = 1;
apl_menu_1_display((menu_item-1)/3);
break;
case KEY4_LONG:
break;
default:
break;
}
}
void apl_menu_1_1_display(uint8_t page)
{
uint8_t dis_str[20];
sprintf((char*)dis_str, " FONT%2d ", font_size);
apl_font_display(0, 0, HUB75_PANEL_WIDTH, 16, dis_str, 16, 0);
if(page == 0)
{
apl_font_display(0, 16, HUB75_PANEL_WIDTH, 16, "1.SEL. *", 16, 0);
apl_font_display(0, 32, HUB75_PANEL_WIDTH, 16, "2.UPG. *", 16, 0);
apl_font_display(0, 48, HUB75_PANEL_WIDTH, 16, "3.EAU. !", 16, 0);
apl_font_reverse(0, menu_item*16, HUB75_PANEL_WIDTH, 16);
}
}
void apl_menu_4_1_callback(void)
{
if(sys_data.display_freq % 60)
sys_data.display_freq = 60;
switch(key_value)
{
case KEY1_SHORT:
if(sys_data.display_freq == 60)
sys_data.display_freq = 900;
else
sys_data.display_freq -= 60;
apl_menu_4_1_display((menu_item-1)/3);
break;
case KEY1_LONG:
break;
case KEY2_SHORT:
if(sys_data.display_freq == 900)
sys_data.display_freq = 60;
else
sys_data.display_freq += 60;
apl_menu_4_1_display((menu_item-1)/3);
break;
case KEY2_LONG:
break;
case KEY3_SHORT:
break;
case KEY3_LONG:
break;
case KEY4_SHORT:
menu_state = Menu_4;
menu_item = 1;
apl_menu_4_display((menu_item-1)/3);
break;
case KEY4_LONG:
break;
default:
break;
}
}
void apl_menu_4_1_display(uint8_t page)
{
uint8_t dis_str[20];
sprintf((char*)dis_str, " %3d Hz ", sys_data.display_freq);
apl_font_display(0, 0, HUB75_PANEL_WIDTH, 16, "Dis_Freq", 16, 0);
if(page == 0)
{
apl_font_display(0, 16, HUB75_PANEL_WIDTH, 16, dis_str, 16, 0);
apl_font_display(0, 32, HUB75_PANEL_WIDTH, 16, " ", 16, 0);
apl_font_display(0, 48, HUB75_PANEL_WIDTH, 16, " ", 16, 0);
apl_font_reverse(0, menu_item*16, HUB75_PANEL_WIDTH, 16);
}
}
void apl_menu_4_2_callback(void)
{
if(sys_data.shift_period % 10)
sys_data.shift_period = 10;
switch(key_value)
{
case KEY1_SHORT:
if(sys_data.shift_period == 10)
sys_data.shift_period = 900;
else
sys_data.shift_period -= 10;
apl_menu_4_2_display((menu_item-1)/3);
break;
case KEY1_LONG:
break;
case KEY2_SHORT:
if(sys_data.shift_period == 900)
sys_data.shift_period = 10;
else
sys_data.shift_period += 10;
apl_menu_4_2_display((menu_item-1)/3);
break;
case KEY2_LONG:
break;
case KEY3_SHORT:
break;
case KEY3_LONG:
break;
case KEY4_SHORT:
menu_state = Menu_4;
menu_item = 1;
apl_menu_4_display((menu_item-1)/3);
break;
case KEY4_LONG:
break;
default:
break;
}
}
void apl_menu_4_2_display(uint8_t page)
{
uint8_t dis_str[20];
sprintf((char*)dis_str, " %3d ms ", sys_data.shift_period);
apl_font_display(0, 0, HUB75_PANEL_WIDTH, 16, "Shi_Peri", 16, 0);
if(page == 0)
{
apl_font_display(0, 16, HUB75_PANEL_WIDTH, 16, dis_str, 16, 0);
apl_font_display(0, 32, HUB75_PANEL_WIDTH, 16, " ", 16, 0);
apl_font_display(0, 48, HUB75_PANEL_WIDTH, 16, " ", 16, 0);
apl_font_reverse(0, menu_item*16, HUB75_PANEL_WIDTH, 16);
}
}
| 2.40625 | 2 |
2024-11-18T20:55:55.701014+00:00 | 2021-10-03T11:56:22 | 1a870f2431c65e280d483659eeac09c88395dd56 | {
"blob_id": "1a870f2431c65e280d483659eeac09c88395dd56",
"branch_name": "refs/heads/main",
"committer_date": "2021-10-03T11:56:22",
"content_id": "6d6b8cc4ec754386486f3115e051649422cf4a9e",
"detected_licenses": [
"MIT"
],
"directory_id": "aca18d757735f0790a6e09e7edbfd168c61a8854",
"extension": "h",
"filename": "db-inline.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 412988821,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1961,
"license": "MIT",
"license_type": "permissive",
"path": "/db-inline.h",
"provenance": "stackv2-0092.json.gz:55084",
"repo_name": "codehz/koka-experiments",
"revision_date": "2021-10-03T11:56:22",
"revision_id": "5c9ca094a5d6519093edd75f273fd007aa31682d",
"snapshot_id": "99b525bf0fb9a7b81a2db0f5a3284f73477e3f60",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/codehz/koka-experiments/5c9ca094a5d6519093edd75f273fd007aa31682d/db-inline.h",
"visit_date": "2023-08-13T22:44:30.179336"
} | stackv2 | #pragma once
#include <sqlite3.h>
static int sqlite3_lasterrno;
static inline intptr_t kk_sqlite3_open(kk_string_t filename, kk_db__open_mode mode, kk_context_t *ctx) {
sqlite3 *ret;
sqlite3_lasterrno = sqlite3_open_v2(
kk_string_cbuf_borrow(filename, NULL),
&ret,
(mode.write ? SQLITE_OPEN_READWRITE : SQLITE_OPEN_READONLY) |
(mode.create ? SQLITE_OPEN_CREATE : 0) |
(mode.uri ? SQLITE_OPEN_URI : 0) |
(mode.memory ? SQLITE_OPEN_MEMORY : 0),
NULL
);
return (intptr_t)ret;
}
static inline intptr_t kk_sqlite3_prepare(intptr_t raw, kk_string_t sql, kk_context_t *ctx) {
sqlite3 *db = (sqlite3*) raw;
sqlite3_stmt *ret;
kk_ssize_t len;
char const *sqlstr = kk_string_cbuf_borrow(sql, &len);
sqlite3_lasterrno = sqlite3_prepare_v2(db, sqlstr, len, &ret, NULL);
return (intptr_t) ret;
}
static inline kk_string_t kk_sqlite3_column_text(intptr_t raw, int32_t idx, kk_context_t *ctx) {
sqlite3_stmt *stmt = (sqlite3_stmt *) raw;
char const *ret = (char const *) sqlite3_column_text(stmt, idx);
kk_ssize_t len = (kk_ssize_t) sqlite3_column_bytes(stmt, idx);
return kk_string_alloc_from_qutf8n(len, ret, ctx);
}
static inline kk_string_t kk_sqlite3_exec(intptr_t raw, kk_string_t sql, kk_context_t *ctx) {
sqlite3 *db = (sqlite3*) raw;
char *errmsg = NULL;
sqlite3_lasterrno = sqlite3_exec(db, kk_string_cbuf_borrow(sql, NULL), NULL, NULL, &errmsg);
if (errmsg != NULL) {
kk_string_t ret = kk_string_alloc_from_qutf8(errmsg, ctx);
sqlite3_free(errmsg);
return ret;
} else {
return kk_string_empty();
}
}
static inline int kk_sqlite3_bind_string(intptr_t raw, int32_t idx, kk_string_t value, kk_context_t *ctx) {
sqlite3_stmt *stmt = (sqlite3_stmt *) raw;
kk_ssize_t len;
char const *str = kk_string_cbuf_borrow(value, &len);
return sqlite3_bind_text64(stmt, idx, str, len, SQLITE_TRANSIENT, SQLITE_UTF8);
}
| 2.265625 | 2 |
2024-11-18T20:55:55.759292+00:00 | 2017-02-06T19:23:44 | c1a451841f27f2dfc7c750fc6bb7dbea184aa6a2 | {
"blob_id": "c1a451841f27f2dfc7c750fc6bb7dbea184aa6a2",
"branch_name": "refs/heads/master",
"committer_date": "2017-02-06T19:23:44",
"content_id": "477987d0082a7e8045276a45e97bc8ec823dd1f2",
"detected_licenses": [
"MIT"
],
"directory_id": "197542e201d267c4ac5b7b3faa89bc475dd65a31",
"extension": "c",
"filename": "handler.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 80952595,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1758,
"license": "MIT",
"license_type": "permissive",
"path": "/Hotkeys/handler.c",
"provenance": "stackv2-0092.json.gz:55215",
"repo_name": "jonayerdi/hotkeys",
"revision_date": "2017-02-06T19:23:44",
"revision_id": "b68fe627c2a981c6786df1263252134916aa9489",
"snapshot_id": "030f1cb2ab6fb620386c5cf030ce8f050a21c535",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/jonayerdi/hotkeys/b68fe627c2a981c6786df1263252134916aa9489/Hotkeys/handler.c",
"visit_date": "2021-01-09T06:17:26.422271"
} | stackv2 | #include "handler.h"
void logString(char * data)
{
FILE * file;
time_t rawtime;
struct tm timeinfo;
char timeString[26];
time(&rawtime);
localtime_s(&timeinfo, &rawtime);
fopen_s(&file, "hotkeys.log", "a");
fputc('[', file);
asctime_s(timeString, 26, &timeinfo);
timeString[strlen(timeString) - 1] = ']';
fputs(timeString, file);
fputc(' ', file);
fputs(data, file);
fputc('\n', file);
fclose(file);
}
int action(char* command)
{
STARTUPINFOA si;
PROCESS_INFORMATION pi;
ZeroMemory(&si, sizeof(si));
si.cb = sizeof(si);
ZeroMemory(&pi, sizeof(pi));
if (CreateProcessA(NULL, command, NULL, NULL, TRUE, CREATE_NO_WINDOW, NULL, NULL, &si, &pi))
{
WaitForSingleObject(pi.hProcess, INFINITE);
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
}
ExitThread(0);
}
void handleKeyboardEvent(unsigned __int64 type, KBDLLHOOKSTRUCT * eventData)
{
switch (type)
{
case WM_KEYDOWN:
for (DWORD i = 0 ; i < hotkeys_config.count ; i++)
if (hotkeys_config.evt[i].code == eventData->vkCode)
{
CreateThread(
NULL, // default security attributes
0, // use default stack size
action, // thread function name
hotkeys_config.evt[i].action, // argument to thread function
0, // use default creation flags
NULL); // return
#ifdef HOTKEYS_LOGGING
int action_len = strlen(hotkeys_config.evt[i].action);
char * message = malloc(sizeof(char)*(action_len + 80));
sprintf_s(message, action_len + 80, "KEYDOWN=%d\tACTION=%s", eventData->vkCode, hotkeys_config.evt[i].action);
logString(message);
free(message);
#endif
}
break;
case WM_KEYUP:
break;
case WM_SYSKEYDOWN:
break;
case WM_SYSKEYUP:
break;
default:
break;
}
}
| 2.453125 | 2 |
2024-11-18T20:55:55.856102+00:00 | 2019-12-01T10:48:39 | ce22eeed44f9ac01a2d1fd7dcc6e4dacdf7548c8 | {
"blob_id": "ce22eeed44f9ac01a2d1fd7dcc6e4dacdf7548c8",
"branch_name": "refs/heads/master",
"committer_date": "2019-12-01T10:48:39",
"content_id": "001e4cd3c42b9a59f09408c4f2ca19b245fe3b73",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "f4de39842f2b9890ff5e90e3989367ae4693f2dc",
"extension": "c",
"filename": "ct_root.c",
"fork_events_count": 0,
"gha_created_at": "2019-12-01T10:02:23",
"gha_event_created_at": "2019-12-01T10:02:24",
"gha_language": null,
"gha_license_id": "Apache-2.0",
"github_id": 225140045,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1514,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/test/ct_root.c",
"provenance": "stackv2-0092.json.gz:55344",
"repo_name": "giobim/libct",
"revision_date": "2019-12-01T10:48:39",
"revision_id": "999a6398cc4fcc9f202f5a9762c9675ad1f7674f",
"snapshot_id": "ab07fc43f2ed8ecf0aa9b7d7f9a4ef9c94fa0938",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/giobim/libct/999a6398cc4fcc9f202f5a9762c9675ad1f7674f/test/ct_root.c",
"visit_date": "2020-09-22T09:34:48.569104"
} | stackv2 | /*
* Test simple chroot()-ed CT
*/
#include <unistd.h>
#include <libct.h>
#include <stdio.h>
#include <sys/mman.h>
#include <string.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include "test.h"
#define FS_ROOT "libct_test_root"
#define FS_DATA "libct_test_string"
#define FS_FILE "file"
static int check_fs_data(void *a)
{
int fd;
fd = open("/" FS_FILE, O_RDONLY);
if (fd < 0)
return 1;
read(fd, a, sizeof(FS_DATA));
close(fd);
return 0;
}
int main(int argc, char **argv)
{
int fd;
char *fs_data;
libct_session_t s;
ct_handler_t ct;
ct_process_desc_t p;
ct_process_t pr;
mkdir(FS_ROOT, 0600);
fd = open(FS_ROOT "/" FS_FILE, O_WRONLY | O_CREAT | O_TRUNC, 0600);
if (fd < 0) {
tst_perr("Can't create file");
return 2;
}
write(fd, FS_DATA, sizeof(FS_DATA));
close(fd);
fs_data = mmap(NULL, 4096, PROT_READ | PROT_WRITE,
MAP_SHARED | MAP_ANON, 0, 0);
fs_data[0] = '\0';
s = libct_session_open_local();
ct = libct_container_create(s, "test");
p = libct_process_desc_create(s);
if (libct_fs_set_root(ct, FS_ROOT))
return fail("Unable to set root");
pr = libct_container_spawn_cb(ct, p, check_fs_data, fs_data);
if (libct_handle_is_err(pr))
return fail("Unable to start CT");
if (libct_container_wait(ct))
return fail("Unable to wait CT");
libct_container_destroy(ct);
libct_session_close(s);
unlink(FS_ROOT "/" FS_FILE);
rmdir(FS_ROOT);
if (strcmp(fs_data, FS_DATA))
return fail("FS not accessed");
else
return pass("FS is OK");
}
| 2.875 | 3 |
2024-11-18T20:55:55.949083+00:00 | 2022-05-17T22:35:29 | 1d24cb7de9716e4fbcebf910aed34d54217fbb14 | {
"blob_id": "1d24cb7de9716e4fbcebf910aed34d54217fbb14",
"branch_name": "refs/heads/master",
"committer_date": "2022-05-17T22:35:29",
"content_id": "d6c70b01ff5707f6ed79ba3b969fcdbfeca7f1fc",
"detected_licenses": [
"MIT"
],
"directory_id": "c9bc4abf08727c668c495ef7df8b366c698f5bdd",
"extension": "c",
"filename": "getcip.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 94823749,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2648,
"license": "MIT",
"license_type": "permissive",
"path": "/source/getcip.c",
"provenance": "stackv2-0092.json.gz:55475",
"repo_name": "nyteshade/niceps1",
"revision_date": "2022-05-17T22:35:29",
"revision_id": "76fb49392ea33657e7fd3b5ef8474d6f0ed59600",
"snapshot_id": "f0d4f29a0880943f12dafcfde8a1ef30587badf3",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/nyteshade/niceps1/76fb49392ea33657e7fd3b5ef8474d6f0ed59600/source/getcip.c",
"visit_date": "2022-06-12T05:56:54.086126"
} | stackv2 | #include <sys/types.h>
#include <arpa/inet.h>
#include <ifaddrs.h>
#include <libgen.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
typedef struct IPA {
char ip[16];
char name[32];
} IPA;
typedef struct Args {
short showColor;
short hideName;
short maxCount;
char *ipFormat;
char *nameFormat;
} Args;
char *mkLowerCase(char *mixed) {
char *s = mixed;
for (; *s; ++s) *s = tolower(*s);
return mixed;
}
short idxOf(char *substring, char *string) {
char *result = strstr(string, substring);
return result ? result - string : -1;
}
short idxOfL(char *substring, char *string) {
char *sub = strdup(substring), *str = strdup(string), res = 0;
mkLowerCase(sub);mkLowerCase(str); res = idxOf(sub,str);
free(sub); free(str); return (short)res;
}
int main(int argc, char **argv) {
struct ifaddrs *tmp, *addrs;
char *s, format[255];
char ipWColor[] = "\x1b[0m%s\x1b[0;34m%s";
char ipWOColor[] = "%s%s";
char nameWColor[] = "\x1b[1;37m:\x1b[0;33m%s\x1b[0m";
char nameWOColor[] = ":%s";
int first = 1, i, shown = 0, ipCount = 0;
IPA ips[10];
Args args;
memset(&args, 0L, sizeof(Args));
args.maxCount = 10;
args.showColor = 1;
args.hideName = 0;
getifaddrs(&addrs);
tmp = addrs;
if (argc > 1 && (~idxOfL("?", argv[1]) || ~idxOfL("help", argv[1]))) {
printf("Usage: %s <args.maxCount> [--no-color] [--hide-name]\n", basename(argv[0]));
return 0;
}
for (i=1;i<argc;i++)
if (~idxOfL("--hide-name",argv[i])) { args.hideName = 1; break;}
for (i=1;i<argc;i++)
if (~idxOfL("--no-color",argv[i])) { args.showColor = 0; break; }
for (i=1;i<argc;i++)
if (!(args.maxCount = atoi(argv[i]))) { args.maxCount = 10; }
i = 0;
while(tmp) {
if (tmp->ifa_addr && tmp->ifa_addr->sa_family == AF_INET) {
struct sockaddr_in *pAddr = (struct sockaddr_in *)tmp->ifa_addr;
sprintf(ips[i].ip, "%s", inet_ntoa(pAddr->sin_addr));
sprintf(ips[i].name, "%s", tmp->ifa_name);
/* convert name tolower */
s = ips[i].name; for (; *s; ++s) *s = tolower(*s); s = ips[i].name;
ipCount++;
i++;
}
tmp = tmp->ifa_next;
}
strcpy(format, args.showColor ? ipWColor : ipWOColor);
if (!args.hideName) {
strcat(format, args.showColor ? nameWColor : nameWOColor);
}
for (i = 0, first = 1; i < ipCount; i++) {
if (!~idxOfL("lo", ips[i].name)) {
printf(
format,
first ? "" : ",",
ips[i].ip,
args.hideName ? "" : ips[i].name
);
first = 0;
shown++;
if (shown >= args.maxCount) break;
}
}
printf("\n");
freeifaddrs(addrs);
}
| 2.765625 | 3 |
2024-11-18T20:55:56.013383+00:00 | 2019-02-11T08:49:08 | cd45178dc3ace9b4c8dea28688422ac5c7467e05 | {
"blob_id": "cd45178dc3ace9b4c8dea28688422ac5c7467e05",
"branch_name": "refs/heads/master",
"committer_date": "2019-02-11T08:49:08",
"content_id": "e25a2e265b262b144a69c3ef5e93d8dc42d59aee",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "72773c724c42a2a2d7da63f04ca1647ce5be179a",
"extension": "c",
"filename": "program.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 159021224,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2818,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/190211_gcc_vs_clang/program.c",
"provenance": "stackv2-0092.json.gz:55605",
"repo_name": "dnobori/DNT-CodeSnipet",
"revision_date": "2019-02-11T08:49:08",
"revision_id": "d9008ac6bdca9209dca8b1e8c4869235305f630f",
"snapshot_id": "460d6bfd3544dd4335010c288f9ec24d201e9796",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/dnobori/DNT-CodeSnipet/d9008ac6bdca9209dca8b1e8c4869235305f630f/190211_gcc_vs_clang/program.c",
"visit_date": "2020-04-08T04:32:44.963230"
} | stackv2 | #include <stdio.h>
#include <time.h>
typedef unsigned short ushort;
typedef unsigned int uint;
typedef unsigned long long ulong;
typedef unsigned char byte;
typedef unsigned int bool;
#define true 1
#define false 0
#define null ((void *)0)
int sprintf(
char* const _Buffer,
char const* const _Format,
...);
#define true 1
#define false 0
typedef unsigned int BOOL;
#define TRUE 1
#define FALSE 0
typedef unsigned int UINT;
typedef unsigned int UINT32;
typedef unsigned int DWORD;
typedef signed int INT;
typedef signed int INT32;
typedef int UINT_PTR;
typedef long LONG_PTR;
typedef unsigned short WORD;
typedef unsigned short USHORT;
typedef signed short SHORT;
typedef unsigned char BYTE;
typedef unsigned char UCHAR;
typedef signed char CHAR;
typedef unsigned long long UINT64;
typedef signed long long INT64;
typedef struct VPageTableEntry
{
byte* RealMemory;
bool CanRead;
bool CanWrite;
} VPageTableEntry;
typedef struct VMemory
{
volatile VPageTableEntry *PageTableEntry;
volatile byte *ContiguousMemory;
volatile uint ContiguousStart;
volatile uint ContiguousEnd;
} VMemory;
typedef struct VCpuState
{
volatile VMemory *Memory;
volatile uint Eax, Ebx, Ecx, Edx, Esi, Edi, Ebp, Esp;
volatile char ExceptionString[256];
volatile uint ExceptionAddress;
} VCpuState;
UINT g_count = 0;
#include "GeneratedCode.c"
UINT64 Tick64()
{
struct timespec t = { 0 };
clock_gettime(CLOCK_MONOTONIC, &t);
return ((UINT64)((UINT32)t.tv_sec)) * 1000LL + (UINT64)t.tv_nsec / 1000000LL;
}
int main()
{
uint count = 10;
uint stackPtr = 0x500000 + 0x10000 / 2;
VMemory *memory = malloc(sizeof(VMemory));
memory->ContiguousMemory = malloc(0x8000000 + 0x100000 - 0x500000);
memory->ContiguousStart = 0x500000;
memory->ContiguousEnd = memory->ContiguousStart + 0x8000000 + 0x100000 - 0x500000;
VCpuState *state = malloc(sizeof(VCpuState));
memset(state, 0, sizeof(VCpuState));
state->Memory = memory;
uint ret = 0xffffffff;
ulong tick_start = Tick64();
for (uint i = 0;i < count;i++)
{
state->Esp = stackPtr;
state->Esp -= 4;
*((uint*)(byte*)(memory->ContiguousMemory + state->Esp - memory->ContiguousStart)) = CallRetAddress__MagicReturn;
Iam_The_IntelCPU_HaHaHa(state, FunctionTable_test_target2);
if (state->ExceptionString[0] != 0)
{
printf("Error: %s at 0x%x.\n", state->ExceptionString, state->ExceptionAddress);
exit(0);
}
else
{
uint r = state->Eax;
if (ret == 0xffffffff)
{
ret = r;
printf("ret = %u\n", state->Eax);
}
else if (ret == r) {}
else
{
printf("Error: Invalid result: %u\n", r);
exit(0);
}
}
}
ulong tick_end = Tick64();
printf("time = %u\n", (UINT)((tick_end - tick_start) / count));
printf("g_count = %u\n", g_count);
return 0;
}
| 2.421875 | 2 |
2024-11-18T20:55:56.472555+00:00 | 2016-11-09T16:56:51 | 4810fa4d94a22338c282782430a0eb4615826926 | {
"blob_id": "4810fa4d94a22338c282782430a0eb4615826926",
"branch_name": "refs/heads/master",
"committer_date": "2016-11-09T16:56:51",
"content_id": "519d10c6354a21c5aaeb5aa9735925df0e417b23",
"detected_licenses": [
"Apache-2.0",
"MIT"
],
"directory_id": "8384bcd2af4aefa1abfa24a857007353dde13330",
"extension": "c",
"filename": "json2map.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 72459872,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 7177,
"license": "Apache-2.0,MIT",
"license_type": "permissive",
"path": "/mongocms/libs/json2map/json2map.c",
"provenance": "stackv2-0092.json.gz:56119",
"repo_name": "maximilianvoss/mongocms",
"revision_date": "2016-11-09T16:56:51",
"revision_id": "f3842efc78422ff3952b7de850e79472c72d67b4",
"snapshot_id": "7961e280820594db9d9c463daffa64c5b8a22020",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/maximilianvoss/mongocms/f3842efc78422ff3952b7de850e79472c72d67b4/mongocms/libs/json2map/json2map.c",
"visit_date": "2021-06-18T18:26:21.397444"
} | stackv2 | #include "json2map.h"
#include "config.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "jsmn.h"
#include "debugging.h"
#include "stringlib.h"
char *json2map_setTokenValue(char *jsonString, jsmntok_t *token);
char *json2map_concatPaths(char *parent, char *key, int arrayIdx);
int json2map_calcEnd(jsmntok_t *token, int start, int end);
int json2map_parseArray(json2map_t *obj, char *path, char *jsonString, jsmntok_t *token, int start, int end);
int json2map_parseObject(json2map_t *obj, char *path, char *jsonString, jsmntok_t *token, int start, int end);
json2map_t *json2map_init() {
DEBUG_PUT("json2map_init()... ");
json2map_t *obj = (json2map_t *) malloc(sizeof(json2map_t));
DEBUG_PUT("json2map_init()... DONE");
return obj;
}
void json2map_destroy(json2map_t *obj) {
DEBUG_PUT("json2map_destroy()... ");
free(obj);
DEBUG_PUT("json2map_destroy()... DONE");
}
char *json2map_setTokenValue(char *jsonString, jsmntok_t *token) {
DEBUG_TEXT("json2map_setTokenValue(%s, [jsmntok_t *])... ", jsonString);
char *buffer;
buffer = calloc(sizeof(char), token->end - token->start + 1);
memcpy(buffer, jsonString + token->start, token->end - token->start);
DEBUG_TEXT("json2map_setTokenValue(%s, [jsmntok_t *])... DONE", jsonString);
return buffer;
}
char *json2map_concatPaths(char *parent, char *key, int arrayIdx) {
DEBUG_TEXT("json2map_concatPaths(%s, %s, %d)...", parent, key, arrayIdx);
char *path;
char arrayIdxBuff[10];
long arrayIdLen = 0;
long keyLen = 0;
long parentLen = 0;
long addition = -1;
if ( key != NULL ) {
keyLen = strlen(key);
addition++;
}
if ( parent != NULL ) {
parentLen = strlen(parent);
addition++;
}
if ( arrayIdx >= 0 ) {
sprintf(arrayIdxBuff, "%c%d%c", JSON2MAP_MAP_ARRAY_START, arrayIdx, JSON2MAP_MAP_ARRAY_END);
arrayIdLen += strlen(arrayIdxBuff);
}
if ( arrayIdx == -2 ) {
sprintf(arrayIdxBuff, "%c%c%c", JSON2MAP_MAP_ARRAY_START, JSON2MAP_MAP_ARRAY_COUNT, JSON2MAP_MAP_ARRAY_END);
arrayIdLen += strlen(arrayIdxBuff);
}
path = (char *) calloc(sizeof(char), parentLen + keyLen + arrayIdLen + addition + 1);
memcpy(path, parent, parentLen);
if ( parentLen && keyLen ) {
path[parentLen] = JSON2MAP_MAP_OBJECT_SEPARATOR;
}
memcpy(path + parentLen + addition, key, keyLen);
if ( arrayIdx >= 0 || arrayIdx == -2 ) {
memcpy(path + parentLen + keyLen + addition, arrayIdxBuff, arrayIdLen);
}
DEBUG_TEXT("json2map_concatPaths(%s, %s, %d)... DONE", parent, key, arrayIdx);
return path;
}
int json2map_calcEnd(jsmntok_t *token, int start, int end) {
// TODO: optimize search
DEBUG_TEXT("json2map_calcEnd([jsmntok_t *], %d, %d)...", start, end);
int i;
for ( i = start + 1; i < end; i++ ) {
if ( token[i].start > token[start].end ) {
DEBUG_TEXT("json2map_calcEnd([jsmntok_t *], %d, %d): return value=%d", start, end, i - 1);
DEBUG_TEXT("json2map_calcEnd([jsmntok_t *], %d, %d)... DONE", start, end);
return i - 1;
}
}
DEBUG_TEXT("json2map_calcEnd([jsmntok_t *], %d, %d): return value=%d", start, end, end - 1);
DEBUG_TEXT("json2map_calcEnd([jsmntok_t *], %d, %d)... DONE", start, end);
return end - 1;
}
int json2map_parseArray(json2map_t *obj, char *path, char *jsonString, jsmntok_t *token, int start, int end) {
DEBUG_TEXT("json2map_parseArray([json2map_t *], %s, %s, [jsmntok_t *], %d, %d)...", path, jsonString, start, end);
int newEnd;
char *buffer;
char *pathBuff;
int count = 0;
int i = start;
while ( i < end && i > 0 ) {
pathBuff = json2map_concatPaths(NULL, path, count);
count++;
switch ( token[i].type ) {
case JSMN_OBJECT:
newEnd = json2map_calcEnd(token, i, end);
i = json2map_parseObject(obj, pathBuff, jsonString, token, i + 1, newEnd + 1);
break;
case JSMN_STRING:
case JSMN_PRIMITIVE:
buffer = json2map_setTokenValue(jsonString, &token[i]);
obj->hookMethod(obj->hookMethodData, pathBuff, buffer);
free(buffer);
i++;
break;
default:
DEBUG_TEXT("json2map_parseArray([json2map_t *], %s, %s, [jsmntok_t *], %d, %d): ERROR: Not defined type", path, jsonString, start, end);
return -1;
}
free(pathBuff);
}
pathBuff = json2map_concatPaths(NULL, path, -2);
char smallBuffer[25];
stringlib_longToString(smallBuffer, count);
obj->hookMethod(obj->hookMethodData, pathBuff, smallBuffer);
free(pathBuff);
DEBUG_TEXT("json2map_parseArray([json2map_t *], %s, %s, [jsmntok_t *], %d, %d)... DONE", path, jsonString, start, end);
if ( i < 0 ) {
return i;
}
return end;
}
int json2map_parseObject(json2map_t *obj, char *path, char *jsonString, jsmntok_t *token, int start, int end) {
DEBUG_TEXT("json2map_parseObject([json2map_t *], %s, %s, [jsmntok_t *], %d, %d)...", path, jsonString, start, end);
int newEnd;
char *buffer;
char *pathBuff = NULL;
int i = start;
while ( i < end && i > 0 ) {
if ( token[i].type == JSMN_STRING ) {
buffer = json2map_setTokenValue(jsonString, &token[i]);
pathBuff = json2map_concatPaths(path, buffer, -1);
free(buffer);
} else {
DEBUG_TEXT("json2map_parseObject([json2map_t *], %s, %s, [jsmntok_t *], %d, %d): ERROR: Name of object has to be a string", path, jsonString, start, end);
return -1;
}
i++;
switch ( token[i].type ) {
case JSMN_OBJECT:
newEnd = json2map_calcEnd(token, i, end);
i = json2map_parseObject(obj, pathBuff, jsonString, token, i + 1, newEnd + 1);
break;
case JSMN_STRING:
case JSMN_PRIMITIVE:
buffer = json2map_setTokenValue(jsonString, &token[i]);
obj->hookMethod(obj->hookMethodData, pathBuff, buffer);
free(buffer);
i++;
break;
case JSMN_ARRAY:
newEnd = json2map_calcEnd(token, i, end);
i = json2map_parseArray(obj, pathBuff, jsonString, token, i + 1, newEnd + 1);
break;
default:
DEBUG_TEXT("json2map_parseObject([json2map_t *], %s, %s, [jsmntok_t *], %d, %d): ERROR: Not defined type", path, jsonString, start, end);
return -1;
}
free(pathBuff);
}
DEBUG_TEXT("json2map_parseObject([json2map_t *], %s, %s, [jsmntok_t *], %d, %d)... DONE", path, jsonString, start, end);
if ( i < 0 ) {
return i;
}
return end;
}
int json2map_parse(json2map_t *obj, char *jsonString) {
DEBUG_TEXT("json2map_parseObject([json2map_t *], %s)... ", jsonString);
jsmn_parser p;
jsmntok_t token[JSON2MAP_MAX_JSON_TOKENS];
jsmn_init(&p);
int count = jsmn_parse(&p, jsonString, strlen(jsonString), token, JSON2MAP_MAX_JSON_TOKENS);
if ( count < 0 ) {
DEBUG_TEXT("json2map_parseObject([json2map_t *], %s): ERROR: no object found", jsonString);
return -1;
}
if ( count < 1 || token[0].type != JSMN_OBJECT ) {
DEBUG_TEXT("json2map_parseObject([json2map_t *], %s): ERROR: first object needs to be a valid object", jsonString);
return -1;
}
DEBUG_TEXT("json2map_parseObject([json2map_t *], %s)... DONE", jsonString);
return json2map_parseObject(obj, NULL, jsonString, token, 1, count);
}
void json2map_registerHook(json2map_t *obj, void *data, void *method) {
DEBUG_PUT("json2map_registerHook([json2map_t *], [void *] [void *])... ");
obj->hookMethod = method;
obj->hookMethodData = data;
DEBUG_PUT("json2map_registerHook([json2map_t *], [void *] [void *])... DONE");
}
| 2.609375 | 3 |
2024-11-18T20:55:56.626755+00:00 | 2017-07-27T05:28:34 | 526e8cbbae926ac97e668f6adbd6f6c0fe6211f4 | {
"blob_id": "526e8cbbae926ac97e668f6adbd6f6c0fe6211f4",
"branch_name": "refs/heads/master",
"committer_date": "2017-07-27T05:28:34",
"content_id": "292e88f62bc5f61c6043b1dabf20ce13b2b0a6e6",
"detected_licenses": [
"MIT"
],
"directory_id": "6b024a41cc27fec03f924a140abe6dbca771c3db",
"extension": "c",
"filename": "ageinput.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 33969524,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2736,
"license": "MIT",
"license_type": "permissive",
"path": "/ascii_game_engine/input/ageinput.c",
"provenance": "stackv2-0092.json.gz:56378",
"repo_name": "paladin-t/ascii_game_engine",
"revision_date": "2017-07-27T05:28:34",
"revision_id": "05c1961b7a3cea5e46909cb5de2012cf0949abc3",
"snapshot_id": "96eb3afbb499647e7c1e1b2cd9ade2911e1672d4",
"src_encoding": "UTF-8",
"star_events_count": 12,
"url": "https://raw.githubusercontent.com/paladin-t/ascii_game_engine/05c1961b7a3cea5e46909cb5de2012cf0949abc3/ascii_game_engine/input/ageinput.c",
"visit_date": "2021-06-20T21:37:16.133180"
} | stackv2 | /*
** This source file is part of AGE
**
** For the latest info, see http://code.google.com/p/ascii-game-engine/
**
** Copyright (c) 2011 Tony & Tony's Toy Game Development Team
**
** 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.
*/
#if AGE_IMPL == AGE_IMPL_CONSOLE
#include "../common/ageutil.h"
#include "../common/ageallocator.h"
#include "ageinput.h"
typedef struct InputContext {
bl keys[256];
} InputContext;
static s32 KEY_MAP[MAX_PLAYER_COUNT][KC_COUNT];
bl open_input(void) {
bl result = TRUE;
memset(&KEY_MAP, 0, sizeof(KEY_MAP));
return result;
}
bl close_input(void) {
bl result = TRUE;
return result;
}
Ptr create_input_context(void) {
InputContext* result = AGE_MALLOC(InputContext);
return result;
}
void destroy_input_context(Ptr _ctx) {
AGE_FREE(_ctx);
}
void update_input_context(Ptr _ctx) {
InputContext* ctx = (InputContext*)_ctx;
s32 key = 0;
memset(ctx->keys, 0, sizeof(ctx->keys));
while(kbhit()) {
key = getch();
if(224 == key) {
key = getch();
}
ctx->keys[key] = TRUE;
}
}
bl register_key_map(s32 _player, KeyIndex _keyIdx, s32 _keyCode) {
bl result = TRUE;
assert(_player >= 0 && _player < MAX_PLAYER_COUNT && _keyIdx >= 0 && _keyIdx < KC_COUNT);
KEY_MAP[_player][_keyIdx] = _keyCode;
return result;
}
bl is_key_down(Ptr _ctx, s32 _player, KeyIndex _keyIdx) {
bl result = FALSE;
s32 key = 0;
InputContext* ctx = (InputContext*)_ctx;
assert(_player >= 0 && _player < MAX_PLAYER_COUNT && _keyIdx >= 0 && _keyIdx < KC_COUNT);
result = ctx->keys[KEY_MAP[_player][_keyIdx]] != 0;
return result;
}
#endif /* AGE_IMPL == AGE_IMPL_CONSOLE */
| 2.09375 | 2 |
2024-11-18T20:55:56.849923+00:00 | 2019-01-04T19:58:51 | bdf2cce6996270859118edfa8f6d3d05fbfe6f96 | {
"blob_id": "bdf2cce6996270859118edfa8f6d3d05fbfe6f96",
"branch_name": "refs/heads/master",
"committer_date": "2019-01-04T19:58:51",
"content_id": "4c6c015e5752f435e1fa56420afcd6415af5f684",
"detected_licenses": [
"MIT"
],
"directory_id": "9f615adae9bc754e52041e1cf8083e8f574219c5",
"extension": "c",
"filename": "bootloader_settings.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 11828699,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5828,
"license": "MIT",
"license_type": "permissive",
"path": "/archive/nrf51_9.0/libs/components/libraries/bootloader_dfu/bootloader_settings.c",
"provenance": "stackv2-0092.json.gz:56634",
"repo_name": "samuelclay/turntouch-remote",
"revision_date": "2019-01-04T19:58:51",
"revision_id": "f21e795a40b84af7779d7cf2d032c4d81fedc363",
"snapshot_id": "a492dc854f531a2b5446f33e88943be369734f9f",
"src_encoding": "UTF-8",
"star_events_count": 12,
"url": "https://raw.githubusercontent.com/samuelclay/turntouch-remote/f21e795a40b84af7779d7cf2d032c4d81fedc363/archive/nrf51_9.0/libs/components/libraries/bootloader_dfu/bootloader_settings.c",
"visit_date": "2021-01-19T07:01:19.018468"
} | stackv2 | /* Copyright (c) 2013 Nordic Semiconductor. All Rights Reserved.
*
* The information contained herein is property of Nordic Semiconductor ASA.
* Terms and conditions of usage are described in detail in NORDIC
* SEMICONDUCTOR STANDARD SOFTWARE LICENSE AGREEMENT.
*
* Licensees are granted free, non-transferable use of the information. NO
* WARRANTY of ANY KIND is provided. This heading must NOT be removed from
* the file.
*
*/
#include "bootloader_settings.h"
#include <stdint.h>
#include <dfu_types.h>
#if defined ( __CC_ARM )
uint8_t m_boot_settings[CODE_PAGE_SIZE] __attribute__((at(BOOTLOADER_SETTINGS_ADDRESS))) __attribute__((used)); /**< This variable reserves a codepage for bootloader specific settings, to ensure the compiler doesn't locate any code or variables at his location. */
uint32_t m_uicr_bootloader_start_address __attribute__((at(NRF_UICR_BOOT_START_ADDRESS))) = BOOTLOADER_REGION_START; /**< This variable ensures that the linker script will write the bootloader start address to the UICR register. This value will be written in the HEX file and thus written to UICR when the bootloader is flashed into the chip. */
#elif defined ( __GNUC__ )
__attribute__ ((section(".bootloaderSettings"))) uint8_t m_boot_settings[CODE_PAGE_SIZE]; /**< This variable reserves a codepage for bootloader specific settings, to ensure the compiler doesn't locate any code or variables at his location. */
__attribute__ ((section(".uicrBootStartAddress"))) volatile uint32_t m_uicr_bootloader_start_address = BOOTLOADER_REGION_START; /**< This variable ensures that the linker script will write the bootloader start address to the UICR register. This value will be written in the HEX file and thus written to UICR when the bootloader is flashed into the chip. */
#elif defined ( __ICCARM__ )
__no_init uint8_t m_boot_settings[CODE_PAGE_SIZE] @ 0x0003FC00; /**< This variable reserves a codepage for bootloader specific settings, to ensure the compiler doesn't locate any code or variables at his location. */
__root const uint32_t m_uicr_bootloader_start_address @ 0x10001014 = BOOTLOADER_REGION_START; /**< This variable ensures that the linker script will write the bootloader start address to the UICR register. This value will be written in the HEX file and thus written to UICR when the bootloader is flashed into the chip. */
#endif
#define SIZE_TEST_INDEX 8 /**< Index where first size field is located when half word aligned, or Bank Code 1 if word aligned. */
#define ZERO 0x00 /**< Value used for determine if struct is half word or word sized on first fields in the struct. */
void bootloader_util_settings_get(const bootloader_settings_t ** pp_bootloader_settings)
{
static bootloader_settings_t s_converted_boot_settings;
// Depending on the configuration / version the compiler used the enums used in bootloader
// settings might have different padding (half word / word padded).
// Half word padding would be, bc = Bank Code enum, crc (half word), xx = byte padding:
// bc0 xx crc crc - bc1 xx xx xx - rest of data
// Word padding would be, bc = Bank Code enum, crc (half word), xx = byte padding:
// bc0 xx xx xx - crc crc xx xx - bc1 xx xx xx - rest of data
// To ensure full compability when updating from older bootloader to new, the padding must
// be checked and conversion must be done accordingly.
// In case of empty flash, 0xFFFFFFFF it is unimportant how settings are loaded.
uint32_t pad_test = *((uint32_t *)&m_boot_settings[SIZE_TEST_INDEX]) & 0xFFFFFF00;
if (pad_test == ZERO)
{
// Bank code enum is word sized, thus it is safe to cast without conversion.
// Read only pointer to bootloader settings in flash.
bootloader_settings_t const * const p_bootloader_settings =
(bootloader_settings_t *)&m_boot_settings[0];
*pp_bootloader_settings = p_bootloader_settings;
}
else
{
// Bank code enum is half word sized, thus crc is following the bank code in same word.
uint32_t index = 0;
s_converted_boot_settings.bank_0 =
(bootloader_bank_code_t)((uint16_t)(m_boot_settings[index]) & 0xFFFF);
index += sizeof(uint16_t);
s_converted_boot_settings.bank_0_crc = uint16_decode(&m_boot_settings[index]);
index += sizeof(uint16_t);
s_converted_boot_settings.bank_1 =
(bootloader_bank_code_t)((uint16_t)(m_boot_settings[index]) & 0xFFFF);
// Rest of settings are word sized values and thus will be aligned to next word.
index += sizeof(uint32_t);
s_converted_boot_settings.bank_0_size = uint32_decode(&m_boot_settings[index]);;
index += sizeof(uint32_t);
s_converted_boot_settings.sd_image_size = uint32_decode(&m_boot_settings[index]);;
index += sizeof(uint32_t);
s_converted_boot_settings.bl_image_size = uint32_decode(&m_boot_settings[index]);;
index += sizeof(uint32_t);
s_converted_boot_settings.app_image_size = uint32_decode(&m_boot_settings[index]);;
index += sizeof(uint32_t);
s_converted_boot_settings.sd_image_start = uint32_decode(&m_boot_settings[index]);;
*pp_bootloader_settings = &s_converted_boot_settings;
}
}
| 2.125 | 2 |
2024-11-18T20:55:57.389901+00:00 | 2023-03-19T12:00:50 | 443d53092e8b5025958e7235b1b51e63f087d044 | {
"blob_id": "443d53092e8b5025958e7235b1b51e63f087d044",
"branch_name": "refs/heads/master",
"committer_date": "2023-03-19T12:00:50",
"content_id": "bce387e759c257971a6a5924e02fcebbcb0bb9cb",
"detected_licenses": [
"MIT"
],
"directory_id": "b085331fe9d658eebeaac0e27a96ea963a6ee5fb",
"extension": "c",
"filename": "string.c",
"fork_events_count": 0,
"gha_created_at": "2015-08-06T22:21:34",
"gha_event_created_at": "2018-10-21T08:36:17",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 40329496,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 174,
"license": "MIT",
"license_type": "permissive",
"path": "/cs50/week2/string.c",
"provenance": "stackv2-0092.json.gz:57916",
"repo_name": "fernandoalex/stuff",
"revision_date": "2023-03-19T12:00:50",
"revision_id": "dff08f1548116c2c9b0e4f36a7b1de76f7a4377a",
"snapshot_id": "a1e78105667bed323e57ee5e44043ef9e10ddf23",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/fernandoalex/stuff/dff08f1548116c2c9b0e4f36a7b1de76f7a4377a/cs50/week2/string.c",
"visit_date": "2023-05-31T20:54:01.504696"
} | stackv2 | #include <stdio.h>
#include <string.h>
int main(void) {
char string[] = "Something";
for (int i = 0, lenght = strlen(string); lenght > 0; i++) {
printf("%i", i);
}
}
| 2.625 | 3 |
2024-11-18T20:55:57.821959+00:00 | 2020-01-31T15:59:26 | a097ef5620223ad35100e476f13b638b83007a3c | {
"blob_id": "a097ef5620223ad35100e476f13b638b83007a3c",
"branch_name": "refs/heads/master",
"committer_date": "2020-01-31T15:59:26",
"content_id": "1f3f8913cd7f0f53fa5122236f6b42590cb8d812",
"detected_licenses": [
"MIT"
],
"directory_id": "98d53231958db63943fcf80544190d222066b21b",
"extension": "c",
"filename": "smh.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 236038800,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 835,
"license": "MIT",
"license_type": "permissive",
"path": "/src/application/smh.c",
"provenance": "stackv2-0092.json.gz:58430",
"repo_name": "lahoising78/gf2d",
"revision_date": "2020-01-31T15:59:26",
"revision_id": "54dc92817e8a45a02698aa0bad41c6b78ee0d2d3",
"snapshot_id": "50642ec9153e4e14c9d91eb159ae52407afd84d6",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/lahoising78/gf2d/54dc92817e8a45a02698aa0bad41c6b78ee0d2d3/src/application/smh.c",
"visit_date": "2020-12-20T10:16:13.721519"
} | stackv2 | #include "smh.h"
#include "simple_logger.h"
#include "gf2d_scene.h"
#include "gf2d_physics_entity.h"
extern float frameTime;
void do_the_thing( Entity *self )
{
self->position.y = 350.0f + 100.0f * cosf( 0.025f * self->position.x );
}
void smh_awake()
{
Entity *ent = NULL;
PhysicsEntity *pe = NULL;
ent = gf2d_entity_new();
ent->render_ent->sprite = gf2d_sprite_load_image("images/backgrounds/bg_flat.png");
gf2d_scene_add_entity(ent);
pe = gf2d_physics_entity_new();
pe->entity->render_ent->sprite = gf2d_sprite_load_all("images/space_bug.png", 128, 128, 16);
pe->entity->position = vector2d(0.0f, 350.0f);
pe->entity->velocity.x = 3.0f;
pe->type = PET_KINETIC;
pe->entity->update = do_the_thing;
if(gf2d_scene_add_entity(pe->entity) < 0)
slog("no le pudimo da na");
} | 2.171875 | 2 |
2024-11-18T20:55:58.636527+00:00 | 2020-05-06T16:31:42 | 8d0ed6c2e98038bdce6206f9a7c977efca197e8e | {
"blob_id": "8d0ed6c2e98038bdce6206f9a7c977efca197e8e",
"branch_name": "refs/heads/master",
"committer_date": "2020-05-06T16:31:42",
"content_id": "7a3a616acea1f750a95ae82d7143d81ae71286e5",
"detected_licenses": [
"Zlib"
],
"directory_id": "e8d24bda03d80e1bf0dda672b340ebb69f38f2b3",
"extension": "c",
"filename": "scoreboard_player.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": 2621,
"license": "Zlib",
"license_type": "permissive",
"path": "/tdd_game1_client/src/game_states/score/scoreboard_player.c",
"provenance": "stackv2-0092.json.gz:58689",
"repo_name": "rfaile313/raylib-webrtc_bomberman",
"revision_date": "2020-05-06T16:31:42",
"revision_id": "4d43e9d5856107e14371339c5d93af25f1cb58d8",
"snapshot_id": "58795c8c35fc877ff1b444e10d1a9788c8469388",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/rfaile313/raylib-webrtc_bomberman/4d43e9d5856107e14371339c5d93af25f1cb58d8/tdd_game1_client/src/game_states/score/scoreboard_player.c",
"visit_date": "2022-06-17T20:17:43.356594"
} | stackv2 | #include <raylib.h>
#include <tdd_ecs.h>
#include "../../components.h"
static Vector2 scoreboard_players_positions[] = {
(Vector2){70, 514},
(Vector2){262, 514},
(Vector2){453, 514},
(Vector2){641, 514}};
static const char* scoreboard_players_happy_region_names[][5] = {
{"scoreboard_bomberman_happy_white1", "scoreboard_bomberman_happy_white2"},
{"scoreboard_bomberman_happy_black1", "scoreboard_bomberman_happy_black2"},
{"scoreboard_bomberman_happy_purple1", "scoreboard_bomberman_happy_purple2"},
{"scoreboard_bomberman_happy_red1", "scoreboard_bomberman_happy_red2"}};
static const char* scoreboard_players_sad_region_names[][5] = {
{"scoreboard_bomberman_sad_white1", "scoreboard_bomberman_sad_white2"},
{"scoreboard_bomberman_sad_black1", "scoreboard_bomberman_sad_black2"},
{"scoreboard_bomberman_sad_purple1", "scoreboard_bomberman_sad_purple2"},
{"scoreboard_bomberman_sad_red1", "scoreboard_bomberman_sad_red2"}};
void create_scoreboard_player_entity(world_t* world, int player_id, bool is_round_winner)
{
TraceLog(LOG_INFO, "Create scoreboard player entity (player_id: %d, is_round_winner: %d)", player_id, is_round_winner);
entity_t* scoreboard_player_entity = world_create_entity(world);
Vector2 position = scoreboard_players_positions[player_id];
transform_t* transform = add_transform_to_entity(scoreboard_player_entity, (int)position.x, (int)position.y);
render_t* render = add_render_to_entity(scoreboard_player_entity);
sprite_data_t* sprite = create_sprite_from_atlas(
GET_TEXTURE_ATLAS_REGION("ui_atlas", (is_round_winner) ? scoreboard_players_happy_region_names[player_id][0] : scoreboard_players_sad_region_names[player_id][0]));
render_add_renderable(render, transform->root, (renderable_t*)sprite);
animated_t* animated = add_animated_to_entity(scoreboard_player_entity);
animated_sprite_t* animated_sprite = animated_create_animated_sprite(animated, sprite);
if (is_round_winner)
{
const char** regions = scoreboard_players_happy_region_names[player_id];
animated_add_animation_to_sprite(animated_sprite, "dance", animation_create("ui_atlas", 2, true, 2, regions[0], regions[1]));
animated_set_sprite_current_animation(animated_sprite, "dance");
}
else
{
const char **regions = scoreboard_players_sad_region_names[player_id];
animated_add_animation_to_sprite(animated_sprite, "cry", animation_create("ui_atlas", 2, true, 2, regions[0], regions[1]));
animated_set_sprite_current_animation(animated_sprite, "cry");
}
} | 2.0625 | 2 |
2024-11-18T20:56:00.337780+00:00 | 2018-04-10T21:16:51 | 4b2f7e7026fcc5ab5aa91ef69b1f1433b58b2585 | {
"blob_id": "4b2f7e7026fcc5ab5aa91ef69b1f1433b58b2585",
"branch_name": "refs/heads/master",
"committer_date": "2018-04-10T21:16:51",
"content_id": "b49251782d9d3a1f25293bbe137c9e0de9c593a3",
"detected_licenses": [
"MIT"
],
"directory_id": "f0e35da626bab2fd72b4326857cf9d12141cdb25",
"extension": "h",
"filename": "dict.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 117587584,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1041,
"license": "MIT",
"license_type": "permissive",
"path": "/c-src/dict.h",
"provenance": "stackv2-0092.json.gz:59205",
"repo_name": "AntonLydike/PasswordGen",
"revision_date": "2018-04-10T21:16:51",
"revision_id": "8fd2e8d2be117a418215d1f7064fc79c75055668",
"snapshot_id": "fea2ba319eb0994a31e016cf899ed2bbc43822ca",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/AntonLydike/PasswordGen/8fd2e8d2be117a418215d1f7064fc79c75055668/c-src/dict.h",
"visit_date": "2021-05-05T18:16:03.423805"
} | stackv2 | #ifndef DICT_H_INCL
#define DICT_H_INCL
#include <sodium.h>
#define DICT_NAME_MAX_LENGTH 64
// get the right path separator
#ifdef _WIN32
#define PATH_SEPARATOR '\\'
#else
#define PATH_SEPARATOR '/'
#endif //_WIN32
typedef struct dict_ {
unsigned int lines;
char name[DICT_NAME_MAX_LENGTH + 1];
char hash[65];
} dict;
typedef struct dict_list {
int length;
long int totalWordCount;
char * path;
dict * dicts;
} dicts;
int dict_create(dict *d, int lines, char * name, char hash[65]);
int dict_set_lines(dict *d, unsigned int lines);
int dict_set_name(dict *d, char * name);
int dict_set_hash(dict *d, char hash[65]);
int dict_update(dict d);
char * dict_getNthWord(dict *d, int n);
int dict_getHashAndLineCount (char* path, char hash[65], unsigned int * linecount);
int dict_import(char * path, dict *d);
int dicts_check(dicts list);
int dicts_write(dicts list);
int dicts_add(dicts list, dict *d);
int dicts_remove(dicts list, dict *d);
char * filenameFromPath(char * path);
void dict_print(dict d);
#endif
| 2.046875 | 2 |
2024-11-18T20:56:01.223229+00:00 | 2018-03-20T11:12:08 | ecda86298f953d03b6185e2ef9c401bccb6d44d4 | {
"blob_id": "ecda86298f953d03b6185e2ef9c401bccb6d44d4",
"branch_name": "refs/heads/master",
"committer_date": "2018-03-20T11:12:08",
"content_id": "51a8ef21a7cc738d70d27bb263ef4f158aa97333",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "ed675ee1295b12773b2cc4562df3b16e296ef2c6",
"extension": "c",
"filename": "instruction_set.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 64665563,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1511,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/src/lib/instruction_set.c",
"provenance": "stackv2-0092.json.gz:59982",
"repo_name": "ederlf/horse",
"revision_date": "2018-03-20T11:12:08",
"revision_id": "5c0b78c539b32e202f53f727e423d073b8c69570",
"snapshot_id": "4fecc99b51c833452b0f7ad493578c39cd10fefa",
"src_encoding": "UTF-8",
"star_events_count": 7,
"url": "https://raw.githubusercontent.com/ederlf/horse/5c0b78c539b32e202f53f727e423d073b8c69570/src/lib/instruction_set.c",
"visit_date": "2020-05-29T15:11:39.334051"
} | stackv2 | #include "instruction_set.h"
#include "util.h"
extern inline bool instruction_is_active(struct instruction_set *is, uint8_t type);
void
instruction_set_init(struct instruction_set *is)
{
is->active = 0;
action_list_init(&is->apply_act.actions);
action_set_init(&is->write_act.actions);
}
void
add_apply_actions(struct instruction_set *is, struct apply_actions act)
{
is->active |= INSTRUCTION_APPLY_ACTIONS;
memcpy(&is->apply_act, &act, sizeof(struct apply_actions));
}
void
add_clear_actions(struct instruction_set *is, struct clear_actions act)
{
is->active |= INSTRUCTION_CLEAR_ACTIONS;
memcpy(&is->clear_act, &act, sizeof(struct goto_table));
}
void
add_write_actions(struct instruction_set *is, struct write_actions act)
{
is->active |= INSTRUCTION_WRITE_ACTIONS;
memcpy(&is->write_act, &act, sizeof(struct write_actions));
}
void
add_write_metadata(struct instruction_set *is, struct write_metadata act)
{
is->active |= INSTRUCTION_WRITE_METADATA;
memcpy(&is->write_meta, &act, sizeof(struct write_metadata));
}
void
add_goto_table(struct instruction_set *is, struct goto_table act)
{
is->active |= INSTRUCTION_GOTO_TABLE;
memcpy(&is->gt_table, &act, sizeof(struct goto_table));
}
void
instruction_set_clean(struct instruction_set *is)
{
apply_actions_clean(&is->apply_act);
write_actions_clean(&is->write_act);
}
bool
instruction_is_active(struct instruction_set *is, uint8_t type){
return (is->active & type);
}
| 2.328125 | 2 |
2024-11-18T20:56:01.498103+00:00 | 2018-05-27T19:30:48 | a81a00ad1a6b15b7a3e7cba69650dc553f1250fa | {
"blob_id": "a81a00ad1a6b15b7a3e7cba69650dc553f1250fa",
"branch_name": "refs/heads/master",
"committer_date": "2018-05-27T19:30:48",
"content_id": "6377a93dc042f8995c745d4f0c8831b32d845e88",
"detected_licenses": [
"MIT"
],
"directory_id": "5d8a4acbf458e531399a61d5ffccfa2c12448f98",
"extension": "h",
"filename": "servo.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 93468203,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5668,
"license": "MIT",
"license_type": "permissive",
"path": "/code/ftclib/servo.h",
"provenance": "stackv2-0092.json.gz:60241",
"repo_name": "trc492/Ftc2012BowledOver",
"revision_date": "2018-05-27T19:30:48",
"revision_id": "7227d1f9160566cd50e737727cbe7ed237b3c5ae",
"snapshot_id": "1ba98603da38115d89de001c0ea5ddc58a05e803",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/trc492/Ftc2012BowledOver/7227d1f9160566cd50e737727cbe7ed237b3c5ae/code/ftclib/servo.h",
"visit_date": "2021-01-25T04:42:00.104877"
} | stackv2 | #if 0
/// Copyright (c) Titan Robotics Club. All rights reserved.
///
/// <module name="servo.h" />
///
/// <summary>
/// This module contains the library functions for the servo subsystem.
/// </summary>
///
/// <remarks>
/// Environment: RobotC for Lego Mindstorms NXT.
/// </remarks>
#endif
#ifndef _SERVO_H
#define _SERVO_H
#pragma systemFile
#ifdef MOD_ID
#undef MOD_ID
#endif
#define MOD_ID MOD_SERVO
//
// Constants.
//
#define SERVOF_CONTINUOUS_ENABLED 0x0100
#define SERVOF_CONTINUOUS 0x0200
#define SERVO_MIN_VALUE 0
#define SERVO_MAX_VALUE 255
#define SERVO_CONTINUOUS_STOP 127
#define SERVO_CONTINUOUS_FWD_MAX 255
#define SERVO_CONTINUOUS_REV_MAX 0
#define SERVO_CONTINUOUS_LOW -127
#define SERVO_CONTINUOUS_HIGH 128
#ifndef SERVO_ANGLE_RANGE
#define SERVO_ANGLE_RANGE 200.0
#define SERVO_POS_PER_DEGREE ((SERVO_MAX_VALUE - SERVO_MIN_VALUE)/ \
SERVO_ANGLE_RANGE)
#endif
//
// Type definitions.
//
typedef struct
{
TServoIndex servoMotor;
int servoFlags;
tSensors lowerTouchID;
tSensors upperTouchID;
int speed;
float posPerDegree;
} SERVO;
/**
* This function initializes a standard servo motor.
*
* @param serv Points to the SERVO structure to be initialized.
* @param servoMotor Specifies the servo motor ID.
* @param posPerDegree Specifies the position value per degree.
* @param initDegrees Specifies the initial position in degrees.
* @param servoFlags Specifies the servo flags.
*/
void
ServoInit(
__out SERVO &serv,
__in TServoIndex servoMotor,
__in float initDegrees,
__in float posPerDegree = SERVO_POS_PER_DEGREE
)
{
TFuncName("ServoInit");
TLevel(INIT);
TEnter();
serv.servoMotor = servoMotor;
serv.servoFlags = 0;
serv.lowerTouchID = (tSensors)-1;
serv.upperTouchID = (tSensors)-1;
serv.speed = SERVO_CONTINUOUS_STOP;
serv.posPerDegree = posPerDegree;
servo[servoMotor] = initDegrees*posPerDegree;
TExit();
return;
} //ServoInit
/**
* This function initializes a continuous servo motor.
*
* @param serv Points to the SERVO structure to be initialized.
* @param servoMotor Specifies the servo motor ID.
* @param lowerTouchID Specifies the sensor ID for the lower limit switch.
* @param upperTouchID Specifies the sensor ID for the upper limit switch.
*/
void
ServoInit(
__out SERVO &serv,
__in TServoIndex servoMotor,
__in tSensors lowerTouchID = -1,
__in tSensors upperTouchID = -1
)
{
TFuncName("ServoInit");
TLevel(INIT);
TEnter();
serv.servoMotor = servoMotor;
serv.servoFlags = SERVOF_CONTINUOUS;
serv.lowerTouchID = lowerTouchID;
serv.upperTouchID = upperTouchID;
serv.speed = SERVO_CONTINUOUS_STOP;
serv.posPerDegree = 0;
servo[servoMotor] = serv.speed;
TExit();
return;
} //ServoInit
/**
* This function gets the current servo position in degrees.
*
* @param serv Points to the SERVO structure.
*
* @return Returns the current servo position in degrees.
*/
float
ServoGetAngle(
__out SERVO &serv
)
{
float degree = 0.0;
TFuncName("ServoGetPos");
TLevel(API);
TEnter();
if (!(serv.servoFlags & SERVOF_CONTINUOUS))
{
degree = (float)ServoValue[serv.servoMotor]/serv.posPerDegree;
}
TExitMsg(("=%5.1f", degree));
return degree;
} //ServoGetAngle
/**
* This function sets servo position in degrees.
*
* @param serv Points to the SERVO structure.
* @param degree Specifies the servo position in degrees.
*/
void
ServoSetAngle(
__out SERVO &serv,
__in float degree
)
{
int servoPos;
TFuncName("ServoSetPos");
TLevel(API);
TEnterMsg(("degree=%5.1f", degree));
if (!(serv.servoFlags & SERVOF_CONTINUOUS))
{
servoPos = (int)(degree*serv.posPerDegree);
if (servoPos > SERVO_MAX_VALUE)
{
servoPos = SERVO_MAX_VALUE;
}
else if (servoPos < SERVO_MIN_VALUE)
{
servoPos = SERVO_MIN_VALUE;
}
servo[serv.servoMotor] = servoPos;
}
TExit();
return;
} //ServoSetAngle
/**
* This function sets servo position in degrees.
*
* @param serv Points to the SERVO structure.
* @param speed Specifies the continuous servo speed.
*/
void
ServoContinuousSetSpeed(
__out SERVO &serv,
__in int speed
)
{
TFuncName("ServoContSetSpeed");
TLevel(API);
TEnterMsg(("speed=%5.1f", speed));
if (serv.servoFlags & SERVOF_CONTINUOUS)
{
serv.speed = BOUND(speed,
SERVO_CONTINUOUS_LOW,
SERVO_CONTINUOUS_HIGH) + 127;
servo[serv.servoMotor] = serv.speed;
serv.servoFlags |= SERVOF_CONTINUOUS_ENABLED;
}
TExit();
return;
} //ServoContinuousSetSpeed
/**
* This function performs the servo task.
*
* @param serv Points to the SERVO structure.
*/
void
ServoTask(
__inout SERVO &serv
)
{
TFuncName("ServoTask");
TLevel(TASK);
TEnter();
if (serv.servoFlags & SERVOF_CONTINUOUS_ENABLED)
{
if ((serv.lowerTouchID != -1) &&
(SensorValue[serv.lowerTouchID] == 1) ||
(serv.upperTouchID != -1) &&
(SensorValue[serv.upperTouchID] == 1))
{
servo[serv.servoMotor] = SERVO_CONTINUOUS_STOP;
serv.servoFlags &= ~SERVOF_CONTINUOUS_ENABLED;
}
}
TExit();
return;
} //ServoTask
#endif //ifndef _SERVO_H
| 2.265625 | 2 |
2024-11-18T20:56:02.718817+00:00 | 2015-04-17T17:56:20 | f22a10f8ab895470fa187614d7cacfb622f28042 | {
"blob_id": "f22a10f8ab895470fa187614d7cacfb622f28042",
"branch_name": "refs/heads/master",
"committer_date": "2015-04-17T17:56:20",
"content_id": "68eeb69b4694b7df61efde55abd9df634ce70331",
"detected_licenses": [
"ISC"
],
"directory_id": "66bdc05e3e7e0a2069cbf59a8dad1fdf7a52caef",
"extension": "c",
"filename": "menulength.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 7389536,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 775,
"license": "ISC",
"license_type": "permissive",
"path": "/gcc/menu/menulength.c",
"provenance": "stackv2-0092.json.gz:60884",
"repo_name": "razzlefratz/MotleyTools",
"revision_date": "2015-04-17T17:56:20",
"revision_id": "3c69c574351ce6f4b7e687c13278d4b6cbb200f3",
"snapshot_id": "5e44f1315baa1be6fe5221916ccc834a96b59ca6",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/razzlefratz/MotleyTools/3c69c574351ce6f4b7e687c13278d4b6cbb200f3/gcc/menu/menulength.c",
"visit_date": "2020-05-19T05:01:58.992424"
} | stackv2 | /*====================================================================*
*
* void menulength (MENU * menu);
*
* menu.h
*
*. Motley Tools by Charles Maier
*: Published 1982-2005 by Charles Maier for personal use
*; Licensed under the Internet Software Consortium License
*
*--------------------------------------------------------------------*/
#ifndef MENULENGTH_SOURCE
#define MENULENGTH_SOURCE
#include <stdio.h>
#include "../menu/menu.h"
unsigned menulength (MENU * menu, signed length)
{
signed count = 0;
if (menu->prior)
{
count = menulength (menu->prior, length);
}
if (menu->equal)
{
count = menulength (menu->equal, length++);
}
if (menu->after)
{
count = menulength (menu->after, length);
}
return (count);
}
#endif
| 2.015625 | 2 |
2024-11-18T20:56:04.429628+00:00 | 2019-06-21T07:10:16 | 1f88441fb767cdb4a8447e7fd1814695095760cf | {
"blob_id": "1f88441fb767cdb4a8447e7fd1814695095760cf",
"branch_name": "refs/heads/master",
"committer_date": "2019-06-21T07:10:16",
"content_id": "9960debca22324c03c5f3ad085ed6cf36c824c4e",
"detected_licenses": [],
"directory_id": "4e0d616e5be0bfaaf36273d335e3aba9f82289f3",
"extension": "c",
"filename": "jacobi.c",
"fork_events_count": 0,
"gha_created_at": "2019-06-21T07:05:42",
"gha_event_created_at": "2019-06-21T07:05:43",
"gha_language": null,
"gha_license_id": "BSD-3-Clause",
"github_id": 193048773,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4606,
"license": "",
"license_type": "permissive",
"path": "/examples/jacobi.c",
"provenance": "stackv2-0092.json.gz:61653",
"repo_name": "luglio/hpx5",
"revision_date": "2019-06-21T07:10:16",
"revision_id": "6cbeebb8e730ee9faa4487dba31a38e3139e1ce7",
"snapshot_id": "4312e700670cca1d0b4439a9fecf627996f525be",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/luglio/hpx5/6cbeebb8e730ee9faa4487dba31a38e3139e1ce7/examples/jacobi.c",
"visit_date": "2020-06-07T15:24:10.492033"
} | stackv2 | // =============================================================================
// High Performance ParalleX Library (libhpx)
//
// Copyright (c) 2013-2017, Trustees of Indiana University,
// All rights reserved.
//
// This software may be modified and distributed under the terms of the BSD
// license. See the COPYING file for details.
//
// This software was created at the Indiana University Center for Research in
// Extreme Scale Technologies (CREST).
// =============================================================================
#include "hpx/hpx.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#define BSIZE sizeof(double)
#define IDX(base, offset) \
hpx_addr_add((base), (offset)*sizeof(double), sizeof(double))
// filename to dump the output to.
static char *_fname;
static void
_usage(FILE *f, int error)
{
fprintf(f, "Usage: jacobi [options]\n"
"\t-n, number of discretized points\n"
"\t-s, number of steps\n"
"\t-f, dump output to file\n"
"\t-h, show help\n");
hpx_print_help();
fflush(f);
exit(error);
}
static int
_op_handler(double *lu, int i, double h2, hpx_addr_t u, hpx_addr_t f)
{
double left, right, lf;
hpx_gas_memget_sync(&left, IDX(u,i-1), sizeof(left));
hpx_gas_memget_sync(&right, IDX(u,i+1), sizeof(right));
hpx_gas_memget_sync(&lf, IDX(f,i), sizeof(lf));
*lu = left + right + h2*lf/2;
return HPX_SUCCESS;
}
static HPX_ACTION(HPX_DEFAULT, HPX_PINNED, _op, _op_handler,
HPX_POINTER, HPX_INT, HPX_DOUBLE, HPX_ADDR, HPX_ADDR);
// Do sweeps of Jacobi iteration on a 1D Poisson problem
// discretized by n+1 equally spaced mesh points on [0,1].
// u is subject to Dirichlet boundary conditions specified in
// the u[0] and u[n] entries of the initial vector.
static void
_jacobi(int nsteps, int n, hpx_addr_t u, hpx_addr_t f)
{
double h = 1.0/n;
double h2 = h*h;
hpx_addr_t utmp = hpx_gas_alloc_local((n+1), BSIZE, 0);
// fill boundary conditions into utmp
hpx_gas_memcpy_sync(IDX(utmp,0), IDX(u,0), sizeof(double));
hpx_gas_memcpy_sync(IDX(utmp,n), IDX(u,n), sizeof(double));
hpx_addr_t and = hpx_lco_and_new(n-1);
for (int sweep = 0; sweep < nsteps; sweep += 2) {
for (int i = 1; i < n; ++i) {
hpx_xcall(IDX(utmp, i), _op, and, i, h2, u, f);
}
hpx_lco_wait_reset(and);
for (int i = 1; i < n; ++i) {
hpx_xcall(IDX(u, i), _op, and, i, h2, utmp, f);
}
hpx_lco_wait_reset(and);
}
hpx_lco_delete(and, HPX_NULL);
hpx_gas_free(utmp, HPX_NULL);
}
static void
_write_solution(int n, hpx_addr_t u, const char *fname)
{
double h = 1.0/n;
FILE* fp = fopen(fname, "w+");
double lu;
for (int i = 0; i <= n; ++i) {
hpx_gas_memget_sync(&lu, IDX(u,i), sizeof(lu));
fprintf(fp, "%g %g\n", i*h, lu);
}
fclose(fp);
}
static int
_jacobi_main_handler(int n, int nsteps)
{
double h = 1.0/n;
// allocate and initialize arrays
hpx_addr_t u = hpx_gas_calloc_local_attr((n+1), BSIZE, 0, HPX_GAS_ATTR_LB);
hpx_addr_t f = hpx_gas_alloc_local((n+1), BSIZE, 0);
hpx_addr_t and = hpx_lco_and_new(n+1);
for (int i = 0; i <= n; ++i) {
double val = i*h;
hpx_gas_memput_lsync(IDX(f,i), &val, sizeof(val), and);
}
hpx_lco_wait(and);
hpx_lco_delete(and, HPX_NULL);
printf("starting jacobi iterations...\n");
hpx_time_t start = hpx_time_now();
_jacobi(n, nsteps, u, f);
double elapsed = hpx_time_elapsed_ms(start)/1e3;
// run the solver
printf("n: %d\n", n);
printf("nsteps: %d\n", nsteps);
printf("seconds: %.7f\n", elapsed);
// write the results
if (_fname) {
_write_solution(n, u, _fname);
}
hpx_gas_free(f, HPX_NULL);
hpx_gas_free(u, HPX_NULL);
hpx_exit(0, NULL);
}
static HPX_ACTION(HPX_DEFAULT, 0, _jacobi_main, _jacobi_main_handler,
HPX_INT, HPX_INT);
int
main(int argc, char **argv)
{
int e = hpx_init(&argc, &argv);
if (e) {
fprintf(stderr, "failed to initialize HPX.\n");
return e;
}
int n = 100;
int nsteps = 100;
// parse the command line
int opt = 0;
while ((opt = getopt(argc, argv, "n:s:f:h?")) != -1) {
switch (opt) {
case 'n':
n = atoi(optarg);
break;
case 's':
nsteps = atoi(optarg);
break;
case 'f':
_fname = optarg;
break;
case 'h':
_usage(stdout, EXIT_SUCCESS);
break;
case '?':
default:
_usage(stderr, EXIT_FAILURE);
}
}
argc -= optind;
argv += optind;
// run the main action
e = hpx_run(&_jacobi_main, NULL, &n, &nsteps);
hpx_finalize();
return e;
}
| 2.4375 | 2 |
2024-11-18T21:20:01.176442+00:00 | 2017-09-13T16:17:56 | e69dfcf08492d2d94b30a7b4b89d50e689ffcb3c | {
"blob_id": "e69dfcf08492d2d94b30a7b4b89d50e689ffcb3c",
"branch_name": "refs/heads/master",
"committer_date": "2017-09-13T16:17:56",
"content_id": "98434f872344cfeb00ea729915fb167d2488a441",
"detected_licenses": [
"BSD-3-Clause",
"BSD-2-Clause"
],
"directory_id": "41ed8144286e50100b78adea787f38969d0a1c9a",
"extension": "c",
"filename": "PPL_Power.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": 8343,
"license": "BSD-3-Clause,BSD-2-Clause",
"license_type": "permissive",
"path": "/cil-template/src/ppl/PPL_Power.c",
"provenance": "stackv2-0094.json.gz:91",
"repo_name": "yijia1212/Workspace",
"revision_date": "2017-09-13T16:17:56",
"revision_id": "4616fb145e4554e72ec699a68db0f137ba13cf29",
"snapshot_id": "690ea2cd19633a410fd9785e5d3fdfe7bc3c1fa2",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/yijia1212/Workspace/4616fb145e4554e72ec699a68db0f137ba13cf29/cil-template/src/ppl/PPL_Power.c",
"visit_date": "2022-07-16T16:44:20.969265"
} | stackv2 | #include <ppl.hh>
#include <sstream>
#include <iostream>
#include "PPL_Power.h"
using namespace std;
using namespace Parma_Polyhedra_Library;
using namespace Parma_Polyhedra_Library::IO_Operators;
/* Check new powerset is the same as old powerset, return true
else merge the two powerset, delete old_m, return false
*/
bool merge(PPL_Manager *old_m, PPL_Manager *new_m){
if((new_m ->power_poly).geometrically_equals(old_m -> power_poly)){
delete old_m; /*just for test*/
return true;
}else{
Pointset_Powerset<NNC_Polyhedron>::const_iterator iter = (old_m -> power_poly).begin();
while(iter != (old_m -> power_poly).end()){
NNC_Polyhedron p = iter -> pointset();
Pointset_Powerset<NNC_Polyhedron> pp(p);
//if(!(new_m -> power_poly).geometrically_covers(pp)){
(new_m -> power_poly).add_disjunct(p); // omega-reduce
//}
iter ++;
}
delete old_m;
return false;
}
}
/*
D = A*B + C
*/
void setAffineFormImage(PPL_Manager *manager, int vid, Polynomial *poly){
Pointset_Powerset<NNC_Polyhedron>::iterator iter = (manager -> power_poly).begin();
Pointset_Powerset<NNC_Polyhedron> update_p(manager -> dimLen, EMPTY);
while(iter != (manager -> power_poly).end()){
NNC_Polyhedron p = iter -> pointset();
FP_Interval_Abstract_Store inv_store(manager -> dimLen);
p.refine_fp_interval_abstract_store(inv_store);
NNC_Polyhedron poly_p = poly -> polyhedronApprox(inv_store, (*(manager->varIdMap)[vid]).id());
p.unconstrain(*(manager->varIdMap)[vid]);
p.intersection_assign (poly_p);
/*
Linear_Form<FP_Interval> lf_lower;
Linear_Form<FP_Interval> lf_upper;
dp_f -> convertToLC(manager, inv_store, lf_lower, lf_upper, vid);
Linear_Form<FP_Interval> vf(*(manager->varIdMap)[vid]);
p.unconstrain(*(manager->varIdMap)[vid]);
p.refine_with_linear_form_inequality(lf_lower, vf);
p.refine_with_linear_form_inequality(vf, lf_upper);*/
update_p.add_disjunct(p);
iter ++;
}
manager -> power_poly = update_p;
delete poly;
}
/*return true, we have found fake counter example; return false, continue the refine process*/
bool refineBadState(PPL_Manager *manager, int vid, Polynomial *poly){
Pointset_Powerset<NNC_Polyhedron>::iterator iter = (manager -> power_poly).begin();
Pointset_Powerset<NNC_Polyhedron> update_p(manager -> dimLen, EMPTY);
/*TODO:currently we assume only one branch, thus the powerset contains just one polyhedron */
while(iter != (manager -> power_poly).end()){
NNC_Polyhedron p = iter -> pointset();
FP_Interval_Abstract_Store inv_store(manager -> dimLen);
p.refine_fp_interval_abstract_store(inv_store);
NNC_Polyhedron poly_p(manager->dimLen);
int count = 0;
while(count < 10){
poly_p = poly -> polyhedronApprox(inv_store, (*(manager->varIdMap)[vid]).id());
cout << "before:" << inv_store << endl;
p.intersection_assign(poly_p);
FP_Interval_Abstract_Store inv_store_test(manager -> dimLen);
p.refine_fp_interval_abstract_store(inv_store_test);
cout << "intersec: " << inv_store_test << endl;
if(p.is_empty()){
cout << "success SSSSSSSSSSSSSSSSSSSSS" << endl;
return true;
}
p.refine_fp_interval_abstract_store(inv_store);
cout << "after:" << inv_store << endl;
count ++;
}
//p.unconstrain(*(manager->varIdMap)[vid]);
update_p.add_disjunct(p);
iter ++;
}
manager -> power_poly = update_p;
cout << "new:" << getConstraintPretty(manager) << endl;
delete poly;
return false;
}
Polynomial *getPolynomialConstant(PPL_Manager *manager, float num){
return new Polynomial(num, manager -> dimLen);
}
Polynomial *getPolynomialVariable(PPL_Manager *manager, int vid){
Polynomial *p = new Polynomial((int)(*(manager->varIdMap)[vid]).id(), manager -> dimLen);
return p;
}
Polynomial *getPolynomialPlus(PPL_Manager *manager, Polynomial *left, Polynomial *right){
Polynomial *p = new Polynomial(*left + *right);
delete left;
delete right;
return p;
}
Polynomial *getPolynomialUnaryMinus(PPL_Manager *manager, Polynomial *l){
Polynomial *minusOne = getPolynomialConstant(manager, -1);
Polynomial *r = getPolynomialTimes(manager, minusOne, l);
return r;
}
Polynomial *getPolynomialMinus(PPL_Manager *manager, Polynomial *left, Polynomial *right){
Polynomial *p = new Polynomial(*left - *right);
delete left;
delete right;
return p;
}
Polynomial *getPolynomialTimes(PPL_Manager *manager, Polynomial *left, Polynomial *right){//parenthesis free
Polynomial *p = new Polynomial((left->monomial_list)[0] * (*right));
delete left;
delete right;
return p;
}
/* add constraint: A <= 0 */
//TODO : need to use linear constraint, instead of linear form constraint
void addConstraint(PPL_Manager *manager, Polynomial *left, Polynomial *right){
Pointset_Powerset<NNC_Polyhedron>::iterator iter = (manager -> power_poly).begin();
Pointset_Powerset<NNC_Polyhedron> update_p(manager -> dimLen, EMPTY);
int dim = 0;
float c = 0.0;
if(((left->monomial_list[0]).coefficients).size() > 0){
c = (left -> monomial_list[0]).coefficients[0].get_d();
for(int j = 0; j < right -> dimLen; j ++){
if((dim = right -> monomial_list[0].m_degree[j]) != 0){
break;
}
}
} else {
c = (right -> monomial_list[0]).coefficients[0].get_d();
for(int j = 0; j < left -> dimLen; j ++){
if((dim = left -> monomial_list[0].m_degree[j]) != 0){
break;
}
}
}
FP_Interval inv_c;
inv_c.lower() = c;
inv_c.upper() = c;
Variable v(dim);
Linear_Form<FP_Interval> lf_v(v), lf_c(inv_c);
while(iter != (manager -> power_poly).end()){
NNC_Polyhedron p = iter -> pointset();
p.refine_with_linear_form_inequality(lf_v, lf_c);
update_p.add_disjunct(p);
iter ++;
}
manager -> power_poly = update_p;
delete left;
delete right;
}
//TODO: see above addConstraint
void evalEqualConstraint(PPL_Manager *manager, Polynomial *left, Polynomial *right){
Pointset_Powerset<NNC_Polyhedron>::iterator iter = (manager -> power_poly).begin();
Pointset_Powerset<NNC_Polyhedron> update_p(manager -> dimLen, EMPTY);
int dim = 0;
float c = 0.0;
if(((left->monomial_list[0]).coefficients).size() > 0){
c = (left -> monomial_list[0]).coefficients[0].get_d();
for(int j = 0; j < right -> dimLen; j ++){
if((dim = right -> monomial_list[0].m_degree[j]) != 0){
break;
}
}
} else {
c = (right -> monomial_list[0]).coefficients[0].get_d();
for(int j = 0; j < left -> dimLen; j ++){
if((dim = left -> monomial_list[0].m_degree[j]) != 0){
break;
}
}
}
FP_Interval inv_c;
inv_c.lower() = c;
inv_c.upper() = c;
cout << "dim: " << dim << endl;
Variable v(10);
Linear_Form<FP_Interval> lf_v(v), lf_c(inv_c);
cout << "before:" << getConstraintPretty(manager) << endl;
while(iter != (manager -> power_poly).end()){
NNC_Polyhedron p = iter -> pointset();
//refine with linear equality lf_v == lf_c
//p.refine_with_linear_form_inequality(lf_v, lf_c);
//p.refine_with_linear_form_inequality(lf_c, lf_v);
//HACK: Fix K == 0
p.add_constraint(v == 0);
update_p.add_disjunct(p);
iter ++;
}
manager -> power_poly = update_p;
cout << "after:" << getConstraintPretty(manager) << endl;
delete left;
delete right;
}
char *getConstraintPretty(PPL_Manager *manager){
ostringstream sStream;
Pointset_Powerset<NNC_Polyhedron>::iterator iter = (manager -> power_poly).begin();
static char *s = new char[10000];
while(iter != (manager -> power_poly).end()){
NNC_Polyhedron p = iter -> pointset();
FP_Interval_Abstract_Store inv_store(manager -> dimLen);
p.refine_fp_interval_abstract_store(inv_store);
//sStream << "{" << p.constraints() << "}" << endl;
sStream << "{" << inv_store << "}" << endl;
/*
for(map<int Variable*>::iterator it = varIdMap.begin(); it != varIdMap.end(); it ++){
sStream << int_store[(it -> second) -> id()]
}
sStream << "}" ;*/
iter ++;
}
strcpy(s, sStream.str().c_str());
return s;
}
| 2.390625 | 2 |
2024-11-18T21:20:01.453519+00:00 | 2016-08-02T01:33:43 | 7590ce174fe0299094f9e4be0e68c2ac1a400979 | {
"blob_id": "7590ce174fe0299094f9e4be0e68c2ac1a400979",
"branch_name": "refs/heads/master",
"committer_date": "2016-08-02T03:01:09",
"content_id": "a0b8fc861d163c11f0c388986709e6908e36110b",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "f8a203c9c6f4032cfc656aee367db8e0eb34b8fa",
"extension": "c",
"filename": "override.c",
"fork_events_count": 5,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 64613730,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 9008,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/src/override.c",
"provenance": "stackv2-0094.json.gz:479",
"repo_name": "DecimalMan/dkp-installer",
"revision_date": "2016-08-02T01:33:43",
"revision_id": "471a869d43e3b117a9d8d386a0daa5a32dffdc37",
"snapshot_id": "e2d80b01279ae41ddcd42e6be7444ab5e5e07da8",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/DecimalMan/dkp-installer/471a869d43e3b117a9d8d386a0daa5a32dffdc37/src/override.c",
"visit_date": "2021-01-20T17:19:35.886820"
} | stackv2 | #include <unistd.h>
#include <stdint.h>
#include <stdlib.h>
#include <errno.h>
#include <time.h>
#include <sys/types.h>
#include "common.h"
#include "cpio.h"
#include <zlib/contrib/minizip/unzip.h>
#include <stdio.h>
// TODO: helper functions for manipulating file_chunks
enum override_flags {
OVER_CREATE = 1<<0, /* create if (apparently) missing */
OVER_POISON = 1<<1, /* duplicate; don't compress */
};
struct ramdisk_override {
const char *name;
int (*get_func)(struct cpio_ent *,
struct ramdisk_override *);
int flags;
char *buf;
unsigned int size;
};
/* ramdisk file overrides:
*/
static int wait_for_gensplash(struct cpio_ent *e, struct ramdisk_override *o);
static int check_zip(struct cpio_ent *e, struct ramdisk_override *o);
static int patch_initrc(struct cpio_ent *e, struct ramdisk_override *o);
static int patch_qcomrc(struct cpio_ent *e, struct ramdisk_override *o);
static struct ramdisk_override overrides[] = {
{ "dkp.profile.sh", check_zip, OVER_CREATE },
{ "init.dkp.rc", check_zip, OVER_CREATE },
{ "init.qcom.rc", patch_qcomrc },
{ "init.rc", patch_initrc },
{ "init.superuser.rc", check_zip, OVER_CREATE },
//{ "init.target.rc", check_zip },
{ "initlogo.rle", wait_for_gensplash },
{ "mpdecision", check_zip, OVER_CREATE },
{ NULL }
};
static unzFile zip;
/* ramdisk_push_override:
* Provide a buffer for later overriding. No synchronization is done.
* Currently, splash screen generation is the only consumer, and wait_thread()
* is sufficient.
*/
int ramdisk_push_override(char *name, char *buf, unsigned int size) {
struct ramdisk_override *rdo = overrides;
while (rdo->name) {
if (!strcmp(name, rdo->name)) {
if (rdo->buf) return -EBUSY;
rdo->buf = buf;
rdo->size = size;
return 0;
}
rdo++;
}
return -ENOENT;
}
/* ramdisk_init_overrides:
* Handle any preparation needed for overriding files. Currently, that means
* opening the install zip for check_zip().
*/
int ramdisk_init_overrides(void) {
int ret = 0;
if (!(zip = unzOpen(zip_path))) {
ret = -ENOENT;
goto out;
}
out:
return ret;
}
/* ramdisk_free_overrides:
* Clean up data used for overriding files. Currently, that means closing the
* install zip and freeing any buffers not freed by the compression thread.
*/
void ramdisk_free_overrides(void) {
struct ramdisk_override *rdo = overrides;
while (rdo->name) {
if (rdo->buf)
free(rdo->buf);
rdo->buf = NULL;
rdo++;
}
unzClose(zip);
}
/* insert_file:
* Create a valid cpio_ent & header, pass it to a get_func, and insert it in
* the output file list.
*/
int insert_file(struct ramdisk_override *o) {
int ret;
struct cpio_ent *e = cpio_ent_alloc();
if (!e) {
rprint("Allocation failed!");
return -ENOMEM;
}
/* Populate the header */
memcpy(&e->hdr,
/* magic */ "070701"
/* ino */ "00000001"
/* mode */ "00000000"
/* uid */ "00000000"
/* gid */ "00000000"
/* nlink */ "00000001"
/* mtime */ "00000000"
/* size */ "00000000"
/* major */ "00000000"
/* minor */ "00000000"
/* rmajor */ "00000000"
/* rminor */ "00000000"
/* namesize */ "00000000"
/* chksum */ "00000000"
, CPIO_HDR_LEN);
// compress thread populates ino, but must already be non-zero
ltox(e->hdr.mode, 0100750);
//ltox(e->hdr.mtime, (unsigned long)time(NULL));
ltox(e->hdr.namesize, strlen(o->name) + 1);
// get_func populates size
strcpy(e->hdr.name, o->name);
e->data.len = CPIO_HDR_LEN + strlen(o->name) + 1;
ret = o->get_func(e, o);
if (!ret) {
file_list_push(&write_files, e);
o->flags |= OVER_POISON;
} else {
cpio_ent_free(e);
}
return ret;
}
/* ramdisk_handle_overrides:
* Check overrides[] for any appropriate override functions. If a file is
* "missing" (i.e. strcmp shows we've passed its assumed location), use
* insert_file to create it.
*/
int ramdisk_handle_overrides(struct cpio_ent *e) {
int ret;
int cmp;
struct ramdisk_override *rdo = overrides;
/* For bizarre ramdisks, don't add files before the . entry. */
if (!strcmp(e->hdr.name, "."))
return 0;
while (rdo->name) {
ret = 0;
cmp = strcmp(e->hdr.name, rdo->name);
if (cmp < 0) {
rdo++;
continue;
}
if (cmp > 0) {
if (rdo->flags & OVER_CREATE &&
!(rdo->flags & OVER_POISON) &&
rdo->get_func) {
ret = insert_file(rdo);
rdo->get_func = NULL;
}
} else {
if (rdo->flags & OVER_POISON) {
e->__poison = 1;
} else if (rdo->get_func) {
ret = rdo->get_func(e, rdo);
rdo->flags |= OVER_POISON;
}
}
rdo++;
if (ret < 0) {
rprint("File patching failed, ignoring!");
//break;
}
}
//return ret < 0 ? ret : 0;
return 0;
}
/* wait_for_gensplash:
* Wait for the splash thread to complete, then (maybe) attach its buffer.
*/
static int wait_for_gensplash(struct cpio_ent *e, struct ramdisk_override *o) {
int ret;
struct file_chunk *c, *s;
if (ret = wait_thread(THREAD_GENSPLASH)) {
rprint("Not writing splash screen");
return 0;
//return ret;
}
s = e->data.next;
if (!(c = file_chunk_alloc(&e->data))) {
rprint("Allocation failed!");
e->data.next = s;
return -ENOMEM;
}
file_chunk_free(s);
ltox(e->hdr.size, o->size);
c->buf = o->buf;
c->len = o->size;
return 0;
}
/* check_zip:
* Look for a file in rd/ inside the install zip.
*/
static int check_zip(struct cpio_ent *e, struct ramdisk_override *o) {
unz_file_info info;
int len, r, ret = 0;
char zipf[40] = "rd/";
struct file_chunk *c, *s;
strcat(zipf, o->name);
if (unzLocateFile(zip, zipf, 1) != UNZ_OK) {
//rprint("File missing from zip!");
//return -ENOENT;
#ifndef RECOVERY_BUILD
printf("%s: skipping %s\n", __func__, o->name);
#endif
/* Don't insert an empty file */
return 1;
}
if (unzGetCurrentFileInfo(zip, &info, NULL, 0, NULL, 0, NULL, 0)
!= UNZ_OK)
return -EFAULT;
s = e->data.next;
if (!(c = file_chunk_alloc(&e->data)))
return -ENOMEM;
if (!(o->buf = malloc(info.uncompressed_size))) {
ret = -ENOMEM;
goto out;
}
//o->size = info.uncompressed_size;
if (unzOpenCurrentFile(zip) != UNZ_OK) {
ret = -EFAULT;
goto out;
}
for (len = 0; len < info.uncompressed_size; ) {
r = unzReadCurrentFile(zip, o->buf + len,
info.uncompressed_size - len);
if (r > 0) {
len += r;
continue;
}
if (r < 0) ret = -EFAULT;
break;
}
if (len < info.uncompressed_size)
ret = -EBADF;
if (unzCloseCurrentFile(zip) == UNZ_CRCERROR)
ret = -EBADF;
out:
if (ret) {
rprint("Error reading zipped file!");
free(o->buf);
o->buf = NULL;
e->data.next = s;
} else {
file_chunk_free(s);
c->buf = o->buf;
c->len = info.uncompressed_size;
ltox(e->hdr.size, c->len);
}
return ret;
}
/* patch_initrc:
* Patch init.rc to include init.dkp.rc.
*/
#define IMPORTDKP "import /init.dkp.rc\n"
#define IMPORTSU "import /init.superuser.rc\n"
static int patch_initrc(struct cpio_ent *e, struct ramdisk_override *o) {
struct file_chunk *c, *s;
char *ptr, *last = NULL, *buf;
int have_dkp = 0, have_su = 0;
if (!e->data.next) {
rprint("Missing init.rc data?!");
return -EINVAL;
}
/* Add a new (packed) chunk. */
s = e->data.next->next;
c = file_chunk_alloc(e->data.next);
if (!c) {
rprint("Out of memory?!");
e->data.next = s;
return 0;
}
/* Make sure we can return safely */
c[0].len = 0;
c[0].buf = (char *)&c[2];
c[0].next = &c[1];
c[1].len = 0;
c[1].buf = NULL;
c[1].next = s;
c[1].__alloc = 0;
/* Split the chunk after the final import line */
ptr = buf = e->data.next->buf;
while (ptr = strstr(ptr, "\nimport /")) {
/* While we're here, check which imports are present */
ptr += strlen("\nimport /");
if (!strncmp(ptr, "init.superuser.rc",
strlen("init.superuser.rc")))
have_su = 1;
else if (!strncmp(ptr, "init.dkp.rc",
strlen("init.dkp.rc")))
have_dkp = 1;
last = ptr;
}
if (!last) return 0;
ptr = strchr(last, '\n');
if (!ptr) return 0;
ptr++;
c[1].buf = ptr;
c[1].len = e->data.next->len - (ptr - buf);
e->data.next->len = ptr - buf;
/* Built our import lines */
c[0].buf[0] = '\0';
if (!have_su && unzLocateFile(zip, "rd/init.superuser.rc", 1) == UNZ_OK)
strcat(c[0].buf, "import /init.superuser.rc\n");
if (!have_dkp && unzLocateFile(zip, "rd/init.dkp.rc", 1) == UNZ_OK)
strcat(c[0].buf, "import /init.dkp.rc\n");
c[0].len = strlen(c[0].buf);
ltox(e->hdr.size, xtol(e->hdr.size) + c[0].len);
return 0;
}
/* patch_qcomrc:
* Comment out the power save profile hook. It's replaced in init.dkp.rc.
*/
#define PERFLINE "on property:sys.perf.profile="
static int patch_qcomrc(struct cpio_ent *e, struct ramdisk_override *o) {
char *ptr;
if (!e->data.next) {
rprint("Missing init.qcom.rc data?!");
return -EINVAL;
}
ptr = strstr(e->data.next->buf, PERFLINE);
if (!ptr) return 0;
do {
ptr = strchr(ptr, '\n');
if (!ptr)
break;
ptr++;
if (*ptr == ' ' || *ptr == '\t')
*ptr = '#';
else if (*ptr == '\r' || *ptr == '\n' || *ptr == '#')
continue;
else if (strncmp(ptr, PERFLINE, strlen(PERFLINE)))
break;
} while (1);
return 0;
}
| 2.203125 | 2 |
2024-11-18T21:20:01.596199+00:00 | 2020-06-26T12:36:36 | 2fb9ae5922fb53337b5e1571a2b41c5a1dbc5a0d | {
"blob_id": "2fb9ae5922fb53337b5e1571a2b41c5a1dbc5a0d",
"branch_name": "refs/heads/master",
"committer_date": "2020-06-26T12:36:36",
"content_id": "474dea1e7c499368d76ede21088c6e2050f8f2ff",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "780dd01e385ee622f3220f2ffcb00f785dbbfb49",
"extension": "h",
"filename": "leds.h",
"fork_events_count": 0,
"gha_created_at": "2020-08-10T22:46:55",
"gha_event_created_at": "2020-08-10T22:46:56",
"gha_language": null,
"gha_license_id": "Apache-2.0",
"github_id": 286593590,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2479,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/leds.h",
"provenance": "stackv2-0094.json.gz:609",
"repo_name": "Melissabenford30/charge-controller-firmware",
"revision_date": "2020-06-26T12:36:36",
"revision_id": "3c9a6e49f1dd97848c826207f729c04b82d47b2b",
"snapshot_id": "f0d7c7daab795b732f347d24924dfe12d538d09e",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Melissabenford30/charge-controller-firmware/3c9a6e49f1dd97848c826207f729c04b82d47b2b/src/leds.h",
"visit_date": "2022-12-03T00:58:57.676829"
} | stackv2 | /*
* Copyright (c) 2016 Martin Jäger / Libre Solar
*
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef LEDS_H
#define LEDS_H
/** @file
*
* @brief
* Control of status LEDs with charlieplexing
*/
#ifdef __cplusplus
extern "C" {
#endif
/** LED state type
*/
enum LedState {
LED_STATE_OFF = 0,
LED_STATE_ON,
LED_STATE_BLINK,
LED_STATE_FLICKER
};
/**
* Initialize LEDs and start timer for charlieplexing. This function only needs to be called if
* used in a single-thread application (mbed)
*/
void leds_init(bool enabled = true);
/** Main thread for LED control in Zephyr, performs pin initializations and charlieplexing at 60 Hz
*/
void leds_update_thread();
/** Enables/disables dedicated charging LED if existing or
* blinks SOC LED when solar power is coming in.
*/
void leds_set_charging(bool enabled);
/** Enables/disables LED
*
* @param led Number of LED in array defined in PCB configuration
* @param enabled LED is switched on if enabled is set to true
* @param timeout Defines for how long this state should be set (-1 for permanent setting)
*/
void leds_set(int led, bool enabled, int timeout = -1);
/** Enables LED
*
* @param led Number of LED in array defined in PCB configuration
* @param timeout Defines for how long this state should be set (-1 for permanent setting)
*/
void leds_on(int led, int timeout = -1);
/** Disables LED
*
* @param led Number of LED in array defined in PCB configuration
*/
void leds_off(int led);
/** Blinks LED
*
* @param led Number of LED in array defined in PCB configuration
* @param timeout Defines for how long this state should be set (-1 for permanent setting)
*/
void leds_blink(int led, int timeout = -1);
/** Flickers LED
*
* @param led Number of LED in array defined in PCB configuration
* @param timeout Defines for how long this state should be set (-1 for permanent setting)
*/
void leds_flicker(int led, int timeout = -1);
/** Updates LED blink and timeout states, must be called every second
*/
void leds_update_1s();
/** Updates SOC LED bar (if existing)
*
* @param soc SOC in percent
* @param load_off_low_soc Prevents showing two SOC LEDs if load is switched off because of low SOC
*/
void leds_update_soc(int soc, bool load_off_low_soc = false);
/** Toggles between even and uneven LEDs switched on/off to create
* annoying flashing in case of an error.
*/
void leds_toggle_error();
#ifdef __cplusplus
}
#endif
#endif /* LEDS_H */
| 2.28125 | 2 |
2024-11-18T22:23:03.230658+00:00 | 2017-04-20T10:17:49 | 507749e40d1172776e33592b4212d958328b9e18 | {
"blob_id": "507749e40d1172776e33592b4212d958328b9e18",
"branch_name": "refs/heads/master",
"committer_date": "2017-04-20T10:17:49",
"content_id": "7c736a8f0e6a77152b0d8d2180c4784648ab01db",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "ebd585fdafb22d31fcd6d04b209f81e88d1a2083",
"extension": "h",
"filename": "secboot_hash.h",
"fork_events_count": 10,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 88847837,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4071,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/boot_images/core/securemsm/secboot/inc/secboot_hash.h",
"provenance": "stackv2-0099.json.gz:183",
"repo_name": "xusl/android-wilhelm",
"revision_date": "2017-04-20T10:17:49",
"revision_id": "13c59cb5b0913252fe0b5c672d8dc2bf938bb720",
"snapshot_id": "fd28144253cd9d7de0646f96ff27a1f4a9bec6e3",
"src_encoding": "UTF-8",
"star_events_count": 11,
"url": "https://raw.githubusercontent.com/xusl/android-wilhelm/13c59cb5b0913252fe0b5c672d8dc2bf938bb720/boot_images/core/securemsm/secboot/inc/secboot_hash.h",
"visit_date": "2018-04-03T21:46:10.195170"
} | stackv2 | #ifndef _SECBOOT_HASH_H
#define _SECBOOT_HASH_H
/*========================================================================
SECURITY SERVICES
HASHING MODULE FOR SECBOOT
FILE: secboot_hash.h
DESCRIPTION:
This is the secboot interface into hashing. There is one function for
hashing a single buffer (secboot_hash), and the standard triumvirate of
init, update, and final (secboot_hashInit, secboot_hashUpdate, and
secboot_hashFinal), for multi-part hashing.
secboot_hash and secboot_hashInit take the hash type at an argument.
At present the only two valid values are PBL_SHA1 and PBL_SHA256.
secboot_hashInit, secboot_hashUpdate, and secboot_hashFinal all take a pointer to
a context structure. The same context structure works for all hash
types, and regardless of whether the implementation is hardware or
software. (See below.)
EXTERNALIZED FUNCTIONS
errno_enum_type secboot_hashInit(secboot_hash_ctx_t *ctx, secboot_hash_alg_t ht);
errno_enum_type secboot_hashUpdate(secboot_hash_ctx_t *ctx, void *data,
uint32 data_len);
errno_enum_type secboot_hashFinal(secboot_hash_ctx_t *ctx, uint8 *digest_ptr,
uint32 digest_buf_len);
errno_enum_type secboot_hash(secboot_hash_alg_t ht, void *data, uint32 data_len,
uint8 *digest_ptr,
uint32 digest_buf_len);
THREADING AND CONCURRENCY
No concurrent use of same CE hw engine is allowed. But this is okay in the boot loader,
which is single-threaded.
RETURN VALUES
E_SUCCESS: success
E_INVALID_ARG: some argument is invalid or out of range, or possibly
the context structure is uninitialized (update and final only).
Functions that accept a hash type (algorithm) check it and will
return this error code if it is invalid. (Thus there is no
need to check the validity of the hash type before calling.)
E_DATA_TOO_LARGE: target buffer is too small to receive the hash value.
E_FAILURE: hardware error, or hardware was unexpecedly busy, or some
other error, other than the above, detected in the driver.
MACROS
PBL_HASH_LEN(hash_type) returns the size of the digest value in bytes,
or zero if the hash_type is invalid.
========================================================================*/
/*=========================================================================
EDIT HISTORY FOR FILE
This section contains comments describing changes made to the module.
Notice that changes are listed in reverse chronological order.
$Header: //source/qcom/qct/core/pkg/bootloaders/rel/1.2.2/boot_images/core/securemsm/secboot/inc/secboot_hash.h#1 $
$DateTime: 2012/08/07 05:32:02 $
$Author: coresvc $
when who what, where, why
-------- --- ------------------------------------------------
10/10/10 sm Remove need for hw crypto feature, as we always go
through HW crypto by default
10/10/10 sm Add history.
============================================================================*/
#include "IxErrno.h"
#include "secboot_types.h"
#include "CeML.h"
/* zero indicates an error */
#define PBL_HASH_LEN(hashtype) \
((hashtype) == PBL_SHA1 ? PBL_SHA1_HASH_LEN : \
((hashtype) == PBL_SHA256 ? PBL_SHA256_HASH_LEN : \
0))
typedef struct
{
secboot_hash_alg_t halg;
union
{
SHA1_CTX sha1_ctx;
SHA256_CTX sha256_ctx;
CeMLCntxHandle *cntx;
} ctx_data;
} secboot_hash_ctx_t;
errno_enum_type secboot_hashInit
(
secboot_hash_ctx_t *ctx,
secboot_hash_alg_t ht
);
errno_enum_type secboot_hashUpdate
(
secboot_hash_ctx_t *ctx,
const uint8 *data,
uint32 data_len
);
errno_enum_type secboot_hashFinal
(
secboot_hash_ctx_t *ctx,
uint8 *digest_ptr,
uint32 digest_buf_len
);
errno_enum_type secboot_hash
(
secboot_hash_alg_t halg,
const uint8 *data,
uint32 data_len,
uint8 *digest_ptr,
uint32 digest_buf_len
);
#endif
| 2.21875 | 2 |
2024-11-18T22:23:03.287009+00:00 | 2023-07-17T19:08:32 | eb195cf067c2013d1dac0437ef64491b8b164575 | {
"blob_id": "eb195cf067c2013d1dac0437ef64491b8b164575",
"branch_name": "refs/heads/master",
"committer_date": "2023-07-17T19:08:32",
"content_id": "ead2ece3ea1532cf12021ce84a1540ca6a76c8f2",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "5dd12f565868b9fd8136a87939fe13997879def4",
"extension": "c",
"filename": "utezuka.c",
"fork_events_count": 15,
"gha_created_at": "2019-09-06T21:28:43",
"gha_event_created_at": "2023-07-17T19:08:34",
"gha_language": "C",
"gha_license_id": "Apache-2.0",
"github_id": 206876688,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 8581,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/testu01/utezuka.c",
"provenance": "stackv2-0099.json.gz:313",
"repo_name": "umontreal-simul/TestU01-2009",
"revision_date": "2023-07-17T19:08:32",
"revision_id": "a038a868755a75fca4ca8734031335aa0a7f7bcb",
"snapshot_id": "5e12d7668e009b2926b7b1ae2684fba7ce278c0c",
"src_encoding": "UTF-8",
"star_events_count": 50,
"url": "https://raw.githubusercontent.com/umontreal-simul/TestU01-2009/a038a868755a75fca4ca8734031335aa0a7f7bcb/testu01/utezuka.c",
"visit_date": "2023-07-25T16:45:16.404172"
} | stackv2 | /*************************************************************************\
*
* Package: TestU01
* File: utezuka.c
* Environment: ANSI C
*
* Copyright (c) 2002 Pierre L'Ecuyer, DIRO, Université de Montréal.
* e-mail: lecuyer@iro.umontreal.ca
* All rights reserved.
*
* This software is provided under the Apache 2 License.
*
* In scientific publications which used this software, a reference to it
* would be appreciated.
*
\*************************************************************************/
#include "util.h"
#include "addstr.h"
#include "utezuka.h"
#include "unif01.h"
#include <stdio.h>
#include <string.h>
/*============================== constants ==============================*/
#define LEN 250 /* Max length of strings */
#define DeuxExp28 268435456
#define DeuxExp29 536870912
#define DeuxExp31 2147483648U
#define DeuxExp32 4294967296.0
/* For the TezLec91 generator */
#define Q1 13
#define Q2 2
#define S1 12
#define S2 17
#define K1mS1 19
#define K2mS2 12
#define K1mK2 2
#define M1 2147483647 /* (2^31) - 1 */
#define M2 536870911 /* (2^29) - 1 */
/*================================ Types ================================*/
typedef struct {
double Norm;
} Tezuka_param;
typedef Tezuka_param TezLec91_param;
typedef Tezuka_param Tez95_param;
typedef Tezuka_param TezMRG95_param;
typedef struct {
unsigned int X1, X2;
} TezLec91_state;
typedef struct {
unsigned int X1, X2, X3;
} Tez95_state;
typedef struct {
int j1, k1, j2, k2;
unsigned int X1[5], X2[7];
} TezMRG95_state;
/*============================== Functions ==============================*/
static void WrTezLec91 (void *vsta)
{
TezLec91_state *state = vsta;
printf (" s1 = %1u, s2 = %1u\n", state->X1, state->X2);
}
static unsigned long TezLec91_Bits (void *junk, void *vsta)
{
TezLec91_state *state = vsta;
unsigned int A, B;
B = (M1 & (state->X1 ^ (state->X1 << Q1))) >> K1mS1;
A = state->X1 << S1;
state->X1 = M1 & (A ^ B);
B = (M2 & (state->X2 ^ (state->X2 << Q2))) >> K2mS2;
A = state->X2 << S2;
state->X2 = M2 & (A ^ B);
return (state->X1 ^ (state->X2 << K1mK2)) << 1;
}
static double TezLec91_U01 (void *vpar, void *vsta)
{
TezLec91_param *param = vpar;
return param->Norm * TezLec91_Bits (vpar, vsta);
}
unif01_Gen * utezuka_CreateTezLec91 (unsigned int Y1, unsigned int Y2)
{
unif01_Gen *gen;
TezLec91_param *param;
TezLec91_state *state;
size_t leng;
char name[LEN + 1];
util_Assert (Y1 < DeuxExp31, "utezuka_CreateTezLec91: Y1 >= 2^31");
util_Assert (Y2 < DeuxExp29, "utezuka_CreateTezLec91: Y2 >= 2^29");
gen = util_Malloc (sizeof (unif01_Gen));
param = util_Malloc (sizeof (TezLec91_param));
state = util_Malloc (sizeof (TezLec91_state));
strncpy (name, "utezuka_CreateTezLec91:", (size_t) LEN);
addstr_Uint (name, " Y1 = ", Y1);
addstr_Uint (name, ", Y2 = ", Y2);
leng = strlen (name);
gen->name = util_Calloc (leng + 1, sizeof (char));
strncpy (gen->name, name, leng);
state->X1 = Y1;
state->X2 = Y2;
param->Norm = 1.0 / DeuxExp32;
gen->GetBits = &TezLec91_Bits;
gen->GetU01 = &TezLec91_U01;
gen->Write = &WrTezLec91;
gen->param = param;
gen->state = state;
return gen;
}
/**************************************************************************/
static void WrTez95 (void *vsta)
{
Tez95_state *state = vsta;
printf (" s1 = %1u, s2 = %1u, s3 = %1u\n",
state->X1, state->X2, state->X3);
}
static unsigned long Tez95_Bits (void *junk, void *vsta)
{
Tez95_state *state = vsta;
unsigned int B;
B = ((state->X1 << 9) ^ state->X1) << 4;
state->X1 = (state->X1 << 13) ^ (B >> 19);
B = ((state->X2 << 2) ^ state->X2) << 3;
state->X2 = (state->X2 << 20) ^ (B >> 12);
B = ((state->X3 << 6) ^ state->X3) << 1;
state->X3 = (state->X3 << 17) ^ (B >> 15);
return state->X1 ^ state->X2 ^ state->X3;
}
static double Tez95_U01 (void *vpar, void *vsta)
{
Tez95_param *param = vpar;
return param->Norm * Tez95_Bits (vpar, vsta);
}
unif01_Gen *utezuka_CreateTez95 (unsigned int Y1, unsigned int Y2,
unsigned int Y3)
{
unif01_Gen *gen;
Tez95_param *param;
Tez95_state *state;
size_t leng;
char name[LEN + 1];
unsigned int B;
util_Assert (Y1 < DeuxExp28, "utezuka_CreateTez95: Y1 >= 2^28");
util_Assert (Y2 < DeuxExp29, "utezuka_CreateTez95: Y2 >= 2^29");
util_Assert (Y3 < DeuxExp31, "utezuka_CreateTez95: Y3 >= 2^31");
gen = util_Malloc (sizeof (unif01_Gen));
param = util_Malloc (sizeof (Tez95_param));
state = util_Malloc (sizeof (Tez95_state));
strncpy (name, "utezuka_CreateTez95:", (size_t) LEN);
addstr_Uint (name, " Y1 = ", Y1);
addstr_Uint (name, ", Y2 = ", Y2);
addstr_Uint (name, ", Y3 = ", Y3);
leng = strlen (name);
gen->name = util_Calloc (leng + 1, sizeof (char));
strncpy (gen->name, name, leng);
B = ((Y1 << 9) ^ Y1) << 4;
state->X1 = (Y1 << 4) ^ (B >> 28);
B = ((Y2 << 2) ^ Y2) << 3;
state->X2 = (Y2 << 3) ^ (B >> 29);
B = ((Y3 << 6) ^ Y3) << 1;
state->X3 = (Y3 << 1) ^ (B >> 31);
param->Norm = 1.0 / DeuxExp32;
gen->GetBits = &Tez95_Bits;
gen->GetU01 = &Tez95_U01;
gen->Write = &WrTez95;
gen->param = param;
gen->state = state;
return gen;
}
/**************************************************************************/
static void WrTezMRG95 (void *vsta)
{
TezMRG95_state *state = vsta;
int k;
if (unif01_WrLongStateFlag) {
printf (" S1 = (");
for (k = 0; k < 5; k++)
printf ("%12u ", state->X1[k]);
printf (" )\n\nS2 = (");
for (k = 0; k < 7; k++) {
printf ("%12u ", state->X2[k]);
if (k == 4)
printf ("\n ");
}
printf (" )\n\n");
} else
unif01_WrLongStateDef ();
}
static unsigned long TezMRG95_Bits (void *junk, void *vsta)
{
TezMRG95_state *state = vsta;
unsigned int *X1 = state->X1;
unsigned int *X2 = state->X2;
unsigned int b1, b2;
b1 = ((X1[state->k1] << 3) ^ X1[state->k1]) << 1;
b2 = ((X1[state->j1] << 3) ^ X1[state->j1]) << 1;
state->X1[state->k1] = (X1[state->k1] << 23) ^ (b1 >> 9) ^
(X1[state->j1] << 5) ^ (b2 >> 27);
b1 = ((X2[state->k2] << 2) ^ X2[state->k2]) << 3;
b2 = ((X2[state->j2] << 2) ^ X2[state->j2]) << 3;
state->X2[state->k2] = (X2[state->k2] << 19) ^ (b1 >> 13) ^
(X2[state->j2] << 16) ^ (b2 >> 16);
--state->j1;
if (state->j1 < 0)
state->j1 = 4;
--state->k1;
if (state->k1 < 0)
state->k1 = 4;
--state->j2;
if (state->j2 < 0)
state->j2 = 6;
--state->k2;
if (state->k2 < 0)
state->k2 = 6;
return state->X1[state->k1] ^ state->X2[state->k2];
}
static double TezMRG95_U01 (void *vpar, void *vsta)
{
TezMRG95_param *param = vpar;
return param->Norm * TezMRG95_Bits (vpar, vsta);
}
unif01_Gen *utezuka_CreateTezMRG95 (unsigned int Y1[5], unsigned int Y2[7])
{
unif01_Gen *gen;
TezMRG95_param *param;
TezMRG95_state *state;
size_t leng;
char name[LEN + 1];
int k;
unsigned int b;
for (k = 0; k < 5; k++)
util_Assert (Y1[k] < DeuxExp31,
"utezuka_CreateTezMRG95: Y1[k] >= 2^31");
for (k = 0; k < 7; k++)
util_Assert (Y2[k] < DeuxExp29,
"utezuka_CreateTezMRG95: Y2[k] >= 2^29");
gen = util_Malloc (sizeof (unif01_Gen));
param = util_Malloc (sizeof (TezMRG95_param));
state = util_Malloc (sizeof (TezMRG95_state));
strncpy (name, "utezuka_CreateTezMRG95:", (size_t) LEN);
addstr_ArrayUint (name, " Y1 = ", 5, Y1);
addstr_ArrayUint (name, ", Y2 = ", 7, Y2);
leng = strlen (name);
gen->name = util_Calloc (leng + 1, sizeof (char));
strncpy (gen->name, name, leng);
for (k = 0; k < 5; k++) {
b = ((Y1[k] << 3) ^ Y1[k]) << 1;
state->X1[k] = (Y1[k] << 1) ^ (b >> 31);
}
for (k = 0; k < 7; k++) {
b = ((Y2[k] << 2) ^ Y2[k]) << 3;
state->X2[k] = (Y2[k] << 3) ^ (b >> 29);
}
state->j1 = 1;
state->k1 = 4;
state->j2 = 4;
state->k2 = 6;
param->Norm = 1.0 / DeuxExp32;
gen->GetBits = &TezMRG95_Bits;
gen->GetU01 = &TezMRG95_U01;
gen->Write = &WrTezMRG95;
gen->param = param;
gen->state = state;
return gen;
}
/**************************************************************************/
void utezuka_DeleteGen (unif01_Gen *gen)
{
unif01_DeleteGen (gen);
}
| 2.375 | 2 |
2024-11-18T22:23:03.586527+00:00 | 2019-09-22T01:46:12 | 9ea8912657d3a724943003cd6bca53ccfee7ab23 | {
"blob_id": "9ea8912657d3a724943003cd6bca53ccfee7ab23",
"branch_name": "refs/heads/master",
"committer_date": "2019-09-22T01:46:12",
"content_id": "51f5a230e6bc5588dee975418bf2d1a7b69d33e4",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "9d8f38036ebddb5dc2cce75c5c500a83d7f51274",
"extension": "c",
"filename": "resource_led.c",
"fork_events_count": 1,
"gha_created_at": "2019-09-22T01:43:48",
"gha_event_created_at": "2022-12-11T06:42:21",
"gha_language": "C",
"gha_license_id": null,
"github_id": 210075623,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3262,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/st-things-neopixel/src/resource/resource_led.c",
"provenance": "stackv2-0099.json.gz:442",
"repo_name": "Bill-Park/tizen-hackathon",
"revision_date": "2019-09-22T01:46:12",
"revision_id": "59ba7490c25ed2ea0b155927dca44651327f1489",
"snapshot_id": "7ee25d7b1a4328b267cb4c28cfa2b06ed6eab6c3",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Bill-Park/tizen-hackathon/59ba7490c25ed2ea0b155927dca44651327f1489/st-things-neopixel/src/resource/resource_led.c",
"visit_date": "2022-12-11T20:01:45.916990"
} | stackv2 | /*
* Copyright (c) 2018 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <peripheral_io.h>
#include "resource/resource_led.h"
#include "log.h"
typedef enum {
LED_HANDLE_ERROR_NONE = 0, /**< Successful */
LED_HANDLE_ERROR_NOT_OPEN,
LED_HANDLE_ERROR_INVALID_PIN
} led_handle_error_e;
static peripheral_gpio_h g_sensor_h = NULL;
static int g_pin_num = -1;
int _resource_validate_led(int pin_num)
{
int ret = LED_HANDLE_ERROR_NONE;
if (!g_sensor_h)
{
ret = LED_HANDLE_ERROR_NOT_OPEN;
} else if (g_pin_num != pin_num) {
ret = LED_HANDLE_ERROR_INVALID_PIN;
}
return ret;
}
int resource_open_led(int pin_num)
{
peripheral_gpio_h temp = NULL;
int ret = peripheral_gpio_open(pin_num, &temp);
if (ret) {
peripheral_gpio_close(temp);
_E("peripheral_gpio_open failed.");
return -1;
}
ret = peripheral_gpio_set_direction(temp, PERIPHERAL_GPIO_DIRECTION_OUT_INITIALLY_LOW);
if (ret) {
peripheral_gpio_close(temp);
_E("peripheral_gpio_set_direction failed.");
return -1;
}
g_sensor_h = temp;
g_pin_num = pin_num;
return 0;
}
void resource_close_led(void)
{
if (!g_sensor_h) return;
_I("LED is finishing...");
peripheral_gpio_close(g_sensor_h);
g_sensor_h = NULL;
g_pin_num = -1;
}
int resource_write_led(int pin_num, int write_value)
{
int ret = PERIPHERAL_ERROR_NONE;
int ret_valid = LED_HANDLE_ERROR_NONE;
ret_valid = _resource_validate_led(pin_num);
if (ret_valid != LED_HANDLE_ERROR_NONE) {
if (ret_valid == LED_HANDLE_ERROR_NOT_OPEN) {
ret = resource_open_led(pin_num);
retv_if(ret != PERIPHERAL_ERROR_NONE, -1);
} else if (ret_valid == LED_HANDLE_ERROR_INVALID_PIN) {
_E("Invalid pin number.");
return -1;
}
}
ret = peripheral_gpio_write(g_sensor_h, write_value);
retv_if(ret < 0, -1);
return 0;
}
int _init_led_state(int pin_num, peripheral_gpio_h *temp) {
int ret = peripheral_gpio_open(pin_num, temp);
//open is 0, fail is -5
//if opened, temp1 be something(not 0), maybe address value
if (ret) {
peripheral_gpio_close(*temp);
_E("peripheral_gpio_open failed.");
return -1;
}
ret = peripheral_gpio_set_direction(*temp, PERIPHERAL_GPIO_DIRECTION_OUT_INITIALLY_LOW);
if (ret) {
peripheral_gpio_close(*temp);
_E("peripheral_gpio_set_direction failed.");
return -1;
}
return 0 ;
}
int _init_button(int pin_num, peripheral_gpio_h *temp)
{
int ret = peripheral_gpio_open(pin_num, temp);
if (ret) {
peripheral_gpio_close(*temp);
_E("peripheral_gpio_btn_open %d failed.", pin_num);
return -1;
}
ret = peripheral_gpio_set_direction(*temp, PERIPHERAL_GPIO_DIRECTION_IN);
if (ret) {
peripheral_gpio_close(*temp);
_E("peripheral_gpio_set_direction failed.");
return -1;
}
return 0;
}
| 2.5625 | 3 |
2024-11-18T22:23:03.780282+00:00 | 2022-05-17T13:30:59 | e8d24248cc3231e8d55ae2c7beecb4a9031ae8c7 | {
"blob_id": "e8d24248cc3231e8d55ae2c7beecb4a9031ae8c7",
"branch_name": "refs/heads/master",
"committer_date": "2022-05-17T13:31:08",
"content_id": "2eb23c01259be74b810177c2479cf3e8873f8431",
"detected_licenses": [
"MIT",
"CC0-1.0"
],
"directory_id": "667d3b23c42d542c468993c789dde4e4745c5695",
"extension": "c",
"filename": "asan.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 134198179,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1290,
"license": "MIT,CC0-1.0",
"license_type": "permissive",
"path": "/resea-old-c-userland/kernel/arch/x64/asan.c",
"provenance": "stackv2-0099.json.gz:700",
"repo_name": "nuta/archives",
"revision_date": "2022-05-17T13:30:59",
"revision_id": "3db15f62dc1b4497a8c9a39e32f997470653157f",
"snapshot_id": "ba72a63704af07415eb830631ca19c8e9006cc8e",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/nuta/archives/3db15f62dc1b4497a8c9a39e32f997470653157f/resea-old-c-userland/kernel/arch/x64/asan.c",
"visit_date": "2022-06-14T10:07:48.055078"
} | stackv2 | #include <arch.h>
#include <x64/apic.h>
#include <debug.h>
#ifdef DEBUG_BUILD
bool arch_asan_is_kernel_address(vaddr_t addr) {
return addr < 0xffff8000fec00000; // APIC registers.
}
extern char __kernel_image_start[];
extern char __kernel_image_end[];
void arch_asan_init(void) {
size_t image_len = (size_t) __kernel_image_end
- (size_t) __kernel_image_start;
// Kernel image.
asan_init_area(ASAN_VALID, (void *) __kernel_image_start, image_len);
// AP boot code.
asan_init_area(ASAN_VALID, from_paddr(AP_BOOT_CODE_PADDR), 0x1000);
// QEMU multiboot info.
asan_init_area(ASAN_VALID, from_paddr(0x9000), 0x1000);
// GRUB multiboot info.
asan_init_area(ASAN_VALID, from_paddr(0x10000), 0x1000);
// Text-mode VGA.
asan_init_area(ASAN_VALID, from_paddr(0xb8000), 0x1000);
// MP table.
asan_init_area(ASAN_VALID, from_paddr(0xe0000), 0x20000);
// Kernel's page table (maps above 0xffff8000_00000000).
asan_init_area(ASAN_VALID, from_paddr(0x700000), 0x30000);
// Kernel boot stacks.
asan_init_area(ASAN_VALID, (void *) KERNEL_BOOT_STACKS_ADDR,
KERNEL_BOOT_STACKS_LEN);
// CPUVARs.
asan_init_area(ASAN_VALID, (void *) CPU_VAR_ADDR, CPU_VAR_LEN);
}
#endif // DEBUG_BUILD
| 2.046875 | 2 |
2024-11-18T22:23:04.169127+00:00 | 2022-08-24T08:26:13 | e0baa359c2bcd1247a94a39898034af5706db052 | {
"blob_id": "e0baa359c2bcd1247a94a39898034af5706db052",
"branch_name": "refs/heads/master",
"committer_date": "2022-08-24T08:45:13",
"content_id": "00f9741f17d3721cf0e218590eb85ed37881c499",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "8aa62ead9aa06e286f88b71ab93f9b960458a0ed",
"extension": "c",
"filename": "hal_test.c",
"fork_events_count": 37,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 133309942,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1481,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/app/hal_app/src/hal_test.c",
"provenance": "stackv2-0099.json.gz:1345",
"repo_name": "alibaba/id2_client_sdk",
"revision_date": "2022-08-24T08:26:13",
"revision_id": "a8955eb7fc7f4b6d33a8d8810aa93ae3bd176007",
"snapshot_id": "424643ec4b302874ab3b4555497a6bc8860f1dfc",
"src_encoding": "UTF-8",
"star_events_count": 92,
"url": "https://raw.githubusercontent.com/alibaba/id2_client_sdk/a8955eb7fc7f4b6d33a8d8810aa93ae3bd176007/app/hal_app/src/hal_test.c",
"visit_date": "2023-03-12T21:17:09.629627"
} | stackv2 | /**
* Copyright (C) 2017-2019 Alibaba Group Holding Limited.
*/
#include "hal_test.h"
int hal_dump_data(const char *name, uint8_t *data, uint32_t size)
{
#if defined(CONFIG_HAL_DEBUG)
size_t i;
if (data == NULL || size == 0) {
HAL_TEST_ERR("invalid input args\n");
return -1;
}
HAL_TEST_INF("%s size: %d\n", name, (int)size);
for (i = 0; i < size - size % 8; i += 8) {
HAL_TEST_INF("%s data: %02x%02x %02x%02x %02x%02x %02x%02x\n", name,
data[i + 0], data[i + 1], data[i + 2], data[i + 3],
data[i + 4], data[i + 5], data[i + 6], data[i + 7]);
}
while (i < size) {
HAL_TEST_INF("%s data: %02x\n", name, data[i]);
i++;
}
return 0;
#else
(void)name;
(void)data;
(void)size;
return 0;
#endif
}
#if defined(CONFIG_HAL_CRYPTO)
int hal_crypto_test(void)
{
int ret = 0;
HAL_TEST_INF("HAL Hash Test:\n");
ret = hal_hash_test();
if (ret < 0) {
return ret;
}
HAL_TEST_INF("HAL Rand Test:\n");
ret = hal_rand_test();
if (ret < 0) {
return ret;
}
HAL_TEST_INF("HAL AES Test:\n");
ret = hal_aes_test();
if (ret < 0) {
return ret;
}
HAL_TEST_INF("HAL RSA Test:\n");
ret = hal_rsa_test();
if (ret < 0) {
return ret;
}
HAL_TEST_INF("HAL SM2 Test:\n");
ret = hal_sm2_test();
if (ret < 0) {
return ret;
}
return ret;
}
#endif
| 2.4375 | 2 |
2024-11-18T22:23:04.317281+00:00 | 2020-04-23T16:20:36 | 0b49d684285fdebf09e3d63935ef7c39456e0e33 | {
"blob_id": "0b49d684285fdebf09e3d63935ef7c39456e0e33",
"branch_name": "refs/heads/master",
"committer_date": "2020-04-23T16:20:36",
"content_id": "eb6307bbe840eed06be1f576c69281369bc74bec",
"detected_licenses": [
"MIT"
],
"directory_id": "04a8ed52b7405fcd7a3902dac354a6cbba6dd98c",
"extension": "c",
"filename": "encrypt.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 258261727,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1522,
"license": "MIT",
"license_type": "permissive",
"path": "/28_fix_vg_encr/encrypt.c",
"provenance": "stackv2-0099.json.gz:1602",
"repo_name": "liamhawkins/c-specialization-duke-university",
"revision_date": "2020-04-23T16:20:36",
"revision_id": "d82521507d53c74a237d3f095954f26835b85fe1",
"snapshot_id": "8d1529b99fa9c8659955dafdc0cb16ce7510164a",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/liamhawkins/c-specialization-duke-university/d82521507d53c74a237d3f095954f26835b85fe1/28_fix_vg_encr/encrypt.c",
"visit_date": "2022-04-24T11:35:07.625289"
} | stackv2 | #include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
void encrypt(FILE * f, int key, FILE * outfile){
char * line = NULL;
size_t sz = 0;
while (getline(&line,&sz, f) >= 0) {
char * ptr = line;
while (*ptr != '\0') {
int c = *ptr;
if (isalpha(c)) {
c = tolower(c);
c -= 'a';
c += key;
c %= 26;
c += 'a';
}
*ptr = c;
ptr++;
}
fprintf(outfile, "%s", line);
}
free(line);
}
int main(int argc, char ** argv) {
if (argc != 3) {
fprintf(stderr,"Usage: encrypt key inputFileName\n");
return EXIT_FAILURE;
}
int key = atoi(argv[1]);
if (key == 0) {
fprintf(stderr,"Invalid key (%s): must be a non-zero integer\n", argv[1]);
return EXIT_FAILURE;
}
FILE * f = fopen(argv[2], "r");
if (f == NULL) {
perror("Could not open file");
return EXIT_FAILURE;
}
//outfileNAme is argv[2] + ".txt", so add 4 to its length.
char * inFileName = argv[2];
char * outFileName = malloc((strlen(inFileName) + 5) * sizeof(*inFileName));
strcpy(outFileName, inFileName);
strcat(outFileName, ".enc");
FILE * outFile = fopen(outFileName, "w");
if (outFile == NULL){
perror("Could not open file");
return EXIT_FAILURE;
}
free(outFileName);
encrypt(f,key, outFile);
if (fclose(outFile) != 0) {
perror("Failed to close the input file!");
return EXIT_FAILURE;
}
if (fclose(f) != 0) {
perror("Failed to close the input file!");
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
| 3.046875 | 3 |
2024-11-18T22:23:04.401101+00:00 | 2021-07-28T16:09:24 | 791944c780c2deb90a8c0ad8f580a6bae71111a1 | {
"blob_id": "791944c780c2deb90a8c0ad8f580a6bae71111a1",
"branch_name": "refs/heads/main",
"committer_date": "2021-07-28T16:09:24",
"content_id": "d61a3ac121eee2f4a5589f96ee0f3f0a0ba48b1b",
"detected_licenses": [
"MIT"
],
"directory_id": "87731093dcdd20800f4609b7fbfd1f78c76add05",
"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": 365926813,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 290,
"license": "MIT",
"license_type": "permissive",
"path": "/area_triangulo/main.c",
"provenance": "stackv2-0099.json.gz:1730",
"repo_name": "Rodrigo98Matos/Projetos_C",
"revision_date": "2021-07-28T16:09:24",
"revision_id": "344432527028ddb6dd09aafbd1c0c66f557b3cc2",
"snapshot_id": "f7bf51731feeed4fc5c2dbd0023851ca4bb6f535",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Rodrigo98Matos/Projetos_C/344432527028ddb6dd09aafbd1c0c66f557b3cc2/area_triangulo/main.c",
"visit_date": "2023-06-25T19:05:57.439726"
} | stackv2 | #include <stdio.h>
/*Faça uma função que dado a base e a altura de um retângulo retorne a área.*/
int main(void) {
float a, b, c;
printf("Base:\t");
scanf("%f",&b);
printf("Altura:\t");
scanf("%f",&a);
c = a * b;
printf("A área deste retângulo é %f", c);
return 0;
} | 3.5625 | 4 |
2024-11-18T22:23:04.510695+00:00 | 2023-07-18T20:28:44 | d61c91e5f7faea122e7b9f41b6349b77b626c79c | {
"blob_id": "d61c91e5f7faea122e7b9f41b6349b77b626c79c",
"branch_name": "refs/heads/master",
"committer_date": "2023-07-18T20:28:44",
"content_id": "b301d0809575331d5bf349136219f9689a6431d1",
"detected_licenses": [
"MIT"
],
"directory_id": "fd30f70fb125ed18f900ec30566756b40d24fc17",
"extension": "h",
"filename": "vm.h",
"fork_events_count": 8,
"gha_created_at": "2018-03-26T17:39:21",
"gha_event_created_at": "2023-06-08T08:47:57",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 126866164,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5978,
"license": "MIT",
"license_type": "permissive",
"path": "/src/vm.h",
"provenance": "stackv2-0099.json.gz:1860",
"repo_name": "bamless/jstar",
"revision_date": "2023-07-18T20:28:44",
"revision_id": "0e2a09c50cdedd234dd801f38b519c3ea435b473",
"snapshot_id": "ec321efe4029433957af5bd37576e1b1d84a22ab",
"src_encoding": "UTF-8",
"star_events_count": 100,
"url": "https://raw.githubusercontent.com/bamless/jstar/0e2a09c50cdedd234dd801f38b519c3ea435b473/src/vm.h",
"visit_date": "2023-07-19T04:02:57.628542"
} | stackv2 | #ifndef VM_H
#define VM_H
#include <signal.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdlib.h>
#include "compiler.h"
#include "hashtable.h"
#include "jstar.h"
#include "jstar_limits.h"
#include "object.h"
#include "util.h"
#include "value.h"
// Enum encoding special method names needed at runtime
// Mainly used for operator overloading
// See methodSyms array in vm.c
typedef enum MethodSymbol {
SYM_CTOR,
SYM_ITER,
SYM_NEXT,
SYM_ADD,
SYM_SUB,
SYM_MUL,
SYM_DIV,
SYM_MOD,
SYM_BAND,
SYM_BOR,
SYM_XOR,
SYM_LSHFT,
SYM_RSHFT,
SYM_RADD,
SYM_RSUB,
SYM_RMUL,
SYM_RDIV,
SYM_RMOD,
SYM_RBAND,
SYM_RBOR,
SYM_RXOR,
SYM_RLSHFT,
SYM_RRSHFT,
SYM_GET,
SYM_SET,
SYM_NEG,
SYM_INV,
SYM_EQ,
SYM_LT,
SYM_LE,
SYM_GT,
SYM_GE,
SYM_POW,
SYM_RPOW,
SYM_END
} MethodSymbol;
// Struct that stores the info needed to
// jump to handler code and to restore the
// VM state when handling exceptions
typedef struct Handler {
enum {
HANDLER_ENSURE,
HANDLER_EXCEPT,
} type; // The type of the handler block
uint8_t* address; // The address of handler code
Value* savedSp; // Saved stack state before the try block was enterd
} Handler;
// Stackframe of a function executing in
// the virtual machine
typedef struct Frame {
uint8_t* ip; // Instruction pointer
Value* stack; // Base of stack for current frame
Obj* fn; // Function associated with the frame (ObjClosure or ObjNative)
ObjGenerator* gen; // Generator of this frame (if any)
Handler handlers[MAX_HANDLERS]; // Exception handlers
uint8_t handlerCount; // Exception handlers count
} Frame;
// The J* VM. This struct stores all the
// state needed to execute J* code.
struct JStarVM {
// Built in classes
ObjClass* clsClass;
ObjClass* objClass;
ObjClass* strClass;
ObjClass* boolClass;
ObjClass* lstClass;
ObjClass* numClass;
ObjClass* funClass;
ObjClass* genClass;
ObjClass* modClass;
ObjClass* nullClass;
ObjClass* stClass;
ObjClass* tupClass;
ObjClass* excClass;
ObjClass* tableClass;
ObjClass* udataClass;
// Script arguments
ObjList* argv;
// The empty tuple (singleton)
ObjTuple* emptyTup;
// Current VM compiler (if any)
Compiler* currCompiler;
// Cached method names needed at runtime
ObjString* methodSyms[SYM_END];
// Loaded modules
HashTable modules;
// Current module and core module
ObjModule *module, *core;
// VM program stack and stack pointer
size_t stackSz;
Value *stack, *sp;
// Frame stack
Frame* frames;
int frameSz, frameCount;
// Number of reentrant calls made into the VM
int reentrantCalls;
// Stack used during native function calls
Value* apiStack;
// Constant string pool, for interned strings
HashTable stringPool;
// Linked list of all open upvalues
ObjUpvalue* upvalues;
// Callback function to report errors
JStarErrorCB errorCallback;
// Callback used to resolve `import`s
JStarImportCB importCallback;
// If set, the VM will break the eval loop as soon as possible.
// Can be set asynchronously by a signal handler
volatile sig_atomic_t evalBreak;
// Custom data associated with the VM
void* customData;
// ---- Memory management ----
// Linked list of all allocated objects (used in
// the sweep phase of GC to free unreached objects)
Obj* objects;
size_t allocated; // Bytes currently allocated
size_t nextGC; // Bytes at which the next GC will be triggered
int heapGrowRate; // Rate at which the heap will grow after a GC
// Stack used to recursevely reach all the fields of reached objects
Obj** reachedStack;
size_t reachedCapacity, reachedCount;
};
bool getValueField(JStarVM* vm, ObjString* name);
bool setValueField(JStarVM* vm, ObjString* name);
bool getValueSubscript(JStarVM* vm);
bool setValueSubscript(JStarVM* vm);
bool callValue(JStarVM* vm, Value callee, uint8_t argc);
bool invokeValue(JStarVM* vm, ObjString* name, uint8_t argc);
void reserveStack(JStarVM* vm, size_t needed);
void swapStackSlots(JStarVM* vm, int a, int b);
bool runEval(JStarVM* vm, int evalDepth);
bool unwindStack(JStarVM* vm, int depth);
inline void push(JStarVM* vm, Value v) {
*vm->sp++ = v;
}
inline Value pop(JStarVM* vm) {
return *--vm->sp;
}
inline Value peek(JStarVM* vm) {
return vm->sp[-1];
}
inline Value peek2(JStarVM* vm) {
return vm->sp[-2];
}
inline Value peekn(JStarVM* vm, int n) {
return vm->sp[-(n + 1)];
}
inline ObjClass* getClass(JStarVM* vm, Value v) {
#ifdef JSTAR_NAN_TAGGING
if(IS_OBJ(v)) return AS_OBJ(v)->cls;
if(IS_NUM(v)) return vm->numClass;
switch(BITS_TAG(v)) {
case HANDLE_BITS:
case NULL_BITS:
return vm->nullClass;
case FALSE_BITS:
case TRUE_BITS:
return vm->boolClass;
default:
UNREACHABLE();
return NULL;
}
#else
switch(v.type) {
case VAL_NUM:
return vm->numClass;
case VAL_BOOL:
return vm->boolClass;
case VAL_OBJ:
return AS_OBJ(v)->cls;
case VAL_HANDLE:
case VAL_NULL:
return vm->nullClass;
default:
UNREACHABLE();
return NULL;
}
#endif
}
inline bool isInstance(JStarVM* vm, Value i, ObjClass* cls) {
for(ObjClass* c = getClass(vm, i); c != NULL; c = c->superCls) {
if(c == cls) {
return true;
}
}
return false;
}
#endif
| 2.125 | 2 |
2024-11-18T22:23:05.325810+00:00 | 2013-06-11T10:58:43 | ba33761b1117a92486a2fd2316fc95df0962a658 | {
"blob_id": "ba33761b1117a92486a2fd2316fc95df0962a658",
"branch_name": "refs/heads/master",
"committer_date": "2013-06-11T10:58:43",
"content_id": "02a176d6994d8244d370d5c359f96fc62adb5051",
"detected_licenses": [
"Apache-2.0",
"Zlib"
],
"directory_id": "e9c0b619c425a96bd71f5c560fd4f2ab126da4b5",
"extension": "c",
"filename": "test_server.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 3176219,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 12273,
"license": "Apache-2.0,Zlib",
"license_type": "permissive",
"path": "/test/server/test_server.c",
"provenance": "stackv2-0099.json.gz:2765",
"repo_name": "coapp-packages/serf",
"revision_date": "2013-06-11T10:58:43",
"revision_id": "95d89583b75091549569e18e2ae5cfd352e2656f",
"snapshot_id": "f707ee4f1bd4b0e3d20a67405464f7a334abb263",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/coapp-packages/serf/95d89583b75091549569e18e2ae5cfd352e2656f/test/server/test_server.c",
"visit_date": "2021-01-23T08:04:32.031378"
} | stackv2 | /* Copyright 2011 Justin Erenkrantz and Greg Stein
*
* 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 "apr.h"
#include "apr_pools.h"
#include <apr_poll.h>
#include <apr_version.h>
#include <stdlib.h>
#include "serf.h"
#include "test_server.h"
/* Cleanup callback for a server. */
static apr_status_t cleanup_server(void *baton)
{
serv_ctx_t *servctx = baton;
apr_status_t status;
status = apr_socket_close(servctx->serv_sock);
if (servctx->client_sock) {
apr_socket_close(servctx->client_sock);
}
return status;
}
/* Replay support functions */
static void next_message(serv_ctx_t *servctx)
{
servctx->cur_message++;
}
static void next_action(serv_ctx_t *servctx)
{
servctx->cur_action++;
servctx->action_buf_pos = 0;
}
static apr_status_t
socket_write(serv_ctx_t *serv_ctx, const char *data,
apr_size_t *len)
{
return apr_socket_send(serv_ctx->client_sock, data, len);
}
static apr_status_t
socket_read(serv_ctx_t *serv_ctx, char *data,
apr_size_t *len)
{
return apr_socket_recv(serv_ctx->client_sock, data, len);
}
/* Verify received requests and take the necessary actions
(return a response, kill the connection ...) */
static apr_status_t replay(serv_ctx_t *servctx,
apr_int16_t rtnevents,
apr_pool_t *pool)
{
apr_status_t status = APR_SUCCESS;
test_server_action_t *action;
if (rtnevents & APR_POLLIN) {
if (servctx->message_list == NULL) {
/* we're not expecting any requests to reach this server! */
serf__log(TEST_VERBOSE, __FILE__,
"Received request where none was expected.\n");
return SERF_ERROR_ISSUE_IN_TESTSUITE;
}
if (servctx->cur_action >= servctx->action_count) {
char buf[128];
apr_size_t len = sizeof(buf);
status = servctx->read(servctx, buf, &len);
if (! APR_STATUS_IS_EAGAIN(status)) {
/* we're out of actions! */
serf__log(TEST_VERBOSE, __FILE__,
"Received more requests than expected.\n");
return SERF_ERROR_ISSUE_IN_TESTSUITE;
}
return status;
}
action = &servctx->action_list[servctx->cur_action];
serf__log(TEST_VERBOSE, __FILE__,
"Replaying action %d, kind: %d.\n", servctx->cur_action,
action->kind);
/* Read the remaining data from the client and kill the socket. */
if (action->kind == SERVER_IGNORE_AND_KILL_CONNECTION) {
char buf[128];
apr_size_t len = sizeof(buf);
status = servctx->read(servctx, buf, &len);
if (status == APR_EOF) {
serf__log(TEST_VERBOSE, __FILE__,
"Killing this connection.\n");
apr_socket_close(servctx->client_sock);
servctx->client_sock = NULL;
next_action(servctx);
return APR_SUCCESS;
}
return status;
}
else if (action->kind == SERVER_RECV ||
(action->kind == SERVER_RESPOND &&
servctx->outstanding_responses == 0)) {
apr_size_t msg_len, len;
char buf[128];
test_server_message_t *message;
message = &servctx->message_list[servctx->cur_message];
msg_len = strlen(message->text);
do
{
len = msg_len - servctx->message_buf_pos;
if (len > sizeof(buf))
len = sizeof(buf);
status = servctx->read(servctx, buf, &len);
if (SERF_BUCKET_READ_ERROR(status))
return status;
if (servctx->options & TEST_SERVER_DUMP)
fwrite(buf, len, 1, stdout);
if (strncmp(buf,
message->text + servctx->message_buf_pos,
len) != 0) {
/* ## TODO: Better diagnostics. */
printf("Expected: (\n");
fwrite(message->text + servctx->message_buf_pos, len, 1,
stdout);
printf(")\n");
printf("Actual: (\n");
fwrite(buf, len, 1, stdout);
printf(")\n");
return SERF_ERROR_ISSUE_IN_TESTSUITE;
}
servctx->message_buf_pos += len;
if (servctx->message_buf_pos >= msg_len) {
next_message(servctx);
servctx->message_buf_pos -= msg_len;
if (action->kind == SERVER_RESPOND)
servctx->outstanding_responses++;
if (action->kind == SERVER_RECV)
next_action(servctx);
break;
}
} while (!status);
}
}
if (rtnevents & APR_POLLOUT) {
action = &servctx->action_list[servctx->cur_action];
serf__log(TEST_VERBOSE, __FILE__,
"Replaying action %d, kind: %d.\n", servctx->cur_action,
action->kind);
if (action->kind == SERVER_RESPOND && servctx->outstanding_responses) {
apr_size_t msg_len;
apr_size_t len;
msg_len = strlen(action->text);
len = msg_len - servctx->action_buf_pos;
status = servctx->send(servctx,
action->text + servctx->action_buf_pos,
&len);
if (status != APR_SUCCESS)
return status;
if (servctx->options & TEST_SERVER_DUMP)
fwrite(action->text + servctx->action_buf_pos, len, 1, stdout);
servctx->action_buf_pos += len;
if (servctx->action_buf_pos >= msg_len) {
next_action(servctx);
servctx->outstanding_responses--;
}
}
else if (action->kind == SERVER_KILL_CONNECTION ||
action->kind == SERVER_IGNORE_AND_KILL_CONNECTION) {
serf__log(TEST_VERBOSE, __FILE__,
"Killing this connection.\n");
apr_socket_close(servctx->client_sock);
servctx->client_sock = NULL;
next_action(servctx);
}
}
else if (rtnevents & APR_POLLIN) {
/* ignore */
}
else {
printf("Unknown rtnevents: %d\n", rtnevents);
abort();
}
return status;
}
apr_status_t run_test_server(serv_ctx_t *servctx,
apr_short_interval_time_t duration,
apr_pool_t *pool)
{
apr_status_t status;
apr_pollset_t *pollset;
apr_int32_t num;
const apr_pollfd_t *desc;
/* create a new pollset */
#ifdef BROKEN_WSAPOLL
status = apr_pollset_create_ex(&pollset, 32, pool, 0,
APR_POLLSET_SELECT);
#else
status = apr_pollset_create(&pollset, 32, pool, 0);
#endif
if (status != APR_SUCCESS)
return status;
/* Don't accept new connection while processing client connection. At
least for present time.*/
if (servctx->client_sock) {
apr_pollfd_t pfd = { 0 };
pfd.desc_type = APR_POLL_SOCKET;
pfd.desc.s = servctx->client_sock;
pfd.reqevents = APR_POLLIN | APR_POLLOUT;
status = apr_pollset_add(pollset, &pfd);
if (status != APR_SUCCESS)
goto cleanup;
}
else {
apr_pollfd_t pfd = { 0 };
pfd.desc_type = APR_POLL_SOCKET;
pfd.desc.s = servctx->serv_sock;
pfd.reqevents = APR_POLLIN;
status = apr_pollset_add(pollset, &pfd);
if (status != APR_SUCCESS)
goto cleanup;
}
status = apr_pollset_poll(pollset, APR_USEC_PER_SEC >> 1, &num, &desc);
if (status != APR_SUCCESS)
goto cleanup;
while (num--) {
if (desc->desc.s == servctx->serv_sock) {
status = apr_socket_accept(&servctx->client_sock, servctx->serv_sock,
servctx->pool);
if (status != APR_SUCCESS)
goto cleanup;
apr_socket_opt_set(servctx->client_sock, APR_SO_NONBLOCK, 1);
apr_socket_timeout_set(servctx->client_sock, 0);
status = APR_SUCCESS;
goto cleanup;
}
if (desc->desc.s == servctx->client_sock) {
if (servctx->handshake) {
status = servctx->handshake(servctx);
}
if (status)
goto cleanup;
/* Replay data to socket. */
status = replay(servctx, desc->rtnevents, pool);
if (APR_STATUS_IS_EOF(status)) {
apr_socket_close(servctx->client_sock);
servctx->client_sock = NULL;
}
else if (APR_STATUS_IS_EAGAIN(status)) {
status = APR_SUCCESS;
}
else if (status != APR_SUCCESS) {
/* Real error. */
goto cleanup;
}
}
desc++;
}
cleanup:
apr_pollset_destroy(pollset);
return status;
}
/* Setup the context needed to start a TCP server on adress.
message_list is a list of expected requests.
action_list is the list of responses to be returned in order.
*/
void setup_test_server(serv_ctx_t **servctx_p,
apr_sockaddr_t *address,
test_server_message_t *message_list,
apr_size_t message_count,
test_server_action_t *action_list,
apr_size_t action_count,
apr_int32_t options,
apr_pool_t *pool)
{
serv_ctx_t *servctx;
servctx = apr_pcalloc(pool, sizeof(*servctx));
apr_pool_cleanup_register(pool, servctx,
cleanup_server,
apr_pool_cleanup_null);
*servctx_p = servctx;
servctx->serv_addr = address;
servctx->options = options;
servctx->pool = pool;
servctx->message_list = message_list;
servctx->message_count = message_count;
servctx->action_list = action_list;
servctx->action_count = action_count;
/* Start replay from first action. */
servctx->cur_action = 0;
servctx->action_buf_pos = 0;
servctx->outstanding_responses = 0;
servctx->read = socket_read;
servctx->send = socket_write;
*servctx_p = servctx;
}
apr_status_t start_test_server(serv_ctx_t *servctx)
{
apr_status_t status;
apr_socket_t *serv_sock;
/* create server socket */
#if APR_VERSION_AT_LEAST(1, 0, 0)
status = apr_socket_create(&serv_sock, servctx->serv_addr->family,
SOCK_STREAM, 0,
servctx->pool);
#else
status = apr_socket_create(&serv_sock, servctx->serv_addr->family,
SOCK_STREAM,
servctx->pool);
#endif
if (status != APR_SUCCESS)
return status;
apr_socket_opt_set(serv_sock, APR_SO_NONBLOCK, 1);
apr_socket_timeout_set(serv_sock, 0);
apr_socket_opt_set(serv_sock, APR_SO_REUSEADDR, 1);
status = apr_socket_bind(serv_sock, servctx->serv_addr);
if (status != APR_SUCCESS)
return status;
/* listen for clients */
status = apr_socket_listen(serv_sock, SOMAXCONN);
if (status != APR_SUCCESS)
return status;
servctx->serv_sock = serv_sock;
servctx->client_sock = NULL;
return APR_SUCCESS;
}
| 2.328125 | 2 |
2024-11-18T22:23:05.547639+00:00 | 2023-07-05T03:22:19 | cd25f10e81ca262e6ad8707828559117fa9decd5 | {
"blob_id": "cd25f10e81ca262e6ad8707828559117fa9decd5",
"branch_name": "refs/heads/master",
"committer_date": "2023-07-05T03:22:19",
"content_id": "83cbe658e1edb4a0ec2de01a8864e052887c4c4b",
"detected_licenses": [
"MIT"
],
"directory_id": "1934dc2bbe2cdb7b7fd553ff6a81d03f03b3fd58",
"extension": "c",
"filename": "parse_hex4.c",
"fork_events_count": 3675,
"gha_created_at": "2016-03-19T18:22:54",
"gha_event_created_at": "2023-09-14T19:07:14",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 54280778,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3434,
"license": "MIT",
"license_type": "permissive",
"path": "/tests/parse_hex4.c",
"provenance": "stackv2-0099.json.gz:3024",
"repo_name": "DaveGamble/cJSON",
"revision_date": "2023-07-05T03:22:19",
"revision_id": "cb8693b058ba302f4829ec6d03f609ac6f848546",
"snapshot_id": "9ca71bd55f9fde294cd3a2412a95b534ad14378f",
"src_encoding": "UTF-8",
"star_events_count": 9900,
"url": "https://raw.githubusercontent.com/DaveGamble/cJSON/cb8693b058ba302f4829ec6d03f609ac6f848546/tests/parse_hex4.c",
"visit_date": "2023-08-23T09:39:54.151473"
} | stackv2 | /*
Copyright (c) 2009-2017 Dave Gamble and cJSON contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "unity/examples/unity_config.h"
#include "unity/src/unity.h"
#include "common.h"
static void parse_hex4_should_parse_all_combinations(void)
{
unsigned int number = 0;
unsigned char digits_lower[6];
unsigned char digits_upper[6];
/* test all combinations */
for (number = 0; number <= 0xFFFF; number++)
{
TEST_ASSERT_EQUAL_INT_MESSAGE(4, sprintf((char*)digits_lower, "%.4x", number), "sprintf failed.");
TEST_ASSERT_EQUAL_INT_MESSAGE(4, sprintf((char*)digits_upper, "%.4X", number), "sprintf failed.");
TEST_ASSERT_EQUAL_INT_MESSAGE(number, parse_hex4(digits_lower), "Failed to parse lowercase digits.");
TEST_ASSERT_EQUAL_INT_MESSAGE(number, parse_hex4(digits_upper), "Failed to parse uppercase digits.");
}
}
static void parse_hex4_should_parse_mixed_case(void)
{
TEST_ASSERT_EQUAL_INT(0xBEEF, parse_hex4((const unsigned char*)"beef"));
TEST_ASSERT_EQUAL_INT(0xBEEF, parse_hex4((const unsigned char*)"beeF"));
TEST_ASSERT_EQUAL_INT(0xBEEF, parse_hex4((const unsigned char*)"beEf"));
TEST_ASSERT_EQUAL_INT(0xBEEF, parse_hex4((const unsigned char*)"beEF"));
TEST_ASSERT_EQUAL_INT(0xBEEF, parse_hex4((const unsigned char*)"bEef"));
TEST_ASSERT_EQUAL_INT(0xBEEF, parse_hex4((const unsigned char*)"bEeF"));
TEST_ASSERT_EQUAL_INT(0xBEEF, parse_hex4((const unsigned char*)"bEEf"));
TEST_ASSERT_EQUAL_INT(0xBEEF, parse_hex4((const unsigned char*)"bEEF"));
TEST_ASSERT_EQUAL_INT(0xBEEF, parse_hex4((const unsigned char*)"Beef"));
TEST_ASSERT_EQUAL_INT(0xBEEF, parse_hex4((const unsigned char*)"BeeF"));
TEST_ASSERT_EQUAL_INT(0xBEEF, parse_hex4((const unsigned char*)"BeEf"));
TEST_ASSERT_EQUAL_INT(0xBEEF, parse_hex4((const unsigned char*)"BeEF"));
TEST_ASSERT_EQUAL_INT(0xBEEF, parse_hex4((const unsigned char*)"BEef"));
TEST_ASSERT_EQUAL_INT(0xBEEF, parse_hex4((const unsigned char*)"BEeF"));
TEST_ASSERT_EQUAL_INT(0xBEEF, parse_hex4((const unsigned char*)"BEEf"));
TEST_ASSERT_EQUAL_INT(0xBEEF, parse_hex4((const unsigned char*)"BEEF"));
}
int CJSON_CDECL main(void)
{
UNITY_BEGIN();
RUN_TEST(parse_hex4_should_parse_all_combinations);
RUN_TEST(parse_hex4_should_parse_mixed_case);
return UNITY_END();
}
| 2.0625 | 2 |
2024-11-18T22:23:06.404620+00:00 | 2021-11-22T16:39:51 | 37c24e6c6aab6dd608d1054d9d69aac4ba0f3f39 | {
"blob_id": "37c24e6c6aab6dd608d1054d9d69aac4ba0f3f39",
"branch_name": "refs/heads/main",
"committer_date": "2021-11-22T16:39:51",
"content_id": "8752d08c635e048891a2fcf7eec78729076cf25a",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "062b8d08a7f8f0e96fcd0b3380da0527d0f00979",
"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": 6066,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/sw/main.c",
"provenance": "stackv2-0099.json.gz:3413",
"repo_name": "kola-hash/neoTRNG",
"revision_date": "2021-11-22T16:39:51",
"revision_id": "838298b40171a6832673fdf1b60454eaec48ff0e",
"snapshot_id": "e1769ef1171de8c618f5001e0884c1cb70b1b029",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/kola-hash/neoTRNG/838298b40171a6832673fdf1b60454eaec48ff0e/sw/main.c",
"visit_date": "2023-09-06T06:52:45.772887"
} | stackv2 | // #################################################################################################
// # << neoTRNG Test (TRNG Peripheral of the NEORV32 RISC-V Processor) #
// # ********************************************************************************************* #
// # NEORV32 HQ: https://github.com/stnolting/neorv32 #
// # ********************************************************************************************* #
// # BSD 3-Clause License #
// # #
// # Copyright (c) 2021, Stephan Nolting. All rights reserved. #
// # #
// # Redistribution and use in source and binary forms, with or without modification, are #
// # permitted provided that the following conditions are met: #
// # #
// # 1. Redistributions of source code must retain the above copyright notice, this list of #
// # conditions and the following disclaimer. #
// # #
// # 2. Redistributions in binary form must reproduce the above copyright notice, this list of #
// # conditions and the following disclaimer in the documentation and/or other materials #
// # provided with the distribution. #
// # #
// # 3. Neither the name of the copyright holder nor the names of its contributors may be used to #
// # endorse or promote products derived from this software without specific prior written #
// # permission. #
// # #
// # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS #
// # OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF #
// # MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE #
// # COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, #
// # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE #
// # GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED #
// # AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING #
// # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED #
// # OF THE POSSIBILITY OF SUCH DAMAGE. #
// # ********************************************************************************************* #
// # neoTRNG - https://github.com/stnolting/neoTRNG (c) Stephan Nolting #
// #################################################################################################
#include <neorv32.h>
/**********************************************************************//**
* User configuration
**************************************************************************/
#define BAUD_RATE_STD 19200 // initial UART baud rate
#define BAUD_RATE_FAST 115200 // fast UART baud rate
/**********************************************************************//**
* Prototypes
**************************************************************************/
uint8_t get_rnd(void);
uint32_t average_access_time(void);
/**********************************************************************//**
* Main function
**************************************************************************/
int main() {
// initialize the neorv32 runtime environment
// this will take care of handling all CPU traps (interrupts and exceptions)
neorv32_rte_setup();
// setup UART0 at default baud rate, no parity bits, ho hw flow control
neorv32_uart0_setup(BAUD_RATE_STD, PARITY_NONE, FLOW_CONTROL_RTSCTS);
neorv32_uart0_printf("neoTRNG TEST\n");
neorv32_uart0_printf("build: "__DATE__" "__TIME__"\n");
// check if TRNG unit is implemented at all
if (neorv32_trng_available() == 0) {
neorv32_uart0_printf("No TRNG implemented.");
return 1;
}
neorv32_trng_enable(); // enable TRNG
neorv32_uart0_printf("Average TRNG system access time: %u cycles @ %uMHz\n", average_access_time(), NEORV32_SYSINFO.CLK);
neorv32_uart0_printf("Going to %u Baud and starting output in 20s.\n", (uint32_t)BAUD_RATE_FAST);
while (neorv32_uart0_tx_busy());
neorv32_uart0_setup(BAUD_RATE_FAST, PARITY_NONE, FLOW_CONTROL_RTSCTS);
neorv32_cpu_delay_ms(20000); // use this time to "warm-up" TRNG
while(1) {
neorv32_uart0_putc((char)get_rnd());
}
return 0;
}
/**********************************************************************//**
* Get raw random byte
**************************************************************************/
uint8_t get_rnd(void) {
uint8_t raw;
while(neorv32_trng_get(&raw));
return raw;
}
/**********************************************************************//**
* Get average number of clock cycles required to get random byte
**************************************************************************/
uint32_t average_access_time(void) {
int i;
const uint32_t runs = 4096;
uint8_t raw;
neorv32_cpu_csr_write(CSR_MCYCLE, 0);
for (i=0; i<runs; i++) {
while(neorv32_trng_get(&raw));
}
return neorv32_cpu_csr_read(CSR_MCYCLE)/runs;
}
| 2.078125 | 2 |
2024-11-18T22:23:06.839149+00:00 | 2012-11-14T00:01:50 | 6a6253aad4902fa782504b9c28629e8d9e3d215d | {
"blob_id": "6a6253aad4902fa782504b9c28629e8d9e3d215d",
"branch_name": "refs/heads/master",
"committer_date": "2012-11-14T00:01:50",
"content_id": "3ac42eda856924887c9dc5b7d0f3dfb7aa377171",
"detected_licenses": [
"MIT"
],
"directory_id": "4a4ecb68a54cdc54504382c83ba98fae7b2ec37b",
"extension": "c",
"filename": "filedump.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": 481,
"license": "MIT",
"license_type": "permissive",
"path": "/src/testutil/filedump.c",
"provenance": "stackv2-0099.json.gz:3927",
"repo_name": "MichaelABarger/ParticleSort",
"revision_date": "2012-11-14T00:01:50",
"revision_id": "31582820b63213dfa4b599b6a3005c0703d570f7",
"snapshot_id": "057e812752a2afecf3dc5535d0254a9b8ec1204b",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/MichaelABarger/ParticleSort/31582820b63213dfa4b599b6a3005c0703d570f7/src/testutil/filedump.c",
"visit_date": "2021-01-10T19:59:18.372850"
} | stackv2 | #include <assert.h>
#include <stdio.h>
int main(int argc, char **argv)
{
unsigned int c1, c2, c3, c4;
int i = 0;
while (1) {
c1 = getchar();
if (feof(stdin))
break;
c2 = getchar();
if (feof(stdin))
break;
c3 = getchar();
if (feof(stdin))
break;
c4 = getchar();
if (feof(stdin))
break;
unsigned int word = (c1 << 24) | (c2 << 16) | (c3 << 8) | c4;
printf(" %8u, ", word);
if ((++i & 7) == 0)
printf("\n");
}
printf("\n");
return 0;
}
| 2.859375 | 3 |
2024-11-18T22:23:06.911501+00:00 | 2019-10-31T05:47:52 | 8569b9d061b4a6b43e5019931832a4e65c1da187 | {
"blob_id": "8569b9d061b4a6b43e5019931832a4e65c1da187",
"branch_name": "refs/heads/develop",
"committer_date": "2019-10-31T05:47:52",
"content_id": "fcba455d08119acea0139d5c091dd9bc91509219",
"detected_licenses": [
"MIT"
],
"directory_id": "2ca42747e43ea1ddb8f5a54f7eaabd89b859c092",
"extension": "h",
"filename": "FontMem.h",
"fork_events_count": 2,
"gha_created_at": "2017-01-20T04:01:54",
"gha_event_created_at": "2019-10-31T05:47:54",
"gha_language": "C++",
"gha_license_id": "MIT",
"github_id": 79523811,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 646,
"license": "MIT",
"license_type": "permissive",
"path": "/Sinhala_Oombi/FontMem.h",
"provenance": "stackv2-0099.json.gz:4056",
"repo_name": "hamparawa/SinhalaOombi",
"revision_date": "2019-10-31T05:47:52",
"revision_id": "0eb1d50f27cb34d3bbdc5fe669e7c53d1abc295c",
"snapshot_id": "c2c1c3abe7cddbe74f29e352da2f917f4747207c",
"src_encoding": "UTF-8",
"star_events_count": 5,
"url": "https://raw.githubusercontent.com/hamparawa/SinhalaOombi/0eb1d50f27cb34d3bbdc5fe669e7c53d1abc295c/Sinhala_Oombi/FontMem.h",
"visit_date": "2021-01-11T18:15:13.465182"
} | stackv2 | // to use AddFontMemResourceEx in VC++ 6
// hamparawa@gmail.com
#ifndef FONTMEM_H
#define FONTMEM_H
#include <windows.h>
typedef int (__stdcall *FONTPROC)(PVOID, DWORD, PVOID, DWORD *);
inline int __stdcall AddFontMemResourceEx_dyn(PVOID pbFont, DWORD cbFont, PVOID pdv, DWORD *pcFonts )
{
FONTPROC pTrans;
HINSTANCE hInstLib;
BOOL retVal = true;
hInstLib = LoadLibrary("gdi32.dll");
if (hInstLib)
{
pTrans = (FONTPROC) (GetProcAddress(hInstLib, "AddFontMemResourceEx"));
if (pTrans)
{
retVal = (pTrans)(pbFont, cbFont, pdv, pcFonts);
}
FreeLibrary(hInstLib);
}
else
return false;
return retVal;
}
#endif //FONTMEM_H
| 2 | 2 |
2024-11-18T22:23:09.496694+00:00 | 2021-10-27T08:27:13 | 834fcc4294932b5869bb4a2032f7dc67ec5fb62d | {
"blob_id": "834fcc4294932b5869bb4a2032f7dc67ec5fb62d",
"branch_name": "refs/heads/master",
"committer_date": "2021-10-27T08:27:13",
"content_id": "c83e0db45a55ecf503310d33451132dabce0bf98",
"detected_licenses": [
"MIT",
"Unlicense"
],
"directory_id": "6eeda417c62f8c35dc8a83dd3adf06a8655f04da",
"extension": "c",
"filename": "11.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": 1302,
"license": "MIT,Unlicense",
"license_type": "permissive",
"path": "/Practical 2/11.c",
"provenance": "stackv2-0099.json.gz:5220",
"repo_name": "Anju787/Datastructures",
"revision_date": "2021-10-27T08:27:13",
"revision_id": "7973a48a60afd99cbb6d94bf2b65f61d963cb183",
"snapshot_id": "cf2784be56803284351715902cfae7f4f326b3a8",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Anju787/Datastructures/7973a48a60afd99cbb6d94bf2b65f61d963cb183/Practical 2/11.c",
"visit_date": "2023-08-24T01:41:31.122390"
} | stackv2 | #include <stdio.h>
#include <string.h>
struct STUDENT {
char name[50];
int rollNo,m1,m2,m3;
float percentage;
};
void result_name(struct STUDENT arr[],int size,char name[50]){
int i=0;
int result=-1;
while(result!=0){
result = strcmp(arr[i].name,name);
i++;
if (i > size){
printf("Name not found\n");
return;
}
}
printf("Percentage of %s\b is %.2f\n",name,arr[i-1].percentage);
}
int main(){
printf("Program written by enrollment number 200420107012\n");
int n,i;
char name[50];
printf("Enter Number of students: ");
scanf("%d",&n);
struct STUDENT student[n];
for(i=0;i<n;i++){
printf("Enter name of student: ");
getchar();
fgets(student[i].name,50,stdin);
printf("Enter student rollNo: ");
scanf("%d",&student[i].rollNo);
printf("Enter marks m1 m2 m3 of student(out of 70): ");
scanf("%d %d %d",&student[i].m1,&student[i].m2,&student[i].m3);
student[i].percentage = ((student[i].m1+student[i].m2+student[i].m3)*100)/210;
}
printf("Enter name of student: ");
getchar();
fgets(name,50,stdin);
// printf("%s",name);
result_name(student,n,name);
return 0;
}
| 3.28125 | 3 |
2024-11-18T20:22:50.962678+00:00 | 2023-08-22T19:25:15 | 0c248923648ccc48f8df9c8c14c7682771ef0555 | {
"blob_id": "0c248923648ccc48f8df9c8c14c7682771ef0555",
"branch_name": "refs/heads/main",
"committer_date": "2023-08-22T19:25:15",
"content_id": "98a1a4fd4ff958c15a1d474daea85206504f00f6",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "6bae10c29fef626e72f8f9ea684fd0be6e1c210b",
"extension": "c",
"filename": "mysql-connector-c-test.c",
"fork_events_count": 443,
"gha_created_at": "2019-07-24T17:46:25",
"gha_event_created_at": "2023-09-14T21:46:16",
"gha_language": "Go",
"gha_license_id": "Apache-2.0",
"github_id": 198683574,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4925,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/integration-tests/mysql-client-tests/c/mysql-connector-c-test.c",
"provenance": "stackv2-0100.json.gz:270071",
"repo_name": "dolthub/dolt",
"revision_date": "2023-08-22T19:25:15",
"revision_id": "897dcd59d4eaca06c06b97aef81274d2998828e2",
"snapshot_id": "63f8db647f2ac5c8d7ab14a6ee2472d7a02125f7",
"src_encoding": "UTF-8",
"star_events_count": 13889,
"url": "https://raw.githubusercontent.com/dolthub/dolt/897dcd59d4eaca06c06b97aef81274d2998828e2/integration-tests/mysql-client-tests/c/mysql-connector-c-test.c",
"visit_date": "2023-08-22T19:42:16.016445"
} | stackv2 | #include <stdio.h>
#include <string.h>
#include <memory.h>
#include <mysql.h>
#define QUERIES_SIZE 14
char *queries[QUERIES_SIZE] =
{
"create table test (pk int, `value` int, primary key(pk))",
"describe test",
"select * from test",
"insert into test (pk, `value`) values (0,0)",
"select * from test",
"call dolt_add('-A');",
"call dolt_commit('-m', 'my commit')",
"select COUNT(*) FROM dolt_log",
"call dolt_checkout('-b', 'mybranch')",
"insert into test (pk, `value`) values (10,10)",
"call dolt_commit('-a', '-m', 'my commit2')",
"call dolt_checkout('main')",
"call dolt_merge('mybranch')",
"select COUNT(*) FROM dolt_log",
};
typedef struct statement_t {
char *query;
MYSQL_BIND bind[10];
int expect_prepare_error;
int expect_exec_error;
int expect_result_metadata;
} statement;
void test_statement(MYSQL *con, statement *stmt) {
MYSQL_STMT *mstmt = mysql_stmt_init(con);
if (!mstmt) {
fprintf(stderr, "failed to init stmt: %s\n", mysql_error(con));
exit(1);
}
if ( mysql_stmt_prepare(mstmt, stmt->query, strlen(stmt->query)) ) {
if ( !stmt->expect_prepare_error) {
fprintf(stderr, "failed to prepare stmt: %s: %s\n", stmt->query, mysql_stmt_error(mstmt));
exit(1);
} else {
goto close;
}
}
if ( mysql_stmt_bind_param(mstmt, stmt->bind) ) {
fprintf(stderr, "failed to bind stmt: %s: %s\n", stmt->query, mysql_stmt_error(mstmt));
exit(1);
}
MYSQL_RES *metadata = mysql_stmt_result_metadata(mstmt);
if (stmt->expect_result_metadata && metadata == NULL) {
fprintf(stderr, "result metadata was unexpectedly NULL: %s\n", stmt->query);
exit(1);
} else if (!stmt->expect_result_metadata && metadata != NULL) {
fprintf(stderr, "result metadata was unexpectedly non-NULL: %s\n", stmt->query);
exit(1);
}
if ( mysql_stmt_execute(mstmt) ) {
if ( !stmt->expect_exec_error) {
fprintf(stderr, "failed to execute stmt: %s: %s\n", stmt->query, mysql_stmt_error(mstmt));
exit(1);
}
}
// TODO: Add test for mysql_stmt_store_result when supported
close:
if ( mysql_stmt_close(mstmt) ) {
fprintf(stderr, "failed to close stmt: %s: %s\n", stmt->query, mysql_error(con));
exit(1);
}
}
statement LAST_STATEMENT = {
};
int main(int argc, char **argv) {
char* user = argv[1];
int port = atoi(argv[2]);
char* db = argv[3];
MYSQL *con = mysql_init(NULL);
if ( con == NULL ) {
fprintf(stderr, "%s\n", mysql_error(con));
exit(1);
}
if ( mysql_real_connect(con,
"127.0.0.1",
user,
"",
db,
port,
NULL,
0 ) == NULL) {
fprintf(stderr, "%s\n", mysql_error(con));
mysql_close(con);
exit(1);
}
for ( int i = 0; i < QUERIES_SIZE; i++ ) {
if ( mysql_query(con, queries[i]) ) {
printf("QUERY FAILED: %s\n", queries[i]);
fprintf(stderr, "%s\n", mysql_error(con));
mysql_close(con);
exit(1);
} else {
// Not checking validity of results for now
MYSQL_RES* result = mysql_use_result(con);
mysql_free_result(result);
}
}
int pk = 1;
int value = 12;
unsigned long string_len = 16;
statement statements[] = {
{
.query = "select * from test where pk = ?",
.bind = {
[0] = {
.buffer_type = MYSQL_TYPE_LONG,
.buffer = (void *)(&pk),
.buffer_length = sizeof(pk),
},
},
.expect_result_metadata = 1,
},
{
.query = "select * from test where pk = ?",
.bind = {
[0] = {
.buffer_type = MYSQL_TYPE_LONG,
.buffer = (void *)(&pk),
.buffer_length = sizeof(pk),
.is_unsigned = 1,
},
},
.expect_result_metadata = 1,
},
{
.query = "insert into test values (?, ?)",
.bind = {
[0] = {
.buffer_type = MYSQL_TYPE_LONG,
.buffer = (void *)(&pk),
.buffer_length = sizeof(pk),
},
[1] = {
.buffer_type = MYSQL_TYPE_LONG,
.buffer = (void *)(&value),
.buffer_length = sizeof(value),
},
},
.expect_result_metadata = 0,
},
{
.query = "update test set `value` = ?",
.bind = {
[0] = {
.buffer_type = MYSQL_TYPE_STRING,
.buffer = (void *)"test string here",
.buffer_length = string_len,
.length = &string_len,
},
},
.expect_exec_error = 1,
.expect_result_metadata = 0,
},
{
.query = "select * from test SYNTAX ERROR where pk = ?",
.bind = {
[0] = {
.buffer_type = MYSQL_TYPE_LONG,
.buffer = (void *)(&pk),
.buffer_length = sizeof(pk),
},
},
.expect_prepare_error = 1,
},
LAST_STATEMENT,
};
for (int i = 0; statements[i].query; i++) {
test_statement(con, &statements[i]);
}
mysql_close(con);
return 0;
}
| 2.3125 | 2 |
2024-11-18T20:22:51.087912+00:00 | 2017-08-18T09:56:18 | fa47dd4fc469d7697528dc9a7b40d7318e7ed68a | {
"blob_id": "fa47dd4fc469d7697528dc9a7b40d7318e7ed68a",
"branch_name": "refs/heads/master",
"committer_date": "2017-08-18T09:56:18",
"content_id": "f23167415f94bbe3740d2c3d36b73a7b2cf1bc54",
"detected_licenses": [
"MIT"
],
"directory_id": "a88e0b422daa713dfa9158f73843539efb757e43",
"extension": "c",
"filename": "walletrpc.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 99806571,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 9677,
"license": "MIT",
"license_type": "permissive",
"path": "/wallet/walletrpc.c",
"provenance": "stackv2-0100.json.gz:270199",
"repo_name": "jl777/chipsln",
"revision_date": "2017-08-18T09:56:18",
"revision_id": "5e2cec1443ccd0b37ffdfc4d6209413182b10a8b",
"snapshot_id": "f098351eeb7963ca8700e32d3379522471f9fa34",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/jl777/chipsln/5e2cec1443ccd0b37ffdfc4d6209413182b10a8b/wallet/walletrpc.c",
"visit_date": "2021-01-15T19:06:18.437247"
} | stackv2 | #include <bitcoin/address.h>
#include <bitcoin/base58.h>
#include <bitcoin/script.h>
#include <ccan/tal/str/str.h>
#include <daemon/bitcoind.h>
#include <daemon/chaintopology.h>
#include <daemon/jsonrpc.h>
#include <errno.h>
#include <lightningd/hsm/gen_hsm_wire.h>
#include <lightningd/hsm_control.h>
#include <lightningd/key_derive.h>
#include <lightningd/lightningd.h>
#include <lightningd/status.h>
#include <lightningd/subd.h>
#include <lightningd/utxo.h>
#include <lightningd/withdraw_tx.h>
#include <permute_tx.h>
#include <wally_bip32.h>
#include <wire/wire_sync.h>
struct withdrawal {
u64 amount, changesatoshi;
struct bitcoin_address destination;
const struct utxo **utxos;
u64 change_key_index;
struct command *cmd;
const char *hextx;
};
/**
* wallet_extract_owned_outputs - given a tx, extract all of our outputs
*/
static int wallet_extract_owned_outputs(struct wallet *w,
const struct bitcoin_tx *tx,
u64 *total_satoshi)
{
int num_utxos = 0;
for (size_t output = 0; output < tal_count(tx->output); output++) {
struct utxo *utxo;
u32 index;
bool is_p2sh;
if (!wallet_can_spend(w, tx->output[output].script, &index, &is_p2sh))
continue;
utxo = tal(w, struct utxo);
utxo->keyindex = index;
utxo->is_p2sh = is_p2sh;
utxo->amount = tx->output[output].amount;
utxo->status = output_state_available;
bitcoin_txid(tx, &utxo->txid);
utxo->outnum = output;
if (!wallet_add_utxo(w, utxo, p2sh_wpkh)) {
tal_free(utxo);
return -1;
}
*total_satoshi += utxo->amount;
num_utxos++;
}
return num_utxos;
}
/**
* wallet_withdrawal_broadcast - The tx has been broadcast (or it failed)
*
* This is the final step in the withdrawal. We either successfully
* broadcast the withdrawal transaction or it failed somehow. So we
* report success or a broadcast failure. Upon success we also mark
* the used outputs as spent, and add the change output to our pool of
* available outputs.
*/
static void wallet_withdrawal_broadcast(struct bitcoind *bitcoind,
int exitstatus, const char *msg,
struct withdrawal *withdraw)
{
struct command *cmd = withdraw->cmd;
struct lightningd *ld = ld_from_dstate(withdraw->cmd->dstate);
struct bitcoin_tx *tx;
u64 change_satoshi = 0;
/* Massage output into shape so it doesn't kill the JSON serialization */
char *output = tal_strjoin(cmd, tal_strsplit(cmd, msg, "\n", STR_NO_EMPTY), " ", STR_NO_TRAIL);
if (exitstatus == 0) {
/* Mark used outputs as spent */
wallet_confirm_utxos(ld->wallet, withdraw->utxos);
/* Parse the tx and extract the change output. We
* generated the hex tx, so this should always work */
tx = bitcoin_tx_from_hex(withdraw, withdraw->hextx, strlen(withdraw->hextx));
assert(tx != NULL);
wallet_extract_owned_outputs(ld->wallet, tx, &change_satoshi);
assert(change_satoshi == withdraw->changesatoshi);
struct json_result *response = new_json_result(cmd);
json_object_start(response, NULL);
json_add_string(response, "tx", withdraw->hextx);
json_add_string(response, "txid", output);
json_object_end(response);
command_success(cmd, response);
} else {
command_fail(cmd, "Error broadcasting transaction: %s", output);
}
}
/**
* json_withdraw - Entrypoint for the withdrawal flow
*
* A user has requested a withdrawal over the JSON-RPC, parse the
* request, select coins and a change key. Then send the request to
* the HSM to generate the signatures.
*/
static void json_withdraw(struct command *cmd,
const char *buffer, const jsmntok_t *params)
{
struct lightningd *ld = ld_from_dstate(cmd->dstate);
jsmntok_t *desttok, *sattok;
struct withdrawal *withdraw;
bool testnet;
/* FIXME: Read feerate and dustlimit */
u32 feerate_per_kw = 15000;
//u64 dust_limit = 600;
u64 fee_estimate;
struct utxo *utxos;
struct ext_key ext;
struct pubkey changekey;
secp256k1_ecdsa_signature *sigs;
struct bitcoin_tx *tx;
if (!json_get_params(buffer, params,
"destination", &desttok,
"satoshi", &sattok,
NULL)) {
command_fail(cmd, "Need destination and satoshi.");
return;
}
withdraw = tal(cmd, struct withdrawal);
withdraw->cmd = cmd;
if (!json_tok_u64(buffer, sattok, &withdraw->amount)) {
command_fail(cmd, "Invalid satoshis");
return;
}
if (!bitcoin_from_base58(&testnet, &withdraw->destination,
buffer + desttok->start,
desttok->end - desttok->start)) {
command_fail(cmd, "Could not parse destination address");
return;
}
/* Select the coins */
withdraw->utxos = wallet_select_coins(cmd, ld->wallet, withdraw->amount,
feerate_per_kw, &fee_estimate,
&withdraw->changesatoshi);
if (!withdraw->utxos) {
command_fail(cmd, "Not enough funds available");
return;
}
/* FIXME(cdecker) Pull this from the daemon config */
if (withdraw->changesatoshi <= 546)
withdraw->changesatoshi = 0;
withdraw->change_key_index = wallet_get_newindex(ld);
utxos = from_utxoptr_arr(withdraw, withdraw->utxos);
u8 *msg = towire_hsmctl_sign_withdrawal(cmd,
withdraw->amount,
withdraw->changesatoshi,
withdraw->change_key_index,
withdraw->destination.addr.u.u8,
utxos);
tal_free(utxos);
if (!wire_sync_write(ld->hsm_fd, take(msg)))
fatal("Could not write sign_withdrawal to HSM: %s",
strerror(errno));
msg = hsm_sync_read(cmd, ld);
if (!fromwire_hsmctl_sign_withdrawal_reply(withdraw, msg, NULL, &sigs))
fatal("HSM gave bad sign_withdrawal_reply %s",
tal_hex(withdraw, msg));
if (bip32_key_from_parent(ld->bip32_base, withdraw->change_key_index,
BIP32_FLAG_KEY_PUBLIC, &ext) != WALLY_OK) {
command_fail(cmd, "Changekey generation failure");
return;
}
pubkey_from_der(ext.pub_key, sizeof(ext.pub_key), &changekey);
tx = withdraw_tx(withdraw, withdraw->utxos, &withdraw->destination,
withdraw->amount, &changekey, withdraw->changesatoshi,
ld->bip32_base);
if (tal_count(sigs) != tal_count(tx->input))
fatal("HSM gave %zu sigs, needed %zu",
tal_count(sigs), tal_count(tx->input));
/* Create input parts from signatures. */
for (size_t i = 0; i < tal_count(tx->input); i++) {
struct pubkey key;
if (!bip32_pubkey(ld->bip32_base,
&key, withdraw->utxos[i]->keyindex))
fatal("Cannot generate BIP32 key for UTXO %u",
withdraw->utxos[i]->keyindex);
/* P2SH inputs have same witness. */
tx->input[i].witness
= bitcoin_witness_p2wpkh(tx, &sigs[i], &key);
}
/* Now broadcast the transaction */
withdraw->hextx = tal_hex(withdraw, linearize_tx(cmd, tx));
bitcoind_sendrawtx(ld->topology->bitcoind, withdraw->hextx,
wallet_withdrawal_broadcast, withdraw);
}
static const struct json_command withdraw_command = {
"withdraw",
json_withdraw,
"Send {satoshi} to the {destination} address via Bitcoin transaction",
"Returns the withdrawal transaction ID"
};
AUTODATA(json_command, &withdraw_command);
static void json_newaddr(struct command *cmd,const char *buffer, const jsmntok_t *params)
{
struct json_result *response = new_json_result(cmd);
struct lightningd *ld = ld_from_dstate(cmd->dstate);
struct ext_key ext;
struct sha256 h;
struct ripemd160 p2sh;
struct pubkey pubkey;
u8 *redeemscript;
s64 keyidx;
keyidx = wallet_get_newindex(ld);
if (keyidx < 0) {
command_fail(cmd, "Keys exhausted ");
return;
}
if (bip32_key_from_parent(ld->bip32_base, keyidx,
BIP32_FLAG_KEY_PUBLIC, &ext) != WALLY_OK) {
command_fail(cmd, "Keys generation failure");
return;
}
if (!secp256k1_ec_pubkey_parse(secp256k1_ctx, &pubkey.pubkey,
ext.pub_key, sizeof(ext.pub_key))) {
command_fail(cmd, "Key parsing failure");
return;
}
redeemscript = bitcoin_redeem_p2sh_p2wpkh(cmd, &pubkey);
sha256(&h, redeemscript, tal_count(redeemscript));
ripemd160(&p2sh, h.u.u8, sizeof(h));
json_object_start(response, NULL);
json_add_string(response, "address",p2sh_to_base58(cmd, cmd->dstate->testnet, &p2sh));
json_object_end(response);
command_success(cmd, response);
}
static const struct json_command newaddr_command = {
"newaddr",
json_newaddr,
"Get a new address to fund a channel",
"Returns {address} a p2sh address"
};
AUTODATA(json_command, &newaddr_command);
static void json_addfunds(struct command *cmd,const char *buffer, const jsmntok_t *params)
{
struct lightningd *ld = ld_from_dstate(cmd->dstate);
struct json_result *response = new_json_result(cmd);
jsmntok_t *txtok;
struct bitcoin_tx *tx;
size_t txhexlen;
int num_utxos = 0;
u64 total_satoshi = 0;
if (!json_get_params(buffer, params, "tx", &txtok, NULL)) {
command_fail(cmd, "Need tx sending to address from newaddr");
return;
}
txhexlen = txtok->end - txtok->start;
tx = bitcoin_tx_from_hex(cmd, buffer + txtok->start, txhexlen);
if (!tx) {
command_fail(cmd, "'%.*s' is not a valid transaction",
txtok->end - txtok->start,
buffer + txtok->start);
return;
}
/* Find an output we know how to spend. */
num_utxos =
wallet_extract_owned_outputs(ld->wallet, tx, &total_satoshi);
if (num_utxos < 0) {
command_fail(cmd, "Couldnt add outputs to wallet");
return;
} else if (!num_utxos) {
command_fail(cmd, "No usable outputs");
return;
}
json_object_start(response, NULL);
json_add_num(response, "outputs", num_utxos);
json_add_u64(response, "satoshis", total_satoshi);
json_object_end(response);
command_success(cmd, response);
}
static const struct json_command addfunds_command = {
"addfunds",
json_addfunds,
"Add funds for lightningd to spend to create channels, using {tx}",
"Returns how many {outputs} it can use and total {satoshis}"
};
AUTODATA(json_command, &addfunds_command);
| 2.03125 | 2 |
2024-11-18T20:48:29.803725+00:00 | 2023-07-15T20:00:27 | 35b5f640f631aed72f5dd07e1014f8525b1f29ee | {
"blob_id": "35b5f640f631aed72f5dd07e1014f8525b1f29ee",
"branch_name": "refs/heads/master",
"committer_date": "2023-07-15T20:00:27",
"content_id": "200ebf7ed5f6657ea36e9c287744aabeb7af2490",
"detected_licenses": [
"Unlicense"
],
"directory_id": "f82defd467c7b33a1518d2df83a81d06b82dfb33",
"extension": "h",
"filename": "stm32l4_clocks.h",
"fork_events_count": 0,
"gha_created_at": "2020-07-04T10:03:19",
"gha_event_created_at": "2020-07-04T10:03:20",
"gha_language": null,
"gha_license_id": "Unlicense",
"github_id": 277084216,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1337,
"license": "Unlicense",
"license_type": "permissive",
"path": "/tmp116/boot/stm32l4_clocks.h",
"provenance": "stackv2-0102.json.gz:63294",
"repo_name": "yihuoyanyan/stm32",
"revision_date": "2023-07-15T20:00:27",
"revision_id": "1805eed90775f78096a49342abf28ff05f4895f5",
"snapshot_id": "a30d6959c5c86ef87dfa2dc0896fa4399becd553",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/yihuoyanyan/stm32/1805eed90775f78096a49342abf28ff05f4895f5/tmp116/boot/stm32l4_clocks.h",
"visit_date": "2023-07-20T00:31:46.602626"
} | stackv2 | #ifndef __STM32L4xx_CLOCKS
#define __STM32L4xx_CLOCKS
// Oscillator values adaptation
// The value of External High Speed oscillator (HSE)
#if !defined(HSE_VALUE)
#define HSE_VALUE ((uint32_t)16000000U) // Hz
#endif // HSE_VALUE
// The default value of Internal Multiple Speed oscillator (MSI)
// This value is the default MSI range value after reset
#if !defined(MSI_VALUE)
#define MSI_VALUE ((uint32_t)4000000U) // Hz
#endif // MSI_VALUE
// The value of Internal High Speed oscillator (HSI)
#if !defined(HSI_VALUE)
#define HSI_VALUE ((uint32_t)16000000U) // Hz
#endif // HSI_VALUE
// The value of External Low Speed oscillator (LSE)
#if !defined(LSE_VALUE)
#define LSE_VALUE ((uint32_t)32768U) // Hz
#endif // LSE_VALUE
// The value of Internal High Speed oscillator for USB FS/SDMMC/RNG (HSI48)
#if defined(RCC_HSI48_SUPPORT)
#if !defined(HSI48_VALUE)
#define HSI48_VALUE ((uint32_t)48000000U) // Hz
#endif // HSI48_VALUE
#endif // RCC_HSI48_SUPPORT
// Startup timeout for HSE
#if !defined(HSE_STARTUP_TIMEOUT)
#define HSE_STARTUP_TIMEOUT ((uint32_t)5000U)
#endif // HSE_STARTUP_TIMEOUT
// Startup timeout for LSE
#if !defined(LSE_STARTUP_TIMEOUT)
#define LSE_STARTUP_TIMEOUT ((uint32_t)5000U)
#endif // HSE_STARTUP_TIMEOUT
#endif // __STM32L4xx_CLOCKS | 2.25 | 2 |
2024-11-18T20:48:30.135181+00:00 | 2023-02-16T11:27:40 | 5ca1954f353975246eb34d6f2f30a525a40d4e0b | {
"blob_id": "5ca1954f353975246eb34d6f2f30a525a40d4e0b",
"branch_name": "refs/heads/main",
"committer_date": "2023-02-16T14:59:16",
"content_id": "2ba31894891ea235544f10c103c50aca08c667b6",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "e8302c75d770d1608b317d6af5c483bbad6c0493",
"extension": "c",
"filename": "test_module.c",
"fork_events_count": 32,
"gha_created_at": "2016-08-05T22:14:50",
"gha_event_created_at": "2022-04-05T17:14:07",
"gha_language": "C",
"gha_license_id": "Apache-2.0",
"github_id": 65052293,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1045,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/tests/subsys/shell/shell/src/test_module.c",
"provenance": "stackv2-0102.json.gz:63681",
"repo_name": "intel/zephyr",
"revision_date": "2023-02-16T11:27:40",
"revision_id": "06d5bc51b580777079bb0b7e769e4127598ea5ee",
"snapshot_id": "819362089aa44ae378a5558f3b222197aaa811f7",
"src_encoding": "UTF-8",
"star_events_count": 32,
"url": "https://raw.githubusercontent.com/intel/zephyr/06d5bc51b580777079bb0b7e769e4127598ea5ee/tests/subsys/shell/shell/src/test_module.c",
"visit_date": "2023-09-04T00:20:35.217393"
} | stackv2 | /*
* Copyright (c) 2022 Nordic Semiconductor ASA
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <zephyr/shell/shell.h>
static int cmd2_handler(const struct shell *sh, size_t argc, char **argv)
{
ARG_UNUSED(sh);
ARG_UNUSED(argc);
ARG_UNUSED(argv);
return 20;
}
SHELL_SUBCMD_ADD((section_cmd), cmd2, NULL, "help for cmd2", cmd2_handler, 1, 0);
static int sub_cmd1_handler(const struct shell *sh, size_t argc, char **argv)
{
ARG_UNUSED(sh);
ARG_UNUSED(argc);
ARG_UNUSED(argv);
return 11;
}
SHELL_SUBCMD_COND_ADD(1, (section_cmd, cmd1), sub_cmd1, NULL,
"help for sub cmd1", sub_cmd1_handler, 1, 0);
static int sub_cmd2_handler(const struct shell *sh, size_t argc, char **argv)
{
ARG_UNUSED(sh);
ARG_UNUSED(argc);
ARG_UNUSED(argv);
return 12;
}
/* Flag set to 0, command will not be compiled. Add to validate that setting
* flag to 0 does not add command and does not generate any warnings.
*/
SHELL_SUBCMD_COND_ADD(0, (section_cmd, cmd1), sub_cmd2, NULL,
"help for sub cmd2", sub_cmd2_handler, 1, 0);
| 2.109375 | 2 |
2024-11-18T20:48:30.647905+00:00 | 2019-07-29T09:42:07 | 088bd374575591db823c8b79e65bd253ef8c06fc | {
"blob_id": "088bd374575591db823c8b79e65bd253ef8c06fc",
"branch_name": "refs/heads/master",
"committer_date": "2019-07-29T09:42:07",
"content_id": "cbc7bdbe7da552d84689b61f6a82d6c80efdf7c4",
"detected_licenses": [
"MIT"
],
"directory_id": "a1541ec9975c2611a79cdeaf4240442a9ac612d6",
"extension": "c",
"filename": "fake_file.c",
"fork_events_count": 1,
"gha_created_at": "2019-02-11T04:20:56",
"gha_event_created_at": "2019-02-17T08:04:07",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 170067161,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1937,
"license": "MIT",
"license_type": "permissive",
"path": "/test/fake_file.c",
"provenance": "stackv2-0102.json.gz:64198",
"repo_name": "wujianguo/libms",
"revision_date": "2019-07-29T09:42:07",
"revision_id": "2b49ca97669fcce173ff584467ff39de53dfc422",
"snapshot_id": "14b388593818addf15e7ea8177ae8fd997dd33c5",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/wujianguo/libms/2b49ca97669fcce173ff584467ff39de53dfc422/test/fake_file.c",
"visit_date": "2020-04-22T02:54:15.992922"
} | stackv2 | //
// fake_file.c
// libms
//
// Created by Jianguo Wu on 2018/12/23.
// Copyright © 2018 wujianguo. All rights reserved.
//
#include "fake_file.h"
static void ms_cs_md5(char buf[33], ...) {
unsigned char hash[16];
const uint8_t *msgs[20], *p;
size_t msg_lens[20];
size_t num_msgs = 0;
va_list ap;
va_start(ap, buf);
while ((p = va_arg(ap, const unsigned char *) ) != NULL) {
msgs[num_msgs] = p;
msg_lens[num_msgs] = va_arg(ap, size_t);
num_msgs++;
}
va_end(ap);
mg_hash_md5_v(num_msgs, msgs, msg_lens, hash);
cs_to_hex(buf, hash, sizeof(hash));
}
struct ms_fake_file *open_fake_file(uint64_t filesize) {
MS_ASSERT(filesize > 0);
struct ms_fake_file *file = MS_MALLOC(sizeof(struct ms_fake_file));
memset(file, 0, sizeof(struct ms_fake_file));
file->filesize = filesize;
return file;
}
size_t read_fake(struct ms_fake_file *file, char *buf, size_t nbyte, off_t offset) {
MS_ASSERT(nbyte + offset <= file->filesize);
size_t read = 0;
while (read < nbyte) {
off_t index = (offset + read) / 32;
off_t off = (offset + read) % 32;
char index_str[128] = {0};
snprintf(index_str, 128, "%" INT64_FMT "%" INT64_FMT, index, file->filesize);
char md5[33];
ms_cs_md5(md5, index_str, strlen(index_str), NULL);
if (nbyte - read > 32 - off) {
memcpy(buf + read, md5 + off, 32 - off);
read += 32 - off;
} else {
memcpy(buf + read, md5 + off, nbyte - read);
read += nbyte - read;
}
}
return read;
}
void validate_buf(struct ms_fake_file *file, char *buf, size_t nbyte, off_t offset) {
if (nbyte == 0) {
return;
}
char *temp = MS_MALLOC(nbyte);
size_t read = read_fake(file, temp, nbyte, offset);
MS_ASSERT(read == nbyte);
int i = 0;
for (; i < read; ++i) {
MS_ASSERT(temp[i] == buf[i]);
}
MS_FREE(temp);
}
int close_fake_file(struct ms_fake_file *file) {
MS_FREE(file);
return 0;
}
| 2.5 | 2 |
2024-11-18T20:48:30.932457+00:00 | 2023-08-26T17:35:16 | 784eb838d4908cf1c3a5c09657552dbdd241cc7c | {
"blob_id": "784eb838d4908cf1c3a5c09657552dbdd241cc7c",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-26T17:35:16",
"content_id": "a6407042fc17d13ae47597396e90009b22067e58",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "f389215145b18879687b8deffdad65c2df127895",
"extension": "c",
"filename": "vm-codeobserver.c",
"fork_events_count": 2,
"gha_created_at": "2017-05-22T13:19:19",
"gha_event_created_at": "2023-04-07T12:57:59",
"gha_language": "C",
"gha_license_id": "Apache-2.0",
"github_id": 92055829,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 8282,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/vm-codeobserver.c",
"provenance": "stackv2-0102.json.gz:64588",
"repo_name": "ednl/c",
"revision_date": "2023-08-26T17:35:16",
"revision_id": "0d98af8c185a56f38624d77d9476f0b89e4819e2",
"snapshot_id": "c3831a6b18f26056d5a1527c987109954436960e",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/ednl/c/0d98af8c185a56f38624d77d9476f0b89e4819e2/vm-codeobserver.c",
"visit_date": "2023-09-01T15:01:22.465399"
} | stackv2 | // Puzzle: Implement a fantasy computer to find out the answer to this program
// https://www.reddit.com/r/adventofcode/comments/128t3c6/puzzle_implement_a_fantasy_computer_to_find_out/
// Puzzle designed by https://www.reddit.com/user/codeobserver for https://codeguppy.com
// Solution by E. Dronkert https://github.com/ednl
#include <stdio.h> // printf, sscanf
#include <stdlib.h> // calloc, free
#include <stdbool.h> // bool
// Default VM setup parameters
#define MEMORYSIZE 64 // actually used by puzzle: 50
#define STACKSIZE 16 // actually used by puzzle: 2
#define REGISTERS 4 // given by puzzle
#define MAXPARCOUNT 3 // instructions have 0 to 3 parameters
// Valid opcode range
#define OPCODE_MIN 10
#define OPCODE_MAX 255
// Opcode parameter addressing modes
#define PAR_IMMEDIATE 1 // parameter is a direct value
#define PAR_REGISTER 2 // parameter is a register index
#define PAR_ABSOLUTE 3 // parameter is an absolute memory address
// #define PAR_RELATIVE 4 // unused
// Error codes
#define ERR_OK 0
#define ERR_NULLPOINTER 1
#define ERR_INVALID_OPCODE 2
#define ERR_PC_UNDERFLOW 3
#define ERR_PC_OVERFLOW 4
#define ERR_STACK_FULL 5
#define ERR_STACK_EMPTY 6
#define ERR_REGISTER_INDEX 7
#define ERR_INTERNAL_PARCOUNT 8
#define ERR_INTERNAL_PARMODE 9
// Program code
static const char *input = "11,0,10,42,6,255,30,0,11,0,0,11,1,1,11,3,1,60,1,10,2,0,20,2,1,60,2,10,0,1,10,1,2,11,2,1,20,3,2,31,2,30,2,41,3,2,19,31,0,50";
// Instruction
// parmode: units = addr mode of 1st par, tens = addr mode of 2nd par, etc.
// stackdir: +1 = wants to push onto the stack, -1 = wants to pop off the stack
typedef struct _Instr {
int opcode, parmode, stackdir;
char name[8];
} Instr;
// Language definition in rows 0-25 and cols 0-5 for each opcode = 10*row + col
static Instr assembly[26][6] = {
{0}, // no opcodes on row 0
{{10, 22, 0, "MOVR" }, {11, 12, 0, "MOVV"}},
{{20, 22, 0, "ADD" }, {21, 22, 0, "SUB" }},
{{30, 2, 1, "PUSH" }, {31, 2, -1, "POP" }},
{{40, 3, 0, "JP" }, {41, 322, 0, "JL" }, {42, 3, 1, "CALL"}},
{{50, 0, -1, "RET" }},
{{60, 2, 0, "PRINT"}},
{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0}, // no opcodes on rows 7-24
{{0},{0},{0},{0},{0},{255,0,0,"HALT"}} // no opcodes in cols 0-4
};
typedef struct {
int *mem, *stack, *reg;
int memsize, progsize, stacksize, regcount;
int pc, sp, tick, tock, retval; // program counter, stack pointer, clock, result
bool halted, silent;
} VirtualMachine;
static int fieldcount(const char * const csvline)
{
if (!csvline || *csvline == '\0')
return 0;
int fields = 1;
const char *c = csvline;
while (*c)
if (*c++ == ',')
++fields;
return fields;
}
static void * del_vm(VirtualMachine ** vm)
{
if (vm && *vm) {
free((*vm)->mem);
free((*vm)->stack);
free((*vm)->reg);
free(*vm);
*vm = NULL;
}
return NULL;
}
static VirtualMachine * new_vm(const char * const csvline)
{
VirtualMachine *vm = calloc(1, sizeof *vm); // also resets all vars
if (!vm)
return NULL;
int progsize = fieldcount(csvline);
int memsize = progsize ? progsize : MEMORYSIZE;
vm->mem = calloc((size_t)memsize, sizeof *(vm->mem));
vm->stack = calloc(STACKSIZE, sizeof *(vm->stack));
vm->reg = calloc(REGISTERS, sizeof *(vm->reg));
if (!vm->mem || !vm->stack || !vm->reg)
return del_vm(&vm);
vm->memsize = memsize;
vm->stacksize = STACKSIZE;
vm->regcount = REGISTERS;
const char *c = csvline;
while (*c != '\0' && vm->progsize < vm->memsize) {
int val;
if (sscanf(c, "%d", &val) != 1)
return del_vm(&vm);
vm->mem[vm->progsize++] = val;
while (*c != '\0' && *c != ',')
++c;
if (*c == ',')
++c;
}
if (vm->progsize != progsize)
return del_vm(&vm);
return vm;
}
static int tick(VirtualMachine * vm)
{
if (!vm)
return ERR_NULLPOINTER;
if (vm->halted)
return 0;
if (vm->pc < 0 || vm->pc >= vm->progsize) {
vm->halted = true;
return vm->pc < 0 ? ERR_PC_UNDERFLOW : ERR_PC_OVERFLOW;
}
// Start clock cycle
vm->tick++;
// Get instruction
int opcode = vm->mem[vm->pc++];
if (opcode < OPCODE_MIN || opcode > OPCODE_MAX) {
vm->halted = true;
return ERR_INVALID_OPCODE;
}
div_t qr = div(opcode, 10);
Instr *instr = &assembly[qr.quot][qr.rem];
if (instr->opcode != opcode) {
vm->halted = true;
return ERR_INVALID_OPCODE;
}
// Check stack integrity
if (instr->stackdir == 1 && vm->sp >= vm->stacksize) {
vm->halted = true;
return ERR_STACK_FULL;
}
if (instr->stackdir == -1 && vm->sp <= 0) {
vm->halted = true;
return ERR_STACK_EMPTY;
}
// Get parameters
int i = 0, par[MAXPARCOUNT] = {0};
int mode = instr->parmode;
while (mode) {
if (i >= MAXPARCOUNT) {
vm->halted = true;
return ERR_INTERNAL_PARCOUNT;
}
if (vm->pc >= vm->progsize) {
vm->halted = true;
return ERR_PC_OVERFLOW;
}
par[i] = vm->mem[vm->pc++];
qr = div(mode, 10); // get current parameter mode from units
mode = qr.quot; // reduce mode to tens
switch (qr.rem) {
case PAR_IMMEDIATE: // nothing to check for immediate value
break;
case PAR_REGISTER: // check if valid register index
if (par[i] < 0 || par[i] >= vm->regcount) {
vm->halted = true;
return ERR_REGISTER_INDEX;
}
break;
case PAR_ABSOLUTE: // check if valid program address (language only uses addr to jump to, not to store/load)
if (par[i] < 0 || par[i] >= vm->progsize) {
vm->halted = true;
return par[i] < 0 ? ERR_PC_UNDERFLOW : ERR_PC_OVERFLOW;
}
break;
default:
vm->halted = true;
return ERR_INTERNAL_PARMODE; // mode must be IMM/REG/ABS
}
++i;
}
// Execute instruction
switch (opcode) {
case 10: vm->reg[par[0]] = vm->reg[par[1]]; break; // MOVR Rdst Rsrc
case 11: vm->reg[par[0]] = par[1]; break; // MOVV Rdst val
case 20: vm->reg[par[0]] += vm->reg[par[1]]; break; // ADD Rdst Rsrc
case 21: vm->reg[par[0]] -= vm->reg[par[1]]; break; // SUB Rdst Rsrc
case 30: vm->stack[vm->sp++] = vm->reg[par[0]]; break; // PUSH Rsrc
case 31: vm->reg[par[0]] = vm->stack[--vm->sp]; break; // POP Rdst
case 40: vm->pc = par[0]; break; // JP addr
case 41: // JL Rx Ry addr
if (vm->reg[par[0]] < vm->reg[par[1]])
vm->pc = par[2];
break;
case 42: // CALL addr (+ push ret-addr)
vm->stack[vm->sp++] = vm->pc;
vm->pc = par[0];
break;
case 50: vm->pc = vm->stack[--vm->sp]; break; // RET (+ pop ret-addr)
case 60: // PRINT Rsrc
vm->retval = vm->reg[par[0]];
if (!vm->silent)
printf("%d\n", vm->retval);
break;
case 255: vm->halted = true; break; // HALT
default: vm->halted = true; return ERR_INVALID_OPCODE; // invalid opcode
}
// End clock cycle
vm->tock++;
return ERR_OK;
}
static int run(VirtualMachine * vm)
{
if (!vm)
return ERR_NULLPOINTER;
int exitcode = 0;
while (!vm->halted)
exitcode = tick(vm);
return exitcode;
}
int main(void)
{
VirtualMachine *vm = new_vm(input); // init
int exitcode = run(vm); // print first 10 Fibonacci numbers
del_vm(&vm); // cleanup
return exitcode; // pass exitcode
}
| 2.46875 | 2 |
2024-11-18T20:48:31.249369+00:00 | 2020-10-19T17:51:59 | 0f28bc06252ece02eaf68686f8b4fae779fd419d | {
"blob_id": "0f28bc06252ece02eaf68686f8b4fae779fd419d",
"branch_name": "refs/heads/master",
"committer_date": "2020-10-19T17:51:59",
"content_id": "4e86f62e085c0b054667483a260358bd8aabc7fd",
"detected_licenses": [
"MIT"
],
"directory_id": "67f3b7aee6600a344a37df82d6331fd0bcab3a9d",
"extension": "h",
"filename": "shell.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 251374712,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2233,
"license": "MIT",
"license_type": "permissive",
"path": "/src/shell.h",
"provenance": "stackv2-0102.json.gz:64847",
"repo_name": "mayank-02/fsh",
"revision_date": "2020-10-19T17:51:59",
"revision_id": "f5c09be75579781349f71bbac0c9da58e42719cd",
"snapshot_id": "e900781f72f78d52104d4c012f4ddf75f13496a6",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/mayank-02/fsh/f5c09be75579781349f71bbac0c9da58e42719cd/src/shell.h",
"visit_date": "2023-01-08T13:15:48.140555"
} | stackv2 | #include <sys/types.h>
#include <unistd.h>
#include "parse.h"
/* Maximum character limit on command */
#define CMD_SIZE 1024
/* Max number of processes allowed in a group */
#define MAX_PROCS_IN_GROUP 16
/* Flags needed while reading/writing a file */
#define READ_FLAGS (O_RDONLY)
#define CREATE_FLAGS (O_WRONLY | O_CREAT | O_TRUNC)
#define APPEND_FLAGS (O_WRONLY | O_CREAT | O_APPEND)
#define READ_MODES (S_IRUSR | S_IRGRP | S_IROTH)
#define CREATE_MODES (S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)
/* For showing colored prompt */
#define CYN "\x1B[36m"
#define BLU "\x1B[34m"
#define GRN "\x1B[32m"
#define RESET "\x1B[0m"
/* States a process or a job can be in */
typedef enum {
FG, BG, STOPPED
} ProcState;
/* Structure to store information for a process group or a job */
typedef struct {
/* To store all information regarding processes in that group */
cmdTable cmdTab;
/* Process Group ID of the job */
pid_t pgid;
/* Process IDs of the processes in the job */
pid_t pids[MAX_PROCS_IN_GROUP];
/* Number of processes running or stopped i.e. not completed */
int numProcs;
/* Status of job */
ProcState status;
} job;
/* A stack of jobs with index to implement job control */
job jobsTable[16];
int jobsTableIdx = 0;
/**
* Function to print prompt in a pretty way
*/
void printPrompt();
/**
* Handler for SIGCHLD signal
* @param signum signal number for corresponding signal
*/
void sigchldHandler(int signum);
/**
* Handler for SIGINT signal or Ctrl-C
* @param signum signal number for corresponding signal
*/
void sigintHandler(int signum);
/**
* Handler for SIGTSTP signal or Ctrl-Z
* @param signum signal number for corresponding signal
*/
void sigtstpHandler(int signum);
/**
* Function to print jobs table using global array of jobs
*/
void printJobsTable();
/**
* Initialise an empty job
* @param cmdTab pointer to command table
* @return initialised job
*/
job makeJob(cmdTable *cmdTab);
/**
* Executes commands
* @param cmdTab pointer to command table
*/
void executor(cmdTable *cmdTab);
/**
* Run job at top of stack, in foreground
*/
void fg();
/**
* Run most recent STOPPED job, in background
*/
void bg();
/**
* Frees jobs table
*/
void freeJobsTable();
| 2.453125 | 2 |
2024-11-18T20:48:31.721529+00:00 | 2014-10-31T07:59:14 | 7d1b9e0609020f01f62e2b4d4b11a03dc100d59d | {
"blob_id": "7d1b9e0609020f01f62e2b4d4b11a03dc100d59d",
"branch_name": "refs/heads/master",
"committer_date": "2014-10-31T07:59:14",
"content_id": "a48d6531952764d8511060e75c031be13d43675e",
"detected_licenses": [
"NTP"
],
"directory_id": "441f1d69b8dc09d769645c670d20edeb78714c2b",
"extension": "c",
"filename": "refclock_as2201.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 8970226,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 11399,
"license": "NTP",
"license_type": "permissive",
"path": "/ntpd/refclock_as2201.c",
"provenance": "stackv2-0102.json.gz:65104",
"repo_name": "aosm/ntp",
"revision_date": "2014-10-31T07:59:14",
"revision_id": "4f74cd7e007a808da6e0e5a9ec7858ec82a37e53",
"snapshot_id": "fa0f7d764793b112440b9159774721a3aca58938",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/aosm/ntp/4f74cd7e007a808da6e0e5a9ec7858ec82a37e53/ntpd/refclock_as2201.c",
"visit_date": "2023-08-28T08:48:46.140856"
} | stackv2 | /*
* refclock_as2201 - clock driver for the Austron 2201A GPS
* Timing Receiver
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#if defined(REFCLOCK) && defined(CLOCK_AS2201)
#include "ntpd.h"
#include "ntp_io.h"
#include "ntp_refclock.h"
#include "ntp_unixtime.h"
#include "ntp_stdlib.h"
#include <stdio.h>
#include <ctype.h>
/*
* This driver supports the Austron 2200A/2201A GPS Receiver with
* Buffered RS-232-C Interface Module. Note that the original 2200/2201
* receivers will not work reliably with this driver, since the older
* design cannot accept input commands at any reasonable data rate.
*
* The program sends a "*toc\r" to the radio and expects a response of
* the form "yy:ddd:hh:mm:ss.mmm\r" where yy = year of century, ddd =
* day of year, hh:mm:ss = second of day and mmm = millisecond of
* second. Then, it sends statistics commands to the radio and expects
* a multi-line reply showing the corresponding statistics or other
* selected data. Statistics commands are sent in order as determined by
* a vector of commands; these might have to be changed with different
* radio options. If flag4 of the fudge configuration command is set to
* 1, the statistics data are written to the clockstats file for later
* processing.
*
* In order for this code to work, the radio must be placed in non-
* interactive mode using the "off" command and with a single <cr>
* response using the "term cr" command. The setting of the "echo"
* and "df" commands does not matter. The radio should select UTC
* timescale using the "ts utc" command.
*
* There are two modes of operation for this driver. The first with
* default configuration is used with stock kernels and serial-line
* drivers and works with almost any machine. In this mode the driver
* assumes the radio captures a timestamp upon receipt of the "*" that
* begins the driver query. Accuracies in this mode are in the order of
* a millisecond or two and the receiver can be connected to only one
* host.
*
* The second mode of operation can be used for SunOS kernels that have
* been modified with the ppsclock streams module included in this
* distribution. The mode is enabled if flag3 of the fudge configuration
* command has been set to 1. In this mode a precise timestamp is
* available using a gadget box and 1-pps signal from the receiver. This
* improves the accuracy to the order of a few tens of microseconds. In
* addition, the serial output and 1-pps signal can be bussed to more
* than one hosts, but only one of them should be connected to the
* radio input data line.
*/
/*
* GPS Definitions
*/
#define SMAX 200 /* statistics buffer length */
#define DEVICE "/dev/gps%d" /* device name and unit */
#define SPEED232 B9600 /* uart speed (9600 baud) */
#define PRECISION (-20) /* precision assumed (about 1 us) */
#define REFID "GPS\0" /* reference ID */
#define DESCRIPTION "Austron 2201A GPS Receiver" /* WRU */
#define LENTOC 19 /* yy:ddd:hh:mm:ss.mmm timecode lngth */
/*
* AS2201 unit control structure.
*/
struct as2201unit {
char *lastptr; /* statistics buffer pointer */
char stats[SMAX]; /* statistics buffer */
int linect; /* count of lines remaining */
int index; /* current statistics command */
};
/*
* Radio commands to extract statitistics
*
* A command consists of an ASCII string terminated by a <cr> (\r). The
* command list consist of a sequence of commands terminated by a null
* string ("\0"). One command from the list is sent immediately
* following each received timecode (*toc\r command) and the ASCII
* strings received from the radio are saved along with the timecode in
* the clockstats file. Subsequent commands are sent at each timecode,
* with the last one in the list followed by the first one. The data
* received from the radio consist of ASCII strings, each terminated by
* a <cr> (\r) character. The number of strings for each command is
* specified as the first line of output as an ASCII-encode number. Note
* that the ETF command requires the Input Buffer Module and the LORAN
* commands require the LORAN Assist Module. However, if these modules
* are not installed, the radio and this driver will continue to operate
* successfuly, but no data will be captured for these commands.
*/
static char stat_command[][30] = {
"ITF\r", /* internal time/frequency */
"ETF\r", /* external time/frequency */
"LORAN ENSEMBLE\r", /* GPS/LORAN ensemble statistics */
"LORAN TDATA\r", /* LORAN signal data */
"ID;OPT;VER\r", /* model; options; software version */
"ITF\r", /* internal time/frequency */
"ETF\r", /* external time/frequency */
"LORAN ENSEMBLE\r", /* GPS/LORAN ensemble statistics */
"TRSTAT\r", /* satellite tracking status */
"POS;PPS;PPSOFF\r", /* position, pps source, offsets */
"ITF\r", /* internal time/frequency */
"ETF\r", /* external time/frequency */
"LORAN ENSEMBLE\r", /* GPS/LORAN ensemble statistics */
"LORAN TDATA\r", /* LORAN signal data */
"UTC\r", /* UTC leap info */
"ITF\r", /* internal time/frequency */
"ETF\r", /* external time/frequency */
"LORAN ENSEMBLE\r", /* GPS/LORAN ensemble statistics */
"TRSTAT\r", /* satellite tracking status */
"OSC;ET;TEMP\r", /* osc type; tune volts; oven temp */
"\0" /* end of table */
};
/*
* Function prototypes
*/
static int as2201_start (int, struct peer *);
static void as2201_shutdown (int, struct peer *);
static void as2201_receive (struct recvbuf *);
static void as2201_poll (int, struct peer *);
/*
* Transfer vector
*/
struct refclock refclock_as2201 = {
as2201_start, /* start up driver */
as2201_shutdown, /* shut down driver */
as2201_poll, /* transmit poll message */
noentry, /* not used (old as2201_control) */
noentry, /* initialize driver (not used) */
noentry, /* not used (old as2201_buginfo) */
NOFLAGS /* not used */
};
/*
* as2201_start - open the devices and initialize data for processing
*/
static int
as2201_start(
int unit,
struct peer *peer
)
{
register struct as2201unit *up;
struct refclockproc *pp;
int fd;
char gpsdev[20];
/*
* Open serial port. Use CLK line discipline, if available.
*/
(void)sprintf(gpsdev, DEVICE, unit);
if (!(fd = refclock_open(gpsdev, SPEED232, LDISC_CLK)))
return (0);
/*
* Allocate and initialize unit structure
*/
if (!(up = (struct as2201unit *)
emalloc(sizeof(struct as2201unit)))) {
(void) close(fd);
return (0);
}
memset((char *)up, 0, sizeof(struct as2201unit));
pp = peer->procptr;
pp->io.clock_recv = as2201_receive;
pp->io.srcclock = (caddr_t)peer;
pp->io.datalen = 0;
pp->io.fd = fd;
if (!io_addclock(&pp->io)) {
(void) close(fd);
free(up);
return (0);
}
pp->unitptr = (caddr_t)up;
/*
* Initialize miscellaneous variables
*/
peer->precision = PRECISION;
peer->burst = NSTAGE;
pp->clockdesc = DESCRIPTION;
memcpy((char *)&pp->refid, REFID, 4);
up->lastptr = up->stats;
up->index = 0;
return (1);
}
/*
* as2201_shutdown - shut down the clock
*/
static void
as2201_shutdown(
int unit,
struct peer *peer
)
{
register struct as2201unit *up;
struct refclockproc *pp;
pp = peer->procptr;
up = (struct as2201unit *)pp->unitptr;
io_closeclock(&pp->io);
free(up);
}
/*
* as2201__receive - receive data from the serial interface
*/
static void
as2201_receive(
struct recvbuf *rbufp
)
{
register struct as2201unit *up;
struct refclockproc *pp;
struct peer *peer;
l_fp trtmp;
/*
* Initialize pointers and read the timecode and timestamp.
*/
peer = (struct peer *)rbufp->recv_srcclock;
pp = peer->procptr;
up = (struct as2201unit *)pp->unitptr;
pp->lencode = refclock_gtlin(rbufp, pp->a_lastcode, BMAX, &trtmp);
#ifdef DEBUG
if (debug)
printf("gps: timecode %d %d %s\n",
up->linect, pp->lencode, pp->a_lastcode);
#endif
if (pp->lencode == 0)
return;
/*
* If linect is greater than zero, we must be in the middle of a
* statistics operation, so simply tack the received data at the
* end of the statistics string. If not, we could either have
* just received the timecode itself or a decimal number
* indicating the number of following lines of the statistics
* reply. In the former case, write the accumulated statistics
* data to the clockstats file and continue onward to process
* the timecode; in the later case, save the number of lines and
* quietly return.
*/
if (pp->sloppyclockflag & CLK_FLAG2)
pp->lastrec = trtmp;
if (up->linect > 0) {
up->linect--;
if ((int)(up->lastptr - up->stats + pp->lencode) > SMAX - 2)
return;
*up->lastptr++ = ' ';
(void)strcpy(up->lastptr, pp->a_lastcode);
up->lastptr += pp->lencode;
return;
} else {
if (pp->lencode == 1) {
up->linect = atoi(pp->a_lastcode);
return;
} else {
record_clock_stats(&peer->srcadr, up->stats);
#ifdef DEBUG
if (debug)
printf("gps: stat %s\n", up->stats);
#endif
}
}
up->lastptr = up->stats;
*up->lastptr = '\0';
/*
* We get down to business, check the timecode format and decode
* its contents. If the timecode has invalid length or is not in
* proper format, we declare bad format and exit.
*/
if (pp->lencode < LENTOC) {
refclock_report(peer, CEVNT_BADREPLY);
return;
}
/*
* Timecode format: "yy:ddd:hh:mm:ss.mmm"
*/
if (sscanf(pp->a_lastcode, "%2d:%3d:%2d:%2d:%2d.%3ld", &pp->year,
&pp->day, &pp->hour, &pp->minute, &pp->second, &pp->nsec)
!= 6) {
refclock_report(peer, CEVNT_BADREPLY);
return;
}
pp->nsec *= 1000000;
/*
* Test for synchronization (this is a temporary crock).
*/
if (pp->a_lastcode[2] != ':')
pp->leap = LEAP_NOTINSYNC;
else
pp->leap = LEAP_NOWARNING;
/*
* Process the new sample in the median filter and determine the
* timecode timestamp.
*/
if (!refclock_process(pp)) {
refclock_report(peer, CEVNT_BADTIME);
return;
}
/*
* If CLK_FLAG4 is set, initialize the statistics buffer and
* send the next command. If not, simply write the timecode to
* the clockstats file.
*/
(void)strcpy(up->lastptr, pp->a_lastcode);
up->lastptr += pp->lencode;
if (pp->sloppyclockflag & CLK_FLAG4) {
*up->lastptr++ = ' ';
(void)strcpy(up->lastptr, stat_command[up->index]);
up->lastptr += strlen(stat_command[up->index]);
up->lastptr--;
*up->lastptr = '\0';
(void)write(pp->io.fd, stat_command[up->index],
strlen(stat_command[up->index]));
up->index++;
if (*stat_command[up->index] == '\0')
up->index = 0;
}
}
/*
* as2201_poll - called by the transmit procedure
*
* We go to great pains to avoid changing state here, since there may be
* more than one eavesdropper receiving the same timecode.
*/
static void
as2201_poll(
int unit,
struct peer *peer
)
{
struct refclockproc *pp;
/*
* Send a "\r*toc\r" to get things going. We go to great pains
* to avoid changing state, since there may be more than one
* eavesdropper watching the radio.
*/
pp = peer->procptr;
if (write(pp->io.fd, "\r*toc\r", 6) != 6) {
refclock_report(peer, CEVNT_FAULT);
} else {
pp->polls++;
if (!(pp->sloppyclockflag & CLK_FLAG2))
get_systime(&pp->lastrec);
}
if (peer->burst > 0)
return;
if (pp->coderecv == pp->codeproc) {
refclock_report(peer, CEVNT_TIMEOUT);
return;
}
refclock_receive(peer);
peer->burst = NSTAGE;
}
#else
int refclock_as2201_bs;
#endif /* REFCLOCK */
| 2.1875 | 2 |
2024-11-18T20:48:32.930604+00:00 | 2023-08-12T07:52:03 | dfa07d7fe10c974534ab263ce72eae3da799f054 | {
"blob_id": "dfa07d7fe10c974534ab263ce72eae3da799f054",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-12T13:24:08",
"content_id": "a1d5190d592472ec1ddd1087f8c09ce70a110f9f",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "1a0276218c8a103c9a76409e510df5b5690f44e5",
"extension": "c",
"filename": "shadow_subsystem.c",
"fork_events_count": 8,
"gha_created_at": "2012-10-29T14:06:58",
"gha_event_created_at": "2021-08-23T18:33:02",
"gha_language": "C",
"gha_license_id": "Apache-2.0",
"github_id": 6441472,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 6051,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/server/shadow/shadow_subsystem.c",
"provenance": "stackv2-0102.json.gz:65878",
"repo_name": "awakecoding/FreeRDP",
"revision_date": "2023-08-12T07:52:03",
"revision_id": "56324906a2d5b2538675e2f10b9f1ffe4a27de79",
"snapshot_id": "4add891a6c5f06db9c7ee110cce4f6b46b71bdc8",
"src_encoding": "UTF-8",
"star_events_count": 27,
"url": "https://raw.githubusercontent.com/awakecoding/FreeRDP/56324906a2d5b2538675e2f10b9f1ffe4a27de79/server/shadow/shadow_subsystem.c",
"visit_date": "2023-08-17T15:47:00.604064"
} | stackv2 | /**
* FreeRDP: A Remote Desktop Protocol Implementation
*
* Copyright 2014 Marc-Andre Moreau <marcandre.moreau@gmail.com>
*
* 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 <freerdp/config.h>
#include "shadow.h"
#include "shadow_subsystem.h"
static pfnShadowSubsystemEntry pSubsystemEntry = NULL;
void shadow_subsystem_set_entry(pfnShadowSubsystemEntry pEntry)
{
pSubsystemEntry = pEntry;
}
static int shadow_subsystem_load_entry_points(RDP_SHADOW_ENTRY_POINTS* pEntryPoints)
{
WINPR_ASSERT(pEntryPoints);
ZeroMemory(pEntryPoints, sizeof(RDP_SHADOW_ENTRY_POINTS));
if (!pSubsystemEntry)
return -1;
if (pSubsystemEntry(pEntryPoints) < 0)
return -1;
return 1;
}
rdpShadowSubsystem* shadow_subsystem_new(void)
{
RDP_SHADOW_ENTRY_POINTS ep;
rdpShadowSubsystem* subsystem = NULL;
shadow_subsystem_load_entry_points(&ep);
if (!ep.New)
return NULL;
subsystem = ep.New();
if (!subsystem)
return NULL;
CopyMemory(&(subsystem->ep), &ep, sizeof(RDP_SHADOW_ENTRY_POINTS));
return subsystem;
}
void shadow_subsystem_free(rdpShadowSubsystem* subsystem)
{
if (subsystem && subsystem->ep.Free)
subsystem->ep.Free(subsystem);
}
int shadow_subsystem_init(rdpShadowSubsystem* subsystem, rdpShadowServer* server)
{
int status = -1;
if (!subsystem || !subsystem->ep.Init)
return -1;
subsystem->server = server;
subsystem->selectedMonitor = server->selectedMonitor;
if (!(subsystem->MsgPipe = MessagePipe_New()))
goto fail;
if (!(subsystem->updateEvent = shadow_multiclient_new()))
goto fail;
if ((status = subsystem->ep.Init(subsystem)) >= 0)
return status;
fail:
if (subsystem->MsgPipe)
{
MessagePipe_Free(subsystem->MsgPipe);
subsystem->MsgPipe = NULL;
}
if (subsystem->updateEvent)
{
shadow_multiclient_free(subsystem->updateEvent);
subsystem->updateEvent = NULL;
}
return status;
}
static void shadow_subsystem_free_queued_message(void* obj)
{
wMessage* message = (wMessage*)obj;
if (message->Free)
{
message->Free(message);
message->Free = NULL;
}
}
void shadow_subsystem_uninit(rdpShadowSubsystem* subsystem)
{
if (!subsystem)
return;
if (subsystem->ep.Uninit)
subsystem->ep.Uninit(subsystem);
if (subsystem->MsgPipe)
{
wObject* obj1;
wObject* obj2;
/* Release resource in messages before free */
obj1 = MessageQueue_Object(subsystem->MsgPipe->In);
obj1->fnObjectFree = shadow_subsystem_free_queued_message;
MessageQueue_Clear(subsystem->MsgPipe->In);
obj2 = MessageQueue_Object(subsystem->MsgPipe->Out);
obj2->fnObjectFree = shadow_subsystem_free_queued_message;
MessageQueue_Clear(subsystem->MsgPipe->Out);
MessagePipe_Free(subsystem->MsgPipe);
subsystem->MsgPipe = NULL;
}
if (subsystem->updateEvent)
{
shadow_multiclient_free(subsystem->updateEvent);
subsystem->updateEvent = NULL;
}
}
int shadow_subsystem_start(rdpShadowSubsystem* subsystem)
{
int status;
if (!subsystem || !subsystem->ep.Start)
return -1;
status = subsystem->ep.Start(subsystem);
return status;
}
int shadow_subsystem_stop(rdpShadowSubsystem* subsystem)
{
int status;
if (!subsystem || !subsystem->ep.Stop)
return -1;
status = subsystem->ep.Stop(subsystem);
return status;
}
UINT32 shadow_enum_monitors(MONITOR_DEF* monitors, UINT32 maxMonitors)
{
UINT32 numMonitors = 0;
RDP_SHADOW_ENTRY_POINTS ep;
if (shadow_subsystem_load_entry_points(&ep) < 0)
return 0;
numMonitors = ep.EnumMonitors(monitors, maxMonitors);
return numMonitors;
}
/**
* Common function for subsystem implementation.
* This function convert 32bit ARGB format pixels to xormask data
* and andmask data and fill into SHADOW_MSG_OUT_POINTER_ALPHA_UPDATE
* Caller should free the andMaskData and xorMaskData later.
*/
int shadow_subsystem_pointer_convert_alpha_pointer_data(
BYTE* pixels, BOOL premultiplied, UINT32 width, UINT32 height,
SHADOW_MSG_OUT_POINTER_ALPHA_UPDATE* pointerColor)
{
UINT32 x, y;
BYTE* pSrc8;
BYTE* pDst8;
UINT32 xorStep;
UINT32 andStep;
UINT32 andBit;
BYTE* andBits;
UINT32 andPixel;
BYTE A, R, G, B;
xorStep = (width * 3);
xorStep += (xorStep % 2);
andStep = ((width + 7) / 8);
andStep += (andStep % 2);
pointerColor->lengthXorMask = height * xorStep;
pointerColor->xorMaskData = (BYTE*)calloc(1, pointerColor->lengthXorMask);
if (!pointerColor->xorMaskData)
return -1;
pointerColor->lengthAndMask = height * andStep;
pointerColor->andMaskData = (BYTE*)calloc(1, pointerColor->lengthAndMask);
if (!pointerColor->andMaskData)
{
free(pointerColor->xorMaskData);
pointerColor->xorMaskData = NULL;
return -1;
}
for (y = 0; y < height; y++)
{
pSrc8 = &pixels[(width * 4) * (height - 1 - y)];
pDst8 = &(pointerColor->xorMaskData[y * xorStep]);
andBit = 0x80;
andBits = &(pointerColor->andMaskData[andStep * y]);
for (x = 0; x < width; x++)
{
B = *pSrc8++;
G = *pSrc8++;
R = *pSrc8++;
A = *pSrc8++;
andPixel = 0;
if (A < 64)
A = 0; /* pixel cannot be partially transparent */
if (!A)
{
/* transparent pixel: XOR = black, AND = 1 */
andPixel = 1;
B = G = R = 0;
}
else
{
if (premultiplied)
{
B = (B * 0xFF) / A;
G = (G * 0xFF) / A;
R = (R * 0xFF) / A;
}
}
*pDst8++ = B;
*pDst8++ = G;
*pDst8++ = R;
if (andPixel)
*andBits |= andBit;
if (!(andBit >>= 1))
{
andBits++;
andBit = 0x80;
}
}
}
return 1;
}
void shadow_subsystem_frame_update(rdpShadowSubsystem* subsystem)
{
shadow_multiclient_publish_and_wait(subsystem->updateEvent);
}
| 2.078125 | 2 |
2024-11-18T20:48:33.181106+00:00 | 2018-02-25T20:04:09 | 4122147079fd300683b543f71d7d80f5008b0200 | {
"blob_id": "4122147079fd300683b543f71d7d80f5008b0200",
"branch_name": "refs/heads/master",
"committer_date": "2018-02-25T20:04:09",
"content_id": "d2ad28e3662e295758cf3d941f4fa90bb22499ca",
"detected_licenses": [
"BSD-2-Clause",
"BSD-3-Clause"
],
"directory_id": "0e321529e10eed6fcf26a30b3bd2eb03ff40cad4",
"extension": "c",
"filename": "walker.c",
"fork_events_count": 0,
"gha_created_at": "2018-02-27T19:43:22",
"gha_event_created_at": "2018-02-27T19:43:22",
"gha_language": null,
"gha_license_id": "BSD-2-Clause",
"github_id": 123179124,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 7855,
"license": "BSD-2-Clause,BSD-3-Clause",
"license_type": "permissive",
"path": "/walker.c",
"provenance": "stackv2-0102.json.gz:66136",
"repo_name": "twiggler/citrine",
"revision_date": "2018-02-25T20:04:09",
"revision_id": "15b295d61822e52658f239eb20879588e3b0c900",
"snapshot_id": "bba27d72fe2358c1b1834d474d3a98aad44472b8",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/twiggler/citrine/15b295d61822e52658f239eb20879588e3b0c900/walker.c",
"visit_date": "2021-01-24T16:15:18.546722"
} | stackv2 | #include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdarg.h>
#include <math.h>
#include <stdint.h>
#include "citrine.h"
/**
* CTRWalkerReturn
*
* Returns from a block of code.
*/
ctr_object* ctr_cwlk_return(ctr_tnode* node) {
char wasReturn = 0;
ctr_tlistitem* li;
ctr_object* e;
if (!node->nodes) {
fprintf(stderr,"Invalid return expression.\n");
exit(1);
}
li = node->nodes;
if (!li->node) {
fprintf(stderr,"Invalid return expression 2.\n");
exit(1);
}
e = ctr_cwlk_expr(li->node, &wasReturn);
return e;
}
/**
* CTRWalkerMessage
*
* Processes a message sending operation.
*/
ctr_object* ctr_cwlk_message(ctr_tnode* paramNode) {
int sticky = 0;
char wasReturn = 0;
ctr_object* result;
ctr_tlistitem* eitem = paramNode->nodes;
ctr_tnode* receiverNode = eitem->node;
ctr_tnode* msgnode;
ctr_tlistitem* li = eitem;
char* message;
ctr_tlistitem* argumentList;
ctr_object* r;
ctr_object* recipientName = NULL;
switch (receiverNode->type) {
case CTR_AST_NODE_REFERENCE:
recipientName = ctr_build_string(receiverNode->value, receiverNode->vlen);
recipientName->info.sticky = 1;
if (CtrStdFlow == NULL) {
ctr_callstack[ctr_callstack_index++] = receiverNode;
}
if (receiverNode->modifier == 1) {
r = ctr_find_in_my(recipientName);
} else {
r = ctr_find(recipientName);
}
if (CtrStdFlow == NULL) {
ctr_callstack_index--;
}
if (!r) {
exit(1);
}
break;
case CTR_AST_NODE_LTRNIL:
r = ctr_build_nil();
break;
case CTR_AST_NODE_LTRBOOLTRUE:
r = ctr_build_bool(1);
break;
case CTR_AST_NODE_LTRBOOLFALSE:
r = ctr_build_bool(0);
break;
case CTR_AST_NODE_LTRSTRING:
r = ctr_build_string(receiverNode->value, receiverNode->vlen);
break;
case CTR_AST_NODE_LTRNUM:
r = ctr_build_number_from_string(receiverNode->value, receiverNode->vlen);
break;
case CTR_AST_NODE_NESTED:
r = ctr_cwlk_expr(receiverNode, &wasReturn);
break;
case CTR_AST_NODE_CODEBLOCK:
r = ctr_build_block(receiverNode);
break;
default:
fprintf(stderr,"Cannot send message to receiver of type: %d \n", receiverNode->type);
break;
}
while(li->next) {
ctr_argument* a;
ctr_argument* aItem;
ctr_size l;
li = li->next;
msgnode = li->node;
message = msgnode->value;
l = msgnode->vlen;
if (CtrStdFlow == NULL) {
ctr_callstack[ctr_callstack_index++] = msgnode;
}
argumentList = msgnode->nodes;
a = (ctr_argument*) ctr_heap_allocate( sizeof( ctr_argument ) );
aItem = a;
aItem->object = CtrStdNil;
if (argumentList) {
ctr_tnode* node;
node = argumentList->node;
while(1) {
ctr_object* o = ctr_cwlk_expr(node, &wasReturn);
aItem->object = o;
/* we always send at least one argument, note that if you want to modify the argumentList, be sure to take this into account */
/* there is always an extra empty argument at the end */
aItem->next = (ctr_argument*) ctr_heap_allocate( sizeof( ctr_argument ) );
aItem = aItem->next;
aItem->object = CtrStdNil;
if (!argumentList->next) break;
argumentList = argumentList->next;
node = argumentList->node;
}
}
sticky = r->info.sticky;
r->info.sticky = 1;
result = ctr_send_message(r, message, l, a);
r->info.sticky = sticky;
aItem = a;
if (CtrStdFlow == NULL) {
ctr_callstack_index --;
}
while(aItem->next) {
a = aItem;
aItem = aItem->next;
ctr_heap_free( a );
}
ctr_heap_free( aItem );
r = result;
}
if (recipientName) recipientName->info.sticky = 0;
return result;
}
/**
* CTRWalkerAssignment
*
* Processes an assignment operation.
*/
ctr_object* ctr_cwlk_assignment(ctr_tnode* node) {
char wasReturn = 0;
ctr_tlistitem* assignmentItems = node->nodes;
ctr_tnode* assignee = assignmentItems->node;
ctr_tlistitem* valueListItem = assignmentItems->next;
ctr_tnode* value = valueListItem->node;
ctr_object* x;
ctr_object* result;
if (CtrStdFlow == NULL) {
ctr_callstack[ctr_callstack_index++] = assignee;
}
x = ctr_cwlk_expr(value, &wasReturn);
if (assignee->modifier == 1) {
result = ctr_assign_value_to_my(ctr_build_string(assignee->value, assignee->vlen), x);
} else if (assignee->modifier == 2) {
result = ctr_assign_value_to_local(ctr_build_string(assignee->value, assignee->vlen), x);
} else {
result = ctr_assign_value(ctr_build_string(assignee->value, assignee->vlen), x);
}
if (CtrStdFlow == NULL) {
ctr_callstack_index--;
}
return result;
}
/**
* CTRWalkerExpression
*
* Processes an expression.
*/
ctr_object* ctr_cwlk_expr(ctr_tnode* node, char* wasReturn) {
ctr_object* result;
uint8_t i;
int line;
char* currentProgram = "?";
ctr_tnode* stackNode;
ctr_source_map* mapItem;
switch (node->type) {
case CTR_AST_NODE_LTRSTRING:
result = ctr_build_string(node->value, node->vlen);
break;
case CTR_AST_NODE_LTRBOOLTRUE:
result = ctr_build_bool(1);
break;
case CTR_AST_NODE_LTRBOOLFALSE:
result = ctr_build_bool(0);
break;
case CTR_AST_NODE_LTRNIL:
result = ctr_build_nil();
break;
case CTR_AST_NODE_LTRNUM:
result = ctr_build_number_from_string(node->value, node->vlen);
break;
case CTR_AST_NODE_CODEBLOCK:
result = ctr_build_block(node);
break;
case CTR_AST_NODE_REFERENCE:
if (CtrStdFlow == NULL) {
ctr_callstack[ctr_callstack_index++] = node;
}
if (node->modifier == 1) {
result = ctr_find_in_my(ctr_build_string(node->value, node->vlen));
} else {
result = ctr_find(ctr_build_string(node->value, node->vlen));
}
if (CtrStdFlow == NULL) {
ctr_callstack_index--;
}
break;
case CTR_AST_NODE_EXPRMESSAGE:
result = ctr_cwlk_message(node);
break;
case CTR_AST_NODE_EXPRASSIGNMENT:
result = ctr_cwlk_assignment(node);
break;
case CTR_AST_NODE_RETURNFROMBLOCK:
result = ctr_cwlk_return(node);
*wasReturn = 1;
break;
case CTR_AST_NODE_NESTED:
result = ctr_cwlk_expr(node->nodes->node, wasReturn);
break;
case CTR_AST_NODE_ENDOFPROGRAM:
if (CtrStdFlow && CtrStdFlow != CtrStdExit && ctr_cwlk_subprogram == 0) {
fprintf(stderr,"Uncatched error has occurred.\n");
if (CtrStdFlow->info.type == CTR_OBJECT_TYPE_OTSTRING) {
fwrite(CtrStdFlow->value.svalue->value, sizeof(char), CtrStdFlow->value.svalue->vlen, stderr);
fprintf(stderr,"\n");
}
for ( i = ctr_callstack_index; i > 0; i--) {
fprintf(stderr,"#%d ", i);
stackNode = ctr_callstack[i-1];
fwrite(stackNode->value, sizeof(char), stackNode->vlen, stderr);
mapItem = ctr_source_map_head;
line = -1;
while(mapItem) {
if (line == -1 && mapItem->node == stackNode) {
line = mapItem->line;
}
if (line > -1 && mapItem->node->type == CTR_AST_NODE_PROGRAM) {
currentProgram = mapItem->node->value;
fprintf(stderr," (%s: %d)", currentProgram, line+1);
break;
}
mapItem = mapItem->next;
}
fprintf(stderr,"\n");
}
}
result = ctr_build_nil();
break;
default:
fprintf(stderr,"Runtime Error. Invalid parse node: %d %s \n", node->type,node->value);
exit(1);
break;
}
return result;
}
/**
* CTRWalkerRunBlock
*
* Processes the execution of a block of code.
*/
ctr_object* ctr_cwlk_run(ctr_tnode* program) {
ctr_object* result = NULL;
char wasReturn = 0;
ctr_tlistitem* li;
li = program->nodes;
while(li) {
ctr_tnode* node = li->node;
if (!li->node) {
fprintf(stderr,"Missing parse node\n");
exit(1);
}
wasReturn = 0;
result = ctr_cwlk_expr(node, &wasReturn);
if ( wasReturn ) {
break;
}
/* Perform garbage collection cycle */
if ( ( ( ctr_gc_mode & 1 ) && ctr_gc_alloc > ( ctr_gc_memlimit * 0.8 ) ) || ctr_gc_mode & 4 ) {
ctr_gc_internal_collect();
}
if (!li->next) break;
li = li->next;
}
if (wasReturn == 0) result = NULL;
return result;
}
| 2.484375 | 2 |
2024-11-18T20:48:33.327422+00:00 | 2020-07-13T02:23:35 | 5209ce691c1ef8785a7a0073cb6956f07dbc4b8a | {
"blob_id": "5209ce691c1ef8785a7a0073cb6956f07dbc4b8a",
"branch_name": "refs/heads/master",
"committer_date": "2020-07-13T02:23:35",
"content_id": "c2d6aac08831b1fbdbd01effb4ec39262ae15fb8",
"detected_licenses": [
"MIT"
],
"directory_id": "5743796cdf5f28a1faf92543d4cb349d703ec23a",
"extension": "c",
"filename": "dataservice_data_txn_commit.c",
"fork_events_count": 0,
"gha_created_at": "2020-07-03T18:19:11",
"gha_event_created_at": "2020-07-13T02:23:37",
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 276962461,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 812,
"license": "MIT",
"license_type": "permissive",
"path": "/src/dataservice/dataservice_data_txn_commit.c",
"provenance": "stackv2-0102.json.gz:66264",
"repo_name": "hocktide/v-c-agentd",
"revision_date": "2020-07-13T02:23:35",
"revision_id": "c06be91c94a143e60d6a03eadc2aa58f1fa60399",
"snapshot_id": "9d4879feb86564e3d52cbcd8e3cf12a9a1a2e131",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/hocktide/v-c-agentd/c06be91c94a143e60d6a03eadc2aa58f1fa60399/src/dataservice/dataservice_data_txn_commit.c",
"visit_date": "2022-11-15T03:18:38.692650"
} | stackv2 | /**
* \file dataservice/dataservice_data_txn_commit.c
*
* \brief Commit a transaction in the data service.
*
* \copyright 2018 Velo Payments, Inc. All rights reserved.
*/
#include <agentd/dataservice/private/dataservice.h>
#include <agentd/inet.h>
#include <cbmc/model_assert.h>
#include <unistd.h>
#include <vpr/parameters.h>
#include "dataservice_internal.h"
/**
* \brief Commit a transaction.
*
* \param txn The transaction to abort.
*/
void dataservice_data_txn_commit(
dataservice_transaction_context_t* txn)
{
/* parameter sanity checks. */
MODEL_ASSERT(NULL != txn);
MODEL_ASSERT(NULL != txn->child);
MODEL_ASSERT(NULL != txn->child->root);
MODEL_ASSERT(NULL != txn->child->root->details);
/* commit the transaction. */
mdb_txn_commit(txn->txn);
}
| 2 | 2 |
2024-11-18T20:48:33.393212+00:00 | 2022-06-21T23:20:46 | d951fe16da6def53a054e5cb433cfece2bf41949 | {
"blob_id": "d951fe16da6def53a054e5cb433cfece2bf41949",
"branch_name": "refs/heads/master",
"committer_date": "2022-06-21T23:20:46",
"content_id": "a0509a138ff384e5b52185ab7c5e3d2fa6162e5e",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "32d00deba84b6e6c03ce6e69c21d4d6aab9b7c71",
"extension": "c",
"filename": "connections.c",
"fork_events_count": 22,
"gha_created_at": "2009-08-07T05:06:16",
"gha_event_created_at": "2022-06-21T23:20:47",
"gha_language": "C++",
"gha_license_id": "BSD-3-Clause",
"github_id": 271346,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 8046,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/cpp/rand-distributions/connections.c",
"provenance": "stackv2-0102.json.gz:66393",
"repo_name": "dterei/Scraps",
"revision_date": "2022-06-21T23:20:46",
"revision_id": "047b5b72888eb3dd29f1d6bab1aae63d1280e05e",
"snapshot_id": "c2b6b55df6554861bc0670be2aae659755748086",
"src_encoding": "UTF-8",
"star_events_count": 40,
"url": "https://raw.githubusercontent.com/dterei/Scraps/047b5b72888eb3dd29f1d6bab1aae63d1280e05e/cpp/rand-distributions/connections.c",
"visit_date": "2022-07-30T05:08:30.106194"
} | stackv2 | // Server connection handling
#include "connections.h"
#include "items.h"
#include "server.h"
#include <assert.h>
#include <event.h>
#include <pthread.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <signal.h>
#include <sys/resource.h>
#include <sys/uio.h>
#include <ctype.h>
#include <stdarg.h>
/* need this to get IOV_MAX on some platforms. */
#ifndef __need_IOV_MAX
#define __need_IOV_MAX
#endif
#include <limits.h>
// Free list management for connections.
static conn **freeconns;
static int freetotal;
static int freecurr;
static pthread_mutex_t conn_lock = PTHREAD_MUTEX_INITIALIZER;
// Initialize our connection system (i.e., free list).
void conn_init(void) {
freetotal = 200;
freecurr = 0;
if ((freeconns = calloc(freetotal, sizeof(conn *))) == NULL) {
fprintf(stderr, "Failed to allocate connection structures\n");
}
return;
}
// Returns a connection from the freelist, if any.
static conn *conn_from_freelist() {
conn *c = NULL;
pthread_mutex_lock(&conn_lock);
if (freecurr > 0) {
c = freeconns[--freecurr];
}
pthread_mutex_unlock(&conn_lock);
return c;
}
// Adds a connection to the freelist. 0 = success.
int conn_add_to_freelist(conn *c) {
int ret = 0;
pthread_mutex_lock(&conn_lock);
if (freecurr < freetotal) {
freeconns[freecurr++] = c;
ret = 1;
} else {
/* try to enlarge free connections array */
size_t newsize = freetotal * 2;
conn **new_freeconns = realloc(freeconns, sizeof(conn *) * newsize);
if (new_freeconns) {
freetotal = newsize;
freeconns = new_freeconns;
freeconns[freecurr++] = c;
ret = 1;
}
}
pthread_mutex_unlock(&conn_lock);
return ret;
}
// Create a new connection value.
conn *conn_new(const int sfd,
enum conn_states init_state,
const int event_flags,
const int read_buffer_size,
struct event_base *base) {
conn *c = conn_from_freelist();
if (NULL == c) {
if (!(c = (conn *)calloc(1, sizeof(conn)))) {
fprintf(stderr, "calloc()\n");
return NULL;
}
c->rsize = read_buffer_size;
c->wsize = DATA_BUFFER_SIZE;
c->rbuf = (char *)malloc((size_t)c->rsize);
c->wbuf = (char *)malloc((size_t)c->wsize);
c->iovsize = IOV_LIST_INITIAL;
c->iov = (struct iovec *)malloc(sizeof(struct iovec) * c->iovsize);
c->msgsize = MSG_LIST_INITIAL;
c->msglist = (struct msghdr *)malloc(sizeof(struct msghdr) * c->msgsize);
c->isize = ITEM_LIST_INITIAL;
c->ilist = (item **)malloc(sizeof(item *) * c->isize);
if (c->rbuf == NULL || c->wbuf == NULL || c->iov == NULL
|| c->msglist == NULL || c->ilist == NULL) {
conn_free(c);
fprintf(stderr, "malloc()\n");
return NULL;
}
}
c->sfd = sfd;
c->state = init_state;
c->after_write = init_state;
c->rbytes = c->wbytes = 0;
c->rcurr = c->rbuf;
c->wcurr = c->wbuf;
c->iovused = 0;
c->msgcurr = 0;
c->msgused = 0;
c->ileft = 0;
c->icurr = c->ilist;
event_set(&c->event, sfd, event_flags, event_handler, (void *)c);
event_base_set(base, &c->event);
c->ev_flags = event_flags;
if (event_add(&c->event, 0) == -1) {
if (conn_add_to_freelist(c)) {
conn_free(c);
}
perror("event_add");
return NULL;
}
return c;
}
// Frees a connection.
void conn_free(conn *c) {
if (c) {
if (c->rbuf) free(c->rbuf);
if (c->wbuf) free(c->wbuf);
if (c->iov) free(c->iov);
if (c->msglist) free(c->msglist);
free(c);
}
}
// Close a connection.
void conn_close(conn *c) {
assert(c != NULL);
/* delete the event, the socket and the conn */
event_del(&c->event);
if (config.verbose > 1) {
fprintf(stderr, "<%d connection closed.\n", c->sfd);
}
close(c->sfd);
/* if the connection has big buffers, just free it */
if (conn_add_to_freelist(c)) {
conn_free(c);
}
}
// Sets a connection's current state in the state machine. Any special
// processing that needs to happen on certain state transitions can happen
// here.
void conn_set_state(conn *c, enum conn_states state) {
assert(c != NULL);
assert(state > conn_min_state && state < conn_max_state);
if (state != c->state) {
if (config.verbose > 2) {
fprintf(stderr, "%d: going from %s to %s\n",
c->sfd, state_text(c->state), state_text(state));
}
c->state = state;
}
}
// update the event type for connection that we are listening on.
int conn_update_event(conn *c, const int new_flags) {
assert(c != NULL);
struct event_base *base = c->event.ev_base;
if (c->ev_flags == new_flags) return 1;
if (event_del(&c->event) == -1) {
if (config.verbose > 0) {
fprintf(stderr, "Couldn't update event\n");
}
return 0;
}
event_set(&c->event, c->sfd, new_flags, event_handler, (void *)c);
event_base_set(base, &c->event);
c->ev_flags = new_flags;
if (event_add(&c->event, 0) == -1) {
if (config.verbose > 0) {
fprintf(stderr, "Couldn't update event\n");
}
return 0;
}
return 1;
}
// Shrinks a connection's buffers if they're too big. This prevents periodic
// large "get" requests from permanently chewing lots of server memory.
//
// This should only be called in between requests since it can wipe output
// buffers!
void conn_shrink(conn *c) {
assert(c != NULL);
}
// Adds a message header to a connection. Returns 1 on success, 0 on
// out-of-memory.
int conn_add_msghdr(conn *c) {
struct msghdr *msg;
assert(c != NULL);
if (c->msgsize == c->msgused) {
msg = realloc(c->msglist, c->msgsize * 2 * sizeof(struct msghdr));
if (!msg) return 0;
c->msglist = msg;
c->msgsize *= 2;
}
msg = c->msglist + c->msgused;
// this wipes msg_iovlen, msg_control, msg_controllen, and msg_flags, the
// last 3 of which aren't defined on solaris:
memset(msg, 0, sizeof(struct msghdr));
msg->msg_iov = &c->iov[c->iovused];
c->msgbytes = 0;
c->msgused++;
return 1;
}
// Ensures that there is room for another struct iovec in a connection's
// iov list.
// @return true on success, false on out-of-memory.
static bool ensure_iov_space(conn *c) {
assert(c != NULL);
if (c->iovused >= c->iovsize) {
int i, iovnum;
struct iovec *new_iov =
(struct iovec *)realloc(c->iov, (c->iovsize * 2) * sizeof(struct iovec));
if (!new_iov) return false;
c->iov = new_iov;
c->iovsize *= 2;
// Point all the msghdr structures at the new list.
for (i = 0, iovnum = 0; i < c->msgused; i++) {
c->msglist[i].msg_iov = &c->iov[iovnum];
iovnum += c->msglist[i].msg_iovlen;
}
}
return true;
}
// Adds data to the list of pending data that will be written out to a
// connection.
//
// @return true on success, false on out-of-memory.
bool conn_add_iov(conn *c, const void *buf, int len) {
assert(c != NULL);
int leftover;
do {
struct msghdr *m = &c->msglist[c->msgused - 1];
// Limit the first payloads of TCP replies, to MAX_PAYLOAD_SIZE bytes.
bool limit_to_mtu = 1 == c->msgused;
// We may need to start a new msghdr if this one is full.
if (m->msg_iovlen == IOV_MAX ||
(limit_to_mtu && c->msgbytes >= MAX_PAYLOAD_SIZE)) {
conn_add_msghdr(c);
m = &c->msglist[c->msgused - 1];
}
if (!ensure_iov_space(c)) return false;
// If the fragment is too big to fit in the datagram, split it up.
if (limit_to_mtu && len + c->msgbytes > MAX_PAYLOAD_SIZE) {
leftover = len + c->msgbytes - MAX_PAYLOAD_SIZE;
len -= leftover;
} else {
leftover = 0;
}
m = &c->msglist[c->msgused - 1];
m->msg_iov[m->msg_iovlen].iov_base = (void *)buf;
m->msg_iov[m->msg_iovlen].iov_len = len;
c->msgbytes += len;
c->iovused++;
m->msg_iovlen++;
buf = ((char *)buf) + len;
len = leftover;
} while (leftover > 0);
return true;
}
// grow the item list of a connection.
bool conn_expand_items(conn *c) {
item **new_list = realloc(c->ilist, sizeof(item *) * c->isize * 2);
if (new_list) {
c->isize *= 2;
c->ilist = new_list;
return true;
} else {
return false;
}
}
| 2.4375 | 2 |
2024-11-18T20:48:34.622566+00:00 | 2017-01-15T12:06:31 | 7f8f0e80d6d0c63edb0e2d70158320c966c6c79a | {
"blob_id": "7f8f0e80d6d0c63edb0e2d70158320c966c6c79a",
"branch_name": "refs/heads/master",
"committer_date": "2017-01-15T12:06:31",
"content_id": "abf0dc58e7a3fc1d118ea3be56ac5e36d94a7448",
"detected_licenses": [
"MIT"
],
"directory_id": "cbbfe762ce01cad1a53523266b1d07c5b34ad571",
"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": 15875810,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 426,
"license": "MIT",
"license_type": "permissive",
"path": "/OSX/Bitwize/Bitwize/main.c",
"provenance": "stackv2-0102.json.gz:67164",
"repo_name": "miguelgazela/playground",
"revision_date": "2017-01-15T12:06:31",
"revision_id": "99a92043df09831eade2154b5c090c1ee7766d10",
"snapshot_id": "026cad85a050af5233a7ebe10fe9fc65072ceb27",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/miguelgazela/playground/99a92043df09831eade2154b5c090c1ee7766d10/OSX/Bitwize/Bitwize/main.c",
"visit_date": "2020-05-20T04:00:52.661786"
} | stackv2 | //
// main.c
// Bitwize
//
// Created by Miguel Oliveira on 25/02/15.
// Copyright (c) 2015 GAZELAINC. All rights reserved.
//
#include <stdio.h>
int main(int argc, const char * argv[]) {
unsigned long a = 0x00000001;
unsigned long b = 0x0;
for (int i = 0; i < 31; i++) {
a = a << 2;
a = a | 0x1;
printf("Hex: 0x%lx\n", a);
}
printf("Decimal: %lu\n", a);
}
| 2.625 | 3 |
2024-11-18T20:48:34.698046+00:00 | 2016-11-26T02:08:41 | 1de19482274fd873217f029db8ac1e71c0d3492b | {
"blob_id": "1de19482274fd873217f029db8ac1e71c0d3492b",
"branch_name": "refs/heads/master",
"committer_date": "2016-11-26T02:08:41",
"content_id": "adfdde128cad3d4f146d34d145e259d7894e5c01",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "b567a85824b775e8ff59af529d4daba0f7b637ac",
"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": 73204295,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1098,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/main.c",
"provenance": "stackv2-0102.json.gz:67294",
"repo_name": "tanishq-dubey/sen3.14",
"revision_date": "2016-11-26T02:08:41",
"revision_id": "5cf0957fb81c38ffede15cf3bd04ec3bf0185a6d",
"snapshot_id": "afe3be5dd4fa35edc4fa61506c4b297392ae750f",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/tanishq-dubey/sen3.14/5cf0957fb81c38ffede15cf3bd04ec3bf0185a6d/main.c",
"visit_date": "2020-12-24T10:59:29.326342"
} | stackv2 | #include "main.h"
int sig_flag = 0;
void sigint(int a) {
sig_flag = 1;
}
int main (int argc, char* argv[]) {
// Input validation
if (argc == 1 || argc > 2) {
debug_print("%s", "Invalid number of arguments!");
return 0;
}
FILE* fp = fopen(argv[1], "rb");
// Load ROM into dynamic memory:
fseek(fp, 0, SEEK_END);
long fsize = ftell(fp);
rewind(fp);
uint8_t *ROM = (uint8_t *)malloc(fsize +1);
fread(ROM, fsize, 1, fp);
fclose(fp);
init_game(ROM);
init_memory();
init_mmc();
ppu_init();
init_cpu();
signal(SIGINT, sigint);
long run_count = 0;
while(1) {
static int cycles = 0;
cycles = cpu_tick();
ppu_tick(cycles);
//if(run_count%50 == 0) {
// static char ch;
// scanf("%c", &ch);
//}
run_count++;
// if(get_pc() == 0xC66E) {
// break;
// }
if(sig_flag) {
memory_dump();
exit(0);
}
}
printf("VALUE AT 0x02: 0x%02X\n", read(0x02));
free(ROM);
}
| 2.359375 | 2 |
2024-11-18T20:48:34.786980+00:00 | 2020-07-29T19:42:15 | 806160c10eb52fa45460720027c3f7c2efacd64e | {
"blob_id": "806160c10eb52fa45460720027c3f7c2efacd64e",
"branch_name": "refs/heads/master",
"committer_date": "2020-07-29T19:42:15",
"content_id": "46f13981e33959f874dad591ebe4cb18af79d1db",
"detected_licenses": [
"curl"
],
"directory_id": "93fa8ba477a8ee5b721f387b3c888b92d61ac825",
"extension": "c",
"filename": "HolidayAPI.c",
"fork_events_count": 0,
"gha_created_at": "2015-04-21T13:23:20",
"gha_event_created_at": "2020-10-13T21:50:29",
"gha_language": "PHP",
"gha_license_id": null,
"github_id": 34328377,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5500,
"license": "curl",
"license_type": "permissive",
"path": "/client-libraries/accutraining/c/api/HolidayAPI.c",
"provenance": "stackv2-0102.json.gz:67423",
"repo_name": "engineerica/engineerica-dev",
"revision_date": "2020-07-29T19:42:15",
"revision_id": "753fae9f19db847337259aa89fdc22e57efccc5c",
"snapshot_id": "574c681446b5b397476aea8e77e9d6cd9efbf133",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/engineerica/engineerica-dev/753fae9f19db847337259aa89fdc22e57efccc5c/client-libraries/accutraining/c/api/HolidayAPI.c",
"visit_date": "2022-12-28T18:32:54.465976"
} | stackv2 | #include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
#include "HolidayAPI.h"
#define MAX_BUFFER_LENGTH 4096
#define intToStr(dst, src) \
do {\
char dst[256];\
snprintf(dst, 256, "%ld", (long int)(src));\
}while(0)
// View a list of entered holidays
//
// Allows the user to view all holidays entered.
//
void
HolidayAPI_holidayList(apiClient_t *apiClient, char * term )
{
list_t *localVarQueryParameters = list_create();
list_t *localVarHeaderParameters = NULL;
list_t *localVarFormParameters = NULL;
list_t *localVarHeaderType = NULL;
list_t *localVarContentType = NULL;
char *localVarBodyParameters = NULL;
// create the path
long sizeOfPath = strlen("/holiday/list")+1;
char *localVarPath = malloc(sizeOfPath);
snprintf(localVarPath, sizeOfPath, "/holiday/list");
// query parameters
char *keyQuery_term = NULL;
char * valueQuery_term ;
keyValuePair_t *keyPairQuery_term = 0;
if (term)
{
keyQuery_term = strdup("term");
valueQuery_term = (term);
keyPairQuery_term = keyValuePair_create(keyQuery_term, &valueQuery_term);
list_addElement(localVarQueryParameters,keyPairQuery_term);
}
apiClient_invoke(apiClient,
localVarPath,
localVarQueryParameters,
localVarHeaderParameters,
localVarFormParameters,
localVarHeaderType,
localVarContentType,
localVarBodyParameters,
"GET");
if (apiClient->response_code == 200) {
printf("%s\n","");
}
//No return type
end:
if (apiClient->dataReceived) {
free(apiClient->dataReceived);
apiClient->dataReceived = NULL;
apiClient->dataReceivedLen = 0;
}
list_free(localVarQueryParameters);
free(localVarPath);
}
// Create or edit a list of holidays
//
// Allows the user to create or edit holidays.
//
void
HolidayAPI_holidaySave(apiClient_t *apiClient, UNKNOWN_BASE_TYPE_t * UNKNOWN_BASE_TYPE )
{
list_t *localVarQueryParameters = NULL;
list_t *localVarHeaderParameters = NULL;
list_t *localVarFormParameters = NULL;
list_t *localVarHeaderType = NULL;
list_t *localVarContentType = list_create();
char *localVarBodyParameters = NULL;
// create the path
long sizeOfPath = strlen("/holiday/save")+1;
char *localVarPath = malloc(sizeOfPath);
snprintf(localVarPath, sizeOfPath, "/holiday/save");
// Body Param
cJSON *localVarSingleItemJSON_UNKNOWN_BASE_TYPE;
if (UNKNOWN_BASE_TYPE != NULL)
{
//string
localVarSingleItemJSON_UNKNOWN_BASE_TYPE = UNKNOWN_BASE_TYPE_convertToJSON(UNKNOWN_BASE_TYPE);
localVarBodyParameters = cJSON_Print(localVarSingleItemJSON_UNKNOWN_BASE_TYPE);
}
list_addElement(localVarContentType,"application/json"); //consumes
apiClient_invoke(apiClient,
localVarPath,
localVarQueryParameters,
localVarHeaderParameters,
localVarFormParameters,
localVarHeaderType,
localVarContentType,
localVarBodyParameters,
"POST");
if (apiClient->response_code == 200) {
printf("%s\n","");
}
//No return type
end:
if (apiClient->dataReceived) {
free(apiClient->dataReceived);
apiClient->dataReceived = NULL;
apiClient->dataReceivedLen = 0;
}
list_free(localVarContentType);
free(localVarPath);
cJSON_Delete(localVarSingleItemJSON_UNKNOWN_BASE_TYPE);
free(localVarBodyParameters);
}
// View the holiday suggestions in the given term
//
// Allows the user to view the holiday suggestions for each term.
//
void
HolidayAPI_holidaySuggest(apiClient_t *apiClient, char * term )
{
list_t *localVarQueryParameters = list_create();
list_t *localVarHeaderParameters = NULL;
list_t *localVarFormParameters = NULL;
list_t *localVarHeaderType = NULL;
list_t *localVarContentType = NULL;
char *localVarBodyParameters = NULL;
// create the path
long sizeOfPath = strlen("/holiday/suggest")+1;
char *localVarPath = malloc(sizeOfPath);
snprintf(localVarPath, sizeOfPath, "/holiday/suggest");
// query parameters
char *keyQuery_term = NULL;
char * valueQuery_term ;
keyValuePair_t *keyPairQuery_term = 0;
if (term)
{
keyQuery_term = strdup("term");
valueQuery_term = (term);
keyPairQuery_term = keyValuePair_create(keyQuery_term, &valueQuery_term);
list_addElement(localVarQueryParameters,keyPairQuery_term);
}
apiClient_invoke(apiClient,
localVarPath,
localVarQueryParameters,
localVarHeaderParameters,
localVarFormParameters,
localVarHeaderType,
localVarContentType,
localVarBodyParameters,
"GET");
if (apiClient->response_code == 200) {
printf("%s\n","");
}
//No return type
end:
if (apiClient->dataReceived) {
free(apiClient->dataReceived);
apiClient->dataReceived = NULL;
apiClient->dataReceivedLen = 0;
}
list_free(localVarQueryParameters);
free(localVarPath);
}
| 2.125 | 2 |
2024-11-18T20:48:35.171798+00:00 | 2023-09-02T14:55:31 | 494eaebbb5f4ace999ef65d5b314a1baed283f15 | {
"blob_id": "494eaebbb5f4ace999ef65d5b314a1baed283f15",
"branch_name": "refs/heads/master",
"committer_date": "2023-09-02T14:55:31",
"content_id": "b5979ae1431c84ca3cf5c6844a335e65092fce2e",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "8838eb997879add5759b6dfb23f9a646464e53ca",
"extension": "h",
"filename": "cache.h",
"fork_events_count": 325,
"gha_created_at": "2015-03-29T15:27:48",
"gha_event_created_at": "2023-09-14T16:58:34",
"gha_language": "C",
"gha_license_id": "BSD-2-Clause",
"github_id": 33078138,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2285,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/src/arch/microblaze/include/asm/cache.h",
"provenance": "stackv2-0102.json.gz:67937",
"repo_name": "embox/embox",
"revision_date": "2023-09-02T14:55:31",
"revision_id": "98e3c06e33f3fdac10a29c069c20775568e0a6d1",
"snapshot_id": "d6aacec876978522f01cdc4b8de37a668c6f4c80",
"src_encoding": "UTF-8",
"star_events_count": 1087,
"url": "https://raw.githubusercontent.com/embox/embox/98e3c06e33f3fdac10a29c069c20775568e0a6d1/src/arch/microblaze/include/asm/cache.h",
"visit_date": "2023-09-04T03:02:20.165042"
} | stackv2 | /**
* @file
* @brief Cache operations
*
* @date 25.11.09
* @author Anton Bondarev
*/
#ifndef MICROBLAZE_CACHE_H_
#define MICROBLAZE_CACHE_H_
#include <framework/mod/options.h>
#include <module/embox/arch/microblaze/kernel/arch.h>
#define CONFIG_ICACHE_BYTE_SIZE \
OPTION_MODULE_GET(embox__arch__microblaze__kernel__arch, \
NUMBER, icache_size)
#define CONFIG_ICACHE_LINE_LENGTH \
OPTION_MODULE_GET(embox__arch__microblaze__kernel__arch, \
NUMBER, icache_line)
#define CONFIG_DCHACE_BYTE_SIZE \
OPTION_MODULE_GET(embox__arch__microblaze__kernel__arch, \
NUMBER, dcache_size)
#define CONFIG_DCACHE_LINE_LENGTH \
OPTION_MODULE_GET(embox__arch__microblaze__kernel__arch, \
NUMBER, dcache_line)
#include <asm/msr.h>
static inline void cache_enable(void) {
msr_set_value(msr_get_value() | (MSR_ICE_MASK | MSR_DCE_MASK));
}
static inline void cache_disable(void) {
msr_set_value(msr_get_value() & ~(MSR_ICE_MASK | MSR_DCE_MASK));
}
static inline void cache_instr_enable(void) {
msr_set_value(msr_get_value() | MSR_ICE_MASK);
}
static inline void cache_instr_disable(void) {
msr_set_value(msr_get_value() & ~MSR_ICE_MASK);
}
static inline void cache_data_enable(void) {
msr_set_value(msr_get_value() | MSR_DCE_MASK);
}
static inline void cache_data_disable(void) {
msr_set_value(msr_get_value() & ~MSR_DCE_MASK);
}
static inline void icache_flush(void) {
int volatile temp = 0;
unsigned int volatile start = 0;
unsigned int volatile end = CONFIG_ICACHE_BYTE_SIZE;
unsigned int volatile line_length = CONFIG_ICACHE_LINE_LENGTH;
__asm__ __volatile__ (
" 1: wic %1, r0;\n\t"
"cmpu %0, %1, %2;\n\t"
"bgtid %0, 1b;\n\t"
"addk %1, %1, %3;" : :
"r" (temp), "r" (start), "r" (end), "r" (line_length)
: "memory"
);
}
static inline void dcache_flush(void) {
int volatile temp = 0;
unsigned int volatile start = 0;
unsigned int volatile end = CONFIG_DCHACE_BYTE_SIZE;
unsigned int volatile line_length = CONFIG_DCACHE_LINE_LENGTH;
__asm__ __volatile__ (
" 1: wdc %1, r0;\n\t"
"cmpu %0, %1, %2;\n\t"
"bgtid %0, 1b;\n\t"
"addk %1, %1, %3;" : :
"r" (temp), "r" (start), "r" (end), "r" (line_length)
: "memory"
);
}
static inline void cache_flush(void) {
icache_flush();
dcache_flush();
}
#endif /* MICROBLAZE_CACHE_H_ */
| 2.40625 | 2 |
2024-11-18T20:48:35.229763+00:00 | 2021-02-26T04:08:10 | 84e8e2881a189a7f0524ad1df00d834e7060e041 | {
"blob_id": "84e8e2881a189a7f0524ad1df00d834e7060e041",
"branch_name": "refs/heads/main",
"committer_date": "2021-02-26T04:08:10",
"content_id": "d455612f3e46b5b875694b6daf1f3cf537c25d8e",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "c8ddfea14a0abcac2db30dbddb1efc9c39d45bef",
"extension": "h",
"filename": "mcommon.h",
"fork_events_count": 2,
"gha_created_at": "2021-02-26T03:26:17",
"gha_event_created_at": "2021-09-15T10:09:53",
"gha_language": "C++",
"gha_license_id": "BSD-2-Clause",
"github_id": 342451286,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2092,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/mindsystem/mindsee/mindnvr/app/ui/thirdparty/include/mgncs/mcommon.h",
"provenance": "stackv2-0102.json.gz:68065",
"repo_name": "ComakeOnline/mindproject",
"revision_date": "2021-02-26T04:08:10",
"revision_id": "9ead6b9df7372f27a7c5c82d148f361aa97bab8b",
"snapshot_id": "4f9fb3e1c8ba55f1ffb0cb0ebaa94e46202fd904",
"src_encoding": "UTF-8",
"star_events_count": 5,
"url": "https://raw.githubusercontent.com/ComakeOnline/mindproject/9ead6b9df7372f27a7c5c82d148f361aa97bab8b/mindsystem/mindsee/mindnvr/app/ui/thirdparty/include/mgncs/mcommon.h",
"visit_date": "2023-08-01T14:13:47.701416"
} | stackv2 |
#ifndef MINICOMMON_H
#define MINICOMMON_H
#if defined (WIN32)
#ifdef __MGNCS_LIB__
#define MGNCS_EXPORT __declspec(dllexport)
#else
#define MGNCS_EXPORT __declspec(dllimport)
#endif
#else
#define MGNCS_EXPORT
#endif
typedef struct Allocator{
void *(*alloc)(void* pold, size_t new_size);
size_t (*getsize)(void* p);
void (*free)(void* p);
}Allocator;
Allocator * ncsGetDefaultAllocator(void);
/**
* \enum Align
*/
enum enumNCSAlign{
NCS_ALIGN_LEFT = 0,
NCS_ALIGN_RIGHT,
NCS_ALIGN_CENTER
};
/**
* \enum VAlign
*/
enum enumNCSVAlign{
NCS_VALIGN_TOP = 0,
NCS_VALIGN_BOTTOM,
NCS_VALIGN_CENTER
};
/**
* \enum ImageDrawMode
*/
enum enumNCSImageDrawMode{
NCS_DM_NORMAL = 0,
NCS_DM_SCALED,
NCS_DM_TILED
};
//support alloca
#ifdef HAVE_ALLOCA
#define ALLOCA(size) alloca(size)
#define FREEA(p)
#else
#define ALLOCA(size) malloc(size)
#define FREEA(p) free(p)
#endif
MGNCS_EXPORT void ncsDrawImage(HDC hdc, PBITMAP pbmp, const RECT * rc, int mode, int align, int valign);
#define IMG_TYPE_UNKNOWN 0
#define IMG_TYPE_BITMAP 1
#define IMG_TYPE_ICON 2
#define IMG_TYPE_MYBITMAP 4
#define IMG_FLAG_IGNORE 0
#define IMG_FLAG_UNLOAD 1
#define IMG_FLAG_RELEASE_RES 2
typedef struct _ImageDrawInfo{
unsigned char img_type;
unsigned char flag;
unsigned char drawMode;
unsigned char revert;
union{
PBITMAP pbmp;
HICON hIcon;
PMYBITMAP pmybmp;
RES_KEY key;
}img;
}ImageDrawInfo;
MGNCS_EXPORT void ncsInitDrawInfo(ImageDrawInfo *idi);
MGNCS_EXPORT void ncsCleanImageDrawInfo(ImageDrawInfo * idi);
MGNCS_EXPORT BOOL ncsSetImageDrawInfoByFile(ImageDrawInfo *idi, const char* image_file, int drawMode, BOOL bas_mybitmp);
MGNCS_EXPORT BOOL ncsSetImageDrawInfoByRes(ImageDrawInfo *idi, RES_KEY key, int drawMode, int res_type);
MGNCS_EXPORT BOOL ncsSetImageDrawInfo(ImageDrawInfo *idi, void* pimg, int drawMode, int img_type);
MGNCS_EXPORT void ncsImageDrawInfoDraw(ImageDrawInfo *idi, HDC hdc, const RECT* prc, int align, int valign);
MGNCS_EXPORT BOOL ncsImageDrawInfoGetImageSize(ImageDrawInfo *idi, int *px, int *py);
#endif
| 2.109375 | 2 |
2024-11-18T20:48:35.644640+00:00 | 2020-10-25T04:45:43 | eb90d24680f7f652227546e42a2a6274f1793210 | {
"blob_id": "eb90d24680f7f652227546e42a2a6274f1793210",
"branch_name": "refs/heads/main",
"committer_date": "2020-10-25T04:45:43",
"content_id": "13a7d091bdcc6ae119a38ac0b405352d1d979421",
"detected_licenses": [
"MIT"
],
"directory_id": "84053f08269ba4e15bf8fd3e33c70644a4db175f",
"extension": "",
"filename": "Perform addition and subtraction of Matrices",
"fork_events_count": 0,
"gha_created_at": "2020-10-25T05:37:49",
"gha_event_created_at": "2020-10-25T05:37:50",
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 307031925,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2405,
"license": "MIT",
"license_type": "permissive",
"path": "/Perform addition and subtraction of Matrices",
"provenance": "stackv2-0102.json.gz:68449",
"repo_name": "ram-jay07/Code-Overflow",
"revision_date": "2020-10-25T04:45:43",
"revision_id": "c151271615078e245b28ad94fcc3b1f7678db092",
"snapshot_id": "008eeecb11a3ba9b36649f07e9f4399dda65f716",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/ram-jay07/Code-Overflow/c151271615078e245b28ad94fcc3b1f7678db092/Perform addition and subtraction of Matrices",
"visit_date": "2023-01-04T00:41:56.028065"
} | stackv2 | #include<stdio.h>
int main()
{
printf("\n\n\t\tStudytonight - Best place to learn\n\n\n");
int n, m, c, d, first[10][10], second[10][10], sum[10][10], diff[10][10];
printf("\nEnter the number of rows and columns of the first matrix \n\n");
scanf("%d%d", &m, &n);
printf("\nEnter the %d elements of the first matrix \n\n", m*n);
for(c = 0; c < m; c++) // to iterate the rows
for(d = 0; d < n; d++) // to iterate the columns
scanf("%d", &first[c][d]);
printf("\nEnter the %d elements of the second matrix \n\n", m*n);
for(c = 0; c < m; c++) // to iterate the rows
for(d = 0; d < n; d++) // to iterate the columns
scanf("%d", &second[c][d]);
/*
printing the first matrix
*/
printf("\n\nThe first matrix is: \n\n");
for(c = 0; c < m; c++) // to iterate the rows
{
for(d = 0; d < n; d++) // to iterate the columns
{
printf("%d\t", first[c][d]);
}
printf("\n");
}
/*
printing the second matrix
*/
printf("\n\nThe second matrix is: \n\n");
for(c = 0; c < m; c++) // to iterate the rows
{
for(d = 0; d < n; d++) // to iterate the columns
{
printf("%d\t", second[c][d]);
}
printf("\n");
}
/*
finding the SUM of the two matrices
and storing in another matrix sum of the same size
*/
for(c = 0; c < m; c++)
for(d = 0; d < n; d++)
sum[c][d] = first[c][d] + second[c][d];
// printing the elements of the sum matrix
printf("\n\nThe sum of the two entered matrices is: \n\n");
for(c = 0; c < m; c++)
{
for(d = 0; d < n; d++)
{
printf("%d\t", sum[c][d]);
}
printf("\n");
}
/*
finding the DIFFERENCE of the two matrices
and storing in another matrix difference of the same size
*/
for(c = 0; c < m; c++)
for(d = 0; d < n; d++)
diff[c][d] = first[c][d] - second[c][d];
// printing the elements of the diff matrix
printf("\n\nThe difference(subtraction) of the two entered matrices is: \n\n");
for(c = 0; c < m; c++)
{
for(d = 0; d < n; d++)
{
printf("%d\t", diff[c][d]);
}
printf("\n");
}
printf("\n\n\t\t\tCoding is Fun !\n\n\n");
return 0;
}
| 3.78125 | 4 |
2024-11-18T20:48:35.809944+00:00 | 2021-11-09T02:55:05 | ae54ee90643968d4572117f00990957d9ab22635 | {
"blob_id": "ae54ee90643968d4572117f00990957d9ab22635",
"branch_name": "refs/heads/master",
"committer_date": "2021-11-09T02:55:05",
"content_id": "4d7914db4f0661e9bc5138a62d165c90c2c6096b",
"detected_licenses": [
"MIT"
],
"directory_id": "6d8ce5aeb3970e78c64fd8cc3c9d0576a5182670",
"extension": "c",
"filename": "gf3d_camera.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 426070401,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3119,
"license": "MIT",
"license_type": "permissive",
"path": "/src/gf3d_camera.c",
"provenance": "stackv2-0102.json.gz:68707",
"repo_name": "BrunnoFirme/GF3D",
"revision_date": "2021-11-09T02:55:05",
"revision_id": "d43e7b5f2a96c1f1c0062beb589598c6617d1b0c",
"snapshot_id": "c1e10348d41b57d8694465463bd3b2597d9623e6",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/BrunnoFirme/GF3D/d43e7b5f2a96c1f1c0062beb589598c6617d1b0c/src/gf3d_camera.c",
"visit_date": "2023-08-29T23:54:08.810871"
} | stackv2 | #include <string.h>
#include "simple_logger.h"
#include "gfc_matrix.h"
#include "gf3d_camera.h"
static Camera gf3d_camera = { 0 };
void gf3d_camera_get_view_mat4(Matrix4* view)
{
if (!view)return;
memcpy(view, gf3d_camera.cameraMat, sizeof(Matrix4));
}
void gf3d_camera_set_view_mat4(Matrix4* view)
{
if (!view)return;
memcpy(gf3d_camera.cameraMat, view, sizeof(Matrix4));
}
void gf3d_camera_look_at(
Vector3D position,
Vector3D target,
Vector3D up
)
{
gfc_matrix_view(
gf3d_camera.cameraMat,
position,
target,
up
);
}
void gf3d_camera_update_view()
{
/**
* Adapted from tutorial:
* https://www.3dgep.com/understanding-the-view-matrix/
*/
Vector3D xaxis, yaxis, zaxis, position;
float cosPitch = cos(gf3d_camera.rotation.x);
float sinPitch = sin(gf3d_camera.rotation.x);
float cosYaw = cos(gf3d_camera.rotation.z);
float sinYaw = sin(gf3d_camera.rotation.z);
position.x = gf3d_camera.position.x;
position.y = -gf3d_camera.position.z; //inverting for Z-up
position.z = gf3d_camera.position.y;
gfc_matrix_identity(gf3d_camera.cameraMat);
vector3d_set(xaxis, cosYaw, 0, -sinYaw);
vector3d_set(yaxis, sinYaw * sinPitch, cosPitch, cosYaw * sinPitch);
vector3d_set(zaxis, sinYaw * cosPitch, -sinPitch, cosPitch * cosYaw);
gf3d_camera.cameraMat[0][0] = xaxis.x;
gf3d_camera.cameraMat[0][1] = yaxis.x;
gf3d_camera.cameraMat[0][2] = zaxis.x;
gf3d_camera.cameraMat[1][0] = xaxis.z;
gf3d_camera.cameraMat[1][1] = yaxis.z;
gf3d_camera.cameraMat[1][2] = zaxis.z;
gf3d_camera.cameraMat[2][0] = -xaxis.y;
gf3d_camera.cameraMat[2][1] = -yaxis.y;
gf3d_camera.cameraMat[2][2] = -zaxis.y;
gf3d_camera.cameraMat[3][0] = vector3d_dot_product(xaxis, position);
gf3d_camera.cameraMat[3][1] = vector3d_dot_product(yaxis, position);
gf3d_camera.cameraMat[3][2] = vector3d_dot_product(zaxis, position);
//slog("X: %f, Y: %f, Z: %f", gf3d_camera.rotation.x, gf3d_camera.rotation.y, gf3d_camera.rotation.z);
}
void gf3d_camera_set_position(Vector3D position)
{
gf3d_camera.position.x = -position.x;
gf3d_camera.position.y = -position.y;
gf3d_camera.position.z = -position.z;
}
void gf3d_camera_set_rotation(Vector3D rotation)
{
gf3d_camera.rotation.x = -rotation.x;
gf3d_camera.rotation.y = -rotation.y;
gf3d_camera.rotation.z = -rotation.z;
}
void gf3d_camera_set_scale(Vector3D scale)
{
if (!scale.x)gf3d_camera.scale.x = 0;
else gf3d_camera.scale.x = 1 / scale.x;
if (!scale.y)gf3d_camera.scale.y = 0;
else gf3d_camera.scale.y = 1 / scale.y;
if (!scale.z)gf3d_camera.scale.z = 0;
else gf3d_camera.scale.z = 1 / scale.z;
}
void gf3d_camera_move_position(Vector3D offset)
{
gf3d_camera.position.x -= offset.x;
gf3d_camera.position.y -= offset.y;
gf3d_camera.position.z -= offset.z;
}
void gf3d_camera_move_rotation(Vector3D offset)
{
gf3d_camera.rotation.x -= offset.x;
gf3d_camera.rotation.y -= offset.y;
gf3d_camera.rotation.z -= offset.z;
}
/*eol@eof*/ | 2.53125 | 3 |
2024-11-18T20:48:36.020109+00:00 | 2021-11-02T23:36:59 | 72f02c6b66e7a82a37e09dcd13d3c1a4d42c0fce | {
"blob_id": "72f02c6b66e7a82a37e09dcd13d3c1a4d42c0fce",
"branch_name": "refs/heads/main",
"committer_date": "2021-11-02T23:36:59",
"content_id": "9d9d3d97ba07de2e59fca633ed52ee742818c751",
"detected_licenses": [
"MIT"
],
"directory_id": "0b894136e13f6e00ea175e28eb47a0456e6a8487",
"extension": "c",
"filename": "TestSort.c",
"fork_events_count": 0,
"gha_created_at": "2021-10-08T21:46:55",
"gha_event_created_at": "2021-10-08T21:46:56",
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 415134918,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3199,
"license": "MIT",
"license_type": "permissive",
"path": "/examples/sort/test/TestSort.c",
"provenance": "stackv2-0102.json.gz:68966",
"repo_name": "BernardoKoefender/Unity",
"revision_date": "2021-11-02T23:36:59",
"revision_id": "5203df6c3b1ef8b70ae6bcbed6ac544cb4192f90",
"snapshot_id": "f08a9d466324b0b74f8f420f4eedeb255b8a3dbb",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/BernardoKoefender/Unity/5203df6c3b1ef8b70ae6bcbed6ac544cb4192f90/examples/sort/test/TestSort.c",
"visit_date": "2023-08-23T08:27:23.595518"
} | stackv2 | //This code is based on the example "foo".
//Authors:
// Bernardo Koefender - @BernardoKoefender
// Frederico Arnaldo Ballve Neto - @fredballve
// Willian Analdo nunes - @Willian-Nunes
#include "sort.h"
#include "unity.h"
#include "unity_fixture.h"
TEST_GROUP(Sort);
TEST_SETUP(Sort)
{
}
TEST_TEAR_DOWN(Sort)
{
}
TEST(Sort, TestSort1)
{
// Test ordered solution
int vec[] = {3,1,2};
int vec_o[] = {1,2,3};
int size = 3;
sort(vec, size);
TEST_ASSERT_EQUAL_INT_ARRAY(vec_o, vec, size);
}
TEST(Sort, TestSort2)
{
// Test ordered solution
int vec[] = {3,0,-40};
int vec_o[] = {-40,0,3};
int size = 3;
sort(vec, size);
TEST_ASSERT_EQUAL_INT_ARRAY(vec_o, vec, size);
}
TEST(Sort, TestSort3)
{
// Test if sort is not ordering in descending order
int vec[] = {3,2,1};
int vec_o[] = {1,2,3};
int size = 3;
sort(vec, size);
TEST_ASSERT_EQUAL_INT_ARRAY(vec_o, vec, size );
}
TEST(Sort, TestSort4)
{
// Test what happens when the vector is already ordered
int vec[] = {1,2,3};
int vec_o[] = {1,2,3};
int size = 3;
sort(vec, size);
TEST_ASSERT_EQUAL_INT_ARRAY(vec_o, vec, size );
}
TEST(Sort, TestSort5)
{
// Assert that the resulting vector is not NULLPTR
int vec[] = {3,0,-40};
int size = 3;
sort(vec, size);
TEST_ASSERT_NOT_NULL(vec);
}
TEST(Sort, TestSort6)
{
// Assert that vector's size match
int vec[] = {3,0,-40};
int size = 3;
sort(vec, size);
TEST_ASSERT_TRUE( (sizeof(vec)/sizeof(vec[0])) == size);
}
TEST(Sort, TestSort7)
{
// Assert memory address hasn't changed. Pointless?
int vec[] = {3,0,10};
int size = 3;
int *p = vec;
sort(vec, size);
TEST_ASSERT_EQUAL_PTR( p, &vec);
}
TEST(Sort, TestSort8)
{
// Test different sizes (excluding last element)
int vec[] = {5,4,3,2,1};
int vec_o[] = {2,3,4,5,1};
int size = 4;
sort(vec, size);
TEST_ASSERT_EQUAL_INT_ARRAY(vec_o, vec, size+1);
}
TEST(Sort, TestSort9)
{
// Test different sizes (excluding first element)
int vec[] = {5,4,3,2,1};
int vec_o[] = {5,1,2,3,4};
int size = 4;
sort(&vec[1], size); // Confere a sintaxe do ponteiro do vec
TEST_ASSERT_EQUAL_INT_ARRAY(vec_o, vec, size+1);
}
TEST(Sort, TestSort10)
{
// Test all negative elements
int vec[] = {-3,-1,-5,-4,-2};
int vec_o[] = {-5,-4,-3,-2,-1};
int size = 5;
sort(vec, size);
TEST_ASSERT_EQUAL_INT_ARRAY(vec_o, vec, size);
}
TEST(Sort, TestSort11)
{
// Test equal elements
int vec[] = {1,2,0,1};
int vec_o[] = {0,1,1,2};
int size = 4;
sort(vec, size);
TEST_ASSERT_EQUAL_INT_ARRAY(vec_o, vec, size);
}
TEST(Sort, TestSort12)
{
// Test only one element array
int vec[] = {78};
int vec_o[] = {78};
int size = 1;
sort(vec, size);
TEST_ASSERT_EQUAL_INT_ARRAY(vec_o, vec, size);
}
TEST(Sort, TestSort13)
{
// Test empty array
int vec[] = {};
int *vec_o = vec;
int size = 0;
sort(vec, size);
TEST_ASSERT_EQUAL(vec_o, vec);
}
//TEST(Sort, TestSort14)
//{
// // THIS TEST FAILS, HOW TO DO ASSERT_NOT_EQUAL???
// int vec[] = {5,4,3,2,1};
// int vec_o[] = {1,2,3,4,5};
// int size = 10;
//
// sort(vec, size);
// TEST_ASSERT_EQUAL_INT_ARRAY(vec_o, vec, size-5);
//} | 2.953125 | 3 |
2024-11-18T20:48:36.195524+00:00 | 2020-12-10T09:01:19 | 8011f1148f962f05505b63cbfc2e36d20f77ebea | {
"blob_id": "8011f1148f962f05505b63cbfc2e36d20f77ebea",
"branch_name": "refs/heads/master",
"committer_date": "2020-12-10T09:02:34",
"content_id": "b6513ea1aa4050be1249358f76ca1dfaff5ffe37",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "ece1b77232731ca6541064c211d42bd713c064d6",
"extension": "h",
"filename": "connection.h",
"fork_events_count": 0,
"gha_created_at": "2019-03-06T07:46:50",
"gha_event_created_at": "2019-10-08T11:59:30",
"gha_language": "C",
"gha_license_id": "Apache-2.0",
"github_id": 174097160,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 6102,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/hicn-light/src/hicn/core/connection.h",
"provenance": "stackv2-0102.json.gz:69094",
"repo_name": "icn-team/hicn",
"revision_date": "2020-12-10T09:01:19",
"revision_id": "72a9acca4500a9c07a4661fe112a1a212567fc9f",
"snapshot_id": "bf38d30d67824803bfce743f1cc633ff53f0af04",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/icn-team/hicn/72a9acca4500a9c07a4661fe112a1a212567fc9f/hicn-light/src/hicn/core/connection.h",
"visit_date": "2021-01-26T04:06:28.696270"
} | stackv2 | /*
* Copyright (c) 2017-2019 Cisco and/or its affiliates.
* 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.
*/
/**
* @file connection.h
* @brief Wrapper for different types of connections
*
* A connection wraps a specific set of {@link IoOperations}. Those operations
* allow for input and output. Connections get stored in the Connection Table.
*
*/
#ifndef connection_h
#define connection_h
#include <hicn/hicn-light/config.h>
#include <hicn/core/connectionState.h>
#include <hicn/io/ioOperations.h>
#include <hicn/utils/address.h>
#ifdef WITH_MAPME
typedef enum {
CONNECTION_EVENT_CREATE,
CONNECTION_EVENT_DELETE,
CONNECTION_EVENT_UPDATE,
CONNECTION_EVENT_SET_UP,
CONNECTION_EVENT_SET_DOWN,
CONNECTION_EVENT_PRIORITY_CHANGED,
CONNECTION_EVENT_TAGS_CHANGED,
} connection_event_t;
#endif /* WITH_MAPME */
#ifdef WITH_POLICY
#include <hicn/policy.h>
#endif /* WITH_POLICY */
struct connection;
typedef struct connection Connection;
/**
* Creates a connection object.
*/
Connection *connection_Create(IoOperations *ops);
/**
* @function connection_Release
* @abstract Releases a reference count, destroying on last release
* @discussion
* Only frees the memory on the final reference count. The pointer will
* always be NULL'd.
*/
void connection_Release(Connection **connectionPtr);
/**
* @function connection_Acquire
* @abstract A reference counted copy.
* @discussion
* A shallow copy, they share the same memory.
*/
Connection *connection_Acquire(Connection *connection);
/**
* @function connection_Send
* @abstract Sends the message on the connection
* @return true if message sent, false if connection not up
*/
bool connection_Send(const Connection *conn, Message *message);
/**
* @function connection_SendIOVBuffer
* @abstract Sends an IOV buffer
*/
bool connection_SendIOVBuffer(const Connection *conn, struct iovec *msg,
size_t size);
/**
* @function connection_SendBuffer
* @abstract Sends a buffer
*/
bool connection_SendBuffer(const Connection *conn, u8 * buffer, size_t length);
/**
* Return the `IoOperations` instance associated with the specified `Connection`
* instance.
* @param [in] connection The allocated connection
* @return a pointer to the IoOperations instance associated by th specified
* connection.
*/
IoOperations *connection_GetIoOperations(const Connection *conn);
/**
* Returns the unique identifier of the connection
* Calls the underlying IoOperations to fetch the connection id
* @param [in] connection The allocated connection
* @return unsigned The unique connection id
*/
unsigned connection_GetConnectionId(const Connection *conn);
/**
* Returns the (remote, local) address pair that describes the connection
* @param [in] connection The allocated connection
* @return non-null The connection's remote and local address
* @return null Should never return NULL
*/
const AddressPair *connection_GetAddressPair(const Connection *conn);
/**
* Checks if the connection is in the "up" state
* @param [in] connection The allocated connection
* @return true The connection is in the "up" state
* @return false The connection is not in the "up" state
*/
bool connection_IsUp(const Connection *conn);
/**
* Checks if the connection is to a Local/Loopback address
*
* A local connection is PF_LOCAL (PF_UNIX) and a loopback connection is
* 127.0.0.0/8 or ::1 for IPv6.
*
* @param [in] connection The allocated connection
*
* @retval true The connection is local or loopback
* @retval false The connection is not local or loopback
*/
bool connection_IsLocal(const Connection *conn);
/**
* Returns an opaque pointer representing the class of the Io Operations
*
* Returns an opaque pointer that an implementation can use to detect if
* the connection is based on that class.
*
* @param [in] conn The Connection to analyze
*
* @return non-null An opaque pointer for each concrete implementation
*/
const void *connection_Class(const Connection *conn);
bool connection_ReSend(const Connection *conn, Message *message,
bool notification);
void connection_Probe(Connection *conn, uint8_t *probe);
void connection_HandleProbe(Connection *conn, uint8_t *message);
void connection_AllowWldrAutoStart(Connection *conn, bool allow);
void connection_EnableWldr(Connection *conn);
void connection_DisableWldr(Connection *conn);
bool connection_HasWldr(const Connection *conn);
bool connection_WldrAutoStartAllowed(const Connection *conn);
void connection_DetectLosses(Connection *conn, Message *message);
void connection_HandleWldrNotification(Connection *conn, Message *message);
connection_state_t connection_GetState(const Connection *conn);
void connection_SetState(Connection *conn, connection_state_t state);
connection_state_t connection_GetAdminState(const Connection *conn);
void connection_SetAdminState(Connection *conn, connection_state_t admin_state);
#ifdef WITH_POLICY
uint32_t connection_GetPriority(const Connection *conn);
void connection_SetPriority(Connection *conn, uint32_t priority);
#endif /* WITH_POLICY */
const char * connection_GetInterfaceName(const Connection * conn);
#ifdef WITH_POLICY
void connection_AddTag(Connection *conn, policy_tag_t tag);
void connection_RemoveTag(Connection *conn, policy_tag_t tag);
policy_tags_t connection_GetTags(const Connection *conn);
void connection_SetTags(Connection *conn, policy_tags_t tags);
void connection_ClearTags(Connection *conn);
int connection_HasTag(const Connection *conn, policy_tag_t tag);
#endif /* WITH_POLICY */
#endif // connection_h
| 2.234375 | 2 |
2024-11-18T20:48:36.878085+00:00 | 2015-10-08T06:10:05 | 59c3dd9e46da2cb085ffbb6be7bc22d110f0c6ab | {
"blob_id": "59c3dd9e46da2cb085ffbb6be7bc22d110f0c6ab",
"branch_name": "refs/heads/master",
"committer_date": "2015-10-08T06:10:05",
"content_id": "9c674f84601fa1bd1c3d4568b2a01f5197fe4b45",
"detected_licenses": [
"MIT"
],
"directory_id": "75780b68b6816e3e3715dce170d07bc2f7211d97",
"extension": "c",
"filename": "search_free_block.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": 1584,
"license": "MIT",
"license_type": "permissive",
"path": "/search_free_block.c",
"provenance": "stackv2-0102.json.gz:69354",
"repo_name": "JonathanOkz/malloc",
"revision_date": "2015-10-08T06:10:05",
"revision_id": "7e79757ae58bd83f9bbe0811edd9c3655aea8410",
"snapshot_id": "51968bedadaf0c7c0e40ab6ada1d3ad4135a6a96",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/JonathanOkz/malloc/7e79757ae58bd83f9bbe0811edd9c3655aea8410/search_free_block.c",
"visit_date": "2021-05-29T15:34:37.456093"
} | stackv2 | /*
** search_free_block.c
**
** Made by oleszkiewicz Jonathan
** Email <JonathanOlesz@gmail.com>
**
** Started on Sun Feb 16 22:04:52 2014 oleszkiewicz
** Last update Sun Feb 16 22:16:04 2014 oleszkiewicz
*/
#include "malloc.h"
/**
* recherche un block de données free de taille >= size + sizeof(t_block)
* @param size: taille de l'allocation mémoire demandée
* @return pointeur sur la sctucture de type t_block contenant les informations sur l'allocation mémoire
*/
t_block *free_block_higher_malloc_size(size_t size)
{
t_block *pnt;
pnt = list.beg;
while (pnt != NULL && !(pnt->free == true && pnt->size >= size + sizeof(t_block)))
pnt = pnt->next;
return pnt;
}
/**
* recherche un block de données free de taille == size
* @param size: taille de l'allocation mémoire demandée
* @return pointeur sur la sctucture de type t_block contenant les informations sur l'allocation mémoire
*/
t_block *free_block_equal_malloc_size(size_t size)
{
t_block *pnt;
pnt = list.beg;
while (pnt != NULL && !(pnt->free == true && pnt->size == size))
pnt = pnt->next;
return pnt;
}
/**
* recherche un block de données free de taille >= size
* @param size: taille de l'allocation mémoire demandée
* @return pointeur sur la sctucture de type t_block contenant les informations sur l'allocation mémoire
*/
t_block *search_free_block(size_t size)
{
t_block *pnt;
pnt = free_block_equal_malloc_size(size);
if (pnt == NULL)
pnt = free_block_higher_malloc_size(size);
return pnt;
}
| 3.0625 | 3 |
2024-11-18T20:48:37.397108+00:00 | 2017-07-05T16:50:53 | 31e72238d363bb65f51d983bcbc50329d6cea6f3 | {
"blob_id": "31e72238d363bb65f51d983bcbc50329d6cea6f3",
"branch_name": "refs/heads/master",
"committer_date": "2017-07-05T16:50:53",
"content_id": "a55617ba58b76d11a2bda7d83c758687e4abb4e0",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "57fbc5752da661c7e39ec3c92de05f7a538a991e",
"extension": "c",
"filename": "general.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": 1983,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/src/general.c",
"provenance": "stackv2-0102.json.gz:69870",
"repo_name": "htoraby/m_list",
"revision_date": "2017-07-05T16:50:53",
"revision_id": "92823d5a329c2c3c92f3265773d15a629f1bf668",
"snapshot_id": "b7a44f223aa4e8031a3ff4f0a8af33dc8aa200e3",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/htoraby/m_list/92823d5a329c2c3c92f3265773d15a629f1bf668/src/general.c",
"visit_date": "2021-06-25T02:44:17.114543"
} | stackv2 | #include <string.h>
#include "m_list.h"
int
m_list_init(m_list* list)
{
if (list == NULL)
return M_LIST_E_NULL;
list->first = NULL;
list->last = NULL;
list->length = 0;
list->index = NULL;
return M_LIST_OK;
}
int
m_list_length(m_list* list, uint64_t* out_length)
{
if (list == NULL || out_length == NULL)
return M_LIST_E_NULL;
*out_length = list->length;
return M_LIST_OK;
}
int
m_list_copy(m_list* list_src, m_list* list_dst, uint8_t copy)
{
m_list_elem* runner_src;
m_list_elem* elem;
if (list_src == NULL || list_dst == NULL)
return M_LIST_E_NULL;
runner_src = list_src->first;
while (runner_src != NULL) {
elem = malloc(sizeof(m_list_elem));
elem->size = runner_src->size;
if (runner_src->copy == M_LIST_COPY_DEEP && copy == M_LIST_COPY_DEEP) {
elem->copy = copy;
if (runner_src->data == NULL) {
elem->data = NULL;
} else {
elem->data = malloc(runner_src->size);
memcpy(elem->data, runner_src->data, runner_src->size);
}
}
if (runner_src->copy == M_LIST_COPY_SHALLOW) {
elem->data = runner_src->data;
elem->copy = copy;
}
if (list_dst->first == NULL) {
list_dst->first = elem;
list_dst->last = elem;
elem->next = NULL;
elem->prev = NULL;
} else {
list_dst->last->next = elem;
elem->prev = list_dst->last;
elem->next = NULL;
list_dst->last = elem;
}
list_dst->length++;
runner_src = runner_src->next;
}
return M_LIST_OK;
}
int
m_list_error_string(int code, const char** out_error_string)
{
static const char* error_strings[] = {
"OK",
"True",
"False",
"One of the objects is NULL",
"Index out of bounds",
"No such element is present in the list",
"Unknown copy method",
"Unknown insert location",
"Unknown return code"
};
if (out_error_string == NULL)
return M_LIST_E_NULL;
if (code < 0 || code > M_LIST_E_MAX) {
*out_error_string = NULL;
return M_LIST_E_UNKNOWN_CODE;
}
*out_error_string = error_strings[code];
return M_LIST_OK;
}
| 2.859375 | 3 |
2024-11-18T20:48:37.940784+00:00 | 2018-04-08T17:33:38 | eba2aa6e72d8dbf74632e78d2b29a76bb3c552c5 | {
"blob_id": "eba2aa6e72d8dbf74632e78d2b29a76bb3c552c5",
"branch_name": "refs/heads/master",
"committer_date": "2018-04-08T17:33:38",
"content_id": "0d06065361aa6b23ceb1ecaf0bcb834581e19e12",
"detected_licenses": [
"MIT"
],
"directory_id": "68ca08feba3026d751d1eed2bdb3b4b09c63d1f5",
"extension": "c",
"filename": "Exer_13_3.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 126492222,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 692,
"license": "MIT",
"license_type": "permissive",
"path": "/Ch13/Exercises/Exer_13_3.c",
"provenance": "stackv2-0102.json.gz:70257",
"repo_name": "RingZEROtlf/C-Primer-Plus",
"revision_date": "2018-04-08T17:33:38",
"revision_id": "25d2bc828b7b596ea2708f4a4fc6caeec8bcace4",
"snapshot_id": "d942997aa401b739f792e20b98ba596790ecc280",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/RingZEROtlf/C-Primer-Plus/25d2bc828b7b596ea2708f4a4fc6caeec8bcace4/Ch13/Exercises/Exer_13_3.c",
"visit_date": "2021-04-12T09:45:20.055205"
} | stackv2 | #include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main(int argc, char *argv[])
{
if (argc != 2) {
printf("Usage: %s filename\n", argv[0]);
exit(EXIT_FAILURE);
}
FILE *fp = fopen(argv[1], "r+");
if (fp == NULL) {
printf("Can't open file.\n");
exit(EXIT_FAILURE);
}
char character;
fseek(fp, 0L, SEEK_END);
long file_length = ftell(fp);
printf("%ld\n", file_length);
fseek(fp, 0L, SEEK_SET);
for (long i = 0L; i < file_length; i++) {
fseek(fp, i, SEEK_SET);
character = fgetc(fp);
fseek(fp, i, SEEK_SET);
fputc(toupper(character), fp);
}
fclose(fp);
return 0;
} | 3.140625 | 3 |
2024-11-18T20:48:39.025951+00:00 | 2019-03-07T04:12:40 | d276e32e2f1a60b110fe3361e7576d8b332f0f99 | {
"blob_id": "d276e32e2f1a60b110fe3361e7576d8b332f0f99",
"branch_name": "refs/heads/master",
"committer_date": "2019-03-07T04:12:40",
"content_id": "0b63b4b2e3ab6664b559662ec6207afc4770fcf8",
"detected_licenses": [
"MIT",
"Apache-2.0"
],
"directory_id": "6fef398b4f213d3883a8392855a67002eda940e8",
"extension": "c",
"filename": "lvgl_fs.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": 5330,
"license": "MIT,Apache-2.0",
"license_type": "permissive",
"path": "/external/littleVGL/lvgl_fs.c",
"provenance": "stackv2-0102.json.gz:71163",
"repo_name": "alveraboquet/TizenRT-lvgl",
"revision_date": "2019-03-07T04:12:40",
"revision_id": "6d896e38275c6efc6d85cd08839d10a491af038e",
"snapshot_id": "38ed27630d3b78aa8fd90c73acd484fe933f6efb",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/alveraboquet/TizenRT-lvgl/6d896e38275c6efc6d85cd08839d10a491af038e/external/littleVGL/lvgl_fs.c",
"visit_date": "2023-03-18T11:34:31.445046"
} | stackv2 | /*
*/
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <errno.h>
#include <lvgl.h>
/* Stub for LVGL ufs (ram based FS) init function
* as we use Zephyr FS API instead
*/
void lv_ufs_init(void)
{
}
bool lvgl_fs_ready(void)
{
return true;
}
static lv_fs_res_t errno_to_lv_fs_res(int err)
{
switch (err) {
case 0:
return LV_FS_RES_OK;
case -EIO:
/*Low level hardware error*/
return LV_FS_RES_HW_ERR;
case -EBADF:
/*Error in the file system structure */
return LV_FS_RES_FS_ERR;
case -ENOENT:
/*Driver, file or directory is not exists*/
return LV_FS_RES_NOT_EX;
case -EFBIG:
/*Disk full*/
return LV_FS_RES_FULL;
case -EACCES:
/*Access denied. Check 'fs_open' modes and write protect*/
return LV_FS_RES_DENIED;
case -EBUSY:
/*The file system now can't handle it, try later*/
return LV_FS_RES_BUSY;
case -ENOMEM:
/*Not enough memory for an internal operation*/
return LV_FS_RES_OUT_OF_MEM;
case -EINVAL:
/*Invalid parameter among arguments*/
return LV_FS_RES_INV_PARAM;
default:
return LV_FS_RES_UNKNOWN;
}
}
static lv_fs_res_t lvgl_fs_open(void *file, const char *path,
lv_fs_mode_t mode)
{
int err = 0;
int oflag = 0;
switch(mode) {
case LV_FS_MODE_WR:
oflag = O_RDWR;
break;
case LV_FS_MODE_RD:
oflag = O_RDONLY;
break;
default:
return LV_FS_RES_INV_PARAM;
}
int *pfd = (int*)file;
*pfd = open(path, oflag);
if(*pfd < 0)
{
err = get_errno();
}
return errno_to_lv_fs_res(err);
}
static lv_fs_res_t lvgl_fs_close(void *file)
{
int *pfd = (int*)file;
close(*pfd);
return LV_FS_RES_OK;
}
static lv_fs_res_t lvgl_fs_remove(const char *path)
{
int err = 0;
if (unlink(path) != OK)
{
err = get_errno();
}
return errno_to_lv_fs_res(err);
}
static lv_fs_res_t lvgl_fs_read(void *file, void *buf, uint32_t btr, uint32_t *br)
{
int result;
int *pfd = (int*)file;
result = read(*pfd, buf, btr);
if (result > 0) {
if (br != NULL) {
*br = result;
}
result = 0;
} else {
if (br != NULL) {
*br = 0;
}
result = get_errno();
}
return errno_to_lv_fs_res(result);
}
static lv_fs_res_t lvgl_fs_write(void *file, const void *buf, uint32_t btw, uint32_t *bw)
{
int result;
int *pfd = (int*)file;
result = write(*pfd, buf, btw);
if (result == btw) {
if (bw != NULL) {
*bw = btw;
}
result = 0;
} else if (result < 0) {
if (bw != NULL) {
*bw = 0;
}
result = get_errno();
} else {
if (bw != NULL) {
*bw = result;
}
result = -EFBIG;
}
return errno_to_lv_fs_res(result);
}
static lv_fs_res_t lvgl_fs_seek(void *file, uint32_t pos)
{
int err = 0;
int *pfd = (int*)file;
if (lseek(*pfd, pos, SEEK_SET) == -1) {
err = get_errno();
}
return errno_to_lv_fs_res(err);
}
static lv_fs_res_t lvgl_fs_tell(void *file, uint32_t *pos_p)
{
int err = 0;
int *pfd = (int*)file;
//we use POSIX fs API here, no std io buff, just get current fs pos
// FILE *f = fdopen(*pfd, 'r');
// long len = (uint32_t*)ftell(f);
long len = lseek(*pfd, 0, SEEK_CUR);
if (len != -1) {
*pos_p = (uint32_t)len;
return LV_FS_RES_OK;
}
else {
err = get_errno();
}
return errno_to_lv_fs_res(err);;
}
static lv_fs_res_t lvgl_fs_trunc(void *file)
{
/*Not used in lvgl*/
return LV_FS_RES_NOT_IMP;
}
static lv_fs_res_t lvgl_fs_size(void *file, uint32_t *fsize)
{
int err = 0;
off_t org_pos;
/* LVGL does not provided path but pointer to file struct as such
* we can not use fs_stat, instead use a combination of fs_tell and
* fs_seek to get the files size.
*/
int *pfd = (int*)file;
org_pos = lseek(*pfd, 0, SEEK_CUR);
err = lseek(*pfd, 0, SEEK_END);
if (err == -1) {
*fsize = 0;
err = get_errno();
return errno_to_lv_fs_res(err);
}
*fsize = err + 1;
lseek(*pfd, org_pos, SEEK_SET);
return LV_FS_RES_OK;
}
static lv_fs_res_t lvgl_fs_rename(const char *from, const char *to)
{
int err;
err = rename(from, to);
return errno_to_lv_fs_res(err);
}
static lv_fs_res_t lvgl_fs_free(uint32_t *total_p, uint32_t *free_p)
{
/* We have no easy way of telling the total file system size.
* Zephyr can only return this information per mount point.
*/
return LV_FS_RES_NOT_IMP;
}
static lv_fs_res_t lvgl_fs_dir_open(void *dir, const char *path)
{
/*Currently not used in lvgl*/
return LV_FS_RES_NOT_IMP;
}
static lv_fs_res_t lvgl_fs_dir_read(void *dir, char *fn)
{
/* LVGL expects a string as return parameter but the format of the
* string is not documented.
*/
return LV_FS_RES_NOT_IMP;
}
static lv_fs_res_t lvgl_fs_dir_close(void *dir)
{
/*Currently not used in lvgl*/
return LV_FS_RES_NOT_IMP;
}
void lvgl_fs_init(void)
{
lv_fs_drv_t fs_drv;
memset(&fs_drv, 0, sizeof(lv_fs_drv_t));
fs_drv.file_size = sizeof(int); //sizeof of file struct, ony save fd here
fs_drv.rddir_size = sizeof(void*);
fs_drv.letter = '/';
fs_drv.ready = lvgl_fs_ready;
fs_drv.open = lvgl_fs_open;
fs_drv.close = lvgl_fs_close;
fs_drv.remove = lvgl_fs_remove;
fs_drv.read = lvgl_fs_read;
fs_drv.write = lvgl_fs_write;
fs_drv.seek = lvgl_fs_seek;
fs_drv.tell = lvgl_fs_tell;
fs_drv.trunc = lvgl_fs_trunc;
fs_drv.size = lvgl_fs_size;
//fs_drv.rename = lvgl_fs_rename;
fs_drv.free = lvgl_fs_free;
fs_drv.dir_open = lvgl_fs_dir_open;
fs_drv.dir_read = lvgl_fs_dir_read;
fs_drv.dir_close = lvgl_fs_dir_close;
lv_fs_add_drv(&fs_drv);
}
| 2.5 | 2 |
2024-11-18T20:48:39.114599+00:00 | 2021-01-28T18:34:37 | 1a655fa9691fbef1df572ec5c401e137d79f7e99 | {
"blob_id": "1a655fa9691fbef1df572ec5c401e137d79f7e99",
"branch_name": "refs/heads/main",
"committer_date": "2021-01-28T18:34:37",
"content_id": "63990a1e787c975aa8f4bd0d77184fc052a5cbc6",
"detected_licenses": [
"MIT"
],
"directory_id": "dc184e8350b88926da2c97aa10643d4aef2aaab0",
"extension": "c",
"filename": "task_console.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 317720205,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2833,
"license": "MIT",
"license_type": "permissive",
"path": "/task_console.c",
"provenance": "stackv2-0102.json.gz:71292",
"repo_name": "MichaelSexton21/Fruit_Eater",
"revision_date": "2021-01-28T18:34:37",
"revision_id": "dafe41a9be3fd2e5743f48a20ddaaf24b224880d",
"snapshot_id": "2b7f5dff004f90618e3abcc683b28dabdf19cfa1",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/MichaelSexton21/Fruit_Eater/dafe41a9be3fd2e5743f48a20ddaaf24b224880d/task_console.c",
"visit_date": "2023-03-03T03:59:58.826757"
} | stackv2 | /*
* task_console.c
*
* Created on: Nov 25, 2020
* Authors: Michael Sexton and Jack Bybel
*
*/
#include <main.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// This file is only used for debugging purposes
QueueHandle_t Queue_Console;
SemaphoreHandle_t Sem_Console;
#define RX_ARRAY_SIZE 10
// Global variables used to store incoming data from RXBUF.
volatile char RX_ARRAY[RX_ARRAY_SIZE];
volatile uint16_t RX_INDEX=0;
/******************************************************************************
* This function configures the eUSCI_A0 to be a UART that communicates at
* 115200 8N1.
******************************************************************************/
static void console_hw_init(void)
{
// Configure the IO pins used for the UART
// set 2-UART pin as secondary function
P1->SEL0 |= BIT2 | BIT3;
P1->SEL1 &= ~(BIT2 | BIT3);
EUSCI_A0->CTLW0 |= EUSCI_A_CTLW0_SWRST; // Put eUSCI in reset
EUSCI_A0->CTLW0 = EUSCI_A_CTLW0_SWRST | // Remain eUSCI in reset
EUSCI_B_CTLW0_SSEL__SMCLK; // Configure eUSCI clock source
// Baurd Rate calculation
// 24000000/(16*115200) = 13.020833333
// Fractional portion = 0.20833333
// UCBRFx = int ( (13.020833333-13)*16) = 0
EUSCI_A0->BRW = 13; // 24000000/16/115200
// Set the fractional portion of the baud rate and turn
// on oversampling
EUSCI_A0->MCTLW = (0 << EUSCI_A_MCTLW_BRF_OFS) | EUSCI_A_MCTLW_OS16;
// Enable eUSCI in UART mode
EUSCI_A0->CTLW0 &= ~EUSCI_A_CTLW0_SWRST;
// Clear any outstanding interrupts.
EUSCI_A0->IFG &= ~(EUSCI_A_IFG_RXIFG | EUSCI_A_IFG_TXIFG);
// Enable Rx Interrupt
EUSCI_A0->IE |= EUSCI_A_IE_RXIE;
// Enable EUSCIA0 Interrupt
NVIC_EnableIRQ(EUSCIA0_IRQn);
NVIC_SetPriority(EUSCIA0_IRQn, 2);
// Prime the pump
EUSCI_A0->TXBUF = 0;
}
/******************************************************************************
* This function initializes the eUSCI_A0 hardware by calling console_hw_init().
* It will also initialize Sem_Console.
******************************************************************************/
void Task_Console_Init(void)
{
// Initialize the array used to hold UART data
memset(RX_ARRAY,0,RX_ARRAY_SIZE);
// Initialize UART
console_hw_init();
// Initialize the binary semaphore used to provide mutual exclusion to
// the UART.
Sem_Console = xSemaphoreCreateBinary();
xSemaphoreGive(Sem_Console);
}
/*****************************************************
* Needed to get printf to work using polling
*****************************************************/
int fputc(int c, FILE* stream)
{
// while UART is busy, wait
while(EUSCI_A0->STATW & EUSCI_A_STATW_BUSY){};
//transmit the character
EUSCI_A0->TXBUF = c;
return 0;
}
| 2.8125 | 3 |
2024-11-18T20:48:39.411492+00:00 | 2018-04-05T17:57:20 | f36a734a2a3a3c934fb61db9c11faa19c0fac07c | {
"blob_id": "f36a734a2a3a3c934fb61db9c11faa19c0fac07c",
"branch_name": "refs/heads/master",
"committer_date": "2018-04-05T17:57:20",
"content_id": "1508912badc841faf9834dcdb1363fbfea7ef5b8",
"detected_licenses": [
"MIT"
],
"directory_id": "cb0600d3f91eb4dbcf80961415ea4e3652194e0d",
"extension": "c",
"filename": "chgrp.c",
"fork_events_count": 3,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 117159508,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 804,
"license": "MIT",
"license_type": "permissive",
"path": "/xv6-pdx/chgrp.c",
"provenance": "stackv2-0102.json.gz:71550",
"repo_name": "h4pdx/cs333_xv6",
"revision_date": "2018-04-05T17:57:20",
"revision_id": "7c734c70ccbac2b11782741f2a3e1f10e93ac06b",
"snapshot_id": "e359030a1ddfd9213a680f70f82f650e414ae7e4",
"src_encoding": "UTF-8",
"star_events_count": 4,
"url": "https://raw.githubusercontent.com/h4pdx/cs333_xv6/7c734c70ccbac2b11782741f2a3e1f10e93ac06b/xv6-pdx/chgrp.c",
"visit_date": "2021-03-27T12:46:05.154112"
} | stackv2 | #ifdef CS333_P5
#include "types.h"
#include "user.h"
// User command for chgrp system call
// Takes a pathname and a GID argument
// reverses order of arguents for system call
// syscall - chmod(TARGET, GROUP);
// usercmd - chmod GROUP TARGET
int
main(int argc, char **argv) {
if (argc != 3) {
printf(1, "Invalid arguments.\n"); // must be 3 - chgrp TARGET GROUP
exit();
}
char * path;
int group, rc;
group = atoi(argv[1]); // convert to int GID
path = argv[2]; // already a char*
rc = chgrp(path, group); // reverse order for system call
if (rc < 0) {
if (rc == -1) {
printf(1, "chgrp: Invalid pathname.\n");
}
else if (rc == -2) {
printf(1, "chgrp: Invalid GID.\n");
}
}
exit();
}
#endif
| 2.90625 | 3 |
2024-11-18T20:48:40.163515+00:00 | 2017-10-21T20:00:27 | be4681290aae833517e7ed1eb9f8eeed0d42805a | {
"blob_id": "be4681290aae833517e7ed1eb9f8eeed0d42805a",
"branch_name": "refs/heads/master",
"committer_date": "2017-10-21T20:00:27",
"content_id": "000fbe0eaea38ce6b949aad839e401f8610d2ae6",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "0d87634341940432c3ea35435441204c4500fa40",
"extension": "c",
"filename": "arraysum.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 107717997,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 458,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/Assignment/bucketsort/arraysum.c",
"provenance": "stackv2-0102.json.gz:72195",
"repo_name": "assaaassin/HPC",
"revision_date": "2017-10-21T20:00:27",
"revision_id": "462d3ffd0263bb4511b80a033755c81506351ce9",
"snapshot_id": "2c416bbb052329ce812cffc868baea3ddd3068c7",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/assaaassin/HPC/462d3ffd0263bb4511b80a033755c81506351ce9/Assignment/bucketsort/arraysum.c",
"visit_date": "2021-07-18T00:53:12.841038"
} | stackv2 | #include <stdio.h>
#include <stdlib.h>
// #include <mpi.h>
#define max_rows 1000
int array[max_rows];
int main(int argc, char **argv){
int i, num_rows;
long int sum;
printf("enter the amount of numbers: \n");
scanf("%d", &num_rows);
if (num_rows > max_rows){
printf("Too many numbers.\n");
exit(1);
}
for (i = 0; i < num_rows; i++){
array[i] = i;
}
sum = 0;
for (i = 0; i < num_rows; i++){
sum += array[i];
}
printf("Sum: %i\n", sum);
} | 3.0625 | 3 |
2024-11-18T20:48:40.229070+00:00 | 2020-06-16T16:18:04 | 8718bbbdf6927653d06d84d605f246d98ad01d0c | {
"blob_id": "8718bbbdf6927653d06d84d605f246d98ad01d0c",
"branch_name": "refs/heads/master",
"committer_date": "2020-06-16T16:18:04",
"content_id": "e2d482205c89530326162e5bf6e8c7b1f6c45d6f",
"detected_licenses": [
"MIT"
],
"directory_id": "df358035400a73ff30fe08a93bf5da36ebddd425",
"extension": "c",
"filename": "sys.c",
"fork_events_count": 0,
"gha_created_at": "2020-03-10T11:41:26",
"gha_event_created_at": "2020-03-10T11:41:27",
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 246285483,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1654,
"license": "MIT",
"license_type": "permissive",
"path": "/07_tmpfs/src/sys.c",
"provenance": "stackv2-0102.json.gz:72323",
"repo_name": "zlsh80826/osdi2020",
"revision_date": "2020-06-16T16:18:04",
"revision_id": "291630c28f1b0b56b161fb169284449f2cb92d3e",
"snapshot_id": "eec01b45fe3aa75f0efb4683ade156f4a04f2e9c",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/zlsh80826/osdi2020/291630c28f1b0b56b161fb169284449f2cb92d3e/07_tmpfs/src/sys.c",
"visit_date": "2021-03-07T18:01:29.513856"
} | stackv2 | #include "peripherals/uart.h"
#include "sys.h"
#include "fork.h"
#include "sched.h"
/*
void handle_sync(unsigned long esr, unsigned long address) {
uart_send_hex(address);
uart_send_hex(esr >> 26);
uart_send_hex(esr & 0x1ffffff);
}
*/
#define SYS_ALLOCATOR_REGISTER 5
#define SYS_ALLOCATOR_ALLOC 6
#define SYS_ALLOCATOR_FREE 7
#define SYS_ALLOCATOR_UNREGISTER 8
int handle_el0_sync(unsigned long arg0, unsigned long arg1) {
int syscall;
asm("mov %0, x8" : "=r"(syscall));
if (syscall == SYS_UART_WRITE) {
for (int i = 0; i < arg1; ++ i) {
uart_send(((char*)arg0)[i]);
}
return arg1;
} else if (syscall == SYS_UART_READ) {
for (int i = 0; i < arg1; ++ i) {
((char*)arg0)[i] = uart_getc();
}
return arg1;
} else if (syscall == SYS_EXEC) {
return do_exec(arg0);
} else if (syscall == SYS_FORK) {
return __clone(0, 0, 0);
} else if (syscall == SYS_EXIT) {
exit_process();
return 0;
} else if (syscall == SYS_ALLOCATOR_REGISTER) {
uart_send_ulong(arg0);
return sys_allocator_register(arg0);
} else if (syscall == SYS_ALLOCATOR_ALLOC) {
return sys_allocator_alloc(arg0);
} else if (syscall == SYS_ALLOCATOR_FREE) {
sys_allocator_free(arg0, arg1);
return 0;
} else if (syscall == SYS_ALLOCATOR_UNREGISTER) {
sys_allocator_unregister(arg0);
return 0;
}
uart_puts("unknown syscall\n");
return -1;
}
int handle_el1_sync(unsigned long arg0, unsigned long arg1) {
uart_puts("el1 sync\n");
return -1;
}
| 2.359375 | 2 |
2024-11-18T20:48:40.293074+00:00 | 2020-07-08T15:11:35 | 6041df49cbd7bd6d2f924141cb777819b5886325 | {
"blob_id": "6041df49cbd7bd6d2f924141cb777819b5886325",
"branch_name": "refs/heads/master",
"committer_date": "2020-07-08T15:11:35",
"content_id": "81b6b7b5a68925d4ae332f08d98079b8b203eaa0",
"detected_licenses": [
"Unlicense"
],
"directory_id": "f00a571b5dc68f264dbb44b84bf47a3bcbc3d9f9",
"extension": "h",
"filename": "PointerNames.h",
"fork_events_count": 1,
"gha_created_at": "2020-06-20T18:08:56",
"gha_event_created_at": "2020-07-08T15:11:36",
"gha_language": "CMake",
"gha_license_id": "Unlicense",
"github_id": 273760301,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4656,
"license": "Unlicense",
"license_type": "permissive",
"path": "/src/PointerNames.h",
"provenance": "stackv2-0102.json.gz:72451",
"repo_name": "NikBenson/pointerNames",
"revision_date": "2020-07-08T15:11:35",
"revision_id": "44e575502ae6296ebcd571b6ace9e32bb76b66b7",
"snapshot_id": "d53b0d00cb43a2493b439573b521c5b76a3bf212",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/NikBenson/pointerNames/44e575502ae6296ebcd571b6ace9e32bb76b66b7/src/PointerNames.h",
"visit_date": "2022-11-12T09:57:53.073298"
} | stackv2 | #ifndef POINTERNAMES_POINTERNAMES_H
#define POINTERNAMES_POINTERNAMES_H
#include <malloc.h>
#define NULL (void*)0
/**
* @struct PointerNamesNamesList in linked list
* @var string name value of this node
* @var PointerNamesNamesList next child node of linked list
*/
struct PointerNamesNamesList {
const char* name;
struct PointerNamesNamesList* next;
};
/**
* @struct PointerToNamesDictionary of pointers to names in linked list
* @var pointer key linked by value
* @var string value linked by key
* @var PointerToNamesDictionary next child node of linked list
*/
struct PointerToNamesDictionary {
void* key;
const char* value;
struct PointerToNamesDictionary* next;
};
/**
* Returns the value according to PointerToNamesDictionary using ptr.
* Updates PointerToNamesDictionary if necessary.
* @param pointer ptr
* @return string name
*/
const char* getPointerName(void*);
/**
* Initialises pointerNames environment with custom names.
* @param string[] names
*/
void setPointerToNamesList(const char names[][16]/* = (char[][16]) {
"Angelo",
"Chris",
"Skyla",
"James",
"Karlos",
"Hans",
"Klaus",
"Linus",
"Frank",
"Wolfgang",
"Paula",
"Kleopatra",
"Nikola",
"Gustav",
"Julius",
"Alexander",
"Nik",
"Fyn",
"Markus",
"Elisabeth",
"Alice",
"Ferdinant",
"Napoleon",
"Thomas",
"Torben",
"Willhelm",
"Vincent",
"Markus",
"Helmut",
"Otto",
"Franz",
"Cleo",
"Sebastian",
"Olliver",
"Diana",
"Maria",
"Herkules",
"Bilbo",
"Merlin",
"Frodo",
"Smaug",
"Shelob",
"Gandalf",
"Dumbledore",
"Samwise",
"Peregrin",
"Meriadoc",
"Sauron",
"Saroman",
"Hermes",
"Loki",
"Zeus",
"Heracles",
"Minos",
"Gilgamech",
"Jesus",
"Charles",
"Logan",
"Anakin",
"Sheev",
"Padme",
"Yoda",
"Chewbacca",
"Maurice",
"Mario",
"Koopa",
"Kamek",
"Bowser",
"Yoshi",
"Gumba",
"Toad",
"Victor",
"Tony",
"Peach",
"Daisy",
"Amy",
"Rosalina",
"Hornet",
"Toadette",
"Fawfull",
"Ray",
"Kylo",
"Shrek",
"Fiona",
"Hera",
"Rosa",
"Ruto",
"Ganondorf",
"Zelda",
"Link",
"Mipha",
"Pauline",
"Zote",
"Grimm",
"Greta",
"Hilda",
"Cynthia",
"Red",
"Blue",
"Pennywise",
"Phineas",
"Ferb",
"Candace",
"Isabella",
"Kirby",
"Dedede",
"Marx",
"Snatcher",
"DJGrooves",
"Louis",
"Marge",
}*/, int length /*= 110*/);
struct PointerToNamesDictionary* pointerToNamesDictionary;
struct PointerNamesNamesList* pointerToNameNames;
/**
* Returns the value according to PointerToNamesDictionary using ptr.
* Updates PointerToNamesDictionary if necessary.
* @param pointer ptr
* @return string name
*/
const char *getPointerName(void* ptr) {
//first entry
if(pointerToNamesDictionary == NULL) {
//make sure that there is always a next name
if(pointerToNameNames == NULL) {
setPointerToNamesList((const char[][16]){"test"}, 1);
}
//use and remove name, init PointerToNamesDictionary
pointerToNamesDictionary = /*(PointerToNamesDictionary*)*/ malloc(sizeof(struct PointerToNamesDictionary));
pointerToNamesDictionary->key = ptr;
pointerToNamesDictionary->value = pointerToNameNames->name;
pointerToNameNames = pointerToNameNames->next;
return pointerToNamesDictionary->value;
}
//search for key in PointerToNamesDictionary
struct PointerToNamesDictionary* dict = pointerToNamesDictionary;
do {
if(dict->key == ptr) return dict->value;
dict = dict->next;
} while(dict != NULL);
//make sure that there is always a next name
if(pointerToNameNames == NULL) {
setPointerToNamesList((const char[][16]){"test"}, 1);
}
//use and remove next name
struct PointerToNamesDictionary* temp = pointerToNamesDictionary;
pointerToNamesDictionary = /*(PointerToNamesDictionary*)*/ malloc(sizeof(struct PointerToNamesDictionary));
pointerToNamesDictionary->key = ptr;
pointerToNamesDictionary->value = pointerToNameNames->name;
pointerToNameNames = pointerToNameNames->next;
pointerToNamesDictionary->next = temp;
return pointerToNamesDictionary->value;
}
/**
* Initialises pointerNames environment with custom names.
* @param string[] names
*/
void setPointerToNamesList(const char names[][16], int length) {
pointerToNameNames = /*(PointerNamesNamesList*)*/ malloc(sizeof(struct PointerNamesNamesList));
pointerToNameNames->name = names[0];
struct PointerNamesNamesList* name = pointerToNameNames;
for(unsigned int i = 1; i < length; i++) {
name->next = /*(PointerNamesNamesList*)*/ malloc(sizeof(struct PointerNamesNamesList));
name->next->name = names[i];
name = name->next;
}
}
#endif //POINTERNAMES_POINTERNAMES_H
| 2.03125 | 2 |
2024-11-18T20:48:41.530221+00:00 | 2012-04-26T08:19:12 | d78f06d78edf618ad7f6a9a100dba69c5b1634c0 | {
"blob_id": "d78f06d78edf618ad7f6a9a100dba69c5b1634c0",
"branch_name": "refs/heads/master",
"committer_date": "2012-04-26T08:19:12",
"content_id": "f3c76bebca72358d5791a4031cf9dd9494c06aae",
"detected_licenses": [
"MIT"
],
"directory_id": "9357bed2ab063ec0d62774a22112bec3dd655ffd",
"extension": "h",
"filename": "assert2.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": 931,
"license": "MIT",
"license_type": "permissive",
"path": "/source/assert2.h",
"provenance": "stackv2-0102.json.gz:72964",
"repo_name": "taparkins/Galaxulon",
"revision_date": "2012-04-26T08:19:12",
"revision_id": "6613e92861799eb16db42cb9cdc8f88179841c19",
"snapshot_id": "25cfb8a277f61dc128f87959b386565a7c09707d",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/taparkins/Galaxulon/6613e92861799eb16db42cb9cdc8f88179841c19/source/assert2.h",
"visit_date": "2023-03-20T20:17:38.883400"
} | stackv2 | // assert2.h
//
// Authors: Aric Parkinson, Spencer Phippen
// Date created: March 29, 2012
//
// Contains an assertion function for debugging purposes
#ifndef ASSERT2_H_
#define ASSERT2_H_
#undef assert2
// MACRO: assert2(bool condition, const char* message)
// If NDEBUG is defined, then the macro does nothing.
// Otherwise, if "condition" evaluates to false, then program execution is halted,
// and information about where the error occurred + your message
// is written to ASSERT_INFO_LOCATION in memory.
#define ASSERT_INFO_LOCATION 0x02020000
#ifdef NDEBUG // we can turn it off
#define assert2(__cond, __mess) ((void)0)
#else
#define assert2(__cond, __mess) ((__cond) ? (void)0 : assert2_func(__FILE__, __LINE__, __PRETTY_FUNCTION__, __mess, #__cond))
#endif
void assert2_func(const char* fileName, int lineNum, const char* funcName, const char* message, const char* condition);
#endif | 2.265625 | 2 |
2024-11-18T20:48:41.920321+00:00 | 2016-12-04T21:11:46 | ea4334cd8a6660d605d3ad6dca6cbfaeadd2b813 | {
"blob_id": "ea4334cd8a6660d605d3ad6dca6cbfaeadd2b813",
"branch_name": "refs/heads/master",
"committer_date": "2016-12-04T21:11:46",
"content_id": "b41b93b1eb6a70c9d0eddc94889975f7af57f0b3",
"detected_licenses": [
"MIT"
],
"directory_id": "1ec04a68de7345754f2243c83ca1c4f5e30443d3",
"extension": "c",
"filename": "01_are_stiga_de.c",
"fork_events_count": 0,
"gha_created_at": "2016-10-08T22:59:15",
"gha_event_created_at": "2016-10-08T22:59:17",
"gha_language": null,
"gha_license_id": null,
"github_id": 70361913,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 142,
"license": "MIT",
"license_type": "permissive",
"path": "/G/02/03/01_are_stiga_de.c",
"provenance": "stackv2-0102.json.gz:73353",
"repo_name": "tishka25/c-programming-homework",
"revision_date": "2016-12-04T21:11:46",
"revision_id": "8199d18f2664b45073917923cb453af65247f65b",
"snapshot_id": "7867f9b5ec0d4202b8319c0d85cd7668b20f6d35",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/tishka25/c-programming-homework/8199d18f2664b45073917923cb453af65247f65b/G/02/03/01_are_stiga_de.c",
"visit_date": "2021-01-10T22:44:29.816783"
} | stackv2 |
#include <stdio.h>
int main(){
int cifra;
scanf("%d", &cifra);
printf("\n%d\n", cifra*cifra);
printf("%d\n", cifra*cifra*cifra);
return 0;
}
| 2.296875 | 2 |
2024-11-18T20:48:42.592575+00:00 | 2022-11-11T07:29:12 | 69ae5cf1b7fc333c2f3edb358b7ca24f2154e76b | {
"blob_id": "69ae5cf1b7fc333c2f3edb358b7ca24f2154e76b",
"branch_name": "refs/heads/master",
"committer_date": "2022-11-11T07:29:12",
"content_id": "cb0e1b8bea098fa536ac4269d54cddea29b5f111",
"detected_licenses": [
"MIT"
],
"directory_id": "3763c9079322394c4840f4f411c0e7f2cf207f81",
"extension": "c",
"filename": "test_itu.c",
"fork_events_count": 8,
"gha_created_at": "2018-04-12T17:02:29",
"gha_event_created_at": "2022-11-06T18:54:26",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 129284949,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 12110,
"license": "MIT",
"license_type": "permissive",
"path": "/src/tests/test_itu.c",
"provenance": "stackv2-0102.json.gz:73870",
"repo_name": "obilaniu/Benzina",
"revision_date": "2022-11-11T07:29:12",
"revision_id": "c5a05333b38cf69167034a7940b1b2088059ff69",
"snapshot_id": "3cbb5af0a08a5b5d0b4ad02463ed2e8aa7f0e3aa",
"src_encoding": "UTF-8",
"star_events_count": 34,
"url": "https://raw.githubusercontent.com/obilaniu/Benzina/c5a05333b38cf69167034a7940b1b2088059ff69/src/tests/test_itu.c",
"visit_date": "2022-11-23T12:10:47.592315"
} | stackv2 | /* Includes */
#include <stdio.h>
#include <stdlib.h>
#include <benzina/benzina.h>
#include <benzina/itu/h26x.h>
/**
* Defines
*/
#define tstmessageflush(fp, f, ...) \
do{ \
fprintf((fp), (f), ## __VA_ARGS__); \
fflush((fp)); \
}while(0)
#define tstmessagetap(r, f, ...) \
do{ \
if((r)){ \
fprintf(stdout, "ok "); \
}else{ \
fprintf(stdout, "not ok "); \
} \
fprintf(stdout, (f), ## __VA_ARGS__); \
fprintf(stdout, "\n"); \
fflush(stdout); \
}while(0)
#define tstmessage(fp, f, ...) \
(fprintf((fp), (f), ## __VA_ARGS__))
#define tstmessageexit(code, fp, f, ...) \
do{ \
tstmessageflush(fp, f, ## __VA_ARGS__); \
exit(code); \
}while(0)
/**
* Functions
*/
/**
* Main
*/
int main(void){
uint8_t buf[1024+64];
BENZ_ITU_H26XBS bs_STACK, *bs = &bs_STACK;
uint32_t a,b,c;
int i,z=0;
/* Test plan */
tstmessageflush(stdout, "1..83\n");
/* Null pointer, 0 bytes {} */
benz_itu_h26xbs_init(bs, NULL, 0);
tstmessagetap(bs->naluptr == NULL, "null init, 0 bytes ptr");
tstmessagetap(bs->nalulen == 0, "null init, 0 bytes len");
tstmessagetap(benz_itu_h26xbs_eos(bs), "null init, 0 bytes EOS");
/* Null pointer, >0 bytes *NULL */
benz_itu_h26xbs_init(bs, NULL, 100);
tstmessagetap(bs->naluptr == NULL, "null init, >0 bytes ptr");
tstmessagetap(bs->nalulen == 0, "null init, >0 bytes len");
tstmessagetap(benz_itu_h26xbs_eos(bs), "null init, >0 bytes EOS");
/* Non-null pointer, 0 bytes {} */
benz_itu_h26xbs_init(bs, "", 0);
tstmessagetap(bs->naluptr != NULL, "non-null init, 0 bytes ptr");
tstmessagetap(bs->nalulen == 0, "non-null init, 0 bytes len");
tstmessagetap(benz_itu_h26xbs_eos(bs), "non-null init, 0 bytes EOS");
/* Non-null pointer, 1 bytes {0x03} */
benz_itu_h26xbs_init(bs, "\x03", 1);
tstmessagetap(bs->naluptr != NULL, "non-null init, 1 bytes ptr");
tstmessagetap(!benz_itu_h26xbs_eos(bs), "non-null init, 1 bytes !EOS");
tstmessagetap(!benz_itu_h26xbs_err(bs), "non-null init, 1 bytes !ERR");
tstmessagetap(benz_itu_h26xbs_read_1b(bs) == 0, "non-null init, 1 bytes, 1 bit read");
tstmessagetap(benz_itu_h26xbs_read_un(bs, 2) == 0, "non-null init, 1 bytes, 2 bit unsigned read");
tstmessagetap(benz_itu_h26xbs_read_sn(bs, 3) == 0, "non-null init, 1 bytes, 3 bit signed read");
tstmessagetap(benz_itu_h26xbs_read_ue(bs) == 0, "non-null init, 1 bytes, unsigned Exp-Golomb");
tstmessagetap(benz_itu_h26xbs_read_ue(bs) == 0, "non-null init, 1 bytes, signed Exp-Golomb");
tstmessagetap(benz_itu_h26xbs_eos(bs), "non-null init, 1 bytes EOS");
tstmessagetap(!benz_itu_h26xbs_err(bs), "non-null init, 1 bytes EOS+!ERR");
benz_itu_h26xbs_skip_xn(bs, 5);
tstmessagetap(bs->sregoff == bs->headoff+5, "non-null init, 1 bytes, 5 bit overread");
tstmessagetap(benz_itu_h26xbs_err(bs) ==
BENZ_H26XBS_ERR_OVERREAD, "non-null init, 1 bytes, ERR=overread");
/* Non-null pointer, 2 bytes {0x00, 0x03} */
benz_itu_h26xbs_init(bs, "\x00\x03", 2);
tstmessagetap(bs->naluptr != NULL, "non-null init, 2 bytes ptr");
tstmessagetap(benz_itu_h26xbs_read_un(bs, 16) == 3, "non-null init, 2 bytes, 16 bit unsigned read");
tstmessagetap(benz_itu_h26xbs_eos(bs), "non-null init, 2 bytes EOS");
tstmessagetap(!benz_itu_h26xbs_err(bs), "non-null init, 2 bytes EOS+!ERR");
/* Non-null pointer, 3 bytes, EPB {0x00, 0x00, 0x03} */
benz_itu_h26xbs_init(bs, "\x00\x00\x03", 3);
tstmessagetap(bs->naluptr != NULL, "non-null init, 3 bytes, EPB ptr");
tstmessagetap(benz_itu_h26xbs_read_sn(bs, 16) == 0, "non-null init, 3 bytes, EPB 16 bit signed read");
tstmessagetap(benz_itu_h26xbs_eos(bs), "non-null init, 3 bytes, EPB EOS");
tstmessagetap(!benz_itu_h26xbs_err(bs), "non-null init, 3 bytes, EPB EOS+!ERR");
/* Non-null pointer, 3 bytes, no EPB {0x00, 0x00, 0xFF} */
benz_itu_h26xbs_init(bs, "\x00\x00\xFF", 3);
tstmessagetap(bs->naluptr != NULL, "non-null init, 3 bytes, no EPB ptr");
tstmessagetap(benz_itu_h26xbs_read_sn(bs, 24) == 0xFF, "non-null init, 3 bytes, no EPB 24 bit signed read");
tstmessagetap(benz_itu_h26xbs_eos(bs), "non-null init, 3 bytes, no EPB EOS");
tstmessagetap(!benz_itu_h26xbs_err(bs), "non-null init, 3 bytes, no EPB EOS+!ERR");
/* Fills & Skips */
benz_itu_h26xbs_init(bs, "\x01\x02\x03\x04\x05\x06\x07\x08"
"\x09\xAA\xB1\xC2\xD3\xE4\xF5\x10", 16);
tstmessagetap(benz_itu_h26xbs_read_ue(bs) == 0x80, "fill, 16 bytes, unsigned Exp-Golomb");
tstmessagetap(bs->sregoff == bs->tailoff+15, "fill, 16 bytes, unsigned Exp-Golomb 0x80 consumed 15 bits");
benz_itu_h26xbs_fill57b(bs);
tstmessagetap(bs->sregoff == bs->tailoff+7, "fill, 16 bytes, fill57b refilled 57 bits");
tstmessagetap(bs->sreg == 0x0182028303840480ULL, "fill, 16 bytes, shift register contains 57 bits");
a = bs->sregoff;
benz_itu_h26xbs_fill57b(bs);
b = bs->sregoff;
tstmessagetap(a == b, "fill, 16 bytes, fill57b idempotent 1");
tstmessagetap(bs->sreg == 0x0182028303840480ULL, "fill, 16 bytes, fill57b idempotent 2");
benz_itu_h26xbs_fill64b(bs);
tstmessagetap(bs->sregoff == bs->tailoff, "fill, 16 bytes, fill64b refilled 64 bits");
tstmessagetap(bs->sreg == 0x01820283038404D5ULL, "fill, 16 bytes, shift register contains 64 bits");
a = bs->sregoff;
benz_itu_h26xbs_fill64b(bs);
b = bs->sregoff;
tstmessagetap(a == b, "fill, 16 bytes, fill64b idempotent 1");
tstmessagetap(bs->sreg == 0x01820283038404D5ULL, "fill, 16 bytes, fill64b idempotent 2");
a = bs->sregoff;
benz_itu_h26xbs_bigfill(bs);
tstmessagetap(bs->sreg == 0x01820283038404D5ULL, "fill, 16 bytes, bigfill refilled 64 bits");
b = bs->sregoff;
benz_itu_h26xbs_bigfill(bs);
c = bs->sregoff;
tstmessagetap(a == b && b == c, "fill, 16 bytes, bigfill idempotent 1");
tstmessagetap(bs->sreg == 0x01820283038404D5ULL, "fill, 16 bytes, bigfill idempotent 2");
a = bs->sregoff;
benz_itu_h26xbs_realign(bs);
b = bs->sregoff;
benz_itu_h26xbs_realign(bs);
c = bs->sregoff;
tstmessagetap(a+1 == b && b%8 == 0, "fill, 16 bytes, realign on even byte boundary");
tstmessagetap(b == c, "fill, 16 bytes, realign idempotent");
a = bs->sregoff;
benz_itu_h26xbs_fill8B(bs);
tstmessagetap(bs->sreg == 0x03040506070809AAULL, "fill, 16 bytes, fill8B refilled 8 bytes");
a = bs->sregoff;
benz_itu_h26xbs_fill8B(bs);
b = bs->sregoff;
tstmessagetap(a == b, "fill, 16 bytes, fill8B idempotent 1");
tstmessagetap(bs->sreg == 0x03040506070809AAULL, "fill, 16 bytes, fill8B idempotent 2");
a = bs->sregoff;
benz_itu_h26xbs_skip_xn(bs, 8);
b = bs->sregoff;
tstmessagetap(a+8 == b, "fill, 16 bytes, skipped 8 bits");
tstmessagetap(bs->sreg == 0x040506070809AA00ULL, "fill, 16 bytes, consumed 8 bits");
a = bs->sregoff;
benz_itu_h26xbs_bigskip(bs, 0);
b = bs->sregoff;
tstmessagetap(a == b, "fill, 16 bytes, bigskip skipped 0 bits");
tstmessagetap(bs->sreg == 0x040506070809AAB1ULL, "fill, 16 bytes, bigskip refilled 64 bits");
a = bs->sregoff;
benz_itu_h26xbs_bigskip(bs, 104);
b = bs->sregoff;
tstmessagetap(a+104 == b, "fill, 16 bytes, bigskip skipped 104 bits");
tstmessagetap(benz_itu_h26xbs_eos(bs), "fill, 16 bytes, EOS");
tstmessagetap(!benz_itu_h26xbs_err(bs), "fill, 16 bytes, !ERR");
/**
* Mass EPB stripping and mass-skipping test.
*
* Synthesize extremely pathological string: {0,0,3}x341 + {0}
* Therefore, 341 EPBs will have to be stripped, and the bitstring is
* (1024-341)*8 = 5464 bits = 683 bytes.
*/
memset(buf, 0, sizeof(buf));
for(i=2;i<1024;i+=3){
buf[i] = 3;
}
benz_itu_h26xbs_init(bs, buf, 1024);
tstmessagetap(!benz_itu_h26xbs_err(bs), "pathological, !ERR");
tstmessagetap(!benz_itu_h26xbs_eos(bs), "pathological, !EOS");
tstmessagetap(bs->nalulen > 0, "pathological, unfiltered bytes > 0");
for(z=0,i=0;i<300;i++){
if(i % 100 == 0){
benz_itu_h26xbs_bigfill(bs);
}
benz_itu_h26xbs_fill57b(bs);
if(benz_itu_h26xbs_read_un(bs, 8) != 0){
z |= 1;
}
}
tstmessagetap(bs->headoff <= 2048, "pathological, headoff in sane bounds");
tstmessagetap(bs->tailoff <= bs->headoff, "pathological, tailoff in sane bounds");
tstmessagetap(bs->sregoff <= 1536, "pathological, sregoff in sane bounds");
tstmessagetap(bs->headoff >= 1536 || !bs->nalulen, "pathological, rbsp sufficiently full");
tstmessagetap(bs->sregoff <= bs->headoff, "pathological, sregoff <= headoff");
tstmessagetap(!benz_itu_h26xbs_err(bs), "pathological, after filter !ERR");
tstmessagetap(!benz_itu_h26xbs_eos(bs), "pathological, after filter !EOS");
tstmessagetap(z == 0, "pathological, 300 filtered bytes all zero");
benz_itu_h26xbs_bigskip(bs, 380*8);
tstmessagetap(!benz_itu_h26xbs_err(bs), "pathological, after bigskip !ERR");
tstmessagetap(!benz_itu_h26xbs_eos(bs), "pathological, after bigskip !EOS");
tstmessagetap(bs->headoff >= 1536 || !bs->nalulen, "pathological, after bigskip rbsp sufficiently full");
tstmessagetap(benz_itu_h26xbs_read_un(bs, 8) == 0, "pathological, preprefinal zero byte");
tstmessagetap(benz_itu_h26xbs_read_un(bs, 8) == 0, "pathological, prefinal zero byte");
tstmessagetap(benz_itu_h26xbs_read_un(bs, 8) == 0, "pathological, final zero byte");
tstmessagetap(benz_itu_h26xbs_eos(bs), "pathological, EOS");
tstmessagetap(!benz_itu_h26xbs_err(bs), "pathological, EOS+!ERR");
/* Corrupt */
benz_itu_h26xbs_init(bs, "\x00\x00\x03\x00\x00\x03\x00\x00"
"\x03\x00\x00\x03\xFF\xFF\xFF\x55", 16);
tstmessagetap(!benz_itu_h26xbs_eos(bs), "corrupt exp-golomb, !EOS");
tstmessagetap(!benz_itu_h26xbs_err(bs), "corrupt exp-golomb, !ERR");
tstmessagetap(benz_itu_h26xbs_read_1b(bs) == 0, "corrupt exp-golomb, read 1 bit");
a = bs->sregoff;
benz_itu_h26xbs_read_ue(bs);
b = bs->sregoff;
tstmessagetap(b-a <= 63, "corrupt exp-golomb, <=63 bits consumed.");
tstmessagetap(!benz_itu_h26xbs_eos(bs), "corrupt exp-golomb, !EOS");
tstmessagetap(benz_itu_h26xbs_err(bs) ==
BENZ_H26XBS_ERR_CORRUPT, "corrupt exp-golomb, ERR=corrupt");
/* Exit. */
return 0;
}
| 2.390625 | 2 |
2024-11-18T20:48:43.553227+00:00 | 2021-01-15T09:45:04 | 89018f43e26a43918706bf95786cf51913fa664a | {
"blob_id": "89018f43e26a43918706bf95786cf51913fa664a",
"branch_name": "refs/heads/master",
"committer_date": "2021-01-15T09:45:04",
"content_id": "c83be611f33cbc58a5aa3970080761b382bf5ea5",
"detected_licenses": [
"Apache-2.0",
"MIT"
],
"directory_id": "ba3b7ea827038ccf4d8d03919ad1c95e18bbe90c",
"extension": "c",
"filename": "intro.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": 6218,
"license": "Apache-2.0,MIT",
"license_type": "permissive",
"path": "/src/demo/intro.c",
"provenance": "stackv2-0102.json.gz:74389",
"repo_name": "jgphpc/notcurses",
"revision_date": "2021-01-15T09:45:04",
"revision_id": "99ef8a02e50b4975ed753cf7c8d926a8b7901208",
"snapshot_id": "2e4beecb5f35d44accbe04dcf5c75903715cbb0c",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/jgphpc/notcurses/99ef8a02e50b4975ed753cf7c8d926a8b7901208/src/demo/intro.c",
"visit_date": "2023-02-17T12:01:36.542077"
} | stackv2 | #include "demo.h"
static int centercols;
static int
fader(struct notcurses* nc, struct ncplane* ncp, void* curry){
int* flipmode = curry;
int rows, cols;
ncplane_dim_yx(ncp, &rows, &cols);
const bool smallscreen = rows < 26;
const int row1 = rows - 10 + smallscreen;
const int row2 = 6 - smallscreen; // box always starts on 4; don't stomp riser
int startx = (cols - (centercols - 2)) / 2;
ncplane_set_fg_rgb8(ncp, 0xd0, 0xf0, 0xd0);
for(int x = startx ; x < startx + centercols - 2 ; ++x){
if(ncplane_putwc_yx(ncp, row1, x, x % 2 != *flipmode % 2 ? L'◪' : L'◩') <= 0){
return -1;
}
if(ncplane_putwc_yx(ncp, row2, x, x % 2 == *flipmode % 2 ? L'◪' : L'◩') <= 0){
return -1;
}
}
++*flipmode;
int err;
if( (err = demo_render(nc)) ){
return err;
}
return 0;
}
int intro(struct notcurses* nc){
if(!notcurses_canutf8(nc)){
return 0;
}
int rows, cols;
struct ncplane* ncp = notcurses_stddim_yx(nc, &rows, &cols);
uint32_t ccul, ccur, ccll, cclr;
ccul = ccur = ccll = cclr = 0;
channel_set_rgb8(&ccul, 0, 0xd0, 0);
channel_set_rgb8(&ccur, 0xff, 0, 0);
channel_set_rgb8(&ccll, 0x88, 0, 0xcc);
channel_set_rgb8(&cclr, 0, 0, 0);
// we use full block rather+fg than space+bg to conflict less with the menu
ncplane_home(ncp);
if(ncplane_highgradient_sized(ncp, ccul, ccur, ccll, cclr, rows, cols) <= 0){
return -1;
}
nccell c = CELL_TRIVIAL_INITIALIZER;
cell_set_bg_rgb8(&c, 0x20, 0x20, 0x20);
ncplane_set_base_cell(ncp, &c);
nccell ul = CELL_TRIVIAL_INITIALIZER, ur = CELL_TRIVIAL_INITIALIZER;
nccell ll = CELL_TRIVIAL_INITIALIZER, lr = CELL_TRIVIAL_INITIALIZER;
nccell hl = CELL_TRIVIAL_INITIALIZER, vl = CELL_TRIVIAL_INITIALIZER;
if(ncplane_cursor_move_yx(ncp, 1, 0)){
return -1;
}
if(cells_rounded_box(ncp, NCSTYLE_BOLD, 0, &ul, &ur, &ll, &lr, &hl, &vl)){
return -1;
}
cell_set_fg_rgb(&ul, 0xff0000); cell_set_bg_rgb(&ul, 0x002000);
cell_set_fg_rgb(&ur, 0x00ff00); cell_set_bg_rgb(&ur, 0x002000);
cell_set_fg_rgb(&ll, 0x0000ff); cell_set_bg_rgb(&ll, 0x002000);
cell_set_fg_rgb(&lr, 0xffffff); cell_set_bg_rgb(&lr, 0x002000);
if(ncplane_box_sized(ncp, &ul, &ur, &ll, &lr, &hl, &vl, rows - 1, cols,
NCBOXGRAD_TOP | NCBOXGRAD_BOTTOM |
NCBOXGRAD_RIGHT | NCBOXGRAD_LEFT)){
return -1;
}
uint64_t cul, cur, cll, clr;
cul = cur = cll = clr = 0;
channels_set_fg_rgb8(&cul, 200, 0, 200); channels_set_bg_rgb8(&cul, 0, 64, 0);
channels_set_fg_rgb8(&cur, 200, 0, 200); channels_set_bg_rgb8(&cur, 0, 64, 0);
channels_set_fg_rgb8(&cll, 200, 0, 200); channels_set_bg_rgb8(&cll, 0, 128, 0);
channels_set_fg_rgb8(&clr, 200, 0, 200); channels_set_bg_rgb8(&clr, 0, 128, 0);
centercols = cols > 80 ? 72 : cols - 8;
if(ncplane_cursor_move_yx(ncp, 5, (cols - centercols) / 2 + 1)){
return -1;
}
if(ncplane_gradient(ncp, "Δ", 0, cul, cur, cll, clr, rows - 8, cols / 2 + centercols / 2 - 1) <= 0){
return -1;
}
cell_set_fg_rgb(&lr, 0xff0000); cell_set_bg_rgb(&lr, 0x002000);
cell_set_fg_rgb(&ll, 0x00ff00); cell_set_bg_rgb(&ll, 0x002000);
cell_set_fg_rgb(&ur, 0x0000ff); cell_set_bg_rgb(&ur, 0x002000);
cell_set_fg_rgb(&ul, 0xffffff); cell_set_bg_rgb(&ul, 0x002000);
if(ncplane_cursor_move_yx(ncp, 4, (cols - centercols) / 2)){
return -1;
}
if(ncplane_box_sized(ncp, &ul, &ur, &ll, &lr, &hl, &vl, rows - 11, centercols,
NCBOXGRAD_TOP | NCBOXGRAD_BOTTOM | NCBOXGRAD_RIGHT | NCBOXGRAD_LEFT)){
return -1;
}
cell_release(ncp, &ul); cell_release(ncp, &ur);
cell_release(ncp, &ll); cell_release(ncp, &lr);
cell_release(ncp, &hl); cell_release(ncp, &vl);
const char s1[] = " Die Welt ist alles, was der Fall ist. ";
const char str[] = " Wovon man nicht sprechen kann, darüber muss man schweigen. ";
if(ncplane_set_fg_rgb8(ncp, 192, 192, 192)){
return -1;
}
if(ncplane_set_bg_rgb8(ncp, 0, 40, 0)){
return -1;
}
if(ncplane_putstr_aligned(ncp, rows / 2 - 4, NCALIGN_CENTER, s1) < 0){
return -1;
}
ncplane_on_styles(ncp, NCSTYLE_ITALIC | NCSTYLE_BOLD);
if(ncplane_putstr_aligned(ncp, rows / 2 - 3, NCALIGN_CENTER, str) < 0){
return -1;
}
ncplane_off_styles(ncp, NCSTYLE_ITALIC);
ncplane_set_fg_rgb8(ncp, 0xff, 0xff, 0xff);
int major, minor, patch, tweak;
notcurses_version_components(&major, &minor, &patch, &tweak);
if(tweak){
if(ncplane_printf_aligned(ncp, rows / 2 - 1, NCALIGN_CENTER, "notcurses %d.%d.%d.%d. press 'q' to quit.",
major, minor, patch, tweak) < 0){
return -1;
}
}else{
if(ncplane_printf_aligned(ncp, rows / 2 - 1, NCALIGN_CENTER, "notcurses %d.%d.%d. press 'q' to quit.",
major, minor, patch) < 0){
return -1;
}
}
ncplane_off_styles(ncp, NCSTYLE_BOLD);
const wchar_t wstr[] = L"▏▁ ▂ ▃ ▄ ▅ ▆ ▇ █ █ ▇ ▆ ▅ ▄ ▃ ▂ ▁▕";
if(ncplane_putwstr_aligned(ncp, rows / 2 - 6, NCALIGN_CENTER, wstr) < 0){
return -1;
}
const wchar_t iwstr[] = L"▏█ ▇ ▆ ▅ ▄ ▃ ▂ ▁ ▁ ▂ ▃ ▄ ▅ ▆ ▇ █▕";
if(ncplane_putwstr_aligned(ncp, rows / 2 + 1, NCALIGN_CENTER, iwstr) < 0){
return -1;
}
if(rows < 45){
ncplane_set_fg_rgb8(ncp, 0xc0, 0x80, 0x80);
ncplane_set_bg_rgb8(ncp, 0x20, 0x20, 0x20);
ncplane_on_styles(ncp, NCSTYLE_BLINK); // heh FIXME replace with pulse
if(ncplane_putstr_aligned(ncp, 2, NCALIGN_CENTER, "demo runs best with at least 45 lines") < 0){
return -1;
}
ncplane_off_styles(ncp, NCSTYLE_BLINK); // heh FIXME replace with pulse
}
struct timespec now;
clock_gettime(CLOCK_MONOTONIC_RAW, &now);
uint64_t deadline = timespec_to_ns(&now) + timespec_to_ns(&demodelay) * 2;
int flipmode = 0;
do{
int err;
if( (err = fader(nc, ncp, &flipmode)) ){
return err;
}
struct timespec iter;
timespec_div(&demodelay, 10, &iter);
demo_nanosleep(nc, &iter);
clock_gettime(CLOCK_MONOTONIC_RAW, &now);
}while(timespec_to_ns(&now) < deadline);
if(!notcurses_canfade(nc)){
return 0;
}
struct timespec fade = demodelay;
return ncplane_fadeout(ncp, &fade, demo_fader, NULL);
}
| 2.40625 | 2 |
2024-11-18T20:48:43.866146+00:00 | 2019-07-21T01:02:33 | 8b680da96638375b93a3bd30a437d979e6bedb4f | {
"blob_id": "8b680da96638375b93a3bd30a437d979e6bedb4f",
"branch_name": "refs/heads/master",
"committer_date": "2019-07-21T01:02:33",
"content_id": "2b5fdfdd95f0a184c335659c9b9fb1b9959c74c8",
"detected_licenses": [
"MIT"
],
"directory_id": "d0f2a76f1c235e25f31b6fde48b70f38022712f2",
"extension": "c",
"filename": "list0511.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": 610,
"license": "MIT",
"license_type": "permissive",
"path": "/chapter05/example/list0511.c",
"provenance": "stackv2-0102.json.gz:74777",
"repo_name": "FlatterKang/crash.course.c",
"revision_date": "2019-07-21T01:02:33",
"revision_id": "a7afbdf743fdf4b894c777141eb27433189b1f6f",
"snapshot_id": "068445460406bdb8c3e051126032407b7288e0d4",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/FlatterKang/crash.course.c/a7afbdf743fdf4b894c777141eb27433189b1f6f/chapter05/example/list0511.c",
"visit_date": "2020-06-23T06:05:38.957777"
} | stackv2 | /*
输入5名学生的分数并显示出其中的最高分和最低分
*/
#include <stdio.h>
#define NUMBER 5
int main(void) {
int i;
int tensu[NUMBER];
int max, min;
printf("请输入%d名学生的分数。\n", NUMBER);
for (i = 0; i < NUMBER; i++) {
printf("%-2d号:", i + 1);
scanf("%d", &tensu[i]);
}
min = max = tensu[0];
for (i = 1; i < NUMBER; i++) {
if (tensu[i] > max) { max = tensu[i]; }
if (tensu[i] < min) { min = tensu[i]; }
}
printf("最高分:%d\n", max);
printf("最低分:%d\n", min);
return 0;
} | 4 | 4 |
2024-11-18T20:48:44.298789+00:00 | 2021-03-02T15:26:10 | 3722817db01dee495b26e20079ec73b2d89183bc | {
"blob_id": "3722817db01dee495b26e20079ec73b2d89183bc",
"branch_name": "refs/heads/main",
"committer_date": "2021-03-02T15:26:10",
"content_id": "745e33fcc30ad24952641e8d78c12aebabe1b28d",
"detected_licenses": [
"MIT"
],
"directory_id": "ff7c2d3080aec61543ac9ccfb298b357479e53d5",
"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": 334345192,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 530,
"license": "MIT",
"license_type": "permissive",
"path": "/Test/test.c",
"provenance": "stackv2-0102.json.gz:75035",
"repo_name": "Ty-Chen/NanoCRT",
"revision_date": "2021-03-02T15:26:10",
"revision_id": "87083284c360651b3745c0a57a387c918f73a40a",
"snapshot_id": "2c2eb422e978d0c0293b1faf5bc9dba5a6946ea6",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/Ty-Chen/NanoCRT/87083284c360651b3745c0a57a387c918f73a40a/Test/test.c",
"visit_date": "2023-03-16T15:27:00.356309"
} | stackv2 | #include "../Include/NanoCRT.h"
int main(long argc, char *argv[])
{
FILE* fp = NULL;
char* buf = "hello how are you \n";
char* tmp = NULL;
long len = strlen(buf);
fp = fopen("test.txt", "w");
fwrite(buf, 1, len, fp);
printf("hello world\n");
printf("%d\n%s\n", len, buf);
fclose(fp);
tmp = (char*) malloc(strlen(buf));
if (tmp == NULL)
{
return -1;
}
tmp = strcpy(tmp, buf);
printf("%s\n", tmp);
free(tmp);
return 0;
}
| 2.625 | 3 |
2024-11-18T20:48:44.637028+00:00 | 2019-03-16T05:56:34 | 6b69134ddb6d908f152604c21caf489cff546209 | {
"blob_id": "6b69134ddb6d908f152604c21caf489cff546209",
"branch_name": "refs/heads/master",
"committer_date": "2019-03-16T05:56:34",
"content_id": "8d5de37e6f751b2f74e2f7cb624b51929b354215",
"detected_licenses": [
"MIT"
],
"directory_id": "5c2d4b84778a9c2c922dc5a974a65ba87c2c000d",
"extension": "h",
"filename": "contacts.h",
"fork_events_count": 0,
"gha_created_at": "2019-03-14T21:33:42",
"gha_event_created_at": "2019-03-14T21:33:43",
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 175703069,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1055,
"license": "MIT",
"license_type": "permissive",
"path": "/ECContactsBook/contacts.h",
"provenance": "stackv2-0102.json.gz:75294",
"repo_name": "JuntongJing/cs16-extra-credit",
"revision_date": "2019-03-16T05:56:34",
"revision_id": "3edee68dacb31423502a4fafb265565c4b84b7ee",
"snapshot_id": "706ef7288ec3b3190c18625d606ef8ef159c0b64",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/JuntongJing/cs16-extra-credit/3edee68dacb31423502a4fafb265565c4b84b7ee/ECContactsBook/contacts.h",
"visit_date": "2020-04-29T00:40:25.601310"
} | stackv2 | #include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include <assert.h>
typedef struct PAGE
{
int TotalItem; //1.共多少条数据
int TotalPage; //2.共多少页
int CurrentPage; //3.当前是第几页
int OnePageItem; //4.一页显示多少条数据
}Page;
typedef struct NODE
{
int serialNum;
char* name;
char* phone;
struct NODE* pNext;
}Node;
char *str_copy(char *des, const char *src);
int GetSerialNum();
Node* GetNode();
Node* GetNodeInput();
char* GetName();
char* GetPhone();
void InsertNode(Node** ppHead,Node** ppEnd, int serialNum,Node* node);
void AddNode(Node** ppHead,Node** ppEnd,Node* node);
void DelNode(Node** ppHead,Node** ppEnd,int serialNum);
void InitInfo(Node** pHead,Node** pEnd,int n);
Page* GetPage(Node* pHead, int onePageItem);
void ShowMenu(Page* page);
void ShowInfo(Node* pHead,Page* page);
void OperatePage(Node* pHead,Page* page);
char* GetString();
void LookTXL(Node* pHead);
char Getkey();
void Query(Node* pHead);
void Del(Node** pHead,Node** pEnd);
void Edit(Node* pHead);
| 2.140625 | 2 |
2024-11-18T20:48:44.749600+00:00 | 2020-09-22T21:07:44 | 4cfbb8eb3aabc2169e07f47a3a15ce81fc737e60 | {
"blob_id": "4cfbb8eb3aabc2169e07f47a3a15ce81fc737e60",
"branch_name": "refs/heads/master",
"committer_date": "2020-09-22T21:07:44",
"content_id": "3288f95b861594b753d77d56a2eae16c239d08a9",
"detected_licenses": [],
"directory_id": "ac0b308bfd3c3e5c46ba28d2c4fe70f8516c9e7d",
"extension": "c",
"filename": "MediaAritmetica100Numeros.c",
"fork_events_count": 0,
"gha_created_at": "2020-02-17T20:53:09",
"gha_event_created_at": "2020-02-17T20:53:09",
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 241205721,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 581,
"license": "",
"license_type": "permissive",
"path": "/For/MediaAritmetica100Numeros.c",
"provenance": "stackv2-0102.json.gz:75422",
"repo_name": "Freddy875/C",
"revision_date": "2020-09-22T21:07:44",
"revision_id": "3cefc24fad613f70486197b0703d4cc433755e4a",
"snapshot_id": "299f2ccdb52fc77113fd5a6b8d3a907ee5c3d790",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Freddy875/C/3cefc24fad613f70486197b0703d4cc433755e4a/For/MediaAritmetica100Numeros.c",
"visit_date": "2021-01-06T02:56:46.701022"
} | stackv2 | /*
Array
Calcular la media aritmatica de los números del 1 al 10
*/
#include <stdio.h>
int main(){
int i, iNumeros[100];
float fSuma,fMedia;
//Llenar los datos del array
for(i = 0; i <= 100; i++ ){
iNumeros[i] = i;
printf("\n N%cmero %d",163,iNumeros[i]);
}//fin for
//Calcular la suma de todos los números
for(i = 0; i <= 100; i++ ){
fSuma = fSuma + iNumeros[i];
}//fin for
//Calcular la media aritmatica
fMedia = fSuma/100;
printf("\nLa media de los n%cmeros del 1 al 100 es: %.2f",163,fMedia);
return 0;
}//fin int main
| 3.75 | 4 |
2024-11-18T20:48:45.016857+00:00 | 2020-04-28T20:23:29 | 76b8008c185fe0e8981098da914c968d4bd08f10 | {
"blob_id": "76b8008c185fe0e8981098da914c968d4bd08f10",
"branch_name": "refs/heads/master",
"committer_date": "2020-04-28T20:23:29",
"content_id": "81193b0432c08e34a8ac7fe3a5d2274a22c9a0f4",
"detected_licenses": [
"MIT"
],
"directory_id": "90d7c26e3f1dc9a16b9091f1e7bb0f8e5e56a9d9",
"extension": "c",
"filename": "mixed_fhn_mod_mitchell.c",
"fork_events_count": 0,
"gha_created_at": "2020-04-28T19:55:47",
"gha_event_created_at": "2020-04-28T19:55:48",
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 259737833,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3641,
"license": "MIT",
"license_type": "permissive",
"path": "/src/models_library/mixed_fhn_mod_mitchell.c",
"provenance": "stackv2-0102.json.gz:75808",
"repo_name": "ElnazP/MonoAlg3D_C",
"revision_date": "2020-04-28T20:23:29",
"revision_id": "3e81952771e8747f8fb713c31225b50117c61a2d",
"snapshot_id": "c457489e4b8dfad66d7183b2c1a4ac416b5fa10f",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ElnazP/MonoAlg3D_C/3e81952771e8747f8fb713c31225b50117c61a2d/src/models_library/mixed_fhn_mod_mitchell.c",
"visit_date": "2022-05-29T16:35:05.745752"
} | stackv2 | #include <stdio.h>
#include "mixed_fhn_mod_mitchell.h"
// TODO: Maybe change this function
// Set number_of_ode_equations to the maximum 'NEQ' ?
GET_CELL_MODEL_DATA(init_cell_model_data)
{
if(get_initial_v)
cell_model->initial_v = INITIAL_V_1;
if(get_neq)
cell_model->number_of_ode_equations = NEQ_1;
}
SET_ODE_INITIAL_CONDITIONS_CPU(set_model_initial_conditions_cpu)
{
static bool first_call = true;
if(first_call)
{
print_to_stdout_and_file("Using mixed version of modified FHN 1961 + Mitchell-Shaeffer 2003 CPU model\n");
first_call = false;
}
// Get the mapping array
uint32_t *mapping = NULL;
if(extra_data)
{
mapping = (uint32_t*)extra_data;
}
else
{
print_to_stderr_and_file_and_exit("You need to specify a mask function when using a mixed model!\n");
}
// Based on the mapping initialize the initial conditions from the correct celular model
if (mapping[sv_id] == 0)
{
sv[0] = 0.000000f; //Vm millivolt
sv[1] = 0.000000f; //v dimensionless
}
else
{
sv[0] = 0.00000820413566106744f; //Vm millivolt
sv[1] = 0.8789655121804799f; //h dimensionless
}
}
SOLVE_MODEL_ODES_CPU(solve_model_odes_cpu)
{
// Get the mapping array
uint32_t *mapping = NULL;
if(extra_data)
{
mapping = (uint32_t*)extra_data;
}
else
{
print_to_stderr_and_file_and_exit("You need to specify a mask function when using a mixed model!\n");
}
uint32_t sv_id;
int i;
#pragma omp parallel for private(sv_id)
for (i = 0; i < num_cells_to_solve; i++)
{
if(cells_to_solve)
sv_id = cells_to_solve[i];
else
sv_id = (uint32_t )i;
for (int j = 0; j < num_steps; ++j)
{
if (mapping[i] == 0)
solve_model_ode_cpu_fhn(dt, sv + (sv_id * NEQ_1), stim_currents[i]);
else
solve_model_ode_cpu_mitchell(dt, sv + (sv_id * NEQ_2), stim_currents[i]);
}
}
}
void solve_model_ode_cpu_fhn (real dt, real *sv, real stim_current)
{
real rY[NEQ_1], rDY[NEQ_1];
for(int i = 0; i < NEQ_1; i++)
rY[i] = sv[i];
RHS_cpu_fhn(rY, rDY, stim_current);
for(int i = 0; i < NEQ_1; i++)
sv[i] = dt*rDY[i] + rY[i];
}
void RHS_cpu_fhn (const real *sv, real *rDY_, real stim_current)
{
//State variables
const real u = sv[0];
const real v = sv[1];
// Constants
const real a = 0.2f;
const real b = 0.5f;
const real k = 36.0;
const real epsilon = 0.000150;
// Rates
rDY_[0] = k*(u*(1.0f - u)*(u - a) - u*v) + stim_current;
rDY_[1] = k*epsilon*(b*u - v);
}
void solve_model_ode_cpu_mitchell (real dt, real *sv, real stim_current)
{
real rY[NEQ_2], rDY[NEQ_2];
for(int i = 0; i < NEQ_2; i++)
rY[i] = sv[i];
RHS_cpu_mitchell(rY, rDY, stim_current);
for(int i = 0; i < NEQ_2; i++)
sv[i] = dt*rDY[i] + rY[i];
}
void RHS_cpu_mitchell(const real *sv, real *rDY_, real stim_current)
{
//State variables
const real V = sv[0];
const real h = sv[1];
// Constants
const real tau_in = 0.3;
const real tau_out = 6.0;
const real V_gate = 0.13;
const real tau_open = 120.0;
const real tau_close = 150.0;
// Algebraics
real J_stim = stim_current;
real J_in = ( h*( pow(V, 2.00000)*(1.00000 - V)))/tau_in;
real J_out = - (V/tau_out);
// Rates
rDY_[0] = J_out + J_in + J_stim;
rDY_[1] = (V < V_gate ? (1.00000 - h)/tau_open : - h/tau_close);
} | 2.578125 | 3 |
2024-11-18T20:48:45.137276+00:00 | 2019-04-24T16:13:07 | 5158a9268e676a02c3091735241eea9085c1bd16 | {
"blob_id": "5158a9268e676a02c3091735241eea9085c1bd16",
"branch_name": "refs/heads/master",
"committer_date": "2019-04-24T16:13:07",
"content_id": "eb6aece1c4499a4352c1730139c7ea1a50f533b4",
"detected_licenses": [
"MIT"
],
"directory_id": "6daa7e1743383b143cffd2686eb4070474745566",
"extension": "c",
"filename": "queue.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 183263713,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5127,
"license": "MIT",
"license_type": "permissive",
"path": "/queue.c",
"provenance": "stackv2-0102.json.gz:76065",
"repo_name": "deesteban/C-Airport",
"revision_date": "2019-04-24T16:13:07",
"revision_id": "0b1b8abf64ea08125df06f2d07b8316691a73d35",
"snapshot_id": "9348466755a3361a1f9a0518ee5575d02048b88d",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/deesteban/C-Airport/0b1b8abf64ea08125df06f2d07b8316691a73d35/queue.c",
"visit_date": "2020-05-16T19:31:00.624825"
} | stackv2 | #include <stdio.h>
#include <stdlib.h>
#include "queue.h"
#include <string.h>
#include <pthread.h>
#include <unistd.h>
#include "plane.h"
struct Node {
struct plane *planeInfo;
struct Node *next;
};
extern char **global_argv;
extern int global_argc;
struct Node *head;// global variable - pointer to head node.
struct Node *tail;
struct Node *deleteTemp;
struct Node *temp;
int queueSize, argv5;
pthread_mutex_t mut_id1 = PTHREAD_MUTEX_INITIALIZER;
/*Creates a new Node and returns pointer to it.*/
struct Node *GetNewNode(struct plane *newPlane) {
struct Node *newNode = (struct Node *) malloc(sizeof(struct Node));
newNode->planeInfo = newPlane;
newNode->next = NULL;
return newNode;
}
struct Node deleteNode() {
deleteTemp = head;
if (head == NULL);
else {
if (head == tail) {
head = tail = NULL;
} else {
head = head->next;
tail->next = head;
}
deleteTemp->next = NULL;
queueSize--;
}
}
/*To create a queue*/
int queue_init(int size) {
printf("[QUEUE] Buffer initialized.\n");
argv5 = size;
return 0;
}
/* To Enqueue an element*/
int queue_put(struct plane *x) {
pthread_mutex_lock(&mut_id1);
if (queueSize == argv5) {
write(1, "Maximum Queue Size Reached.\n", 28);
} else {
if (global_argc == 1) {
if (x->id_number > 6) return -1;
if (x->id_number == 6) {
x->last_flight = 1;
} else { x->last_flight = 0; }
if (x->action == 0) x->time_action = 2;
if (x->action == 1) x->time_action = 3;
} else {
int argv1, argv2, argv3, argv4, sum;
argv1 = atoi(global_argv[1]);
argv2 = atoi(global_argv[2]);
argv3 = atoi(global_argv[3]);
argv4 = atoi(global_argv[4]);
sum = argv1 + argv3;
if (x->id_number > sum) return -1;
if (x->id_number == sum) {
x->last_flight = 1;
} else { x->last_flight = 0; }
if (x->action == 0) x->time_action = argv2;
if (x->action == 1) x->time_action = argv4;
}
struct Node *newNode = GetNewNode(x);
switch (queueSize) {
case 0: {
head = tail = newNode;
head->next = tail;
tail->next = head;
break;
}
case 1: {
tail = newNode;
head->next = tail;
tail->next = head;
break;
}
default: {
temp = head;
for (int i = 0; i < queueSize - 1; i++) {
temp = temp->next;
}
tail = newNode;
temp->next = tail;
tail->next = head;
break;
}
}
printf("[QUEUE] Storing plane with id <%d>\n", x->id_number);
queueSize++;
pthread_mutex_unlock(&mut_id1);
return 0;
}
}
/* To Dequeue an element.*/
struct plane *queue_get(void) {
if (queueSize >= 0) {
switch (queueSize) {
case 0: {
write(1, "Cannot empty queue when it's already empty.\n", 44);
break;
}
case 1: {
temp = head;
//queue_destroy();
printf("[QUEUE] Getting plane with id <%d>\n", temp->planeInfo->id_number);
return temp->planeInfo;
}
default: {
temp = head;
tail->next = temp->next;
head = tail->next;
queueSize--;
printf("[QUEUE] Getting plane with id <%d>\n", temp->planeInfo->id_number);
return temp->planeInfo;
}
}
}
return NULL;
}
/*To check queue state*/
int queue_empty(void) {
int isEmpty = 0;
if (queueSize == 0) {
isEmpty = 1;
}
return isEmpty;
}
/*To check queue state*/
int queue_full(void) {
if (global_argc == 1) {
if (queueSize == 6)return 1;
} else {
if (atoi(global_argv[5]) == queueSize) {
return 1;
}
}
return 0;
}
/*To destroy the queue and free the resources*/
int queue_destroy(void) {
while (queue_empty() == 0) deleteNode();
return 0;
}
/*int main(int argc, char **global_argv) {
int j = queue_empty();
struct plane plane1;
plane1.action = 1;
struct plane plane2;
plane2.action = 0;
struct plane plane3;
plane3.action = 1;
struct plane plane4;
plane4.action = 1;
struct plane plane5;
plane5.action = 1;
struct plane plane6;
plane6.action = 0;
struct plane plane11;
plane6.action = 0;
queue_put(&plane1);
queue_put(&plane2);
queue_put(&plane3);
queue_put(&plane4);
queue_put(&plane5);
queue_put(&plane6);
struct plane *plane7 = queue_get();
struct plane *plane8 = queue_get();
int i = queue_full();
int r = queue_empty();
queue_destroy();
int a = 0;
}*/
| 3.171875 | 3 |
2024-11-18T20:48:45.403052+00:00 | 2019-11-12T00:20:51 | 46f7ebf1df43a0826f096087078462dbd1a58e08 | {
"blob_id": "46f7ebf1df43a0826f096087078462dbd1a58e08",
"branch_name": "refs/heads/master",
"committer_date": "2019-11-12T00:20:51",
"content_id": "55bfbbf9113b7947ec80d284f07bcc2379352d58",
"detected_licenses": [
"MIT"
],
"directory_id": "af1713d6dcaed61b4ba0e59af9a55c4f04cbe8ae",
"extension": "c",
"filename": "for.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 215041356,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 360,
"license": "MIT",
"license_type": "permissive",
"path": "/for.c",
"provenance": "stackv2-0102.json.gz:76193",
"repo_name": "ThomasB123/C",
"revision_date": "2019-11-12T00:20:51",
"revision_id": "4654c1884a861aab57442e3852df2977e7660238",
"snapshot_id": "042af039378f5754ed15c61cf3666bef6fccb91c",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ThomasB123/C/4654c1884a861aab57442e3852df2977e7660238/for.c",
"visit_date": "2020-08-13T21:33:24.646102"
} | stackv2 | // For loop example
// Converts temperatures in Celsius to Fahrenheit
#include <stdio.h>
int main(void) {
double fahr, celsius;
int lower = 0;
int upper = 100;
int step = 10;
printf("C F\n\n");
for (celsius = lower; celsius <= upper; celsius += step) {
fahr = (9.0/5.0) * celsius + 32.0;
printf("%3.0f %6.1f\n", celsius, fahr);
}
return 0;
} | 3.734375 | 4 |
2024-11-18T20:48:45.657866+00:00 | 2017-12-17T12:46:31 | 59d8dda73b4d8bfbd330bad03df7a1293be2b86e | {
"blob_id": "59d8dda73b4d8bfbd330bad03df7a1293be2b86e",
"branch_name": "refs/heads/master",
"committer_date": "2017-12-17T12:46:31",
"content_id": "40e75379ec519c0ced5cd22ecbc9c085ec673069",
"detected_licenses": [
"MIT"
],
"directory_id": "711791acea0ce300c1aa035778ead8392f43c2cd",
"extension": "c",
"filename": "kondo.c",
"fork_events_count": 1,
"gha_created_at": "2017-07-30T11:58:32",
"gha_event_created_at": "2017-07-30T20:29:34",
"gha_language": "C",
"gha_license_id": null,
"github_id": 98794493,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1917,
"license": "MIT",
"license_type": "permissive",
"path": "/kondo.c",
"provenance": "stackv2-0102.json.gz:76451",
"repo_name": "SKantar/KondoRobot",
"revision_date": "2017-12-17T12:46:31",
"revision_id": "041ebc4b4cfa7581da8159f5b64fdb419e1533d0",
"snapshot_id": "3ff46df8240dfb29f46778a0674f864884173ca8",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/SKantar/KondoRobot/041ebc4b4cfa7581da8159f5b64fdb419e1533d0/kondo.c",
"visit_date": "2021-01-01T20:21:17.431137"
} | stackv2 | /*
* Library for moving Kondo robot
* Version 0.1 2016-05-21 Sladjan Kantar (School of Computing)
*
*
* kondo.c
*/
/**
* Make one's bow
*/
void bow(){
int speed = 200;
sbus_initnext();
sbus_setnext( 18, 60 * PWM_DEG ); //groin
sbus_setnext( 12, 60 * PWM_DEG ); //groin
sbus_setnext( 19, 40 * PWM_DEG ); //knee
sbus_setnext( 13, 40 * PWM_DEG ); //knee
sbus_setnext( 6, -70 * PWM_DEG ); //shoulder
sbus_movesync( speed );
sbus_initnext();
sbus_setnext( 18, 80 * PWM_DEG ); //groin
sbus_setnext( 12, 80 * PWM_DEG ); //groin
sbus_setnext( 8, -70 * PWM_DEG ); //elbow
sbus_movesync( speed );
sleep(2);
sbus_initnext();
sbus_setnext( 18, 60 * PWM_DEG ); //groin
sbus_setnext( 12, 60 * PWM_DEG ); //groin
sbus_setnext( 8, 0 * PWM_DEG ); //elbow
sbus_movesync( speed );
sbus_initnext();
sbus_setnext( 18, 0 * PWM_DEG ); //groin
sbus_setnext( 12, 0 * PWM_DEG ); //groin
sbus_setnext( 19, 0 * PWM_DEG ); //knee
sbus_setnext( 13, 0 * PWM_DEG ); //knee
sbus_setnext( 6, 0 * PWM_DEG ); //shoulder
sbus_movesync( speed );
}
/**
* Denial of head
*/
void denial(){
sbus_initnext();
sbus_setnext( 0, 45 * PWM_DEG ); //head
sbus_movesync( speed );
sbus_initnext();
sbus_setnext( 0, -45 * PWM_DEG ); //head
sbus_movesync( speed );
sbus_initnext();
sbus_setnext( 0, 45 * PWM_DEG ); //head
sbus_movesync( speed );
sbus_initnext();
sbus_setnext( 0, -45 * PWM_DEG ); //head
sbus_movesync( speed );
sbus_initnext();
sbus_setnext( 0, 0 * PWM_DEG ); //head
sbus_movesync( speed );
}
/**
* Make an forward step
*/
void step_forward(){
}
/**
* Make an backward step
*/
void step_backward(){
}
/**
* Turn to the left
*/
void rotate_left(){
}
/**
* Turn to the right
*/
void rotate_right(){
} | 2.515625 | 3 |
2024-11-18T20:48:45.821753+00:00 | 2020-05-28T00:19:01 | a84fe344b72584ed5fe160ecda7f121a376fb7b5 | {
"blob_id": "a84fe344b72584ed5fe160ecda7f121a376fb7b5",
"branch_name": "refs/heads/master",
"committer_date": "2020-05-28T00:19:01",
"content_id": "5606f01e9dedf20a8de50c2c7a48ec197a381199",
"detected_licenses": [
"CC0-1.0"
],
"directory_id": "0fa4e3520321bee02a3d204148b89c043f689287",
"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": 229123735,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2659,
"license": "CC0-1.0",
"license_type": "permissive",
"path": "/tutorial_BouncingBall/bball_tutJaen/Codigo/The bouncy ball/BouncingBallFase 3/BouncingBall/source/main.c",
"provenance": "stackv2-0102.json.gz:76709",
"repo_name": "magusti/NDS-hombrew-development",
"revision_date": "2020-05-28T00:19:01",
"revision_id": "15679cc72a377bdaff749440ca82318d4aa5d3e8",
"snapshot_id": "ed09e65702a231a65547c2cdabe18aceccda9017",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/magusti/NDS-hombrew-development/15679cc72a377bdaff749440ca82318d4aa5d3e8/tutorial_BouncingBall/bball_tutJaen/Codigo/The bouncy ball/BouncingBallFase 3/BouncingBall/source/main.c",
"visit_date": "2020-11-26T15:36:30.614877"
} | stackv2 | #include <nds.h>
//Referenias Graficas
#include "gfx_ball.h"
#include "gfx_brick.h"
#include "gfx_gradient.h"
//Entradas tile
#define tile_empty 0 //tile 0 = empty
#define tile_brick 1 //tile 1 = brick
#define tile_gradient 2 //tile 2 = gradient
//macro para calcular memoria BG VRAM
//direccion con el indice de tile
#define tile2bgram(t) (BG_GFX + (t) *16)
//Paletas de entrada
#define pal_bricks 0 //paleta brick (entrada 0->15)
#define pal_gradient 1 //paleta gradient (entrada 16->31)
#define backdrop_colour RGB8( 190, 255, 255 )
#define pal2bgram(p) (BG_PALETTE + (p) * 16)
#define bg0map ((u16*)BG_MAP_RAM(1))
#define bg1map ((u16*)BG_MAP_RAM(2))
void update_logic(){}
void update_graphics(){}
void setupGraphics( void )
{
vramSetBankE( VRAM_E_MAIN_BG );
vramSetBankF( VRAM_F_MAIN_SPRITE );
//generar el primer banco de tile por borrado a cero
int n;
for( n = 0; n < 16; n++ )
{
BG_GFX[n] = 0;
}
for(n = 0; n < 1024; n++)
{
bg0map[n] = 0;
bg1map[n] = 0;
}
int x, y;
for( x = 0; x < 32; x++ )
{
for( y = 0; y < 6; y++ )
{
//formula magica para saber si el tile tiene que voltearse
int hflip = (x & 1) ^ (y & 1);
//establecer la entrada tilemap
bg0map[x + y * 32] = tile_brick | (hflip << 10) | (pal_bricks << 12);
}
REG_BG0VOFS = 112;
for( y = 0; y < 8; y++ )
{
int tile = tile_gradient +y;
bg1map[ x + y * 32 ] = tile | (pal_gradient << 12);
}
}
REG_BLDCNT = BLEND_ALPHA | BLEND_SRC_BG1 | BLEND_DST_BACKDROP;
REG_BLDALPHA = (4) + (16<<8);
videoSetMode( MODE_0_2D | DISPLAY_BG0_ACTIVE | DISPLAY_BG1_ACTIVE);
//Copiando graficos
dmaCopyHalfWords( 3, gfx_brickTiles, tile2bgram( tile_brick ), gfx_brickTilesLen );
dmaCopyHalfWords( 3, gfx_gradientTiles, tile2bgram( tile_gradient ), gfx_gradientTilesLen );
//Paleta direccionada a la memoria de paleta
dmaCopyHalfWords( 3, gfx_brickPal, pal2bgram( pal_bricks ), gfx_brickPalLen );
dmaCopyHalfWords( 3, gfx_gradientPal, pal2bgram( pal_gradient ), gfx_gradientPalLen );
//Asignar Color de fondo
BG_PALETTE[0] = backdrop_colour;
//libnds prefijos del registro de nombres con REG_
REG_BG0CNT = BG_MAP_BASE(1);
REG_BG1CNT = BG_MAP_BASE(2);
}
int main( void )
{
irqInit(); //inicializar interrupciones
irqEnable( IRQ_VBLANK ); //HAbilitar interrupcion vblank
setupGraphics();
while(1)
{
//Periodo de Renderizado
//Actualizacion objetos del juego (Moverlos alrededor, calcular velocidades, etc)
update_logic();
//Espera para periodo vblank
swiWaitForVBlank();
//Periodo vblank: (seguro modificar graficos)
//mover graficos alrededor
update_graphics();
}
//return 0;
}
| 2.46875 | 2 |
2024-11-18T20:48:46.031639+00:00 | 2023-08-19T14:05:02 | e3e3a78460981c1f907f93cc104eee6ab62bc355 | {
"blob_id": "e3e3a78460981c1f907f93cc104eee6ab62bc355",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-19T14:05:02",
"content_id": "44de290449edbcf56f264c4b0989bff361ea2dcf",
"detected_licenses": [
"MIT"
],
"directory_id": "4ed2d6d3646dbcc3676aed7ed6297cc827048876",
"extension": "c",
"filename": "shader.c",
"fork_events_count": 233,
"gha_created_at": "2016-04-01T20:39:14",
"gha_event_created_at": "2023-09-04T18:53:12",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 55260928,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 7138,
"license": "MIT",
"license_type": "permissive",
"path": "/SDL/shader.c",
"provenance": "stackv2-0102.json.gz:76837",
"repo_name": "LIJI32/SameBoy",
"revision_date": "2023-08-19T14:05:02",
"revision_id": "7542de74e750738d3405f496eca0c5fbc6108c5b",
"snapshot_id": "6ece0d745887e66078ae71080eb52415fbb872fb",
"src_encoding": "UTF-8",
"star_events_count": 1424,
"url": "https://raw.githubusercontent.com/LIJI32/SameBoy/7542de74e750738d3405f496eca0c5fbc6108c5b/SDL/shader.c",
"visit_date": "2023-08-29T05:10:29.296103"
} | stackv2 | #include <stdio.h>
#include <string.h>
#include "shader.h"
#include "utils.h"
static const char *vertex_shader = "\n\
#version 150 \n\
in vec4 aPosition;\n\
void main(void) {\n\
gl_Position = aPosition;\n\
}\n\
";
static GLuint create_shader(const char *source, GLenum type)
{
// Create the shader object
GLuint shader = glCreateShader(type);
// Load the shader source
glShaderSource(shader, 1, &source, 0);
// Compile the shader
glCompileShader(shader);
// Check for errors
GLint status = 0;
glGetShaderiv(shader, GL_COMPILE_STATUS, &status);
if (status == GL_FALSE) {
GLchar messages[1024];
glGetShaderInfoLog(shader, sizeof(messages), 0, &messages[0]);
fprintf(stderr, "GLSL Shader Error: %s", messages);
}
return shader;
}
static GLuint create_program(const char *vsh, const char *fsh)
{
// Build shaders
GLuint vertex_shader = create_shader(vsh, GL_VERTEX_SHADER);
GLuint fragment_shader = create_shader(fsh, GL_FRAGMENT_SHADER);
// Create program
GLuint program = glCreateProgram();
// Attach shaders
glAttachShader(program, vertex_shader);
glAttachShader(program, fragment_shader);
// Link program
glLinkProgram(program);
// Check for errors
GLint status;
glGetProgramiv(program, GL_LINK_STATUS, &status);
if (status == GL_FALSE) {
GLchar messages[1024];
glGetProgramInfoLog(program, sizeof(messages), 0, &messages[0]);
fprintf(stderr, "GLSL Program Error: %s", messages);
}
// Delete shaders
glDeleteShader(vertex_shader);
glDeleteShader(fragment_shader);
return program;
}
extern bool uses_gl(void);
bool init_shader_with_name(shader_t *shader, const char *name)
{
if (!uses_gl()) return false;
GLint major = 0, minor = 0;
glGetIntegerv(GL_MAJOR_VERSION, &major);
glGetIntegerv(GL_MINOR_VERSION, &minor);
if (major * 0x100 + minor < 0x302) {
return false;
}
static char master_shader_code[0x801] = {0,};
static char shader_code[0x10001] = {0,};
static char final_shader_code[0x10801] = {0,};
static ssize_t filter_token_location = 0;
if (!master_shader_code[0]) {
FILE *master_shader_f = fopen(resource_path("Shaders/MasterShader.fsh"), "r");
if (!master_shader_f) return false;
fread(master_shader_code, 1, sizeof(master_shader_code) - 1, master_shader_f);
fclose(master_shader_f);
filter_token_location = strstr(master_shader_code, "{filter}") - master_shader_code;
if (filter_token_location < 0) {
master_shader_code[0] = 0;
return false;
}
}
char shader_path[1024];
sprintf(shader_path, "Shaders/%s.fsh", name);
FILE *shader_f = fopen(resource_path(shader_path), "r");
if (!shader_f) return false;
memset(shader_code, 0, sizeof(shader_code));
fread(shader_code, 1, sizeof(shader_code) - 1, shader_f);
fclose(shader_f);
memset(final_shader_code, 0, sizeof(final_shader_code));
memcpy(final_shader_code, master_shader_code, filter_token_location);
strcpy(final_shader_code + filter_token_location, shader_code);
strcat(final_shader_code + filter_token_location,
master_shader_code + filter_token_location + sizeof("{filter}") - 1);
shader->program = create_program(vertex_shader, final_shader_code);
// Attributes
shader->position_attribute = glGetAttribLocation(shader->program, "aPosition");
// Uniforms
shader->resolution_uniform = glGetUniformLocation(shader->program, "output_resolution");
shader->origin_uniform = glGetUniformLocation(shader->program, "origin");
glGenTextures(1, &shader->texture);
glBindTexture(GL_TEXTURE_2D, shader->texture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glBindTexture(GL_TEXTURE_2D, 0);
shader->texture_uniform = glGetUniformLocation(shader->program, "image");
glGenTextures(1, &shader->previous_texture);
glBindTexture(GL_TEXTURE_2D, shader->previous_texture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glBindTexture(GL_TEXTURE_2D, 0);
shader->previous_texture_uniform = glGetUniformLocation(shader->program, "previous_image");
shader->blending_mode_uniform = glGetUniformLocation(shader->program, "frame_blending_mode");
// Program
glUseProgram(shader->program);
GLuint vao;
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
GLuint vbo;
glGenBuffers(1, &vbo);
// Attributes
static GLfloat const quad[16] = {
-1.f, -1.f, 0, 1,
-1.f, +1.f, 0, 1,
+1.f, -1.f, 0, 1,
+1.f, +1.f, 0, 1,
};
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(quad), quad, GL_STATIC_DRAW);
glEnableVertexAttribArray(shader->position_attribute);
glVertexAttribPointer(shader->position_attribute, 4, GL_FLOAT, GL_FALSE, 0, 0);
return true;
}
void render_bitmap_with_shader(shader_t *shader, void *bitmap, void *previous,
unsigned source_width, unsigned source_height,
unsigned x, unsigned y, unsigned w, unsigned h,
GB_frame_blending_mode_t blending_mode)
{
glUseProgram(shader->program);
glUniform2f(shader->origin_uniform, x, y);
glUniform2f(shader->resolution_uniform, w, h);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, shader->texture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, source_width, source_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, bitmap);
glUniform1i(shader->texture_uniform, 0);
glUniform1i(shader->blending_mode_uniform, previous? blending_mode : GB_FRAME_BLENDING_MODE_DISABLED);
if (previous) {
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, shader->previous_texture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, source_width, source_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, previous);
glUniform1i(shader->previous_texture_uniform, 1);
}
glBindFragDataLocation(shader->program, 0, "frag_color");
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
}
void free_shader(shader_t *shader)
{
if (!uses_gl()) return;
GLint major = 0, minor = 0;
glGetIntegerv(GL_MAJOR_VERSION, &major);
glGetIntegerv(GL_MINOR_VERSION, &minor);
if (major * 0x100 + minor < 0x302) {
return;
}
glDeleteProgram(shader->program);
glDeleteTextures(1, &shader->texture);
glDeleteTextures(1, &shader->previous_texture);
}
| 2.375 | 2 |
2024-11-18T20:48:46.347918+00:00 | 2023-08-22T10:28:25 | a97c9cb2aaf9dbe4671e4d56e877b74a42febfdb | {
"blob_id": "a97c9cb2aaf9dbe4671e4d56e877b74a42febfdb",
"branch_name": "refs/heads/main",
"committer_date": "2023-08-22T10:28:25",
"content_id": "041333ef0d146b8c682db321d9e431c0befab65a",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "255dbd3013e6aa689282591f29831cf0355c7a4c",
"extension": "c",
"filename": "sopts.c",
"fork_events_count": 89,
"gha_created_at": "2015-10-09T19:57:17",
"gha_event_created_at": "2023-09-13T18:31:02",
"gha_language": "C",
"gha_license_id": "Apache-2.0",
"github_id": 43977215,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4839,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/stan/sopts.c",
"provenance": "stackv2-0102.json.gz:77224",
"repo_name": "nats-io/nats.c",
"revision_date": "2023-08-22T10:28:25",
"revision_id": "0ac5cd4bb6ffe2c619677f4cdf01b2ad861f8bd9",
"snapshot_id": "9b30c90bc1fd5212e78dbc93e6532007e03e9333",
"src_encoding": "UTF-8",
"star_events_count": 215,
"url": "https://raw.githubusercontent.com/nats-io/nats.c/0ac5cd4bb6ffe2c619677f4cdf01b2ad861f8bd9/src/stan/sopts.c",
"visit_date": "2023-08-28T16:16:41.122238"
} | stackv2 | // Copyright 2018 The NATS Authors
// 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 "sopts.h"
#include "../opts.h"
static void
_stanSubOpts_free(stanSubOptions *opts)
{
if (opts == NULL)
return;
NATS_FREE(opts->durableName);
natsMutex_Destroy(opts->mu);
NATS_FREE(opts);
}
natsStatus
stanSubOptions_Create(stanSubOptions **newOpts)
{
natsStatus s = NATS_OK;
stanSubOptions *opts = NULL;
// Ensure the library is loaded
s = nats_Open(-1);
if (s != NATS_OK)
return s;
opts = (stanSubOptions*) NATS_CALLOC(1, sizeof(stanSubOptions));
if (opts == NULL)
return nats_setDefaultError(NATS_NO_MEMORY);
if (natsMutex_Create(&(opts->mu)) != NATS_OK)
{
NATS_FREE(opts);
return NATS_UPDATE_ERR_STACK(NATS_NO_MEMORY);
}
opts->maxInflight = STAN_SUB_OPTS_DEFAULT_MAX_INFLIGHT;
opts->ackWait = STAN_SUB_OPTS_DEFAULT_ACK_WAIT;
opts->startAt = PB__START_POSITION__NewOnly;
if (s == NATS_OK)
*newOpts = opts;
else
_stanSubOpts_free(opts);
return s;
}
natsStatus
stanSubOptions_SetDurableName(stanSubOptions *opts, const char *durableName)
{
natsStatus s = NATS_OK;
LOCK_AND_CHECK_OPTIONS(opts, 0);
if (opts->durableName != NULL)
{
NATS_FREE(opts->durableName);
opts->durableName = NULL;
}
if (durableName != NULL)
DUP_STRING(s, opts->durableName, durableName);
UNLOCK_OPTS(opts);
return s;
}
natsStatus
stanSubOptions_SetAckWait(stanSubOptions *opts, int64_t wait)
{
LOCK_AND_CHECK_OPTIONS(opts, (wait <= 0));
opts->ackWait = wait;
UNLOCK_OPTS(opts);
return NATS_OK;
}
natsStatus
stanSubOptions_SetMaxInflight(stanSubOptions *opts, int maxInflight)
{
LOCK_AND_CHECK_OPTIONS(opts, (maxInflight < 1));
opts->maxInflight = maxInflight;
UNLOCK_OPTS(opts);
return NATS_OK;
}
natsStatus
stanSubOptions_StartAtSequence(stanSubOptions *opts, uint64_t seq)
{
LOCK_AND_CHECK_OPTIONS(opts, (seq < 1));
opts->startAt = PB__START_POSITION__SequenceStart;
opts->startSequence = seq;
UNLOCK_OPTS(opts);
return NATS_OK;
}
natsStatus
stanSubOptions_StartAtTime(stanSubOptions *opts, int64_t time)
{
LOCK_AND_CHECK_OPTIONS(opts, (time < 0));
opts->startAt = PB__START_POSITION__TimeDeltaStart;
opts->startTime = time;
UNLOCK_OPTS(opts);
return NATS_OK;
}
natsStatus
stanSubOptions_StartAtTimeDelta(stanSubOptions *opts, int64_t delta)
{
LOCK_AND_CHECK_OPTIONS(opts, (delta < 0));
opts->startAt = PB__START_POSITION__TimeDeltaStart;
opts->startTime = nats_Now() - delta;
UNLOCK_OPTS(opts);
return NATS_OK;
}
natsStatus
stanSubOptions_StartWithLastReceived(stanSubOptions *opts)
{
LOCK_AND_CHECK_OPTIONS(opts, 0);
opts->startAt = PB__START_POSITION__LastReceived;
UNLOCK_OPTS(opts);
return NATS_OK;
}
natsStatus
stanSubOptions_DeliverAllAvailable(stanSubOptions *opts)
{
LOCK_AND_CHECK_OPTIONS(opts, 0);
opts->startAt = PB__START_POSITION__First;
UNLOCK_OPTS(opts);
return NATS_OK;
}
natsStatus
stanSubOptions_SetManualAckMode(stanSubOptions *opts, bool manual)
{
LOCK_AND_CHECK_OPTIONS(opts, 0);
opts->manualAcks = manual;
UNLOCK_OPTS(opts);
return NATS_OK;
}
natsStatus
stanSubOptions_clone(stanSubOptions **clonedOpts, stanSubOptions *opts)
{
natsStatus s = NATS_OK;
stanSubOptions *cloned = NULL;
int muSize;
s = stanSubOptions_Create(&cloned);
if (s != NATS_OK)
return NATS_UPDATE_ERR_STACK(s);
natsMutex_Lock(opts->mu);
muSize = sizeof(cloned->mu);
// Make a blind copy first...
memcpy((char*)cloned + muSize, (char*)opts + muSize,
sizeof(stanSubOptions) - muSize);
// Then remove all pointers, so that if we fail while
// copying them, and free the cloned, we don't free the pointers
// from the original.
cloned->durableName = NULL;
s = stanSubOptions_SetDurableName(cloned, opts->durableName);
if (s == NATS_OK)
*clonedOpts = cloned;
else
_stanSubOpts_free(cloned);
natsMutex_Unlock(opts->mu);
return s;
}
void
stanSubOptions_Destroy(stanSubOptions *opts)
{
if (opts == NULL)
return;
_stanSubOpts_free(opts);
}
| 2.09375 | 2 |
2024-11-18T20:48:46.550830+00:00 | 2016-04-21T16:53:57 | 163b47bd33e38322871e719ba6cce390b3fa9c53 | {
"blob_id": "163b47bd33e38322871e719ba6cce390b3fa9c53",
"branch_name": "refs/heads/master",
"committer_date": "2016-04-21T16:53:57",
"content_id": "16b2b5059c703e8eea1ed54d5f3706b87378757e",
"detected_licenses": [
"MIT"
],
"directory_id": "2c3e5676fde1a80d3e0cda0e2a4b69309445b288",
"extension": "c",
"filename": "diffprocio.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": 5554,
"license": "MIT",
"license_type": "permissive",
"path": "/src/diffproc/diffprocio.c",
"provenance": "stackv2-0102.json.gz:77481",
"repo_name": "standardgalactic/SeRPeNT",
"revision_date": "2016-04-21T16:53:57",
"revision_id": "40846923672b19a700b84fa332ac5df07ffb86cc",
"snapshot_id": "0e0821524b75d93d9124dfc2b0173e737fbbffcd",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/standardgalactic/SeRPeNT/40846923672b19a700b84fa332ac5df07ffb86cc/src/diffproc/diffprocio.c",
"visit_date": "2022-01-27T04:29:54.666862"
} | stackv2 | #include <diffproc/diffprocio.h>
/*
* Generate a vector of gaussian white noise adjusted to a given mean and variance.
*
* Vector is generated by the Central Limit Thorem Method, that states that
* the sum of N randoms will approach normal distribution as N approaches infinity.
* N is recommended to be >= 20.
*
* @reference Jeruchim, "Simulation of communication systems"
* 1st Ed. Springer, 1992.
*
* @arg const double signal[]
* Deterministic signal
* @arg const double mean
* Mean value which the vector will be adjusted for
* @arg const double variance
* Variance value which the vector will be adjusted for
* @arg double* noise
* The Gaussian white noise vector
* @arg int nlen
* Length of the gaussian noise vector
*/
void pgnoise(const double signal[], const double mean, const double variance, double* noise, int nlen)
{
double x = 0;
int i, j;
for (i = 0; i < nlen; i++) {
for (j = 0; j < MAX_GNOISE_N; j++) {
double u = (double) rand() / (double)RAND_MAX;
x += u;
}
// for uniform randoms in [0,1], mu = 0.5 and var = 1/12
x = x - MAX_GNOISE_N / 2; // set mean to 0
x = x * sqrt(12 / MAX_GNOISE_N); // adjust variance to 1
// modify x in order to have a particular mean and variance
noise[i] = mean + sqrt(variance) * x;
}
}
/*
* next_diffproc_feature
*
* @see include/diffproc/diffprocio.h
*/
int next_diffproc_feature(FILE* bedf, feature_struct_diffproc* feature)
{
char *line = NULL;
char *token, *index;
size_t len = 0;
ssize_t read;
read = getline(&line, &len, bedf);
if (read < 0) {
free(line);
return(0);
}
if ((token = strtok(line, "\t")) == NULL) {
free(line);
return(-1);
}
strncpy(feature->chromosome, token, MAX_FEATURE);
if ((token = strtok(NULL, "\t")) == NULL) {
free(line);
return(-1);
}
feature->start = atoi(token);
if ((token = strtok(NULL, "\t")) == NULL) {
free(line);
return(-1);
}
feature->end = atoi(token);
if ((token = strtok(NULL, "\t")) == NULL) {
free(line);
return(-1);
}
strncpy(feature->name, token, MAX_FEATURE);
if ((token = strtok(NULL, "\t")) == NULL) {
free(line);
return(-1);
}
feature->score = atof(token);
if ((token = strtok(NULL, "\t")) == NULL) {
free(line);
return(-1);
}
if (strcmp(token, "+") == 0) feature->strand = FWD_STRAND;
else feature->strand = REV_STRAND;
if ((token = strtok(NULL, "\t")) == NULL) {
free(line);
return(-1);
}
if (strcmp(token, "NOVEL") == 0) feature->status = 0;
else feature->status = 1;
if ((token = strtok(NULL, "\t")) == NULL) {
free(line);
return(-1);
}
index = token;
while(index[1]) ++index;
if (*index == '\n') *index = '\0';
feature->cluster = atoi(token);
free(line);
return(1);
}
/*
* next_diffproc_profile
*
* @see include/diffproc/diffprocio.h
*/
int next_diffproc_profile(FILE* fp, profile_struct_diffproc* profile)
{
char *line = NULL;
char *token, *feature, *cline;
size_t len = 0;
ssize_t read;
int i;
read = getline(&line, &len, fp);
if (read < 0) {
free(line);
return(0);
}
cline = (char*) malloc((strlen(line) + 1) * sizeof(char));
strcpy(cline, line);
if ((token = strtok(line, "\t")) == NULL) {
free(cline);
free(line);
return(-1);
}
if ((feature = strtok(token, ":")) == NULL) {
free(cline);
free(line);
return(-1);
}
strcpy(profile->chromosome, feature);
if ((feature = strtok(NULL, "-")) == NULL) {
free(cline);
free(line);
return(-1);
}
profile->start = atoi(feature);
if ((feature = strtok(NULL, ":")) == NULL) {
free(cline);
free(line);
return(-1);
}
profile->end = atoi(feature);
profile->length = profile->end - profile->start + 1;
if ((feature = strtok(NULL, ":")) == NULL) {
free(cline);
free(line);
return(-1);
}
if (strcmp(feature, "+") == 0)
profile->strand = FWD_STRAND;
else if (strcmp(feature, "-") == 0)
profile->strand = REV_STRAND;
else {
free(cline);
free(line);
return(-1);
}
profile->profile = (double*) malloc((profile->end - profile->start + 1) * sizeof(double));
if ((token = strtok(cline, "\t")) == NULL) {
free(cline);
free(line);
return(-1);
}
for (i = 0; i < (profile->end - profile->start + 1); i++) {
if ((token = strtok(NULL, "\t")) != NULL)
profile->profile[i] = (double) atof(token);
else {
free(cline);
free(line);
return(-1);
}
}
strncpy(profile->annotation, "unknown", MAX_FEATURE);
pgnoise(profile->profile, gsl_stats_mean(profile->profile, 1, profile->length), gsl_stats_variance(profile->profile, 1, profile->length), profile->noise, MAX_PROFILE_LENGTH);
profile->cluster = -1;
profile->position = -1;
profile->differential = 0;
profile->partner = NULL;
free(cline);
free(line);
return(1);
}
/*
* find_clusters
*
* @see include/diffproc/diffprocio.h
*/
int find_clusters(FILE* bedf)
{
feature_struct_diffproc feature;
int result;
int ncl = -1;
while((result = next_diffproc_feature(bedf, &feature) > 0)) {
if (ncl < feature.cluster)
ncl = feature.cluster;
}
return(ncl);
}
/*
* allocate_clusters
*
* @see include/diffproc/diffprocio.h
*/
void allocate_clusters(FILE* bedf, int* profiles_per_cluster)
{
feature_struct_diffproc feature;
int result;
while((result = next_diffproc_feature(bedf, &feature) > 0))
profiles_per_cluster[feature.cluster - 1]++;
}
| 2.375 | 2 |
2024-11-18T20:48:46.737326+00:00 | 2023-07-25T00:14:43 | a0724c81a99a7602c40613c5af3b2f0ea735c736 | {
"blob_id": "a0724c81a99a7602c40613c5af3b2f0ea735c736",
"branch_name": "refs/heads/develop",
"committer_date": "2023-07-25T05:28:12",
"content_id": "07d275353fa0c3fb5b563f5a16ef1045c4f905cc",
"detected_licenses": [
"MIT"
],
"directory_id": "41969c213434c5a5942d52f9f23993a65613a52e",
"extension": "h",
"filename": "setproctitle.h",
"fork_events_count": 35,
"gha_created_at": "2015-10-21T15:39:36",
"gha_event_created_at": "2023-07-25T05:04:35",
"gha_language": "Go",
"gha_license_id": "MIT",
"github_id": 44686588,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 6969,
"license": "MIT",
"license_type": "permissive",
"path": "/vendor/github.com/ErikDubbelboer/gspt/setproctitle.h",
"provenance": "stackv2-0102.json.gz:77738",
"repo_name": "shieldproject/shield",
"revision_date": "2023-07-25T00:14:43",
"revision_id": "9f737cea15b80855f35c61fa2af97819a883db72",
"snapshot_id": "69f25bd6cf37a0f2c480f05198c3a908a636566e",
"src_encoding": "UTF-8",
"star_events_count": 121,
"url": "https://raw.githubusercontent.com/shieldproject/shield/9f737cea15b80855f35c61fa2af97819a883db72/vendor/github.com/ErikDubbelboer/gspt/setproctitle.h",
"visit_date": "2023-08-21T12:27:27.255840"
} | stackv2 | /* ==========================================================================
* setproctitle.h - Linux/Darwin setproctitle.
* --------------------------------------------------------------------------
* Copyright (C) 2010 William Ahern
* Copyright (C) 2013 Salvatore Sanfilippo
* Copyright (C) 2013 Stam He
* Copyright (C) 2013 Erik Dubbelboer
*
* 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 _GNU_SOURCE
#define _GNU_SOURCE
#endif
#include <stddef.h> // NULL size_t
#include <stdarg.h> // va_list va_start va_end
#include <stdlib.h> // malloc(3) setenv(3) clearenv(3) setproctitle(3) getprogname(3)
#include <stdio.h> // vsnprintf(3) snprintf(3)
#include <string.h> // strlen(3) strdup(3) memset(3) memcpy(3)
#include <errno.h> /* program_invocation_name program_invocation_short_name */
#include <sys/param.h> /* os versions */
#include <sys/types.h> /* freebsd setproctitle(3) */
#include <unistd.h> /* freebsd setproctitle(3) */
#if !defined(HAVE_SETPROCTITLE)
#if (__NetBSD__ || __FreeBSD__ || __OpenBSD__)
#define HAVE_SETPROCTITLE 1
#if (__FreeBSD__ && __FreeBSD_version > 1200000)
#define HAVE_SETPROCTITLE_FAST 1
#else
#define HAVE_SETPROCTITLE_FAST 0
#endif
#else
#define HAVE_SETPROCTITLE 0
#define HAVE_SETPROCTITLE_FAST 0
#endif
#endif
#if HAVE_SETPROCTITLE
#define HAVE_SETPROCTITLE_REPLACEMENT 0
#elif (defined __linux || defined __APPLE__)
#define HAVE_SETPROCTITLE_REPLACEMENT 1
#else
#define HAVE_SETPROCTITLE_REPLACEMENT 0
#endif
#if HAVE_SETPROCTITLE_REPLACEMENT
#ifndef SPT_MAXTITLE
#define SPT_MAXTITLE 255
#endif
extern char **environ;
static struct {
// Original value.
const char *arg0;
// First enviroment variable.
char* env0;
// Title space available.
char* base;
char* end;
// Pointer to original nul character within base.
char *nul;
int reset;
} SPT;
#ifndef SPT_MIN
#define SPT_MIN(a, b) (((a) < (b))? (a) : (b))
#endif
static inline size_t spt_min(size_t a, size_t b) {
return SPT_MIN(a, b);
}
static char **spt_find_argv_from_env(int argc, char *arg0) {
int i;
char **buf = NULL;
char *ptr;
char *limit;
if (!(buf = (char **)malloc((argc + 1) * sizeof(char *)))) {
return NULL;
}
buf[argc] = NULL;
// Walk back from environ until you find argc-1 null-terminated strings.
// Don't look for argv[0] as it's probably not preceded by 0.
ptr = SPT.env0;
limit = ptr - 8192; // TODO: empiric limit: should use MAX_ARG
--ptr;
for (i = argc - 1; i >= 1; --i) {
if (*ptr) {
return NULL;
}
--ptr;
while (*ptr && ptr > limit) { --ptr; }
if (ptr <= limit) {
return NULL;
}
buf[i] = (ptr + 1);
}
// The first arg has not a zero in front. But what we have is reliable
// enough (modulo its encoding). Check if it is exactly what found.
//
// The check is known to fail on OS X with locale C if there are
// non-ascii characters in the executable path.
ptr -= strlen(arg0);
if (ptr <= limit) {
return NULL;
}
if (strcmp(ptr, arg0)) {
return NULL;
}
buf[0] = ptr;
return buf;
}
static int spt_init1() {
// Store a pointer to the first environment variable since go
// will overwrite environment.
SPT.env0 = environ[0];
return 2;
}
static int spt_fast_init1() {
return 0;
}
static void spt_init2(int argc, char *arg0) {
char **argv = spt_find_argv_from_env(argc, arg0);
char **envp = &SPT.env0;
char *base, *end, *nul, *tmp;
int i;
if (!(base = argv[0]))
return;
nul = &base[strlen(base)];
end = nul + 1;
for (i = 0; i < argc || (i >= argc && argv[i]); i++) {
if (!argv[i] || argv[i] < end)
continue;
end = argv[i] + strlen(argv[i]) + 1;
}
for (i = 0; envp[i]; i++) {
if (envp[i] < end)
continue;
end = envp[i] + strlen(envp[i]) + 1;
}
if (!(SPT.arg0 = strdup(argv[0])))
return;
#if __GLIBC__
if (!(tmp = strdup(program_invocation_name)))
return;
program_invocation_name = tmp;
if (!(tmp = strdup(program_invocation_short_name)))
return;
program_invocation_short_name = tmp;
#elif __APPLE__
if (!(tmp = strdup(getprogname())))
return;
setprogname(tmp);
#endif
memset(base, 0, end - base);
SPT.nul = nul;
SPT.base = base;
SPT.end = end;
return;
}
static void setproctitle(const char *fmt, ...) {
char buf[SPT_MAXTITLE + 1]; // Use buffer in case argv[0] is passed.
va_list ap;
char *nul;
int len;
if (!SPT.base)
return;
if (fmt) {
va_start(ap, fmt);
len = vsnprintf(buf, sizeof buf, fmt, ap);
va_end(ap);
} else {
len = snprintf(buf, sizeof buf, "%s", SPT.arg0);
}
if (len <= 0) {
return;
}
if (!SPT.reset) {
memset(SPT.base, 0, SPT.end - SPT.base);
SPT.reset = 1;
} else {
memset(SPT.base, 0, spt_min(sizeof buf, SPT.end - SPT.base));
}
len = spt_min(len, spt_min(sizeof buf, SPT.end - SPT.base) - 1);
memcpy(SPT.base, buf, len);
nul = &SPT.base[len];
if (nul < SPT.nul) {
memset(nul, ' ', SPT.nul - nul);
} else if (nul == SPT.nul && &nul[1] < SPT.end) {
*SPT.nul = ' ';
*++nul = '\0';
}
}
#else // HAVE_SETPROCTITLE_REPLACEMENT
static int spt_init1() {
#if HAVE_SETPROCTITLE
return 1;
#else
return 0;
#endif
}
static int spt_fast_init1() {
#if HAVE_SETPROCTITLE_FAST
return 1;
#else
return 0;
#endif
}
static void spt_init2(int argc, char *arg0) {
(void)argc;
(void)arg0;
}
#endif // HAVE_SETPROCTITLE_REPLACEMENT
static void spt_setproctitle(const char *title) {
#if HAVE_SETPROCTITLE || HAVE_SETPROCTITLE_REPLACEMENT
setproctitle("%s", title);
#else
(void)title;
#endif
}
static void spt_setproctitle_fast(const char *title) {
#if HAVE_SETPROCTITLE_FAST
setproctitle_fast("%s", title);
#else
(void)title;
#endif
}
| 2.078125 | 2 |
2024-11-18T20:48:46.885031+00:00 | 2017-12-31T01:19:26 | ce54b1992d7a7cc7c2155818b94834746d3b890c | {
"blob_id": "ce54b1992d7a7cc7c2155818b94834746d3b890c",
"branch_name": "refs/heads/master",
"committer_date": "2017-12-31T01:19:26",
"content_id": "cd8df698d0d48f82b8a23f5271db590c10411d61",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "35b71f0329e774b346d643d9df4c58182597eabd",
"extension": "c",
"filename": "15.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": 893,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/c/15.c",
"provenance": "stackv2-0102.json.gz:77867",
"repo_name": "pdobrzynski/adventofcode-rb-2017",
"revision_date": "2017-12-31T01:19:26",
"revision_id": "a1b7b2adb0aa1e03ecc07e75ac435897cac39d46",
"snapshot_id": "da0f53e4796c2c0ac0ccc202d83ec2e2cfb15361",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/pdobrzynski/adventofcode-rb-2017/a1b7b2adb0aa1e03ecc07e75ac435897cac39d46/c/15.c",
"visit_date": "2021-05-05T16:14:16.053729"
} | stackv2 | #include <stdint.h>
static uint64_t next(uint64_t g, uint16_t factor) {
g *= factor;
// This is an optimised way to take remainder modulo a Mersenne prime.
// But newer versions of GCC might already know how to optimise that!
// So might not be necessary to explicitly do this.
while (g >= 0x7fffffff) {
g = (g & 0x7fffffff) + (g >> 31);
}
return g;
}
static uint64_t part(uint64_t a, uint64_t b, uint64_t limit, uint8_t mod_a, uint8_t mod_b) {
uint64_t c = 0;
for (uint64_t i = 0; i < limit; ++i) {
do {
a = next(a, 16807);
} while (a % mod_a != 0);
do {
b = next(b, 48271);
} while (b % mod_b != 0);
if ((a & 0xffff) == (b & 0xffff)) {
c += 1;
}
}
return c;
}
uint64_t part1(uint64_t a, uint64_t b) {
return part(a, b, 40000000, 1, 1);
}
uint64_t part2(uint64_t a, uint64_t b) {
return part(a, b, 5000000, 4, 8);
}
| 2.96875 | 3 |
2024-11-18T20:48:47.486487+00:00 | 2023-02-16T11:27:40 | 6ebb077198847039b61af4d05bc00649b036fdf3 | {
"blob_id": "6ebb077198847039b61af4d05bc00649b036fdf3",
"branch_name": "refs/heads/main",
"committer_date": "2023-02-16T14:59:16",
"content_id": "66e3e881c696621d7c0fd92b29dfed54d2bf4530",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "e8302c75d770d1608b317d6af5c483bbad6c0493",
"extension": "c",
"filename": "targets.c",
"fork_events_count": 32,
"gha_created_at": "2016-08-05T22:14:50",
"gha_event_created_at": "2022-04-05T17:14:07",
"gha_language": "C",
"gha_license_id": "Apache-2.0",
"github_id": 65052293,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 341,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/tests/kernel/mem_protect/protection/src/targets.c",
"provenance": "stackv2-0102.json.gz:78384",
"repo_name": "intel/zephyr",
"revision_date": "2023-02-16T11:27:40",
"revision_id": "06d5bc51b580777079bb0b7e769e4127598ea5ee",
"snapshot_id": "819362089aa44ae378a5558f3b222197aaa811f7",
"src_encoding": "UTF-8",
"star_events_count": 32,
"url": "https://raw.githubusercontent.com/intel/zephyr/06d5bc51b580777079bb0b7e769e4127598ea5ee/tests/kernel/mem_protect/protection/src/targets.c",
"visit_date": "2023-09-04T00:20:35.217393"
} | stackv2 | /*
* Copyright (c) 2017 Intel Corp.
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <zephyr/kernel.h>
#include <zephyr/sys/printk.h>
#include "targets.h"
const uint32_t rodata_var = RODATA_VALUE;
uint8_t data_buf[BUF_SIZE] __aligned(sizeof(int));
int overwrite_target(int i)
{
printk("text not modified\n");
return (i - 1);
}
| 2.046875 | 2 |
2024-11-18T20:48:47.589125+00:00 | 2023-05-13T23:51:51 | b4d7534f6c8d1000a025c41e53a4f538f4f6bf10 | {
"blob_id": "b4d7534f6c8d1000a025c41e53a4f538f4f6bf10",
"branch_name": "refs/heads/main",
"committer_date": "2023-05-13T23:51:51",
"content_id": "d917d73400de3e78fa2c905b5429ed46f193c916",
"detected_licenses": [
"MIT"
],
"directory_id": "592977275dab4c9efa2550cf78387d8951d06e2e",
"extension": "c",
"filename": "curry.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 352899500,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5166,
"license": "MIT",
"license_type": "permissive",
"path": "/curry.c",
"provenance": "stackv2-0102.json.gz:78512",
"repo_name": "dlenski/c-curry",
"revision_date": "2023-05-13T23:51:51",
"revision_id": "89f108a5ce42a0043dc604bb01ee8ff9829eb88a",
"snapshot_id": "6e6bb844325e982dca52d514589398cc79098a1f",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/dlenski/c-curry/89f108a5ce42a0043dc604bb01ee8ff9829eb88a/curry.c",
"visit_date": "2023-05-27T02:59:52.557069"
} | stackv2 | /*
* Author: Daniel Lenski <dlenski@gmail.com>
* Copyright © 2021 Daniel Lenski
*
* 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 program demonstrates how to curry a 2-parameter function into
* a 1-parameter function, in C, for the x86-64 architecture and
* System V ABI.
*
* It is based on the "Trampoline Illustration" from
* https://nullprogram.com/blog/2019/11/15, but with the trampoline
* stored on the heap rather than the stack. This is much safer
* because it means we don't have to disable the compiler's stack
* execution protection (no 'gcc -Wl,-z,execstack').
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/mman.h>
#include <stdint.h>
#define PAGE_START(P) ((uintptr_t)(P) & ~(pagesize-1))
#define PAGE_END(P) (((uintptr_t)(P) + pagesize - 1) & ~(pagesize-1))
/* x86-64 ABI passes parameters in rdi, rsi, rdx, rcx, r8, r9
* (https://wiki.osdev.org/System_V_ABI), and return value
* goes in %rax.
*
* Binary format of useful opcodes:
*
* 0xbf, [le32] = movl $imm32, %edi (1st param)
* 0xbe, [le32] = movl $imm32, %esi (2nd param)
* 0xba, [le32] = movl $imm32, %edx (3rd param)
* 0xb9, [le32] = movl $imm32, %ecx (4rd param)
* 0xb8, [le32] = movl $imm32, %eax
* 0x48, 0x__, [le64] = movq $imm64, %r__
* 0xff, 0xe0 = jmpq *%rax
* 0xe9, [le32] = jmpq *(%rip + $imm32)
*/
typedef uint32_t (*one_param_func_ptr)(uint32_t);
one_param_func_ptr curry_two_param_func(
void *two_param_func,
uint32_t second_param)
{
/* We create a small buffer for executable code on the HEAP.
* We fill it in with a "curried" version of
* uint32_t (*two_param_func)(uint32_t a, uint32_t b),
* using the Linux x86-64 ABI. The curried version can be
* treated as if it were
* uint32_t (*one_param_func)(uint32_t a).
*/
const size_t BUFSZ = 17;
uint8_t *volatile buf = malloc(BUFSZ);
if (!buf)
return NULL;
/* If relative jump offset fits in 32 bits, then we
* use RIP-relative JMP and fit it all in 10 bytes:
* movl $imm32, %esi ; $imm32 = second_param
* jmpl %rip + $imm32 ; $imm32 = offset of fp
*
* ... otherwise we need all 17 bytes:
*
* movl $imm32, %esi ; $imm32 = second_param
* movq $imm64, %rax ; $imm64 = fp
* jmpq *%rax
*/
uintptr_t fp = (uintptr_t)two_param_func;
intptr_t rel = (uint8_t*)two_param_func - &buf[10];
buf[0] = 0xbe; *(uint32_t*)(buf+1) = second_param ; /* movl $imm32, %esi */
if (rel >= INT32_MIN && rel <= INT32_MAX) {
printf("rel = %s0x%08lx\n", rel < 0 ? "-" : "", rel < 0 ? -rel : rel);
buf[5] = 0xe9; *(int32_t*)(&buf[6]) = rel; /* jmpl *(%rip + $imm32) */
} else {
buf[5] = 0x48; buf[6] = 0xb8; /* movq $imm64, %rax */
*(uintptr_t*)&buf[7] = fp;
buf[15] = 0xff; buf[16] = 0xe0; /* jmpq *%rax */
}
/* We do NOT want to make the stack executable,
* but we NEED the heap-allocated buf to be executable.
* Compiling with 'gcc -Wl,-z,execstack' would do BOTH.
*
* This appears to be the right way to only make a heap object executable:
* https://stackoverflow.com/questions/23276488/why-is-execstack-required-to-execute-code-on-the-heap
*/
uintptr_t pagesize = sysconf(_SC_PAGE_SIZE);
mprotect((void *)PAGE_START(buf),
PAGE_END(buf + BUFSZ) - PAGE_START(buf),
PROT_READ|PROT_WRITE|PROT_EXEC);
return (one_param_func_ptr)buf;
}
/********************************************/
int print_both_params(int a, int b)
{
printf("Called with a=%d, b=%d\n", a, b);
return a+b;
}
int main(int argc, char **argv)
{
one_param_func_ptr print_both_params_b4 =
curry_two_param_func(print_both_params, 4);
one_param_func_ptr print_both_params_b256 =
curry_two_param_func(print_both_params, 256);
print_both_params_b4(3); // "Called with a=3, b=4"
print_both_params_b256(6); // "Called with a=6, b=256"
return 0;
}
| 2.546875 | 3 |
2024-11-18T20:48:47.651897+00:00 | 2017-03-04T03:21:35 | 7a96616f6ff516fe02f01368bab4a276f800d063 | {
"blob_id": "7a96616f6ff516fe02f01368bab4a276f800d063",
"branch_name": "refs/heads/master",
"committer_date": "2017-03-04T03:21:35",
"content_id": "4da98f2165747d4c4aaf297ccee033e3f09ab83b",
"detected_licenses": [
"MIT"
],
"directory_id": "82e0bc6a6b1d884d74f3e9279a6d5264a077c2c7",
"extension": "h",
"filename": "uthr.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 83861446,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 898,
"license": "MIT",
"license_type": "permissive",
"path": "/Assignment 6/uthr.h",
"provenance": "stackv2-0102.json.gz:78641",
"repo_name": "PeiyiZheng/Operating-Systems",
"revision_date": "2017-03-04T03:21:35",
"revision_id": "6908e376f90615d74c6cdc2ad8b5410ab3c7a99d",
"snapshot_id": "fb105db231bf100705ab5c4728d1c7fed561f4a5",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/PeiyiZheng/Operating-Systems/6908e376f90615d74c6cdc2ad8b5410ab3c7a99d/Assignment 6/uthr.h",
"visit_date": "2021-01-20T05:40:10.997139"
} | stackv2 | /* Userland spinlock public API */
#define NTHR 256
struct uspin; /* forward declaration */
int uspin_init (struct uspin *sem);
void uspin_acquire(struct uspin *sem);
void uspin_release(struct uspin *sem);
void uspin_destroy(struct uspin *sem);
/* Userland semaphore public API */
struct usem; /* forward declaration */
int usem_init (struct usem *sem, uint initial_count);
void usem_acquire(struct usem *sem);
void usem_release(struct usem *sem);
void usem_destroy(struct usem *sem);
/* Userland thread library public API */
int uthr_init(unsigned int stack_size);
int uthr_create(void (*f)(void *), void *arg);
void uthr_exit(void *baton);
int uthr_join(int tid, void **hand);
/* Thread safe wrappers! */
void *uthr_malloc(int);
void uthr_free(void *);
// Assignment 6
// Thread Struct
struct uthr;
//Define thread states
#define UNUSED 0
#define RUNNABLE 1
#define ZOMBIE 2
| 2.25 | 2 |
2024-11-18T20:48:51.628610+00:00 | 2021-06-10T14:57:30 | d5f68a181664dbb140062f98785c1ec89014c3ee | {
"blob_id": "d5f68a181664dbb140062f98785c1ec89014c3ee",
"branch_name": "refs/heads/main",
"committer_date": "2021-06-10T14:57:30",
"content_id": "deee9a069a3dd0403fda95fe77e386da9c1b2167",
"detected_licenses": [
"MIT"
],
"directory_id": "28bf7793cde66074ac6cbe2c76df92bd4803dab9",
"extension": "c",
"filename": "Question 2.c",
"fork_events_count": 135,
"gha_created_at": "2021-03-15T23:37:26",
"gha_event_created_at": "2021-06-10T14:57:31",
"gha_language": "Java",
"gha_license_id": "MIT",
"github_id": 348153476,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 658,
"license": "MIT",
"license_type": "permissive",
"path": "/answers/AkashKumar/Day13/Question 2.c",
"provenance": "stackv2-0102.json.gz:84021",
"repo_name": "Codechef-SRM-NCR-Chapter/30-DaysOfCode-March-2021",
"revision_date": "2021-06-10T14:57:30",
"revision_id": "66c7d85025481074c93cfda7853b145c88a30da4",
"snapshot_id": "2dee33e057ba22092795a6ecc6686a9d31607c9d",
"src_encoding": "UTF-8",
"star_events_count": 22,
"url": "https://raw.githubusercontent.com/Codechef-SRM-NCR-Chapter/30-DaysOfCode-March-2021/66c7d85025481074c93cfda7853b145c88a30da4/answers/AkashKumar/Day13/Question 2.c",
"visit_date": "2023-05-29T10:33:31.795738"
} | stackv2 | #include <stdio.h>
int palindrome(int arr[], int first, int last);
int main()
{
int n, i;
printf("Enter the no of elements in array:- ");
scanf("%d",&n);
int a[n];
for(i=0;i<n;i++)
{
printf("Enter element no %d of array",i+1);
scanf("%d", &a[i]);
}
if (palindrome(a, 0, n - 1) == 1)
printf("PALINDROME");
else
printf("NOT PALINDROME");
return 0;
}
int palindrome(int arr[], int first, int last)
{
if (first >= last) {
return 1;
}
if (arr[first] == arr[last]) {
return palindrome(arr, first + 1, last - 1);
}
else {
return 0;
}
}
| 3.546875 | 4 |
2024-11-18T20:48:51.787246+00:00 | 2021-07-10T07:27:56 | 219c51b21847746dd05930a1fadbf4b8e0633d8d | {
"blob_id": "219c51b21847746dd05930a1fadbf4b8e0633d8d",
"branch_name": "refs/heads/master",
"committer_date": "2021-07-10T07:27:56",
"content_id": "a5344e19242ed8fb29a685303ad0ed5743d701eb",
"detected_licenses": [
"MIT"
],
"directory_id": "ff5fa972c44a80ee89bbd5693790fb2ef7a05758",
"extension": "c",
"filename": "UsbMailDevice.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": 3267,
"license": "MIT",
"license_type": "permissive",
"path": "/C/UsbMailDevice.c",
"provenance": "stackv2-0102.json.gz:84150",
"repo_name": "fengjixuchui/UsbMailNotifier",
"revision_date": "2021-07-10T07:27:56",
"revision_id": "f87c79783e2df72b189e4b8aff46d0dd84ebff3a",
"snapshot_id": "ab1653302ca0d974e10801229ebfd241e27c1d65",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/fengjixuchui/UsbMailNotifier/f87c79783e2df72b189e4b8aff46d0dd84ebff3a/C/UsbMailDevice.c",
"visit_date": "2023-06-11T21:52:16.722992"
} | stackv2 |
// Minimalist USB "Mail Notifier" LED device support
#define WIN32_LEAN_AND_MEAN
#define WINVER 0x0A00 // _WIN32_WINNT_WIN10
#define _WIN32_WINNT 0x0A00
#include <windows.h>
#include <stdio.h>
#include <SetupAPI.h>
#pragma comment(lib, "SetupAPI.lib")
#ifdef __cplusplus
extern "C"
{
#endif
#define INITGUID
#include <hidsdi.h>
#include <hidclass.h>
#ifdef __cplusplus
}
#endif
#pragma comment(lib, "hid.lib")
// Open the first supported HID LED mail light device if any
HANDLE OpenMailDevice()
{
HANDLE result = NULL;
// Get HID device information set
HDEVINFO devNfoSet = SetupDiGetClassDevsA(&GUID_DEVINTERFACE_HID, NULL, NULL, (DIGCF_PRESENT | DIGCF_DEVICEINTERFACE));
if (devNfoSet != INVALID_HANDLE_VALUE)
{
// Iterate over HID devices..
for(DWORD i = 0; ; i++)
{
// Next device by index
SP_DEVICE_INTERFACE_DATA DeviceInterfaceData;
DeviceInterfaceData.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
if (!SetupDiEnumDeviceInterfaces(devNfoSet, NULL, &GUID_DEVINTERFACE_HID, i, &DeviceInterfaceData))
// No more devices..
break;
else
{
// Get registered device path
BYTE pathBuffer[256];
PSP_DEVICE_INTERFACE_DETAIL_DATA_A deviceDetails = (PSP_DEVICE_INTERFACE_DETAIL_DATA_A) pathBuffer;
deviceDetails->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA_A);
if (SetupDiGetDeviceInterfaceDetailA(devNfoSet, &DeviceInterfaceData, deviceDetails, sizeof(pathBuffer), NULL, NULL))
{
//printf("DevicePath: \"%s\"\n", deviceDetails->DevicePath);
// Open an overlapped R/W handle to the device
HANDLE deviceHandle = CreateFileA(deviceDetails->DevicePath, (GENERIC_WRITE | GENERIC_READ), 0, NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
if (deviceHandle != INVALID_HANDLE_VALUE)
{
// Get the Vendor ID and Product ID for it
HIDD_ATTRIBUTES attrib;
attrib.Size = sizeof(HIDD_ATTRIBUTES);
if (HidD_GetAttributes(deviceHandle, &attrib))
{
//printf("Product/Vendor: %04X %04X\n", Attrib.ProductID, Attrib.VendorID);
// Match wanted mail notifier device?
// Could also match by manufacture or product string as L"MAIL "
static const WORD MailVendorID = 0x1294, MailProductID = 0x1320;
if ((attrib.VendorID == MailVendorID) && (attrib.ProductID == MailProductID))
{
// Yes, break out with this handle
result = deviceHandle;
break;
}
}
CloseHandle(deviceHandle);
deviceHandle = NULL;
}
}
}
}
SetupDiDestroyDeviceInfoList(devNfoSet);
devNfoSet = NULL;
}
return result;
}
// Close the device handle
void CloseMailDevice(HANDLE deviceHandle)
{
if (deviceHandle)
{
CancelIo(deviceHandle);
CloseHandle(deviceHandle);
}
}
// Set mail device color
void SetMailDeviceColor(HANDLE deviceHandle, UINT color)
{
if (deviceHandle)
{
// HID control packet
BYTE packet[6] = { 2, (BYTE) (color & 7), 0, 0, 0, 0};
// Overlapped IO to avoid blocking this thread for several milliseconds writing to the slow device
OVERLAPPED ol;
ZeroMemory(&ol, sizeof(ol));
WriteFile(deviceHandle, packet, sizeof(packet), NULL, &ol);
}
} | 2.328125 | 2 |
2024-11-18T20:48:52.982064+00:00 | 2018-12-03T05:14:35 | 8851e64b0effe7eb3cf7d507dfbf99c65f676453 | {
"blob_id": "8851e64b0effe7eb3cf7d507dfbf99c65f676453",
"branch_name": "refs/heads/master",
"committer_date": "2018-12-03T05:14:35",
"content_id": "d3a4a80f851b19d58791e7beac0cfafd8ba97660",
"detected_licenses": [
"MIT"
],
"directory_id": "b168762c80deb54832ad04adf602b5fdf99319bb",
"extension": "h",
"filename": "enemy2.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 160134248,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2226,
"license": "MIT",
"license_type": "permissive",
"path": "/20180726_01/enemy2.h",
"provenance": "stackv2-0102.json.gz:84408",
"repo_name": "HALMASATO/sample",
"revision_date": "2018-12-03T05:14:35",
"revision_id": "dbe476f426561b8f7c28dd17107ba4e328571ca8",
"snapshot_id": "5bc409137c94065aca451a3b7299404ec4c447eb",
"src_encoding": "SHIFT_JIS",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/HALMASATO/sample/dbe476f426561b8f7c28dd17107ba4e328571ca8/20180726_01/enemy2.h",
"visit_date": "2020-04-09T06:57:13.416864"
} | stackv2 | //=============================================================================
//
// 敵処理 [enemy.h]
// Author :
//
//=============================================================================
#ifndef _ENEMY2_H_
#define _ENEMY2_H_
// マクロ定義
#define NUM_ENEMY2 (2) // ポリゴン数
#define TEXTURE_GAME_ENEMY2 _T("data/TEXTURE/tama1.png") // 画像
#define TEXTURE_ENEMY2_SIZE_X (50/2) // テクスチャサイズ
#define TEXTURE_ENEMY2_SIZE_Y (50/2) // 同上
#define TEXTURE_PATTERN_DIVIDE_X_ENEMY2 (9) // アニメパターンのテクスチャ内分割数(X)
#define TEXTURE_PATTERN_DIVIDE_Y_ENEMY2 (1) // アニメパターンのテクスチャ内分割数(Y)
#define ANIM_PATTERN_NUM_ENEMY2 (TEXTURE_PATTERN_DIVIDE_X_ENEMY2*TEXTURE_PATTERN_DIVIDE_Y_ENEMY2) // アニメーションパターン数
#define TIME_ANIMATION_ENEMY2 (4) // アニメーションの切り替わるカウント
#define ENEMY2_MAX (6) // 敵の最大数
//*****************************************************************************
// 構造体宣言
//*****************************************************************************
typedef struct // エネミー構造体
{
bool use; // true:使用 false:未使用
bool effectflag2;
bool BBflag;
bool comeback;
D3DXVECTOR3 pos; // ポリゴンの移動量
D3DXVECTOR3 rot; // ポリゴンの回転量
int PatternAnim; // アニメーションパターンナンバー
int CountAnim; // アニメーションカウント
int i;
int counter; //時間を制御する変数
float enemy2pos_x;
float enemy2pos_y;
LPDIRECT3DTEXTURE9 Texture_enemy; // テクスチャ情報
VERTEX_2D vertexWk_enemy[NUM_VERTEX]; // 頂点情報格納ワーク
float Radius; // エネミーの半径
float BaseAngle; // エネミーの角度
} ENEMY2;
//*****************************************************************************
// プロトタイプ宣言
//*****************************************************************************
HRESULT InitEnemy2(int type);
void UninitEnemy2(void);
void UpdateEnemy2(void);
void DrawEnemy2(void);
ENEMY2 *GetEnemy2(int no);
#endif
| 2.34375 | 2 |
2024-11-18T20:48:53.214838+00:00 | 2014-05-05T17:33:31 | ecac04b5903f5a7668b07ca94b7dbdcb8e78f2a5 | {
"blob_id": "ecac04b5903f5a7668b07ca94b7dbdcb8e78f2a5",
"branch_name": "refs/heads/master",
"committer_date": "2014-05-05T17:33:31",
"content_id": "c3b9678592a3b64b01a94116c1beb81e4a7991a7",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "ca0b220bc0e3d65b2ea19985dda2817dafa37406",
"extension": "h",
"filename": "tl_slist-inl.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": 3603,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/include/typelib/tl_slist-inl.h",
"provenance": "stackv2-0102.json.gz:84670",
"repo_name": "mnunberg/typelib",
"revision_date": "2014-05-05T17:33:31",
"revision_id": "e28e284d5d3d040038027a17e196d93b8950b9d9",
"snapshot_id": "2794bc89aca83741643fa04f06008c3dc09fa8b2",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/mnunberg/typelib/e28e284d5d3d040038027a17e196d93b8950b9d9/include/typelib/tl_slist-inl.h",
"visit_date": "2021-01-24T15:05:45.213846"
} | stackv2 | #include "tl_slist.h"
#include <stdlib.h>
#include <assert.h>
#ifndef INLINE
#ifdef _MSC_VER
#define INLINE __inline
#elif __GNUC__
#define INLINE __inline__
#else
#define INLINE inline
#endif /* MSC_VER */
#endif /* !INLINE */
static INLINE int
sllist_contains(tl_SLIST *list, tl_SLNODE *item)
{
tl_SLNODE *ll;
TL_SL_ITERBASIC(list, ll) {
if (item == ll) {
return 1;
}
}
return 0;
}
static INLINE unsigned
sllist_get_size(tl_SLIST *list)
{
unsigned ret = 0;
tl_SLNODE *ll;
TL_SL_ITERBASIC(list, ll) {
ret++;
}
return ret;
}
/* #define SLLIST_DEBUG */
#ifdef SLLIST_DEBUG
#define slist_sanity_insert(l, n) assert(!slist_contains(l, n))
#else
#define slist_sanity_insert(l, n)
#endif
static INLINE void
slist_iter_init_at(tl_SLNODE *node, tl_SLITER *iter)
{
iter->cur = node->next;
iter->prev = node;
iter->removed = 0;
if (iter->cur) {
iter->next = iter->cur->next;
} else {
iter->next = NULL;
}
}
static INLINE void
slist_iter_init(const tl_SLIST *list, tl_SLITER *iter)
{
slist_iter_init_at((tl_SLNODE *)&list->first, iter);
}
static INLINE void
slist_iter_incr(tl_SLIST *list, tl_SLITER *iter)
{
if (!iter->removed) {
iter->prev = iter->prev->next;
} else {
iter->removed = 0;
}
if ((iter->cur = iter->next)) {
iter->next = iter->cur->next;
} else {
iter->next = NULL;
}
assert(iter->cur != iter->prev);
(void)list;
}
static INLINE void
sllist_iter_remove(tl_SLIST *list, tl_SLITER *iter)
{
iter->prev->next = iter->next;
/** GCC strict aliasing. Yay. */
if (iter->prev->next == NULL && (void *)iter->prev == (void *)&list->first) {
list->last = NULL;
} else if (iter->cur == list->last && iter->next == NULL) {
/* removing the last item */
list->last = iter->prev;
}
iter->removed = 1;
}
static INLINE void
sllist_remove_head(tl_SLIST *list)
{
if (!list->first) {
return;
}
list->first = list->first->next;
if (!list->first) {
list->last = NULL;
}
}
static INLINE void
sllist_remove(tl_SLIST *list, tl_SLNODE *item)
{
tl_SLITER iter;
TL_SL_FOREACH(list, &iter) {
if (iter.cur == item) {
sllist_iter_remove(list, &iter);
return;
}
}
abort();
}
static INLINE void
sllist_append(tl_SLIST *list, tl_SLNODE *item)
{
if (TL_SL_EMPTY(list)) {
list->first = list->last = item;
item->next = NULL;
} else {
slist_sanity_insert(list, item);
list->last->next = item;
list->last = item;
}
item->next = NULL;
}
static INLINE void
sllist_prepend(tl_SLIST *list, tl_SLNODE *item)
{
if (TL_SL_EMPTY(list)) {
list->first = list->last = item;
} else {
slist_sanity_insert(list, item);
item->next = list->first;
list->first = item;
}
}
static void
sllist_insert(tl_SLIST *list, tl_SLNODE *prev, tl_SLNODE *item)
{
item->next = prev->next;
prev->next = item;
if (item->next == NULL) {
list->last = item;
}
}
static INLINE void
sllist_insert_sorted(tl_SLIST *list, tl_SLNODE *item,
int (*compar)(tl_SLNODE*, tl_SLNODE*))
{
tl_SLITER iter;
TL_SL_FOREACH(list, &iter) {
int rv = compar(item, iter.cur);
/** if the item we have is before the current, prepend it here */
if (rv <= 0) {
sllist_insert(list, iter.prev, item);
return;
}
}
sllist_append(list, item);
}
| 2.765625 | 3 |
2024-11-18T20:48:53.437831+00:00 | 2021-07-28T02:15:44 | 370dd5e39390df2efe15cc8b375268876cca8ab8 | {
"blob_id": "370dd5e39390df2efe15cc8b375268876cca8ab8",
"branch_name": "refs/heads/master",
"committer_date": "2021-07-28T02:15:44",
"content_id": "33a81099f32d2a99eff976c35230b81233437f50",
"detected_licenses": [
"MIT"
],
"directory_id": "1d711f63f16977e50ff64e1fb8e5e63fdd50d037",
"extension": "h",
"filename": "arraylist.h",
"fork_events_count": 0,
"gha_created_at": "2020-05-09T17:18:18",
"gha_event_created_at": "2020-05-12T00:23:26",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 262621266,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 8313,
"license": "MIT",
"license_type": "permissive",
"path": "/include/arraylist.h",
"provenance": "stackv2-0102.json.gz:84800",
"repo_name": "cvikupitz/libcds",
"revision_date": "2021-07-28T02:15:44",
"revision_id": "b7fe92041fb4c4bad73815a1e1396a931fa161bf",
"snapshot_id": "c1bf2eda4571f08f356c7cd3b628341e79abcd69",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/cvikupitz/libcds/b7fe92041fb4c4bad73815a1e1396a931fa161bf/include/arraylist.h",
"visit_date": "2023-06-27T01:33:34.720869"
} | stackv2 | /**
* MIT License
*
* Copyright (c) 2020 Cole Vikupitz
*
* 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 _CDS_ARRAYLIST_H__
#define _CDS_ARRAYLIST_H__
#include "cds_common.h"
#include "iterator.h"
/**
* Interface for the ArrayList ADT.
*
* The ArrayList class is a collection of elements stored in a resizable array.
*
* Modeled after the Java 7 ArrayList interface.
*/
typedef struct arraylist ArrayList;
/**
* Constructs a new array list instance with the specified starting capacity, then
* stores the new instance into '*list'. If the capacity given is <= 0, a default
* capacity is assigned.
*
* Params:
* list - The pointer address to store the new ArrayList instance.
* capacity - The default capacity of the arraylist.
* Returns:
* OK - ArrayList was successfully created.
* ALLOC_FAILURE - Failed to allocate enough memory from the heap.
*/
Status arraylist_new(ArrayList **list, long capacity);
/**
* Appends the specified element to the end of the array list.
*
* Params:
* list - The array list to operate on.
* item - The element to be appended to the array list.
* Returns:
* OK - Operation was successful.
* ALLOC_FAILURE - Failed to allocate enough memory from the heap.
*/
Status arraylist_add(ArrayList *list, void *item);
/**
* Inserts the specified element at the specified position in the array list. Shifts
* the element currently at that position (if any) and any subsequent elements to the
* right (adds one to their indices).
*
* Params:
* list - The array list to operate on.
* i - The index at which the specified element is to be inserted.
* item - The element to be inserted.
* Returns:
* OK - Operation was successful.
* INVALID_INDEX - Index given is out of range (index < 0 || index > size()).
* ALLOC_FAILURE - Failed to allocate enough memory from the heap.
*/
Status arraylist_insert(ArrayList *list, long i, void *item);
/**
* Returns the element at the specified position in the array list.
*
* Params:
* list - The array list to operate on.
* i - The index of the element to retrieve.
* item - The pointer address to store the retrieved element into.
* Returns:
* OK - Operation was successful.
* STRUCT_EMPTY - Array list is currently empty.
* INVALID_INDEX - Index given is out of range (index < 0 || index >= size()).
*/
Status arraylist_get(ArrayList *list, long i, void **item);
/**
* Replaces the element at the specified position in the array list with the specified
* element.
*
* Params:
* list - The array list to operate on.
* i - The index of the element to replace.
* item - The element to be stored at the specified position.
* previous - The pointer address to store the element previously at the specified
* position.
* Returns:
* OK - Operation was successful.
* STRUCT_EMPTY - Array list is currently empty.
* INVALID_INDEX - Index given is out of range (index < 0 || index >= size()).
*/
Status arraylist_set(ArrayList *list, long i, void *item, void **previous);
/**
* Removes the element at the specified position in the array list. Shifts any subsequent
* elements to the left (subtracts one from their indices).
*
* Params:
* list - The array list to operate on.
* i - The index of the element to be removed.
* item - The pointer address to store the element that was removed from the list.
* Returns:
* OK - Operation was successful.
* STRUCT_EMPTY - Array list is currently empty.
* INVALID_INDEX - Index given is out of range (index < 0 || index >= size()).
*/
Status arraylist_remove(ArrayList *list, long i, void **item);
/**
* Increases the capacity of the array list, if necessary, to ensure that it can hold
* at least the number of elements specified by the minimum capacity argument.
*
* Params:
* list - The array list to operate on.
* capacity - The desired minimum capacity.
* Returns:
* OK - Operation was successful.
* ALLOC_FAILURE - Failed to allocate enough memory from the heap.
*/
Status arraylist_ensureCapacity(ArrayList *list, long capacity);
/**
* Trims the capacity of the array list instance to be the list's current size.
*
* Params:
* list - The array list to operate on.
* Returns:
* OK - Operation was successful.
* STRUCT_EMPTY - ArrayList is currently empty.
* ALLOC_FAILURE - Failed to allocate enough memory from the heap.
*/
Status arraylist_trimToSize(ArrayList *list);
/**
* Removes all elements from the array list. If 'destructor' is not NULL, it will be
* invoked on each element in the array list after being removed.
*
* Params:
* list - The array list to operate on.
* destructor - Function to operate on each element after removal.
* Returns:
* None
*/
void arraylist_clear(ArrayList *list, void (*destructor)(void *));
/**
* Returns the number of elements in the array list.
*
* Params:
* list - The array list to operate on.
* Returns:
* The array list's current size.
*/
long arraylist_size(ArrayList *list);
/**
* Returns the array list's current capacity, that is, the maximum number of elements
* it can hold before resizing is required.
*
* Params:
* list - The array list to operate on.
* Returns:
* The array list's current capacity.
*/
long arraylist_capacity(ArrayList *list);
/**
* Returns TRUE if the array list contains no elements, FALSE if otherwise.
*
* Params:
* list - The array list to operate on.
* Returns:
* TRUE if the array list is empty, FALSE if not.
*/
Boolean arraylist_isEmpty(ArrayList *list);
/**
* Allocates and generates an array containing all of the array list's elements in
* proper sequence (from first to last element), then stores the array into '*array'.
* Caller is responsible for freeing the array when finished.
*
* Params:
* list - The array list to operate on.
* array - Address where the new array will be stored.
* Returns:
* OK - Operation was successful.
* STRUCT_EMPTY - Array list is currently empty.
* ALLOC_FAILURE - Failed to allocate enough memory from the heap.
*/
Status arraylist_toArray(ArrayList *list, Array **array);
/**
* Creates an Iterator instance to iterate over the array list's elements in proper
* sequence (from first to last element), then stores the iterator into '*iter'. Caller
* is responsible for destroying the iterator instance when finished.
*
* Params:
* list - The array list to operate on.
* iter - Address where the new iterator will be stored.
* Returns:
* OK - Operation was successful.
* STRUCT_EMPTY - Array list is currently empty.
* ALLOC_FAILURE - Failed to allocate enough memory from the heap.
*/
Status arraylist_iterator(ArrayList *list, Iterator **iter);
/**
* Destroys the array list instance by freeing all of its reserved memory. If 'destructor'
* is not NULL, it will be invoked on each element before the arraylist is destroyed.
*
* Params:
* list - The array list to destroy.
* destructor - Function to operate on each element prior to array list destruction.
* Returns:
* None
*/
void arraylist_destroy(ArrayList *list, void (*destructor)(void *));
#endif /* _CDS_ARRAYLIST_H__ */
| 2.46875 | 2 |
2024-11-18T20:48:53.679988+00:00 | 2017-09-07T17:01:48 | 54a924dbaa9983c5e6d6d136f9dd575dda625415 | {
"blob_id": "54a924dbaa9983c5e6d6d136f9dd575dda625415",
"branch_name": "refs/heads/master",
"committer_date": "2017-09-07T17:01:48",
"content_id": "951e9057d45f7fe8d370932155bd5bd1ec742584",
"detected_licenses": [
"MIT"
],
"directory_id": "9fe68253bdaf1fea4a484ff9fe5c6ca5c0fcad67",
"extension": "c",
"filename": "bhjl.c",
"fork_events_count": 4,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 102653894,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3687,
"license": "MIT",
"license_type": "permissive",
"path": "/src/bhjl/bhjl.c",
"provenance": "stackv2-0102.json.gz:85186",
"repo_name": "haslab/labhe",
"revision_date": "2017-09-07T17:01:48",
"revision_id": "f6b362376f446e9f3a0ac91508fcaf1febd2167d",
"snapshot_id": "934bf24817aa2e0345e4e59017f702bcfc4b7295",
"src_encoding": "UTF-8",
"star_events_count": 8,
"url": "https://raw.githubusercontent.com/haslab/labhe/f6b362376f446e9f3a0ac91508fcaf1febd2167d/src/bhjl/bhjl.c",
"visit_date": "2021-01-23T12:48:33.229597"
} | stackv2 | #include <gmp.h>
#include "bhjl.h"
/*
* BHJL encryption
* Inputs:
* - Message to encrypt: m
* - Public parameters and precomputed values: n, y, _2k
* - Bit-length of messages: k
* - State of GMP randomness generator
* Outputs: ciphertext c
* Assumptions:
* - message is within the valid range 0 <= m < 2^{k}
* - all I/O pointers are allocated and initialized by caller
* - GMP randomness state is managed by the caller
*/
int bhjl_encrypt(mpz_t c,const mpz_t m,
const mpz_t n,const mpz_t y, const int k,
const mpz_t _2k,
gmp_randstate_t gmpRandState)
{
mpz_t x, t1, t2, t3;
mpz_init(x);
mpz_urandomm(x,gmpRandState,n);
mpz_init(t1);
mpz_powm(t1,x,_2k,n);
mpz_init(t2);
mpz_powm(t2,y,m,n);
mpz_init(t3);
mpz_mul(t3,t1,t2);
mpz_mod(c,t3,n);
mpz_clears(x,t1,t2,t3,NULL);
return 0;
}
/*
* BHJL decryption
* Inputs:
* - Ciphertext to decrypt: c
* - Secret parameters and precomputed values: p, D, _2k1, pm12k
* - Bit-length of messages: k
* - State of GMP randomness generator
* Outputs: recovered message m
* Assumptions:
* - all I/O pointers are allocated and initialized by caller
* - ciphertext is in the correct range 0 <= c < n
* - GMP randomness state is managed by the caller
*/
int bhjl_decrypt(mpz_t m,const mpz_t c,
const mpz_t p,const mpz_t D,const int k,
const mpz_t _2k1,const mpz_t pm12k)
{
int j;
mpz_t t1, t2, Bloop, Dloop, Cloop, Eloop;
mpz_init(t1);
mpz_init(t2);
mpz_init(Cloop);
mpz_powm(Cloop,c,pm12k,p); // c^{(p-1)/2^k}
mpz_set_ui(m,0);
mpz_init_set_ui(Bloop,1);
mpz_init_set(Dloop,D);
mpz_init_set(Eloop,_2k1);
for (j=1;j<k;j++) {
mpz_powm(t1,Cloop,Eloop,p);
if (mpz_cmp_ui(t1,1)!=0) {
// Not equal to 1
mpz_add(m,m,Bloop);
mpz_mul(t1,Cloop,Dloop);
mpz_mod(Cloop,t1,p);
}
mpz_add(Bloop,Bloop,Bloop);
mpz_powm_ui(Dloop,Dloop,2,p);
mpz_tdiv_q_2exp(Eloop,Eloop,1);
}
if (mpz_cmp_ui(Cloop,1)!=0) {
// Not equal to 1
mpz_add(m,m,Bloop);
}
mpz_clears(t1, t2, Bloop, Dloop, Cloop, Eloop, NULL);
return 0;
}
/*
* BHJL homomorphic addition
* Inputs:
* - Ciphertexts containing messages to add: c1, c2
* - Modulus: n
* Outputs: ciphertext encoding addition
* Assumptions:
* - all I/O pointers are allocated and initialized by caller
* - ciphertexts c1, c2 are in the correct range 0 <= c1,c2 < n
*/
int bhjl_homadd(mpz_t c, const mpz_t c1, const mpz_t c2,
const mpz_t n) {
mpz_t t;
mpz_init(t);
mpz_mul(t,c1,c2);
mpz_mod(c,t,n);
mpz_clear(t);
return 0;
}
/*
* BHJL homomorphic subtraction
* Inputs:
* - Ciphertexts containing messages to subtract: c1, c2
* - Modulus: n
* Outputs: ciphertext encoding difference
* Assumptions:
* - all I/O pointers are allocated and initialized by caller
* - ciphertexts c1, c2 are in the correct range 0 <= c1,c2 < n
*/
int bhjl_homsub(mpz_t c, const mpz_t c1, const mpz_t c2,
const mpz_t n) {
mpz_t t1,t2;
mpz_init(t1);
mpz_init(t2);
mpz_invert(t1, c2, n);
mpz_mul(t2,c1,t1);
mpz_mod(c,t2,n);
mpz_clears(t1,t2,NULL);
return 0;
}
/*
* BHJL homomorphic scalar multiplication
* Inputs:
* - Ciphertext containing message multiply: c1
* - The scalar: s
* - Modulus: n
* Outputs: ciphertext encoding scalar multiplication
* Assumptions:
* - all I/O pointers are allocated and initialized by caller
* - ciphertexts c1, c2 are in the correct range 0 <= c1 < n
*/
int bhjl_homsmul(mpz_t c, const mpz_t c1, const mpz_t s,
const mpz_t n) {
mpz_powm(c,c1,s,n);
return 0;
}
| 2.828125 | 3 |
2024-11-18T20:48:53.741747+00:00 | 2020-07-02T01:30:38 | 7e52491004f75479d213fbc49b3cebe6d00afbe6 | {
"blob_id": "7e52491004f75479d213fbc49b3cebe6d00afbe6",
"branch_name": "refs/heads/master",
"committer_date": "2020-07-02T01:30:38",
"content_id": "8fd27dd26290d1b5f07bdfeeba62523e4f22b8e0",
"detected_licenses": [
"PostgreSQL"
],
"directory_id": "9b972e7e915a1b68c1a3b46811a2903727d882a2",
"extension": "c",
"filename": "d-tree.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 275687839,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 45369,
"license": "PostgreSQL",
"license_type": "permissive",
"path": "/postgresql-8.3.3/src/backend/maybms/d-tree.c",
"provenance": "stackv2-0102.json.gz:85315",
"repo_name": "IITDBGroup/maybms",
"revision_date": "2020-07-02T01:30:38",
"revision_id": "7659b67149f4b8f1471941c86ff7aca0550de897",
"snapshot_id": "9262517da3f7d19327d42c4873c28197ff944377",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/IITDBGroup/maybms/7659b67149f4b8f1471941c86ff7aca0550de897/postgresql-8.3.3/src/backend/maybms/d-tree.c",
"visit_date": "2022-11-14T16:43:33.966051"
} | stackv2 | /*-------------------------------------------------------------------------
*
* d-tree.c
* Implementation of the decomposition-tree algorithm for approximate confidence computation.
*
*
* Copyright (c) 2009, MayBMS Development Group
*
*-------------------------------------------------------------------------
*/
#include "maybms/localcond.h"
#include "maybms/conf_comp.h"
/* Macros used in bitset operation */
#define BITSET_USED(nbits) \
( ((nbits) + (BITSET_BITS - 1)) / BITSET_BITS )
#define BITSET_BITS \
( CHAR_BIT * sizeof(size_t) )
/* Macros used to identify different situation after variable elimination */
#define SUBSET_VAR_RNG_IS_NULL 0
#define SUBSET_VAR_RNG_IS_EMPTY 1
#define SUBSET_VAR_RNG_SHOULD_UNION 2
//#define STATISTICS 1
/* The approach of confidence computation, true for relative and false for absolute */
bool is_relative = true;
char *appro_approach = NULL;
/* The error allowed in approximation */
prob appro_epsilon = 0.05;
/* Variables used in statistics collection */
int counter = 0;
int ind_counter = 0;
int subsumption_counter = 0;
/* A data structure for passing around the coefficients and constants used in the
* upper and lower bound computation.
*/
typedef struct
{
float8 coefficient_upper; /* Coefficient of the whole upper bound */
float8 constant_upper; /* Constant of the whole upper bound */
float8 coefficient_lower; /* Coefficient of the whole lower bound */
float8 constant_lower; /* Constant of the whole lower bound */
float8 condition_coefficient_upper; /* Coefficient of the whole upper bound in deciding whether to close a leave */
float8 condition_constant_upper; /* Constant of the whole upper bound in deciding whether to close a leave */
} bound_information;
/* A data structure for keeping a bucket. A bucket is a set of clauses among whom
* no variables are shared.
*/
typedef struct
{
int capacity; /* The capacity of variables in the bucket */
int count; /* The current number of variables in the bucket */
varType *vars; /* The set of variables in the bucket */
float8 prob; /* The probability of clauses in the bucket */
} bucket_info;
/* A data structure for keeping the set of all buckets */
typedef struct
{
int capacity; /* The capacity of buckets */
int count; /* The current number of buckets */
bucket_info *bucket_list; /* The set of all buckets */
} buckets;
/* If the results of equations are not bigger than stopping_number,
* then the decomposition tree refinement can stop or a leave can be safely closed
* (the equations vary in different cases). It is calculated once before
* the tree construction and is never changed afterwords.
*/
float8 stopping_number;
/* This variable is set to true when an epsilon-approximation is reached */
bool has_satisfied_stopping_condition;
/* Local functions */
/* Functions used in quick sort */
static void quicksort(WSD **array, int left, int right);
static int partition(WSD **array, int left, int right);
static prob findMedianOfMedians(WSD **array, int left, int right);
static int findMedianIndex(WSD **array, int left, int right, int shift);
static void swap(WSD **array, int a, int b);
/* Heuristic for variable elimination */
static void compute_upper_and_lower_bounds(bitset *set, float8 *upper, float8 *lower, generalState *state);
static bool exists_in_bucket(WSD* wsd, bucket_info *bucket);
static void add_to_bucket(WSD* wsd, bucket_info *bucket);
static void add_var_to_bucket(int var, bucket_info *bucket);
static void add_new_bucket(WSD *wsd, buckets *all_buckets);
/* The major functions */
static void decomposition_tree_approximate(bitset* set, generalState *state,
float8 path_prob, float8 *lower, float8 *upper,
bound_information *bound_info, int latest_var_column);
static prob decomposition_tree_exact(bitset* set, generalState *state,
int latest_var_column);
/* Heuristic for variable elimination */
static worldTableEntry *choose_var_max_occur_same_column(bitset* set, generalState *state, int latest_var_col, int *new_var_col);
/* Functions used in bitset operation */
static void bitset_union_removing_subsumption(bitset *set1, bitset *set2);
static bitset* find_independent_split(bitset* set);
static bitset* find_wsds_with_var_rng(bitset* set, int var, int rng);
static bitset* find_wsds_without_var(bitset* set, int var);
static void dfs (bitset* set, bitset* set_to_construct, int idx);
static void reset_wsds_var_rng(bitset* set, int var, int rng);
static int wsd_ind (WSD* d1, WSD* d2);
static int compare_map (Map* m1, Map* m2);
/* compute_upper_and_lower_bounds
*
* Compute the probability upper and lower bounds for a set of clauses.
* The heuristic used here is named "bucketing" in the paper.
*/
static void
compute_upper_and_lower_bounds(bitset *set, float8 *upper, float8 *lower, generalState *state)
{
float8 sum = 0;
float8 max = 0;
int i, j;
buckets *all_buckets;
MemoryContext oldcxt, currentcxt;
/* If the bitset is NULL, set both bounds to zeros. */
if (set == NULL)
{
*lower = 0;
*upper = 0;
return;
}
/* Allocate a new memory context. */
currentcxt = AllocSetContextCreate( NULL, "CurrentContext",
ALLOCSET_DEFAULT_MINSIZE,
ALLOCSET_DEFAULT_INITSIZE,
ALLOCSET_DEFAULT_MAXSIZE);
/* Allocate a new memory context. */
oldcxt = MemoryContextSwitchTo(currentcxt);
/* Initialization of the list of buckets */
all_buckets = (buckets *) palloc0(sizeof(buckets));
all_buckets->capacity = 10;
all_buckets->count = 0;
all_buckets->bucket_list = (bucket_info *) palloc0(sizeof(bucket_info) * all_buckets->capacity);
/* Loop over all clauses */
for (i = 0; i < NUM_WSDS; i++)
/* If the bit of a clause is set, process it */
if (bitset_test_bit(set,i))
{
bool bucket_is_found = false;
/* Loop over all buckets */
for (j = 0; j < all_buckets->count; j++)
{
/* Important: Do not write code like this:
* Put bucket_list = all_buckets->bucket_list; outside the loop
* and write bucket_info *bucket = bucket_list + j;
* This will cause the crash of system because all_buckets->bucket_list
* may change in the loop.
*/
bucket_info *bucket = all_buckets->bucket_list + j;
/* If a clause does not share any variable with clauses in a bucket,
* add it to the bucket.
*/
if (!exists_in_bucket(S[i], bucket))
{
add_to_bucket(S[i], bucket);
bucket_is_found = true;
break;
}
}
/* If a clause share variables with clauses in all existing buckets
* create a new one for it.
*/
if (!bucket_is_found)
{
add_new_bucket(S[i], all_buckets);
}
}
/* Loop over all buckets */
for (i = 0; i < all_buckets->count; i++)
{
float8 p = (all_buckets->bucket_list + i)->prob;
/* Keep the maximal probability of the buckets */
if (p > max)
max = p;
/* Calculate the sum of probabilities of all buckets */
sum += p;
}
/* Set the lower bound as the maximal probability of all buckets */
*lower = max;
/* Set the upper bound as 1 or sum of probabilities of all buckets */
if (sum > 1)
*upper = 1;
else
*upper = sum;
/* Switch back to the old memory context and delete the current one. */
MemoryContextSwitchTo(oldcxt);
MemoryContextDelete(currentcxt);
}
/* exists_in_bucket
*
* Return true if a clause share any variables with clauses in a bucket.
*/
static bool
exists_in_bucket(WSD* wsd, bucket_info *bucket)
{
int i, j;
/* Loop over all variables in the bucket */
for(i = 0; i < bucket->count; i++)
{
varType var = *(bucket->vars + i);
/* Loop over all variables in the clause */
for (j = 0; j < WSD_LEN; j++)
{
/* If a variable has not been eliminated and it is the same as
* as a variable in the bucket, return true;
*/
if (wsd->data[j]->rng != -1 && wsd->data[j]->var == var)
{
return true;
}
}
}
/* If no match is found, return false */
return false;
}
/* add_to_bucket
*
* Add all variables of a clause to a bucket.
*/
static void
add_to_bucket(WSD* wsd, bucket_info *bucket)
{
int i;
/* Loop over all variables in the clause */
for (i = 0; i < WSD_LEN; i++)
{
/* If a variable has not been eliminated, add it to the bucket */
if (wsd->data[i]->rng != -1)
{
add_var_to_bucket(wsd->data[i]->var, bucket);
}
}
/* Update the probability of the bucket */
bucket->prob = bucket->prob + wsd->prob - bucket->prob * wsd->prob;
}
/* add_var_to_bucket
*
* Add a variable to a bucket.
*/
static void
add_var_to_bucket(int var, bucket_info *bucket)
{
*(bucket->vars + bucket->count) = var;
bucket->count++;
/* If the bucket is full, double its size */
if (bucket->capacity == bucket->count)
{
bucket->capacity = bucket->capacity * 2;
bucket->vars = (varType *) repalloc(bucket->vars, bucket->capacity * sizeof(varType));
}
}
/* add_var_to_bucket
*
* Add a variable to a bucket.
*/
static void
add_new_bucket(WSD *wsd, buckets *all_buckets)
{
bucket_info *bucket;
/* Initialization of a new bucket */
bucket = all_buckets->bucket_list + all_buckets->count;
bucket->capacity = WSD_LEN;
bucket->count = 0;
bucket->prob = 0;
bucket->vars = (varType *) palloc0(sizeof(varType) * WSD_LEN);
/* Add a clause to the new bucket */
add_to_bucket(wsd, bucket);
all_buckets->count++;
/* If the bucket list is full, double its size */
if (all_buckets->capacity == all_buckets->count)
{
all_buckets->capacity = all_buckets->capacity * 2;
all_buckets->bucket_list = (bucket_info *) repalloc(all_buckets->bucket_list, all_buckets->capacity * sizeof(bucket_info));
}
}
/* find_independent_split
*
* Partition the given wsd set into 2 independent sets
* first set is returned and contains dependent wsds.
*/
static bitset*
find_independent_split(bitset* set)
{
int i = 0;
bitset *subset;
if (bitset_test_empty(set))
return NULL;
subset = bitset_init(NUM_WSDS);
bitset_reset(subset);
while (i < NUM_WSDS && !bitset_test_bit(set,i))
i++;
if (i == NUM_WSDS)
elog(ERROR, "An invalid input of bitset!");
dfs(set,subset,i);
return subset;
}
static void
dfs (bitset* set, bitset* set_to_construct, int idx)
{
int j;
bitset_set_bit(set_to_construct,idx);
for ( j=0; j<NUM_WSDS; j++)
if (bitset_test_bit(set,j) && !bitset_test_bit(set_to_construct,j) &&
!wsd_ind(S[idx],S[j]) && idx != j)
dfs(set,set_to_construct,j);
}
/* wsd_ind
*
* Return 0 if not independent and 1 if independent.
*/
static int
wsd_ind (WSD* d1, WSD* d2)
{
int is_independent = 1;
int i=0;
while (i<WSD_LEN && is_independent)
{
int j=0;
while (j<WSD_LEN && compare_map(d1->data[i],d2->data[j]) == 0)
j++;
if (j < WSD_LEN)
is_independent = 0;
i++;
}
return is_independent;
}
/* compare_map
*
* Return
* -2: equal
* -1: mutex
* 0: different vars
* 2: same vars, diff rng, both neg
* 3: same vars, diff rng, diff neg (the positive one constrains the negative one)
*/
static int
compare_map (Map* m1, Map* m2)
{
if (!m1 || !m2 || m1->rng == -1 || m2->rng == -1)
return 0;
if (m1->var == m2->var)
{
if (m1->rng == m2->rng)
{
if (m1->neg == m2->neg)
return -2;
else
return -1;
}
else if (m1->neg != m2->neg)
return 3;
else if (m1->neg && m2->neg)
return 2;
else
return -1;
}
return 0;
}
/* choose_var_max_occur_same_column
*
* Find a variable in column latest_var_col with most occurrence. If all in this
* column has been eliminated, pick a variable with most occurrence in any column.
*/
static worldTableEntry *
choose_var_max_occur_same_column(bitset* set, generalState *state, int latest_var_col, int *new_var_col)
{
int i;
int j;
float8 same_column_max = -1;
float8 other_columns_max = -1;
worldTableEntry *same_column_max_wt_entry = NULL;
worldTableEntry *other_columns_max_wt_entry = NULL;
/* Clear the counters for all varibles */
for ( i = 0; i < state->wt_entry_count; i++)
{
(state->wt_entries + i)->occur_count = 0;
}
/* Loop over all clauses and count the occurrence of every variable */
for( i = 0; i < NUM_WSDS; i++)
if (bitset_test_bit(set, i))
{
for ( j = 0; j < WSD_LEN; j++)
{
/* If a variable has not been eliminated, increase its occurrence */
if( S[i]->data[j]->rng >= 0 )
{
S[i]->data[j]->wt_entry->occur_count++;
if (j == latest_var_col)
{
if (S[i]->data[j]->wt_entry->occur_count > same_column_max)
{
same_column_max_wt_entry = S[i]->data[j]->wt_entry;
same_column_max = S[i]->data[j]->wt_entry->occur_count;
*new_var_col = j;
}
}
else if (same_column_max == -1)
{
if (S[i]->data[j]->wt_entry->occur_count > other_columns_max)
{
other_columns_max_wt_entry = S[i]->data[j]->wt_entry;
other_columns_max = S[i]->data[j]->wt_entry->occur_count;
*new_var_col = j;
}
}
}
}
}
if (same_column_max != -1)
{
return same_column_max_wt_entry;
}
else
return other_columns_max_wt_entry;
}
/* find_wsds_without_var
*
* Find the wsds that do not contain mapping of the given var
*/
static bitset*
find_wsds_without_var(bitset* set, int var)
{
bitset *subset = NULL;
int i;
/* Loop the world set descriptors */
for ( i = 0; i < NUM_WSDS; i++)
if (bitset_test_bit(set,i))
{
int j = 0;
while (j < WSD_LEN && S[i]->data[j]->var != var)
j++;
if (j == WSD_LEN)
{
if (subset == NULL)
{
subset = bitset_init(NUM_WSDS);
bitset_reset(subset);
}
bitset_set_bit(subset,i);
}
}
return subset;
}
/* find_wsds_with_var_rng
*
* Find the world set descriptors that contain mapping var->rng; also *temporarily* drop this mapping.
*/
static bitset*
find_wsds_with_var_rng(bitset* set, int var, int rng)
{
bitset *subset = NULL;
int found_empty_wsd = 0;
int i = 0;
while (i < NUM_WSDS && !found_empty_wsd)
{
if (bitset_test_bit(set,i))
{
int j;
for(j = 0; j < WSD_LEN; j++)
{
if (S[i]->data[j]->var == var && S[i]->data[j]->rng == rng)
{
if (subset == NULL)
{
subset = bitset_init(NUM_WSDS);
bitset_reset(subset);
}
bitset_set_bit(subset,i);
/* Mark the used choices of rng for that var. */
S[i]->data[j]->rng = -1;
S[i]->prob /= S[i]->data[j]->prob;
/* Check if the remaining S[i] is empty,
* in which case the prob of all wsds agreeing with (var,rng) is just S[i]->data[j]->prob
*/
if (S[i]->prob == 1.0)
found_empty_wsd = 1;
}
}
}
i++;
}
if (found_empty_wsd)
{
reset_wsds_var_rng(subset, var, rng);
bitset_reset(subset);
}
return subset;
}
/* reset_wsds_var_rng
*
* The temporarily dropped mappings (see find_wsds_with_var_rng) are restored.
*/
static void
reset_wsds_var_rng(bitset* set, int var, int rng)
{
int i; int j;
/* Loop the world set descriptors */
for ( i = 0; i < NUM_WSDS; i++)
if (bitset_test_bit(set,i))
/* Restore the world set descriptors */
for ( j = 0; j < WSD_LEN; j++)
if(S[i]->data[j]->var == var)
{
S[i]->data[j]->rng = rng;
S[i]->prob *= S[i]->data[j]->prob;
}
}
/* quicksort
*
* Quicksort the array.
*/
static void
quicksort(WSD **array, int left, int right)
{
int index;
if(left >= right)
return;
index = partition(array, left, right);
quicksort(array, left, index - 1);
quicksort(array, index + 1, right);
}
/* partition
*
* Partition the array into two halves and return the index about which the
* array is partitioned.
*/
static int
partition(WSD **array, int left, int right)
{
int pivotIndex, index, i;
prob pivotValue;
/* Makes the leftmost element a good pivot, specifically the median of medians */
findMedianOfMedians(array, left, right);
pivotIndex = left;
index = left;
pivotValue = array[pivotIndex]->prob;
swap(array, pivotIndex, right);
for(i = left; i < right; i++)
{
if(array[i]->prob > pivotValue)
{
swap(array, i, index);
index += 1;
}
}
swap(array, right, index);
return index;
}
/* findMedianOfMedians
*
* Computes the median of each group of 5 elements and stores it as the first
* element of the group. Recursively does this till there is only one group and
* hence only one Median.
*/
static prob
findMedianOfMedians(WSD **array, int left, int right)
{
int i, shift = 1;
if(left == right)
return array[left]->prob;
while(shift <= (right - left))
{
for(i = left; i <= right; i+=shift*5)
{
int endIndex = (i + shift*5 - 1 < right) ? i + shift*5 - 1 : right;
int medianIndex = findMedianIndex(array, i, endIndex, shift);
swap(array, i, medianIndex);
}
shift *= 5;
}
return array[left]->prob;
}
/* findMedianIndex
*
* Find the index of the Median of the elements of array that occur at every
* "shift" positions.
*/
static int
findMedianIndex(WSD **array, int left, int right, int shift)
{
int i, groups = (right - left)/shift + 1, k = left + groups/2*shift;
for(i = left; i <= k; i+= shift)
{
int minIndex = i, j;
prob minValue = array[minIndex]->prob;
for(j = i; j <= right; j+=shift)
if(array[j]->prob > minValue)
{
minIndex = j;
minValue = array[minIndex]->prob;
}
swap(array, i, minIndex);
}
return k;
}
/* swap
*
* Swap the positions of two world set descriptors.
*/
static void
swap(WSD **array, int a, int b)
{
WSD *tmp = array[a];
array[a] = array[b];
array[b] = tmp;
}
/* bitset_union_removing_subsumption
*
* Union two bitsets and remove the subsumed clauses.
* CNF A is subsumed by CNF B if A implies B.
*/
static void
bitset_union_removing_subsumption(bitset *set1, bitset *set2)
{
int i, j, k, h;
bitset *temp_set;
if (set2 == NULL)
{
return;
}
/* Copy the second bitset to a temporary one because modifications are needed */
temp_set = bitset_init(NUM_WSDS);
bitset_copy(set2, temp_set);
/* Loop over all clauses in the first bitset */
for (i = 0; i < NUM_WSDS; i++)
/* Pick a valid clause in the first bitset */
if (bitset_test_bit(set1,i))
{
/* Loop over all clauses in the temporary bitset */
for (j = 0; j < NUM_WSDS; j++)
{
/* Pick a valid clause in the second bitset */
if (bitset_test_bit(temp_set,j))
{
bool vars_found = true;
/* Loop over all variables in the first clause */
for (k = 0; k < WSD_LEN; k++)
{
if (S[i]->data[k]->rng != -1)
{
bool var_found = false;
/* Loop over all variables in the second clause */
for (h = 0; h < WSD_LEN; h++)
{
if (S[i]->data[k]->var == S[j]->data[h]->var)
{
var_found = true;
break;
}
}
/* If a variable in the second clause is not found
* in the first clause, it is sure that the second clause
* does not imply the first clause.
*/
if (!var_found)
{
vars_found = false;
break;
}
}
}
/* If all variables in the first clause are found in the
* second clause, then clear the bit for the second clause */
if (vars_found)
{
bitset_clear_bit(temp_set,j);
#ifdef STATISTICS
subsumption_counter++;
#endif
}
}
}
}
/* Perform the union operation. */
for( i = 0; i < BITSET_USED(set1->nbits); i++)
set1->bits[i] |= temp_set->bits[i];
/* Free the temporary bitset */
bitset_free(temp_set);
}
/* decomposition_tree_approximate
*
* This is the major function for approximate confidence computation with
* decomposition tree.
*/
static void
decomposition_tree_approximate (bitset* set, generalState *state,
float8 path_prob, float8 *lower, float8 *upper,
bound_information *bound_info, int latest_var_column)
{
int pos;
int var = -1;
int i;
int j;
bitset* subset_without_var = NULL;
bitset* subset;
worldTableEntry *wt_entry;
rngEntry *rng_entry;
bound_information next_bound_info;
float8 p_left_lower = 0;
float8 p_left_upper = 0;
float8 p_right_lower = 0;
float8 p_right_upper = 0;
float8 whole_upper;
float8 whole_lower;
float8 condition_whole_upper;
/* If the set is empty, return 0s as the bounds. */
if (bitset_test_empty(set))
{
*lower = 0;
*upper = 0;
return;
}
/* Find a subset of clauses which do not share variables with the rest of the clauses */
subset = find_independent_split(set);
/* Get the bitset of the rest of the clauses so that their upper and lower bounds can be computed. */
bitset_negate(set, subset);
/* Compute the bounds of the rest of the clauses. */
compute_upper_and_lower_bounds(subset, &p_right_upper, &p_right_lower, state);
#ifdef STATISTICS
counter++;
if (p_right_upper != 0)
{
ind_counter++;
}
#endif
/* Get back the bitset of the subset. */
bitset_negate(set, subset);
/* Singleton test */
pos = bitset_test_singleton(subset);
/* Special case of 1 clause: the bounds are the probability of the clause */
if (pos != -1)
{
p_left_lower = S[pos]->prob;
p_left_upper = S[pos]->prob;
}
/* Cases with more than 1 clause */
else
{
int new_var_column;
/* Choose a variable with most occurrence from the same column of last eliminated variable */
wt_entry = choose_var_max_occur_same_column(subset, state,
latest_var_column, &new_var_column);
/* If the variable is NULL, return the bounds as 1s. */
if (wt_entry == NULL)
{
*lower = 1;
*upper = 1;
bitset_free(subset);
return;
}
/* The variable in the returned world table entry */
var = wt_entry->var;
/* All range values of the variable */
rng_entry = wt_entry->rng_entries;
/* The bitset of clauses which do not contain the eliminated variables */
subset_without_var = find_wsds_without_var(subset, var);
/* The bounds for clauses where a range value of the variable is chose */
float8 upper_bounds[wt_entry->rng_entry_count];
float8 lower_bounds[wt_entry->rng_entry_count];
/* The states of clauses after the variable is eliminated */
int state_of_subset_var_rng[wt_entry->rng_entry_count];
float8 upper_bound_without_var = -1;
float8 lower_bound_without_var = -1;
int rng_count = wt_entry->rng_entry_count;
/* Loop over all range values for the first round to compute the upper
* and lower bounds for each range value.
*/
for (i = 0; i < rng_count; i++)
{
/* The probability of the range value */
float8 cur_prob = (rng_entry + i)->p;
/* The bitset of clauses where the range value of the variable appears */
bitset* subset_var_rng = find_wsds_with_var_rng(subset, var, (rng_entry + i)->rng);
/* No clauses contain the range value of the variable */
if (subset_var_rng == NULL)
{
/* Compute the upper and lower bounds if they are not yet computed */
if (upper_bound_without_var == -1)
{
compute_upper_and_lower_bounds(
subset_without_var,
&upper_bound_without_var,
&lower_bound_without_var,
state);
}
/* Set the bounds */
upper_bounds[i] = cur_prob * upper_bound_without_var;
lower_bounds[i] = cur_prob * lower_bound_without_var;
/* Set the state of clauses for the range value */
state_of_subset_var_rng[i] = SUBSET_VAR_RNG_IS_NULL;
}
else
{
/* One clause has exhausted all its variables due to variable elimination */
if (bitset_test_empty(subset_var_rng))
{
/* The bounds are simply the probability of the range value */
upper_bounds[i] = cur_prob;
lower_bounds[i] = cur_prob;
/* Set the state of clauses for the range value */
state_of_subset_var_rng[i] = SUBSET_VAR_RNG_IS_EMPTY;
#ifdef STATISTICS
subsumption_counter += bitset_count_set(set);
#endif
}
/* Other cases */
else
{
/* Get the union of bitset of clauses that contain the range
* values and that do not contain the variable.
*/
bitset_union(subset_var_rng, subset_without_var);
/* Compute the bounds */
compute_upper_and_lower_bounds(
subset_var_rng,
&upper_bounds[i],
&lower_bounds[i],
state);
/* Take into account the probability of the range value */
upper_bounds[i] *= cur_prob;
lower_bounds[i] *= cur_prob;
/* Reset the bitset */
reset_wsds_var_rng(subset_var_rng, var, (rng_entry + i)->rng);
/* Set the state of clauses for the range value */
state_of_subset_var_rng[i] = SUBSET_VAR_RNG_SHOULD_UNION;
}
}
/* Free local bitsets */
if (subset_var_rng)
bitset_free(subset_var_rng);
}
/* Loop over all range values for the second round to decide whether to
* refine or close a leave.
*/
for (i = 0; i < rng_count; i++)
{
/* The sum of upper bounds of all range values */
float8 aggregate_upper = 0;
/* The sum of lower bounds of all range values */
float8 aggregate_lower = 0;
/* The sum of upper bounds of all range values used in deciding whether to close a leave.
* It is not the same as aggregate_upper.
*/
float8 condition_aggregate_upper = 0;
/* The probability of the range value */
float8 cur_prob;
/* The sum of upper bounds of all range values except for the current one */
float8 aggregate_upper_without_itself;
/* The sum of lower bounds of all range values except for the current one */
float8 aggregate_lower_without_itself;
/* Compute the sums of bounds */
for (j = 0; j < rng_count; j++)
{
aggregate_upper += upper_bounds[j];
aggregate_lower += lower_bounds[j];
}
/* Compute the sums of upper bounds used in deciding whether to close a leave. */
for (j = 0; j < rng_count; j++)
{
/* Use the upper bounds of iterated range values */
if (j < i)
condition_aggregate_upper += upper_bounds[j];
/* Use the lower bounds of uniterated range values */
/* Please refer to the page for the reason. */
else if (j > i)
condition_aggregate_upper += lower_bounds[j];
}
/* Compute the upper bound of the whole decomposition tree */
whole_upper = bound_info->coefficient_upper * (aggregate_upper +
p_right_upper - aggregate_upper * p_right_upper) +
bound_info->constant_upper;
/* Compute the lower bound of the whole decomposition tree */
whole_lower = bound_info->coefficient_lower * (aggregate_lower +
p_right_lower - aggregate_lower * p_right_lower) +
bound_info->constant_lower;
/* Compute the upper bound of the whole decomposition tree used in deciding whether to close a leave */
condition_whole_upper = bound_info->condition_coefficient_upper *
(condition_aggregate_upper + p_right_lower -
condition_aggregate_upper * p_right_lower) +
bound_info->condition_constant_upper;
/* Relative cases */
if (is_relative)
{
/* Test the stopping condition */
if ((whole_upper - whole_lower) / whole_lower <= stopping_number)
{
has_satisfied_stopping_condition = true;
break;
}
/* Test whether we can close an open leave */
if ((condition_whole_upper - whole_lower) / whole_lower <= stopping_number)
{
/* Decide whether we should close the leave */
if (((upper_bounds[i] - lower_bounds[i]) * path_prob) / whole_lower <= 0.001 * stopping_number)
{
continue;
}
}
}
/* Absolute cases */
else
{
/* Test the stopping condition */
if ((whole_upper - whole_lower) <= stopping_number)
{
has_satisfied_stopping_condition = true;
break;
}
/* Test whether we can close an open leave */
if ((condition_whole_upper - whole_lower) <= stopping_number )
{
/* Decide whether we should close the leave */
if (((upper_bounds[i] - lower_bounds[i]) * path_prob) <= 0.001 * stopping_number)
{
continue;
}
}
}
/* The code below prepares the necessary information to refine a leave */
/* TODO: More detailed explanation of coefficients and constants below is needed */
/* Get the probability of range value */
cur_prob = (rng_entry + i)->p;
aggregate_upper_without_itself = aggregate_upper - upper_bounds[i];
/* Compute the coefficient to be passed down in calculating the upper bound */
next_bound_info.coefficient_upper = bound_info->coefficient_upper *
(1 - p_right_upper) * cur_prob;
/* Compute the constant to be passed down in calculating the upper bound */
next_bound_info.constant_upper = bound_info->constant_upper +
bound_info->coefficient_upper *
(p_right_upper + aggregate_upper_without_itself -
p_right_upper * aggregate_upper_without_itself);
aggregate_lower_without_itself = aggregate_lower - lower_bounds[i];
/* Compute the coefficient to be passed down in calculating the lower bound */
next_bound_info.coefficient_lower = bound_info->coefficient_lower
* (1 - p_right_lower) * cur_prob;
/* Compute the constant to be passed down in calculating the lower bound */
next_bound_info.constant_lower = bound_info->constant_lower +
bound_info->coefficient_lower *
(p_right_lower + aggregate_lower_without_itself -
p_right_lower * aggregate_lower_without_itself);
/* Compute the coefficient to be passed down in calculating the upper bound for deciding whether to close a leave */
next_bound_info.condition_coefficient_upper = next_bound_info.coefficient_lower;
/* Compute the constant to be passed down in calculating the upper bound for deciding whether to close a leave */
next_bound_info.condition_constant_upper =
bound_info->condition_constant_upper +
bound_info->condition_coefficient_upper *
(p_right_lower + condition_aggregate_upper -
p_right_lower * condition_aggregate_upper);
/* No clauses contain the range value of the variable */
if (state_of_subset_var_rng[i] == SUBSET_VAR_RNG_IS_NULL)
{
/* Refine the leave */
decomposition_tree_approximate(subset_without_var, state,
path_prob * cur_prob, &lower_bounds[i], &upper_bounds[i],
&next_bound_info, latest_var_column);
/* Update the bounds with probability of the range value */
lower_bounds[i] *= cur_prob;
upper_bounds[i] *= cur_prob;
}
else
{
/* One clause has exhausted all its variables due to variable elimination */
if (state_of_subset_var_rng[i] == SUBSET_VAR_RNG_IS_EMPTY)
{
/* No actions are needed, because refinement cannot narrow
* the gap between lower and upper bounds.
*/
}
/* Other cases */
else
{
/* Compute the bitset of clauses containing the range value */
bitset* subset_var_rng = find_wsds_with_var_rng(subset, var, (rng_entry + i)->rng);
/* Get the union of bitset of clauses that contain the range
* values and that do not contain the variable. Subsumed clases
* are removed at the same time.
*/
bitset_union_removing_subsumption(subset_var_rng, subset_without_var);
/* Refine the leave */
decomposition_tree_approximate(subset_var_rng, state,
path_prob * cur_prob, &lower_bounds[i], &upper_bounds[i],
&next_bound_info, latest_var_column);
/* Reset the bitset */
reset_wsds_var_rng(subset_var_rng, var, (rng_entry + i)->rng);
/* Free the local bitset */
bitset_free(subset_var_rng);
/* Update the bounds with probability of the range value */
lower_bounds[i] *= cur_prob;
upper_bounds[i] *= cur_prob;
}
}
/* If the an epsilon-refinement has been reached, stop the iteration */
if (has_satisfied_stopping_condition)
break;
}
/* Sum up the bounds for all range values */
for (j = 0; j < rng_count; j++)
{
p_left_upper += upper_bounds[j];
p_left_lower += lower_bounds[j];
}
}
/* Compute the upper and lower bounds of the whole decomposition tree */
whole_upper = bound_info->coefficient_upper *
(p_left_upper + p_right_upper - p_left_upper * p_right_upper)
+ bound_info->constant_upper;
whole_lower = bound_info->coefficient_lower *
(p_left_lower + p_right_lower - p_left_lower * p_right_lower)
+ bound_info->constant_lower;
/* Relative cases */
if (is_relative)
{
/* Test the stopping condition */
if ((whole_upper - whole_lower) / whole_lower <= stopping_number)
{
has_satisfied_stopping_condition = true;
}
}
/* Absolute cases */
else
{
/* Test the stopping condition */
if ((whole_upper - whole_lower) <= stopping_number)
{
has_satisfied_stopping_condition = true;
}
}
/* If an epsilon-approximation has not been reached and the right partition
* is not NULL, proceed to the right partition.
*/
if (!has_satisfied_stopping_condition && p_right_lower != 0)
{
/* The code below prepares the necessary information to refine a leave */
/* TODO: More detailed explanation of coefficients and constants below is needed */
/* Compute the coefficient to be passed down in calculating the upper bound */
next_bound_info.coefficient_upper = bound_info->coefficient_upper * (1 - p_left_upper);
/* Compute the constant to be passed down in calculating the upper bound */
next_bound_info.constant_upper = bound_info->constant_upper + bound_info->coefficient_upper * p_left_upper;
/* Compute the coefficient to be passed down in calculating the lower bound */
next_bound_info.coefficient_lower = bound_info->coefficient_lower * (1 - p_left_lower);
/* Compute the constant to be passed down in calculating the lower bound */
next_bound_info.constant_lower = bound_info->constant_lower + bound_info->coefficient_lower * p_left_lower;
/* Compute the coefficient to be passed down in calculating the upper bound for deciding whether to close a leave */
next_bound_info.condition_coefficient_upper = next_bound_info.coefficient_upper;
/* Compute the constant to be passed down in calculating the upper bound for deciding whether to close a leave */
next_bound_info.condition_constant_upper = next_bound_info.constant_upper;
/* Compute the bitset for the right partition */
bitset_negate(set, subset);
/* Refine the right partition */
decomposition_tree_approximate(subset, state, path_prob, &p_right_lower,
&p_right_upper, &next_bound_info, latest_var_column);
}
/* Compute the upper and lower bounds of the node */
*lower = p_left_lower + p_right_lower - p_left_lower * p_right_lower;
*upper = p_left_upper + p_right_upper - p_left_upper * p_right_upper;
/* Free local bitsets */
if (subset_without_var)
bitset_free(subset_without_var);
bitset_free(subset);
}
/* decomposition_tree_exact
*
* This is the major function for exact confidence computation with
* decomposition tree. This is function is called only when epsilon is 0.
*/
static prob
decomposition_tree_exact(bitset* set, generalState *state, int latest_var_column)
{
prob p_left = 0.0;
prob p_right = 0.0;
int i;
bitset *subset;
int pos;
int var;
prob p_without_var = -1;
prob cur_prob = 0.0;
worldTableEntry *wt_entry;
rngEntry *rng_entry;
bitset* subset_without_var = NULL;
bitset* subset_var_rng;
/* Return 0 if the set if empty */
if (bitset_test_empty(set))
{
return 0.0;
}
/* Find subset of S independent of the rest (subset repr. dependent wsds) */
subset = find_independent_split(set);
#ifdef STATISTICS
counter++;
bitset_negate(set,subset);
if (subset != NULL && !bitset_test_empty(subset))
{
ind_counter++;
}
bitset_negate(set,subset);
#endif
/* Process the left subset containing dependent wsds */
pos = bitset_test_singleton(subset);
/* Special case of 1 wsd */
if (pos != -1)
p_left = S[pos]->prob;
/* Subset contains more than one wsd */
else
{
int new_var_column;
wt_entry = choose_var_max_occur_same_column(subset, state, latest_var_column, &new_var_column);
/* All vars are used in the wsd set */
if (wt_entry == NULL)
{
return 1.0;
}
var = wt_entry->var;
subset_without_var = find_wsds_without_var(subset, var);
rng_entry = wt_entry->rng_entries;
/* Loop the range values for a single variable */
for ( i = 0; i < wt_entry->rng_entry_count; i++)
{
cur_prob = ( rng_entry + i )->p;
subset_var_rng = find_wsds_with_var_rng(subset, var, ( rng_entry + i )->rng );
if (subset_var_rng == NULL)
{
if (p_without_var == -1)
{
p_without_var = decomposition_tree_exact (subset_without_var, state, new_var_column);
}
cur_prob *= p_without_var;
}
else
{
if (bitset_test_empty(subset_var_rng))
{
#ifdef STATISTICS
subsumption_counter += bitset_count_set(set);
#endif
}
else
{
bitset_union_removing_subsumption(subset_var_rng, subset_without_var);
cur_prob *= decomposition_tree_exact (subset_var_rng, state, new_var_column);
reset_wsds_var_rng(subset_var_rng, var, ( rng_entry + i )->rng );
}
}
p_left += cur_prob;
/* Stop early */
if ((p_left == 1.0) && (wt_entry->rng_entry_count == 1))
{
return 1.0;
}
if (subset_var_rng != NULL)
bitset_free(subset_var_rng);
}
}
/* Stop early */
if (p_left == 1.0)
{
return 1.0;
}
if (subset_without_var != NULL)
bitset_free(subset_without_var);
/* Process recursively the right subset */
bitset_negate(set,subset);
p_right = decomposition_tree_exact(subset, state, latest_var_column);
bitset_free(subset);
/* Combine the probabilities of left and right subsets */
return p_left + p_right - p_left * p_right;
}
/* Following are transition functions for ws-tree algorithm.
* They are actually only dummies and the task is done in the MACRO accum
*/
/* TODO: We can use arrays to store the condition columns in the future. */
/* conf_accum1_ge
*
* Transition function for exact confidence computation with 1 triple of
* condition columns
*/
Datum
conf_appro_accum1_ge(PG_FUNCTION_ARGS)
{
conf_appro_accum( 1 )
}
/* conf_accum2_ge
*
* Transition function for exact confidence computation with 2 triples of
* condition columns
*/
Datum
conf_appro_accum2_ge(PG_FUNCTION_ARGS)
{
conf_appro_accum( 2 )
}
/* conf_accum3_ge
*
* Transition function for exact confidence computation with 3 triples of
* condition columns
*/
Datum
conf_appro_accum3_ge(PG_FUNCTION_ARGS)
{
conf_appro_accum( 3 )
}
/* conf_accum4_ge
*
* Transition function for exact confidence computation with 4 triples of
* condition columns
*/
Datum
conf_appro_accum4_ge(PG_FUNCTION_ARGS)
{
conf_appro_accum( 4 )
}
/* conf_accum5_ge
*
* Transition function for exact confidence computation with 5 triples of
* condition columns
*/
Datum
conf_appro_accum5_ge(PG_FUNCTION_ARGS)
{
conf_appro_accum( 5 )
}
/* conf_accum6_ge
*
* Transition function for exact confidence computation with 6 triples of
* condition columns
*/
Datum
conf_appro_accum6_ge(PG_FUNCTION_ARGS)
{
conf_appro_accum( 6 )
}
/* conf_accum7_ge
*
* Transition function for exact confidence computation with 7 triples of
* condition columns
*/
Datum
conf_appro_accum7_ge(PG_FUNCTION_ARGS)
{
conf_appro_accum( 7 )
}
/* conf_accum8_ge
*
* Transition function for exact confidence computation with 8 triples of
* condition columns
*/
Datum
conf_appro_accum8_ge(PG_FUNCTION_ARGS)
{
conf_appro_accum( 8 )
}
/* conf_accum9_ge
*
* Transition function for exact confidence computation with 9 triples of
* condition columns
*/
Datum
conf_appro_accum9_ge(PG_FUNCTION_ARGS)
{
conf_appro_accum( 9 )
}
/* conf_accum10_ge
*
* Transition function for exact confidence computation with 10 triples of
* condition columns
*/
Datum
conf_appro_accum10_ge(PG_FUNCTION_ARGS)
{
conf_appro_accum( 10 )
}
/* conf_final_ge
*
* The final function for confidence computation of decomposition tree.
*/
Datum
conf_appro_final_ge(PG_FUNCTION_ARGS)
{
generalState *state = ( ( AggState *) fcinfo->context )->genstate;
prob result = 0;
bitset* set;
MemoryContext oldcxt;
bound_information bound_info;
float8 lower = 0;
float8 upper = 0;
#ifdef STATISTICS
int no_of_posssible_worlds = 1;
int i;
FILE * fp = fopen( "report.txt", "a" );
#endif
/* Return 0 if there is no tuple */
if (groupcxt == NULL)
PG_RETURN_FLOAT4(0);
/* Check the validity of the input */
if (strncmp(appro_approach, "R", 1) == 0)
is_relative = true;
else if (strncmp(appro_approach, "A", 1) == 0)
is_relative = false;
else
{
/* Delete the memory context for the group of duplicates */
MemoryContextDelete( groupcxt );
/* Set the world-set-descriptor-related global variables to NULL */
NUM_WSDS = 0;
S = NULL;
groupcxt = NULL;
elog(ERROR, "The approximation approach can only be 'R' (relative approximation) or 'A' (absolute approximation).");
}
/* Switch to the group context */
oldcxt = MemoryContextSwitchTo( groupcxt );
/* Complete the local world table */
getMissingRngs( state );
/* Compute the entry pointers of all clauses */
computeEntryPointers(state);
/* bitset related operation */
set = bitset_init(NUM_WSDS);
bitset_set(set);
/* If epsilon is larger than 0, call the approximate approach */
if (appro_epsilon > 0)
{
/* Set the stopping number used to decide whether an epsilon approximation is reached */
if (is_relative)
stopping_number = 2 * appro_epsilon / (1 - appro_epsilon);
else
stopping_number = 2 * appro_epsilon;
has_satisfied_stopping_condition = false;
/* Prepare the coefficients and constants for efficient upper and lower bound computation */
bound_info.coefficient_upper = 1;
bound_info.constant_upper = 0;
bound_info.coefficient_lower = 1;
bound_info.constant_lower = 0;
bound_info.condition_coefficient_upper = 1;
bound_info.condition_constant_upper = 0;
/* Statistics initialization */
ind_counter = 0;
counter = 0;
subsumption_counter = 0;
/* Quicksort the clauses according to their probabilities */
quicksort(S, 0, NUM_WSDS - 1);
/* Compute the upper and lower bounds before any node is constructed */
compute_upper_and_lower_bounds(set, &upper, &lower, state);
/* Relative case */
if (is_relative)
{
/* Test the stopping condition */
if ((upper - lower) / lower <= stopping_number)
has_satisfied_stopping_condition = true;
}
/* Absolute case */
else
{
/* Test the stopping condition */
if ((upper - lower) <= stopping_number)
has_satisfied_stopping_condition = true;
}
/* If an epsilon approximation is not reached, construct the decomposition tree */
if (!has_satisfied_stopping_condition)
{
lower = 0;
upper = 0;
decomposition_tree_approximate(set, state, 1, &lower, &upper, &bound_info, -1);
}
/* Relative case */
if (is_relative)
{
result = (upper * (1- appro_epsilon) + lower * (1 + appro_epsilon)) / 2;
}
/* Absolute case */
else
{
result = (upper + lower) / 2;
}
}
/* If epsilon is 0, call the exact confidence computation */
else
{
/* As above, test whether a 0-approximation has been reached before the tree construction */
compute_upper_and_lower_bounds(set, &upper, &lower, state);
/* Call the exact confidence computation */
if (upper - lower > 0)
{
result = decomposition_tree_exact(set, state, -1);
}
/* Stop early */
else
result = upper;
}
#ifdef STATISTICS
for (i = 0; i < state->wt_entry_count; i++)
{
no_of_posssible_worlds *= (state->wt_entries + i)->rng_entry_count;
}
fprintf(fp, "---------stats for 1 set of duplicates:\n");
fprintf(fp, "#clauses: %d\n", NUM_WSDS);
fprintf(fp, "#variables in a clause:%d\n", WSD_LEN);
fprintf(fp, "#variables:%d\n", state->wt_entry_count);
fprintf(fp, "#nodes:%d\n", counter);
fprintf(fp, "#possible worlds:%d\n", no_of_posssible_worlds);
fprintf(fp, "#independent partitions:%d\n", ind_counter);
fprintf(fp, "#subsumed claused:%d\n", subsumption_counter);
fprintf(fp, "Upper bound:%f\n", upper);
fprintf(fp, "Lower bound:%f\n", lower);
fclose(fp);
#endif
/* Switch back to the old context */
MemoryContextSwitchTo( oldcxt );
MemoryContextDelete( groupcxt );
/* Set the world-set-descriptor-related global variables to NULL */
NUM_WSDS = 0;
S = NULL;
groupcxt = NULL;
/* Return the result */
PG_RETURN_FLOAT4(result);
}
| 2.078125 | 2 |
2024-11-18T20:48:53.843795+00:00 | 2020-07-19T23:21:11 | 7449be706cab0508fe77c28a38bb2f33f10ba89c | {
"blob_id": "7449be706cab0508fe77c28a38bb2f33f10ba89c",
"branch_name": "refs/heads/master",
"committer_date": "2020-07-19T23:21:11",
"content_id": "9aa5bea31c389ce9a0526ee1f5bf4fd76d777933",
"detected_licenses": [
"MIT"
],
"directory_id": "4819e1478ff71392d72be8c8222863cfc3a9847e",
"extension": "c",
"filename": "bitarray.c",
"fork_events_count": 4,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 261607273,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 24717,
"license": "MIT",
"license_type": "permissive",
"path": "/ext/bitarray.c",
"provenance": "stackv2-0102.json.gz:85444",
"repo_name": "cleoold/bitarray",
"revision_date": "2020-07-19T23:21:11",
"revision_id": "0481816928afc54ad2a243dc0af22de457610ee8",
"snapshot_id": "dba1cc52120f9d649448c1ed6d0d296805d7ab1f",
"src_encoding": "UTF-8",
"star_events_count": 9,
"url": "https://raw.githubusercontent.com/cleoold/bitarray/0481816928afc54ad2a243dc0af22de457610ee8/ext/bitarray.c",
"visit_date": "2022-11-17T22:58:24.285311"
} | stackv2 | #include "bitarray_impl.h"
#include "lualibdefs.h"
/**
* The data structure Bitarray stores bits (booleans) in an array in a
* memory-saving manner internally. One can assign value (0 or 1) to
* each element as well as extract values from the array. <br/>
* Github: <a href="https://github.com/cleoold/bitarray">repo</a>
* @module bitarray
*/
/**
* Describes the loaded bitarray library info (version and lua version)
* @string __version
*/
#define BITARRAY_INFO "bitarray 1.51 for " LUA_VERSION
/**
* <code>sizeof(unsigned int)</code>.
* @number _blocksize
*/
#define BITARRAY_BLOCK_SIZE sizeof(WORD)
#define BITARRAY_MT_1 "cleoold.lua.bitarray_mt1"
/* checks whether given argument is bitarray */
#define checkbitarray(L, i) (Bitarray *)luaL_checkudata(L, (i), BITARRAY_MT_1)
/* create an array and push it to the top of the stack */
static int _l_new(lua_State *L, size_t nbits)
{
Bitarray *ba = (Bitarray *)lua_newuserdata(L, sizeof(Bitarray));
if (bitarray_validate(ba, nbits) == 0)
/* if fails to allocate array */
return 0;
luaL_getmetatable(L, BITARRAY_MT_1);
lua_setmetatable(L, -2);
return 1;
}
/**
* Creates a new bit array of n bits. all fields are initialized to 0.
* @function new
* @tparam integer nbits number of bits of the array
* @treturn Bitarray|nil the newly created bitarray if successful
*/
BITARRAY_API static int l_new(lua_State *L)
{
lua_Integer nbits = luaL_checkinteger(L, 1);
luaL_argcheck(L, nbits > 0, 1, "invalid size");
return _l_new(L, (size_t)nbits);
}
/**
* Creates a new bit array, identical to src.
* @function copyfrom
* @tparam Bitarray src
* @treturn Bitarray|nil the newly created bitarray if successful
*/
BITARRAY_API static int l_copyfrom(lua_State *L)
{
Bitarray *ba = checkbitarray(L, 1);
if (_l_new(L, ba->size) == 0)
return 0;
bitarray_copyvalues(ba, (Bitarray *)lua_touserdata(L, -1));
return 1;
}
/**
* @type Bitarray
*/
static Bitarray *checkbitarray_and_index(lua_State *L, size_t *i)
{
Bitarray *ba = checkbitarray(L, 1);
lua_Integer i_ = luaL_checkinteger(L, 2) - 1;
luaL_argcheck(L, 0 <= i_ && i_ < ba->size, 2, "index out of range");
*i = (size_t)i_;
return ba;
}
/* default opt chain: [,1 [,array size]] */
static Bitarray *checkbitarray_and_optrange(lua_State *L, size_t *from, size_t *to)
{
Bitarray *ba = checkbitarray(L, 1);
lua_Integer from_ = luaL_optinteger(L, 2, 1) - 1;
luaL_argcheck(L, 0 <= from_ && from_ < ba->size, 2, "invalid index");
lua_Integer to_ = luaL_optinteger(L, 3, ba->size);
luaL_argcheck(L, to_ > from_ && to_ <= ba->size, 3, "invalid index");
*from = (size_t)from_;
*to = (size_t)to_;
return ba;
}
/**
* <i>Mutates the array.</i> <br />
* Set the ith bit of the array. Any value other than false or nil will be
* considered a truthy(1) bit. <br />
* Operator __newindex is overloaded with this method.
* @function set
* @tparam integer i the index
* @tparam any b the value to change to
* @treturn Bitarray the original bit array reference
* @usage
* local a = Bitarray.new(10)
* a:set(4, true)
* a[4] = true -- same
*/
BITARRAY_API static int setbit(lua_State *L)
{
size_t i;
Bitarray *ba = checkbitarray_and_index(L, &i);
luaL_checkany(L, 3);
bitarray_set_bit(ba, i, lua_toboolean(L, 3));
lua_pushvalue(L, 1);
return 1;
}
/**
* <i>Does not mutate the array.</i> <br />
* Get the ith bit of the array. <br />
* Operator __index is overloaded with this method.
* @function at
* @tparam integer i the index
* @treturn boolean true if bit is 1, false if 0
* @usage
* local a = Bitarray.new(10)
* a:at(7) -- false
* a[7] -- false
*/
BITARRAY_API static int getbit(lua_State *L)
{
size_t i;
Bitarray *ba = checkbitarray_and_index(L, &i);
lua_pushboolean(L, bitarray_get_bit(ba, i));
return 1;
}
/**
* <i>Does not mutate the array.</i> <br />
* Get the length of the array. <br />
* Operator __len is overloaded with this method.
* @function len
* @treturn integer the number of bits of the array
* @usage
* local a = Bitarray.new(10)
* a:len(a) -- 10
* #a -- 10
*/
BITARRAY_API static int len(lua_State *L)
{
Bitarray *ba = checkbitarray(L, 1);
lua_pushinteger(L, ba->size);
return 1;
}
/**
* <i>Mutates the array.</i> <br />
* Set all bits of the array. Any value other than false or nil will be
* considered a truthy(1) bit. <br />
* @function fill
* @tparam any b the value to change to
* @treturn Bitarray the original bit array reference
* @usage
* local a = Bitarray.new(10)
* a:fill(true) -- all bits set to 1
*/
BITARRAY_API static int fill(lua_State *L)
{
Bitarray *ba = checkbitarray(L, 1);
luaL_checkany(L, 2);
bitarray_fill(ba, lua_toboolean(L, 2));
lua_pushvalue(L, 1);
return 1;
}
/**
* <i>Mutates the array.</i> <br />
* If argument i is present, the bit at that index is flipped, if not or
* i is 0, all the bits are flipped.
* @function flip
* @tparam[opt] integer i the index
* @treturn Bitarray the original bit array reference
* @usage
* local a = Bitarray.new(10)
* a:flip() -- all bits set to true
* a:flip(1) -- sets first bit to true
*/
BITARRAY_API static int flip(lua_State *L)
{
Bitarray *ba = checkbitarray(L, 1);
lua_Integer i = luaL_optinteger(L, 2, 0);
luaL_argcheck(L, 0 <= i && i <= ba->size, 2, "index out of range");
if (i == 0)
bitarray_flip(ba);
else
bitarray_flip_bit(ba, (size_t)i - 1);
lua_pushvalue(L, 1);
return 1;
}
/**
* <i>May mutate the array. </i> <br />
* Resize the array to length n. if new size is greater, the new bits
* are appended to the right and initialized to 0, otherwise additional
* rightmost bits are lost.
* @function resize
* @tparam integer n >= 1
* @treturn Bitarray|nil the original bit array reference if successful,
* otherwise nil
*/
BITARRAY_API static int resize(lua_State *L)
{
Bitarray *ba = checkbitarray(L, 1);
lua_Integer i = luaL_checkinteger(L, 2);
luaL_argcheck(L, 0 < i, 2, "invalid length");
if (bitarray_resize(ba, (size_t)i) == 0)
/* resize failed */
return 0;
lua_pushvalue(L, 1);
return 1;
}
/**
* <i>Mutates the array.</i> <br />
* Reverse the contents of the array.
* @function reverse
* @treturn Bitarray the original bit array reference
*/
BITARRAY_API static int reverse(lua_State *L)
{
Bitarray *ba = checkbitarray(L, 1);
bitarray_reverse(ba);
return 1;
}
/**
* <i>Does not mutate the array.</i> <br />
* Creates a new array with bits obtained from those at index i to n in the
* original array, inclusive. Resultant length is n - i + 1.
* @function slice
* @tparam[opt] integer i the starting index, default 1
* @tparam[optchain] integer n the ending index, default the length of the array.
* @treturn Bitarray|nil the newly created bit array reference if successful
* @usage
* local a = Bitarray.new(8):set(3, true):set(5, true)
* local b = a:slice(1, 4)
* print(a) -- Bitarray[0,0,1,0,1,0,0,0]
* print(b) -- Bitarray[0,0,1,0]
*/
BITARRAY_API static int slice(lua_State *L)
{
size_t from, to;
Bitarray *ba = checkbitarray_and_optrange(L, &from, &to);
if (_l_new(L, to - from) == 0)
return 0;
bitarray_copyvalues2(ba, (Bitarray *)lua_touserdata(L, -1), from, to, 0);
return 1;
}
/**
* <i>Does not mutate the array.</i> <br />
* Repeat the array n times and return the new array. <br />
* @function rep
* @tparam integer n >= 1
* @treturn Bitarray|nil the newly created bit array reference if successful
* @usage
* local a = Bitarray.new(3):set(3, true)
* print(a:rep(4)) -- Bitarray[0,0,1,0,0,1,0,0,1,0,0,1]
*/
BITARRAY_API static int rep(lua_State *L)
{
Bitarray *ba = checkbitarray(L, 1);
lua_Integer n = luaL_checkinteger(L, 2);
luaL_argcheck(L, n > 0, 2, "number of repetition must be positive integer");
if (_l_new(L, ba->size * n) == 0)
return 0;
Bitarray *r = (Bitarray *)lua_touserdata(L, -1);
bitarray_copyvalues(ba, r);
for (size_t i = 1; i < (size_t)n; ++i)
bitarray_copyvalues2(ba, r, 0, ba->size, i * ba->size);
return 1;
}
/**
* <i>Does not mutate the array.</i> <br />
* Compares whether two arrays are identical (same value and length). <br />
* Operator __eq is overloaded with this method.
* @function equal
* @tparam Bitarray other
* @treturn boolean
* @usage
* local a = Bitarray.new(10)
* local b = Bitarray.copyfrom(a)
* a:equal(b) -- true
* a == b:resize(1) -- false
*/
BITARRAY_API static int equal(lua_State *L)
{
Bitarray *ba = checkbitarray(L, 1);
Bitarray *o = checkbitarray(L, 2);
lua_pushboolean(L, bitarray_equal(ba, o));
return 1;
}
/**
* <i>Does not mutate the array.</i> <br />
* Concatenate two arrays and return the new array. <br />
* Operator __concat is overloaded with this method.
* @function concat
* @tparam Bitarray other
* @treturn Bitarray|nil the newly created bit array reference if successful
* @usage
* local a = Bitarray.new(1)
* local b = Bitarray.new(4):fill(true)
* print(a..b) -- Bitarray[0,1,1,1,1]
*/
BITARRAY_API static int concat(lua_State *L)
{
Bitarray *ba = checkbitarray(L, 1);
Bitarray *o = checkbitarray(L, 2);
if (_l_new(L, ba->size + o->size) == 0)
return 0;
Bitarray *r = (Bitarray *)lua_touserdata(L, -1);
bitarray_copyvalues(ba, r);
bitarray_copyvalues2(o, r, 0, o->size, ba->size);
return 1;
}
/**
* <i>Does not mutate the array.</i> <br />
* Flip all bits of the array and return the new array. <br />
* Operator __bnot is overloaded with this method. (5.3+)
* @function bnot
* @treturn Bitarray|nil the newly created bit array reference if successful
* @usage
* local a = Bitarray.new(2):set(1, true)
* print(~a) -- Bitarray[0,1]
*/
BITARRAY_API static int bnot(lua_State *L)
{
Bitarray *ba = checkbitarray(L, 1);
if (_l_new(L, ba->size) == 0)
return 0;
Bitarray *r = (Bitarray *)lua_touserdata(L, -1);
bitarray_copyvalues(ba, r);
bitarray_flip(r);
return 1;
}
#define BITARRAY_BIT_BIOP(NAME, OP) \
static int NAME(lua_State *L) \
{ \
Bitarray *ba = checkbitarray(L, 1); \
Bitarray *o = checkbitarray(L, 2); \
luaL_argcheck(L, ba->size == o->size, 2, \
"two operands must be of same size"); \
\
if (_l_new(L, ba->size) == 0) \
return 0; \
Bitarray *r = (Bitarray *)lua_touserdata(L, -1); \
BITARRAY_WORD_ITER(r, i, \
r->values[i] = ba->values[i] OP o->values[i]; \
); \
return 1; \
}
/**
* <i>Does not mutate the array.</i> <br />
* Perform a bitwise AND and return the new array. Two arrays have to be of
* same size. <br />
* Operator __band is overloaded with this method. (5.3+)
* @function band
* @tparam Bitarray other
* @treturn Bitarray|nil the newly created bit array reference if successful
* @usage
* local a = Bitarray.new(4):set(1, true):set(3, true)
* local b = Bitarray.new(4):set(1, true)
* print(a & b) -- Bitarray[1,0,0,0]
*/
BITARRAY_API BITARRAY_BIT_BIOP(band, &)
/**
* <i>Does not mutate the array.</i> <br />
* Perform a bitwise OR and return the new array. Two arrays have to be of
* same size. <br />
* Operator __bor is overloaded with this method. (5.3+)
* @see band
* @function bor
* @tparam Bitarray other
* @treturn Bitarray|nil the newly created bit array reference if successful
*/
BITARRAY_API BITARRAY_BIT_BIOP(bor, |)
/**
* <i>Does not mutate the array.</i> <br />
* Perform a bitwise XOR and return the new array. Two arrays have to be of
* same size. <br />
* Operator __bxor is overloaded with this method. (5.3+)
* @see band
* @function bxor
* @tparam Bitarray other
* @treturn Bitarray|nil the newly created bit array reference if successful
*/
BITARRAY_API BITARRAY_BIT_BIOP(bxor, ^)
#undef BITARRAY_BIT_BIOP
/**
* <i>Does not mutate the array.</i> <br />
* Shift all content left n bits and return the new array. Extra bits are
* discarded and empty bits are filled with 0. <br />
* Operator __shl is overloaded with this method. (5.3+)
* @function shiftleft
* @tparam integer n
* @treturn Bitarray|nil the newly created bit array reference if successful
* @usage
* local a = Bitarray.new(8):from_uint8(15)
* print(a) -- Bitarray[0,0,0,0,1,1,1,1]
* print(a << 2) -- Bitarray[0,0,1,1,1,1,0,0]
*/
BITARRAY_API static int shl(lua_State *L)
{
Bitarray *ba = checkbitarray(L, 1);
long s = (long)luaL_checkinteger(L, 2);
if (_l_new(L, ba->size) == 0)
return 0;
Bitarray *r = (Bitarray *)lua_touserdata(L, -1);
bitarray_copyvalues(ba, r);
if (s >= 0)
bitarray_be_lshift(r, (size_t)s);
else
bitarray_be_rshift(r, (size_t)-s);
return 1;
}
/**
* <i>Does not mutate the array.</i> <br />
* Shift all content right n bits and return the new array. Extra bits are
* discarded and empty bits are filled with 0. The shift is unsigned. <br />
* Operator __shr is overloaded with this method. (5.3+)
* @see shiftleft
* @function shiftright
* @tparam integer n
* @treturn Bitarray|nil the newly created bit array reference if successful
*/
BITARRAY_API static int shr(lua_State *L)
{
Bitarray *ba = checkbitarray(L, 1);
long s = (long)luaL_checkinteger(L, 2);
if (_l_new(L, ba->size) == 0)
return 0;
Bitarray *r = (Bitarray *)lua_touserdata(L, -1);
bitarray_copyvalues(ba, r);
if (s >= 0)
bitarray_be_rshift(r, (size_t)s);
else
bitarray_be_lshift(r, (size_t)-s);
return 1;
}
static size_t checkopt_index(lua_State *L, Bitarray *ba, int nArg)
{
lua_Integer i = luaL_optinteger(L, nArg, 1) - 1;
luaL_argcheck(L, 0 <= i && i < ba->size, nArg, "index out of range");
return (size_t)i;
}
#define BITARRAY_AT_TYPE(TYPE) \
static int at_ ## TYPE(lua_State *L) \
{ \
Bitarray *ba = checkbitarray(L, 1); \
size_t i = checkopt_index(L, ba, 2); \
size_t tgt = sizeof(TYPE) * CHAR_BIT; \
luaL_argcheck(L, ba->size - i + 1 > tgt, 2, \
"too few bits to construct this type"); \
\
TYPE res = 0; \
for (size_t j = i, k = 0; k < tgt; ++j, ++k) { \
WORD mask; \
WORD *word = bitarray_get_bit_access(ba, j, &mask); \
TYPE maskt = (TYPE)1 << (TYPE)(tgt-k-1); \
res = (*word & mask) ? (res | maskt) : (res & ~maskt); \
} \
lua_pushinteger(L, (lua_Integer)res); \
return 1; \
}
/**
* <i>Does not mutate the array.</i> <br />
* Converts the contents starting at index i to an uint8 (uchar) integer.
* The array should be big enough to hold bits required to construct the
* type.
* The leftmost bit corresponds to the most significant digit of the number
* and the last bit corresponds to the least significant digit (big endian).
* @function at_uint8
* @tparam[opt] integer i default to 1
* @treturn integer
* @usage
* local a = Bitarray.new(10):set(2, 1):set(3, 1):set(4, 1):set(5, 1):set(7, 1)
* print(a) -- Bitarray[0,1,1,1,1,0,1,0,0,0]
* a:at_uint8(2) -- intepreted as 11110100, which is 244
*/
BITARRAY_API BITARRAY_AT_TYPE(uint8_t)
/**
* <i>Does not mutate the array.</i> <br />
* Converts the contents starting at index i to an uint16 integer.
* @see at_uint8
* @function at_uint16
* @tparam[opt] integer i
* @treturn integer
*/
BITARRAY_API BITARRAY_AT_TYPE(uint16_t)
/**
* <i>Does not mutate the array.</i> <br />
* Converts the contents starting at index i to an uint32 integer.
* @see at_uint8
* @function at_uint32
* @tparam[opt] integer i
* @treturn integer
*/
BITARRAY_API BITARRAY_AT_TYPE(uint32_t)
/**
* <i>Does not mutate the array.</i> <br />
* Converts the contents starting at index i to an uint64 integer.
* @see at_uint8
* @function at_uint64
* @tparam[opt] integer i
* @treturn integer
* @usage
* -- lua5.3 added support for displaying and manipulating unsigned integers,
* -- prior to that this function may not work as intended always
* local a = Bitarray.new(64):fill(true)
* string.format('%u', a:at_uint64()) -- 18446744073709551615
*/
BITARRAY_API BITARRAY_AT_TYPE(uint64_t)
#undef BITARRAY_AT_TYPE
#define BITARRAY_FROM_TYPE(TYPE) \
static int from_ ## TYPE(lua_State *L) \
{ \
Bitarray *ba = checkbitarray(L, 1); \
TYPE src = (TYPE)luaL_checkinteger(L, 2); \
size_t i = checkopt_index(L, ba, 3); \
size_t tgt = sizeof(TYPE) * CHAR_BIT; \
luaL_argcheck(L, ba->size - i + 1 > tgt, 3, \
"too few bits to contain this type"); \
\
for (size_t j = i, k = 0; k < tgt; ++j, ++k) { \
TYPE maskt = (TYPE)1 << (TYPE)(tgt-k-1); \
int b = !!(src & maskt); \
bitarray_set_bit(ba, j, b); \
} \
lua_pushvalue(L, 1); \
return 1; \
}
/**
* <i>Mutates the array.</i> <br />
* Assign the array from index i from an uint8 (uchar) integer. The array should
* be big enough to store the representation.
* The leftmost bit corresponds to the most significant digit of the number
* and the last bit corresponds to the least significant digit (big endian).
* @function from_uint8
* @tparam integer src the source integer to convert from
* @tparam[opt] integer i the index in this array where the first bit gets
* copied from src. default 1
* @treturn Bitarray the original bit array reference
* @usage
* local a = Bitarray.new(8):from_uint8(253)
* print(a) -- Bitarray[1,1,1,1,1,1,0,1]
* local b = Bitarray.new(16):from_uint8(255, 9)
* print(b) -- Bitarray[0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1]
*/
BITARRAY_API BITARRAY_FROM_TYPE(uint8_t)
/**
* <i>Mutates the array.</i> <br />
* Assign the array from index i from an uint16 integer. The array should
* be big enough to store the representation.
* @see from_uint8
* @function from_uint16
* @tparam integer src
* @tparam[opt] integer i
* @treturn Bitarray the original bit array reference
*/
BITARRAY_API BITARRAY_FROM_TYPE(uint16_t)
/**
* <i>Mutates the array.</i> <br />
* Assign the array from index i from an uint32 integer. The array should
* be big enough to store the representation.
* @see from_uint8
* @function from_uint32
* @tparam integer src
* @tparam[opt] integer i
* @treturn Bitarray the original bit array reference
*/
BITARRAY_API BITARRAY_FROM_TYPE(uint32_t)
/**
* <i>Mutates the array.</i> <br />
* Assign the array from index i from an uint64 integer. The array should
* be big enough to store the representation.
* @see from_uint8
* @see at_uint64
* @function from_uint64
* @tparam integer src
* @tparam[opt] integer i
* @treturn Bitarray the original bit array reference
*/
BITARRAY_API BITARRAY_FROM_TYPE(uint64_t)
#undef BITARRAY_FROM_TYPE
/**
* <i>Mutates the array.</i> <br />
* Copy the content from bitarray src to the operand. The array's ith, i+1th,
* ... bit will be the bits from src starting from 1st to the last. The array
* needs to be big enough to hold the data.
* @function from_bitarray
* @tparam Bitarray src
* @tparam[opt] integer i the index in this array where the first bit gets
* copied from src. default 1
* @treturn Bitarray the original bit array reference
* @usage
* local a = Bitarray.new(10)
* :from_bitarray(Bitarray.new(5):fill(true):set(3, false), 6)
* print(a) -- Bitarray[0,0,0,0,0,1,1,0,1,1]
*/
BITARRAY_API static int from_bitarray(lua_State *L)
{
Bitarray *ba = checkbitarray(L, 1);
Bitarray *src = checkbitarray(L, 2);
size_t i = checkopt_index(L, ba, 3);
luaL_argcheck(L, ba->size - i + 1 > src->size, 3, "not enough space");
bitarray_copyvalues2(src, ba, 0, src->size, i);
lua_pushvalue(L, 1);
return 1;
}
/**
* <i>Mutates the array.</i> <br />
* Copy the content from a binary string to the operand. Given the string
* consisting of only 0 and 1's, the array's ith, i+1th, ... bit will be
* the false/true values represented by chars in this string. The array
* needs to be big enough to hold the data.
* @function from_binarystring
* @tparam string src
* @tparam[opt] integer i the index in this array where the first bit gets
* copied from src. default 1
* @treturn Bitarray the original bit array reference
* @usage
* local a = Bitarray.new(12)
* :from_binarystring('001100'):from_binarystring('111111', 7)
* print(a) -- Bitarray[0,0,1,1,0,0,1,1,1,1,1,1]
* -- a:from_binarystring('10x0') error! invalid string
*/
BITARRAY_API static int from_binarystring(lua_State *L)
{
Bitarray *ba = checkbitarray(L, 1);
size_t slen;
const char *s = luaL_checklstring(L, 2, &slen);
size_t i = checkopt_index(L, ba, 3);
for (size_t j = 0; j < slen; ++j) {
if (s[j] != '1' && s[j] != '0')
luaL_argerror(L, 2, "invalid binary string");
}
luaL_argcheck(L, ba->size - i + 1 > slen, 3, "not enough space");
for (size_t j = 0; j < slen; ++j)
bitarray_set_bit(ba, i + j, s[j] == '1');
lua_pushvalue(L, 1);
return 1;
}
/**
* <i>Does not mutate the array.</i> <br />
* Returns the string representation for the array. <br />
* Metamethod __tostring is overloaded with this method so it can be implicitly
* called if string is needed. The full array is not displayed if it is too long.
* @function tostring
* @treturn string
* @usage
* local a = Bitarray.new(8):set(8, true)
* print(a)
* -- Bitarray[0,0,0,0,0,0,0,1]
* a:resize(65)
* print(a)
* -- Bitarray[...]
*/
BITARRAY_API static int tostring(lua_State *L)
{
Bitarray *ba = checkbitarray(L, 1);
luaL_Buffer buf;
luaL_buffinit(L, &buf);
luaL_addstring(&buf, "Bitarray[");
if (ba->size > (size_t)64) {
luaL_addstring(&buf, "...]");
goto push;
}
for (size_t i = 0; i < ba->size-1; ++i) {
luaL_addstring(&buf, bitarray_get_bit(ba, i) ? "1," : "0,");
}
/* size cannot be 0 in this context */
luaL_addstring(&buf, bitarray_get_bit(ba, ba->size-1) ? "1]" : "0]");
push:
luaL_addvalue(&buf);
luaL_pushresult(&buf);
return 1;
}
/* finalizer for bitarray */
BITARRAY_API static int gc(lua_State *L)
{
Bitarray *ba = checkbitarray(L, 1);
bitarray_invalidate(ba);
return 0;
}
/* actual __index, if param if number it returns result of get(), otherwise
looks up for fields */
BITARRAY_API static int get(lua_State *L)
{
#if LUA_VERSION_NUM >= 503
if (lua_isinteger(L, 2))
#else
if (lua_isnumber(L, 2))
#endif
return getbit(L);
luaL_getmetatable(L, BITARRAY_MT_1);
lua_pushvalue(L, 2);
lua_rawget(L, -2);
return 1;
}
static const struct luaL_Reg bitarraylib_f[] =
{
{ "new", l_new },
{ "copyfrom", l_copyfrom },
{ NULL, NULL }
};
static const struct luaL_Reg bitarraylib_m1[] =
{
{ "at", getbit },
{ "set", setbit },
{ "len", len },
{ "fill", fill },
{ "flip", flip },
{ "equal", equal },
{ "concat", concat },
{ "bnot", bnot },
{ "band", band },
{ "bor", bor },
{ "bxor", bxor },
{ "shiftleft", shl },
{ "shiftright", shr },
{ "resize", resize },
{ "reverse", reverse },
{ "slice", slice },
{ "rep", rep },
{ "at_uint8", at_uint8_t },
{ "at_uint16", at_uint16_t },
{ "at_uint32", at_uint32_t },
{ "at_uint64", at_uint64_t },
{ "from_bitarray", from_bitarray },
{ "from_binarystring", from_binarystring },
{ "from_uint8", from_uint8_t },
{ "from_uint16", from_uint16_t },
{ "from_uint32", from_uint32_t },
{ "from_uint64", from_uint64_t },
{ "tostring", tostring },
{ "__index", get },
{ "__newindex", setbit },
{ "__len", len },
{ "__eq", equal },
{ "__concat", concat },
#if (defined(LUA_VERSION_NUM) && (LUA_VERSION_NUM >= 503))
{ "__bnot", bnot },
{ "__band", band },
{ "__bor", bor },
{ "__bxor", bxor },
{ "__shl", shl },
{ "__shr", shr },
#endif
{ "__gc", gc },
{ "__tostring", tostring },
{ NULL, NULL }
};
BITARRAY_MAIN int luaopen_bitarray(lua_State *L)
{
luaL_newmetatable(L, BITARRAY_MT_1);
#ifndef LUA_VERSION_NUM
#error "unknown lua version"
#elif LUA_VERSION_NUM <= 501 /* for old module system */
luaL_register(L, NULL, bitarraylib_m1);
luaL_register(L, "bitarray", bitarraylib_f);
#else /* for above lua 5.2 */
luaL_setfuncs(L, bitarraylib_m1, 0);
luaL_newlib(L, bitarraylib_f);
#endif
lua_pushliteral(L, BITARRAY_INFO);
lua_setfield(L, -2, "__version");
lua_pushinteger(L, BITARRAY_BLOCK_SIZE);
lua_setfield(L, -2, "_blocksize");
return 1;
}
| 2.609375 | 3 |
2024-11-18T20:48:53.911828+00:00 | 2021-03-31T05:54:26 | dac0912f44ca2f665836a36fc3de823df6f5cf68 | {
"blob_id": "dac0912f44ca2f665836a36fc3de823df6f5cf68",
"branch_name": "refs/heads/main",
"committer_date": "2021-03-31T05:54:26",
"content_id": "fccff4b26d81fa91ac633476c792d0ae550b1251",
"detected_licenses": [
"MIT"
],
"directory_id": "52278536766976999f22bed761e271e0f3fbe84a",
"extension": "c",
"filename": "frame.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 342571726,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 10039,
"license": "MIT",
"license_type": "permissive",
"path": "/hdlc/frame.c",
"provenance": "stackv2-0102.json.gz:85572",
"repo_name": "gremlin1206/openspodes",
"revision_date": "2021-03-31T05:54:26",
"revision_id": "8181290eb0b70bf8e52a9f26f67cc31ce4b3bf5f",
"snapshot_id": "d3aed7910519dd0ea11557b2ada60cb231bd9dd2",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/gremlin1206/openspodes/8181290eb0b70bf8e52a9f26f67cc31ce4b3bf5f/hdlc/frame.c",
"visit_date": "2023-03-31T23:59:51.364236"
} | stackv2 | /*
MIT License
Copyright (c) 2021 gremlin1206
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include "frame.h"
#include "hdlc.h"
#include "fcs16.h"
//#define DLMS_HDLC_DEBUG 1
#ifdef DLMS_HDLC_DEBUG
# define PRINTF printf
#else
# define PRINTF(...)
#endif
static int hdlc_put_format_type(unsigned char *p, struct hdlc_format_t value, unsigned int length)
{
p[0] = ((length >> 8) & 0x7) | (value.type << 4) | (value.S << 3);
p[1] = (length & 0xFF);
return 2;
}
static int hdlc_put_address_type(unsigned char *p, struct hdlc_address_t addr)
{
switch (addr.len)
{
case 1:
p[0] = (addr.upper << 1) | 1;
return 1;
case 2:
p[0] = (addr.upper << 1);
p[1] = (addr.lower << 1) | 1;
return 2;
case 4:
p[0] = (addr.upper >> 6) & 0xFE;
p[1] = (addr.upper << 1);
p[2] = (addr.lower >> 6) & 0xFE;
p[3] = (addr.lower << 1) | 1;
return 4;
default:
return -1;
}
}
static int hdlc_put_control_type(unsigned char *p, struct hdlc_control_t value)
{
unsigned char b = 0;
switch (value.code)
{
case HDLC_FRAME_I:
b = (value.nr << 5) | (value.pf << 4) | (value.ns << 1);
break;
case HDLC_FRAME_RR:
b = (value.nr << 5) | (value.pf << 4) | 0x01;
break;
case HDLC_FRAME_RNR:
b = (value.nr << 5) | (value.pf << 4) | 0x05;
break;
case HDLC_COMMAND_SNRM:
b = (value.pf << 4) | 0x83;
break;
case HDLC_COMMAND_DISC:
b = (value.pf << 4) | 0x43;
break;
case HDLC_RESPONSE_UA:
b = (value.pf << 4) | 0x63;
break;
case HDLC_RESPONSE_DM:
b = (value.pf << 4) | 0x0F;
break;
case HDLC_RESPONSE_FRMR:
b = (value.pf << 4) | 0x87;
break;
case HDLC_FRAME_UI:
b = (value.pf << 4) | 0x03;
break;
default:
return -1;
}
*p = b;
return 1;
}
static int hdlc_get_frame_length(unsigned char* p, unsigned int size)
{
unsigned char high, low;
uint16_t length;
if (size < 2)
return -1;
high = p[0];
low = p[1];
length = (high & 0x7);
length <<= 8;
length |= low;
return (int)length;
}
static int hdlc_get_format_type(struct hdlc_format_t *value, unsigned char* p, unsigned int size)
{
unsigned char high;
if (size < 2)
return -1;
high = p[0];
value->type = high >> 4;
value->S = (high & (1 << 3)) ? 1 : 0;
return 2;
}
static int hdlc_get_address_type(struct hdlc_address_t *value, unsigned char* p, unsigned int size)
{
uint32_t b1, b2, b3, b4;
value->upper = value->lower = 0;
if (size < 1)
return -1;
b1 = p[0];
if (b1 & 1)
{
value->upper = b1 >> 1;
value->len = 1;
return 1;
}
if (size < 2)
return -1;
b2 = p[1];
if (b2 & 1)
{
value->upper = (b1 >> 1);
value->lower = (b2 >> 1);
value->len = 2;
return 2;
}
if (size < 4)
return -1;
b3 = p[2];
b4 = p[3];
if ((b3 & 1) == 0 && (b4 & 1))
{
value->upper = (b1 << 6) | (b2 >> 1);
value->lower = (b3 << 6) | (b4 >> 1);
value->len = 4;
return 4;
}
return -1;
}
static int hdlc_check_hcs_fcs(unsigned char* p, unsigned int size, int hcs_index)
{
uint16_t fcs = FCS16_INIT_VALUE;
unsigned int pos = 0;
if (hcs_index > 0)
{
for (; pos < hcs_index; pos++)
{
fcs = fcs16(fcs, p[pos]);
}
if (fcs != FCS16_GOOD_VALUE)
{
PRINTF("BAD HCS\n");
return -2;
}
}
for (; pos < size; pos++)
{
fcs = fcs16(fcs, p[pos]);
}
if (fcs != FCS16_GOOD_VALUE)
{
PRINTF("BAD FCS\n");
return -1;
}
return 0;
}
static int hdlc_get_control_type(struct hdlc_control_t *value, unsigned char* p, unsigned int size)
{
unsigned char b;
unsigned char nr, ns;
if (size < 1)
return -1;
memset(value, 0, sizeof(*value));
b = *p;
value->pf = (b & (1 << 4)) ? 1 : 0;
nr = b >> 5;
ns = (b >> 1) & 0x7;
if (!(b & 1))
{
// I command/response
value->nr = nr;
value->ns = ns;
value->code = HDLC_FRAME_I;
}
else
{
switch (ns)
{
case 0:
value->nr = nr;
value->code = HDLC_FRAME_RR;
break;
case 2:
value->nr = nr;
value->code = HDLC_FRAME_RNR;
break;
case 1:
switch (nr)
{
case 4:
value->code = HDLC_COMMAND_SNRM;
break;
case 2:
value->code = HDLC_COMMAND_DISC;
break;
case 3:
value->code = HDLC_RESPONSE_UA;
break;
case 0:
value->code = HDLC_FRAME_UI;
break;
}
break;
case 7:
if (nr == 0)
value->code = HDLC_RESPONSE_DM;
break;
case 3:
if (nr == 4)
value->code = HDLC_RESPONSE_FRMR;
break;
}
}
if (value->code == 0)
{
PRINTF("unrecognized frame code\n");
value->code = HDLC_FRAME_UNKNOWN;
}
return 1;
}
void hdlc_frame_print(struct hdlc_frame_t *frame)
{
PRINTF("frame: [%p]\n", frame);
PRINTF("\ttype: %u\n", frame->format.type);
PRINTF("\tS: %u\n", frame->format.S);
//PRINTF("\tlength: %u\n", frame->format.length);
PRINTF("\tdest: %u.%u\n", frame->dest_address.upper, frame->dest_address.lower);
PRINTF("\tsrc: %u.%u\n", frame->src_address.upper, frame->src_address.lower);
PRINTF("\tctrl.code: %u\n", frame->control.code);
PRINTF("\tN(R): %u\n", frame->control.nr);
PRINTF("\tN(S): %u\n", frame->control.ns);
PRINTF("\tP/F: %u\n", frame->control.pf);
PRINTF("\tinfo_len: %u\n", frame->info_len);
if (frame->info_len > 0)
{
unsigned int i;
for (i = 0; i < frame->info_len; i++)
{
PRINTF("%02X ", frame->info[i]);
}
PRINTF("\n");
}
}
/*
* Frame Format:
* Flag | Frame format | Dest. address | Src. address | Control | HCS | Information | FCS | Flag
*
* Flag = 0x7E
*/
int hdlc_frame_parse(struct hdlc_frame_t *frame, struct hdlc_bs_t *bs)
{
int ret;
unsigned char *frm = bs->frame;
unsigned char *p = frm;
unsigned int length = bs->length;
unsigned int s = length;
//uint16_t hcs = FCS16_INIT_VALUE;
int hcs_index = 0;
//PRINTF("hdlc_frame_parse length: %u\n", length);
ret = hdlc_get_frame_length(p, s);
if (ret < 0)
{
PRINTF("fail to get frame length\n");
return ret;
}
frame->length = (unsigned int)ret;
if (length != frame->length)
{
PRINTF("invalid length\n");
PRINTF("expected frame length: %u input length: %u\n", frame->length, length);
unsigned int i;
for (i = 0; i < length; i++)
{
PRINTF("%02X ", frm[i]);
}
PRINTF("\n");
return -1;
}
ret = hdlc_get_format_type(&frame->format, p, s);
if (ret < 0)
{
PRINTF("bad format type\n");
return ret;
}
if (frame->format.type != HDLC_TYPE_3)
{
PRINTF("invalid format type value: %u\n", frame->format.type);
return -1;
}
s -= ret;
p += ret;
ret = hdlc_get_address_type(&frame->dest_address, p, s);
if (ret < 0)
{
PRINTF("bad dest address\n");
return ret;
}
s -= ret;
p += ret;
ret = hdlc_get_address_type(&frame->src_address, p, s);
if (ret < 0)
{
PRINTF("bad src address\n");
return ret;
}
s -= ret;
p += ret;
ret = hdlc_get_control_type(&frame->control, p, s);
if (ret < 0)
{
PRINTF("bad control field\n");
return ret;
}
s -= ret;
p += ret;
if (s > 0)
{
hcs_index = p - frm + 2;
if (hcs_index >= length) {
hcs_index = 0;
frame->info_len = 0; // No info field
frame->info = 0;
}
else {
frame->info_len = s - (2 /* HCS */ + 2 /* FCS */); // Truncate two FCS bytes and two HCS bytes
frame->info = p + 2; // Skip two bytes of HCS (Header check sequence)
}
}
else
{
frame->info = 0;
frame->info_len = 0;
}
ret = hdlc_check_hcs_fcs(frm, length, hcs_index);
if (ret < 0)
{
PRINTF("FCS HCS check failed\n");
return ret;
}
return ret;
}
int hdlc_frame_encode_hdr(unsigned char *hdr, unsigned int hdr_len, struct hdlc_frame_t *frame)
{
int ret;
unsigned char *p, *pformat;
unsigned int length;
unsigned int frame_length;
p = hdr;
// Save format pointer as length will be known at the end of encoding process
//
pformat = p;
p += 2;
length = 2;
hdr_len -= 2;
if (hdr_len < 4)
return -1;
ret = hdlc_put_address_type(p, frame->dest_address);
if (ret < 0)
{
PRINTF("Fail to put dest address\n");
return ret;
}
length += ret;
p += ret;
hdr_len -= ret;
if (hdr_len < 4)
return -1;
ret = hdlc_put_address_type(p, frame->src_address);
if (ret < 0)
{
PRINTF("Fail to put src address\n");
return ret;
}
length += ret;
p += ret;
hdr_len -= ret;
if (hdr_len < 1)
return -1;
ret = hdlc_put_control_type(p, frame->control);
if (ret < 0)
return ret;
length += ret;
p += ret;
frame_length = length + 2;
if (frame->info_len > 0) {
frame_length += frame->info_len + 2;
}
ret = hdlc_put_format_type(pformat, frame->format, frame_length);
if (ret < 0)
return ret;
return (int)length;
}
unsigned int hdlc_frame_max_info_length(struct hdlc_frame_t *frame, unsigned int hdlc_frame_size)
{
unsigned int overhead = 0;
overhead += 1 /*Flag*/ + 2 /*Frame format*/ + 1 /*Control*/ + 2 /*HCS*/ + 2 /*FCS*/ + 1 /*Flag*/;
overhead += frame->dest_address.len;
overhead += frame->src_address.len;
return hdlc_frame_size - overhead;
}
| 2.109375 | 2 |
2024-11-18T20:48:54.238456+00:00 | 2019-08-07T01:16:48 | 0bd8233114f920f5779782c01b18cd7e8a8dcfb7 | {
"blob_id": "0bd8233114f920f5779782c01b18cd7e8a8dcfb7",
"branch_name": "refs/heads/master",
"committer_date": "2019-08-07T01:16:48",
"content_id": "4541ed67f278f24bf391c9614c045c566a6531b1",
"detected_licenses": [
"MIT"
],
"directory_id": "63a54bc72b5860fa51117334b80c4e8e027258dd",
"extension": "c",
"filename": "my_putchar.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": 425,
"license": "MIT",
"license_type": "permissive",
"path": "/CProjects/fractals/gwen/my_putchar.c",
"provenance": "stackv2-0102.json.gz:86085",
"repo_name": "Epitech-Strasbourg-CT/Epitech-Computer-Science-School-Projects",
"revision_date": "2019-08-07T01:16:48",
"revision_id": "43065b7230534a8ba08793dadbf99ce07ac9af3a",
"snapshot_id": "b90e12137b56902e2862f956844a64b85164e724",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Epitech-Strasbourg-CT/Epitech-Computer-Science-School-Projects/43065b7230534a8ba08793dadbf99ce07ac9af3a/CProjects/fractals/gwen/my_putchar.c",
"visit_date": "2022-02-11T21:59:20.801001"
} | stackv2 | /*
** my_putchar.c for my_putchar in /home/rodrig_1/fractals/gwen
**
** Made by gwendoline rodriguez
** Login <rodrig_1@epitech.net>
**
** Started on Tue Apr 28 11:40:38 2015 gwendoline rodriguez
** Last update Tue Apr 28 10:25:56 2015 Loik Fauré-Berlinguette
*/
void my_putchar(char c)
{
write(1, &c, 1);
}
void my_putstr(char *s)
{
int i;
i = 0;
while (s[i])
{
my_putchar(s[i]);
i++;
}
}
| 2.53125 | 3 |
2024-11-18T20:48:54.343303+00:00 | 2023-02-01T02:28:07 | 0c72f6bb704a667b59fe15182565377a4373e751 | {
"blob_id": "0c72f6bb704a667b59fe15182565377a4373e751",
"branch_name": "refs/heads/master",
"committer_date": "2023-02-01T02:28:07",
"content_id": "554ac6fbc5037c098a74e5a97b71e03d642fde1a",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "07bf9cf42b6de573861515451034cd0215deb0ba",
"extension": "c",
"filename": "espresso_expand.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 174751069,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 20303,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/Source/UtilsDevice/UtEspresso/espresso_expand.c",
"provenance": "stackv2-0102.json.gz:86216",
"repo_name": "keshbach/PEP",
"revision_date": "2023-02-01T02:28:07",
"revision_id": "bf9318c01c3549d267e6c53febd366e2427aea11",
"snapshot_id": "cd2441cd64cf27b1b0ebf952415a011369cee267",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/keshbach/PEP/bf9318c01c3549d267e6c53febd366e2427aea11/Source/UtilsDevice/UtEspresso/espresso_expand.c",
"visit_date": "2023-02-06T07:13:53.346329"
} | stackv2 | /***************************************************************************/
/* Copyright (c) 1988, 1989, Regents of the University of California. */
/* All rights reserved. */
/***************************************************************************/
#include "espresso_hdrs.h"
#include "espresso_defs.h"
#include "espresso_expand.h"
#include "espresso_cvrm.h"
#include "espresso_set.h"
#include "espresso_setc.h"
#include "espresso_sminterf.h"
/*
module: expand.c
purpose: Perform the Espresso-II Expansion Step
The idea is to take each nonprime cube of the on-set and expand it
into a prime implicant such that we can cover as many other cubes
of the on-set. If no cube of the on-set can be covered, then we
expand each cube into a large prime implicant by transforming the
problem into a minimum covering problem which is solved by the
heuristics of minimum_cover.
These routines revolve around having a representation of the
OFF-set. (In contrast to the Espresso-II manuscript, we do NOT
require an "unwrapped" version of the OFF-set).
Some conventions on variable names:
SUPER_CUBE is the supercube of all cubes which can be covered
by an expansion of the cube being expanded
OVEREXPANDED_CUBE is the cube which would result from expanding
all parts which can expand individually of the cube being expanded
RAISE is the current expansion of the current cube
FREESET is the set of parts which haven't been raised or lowered yet.
INIT_LOWER is a set of parts to be removed from the free parts before
starting the expansion
*/
/*
expand -- expand each nonprime cube of F into a prime implicant
If nonsparse is true, only the non-sparse variables will be expanded;
this is done by forcing all of the sparse variables out of the free set.
*/
TPCover expand(
TPCubeContext pCubeContext,
TPCover F,
const TPCover R,
TEspressoBool nonsparse) /* expand non-sparse variables only */
{
TPCubeSettings pCubeSettings = &pCubeContext->CubeSettings;
register TPCube last, p;
TPCube RAISE, FREESET, INIT_LOWER, SUPER_CUBE, OVEREXPANDED_CUBE;
TEspressoInt32 var, num_covered;
TEspressoBool change;
/* Order the cubes according to "chewing-away from the edges" of mini */
if (pCubeContext->use_random_order)
{
F = random_order(F);
}
else
{
F = mini_sort(pCubeContext, F, ascend);
}
/* Allocate memory for variables needed by expand1() */
RAISE = MNew_Cube(pCubeSettings);
FREESET = MNew_Cube(pCubeSettings);
INIT_LOWER = MNew_Cube(pCubeSettings);
SUPER_CUBE = MNew_Cube(pCubeSettings);
OVEREXPANDED_CUBE = MNew_Cube(pCubeSettings);
/* Setup the initial lowering set (differs only for nonsparse) */
if (nonsparse)
{
for(var = 0; var < pCubeSettings->nNum_Vars; var++)
{
if (pCubeSettings->pnSparse[var])
{
set_or(INIT_LOWER, INIT_LOWER, pCubeSettings->ppVar_Mask[var]);
}
}
}
/* Mark all cubes as not covered, and maybe essential */
MForeach_Set(F, last, p)
{
MReset(p, CEspressoCovered);
MReset(p, CEspressoNoneEssen);
}
/* Try to expand each nonprime and noncovered cube */
MForeach_Set(F, last, p)
{
/* do not expand if PRIME or if covered by previous expansion */
if (! MTestP(p, CEspressoPrime) && ! MTestP(p, CEspressoCovered))
{
/* expand the cube p, result is RAISE */
expand1(pCubeContext, R, F, RAISE, FREESET, OVEREXPANDED_CUBE, SUPER_CUBE,
INIT_LOWER, &num_covered, p);
set_copy(p, RAISE);
MSet(p, CEspressoPrime);
MReset(p, CEspressoCovered); /* not really necessary */
/* See if we generated an inessential prime */
if (num_covered == 0 && ! setp_equal(p, OVEREXPANDED_CUBE))
{
MSet(p, CEspressoNoneEssen);
}
}
}
/* Delete any cubes of F which became covered during the expansion */
F->nActive_Count = 0;
change = CEspressoFalse;
MForeach_Set(F, last, p)
{
if (MTestP(p, CEspressoCovered))
{
MReset(p, CEspressoActive);
change = CEspressoTrue;
}
else
{
MSet(p, CEspressoActive);
F->nActive_Count++;
}
}
if (change)
{
F = sf_inactive(F);
}
MFree_Cube(RAISE);
MFree_Cube(FREESET);
MFree_Cube(INIT_LOWER);
MFree_Cube(SUPER_CUBE);
MFree_Cube(OVEREXPANDED_CUBE);
return F;
}
/*
expand1 -- Expand a single cube against the OFF-set
*/
void expand1(
TPCubeContext pCubeContext,
TPCover BB, /* Blocking matrix (OFF-set) */
TPCover CC, /* Covering matrix (ON-set) */
TPCube RAISE, /* The current parts which have been raised */
TPCube FREESET, /* The current parts which are free */
TPCube OVEREXPANDED_CUBE, /* Overexpanded cube of c */
TPCube SUPER_CUBE, /* Supercube of all cubes of CC we cover */
TPCube INIT_LOWER, /* Parts to initially remove from FREESET */
TEspressoInt32 *num_covered, /* Number of cubes of CC which are covered */
TPCube c) /* The cube to be expanded */
{
TPCubeSettings pCubeSettings = &pCubeContext->CubeSettings;
TEspressoInt32 bestindex;
/* initialize BB and CC */
MSet(c, CEspressoPrime); /* don't try to cover ourself */
setup_BB_CC(BB, CC);
/* initialize count of # cubes covered, and the supercube of them */
*num_covered = 0;
set_copy(SUPER_CUBE, c);
/* Initialize the lowering, raising and unassigned sets */
set_copy(RAISE, c);
set_diff(FREESET, pCubeSettings->pFullSet, RAISE);
/* If some parts are forced into lowering set, remove them */
if (! setp_empty(INIT_LOWER))
{
set_diff(FREESET, FREESET, INIT_LOWER);
elim_lowering(pCubeContext, BB, CC, RAISE, FREESET);
}
/* Determine what can be raised, and return the over-expanded cube */
essen_parts(pCubeContext, BB, CC, RAISE, FREESET);
set_or(OVEREXPANDED_CUBE, RAISE, FREESET);
/* While there are still cubes which can be covered, cover them ! */
if (CC->nActive_Count > 0)
{
select_feasible(pCubeContext, BB, CC, RAISE, FREESET, SUPER_CUBE, num_covered);
}
/* While there are still cubes covered by the overexpanded cube ... */
while (CC->nActive_Count > 0)
{
bestindex = most_frequent(pCubeContext, CC, FREESET);
MSet_Insert(RAISE, bestindex);
MSet_Remove(FREESET, bestindex);
essen_parts(pCubeContext, BB, CC, RAISE, FREESET);
}
/* Finally, when all else fails, choose the largest possible prime */
/* We will loop only if we decide unravelling OFF-set is too expensive */
while (BB->nActive_Count > 0)
{
mincov(pCubeContext, BB, RAISE, FREESET);
}
/* Raise any remaining free coordinates */
set_or(RAISE, RAISE, FREESET);
}
/*
most_frequent -- When all else fails, select a reasonable part to raise
The active cubes of CC are the cubes which are covered by the
overexpanded cube of the original cube (however, we know that none
of them can actually be covered by a feasible expansion of the
original cube). We resort to the MINI strategy of selecting to
raise the part which will cover the same part in the most cubes of CC.
*/
TEspressoInt32 most_frequent(
TPCubeContext pCubeContext,
TPCover CC,
TPCube FREESET)
{
TPCubeSettings pCubeSettings = &pCubeContext->CubeSettings;
register TEspressoInt32 i, best_part, best_count, *count;
register TPSet p, last;
/* Count occurences of each variable */
count = (TEspressoInt32*)UtAllocMem(sizeof(TEspressoInt32) * pCubeSettings->nSize);
for(i = 0; i < pCubeSettings->nSize; i++)
{
count[i] = 0;
}
if (CC != NULL)
MForeach_Active_Set(CC, last, p)
set_adjcnt(p, count, 1);
/* Now find which free part occurs most often */
best_count = best_part = -1;
for (i = 0; i < pCubeSettings->nSize; i++)
{
if (MIs_In_Set(FREESET,i) && count[i] > best_count)
{
best_part = i;
best_count = count[i];
}
}
if (count)
{
UtFreeMem(count);
count = NULL;
}
return best_part;
}
/*
setup_BB_CC -- set up the blocking and covering set families;
Note that the blocking family is merely the set of cubes of R, and
that CC is the set of cubes of F which might possibly be covered
(i.e., nonprime cubes, and cubes not already covered)
*/
void setup_BB_CC(
register TPCover BB,
register TPCover CC)
{
register TPCube p, last;
/* Create the block and cover set families */
BB->nActive_Count = BB->nCount;
MForeach_Set(BB, last, p)
MSet(p, CEspressoActive);
if (CC != NULL)
{
CC->nActive_Count = CC->nCount;
MForeach_Set(CC, last, p)
{
if (MTestP(p, CEspressoCovered) || MTestP(p, CEspressoPrime))
{
CC->nActive_Count--, MReset(p, CEspressoActive);
}
else
{
MSet(p, CEspressoActive);
}
}
}
}
/*
select_feasible -- Determine if there are cubes which can be covered,
and if so, raise those parts necessary to cover as many as possible.
We really don't check to maximize the number that can be covered;
instead, we check, for each fcc, how many other fcc remain fcc
after expanding to cover the fcc. (Essentially one-level lookahead).
*/
void select_feasible(
TPCubeContext pCubeContext,
TPCover BB,
TPCover CC,
TPCube RAISE,
TPCube FREESET,
TPCube SUPER_CUBE,
TEspressoInt32 *num_covered)
{
TPCubeSettings pCubeSettings = &pCubeContext->CubeSettings;
register TPCube p, last, bestfeas, *feas;
register TEspressoInt32 i, j;
TPCube *feas_new_lower;
TEspressoInt32 bestcount, bestsize, count, size, numfeas, lastfeas;
TPCover new_lower;
bestfeas = NULL;
/* Start out with all cubes covered by the over-expanded cube as
* the "possibly" feasibly-covered cubes (pfcc)
*/
feas = (TPCube*)UtAllocMem(sizeof(TPCube) * CC->nActive_Count);
numfeas = 0;
MForeach_Active_Set(CC, last, p)
feas[numfeas++] = p;
/* Setup extra cubes to record parts forced low after a covering */
feas_new_lower = (TPCube*)UtAllocMem(sizeof(TPCube) * CC->nActive_Count);
new_lower = MNew_Cover(pCubeContext, numfeas, pCubeSettings);
for(i = 0; i < numfeas; i++)
{
feas_new_lower[i] = MGetSet(new_lower, i);
}
loop:
/* Find the essentially raised parts -- this might cover some cubes
for us, without having to find out if they are fcc or not
*/
essen_raising(pCubeContext, BB, RAISE, FREESET);
/* Now check all "possibly" feasibly covered cubes to check feasibility */
lastfeas = numfeas;
numfeas = 0;
for(i = 0; i < lastfeas; i++)
{
p = feas[i];
/* Check active because essen_parts might have removed it */
if (MTestP(p, CEspressoActive))
{
/* See if the cube is already covered by RAISE --
* this can happen because of essen_raising() or because of
* the previous "loop"
*/
if (setp_implies(p, RAISE))
{
(*num_covered) += 1;
set_or(SUPER_CUBE, SUPER_CUBE, p);
CC->nActive_Count--;
MReset(p, CEspressoActive);
MSet(p, CEspressoCovered);
/* otherwise, test if it is feasibly covered */
}
else if (feasibly_covered(pCubeContext, BB,p,RAISE,feas_new_lower[numfeas]))
{
feas[numfeas] = p; /* save the fcc */
numfeas++;
}
}
}
/* Exit here if there are no feasibly covered cubes */
if (numfeas == 0)
{
if (feas)
{
UtFreeMem(feas);
feas = NULL;
}
if (feas_new_lower)
{
UtFreeMem(feas_new_lower);
feas_new_lower = NULL;
}
MFree_Cover(pCubeContext, new_lower);
return;
}
/* Now find which is the best feasibly covered cube */
bestcount = 0;
bestsize = 9999;
for(i = 0; i < numfeas; i++)
{
size = set_dist(pCubeContext, feas[i], FREESET); /* # of newly raised parts */
count = 0; /* # of other cubes which remain fcc after raising */
#define NEW
#ifdef NEW
for(j = 0; j < numfeas; j++)
if (setp_disjoint(feas_new_lower[i], feas[j]))
count++;
#else
for(j = 0; j < numfeas; j++)
if (setp_implies(feas[j], feas[i]))
count++;
#endif
if (count > bestcount)
{
bestcount = count;
bestfeas = feas[i];
bestsize = size;
}
else if (count == bestcount && size < bestsize)
{
bestfeas = feas[i];
bestsize = size;
}
}
/* Add the necessary parts to the raising set */
set_or(RAISE, RAISE, bestfeas);
set_diff(FREESET, FREESET, RAISE);
essen_parts(pCubeContext, BB, CC, RAISE, FREESET);
goto loop;
/* NOTREACHED */
}
/*
elim_lowering -- after removing parts from FREESET, we can reduce the
size of both BB and CC.
We mark as inactive any cube of BB which does not intersect the
overexpanded cube (i.e., RAISE + FREESET). Likewise, we remove
from CC any cube which is not covered by the overexpanded cube.
*/
void elim_lowering(
TPCubeContext pCubeContext,
TPCover BB,
TPCover CC,
TPCube RAISE,
TPCube FREESET)
{
TPCubeSettings pCubeSettings = &pCubeContext->CubeSettings;
register TPCube p, r = set_or(pCubeSettings->ppTemp[0], RAISE, FREESET);
TPCube last;
/*
* Remove sets of BB which are orthogonal to future expansions
*/
MForeach_Active_Set(BB, last, p)
{
if (! cdist0(pCubeContext, p, r))
{
BB->nActive_Count--, MReset(p, CEspressoActive);
}
}
/*
* Remove sets of CC which cannot be covered by future expansions
*/
if (CC != NULL)
{
MForeach_Active_Set(CC, last, p)
{
if (! setp_implies(p, r))
CC->nActive_Count--, MReset(p, CEspressoActive);
}
}
}
/*
essen_parts -- determine which parts are forced into the lowering
set to insure that the cube be orthognal to the OFF-set.
If any cube of the OFF-set is distance 1 from the raising cube,
then we must lower all parts of the conflicting variable. (If the
cube is distance 0, we detect this error here.)
If there are essentially lowered parts, we can remove from consideration
any cubes of the OFF-set which are more than distance 1 from the
overexpanded cube of RAISE.
*/
void essen_parts(
TPCubeContext pCubeContext,
TPCover BB,
TPCover CC,
TPCube RAISE,
TPCube FREESET)
{
TPCubeSettings pCubeSettings = &pCubeContext->CubeSettings;
register TPCube p, r = RAISE;
TPCube lastp, xlower = pCubeSettings->ppTemp[0];
TEspressoInt32 dist;
set_copy(xlower, pCubeSettings->pEmptySet);
MForeach_Active_Set(BB, lastp, p)
{
if ((dist = cdist01(pCubeContext, p, r)) > 1)
goto exit_if;
if (dist == 0)
{
assert(0);
//fatal("ON-set and OFF-set are not orthogonal");
}
else
{
force_lower(pCubeContext, xlower, p, r);
BB->nActive_Count--;
MReset(p, CEspressoActive);
}
exit_if: ;
}
if (! setp_empty(xlower))
{
set_diff(FREESET, FREESET, xlower);/* remove from free set */
elim_lowering(pCubeContext, BB, CC, RAISE, FREESET);
}
}
/*
essen_raising -- determine which parts may always be added to
the raising set without restricting further expansions
General rule: if some part is not blocked by any cube of BB, then
this part can always be raised.
*/
void essen_raising(
TPCubeContext pCubeContext,
register TPCover BB,
TPCube RAISE,
TPCube FREESET)
{
TPCubeSettings pCubeSettings = &pCubeContext->CubeSettings;
register TPCube last, p, xraise = pCubeSettings->ppTemp[0];
/* Form union of all cubes of BB, and then take complement wrt FREESET */
set_copy(xraise, pCubeSettings->pEmptySet);
MForeach_Active_Set(BB, last, p)
MInlineSet_Or(xraise, xraise, p);
set_diff(xraise, FREESET, xraise);
set_or(RAISE, RAISE, xraise); /* add to raising set */
set_diff(FREESET, FREESET, xraise); /* remove from free set */
}
/*
mincov -- transform the problem of expanding a cube to a maximally-
large prime implicant into the problem of selecting a minimum
cardinality cover over a family of sets.
When we get to this point, we must unravel the remaining off-set.
This may be painful.
*/
void mincov(
TPCubeContext pCubeContext,
TPCover BB,
TPCube RAISE,
TPCube FREESET)
{
TPCubeSettings pCubeSettings = &pCubeContext->CubeSettings;
TEspressoInt32 expansion, nset, var, dist;
TPSet_Family B;
register TPCube xraise=pCubeSettings->ppTemp[0], xlower, p, last, plower;
#ifdef RANDOM_MINCOV
dist = random() % set_ord(FREESET);
for(var = 0; var < cubesize && dist >= 0; var++)
{
if (is_in_set(FREESET, var))
{
dist--;
}
}
set_insert(RAISE, var);
set_remove(FREESET, var);
essen_parts(BB, /*CC*/ NULL, RAISE, FREESET);
#else
/* Create B which are those cubes which we must avoid intersecting */
B = MNew_Cover(pCubeContext, BB->nActive_Count, pCubeSettings);
MForeach_Active_Set(BB, last, p)
{
plower = set_copy(MGetSet(B, B->nCount++), pCubeSettings->pEmptySet);
force_lower(pCubeContext, plower, p, RAISE);
}
/* Determine how many sets it will blow up into after the unravel */
nset = 0;
MForeach_Set(B, last, p)
{
expansion = 1;
for(var = pCubeSettings->nNum_Binary_Vars; var < pCubeSettings->nNum_Vars; var++)
{
if ((dist=set_dist(pCubeContext, p, pCubeSettings->ppVar_Mask[var])) > 1)
{
expansion *= dist;
if (expansion > 500)
{
goto heuristic_mincov;
}
}
}
nset += expansion;
if (nset > 500)
{
goto heuristic_mincov;
}
}
B = unravel(pCubeContext, B, pCubeSettings->nNum_Binary_Vars);
xlower = do_sm_minimum_cover(B);
/* Add any remaining free parts to the raising set */
set_or(RAISE, RAISE, set_diff(xraise, FREESET, xlower));
set_copy(FREESET, pCubeSettings->pEmptySet); /* free set is empty */
BB->nActive_Count = 0; /* BB satisfied */
sf_free(pCubeContext, B);
MSet_Free(xlower);
return;
heuristic_mincov:
sf_free(pCubeContext, B);
/* most_frequent will pick first free part */
MSet_Insert(RAISE, most_frequent(pCubeContext, /*CC*/ NULL, FREESET));
set_diff(FREESET, FREESET, RAISE);
essen_parts(pCubeContext, BB, /*CC*/ NULL, RAISE, FREESET);
return;
#endif
}
/*
feasibly_covered -- determine if the cube c is feasibly covered
(i.e., if it is possible to raise all of the necessary variables
while still insuring orthogonality with R). Also, if c is feasibly
covered, then compute the new set of parts which are forced into
the lowering set.
*/
TEspressoBool feasibly_covered(
TPCubeContext pCubeContext,
TPCover BB,
TPCube c,
TPCube RAISE,
TPCube new_lower)
{
TPCubeSettings pCubeSettings = &pCubeContext->CubeSettings;
register TPCube p, r = set_or(pCubeSettings->ppTemp[0], RAISE, c);
TEspressoInt32 dist;
TPCube lastp;
set_copy(new_lower, pCubeSettings->pEmptySet);
MForeach_Active_Set(BB, lastp, p)
{
if ((dist = cdist01(pCubeContext, p, r)) > 1)
goto exit_if;
if (dist == 0)
{
return CEspressoFalse;
}
else
{
force_lower(pCubeContext, new_lower, p, r);
}
exit_if: ;
}
return CEspressoTrue;
}
/***************************************************************************/
/* Copyright (c) 1988, 1989, Regents of the University of California. */
/* All rights reserved. */
/***************************************************************************/
| 2.015625 | 2 |
2024-11-18T20:48:54.779624+00:00 | 2022-08-14T07:18:35 | 591eea2ef5632b6c55fdcc6232e30cd88a771a8b | {
"blob_id": "591eea2ef5632b6c55fdcc6232e30cd88a771a8b",
"branch_name": "refs/heads/main",
"committer_date": "2022-08-14T07:18:35",
"content_id": "aef8d5ce993d9fb8ae9c54c18a0ea515549911e0",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "8c9eba1dee9fb8d03a739e8ba262469ffa197c86",
"extension": "c",
"filename": "ch32v307-flash.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 494374182,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 14199,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/software/boards/demi1-ch32/ch32v307-flash.c",
"provenance": "stackv2-0102.json.gz:86990",
"repo_name": "AwesomeAudioApparatus/demiurge",
"revision_date": "2022-08-14T07:18:35",
"revision_id": "53f88d4c14fa36695eea6680b53b2ed5ade8abb5",
"snapshot_id": "efd9e20911f66617c669aa591ea71c8e19b0d6bb",
"src_encoding": "UTF-8",
"star_events_count": 4,
"url": "https://raw.githubusercontent.com/AwesomeAudioApparatus/demiurge/53f88d4c14fa36695eea6680b53b2ed5ade8abb5/software/boards/demi1-ch32/ch32v307-flash.c",
"visit_date": "2023-02-20T01:02:57.108719"
} | stackv2 | /*
Copyright 2019, Awesome Audio Apparatus.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "ch32v30x.h"
#include "lfs.h"
#include "demiurge-spi.h"
#define SECTOR_SIZE 256
#define NUMBER_OF_SECTORS 65536
/* Winbond SPIFalsh ID */
#define W25Q80 0XEF13
#define W25Q16 0XEF14
#define W25Q32 0XEF15
#define W25Q64 0XEF16
#define W25Q128 0XEF17
/* Winbond SPIFlash Instruction List */
#define W25X_WriteEnable 0x06
#define W25X_WriteDisable 0x04
#define W25X_ReadStatusReg 0x05
#define W25X_WriteStatusReg 0x01
#define W25X_ReadData 0x03
#define W25X_FastReadData 0x0B
#define W25X_FastReadDual 0x3B
#define W25X_PageProgram 0x02
#define W25X_BlockErase 0xD8
#define W25X_SectorErase 0x20
#define W25X_ChipErase 0xC7
#define W25X_PowerDown 0xB9
#define W25X_ReleasePowerDown 0xAB
#define W25X_DeviceID 0xAB
#define W25X_ManufactDeviceID 0x90
#define W25X_JedecDeviceID 0x9F
uint8_t SPI_FLASH_BUF[4096];
static inline void enable_flash() {
GPIO_WriteBit(GPIOB, GPIO_Pin_12, Bit_RESET);
}
static inline void disable_flash() {
GPIO_WriteBit(GPIOB, GPIO_Pin_12, Bit_SET);
}
/*********************************************************************
* @fn SPI2_ReadWriteByte
*
* @brief SPI2 read or write one byte.
*
* @param TxData - write one byte data.
*
* @return Read one byte data.
*/
uint8_t SPI2_ReadWriteByte(uint8_t TxData)
{
uint8_t i = 0;
while(SPI_I2S_GetFlagStatus(SPI2, SPI_I2S_FLAG_TXE) == RESET)
{
i++;
if(i > 2000)
return 0;
}
SPI_I2S_SendData(SPI2, TxData);
i = 0;
while(SPI_I2S_GetFlagStatus(SPI2, SPI_I2S_FLAG_RXNE) == RESET)
{
i++;
if(i > 2000)
return 0;
}
return SPI_I2S_ReceiveData(SPI2);
}
/*********************************************************************
* @fn SPI_Flash_ReadSR
*
* @brief Read W25Qxx status register.
* ����BIT7 6 5 4 3 2 1 0
* ����SPR RV TB BP2 BP1 BP0 WEL BUSY
*
* @return byte - status register value.
*/
uint8_t SPI_Flash_ReadSR(void)
{
uint8_t byte = 0;
enable_flash();
SPI2_ReadWriteByte(W25X_ReadStatusReg);
byte = SPI2_ReadWriteByte(0Xff);
disable_flash();
return byte;
}
/*********************************************************************
* @fn SPI_FLASH_Write_SR
*
* @brief Write W25Qxx status register.
*
* @param sr - status register value.
*
* @return none
*/
void SPI_FLASH_Write_SR(uint8_t sr)
{
enable_flash();
SPI2_ReadWriteByte(W25X_WriteStatusReg);
SPI2_ReadWriteByte(sr);
disable_flash();
}
/*********************************************************************
* @fn SPI_Flash_Wait_Busy
*
* @brief Wait flash free.
*
* @return none
*/
void SPI_Flash_Wait_Busy(void)
{
while((SPI_Flash_ReadSR() & 0x01) == 0x01)
;
}
/*********************************************************************
* @fn SPI_FLASH_Write_Enable
*
* @brief Enable flash write.
*
* @return none
*/
void SPI_FLASH_Write_Enable(void)
{
enable_flash();
SPI2_ReadWriteByte(W25X_WriteEnable);
disable_flash();
}
/*********************************************************************
* @fn SPI_FLASH_Write_Disable
*
* @brief Disable flash write.
*
* @return none
*/
void SPI_FLASH_Write_Disable(void)
{
enable_flash();
SPI2_ReadWriteByte(W25X_WriteDisable);
disable_flash();
}
/*********************************************************************
* @fn SPI_Flash_ReadID
*
* @brief Read flash ID.
*
* @return Temp - FLASH ID.
*/
uint16_t SPI_Flash_ReadID(void)
{
uint16_t Temp = 0;
enable_flash();
SPI2_ReadWriteByte(W25X_ManufactDeviceID);
SPI2_ReadWriteByte(0x00);
SPI2_ReadWriteByte(0x00);
SPI2_ReadWriteByte(0x00);
Temp |= SPI2_ReadWriteByte(0xFF) << 8;
Temp |= SPI2_ReadWriteByte(0xFF);
disable_flash();
return Temp;
}
/*********************************************************************
* @fn SPI_Flash_Erase_Sector
*
* @brief Erase one sector(4Kbyte).
*
* @param Dst_Addr - 0 ���� 2047
*
* @return none
*/
void SPI_Flash_Erase_Sector(uint32_t Dst_Addr)
{
Dst_Addr *= 4096;
SPI_FLASH_Write_Enable();
SPI_Flash_Wait_Busy();
enable_flash();
SPI2_ReadWriteByte(W25X_SectorErase);
SPI2_ReadWriteByte((uint8_t)((Dst_Addr) >> 16));
SPI2_ReadWriteByte((uint8_t)((Dst_Addr) >> 8));
SPI2_ReadWriteByte((uint8_t)Dst_Addr);
disable_flash();
SPI_Flash_Wait_Busy();
}
/*********************************************************************
* @fn SPI_Flash_Read
*
* @brief Read data from flash.
*
* @param pBuffer -
* ReadAddr -Initial address(24bit).
* size - Data length.
*
* @return none
*/
void SPI_Flash_Read(uint8_t *pBuffer, uint32_t ReadAddr, uint16_t size)
{
uint16_t i;
enable_flash();
SPI2_ReadWriteByte(W25X_ReadData);
SPI2_ReadWriteByte((uint8_t)((ReadAddr) >> 16));
SPI2_ReadWriteByte((uint8_t)((ReadAddr) >> 8));
SPI2_ReadWriteByte((uint8_t)ReadAddr);
for(i = 0; i < size; i++)
{
pBuffer[i] = SPI2_ReadWriteByte(0XFF);
}
disable_flash();
}
/*********************************************************************
* @fn SPI_Flash_Write_Page
*
* @brief Write data by one page.
*
* @param pBuffer -
* WriteAddr - Initial address(24bit).
* size - Data length.
*
* @return none
*/
void SPI_Flash_Write_Page(uint8_t *pBuffer, uint32_t WriteAddr, uint16_t size)
{
uint16_t i;
SPI_FLASH_Write_Enable();
enable_flash();
SPI2_ReadWriteByte(W25X_PageProgram);
SPI2_ReadWriteByte((uint8_t)((WriteAddr) >> 16));
SPI2_ReadWriteByte((uint8_t)((WriteAddr) >> 8));
SPI2_ReadWriteByte((uint8_t)WriteAddr);
for(i = 0; i < size; i++)
{
SPI2_ReadWriteByte(pBuffer[i]);
}
disable_flash();
SPI_Flash_Wait_Busy();
}
/*********************************************************************
* @fn SPI_Flash_Write_NoCheck
*
* @brief Write data to flash.(need Erase)
* All data in address rang is 0xFF.
*
* @param pBuffer -
* WriteAddr - Initial address(24bit).
* size - Data length.
*
* @return none
*/
void SPI_Flash_Write_NoCheck(uint8_t *pBuffer, uint32_t WriteAddr, uint16_t size)
{
uint16_t pageremain;
pageremain = 256 - WriteAddr % 256;
if(size <= pageremain)
pageremain = size;
while(1)
{
SPI_Flash_Write_Page(pBuffer, WriteAddr, pageremain);
if(size == pageremain)
{
break;
}
else
{
pBuffer += pageremain;
WriteAddr += pageremain;
size -= pageremain;
if(size > 256)
pageremain = 256;
else
pageremain = size;
}
}
}
/*********************************************************************
* @fn SPI_Flash_Write
*
* @brief Write data to flash.(no need Erase)
*
* @param pBuffer -
* WriteAddr - Initial address(24bit).
* size - Data length.
*
* @return none
*/
void SPI_Flash_Write(uint8_t *pBuffer, uint32_t WriteAddr, uint16_t size)
{
uint32_t secpos;
uint16_t secoff;
uint16_t secremain;
uint16_t i;
secpos = WriteAddr / 4096;
secoff = WriteAddr % 4096;
secremain = 4096 - secoff;
if(size <= secremain)
secremain = size;
while(1)
{
SPI_Flash_Read(SPI_FLASH_BUF, secpos * 4096, 4096);
for(i = 0; i < secremain; i++)
{
if(SPI_FLASH_BUF[secoff + i] != 0XFF)
break;
}
if(i < secremain)
{
SPI_Flash_Erase_Sector(secpos);
for(i = 0; i < secremain; i++)
{
SPI_FLASH_BUF[i + secoff] = pBuffer[i];
}
SPI_Flash_Write_NoCheck(SPI_FLASH_BUF, secpos * 4096, 4096);
}
else
{
SPI_Flash_Write_NoCheck(pBuffer, WriteAddr, secremain);
}
if(size == secremain)
{
break;
}
else
{
secpos++;
secoff = 0;
pBuffer += secremain;
WriteAddr += secremain;
size -= secremain;
if(size > 4096)
{
secremain = 4096;
}
else
{
secremain = size;
}
}
}
}
/*********************************************************************
* @fn SPI_Flash_Erase_Chip
*
* @brief Erase all FLASH pages.
*
* @return none
*/
void SPI_Flash_Erase_Chip(void)
{
SPI_FLASH_Write_Enable();
SPI_Flash_Wait_Busy();
enable_flash();
SPI2_ReadWriteByte(W25X_ChipErase);
disable_flash();
SPI_Flash_Wait_Busy();
}
/*********************************************************************
* @fn SPI_Flash_PowerDown
*
* @brief Enter power down mode.
*
* @return none
*/
void SPI_Flash_PowerDown(void)
{
enable_flash();
SPI2_ReadWriteByte(W25X_PowerDown);
disable_flash();
Delay_Us(3);
}
/*********************************************************************
* @fn SPI_Flash_WAKEUP
*
* @brief Power down wake up.
*
* @return none
*/
void SPI_Flash_WAKEUP(void)
{
enable_flash();
SPI2_ReadWriteByte(W25X_ReleasePowerDown);
disable_flash();
Delay_Us(3);
}
int littlefs_read(const struct lfs_config *c, lfs_block_t block, lfs_off_t off, void *buffer, lfs_size_t size)
{
printf("Read %d bytes to block %d at %d\n", size, block, off);
uint32_t readAddr = block * SECTOR_SIZE + off;
SPI_Flash_Read(buffer, readAddr, size);
return 0;
}
int littlefs_prog(const struct lfs_config *c, lfs_block_t block, lfs_off_t off, const void *buffer, lfs_size_t size)
{
printf("Write %d bytes to block %d at %d\n", size, block, off);
uint32_t writeAddr = block * SECTOR_SIZE + off;
SPI_Flash_Write(buffer, writeAddr, size);
return 0;
}
int littlefs_erase(const struct lfs_config *c, lfs_block_t block)
{
printf("Erase block %d\n", block );
SPI_Flash_Erase_Sector(block);
return 0;
}
int littlefs_sync(const struct lfs_config *c)
{
return 0;
}
struct lfs_config demiurge_flash_fs_config = {
// block device operations
.read = littlefs_read,
.prog = littlefs_prog,
.erase = littlefs_erase,
.sync = littlefs_sync,
// block device configuration
.read_size = 256,
.prog_size = 256,
.block_size = 4096,
.block_count = 4096,
.cache_size = 4096,
.lookahead_size = 256,
.block_cycles = 100,
};
lfs_t demiurge_flash_fs;
void init_flash()
{
Delay_Init();
printf("Initializing flash disk...\n");
RCC_APB1PeriphClockCmd(RCC_APB1Periph_SPI2, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC, ENABLE);
GPIO_InitTypeDef GPIO_InitStructure = {0};
// HOLD and WP pins
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0;
GPIO_Init(GPIOC, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_1;
GPIO_Init(GPIOC, &GPIO_InitStructure);
GPIO_SetBits(GPIOC, GPIO_Pin_0);
GPIO_SetBits(GPIOC, GPIO_Pin_1);
// SPI2 CS
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_12;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOB, &GPIO_InitStructure);
GPIO_SetBits(GPIOB, GPIO_Pin_12);
// SPI2 SCK
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_13;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOB, &GPIO_InitStructure);
// SPI2 MISO
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_14;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init(GPIOB, &GPIO_InitStructure);
// SPI2 MOSI
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_15;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOB, &GPIO_InitStructure);
SPI_InitTypeDef SPI_InitStructure = {0};
SPI_InitStructure.SPI_Direction = SPI_Direction_2Lines_FullDuplex;
SPI_InitStructure.SPI_Mode = SPI_Mode_Master;
SPI_InitStructure.SPI_DataSize = SPI_DataSize_8b;
SPI_InitStructure.SPI_CPOL = SPI_CPOL_High;
SPI_InitStructure.SPI_CPHA = SPI_CPHA_2Edge;
SPI_InitStructure.SPI_NSS = SPI_NSS_Soft;
SPI_InitStructure.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_8;
SPI_InitStructure.SPI_FirstBit = SPI_FirstBit_MSB;
SPI_InitStructure.SPI_CRCPolynomial = 7;
SPI_Init(SPI2, &SPI_InitStructure);
SPI_Cmd(SPI2, ENABLE);
printf("Waiting for flash chip...");
Delay_Ms(10);
SPI_Flash_Wait_Busy();
printf("ready\n");
Delay_Ms(10);
uint16_t model = SPI_Flash_ReadID();
printf("Model: %d\n", model);
Delay_Ms(10);
int err = lfs_mount(&demiurge_flash_fs, &demiurge_flash_fs_config);
Delay_Ms(10);
// reformat if we can't mount the filesystem
// this should only happen on the first boot
if (err) {
printf("Formatting flash disk...");
lfs_format(&demiurge_flash_fs, &demiurge_flash_fs_config);
lfs_mount(&demiurge_flash_fs, &demiurge_flash_fs_config);
printf("Done!\n");
}
printf("Flash disk initialized.\n");
}
void start_flash()
{
}
void stop_flash()
{
}
| 2.046875 | 2 |
2024-11-18T20:48:54.917416+00:00 | 2018-03-22T02:13:11 | d07fbce4cbbb2febd8f530446683e970ac74c0cd | {
"blob_id": "d07fbce4cbbb2febd8f530446683e970ac74c0cd",
"branch_name": "refs/heads/master",
"committer_date": "2018-03-22T02:13:11",
"content_id": "a96b6f30b759459917b89c94f16834300ec3f849",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "fa4deb7f4cbfc8083fbacd5ccdd5137850a76fe3",
"extension": "c",
"filename": "spi_Z4_1.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": 3953,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/spi/spi_Z4_1/src/spi_Z4_1.c",
"provenance": "stackv2-0102.json.gz:87118",
"repo_name": "cooper1025/mpc5748G_examples",
"revision_date": "2018-03-22T02:13:11",
"revision_id": "6ba2fd8cfa312d59036284e368a3cca2aba7df4b",
"snapshot_id": "493b77a4990c8b6bb1e1e40f37af10c7fab2b258",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/cooper1025/mpc5748G_examples/6ba2fd8cfa312d59036284e368a3cca2aba7df4b/spi/spi_Z4_1/src/spi_Z4_1.c",
"visit_date": "2020-09-08T01:44:30.432641"
} | stackv2 | /*****************************************************************************/
/* FILE NAME: spi_Z4_1.c COPYRIGHT (c) NXP Semiconductors 2016 */
/* All Rights Reserved */
/* PLATFORM: DEVKIT-MPC5748G */
/* DESCRIPTION: Main C program for core 0 (e200z4a) to call SPI functions */
/* Configures DSPI_3 in Master mode and SPI_0 in slave mode. */
/* Master continuously sends data to Slave and Slave replies */
/* to master. */
/* */
/* DSPI_3 Pin Mapping: SPI_0 Pin Mapping */
/* CLK PG4 J4_2 CLK PF7 J13_12 */
/* SOUT PG2 J4_1 SOUT PG12 J14_3 */
/* SIN PG5 J4_4 SIN PI14 J14_13 */
/* SS/CS0 PG3 J4_3 SS/CS0 PI15 J14_15 */
/*****************************************************************************/
/* REV AUTHOR DATE DESCRIPTION OF CHANGE */
/* --- ----------- ---------- --------------------- */
/* 1.0 Scott Obrien 21 Apr 2015 Initial Version */
/* 1.1 K Shah 16 Mar 2016 Ported to S32DS */
/*****************************************************************************/
#include "derivative.h" /* include peripheral declarations */
#include "project.h"
#include "spi.h"
#include "mode.h"
#define KEY_VALUE1 0x5AF0ul
#define KEY_VALUE2 0xA50Ful
extern void xcptn_xmpl(void);
void peri_clock_gating (void); /* Configures gating/enabling peripheral(DSPI, SPI) clocks */
void hw_init(void)
{
#if defined(DEBUG_SECONDARY_CORES)
uint32_t mctl = MC_ME.MCTL.R;
#if defined(TURN_ON_CPU1)
/* enable core 1 in all modes */
MC_ME.CCTL[2].R = 0x00FE;
/* Set Start address for core 1: Will reset and start */
MC_ME.CADDR[2].R = 0x11d0000 | 0x1;
#endif
#if defined(TURN_ON_CPU2)
/* enable core 2 in all modes */
MC_ME.CCTL[3].R = 0x00FE;
/* Set Start address for core 2: Will reset and start */
MC_ME.CADDR[3].R = 0x13a0000 | 0x1;
#endif
MC_ME.MCTL.R = (mctl & 0xffff0000ul) | KEY_VALUE1;
MC_ME.MCTL.R = mctl; /* key value 2 always from MCTL */
#endif /* defined(DEBUG_SECONDARY_CORES) */
}
__attribute__ ((section(".text")))
/************************************ Main ***********************************/
int main(void)
{
unsigned int i = 0;
xcptn_xmpl (); /* Configure and Enable Interrupts */
peri_clock_gating(); /* Configures gating/enabling peripheral(DSPI, SPI) clocks for modes*/
/* Configuration occurs after mode transition */
system160mhz(); /* sysclk=160MHz, dividers configured, mode trans*/
init_DSPI_3(); /* Initialize DSPI_3 as master SPI and initialize CTAR0 */
init_SPI_0(); /* Initialize SPI_0 as Slave SPI and initialize CTAR0 */
init_spi_ports(); /* DSPI3 Master, SPI_0 Slave */
while( 1 )
{
SPI_0.PUSHR.PUSHR.R = 0x00001234; /* Initialize slave SPI_0's response to master */
DSPI_3.PUSHR.PUSHR.R = 0x08015678; /* Transmit data from master DSPI to slave SPI with EOQ */
read_data_SPI_0(); /* Read data on slave SPI */
read_data_DSPI_3(); /* Read data on master DSPI */
i++;
}
return 0;
}
/************************ End of Main ***************************************/
void peri_clock_gating (void) { /* Configures gating/enabling peripheral(DSPI, SPI) clocks */
MC_ME.RUN_PC[0].R = 0x00000000; /* Gate off clock for all RUN modes */
MC_ME.RUN_PC[1].R = 0x000000FE; /* Configures peripheral clock for all RUN modes */
MC_ME.PCTL[43].B.RUN_CFG = 0x1; /* DSPI 2: select peripheral configuration RUN_PC[1] */
MC_ME.PCTL[96].B.RUN_CFG = 0x1; /* SPI 0: select peripheral configuration RUN_PC[1] */
}
| 2.140625 | 2 |
2024-11-18T20:48:55.348895+00:00 | 2021-05-03T01:33:11 | c45d9856ddcfcbc3a25be8ad9ede92c40d4616ef | {
"blob_id": "c45d9856ddcfcbc3a25be8ad9ede92c40d4616ef",
"branch_name": "refs/heads/master",
"committer_date": "2021-05-03T01:33:11",
"content_id": "254fad5aa2b1f5c4527740c5c64d5f41331b4403",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "87c2b3b746e97b2442b6fbfc3845e88e27130a75",
"extension": "c",
"filename": "u64.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 163479296,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2262,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/src/libc/stdio/printf/u64.c",
"provenance": "stackv2-0102.json.gz:87379",
"repo_name": "zhengruohuang/toddler-ng",
"revision_date": "2021-05-03T01:33:11",
"revision_id": "e3a8c6d812c85815ce2231a9c387488b77c9def1",
"snapshot_id": "20a358ae6679d60502e48745a162ed4979688928",
"src_encoding": "UTF-8",
"star_events_count": 14,
"url": "https://raw.githubusercontent.com/zhengruohuang/toddler-ng/e3a8c6d812c85815ce2231a9c387488b77c9def1/src/libc/stdio/printf/u64.c",
"visit_date": "2021-06-11T12:56:24.623551"
} | stackv2 | #include <internal/printf.h>
#include "libk/include/math.h"
static void u64_to_hex(u64 num, char *buf)
{
for (int i = 0; i < 16; i++) {
u64 digit = (int)((num << (i << 2)) >> 60);
buf[i] = digit >= 10 ?
(char)(digit - 10 + 'a') :
(char)(digit + '0');
}
}
static void u64_to_dec(u64 num, char *buf)
{
u64 dividers[] = {
10000000000000000000ull,
1000000000000000000ull, 100000000000000000ull,
10000000000000000ull, 1000000000000000ull,
100000000000000ull, 10000000000000ull,
1000000000000ull, 100000000000ull,
10000000000ull,
1000000000ull, 100000000ull,
10000000ull, 1000000ull,
100000ull, 10000ull, 1000ull, 100ull,
10ull, 1ull
};
u64 q = 0;
for (int i = 0; i < 20; i++) {
div_u64(num, dividers[i], &q, &num);
buf[i] = '0' + q;
}
}
int _printf_u64(struct printf_closure *closure, struct printf_token *token)
{
int i;
int started = 0;
char buf[20];
int len = 0;
char fmt = token->spec;
u64 num = token->va_u64;
switch (fmt) {
case 'b':
for (i = 63; i >= 0; i--) {
_printf_write_char(closure, num & (0x1 << i) ? '1' : '0');
}
break;
case 'p':
case 'x':
_printf_write_str(closure, "0x");
case 'h':
if (!num) {
_printf_write_char(closure, '0');
} else {
u64_to_hex(num, buf);
for (i = 0; i < 16; i++) {
if (buf[i] != '0') started = 1;
if (started) { _printf_write_char(closure, buf[i]); len++; }
}
}
break;
case 'd':
if (num & (0x1ull << 63)) {
_printf_write_char(closure, '-');
num = ~num + 0x1ull;
}
case 'u':
if (!num) {
_printf_write_char(closure, '0');
break;
} else {
u64_to_dec(num, buf);
for (i = 0; i < 20; i++) {
if (buf[i] != '0') started = 1;
if (started) { _printf_write_char(closure, buf[i]); len++; }
}
}
break;
default:
break;
}
return len;
}
| 2.5 | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.