added
stringdate 2024-11-18 17:54:19
2024-11-19 03:39:31
| created
timestamp[s]date 1970-01-01 00:04:39
2023-09-06 04:41:57
| id
stringlengths 40
40
| metadata
dict | source
stringclasses 1
value | text
stringlengths 13
8.04M
| score
float64 2
4.78
| int_score
int64 2
5
|
---|---|---|---|---|---|---|---|
2024-11-18T21:15:51.671276+00:00 | 2018-10-03T22:32:42 | 4f614b6ee15e8a30c80dc34c588838b5142bbb3b | {
"blob_id": "4f614b6ee15e8a30c80dc34c588838b5142bbb3b",
"branch_name": "refs/heads/master",
"committer_date": "2018-10-03T22:32:42",
"content_id": "d0582f68e4e12448f2efa3e24fe021a0d77b9d5b",
"detected_licenses": [
"MIT"
],
"directory_id": "883b9d169e6bc47f7ec53e1cd26051c4b2659f92",
"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": 59057555,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1083,
"license": "MIT",
"license_type": "permissive",
"path": "/examples/advanced/main.c",
"provenance": "stackv2-0112.json.gz:13692",
"repo_name": "GaloisInc/galua",
"revision_date": "2018-10-03T22:32:42",
"revision_id": "c64ae96b78d2d9bda2db1021227f4ef072969dd5",
"snapshot_id": "0558021f52c694b7cccd3ef45eec96d07f6f8e59",
"src_encoding": "UTF-8",
"star_events_count": 33,
"url": "https://raw.githubusercontent.com/GaloisInc/galua/c64ae96b78d2d9bda2db1021227f4ef072969dd5/examples/advanced/main.c",
"visit_date": "2020-04-12T05:00:37.463436"
} | stackv2 | #include <stdio.h>
#include <stdlib.h>
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
__attribute__((noreturn))
static void failure(const char *msg);
static int my_counter(lua_State *L) {
lua_pushvalue(L, lua_upvalueindex(1)); // [num]
lua_pushinteger(L, 1); // [num, 1]
lua_arith(L, LUA_OPADD); // [num + 1]
lua_replace(L, lua_upvalueindex(1)); // []
lua_pushvalue(L, lua_upvalueindex(1)); // [num + 1]
return 1;
}
int main(int argc, char* argv[]) {
int res;
(void)argc;
(void)argv;
lua_State *L = luaL_newstate();
res = luaL_dostring(L, "");
luaL_openlibs(L);
lua_pushinteger(L, 0);
lua_pushcclosure(L, my_counter, 1);
lua_setglobal(L, "my_counter");
res = luaL_dofile(L, "lua_code.lua");
if (res) { failure("dofile"); }
lua_close(L);
return 0;
}
static void failure (const char *msg) {
fprintf(stderr, "Error occurred in %s\n", msg);
exit(EXIT_FAILURE);
}
| 2.15625 | 2 |
2024-11-18T21:15:51.950987+00:00 | 2018-08-14T12:52:18 | 44ce80a3e15b398cc6cf44a01b689f3ea6bee7cf | {
"blob_id": "44ce80a3e15b398cc6cf44a01b689f3ea6bee7cf",
"branch_name": "refs/heads/master",
"committer_date": "2018-08-14T12:52:18",
"content_id": "c22c59dc82827d146c513218aef64eda0dc59f3e",
"detected_licenses": [
"MIT"
],
"directory_id": "8fcf62cb9f1b7191083a5f9322b4a7eb81e2647f",
"extension": "c",
"filename": "bank.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 128032683,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 640,
"license": "MIT",
"license_type": "permissive",
"path": "/c/Project2/Project2/bank.c",
"provenance": "stackv2-0112.json.gz:14078",
"repo_name": "cnzht/grit",
"revision_date": "2018-08-14T12:52:18",
"revision_id": "eab457a0a9b216f5a6026669095b8126bf8a9e1d",
"snapshot_id": "0b5b0d3f137530ed0cac246a0de314807632e6af",
"src_encoding": "GB18030",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/cnzht/grit/eab457a0a9b216f5a6026669095b8126bf8a9e1d/c/Project2/Project2/bank.c",
"visit_date": "2020-03-08T08:52:18.583920"
} | stackv2 | #include "lead.h"
void main()
{
char userName[8];
char userPWD[7];
int i;
welcome();
for ( i = 0; i < 3; i++)
{
printf("请输入您的用户名:(第%d次)\n",i+1);
scanf("%s",userName);
printf("请输入您的密码:(第%d次)\n",i+1);
scanf("%s", userPWD);
if ((strcmp(userName,"admin")==0)&&(strcmp(userPWD,"123456")==0))
{
mainmenu();
break;
}
else
{
if (i<2)
{
printf("用户名或密码错误,请重新输入!:(第%d次)\n",i+1);
}
else
{
printf("%d次机会用完,用户名或者密码错误,退出系统!", i + 1);
exit(1);
}
}
}
system("pause");
} | 2.453125 | 2 |
2024-11-18T21:15:52.048796+00:00 | 2020-01-31T01:54:37 | 9e1e4bf6a06553e8ab42cee97fac75c9804bb01e | {
"blob_id": "9e1e4bf6a06553e8ab42cee97fac75c9804bb01e",
"branch_name": "refs/heads/master",
"committer_date": "2020-01-31T01:54:37",
"content_id": "66bcae31f57d08448840c96c3fea661fbd13cc73",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "473fc28d466ddbe9758ca49c7d4fb42e7d82586e",
"extension": "c",
"filename": "get_syscall_args.c",
"fork_events_count": 2,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 237205127,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 320,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/app/src/main/java/com/syd/source/aosp/external/strace/linux/powerpc/get_syscall_args.c",
"provenance": "stackv2-0112.json.gz:14207",
"repo_name": "lz-purple/Source",
"revision_date": "2020-01-31T01:54:37",
"revision_id": "e2745b756317aac3c7a27a4c10bdfe0921a82a1c",
"snapshot_id": "a7788070623f2965a8caa3264778f48d17372bab",
"src_encoding": "UTF-8",
"star_events_count": 4,
"url": "https://raw.githubusercontent.com/lz-purple/Source/e2745b756317aac3c7a27a4c10bdfe0921a82a1c/app/src/main/java/com/syd/source/aosp/external/strace/linux/powerpc/get_syscall_args.c",
"visit_date": "2020-12-23T17:03:12.412572"
} | stackv2 | /* Return -1 on error or 1 on success (never 0!). */
static int
get_syscall_args(struct tcb *tcp)
{
tcp->u_arg[0] = ppc_regs.orig_gpr3;
tcp->u_arg[1] = ppc_regs.gpr[4];
tcp->u_arg[2] = ppc_regs.gpr[5];
tcp->u_arg[3] = ppc_regs.gpr[6];
tcp->u_arg[4] = ppc_regs.gpr[7];
tcp->u_arg[5] = ppc_regs.gpr[8];
return 1;
}
| 2.125 | 2 |
2024-11-18T21:15:52.273793+00:00 | 2020-06-01T10:51:37 | 142ed045683527dc630f783d1182e260a4d30ddb | {
"blob_id": "142ed045683527dc630f783d1182e260a4d30ddb",
"branch_name": "refs/heads/master",
"committer_date": "2020-06-01T10:51:37",
"content_id": "9304fd8594a1f561a374d69e1d37dbe40dad8d48",
"detected_licenses": [
"MIT"
],
"directory_id": "1aeee8682282c0ae79499314d067e5cd88a9261d",
"extension": "c",
"filename": "panic.c",
"fork_events_count": 1,
"gha_created_at": "2019-05-20T21:40:29",
"gha_event_created_at": "2019-05-24T17:32:50",
"gha_language": "C",
"gha_license_id": "NOASSERTION",
"github_id": 187717197,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 208,
"license": "MIT",
"license_type": "permissive",
"path": "/StdLib/Panic/panic.c",
"provenance": "stackv2-0112.json.gz:14463",
"repo_name": "hungrybluedev/C-Programs",
"revision_date": "2020-06-01T10:51:37",
"revision_id": "f02dd27f626eb004b1ddd6f2483d9cc19c509b2b",
"snapshot_id": "51574097333772b96cfecf7f45aabb37934f5b7b",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/hungrybluedev/C-Programs/f02dd27f626eb004b1ddd6f2483d9cc19c509b2b/StdLib/Panic/panic.c",
"visit_date": "2021-08-16T07:57:46.037668"
} | stackv2 | #include <stdio.h>
#include <stdlib.h>
void panic(FILE *output, const char *message) {
fprintf(output, "Program panicked with the following message:\n\n%s\n\n",
message);
exit(EXIT_FAILURE);
}
| 2.328125 | 2 |
2024-11-18T21:15:52.346125+00:00 | 2018-08-11T16:07:10 | 122c5e1f6d3a504f62e522eacf45319931ed4de5 | {
"blob_id": "122c5e1f6d3a504f62e522eacf45319931ed4de5",
"branch_name": "refs/heads/master",
"committer_date": "2018-08-11T16:07:10",
"content_id": "a8a866874262f5077640ddfff9635aee2cc1851f",
"detected_licenses": [
"MIT"
],
"directory_id": "4f03686cdeefae854a112d0ee9781fb622eda231",
"extension": "c",
"filename": "test_bootloader_agent.c",
"fork_events_count": 0,
"gha_created_at": "2018-10-08T20:50:36",
"gha_event_created_at": "2018-10-08T20:50:36",
"gha_language": null,
"gha_license_id": null,
"github_id": 152144961,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1719,
"license": "MIT",
"license_type": "permissive",
"path": "/test/agents/test_bootloader_agent.c",
"provenance": "stackv2-0112.json.gz:14592",
"repo_name": "xrmx/libpull",
"revision_date": "2018-08-11T16:07:10",
"revision_id": "feec4359ddfb04779f484d9828ca793a430b0a2b",
"snapshot_id": "0f43a9f5ef3190f6732694f85f2c6093b1190084",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/xrmx/libpull/feec4359ddfb04779f484d9828ca793a430b0a2b/test/agents/test_bootloader_agent.c",
"visit_date": "2020-03-31T10:41:21.887434"
} | stackv2 | #include <libpull/security/sha256.h>
#include "libpull_agents/bootloader_agent.h"
#include "support/support.h"
#include <unistd.h>
#define BUFFER_SIZE 1024
static agent_msg_t agent_msg;
static bootloader_agent_config cfg;
static int8_t retries = 3;
static uint8_t success = 0;
static uint8_t buffer[BUFFER_SIZE];
// The test logic should update the OBJ_2 with the firmware with version 0xdead
// After the test is finished I invalidate the OBJ_2 to restore the status
void ntest_prepare(void) {
bzero(&cfg, sizeof(cfg));
}
void ntest_clean(void) {
restore_assets();
retries = 3;
success = 0;
}
void test_bootloader_success(void) {
bootloader_agent_vendor_keys(&cfg, (uint8_t*) vendor_x_g, (uint8_t*) vendor_y_g);
bootloader_agent_digest_func(&cfg, tinydtls_digest_sha256);
bootloader_agent_ecc_func(&cfg, tinydtls_secp256r1_ecc);
bootloader_agent_set_buffer(&cfg, buffer, BUFFER_SIZE);
cfg.bootloader_ctx_id = BOOTLOADER_CTX;
cfg.recovery_id = OBJ_GOLD;
while(1) {
agent_msg = bootloader_agent(&cfg);
if (IS_FAILURE(agent_msg)) {
printf("error is:%s\n", (err_as_str(GET_ERROR(agent_msg))));
success = false;
break;
} else if (IS_CONTINUE(agent_msg)) {
if (agent_msg.event == EVENT_BOOT) {
nTEST_TRUE(agent_msg.event == EVENT_BOOT);
nTEST_COMPARE_INT(OBJ_B, GET_BOOT_ID(agent_msg));
success = true;
break;
}
continue;
}
}
nTEST_TRUE(success, "Error during the booting process");
}
int main() {
nTEST_INIT();
nTEST_RUN(test_bootloader_success);
nTEST_END();
nTEST_RETURN();
}
| 2.1875 | 2 |
2024-11-18T21:15:52.421444+00:00 | 2017-11-12T16:01:45 | 2811b7cc0c2b3b74308678846905377b2a5d1809 | {
"blob_id": "2811b7cc0c2b3b74308678846905377b2a5d1809",
"branch_name": "refs/heads/master",
"committer_date": "2017-11-12T16:01:45",
"content_id": "0ecf68dae788fd7b5567a00eac0b02913c231455",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "0345df8f3f019cce422ed303783b0d2c2e17eb29",
"extension": "c",
"filename": "udp_print.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 91232511,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 339,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/udp_print.c",
"provenance": "stackv2-0112.json.gz:14722",
"repo_name": "cakturk/unet",
"revision_date": "2017-11-12T16:01:45",
"revision_id": "206da696408c1329908376b88616f575255b7196",
"snapshot_id": "85ed550ee867b8136455ed5241d4c6603974dca9",
"src_encoding": "UTF-8",
"star_events_count": 18,
"url": "https://raw.githubusercontent.com/cakturk/unet/206da696408c1329908376b88616f575255b7196/udp_print.c",
"visit_date": "2020-12-30T13:38:49.782701"
} | stackv2 | #include <stdio.h>
#include <errno.h>
#include "netsniff.h"
#define UDPSTR_MAX 24
int
udp_print(struct udphdr *uh, struct strbuf *sb)
{
char tmp[UDPSTR_MAX];
if (sb_room(sb) < UDPSTR_MAX)
return -ENOBUFS;
sprintf(tmp, "%d->%d len: %d", ntohs(uh->sport),
ntohs(uh->dport), ntohs(uh->len));
sb_append_str(sb, tmp);
return 0;
}
| 2.265625 | 2 |
2024-11-18T21:15:52.850296+00:00 | 2018-03-21T14:43:49 | 8bbe04cf349d31742565cb4aa2698367071e479b | {
"blob_id": "8bbe04cf349d31742565cb4aa2698367071e479b",
"branch_name": "refs/heads/master",
"committer_date": "2018-03-21T14:43:49",
"content_id": "881a63c9525a876a90b2a26515446388f492aff3",
"detected_licenses": [
"MIT"
],
"directory_id": "cf9056b12deda80eb6b461e5ff4b8a5ec86c9d2d",
"extension": "h",
"filename": "print.h",
"fork_events_count": 2,
"gha_created_at": "2018-03-28T10:24:34",
"gha_event_created_at": "2018-03-28T10:24:34",
"gha_language": null,
"gha_license_id": null,
"github_id": 127123539,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 596,
"license": "MIT",
"license_type": "permissive",
"path": "/kernel/include/print.h",
"provenance": "stackv2-0112.json.gz:14983",
"repo_name": "killvxk/MiraiOS",
"revision_date": "2018-03-21T14:43:49",
"revision_id": "d18b33cbab198e1253fc6474799a22d8431a5b86",
"snapshot_id": "febcbcd9564f8023b2239297e4753a738fbad2b3",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/killvxk/MiraiOS/d18b33cbab198e1253fc6474799a22d8431a5b86/kernel/include/print.h",
"visit_date": "2020-03-06T23:05:58.523902"
} | stackv2 | #ifndef INCLUDE_PRINT_H
#define INCLUDE_PRINT_H
#include <stdint.h>
#include <stdarg.h>
/*
Formatted print
*/
void printk(const char *fmt, ...);
void vprintk(const char *fmt, va_list args);
/*
Prints a character to the output console
*/
void putc(char c);
/*
Prints a string to the output console
*/
void puts(const char *text);
/*
Prints a 64-bit integer as hex to the output console
*/
void hexprint64(uint64_t value);
/*
Prints a 64-bit integer as hex to the output console
With newline
*/
void hexprintln64(uint64_t value);
void setKernelStdout(int (*puts)(const char *str));
#endif
| 2.203125 | 2 |
2024-11-18T21:15:52.909814+00:00 | 2016-08-11T11:48:43 | 48696492ddebd1e24d674e4581c93eee56012fc0 | {
"blob_id": "48696492ddebd1e24d674e4581c93eee56012fc0",
"branch_name": "refs/heads/master",
"committer_date": "2016-08-11T11:48:43",
"content_id": "9b96f5222081b29d1b98e0c00259694f0232e1d2",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "7621c83f8dfe0521f48a74f840302326b01fe4f9",
"extension": "c",
"filename": "nbodies - dynamic parallel.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 65464834,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 12234,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/nbodies - dynamic parallel.c",
"provenance": "stackv2-0112.json.gz:15111",
"repo_name": "esainty/parallel-planetary-simulation",
"revision_date": "2016-08-11T11:48:43",
"revision_id": "4f76266aefa6ecc4ffb7295d7b70d25f79f1bcf7",
"snapshot_id": "8d543991feb8cd81ffafa776f3df5fa4a95f4114",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/esainty/parallel-planetary-simulation/4f76266aefa6ecc4ffb7295d7b70d25f79f1bcf7/nbodies - dynamic parallel.c",
"visit_date": "2020-12-25T13:51:26.065995"
} | stackv2 | #include <stdio.h>
#include <stdlib.h>
#include <mpi.h>
#include <math.h>
#include <time.h>
#include <X11/Xlib.h> // X11 library headers
#include <X11/Xutil.h>
#include <X11/Xos.h>
#define X_RESN 1000 /* x resolution */
#define Y_RESN 1000 /* y resolution */
#define UNIVERSE_SIZE 1000 // Universe width/height in km.
#define G 0.0000000000667 // Gravitational Constant
// #define G 3
#define PI 3.14159265358979323846 // Pi
// Body type.
struct Body {
long m;
double fx;
double fy;
double vx;
double vy;
double posx;
double posy;
int depth;
};
typedef struct Body Body;
// function prototype
Display * x11setup(Window *win, GC *gc, int width, int height);
MPI_Datatype createMPIBodyType();
void createBodies(Body *bodies, int n, XColor *colours);
long genRand(long max, long min);
void printBody(Body *a);
void initBody(Body *a, long m, double vx, double vy, double posx, double posy, int depth);
void calcForce(Body *a, Body *b);
void updatePosition(Body *a, double dt);
void setupColours(Display *display, XColor *colours, Colormap screenColourmap);
XColor pickColour(int depth);
int main(int argc, char *argv[])
{
int rank, nprocs, i, nbodies, x, y;
Window win; // initialization for a window
GC gc; // graphics context
Display *display = NULL;
unsigned int width = X_RESN, height = Y_RESN; /* window size */
clock_t start, end, elapsed;
Colormap screenColourmap;
XColor colours[14];
int n = 100;
Body bodies[n];
MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &nprocs);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Datatype MPI_BODY = createMPIBodyType();
if(rank==0)
{
display = x11setup(&win, &gc, width, height);
screenColourmap = DefaultColormap(display, DefaultScreen(display));
setupColours(display, colours, screenColourmap);
time_t t;
srand((unsigned) time(&t));
createBodies(bodies, n, colours);
}
// main loop
int running = 1; // loop variable
start = clock();
int counter = 0;
while(running) {
// checks to see if there have been any events,
// will exit the main loop if any key is pressed
if(rank==0) {
if(XPending(display)) {
printf("Dunno what this does.\n");
XEvent ev;
XNextEvent(display, &ev);
switch(ev.type) {
case KeyPress:
printf("Not running\n");
running = 0;
break;
}
}
}
end = clock();
elapsed = end - start;
// Only update the display if > 1 millisecond has passed since the last update.
if(elapsed / (CLOCKS_PER_SEC/1000) > 1 && rank==0) {
// printf("Run Count: %d\n", counter++);
int probeFlag = 0;
MPI_Status status;
int count = 0;
int tracker[nprocs];
for (int i = 1; i < nprocs; i++) {
MPI_Send(bodies, n, MPI_BODY, i, 98, MPI_COMM_WORLD);
}
for (int i = 0; i < nprocs-1; i++) {
MPI_Probe(i+1, 98, MPI_COMM_WORLD, &status);
int slave = status.MPI_SOURCE;
MPI_Recv(&probeFlag, 1, MPI_INT, MPI_ANY_SOURCE, 98, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
MPI_Send(&i, 1, MPI_INT, slave, 99, MPI_COMM_WORLD);
tracker[slave] = i;
// printf("Next: %d, to be processed by: %d\n", tracker[slave], slave);
}
for (int i = nprocs-1; i < n; i++) {
while (!probeFlag) {
MPI_Iprobe(MPI_ANY_SOURCE, 99, MPI_COMM_WORLD, &probeFlag, &status);
if (probeFlag) {
int slave = status.MPI_SOURCE;
MPI_Recv(&bodies[tracker[slave]], 1, MPI_BODY, MPI_ANY_SOURCE, 99, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
MPI_Send(&i, 1, MPI_INT, slave, 99, MPI_COMM_WORLD);
// printf("Body: %d processed by: %d, Next: %d\n", tracker[slave], slave, i);
tracker[slave] = i;
count++;
}
}
probeFlag = 0;
}
probeFlag = 0;
for (int i = 1; i < nprocs; i++) {
MPI_Probe(MPI_ANY_SOURCE, 99, MPI_COMM_WORLD, &status);
int slave = status.MPI_SOURCE;
// printf("Final result from: %d\n", slave);
MPI_Recv(&bodies[tracker[slave]], 1, MPI_BODY, MPI_ANY_SOURCE, 99, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
MPI_Send(&probeFlag, 1, MPI_INT, i, 98, MPI_COMM_WORLD);
}
for (int i = 1; i < nprocs; i++) {
MPI_Recv(&probeFlag, 1, MPI_INT, i, 98, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
// printf("Resignation received from %d\n", i);
}
XClearWindow(display, win);
for (int i = 0; i < n; i++) {
XColor colour = colours[bodies[i].depth];
XSetForeground(display, gc, colour.pixel);
// Draw the bodies. Uses the density of Andesite magma to estimate a size from the mass.
double diameter = cbrt(((double)bodies[i].m / 2500) / 1000) * 20;
int posX = (((bodies[i].posx - diameter / 2) / UNIVERSE_SIZE) * X_RESN);
int posY = (((bodies[i].posy - diameter / 2) / UNIVERSE_SIZE) * X_RESN); // Intentionally X_RESN to force position scaling to be based on screen height.
XFillArc(display, win, gc, posX, posY, diameter, diameter, 0, 23040);
}
start = end;
XFlush(display);
} else if (rank != 0) {
int flag = 1;
int probeFlag = 0;
MPI_Status status;
Body body;
MPI_Recv(&bodies, n, MPI_BODY, 0, 98, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
MPI_Send(&flag, 1, MPI_INT, 0, 98, MPI_COMM_WORLD);
while (flag) {
MPI_Iprobe(0, 98, MPI_COMM_WORLD, &probeFlag, MPI_STATUS_IGNORE);
if (probeFlag) {
MPI_Recv(&flag, 1, MPI_INT, 0, 98, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
MPI_Send(&flag, 1, MPI_INT, 0, 98, MPI_COMM_WORLD);
} else {
MPI_Iprobe(0, 99, MPI_COMM_WORLD, &probeFlag, MPI_STATUS_IGNORE);
if (probeFlag) {
MPI_Recv(&i, 1, MPI_INT, 0, 99, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
bodies[i].fx = 0;
bodies[i].fy = 0;
for (int j = 0; j < n; j++) {
if (j != i) {
calcForce(&bodies[i], &bodies[j]);
}
}
updatePosition(&bodies[i], 200);
MPI_Send(&bodies[i], 1, MPI_BODY, 0, 99, MPI_COMM_WORLD);
}
}
}
}
}
if(rank==0 && display) {
XCloseDisplay(display); // close the display window
}
MPI_Finalize();
return 0;
}
MPI_Datatype createMPIBodyType() {
int count = 8;
int array_of_blocklengths[8] = {1, 1, 1, 1, 1, 1, 1, 1};
MPI_Aint array_of_displacements[8];
MPI_Datatype array_of_types[8] = {MPI_LONG, MPI_DOUBLE, MPI_DOUBLE, MPI_DOUBLE, MPI_DOUBLE, MPI_DOUBLE, MPI_DOUBLE, MPI_INT};
MPI_Datatype MPI_BODY;
MPI_Aint longextent, doubleextent, intextent;
MPI_Type_extent(MPI_LONG, &longextent);
MPI_Type_extent(MPI_INT, &intextent);
MPI_Type_extent(MPI_DOUBLE, &doubleextent);
array_of_displacements[0] = 0;
array_of_displacements[1] = longextent;
array_of_displacements[2] = array_of_displacements[1] + doubleextent;
array_of_displacements[3] = array_of_displacements[2] + doubleextent;
array_of_displacements[4] = array_of_displacements[3] + doubleextent;
array_of_displacements[5] = array_of_displacements[4] + doubleextent;
array_of_displacements[6] = array_of_displacements[5] + doubleextent;
array_of_displacements[7] = array_of_displacements[6] + doubleextent;
MPI_Type_create_struct(count, array_of_blocklengths, array_of_displacements, array_of_types, &MPI_BODY);
MPI_Type_commit(&MPI_BODY);
return MPI_BODY;
}
// Creates n bodies and stores them into the bodies array.
void createBodies(Body *bodies, int n, XColor *colours) {
for (int i = 0; i < n; i++) {
double posx = genRand(1000, 0);
double posy = genRand(1000, 0);
double vx = genRand(0, 0);
double vy = genRand(0, 0);
long m = genRand(5000000, 1000000);
int depth = (int)genRand(13, 0);
initBody(&bodies[i], m, vx, vy, posx, posy, depth);
}
}
// Generates a random long between max and min.
long genRand(long max, long min) {
double randBase = (double)rand() / (double)RAND_MAX; //Generate random between 0 and 1.
return (randBase * (max - min)) + min;
}
// Prints out all variables within a Body.
void printBody(Body *a) {
printf("Position = %f, %f. Force = %f, %f. Velocity = %f, %f. Mass = %d. Colour = %d\n", (*a).posx, (*a).posy, (*a).fx, (*a).fy, (*a).vx, (*a).vy, (*a).m, (*a).depth);
}
// Initialise values within the body.
void initBody(Body *a, long m, double vx, double vy, double posx, double posy, int depth) {
(*a).m = m;
(*a).fx = 0;
(*a).fy = 0;
(*a).vx = vx;
(*a).vy = vy;
(*a).posx = posx;
(*a).posy = posy;
(*a).depth = depth;
}
// Calculate the forces on the body and apply to Body a.
void calcForce(Body *a, Body *b) {
double dx = (*b).posx - (*a).posx;
double dy = (*b).posy - (*a).posy;
double r = sqrt(pow(dx, 2) + pow(dy, 2));
if (r != 0.0) {
double F = (G * (*a).m * (*b).m) / pow(r, 2);
double rmod = sqrt((*a).m) / 100 + sqrt((*b).m) / 100; // Modifier to dampen the effect of r values close to 0.
(*a).fx += F * dx / (r + rmod);
(*a).fy += F * dy / (r + rmod);
}
}
// Update the velocity and X/Y positions of Body a with respect to the time interval dt.
void updatePosition(Body *a, double dt) {
(*a).vx += dt * (*a).fx / (*a).m;
(*a).vy += dt * (*a).fy / (*a).m;
(*a).posx += dt * (*a).vx;
(*a).posy += dt * (*a).vy;
}
// Allocates a set of colours for use by way of a Colourmap.
void setupColours(Display *display, XColor *colours, Colormap screenColourmap) {
for (int i = 0; i < 14; i++) {
colours[i] = pickColour(i);
XAllocColor(display, screenColourmap, &colours[i]);
}
}
// Picks a colour based on an integer input between 0 and 13.
XColor pickColour(int depth) {
double tau = PI * 2;
double tauRainbow = tau / 14;
double tauPart = tau / 3;
XColor colour;
colour.red = (int)(sin(tauRainbow * depth + 1 * tauPart) * 32767 + 32768);
colour.green = (int)(sin(tauRainbow * depth + 2 * tauPart) * 32767 + 32768);
colour.blue = (int)(sin(tauRainbow * depth + 3 * tauPart) * 32767 + 32768);
return colour;
}
Display * x11setup(Window *win, GC *gc, int width, int height)
{
/* --------------------------- X11 graphics setup ------------------------------ */
Display *display;
unsigned int win_x,win_y, /* window position */
border_width, /* border width in pixels */
display_width, display_height, /* size of screen */
screen; /* which screen */
char window_name[] = "N-Body Simulation", *display_name = NULL;
unsigned long valuemask = 0;
XGCValues values;
XSizeHints size_hints;
//Pixmap bitmap;
//XPoint points[800];
FILE *fopen ();//, *fp;
//char str[100];
XSetWindowAttributes attr[1];
if ( (display = XOpenDisplay (display_name)) == NULL ) { /* connect to Xserver */
fprintf (stderr, "Cannot connect to X server %s\n",XDisplayName (display_name) );
exit (-1);
}
screen = DefaultScreen (display); /* get screen size */
display_width = DisplayWidth (display, screen);
display_height = DisplayHeight (display, screen);
win_x = 0; win_y = 0; /* set window position */
border_width = 4; /* create opaque window */
*win = XCreateSimpleWindow (display, RootWindow (display, screen),
win_x, win_y, width, height, border_width,
WhitePixel (display, screen), BlackPixel (display, screen));
size_hints.flags = USPosition|USSize;
size_hints.x = win_x;
size_hints.y = win_y;
size_hints.width = width;
size_hints.height = height;
size_hints.min_width = 300;
size_hints.min_height = 300;
XSetNormalHints (display, *win, &size_hints);
XStoreName(display, *win, window_name);
*gc = XCreateGC (display, *win, valuemask, &values); /* create graphics context */
XSetBackground (display, *gc, BlackPixel (display, screen));
XSetForeground (display, *gc, WhitePixel (display, screen));
XSetLineAttributes (display, *gc, 1, LineSolid, CapRound, JoinRound);
attr[0].backing_store = Always;
attr[0].backing_planes = 1;
attr[0].backing_pixel = BlackPixel(display, screen);
XChangeWindowAttributes(display, *win, CWBackingStore | CWBackingPlanes | CWBackingPixel, attr);
XSelectInput(display, *win, KeyPressMask);
XMapWindow (display, *win);
XSync(display, 0);
/* --------------------------- End of X11 graphics setup ------------------------------ */
return display;
} | 2.3125 | 2 |
2024-11-18T21:15:52.961893+00:00 | 2016-01-12T01:01:29 | b616de09a26ab6386ec01c80b4a6723c01fc2262 | {
"blob_id": "b616de09a26ab6386ec01c80b4a6723c01fc2262",
"branch_name": "refs/heads/master",
"committer_date": "2016-01-12T01:01:29",
"content_id": "fb7efc7a20e7890ac90b5be406f5bea74ba29fc4",
"detected_licenses": [
"MIT"
],
"directory_id": "25ef7e034d84344a18515d42e6498a1ba92ad352",
"extension": "c",
"filename": "dns_protocol.c",
"fork_events_count": 0,
"gha_created_at": "2015-12-18T13:24:53",
"gha_event_created_at": "2015-12-18T13:24:53",
"gha_language": null,
"gha_license_id": null,
"github_id": 48236655,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5618,
"license": "MIT",
"license_type": "permissive",
"path": "/collector/dsc/dns_protocol.c",
"provenance": "stackv2-0112.json.gz:15240",
"repo_name": "McStork/dsc",
"revision_date": "2016-01-12T01:01:29",
"revision_id": "0f6d3bd3d9b12322818e6108e00c95ed85f7e353",
"snapshot_id": "406071c5dd4545240846d93f4ee67711c6d85ff4",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/McStork/dsc/0f6d3bd3d9b12322818e6108e00c95ed85f7e353/collector/dsc/dns_protocol.c",
"visit_date": "2021-01-14T14:06:25.028105"
} | stackv2 | #include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/time.h>
#include <assert.h>
#include <ctype.h>
#include <arpa/nameser.h>
#include <arpa/nameser_compat.h>
#include <syslog.h>
#include "xmalloc.h"
#include "dns_message.h"
#include "byteorder.h"
#define DNS_MSG_HDR_SZ 12
#define RFC1035_MAXLABELSZ 63
static int
rfc1035NameUnpack(const u_char * buf, size_t sz, off_t * off, char *name, int ns)
{
off_t no = 0;
unsigned char c;
size_t len;
static int loop_detect = 0;
if (loop_detect > 2)
return 4; /* compression loop */
if (ns <= 0)
return 4; /* probably compression loop */
do {
if ((*off) >= sz)
break;
c = *(buf + (*off));
if (c > 191) {
/* blasted compression */
int rc;
unsigned short s;
off_t ptr;
s = nptohs(buf + (*off));
(*off) += sizeof(s);
/* Sanity check */
if ((*off) >= sz)
return 1; /* message too short */
ptr = s & 0x3FFF;
/* Make sure the pointer is inside this message */
if (ptr >= sz)
return 2; /* bad compression ptr */
if (ptr < DNS_MSG_HDR_SZ)
return 2; /* bad compression ptr */
loop_detect++;
rc = rfc1035NameUnpack(buf, sz, &ptr, name + no, ns - no);
loop_detect--;
return rc;
} else if (c > RFC1035_MAXLABELSZ) {
/*
* "(The 10 and 01 combinations are reserved for future use.)"
*/
return 3; /* reserved label/compression flags */
break;
} else {
(*off)++;
len = (size_t) c;
if (len == 0)
break;
if (len > (ns - 1))
len = ns - 1;
if ((*off) + len > sz)
return 4; /* message is too short */
if (no + len + 1 > ns)
return 5; /* qname would overflow name buffer */
memcpy(name + no, buf + (*off), len);
(*off) += len;
no += len;
*(name + (no++)) = '.';
}
} while (c > 0);
if (no > 0)
*(name + no - 1) = '\0';
/* make sure we didn't allow someone to overflow the name buffer */
assert(no <= ns);
return 0;
}
static off_t
grok_question(const u_char * buf, int len, off_t offset, char *qname, unsigned short *qtype, unsigned short *qclass)
{
char *t;
int x;
x = rfc1035NameUnpack(buf, len, &offset, qname, MAX_QNAME_SZ);
if (0 != x)
return 0;
if ('\0' == *qname)
strcpy(qname, ".");
/* XXX remove special characters from QNAME */
while ((t = strchr(qname, '\n')))
*t = ' ';
while ((t = strchr(qname, '\r')))
*t = ' ';
for (t = qname; *t; t++)
*t = tolower(*t);
if (offset + 4 > len)
return 0;
*qtype = nptohs(buf + offset);
*qclass = nptohs(buf + offset + 2);
offset += 4;
return offset;
}
static off_t
grok_additional_for_opt_rr(const u_char * buf, int len, off_t offset, dns_message * m)
{
int x;
unsigned short sometype;
unsigned short someclass;
unsigned short us;
char somename[MAX_QNAME_SZ];
x = rfc1035NameUnpack(buf, len, &offset, somename, MAX_QNAME_SZ);
if (0 != x)
return 0;
if (offset + 10 > len)
return 0;
sometype = nptohs(buf + offset);
someclass = nptohs(buf + offset + 2);
if (sometype == T_OPT) {
m->edns.found = 1;
m->edns.bufsiz = someclass;
memcpy(&m->edns.version, buf + offset + 5, 1);
us = nptohs(buf + offset + 6);
m->edns.DO = (us >> 15) & 0x01; /* RFC 3225 */
}
/* get rdlength */
us = nptohs(buf + offset + 8);
offset += 10;
if (offset + us > len)
return 0;
offset += us;
return offset;
}
void
dns_protocol_handler(const u_char * buf, uint16_t len, void *udata)
{
transport_message *tm = udata;
unsigned short us;
off_t offset;
int qdcount;
/* int ancount; */
/* int nscount; */
int arcount;
dns_message m;
memset(&m, 0, sizeof(dns_message));
m.tm = tm;
m.msglen = len;
if (len < DNS_MSG_HDR_SZ) {
m.malformed = 1;
return;
}
us = nptohs(buf + 2);
m.qr = (us >> 15) & 0x01;
if (0 == m.qr) { /* query */
m.client_ip_addr = m.tm->src_ip_addr;
m.server_ip_addr = m.tm->dst_ip_addr;
} else { /* reply */
m.client_ip_addr = m.tm->dst_ip_addr;
m.server_ip_addr = m.tm->src_ip_addr;
}
#if 0
tc = (us >> 9) & 0x01;
ra = (us >> 7) & 0x01;
#endif
m.opcode = (us >> 11) & 0x0F;
m.rd = (us >> 8) & 0x01;
m.aa = (us >> 10) & 0x01;
m.tc = (us >> 9) & 0x01;
m.rcode = us & 0x0F;
qdcount = nptohs(buf + 4);
/* ancount = nptohs(buf + 6); */
/* nscount = nptohs(buf + 8); */
arcount = nptohs(buf + 10);
offset = DNS_MSG_HDR_SZ;
/*
* Grab the first question
*/
if (qdcount > 0 && offset < len) {
off_t new_offset;
new_offset = grok_question(buf, len, offset, m.qname, &m.qtype, &m.qclass);
if (0 == new_offset) {
m.malformed = 1;
return;
}
offset = new_offset;
qdcount--;
}
assert(offset <= len);
/*
* Gobble up subsequent questions, if any
*/
while (qdcount > 0 && offset < len) {
off_t new_offset;
char t_qname[MAX_QNAME_SZ];
unsigned short t_qtype;
unsigned short t_qclass;
new_offset = grok_question(buf, len, offset, t_qname, &t_qtype, &t_qclass);
if (0 == new_offset) {
/*
* point offset to the end of the buffer to avoid any subsequent processing
*/
offset = len;
break;
}
offset = new_offset;
qdcount--;
}
assert(offset <= len);
if (arcount > 0 && offset < len) {
off_t new_offset;
new_offset = grok_additional_for_opt_rr(buf, len, offset, &m);
if (0 == new_offset) {
offset = len;
} else {
offset = new_offset;
}
arcount--;
}
assert(offset <= len);
dns_message_handle(&m);
}
| 2.171875 | 2 |
2024-11-18T21:15:53.238005+00:00 | 2019-03-07T12:49:15 | 06baa33ac0a584d27350bf98536f47946fed8dea | {
"blob_id": "06baa33ac0a584d27350bf98536f47946fed8dea",
"branch_name": "refs/heads/master",
"committer_date": "2019-04-02T16:59:01",
"content_id": "df276acb2b06e2a52ddf16780d2d03666de6faaf",
"detected_licenses": [
"Zlib"
],
"directory_id": "21c5c3609afb4e19b44eb7aa0a9ad6a9eb58c746",
"extension": "h",
"filename": "addr.h",
"fork_events_count": 0,
"gha_created_at": "2018-09-06T14:38:28",
"gha_event_created_at": "2018-09-06T14:38:29",
"gha_language": null,
"gha_license_id": "Zlib",
"github_id": 147687706,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1614,
"license": "Zlib",
"license_type": "permissive",
"path": "/net/addr.h",
"provenance": "stackv2-0112.json.gz:15371",
"repo_name": "zyablik/osdev",
"revision_date": "2019-03-07T12:49:15",
"revision_id": "18df7a93bbb1122f3d5074573f129ea30f492be8",
"snapshot_id": "90cf209d6713d2579b6c52c7d3178521dfadde19",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/zyablik/osdev/18df7a93bbb1122f3d5074573f129ea30f492be8/net/addr.h",
"visit_date": "2020-03-28T03:59:33.637289"
} | stackv2 | // ------------------------------------------------------------------------------------------------
// net/addr.h
// ------------------------------------------------------------------------------------------------
#pragma once
#include "stdlib/types.h"
// ------------------------------------------------------------------------------------------------
// Ethernet Address
typedef struct EthAddr
{
u8 n[6];
} PACKED EthAddr;
#define ETH_ADDR_STRING_SIZE 18
// ------------------------------------------------------------------------------------------------
// IPv4 Address
typedef struct Ipv4Addr
{
union
{
u8 n[4];
u32 bits;
} u;
} PACKED Ipv4Addr;
#define IPV4_ADDR_STRING_SIZE 16
#define IPV4_ADDR_PORT_STRING_SIZE 22
// ------------------------------------------------------------------------------------------------
// Globals
extern const EthAddr g_nullEthAddr;
extern const EthAddr g_broadcastEthAddr;
extern const Ipv4Addr g_nullIpv4Addr;
extern const Ipv4Addr g_broadcastIpv4Addr;
// ------------------------------------------------------------------------------------------------
// Functions
bool EthAddrEq(const EthAddr *x, const EthAddr *y);
bool Ipv4AddrEq(const Ipv4Addr *x, const Ipv4Addr *y);
void EthAddrToStr(char *str, size_t size, const EthAddr *addr);
void Ipv4AddrToStr(char *str, size_t size, const Ipv4Addr *addr);
void Ipv4AddrPortToStr(char *str, size_t size, const Ipv4Addr *addr, u16 port);
bool StrToIpv4Addr(Ipv4Addr *addr, const char *str);
bool StrToIpv4AddrPort(Ipv4Addr *addr, const char *str, u16 *port);
| 2.21875 | 2 |
2024-11-18T21:15:53.483109+00:00 | 2021-03-05T08:57:46 | 48145e517cc77066ea5af8d5f021cad7bd1afcae | {
"blob_id": "48145e517cc77066ea5af8d5f021cad7bd1afcae",
"branch_name": "refs/heads/master",
"committer_date": "2021-03-05T08:57:46",
"content_id": "bf42fb60cf0fca4da0142880655952d403ddf224",
"detected_licenses": [
"MIT"
],
"directory_id": "b7f216f70018dfac5c1974ffb7d86d413bebaf91",
"extension": "c",
"filename": "fake-gpio-chip.c",
"fork_events_count": 0,
"gha_created_at": "2019-05-12T13:40:05",
"gha_event_created_at": "2021-03-05T08:57:47",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 186259860,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1629,
"license": "MIT",
"license_type": "permissive",
"path": "/Chapter15/fake-gpio-chip.c",
"provenance": "stackv2-0112.json.gz:15757",
"repo_name": "MCU-LONG/Linux-Device-Drivers-Development",
"revision_date": "2021-03-05T08:57:46",
"revision_id": "6914ecd62ec6112cf0dc35ee2b74a360d03cb9a4",
"snapshot_id": "e146bd961d47c65f8fb6e7702982bc613b3ab783",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/MCU-LONG/Linux-Device-Drivers-Development/6914ecd62ec6112cf0dc35ee2b74a360d03cb9a4/Chapter15/fake-gpio-chip.c",
"visit_date": "2021-06-19T03:48:39.592198"
} | stackv2 | #include <linux/kernel.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/gpio.h>
#include <linux/platform_device.h> /* For platform devices */
#include <linux/of.h> /* For DT*/
#define GPIO_NUM 16
static struct gpio_chip chip;
static int fake_get_value(struct gpio_chip *gc, unsigned offset)
{
return 0;
}
static void fake_set_value(struct gpio_chip *gc, unsigned offset, int val)
{
}
static int fake_direction_output(struct gpio_chip *gc,
unsigned offset, int val)
{
return 0;
}
static int fake_direction_input(struct gpio_chip *gc,
unsigned offset)
{
return 0;
}
static const struct of_device_id fake_gpiochip_ids[] = {
{ .compatible = "packt,fake-gpio-chip", },
{ /* sentinel */ }
};
static int my_pdrv_probe (struct platform_device *pdev)
{
chip.label = pdev->name;
chip.base = -1;
chip.dev = &pdev->dev;
chip.owner = THIS_MODULE;
chip.ngpio = GPIO_NUM;
chip.can_sleep = 1;
chip.get = fake_get_value;
chip.set = fake_set_value;
chip.direction_output = fake_direction_output;
chip.direction_input = fake_direction_input;
return gpiochip_add(&chip);
}
static int my_pdrv_remove(struct platform_device *pdev)
{
gpiochip_remove(&chip);
return 0;
}
static struct platform_driver mypdrv = {
.probe = my_pdrv_probe,
.remove = my_pdrv_remove,
.driver = {
.name = "fake-gpio-chip",
.of_match_table = of_match_ptr(fake_gpiochip_ids),
.owner = THIS_MODULE,
},
};
module_platform_driver(mypdrv);
MODULE_AUTHOR("John Madieu <john.madieu@gmail.com>");
MODULE_LICENSE("GPL");
| 2.375 | 2 |
2024-11-18T21:15:54.048318+00:00 | 2017-04-06T08:48:32 | 3504cdf6cca37b478b1679124fb846bed7e94cd9 | {
"blob_id": "3504cdf6cca37b478b1679124fb846bed7e94cd9",
"branch_name": "refs/heads/master",
"committer_date": "2017-04-06T08:48:32",
"content_id": "ce11888c42853689191db4c30be9077770ad3415",
"detected_licenses": [
"MIT"
],
"directory_id": "b2502ec930e636e41005d19a06ee36d33f9487a7",
"extension": "h",
"filename": "bed.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 87030013,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1513,
"license": "MIT",
"license_type": "permissive",
"path": "/bed.h",
"provenance": "stackv2-0112.json.gz:16146",
"repo_name": "andreas-wilm/split_bam",
"revision_date": "2017-04-06T08:48:32",
"revision_id": "6c94c38398ee0b850519f97dca39f4be1cc1e817",
"snapshot_id": "6af47153de0562312807bf1a854183489c938c54",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/andreas-wilm/split_bam/6c94c38398ee0b850519f97dca39f4be1cc1e817/bed.h",
"visit_date": "2021-01-18T21:56:31.803952"
} | stackv2 | /* Trimmed down version of Devon Ryan's original https://github.com/dpryan79/MethylDackel/blob/master/MethylDackel.h
* commit c04fb45
*/
#include <inttypes.h>
#include <stdio.h>
#include <zlib.h>
#include "htslib/sam.h"
//#include "htslib/faidx.h"
/*! @typedef
@abstract Structure to hold one region defined in a BED file
@field tid The chromosome ID, defined by bam_hdr_t
@field start 0-based start position
@field end 1-based end position
@field strand 0: Ignore strand (".")
1: Top strand ("+")
2: Bottom strand ("-")
@discussion The start and end coordinates will be truncated if they go beyond
the bounds of a chromosome, as indicated by bam_hdr_t.
*/
typedef struct {
int32_t tid, start, end; //0-based, [start, end)
int8_t strand; //0: ., 1: +, 2: -
} bedRegion;
/*! @typedef
@abstract Structure to hold one region defined in a BED file
@field region Pointer to the regions
@field n Number of regions
@field m maxmum number of regions that can currently be stored.
@discussion You must free this with destroyBED()
*/
typedef struct {
bedRegion *region;
int32_t n, m; //Current (n) and maximal possible (m) number of regions
} bedRegions;
//bed.c
int posOverlapsBED(int32_t tid, int32_t pos, bedRegions *regions, int idxBED);
int spanOverlapsBED(int32_t tid, int32_t start, int32_t end, bedRegions *regions, int *idx);
void sortBED(bedRegions *regions);
void destroyBED(bedRegions *regions);
bedRegions *parseBED(char *fn, bam_hdr_t *hdr);
| 2.390625 | 2 |
2024-11-18T21:15:54.357255+00:00 | 2021-06-04T17:46:15 | 4709c12df76ce389133e6e1b7711ca553c045f73 | {
"blob_id": "4709c12df76ce389133e6e1b7711ca553c045f73",
"branch_name": "refs/heads/master",
"committer_date": "2021-06-04T17:46:15",
"content_id": "6916121fe996adf70f28a8c2c17997a7f4b2cace",
"detected_licenses": [
"Unlicense"
],
"directory_id": "93800b28cce95dbb3ead0f4e8681cc4fb51e5f14",
"extension": "h",
"filename": "ray_trace.h",
"fork_events_count": 2,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 181644672,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2202,
"license": "Unlicense",
"license_type": "permissive",
"path": "/includes/ray_trace.h",
"provenance": "stackv2-0112.json.gz:16532",
"repo_name": "dolovnyak/fractals",
"revision_date": "2021-06-04T17:46:15",
"revision_id": "fe2634f8d1ed7758b405e20e53c79f9aaff30e2f",
"snapshot_id": "6191b28c31f9c2271ca98431c9f45018ca56c92b",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/dolovnyak/fractals/fe2634f8d1ed7758b405e20e53c79f9aaff30e2f/includes/ray_trace.h",
"visit_date": "2021-06-11T00:13:06.506854"
} | stackv2 | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ray_trace.h :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: sbecker <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/05/14 23:25:55 by sbecker #+# #+# */
/* Updated: 2019/05/15 21:38:38 by sbecker ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef RAY_TRACE_H
# define RAY_TRACE_H
# include "math_vec.h"
# include "utilits.h"
typedef struct s_sphere
{
t_vector3d center;
float radius;
float sq_radius;
} t_sphere;
typedef struct s_object3d
{
int type;
t_color color;
int smoothness;
float reflectivity;
t_sphere sphere;
} t_object3d;
typedef struct s_lights
{
int type;
float intensity;
t_vector3d position;
t_vector3d direction;
float sqrt_scalar_direction;
} t_lights;
typedef struct s_canvas
{
float width;
float height;
float min_distance;
float max_distance;
float x_rotation;
float y_rotation;
float z_rotation;
float cos_x_rotate;
float sin_x_rotate;
float cos_y_rotate;
float sin_y_rotate;
float cos_z_rotate;
float sin_z_rotate;
t_vector3d camera;
} t_canvas;
typedef struct s_inicialization_object
{
t_vector3d center;
float radius;
t_color color;
int smoothness;
float reflectivity;
} t_inicialization_object;
t_object3d new_obj_sphere(t_inicialization_object sphere);
t_vector3d get_normal_vector_sphere(t_sphere sphere,
const t_vector3d intersection_point);
t_lights new_light_ambient(float intensity);
t_lights new_light_point(float intensity, t_vector3d position);
t_lights new_light_directional(float intensity, t_vector3d direction);
#endif
| 2.109375 | 2 |
2024-11-18T21:15:54.418233+00:00 | 2021-10-16T05:49:22 | caeb13307aaa8c41e0b284df7dc4bf82f80081aa | {
"blob_id": "caeb13307aaa8c41e0b284df7dc4bf82f80081aa",
"branch_name": "refs/heads/main",
"committer_date": "2021-10-16T07:31:21",
"content_id": "1d451097fc9cf8d8ab5e992c178aa1a7faa9146a",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "91729ccf7286bddffb04df2f4889462e4a40a294",
"extension": "c",
"filename": "std.c",
"fork_events_count": 0,
"gha_created_at": "2021-06-05T00:30:58",
"gha_event_created_at": "2021-06-05T00:30:59",
"gha_language": null,
"gha_license_id": "Apache-2.0",
"github_id": 373988418,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1503,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/NMSIS/DSP/Test/StatisticsFunctions/part1/std.c",
"provenance": "stackv2-0112.json.gz:16662",
"repo_name": "soburi/NMSIS",
"revision_date": "2021-10-16T05:49:22",
"revision_id": "bfb0709d919e9fb3d96a8c75b5d04500943b7240",
"snapshot_id": "dd244e2ebcd0424f361286b475e3a447c4003271",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/soburi/NMSIS/bfb0709d919e9fb3d96a8c75b5d04500943b7240/NMSIS/DSP/Test/StatisticsFunctions/part1/std.c",
"visit_date": "2023-08-22T03:35:32.818232"
} | stackv2 | #include "ref.h"
void ref_std_f32(float32_t *pSrc, uint32_t blockSize, float32_t *pResult)
{
uint32_t i;
float32_t sum = 0, sumsq = 0;
if (blockSize == 1) {
*pResult = 0;
return;
}
for (i = 0; i < blockSize; i++) {
sum += pSrc[i];
sumsq += pSrc[i] * pSrc[i];
}
*pResult = sqrtf((sumsq - sum * sum / (float32_t)blockSize) /
((float32_t)blockSize - 1));
}
void ref_std_q31(q31_t *pSrc, uint32_t blockSize, q31_t *pResult)
{
uint32_t i;
q63_t sum = 0, sumsq = 0;
q31_t in;
if (blockSize == 1) {
*pResult = 0;
return;
}
for (i = 0; i < blockSize; i++) {
in = pSrc[i] >> 8;
sum += in;
sumsq += (q63_t)in * in;
}
sumsq /= (q63_t)(blockSize - 1);
sum = sum * sum / (q63_t)(blockSize * (blockSize - 1));
*pResult = (q31_t)(sqrtf((float)((sumsq - sum) >> 15) / 2147483648.0f) *
2147483648.0f);
}
void ref_std_q15(q15_t *pSrc, uint32_t blockSize, q15_t *pResult)
{
uint32_t i;
q31_t sum = 0;
q63_t sumsq = 0;
if (blockSize == 1) {
*pResult = 0;
return;
}
for (i = 0; i < blockSize; i++) {
sum += pSrc[i];
sumsq += (q63_t)pSrc[i] * pSrc[i];
}
sumsq /= (q63_t)(blockSize - 1);
sum = (q31_t)((q63_t)sum * sum / (q63_t)(blockSize * (blockSize - 1)));
*pResult = (q15_t)(
sqrtf((float)ref_sat_q15((sumsq - sum) >> 15) / 32768.0f) * 32768.0f);
}
| 2.8125 | 3 |
2024-11-18T21:15:54.517167+00:00 | 2021-05-16T21:46:26 | b8b49ff659d850b900ecfb460ea3eb7d1811e5f3 | {
"blob_id": "b8b49ff659d850b900ecfb460ea3eb7d1811e5f3",
"branch_name": "refs/heads/master",
"committer_date": "2021-05-16T21:46:26",
"content_id": "a57b8e29f64450a5978c424053a072a8a30aca84",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "0853c4c87ccdbda20ad3facc7702baf187ebc8dc",
"extension": "h",
"filename": "mdv_bitset.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": 1855,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/mdv_platform/generic/mdv_bitset.h",
"provenance": "stackv2-0112.json.gz:16791",
"repo_name": "bellyfat/MedvedDB",
"revision_date": "2021-05-16T21:46:26",
"revision_id": "2c4b999871decd77ed12a8a9d0ec2f4a73215354",
"snapshot_id": "0f4d0508a5234565b68a07153423d135435b457c",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/bellyfat/MedvedDB/2c4b999871decd77ed12a8a9d0ec2f4a73215354/mdv_platform/generic/mdv_bitset.h",
"visit_date": "2023-04-29T07:06:39.099296"
} | stackv2 | /**
* @file mdv_bitset.h
* @author Vladislav Volkov (wwwvladislav@gmail.com)
* @brief Fixed-size sequence of N bits.
* @version 0.1
* @date 2019-10-13
*
* @copyright Copyright (c) 2019, Vladislav Volkov
*
*/
#pragma once
#include <mdv_alloc.h>
/// Fixed-size sequence of N bits
typedef struct mdv_bitset mdv_bitset;
/**
* @brief Creates new bitset given capacity
*/
mdv_bitset * mdv_bitset_create(size_t size, mdv_allocator const *allocator);
/**
* @brief Retains bitset.
* @details Reference counter is increased by one.
*/
mdv_bitset * mdv_bitset_retain(mdv_bitset *bitset);
/**
* @brief Releases bitset.
* @details Reference counter is decreased by one.
* When the reference counter reaches zero, the bitset's destructor is called.
*/
uint32_t mdv_bitset_release(mdv_bitset *bitset);
/**
* @brief Sets the bit at position pos to the value true.
*/
bool mdv_bitset_set(mdv_bitset *bitset, size_t pos);
/**
* @brief Sets the bit at position pos to the value false.
*/
void mdv_bitset_reset(mdv_bitset *bitset, size_t pos);
/**
* @brief Returns the value of the bit at the position pos.
*/
bool mdv_bitset_test(mdv_bitset const *bitset, size_t pos);
/**
* @brief Fills bitset with given value.
*/
void mdv_bitset_fill(mdv_bitset *bitset, bool val);
/**
* @brief Returns the bitset size
*/
size_t mdv_bitset_size(mdv_bitset const *bitset);
/**
* @brief Returns items number in bitset
*/
size_t mdv_bitset_count(mdv_bitset const *bitset, bool val);
/**
* @brief Returns the bitset capacity (in bits number). Bitset alignment is 32 bits.
*/
size_t mdv_bitset_capacity(mdv_bitset const *bitset);
enum { MDV_BITSET_ALIGNMENT = sizeof(uint32_t) };
/**
* @brief Returns pointer to the underlying array serving as element storage.
*/
uint32_t const * mdv_bitset_data(mdv_bitset const *bitset);
| 2.84375 | 3 |
2024-11-18T21:15:56.133604+00:00 | 2020-01-28T12:40:32 | 7dde71c6c2e73f0d53434ae0b24a7321ee4a6ae6 | {
"blob_id": "7dde71c6c2e73f0d53434ae0b24a7321ee4a6ae6",
"branch_name": "refs/heads/master",
"committer_date": "2020-01-28T12:41:35",
"content_id": "3beff307a9a4b7acfb610c913fe28fc093223880",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "27b8371fabd24739aec8d524d177c09eeda04fa0",
"extension": "c",
"filename": "redefinedVariableTest.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 236732210,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 399,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/errorTest/redefinedVariableTest.c",
"provenance": "stackv2-0112.json.gz:17178",
"repo_name": "lamhacker/VPL-Compiler",
"revision_date": "2020-01-28T12:40:32",
"revision_id": "c54850f95342504e962b990c5cac17679e7069a9",
"snapshot_id": "849d8080b4da249528a851b87bee4180a1cfcc57",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/lamhacker/VPL-Compiler/c54850f95342504e962b990c5cac17679e7069a9/errorTest/redefinedVariableTest.c",
"visit_date": "2020-12-22T08:50:45.337723"
} | stackv2 | #include "base.h"
#define NUM (4)
extern void redefinedVariableTest(long, float*, float*);
int main(void)
{
float* a = mallocVec(NUM);
float* b = mallocVec(NUM);
printf("errorThree: \n");
setValue(a, 10, NUM);
setValue(b, 30, NUM);
redefinedVariableTest(NUM, a, b);
printVec("a", a, NUM);
printVec("b", b, NUM);
freeVec(a);
freeVec(b);
}
| 2.046875 | 2 |
2024-11-18T21:15:56.510648+00:00 | 2020-08-27T06:28:10 | 77085e33b7df2f57b176e4d323dbbd9aff56b4c1 | {
"blob_id": "77085e33b7df2f57b176e4d323dbbd9aff56b4c1",
"branch_name": "refs/heads/master",
"committer_date": "2020-08-27T06:28:10",
"content_id": "e2fd7d6e806c3334b3d6a0b49050e04a24bd6d68",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "10f343668fbe791d53dd02854ccea0748d6aa530",
"extension": "c",
"filename": "uart.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": 2918,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/project/uart/uart.c",
"provenance": "stackv2-0112.json.gz:17439",
"repo_name": "VivOO7/libc-atmega32",
"revision_date": "2020-08-27T06:28:10",
"revision_id": "602150f272d405a496497b66c292917a5bf594a0",
"snapshot_id": "9bfa61946dc817b629c1aeec03f5926adab8de8a",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/VivOO7/libc-atmega32/602150f272d405a496497b66c292917a5bf594a0/project/uart/uart.c",
"visit_date": "2022-12-07T02:35:52.318315"
} | stackv2 | #include <avr/io.h>
#include <avr/interrupt.h>
#define BAUD_PRESCALER (((F_CPU/(UART_BAUD*16UL)))-1)
#define SERIAL_BUFF_SIZE 50
#define STRING_SIZE 50
#define STOP_CHAR -1
static unsigned char rxBuffer[SERIAL_BUFF_SIZE]={0X00};
static uint8_t inPos = 0;
static uint8_t outPos = 0;
static uint8_t filled = 0;
char str[STRING_SIZE]={0X00};
uint8_t ind=0;
char strg[STRING_SIZE]={0X00};
static char empty_str[]="";
// uart receive interrupt service routine
ISR(USART_RXC_vect)
{
if(filled < SERIAL_BUFF_SIZE)
{
rxBuffer[ inPos ++ ] = UDR;
filled++;
if(inPos == SERIAL_BUFF_SIZE) inPos=0;
}
}
// function for initialization of uart port
void uartBegin(long UART_BAUD, char parity, char stopBits)
{
// 0X86h is the default value of UCSRC register
unsigned char ucsrc = 0X86;
//parity mode setting
switch(parity)
{
case 'n':
case 'N':
ucsrc &= (~( (1<<UPM1) | (1<<UPM0) ) );
break;
case 'e':
case 'E':
ucsrc |= (1<<UPM1);
ucsrc &= (~(1<<UPM0));
break;
case 'o':
case 'O':
ucsrc |= ( (1<<UPM1) | (1<<UPM0) );
break;
}
//setting the number of stop bits
if(stopBits==2)
ucsrc |= (1<<USBS);
else
ucsrc &= (~(1<<USBS));
//setting the data length
ucsrc |= (1<<URSEL) | (1<<UCSZ0) | (1<<UCSZ1);
UCSRB |= (1<<RXEN) | (1<<TXEN) | (1<<RXCIE);
//UCSRC = (1<<URSEL) | (1<<UCSZ0) | (1<<UCSZ1);
UCSRC = ucsrc;
//setting the baud rate
UBRRL = BAUD_PRESCALER;
UBRRH = (BAUD_PRESCALER >> 8 );
sei();
}
// function to send a character through uart port
void uartSend(char ch)
{
while( (UCSRA & (1<<UDRE)) == 0 );
UDR = ch;
}
//function to send a string of character through uart port
void uartSendString(char *str)
{
while( (*str) != '\0')
{
uartSend( *str );
str+=1;
}
}
// function to read a character that was received through uart port
char uartRead(void)
{
if( filled > 0 )
{
char data=rxBuffer[outPos++];
filled--;
if(outPos==SERIAL_BUFF_SIZE) outPos=0;
return data;
}
else return STOP_CHAR;
}
// function to disable uart port
void uartDisable(void)
{
UCSRB &= ( ~ ( (1<<RXEN) | (1<<TXEN) | (1<<RXCIE) ) );
}
// function to read a string of passed length, received through the uart port
char * readString(uint16_t length)
{
if(filled>=length)
{
for(unsigned int x=0;x<length;x++)
str[x]=uartRead();
str[length]='\0';
return str;
}
else
{
return empty_str;
}
}
// function to read a string delimited by the passed character, received through the uart port
char * readStringUntil(char delimiter)
{
if(filled)
{
char ch=uartRead();
if(ch==delimiter)
{
str[ind]='\0';
ind=0;
return str;
}
else
{
if(ind<STRING_SIZE-1)
str[ind++]=ch;
else
{
str[ind]='\0';
ind=0;
return str;
}
return empty_str;
}
}
else
{
return empty_str;
}
}
//function to print a character string to the uart port
void uartPrintln(char *st)
{
uartSendString(st);
uartSend('\n');
}
| 2.84375 | 3 |
2024-11-18T21:15:56.811554+00:00 | 2020-12-19T11:25:10 | edf517beeb8037e1755cacdeeef24d45f04374fb | {
"blob_id": "edf517beeb8037e1755cacdeeef24d45f04374fb",
"branch_name": "refs/heads/master",
"committer_date": "2020-12-19T11:25:10",
"content_id": "f613bdd38eae5930cc01da2de0c07d6a1be17446",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "193920eb3b12667cc38f549beb7e40e98e69f400",
"extension": "c",
"filename": "i2s.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 21398012,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4468,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/os/hal/src/i2s.c",
"provenance": "stackv2-0112.json.gz:17825",
"repo_name": "marcoveeneman/ChibiOS-Tiva",
"revision_date": "2020-12-19T11:25:10",
"revision_id": "959c058ce94313ab4c38ba526669a5e83978fa1d",
"snapshot_id": "4f13853ea5eaeafe4736576097dfce0746e430ea",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/marcoveeneman/ChibiOS-Tiva/959c058ce94313ab4c38ba526669a5e83978fa1d/os/hal/src/i2s.c",
"visit_date": "2021-01-10T19:01:11.558639"
} | stackv2 | /*
ChibiOS/HAL - Copyright (C) 2006,2007,2008,2009,2010,
2011,2012,2013,2014 Giovanni Di Sirio.
This file is part of ChibiOS/HAL
ChibiOS/HAL is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
ChibiOS/RT is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @file i2s.c
* @brief I2S Driver code.
*
* @addtogroup I2S
* @{
*/
#include "hal.h"
#if HAL_USE_I2S || defined(__DOXYGEN__)
/*===========================================================================*/
/* Driver local definitions. */
/*===========================================================================*/
/*===========================================================================*/
/* Driver exported variables. */
/*===========================================================================*/
/*===========================================================================*/
/* Driver local variables and types. */
/*===========================================================================*/
/*===========================================================================*/
/* Driver local functions. */
/*===========================================================================*/
/*===========================================================================*/
/* Driver exported functions. */
/*===========================================================================*/
/**
* @brief I2S Driver initialization.
* @note This function is implicitly invoked by @p halInit(), there is
* no need to explicitly initialize the driver.
*
* @init
*/
void i2sInit(void) {
i2s_lld_init();
}
/**
* @brief Initializes the standard part of a @p I2SDriver structure.
*
* @param[out] i2sp pointer to the @p I2SDriver object
*
* @init
*/
void i2sObjectInit(I2SDriver *i2sp) {
i2sp->state = I2S_STOP;
i2sp->config = NULL;
}
/**
* @brief Configures and activates the I2S peripheral.
*
* @param[in] i2sp pointer to the @p I2SDriver object
* @param[in] config pointer to the @p I2SConfig object
*
* @api
*/
void i2sStart(I2SDriver *i2sp, const I2SConfig *config) {
osalDbgCheck((i2sp != NULL) && (config != NULL));
osalSysLock();
osalDbgAssert((i2sp->state == I2S_STOP) || (i2sp->state == I2S_READY),
"invalid state");
i2sp->config = config;
i2s_lld_start(i2sp);
i2sp->state = I2S_READY;
osalSysUnlock();
}
/**
* @brief Deactivates the I2S peripheral.
*
* @param[in] i2sp pointer to the @p I2SDriver object
*
* @api
*/
void i2sStop(I2SDriver *i2sp) {
osalDbgCheck(i2sp != NULL);
osalSysLock();
osalDbgAssert((i2sp->state == I2S_STOP) || (i2sp->state == I2S_READY),
"invalid state");
i2s_lld_stop(i2sp);
i2sp->state = I2S_STOP;
osalSysUnlock();
}
/**
* @brief Starts a I2S data exchange.
*
* @param[in] i2sp pointer to the @p I2SDriver object
*
* @api
*/
void i2sStartExchange(I2SDriver *i2sp) {
osalDbgCheck(i2sp != NULL);
osalSysLock();
osalDbgAssert(i2sp->state == I2S_READY, "not ready");
i2sStartExchangeI(i2sp);
osalSysUnlock();
}
/**
* @brief Stops the ongoing data exchange.
* @details The ongoing data exchange, if any, is stopped, if the driver
* was not active the function does nothing.
*
* @param[in] i2sp pointer to the @p I2SDriver object
*
* @api
*/
void i2sStopExchange(I2SDriver *i2sp) {
osalDbgCheck((i2sp != NULL));
osalSysLock();
osalDbgAssert((i2sp->state == I2S_READY) ||
(i2sp->state == I2S_ACTIVE) ||
(i2sp->state == I2S_COMPLETE),
"invalid state");
i2sStopExchangeI(i2sp);
osalSysUnlock();
}
#endif /* HAL_USE_I2S */
/** @} */
| 2.078125 | 2 |
2024-11-18T21:15:57.205094+00:00 | 2017-01-07T19:51:22 | b078eee4c4dbd9130f9e67af9a9c5d15f5202ae6 | {
"blob_id": "b078eee4c4dbd9130f9e67af9a9c5d15f5202ae6",
"branch_name": "refs/heads/master",
"committer_date": "2017-01-07T19:51:22",
"content_id": "45874470698dad01a448a78e6b8e1efa8905907d",
"detected_licenses": [
"MIT"
],
"directory_id": "a0b70267e7e868828eae407016863374945a5d47",
"extension": "c",
"filename": "AVeryBigSum.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 76441489,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 420,
"license": "MIT",
"license_type": "permissive",
"path": "/Algorithms/Warmup/AVeryBigSum.c",
"provenance": "stackv2-0112.json.gz:18339",
"repo_name": "GowthamSiddarth/Hackerrank",
"revision_date": "2017-01-07T19:51:22",
"revision_id": "3a63bbe673300f0cea85c9c59a540197213fca19",
"snapshot_id": "51d02cbd524d616231e4256fd2f31fc4076b7887",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/GowthamSiddarth/Hackerrank/3a63bbe673300f0cea85c9c59a540197213fca19/Algorithms/Warmup/AVeryBigSum.c",
"visit_date": "2021-01-11T12:25:44.032946"
} | stackv2 | #include <stdio.h>
long int array_sum(long int *arr, int len) {
long int sum = 0;
for (int i = 0; i < len; i++) {
sum += arr[i];
}
return sum;
}
int main() {
int n;
scanf("%d",&n);
long int arr[n];
for(int arr_i = 0; arr_i < n; arr_i++){
scanf("%ld",&arr[arr_i]);
}
long int sum = array_sum(arr, n);
printf("%ld", sum);
return 0;
}
| 3.15625 | 3 |
2024-11-18T21:15:57.337985+00:00 | 2019-01-17T06:31:31 | 5b13c783735c60e9a54fa1eb19cad3cf7342d4fb | {
"blob_id": "5b13c783735c60e9a54fa1eb19cad3cf7342d4fb",
"branch_name": "refs/heads/develop",
"committer_date": "2019-01-17T06:31:31",
"content_id": "135b4137141315817ed3ceb4cc40684517c22519",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "445e7c60861fda8dfcd1c41660504c5fcb9dc263",
"extension": "c",
"filename": "tangle.c",
"fork_events_count": 0,
"gha_created_at": "2019-01-17T08:56:31",
"gha_event_created_at": "2023-04-04T01:05:07",
"gha_language": "C",
"gha_license_id": "Apache-2.0",
"github_id": 166193381,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 12488,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/consensus/tangle/tangle.c",
"provenance": "stackv2-0112.json.gz:18596",
"repo_name": "EwoutH/entangled",
"revision_date": "2019-01-17T06:31:31",
"revision_id": "fbe015fae8ff6d005cd3d083e621238d85c94317",
"snapshot_id": "bfc9096c357b5e0afe6a8bc8f4e8c568168a94cb",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/EwoutH/entangled/fbe015fae8ff6d005cd3d083e621238d85c94317/consensus/tangle/tangle.c",
"visit_date": "2023-04-04T13:11:34.406804"
} | stackv2 | /*
* Copyright (c) 2018 IOTA Stiftung
* https://github.com/iotaledger/entangled
*
* Refer to the LICENSE file for licensing information
*/
#include <inttypes.h>
#include "consensus/tangle/tangle.h"
#include "utils/logger_helper.h"
#define TANGLE_LOGGER_ID "tangle"
static logger_id_t logger_id;
retcode_t iota_tangle_init(tangle_t *const tangle,
connection_config_t const *const conf) {
logger_id = logger_helper_enable(TANGLE_LOGGER_ID, LOGGER_DEBUG, true);
return connection_init(&tangle->connection, conf);
}
retcode_t iota_tangle_destroy(tangle_t *const tangle) {
logger_helper_release(logger_id);
return connection_destroy(&tangle->connection);
}
/*
* Transaction operations
*/
retcode_t iota_tangle_transaction_count(tangle_t const *const tangle,
size_t *const count) {
return iota_stor_transaction_count(&tangle->connection, count);
}
retcode_t iota_tangle_transaction_store(tangle_t const *const tangle,
iota_transaction_t const *const tx) {
return iota_stor_transaction_store(&tangle->connection, tx);
}
retcode_t iota_tangle_transaction_load(tangle_t const *const tangle,
transaction_field_t const field,
flex_trit_t const *const key,
iota_stor_pack_t *const tx) {
return iota_stor_transaction_load(&tangle->connection, field, key, tx);
}
retcode_t iota_tangle_transaction_update_solid_state(
tangle_t const *const tangle, flex_trit_t const *const hash,
bool const state) {
return iota_stor_transaction_update_solid_state(&tangle->connection, hash,
state);
}
retcode_t iota_tangle_transactions_update_solid_state(
tangle_t const *const tangle, hash243_set_t const hashes,
bool const is_solid) {
return iota_stor_transactions_update_solid_state(&tangle->connection, hashes,
is_solid);
}
retcode_t iota_tangle_transaction_load_hashes_of_approvers(
tangle_t const *const tangle, flex_trit_t const *const approvee_hash,
iota_stor_pack_t *const pack, int64_t before_timestamp) {
retcode_t res = RC_OK;
res = iota_stor_transaction_load_hashes_of_approvers(
&tangle->connection, approvee_hash, pack, before_timestamp);
while (res == RC_OK && pack->insufficient_capacity) {
res = hash_pack_resize(pack, 2);
if (res == RC_OK) {
pack->num_loaded = 0;
res = iota_stor_transaction_load_hashes_of_approvers(
&tangle->connection, approvee_hash, pack, before_timestamp);
}
}
if (res != RC_OK) {
log_error(logger_id,
"Failed in loading approvers, error code is: %" PRIu64 "\n", res);
}
return res;
}
retcode_t iota_tangle_transaction_load_partial(
tangle_t const *const tangle, flex_trit_t const *const hash,
iota_stor_pack_t *const pack, partial_transaction_model_e models_mask) {
if (models_mask == PARTIAL_TX_MODEL_METADATA) {
return iota_stor_transaction_load_metadata(&tangle->connection, hash, pack);
} else if (models_mask == PARTIAL_TX_MODEL_ESSENCE_METADATA) {
return iota_stor_transaction_load_essence_and_metadata(&tangle->connection,
hash, pack);
} else if (models_mask == PARTIAL_TX_MODEL_ESSENCE_ATTACHMENT_METADATA) {
return iota_stor_transaction_load_essence_attachment_and_metadata(
&tangle->connection, hash, pack);
} else if (models_mask == PARTIAL_TX_MODEL_ESSENCE_CONSENSUS) {
return iota_stor_transaction_load_essence_and_consensus(&tangle->connection,
hash, pack);
} else {
return RC_CONSENSUS_NOT_IMPLEMENTED;
}
}
retcode_t iota_tangle_transaction_load_hashes_of_requests(
tangle_t const *const tangle, iota_stor_pack_t *const pack,
size_t const limit) {
retcode_t res = RC_OK;
res = iota_stor_transaction_load_hashes_of_requests(&tangle->connection, pack,
limit);
while (res == RC_OK && pack->insufficient_capacity) {
if ((res = hash_pack_resize(pack, 2)) == RC_OK) {
pack->num_loaded = 0;
res = iota_stor_transaction_load_hashes_of_requests(&tangle->connection,
pack, limit);
}
}
if (res != RC_OK) {
log_error(logger_id,
"Failed in loading hash requests, error code is: %" PRIu64 "\n",
res);
}
return res;
}
retcode_t iota_tangle_transaction_load_hashes_of_tips(
tangle_t const *const tangle, iota_stor_pack_t *const pack,
size_t const limit) {
retcode_t res = RC_OK;
res = iota_stor_transaction_load_hashes_of_tips(&tangle->connection, pack,
limit);
while (res == RC_OK && pack->insufficient_capacity) {
if ((res = hash_pack_resize(pack, 2)) == RC_OK) {
pack->num_loaded = 0;
res = iota_stor_transaction_load_hashes_of_tips(&tangle->connection, pack,
limit);
}
}
if (res != RC_OK) {
log_error(logger_id,
"Failed in loading hashes of tips, error code is: %" PRIu64 "\n",
res);
}
return res;
}
retcode_t iota_tangle_transaction_load_hashes_of_milestone_candidates(
tangle_t const *const tangle, iota_stor_pack_t *const pack,
flex_trit_t const *const coordinator) {
retcode_t res = RC_OK;
res = iota_stor_transaction_load_hashes_of_milestone_candidates(
&tangle->connection, pack, coordinator);
while (res == RC_OK && pack->insufficient_capacity) {
if ((res = hash_pack_resize(pack, 2)) == RC_OK) {
pack->num_loaded = 0;
res = iota_stor_transaction_load_hashes_of_milestone_candidates(
&tangle->connection, pack, coordinator);
}
}
if (res != RC_OK) {
log_error(logger_id,
"Failed in loading hashes of milestone candidates, error code "
"is: %" PRIu64 "\n",
res);
}
return res;
}
retcode_t iota_tangle_transaction_update_snapshot_index(
tangle_t const *const tangle, flex_trit_t const *const hash,
uint64_t const snapshot_index) {
return iota_stor_transaction_update_snapshot_index(&tangle->connection, hash,
snapshot_index);
}
retcode_t iota_tangle_transactions_update_snapshot_index(
tangle_t const *const tangle, hash243_set_t const hashes,
uint64_t const snapshot_index) {
return iota_stor_transactions_update_snapshot_index(&tangle->connection,
hashes, snapshot_index);
}
retcode_t iota_tangle_transaction_exist(tangle_t const *const tangle,
transaction_field_t const field,
flex_trit_t const *const key,
bool *const exist) {
return iota_stor_transaction_exist(&tangle->connection, field, key, exist);
}
retcode_t iota_tangle_transaction_approvers_count(tangle_t const *const tangle,
flex_trit_t const *const hash,
size_t *const count) {
return iota_stor_transaction_approvers_count(&tangle->connection, hash,
count);
}
retcode_t iota_tangle_transaction_find(tangle_t const *const tangle,
hash243_queue_t const bundles,
hash243_queue_t const addresses,
hash81_queue_t const tags,
hash243_queue_t const approvees,
iota_stor_pack_t *const pack) {
return iota_stor_transaction_find(&tangle->connection, bundles, addresses,
tags, approvees, pack);
}
/*
* Milestone operations
*/
retcode_t iota_tangle_milestone_store(tangle_t const *const tangle,
iota_milestone_t const *const data_in) {
return iota_stor_milestone_store(&tangle->connection, data_in);
}
retcode_t iota_tangle_milestone_load(tangle_t const *const tangle,
flex_trit_t const *const hash,
iota_stor_pack_t *const pack) {
return iota_stor_milestone_load(&tangle->connection, hash, pack);
}
retcode_t iota_tangle_milestone_load_first(tangle_t const *const tangle,
iota_stor_pack_t *const pack) {
return iota_stor_milestone_load_first(&tangle->connection, pack);
}
retcode_t iota_tangle_milestone_load_last(tangle_t const *const tangle,
iota_stor_pack_t *const pack) {
return iota_stor_milestone_load_last(&tangle->connection, pack);
}
retcode_t iota_tangle_milestone_load_next(tangle_t const *const tangle,
uint64_t const index,
iota_stor_pack_t *const pack) {
return iota_stor_milestone_load_next(&tangle->connection, index, pack);
}
retcode_t iota_tangle_milestone_exist(tangle_t const *const tangle,
flex_trit_t const *const hash,
bool *const exist) {
return iota_stor_milestone_exist(&tangle->connection, hash, exist);
}
/*
* Utilities
*/
retcode_t iota_tangle_find_tail(tangle_t const *const tangle,
flex_trit_t const *const tx_hash,
flex_trit_t *const tail,
bool *const found_tail) {
retcode_t res = RC_OK;
iota_transaction_t next_tx_s;
iota_transaction_t *next_tx = &next_tx_s;
flex_trit_t bundle_hash[FLEX_TRIT_SIZE_243];
bool found_approver = false;
DECLARE_PACK_SINGLE_TX(curr_tx_s, curr_tx, tx_pack);
*found_tail = false;
res = iota_tangle_transaction_load_partial(
tangle, tx_hash, &tx_pack, PARTIAL_TX_MODEL_ESSENCE_CONSENSUS);
if (res != RC_OK || tx_pack.num_loaded == 0) {
return res;
}
uint32_t index = transaction_current_index(curr_tx);
memcpy(bundle_hash, transaction_bundle(curr_tx), FLEX_TRIT_SIZE_243);
iota_stor_pack_t hash_pack;
if ((res = hash_pack_init(&hash_pack, 10)) != RC_OK) {
return res;
}
while (res == RC_OK && index > 0 &&
memcmp(transaction_bundle(curr_tx), bundle_hash, FLEX_TRIT_SIZE_243) ==
0) {
hash_pack_reset(&hash_pack);
if ((res = iota_tangle_transaction_load_hashes_of_approvers(
tangle, transaction_hash(curr_tx), &hash_pack, 0)) != RC_OK) {
break;
}
--index;
uint32_t approver_idx = 0;
found_approver = false;
while (approver_idx < hash_pack.num_loaded) {
flex_trit_t *approver_hash =
(flex_trit_t *)hash_pack.models[approver_idx];
tx_pack.models = (void **)(&next_tx);
hash_pack_reset(&tx_pack);
res = iota_tangle_transaction_load_partial(
tangle, approver_hash, &tx_pack, PARTIAL_TX_MODEL_ESSENCE_CONSENSUS);
if (res != RC_OK || tx_pack.num_loaded == 0) {
break;
}
if (transaction_current_index(next_tx) == index &&
memcmp(transaction_bundle(next_tx), bundle_hash,
FLEX_TRIT_SIZE_243) == 0) {
curr_tx = next_tx;
found_approver = true;
break;
}
}
if (!found_approver) {
break;
}
}
if (transaction_current_index(curr_tx) == 0) {
memcpy(tail, transaction_hash(curr_tx), FLEX_TRIT_SIZE_243);
*found_tail = true;
}
hash_pack_free(&hash_pack);
return res;
}
/*
* State delta operations
*/
retcode_t iota_tangle_state_delta_store(tangle_t const *const tangle,
uint64_t const index,
state_delta_t const *const delta) {
return iota_stor_state_delta_store(&tangle->connection, index, delta);
}
retcode_t iota_tangle_state_delta_load(tangle_t const *const tangle,
uint64_t const index,
state_delta_t *const delta) {
return iota_stor_state_delta_load(&tangle->connection, index, delta);
}
| 2 | 2 |
2024-11-18T21:15:57.486049+00:00 | 2018-01-11T13:20:47 | 15fe7aa007de51e8c6caf855fd23b2efec5d9e9b | {
"blob_id": "15fe7aa007de51e8c6caf855fd23b2efec5d9e9b",
"branch_name": "refs/heads/master",
"committer_date": "2018-01-11T13:20:47",
"content_id": "a9503b2290f4a48014fa427bdb6456be70f04e3c",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "2a7dbaf76388e968463e0b0683e294a94af00b81",
"extension": "c",
"filename": "struct_values.c",
"fork_events_count": 1,
"gha_created_at": "2015-09-25T12:13:33",
"gha_event_created_at": "2017-10-09T11:03:12",
"gha_language": "C++",
"gha_license_id": null,
"github_id": 43138559,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 7633,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/seabolt/src/values/struct_values.c",
"provenance": "stackv2-0112.json.gz:18724",
"repo_name": "technige/seabolt",
"revision_date": "2018-01-11T13:20:47",
"revision_id": "0a46c1e45dbbc5e4c8fe6647a5745d1e1cdecef7",
"snapshot_id": "0743a05246a9b9b53526a3d058cec0fa3afc6c7a",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/technige/seabolt/0a46c1e45dbbc5e4c8fe6647a5745d1e1cdecef7/seabolt/src/values/struct_values.c",
"visit_date": "2023-06-16T12:26:42.299316"
} | stackv2 | /*
* Copyright (c) 2002-2017 "Neo Technology,"
* Network Engine for Objects in Lund AB [http://neotechnology.com]
*
* This file is part of Neo4j.
*
* 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 <assert.h>
#include <stdint.h>
#include <string.h>
#include <values.h>
#include "../protocol/v1.h"
#include "mem.h"
static const char HEX_DIGITS[] = {'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
#define hex3(mem, offset) HEX_DIGITS[((mem)[offset] >> 12) & 0x0F]
#define hex2(mem, offset) HEX_DIGITS[((mem)[offset] >> 8) & 0x0F]
#define hex1(mem, offset) HEX_DIGITS[((mem)[offset] >> 4) & 0x0F]
#define hex0(mem, offset) HEX_DIGITS[(mem)[offset] & 0x0F]
void _to_structure(struct BoltValue* value, enum BoltType type, int16_t code, int32_t size)
{
_recycle(value);
value->data.extended.as_ptr = BoltMem_adjust(value->data.extended.as_ptr, value->data_size,
sizeof_n(struct BoltValue, size));
value->data_size = sizeof_n(struct BoltValue, size);
memset(value->data.extended.as_char, 0, value->data_size);
_set_type(value, type, size);
value->code = code;
}
void BoltValue_to_Structure(struct BoltValue* value, int16_t code, int32_t size)
{
_to_structure(value, BOLT_STRUCTURE, code, size);
}
void BoltValue_to_StructureArray(struct BoltValue* value, int16_t code, int32_t size)
{
_to_structure(value, BOLT_STRUCTURE_ARRAY, code, size);
for (long i = 0; i < size; i++)
{
BoltValue_to_List(&value->data.extended.as_value[i], 0);
}
}
void BoltValue_to_Request(struct BoltValue* value, int16_t code, int32_t size)
{
_to_structure(value, BOLT_REQUEST, code, size);
}
void BoltValue_to_Summary(struct BoltValue* value, int16_t code, int32_t size)
{
_to_structure(value, BOLT_SUMMARY, code, size);
}
int16_t BoltStructure_code(const struct BoltValue* value)
{
assert(BoltValue_type(value) == BOLT_STRUCTURE || BoltValue_type(value) == BOLT_STRUCTURE_ARRAY);
return value->code;
}
int16_t BoltRequest_code(const struct BoltValue* value)
{
assert(BoltValue_type(value) == BOLT_REQUEST);
return value->code;
}
int16_t BoltSummary_code(const struct BoltValue* value)
{
assert(BoltValue_type(value) == BOLT_SUMMARY);
return value->code;
}
struct BoltValue* BoltStructure_value(const struct BoltValue* value, int32_t index)
{
assert(BoltValue_type(value) == BOLT_STRUCTURE);
return &value->data.extended.as_value[index];
}
struct BoltValue* BoltRequest_value(const struct BoltValue* value, int32_t index)
{
assert(BoltValue_type(value) == BOLT_REQUEST);
return &value->data.extended.as_value[index];
}
struct BoltValue* BoltSummary_value(const struct BoltValue* value, int32_t index)
{
assert(BoltValue_type(value) == BOLT_SUMMARY);
return &value->data.extended.as_value[index];
}
int32_t BoltStructureArray_get_size(const struct BoltValue* value, int32_t index)
{
return value->data.extended.as_value[index].size;
}
void BoltStructureArray_set_size(struct BoltValue* value, int32_t index, int32_t size)
{
BoltList_resize(&value->data.extended.as_value[index], size);
}
struct BoltValue* BoltStructureArray_at(const struct BoltValue* value, int32_t array_index, int32_t structure_index)
{
return BoltList_value(&value->data.extended.as_value[array_index], structure_index);
}
int BoltStructure_write(struct BoltValue * value, FILE * file, int32_t protocol_version)
{
assert(BoltValue_type(value) == BOLT_STRUCTURE);
int16_t code = BoltStructure_code(value);
switch (protocol_version)
{
case 1:
{
const char* name = BoltProtocolV1_structure_name(code);
fprintf(file, "$%s", name);
break;
}
default:
fprintf(file, "$#%c%c%c%c", hex3(&code, 0), hex2(&code, 0), hex1(&code, 0), hex0(&code, 0));
}
fprintf(file, "(");
for (int i = 0; i < value->size; i++)
{
if (i > 0) fprintf(file, " ");
BoltValue_write(BoltStructure_value(value, i), file, protocol_version);
}
fprintf(file, ")");
return 0;
}
int BoltStructureArray_write(struct BoltValue * value, FILE * file, int32_t protocol_version)
{
assert(BoltValue_type(value) == BOLT_STRUCTURE_ARRAY);
int16_t code = BoltStructure_code(value);
switch (protocol_version)
{
case 1:
{
const char* name = BoltProtocolV1_structure_name(code);
if (name == NULL)
{
fprintf(file, "$#%c%c%c%c", hex3(&code, 0), hex2(&code, 0), hex1(&code, 0), hex0(&code, 0));
}
else
{
fprintf(file, "$%s", name);
}
break;
}
default:
fprintf(file, "$#%c%c%c%c", hex3(&code, 0), hex2(&code, 0), hex1(&code, 0), hex0(&code, 0));
}
fprintf(file, "[");
for (int i = 0; i < value->size; i++)
{
if (i > 0) fprintf(file, ", ");
for (int j = 0; j < BoltStructureArray_get_size(value, i); j++)
{
if (j > 0) fprintf(file, " ");
BoltValue_write(BoltStructureArray_at(value, i, j), file, protocol_version);
}
}
fprintf(file, "]");
return 0;
}
int BoltRequest_write(struct BoltValue * value, FILE * file, int32_t protocol_version)
{
assert(BoltValue_type(value) == BOLT_REQUEST);
int16_t code = BoltRequest_code(value);
switch (protocol_version)
{
case 1:
{
const char* name = BoltProtocolV1_request_name(code);
if (name == NULL)
{
fprintf(file, "Request<#%c%c>", hex1(&code, 0), hex0(&code, 0));
}
else
{
fprintf(file, "%s", name);
}
break;
}
default:
fprintf(file, "Request<#%c%c>", hex1(&code, 0), hex0(&code, 0));
}
fprintf(file, "(");
for (int i = 0; i < value->size; i++)
{
if (i > 0) fprintf(file, " ");
BoltValue_write(BoltRequest_value(value, i), file, protocol_version);
}
fprintf(file, ")");
return 0;
}
int BoltSummary_write(struct BoltValue * value, FILE * file, int32_t protocol_version)
{
assert(BoltValue_type(value) == BOLT_SUMMARY);
int16_t code = BoltSummary_code(value);
switch (protocol_version)
{
case 1:
{
const char* name = BoltProtocolV1_summary_name(code);
if (name == NULL)
{
fprintf(file, "Summary<#%c%c>", hex1(&code, 0), hex0(&code, 0));
}
else
{
fprintf(file, "%s", name);
}
break;
}
default:
fprintf(file, "Summary<#%c%c>", hex1(&code, 0), hex0(&code, 0));
}
fprintf(file, "(");
for (int i = 0; i < value->size; i++)
{
if (i > 0) fprintf(file, " ");
BoltValue_write(BoltSummary_value(value, i), file, protocol_version);
}
fprintf(file, ")");
return 0;
}
| 2 | 2 |
2024-11-18T21:15:57.620147+00:00 | 2019-11-27T22:32:38 | 7e64cceac82620a748494869eea9492fde891eae | {
"blob_id": "7e64cceac82620a748494869eea9492fde891eae",
"branch_name": "refs/heads/master",
"committer_date": "2019-11-27T22:32:38",
"content_id": "aa7d0c2b54f6d74b90848ce3e4e49372695c4599",
"detected_licenses": [
"Unlicense"
],
"directory_id": "84b23a9c3b7056bfcb11a273d49cdfed51d22380",
"extension": "c",
"filename": "tableware.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 208145268,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3993,
"license": "Unlicense",
"license_type": "permissive",
"path": "/8class/tableware.c",
"provenance": "stackv2-0112.json.gz:18853",
"repo_name": "alexei-bukhgolts/3sem",
"revision_date": "2019-11-27T22:32:38",
"revision_id": "677cbcc12ce09ec6ad5af3e5d04df10b012f4694",
"snapshot_id": "0c377d9dae7de00077c191ff843cb4854cd3ef5d",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/alexei-bukhgolts/3sem/677cbcc12ce09ec6ad5af3e5d04df10b012f4694/8class/tableware.c",
"visit_date": "2020-07-25T03:05:00.938742"
} | stackv2 | #include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <time.h>
#include <limits.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <errno.h>
#define MAX(x, y) (((x) > (y)) ? (x) : (y))
#define TABLEWARE_TYPES_N 20
#define DIRTY_ENTRIES_N 20
int TABLE_SIZE = 30;
int TABLEWARE_COUNT = 0;
typedef enum {
WASHING_COMPLETE = 1,
WIPING_COMPLETE = 2,
DUMMY = LONG_MAX // to force enum to be long
} MessageType;
typedef struct {
long globalTime;
long tablewareType;
} MessagePayload;
typedef struct {
MessageType mtype;
MessagePayload data;
} Message;
typedef struct {
long a;
long b;
} longPair;
longPair washingTimes[TABLEWARE_TYPES_N] = {0};
longPair wipingTimes[TABLEWARE_TYPES_N] = {0};
longPair dirtyTableware[TABLEWARE_TYPES_N] = {0};
long getTime(long tablewareType, int isWiping) { // Otherwise washing
longPair* array = isWiping ? wipingTimes : washingTimes;
for (size_t i = 0; i < TABLEWARE_TYPES_N; i++) {
if (array[i].a == tablewareType) return array[i].b;
}
return 0;
}
void washer(int qid) {
long globalTime = 0;
long freePositionsOnTable = TABLE_SIZE;
Message msg;
int tablewareCount = TABLEWARE_COUNT;
longPair* dirtyPtr = dirtyTableware;
long washingTime;
while (tablewareCount > 0) {
while (freePositionsOnTable > 0) {
while (dirtyPtr->b == 0) {
dirtyPtr += 1;
washingTime = getTime(dirtyPtr->a, 0);
}
(dirtyPtr->b)--;
globalTime += washingTime;
freePositionsOnTable--;
tablewareCount--;
printf("Washed! type:%ld, global time: %ld\n", dirtyPtr->a, globalTime);
fflush(stdout); // Avoid mixing outputs
msg.mtype = WASHING_COMPLETE;
msg.data.globalTime = globalTime;
msg.data.tablewareType = dirtyPtr->a;
msgsnd(qid, &msg, sizeof(MessagePayload), 0);
if (tablewareCount == 0) {
printf("Washer has finished working at %ld.\n", globalTime);
return;
}
}
msgrcv(qid, &msg, sizeof(MessagePayload), WIPING_COMPLETE, 0);
freePositionsOnTable++;
globalTime = MAX(globalTime, msg.data.globalTime);
}
}
void wiper(int qid) {
long globalTime = 0;
Message msg;
int tablewareCount = TABLEWARE_COUNT;
while(tablewareCount > 0) {
msgrcv(qid, &msg, sizeof(MessagePayload), WASHING_COMPLETE, 0);
globalTime = MAX(globalTime, msg.data.globalTime);
globalTime += getTime(msg.data.tablewareType, 1);
tablewareCount--;
printf("Wiped: type:%ld, global time: %ld\n",
msg.data.tablewareType, globalTime);
fflush(stdout); // Avoid mixing outputs
msg.mtype = WIPING_COMPLETE;
msg.data.globalTime = globalTime;
msgsnd(qid, &msg, sizeof(MessagePayload), 0);
}
printf("Wiper has finished working at %ld.\n", globalTime);
return;
}
void fileInput() {
long a, b, i = 0;
FILE* washingTimesFile = fopen("washing-times.txt", "r");
while (fscanf(washingTimesFile, "%ld:%ld", &a, &b) == 2) {
washingTimes[i] = (longPair){.a = a, .b = b};
i++;
}
fclose(washingTimesFile);
FILE* wipingTimesFile = fopen("wiping-times.txt", "r");
while (fscanf(wipingTimesFile, "%ld:%ld", &a, &b) == 2) {
wipingTimes[i] = (longPair){.a = a, .b = b};
i++;
}
fclose(wipingTimesFile);
FILE* dirtyFile = fopen("dirty.txt", "r");
while (fscanf(wipingTimesFile, "%ld:%ld", &a, &b) == 2) {
TABLEWARE_COUNT += b;
dirtyTableware[i] = (longPair){.a = a, .b = b};
i++;
}
fclose(dirtyFile);
}
int main(int argc, char const *argv[]) {
char* TABLE_LIMIT = getenv("TABLE_LIMIT");
if (TABLE_LIMIT == NULL) {
puts("TABLE_LIMIT not specifed");
return 1;
}
TABLE_SIZE = atol(TABLE_LIMIT);
fileInput();
key_t msg_queue_key = ftok("desc", 0);
int qid = msgget(msg_queue_key, IPC_CREAT | 0666);
int pid = fork();
if (pid != 0) {
wiper(qid);
msgctl(qid, IPC_RMID, NULL);
}
else {
washer(qid);
}
return 0;
}
| 2.640625 | 3 |
2024-11-18T21:15:58.038172+00:00 | 2019-06-27T00:49:40 | df36940041febbc27a787b590379d040559f1c18 | {
"blob_id": "df36940041febbc27a787b590379d040559f1c18",
"branch_name": "refs/heads/master",
"committer_date": "2019-06-27T00:49:40",
"content_id": "56c5f78a08394d61295323653837cd21c38ebfa7",
"detected_licenses": [
"BSD-3-Clause-Open-MPI"
],
"directory_id": "7047c2ebf8d7944c6b4467560e190b184d54697d",
"extension": "h",
"filename": "orte_pointer_array.h",
"fork_events_count": 6,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 33182022,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 6740,
"license": "BSD-3-Clause-Open-MPI",
"license_type": "permissive",
"path": "/openmpi-1.2.4/orte/class/orte_pointer_array.h",
"provenance": "stackv2-0112.json.gz:18984",
"repo_name": "NirantK/Text-Summarization",
"revision_date": "2019-06-27T00:49:40",
"revision_id": "45bfa88f77515e1e5c8c6c6b3c64aba4ef8e1575",
"snapshot_id": "7afb7be3810ccfc1341758ce7899fb2e41b49d4c",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/NirantK/Text-Summarization/45bfa88f77515e1e5c8c6c6b3c64aba4ef8e1575/openmpi-1.2.4/orte/class/orte_pointer_array.h",
"visit_date": "2020-06-04T07:12:43.455919"
} | stackv2 | /*
* Copyright (c) 2004-2005 The Trustees of Indiana University and Indiana
* University Research and Technology
* Corporation. All rights reserved.
* Copyright (c) 2004-2005 The University of Tennessee and The University
* of Tennessee Research Foundation. All rights
* reserved.
* Copyright (c) 2004-2005 High Performance Computing Center Stuttgart,
* University of Stuttgart. All rights reserved.
* Copyright (c) 2004-2005 The Regents of the University of California.
* All rights reserved.
* $COPYRIGHT$
*
* Additional copyrights may follow
*
* $HEADER$
*/
/** @file
*
* See ompi_bitmap.h for an explanation of why there is a split
* between OMPI and ORTE for this generic class.
*/
#ifndef ORTE_POINTER_ARRAY_H
#define ORTE_POINTER_ARRAY_H
#include "orte_config.h"
#include "orte/orte_types.h"
#if HAVE_STRING_H
#include <string.h>
#endif /* HAVE_STRING_H */
#include "opal/threads/mutex.h"
#include "opal/class/opal_object.h"
#if defined(c_plusplus) || defined(__cplusplus)
extern "C" {
#endif
/**
* dynamic pointer array
*/
struct orte_pointer_array_t {
/** base class */
opal_object_t super;
/** synchronization object */
opal_mutex_t lock;
/** Index of lowest free element. NOTE: This is only an
optimization to know where to search for the first free slot.
It does \em not necessarily imply indices all above this index
are not taken! */
orte_std_cntr_t lowest_free;
/** number of free elements in the list */
orte_std_cntr_t number_free;
/** size of list, i.e. number of elements in addr */
orte_std_cntr_t size;
/** maximum size list is allowed to reach */
orte_std_cntr_t max_size;
/** growth steps for list */
orte_std_cntr_t block_size;
/** pointer to array of pointers */
void **addr;
};
/**
* Convenience typedef
*/
typedef struct orte_pointer_array_t orte_pointer_array_t;
/**
* Class declaration
*/
ORTE_DECLSPEC OBJ_CLASS_DECLARATION(orte_pointer_array_t);
/**
* Initialize the pointer array
*
* @param array Address of the pointer array object to be initialized
* @param initial_alloc The initial number of elements to be allocated
* @param max_size Maximum size the array is allowed to reach
* @param block_size Number of array elements to be added when increase required
*
* @retval ORTE_SUCCESS Initialization successful
* @retval ORTE_ERROR(s) Appropriate error code
*
*/
ORTE_DECLSPEC int orte_pointer_array_init(orte_pointer_array_t **array,
orte_std_cntr_t initial_allocation,
orte_std_cntr_t max_size, orte_std_cntr_t block_size);
/**
* Add a pointer to the array (Grow the array, if need be)
*
* @param array Pointer to array (IN)
* @param ptr Pointer value (IN)
*
* @param (OUT) Index of inserted array element.
* @return Return value less than zero indicates an error.
*/
ORTE_DECLSPEC int orte_pointer_array_add(orte_std_cntr_t *index, orte_pointer_array_t *array, void *ptr);
/**
* Set the value of an element in array
* Automatically extend array if required.
*
* @param array Pointer to array (IN)
* @param index Index of element to be reset (IN)
* @param value New value to be set at element index (IN)
*
* @return Error code. (-1) indicates an error.
*/
ORTE_DECLSPEC int orte_pointer_array_set_item(orte_pointer_array_t *array,
orte_std_cntr_t index, void *value);
/**
* Get the value of an element in array
*
* @param array Pointer to array (IN)
* @param index Index of element to be returned (IN)
*
* @return Error code. NULL indicates an error.
*/
static inline void *orte_pointer_array_get_item(orte_pointer_array_t *table,
orte_std_cntr_t index)
{
void *p;
OPAL_THREAD_LOCK(&(table->lock));
p = table->addr[index];
OPAL_THREAD_UNLOCK(&(table->lock));
return p;
}
/**
* Get the size of the pointer array
*
* @param array Pointer to array (IN)
*
* @returns size Size of the array
*
* Simple inline function to return the size of the array in order to
* hide the member field from external users.
*/
static inline orte_std_cntr_t orte_pointer_array_get_size(orte_pointer_array_t *array)
{
return array->size;
}
/**
* Set the size of the pointer array
*
* @param array Pointer to array (IN)
*
* @param size Desired size of the array
*
* Simple function to set the size of the array in order to
* hide the member field from external users.
*/
ORTE_DECLSPEC int orte_pointer_array_set_size(orte_pointer_array_t *array, orte_std_cntr_t size);
/**
* Clear the pointer array
*
* @param array Pointer to array (IN)
*
* @returns void
*
* Simple inline function to clear the pointer array and reset all
* counters.
*/
static inline void orte_pointer_array_clear(orte_pointer_array_t *array)
{
OPAL_THREAD_LOCK(&(array->lock));
/* set the array elements to NULL */
memset(array->addr, 0, array->size * sizeof(void*));
array->lowest_free = 0;
array->number_free = array->size;
OPAL_THREAD_UNLOCK(&(array->lock));
}
/**
* Clear the pointer array, freeing any storage
*
* @param array Pointer to array (IN)
*
* @returns void
*
* Simple inline function to clear the pointer array and reset all
* counters.
*/
static inline void orte_pointer_array_free_clear(orte_pointer_array_t *array)
{
orte_std_cntr_t i;
OPAL_THREAD_LOCK(&(array->lock));
for (i=0; i < array->size; i++) {
if (NULL != array->addr[i]) free(array->addr[i]);
array->addr[i] = NULL;
}
array->lowest_free = 0;
array->number_free = array->size;
OPAL_THREAD_UNLOCK(&(array->lock));
}
/**
* Test whether a certain element is already in use. If not yet
* in use, reserve it.
*
* @param array Pointer to array (IN)
* @param index Index of element to be tested (IN)
* @param value New value to be set at element index (IN)
*
* @return true/false True if element could be reserved
* False if element could not be reserved (e.g., in use).
*
* In contrary to array_set, this function does not allow to overwrite
* a value, unless the previous value is NULL ( equiv. to free ).
*/
ORTE_DECLSPEC bool orte_pointer_array_test_and_set_item (orte_pointer_array_t *table,
orte_std_cntr_t index,
void *value);
#if defined(c_plusplus) || defined(__cplusplus)
}
#endif
#endif /* OMPI_POINTER_ARRAY_H */
| 2.203125 | 2 |
2024-11-18T21:15:58.369438+00:00 | 2012-01-27T08:43:21 | 962a0dc91d982c7fc7448eb1758a375681472b40 | {
"blob_id": "962a0dc91d982c7fc7448eb1758a375681472b40",
"branch_name": "refs/heads/master",
"committer_date": "2012-01-27T08:43:21",
"content_id": "f9bdeb42e5a265d961031457cf53cfb96380b9f2",
"detected_licenses": [
"MIT-Modern-Variant"
],
"directory_id": "7400ccd91c6d2ce3f8a30e9485f4d65a44b317f6",
"extension": "c",
"filename": "step3_testJoin2.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 32145087,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 985,
"license": "MIT-Modern-Variant",
"license_type": "permissive",
"path": "/code/test/step3_testJoin2.c",
"provenance": "stackv2-0112.json.gz:19114",
"repo_name": "rohartb/projet-burritos",
"revision_date": "2012-01-27T08:43:21",
"revision_id": "a93d56a66ba2ef0ab8ba29433c61b8dc0d77f744",
"snapshot_id": "2b798223ee921f420a2871ba2cd9840ee060ea56",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/rohartb/projet-burritos/a93d56a66ba2ef0ab8ba29433c61b8dc0d77f744/code/test/step3_testJoin2.c",
"visit_date": "2020-03-26T17:32:07.416463"
} | stackv2 | #include "syscall.h"
// test du UserThreadJoin
int thID;
int arg=0;
void function6(void * a){
arg++;
PutString("thread n ");
PutInt((int) a);
PutString(" fini!\n");
}
//fonction qui creee un thread et l'attend
void function5(void * a){
arg++;
thID=UserThreadCreate(function6,(void *)arg);
UserThreadJoin(thID);
PutString("thread n ");
PutInt((int) a);
PutString(" fini!\n");
}
//fonction qui creee un thread et l'attend
void function4(void * a){
arg++;
thID=UserThreadCreate(function5,(void *)arg);
UserThreadJoin(thID);
PutString("thread n ");
PutInt((int) a);
PutString(" fini!\n");
}
//fonction qui creee un thread et l'attend
void function3(void * a){
arg++;
thID=UserThreadCreate(function4,(void *)arg);
UserThreadJoin(thID);
PutString("thread n ");
PutInt((int) a);
PutString(" fini!\n");
}
int main(){
PutString("test2:\n");
PutString("Chaque thread créé attend le suivant:\n");
arg=0;
UserThreadCreate(function3,(void *)arg);
Exit(0);
}
| 2.84375 | 3 |
2024-11-18T21:15:58.440077+00:00 | 2017-08-02T22:39:19 | 823115f681ed7f9b51ecb03b8ce233e23dc20eaf | {
"blob_id": "823115f681ed7f9b51ecb03b8ce233e23dc20eaf",
"branch_name": "refs/heads/master",
"committer_date": "2017-08-02T22:39:19",
"content_id": "2318a67d6d740b56ca7d05fd58f272eabe6eb077",
"detected_licenses": [
"MIT"
],
"directory_id": "b617478c1cde912926737f31d9bbcd97a7ef95e4",
"extension": "c",
"filename": "sort.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 87109968,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1074,
"license": "MIT",
"license_type": "permissive",
"path": "/skiena/algorithms/sort.c",
"provenance": "stackv2-0112.json.gz:19244",
"repo_name": "kjchalup/algorithm_design",
"revision_date": "2017-08-02T22:39:19",
"revision_id": "99176322b83d120f0ceb83dbba254a6e15f95264",
"snapshot_id": "bb000764a0bfce2d2365eebda7a306799a7eb230",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/kjchalup/algorithm_design/99176322b83d120f0ceb83dbba254a6e15f95264/skiena/algorithms/sort.c",
"visit_date": "2021-01-18T23:25:17.106476"
} | stackv2 | #include <stdlib.h>
#include <stdio.h>
#include "algorithms.h"
void quick(void **, int, int, int, void **, const comp_fn);
void quicksort(void **arr, int n, const comp_fn f_comp){
/* Sort an array of n items in n log(n) time. */
void **copy = (void *) calloc(n, sizeof(void *));
quick(arr, 0, n, 0, copy, f_comp);
free(copy);
}
void quick(void **arr, int low, int high,
int pivot, void **copy, const comp_fn f_comp){
int i, i_low, i_high, new_pivot;
i_low = low;
i_high = high - 1;
// Sort to the left and right of pivot.
for (i = low; i < high; i++){
if (i == pivot) continue;
if (f_comp(arr[i], arr[pivot]) <= 0)
copy[i_low++] = arr[i];
else
copy[i_high--] = arr[i];
}
new_pivot = i_low;
copy[new_pivot] = arr[pivot];
// Copy over to the main array.
for (i = low; i < high; i++)
arr[i] = copy[i];
// Continue recursively.
if (low < new_pivot - 1)
quick(arr, low, new_pivot, low, copy, f_comp);
if (high > new_pivot + 2)
quick(arr, new_pivot + 1, high, new_pivot + 1, copy, f_comp);
}
| 3.296875 | 3 |
2024-11-18T21:15:58.603032+00:00 | 2018-10-25T19:08:56 | 648bc27d56f9b7989d2c7e504285bcac9d7b0f8f | {
"blob_id": "648bc27d56f9b7989d2c7e504285bcac9d7b0f8f",
"branch_name": "refs/heads/master",
"committer_date": "2018-10-25T19:08:56",
"content_id": "074ebe4777307e0007232572309653ea09b17f2c",
"detected_licenses": [
"MIT",
"Zlib"
],
"directory_id": "b087c506d4384db1db70b68471c3053a082adcb0",
"extension": "c",
"filename": "concat.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 118653204,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 431,
"license": "MIT,Zlib",
"license_type": "permissive",
"path": "/lib/concatf/sources/concat.c",
"provenance": "stackv2-0112.json.gz:19374",
"repo_name": "Gegel85/VEDA",
"revision_date": "2018-10-25T19:08:56",
"revision_id": "25603d102d20b8f5a6eb9494746f3bc1de29ebb0",
"snapshot_id": "f0c320042fddd66a9b6d7f57b16dfd8eb5980475",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/Gegel85/VEDA/25603d102d20b8f5a6eb9494746f3bc1de29ebb0/lib/concatf/sources/concat.c",
"visit_date": "2021-05-05T05:04:13.531192"
} | stackv2 | #include <string.h>
#include <stdlib.h>
#include <stdbool.h>
char *concat(char *str1, char *str2, bool free1, bool free2)
{
char *result;
if (!str1 || !str2) {
if (free1)
free(str1);
if (free2)
free(str2);
return (NULL);
}
result = malloc(strlen(str1) + strlen(str2) + 1);
if (result) {
strcpy(result, str1);
strcat(result, str2);
}
if (free1)
free(str1);
if (free2)
free(str2);
return (result);
} | 2.890625 | 3 |
2024-11-18T21:15:58.780074+00:00 | 2020-05-04T04:32:25 | 32803fd53d8940cc94ca4ac09aed2117fb2c0492 | {
"blob_id": "32803fd53d8940cc94ca4ac09aed2117fb2c0492",
"branch_name": "refs/heads/master",
"committer_date": "2020-05-04T04:32:25",
"content_id": "f59ab94add04eb66017ce2758f2b56e459a33aae",
"detected_licenses": [
"MIT"
],
"directory_id": "1929c33f96719af6ce62da7d76e5cba6d361eea8",
"extension": "c",
"filename": "A.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 261061115,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 263,
"license": "MIT",
"license_type": "permissive",
"path": "/estruturaDeRepeticao/A.c",
"provenance": "stackv2-0112.json.gz:19632",
"repo_name": "RuthMaria/algoritmo",
"revision_date": "2020-05-04T04:32:25",
"revision_id": "ec9ebf629598dd75a05e33861706f1a6bc956cd5",
"snapshot_id": "b863a6d3610fbce4e29a3fcf3641f2179b7df818",
"src_encoding": "ISO-8859-1",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/RuthMaria/algoritmo/ec9ebf629598dd75a05e33861706f1a6bc956cd5/estruturaDeRepeticao/A.c",
"visit_date": "2022-06-26T09:50:28.224747"
} | stackv2 | /*
a)Mostrar todos os números inteiros de 5 a 50.
*/
#include<stdio.h>
#include<stdlib.h>
main(){
int i;
i = 5;
while(i <= 50){
printf("\n %d", i);
i++;
}
getch();
}
| 3.03125 | 3 |
2024-11-18T21:15:58.921786+00:00 | 2021-09-30T08:51:01 | 5a1c4040f693bfd7d5733b4b6d4e6b27de8d4a13 | {
"blob_id": "5a1c4040f693bfd7d5733b4b6d4e6b27de8d4a13",
"branch_name": "refs/heads/main",
"committer_date": "2021-09-30T08:51:01",
"content_id": "d6ea1a260ff87771ef6f11fe494be2c1644dc7f9",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "f354f49d62e9498623aec95eb8f90f09aa1f12e0",
"extension": "c",
"filename": "bmp_gen.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 411970841,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3128,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/RTT-Project/applications/bmp_gen.c",
"provenance": "stackv2-0112.json.gz:19888",
"repo_name": "zhenzhen1003/Defect-Detection",
"revision_date": "2021-09-30T08:51:01",
"revision_id": "45d28535092d8268a26b2180c11de15848c940d8",
"snapshot_id": "7a65417d5ba971a45ac48230f1943e31a2b68bef",
"src_encoding": "GB18030",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/zhenzhen1003/Defect-Detection/45d28535092d8268a26b2180c11de15848c940d8/RTT-Project/applications/bmp_gen.c",
"visit_date": "2023-08-06T17:42:50.172259"
} | stackv2 | /*
* Copyright (c) 2006-2021, RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
* 2021-09-23 zhenzhen1003 the first version
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include "bmp_gen.h"
/*
按小端字节序来存储,且数据块一般组织成4字节对齐。
图像数据区也不例外,按每行图像的数据字节,按4字节对齐。
图像数据按行倒序存放,先存储最后一行图像数据,然后依次存放,直到第一行数据。
这样设计,可能是为了从文件尾部往前读的时候,能够直接顺序读出图像数据吧。
*/
typedef union {
uint8_t bytes[4];
uint32_t value;
}LITTLE;
/*
* @fileName: bmp file name: test.bmp
* @width : bmp pixel width: 32bit
* @height : bmp pixel width: 32bit
* @color : R[8]/G[8]/B[8]
* @note : BMP is l endian mode
*/
uint8_t* bmp_gen_test(uint32_t width, uint32_t height, uint8_t* color)
{
uint32_t i, j;
LITTLE l_width, l_height, l_bfSize, l_biSizeImage;
uint32_t width_r = (width * 24 / 8 + 3) / 4 * 4;
uint32_t bfSize = width_r * height + 54 + 2;
uint32_t biSizeImage = width_r * height;
uint32_t size = width_r - width * 3 + 54 + width * height * 3 + 2;
//rt_kprintf("%d ",size);
uint8_t* data = (uint8_t*)rt_malloc(size);
l_width.value = width;
l_height.value = height;
l_bfSize.value = bfSize;
l_biSizeImage.value = biSizeImage;
/* BMP file format: www.cnblogs.com/wainiwann/p/7086844.html */
uint8_t bmp_head_map[54] = {
/* bmp file header: 14 byte */
0x42, 0x4d,
// bmp pixel size: width * height * 3 + 54
l_bfSize.bytes[0], l_bfSize.bytes[1], l_bfSize.bytes[2], l_bfSize.bytes[3],
0, 0 , 0, 0,
54, 0 , 0, 0, /* 14+40=54 */
/* bmp map info: 40 byte */
40, 0, 0, 0,
//width
l_width.bytes[0], l_width.bytes[1], l_width.bytes[2], l_width.bytes[3],
//height
l_height.bytes[0], l_height.bytes[1], l_height.bytes[2], l_height.bytes[3],
1, 0,
24, 00, /* 24 bit: R[8]/G[8]/B[8] */
0, 0, 0, 0, //biCompression:0
// 0, 0, 0, 0, //biSizeImage锛欰2 00 00 00=162
l_biSizeImage.bytes[0], l_biSizeImage.bytes[1], l_biSizeImage.bytes[2], l_biSizeImage.bytes[3],
0, 0, 0, 0, //biXPelsPerMeter: 60 0F 00 00
0, 0, 0, 0, //biYPelsPerMeter
0, 0, 0, 0, //biClrUsed
0, 0, 0, 0 //biClrImportant
};
/* write in binary format */
for(int k = 0; k < 54; k++){
data[k] = bmp_head_map[k];
}
for (i = 0; i < height; i++) {
for (j = 0; j < width; j++) {
for (int k = 2; k >= 0; k--) {
data[54 + i*width * 3 + j * 3 + (2 - k)] = color[(height - i - 1) * width * 3 + j * 3 + k];
}
}
//4 byte align
for(j = 0; j < width_r-width*3; j++)
data[size - width_r-width*3 - 2 + j] = 0;
}
data[size - 2] = 0;
data[size - 1] = 0;
return data;
}
| 2.53125 | 3 |
2024-11-18T21:15:59.352832+00:00 | 2018-01-24T14:52:14 | 37dae1a5fe247b0319a3d0af5091039de3d16dd3 | {
"blob_id": "37dae1a5fe247b0319a3d0af5091039de3d16dd3",
"branch_name": "refs/heads/master",
"committer_date": "2018-01-24T14:52:14",
"content_id": "b1a132e19dd396e477a1c753c25db755ccfe0576",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "6ebfe81ecf73508ae8f520ce448387a9065dee5a",
"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": 200,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/ExternalDependencies/RegressionTests/augmentation/main.c",
"provenance": "stackv2-0112.json.gz:20145",
"repo_name": "clayne/DIVA",
"revision_date": "2018-01-24T14:52:14",
"revision_id": "fdc066d84f5599427ecc6eb71fd7648ea8833b37",
"snapshot_id": "48ba96bd9c643d736fa8e9d3090da88a805e7b6f",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/clayne/DIVA/fdc066d84f5599427ecc6eb71fd7648ea8833b37/ExternalDependencies/RegressionTests/augmentation/main.c",
"visit_date": "2023-03-17T04:12:19.760279"
} | stackv2 | #include <stdio.h>
void print_sample(char * str)
{
printf("%s\n",str);
print_sample("Done!");
}
int main()
{
for (int i=0; i<10; i++)
print_sample("printing...");
return 0;
}
| 2.484375 | 2 |
2024-11-18T21:15:59.436838+00:00 | 2020-04-11T16:56:12 | 0f33508d11e8c8ccbcfbfa08146a1b3763dbb870 | {
"blob_id": "0f33508d11e8c8ccbcfbfa08146a1b3763dbb870",
"branch_name": "refs/heads/master",
"committer_date": "2020-04-11T16:56:12",
"content_id": "b92d084a35b4ce0a54dff5de628b6011fb33511e",
"detected_licenses": [
"MIT"
],
"directory_id": "8ce615c6a5da929238742b7b10846ad9a852422a",
"extension": "c",
"filename": "main.c",
"fork_events_count": 0,
"gha_created_at": "2020-02-17T12:09:27",
"gha_event_created_at": "2020-02-17T12:09:27",
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 241098543,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 815,
"license": "MIT",
"license_type": "permissive",
"path": "/level1/p01_runningLetter/main.c",
"provenance": "stackv2-0112.json.gz:20273",
"repo_name": "ouovowo/c2020",
"revision_date": "2020-04-11T16:56:12",
"revision_id": "93b2c6886a36431a0f293d062f3bf54b2b6bee66",
"snapshot_id": "b628e8508152fb0251e6c3c4b7a2356894ddfeac",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ouovowo/c2020/93b2c6886a36431a0f293d062f3bf54b2b6bee66/level1/p01_runningLetter/main.c",
"visit_date": "2021-01-05T18:06:34.367378"
} | stackv2 | #include <stdio.h>
#include <stdlib.h>
#include <windows.h> // #include <unistd.h>
#define WORD "Look_at_Me"
#define SECOND 1000
#define WIDTH 80
#define FPS 30
const int TERMINAL = WIDTH - sizeof(WORD) / sizeof(char) + 1;
int position = 0, delta = 1;
void step();
void render();
int main() {
char command[100];
sprintf(command, "mode con cols=%d lines=1", WIDTH);
system("title runningLetter");
system(command);
for (;;) {
render();
step();
}
return 0;
}
void step() {
position += delta;
if (position < 0 || position > TERMINAL) {
position -= delta;
delta *= -1;
position += delta;
}
}
void render() {
system("cls");
for (int p = 0; p < position; p++) {
printf(" ");
}
printf(WORD);
Sleep(SECOND / FPS); // usleep(SECOND / FPS * 1000)
}
| 2.5625 | 3 |
2024-11-18T21:15:59.954726+00:00 | 2023-08-21T06:22:41 | 6d0d2165fd1e3e4d0c875cc84efd263e63639ec3 | {
"blob_id": "6d0d2165fd1e3e4d0c875cc84efd263e63639ec3",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-21T06:22:41",
"content_id": "ce92ee1f3cd45c5b1afe88f1eed3d2e3c5554359",
"detected_licenses": [
"BSD-3-Clause",
"BSD-2-Clause"
],
"directory_id": "0d7fc78bb265197a9c81fded765f70871e4668e6",
"extension": "c",
"filename": "test_options.c",
"fork_events_count": 393,
"gha_created_at": "2015-07-13T08:19:17",
"gha_event_created_at": "2023-07-11T09:23:42",
"gha_language": "C",
"gha_license_id": "NOASSERTION",
"github_id": 38999874,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 6609,
"license": "BSD-3-Clause,BSD-2-Clause",
"license_type": "permissive",
"path": "/test/test_options.c",
"provenance": "stackv2-0112.json.gz:20531",
"repo_name": "kkos/oniguruma",
"revision_date": "2023-08-21T06:22:41",
"revision_id": "1713dfaed25f9ef680ba998e83767487f80cf5ae",
"snapshot_id": "7e10a9d6e8bda7940cf66ee6b30883c3c37804f1",
"src_encoding": "UTF-8",
"star_events_count": 2164,
"url": "https://raw.githubusercontent.com/kkos/oniguruma/1713dfaed25f9ef680ba998e83767487f80cf5ae/test/test_options.c",
"visit_date": "2023-09-04T16:44:46.396571"
} | stackv2 | /*
* test_options.c
* Copyright (c) 2020-2021 K.Kosako
*/
#ifdef ONIG_ESCAPE_UCHAR_COLLISION
#undef ONIG_ESCAPE_UCHAR_COLLISION
#endif
#include <stdio.h>
#include "oniguruma.h"
#include <string.h>
#define SLEN(s) strlen(s)
static int nsucc = 0;
static int nfail = 0;
static int nerror = 0;
#ifdef __TRUSTINSOFT_ANALYZER__
static int nall = 0;
#endif
static FILE* err_file;
static OnigRegion* region;
static void xx(OnigOptionType options, char* pattern, char* str,
int from, int to, int mem, int not, int error_no, int line_no)
{
#ifdef __TRUSTINSOFT_ANALYZER__
if (nall++ % TIS_TEST_CHOOSE_MAX != TIS_TEST_CHOOSE_CURRENT) return;
#endif
int r;
regex_t* reg;
OnigErrorInfo einfo;
r = onig_new(®, (UChar* )pattern, (UChar* )(pattern + SLEN(pattern)),
options, ONIG_ENCODING_UTF8, ONIG_SYNTAX_DEFAULT, &einfo);
if (r) {
char s[ONIG_MAX_ERROR_MESSAGE_LEN];
if (error_no == 0) {
onig_error_code_to_str((UChar* )s, r, &einfo);
fprintf(err_file, "ERROR: %s /%s/ #%d\n", s, pattern, line_no);
nerror++;
}
else {
if (r == error_no) {
fprintf(stdout, "OK(ERROR): /%s/ %d #%d\n", pattern, r, line_no);
nsucc++;
}
else {
fprintf(stdout, "FAIL(ERROR): /%s/ '%s', %d, %d #%d\n", pattern, str,
error_no, r, line_no);
nfail++;
}
}
return ;
}
r = onig_search(reg, (UChar* )str, (UChar* )(str + SLEN(str)),
(UChar* )str, (UChar* )(str + SLEN(str)),
region, options);
if (r < ONIG_MISMATCH) {
char s[ONIG_MAX_ERROR_MESSAGE_LEN];
if (error_no == 0) {
onig_error_code_to_str((UChar* )s, r);
fprintf(err_file, "ERROR: %s /%s/ #%d\n", s, pattern, line_no);
nerror++;
}
else {
if (r == error_no) {
fprintf(stdout, "OK(ERROR): /%s/ '%s', %d #%d\n",
pattern, str, r, line_no);
nsucc++;
}
else {
fprintf(stdout, "FAIL ERROR NO: /%s/ '%s', %d, %d #%d\n",
pattern, str, error_no, r, line_no);
nfail++;
}
}
return ;
}
if (r == ONIG_MISMATCH) {
if (not) {
fprintf(stdout, "OK(N): /%s/ '%s' #%d\n", pattern, str, line_no);
nsucc++;
}
else {
fprintf(stdout, "FAIL: /%s/ '%s' #%d\n", pattern, str, line_no);
nfail++;
}
}
else {
if (not) {
fprintf(stdout, "FAIL(N): /%s/ '%s' #%d\n", pattern, str, line_no);
nfail++;
}
else {
if (region->beg[mem] == from && region->end[mem] == to) {
fprintf(stdout, "OK: /%s/ '%s' #%d\n", pattern, str, line_no);
nsucc++;
}
else {
fprintf(stdout, "FAIL: /%s/ '%s' %d-%d : %d-%d #%d\n", pattern, str,
from, to, region->beg[mem], region->end[mem], line_no);
nfail++;
}
}
}
onig_free(reg);
}
static void xx2(OnigOptionType options, char* pattern, char* str,
int from, int to, int line_no)
{
xx(options, pattern, str, from, to, 0, 0, 0, line_no);
}
static void xx3(OnigOptionType options, char* pattern, char* str,
int from, int to, int mem, int line_no)
{
xx(options, pattern, str, from, to, mem, 0, 0, line_no);
}
static void xn(OnigOptionType options, char* pattern, char* str, int line_no)
{
xx(options, pattern, str, 0, 0, 0, 1, 0, line_no);
}
#if 0
static void xe(OnigOptionType options, char* pattern, char* str,
int error_no, int line_no)
{
xx(options, pattern, str, 0, 0, 0, 0, error_no, line_no);
}
#endif
#define x2(o,p,s,f,t) xx2(o,p,s,f,t, __LINE__)
#define x3(o,p,s,f,t,m) xx3(o,p,s,f,t,m, __LINE__)
#define n(o,p,s) xn(o,p,s, __LINE__)
#define e(o,p,s,en) xe(o,p,s,en, __LINE__)
#define OIA (ONIG_OPTION_IGNORECASE | ONIG_OPTION_IGNORECASE_IS_ASCII)
extern int main(int argc, char* argv[])
{
OnigEncoding use_encs[1];
use_encs[0] = ONIG_ENCODING_UTF8;
onig_initialize(use_encs, sizeof(use_encs)/sizeof(use_encs[0]));
err_file = stdout;
region = onig_region_new();
x2(ONIG_OPTION_IGNORECASE, "a", "A", 0, 1);
n(ONIG_OPTION_IGNORECASE_IS_ASCII, "a", "A");
/* KELVIN SIGN */
x2(ONIG_OPTION_IGNORECASE, "\xe2\x84\xaa", "k", 0, 1);
x2(ONIG_OPTION_IGNORECASE, "k", "\xe2\x84\xaa", 0, 3);
n(OIA, "\xe2\x84\xaa", "k");
n(OIA, "k", "\xe2\x84\xaa");
x2(OIA, "a", "a", 0, 1);
x2(OIA, "A", "A", 0, 1);
x2(OIA, "a", "A", 0, 1);
x2(OIA, "A", "a", 0, 1);
x2(OIA, "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz", 0, 26);
x2(OIA, "abcdefghijklmnopqrstuvwxyz", "ABCDEFGHIJKLMNOPQRSTUVWXYZ", 0, 26);
x2(OIA, "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "ABCabcdefghijklmnopqrstuvwxyz", 3, 29);
x2(OIA, "abcdefghijklmnopqrstuvwxyz", "abcABCDEFGHIJKLMNOPQRSTUVWXYZ", 3, 29);
x3(OIA, "#%(a!;)(b&)", "#%A!;B&", 5, 7, 2);
x2(ONIG_OPTION_IGNORECASE, "ss", "\xc3\x9f", 0, 2);
x2(ONIG_OPTION_IGNORECASE, "\xc3\x9f", "SS", 0, 2);
n(OIA, "ss", "\xc3\x9f");
n(OIA, "\xc3\x9f", "ss");
x2(OIA, "ss", "SS", 0, 2);
x2(OIA, "Ss", "sS", 0, 2);
n(ONIG_OPTION_NOTBOL, "^ab", "ab");
n(ONIG_OPTION_NOTBOL, "\\Aab", "ab");
n(ONIG_OPTION_NOTEOL, "ab$", "ab");
n(ONIG_OPTION_NOTEOL, "ab\\z", "ab");
n(ONIG_OPTION_NOTEOL, "ab\\Z", "ab");
n(ONIG_OPTION_NOTEOL, "ab\\Z", "ab\n");
n(ONIG_OPTION_NOT_BEGIN_STRING, "\\Aab", "ab");
n(ONIG_OPTION_NOT_END_STRING, "ab\\z", "ab");
n(ONIG_OPTION_NOT_END_STRING, "ab\\Z", "ab");
n(ONIG_OPTION_NOT_END_STRING, "ab\\Z", "ab\n");
x2(ONIG_OPTION_NONE, "a|abc", "abc", 0, 1);
x2(ONIG_OPTION_NONE, "(a|abc)\\Z", "abc", 0, 3);
x2(ONIG_OPTION_MATCH_WHOLE_STRING, "a|abc", "abc", 0, 3);
x2(ONIG_OPTION_MATCH_WHOLE_STRING, "a|abc", "a", 0, 1);
x2(ONIG_OPTION_WORD_IS_ASCII, "\\w", "@g", 1, 2);
n(ONIG_OPTION_WORD_IS_ASCII, "\\w", "あ");
x2(ONIG_OPTION_NONE, "\\d", "1", 0, 3);
n(ONIG_OPTION_DIGIT_IS_ASCII, "\\d", "1");
x2(ONIG_OPTION_SPACE_IS_ASCII, "\\s", " ", 0, 1);
x2(ONIG_OPTION_NONE, "\\s", " ", 0, 3);
n(ONIG_OPTION_SPACE_IS_ASCII, "\\s", " ");
x2(ONIG_OPTION_POSIX_IS_ASCII, "\\w\\d\\s", "c3 ", 0, 3);
n(ONIG_OPTION_POSIX_IS_ASCII, "\\w|\\d|\\s", "あ4 ");
x2(ONIG_OPTION_EXTEND, " abc \n def", "abcdef", 0, 6);
x2(ONIG_OPTION_FIND_LONGEST, "\\w+", "abc defg hij", 4, 8);
x2(ONIG_OPTION_FIND_NOT_EMPTY, "\\w*", "@@@ abc defg hij", 4, 7);
fprintf(stdout,
"\nRESULT SUCC: %4d, FAIL: %d, ERROR: %d (by Oniguruma %s)\n",
nsucc, nfail, nerror, onig_version());
onig_region_free(region, 1);
onig_end();
return ((nfail == 0 && nerror == 0) ? 0 : -1);
}
| 2.15625 | 2 |
2024-11-18T21:16:01.219625+00:00 | 2012-01-10T22:18:03 | d400c787438f6ccf1d1d585055cee9fd049f9aa4 | {
"blob_id": "d400c787438f6ccf1d1d585055cee9fd049f9aa4",
"branch_name": "refs/heads/master",
"committer_date": "2012-01-10T22:19:36",
"content_id": "f9e7c5b541a95bc2dfd58a15e84e334abb3c4734",
"detected_licenses": [
"ISC"
],
"directory_id": "596fea8f5b6bef94c81ae0171ab8025d35710dca",
"extension": "c",
"filename": "BASCommon.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": 1500,
"license": "ISC",
"license_type": "permissive",
"path": "/BASCommon.c",
"provenance": "stackv2-0112.json.gz:21687",
"repo_name": "alex-tools/vpnoo",
"revision_date": "2012-01-10T22:18:03",
"revision_id": "03708690ecc2998381b565338d36f889d5ef3284",
"snapshot_id": "94f82bb60ee4edeeeb27d930570b574b6bd833bc",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/alex-tools/vpnoo/03708690ecc2998381b565338d36f889d5ef3284/BASCommon.c",
"visit_date": "2020-12-24T18:55:10.304903"
} | stackv2 | /*
* BASCommon.c
* vpnoo
*
*/
#include <fcntl.h>
#include <sys/types.h>
#include <sys/uio.h>
#include <unistd.h>
#include "BASCommon.h"
const BASCommandSpec kVpnooCommandSet[] = {
{ kVpnooGetHashCommand,
NULL,
NULL,
NULL,
NULL,
},
{ kVpnooStartStopRacoonCommand,
kVpnooStartStopRacoonRightName,
"allow",
"You must be authorized to start or stop IPsec daemon.",
NULL,
},
{ kVpnooStartRacoonCtlCommand,
kVpnooStartRacoonCtlRightName,
"allow",
"You must be authorized to invoke IPsec control program.",
NULL,
},
{ NULL,
NULL,
NULL,
NULL,
NULL,
}
};
unsigned int hashFile(const char *path) {
int fd;
int err;
char str;
unsigned int hash = 0xAAAAAAAA;
unsigned int i = 0;
fd = open(path, O_RDONLY);
if (fd == -1) {
return 0;
}
// We use a simple hash algorithm from Arash Partow
i = 0;
while (1) {
err = read(fd, &str, 1);
if (err == 0) {
break;
}
if ((err == -1) && (errno == EINTR)) {
continue;
}
if (err == -1) {
return 0;
}
i++;
hash ^= ((i & 1) == 0) ? ( (hash << 7) ^ str * (hash >> 3)) :
(~((hash << 11) + (str ^ (hash >> 5))));
}
close(fd);
if (hash == 0) {
hash = 1;
}
return hash;
}
| 2.5 | 2 |
2024-11-18T21:16:01.618251+00:00 | 2020-06-17T17:45:50 | 4b4b8e9d153411415dad074e87e8a1f2eb4a23e4 | {
"blob_id": "4b4b8e9d153411415dad074e87e8a1f2eb4a23e4",
"branch_name": "refs/heads/master",
"committer_date": "2020-06-17T17:45:50",
"content_id": "70a94e53b9cdc97c850e74b4313d94ab7eeb4aca",
"detected_licenses": [
"ISC"
],
"directory_id": "766aab3ae97e3affa4f0838802f4518728aa946d",
"extension": "c",
"filename": "pic32mz-interrupt-latency-test.c",
"fork_events_count": 0,
"gha_created_at": "2020-05-12T16:51:40",
"gha_event_created_at": "2020-05-12T16:51:41",
"gha_language": null,
"gha_license_id": "ISC",
"github_id": 263396885,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2472,
"license": "ISC",
"license_type": "permissive",
"path": "/drivers/pic32mz-interrupt-latency-test.c",
"provenance": "stackv2-0112.json.gz:21945",
"repo_name": "zanon005/hellfire-hypervisor",
"revision_date": "2020-06-17T17:45:50",
"revision_id": "695ebba6ce8cd5c7c547158d68c8351c4f43ddef",
"snapshot_id": "3d213d322a01192a37dd373b16e88305050dec3a",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/zanon005/hellfire-hypervisor/695ebba6ce8cd5c7c547158d68c8351c4f43ddef/drivers/pic32mz-interrupt-latency-test.c",
"visit_date": "2022-11-10T20:30:54.560561"
} | stackv2 | /*
Copyright (c) 2016, prpl Foundation
Permission to use, copy, modify, and/or distribute this software for any purpose with or without
fee is hereby granted, provided that the above copyright notice and this permission notice appear
in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE
INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE
FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
This code was written by Carlos Moratelli at Embedded System Group (GSE) at PUCRS/Brazil.
*/
/**
* @file pic32mz-interrupt-latency-test.c
*
* @section DESCRIPTION
*
* Test the interrupt latency on internal hypervisor drivers.
*
* Test procedure for PIC32mz Starter Kit:
*
* * Connect a signal generator to pin RD10 (pin 37 on J12 connector).
* You can use another board for that. The application output_signal
* works with PIC32mz Curiosity boards for this purpose.
*
* * Connect a logical analizer to pins RD10 and RF4 (pin 21 on J12 connector).
*
* * The test consists of measure the time difference between the interrupt on RD10
* and the response on pin RF4.
*
*/
#include <hypercall.h>
#include <globals.h>
#include <driver.h>
#include <hypercall_defines.h>
#include <mips_cp0.h>
#include <hal.h>
#include <scheduler.h>
#include <libc.h>
#include <uart.h>
#include <interrupts.h>
void interrupt_handler(){
IFSCLR(3) = 1<<25;
if(PORTD & (1<<10)){
LATFSET = 1 << 4;
}else{
LATFCLR = 1 << 4;
}
}
/**
* @brief Driver init call.
* Register the interrupt handler and enable the timer.
*/
void start_latency_init(){
uint32_t offset;
TRISDSET = 1 << 10; /* RD10 (Input pin) */
CNPUDSET = 1 << 10; /* enable pull-up */
TRISFCLR = 1 << 4; /* RD0 as output*/
LATFCLR = 1 << 4;
CNPUFCLR = 1 << 4;
CNPDFCLR = 1 << 4;
ANSELFCLR = 1 << 4;
/* Configure interrupt for pin RD10 */
offset = register_interrupt(interrupt_handler);
OFF(121) = offset;
CNCONDSET = 0x8000;
CNENDSET = 1<<10;
IPC(30) = 0x1f<<8;
IFSCLR(3) = 1<<25;
IECSET(3) = 1<<25;
INFO("PIC32mz driver for interrupt latency test.");
}
driver_init(start_latency_init);
| 2.046875 | 2 |
2024-11-18T21:16:02.292499+00:00 | 2021-07-30T07:16:44 | 8aa226d165b6ee4942fe2ba692e6e2e8c63de5f1 | {
"blob_id": "8aa226d165b6ee4942fe2ba692e6e2e8c63de5f1",
"branch_name": "refs/heads/main",
"committer_date": "2021-07-30T07:16:44",
"content_id": "8e7f19fff51677189eadc2226ce293153c91100a",
"detected_licenses": [
"MIT"
],
"directory_id": "cc4e24c0684e37b381b4a45c297b1dabe8cfa27f",
"extension": "h",
"filename": "module.h",
"fork_events_count": 2,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 390132752,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2511,
"license": "MIT",
"license_type": "permissive",
"path": "/common/module.h",
"provenance": "stackv2-0112.json.gz:22589",
"repo_name": "Dnawrkshp/uya-patch",
"revision_date": "2021-07-30T07:16:44",
"revision_id": "b0f8e1cb7c65406e25b709185ac9096f858502b1",
"snapshot_id": "d58c4c9fe5959ca22fd8b3ba8bc389518627ca74",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Dnawrkshp/uya-patch/b0f8e1cb7c65406e25b709185ac9096f858502b1/common/module.h",
"visit_date": "2023-06-27T23:15:32.525463"
} | stackv2 | /***************************************************
* FILENAME : module.h
*
* DESCRIPTION :
* Modules are a way to optimize the limited memory available on the PS2.
* Modules are dynamically loaded by the server and dynamically invoked by the patcher.
* This header file contains the relevant structues for patch modules.
*
* NOTES :
*
* AUTHOR : Daniel "Dnawrkshp" Gerendasy
*/
#ifndef _MODULE_H_
#define _MODULE_H_
#include <tamtypes.h>
// Forward declarations
struct GameModule;
/*
* Size of game module arg buffer.
*/
#define GAME_MODULE_ARG_SIZE (8)
/*
* NAME : ModuleStart
*
* DESCRIPTION :
* Defines the function pointer for all module entrypoints.
* Modules will provide a pointer to their entrypoint that will match
* this type.
*
* NOTES :
*
*
* AUTHOR : Daniel "Dnawrkshp" Gerendasy
*/
typedef void (*ModuleStart)(struct GameModule * module);
/*
* NAME : GameModuleState
*
* DESCRIPTION :
* Contains the different states for a game module.
* The state will define how the patcher handles the module.
*
* NOTES :
*
*
* AUTHOR : Daniel "Dnawrkshp" Gerendasy
*/
typedef enum GameModuleState
{
/*
* Module is not active.
*/
GAMEMODULE_OFF,
/*
* The module will be invoked when the game/lobby starts and
* it will be set to 'OFF' when the game/lobby ends.
*/
GAMEMODULE_TEMP_ON,
/*
* The module will always be invoked as long as the player
* is in a game.
*/
GAMEMODULE_ALWAYS_ON
} GameModuleState;
/*
* NAME : GameModule
*
* DESCRIPTION :
* A game module is a dynamically loaded and invoked program.
* It contains a state and an entrypoint pointer.
*
* NOTES :
* Game modules are only executed while the player is in a game.
*
* AUTHOR : Daniel "Dnawrkshp" Gerendasy
*/
typedef struct GameModule
{
/*
* State of the module.
*/
GameModuleState State;
/*
* Entrypoint of module to be invoked when in game.
*/
ModuleStart GameEntrypoint;
/*
* Entrypoint of module to be invoked when in staging or menus.
*/
ModuleStart LobbyEntrypoint;
/*
* Buffer containing module specific arguments given by the server.
*/
char Argbuffer[GAME_MODULE_ARG_SIZE];
} GameModule;
#endif // _MODULE_H_
| 2.484375 | 2 |
2024-11-18T21:16:02.868353+00:00 | 2020-02-28T09:55:07 | 028ca4d7d8a19baec39a8c16fcea79791de4bce6 | {
"blob_id": "028ca4d7d8a19baec39a8c16fcea79791de4bce6",
"branch_name": "refs/heads/master",
"committer_date": "2020-02-28T09:55:07",
"content_id": "7c3ee773ba46c36c4790706be0d265c7c0389ad4",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "00ccc619830f3eddb616e78b3f1637ec5183e3b2",
"extension": "c",
"filename": "gf2m.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 243224874,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 9414,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/ROLLOI_128/gf2m.c",
"provenance": "stackv2-0112.json.gz:22718",
"repo_name": "lmortajine/PQC",
"revision_date": "2020-02-28T09:55:07",
"revision_id": "e17cf5a18fee520ef3958e2de3a30828984d688f",
"snapshot_id": "48e9e9ea1bb5e21665bc1b7106ed02f6f0203914",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/lmortajine/PQC/e17cf5a18fee520ef3958e2de3a30828984d688f/ROLLOI_128/gf2m.c",
"visit_date": "2021-02-03T21:33:26.376092"
} | stackv2 | #include <stdio.h>
#include <string.h>
#include "typedef.h"
#include "api.h"
#include "gf2m.h"
#include "utils.h"
/******************************************
*
* Operations in GF(2^m)
*
*******************************************/
const u4 MODULO_GF2_M[3] = {0x00000201, 0x00000000, 0x00008000};
/**
* \fn extern u2 Add_GF2m(pu4 pu4X, pu4 pu4Y, pu4 pu4R, u1 u1Len)
* \brief This function adds two elements in GF(2^m).
*
* \param[in] pu4X : adress of the first polynomial.
* \param[in] pu4Y : adress of the second polynomial.
* \param[in] pu4R : adress of the result.
* \param[in] u1Len : number of 32-bits words in pu4X and pu4Y.
*/
extern u2 Add_GF2m(pu4 pu4X, pu4 pu4Y, pu4 pu4R, u1 u1Len)
{
u1 i;
// XOR word per word.
for(i = 0 ; i < u1Len ; i++)
*(pu4R++) = *(pu4X++) ^ *(pu4Y++);
return 0;
}
/**
* \fn extern u2 Mupliply_GF2m_PreCompute(pu4 pu4X, pu4 pu4Storage, u1 u1Len)
* \brief This function computes the pre-computation for polynomial multiplication in GF(2^m)
* as detailed in the next function.
*
* \param[in] pu4X : adress of the polynomial.
* \param[in] pu4Storage : adress of the storage.
* /!\ Requires at least 16*u1Len 32-bits words.
* \param[in] u1Len : number of 32-bits words per element.
*/
extern u2 Mupliply_GF2m_PreCompute(pu4 pu4X, pu4 pu4Storage, u1 u1Len)
{
Shift_32bits_Words_Left(pu4X, pu4Storage + u1Len, u1Len, 0); // 0x1
Shift_32bits_Words_Left(pu4X, pu4Storage + 2*u1Len, u1Len, 1); // 0x2
Add_GF2m(pu4Storage + u1Len, pu4Storage + 2*u1Len, pu4Storage + 3*u1Len, 3); // 0x3
Shift_32bits_Words_Left(pu4X, pu4Storage + 4*u1Len, u1Len, 2); // 0x4
Add_GF2m(pu4Storage + 4*u1Len, pu4Storage + u1Len, pu4Storage + 5*u1Len, 3); // 0x5
Add_GF2m(pu4Storage + 4*u1Len, pu4Storage + 2*u1Len, pu4Storage + 6*u1Len, 3); // 0x6
Add_GF2m(pu4Storage + u1Len, pu4Storage + 2*u1Len, pu4Storage + 7*u1Len, 3); // 0x7
Add_GF2m(pu4Storage + 4*u1Len, pu4Storage + 7*u1Len, pu4Storage + 7*u1Len, 3); // 0x7
Shift_32bits_Words_Left(pu4X, pu4Storage + 8*u1Len, u1Len, 3); // 0x8
Add_GF2m(pu4Storage + 8*u1Len, pu4Storage + u1Len, pu4Storage + 9*u1Len, 3); // 0x9
Add_GF2m(pu4Storage + 8*u1Len, pu4Storage + 2*u1Len, pu4Storage + 10*u1Len, 3); // 0xA
Add_GF2m(pu4Storage + 8*u1Len, pu4Storage + 2*u1Len, pu4Storage + 11*u1Len, 3); // 0xB
Add_GF2m(pu4Storage + 11*u1Len, pu4Storage + u1Len, pu4Storage + 11*u1Len, 3); // 0xB
Add_GF2m(pu4Storage + 8*u1Len, pu4Storage + 4*u1Len, pu4Storage + 12*u1Len, 3); // 0xC
Add_GF2m(pu4Storage + 8*u1Len, pu4Storage + 4*u1Len, pu4Storage + 13*u1Len, 3); // 0xD
Add_GF2m(pu4Storage + u1Len, pu4Storage + 13*u1Len, pu4Storage + 13*u1Len, 3); // 0xD
Add_GF2m(pu4Storage + 4*u1Len, pu4Storage + 8*u1Len, pu4Storage + 14*u1Len, 3); // 0xE
Add_GF2m(pu4Storage + 2*u1Len, pu4Storage + 14*u1Len, pu4Storage + 14*u1Len, 3); // 0xE
Add_GF2m(pu4Storage + 2*u1Len, pu4Storage + u1Len, pu4Storage + 15*u1Len, 3); // 0xF
Add_GF2m(pu4Storage + 4*u1Len, pu4Storage + 15*u1Len, pu4Storage + 15*u1Len, 3); // 0xF
Add_GF2m(pu4Storage + 8*u1Len, pu4Storage + 15*u1Len, pu4Storage + 15*u1Len, 3); // 0xF
return 0;
}
/**
* \fn extern u2 Mupliply_GF2m_With_PreCompute(pu4 pu4X, pu4 pu4PreCompute, pu4 pu4R, u1 u1Len, u1 u1Degree)
* \brief This function processes the polynomial multiplication in GF(2^m) :
* Step 1 : For two polynmials P and Q of degree at most u1Degree, pre-compute C*Q for every value of Q contained in 4 bits.
* Step 2 : For every 4 bits value U of P, add U*Q to R with the right shift.
*
* \param[in] pu4X : adress of the first polynomial.
* \param[in] pu4PreCompute : adress of the storage.
* /!\ Requires at least 16*u1Len 32-bits words.
* \param[in] pu4R : adress of the result
* \param[in] u1Len : number of 32-bits words in pu4X.
* \param[in] u1Degree : maximum degree of the polynomials.
*/
extern u2 Mupliply_GF2m_With_PreCompute(pu4 pu4X, pu4 pu4PreCompute, pu4 pu4R, u1 u1Len, u1 u1Degree)
{
int i,j;
u4 u4Mask = 0xF0000000;
u1 u1Nb_32bits_Words = (u1Degree + 31) / 32;
u4 u4Nibble = 0;
for(i = 7 ; i >= 0 ; i-- )
{
for(j = 0 ; j < u1Nb_32bits_Words ; j++)
{
u4Nibble = ((*(pu4X + j)) & u4Mask) >> (4 * i);
Add_GF2m(pu4PreCompute + u4Nibble*u1Len, pu4R + j, pu4R + j, u1Len);
}
u4Mask >>= 4;
if(i != 0)
{
Shift_32bits_5Words_Left_4bits(pu4R);
}
}
return 0;
}
/**
* \fn extern u2 Modular_Reduction_GF2m(pu4 pu4X, pu4 pu4R)
* \brief This function efficiently performs the modular reduction modulo P = X^79 + X^9 + 1
* This algorithm is designed specifically for ROLLO-I.
*
* \param[in] pu4X : adress of the polynomial to reduce.
* \param[in] pu4R : adress of the result.
* \param[in] u1Len : number of 32-bits words per element.
*/
extern u2 Modular_Reduction_GF2m(pu4 pu4X, pu4 pu4R)
{
u4 u4MSBStorage[8] = { (*(pu4X + 4)) >> 6,
(*(pu4X + 4)) >> 15,
(*(pu4X + 4)) << 17,
(*(pu4X + 4)) << 26,
(*(pu4X + 3)) >> 6,
(*(pu4X + 3)) >> 15,
(*(pu4X + 3)) << 17,
(*(pu4X + 3)) << 26
};
*(pu4X + 2) ^= u4MSBStorage[0] ^ u4MSBStorage[1];
*(pu4X + 1) ^= u4MSBStorage[2] ^ u4MSBStorage[3] ^ u4MSBStorage[4] ^ u4MSBStorage[5];
* pu4X ^= u4MSBStorage[6] ^ u4MSBStorage[7];
// Extract bits 15 to 31 of C[2]
u4 u4Extract = *(pu4X + 2) & 0xFFFF8000; // 0xFFF80000
* pu4X ^= u4Extract >> 15;
*(pu4X ++) ^= u4Extract >> 6;
*(pu4X ++) ^= u4Extract << 22;
*(pu4X ++) &= 0x00007FFF; // Clear MSB
if((pu4X - 3) != pu4R)
{
memcpy(pu4R, pu4X - 3, PARAM_M_LEN_WORD*4);
memset(pu4X - 3, 0x00, 20);
}
*(pu4R + 3) = 0x00;
*(pu4R + 4) = 0x00;
*(pu4R + 5) = 0x00;
return 0;
}
/**
* \fn extern u2 Modular_inverse_GF2m(pu4 pu4X, pu4 pu4Modulo, pu4 pu4R, pu4 pu4Workspace, u1 u1Len)
* \brief This function computes the inverse of an element in GF(2^m).
*
* \param[in] pu4X : adress of the polynomial to inverse.
* \param[in] pu4Modulo : adress of the modulo.
* \param[in] pu4R : adress of the result.
* \param[in] pu4Workspace : adress of workspace.
* \param[in] u1Len : number of 32-bits words in pu4X.
*/
extern u2 Modular_inverse_GF2m(pu4 pu4X, pu4 pu4Modulo, pu4 pu4R, pu4 pu4Workspace, u1 u1Len)
{
ConstToRamMemCpy(pu4Modulo,
(pu4) MODULO_GF2_M,
MODULO_GF2M_LEN);
pu4 pu4U;
pu4 pu4V;
pu4 pu4G2 = pu4Workspace + u1Len;
pu4 pu4Temp = pu4G2 + u1Len;
pu4 pu4Vtemp = pu4Temp + u1Len;
pu4 pu4G2temp = pu4Vtemp + u1Len;
pu4V = pu4Modulo;
pu4U = pu4X;
u1 j;
u4 u4Count = 0;
memset(pu4R, 0, u1Len*4);
memset(pu4G2, 0, u1Len*4);
*(pu4R) = 0x01;
*(pu4G2) = 0x00;
u1 uLen = u1Len;
u1 vLen = MODULO_GF2M_LEN;
u1 u1Lentmp;
u1 uDegree = Degree_GF2m(pu4U, uLen);
u1 vDegree = Degree_GF2m(pu4V, vLen);
while(Is_Unit(pu4U, uLen) != 0)
{
if(uDegree>=vDegree)
{
j = uDegree - vDegree;
}
else
{
/* Swap between u and v as well as the length in words of u and v */
pu4Temp = pu4V;
pu4V = pu4U;
pu4U = pu4Temp;
u1Lentmp = uLen;
uLen = vLen;
vLen = u1Lentmp;
/* Swap between g1 and g2 */
pu4Temp = pu4R;
pu4R = pu4G2;
pu4G2 = pu4Temp;
j = vDegree - uDegree;
u4Count += 1;
}
/* These two shifts amount to multiply v and g2 by x^j */
Shift_32bits_Words_Left(pu4V, pu4Vtemp, u1Len, j);
Shift_32bits_Words_Left(pu4G2, pu4G2temp, u1Len, j);
/* u = u x^j * v and g1 = g1 + x^j * g2*/
Add_GF2m(pu4U, pu4Vtemp, pu4U, u1Len);
Add_GF2m(pu4R, pu4G2temp, pu4R, u1Len);
/* Determination of the degree of u and v*/
if(pu4U[uLen-1] == 0)
{
uLen = uLen - 1;
}
uDegree = Degree_GF2m(pu4U, uLen);
if(pu4V[vLen-1] == 0)
{
vLen = vLen - 1;
}
vDegree = Degree_GF2m(pu4V,vLen);
}
if((u4Count %2) == 1)
{
memcpy(pu4G2, pu4R, MODULO_GF2M_LEN*4);
memcpy(pu4X,pu4U,MODULO_GF2M_LEN*4);
}
return 0;
}
| 2.671875 | 3 |
2024-11-18T21:29:37.128983+00:00 | 2016-12-08T23:54:56 | bcf49170e6efc0ce493a66de9a9fdba619d03dd4 | {
"blob_id": "bcf49170e6efc0ce493a66de9a9fdba619d03dd4",
"branch_name": "refs/heads/master",
"committer_date": "2016-12-08T23:54:56",
"content_id": "cc4270823d7d22a10cb6fb9f54e6fe413e314c27",
"detected_licenses": [
"MIT"
],
"directory_id": "5127c36c826ea287a8cce504247976c53672ef3b",
"extension": "c",
"filename": "pwd.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 74437349,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 727,
"license": "MIT",
"license_type": "permissive",
"path": "/pwd.c",
"provenance": "stackv2-0112.json.gz:174564",
"repo_name": "tvanollefen/OSArch",
"revision_date": "2016-12-08T23:54:56",
"revision_id": "ce20db388cafabd8f38588f97ec8b575219ba055",
"snapshot_id": "08d613e844ec42954dcfe80cfdf49d271cd08e37",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/tvanollefen/OSArch/ce20db388cafabd8f38588f97ec8b575219ba055/pwd.c",
"visit_date": "2020-06-29T09:19:41.761142"
} | stackv2 | /*
Authors: Paul Turchinetz and Tyler Van Ollefen
Class: CSI-385-01
Assignment: FAT
Due Date: 6 December 2016, 11:59PM
Description: This is the pwd command - print working directory.
Certification of Authenticity:
I certify that this assignment is entirely our own work unless cited otherwise.
*/
#include <stdio.h>
#include <stdlib.h>
#include "sharedMemory.h"
int main(int argc, char **argv)
{
//https://beej.us/guide/bgipc/output/html/multipage/shm.html
//ALEX APMANNNNNN
int shmId = shmget((key_t) 8888888, sizeof(char), 0666 | IPC_CREAT);
SharedMemory *sharedMemory = (SharedMemory *)shmat(shmId, (void *) 0, 0);
//this one was a doozy
printf("%s\n", sharedMemory->curDir);
return 0;
}
| 2.40625 | 2 |
2024-11-18T21:29:37.239715+00:00 | 2013-11-14T09:45:47 | 7dcd3e39fdf1f7bd8fbf307966c2777480ac96d9 | {
"blob_id": "7dcd3e39fdf1f7bd8fbf307966c2777480ac96d9",
"branch_name": "refs/heads/master",
"committer_date": "2013-11-14T09:45:47",
"content_id": "eaf193e9a0776bd5f0be349734a18d3f4e250417",
"detected_licenses": [
"MIT"
],
"directory_id": "1b150c389b12047f0fc41251b8202a185f1f19be",
"extension": "h",
"filename": "storage.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": 3023,
"license": "MIT",
"license_type": "permissive",
"path": "/src/include/storage.h",
"provenance": "stackv2-0112.json.gz:174693",
"repo_name": "jakobjanot/ctst",
"revision_date": "2013-11-14T09:45:47",
"revision_id": "fe6f079f30e00b4d6607c48c471e0728cc709434",
"snapshot_id": "5a6ef6d332aac2b775e11a4c6b7721677c6f31e5",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/jakobjanot/ctst/fe6f079f30e00b4d6607c48c471e0728cc709434/src/include/storage.h",
"visit_date": "2021-01-18T13:50:18.059416"
} | stackv2 | #ifndef __CTST_STORAGE_H__
#define __CTST_STORAGE_H__
/*
ctst - (c) 2007 Nicolas Lehuen
This is released under the LGPL - see http://www.gnu.org/licenses/lgpl.html
$Id: $
This file defines the storage interface.
*/
#include <stdio.h>
/* This is the maximum number of bytes that can be stored
in a single node. The exact value depends on the storage
implementation. */
extern const size_t ctst_max_bytes_per_node;
/* This is the structure storing data about the storage. There
again, its contents depends on the implementation. */
typedef struct struct_ctst_storage ctst_storage;
typedef struct struct_ctst_two_node_refs {
ctst_node_ref ref1;
ctst_node_ref ref2;
} ctst_two_node_refs;
typedef struct struct_ctst_balance_info {
ctst_node_ref node;
ctst_data data;
} ctst_balance_info;
/* Storage allocation / deallocation */
ctst_storage* ctst_storage_alloc();
void ctst_storage_free(ctst_storage* storage);
/* Node allocation / deallocation */
ctst_node_ref ctst_storage_node_alloc(ctst_storage* storage, ctst_data data, char* bytes, size_t bytes_index, size_t bytes_length, char next_byte, ctst_node_ref next_node);
void ctst_storage_node_free(ctst_storage* storage, ctst_node_ref node);
/* Statistics about the storage */
size_t ctst_storage_node_count(ctst_storage* storage);
size_t ctst_storage_memory_usage(ctst_storage* storage);
/* Node attribute reading */
ctst_data ctst_storage_get_data(ctst_storage* storage, ctst_node_ref node);
ctst_node_ref ctst_storage_get_next(ctst_storage* storage, ctst_node_ref node, char byte);
size_t ctst_storage_get_bytes_length(ctst_storage* storage, ctst_node_ref node);
char ctst_storage_get_byte(ctst_storage* storage, ctst_node_ref node, size_t byte_index);
void ctst_storage_load_bytes(ctst_storage* storage, ctst_node_ref node, char** bytes, size_t* bytes_length);
void ctst_storage_unload_bytes(ctst_storage* storage, ctst_node_ref node, char* bytes);
/* Node attribute writing */
void ctst_storage_set_data(ctst_storage* storage, ctst_balance_info* balance_info);
void ctst_storage_set_next(ctst_storage* storage, ctst_node_ref* node, char byte, ctst_node_ref next);
void ctst_storage_set_bytes(ctst_storage* storage, ctst_node_ref* node, char* bytes, size_t bytes_index, size_t bytes_length);
/* Special node operations */
ctst_two_node_refs ctst_storage_split_node(ctst_storage* storage, ctst_node_ref node, size_t split_index);
ctst_node_ref ctst_storage_join_nodes(ctst_storage* storage, ctst_node_ref node);
/* Visitor support */
typedef ctst_data(*ctst_visitor_function)(void* context, char *key_bytes, size_t key_length, ctst_data data, size_t distance);
ctst_data ctst_storage_visit_all(ctst_storage* ctst, ctst_visitor_function visitor, void* context, ctst_node_ref node, char** bytes, size_t bytes_length, size_t *bytes_limit);
/* Debug functions */
void ctst_storage_debug_node(ctst_storage* storage, ctst_node_ref node, FILE* output, int start);
#endif
| 2.578125 | 3 |
2024-11-18T21:29:37.771839+00:00 | 2017-02-19T20:04:42 | 1a24f1b712b5f30e33de4775bc69c635b996b197 | {
"blob_id": "1a24f1b712b5f30e33de4775bc69c635b996b197",
"branch_name": "refs/heads/master",
"committer_date": "2017-02-19T20:04:42",
"content_id": "bc905a7121bdd78241be54e330b0e0f9e0751493",
"detected_licenses": [
"MIT"
],
"directory_id": "2492857a845e0058c9ec734ba164977bc9b5a6cf",
"extension": "h",
"filename": "lwdopetrack.h",
"fork_events_count": 3,
"gha_created_at": "2014-10-11T16:32:14",
"gha_event_created_at": "2015-07-02T21:22:33",
"gha_language": "C++",
"gha_license_id": null,
"github_id": 25086193,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4747,
"license": "MIT",
"license_type": "permissive",
"path": "/Emerald/deps/lwsdk/lwdopetrack.h",
"provenance": "stackv2-0112.json.gz:174822",
"repo_name": "kbiElude/Emerald",
"revision_date": "2017-02-19T20:04:42",
"revision_id": "d4309e9c1a9ff79790008958e5a2956aec67cd5f",
"snapshot_id": "c597d67b4323481079968a368d33c52d02318e45",
"src_encoding": "UTF-8",
"star_events_count": 11,
"url": "https://raw.githubusercontent.com/kbiElude/Emerald/d4309e9c1a9ff79790008958e5a2956aec67cd5f/Emerald/deps/lwsdk/lwdopetrack.h",
"visit_date": "2020-04-03T21:32:47.573267"
} | stackv2 | /*
* LWSDK Header File
* Copyright 2004, NewTek, Inc.
*
* LWDOPETRACK.H -- Layout Dopetrack Interface
*
* This header contains declarations that allow a Tool-class plug-in
* to take over most of the functionality of the Layout Dopetrack
*/
#ifndef LWSDK_DOPETRACK_H
#define LWSDK_DOPETRACK_H
#include <lwtypes.h>
#include <lwenvel.h>
#define LWDOPETRACK_GLOBAL "Dopetrack Proxy"
#ifndef RGB_
#define RGB_(r,g,b) (((r) << 16) | ((b) << 8) | (g))
#endif
#define TIME_MARKER ((LWTime)99999.0)
typedef enum
{
DTOPMODE_CHANNEL = 0,
DTOPMODE_GLOBAL
} DTOperatingMode;
typedef enum
{
DTEVENT_KEYFUNCTION,
DTEVENT_EDITSTATECHANGE,
DTEVENT_BAKEZONECHANGE,
DTEVENT_UNDO,
DTEVENT_REDO
} DTEventType;
typedef enum
{
DTACTION_SELECT,
DTACTION_SHIFT,
DTACTION_SHIFT_COPY,
DTACTION_CREATE_KEY,
DTACTION_DELETE_KEY
} DTKeyAction;
typedef enum
{
DTMOUSE_DOWN,
DTMOUSE_MOVE,
DTMOUSE_UP
} DTMouseEvent;
typedef struct _dtevent_mouse_st
{
DTMouseEvent event;
int context; // 0=left margin, 1=right margin
int x,y; // relative to drawing area
int w,h; // dimensions of drawing area
int button; // 0=left, 1=right, 2=middle
int count; // click count: 1=single, 2=double, etc.
} DTMouseParam, *DTMouseParamID;
typedef struct _dtevent_keyselect_st
{
int count;
LWTime *indices; // list of time indices effected
LWTime offset; // shift offset of time indices (if DTACTION_SHIFT/DTACTION_SHIFT_COPY)
} DTKeySelect, *DTKeySelectID;
typedef struct _dtevent_bakezone_st
{
int count;
// parallel arrays
int *start_frame,*end_frame;
LWTime *start_time,*end_time;
int *selected;
} DTBakeZone, *DTBakeZoneID;
typedef struct _dteventparam_st
{
DTEventType event;
int value;
LWTime offset;
} DTEventParam, *DTEventParamID;
// menu management functions
typedef int (*DTMenuCount)(int);
typedef int (*DTMenuSub)(int,int);
typedef int * (*DTMenuSep)(int);
typedef int (*DTMenuEnable)(int,int);
typedef const char * (*DTMenuItem)(int,int);
typedef void (*DTMenuSelect)(int,int);
typedef int (*DTMenuInitial)(void);
// events on the dopetrack
typedef void (*DTUserEvent)(DTEventParamID);
typedef int (*DTAllow)(DTKeyAction);
typedef void (*DTMouse)(DTMouseParamID);
typedef struct _dtmenucallbacks
{
DTMenuCount menuCount;
DTMenuSub menuSubMenu;
DTMenuSep menuSep;
DTMenuEnable menuEnable;
DTMenuItem menuItem;
DTMenuSelect menuSelect;
DTMenuInitial menuInitial;
} DTMenuCallbacks, *DTMenuCallbacksID;
typedef struct _dttoolcallbacks
{
DTUserEvent userEvent;
DTAllow allow;
DTMouse mouseEvent;
DTMenuCallbacks menu;
} DTToolCallbacks, *DTToolCallbacksID;
typedef struct _dtdrawcallbacks
{
int *(*context)(int side); // 0=left margin, 1=right margin
void (*erase)(int x,int y,int w,int h);
void (*pixel)(int x,int y,int color); // use RGB_() to construct color
void (*line)(int x1,int y1,int x2,int y2,int color);
void (*rectOutline)(int x,int y,int w,int h,int color);
void (*rectFilled)(int x,int y,int w,int h,int bcolor,int fcolor);
void (*border)(int x,int y,int w,int h);
void (*divider)(int x,int y,int w);
void (*text)(int x,int y,int color,const char *text);
void (*text_box)(int x,int y,int w,int h,const char *text);
void (*button)(int x,int y,int w,int h,int color);
void (*flush)(void);
} DTDrawFuncs, *DTDrawFuncsID;
typedef struct st_LWDopetrackProxy
{
void (*toolRegister)(DTToolCallbacksID);
void (*toolRelease)(void);
void (*exposeEnvelopes)(LWEnvelopeID *,const char **,int *);
void (*refreshDisplay)(void);
DTKeySelectID (*querySelectedKeys)(void);
void (*querySelection)(LWTime *,LWTime *);
const LWTime *(*queryMarkers)(void);
void (*addMarker)(LWTime);
void (*remMarker)(LWTime);
DTBakeZoneID (*queryBakeZones)(void);
void (*addBakeZone)(LWTime,LWTime);
void (*remBakeZone)(LWTime,LWTime);
DTOperatingMode (*queryOpMode)(void);
void (*displayMenu)(DTMenuCallbacksID);
int (*visible)(void);
DTDrawFuncs drawfuncs;
} LWDopetrackProxy, *LWDopetrackProxyID;
#endif
| 2.125 | 2 |
2024-11-18T21:29:39.127284+00:00 | 2020-05-21T16:58:53 | 109dde38154f2e5d99112d2f4a7c2117e4e8f7e7 | {
"blob_id": "109dde38154f2e5d99112d2f4a7c2117e4e8f7e7",
"branch_name": "refs/heads/master",
"committer_date": "2020-05-21T16:58:53",
"content_id": "f873d877fbfa7fcf77ea14a7e341c0beb62dcd7b",
"detected_licenses": [
"MIT"
],
"directory_id": "2c0a46d0835982ea928e65f18a95514834d578b2",
"extension": "h",
"filename": "sleep.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": 1611,
"license": "MIT",
"license_type": "permissive",
"path": "/src/utils/sleep.h",
"provenance": "stackv2-0112.json.gz:175596",
"repo_name": "littledivy/native-utils",
"revision_date": "2020-05-21T16:58:53",
"revision_id": "f559b715248811ed788efd25f39794a65b6c0daa",
"snapshot_id": "a25f8d389b819f0952c7c13d30f5a440522e60fb",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/littledivy/native-utils/f559b715248811ed788efd25f39794a65b6c0daa/src/utils/sleep.h",
"visit_date": "2022-07-30T00:57:37.900335"
} | stackv2 | #pragma once
#ifndef MICROSLEEP_H
#define MICROSLEEP_H
/* A complicated, portable model for declaring inline functions in
* header files. */
#if !defined(H_INLINE)
#if defined(__GNUC__)
#define H_INLINE static __inline__ __attribute__((always_inline))
#elif defined(__MWERKS__) || defined(__cplusplus)
#define H_INLINE static inline
#elif defined(_MSC_VER)
#define H_INLINE static __inline
#elif TARGET_OS_WIN32
#define H_INLINE static __inline__
#endif
#endif /* H_INLINE */
#include "../os_def.h"
#if !defined(IS_WINDOWS)
/* Make sure nanosleep gets defined even when using C89. */
#if !defined(__USE_POSIX199309) || !__USE_POSIX199309
#define __USE_POSIX199309 1
#endif
#include <time.h> /* For nanosleep() */
#endif
/*
* A more widely supported alternative to usleep(), based on Sleep() in Windows
* and nanosleep() everywhere else.
*
* Pauses execution for the given amount of milliseconds.
*/
H_INLINE void microsleep(double milliseconds)
{
#if defined(IS_WINDOWS)
Sleep((DWORD)milliseconds); /* (Unfortunately truncated to a 32-bit integer.) */
#else
/* Technically, nanosleep() is not an ANSI function, but it is the most
* supported precise sleeping function I can find.
*
* If it is really necessary, it may be possible to emulate this with some
* hack using select() in the future if we really have to. */
struct timespec sleepytime;
sleepytime.tv_sec = milliseconds / 1000;
sleepytime.tv_nsec = (milliseconds - (sleepytime.tv_sec * 1000)) * 1000000;
nanosleep(&sleepytime, NULL);
#endif
}
#endif /* MICROSLEEP_H */
| 2.609375 | 3 |
2024-11-18T21:29:39.217462+00:00 | 2018-10-05T12:15:05 | f2f2e99507487e68d1e5f399515abe83220292e2 | {
"blob_id": "f2f2e99507487e68d1e5f399515abe83220292e2",
"branch_name": "refs/heads/master",
"committer_date": "2018-10-05T12:15:05",
"content_id": "2c7d11301a825ffeb53127120468ef50fe2eeb1c",
"detected_licenses": [
"MIT"
],
"directory_id": "715eb536f173a2ed1e621d12fee8663f4eabf96b",
"extension": "c",
"filename": "timer.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 143037660,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 577,
"license": "MIT",
"license_type": "permissive",
"path": "/timer.c",
"provenance": "stackv2-0112.json.gz:175725",
"repo_name": "WLBF/toy-os",
"revision_date": "2018-10-05T12:15:05",
"revision_id": "d728043fdf16d819851f2bc0511eb2ebc1295b28",
"snapshot_id": "38431e73d9ebc17c42a63825be008e7c76748806",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/WLBF/toy-os/d728043fdf16d819851f2bc0511eb2ebc1295b28/timer.c",
"visit_date": "2020-03-24T21:32:06.391310"
} | stackv2 | #include "io.h"
#include "timer.h"
#include "fb_driver.h"
#include "interrupt_handler.h"
uint32_t tick = 0;
static void timer_callback(struct registers regs)
{
tick++;
fb_write("tick: ", 6);
fb_write_hex(regs.int_no);
fb_put('\n');
fb_write_hex(tick);
fb_put('\n');
}
void init_timer(uint32_t frequency)
{
register_interrupt_handler(IRQ0, &timer_callback);
uint32_t divisor = 1193180 / frequency;
outb(0x43, 0x36);
uint8_t l = (uint8_t)(divisor & 0xff);
uint8_t h = (uint8_t)( (divisor>>8) & 0xff );
outb(0x40, l);
outb(0x40, h);
} | 2.484375 | 2 |
2024-11-18T21:29:44.217440+00:00 | 2021-05-16T09:10:40 | 8f84a9829d9fc88614491c9a45b5b2b4b56d933c | {
"blob_id": "8f84a9829d9fc88614491c9a45b5b2b4b56d933c",
"branch_name": "refs/heads/master",
"committer_date": "2021-05-16T09:10:40",
"content_id": "c7aec27d1c093f829bf4cd037724e089d4a69c27",
"detected_licenses": [
"MIT"
],
"directory_id": "7aa3ff1a1f748c7e7107570f388907a4ef79305b",
"extension": "h",
"filename": "hardirq.h",
"fork_events_count": 0,
"gha_created_at": "2021-03-27T00:05:30",
"gha_event_created_at": "2021-08-21T06:36:52",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 351942409,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1348,
"license": "MIT",
"license_type": "permissive",
"path": "/src/include/xbook/hardirq.h",
"provenance": "stackv2-0112.json.gz:176501",
"repo_name": "iOSPrincekin/xbook2",
"revision_date": "2021-05-16T09:10:40",
"revision_id": "e06e58e91dabb9ea18c3e140e2ce2eae74f8973a",
"snapshot_id": "5f2e9f67c777a687d380a3827c395d54af99a8a0",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/iOSPrincekin/xbook2/e06e58e91dabb9ea18c3e140e2ce2eae74f8973a/src/include/xbook/hardirq.h",
"visit_date": "2023-08-03T09:58:24.882517"
} | stackv2 | #ifndef _XBOOK_HARDIRQ_H
#define _XBOOK_HARDIRQ_H
#include <arch/interrupt.h>
#include <types.h>
#define IRQF_DISABLED 0x01
#define IRQF_SHARED 0x02
#define IRQF_TIMER 0x03
#define IRQ_HANDLED 0
#define IRQ_NEXTONE -1
typedef struct {
void (*enable)(irqno_t irq);
void (*disable)(irqno_t irq);
unsigned int (*install)(irqno_t irq, void *arg);
void (*uninstall)(irqno_t irq);
void (*ack)(irqno_t irq);
} interrupt_controller_t;
extern interrupt_controller_t interrupt_controller;
typedef int (*irq_handler_t)(irqno_t, void *);
#define irq_enable(n) interrupt_controller.enable(n)
#define irq_disable(n) interrupt_controller.disable(n)
typedef struct irq_action {
void *data;
irq_handler_t handler;
unsigned long flags;
struct irq_action *next;
char *name;
} irq_action_t;
typedef struct irq_description {
interrupt_controller_t *controller;
struct irq_action *action;
unsigned long flags;
atomic_t device_count;
char *irqname;
} irq_description_t;
int irq_register(irqno_t irq,
irq_handler_t handler,
unsigned long flags,
char *irqname,
char *devname,
void *data);
int irq_unregister(irqno_t irq, void *data);
int irq_handle(irqno_t irq, trap_frame_t *frame);
void irq_description_init();
#endif /* _XBOOK_HARDIRQ_H */
| 2.09375 | 2 |
2024-11-18T21:29:44.608744+00:00 | 2014-07-27T01:09:59 | fd8f6b66da2d9dd147ae9ea1d376463ab057e1ae | {
"blob_id": "fd8f6b66da2d9dd147ae9ea1d376463ab057e1ae",
"branch_name": "refs/heads/master",
"committer_date": "2014-07-27T01:09:59",
"content_id": "3227c332be24191929db57a84fcbaacb9acb275e",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "c862fe4a0285c8984be7a3dee20d52550fe269fb",
"extension": "c",
"filename": "problem6.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": 479,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/projecteuler/C/problem6.c",
"provenance": "stackv2-0112.json.gz:176889",
"repo_name": "chrismoulds/Misc.-Projects",
"revision_date": "2014-07-27T01:09:59",
"revision_id": "82d81fb21f6876b99726a2835e029f895c262c6b",
"snapshot_id": "26d2929babdac3c50326102efddb7918b568a749",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/chrismoulds/Misc.-Projects/82d81fb21f6876b99726a2835e029f895c262c6b/projecteuler/C/problem6.c",
"visit_date": "2016-09-05T10:07:29.958579"
} | stackv2 | /*
* Project Euler Problem #6:
* Find the difference between the sum of the squares of the first one
* hundred natural numbers and the square of the sum.
*
* Author: Chris Moulds
*/
#include <stdio.h>
#include <math.h>
int gauss_trick(int value){
return (value*(value + 1))/2;
}
int main()
{
int difference = 0;
difference = pow(gauss_trick(100), 2);
for (int i=1; i<=100; i++){
difference-=pow(i, 2);
}
printf("DIFFERENCE: %d\n", difference);
return 0;
}
| 3.75 | 4 |
2024-11-18T21:29:44.687450+00:00 | 2019-05-09T17:20:16 | 1c9bcd2382bb3e0061a079419079d52c3e0f47b7 | {
"blob_id": "1c9bcd2382bb3e0061a079419079d52c3e0f47b7",
"branch_name": "refs/heads/master",
"committer_date": "2019-05-09T17:20:16",
"content_id": "0c5684539584ed298ce18d229030b1ec7f5d3866",
"detected_licenses": [
"MIT"
],
"directory_id": "b026f86da7df693f12d0ce945be9be9616e0d22f",
"extension": "c",
"filename": "aspace.c",
"fork_events_count": 0,
"gha_created_at": "2019-01-25T18:37:34",
"gha_event_created_at": "2019-01-25T18:37:34",
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 167595291,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 849,
"license": "MIT",
"license_type": "permissive",
"path": "/exercises/ex02/aspace.c",
"provenance": "stackv2-0112.json.gz:177018",
"repo_name": "ssreekanth2000/ExercisesInC",
"revision_date": "2019-05-09T17:20:16",
"revision_id": "4d7f9d8f0a099f0af47de1c74b5b75a00ebc1d2b",
"snapshot_id": "98e2cdbff799169c37e1c3c202d315bc4779f710",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ssreekanth2000/ExercisesInC/4d7f9d8f0a099f0af47de1c74b5b75a00ebc1d2b/exercises/ex02/aspace.c",
"visit_date": "2020-04-18T14:41:01.577047"
} | stackv2 | /* Example code for Think OS.
Copyright 2014 Allen Downey
License: GNU GPLv3
*/
#include <stdio.h>
#include <stdlib.h>
int var1;
// int check_heap(int var2){
// int address_1=&var2;
//
//
// }
int main ()
{
int var2 = 5;
void *p = malloc(128);
void *p1 = malloc(128);
void *p2 = malloc(16);
void *p3 = malloc(16);
char *s = "Hello, World";
printf ("Address of main is %p\n", main);
printf ("Address of var1 is %p\n", &var1);
printf ("Address of var2 is %p\n", &var2);
printf ("p points to %p\n", p);
printf ("p1 points to %p\n", p1);
printf ("p2 points to %p\n", p2);
printf ("p3 points to %p\n", p3);
printf ("s points to %p\n", s);
return 0;
}
//output
// p2 points to 0x1304130
// p3 points to 0x1304150
//The difference is 32 when calculated which makes sense as 16_16 is 32.
| 2.984375 | 3 |
2024-11-18T21:29:44.768300+00:00 | 2015-04-28T19:56:51 | 84db8a6162d64c9dc208ccd5b70820cf5cf4179b | {
"blob_id": "84db8a6162d64c9dc208ccd5b70820cf5cf4179b",
"branch_name": "refs/heads/mirror",
"committer_date": "2015-04-28T19:56:51",
"content_id": "0a03b891777f9347a5d70babef2332c247a4a4e7",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "83102f87c241c833e176b355af654ef77f7b0762",
"extension": "c",
"filename": "binary_heap_array.c",
"fork_events_count": 0,
"gha_created_at": "2014-05-22T20:16:39",
"gha_event_created_at": "2014-11-28T01:50:06",
"gha_language": "C",
"gha_license_id": null,
"github_id": 20075555,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 11566,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/core/structures/unordered/binary_heap_array.c",
"provenance": "stackv2-0112.json.gz:177148",
"repo_name": "GeneAssembly/biosal",
"revision_date": "2015-04-28T19:56:51",
"revision_id": "a18d6d08f1b31dfd78a6c1d1c5af8d7bb6e91584",
"snapshot_id": "ed113766c60b743af4e8c1b04004fd6befda57ba",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/GeneAssembly/biosal/a18d6d08f1b31dfd78a6c1d1c5af8d7bb6e91584/core/structures/unordered/binary_heap_array.c",
"visit_date": "2020-05-07T20:16:14.905809"
} | stackv2 |
#include "binary_heap_array.h"
#include "binary_heap.h"
#include <core/constants.h>
#include <core/system/debugger.h>
#include <core/system/memory.h>
#include <stdlib.h>
#include <string.h>
void *core_binary_heap_array_get_key(struct core_binary_heap_array *self, int i);
void *core_binary_heap_array_get_value(struct core_binary_heap_array *self, int i);
static inline int core_binary_heap_array_get_first_child(int i);
static inline int core_binary_heap_array_get_parent(int i);
static inline int core_binary_heap_array_get_second_child(int i);
void core_binary_heap_array_sift_up(struct core_binary_heap_array *self, int i);
void core_binary_heap_array_sift_down(struct core_binary_heap_array *self, int i);
void core_binary_heap_array_swap(struct core_binary_heap_array *self, int i, int j);
/*
* relation functions.
*/
int core_binary_heap_array_test_relation(struct core_binary_heap_array *self, int i, int j);
int core_binary_heap_array_test_relation_lower_than_int(struct core_binary_heap_array *self,
void *key1, void *key2);
int core_binary_heap_array_test_relation_lower_than_uint64_t(struct core_binary_heap_array *self,
void *key1, void *key2);
int core_binary_heap_array_test_relation_lower_than_void_pointer(struct core_binary_heap_array *self,
void *key1, void *key2);
int core_binary_heap_array_test_relation_greater_than_int(struct core_binary_heap_array *self,
void *key1, void *key2);
int core_binary_heap_array_test_relation_greater_than_uint64_t(struct core_binary_heap_array *self,
void *key1, void *key2);
int core_binary_heap_array_test_relation_greater_than_void_pointer(struct core_binary_heap_array *self,
void *key1, void *key2);
void core_binary_heap_array_init(struct core_binary_heap_array *self, int key_size,
int value_size, uint32_t flags)
{
core_vector_init(&self->vector, key_size + value_size);
self->size = 0;
self->test_relation = NULL;
self->key_size = key_size;
self->value_size = value_size;
if (flags & CORE_BINARY_HEAP_MIN) {
if (flags & CORE_BINARY_HEAP_INT_KEYS)
self->test_relation = core_binary_heap_array_test_relation_lower_than_int;
else if (flags & CORE_BINARY_HEAP_UINT64_T_KEYS)
self->test_relation = core_binary_heap_array_test_relation_lower_than_uint64_t;
else
self->test_relation = core_binary_heap_array_test_relation_lower_than_void_pointer;
} else if (flags & CORE_BINARY_HEAP_MAX) {
if (flags & CORE_BINARY_HEAP_INT_KEYS)
self->test_relation = core_binary_heap_array_test_relation_greater_than_int;
else if (flags & CORE_BINARY_HEAP_UINT64_T_KEYS)
self->test_relation = core_binary_heap_array_test_relation_greater_than_uint64_t;
else
self->test_relation = core_binary_heap_array_test_relation_greater_than_void_pointer;
}
CORE_DEBUGGER_ASSERT_NOT_NULL(self->test_relation);
CORE_DEBUGGER_ASSERT(self->key_size >= 1);
CORE_DEBUGGER_ASSERT(self->value_size >= 0);
}
void core_binary_heap_array_destroy(struct core_binary_heap_array *self)
{
core_vector_destroy(&self->vector);
}
int core_binary_heap_array_get_root(struct core_binary_heap_array *self, void **key, void **value)
{
void *stored_key;
void *stored_value;
if (self->size == 0)
return FALSE;
stored_key = core_binary_heap_array_get_key(self, 0);
stored_value = core_binary_heap_array_get_value(self, 0);
if (key != NULL)
*key = stored_key;
if (value != NULL)
*value = stored_value;
return TRUE;
}
/**
* @see http://en.wikipedia.org/wiki/Binary_heap#Delete
*/
int core_binary_heap_array_delete_root(struct core_binary_heap_array *self)
{
int last;
int root;
if (self->size == 0)
return FALSE;
last = self->size - 1;
root = 0;
/*
* Swap with the end.
*/
core_binary_heap_array_swap(self, root, last);
--self->size;
core_binary_heap_array_sift_down(self, root);
return TRUE;
}
/**
* @see http://en.wikipedia.org/wiki/Binary_heap#Insert
*/
int core_binary_heap_array_insert(struct core_binary_heap_array *self, void *key, void *value)
{
int position;
void *stored_key;
void *stored_value;
#ifdef HEAP_DEBUG_INSERT
printf("DEBUG before insert, %d elements\n", self->size);
core_vector_print_int(&self->vector);
printf("\n");
#endif
position = self->size;
#ifdef HEAP_DEBUG_INSERT
printf("DEBUG insert at position %d\n", position);
#endif
if (position + 1 > core_vector_size(&self->vector))
core_vector_resize(&self->vector, position + 1);
++self->size;
/*
* Add the pair at the end on the last level.
*/
stored_key = core_binary_heap_array_get_key(self, position);
stored_value = core_binary_heap_array_get_value(self, position);
core_memory_copy(stored_key, key, self->key_size);
if (self->value_size)
core_memory_copy(stored_value, value, self->value_size);
#ifdef HEAP_DEBUG_INSERT
printf("DEBUG before sift_up\n");
core_vector_print_int(&self->vector);
printf("\n");
#endif
core_binary_heap_array_sift_up(self, position);
return TRUE;
}
void *core_binary_heap_array_get_key(struct core_binary_heap_array *self, int i)
{
void *stored_key;
stored_key = core_vector_at(&self->vector, i);
return stored_key;
}
void *core_binary_heap_array_get_value(struct core_binary_heap_array *self, int i)
{
void *stored_value;
stored_value = ((char *)core_vector_at(&self->vector, i)) + self->key_size;
return stored_value;
}
void core_binary_heap_array_sift_up(struct core_binary_heap_array *self, int i)
{
int parent;
/*
* It is the root already.
*/
if (i == 0)
return;
while (1) {
parent = core_binary_heap_array_get_parent(i);
/*
* This is already correct.
*
* With CORE_BINARY_HEAP_MIN: key(i) < key(parent).
*
* With CORE_BINARY_HEAP_MAX: key(i) > key(parent).
*
* If key(i) and key(parent) are equal, no change is required.
*/
if (!core_binary_heap_array_test_relation(self, i, parent))
break;
/*
* Otherwise, swap the entries and continue.
*/
core_binary_heap_array_swap(self, parent, i);
i = parent;
}
}
int core_binary_heap_array_test_relation(struct core_binary_heap_array *self, int i, int j)
{
void *key_i;
void *key_j;
key_i = core_binary_heap_array_get_key(self, i);
key_j = core_binary_heap_array_get_key(self, j);
#ifdef HEAP_DEBUG_INSERT
printf("DEBUG Test %d %d\n", i, j);
#endif
return self->test_relation(self, key_i, key_j);
}
int core_binary_heap_array_test_relation_lower_than_void_pointer(struct core_binary_heap_array *self,
void *key1, void *key2)
{
return core_memory_compare(key1, key2, self->key_size) < 0;
}
static inline int core_binary_heap_array_get_first_child(int i)
{
return 2 * i + 1;
}
static inline int core_binary_heap_array_get_second_child(int i)
{
return 2 * i + 2;
}
static inline int core_binary_heap_array_get_parent(int i)
{
return (i - 1) / 2;
}
int core_binary_heap_array_test_relation_lower_than_int(struct core_binary_heap_array *self,
void *key1, void *key2)
{
int a;
int b;
a = *(int *)key1;
b = *(int *)key2;
#ifdef HEAP_DEBUG_INSERT
printf("DEBUG lower_than_int %d %d\n", a, b);
#endif
return a < b;
}
int core_binary_heap_array_test_relation_lower_than_uint64_t(struct core_binary_heap_array *self,
void *key1, void *key2)
{
uint64_t a;
uint64_t b;
a = *(uint64_t *)key1;
b = *(uint64_t *)key2;
return a < b;
}
int core_binary_heap_array_test_relation_greater_than_int(struct core_binary_heap_array *self,
void *key1, void *key2)
{
int a;
int b;
a = *(int *)key1;
b = *(int *)key2;
return a > b;
}
int core_binary_heap_array_test_relation_greater_than_uint64_t(struct core_binary_heap_array *self,
void *key1, void *key2)
{
uint64_t a;
uint64_t b;
a = *(uint64_t *)key1;
b = *(uint64_t *)key2;
return a > b;
}
int core_binary_heap_array_test_relation_greater_than_void_pointer(struct core_binary_heap_array *self,
void *key1, void *key2)
{
return core_memory_compare(key1, key2, self->key_size) > 0;
}
void core_binary_heap_array_swap(struct core_binary_heap_array *self, int i, int j)
{
void *item_i;
void *item_j;
void *temporary_place;
int pair_size;
/*
* Make space for a temporary place.
*/
if (self->size + 1 > core_vector_size(&self->vector))
core_vector_resize(&self->vector, self->size + 1);
temporary_place = core_vector_at(&self->vector, self->size);
item_i = core_vector_at(&self->vector, i);
item_j = core_vector_at(&self->vector, j);
pair_size = self->key_size + self->value_size;
core_memory_copy(temporary_place, item_i, pair_size);
core_memory_copy(item_i, item_j, pair_size);
core_memory_copy(item_j, temporary_place, pair_size);
}
int core_binary_heap_array_size(struct core_binary_heap_array *self)
{
return self->size;
}
int core_binary_heap_array_empty(struct core_binary_heap_array *self)
{
return self->size == 0;
}
void core_binary_heap_array_sift_down(struct core_binary_heap_array *self, int i)
{
int left_child;
int right_child;
int selected_child;
while (1) {
left_child = core_binary_heap_array_get_first_child(i);
right_child = core_binary_heap_array_get_second_child(i);
/*
* The node i is already at the good place with respect to
* its children (which are possible not existent).
*/
if ((!(left_child < self->size) || !core_binary_heap_array_test_relation(self, left_child, i))
&& (!(right_child < self->size) || !core_binary_heap_array_test_relation(self, right_child, i)))
return;
selected_child = -1;
/*
* At this point, some swap operations are required.
*
* There is at least 1 child.
*/
if (left_child < self->size)
selected_child = left_child;
/*
* There is no right child (and therefore there is a left child)
* or the RELATION(left, right) is TRUE (left < right or left > right).
*/
if (selected_child == -1
|| (right_child < self->size
&& core_binary_heap_array_test_relation(self, left_child, right_child)))
selected_child = right_child;
/*
*/
CORE_DEBUGGER_ASSERT(selected_child != -1);
#ifdef CORE_DEBUGGER_ASSERT_ENABLED
if (!(selected_child < self->size)) {
printf("selected_child = %d size = %d\n", selected_child,
self->size);
}
#endif
CORE_DEBUGGER_ASSERT(selected_child < self->size);
CORE_DEBUGGER_ASSERT(selected_child >= 0);
/*
* Swap items and continue.
*/
core_binary_heap_array_swap(self, i, selected_child);
i = selected_child;
}
}
void core_binary_heap_array_set_memory_pool(struct core_binary_heap_array *self,
struct core_memory_pool *pool)
{
core_vector_set_memory_pool(&self->vector, pool);
}
| 2.34375 | 2 |
2024-11-18T21:29:45.065811+00:00 | 2018-10-19T00:34:53 | 6e11db45b18e22f41ba2dd27919dd4189705651e | {
"blob_id": "6e11db45b18e22f41ba2dd27919dd4189705651e",
"branch_name": "refs/heads/master",
"committer_date": "2018-10-19T00:34:53",
"content_id": "7997dc612562300cd6f7955b6e7e6594234bc6ab",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "d2507bfc2cbeea5ef050a2ecc3a21b0b3b12a770",
"extension": "c",
"filename": "i2c.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 143207413,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5580,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/projects/lib/i2c.c",
"provenance": "stackv2-0112.json.gz:177540",
"repo_name": "krtkl/piSmasher-software",
"revision_date": "2018-10-19T00:34:53",
"revision_id": "b67f63c0a0ebe8ac2aac7442a82ca6634fc43d9d",
"snapshot_id": "6aa146245b186c586a24d829558fe7784fdfa2c0",
"src_encoding": "UTF-8",
"star_events_count": 4,
"url": "https://raw.githubusercontent.com/krtkl/piSmasher-software/b67f63c0a0ebe8ac2aac7442a82ca6634fc43d9d/projects/lib/i2c.c",
"visit_date": "2020-03-25T00:49:08.037276"
} | stackv2 | /*
* i2c.c
*
* Created on: Jul 11, 2017
* Author: Russell Bush
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <errno.h>
#include <fcntl.h>
#include <linux/i2c.h>
#include <linux/i2c-dev.h>
#include <sys/ioctl.h>
#include "i2c.h"
#define I2C_NDEVS (16)
struct i2c_addr_fd {
uint8_t addr;
int fd;
};
static struct i2c_addr_fd i2c_fd[I2C_NDEVS];
static int i2c_ndevs = 0;
static int i2c_addr_fd_lookup(struct i2c_addr_fd *tab, int len, uint8_t addr)
{
int i;
int fd = -1;
for (i = 0; i < len; i++, tab++)
if (tab->addr == addr)
fd = tab->fd;
return fd;
}
static inline __s32 i2c_smbus_access(int fd, char read_write, __u8 cmd,
int size, union i2c_smbus_data *data)
{
struct i2c_smbus_ioctl_data args;
args.read_write = read_write;
args.command = cmd;
args.size = size;
args.data = data;
return ioctl(fd, I2C_SMBUS, &args);
}
static inline __s32 i2c_smbus_read_byte_data(int fd, __u8 cmd)
{
union i2c_smbus_data data;
if (i2c_smbus_access(fd, I2C_SMBUS_READ, cmd, I2C_SMBUS_BYTE_DATA, &data))
return -1;
else
return 0x0FF & data.byte;
}
static inline __s32 i2c_smbus_write_byte_data(int fd, __u8 cmd,
__u8 val)
{
union i2c_smbus_data data;
data.byte = val;
return i2c_smbus_access(fd, I2C_SMBUS_WRITE, cmd,
I2C_SMBUS_BYTE_DATA, &data);
}
static inline __s32 i2c_smbus_read_word_data(int fd, __u8 cmd)
{
union i2c_smbus_data data;
if (i2c_smbus_access(fd, I2C_SMBUS_READ, cmd, I2C_SMBUS_WORD_DATA, &data))
return -1;
else
return 0x0FFFF & data.word;
}
static inline __s32 i2c_smbus_write_word_data(int fd, __u8 cmd,
__u16 val)
{
union i2c_smbus_data data;
data.word = val;
return i2c_smbus_access(fd, I2C_SMBUS_WRITE, cmd, I2C_SMBUS_WORD_DATA, &data);
}
static inline __s32 i2c_smbus_read_block_data(int fd, __u8 cmd,
__u8 *block)
{
int i;
union i2c_smbus_data data;
if (i2c_smbus_access(fd, I2C_SMBUS_READ, cmd,
I2C_SMBUS_BLOCK_DATA, &data))
return -1;
for (i = 1; i <= data.block[0]; i++)
block[i-1] = data.block[i];
return data.block[0];
}
static inline __s32 i2c_smbus_write_block_data(int fd, __u8 cmd,
__u8 len, __u8 *block)
{
int i;
union i2c_smbus_data data;
if (len > 32)
len = 32;
for (i = 1; i <= len; i++)
data.block[i] = block[i-1];
data.block[0] = len;
return i2c_smbus_access(fd, I2C_SMBUS_WRITE, cmd, I2C_SMBUS_BLOCK_DATA, &data);
}
static inline __s32 i2c_smbus_read_i2c_block_data(int fd, __u8 cmd,
__u8 len, __u8 *block)
{
int i;
union i2c_smbus_data data;
if (len > 32)
len = 32;
data.block[0] = len;
if (i2c_smbus_access(fd, I2C_SMBUS_READ, cmd,
len == 32 ? I2C_SMBUS_I2C_BLOCK_BROKEN :
I2C_SMBUS_I2C_BLOCK_DATA, &data))
return -1;
for (i = 1; i <= data.block[0]; i++)
block[i-1] = data.block[i];
return data.block[0];
}
static inline __s32 i2c_smbus_write_i2c_block_data(int fd, __u8 cmd,
__u8 len, __u8 *block)
{
int i;
union i2c_smbus_data data;
if (len > 32)
len = 32;
for (i = 1; i <= len; i++)
data.block[i] = block[i-1];
data.block[0] = len;
return i2c_smbus_access(fd, I2C_SMBUS_WRITE, cmd,
I2C_SMBUS_I2C_BLOCK_BROKEN, &data);
}
/**
* @brief Initialize I2C device for communication
*/
int i2c_init(uint8_t addr)
{
int err;
int fd;
/* Perform filename parsing here */
fd = open("/dev/i2c-0", O_RDWR);
if (fd < 0)
return fd;
/* Add the file descriptor to the list */
i2c_fd[i2c_ndevs].fd = fd;
i2c_fd[i2c_ndevs].addr = addr;
err = ioctl(i2c_fd[i2c_ndevs].fd, I2C_SLAVE, addr);
if (err < 0)
return err;
i2c_ndevs++;
return fd;
}
int i2c_close(uint8_t sl_addr)
{
int fd;
fd = i2c_addr_fd_lookup(i2c_fd, i2c_ndevs, sl_addr);
if (fd < 0)
return fd;
close(fd);
return 0;
}
/**
* @brief Write a byte value to a register on an I2C slave device
*
* @sl_addr
* @reg_addr
* @data
* @return
*/
int i2c_write_reg(uint16_t sl_addr, uint8_t reg_addr, uint8_t *data)
{
int fd, error;
fd = i2c_addr_fd_lookup(i2c_fd, i2c_ndevs, sl_addr);
if (fd < 0)
return fd;
error = i2c_smbus_write_byte_data(fd, reg_addr, *data);
if (error < 0)
return error;
return 0;
}
/**
* @brief Read a byte value from a register on an I2C slave device
*
* @sl_addr
* @reg_addr
* @data
* @return
*/
int i2c_read_reg(uint16_t sl_addr, uint8_t reg_addr, uint8_t *data)
{
int tmp, fd;
fd = i2c_addr_fd_lookup(i2c_fd, i2c_ndevs, sl_addr);
if (fd < 0)
return fd;
tmp = i2c_smbus_read_byte_data(fd, reg_addr);
if (tmp < 0)
return tmp;
*data = tmp;
return 0;
}
int i2c_write_block(uint16_t sl_addr, uint8_t reg_addr, uint8_t len, uint8_t *data)
{
int tmp, fd;
fd = i2c_addr_fd_lookup(i2c_fd, i2c_ndevs, sl_addr);
if (fd < 0)
return fd;
tmp = i2c_smbus_write_block_data(fd, reg_addr, len, data);
if (tmp < 0)
return tmp;
return 0;
}
int i2c_read_block(uint16_t sl_addr, uint8_t reg_addr, uint8_t len, uint8_t *data)
{
int i, fd, err;
union i2c_smbus_data bus_data;
fd = i2c_addr_fd_lookup(i2c_fd, i2c_ndevs, sl_addr);
if (fd < 0)
return fd;
err = i2c_smbus_read_i2c_block_data(fd, reg_addr, len, data);
if (err < 0)
return err;
return 0;
}
| 2.515625 | 3 |
2024-11-18T21:29:46.058401+00:00 | 2020-12-15T03:14:29 | 93b2ebe6a1115259b507947c45256adc49f64e2e | {
"blob_id": "93b2ebe6a1115259b507947c45256adc49f64e2e",
"branch_name": "refs/heads/main",
"committer_date": "2020-12-15T03:14:29",
"content_id": "8faf4117b8812020344ee70c4df8157c64ffa901",
"detected_licenses": [
"MIT"
],
"directory_id": "c349a18d12a6ee89d3b4835beb9b4dd2c352a5b5",
"extension": "c",
"filename": "loopdet.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": 11007,
"license": "MIT",
"license_type": "permissive",
"path": "/src/loop/loopdet.c",
"provenance": "stackv2-0112.json.gz:178194",
"repo_name": "evgeni-skk/SparX-III_Unmanaged",
"revision_date": "2020-12-15T03:14:29",
"revision_id": "7d85d2b0dc765e22a5c7ce1348edc91d766f7f41",
"snapshot_id": "614acb8f3dfb34a89caf8d2cc50a16fac897185f",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/evgeni-skk/SparX-III_Unmanaged/7d85d2b0dc765e22a5c7ce1348edc91d766f7f41/src/loop/loopdet.c",
"visit_date": "2023-05-30T22:34:05.227945"
} | stackv2 | //Copyright (c) 2004-2020 Microchip Technology Inc. and its subsidiaries.
//SPDX-License-Identifier: MIT
#define LOOPDETECT_DEBUG (0)
#include "common.h" /* Always include common.h at the first place of user-defined herder files */
#include "ledtsk.h"
#include "vtss_luton26_reg.h"
#include "h2io.h"
#include "h2.h"
#include "timer.h"
#include "main.h"
#include "phydrv.h"
#include "phytsk.h"
#include "phymap.h"
#include "hwport.h"
#include "misc2.h"
#if LOOPDETECT_DEBUG
#include "print.h"
#endif
#if TRANSIT_LOOPDETECT
/*****************************************************************************
*
*
* Defines
*
*
*
****************************************************************************/
#define LOOPBACK_AGE_TIMEOUT (100)
#define LOOP_DETECT_MAX (2)
/*****************************************************************************
*
*
* Typedefs and enums
*
*
*
****************************************************************************/
typedef enum {
IDLE,
MONITORING,
LOOPING
} state_t;
enum {
VTSS_PGID_DEST_MASK_START = 0,
VTSS_PGID_AGGR_MASK_START = 64,
VTSS_PGID_SOURCE_MASK_START = 80
};
/*****************************************************************************
*
*
* Prototypes for local functions
*
*
*
****************************************************************************/
/*****************************************************************************
*
*
* Local data
*
*
*
****************************************************************************/
/* Boot up status is IDLE */
static state_t g_state = IDLE;
static bit ldet_aging_timer_started = 0;
static uchar loopback_aging_timeout = LOOPBACK_AGE_TIMEOUT;
static port_bit_mask_t log_block_mask = 0;
static uchar xdata loop_count [NO_OF_PORTS];
static bit led_on_flag = 0;
static port_bit_mask_t log_blocked_mask = 0;
static port_bit_mask_t cpu_learned_loop_mask = 0;
/*****************************************************************************
*
*
* Local functins
*
*
*
****************************************************************************/
#if LOOPDETECT_DEBUG
static void ldet_print_port_mask(char *str, port_bit_mask_t mask)
{
print_str(str);
print_hex_prefix();
print_hex_dw(mask);
print_cr_lf();
}
#endif
static void ldet_status_set (state_t new_state)
{
if (new_state != g_state) {
#if LOOPDETECT_DEBUG
print_str("ldet: state ");
print_dec(g_state);
print_str(" -> ");
print_dec(new_state);
print_cr_lf();
#endif
}
g_state = new_state;
}
#if LOOPDETECT_DEBUG
static state_t ldet_status_get ( void )
{
return g_state;
}
#endif
static void ldet_down_ports_clear (
port_bit_mask_t link_mask
) {
vtss_port_no_t port_no;
vtss_port_no_t i_port_no;
for (port_no = 1; port_no <= NO_OF_PORTS; port_no++)
{
i_port_no = port2int(port_no);
if (TEST_PORT_BIT_MASK(i_port_no, &link_mask))
continue;
// clear the counter when the port is linkdown
loop_count[ port_no - 1 ] = 0;
//clear mask if link down
WRITE_PORT_BIT_MASK(i_port_no, 0, &log_block_mask);
//clear mask if link down
WRITE_PORT_BIT_MASK(i_port_no, 0, &cpu_learned_loop_mask);
}
}
static void ldet_timer_refresh (void)
{
/* loop might happend, start to monitor if happened again in 10 second */
ldet_aging_timer_started = 1;
loopback_aging_timeout = LOOPBACK_AGE_TIMEOUT; // Refresh the timer
}
/*****************************************************************************
*
*
* Public API functins
*
*
*
****************************************************************************/
void ldettsk ( void )
{
port_bit_mask_t move_mask;
port_bit_mask_t link_mask;
vtss_port_no_t port_no;
vtss_port_no_t i_port_no;
uchar lp_eab;
/*
* 1. Read current move mask
*/
H2_READ (VTSS_ANA_ANA_TABLES_ANMOVED, move_mask);
H2_WRITE(VTSS_ANA_ANA_TABLES_ANMOVED, 0); // Clear the counter
/*
* 2. Read link mask and clear counters and masks if a port is linked down.
*/
link_mask = phy_get_link_mask();
ldet_down_ports_clear(link_mask);
/*
* 3. If there is a *possible* loop condition, start/refresh timer.
*/
if (move_mask || cpu_learned_loop_mask)
{
#if LOOPDETECT_DEBUG
if (!ldet_aging_timer_started)
{
if (move_mask)
ldet_print_port_mask("ldet: move mask: ", move_mask);
if (cpu_learned_loop_mask)
ldet_print_port_mask("ldet: self mac: ", cpu_learned_loop_mask);
}
#endif
ldet_timer_refresh();
ldet_status_set( MONITORING );
}
/*
* 4. If timer is started and we found:
* 4.1 Possible loop of MAC address move on some ports.
* - Increment the counter of those ports.
* - If counter exceeds LOOP_DETECT_MAX, consider it as a loop.
* 4.2 Found the MAC address of myself from some ports.
* - Consider it as a loop.
*/
if (ldet_aging_timer_started && (move_mask || cpu_learned_loop_mask))
{
for (port_no = 1; port_no <= NO_OF_PORTS; port_no++)
{
i_port_no = port2int(port_no);
if ( TEST_PORT_BIT_MASK(i_port_no, &cpu_learned_loop_mask) )
{
#if LOOPDETECT_DEBUG
if ( ldet_status_get() != LOOPING ) {
print_str("ldet: looped at ");
print_dec(port_no);
print_cr_lf();
}
#endif
WRITE_PORT_BIT_MASK(i_port_no, 1, &log_block_mask); //Local looped
loop_count[ port_no - 1 ] = 0;
WRITE_PORT_BIT_MASK(i_port_no, 0, &cpu_learned_loop_mask); //clear mask after log
ldet_status_set ( LOOPING );
}
else if ( TEST_PORT_BIT_MASK( i_port_no, &move_mask ) )
{
if ( loop_count[ port_no - 1] < LOOP_DETECT_MAX )
{
/* Update counter block */
loop_count[ port_no - 1]++;
}
else
{
#if LOOPDETECT_DEBUG
if ( ldet_status_get() != LOOPING ) {
print_str("ldet: looped at ");
print_dec(port_no);
print_cr_lf();
}
#endif
WRITE_PORT_BIT_MASK(i_port_no, 1, &log_block_mask);
loop_count[port_no - 1] = 0;
ldet_status_set ( LOOPING );
}
}
}
}
/*
* 5. If the new block mask may have changed (log_block_mask) from old
* mask (log_blocked_mask), update it to LED.
*/
if ( log_block_mask != log_blocked_mask )
{
log_blocked_mask |= log_block_mask;
for (port_no = 1; port_no <= NO_OF_PORTS; port_no++)
{
vtss_led_mode_type_t led_mode;
i_port_no = port2int(port_no);
if (!TEST_PORT_BIT_MASK(i_port_no, &link_mask)) {
WRITE_PORT_BIT_MASK(i_port_no, 0, &log_blocked_mask);
}
#if FRONT_LED_PRESENT
led_mode = TEST_PORT_BIT_MASK(i_port_no, &log_blocked_mask) ?
VTSS_LED_MODE_OFF :
VTSS_LED_MODE_BLINK_YELLOW;
led_state_set(port_no, VTSS_LED_EVENT_CABLE, led_mode);
#endif
}
led_on_flag = 1;
#if LOOPDETECT_DEBUG
print_str("update blink ...\r\n");
#endif
}
else if ( log_blocked_mask )
{
if (!led_on_flag)
{
for (port_no = 1; port_no <= NO_OF_PORTS; port_no++)
{
i_port_no = port2int(port_no);
if (!TEST_PORT_BIT_MASK(i_port_no, &link_mask)) {
WRITE_PORT_BIT_MASK(i_port_no, 0, &log_blocked_mask);
}
#if FRONT_LED_PRESENT
if (TEST_PORT_BIT_MASK(i_port_no, &log_blocked_mask)) {
led_state_set(port_no, VTSS_LED_EVENT_CABLE, VTSS_LED_MODE_OFF);
} else {
led_state_set(port_no, VTSS_LED_EVENT_CABLE, VTSS_LED_MODE_BLINK_YELLOW);
}
#endif
}
led_on_flag = 1;
#if LOOPDETECT_DEBUG
print_str("blink ...\r\n");
#endif
}
}
/*
* 6. If no loop happened again, stop blinking
*/
if (!ldet_aging_timer_started) {
if (led_on_flag) {
#if FRONT_LED_PRESENT
for (port_no = 1; port_no <= NO_OF_PORTS; port_no++) {
led_state_set(port_no, VTSS_LED_EVENT_CABLE, VTSS_LED_MODE_NORMAL);
}
#endif
led_on_flag = 0;
#if LOOPDETECT_DEBUG
ldet_status_set ( IDLE );
#endif
}
for (port_no = 1; port_no <= NO_OF_PORTS; port_no++) {
i_port_no = port2int(port_no);
loop_count[port_no - 1] = 0;
}
log_block_mask = 0x0; // Clear the loop port mask record
log_blocked_mask = 0x0;
}
/*
* 7. Block/Unblock port forwarding.
*/
lp_eab = 1;
for ( port_no = 1; port_no <= NO_OF_PORTS; port_no++ )
{
#if LOOPDETECT_DEBUG
static port_bit_mask_t src_fwd_mask_backup[ NO_OF_PORTS ];
port_bit_mask_t src_fwd_mask;
#endif
unsigned long addr;
port_bit_mask_t inv_mask;
i_port_no = port2int(port_no);
addr = VTSS_ANA_ANA_TABLES_PGID(i_port_no + VTSS_PGID_SOURCE_MASK_START);
inv_mask = ~PORT_BIT_MASK(i_port_no) & link_mask;
if (lp_eab)
inv_mask &= ~log_blocked_mask;
H2_WRITE_MASKED(addr, inv_mask, ALL_PORTS);
#if LOOPDETECT_DEBUG
H2_READ(addr, src_fwd_mask);
if ( src_fwd_mask_backup[ port_no - 1 ] != src_fwd_mask ) {
print_str("ldet: port ");
print_dec(port_no);
ldet_print_port_mask(" forwarding: ", src_fwd_mask);
src_fwd_mask_backup[ port_no - 1 ] = src_fwd_mask;
}
#endif
}
}
void ldet_aging_100ms (void)
{
if (ldet_aging_timer_started) {
loopback_aging_timeout--;
if (loopback_aging_timeout == 0) {
ldet_aging_timer_started = 0;
}
}
}
void ldet_add_cpu_found (vtss_port_no_t i_port_no)
{
#if LOOPDETECT_DEBUG
if (!TEST_PORT_BIT_MASK(i_port_no, &cpu_learned_loop_mask)) {
print_str("ldet: found self on port ");
print_dec(port2ext(i_port_no));
print_cr_lf();
}
#endif
WRITE_PORT_BIT_MASK(i_port_no, 1, &cpu_learned_loop_mask);
}
#endif /* TRANSIT_LOOPDETECT */
| 2.078125 | 2 |
2024-11-18T21:29:46.200981+00:00 | 2015-02-13T06:03:43 | c15fab410fcfd1620e2834f0b201a682073bd4b6 | {
"blob_id": "c15fab410fcfd1620e2834f0b201a682073bd4b6",
"branch_name": "refs/heads/master",
"committer_date": "2015-02-13T06:03:43",
"content_id": "4e98c7f9b5766d13edd3b454299ef95362b7e38d",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "c06315bccf96c4992b3176a9f2d56260ab8a00a7",
"extension": "c",
"filename": "avl_tree.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 29958717,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 6523,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/avl/avl_tree.c",
"provenance": "stackv2-0112.json.gz:178323",
"repo_name": "don7hao/algorithm",
"revision_date": "2015-02-13T06:03:43",
"revision_id": "43a8c7eab48e17f552407a9d1d07aed6eb0bf85c",
"snapshot_id": "72a8d243b6e2b477ce6b8d34e7229dfdffd3f883",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/don7hao/algorithm/43a8c7eab48e17f552407a9d1d07aed6eb0bf85c/avl/avl_tree.c",
"visit_date": "2021-01-16T23:11:48.840469"
} | stackv2 | /*
* AVL TREE
*/
#include <stdio.h>
#include <stdlib.h>
#include "avl_tree.h"
static void left_rotation(tree_pointer *parent);
static void right_rotation(tree_pointer *parent);
void list_insert(list_head_pointer list_head, tree_pointer *tree_node);
list_pointer list_remove(list_head_pointer list_head);
list_pointer list_remove(list_head_pointer list_head)
{
if (NULL == list_head || NULL == list_head->head){
return NULL;
}
list_pointer tmp = list_head->head;
if (tmp->next == NULL){
list_head->head = NULL;
return tmp;
}
list_pointer prev = tmp;
while(1){
if (NULL == tmp->next){
prev->next = NULL;
break;
}
prev = tmp;
tmp = tmp->next;
}
return tmp;
}
void list_insert(list_head_pointer list_head, tree_pointer *tree_node)
{
list_pointer node = (list_pointer)calloc(1, sizeof(struct list_node));
if (NULL == node){
printf("calloc error!\n");
return;
}
node->data = (void **)(tree_node);
node->next = NULL;
list_pointer head = list_head->head;
if (NULL == head){
list_head->head = node;
}else{
list_pointer tmp = head;
while(NULL != tmp){
if(NULL == tmp->next){
tmp->next = node;
break;
}
tmp = tmp->next;
}
}
return;
}
void avl_print(tree_pointer parent)
{
if (NULL == parent)
return;
avl_print(parent->left_child);
avl_print(parent->right_child);
printf("%d\n", parent->data.key);
return;
}
int main()
{
/*create a avl tree*/
/*element ele[4] = {{10}, {9}, {8}, {7}};*/
element ele[] = {{30}, {20}, {4}, {2}, {9}, {3}, {15}, {5}, {10}};
int size = sizeof(ele)/sizeof(int);
tree_pointer parent = NULL;
while(size > 0){
avl_insert(&parent, ele[--size]);
}
printf("post order:\n");
avl_print(parent);
printf("++++++++++++++++++++\n");
/*search a key in avl tree */
/* insert a tree_node in avl tree */
/* delete a tree_node in avl_treee */
return 0x00;
}
static void right_rotation(tree_pointer *parent)
{
tree_pointer child = (*parent)->right_child;
tree_pointer grand_child = NULL;
if (-1 == child->bf){
printf("RR Rotation : \n");
(*parent)->right_child = child->left_child;
child->left_child = (*parent);
(*parent)->bf = 0x00;
(*parent) = child;
}else{
printf("RL Rotation : \n");
grand_child = child->left_child;
(*parent)->right_child = grand_child->left_child;
child->left_child = grand_child->right_child;
grand_child->left_child = (*parent);
grand_child->right_child = child;
switch(grand_child->bf){
case -1: /* RLR */
(*parent)->bf = 1;
child->bf = 0x00;
break;
case 1: /* RLL */
(*parent)->bf = 0x00;
child->bf = -1;
break;
case 0: /* RL */
(*parent)->bf = 0x00;
child->bf = 0x00;
break;
}
(*parent) = grand_child;
}
(*parent)->bf = 0x00;
return;
}
static void left_rotation(tree_pointer *parent)
{
tree_pointer child = (*parent)->left_child;
tree_pointer grand_child = NULL;
if (0x01 == child->bf){
/* LL rotation */
printf("LL Rotation : \n");
(*parent)->left_child = child->right_child;
child->right_child = (*parent);
(*parent)->bf = 0;
(*parent) = child;
}else{
/* LR rotation */
printf("LR Rotation : \n");
grand_child = child->right_child;
(*parent)->left_child = grand_child->right_child;
child->right_child = grand_child->left_child;
grand_child->left_child = child;
grand_child->right_child = (*parent);
switch(grand_child->bf){
case -1: /* LRR */
child->bf = 0x01;
(*parent)->bf = 0x00;
break;
case 0x01: /* LRL */
child->bf = 0x00;
(*parent)->bf = -1;
break;
case 0x00: /* LR */
child->bf = 0x00;
(*parent)->bf = 0x00;
break;
}
(*parent) = grand_child;
}
(*parent)->bf = 0;
return;
}
void do_rotation(tree_pointer *tp)
{
switch((*tp)->bf){
case 0x00:
((*tp)->flag == RIGHT_WEIGHT)?((*tp)->bf = -1):((*tp)->bf = 1);
break;
case 0x01:
if ((*tp)->flag == RIGHT_WEIGHT){
(*tp)->bf = 0x00;
}else{
if (0x00 != (*tp)->left_child->bf){
left_rotation(tp);
}
}
break;
case -1:
if ((*tp)->flag == RIGHT_WEIGHT){
if (0x00 != (*tp)->right_child->bf){
right_rotation(tp);
}
}else{
(*tp)->bf = 0x00;
}
break;
default:
printf("balance factor was abnormal!\n");
break;
}
return;
}
int avl_insert(tree_pointer *parent, element x)
{
struct list_head head = {NULL};
tree_pointer leaf_node = (tree_pointer)calloc(1, sizeof(struct tree_node));
if (NULL == leaf_node){
printf("calloc error!\n");
return FALSE;
}
leaf_node->bf = 0x00;
leaf_node->data = x;
leaf_node->right_child = NULL;
leaf_node->left_child = NULL;
leaf_node->flag = -1;
printf("insert x.key : %d\n", x.key);
tree_pointer *tmp_pointer = parent;
while(NULL != *tmp_pointer){
/* insert tree_pointer into tnlist */
list_insert(&head, tmp_pointer);
printf("insert tmp_pointer's key : %d, bf : %d\n\n", (*tmp_pointer)->data.key, (*tmp_pointer)->bf);
if (x.key < (*tmp_pointer)->data.key){
(*tmp_pointer)->flag = LEFT_WEIGHT;
tmp_pointer = &((*tmp_pointer)->left_child);
}else{
(*tmp_pointer)->flag = RIGHT_WEIGHT;
tmp_pointer = &((*tmp_pointer)->right_child);
}
}
*tmp_pointer = leaf_node;
while(NULL != head.head){
list_pointer list_node = list_remove(&head);
do_rotation((tree_pointer *)(list_node->data));
}
printf("++++++++++++++++++++++++++++++++++++++++\n");
return TRUE;
}
| 3.578125 | 4 |
2024-11-18T21:29:46.274509+00:00 | 2014-05-07T14:31:33 | 7ab50614aa9ddc363b2ab3571cc30f0bece28391 | {
"blob_id": "7ab50614aa9ddc363b2ab3571cc30f0bece28391",
"branch_name": "refs/heads/master",
"committer_date": "2014-05-07T14:31:33",
"content_id": "ef24551fcae3d77675457844bc12d989d81c95f6",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "5168eec901b0e716853563e5a2fb7f4321676ae5",
"extension": "h",
"filename": "machine.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": 1700,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/tools/pegasus-kickstart/machine.h",
"provenance": "stackv2-0112.json.gz:178456",
"repo_name": "tstoltmann/pegasus",
"revision_date": "2014-05-07T14:31:33",
"revision_id": "34970b22f0fc57b52f2dc0b572efcdff7724b2f1",
"snapshot_id": "5827959e9567ea9e05394bce5b03286047a0ba34",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/tstoltmann/pegasus/34970b22f0fc57b52f2dc0b572efcdff7724b2f1/src/tools/pegasus-kickstart/machine.h",
"visit_date": "2021-01-17T08:47:17.261119"
} | stackv2 | /*
* This file or a portion of this file is licensed under the terms of
* the Globus Toolkit Public License, found in file GTPL, or at
* http://www.globus.org/toolkit/download/license.html. This notice must
* appear in redistributions of this file, with or without modification.
*
* Redistributions of this Software, with or without modification, must
* reproduce the GTPL in: (1) the Software, or (2) the Documentation or
* some other similar material which is provided with the Software (if
* any).
*
* Copyright 1999-2004 University of Chicago and The University of
* Southern California. All rights reserved.
*/
#ifndef _MACHINE_H
#define _MACHINE_H
#include <stdio.h>
#include <sys/types.h>
typedef struct {
/* virtual method table */
void* (*ctor)( void );
int (*show)( FILE*, int, const char*, const void* );
void (*dtor)( void* );
/* mutable object data */
void* data;
} MachineInfo;
extern
void
initMachineInfo( MachineInfo* machine );
/* purpose: initialize the data structure.
* paramtr: machine (OUT): initialized MachineInfo structure.
*/
extern
int
printXMLMachineInfo(FILE *out, int indent, const char* tag,
const MachineInfo* machine);
/* purpose: format the job information into the given stream as XML.
* paramtr: out (IO): The stream
* indent (IN): indentation level
* tag (IN): name to use for element tags.
* machine (IN): machine info to print.
* returns: number of characters put into buffer (buffer length)
*/
extern
void
deleteMachineInfo( MachineInfo* machine );
/* purpose: destructor
* paramtr: machine (IO): valid MachineInfo structure to destroy.
*/
#endif /* _MACHINE_H */
| 2.09375 | 2 |
2024-11-18T21:29:46.346814+00:00 | 2018-11-04T18:47:51 | be06d88b3bed53e1aa4b76d565d213a96c812f0d | {
"blob_id": "be06d88b3bed53e1aa4b76d565d213a96c812f0d",
"branch_name": "refs/heads/master",
"committer_date": "2018-11-04T18:47:51",
"content_id": "41aa70d4ac3d95d60036eee188d9e06fd4b82b30",
"detected_licenses": [
"MIT"
],
"directory_id": "42c3afe82e78bd27076bb94e5ec03667aac3d366",
"extension": "c",
"filename": "irq.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 139850899,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2834,
"license": "MIT",
"license_type": "permissive",
"path": "/src/kernel/kernel/irq.c",
"provenance": "stackv2-0112.json.gz:178586",
"repo_name": "DrDeano/DeanOS",
"revision_date": "2018-11-04T18:47:51",
"revision_id": "845223d085a2c5efc2a77f0a491a58b8a297637d",
"snapshot_id": "196849adc105dc8980cb8a0b0ae57ea0e86d6a52",
"src_encoding": "UTF-8",
"star_events_count": 7,
"url": "https://raw.githubusercontent.com/DrDeano/DeanOS/845223d085a2c5efc2a77f0a491a58b8a297637d/src/kernel/kernel/irq.c",
"visit_date": "2020-03-22T09:38:44.467561"
} | stackv2 | #include <irq.h>
#include <portio.h>
#include <idt.h>
#include <pic.h>
extern void _irq00();
extern void _irq01();
extern void _irq02();
extern void _irq03();
extern void _irq04();
extern void _irq05();
extern void _irq06();
extern void _irq07();
extern void _irq08();
extern void _irq09();
extern void _irq10();
extern void _irq11();
extern void _irq12();
extern void _irq13();
extern void _irq14();
extern void _irq15();
/**
* \brief The list of handlers for each IRQ.
*/
static irq_handler irq_handlers[IRQ_TOTAL] = {
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0
};
void irq_install_handler(int irq_num, irq_handler handler) {
irq_handlers[irq_num] = handler;
}
void irq_uninstall_handler(int irq_num) {
irq_handlers[irq_num] = 0;
}
/**
* \brief Each of the IRQ ISR's point to this function, rather than the 'fault_handler' in 'isr.c'.
* The IRQ Controllers need to be told when you are done servicing them, so you need to send them
* an "End of Interrupt" command (0x20).
*
* \param [in] regs The registers when this is called.
*/
void _irq_handler(regs_t * regs) {
uint8_t irq_num = regs->int_num - 32;
// Get the handler
irq_handler handler = irq_handlers[irq_num];
// Run the handler if got one
if (handler) {
handler(regs);
}
// Send the end of interrupt command
pic_send_end_of_interrupt(irq_num);
}
void irq_set_mask(uint8_t irq_num) {
uint16_t port;
uint8_t value;
if(irq_num < 8) {
port = PIC_INTERRUPT_MASK_REG_MASTER;
} else {
port = PIC_INTERRUPT_MASK_REG_SLAVE;
irq_num -= 8;
}
value = in_port_byte(port) | (1 << irq_num);
out_port_byte(port, value);
}
void irq_clear_mask(uint8_t irq_num) {
uint16_t port;
uint8_t value;
if(irq_num < 8) {
port = PIC_INTERRUPT_MASK_REG_MASTER;
} else {
port = PIC_INTERRUPT_MASK_REG_SLAVE;
irq_num -= 8;
}
value = in_port_byte(port) & ~(1 << irq_num);
out_port_byte(port, value);
}
void irq_init(void) {
// Remap the PIC IRQ so not to overlap with other exceptions
pic_remap_irq();
// Open all the IRQ's
idt_open_interrupt_gate(32, (uint32_t) &_irq00);
idt_open_interrupt_gate(33, (uint32_t) &_irq01);
idt_open_interrupt_gate(34, (uint32_t) &_irq02);
idt_open_interrupt_gate(35, (uint32_t) &_irq03);
idt_open_interrupt_gate(36, (uint32_t) &_irq04);
idt_open_interrupt_gate(37, (uint32_t) &_irq05);
idt_open_interrupt_gate(38, (uint32_t) &_irq06);
idt_open_interrupt_gate(39, (uint32_t) &_irq07);
idt_open_interrupt_gate(40, (uint32_t) &_irq08);
idt_open_interrupt_gate(41, (uint32_t) &_irq09);
idt_open_interrupt_gate(42, (uint32_t) &_irq10);
idt_open_interrupt_gate(43, (uint32_t) &_irq11);
idt_open_interrupt_gate(44, (uint32_t) &_irq12);
idt_open_interrupt_gate(45, (uint32_t) &_irq13);
idt_open_interrupt_gate(46, (uint32_t) &_irq14);
idt_open_interrupt_gate(47, (uint32_t) &_irq15);
}
| 2.71875 | 3 |
2024-11-18T21:29:46.442754+00:00 | 2015-02-27T04:14:54 | 60778435324187fdf00bfa94d7f334964cbcec9e | {
"blob_id": "60778435324187fdf00bfa94d7f334964cbcec9e",
"branch_name": "refs/heads/master",
"committer_date": "2015-02-27T04:14:54",
"content_id": "762cea1b712bdd7b29ba9ae8450f9841281e066c",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "8951bfce1ca941fb5681c9ec547f930c15f962dd",
"extension": "c",
"filename": "fsh.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": 142,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/src/fsh.c",
"provenance": "stackv2-0112.json.gz:178716",
"repo_name": "saadj55/fsh",
"revision_date": "2015-02-27T04:14:54",
"revision_id": "0c7140e2841acd53093aa9ac4ce516166963a788",
"snapshot_id": "4982f551f3bacaafc5177b87334fb7a91797f5ea",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/saadj55/fsh/0c7140e2841acd53093aa9ac4ce516166963a788/src/fsh.c",
"visit_date": "2020-04-09T10:35:46.740171"
} | stackv2 | #include <stdio.h>
#include <stdlib.h>
int main()
{
printf("Well, welcome to the fucking shell, %s!\n", getenv("USER"));
return 1;
}
| 2.015625 | 2 |
2024-11-18T21:29:46.662160+00:00 | 2020-09-15T06:54:33 | f3866f42c848fecf91b946fc763fac74d44f35ee | {
"blob_id": "f3866f42c848fecf91b946fc763fac74d44f35ee",
"branch_name": "refs/heads/master",
"committer_date": "2020-09-15T06:54:33",
"content_id": "7d701fd222b071e923e10029661dc701596b2f16",
"detected_licenses": [
"MIT"
],
"directory_id": "0c06bdcd1e65a8864f94e05b1d383361d8314b49",
"extension": "c",
"filename": "udict.c",
"fork_events_count": 0,
"gha_created_at": "2017-09-07T15:15:16",
"gha_event_created_at": "2017-09-11T07:10:22",
"gha_language": "C",
"gha_license_id": null,
"github_id": 102752555,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 6521,
"license": "MIT",
"license_type": "permissive",
"path": "/src/udict.c",
"provenance": "stackv2-0112.json.gz:178975",
"repo_name": "masscry/alpha0",
"revision_date": "2020-09-15T06:54:33",
"revision_id": "ee8cd2fe783f368362c72e6c50fd09a5f2826b7f",
"snapshot_id": "1b783dd1df81349d496727d2542101bd58635171",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/masscry/alpha0/ee8cd2fe783f368362c72e6c50fd09a5f2826b7f/src/udict.c",
"visit_date": "2021-01-23T16:57:14.898660"
} | stackv2 | #include <stdio.h>
#include <udict.h>
/**
* Internal structure of hash table item.
*/
struct _udict_item_ {
uint32_t key; /**< Key */
void* value; /**< Value */
};
/**
* Internal structure of hash table
*/
struct _udict_ {
uint32_t cap; /**< Capacity */
uint32_t size; /**< Size */
uint32_t* dups; /**< Number of duplicates */
uint8_t* active; /**< Is bucket empty */
UDITEM data; /**< Actual table */
};
UDICT udInit(uint32_t icap){
UDICT result = 0;
void* tmpMem = 0;
if (icap == 0){
return 0;
}
result = (UDICT)malloc(sizeof(struct _udict_));
if (result == 0){
return 0;
}
result->size = 0;
result->cap = icap;
/*
* Small memory allocation optimization.
*
* Allocate three arrays with as one chunk.
*/
tmpMem = calloc(icap, sizeof(uint32_t) + sizeof(uint8_t) + sizeof(struct _udict_item_));
if (tmpMem == 0){
free(result);
return 0;
}
/*
* Then setup arrays accordingly
*/
result->dups = (uint32_t*)tmpMem;
result->active = (uint8_t*)(result->dups + icap);
result->data = (UDITEM)(result->active + icap);
return result;
}
UDICT udRehash(UDICT* old, uint32_t icap){
UDICT nhash = 0;
if ((old != 0) && (*old != 0)){
if (icap < udCap(*old)){
return 0;
}
}
nhash = udInit(icap);
if (nhash == 0){
return 0;
}
if ((old != 0) && (*old != 0)){
/* Actual rehashing */
uint32_t cap = udCap(*old);
uint32_t ind = 0;
for (ind = 0; ind < cap; ++ind){
if ( (*old)->active[ind] != 0 ){
/* No test on udInsert result, because everything must fit */
udInsert(
nhash,
(*old)->data[ind].key,
(*old)->data[ind].value
);
}
}
udCleanup(old);
}
return nhash;
}
void udCleanup(UDICT* ud){
udCleanupDeep(ud, 0);
}
void udCleanupDeep(UDICT* ud, udCleanupFunc func){
if (ud != 0){
if (*ud != 0){
if (func != 0) {
uint32_t index = 0;
while((udSize(*ud) > 0) && (index < udCap(*ud))) {
if ((*ud)->active[index] != 0) {
func((*ud)->data + index);
(*ud)->active[index] = 0;
--(*ud)->size;
}
++index;
}
}
free((*ud)->dups);
free(*ud);
*ud = 0;
}
}
}
uint32_t udSize(const UDICT ud){
if (ud == 0){
return 0;
}
return ud->size;
}
uint32_t udCap(const UDICT ud){
if (ud == 0){
return 0;
}
return ud->cap;
}
UDITEM udInsert(UDICT ud, uint32_t key, void* data){
uint32_t plk = key & (ud->cap-1);
int looped = 2;
if (ud->size == ud->cap){ /* No space left */
return 0;
}
while(looped-->0) {
while ((plk < ud->cap)&&(ud->active[plk] != 0)) {
ud->dups[plk] += (ud->data[plk].key == key); /* better that if-clause? */
++plk;
}
if (plk != ud->cap){ /* Found empty item */
break;
}
plk = 0; /* rewind to start */
}
if (ud->active[plk] != 0){
/* after looping didn't found empty item */
return 0;
}
ud->size += 1;
ud->active[plk] = 1;
ud->data[plk].key = key;
ud->data[plk].value = data;
return ud->data+plk;
}
/**
* @todo Add test for insertion of new pair when capacity reached.
*/
UDITEM udReset(UDICT ud, uint32_t key, void* data){
uint32_t plk = key & (ud->cap-1);
int looped = 2;
while(looped-->0) {
/* Here may be added the insertion test */
while ((plk < ud->cap)&&(ud->active[plk] != 0) /* Is active */
&& (ud->data[plk].key != key)){ /* But different key */
++plk;
}
if (plk != ud->cap){ /* Found empty item */
break;
}
plk = 0; /* rewind to start */
}
if ((ud->active[plk] != 0) && (ud->data[plk].key != key)){
/* after looping didn't found empty item */
return 0;
}
ud->size += (ud->active[plk] == 0);
ud->active[plk] = 1;
ud->data[plk].key = key;
ud->data[plk].value = data;
return ud->data+plk;
}
UDITEM udFind(const UDICT ud, uint32_t key){
uint32_t plk = 0;
int looped = 2;
if (ud == 0) {
return 0;
}
plk = key & (ud->cap-1);
while (looped-->0) {
while ((plk < ud->cap) /* And less than cap */
&& (ud->active[plk] != 0) /* Active */
&& (ud->data[plk].key != key) /* But different key */
){
++plk; /* Iterate */
}
if (plk == ud->cap){ /* Hit capacity, rewind */
plk = 0;
continue;
}
if (ud->active[plk] == 0){ /* If stopped at non-active, than no items with such key left */
return 0;
}
if (ud->data[plk].key == key){
return ud->data + plk;
}
}
return 0;
}
void* udGet(const UDICT ud, uint32_t key){
UDITEM it = udFind(ud, key);
if (it != 0){
return it->value;
}
return 0;
}
uint32_t udKey(const UDITEM item){
return item->key;
}
void* udValue(const UDITEM item){
return item->value;
}
void udSetValue(UDITEM item, void* value) {
item->value = value;
}
UDITEM udNext(UDICT ud, UDITEM item){
uint32_t left = udLeft(ud, item);
int looped = 2;
uint32_t plk = item - ud->data + 1; /* Next item after this */
if (left == 0){
return 0;
}
while (looped-->0){
while ((plk < ud->cap) /* And less than cap */
&& (ud->active[plk] != 0) /* Active */
&& (ud->data[plk].key != udKey(item)) /* But different key */
){
++plk; /* Iterate */
}
if (plk == ud->cap){ /* Hit capacity, rewind */
plk = 0;
continue;
}
return ud->data + plk;
}
return 0;
}
uint32_t udLeft(UDICT ud, UDITEM item){
uint32_t pos = item - ud->data;
return ud->dups[pos];
}
UDITEM udIterFirst(UDICT ud) {
uint32_t index = 0;
if (ud == 0) {
return 0;
}
if (ud->size == 0) {
return 0;
}
for (index = 0; index < ud->cap; ++index) {
if (ud->active[index] != 0) {
return ud->data + index;
}
}
return 0;
}
UDITEM udIterNext(UDICT ud, UDITEM item) {
uint32_t index = 0;
if ((ud == 0) || (item == 0)) {
return 0;
}
for (index = item - ud->data + 1; index < ud->cap; ++index) {
if (ud->active[index] != 0) {
return ud->data + index;
}
}
return 0;
}
UDITEM udIterLast(UDICT ud) {
int32_t index = 0;
if (ud == 0) {
return 0;
}
for (index = ud->cap - 1; index >= 0; --index) {
if (ud->active[index] != 0) {
return ud->data + index;
}
}
return 0;
} | 2.984375 | 3 |
2024-11-18T21:29:47.309744+00:00 | 2016-12-12T02:32:35 | d62f8f350fe2615d6e338b16898041dfde2c05b6 | {
"blob_id": "d62f8f350fe2615d6e338b16898041dfde2c05b6",
"branch_name": "refs/heads/master",
"committer_date": "2016-12-12T02:32:35",
"content_id": "b898ea0a9fa9c7176acf0edc30e6689baa8394d2",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "da2cfe721a5e85ceb3730b35dc96c752179ab325",
"extension": "h",
"filename": "W25QXX.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 76214343,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1427,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/Project/QBL-Pilot-STD/Module/Driver/W25QXX.h",
"provenance": "stackv2-0112.json.gz:179363",
"repo_name": "QBL-Team/QBL-Pilot-STD-MDK",
"revision_date": "2016-12-12T02:32:35",
"revision_id": "62c51824c81c5051d3b062786a6db080c5557c19",
"snapshot_id": "5de92a9843e924b9156bb5ce1807f2734e243590",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/QBL-Team/QBL-Pilot-STD-MDK/62c51824c81c5051d3b062786a6db080c5557c19/Project/QBL-Pilot-STD/Module/Driver/W25QXX.h",
"visit_date": "2021-01-12T09:38:45.927294"
} | stackv2 | /*!
* \file W25QXX.h
* \author no1wudi
*/
#ifndef __W25QXX_H
#define __W25QXX_H
#include "QBL_Type.h"
/*!
*
* @defgroup w25qxx_driver W25QXX 驱动
* @{
*/
/*!
* \brief W25Q_Init 初始化W25Qx系列的闪存芯片
* \param handle 挂载闪存芯片的SPI总线的句柄
* \return 如果初始化成功,返回true
*/
extern QBL_STATUS W25Q_Init(void);
/*!
* \brief W25Q_CheckForIdle 检查闪存芯片是否处于空闲状态,只有空闲状态可以进行操作
* \return 如果芯片处于空闲状态,返回true
*/
extern QBL_STATUS W25Q_CheckForIdle(void);
/*!
* \brief W25Q_EraseSector 擦除制定的扇区
* \param addr 要擦除的扇区的地址
* \return
*/
extern QBL_STATUS W25Q_EraseSector(uint32_t addr);
/*!
* \brief W25Q_EraseChp 擦除整个芯片
* \return 如果指令发送成功,返回true
*/
extern QBL_STATUS W25Q_EraseChip(void);
/*!
* \brief W25Q_EraseSector 擦除制定的扇区
* \param addr 要擦除的扇区的地址
* \return
*/
extern QBL_STATUS W25Q_Write(uint32_t addr,uint8_t * buffer,uint16_t length);
/*!
* \brief W25Q_Read 从闪存中读取数据
* \param addr 将要读取数据的起始地址
* \param buffer 接收数据的缓冲
* \param length 要读取的数据的长度
* \return 如果读取成功,返回true
*/
extern QBL_STATUS W25Q_Read(uint32_t addr,uint8_t * buffer,uint16_t length);
/*!
* @}
*/
#endif
| 2.34375 | 2 |
2024-11-18T21:29:53.716119+00:00 | 2018-03-31T08:35:21 | aae9deb15abf70900c1b2dd35cf6ee68f5805b6a | {
"blob_id": "aae9deb15abf70900c1b2dd35cf6ee68f5805b6a",
"branch_name": "refs/heads/master",
"committer_date": "2018-03-31T08:35:21",
"content_id": "9c204ca9db2a80cb24b81346266bedcd6c766a6c",
"detected_licenses": [
"MIT"
],
"directory_id": "04da8da6b93505d0d5e3c3bf591d36070f378400",
"extension": "c",
"filename": "ListTest.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 127514076,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1685,
"license": "MIT",
"license_type": "permissive",
"path": "/ListTest.c",
"provenance": "stackv2-0112.json.gz:179752",
"repo_name": "LunguIonut007/Laborator-2-4-OOP",
"revision_date": "2018-03-31T08:35:21",
"revision_id": "34dde0cbb8ce55716afa6539d3f0b11a7019d858",
"snapshot_id": "c0afaa544a98d80aa236d19efda6f124ad6a9035",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/LunguIonut007/Laborator-2-4-OOP/34dde0cbb8ce55716afa6539d3f0b11a7019d858/ListTest.c",
"visit_date": "2020-03-07T13:55:48.265646"
} | stackv2 | #include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#include "ListTest.h"
#include "Utils\List.h"
TestStruct* createTestStruct(int x) {
TestStruct* testS = malloc(sizeof(TestStruct));
testS->x = x;
return testS;
}
void destroyFunc(TestStruct* something) {
free(something);
}
TestStruct* deepCopy(TestStruct* something) {
return createTestStruct(something->x);
}
void testResize() {
List* list2 = createList(destroyFunc, sizeof(TestStruct*));
addToList(list2, createTestStruct(2));
addToList(list2, createTestStruct(4));
addToList(list2, createTestStruct(2));
addToList(list2, createTestStruct(4));
addToList(list2, createTestStruct(2));
addToList(list2, createTestStruct(4));
assert(((TestStruct*)getAtListIndex(list2, 5))->x == 4);
destroyList(list2);
}
void runListTests() {
testResize();
List* list = createList(destroyFunc, sizeof(TestStruct*));
assert(getListSize(list) == 0);
addToList(list, createTestStruct(2));
addToList(list, createTestStruct(4));
assert(getListSize(list) == 2);
assert(((TestStruct*)getAtListIndex(list, 0))->x == 2);
assert(((TestStruct*)getAtListIndex(list, 1))->x == 4);
List* list2 = deepCopyList(list, deepCopy);
destroyList(list);
assert(getListSize(list2) == 2);
assert(((TestStruct*)getAtListIndex(list2, 0))->x == 2);
assert(((TestStruct*)getAtListIndex(list2, 1))->x == 4);
// //test if works with a lot of data
addToList(list2, createTestStruct(2));
addToList(list2, createTestStruct(4));
addToList(list2, createTestStruct(2));
addToList(list2, createTestStruct(4));
addToList(list2, createTestStruct(2));
assert(((TestStruct*)getAtListIndex(list2, 5))->x == 4);
destroyList(list2);
} | 2.921875 | 3 |
2024-11-18T21:29:53.812897+00:00 | 2023-08-11T17:19:13 | e2d95206041a6c134804ce34fd9b5f3ba813741f | {
"blob_id": "e2d95206041a6c134804ce34fd9b5f3ba813741f",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-11T17:19:13",
"content_id": "d0c5c857e20bbb63583cfa1906eba5bc05612698",
"detected_licenses": [
"MIT"
],
"directory_id": "382c5c64e7f179a345ad267806824099d7986d64",
"extension": "c",
"filename": "matchcat.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 14975486,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 17922,
"license": "MIT",
"license_type": "permissive",
"path": "/src/gen/src/matchcat.c",
"provenance": "stackv2-0112.json.gz:179881",
"repo_name": "cdfassnacht/CodeCDF",
"revision_date": "2023-08-11T17:19:13",
"revision_id": "d285c51fd53e52b77e8288ede3126b1f927ea0f1",
"snapshot_id": "e094089b2d704a96d25e2b9a701d986efff8f9c5",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/cdfassnacht/CodeCDF/d285c51fd53e52b77e8288ede3126b1f927ea0f1/src/gen/src/matchcat.c",
"visit_date": "2023-08-16T10:37:23.498236"
} | stackv2 | /*
* matchcat.c
*
* Usage: matchcat [source root name] [epoch_name] [xyz]
* The root name is the name used to ID the lens files,
* e.g. '0712' for the CLASS B0712+472 files.
* The epoch name is the epoch of the observations, e.g. jan01, comb,
* etc.
* 'xyz' is a 3-character (for now) photometric system, e.g. 'gri'
* or 'BRI'. The second band (e.g. r or R) is assumed to be the
* master catalog.
* The expected input files are called
* [source_root]_[x].cat, [source_root]_[y].cat,
* and [source_root]_[z].cat
*
* This program compares three ascii catalogs that are output from the
* SExtractor program. The catalogs are assumed to be in the g, r, and i
* or B, R, and I bands. This program finds matches between sources in
* the catalogs, based on their positions.
*
* 13Nov99 CDF
* v22Nov99 CDF, Revised to do all three catalogs (g, r, and i) at once,
* rather than two at a time.
* v25Feb00 CDF, Now sort the r-band catalog in x before doing the
* matching. This should make the output file easier to read.
* v26Feb00 CDF, Read in object flags as well, and add a flag cutoff (>=16)
* to reject seriously corrupted magnitudes.
* v28Feb00 CDF, Now check for SExtractor error value (99.00) in aperture
* magnitude in match catalogs.
* v01Jun00 CDF, Added a source ID to the catalog.
* v08Jun00 CDF, Split catalog matching into a function that is called for
* both the g and i-band matching.
* New flag cutoff for g and i-band catalogs is COMPLIM.
* Split the output catalog generation into a function.
* Added a purge of the r-band (master) catalog to delete
* members with fitflag >= MASTERLIM.
* v10Jan01 CDF, Added option of doing BRI catalog in addition to the
* gri catalog.
* v16Oct01 CDF, Added epoch to command-line input.
* Changed read_secat, run_match to include new aperture error
* column.
* v28Jun02 CDF, Added new members of Secat structure and modified the
* read_secat function accordingly.
* v01Jul02 CDF, Changed sorting of output catalog to be in increasing
* distance from the lens rather than in increasing x.
* Thus, changed xcmp function to dposcmp function.
* Moved acquisition of lensx and lensy to the find_lens
* function.
* v02Jul02 CDF, Changed print_matchcat to include dpos field in output.
* v04Jul02 CDF, Added aperture color information to output, so changed
* run_match and print_matchcat functions.
* v12Jul03 CDF, Moved new_secat and del_secat into structdef.c/structdef.h
* Moved read_secat into dataio.c/dataio.h
* v20Jul03 CDF, Added printout of RA and Dec of catalog sources.
* v29Jul03 CDF, Moved purge_cat, find_lens, and dposcmp functions into
* the new catlib.c/catlib.h library files.
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include "structdef.h"
#include "dataio.h"
#include "catlib.h"
/*.......................................................................
*
* Function declarations
*
*/
int run_match(Secat *masterval, Secat *compcat, int ncompcat,
Secat *matchptr, double match_thresh, int switchcolor);
int print_matchcat(char *root, char *ext1, char *ext2, char *ext3,
Secat *mastercat, int nmaster, Secat *match12,
int nmatch1, Secat *match23, int nmatch2,
int nmatchall);
/*.......................................................................
*
* Main program
*
*/
int main(int argc, char *argv[])
{
int i; /* Looping variable */
int no_error=1; /* Flag set to 0 on error */
int nband=0; /* Number of bands */
int ncat1,ncat2,ncat3; /* Number of lines in the three catalogs */
int nmaster; /* Number of members of master catalog */
int lensindex; /* Catalog index of closest match to lens pos */
int nmatch1=0; /* Number of matches found btwn cat1 and cat2 */
int nmatch2=0; /* Number of matches found btwn cat2 and cat3 */
int mflag1,mflag2; /* Flags set when matches are found */
int nmatchall=0; /* Number of sources in all three catalogs */
double match_thresh=3.0; /* Threshold for a valid match */
char *root; /* source "root name" for file IDs" */
char name1[MAXC]; /* Filename for catalog 1 */
char name2[MAXC]; /* Filename for catalog 2 */
char name3[MAXC]; /* Filename for catalog 3 */
char epoch[MAXC]; /* Observing epoch */
char ext[MAXC]; /* Array to hold band names */
char mext; /* Master catalog band name */
char ext1[MAXC]; /* Band name for catalog 1 */
char ext2[MAXC]; /* Band name for catalog 2 */
char ext3[MAXC]; /* Band name for catalog 3 */
char line[MAXC]; /* General string for getting input */
Secat *cat1=NULL; /* Data array from catalog 1 */
Secat *cat2=NULL; /* Data array from catalog 2 */
Secat *cat3=NULL; /* Data array from catalog 3 */
Secat *mastercat=NULL; /* Master catalog (purged version of cat2) */
Secat *match12=NULL; /* Array containing matches between cats 1 and 2 */
Secat *match23=NULL; /* Array containing matches between cats 2 and 3 */
Secat *mstrptr; /* Pointer to navigate mastercat */
Secat *mptr1; /* Pointer to navigate match12 */
Secat *mptr2; /* Pointer to navigate match23 */
/*
* Check the command line invocation
*/
if(argc < 4) {
fprintf(stderr,"\nUsage: matchcat [source root name] [epoch] [xyz]\n\n");
fprintf(stderr,
"The root name is the name used to ID the lens files.\n");
fprintf(stderr,
"The epoch is the observing epoch, e.g., jan01, comb, etc.\n");
fprintf(stderr,"\'xyz\' is a 3-character photometric system, e.g. ");
fprintf(stderr,"\'gri\' or 'BRI'.\n");
fprintf(stderr,"The second band (e.g. r or R) is assumed to be the ");
fprintf(stderr,"master catalog.\n\n");
fprintf(stderr,"For example,");
fprintf(stderr,
" if the system were CLASS B0712+472, the root name might be\n");
fprintf(stderr,
" \'0712\', the epoch might be jan01 and the phot system might ");
fprintf(stderr,"be \'BRI\'.\n");
fprintf(stderr,"In that case, the input files would be called:");
fprintf(stderr," 0712_jan01_B.cat, 0712_jan01_R.cat, and");
fprintf(stderr," 0712_jan01_I.cat.\n\n");
return 1;
}
printf("\n");
/*
* Get the root name from the command line.
*/
root = argv[1];
#if 0
/*
* Get the master band name
*/
if(no_error) {
mext = *argv[3];
printf("\nMaster catalog is %c\n",mext);
}
#endif
/*
* Get the bands for the catalogs from the third input string
*/
if((nband = strlen(argv[3])) != 3)
no_error = 0;
else {
printf("\nCatalogs in %d bands:\n",nband);
for(i=0; i<nband; i++) {
ext[i] = *(argv[3]+i);
printf(" %c\n",ext[i]);
}
printf("\n");
}
/*
* Create the filenames from the source root name
*/
if(no_error) {
sprintf(ext1,"%c",ext[0]);
sprintf(ext2,"%c",ext[1]);
sprintf(ext3,"%c",ext[2]);
sprintf(name1,"%s_%s_%s.cat",root,argv[2],ext1);
sprintf(name2,"%s_%s_%s.cat",root,argv[2],ext2);
sprintf(name3,"%s_%s_%s.cat",root,argv[2],ext3);
/*
* Fill the data structures
*/
if(!(cat1 = read_secat(name1,'#',&ncat1,1)))
no_error = 0;
if(!(cat2 = read_secat(name2,'#',&ncat2,1)))
no_error = 0;
if(!(cat3 = read_secat(name3,'#',&ncat3,1)))
no_error = 0;
}
/*
* Allocate memory for the match arrays. Make them the same
* size as cat2, which will be used as the master catalog
*/
if(!(match12 = new_secat(ncat2)))
no_error = 0;
if(!(match23 = new_secat(ncat2)))
no_error = 0;
/*
* Purge catalog 2 of entries with SExtractor flags greater than
* MASTERLIM to create the "master" catalog.
*/
if(no_error)
if(!(mastercat = purge_cat(cat2,ncat2,name2,&nmaster,MASTERLIM)))
no_error = 0;
/*
* Find lens system in master catalog.
*/
if(no_error)
if(find_lens(mastercat,nmaster,&lensindex))
no_error = 0;
/*
* Sort the "master" catalog in order of
* increasing distance from the lens.
*/
if(no_error) {
printf("\nSorting the master catalog in order of increasing distance ");
printf("from lens...");
qsort(mastercat,nmaster,sizeof(mastercat[0]),dposcmp);
printf(" Done.\n");
}
/*
* Set threshold levels
*/
if(no_error) {
printf("\nSet maximum separation for a match in pixels: [%4.1f] ",
match_thresh);
fgets(line,MAXC,stdin);
if(line[0] != '\n') {
while(sscanf(line,"%lf",&match_thresh) != 1 || match_thresh <= 0.0) {
fprintf(stderr,"ERROR. Bad input. Enter max separation again: ");
fgets(line,MAXC,stdin);
}
}
}
/*
* Fill match arrays by comparing catalogs
*/
if(no_error) {
/*
* Loop through the arrays computing positional offsets.
* Use catalog 2 as the "master" catalog since the r image is usually
* deeper and cleaner than the g and i images.
*/
for(i=0,mstrptr=mastercat,mptr1=match12,mptr2=match23; i<nmaster;
i++,mstrptr++,mptr1++,mptr2++) {
/*
* First compare to catalog 1
*/
if((mflag1 = run_match(mstrptr,cat1,ncat1,mptr1,match_thresh,1)) == 1)
nmatch1++;
/*
* Now compare to catalog 3
*/
if((mflag2 = run_match(mstrptr,cat3,ncat3,mptr2,match_thresh,-1)) == 1)
nmatch2++;
/*
* Increment nmatchall if matches found in both catalogs.
*/
if(mflag1 && mflag2)
nmatchall++;
}
}
/*
* Write output file
*/
if(no_error) {
sprintf(name1,"%s_%s",root,argv[2]);
if(print_matchcat(name1,ext1,ext2,ext3,mastercat,nmaster,match12,nmatch1,
match23,nmatch2,nmatchall))
no_error = 0;
}
/*
* Clean up and exit
*/
cat1 = del_secat(cat1);
cat2 = del_secat(cat2);
cat3 = del_secat(cat3);
mastercat = del_secat(mastercat);
match12 = del_secat(match12);
match23 = del_secat(match23);
if(no_error) {
printf("\nProgram matchcat finished.\n\n");
return 0;
}
else {
fprintf(stderr,"\nERROR. Exiting matchcat.\n\n");
return 1;
}
}
/*.......................................................................
*
* Function run_match
*
* Searches through a "comparison" catalog for a match to an entry in the
* "master" catalog. The matching is based on the position of the
* detected source. If a match is found, the "match" catalog is updated
* to include the entry.
*
* Inputs: Secat *masterval value of entry in master catalog
* Secat *compcat comparison catalog
* int ncompcat number of entries in comparison catalog
* Secat *matchptr pointer to current position in match catalog
* double match_thresh threshold for a valid positional match
* int switchcolor constant set to +1 if color is defined as
* (comparison-master) and set to -1 if color
* is defined as (master-comparison)
*
* Output: int matchflag flag set to 1 if a match is found
*
*/
int run_match(Secat *masterval, Secat *compcat, int ncompcat,
Secat *matchptr, double match_thresh, int switchcolor)
{
int j; /* Looping variable */
int matchflag=0; /* Flag set to 1 if a match is found */
double dx,dy; /* Difference between x and y positions */
double sep; /* Position separation */
double minsep; /* Minimum separation between catalog positions */
Secat closest; /* Closest match between catalog sources */
Secat *cptr; /* Pointer to navigate compcat */
/*
* Run through the comparison catalog looking for the closest
* positional match. All info from this match is put into the
* "closest" structure.
*/
minsep = 50.0 * match_thresh;
closest = *masterval;
matchflag = 0;
for(j=0,cptr=compcat; j<ncompcat; j++,cptr++) {
if((dx = cptr->x - masterval->x) < match_thresh &&
(dy = cptr->y - masterval->y) < match_thresh) {
sep = sqrt(dx*dx + dy*dy);
if(sep < minsep) {
minsep = sep;
closest = *cptr;
closest.sep = sep;
}
}
}
/*
* If we've got a match, put color and compcat magnitude into the
* match catalog. A valid match is defined by a small separation,
* (separation < match_thresh), a valid fitflag (< COMPLIM), and a valid
* isophotal magnitude (not equal to 99.00, which is SExtractor's
* error code).
*/
if(minsep < match_thresh && closest.fitflag < COMPLIM &&
fabs(closest.miso - 99.0) > 1.0) {
matchflag = 1;
*matchptr = *masterval;
matchptr->matchflag = 1;
matchptr->sep = closest.sep;
/*
* Put relevant info from the comparison catalog into the match
* catalog. The comparison magnitude goes into the mtot container
* and the aperture colors (= switchcolor * (m*_compcat - m*_master))
* goes into the miso and ma* containers.
*/
matchptr->mtot = closest.mtot;
matchptr->merr = closest.merr;
matchptr->misoerr = closest.misoerr;
matchptr->miso = switchcolor * (closest.miso - masterval->miso);
matchptr->ma1 = switchcolor * (closest.ma1 - masterval->ma1);
matchptr->ma2 = switchcolor * (closest.ma2 - masterval->ma2);
matchptr->ma3 = switchcolor * (closest.ma3 - masterval->ma3);
matchptr->fwhm = closest.fwhm;
matchptr->fitflag = closest.fitflag;
}
/*
* Otherwise, if there is no match, set matchflag to 0
*/
else {
matchptr->matchflag = 0;
matchptr->miso = -99.0;
matchptr->ma1 = -99.0;
matchptr->ma2 = -99.0;
matchptr->ma3 = -99.0;
matchptr->mtot = -99.0;
matchptr->merr = 99.0;
matchptr->fitflag = -1;
}
return matchflag;
}
/*.......................................................................
*
* Function print_matchcat
*
* Prints the matched catalog to an output file.
*
* Inputs: char *root lens system root name
* char *ext1 photometric band for catalog 1
* char *ext2 photometric band for catalog 2
* char *ext3 photometric band for catalog 3
* Secat *mastercat master catalog
* int nmaster number in master catalog
* Secat *match12 catalog of matches between catalogs 1 and 2
* int nmatch1 number of members in match12
* Secat *match23 catalog of matches between catalogs 2 and 3
* int nmatch2 number of members in match23
* int nmatchall number of sources found in all three catalogs
*
* Output: int (0 or 1) 0 ==> success, 1 ==> error
*
* v20Jul03 CDF, Added printout of RA and Dec of catalog sources.
*/
int print_matchcat(char *root, char *ext1, char *ext2, char *ext3,
Secat *mastercat, int nmaster, Secat *match12,
int nmatch1, Secat *match23, int nmatch2,
int nmatchall)
{
int i; /* Looping variable */
int no_error=1; /* Flag set to 0 on error */
char outname[MAXC]; /* Output filename */
Secat *mstrptr; /* Pointer to navigate mastercat */
Secat *mptr1; /* Pointer to navigate match12 */
Secat *mptr2; /* Pointer to navigate match23 */
FILE *ofp=NULL; /* Pointer to output file */
/*
* Open output file
*/
sprintf(outname,"%s_%s%s%s.cat",root,ext1,ext2,ext3);
ofp = open_writefile(outname);
/*
* Print out results
*/
if(no_error) {
printf("\nNumber of valid matches:\n");
printf(" %d in %s and %s catalogs\n",nmatch1,ext1,ext2);
printf(" %d in %s and %s catalogs\n",nmatch2,ext2,ext3);
printf(" %d in all three catalogs\n",nmatchall);
fprintf(ofp,"#ID dpos %s_x %s_y class ",ext2,ext2);
fprintf(ofp,"%sflg %s_tot %s_err %s_iso %s_ap2 fwhm_%s ",
ext2,ext2,ext2,ext2,ext2,ext2);
fprintf(ofp,"%sflg %s_tot %s_err (%s-%s)iso (%s-%s)ap2 fwhm_%s ",
ext1,ext1,ext1,ext1,ext2,ext1,ext2,ext1);
fprintf(ofp,"%sflg %s_tot %s_err (%s-%s)iso (%s-%s)ap2 fwhm_%s ",
ext3,ext3,ext3,ext2,ext3,ext2,ext3,ext3);
fprintf(ofp," RA2000 Dec2000\n");
fprintf(ofp,"#--- ---- -------- -------- ----- ");
fprintf(ofp,"---- ------ ----- ------ ------ ------ ");
fprintf(ofp,"---- ------ ----- -------- -------- ------ ");
fprintf(ofp,"---- ------ ----- -------- -------- ------\n");
for(i=0,mstrptr=mastercat,mptr1=match12,mptr2=match23; i<nmaster;
i++,mstrptr++,mptr1++,mptr2++) {
fprintf(ofp,
"%04d %4.0f %8.2f %8.2f %5.2f ",
i+1,mstrptr->dpos,mstrptr->x,mstrptr->y,mstrptr->class);
fprintf(ofp,"%3d %6.2f %5.2f %6.2f %6.2f %6.2f ",
mstrptr->fitflag,mstrptr->mtot,mstrptr->merr,mstrptr->miso,
mstrptr->ma2,mstrptr->fwhm);
fprintf(ofp,"%3d %6.2f %5.2f %6.2f %6.2f %6.2f ",
mptr1->fitflag,mptr1->mtot,mptr1->merr,mptr1->miso,
mptr1->ma2,mptr1->fwhm);
fprintf(ofp,"%3d %6.2f %5.2f %6.2f %6.2f %6.2f ",
mptr2->fitflag,mptr2->mtot,mptr2->merr,mptr2->miso,
mptr2->ma2,mptr2->fwhm);
fprintf(ofp,"%02d %02d %07.4f %+03d %02d %06.3f\n",
mptr2->skypos.hr,mptr2->skypos.min,mptr2->skypos.sec,
mptr2->skypos.deg,mptr2->skypos.amin,mptr2->skypos.asec);
}
}
/*
* Clean up and exit
*/
if(ofp)
fclose(ofp);
return 0;
}
| 2.390625 | 2 |
2024-11-18T21:29:53.883328+00:00 | 2022-10-17T06:37:06 | 4152c7be8f3fdc1aaa2db3aa3d0b999f7d2a8f6f | {
"blob_id": "4152c7be8f3fdc1aaa2db3aa3d0b999f7d2a8f6f",
"branch_name": "refs/heads/master",
"committer_date": "2022-10-17T06:37:06",
"content_id": "e3fd9f67289c9178739cc13c99d36f0cce518621",
"detected_licenses": [
"MIT"
],
"directory_id": "02b29b1994900b6918aa740365a990dcb73582c3",
"extension": "c",
"filename": "browser.c",
"fork_events_count": 5,
"gha_created_at": "2017-08-11T07:03:29",
"gha_event_created_at": "2017-09-18T04:22:00",
"gha_language": "Python",
"gha_license_id": null,
"github_id": 100002542,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 14042,
"license": "MIT",
"license_type": "permissive",
"path": "/src/browser.c",
"provenance": "stackv2-0112.json.gz:180011",
"repo_name": "lilydjwg/ncdu-diff",
"revision_date": "2022-10-17T06:37:06",
"revision_id": "65c3a77d8e6f854974ce883a263f15576b27943e",
"snapshot_id": "08869a95f178e806953edbece5beb679cd445e0b",
"src_encoding": "UTF-8",
"star_events_count": 24,
"url": "https://raw.githubusercontent.com/lilydjwg/ncdu-diff/65c3a77d8e6f854974ce883a263f15576b27943e/src/browser.c",
"visit_date": "2023-08-19T13:03:02.568223"
} | stackv2 | /* ncdu - NCurses Disk Usage
Copyright (c) 2007-2020 Yoran Heling
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 "global.h"
#include <string.h>
#include <stdlib.h>
#include <ncurses.h>
#include <time.h>
static int graph = 1, show_as = 0, info_show = 0, info_page = 0, info_start = 0, show_items = 0, show_mtime = 0;
static char *message = NULL;
static void browse_draw_info(struct dir *dr) {
struct dir *t;
struct dir_ext *e = dir_ext_ptr(dr);
char mbuf[46];
int i;
nccreate(11, 60, "Item info");
if(dr->hlnk) {
nctab(41, info_page == 0, 1, "Info");
nctab(50, info_page == 1, 2, "Links");
}
switch(info_page) {
case 0:
attron(A_BOLD);
ncaddstr(2, 3, "Name:");
ncaddstr(3, 3, "Path:");
if(!e)
ncaddstr(4, 3, "Type:");
else {
ncaddstr(4, 3, "Mode:");
ncaddstr(4, 21, "UID:");
ncaddstr(4, 33, "GID:");
ncaddstr(5, 3, "Last modified:");
}
ncaddstr(6, 3, " Disk usage:");
ncaddstr(7, 3, "Apparent size:");
attroff(A_BOLD);
ncaddstr(2, 9, cropstr(dr->name, 49));
ncaddstr(3, 9, cropstr(getpath(dr->parent), 49));
ncaddstr(4, 9, dr->flags & FF_DIR ? "Directory" : dr->flags & FF_FILE ? "File" : "Other");
if(e) {
ncaddstr(4, 9, fmtmode(e->mode));
ncprint(4, 26, "%d", e->uid);
ncprint(4, 38, "%d", e->gid);
time_t t = (time_t)e->mtime;
strftime(mbuf, sizeof(mbuf), "%Y-%m-%d %H:%M:%S %z", localtime(&t));
ncaddstr(5, 18, mbuf);
}
ncmove(6, 18);
printsize(UIC_DEFAULT, dr->size);
addstrc(UIC_DEFAULT, " (");
addstrc(UIC_NUM, fullsize(dr->size));
addstrc(UIC_DEFAULT, " B)");
ncmove(7, 18);
printsize(UIC_DEFAULT, dr->asize);
addstrc(UIC_DEFAULT, " (");
addstrc(UIC_NUM, fullsize(dr->asize));
addstrc(UIC_DEFAULT, " B)");
break;
case 1:
for(i=0,t=dr->hlnk; t!=dr; t=t->hlnk,i++) {
if(info_start > i)
continue;
if(i-info_start > 5)
break;
ncaddstr(2+i-info_start, 3, cropstr(getpath(t), 54));
}
if(t!=dr)
ncaddstr(8, 25, "-- more --");
break;
}
ncaddstr(9, 31, "Press ");
addchc(UIC_KEY, 'i');
addstrc(UIC_DEFAULT, " to hide this window");
}
static void browse_draw_flag(struct dir *n, int *x) {
addchc(n->flags & FF_BSEL ? UIC_FLAG_SEL : UIC_FLAG,
n == dirlist_parent ? ' ' :
n->flags & FF_EXL ? '<' :
n->flags & FF_ERR ? '!' :
n->flags & FF_SERR ? '.' :
n->flags & FF_OTHFS ? '>' :
n->flags & FF_HLNKC ? 'H' :
!(n->flags & FF_FILE
|| n->flags & FF_DIR) ? '@' :
n->flags & FF_DIR
&& n->sub == NULL ? 'e' :
' ');
*x += 2;
}
static void browse_draw_graph(struct dir *n, int *x) {
float pc = 0.0f;
int o, i;
enum ui_coltype c = n->flags & FF_BSEL ? UIC_SEL : UIC_DEFAULT;
if(!graph)
return;
*x += graph == 1 ? 13 : graph == 2 ? 9 : 20;
if(n == dirlist_parent)
return;
addchc(c, '[');
/* percentage (6 columns) */
if(graph == 2 || graph == 3) {
pc = (float)(show_as ? n->parent->asize : n->parent->size);
if(pc < 1)
pc = 1.0f;
uic_set(c == UIC_SEL ? UIC_NUM_SEL : UIC_NUM);
printw("%5.1f", ((float)(show_as ? n->asize : n->size) / pc) * 100.0f);
addchc(c, '%');
}
if(graph == 3)
addch(' ');
/* graph (10 columns) */
if(graph == 1 || graph == 3) {
uic_set(c == UIC_SEL ? UIC_GRAPH_SEL : UIC_GRAPH);
o = (int)(10.0f*(float)(show_as ? n->asize : n->size) / (float)(show_as ? dirlist_maxa : dirlist_maxs));
for(i=0; i<10; i++)
addch(i < o ? '#' : ' ');
}
addchc(c, ']');
}
static void browse_draw_items(struct dir *n, int *x) {
enum ui_coltype c = n->flags & FF_BSEL ? UIC_SEL : UIC_DEFAULT;
enum ui_coltype cn = c == UIC_SEL ? UIC_NUM_SEL : UIC_NUM;
if(!show_items)
return;
*x += 7;
if(!n->items)
return;
else if(n->items < 100*1000) {
uic_set(cn);
printw("%6s", fullsize(n->items));
} else if(n->items < 1000*1000) {
uic_set(cn);
printw("%5.1f", n->items / 1000.0);
addstrc(c, "k");
} else if(n->items < 1000*1000*1000) {
uic_set(cn);
printw("%5.1f", n->items / 1e6);
addstrc(c, "M");
} else {
addstrc(c, " > ");
addstrc(cn, "1");
addchc(c, 'B');
}
}
static void browse_draw_mtime(struct dir *n, int *x) {
enum ui_coltype c = n->flags & FF_BSEL ? UIC_SEL : UIC_DEFAULT;
char mbuf[26];
struct dir_ext *e;
time_t t;
if (n->flags & FF_EXT) {
e = dir_ext_ptr(n);
} else if (!strcmp(n->name, "..") && (n->parent->flags & FF_EXT)) {
e = dir_ext_ptr(n->parent);
} else {
snprintf(mbuf, sizeof(mbuf), "no mtime");
goto no_mtime;
}
t = (time_t)e->mtime;
strftime(mbuf, sizeof(mbuf), "%Y-%m-%d %H:%M:%S %z", localtime(&t));
uic_set(c == UIC_SEL ? UIC_NUM_SEL : UIC_NUM);
no_mtime:
printw("%26s", mbuf);
*x += 27;
}
static void browse_draw_item(struct dir *n, int row) {
int x = 0;
enum ui_coltype c = n->flags & FF_BSEL ? UIC_SEL : UIC_DEFAULT;
uic_set(c);
mvhline(row, 0, ' ', wincols);
move(row, 0);
browse_draw_flag(n, &x);
move(row, x);
if(n != dirlist_parent)
printsize(c, show_as ? n->asize : n->size);
x += 11;
move(row, x);
browse_draw_graph(n, &x);
move(row, x);
browse_draw_items(n, &x);
move(row, x);
if (extended_info && show_mtime) {
browse_draw_mtime(n, &x);
move(row, x);
}
if(n->flags & FF_DIR)
c = c == UIC_SEL ? UIC_DIR_SEL : UIC_DIR;
addchc(c, n->flags & FF_DIR ? '/' : ' ');
addstrc(c, cropstr(n->name, wincols-x-1));
}
void browse_draw() {
struct dir *t;
char *tmp;
int selected = 0, i;
erase();
t = dirlist_get(0);
/* top line - basic info */
uic_set(UIC_HD);
mvhline(0, 0, ' ', wincols);
mvprintw(0,0,"%s %s ~ Use the arrow keys to navigate, press ", PACKAGE_NAME, PACKAGE_VERSION);
addchc(UIC_KEY_HD, '?');
addstrc(UIC_HD, " for help");
if(dir_import_active)
mvaddstr(0, wincols-10, "[imported]");
else if(read_only)
mvaddstr(0, wincols-11, "[read-only]");
/* second line - the path */
mvhlinec(UIC_DEFAULT, 1, 0, '-', wincols);
if(dirlist_par) {
mvaddchc(UIC_DEFAULT, 1, 3, ' ');
tmp = getpath(dirlist_par);
mvaddstrc(UIC_DIR, 1, 4, cropstr(tmp, wincols-8));
mvaddchc(UIC_DEFAULT, 1, 4+((int)strlen(tmp) > wincols-8 ? wincols-8 : (int)strlen(tmp)), ' ');
}
/* bottom line - stats */
uic_set(UIC_HD);
mvhline(winrows-1, 0, ' ', wincols);
if(t) {
mvaddstr(winrows-1, 0, " Total disk usage: ");
printsize(UIC_HD, t->parent->size);
addstrc(UIC_HD, " Apparent size: ");
uic_set(UIC_NUM_HD);
printsize(UIC_HD, t->parent->asize);
addstrc(UIC_HD, " Items: ");
uic_set(UIC_NUM_HD);
printw("%d", t->parent->items);
} else
mvaddstr(winrows-1, 0, " No items to display.");
uic_set(UIC_DEFAULT);
/* nothing to display? stop here. */
if(!t)
return;
/* get start position */
t = dirlist_top(0);
/* print the list to the screen */
for(i=0; t && i<winrows-3; t=dirlist_next(t),i++) {
browse_draw_item(t, 2+i);
/* save the selected row number for later */
if(t->flags & FF_BSEL)
selected = i;
}
/* draw message window */
if(message) {
nccreate(6, 60, "Message");
ncaddstr(2, 2, message);
ncaddstr(4, 34, "Press any key to continue");
}
/* draw information window */
t = dirlist_get(0);
if(!message && info_show && t != dirlist_parent)
browse_draw_info(t);
/* move cursor to selected row for accessibility */
move(selected+2, 0);
}
int browse_key(int ch) {
struct dir *t, *sel;
int i, catch = 0;
/* message window overwrites all keys */
if(message) {
message = NULL;
return 0;
}
sel = dirlist_get(0);
/* info window overwrites a few keys */
if(info_show && sel)
switch(ch) {
case '1':
info_page = 0;
break;
case '2':
if(sel->hlnk)
info_page = 1;
break;
case KEY_RIGHT:
case 'l':
if(sel->hlnk) {
info_page = 1;
catch++;
}
break;
case KEY_LEFT:
case 'h':
if(sel->hlnk) {
info_page = 0;
catch++;
}
break;
case KEY_UP:
case 'k':
if(sel->hlnk && info_page == 1) {
if(info_start > 0)
info_start--;
catch++;
}
break;
case KEY_DOWN:
case 'j':
case ' ':
if(sel->hlnk && info_page == 1) {
for(i=0,t=sel->hlnk; t!=sel; t=t->hlnk)
i++;
if(i > info_start+6)
info_start++;
catch++;
}
break;
}
if(!catch)
switch(ch) {
/* selecting items */
case KEY_UP:
case 'k':
dirlist_select(dirlist_get(-1));
dirlist_top(-1);
info_start = 0;
break;
case KEY_DOWN:
case 'j':
dirlist_select(dirlist_get(1));
dirlist_top(1);
info_start = 0;
break;
case KEY_HOME:
dirlist_select(dirlist_next(NULL));
dirlist_top(2);
info_start = 0;
break;
case KEY_LL:
case KEY_END:
dirlist_select(dirlist_get(1<<30));
dirlist_top(1);
info_start = 0;
break;
case KEY_PPAGE:
dirlist_select(dirlist_get(-1*(winrows-3)));
dirlist_top(-1);
info_start = 0;
break;
case KEY_NPAGE:
dirlist_select(dirlist_get(winrows-3));
dirlist_top(1);
info_start = 0;
break;
/* sorting items */
case 'n':
dirlist_set_sort(DL_COL_NAME, dirlist_sort_col == DL_COL_NAME ? !dirlist_sort_desc : 0, DL_NOCHANGE);
info_show = 0;
break;
case 's':
i = show_as ? DL_COL_ASIZE : DL_COL_SIZE;
dirlist_set_sort(i, dirlist_sort_col == i ? !dirlist_sort_desc : 1, DL_NOCHANGE);
info_show = 0;
break;
case 'C':
dirlist_set_sort(DL_COL_ITEMS, dirlist_sort_col == DL_COL_ITEMS ? !dirlist_sort_desc : 1, DL_NOCHANGE);
info_show = 0;
break;
case 'M':
if (extended_info) {
dirlist_set_sort(DL_COL_MTIME, dirlist_sort_col == DL_COL_MTIME ? !dirlist_sort_desc : 1, DL_NOCHANGE);
info_show = 0;
}
break;
case 'e':
dirlist_set_hidden(!dirlist_hidden);
info_show = 0;
break;
case 't':
dirlist_set_sort(DL_NOCHANGE, DL_NOCHANGE, !dirlist_sort_df);
info_show = 0;
break;
case 'a':
show_as = !show_as;
if(dirlist_sort_col == DL_COL_ASIZE || dirlist_sort_col == DL_COL_SIZE)
dirlist_set_sort(show_as ? DL_COL_ASIZE : DL_COL_SIZE, DL_NOCHANGE, DL_NOCHANGE);
info_show = 0;
break;
/* browsing */
case 10:
case KEY_RIGHT:
case 'l':
if(sel != NULL && sel->flags & FF_DIR) {
dirlist_open(sel == dirlist_parent ? dirlist_par->parent : sel);
dirlist_top(-3);
}
info_show = 0;
break;
case KEY_LEFT:
case KEY_BACKSPACE:
case 'h':
case '<':
if(dirlist_par && dirlist_par->parent != NULL) {
dirlist_open(dirlist_par->parent);
dirlist_top(-3);
}
info_show = 0;
break;
/* and other stuff */
case 'r':
if(dir_import_active) {
message = "Directory imported from file, won't refresh.";
break;
}
if(dirlist_par) {
dir_ui = 2;
dir_mem_init(dirlist_par);
dir_scan_init(getpath(dirlist_par));
}
info_show = 0;
break;
case 'q':
if(info_show)
info_show = 0;
else
if (confirm_quit)
quit_init();
else return 1;
break;
case 'g':
if(++graph > 3)
graph = 0;
info_show = 0;
break;
case 'c':
show_items = !show_items;
break;
case 'm':
if (extended_info)
show_mtime = !show_mtime;
break;
case 'i':
info_show = !info_show;
break;
case '?':
help_init();
info_show = 0;
break;
case 'd':
if(read_only >= 1 || dir_import_active) {
message = read_only >= 1
? "File deletion disabled in read-only mode."
: "File deletion not available for imported directories.";
break;
}
if(sel == NULL || sel == dirlist_parent)
break;
info_show = 0;
if((t = dirlist_get(1)) == sel)
if((t = dirlist_get(-1)) == sel || t == dirlist_parent)
t = NULL;
delete_init(sel, t);
break;
case 'b':
if(read_only >= 2 || dir_import_active) {
message = read_only >= 2
? "Shell feature disabled in read-only mode."
: "Shell feature not available for imported directories.";
break;
}
shell_init();
break;
}
/* make sure the info_* options are correct */
sel = dirlist_get(0);
if(!info_show || sel == dirlist_parent)
info_show = info_page = info_start = 0;
else if(sel && !sel->hlnk)
info_page = info_start = 0;
return 0;
}
void browse_init(struct dir *par) {
pstate = ST_BROWSE;
message = NULL;
dirlist_open(par);
}
| 2.1875 | 2 |
2024-11-18T21:29:54.140894+00:00 | 2017-12-02T09:03:37 | e881003e2823b2c39bb333031635e521ce2495ac | {
"blob_id": "e881003e2823b2c39bb333031635e521ce2495ac",
"branch_name": "refs/heads/master",
"committer_date": "2017-12-02T09:03:37",
"content_id": "cd5e726d9fae2e913f27eca842a0c8023e6c67ae",
"detected_licenses": [
"MIT"
],
"directory_id": "ed13e0652313d63faf4f0a6ea49ed3fd6511ec8e",
"extension": "c",
"filename": "ast.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 109574684,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4622,
"license": "MIT",
"license_type": "permissive",
"path": "/ast.c",
"provenance": "stackv2-0112.json.gz:180271",
"repo_name": "rst256/packcc_lc",
"revision_date": "2017-12-02T09:03:37",
"revision_id": "0a5cb72f0a840be2db75f0db1ec4eb4a1b483124",
"snapshot_id": "311174516d3524773f3cd7b91db301296a289554",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/rst256/packcc_lc/0a5cb72f0a840be2db75f0db1ec4eb4a1b483124/ast.c",
"visit_date": "2021-08-23T01:51:55.193907"
} | stackv2 | #include "ast.h"
int get_line(parser_t* p, int pos){
if(p->pos < pos) return 0;
for(int i = 0; i<p->lines_count; i++) if(p->lines[i] > pos) return i+1;
return p->lines_count+1;
}
int get_col(parser_t* p, int pos){
if(p->pos < pos) return 0;
int i;
for(i = 0; i<p->lines_count; i++) if(p->lines[i] > pos) break;
return ( i ? pos - p->lines[i-1] : pos ) + 1;
}
const char * __dump_asn(asn_t *n, char *buff, size_t size){
int shift;
if(!n) return "";
switch(n->type){
case asn_null:
shift = snprintf(buff, size, " ");
break;
case expr_integer:
shift = snprintf(buff, size, "%g", n->number);
break;
case expr_float:
shift = snprintf(buff, size, "%g", n->float_num);
break;
case expr_string:
shift = snprintf(buff, size, "\"%s\"", n->string);
break;
case expr_ident:
shift = snprintf(buff, size, "%s", ident_name(n->ident));
break;
case expr_field:
shift = snprintf(buff, size, "%s.%s", dump_asn(n->object), ident_name(n->field));
break;
case expr_index:
shift = snprintf(buff, size, "%s[%s]", dump_asn(n->array), dump_asn(n->index));
break;
case expr_binop:
shift = snprintf(buff, size, "(%s %c %s)", dump_asn(n->larg), n->op, dump_asn(n->rarg));
break;
case expr_call:
shift = snprintf(buff, size, "%s()", dump_asn(n->func));
/*/for(int i = 0; i<n->args_count; i++){ print_asn(n->args[i]); if(i+1<n->args_count) shift = snprintf(buff, size, ", "); }
# shift = snprintf(buff, size, ")"); */
break;
case stat_assign:
shift = snprintf(buff, size, "%s = %s", dump_asn(n->lvalue), dump_asn(n->rvalue));
break;
default:
shift = snprintf(buff, size, "?[%d]?", n->type);
break;
}
if(n->is_statement) snprintf(buff+shift, size-shift, ";");
return buff;
}
void __print_asn(asn_t *n, int level){
if(!n) return;
// if(n->is_statement)
for(int i = 0; i<level; i++) printf("\t");
switch(n->type){
case asn_null:
printf(" ");
break;
case expr_integer:
printf("%g", n->number);
break;
case expr_float:
printf("%g", n->float_num);
break;
case expr_string:
printf("\"%s\"", n->string);
break;
case expr_ident:
printf("%s", ident_name(n->ident));
break;
case expr_field:
print_asn(n->object); printf(".%s", ident_name(n->field));
break;
case expr_index:
print_asn(n->array); printf("["); print_asn(n->index); printf("]");
break;
case expr_binop:
printf("("); print_asn(n->larg); printf(" %c ", n->op); print_asn(n->rarg); printf(")");
break;
case expr_call:
print_asn(n->func); printf("(");
for(int i = 0; i<n->args_count; i++){ print_asn(n->args[i]); if(i+1<n->args_count) printf(", "); }
printf(")");
break;
case block:
for(int i = 0; i<n->count; i++){
print_asn(n->nodes[i], (i ? level : 0));
if(i+1<n->count) printf("\n");
}
break;
case stat_assign:
print_asn(n->lvalue); printf(" = "); print_asn(n->rvalue);
break;
case stat_if:
printf("if "); print_asn(n->condition);
printf(" then\n"); print_asn(n->then_block, level+1);
printf("\n"); for(int i = 0; i<level; i++) printf("\t");
printf("end");
break;
case stat_if_then_else:
printf("if "); print_asn(n->condition);
printf(" then\n"); print_asn(n->then_block, level+1);
printf("\n"); for(int i = 0; i<level; i++) printf("\t");
printf("else\n"); print_asn(n->else_block, level+1);
printf("\n"); for(int i = 0; i<level; i++) printf("\t");
printf("end");
break;
case type_expr:
if(n->is_const && n->te_type!=te_pointer) printf("const ");
print_asn(n->base_type);
if(n->is_const && n->te_type==te_pointer) printf(" const");
if(n->te_type==te_pointer) printf("*");
break;
case stat_define:
print_asn(n->def_type);
printf(" %s", ident_name(n->def_ident));
if(n->init_value){
printf(" = "); print_asn(n->init_value);
}
break;
default:
printf("?[%d]?", n->type);
break;
}
//if(n->is_statement) printf(";");
}
asn_t * binop(asn_t * l, const char *op, asn_t * r, parser_t * auxil, const char* _0){
asn_t * __;
if(l->type==expr_integer && r->type==expr_integer){
__ = malloc(sizeof(asn_t));
__->type = expr_integer; __->is_statement = 0;
switch(op[0]){
case '-': __->number = l->number - r->number; break;
case '+': __->number = l->number + r->number; break;
case '/': __->number = l->number / r->number; break;
case '*': __->number = l->number * r->number; break;
default:
break;
}
}else{
__ = malloc(sizeof(asn_t));
__->type = expr_binop; __->is_statement = 0;
__->larg=l; __->rarg=r; __->op=op[0];
}
return __;
}
| 2.75 | 3 |
2024-11-18T21:29:54.213429+00:00 | 2016-05-05T20:19:13 | c133136c0011963339156ca24e782d972a57a215 | {
"blob_id": "c133136c0011963339156ca24e782d972a57a215",
"branch_name": "refs/heads/master",
"committer_date": "2016-05-05T20:20:08",
"content_id": "c53ab4e48782640bfc73d2c2bde1c4a66053b2e0",
"detected_licenses": [
"MIT"
],
"directory_id": "4919538a19366f2dea94b40e71694cf70556fee6",
"extension": "h",
"filename": "utils.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": 2573,
"license": "MIT",
"license_type": "permissive",
"path": "/src/utils.h",
"provenance": "stackv2-0112.json.gz:180399",
"repo_name": "zhangjinde/Dialogue",
"revision_date": "2016-05-05T20:19:13",
"revision_id": "9817dd905d91c5c6b18faa47edcbcd9d231722d8",
"snapshot_id": "8209bb0dd6e24ecd3cfad2878ba2c41f497107e4",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/zhangjinde/Dialogue/9817dd905d91c5c6b18faa47edcbcd9d231722d8/src/utils.h",
"visit_date": "2021-05-31T20:25:32.845726"
} | stackv2 | #ifndef DIALOGUE_UTILS
#define DIALOGUE_UTILS
#include "dialogue.h"
static inline void utils_copy_top (lua_State *to, lua_State *from);
static inline void utils_transfer (lua_State *to, lua_State *from, const int n);
/*
* Copy a table of the `from' stack at the index to the `to' stack.
*/
static inline void
utils_copy_table (lua_State *T, lua_State *F, const int index)
{
const int table = lua_gettop(T) + 1;
int i = 0;
lua_newtable(T);
lua_pushnil(F);
while (lua_next(F, index)) {
i++;
/* if there *is* a key for value at -1 */
if (!lua_isnil(F, -2)) {
lua_pushvalue(F, -2); /* push the key */
/* pops pushvalue'd key & value. transfers in reverse order */
utils_transfer(T, F, 2);
lua_settable(T, table);
continue;
}
utils_copy_top(T, F);
lua_rawseti(T, table, i);
lua_pop(F, 1);
}
}
/*
* Copy the top element of `from' and push it onto `to'. Does *not* pop the
* `from' stack.
*/
static inline void
utils_copy_top (lua_State *to, lua_State *from)
{
switch (lua_type(from, -1)) {
case LUA_TNUMBER:
lua_pushnumber(to, lua_tonumber(from, -1));
break;
case LUA_TSTRING:
lua_pushstring(to, lua_tostring(from, -1));
break;
case LUA_TBOOLEAN:
lua_pushinteger(to, lua_tointeger(from, -1));
break;
case LUA_TTABLE:
utils_copy_table(to, from, lua_gettop(from));
break;
case LUA_TUSERDATA:
case LUA_TLIGHTUSERDATA:
lua_pushlightuserdata(to, lua_touserdata(from, -1));
break;
case LUA_TNIL:
lua_pushnil(to);
break;
default:
break;
}
}
/*
* Pop the top N elements of the `from' stack and push them to the `to' stack.
*/
static inline void
utils_transfer (lua_State *to, lua_State *from, const int n)
{
int i;
for (i = 1; i <= n; i++) {
utils_copy_top(to, from);
lua_pop(from, 1);
}
}
/*
* Push the first element of a table at index.
*/
static inline void
utils_push_table_head (lua_State *L, int index)
{
lua_rawgeti(L, index, 1);
}
/*
* Push N elements after first of a table at index. Returns elements pushed.
*/
static inline int
utils_push_table_data (lua_State *L, int index)
{
int i, len;
luaL_checktype(L, index, LUA_TTABLE);
len = luaL_len(L, index);
/* first element in an envelope table is the title */
for (i = 2; i <= len; i++)
lua_rawgeti(L, index, i);
return len - 1;
}
#endif
| 2.796875 | 3 |
2024-11-18T21:29:54.367163+00:00 | 2023-08-02T09:06:56 | 5bd30abb5cf90d5d932c1c5d4056a9634cffc027 | {
"blob_id": "5bd30abb5cf90d5d932c1c5d4056a9634cffc027",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-08T07:01:20",
"content_id": "35b77bd1d38618801b3458e18cc206d702b41f13",
"detected_licenses": [
"Intel",
"BSD-2-Clause",
"BSD-3-Clause"
],
"directory_id": "a8194cf6ffd12f7551eaba53572744080a0bfef3",
"extension": "c",
"filename": "ftl_mempool.c",
"fork_events_count": 1158,
"gha_created_at": "2015-07-13T23:15:15",
"gha_event_created_at": "2023-08-11T09:50:50",
"gha_language": "C",
"gha_license_id": "NOASSERTION",
"github_id": 39042157,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 6104,
"license": "Intel,BSD-2-Clause,BSD-3-Clause",
"license_type": "permissive",
"path": "/lib/ftl/utils/ftl_mempool.c",
"provenance": "stackv2-0112.json.gz:180529",
"repo_name": "spdk/spdk",
"revision_date": "2023-08-02T09:06:56",
"revision_id": "d62a3810364cb87be352c66acf7c7f968508ca17",
"snapshot_id": "51294f67104b8c3d18f19147d63a212e9486c687",
"src_encoding": "UTF-8",
"star_events_count": 2708,
"url": "https://raw.githubusercontent.com/spdk/spdk/d62a3810364cb87be352c66acf7c7f968508ca17/lib/ftl/utils/ftl_mempool.c",
"visit_date": "2023-08-08T16:07:41.263000"
} | stackv2 | /* SPDX-License-Identifier: BSD-3-Clause
* Copyright (C) 2022 Intel Corporation.
* All rights reserved.
*/
#include "spdk/stdinc.h"
#include "spdk/queue.h"
#include "spdk/util.h"
#include "spdk/env.h"
#include "spdk/likely.h"
#include "ftl_mempool.h"
#include "ftl_bitmap.h"
struct ftl_mempool_element {
SLIST_ENTRY(ftl_mempool_element) entry;
};
struct ftl_mempool {
SLIST_HEAD(, ftl_mempool_element) list;
size_t element_size;
void *buffer;
size_t buffer_size;
size_t count;
size_t alignment;
int socket_id;
struct ftl_bitmap *inuse_bmp;
void *inuse_buf;
};
static inline bool is_element_valid(struct ftl_mempool *mpool,
void *element) __attribute__((unused));
static inline bool ftl_mempool_is_initialized(struct ftl_mempool *mpool) __attribute__((unused));
static size_t
element_size_aligned(size_t size, size_t alignment)
{
if (!alignment) {
return size;
}
if (size % alignment) {
return (size / alignment + 1) * alignment;
}
return size;
}
static inline bool
is_element_valid(struct ftl_mempool *mpool, void *element)
{
if (element < mpool->buffer) {
return false;
}
if (element + mpool->element_size > mpool->buffer + mpool->buffer_size) {
return false;
}
if (!mpool->alignment) {
return true;
}
if ((size_t)element % mpool->alignment) {
return false;
}
if ((element - mpool->buffer) % mpool->element_size != 0) {
return false;
}
return true;
}
struct ftl_mempool *ftl_mempool_create(size_t count, size_t size,
size_t alignment, int socket_id)
{
struct ftl_mempool *mp;
void *buffer;
size_t i;
assert(count > 0);
assert(size > 0);
if (!spdk_u64_is_pow2(alignment)) {
return NULL;
}
mp = calloc(1, sizeof(*mp));
if (!mp) {
return NULL;
}
size = spdk_max(size, sizeof(struct ftl_mempool_element));
mp->count = count;
mp->element_size = element_size_aligned(size, alignment);
mp->alignment = alignment;
mp->socket_id = socket_id;
SLIST_INIT(&mp->list);
mp->buffer_size = mp->element_size * mp->count;
mp->buffer = spdk_dma_malloc_socket(mp->buffer_size, mp->alignment,
NULL, socket_id);
if (!mp->buffer) {
free(mp);
return NULL;
}
buffer = mp->buffer;
for (i = 0; i < count; i++, buffer += mp->element_size) {
struct ftl_mempool_element *el = buffer;
assert(is_element_valid(mp, el));
SLIST_INSERT_HEAD(&mp->list, el, entry);
}
return mp;
}
void
ftl_mempool_destroy(struct ftl_mempool *mpool)
{
if (!mpool) {
return;
}
spdk_dma_free(mpool->buffer);
free(mpool);
}
static inline bool
ftl_mempool_is_initialized(struct ftl_mempool *mpool)
{
return mpool->inuse_buf == NULL;
}
void *
ftl_mempool_get(struct ftl_mempool *mpool)
{
struct ftl_mempool_element *el;
assert(ftl_mempool_is_initialized(mpool));
if (spdk_unlikely(SLIST_EMPTY(&mpool->list))) {
return NULL;
}
el = SLIST_FIRST(&mpool->list);
SLIST_REMOVE_HEAD(&mpool->list, entry);
return el;
}
void
ftl_mempool_put(struct ftl_mempool *mpool, void *element)
{
struct ftl_mempool_element *el = element;
assert(ftl_mempool_is_initialized(mpool));
assert(is_element_valid(mpool, element));
SLIST_INSERT_HEAD(&mpool->list, el, entry);
}
struct ftl_mempool *
ftl_mempool_create_ext(void *buffer, size_t count, size_t size, size_t alignment)
{
struct ftl_mempool *mp;
size_t inuse_buf_sz;
assert(buffer);
assert(count > 0);
assert(size > 0);
mp = calloc(1, sizeof(*mp));
if (!mp) {
goto error;
}
size = spdk_max(size, sizeof(struct ftl_mempool_element));
mp->count = count;
mp->element_size = element_size_aligned(size, alignment);
mp->alignment = alignment;
SLIST_INIT(&mp->list);
/* Calculate underlying inuse_bmp's buf size */
inuse_buf_sz = spdk_divide_round_up(mp->count, 8);
/* The bitmap size must be a multiple of word size (8b) - round up */
if (inuse_buf_sz & 7UL) {
inuse_buf_sz &= ~7UL;
inuse_buf_sz += 8;
}
mp->inuse_buf = calloc(1, inuse_buf_sz);
if (!mp->inuse_buf) {
goto error;
}
mp->inuse_bmp = ftl_bitmap_create(mp->inuse_buf, inuse_buf_sz);
if (!mp->inuse_bmp) {
goto error;
}
/* Map the buffer */
mp->buffer_size = mp->element_size * mp->count;
mp->buffer = buffer;
return mp;
error:
ftl_mempool_destroy_ext(mp);
return NULL;
}
void
ftl_mempool_destroy_ext(struct ftl_mempool *mpool)
{
if (!mpool) {
return;
}
if (mpool->inuse_bmp) {
ftl_bitmap_destroy(mpool->inuse_bmp);
}
free(mpool->inuse_buf);
free(mpool);
}
void
ftl_mempool_initialize_ext(struct ftl_mempool *mpool)
{
struct ftl_mempool_element *el;
void *buffer = mpool->buffer;
size_t i;
assert(!ftl_mempool_is_initialized(mpool));
for (i = 0; i < mpool->count; i++, buffer += mpool->element_size) {
if (ftl_bitmap_get(mpool->inuse_bmp, i)) {
continue;
}
el = buffer;
assert(is_element_valid(mpool, el));
SLIST_INSERT_HEAD(&mpool->list, el, entry);
}
ftl_bitmap_destroy(mpool->inuse_bmp);
mpool->inuse_bmp = NULL;
free(mpool->inuse_buf);
mpool->inuse_buf = NULL;
}
ftl_df_obj_id
ftl_mempool_get_df_obj_id(struct ftl_mempool *mpool, void *df_obj_ptr)
{
return ftl_df_get_obj_id(mpool->buffer, df_obj_ptr);
}
size_t
ftl_mempool_get_df_obj_index(struct ftl_mempool *mpool, void *df_obj_ptr)
{
return ftl_mempool_get_df_obj_id(mpool, df_obj_ptr) / mpool->element_size;
}
void *
ftl_mempool_get_df_ptr(struct ftl_mempool *mpool, ftl_df_obj_id df_obj_id)
{
return ftl_df_get_obj_ptr(mpool->buffer, df_obj_id);
}
void *
ftl_mempool_claim_df(struct ftl_mempool *mpool, ftl_df_obj_id df_obj_id)
{
struct ftl_mempool_element *el = ftl_df_get_obj_ptr(mpool->buffer, df_obj_id);
assert(!ftl_mempool_is_initialized(mpool));
assert(df_obj_id % mpool->element_size == 0);
assert(df_obj_id / mpool->element_size < mpool->count);
ftl_bitmap_set(mpool->inuse_bmp, df_obj_id / mpool->element_size);
return el;
}
void
ftl_mempool_release_df(struct ftl_mempool *mpool, ftl_df_obj_id df_obj_id)
{
assert(!ftl_mempool_is_initialized(mpool));
assert(df_obj_id % mpool->element_size == 0);
assert(df_obj_id / mpool->element_size < mpool->count);
ftl_bitmap_clear(mpool->inuse_bmp, df_obj_id / mpool->element_size);
}
| 2.578125 | 3 |
2024-11-18T21:29:57.314105+00:00 | 2017-04-28T15:16:26 | 4f25c7c5189a38331ce6127eb08a4023d7563def | {
"blob_id": "4f25c7c5189a38331ce6127eb08a4023d7563def",
"branch_name": "refs/heads/master",
"committer_date": "2017-04-28T15:16:26",
"content_id": "7b6f0200782477c8f3067db0c7cc1d962e121a93",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "228ad7060a1215c7a6a2ac09fb6519806f963d85",
"extension": "c",
"filename": "murmur3.c",
"fork_events_count": 0,
"gha_created_at": "2017-04-24T13:50:40",
"gha_event_created_at": "2017-04-24T13:50:41",
"gha_language": null,
"gha_license_id": null,
"github_id": 89245819,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2361,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/murmur3.c",
"provenance": "stackv2-0112.json.gz:181180",
"repo_name": "robin900/timescaledb",
"revision_date": "2017-04-28T15:16:26",
"revision_id": "035cfc9f72b60361530172eb0313aba5b5ccab41",
"snapshot_id": "90cf46204c436597262fed0006acad63c388461f",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/robin900/timescaledb/035cfc9f72b60361530172eb0313aba5b5ccab41/src/murmur3.c",
"visit_date": "2021-01-20T01:14:26.521115"
} | stackv2 | /* ----------------------------------------------------------------------------- */
/* MurmurHash3 was written by Austin Appleby, and is placed in the public */
/* domain. The author hereby disclaims copyright to this source code. */
/* Note - The x86 and x64 versions do _not_ produce the same results, as the */
/* algorithms are optimized for their respective platforms. You can still */
/* compile and run any of them on any platform, but your performance with the */
/* non-native version will be less than optimal. */
#include "pgmurmur3.h"
/* ----------------------------------------------------------------------------- */
/* Platform-specific functions and macros */
static inline uint32_t
rotl32(uint32_t x, int8_t r)
{
return (x << r) | (x >> (32 - r));
}
#define ROTL32(x,y) rotl32(x,y)
/* ----------------------------------------------------------------------------- */
/* Block read - if your platform needs to do endian-swapping or can only */
/* handle aligned reads, do the conversion here */
static inline uint32_t
getblock(const uint32_t *p, int i)
{
return p[i];
}
/* ----------------------------------------------------------------------------- */
/* Finalization mix - force all bits of a hash block to avalanche */
static inline uint32_t
fmix(uint32_t h)
{
h ^= h >> 16;
h *= 0x85ebca6b;
h ^= h >> 13;
h *= 0xc2b2ae35;
h ^= h >> 16;
return h;
}
/* ----------------------------------------------------------------------------- */
void
hlib_murmur3(const void *key, size_t len, uint64_t * io)
{
const uint8_t *data = (const uint8_t *) key;
const int nblocks = len / 4;
uint32_t h1 = io[0];
uint32_t c1 = 0xcc9e2d51;
uint32_t c2 = 0x1b873593;
const uint32_t *blocks;
const uint8_t *tail;
int i;
uint32_t k1;
/* ---------- */
/* body */
blocks = (const uint32_t *) (data + nblocks * 4);
for (i = -nblocks; i; i++)
{
k1 = getblock(blocks, i);
k1 *= c1;
k1 = ROTL32(k1, 15);
k1 *= c2;
h1 ^= k1;
h1 = ROTL32(h1, 13);
h1 = h1 * 5 + 0xe6546b64;
}
/* ---------- */
/* tail */
tail = (const uint8_t *) (data + nblocks * 4);
k1 = 0;
switch (len & 3)
{
case 3:
k1 ^= tail[2] << 16;
case 2:
k1 ^= tail[1] << 8;
case 1:
k1 ^= tail[0];
k1 *= c1;
k1 = ROTL32(k1, 15);
k1 *= c2;
h1 ^= k1;
};
/* ---------- */
/* finalization */
h1 ^= len;
h1 = fmix(h1);
io[0] = h1;
}
| 2.765625 | 3 |
2024-11-18T21:29:57.622512+00:00 | 2015-04-26T20:06:14 | 00cf3765c7e2f72f3c999bfc08de494c67c838a4 | {
"blob_id": "00cf3765c7e2f72f3c999bfc08de494c67c838a4",
"branch_name": "refs/heads/master",
"committer_date": "2015-04-26T20:06:14",
"content_id": "7e1c5aeeee3fc73105857b82562d7fa430a70b7a",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "2de96e41dad265fbea7e70e849c4b2e61b582c47",
"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": 4411,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/main.c",
"provenance": "stackv2-0112.json.gz:181569",
"repo_name": "tigerjibo/netns-1",
"revision_date": "2015-04-26T20:06:14",
"revision_id": "de9059c694d27eb5e57ba69f9173998b7bcfb031",
"snapshot_id": "8a7c5e9b9fdbea8a09d99ad6b76cc91c24976230",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/tigerjibo/netns-1/de9059c694d27eb5e57ba69f9173998b7bcfb031/main.c",
"visit_date": "2021-01-21T21:29:28.876270"
} | stackv2 | /*
Copyright (c) 2015, Andreas Fett
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
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.
*/
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <errno.h>
#include <sched.h>
#include <unistd.h>
#include <sys/mount.h>
enum ns_op {
NS_OP_UNKNOWN = 0,
NS_OP_ADD,
NS_OP_DEL,
NS_OP_EXEC,
};
static struct {
const char *cmd;
const char *usage;
int op;
} cmds[] = {
{ .cmd = "add", .op = NS_OP_ADD, .usage = "<name>" },
{ .cmd = "del", .op = NS_OP_DEL, .usage = "<name>" },
{ .cmd = "exec", .op = NS_OP_EXEC, .usage = "<name> cmd [args]" },
{ 0 },
};
static void usage(char *argv0)
{
fprintf(stderr, "usage: %s command\ncommands:\n", argv0);
for (size_t i = 0; cmds[i].cmd; ++i) {
fprintf(stderr, "\t%s %s\n", cmds[i].cmd, cmds[i].usage);
}
}
/* add a namespace
- leave the current network namespace
- create a new regular file
- bind mount out new namespace to the file
*/
static int add(const char *path)
{
if (unshare(CLONE_NEWNET) != 0) {
fprintf(stderr, "can't create new namespace: %s\n",
strerror(errno));
return -1;
}
int fd = open(path, O_RDONLY|O_CREAT|O_EXCL);
if (fd < 0) {
fprintf(stderr, "can't create %s: %s\n",
path, strerror(errno));
return -1;
}
close(fd);
int ret = mount("/proc/self/ns/net", path, 0, MS_BIND, 0);
if (ret != 0) {
fprintf(stderr, "can't mount namespace: %s\n",
strerror(errno));
return -1;
}
return 0;
}
/* delete a namespace
- umount the namespace
- unlink the file
*/
static int del(const char *path)
{
if (umount(path) != 0) {
fprintf(stderr, "can't umount namespace '%s': %s\n",
path, strerror(errno));
return -1;
}
if (unlink(path) != 0) {
fprintf(stderr, "can't unlink %s: %s\n",
path, strerror(errno));
return -1;
}
return 0;
}
/* exec a program in the given namespace
- open the namespace
- associate with the namesapce fd
- pass command line args to exec
*/
static int exec(const char *path, char *argv[])
{
int fd = open(path, O_RDONLY|O_CLOEXEC);
if (fd < 0) {
fprintf(stderr, "can't open namespace %s: %s\n",
path, strerror(errno));
return -1;
}
if (setns(fd, CLONE_NEWNET) != 0) {
fprintf(stderr, "can't enter namespace %s: %s\n",
path, strerror(errno));
close(fd);
return -1;
}
if (execvp(argv[0], argv) != 0) {
fprintf(stderr, "can't exec %s: %s\n",
argv[0], strerror(errno));
return -1;
}
return 0;
}
static enum ns_op getop(const char *cmd)
{
for (size_t i = 0; cmds[i].cmd; ++i) {
if (strcmp(cmd, cmds[i].cmd) == 0) {
return cmds[i].op;
}
}
return NS_OP_UNKNOWN;
}
int main(int argc, char *argv[])
{
if (argc < 3) {
usage(argv[0]);
return 1;
}
int ret = 0;
const char *nspath = argv[2];
switch (getop(argv[1])) {
case NS_OP_ADD:
ret = add(nspath);
break;
case NS_OP_DEL:
ret = del(nspath);
break;
case NS_OP_EXEC:
if (argc < 4) {
fprintf(stderr, "exec is missing command\n");
usage(argv[0]);
return 1;
}
ret = exec(nspath, &argv[3]);
break;
case NS_OP_UNKNOWN:
fprintf(stderr, "unknown command '%s'\n", argv[1]);
usage(argv[0]);
return 1;
}
return ret == 0 ? 0 : 1;
}
| 2.8125 | 3 |
2024-11-18T21:29:58.192631+00:00 | 2023-08-02T17:24:06 | 89f53da932666fb56c987d524516c33bb0022cf4 | {
"blob_id": "89f53da932666fb56c987d524516c33bb0022cf4",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-02T17:24:06",
"content_id": "33bcf9dc1e8254800b849cf0035937c276db9ab2",
"detected_licenses": [
"Apache-2.0",
"NCSA"
],
"directory_id": "bea347f558db7ef3521038bc4089471e9b563307",
"extension": "h",
"filename": "Array.h",
"fork_events_count": 6,
"gha_created_at": "2014-07-22T18:58:51",
"gha_event_created_at": "2023-09-01T16:37:04",
"gha_language": "Java",
"gha_license_id": "Apache-2.0",
"github_id": 22116816,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1881,
"license": "Apache-2.0,NCSA",
"license_type": "permissive",
"path": "/include/standard/Array.h",
"provenance": "stackv2-0112.json.gz:182219",
"repo_name": "TeamShadow/shadow",
"revision_date": "2023-08-02T17:24:06",
"revision_id": "225fd95278ca9cd77139834661e1d297b8a5de3d",
"snapshot_id": "6114a72354eeb1182fdcf0bb1f61795b69ba3110",
"src_encoding": "UTF-8",
"star_events_count": 9,
"url": "https://raw.githubusercontent.com/TeamShadow/shadow/225fd95278ca9cd77139834661e1d297b8a5de3d/include/standard/Array.h",
"visit_date": "2023-08-31T21:27:39.902907"
} | stackv2 | /**
* Authors: Claude Abounegm and Barry Wittman
*/
#ifndef SHADOW_ARRAY_H
#define SHADOW_ARRAY_H
#include <standard/ULong.h>
#include <standard/Boolean.h>
#include <standard/Long.h>
#include <standard/Class.h>
#include <standard/MethodTable.h>
#include <stddef.h>
// This should be changed when the structure of the arrays change.
// YOU SHOULD NOT ATTEMPT TO USE THIS STRUCT UNLESS YOU REALLY KNOW
// KNOW WHAT YOU'RE DOING. USE ArrayData INSTEAD.
typedef struct {
shadow_ulong_t ref_count;
shadow_Class_t* class_ref;
shadow_MethodTable_t* methods;
shadow_long_t size;
} shadow_Array_t;
/**
* This is the C representation of the Shadow array when unpacked.
*/
typedef struct {
shadow_long_t size; // how many elements are in the array
void* data; // the pointer to the data, which needs to be cast
// to the desired data structure.
} ArrayData;
/**
* Takes a shadow_Array_t* supplied from Shadow code, and stores the data
* in the C usable format, in ArrayData* array. If data is modified here,
* the data is also modified in Shadow.
*/
ArrayData* __shadow_standard__Array_getData(shadow_Array_t* shadowArray, ArrayData* array);
/**
* Creates a Shadow Array which can be passed to Shadow methods.
*
* param num - the number of elements in the array.
* param class - the Shadow Class of the array (NOT the class of the elements, the class of the whole array)
* param nullable - true if the array can contain null elements, false otherwise
* param data - this is a block of memory initialized using calloc(num, size)
* and is the actual data that Shadow will use. So index through that.
*/
shadow_Array_t* __shadow_standard__Array_create(size_t num, shadow_Class_t* class, bool nullable, void** data);
/**
* Frees the array that was created using shadowArray_Create();
*/
void __shadow_standard__Array_free(shadow_Array_t* array);
#endif | 2.609375 | 3 |
2024-11-18T21:29:58.274702+00:00 | 2023-03-17T20:27:37 | b8728549275ed0cc1a6f9651e37d06738dda3fd2 | {
"blob_id": "b8728549275ed0cc1a6f9651e37d06738dda3fd2",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-31T11:52:41",
"content_id": "8cff1b1b1f2f77bf8a7655dca546b5e17c6aefc8",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "85ccd32aa73eecf274a937f1fc3b6f4d484b77da",
"extension": "c",
"filename": "comparer-end.c",
"fork_events_count": 1848,
"gha_created_at": "2014-05-14T15:08:16",
"gha_event_created_at": "2023-09-14T15:47:23",
"gha_language": "Python",
"gha_license_id": "Apache-2.0",
"github_id": 19784232,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 375,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/test cases/common/107 spaces backslash/comparer-end.c",
"provenance": "stackv2-0112.json.gz:182348",
"repo_name": "mesonbuild/meson",
"revision_date": "2023-03-17T20:27:37",
"revision_id": "cf5adf0c646474f0259d123fad60ca5ed38ec891",
"snapshot_id": "48321cf4235dfcc0194fed90ff43a57367592bf7",
"src_encoding": "UTF-8",
"star_events_count": 5122,
"url": "https://raw.githubusercontent.com/mesonbuild/meson/cf5adf0c646474f0259d123fad60ca5ed38ec891/test cases/common/107 spaces backslash/comparer-end.c",
"visit_date": "2023-09-01T05:58:50.807952"
} | stackv2 | #include "comparer.h"
#ifndef COMPARER_INCLUDED
#error "comparer.h not included"
#endif
#define COMPARE_WITH "foo\\bar\\" /* This is `foo\bar\` */
int main(void) {
if (strcmp (DEF_WITH_BACKSLASH, COMPARE_WITH)) {
printf ("Arg string is quoted incorrectly: %s vs %s\n",
DEF_WITH_BACKSLASH, COMPARE_WITH);
return 1;
}
return 0;
}
| 2.109375 | 2 |
2024-11-18T21:29:58.353913+00:00 | 2017-11-19T10:48:00 | eba07430addeb6ccfbe1a7f2f39fc2d2f6d7a303 | {
"blob_id": "eba07430addeb6ccfbe1a7f2f39fc2d2f6d7a303",
"branch_name": "refs/heads/master",
"committer_date": "2017-11-19T10:48:00",
"content_id": "f0ce6d19436dd7a06d5b4ebc8be3cf988f83af3c",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "57c2eaaf42f372bbd8ae55e533e86af35c359ef8",
"extension": "c",
"filename": "message_example4.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 111287175,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 6107,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/example/book_chapter_7_message/message_example4.c",
"provenance": "stackv2-0112.json.gz:182476",
"repo_name": "BlackAnt2015/BlackAnt_Robort_v3.0",
"revision_date": "2017-11-19T10:48:00",
"revision_id": "58f1dad457747bd5856634704c4c68a90d3e838b",
"snapshot_id": "a8331576b15e6a3f0a27e16d47f6efc751ace84f",
"src_encoding": "GB18030",
"star_events_count": 4,
"url": "https://raw.githubusercontent.com/BlackAnt2015/BlackAnt_Robort_v3.0/58f1dad457747bd5856634704c4c68a90d3e838b/example/book_chapter_7_message/message_example4.c",
"visit_date": "2021-08-16T08:47:50.171470"
} | stackv2 | #include "example.h"
#include "trochili.h"
#if (EVB_EXAMPLE == CH7_MESSAGE_EXAMPLE4)
/* 用户线程参数 */
#define THREAD_LED_STACK_BYTES (512)
#define THREAD_LED_PRIORITY (7)
#define THREAD_LED_SLICE (20)
/* 用户线程定义 */
static TThread ThreadLed1;
static TThread ThreadLed2;
/* 用户线程栈定义 */
static TBase32 ThreadLed1Stack[THREAD_LED_STACK_BYTES/4];
static TBase32 ThreadLed2Stack[THREAD_LED_STACK_BYTES/4];
/* 用户消息类型定义 */
typedef struct
{
TBase32 Index;
TBase32 Value;
} TLedMsg;
/* 用户消息队列定义 */
#define MQ_POOL_LEN (32)
static TMsgQueue LedMQ1;
static TMsgQueue LedMQ2;
static void* Led1MsgPool[MQ_POOL_LEN];
static void* Led2MsgPool[MQ_POOL_LEN];
/* 用户消息定义 */
static TLedMsg LedMsg1;
static TLedMsg LedMsg2;
/* Led1的线程的主函数 */
static void ThreadLed1Entry(TArgument arg)
{
TState state;
TError error;
TLedMsg* pMsg1 = &LedMsg1;
TLedMsg* pMsg2 = &LedMsg2;
while (eTrue)
{
/* Led1线程以阻塞方式发送Led1点亮消息 */
pMsg2->Index = LED2;
pMsg2->Value = LED_ON;
state = TclSendMessage(&LedMQ2, (void**)(&pMsg2), TCLO_IPC_WAIT, 0, &error);
TCLM_ASSERT((state == eSuccess), "");
TCLM_ASSERT((error == TCLE_IPC_NONE), "");
/* Led1线程以阻塞方式接收消息,根据消息内容来点亮或者熄灭Led1 */
state = TclReceiveMessage(&LedMQ1, (void**)(&pMsg1), TCLO_IPC_WAIT, 0, &error);
TCLM_ASSERT((state == eSuccess), "");
TCLM_ASSERT((error == TCLE_IPC_NONE), "");
EvbLedControl(pMsg1->Index, pMsg1->Value);
pMsg2->Index = LED2;
pMsg2->Value = LED_OFF;
state = TclSendMessage(&LedMQ2, (void**)(&pMsg2), TCLO_IPC_WAIT, 0, &error);
TCLM_ASSERT((state == eSuccess), "");
TCLM_ASSERT((error == TCLE_IPC_NONE), "");
/* Led1线程以阻塞方式接收消息,根据消息内容来点亮或者熄灭Led1 */
state = TclReceiveMessage(&LedMQ1, (void**)(&pMsg1), TCLO_IPC_WAIT, 0, &error);
TCLM_ASSERT((state == eSuccess), "");
TCLM_ASSERT((error == TCLE_IPC_NONE), "");
EvbLedControl(pMsg1->Index, pMsg1->Value);
}
}
/* Led2线程的主函数 */
static void ThreadLed2Entry(TArgument arg)
{
TState state;
TError error;
TLedMsg* pMsg1 = &LedMsg1;
TLedMsg* pMsg2 = &LedMsg2;
while (eTrue)
{
/* Led2线程以阻塞方式接收消息,根据消息内容来点亮或者熄灭Led2 */
state = TclReceiveMessage(&LedMQ2, (void**)(&pMsg2), TCLO_IPC_WAIT, 0, &error);
TCLM_ASSERT((state == eSuccess), "");
TCLM_ASSERT((error == TCLE_IPC_NONE), "");
EvbLedControl(pMsg2->Index, pMsg2->Value);
/* Led2线程延时1秒 */
state = TclDelayThread(TCLM_MLS2TICKS(1000), &error);
TCLM_ASSERT((state == eSuccess), "");
TCLM_ASSERT((error == TCLE_THREAD_NONE), "");
/* Led2线程以阻塞方式发送Led1点亮消息 */
pMsg1->Index = LED1;
pMsg1->Value = LED_ON;
state = TclSendMessage(&LedMQ1, (void**)(&pMsg1), TCLO_IPC_WAIT, 0, &error);
TCLM_ASSERT((state == eSuccess), "");
TCLM_ASSERT((error == TCLE_IPC_NONE), "");
/* Led2线程以阻塞方式接收消息,根据消息内容来点亮或者熄灭Led2 */
state = TclReceiveMessage(&LedMQ2, (void**)(&pMsg2), TCLO_IPC_WAIT, 0, &error);
TCLM_ASSERT((state == eSuccess), "");
TCLM_ASSERT((error == TCLE_IPC_NONE), "");
EvbLedControl(pMsg2->Index, pMsg2->Value);
/* Led2线程延时1秒 */
state = TclDelayThread(TCLM_MLS2TICKS(1000), &error);
TCLM_ASSERT((state == eSuccess), "");
TCLM_ASSERT((error == TCLE_THREAD_NONE), "");
/* Led2线程以阻塞方式发送Led1熄灭消息 */
pMsg1->Index = LED1;
pMsg1->Value = LED_OFF;
state = TclSendMessage(&LedMQ1, (void**)(&pMsg1), TCLO_IPC_WAIT, 0, &error);
TCLM_ASSERT((state == eSuccess), "");
TCLM_ASSERT((error == TCLE_IPC_NONE), "");
}
}
/* 用户应用入口函数 */
static void AppSetupEntry(void)
{
TState state;
TError error;
/* 初始化消息队列 */
state = TclCreateMsgQueue(&LedMQ1, "queue1", (void**)(&Led1MsgPool),
MQ_POOL_LEN, TCLP_IPC_DEFAULT, &error);
TCLM_ASSERT((state == eSuccess), "");
TCLM_ASSERT((error == TCLE_IPC_NONE), "");
state = TclCreateMsgQueue(&LedMQ2, "queue2", (void**)(&Led2MsgPool),
MQ_POOL_LEN, TCLP_IPC_DEFAULT, &error);
TCLM_ASSERT((state == eSuccess), "");
TCLM_ASSERT((error == TCLE_IPC_NONE), "");
/* 初始化Led设备控制线程1 */
state = TclCreateThread(&ThreadLed1, "thread led1",
&ThreadLed1Entry, (TArgument)0,
ThreadLed1Stack, THREAD_LED_STACK_BYTES,
THREAD_LED_PRIORITY, THREAD_LED_SLICE,
&error);
TCLM_ASSERT((state == eSuccess), "");
TCLM_ASSERT((error == TCLE_THREAD_NONE), "");
/* 初始化Led设备控制线程2 */
state = TclCreateThread(&ThreadLed2, "thread led2",
&ThreadLed2Entry, (TArgument)0,
ThreadLed2Stack, THREAD_LED_STACK_BYTES,
THREAD_LED_PRIORITY, THREAD_LED_SLICE,
&error);
TCLM_ASSERT((state == eSuccess), "");
TCLM_ASSERT((error == TCLE_THREAD_NONE), "");
/* 激活Led线程1 */
state = TclActivateThread(&ThreadLed1,&error);
TCLM_ASSERT((state == eSuccess), "");
TCLM_ASSERT((error == TCLE_THREAD_NONE), "");
/* 激活Led线程2 */
state = TclActivateThread(&ThreadLed2,&error);
TCLM_ASSERT((state == eSuccess), "");
TCLM_ASSERT((error == TCLE_THREAD_NONE), "");
}
/* 处理器BOOT之后会调用main函数,必须提供 */
int main(void)
{
/* 注册各个内核函数,启动内核 */
TclStartKernel(&AppSetupEntry,
&OsCpuSetupEntry,
&EvbSetupEntry,
&EvbTraceEntry);
return 1;
}
#endif
| 2.328125 | 2 |
2024-11-18T21:29:58.892724+00:00 | 2021-05-31T05:23:52 | 610de8adcba60bc9b653f57b022050d5d66a3e6d | {
"blob_id": "610de8adcba60bc9b653f57b022050d5d66a3e6d",
"branch_name": "refs/heads/develop",
"committer_date": "2021-05-31T05:23:52",
"content_id": "8f6fb6c1b0144f9f51f64e8e9608eee99a08ccc7",
"detected_licenses": [
"Apache-2.0",
"MIT"
],
"directory_id": "d2d9ebc032f26f54b08ac3f35e3777e3a3ef68f6",
"extension": "c",
"filename": "riff_misc.c",
"fork_events_count": 0,
"gha_created_at": "2021-01-03T23:29:52",
"gha_event_created_at": "2021-05-31T03:58:15",
"gha_language": "Verilog",
"gha_license_id": "MIT",
"github_id": 326521284,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1607,
"license": "Apache-2.0,MIT",
"license_type": "permissive",
"path": "/quickfeather/source/qorc-sdk/Libraries/riff_file/src/riff_misc.c",
"provenance": "stackv2-0112.json.gz:182993",
"repo_name": "rahmant3/polymath-iot",
"revision_date": "2021-05-31T05:23:52",
"revision_id": "2bfa10f763d4d612a850413599bb4e76471426c7",
"snapshot_id": "9976d09ad5b2f0287d9d91b07fea193c34f153e6",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/rahmant3/polymath-iot/2bfa10f763d4d612a850413599bb4e76471426c7/quickfeather/source/qorc-sdk/Libraries/riff_file/src/riff_misc.c",
"visit_date": "2023-04-26T03:27:19.844781"
} | stackv2 | #include "Fw_global_config.h"
#include "ql_riff.h"
#include "riff_internal.h"
/* initialize */
void RIFF_init(void)
{
/* nothing yet */
RIFF_file_init();
RIFF_block_init();
}
/* we want to overide the length element with this value */
void RIFF_override_size( struct riff_object *pObject, uint32_t size )
{
riff_valid_busy_object(pObject);
pObject->over_ride_length = size;
}
/* get pointer to the raw data in the riff block */
void* RIFF_raw_data_ptr( struct riff_object *pObject )
{
riff_valid_busy_object( pObject );
return (void *)(pObject->u.pDataVp);
}
/* return number of bytes available in the riff block */
size_t RIFF_space_avail( struct riff_object *pObj )
{
size_t size;
RIFF_dma_wr_get( pObj, NULL, &size );
return size;
}
/* Get location (and length) where we can insert data into the RIFF block. */
void RIFF_dma_wr_get( struct riff_object *pObj, void **vpp, size_t *pSize)
{
int r;
if( vpp ){
*vpp = &(pObj->u.pData8[ pObj->byte_wr_index]);
}
r = pObj->pOwner->block_size;
r = r - pObj->byte_wr_index;
if( r < 0 ){
r = 0;
}
if( pSize ){
*pSize = r;
}
}
/* That external code has completed writing data into the RIFF block
* we need to update the write index with the actual amount written.
*/
void RIFF_dma_wr_complete( struct riff_object *pObj, size_t nActual )
{
riff_valid_busy_object( pObj );
pObj->byte_wr_index += nActual;
if( pObj->byte_wr_index > pObj->pOwner->block_size ){
pObj->byte_wr_index = pObj->pOwner->block_size;
}
}
| 2.4375 | 2 |
2024-11-18T21:29:59.087719+00:00 | 2021-06-07T08:59:08 | df3c5fe2c4e4e981778cd0ff888255ac16269af4 | {
"blob_id": "df3c5fe2c4e4e981778cd0ff888255ac16269af4",
"branch_name": "refs/heads/main",
"committer_date": "2021-06-07T08:59:08",
"content_id": "e313d8b7ec44bffd6c3acc055a6534e6a1c675f3",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "4fd36a344e34743f529a0a00eec12ecb3d7bed41",
"extension": "h",
"filename": "radio.h",
"fork_events_count": 0,
"gha_created_at": "2021-01-15T11:02:28",
"gha_event_created_at": "2021-06-07T08:59:09",
"gha_language": "C",
"gha_license_id": "Apache-2.0",
"github_id": 329887791,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 581,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/net_core/include/radio.h",
"provenance": "stackv2-0112.json.gz:183252",
"repo_name": "Simula-UiB/mesh-node",
"revision_date": "2021-06-07T08:59:08",
"revision_id": "89e1dc78ede254ff8c95b85d44b8e1443b31f12e",
"snapshot_id": "d413aa48202e681d64a7f649587a3334694ea2c2",
"src_encoding": "UTF-8",
"star_events_count": 4,
"url": "https://raw.githubusercontent.com/Simula-UiB/mesh-node/89e1dc78ede254ff8c95b85d44b8e1443b31f12e/net_core/include/radio.h",
"visit_date": "2023-06-03T00:23:26.629356"
} | stackv2 | /**
* @brief Initialize radio
*/
void init_radio();
/**
* @brief Start radio transmission
*/
int radio_send(uint8_t *data, size_t length);
/**
* @brief Radio receive callback function.
*
* @details This function must be implemented by the module making use of the radio. It will be called
* when the radio has received a frame. The data buffer may be overwritten at any time after this
* function returns, so data should be copied to another buffer or processing should be completed
* before returning.
*/
void radio_receive_cb(struct message *msg);
| 2.046875 | 2 |
2024-11-18T21:29:59.241945+00:00 | 2020-11-28T06:28:04 | 45b217081c4cacb0bfc23283af9dfaade1335343 | {
"blob_id": "45b217081c4cacb0bfc23283af9dfaade1335343",
"branch_name": "refs/heads/master",
"committer_date": "2020-11-28T06:28:04",
"content_id": "60d36e75fc00b63466bec589c65ecb7d05d4c6e1",
"detected_licenses": [
"MIT"
],
"directory_id": "330ed9e03b2cdd42d165993dfd0fe1f1c9644808",
"extension": "c",
"filename": "queueUsingList.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 311221733,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 636,
"license": "MIT",
"license_type": "permissive",
"path": "/queueUsingList.c",
"provenance": "stackv2-0112.json.gz:183381",
"repo_name": "udit512/Data-Structure-Using-c",
"revision_date": "2020-11-28T06:28:04",
"revision_id": "5f44cdae4307c2d7882d96a5da5e8578f34337f5",
"snapshot_id": "1810727c68364d96113d88e527036e9b807fb5b1",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/udit512/Data-Structure-Using-c/5f44cdae4307c2d7882d96a5da5e8578f34337f5/queueUsingList.c",
"visit_date": "2023-01-20T18:43:53.375330"
} | stackv2 | #include<stdlib.h>
#include<stdio.h>
struct Queue{
int data;
struct Queue * next;
};
typedef struct Queue * ptr;
ptr front=NULL,rear=NULL;
void enQueue(){
ptr q = (ptr)malloc(sizeof(struct Queue));
printf("Enter the number");
scanf("%d",&q->data);
q->next = NULL;
if (front == rear)
{
front = rear = q;
}
else
{
rear->next = q;
rear = q;
}
}
void deQueue(){
if(front == NULL){
printf("Empty Queue");
}
else{
ptr q = front;
front = front->next;
free(q);
}
}
void displayQueue(){
//normal display like linked list traversing
} | 3.4375 | 3 |
2024-11-18T21:29:59.331651+00:00 | 2019-04-17T18:08:31 | 96168b647beeda50d5509ec7109e422074915aea | {
"blob_id": "96168b647beeda50d5509ec7109e422074915aea",
"branch_name": "refs/heads/master",
"committer_date": "2019-04-17T18:08:31",
"content_id": "7125efe0f171ec3aa2b844308931236a009480d4",
"detected_licenses": [
"MIT"
],
"directory_id": "916e6f4d149d9f089d6fa16b6a8ea6527b56e633",
"extension": "c",
"filename": "fractional_knapsack.c",
"fork_events_count": 10,
"gha_created_at": "2018-06-16T13:38:49",
"gha_event_created_at": "2020-10-03T06:39:42",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 137583289,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2018,
"license": "MIT",
"license_type": "permissive",
"path": "/algorithmic_toolbox/greedy_algorithms/fractional_knapsack.c",
"provenance": "stackv2-0112.json.gz:183513",
"repo_name": "leandrolcampos/coursera-dsa",
"revision_date": "2019-04-17T18:08:31",
"revision_id": "4ffe8792b9818b41007af07a8381c41d035fd308",
"snapshot_id": "7cce6c9dd4cc691fccfe016d1d6f4e1641b2e4e5",
"src_encoding": "UTF-8",
"star_events_count": 10,
"url": "https://raw.githubusercontent.com/leandrolcampos/coursera-dsa/4ffe8792b9818b41007af07a8381c41d035fd308/algorithmic_toolbox/greedy_algorithms/fractional_knapsack.c",
"visit_date": "2021-06-26T00:11:24.288879"
} | stackv2 | /*
* Author: Leandro Augusto Lacerda Campos <llacerdacampos@gmail.com>
*
* Data Structures and Algorithms Specialization,
* by University of California, San Diego,
* and National Research University Higher School of Economics
*
* Course 1: Algorithmic Toolbox
*
* Solution for Maximum Value of the Loot Problem
*/
#include <stdio.h>
#include <stdlib.h>
#define min(a, b) ((a) < (b) ? (a) : (b))
typedef struct item
{
unsigned int value;
unsigned int weight;
} item;
int item_comparison(const item *, const item *);
double optimal_value(unsigned int, const item *, unsigned int);
int main()
{
unsigned short n; /* number of items */
unsigned int W; /* capacity */
item *items;
scanf("%hu %u", &n, &W);
items = malloc(n * sizeof(item));
for (unsigned short i = 0; i < n; i++)
scanf("%u %u", &(items[i].value), &(items[i].weight));
printf("%.4lf\n", optimal_value(W, items, n));
free(items);
return 0;
}
/*
* item_comparison: return < 0 if the value per weight of item1 is less than the value per
* weight of item2; 0 if is equal; and > 0 if is greater.
*/
int item_comparison(const item *item1, const item *item2)
{
return (item1->value * item2->weight) - (item2->value * item1->weight);
}
/*
* optimal_value: find the most valuable combination of items, where 1 <= nitems <= 10^3,
* 0 <= capacity <= 2*10^6, 0 <= items[i].value <= 2*10^6, 0 <= items[i].weight <= 2*10^6,
* and 0 <= i <= nitems - 1.
*/
double optimal_value(unsigned int capacity, const item *items, unsigned int nitems)
{
const item *c_item;
unsigned int weight;
double total;
qsort((void *)items, nitems, sizeof(item),
(int (*)(const void *, const void *))item_comparison);
c_item = &items[nitems];
total = 0.0;
while (capacity && c_item-- - items)
{
weight = min(capacity, c_item->weight);
total += (double)c_item->value / c_item->weight * weight;
capacity -= weight;
}
return total;
} | 3.515625 | 4 |
2024-11-18T21:29:59.880456+00:00 | 2019-08-31T00:39:58 | 8090d65892c2bdd74e2b0c5d1aa54040c1b0156e | {
"blob_id": "8090d65892c2bdd74e2b0c5d1aa54040c1b0156e",
"branch_name": "refs/heads/master",
"committer_date": "2019-08-31T00:39:58",
"content_id": "253b8b34ba2875a87a5032927520f61ce06c76fa",
"detected_licenses": [
"MIT"
],
"directory_id": "e649358eea83e1d7d3e5cfaf88656e9b0bc7aa5f",
"extension": "c",
"filename": "IATextureSelectionData.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 150095088,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3059,
"license": "MIT",
"license_type": "permissive",
"path": "/modules/common/opengl/c/shared/graphics/texture/IATextureSelectionData.c",
"provenance": "stackv2-0112.json.gz:183772",
"repo_name": "impsapps/impsengine",
"revision_date": "2019-08-31T00:39:58",
"revision_id": "1b796bb4bccbe27b3f084a298a22c55555429aa2",
"snapshot_id": "4c23c1bd801ebd363c96d858c4d7ebb19dc19362",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/impsapps/impsengine/1b796bb4bccbe27b3f084a298a22c55555429aa2/modules/common/opengl/c/shared/graphics/texture/IATextureSelectionData.c",
"visit_date": "2020-03-29T16:03:49.678574"
} | stackv2 | #include "IALibrary.h"
#include "IATextureSelectionData.h"
#define CLASSNAME "IATextureSelectionData"
void IATextureSelectionData_setDataWithLeftTopRightBottomAndCurrentIsRotated(IATextureSelectionData * this, GLfloat left, GLfloat top, GLfloat right, GLfloat bottom);
void IATextureSelectionData_make(IATextureSelectionData * this, IATextureSelection textureSelection){
this->isRotated = textureSelection.isRotated;
GLfloat left = textureSelection.selectionRect.origin.x / textureSelection.baseSizeOfTexture.width;
GLfloat top = textureSelection.selectionRect.origin.y / textureSelection.baseSizeOfTexture.height;
GLfloat right = (textureSelection.selectionRect.origin.x + textureSelection.selectionRect.size.width) / textureSelection.baseSizeOfTexture.width;
GLfloat bottom = (textureSelection.selectionRect.origin.y + textureSelection.selectionRect.size.height) / textureSelection.baseSizeOfTexture.height;
IATextureSelectionData_setDataWithLeftTopRightBottomAndCurrentIsRotated(this, left, top, right, bottom);
}
void IATextureSelectionData_makeCopy(IATextureSelectionData * this, const IATextureSelectionData * textureSelectionDataToCopy){
*this = *textureSelectionDataToCopy;
}
void IATextureSelectionData_setDataWithLeftTopRightBottomAndCurrentIsRotated(IATextureSelectionData * this, GLfloat left, GLfloat top, GLfloat right, GLfloat bottom){
if (this->isRotated == false){
this->values[0] = left;
this->values[1] = top;
this->values[2] = left;
this->values[3] = bottom;
this->values[4] = right;
this->values[5] = bottom;
this->values[6] = right;
this->values[7] = top;
}else{
this->values[0] = right;
this->values[1] = top;
this->values[2] = left;
this->values[3] = top;
this->values[4] = left;
this->values[5] = bottom;
this->values[6] = right;
this->values[7] = bottom;
}
}
GLfloat IATextureSelectionData_getSelectionLeft(IATextureSelectionData * this){
return this->values[2];
}
GLfloat IATextureSelectionData_getSelectionTop(IATextureSelectionData * this){
return this->values[1];
}
GLfloat IATextureSelectionData_getSelectionRight(IATextureSelectionData * this){
return this->values[6];
}
GLfloat IATextureSelectionData_getSelectionBottom(IATextureSelectionData * this){
return this->values[5];
}
IASize IATextureSelectionData_getSizeOfSelection(IATextureSelectionData * this, IASize textureSize){
float scaleWidth = IATextureSelectionData_getSelectionRight(this) - IATextureSelectionData_getSelectionLeft(this);
float scaleHeight = IATextureSelectionData_getSelectionBottom(this) - IATextureSelectionData_getSelectionTop(this);
IASize sizeOfSelection = IASize_make(scaleWidth * textureSize.width, scaleHeight * textureSize.height);
if (this->isRotated) {
float temp = sizeOfSelection.width;
sizeOfSelection.width = sizeOfSelection.height;
sizeOfSelection.height = temp;
}
return sizeOfSelection;
}
| 2.328125 | 2 |
2024-11-18T21:30:00.757495+00:00 | 2022-10-04T09:14:42 | e31306d55b9f6dee7a682209fee81edf728c18a3 | {
"blob_id": "e31306d55b9f6dee7a682209fee81edf728c18a3",
"branch_name": "refs/heads/master",
"committer_date": "2022-10-04T09:14:42",
"content_id": "fe76959e0354d345739636e7f6e9e275596ea870",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "86a550d434047d421935772054c53a72c5690570",
"extension": "c",
"filename": "test_bitmap.c",
"fork_events_count": 9,
"gha_created_at": "2012-12-22T02:46:04",
"gha_event_created_at": "2020-06-21T19:41:15",
"gha_language": "C",
"gha_license_id": "NOASSERTION",
"github_id": 7281853,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2724,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/kern/test/generic/test_bitmap.c",
"provenance": "stackv2-0112.json.gz:184554",
"repo_name": "Zeke-OS/zeke",
"revision_date": "2022-10-04T09:14:42",
"revision_id": "c6cd23959e3916c1aae04d909997f67c57c25e91",
"snapshot_id": "55cb5f3153a94cea21b6757bad9d3755f53e2339",
"src_encoding": "UTF-8",
"star_events_count": 81,
"url": "https://raw.githubusercontent.com/Zeke-OS/zeke/c6cd23959e3916c1aae04d909997f67c57c25e91/kern/test/generic/test_bitmap.c",
"visit_date": "2022-10-15T13:16:43.112688"
} | stackv2 | /**
* @file test_bitmap.c
* @brief Test bitmap functions.
*/
#if 0
#include <time.h>
#endif
#include <libkern.h>
#include <kunit.h>
#include <bitmap.h>
#if 0
static void rnd_allocs(int n);
#endif
static void setup(void)
{
/* Intentionally unimplemented... */
}
static void teardown(void)
{
/* Intentionally unimplemented... */
}
static char * test_search(void)
{
bitmap_t bmap[32/4];
size_t retval, err;
memset(bmap, 0, sizeof(bmap));
err = bitmap_block_search(&retval, 256, bmap, sizeof(bmap));
ku_assert_equal("No error", err, 0);
ku_assert_equal("retval ok", retval, 0);
return NULL;
}
static char * test_alloc(void)
{
bitmap_t bmap[64];
size_t ret, err;
memset(bmap, 0, sizeof(bmap));
err = bitmap_block_alloc(&ret, 4, bmap, sizeof(bmap));
ku_assert_equal("No error on allocation", err, 0);
ku_assert_equal("4 bits allocated from bitmap", bmap[0], 0xf);
return NULL;
}
#if 0
static void rnd_allocs(int n)
{
const int allocs = 8000;
const int maxsim = 1000;
int i, j, err;
size_t ret, sti = 0;
size_t st[maxsim][2];
bitmap_t bmap[n][E2BITMAP_SIZE(2048)];
memset(bmap, 0, sizeof(bmap));
for (i = 0; i < allocs; i++) {
for (j = 0; j < n; j++) {
if (kunirand(1)) {
while (!(st[sti][1] = kunirand(100)));
err = bitmap_block_alloc(&ret, st[sti][1], bmap[j], sizeof(bmap[j]));
if (err == 0) {
st[sti][0] = ret;
sti++;
} else if (sti > 0) {
sti--;
bitmap_block_update(bmap[j], 0, st[sti][0], st[sti][1]);
}
}
if ((kunirand(1) || sti >= maxsim) && (sti > 0)) {
sti--;
bitmap_block_update(bmap[j], 0, st[sti][0], st[sti][1]);
}
}
}
}
#endif
#if 0
static char * perf_test(void)
{
const int trials = 3;
int i, n;
int result = 0;
printf("Performance test:\n");
for (n = 1; n <= 4; n++) {
result = 0;
for (i = 0; i < trials; i++) {
struct timeval tv;
gettimeofday(&tv, NULL);
uint32_t start = tv.tv_sec * 1000 + tv.tv_usec / 1000;
rnd_allocs(n);
gettimeofday(&tv, NULL);
uint32_t end = tv.tv_sec * 1000 + tv.tv_usec / 1000;
result += end - start;
}
printf("\tn = %i: %i ms\n", n, result / trials);
}
return NULL;
}
#endif
static void all_tests(void)
{
ku_def_test(test_search, KU_RUN);
ku_def_test(test_alloc, KU_RUN);
#if 0
ku_def_test(perf_test, KU_RUN);
#endif
}
TEST_MODULE(generic, bitmap);
| 2.65625 | 3 |
2024-11-18T21:30:00.828577+00:00 | 2020-12-27T04:20:31 | f0168843dbfa26bb07aac07b16e2aae7f7a644af | {
"blob_id": "f0168843dbfa26bb07aac07b16e2aae7f7a644af",
"branch_name": "refs/heads/main",
"committer_date": "2020-12-27T04:20:31",
"content_id": "29c186872c3052b8dcfa23b7d228924e6d4cf6b6",
"detected_licenses": [
"MIT"
],
"directory_id": "9800268076a4b136f652663a78f37316a93b8dee",
"extension": "c",
"filename": "miniQ.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 324262520,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 13147,
"license": "MIT",
"license_type": "permissive",
"path": "/documentation/avr program/miniQ/miniQ.c",
"provenance": "stackv2-0112.json.gz:184685",
"repo_name": "bstadick/dfrobot-miniq-2wd",
"revision_date": "2020-12-27T04:20:31",
"revision_id": "467f8908291c5c4fe04cd6bf6bab12e330bc67a2",
"snapshot_id": "b46c2f7c5e11975d2750a5401346617ff4952215",
"src_encoding": "GB18030",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/bstadick/dfrobot-miniq-2wd/467f8908291c5c4fe04cd6bf6bab12e330bc67a2/documentation/avr program/miniQ/miniQ.c",
"visit_date": "2023-02-07T04:03:49.748849"
} | stackv2 | #include<avr/io.h>
#include<avr/interrupt.h>
#include<util/delay.h>
#define FORW 1//前进
#define BACK 0//后退
#define Vr 5//参考电压值5v
float data[8]={0X00,0X00,0X00,0X00,0x00,0xff,0x00,0x00};//存储8个通道ad转换的值
float data_;
char channel=0x40;//ad转换通道的选择
char key_1 = 0,key_2=0,key_3=0;//按键按下的次数计数
char value[5]={0X00,0X00,0X00,0X00,0x00};//红外传感器输出的电压值
int count=0;
int count_r=0,count_l=0;//对左右轮返回的脉冲进行计数
int Pulse_Width=0;//存储脉宽
int ir_code=0x00; //命令值
//pwm初始化子函数
void pwm_init(void)
{
TCCR0A = 0XA3;
TCCR0B = 0X03;//时钟源设置为clk/64
TCNT0 = 0X00; //初值设置为0
TIMSK0 = 0X00;//禁止中断
}
//控制电机转动
void Motor_Control(int M1_DIR,int M1_EN,int M2_DIR,int M2_EN)
{
//////////M1////////////////////////
if(M1_DIR==FORW)//M1电机方向
PORTD |=(1<<7);//设置向前
else
PORTD &=~(1<<7);//设置向后
if(M1_EN==0)//M1电机速度
OCR0A = 0;//停止
else
OCR0A = M1_EN;//设置给定的数值
///////////M2//////////////////////
if(M2_DIR==FORW)//M2电机的方向
PORTD |=(1<<4);//设置向前
else
PORTD &=~(1<<4);//设置向后
if(M2_EN==0) //M2电机的速度
OCR0B = 0;//停止
else
OCR0B = M2_EN;//设置给定的数值
}
//ad转换初始化函数
void adc_init(int channel)
{
//设置ad转换寄存器
ADMUX =channel;
ADCSRA =0xcb;
}
//ad转换中断函数
ISR(ADC_vect)
{
ADCSRA &=~ (1<<ADEN); //关中断
data_ = ADCL; //接收第八位值
data_ = data_+ADCH*256; //整个adc的数字值
data_ = ((data_*Vr)/1024); //转换成模拟值
switch(ADMUX)
{
case 0x40:
data[0] = data_;
break;
case 0x41:
data[1] = data_;
break;
case 0x42:
data[2] = data_;
break;
case 0x43:
data[3] = data_;
break;
case 0x44:
data[4] = data_;
break;
case 0x45:
data[5] = data_;
break;
case 0x46:
data[6] = data_;
break;
case 0x47:
data[7] = data_;
break;
}
if(++channel==0x48)//换通道
{
channel = 0x40;
}
adc_init(channel);//重新初始化
}
//左红外发射管发射频率为38khz脉冲
void L_Send(void)
{
int i;
for(i=0;i<24;i++)
{
PORTB &=~(1<<1);//置低,导通
_delay_us(12);//延时
PORTB |=(1<<1);//置高,截止
_delay_us(12);//延时
}
}
//右红外发射管发射频率为38khz脉冲
void R_Send(void)
{
int i;
for(i=0;i<24;i++)
{
PORTB &=~(1<<2);
_delay_us(12);
PORTB |=(1<<2);
_delay_us(12);
}
}
//引脚变化中断初始化函数
void pcint0_init(void)
{
PCICR = 0X01;//使能第0组引脚变化中断
PCMSK0 = 0X01;//使能第0组的第0个引脚变化中断
}
//引脚变化中断函数
ISR(PCINT0_vect)
{
count++;//对接收到的脉冲计数
}
//避障功能子函数
void Obstacle_Avoidance(void)
{
char i,j;
count=0;//计数清零
for(i=0;i<20;i++)//左管发射20个脉冲,会有40个中断
{
L_Send();
for(j=0;j<54;j++)
_delay_us(10);
}
if(count>20)//接收到大于20个中断
{
if(key_2==1||key_3==3)//避障行为或者小鸡行为
{
Motor_Control(BACK,100,BACK,100);//后退
for(j=0;j<50;j++)//延时500ms
_delay_ms(10);
Motor_Control(BACK,100,FORW,100);//右转
for(j=0;j<50;j++)//延时500ms
_delay_ms(10);
}
if(key_3==1)//袭击者模式
{
Motor_Control(FORW,100,FORW,100);//前进
for(j=0;j<30;j++)//延时
_delay_ms(10);//延时
}
}
else
{
count=0;//清零
for(i=0;i<20;i++)//右发射管发射20个脉冲,会有40个中断
{
R_Send();
for(j=0;j<54;j++)
_delay_us(10);
}
if(count>20)//接收到大于20个中断
{
if(key_2==1||key_3==3)//避障行为或者小鸡行为
{
Motor_Control(BACK,100,BACK,100);//后退
for(j=0;j<50;j++)//延时
_delay_ms(10);
Motor_Control(FORW,100,BACK,100);//左转
for(j=0;j<50;j++)//延时
_delay_ms(10);
}
if(key_3==1)//袭击者模式
{
Motor_Control(FORW,100,FORW,100);//前进
for(j=0;j<30;j++)//延时
_delay_ms(10);//延时
}
}
else
if(key_2==1||key_3==3)//避障模式或者小鸡模式
Motor_Control(FORW,100,FORW,100);//前进
if(key_3==1)//袭击者模式
Motor_Control(FORW,0,FORW,0);//前进
}
}
//寻线函数
void huntline_deal(void)
{
if(data[0]>(value[0]-1)&&data[1]>(value[1]-1)&&data[2]<(value[2]-1)&&data[3]>(value[3]-1)&&data[7]>(value[4]-1))
{
Motor_Control(FORW,100,FORW,100);//前进
}
else if(data[0]>(value[0]-1)&&data[1]>(value[1]-1)&&data[2]<(value[2]-1)&&data[3]<(value[3]-1)&&data[7]>(value[4]-1))
{
Motor_Control(BACK,0,FORW,100);//右转
}
else if(data[0]>(value[0]-1)&&data[1]>(value[1]-1)&&data[2]>(value[2]-1)&&data[3]<(value[3]-1)&&data[7]>(value[4]-1))
{
Motor_Control(BACK,0,FORW,100);//右转
}
else if(data[0]>(value[0]-1)&&data[1]>(value[1]-1)&&data[2]>(value[2]-1)&&data[3]<(value[3]-1)&&data[7]<(value[4]-1))
{
Motor_Control(BACK,100,FORW,100);//右转
}
else if(data[0]>(value[0]-1)&&data[1]>(value[1]-1)&&data[2]>(value[2]-1)&&data[3]>(value[3]-1)&&data[7]<(value[4]-1))
{
Motor_Control(BACK,100,FORW,100);//右转
}
else if(data[0]>(value[0]-1)&&data[1]<(value[1]-1)&&data[2]<(value[2]-1)&&data[3]>(value[3]-1)&&data[7]>(value[4]-1))
{
Motor_Control(FORW,100,BACK,0);//左转
}
else if(data[0]>(value[0]-1)&&data[1]<(value[1]-1)&&data[2]>(value[2]-1)&&data[3]>(value[3]-1)&&data[7]>(value[4]-1))
{
Motor_Control(FORW,100,BACK,0);//左转
}
else if(data[0]<(value[0]-1)&&data[1]<(value[1]-1)&&data[2]>(value[2]-1)&&data[3]>(value[3]-1)&&data[7]>(value[4]-1))
{
Motor_Control(FORW,100,BACK,100);//左转
}
else if(data[0]<(value[0]-1)&&data[1]>(value[1]-1)&&data[2]>(value[2]-1)&&data[3]>(value[3]-1)&&data[7]>(value[4]-1))
{
Motor_Control(FORW,100,BACK,100);//左转
}
}
//电压值调整函数
void value_adjust(char num)
{
if(num==1)
{
if(data[0]>value[0])
{
PORTB |=(1<<4); //当前值小红灯亮
PORTB &=~(1<<5);
}
else
{
PORTB |=(1<<5); //当前值大绿灯亮
PORTB &=~(1<<4);
}
}
if(num==2)
{
if(data[1]>value[1])
{
PORTB |=(1<<4); //当前值小红灯亮
PORTB &=~(1<<5);
}
else
{
PORTB |=(1<<5); //当前值大绿灯亮
PORTB &=~(1<<4);
}
}
if(num==3)
{
if(data[2]>value[2])
{
PORTB |=(1<<4); //当前值小红灯亮
PORTB &=~(1<<5);
}
else
{
PORTB |=(1<<5); //当前值大绿灯亮
PORTB &=~(1<<4);
}
}
if(num==4)
{
if(data[3]>value[3])
{
PORTB |=(1<<4); //当前值小红灯亮
PORTB &=~(1<<5);
}
else
{
PORTB |=(1<<5); //当前值大绿灯亮
PORTB &=~(1<<4);
}
}
if(num==5)
{
if(data[4]>value[4])
{
PORTB |=(1<<4); //当前值小红灯亮
PORTB &=~(1<<5);
}
else
{
PORTB |=(1<<5); //当前值大绿灯亮
PORTB &=~(1<<4);
}
}
}
//寻光函数
void hunt_light(void)
{
if (data[4]> 1 && data[4]< 2)
{
Motor_Control(BACK,100,FORW,100);//右转
}
else if (data[4]> 4 && data[4]< 5)
{
Motor_Control(FORW,100,BACK,100);//左转
}
else
{
Motor_Control(FORW,0,FORW,0);//停止
}
}
//遥控
//设置定时器T1为定时模式
void timer1_init(void)
{
TCCR1A = 0X00;
TCCR1B = 0X05;//给定时器时钟源
TCCR1C = 0X00;
TCNT1 = 0X00;
TIMSK1 = 0X00;//禁止定时器溢出中断
}
//执行译码结果
void remote_deal(void)
{
switch(ir_code)
{
case 0xff00://停止
Motor_Control(FORW,0,FORW,0);
break;
case 0xfe01://前进
Motor_Control(FORW,100,FORW,100);
break;
case 0xf609://后退
Motor_Control(BACK,100,BACK,100);
break;
case 0xfb04://左转
Motor_Control(FORW,100,BACK,100);
break;
case 0xf906://右转
Motor_Control(BACK,100,FORW,100);
break;
}
}
char logic_value()//逻辑‘0’和‘1’判断函数
{
while(!(PINB&0X01)); //低等待
Pulse_Width=TCNT1;
TCNT1=0;
if(Pulse_Width>=7&&Pulse_Width<=10)//低电平560us
{
while(PINB&0X01);//是高就等待
Pulse_Width=TCNT1;
TCNT1=0;
if(Pulse_Width>=7&&Pulse_Width<=10)//接着高电平560us
return 0;
else if(Pulse_Width>=25&&Pulse_Width<=27) //接着高电平1.7ms
return 1;
}
return -1;
}
void pulse_deal()//接收地址码和命令码
{
int i;
//地址码
//执行8个0
for(i=0; i<8; i++)
{
if(logic_value() != 0) //不是0
return;
}
//地址反码
//执行6个1
for(i=0; i<6; i++)
{
if(logic_value()!= 1) //不是1
return;
}
//执行1个0
if(logic_value()!= 0) //不是0
return;
//执行1个1
if(logic_value()!= 1) //不是1
return;
//解析遥控器编码中的command指令
ir_code=0x00;//清零
for(i=0; i<16;i++ )
{
if(logic_value() == 1)
{
ir_code |=(1<<i);
}
}
}
void remote_decode(void)//译码函数
{
TCNT1=0X00;
while(PINB&0X01)//是高就等待
{
if(TCNT1>=1563) //当高电平持续时间超过100ms,表明此时没有按键按下
{
ir_code = 0xff00;
return;
}
}
//如果高电平持续时间不超过100ms
TCNT1=0X00;
while(!(PINB&0X01)); //低等待
Pulse_Width=TCNT1;
TCNT1=0;
if(Pulse_Width>=140&&Pulse_Width<=141)//9ms
{
while(PINB&0X01);//是高就等待
Pulse_Width=TCNT1;
TCNT1=0;
if(Pulse_Width>=68&&Pulse_Width<=72)//4.5ms
{
pulse_deal();
return;
}
else if(Pulse_Width>=34&&Pulse_Width<=36)//2.25ms
{
while(!(PINB&0X01));//低等待
Pulse_Width=TCNT1;
TCNT1=0;
if(Pulse_Width>=7&&Pulse_Width<=10)//560us
{
return;
}
}
}
}
//蜂鸣器
void buzzer(void)
{
char k=0;
for(k=0;k<5;k++)
{
PORTB |= (1<<3);
_delay_us(10);
PORTB &= ~(1<<3);
_delay_us(40);//蜂鸣器响
}
}
//按键扫描
void key_scan(void)
{
if(data[5]>4.50&&data[5]<6.00)//没有按键按下
return;
else
{
if(data[5]>=0.00&&data[5]<0.50)//按键1按下
{
_delay_ms(5);//延时消抖
if(data[5]>=0.00&&data[5]<0.50)//按键1确实按下
{
buzzer();//蜂鸣器响
key_1++;//按键1计数
if(key_1>=1&&key_1<=5)
value_adjust(key_1);//寻线传感器的值调整
}
}
else if(data[5]>=0.50&&data[5]<2.00)
{
_delay_ms(5);//延时消抖
if(data[5]>=0.50&&data[5]<2.00)
{
buzzer();//蜂鸣器响
if(key_1>=1&&key_1<=5)
{
value[key_1-1]++;//传感器的分辨轨迹的界限值加加(调整)
value_adjust(key_1);//跟实际值对比
}
else
key_2++;//key2计数
}
}
else if(data[5]>=2.00&&data[5]<3.00)
{
_delay_ms(5);//延时消抖
if(data[5]>=2.00&&data[5]<3.00)
{
buzzer();//蜂鸣器响
if(key_1>=1&&key_1<=5)
{
value[key_1-1]--;//传感器的分辨轨迹的界限值减减(调整)
value_adjust(key_1);//跟实际值对比
}
else
key_3++;//key3计数
}
}
}
}
//按键值处理函数
void key_deal(void)
{
if(key_1==6)//寻线
{
PORTB &=~(1<<5);//绿灯灭
PORTB &=~(1<<4);//红灯灭
huntline_deal();//寻线
}
if(key_2==1||key_3==1||key_3==3)//key_2=1避障行为,key_3==1袭击者,key_3==3小鸡行为
{
ADCSRA=0XC3;
PORTB |=(1<<4);
pcint0_init();//引脚变化中断初始化
Obstacle_Avoidance();
ADCSRA=0XCB;
}
if(key_2==3)//key_2==3寻光行为
{
PORTB |=(1<<4);
hunt_light();//寻光
}
if(key_3==5)//遥控
{
ADCSRA=0XC3;
PORTB |=(1<<4);
timer1_init();//定时器初始化函数
remote_decode(); //译码
remote_deal(); //执行译码结果
ADCSRA=0XCB;
}
if(key_1==7||key_2==2||key_2==4||key_3==2||key_3==4||key_3==6)
{
//按键值清零
key_1=0;
if(key_2==4)
key_2=0;
if(key_3==6)
key_3=0;
PORTB &=~(1<<4);
Motor_Control(FORW,0,FORW,0);//停止
}
}
//主函数
int main(void)
{
DDRD = 0XF2;//设置PORTD口引脚
PORTD |= ((1<<0)|(1<<2)|(1<<3));//设置PORTD口输入引脚的上拉电阻有效
DDRB = 0XFE;//设置PORTB口引脚
PORTB |= (1<<0);//设置PORTB口输入引脚的上拉电阻有效
pwm_init();//PWM脉冲初始化
adc_init(channel);//ad转换初始化
sei();//全局中断允许
while(1)
{
key_scan();//扫描按键
key_deal();//按键处理
}
}
| 2.828125 | 3 |
2024-11-18T21:30:00.891308+00:00 | 2018-01-15T13:10:31 | 0682ea413892e332fe62c2fc499f5b41f541b2db | {
"blob_id": "0682ea413892e332fe62c2fc499f5b41f541b2db",
"branch_name": "refs/heads/master",
"committer_date": "2018-01-15T13:10:31",
"content_id": "de15b28d2e3ddc2a1187e84817e53c6a5baaa63f",
"detected_licenses": [
"MIT"
],
"directory_id": "76a4c5f8e98be972c7cbf835d63c28da22a98bda",
"extension": "c",
"filename": "day15_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": 591,
"license": "MIT",
"license_type": "permissive",
"path": "/day15/day15_1.c",
"provenance": "stackv2-0112.json.gz:184817",
"repo_name": "tinybeachthor/advent-of-code-2017",
"revision_date": "2018-01-15T13:10:31",
"revision_id": "4f3c5dd64fad2c9be71e4723a94347275fb619e8",
"snapshot_id": "d81fe608db34dc3082f9f3781d60fa060167737c",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/tinybeachthor/advent-of-code-2017/4f3c5dd64fad2c9be71e4723a94347275fb619e8/day15/day15_1.c",
"visit_date": "2021-09-04T03:46:16.954388"
} | stackv2 | #include "stdio.h"
int main() {
struct {
unsigned long val;
unsigned long factor;
} gens[2], *gen;
gens[0].factor = 16807;
gens[1].factor = 48271;
gens[0].val = 634;
gens[1].val = 301;
const unsigned long divider = 2147483647;
int judge = 0;
for (unsigned long i = 0; i < 40e6; i++) {
//generate new values
for (unsigned int j = 0; j < 2; j++) {
gen = &gens[j];
gen->val = (gen->val * gen->factor) % divider;
}
//judge 'em
if((gens[0].val & 0xFFFF) == (gens[1].val & 0xFFFF))
judge++;
}
printf("%d\n\n", judge);
}
| 2.9375 | 3 |
2024-11-18T21:30:00.976353+00:00 | 2016-12-13T02:14:17 | b8da791d9ebb3acc3022cd35d5d9dd198c5f009f | {
"blob_id": "b8da791d9ebb3acc3022cd35d5d9dd198c5f009f",
"branch_name": "refs/heads/master",
"committer_date": "2016-12-13T02:14:17",
"content_id": "2de30729c5300d94cc8de1f13ba0fe0868068644",
"detected_licenses": [
"MIT"
],
"directory_id": "64ba1fb68e1bdab4f31ab3c03a1dfe238431da56",
"extension": "c",
"filename": "lsm_work_unit.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": 14212,
"license": "MIT",
"license_type": "permissive",
"path": "/lsm/lsm_work_unit.c",
"provenance": "stackv2-0112.json.gz:184947",
"repo_name": "XXGF/wiredtiger",
"revision_date": "2016-12-13T02:14:17",
"revision_id": "cf4ba57d68dd25620c9c0f0762e8e52f0b2ba4a2",
"snapshot_id": "2665cc639b7347920674a3d75928be25d5e68ac1",
"src_encoding": "GB18030",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/XXGF/wiredtiger/cf4ba57d68dd25620c9c0f0762e8e52f0b2ba4a2/lsm/lsm_work_unit.c",
"visit_date": "2021-12-12T05:47:11.994310"
} | stackv2 | /*****************************************************************************
*
*****************************************************************************/
#include "wt_internal.h"
static int __lsm_bloom_create(WT_SESSION_IMPL* , WT_LSM_TREE* , WT_LSM_CHUNK*, u_int);
static int __lsm_discard_handle(WT_SESSION_IMPL*, const char* , const char*);
/*将lsm tree中的chunks指针数组拷贝到cookie->chunk_array中*/
static int __lsm_copy_chunks(WT_SESSION_IMPL* session, WT_LSM_TREE* lsm_tree, WT_LSM_WORKER_COOKIE* cookie, int old_chunks)
{
WT_DECL_RET;
u_int i, nchunks;
size_t alloc;
cookie->nchunks = 0;
/*获得lsm tree的读锁权限,因为只是拷贝指针,可以使用spin read/write lock*/
WT_RET(__wt_lsm_tree_readlock(session, lsm_tree));
if (!F_ISSET(lsm_tree, WT_LSM_TREE_ACTIVE))
return (__wt_lsm_tree_readunlock(session, lsm_tree));
nchunks = old_chunks ? lsm_tree->nold_chunks : lsm_tree->nchunks;
alloc = old_chunks ? lsm_tree->old_alloc : lsm_tree->chunk_alloc;
if (cookie->chunk_alloc < alloc)
WT_ERR(__wt_realloc(session, &cookie->chunk_alloc, alloc, &cookie->chunk_array));
if (nchunks > 0)
memcpy(cookie->chunk_array, old_chunks ? lsm_tree->old_chunks : lsm_tree->chunk, nchunks * sizeof(*cookie->chunk_array));
/*为每一个chunk增加一个引用计数,在从array中删除的时候再递减*/
for (i = 0; i < nchunks; i++)
WT_ATOMIC_ADD4(cookie->chunk_array[i]->refcnt, 1);
err:
WT_TRET(__wt_lsm_tree_readunlock(session, lsm_tree));
if(ret == 0)
cookie->nchunks = nchunks;
return ret;
}
/*确定一个可以flush的chunk*/
int __wt_lsm_get_chunk_to_flush(WT_SESSION_IMPL *session, WT_LSM_TREE *lsm_tree, int force, WT_LSM_CHUNK **chunkp)
{
WT_DECL_RET;
WT_LSM_CHUNK *chunk, *evict_chunk, *flush_chunk;
u_int i;
*chunkp = NULL;
chunk = evict_chunk = flush_chunk = NULL;
WT_ASSERT(session, lsm_tree->queue_ref > 0);
WT_RET(__wt_lsm_tree_readlock(session, lsm_tree));
if(!F_ISSET(lsm_tree, WT_LSM_TREE_ACTIVE) || lsm_tree->nchunks == 0)
return __wt_lsm_tree_readunlock(session, lsm_tree);
for(i = 0; i < lsm_tree->nchunks; i ++){
chunk = lsm_tree->chunk[i];
if(F_ISSET(chunk, WT_LSM_CHUNK_ONDISK)){
/*
* Normally we don't want to force out the last chunk.
* But if we're doing a forced flush on behalf of a
* compact, then we want to include the final chunk.
*/
if (evict_chunk == NULL && !chunk->evicted && !F_ISSET(chunk, WT_LSM_CHUNK_STABLE))
evict_chunk = chunk;
}
else if (flush_chunk == NULL && chunk->switch_txn != 0 && (force || i < lsm_tree->nchunks - 1)){
flush_chunk = chunk;
}
}
/*确定需要flush的chunk*/
if (evict_chunk != NULL && flush_chunk != NULL) {
chunk = (__wt_random(session->rnd) & 1) ? evict_chunk : flush_chunk;
WT_ERR(__wt_lsm_manager_push_entry(session, WT_LSM_WORK_FLUSH, 0, lsm_tree));
}
else
chunk = (evict_chunk != NULL) ? evict_chunk : flush_chunk;
if (chunk != NULL) {
WT_ERR(__wt_verbose(session, WT_VERB_LSM, "Flush%s: return chunk %u of %u: %s", force ? " w/ force" : "",
i, lsm_tree->nchunks, chunk->uri));
/*增加引用计数*/
(void)WT_ATOMIC_ADD4(chunk->refcnt, 1);
}
err:
WT_RET(__wt_lsm_tree_readunlock(session, lsm_tree));
*chunkp = chunk;
return ret;
}
/*对cookie中的chunk全部去掉引用计数*/
static void __lsm_unpin_chunks(WT_SESSION_IMPL* session, WT_LSM_WORKER_COOKIE* cookie)
{
u_int i;
for (i = 0; i < cookie->nchunks; i++) {
if (cookie->chunk_array[i] == NULL)
continue;
WT_ASSERT(session, cookie->chunk_array[i]->refcnt > 0);
WT_ATOMIC_SUB4(cookie->chunk_array[i]->refcnt, 1);
}
/* Ensure subsequent calls don't double decrement. */
cookie->nchunks = 0;
}
/*检查lsm tree是否需要进行chunk switch,如果需要,调用__wt_lsm_tree_switch进行switch,如果__wt_lsm_tree_switch
* 忙状态,从新加入一个switch信号到lsm manager中*/
int __wt_lsm_work_switch(WT_SESSION_IMPL *session, WT_LSM_WORK_UNIT **entryp, int *ran)
{
WT_DECL_RET;
WT_LSM_WORK_UNIT *entry;
entry = *entryp;
*ran = 0;
*entryp = NULL;
if (F_ISSET(entry->lsm_tree, WT_LSM_TREE_NEED_SWITCH)) {
WT_WITH_SCHEMA_LOCK(session, ret = __wt_lsm_tree_switch(session, entry->lsm_tree));
/* Failing to complete the switch is fine */
if (ret == EBUSY) {
if (F_ISSET(entry->lsm_tree, WT_LSM_TREE_NEED_SWITCH))
WT_ERR(__wt_lsm_manager_push_entry(session, WT_LSM_WORK_SWITCH, 0, entry->lsm_tree));
ret = 0;
}
else
*ran = 1;
}
err:
__wt_lsm_manager_free_work_unit(session, entry);
return ret;
}
/*尝试在chunk中建立一个bloom filter数据,一般是在chunk落盘的时候调用*/
int __wt_lsm_work_bloom(WT_SESSION_IMPL* session, WT_LSM_TREE* lsm_tree)
{
WT_DECL_RET;
WT_LSM_CHUNK *chunk;
WT_LSM_WORKER_COOKIE cookie;
u_int i, merge;
WT_CLEAR(cookie);
/*增加lsm_tree中的chunk引用计数*/
WT_RET(__lsm_copy_chunks(session, lsm_tree, &cookie, 0));
merge = 0;
/*对所有的chunk建立bloom filter*/
for(i = 0; i < cookie.nchunks; i ++){
chunk = cookie.chunk_array[i];
/*跳过正在处理的chunk*/
if(!F_ISSET(chunk, WT_LSM_CHUNK_ONDISK) || F_ISSET(chunk, WT_LSM_CHUNK_BLOOM | WT_LSM_CHUNK_MERGING)
|| chunk->generation > 0 || chunk->count == 0)
continue;
if (WT_ATOMIC_CAS4(chunk->bloom_busy, 0, 1)) {
/*建立bloom filter*/
if (!F_ISSET(chunk, WT_LSM_CHUNK_BLOOM)) {
ret = __lsm_bloom_create(session, lsm_tree, chunk, (u_int)i);
if (ret == 0)
merge = 1;
}
chunk->bloom_busy = 0;
break;
}
}
/*发起一个chunk merge操作,为什么会发起一个merge呢??需要仔细分析*/
if (merge)
WT_ERR(__wt_lsm_manager_push_entry(session, WT_LSM_WORK_MERGE, 0, lsm_tree));
err:
/*删除chunks的引用计数*/
__lsm_unpin_chunks(session, &cookie);
__wt_free(session, cookie.chunk_array);
return ret;
}
/*将chunk上的数据flush到磁盘上*/
int __wt_lsm_checkpoint_chunk(WT_SESSION_IMPL *session, WT_LSM_TREE *lsm_tree, WT_LSM_CHUNK *chunk)
{
WT_DECL_RET;
WT_TXN_ISOLATION saved_isolation;
/*这个chunk已经被建立了checkpoint,我们必须将其设置为被废弃状态*/
if (F_ISSET(chunk, WT_LSM_CHUNK_ONDISK) && !F_ISSET(chunk, WT_LSM_CHUNK_STABLE) && !chunk->evicted) {
if ((ret = __lsm_discard_handle(session, chunk->uri, NULL)) == 0)
chunk->evicted = 1;
else if (ret == EBUSY)
ret = 0;
else
WT_RET_MSG(session, ret, "discard handle");
}
if(F_ISSET(chunk, WT_LSM_CHUNK_ONDISK)){
WT_RET(__wt_verbose(session, WT_VERB_LSM, "LSM worker %s already on disk", chunk->uri));
return 0;
}
/*假如有事务正在操作这个chunk,那么checkpoint需要暂停*/
__wt_txn_update_oldest(session);
if (chunk->switch_txn == WT_TXN_NONE || !__wt_txn_visible_all(session, chunk->switch_txn)) {
WT_RET(__wt_verbose(session, WT_VERB_LSM, "LSM worker %s: running transaction, return", chunk->uri));
return 0;
}
WT_RET(__wt_verbose(session, WT_VERB_LSM, "LSM worker flushing %s", chunk->uri));
/*设置事务的隔离属性标识*/
if ((ret = __wt_session_get_btree(session, chunk->uri, NULL, NULL, 0)) == 0) {
saved_isolation = session->txn.isolation;
session->txn.isolation = TXN_ISO_EVICTION;
ret = __wt_cache_op(session, NULL, WT_SYNC_WRITE_LEAVES);
session->txn.isolation = saved_isolation;
WT_TRET(__wt_session_release_btree(session));
}
WT_RET(ret);
WT_RET(__wt_verbose(session, WT_VERB_LSM, "LSM worker checkpointing %s", chunk->uri));
WT_WITH_SCHEMA_LOCK(session,
ret = __wt_schema_worker(session, chunk->uri, __wt_checkpoint, NULL, NULL, 0));
if (ret != 0)
WT_RET_MSG(session, ret, "LSM checkpoint");
/* Now the file is written, get the chunk size. */
WT_RET(__wt_lsm_tree_set_chunk_size(session, chunk));
/* Update the flush timestamp to help track ongoing progress. */
WT_RET(__wt_epoch(session, &lsm_tree->last_flush_ts));
/* Lock the tree, mark the chunk as on disk and update the metadata. */
WT_RET(__wt_lsm_tree_writelock(session, lsm_tree));
F_SET(chunk, WT_LSM_CHUNK_ONDISK);
ret = __wt_lsm_meta_write(session, lsm_tree);
++lsm_tree->dsk_gen;
/* Update the throttle time. */
__wt_lsm_tree_throttle(session, lsm_tree, 1);
WT_TRET(__wt_lsm_tree_writeunlock(session, lsm_tree));
if (ret != 0)
WT_RET_MSG(session, ret, "LSM metadata write");
WT_RET(__wt_session_get_btree(session, chunk->uri, NULL, NULL, 0));
__wt_btree_evictable(session, 1);
WT_RET(__wt_session_release_btree(session));
/* Make sure we aren't pinning a transaction ID. */
__wt_txn_release_snapshot(session);
WT_RET(__wt_verbose(session, WT_VERB_LSM, "LSM worker checkpointed %s", chunk->uri));
/* Schedule a bloom filter create for our newly flushed chunk. */
if (!FLD_ISSET(lsm_tree->bloom, WT_LSM_BLOOM_OFF))
WT_RET(__wt_lsm_manager_push_entry(session, WT_LSM_WORK_BLOOM, 0, lsm_tree));
else
WT_RET(__wt_lsm_manager_push_entry(session, WT_LSM_WORK_MERGE, 0, lsm_tree));
return 0;
}
/*为chunk创建一个bloom filter*/
static int __lsm_bloom_create(WT_SESSION_IMPL* session, WT_LSM_TREE* lsm_tree, WT_LSM_CHUNK* chunk, u_int chunk_off)
{
WT_BLOOM *bloom;
WT_CURSOR *src;
WT_DECL_RET;
WT_ITEM key;
uint64_t insert_count;
WT_RET(__wt_lsm_tree_setup_bloom(session, lsm_tree, chunk));
bloom = NULL;
++lsm_tree->merge_progressing;
/*创建并初始化一个bloom filter*/
WT_RET(__wt_bloom_create(session, chunk->bloom_uri, lsm_tree->bloom_config, chunk->count,
lsm_tree->bloom_bit_count, lsm_tree->bloom_hash_count, &bloom));
/*构建一个lsm tree cursor*/
WT_ERR(__wt_open_cursor(session, lsm_tree->name, NULL, NULL, &src));
F_SET(src, WT_CURSTD_RAW);
WT_ERR(__wt_clsm_init_merge(src, chunk_off, chunk->id, 1));
F_SET(session, WT_SESSION_NO_CACHE | WT_SESSION_NO_CACHE_CHECK);
/*构建bloom filter数据*/
for (insert_count = 0; (ret = src->next(src)) == 0; insert_count++) {
WT_ERR(src->get_key(src, &key));
WT_ERR(__wt_bloom_insert(bloom, &key));
}
WT_ERR_NOTFOUND_OK(ret);
WT_TRET(src->close(src));
/*将bloom filter写入到session对应的元数据中*/
WT_TRET(__wt_bloom_finalize(bloom));
WT_ERR(ret);
F_CLR(session, WT_SESSION_NO_CACHE);
/*校验新构建的bloom filter是否正确*/
WT_CLEAR(key);
WT_ERR_NOTFOUND_OK(__wt_bloom_get(bloom, &key));
WT_ERR(__wt_verbose(session, WT_VERB_LSM,
"LSM worker created bloom filter %s. Expected %" PRIu64 " items, got %" PRIu64, chunk->bloom_uri, chunk->count, insert_count));
/*写入bloom filter数据*/
WT_ERR(__wt_lsm_tree_writelock(session, lsm_tree));
F_SET(chunk, WT_LSM_CHUNK_BLOOM);
ret = __wt_lsm_meta_write(session, lsm_tree);
++lsm_tree->dsk_gen;
WT_TRET(__wt_lsm_tree_writeunlock(session, lsm_tree));
if (ret != 0)
WT_ERR_MSG(session, ret, "LSM bloom worker metadata write");
err:
if (bloom != NULL)
WT_TRET(__wt_bloom_close(bloom));
F_CLR(session, WT_SESSION_NO_CACHE | WT_SESSION_NO_CACHE_CHECK);
return ret;
}
/*尝试从cache中废弃一个handler对应的数据*/
static int __lsm_discard_handle(WT_SESSION_IMPL *session, const char *uri, const char *checkpoint)
{
WT_RET(__wt_session_get_btree(session, uri, checkpoint, NULL, WT_DHANDLE_EXCLUSIVE | WT_DHANDLE_LOCK_ONLY));
F_SET(session->dhandle, WT_DHANDLE_DISCARD);
return __wt_session_release_btree(session);
}
/*删除掉lsm tree的一个文件*/
static int __lsm_drop_file(WT_SESSION_IMPL* session, const char* uri)
{
WT_DECL_RET;
const char *drop_cfg[] = {
WT_CONFIG_BASE(session, session_drop), "remove_files=false", NULL
};
/*从cache中驱逐已经建立checkpoint的数据*/
WT_RET(__lsm_discard_handle(session, uri, WT_CHECKPOINT));
/*删除元数据*/
WT_WITH_SCHEMA_LOCK(session, ret = __wt_schema_drop(session, uri, drop_cfg));
/*文件删除*/
if (ret == 0)
ret = __wt_remove(session, uri + strlen("file:"));
WT_RET(__wt_verbose(session, WT_VERB_LSM, "Dropped %s", uri));
if (ret == EBUSY || ret == ENOENT)
WT_RET(__wt_verbose(session, WT_VERB_LSM, "LSM worker drop of %s failed with %d", uri, ret));
return ret;
}
/*释放掉old chunks中的空闲chunk*/
int __wt_lsm_free_chunks(WT_SESSION_IMPL *session, WT_LSM_TREE *lsm_tree)
{
WT_DECL_RET;
WT_LSM_CHUNK *chunk;
WT_LSM_WORKER_COOKIE cookie;
u_int i, skipped;
int flush_metadata, drop_ret;
flush_metadata = 0;
/*设置free状态*/
if (!WT_ATOMIC_CAS4(lsm_tree->freeing_old_chunks, 0, 1))
return 0;
/*对old chunks的引用计数进行增加,做占用标识*/
WT_CLEAR(cookie);
WT_RET(__lsm_copy_chunks(session, lsm_tree, &cookie, 1));
for(i = skipped = 0; i < cookie.nchunks; i ++){
chunk = cookie.chunk_array[i];
WT_ASSERT(session, chunk != NULL);
/* Skip the chunk if another worker is using it. 还有其他模块在引用这个chunk,不做释放*/
if (chunk->refcnt > 1) {
++skipped;
continue;
}
if (S2C(session)->hot_backup != 0)
break;
/*如果chunk是一个bloom filter数据,那么直接删除掉对应的bloom filter对应的文件,如果这个文件正在被引用,那么暂时不删除*/
if (F_ISSET(chunk, WT_LSM_CHUNK_BLOOM)) {
drop_ret = __lsm_drop_file(session, chunk->bloom_uri);
if (drop_ret == EBUSY) {
++skipped;
continue;
}
else if (drop_ret != ENOENT)
WT_ERR(drop_ret);
flush_metadata = 1;
F_CLR(chunk, WT_LSM_CHUNK_BLOOM);
}
if (chunk->uri != NULL) {
drop_ret = __lsm_drop_file(session, chunk->uri);
if (drop_ret == EBUSY) {
++skipped;
continue;
}
else if (drop_ret != ENOENT)
WT_ERR(drop_ret);
flush_metadata = 1;
}
/* Lock the tree to clear out the old chunk information. */
WT_ERR(__wt_lsm_tree_writelock(session, lsm_tree));
/*更新old_chunks的状态*/
WT_ASSERT(session, lsm_tree->old_chunks[skipped] == chunk);
__wt_free(session, chunk->bloom_uri);
__wt_free(session, chunk->uri);
__wt_free(session, lsm_tree->old_chunks[skipped]);
/*删除掉chunk在old chunks中的关系*/
if (--lsm_tree->nold_chunks > skipped) {
memmove(lsm_tree->old_chunks + skipped, lsm_tree->old_chunks + skipped + 1, (lsm_tree->nold_chunks - skipped) * sizeof(WT_LSM_CHUNK *));
lsm_tree->old_chunks[lsm_tree->nold_chunks] = NULL;
}
WT_ERR(__wt_lsm_tree_writeunlock(session, lsm_tree));
cookie.chunk_array[i] = NULL;
}
}
| 2.359375 | 2 |
2024-11-18T21:30:05.609354+00:00 | 2021-04-16T22:18:45 | 3d7f77b49265dc9acf31b86c956704dbf5673318 | {
"blob_id": "3d7f77b49265dc9acf31b86c956704dbf5673318",
"branch_name": "refs/heads/master",
"committer_date": "2021-04-16T22:18:45",
"content_id": "df40c5d492cf99749bace1470668a872d38ef6d4",
"detected_licenses": [
"MIT"
],
"directory_id": "e6df22f6948faac67aa3a63d1dfcc11709f1a5c5",
"extension": "c",
"filename": "mergin.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 358728847,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1747,
"license": "MIT",
"license_type": "permissive",
"path": "/mergin.c",
"provenance": "stackv2-0112.json.gz:185077",
"repo_name": "aiquie/mergin",
"revision_date": "2021-04-16T22:18:45",
"revision_id": "45a5e879f545f59fe029bc378b089b07667f6385",
"snapshot_id": "23c3c199ab6f16763f9f280d82d40ed66963936c",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/aiquie/mergin/45a5e879f545f59fe029bc378b089b07667f6385/mergin.c",
"visit_date": "2023-04-16T16:24:06.943352"
} | stackv2 | #include "unifile.h"
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char buff[4096];
int const FDCOUNT = 64;
size_t remove_fd(int fd, int * fds, size_t fdc) {
int res = fdc;
while(fdc && *fds != fd) { ++fds; --fdc; }
if(fdc) { memmove(fds, fds + 1, --fdc * sizeof(fd)); --res; }
return res;
}
int main(int argc, char * const argv[]) {
int opt;
while((opt = getopt(argc, argv, "h")) != -1) {
switch (opt) {
case 'h':
default:
fprintf(stderr, "Usage: %s [FILE]...\n", argv[0]);
fprintf(stderr, "Concatenate FILE(s) to standard output by lines.\n");
fprintf(stderr, "With no FILE, or when FILE is -, read standard input.\n");
return EXIT_FAILURE;
}
}
size_t fdc = 0;
int fds[FDCOUNT];
for(; optind < argc; ++optind) {
if(fdc == FDCOUNT) {
fprintf(stderr, "Error: large number of files defined.\n");
return EXIT_FAILURE;
}
if(!strcmp(argv[optind], "-")) fds[fdc++] = STDIN_FILENO;
else if((fds[fdc++] = open(argv[optind], O_RDWR)) == -1) {
fprintf(stderr, "Error: %s does not open.\n", argv[optind]);
return errno;
}
}
if(!fdc) fds[fdc++] = STDIN_FILENO;
int fd;
while((fd = get_ready(fds, fdc)) != -1) {
int read_size = 0;
while((read_size = read(fd, buff, sizeof(buff))) > 0) {
if(safe_write(STDOUT_FILENO, buff, read_size) == -1) return errno;
if(buff[read_size - 1] == '\n') break;
}
if(read_size == -1) return errno;
if(read_size == 0) fdc = remove_fd(fd, fds, fdc);
}
return EXIT_SUCCESS;
}
| 2.875 | 3 |
2024-11-18T21:30:05.822431+00:00 | 2011-10-17T01:04:28 | 577793f8d7416843f710ca56103340389cb8b721 | {
"blob_id": "577793f8d7416843f710ca56103340389cb8b721",
"branch_name": "refs/heads/master",
"committer_date": "2011-10-17T01:04:28",
"content_id": "996295bd3dddebd8a8f4d3dd254baa72b1dcc512",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "f9ab1811080ca66b8df43ae44f907eb493f0bac6",
"extension": "c",
"filename": "Limbo.C",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 2586499,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1688,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/GUI/Limbo.C",
"provenance": "stackv2-0112.json.gz:185337",
"repo_name": "kylegibson/yloponom",
"revision_date": "2011-10-17T01:04:28",
"revision_id": "a1904529d58c5d39c50a3eebdd1589588d4d02ed",
"snapshot_id": "24e73bafb5e83349628ebf569960bb6bfd9c13b7",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/kylegibson/yloponom/a1904529d58c5d39c50a3eebdd1589588d4d02ed/GUI/Limbo.C",
"visit_date": "2021-01-18T14:00:10.809105"
} | stackv2 | /////////////////////////////////////////////////////////////////////////////////////////////////
//
// YLOPONOM
//
// CS3141 - Spring 2006
// Group 7
// Michael Hyde, Nick Quaderer, Will Pratt, Kyle Gibson
//
// GUI - This file contains the code for structuring the GUI for Yloponom
/////////////////////////////////////////////////////////////////////////////////////////////////
#include "Limbo.h"
#include "network/GameState.h"
#include <qpushbutton.h>
#include <qlabel.h>
#include <qlayout.h>
#include <iostream>
Limbo::Limbo(QWidget *parent, const char *name )
: QWidget( parent, name )
{
setFixedSize(200,200);
QVBoxLayout * layout = new QVBoxLayout(this, 5, 5);
_msg = new QLabel("Waiting for players to join...", this);
_msg->setAlignment(Qt::AlignCenter);
layout->addWidget(_msg);
_start = new QPushButton("Start Game Now!", this);
_start->setHidden(true);
_start->setEnabled(false);
_start->setFixedWidth(150);
layout->addWidget(_start, 0, Qt::AlignHCenter);
layout->addSpacing(50);
}
void Limbo::enable_first_player()
{
// unhide the start button :)
_start->setHidden(false);
//_start->setEnabled(true);
// setup connection
connect(_start, SIGNAL(clicked()), this, SLOT(start_pushed()));
}
void Limbo::start_pushed()
{
emit start_the_game_now();
}
void Limbo::game_state_updated(net::GameState * state)
{
if(state->get_player_count() == 0) {
_msg->setText("Waiting for players to join...");
} else {
if( state->get_player_count() == 1 ) {
_start->setEnabled(false);
} else {
_start->setEnabled(true);
}
_msg->setText(QString("There are ") + QString::number(state->get_player_count()) + QString(" players connected.") );
}
}
| 2.34375 | 2 |
2024-11-18T21:30:07.231094+00:00 | 2023-07-12T00:17:20 | 23dec57d59a7a77c48228538997a7b49df781dbf | {
"blob_id": "23dec57d59a7a77c48228538997a7b49df781dbf",
"branch_name": "refs/heads/master",
"committer_date": "2023-07-12T00:17:20",
"content_id": "af9fcd07c207f304fe352c39ba8be7cad5533b97",
"detected_licenses": [
"MIT"
],
"directory_id": "468a6ba4385730b649f2ec0e1e671bdef511110b",
"extension": "c",
"filename": "exemplo_fila_de_prioridade_cantina.c",
"fork_events_count": 7,
"gha_created_at": "2016-07-08T17:53:05",
"gha_event_created_at": "2022-09-30T14:48:40",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 62906945,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1862,
"license": "MIT",
"license_type": "permissive",
"path": "/examples/exemplo_fila_de_prioridade_cantina.c",
"provenance": "stackv2-0112.json.gz:185596",
"repo_name": "danielsaad/EDA-IFB-CC",
"revision_date": "2023-07-12T00:17:20",
"revision_id": "00108100bfa5306330c7f61ff94d96457ddcba12",
"snapshot_id": "c482d2136c5bb0f2971ce3fafbcb480c0f9cab50",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/danielsaad/EDA-IFB-CC/00108100bfa5306330c7f61ff94d96457ddcba12/examples/exemplo_fila_de_prioridade_cantina.c",
"visit_date": "2023-07-31T11:32:52.889304"
} | stackv2 | #include <stdio.h>
#include <string.h>
#include "generic_priority_queue.h"
#include "alloc.h"
typedef struct pessoa{
char nome[30];
int professor;
char curso[30];
}pessoa;
void* construtor_pessoa(void* dado){
pessoa* ptr = mallocx(sizeof(pessoa));
memcpy(ptr,dado,sizeof(pessoa));
return ptr;
}
void destructor_pessoa(void* data){
free(data);
}
int comparator_pessoa(const void* a, const void* b){
const pessoa *p1,*p2;
p1 = a;
p2 = b;
if(p1->professor == p2->professor){
return 0;
}
if(p1->professor){
return 1;
}
return -1;
}
void le_pessoa(pessoa* p){
printf("Nome: ");
scanf("%s",p->nome);
printf("É professor? (1 para sim 0 para não): ");
scanf("%d",&(p->professor));
printf("Curso: ");
scanf("%s",p->curso);
}
void insere_pessoa(generic_priority_queue_t* pq,pessoa* p){
generic_priority_queue_push(pq,p);
}
void atende_pessoa(generic_priority_queue_t* pq){
pessoa p = *(pessoa*) generic_priority_queue_front(pq);
printf("Atendendo pessoa.\n");
printf("Nome = %s\n",p.nome);
printf("Professor = %d\n",p.professor);
printf("Curso = %s\n",p.curso);
generic_priority_queue_pop(pq);
}
int main(void){
generic_priority_queue_t* fila_de_prioridade;
generic_priority_queue_initialize(&fila_de_prioridade,
construtor_pessoa,
destructor_pessoa,
comparator_pessoa);
while(1){
int opcao;
printf("1) Inserir pessoa na fila.\n");
printf("2) Atender uma pessoa.\n");
printf("Tia sandra, qual é a opção: ");
scanf("%d",&opcao);
if(opcao==1){
pessoa p;
le_pessoa(&p);
insere_pessoa(fila_de_prioridade,&p);
}
else{
atende_pessoa(fila_de_prioridade);
}
}
return 0;
}
| 3.671875 | 4 |
2024-11-18T21:30:07.702149+00:00 | 2015-08-19T00:36:19 | 1da8b8685a8c8fbf34c3b7e59b36ebb8cbffe0c7 | {
"blob_id": "1da8b8685a8c8fbf34c3b7e59b36ebb8cbffe0c7",
"branch_name": "refs/heads/master",
"committer_date": "2015-08-19T00:36:19",
"content_id": "69a0649a97c607d31b7b33cd2cd1bbe758810d14",
"detected_licenses": [
"MIT"
],
"directory_id": "bf4b027def213a507f00f2b32ef9b61d14f6f249",
"extension": "c",
"filename": "test_list.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 32193266,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 402,
"license": "MIT",
"license_type": "permissive",
"path": "/Lab 9/test_list.c",
"provenance": "stackv2-0112.json.gz:185726",
"repo_name": "brandonlee503/Intro-to-Programming-II-Labs",
"revision_date": "2015-08-19T00:36:19",
"revision_id": "a542783cc0566cc42d64c8e7012c4f67f6fff083",
"snapshot_id": "8ba912b1043c92487ed37ca498dd6677153c55da",
"src_encoding": "WINDOWS-1250",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/brandonlee503/Intro-to-Programming-II-Labs/a542783cc0566cc42d64c8e7012c4f67f6fff083/Lab 9/test_list.c",
"visit_date": "2020-04-14T14:05:25.329259"
} | stackv2 | #include "list.h"
#include <stdio.h>
#include <stdlib.h>
int main (){
char ans;
int num;
struct node *head = NULL;
do {
printf("Enter a number: ");
scanf("%d", &num);
push(&head, num); //Change push to append…
printf("Do you want another num (y or n): "); //printf = cout
scanf("%1s",&ans); //scanf = cin
} while(ans=='y');
print(head, length(head));
return 0;
} | 2.984375 | 3 |
2024-11-18T21:30:07.867593+00:00 | 2021-07-09T06:47:09 | 93f582783d956e4eca3cd53a9832f94be4561c16 | {
"blob_id": "93f582783d956e4eca3cd53a9832f94be4561c16",
"branch_name": "refs/heads/master",
"committer_date": "2021-07-09T06:47:09",
"content_id": "9bb007e1139ac670676570cc85877fb088b6c5cb",
"detected_licenses": [
"MIT"
],
"directory_id": "158bc8098869730952950746cc154000bfb00ef1",
"extension": "c",
"filename": "bench.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 384336339,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2433,
"license": "MIT",
"license_type": "permissive",
"path": "/bench.c",
"provenance": "stackv2-0112.json.gz:185990",
"repo_name": "ashwin-mittal/Customized-Xv6-Operating-System",
"revision_date": "2021-07-09T06:47:09",
"revision_id": "f3a641f774ce69f589e3d45e260ea29559765c49",
"snapshot_id": "7638e3bcd35222048348d22ae0819e0965ac3b34",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ashwin-mittal/Customized-Xv6-Operating-System/f3a641f774ce69f589e3d45e260ea29559765c49/bench.c",
"visit_date": "2023-06-16T08:40:23.038653"
} | stackv2 | #include "types.h"
#include "user.h"
int number_of_processes = 10;
int main(int argc, char *argv[]) {
int j;
for (j = 0; j < number_of_processes; j++) {
int pid = fork();
if (pid < 0) {
printf(1, "Fork failed\n");
continue;
}
if (pid == 0) {
volatile int i;
for (volatile int k = 0; k < number_of_processes; k++) {
if (k <= j) {
sleep(200); //io time
} else {
for (i = 0; i < 100000000; i++) {
; //cpu time
}
}
}
// printf(1, "Process: %d Finished\n", j);
exit();
} else {
set_priority(100 - (20 + j), pid); // will only matter for PBS, comment it out if not implemented yet (better priorty for more IO intensive jobs)
}
}
int wtime = 0, rtime = 0;
for (j = 0; j < number_of_processes; j++) {
int w, c;
waitx(&w, &c);
wtime += w;
rtime += c;
}
printf(1, "WAITING TIME: %d\nCPU TIME: %d\n", wtime, rtime);
exit();
}
//#include "types.h"
//#include "stat.h"
//#include "user.h"
//#include "fcntl.h"
//
//int main(int argc, char *argv[]) {
// int pid, n = 8, limit = 3e8;
// double x = 0, z;
// x = 0;
// pid = 0;
// for (int k = 0; k < n; k++) {
// pid = fork();
// if (pid < 0) {
// printf(1, "%d failed in fork!\n", getpid());
// }
// if (pid == 0) { // child
// for (z = 0; z < limit; z += 1)
// x = x + 3.14 * 89.64; // useless calculations to consume CPU time
// exit();
// }
// }
// for (int k = 0; k < n; k++) {
// wait();
// }
// exit();
//}
//_______________________________________________
//RR
//WAITING TIME: 16451
//CPU TIME : 2701
//FCFS
//WAITING TIME: 20959
//CPU TIME : 1862
//PBS
//WAITING TIME: 11668
//CPU TIME : 3714
//MLFQ
//WAITING TIME: 12162
//CPU TIME : 3069
//_______________________________________________
//PBS
// WAITING TIME: 4045
// CPU TIME : 1809
//MLFQ
// WAITING TIME: 10974
// CPU TIME : 1762
//FCFS
// WAITING TIME: 11879
// CPU TIME : 1866
//RR
// WAITING TIME: 11471
// CPU TIME : 1970
//MLFQ (IMPROVED)
// WAITING TIME: 3734
// CPU TIME : 1811
//_______________________________________________
| 2.53125 | 3 |
2024-11-18T21:30:09.061963+00:00 | 2021-05-04T01:52:06 | 4e56902732c942c49176ef8c4cf9616336efeb4f | {
"blob_id": "4e56902732c942c49176ef8c4cf9616336efeb4f",
"branch_name": "refs/heads/master",
"committer_date": "2021-05-04T01:52:06",
"content_id": "56b7803dd833a3437115186d1bc8c248d7cc8c77",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "e57cfff17fee2ecb480d3c71d96c1a23e0acf6b7",
"extension": "c",
"filename": "TestWebOSLocale_C.c",
"fork_events_count": 2,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 125007697,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 34066,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/test/TestWebOSLocale_C.c",
"provenance": "stackv2-0112.json.gz:186762",
"repo_name": "webosose/libwebosi18n",
"revision_date": "2021-05-04T01:52:06",
"revision_id": "3e757518ad9fa280a0cb12aca8248da912052b8b",
"snapshot_id": "5bf53b98474b174b5941bcfbe46de4299756aba1",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/webosose/libwebosi18n/3e757518ad9fa280a0cb12aca8248da912052b8b/test/TestWebOSLocale_C.c",
"visit_date": "2023-06-02T04:13:47.711264"
} | stackv2 | // Copyright (c) 2013-2018 LG Electronics, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// SPDX-License-Identifier: Apache-2.0
/*
* TestWebOSLocale_C.c
*
* Created on: Oct 29, 2013
* Author: oleksandr.gorbunov
*/
#include "TestWebOSLocale_C.h"
#include "webosi18n/c/WebOSLocale_C.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <time.h>
size_t webosC_failures_count = 0;
bool assertNotNull(WebOSLocaleC* locale, const char* methodName) {
if (!locale) {
printf("\nTEST_FAILED testname = %s TestWebOSLocale_C locale is NULL\n", methodName);
webosC_failures_count++;
return false;
}
return true;
}
void assertEquals(const char* current, const char* expected, const char* method_name) {
if (strcmp(expected, current) != 0) {
printf("\nTEST_FAILED testname = %s TestWebOSLocale_C locale is NULL\n", method_name);
printf("\n Expetcted = %s, actual: %s\n", expected, current);
webosC_failures_count++;
}
}
void assertTrue(bool value, const char* method_name) {
if (!value) {
printf("\nTEST_FAILED testname = %s TestWebOSLocale_C locale is NULL\n", method_name);
printf("\n Expetcted value: true\n");
webosC_failures_count++;
}
}
void assertFalse(bool value, const char* method_name) {
if (value) {
printf("\nTEST_FAILED testname = %s TestWebOSLocale_C locale is NULL\n", method_name);
printf("\n Expetcted value: false\n");
webosC_failures_count++;
}
}
void testWebOSLocaleCConstructorSpec()
{
WebOSLocaleC* loc = webOSLocale_create("en-US");
if (!assertNotNull(loc, "testWebOSLocaleCConstructorSpec")) return;
webOSLocale_destroy(loc);
}
void testWebOSLocaleCConstructorParts()
{
WebOSLocaleC* loc = webOSLocale_createByParts("en", "US", "Latn", "govnt");
if (!assertNotNull(loc, "testWebOSLocaleCConstructorParts")) return;
webOSLocale_destroy(loc);
}
void testWebOSLocaleCGetLanguage()
{
WebOSLocaleC* loc = webOSLocale_create("en-US");
if (!assertNotNull(loc, "testWebOSLocaleCGetLanguage")) return;
assertEquals(webOSLocale_GetLanguage(loc), "en", "testWebOSLocaleCGetLanguage");
webOSLocale_destroy(loc);
}
void testWebOSLocaleCGetLanguage2LowerChars()
{
WebOSLocaleC* loc = webOSLocale_create("de-AU");
if (!assertNotNull(loc, "testWebOSLocaleCGetLanguage2LowerChars")) return;
assertEquals(webOSLocale_GetLanguage(loc), "de", "testWebOSLocaleCGetLanguage2LowerChars");
webOSLocale_destroy(loc);
}
void testWebOSLocaleCGetLanguage3LowerChars()
{
WebOSLocaleC* loc = webOSLocale_create("ger-Latn");
if (!assertNotNull(loc, "testWebOSLocaleCGetLanguage3LowerChars")) return;
assertEquals(webOSLocale_GetLanguage(loc), "ger", "testWebOSLocaleCGetLanguage3LowerChars");
webOSLocale_destroy(loc);
}
void testWebOSLocaleCGetLanguageNonDigit()
{
WebOSLocaleC* loc = webOSLocale_create("ru3-RU");
if (!assertNotNull(loc, "testWebOSLocaleCGetLanguage")) return;
assertEquals(webOSLocale_GetLanguage(loc), "", "testWebOSLocaleCGetLanguage");
webOSLocale_destroy(loc);
}
void testWebOSLocaleCGetLanguageParts()
{
WebOSLocaleC* loc = webOSLocale_createByParts("en", "US", "Latn", "govnt");
if (!assertNotNull(loc, "testWebOSLocaleCGetLanguageParts")) return;
assertEquals(webOSLocale_GetLanguage(loc), "en", "testWebOSLocaleCGetLanguageParts");
webOSLocale_destroy(loc);
}
void testWebOSLocaleCGetRegion()
{
WebOSLocaleC* loc = webOSLocale_create("en-US");
if (!assertNotNull(loc, "testWebOSLocaleCGetRegion")) return;
assertEquals(webOSLocale_GetRegion(loc), "US", "testWebOSLocaleCGetRegion");
webOSLocale_destroy(loc);
}
void testWebOSLocaleCGetRegionParts()
{
WebOSLocaleC* loc = webOSLocale_createByParts("en", "US", "Latn", "govnt");
if (!assertNotNull(loc, "testWebOSLocaleCGetLanguageParts")) return;
assertEquals(webOSLocale_GetRegion(loc), "US", "testWebOSLocaleCGetLanguageParts");
webOSLocale_destroy(loc);
}
void testWebOSLocaleCGetScript()
{
WebOSLocaleC* loc = webOSLocale_create("en-US-Latn");
if (!assertNotNull(loc, "testWebOSLocaleCGetScript")) return;
assertEquals(webOSLocale_GetScript(loc), "Latn", "testWebOSLocaleCGetScript");
webOSLocale_destroy(loc);
}
void testWebOSLocaleCGetScriptParts()
{
WebOSLocaleC* loc = webOSLocale_createByParts("en", "US", "Latn", "govnt");
if (!assertNotNull(loc, "testWebOSLocaleCGetLanguageParts")) return;
assertEquals(webOSLocale_GetScript(loc), "Latn", "testWebOSLocaleCGetLanguageParts");
webOSLocale_destroy(loc);
}
void testWebOSLocaleCGetVariant()
{
WebOSLocaleC* loc = webOSLocale_create("en-US-govnt");
if (!assertNotNull(loc, "testWebOSLocaleCGetVariant")) return;
assertEquals(webOSLocale_GetVariant(loc), "govnt", "testWebOSLocaleCGetVariant");
webOSLocale_destroy(loc);
}
void testWebOSLocaleCGetVariantParts()
{
WebOSLocaleC* loc = webOSLocale_createByParts("en", "US", "Latn", "govnt");
if (!assertNotNull(loc, "testWebOSLocaleCGetVariantParts")) return;
assertEquals(webOSLocale_GetVariant(loc), "govnt", "testWebOSLocaleCGetVariantParts");
webOSLocale_destroy(loc);
}
void testWebOSLocaleCGetOutOfOrder()
{
WebOSLocaleC* loc = webOSLocale_create("US-govnt-en-Latn");
if (!assertNotNull(loc, "testWebOSLocaleCGetOutOfOrder")) return;
assertEquals(webOSLocale_GetLanguage(loc), "en", "testWebOSLocaleCGetOutOfOrder");
assertEquals(webOSLocale_GetScript(loc), "Latn", "testWebOSLocaleCGetOutOfOrder");
assertEquals(webOSLocale_GetRegion(loc), "US", "testWebOSLocaleCGetOutOfOrder");
assertEquals(webOSLocale_GetVariant(loc), "govnt", "testWebOSLocaleCGetOutOfOrder");
webOSLocale_destroy(loc);
}
void testWebOSLocaleCGetLanguageSpecEmpty()
{
WebOSLocaleC* loc = webOSLocale_create("");
if (!assertNotNull(loc, "testWebOSLocaleCGetLanguageSpecEmpty")) return;
assertEquals(webOSLocale_GetLanguage(loc), "", "testWebOSLocaleCGetLanguageSpecEmpty");
webOSLocale_destroy(loc);
}
void testWebOSLocaleCGetRegionSpecEmpty()
{
WebOSLocaleC* loc = webOSLocale_create("");
if (!assertNotNull(loc, "testWebOSLocaleCGetRegionSpecEmpty")) return;
assertEquals(webOSLocale_GetRegion(loc), "", "testWebOSLocaleCGetRegionSpecEmpty");
webOSLocale_destroy(loc);
}
void testWebOSLocaleCGetScriptSpecEmpty()
{
WebOSLocaleC* loc = webOSLocale_create("");
if (!assertNotNull(loc, "testWebOSLocaleCGetScriptSpecEmpty")) return;
assertEquals(webOSLocale_GetScript(loc), "", "testWebOSLocaleCGetScriptSpecEmpty");
webOSLocale_destroy(loc);
}
void testWebOSLocaleCGetVariantSpecEmpty()
{
WebOSLocaleC* loc = webOSLocale_create("");
if (!assertNotNull(loc, "testWebOSLocaleCGetVariantSpecEmpty")) return;
assertEquals(webOSLocale_GetVariant(loc), "", "testWebOSLocaleCGetVariantSpecEmpty");
webOSLocale_destroy(loc);
}
void testWebOSLocaleCGetLanguageSpecMissing()
{
WebOSLocaleC* loc = webOSLocale_create("-US-govt");
if (!assertNotNull(loc, "testWebOSLocaleCGetLanguageSpecMissing")) return;
assertEquals(webOSLocale_GetLanguage(loc), "", "testWebOSLocaleCGetLanguageSpecMissing");
webOSLocale_destroy(loc);
}
void testWebOSLocaleCGetRegionSpecMissing()
{
WebOSLocaleC* loc = webOSLocale_create("en--govt");
if (!assertNotNull(loc, "testWebOSLocaleCGetRegionSpecMissing")) return;
assertEquals(webOSLocale_GetRegion(loc), "", "testWebOSLocaleCGetRegionSpecMissing");
webOSLocale_destroy(loc);
}
void testWebOSLocaleCGetRegionSpecOnlyLang()
{
WebOSLocaleC* loc = webOSLocale_create("en");
if (!assertNotNull(loc, "testWebOSLocaleCGetRegionSpecOnlyLang")) return;
assertEquals(webOSLocale_GetRegion(loc), "", "testWebOSLocaleCGetRegionSpecOnlyLang");
webOSLocale_destroy(loc);
}
void testWebOSLocaleCGetVariantSpecOnlyLangAndReg()
{
WebOSLocaleC* loc = webOSLocale_create("en-US");
if (!assertNotNull(loc, "testWebOSLocaleCGetVariantSpecOnlyLangAndReg")) return;
assertEquals(webOSLocale_GetVariant(loc), "", "testWebOSLocaleCGetVariantSpecOnlyLangAndReg");
webOSLocale_destroy(loc);
}
void testWebOSLocaleCGetVariantSpecMissing()
{
WebOSLocaleC* loc = webOSLocale_create("en-US-");
if (!assertNotNull(loc, "testWebOSLocaleCGetVariantSpecMissing")) return;
assertEquals(webOSLocale_GetVariant(loc), "", "testWebOSLocaleCGetVariantSpecMissing");
webOSLocale_destroy(loc);
}
void testWebOSLocaleCGetLanguageEmptySpecMissing()
{
WebOSLocaleC* loc = webOSLocale_create("");
if (!assertNotNull(loc, "testWebOSLocaleCGetLanguageSpecNull")) return;
assertEquals(webOSLocale_GetLanguage(loc), "", "testWebOSLocaleCGetLanguageSpecNull");
webOSLocale_destroy(loc);
}
void testWebOSLocaleCGetRegionEmptySpecEmpty()
{
WebOSLocaleC* loc = webOSLocale_create("");
if (!assertNotNull(loc, "testWebOSLocaleCGetRegionEmptySpecEmpty")) return;
assertEquals(webOSLocale_GetRegion(loc), "", "testWebOSLocaleCGetRegionEmptySpecEmpty");
webOSLocale_destroy(loc);
}
void testWebOSLocaleCGetVariantEmptySpecEmpty()
{
WebOSLocaleC* loc = webOSLocale_create("");
if (!assertNotNull(loc, "testWebOSLocaleCGetVariantEmptySpecEmpty")) return;
assertEquals(webOSLocale_GetVariant(loc), "", "testWebOSLocaleCGetVariantEmptySpecEmpty");
webOSLocale_destroy(loc);
}
void testWebOSLocaleCGetLanguagePartsEmpty()
{
WebOSLocaleC* loc = webOSLocale_createByParts("", "US", "Latn", "govnt");
if (!assertNotNull(loc, "testWebOSLocaleCGetLanguagePartsEmpty")) return;
assertEquals(webOSLocale_GetLanguage(loc), "", "testWebOSLocaleCGetLanguagePartsEmpty");
webOSLocale_destroy(loc);
}
void testWebOSLocaleCGetRegionPartsEmpty()
{
WebOSLocaleC* loc = webOSLocale_createByParts("en", "", "Latn", "govnt");
if (!assertNotNull(loc, "testWebOSLocaleCGetRegionPartsEmpty")) return;
assertEquals(webOSLocale_GetRegion(loc), "", "testWebOSLocaleCGetRegionPartsEmpty");
webOSLocale_destroy(loc);
}
void testWebOSLocaleCGetScriptPartsEmpty()
{
WebOSLocaleC* loc = webOSLocale_createByParts("en", "US", "", "govnt");
if (!assertNotNull(loc, "testWebOSLocaleCGetScriptPartsEmpty")) return;
assertEquals(webOSLocale_GetScript(loc), "", "testWebOSLocaleCGetScriptPartsEmpty");
webOSLocale_destroy(loc);
}
void testWebOSLocaleCGetVariantPartsEmpty()
{
WebOSLocaleC* loc = webOSLocale_createByParts("en", "US", "Latn", "");
if (!assertNotNull(loc, "testWebOSLocaleCGetVariantPartsEmpty")) return;
assertEquals(webOSLocale_GetVariant(loc), "", "testWebOSLocaleCGetVariantPartsEmpty");
webOSLocale_destroy(loc);
}
void testWebOSLocaleCGetLanguageOldISOCodes1()
{
WebOSLocaleC* loc = webOSLocale_create("he-IL");
if (!assertNotNull(loc, "testWebOSLocaleCGetLanguageOldISOCodes1")) return;
assertEquals(webOSLocale_GetLanguage(loc), "he", "testWebOSLocaleCGetLanguageOldISOCodes1");
webOSLocale_destroy(loc);
}
void testWebOSLocaleCGetLanguageOldISOCodes2()
{
WebOSLocaleC* loc = webOSLocale_create("yi");
if (!assertNotNull(loc, "testWebOSLocaleCGetLanguageOldISOCodes2")) return;
assertEquals(webOSLocale_GetLanguage(loc), "yi", "testWebOSLocaleCGetLanguageOldISOCodes2");
webOSLocale_destroy(loc);
}
void testWebOSLocaleCGetLanguageOldISOCodes3()
{
WebOSLocaleC* loc = webOSLocale_create("id-ID");
if (!assertNotNull(loc, "testWebOSLocaleCGetLanguageOldISOCodes3")) return;
assertEquals(webOSLocale_GetLanguage(loc), "id", "testWebOSLocaleCGetLanguageOldISOCodes3");
webOSLocale_destroy(loc);
}
void testWebOSLocaleCIsPseudoTrue()
{
WebOSLocaleC* loc = webOSLocale_create("zxx-XX");
if (!assertNotNull(loc, "testWebOSLocaleCIsPseudoTrue")) return;
assertTrue(webOSLocale_IsPseudo(loc), "testWebOSLocaleCIsPseudoTrue");
webOSLocale_destroy(loc);
}
void testWebOSLocaleCIsPseudoFalse()
{
WebOSLocaleC* loc = webOSLocale_create("uk-UA");
if (!assertNotNull(loc, "testWebOSLocaleCIsPseudoFalse")) return;
assertFalse(webOSLocale_IsPseudo(loc), "testWebOSLocaleCIsPseudoFalse");
webOSLocale_destroy(loc);
}
void testWebOSLocaleCGetSpec()
{
WebOSLocaleC* loc = webOSLocale_createByParts("en", "US", "Latn", "govnt");
if (!assertNotNull(loc, "testWebOSLocaleCGetSpec")) return;
assertEquals(webOSLocale_ToString(loc), "en-Latn-US-govnt", "testWebOSLocaleCGetSpec");
webOSLocale_destroy(loc);
}
void testWebOSLocaleCGetSpecPartsMissing()
{
WebOSLocaleC* loc = webOSLocale_createByParts("en", "", "Latn", "govnt");
if (!assertNotNull(loc, "testWebOSLocaleCGetSpecPartsMissing")) return;
assertEquals(webOSLocale_ToString(loc), "en-Latn-govnt", "testWebOSLocaleCGetSpecPartsMissing");
webOSLocale_destroy(loc);
}
void testWebOSLocaleCGetSpecNoVariant()
{
WebOSLocaleC* loc = webOSLocale_createByParts("en", "US", "Latn", "");
if (!assertNotNull(loc, "testWebOSLocaleCGetSpecNoVariant")) return;
assertEquals(webOSLocale_ToString(loc), "en-Latn-US", "testWebOSLocaleCGetSpecNoVariant");
webOSLocale_destroy(loc);
}
void testWebOSLocaleCGetSpecRearrange()
{
WebOSLocaleC* loc = webOSLocale_create("US-en-GOVERNMT-Latn");
if (!assertNotNull(loc, "testWebOSLocaleCGetSpecRearrange")) return;
assertEquals(webOSLocale_ToString(loc), "en-Latn-US-GOVERNMT", "testWebOSLocaleCGetSpecRearrange");
webOSLocale_destroy(loc);
}
void testWebOSLocaleCEquals()
{
WebOSLocaleC* loc1 = webOSLocale_create("en-US-Latn-govnt");
WebOSLocaleC* loc2 = webOSLocale_createByParts("en", "US", "Latn", "govnt");
if (!assertNotNull(loc1, "testWebOSLocaleCEquals")) return;
if (!assertNotNull(loc2, "testWebOSLocaleCEquals")) return;
assertTrue(webOSLocale_EqualsObject(loc1, loc2), "testWebOSLocaleCEquals");
webOSLocale_destroy(loc1);
webOSLocale_destroy(loc2);
}
void testWebOSLocaleCEqualsSymmetric()
{
WebOSLocaleC* loc1 = webOSLocale_create("en-US-Latn-govnt");
WebOSLocaleC* loc2 = webOSLocale_createByParts("en", "US", "Latn", "govnt");
if (!assertNotNull(loc1, "testWebOSLocaleCEqualsSymmetric")) return;
if (!assertNotNull(loc2, "testWebOSLocaleCEqualsSymmetric")) return;
assertTrue(webOSLocale_EqualsObject(loc2, loc1), "testWebOSLocaleCEqualsSymmetric");
webOSLocale_destroy(loc1);
webOSLocale_destroy(loc2);
}
void testWebOSLocaleCNotEquals()
{
WebOSLocaleC* loc1 = webOSLocale_create("de-DE");
WebOSLocaleC* loc2 = webOSLocale_createByParts("en", "US", "Latn", "govnt");
if (!assertNotNull(loc1, "testWebOSLocaleCNotEquals")) return;
if (!assertNotNull(loc2, "testWebOSLocaleCNotEquals")) return;
assertFalse(webOSLocale_EqualsObject(loc1, loc2), "testWebOSLocaleCEqualsSymmetric");
webOSLocale_destroy(loc1);
webOSLocale_destroy(loc2);
}
void testWebOSLocaleCNotEqualsClose()
{
WebOSLocaleC* loc1 = webOSLocale_create("de-DE-govnt");
WebOSLocaleC* loc2 = webOSLocale_createByParts("en", "US", "Latn", "govnt");
if (!assertNotNull(loc1, "testWebOSLocaleCNotEqualsClose")) return;
if (!assertNotNull(loc2, "testWebOSLocaleCNotEqualsClose")) return;
assertFalse(webOSLocale_EqualsObject(loc1, loc2), "testWebOSLocaleCNotEqualsClose");
webOSLocale_destroy(loc1);
webOSLocale_destroy(loc2);
}
void testWebOSLocaleCEqualsNull()
{
WebOSLocaleC* loc1 = webOSLocale_create("en-US-govnt");
WebOSLocaleC* loc2 = NULL;
if (!assertNotNull(loc1, "testWebOSLocaleCEqualsNull")) return;
assertFalse(webOSLocale_EqualsObject(loc1, loc2), "testWebOSLocaleCEqualsNull");
webOSLocale_destroy(loc1);
webOSLocale_destroy(loc2);
}
void testWebOSLocaleCEqualsMissingParts()
{
WebOSLocaleC* loc1 = webOSLocale_create("en-US-govnt");
WebOSLocaleC* loc2 = webOSLocale_createByParts("en", "US", "", "");
if (!assertNotNull(loc1, "testWebOSLocaleCEqualsMissingParts")) return;
if (!assertNotNull(loc2, "testWebOSLocaleCEqualsMissingParts")) return;
assertFalse(webOSLocale_EqualsObject(loc1, loc2), "testWebOSLocaleCEqualsMissingParts");
webOSLocale_destroy(loc1);
webOSLocale_destroy(loc2);
}
void testWebOSLocaleCEqualsBothMissingParts()
{
WebOSLocaleC* loc1 = webOSLocale_create("en-US");
WebOSLocaleC* loc2 = webOSLocale_createByParts("en", "US", "", "");
if (!assertNotNull(loc1, "testWebOSLocaleCEqualsBothMissingParts")) return;
if (!assertNotNull(loc2, "testWebOSLocaleCEqualsBothMissingParts")) return;
assertTrue(webOSLocale_EqualsObject(loc1, loc2), "testWebOSLocaleCEqualsBothMissingParts");
webOSLocale_destroy(loc1);
webOSLocale_destroy(loc2);
}
void testWebOSLocaleCIsCompatibleWithSelf()
{
WebOSLocaleC* loc1 = webOSLocale_create("en-US");
if (!assertNotNull(loc1, "testWebOSLocaleCIsCompatibleWithSelf")) return;
assertTrue(webOSLocale_IsCompatibleWith(loc1, loc1), "testWebOSLocaleCIsCompatibleWithSelf");
webOSLocale_destroy(loc1);
}
void testWebOSLocaleCIsCompatibleWithEqual()
{
WebOSLocaleC* loc1 = webOSLocale_create("en-US");
WebOSLocaleC* loc2 = webOSLocale_create("en-US");
if (!assertNotNull(loc1, "testWebOSLocaleCIsCompatibleWithEqual")) return;
if (!assertNotNull(loc2, "testWebOSLocaleCIsCompatibleWithEqual")) return;
assertTrue(webOSLocale_IsCompatibleWith(loc1, loc2), "testWebOSLocaleCIsCompatibleWithEqual");
webOSLocale_destroy(loc1);
webOSLocale_destroy(loc2);
}
void testWebOSLocaleCIsCompatibleWithParentWithRegion()
{
WebOSLocaleC* loc1 = webOSLocale_create("en-US-govnt");
WebOSLocaleC* loc2 = webOSLocale_create("en-US");
if (!assertNotNull(loc1, "testWebOSLocaleCIsCompatibleWithParentWithRegion")) return;
if (!assertNotNull(loc2, "testWebOSLocaleCIsCompatibleWithParentWithRegion")) return;
assertTrue(webOSLocale_IsCompatibleWith(loc1, loc2), "testWebOSLocaleCIsCompatibleWithParentWithRegion");
webOSLocale_destroy(loc1);
webOSLocale_destroy(loc2);
}
void testWebOSLocaleCIsCompatibleWithParentWithLanguage()
{
WebOSLocaleC* loc1 = webOSLocale_create("en-US");
WebOSLocaleC* loc2 = webOSLocale_create("en");
if (!assertNotNull(loc1, "testWebOSLocaleCIsCompatibleWithParentWithLanguage")) return;
if (!assertNotNull(loc2, "testWebOSLocaleCIsCompatibleWithParentWithLanguage")) return;
assertTrue(webOSLocale_IsCompatibleWith(loc1, loc2), "testWebOSLocaleCIsCompatibleWithParentWithLanguage");
webOSLocale_destroy(loc1);
webOSLocale_destroy(loc2);
}
void testWebOSLocaleCIsCompatibleWithParentWithRoot()
{
WebOSLocaleC* loc1 = webOSLocale_create("en");
WebOSLocaleC* loc2 = webOSLocale_create("");
if (!assertNotNull(loc1, "testWebOSLocaleCIsCompatibleWithParentWithRoot")) return;
if (!assertNotNull(loc2, "testWebOSLocaleCIsCompatibleWithParentWithRoot")) return;
assertTrue(webOSLocale_IsCompatibleWith(loc1, loc2), "testWebOSLocaleCIsCompatibleWithParentWithRoot");
webOSLocale_destroy(loc1);
webOSLocale_destroy(loc2);
}
void testWebOSLocaleCIsCompatibleWithGrandFather()
{
WebOSLocaleC* loc1 = webOSLocale_create("en-US-govnt");
WebOSLocaleC* loc2 = webOSLocale_create("en");
if (!assertNotNull(loc1, "testWebOSLocaleCIsCompatibleWithGrandFather")) return;
if (!assertNotNull(loc2, "testWebOSLocaleCIsCompatibleWithGrandFather")) return;
assertTrue(webOSLocale_IsCompatibleWith(loc1, loc2), "testWebOSLocaleCIsCompatibleWithGrandFather");
webOSLocale_destroy(loc1);
webOSLocale_destroy(loc2);
}
void testWebOSLocaleCIsCompatibleWithGreatGrandFather2()
{
WebOSLocaleC* loc1 = webOSLocale_create("en-US-Latn-govnt");
WebOSLocaleC* loc2 = webOSLocale_create("en");
if (!assertNotNull(loc1, "testWebOSLocaleCIsCompatibleWithGreatGrandFather2")) return;
if (!assertNotNull(loc2, "testWebOSLocaleCIsCompatibleWithGreatGrandFather2")) return;
assertTrue(webOSLocale_IsCompatibleWith(loc1, loc2), "testWebOSLocaleCIsCompatibleWithGreatGrandFather2");
webOSLocale_destroy(loc1);
webOSLocale_destroy(loc2);
}
void testWebOSLocaleCIsCompatibleWithGreatGrandFather()
{
WebOSLocaleC* loc1 = webOSLocale_create("en-US-govnt");
WebOSLocaleC* loc2 = webOSLocale_create("");
if (!assertNotNull(loc1, "testWebOSLocaleCIsCompatibleWithGreatGrandFather")) return;
if (!assertNotNull(loc2, "testWebOSLocaleCIsCompatibleWithGreatGrandFather")) return;
assertTrue(webOSLocale_IsCompatibleWith(loc1, loc2), "testWebOSLocaleCIsCompatibleWithGreatGrandFather");
webOSLocale_destroy(loc1);
webOSLocale_destroy(loc2);
}
void testWebOSLocaleCIsCompatibleWithGrandFather3()
{
WebOSLocaleC* loc1 = webOSLocale_create("en-US");
WebOSLocaleC* loc2 = webOSLocale_create("");
if (!assertNotNull(loc1, "testWebOSLocaleCIsCompatibleWithGrandFather3")) return;
if (!assertNotNull(loc2, "testWebOSLocaleCIsCompatibleWithGrandFather3")) return;
assertTrue(webOSLocale_IsCompatibleWith(loc1, loc2), "testWebOSLocaleCIsCompatibleWithGrandFather3");
webOSLocale_destroy(loc1);
webOSLocale_destroy(loc2);
}
void testWebOSLocaleCIsCompatibleWithCousinVariant()
{
WebOSLocaleC* loc1 = webOSLocale_create("en-US-govnt");
WebOSLocaleC* loc2 = webOSLocale_create("en-US-SCIENTIF");
if (!assertNotNull(loc1, "testWebOSLocaleCIsCompatibleWithCousinVariant")) return;
if (!assertNotNull(loc2, "testWebOSLocaleCIsCompatibleWithCousinVariant")) return;
assertTrue(webOSLocale_IsCompatibleWith(loc1, loc2), "testWebOSLocaleCIsCompatibleWithCousinVariant");
webOSLocale_destroy(loc1);
webOSLocale_destroy(loc2);
}
void runTestWebOSLocale_C(int* testsNumber, int* failuresNumber)
{
printf("\nRunning TestWebOSLocale_C file\n");
clock_t begin, end, tmp;
double timeElapsed = .0000;
short tests_count = 0;
tmp = clock();
begin = tmp;
testWebOSLocaleCConstructorSpec();
timeElapsed = ((double)(clock() - tmp))/CLOCKS_PER_SEC;
printf("Testcase: testWebOSLocaleCConstructorSpec took %f seconds\n", timeElapsed);
tests_count++;
tmp = clock();
testWebOSLocaleCConstructorParts();
timeElapsed = ((double)(clock() - tmp))/CLOCKS_PER_SEC;
printf("Testcase: testWebOSLocaleCConstructorParts took %f seconds\n", timeElapsed);
tests_count++;
tmp = clock();
testWebOSLocaleCGetLanguage();
timeElapsed = ((double)(clock() - tmp))/CLOCKS_PER_SEC;
printf("Testcase: testWebOSLocaleCGetLanguage took %f seconds\n", timeElapsed);
tests_count++;
tmp = clock();
testWebOSLocaleCGetLanguage2LowerChars();
timeElapsed = ((double)(clock() - tmp))/CLOCKS_PER_SEC;
printf("Testcase: testWebOSLocaleCGetLanguage2LowerChars took %f seconds\n", timeElapsed);
tests_count++;
tmp = clock();
testWebOSLocaleCGetLanguage3LowerChars();
timeElapsed = ((double)(clock() - tmp))/CLOCKS_PER_SEC;
printf("Testcase: testWebOSLocaleCGetLanguage3LowerChars took %f seconds\n", timeElapsed);
tests_count++;
tmp = clock();
testWebOSLocaleCGetLanguageNonDigit();
timeElapsed = ((double)(clock() - tmp))/CLOCKS_PER_SEC;
printf("Testcase: testWebOSLocaleCGetLanguageNonDigit took %f seconds\n", timeElapsed);
tests_count++;
tmp = clock();
testWebOSLocaleCGetLanguageParts();
timeElapsed = ((double)(clock() - tmp))/CLOCKS_PER_SEC;
printf("Testcase: testWebOSLocaleCGetLanguageParts took %f seconds\n", timeElapsed);
tests_count++;
tmp = clock();
testWebOSLocaleCGetRegion();
timeElapsed = ((double)(clock() - tmp))/CLOCKS_PER_SEC;
printf("Testcase: testWebOSLocaleCGetRegion took %f seconds\n", timeElapsed);
tests_count++;
tmp = clock();
testWebOSLocaleCGetRegionParts();
timeElapsed = ((double)(clock() - tmp))/CLOCKS_PER_SEC;
printf("Testcase: testWebOSLocaleCGetLanguageParts took %f seconds\n", timeElapsed);
tests_count++;
tmp = clock();
testWebOSLocaleCGetScript();
timeElapsed = ((double)(clock() - tmp))/CLOCKS_PER_SEC;
printf("Testcase: testWebOSLocaleCGetScript took %f seconds\n", timeElapsed);
tests_count++;
tmp = clock();
testWebOSLocaleCGetScriptParts();
timeElapsed = ((double)(clock() - tmp))/CLOCKS_PER_SEC;
printf("Testcase: testWebOSLocaleCGetScriptParts took %f seconds\n", timeElapsed);
tests_count++;
tmp = clock();
testWebOSLocaleCGetVariant();
timeElapsed = ((double)(clock() - tmp))/CLOCKS_PER_SEC;
printf("Testcase: testWebOSLocaleCGetVariant took %f seconds\n", timeElapsed);
tests_count++;
tmp = clock();
testWebOSLocaleCGetVariantParts();
timeElapsed = ((double)(clock() - tmp))/CLOCKS_PER_SEC;
printf("Testcase: testWebOSLocaleCGetVariantParts took %f seconds\n", timeElapsed);
tests_count++;
tmp = clock();
testWebOSLocaleCGetOutOfOrder();
timeElapsed = ((double)(clock() - tmp))/CLOCKS_PER_SEC;
printf("Testcase: testWebOSLocaleCGetOutOfOrder took %f seconds\n", timeElapsed);
tests_count++;
tmp = clock();
testWebOSLocaleCGetLanguageSpecEmpty();
timeElapsed = ((double)(clock() - tmp))/CLOCKS_PER_SEC;
printf("Testcase: testWebOSLocaleCGetLanguageSpecEmpty took %f seconds\n", timeElapsed);
tests_count++;
tmp = clock();
testWebOSLocaleCGetRegionSpecEmpty();
timeElapsed = ((double)(clock() - tmp))/CLOCKS_PER_SEC;
printf("Testcase: testWebOSLocaleCGetRegionSpecEmpty took %f seconds\n", timeElapsed);
tests_count++;
tmp = clock();
testWebOSLocaleCGetScriptSpecEmpty();
timeElapsed = ((double)(clock() - tmp))/CLOCKS_PER_SEC;
printf("Testcase: testWebOSLocaleCGetScriptSpecEmpty took %f seconds\n", timeElapsed);
tests_count++;
tmp = clock();
testWebOSLocaleCGetVariantSpecEmpty();
timeElapsed = ((double)(clock() - tmp))/CLOCKS_PER_SEC;
printf("Testcase: testWebOSLocaleCGetVariantSpecEmpty took %f seconds\n", timeElapsed);
tests_count++;
tmp = clock();
testWebOSLocaleCGetLanguageSpecMissing();
timeElapsed = ((double)(clock() - tmp))/CLOCKS_PER_SEC;
printf("Testcase: testWebOSLocaleCGetLanguageSpecMissing took %f seconds\n", timeElapsed);
tests_count++;
tmp = clock();
testWebOSLocaleCGetRegionSpecMissing();
timeElapsed = ((double)(clock() - tmp))/CLOCKS_PER_SEC;
printf("Testcase: testWebOSLocaleCGetRegionSpecMissing took %f seconds\n", timeElapsed);
tests_count++;
tmp = clock();
testWebOSLocaleCGetRegionSpecOnlyLang();
timeElapsed = ((double)(clock() - tmp))/CLOCKS_PER_SEC;
printf("Testcase: testWebOSLocaleCGetRegionSpecOnlyLang took %f seconds\n", timeElapsed);
tests_count++;
tmp = clock();
testWebOSLocaleCGetVariantSpecOnlyLangAndReg();
timeElapsed = ((double)(clock() - tmp))/CLOCKS_PER_SEC;
printf("Testcase: testWebOSLocaleCGetVariantSpecOnlyLangAndReg took %f seconds\n", timeElapsed);
tests_count++;
tmp = clock();
testWebOSLocaleCGetVariantSpecMissing();
timeElapsed = ((double)(clock() - tmp))/CLOCKS_PER_SEC;
printf("Testcase: testWebOSLocaleCGetVariantSpecMissing took %f seconds\n", timeElapsed);
tests_count++;
tmp = clock();
testWebOSLocaleCGetLanguageEmptySpecMissing();
timeElapsed = ((double)(clock() - tmp))/CLOCKS_PER_SEC;
printf("Testcase: testWebOSLocaleCGetLanguageEmptySpecMissing took %f seconds\n", timeElapsed);
tests_count++;
tmp = clock();
testWebOSLocaleCGetRegionEmptySpecEmpty();
timeElapsed = ((double)(clock() - tmp))/CLOCKS_PER_SEC;
printf("Testcase: testWebOSLocaleCGetRegionEmptySpecEmpty took %f seconds\n", timeElapsed);
tests_count++;
tmp = clock();
testWebOSLocaleCGetVariantEmptySpecEmpty();
timeElapsed = ((double)(clock() - tmp))/CLOCKS_PER_SEC;
printf("Testcase: testWebOSLocaleCGetVariantEmptySpecEmpty took %f seconds\n", timeElapsed);
tests_count++;
tmp = clock();
testWebOSLocaleCGetLanguagePartsEmpty();
timeElapsed = ((double)(clock() - tmp))/CLOCKS_PER_SEC;
printf("Testcase: testWebOSLocaleCGetLanguagePartsEmpty took %f seconds\n", timeElapsed);
tests_count++;
tmp = clock();
testWebOSLocaleCGetRegionPartsEmpty();
timeElapsed = ((double)(clock() - tmp))/CLOCKS_PER_SEC;
printf("Testcase: testWebOSLocaleCGetRegionPartsEmpty took %f seconds\n", timeElapsed);
tests_count++;
tmp = clock();
testWebOSLocaleCGetScriptPartsEmpty();
timeElapsed = ((double)(clock() - tmp))/CLOCKS_PER_SEC;
printf("Testcase: testWebOSLocaleCGetScriptPartsEmpty took %f seconds\n", timeElapsed);
tests_count++;
tmp = clock();
testWebOSLocaleCGetVariantPartsEmpty();
timeElapsed = ((double)(clock() - tmp))/CLOCKS_PER_SEC;
printf("Testcase: testWebOSLocaleCGetVariantPartsEmpty took %f seconds\n", timeElapsed);
tests_count++;
tmp = clock();
testWebOSLocaleCGetLanguageOldISOCodes1();
timeElapsed = ((double)(clock() - tmp))/CLOCKS_PER_SEC;
printf("Testcase: testWebOSLocaleCGetLanguageOldISOCodes1 took %f seconds\n", timeElapsed);
tests_count++;
tmp = clock();
testWebOSLocaleCGetLanguageOldISOCodes2();
timeElapsed = ((double)(clock() - tmp))/CLOCKS_PER_SEC;
printf("Testcase: testWebOSLocaleCGetLanguageOldISOCodes2 took %f seconds\n", timeElapsed);
tests_count++;
tmp = clock();
testWebOSLocaleCGetLanguageOldISOCodes3();
timeElapsed = ((double)(clock() - tmp))/CLOCKS_PER_SEC;
printf("Testcase: testWebOSLocaleCGetLanguageOldISOCodes3 took %f seconds\n", timeElapsed);
tests_count++;
tmp = clock();
testWebOSLocaleCIsPseudoTrue();
timeElapsed = ((double)(clock() - tmp))/CLOCKS_PER_SEC;
printf("Testcase: testWebOSLocaleCIsPseudoTrue took %f seconds\n", timeElapsed);
tests_count++;
tmp = clock();
testWebOSLocaleCIsPseudoFalse();
timeElapsed = ((double)(clock() - tmp))/CLOCKS_PER_SEC;
printf("Testcase: testWebOSLocaleCIsPseudoFalse took %f seconds\n", timeElapsed);
tests_count++;
tmp = clock();
testWebOSLocaleCGetSpec();
timeElapsed = ((double)(clock() - tmp))/CLOCKS_PER_SEC;
printf("Testcase: testWebOSLocaleCGetSpec took %f seconds\n", timeElapsed);
tests_count++;
tmp = clock();
testWebOSLocaleCGetSpecPartsMissing();
timeElapsed = ((double)(clock() - tmp))/CLOCKS_PER_SEC;
printf("Testcase: testWebOSLocaleCGetSpecPartsMissing took %f seconds\n", timeElapsed);
tests_count++;
tmp = clock();
testWebOSLocaleCGetSpecNoVariant();
timeElapsed = ((double)(clock() - tmp))/CLOCKS_PER_SEC;
printf("Testcase: testWebOSLocaleCGetSpecNoVariant took %f seconds\n", timeElapsed);
tests_count++;
tmp = clock();
testWebOSLocaleCGetSpecRearrange();
timeElapsed = ((double)(clock() - tmp))/CLOCKS_PER_SEC;
printf("Testcase: testWebOSLocaleCGetSpecRearrange took %f seconds\n", timeElapsed);
tests_count++;
tmp = clock();
testWebOSLocaleCEquals();
timeElapsed = ((double)(clock() - tmp))/CLOCKS_PER_SEC;
printf("Testcase: testWebOSLocaleCEquals took %f seconds\n", timeElapsed);
tests_count++;
tmp = clock();
testWebOSLocaleCEqualsSymmetric();
timeElapsed = ((double)(clock() - tmp))/CLOCKS_PER_SEC;
printf("Testcase: testWebOSLocaleCEqualsSymmetric took %f seconds\n", timeElapsed);
tests_count++;
tmp = clock();
testWebOSLocaleCNotEquals();
timeElapsed = ((double)(clock() - tmp))/CLOCKS_PER_SEC;
printf("Testcase: testWebOSLocaleCNotEquals took %f seconds\n", timeElapsed);
tests_count++;
tmp = clock();
testWebOSLocaleCNotEqualsClose();
timeElapsed = ((double)(clock() - tmp))/CLOCKS_PER_SEC;
printf("Testcase: testWebOSLocaleCNotEqualsClose took %f seconds\n", timeElapsed);
tests_count++;
tmp = clock();
testWebOSLocaleCEqualsNull();
timeElapsed = ((double)(clock() - tmp))/CLOCKS_PER_SEC;
printf("Testcase: testWebOSLocaleCEqualsNull took %f seconds\n", timeElapsed);
tests_count++;
tmp = clock();
testWebOSLocaleCEqualsMissingParts();
timeElapsed = ((double)(clock() - tmp))/CLOCKS_PER_SEC;
printf("Testcase: testWebOSLocaleCEqualsMissingParts took %f seconds\n", timeElapsed);
tests_count++;
tmp = clock();
testWebOSLocaleCEqualsBothMissingParts();
timeElapsed = ((double)(clock() - tmp))/CLOCKS_PER_SEC;
printf("Testcase: testWebOSLocaleCEqualsBothMissingParts took %f seconds\n", timeElapsed);
tests_count++;
tmp = clock();
testWebOSLocaleCIsCompatibleWithSelf();
timeElapsed = ((double)(clock() - tmp))/CLOCKS_PER_SEC;
printf("Testcase: testWebOSLocaleCIsCompatibleWithSelf took %f seconds\n", timeElapsed);
tests_count++;
tmp = clock();
testWebOSLocaleCIsCompatibleWithEqual();
timeElapsed = ((double)(clock() - tmp))/CLOCKS_PER_SEC;
printf("Testcase: testWebOSLocaleCIsCompatibleWithEqual took %f seconds\n", timeElapsed);
tests_count++;
tmp = clock();
testWebOSLocaleCIsCompatibleWithParentWithRegion();
timeElapsed = ((double)(clock() - tmp))/CLOCKS_PER_SEC;
printf("Testcase: testWebOSLocaleCIsCompatibleWithParentWithRegion took %f seconds\n", timeElapsed);
tests_count++;
tmp = clock();
testWebOSLocaleCIsCompatibleWithParentWithLanguage();
timeElapsed = ((double)(clock() - tmp))/CLOCKS_PER_SEC;
printf("Testcase: testWebOSLocaleCIsCompatibleWithParentWithLanguage took %f seconds\n", timeElapsed);
tests_count++;
tmp = clock();
testWebOSLocaleCIsCompatibleWithParentWithRoot();
timeElapsed = ((double)(clock() - tmp))/CLOCKS_PER_SEC;
printf("Testcase: testWebOSLocaleCIsCompatibleWithParentWithRoot took %f seconds\n", timeElapsed);
tests_count++;
tmp = clock();
testWebOSLocaleCIsCompatibleWithGrandFather();
timeElapsed = ((double)(clock() - tmp))/CLOCKS_PER_SEC;
printf("Testcase: testWebOSLocaleCIsCompatibleWithGrandFather took %f seconds\n", timeElapsed);
tests_count++;
tmp = clock();
testWebOSLocaleCIsCompatibleWithGreatGrandFather2();
timeElapsed = ((double)(clock() - tmp))/CLOCKS_PER_SEC;
printf("Testcase: testWebOSLocaleCIsCompatibleWithGreatGrandFather2 took %f seconds\n", timeElapsed);
tests_count++;
tmp = clock();
testWebOSLocaleCIsCompatibleWithGreatGrandFather();
timeElapsed = ((double)(clock() - tmp))/CLOCKS_PER_SEC;
printf("Testcase: testWebOSLocaleCIsCompatibleWithGreatGrandFather took %f seconds\n", timeElapsed);
tests_count++;
tmp = clock();
testWebOSLocaleCIsCompatibleWithGrandFather3();
timeElapsed = ((double)(clock() - tmp))/CLOCKS_PER_SEC;
printf("Testcase: testWebOSLocaleCIsCompatibleWithGrandFather3 took %f seconds\n", timeElapsed);
tests_count++;
tmp = clock();
testWebOSLocaleCIsCompatibleWithCousinVariant();
end = clock();
timeElapsed = ((double)(end - tmp))/CLOCKS_PER_SEC;
printf("Testcase: testWebOSLocaleCIsCompatibleWithCousinVariant took %f seconds\n", timeElapsed);
tests_count++;
*testsNumber += tests_count;
*failuresNumber += webosC_failures_count;
printf("Tests run: %i , Failures: %i, Time elapsed: %f sec\n", tests_count, webosC_failures_count, ((double)(end - begin)/CLOCKS_PER_SEC));
printf("---------------------- Standard Output ----------------------\n");
}
| 2.109375 | 2 |
2024-11-18T21:30:09.155687+00:00 | 2019-06-18T00:37:43 | 650530ff072c974eb6e1dec77fdedf6e2164ab45 | {
"blob_id": "650530ff072c974eb6e1dec77fdedf6e2164ab45",
"branch_name": "refs/heads/master",
"committer_date": "2019-06-18T00:37:43",
"content_id": "78783da6c1be132c0e200eab395a679dd86e3c0a",
"detected_licenses": [
"MIT"
],
"directory_id": "c4e1dd7d0070fb840cfa5b5b8c7dd8e9e8bca051",
"extension": "c",
"filename": "init_trees_vertical.c",
"fork_events_count": 4,
"gha_created_at": "2014-05-24T08:51:38",
"gha_event_created_at": "2019-06-18T00:37:44",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 20125725,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1001,
"license": "MIT",
"license_type": "permissive",
"path": "/src/gbpAstro/gbpTrees/core/init_trees_vertical.c",
"provenance": "stackv2-0112.json.gz:186890",
"repo_name": "gbpoole/gbpCode",
"revision_date": "2019-06-18T00:37:43",
"revision_id": "5157d2e377edbd4806258d1c16b329373186d43a",
"snapshot_id": "1a96cfd454b05fe8cfc9231f39f3f47f1cacea55",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/gbpoole/gbpCode/5157d2e377edbd4806258d1c16b329373186d43a/src/gbpAstro/gbpTrees/core/init_trees_vertical.c",
"visit_date": "2021-01-17T03:26:08.638552"
} | stackv2 | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <gbpLib.h>
#include <gbpMath.h>
#include <gbpHalos.h>
#include <gbpTrees_build.h>
void init_trees_vertical(int n_snaps, tree_vertical_info **tree) {
int i_search;
(*tree) = (tree_vertical_info *)SID_malloc(sizeof(tree_vertical_info));
(*tree)->n_neighbours = (int *)SID_malloc(sizeof(int) * n_snaps);
(*tree)->neighbour_halos = (tree_vertical_node_info **)SID_malloc(sizeof(tree_vertical_node_info *) * n_snaps);
(*tree)->neighbour_halo_last = (tree_vertical_node_info **)SID_malloc(sizeof(tree_vertical_node_info *) * n_snaps);
for(i_search = 0; i_search < n_snaps; i_search++) {
(*tree)->n_neighbours[i_search] = 0;
(*tree)->neighbour_halos[i_search] = NULL;
(*tree)->neighbour_halo_last[i_search] = NULL;
}
(*tree)->root = NULL;
(*tree)->last_leaf = NULL;
}
| 2 | 2 |
2024-11-18T21:30:10.023355+00:00 | 2017-09-22T19:18:37 | 70972182b85b14777879f498502b752ef08d8ef4 | {
"blob_id": "70972182b85b14777879f498502b752ef08d8ef4",
"branch_name": "refs/heads/master",
"committer_date": "2017-09-22T19:30:38",
"content_id": "c1660fae38a179935d6600220b2ddf7c8a18e449",
"detected_licenses": [
"MIT"
],
"directory_id": "afa5fc5f76dc061f6e2fdc5e70424b5688c66155",
"extension": "c",
"filename": "intel-microcode2ucode.c",
"fork_events_count": 0,
"gha_created_at": "2019-03-20T14:15:24",
"gha_event_created_at": "2019-03-20T14:15:25",
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 176749165,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3163,
"license": "MIT",
"license_type": "permissive",
"path": "/pkgs/os-specific/linux/microcode/intel-microcode2ucode.c",
"provenance": "stackv2-0112.json.gz:187407",
"repo_name": "PavelSheremetev/airapkgs",
"revision_date": "2017-09-22T19:18:37",
"revision_id": "5257232ac7a59dc3c7598042f0d21dc4ae60ea14",
"snapshot_id": "b8889c95e1b878acc66742eab544fbc83c322103",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/PavelSheremetev/airapkgs/5257232ac7a59dc3c7598042f0d21dc4ae60ea14/pkgs/os-specific/linux/microcode/intel-microcode2ucode.c",
"visit_date": "2021-12-04T20:22:23.082415"
} | stackv2 | /*
* Convert Intel microcode.dat into a single binary microcode.bin file
*
* Based on code by Kay Sievers <kay.sievers@vrfy.org>
* Changed to create a single file by Thomas Bächler <thomas@archlinux.org>
*/
#ifndef _GNU_SOURCE
# define _GNU_SOURCE 1
#endif
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <limits.h>
#include <stdbool.h>
#include <inttypes.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/stat.h>
struct microcode_header_intel {
unsigned int hdrver;
unsigned int rev;
unsigned int date;
unsigned int sig;
unsigned int cksum;
unsigned int ldrver;
unsigned int pf;
unsigned int datasize;
unsigned int totalsize;
unsigned int reserved[3];
};
union mcbuf {
struct microcode_header_intel hdr;
unsigned int i[0];
char c[0];
};
int main(int argc, char *argv[])
{
const char *filename = "/lib/firmware/microcode.dat";
FILE *f;
char line[LINE_MAX];
char buf[4000000];
union mcbuf *mc;
size_t bufsize, count, start;
int rc = EXIT_SUCCESS;
if (argv[1] != NULL)
filename = argv[1];
count = 0;
mc = (union mcbuf *) buf;
f = fopen(filename, "re");
if (f == NULL) {
printf("open %s: %m\n", filename);
rc = EXIT_FAILURE;
goto out;
}
while (fgets(line, sizeof(line), f) != NULL) {
if (sscanf(line, "%x, %x, %x, %x",
&mc->i[count],
&mc->i[count + 1],
&mc->i[count + 2],
&mc->i[count + 3]) != 4)
continue;
count += 4;
}
fclose(f);
bufsize = count * sizeof(int);
printf("%s: %lu(%luk) bytes, %zu integers\n",
filename,
bufsize,
bufsize / 1024,
count);
if (bufsize < sizeof(struct microcode_header_intel))
goto out;
f = fopen("microcode.bin", "we");
if (f == NULL) {
printf("open microcode.bin: %m\n");
rc = EXIT_FAILURE;
goto out;
}
start = 0;
for (;;) {
size_t size;
unsigned int family, model, stepping;
unsigned int year, month, day;
mc = (union mcbuf *) &buf[start];
if (mc->hdr.totalsize)
size = mc->hdr.totalsize;
else
size = 2000 + sizeof(struct microcode_header_intel);
if (mc->hdr.ldrver != 1 || mc->hdr.hdrver != 1) {
printf("unknown version/format:\n");
rc = EXIT_FAILURE;
break;
}
/*
* 0- 3 stepping
* 4- 7 model
* 8-11 family
* 12-13 type
* 16-19 extended model
* 20-27 extended family
*/
family = (mc->hdr.sig >> 8) & 0xf;
if (family == 0xf)
family += (mc->hdr.sig >> 20) & 0xff;
model = (mc->hdr.sig >> 4) & 0x0f;
if (family == 0x06)
model += ((mc->hdr.sig >> 16) & 0x0f) << 4;
stepping = mc->hdr.sig & 0x0f;
year = mc->hdr.date & 0xffff;
month = mc->hdr.date >> 24;
day = (mc->hdr.date >> 16) & 0xff;
printf("\n");
printf("signature: 0x%02x\n", mc->hdr.sig);
printf("flags: 0x%02x\n", mc->hdr.pf);
printf("revision: 0x%02x\n", mc->hdr.rev);
printf("date: %04x-%02x-%02x\n", year, month, day);
printf("size: %zu\n", size);
if (fwrite(mc, size, 1, f) != 1) {
printf("write microcode.bin: %m\n");
rc = EXIT_FAILURE;
goto out;
}
start += size;
if (start >= bufsize)
break;
}
fclose(f);
printf("\n");
out:
return rc;
}
| 2.421875 | 2 |
2024-11-18T21:30:10.419823+00:00 | 2023-06-21T03:14:20 | 4c63ff874df9d16126ee6d354671da363a27cf21 | {
"blob_id": "4c63ff874df9d16126ee6d354671da363a27cf21",
"branch_name": "refs/heads/master",
"committer_date": "2023-06-21T03:14:20",
"content_id": "986da1d2a66ad8f770e36b8c42ac41e6a1669e5e",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "317410b28757af216145d23259d63fc96d07f613",
"extension": "c",
"filename": "spi_test.c",
"fork_events_count": 76,
"gha_created_at": "2020-06-16T02:02:15",
"gha_event_created_at": "2022-10-20T23:07:31",
"gha_language": "C",
"gha_license_id": "Apache-2.0",
"github_id": 272586610,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5543,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/cpu/br25/spi_test.c",
"provenance": "stackv2-0112.json.gz:187665",
"repo_name": "Jieli-Tech/fw-AC63_BT_SDK",
"revision_date": "2023-06-21T03:14:20",
"revision_id": "393d63758081d56f0bf0a39ac596bee32c33d493",
"snapshot_id": "48c757dca7e8000ec763bf5466583a4cd8c4a11c",
"src_encoding": "UTF-8",
"star_events_count": 113,
"url": "https://raw.githubusercontent.com/Jieli-Tech/fw-AC63_BT_SDK/393d63758081d56f0bf0a39ac596bee32c33d493/cpu/br25/spi_test.c",
"visit_date": "2023-07-18T02:14:56.187266"
} | stackv2 | #include "system/includes.h"
#include "media/includes.h"
#include "asm/spi.h"
#include "generic/log.h"
#if 0
/*
[[[ README ]]]
1. 本spi测试demo提供了spi.c的API使用例程,测试方式为两个spi的环回测试。
spi1设置为主机模式,spi2设置为从机模式,spi1发送数据到spi2,然后接收spi2
原样返回的数据,然后比较发送出去的数据与接收的数据是否一致,一致则说明
验证通过。
2. 本demo涉及BYTE收发测试及DMA收发测试,通过宏SPI_TEST_MODE选择。另外
demo还涉及到spi中断中调用可用于中断的spi API的使用。
3. spi.c的API不包含CS引脚,CS由API以外控制。
4. 请在board_xxx.c中定义配置结构体,例如用到spi1,需要定义spi1_p_data,
否则编译出错。
5. spi的DMA地址需要4字节对齐。
6. 虽然spi.c的API带有spi0,但在有挂spi flash的芯片上使用可能会出问题,
避免使用spi0。
*/
#define SPI1_CS_OUT() \
do { \
JL_PORTB->DIR &= ~BIT(4); \
JL_PORTB->DIE |= BIT(4); \
JL_PORTB->PU &= ~BIT(4); \
JL_PORTB->PD &= ~BIT(4); \
} while(0)
#define SPI1_CS_L() (JL_PORTB->OUT &= ~BIT(4))
#define SPI1_CS_H() (JL_PORTB->OUT |= BIT(4))
#define SPI2_CS_IN() \
do { \
JL_PORTA->DIR |= BIT(3); \
JL_PORTA->DIE |= BIT(3); \
JL_PORTA->PU &= ~BIT(3); \
JL_PORTA->PD &= ~BIT(3); \
} while (0)
#define SPI2_READ_CS() (JL_PORTA->IN & BIT(3))
static u8 slave_dir = 1;
static u8 spi1_send_buf[100] __attribute__((aligned(4)));
static u8 spi1_recv_buf[100] __attribute__((aligned(4)));
static u8 spi2_send_buf[100] __attribute__((aligned(4)));
static u8 spi2_recv_buf[100] __attribute__((aligned(4)));
static spi_dev spi1_hdl = 1;
static spi_dev spi2_hdl = 2;
#define SPI_TEST_BYTE_MODE 0x01
#define SPI_TEST_DMA_MODE 0x02
//测试模式选择
#define SPI_TEST_MODE SPI_TEST_BYTE_MODE
static void my_put_u8hex(u8 b)
{
u8 dat;
dat = b / 16;
if (dat >= 0 && dat <= 9) {
putchar('0' + dat);
} else {
putchar('A' + dat - 10);
}
dat = b % 16;
if (dat >= 0 && dat <= 9) {
putchar('0' + dat);
} else {
putchar('A' + dat - 10);
}
putchar(' ');
}
//中断函数,需以下特殊声明
__attribute__((interrupt("")))
static void spi2_isr()
{
static int i = 0;
if (spi_get_pending(spi2_hdl)) {
spi_clear_pending(spi2_hdl);
if (SPI2_READ_CS()) {
return;
}
#if SPI_TEST_MODE == SPI_TEST_BYTE_MODE
if (slave_dir == 1) {
spi2_recv_buf[i] = spi_recv_byte_for_isr(spi2_hdl);
spi_send_byte_for_isr(spi2_hdl, spi2_recv_buf[i]);
i >= 100 ? i = 0 : i++;
slave_dir = 0;
} else {
slave_dir = 1;
}
#elif SPI_TEST_MODE == SPI_TEST_DMA_MODE
if (slave_dir == 1) {
spi_dma_set_addr_for_isr(spi2_hdl, spi2_recv_buf, 100, 0);
slave_dir = 0;
} else {
slave_dir = 1;
}
#endif
}
}
#if 1 //仅用于spi demo,正式工程请放到board_xxx.c文件中
/* const struct spi_platform_data spi0_p_data = { */
/* .port = 'A', */
/* .mode = SPI_MODE_BIDIR_1BIT, */
/* .clk = 1000000, */
/* .role = SPI_ROLE_MASTER, */
/* }; */
const struct spi_platform_data spi1_p_data = {
.port = 'A',
.mode = SPI_MODE_BIDIR_1BIT,
.clk = 1000000,
.role = SPI_ROLE_MASTER,
};
const struct spi_platform_data spi2_p_data = {
.port = 'A',
.mode = SPI_MODE_BIDIR_1BIT,
.clk = 1000000,
.role = SPI_ROLE_SLAVE,
};
#endif
void spi_test_main()
{
int i;
int err;
spi_open(spi1_hdl);
spi_open(spi2_hdl);
spi_set_ie(spi2_hdl, 1);
//配置中断优先级,中断函数
request_irq(IRQ_SPI2_IDX, 3, spi2_isr, 0);
SPI1_CS_OUT();
SPI2_CS_IN();
SPI1_CS_H();
for (i = 0; i < 100; i++) {
spi1_send_buf[i] = i % 26 + 'A';
spi1_recv_buf[i] = 0;
}
puts(">>> spi test start\n");
#if SPI_TEST_MODE == SPI_TEST_BYTE_MODE
SPI1_CS_L();
for (i = 0; i < 100; i++) {
err = spi_send_byte(spi1_hdl, spi1_send_buf[i]);
if (err) {
puts("spi1 byte send timeout\n");
break;
}
delay(100);
spi1_recv_buf[i] = spi_recv_byte(spi1_hdl, &err);
if (err) {
puts("spi1 byte recv timeout\n");
break;
}
delay(100);
}
SPI1_CS_H();
#elif SPI_TEST_MODE == SPI_TEST_DMA_MODE
spi_dma_set_addr_for_isr(spi2_hdl, spi2_recv_buf, 100, 1);
SPI1_CS_L();
err = spi_dma_send(spi1_hdl, spi1_send_buf, 100);
if (err < 0) {
puts("spi1 dma send timeout\n");
goto __out_dma;
}
//delay(100);
err = spi_dma_recv(spi1_hdl, spi1_recv_buf, 100);
if (err < 0) {
puts("spi1 dma recv timeout\n");
goto __out_dma;
}
//delay(100);
__out_dma:
SPI1_CS_H();
#endif
puts("<<< spi test end\n");
puts("\nspi master receivce buffer:\n");
for (i = 0; i < 100; i++) {
//my_put_u8hex(spi1_recv_buf[i]);
putchar(spi1_recv_buf[i]), putchar(0x20);
if (i % 16 == 15) {
putchar('\n');
}
}
if (i % 16) {
putchar('\n');
}
if (!memcmp(spi1_send_buf, spi1_recv_buf, 100)) {
puts("\nspi test pass\n");
} else {
puts("\nspi test fail\n");
}
spi_close(spi1_hdl);
spi_close(spi2_hdl);
}
#endif
| 2.40625 | 2 |
2024-11-18T21:30:10.497212+00:00 | 2021-09-09T12:58:37 | 8d656b1c5f5c106e5f7b8584a763efd7767747cd | {
"blob_id": "8d656b1c5f5c106e5f7b8584a763efd7767747cd",
"branch_name": "refs/heads/main",
"committer_date": "2021-09-09T13:07:49",
"content_id": "06766af39fa4d6c568f3e5d31e78d18c02793a57",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "757d9589b330add8dbd5151dcd818a8d06d551a9",
"extension": "c",
"filename": "ttyconfig.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 360196538,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2081,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/linux/ttyconfig.c",
"provenance": "stackv2-0112.json.gz:187795",
"repo_name": "somebyte/S32K144ZENKIT",
"revision_date": "2021-09-09T12:58:37",
"revision_id": "46e40f6dde23601c25fb694b09bb7d7b3dd9cacb",
"snapshot_id": "afb6418d5f4944adc7509948b9a0648a666720fe",
"src_encoding": "UTF-8",
"star_events_count": 5,
"url": "https://raw.githubusercontent.com/somebyte/S32K144ZENKIT/46e40f6dde23601c25fb694b09bb7d7b3dd9cacb/linux/ttyconfig.c",
"visit_date": "2023-07-26T04:09:54.589497"
} | stackv2 | #include "ttyconfig.h"
#include <stdio.h>
#include <errno.h>
speed_t
baudrate (const char* from)
{
speed_t _baudrate = B0;
sscanf (from, "%u", &_baudrate);
switch (_baudrate)
{
case 9600: _baudrate = B9600; break;
case 19200: _baudrate = B19200; break;
case 38400: _baudrate = B38400; break;
case 57600: _baudrate = B57600; break;
case 115200: _baudrate = B115200; break;
case 230400: _baudrate = B230400; break;
case 460800: _baudrate = B460800; break;
case 921600: _baudrate = B921600; break;
}
return _baudrate;
}
FILE*
open_tty (const char* filepath, speed_t brate)
{
if (!filepath)
return NULL;
struct termios ts;
int fd = -1;
FILE* fp = fopen (filepath, "r+");
if (fp == NULL)
{
perror ("open tty");
return NULL;
}
if (tcgetattr (fileno (fp), &ts) < 0)
{
perror ("get tty attr");
return NULL;
}
if (cfsetspeed (&ts, brate))
{
perror ("set tty speed");
return NULL;
}
tcflag_t lflag = ECHO|ICANON|IEXTEN|ISIG; /* local mode flags */
tcflag_t iflag = BRKINT|ICRNL|INPCK|ISTRIP|IXON; /* input mode flags */
tcflag_t cflag = PARENB|CSTOPB; /* control mode flags */
tcflag_t oflag = OCRNL|OFDEL|ONLCR; /* ouput mode flags */
ts.c_lflag &= ~lflag;
ts.c_iflag &= ~iflag;
ts.c_cflag |= CS8;
ts.c_cflag &= ~cflag;
ts.c_oflag &= ~oflag;
ts.c_cc[VTIME] = 5;
ts.c_cc[VMIN] = 0;
if ((fd = fileno (fp)) < 0)
{
perror ("get fileno");
fclose (fp);
return NULL;
}
if (tcsetattr (fd, TCSAFLUSH, &ts) < 0)
{
perror ("set tty attr");
fclose (fp);
return NULL;
}
if (tcgetattr (fd, &ts) < 0)
{
perror ("get tty attr");
fclose (fp);
return NULL;
}
if ((ts.c_lflag & lflag) ||
(ts.c_iflag & iflag) ||
((ts.c_cflag & (CS8|cflag)) != CS8) ||
(ts.c_oflag & oflag)
)
{
errno = EINVAL;
perror ("check setted tty attr");
fclose (fp);
return NULL;
}
return fp;
}
| 2.390625 | 2 |
2024-11-18T21:30:11.794952+00:00 | 2021-11-10T14:30:29 | c5bc704e1f8daea0913845c30fd73042df11461e | {
"blob_id": "c5bc704e1f8daea0913845c30fd73042df11461e",
"branch_name": "refs/heads/master",
"committer_date": "2021-11-10T14:30:29",
"content_id": "11d7f47d081fbe259ee4d2cb30d68b8db7630123",
"detected_licenses": [
"MIT"
],
"directory_id": "47158360ac0db71aff734fd8f87072b14ba72c00",
"extension": "c",
"filename": "holyhttp.c",
"fork_events_count": 0,
"gha_created_at": "2017-08-28T17:21:25",
"gha_event_created_at": "2017-09-03T07:35:38",
"gha_language": "C",
"gha_license_id": null,
"github_id": 101668408,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2251,
"license": "MIT",
"license_type": "permissive",
"path": "/holyhttp.c",
"provenance": "stackv2-0112.json.gz:189227",
"repo_name": "zengfanfan/holyhttp",
"revision_date": "2021-11-10T14:30:29",
"revision_id": "7b20bfbd6007e873710916ac5dfb277fe21a1e46",
"snapshot_id": "2a088ac9dd621b00be85f74a6a2696ce29055987",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/zengfanfan/holyhttp/7b20bfbd6007e873710916ac5dfb277fe21a1e46/holyhttp.c",
"visit_date": "2021-11-13T09:52:58.462706"
} | stackv2 | #include <stdarg.h>
#include <sys/resource.h>
#include <utils/print.h>
#include <server/server.h>
#include <holyhttp.h>
#define MAX_FD_LIMIT (1UL << 30)
rlim_t g_rlim_cur, g_rlim_max;
holy_dbg_lvl_t holydebug = HOLY_DBG_ERROR;
static void set_fd_limit(void)
{
struct rlimit r;
u32 i, limit, step;
for (limit = MAX_FD_LIMIT; limit > 0; limit >>= 1) {
r.rlim_cur = r.rlim_max = limit;
if (setrlimit(RLIMIT_NOFILE, &r) == 0) {// success
step = limit / 10;// try 10 times at most
for (i = limit; i > 0; i -= step) {
r.rlim_max = r.rlim_cur = limit + i;
if (setrlimit(RLIMIT_NOFILE, &r) == 0) {
break;
}
}
break;
}
}
getrlimit(RLIMIT_NOFILE, &r);
g_rlim_cur = r.rlim_cur;
g_rlim_max = r.rlim_max;
}
int holyhttp_init(holycfg_t *cfg)
{
static int inited = 0;
if (inited) {
return 1;
}
set_fd_limit();
if (!holy_server_init(&holyserver, cfg)) {
FATAL("Failed to init server.");
return 0;
}
return 1;
}
void holyhttp_run()
{
if (!holyserver.inited) {
FATAL("Call holyhttp_init first!");
return;
}
holyserver.run(&holyserver);
}
int holyhttp_set_route(char *uri, holyreq_handler_t handler)
{
if (!holyserver.inited) {
FATAL("Call holyhttp_init first!");
return 0;
}
return holyserver.set_route(&holyserver, uri, handler);
}
int holyhttp_set_white_route(char *uri, holyreq_handler_t handler)
{
if (!holyserver.inited) {
FATAL("Call holyhttp_init first!");
return 0;
}
return holyserver.set_whiteroute(&holyserver, uri, handler);
}
void holyhttp_set_debug_level(holy_dbg_lvl_t level)
{
if (level <= 0) {
holydebug = HOLY_DBG_ERROR;
} else {
holydebug = level;
}
}
void holyhttp_set_prerouting(prerouting_t handler)
{
holyserver.prerouting = handler;
}
void holyhttp_set_common_render_args(char *separator, char *fmt, ...)
{
va_list ap;
holyserver.common_separator = separator;
va_start(ap, fmt);
vsnprintf(holyserver.common_args, sizeof holyserver.common_args, fmt, ap);
va_end(ap);
}
| 2.3125 | 2 |
2024-11-18T21:30:11.883559+00:00 | 2021-06-29T02:10:14 | 261bfb529de22f0304955bad435d114417e446fe | {
"blob_id": "261bfb529de22f0304955bad435d114417e446fe",
"branch_name": "refs/heads/main",
"committer_date": "2021-06-29T02:10:14",
"content_id": "b2a16c9935776b84c482cb79aa2eb8b1c4571715",
"detected_licenses": [
"MIT"
],
"directory_id": "61545ffb3d820850e3fd849b1b7c3e2f6e64fbcf",
"extension": "c",
"filename": "MUNIZ-2.11.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 348110050,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1367,
"license": "MIT",
"license_type": "permissive",
"path": "/LISTA-11/MUNIZ-2.11.c",
"provenance": "stackv2-0112.json.gz:189356",
"repo_name": "Munizz77/PROGRAMMING-IN-C-",
"revision_date": "2021-06-29T02:10:14",
"revision_id": "c660d14fe256a0d84d24965861c2d8e9fa90c999",
"snapshot_id": "ad44df03243e98ea9e02ee7bfea35c8409ed10a3",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Munizz77/PROGRAMMING-IN-C-/c660d14fe256a0d84d24965861c2d8e9fa90c999/LISTA-11/MUNIZ-2.11.c",
"visit_date": "2023-06-08T02:08:52.621617"
} | stackv2 | #include <stdio.h>
#include <stdlib.h>
#include <time.h>
void gerarMatriz(int tamanhoMatriz, int matriz[tamanhoMatriz][tamanhoMatriz]){
int linha, coluna;
for (linha = 0; linha < tamanhoMatriz; linha++) {
for (coluna = 0; coluna < tamanhoMatriz; coluna++) {
matriz[linha][coluna] = 0;
}
}
}
void preencherDiagonalPrincipal(int tamanhoMatriz,
int matriz[tamanhoMatriz][tamanhoMatriz]){
int linha, coluna;
for (linha = 0; linha < tamanhoMatriz; linha++) {
for (coluna = 0; coluna <= linha + 1; coluna++) {
if(linha == coluna){
matriz[linha][coluna] = 1;
}
}
}
}
void imprimirMatriz(int tamanhoMatriz, int matriz[tamanhoMatriz][tamanhoMatriz]){
int linha, coluna, valorAleatorio;
for (linha = 0; linha < tamanhoMatriz; linha++) {
for (coluna = 0; coluna < tamanhoMatriz; coluna++) {
printf("%d | ", matriz[linha][coluna]);
}
printf("\n");
}
printf("\n");
}
int main() {
int tamanhoMatriz = 6, matriz[tamanhoMatriz][tamanhoMatriz];
srand(time(NULL));
gerarMatriz(tamanhoMatriz, matriz);
printf("Imprimindo matriz inicial: \n\n");
imprimirMatriz(tamanhoMatriz, matriz);
printf("Imprimindo matriz preechida diagonal principal com 1: \n\n");
preencherDiagonalPrincipal(tamanhoMatriz, matriz);
imprimirMatriz(tamanhoMatriz, matriz);
return 0;
} | 3.140625 | 3 |
2024-11-18T21:30:11.946679+00:00 | 2016-09-03T21:53:19 | bc2dd0956d036881159cab33a867dddf0fa9fbee | {
"blob_id": "bc2dd0956d036881159cab33a867dddf0fa9fbee",
"branch_name": "refs/heads/master",
"committer_date": "2016-09-03T21:53:19",
"content_id": "0354337f315458be6c884a4144905ebcae8297b3",
"detected_licenses": [
"MIT"
],
"directory_id": "77f36eaf4ae5e87a310b6d5a11b7c71b7a755c90",
"extension": "c",
"filename": "4-pointers-1.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 67311365,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3250,
"license": "MIT",
"license_type": "permissive",
"path": "/4-pointers-1.c",
"provenance": "stackv2-0112.json.gz:189485",
"repo_name": "MaxRoecker/learning-c",
"revision_date": "2016-09-03T21:53:19",
"revision_id": "081ceadbd67486aac78397c45cf445c0981370b1",
"snapshot_id": "486885a5832bb7878d2edc298b250f974c485b42",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/MaxRoecker/learning-c/081ceadbd67486aac78397c45cf445c0981370b1/4-pointers-1.c",
"visit_date": "2020-07-29T00:27:02.846744"
} | stackv2 | #include <stdlib.h>
#include <stdio.h>
/* Pointers, denoted by `<type> *<id>`, allows you to store memory addresses as
* its value. A pointer that points to nowhere is usually defined to point to a
* "NULL" value.
* (1) The operator `&<id>` returns the memory address of the given identifier.
* (2) The operator `*<id>` returns the value of the memory address stored in
the pointer.
* (3) You can copy the memory address of a pointer to another pointer by
using atribuition `=`.
*/
void pointers_to_variables(void) {
printf("\n[1] ----------------------------\n\n");
printf("Pointers to variables:\n");
int a = 32,
b = a;
int *c = &(a),
*d = &(b),
*e = NULL;
*c = 16;
e = c;
printf("Memory Address of 'a': %p\n", c);
printf("Value of 'a': %i\n\n", *e);
printf("Memory Address of 'b': %p\n", d);
printf("Value of 'b': %i\n\n", *d);
}
/* A constant, denoted by "const <type> <id>", has a particular behavior: it
* exclusively allows read-only operations to the value it represents. Pointers
* to constants, denoted by "const <type> *<id>", has the same behavior.
*
* However, if you define a non-constant pointer that address to a constant, you
* can perform read and write operations in the value. This is not recommended.
*/
void pointers_to_constants(void) {
printf("\n[2] ----------------------------\n\n");
printf("Pointers to constants:\n");
const int a = 32,
b = 16;
const int *c = &(a);
int *d = &(b);
*d = 8;
printf("Memory Address of 'a': %p\n", c);
printf("Value of 'a': %i\n\n", *c);
printf("Memory Address of 'b': %p\n", d);
printf("Value of 'b': %i\n\n", *d);
}
/* A constant pointer, denoted by "<type> *const <id>", behaves like a constant
* to a memory address value. You can change the value addressed by the pointer,
* but you cannot change the memory address in the pointer.
*/
void constant_pointers_to_variables(void) {
printf("\n[3] ----------------------------\n\n");
printf("Constant pointer to variables:\n");
int a = 32,
b = 16;
int *const c = &(a);
int *const d = &(b);
*d = *c;
printf("Memory Address of 'a': %p\n", c);
printf("Value of 'a': %i\n\n", *c);
printf("Memory Address of 'b': %p\n", d);
printf("Value of 'b': %i\n\n", *d);
}
/* A constant pointer to a constant exclusively allows read-only operations in a
* constant memory address value. Neither the pointer value nor the value
* addressed by it can be changed after its defition.
*/
void constant_pointers_to_constants(void) {
printf("\n[4] ----------------------------\n\n");
printf("Constant pointer to variables:\n");
const int a = 32,
b = 16;
const int *const c = &(a);
const int *const d = &(b);
printf("Memory Address of 'a': %p\n", c);
printf("Value of 'a': %i\n\n", *c);
printf("Memory Address of 'b': %p\n", d);
printf("Value of 'b': %i\n\n", *d);
}
int main(int argc, char const *argv[]) {
printf("================================\n");
printf("POINTERS #1\n");
printf("================================\n");
pointers_to_variables();
pointers_to_constants();
constant_pointers_to_variables();
constant_pointers_to_constants();
printf("\n");
return EXIT_SUCCESS;
}
| 3.875 | 4 |
2024-11-18T21:30:12.118249+00:00 | 2020-04-06T15:58:12 | 296d0db906e6667bf4e8ab42199702d52bce71f2 | {
"blob_id": "296d0db906e6667bf4e8ab42199702d52bce71f2",
"branch_name": "refs/heads/master",
"committer_date": "2020-04-06T15:58:12",
"content_id": "f9b32bf3db4757c1ce084998959df8e53d33165c",
"detected_licenses": [
"MIT"
],
"directory_id": "3193d4fad6b05927b6b115619fc204ca530f6097",
"extension": "c",
"filename": "server.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 116788915,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 679,
"license": "MIT",
"license_type": "permissive",
"path": "/CourseWork/networks/MA61010/tcp/server.c",
"provenance": "stackv2-0112.json.gz:189745",
"repo_name": "ank247/IITKGP",
"revision_date": "2020-04-06T15:58:12",
"revision_id": "b8e7185b2c436de6df00c95dbdc1ef9a231c9056",
"snapshot_id": "8fd2c036b3e52cab85fac702de53025a514b62da",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/ank247/IITKGP/b8e7185b2c436de6df00c95dbdc1ef9a231c9056/CourseWork/networks/MA61010/tcp/server.c",
"visit_date": "2022-04-19T19:18:09.875553"
} | stackv2 |
#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<fcntl.h>
main()
{
int sockfd,fd,len,i,p;
char b[200];
struct sockaddr_in sa,ca;
len=sizeof(sa);
sockfd=socket(AF_INET,SOCK_STREAM,0);
sa.sin_family=AF_INET;
sa.sin_addr.s_addr=INADDR_ANY;
printf("Give self port no.:");
scanf("%d",&sa.sin_port);
i=bind(sockfd,(struct sockaddr *)&sa,len);
printf("(%d %d)\n",sockfd,i);
listen(sockfd,5);
fd=accept(sockfd,(struct sockaddr *)&ca,&len);
printf("[%d]\n",fd);
recv(fd,&p,4,0);
printf("client sent %d\n",p);
printf("\nGive string to send to client");
scanf("%s",b);
send(fd,b,50,0);
return 0;
}
| 2.84375 | 3 |
2024-11-18T21:30:12.283948+00:00 | 2018-11-08T18:18:58 | d615f42190863233832d5eb86566fe09a55e8f48 | {
"blob_id": "d615f42190863233832d5eb86566fe09a55e8f48",
"branch_name": "refs/heads/master",
"committer_date": "2018-11-08T18:18:58",
"content_id": "ba170eec007625cd2aca026a95f996ecaf90a185",
"detected_licenses": [
"MIT"
],
"directory_id": "196ad284a515df7ef9aa9f984c9fd536d19d0d52",
"extension": "c",
"filename": "F_2_RecursiveFunction.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 156748485,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 410,
"license": "MIT",
"license_type": "permissive",
"path": "/C_Assignment/A6_Functions/F_2_RecursiveFunction.c",
"provenance": "stackv2-0112.json.gz:189874",
"repo_name": "sonijaiswal1501/C-_Programs",
"revision_date": "2018-11-08T18:18:58",
"revision_id": "119c7540e51c6347e041f61e23fd22f1af01d690",
"snapshot_id": "a501e403c1de7009211ed511f1c1755e15755520",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/sonijaiswal1501/C-_Programs/119c7540e51c6347e041f61e23fd22f1af01d690/C_Assignment/A6_Functions/F_2_RecursiveFunction.c",
"visit_date": "2020-04-05T09:14:56.540768"
} | stackv2 | //Write a recursive function to find factorial of a number.
#include<stdio.h>
int factorial(int);
int main()
{
int i, num, result;
printf("\nEnter any number: ");
scanf("%d", &num);
result = factorial(num);
printf("\nFactorial of %d is %d\n", num, result);
return 0;
}
int factorial(int n)
{
int i, fact = 1;
if(n<2)
return 1;
else
return factorial(n-1)*n;
return fact;
}
| 3.875 | 4 |
2024-11-18T21:30:12.479507+00:00 | 2021-03-06T16:15:56 | fb01795dc21e9f42f166ba0e41ba8a7c6e94350c | {
"blob_id": "fb01795dc21e9f42f166ba0e41ba8a7c6e94350c",
"branch_name": "refs/heads/main",
"committer_date": "2021-03-06T16:15:56",
"content_id": "c9bf7ec0cc36d61808913e91eab9960d0751616e",
"detected_licenses": [
"MIT"
],
"directory_id": "019f4911ba4c62f1ee6512b0f7da5f9201da3a86",
"extension": "c",
"filename": "kmconverter.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 328594836,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1562,
"license": "MIT",
"license_type": "permissive",
"path": "/assigned-tasks/kmconverter.c",
"provenance": "stackv2-0112.json.gz:190134",
"repo_name": "SoulHarsh007/c-labs",
"revision_date": "2021-03-06T16:15:56",
"revision_id": "b1eed226c2ff3b769ecb72fd95f71604787b0789",
"snapshot_id": "8d9dbc0c822d35c014d66ac0142d7b3dc7b5b1e8",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/SoulHarsh007/c-labs/b1eed226c2ff3b769ecb72fd95f71604787b0789/assigned-tasks/kmconverter.c",
"visit_date": "2023-03-17T16:01:54.952930"
} | stackv2 | /* Copyright (c) 2020 SoulHarsh007 (Harsh Peshwani)
* Contact: maintainter@theniabot.ml or harshtheking@hotmail.com
* GitHub: https://github.com/SoulHarsh007/
*/
#include <stdio.h>
int main() {
float km;
int i;
printf("1. Convert Kilometers to Meters\n");
printf("2. Convert Kilometers to Feet\n");
printf("3. Convert Kilometers to Inches\n");
printf("4. Convert Kilometers to Centimeters\n");
printf("5. Exit\n");
printf("Input your choice: ");
scanf("%d", &i);
switch (i) {
case 1:
printf("Input the value in km: ");
scanf("%f", &km);
printf("%.2f Meters\n", (km * 1000));
break;
case 2:
printf("Input the value in km: ");
scanf("%f", &km);
printf("%.2f Feet\n", (km * 3280.8399));
break;
case 3:
printf("Input the value in km: ");
scanf("%f", &km);
printf("%.2f Inches\n", (km * 39370.0787));
break;
case 4:
printf("Input the value in km: ");
scanf("%f", &km);
printf("%.2f Centimeters\n", (km * 100000));
break;
case 5:
printf("Exit signal received, exiting...\n");
return 0;
break;
default:
printf("Invalid response received, exiting...\n");
/*
* Wondering why return 1 here? this will be exit code for the process and
* exit code 1 means error while processing by convention in many programs
* while exit code 0 means clean exit. This can help users with
* Accessibility services such as talkback to understand that the program
* failed because of their incorrect input.
*/
return 1;
break;
}
}
| 3.078125 | 3 |
2024-11-18T21:30:12.574648+00:00 | 2018-11-18T10:47:53 | 9a85b4c3a006873a0ca6b6cabfc6ea672067a5dc | {
"blob_id": "9a85b4c3a006873a0ca6b6cabfc6ea672067a5dc",
"branch_name": "refs/heads/master",
"committer_date": "2018-11-18T10:47:53",
"content_id": "e9d23a366e84e09c45bd717db7bdc7ae83ffd6b2",
"detected_licenses": [
"MIT"
],
"directory_id": "5b6bb281059e1bed0cfc16977d009649bb1ba4c5",
"extension": "c",
"filename": "1D Arrays.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 150771867,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 283,
"license": "MIT",
"license_type": "permissive",
"path": "/Hackerrank/Language Proficiency in C/1D Arrays.c",
"provenance": "stackv2-0112.json.gz:190264",
"repo_name": "MayThirtyOne/Competitive-Coding",
"revision_date": "2018-11-18T10:47:53",
"revision_id": "f9de1dc4a11d04e63a130be83a02628981bac29d",
"snapshot_id": "eecd5f17a4081a78330934cbf46d77fff3d306c1",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/MayThirtyOne/Competitive-Coding/f9de1dc4a11d04e63a130be83a02628981bac29d/Hackerrank/Language Proficiency in C/1D Arrays.c",
"visit_date": "2020-03-30T04:58:12.887351"
} | stackv2 | #include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main() {
int num;
scanf("%d",&num);
int arr[num],sum=0;
while(num--)
{scanf("%d",&arr[num]);
sum=sum+arr[num];}
printf("%d\n",sum);
return 0;
}
| 2.390625 | 2 |
2024-11-18T21:30:12.643865+00:00 | 2016-02-22T07:54:50 | ce63bc5af10d7b83a3eac18b0f22ead184b49a9b | {
"blob_id": "ce63bc5af10d7b83a3eac18b0f22ead184b49a9b",
"branch_name": "refs/heads/master",
"committer_date": "2016-02-22T07:54:50",
"content_id": "c04705dbd621761c6648e92c7ae260c1e947c381",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "9705ba6476b728f2a320b254c47638ada14d0e4e",
"extension": "c",
"filename": "cresource_data.c",
"fork_events_count": 0,
"gha_created_at": "2015-10-30T08:27:27",
"gha_event_created_at": "2015-10-30T08:27:28",
"gha_language": null,
"gha_license_id": null,
"github_id": 45238290,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1411,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/std/av/src/mupnp/std/av/cresource_data.c",
"provenance": "stackv2-0112.json.gz:190394",
"repo_name": "jink2005/mupnpc",
"revision_date": "2016-02-22T07:54:50",
"revision_id": "9f0a41c19b439875680fc7850b22fcbd3ff5a50c",
"snapshot_id": "71d19eab5faed7ab2503f9d3c8b15718db66e05f",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/jink2005/mupnpc/9f0a41c19b439875680fc7850b22fcbd3ff5a50c/std/av/src/mupnp/std/av/cresource_data.c",
"visit_date": "2021-01-18T16:35:15.468260"
} | stackv2 | /************************************************************
*
* CyberLink for C
*
* Copyright (C) Satoshi Konno 2005
*
* File: cresource_data.c
*
* Revision:
* 05/11/05
* - first release.
*
************************************************************/
#include <mupnp/std/av/cresource.h>
#include <mupnp/util/string.h>
/****************************************
* mupnp_upnpav_resource_data_new
****************************************/
mUpnpAvResourceData *mupnp_upnpav_resource_data_new()
{
mUpnpAvResourceData *resData;
resData = (mUpnpAvResourceData *)malloc(sizeof(mUpnpAvResourceData));
resData->mimeType = mupnp_string_new();
resData->dlnaAttr = mupnp_string_new();
return resData;
}
/****************************************
* mupnp_upnpav_resource_data_delete
****************************************/
void mupnp_upnpav_resource_data_delete(mUpnpAvResourceData *resData)
{
mupnp_string_delete(resData->mimeType);
mupnp_string_delete(resData->dlnaAttr);
free(resData);
}
/****************************************
* mupnp_upnpav_resource_data_copy
****************************************/
void mupnp_upnpav_resource_data_copy(mUpnpAvResourceData *destResData, mUpnpAvResourceData *srcResData)
{
if (NULL == destResData || NULL == srcResData) {
return;
}
mupnp_string_setvalue(destResData->mimeType, mupnp_string_getvalue(srcResData->mimeType));
}
| 2.15625 | 2 |
2024-11-18T21:30:12.711621+00:00 | 2018-01-11T12:38:34 | 5c5fc85021ace058db73604eec05c4f7d472f373 | {
"blob_id": "5c5fc85021ace058db73604eec05c4f7d472f373",
"branch_name": "refs/heads/master",
"committer_date": "2018-01-11T12:38:34",
"content_id": "2f772261d4e120cabd727b11f05130df31c70570",
"detected_licenses": [
"MIT"
],
"directory_id": "797daffa086ed6fe502010bf027891619c06cc5f",
"extension": "c",
"filename": "command.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 113842266,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2156,
"license": "MIT",
"license_type": "permissive",
"path": "/src/command.c",
"provenance": "stackv2-0112.json.gz:190523",
"repo_name": "babariviere/minishell",
"revision_date": "2018-01-11T12:38:34",
"revision_id": "69f85176293f224dc79cbed6a2dea848d597c920",
"snapshot_id": "d827e01eae46ccd6f292be42d00c20877ada68a5",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/babariviere/minishell/69f85176293f224dc79cbed6a2dea848d597c920/src/command.c",
"visit_date": "2021-09-03T19:29:54.727925"
} | stackv2 | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* command.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: briviere <briviere@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/12/12 11:53:05 by briviere #+# #+# */
/* Updated: 2017/12/26 09:14:29 by briviere ### ########.fr */
/* */
/* ************************************************************************** */
#include "msh.h"
static char *file_exists(const char *path, const char *file)
{
char *tmp;
struct stat st;
tmp = ft_strjoin_sep(path, '/', file);
if (lstat(tmp, &st) < 0)
{
free(tmp);
return (0);
}
return (tmp);
}
void free_command(t_command **cmdptr)
{
t_command *cmd;
cmd = *cmdptr;
if (cmd->env)
ft_tabdel((void ***)&cmd->env, sizeof(char *));
if (cmd->bin)
free(cmd->bin);
if (cmd->av)
ft_tabdel((void ***)&cmd->av, sizeof(char *));
ft_memdel((void **)cmdptr);
}
static char *cmd_bin_path_sub(char *cmd, const char *epath, size_t beg,
size_t end)
{
char *res;
char *tmp;
if (cmd == 0 || epath == 0)
return (0);
tmp = ft_strsub(epath, beg, end - beg);
res = file_exists(tmp, cmd);
if (tmp)
free(tmp);
if (res)
return (res);
return (0);
}
char *cmd_bin_path(char *cmd, const char *epath)
{
size_t beg;
size_t end;
char *res;
if (cmd == 0 || cmd[0] == 0)
return (cmd);
if (ft_strchr(cmd, '/'))
return (cmd);
if (get_builtin(cmd) >= 0)
return (cmd);
beg = 0;
end = beg;
res = 0;
while (epath && epath[end])
{
if (epath[end] == ':')
{
if ((res = cmd_bin_path_sub(cmd, epath, beg, end)))
return (res);
beg = end + 1;
}
end++;
}
return (cmd_bin_path_sub(cmd, epath, beg, end));
}
| 2.453125 | 2 |
2024-11-18T21:30:12.828611+00:00 | 2023-09-01T13:02:25 | 02a0c3288438f0eabd3d9e733b636fda76620eca | {
"blob_id": "02a0c3288438f0eabd3d9e733b636fda76620eca",
"branch_name": "refs/heads/master",
"committer_date": "2023-09-01T13:02:25",
"content_id": "2545bc4274786061bc17c416cbb896d49cf3af58",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "baa9fffc817a2a993d4ecc774d3f277783308c20",
"extension": "h",
"filename": "ucp_am.h",
"fork_events_count": 420,
"gha_created_at": "2014-10-17T22:17:24",
"gha_event_created_at": "2023-09-14T12:29:35",
"gha_language": "C",
"gha_license_id": "NOASSERTION",
"github_id": 25379390,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4587,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/src/ucp/core/ucp_am.h",
"provenance": "stackv2-0112.json.gz:190653",
"repo_name": "openucx/ucx",
"revision_date": "2023-09-01T13:02:25",
"revision_id": "73a48700badb7cbace64d94b82f408e2a26fca32",
"snapshot_id": "9a0f2205295afbdf3cff14b5d24af781b123f5ea",
"src_encoding": "UTF-8",
"star_events_count": 966,
"url": "https://raw.githubusercontent.com/openucx/ucx/73a48700badb7cbace64d94b82f408e2a26fca32/src/ucp/core/ucp_am.h",
"visit_date": "2023-09-01T16:51:26.913950"
} | stackv2 | /**
* Copyright (C) Los Alamos National Security, LLC. 2019 ALL RIGHTS RESERVED.
* Copyright (c) NVIDIA CORPORATION & AFFILIATES, 2020. ALL RIGHTS RESERVED.
*
* See file LICENSE for terms.
*/
#ifndef UCP_AM_H_
#define UCP_AM_H_
#include <ucs/datastruct/array.h>
#include <ucp/rndv/rndv.h>
#define ucp_am_hdr_from_rts(_rts) \
({ \
UCS_STATIC_ASSERT(sizeof((_rts)->hdr) == sizeof(ucp_am_hdr_t)); \
((ucp_am_hdr_t*)&(_rts)->hdr); \
})
enum {
UCP_AM_CB_PRIV_FIRST_FLAG = UCS_BIT(15),
/* Indicates that cb was set with ucp_worker_set_am_recv_handler */
UCP_AM_CB_PRIV_FLAG_NBX = UCP_AM_CB_PRIV_FIRST_FLAG
};
/**
* Data that is stored about each callback registered with a worker
*/
typedef struct ucp_am_entry {
union {
ucp_am_callback_t cb_old; /* user defined callback, used by legacy API */
ucp_am_recv_callback_t cb; /* user defined callback */
};
void *context; /* user defined callback argument */
unsigned flags; /* flags affecting callback behavior
(set by the user) */
} ucp_am_entry_t;
UCS_ARRAY_DECLARE_TYPE(ucp_am_cbs, unsigned, ucp_am_entry_t)
typedef struct ucp_am_info {
size_t alignment;
ucs_array_t(ucp_am_cbs) cbs;
} ucp_am_info_t;
/**
* All eager messages are sent with 8 byte basic header. If more meta data need
* to be sent, it is added as a footer in the end of message. This helps to
* guarantee proper alignment on the receiver. Below are the layouts of
* different eager messages:
*
* Single fragment message:
* +------------------+---------+----------+
* | ucp_am_hdr_t | payload | user hdr |
* +------------------+---------+----------+
*
* Single fragment message with reply protocol:
* +------------------+---------+----------+--------------------+
* | ucp_am_hdr_t | payload | user hdr | ucp_am_reply_ftr_t |
* +------------------+---------+----------+--------------------+
*
* First fragment of the multi-fragment message:
* +------------------+---------+----------+--------------------+
* | ucp_am_hdr_t | payload | user hdr | ucp_am_first_ftr_t |
* +------------------+---------+----------+--------------------+
*
* Middle/last fragment of the multi-fragment message:
* +------------------+---------+------------------+
* | ucp_am_mid_hdr_t | payload | ucp_am_mid_ftr_t |
* +------------------+---------+------------------+
*/
typedef union {
struct {
uint16_t am_id; /* index into callback array */
uint16_t flags; /* operation flags */
uint32_t header_length; /* user header length */
};
uint64_t u64; /* this is used to ensure the size of
the header is 64 bytes and aligned */
} UCS_S_PACKED ucp_am_hdr_t;
typedef struct {
size_t offset;
} UCS_S_PACKED ucp_am_mid_hdr_t;
typedef struct {
uint64_t ep_id; /* ep which can be used for reply */
} UCS_S_PACKED ucp_am_reply_ftr_t;
typedef struct {
uint64_t msg_id; /* method to match parts of the same AM */
uint64_t ep_id; /* ep which can be used for reply */
} UCS_S_PACKED ucp_am_mid_ftr_t;
typedef struct {
ucp_am_mid_ftr_t super; /* base fragment header */
size_t total_size; /* length of buffer needed for all data */
} UCS_S_PACKED ucp_am_first_ftr_t;
typedef struct {
ucs_list_link_t list; /* entry into list of unfinished AM's */
size_t remaining; /* how many bytes left to receive */
} ucp_am_first_desc_t;
#define UCP_AM_FIRST_FRAG_META_LEN \
(sizeof(ucp_am_hdr_t) + sizeof(ucp_am_first_ftr_t))
#define UCP_AM_MID_FRAG_META_LEN \
(sizeof(ucp_am_hdr_t) + sizeof(ucp_am_mid_ftr_t))
ucs_status_t ucp_am_init(ucp_worker_h worker);
void ucp_am_cleanup(ucp_worker_h worker);
void ucp_am_ep_init(ucp_ep_h ep);
void ucp_am_ep_cleanup(ucp_ep_h ep);
ucs_status_t ucp_proto_progress_am_rndv_rts(uct_pending_req_t *self);
ucs_status_t ucp_am_rndv_process_rts(void *arg, void *data, size_t length,
unsigned tl_flags);
ucs_status_t ucp_am_proto_request_zcopy_reset(ucp_request_t *request);
void ucp_proto_am_request_bcopy_abort(ucp_request_t *req, ucs_status_t status);
void ucp_proto_am_request_zcopy_abort(ucp_request_t *req, ucs_status_t status);
#endif
| 2.015625 | 2 |
2024-11-18T21:30:13.522080+00:00 | 2016-02-10T00:06:18 | 4a16849fc18fc92dae9c4db5cfd4dc1d9c312603 | {
"blob_id": "4a16849fc18fc92dae9c4db5cfd4dc1d9c312603",
"branch_name": "refs/heads/master",
"committer_date": "2016-02-10T00:06:18",
"content_id": "a10297b22e5be22e525d34608dc0d52ff359da9d",
"detected_licenses": [
"Ruby",
"MIT"
],
"directory_id": "0e8d27195d07c23fe249f1bb50b192aa7ff90da2",
"extension": "h",
"filename": "rmtools.h",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 1151376,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3507,
"license": "Ruby,MIT",
"license_type": "permissive",
"path": "/ext/rmtools.h",
"provenance": "stackv2-0112.json.gz:191171",
"repo_name": "tinbka/rmtools",
"revision_date": "2016-02-10T00:06:18",
"revision_id": "bfb54f07d3d7622ec45994f93af294243982cee0",
"snapshot_id": "e04941f635668323048a4389845d802d31c7b2af",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/tinbka/rmtools/bfb54f07d3d7622ec45994f93af294243982cee0/ext/rmtools.h",
"visit_date": "2020-05-18T13:50:43.081456"
} | stackv2 | #ifndef __RUBY_INTERNALS_HH__
#define __RUBY_INTERNALS_HH__
#include <ruby.h>
#ifdef RUBY_IS_19
#include <ruby/intern.h>
#include <ruby/defines.h>
#include <ruby/re.h>
#include <assert.h>
# define ARY_EMBED_P(ary) \
(assert(!FL_TEST(ary, ELTS_SHARED) || !FL_TEST(ary, RARRAY_EMBED_FLAG)), \
FL_TEST(ary, RARRAY_EMBED_FLAG))
#define ARY_SET_EMBED_LEN(ary, n) do { \
long tmp_n = n; \
RBASIC(ary)->flags &= ~RARRAY_EMBED_LEN_MASK; \
RBASIC(ary)->flags |= (tmp_n) << RARRAY_EMBED_LEN_SHIFT; \
} while (0)
#define ARY_SET_HEAP_LEN(ary, n) do { \
RARRAY(ary)->as.heap.len = n; \
} while (0)
#define ARY_SET_LEN(ary, n) do { \
if (ARY_EMBED_P(ary)) { \
ARY_SET_EMBED_LEN(ary, n); \
} \
else { \
ARY_SET_HEAP_LEN(ary, n); \
} \
} while (0)
#define BDIGITS(x) ((BDIGIT*)RBIGNUM_DIGITS(x))
// copied from utilrb gem
typedef struct RNode {
unsigned long flags;
char *nd_file;
union {
struct RNode *node;
ID id;
VALUE value;
VALUE (*cfunc)(ANYARGS);
ID *tbl;
} u1;
union {
struct RNode *node;
ID id;
long argc;
VALUE value;
} u2;
union {
struct RNode *node;
ID id;
long state;
struct global_entry *entry;
long cnt;
VALUE value;
} u3;
} NODE;
typedef struct RVALUE {
union {
struct {
VALUE flags; /* always 0 for freed obj */
struct RVALUE *next;
} free;
struct RBasic basic;
struct RObject object;
struct RClass klass;
struct RFloat flonum;
struct RString string;
struct RArray array;
struct RRegexp regexp;
struct RHash hash;
struct RData data;
struct RStruct rstruct;
struct RBignum bignum;
struct RFile file;
struct RNode node;
struct RMatch match;
struct RRational rational;
struct RComplex complex;
} as;
} RVALUE;
static const size_t SLOT_SIZE = sizeof(RVALUE);
#else
#include <intern.h>
#include <node.h>
#include <env.h>
#include <re.h>
# define STR_SET_LEN(x, i) (RSTRING(x)->len = (i))
#ifndef RFLOAT_VALUE
# define RFLOAT_VALUE(f) (RFLOAT(f)->value)
# define RBIGNUM_DIGITS(f) (RBIGNUM(f)->digits)
# define RBIGNUM_LEN(f) (RBIGNUM(f)->len)
#endif
# define ARY_SET_LEN(x, i) (RARRAY(x)->len = (i))
# define BDIGITS(x) ((BDIGIT*)RBIGNUM(x)->digits)
// copied from utilrb gem
typedef struct RVALUE {
union {
struct {
unsigned long flags; /* always 0 for freed obj */
struct RVALUE *next;
} free;
struct RBasic basic;
struct RObject object;
struct RClass klass;
struct RFloat flonum;
struct RString string;
struct RArray array;
struct RRegexp regexp;
struct RHash hash;
struct RData data;
struct RStruct rstruct;
struct RBignum bignum;
struct RFile file;
struct RNode node;
struct RMatch match;
struct RVarmap varmap;
struct SCOPE scope;
} as;
#ifdef GC_DEBUG
char *file;
int line;
#endif
} RVALUE;
static const size_t SLOT_SIZE = sizeof(RVALUE);
#endif // 1.9
// shortcuts for debug r_r
extern void rb_log(const char* str)
{
rb_funcall(rb_gv_get("$log"), rb_intern("debug"), 1, rb_str_new2(str));
}
extern void rb_log_obj(VALUE obj)
{
rb_funcall(rb_gv_get("$log"), rb_intern("debug"), 1, obj);
}
extern void rb_log_file(const char* str)
{
rb_funcall(rb_gv_get("$log"), rb_intern("log"), 1, rb_str_new2(str));
}
extern void rb_log_file_obj(VALUE obj)
{
rb_funcall(rb_gv_get("$log"), rb_intern("log"), 1, obj);
}
#endif | 2.078125 | 2 |
2024-11-18T21:30:13.917311+00:00 | 2023-08-25T08:03:33 | e7528d28bfe74145f0d013693b2851abb5e68dc5 | {
"blob_id": "e7528d28bfe74145f0d013693b2851abb5e68dc5",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-25T08:03:33",
"content_id": "ef28e1ec1add119b81c511581f65c9a4a862792e",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "df90ed23a49dba79f61e5a28366424f0ecec60de",
"extension": "c",
"filename": "main.c",
"fork_events_count": 12,
"gha_created_at": "2016-07-29T20:43:25",
"gha_event_created_at": "2021-02-03T17:18:22",
"gha_language": "C++",
"gha_license_id": "NOASSERTION",
"github_id": 64509332,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2041,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/examples/misc/rescipher/src/main.c",
"provenance": "stackv2-0112.json.gz:191301",
"repo_name": "Damdoshi/LibLapin",
"revision_date": "2023-08-25T08:03:33",
"revision_id": "41491d3d3926b8e42e3aec8d1621340501841aae",
"snapshot_id": "306e8ae8be70be9e4de93db60913c4f092a714a7",
"src_encoding": "UTF-8",
"star_events_count": 39,
"url": "https://raw.githubusercontent.com/Damdoshi/LibLapin/41491d3d3926b8e42e3aec8d1621340501841aae/examples/misc/rescipher/src/main.c",
"visit_date": "2023-09-03T10:11:06.743172"
} | stackv2 | /*
** Jason Brillante "Damdoshi"
** Hanged Bunny Studio 2014-2017
**
** Bibliotheque Lapin
*/
#include <string.h>
#include <lapin.h>
t_bunny_window *win;
t_bunny_picture *pic;
/* ashiciphs : a shitty ciphering system */
static void ashiciph(char *data,
size_t len,
void *dat,
bool cipher)
{
(void)data;
(void)len;
(void)dat;
(void)cipher;
if (cipher)
{
bunny_cipher_data(data, len, BS_CAESAR, dat);
bunny_cipher_data(data, len, BS_XOR, dat);
bunny_cipher_data(data, len, BS_SHAKER, dat);
bunny_cipher_data(data, len, BS_SWITCH, dat);
}
else
{
bunny_uncipher_data(data, len, BS_SWITCH, dat);
bunny_uncipher_data(data, len, BS_SHAKER, dat);
bunny_uncipher_data(data, len, BS_XOR, dat);
bunny_uncipher_data(data, len, BS_CAESAR, dat);
}
}
t_bunny_response keyexit(t_bunny_event_state state,
t_bunny_keysym sym,
void *data)
{
(void)sym;
(void)data;
if (state == GO_DOWN)
return (EXIT_ON_SUCCESS);
return (GO_ON);
}
t_bunny_response loop(void *data)
{
(void)data;
bunny_display(win);
return (GO_ON);
}
int main(int argc,
char **argv)
{
const char *key_content = "abcdef";
size_t len = strlen(key_content);
t_bunny_cipher_key *key = bunny_alloca(sizeof(*key) + len + 1);
strcpy(&key->key[0], key_content);
key->length = len;
gl_bunny_ressource_ciphering = ashiciph;
gl_bunny_ressource_data = key;
if (argc != 2)
{
printf("%s picture_file\n", argv[0]);
return (EXIT_FAILURE);
}
if ((pic = bunny_load_picture(argv[1])) == NULL)
return (EXIT_FAILURE);
if ((win = bunny_start
(pic->buffer.width, pic->buffer.height, false, "Picture cipher")) == NULL)
{
bunny_delete_clipable(pic);
return (EXIT_FAILURE);
}
bunny_set_key_response(keyexit);
bunny_set_loop_main_function(loop);
bunny_blit(&win->buffer, pic, NULL);
bunny_loop(win, 20, NULL);
bunny_delete_clipable(pic);
bunny_stop(win);
return (EXIT_SUCCESS);
}
| 2.640625 | 3 |
2024-11-18T21:30:14.170668+00:00 | 2023-07-28T18:29:40 | 153befa6a6136bd16a42c9ab28b5487353339f12 | {
"blob_id": "153befa6a6136bd16a42c9ab28b5487353339f12",
"branch_name": "refs/heads/master",
"committer_date": "2023-07-28T18:29:40",
"content_id": "a59a901bb23c7465022825832e82126c8a2882da",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "93bbfb0b9e3b2e9beabc8bc1faf3aefeffada3ad",
"extension": "h",
"filename": "output.h",
"fork_events_count": 60,
"gha_created_at": "2016-06-14T18:33:32",
"gha_event_created_at": "2023-07-28T18:10:43",
"gha_language": "Verilog",
"gha_license_id": "Apache-2.0",
"github_id": 61146698,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1367,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/test/basic_tests/rdl_fieldstruct/golden/output.h",
"provenance": "stackv2-0112.json.gz:191825",
"repo_name": "Juniper/open-register-design-tool",
"revision_date": "2023-07-28T18:29:40",
"revision_id": "bb9d0072dd07ceeccfd285f0fec04625cf99c1df",
"snapshot_id": "4970783eb40d83d863c0a82904687c0f21259932",
"src_encoding": "UTF-8",
"star_events_count": 182,
"url": "https://raw.githubusercontent.com/Juniper/open-register-design-tool/bb9d0072dd07ceeccfd285f0fec04625cf99c1df/test/basic_tests/rdl_fieldstruct/golden/output.h",
"visit_date": "2023-08-28T14:45:06.964154"
} | stackv2 | // Ordt 230719.01 autogenerated file
// Input: ./rdl_fieldstruct/test.rdl
// Parms: ./rdl_fieldstruct/test.parms
// Date: Thu Jul 20 13:46:42 EDT 2023
//
#ifndef __FOO_REGISTER_MAP__
#define __FOO_REGISTER_MAP__
#include <bits.h>
/* FOO_REGISTERS memory map */
enum FOO_REGS {
AREG_0 = 0x0,
AREG_1 = 0x4,
BLABLA = 0x8
};
/* AREG_0 register fields */
#define AREG_0_HIER_FS_FS1_FLD1 GENMASK(3, 0)
#define AREG_0_HIER_FS_FS1_FLD2 BIT(4)
#define AREG_0_HIER_FS_FLD1 BIT(5)
#define AREG_0_HIER_FS_FS2_FLD1 GENMASK(9, 6)
#define AREG_0_HIER_FS_FS2_FLD2 BIT(14)
#define AREG_0_FS3_FLD1 GENMASK(27, 24)
#define AREG_0_FS3_FLD2 BIT(28)
/* AREG_1 register fields */
#define AREG_1_HIER_FS_FS1_FLD1 GENMASK(3, 0)
#define AREG_1_HIER_FS_FS1_FLD2 BIT(4)
#define AREG_1_HIER_FS_FLD1 BIT(5)
#define AREG_1_HIER_FS_FS2_FLD1 GENMASK(9, 6)
#define AREG_1_HIER_FS_FS2_FLD2 BIT(14)
#define AREG_1_FS3_FLD1 GENMASK(27, 24)
#define AREG_1_FS3_FLD2 BIT(28)
/* BLABLA register fields */
#define BLABLA_FS1_0_FLD1 GENMASK(3, 0)
#define BLABLA_FS1_0_FLD2 BIT(4)
#define BLABLA_FS1_1_FLD1 GENMASK(8, 5)
#define BLABLA_FS1_1_FLD2 BIT(9)
#define BLABLA_FS1_2_FLD1 GENMASK(13, 10)
#define BLABLA_FS1_2_FLD2 BIT(14)
#define BLABLA_FS3_0_FLD1 GENMASK(18, 15)
#define BLABLA_FS3_0_FLD2 BIT(19)
#define BLABLA_FS3_1_FLD1 GENMASK(26, 23)
#define BLABLA_FS3_1_FLD2 BIT(27)
#endif
| 2.078125 | 2 |
2024-11-18T21:30:14.547796+00:00 | 2019-02-10T16:04:12 | 409eccd9ee1161f07d9489dde4158ce9dc5db596 | {
"blob_id": "409eccd9ee1161f07d9489dde4158ce9dc5db596",
"branch_name": "refs/heads/master",
"committer_date": "2019-02-10T16:04:12",
"content_id": "4edb2d4923fad9e38a70c493f806830dbdc94ffc",
"detected_licenses": [
"MIT"
],
"directory_id": "d1706d7efbea7783b6910e05f276862eb85142d2",
"extension": "c",
"filename": "zoo.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": 696,
"license": "MIT",
"license_type": "permissive",
"path": "/modules/zoo.c",
"provenance": "stackv2-0112.json.gz:192340",
"repo_name": "svein83/deark",
"revision_date": "2019-02-10T16:04:12",
"revision_id": "1c99d2ce8efac9dc07b8e45f6949bcd566903183",
"snapshot_id": "5ec31279c8c7c478c61a42fe8086f6720aa21a2e",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/svein83/deark/1c99d2ce8efac9dc07b8e45f6949bcd566903183/modules/zoo.c",
"visit_date": "2020-04-22T10:29:38.684372"
} | stackv2 | // This file is part of Deark.
// Copyright (C) 2017 Jason Summers
// See the file COPYING for terms of use.
// ZOO compressed archive format
#include <deark-config.h>
#include <deark-private.h>
#include "../foreign/unzoo.h"
#include "../foreign/zoo-lzd.h"
DE_DECLARE_MODULE(de_module_zoo);
static void de_run_zoo(deark *c, de_module_params *mparams)
{
ExtrArch(c, c->infile);
}
static int de_identify_zoo(deark *c)
{
if(!dbuf_memcmp(c->infile, 20, "\xdc\xa7\xc4\xfd", 4))
return 100;
return 0;
}
void de_module_zoo(deark *c, struct deark_module_info *mi)
{
mi->id = "zoo";
mi->desc = "ZOO compressed archive format";
mi->run_fn = de_run_zoo;
mi->identify_fn = de_identify_zoo;
}
| 2 | 2 |
2024-11-18T21:30:15.433531+00:00 | 2014-05-28T18:17:34 | 3639baf7479125f77b9cf02d1a14711721c82b4f | {
"blob_id": "3639baf7479125f77b9cf02d1a14711721c82b4f",
"branch_name": "refs/heads/master",
"committer_date": "2014-05-28T18:17:34",
"content_id": "3ea057bb3d7cdc29d96ef26c381e57b0e5ebc1f0",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "cd650000a8467b1d84492fc18e1ffd9c1141877a",
"extension": "c",
"filename": "tcpm.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": 5262,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/tcpm/tcpm.c",
"provenance": "stackv2-0112.json.gz:192859",
"repo_name": "wxue/UnixTools",
"revision_date": "2014-05-28T18:17:34",
"revision_id": "4ad068d8ea6c09afade9a46ad9bcb6f78e181c30",
"snapshot_id": "dcefdbfc84a27a366fb698b4b2f8a4ecf7f424e3",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/wxue/UnixTools/4ad068d8ea6c09afade9a46ad9bcb6f78e181c30/tcpm/tcpm.c",
"visit_date": "2020-05-03T11:46:30.266912"
} | stackv2 | /* $NetBSD: tcpm.c,v 0.02 2013/09/17 00:25:22 Weiyu Exp $ */
/* Copyright (c) 2013, Weiyu Xue
* 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. 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 WEIYU XUE "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 WEIYU XUE BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
/*
* Functions
*/
void
checkArgc(int argc){
if (argc != 3){
printf("Usage: tcpm source_file target_file\n");
printf(" tcpm source_file ... target_directory\n");
exit(EXIT_FAILURE);
}
}
char *
nameFilter(char *file_name){
char *p_name = strtok(file_name,"/");
while (p_name != NULL) {
file_name = p_name;
p_name = strtok(NULL,"/");
}
return file_name;
}
int
createFile(char *src_file, char *trgt_file) {
int fd;
/*
* Set O_TRUNC: If the file exists and is a regular file, and the file is
* successfully opened O_RDWR or O_WRONLY, its length is truncated to 0 and
* the mode and owner are unchanged.
*/
if ((fd = open(trgt_file, O_RDWR | O_CREAT | O_TRUNC,
S_IRUSR | S_IWUSR)) == -1) {
/*
* If trget_file is a directory, give it the same name as
* its source file.
*/
/* Errno 21: Can't open a directory. */
if (errno == 21){
(void)close(fd);
strcpy(trgt_file+strlen(trgt_file),"/");
strcpy(trgt_file+strlen(trgt_file),src_file);
if ((fd = open(trgt_file, O_RDWR | O_CREAT,
S_IRUSR | S_IWUSR)) == -1){
fprintf(stderr, "Unable to create 'trgt_file': %s\n",
strerror(errno));
exit(EXIT_FAILURE);
}
}
else{
fprintf(stderr, "Unable to create 'trgt_file': %s\n",
strerror(errno));
exit(EXIT_FAILURE);
}
}
return fd;
}
int
openFile(char *src_file){
int fd;
if ((fd = open(src_file, O_RDONLY | O_APPEND)) == -1) {
fprintf(stderr, "Unable to open '%s': %s\n", src_file,
strerror(errno));
exit(EXIT_FAILURE);
}
return fd;
}
int
getSize(int fd){
struct stat stat_src;
if (fstat(fd, &stat_src) == -1){
fprintf(stderr, "Unable to get file source status: %s\n",
strerror(errno));
exit(EXIT_FAILURE);
}
return stat_src.st_size;
}
/*
* Main
*/
int
main(int argc, char *argv[])
{
int fd_src, fd_trgt, file_size;
char *file_name;
char *addr_src; char *addr_trgt;
/* This works on BSD, but not in the stdlib on Linux. */
setprogname(argv[0]);
/* Check the command and show the correct usage if meets any error */
checkArgc(argc);
/* Set file name.(Avoiding change argv[1])*/
int length;
length = strlen(argv[1]);
char changeable_name[length];
strcpy(changeable_name, argv[1]);
file_name = changeable_name;
/* Get the source file name only.(Get rid of its path.) */
file_name = nameFilter(file_name);
/*
* Create a target file in the directory as declared in the command or
* in the current directory if path is given.
* Then get its file descriptor.
*/
fd_trgt = createFile(file_name, argv[2]);
/* Open the source file and get its file descriptor*/
fd_src = openFile(argv[1]);
/* Get file size. */
file_size = getSize(fd_src);
/* Make the target file a hole file, same size with the source file.*/
char buf[file_size];
if (write(fd_trgt, buf, file_size) != file_size){
perror("Error writing hole-target_file");
return 1;
}
/* mmap both source file and target file. */
addr_src = mmap(NULL, file_size, PROT_READ, MAP_PRIVATE, fd_src, 0);
addr_trgt = mmap(NULL, file_size, PROT_READ | PROT_WRITE, MAP_SHARED,
fd_trgt, 0);
/* length + 1 for the string's end-char '\0' */
memcpy(addr_trgt, addr_src, file_size+1);
/* unmap the files */
munmap(addr_src, file_size);
munmap(addr_trgt, file_size);
return 0;
} | 2.1875 | 2 |
2024-11-18T21:30:15.825551+00:00 | 2020-06-09T21:15:37 | c83aadb45e8a6bdd9c18c0e9e9f93fab7737eb86 | {
"blob_id": "c83aadb45e8a6bdd9c18c0e9e9f93fab7737eb86",
"branch_name": "refs/heads/master",
"committer_date": "2020-06-09T21:15:37",
"content_id": "942630af49613adf7ab7db4fa864c15a9ecb8edf",
"detected_licenses": [
"MIT"
],
"directory_id": "ca75f7099b93d8083d5b2e9c6db2e8821e63f83b",
"extension": "c",
"filename": "535794538.c",
"fork_events_count": 0,
"gha_created_at": "2020-05-08T10:10:47",
"gha_event_created_at": "2020-06-09T21:15:38",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 262290632,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1433,
"license": "MIT",
"license_type": "permissive",
"path": "/z2/part1/jm/random/535794538.c",
"provenance": "stackv2-0112.json.gz:193120",
"repo_name": "kozakusek/ipp-2020-testy",
"revision_date": "2020-06-09T21:15:37",
"revision_id": "09aa008fa53d159672cc7cbf969a6b237e15a7b8",
"snapshot_id": "210ed201eaea3c86933266bd57ee284c9fbc1b96",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/kozakusek/ipp-2020-testy/09aa008fa53d159672cc7cbf969a6b237e15a7b8/z2/part1/jm/random/535794538.c",
"visit_date": "2022-10-04T18:55:37.875713"
} | stackv2 | #include <stdint.h>
#include <stdlib.h>
#include <assert.h>
#include <stdio.h>
#include "gamma.h"
#include <stdbool.h>
#include <string.h>
int main() {
/*
scenario: test_random_actions
uuid: 535794538
*/
/*
random actions, total chaos
*/
gamma_t* board = gamma_new(7, 1, 7, 5);
assert( board != NULL );
assert( gamma_move(board, 1, 0, 0) == 1 );
assert( gamma_move(board, 1, 4, 0) == 1 );
assert( gamma_move(board, 2, 0, 3) == 0 );
assert( gamma_move(board, 3, 3, 0) == 1 );
assert( gamma_move(board, 3, 4, 0) == 0 );
assert( gamma_move(board, 4, 1, 0) == 1 );
assert( gamma_move(board, 5, 0, 5) == 0 );
assert( gamma_move(board, 6, 3, 0) == 0 );
assert( gamma_move(board, 6, 5, 0) == 1 );
assert( gamma_busy_fields(board, 6) == 1 );
assert( gamma_golden_possible(board, 6) == 1 );
assert( gamma_move(board, 7, 4, 0) == 0 );
char* board664125696 = gamma_board(board);
assert( board664125696 != NULL );
assert( strcmp(board664125696,
"14.316.\n") == 0);
free(board664125696);
board664125696 = NULL;
assert( gamma_move(board, 1, 3, 0) == 0 );
assert( gamma_move(board, 2, 0, 2) == 0 );
assert( gamma_move(board, 3, 1, 0) == 0 );
assert( gamma_move(board, 4, 0, 2) == 0 );
assert( gamma_move(board, 5, 0, 2) == 0 );
assert( gamma_move(board, 5, 0, 0) == 0 );
assert( gamma_move(board, 6, 0, 6) == 0 );
assert( gamma_move(board, 7, 2, 0) == 1 );
assert( gamma_move(board, 7, 0, 0) == 0 );
gamma_delete(board);
return 0;
}
| 2.359375 | 2 |
2024-11-18T21:30:15.889713+00:00 | 2017-10-06T09:16:03 | 9760891f3ee8a26cedb903d8f3d67b19fd4153ee | {
"blob_id": "9760891f3ee8a26cedb903d8f3d67b19fd4153ee",
"branch_name": "refs/heads/master",
"committer_date": "2017-10-06T09:16:03",
"content_id": "851378280a64f048030c493005080d93a2c4d080",
"detected_licenses": [
"MIT"
],
"directory_id": "007aabb633548fcaba33d33bb7523c563785ce41",
"extension": "h",
"filename": "xmalloc.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 93598369,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1707,
"license": "MIT",
"license_type": "permissive",
"path": "/include/il/adt/xmalloc.h",
"provenance": "stackv2-0112.json.gz:193251",
"repo_name": "uael/il",
"revision_date": "2017-10-06T09:16:03",
"revision_id": "cdb889ddacd2af9c5108bcc35a41f2c0febf5286",
"snapshot_id": "1bcb0b3ed4962420427d44f83cff41c2746a60fb",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/uael/il/cdb889ddacd2af9c5108bcc35a41f2c0febf5286/include/il/adt/xmalloc.h",
"visit_date": "2021-01-25T06:44:38.934955"
} | stackv2 | /*
* libil - Intermediate Language cross-platform c library
* Copyright (C) 2016-2017 Lucas Abel <www.github.com/uael>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library; if not, see <http://www.gnu.org/licenses/>
*/
#ifndef IL_XMALLOC_H__
# define IL_XMALLOC_H__
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
/* Includes for alloca() */
#ifndef alloca
# if defined(__GNUC__)
# define alloca(x) __builtin_alloca(x)
# elif defined(_WIN32)
# include <malloc.h>
# ifdef _alloca
# define alloca _alloca
# endif
# else
# error do not know how to get alloca
# endif
#endif
/**
* Allocate @p size bytes on the heap.
* This is a wrapper for malloc which calls panic() in case of errors, so no
* error handling is required for code using it.
*/
void *xmalloc(size_t size);
/**
* Chane size of a previously allocated memory block to @p size bytes.
* This is a wrapper for realloc which calls panic() in case of errors, so no
* error handling is required for code using it.
*/
void *xrealloc(void *ptr, size_t size);
void *xcalloc(size_t num, size_t size);
void xfree(void *ptr);
#endif /* IL_XMALLOC_H__ */
| 2.140625 | 2 |
2024-11-18T21:30:16.462273+00:00 | 2017-03-23T23:21:15 | c794f4bdff57d85672603b2a81cd392cc53a83d2 | {
"blob_id": "c794f4bdff57d85672603b2a81cd392cc53a83d2",
"branch_name": "refs/heads/master",
"committer_date": "2017-03-23T23:21:15",
"content_id": "fe870ac08884fe8c03f02af58b5795315debc797",
"detected_licenses": [
"MIT"
],
"directory_id": "67df5b1d7d1ecbf15b8ca3259ba01d693d08a978",
"extension": "h",
"filename": "Sistema.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 86006553,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4893,
"license": "MIT",
"license_type": "permissive",
"path": "/Desenvolvimento/app/Strassen/include/Sistema.h",
"provenance": "stackv2-0112.json.gz:193387",
"repo_name": "phillpassos/feS.O",
"revision_date": "2017-03-23T23:21:15",
"revision_id": "a1a76abe54fa4a66223f1e4737f2f45a60b26261",
"snapshot_id": "833761f8250013785e509b97129999cff50fe159",
"src_encoding": "ISO-8859-1",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/phillpassos/feS.O/a1a76abe54fa4a66223f1e4737f2f45a60b26261/Desenvolvimento/app/Strassen/include/Sistema.h",
"visit_date": "2021-01-23T02:34:41.525486"
} | stackv2 | #ifndef _SISTEMA
#define _SISTEMA
#define NULL 0
#define INFO_PROCESSOS 1
#define INFO_MENSAGENS 2
#define INFO_MEMORIA 3
#define INFO_VFS 4
//constantes sistema de troca de mensagems
const int MSG_COMUM = -1;
const int MSG_IRQ = -2;
const int MSG_EVT = -3;
const int MSG_QLQR_PORTA = -1;
const int NAO_HA_MSGS = 0;
const int MSG_SUCESSO = 1;
const int MSG_ERR_PROC_NAO_EXISTE = 5;
const int MSG_ERR_PORTA_NAO_ATIVA = 6;
const int MSG_ERR_PORTA_OCUPADA = 7;
//porta para mensagens do kernel
const int KERNEL_PORTA_PROC_CRIADO = 20;
const int KERNEL_PORTA_PROC_DESTRUIDO = 21;
const int KERNEL_PORTA_ALOCADA = 22;
const int KERNEL_PORTA_DESALOCADA = 23;
const int KERNEL_PORTA_VFS = 24;
const int KERNEL_PORTA_EXCEPTION = 25;
//constantes do sistem de arquivos
const int VFS_SUCESSO = 1;
const int VFS_ARQUIVO_EXTERNO = -2;
const int VFS_EOF = -2;
const int VFS_POSICAO_INVALIDA = -5;
const int VFS_ARQUIVO_FECHADO = -6;
const int VFS_ARQUIVO_ABERTO = -7;
const int VFS_DIR_NAO_ENCONTRADO = -8;
const int VFS_SEM_PERMISSAO = -9;
const int VFS_ERR_TAM_MAX_DIR = -10;
const int VFS_ERR_ARQ_NAO_ENCONTRADO = -11;
const int VFS_NOME_INVALIDO = -12;
const int VFS_TENTATIVA_ESCREVER_PASTA = -13;
const int VFS_BLOCO_ABRIR = 1;
const int VFS_BLOCO_LER = 2;
const int VFS_BLOCO_ESCREVER = 3;
const int VFS_BLOCO_EXCLUIR = 4;
const int VFS_BLOCO_FECHAR = 5;
const int VFS_ARQ = 0;
const int VFS_DIR = 1;
const int VFS_MNT = 2;
const int VFS_MNT_DIR = 3;
const int VFS_MNT_ABERTO = 4;
//constantes da gerência de processos
const int PROC_SUCESSO = 1;
const int PROC_FORMATO_INVALIDO = 2;
const int PROC_SEM_MEMORIA = 3;
//struct de eventos do sistema operacional
struct Evento
{
char num;
int param1;
int param2;
char dados[80];
};
struct Arq_Info
{
unsigned char nome[15];
unsigned int offset;
unsigned int tamanho;
unsigned int tamanho_em_disco;
unsigned int pai;
unsigned int tipo;
unsigned int descritor;
unsigned int porta_servidor;
unsigned int flags;
int aberto_por;
char enchimento[60];
}__attribute__((packed));
struct Bloco_Vfs
{
unsigned int cod;
unsigned int pid;
unsigned int descritor;
unsigned char param1;
unsigned char param2;
unsigned char nome[80];
}__attribute__((packed));
//para comunicação com servidor do shell
struct Bloco_Shell
{
int pid;
char arquivo[80];
};
struct Bloco_Resposta
{
int retorno;
char msg[80];
};
//informações do kernel
extern "C" void obter_info_kernel(unsigned char * arquivo, int codigo);
//executar operação do sistema
void sistema(char * comando, Bloco_Resposta * br);
//gerência de memória
extern "C" int sbk(unsigned int tam);
void *kmalloc(unsigned nbytes);
void free(void *ap);
//sistema de troca de mensagens
extern "C" int enviar_msg(unsigned int porta, unsigned char * mensagem);
extern "C" int enviar_msg_pid(unsigned int pid, unsigned char * mensagem);
extern "C" int enviar_receber_msg(unsigned int porta, unsigned char * mensagem);
extern "C" int escutar_porta(unsigned int porta);
extern "C" int receber_msg(unsigned char mensagem[100], int porta);
//sistema de arquivos
extern "C" int _abrir(unsigned char * caminho, char modo, unsigned int * servidor);
extern "C" int _ler(unsigned int descritor, unsigned char * buffer ,unsigned int tam);
extern "C" int _escrever(unsigned int descritor, unsigned char * buffer ,unsigned int tam);
extern "C" int _buscar(unsigned int descritor, unsigned int pos);
extern "C" int _excluir(unsigned int descritor);
extern "C" int _fechar(unsigned int descritor);
extern "C" int _obter_info_arq(unsigned descritor, unsigned char * dados);
extern "C" int _adicionar_no(unsigned char * nome, unsigned int tamanho, unsigned int * novo_descritor, int porta_servidor);
extern "C" int _montar_no(unsigned int novo_descritor);
extern "C" int _remover_no(unsigned int novo_descritor);
//wrappers em c++
int abrir(unsigned char * caminho, char modo);
int ler(unsigned int descritor, unsigned char * buffer ,unsigned int tam);
int escrever(unsigned int descritor, unsigned char * buffer ,unsigned int tam);
int buscar(unsigned int descritor, unsigned int pos);
int excluir(unsigned int descritor);
int fechar(unsigned int descritor);
int obter_info_arq(unsigned descritor, unsigned char * dados);
int adicionar_no(unsigned char * nome, unsigned int tamanho, unsigned int * novo_descritor, int porta_servidor);
int montar_no(unsigned int novo_descritor);
int remover_no(unsigned int novo_descritor);
//processos
extern "C" int _executar(unsigned char * nome, unsigned int argc, unsigned char * args, int descritor);
extern "C" int _obter_pid(int pid_thread);
extern "C" void sair(void);
extern "C" void finalizar_proceso(unsigned int pid);
extern "C" int criar_thread(unsigned int entrada);
int executar(unsigned char * caminho, unsigned int argc, unsigned char * args);
int obter_pid(void);
int obter_pid(int pid_thread);
#endif | 2.140625 | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.