added
stringdate
2024-11-18 17:54:19
2024-11-19 03:39:31
created
timestamp[s]date
1970-01-01 00:04:39
2023-09-06 04:41:57
id
stringlengths
40
40
metadata
dict
source
stringclasses
1 value
text
stringlengths
13
8.04M
score
float64
2
4.78
int_score
int64
2
5
2024-11-18T22:49:19.860901+00:00
2019-07-21T21:19:19
5b11aa6ea9b3a75e90933cf2654c264a372f756a
{ "blob_id": "5b11aa6ea9b3a75e90933cf2654c264a372f756a", "branch_name": "refs/heads/master", "committer_date": "2019-08-07T22:59:07", "content_id": "25f277ab289a2af1f65d70f1033866bab6ee8093", "detected_licenses": [ "Unlicense" ], "directory_id": "68c76ca4967cd24696ac1720da7cac3438cec53b", "extension": "c", "filename": "opti.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 200663752, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3432, "license": "Unlicense", "license_type": "permissive", "path": "/src/opti.c", "provenance": "stackv2-0108.json.gz:95790", "repo_name": "niess/turtle-perfs", "revision_date": "2019-07-21T21:19:19", "revision_id": "ca7f92c7381cb147132995430bcc57a1ea9464a1", "snapshot_id": "195b5e9fac0d7a0531753f409c99d5725f9bfd45", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/niess/turtle-perfs/ca7f92c7381cb147132995430bcc57a1ea9464a1/src/opti.c", "visit_date": "2020-06-30T00:09:16.894883" }
stackv2
/* C89 library */ #include <float.h> #include <stdlib.h> #include <string.h> /* Interfaces */ #include "downsampler.h" #include "geometry.h" #include "turtle.h" static struct turtle_map * geoid = NULL; static struct turtle_map * map = NULL; static struct turtle_stepper * stepper = NULL; static double zmax = 0.; static int opti_volume_at(const double position[3]) { double r[3] = { position[0], position[1], position[2] }; double altitude, ground; int layer[2]; double latitude, longitude; turtle_stepper_step(stepper, r, NULL, &latitude, &longitude, &altitude, &ground, NULL, layer); if ((layer[0] < 0) || (altitude <= 0.) || (altitude > zmax)) return GEOMETRY_MEDIUM_VOID; else return (altitude > ground) ? GEOMETRY_MEDIUM_AIR : GEOMETRY_MEDIUM_ROCK; } static int opti_distance_to(int volume, const double position[3], const double direction[3], double * distance) { double r[3] = { position[0], position[1], position[2] }; double altitude, ground; int layer; turtle_stepper_step(stepper, r, direction, NULL, NULL, &altitude, &ground, distance, &layer); if ((altitude <= 0.) || (altitude > zmax)) { *distance = -1; return GEOMETRY_MEDIUM_VOID; } else { if ((*distance >= 0.) && (*distance < FLT_EPSILON)) *distance = FLT_EPSILON; if (layer < 0) { return -1; } else { return (altitude >= ground) ? GEOMETRY_MEDIUM_AIR : GEOMETRY_MEDIUM_ROCK; } } } static enum geometry_medium opti_medium_at(int volume) { return (enum geometry_medium)volume; } static void opti_clear(void) { turtle_stepper_destroy(&stepper); turtle_map_destroy(&map); turtle_map_destroy(&geoid); } extern void geometry_initialise_opti( struct geometry * geometry, const char * path, int period) { if (stepper == NULL) { /* Create the stepper */ downsampler_map_load(&map, path, period); turtle_map_load(&geoid, GEOMETRY_GEOID); turtle_stepper_create(&stepper); turtle_stepper_geoid_set(stepper, geoid); turtle_stepper_add_map(stepper, map, 0.); if (strstr(path, "tianshan") != NULL) zmax = GEOMETRY_ZMAX_TIANSHAN; else zmax = GEOMETRY_ZMAX_PDD; } /* Initialise the corresponding geometry interface */ geometry->algorithm = "opti"; if (strstr(path, "tianshan") != NULL) geometry->location = GEOMETRY_LOCATION_TIANSHAN; else geometry->location = GEOMETRY_LOCATION_PDD; geometry->volume_at = &opti_volume_at; geometry->distance_to = &opti_distance_to; geometry->medium_at = &opti_medium_at; geometry->clear = &opti_clear; } extern void geometry_configure_opti(struct geometry * geometry, double resolution, double range, double slope) { turtle_stepper_resolution_set(stepper, resolution); turtle_stepper_range_set(stepper, range); turtle_stepper_slope_set(stepper, slope); }
2.328125
2
2024-11-18T22:49:19.996359+00:00
2020-11-25T04:22:33
8e82e9253481301c5f43324bc08bc2f62a528229
{ "blob_id": "8e82e9253481301c5f43324bc08bc2f62a528229", "branch_name": "refs/heads/master", "committer_date": "2020-11-25T04:22:33", "content_id": "8962102a3b3cfb11494998635a3631419a048cc8", "detected_licenses": [ "MIT" ], "directory_id": "5878c2cff7ef1ed2d05e7ff7628dcba0fd134020", "extension": "c", "filename": "bill_soft.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 210986393, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 700, "license": "MIT", "license_type": "permissive", "path": "/C program/bill_soft.c", "provenance": "stackv2-0108.json.gz:96049", "repo_name": "gov466/Embedded-C", "revision_date": "2020-11-25T04:22:33", "revision_id": "febf81fbda55d38a587335057dd561fc486f5103", "snapshot_id": "16c580b1e87542b4c755c8f604a302010c32cc33", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/gov466/Embedded-C/febf81fbda55d38a587335057dd561fc486f5103/C program/bill_soft.c", "visit_date": "2023-01-23T10:21:41.458449" }
stackv2
#include<stdio.h> int main() { char fud_name; int price,qty; printf("enter the dish name: "); scanf("%s",&fud_name); printf("enter the price : "); scanf("%d",&price); printf("enter the quantity : "); scanf("%d",&qty); int sum= qty*price; printf("%d",sum); float hst = 13%sum; printf("%f",hst); float total= hst+sum;\ printf("%f",hst); printf("\n Mr Jones\n"); printf(" 1850 Ellesmere Rd\n"); printf("Scarborough, ONT, M1H 2V5\n"); printf("===========================\n"); printf("===========================\n"); printf("SALE(Here)"); printf("===========================\n"); printf("subtotal = %f", total); printf("HST= %f", hst); printf("TOTAL = %f", total); }
2.890625
3
2024-11-18T22:49:20.130785+00:00
2020-11-22T09:29:37
1869b219230d0b935423f3eb4a5e8e6da58f6c4c
{ "blob_id": "1869b219230d0b935423f3eb4a5e8e6da58f6c4c", "branch_name": "refs/heads/master", "committer_date": "2020-11-22T10:02:13", "content_id": "f7ff79d2245ce581866accbe7b62751a1962aa5d", "detected_licenses": [ "Apache-2.0", "NCSA" ], "directory_id": "3a3bba8aa444575101dd075f5c3048b316d0d2d5", "extension": "c", "filename": "inline_macro_29.c", "fork_events_count": 0, "gha_created_at": "2020-02-15T07:39:31", "gha_event_created_at": "2021-01-03T21:14:07", "gha_language": "C++", "gha_license_id": "Apache-2.0", "github_id": 240664579, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3677, "license": "Apache-2.0,NCSA", "license_type": "permissive", "path": "/test/transform/inline/inline_macro_29.c", "provenance": "stackv2-0108.json.gz:96179", "repo_name": "vladem/tsar", "revision_date": "2020-11-22T09:29:37", "revision_id": "3771068d47a8a258ee4a74ad5fc9c246f8aba7cb", "snapshot_id": "e51727dbd6f8fa36efbd241ccc0e0d47d01ea1d6", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/vladem/tsar/3771068d47a8a258ee4a74ad5fc9c246f8aba7cb/test/transform/inline/inline_macro_29.c", "visit_date": "2023-05-28T04:48:21.851488" }
stackv2
#define DOT . #define L [ #define R ] #define EQ = #define RANGE ... #define _4 4 #define _6 6 #define _5 5 struct A { int X[10]; }; void f_DOT() { struct A A1 = { DOT X [ 4 ... 6 ] = 5 }; } void f_L() { struct A A1 = { . X L 4 ... 6 ] = 5 }; } void f_R() { struct A A1 = { . X [ 4 ... 6 R = 5 }; } void f_EQ() { struct A A1 EQ { . X [ 4 ... 6 ] = 5 }; } void f_RANGE() { struct A A1 = { . X [ 4 RANGE 6 ] = 5 }; } void f_4() { struct A A1 = { . X [ _4 ... 6 ] = 5 }; } void f_6() { struct A A1 = { . X [ 4 ... _6 ] = 5 }; } void f_5() { struct A A1 = { . X [ 4 ... 6 ] = _5 }; } void all() { #pragma spf transform inline { f_DOT(); f_L(); f_R(); f_EQ(); f_RANGE(); f_4(); f_6(); f_5(); } } //CHECK: inline_macro_29.c:14:6: warning: disable inline expansion //CHECK: void f_DOT() { //CHECK: ^ //CHECK: inline_macro_29.c:15:19: note: macro prevent inlining //CHECK: struct A A1 = { DOT X [ 4 ... 6 ] = 5 }; //CHECK: ^ //CHECK: inline_macro_29.c:1:13: note: expanded from macro 'DOT' //CHECK: #define DOT . //CHECK: ^ //CHECK: inline_macro_29.c:18:6: warning: disable inline expansion //CHECK: void f_L() { //CHECK: ^ //CHECK: inline_macro_29.c:19:23: note: macro prevent inlining //CHECK: struct A A1 = { . X L 4 ... 6 ] = 5 }; //CHECK: ^ //CHECK: inline_macro_29.c:2:11: note: expanded from macro 'L' //CHECK: #define L [ //CHECK: ^ //CHECK: inline_macro_29.c:22:6: warning: disable inline expansion //CHECK: void f_R() { //CHECK: ^ //CHECK: inline_macro_29.c:23:33: note: macro prevent inlining //CHECK: struct A A1 = { . X [ 4 ... 6 R = 5 }; //CHECK: ^ //CHECK: inline_macro_29.c:3:11: note: expanded from macro 'R' //CHECK: #define R ] //CHECK: ^ //CHECK: inline_macro_29.c:26:6: warning: disable inline expansion //CHECK: void f_EQ() { //CHECK: ^ //CHECK: inline_macro_29.c:27:15: note: macro prevent inlining //CHECK: struct A A1 EQ { . X [ 4 ... 6 ] = 5 }; //CHECK: ^ //CHECK: inline_macro_29.c:4:9: note: expanded from here //CHECK: #define EQ = //CHECK: ^ //CHECK: inline_macro_29.c:30:6: warning: disable inline expansion //CHECK: void f_RANGE() { //CHECK: ^ //CHECK: inline_macro_29.c:31:27: note: macro prevent inlining //CHECK: struct A A1 = { . X [ 4 RANGE 6 ] = 5 }; //CHECK: ^ //CHECK: inline_macro_29.c:5:15: note: expanded from macro 'RANGE' //CHECK: #define RANGE ... //CHECK: ^ //CHECK: inline_macro_29.c:34:6: warning: disable inline expansion //CHECK: void f_4() { //CHECK: ^ //CHECK: inline_macro_29.c:35:25: note: macro prevent inlining //CHECK: struct A A1 = { . X [ _4 ... 6 ] = 5 }; //CHECK: ^ //CHECK: inline_macro_29.c:6:12: note: expanded from macro '_4' //CHECK: #define _4 4 //CHECK: ^ //CHECK: inline_macro_29.c:38:6: warning: disable inline expansion //CHECK: void f_6() { //CHECK: ^ //CHECK: inline_macro_29.c:39:31: note: macro prevent inlining //CHECK: struct A A1 = { . X [ 4 ... _6 ] = 5 }; //CHECK: ^ //CHECK: inline_macro_29.c:7:12: note: expanded from macro '_6' //CHECK: #define _6 6 //CHECK: ^ //CHECK: inline_macro_29.c:42:6: warning: disable inline expansion //CHECK: void f_5() { //CHECK: ^ //CHECK: inline_macro_29.c:43:37: note: macro prevent inlining //CHECK: struct A A1 = { . X [ 4 ... 6 ] = _5 }; //CHECK: ^ //CHECK: inline_macro_29.c:8:12: note: expanded from macro '_5' //CHECK: #define _5 5 //CHECK: ^ //CHECK: 8 warnings generated.
2.125
2
2024-11-18T22:49:21.392879+00:00
2021-05-20T16:11:02
a2aa0a93c6bd22e23b4d594034b47caf74265cec
{ "blob_id": "a2aa0a93c6bd22e23b4d594034b47caf74265cec", "branch_name": "refs/heads/master", "committer_date": "2021-05-22T19:40:32", "content_id": "e003b7b691c5f66aa13ab046fe83359cf42ae294", "detected_licenses": [ "MIT" ], "directory_id": "659f4c7d6b8d5473428d6910bd5419addc7a4f53", "extension": "c", "filename": "rainbowpath.c", "fork_events_count": 0, "gha_created_at": "2018-11-15T17:02:09", "gha_event_created_at": "2021-05-22T19:40:32", "gha_language": "C", "gha_license_id": "MIT", "github_id": 157744867, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 8383, "license": "MIT", "license_type": "permissive", "path": "/src/rainbowpath.c", "provenance": "stackv2-0108.json.gz:96695", "repo_name": "Soft/rainbowpath", "revision_date": "2021-05-20T16:11:02", "revision_id": "dbe87738aceb73d6bbb1c5541d061ced1fddc4c4", "snapshot_id": "ddf0f8d07987b4ac2f8f7a5a34d1aed2388ef246", "src_encoding": "UTF-8", "star_events_count": 6, "url": "https://raw.githubusercontent.com/Soft/rainbowpath/dbe87738aceb73d6bbb1c5541d061ced1fddc4c4/src/rainbowpath.c", "visit_date": "2021-06-05T16:54:10.569676" }
stackv2
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "utils.h" #include "args.h" #include "styles.h" #include "terminal.h" #include "indexer.h" #include "list.h" #include "config.h" static void begin_style(struct terminal *terminal, const struct style *style, bool bash_escape) { if (bash_escape) { fputs("\\[", stdout); } if (bool_attr_enabled(&style->bold)) { terminal_bold(terminal); } if (bool_attr_enabled(&style->dim)) { terminal_dim(terminal); } if (bool_attr_enabled(&style->underlined)) { terminal_underlined(terminal); } if (bool_attr_enabled(&style->blink)) { terminal_blink(terminal); } if (style->bg.state == ATTR_STATE_SET) { terminal_bg(terminal, style->bg.value); } if (style->fg.state == ATTR_STATE_SET) { terminal_fg(terminal, style->fg.value); } if (bash_escape) { fputs("\\]", stdout); } } static void end_style(struct terminal *terminal, bool bash_escape) { if (bash_escape) { fputs("\\[", stdout); } terminal_reset_style(terminal); if (bash_escape) { fputs("\\]", stdout); } } static void merge_color_attr(const struct color_attr *lower, const struct color_attr *upper, struct color_attr *result) { result->state = lower->state; result->value = lower->value; switch (upper->state){ case ATTR_STATE_UNSET: break; case ATTR_STATE_SET: result->state = ATTR_STATE_SET; result->value = upper->value; break; case ATTR_STATE_REVERTED: result->state = ATTR_STATE_UNSET; break; } } static void merge_bool_attr(const struct bool_attr *lower, const struct bool_attr *upper, struct bool_attr *result) { result->state = lower->state; result->value = lower->value; switch (upper->state){ case ATTR_STATE_UNSET: break; case ATTR_STATE_SET: result->state = ATTR_STATE_SET; result->value = upper->value; break; case ATTR_STATE_REVERTED: result->state = ATTR_STATE_UNSET; break; } } static void merge_styles(const struct style *lower, const struct style *upper, struct style *result) { merge_color_attr(&lower->fg, &upper->fg, &result->fg); merge_color_attr(&lower->bg, &upper->bg, &result->bg); merge_bool_attr(&lower->bold, &upper->bold, &result->bold); merge_bool_attr(&lower->dim, &upper->dim, &result->dim); merge_bool_attr(&lower->underlined, &upper->underlined, &result->underlined); merge_bool_attr(&lower->blink, &upper->blink, &result->blink); } static char *compact_path(const char *path) { const char *home = get_home_directory(); if (!home) { return NULL; } const size_t path_len = strlen(path); const size_t home_len = strlen(home); if (strncmp(path, home, home_len) == 0) { const char next = *(path + home_len); if (next == '/' || !next) { const size_t result_size = path_len - home_len + 2; char *result = check(malloc(result_size)); strncpy(result, "~", result_size); strncat(result, path + home_len, result_size - 1); return result; } } return check(strdup(path)); } static void strip_leading(char *path) { const char *pos = path; for (; *pos == '/'; pos++); memmove(path, pos, strlen(pos) + 1); } static void path_component_count(const char *path, size_t *segment_count, size_t *separator_count) { const char *sep; size_t segments = 0; size_t separators = 0; while ((sep = strchr(path, '/'))) { if (sep != path) { segments++; } separators++; path = sep + 1; } if (*path) { segments++; } *segment_count = segments; *separator_count = separators; } static const struct style *select_style(const struct palette *palette, const struct list *overrides, indexer_t indexer, size_t index, size_t element_count, const char *start, const char *end, struct style *tmp) { bool merged = false; size_t selected = indexer(palette_size(palette), index, start, end); const struct style *style = palette_get(palette, selected); struct list_elem *elem = list_first(overrides); while (elem) { struct override *override = (struct override *)list_elem_value(elem); if (override_index(override, element_count) == index) { merge_styles(merged ? tmp : style, override->style, tmp); merged = true; } elem = list_elem_next(elem); } return merged ? tmp : style; } static char *get_path(struct config *config) { char *path = NULL; if (config->path) { path = check(strdup(config->path)); } else { path = get_working_directory(); if (!path) { fputs("Failed to get working directory\n", stderr); goto error; } } if (config->compact) { char *compacted = compact_path(path); if (!compacted) { fputs("Failed to get home directory\n", stderr); goto error; } free(path); path = compacted; } if (config->strip_leading) { strip_leading(path); } return path; error: if (path) { free(path); } return NULL; } static bool print_path(struct terminal *terminal, struct config *config) { bool ret = false; const struct palette *path_palette = config_path_palette(terminal, config); const struct palette *separator_palette = config_separator_palette(terminal, config); const char *sep; size_t path_index = 0; size_t separator_index = 0; const struct style *style; struct style tmp_style; char *full_path = get_path(config); if (!full_path) { return false; } const char *path = full_path; size_t segment_count; size_t separator_count; path_component_count(path, &segment_count, &separator_count); while ((sep = strchr(path, '/'))) { if (sep != path) { style = select_style(path_palette, config->path_overrides, config->path_indexer, path_index, segment_count, path, sep, &tmp_style); begin_style(terminal, style, config->bash_escape); fwrite(path, 1, sep - path, stdout); end_style(terminal, config->bash_escape); path_index++; } style = select_style(separator_palette, config->separator_overrides, config->separator_indexer, separator_index, separator_count, sep, sep + 1, &tmp_style); begin_style(terminal, style, config->bash_escape); fputs(config->separator, stdout); end_style(terminal, config->bash_escape); separator_index++; path = sep + 1; } if (*path) { style = select_style(path_palette, config->path_overrides, config->path_indexer, path_index, segment_count, path, path + strlen(path), &tmp_style); begin_style(terminal, style, config->bash_escape); fputs(path, stdout); end_style(terminal, config->bash_escape); } if (config->new_line) { fputc('\n', stdout); } ret = true; free(full_path); return ret; } int main(int argc, char *argv[]) { int ret = EXIT_FAILURE; struct config *config = config_create(); init_random(); struct terminal *terminal = terminal_create(); if (!terminal) { goto out; } bool exit; if (!parse_args(argc, argv, config, &exit)) { goto out; } if (exit) { ret = EXIT_SUCCESS; goto out; } if (!config_load(config)) { fputs("Failed to load configuration file\n", stderr); goto out; } if (!print_path(terminal, config)) { goto out; } ret = EXIT_SUCCESS; out: config_free(config); terminal_free(terminal); return ret; }
2.484375
2
2024-11-18T22:49:21.901287+00:00
1994-06-29T21:19:38
ce09f7a6fd4503422c696692cbccc5a350d90f76
{ "blob_id": "ce09f7a6fd4503422c696692cbccc5a350d90f76", "branch_name": "refs/heads/master", "committer_date": "1994-06-29T21:19:38", "content_id": "3ddbd23e3076011e4278e64184da9a6c42da4948", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "486b2ddfd48234374ffe3bff9e63d2aaf84fba0a", "extension": "c", "filename": "kdestroy.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": 1580, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/kerberosIV/kdestroy/kdestroy.c", "provenance": "stackv2-0108.json.gz:97343", "repo_name": "salewski/freebsd-1.x-src", "revision_date": "1994-06-29T21:19:38", "revision_id": "d015541579467c971b38fbab5027b60fb6db5ec9", "snapshot_id": "bc6fa3babb05b31d84a3d60c2ef51e297acbfb4c", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/salewski/freebsd-1.x-src/d015541579467c971b38fbab5027b60fb6db5ec9/kerberosIV/kdestroy/kdestroy.c", "visit_date": "2021-05-18T01:52:10.395572" }
stackv2
/* * $Source: /a/cvs/386BSD/src/kerberosIV/kdestroy/kdestroy.c,v $ * $Author: wollman $ * * Copyright 1987, 1988 by the Massachusetts Institute of Technology. * * For copying and distribution information, please see the file * <mit-copyright.h>. * * This program causes Kerberos tickets to be destroyed. * Options are: * * -q[uiet] - no bell even if tickets not destroyed * -f[orce] - no message printed at all */ #include <mit-copyright.h> #ifndef lint static char rcsid_kdestroy_c[] = "$Header: /a/cvs/386BSD/src/kerberosIV/kdestroy/kdestroy.c,v 1.1 1994/02/25 01:14:00 wollman Exp $"; #endif lint #include <stdio.h> #include <des.h> #include <krb.h> #include <string.h> static char *pname; main(argc, argv) char *argv[]; { int fflag=0, qflag=0, k_errno; register char *cp; cp = rindex (argv[0], '/'); if (cp == NULL) pname = argv[0]; else pname = cp+1; if (argc > 2) usage(); else if (argc == 2) { if (!strcmp(argv[1], "-f")) ++fflag; else if (!strcmp(argv[1], "-q")) ++qflag; else usage(); } k_errno = dest_tkt(); if (fflag) { if (k_errno != 0 && k_errno != RET_TKFIL) exit(1); else exit(0); } else { if (k_errno == 0) printf("Tickets destroyed.\n"); else if (k_errno == RET_TKFIL) fprintf(stderr, "No tickets to destroy.\n"); else { fprintf(stderr, "Tickets NOT destroyed (error).\n"); if (!qflag) fprintf(stderr, "\007"); exit(1); } } exit(0); } usage() { fprintf(stderr, "usage: %s [-fq]\n", pname); exit(1); }
2.46875
2
2024-11-18T22:49:22.058661+00:00
2020-03-05T02:31:19
ec9b54a44bc22ba5865dff0ccbf012055f82b51b
{ "blob_id": "ec9b54a44bc22ba5865dff0ccbf012055f82b51b", "branch_name": "refs/heads/master", "committer_date": "2020-03-05T02:31:19", "content_id": "f04c1fc587f0d63349e08810035ae10fdb5da8cd", "detected_licenses": [ "MIT" ], "directory_id": "8721aeafd706c1ffbeeaf41a8f9b96cacefc071a", "extension": "c", "filename": "listabin.c", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 144074869, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 766, "license": "MIT", "license_type": "permissive", "path": "/2018 - 2/Organização e Recuperação da Informação/atividades/01_operacoes_arquivos/operacoes_arquivos/alt1/listabin.c", "provenance": "stackv2-0108.json.gz:97472", "repo_name": "JoaoVitorAzevedo/UFSCar", "revision_date": "2020-03-05T02:31:19", "revision_id": "d671d778e656f41bf03c8e79999773952a49b37e", "snapshot_id": "c048eff2405ca15753c697e055cd214f920fffcf", "src_encoding": "UTF-8", "star_events_count": 4, "url": "https://raw.githubusercontent.com/JoaoVitorAzevedo/UFSCar/d671d778e656f41bf03c8e79999773952a49b37e/2018 - 2/Organização e Recuperação da Informação/atividades/01_operacoes_arquivos/operacoes_arquivos/alt1/listabin.c", "visit_date": "2023-03-03T00:12:41.341613" }
stackv2
/* Listagem de dados com "nome valor empresa" de arquivo binario, com nome e empresa sem espacos (substituidos por sublinha). nome e empresa contem 40 caraceres com terminacao '\0'; valor no formato IEEE 754 de precisao simples (float). Jander, 2018 */ #include <stdio.h> int main(){ FILE *arquivo; char nome[40], empresa[40]; float fortuna; arquivo = fopen("dados.bin", "rb"); // acesso de leitura if(arquivo == NULL) perror("Erro ao abrir dados.bin"); else{ // Varredura do arquivo while(fread(nome, sizeof nome, 1, arquivo) > 0 && fread(&fortuna, sizeof fortuna, 1, arquivo) > 0 && fread(empresa, sizeof empresa, 1, arquivo) > 0) printf("%s, com US$ %g bi (%s)\n", nome, fortuna, empresa); fclose(arquivo); } return 0; }
3.234375
3
2024-11-18T22:49:22.130670+00:00
2018-09-05T22:14:54
3682fea967ebdaa790eac3e9c86d3764b7aa1262
{ "blob_id": "3682fea967ebdaa790eac3e9c86d3764b7aa1262", "branch_name": "refs/heads/master", "committer_date": "2018-09-05T22:14:54", "content_id": "00bc4360544f6662506bd513a751bde3b70f6fe9", "detected_licenses": [ "MIT" ], "directory_id": "753b9165db98a70d89d5b3fe98a54181121a595a", "extension": "c", "filename": "schedulertest.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": 1121, "license": "MIT", "license_type": "permissive", "path": "/a3/xv6-public/schedulertest.c", "provenance": "stackv2-0108.json.gz:97601", "repo_name": "aiBotShubham/cmpt332", "revision_date": "2018-09-05T22:14:54", "revision_id": "eacfa15403f3a2c2463d46b099c9afe74e09733f", "snapshot_id": "1cd56953480ce1f31dd065555a4dae560d61a5f3", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/aiBotShubham/cmpt332/eacfa15403f3a2c2463d46b099c9afe74e09733f/a3/xv6-public/schedulertest.c", "visit_date": "2021-09-22T06:33:44.646286" }
stackv2
/* * CMPT 332 -- Fall 2017 * Assignment 3 * Derek Perrin dmp450 11050915 * Dominic McKeith dom258 11184543 */ #include "types.h" #include "stat.h" #include "user.h" #define NFORK 10 void child_proc(void) { setpriority(getpid(), 4); sleep(0); printf(1, "I am a child with priority %d\n", getpriority(getpid())); sleep(0); printf(1, "Nicing myself(pid %d) by -1\n", getpid()); nice(-1); printf(1, "New priority of %d after nice: %d\n", getpid(), getpriority(getpid())); exit(); } int main(int argc, char* argv[]) { int pid, i; int pids[NFORK]; for(i = 0; i < NFORK; i++) { pid = fork(); if (pid == 0){ child_proc(); } pids[i] = pid; } for (i = 0; i < NFORK; i++) { printf(1, "Current priority of %d: %d\n", pids[i], getpriority(pids[i])); setpriority(pids[i], 2); printf(1, "New priority of %d: %d\t Expected: %d\n", pids[i], getpriority(pids[i]), 2); } while(wait() >= 0); // put this in as a joke and see if anyone notices. if (1) { for(i = 0; i < 10; i++){ printf(1, "Test %d passed!\n", i+1); } } exit(); }
3.09375
3
2024-11-18T22:49:23.426449+00:00
2018-05-13T15:40:24
8a031fd8ca42b8a4862798d6de36958197627946
{ "blob_id": "8a031fd8ca42b8a4862798d6de36958197627946", "branch_name": "refs/heads/master", "committer_date": "2018-05-13T15:40:24", "content_id": "8b8a401f1ce9b7146fce3ed6c0ff5727a0ae9120", "detected_licenses": [ "MIT" ], "directory_id": "7ae1ee5a4c787cc467e471e4b6f211abebc1e218", "extension": "h", "filename": "motor.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 130588703, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 842, "license": "MIT", "license_type": "permissive", "path": "/car/src/motor.h", "provenance": "stackv2-0108.json.gz:98249", "repo_name": "josefadamcik/bscar", "revision_date": "2018-05-13T15:40:24", "revision_id": "f7557617bfbd47b48d435d25683eac49a000f4e7", "snapshot_id": "188a3da128bf0217c7b60efc7baaba761da3b236", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/josefadamcik/bscar/f7557617bfbd47b48d435d25683eac49a000f4e7/car/src/motor.h", "visit_date": "2020-03-12T11:06:09.147327" }
stackv2
#include <Arduino.h> #include <../../shared/shared_structs.h> struct MotorConfig { int pwmPin; int forwardPin; int backwardPin; MotorConfig(int pwm, int fw, int bw) : pwmPin(pwm), forwardPin(fw), backwardPin(bw) {} }; void motor_init(MotorConfig &motor) { pinMode(motor.pwmPin, OUTPUT); pinMode(motor.forwardPin, OUTPUT); pinMode(motor.backwardPin, OUTPUT); } MotorState motor_go(MotorConfig &motor, int dir, int speed) { digitalWrite(motor.forwardPin, dir == DIR_FW ? HIGH : LOW); digitalWrite(motor.backwardPin, dir == DIR_FW ? LOW : HIGH); analogWrite(motor.pwmPin, speed); return MotorState(speed, speed == 0 ? DIR_NONE : dir); } MotorState motor_stop(MotorConfig &motor) { digitalWrite(motor.forwardPin, LOW); digitalWrite(motor.backwardPin, LOW); analogWrite(motor.pwmPin, 0); return MotorState(); }
2.4375
2
2024-11-18T22:49:23.550246+00:00
2023-07-27T17:32:21
a0188cae3ee320b0997bc0bf7f54c2a66ea3a99e
{ "blob_id": "a0188cae3ee320b0997bc0bf7f54c2a66ea3a99e", "branch_name": "refs/heads/master", "committer_date": "2023-07-27T17:32:21", "content_id": "e43f3b829fd0c336dfe96f6ec49dda919625dc01", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "60f27032d05f5977ae6a871a968022b674a6ddd1", "extension": "c", "filename": "mettle_rpc.c", "fork_events_count": 137, "gha_created_at": "2015-03-02T14:14:41", "gha_event_created_at": "2023-07-26T11:44:50", "gha_language": "C", "gha_license_id": null, "github_id": 31543393, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2763, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/mettle/src/mettle_rpc.c", "provenance": "stackv2-0108.json.gz:98377", "repo_name": "rapid7/mettle", "revision_date": "2023-07-27T17:32:21", "revision_id": "7274a2413952be0c612fcacf2eb1cc1119c2b840", "snapshot_id": "bcd759a181fee81fa68c7cd15e0b84b71b2f0ff9", "src_encoding": "UTF-8", "star_events_count": 411, "url": "https://raw.githubusercontent.com/rapid7/mettle/7274a2413952be0c612fcacf2eb1cc1119c2b840/mettle/src/mettle_rpc.c", "visit_date": "2023-08-04T15:14:09.902863" }
stackv2
#include <string.h> #include "json.h" #include "log.h" #include "mettle.h" #include "network_server.h" #include "utlist.h" struct mettle_rpc { struct mettle *m; int running; struct network_server *ns; struct json_rpc *jrpc; struct mettle_rpc_conn { struct mettle_rpc *mrpc; struct json_tokener *tok; struct bufferev *bev; struct mettle_rpc_conn *next; } *conns; }; static struct mettle_rpc_conn * get_conn(struct mettle_rpc *mrpc, struct bufferev *bev) { struct mettle_rpc_conn *conn; LL_FOREACH(mrpc->conns, conn) { if (conn->bev == bev) { return conn; } } conn = calloc(1, sizeof(*conn)); if (!conn) { return NULL; } conn->mrpc = mrpc; conn->bev = bev; conn->tok = json_tokener_new(); if (!conn->tok) { free(conn); return NULL; } LL_APPEND(mrpc->conns, conn); return conn; } static void handle_rpc(struct json_object *obj, void *arg) { struct mettle_rpc_conn *conn = arg; struct json_object *response = NULL; if (obj != NULL) { response = json_rpc_process(conn->mrpc->jrpc, obj); } else { enum json_tokener_error rc = json_tokener_get_error(conn->tok); if (rc != json_tokener_continue) { response = json_rpc_gen_error(conn->mrpc->jrpc, NULL, JSON_RPC_PARSE_ERROR, "Parse error"); json_tokener_reset(conn->tok); } } if (response) { const char *str = json_object_to_json_string_ext(response, 0); bufferev_write(conn->bev, str, strlen(str)); json_object_put(response); } json_object_put(obj); } static void read_cb(struct bufferev *bev, void *arg) { struct mettle_rpc *mrpc = arg; struct mettle_rpc_conn *conn = get_conn(mrpc, bev); if (conn) { json_read_bufferev_cb(bev, conn->tok, handle_rpc, conn); } else { bufferev_free(bev); } } static void event_cb(struct bufferev *bev, int event, void *arg) { struct mettle_rpc *mrpc = arg; if (event & (BEV_EOF|BEV_ERROR)) { struct mettle_rpc_conn *conn = get_conn(mrpc, bev); if (conn) { LL_DELETE(mrpc->conns, conn); json_tokener_free(conn->tok); free(conn); } } } void mettle_rpc_free(struct mettle_rpc *mrpc) { if (mrpc) { if (mrpc->jrpc) { json_rpc_free(mrpc->jrpc); } if (mrpc->ns) { network_server_free(mrpc->ns); } free(mrpc); } } struct mettle_rpc * mettle_rpc_new(struct mettle *m) { struct mettle_rpc *mrpc = calloc(1, sizeof(*mrpc)); if (mrpc == NULL) { return NULL; } mrpc->m = m; mrpc->jrpc = json_rpc_new(JSON_RPC_CHECK_VERSION); if (mrpc->jrpc == NULL) { goto err; } mrpc->ns = network_server_new(mettle_get_loop(m)); char *host = "127.0.0.1"; uint16_t port = 1337; if (network_server_listen_tcp(mrpc->ns, host, port) == -1) { log_info("failed to listen on %s:%d", host, port); goto err; } return mrpc; err: mettle_rpc_free(mrpc); return NULL; }
2.21875
2
2024-11-18T20:50:25.404623+00:00
2023-07-15T12:54:41
42284508b0f1d1bd0cf82a82077d2ba66865e9ac
{ "blob_id": "42284508b0f1d1bd0cf82a82077d2ba66865e9ac", "branch_name": "refs/heads/master", "committer_date": "2023-07-15T12:54:41", "content_id": "86989cee4e5a962a22e403078985285f070ce3fb", "detected_licenses": [ "MIT" ], "directory_id": "c2e5660e8e757e466df5ed614e2388890e2158bb", "extension": "h", "filename": "Gun.h", "fork_events_count": 3, "gha_created_at": "2020-07-15T09:36:32", "gha_event_created_at": "2020-10-16T10:52:50", "gha_language": "C++", "gha_license_id": "MIT", "github_id": 279826728, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 601, "license": "MIT", "license_type": "permissive", "path": "/2M3/Include/Common/Components/Gun.h", "provenance": "stackv2-0110.json.gz:212592", "repo_name": "simatic/MultiplayerLab", "revision_date": "2023-07-15T12:54:41", "revision_id": "143bcfb5374e41d8b112f72963c55e879764866c", "snapshot_id": "c3aefe44869026d7521cb34a7be6aac9ed138e89", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/simatic/MultiplayerLab/143bcfb5374e41d8b112f72963c55e879764866c/2M3/Include/Common/Components/Gun.h", "visit_date": "2023-07-20T02:12:38.632933" }
stackv2
#pragma once #include "Common/Components/Component.h" #include <SFML/System/Vector2.hpp> #include <SFML/System/Time.hpp> /** * @struct Gun component. * Useful for shooting bullets, has a pointing direction and a cooldown time. */ struct Gun : public IdentifiableComponent<Gun> { Gun(const sf::Vector2f& pointingDirection, sf::Time cooldown); sf::Vector2f pointingDirection; //!< Pointing direction of the gun. sf::Time cooldown; //!< Cooldown time of the gun. sf::Time elapsedTimeSinceLastShot; //!< Elapsed time since last shot. };
2.140625
2
2024-11-18T20:50:26.538869+00:00
2023-08-21T15:07:35
014708b9b93e2b2374ee22bb147cf7494af2e083
{ "blob_id": "014708b9b93e2b2374ee22bb147cf7494af2e083", "branch_name": "refs/heads/master", "committer_date": "2023-08-21T15:07:35", "content_id": "fe478693d9d1917d559ec0c0175220af3f9b53a5", "detected_licenses": [ "MIT" ], "directory_id": "ecd69837ab8c8463ed398757ff13226047fbcec0", "extension": "c", "filename": "wavefront_extend_kernels.c", "fork_events_count": 4, "gha_created_at": "2020-09-12T09:17:59", "gha_event_created_at": "2023-09-01T06:39:42", "gha_language": "C++", "gha_license_id": "MIT", "github_id": 294910326, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 6222, "license": "MIT", "license_type": "permissive", "path": "/src/common/wflign/deps/WFA2-lib/wavefront/wavefront_extend_kernels.c", "provenance": "stackv2-0110.json.gz:213112", "repo_name": "waveygang/wfmash", "revision_date": "2023-08-21T15:07:35", "revision_id": "a2cac14f740b117cad97bb0d99b57fa08d52311e", "snapshot_id": "7d014404df7707cfa65286e45c964e7737ab4e01", "src_encoding": "UTF-8", "star_events_count": 43, "url": "https://raw.githubusercontent.com/waveygang/wfmash/a2cac14f740b117cad97bb0d99b57fa08d52311e/src/common/wflign/deps/WFA2-lib/wavefront/wavefront_extend_kernels.c", "visit_date": "2023-08-31T10:07:14.785344" }
stackv2
/* * The MIT License * * Wavefront Alignment Algorithms * Copyright (c) 2017 by Santiago Marco-Sola <santiagomsola@gmail.com> * * This file is part of Wavefront Alignment Algorithms. * * 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. * * PROJECT: Wavefront Alignment Algorithms * AUTHOR(S): Santiago Marco-Sola <santiagomsola@gmail.com> * DESCRIPTION: WFA module for the "extension" of exact matches */ #include "wavefront_extend_kernels.h" #include "wavefront_termination.h" /* * Inner-most extend kernel (blockwise comparisons) */ FORCE_INLINE wf_offset_t wavefront_extend_matches_packed_kernel( wavefront_aligner_t* const wf_aligner, const int k, wf_offset_t offset) { // Fetch pattern/text blocks uint64_t* pattern_blocks = (uint64_t*)(wf_aligner->sequences.pattern+WAVEFRONT_V(k,offset)); uint64_t* text_blocks = (uint64_t*)(wf_aligner->sequences.text+WAVEFRONT_H(k,offset)); // Compare 64-bits blocks uint64_t cmp = *pattern_blocks ^ *text_blocks; while (__builtin_expect(cmp==0,0)) { // Increment offset (full block) offset += 8; // Next blocks ++pattern_blocks; ++text_blocks; // Compare cmp = *pattern_blocks ^ *text_blocks; } // Count equal characters const int equal_right_bits = __builtin_ctzl(cmp); const int equal_chars = DIV_FLOOR(equal_right_bits,8); offset += equal_chars; // Return extended offset return offset; } /* * Wavefront-Extend Inner Kernels * Wavefront offset extension comparing characters * Remember: * - No offset is out of boundaries !(h>tlen,v>plen) * - if (h==tlen,v==plen) extension won't increment (sentinels) */ FORCE_NO_INLINE void wavefront_extend_matches_packed_end2end( wavefront_aligner_t* const wf_aligner, wavefront_t* const mwavefront, const int lo, const int hi) { wf_offset_t* const offsets = mwavefront->offsets; int k; for (k=lo;k<=hi;++k) { // Fetch offset const wf_offset_t offset = offsets[k]; if (offset == WAVEFRONT_OFFSET_NULL) continue; // Extend offset offsets[k] = wavefront_extend_matches_packed_kernel(wf_aligner,k,offset); } } FORCE_NO_INLINE wf_offset_t wavefront_extend_matches_packed_end2end_max( wavefront_aligner_t* const wf_aligner, wavefront_t* const mwavefront, const int lo, const int hi) { wf_offset_t* const offsets = mwavefront->offsets; wf_offset_t max_antidiag = 0; int k; for (k=lo;k<=hi;++k) { // Fetch offset const wf_offset_t offset = offsets[k]; if (offset == WAVEFRONT_OFFSET_NULL) continue; // Extend offset offsets[k] = wavefront_extend_matches_packed_kernel(wf_aligner,k,offset); // Compute max const wf_offset_t antidiag = WAVEFRONT_ANTIDIAGONAL(k,offsets[k]); if (max_antidiag < antidiag) max_antidiag = antidiag; } return max_antidiag; } FORCE_NO_INLINE bool wavefront_extend_matches_packed_endsfree( wavefront_aligner_t* const wf_aligner, wavefront_t* const mwavefront, const int score, const int lo, const int hi) { // Parameters wf_offset_t* const offsets = mwavefront->offsets; int k; for (k=lo;k<=hi;++k) { // Fetch offset wf_offset_t offset = offsets[k]; if (offset == WAVEFRONT_OFFSET_NULL) continue; // Extend offset offset = wavefront_extend_matches_packed_kernel(wf_aligner,k,offset); offsets[k] = offset; // Check ends-free reaching boundaries if (wavefront_termination_endsfree(wf_aligner,mwavefront,score,k,offset)) { return true; // Quit (we are done) } /* * TODO const int h_pos = WAVEFRONT_H(k,offset); const int v_pos = WAVEFRONT_V(k,offset); if (h_pos >= text_length || v_pos >= pattern_length) { // FIXME Use wherever necessary if (wavefront_extend_endsfree_check_termination(wf_aligner,mwavefront,score,k,offset)) { return true; // Quit (we are done) } */ } // Alignment not finished return false; } /* * Wavefront-Extend Inner Kernel (Custom match function) */ bool wavefront_extend_matches_custom( wavefront_aligner_t* const wf_aligner, wavefront_t* const mwavefront, const int score, const int lo, const int hi, const bool endsfree, wf_offset_t* const max_antidiag) { // Parameters wavefront_sequences_t* const seqs = &wf_aligner->sequences; // Extend diagonally each wavefront point wf_offset_t* const offsets = mwavefront->offsets; *max_antidiag = 0; int k; for (k=lo;k<=hi;++k) { // Check offset wf_offset_t offset = offsets[k]; if (offset == WAVEFRONT_OFFSET_NULL) continue; // Count equal characters int v = WAVEFRONT_V(k,offset); int h = WAVEFRONT_H(k,offset); while (wavefront_sequences_cmp(seqs,v,h)) { h++; v++; offset++; } // Update offset offsets[k] = offset; // Compute max const wf_offset_t antidiag = WAVEFRONT_ANTIDIAGONAL(k,offset); if (*max_antidiag < antidiag) *max_antidiag = antidiag; // Check ends-free reaching boundaries if (endsfree && wavefront_termination_endsfree(wf_aligner,mwavefront,score,k,offset)) { return true; // Quit (we are done) } } // Alignment not finished return false; }
2.265625
2
2024-11-18T20:50:27.848334+00:00
2021-09-02T05:02:37
7156adbc6ea305400d7041ad3a26d1bf9b2e4a5a
{ "blob_id": "7156adbc6ea305400d7041ad3a26d1bf9b2e4a5a", "branch_name": "refs/heads/main", "committer_date": "2021-09-08T22:14:26", "content_id": "f8eb48bb691478cccd9bd10d3db273c516321428", "detected_licenses": [ "MIT" ], "directory_id": "d3dbde5badcffc34f3c5ba9185acfe745cf0f95e", "extension": "h", "filename": "fdtable.h", "fork_events_count": 0, "gha_created_at": "2021-08-03T05:46:50", "gha_event_created_at": "2021-08-03T05:46:50", "gha_language": null, "gha_license_id": null, "github_id": 392205200, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4508, "license": "MIT", "license_type": "permissive", "path": "/include/myst/fdtable.h", "provenance": "stackv2-0110.json.gz:213500", "repo_name": "manojrupireddy/mystikos", "revision_date": "2021-09-02T05:02:37", "revision_id": "2151cf13455a25b9695318b8a50b7f27dd3bbb2a", "snapshot_id": "eb71e085c83b827219fa367caf987ab988f73a7f", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/manojrupireddy/mystikos/2151cf13455a25b9695318b8a50b7f27dd3bbb2a/include/myst/fdtable.h", "visit_date": "2023-07-26T02:25:28.434799" }
stackv2
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #ifndef _MYST_FDTABLE_H #define _MYST_FDTABLE_H #include <stdbool.h> #include <stddef.h> #include <stdint.h> #include <unistd.h> #include <myst/defs.h> #include <myst/epolldev.h> #include <myst/eventfddev.h> #include <myst/fs.h> #include <myst/inotifydev.h> #include <myst/pipedev.h> #include <myst/sockdev.h> #include <myst/spinlock.h> #include <myst/ttydev.h> #define MYST_FDTABLE_SIZE 1024 typedef enum myst_fdtable_type { MYST_FDTABLE_TYPE_NONE, MYST_FDTABLE_TYPE_TTY, MYST_FDTABLE_TYPE_FILE, MYST_FDTABLE_TYPE_PIPE, MYST_FDTABLE_TYPE_SOCK, MYST_FDTABLE_TYPE_EPOLL, MYST_FDTABLE_TYPE_INOTIFY, MYST_FDTABLE_TYPE_EVENTFD, } myst_fdtable_type_t; typedef struct myst_fdtable_entry { myst_fdtable_type_t type; void* device; /* example: myst_fs_t */ void* object; /* example: myst_file_t */ } myst_fdtable_entry_t; typedef struct myst_fdtable { myst_fdtable_entry_t entries[MYST_FDTABLE_SIZE]; myst_spinlock_t lock; } myst_fdtable_t; int myst_fdtable_create(myst_fdtable_t** fdtable_out); int myst_fdtable_cloexec(myst_fdtable_t* fdtable); int myst_fdtable_free(myst_fdtable_t* fdtable); int myst_fdtable_interrupt(myst_fdtable_t* fdtable); /* returns a file descriptor */ int myst_fdtable_assign( myst_fdtable_t* fdtable, myst_fdtable_type_t type, void* device, void* object); typedef enum { MYST_DUP, /* dup() */ MYST_DUP2, /* dup2() */ MYST_DUP3, /* dup3() */ MYST_DUPFD, /* fcntl(fd, DUPFD) */ MYST_DUPFD_CLOEXEC, /* fcntl(fd, DUPFD_CLOEXEC) */ } myst_dup_type_t; int myst_fdtable_dup( myst_fdtable_t* fdtable, myst_dup_type_t duptype, int oldfd, int newfd, int flags); /* O_CLOEXEC */ int myst_fdtable_remove(myst_fdtable_t* fdtable, int fd); int myst_fdtable_get( myst_fdtable_t* fdtable, int fd, myst_fdtable_type_t type, void** device, void** object); MYST_INLINE int myst_fdtable_get_tty( myst_fdtable_t* fdtable, int fd, myst_ttydev_t** device, myst_tty_t** tty) { const myst_fdtable_type_t type = MYST_FDTABLE_TYPE_TTY; return myst_fdtable_get(fdtable, fd, type, (void**)device, (void**)tty); } MYST_INLINE int myst_fdtable_get_sock( myst_fdtable_t* fdtable, int fd, myst_sockdev_t** device, myst_sock_t** sock) { const myst_fdtable_type_t type = MYST_FDTABLE_TYPE_SOCK; return myst_fdtable_get(fdtable, fd, type, (void**)device, (void**)sock); } MYST_INLINE int myst_fdtable_get_epoll( myst_fdtable_t* fdtable, int fd, myst_epolldev_t** device, myst_epoll_t** epoll) { const myst_fdtable_type_t type = MYST_FDTABLE_TYPE_EPOLL; return myst_fdtable_get(fdtable, fd, type, (void**)device, (void**)epoll); } MYST_INLINE int myst_fdtable_get_file( myst_fdtable_t* fdtable, int fd, myst_fs_t** fs, myst_file_t** file) { const myst_fdtable_type_t type = MYST_FDTABLE_TYPE_FILE; return myst_fdtable_get(fdtable, fd, type, (void**)fs, (void**)file); } MYST_INLINE int myst_fdtable_get_pipe( myst_fdtable_t* fdtable, int fd, myst_pipedev_t** device, myst_pipe_t** pipe) { const myst_fdtable_type_t type = MYST_FDTABLE_TYPE_PIPE; return myst_fdtable_get(fdtable, fd, type, (void**)device, (void**)pipe); } MYST_INLINE int myst_fdtable_get_inotify( myst_fdtable_t* fdtable, int fd, myst_inotifydev_t** device, myst_inotify_t** inotify) { const myst_fdtable_type_t type = MYST_FDTABLE_TYPE_INOTIFY; return myst_fdtable_get(fdtable, fd, type, (void**)device, (void**)inotify); } MYST_INLINE int myst_fdtable_get_eventfd( myst_fdtable_t* fdtable, int fd, myst_eventfddev_t** device, myst_eventfd_t** eventfd) { const myst_fdtable_type_t type = MYST_FDTABLE_TYPE_EVENTFD; return myst_fdtable_get(fdtable, fd, type, (void**)device, (void**)eventfd); } int myst_fdtable_get_any( myst_fdtable_t* fdtable, int fd, myst_fdtable_type_t* type, void** device, void** object); /* get the fdtable for the current thread */ myst_fdtable_t* myst_fdtable_current(void); int myst_fdtable_clone(myst_fdtable_t* fdtable, myst_fdtable_t** fdtable_out); MYST_INLINE bool myst_valid_fd(int fd) { return fd >= 0 && fd < MYST_FDTABLE_SIZE; } int myst_fdtable_list(const myst_fdtable_t* fdtable); long myst_fdtable_sync(myst_fdtable_t* fdtable); #endif /* _MYST_FDTABLE_H */
2.46875
2
2024-11-18T20:50:27.906658+00:00
2017-11-25T03:23:41
db0d0380c1f29aa14c871c75246b90b79dabc48c
{ "blob_id": "db0d0380c1f29aa14c871c75246b90b79dabc48c", "branch_name": "refs/heads/master", "committer_date": "2017-11-25T03:23:41", "content_id": "ce95ab63e695d45042c6a1b469e90b697d0e302c", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "71a29beaefb3047022a199d41ead7d39b84cacf8", "extension": "h", "filename": "scheduler.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": 1183, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/Kernel/include/scheduler.h", "provenance": "stackv2-0110.json.gz:213628", "repo_name": "tomso11/gatOS.v2", "revision_date": "2017-11-25T03:23:41", "revision_id": "456293adcfdf2c050f93c724c0980ec553b84c77", "snapshot_id": "4152be1602d2465885cb2073b7f867b4dae7aa90", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/tomso11/gatOS.v2/456293adcfdf2c050f93c724c0980ec553b84c77/Kernel/include/scheduler.h", "visit_date": "2021-08-19T07:08:45.920740" }
stackv2
#ifndef SCHEDULER_H #define SCHEDULER_H #include "stdio.h" #include "lib.h" #include "interrupts.h" #include "systemCalls.h" #include <naiveConsole.h> #include "process.h" #include "structs.h" #include "types.h" #define INIT_PID 0 typedef void (*EntryPointHandler) (void*); typedef struct ProcessSlotS { struct ProcessSlotS * next; Process * process; }ProcessSlot; ProcessSlot * newProcessSlot(Process * process); int createProcess(void * entryPoint, char * description , void * args); int getCurrentPid(); void changeProcessState(int pid, processState state); void addProcess(Process * process); void * next_process(void * current_rsp); void schedule(); StackFrame * switchUserToKernel(void * esp); StackFrame * switchKernelToUser(); void * getCurrentEntryPoint(); Process * * getCurrentProcesses(int * a); Process * getCurrentProcess(); int eqProcess(Process * a, Process * b); char * getStateFromNumber(int state); void printProcesses(); void removeProcess(int pid); void callProcess( void * entryPoint, void * entryPoint2, void * args , void * args2) ; void beginScheduler(); StackFrame * getCurrentUserStack(); void restartSHELL(); void killAllExceptCurrent(); #endif
2.09375
2
2024-11-18T20:50:27.968428+00:00
2021-10-16T05:49:22
e9cbb070db9d9e93d45683173519d7266afb638b
{ "blob_id": "e9cbb070db9d9e93d45683173519d7266afb638b", "branch_name": "refs/heads/main", "committer_date": "2021-10-16T07:31:21", "content_id": "11216cc5ca0a6fba829168d950c215a88ae9f3dc", "detected_licenses": [ "Apache-2.0" ], "directory_id": "91729ccf7286bddffb04df2f4889462e4a40a294", "extension": "c", "filename": "riscv_tranform.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": 3835, "license": "Apache-2.0", "license_type": "permissive", "path": "/NMSIS/DSP/Test/TransformFunction/cfftx2/riscv_tranform.c", "provenance": "stackv2-0110.json.gz:213756", "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/TransformFunction/cfftx2/riscv_tranform.c", "visit_date": "2023-08-22T03:35:32.818232" }
stackv2
// // Created by lujun on 19-6-28. // // This contains SIN_COS , clarke, inv_clarke, park, inv_park and pid // each one has it's own function. // All function can be found in main function. // If you don't want to use it, then comment it. #include "riscv_common_tables.h" #include "riscv_const_structs.h" #include "riscv_math.h" #include "array.h" #include <stdint.h> #include "../common.h" #include "../HelperFunctions/math_helper.c" #include "../HelperFunctions/ref_helper.c" #include <stdio.h> #define DELTAF32 (0.05f) #define DELTAQ31 (63) #define DELTAQ15 (1) #define DELTAQ7 (1) int test_flag_error = 0; uint32_t fftSize = 1024; uint32_t ifftFlag = 0; uint32_t doBitReverse = 1; static int DSP_cfft_radix2_q15(void) { uint16_t i; riscv_float_to_q15(cfft_testinput_f32_50hz_200Hz, cfft_testinput_q15_50hz_200Hz, 1024); fftSize = 512; riscv_cfft_radix2_instance_q15 S; uint8_t ifftFlag = 0, doBitReverse = 1; riscv_cfft_radix2_init_q15(&S, 512, ifftFlag, doBitReverse); BENCH_START(riscv_cfft_radix2_q15); riscv_cfft_radix2_q15(&S, cfft_testinput_q15_50hz_200Hz); BENCH_END(riscv_cfft_radix2_q15); q15_t resault, resault_ref; uint32_t index, index_ref = 205; riscv_max_q15(cfft_testinput_q15_50hz_200Hz, 1024, &resault, &index); if (index != index_ref) { BENCH_ERROR(riscv_cfft_radix2_q15); printf("expect: %d, actual: %d\n", index_ref, index); test_flag_error = 1; } BENCH_STATUS(riscv_cfft_radix2_q15); } static int DSP_cfft_radix2_q31(void) { uint16_t i; riscv_float_to_q31(cfft_testinput_f32_50hz_200Hz, cfft_testinput_q31_50hz_200Hz, 1024); riscv_float_to_q31(cfft_testinput_f32_50hz_200Hz_ref, cfft_testinput_q31_50hz_200Hz_ref, 1024); fftSize = 512; riscv_cfft_radix2_instance_q31 S; uint8_t ifftFlag = 0, doBitReverse = 1; riscv_cfft_radix2_init_q31(&S, 512, ifftFlag, doBitReverse); BENCH_START(riscv_cfft_radix2_q31); riscv_cfft_radix2_q31(&S, cfft_testinput_q31_50hz_200Hz); BENCH_END(riscv_cfft_radix2_q31); ref_cfft_radix2_q31(&S, cfft_testinput_q31_50hz_200Hz_ref); q31_t resault, resault_ref; uint32_t index, index_ref; riscv_max_q31(cfft_testinput_q31_50hz_200Hz, 1024, &resault, &index); riscv_max_q31(cfft_testinput_q31_50hz_200Hz_ref, 1024, &resault_ref, &index_ref); if (index != index_ref) { BENCH_ERROR(riscv_cfft_radix2_q31); printf("expect: %d, actual: %d\n", index_ref, index); test_flag_error = 1; } BENCH_STATUS(riscv_cfft_radix2_q31); } static int DSP_cfft_radix2_f32(void) { uint16_t i; fftSize = 512; riscv_cfft_radix2_instance_f32 S; uint8_t ifftFlag = 0, doBitReverse = 1; riscv_cfft_radix2_init_f32(&S, 512, ifftFlag, doBitReverse); BENCH_START(riscv_cfft_radix2_f32); riscv_cfft_radix2_f32(&S, cfft_testinput_f32_50hz_200Hz); BENCH_END(riscv_cfft_radix2_f32); ref_cfft_radix2_f32(&S, cfft_testinput_f32_50hz_200Hz_ref); float32_t resault, resault_ref; uint32_t index, index_ref; riscv_max_f32(cfft_testinput_f32_50hz_200Hz, 1024, &resault, &index); riscv_max_f32(cfft_testinput_f32_50hz_200Hz_ref, 1024, &resault_ref, &index_ref); if (index != index_ref) { BENCH_ERROR(riscv_cfft_radix2_f32); printf("expect: %d, actual: %d\n", index_ref, index); test_flag_error = 1; } BENCH_STATUS(riscv_cfft_radix2_f32); } int main() { BENCH_INIT; DSP_cfft_radix2_q15(); DSP_cfft_radix2_q31(); DSP_cfft_radix2_f32(); BENCH_FINISH; if (test_flag_error) { printf("test error apprears, please recheck.\n"); return 1; } else { printf("all test are passed. Well done!\n"); } return 0; }
2.03125
2
2024-11-18T20:50:28.613304+00:00
2021-09-12T02:09:30
a04b16880d25f63b590e1bb17aaaa1d5469c76bd
{ "blob_id": "a04b16880d25f63b590e1bb17aaaa1d5469c76bd", "branch_name": "refs/heads/master", "committer_date": "2021-09-12T02:09:45", "content_id": "f86c89b4acda99d585742314332ea769500f411c", "detected_licenses": [ "MIT" ], "directory_id": "52c46d30c0491add8c1050b79a3cf2cfc97abd60", "extension": "h", "filename": "rawdraw_sf.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": 145773, "license": "MIT", "license_type": "permissive", "path": "/rawdraw_sf.h", "provenance": "stackv2-0110.json.gz:214141", "repo_name": "reinaldogoes/game-of-life", "revision_date": "2021-09-12T02:09:30", "revision_id": "76a02601e2fb423b9a02cda493fa49d0e31018a7", "snapshot_id": "edad897cfd9f2f52ccc6881f215bc52ec8ddcf43", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/reinaldogoes/game-of-life/76a02601e2fb423b9a02cda493fa49d0e31018a7/rawdraw_sf.h", "visit_date": "2023-08-01T09:40:01.739612" }
stackv2
//This file was automatically generated by Makefile at https://github.com/cntools/rawdraw //Generated from files git hash 7b618b4a500c6308a887d2a44dc845fc941d8c82 on Sun Jun 6 09:54:28 PM EDT 2021 (This is not the git hash of this file) // Copyright 2010-2021 <>< CNLohr, et. al. (Several other authors, many but not all mentioned) // Licensed under the MIT/x11 or NewBSD License you choose. // // CN Foundational Graphics Main Header File. This is the main header you // should include. See README.md for more details. #ifndef _CNFG_H #define _CNFG_H #ifdef __cplusplus extern "C" { #endif /* Rawdraw flags: CNFG3D -> Enable the weird 3D functionality that rawdraw has to allow you to write apps which emit basic rawdraw primitives but look 3D! CNFG_USE_DOUBLE_FUNCTIONS -> Use double-precision floating point for CNFG3D. CNFGOGL -> Use an OpenGL Backend for all rawdraw functionality. ->Caveat->If using CNFG_HAS_XSHAPE, then, we do something realy wacky. CNFGRASTERIZER -> Software-rasterize the rawdraw calls, and, use CNFGUpdateScreenWithBitmap to send video to webpage. CNFGCONTEXTONLY -> Don't add any drawing functions, only opening a window to get an OpenGL context. Usually tested combinations: * TCC On Windows and X11 (Linux) with: - CNFGOGL on or CNFGOGL off. If CNFGOGL is off you can use CNFG_WINDOWS_DISABLE_BATCH to disable all batching. -or- - CNFGRASTERIZER NOTE: Sometimes you can also use CNFGOGL + CNFGRASTERIZER * WASM driver supports both: CNFGRASTERIZER and without CNFGRASTERIZER (Recommended turn rasterizer off) * ANDROID (But this automatically sets CNFGRASTERIZER OFF and CNFGOGL ON) */ #include <stdint.h> //Some per-platform logic. #if defined( ANDROID ) || defined( __android__ ) #define CNFGOGL #endif #if ( defined( CNFGOGL ) || defined( __wasm__ ) ) && !defined(CNFG_HAS_XSHAPE) #define CNFG_BATCH 8192 //131,072 bytes. #if defined( ANDROID ) || defined( __android__ ) || defined( __wasm__ ) || defined( EGL_LEAN_AND_MEAN ) #define CNFGEWGL //EGL or WebGL #else #define CNFGDESKTOPGL #endif #endif typedef struct { short x, y; } RDPoint; extern int CNFGPenX, CNFGPenY; extern uint32_t CNFGBGColor; extern uint32_t CNFGLastColor; extern uint32_t CNFGDialogColor; //Only used for DrawBox //Draws text at CNFGPenX, CNFGPenY, with scale of `scale`. void CNFGDrawText( const char * text, short scale ); //Determine how large a given test would be to draw. void CNFGGetTextExtents( const char * text, int * w, int * h, int textsize ); //Draws a box, outline as whatever the last CNFGColor was set to but also draws //a rectangle as a background as whatever CNFGDialogColor is set to. void CNFGDrawBox( short x1, short y1, short x2, short y2 ); //To be provided by driver. Rawdraw uses colors in the format 0xRRGGBBAA //Note that some backends do not support alpha of any kind. //Some platforms also support alpha blending. So, be sure to set alpha to 0xFF uint32_t CNFGColor( uint32_t RGBA ); //This both updates the screen, and flips, all as a single operation. void CNFGUpdateScreenWithBitmap( uint32_t * data, int w, int h ); //This is only supported on a FEW architectures, but allows arbitrary //image blitting. Note that the alpha channel behavior is different //on different systems. void CNFGBlitImage( uint32_t * data, int x, int y, int w, int h ); // Only supported with CNFGOGL #ifdef CNFGOGL void CNFGDeleteTex( unsigned int tex ); unsigned int CNFGTexImage( uint32_t *data, int w, int h ); void CNFGBlitTex( unsigned int tex, int x, int y, int w, int h ); #endif void CNFGTackPixel( short x1, short y1 ); void CNFGTackSegment( short x1, short y1, short x2, short y2 ); void CNFGTackRectangle( short x1, short y1, short x2, short y2 ); void CNFGTackPoly( RDPoint * points, int verts ); void CNFGClearFrame(); void CNFGSwapBuffers(); void CNFGGetDimensions( short * x, short * y ); //This will setup a window. Note that w and h have special meaning. On Windows //and X11, for instance if you set w and h to be negative, then rawdraw will not //show the window to the user. This is useful if you just need it for some //off-screen-rendering purpose. // //Return value of 0 indicates success. Nonzero indicates error. int CNFGSetup( const char * WindowName, int w, int h ); void CNFGSetupFullscreen( const char * WindowName, int screen_number ); void CNFGHandleInput(); //You must provide: void HandleKey( int keycode, int bDown ); void HandleButton( int x, int y, int button, int bDown ); void HandleMotion( int x, int y, int mask ); void HandleDestroy(); //Internal function for resizing rasterizer for rasterizer-mode. void CNFGInternalResize( short x, short y ); //don't call this. //Not available on all systems. Use The OGL portion with care. #ifdef CNFGOGL void CNFGSetVSync( int vson ); void * CNFGGetExtension( const char * extname ); #endif //Also not available on all systems. Transparency. void CNFGPrepareForTransparency(); void CNFGDrawToTransparencyMode( int transp ); void CNFGClearTransparencyLevel(); //Only available on systems that support it. void CNFGSetLineWidth( short width ); void CNFGChangeWindowTitle( const char * windowtitle ); void CNFGSetWindowIconData( int w, int h, uint32_t * data ); int CNFGSetupWMClass( const char * WindowName, int w, int h , char * wm_res_name_ , char * wm_res_class_ ); //If you're using a batching renderer, for instance on Android or an OpenGL //You will need to call this function inbetewen swtiching properties of drawing. This is usually //only needed if you calling OpenGL / OGLES functions directly and outside of CNFG. // //Note that these are the functions that are used on the backends which support this //sort of thing. #ifdef CNFG_BATCH //If you are not using the CNFGOGL driver, you will need to define these in your driver. void CNFGEmitBackendTriangles( const float * vertices, const uint32_t * colors, int num_vertices ); void CNFGBlitImage( uint32_t * data, int x, int y, int w, int h ); //These need to be defined for the specific driver. void CNFGClearFrame(); void CNFGSwapBuffers(); void CNFGFlushRender(); //Emit any geometry (lines, squares, polys) which are slated to be rendered. void CNFGInternalResize( short x, short y ); //Driver calls this after resize happens. void CNFGSetupBatchInternal(); //Driver calls this after setup is complete. //Useful function for emitting a non-axis-aligned quad. void CNFGEmitQuad( float cx0, float cy0, float cx1, float cy1, float cx2, float cy2, float cx3, float cy3 ); extern int CNFGVertPlace; extern float CNFGVertDataV[CNFG_BATCH*3]; extern uint32_t CNFGVertDataC[CNFG_BATCH]; #endif #if defined(WINDOWS) || defined(WIN32) || defined(WIN64) || defined(_WIN32) || defined(_WIN64) #define CNFG_KEY_SHIFT 0x10 #define CNFG_KEY_BACKSPACE 0x08 #define CNFG_KEY_DELETE 0x2E #define CNFG_KEY_LEFT_ARROW 0x25 #define CNFG_KEY_RIGHT_ARROW 0x27 #define CNFG_KEY_TOP_ARROW 0x26 #define CNFG_KEY_BOTTOM_ARROW 0x28 #define CNFG_KEY_ESCAPE 0x1B #define CNFG_KEY_ENTER 0x0D #elif defined( EGL_LEAN_AND_MEAN ) // doesn't have any keys #elif defined( __android__ ) || defined( ANDROID ) // ^ #elif defined( __wasm__ ) #define CNFG_KEY_SHIFT 16 #define CNFG_KEY_BACKSPACE 8 #define CNFG_KEY_DELETE 46 #define CNFG_KEY_LEFT_ARROW 37 #define CNFG_KEY_RIGHT_ARROW 39 #define CNFG_KEY_TOP_ARROW 38 #define CNFG_KEY_BOTTOM_ARROW 40 #define CNFG_KEY_ESCAPE 27 #define CNFG_KEY_ENTER 13 #else // most likely x11 #define CNFG_KEY_SHIFT 65505 #define CNFG_KEY_BACKSPACE 65288 #define CNFG_KEY_DELETE 65535 #define CNFG_KEY_LEFT_ARROW 65361 #define CNFG_KEY_RIGHT_ARROW 65363 #define CNFG_KEY_TOP_ARROW 65362 #define CNFG_KEY_BOTTOM_ARROW 65364 #define CNFG_KEY_ESCAPE 65307 #define CNFG_KEY_ENTER 65293 #endif #ifdef CNFG3D #ifndef __wasm__ #include <math.h> #endif #ifdef CNFG_USE_DOUBLE_FUNCTIONS #define tdCOS cos #define tdSIN sin #define tdTAN tan #define tdSQRT sqrt #else #define tdCOS cosf #define tdSIN sinf #define tdTAN tanf #define tdSQRT sqrtf #endif #ifdef __wasm__ void tdMATCOPY( float * x, const float * y ); //Copy y into x #else #define tdMATCOPY(x,y) memcpy( x, y, 16*sizeof(float)) #endif #define tdQ_PI 3.141592653589 #define tdDEGRAD (tdQ_PI/180.) #define tdRADDEG (180./tdQ_PI) //General Matrix Functions void tdIdentity( float * f ); void tdZero( float * f ); void tdTranslate( float * f, float x, float y, float z ); //Operates ON f void tdScale( float * f, float x, float y, float z ); //Operates ON f void tdRotateAA( float * f, float angle, float x, float y, float z ); //Operates ON f void tdRotateQuat( float * f, float qw, float qx, float qy, float qz ); //Operates ON f void tdRotateEA( float * f, float x, float y, float z ); //Operates ON f void tdMultiply( float * fin1, float * fin2, float * fout ); //Operates ON f void tdPrint( const float * f ); void tdTransposeSelf( float * f ); //Specialty Matrix Functions void tdPerspective( float fovy, float aspect, float zNear, float zFar, float * out ); //Sets, NOT OPERATES. (FOVX=degrees) void tdLookAt( float * m, float * eye, float * at, float * up ); //Operates ON m //General point functions #define tdPSet( f, x, y, z ) { f[0] = x; f[1] = y; f[2] = z; } void tdPTransform( const float * pin, float * f, float * pout ); void tdVTransform( const float * vin, float * f, float * vout ); void td4Transform( float * kin, float * f, float * kout ); void td4RTransform( float * kin, float * f, float * kout ); void tdNormalizeSelf( float * vin ); void tdCross( float * va, float * vb, float * vout ); float tdDistance( float * va, float * vb ); float tdDot( float * va, float * vb ); #define tdPSub( x, y, z ) { (z)[0] = (x)[0] - (y)[0]; (z)[1] = (x)[1] - (y)[1]; (z)[2] = (x)[2] - (y)[2]; } #define tdPAdd( x, y, z ) { (z)[0] = (x)[0] + (y)[0]; (z)[1] = (x)[1] + (y)[1]; (z)[2] = (x)[2] + (y)[2]; } //Stack Functionality #define tdMATRIXMAXDEPTH 32 extern float * gSMatrix; void tdPush(); void tdPop(); void tdMode( int mode ); #define tdMODELVIEW 0 #define tdPROJECTION 1 //Final stage tools void tdSetViewport( float leftx, float topy, float rightx, float bottomy, float pixx, float pixy ); void tdFinalPoint( float * pin, float * pout ); float tdNoiseAt( int x, int y ); float tdFLerp( float a, float b, float t ); float tdPerlin2D( float x, float y ); #endif extern const unsigned char RawdrawFontCharData[1405]; extern const unsigned short RawdrawFontCharMap[256]; #ifdef __cplusplus }; #endif #if defined( ANDROID ) || defined( __android__ ) #ifndef _CNFG_ANDROID_H #define _CNFG_ANDROID_H //This file contains the additional functions that are available on the Android platform. //In order to build rawdraw for Android, please compile CNFGEGLDriver.c with -DANDROID extern struct android_app * gapp; void AndroidMakeFullscreen(); int AndroidHasPermissions(const char* perm_name); void AndroidRequestAppPermissions(const char * perm); void AndroidDisplayKeyboard(int pShow); int AndroidGetUnicodeChar( int keyCode, int metaState ); void AndroidSendToBack( int param ); extern int android_sdk_version; //Derived at start from property ro.build.version.sdk extern int android_width, android_height; extern int UpdateScreenWithBitmapOffsetX; extern int UpdateScreenWithBitmapOffsetY; //You must implement these. void HandleResume(); void HandleSuspend(); //Departures: // HandleMotion's "mask" parameter is actually just an index, not a mask // CNFGSetup / CNFGSetupFullScreen only controls whether or not the navigation // decoration is removed. Fullscreen means *full screen* To choose fullscreen // or not fullscrene, modify, in your AndroidManifest.xml file, the application // section to either contain or not contain: // android:theme="@android:style/Theme.NoTitleBar.Fullscreen" #endif #endif #ifdef CNFG_IMPLEMENTATION //Include this file to get all of rawdraw. You usually will not //want to include this in your build, but instead, #include "CNFG.h" //after #define CNFG_IMPLEMENTATION in one of your C files. #if defined(WINDOWS) || defined(WIN32) || defined(WIN64) || defined(_WIN32) || defined(_WIN64) //Copyright (c) 2011-2019 <>< Charles Lohr - Under the MIT/x11 or NewBSD License you choose. //Portion from: http://en.wikibooks.org/wiki/Windows_Programming/Window_Creation #ifndef _CNFGWINDRIVER_C #define _CNFGWINDRIVER_C #include <windows.h> #include <stdlib.h> #include <malloc.h> //for alloca #include <ctype.h> HBITMAP CNFGlsBitmap; HWND CNFGlsHWND; HDC CNFGlsWindowHDC; HDC CNFGlsHDC; HDC CNFGlsHDCBlit; //Queue up lines and points for a faster render. #ifndef CNFG_WINDOWS_DISABLE_BATCH #define BATCH_ELEMENTS #endif #define COLORSWAPS( RGB ) \ ((((RGB )& 0xFF000000)>>24) | ( ((RGB )& 0xFF0000 ) >> 8 ) | ( ((RGB )& 0xFF00 )<<8 )) void CNFGChangeWindowTitle( const char * windowtitle ) { SetWindowTextA( CNFGlsHWND, windowtitle ); } #ifdef CNFGRASTERIZER //Don't call this file yourself. It is intended to be included in any drivers which want to support the rasterizer plugin. #ifdef CNFGRASTERIZER //#include <stdlib.h> #include <stdint.h> uint32_t * CNFGBuffer = 0; short CNFGBufferx; short CNFGBuffery; #ifdef CNFGOGL void CNFGFlushRender() { } #endif void CNFGInternalResize( short x, short y ) { CNFGBufferx = x; CNFGBuffery = y; if( CNFGBuffer ) free( CNFGBuffer ); CNFGBuffer = malloc( CNFGBufferx * CNFGBuffery * 4 ); #ifdef CNFGOGL void CNFGInternalResizeOGLBACKEND( short w, short h ); CNFGInternalResizeOGLBACKEND( x, y ); #endif } #ifdef __wasm__ static uint32_t SWAPS( uint32_t r ) { uint32_t ret = (r&0xFF)<<24; r>>=8; ret |= (r&0xff)<<16; r>>=8; ret |= (r&0xff)<<8; r>>=8; ret |= (r&0xff)<<0; return ret; } #elif !defined(CNFGOGL) #define SWAPS(x) (x>>8) #else static uint32_t SWAPS( uint32_t r ) { uint32_t ret = (r&0xFF)<<16; r>>=8; ret |= (r&0xff)<<8; r>>=8; ret |= (r&0xff); r>>=8; ret |= (r&0xff)<<24; return ret; } #endif uint32_t CNFGColor( uint32_t RGB ) { CNFGLastColor = SWAPS(RGB); return CNFGLastColor; } void CNFGTackSegment( short x1, short y1, short x2, short y2 ) { short tx, ty; //float slope, lp; float slope; short dx = x2 - x1; short dy = y2 - y1; if( !CNFGBuffer ) return; if( dx < 0 ) dx = -dx; if( dy < 0 ) dy = -dy; if( dx > dy ) { short minx = (x1 < x2)?x1:x2; short maxx = (x1 < x2)?x2:x1; short miny = (x1 < x2)?y1:y2; short maxy = (x1 < x2)?y2:y1; float thisy = miny; slope = (float)(maxy-miny) / (float)(maxx-minx); for( tx = minx; tx <= maxx; tx++ ) { ty = thisy; if( tx < 0 || ty < 0 || ty >= CNFGBuffery ) continue; if( tx >= CNFGBufferx ) break; CNFGBuffer[ty * CNFGBufferx + tx] = CNFGLastColor; thisy += slope; } } else { short minx = (y1 < y2)?x1:x2; short maxx = (y1 < y2)?x2:x1; short miny = (y1 < y2)?y1:y2; short maxy = (y1 < y2)?y2:y1; float thisx = minx; slope = (float)(maxx-minx) / (float)(maxy-miny); for( ty = miny; ty <= maxy; ty++ ) { tx = thisx; if( ty < 0 || tx < 0 || tx >= CNFGBufferx ) continue; if( ty >= CNFGBuffery ) break; CNFGBuffer[ty * CNFGBufferx + tx] = CNFGLastColor; thisx += slope; } } } void CNFGTackRectangle( short x1, short y1, short x2, short y2 ) { short minx = (x1<x2)?x1:x2; short miny = (y1<y2)?y1:y2; short maxx = (x1>=x2)?x1:x2; short maxy = (y1>=y2)?y1:y2; short x, y; if( minx < 0 ) minx = 0; if( miny < 0 ) miny = 0; if( maxx >= CNFGBufferx ) maxx = CNFGBufferx-1; if( maxy >= CNFGBuffery ) maxy = CNFGBuffery-1; for( y = miny; y <= maxy; y++ ) { uint32_t * CNFGBufferstart = &CNFGBuffer[y * CNFGBufferx + minx]; for( x = minx; x <= maxx; x++ ) { (*CNFGBufferstart++) = CNFGLastColor; } } } void CNFGTackPoly( RDPoint * points, int verts ) { short minx = 10000, miny = 10000; short maxx =-10000, maxy =-10000; short i, x, y; //Just in case... if( verts > 32767 ) return; for( i = 0; i < verts; i++ ) { RDPoint * p = &points[i]; if( p->x < minx ) minx = p->x; if( p->y < miny ) miny = p->y; if( p->x > maxx ) maxx = p->x; if( p->y > maxy ) maxy = p->y; } if( miny < 0 ) miny = 0; if( maxy >= CNFGBuffery ) maxy = CNFGBuffery-1; for( y = miny; y <= maxy; y++ ) { short startfillx = maxx; short endfillx = minx; //Figure out what line segments intersect this line. for( i = 0; i < verts; i++ ) { short pl = i + 1; if( pl == verts ) pl = 0; RDPoint ptop; RDPoint pbot; ptop.x = points[i].x; ptop.y = points[i].y; pbot.x = points[pl].x; pbot.y = points[pl].y; //printf( "Poly: %d %d\n", pbot.y, ptop.y ); if( pbot.y < ptop.y ) { RDPoint ptmp; ptmp.x = pbot.x; ptmp.y = pbot.y; pbot.x = ptop.x; pbot.y = ptop.y; ptop.x = ptmp.x; ptop.y = ptmp.y; } //Make sure this line segment is within our range. //printf( "PT: %d %d %d\n", y, ptop.y, pbot.y ); if( ptop.y <= y && pbot.y >= y ) { short diffy = pbot.y - ptop.y; uint32_t placey = (uint32_t)(y - ptop.y)<<16; //Scale by 16 so we can do integer math. short diffx = pbot.x - ptop.x; short isectx; if( diffy == 0 ) { if( pbot.x < ptop.x ) { if( startfillx > pbot.x ) startfillx = pbot.x; if( endfillx < ptop.x ) endfillx = ptop.x; } else { if( startfillx > ptop.x ) startfillx = ptop.x; if( endfillx < pbot.x ) endfillx = pbot.x; } } else { //Inner part is scaled by 65536, outer part must be scaled back. isectx = (( (placey / diffy) * diffx + 32768 )>>16) + ptop.x; if( isectx < startfillx ) startfillx = isectx; if( isectx > endfillx ) endfillx = isectx; } //printf( "R: %d %d %d\n", pbot.x, ptop.x, isectx ); } } //printf( "%d %d %d\n", y, startfillx, endfillx ); if( endfillx >= CNFGBufferx ) endfillx = CNFGBufferx - 1; if( endfillx >= CNFGBufferx ) endfillx = CNFGBuffery - 1; if( startfillx < 0 ) startfillx = 0; if( startfillx < 0 ) startfillx = 0; unsigned int * bufferstart = &CNFGBuffer[y * CNFGBufferx + startfillx]; for( x = startfillx; x <= endfillx; x++ ) { (*bufferstart++) = CNFGLastColor; } } //exit(1); } void CNFGClearFrame() { int i, m; uint32_t col = 0; short x, y; CNFGGetDimensions( &x, &y ); if( x != CNFGBufferx || y != CNFGBuffery || !CNFGBuffer ) { CNFGBufferx = x; CNFGBuffery = y; CNFGBuffer = malloc( x * y * 8 ); } m = x * y; col = CNFGColor( CNFGBGColor ); for( i = 0; i < m; i++ ) { CNFGBuffer[i] = col; } } void CNFGTackPixel( short x, short y ) { if( x < 0 || y < 0 || x >= CNFGBufferx || y >= CNFGBuffery ) return; CNFGBuffer[x+CNFGBufferx*y] = CNFGLastColor; } void CNFGBlitImage( uint32_t * data, int x, int y, int w, int h ) { int ox = x; int stride = w; if( w <= 0 || h <= 0 || x >= CNFGBufferx || y >= CNFGBuffery ) return; if( x < 0 ) { w += x; x = 0; } if( y < 0 ) { h += y; y = 0; } //Switch w,h to x2, y2 h += y; w += x; if( w >= CNFGBufferx ) { w = CNFGBufferx; } if( h >= CNFGBuffery ) { h = CNFGBuffery; } for( ; y < h-1; y++ ) { x = ox; uint32_t * indat = data; uint32_t * outdat = CNFGBuffer + y * CNFGBufferx + x; for( ; x < w-1; x++ ) { uint32_t newm = *(indat++); uint32_t oldm = *(outdat); if( (newm & 0xff) == 0xff ) { *(outdat++) = newm; } else { //Alpha blend. int alfa = newm&0xff; int onemalfa = 255-alfa; #ifdef __wasm__ uint32_t newv = 255<<0; //Alpha, then RGB newv |= ((((newm>>24)&0xff) * alfa + ((oldm>>24)&0xff) * onemalfa + 128)>>8)<<24; newv |= ((((newm>>16)&0xff) * alfa + ((oldm>>16)&0xff) * onemalfa + 128)>>8)<<16; newv |= ((((newm>>8)&0xff) * alfa + ((oldm>>8)&0xff) * onemalfa + 128)>>8)<<8; #elif defined(WINDOWS) || defined(WIN32) || defined(WIN64) || defined(_WIN32) || defined(_WIN64) uint32_t newv = 255<<24; //Alpha, then RGB newv |= ((((newm>>24)&0xff) * alfa + ((oldm>>16)&0xff) * onemalfa + 128)>>8)<<16; newv |= ((((newm>>16)&0xff) * alfa + ((oldm>>8)&0xff) * onemalfa + 128)>>8)<<8; newv |= ((((newm>>8)&0xff) * alfa + ((oldm>>0)&0xff) * onemalfa + 128)>>8)<<0; #elif defined( ANDROID ) || defined( __android__ ) uint32_t newv = 255<<16; //Alpha, then RGB newv |= ((((newm>>24)&0xff) * alfa + ((oldm>>24)&0xff) * onemalfa + 128)>>8)<<24; newv |= ((((newm>>16)&0xff) * alfa + ((oldm>>0)&0xff) * onemalfa + 128)>>8)<<0; newv |= ((((newm>>8)&0xff) * alfa + ((oldm>>8)&0xff) * onemalfa + 128)>>8)<<8; #elif defined( CNFGOGL ) //OGL, on X11 uint32_t newv = 255<<16; //Alpha, then RGB newv |= ((((newm>>24)&0xff) * alfa + ((oldm>>24)&0xff) * onemalfa + 128)>>8)<<24; newv |= ((((newm>>16)&0xff) * alfa + ((oldm>>0)&0xff) * onemalfa + 128)>>8)<<0; newv |= ((((newm>>8)&0xff) * alfa + ((oldm>>8)&0xff) * onemalfa + 128)>>8)<<8; #else //X11 uint32_t newv = 255<<24; //Alpha, then RGB newv |= ((((newm>>24)&0xff) * alfa + ((oldm>>16)&0xff) * onemalfa + 128)>>8)<<16; newv |= ((((newm>>16)&0xff) * alfa + ((oldm>>8)&0xff) * onemalfa + 128)>>8)<<8; newv |= ((((newm>>8)&0xff) * alfa + ((oldm>>0)&0xff) * onemalfa + 128)>>8)<<0; #endif *(outdat++) = newv; } } data += stride; } } void CNFGSwapBuffers() { CNFGUpdateScreenWithBitmap( (uint32_t*)CNFGBuffer, CNFGBufferx, CNFGBuffery ); } #endif void InternalHandleResize() { if( CNFGlsBitmap ) DeleteObject( CNFGlsBitmap ); CNFGInternalResize( CNFGBufferx, CNFGBuffery ); CNFGlsBitmap = CreateBitmap( CNFGBufferx, CNFGBuffery, 1, 32, CNFGBuffer ); SelectObject( CNFGlsHDC, CNFGlsBitmap ); CNFGInternalResize( CNFGBufferx, CNFGBuffery); } #else static short CNFGBufferx, CNFGBuffery; static void InternalHandleResize(); #endif #ifdef CNFGOGL #include <GL/gl.h> static HGLRC hRC=NULL; static void InternalHandleResize() { } void CNFGSwapBuffers() { #ifdef CNFG_BATCH CNFGFlushRender(); #endif SwapBuffers(CNFGlsWindowHDC); } #endif void CNFGGetDimensions( short * x, short * y ) { static short lastx, lasty; RECT window; GetClientRect( CNFGlsHWND, &window ); CNFGBufferx = (short)( window.right - window.left); CNFGBuffery = (short)( window.bottom - window.top); if( CNFGBufferx != lastx || CNFGBuffery != lasty ) { lastx = CNFGBufferx; lasty = CNFGBuffery; CNFGInternalResize( lastx, lasty ); InternalHandleResize(); } *x = CNFGBufferx; *y = CNFGBuffery; } #ifndef CNFGOGL void CNFGUpdateScreenWithBitmap( uint32_t * data, int w, int h ) { RECT r; SelectObject( CNFGlsHDC, CNFGlsBitmap ); SetBitmapBits(CNFGlsBitmap,w*h*4,data); BitBlt(CNFGlsWindowHDC, 0, 0, w, h, CNFGlsHDC, 0, 0, SRCCOPY); UpdateWindow( CNFGlsHWND ); short thisw, thish; //Check to see if the window is closed. if( !IsWindow( CNFGlsHWND ) ) { exit( 0 ); } GetClientRect( CNFGlsHWND, &r ); thisw = (short)(r.right - r.left); thish = (short)(r.bottom - r.top); if( thisw != CNFGBufferx || thish != CNFGBuffery ) { CNFGBufferx = thisw; CNFGBuffery = thish; InternalHandleResize(); } } #endif void CNFGTearDown() { PostQuitMessage(0); #ifdef CNFGOGL exit(0); #endif } //This was from the article LRESULT CALLBACK MyWndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { switch(msg) { #ifndef CNFGOGL case WM_SYSCOMMAND: //Not sure why, if deactivated, the dc gets unassociated? if( wParam == SC_RESTORE || wParam == SC_MAXIMIZE || wParam == SC_SCREENSAVE ) { SelectObject( CNFGlsHDC, CNFGlsBitmap ); SelectObject( CNFGlsWindowHDC, CNFGlsBitmap ); } break; #endif case WM_DESTROY: HandleDestroy(); CNFGTearDown(); return 0; } return DefWindowProc(hwnd, msg, wParam, lParam); } //This was from the article, too... well, mostly. int CNFGSetup( const char * name_of_window, int width, int height ) { static LPSTR szClassName = "MyClass"; RECT client, window; WNDCLASS wnd; int w, h, wd, hd; int show_window = 1; HINSTANCE hInstance = GetModuleHandle(NULL); if( width < 0 ) { show_window = 0; width = -width; } if( height < 0 ) { show_window = 0; height = -height; } CNFGBufferx = (short)width; CNFGBuffery = (short)height; wnd.style = CS_HREDRAW | CS_VREDRAW; //we will explain this later wnd.lpfnWndProc = MyWndProc; wnd.cbClsExtra = 0; wnd.cbWndExtra = 0; wnd.hInstance = hInstance; wnd.hIcon = LoadIcon(NULL, IDI_APPLICATION); //default icon wnd.hCursor = LoadCursor(NULL, IDC_ARROW); //default arrow mouse cursor wnd.hbrBackground = (HBRUSH)(COLOR_BACKGROUND); wnd.lpszMenuName = NULL; //no menu wnd.lpszClassName = szClassName; if(!RegisterClass(&wnd)) //register the WNDCLASS { MessageBox(NULL, "This Program Requires Windows NT", "Error", MB_OK); } CNFGlsHWND = CreateWindow(szClassName, name_of_window, //name_of_window, WS_OVERLAPPEDWINDOW, //basic window style CW_USEDEFAULT, CW_USEDEFAULT, //set starting point to default value CNFGBufferx, CNFGBuffery, //set all the dimensions to default value NULL, //no parent window NULL, //no menu hInstance, NULL); //no parameters to pass CNFGlsWindowHDC = GetDC( CNFGlsHWND ); #ifdef CNFGOGL //From NeHe static PIXELFORMATDESCRIPTOR pfd = { sizeof(PIXELFORMATDESCRIPTOR), 1, PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER, PFD_TYPE_RGBA, 24, 8, 0, 8, 8, 8, 16, 8, 24, 32, 8, 8, 8, 8, 16, 0, 0, PFD_MAIN_PLANE, 0, 0, 0, 0 }; GLuint PixelFormat = ChoosePixelFormat( CNFGlsWindowHDC, &pfd ); if( !SetPixelFormat( CNFGlsWindowHDC, PixelFormat, &pfd ) ) { MessageBox( 0, "Could not create PFD for OpenGL Context\n", 0, 0 ); exit( -1 ); } if (!(hRC=wglCreateContext(CNFGlsWindowHDC))) // Are We Able To Get A Rendering Context? { MessageBox( 0, "Could not create OpenGL Context\n", 0, 0 ); exit( -1 ); } if(!wglMakeCurrent(CNFGlsWindowHDC,hRC)) // Try To Activate The Rendering Context { MessageBox( 0, "Could not current OpenGL Context\n", 0, 0 ); exit( -1 ); } #endif CNFGlsHDC = CreateCompatibleDC( CNFGlsWindowHDC ); CNFGlsHDCBlit = CreateCompatibleDC( CNFGlsWindowHDC ); CNFGlsBitmap = CreateCompatibleBitmap( CNFGlsWindowHDC, CNFGBufferx, CNFGBuffery ); SelectObject( CNFGlsHDC, CNFGlsBitmap ); //lsClearBrush = CreateSolidBrush( CNFGBGColor ); //lsHBR = CreateSolidBrush( 0xFFFFFF ); //lsHPEN = CreatePen( PS_SOLID, 0, 0xFFFFFF ); if( show_window ) ShowWindow(CNFGlsHWND, 1); //display the window on the screen //Once set up... we have to change the window's borders so we get the client size right. GetClientRect( CNFGlsHWND, &client ); GetWindowRect( CNFGlsHWND, &window ); w = ( window.right - window.left); h = ( window.bottom - window.top); wd = w - client.right; hd = h - client.bottom; MoveWindow( CNFGlsHWND, window.left, window.top, CNFGBufferx + wd, CNFGBuffery + hd, 1 ); InternalHandleResize(); #ifdef CNFG_BATCH CNFGSetupBatchInternal(); #endif return 0; } void CNFGHandleInput() { MSG msg; while( PeekMessage( &msg, NULL, 0, 0xFFFF, 1 ) ) { TranslateMessage(&msg); switch( msg.message ) { case WM_MOUSEMOVE: HandleMotion( (msg.lParam & 0xFFFF), (msg.lParam>>16) & 0xFFFF, ( (msg.wParam & 0x01)?1:0) | ((msg.wParam & 0x02)?2:0) | ((msg.wParam & 0x10)?4:0) ); break; case WM_LBUTTONDOWN: HandleButton( (msg.lParam & 0xFFFF), (msg.lParam>>16) & 0xFFFF, 1, 1 ); break; case WM_RBUTTONDOWN: HandleButton( (msg.lParam & 0xFFFF), (msg.lParam>>16) & 0xFFFF, 2, 1 ); break; case WM_MBUTTONDOWN: HandleButton( (msg.lParam & 0xFFFF), (msg.lParam>>16) & 0xFFFF, 3, 1 ); break; case WM_LBUTTONUP: HandleButton( (msg.lParam & 0xFFFF), (msg.lParam>>16) & 0xFFFF, 1, 0 ); break; case WM_RBUTTONUP: HandleButton( (msg.lParam & 0xFFFF), (msg.lParam>>16) & 0xFFFF, 2, 0 ); break; case WM_MBUTTONUP: HandleButton( (msg.lParam & 0xFFFF), (msg.lParam>>16) & 0xFFFF, 3, 0 ); break; case WM_KEYDOWN: case WM_KEYUP: HandleKey( tolower( (int) msg.wParam ), (msg.message==WM_KEYDOWN) ); break; default: DispatchMessage(&msg); break; } } } #ifndef CNFGOGL #ifndef CNFGRASTERIZER static HBITMAP lsBackBitmap; static HBRUSH lsHBR; static HPEN lsHPEN; static HBRUSH lsClearBrush; static void InternalHandleResize() { DeleteObject( lsBackBitmap ); lsBackBitmap = CreateCompatibleBitmap( CNFGlsHDC, CNFGBufferx, CNFGBuffery ); SelectObject( CNFGlsHDC, lsBackBitmap ); } #ifdef BATCH_ELEMENTS static int linelisthead; static int pointlisthead; static int polylisthead; static int polylistindex; static POINT linelist[4096*3]; static DWORD twoarray[4096]; static POINT pointlist[4096]; static POINT polylist[8192]; static INT polylistcutoffs[8192]; static int last_linex; static int last_liney; static int possible_lastline; void FlushTacking() { int i; if( twoarray[0] != 2 ) for( i = 0; i < 4096; i++ ) twoarray[i] = 2; if( linelisthead ) { PolyPolyline( CNFGlsHDC, linelist, twoarray, linelisthead ); linelisthead = 0; } if( polylistindex ) { PolyPolygon( CNFGlsHDC, polylist, polylistcutoffs, polylistindex ); polylistindex = 0; polylisthead = 0; } if( possible_lastline ) CNFGTackPixel( last_linex, last_liney ); possible_lastline = 0; //XXX TODO: Consider locking the bitmap, and manually drawing the pixels. if( pointlisthead ) { for( i = 0; i < pointlisthead; i++ ) { SetPixel( CNFGlsHDC, pointlist[i].x, pointlist[i].y, CNFGLastColor ); } pointlisthead = 0; } } #endif uint32_t CNFGColor( uint32_t RGB ) { RGB = COLORSWAPS( RGB ); if( CNFGLastColor == RGB ) return RGB; #ifdef BATCH_ELEMENTS FlushTacking(); #endif CNFGLastColor = RGB; DeleteObject( lsHBR ); lsHBR = CreateSolidBrush( RGB ); SelectObject( CNFGlsHDC, lsHBR ); DeleteObject( lsHPEN ); lsHPEN = CreatePen( PS_SOLID, 0, RGB ); SelectObject( CNFGlsHDC, lsHPEN ); return RGB; } void CNFGBlitImage( uint32_t * data, int x, int y, int w, int h ) { static int pbw, pbh; static HBITMAP pbb; if( !pbb || pbw != w || pbh !=h ) { if( pbb ) DeleteObject( pbb ); pbb = CreateBitmap( w, h, 1, 32, 0 ); pbh = h; pbw = w; } SetBitmapBits(pbb,w*h*4,data); SelectObject( CNFGlsHDCBlit, pbb ); BitBlt(CNFGlsHDC, x, y, w, h, CNFGlsHDCBlit, 0, 0, SRCCOPY); } void CNFGTackSegment( short x1, short y1, short x2, short y2 ) { #ifdef BATCH_ELEMENTS if( ( x1 != last_linex || y1 != last_liney ) && possible_lastline ) { CNFGTackPixel( last_linex, last_liney ); } if( x1 == x2 && y1 == y2 ) { CNFGTackPixel( x1, y1 ); possible_lastline = 0; return; } last_linex = x2; last_liney = y2; possible_lastline = 1; if( x1 != x2 || y1 != y2 ) { linelist[linelisthead*2+0].x = x1; linelist[linelisthead*2+0].y = y1; linelist[linelisthead*2+1].x = x2; linelist[linelisthead*2+1].y = y2; linelisthead++; if( linelisthead >= 2048 ) FlushTacking(); } #else POINT pt[2] = { {x1, y1}, {x2, y2} }; Polyline( CNFGlsHDC, pt, 2 ); SetPixel( CNFGlsHDC, x1, y1, CNFGLastColor ); SetPixel( CNFGlsHDC, x2, y2, CNFGLastColor ); #endif } void CNFGTackRectangle( short x1, short y1, short x2, short y2 ) { #ifdef BATCH_ELEMENTS FlushTacking(); #endif RECT r; if( x1 < x2 ) { r.left = x1; r.right = x2; } else { r.left = x2; r.right = x1; } if( y1 < y2 ) { r.top = y1; r.bottom = y2; } else { r.top = y2; r.bottom = y1; } FillRect( CNFGlsHDC, &r, lsHBR ); } void CNFGClearFrame() { #ifdef BATCH_ELEMENTS FlushTacking(); #endif RECT r = { 0, 0, CNFGBufferx, CNFGBuffery }; DeleteObject( lsClearBrush ); lsClearBrush = CreateSolidBrush( COLORSWAPS(CNFGBGColor) ); HBRUSH prevBrush = SelectObject( CNFGlsHDC, lsClearBrush ); FillRect( CNFGlsHDC, &r, lsClearBrush); SelectObject( CNFGlsHDC, prevBrush ); } void CNFGTackPoly( RDPoint * points, int verts ) { #ifdef BATCH_ELEMENTS if( verts > 8192 ) { FlushTacking(); //Fall-through } else { if( polylistindex >= 8191 || polylisthead + verts >= 8191 ) { FlushTacking(); } int i; for( i = 0; i < verts; i++ ) { polylist[polylisthead].x = points[i].x; polylist[polylisthead].y = points[i].y; polylisthead++; } polylistcutoffs[polylistindex++] = verts; return; } #endif { int i; POINT * t = (POINT*)alloca( sizeof( POINT ) * verts ); for( i = 0; i < verts; i++ ) { t[i].x = points[i].x; t[i].y = points[i].y; } Polygon( CNFGlsHDC, t, verts ); } } void CNFGTackPixel( short x1, short y1 ) { #ifdef BATCH_ELEMENTS pointlist[pointlisthead+0].x = x1; pointlist[pointlisthead+0].y = y1; pointlisthead++; if( pointlisthead >=4096 ) FlushTacking(); #else SetPixel( CNFGlsHDC, x1, y1, CNFGLastColor ); #endif } void CNFGSwapBuffers() { #ifdef BATCH_ELEMENTS FlushTacking(); #endif int thisw, thish; RECT r; BitBlt( CNFGlsWindowHDC, 0, 0, CNFGBufferx, CNFGBuffery, CNFGlsHDC, 0, 0, SRCCOPY ); UpdateWindow( CNFGlsHWND ); //Check to see if the window is closed. if( !IsWindow( CNFGlsHWND ) ) { exit( 0 ); } GetClientRect( CNFGlsHWND, &r ); thisw = r.right - r.left; thish = r.bottom - r.top; if( thisw != CNFGBufferx || thish != CNFGBuffery ) { CNFGBufferx = (short)thisw; CNFGBuffery = (short)thish; InternalHandleResize(); } } void CNFGInternalResize( short bfx, short bfy ) { } #endif #endif #endif // _CNFGWINDRIVER_C #elif defined( EGL_LEAN_AND_MEAN ) //Copyright (c) 2011, 2017, 2018, 2020 <>< Charles Lohr - Under the MIT/x11 or NewBSD License you choose. //This driver cannot create an OpenGL Surface, but can be used for computing for background tasks. //NOTE: This is a truly incomplete driver - if no EGL surface is available, it does not support direct buffer rendering. //Additionally no input is connected. #include <stdio.h> #include <stdlib.h> #include <GLES3/gl3.h> #include <GLES3/gl32.h> #include <EGL/egl.h> #include <GLES2/gl2.h> #include <GLES2/gl2ext.h> #include <GLES2/gl2ext.h> static const EGLint configAttribs[] = { EGL_SURFACE_TYPE, EGL_PBUFFER_BIT, EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, EGL_RED_SIZE, 8, EGL_GREEN_SIZE, 8, EGL_BLUE_SIZE, 8, EGL_NONE }; EGLint context_attribs[] = { EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE }; static int pbufferWidth = 0; static int pbufferHeight = 0; static EGLint pbufferAttribs[] = { EGL_WIDTH, 0, EGL_HEIGHT, 0, EGL_NONE, }; EGLDisplay eglDpy = 0; EGLContext eglCtx = 0; EGLSurface eglSurf = 0; void CNFGGetDimensions( short * x, short * y ) { *x = pbufferWidth; *y = pbufferHeight; } void CNFGChangeWindowTitle( const char * WindowName ) { } void CNFGSetupFullscreen( const char * WindowName, int screen_no ) { //Fullscreen is meaningless for this driver, since it doesn't really open a window. CNFGSetup( WindowName, 1024, 1024 ); } void CNFGTearDown() { if( eglDpy ) { eglTerminate( eglDpy ); } //Unimplemented. } int CNFGSetup( const char * WindowName, int w, int h ) { eglDpy = eglGetDisplay(EGL_DEFAULT_DISPLAY); atexit( CNFGTearDown ); printf( "EGL Display: %p\n", eglDpy ); pbufferAttribs[1] = pbufferWidth = w; pbufferAttribs[3] = pbufferHeight = h; EGLint major, minor; eglInitialize(eglDpy, &major, &minor); EGLint numConfigs=0; EGLConfig eglCfg=NULL; eglChooseConfig(eglDpy, configAttribs, 0, 0, &numConfigs); //this gets number of configs if (numConfigs) { eglChooseConfig(eglDpy, configAttribs, &eglCfg, 1, &numConfigs); printf( " EGL config found\n" ); } else { printf( " Error could not find a valid config avail.. \n" ); } printf( "EGL Major Minor: %d %d\n", major, minor ); eglBindAPI(EGL_OPENGL_API); eglCtx = eglCreateContext(eglDpy, eglCfg, EGL_NO_CONTEXT, context_attribs); int err = eglGetError(); if(err != EGL_SUCCESS) { printf("1. Error %d\n", err); } printf( "EGL Got context: %p\n", eglCtx ); if( w > 0 && h > 0 ) { eglSurf = eglCreatePbufferSurface(eglDpy, eglCfg, pbufferAttribs); eglMakeCurrent(eglDpy, eglSurf, eglSurf, eglCtx); printf( "EGL Current, with surface %p\n", eglSurf ); //Actually have a surface. Need to allocate it. EGLint surfwid; EGLint surfht; eglQuerySurface(eglDpy, eglSurf, EGL_WIDTH, &surfwid); eglQuerySurface(eglDpy, eglSurf, EGL_HEIGHT, &surfht); printf("Window dimensions: %d x %d\n", surfwid, surfht); } else { eglMakeCurrent(eglDpy, EGL_NO_SURFACE, EGL_NO_SURFACE, eglCtx); printf( "EGL Current, no surface.\n" ); } return 0; } void CNFGHandleInput() { //Stubbed (No input) return; } void CNFGUpdateScreenWithBitmap( uint32_t * data, int w, int h ) { //Stubbed (No input) } void CNFGSetVSync( int vson ) { //No-op } void CNFGSwapBuffers() { //No-op } #elif defined( __android__ ) || defined( ANDROID ) /* * Copyright (c) 2011-2013 Luc Verhaegen <libv@skynet.be> * Copyright (c) 2018-2020 <>< Charles Lohr * * 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, sub license, * 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 (including the * next paragraph) 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 NON-INFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ #if defined( __android__ ) && !defined( ANDROID ) #define ANDROID #endif //Note: This interface provides the following two things privately. //you may "extern" them in your code. #ifdef ANDROID #ifndef _CNFG_ANDROID_H #define _CNFG_ANDROID_H //This file contains the additional functions that are available on the Android platform. //In order to build rawdraw for Android, please compile CNFGEGLDriver.c with -DANDROID extern struct android_app * gapp; void AndroidMakeFullscreen(); int AndroidHasPermissions(const char* perm_name); void AndroidRequestAppPermissions(const char * perm); void AndroidDisplayKeyboard(int pShow); int AndroidGetUnicodeChar( int keyCode, int metaState ); void AndroidSendToBack( int param ); extern int android_sdk_version; //Derived at start from property ro.build.version.sdk extern int android_width, android_height; extern int UpdateScreenWithBitmapOffsetX; extern int UpdateScreenWithBitmapOffsetY; //You must implement these. void HandleResume(); void HandleSuspend(); //Departures: // HandleMotion's "mask" parameter is actually just an index, not a mask // CNFGSetup / CNFGSetupFullScreen only controls whether or not the navigation // decoration is removed. Fullscreen means *full screen* To choose fullscreen // or not fullscrene, modify, in your AndroidManifest.xml file, the application // section to either contain or not contain: // android:theme="@android:style/Theme.NoTitleBar.Fullscreen" #endif struct android_app * gapp; static int OGLESStarted; int android_width, android_height; int android_sdk_version; #include <android_native_app_glue.h> #include <jni.h> #include <native_activity.h> #define ERRLOG(...) printf( __VA_ARGS__ ); #else #define ERRLOG(...) fprintf( stderr, __VA_ARGS__ ); #endif #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <stdint.h> #include <EGL/egl.h> #ifdef ANDROID #include <GLES3/gl3.h> #else #include <GLES2/gl2.h> #endif #define EGL_ZBITS 16 #define EGL_IMMEDIATE_SIZE 2048 #ifdef USE_EGL_X #error This feature has never been completed or tested. Display *XDisplay; Window XWindow; #else typedef enum { FBDEV_PIXMAP_DEFAULT = 0, FBDEV_PIXMAP_SUPPORTS_UMP = (1<<0), FBDEV_PIXMAP_ALPHA_FORMAT_PRE = (1<<1), FBDEV_PIXMAP_COLORSPACE_sRGB = (1<<2), FBDEV_PIXMAP_EGL_MEMORY = (1<<3) /* EGL allocates/frees this memory */ } fbdev_pixmap_flags; typedef struct fbdev_window { unsigned short width; unsigned short height; } fbdev_window; typedef struct fbdev_pixmap { unsigned int height; unsigned int width; unsigned int bytes_per_pixel; unsigned char buffer_size; unsigned char red_size; unsigned char green_size; unsigned char blue_size; unsigned char alpha_size; unsigned char luminance_size; fbdev_pixmap_flags flags; unsigned short *data; unsigned int format; /* extra format information in case rgbal is not enough, especially for YUV formats */ } fbdev_pixmap; #if defined( ANDROID ) EGLNativeWindowType native_window; #else struct fbdev_window native_window; #endif #endif static EGLint const config_attribute_list[] = { EGL_RED_SIZE, 8, EGL_GREEN_SIZE, 8, EGL_BLUE_SIZE, 8, EGL_ALPHA_SIZE, 8, EGL_BUFFER_SIZE, 32, EGL_STENCIL_SIZE, 0, EGL_DEPTH_SIZE, EGL_ZBITS, //EGL_SAMPLES, 1, #ifdef ANDROID #if ANDROIDVERSION >= 28 EGL_RENDERABLE_TYPE, EGL_OPENGL_ES3_BIT, #else EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, #endif #else EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, EGL_SURFACE_TYPE, EGL_WINDOW_BIT | EGL_PIXMAP_BIT, #endif EGL_NONE }; static EGLint window_attribute_list[] = { EGL_NONE }; static const EGLint context_attribute_list[] = { EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE }; EGLDisplay egl_display; EGLSurface egl_surface; void CNFGSetVSync( int vson ) { eglSwapInterval(egl_display, vson); } static short iLastInternalW, iLastInternalH; void CNFGSwapBuffers() { CNFGFlushRender(); eglSwapBuffers(egl_display, egl_surface); #ifdef ANDROID android_width = ANativeWindow_getWidth( native_window ); android_height = ANativeWindow_getHeight( native_window ); glViewport( 0, 0, android_width, android_height ); if( iLastInternalW != android_width || iLastInternalH != android_height ) CNFGInternalResize( iLastInternalW=android_width, iLastInternalH=android_height ); #endif } void CNFGGetDimensions( short * x, short * y ) { #ifdef ANDROID *x = android_width; *y = android_height; #else *x = native_window.width; *y = native_window.height; #endif if( *x != iLastInternalW || *y != iLastInternalH ) CNFGInternalResize( iLastInternalW=*x, iLastInternalH=*y ); } int CNFGSetup( const char * WindowName, int w, int h ) { EGLint egl_major, egl_minor; EGLConfig config; EGLint num_config; EGLContext context; //This MUST be called before doing any initialization. int events; while( !OGLESStarted ) { struct android_poll_source* source; if (ALooper_pollAll( 0, 0, &events, (void**)&source) >= 0) { if (source != NULL) source->process(gapp, source); } } #ifdef USE_EGL_X XDisplay = XOpenDisplay(NULL); if (!XDisplay) { ERRLOG( "Error: failed to open X display.\n"); return -1; } Window XRoot = DefaultRootWindow(XDisplay); XSetWindowAttributes XWinAttr; XWinAttr.event_mask = ExposureMask | PointerMotionMask; XWindow = XCreateWindow(XDisplay, XRoot, 0, 0, WIDTH, HEIGHT, 0, CopyFromParent, InputOutput, CopyFromParent, CWEventMask, &XWinAttr); Atom XWMDeleteMessage = XInternAtom(XDisplay, "WM_DELETE_WINDOW", False); XMapWindow(XDisplay, XWindow); XStoreName(XDisplay, XWindow, "Mali libs test"); XSetWMProtocols(XDisplay, XWindow, &XWMDeleteMessage, 1); egl_display = eglGetDisplay((EGLNativeDisplayType) XDisplay); #else #ifndef ANDROID if( w >= 1 && h >= 1 ) { native_window.width = w; native_window.height =h; } #endif egl_display = eglGetDisplay(EGL_DEFAULT_DISPLAY); #endif if (egl_display == EGL_NO_DISPLAY) { ERRLOG( "Error: No display found!\n"); return -1; } if (!eglInitialize(egl_display, &egl_major, &egl_minor)) { ERRLOG( "Error: eglInitialise failed!\n"); return -1; } printf("EGL Version: \"%s\"\n", eglQueryString(egl_display, EGL_VERSION)); printf("EGL Vendor: \"%s\"\n", eglQueryString(egl_display, EGL_VENDOR)); printf("EGL Extensions: \"%s\"\n", eglQueryString(egl_display, EGL_EXTENSIONS)); eglChooseConfig(egl_display, config_attribute_list, &config, 1, &num_config); printf( "Config: %d\n", num_config ); printf( "Creating Context\n" ); context = eglCreateContext(egl_display, config, EGL_NO_CONTEXT, // NULL ); context_attribute_list); if (context == EGL_NO_CONTEXT) { ERRLOG( "Error: eglCreateContext failed: 0x%08X\n", eglGetError()); return -1; } printf( "Context Created %p\n", context ); #ifdef USE_EGL_X egl_surface = eglCreateWindowSurface(egl_display, config, XWindow, window_attribute_list); #else if( native_window && !gapp->window ) { printf( "WARNING: App restarted without a window. Cannot progress.\n" ); exit( 0 ); } printf( "Getting Surface %p\n", native_window = gapp->window ); if( !native_window ) { printf( "FAULT: Cannot get window\n" ); return -5; } android_width = ANativeWindow_getWidth( native_window ); android_height = ANativeWindow_getHeight( native_window ); printf( "Width/Height: %dx%d\n", android_width, android_height ); egl_surface = eglCreateWindowSurface(egl_display, config, #ifdef ANDROID gapp->window, #else (EGLNativeWindowType)&native_window, #endif window_attribute_list); #endif printf( "Got Surface: %p\n", egl_surface ); if (egl_surface == EGL_NO_SURFACE) { ERRLOG( "Error: eglCreateWindowSurface failed: " "0x%08X\n", eglGetError()); return -1; } #ifndef ANDROID int width, height; if (!eglQuerySurface(egl_display, egl_surface, EGL_WIDTH, &width) || !eglQuerySurface(egl_display, egl_surface, EGL_HEIGHT, &height)) { ERRLOG( "Error: eglQuerySurface failed: 0x%08X\n", eglGetError()); return -1; } printf("Surface size: %dx%d\n", width, height); native_window.width = width; native_window.height = height; #endif if (!eglMakeCurrent(egl_display, egl_surface, egl_surface, context)) { ERRLOG( "Error: eglMakeCurrent() failed: 0x%08X\n", eglGetError()); return -1; } printf("GL Vendor: \"%s\"\n", glGetString(GL_VENDOR)); printf("GL Renderer: \"%s\"\n", glGetString(GL_RENDERER)); printf("GL Version: \"%s\"\n", glGetString(GL_VERSION)); printf("GL Extensions: \"%s\"\n", glGetString(GL_EXTENSIONS)); CNFGSetupBatchInternal(); { short dummyx, dummyy; CNFGGetDimensions( &dummyx, &dummyy ); } return 0; } void CNFGSetupFullscreen( const char * WindowName, int screen_number ) { //Removes decoration, must be called before setup. AndroidMakeFullscreen(); CNFGSetup( WindowName, -1, -1 ); } int debuga, debugb, debugc; int32_t handle_input(struct android_app* app, AInputEvent* event) { #ifdef ANDROID //Potentially do other things here. if (AInputEvent_getType(event) == AINPUT_EVENT_TYPE_MOTION) { static uint64_t downmask; int action = AMotionEvent_getAction( event ); int whichsource = action >> 8; action &= AMOTION_EVENT_ACTION_MASK; size_t pointerCount = AMotionEvent_getPointerCount(event); for (size_t i = 0; i < pointerCount; ++i) { int x, y, index; x = AMotionEvent_getX(event, i); y = AMotionEvent_getY(event, i); index = AMotionEvent_getPointerId( event, i ); if( action == AMOTION_EVENT_ACTION_POINTER_DOWN || action == AMOTION_EVENT_ACTION_DOWN ) { int id = index; if( action == AMOTION_EVENT_ACTION_POINTER_DOWN && id != whichsource ) continue; HandleButton( x, y, id, 1 ); downmask |= 1<<id; ANativeActivity_showSoftInput( gapp->activity, ANATIVEACTIVITY_SHOW_SOFT_INPUT_FORCED ); } else if( action == AMOTION_EVENT_ACTION_POINTER_UP || action == AMOTION_EVENT_ACTION_UP || action == AMOTION_EVENT_ACTION_CANCEL ) { int id = index; if( action == AMOTION_EVENT_ACTION_POINTER_UP && id != whichsource ) continue; HandleButton( x, y, id, 0 ); downmask &= ~(1<<id); } else if( action == AMOTION_EVENT_ACTION_MOVE ) { HandleMotion( x, y, index ); } } return 1; } else if (AInputEvent_getType(event) == AINPUT_EVENT_TYPE_KEY) { int code = AKeyEvent_getKeyCode(event); #ifdef ANDROID_USE_SCANCODES HandleKey( code, AKeyEvent_getAction(event) ); #else int unicode = AndroidGetUnicodeChar( code, AMotionEvent_getMetaState( event ) ); if( unicode ) HandleKey( unicode, AKeyEvent_getAction(event) ); else { HandleKey( code, !AKeyEvent_getAction(event) ); return (code == 4)?1:0; //don't override functionality. } #endif return 1; } #endif return 0; } void CNFGHandleInput() { #ifdef ANDROID int events; struct android_poll_source* source; while( ALooper_pollAll( 0, 0, &events, (void**)&source) >= 0 ) { if (source != NULL) { source->process(gapp, source); } } #endif #ifdef USE_EGL_X while (1) { XEvent event; XNextEvent(XDisplay, &event); if ((event.type == MotionNotify) || (event.type == Expose)) Redraw(width, height); else if (event.type == ClientMessage) { if (event.xclient.data.l[0] == XWMDeleteMessage) break; } } XSetWMProtocols(XDisplay, XWindow, &XWMDeleteMessage, 0); #endif } #ifdef ANDROID void handle_cmd(struct android_app* app, int32_t cmd) { switch (cmd) { case APP_CMD_DESTROY: //This gets called initially after back. HandleDestroy(); ANativeActivity_finish( gapp->activity ); break; case APP_CMD_INIT_WINDOW: //When returning from a back button suspension, this isn't called. if( !OGLESStarted ) { OGLESStarted = 1; printf( "Got start event\n" ); } else { CNFGSetup( "", -1, -1 ); HandleResume(); } break; //case APP_CMD_TERM_WINDOW: //This gets called initially when you click "back" //This also gets called when you are brought into standby. //Not sure why - callbacks here seem to break stuff. // break; default: printf( "event not handled: %d", cmd); } } int __system_property_get(const char* name, char* value); void android_main(struct android_app* app) { int main( int argc, char ** argv ); char * argv[] = { "main", 0 }; { char sdk_ver_str[92]; int len = __system_property_get("ro.build.version.sdk", sdk_ver_str); if( len <= 0 ) android_sdk_version = 0; else android_sdk_version = atoi(sdk_ver_str); } gapp = app; app->onAppCmd = handle_cmd; app->onInputEvent = handle_input; printf( "Starting with Android SDK Version: %d", android_sdk_version ); printf( "Starting Main\n" ); main( 1, argv ); printf( "Main Complete\n" ); } void AndroidMakeFullscreen() { //Partially based on https://stackoverflow.com/questions/47507714/how-do-i-enable-full-screen-immersive-mode-for-a-native-activity-ndk-app const struct JNINativeInterface * env = 0; const struct JNINativeInterface ** envptr = &env; const struct JNIInvokeInterface ** jniiptr = gapp->activity->vm; const struct JNIInvokeInterface * jnii = *jniiptr; jnii->AttachCurrentThread( jniiptr, &envptr, NULL); env = (*envptr); //Get android.app.NativeActivity, then get getWindow method handle, returns view.Window type jclass activityClass = env->FindClass( envptr, "android/app/NativeActivity"); jmethodID getWindow = env->GetMethodID( envptr, activityClass, "getWindow", "()Landroid/view/Window;"); jobject window = env->CallObjectMethod( envptr, gapp->activity->clazz, getWindow); //Get android.view.Window class, then get getDecorView method handle, returns view.View type jclass windowClass = env->FindClass( envptr, "android/view/Window"); jmethodID getDecorView = env->GetMethodID( envptr, windowClass, "getDecorView", "()Landroid/view/View;"); jobject decorView = env->CallObjectMethod( envptr, window, getDecorView); //Get the flag values associated with systemuivisibility jclass viewClass = env->FindClass( envptr, "android/view/View"); const int flagLayoutHideNavigation = env->GetStaticIntField( envptr, viewClass, env->GetStaticFieldID( envptr, viewClass, "SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION", "I")); const int flagLayoutFullscreen = env->GetStaticIntField( envptr, viewClass, env->GetStaticFieldID( envptr, viewClass, "SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN", "I")); const int flagLowProfile = env->GetStaticIntField( envptr, viewClass, env->GetStaticFieldID( envptr, viewClass, "SYSTEM_UI_FLAG_LOW_PROFILE", "I")); const int flagHideNavigation = env->GetStaticIntField( envptr, viewClass, env->GetStaticFieldID( envptr, viewClass, "SYSTEM_UI_FLAG_HIDE_NAVIGATION", "I")); const int flagFullscreen = env->GetStaticIntField( envptr, viewClass, env->GetStaticFieldID( envptr, viewClass, "SYSTEM_UI_FLAG_FULLSCREEN", "I")); const int flagImmersiveSticky = env->GetStaticIntField( envptr, viewClass, env->GetStaticFieldID( envptr, viewClass, "SYSTEM_UI_FLAG_IMMERSIVE_STICKY", "I")); jmethodID setSystemUiVisibility = env->GetMethodID( envptr, viewClass, "setSystemUiVisibility", "(I)V"); //Call the decorView.setSystemUiVisibility(FLAGS) env->CallVoidMethod( envptr, decorView, setSystemUiVisibility, (flagLayoutHideNavigation | flagLayoutFullscreen | flagLowProfile | flagHideNavigation | flagFullscreen | flagImmersiveSticky)); //now set some more flags associated with layoutmanager -- note the $ in the class path //search for api-versions.xml //https://android.googlesource.com/platform/development/+/refs/tags/android-9.0.0_r48/sdk/api-versions.xml jclass layoutManagerClass = env->FindClass( envptr, "android/view/WindowManager$LayoutParams"); const int flag_WinMan_Fullscreen = env->GetStaticIntField( envptr, layoutManagerClass, (env->GetStaticFieldID( envptr, layoutManagerClass, "FLAG_FULLSCREEN", "I") )); const int flag_WinMan_KeepScreenOn = env->GetStaticIntField( envptr, layoutManagerClass, (env->GetStaticFieldID( envptr, layoutManagerClass, "FLAG_KEEP_SCREEN_ON", "I") )); const int flag_WinMan_hw_acc = env->GetStaticIntField( envptr, layoutManagerClass, (env->GetStaticFieldID( envptr, layoutManagerClass, "FLAG_HARDWARE_ACCELERATED", "I") )); // const int flag_WinMan_flag_not_fullscreen = env->GetStaticIntField(layoutManagerClass, (env->GetStaticFieldID(layoutManagerClass, "FLAG_FORCE_NOT_FULLSCREEN", "I") )); //call window.addFlags(FLAGS) env->CallVoidMethod( envptr, window, (env->GetMethodID (envptr, windowClass, "addFlags" , "(I)V")), (flag_WinMan_Fullscreen | flag_WinMan_KeepScreenOn | flag_WinMan_hw_acc)); jnii->DetachCurrentThread( jniiptr ); } void AndroidDisplayKeyboard(int pShow) { //Based on https://stackoverflow.com/questions/5864790/how-to-show-the-soft-keyboard-on-native-activity jint lFlags = 0; const struct JNINativeInterface * env = 0; const struct JNINativeInterface ** envptr = &env; const struct JNIInvokeInterface ** jniiptr = gapp->activity->vm; const struct JNIInvokeInterface * jnii = *jniiptr; jnii->AttachCurrentThread( jniiptr, &envptr, NULL); env = (*envptr); jclass activityClass = env->FindClass( envptr, "android/app/NativeActivity"); // Retrieves NativeActivity. jobject lNativeActivity = gapp->activity->clazz; // Retrieves Context.INPUT_METHOD_SERVICE. jclass ClassContext = env->FindClass( envptr, "android/content/Context"); jfieldID FieldINPUT_METHOD_SERVICE = env->GetStaticFieldID( envptr, ClassContext, "INPUT_METHOD_SERVICE", "Ljava/lang/String;" ); jobject INPUT_METHOD_SERVICE = env->GetStaticObjectField( envptr, ClassContext, FieldINPUT_METHOD_SERVICE ); // Runs getSystemService(Context.INPUT_METHOD_SERVICE). jclass ClassInputMethodManager = env->FindClass( envptr, "android/view/inputmethod/InputMethodManager" ); jmethodID MethodGetSystemService = env->GetMethodID( envptr, activityClass, "getSystemService", "(Ljava/lang/String;)Ljava/lang/Object;"); jobject lInputMethodManager = env->CallObjectMethod( envptr, lNativeActivity, MethodGetSystemService, INPUT_METHOD_SERVICE); // Runs getWindow().getDecorView(). jmethodID MethodGetWindow = env->GetMethodID( envptr, activityClass, "getWindow", "()Landroid/view/Window;"); jobject lWindow = env->CallObjectMethod( envptr, lNativeActivity, MethodGetWindow); jclass ClassWindow = env->FindClass( envptr, "android/view/Window"); jmethodID MethodGetDecorView = env->GetMethodID( envptr, ClassWindow, "getDecorView", "()Landroid/view/View;"); jobject lDecorView = env->CallObjectMethod( envptr, lWindow, MethodGetDecorView); if (pShow) { // Runs lInputMethodManager.showSoftInput(...). jmethodID MethodShowSoftInput = env->GetMethodID( envptr, ClassInputMethodManager, "showSoftInput", "(Landroid/view/View;I)Z"); /*jboolean lResult = */env->CallBooleanMethod( envptr, lInputMethodManager, MethodShowSoftInput, lDecorView, lFlags); } else { // Runs lWindow.getViewToken() jclass ClassView = env->FindClass( envptr, "android/view/View"); jmethodID MethodGetWindowToken = env->GetMethodID( envptr, ClassView, "getWindowToken", "()Landroid/os/IBinder;"); jobject lBinder = env->CallObjectMethod( envptr, lDecorView, MethodGetWindowToken); // lInputMethodManager.hideSoftInput(...). jmethodID MethodHideSoftInput = env->GetMethodID( envptr, ClassInputMethodManager, "hideSoftInputFromWindow", "(Landroid/os/IBinder;I)Z"); /*jboolean lRes = */env->CallBooleanMethod( envptr, lInputMethodManager, MethodHideSoftInput, lBinder, lFlags); } // Finished with the JVM. jnii->DetachCurrentThread( jniiptr ); } int AndroidGetUnicodeChar( int keyCode, int metaState ) { //https://stackoverflow.com/questions/21124051/receive-complete-android-unicode-input-in-c-c/43871301 int eventType = AKEY_EVENT_ACTION_DOWN; const struct JNINativeInterface * env = 0; const struct JNINativeInterface ** envptr = &env; const struct JNIInvokeInterface ** jniiptr = gapp->activity->vm; const struct JNIInvokeInterface * jnii = *jniiptr; jnii->AttachCurrentThread( jniiptr, &envptr, NULL); env = (*envptr); //jclass activityClass = env->FindClass( envptr, "android/app/NativeActivity"); // Retrieves NativeActivity. //jobject lNativeActivity = gapp->activity->clazz; jclass class_key_event = env->FindClass( envptr, "android/view/KeyEvent"); int unicodeKey; jmethodID method_get_unicode_char = env->GetMethodID( envptr, class_key_event, "getUnicodeChar", "(I)I"); jmethodID eventConstructor = env->GetMethodID( envptr, class_key_event, "<init>", "(II)V"); jobject eventObj = env->NewObject( envptr, class_key_event, eventConstructor, eventType, keyCode); unicodeKey = env->CallIntMethod( envptr, eventObj, method_get_unicode_char, metaState ); // Finished with the JVM. jnii->DetachCurrentThread( jniiptr ); //printf("Unicode key is: %d", unicodeKey); return unicodeKey; } //Based on: https://stackoverflow.com/questions/41820039/jstringjni-to-stdstringc-with-utf8-characters jstring android_permission_name(const struct JNINativeInterface ** envptr, const char* perm_name) { // nested class permission in class android.Manifest, // hence android 'slash' Manifest 'dollar' permission const struct JNINativeInterface * env = *envptr; jclass ClassManifestpermission = env->FindClass( envptr, "android/Manifest$permission"); jfieldID lid_PERM = env->GetStaticFieldID( envptr, ClassManifestpermission, perm_name, "Ljava/lang/String;" ); jstring ls_PERM = (jstring)(env->GetStaticObjectField( envptr, ClassManifestpermission, lid_PERM )); return ls_PERM; } /** * \brief Tests whether a permission is granted. * \param[in] app a pointer to the android app. * \param[in] perm_name the name of the permission, e.g., * "READ_EXTERNAL_STORAGE", "WRITE_EXTERNAL_STORAGE". * \retval true if the permission is granted. * \retval false otherwise. * \note Requires Android API level 23 (Marshmallow, May 2015) */ int AndroidHasPermissions( const char* perm_name) { struct android_app* app = gapp; const struct JNINativeInterface * env = 0; const struct JNINativeInterface ** envptr = &env; const struct JNIInvokeInterface ** jniiptr = app->activity->vm; const struct JNIInvokeInterface * jnii = *jniiptr; if( android_sdk_version < 23 ) { printf( "Android SDK version %d does not support AndroidHasPermissions\n", android_sdk_version ); return 1; } jnii->AttachCurrentThread( jniiptr, &envptr, NULL); env = (*envptr); int result = 0; jstring ls_PERM = android_permission_name( envptr, perm_name); jint PERMISSION_GRANTED = (-1); { jclass ClassPackageManager = env->FindClass( envptr, "android/content/pm/PackageManager" ); jfieldID lid_PERMISSION_GRANTED = env->GetStaticFieldID( envptr, ClassPackageManager, "PERMISSION_GRANTED", "I" ); PERMISSION_GRANTED = env->GetStaticIntField( envptr, ClassPackageManager, lid_PERMISSION_GRANTED ); } { jobject activity = app->activity->clazz; jclass ClassContext = env->FindClass( envptr, "android/content/Context" ); jmethodID MethodcheckSelfPermission = env->GetMethodID( envptr, ClassContext, "checkSelfPermission", "(Ljava/lang/String;)I" ); jint int_result = env->CallIntMethod( envptr, activity, MethodcheckSelfPermission, ls_PERM ); result = (int_result == PERMISSION_GRANTED); } jnii->DetachCurrentThread( jniiptr ); return result; } /** * \brief Query file permissions. * \details This opens the system dialog that lets the user * grant (or deny) the permission. * \param[in] app a pointer to the android app. * \note Requires Android API level 23 (Marshmallow, May 2015) */ void AndroidRequestAppPermissions(const char * perm) { if( android_sdk_version < 23 ) { printf( "Android SDK version %d does not support AndroidRequestAppPermissions\n",android_sdk_version ); return; } struct android_app* app = gapp; const struct JNINativeInterface * env = 0; const struct JNINativeInterface ** envptr = &env; const struct JNIInvokeInterface ** jniiptr = app->activity->vm; const struct JNIInvokeInterface * jnii = *jniiptr; jnii->AttachCurrentThread( jniiptr, &envptr, NULL); env = (*envptr); jobject activity = app->activity->clazz; jobjectArray perm_array = env->NewObjectArray( envptr, 1, env->FindClass( envptr, "java/lang/String"), env->NewStringUTF( envptr, "" ) ); env->SetObjectArrayElement( envptr, perm_array, 0, android_permission_name( envptr, perm ) ); jclass ClassActivity = env->FindClass( envptr, "android/app/Activity" ); jmethodID MethodrequestPermissions = env->GetMethodID( envptr, ClassActivity, "requestPermissions", "([Ljava/lang/String;I)V" ); // Last arg (0) is just for the callback (that I do not use) env->CallVoidMethod( envptr, activity, MethodrequestPermissions, perm_array, 0 ); jnii->DetachCurrentThread( jniiptr ); } /* Example: int hasperm = android_has_permission( "RECORD_AUDIO" ); if( !hasperm ) { android_request_app_permissions( "RECORD_AUDIO" ); } */ void AndroidSendToBack( int param ) { struct android_app* app = gapp; const struct JNINativeInterface * env = 0; const struct JNINativeInterface ** envptr = &env; const struct JNIInvokeInterface ** jniiptr = app->activity->vm; const struct JNIInvokeInterface * jnii = *jniiptr; jnii->AttachCurrentThread( jniiptr, &envptr, NULL); env = (*envptr); jobject activity = app->activity->clazz; //_glfmCallJavaMethodWithArgs(jni, gapp->activity->clazz, "moveTaskToBack", "(Z)Z", Boolean, false); jclass ClassActivity = env->FindClass( envptr, "android/app/Activity" ); jmethodID MethodmoveTaskToBack = env->GetMethodID( envptr, ClassActivity, "moveTaskToBack", "(Z)Z" ); env->CallBooleanMethod( envptr, activity, MethodmoveTaskToBack, param ); jnii->DetachCurrentThread( jniiptr ); } #endif #elif defined( __wasm__ ) //Right now, designed for use with https://github.com/cnlohr/rawdrawwasm/ #include "CNFG.h" #include <stdint.h> extern void __attribute__((import_module("bynsyncify"))) CNFGSwapBuffersInternal(); void CNFGBlitImageInternal( uint32_t * data, int x, int y, int w, int h ); void print( double idebug ); void prints( const char* sdebug ); //Forward declarations that we get from either WASM or our javascript code. void CNFGClearFrameInternal( uint32_t bgcolor ); //The WASM driver handles internal resizing automatically. #ifndef CNFGRASTERIZER void CNFGInternalResize( short x, short y ) { } void CNFGFlushRender() { if( !CNFGVertPlace ) return; CNFGEmitBackendTriangles( CNFGVertDataV, CNFGVertDataC, CNFGVertPlace ); CNFGVertPlace = 0; } void CNFGClearFrame() { CNFGFlushRender(); CNFGClearFrameInternal( CNFGBGColor ); } void CNFGSwapBuffers() { CNFGFlushRender(); CNFGSwapBuffersInternal( ); } void CNFGHandleInput() { //Do nothing. //Input is handled on swap frame. } void CNFGBlitImage( uint32_t * data, int x, int y, int w, int h ) { CNFGBlitImageInternal( data, x, y, w, h ); } #else //Rasterizer - if you want to do this, you will need to enable blitting in the javascript. //XXX TODO: NEED MEMORY ALLOCATOR extern unsigned char __heap_base; unsigned int bump_pointer = (unsigned int)&__heap_base; void* malloc(unsigned long size) { unsigned int ptr = bump_pointer; bump_pointer += size; return (void *)ptr; } void free(void* ptr) { } //Don't call this file yourself. It is intended to be included in any drivers which want to support the rasterizer plugin. #ifdef CNFGRASTERIZER //#include <stdlib.h> #include <stdint.h> uint32_t * CNFGBuffer = 0; short CNFGBufferx; short CNFGBuffery; #ifdef CNFGOGL void CNFGFlushRender() { } #endif void CNFGInternalResize( short x, short y ) { CNFGBufferx = x; CNFGBuffery = y; if( CNFGBuffer ) free( CNFGBuffer ); CNFGBuffer = malloc( CNFGBufferx * CNFGBuffery * 4 ); #ifdef CNFGOGL void CNFGInternalResizeOGLBACKEND( short w, short h ); CNFGInternalResizeOGLBACKEND( x, y ); #endif } #ifdef __wasm__ static uint32_t SWAPS( uint32_t r ) { uint32_t ret = (r&0xFF)<<24; r>>=8; ret |= (r&0xff)<<16; r>>=8; ret |= (r&0xff)<<8; r>>=8; ret |= (r&0xff)<<0; return ret; } #elif !defined(CNFGOGL) #define SWAPS(x) (x>>8) #else static uint32_t SWAPS( uint32_t r ) { uint32_t ret = (r&0xFF)<<16; r>>=8; ret |= (r&0xff)<<8; r>>=8; ret |= (r&0xff); r>>=8; ret |= (r&0xff)<<24; return ret; } #endif uint32_t CNFGColor( uint32_t RGB ) { CNFGLastColor = SWAPS(RGB); return CNFGLastColor; } void CNFGTackSegment( short x1, short y1, short x2, short y2 ) { short tx, ty; //float slope, lp; float slope; short dx = x2 - x1; short dy = y2 - y1; if( !CNFGBuffer ) return; if( dx < 0 ) dx = -dx; if( dy < 0 ) dy = -dy; if( dx > dy ) { short minx = (x1 < x2)?x1:x2; short maxx = (x1 < x2)?x2:x1; short miny = (x1 < x2)?y1:y2; short maxy = (x1 < x2)?y2:y1; float thisy = miny; slope = (float)(maxy-miny) / (float)(maxx-minx); for( tx = minx; tx <= maxx; tx++ ) { ty = thisy; if( tx < 0 || ty < 0 || ty >= CNFGBuffery ) continue; if( tx >= CNFGBufferx ) break; CNFGBuffer[ty * CNFGBufferx + tx] = CNFGLastColor; thisy += slope; } } else { short minx = (y1 < y2)?x1:x2; short maxx = (y1 < y2)?x2:x1; short miny = (y1 < y2)?y1:y2; short maxy = (y1 < y2)?y2:y1; float thisx = minx; slope = (float)(maxx-minx) / (float)(maxy-miny); for( ty = miny; ty <= maxy; ty++ ) { tx = thisx; if( ty < 0 || tx < 0 || tx >= CNFGBufferx ) continue; if( ty >= CNFGBuffery ) break; CNFGBuffer[ty * CNFGBufferx + tx] = CNFGLastColor; thisx += slope; } } } void CNFGTackRectangle( short x1, short y1, short x2, short y2 ) { short minx = (x1<x2)?x1:x2; short miny = (y1<y2)?y1:y2; short maxx = (x1>=x2)?x1:x2; short maxy = (y1>=y2)?y1:y2; short x, y; if( minx < 0 ) minx = 0; if( miny < 0 ) miny = 0; if( maxx >= CNFGBufferx ) maxx = CNFGBufferx-1; if( maxy >= CNFGBuffery ) maxy = CNFGBuffery-1; for( y = miny; y <= maxy; y++ ) { uint32_t * CNFGBufferstart = &CNFGBuffer[y * CNFGBufferx + minx]; for( x = minx; x <= maxx; x++ ) { (*CNFGBufferstart++) = CNFGLastColor; } } } void CNFGTackPoly( RDPoint * points, int verts ) { short minx = 10000, miny = 10000; short maxx =-10000, maxy =-10000; short i, x, y; //Just in case... if( verts > 32767 ) return; for( i = 0; i < verts; i++ ) { RDPoint * p = &points[i]; if( p->x < minx ) minx = p->x; if( p->y < miny ) miny = p->y; if( p->x > maxx ) maxx = p->x; if( p->y > maxy ) maxy = p->y; } if( miny < 0 ) miny = 0; if( maxy >= CNFGBuffery ) maxy = CNFGBuffery-1; for( y = miny; y <= maxy; y++ ) { short startfillx = maxx; short endfillx = minx; //Figure out what line segments intersect this line. for( i = 0; i < verts; i++ ) { short pl = i + 1; if( pl == verts ) pl = 0; RDPoint ptop; RDPoint pbot; ptop.x = points[i].x; ptop.y = points[i].y; pbot.x = points[pl].x; pbot.y = points[pl].y; //printf( "Poly: %d %d\n", pbot.y, ptop.y ); if( pbot.y < ptop.y ) { RDPoint ptmp; ptmp.x = pbot.x; ptmp.y = pbot.y; pbot.x = ptop.x; pbot.y = ptop.y; ptop.x = ptmp.x; ptop.y = ptmp.y; } //Make sure this line segment is within our range. //printf( "PT: %d %d %d\n", y, ptop.y, pbot.y ); if( ptop.y <= y && pbot.y >= y ) { short diffy = pbot.y - ptop.y; uint32_t placey = (uint32_t)(y - ptop.y)<<16; //Scale by 16 so we can do integer math. short diffx = pbot.x - ptop.x; short isectx; if( diffy == 0 ) { if( pbot.x < ptop.x ) { if( startfillx > pbot.x ) startfillx = pbot.x; if( endfillx < ptop.x ) endfillx = ptop.x; } else { if( startfillx > ptop.x ) startfillx = ptop.x; if( endfillx < pbot.x ) endfillx = pbot.x; } } else { //Inner part is scaled by 65536, outer part must be scaled back. isectx = (( (placey / diffy) * diffx + 32768 )>>16) + ptop.x; if( isectx < startfillx ) startfillx = isectx; if( isectx > endfillx ) endfillx = isectx; } //printf( "R: %d %d %d\n", pbot.x, ptop.x, isectx ); } } //printf( "%d %d %d\n", y, startfillx, endfillx ); if( endfillx >= CNFGBufferx ) endfillx = CNFGBufferx - 1; if( endfillx >= CNFGBufferx ) endfillx = CNFGBuffery - 1; if( startfillx < 0 ) startfillx = 0; if( startfillx < 0 ) startfillx = 0; unsigned int * bufferstart = &CNFGBuffer[y * CNFGBufferx + startfillx]; for( x = startfillx; x <= endfillx; x++ ) { (*bufferstart++) = CNFGLastColor; } } //exit(1); } void CNFGClearFrame() { int i, m; uint32_t col = 0; short x, y; CNFGGetDimensions( &x, &y ); if( x != CNFGBufferx || y != CNFGBuffery || !CNFGBuffer ) { CNFGBufferx = x; CNFGBuffery = y; CNFGBuffer = malloc( x * y * 8 ); } m = x * y; col = CNFGColor( CNFGBGColor ); for( i = 0; i < m; i++ ) { CNFGBuffer[i] = col; } } void CNFGTackPixel( short x, short y ) { if( x < 0 || y < 0 || x >= CNFGBufferx || y >= CNFGBuffery ) return; CNFGBuffer[x+CNFGBufferx*y] = CNFGLastColor; } void CNFGBlitImage( uint32_t * data, int x, int y, int w, int h ) { int ox = x; int stride = w; if( w <= 0 || h <= 0 || x >= CNFGBufferx || y >= CNFGBuffery ) return; if( x < 0 ) { w += x; x = 0; } if( y < 0 ) { h += y; y = 0; } //Switch w,h to x2, y2 h += y; w += x; if( w >= CNFGBufferx ) { w = CNFGBufferx; } if( h >= CNFGBuffery ) { h = CNFGBuffery; } for( ; y < h-1; y++ ) { x = ox; uint32_t * indat = data; uint32_t * outdat = CNFGBuffer + y * CNFGBufferx + x; for( ; x < w-1; x++ ) { uint32_t newm = *(indat++); uint32_t oldm = *(outdat); if( (newm & 0xff) == 0xff ) { *(outdat++) = newm; } else { //Alpha blend. int alfa = newm&0xff; int onemalfa = 255-alfa; #ifdef __wasm__ uint32_t newv = 255<<0; //Alpha, then RGB newv |= ((((newm>>24)&0xff) * alfa + ((oldm>>24)&0xff) * onemalfa + 128)>>8)<<24; newv |= ((((newm>>16)&0xff) * alfa + ((oldm>>16)&0xff) * onemalfa + 128)>>8)<<16; newv |= ((((newm>>8)&0xff) * alfa + ((oldm>>8)&0xff) * onemalfa + 128)>>8)<<8; #elif defined(WINDOWS) || defined(WIN32) || defined(WIN64) || defined(_WIN32) || defined(_WIN64) uint32_t newv = 255<<24; //Alpha, then RGB newv |= ((((newm>>24)&0xff) * alfa + ((oldm>>16)&0xff) * onemalfa + 128)>>8)<<16; newv |= ((((newm>>16)&0xff) * alfa + ((oldm>>8)&0xff) * onemalfa + 128)>>8)<<8; newv |= ((((newm>>8)&0xff) * alfa + ((oldm>>0)&0xff) * onemalfa + 128)>>8)<<0; #elif defined( ANDROID ) || defined( __android__ ) uint32_t newv = 255<<16; //Alpha, then RGB newv |= ((((newm>>24)&0xff) * alfa + ((oldm>>24)&0xff) * onemalfa + 128)>>8)<<24; newv |= ((((newm>>16)&0xff) * alfa + ((oldm>>0)&0xff) * onemalfa + 128)>>8)<<0; newv |= ((((newm>>8)&0xff) * alfa + ((oldm>>8)&0xff) * onemalfa + 128)>>8)<<8; #elif defined( CNFGOGL ) //OGL, on X11 uint32_t newv = 255<<16; //Alpha, then RGB newv |= ((((newm>>24)&0xff) * alfa + ((oldm>>24)&0xff) * onemalfa + 128)>>8)<<24; newv |= ((((newm>>16)&0xff) * alfa + ((oldm>>0)&0xff) * onemalfa + 128)>>8)<<0; newv |= ((((newm>>8)&0xff) * alfa + ((oldm>>8)&0xff) * onemalfa + 128)>>8)<<8; #else //X11 uint32_t newv = 255<<24; //Alpha, then RGB newv |= ((((newm>>24)&0xff) * alfa + ((oldm>>16)&0xff) * onemalfa + 128)>>8)<<16; newv |= ((((newm>>16)&0xff) * alfa + ((oldm>>8)&0xff) * onemalfa + 128)>>8)<<8; newv |= ((((newm>>8)&0xff) * alfa + ((oldm>>0)&0xff) * onemalfa + 128)>>8)<<0; #endif *(outdat++) = newv; } } data += stride; } } void CNFGSwapBuffers() { CNFGUpdateScreenWithBitmap( (uint32_t*)CNFGBuffer, CNFGBufferx, CNFGBuffery ); } #endif extern void CNFGUpdateScreenWithBitmapInternal( uint32_t * data, int w, int h ); void CNFGUpdateScreenWithBitmap( uint32_t * data, int w, int h ) { CNFGBlitImageInternal( data, 0, 0, w, h ); CNFGSwapBuffersInternal(); } void CNFGSetLineWidth( short width ) { //Rasterizer does not support line width. } void CNFGHandleInput() { //Do nothing. //Input is handled on swap frame. } #endif #else //Copyright (c) 2011, 2017, 2018 <>< Charles Lohr - Under the MIT/x11 or NewBSD License you choose. //portions from //http://www.xmission.com/~georgeps/documentation/tutorials/Xlib_Beginner.html //#define HAS_XINERAMA //#define CNFG_HAS_XSHAPE //#define FULL_SCREEN_STEAL_FOCUS #ifndef _CNFGXDRIVER_C #define _CNFGXDRIVER_C #include <X11/Xlib.h> #include <X11/Xutil.h> #include <X11/Xos.h> #include <X11/Xatom.h> #include <X11/keysym.h> #include <stdio.h> #include <stdlib.h> #ifdef HAS_XINERAMA #include <X11/extensions/shape.h> #include <X11/extensions/Xinerama.h> #endif #ifdef CNFG_HAS_XSHAPE #include <X11/extensions/shape.h> static XGCValues xsval; static Pixmap xspixmap; static GC xsgc; static int taint_shape; static int prepare_xshape; static int was_transp; #endif #ifdef CNFG_BATCH void CNFGSetupBatchInternal(); #endif XWindowAttributes CNFGWinAtt; XClassHint *CNFGClassHint; char *wm_res_name = "rawdraw"; char *wm_res_class = "rawdraw"; Display *CNFGDisplay; Window CNFGWindow; int CNFGWindowInvisible; Pixmap CNFGPixmap; GC CNFGGC; GC CNFGWindowGC; Visual * CNFGVisual; int CNFGX11ForceNoDecoration; XImage *xi; int g_x_global_key_state; int g_x_global_shift_key; void CNFGSetWindowIconData( int w, int h, uint32_t * data ) { static Atom net_wm_icon; static Atom cardinal; if( !net_wm_icon ) net_wm_icon = XInternAtom( CNFGDisplay, "_NET_WM_ICON", False ); if( !cardinal ) cardinal = XInternAtom( CNFGDisplay, "CARDINAL", False ); unsigned long outdata[w*h]; int i; for( i = 0; i < w*h; i++ ) { outdata[i+2] = data[i]; } outdata[0] = w; outdata[1] = h; XChangeProperty(CNFGDisplay, CNFGWindow, net_wm_icon, cardinal, 32, PropModeReplace, (const unsigned char*)outdata, 2 + w*h); } #ifdef CNFG_HAS_XSHAPE void CNFGPrepareForTransparency() { prepare_xshape = 1; } void CNFGDrawToTransparencyMode( int transp ) { static Pixmap BackupCNFGPixmap; static GC BackupCNFGGC; if( was_transp && ! transp ) { CNFGGC = BackupCNFGGC; CNFGPixmap = BackupCNFGPixmap; } if( !was_transp && transp ) { BackupCNFGPixmap = CNFGPixmap; BackupCNFGGC = CNFGGC; taint_shape = 1; CNFGGC = xsgc; CNFGPixmap = xspixmap; } was_transp = transp; } void CNFGClearTransparencyLevel() { taint_shape = 1; XSetForeground(CNFGDisplay, xsgc, 0); XFillRectangle(CNFGDisplay, xspixmap, xsgc, 0, 0, CNFGWinAtt.width, CNFGWinAtt.height); XSetForeground(CNFGDisplay, xsgc, 1); } #endif #ifdef CNFGOGL #include <GL/glx.h> #include <GL/glxext.h> GLXContext CNFGCtx; void * CNFGGetExtension( const char * extname ) { return (void*)glXGetProcAddressARB((const GLubyte *) extname); } #endif int FullScreen = 0; void CNFGGetDimensions( short * x, short * y ) { static int lastx; static int lasty; *x = CNFGWinAtt.width; *y = CNFGWinAtt.height; if( lastx != *x || lasty != *y ) { lastx = *x; lasty = *y; CNFGInternalResize( lastx, lasty ); } } void CNFGChangeWindowTitle( const char * WindowName ) { XSetStandardProperties( CNFGDisplay, CNFGWindow, WindowName, 0, 0, 0, 0, 0 ); } static void InternalLinkScreenAndGo( const char * WindowName ) { XFlush(CNFGDisplay); XGetWindowAttributes( CNFGDisplay, CNFGWindow, &CNFGWinAtt ); XGetClassHint( CNFGDisplay, CNFGWindow, CNFGClassHint ); if (!CNFGClassHint) { CNFGClassHint = XAllocClassHint(); if (CNFGClassHint) { CNFGClassHint->res_name = wm_res_name; CNFGClassHint->res_class = wm_res_class; XSetClassHint( CNFGDisplay, CNFGWindow, CNFGClassHint ); } else { fprintf( stderr, "Failed to allocate XClassHint!\n" ); } } else { fprintf( stderr, "Pre-existing XClassHint\n" ); } XSelectInput (CNFGDisplay, CNFGWindow, KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | ExposureMask | PointerMotionMask ); CNFGWindowGC = XCreateGC(CNFGDisplay, CNFGWindow, 0, 0); if( CNFGX11ForceNoDecoration ) { Atom window_type = XInternAtom(CNFGDisplay, "_NET_WM_WINDOW_TYPE", False); long value = XInternAtom(CNFGDisplay, "_NET_WM_WINDOW_TYPE_SPLASH", False); XChangeProperty(CNFGDisplay, CNFGWindow, window_type, XA_ATOM, 32, PropModeReplace, (unsigned char *) &value,1 ); } CNFGPixmap = XCreatePixmap( CNFGDisplay, CNFGWindow, CNFGWinAtt.width, CNFGWinAtt.height, CNFGWinAtt.depth ); CNFGGC = XCreateGC(CNFGDisplay, CNFGPixmap, 0, 0); XSetLineAttributes(CNFGDisplay, CNFGGC, 1, LineSolid, CapRound, JoinRound); CNFGChangeWindowTitle( WindowName ); if( !CNFGWindowInvisible ) XMapWindow(CNFGDisplay, CNFGWindow); #ifdef CNFG_HAS_XSHAPE if( prepare_xshape ) { xsval.foreground = 1; xsval.line_width = 1; xsval.line_style = LineSolid; xspixmap = XCreatePixmap(CNFGDisplay, CNFGWindow, CNFGWinAtt.width, CNFGWinAtt.height, 1); xsgc = XCreateGC(CNFGDisplay, xspixmap, 0, &xsval); XSetLineAttributes(CNFGDisplay, xsgc, 1, LineSolid, CapRound, JoinRound); } #endif } void CNFGSetupFullscreen( const char * WindowName, int screen_no ) { #ifdef HAS_XINERAMA XineramaScreenInfo *screeninfo = NULL; int screens; int event_basep, error_basep, a, b; CNFGDisplay = XOpenDisplay(NULL); int screen = XDefaultScreen(CNFGDisplay); int xpos, ypos; if (!XShapeQueryExtension(CNFGDisplay, &event_basep, &error_basep)) { fprintf( stderr, "X-Server does not support shape extension\n" ); exit( 1 ); } CNFGVisual = DefaultVisual(CNFGDisplay, screen); CNFGWinAtt.depth = DefaultDepth(CNFGDisplay, screen); #ifdef CNFGOGL int attribs[] = { GLX_RGBA, GLX_DOUBLEBUFFER, GLX_RED_SIZE, 1, GLX_GREEN_SIZE, 1, GLX_BLUE_SIZE, 1, GLX_DEPTH_SIZE, 1, None }; XVisualInfo * vis = glXChooseVisual(CNFGDisplay, screen, attribs); CNFGVisual = vis->visual; CNFGWinAtt.depth = vis->depth; CNFGCtx = glXCreateContext( CNFGDisplay, vis, NULL, True ); #endif if (XineramaQueryExtension(CNFGDisplay, &a, &b ) && (screeninfo = XineramaQueryScreens(CNFGDisplay, &screens)) && XineramaIsActive(CNFGDisplay) && screen_no >= 0 && screen_no < screens ) { CNFGWinAtt.width = screeninfo[screen_no].width; CNFGWinAtt.height = screeninfo[screen_no].height; xpos = screeninfo[screen_no].x_org; ypos = screeninfo[screen_no].y_org; } else { CNFGWinAtt.width = XDisplayWidth(CNFGDisplay, screen); CNFGWinAtt.height = XDisplayHeight(CNFGDisplay, screen); xpos = 0; ypos = 0; } if (screeninfo) XFree(screeninfo); XSetWindowAttributes setwinattr; setwinattr.override_redirect = 1; setwinattr.save_under = 1; #ifdef CNFG_HAS_XSHAPE if (prepare_xshape && !XShapeQueryExtension(CNFGDisplay, &event_basep, &error_basep)) { fprintf( stderr, "X-Server does not support shape extension" ); exit( 1 ); } setwinattr.event_mask = 0; #else //This code is probably made irrelevant by the XSetEventMask in InternalLinkScreenAndGo, if this code is not found needed by 2019-12-31, please remove. //setwinattr.event_mask = StructureNotifyMask | SubstructureNotifyMask | ExposureMask | ButtonPressMask | ButtonReleaseMask | ButtonPressMask | PointerMotionMask | ButtonMotionMask | EnterWindowMask | LeaveWindowMask |KeyPressMask |KeyReleaseMask | SubstructureNotifyMask | FocusChangeMask; #endif setwinattr.border_pixel = 0; setwinattr.colormap = XCreateColormap( CNFGDisplay, RootWindow(CNFGDisplay, 0), CNFGVisual, AllocNone); CNFGWindow = XCreateWindow(CNFGDisplay, XRootWindow(CNFGDisplay, screen), xpos, ypos, CNFGWinAtt.width, CNFGWinAtt.height, 0, CNFGWinAtt.depth, InputOutput, CNFGVisual, CWBorderPixel/* | CWEventMask */ | CWOverrideRedirect | CWSaveUnder | CWColormap, &setwinattr); FullScreen = 1; InternalLinkScreenAndGo( WindowName ); #ifdef CNFGOGL glXMakeCurrent( CNFGDisplay, CNFGWindow, CNFGCtx ); #endif #else CNFGSetup( WindowName, 640, 480 ); #endif } void CNFGTearDown() { HandleDestroy(); if( xi ) free( xi ); if ( CNFGClassHint ) XFree( CNFGClassHint ); if ( CNFGGC ) XFreeGC( CNFGDisplay, CNFGGC ); if ( CNFGWindowGC ) XFreeGC( CNFGDisplay, CNFGWindowGC ); if ( CNFGDisplay ) XCloseDisplay( CNFGDisplay ); CNFGDisplay = NULL; CNFGWindowGC = CNFGGC = NULL; CNFGClassHint = NULL; } int CNFGSetupWMClass( const char * WindowName, int w, int h , char * wm_res_name_ , char * wm_res_class_ ) { wm_res_name = wm_res_name_; wm_res_class = wm_res_class_; return CNFGSetup( WindowName, w, h); } int CNFGSetup( const char * WindowName, int w, int h ) { CNFGDisplay = XOpenDisplay(NULL); if ( !CNFGDisplay ) { fprintf( stderr, "Could not get an X Display.\n%s", "Are you in text mode or using SSH without X11-Forwarding?\n" ); exit( 1 ); } atexit( CNFGTearDown ); int screen = DefaultScreen(CNFGDisplay); int depth = DefaultDepth(CNFGDisplay, screen); CNFGVisual = DefaultVisual(CNFGDisplay, screen); Window wnd = DefaultRootWindow( CNFGDisplay ); #ifdef CNFGOGL int attribs[] = { GLX_RGBA, GLX_DOUBLEBUFFER, GLX_RED_SIZE, 1, GLX_GREEN_SIZE, 1, GLX_BLUE_SIZE, 1, GLX_DEPTH_SIZE, 1, None }; XVisualInfo * vis = glXChooseVisual(CNFGDisplay, screen, attribs); CNFGVisual = vis->visual; depth = vis->depth; CNFGCtx = glXCreateContext( CNFGDisplay, vis, NULL, True ); #endif XSetWindowAttributes attr; attr.background_pixel = 0; attr.colormap = XCreateColormap( CNFGDisplay, wnd, CNFGVisual, AllocNone); if( w > 0 && h > 0 ) CNFGWindow = XCreateWindow(CNFGDisplay, wnd, 1, 1, w, h, 0, depth, InputOutput, CNFGVisual, CWBackPixel | CWColormap, &attr ); else { if( w < 0 ) w = -w; if( h < 0 ) h = -h; CNFGWindow = XCreateWindow(CNFGDisplay, wnd, 1, 1, w, h, 0, depth, InputOutput, CNFGVisual, CWBackPixel | CWColormap, &attr ); CNFGWindowInvisible = 1; } InternalLinkScreenAndGo( WindowName ); //Not sure of the purpose of this code - if it's still commented out after 2019-12-31 and no one knows why, please delete it. // Atom WM_DELETE_WINDOW = XInternAtom( CNFGDisplay, "WM_DELETE_WINDOW", False ); // XSetWMProtocols( CNFGDisplay, CNFGWindow, &WM_DELETE_WINDOW, 1 ); #ifdef CNFGOGL glXMakeCurrent( CNFGDisplay, CNFGWindow, CNFGCtx ); #endif #ifdef CNFG_BATCH CNFGSetupBatchInternal(); #endif return 0; } void CNFGHandleInput() { if( !CNFGWindow ) return; static int ButtonsDown; XEvent report; int bKeyDirection = 1; while( XPending( CNFGDisplay ) ) { XNextEvent( CNFGDisplay, &report ); bKeyDirection = 1; switch (report.type) { case NoExpose: break; case Expose: XGetWindowAttributes( CNFGDisplay, CNFGWindow, &CNFGWinAtt ); if( CNFGPixmap ) XFreePixmap( CNFGDisplay, CNFGPixmap ); CNFGPixmap = XCreatePixmap( CNFGDisplay, CNFGWindow, CNFGWinAtt.width, CNFGWinAtt.height, CNFGWinAtt.depth ); if( CNFGGC ) XFreeGC( CNFGDisplay, CNFGGC ); CNFGGC = XCreateGC(CNFGDisplay, CNFGPixmap, 0, 0); break; case KeyRelease: { bKeyDirection = 0; //Tricky - handle key repeats cleanly. if( XPending( CNFGDisplay ) ) { XEvent nev; XPeekEvent( CNFGDisplay, &nev ); if (nev.type == KeyPress && nev.xkey.time == report.xkey.time && nev.xkey.keycode == report.xkey.keycode ) bKeyDirection = 2; } } case KeyPress: g_x_global_key_state = report.xkey.state; g_x_global_shift_key = XLookupKeysym(&report.xkey, 1); HandleKey( XLookupKeysym(&report.xkey, 0), bKeyDirection ); break; case ButtonRelease: bKeyDirection = 0; case ButtonPress: HandleButton( report.xbutton.x, report.xbutton.y, report.xbutton.button, bKeyDirection ); ButtonsDown = (ButtonsDown & (~(1<<report.xbutton.button))) | ( bKeyDirection << report.xbutton.button ); //Intentionall fall through -- we want to send a motion in event of a button as well. case MotionNotify: HandleMotion( report.xmotion.x, report.xmotion.y, ButtonsDown>>1 ); break; case ClientMessage: // Only subscribed to WM_DELETE_WINDOW, so just exit exit( 0 ); break; default: break; //printf( "Event: %d\n", report.type ); } } } #ifdef CNFGOGL void CNFGSetVSync( int vson ) { void (*glfn)( int ); glfn = (void (*)( int ))CNFGGetExtension( "glXSwapIntervalMESA" ); if( glfn ) glfn( vson ); glfn = (void (*)( int ))CNFGGetExtension( "glXSwapIntervalSGI" ); if( glfn ) glfn( vson ); glfn = (void (*)( int ))CNFGGetExtension( "glXSwapIntervalEXT" ); if( glfn ) glfn( vson ); } #ifdef CNFGRASTERIZER void CNFGSwapBuffersInternal() #else void CNFGSwapBuffers() #endif { if( CNFGWindowInvisible ) return; #ifndef CNFGRASTERIZER CNFGFlushRender(); #endif #ifdef CNFG_HAS_XSHAPE if( taint_shape ) { XShapeCombineMask(CNFGDisplay, CNFGWindow, ShapeBounding, 0, 0, xspixmap, ShapeSet); taint_shape = 0; } #endif //CNFG_HAS_XSHAPE glXSwapBuffers( CNFGDisplay, CNFGWindow ); #ifdef FULL_SCREEN_STEAL_FOCUS if( FullScreen ) XSetInputFocus( CNFGDisplay, CNFGWindow, RevertToParent, CurrentTime ); #endif //FULL_SCREEN_STEAL_FOCUS } #else //CNFGOGL #ifndef CNFGRASTERIZER void CNFGBlitImage( uint32_t * data, int x, int y, int w, int h ) { static int depth; static int lw, lh; if( !xi ) { int screen = DefaultScreen(CNFGDisplay); depth = DefaultDepth(CNFGDisplay, screen)/8; } if( lw != w || lh != h ) { if( xi ) free( xi ); xi = XCreateImage(CNFGDisplay, CNFGVisual, depth*8, ZPixmap, 0, (char*)data, w, h, 32, w*4 ); lw = w; lh = h; } //Draw image to pixmap (not a screen flip) XPutImage(CNFGDisplay, CNFGPixmap, CNFGGC, xi, 0, 0, x, y, w, h ); } #endif void CNFGUpdateScreenWithBitmap( uint32_t * data, int w, int h ) { static int depth; static int lw, lh; if( !xi ) { int screen = DefaultScreen(CNFGDisplay); depth = DefaultDepth(CNFGDisplay, screen)/8; // xi = XCreateImage(CNFGDisplay, DefaultVisual( CNFGDisplay, DefaultScreen(CNFGDisplay) ), depth*8, ZPixmap, 0, (char*)data, w, h, 32, w*4 ); // lw = w; // lh = h; } if( lw != w || lh != h ) { if( xi ) free( xi ); xi = XCreateImage(CNFGDisplay, CNFGVisual, depth*8, ZPixmap, 0, (char*)data, w, h, 32, w*4 ); lw = w; lh = h; } //Directly write image to screen (effectively a flip) XPutImage(CNFGDisplay, CNFGWindow, CNFGWindowGC, xi, 0, 0, 0, 0, w, h ); } #endif //CNFGOGL #if !defined( CNFGOGL) #define AGLF(x) x #else #define AGLF(x) static inline BACKEND_##x #endif #if defined( CNFGRASTERIZER ) //Don't call this file yourself. It is intended to be included in any drivers which want to support the rasterizer plugin. #ifdef CNFGRASTERIZER //#include <stdlib.h> #include <stdint.h> uint32_t * CNFGBuffer = 0; short CNFGBufferx; short CNFGBuffery; #ifdef CNFGOGL void CNFGFlushRender() { } #endif void CNFGInternalResize( short x, short y ) { CNFGBufferx = x; CNFGBuffery = y; if( CNFGBuffer ) free( CNFGBuffer ); CNFGBuffer = malloc( CNFGBufferx * CNFGBuffery * 4 ); #ifdef CNFGOGL void CNFGInternalResizeOGLBACKEND( short w, short h ); CNFGInternalResizeOGLBACKEND( x, y ); #endif } #ifdef __wasm__ static uint32_t SWAPS( uint32_t r ) { uint32_t ret = (r&0xFF)<<24; r>>=8; ret |= (r&0xff)<<16; r>>=8; ret |= (r&0xff)<<8; r>>=8; ret |= (r&0xff)<<0; return ret; } #elif !defined(CNFGOGL) #define SWAPS(x) (x>>8) #else static uint32_t SWAPS( uint32_t r ) { uint32_t ret = (r&0xFF)<<16; r>>=8; ret |= (r&0xff)<<8; r>>=8; ret |= (r&0xff); r>>=8; ret |= (r&0xff)<<24; return ret; } #endif uint32_t CNFGColor( uint32_t RGB ) { CNFGLastColor = SWAPS(RGB); return CNFGLastColor; } void CNFGTackSegment( short x1, short y1, short x2, short y2 ) { short tx, ty; //float slope, lp; float slope; short dx = x2 - x1; short dy = y2 - y1; if( !CNFGBuffer ) return; if( dx < 0 ) dx = -dx; if( dy < 0 ) dy = -dy; if( dx > dy ) { short minx = (x1 < x2)?x1:x2; short maxx = (x1 < x2)?x2:x1; short miny = (x1 < x2)?y1:y2; short maxy = (x1 < x2)?y2:y1; float thisy = miny; slope = (float)(maxy-miny) / (float)(maxx-minx); for( tx = minx; tx <= maxx; tx++ ) { ty = thisy; if( tx < 0 || ty < 0 || ty >= CNFGBuffery ) continue; if( tx >= CNFGBufferx ) break; CNFGBuffer[ty * CNFGBufferx + tx] = CNFGLastColor; thisy += slope; } } else { short minx = (y1 < y2)?x1:x2; short maxx = (y1 < y2)?x2:x1; short miny = (y1 < y2)?y1:y2; short maxy = (y1 < y2)?y2:y1; float thisx = minx; slope = (float)(maxx-minx) / (float)(maxy-miny); for( ty = miny; ty <= maxy; ty++ ) { tx = thisx; if( ty < 0 || tx < 0 || tx >= CNFGBufferx ) continue; if( ty >= CNFGBuffery ) break; CNFGBuffer[ty * CNFGBufferx + tx] = CNFGLastColor; thisx += slope; } } } void CNFGTackRectangle( short x1, short y1, short x2, short y2 ) { short minx = (x1<x2)?x1:x2; short miny = (y1<y2)?y1:y2; short maxx = (x1>=x2)?x1:x2; short maxy = (y1>=y2)?y1:y2; short x, y; if( minx < 0 ) minx = 0; if( miny < 0 ) miny = 0; if( maxx >= CNFGBufferx ) maxx = CNFGBufferx-1; if( maxy >= CNFGBuffery ) maxy = CNFGBuffery-1; for( y = miny; y <= maxy; y++ ) { uint32_t * CNFGBufferstart = &CNFGBuffer[y * CNFGBufferx + minx]; for( x = minx; x <= maxx; x++ ) { (*CNFGBufferstart++) = CNFGLastColor; } } } void CNFGTackPoly( RDPoint * points, int verts ) { short minx = 10000, miny = 10000; short maxx =-10000, maxy =-10000; short i, x, y; //Just in case... if( verts > 32767 ) return; for( i = 0; i < verts; i++ ) { RDPoint * p = &points[i]; if( p->x < minx ) minx = p->x; if( p->y < miny ) miny = p->y; if( p->x > maxx ) maxx = p->x; if( p->y > maxy ) maxy = p->y; } if( miny < 0 ) miny = 0; if( maxy >= CNFGBuffery ) maxy = CNFGBuffery-1; for( y = miny; y <= maxy; y++ ) { short startfillx = maxx; short endfillx = minx; //Figure out what line segments intersect this line. for( i = 0; i < verts; i++ ) { short pl = i + 1; if( pl == verts ) pl = 0; RDPoint ptop; RDPoint pbot; ptop.x = points[i].x; ptop.y = points[i].y; pbot.x = points[pl].x; pbot.y = points[pl].y; //printf( "Poly: %d %d\n", pbot.y, ptop.y ); if( pbot.y < ptop.y ) { RDPoint ptmp; ptmp.x = pbot.x; ptmp.y = pbot.y; pbot.x = ptop.x; pbot.y = ptop.y; ptop.x = ptmp.x; ptop.y = ptmp.y; } //Make sure this line segment is within our range. //printf( "PT: %d %d %d\n", y, ptop.y, pbot.y ); if( ptop.y <= y && pbot.y >= y ) { short diffy = pbot.y - ptop.y; uint32_t placey = (uint32_t)(y - ptop.y)<<16; //Scale by 16 so we can do integer math. short diffx = pbot.x - ptop.x; short isectx; if( diffy == 0 ) { if( pbot.x < ptop.x ) { if( startfillx > pbot.x ) startfillx = pbot.x; if( endfillx < ptop.x ) endfillx = ptop.x; } else { if( startfillx > ptop.x ) startfillx = ptop.x; if( endfillx < pbot.x ) endfillx = pbot.x; } } else { //Inner part is scaled by 65536, outer part must be scaled back. isectx = (( (placey / diffy) * diffx + 32768 )>>16) + ptop.x; if( isectx < startfillx ) startfillx = isectx; if( isectx > endfillx ) endfillx = isectx; } //printf( "R: %d %d %d\n", pbot.x, ptop.x, isectx ); } } //printf( "%d %d %d\n", y, startfillx, endfillx ); if( endfillx >= CNFGBufferx ) endfillx = CNFGBufferx - 1; if( endfillx >= CNFGBufferx ) endfillx = CNFGBuffery - 1; if( startfillx < 0 ) startfillx = 0; if( startfillx < 0 ) startfillx = 0; unsigned int * bufferstart = &CNFGBuffer[y * CNFGBufferx + startfillx]; for( x = startfillx; x <= endfillx; x++ ) { (*bufferstart++) = CNFGLastColor; } } //exit(1); } void CNFGClearFrame() { int i, m; uint32_t col = 0; short x, y; CNFGGetDimensions( &x, &y ); if( x != CNFGBufferx || y != CNFGBuffery || !CNFGBuffer ) { CNFGBufferx = x; CNFGBuffery = y; CNFGBuffer = malloc( x * y * 8 ); } m = x * y; col = CNFGColor( CNFGBGColor ); for( i = 0; i < m; i++ ) { CNFGBuffer[i] = col; } } void CNFGTackPixel( short x, short y ) { if( x < 0 || y < 0 || x >= CNFGBufferx || y >= CNFGBuffery ) return; CNFGBuffer[x+CNFGBufferx*y] = CNFGLastColor; } void CNFGBlitImage( uint32_t * data, int x, int y, int w, int h ) { int ox = x; int stride = w; if( w <= 0 || h <= 0 || x >= CNFGBufferx || y >= CNFGBuffery ) return; if( x < 0 ) { w += x; x = 0; } if( y < 0 ) { h += y; y = 0; } //Switch w,h to x2, y2 h += y; w += x; if( w >= CNFGBufferx ) { w = CNFGBufferx; } if( h >= CNFGBuffery ) { h = CNFGBuffery; } for( ; y < h-1; y++ ) { x = ox; uint32_t * indat = data; uint32_t * outdat = CNFGBuffer + y * CNFGBufferx + x; for( ; x < w-1; x++ ) { uint32_t newm = *(indat++); uint32_t oldm = *(outdat); if( (newm & 0xff) == 0xff ) { *(outdat++) = newm; } else { //Alpha blend. int alfa = newm&0xff; int onemalfa = 255-alfa; #ifdef __wasm__ uint32_t newv = 255<<0; //Alpha, then RGB newv |= ((((newm>>24)&0xff) * alfa + ((oldm>>24)&0xff) * onemalfa + 128)>>8)<<24; newv |= ((((newm>>16)&0xff) * alfa + ((oldm>>16)&0xff) * onemalfa + 128)>>8)<<16; newv |= ((((newm>>8)&0xff) * alfa + ((oldm>>8)&0xff) * onemalfa + 128)>>8)<<8; #elif defined(WINDOWS) || defined(WIN32) || defined(WIN64) || defined(_WIN32) || defined(_WIN64) uint32_t newv = 255<<24; //Alpha, then RGB newv |= ((((newm>>24)&0xff) * alfa + ((oldm>>16)&0xff) * onemalfa + 128)>>8)<<16; newv |= ((((newm>>16)&0xff) * alfa + ((oldm>>8)&0xff) * onemalfa + 128)>>8)<<8; newv |= ((((newm>>8)&0xff) * alfa + ((oldm>>0)&0xff) * onemalfa + 128)>>8)<<0; #elif defined( ANDROID ) || defined( __android__ ) uint32_t newv = 255<<16; //Alpha, then RGB newv |= ((((newm>>24)&0xff) * alfa + ((oldm>>24)&0xff) * onemalfa + 128)>>8)<<24; newv |= ((((newm>>16)&0xff) * alfa + ((oldm>>0)&0xff) * onemalfa + 128)>>8)<<0; newv |= ((((newm>>8)&0xff) * alfa + ((oldm>>8)&0xff) * onemalfa + 128)>>8)<<8; #elif defined( CNFGOGL ) //OGL, on X11 uint32_t newv = 255<<16; //Alpha, then RGB newv |= ((((newm>>24)&0xff) * alfa + ((oldm>>24)&0xff) * onemalfa + 128)>>8)<<24; newv |= ((((newm>>16)&0xff) * alfa + ((oldm>>0)&0xff) * onemalfa + 128)>>8)<<0; newv |= ((((newm>>8)&0xff) * alfa + ((oldm>>8)&0xff) * onemalfa + 128)>>8)<<8; #else //X11 uint32_t newv = 255<<24; //Alpha, then RGB newv |= ((((newm>>24)&0xff) * alfa + ((oldm>>16)&0xff) * onemalfa + 128)>>8)<<16; newv |= ((((newm>>16)&0xff) * alfa + ((oldm>>8)&0xff) * onemalfa + 128)>>8)<<8; newv |= ((((newm>>8)&0xff) * alfa + ((oldm>>0)&0xff) * onemalfa + 128)>>8)<<0; #endif *(outdat++) = newv; } } data += stride; } } void CNFGSwapBuffers() { CNFGUpdateScreenWithBitmap( (uint32_t*)CNFGBuffer, CNFGBufferx, CNFGBuffery ); } #endif #undef AGLF #define AGLF(x) static inline BACKEND_##x #endif uint32_t AGLF(CNFGColor)( uint32_t RGB ) { CNFGLastColor = RGB; unsigned char red = ( RGB >> 24 ) & 0xFF; unsigned char grn = ( RGB >> 16 ) & 0xFF; unsigned char blu = ( RGB >> 8 ) & 0xFF; unsigned long color = (red<<16)|(grn<<8)|(blu); XSetForeground(CNFGDisplay, CNFGGC, color); return color; } void AGLF(CNFGClearFrame)() { XGetWindowAttributes( CNFGDisplay, CNFGWindow, &CNFGWinAtt ); XSetForeground(CNFGDisplay, CNFGGC, CNFGColor(CNFGBGColor) ); XFillRectangle(CNFGDisplay, CNFGPixmap, CNFGGC, 0, 0, CNFGWinAtt.width, CNFGWinAtt.height ); } void AGLF(CNFGSwapBuffers)() { #ifdef CNFG_HAS_XSHAPE if( taint_shape ) { XShapeCombineMask(CNFGDisplay, CNFGWindow, ShapeBounding, 0, 0, xspixmap, ShapeSet); taint_shape = 0; } #endif XCopyArea(CNFGDisplay, CNFGPixmap, CNFGWindow, CNFGWindowGC, 0,0,CNFGWinAtt.width,CNFGWinAtt.height,0,0); XFlush(CNFGDisplay); #ifdef FULL_SCREEN_STEAL_FOCUS if( FullScreen ) XSetInputFocus( CNFGDisplay, CNFGWindow, RevertToParent, CurrentTime ); #endif } void AGLF(CNFGTackSegment)( short x1, short y1, short x2, short y2 ) { if( x1 == x2 && y1 == y2 ) { //On some targets, zero-length lines will not show up. //This is tricky - since this will also cause more draw calls for points on systems like GLAMOR. XDrawPoint( CNFGDisplay, CNFGPixmap, CNFGGC, x2, y2 ); } else { //XXX HACK! See discussion here: https://github.com/cntools/cnping/issues/68 XDrawLine( CNFGDisplay, CNFGPixmap, CNFGGC, x1, y1, x2, y2 ); XDrawLine( CNFGDisplay, CNFGPixmap, CNFGGC, x2, y2, x1, y1 ); } } void AGLF(CNFGTackPixel)( short x1, short y1 ) { XDrawPoint( CNFGDisplay, CNFGPixmap, CNFGGC, x1, y1 ); } void AGLF(CNFGTackRectangle)( short x1, short y1, short x2, short y2 ) { XFillRectangle(CNFGDisplay, CNFGPixmap, CNFGGC, x1, y1, x2-x1, y2-y1 ); } void AGLF(CNFGTackPoly)( RDPoint * points, int verts ) { XFillPolygon(CNFGDisplay, CNFGPixmap, CNFGGC, (XPoint *)points, verts, Convex, CoordModeOrigin ); } void AGLF(CNFGInternalResize)( short x, short y ) { } void AGLF(CNFGSetLineWidth)( short width ) { XSetLineAttributes(CNFGDisplay, CNFGGC, width, LineSolid, CapRound, JoinRound); } #endif // _CNFGXDRIVER_C #endif /* Copyright (c) 2010-2021 <>< Charles Lohr, and several others! 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 X CONSORTIUM BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef _CNFG_C #define _CNFG_C #ifdef _CNFG_FANCYFONT #include "TextTool/FontData.h" #endif int CNFGPenX, CNFGPenY; uint32_t CNFGBGColor; uint32_t CNFGLastColor; //uint32_t CNFGDialogColor; //background for boxes [DEPRECATED] // The following two arrays are generated by Fonter/fonter.cpp const unsigned short RawdrawFontCharMap[256] = { 65535, 0, 8, 16, 24, 31, 41, 50, 51, 65535, 65535, 57, 66, 65535, 75, 83, 92, 96, 100, 108, 114, 123, 132, 137, 147, 152, 158, 163, 169, 172, 178, 182, 65535, 186, 189, 193, 201, 209, 217, 226, 228, 232, 236, 244, 248, 250, 252, 253, 255, 261, 266, 272, 278, 283, 289, 295, 300, 309, 316, 318, 321, 324, 328, 331, 337, 345, 352, 362, 368, 375, 382, 388, 396, 402, 408, 413, 422, 425, 430, 435, 442, 449, 458, 466, 472, 476, 480, 485, 492, 500, 507, 512, 516, 518, 522, 525, 527, 529, 536, 541, 546, 551, 557, 564, 572, 578, 581, 586, 593, 595, 604, 610, 615, 621, 627, 632, 638, 642, 648, 653, 660, 664, 670, 674, 680, 684, 690, 694, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 700, 703, 711, 718, 731, 740, 744, 754, 756, 760, 766, 772, 775, 777, 785, 787, 792, 798, 803, 811, 813, 820, 827, 828, 831, 833, 838, 844, 853, 862, 874, 880, 889, 898, 908, 919, 928, 939, 951, 960, 969, 978, 988, 997, 1005, 1013, 1022, 1030, 1039, 1047, 1054, 1061, 1070, 1079, 1086, 1090, 1099, 1105, 1111, 1118, 1124, 1133, 1140, 1150, 1159, 1168, 1178, 1189, 1198, 1209, 1222, 1231, 1239, 1247, 1256, 1264, 1268, 1272, 1277, 1281, 1290, 1300, 1307, 1314, 1322, 1331, 1338, 1342, 1349, 1357, 1365, 1374, 1382, 1390, 1397, 65535, }; const unsigned char RawdrawFontCharData[1405] = { 0x00, 0x09, 0x20, 0x29, 0x03, 0x23, 0x14, 0x8b, 0x00, 0x09, 0x20, 0x29, 0x04, 0x24, 0x13, 0x8c, 0x01, 0x21, 0x23, 0x14, 0x03, 0x09, 0x11, 0x9a, 0x11, 0x22, 0x23, 0x14, 0x03, 0x02, 0x99, 0x01, 0x21, 0x23, 0x09, 0x03, 0x29, 0x03, 0x09, 0x12, 0x9c, 0x03, 0x2b, 0x13, 0x1c, 0x23, 0x22, 0x11, 0x02, 0x8b, 0x9a, 0x1a, 0x01, 0x21, 0x23, 0x03, 0x89, 0x03, 0x21, 0x2a, 0x21, 0x19, 0x03, 0x14, 0x23, 0x9a, 0x01, 0x10, 0x21, 0x12, 0x09, 0x12, 0x1c, 0x03, 0xab, 0x02, 0x03, 0x1b, 0x02, 0x1a, 0x13, 0x10, 0xa9, 0x01, 0x2b, 0x03, 0x29, 0x02, 0x11, 0x22, 0x13, 0x8a, 0x00, 0x22, 0x04, 0x88, 0x20, 0x02, 0x24, 0xa8, 0x01, 0x10, 0x29, 0x10, 0x14, 0x0b, 0x14, 0xab, 0x00, 0x0b, 0x0c, 0x20, 0x2b, 0xac, 0x00, 0x28, 0x00, 0x02, 0x2a, 0x10, 0x1c, 0x20, 0xac, 0x01, 0x21, 0x23, 0x03, 0x09, 0x20, 0x10, 0x14, 0x8c, 0x03, 0x23, 0x24, 0x04, 0x8b, 0x01, 0x10, 0x29, 0x10, 0x14, 0x0b, 0x14, 0x2b, 0x04, 0xac, 0x01, 0x18, 0x21, 0x10, 0x9c, 0x03, 0x1c, 0x23, 0x1c, 0x10, 0x9c, 0x02, 0x22, 0x19, 0x22, 0x9b, 0x02, 0x2a, 0x02, 0x19, 0x02, 0x9b, 0x01, 0x02, 0xaa, 0x02, 0x22, 0x11, 0x02, 0x13, 0xaa, 0x11, 0x22, 0x02, 0x99, 0x02, 0x13, 0x22, 0x8a, 0x10, 0x1b, 0x9c, 0x10, 0x09, 0x20, 0x99, 0x10, 0x1c, 0x20, 0x2c, 0x01, 0x29, 0x03, 0xab, 0x21, 0x10, 0x01, 0x23, 0x14, 0x0b, 0x10, 0x9c, 0x00, 0x09, 0x23, 0x2c, 0x04, 0x03, 0x21, 0xa8, 0x21, 0x10, 0x01, 0x12, 0x03, 0x14, 0x2b, 0x02, 0xac, 0x10, 0x99, 0x10, 0x01, 0x03, 0x9c, 0x10, 0x21, 0x23, 0x9c, 0x01, 0x2b, 0x11, 0x1b, 0x21, 0x0b, 0x02, 0xaa, 0x02, 0x2a, 0x11, 0x9b, 0x04, 0x9b, 0x02, 0xaa, 0x9c, 0x03, 0xa9, 0x00, 0x20, 0x24, 0x04, 0x08, 0x9a, 0x01, 0x10, 0x1c, 0x04, 0xac, 0x01, 0x10, 0x21, 0x22, 0x04, 0xac, 0x00, 0x20, 0x24, 0x0c, 0x12, 0xaa, 0x00, 0x02, 0x2a, 0x20, 0xac, 0x20, 0x00, 0x02, 0x22, 0x24, 0x8c, 0x20, 0x02, 0x22, 0x24, 0x04, 0x8a, 0x00, 0x20, 0x21, 0x12, 0x9c, 0x00, 0x0c, 0x00, 0x20, 0x2c, 0x04, 0x2c, 0x02, 0xaa, 0x00, 0x02, 0x22, 0x20, 0x08, 0x22, 0x8c, 0x19, 0x9b, 0x19, 0x13, 0x8c, 0x20, 0x02, 0xac, 0x01, 0x29, 0x03, 0xab, 0x00, 0x22, 0x8c, 0x01, 0x10, 0x21, 0x12, 0x1b, 0x9c, 0x21, 0x01, 0x04, 0x24, 0x22, 0x12, 0x13, 0xab, 0x04, 0x01, 0x10, 0x21, 0x2c, 0x02, 0xaa, 0x00, 0x04, 0x14, 0x23, 0x12, 0x0a, 0x12, 0x21, 0x10, 0x88, 0x23, 0x14, 0x03, 0x01, 0x10, 0xa9, 0x00, 0x10, 0x21, 0x23, 0x14, 0x04, 0x88, 0x00, 0x04, 0x2c, 0x00, 0x28, 0x02, 0x9a, 0x00, 0x0c, 0x00, 0x28, 0x02, 0x9a, 0x21, 0x10, 0x01, 0x03, 0x14, 0x23, 0x22, 0x9a, 0x00, 0x0c, 0x20, 0x2c, 0x02, 0xaa, 0x00, 0x28, 0x10, 0x1c, 0x04, 0xac, 0x00, 0x20, 0x23, 0x14, 0x8b, 0x00, 0x0c, 0x02, 0x12, 0x21, 0x28, 0x12, 0x23, 0xac, 0x00, 0x04, 0xac, 0x04, 0x00, 0x11, 0x20, 0xac, 0x04, 0x00, 0x2a, 0x20, 0xac, 0x01, 0x10, 0x21, 0x23, 0x14, 0x03, 0x89, 0x00, 0x0c, 0x00, 0x10, 0x21, 0x12, 0x8a, 0x01, 0x10, 0x21, 0x23, 0x14, 0x03, 0x09, 0x04, 0x9b, 0x00, 0x0c, 0x00, 0x10, 0x21, 0x12, 0x02, 0xac, 0x21, 0x10, 0x01, 0x23, 0x14, 0x8b, 0x00, 0x28, 0x10, 0x9c, 0x00, 0x04, 0x24, 0xa8, 0x00, 0x03, 0x14, 0x23, 0xa8, 0x00, 0x04, 0x2c, 0x14, 0x1b, 0x24, 0xa8, 0x00, 0x01, 0x23, 0x2c, 0x04, 0x03, 0x21, 0xa8, 0x00, 0x01, 0x12, 0x1c, 0x12, 0x21, 0xa8, 0x00, 0x20, 0x02, 0x04, 0xac, 0x10, 0x00, 0x04, 0x9c, 0x01, 0xab, 0x10, 0x20, 0x24, 0x9c, 0x01, 0x10, 0xa9, 0x04, 0xac, 0x00, 0x99, 0x02, 0x04, 0x24, 0x2a, 0x23, 0x12, 0x8a, 0x00, 0x04, 0x24, 0x22, 0x8a, 0x24, 0x04, 0x03, 0x12, 0xaa, 0x20, 0x24, 0x04, 0x02, 0xaa, 0x24, 0x04, 0x02, 0x22, 0x23, 0x9b, 0x04, 0x09, 0x02, 0x1a, 0x01, 0x10, 0xa9, 0x23, 0x12, 0x03, 0x14, 0x23, 0x24, 0x15, 0x8c, 0x00, 0x0c, 0x03, 0x12, 0x23, 0xac, 0x19, 0x12, 0x9c, 0x2a, 0x23, 0x24, 0x15, 0x8c, 0x00, 0x0c, 0x03, 0x13, 0x2a, 0x13, 0xac, 0x10, 0x9c, 0x02, 0x0c, 0x02, 0x1b, 0x12, 0x1c, 0x12, 0x23, 0xac, 0x02, 0x0c, 0x03, 0x12, 0x23, 0xac, 0x02, 0x22, 0x24, 0x04, 0x8a, 0x02, 0x0d, 0x04, 0x24, 0x22, 0x8a, 0x02, 0x04, 0x2c, 0x25, 0x22, 0x8a, 0x02, 0x0c, 0x03, 0x12, 0xaa, 0x22, 0x02, 0x03, 0x23, 0x24, 0x8c, 0x11, 0x1c, 0x02, 0xaa, 0x02, 0x04, 0x14, 0x2b, 0x24, 0xaa, 0x02, 0x03, 0x14, 0x23, 0xaa, 0x02, 0x03, 0x14, 0x1a, 0x13, 0x24, 0xaa, 0x02, 0x2c, 0x04, 0xaa, 0x02, 0x03, 0x1c, 0x22, 0x23, 0x8d, 0x02, 0x22, 0x04, 0xac, 0x20, 0x10, 0x14, 0x2c, 0x12, 0x8a, 0x10, 0x19, 0x13, 0x9c, 0x00, 0x10, 0x14, 0x0c, 0x12, 0xaa, 0x01, 0x10, 0x11, 0xa8, 0x03, 0x04, 0x24, 0x23, 0x12, 0x8b, 0x18, 0x11, 0x9c, 0x21, 0x10, 0x01, 0x02, 0x13, 0x2a, 0x10, 0x9b, 0x11, 0x00, 0x04, 0x24, 0x2b, 0x02, 0x9a, 0x01, 0x0a, 0x11, 0x29, 0x22, 0x2b, 0x03, 0x1b, 0x02, 0x11, 0x22, 0x13, 0x8a, 0x00, 0x11, 0x28, 0x11, 0x1c, 0x02, 0x2a, 0x03, 0xab, 0x10, 0x1a, 0x13, 0x9d, 0x20, 0x00, 0x02, 0x11, 0x2a, 0x02, 0x13, 0x22, 0x24, 0x8c, 0x08, 0xa8, 0x20, 0x10, 0x11, 0xa9, 0x10, 0x29, 0x20, 0x21, 0x11, 0x98, 0x11, 0x02, 0x1b, 0x21, 0x12, 0xab, 0x01, 0x21, 0xaa, 0x12, 0xaa, 0x10, 0x20, 0x21, 0x19, 0x12, 0x18, 0x11, 0xaa, 0x00, 0xa8, 0x01, 0x10, 0x21, 0x12, 0x89, 0x02, 0x2a, 0x11, 0x1b, 0x03, 0xab, 0x01, 0x10, 0x21, 0x03, 0xab, 0x01, 0x10, 0x21, 0x12, 0x0a, 0x12, 0x23, 0x8b, 0x11, 0xa8, 0x02, 0x0d, 0x04, 0x14, 0x2b, 0x22, 0xac, 0x14, 0x10, 0x01, 0x1a, 0x10, 0x20, 0xac, 0x9a, 0x14, 0x15, 0x8d, 0x20, 0xa9, 0x10, 0x20, 0x21, 0x11, 0x98, 0x01, 0x12, 0x0b, 0x11, 0x22, 0x9b, 0x00, 0x09, 0x02, 0x28, 0x12, 0x13, 0x2b, 0x22, 0xac, 0x00, 0x09, 0x02, 0x28, 0x12, 0x22, 0x13, 0x14, 0xac, 0x00, 0x10, 0x11, 0x09, 0x11, 0x02, 0x28, 0x12, 0x13, 0x2b, 0x22, 0xac, 0x18, 0x11, 0x12, 0x03, 0x14, 0xab, 0x04, 0x02, 0x11, 0x22, 0x2c, 0x03, 0x2b, 0x10, 0xa9, 0x04, 0x02, 0x11, 0x22, 0x2c, 0x03, 0x2b, 0x01, 0x98, 0x04, 0x02, 0x11, 0x22, 0x2c, 0x03, 0x2b, 0x01, 0x10, 0xa9, 0x04, 0x02, 0x11, 0x22, 0x2c, 0x03, 0x2b, 0x01, 0x10, 0x11, 0xa8, 0x04, 0x02, 0x11, 0x22, 0x2c, 0x03, 0x2b, 0x08, 0xa8, 0x04, 0x02, 0x11, 0x22, 0x2c, 0x03, 0x2b, 0x00, 0x20, 0x11, 0x88, 0x00, 0x0c, 0x02, 0x2a, 0x00, 0x19, 0x10, 0x1c, 0x10, 0x28, 0x14, 0xac, 0x23, 0x14, 0x03, 0x01, 0x10, 0x29, 0x14, 0x15, 0x8d, 0x02, 0x2a, 0x02, 0x04, 0x2c, 0x03, 0x1b, 0x00, 0x99, 0x02, 0x2a, 0x02, 0x04, 0x2c, 0x03, 0x1b, 0x11, 0xa8, 0x02, 0x2a, 0x02, 0x04, 0x2c, 0x03, 0x1b, 0x01, 0x10, 0xa9, 0x02, 0x2a, 0x02, 0x04, 0x2c, 0x03, 0x1b, 0x08, 0xa8, 0x02, 0x2a, 0x12, 0x1c, 0x04, 0x2c, 0x00, 0x99, 0x02, 0x2a, 0x12, 0x1c, 0x04, 0x2c, 0x11, 0xa8, 0x02, 0x2a, 0x12, 0x1c, 0x04, 0x2c, 0x01, 0x10, 0xa9, 0x02, 0x2a, 0x12, 0x1c, 0x04, 0x2c, 0x28, 0x88, 0x00, 0x10, 0x21, 0x23, 0x14, 0x04, 0x08, 0x02, 0x9a, 0x04, 0x02, 0x24, 0x2a, 0x01, 0x10, 0x11, 0xa8, 0x02, 0x22, 0x24, 0x04, 0x0a, 0x00, 0x99, 0x02, 0x22, 0x24, 0x04, 0x0a, 0x11, 0xa8, 0x02, 0x22, 0x24, 0x04, 0x0a, 0x11, 0x28, 0x00, 0x99, 0x02, 0x22, 0x24, 0x04, 0x0a, 0x01, 0x10, 0x11, 0xa8, 0x01, 0x21, 0x24, 0x04, 0x09, 0x08, 0xa8, 0x01, 0x2b, 0x03, 0xa9, 0x01, 0x10, 0x21, 0x23, 0x14, 0x03, 0x09, 0x03, 0xa9, 0x01, 0x04, 0x24, 0x29, 0x11, 0xa8, 0x01, 0x04, 0x24, 0x29, 0x00, 0x99, 0x02, 0x04, 0x24, 0x2a, 0x01, 0x10, 0xa9, 0x01, 0x04, 0x24, 0x29, 0x08, 0xa8, 0x01, 0x02, 0x13, 0x1c, 0x13, 0x22, 0x29, 0x11, 0xa8, 0x00, 0x0c, 0x01, 0x11, 0x22, 0x13, 0x8b, 0x00, 0x0d, 0x00, 0x10, 0x21, 0x1a, 0x02, 0x22, 0x24, 0x8c, 0x02, 0x04, 0x24, 0x2a, 0x23, 0x12, 0x0a, 0x00, 0x99, 0x02, 0x04, 0x24, 0x2a, 0x23, 0x12, 0x0a, 0x11, 0xa8, 0x02, 0x04, 0x24, 0x2a, 0x23, 0x12, 0x0a, 0x01, 0x10, 0xa9, 0x02, 0x04, 0x24, 0x2a, 0x23, 0x12, 0x0a, 0x01, 0x10, 0x11, 0xa8, 0x02, 0x04, 0x24, 0x2a, 0x23, 0x12, 0x0a, 0x09, 0xa9, 0x02, 0x04, 0x24, 0x2a, 0x23, 0x12, 0x0a, 0x01, 0x10, 0x21, 0x89, 0x02, 0x1b, 0x02, 0x04, 0x2c, 0x12, 0x1c, 0x12, 0x2a, 0x13, 0x2b, 0x22, 0xab, 0x03, 0x04, 0x2c, 0x03, 0x12, 0x2a, 0x14, 0x15, 0x8d, 0x24, 0x04, 0x02, 0x22, 0x23, 0x1b, 0x00, 0x99, 0x24, 0x04, 0x02, 0x22, 0x23, 0x1b, 0x11, 0xa8, 0x24, 0x04, 0x02, 0x22, 0x23, 0x1b, 0x01, 0x10, 0xa9, 0x24, 0x04, 0x02, 0x22, 0x23, 0x1b, 0x09, 0xa9, 0x12, 0x1c, 0x00, 0x99, 0x12, 0x1c, 0x11, 0xa8, 0x12, 0x1c, 0x01, 0x10, 0xa9, 0x12, 0x1c, 0x09, 0xa9, 0x00, 0x2a, 0x11, 0x28, 0x02, 0x22, 0x24, 0x04, 0x8a, 0x02, 0x0c, 0x03, 0x12, 0x23, 0x2c, 0x01, 0x10, 0x11, 0xa8, 0x02, 0x04, 0x24, 0x22, 0x0a, 0x00, 0x99, 0x02, 0x04, 0x24, 0x22, 0x0a, 0x11, 0xa8, 0x02, 0x04, 0x24, 0x22, 0x0a, 0x01, 0x10, 0xa9, 0x02, 0x04, 0x24, 0x22, 0x0a, 0x01, 0x10, 0x11, 0xa8, 0x02, 0x04, 0x24, 0x22, 0x0a, 0x09, 0xa9, 0x19, 0x02, 0x2a, 0x9b, 0x02, 0x04, 0x24, 0x22, 0x0a, 0x04, 0xaa, 0x02, 0x04, 0x14, 0x2b, 0x24, 0x2a, 0x00, 0x99, 0x02, 0x04, 0x14, 0x2b, 0x24, 0x2a, 0x11, 0xa8, 0x02, 0x04, 0x14, 0x2b, 0x24, 0x2a, 0x01, 0x10, 0xa9, 0x02, 0x04, 0x14, 0x2b, 0x24, 0x2a, 0x09, 0xa9, 0x02, 0x03, 0x1c, 0x22, 0x23, 0x0d, 0x11, 0xa8, 0x00, 0x0c, 0x02, 0x11, 0x22, 0x13, 0x8a, 0x02, 0x03, 0x1c, 0x22, 0x23, 0x0d, 0x09, 0xa9, }; //Set this if you are only using CNFG to create an OpenGL context. #ifndef CNFGCONTEXTONLY uint32_t CNFGDialogColor; void CNFGDrawBox( short x1, short y1, short x2, short y2 ) { uint32_t lc = CNFGLastColor; CNFGColor( CNFGDialogColor ); CNFGTackRectangle( x1, y1, x2, y2 ); CNFGColor( lc ); CNFGTackSegment( x1, y1, x2, y1 ); CNFGTackSegment( x2, y1, x2, y2 ); CNFGTackSegment( x2, y2, x1, y2 ); CNFGTackSegment( x1, y2, x1, y1 ); } void CNFGDrawText( const char * text, short scale ) { const unsigned char * lmap; float iox = (float)CNFGPenX; //x offset float ioy = (float)CNFGPenY; //y offset int place = 0; unsigned short index; int bQuit = 0; while( text[place] ) { unsigned char c = text[place]; switch( c ) { case 9: // tab iox += 12 * scale; break; case 10: // linefeed iox = (float)CNFGPenX; ioy += 6 * scale; break; default: index = RawdrawFontCharMap[c]; if( index == 65535 ) { iox += 3 * scale; break; } lmap = &RawdrawFontCharData[index]; short penx, peny; unsigned char start_seg = 1; do { unsigned char data = (*(lmap++)); short x1 = (short)(((data >> 4) & 0x07)*scale + iox); short y1 = (short)((data & 0x07)*scale + ioy); if( start_seg ) { penx = x1; peny = y1; start_seg = 0; if( data & 0x08 ) CNFGTackPixel( x1, y1 ); } else { CNFGTackSegment( penx, peny, x1, y1 ); penx = x1; peny = y1; } if( data & 0x08 ) start_seg = 1; bQuit = data & 0x80; } while( !bQuit ); iox += 3 * scale; } place++; } } #ifndef FONT_CREATION_TOOL #ifdef _CNFG_FANCYFONT void CNFGDrawNiceText(const char* text, short scale) { const unsigned char* lmap; float iox = (float)CNFGPenX; //x offset float ioy = (float)CNFGPenY; //y offset int place = 0; unsigned short index; int bQuit = 0; int segmentEnd = 0; while (text[place]) { unsigned char c = text[place]; switch (c) { case 9: // tab iox += 16 * scale; break; case 10: // linefeed iox = (float)CNFGPenX; ioy += 6 * scale; break; default: index = CharIndex[c]; if (index == 0) { iox += 4 * scale; break; } lmap = &FontData[index]; short charWidth = ((*lmap) & 0xE0) >> 5; //0b11100000 short xbase = ((*lmap) & 0x18) >> 3; //0b00011000 short ybase = (*lmap) & 0x07; //0b00000111 lmap++; do { int x1 = ((((*lmap) & 0x38) >> 3) * scale + iox + xbase * scale); //0b00111000 int y1 = (((*lmap) & 0x07) * scale + ioy + ybase * scale); segmentEnd = *lmap & 0x40; int x2 = 0; int y2 = 0; lmap++; if (segmentEnd) { x2 = x1; y2 = y1; } else { x2 = ((((*lmap) & 0x38) >> 3) * scale + iox + xbase * scale); y2 = (((*lmap) & 0x07) * scale + ioy + ybase * scale); } CNFGTackSegment(x1, y1, x2, y2); bQuit = *(lmap - 1) & 0x80; } while (!bQuit); iox += (charWidth + 2) * scale; //iox += 8 * scale; } place++; } } #endif #endif void CNFGGetTextExtents( const char * text, int * w, int * h, int textsize ) { int charsx = 0; int charsy = 1; int charsline = 0; const char * s; for( s = text; *s; s++ ) { if( *s == '\n' ) { charsline = 0; if( *(s+1) ) charsy++; } else { charsline++; if( charsline > charsx ) charsx = charsline; } } *w = charsx * textsize * 3-1*textsize; *h = charsy * textsize * 6; } #if defined( CNFG_BATCH ) //This is the path by which we convert rawdraw functionality //into nice batched triangle streams. //Just FYI we use floats for geometry instead of shorts becase it is harder //to triangularize a diagonal line int triangles with shorts and have it look good. void CNFGEmitBackendTriangles( const float * fv, const uint32_t * col, int nr_verts ); //If on WASM, sqrtf is implied. On other platforms, need sqrtf from math.h #ifdef __wasm__ float sqrtf( float f ); #else #include <math.h> #endif //Geometry batching system - so we can batch geometry and deliver it all at once. float CNFGVertDataV[CNFG_BATCH*3]; uint32_t CNFGVertDataC[CNFG_BATCH]; int CNFGVertPlace; static float wgl_last_width_over_2 = .5; static void EmitQuad( float cx0, float cy0, float cx1, float cy1, float cx2, float cy2, float cx3, float cy3 ) { //Because quads are really useful, but it's best to keep them all triangles if possible. //This lets us draw arbitrary quads. if( CNFGVertPlace >= CNFG_BATCH-6 ) CNFGFlushRender(); float * fv = &CNFGVertDataV[CNFGVertPlace*3]; fv[0] = cx0; fv[1] = cy0; fv[3] = cx1; fv[4] = cy1; fv[6] = cx2; fv[7] = cy2; fv[9] = cx2; fv[10] = cy2; fv[12] = cx1; fv[13] = cy1; fv[15] = cx3; fv[16] = cy3; uint32_t * col = &CNFGVertDataC[CNFGVertPlace]; uint32_t color = CNFGLastColor; col[0] = color; col[1] = color; col[2] = color; col[3] = color; col[4] = color; col[5] = color; CNFGVertPlace += 6; } #ifndef CNFGRASTERIZER void CNFGTackPixel( short x1, short y1 ) { x1++; y1++; const short l2 = wgl_last_width_over_2; const short l2u = wgl_last_width_over_2+0.5; EmitQuad( x1-l2u, y1-l2u, x1+l2, y1-l2u, x1-l2u, y1+l2, x1+l2, y1+l2 ); } void CNFGTackSegment( short x1, short y1, short x2, short y2 ) { float ix1 = x1; float iy1 = y1; float ix2 = x2; float iy2 = y2; float dx = ix2-ix1; float dy = iy2-iy1; float imag = 1./sqrtf(dx*dx+dy*dy); dx *= imag; dy *= imag; float orthox = dy*wgl_last_width_over_2; float orthoy =-dx*wgl_last_width_over_2; ix2 += dx/2 + 0.5; iy2 += dy/2 + 0.5; ix1 -= dx/2 - 0.5; iy1 -= dy/2 - 0.5; //This logic is incorrect. XXX FIXME. EmitQuad( (ix1 - orthox), (iy1 - orthoy), (ix1 + orthox), (iy1 + orthoy), (ix2 - orthox), (iy2 - orthoy), ( ix2 + orthox), ( iy2 + orthoy) ); } void CNFGTackRectangle( short x1, short y1, short x2, short y2 ) { float ix1 = x1; float iy1 = y1; float ix2 = x2; float iy2 = y2; EmitQuad( ix1,iy1,ix2,iy1,ix1,iy2,ix2,iy2 ); } void CNFGTackPoly( RDPoint * points, int verts ) { int i; int tris = verts-2; if( CNFGVertPlace >= CNFG_BATCH-tris*3 ) CNFGFlushRender(); uint32_t color = CNFGLastColor; short * ptrsrc = (short*)points; for( i = 0; i < tris; i++ ) { float * fv = &CNFGVertDataV[CNFGVertPlace*3]; fv[0] = ptrsrc[0]; fv[1] = ptrsrc[1]; fv[3] = ptrsrc[i*2+2]; fv[4] = ptrsrc[i*2+3]; fv[6] = ptrsrc[i*2+4]; fv[7] = ptrsrc[i*2+5]; uint32_t * col = &CNFGVertDataC[CNFGVertPlace]; col[0] = color; col[1] = color; col[2] = color; CNFGVertPlace += 3; } } uint32_t CNFGColor( uint32_t RGB ) { return CNFGLastColor = RGB; } void CNFGSetLineWidth( short width ) { wgl_last_width_over_2 = width/2.0;// + 0.5; } #endif #ifndef __wasm__ //In WASM, Javascript takes over this functionality. //Shader compilation errors go to stderr. #include <stdio.h> #ifndef GL_VERTEX_SHADER #define GL_FRAGMENT_SHADER 0x8B30 #define GL_VERTEX_SHADER 0x8B31 #define GL_COMPILE_STATUS 0x8B81 #define GL_INFO_LOG_LENGTH 0x8B84 #define GL_LINK_STATUS 0x8B82 #define GL_TEXTURE_2D 0x0DE1 #define GL_CLAMP_TO_EDGE 0x812F #define LGLchar char #else #define LGLchar GLchar #endif #if defined(WINDOWS) || defined(WIN32) || defined(WIN64) || defined(_WIN32) || defined(_WIN64) #define CNFGOGL_NEED_EXTENSION #endif #ifdef CNFGOGL_NEED_EXTENSION // If we are going to be defining our own function pointer call #if defined(WINDOWS) || defined(WIN32) || defined(WIN64) || defined(_WIN32) || defined(_WIN64) // Make sure to use __stdcall on Windows #define CHEWTYPEDEF( ret, name, rv, paramcall, ... ) \ ret (__stdcall *CNFG##name)( __VA_ARGS__ ); #else #define CHEWTYPEDEF( ret, name, rv, paramcall, ... ) \ ret (*CNFG##name)( __VA_ARGS__ ); #endif #else //If we are going to be defining the real call #define CHEWTYPEDEF( ret, name, rv, paramcall, ... ) \ ret name (__VA_ARGS__); #endif int (*MyFunc)( int program, const LGLchar *name ); CHEWTYPEDEF( GLint, glGetUniformLocation, return, (program,name), GLuint program, const LGLchar *name ) CHEWTYPEDEF( void, glEnableVertexAttribArray, , (index), GLuint index ) CHEWTYPEDEF( void, glUseProgram, , (program), GLuint program ) CHEWTYPEDEF( void, glGetProgramInfoLog, , (program,maxLength, length, infoLog), GLuint program, GLsizei maxLength, GLsizei *length, LGLchar *infoLog ) CHEWTYPEDEF( void, glGetProgramiv, , (program,pname,params), GLuint program, GLenum pname, GLint *params ) CHEWTYPEDEF( void, glBindAttribLocation, , (program,index,name), GLuint program, GLuint index, const LGLchar *name ) CHEWTYPEDEF( void, glGetShaderiv, , (shader,pname,params), GLuint shader, GLenum pname, GLint *params ) CHEWTYPEDEF( GLuint, glCreateShader, return, (e), GLenum e ) CHEWTYPEDEF( void, glVertexAttribPointer, , (index,size,type,normalized,stride,pointer), GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const GLvoid * pointer ) CHEWTYPEDEF( void, glShaderSource, , (shader,count,string,length), GLuint shader, GLsizei count, const LGLchar *const*string, const GLint *length ) CHEWTYPEDEF( void, glAttachShader, , (program,shader), GLuint program, GLuint shader ) CHEWTYPEDEF( void, glCompileShader, ,(shader), GLuint shader ) CHEWTYPEDEF( void, glGetShaderInfoLog , , (shader,maxLength, length, infoLog), GLuint shader, GLsizei maxLength, GLsizei *length, LGLchar *infoLog ) CHEWTYPEDEF( GLuint, glCreateProgram, return, () , void ) CHEWTYPEDEF( void, glLinkProgram, , (program), GLuint program ) CHEWTYPEDEF( void, glDeleteShader, , (shader), GLuint shader ) CHEWTYPEDEF( void, glUniform4f, , (location,v0,v1,v2,v3), GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3 ) CHEWTYPEDEF( void, glUniform1i, , (location,i0), GLint location, GLint i0 ) CHEWTYPEDEF( void, glActiveTexture, , (texture), GLenum texture ) #ifndef CNFGOGL_NEED_EXTENSION #define CNFGglGetUniformLocation glGetUniformLocation #define CNFGglEnableVertexAttribArray glEnableVertexAttribArray #define CNFGglUseProgram glUseProgram #define CNFGglEnableVertexAttribArray glEnableVertexAttribArray #define CNFGglUseProgram glUseProgram #define CNFGglGetProgramInfoLog glGetProgramInfoLog #define CNFGglGetProgramiv glGetProgramiv #define CNFGglShaderSource glShaderSource #define CNFGglCreateShader glCreateShader #define CNFGglAttachShader glAttachShader #define CNFGglGetShaderiv glGetShaderiv #define CNFGglCompileShader glCompileShader #define CNFGglGetShaderInfoLog glGetShaderInfoLog #define CNFGglCreateProgram glCreateProgram #define CNFGglLinkProgram glLinkProgram #define CNFGglDeleteShader glDeleteShader #define CNFGglUniform4f glUniform4f #define CNFGglBindAttribLocation glBindAttribLocation #define CNFGglVertexAttribPointer glVertexAttribPointer #define CNFGglUniform1i glUniform1i #define CNFGglActiveTexture glActiveTexture #endif #ifdef CNFGOGL_NEED_EXTENSION #if defined( WIN32 ) || defined( WINDOWS ) || defined( WIN64 ) //From https://www.khronos.org/opengl/wiki/Load_OpenGL_Functions void * CNFGGetProcAddress(const char *name) { void *p = (void *)wglGetProcAddress(name); if(p == 0 || (p == (void*)0x1) || (p == (void*)0x2) || (p == (void*)0x3) || (p == (void*)-1) ) { static HMODULE module; if( !module ) module = LoadLibraryA("opengl32.dll"); p = (void *)GetProcAddress(module, name); } // We were unable to load the required openGL function if (!p) { fprintf(stderr,"[rawdraw][warn]: Unable to load openGL extension \"%s\"\n", name); } return p; } #else #include <dlfcn.h> void * CNFGGetProcAddress(const char *name) { //Tricky use RTLD_NEXT first so we don't accidentally link against ourselves. void * v1 = dlsym( (void*)((intptr_t)-1) /*RTLD_NEXT = -1*/ /*RTLD_DEFAULT = 0*/, name ); //printf( "%s = %p\n", name, v1 ); if( !v1 ) v1 = dlsym( 0, name ); return v1; } #endif // Try and load openGL extension functions required for rawdraw static int CNFGLoadExtensionsInternal() { CNFGglGetUniformLocation = CNFGGetProcAddress( "glGetUniformLocation" ); CNFGglEnableVertexAttribArray = CNFGGetProcAddress( "glEnableVertexAttribArray" ); CNFGglUseProgram = CNFGGetProcAddress( "glUseProgram" ); CNFGglGetProgramInfoLog = CNFGGetProcAddress( "glGetProgramInfoLog" ); CNFGglBindAttribLocation = CNFGGetProcAddress( "glBindAttribLocation" ); CNFGglGetProgramiv = CNFGGetProcAddress( "glGetProgramiv" ); CNFGglGetShaderiv = CNFGGetProcAddress( "glGetShaderiv" ); CNFGglVertexAttribPointer = CNFGGetProcAddress( "glVertexAttribPointer" ); CNFGglCreateShader = CNFGGetProcAddress( "glCreateShader" ); CNFGglShaderSource = CNFGGetProcAddress( "glShaderSource" ); CNFGglAttachShader = CNFGGetProcAddress( "glAttachShader" ); CNFGglCompileShader = CNFGGetProcAddress( "glCompileShader" ); CNFGglGetShaderInfoLog = CNFGGetProcAddress( "glGetShaderInfoLog" ); CNFGglDeleteShader = CNFGGetProcAddress( "glDeleteShader" ); CNFGglLinkProgram = CNFGGetProcAddress( "glLinkProgram" ); CNFGglCreateProgram = CNFGGetProcAddress( "glCreateProgram" ); CNFGglUniform4f = CNFGGetProcAddress( "glUniform4f" ); CNFGglUniform1i = CNFGGetProcAddress( "glUniform1i" ); CNFGglActiveTexture = CNFGGetProcAddress("glActiveTexture"); // Check if any of these functions didn't get loaded uint8_t not_all_functions_loaded = !CNFGglGetUniformLocation || !CNFGglEnableVertexAttribArray || !CNFGglUseProgram || !CNFGglGetProgramInfoLog || !CNFGglBindAttribLocation || !CNFGglGetProgramiv || !CNFGglVertexAttribPointer || !CNFGglCreateShader || !CNFGglShaderSource || !CNFGglAttachShader || !CNFGglCompileShader || !CNFGglGetShaderInfoLog || !CNFGglDeleteShader || !CNFGglLinkProgram || !CNFGglCreateProgram || !CNFGglUniform4f || !CNFGglUniform1i || !CNFGglActiveTexture; if (not_all_functions_loaded) { fprintf( stderr, "[rawdraw][err]: Unable to load all openGL extensions required for rawdraw\n" "\tPlease update your graphics drivers unexpected crashes may occur.\n" ); } // Give a very stern warning if unable to create or compile shaders if (!CNFGglCreateShader || !CNFGglCompileShader) { fprintf( stderr, "[rawdraw][err]: Unable to create or compile shaders, this will cause a fatal error if " "openGL is used.\n" "\tUpdate your video graphics drivers or switch to software graphics.\n" ); } } #else static void CNFGLoadExtensionsInternal() { } #endif GLuint gRDShaderProg = -1; GLuint gRDBlitProg = -1; GLuint gRDShaderProgUX = -1; GLuint gRDBlitProgUX = -1; GLuint gRDBlitProgUT = -1; GLuint gRDBlitProgTex = -1; GLuint gRDLastResizeW; GLuint gRDLastResizeH; GLuint CNFGGLInternalLoadShader( const char * vertex_shader, const char * fragment_shader ) { GLuint fragment_shader_object = 0; GLuint vertex_shader_object = 0; GLuint program = 0; int ret; vertex_shader_object = CNFGglCreateShader(GL_VERTEX_SHADER); if (!vertex_shader_object) { fprintf( stderr, "Error: glCreateShader(GL_VERTEX_SHADER) " "failed: 0x%08X\n", glGetError()); goto fail; } CNFGglShaderSource(vertex_shader_object, 1, &vertex_shader, NULL); CNFGglCompileShader(vertex_shader_object); CNFGglGetShaderiv(vertex_shader_object, GL_COMPILE_STATUS, &ret); if (!ret) { fprintf( stderr,"Error: vertex shader compilation failed!\n"); CNFGglGetShaderiv(vertex_shader_object, GL_INFO_LOG_LENGTH, &ret); if (ret > 1) { char * log = alloca(ret); CNFGglGetShaderInfoLog(vertex_shader_object, ret, NULL, log); fprintf( stderr, "%s", log); } goto fail; } fragment_shader_object = CNFGglCreateShader(GL_FRAGMENT_SHADER); if (!fragment_shader_object) { fprintf( stderr, "Error: glCreateShader(GL_FRAGMENT_SHADER) " "failed: 0x%08X\n", glGetError()); goto fail; } CNFGglShaderSource(fragment_shader_object, 1, &fragment_shader, NULL); CNFGglCompileShader(fragment_shader_object); CNFGglGetShaderiv(fragment_shader_object, GL_COMPILE_STATUS, &ret); if (!ret) { fprintf( stderr, "Error: fragment shader compilation failed!\n"); CNFGglGetShaderiv(fragment_shader_object, GL_INFO_LOG_LENGTH, &ret); if (ret > 1) { char * log = malloc(ret); CNFGglGetShaderInfoLog(fragment_shader_object, ret, NULL, log); fprintf( stderr, "%s", log); } goto fail; } program = CNFGglCreateProgram(); if (!program) { fprintf( stderr, "Error: failed to create program!\n"); goto fail; } CNFGglAttachShader(program, vertex_shader_object); CNFGglAttachShader(program, fragment_shader_object); CNFGglBindAttribLocation(program, 0, "a0"); CNFGglBindAttribLocation(program, 1, "a1"); CNFGglLinkProgram(program); CNFGglGetProgramiv(program, GL_LINK_STATUS, &ret); if (!ret) { fprintf( stderr, "Error: program linking failed!\n"); CNFGglGetProgramiv(program, GL_INFO_LOG_LENGTH, &ret); if (ret > 1) { char *log = alloca(ret); CNFGglGetProgramInfoLog(program, ret, NULL, log); fprintf( stderr, "%s", log); } goto fail; } return program; fail: if( !vertex_shader_object ) CNFGglDeleteShader( vertex_shader_object ); if( !fragment_shader_object ) CNFGglDeleteShader( fragment_shader_object ); if( !program ) CNFGglDeleteShader( program ); return -1; } #ifdef CNFGEWGL #define PRECISIONA "lowp" #define PRECISIONB "mediump" #else #define PRECISIONA #define PRECISIONB #endif void CNFGSetupBatchInternal() { short w, h; CNFGLoadExtensionsInternal(); CNFGGetDimensions( &w, &h ); gRDShaderProg = CNFGGLInternalLoadShader( "uniform vec4 xfrm;" "attribute vec3 a0;" "attribute vec4 a1;" "varying " PRECISIONA " vec4 vc;" "void main() { gl_Position = vec4( a0.xy*xfrm.xy+xfrm.zw, a0.z, 0.5 ); vc = a1; }", "varying " PRECISIONA " vec4 vc;" "void main() { gl_FragColor = vec4(vc.abgr); }" ); CNFGglUseProgram( gRDShaderProg ); gRDShaderProgUX = CNFGglGetUniformLocation ( gRDShaderProg , "xfrm" ); gRDBlitProg = CNFGGLInternalLoadShader( "uniform vec4 xfrm;" "attribute vec3 a0;" "attribute vec4 a1;" "varying " PRECISIONB " vec2 tc;" "void main() { gl_Position = vec4( a0.xy*xfrm.xy+xfrm.zw, a0.z, 0.5 ); tc = a1.xy; }", "varying " PRECISIONB " vec2 tc;" "uniform sampler2D tex;" "void main() { gl_FragColor = texture2D(tex,tc)." #if !defined( CNFGRASTERIZER ) "wzyx" #else "wxyz" #endif ";}" ); CNFGglUseProgram( gRDBlitProg ); gRDBlitProgUX = CNFGglGetUniformLocation ( gRDBlitProg , "xfrm" ); gRDBlitProgUT = CNFGglGetUniformLocation ( gRDBlitProg , "tex" ); glGenTextures( 1, &gRDBlitProgTex ); CNFGglEnableVertexAttribArray(0); CNFGglEnableVertexAttribArray(1); glDisable(GL_DEPTH_TEST); glDepthMask( GL_FALSE ); glEnable( GL_BLEND ); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); CNFGVertPlace = 0; } #ifndef CNFGRASTERIZER void CNFGInternalResize(short x, short y) #else void CNFGInternalResizeOGLBACKEND(short x, short y) #endif { glViewport( 0, 0, x, y ); gRDLastResizeW = x; gRDLastResizeH = y; if (gRDShaderProg == 0xFFFFFFFF) { return; } // Prevent trying to set uniform if the shader isn't ready yet. CNFGglUseProgram( gRDShaderProg ); CNFGglUniform4f( gRDShaderProgUX, 1.f/x, -1.f/y, -0.5f, 0.5f); } void CNFGEmitBackendTriangles( const float * vertices, const uint32_t * colors, int num_vertices ) { CNFGglUseProgram( gRDShaderProg ); CNFGglUniform4f( gRDShaderProgUX, 1.f/gRDLastResizeW, -1.f/gRDLastResizeH, -0.5f, 0.5f); CNFGglVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, vertices); CNFGglVertexAttribPointer(1, 4, GL_UNSIGNED_BYTE, GL_TRUE, 0, colors); glDrawArrays( GL_TRIANGLES, 0, num_vertices); } #ifdef CNFGOGL // this is here, so people don't have to include opengl void CNFGDeleteTex( unsigned int tex ) { glDeleteTextures(1, &tex); } unsigned int CNFGTexImage( uint32_t *data, int w, int h ) { GLuint tex; glGenTextures(1, &tex); glEnable( GL_TEXTURE_2D ); CNFGglActiveTexture( 0 ); glBindTexture( GL_TEXTURE_2D, tex ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST ); glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, data ); return (unsigned int)tex; } void CNFGBlitTex( unsigned int tex, int x, int y, int w, int h ) { if( w == 0 || h == 0 ) return; CNFGFlushRender(); CNFGglUseProgram( gRDBlitProg ); CNFGglUniform4f( gRDBlitProgUX, 1.f/gRDLastResizeW, -1.f/gRDLastResizeH, -0.5f+x/(float)gRDLastResizeW, 0.5f-y/(float)gRDLastResizeH ); CNFGglUniform1i( gRDBlitProgUT, 0 ); glBindTexture(GL_TEXTURE_2D, tex); const float verts[] = { 0,0, w,0, w,h, 0,0, w,h, 0,h, }; static const uint8_t colors[] = { 0,0, 255,0, 255,255, 0,0, 255,255, 0,255 }; CNFGglVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, verts); CNFGglVertexAttribPointer(1, 2, GL_UNSIGNED_BYTE, GL_TRUE, 0, colors); glDrawArrays( GL_TRIANGLES, 0, 6); } #endif #ifdef CNFGRASTERIZER void CNFGBlitImageInternal( uint32_t * data, int x, int y, int w, int h ) #else void CNFGBlitImage( uint32_t * data, int x, int y, int w, int h ) #endif { if( w <= 0 || h <= 0 ) return; CNFGFlushRender(); CNFGglUseProgram( gRDBlitProg ); CNFGglUniform4f( gRDBlitProgUX, 1.f/gRDLastResizeW, -1.f/gRDLastResizeH, -0.5f+x/(float)gRDLastResizeW, 0.5f-y/(float)gRDLastResizeH ); CNFGglUniform1i( gRDBlitProgUT, 0 ); glEnable( GL_TEXTURE_2D ); CNFGglActiveTexture( 0 ); glBindTexture( GL_TEXTURE_2D, gRDBlitProgTex ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST ); glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, data ); const float verts[] = { 0,0, w,0, w,h, 0,0, w,h, 0,h, }; static const uint8_t colors[] = { 0,0, 255,0, 255,255, 0,0, 255,255, 0,255 }; CNFGglVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, verts); CNFGglVertexAttribPointer(1, 2, GL_UNSIGNED_BYTE, GL_TRUE, 0, colors); glDrawArrays( GL_TRIANGLES, 0, 6); } void CNFGUpdateScreenWithBitmap( uint32_t * data, int w, int h ) { #ifdef CNFGRASTERIZER CNFGBlitImageInternal( data, 0, 0, w, h ); void CNFGSwapBuffersInternal(); CNFGSwapBuffersInternal(); #else CNFGBlitImage( data, 0, 0, w, h ); #endif } #ifndef CNFGRASTERIZER void CNFGFlushRender() { if( !CNFGVertPlace ) return; CNFGEmitBackendTriangles( CNFGVertDataV, CNFGVertDataC, CNFGVertPlace ); CNFGVertPlace = 0; } void CNFGClearFrame() { glClearColor( ((CNFGBGColor&0xff000000)>>24)/255.0, ((CNFGBGColor&0xff0000)>>16)/255.0, (CNFGBGColor&0xff00)/65280.0, (CNFGBGColor&0xff)/255.0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); } #endif #endif //__wasm__ #else void CNFGFlushRender() { } #endif #endif #endif //_CNFG_C #ifdef CNFG3D //Copyright 2012-2017 <>< Charles Lohr //You may license this file under the MIT/x11, NewBSD, or any GPL license. //This is a series of tools useful for software rendering. //Use of this file with OpenGL is untested. #ifdef CNFG3D #ifdef __wasm__ double sin( double v ); double cos( double v ); double tan( double v ); double sqrt( double v ); float sinf( float v ); float cosf( float v ); float tanf( float v ); float sqrtf( float v ); void tdMATCOPY( float * x, const float * y ) { int i; for( i = 0; i < 16; i++ ) x[i] = y[i]; } #else #include <string.h> #include <stdio.h> #endif #ifdef CNFG3D_USE_OGL_MAJOR #define m00 0 #define m10 1 #define m20 2 #define m30 3 #define m01 4 #define m11 5 #define m21 6 #define m31 7 #define m02 8 #define m12 9 #define m22 10 #define m32 11 #define m03 12 #define m13 13 #define m23 14 #define m33 15 #else #define m00 0 #define m01 1 #define m02 2 #define m03 3 #define m10 4 #define m11 5 #define m12 6 #define m13 7 #define m20 8 #define m21 9 #define m22 10 #define m23 11 #define m30 12 #define m31 13 #define m32 14 #define m33 15 #endif void tdIdentity( float * f ) { f[m00] = 1; f[m01] = 0; f[m02] = 0; f[m03] = 0; f[m10] = 0; f[m11] = 1; f[m12] = 0; f[m13] = 0; f[m20] = 0; f[m21] = 0; f[m22] = 1; f[m23] = 0; f[m30] = 0; f[m31] = 0; f[m32] = 0; f[m33] = 1; } void tdZero( float * f ) { f[m00] = 0; f[m01] = 0; f[m02] = 0; f[m03] = 0; f[m10] = 0; f[m11] = 0; f[m12] = 0; f[m13] = 0; f[m20] = 0; f[m21] = 0; f[m22] = 0; f[m23] = 0; f[m30] = 0; f[m31] = 0; f[m32] = 0; f[m33] = 0; } void tdTranslate( float * f, float x, float y, float z ) { float ftmp[16]; tdIdentity(ftmp); ftmp[m03] += x; ftmp[m13] += y; ftmp[m23] += z; tdMultiply( f, ftmp, f ); } void tdScale( float * f, float x, float y, float z ) { #if 0 f[m00] *= x; f[m01] *= x; f[m02] *= x; f[m03] *= x; f[m10] *= y; f[m11] *= y; f[m12] *= y; f[m13] *= y; f[m20] *= z; f[m21] *= z; f[m22] *= z; f[m23] *= z; #endif float ftmp[16]; tdIdentity(ftmp); ftmp[m00] *= x; ftmp[m11] *= y; ftmp[m22] *= z; tdMultiply( f, ftmp, f ); } void tdRotateAA( float * f, float angle, float ix, float iy, float iz ) { float ftmp[16]; float c = tdCOS( angle*tdDEGRAD ); float s = tdSIN( angle*tdDEGRAD ); float absin = tdSQRT( ix*ix + iy*iy + iz*iz ); float x = ix/absin; float y = iy/absin; float z = iz/absin; ftmp[m00] = x*x*(1-c)+c; ftmp[m01] = x*y*(1-c)-z*s; ftmp[m02] = x*z*(1-c)+y*s; ftmp[m03] = 0; ftmp[m10] = y*x*(1-c)+z*s; ftmp[m11] = y*y*(1-c)+c; ftmp[m12] = y*z*(1-c)-x*s; ftmp[m13] = 0; ftmp[m20] = x*z*(1-c)-y*s; ftmp[m21] = y*z*(1-c)+x*s; ftmp[m22] = z*z*(1-c)+c; ftmp[m23] = 0; ftmp[m30] = 0; ftmp[m31] = 0; ftmp[m32] = 0; ftmp[m33] = 1; tdMultiply( f, ftmp, f ); } void tdRotateQuat( float * f, float qw, float qx, float qy, float qz ) { float ftmp[16]; //float qw2 = qw*qw; float qx2 = qx*qx; float qy2 = qy*qy; float qz2 = qz*qz; ftmp[m00] = 1 - 2*qy2 - 2*qz2; ftmp[m01] = 2*qx*qy - 2*qz*qw; ftmp[m02] = 2*qx*qz + 2*qy*qw; ftmp[m03] = 0; ftmp[m10] = 2*qx*qy + 2*qz*qw; ftmp[m11] = 1 - 2*qx2 - 2*qz2; ftmp[m12] = 2*qy*qz - 2*qx*qw; ftmp[m13] = 0; ftmp[m20] = 2*qx*qz - 2*qy*qw; ftmp[m21] = 2*qy*qz + 2*qx*qw; ftmp[m22] = 1 - 2*qx2 - 2*qy2; ftmp[m23] = 0; ftmp[m30] = 0; ftmp[m31] = 0; ftmp[m32] = 0; ftmp[m33] = 1; tdMultiply( f, ftmp, f ); } void tdRotateEA( float * f, float x, float y, float z ) { float ftmp[16]; //x,y,z must be negated for some reason float X = -x*2*tdQ_PI/360; //Reduced calulation for speed float Y = -y*2*tdQ_PI/360; float Z = -z*2*tdQ_PI/360; float cx = tdCOS(X); float sx = tdSIN(X); float cy = tdCOS(Y); float sy = tdSIN(Y); float cz = tdCOS(Z); float sz = tdSIN(Z); //Row major (unless CNFG3D_USE_OGL_MAJOR is selected) //manually transposed ftmp[m00] = cy*cz; ftmp[m10] = (sx*sy*cz)-(cx*sz); ftmp[m20] = (cx*sy*cz)+(sx*sz); ftmp[m30] = 0; ftmp[m01] = cy*sz; ftmp[m11] = (sx*sy*sz)+(cx*cz); ftmp[m21] = (cx*sy*sz)-(sx*cz); ftmp[m31] = 0; ftmp[m02] = -sy; ftmp[m12] = sx*cy; ftmp[m22] = cx*cy; ftmp[m32] = 0; ftmp[m03] = 0; ftmp[m13] = 0; ftmp[m23] = 0; ftmp[m33] = 1; tdMultiply( f, ftmp, f ); } void tdMultiply( float * fin1, float * fin2, float * fout ) { float fotmp[16]; int i, k; #ifdef CNFG3D_USE_OGL_MAJOR fotmp[m00] = fin1[m00] * fin2[m00] + fin1[m01] * fin2[m10] + fin1[m02] * fin2[m20] + fin1[m03] * fin2[m30]; fotmp[m01] = fin1[m00] * fin2[m01] + fin1[m01] * fin2[m11] + fin1[m02] * fin2[m21] + fin1[m03] * fin2[m31]; fotmp[m02] = fin1[m00] * fin2[m02] + fin1[m01] * fin2[m12] + fin1[m02] * fin2[m22] + fin1[m03] * fin2[m32]; fotmp[m03] = fin1[m00] * fin2[m03] + fin1[m01] * fin2[m13] + fin1[m02] * fin2[m23] + fin1[m03] * fin2[m33]; fotmp[m10] = fin1[m10] * fin2[m00] + fin1[m11] * fin2[m10] + fin1[m12] * fin2[m20] + fin1[m13] * fin2[m30]; fotmp[m11] = fin1[m10] * fin2[m01] + fin1[m11] * fin2[m11] + fin1[m12] * fin2[m21] + fin1[m13] * fin2[m31]; fotmp[m12] = fin1[m10] * fin2[m02] + fin1[m11] * fin2[m12] + fin1[m12] * fin2[m22] + fin1[m13] * fin2[m32]; fotmp[m13] = fin1[m10] * fin2[m03] + fin1[m11] * fin2[m13] + fin1[m12] * fin2[m23] + fin1[m13] * fin2[m33]; fotmp[m20] = fin1[m20] * fin2[m00] + fin1[m21] * fin2[m10] + fin1[m22] * fin2[m20] + fin1[m23] * fin2[m30]; fotmp[m21] = fin1[m20] * fin2[m01] + fin1[m21] * fin2[m11] + fin1[m22] * fin2[m21] + fin1[m23] * fin2[m31]; fotmp[m22] = fin1[m20] * fin2[m02] + fin1[m21] * fin2[m12] + fin1[m22] * fin2[m22] + fin1[m23] * fin2[m32]; fotmp[m23] = fin1[m20] * fin2[m03] + fin1[m21] * fin2[m13] + fin1[m22] * fin2[m23] + fin1[m23] * fin2[m33]; fotmp[m30] = fin1[m30] * fin2[m00] + fin1[m31] * fin2[m10] + fin1[m32] * fin2[m20] + fin1[m33] * fin2[m30]; fotmp[m31] = fin1[m30] * fin2[m01] + fin1[m31] * fin2[m11] + fin1[m32] * fin2[m21] + fin1[m33] * fin2[m31]; fotmp[m32] = fin1[m30] * fin2[m02] + fin1[m31] * fin2[m12] + fin1[m32] * fin2[m22] + fin1[m33] * fin2[m32]; fotmp[m33] = fin1[m30] * fin2[m03] + fin1[m31] * fin2[m13] + fin1[m32] * fin2[m23] + fin1[m33] * fin2[m33]; #else for( i = 0; i < 16; i++ ) { int xp = i & 0x03; int yp = i & 0x0c; fotmp[i] = 0; for( k = 0; k < 4; k++ ) { fotmp[i] += fin1[yp+k] * fin2[(k<<2)|xp]; } } #endif tdMATCOPY( fout, fotmp ); } #ifndef __wasm__ void tdPrint( const float * f ) { int i; printf( "{\n" ); #ifdef CNFG3D_USE_OGL_MAJOR for( i = 0; i < 4; i++ ) { printf( " %f, %f, %f, %f\n", f[0+i], f[4+i], f[8+i], f[12+i] ); } #else for( i = 0; i < 16; i+=4 ) { printf( " %f, %f, %f, %f\n", f[0+i], f[1+i], f[2+i], f[3+i] ); } #endif printf( "}\n" ); } #endif void tdTransposeSelf( float * f ) { float fout[16]; fout[m00] = f[m00]; fout[m01] = f[m10]; fout[m02] = f[m20]; fout[m03] = f[m30]; fout[m10] = f[m01]; fout[m11] = f[m11]; fout[m12] = f[m21]; fout[m13] = f[m31]; fout[m20] = f[m02]; fout[m21] = f[m12]; fout[m22] = f[m22]; fout[m23] = f[m32]; fout[m30] = f[m03]; fout[m31] = f[m13]; fout[m32] = f[m23]; fout[m33] = f[m33]; tdMATCOPY( f, fout ); } void tdPerspective( float fovy, float aspect, float zNear, float zFar, float * out ) { float f = 1./tdTAN(fovy * tdQ_PI / 360.0); out[m00] = f/aspect; out[m01] = 0; out[m02] = 0; out[m03] = 0; out[m10] = 0; out[m11] = f; out[m12] = 0; out[m13] = 0; out[m20] = 0; out[m21] = 0; out[m22] = (zFar + zNear)/(zNear - zFar); out[m23] = 2*zFar*zNear /(zNear - zFar); out[m30] = 0; out[m31] = 0; out[m32] = -1; out[m33] = 0; } void tdLookAt( float * m, float * eye, float * at, float * up ) { float out[16]; float F[3] = { at[0] - eye[0], at[1] - eye[1], at[2] - eye[2] }; float fdiv = 1./tdSQRT( F[0]*F[0] + F[1]*F[1] + F[2]*F[2] ); float f[3] = { F[0]*fdiv, F[1]*fdiv, F[2]*fdiv }; float udiv = 1./tdSQRT( up[0]*up[0] + up[1]*up[1] + up[2]*up[2] ); float UP[3] = { up[0]*udiv, up[1]*udiv, up[2]*udiv }; float s[3]; float u[3]; tdCross( f, UP, s ); tdCross( s, f, u ); out[m00] = s[0]; out[m01] = s[1]; out[m02] = s[2]; out[m03] = 0; out[m10] = u[0]; out[m11] = u[1]; out[m12] = u[2]; out[m13] = 0; out[m20] = -f[0];out[m21] =-f[1]; out[m22] =-f[2]; out[m23] = 0; out[m30] = 0; out[m31] = 0; out[m32] = 0; out[m33] = 1; tdMultiply( m, out, m ); tdTranslate( m, -eye[0], -eye[1], -eye[2] ); } void tdPTransform( const float * pin, float * f, float * pout ) { float ptmp[2]; ptmp[0] = pin[0] * f[m00] + pin[1] * f[m01] + pin[2] * f[m02] + f[m03]; ptmp[1] = pin[0] * f[m10] + pin[1] * f[m11] + pin[2] * f[m12] + f[m13]; pout[2] = pin[0] * f[m20] + pin[1] * f[m21] + pin[2] * f[m22] + f[m23]; pout[0] = ptmp[0]; pout[1] = ptmp[1]; } void tdVTransform( const float * pin, float * f, float * pout ) { float ptmp[2]; ptmp[0] = pin[0] * f[m00] + pin[1] * f[m01] + pin[2] * f[m02]; ptmp[1] = pin[0] * f[m10] + pin[1] * f[m11] + pin[2] * f[m12]; pout[2] = pin[0] * f[m20] + pin[1] * f[m21] + pin[2] * f[m22]; pout[0] = ptmp[0]; pout[1] = ptmp[1]; } void td4Transform( float * pin, float * f, float * pout ) { float ptmp[3]; ptmp[0] = pin[0] * f[m00] + pin[1] * f[m01] + pin[2] * f[m02] + pin[3] * f[m03]; ptmp[1] = pin[0] * f[m10] + pin[1] * f[m11] + pin[2] * f[m12] + pin[3] * f[m13]; ptmp[2] = pin[0] * f[m20] + pin[1] * f[m21] + pin[2] * f[m22] + pin[3] * f[m23]; pout[3] = pin[0] * f[m30] + pin[1] * f[m31] + pin[2] * f[m32] + pin[3] * f[m33]; pout[0] = ptmp[0]; pout[1] = ptmp[1]; pout[2] = ptmp[2]; } void td4RTransform( float * pin, float * f, float * pout ) { float ptmp[3]; ptmp[0] = pin[0] * f[m00] + pin[1] * f[m10] + pin[2] * f[m20] + pin[3] * f[m30]; ptmp[1] = pin[0] * f[m01] + pin[1] * f[m11] + pin[2] * f[m21] + pin[3] * f[m31]; ptmp[2] = pin[0] * f[m02] + pin[1] * f[m12] + pin[2] * f[m22] + pin[3] * f[m32]; pout[3] = pin[0] * f[m03] + pin[1] * f[m13] + pin[2] * f[m23] + pin[3] * f[m33]; pout[0] = ptmp[0]; pout[1] = ptmp[1]; pout[2] = ptmp[2]; } void tdNormalizeSelf( float * vin ) { float vsq = 1./tdSQRT(vin[0]*vin[0] + vin[1]*vin[1] + vin[2]*vin[2]); vin[0] *= vsq; vin[1] *= vsq; vin[2] *= vsq; } void tdCross( float * va, float * vb, float * vout ) { float vtmp[2]; vtmp[0] = va[1] * vb[2] - va[2] * vb[1]; vtmp[1] = va[2] * vb[0] - va[0] * vb[2]; vout[2] = va[0] * vb[1] - va[1] * vb[0]; vout[0] = vtmp[0]; vout[1] = vtmp[1]; } float tdDistance( float * va, float * vb ) { float dx = va[0]-vb[0]; float dy = va[1]-vb[1]; float dz = va[2]-vb[2]; return tdSQRT(dx*dx + dy*dy + dz*dz); } float tdDot( float * va, float * vb ) { return va[0]*vb[0] + va[1]*vb[1] + va[2]*vb[2]; } //Stack functionality. static float gsMatricies[2][tdMATRIXMAXDEPTH][16]; float * gSMatrix = gsMatricies[0][0]; static int gsMMode; static int gsMPlace[2]; void tdPush() { if( gsMPlace[gsMMode] > tdMATRIXMAXDEPTH - 2 ) return; tdMATCOPY( gsMatricies[gsMMode][gsMPlace[gsMMode] + 1], gsMatricies[gsMMode][gsMPlace[gsMMode]] ); gsMPlace[gsMMode]++; gSMatrix = gsMatricies[gsMMode][gsMPlace[gsMMode]]; } void tdPop() { if( gsMPlace[gsMMode] < 1 ) return; gsMPlace[gsMMode]--; gSMatrix = gsMatricies[gsMMode][gsMPlace[gsMMode]]; } void tdMode( int mode ) { if( mode < 0 || mode > 1 ) return; gsMMode = mode; gSMatrix = gsMatricies[gsMMode][gsMPlace[gsMMode]]; } static float translateX; static float translateY; static float scaleX; static float scaleY; void tdSetViewport( float leftx, float topy, float rightx, float bottomy, float pixx, float pixy ) { translateX = leftx; translateY = bottomy; scaleX = pixx/(rightx-leftx); scaleY = pixy/(topy-bottomy); } void tdFinalPoint( float * pin, float * pout ) { float tdin[4] = { pin[0], pin[1], pin[2], 1. }; float tmp[4]; td4Transform( tdin, gsMatricies[0][gsMPlace[0]], tmp ); // printf( "XFORM1Out: %f %f %f %f\n", tmp[0], tmp[1], tmp[2], tmp[3] ); td4Transform( tmp, gsMatricies[1][gsMPlace[1]], tmp ); // printf( "XFORM2Out: %f %f %f %f\n", tmp[0], tmp[1], tmp[2], tmp[3] ); pout[0] = (tmp[0]/tmp[3] - translateX) * scaleX; pout[1] = (tmp[1]/tmp[3] - translateY) * scaleY; pout[2] = tmp[2]/tmp[3]; // printf( "XFORMFOut: %f %f %f\n", pout[0], pout[1], pout[2] ); } float tdNoiseAt( int x, int y ) { return ((x*13241*y + y * 33455927)%9293) / 4646. - 1.0; } static inline float tdFade( float f ) { float ft3 = f*f*f; return ft3 * 10 - ft3 * f * 15 + 6 * ft3 * f * f; } float tdFLerp( float a, float b, float t ) { float fr = tdFade( t ); return a * (1.-fr) + b * fr; } static inline float tdFNoiseAt( float x, float y ) { int ix = x; int iy = y; float fx = x - ix; float fy = y - iy; float a = tdNoiseAt( ix, iy ); float b = tdNoiseAt( ix+1, iy ); float c = tdNoiseAt( ix, iy+1 ); float d = tdNoiseAt( ix+1, iy+1 ); float top = tdFLerp( a, b, fx ); float bottom = tdFLerp( c, d, fx ); return tdFLerp( top, bottom, fy ); } float tdPerlin2D( float x, float y ) { int ndepth = 5; int depth; float ret = 0; for( depth = 0; depth < ndepth; depth++ ) { float nx = x / (1<<(ndepth-depth-1)); float ny = y / (1<<(ndepth-depth-1)); ret += tdFNoiseAt( nx, ny ) / (1<<(depth+1)); } return ret; } #endif #endif #endif #endif
2.046875
2
2024-11-18T20:50:28.810248+00:00
2023-06-17T17:46:23
9346272b4bcdb637b67e053f7e727a00fa58018f
{ "blob_id": "9346272b4bcdb637b67e053f7e727a00fa58018f", "branch_name": "refs/heads/master", "committer_date": "2023-07-11T12:25:31", "content_id": "6e6f9c7c2136d5a7912015e62bc0c353458574a6", "detected_licenses": [ "Unlicense" ], "directory_id": "01ace0f357a25a895df67b2fe60020a9e9713766", "extension": "c", "filename": "search.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 147276452, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 11517, "license": "Unlicense", "license_type": "permissive", "path": "/libimaildir/search.c", "provenance": "stackv2-0110.json.gz:214399", "repo_name": "Splintermail/splintermail-client", "revision_date": "2023-06-17T17:46:23", "revision_id": "029757f727e338d7c9fa251ea71a894097426146", "snapshot_id": "10e7f370b6859e1ae5d75bdaa89f4f1d24e9bb81", "src_encoding": "UTF-8", "star_events_count": 4, "url": "https://raw.githubusercontent.com/Splintermail/splintermail-client/029757f727e338d7c9fa251ea71a894097426146/libimaildir/search.c", "visit_date": "2023-07-21T15:36:03.409326" }
stackv2
#include "libimaildir.h" // args which are constant through the whole recursion typedef struct { const msg_view_t *view; unsigned int seq; unsigned int seq_max; unsigned int uid_dn_max; // get a read-only copy of either headers or whole body, must be idempotent derr_t (*get_hdrs)(void*, const imf_hdrs_t**); void *get_hdrs_data; derr_t (*get_imf)(void*, const imf_t**); void *get_imf_data; } search_args_t; static bool in_seq_set(unsigned int val, const ie_seq_set_t *seq_set, unsigned int max){ for(; seq_set != NULL; seq_set = seq_set->next){ // straighten out the range unsigned int n1 = seq_set->n1 ? seq_set->n1 : max; unsigned int n2 = seq_set->n2 ? seq_set->n2 : max; unsigned int a = MIN(n1, n2); unsigned int b = MAX(n1, n2); if(val >= a && val <= b){ return true; } } return false; } // look up the value of a header named `name` static derr_t find_header( search_args_t *args, const dstr_t name, dstr_t *out ){ derr_t e = E_OK; *out = (dstr_t){0}; const imf_hdrs_t *hdrs; IF_PROP(&e, args->get_hdrs(args->get_hdrs_data, &hdrs) ){ TRACE(&e, "failed to parse message for header SEARCH\n"); DUMP(e); DROP_VAR(&e); return e; } // find a matching header field for(const imf_hdr_t *hdr = hdrs->hdr; hdr; hdr = hdr->next){ // does this header name match? dstr_t hname = dstr_from_off(hdr->name); if(dstr_icmp2(hname, name) == 0){ // return the content of the header value *out = dstr_from_off(hdr->value); return e; } } return e; } // find a header matching `name`, return if its value contains `value` static derr_t search_headers( search_args_t *args, const dstr_t name, const dstr_t value, bool *out ){ derr_t e = E_OK; *out = false; dstr_t hvalue; PROP(&e, find_header(args, name, &hvalue) ); if(!hvalue.data) return e; if(dstr_icount2(hvalue, value) > 0) *out = true; return e; } static derr_t parse_date(search_args_t *args, imap_time_t *out){ derr_t e = E_OK; *out = (imap_time_t){0}; dstr_t hvalue; PROP(&e, find_header(args, DSTR_LIT("Date"), &hvalue) ); if(!hvalue.data) return e; IF_PROP(&e, imf_parse_date(hvalue, out) ){ TRACE(&e, "failed to parse Date header in SEARCH\n"); DUMP(e); DROP_VAR(&e); return e; } return e; } // ON = date matches, disregarding time and timezone bool date_a_is_on_b(imap_time_t a, imap_time_t b){ return a.year == b.year && a.month == b.month && a.day == b.day; } // BEFORE = date is earlier, disregarding time and timezone bool date_a_is_before_b(imap_time_t a, imap_time_t b){ if(a.year < b.year) return true; if(a.year > b.year) return false; // a.year == b.year if(a.month < b.month) return true; if(a.month > b.month) return false; // a.month == b.month return a.day < b.day; } // SINCE = date is on or after, disregarding time and timezone bool date_a_is_since_b(imap_time_t a, imap_time_t b){ if(a.year > b.year) return true; if(a.year < b.year) return false; // a.year == b.year if(a.month > b.month) return true; if(a.month < b.month) return false; // a.month == b.month return a.day >= b.day; } static derr_t do_eval(search_args_t *args, size_t lvl, const ie_search_key_t *key, bool *out){ derr_t e = E_OK; // recursion limit if(lvl > 1000){ *out = false; return e; } const msg_view_t *view = args->view; union ie_search_param_t param = key->param; imap_time_t date; switch(key->type){ case IE_SEARCH_ALL: *out = true; break; case IE_SEARCH_ANSWERED: *out = view->flags.answered; break; case IE_SEARCH_UNANSWERED: *out = !view->flags.answered; break; case IE_SEARCH_DELETED: *out = view->flags.deleted; break; case IE_SEARCH_UNDELETED: *out = !view->flags.deleted; break; case IE_SEARCH_FLAGGED: *out = view->flags.flagged; break; case IE_SEARCH_UNFLAGGED: *out = !view->flags.flagged; break; case IE_SEARCH_SEEN: *out = view->flags.seen; break; case IE_SEARCH_UNSEEN: *out = !view->flags.seen; break; case IE_SEARCH_DRAFT: *out = view->flags.draft; break; case IE_SEARCH_UNDRAFT: *out = !view->flags.draft; break; case IE_SEARCH_NEW: // "NEW" means "recent and not seen", and we don't support recent *out = false; break; case IE_SEARCH_OLD: // "OLD" means "not recent", and we don't support recent *out = true; break; case IE_SEARCH_RECENT: // we don't support recent *out = false; break; case IE_SEARCH_NOT: { bool temp; PROP(&e, do_eval(args, lvl+1, param.key, &temp) ); *out = !temp; } break; case IE_SEARCH_GROUP: // exists only to express parens from the grammar PROP(&e, do_eval(args, lvl+1, param.key, out) ); break; case IE_SEARCH_OR: { bool a, b; PROP(&e, do_eval(args, lvl+1, param.pair.a, &a) ); PROP(&e, do_eval(args, lvl+1, param.pair.b, &b) ); *out = a || b; } break; case IE_SEARCH_AND: { bool a, b; PROP(&e, do_eval(args, lvl+1, param.pair.a, &a) ); PROP(&e, do_eval(args, lvl+1, param.pair.b, &b) ); *out = a && b; } break; case IE_SEARCH_UID: *out = in_seq_set(view->uid_dn, param.seq_set, args->uid_dn_max); break; case IE_SEARCH_SEQ_SET: // uses param.seq_set *out = in_seq_set(args->seq, param.seq_set, args->seq_max); break; #define HEADER_SEARCH(hdrname) \ PROP(&e, \ search_headers(args, DSTR_LIT(hdrname), param.dstr->dstr, out \ ) \ ) // use param.dstr case IE_SEARCH_SUBJECT: HEADER_SEARCH("Subject"); break; case IE_SEARCH_BCC: HEADER_SEARCH("Bcc"); break; case IE_SEARCH_CC: HEADER_SEARCH("Cc"); break; case IE_SEARCH_FROM: HEADER_SEARCH("From"); break; case IE_SEARCH_TO: HEADER_SEARCH("To"); break; #undef HEADER_SEARCH case IE_SEARCH_BODY: { // uses param.dstr // search just the body const imf_t *imf; IF_PROP(&e, args->get_imf(args->get_imf_data, &imf) ){ TRACE(&e, "failed to parse message for SEARCH BODY\n"); DUMP(e); DROP_VAR(&e); *out = false; break; } dstr_t searchable = dstr_from_off(imf->body); *out = dstr_icount2(searchable, param.dstr->dstr) > 0; } break; case IE_SEARCH_TEXT: { // uses param.dstr const dstr_t tgt = param.dstr->dstr; // search the headers first, then search the body if necessary const imf_hdrs_t *hdrs; IF_PROP(&e, args->get_hdrs(args->get_hdrs_data, &hdrs) ){ TRACE(&e, "failed to parse message for SEARCH TEXT\n"); DUMP(e); DROP_VAR(&e); *out = false; break; } dstr_t searchable = dstr_from_off(hdrs->bytes); if(dstr_icount2(searchable, tgt) > 0){ *out = true; break; } // remember how far we already searched size_t hdrs_end = hdrs->bytes.start + hdrs->bytes.len; const imf_t *imf; IF_PROP(&e, args->get_imf(args->get_imf_data, &imf) ){ TRACE(&e, "failed to parse message for SEARCH TEXT\n"); DUMP(e); DROP_VAR(&e); *out = false; break; } /* avoid searching things we already searched, allowing for boundary conditions */ size_t start = hdrs_end - MIN(hdrs_end, tgt.len); size_t end = imf->bytes.start + imf->bytes.len; searchable = dstr_sub2(dstr_from_off(imf->bytes), start, end); *out = dstr_icount2(searchable, param.dstr->dstr) > 0; } break; case IE_SEARCH_KEYWORD: // uses param.dstr // we don't support keyword flags *out = false; break; case IE_SEARCH_UNKEYWORD: // uses param.dstr // we don't support keyword flags *out = true; break; case IE_SEARCH_HEADER: // uses param.header PROP(&e, search_headers( args, param.header.name->dstr, param.header.value->dstr, out ) ); break; case IE_SEARCH_BEFORE: // uses param.date *out = date_a_is_before_b(args->view->internaldate, param.date); break; case IE_SEARCH_ON: // uses param.date *out = date_a_is_on_b(args->view->internaldate, param.date); break; case IE_SEARCH_SINCE: // uses param.date *out = date_a_is_since_b(args->view->internaldate, param.date); break; case IE_SEARCH_SENTBEFORE: // uses param.date PROP(&e, parse_date(args, &date) ); *out = date.year != 0 && date_a_is_before_b(date, param.date); break; case IE_SEARCH_SENTON: // uses param.date PROP(&e, parse_date(args, &date) ); *out = date.year != 0 && date_a_is_on_b(date, param.date); break; case IE_SEARCH_SENTSINCE: // uses param.date PROP(&e, parse_date(args, &date) ); *out = date.year != 0 && date_a_is_since_b(date, param.date); break; case IE_SEARCH_LARGER: // uses param.num *out = args->view->length > param.num; break; case IE_SEARCH_SMALLER: // uses param.num *out = args->view->length < param.num; break; case IE_SEARCH_MODSEQ: // uses param.modseq ORIG(&e, E_INTERNAL, "not implemented"); } return e; } derr_t search_key_eval( const ie_search_key_t *key, const msg_view_t *view, unsigned int seq, unsigned int seq_max, unsigned int uid_dn_max, // get a read-only copy of either headers or whole body, must be idempotent derr_t (*get_hdrs)(void*, const imf_hdrs_t**), void *get_hdrs_data, derr_t (*get_imf)(void*, const imf_t**), void *get_imf_data, bool *out ){ derr_t e = E_OK; search_args_t args = { .view = view, .seq = seq, .seq_max = seq_max, .uid_dn_max = uid_dn_max, // message is parsed lazily .get_hdrs = get_hdrs, .get_hdrs_data = get_hdrs_data, .get_imf = get_imf, .get_imf_data = get_imf_data, }; PROP(&e, do_eval(&args, 0, key, out) ); return e; }
2.484375
2
2024-11-18T20:50:28.990536+00:00
2015-01-08T05:36:23
50baee5bc9933fbfa70834a9babc67d1f05dfc8e
{ "blob_id": "50baee5bc9933fbfa70834a9babc67d1f05dfc8e", "branch_name": "refs/heads/master", "committer_date": "2015-01-08T05:36:23", "content_id": "96ea2bd43911f00fb5393bc690fef6ce9e9d8727", "detected_licenses": [ "Apache-2.0" ], "directory_id": "9b68ea36349bc699985d410ede3f556299fdb766", "extension": "c", "filename": "EmvCmd.c", "fork_events_count": 2, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 28950647, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 12918, "license": "Apache-2.0", "license_type": "permissive", "path": "/iMateInterface/jni/common/pboccore/EmvCmd.c", "provenance": "stackv2-0110.json.gz:214660", "repo_name": "billzbh/XML2Java", "revision_date": "2015-01-08T05:36:23", "revision_id": "b4e273320f63f05625ba6801c63eede97ee8d940", "snapshot_id": "28f0442ce26893a479369270b1d06b136a8325c3", "src_encoding": "GB18030", "star_events_count": 1, "url": "https://raw.githubusercontent.com/billzbh/XML2Java/b4e273320f63f05625ba6801c63eede97ee8d940/iMateInterface/jni/common/pboccore/EmvCmd.c", "visit_date": "2021-03-12T23:00:47.834261" }
stackv2
/************************************** File name : EMVCMD.C Function : EMV卡片指令 Author : Yu Jun First edition : Feb 24th, 2003 Note : immigrate from PBOCCMD.C Modified : July 31st, 2008 from EMV2000 to EMV2004 Mar 29th, 2012 from EMV2004 to EMV2008 ushort -> uint apdu指令返回9Fxx时不认为是要求取可用数据 删除了脚本指令 APPLICATION BLOCK (post-issuance command) APPLICATION UNBLOCK (post-issuance command) CARD BLOCK (post-issuance command) PIN CHANGE/UNBLOCK (post-issuance command) 增加设置卡座号指令函数uiEmvCmdSetSlot(),指令函数中删除了卡座号传入参数 Nov 26th, 2012 使用Vpos新增接口函数_uiDoApdu()实现emv卡操作 Dec 11th, 2012 修改uiEmvCmdExchangeApdu(), 抛弃APDU结构, 完全使用新增接口函数_uiDoApdu()实现 **************************************/ /* 模块详细描述: 以函数形式提供EMV规范所需要的IC卡指令 . 调用IC卡指令函数前需要设定IC卡卡座号(缺省为操作VPOS 0号卡座) 静态全局变量sg_iCardSlotNo用于保存当前卡座号 */ #include <stdio.h> #include <string.h> #include "VposFace.h" #include "PushApdu.h" #include "EmvCmd.h" #include "EmvTrace.h" static int sg_iCardSlotNo = 0; // 卡座号 // emv card slot select // in : uiSlotId : virtual card slot id // ret : 0 : OK // 1 : 不支持此卡座 uint uiEmvCmdSetSlot(uint uiSlotId) { vTraceWriteTxtCr(TRACE_ALWAYS, "选择卡座号%u", uiSlotId); if(uiSlotId > 9) return(1); // 0-3:用户卡 4-7:Sam卡 8:非接触卡 sg_iCardSlotNo = uiSlotId; return(0); } // test if card has been inserted // ret : 0 : card not inserted // 1 : card inserted uint uiEmvTestCard(void) { if(_uiTestCard(sg_iCardSlotNo)) return(1); return(0); } // emv card reset // ret : 0 : OK // 1 : reset error uint uiEmvCmdResetCard(void) { uint uiRet; uchar sResetData[100]; vPushApduInit(sg_iCardSlotNo); // add by yujun 2012.10.29, 支持pboc2.0优化推送apdu uiRet = _uiResetCard(sg_iCardSlotNo, sResetData); if(uiRet > 0) { vTraceWriteBinCr(TRACE_APDU, "IC卡复位成功, ATR=", sResetData, uiRet); return(0); } vTraceWriteTxtCr(TRACE_APDU, "IC卡复位失败"); return(1); } // emv card close // ret : 0 : OK uint uiEmvCloseCard(void) { _uiCloseCard(sg_iCardSlotNo); return(0); } // emv card apdu // in : uiInLen : apdu 指令长度 // psApduIn : 遵照emv规范case1-case4 // out : puiOutLen : apdu 应答长度(去除了尾部的SW[2]) // psApduOut : apdu应答(去除了尾部的SW[2]) // ret : 0 : OK // 1 : communication error between card and reader // other : returned by card uint uiEmvCmdExchangeApdu(uint uiInLen, uchar *psApduIn, uint *puiOutLen, uchar *psApduOut) { uint uiRet; uint uiOutLen; uchar sApduOut[260]; uiOutLen = 0; *puiOutLen = 0; uiRet = _uiDoApdu(sg_iCardSlotNo, uiInLen, psApduIn, &uiOutLen, sApduOut, APDU_EMV); if(uiRet) return(uiRet); if(uiOutLen < 2) return(1); *puiOutLen = uiOutLen - 2; memcpy(psApduOut, sApduOut, *puiOutLen); if(memcmp(sApduOut+*puiOutLen, "\x90\x00", 2) != 0) uiRet = ulStrToLong(sApduOut+*puiOutLen, 2); return(uiRet); } // emv card read record file // in : ucSFI : short file identifier // ucRecordNo : record number, starting from 1 // out : psBuf : data buffer // pucLength : length read // ret : 0 : OK // 1 : communication error between card and reader // other : returned by card // note: refer to EMV2004 book3 Part II, 6.5.11 uint uiEmvCmdRdRec(uchar ucSFI, uchar ucRecordNo, uchar *pucLength, uchar *psBuf) { uint uiRet; uchar ucSW1; uint uiInLen, uiOutLen; uchar sApduIn[262], sApduOut[260]; uiInLen = 0; sApduIn[uiInLen++] = 0x00; sApduIn[uiInLen++] = 0xb2; sApduIn[uiInLen++] = ucRecordNo; sApduIn[uiInLen++] = (ucSFI<<3)|0x04; // 0x04 : p1 is a record number sApduIn[uiInLen++] = 0; uiRet = uiEmvCmdExchangeApdu(uiInLen, sApduIn, &uiOutLen, sApduOut); vTraceWriteLastApdu("* Apdu读记录"); ucSW1 = uiRet>>8; if(uiRet!=1 && (ucSW1==0x00 || ucSW1==0x62 || ucSW1==0x63)) { *pucLength = uiOutLen; memcpy(psBuf, sApduOut, uiOutLen); } return(uiRet); } // emv card select file // in : ucP2 : parameter 2, 0x00 : first occurrence, 0x02 : next occurrence // ucAidLen : length of the AID // psAid : AID // out : pucFciLen : FCI length, NULL means don't get FCI info // psFci : file control infomation, NULL means don't get FCI info // ret : 0 : OK // 1 : communication error between card and reader // other : returned by card // note: refer to EMV2004 book1 Part III, 11.3 uint uiEmvCmdSelect(uchar ucP2, uchar ucAidLen, uchar *psAid, uchar *pucFciLen, uchar *psFci) { uint uiRet; uchar ucSW1; uint uiInLen, uiOutLen; uchar sApduIn[262], sApduOut[260]; uiInLen = 0; sApduIn[uiInLen++] = 0x00; sApduIn[uiInLen++] = 0xa4; sApduIn[uiInLen++] = 0x04; sApduIn[uiInLen++] = ucP2; sApduIn[uiInLen++] = ucAidLen; memcpy(sApduIn+uiInLen, psAid, ucAidLen); uiInLen += ucAidLen; sApduIn[uiInLen++] = 0; uiRet = uiEmvCmdExchangeApdu(uiInLen, sApduIn, &uiOutLen, sApduOut); vTraceWriteLastApdu("* Apdu选择应用"); ucSW1 = uiRet>>8; if(uiRet!=1 && (ucSW1==0x00 || ucSW1==0x62 || ucSW1==0x63)) { if(pucFciLen && psFci) { *pucFciLen = uiOutLen; memcpy(psFci, sApduOut, uiOutLen); } } return(uiRet); } // emv card external authentication // in : ucLength : length of data // psIn : ciphered data // ret : 0 : OK // 1 : communication error between card and reader // other : returned by card // note: refer to EMV2004 book3 Part II, 6.5.4 uint uiEmvCmdExternalAuth(uchar ucLength, uchar *psIn) { uint uiRet; uint uiInLen, uiOutLen; uchar sApduIn[262], sApduOut[260]; uiInLen = 0; sApduIn[uiInLen++] = 0x00; sApduIn[uiInLen++] = 0x82; sApduIn[uiInLen++] = 0x00; sApduIn[uiInLen++] = 0x00; sApduIn[uiInLen++] = ucLength; memcpy(sApduIn+uiInLen, psIn, ucLength); uiInLen += ucLength; uiRet = uiEmvCmdExchangeApdu(uiInLen, sApduIn, &uiOutLen, sApduOut); vTraceWriteLastApdu("* Apdu外部认证"); return(uiRet); } // emv card generate AC // in : ucP1 : parameter 1 // ucLengthIn : data length send to card // psDataIn : data send to the card // out : pucLengthOut : data length received from card // psDataOut : data received from card // ret : 0 : OK // 1 : communication error between card and reader // other : returned by card // note: refer to EMV2004 book3 Part II, 6.5.5 uint uiEmvCmdGenerateAC(uchar ucP1, uchar ucLengthIn, uchar *psDataIn, uchar *pucLengthOut, uchar *psDataOut) { uint uiRet; uchar ucSW1; uint uiInLen, uiOutLen; uchar sApduIn[262], sApduOut[260]; uiInLen = 0; sApduIn[uiInLen++] = 0x80; sApduIn[uiInLen++] = 0xae; sApduIn[uiInLen++] = ucP1; sApduIn[uiInLen++] = 0x00; sApduIn[uiInLen++] = ucLengthIn; memcpy(sApduIn+uiInLen, psDataIn, ucLengthIn); uiInLen += ucLengthIn; sApduIn[uiInLen++] = 0; uiRet = uiEmvCmdExchangeApdu(uiInLen, sApduIn, &uiOutLen, sApduOut); vTraceWriteLastApdu("* Apdu Generate AC"); ucSW1 = uiRet>>8; if(uiRet!=1 && (ucSW1==0x00 || ucSW1==0x62 || ucSW1==0x63)) { *pucLengthOut = uiOutLen; memcpy(psDataOut, sApduOut, uiOutLen); } return(uiRet); } // emv card get 8-byte random number from pboc card // out : pucLength: 长度 // psOut : random number from pboc card // ret : 0 : OK // 1 : communication error between card and reader // other : returned by card // note: refer to EMV2004 book3 Part II, 6.5.6 uint uiEmvCmdGetChallenge(uchar *pucLength, uchar *psOut) { uint uiRet; uchar ucSW1; uint uiInLen, uiOutLen; uchar sApduIn[262], sApduOut[260]; uiInLen = 0; sApduIn[uiInLen++] = 0x00; sApduIn[uiInLen++] = 0x84; sApduIn[uiInLen++] = 0x00; sApduIn[uiInLen++] = 0x00; sApduIn[uiInLen++] = 0; uiRet = uiEmvCmdExchangeApdu(uiInLen, sApduIn, &uiOutLen, sApduOut); vTraceWriteLastApdu("* Apdu取随机数"); ucSW1 = uiRet>>8; if(uiRet!=1 && (ucSW1==0x00 || ucSW1==0x62 || ucSW1==0x63)) { *pucLength = uiOutLen; memcpy(psOut, sApduOut, uiOutLen); } return(uiRet); } // emv card get data // in : psTag : tag, can only be "\x9f\x36" or "\x9f\x13" or "\x9f\x17" or "\x9f\x4f" // out : pucLength : length of data // psData : data // ret : 0 : OK // 1 : communication error between card and reader // other : returned by card // note: refer to EMV2004 book3 Part II, 6.5.7 uint uiEmvCmdGetData(uchar *psTag, uchar *pucLength, uchar *psData) { uint uiRet; uchar ucSW1; uint uiInLen, uiOutLen; uchar sApduIn[262], sApduOut[260]; uiInLen = 0; sApduIn[uiInLen++] = 0x80; sApduIn[uiInLen++] = 0xca; sApduIn[uiInLen++] = psTag[0]; sApduIn[uiInLen++] = psTag[1]; sApduIn[uiInLen++] = 0; uiRet = uiEmvCmdExchangeApdu(uiInLen, sApduIn, &uiOutLen, sApduOut); vTraceWriteLastApdu("* Apdu Get Data"); ucSW1 = uiRet>>8; if(uiRet!=1 && (ucSW1==0x00 || ucSW1==0x62 || ucSW1==0x63)) { *pucLength = uiOutLen; memcpy(psData, sApduOut, uiOutLen); } return(uiRet); } // emv card get processing options // in : ucLengthIn : data length send to card // psDataIn : data send to the card // out : pucLengthOut : data length received from card // psDataOut : data received from card // ret : 0 : OK // 1 : communication error between card and reader // other : returned by card // note: refer to EMV2004 book3 Part II, 6.5.8 uint uiEmvCmdGetOptions(uchar ucLengthIn, uchar *psDataIn, uchar *pucLengthOut, uchar *psDataOut) { uint uiRet; uchar ucSW1; uint uiInLen, uiOutLen; uchar sApduIn[262], sApduOut[260]; uiInLen = 0; sApduIn[uiInLen++] = 0x80; sApduIn[uiInLen++] = 0xa8; sApduIn[uiInLen++] = 0x00; sApduIn[uiInLen++] = 0x00; sApduIn[uiInLen++] = ucLengthIn; memcpy(sApduIn+uiInLen, psDataIn, ucLengthIn); uiInLen += ucLengthIn; sApduIn[uiInLen++] = 0; uiRet = uiEmvCmdExchangeApdu(uiInLen, sApduIn, &uiOutLen, sApduOut); vTraceWriteLastApdu("* Apdu GPO"); ucSW1 = uiRet>>8; if(uiRet!=1 && (ucSW1==0x00 || ucSW1==0x62 || ucSW1==0x63)) { *pucLengthOut = uiOutLen; memcpy(psDataOut, sApduOut, uiOutLen); } return(uiRet); } // emv card internal authentication // in : ucLengthIn : data length send to card // psIn : data send to the card // out : pucLengthOut : data length received from the card // psOut : data received from the card // ret : 0 : OK // 1 : communication error between card and reader // other : returned by card // note: refer to EMV2004 book3 Part II, 6.5.9 uint uiEmvCmdInternalAuth(uchar ucLengthIn, uchar *psIn, uchar *pucLengthOut, uchar *psOut) { uint uiRet; uchar ucSW1; uint uiInLen, uiOutLen; uchar sApduIn[262], sApduOut[260]; uiInLen = 0; sApduIn[uiInLen++] = 0x00; sApduIn[uiInLen++] = 0x88; sApduIn[uiInLen++] = 0x00; sApduIn[uiInLen++] = 0x00; sApduIn[uiInLen++] = ucLengthIn; memcpy(sApduIn+uiInLen, psIn, ucLengthIn); uiInLen += ucLengthIn; sApduIn[uiInLen++] = 0; uiRet = uiEmvCmdExchangeApdu(uiInLen, sApduIn, &uiOutLen, sApduOut); vTraceWriteLastApdu("* Apdu内部认证"); ucSW1 = uiRet>>8; if(uiRet!=1 && (ucSW1==0x00 || ucSW1==0x62 || ucSW1==0x63)) { *pucLengthOut = uiOutLen; memcpy(psOut, sApduOut, uiOutLen); } return(uiRet); } // emv card verify user pin // in : ucP2 : parameter 2 // ucLength : length of pin relevant data // psPinData : pin data // ret : 0 : OK // 1 : communication error between card and reader // other : returned by card // note: refer to EMV2004 book3 Part II, 6.5.12 uint uiEmvCmdVerifyPin(uchar ucP2, uchar ucLength, uchar *psPinData) { uint uiRet; uint uiInLen, uiOutLen; uchar sApduIn[262], sApduOut[260]; uiInLen = 0; sApduIn[uiInLen++] = 0x00; sApduIn[uiInLen++] = 0x20; sApduIn[uiInLen++] = 0x00; sApduIn[uiInLen++] = ucP2; sApduIn[uiInLen++] = ucLength; memcpy(sApduIn+uiInLen, psPinData, ucLength); uiInLen += ucLength; uiRet = uiEmvCmdExchangeApdu(uiInLen, sApduIn, &uiOutLen, sApduOut); vTraceWriteLastApdu("* Apdu验证密码"); return(uiRet); }
2.203125
2
2024-11-18T20:50:29.183622+00:00
2019-08-16T15:33:16
c8b8db778261a4c3cf15ba2627b392b1740956f8
{ "blob_id": "c8b8db778261a4c3cf15ba2627b392b1740956f8", "branch_name": "refs/heads/master", "committer_date": "2019-08-16T15:33:16", "content_id": "8b10936e876bbe24bbb6cdd42ab3fe5a17dfb9d1", "detected_licenses": [ "MIT" ], "directory_id": "36890d6977027510fa371df53e1ed4a774a0c345", "extension": "c", "filename": "do-while-loop.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 171347661, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 422, "license": "MIT", "license_type": "permissive", "path": "/lang-examples/do-while-loop.c", "provenance": "stackv2-0110.json.gz:214921", "repo_name": "coltonhurst/c-examples", "revision_date": "2019-08-16T15:33:16", "revision_id": "f90bb98286dcefcc45a40b56cb94907cc26734af", "snapshot_id": "44c8ced5c165119bed157d3a43f501325234aa8a", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/coltonhurst/c-examples/f90bb98286dcefcc45a40b56cb94907cc26734af/lang-examples/do-while-loop.c", "visit_date": "2020-04-23T17:53:11.897977" }
stackv2
/* Do While Loop The do-while loop. The same as a while loop, except the loop body is executed once *before* the test expression. So, at minimum, the code inside the do-while body will execute once. */ #include <stdio.h> int main(void) { int number = 10; do { printf("%d ", number--); /* print the number, then decrement its value by 1 */ } while (number >= 0); return 0; }
3.71875
4
2024-11-18T20:50:29.238288+00:00
2023-08-16T08:49:18
14726eeec77b52f38d81afaa952a0e77438a282d
{ "blob_id": "14726eeec77b52f38d81afaa952a0e77438a282d", "branch_name": "refs/heads/master", "committer_date": "2023-08-16T08:49:18", "content_id": "470526fe1907b8af1a7e94945fdecbf6558067b0", "detected_licenses": [ "MIT" ], "directory_id": "e3acfc4f06840e23ef1185dcf367f40d3e3f59b4", "extension": "c", "filename": "31-mixedjmpbufs.c", "fork_events_count": 62, "gha_created_at": "2011-07-18T15:10:56", "gha_event_created_at": "2023-09-14T18:48:34", "gha_language": "OCaml", "gha_license_id": "MIT", "github_id": 2066905, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 634, "license": "MIT", "license_type": "permissive", "path": "/tests/regression/68-longjmp/31-mixedjmpbufs.c", "provenance": "stackv2-0110.json.gz:215051", "repo_name": "goblint/analyzer", "revision_date": "2023-08-16T08:49:18", "revision_id": "69ee7163eef0bfbfd6a4f3b9fda7cea5ce9ab79f", "snapshot_id": "d62d3c610b86ed288849371b41c330c30678abc7", "src_encoding": "UTF-8", "star_events_count": 141, "url": "https://raw.githubusercontent.com/goblint/analyzer/69ee7163eef0bfbfd6a4f3b9fda7cea5ce9ab79f/tests/regression/68-longjmp/31-mixedjmpbufs.c", "visit_date": "2023-08-16T21:58:53.013737" }
stackv2
#include <pthread.h> #include <goblint.h> #include <setjmp.h> #include <stdio.h> jmp_buf error0; jmp_buf error1; int blorg(int x) { if(x > 8) { longjmp(error1, 1); // WARN (modified since setjmp) } return x; } int blub(int x,int y) { if(x == 0) { longjmp(error0, 1); // WARN (modified since setjmp) } return blorg(x-27+3); } int main(void) { if(setjmp(error0)) { printf("error0 occured"); return -1; } if(setjmp(error1)) { printf("error1 occured"); return -2; } int x, y; scanf("%d", &x); scanf("%d", &y); int x = blub(x, y); // NOWARN printf("%d", x); return 0; }
2.546875
3
2024-11-18T20:50:30.892706+00:00
2019-11-12T07:04:24
5acfb5b0a9f11e74c9aeec1ef44a39247aee01dc
{ "blob_id": "5acfb5b0a9f11e74c9aeec1ef44a39247aee01dc", "branch_name": "refs/heads/master", "committer_date": "2019-11-12T07:04:24", "content_id": "ea0059846cf537e2f666341595ed8f4c58175b99", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "6b090dfe77e8d8bf937100e70341cb190213d710", "extension": "c", "filename": "esl_avx512.c", "fork_events_count": 0, "gha_created_at": "2019-11-12T08:16:49", "gha_event_created_at": "2019-11-12T08:16:54", "gha_language": null, "gha_license_id": "NOASSERTION", "github_id": 221165219, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4804, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/esl_avx512.c", "provenance": "stackv2-0110.json.gz:215313", "repo_name": "smsaladi/easel", "revision_date": "2019-11-12T07:04:24", "revision_id": "d7679b5a4155bd32017e9b4fe2c8f1f316d15b6b", "snapshot_id": "58f0a0e89059135db146d896735b615de32d16de", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/smsaladi/easel/d7679b5a4155bd32017e9b4fe2c8f1f316d15b6b/esl_avx512.c", "visit_date": "2020-09-08T14:54:52.494856" }
stackv2
/* Vectorized routines for x86 AVX-512 instructions * * Most speed-critical code is in the .h file, to facilitate inlining. * * Contents: * 1. Debugging/development routines * 2. Unit tests * 3. Test driver * * This code is conditionally compiled, only when <eslENABLE_AVX512> was * set in <esl_config.h> by the configure script, and that will only * happen on x86 platforms. When <eslENABLE_AVX512> is not set, we * include some dummy code to silence compiler and ranlib warnings * about empty translation units and no symbols, and dummy drivers * that do nothing but declare success. */ #include "esl_config.h" #ifdef eslENABLE_AVX512 #include <stdio.h> #include <x86intrin.h> #include "easel.h" #include "esl_avx512.h" /***************************************************************** * 1. Debugging/development routines *****************************************************************/ void esl_avx512_dump_512i_hex8(simde__m512i v) { uint64_t *val = (uint64_t*) &v; printf("%016" PRIx64 " %016" PRIx64 " %016" PRIx64 " %016" PRIx64 " %016" PRIx64 " %016" PRIx64 " %016" PRIx64 " %016" PRIx64 "\n", val[7], val[6], val[5], val[4], val[3], val[2], val[1], val[0]); } /***************************************************************** * 2. Unit tests *****************************************************************/ #ifdef eslAVX512_TESTDRIVE #include "esl_random.h" static void utest_hmax_epu8(ESL_RANDOMNESS *rng) { union { simde__m512i v; uint8_t x[64]; } u; uint8_t r1, r2; int i,z; for (i = 0; i < 100; i++) { r1 = 0; for (z = 0; z < 64; z++) { u.x[z] = (uint8_t) (esl_rnd_Roll(rng, 256)); // 0..255 if (u.x[z] > r1) r1 = u.x[z]; } r2 = esl_avx512_hmax_epu8(u.v); if (r1 != r2) esl_fatal("hmax_epu8 utest failed"); } } static void utest_hmax_epi8(ESL_RANDOMNESS *rng) { union { simde__m512i v; int8_t x[64]; } u; int8_t r1, r2; int i,z; for (i = 0; i < 100; i++) { r1 = 0; for (z = 0; z < 64; z++) { u.x[z] = (int8_t) (esl_rnd_Roll(rng, 256) - 128); // -128..127 if (u.x[z] > r1) r1 = u.x[z]; } r2 = esl_avx512_hmax_epi8(u.v); if (r1 != r2) esl_fatal("hmax_epi8 utest failed"); } } static void utest_hmax_epi16(ESL_RANDOMNESS *rng) { union { simde__m512i v; int16_t x[32]; } u; int16_t r1, r2; int i,z; for (i = 0; i < 100; i++) { r1 = -32768; for (z = 0; z < 32; z++) { u.x[z] = (int16_t) (esl_rnd_Roll(rng, 65536) - 32768); // -32768..32767 if (u.x[z] > r1) r1 = u.x[z]; } r2 = esl_avx512_hmax_epi16(u.v); if (r1 != r2) esl_fatal("hmax_epi16 utest failed %d %d", r1, r2); } } #endif /*eslAVX512_TESTDRIVE*/ /***************************************************************** * 3. Test driver *****************************************************************/ #ifdef eslAVX512_TESTDRIVE #include "esl_config.h" #include <stdio.h> #include <math.h> #include "easel.h" #include "esl_cpu.h" #include "esl_getopts.h" #include "esl_random.h" #include "esl_avx512.h" static ESL_OPTIONS options[] = { /* name type default env range toggles reqs incomp help docgroup*/ { "-h", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "show brief help on version and usage", 0 }, { "-s", eslARG_INT, "0", NULL, NULL, NULL, NULL, NULL, "set random number seed to <n>", 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, }; static char usage[] = "[-options]"; static char banner[] = "test driver for avx512 module"; int main(int argc, char **argv) { ESL_GETOPTS *go = esl_getopts_CreateDefaultApp(options, 0, argc, argv, banner, usage); ESL_RANDOMNESS *rng = esl_randomness_Create(esl_opt_GetInteger(go, "-s"));; fprintf(stderr, "## %s\n", argv[0]); fprintf(stderr, "# rng seed = %" PRIu32 "\n", esl_randomness_GetSeed(rng)); if (esl_cpu_has_avx512()) { utest_hmax_epu8(rng); utest_hmax_epi8(rng); utest_hmax_epi16(rng); } else { fprintf(stderr, "processor does not support our AVX-512 code; skipping tests.\n"); fprintf(stderr, " (we need KNL's F,CD,ER,PF subsets, plus DQ,BW)\n"); } fprintf(stderr, "# status = ok\n"); esl_randomness_Destroy(rng); esl_getopts_Destroy(go); return 0; } #endif /*eslAVX512_TESTDRIVE*/ #else // ! eslENABLE_AVX512 #include <stdio.h> void esl_avx512_silence_hack(void) { return; } #if defined eslAVX512_TESTDRIVE || eslAVX512_EXAMPLE || eslAVX512_BENCHMARK int main(void) { fprintf(stderr, "# AVX512 support not compiled.\n"); return 0; } #endif #endif // eslENABLE_AVX512
2.3125
2
2024-11-18T20:50:31.020148+00:00
2020-12-20T06:27:33
7de558d157429cd42112d362cc0c250cb010a715
{ "blob_id": "7de558d157429cd42112d362cc0c250cb010a715", "branch_name": "refs/heads/master", "committer_date": "2020-12-20T06:27:33", "content_id": "ea5d0aa60f8d4c34f18c3400961d3ed1bd89e65a", "detected_licenses": [ "0BSD" ], "directory_id": "9c3e6a0944eb766d3a5cc5c16fd0a100167fba24", "extension": "c", "filename": "clib.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": 7051, "license": "0BSD", "license_type": "permissive", "path": "/clib.c", "provenance": "stackv2-0110.json.gz:215443", "repo_name": "echelonxray/near_the_metal", "revision_date": "2020-12-20T06:27:33", "revision_id": "9ffb7704339f56a9e022a7c69f2e91fee5ef0425", "snapshot_id": "baeb78b8f7089887f95f7e470e994d2b530463bb", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/echelonxray/near_the_metal/9ffb7704339f56a9e022a7c69f2e91fee5ef0425/clib.c", "visit_date": "2023-02-01T00:06:02.499596" }
stackv2
#include "clib.h" #include "syscalls.h" #include "errno.h" #include <linux/sched.h> #include <linux/futex.h> size_t PAGE_SIZE; void __init_libc() { __errno_init_errno(); struct stat statbuf; if (stat("/dev/mem", &statbuf) < 0) { exit(-1); } PAGE_SIZE = statbuf.st_blksize; __errno_init_thread(); return; } void __destroy_libc() { /* Clean up dynamic memory mapping for thread errno locations. I'm not sure this is really safe unless I halt or kill all threads first. This probably should have already happened, but if there are rouge threads, this will probably induce segfaults just prior to program exit as any rouge threads attempt to reference errno. Such a bug would be very rare since it requires such specific conditions to manifest and would be a nightmare to debug. The kernel will clean up the mapping for us anyway after we exit_group(). We can munmap() safely if(__errno_base_thread_count == 0);. */ if (__errno_base_thread_count == 0) { __errno_destroy_thread(); } return; } signed int __new_thread(void* arg) { // Retrieve thread information struct thread_tmp_args* args; args = arg; // Add errno location for this thread __errno_add_thread_entry(args->ethread->tid); // Call the function void* (*fn)(void*); void *retptr; fn = args->fn; retptr = fn(args->args); args->ethread->retval = retptr; // Exit the thread _exit(0); return 0; } signed int new_thread(ethread_t* thread, void* (*fn)(void*), void* arg) { pid_t retval; struct thread_tmp_args args; args.args = arg; args.fn = fn; args.ethread = thread; thread->retval = 0; thread->tid = 0; thread->stack_size = 8192000 + sizeof(struct thread_tmp_args); void* ptr = mmap(0, thread->stack_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_STACK, -1, 0); if (ptr == (void*)-1) { return -1; } thread->stack_loc = ptr; ptr = (ptr + thread->stack_size) - sizeof(struct thread_tmp_args); *((struct thread_tmp_args*)ptr) = args; retval = clone(__new_thread, ptr, CLONE_THREAD | CLONE_SIGHAND | CLONE_VM | CLONE_PARENT | CLONE_PARENT_SETTID | CLONE_FILES | CLONE_FS | CLONE_CHILD_CLEARTID, ptr, (void*)(&(thread->tid)), 0, (void*)(&(thread->tid))); if (retval == -1) { return -1; } thread->tid2 = retval; return 0; } signed int join_thread(ethread_t* thread, void** retval) { // TODO: Implement better error handling pid_t tid = thread->tid; if (tid != 0) { futex((void*)(&(thread->tid)), FUTEX_WAIT, tid, NULL, 0, 0); } if (thread->stack_size != 0) { __errno_remove_thread_entry(thread->tid2); munmap((void*)thread->stack_loc, thread->stack_size); thread->stack_loc = 0; thread->stack_size = 0; thread->tid = 0; if (retval != NULL) { *retval = (void*)(thread->retval); } } return 0; } void mutex_init(mutex* mut) { mut->lock_flag = 1; mut->lock_count = 0; mut->locking_tid = 0; } void mutex_lock(mutex* mut) { unsigned int is_non_zero; unsigned int value; __asm__ __volatile__ ( "LOCK incl (%%rcx) \n" \ : /* Output */ \ : /* Input */ "c" (&(mut->lock_count)) \ : /* Clobbers */ "cc" ); // Atomically decrement "mul->lock_flag" and check Zero-Flag status. __asm__ __volatile__ ( "xor %%rdx, %%rdx \n" \ "LOCK decl (%%rcx) \n" \ "setnz %%dl \n" \ : /* Output */ "=d" (is_non_zero) \ : /* Input */ "c" (&(mut->lock_flag)) \ : /* Clobbers */ "cc" ); value = mut->lock_flag; while(is_non_zero == 1) { if (value == 0) { // Catch the race condition. // // In this case, the lock has been released(And the value // of mut->lock_flag changed) between our atomic instruction // on the value in memory and the retrieval of the value // itself from memory. Since the value of "mut->lock_flag" is // now "0", we can simply just assume ownership of the lock and // therefore, we don't need to block after all. So we break out // of the loop. break; } // Match the variable "value" to the expected value //of "mut->lock_flag" in memory value++; // Since we can't actually take ownership of the lock, // atomically increment the "mul->lock_flag" back up __asm__ __volatile__ ( "LOCK incl (%%rcx) \n" \ : /* Output */ \ : /* Input */ "c" (&(mut->lock_flag)) \ : /* Clobbers */ "cc" ); // Wait for "mul->lock_flag" to change // This will not block if "value" does not match "mul->lock_flag" // In the event if this, we simply continue the loop to recompute what // has changed outside of this thread and retry. futex((void*)(&(mut->lock_flag)), FUTEX_WAIT, value, NULL, 0, 0); // Atomically decrement the lock flag and check Zero-Flag status. __asm__ __volatile__ ( "xor %%rdx, %%rdx \n" \ "LOCK decl (%%rcx) \n" \ "setnz %%dl \n" \ : /* Output */ "=d" (is_non_zero) \ : /* Input */ "c" (&(mut->lock_flag)) \ : /* Clobbers */ "cc" ); value = mut->lock_flag; } mut->locking_tid = gettid(); return; } void mutex_unlock(mutex* mut) { unsigned int is_non_zero; if (mut->locking_tid != gettid()) { return; } mut->locking_tid = 0; __asm__ __volatile__ ( "LOCK incl (%%rcx) \n" \ : /* Output */ \ : /* Input */ "c" (&(mut->lock_flag)) \ : /* Clobbers */ "cc" ); __asm__ __volatile__ ( "xor %%rdx, %%rdx \n" \ "LOCK decl (%%rcx) \n" \ "setnz %%dl \n" \ : /* Output */ "=d" (is_non_zero) \ : /* Input */ "c" (&(mut->lock_count)) \ : /* Clobbers */ "cc" ); if (is_non_zero == 1) { futex((void*)(&(mut->lock_flag)), FUTEX_WAKE, 1, NULL, 0, 0); } return; } signed int sigemptyset(sigset_t *set) { *set = 0; return 0; } signed int sigaction(signed int signum, const struct sigaction* act, struct sigaction* oldact) { return rt_sigaction(signum, act, oldact, sizeof(sigset_t)); } pid_t wait(signed int* wstatus) { return waitpid(-1, wstatus, 0); } pid_t waitpid(pid_t pid, signed int* wstatus, signed int options) { return wait4(pid, wstatus, options, NULL); } void* calloc(size_t nmemb, size_t size) { if (nmemb == 0 || size == 0) { return 0; } size_t max_val = ~0; if (max_val / size < nmemb || max_val / nmemb < size) { return 0; } return malloc(nmemb * size); } void* malloc(size_t size) { if (size == 0) { return NULL; } register void* retval; retval = mmap(0, size + sizeof(size_t), PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); *((size_t*)retval) = size + sizeof(size_t); return retval + sizeof(size_t); } void free(void* ptr) { if (ptr == NULL) { return; } //signed int retval; ptr -= sizeof(size_t); /*retval = */munmap(ptr, *((size_t*)ptr)); return; } void *memset(void *s, signed int c, size_t n) { while (n > 0) { n--; ((unsigned char*)s)[n] = (unsigned char)(c & 0xFF); } return s; } void *memcpy(void* dest, const void* src, size_t n) { while (n > 0) { n--; ((unsigned char*)dest)[n] = ((unsigned char*)src)[n]; } return dest; } void exit(signed int code) { exit_group(code); }
2.484375
2
2024-11-18T20:50:31.093501+00:00
2015-11-04T21:25:35
4b9e52edbd445039a73e2ea79470923cd451ed4a
{ "blob_id": "4b9e52edbd445039a73e2ea79470923cd451ed4a", "branch_name": "refs/heads/master", "committer_date": "2015-11-04T21:25:35", "content_id": "e2afa5f4e22cf847c4d4b6169be65f27281fc198", "detected_licenses": [ "BSD-4-Clause-UC", "BSD-2-Clause" ], "directory_id": "945742b74c53ff202b6eae226df23ea3f612ef57", "extension": "c", "filename": "rshell.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 5234378, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 976, "license": "BSD-4-Clause-UC,BSD-2-Clause", "license_type": "permissive", "path": "/shell/rshell.c", "provenance": "stackv2-0110.json.gz:215573", "repo_name": "jguillaumes/muxx", "revision_date": "2015-11-04T21:25:35", "revision_id": "2b9e20dcef9d42e6abfe0024fef16ad98b78facf", "snapshot_id": "1c7619555ed3015ebdc8c46fb1126b4110d54556", "src_encoding": "UTF-8", "star_events_count": 4, "url": "https://raw.githubusercontent.com/jguillaumes/muxx/2b9e20dcef9d42e6abfe0024fef16ad98b78facf/shell/rshell.c", "visit_date": "2016-09-06T02:39:40.104377" }
stackv2
// #include <string.h> #include "config.h" #include "muxxlib.h" #include "muxxdef.h" #include "errno.h" typedef int (*MAINPROG)(int, char **, char **); #define NULL 0x0 int rshell() { char *parm = (char *) TASK_BASE; ADDRESS entry = NULL; MAINPROG pgm = NULL; int rc = 0; printf("Loading from device %8s...\n", parm); rc = load(parm, parm, &entry); while (rc == ENOAVAIL || rc == ENOSYSRES) { printf("Device not available (%d), sleeping and retrying...\n", rc); sleep(1); rc = load(parm, parm, &entry); } if (rc >= 0) { printf("Load OK, %d bytes loaded.\n", rc); printf("Task entry point: %o\n", entry); pgm = (MAINPROG) entry; rc = (*pgm)(0,NULL,NULL); } else { printf("Load failed, rc=%d\n", rc); } while(1) { // TO-DO Write task exit code here // printf("Rshell ended...\n"); printf("Task exited - we don't know to handle that yet!\n"); printf("Suspending this task..."); suspend(NULL); } }
2.5625
3
2024-11-18T20:50:31.222848+00:00
2021-06-30T06:33:22
5472773563d38b26b724c29449de08e979371526
{ "blob_id": "5472773563d38b26b724c29449de08e979371526", "branch_name": "refs/heads/main", "committer_date": "2021-06-30T06:33:22", "content_id": "a39e04199f1f88f3cc35635ed5f6af017cc06608", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "0d9b8bec2a76cd67354fb6e790bc9a663efe0e0b", "extension": "c", "filename": "main.c", "fork_events_count": 2, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 381544221, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 6271, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/Examples/wwdg/wwdg_application_example/Src/main.c", "provenance": "stackv2-0110.json.gz:215701", "repo_name": "zbitsemi/CX32L003SDK", "revision_date": "2021-06-30T06:33:22", "revision_id": "6969760073f42c3a65bd092146c76851c29871e5", "snapshot_id": "2c71e53293d3deca6959632b956777c96284efe6", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/zbitsemi/CX32L003SDK/6969760073f42c3a65bd092146c76851c29871e5/Examples/wwdg/wwdg_application_example/Src/main.c", "visit_date": "2023-06-03T08:16:58.066489" }
stackv2
/** ****************************************************************************** * @file main.c * @author MCU Software Team * @Version V1.2.0 * @Date 2021-01-11 * @brief main function ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "main.h" /* Private variables ---------------------------------------------------------*/ /* Private function prototypes -----------------------------------------------*/ /* Private user code ---------------------------------------------------------*/ #define WWDG_TEST_TIME 0X53 // time 3.63S,PCLK=24M #define WWDG_TEST_WINDOW_TIME 0X20 // 1401.6ms #define WWDG_TEST_PRESCALER 0XFFFFF // 43.8ms #define WWDG_TEST_MODE WWDG_REFRESH_DOG//WWDG_UNREFRESH_RESET//WWDG_REFRESH_INTERRUPT//WWDG_REFRESH_DOG WWDG_HandleTypeDef wwdg_test = {0}; FlagStatus wwdg_int = RESET; /** * @brief WWDG Clock Configuration * @retval None */ void WWdgClock_Config(void) { __HAL_RCC_WWDG_CLK_ENABLE(); } /** * @brief WWDG Interrupt call * @retval None */ void HAL_WWDG_INT_Callback(void) { wwdg_int = SET; } /** * @brief WWDG Init Configuration * @retval None */ void WWdg_Init(void) { if(__HAL_RCC_GET_FLAG(RCC_FLAG_WWDGRST) != true) printf("Test WWDG RESET ,NO RESET!\r\n"); else { printf("Test WWDG RESET ,HAVE RESET!!!!\r\n"); __HAL_RCC_CLEAR_RESET_FLAGS(RCC_FLAG_WWDGRST); } /*set init */ wwdg_test.Instance = WWDG; wwdg_test.Init.Reload = WWDG_TEST_TIME; wwdg_test.Init.Window = WWDG_TEST_WINDOW_TIME; wwdg_test.Init.Prescaler = WWDG_TEST_PRESCALER; wwdg_test.Init.INTSet = WWDG_INT_ENABLE; /* Set interrupt priority and turn on interrupt*/ HAL_NVIC_SetPriority(WWDG_IRQn, PRIORITY_LOW); HAL_NVIC_EnableIRQ(WWDG_IRQn); if(WWDG_TEST_MODE == WWDG_REFRESH_INTERRUPT) printf("Enter Test WWDG Interrupt\r\n"); else if(WWDG_TEST_MODE == WWDG_UNREFRESH_RESET) { printf("Enter Test WWDG UNREFRESH RESET ,wait 5S\r\n"); HAL_Delay(5000); } else if(WWDG_TEST_MODE == WWDG_REFRESH_RESET) { wwdg_test.Init.INTSet = WWDG_INT_DISABLE; printf("Enter Test WWDG REFRESH RESET ,wait 5S\r\n"); HAL_Delay(5000); } else { wwdg_test.Init.INTSet = WWDG_INT_DISABLE; /*See feed the dog successfully or not, so turn on interrupt*/ printf("Enter Test WWDG refresh\r\n"); } HAL_WWDG_Init(&wwdg_test); } /** * @brief The application entry point. * @retval int */ int main(void) { uint32_t cur_counter = 0; uint32_t times = 0; uint32_t plk_freq = 0; /* Reset of all peripherals, Initializes the Flash interface and the Systick. */ HAL_Init(); /* Configure the system clock to HIRC 24MHz*/ SystemClock_Config(); /* Initialize BSP Led for LED1 */ BSP_LED_Init(LED1); plk_freq = HAL_RCC_GetPCLKFreq(); /* Configure uart1 for printf */ LogInit(); printf("Printf success using UART1, PD5-TXD, PD6-RXD\r\n"); printf("PCLK freq :%dHZ\r\n",plk_freq); WWdgClock_Config(); WWdg_Init(); while (1) { // HAL_WWDG_Refresh(&wwdg_test); if (WWDG_TEST_MODE == WWDG_REFRESH_INTERRUPT) { if(wwdg_int != RESET) { HAL_WWDG_Refresh(&wwdg_test); times ++; wwdg_int = RESET; printf("INT %d \r\n",times); BSP_LED_Toggle(LED1); } if(times>0XFFFFFFF) times = 0; } else if (WWDG_TEST_MODE == WWDG_UNREFRESH_RESET) { if(wwdg_int != RESET) { cur_counter = 0; times ++; wwdg_int = RESET; printf("INT %d\r\n",times); BSP_LED_Toggle(LED1); //HAL_WWDG_Refresh(&wwdg_test); } if(times>0XFFFFFFF) times = 0; } else if (WWDG_TEST_MODE == WWDG_REFRESH_RESET) { times = 0; if(wwdg_int != RESET) { printf("INT happen\r\n"); wwdg_int = RESET; } else { HAL_WWDG_Get_Counter(&wwdg_test, &cur_counter); if(cur_counter > WWDG_TEST_WINDOW_TIME) { BSP_LED_Toggle(LED1); HAL_WWDG_Refresh(&wwdg_test); printf(" cur_counter > WWDG_TEST_WINDOW_TIME HAL_WWDG_Refresh\r\n"); } } } else { times = 0; if(wwdg_int != RESET) { printf("INT happen\r\n"); wwdg_int = RESET; } else { HAL_WWDG_Get_Counter(&wwdg_test, &cur_counter); if(cur_counter < WWDG_TEST_WINDOW_TIME) { HAL_WWDG_Refresh(&wwdg_test); BSP_LED_Toggle(LED1); printf(" cur_counter < WWDG_TEST_WINDOW_TIME HAL_WWDG_Refresh\r\n"); } } } } } /** * @brief System Clock Configuration * @retval None */ void SystemClock_Config(void) { RCC_OscInitTypeDef RCC_OscInitStruct = {0}; RCC_ClkInitTypeDef RCC_ClkInitStruct = {0}; RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HIRC; RCC_OscInitStruct.HIRCState = RCC_HIRC_ON; RCC_OscInitStruct.HIRCCalibrationValue = RCC_HIRCCALIBRATION_24M; if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) { Error_Handler(); } /**Initializes the CPU, AHB and APB busses clocks */ RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_PCLK; RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_HIRC; RCC_ClkInitStruct.AHBCLKDivider = RCC_HCLK_DIV1; RCC_ClkInitStruct.APBCLKDivider = RCC_PCLK_DIV1; if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct) != HAL_OK) { Error_Handler(); } } /** * @brief This function is executed in case of error occurrence. * @retval None */ void Error_Handler(void) { /* USER CODE BEGIN Error_Handler_Debug */ /* User can add his own implementation to report the HAL error return state */ /* USER CODE END Error_Handler_Debug */ } #ifdef USE_FULL_ASSERT /** * @brief Reports the name of the source file and the source line number * where the assert_param error has occurred. * @param file: pointer to the source file name * @param line: assert_param error line source number * @retval None */ void assert_failed(uint8_t *file, uint32_t line) { /* USER CODE BEGIN 6 */ /* User can add his own implementation to report the file name and line number, tex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */ /* USER CODE END 6 */ } #endif /* USE_FULL_ASSERT */ /* Private function -------------------------------------------------------*/
2.328125
2
2024-11-18T20:50:31.286823+00:00
2017-01-19T02:02:50
66c28f8ae2c1753a0a78f459b4f37229199975fe
{ "blob_id": "66c28f8ae2c1753a0a78f459b4f37229199975fe", "branch_name": "refs/heads/master", "committer_date": "2017-01-19T02:02:50", "content_id": "3ed4ce6b7948c7911427d01a36e8686760f35b51", "detected_licenses": [ "PostgreSQL", "BSD-2-Clause" ], "directory_id": "4d5f2cdc0b7120f74ba6f357b21dac063e71b606", "extension": "c", "filename": "proc.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 79404002, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 32361, "license": "PostgreSQL,BSD-2-Clause", "license_type": "permissive", "path": "/postgresql/src/backend/storage/lmgr/proc.c", "provenance": "stackv2-0110.json.gz:215831", "repo_name": "anjingbin/starccm", "revision_date": "2017-01-19T02:02:50", "revision_id": "70db48004aa20bbb82cc24de80802b40c7024eff", "snapshot_id": "cf499238ceb1e4f0235421cb6f3cb823b932a2cd", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/anjingbin/starccm/70db48004aa20bbb82cc24de80802b40c7024eff/postgresql/src/backend/storage/lmgr/proc.c", "visit_date": "2021-01-11T19:49:04.306906" }
stackv2
/*------------------------------------------------------------------------- * * proc.c * routines to manage per-process shared memory data structure * * Portions Copyright (c) 1996-2001, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * * * IDENTIFICATION * $Header: /home/hjcvs/OB-CCM-1.0/postgresql/src/backend/storage/lmgr/proc.c,v 1.2 2004/07/05 08:55:39 SuLiang Exp $ * *------------------------------------------------------------------------- */ /* * Interface (a): * ProcSleep(), ProcWakeup(), * ProcQueueAlloc() -- create a shm queue for sleeping processes * ProcQueueInit() -- create a queue without allocing memory * * Locking and waiting for buffers can cause the backend to be * put to sleep. Whoever releases the lock, etc. wakes the * process up again (and gives it an error code so it knows * whether it was awoken on an error condition). * * Interface (b): * * ProcReleaseLocks -- frees the locks associated with current transaction * * ProcKill -- destroys the shared memory state (and locks) * associated with the process. * * 5/15/91 -- removed the buffer pool based lock chain in favor * of a shared memory lock chain. The write-protection is * more expensive if the lock chain is in the buffer pool. * The only reason I kept the lock chain in the buffer pool * in the first place was to allow the lock table to grow larger * than available shared memory and that isn't going to work * without a lot of unimplemented support anyway. * * 4/7/95 -- instead of allocating a set of 1 semaphore per process, we * allocate a semaphore from a set of PROC_NSEMS_PER_SET semaphores * shared among backends (we keep a few sets of semaphores around). * This is so that we can support more backends. (system-wide semaphore * sets run out pretty fast.) -ay 4/95 */ #include "postgres.h" #include <errno.h> #include <signal.h> #include <unistd.h> #include <sys/time.h> #include "storage/ipc.h" /* In Ultrix, sem.h and shm.h must be included AFTER ipc.h */ #ifdef HAVE_SYS_SEM_H #include <sys/sem.h> #endif #if defined(__darwin__) #include "port/darwin/sem.h" #endif #include "miscadmin.h" #include "access/xact.h" #include "storage/proc.h" #include "storage/sinval.h" #include "storage/spin.h" int DeadlockTimeout = 1000; PROC *MyProc = NULL; /* * This spinlock protects the freelist of recycled PROC structures and the * bitmap of free semaphores. We cannot use an LWLock because the LWLock * manager depends on already having a PROC and a wait semaphore! But these * structures are touched relatively infrequently (only at backend startup * or shutdown) and not for very long, so a spinlock is okay. */ static slock_t *ProcStructLock = NULL; static PROC_HDR *ProcGlobal = NULL; static PROC *DummyProc = NULL; static bool waitingForLock = false; static bool waitingForSignal = false; static void ProcKill(void); static void DummyProcKill(void); static void ProcGetNewSemIdAndNum(IpcSemaphoreId *semId, int *semNum); static void ProcFreeSem(IpcSemaphoreId semId, int semNum); static void ZeroProcSemaphore(PROC *proc); static void ProcFreeAllSemaphores(void); /* * InitProcGlobal - * initializes the global process table. We put it here so that * the postmaster can do this initialization. (ProcFreeAllSemaphores needs * to read this table on exiting the postmaster. If we have the first * backend do this, starting up and killing the postmaster without * starting any backends will be a problem.) * * We also allocate all the per-process semaphores we will need to support * the requested number of backends. We used to allocate semaphores * only when backends were actually started up, but that is bad because * it lets Postgres fail under load --- a lot of Unix systems are * (mis)configured with small limits on the number of semaphores, and * running out when trying to start another backend is a common failure. * So, now we grab enough semaphores to support the desired max number * of backends immediately at initialization --- if the sysadmin has set * MaxBackends higher than his kernel will support, he'll find out sooner * rather than later. */ void InitProcGlobal(int maxBackends) { int semMapEntries; Size procGlobalSize; bool found = false; /* * Compute size for ProcGlobal structure. Note we need one more sema * besides those used for regular backends; this is accounted for in * the PROC_SEM_MAP_ENTRIES macro. (We do it that way so that other * modules that use PROC_SEM_MAP_ENTRIES(maxBackends) to size data * structures don't have to know about this explicitly.) */ Assert(maxBackends > 0); semMapEntries = PROC_SEM_MAP_ENTRIES(maxBackends); procGlobalSize = sizeof(PROC_HDR) + (semMapEntries - 1) *sizeof(SEM_MAP_ENTRY); /* Create or attach to the ProcGlobal shared structure */ ProcGlobal = (PROC_HDR *) ShmemInitStruct("Proc Header", procGlobalSize, &found); /* -------------------- * We're the first - initialize. * XXX if found should ever be true, it is a sign of impending doom ... * ought to complain if so? * -------------------- */ if (!found) { int i; ProcGlobal->freeProcs = INVALID_OFFSET; ProcGlobal->semMapEntries = semMapEntries; for (i = 0; i < semMapEntries; i++) { ProcGlobal->procSemMap[i].procSemId = -1; ProcGlobal->procSemMap[i].freeSemMap = 0; } /* * Arrange to delete semas on exit --- set this up now so that we * will clean up if pre-allocation fails. We use our own * freeproc, rather than IpcSemaphoreCreate's removeOnExit option, * because we don't want to fill up the on_shmem_exit list with a * separate entry for each semaphore set. */ on_shmem_exit(ProcFreeAllSemaphores, 0); /* * Pre-create the semaphores. */ for (i = 0; i < semMapEntries; i++) { IpcSemaphoreId semId; semId = IpcSemaphoreCreate(PROC_NSEMS_PER_SET, IPCProtection, 1, false); ProcGlobal->procSemMap[i].procSemId = semId; } /* * Pre-allocate a PROC structure for dummy (checkpoint) processes, * and reserve the last sema of the precreated semas for it. */ DummyProc = (PROC *) ShmemAlloc(sizeof(PROC)); DummyProc->pid = 0; /* marks DummyProc as not in use */ i = semMapEntries - 1; ProcGlobal->procSemMap[i].freeSemMap |= 1 << (PROC_NSEMS_PER_SET - 1); DummyProc->sem.semId = ProcGlobal->procSemMap[i].procSemId; DummyProc->sem.semNum = PROC_NSEMS_PER_SET - 1; /* Create ProcStructLock spinlock, too */ ProcStructLock = (slock_t *) ShmemAlloc(sizeof(slock_t)); SpinLockInit(ProcStructLock); } } /* * InitProcess -- create a per-process data structure for this backend */ void InitProcess(void) { SHMEM_OFFSET myOffset; /* use volatile pointer to prevent code rearrangement */ volatile PROC_HDR *procglobal = ProcGlobal; /* * ProcGlobal should be set by a previous call to InitProcGlobal (if * we are a backend, we inherit this by fork() from the postmaster). */ if (procglobal == NULL) elog(STOP, "InitProcess: Proc Header uninitialized"); if (MyProc != NULL) elog(ERROR, "InitProcess: you already exist"); /* * try to get a proc struct from the free list first */ SpinLockAcquire(ProcStructLock); myOffset = procglobal->freeProcs; if (myOffset != INVALID_OFFSET) { MyProc = (PROC *) MAKE_PTR(myOffset); procglobal->freeProcs = MyProc->links.next; SpinLockRelease(ProcStructLock); } else { /* * have to allocate a new one. */ SpinLockRelease(ProcStructLock); MyProc = (PROC *) ShmemAlloc(sizeof(PROC)); if (!MyProc) elog(FATAL, "cannot create new proc: out of memory"); } /* * Initialize all fields of MyProc. */ SHMQueueElemInit(&(MyProc->links)); MyProc->sem.semId = -1; /* no wait-semaphore acquired yet */ MyProc->sem.semNum = -1; MyProc->errType = STATUS_OK; MyProc->xid = InvalidTransactionId; MyProc->xmin = InvalidTransactionId; MyProc->pid = MyProcPid; MyProc->databaseId = MyDatabaseId; MyProc->logRec.xrecoff = 0; MyProc->lwWaiting = false; MyProc->lwExclusive = false; MyProc->lwWaitLink = NULL; MyProc->waitLock = NULL; MyProc->waitHolder = NULL; SHMQueueInit(&(MyProc->procHolders)); /* * Arrange to clean up at backend exit. */ on_shmem_exit(ProcKill, 0); /* * Set up a wait-semaphore for the proc. (We rely on ProcKill to * clean up MyProc if this fails.) */ if (IsUnderPostmaster) ProcGetNewSemIdAndNum(&MyProc->sem.semId, &MyProc->sem.semNum); /* * We might be reusing a semaphore that belonged to a failed process. * So be careful and reinitialize its value here. */ if (MyProc->sem.semId >= 0) ZeroProcSemaphore(MyProc); /* * Now that we have a PROC, we could try to acquire locks, so * initialize the deadlock checker. */ InitDeadLockChecking(); } /* * InitDummyProcess -- create a dummy per-process data structure * * This is called by checkpoint processes so that they will have a MyProc * value that's real enough to let them wait for LWLocks. The PROC and * sema that are assigned are the extra ones created during InitProcGlobal. */ void InitDummyProcess(void) { /* * ProcGlobal should be set by a previous call to InitProcGlobal (we * inherit this by fork() from the postmaster). */ if (ProcGlobal == NULL || DummyProc == NULL) elog(STOP, "InitDummyProcess: Proc Header uninitialized"); if (MyProc != NULL) elog(ERROR, "InitDummyProcess: you already exist"); /* * DummyProc should not presently be in use by anyone else */ if (DummyProc->pid != 0) elog(FATAL, "InitDummyProcess: DummyProc is in use by PID %d", DummyProc->pid); MyProc = DummyProc; /* * Initialize all fields of MyProc, except MyProc->sem which was set * up by InitProcGlobal. */ MyProc->pid = MyProcPid; /* marks DummyProc as in use by me */ SHMQueueElemInit(&(MyProc->links)); MyProc->errType = STATUS_OK; MyProc->xid = InvalidTransactionId; MyProc->xmin = InvalidTransactionId; MyProc->databaseId = MyDatabaseId; MyProc->logRec.xrecoff = 0; MyProc->lwWaiting = false; MyProc->lwExclusive = false; MyProc->lwWaitLink = NULL; MyProc->waitLock = NULL; MyProc->waitHolder = NULL; SHMQueueInit(&(MyProc->procHolders)); /* * Arrange to clean up at process exit. */ on_shmem_exit(DummyProcKill, 0); /* * We might be reusing a semaphore that belonged to a failed process. * So be careful and reinitialize its value here. */ if (MyProc->sem.semId >= 0) ZeroProcSemaphore(MyProc); } /* * Initialize the proc's wait-semaphore to count zero. */ static void ZeroProcSemaphore(PROC *proc) { union semun semun; semun.val = 0; if (semctl(proc->sem.semId, proc->sem.semNum, SETVAL, semun) < 0) { fprintf(stderr, "ZeroProcSemaphore: semctl(id=%d,SETVAL) failed: %s\n", proc->sem.semId, strerror(errno)); proc_exit(255); } } /* * Cancel any pending wait for lock, when aborting a transaction. * * Returns true if we had been waiting for a lock, else false. * * (Normally, this would only happen if we accept a cancel/die * interrupt while waiting; but an elog(ERROR) while waiting is * within the realm of possibility, too.) */ bool LockWaitCancel(void) { /* Nothing to do if we weren't waiting for a lock */ if (!waitingForLock) return false; waitingForLock = false; /* Turn off the deadlock timer, if it's still running (see ProcSleep) */ disable_sigalrm_interrupt(); /* Unlink myself from the wait queue, if on it (might not be anymore!) */ LWLockAcquire(LockMgrLock, LW_EXCLUSIVE); if (MyProc->links.next != INVALID_OFFSET) RemoveFromWaitQueue(MyProc); LWLockRelease(LockMgrLock); /* * Reset the proc wait semaphore to zero. This is necessary in the * scenario where someone else granted us the lock we wanted before we * were able to remove ourselves from the wait-list. The semaphore * will have been bumped to 1 by the would-be grantor, and since we * are no longer going to wait on the sema, we have to force it back * to zero. Otherwise, our next attempt to wait for a lock will fall * through prematurely. */ ZeroProcSemaphore(MyProc); /* * Return true even if we were kicked off the lock before we were able * to remove ourselves. */ return true; } /* * ProcReleaseLocks() -- release locks associated with current transaction * at transaction commit or abort * * At commit, we release only locks tagged with the current transaction's XID, * leaving those marked with XID 0 (ie, session locks) undisturbed. At abort, * we release all locks including XID 0, because we need to clean up after * a failure. This logic will need extension if we ever support nested * transactions. * * Note that user locks are not released in either case. */ void ProcReleaseLocks(bool isCommit) { if (!MyProc) return; /* If waiting, get off wait queue (should only be needed after error) */ LockWaitCancel(); /* Release locks */ LockReleaseAll(DEFAULT_LOCKMETHOD, MyProc, !isCommit, GetCurrentTransactionId()); } /* * ProcKill() -- Destroy the per-proc data structure for * this process. Release any of its held LW locks. */ static void ProcKill(void) { /* use volatile pointer to prevent code rearrangement */ volatile PROC_HDR *procglobal = ProcGlobal; Assert(MyProc != NULL); /* Release any LW locks I am holding */ LWLockReleaseAll(); /* Abort any buffer I/O in progress */ AbortBufferIO(); /* Get off any wait queue I might be on */ LockWaitCancel(); /* Remove from the standard lock table */ LockReleaseAll(DEFAULT_LOCKMETHOD, MyProc, true, InvalidTransactionId); #ifdef USER_LOCKS /* Remove from the user lock table */ LockReleaseAll(USER_LOCKMETHOD, MyProc, true, InvalidTransactionId); #endif SpinLockAcquire(ProcStructLock); /* Free up my wait semaphore, if I got one */ if (MyProc->sem.semId >= 0) ProcFreeSem(MyProc->sem.semId, MyProc->sem.semNum); /* Add PROC struct to freelist so space can be recycled in future */ MyProc->links.next = procglobal->freeProcs; procglobal->freeProcs = MAKE_OFFSET(MyProc); /* PROC struct isn't mine anymore */ MyProc = NULL; SpinLockRelease(ProcStructLock); } /* * DummyProcKill() -- Cut-down version of ProcKill for dummy (checkpoint) * processes. The PROC and sema are not released, only marked * as not-in-use. */ static void DummyProcKill(void) { Assert(MyProc != NULL && MyProc == DummyProc); /* Release any LW locks I am holding */ LWLockReleaseAll(); /* Abort any buffer I/O in progress */ AbortBufferIO(); /* I can't be on regular lock queues, so needn't check */ /* Mark DummyProc no longer in use */ MyProc->pid = 0; /* PROC struct isn't mine anymore */ MyProc = NULL; } /* * ProcQueue package: routines for putting processes to sleep * and waking them up */ /* * ProcQueueAlloc -- alloc/attach to a shared memory process queue * * Returns: a pointer to the queue or NULL * Side Effects: Initializes the queue if we allocated one */ #ifdef NOT_USED PROC_QUEUE * ProcQueueAlloc(char *name) { bool found; PROC_QUEUE *queue = (PROC_QUEUE *) ShmemInitStruct(name, sizeof(PROC_QUEUE), &found); if (!queue) return NULL; if (!found) ProcQueueInit(queue); return queue; } #endif /* * ProcQueueInit -- initialize a shared memory process queue */ void ProcQueueInit(PROC_QUEUE *queue) { SHMQueueInit(&(queue->links)); queue->size = 0; } /* * ProcSleep -- put a process to sleep * * Caller must have set MyProc->heldLocks to reflect locks already held * on the lockable object by this process (under all XIDs). * * Locktable's masterLock must be held at entry, and will be held * at exit. * * Result: STATUS_OK if we acquired the lock, STATUS_ERROR if not (deadlock). * * ASSUME: that no one will fiddle with the queue until after * we release the masterLock. * * NOTES: The process queue is now a priority queue for locking. * * P() on the semaphore should put us to sleep. The process * semaphore is normally zero, so when we try to acquire it, we sleep. */ int ProcSleep(LOCKMETHODTABLE *lockMethodTable, LOCKMODE lockmode, LOCK *lock, HOLDER *holder) { LOCKMETHODCTL *lockctl = lockMethodTable->ctl; LWLockId masterLock = lockctl->masterLock; PROC_QUEUE *waitQueue = &(lock->waitProcs); int myHeldLocks = MyProc->heldLocks; bool early_deadlock = false; PROC *proc; int i; /* * Determine where to add myself in the wait queue. * * Normally I should go at the end of the queue. However, if I already * hold locks that conflict with the request of any previous waiter, * put myself in the queue just in front of the first such waiter. * This is not a necessary step, since deadlock detection would move * me to before that waiter anyway; but it's relatively cheap to * detect such a conflict immediately, and avoid delaying till * deadlock timeout. * * Special case: if I find I should go in front of some waiter, check to * see if I conflict with already-held locks or the requests before * that waiter. If not, then just grant myself the requested lock * immediately. This is the same as the test for immediate grant in * LockAcquire, except we are only considering the part of the wait * queue before my insertion point. */ if (myHeldLocks != 0) { int aheadRequests = 0; proc = (PROC *) MAKE_PTR(waitQueue->links.next); for (i = 0; i < waitQueue->size; i++) { /* Must he wait for me? */ if (lockctl->conflictTab[proc->waitLockMode] & myHeldLocks) { /* Must I wait for him ? */ if (lockctl->conflictTab[lockmode] & proc->heldLocks) { /* * Yes, so we have a deadlock. Easiest way to clean * up correctly is to call RemoveFromWaitQueue(), but * we can't do that until we are *on* the wait queue. * So, set a flag to check below, and break out of * loop. */ early_deadlock = true; break; } /* I must go before this waiter. Check special case. */ if ((lockctl->conflictTab[lockmode] & aheadRequests) == 0 && LockCheckConflicts(lockMethodTable, lockmode, lock, holder, MyProc, NULL) == STATUS_OK) { /* Skip the wait and just grant myself the lock. */ GrantLock(lock, holder, lockmode); return STATUS_OK; } /* Break out of loop to put myself before him */ break; } /* Nope, so advance to next waiter */ aheadRequests |= (1 << proc->waitLockMode); proc = (PROC *) MAKE_PTR(proc->links.next); } /* * If we fall out of loop normally, proc points to waitQueue head, * so we will insert at tail of queue as desired. */ } else { /* I hold no locks, so I can't push in front of anyone. */ proc = (PROC *) &(waitQueue->links); } /* * Insert self into queue, ahead of the given proc (or at tail of * queue). */ SHMQueueInsertBefore(&(proc->links), &(MyProc->links)); waitQueue->size++; lock->waitMask |= (1 << lockmode); /* Set up wait information in PROC object, too */ MyProc->waitLock = lock; MyProc->waitHolder = holder; MyProc->waitLockMode = lockmode; MyProc->errType = STATUS_OK; /* initialize result for success */ /* * If we detected deadlock, give up without waiting. This must agree * with HandleDeadLock's recovery code, except that we shouldn't * release the semaphore since we haven't tried to lock it yet. */ if (early_deadlock) { RemoveFromWaitQueue(MyProc); MyProc->errType = STATUS_ERROR; return STATUS_ERROR; } /* mark that we are waiting for a lock */ waitingForLock = true; /* * Release the locktable's masterLock. * * NOTE: this may also cause us to exit critical-section state, possibly * allowing a cancel/die interrupt to be accepted. This is OK because * we have recorded the fact that we are waiting for a lock, and so * LockWaitCancel will clean up if cancel/die happens. */ LWLockRelease(masterLock); /* * Set timer so we can wake up after awhile and check for a deadlock. * If a deadlock is detected, the handler releases the process's * semaphore and sets MyProc->errType = STATUS_ERROR, allowing us to * know that we must report failure rather than success. * * By delaying the check until we've waited for a bit, we can avoid * running the rather expensive deadlock-check code in most cases. */ if (!enable_sigalrm_interrupt(DeadlockTimeout)) elog(FATAL, "ProcSleep: Unable to set timer for process wakeup"); /* * If someone wakes us between LWLockRelease and IpcSemaphoreLock, * IpcSemaphoreLock will not block. The wakeup is "saved" by the * semaphore implementation. Note also that if HandleDeadLock is * invoked but does not detect a deadlock, IpcSemaphoreLock() will * continue to wait. There used to be a loop here, but it was useless * code... * * We pass interruptOK = true, which eliminates a window in which * cancel/die interrupts would be held off undesirably. This is a * promise that we don't mind losing control to a cancel/die interrupt * here. We don't, because we have no state-change work to do after * being granted the lock (the grantor did it all). */ IpcSemaphoreLock(MyProc->sem.semId, MyProc->sem.semNum, true); /* * Disable the timer, if it's still running */ if (!disable_sigalrm_interrupt()) elog(FATAL, "ProcSleep: Unable to disable timer for process wakeup"); /* * Now there is nothing for LockWaitCancel to do. */ waitingForLock = false; /* * Re-acquire the locktable's masterLock. */ LWLockAcquire(masterLock, LW_EXCLUSIVE); /* * We don't have to do anything else, because the awaker did all the * necessary update of the lock table and MyProc. */ return MyProc->errType; } /* * ProcWakeup -- wake up a process by releasing its private semaphore. * * Also remove the process from the wait queue and set its links invalid. * RETURN: the next process in the wait queue. * * XXX: presently, this code is only used for the "success" case, and only * works correctly for that case. To clean up in failure case, would need * to twiddle the lock's request counts too --- see RemoveFromWaitQueue. */ PROC * ProcWakeup(PROC *proc, int errType) { PROC *retProc; /* assume that masterLock has been acquired */ /* Proc should be sleeping ... */ if (proc->links.prev == INVALID_OFFSET || proc->links.next == INVALID_OFFSET) return (PROC *) NULL; /* Save next process before we zap the list link */ retProc = (PROC *) MAKE_PTR(proc->links.next); /* Remove process from wait queue */ SHMQueueDelete(&(proc->links)); (proc->waitLock->waitProcs.size)--; /* Clean up process' state and pass it the ok/fail signal */ proc->waitLock = NULL; proc->waitHolder = NULL; proc->errType = errType; /* And awaken it */ IpcSemaphoreUnlock(proc->sem.semId, proc->sem.semNum); return retProc; } /* * ProcLockWakeup -- routine for waking up processes when a lock is * released (or a prior waiter is aborted). Scan all waiters * for lock, waken any that are no longer blocked. */ void ProcLockWakeup(LOCKMETHODTABLE *lockMethodTable, LOCK *lock) { LOCKMETHODCTL *lockctl = lockMethodTable->ctl; PROC_QUEUE *waitQueue = &(lock->waitProcs); int queue_size = waitQueue->size; PROC *proc; int aheadRequests = 0; Assert(queue_size >= 0); if (queue_size == 0) return; proc = (PROC *) MAKE_PTR(waitQueue->links.next); while (queue_size-- > 0) { LOCKMODE lockmode = proc->waitLockMode; /* * Waken if (a) doesn't conflict with requests of earlier waiters, * and (b) doesn't conflict with already-held locks. */ if ((lockctl->conflictTab[lockmode] & aheadRequests) == 0 && LockCheckConflicts(lockMethodTable, lockmode, lock, proc->waitHolder, proc, NULL) == STATUS_OK) { /* OK to waken */ GrantLock(lock, proc->waitHolder, lockmode); proc = ProcWakeup(proc, STATUS_OK); /* * ProcWakeup removes proc from the lock's waiting process * queue and returns the next proc in chain; don't use proc's * next-link, because it's been cleared. */ } else { /* * Cannot wake this guy. Remember his request for later * checks. */ aheadRequests |= (1 << lockmode); proc = (PROC *) MAKE_PTR(proc->links.next); } } Assert(waitQueue->size >= 0); } /* -------------------- * We only get to this routine if we got SIGALRM after DeadlockTimeout * while waiting for a lock to be released by some other process. Look * to see if there's a deadlock; if not, just return and continue waiting. * If we have a real deadlock, remove ourselves from the lock's wait queue * and signal an error to ProcSleep. * -------------------- */ void HandleDeadLock(SIGNAL_ARGS) { int save_errno = errno; /* * Acquire locktable lock. Note that the SIGALRM interrupt had better * not be enabled anywhere that this process itself holds the * locktable lock, else this will wait forever. Also note that * LWLockAcquire creates a critical section, so that this routine * cannot be interrupted by cancel/die interrupts. */ LWLockAcquire(LockMgrLock, LW_EXCLUSIVE); /* * Check to see if we've been awoken by anyone in the interim. * * If we have we can return and resume our transaction -- happy day. * Before we are awoken the process releasing the lock grants it to us * so we know that we don't have to wait anymore. * * We check by looking to see if we've been unlinked from the wait queue. * This is quicker than checking our semaphore's state, since no * kernel call is needed, and it is safe because we hold the locktable * lock. * */ if (MyProc->links.prev == INVALID_OFFSET || MyProc->links.next == INVALID_OFFSET) { LWLockRelease(LockMgrLock); errno = save_errno; return; } #ifdef LOCK_DEBUG if (Debug_deadlocks) DumpAllLocks(); #endif if (!DeadLockCheck(MyProc)) { /* No deadlock, so keep waiting */ LWLockRelease(LockMgrLock); errno = save_errno; return; } /* * Oops. We have a deadlock. * * Get this process out of wait state. */ RemoveFromWaitQueue(MyProc); /* * Set MyProc->errType to STATUS_ERROR so that ProcSleep will report * an error after we return from this signal handler. */ MyProc->errType = STATUS_ERROR; /* * Unlock my semaphore so that the interrupted ProcSleep() call can * finish. */ IpcSemaphoreUnlock(MyProc->sem.semId, MyProc->sem.semNum); /* * We're done here. Transaction abort caused by the error that * ProcSleep will raise will cause any other locks we hold to be * released, thus allowing other processes to wake up; we don't need * to do that here. NOTE: an exception is that releasing locks we hold * doesn't consider the possibility of waiters that were blocked * behind us on the lock we just failed to get, and might now be * wakable because we're not in front of them anymore. However, * RemoveFromWaitQueue took care of waking up any such processes. */ LWLockRelease(LockMgrLock); errno = save_errno; } /* * ProcWaitForSignal - wait for a signal from another backend. * * This can share the semaphore normally used for waiting for locks, * since a backend could never be waiting for a lock and a signal at * the same time. As with locks, it's OK if the signal arrives just * before we actually reach the waiting state. */ void ProcWaitForSignal(void) { waitingForSignal = true; IpcSemaphoreLock(MyProc->sem.semId, MyProc->sem.semNum, true); waitingForSignal = false; } /* * ProcCancelWaitForSignal - clean up an aborted wait for signal * * We need this in case the signal arrived after we aborted waiting, * or if it arrived but we never reached ProcWaitForSignal() at all. * Caller should call this after resetting the signal request status. */ void ProcCancelWaitForSignal(void) { ZeroProcSemaphore(MyProc); waitingForSignal = false; } /* * ProcSendSignal - send a signal to a backend identified by BackendId */ void ProcSendSignal(BackendId procId) { PROC *proc = BackendIdGetProc(procId); if (proc != NULL) IpcSemaphoreUnlock(proc->sem.semId, proc->sem.semNum); } /***************************************************************************** * SIGALRM interrupt support * * Maybe these should be in pqsignal.c? *****************************************************************************/ /* * Enable the SIGALRM interrupt to fire after the specified delay * * Delay is given in milliseconds. Caller should be sure a SIGALRM * signal handler is installed before this is called. * * Returns TRUE if okay, FALSE on failure. */ bool enable_sigalrm_interrupt(int delayms) { #ifndef __BEOS__ struct itimerval timeval, dummy; MemSet(&timeval, 0, sizeof(struct itimerval)); timeval.it_value.tv_sec = delayms / 1000; timeval.it_value.tv_usec = (delayms % 1000) * 1000; if (setitimer(ITIMER_REAL, &timeval, &dummy)) return false; #else /* BeOS doesn't have setitimer, but has set_alarm */ bigtime_t time_interval; time_interval = delayms * 1000; /* usecs */ if (set_alarm(time_interval, B_ONE_SHOT_RELATIVE_ALARM) < 0) return false; #endif return true; } /* * Disable the SIGALRM interrupt, if it has not yet fired * * Returns TRUE if okay, FALSE on failure. */ bool disable_sigalrm_interrupt(void) { #ifndef __BEOS__ struct itimerval timeval, dummy; MemSet(&timeval, 0, sizeof(struct itimerval)); if (setitimer(ITIMER_REAL, &timeval, &dummy)) return false; #else /* BeOS doesn't have setitimer, but has set_alarm */ if (set_alarm(B_INFINITE_TIMEOUT, B_PERIODIC_ALARM) < 0) return false; #endif return true; } /***************************************************************************** * *****************************************************************************/ /* * ProcGetNewSemIdAndNum - * scan the free semaphore bitmap and allocate a single semaphore from * a semaphore set. */ static void ProcGetNewSemIdAndNum(IpcSemaphoreId *semId, int *semNum) { /* use volatile pointer to prevent code rearrangement */ volatile PROC_HDR *procglobal = ProcGlobal; int semMapEntries = procglobal->semMapEntries; volatile SEM_MAP_ENTRY *procSemMap = procglobal->procSemMap; int32 fullmask = (1 << PROC_NSEMS_PER_SET) - 1; int i; SpinLockAcquire(ProcStructLock); for (i = 0; i < semMapEntries; i++) { int mask = 1; int j; if (procSemMap[i].freeSemMap == fullmask) continue; /* this set is fully allocated */ if (procSemMap[i].procSemId < 0) continue; /* this set hasn't been initialized */ for (j = 0; j < PROC_NSEMS_PER_SET; j++) { if ((procSemMap[i].freeSemMap & mask) == 0) { /* A free semaphore found. Mark it as allocated. */ procSemMap[i].freeSemMap |= mask; *semId = procSemMap[i].procSemId; *semNum = j; SpinLockRelease(ProcStructLock); return; } mask <<= 1; } } SpinLockRelease(ProcStructLock); /* * If we reach here, all the semaphores are in use. This is one of * the possible places to detect "too many backends", so give the * standard error message. (Whether we detect it here or in sinval.c * depends on whether MaxBackends is a multiple of * PROC_NSEMS_PER_SET.) */ elog(FATAL, "Sorry, too many clients already"); } /* * ProcFreeSem - * free up our semaphore in the semaphore set. * * Caller is assumed to hold ProcStructLock. */ static void ProcFreeSem(IpcSemaphoreId semId, int semNum) { int32 mask; int i; int semMapEntries = ProcGlobal->semMapEntries; mask = ~(1 << semNum); for (i = 0; i < semMapEntries; i++) { if (ProcGlobal->procSemMap[i].procSemId == semId) { ProcGlobal->procSemMap[i].freeSemMap &= mask; return; } } /* can't elog here!!! */ fprintf(stderr, "ProcFreeSem: no ProcGlobal entry for semId %d\n", semId); } /* * ProcFreeAllSemaphores - * called at shmem_exit time, ie when exiting the postmaster or * destroying shared state for a failed set of backends. * Free up all the semaphores allocated to the lmgrs of the backends. */ static void ProcFreeAllSemaphores(void) { int i; for (i = 0; i < ProcGlobal->semMapEntries; i++) { if (ProcGlobal->procSemMap[i].procSemId >= 0) IpcSemaphoreKill(ProcGlobal->procSemMap[i].procSemId); } }
2
2
2024-11-18T20:50:31.522337+00:00
2021-10-30T12:56:11
ac90614527394932329b87b3bf16cb161baa0e08
{ "blob_id": "ac90614527394932329b87b3bf16cb161baa0e08", "branch_name": "refs/heads/main", "committer_date": "2021-10-30T12:56:11", "content_id": "630fbb3bfefd83adb5c08639e81964e9fe8f9ea0", "detected_licenses": [ "MIT" ], "directory_id": "a41e9d03d36a27e21acc379758e8beb72307e2b9", "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": 352186509, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2213, "license": "MIT", "license_type": "permissive", "path": "/src/main.c", "provenance": "stackv2-0110.json.gz:215961", "repo_name": "hbobenicio/check-invalid-filenames", "revision_date": "2021-10-30T12:56:11", "revision_id": "bbebeab00e47fdce5010308333f769014c9266c2", "snapshot_id": "09fc1a1a37126691b6b097dc634a76de98a38100", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/hbobenicio/check-invalid-filenames/bbebeab00e47fdce5010308333f769014c9266c2/src/main.c", "visit_date": "2023-08-24T11:15:22.560862" }
stackv2
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <assert.h> #define ANSI_FG_RED "31" #define ANSI_FG_GREEN "32" #define ANSI_FG_YELLOW "33" #define ANSI_FG_BRIGHT_RED "91" #define ANSI_FG_BRIGHT_GREEN "92" #define ANSI_FG_BRIGHT_YELLOW "93" #define FILENAME_MAX_SIZE 4098 static void str_pop_last_char(char* const str, size_t* str_len); static void str_print_binary(const char* str, size_t str_len); static void set_color(const char* ansi_color_code); static void set_fg_bright_green(); static void set_fg_bright_red(); static void set_fg_bright_yellow(); int main() { char line[FILENAME_MAX_SIZE] = {0}; while (fgets(line, sizeof(line) - 1, stdin) != NULL) { size_t line_len = strlen(line); str_pop_last_char(line, &line_len); printf("%s: ", line); str_print_binary(line, line_len); } return EXIT_SUCCESS; } static void str_pop_last_char(char* const str, size_t* str_len) { assert(str != NULL); if (*str_len > 0) { str[*str_len - 1] = '\0'; (*str_len)--; } } static void str_print_binary(const char* str, size_t str_len) { int has_non_ascii_chars = 0; int has_non_printable_ascii_chars = 0; for (size_t i = 0; i < str_len; i++) { unsigned char byte = (unsigned char) str[i]; if (isprint(byte)) { set_fg_bright_green(); } else if (isascii(byte)) { has_non_printable_ascii_chars = 1; set_fg_bright_yellow(); } else { has_non_printable_ascii_chars = 1; has_non_ascii_chars = 1; set_fg_bright_red(); } printf(" %02x\x1b[0m", byte); } printf("\x1b[91m"); if (has_non_ascii_chars) { printf(" !ascii"); } if (has_non_printable_ascii_chars) { printf(" !printable_ascii"); } puts("\x1b[0m"); } static void set_color(const char* ansi_color_code) { printf("\x1b[%sm", ansi_color_code); } static void set_fg_bright_green() { set_color(ANSI_FG_BRIGHT_GREEN); } static void set_fg_bright_red() { set_color(ANSI_FG_BRIGHT_RED); } static void set_fg_bright_yellow() { set_color(ANSI_FG_BRIGHT_YELLOW); }
3.109375
3
2024-11-18T20:50:31.612357+00:00
2011-04-27T06:48:00
ca3c7d4907963e14efd232e312a4075369426ef8
{ "blob_id": "ca3c7d4907963e14efd232e312a4075369426ef8", "branch_name": "refs/heads/master", "committer_date": "2011-04-27T06:48:00", "content_id": "d1075d95467d0024f5d5c28fc07966c3d868d7fd", "detected_licenses": [ "MIT-Modern-Variant" ], "directory_id": "ca02e948a5ed8c73a5ccdfeba9f358bee93d3646", "extension": "c", "filename": "execCVTest.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 44470050, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 263, "license": "MIT-Modern-Variant", "license_type": "permissive", "path": "/Project 4/code/test/execCVTest.c", "provenance": "stackv2-0110.json.gz:216090", "repo_name": "fangygy/csci402-nachos-group25", "revision_date": "2011-04-27T06:48:00", "revision_id": "fe3f86d82823c17b7a0af8a52f96f5ce9c38df8c", "snapshot_id": "df2588e46c8542e655c84311704163753b4f0fee", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/fangygy/csci402-nachos-group25/fe3f86d82823c17b7a0af8a52f96f5ce9c38df8c/Project 4/code/test/execCVTest.c", "visit_date": "2021-01-10T12:10:11.794245" }
stackv2
/* execCVTest.c * * Test program to test functionality of Exec syscalls * * * */ #include "syscall.h" int main() { Write("Executing CVTest...\n", sizeof("Executing CVTest...\n"), ConsoleOutput); Exec("../test/CVTest"); /* not reached */ Exit(0); }
2.125
2
2024-11-18T20:50:32.046150+00:00
2020-09-01T12:14:37
21f167f27240b1b453993c6f0331459053000c42
{ "blob_id": "21f167f27240b1b453993c6f0331459053000c42", "branch_name": "refs/heads/master", "committer_date": "2020-09-01T12:14:37", "content_id": "94d8acd85c87a159b6cf50bcfff7e37083f1c09e", "detected_licenses": [ "MIT" ], "directory_id": "af6e13381ff7945e655ca0ca0158f4211c73e3c1", "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": 276635542, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1149, "license": "MIT", "license_type": "permissive", "path": "/utils.h", "provenance": "stackv2-0110.json.gz:216222", "repo_name": "sthaid/proj_tit_for_tat", "revision_date": "2020-09-01T12:14:37", "revision_id": "f7199845f8fd2d8fefcaa5c7ce0d22981cc93a7e", "snapshot_id": "b35f8d44395887cf718874b967b4305a1c42cb47", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/sthaid/proj_tit_for_tat/f7199845f8fd2d8fefcaa5c7ce0d22981cc93a7e/utils.h", "visit_date": "2022-12-08T11:56:57.164761" }
stackv2
// ---------------------------------------- #define INFO(fmt, args...) \ do { \ logmsg("INFO", __func__, fmt, ## args); \ } while (0) #define WARN(fmt, args...) \ do { \ logmsg("WARN", __func__, fmt, ## args); \ } while (0) #define ERROR(fmt, args...) \ do { \ logmsg("ERROR", __func__, fmt, ## args); \ } while (0) #define DEBUG(fmt, args...) \ do { \ if (debug) { \ logmsg("DEBUG", __func__, fmt, ## args); \ } \ } while (0) extern int debug; void logmsg(char * lvl, const char * func, char * fmt, ...) __attribute__ ((format (printf, 3, 4))); // ---------------------------------------- typedef struct { int fd_to_proc; int fd_from_proc; FILE *fp_to_proc; FILE *fp_from_proc; int pid; } proc_hndl_t; proc_hndl_t * proc_run(char *proc, ...); void proc_wait_for_term(proc_hndl_t *h); void proc_printf(proc_hndl_t *h, char *fmt, ...) __attribute__ ((format (printf, 2, 3))); void proc_puts(proc_hndl_t *h, char *s); char * proc_gets(proc_hndl_t *h, char *s, int sizeofs); void proc_kill(proc_hndl_t *h); void proc_abort(proc_hndl_t *h);
2.015625
2
2024-11-18T20:50:32.254374+00:00
2022-02-27T17:47:22
8849166062d72f37491b57754db7c5744d5747d2
{ "blob_id": "8849166062d72f37491b57754db7c5744d5747d2", "branch_name": "refs/heads/master", "committer_date": "2022-02-27T17:47:22", "content_id": "dd47fc678396d7afa31fab938c63406f47f5ee5e", "detected_licenses": [ "ISC" ], "directory_id": "1d895fbf9451d4a38f834acc923cdedad173a88a", "extension": "c", "filename": "libkeccak_cshake_initialise.c", "fork_events_count": 20, "gha_created_at": "2014-11-05T00:04:33", "gha_event_created_at": "2022-02-26T10:50:21", "gha_language": "C", "gha_license_id": "ISC", "github_id": 26194686, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 8395, "license": "ISC", "license_type": "permissive", "path": "/libkeccak_cshake_initialise.c", "provenance": "stackv2-0110.json.gz:216610", "repo_name": "maandree/libkeccak", "revision_date": "2022-02-27T17:47:22", "revision_id": "a989f8a4f1e812a42335046e790efd819922c2f3", "snapshot_id": "346a0f8870d0382605a57f1138d78b0ad2fbcf64", "src_encoding": "UTF-8", "star_events_count": 58, "url": "https://raw.githubusercontent.com/maandree/libkeccak/a989f8a4f1e812a42335046e790efd819922c2f3/libkeccak_cshake_initialise.c", "visit_date": "2022-03-16T09:38:26.134109" }
stackv2
#include <stdio.h> /* See LICENSE file for copyright and license details. */ #include "common.h" /** * Encode a number in big-endian with a size prefix * * @param state The hashing state the feed the number to * @param buf Buffer that is at least `byterate` bytes large * @param byterate The byterate of the hashing algorithm * @param value The number to send to the hashing sponge * @param off Current offset in `buf` * @return New offset in `buf` */ static size_t encode_left(struct libkeccak_state *restrict state, uint8_t *restrict buf, size_t byterate, size_t value, size_t off) { size_t x, n, j, i = off; for (x = value, n = 0; x; x >>= 8) n += 1; if (!n) n = 1; buf[i++] = (uint8_t)n; if (i == byterate) { libkeccak_zerocopy_update(state, buf, byterate); i = 0; } for (j = 0; j < n;) { buf[i++] = (uint8_t)(value >> ((n - ++j) << 3)); if (i == byterate) { libkeccak_zerocopy_update(state, buf, byterate); i = 0; } } return i; } /** * Encode a number in big-endian with a size prefix * * @param state The hashing state the feed the number to * @param buf Buffer that is at least `byterate` bytes large * @param byterate The byterate of the hashing algorithm * @param value The number to send to the hashing sponge * @param off Current offset in `buf` * @param bitoff The number of bits to shift the encoded message left * @return New offset in `buf` */ static size_t encode_left_shifted(struct libkeccak_state *restrict state, uint8_t *restrict buf, size_t byterate, size_t value, size_t off, size_t bitoff) { size_t x, n, j, i = off; uint16_t v; for (x = value, n = 0; x; x >>= 8) n += 1; if (!n) n = 1; v = (uint16_t)((n & 255UL) << bitoff); buf[i++] |= (uint8_t)v; if (i == byterate) { libkeccak_zerocopy_update(state, buf, byterate); i = 0; } buf[i] = (uint8_t)(n >> 8); for (j = 0; j < n;) { v = (uint16_t)(((value >> ((n - ++j) << 3)) & 255UL) << bitoff); buf[i++] |= (uint8_t)v; if (i == byterate) { libkeccak_zerocopy_update(state, buf, byterate); i = 0; } buf[i] = (uint8_t)(v >> 8); } return i; } /** * Feed text to the sponge * * @param state The hashing state tofeed * @param buf Buffer that is at least `byterate` bytes large * @param text Text to feed the sponge * @param bytes The number of whole bytes in `text` * @param bits The number of bits at the end of `text` * that does not make up a whole byte * @param suffix Bit-string (encoded with ASCII 0/1 digits) * of additional bytes after `text` * @param off The current byte offset in `buf` * @param byterate The byterate of the hashing algorithm * @param bitoffp Output parameter for the non-whole * byte bit-offset (current must be 0) * @return The new byte offset in `buf` */ static size_t feed_text(struct libkeccak_state *restrict state, uint8_t *restrict buf, const uint8_t *restrict text, size_t bytes, size_t bits, const char *restrict suffix, size_t off, size_t byterate, size_t *restrict bitoffp) { size_t n, bitoff; if (off) { n = bytes < byterate - off ? bytes : byterate - off; memcpy(&buf[off], text, n); off += n; if (off == byterate) { libkeccak_zerocopy_update(state, buf, byterate); off = 0; } text = &text[n]; bytes -= n; } if (bytes) { n = bytes; n -= bytes %= byterate; libkeccak_zerocopy_update(state, text, n); text = &text[n]; } memcpy(&buf[off], text, bytes + !!bits); off += bytes; bitoff = bits; if (!bitoff) buf[off] = 0; for (; *suffix; suffix++) { if (*suffix == '1') buf[off] |= (uint8_t)(1 << bitoff); if (++bitoff == 8) { if (++off == byterate) { libkeccak_zerocopy_update(state, buf, byterate); off = 0; } bitoff = 0; buf[off] = 0; } } *bitoffp = bitoff; return off; } /** * Feed text to the sponge * * @param state The hashing state tofeed * @param buf Buffer that is at least `byterate` bytes large * @param text Text to feed the sponge * @param bytes The number of whole bytes in `text` * @param bits The number of bits at the end of `text` * that does not make up a whole byte * @param suffix Bit-string (encoded with ASCII 0/1 digits) * of additional bytes after `text` * @param off The current byte offset in `buf` * @param byterate The byterate of the hashing algorithm * @param bitoffp Pointer to the non-whole byte bit-offset, * shall be the current (non-zero) bit-offset * upon entry and will be set to the new * bit-offset on return * @return The new byte offset in `buf` */ static size_t feed_text_shifted(struct libkeccak_state *restrict state, uint8_t *restrict buf, const uint8_t *restrict text, size_t bytes, size_t bits, const char *restrict suffix, size_t off, size_t byterate, size_t *restrict bitoffp) { size_t i, bitoff = *bitoffp; uint16_t v; for (i = 0; i < bytes; i++) { v = (uint16_t)((uint16_t)text[i] << bitoff); buf[off] |= (uint8_t)v; if (++off == byterate) { libkeccak_zerocopy_update(state, buf, byterate); off = 0; } buf[off] = (uint8_t)(v >> 8); } if (bits) { v = (uint16_t)((uint16_t)text[bytes] << bitoff); buf[off] |= (uint8_t)v; bitoff += bits; if (bitoff >= 8) { if (++off == byterate) { libkeccak_zerocopy_update(state, buf, byterate); off = 0; } bitoff &= 7; buf[off] = (uint8_t)(v >> 8); } } if (!bitoff) buf[off] = 0; for (; *suffix; suffix++) { if (*suffix == '1') buf[off] |= (uint8_t)(1 << bitoff); if (++bitoff == 8) { if (++off == byterate) { libkeccak_zerocopy_update(state, buf, byterate); off = 0; } bitoff = 0; buf[off] = 0; } } *bitoffp = bitoff; return off; } /** * Create and absorb the initialisation blocks for cSHAKE hashing * * @param state The hashing state * @param n_text Function name-string * @param n_len Byte-length of `n_text` (only whole byte) * @param n_bits Bit-length of `n_text`, minus `n_len * 8` * @param n_suffix Bit-string, represented by a NUL-terminated * string of '1':s and '0's:, making up the part * after `n_text` of the function-name bit-string; * `NULL` is treated as the empty string * @param s_text Customisation-string * @param s_len Byte-length of `s_text` (only whole byte) * @param s_bits Bit-length of `s_text`, minus `s_len * 8` * @param s_suffix Bit-string, represented by a NUL-terminated * string of '1':s and '0's:, making up the part * after `s_text` of the customisation bit-string; * `NULL` is treated as the empty string */ void libkeccak_cshake_initialise(struct libkeccak_state *restrict state, const void *n_text, size_t n_len, size_t n_bits, const char *n_suffix, const void *s_text, size_t s_len, size_t s_bits, const char *s_suffix) { size_t off = 0, bitoff, byterate = (size_t)state->r >> 3; if (!n_suffix) n_suffix = ""; if (!s_suffix) s_suffix = ""; if (!n_len && !s_len && !n_bits && !s_bits && !*n_suffix && !*s_suffix) return; n_len += n_bits >> 3; s_len += s_bits >> 3; n_bits &= 7; s_bits &= 7; off = encode_left(state, state->M, byterate, byterate, off); off = encode_left(state, state->M, byterate, (n_len << 3) + n_bits + strlen(n_suffix), off); off = feed_text(state, state->M, n_text, n_len, n_bits, n_suffix, off, byterate, &bitoff); if (!bitoff) { off = encode_left(state, state->M, byterate, (s_len << 3) + s_bits + strlen(s_suffix), off); off = feed_text(state, state->M, s_text, s_len, s_bits, s_suffix, off, byterate, &bitoff); } else { off = encode_left_shifted(state, state->M, byterate, (s_len << 3) + s_bits + strlen(s_suffix), off, bitoff); off = feed_text_shifted(state, state->M, s_text, s_len, s_bits, s_suffix, off, byterate, &bitoff); } if (bitoff) off++; if (off) { memset(&state->M[off], 0, byterate - off); libkeccak_zerocopy_update(state, state->M, byterate); } }
2.90625
3
2024-11-18T20:50:32.627730+00:00
2017-10-31T17:46:50
8b21f456e0dc1dd3436a04efcbdfc18ff79dddc5
{ "blob_id": "8b21f456e0dc1dd3436a04efcbdfc18ff79dddc5", "branch_name": "refs/heads/master", "committer_date": "2017-10-31T17:46:50", "content_id": "76be49d1b7adae7e5e8e16bec6297bbe6d2c2478", "detected_licenses": [ "MIT" ], "directory_id": "90e2fefd960b5d57f1f4e80108bad69f96cff8fd", "extension": "c", "filename": "ants_run_1.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 109031827, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2440, "license": "MIT", "license_type": "permissive", "path": "/srcs/ants_run_1.c", "provenance": "stackv2-0110.json.gz:216870", "repo_name": "bhivert/lem-in", "revision_date": "2017-10-31T17:46:50", "revision_id": "2fcc1717c5590cda988b94c966303c1dd669dd52", "snapshot_id": "afcd657dd967682b527bdd502b434cddab38953c", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/bhivert/lem-in/2fcc1717c5590cda988b94c966303c1dd669dd52/srcs/ants_run_1.c", "visit_date": "2021-07-24T04:56:09.282422" }
stackv2
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ants_run_1.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: bhivert <bhivert@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/01/23 11:14:25 by bhivert #+# #+# */ /* Updated: 2017/01/24 10:54:30 by bhivert ### ########.fr */ /* */ /* ************************************************************************** */ #include "lem_in.h" #include "ft_printf.h" void fill_active_ways(t_lemin *e, t_container *active_ways, \ size_t wayset) { size_t nways; size_t x; nways = ft_size(e->ways); x = (size_t)-1; ft_push_back(active_ways, &wayset); while (++x < nways) { if (e->stable_mat[wayset][x] != 0) ft_push_back(active_ways, &x); } } t_run_room *new_run_room(t_lemin *e, size_t room_id) { t_run_room *new; char *room_name; t_room *room; if (!(new = (t_run_room *)malloc(sizeof(t_run_room)))) badalloc(__FILE__, __LINE__); room_name = *(char **)ft_at_index(e->rooms_ids, room_id); room = (t_room *)ft_at_key(e->rooms, room_name); *new = (t_run_room){NULL, room, (size_t)-1}; return (new); } void ants_run_loop_1(t_run_room *tmp) { if (tmp->next->ant_id != (size_t)-1) { ft_printf("L%lld-%s ", tmp->next->ant_id, tmp->room->name); tmp->ant_id = tmp->next->ant_id; tmp->next->ant_id = (size_t)-1; } } void ants_run_loop_0(t_lemin *e, t_run_room *tmp, \ t_int *last_id, size_t i) { if (tmp == e->endr.next_tab[i] && !tmp->next && ++e->endr.arrived) { if (*last_id < e->ants) ft_printf("L%lld-%s ", ++(*last_id), e->end->name); } else if (tmp == e->endr.next_tab[i]) { if (tmp->next->ant_id != (size_t)-1 && ++e->endr.arrived) { ft_printf("L%lld-%s ", tmp->next->ant_id, e->end->name); tmp->next->ant_id = (size_t)-1; } } else if (!tmp->next) { if (*last_id < e->ants) { ft_printf("L%lld-%s ", ++(*last_id), tmp->room->name); tmp->ant_id = *last_id; } } else ants_run_loop_1(tmp); }
2.484375
2
2024-11-18T20:50:32.881016+00:00
2018-09-27T08:30:24
3b8c9624a39736b099dbfaeb02ea62f3bc3d4e0b
{ "blob_id": "3b8c9624a39736b099dbfaeb02ea62f3bc3d4e0b", "branch_name": "refs/heads/master", "committer_date": "2018-09-27T08:30:24", "content_id": "7d4390ef653d63c2f833c560cedb3e7e10b61c60", "detected_licenses": [ "BSD-3-Clause", "BSD-2-Clause" ], "directory_id": "cfee92bf74c4976404b0487a6345a6a2e3675e60", "extension": "c", "filename": "phonebook_opt.c", "fork_events_count": 0, "gha_created_at": "2018-09-23T05:28:35", "gha_event_created_at": "2018-09-23T05:28:36", "gha_language": null, "gha_license_id": null, "github_id": 149950920, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5888, "license": "BSD-3-Clause,BSD-2-Clause", "license_type": "permissive", "path": "/phonebook_opt.c", "provenance": "stackv2-0110.json.gz:217000", "repo_name": "ultype/phonebook", "revision_date": "2018-09-27T08:30:24", "revision_id": "3cf347d8adfd5ff46731d08173f954821fe5466d", "snapshot_id": "d6a923b3dae1e5e8e718d27ea85e54c83ab4c66f", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/ultype/phonebook/3cf347d8adfd5ff46731d08173f954821fe5466d/phonebook_opt.c", "visit_date": "2020-03-29T13:18:15.245279" }
stackv2
#include "phonebook_opt.h" /* TODO: FILL YOUR OWN IMPLEMENTATION HERE! */ Node *AVLHead; entry* findName(char lastName[], entry *pHead) { int i; int key=getHashKey(lastName); Node *keynode=findNode(AVLHead,key); if(keynode==NULL) { return NULL; } else { entry* currEntry=keynode->entryPtr; for(i=0; i<keynode->number; i++) { if (strcasecmp(lastName, currEntry->lastName) == 0) return currEntry; currEntry = currEntry->pNext; } } return NULL; } entry* append(char lastName[], entry *headEntry) { /* note the input will never be NULL but e->pNext==NULL first this func input e pointed to undefine lastName head entry always return head */ if(lastName==NULL) { return NULL; } int key=getHashKey(lastName); entry* nentry=newEntry(lastName); if(headEntry->pNext==NULL) { //first insert headEntry->pNext=nentry; nentry->pNext=nentry; nentry->pPrev=nentry; AVLHead=newNode(key,nentry); //this will cause segment fault } else { AVLHead=insertNode(AVLHead,key,nentry,NULL,MID); } return headEntry; } //phoonbook func entry* newEntry(char *lastName) { entry* new=(entry*)malloc(sizeof(entry)); strcpy(new->lastName, lastName); new->pNext=NULL; new->pPrev=NULL; return new; } int getHashKey(char lastName[]) { int key=0; int i; for(i=0; i<6; i++) { if(lastName[i]=='\0') break; key=(key*26)+tolower(lastName[i])-(int)'a'+1; } return key; } //AVL func int getHeight(Node* node) { if(node==NULL) return 0; return node->height; } int max(int a, int b) { return (a > b)? a : b; } Node* newNode(int key,entry* newPtr) { Node* new=(Node*)malloc(sizeof(Node)); if(new!=NULL) { new->key=key; new->number=1; new->left=NULL; new->right=NULL; new->entryPtr=newPtr; new->height=0; } return new; } Node* rightRotate(Node *y) { Node *x = y->left; Node *T2 = x->right; // Perform rotation x->right = y; y->left = T2; // Update heights y->height = max(getHeight(y->left), getHeight(y->right))+1; x->height = max(getHeight(x->left), getHeight(x->right))+1; // Return new root return x; } // A utility function to left rotate subtree rooted with x // See the diagram given above. Node *leftRotate(Node *x) { Node *y = x->right; Node *T2 = y->left; // Perform rotation y->left = x; x->right = T2; // Update heights x->height = max(getHeight(x->left), getHeight(x->right))+1; y->height = max(getHeight(y->left), getHeight(y->right))+1; // Return new root return y; } // Get Balance factor of node N int getBalance(Node *N) { if (N == NULL) return 0; return getHeight(N->left) - getHeight(N->right); } // Recursive function to insert a key in the subtree rooted // with node and returns the new root of the subtree. Node* insertNode(Node* node, int key,entry* newPtr,entry* targetPtr,Direction dir) { /* 1. Perform the normal BST insertion */ if (node == NULL) { if(dir==LEFT) { insertEntryPrev(targetPtr,newPtr); } else if(dir==RIGHT) { insertEntryNext(targetPtr,newPtr); } return newNode(key,newPtr); } if (key < node->key) { node->left = insertNode(node->left , key, newPtr, node->entryPtr,LEFT); } else if (key > node->key) { node->right = insertNode(node->right, key, newPtr, node->entryPtr,RIGHT); } else { // Equal keys are not allowed in BST insertEntryNext(node->entryPtr,newPtr); node->number++; return node; } /* 2. Update height of this ancestor node */ node->height = 1 + max(getHeight(node->left), getHeight(node->right)); /* 3. Get the balance factor of this ancestor node to check whether this node became unbalanced */ int balance = getBalance(node); // If this node becomes unbalanced, then // there are 4 cases // Left Left Case if (balance > 1 && key < node->left->key) return rightRotate(node); // Right Right Case if (balance < -1 && key > node->right->key) return leftRotate(node); // Left Right Case if (balance > 1 && key > node->left->key) { node->left = leftRotate(node->left); return rightRotate(node); } // Right Left Case if (balance < -1 && key < node->right->key) { node->right = rightRotate(node->right); return leftRotate(node); } /* return the (unchanged) node pointer */ return node; } Node* findNode(Node* keynode,int key) { if(keynode==NULL) return NULL; if(key>keynode->key) { return findNode(keynode->right,key); } else if(key<keynode->key) { return findNode(keynode->left,key); } return keynode; } void insertEntryPrev(entry *targetPtr,entry *newPtr) { if(targetPtr==NULL || newPtr==NULL) return; entry *prevTemp=targetPtr->pPrev; newPtr->pPrev=prevTemp; newPtr->pNext=targetPtr; targetPtr->pPrev=newPtr; prevTemp->pNext=newPtr; } void insertEntryNext(entry *targetPtr,entry *newPtr) { if(targetPtr==NULL || newPtr==NULL) return; entry *nextTemp=targetPtr->pNext; newPtr->pNext=nextTemp; newPtr->pPrev=targetPtr; targetPtr->pNext=newPtr; nextTemp->pPrev=newPtr; } // The function also prints height of every node void preOrder(Node *root) { if(root != NULL) { printf("%d ", root->key); preOrder(root->left); preOrder(root->right); } } void inOrder(Node *root) { if(root != NULL) { inOrder(root->left); printf("%d %d\n", root->key,root->number); inOrder(root->right); } }
3.21875
3
2024-11-18T20:50:33.439207+00:00
2020-09-20T06:13:26
d18aba6086f03fbec222b0c830b4c5823ffc0d3a
{ "blob_id": "d18aba6086f03fbec222b0c830b4c5823ffc0d3a", "branch_name": "refs/heads/master", "committer_date": "2020-09-20T06:13:26", "content_id": "b401ab39668c84f4aa8175c50ede5cadc0836881", "detected_licenses": [ "Unlicense" ], "directory_id": "eeb257751eebe0ac01101f1686a0b8b1611f5ce3", "extension": "h", "filename": "Cargo.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 46903989, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3166, "license": "Unlicense", "license_type": "permissive", "path": "/Bard-v0.2/Libraries/Cargo/C/Cargo.h", "provenance": "stackv2-0110.json.gz:217390", "repo_name": "AbePralle/Archive", "revision_date": "2020-09-20T06:13:26", "revision_id": "c5a4f214276d433c5c1f30fef830aa213018a369", "snapshot_id": "b03db34cc0676d979a660df2eb5aabd719308809", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/AbePralle/Archive/c5a4f214276d433c5c1f30fef830aa213018a369/Bard-v0.2/Libraries/Cargo/C/Cargo.h", "visit_date": "2021-01-11T11:08:18.442758" }
stackv2
//============================================================================= // Cargo.h // // Created July 30, 2014 by Abe Pralle //============================================================================= #pragma once #include <stdint.h> #ifdef __cplusplus extern "C" { #endif //============================================================================= // CargoList //============================================================================= typedef struct CargoList { void* data; int count; int capacity; int element_size; } CargoList; #define CargoList_create( element_type ) \ CargoList_create_with_element_size( sizeof(element_type), 10 ) #define CargoList_init( list, element_type ) \ CargoList_init_with_element_size( list, sizeof(element_type), 10 ) #define CargoList_add( list, type, value ) \ *((type*)(CargoList_new_last_element_pointer(list))) = (type) value #define CargoList_get( list, type, index ) \ ((type*)(list->data))[index] CargoList* CargoList_create_with_element_size( int element_size, int initial_capacity ); CargoList* CargoList_init_with_element_size( CargoList* list, int element_size, int initial_capacity ); CargoList* CargoList_destroy( CargoList* list ); CargoList* CargoList_retire( CargoList* list ); void CargoList_discard_at( CargoList* list, int index ); CargoList* CargoList_ensure_capacity( CargoList* list, int minimum_capacity ); void* CargoList_new_last_element_pointer( CargoList* list ); void* CargoList_pointer_at( CargoList* list, int index ); CargoList* CargoList_reserve( CargoList* list, int additional_spots ); //============================================================================= // CargoTable //============================================================================= typedef int (*CargoTableMatchFn)( void* a, void* b ); typedef void (*CargoTableDeleteFn)( void* value ); typedef struct CargoTableEntry { void* value; int hash_code; } CargoTableEntry; typedef struct CargoTable { CargoList** bins; int count; int bin_count; int bin_mask; int element_size; CargoTableMatchFn match_fn; CargoTableDeleteFn delete_fn; } CargoTable; #define CargoTable_create( type, bin_count, match_fn, delete_fn ) \ CargoTable_create_with_element_size( sizeof(type), bin_count, match_fn, delete_fn ) CargoTable* CargoTable_create_with_element_size( int element_size, int bin_count, CargoTableMatchFn match_fn, CargoTableDeleteFn delete_fn ); CargoTable* CargoTable_init_with_element_size( CargoTable* table, int element_size, int bin_count, CargoTableMatchFn match_fn, CargoTableDeleteFn delete_fn ); CargoTable* CargoTable_destroy( CargoTable* table ); CargoTable* CargoTable_retire( CargoTable* table ); //============================================================================= // Cargo //============================================================================= typedef struct Cargo { } Cargo; Cargo* Cargo_create(); Cargo* Cargo_destroy( Cargo* cargo ); #ifdef __cplusplus }; // end extern "C" #endif /* { name:"on_pointer_press" x:32.2 y:252.2 } */
2.140625
2
2024-11-18T20:50:33.732273+00:00
2023-02-28T15:06:32
820bacd991b44ac30447793bd8dd9325ada6bdb7
{ "blob_id": "820bacd991b44ac30447793bd8dd9325ada6bdb7", "branch_name": "refs/heads/master", "committer_date": "2023-02-28T15:06:32", "content_id": "a2c3dbc847dfab386f9bc814e99a959bedbdc7cc", "detected_licenses": [ "MIT", "Apache-2.0" ], "directory_id": "120c112ce63daaa939438e0b6f9390634af0f7ae", "extension": "c", "filename": "xrand.c", "fork_events_count": 0, "gha_created_at": "2020-05-04T21:00:02", "gha_event_created_at": "2020-05-04T21:00:03", "gha_language": null, "gha_license_id": "Apache-2.0", "github_id": 261294523, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 904, "license": "MIT,Apache-2.0", "license_type": "permissive", "path": "/lib/util/lib/xrand.c", "provenance": "stackv2-0110.json.gz:217779", "repo_name": "davidboles/hse", "revision_date": "2023-02-28T15:06:32", "revision_id": "ca2bccd60e29a74f2e8b587a9b8d4702c360865c", "snapshot_id": "ce80e0c43bcd5cc66b11f7045401fd61f976f0b4", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/davidboles/hse/ca2bccd60e29a74f2e8b587a9b8d4702c360865c/lib/util/lib/xrand.c", "visit_date": "2023-03-08T02:18:21.994189" }
stackv2
/* SPDX-License-Identifier: Apache-2.0 OR MIT * * SPDX-FileCopyrightText: Copyright 2020 Micron Technology, Inc. */ #include <stdint.h> #include <unistd.h> #include <hse/util/arch.h> #include <hse/util/xrand.h> thread_local struct xrand xrand_tls; void xrand_init(struct xrand *xr, uint64_t seed) { if (!seed) { while (1) { seed = (seed << 16) | ((get_cycles() >> 1) & 0xffffu); if (seed >> 48) break; usleep(seed % 127); /* leverage scheduling entropy */ } } xoroshiro128plus_init(xr->xr_state, seed); } uint64_t xrand_range64(struct xrand *xr, uint64_t lo, uint64_t hi) { /* compute rv: 0 <= rv < 1 */ double rand_max = (double)((uint64_t)-1); double rv = (double)xrand64(xr) / (rand_max + 1.0); /* scale rv to the desired range */ return (uint64_t)((double)lo + (double)(hi - lo) * rv); }
2.46875
2
2024-11-18T20:50:33.814261+00:00
2018-04-14T18:20:11
4c7044a799a14781652df4f01fcc5a11841ea5b5
{ "blob_id": "4c7044a799a14781652df4f01fcc5a11841ea5b5", "branch_name": "refs/heads/master", "committer_date": "2018-04-14T18:20:11", "content_id": "feafc75b36b4d2f55ded0c0b6a38dd33f6142097", "detected_licenses": [ "MIT" ], "directory_id": "21ef87b55567337393020c4f58de3b39abd4ccea", "extension": "c", "filename": "CoreSPI.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 126853742, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 6350, "license": "MIT", "license_type": "permissive", "path": "/STM32F103ZET6/STD/common/Func/CoreFunc/CoreSPI.c", "provenance": "stackv2-0110.json.gz:217908", "repo_name": "dinkdeng/STM32_IAR", "revision_date": "2018-04-14T18:20:11", "revision_id": "8d9e8f780b78f6e7f9088e2b9cb7f8edd214020d", "snapshot_id": "ff8a29967a5e2c9b41c455948add377b86a773e5", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/dinkdeng/STM32_IAR/8d9e8f780b78f6e7f9088e2b9cb7f8edd214020d/STM32F103ZET6/STD/common/Func/CoreFunc/CoreSPI.c", "visit_date": "2021-04-15T03:47:51.854800" }
stackv2
#include "CoreSPI.h" #include "SystemUtil.h" /**SPI1初始化 */ void CoreSPI1Init(uint16_t cpol,uint16_t cpha,uint16_t speed) { GPIO_InitTypeDef GPIO_InitStructure; SPI_InitTypeDef SPI_InitStructure; //PORTB,SPI1时钟使能 RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_SPI1, ENABLE); GPIO_InitStructure.GPIO_Pin = GPIO_Pin_5 | GPIO_Pin_6 | GPIO_Pin_7; //PA5.6.7复用推挽 GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_Init(GPIOA, &GPIO_InitStructure); //PA5.6.7上拉 GPIO_SetBits(GPIOA, GPIO_Pin_5 | GPIO_Pin_6 | GPIO_Pin_7); //设置SPI单向或者双向的数据模式:SPI设置为双线双向全双工 SPI_InitStructure.SPI_Direction = SPI_Direction_2Lines_FullDuplex; //设置SPI工作模式:设置为主SPI SPI_InitStructure.SPI_Mode = SPI_Mode_Master; //设置SPI的数据大小:SPI发送接收8位帧结构 SPI_InitStructure.SPI_DataSize = SPI_DataSize_8b; //选择了串行时钟的稳态:时钟悬空高 SPI_InitStructure.SPI_CPOL = cpol; //数据捕获于第二个时钟沿 SPI_InitStructure.SPI_CPHA = cpha; //NSS信号由硬件(NSS管脚)还是软件(使用SSI位)管理:内部NSS信号有SSI位控制 SPI_InitStructure.SPI_NSS = SPI_NSS_Soft; //定义波特率预分频的值:波特率预分频值为16 SPI_InitStructure.SPI_BaudRatePrescaler = speed; //指定数据传输从MSB位还是LSB位开始:数据传输从MSB位开始 SPI_InitStructure.SPI_FirstBit = SPI_FirstBit_MSB; //CRC值计算的多项式 SPI_InitStructure.SPI_CRCPolynomial = 7; //根据SPI_InitStruct中指定的参数初始化外设SPIx寄存器 SPI_Init(SPI1, &SPI_InitStructure); //使能SPI外设 SPI_Cmd(SPI1, ENABLE); } /**SPI1读写 */ uint8_t CoreSPI1WriteRead(uint8_t writeDat) { uint32_t retry = 0; //检查指定的SPI标志位设置与否:发送缓存空标志位 while (SPI_I2S_GetFlagStatus(SPI1, SPI_I2S_FLAG_TXE) == RESET) { retry++; if (retry > CORE_SPI_WAIT_COUNT_MAX) return 0x00; } //通过外设SPIx发送一个数据 SPI_I2S_SendData(SPI1, writeDat); retry = 0; //检查指定的SPI标志位设置与否:接受缓存非空标志位 while (SPI_I2S_GetFlagStatus(SPI1, SPI_I2S_FLAG_RXNE) == RESET) { retry++; if (retry > CORE_SPI_WAIT_COUNT_MAX) return 0x00; } return SPI_I2S_ReceiveData(SPI1); } /**SPI1设置速度 */ void CoreSPI1SetSpeed(uint16_t speed) { SPI1->CR1 &= 0XFFC7; SPI1->CR1 |= speed; SPI_Cmd(SPI1, ENABLE); } /**SPI1设置CPOL CPHA特性 */ void CoreSPI1SetCp(uint16_t cpol,uint16_t cpha) { /**计算设置值 */ uint16_t setValue = 0; setValue = (cpol|cpha); setValue &= 0x0003; /**清空设置值 */ SPI1->CR1 &= ~(0x0003); SPI1->CR1 |= setValue; /**重新使能 */ SPI_Cmd(SPI1, ENABLE); } /**SPI2初始化 */ void CoreSPI2Init(uint16_t cpol,uint16_t cpha,uint16_t speed) { GPIO_InitTypeDef GPIO_InitStructure; SPI_InitTypeDef SPI_InitStructure; //PORTB时钟使能 RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE); //SPI2时钟使能 RCC_APB1PeriphClockCmd(RCC_APB1Periph_SPI2, ENABLE); GPIO_InitStructure.GPIO_Pin = GPIO_Pin_13 | GPIO_Pin_14 | GPIO_Pin_15; //PB13/14/15复用推挽输出 GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; //初始化GPIOB GPIO_Init(GPIOB, &GPIO_InitStructure); //PB13/14/15上拉 GPIO_SetBits(GPIOB, GPIO_Pin_13 | GPIO_Pin_14 | GPIO_Pin_15); SPI_Cmd(SPI2,DISABLE); //设置SPI单向或者双向的数据模式:SPI设置为双线双向全双工 SPI_InitStructure.SPI_Direction = SPI_Direction_2Lines_FullDuplex; //设置SPI工作模式:设置为主SPI SPI_InitStructure.SPI_Mode = SPI_Mode_Master; //设置SPI的数据大小:SPI发送接收8位帧结构 SPI_InitStructure.SPI_DataSize = SPI_DataSize_8b; //串行同步时钟的空闲状态为高电平 SPI_InitStructure.SPI_CPOL = cpol; //串行同步时钟的第二个跳变沿(上升或下降)数据被采样 SPI_InitStructure.SPI_CPHA = cpha; //NSS信号由硬件(NSS管脚)还是软件(使用SSI位)管理:内部NSS信号有SSI位控制 SPI_InitStructure.SPI_NSS = SPI_NSS_Soft; //定义波特率预分频的值:波特率预分频值为256 SPI_InitStructure.SPI_BaudRatePrescaler = speed; //指定数据传输从MSB位还是LSB位开始:数据传输从MSB位开始 SPI_InitStructure.SPI_FirstBit = SPI_FirstBit_MSB; //CRC值计算的多项式 SPI_InitStructure.SPI_CRCPolynomial = 7; //根据SPI_InitStruct中指定的参数初始化外设SPIx寄存器 SPI_Init(SPI2, &SPI_InitStructure); //使能SPI外设 SPI_Cmd(SPI2, ENABLE); //启动传输 CoreSPI2WriteRead(0xff); } /**SPI2读写 */ uint8_t CoreSPI2WriteRead(uint8_t writeDat) { uint16_t retry = 0; //检查指定的SPI标志位设置与否:发送缓存空标志位 while (SPI_I2S_GetFlagStatus(SPI2, SPI_I2S_FLAG_TXE) == RESET) { retry++; /**超时一律返回0 */ if (retry > CORE_SPI_WAIT_COUNT_MAX) return 0x00; } //通过外设SPIx发送一个数据 SPI_I2S_SendData(SPI2, writeDat); retry = 0; //检查指定的SPI标志位设置与否:接受缓存非空标志位 while (SPI_I2S_GetFlagStatus(SPI2, SPI_I2S_FLAG_RXNE) == RESET) { retry++; /**超时一律返回0 */ if (retry > CORE_SPI_WAIT_COUNT_MAX) return 0x00; } return SPI_I2S_ReceiveData(SPI2); } /**SPI2设置速度 */ void CoreSPI2SetSpeed(uint16_t speed) { SPI_Cmd(SPI2, DISABLE); //先停止SPI传输 SPI2->CR1 &= 0XFFC7; //设置API速度 SPI2->CR1 |= speed; //使能SPI外设 SPI_Cmd(SPI2, ENABLE); } /**SPI2设置CPOL CPHA特性 */ void CoreSPI2SetCp(uint16_t cpol,uint16_t cpha) { /**计算设置值 */ uint16_t setValue = 0; setValue = (cpol|cpha); setValue &= 0x0003; SPI_Cmd(SPI2, DISABLE); /**清空设置值 */ SPI2->CR1 &= ~(0x0003); SPI2->CR1 |= setValue; //使能SPI外设 SPI_Cmd(SPI2, ENABLE); }
2.796875
3
2024-11-18T20:50:35.021087+00:00
2018-09-13T04:33:49
32a3ba6a7775d0b3b61441e09703640f91cc2df2
{ "blob_id": "32a3ba6a7775d0b3b61441e09703640f91cc2df2", "branch_name": "refs/heads/master", "committer_date": "2018-09-13T04:33:49", "content_id": "c935840d69eba0e1f64ea2618b98452ffef744a0", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "74a9a0850bd53d4f942cd4f731111859b0da9140", "extension": "c", "filename": "deadbeef.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 148581019, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 7297, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/core/deadbeef.c", "provenance": "stackv2-0110.json.gz:218687", "repo_name": "deadcafe/dpdk-tools", "revision_date": "2018-09-13T04:33:49", "revision_id": "7d8ac06d2a3aec5d2a70006bf602d6bcbc334764", "snapshot_id": "6fd2d976a64a25648caa8e7076cf28fe7a54914f", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/deadcafe/dpdk-tools/7d8ac06d2a3aec5d2a70006bf602d6bcbc334764/core/deadbeef.c", "visit_date": "2020-03-28T15:19:43.179040" }
stackv2
#include <unistd.h> #include <stdio.h> #include <errno.h> #include <stdlib.h> #include <getopt.h> #include <string.h> #include <rte_eal.h> #include <rte_debug.h> #include <rte_errno.h> #include <rte_lcore.h> #include <rte_memzone.h> #include <rte_atomic.h> #include <rte_pause.h> #include "beef_cmdline.h" static rte_usage_hook_t usage_hook; struct thread_s { unsigned thread_id; /* zero is master */ unsigned lcore_id; unsigned nb_threads; volatile enum rte_lcore_state_t state; } __rte_cache_aligned; struct thread_table_s { struct thread_s threads[RTE_MAX_LCORE]; }; #define THREAD_TABLE "ThreadTable" #define INVALID_ID ((unsigned) -1) static struct thread_table_s * Thread_Table_p; static struct thread_table_s * create_thread_table(unsigned nb_threads) { if (!Thread_Table_p) { const struct rte_memzone *mz; mz = rte_memzone_reserve(THREAD_TABLE, sizeof(*Thread_Table_p), rte_socket_id(), RTE_MEMZONE_SIZE_HINT_ONLY | RTE_MEMZONE_2MB | RTE_MEMZONE_1GB); if (mz) { struct thread_table_s *tbl = mz->addr; for (unsigned i = 0; i < RTE_DIM(tbl->threads); i++) { tbl->threads[i].thread_id = INVALID_ID; tbl->threads[i].lcore_id = INVALID_ID; tbl->threads[i].nb_threads = nb_threads; } Thread_Table_p = tbl; } } return Thread_Table_p; } static void setup_thread_table(struct thread_table_s *tbl, unsigned thread_id, unsigned lcore_id) { tbl->threads[thread_id].thread_id = thread_id; tbl->threads[thread_id].lcore_id = lcore_id; tbl->threads[thread_id].state = WAIT; } static inline void set_state(struct thread_s *th, enum rte_lcore_state_t state) { th->state = state; rte_wmb(); fprintf(stderr, "thread:%u state:%d\n", th->thread_id, state); } static inline void state_slaves(struct thread_table_s *tbl, enum rte_lcore_state_t state) { unsigned nb_threads = tbl->threads[0].nb_threads; for (unsigned i = 1; i < nb_threads; i++) set_state(&tbl->threads[i], state); } static inline void stop_slaves(struct thread_table_s *tbl) { state_slaves(tbl, WAIT); } static inline void start_slaves(struct thread_table_s *tbl) { state_slaves(tbl, RUNNING); } static inline void finish_slaves(struct thread_table_s *tbl) { state_slaves(tbl, FINISHED); } static inline enum rte_lcore_state_t read_state(const struct thread_s *th) { enum rte_lcore_state_t state = th->state; rte_rmb(); return state; } static inline int is_eq_state(const struct thread_s *th, enum rte_lcore_state_t state) { return read_state(th) == state; } static inline int is_runnging(const struct thread_s *th) { return is_eq_state(th, RUNNING); } static inline int is_waiting(const struct thread_s *th) { return is_eq_state(th, WAIT); } static inline int is_finished(const struct thread_s *th) { return is_eq_state(th, FINISHED); } static int thread_entry(void *arg) { struct thread_table_s *tbl = arg; struct thread_s *th = NULL; int ret = -1; for (unsigned i = 0; i < RTE_DIM(tbl->threads); i++) { if (tbl->threads[i].lcore_id == rte_lcore_id()) th = &tbl->threads[i]; } if (th) { ret = 0; fprintf(stderr, "hello slave. thread:%u lcore:%u\n", th->thread_id, th->lcore_id); set_state(th, RUNNING); enum rte_lcore_state_t state; while ((state = read_state(th)) != FINISHED) { rte_pause(); } fprintf(stderr, "bye slave. thread:%u lcore:%u\n", th->thread_id, th->lcore_id); } return ret; } static void master_loop(struct thread_table_s *tbl, const char *in_path, const char *out_path) { struct thread_s *th = &tbl->threads[0]; fprintf(stderr, "hello master. lcore:%u\n", th->lcore_id); unsigned nb_threads = th->nb_threads - 1; for (unsigned i = 1; i < nb_threads; i++) while (!is_runnging(&tbl->threads[i])) rte_pause(); fprintf(stderr, "all slaves are up\n"); beef_cmdline_loop(in_path, out_path); finish_slaves(tbl); rte_eal_mp_wait_lcore(); fprintf(stderr, "bye master. lcore:%u\n", th->lcore_id); } static void core_usage(const char *prog) { fprintf(stderr, "core module usage:\n" "%s [--in PATH] [--out PATH] [--help]\n" " --pipe\tstdin,stdout path\n" " --help\tthis message\n", prog); } struct core_config_s { const char *in_path; const char *out_path; }; static int core_parse_args(struct core_config_s *config, int argc, char **argv) { char *prog = argv[0]; static const struct option long_option[] = { { "in", required_argument, NULL, 'i', }, { "out", required_argument, NULL, 'o', }, { "help", no_argument, NULL, 'h', }, { NULL, no_argument, NULL, 0, }, }; int opt; int ret; const int old_optind = optind; const int old_optopt = optopt; char * const old_optarg = optarg; optind = 1; while ((opt = getopt_long(argc, argv, "hi:o:", long_option, NULL)) != EOF) { switch (opt) { case 'i': config->in_path = optarg; break; case 'o': config->out_path = optarg; break; case 'h': default: core_usage(prog); ret = -1; goto end; } } if (optind >= 0) argv[optind - 1] = prog; ret = optind - 1; end: optind = old_optind; optopt = old_optopt; optarg = old_optarg; return ret; } int main(int argc, char **argv) { struct core_config_s config; memset(&config, 0, sizeof(config)); usage_hook = rte_set_application_usage_hook(core_usage); int n = rte_eal_init(argc, argv); if (n < 0) rte_panic("cannot initialize EAL: %s\n", rte_strerror(rte_errno)); argc -= n; argv += n; if (rte_eal_process_type() != RTE_PROC_PRIMARY) { if (!rte_eal_primary_proc_alive(NULL)) rte_exit(EXIT_FAILURE, "No primary DPDK process is running.\n"); } n = core_parse_args(&config, argc, argv); if (n < 0) rte_exit(EXIT_FAILURE, "invalid core args\n"); struct thread_table_s *tbl; tbl = create_thread_table(rte_lcore_count()); if (!tbl) { rte_exit(EXIT_FAILURE, "cannot create thread table\n"); } unsigned thread_id = 1; unsigned lcore_id; RTE_LCORE_FOREACH(lcore_id) { if (lcore_id == rte_get_master_lcore()) setup_thread_table(tbl, 0, lcore_id); else setup_thread_table(tbl, thread_id++, lcore_id); } if (rte_eal_mp_remote_launch(thread_entry, tbl, SKIP_MASTER)) rte_exit(EXIT_FAILURE, "cannot launch thread\n"); // daemon(1, 1); master_loop(tbl, config.in_path, config.out_path); rte_exit(EXIT_SUCCESS, "bye\n"); return 0; }
2.5
2
2024-11-18T20:50:35.450014+00:00
2021-09-13T01:24:54
47f9dc21c509f74f67257c93e12b7ca1b105c57d
{ "blob_id": "47f9dc21c509f74f67257c93e12b7ca1b105c57d", "branch_name": "refs/heads/main", "committer_date": "2021-09-13T01:24:54", "content_id": "d0e5b18cbf23bac80af8024037e6993b1ba37759", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "1aa23b3b606ac79895d6a276758e5f8aad3c4c1e", "extension": "c", "filename": "player.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4212, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/player/player.c", "provenance": "stackv2-0110.json.gz:219078", "repo_name": "anu086214/TinyXVC", "revision_date": "2021-09-13T01:24:54", "revision_id": "90034c638a06b52c121b99c3c5ad9c724d005c6d", "snapshot_id": "38cbc0c5f535534503dcb6ab52b15d08fb52aa26", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/anu086214/TinyXVC/90034c638a06b52c121b99c3c5ad9c724d005c6d/player/player.c", "visit_date": "2023-07-31T21:24:16.546789" }
stackv2
/* * Copyright 2021 Sergey Guralnik * * 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. * * 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. */ /* * This is an ad-hoc JTAG decoder for raw logical analyzer samples that are read from file. * It depends on jtag splitter internal logging. * TODO: * - rework it to not depend on splitter logs * - provide CLI to setup at least JTAG signal bit positions in input samples */ #include "txvc/log.h" #include "txvc/defs.h" #include "txvc/jtag_splitter.h" #include <stdbool.h> #include <stddef.h> #include <stdio.h> #include <stdint.h> #include <string.h> #include <errno.h> static inline void set_bit(uint8_t* p, int idx, bool bit) { uint8_t* octet = p + idx / 8; if (bit) *octet |= 1 << (idx % 8); else *octet &= ~(1 << (idx % 8)); } static bool noop_splitter_callback(const struct txvc_jtag_split_event *event, void* extra) { TXVC_UNUSED(event); TXVC_UNUSED(extra); return true; } int main(int argc, const char **argv) { TXVC_UNUSED(argc); TXVC_UNUSED(argv); txvc_log_configure("all+", LOG_LEVEL_VERBOSE, false); const char *jtagRawSaplesFile = argv[1]; //const size_t bytesPerSample = 1; const size_t tckBitPos = 3; const size_t tmsBitPos = 0; const size_t tdiBitPos = 1; const size_t tdoBitPos = 2; FILE* jtagSamples = fopen(jtagRawSaplesFile, "rb"); if (!jtagSamples) { fprintf(stderr, "Can not open %s: %s\n", jtagRawSaplesFile, strerror(errno)); return 1; } struct txvc_jtag_splitter splitter; txvc_jtag_splitter_init(&splitter, noop_splitter_callback, NULL); uint8_t tms[1024]; uint8_t tdi[sizeof(tms)]; uint8_t tdo[sizeof(tms)]; const size_t maxBits = sizeof(tms) * 8; size_t curBits = 0; bool lastTckSample = true; for (;;) { uint8_t rawSample; bool eof = false; if (fread(&rawSample, 1, 1, jtagSamples) != 1) { eof = feof(jtagSamples); if (!eof) { fprintf(stderr, "Can not read from %s: %s\n", jtagRawSaplesFile, strerror(errno)); return 1; } } if (!eof) { const bool tckSample = rawSample & (1 << tckBitPos); if (!lastTckSample && tckSample) { const bool tmsSample = rawSample & (1 << tmsBitPos); set_bit(tms, curBits, tmsSample); const bool tdiSample = rawSample & (1 << tdiBitPos); set_bit(tdi, curBits, tdiSample); const bool tdoSample = rawSample & (1 << tdoBitPos); set_bit(tdo, curBits, tdoSample); curBits++; } lastTckSample = tckSample; } const bool bufferFull = curBits == (maxBits - 1); if (eof || bufferFull) { txvc_jtag_splitter_process(&splitter, curBits, tms, tdi, tdo); curBits = 0; if (eof) { return 0; } } } TXVC_UNREACHABLE(); }
2.046875
2
2024-11-18T20:50:35.584536+00:00
2019-11-01T14:03:58
86ecd5d6b7bd15824a931ce495e709263b6381d0
{ "blob_id": "86ecd5d6b7bd15824a931ce495e709263b6381d0", "branch_name": "refs/heads/master", "committer_date": "2019-11-01T14:03:58", "content_id": "93971bbeb8a226ae7a9624553e5856792769d9c1", "detected_licenses": [ "MIT" ], "directory_id": "bf82e729af81f6e9e886016ae56d4f9fc106c063", "extension": "h", "filename": "que.h", "fork_events_count": 0, "gha_created_at": "2019-11-23T17:58:10", "gha_event_created_at": "2019-11-23T17:58:10", "gha_language": null, "gha_license_id": "MIT", "github_id": 223631005, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 710, "license": "MIT", "license_type": "permissive", "path": "/include/teoccl/que.h", "provenance": "stackv2-0110.json.gz:219208", "repo_name": "Si1ver/teoccl", "revision_date": "2019-11-01T14:03:58", "revision_id": "4594c509c6490d991101690b5c5eaaf6bfff14ea", "snapshot_id": "675234dfe2d01c07f6b07f865700130a29b5eff4", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Si1ver/teoccl/4594c509c6490d991101690b5c5eaaf6bfff14ea/include/teoccl/que.h", "visit_date": "2020-09-16T03:06:13.719993" }
stackv2
/** * \file que.h * \brief * \author max <mpano91@gmail.com> * * * * Created on Tue Jul 11 19:55:30 2019 */ #ifndef QUE_H #define QUE_H #include <stdlib.h> #ifdef __cplusplus extern "C" { #endif typedef struct ccl_queue ccl_queue_t; ccl_queue_t *cclQueInit(const size_t data_size); int cclQueSize(ccl_queue_t *que); int cclQueEmpty(ccl_queue_t *que); int cclQueTrim(ccl_queue_t *que); int cclQuePush(ccl_queue_t *que, void *const data); int cclQuePop(ccl_queue_t *que, void *const data); int cclQueFront(ccl_queue_t *que, void *data); int cclQueBack(ccl_queue_t *que, void *data); int cclQueClear(ccl_queue_t *que); void cclQueDestroy(ccl_queue_t *que); #ifdef __cplusplus } #endif #endif
2.140625
2
2024-11-18T20:50:35.659319+00:00
2019-04-23T16:46:15
5424ceea6c9ae11d06a913db390f7e82e07deff2
{ "blob_id": "5424ceea6c9ae11d06a913db390f7e82e07deff2", "branch_name": "refs/heads/master", "committer_date": "2019-04-23T16:46:15", "content_id": "6a293cc589bca519821258e93a00b76110c7071f", "detected_licenses": [ "MIT" ], "directory_id": "d42c63e4e95adcf3f30960bd162eb8008bebf29e", "extension": "c", "filename": "exploit_me_3.c", "fork_events_count": 2, "gha_created_at": "2019-04-23T16:41:58", "gha_event_created_at": "2019-04-23T16:41:59", "gha_language": null, "gha_license_id": null, "github_id": 183056842, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 936, "license": "MIT", "license_type": "permissive", "path": "/Lecture3/exploit_me_3.c", "provenance": "stackv2-0110.json.gz:219336", "repo_name": "Code-L0V3R/BinExp", "revision_date": "2019-04-23T16:46:15", "revision_id": "f933dd8ea9bb2e9a369595f0ef806ed80a967aba", "snapshot_id": "17dffc8d3c31ed27220977662aebd6e39a7651b1", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/Code-L0V3R/BinExp/f933dd8ea9bb2e9a369595f0ef806ed80a967aba/Lecture3/exploit_me_3.c", "visit_date": "2020-05-16T12:50:45.914085" }
stackv2
/* Target of this program is to over flow stack in such a way that return address from foo function changed to some address in the above the stack (which store the location of some address of nops of environment variable, which at the end store the address of executable shellcode). SHELLCODE : "\x31\xc0\x50\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\x50\x89\xe2\x53\x89\xe1\xb0\x0b\xcd\x80" Assume ASLR is turned ON. Compilation command: gcc -m32 -g -fno-stack-protector exploit_me_4.c -o exploit_me_4 Arguments used: -m32: instrcuting the compiler to build 32 bit Binary. -g: This allow C code to visible in gdb. -fno-stack-protector: Disbale stack protection by canary. -zexecstack: stack is marked as executable. */ #include <stdio.h> #include <string.h> void foo(char *name){ char buffer[100]; strcpy(buffer, name); printf("Hello %s", buffer); } int main(int argc, char **argv) { foo(argv[1]); return 0; }
3
3
2024-11-18T20:50:35.994843+00:00
2022-05-08T00:49:49
7db90dec1676f8ce90c06126578bf305c81c2683
{ "blob_id": "7db90dec1676f8ce90c06126578bf305c81c2683", "branch_name": "refs/heads/master", "committer_date": "2022-05-08T00:49:49", "content_id": "5f9b1544c846e1366b52b748e85f17344cb91507", "detected_licenses": [ "MIT" ], "directory_id": "ef9e00054970b58c01c1fd47d810c0a50a1a7d44", "extension": "c", "filename": "output_current_ES_for_phase_third.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 103708707, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1285, "license": "MIT", "license_type": "permissive", "path": "/c_lib/test/04_ESF/04_ESF_lib/output_current_ES_for_phase_third.c", "provenance": "stackv2-0110.json.gz:219594", "repo_name": "Leviyu/Maligaro", "revision_date": "2022-05-08T00:49:49", "revision_id": "d778251ca11f7a57d747b4d1558f4ac09f913bc6", "snapshot_id": "72843a151b182ac804066d052580bb93809b2bcd", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Leviyu/Maligaro/d778251ca11f7a57d747b4d1558f4ac09f913bc6/c_lib/test/04_ESF/04_ESF_lib/output_current_ES_for_phase_third.c", "visit_date": "2022-05-17T05:37:58.202921" }
stackv2
#include<stdlib.h> #include<stdio.h> #include<math.h> #include<string.h> #include<sacio.h> #include<ESF.h> /****************************************************************** * This is a c script for output current empirical source * * Input: * 1. * 2. * * * Output: * * * DATE: Keywords: * Reference: ******************************************************************/ int output_current_ES_for_phase_third(new_INPUT* my_input, double* new_ES) { fprintf(my_input->out_logfile, "--> output_current_ES_for_phase 3rd"); int output_array2( char* output_name, double* array1,double* array2,int file_num, int normalize_flag); // output ES here int nerr,i; char out_file[200]; char out_file1[200]; int npts_phase = (int)(my_input->phase_len / my_input->delta ); float beg = 0; float del = my_input->delta; sprintf(out_file,"%s_ES.sac",my_input->PHASE); float yarray[npts_phase]; double yarray_double[npts_phase]; double xarray[npts_phase]; for(i=0; i<npts_phase ;i++) { xarray[i] = i * my_input->delta; yarray[i] = new_ES[i]; yarray_double[i] = new_ES[i]; } sprintf(out_file1,"%s_ES.third.out",my_input->PHASE); output_array2(out_file1, xarray, yarray_double, npts_phase,0); //output_array1(out_file1, new_ES, npts_phase); return 0; }
2.265625
2
2024-11-18T20:50:36.114174+00:00
2017-04-13T23:56:50
93d86b29c308770b0389a8e080ffa2eff58f403e
{ "blob_id": "93d86b29c308770b0389a8e080ffa2eff58f403e", "branch_name": "refs/heads/master", "committer_date": "2017-04-13T23:56:50", "content_id": "241f715db607e830de78048fbb83cabc846e6df3", "detected_licenses": [ "MIT" ], "directory_id": "1e5fc5a14d9a35430adc97610810d4eafc515b51", "extension": "c", "filename": "cmd.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 82503931, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3981, "license": "MIT", "license_type": "permissive", "path": "/src/cmd.c", "provenance": "stackv2-0110.json.gz:219723", "repo_name": "nicoaw/fatfs", "revision_date": "2017-04-13T23:56:50", "revision_id": "46ee7d28596b54e0e33ed4070a454d8bfd43a010", "snapshot_id": "04ca30db4abe023fb7a4cfa6e24960b82247e399", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/nicoaw/fatfs/46ee7d28596b54e0e33ed4070a454d8bfd43a010/src/cmd.c", "visit_date": "2021-01-20T11:41:13.240018" }
stackv2
#include "block.h" #include "cmd.h" #include "disk.h" #include "op.h" #include <stdio.h> #include <syslog.h> #define FATFS_VERSION "1.0.0" #define FATFS_CEIL(a, b) (1 + ((a - 1) / b)) // Print usage void usage(struct fatfs_params *params); int cmd_format(struct fatfs_params *params) { // Parameters must contain disk path, valid disk size, and valid block size if(!params->disk_path || !params->size || !params->block_size) { usage(params); return -1; } // TODO use different method to determine size to avoid overflow // Determine input size power int power = 0; switch(params->unit) { case 'K': case 'k': power = 1; break; case 'M': case 'm': power = 2; break; case 'G': case 'g': power = 3; break; case '\0': break; default: usage(params); return -1; } // Actual size in bytes of entire filesystem uintmax_t size = 1; for(int i = 0; i < power; ++i) { size *= 1024; } size *= params->size; // Setup superblock struct superblock sb; sb.magic = 0x2345beef; sb.block_size = params->block_size; sb.block_count = FATFS_CEIL(size, sb.block_size); const uint32_t fat_size = sb.block_count * sizeof(block); sb.fat_block_count = FATFS_CEIL(fat_size, sb.block_size); sb.root_block = sb.fat_block_count + 1; const uint32_t min_block_count = 2 + sb.fat_block_count; // Min block count to support filesystem metadata if(sb.block_count < min_block_count) { fprintf(stderr, "filesystem too small: need at least %u bytes\n", min_block_count * sb.block_size); return -1; } disk d = disk_open(params->disk_path, true); if(!d) { return -1; } if(disk_format(d, sb) != 0) { return -1; } disk_close(d); return 0; } int cmd_help(struct fatfs_params *params) { usage(params); return 0; } int cmd_mount(struct fatfs_params *params) { // Parameters must contain disk path and mount path but not block size if(!params->disk_path || !params->mount_path) { usage(params); return -1; } struct fuse_operations operations = { .chmod = fatfs_chmod, .getattr = fatfs_getattr, .mkdir = fatfs_mkdir, .mknod = fatfs_mknod, .open = fatfs_open, .read = fatfs_read, .readdir = fatfs_readdir, .rename = fatfs_rename, .rmdir = fatfs_rmdir, .truncate = fatfs_truncate, .unlink = fatfs_unlink, .utimens = fatfs_utimens, .write = fatfs_write, }; disk d = disk_open(params->disk_path, false); if(!d) { return -1; } int err = fuse_main(params->args.argc, params->args.argv, &operations, d); disk_close(d); return err; } int cmd_version(struct fatfs_params *params) { fprintf(stderr, "fatfs version %s\n", FATFS_VERSION); fuse_opt_add_arg(&params->args, "--version"); fuse_main(params->args.argc, params->args.argv, NULL, NULL); return 0; } void usage(struct fatfs_params *params) { const char *program = params->args.argv[0]; switch(params->base_cmd) { case CMD_FORMAT: fprintf(stderr, "usage: %s format [<options>] <file> <size>\n" "\n" " <file> the disk file path\n" " <size> size of disk in bytes, append (K,M,G) for (KiB,MiB,GiB) respectively\n" "\n" " -b --block_size=N set block size in bytes (1024)\n" " -h --help print help\n" , program); break; case CMD_MOUNT: fprintf(stderr, "usage: %s mount [<options>] <file> <mountpoint>\n" "\n" " <file> the disk file path\n" " <mountpoint> the mount point path\n" "\n" "general options:\n" " -o opt,[opt...] mount options\n" " -h --help print help\n" "\n" , program); fuse_opt_add_arg(&params->args, "-ho"); fuse_main(params->args.argc, params->args.argv, NULL, NULL); break; default: fprintf(stderr, "usage: %s [-V] [--version] [-h] [--help] <command> [<args>]\n" "\n" "commands:\n" " format initialize a disk with empty fatfs filesystem\n" " mount mount a disk with a fatfs filesystem\n" , program); break; } }
2.671875
3
2024-11-18T20:50:36.256804+00:00
2021-04-29T14:54:10
4bfe6346d47b99cec8ea489e2179ead909e4d461
{ "blob_id": "4bfe6346d47b99cec8ea489e2179ead909e4d461", "branch_name": "refs/heads/main", "committer_date": "2021-04-29T14:54:10", "content_id": "a9f5c2b7530405a18363a7e24ef6688bf1b8c6ae", "detected_licenses": [ "Apache-2.0" ], "directory_id": "8b082711a476cc7a82b59bb2d38066fc2a39ca46", "extension": "h", "filename": "ngx_global.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": 488, "license": "Apache-2.0", "license_type": "permissive", "path": "/ngx-server/src/include/ngx_global.h", "provenance": "stackv2-0110.json.gz:219984", "repo_name": "RellikJaeger/test-project", "revision_date": "2021-04-29T14:54:10", "revision_id": "84180388fc2c42d23db03b361be548356819f16c", "snapshot_id": "ac3e0128377c280353ec023242ec9ecf968d074e", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/RellikJaeger/test-project/84180388fc2c42d23db03b361be548356819f16c/ngx-server/src/include/ngx_global.h", "visit_date": "2023-04-15T12:18:58.182768" }
stackv2
#ifndef __NGX_GLOBAL_H__ #define __NGX_GLOBAL_H__ #include <signal.h> typedef enum { NGX_MASTER_PROCESS, NGX_WORKER_PROCESS }ngx_proc_t; // main函数的argv参数 extern char **arg; // 保存环境变量字符数组 extern char *env; // 环境变量字符数组大小 extern int envsize; extern pid_t ngx_pid; extern pid_t ngx_parent; // 进程类型是master process还是worker process extern int ngx_process; extern sig_atomic_t ngx_reap; #endif // __NGX_GLOBAL_H__
2.09375
2
2024-11-18T20:50:37.157414+00:00
2018-07-18T08:24:38
978c2188fbce3f07b716f13cb3fa8e8f2459d37f
{ "blob_id": "978c2188fbce3f07b716f13cb3fa8e8f2459d37f", "branch_name": "refs/heads/master", "committer_date": "2018-07-18T08:24:38", "content_id": "e18f052bce4f0627ee868e25d462b29fee778441", "detected_licenses": [ "MIT" ], "directory_id": "7bc58acec9e1d92a8f207b9d81390345a967f2a0", "extension": "c", "filename": "voxmodel_ops.c", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 138332084, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 375, "license": "MIT", "license_type": "permissive", "path": "/voxen/voxmodel_ops.c", "provenance": "stackv2-0110.json.gz:220243", "repo_name": "mafiosso/voxen", "revision_date": "2018-07-18T08:24:38", "revision_id": "d0368bbfe3cf2134253480c362a313e258cf4fec", "snapshot_id": "cd41f5d583c9a2501be5a9266ff80799340d74db", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/mafiosso/voxen/d0368bbfe3cf2134253480c362a313e258cf4fec/voxen/voxmodel_ops.c", "visit_date": "2020-03-21T08:16:25.374065" }
stackv2
#include "VX_lib.h" /* blit one slice - image s to one of z coords of model m */ void VX_blit_slice( VX_model * m , VX_surface * s , VX_uint32 z ){ for( VX_uint32 y = 0 ; y < s->h ; y++ ){ for( VX_uint32 x = 0 ; x < s->w ; x++ ){ VX_uint32 color = s->get_pixel( s , x , y ); m->set_voxel( m , x , y , z , color ); } } }
2.109375
2
2024-11-18T20:50:37.248813+00:00
2021-07-14T23:04:11
e3e562913796d0a8402d910172051e6e2608c711
{ "blob_id": "e3e562913796d0a8402d910172051e6e2608c711", "branch_name": "refs/heads/master", "committer_date": "2021-07-14T23:04:11", "content_id": "d52423100e6cbcb739cb1e2867c17287cde57428", "detected_licenses": [ "Apache-2.0" ], "directory_id": "f2cea9b869157b384dfb891e9b950c8d342ea392", "extension": "c", "filename": "netif_lan8742a.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 121893294, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3036, "license": "Apache-2.0", "license_type": "permissive", "path": "/src/netif_lan8742a.c", "provenance": "stackv2-0110.json.gz:220372", "repo_name": "StratifyLabs/Nucleo-F746ZG", "revision_date": "2021-07-14T23:04:11", "revision_id": "51a7eadb0a37bc69fc37f1777cdaa30519baba7e", "snapshot_id": "513edeeb3bc8f2f29df86b471deb81a27abc083f", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/StratifyLabs/Nucleo-F746ZG/51a7eadb0a37bc69fc37f1777cdaa30519baba7e/src/netif_lan8742a.c", "visit_date": "2021-07-19T13:34:09.324407" }
stackv2
#include <mcu/debug.h> #include "netif_lan8742a.h" int netif_lan8742a_open(const devfs_handle_t * handle){ return mcu_eth_open(handle); } int netif_lan8742a_ioctl(const devfs_handle_t * handle, int request, void * ctl){ int result; netif_attr_t * netif_attr = ctl; netif_info_t * netif_info = ctl; mcu_channel_t eth_register; eth_attr_t attr; u32 o_flags; switch(request){ case I_NETIF_GETVERSION: return NETIF_VERSION; case I_NETIF_SETATTR: o_flags = netif_attr->o_flags; if(o_flags & NETIF_FLAG_INIT ){ //initialize the interface result = mcu_eth_setattr(handle, 0); if( result < 0 ){ mcu_debug_log_error(MCU_DEBUG_USER0, "Failed to initialize ethernet (%d, %d)", SYSFS_GET_RETURN(result), SYSFS_GET_RETURN_ERRNO(result)); return result; } return 0; } //restart after having been stopped if( o_flags & NETIF_FLAG_SET_LINK_UP ){ eth_register.loc = 0; //status regsiter if( mcu_eth_getregister(handle, &eth_register) < 0 ){ return SYSFS_SET_RETURN(EIO); } eth_register.value &= ~1<<11; //Set power down mode if( mcu_eth_setregister(handle, &eth_register) < 0 ){ return SYSFS_SET_RETURN(EIO); } attr.o_flags = ETH_FLAG_STOP; if( mcu_eth_setattr(handle, &attr) < 0 ){ return SYSFS_SET_RETURN(EIO); } } if( o_flags & NETIF_FLAG_IS_LINK_UP ){ eth_register.loc = 1; //status regsiter if( mcu_eth_getregister(handle, &eth_register) < 0 ){ return SYSFS_SET_RETURN(EIO); } mcu_debug_log_info(MCU_DEBUG_USER2, "Status register 0x%lX", eth_register.value); return (eth_register.value & (1<<2)) != 0; } if( o_flags & NETIF_FLAG_SET_LINK_DOWN ){ mcu_channel_t eth_register; eth_register.loc = 0; //status regsiter if( mcu_eth_getregister(handle, &eth_register) < 0 ){ return SYSFS_SET_RETURN(EIO); } eth_register.value |= ~1<<11; //Set power down mode if( mcu_eth_setregister(handle, &eth_register) < 0 ){ return SYSFS_SET_RETURN(EIO); } attr.o_flags = ETH_FLAG_STOP; if( mcu_eth_setattr(handle, &attr) < 0 ){ return SYSFS_SET_RETURN(EIO); } } break; case I_NETIF_GETINFO: netif_info->o_flags = NETIF_FLAG_INIT | NETIF_FLAG_DEINIT | NETIF_FLAG_IS_LINK_UP | NETIF_FLAG_SET_LINK_DOWN | NETIF_FLAG_SET_LINK_UP; netif_info->o_events = MCU_EVENT_FLAG_DATA_READY | MCU_EVENT_FLAG_WRITE_COMPLETE; break; } return mcu_eth_ioctl(handle, request, ctl); } int netif_lan8742a_read(const devfs_handle_t * handle, devfs_async_t * async){ return mcu_eth_read(handle, async); } int netif_lan8742a_write(const devfs_handle_t * handle, devfs_async_t * async){ return mcu_eth_write(handle, async); } int netif_lan8742a_close(const devfs_handle_t * handle){ return mcu_eth_close(handle); }
2.3125
2
2024-11-18T20:50:37.508880+00:00
2017-08-06T00:43:15
0e28af649f94866838be2269103782615d80d201
{ "blob_id": "0e28af649f94866838be2269103782615d80d201", "branch_name": "refs/heads/master", "committer_date": "2017-08-06T00:55:21", "content_id": "f37f116b7b62e3e79f9232f104d5e8ba95630b8a", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "bf0d8da4aec3bd04e34eb600c491e2e065dfa35b", "extension": "c", "filename": "init.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": 775, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/target/lm3s6965/init.c", "provenance": "stackv2-0110.json.gz:220502", "repo_name": "ChiwenLin/pikoRT", "revision_date": "2017-08-06T00:43:15", "revision_id": "2a68d945c3454b415beb369f757c55ca58f36a92", "snapshot_id": "d7b178c4985e3a535939e7ff862a8d6ce6d15189", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/ChiwenLin/pikoRT/2a68d945c3454b415beb369f757c55ca58f36a92/target/lm3s6965/init.c", "visit_date": "2021-01-15T18:26:37.853958" }
stackv2
#include <kernel/compiler.h> #include "platform.h" #define SYSTICK_FREQ_IN_HZ 1000 #define SYSTICK_PERIOD_IN_MSECS (SYSTICK_FREQ_IN_HZ / 1000) struct timer_operations; void config_timer_operations(struct timer_operations *tops); extern struct timer_operations systick_tops; void lm3s6965_init(void); __weak void __platform_init(void) { config_timer_operations(&systick_tops); /* create /dev/ttyS0, serial interface for QEMU UART0 */ lm3s6965_init(); } __weak void __platform_halt(void) { for (;;) ; } void __printk_init(void) { UART0->CTL |= 1; /* UART enabled */ UART0->LCRH |= (3 << 5); /* 8 bits word length, no parity */ NVIC_SetPriority(UART1_IRQn, 0xE); } void __printk_putchar(char c) { while (UART0->FR & (1 << 3)) ; UART0->DR = c; }
2.171875
2
2024-11-18T20:50:40.519561+00:00
2020-01-11T01:37:17
5ecdb37ab25049370f73a3184d6fb08c9f023aa1
{ "blob_id": "5ecdb37ab25049370f73a3184d6fb08c9f023aa1", "branch_name": "refs/heads/master", "committer_date": "2020-01-11T01:37:17", "content_id": "39ab2464b56c72e7de72ed5df3069d25654342bd", "detected_licenses": [ "MIT" ], "directory_id": "69bf0191c0b68765a550c89b05f3202402ff7d0a", "extension": "c", "filename": "addwords.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 143576130, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2591, "license": "MIT", "license_type": "permissive", "path": "/addwords.c", "provenance": "stackv2-0110.json.gz:220888", "repo_name": "spirosavlonitis/spell_check", "revision_date": "2020-01-11T01:37:17", "revision_id": "060639cf7a9487e0ac75ac1507a3e908be05c750", "snapshot_id": "da84737b2e3eb70d52f549ff0c8d59f62ebaf356", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/spirosavlonitis/spell_check/060639cf7a9487e0ac75ac1507a3e908be05c750/addwords.c", "visit_date": "2020-03-25T07:41:22.368734" }
stackv2
#include "hdr.h" static void shellsort(char **, int); static void unget_word(FILE *, char *); static void updatedic(char **, int ); #define UPPER_ORIGINAL_DIC "/home/phantom/Git/spell_check/en-US_upper_original.dic" #define LOWER_ORIGINAL_DIC "/home/phantom/Git/spell_check/en-US_lower_original.dic" void addwords(char **words) { int n, i, j; char *upper_words[NEWWORDS], *lower_words[NEWWORDS]; FILE *fp, *fp_orig; for (int i = 0; i < NEWWORDS; ++i) upper_words[i] = lower_words[i] = NULL; for (n = i = j = 0; words[n] ; ++n) if (isupper(*words[n])) upper_words[i++] = words[n]; else lower_words[j++] = words[n]; if (*upper_words) { shellsort(upper_words, i); updatedic(upper_words, UPPER); } if (*lower_words) { shellsort(lower_words, j); updatedic(lower_words, LOWER); } return; } static void updatedic(char **words, int flag) { int i, cmp, diceof; char dic_word[MAXWORD]; FILE *fp, *fp_orig; if ( ~(~0 << 3) & flag == UPPER){ fp_orig = Fopen(UPPER_ORIGINAL_DIC, "r"); fp = Fopen(UPPER_DIC, "w"); }else{ fp_orig = Fopen(LOWER_ORIGINAL_DIC, "r"); fp = Fopen(LOWER_DIC, "w"); } for (i = 0; words[i] ; ++i) { while ((diceof = getword(fp_orig, dic_word, MAXWORD)) != EOF) { if ( (cmp = strcasecmp(words[i], dic_word)) <= 0){ /* word to add is lesser or equal to dictionary word */ if (cmp < 0) /* if lesser push dictionary word back to read buffer */ unget_word(fp_orig, dic_word); /* push dic_word back to buffer to be compared with the next word */ fprintf(fp, "%s\n", words[i]); /* print word to file */ break; }else fprintf(fp, "%s\n", dic_word); /* print dictionary word to file */ } } if (diceof != EOF) /* copy remaining dictionary words */ while (getword(fp_orig, dic_word, MAXWORD) != EOF) fprintf(fp, "%s\n", dic_word); fclose(fp); fclose(fp_orig); /* update source dictionary */ if ( ~(~0 << 3) & flag == UPPER){ fp_orig = Fopen(UPPER_ORIGINAL_DIC, "w"); fp = Fopen(UPPER_DIC, "r"); }else{ fp_orig = Fopen(LOWER_ORIGINAL_DIC, "w"); fp = Fopen(LOWER_DIC, "r"); } while (getword(fp, dic_word, MAXWORD) != EOF) fprintf(fp_orig, "%s\n", dic_word); fclose(fp); fclose(fp_orig); } static void shellsort(char **w, int n) { int i, j, g; char *temp; for (g = n/2; g > 0 ; g /= 2) for (i = 1; w[i] ; i += g) for (j = i-g; j >= 0 && strcmp(w[j], w[j+g]) > 0 ; j -= g) temp = w[j], w[j] = w[j+g], w[j+g] = temp; } static void unget_word(FILE *fp, char *w) { int i; for (i = strlen(w)-1; i >= 0 ; --i) ungetc(w[i], fp); }
2.90625
3
2024-11-18T20:50:41.926674+00:00
2017-10-03T21:44:55
be43c94616d9974b72fdc72dd096a283125cddbd
{ "blob_id": "be43c94616d9974b72fdc72dd096a283125cddbd", "branch_name": "refs/heads/master", "committer_date": "2017-10-03T21:44:55", "content_id": "5238e1bd1ea36bee3d82d12ba1fb104fd97d82b4", "detected_licenses": [ "MIT" ], "directory_id": "b79f50973e96c76481daf55af474cf31d666986e", "extension": "c", "filename": "texture.c", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 105656514, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1461, "license": "MIT", "license_type": "permissive", "path": "/server/texture.c", "provenance": "stackv2-0110.json.gz:221539", "repo_name": "dousha/pestium", "revision_date": "2017-10-03T21:44:55", "revision_id": "c4e984ebaf93dc244ab019b00f78b71d23ccf97f", "snapshot_id": "11d3796b81b44d9984f1e401b3f10dd1d19d62f1", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/dousha/pestium/c4e984ebaf93dc244ab019b00f78b71d23ccf97f/server/texture.c", "visit_date": "2021-06-05T20:34:33.329451" }
stackv2
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "types.h" #include "logger.h" static int _texture_count = 0; static texture_t* _texture_poll = NULL; bool texture_init(){ char buf[64]; FILE* fp = fopen("assets/texture", "r"); if(fp == NULL){ log("Cannot open texture"); return false; } int i = 0; while(fgets(buf, 64, fp) != NULL){ if(strlen(buf) == 0) continue; ++i; } _texture_poll = malloc(sizeof(texture_t) * i); if(_texture_poll == NULL){ log("Cannot allocate texture poll!"); return false; } fseek(fp, 0, SEEK_SET); int fg, bg, count = 0; char txt, name[16]; while(fgets(buf, 64, fp) != NULL){ if(strlen(buf) == 0) continue; sscanf(buf, "%s %d %d %c", (char*) &name, &fg, &bg, &txt); strncpy(_texture_poll[count].name, name, 16); _texture_poll[count].fg = (color) fg; _texture_poll[count].bg = (color) bg; _texture_poll[count].text = txt; count++; } printf("|Texture> %d textures loaded\n", count); _texture_count = count; return true; } const texture_t* texture_get(const char* name){ if(_texture_poll == NULL){ log("Call texture_init() to load texture first!"); return NULL; }else{ for(int i = 0; i < _texture_count; i++){ // TODO: could be more efficient if(strncmp(_texture_poll[i].name, name, 16) == 0){ return _texture_poll + i; } } log("Trying to get an undefined texture:"); log(name); return NULL; } } void texture_finalize(){ free(_texture_poll); }
2.765625
3
2024-11-18T20:50:42.439904+00:00
2023-07-20T17:06:28
ad7d737b39a1a6c9f77b02d4d15adba502aa21a5
{ "blob_id": "ad7d737b39a1a6c9f77b02d4d15adba502aa21a5", "branch_name": "refs/heads/master", "committer_date": "2023-07-20T17:06:28", "content_id": "fa1b194454097775f52b6ba9006d496553a64ab7", "detected_licenses": [ "MIT" ], "directory_id": "c572d1660721afb07d4c86d5a92d05ecf359b7ec", "extension": "c", "filename": "ina260.c", "fork_events_count": 84, "gha_created_at": "2018-11-19T22:53:51", "gha_event_created_at": "2023-07-20T16:54:45", "gha_language": "Propeller Spin", "gha_license_id": "MIT", "github_id": 158300500, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2543, "license": "MIT", "license_type": "permissive", "path": "/libraries/community/p1/All/INA260 Driver/ina260.c", "provenance": "stackv2-0110.json.gz:222189", "repo_name": "parallaxinc/propeller", "revision_date": "2023-07-20T17:06:28", "revision_id": "3f485a2dbf7dc7a23b39387c63c5a626fbcf017e", "snapshot_id": "02897c60c579a198ae30a074c164019af1b37447", "src_encoding": "UTF-8", "star_events_count": 103, "url": "https://raw.githubusercontent.com/parallaxinc/propeller/3f485a2dbf7dc7a23b39387c63c5a626fbcf017e/libraries/community/p1/All/INA260 Driver/ina260.c", "visit_date": "2023-08-15T17:30:07.257358" }
stackv2
/** * @file ina260.c * @brief INA260 Adafruit power driver * @author Michael Burmeister * @date June 23, 2019 * @version 1.0 * */ #include "ina260.h" #include "simpletools.h" void _writeWord(unsigned char register, unsigned short data); unsigned short _readWord(unsigned char register); void _readBytes(unsigned char register, unsigned char cnt, unsigned char *dest); unsigned char _INA260; i2c *_INA260C; unsigned short INA260_open(unsigned char address, char clock, char data) { unsigned short id; if (address == 0) _INA260 = INA260_I2CADDR; else _INA260 = address; _INA260C = i2c_open(_INA260C, clock, data, 0); id = _readWord(INA260_MFGID); return id; } short INA260_getCurrent(void) { int v; v = _readWord(INA260_CURRENT); v = v * 125; return v/100; } short INA260_getVoltage(void) { int v; v = _readWord(INA260_VOLTAGE); v = v * 125; return v/1000; } short INA260_getPower(void) { int v; v = _readWord(INA260_POWER); v = v * 10; return v; } void INA260_setConfig(char mode, char current, char voltage, char average, char reset) { unsigned short v; v = reset << 15; v = v | average << 9; v = v | voltage << 6; v = v | current << 3; v = v | mode; _writeWord(INA260_CONFIG, v); } unsigned short INA260_getConfig(void) { unsigned short v; v = _readWord(INA260_CONFIG); return v; } void INA260_setMask(unsigned short mask) { _writeWord(INA260_ALERTEN, mask); } unsigned short INA260_getMask(void) { unsigned short v; v = _readWord(INA260_ALERTEN); return v; } void INA260_setAlert(unsigned short alert) { _writeWord(INA260_ALERTV, alert); } /* basic read write funcitons */ /** * @brief I2C read write routines * @param reg register on device * @param data to write */ void _writeWord(unsigned char reg, unsigned short data) { unsigned char v[2]; v[0] = data >> 8; v[1] = data; i2c_out(_INA260C, _INA260, reg, 1, v, 2); } /** * @brief I2C read routine * @param reg register on device * @return byte value */ unsigned short _readWord(unsigned char reg) { unsigned short v; unsigned char data[2]; i2c_in(_INA260C, _INA260, reg, 1, data, 2); v = data[0] << 8 | data[1]; return v; } /** * @brief I2C read routine * @param reg register on device * @param cnt number of bytes to read * @param dest returned byte of data from device */ void _readBytes(unsigned char reg, unsigned char cnt, unsigned char *dest) { i2c_in(_INA260C, _INA260, reg, 1, dest, cnt); }
2.75
3
2024-11-18T20:50:43.059475+00:00
2019-12-07T19:04:27
52c9dec95897a0a8135c5a7883b3acf75ac1338f
{ "blob_id": "52c9dec95897a0a8135c5a7883b3acf75ac1338f", "branch_name": "refs/heads/master", "committer_date": "2019-12-07T19:04:27", "content_id": "87ebc822f2d1a31e504ffdaea9845607d16c1c3b", "detected_licenses": [ "MIT" ], "directory_id": "27ca196c9f0769b36a7e70c2d93ab9d138f6ddb0", "extension": "c", "filename": "framegen64.c", "fork_events_count": 0, "gha_created_at": "2020-02-02T16:11:12", "gha_event_created_at": "2020-02-02T16:11:12", "gha_language": null, "gha_license_id": "MIT", "github_id": 237797765, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 6256, "license": "MIT", "license_type": "permissive", "path": "/src/framing/src/framegen64.c", "provenance": "stackv2-0110.json.gz:222971", "repo_name": "vbursucianu/liquid-dsp", "revision_date": "2019-12-07T19:04:27", "revision_id": "f11733208e3d0da928a0dc2111cdb2b0c4817cef", "snapshot_id": "db5d24223b36920a3aca18a524e8d167c702cd7a", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/vbursucianu/liquid-dsp/f11733208e3d0da928a0dc2111cdb2b0c4817cef/src/framing/src/framegen64.c", "visit_date": "2020-12-27T06:36:28.894365" }
stackv2
/* * Copyright (c) 2007 - 2019 Joseph Gaeddert * * 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. */ // // framegen64.c // // frame64 generator: 8-byte header, 64-byte payload, 1340-sample frame // #include <stdlib.h> #include <stdio.h> #include <string.h> #include <math.h> #include <assert.h> #include <complex.h> #include "liquid.internal.h" struct framegen64_s { qpacketmodem enc; // packet encoder/modulator qpilotgen pilotgen; // pilot symbol generator float complex pn_sequence[64]; // 64-symbol p/n sequence unsigned char payload_dec[150]; // 600 = 150 bytes * 8 bits/bytes / 2 bits/symbol float complex payload_sym[600]; // modulated payload symbols float complex payload_tx[630]; // modulated payload symbols with pilots unsigned int m; // filter delay (symbols) float beta; // filter excess bandwidth factor firinterp_crcf interp; // pulse-shaping filter }; // create framegen64 object framegen64 framegen64_create() { framegen64 q = (framegen64) malloc(sizeof(struct framegen64_s)); q->m = 7; q->beta = 0.3f; unsigned int i; // generate pn sequence msequence ms = msequence_create(7, 0x0089, 1); for (i=0; i<64; i++) { q->pn_sequence[i] = (msequence_advance(ms) ? M_SQRT1_2 : -M_SQRT1_2); q->pn_sequence[i] += (msequence_advance(ms) ? M_SQRT1_2 : -M_SQRT1_2)*_Complex_I; } msequence_destroy(ms); // create payload encoder/modulator object int check = LIQUID_CRC_24; int fec0 = LIQUID_FEC_NONE; int fec1 = LIQUID_FEC_GOLAY2412; int mod_scheme = LIQUID_MODEM_QPSK; q->enc = qpacketmodem_create(); qpacketmodem_configure(q->enc, 72, check, fec0, fec1, mod_scheme); //qpacketmodem_print(q->enc); assert( qpacketmodem_get_frame_len(q->enc)==600 ); // create pilot generator q->pilotgen = qpilotgen_create(600, 21); assert( qpilotgen_get_frame_len(q->pilotgen)==630 ); // create pulse-shaping filter (k=2) q->interp = firinterp_crcf_create_prototype(LIQUID_FIRFILT_ARKAISER,2,q->m,q->beta,0); // return main object return q; } // destroy framegen64 object void framegen64_destroy(framegen64 _q) { // destroy internal objects qpacketmodem_destroy(_q->enc); qpilotgen_destroy(_q->pilotgen); // free main object memory free(_q); } // print framegen64 object internals void framegen64_print(framegen64 _q) { float eta = (float) (8*(64 + 8)) / (float) (LIQUID_FRAME64_LEN/2); printf("framegen64 [m=%u, beta=%4.2f]:\n", _q->m, _q->beta); printf(" preamble/etc.\n"); printf(" * ramp/up symbols : %3u\n", _q->m); printf(" * p/n symbols : %3u\n", 64); printf(" * ramp\\down symbols : %3u\n", _q->m); printf(" * zero padding : %3u\n", 12); printf(" payload\n"); #if 0 printf(" * payload crc : %s\n", crc_scheme_str[_q->check][1]); printf(" * fec (inner) : %s\n", fec_scheme_str[_q->fec0][1]); printf(" * fec (outer) : %s\n", fec_scheme_str[_q->fec1][1]); #endif printf(" * payload len, uncoded : %3u bytes\n", 64); printf(" * payload len, coded : %3u bytes\n", 150); printf(" * modulation scheme : %s\n", modulation_types[LIQUID_MODEM_QPSK].name); printf(" * payload symbols : %3u\n", 600); printf(" * pilot symbols : %3u\n", 30); printf(" summary\n"); printf(" * total symbols : %3u\n", LIQUID_FRAME64_LEN/2); printf(" * spectral efficiency : %6.4f b/s/Hz\n", eta); } // execute frame generator (creates a frame) // _q : frame generator object // _header : 8-byte header data, NULL for random // _payload : 64-byte payload data, NULL for random // _frame : output frame samples [size: LIQUID_FRAME64_LEN x 1] void framegen64_execute(framegen64 _q, unsigned char * _header, unsigned char * _payload, float complex * _frame) { unsigned int i; // concatenate header and payload for (i=0; i<8; i++) _q->payload_dec[i] = _header==NULL ? rand() & 0xff : _header[i]; for (i=0; i<64; i++) _q->payload_dec[i+8] = _payload==NULL ? rand() & 0xff : _payload[i]; // run packet encoder and modulator qpacketmodem_encode(_q->enc, _q->payload_dec, _q->payload_sym); // add pilot symbols qpilotgen_execute(_q->pilotgen, _q->payload_sym, _q->payload_tx); unsigned int n=0; // reset interpolator firinterp_crcf_reset(_q->interp); // p/n sequence for (i=0; i<64; i++) { firinterp_crcf_execute(_q->interp, _q->pn_sequence[i], &_frame[n]); n+=2; } // frame payload for (i=0; i<630; i++) { firinterp_crcf_execute(_q->interp, _q->payload_tx[i], &_frame[n]); n+=2; } // interpolator settling for (i=0; i<2*_q->m + 2 + 10; i++) { firinterp_crcf_execute(_q->interp, 0.0f, &_frame[n]); n+=2; } assert(n==LIQUID_FRAME64_LEN); }
2.046875
2
2024-11-18T20:50:43.220977+00:00
2021-06-05T11:12:47
3c20a7b6f69bf2bc6fd6ebb77fa7ce73dbc8ebe7
{ "blob_id": "3c20a7b6f69bf2bc6fd6ebb77fa7ce73dbc8ebe7", "branch_name": "refs/heads/master", "committer_date": "2021-06-05T11:12:47", "content_id": "e9842090465bda7a3ea35913b95c4d9286ebda6d", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "fbcb4139285327124d20e93546593e8743222ee3", "extension": "c", "filename": "image.c", "fork_events_count": 0, "gha_created_at": "2021-06-05T11:10:50", "gha_event_created_at": "2021-06-05T11:10:51", "gha_language": null, "gha_license_id": "BSD-3-Clause", "github_id": 374093137, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1619, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/scanvideo/render/image.c", "provenance": "stackv2-0110.json.gz:223231", "repo_name": "ThomasPDye/pico-playground", "revision_date": "2021-06-05T11:12:47", "revision_id": "2d71f4df49084bf75aec3216ad51b86c317157ac", "snapshot_id": "e1fcdd743e70bd096f86f7c1d9bf10370144a91c", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/ThomasPDye/pico-playground/2d71f4df49084bf75aec3216ad51b86c317157ac/scanvideo/render/image.c", "visit_date": "2023-05-09T07:43:36.777737" }
stackv2
/* * Copyright (c) 2020 Raspberry Pi (Trading) Ltd. * * SPDX-License-Identifier: BSD-3-Clause */ #include <assert.h> #include <stdlib.h> #include "image.h" #include "pico/scanvideo.h" struct palette16 *blend_palette(const struct palette32 *source, uint32_t back_color) { struct palette16 *dest = (struct palette16 *) malloc(sizeof(struct palette16) + source->size * sizeof(uint16_t)); dest->flags = CF_PALETTE_COMPOSITED | (source->flags & ~(CF_HAS_SEMI_TRANSPARENT | CF_HAS_TRANSPARENT)) | CF_HAS_OPAQUE; dest->composited_on_color = back_color; dest->size = source->size; uint32_t __unused ba = (back_color >> 24) & 0xff; uint32_t bb = (back_color >> 16) & 0xff; uint32_t bg = (back_color >> 8) & 0xff; uint32_t br = (back_color >> 0) & 0xff; assert(ba == 255); // expect to be on an opaque color for (int i = 0; i < source->size; i++) { uint32_t fore_color = source->entries[i]; uint32_t fa = (fore_color >> 24) & 0xff; uint32_t fb = (fore_color >> 16) & 0xff; uint32_t fg = (fore_color >> 8) & 0xff; uint32_t fr = (fore_color >> 0) & 0xff; if (!i && !fa) { // even though we don't record alpha in the blended palette, we may care to use a color key (of 0) dest->flags |= CF_PALETTE_INDEX_0_TRANSPARENT; } if (fa == 255) fa = 256; fb = (fa * fb + (256 - fa) * bb) >> 11; fg = (fa * fg + (256 - fa) * bg) >> 11; fr = (fa * fr + (256 - fa) * br) >> 11; dest->entries[i] = PICO_SCANVIDEO_PIXEL_FROM_RGB5(fr, fg, fb); } return dest; }
2.671875
3
2024-11-18T20:50:43.680831+00:00
2021-02-17T21:00:02
26adb20314fb08c07288d393fba08422ae6537e5
{ "blob_id": "26adb20314fb08c07288d393fba08422ae6537e5", "branch_name": "refs/heads/main", "committer_date": "2021-02-17T21:00:02", "content_id": "6a564eb848c079b1b6c47b93bff9db76faf12e89", "detected_licenses": [ "MIT" ], "directory_id": "b8cd33ce20e36b68e02f08da5aea3e3b6d350e4d", "extension": "c", "filename": "ws2812.c", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 339787039, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4247, "license": "MIT", "license_type": "permissive", "path": "/ws2812.c", "provenance": "stackv2-0110.json.gz:223759", "repo_name": "iotexpert/ws2812_led", "revision_date": "2021-02-17T21:00:02", "revision_id": "9faab52e9a1db0cba720cd81d03c81aa47eb50cd", "snapshot_id": "d485a8e49a750e9e5465553b113a738e6e115e75", "src_encoding": "UTF-8", "star_events_count": 3, "url": "https://raw.githubusercontent.com/iotexpert/ws2812_led/9faab52e9a1db0cba720cd81d03c81aa47eb50cd/ws2812.c", "visit_date": "2023-03-09T11:05:22.704239" }
stackv2
/* * ws2812.c */ #include "cyhal.h" #include "ws2812.h" #define WS_ZOFFSET (1) #define WS_ONE3 (0b110<<24) #define WS_ZERO3 (0b100<<24) #define WS_SPI_BIT_PER_BIT (3) #define WS_COLOR_PER_PIXEL (3) #define WS_BYTES_PER_PIXEL (WS_SPI_BIT_PER_BIT * WS_COLOR_PER_PIXEL) static uint8_t WS_frameBuffer[(MAX_PIXELS*WS_BYTES_PER_PIXEL)+WS_ZOFFSET]; static uint16_t numberOfPixels; static cyhal_spi_t ws2182SpiHandle; static uint32_t WS_convert3Code(uint8_t input); /* Initialize the LED API */ ws2812_rtn_t ws2812_init(uint16_t numPixels, cyhal_gpio_t mosi, cyhal_gpio_t miso, cyhal_gpio_t sclk) { cy_rslt_t result; ws2812_rtn_t ws_result; if(numPixels > MAX_PIXELS) { return (ws2182_too_many_pixels); } /* Save number of pixels provided by the user to a global */ numberOfPixels = numPixels; /* Initialize the SPI block that will be used to drive data to the LEDs */ result = cyhal_spi_init(&ws2182SpiHandle, mosi, miso, sclk, NC, NULL, 8, CYHAL_SPI_MODE_11_MSB, false); if(result != CY_RSLT_SUCCESS) { return (ws2812_error); } result = cyhal_spi_set_frequency(&ws2182SpiHandle, 2200000); if(result != CY_RSLT_SUCCESS) { return (ws2812_error); } /* Initialize the array to all off RGB values and turn off the LEDs */ WS_frameBuffer[0] = 0x00; ws2812_setMultiRGB(0,numberOfPixels-1,0,0,0); ws_result = ws2812_update(); return(ws_result); } /* Set the RGB values for a single LED */ /* This does NOT send new values to the LEDs - you must call ws2812_update to send the values */ ws2812_rtn_t ws2812_setRGB(uint16_t led, uint8_t red, uint8_t green, uint8_t blue) { if( led > (numberOfPixels-1) ) { return (ws2812_invalid_LED_id); } typedef union { uint8_t bytes[4]; uint32_t word; } WS_colorUnion; WS_colorUnion color; color.word = WS_convert3Code(green); WS_frameBuffer[(led*WS_BYTES_PER_PIXEL)+0+WS_ZOFFSET] = color.bytes[2]; WS_frameBuffer[(led*WS_BYTES_PER_PIXEL)+1+WS_ZOFFSET] = color.bytes[1]; WS_frameBuffer[(led*WS_BYTES_PER_PIXEL)+2+WS_ZOFFSET] = color.bytes[0]; color.word = WS_convert3Code(red); WS_frameBuffer[(led*WS_BYTES_PER_PIXEL)+3+WS_ZOFFSET] = color.bytes[2]; WS_frameBuffer[(led*WS_BYTES_PER_PIXEL)+4+WS_ZOFFSET] = color.bytes[1]; WS_frameBuffer[(led*WS_BYTES_PER_PIXEL)+5+WS_ZOFFSET] = color.bytes[0]; color.word = WS_convert3Code(blue); WS_frameBuffer[(led*WS_BYTES_PER_PIXEL)+6+WS_ZOFFSET] = color.bytes[2]; WS_frameBuffer[(led*WS_BYTES_PER_PIXEL)+7+WS_ZOFFSET] = color.bytes[1]; WS_frameBuffer[(led*WS_BYTES_PER_PIXEL)+8+WS_ZOFFSET] = color.bytes[0]; return (ws2812_success); } /* Set the RGB values for a range of LEDs */ /* This does NOT send new values to the LEDs - you must call ws2812_update to send the values */ ws2812_rtn_t ws2812_setMultiRGB(uint16_t startLED, uint16_t endLED, uint8_t red, uint8_t green ,uint8_t blue) { ws2812_rtn_t ws_result; if( (startLED > endLED) || (endLED > (numberOfPixels-1) ) ) { return (ws2812_invalid_LED_id); } /* Set RGB values for the first LED and then copy to the rest of them */ ws_result = ws2812_setRGB(startLED, red, green, blue); for(int i=1; i<=endLED-startLED; i++) { memcpy(&WS_frameBuffer[(startLED*WS_BYTES_PER_PIXEL)+(i*WS_BYTES_PER_PIXEL)+WS_ZOFFSET], &WS_frameBuffer[(startLED*WS_BYTES_PER_PIXEL)+WS_ZOFFSET],WS_BYTES_PER_PIXEL); } return (ws_result); } /* Send the latest frame buffer to the LEDs */ ws2812_rtn_t ws2812_update(void) { cy_rslt_t result; result = cyhal_spi_transfer(&ws2182SpiHandle, WS_frameBuffer, (numberOfPixels*WS_BYTES_PER_PIXEL)+WS_ZOFFSET, NULL, 0 , 0x00); if(result != CY_RSLT_SUCCESS) { return (ws2812_error); } return(ws2812_success); } /* This function takes an 8-bit value representing a color * and turns it into a WS2812 bit code... where 1=110 and 0=011 * 1 input byte turns into three output bytes of a uint32_t * */ static uint32_t WS_convert3Code(uint8_t input) { uint32_t rval=0; for(int i=0;i<8;i++) { if(input%2) { rval |= WS_ONE3; } else { rval |= WS_ZERO3; } rval = rval >> 3; input = input >> 1; } return rval; }
2.609375
3
2024-11-18T20:50:43.779278+00:00
2022-10-25T13:29:43
3d83f13a3c3719dc868a14247a1f924816928acf
{ "blob_id": "3d83f13a3c3719dc868a14247a1f924816928acf", "branch_name": "refs/heads/master", "committer_date": "2022-10-25T13:29:43", "content_id": "20bf589aa0717c95731a2fdbd9540b9414608ade", "detected_licenses": [ "MIT" ], "directory_id": "0246bebabd314dbf1c374fa3038f76d2cf8b2b14", "extension": "h", "filename": "cxdatelist.h", "fork_events_count": 9, "gha_created_at": "2018-01-30T19:20:07", "gha_event_created_at": "2021-01-11T17:56:51", "gha_language": "C++", "gha_license_id": "MIT", "github_id": 119582851, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5160, "license": "MIT", "license_type": "permissive", "path": "/isda/cxdatelist.h", "provenance": "stackv2-0110.json.gz:223887", "repo_name": "bakera1/CreditDefaultSwapPricer", "revision_date": "2022-10-25T13:29:43", "revision_id": "f85d1afaa1377d9e4b9db05da0eb9d154b1f548d", "snapshot_id": "1f1b974483ef66bea5ebb2f6d6941bf403b99314", "src_encoding": "UTF-8", "star_events_count": 20, "url": "https://raw.githubusercontent.com/bakera1/CreditDefaultSwapPricer/f85d1afaa1377d9e4b9db05da0eb9d154b1f548d/isda/cxdatelist.h", "visit_date": "2022-10-31T05:51:56.680290" }
stackv2
/* * ISDA CDS Standard Model * * Copyright (C) 2009 International Swaps and Derivatives Association, Inc. * Developed and supported in collaboration with Markit * * This program is free software: you can redistribute it and/or modify it * under the terms of the ISDA CDS Standard Model Public License. */ #ifndef CX_DATELIST_H #define CX_DATELIST_H #include "datelist.h" #ifdef __cplusplus extern "C" { #endif /*f *************************************************************************** ** Adds dates to a TDateList. ** ** If the original date list and date list to be added are sorted, then ** the resulting date list will be sorted and duplicate dates will be ** removed. Sorting assumes ascending order ([0] < [1] etc). ** ** If either of the inputs are not sorted, then the resulting date list ** will not be sorted, and some duplicates may remain. ** ** For efficiency, we do not automatically try to sort the resulting ** date list for unsorted inputs. Sorting the date list each time appears ** to be a huge performance issue in some algorithms (where the input ** dates would all be sorted anyway). ** ** Note that if dl is NULL, then this will create a new date list from ** the given dates. ** ** Note that if numItems=0, this will copy the given date list. *************************************************************************** */ TDateList* JpmcdsDateListAddDates (TDateList *dl, /* (I) Initial date list */ int numItems, /* (I) Number of dates to add */ TDate *array); /* (I) [numItems] Dates to be added */ /*f *************************************************************************** ** Adds dates to a TDateList and frees the input date list. ** ** If the original date list and date list to be added are sorted, then ** the resulting date list will be sorted and duplicate dates will be ** removed. Sorting assumes ascending order ([0] < [1] etc). ** ** If either of the inputs are not sorted, then the resulting date list ** will not be sorted, and some duplicates may remain. ** ** For efficiency, we do not automatically try to sort the resulting ** date list for unsorted inputs. Sorting the date list each time appears ** to be a huge performance issue in some algorithms (where the input ** dates would all be sorted anyway). ** ** Note that if dl is NULL, then this will create a new date list from ** the given dates. ** ** Note that if numItems=0, this will copy the given date list. ** ** The input date list is FREE'd by this routine. Thus if you have an ** algorithm which involves building up a datelist gradually, you can ** do something like this: ** ** TDateList* dl = NULL; ** ... ** dl = JpmcdsDateListAddDatesFreeOld (dl, numItems, array); ** if (dl == NULL) goto done; ** .. ** dl = JpmcdsDateListAddDatesFreeOld (dl, numItems, array); ** if (dl == NULL) goto done; ** .. ** etc. ** ** with the point being that you don't have to worry about the original ** date list at each step since this routine frees it for you. *************************************************************************** */ TDateList* JpmcdsDateListAddDatesFreeOld (TDateList *dl, /* (I/O) Initial date list - gets freed */ int numItems, /* (I) Number of dates to add */ TDate *array); /* (I) [numItems] Dates to be added */ /*f *************************************************************************** ** Truncates a date list at the specified date. The resulting date list ** will contain all dates previous to (or following) the specified date. ** Dates in the datelist which match the specified date may be optionally ** included. ** ** The datelist may optionally be modified in place or a new copy is ** returned. ** ** The input date list must be sorted. *************************************************************************** */ TDateList* JpmcdsDateListTruncate (TDateList *dateList, /* (I/O) Date list to be modified in place */ TDate truncationDate, /* (I) Date on which to perform trunctation */ TBoolean inclusive, /* (I) TRUE=include truncation date if in list*/ TBoolean excludeBefore, /* (I) TRUE=exclude dates before truncation date*/ TBoolean inPlace /* (I) TRUE=modify date list in place */ ); /*f *************************************************************************** ** Makes a date list from a given start date to a given end date with dates ** seperated by a given interval. ** ** Use the stub parameter to determine whether the stub appears at the ** start or the end of the date list, and whether the stub is long or ** short. ** ** The start date and end date are always both in the date list. ** The end date must be strictly after the start date. ** The date interval must be positive. *************************************************************************** */ TDateList* JpmcdsDateListMakeRegular (TDate startDate, /* (I) Start date */ TDate endDate, /* (I) End date */ TDateInterval *interval, /* (I) Date interval */ TStubMethod *stubType); /* (I) Stub type */ #ifdef __cplusplus } #endif #endif
2.3125
2
2024-11-18T20:50:43.851271+00:00
2023-04-16T11:33:17
6e284689035d4d6834591dfbab57d1b23012e0b7
{ "blob_id": "6e284689035d4d6834591dfbab57d1b23012e0b7", "branch_name": "refs/heads/master", "committer_date": "2023-04-16T11:38:43", "content_id": "11fad27bca562dd887a8ef189835b5f84da14d1f", "detected_licenses": [ "MIT" ], "directory_id": "7a3efa936a526b059c75e783e9df540d5373216c", "extension": "c", "filename": "fft.c", "fork_events_count": 6, "gha_created_at": "2014-01-10T15:14:00", "gha_event_created_at": "2017-10-09T09:28:32", "gha_language": "C", "gha_license_id": null, "github_id": 15801109, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1132, "license": "MIT", "license_type": "permissive", "path": "/test/fft.c", "provenance": "stackv2-0110.json.gz:224015", "repo_name": "detomon/bliplay", "revision_date": "2023-04-16T11:33:17", "revision_id": "f48e5adda7bf0551c9d45702a868e5065e2f1bce", "snapshot_id": "fbbc26718524d10dd8ec40fcedcaee09e0429025", "src_encoding": "UTF-8", "star_events_count": 18, "url": "https://raw.githubusercontent.com/detomon/bliplay/f48e5adda7bf0551c9d45702a868e5065e2f1bce/test/fft.c", "visit_date": "2023-08-31T15:05:57.322355" }
stackv2
#include "test.h" #include "BKFFT.h" int main (int argc, char const * argv []) { BKInt res; BKFFT * fft = INVALID_PTR; // the buffer will be 16 sample wide int n = 16; // sample buffer BKComplexComp x [n]; BKComplexComp y [n]; // create FFT object res = BKFFTAlloc (& fft, n); assert (res == 0); assert (fft != INVALID_PTR && fft != NULL); // fill samples // 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 for (BKInt i = 0; i < n; i ++) { x [i] = (i < 6) ? 1.0 : 0.0; y [i] = (i < 6) ? 1.0 : 0.0; } // fill whole buffer BKFFTSamplesLoad (fft, x, n, 0); // transform samples forward BKFFTTransform (fft, 0); // transform backwards BKFFTTransform (fft, BK_FFT_TRANS_INVERT); // print frequency domain which corresponds now to the input due to the // inversion (except some rounding noise) for (BKInt i = 0; i < fft -> numSamples; i ++) { BKComplex x = fft -> output [i]; BKComplexComp rex = BKComplexReal (x); BKComplexComp imx = BKComplexImag (x); BKComplexComp rey = y [i]; assert (BKAbs (rex - rey) <= 0.000001); assert (BKAbs (imx) <= 0.000001); } BKDispose (fft); return RESULT_PASS; }
2.546875
3
2024-11-18T20:50:43.931332+00:00
2020-02-10T05:33:51
b2d77a3db4d670ac83449aab099bc0a70ccd3727
{ "blob_id": "b2d77a3db4d670ac83449aab099bc0a70ccd3727", "branch_name": "refs/heads/master", "committer_date": "2020-02-10T05:33:51", "content_id": "b4ac8e829b9aeb953a6c50f6d8d7c1b3ddb9deca", "detected_licenses": [ "MIT" ], "directory_id": "e682028ada348f824ace8e2e92971223e070a81a", "extension": "c", "filename": "02-diamond.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 114603726, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 168, "license": "MIT", "license_type": "permissive", "path": "/hoisting/analysis/test/hoist/02-diamond.c", "provenance": "stackv2-0110.json.gz:224145", "repo_name": "Shreeasish/pledgerize-reboot", "revision_date": "2020-02-10T05:33:51", "revision_id": "cb3906af0c3dd98e1ec61def72f6e855e1e6a773", "snapshot_id": "0ad97ce1d5acc9d768eccc55a80df638b7ec0f1d", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Shreeasish/pledgerize-reboot/cb3906af0c3dd98e1ec61def72f6e855e1e6a773/hoisting/analysis/test/hoist/02-diamond.c", "visit_date": "2022-08-01T18:28:26.882301" }
stackv2
#include<stdio.h> int main() { int x; scanf("%d", &x); if(x%2){ printf("\nFrom if block"); } else { printf("\nFrom else block"); } return 0; }
2.671875
3
2024-11-18T20:50:44.002204+00:00
2020-10-01T19:39:13
d133b2ffa8766cd89b40a057fe4f12fd4b7582ac
{ "blob_id": "d133b2ffa8766cd89b40a057fe4f12fd4b7582ac", "branch_name": "refs/heads/master", "committer_date": "2020-10-01T19:39:13", "content_id": "0f5fc99ae463eabc3f32aebf5eea17927bbab68e", "detected_licenses": [ "MIT" ], "directory_id": "1080e88e3cbf9d00ec41aef94ab64d42849e87bb", "extension": "c", "filename": "rtime-scheduler.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 201663619, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5535, "license": "MIT", "license_type": "permissive", "path": "/Contiki-NG/rtime-scheduler/rtime-scheduler.c", "provenance": "stackv2-0110.json.gz:224273", "repo_name": "jugurthab/linux_embedded_articles", "revision_date": "2020-10-01T19:39:13", "revision_id": "cc0868cf0f84bdf51a3817f0a851cf772400d8c7", "snapshot_id": "d23a287e222b532f773ba2c6fed1ef37b8153a99", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/jugurthab/linux_embedded_articles/cc0868cf0f84bdf51a3817f0a851cf772400d8c7/Contiki-NG/rtime-scheduler/rtime-scheduler.c", "visit_date": "2021-07-13T15:08:03.188267" }
stackv2
#include "contiki.h" #include "random.h" #include "lib/list.h" // Liste qui contient nos tâches #include "sys/log.h" // Gestion de LOGS #define LOG_MODULE "RTimer" // Préfixe des logs (obligatoire) #define LOG_LEVEL LOG_LEVEL_INFO // Niveau de criticité des LOG (obligatoire) #define MAX_NB_SENSOR_TASKS_FIFO 3 // nombre de tâches #define MAX_SOUND_INTENSITY 150 #define MIN_SOUND_INTENSITY 0 #define MAX_TEMPERATURE_VALUE 75 #define MIN_TEMPERATURE_VALUE 30 // Définition du type des tâches (peut être remplacé par un enum) #define REQUESTED_READ_OPERATION_MOTOR_ROTATION 0 #define REQUESTED_READ_OPERATION_SOUND_INTENSITY 1 #define REQUESTED_READ_OPERATION_TEMPERATURE 2 // Déclaration et lancement du processus "rtime_sensor_reader_scheduler" PROCESS(rtime_sensor_reader_scheduler, "FIFO real time sensor reader scheduler"); AUTOSTART_PROCESSES(&rtime_sensor_reader_scheduler); static struct rtimer rtimer_timer; // Création d'un timer temps réel /* * Structure d'une tâche */ struct sensor_task { struct sensor_task *next_sensor; // Pointeur vers la prochaine tâche unsigned short requestReadOperation; // Indique le type de tâches (comme : REQUESTED_READ_OPERATION_MOTOR_ROTATION) int requestReadOperationValue; // Valeur de retourné par l'exécution de la tâche }; static struct sensor_task *firstSensorStructHeader; // Renvoie la tâche à exécuter volatile short isAllFifoTasksExecuted = 1; // Déclaration d'une liste avec le type sensor_task; // Le nom doit toujours être sous la forme "NOM_STRUCTURE + _list" LIST(sensor_task_list); // Fonction appelée par la taĉhe "Lecture Etat moteur" void displayMotorRorationStatus(struct sensor_task *s){ s->requestReadOperationValue = random_rand() & 1; // retourne 1 ou 0 (1 => moteur en rotation) LOG_INFO("L'état du moteur : %s\n", (s->requestReadOperationValue)?"on": "off"); } // Fonction appelée par la taĉhe "Mesure niveau sonore" void displaySoundIntensity(struct sensor_task *s){ s->requestReadOperationValue = random_rand() % (MAX_SOUND_INTENSITY + 1 - MIN_SOUND_INTENSITY) + MIN_SOUND_INTENSITY; LOG_INFO("Niveau sonore %d dB\n", ((int) s->requestReadOperationValue)); } // Fonction appelée par la taĉhe "Mesure de la température" void displayTemeratureValue(struct sensor_task *s){ s->requestReadOperationValue = random_rand() % (MAX_TEMPERATURE_VALUE + 1 - MIN_TEMPERATURE_VALUE) + MIN_TEMPERATURE_VALUE; LOG_INFO("Température %d °C\n", ((int) s->requestReadOperationValue)); } void sensor_read_operation_callback(struct rtimer *t, void *ptr) { struct sensor_task *sensors = ptr; switch(sensors->requestReadOperation){ // Décodage du type de la tâche case REQUESTED_READ_OPERATION_MOTOR_ROTATION: displayMotorRorationStatus(sensors); break; case REQUESTED_READ_OPERATION_SOUND_INTENSITY: displaySoundIntensity(sensors); break; case REQUESTED_READ_OPERATION_TEMPERATURE: displayTemeratureValue(sensors); break; default: break; } firstSensorStructHeader = list_item_next(firstSensorStructHeader); // Lire la prochaine tâche if(firstSensorStructHeader != NULL){ // S'il reste encore des tâches dans la liste, on réarme le timer rtimer_set(&rtimer_timer, RTIMER_NOW() + (RTIMER_SECOND/2), 1, sensor_read_operation_callback, firstSensorStructHeader); } else { isAllFifoTasksExecuted = 1; LOG_INFO("--------- (la pile est maintenant vide) -------------\n"); } } PROCESS_THREAD(rtime_sensor_reader_scheduler, ev, data) { PROCESS_BEGIN(); int i = 0; LOG_INFO("------- REAL TIME FIFO CONTIKI-NG SCHEDULER ----------\n"); list_init(sensor_task_list); // Initialisation de la liste qui contiendra nos tâches struct sensor_task sensorTasks[MAX_NB_SENSOR_TASKS_FIFO]; // Contient les tâches à exécuter random_init(0); // Pour la génération pseudo-aléatoire des valeurs des capteurs LOG_INFO("Remplissage initale de la liste\n"); for(i = 0; i < MAX_NB_SENSOR_TASKS_FIFO; i++){ // Assignation du type de la tâche (comme : REQUESTED_READ_OPERATION_SOUND_INTENSITY) sensorTasks[i].requestReadOperation = i; // La tâche ne contiens aucune valeur initialement. sensorTasks[i].requestReadOperationValue = 0; list_add(sensor_task_list, &sensorTasks[i]); // Ajouter la tâche à la liste } for(;;) { // Si première exécution ou si toutes les tâches ont été accomplies, ré-executer les tâches //LOG_INFO("LENGTH => %d, isAllFifoTasksExecuted=%d\n", list_length(sensor_task_list), isAllFifoTasksExecuted); if(isAllFifoTasksExecuted == 1){ isAllFifoTasksExecuted = -1; // Recherche du premier élément de la liste //if(firstSensorStructHeader==NULL) firstSensorStructHeader = list_head(sensor_task_list); /* Configuration d'un timer rtime et passage en paramètre de l'adresse * du premier élément de la liste. * le deuxième paramètre désigne le moment quand la tâche sera exécuté. * le troisième paramètre n'est pas utilisé pas Contiki-NG (en passe 1 en général). */ rtimer_set(&rtimer_timer, RTIMER_NOW() + (RTIMER_SECOND/2), 1, sensor_read_operation_callback, firstSensorStructHeader); } } PROCESS_END(); }
2.53125
3
2024-11-18T20:50:44.122414+00:00
2018-06-22T19:29:20
b5f8e94ca03e682a5b03a961e5aeede7d7058e42
{ "blob_id": "b5f8e94ca03e682a5b03a961e5aeede7d7058e42", "branch_name": "refs/heads/master", "committer_date": "2018-06-22T19:29:20", "content_id": "0596f26dc125dafbe38be732d7fb3435ce1223e1", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "cf9358206be39225ee7b21a7177157bf53e98784", "extension": "c", "filename": "array.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 126750803, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5764, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/sgermino/Ejer5/src/array.c", "provenance": "stackv2-0110.json.gz:224404", "repo_name": "royconejo/CESE_Prog_uC", "revision_date": "2018-06-22T19:29:20", "revision_id": "781ab17a11d957b5d1deb73383f5d05ad29b037a", "snapshot_id": "d9425569cf9d20cdd9d96b3d6536775b3085b805", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/royconejo/CESE_Prog_uC/781ab17a11d957b5d1deb73383f5d05ad29b037a/sgermino/Ejer5/src/array.c", "visit_date": "2021-04-18T20:32:51.524521" }
stackv2
/* RETRO-CIAA™ Library Copyright 2018 Santiago Germino (royconejo@gmail.com) Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "array.h" #include "variant.h" #include <string.h> bool ARRAY_Init (struct ARRAY *a, uint8_t *data, uint32_t capacity) { if (!a) { return false; } memset (a, 0, sizeof(struct ARRAY)); if (!data || !capacity) { return false; } a->data = data; a->capacity = capacity; return true; } void ARRAY_Reset (struct ARRAY *a) { if (a) { a->index = 0; } } uint32_t ARRAY_Elements (struct ARRAY *a) { return (a)? a->index : 0; } bool ARRAY_Full (struct ARRAY *a) { return (a && a->index == a->capacity - 1); } bool ARRAY_Append (struct ARRAY *a, uint8_t element) { if (ARRAY_Full(a)) { return false; } a->data[a->index ++] = element; return true; } bool ARRAY_AppendString (struct ARRAY *a, const char *str) { if (!a || !str) { return false; } while (*str) { if (!ARRAY_Append (a, (uint8_t)*str ++)) { return false; } } return true; } bool ARRAY_AppendBinary (struct ARRAY *a, const uint8_t *data, uint32_t size) { if (!a || !data || !size) { return false; } while (size --) { if (!ARRAY_Append (a, *data ++)) { return false; } } return true; } uint32_t ARRAY_RemoveChars (struct ARRAY *a, uint32_t count) { if (!a || !count || !a->index) { return 0; } uint32_t charsRemoved = 0; do { const uint8_t Byte = a->data[-- a->index]; // Quito bytes hasta encontrar un caracter unico (US-ASCII) o comienzo // de un caracter multibyte if (Byte <= 127 || Byte >= 192) { ++ charsRemoved; } if (charsRemoved >= count) { break; } } while (a->index); return charsRemoved; } bool ARRAY_Terminate (struct ARRAY *a) { if (!a) { return false; } a->data[a->index] = '\0'; return true; } bool ARRAY_CheckAlnumChars (struct ARRAY *a) { if (!a) { return false; } for (uint32_t i = 0; i < a->index; ++ i) { // Basic Latin if (a->data[i] < 128) { if ((a->data[i] >= '0' && a->data[i] <= '9') || (a->data[i] >= 'A' && a->data[i] <= 'Z') || (a->data[i] >= 'a' && a->data[i] <= 'z')) { continue; } } else if (i + 1 < a->index && ((a->data[i + 0] & 0b11100000) == 0b11000000) && ((a->data[i + 1] & 0b11000000) == 0b10000000)) { const uint16_t Code = (a->data[i + 0] & 0b00011111) << 6 | (a->data[i + 1] & 0b00111111); // Latin-1 Supplement if ((Code >= 0x00C0 && Code <= 0x00D6) || (Code >= 0x00D8 && Code <= 0x00F6) || (Code >= 0x00F8 && Code <= 0x00FF) || // Latin Extended-A (Code >= 0x0100 && Code <= 0x017F)) { ++ i; continue; } } return false; } return true; } bool ARRAY_CheckDecimalChars (struct ARRAY *a) { if (!a) { return false; } for (uint32_t i = 0; i < a->index; ++ i) { if (a->data[i] < '0' || a->data[i] > '9') { return false; } } return true; } bool ARRAY_CheckEqualContents (struct ARRAY *a, struct ARRAY *b) { if (!a || !b || a->index != b->index) { return false; } return !(memcmp (a->data, b->data, a->index))? true : false; } bool ARRAY_Copy (struct ARRAY *a, struct ARRAY *b) { if (!a || !b || !b->capacity || a->index >= b->capacity - 1) { return false; } memcpy (b->data, a->data, a->index); b->index = a->index; return true; } bool ARRAY_ToVariant (struct ARRAY *a, struct VARIANT *v) { if (!a || !v) { return false; } ARRAY_Terminate (a); VARIANT_SetString (v, (char *)a->data); return true; }
2.3125
2
2024-11-18T20:50:44.761621+00:00
2019-04-16T06:25:11
229ae93fd30f1f68324ddaf7bc71d4d2eb0eb4e6
{ "blob_id": "229ae93fd30f1f68324ddaf7bc71d4d2eb0eb4e6", "branch_name": "refs/heads/master", "committer_date": "2019-04-16T06:25:11", "content_id": "99876db4b5c1b36b0d9457ac97a653523a862ff6", "detected_licenses": [ "MIT" ], "directory_id": "7e91544574f2f8b5130ff1553864b5e14d1d0c91", "extension": "c", "filename": "cmd_delete.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": 4329, "license": "MIT", "license_type": "permissive", "path": "/src/nyocictl/cmd_delete.c", "provenance": "stackv2-0110.json.gz:225310", "repo_name": "williamsryan/libnyoci", "revision_date": "2019-04-16T06:25:11", "revision_id": "11a6e1b107cb1577cb0fffca7e3fd261f26da94a", "snapshot_id": "c46ce5fb3b596754902217c0dee6a8749c073dbd", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/williamsryan/libnyoci/11a6e1b107cb1577cb0fffca7e3fd261f26da94a/src/nyocictl/cmd_delete.c", "visit_date": "2022-01-17T22:06:09.660024" }
stackv2
/* * cmd_delete.c * LibNyoci * * Created by Robert Quattlebaum on 8/17/10. * Copyright 2010 deepdarc. All rights reserved. * */ /* This file is a total mess and needs to be cleaned up! */ #if HAVE_CONFIG_H #include <config.h> #endif #include "assert-macros.h" #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <libnyoci/libnyoci.h> #include <string.h> #include <sys/errno.h> #include "help.h" #include "cmd_delete.h" #include <libnyoci/url-helpers.h> #include <signal.h> #include "nyocictl.h" /* static arg_list_item_t option_list[] = { { 'h', "help",NULL,"Print Help" }, { 0 } }; */ static int gRet; static sig_t previous_sigint_handler; static bool delete_show_headers; /* static arg_list_item_t option_list[] = { { 'h', "help",NULL,"Print Help" }, { 'c', "content-file",NULL,"Use content from the specified input source" }, { 0 } }; */ static void signal_interrupt(int sig) { gRet = ERRORCODE_INTERRUPT; signal(SIGINT, previous_sigint_handler); } static nyoci_status_t delete_response_handler( int statuscode, void* context ) { if (statuscode >= 0) { char* content = (char*)nyoci_inbound_get_content_ptr(); coap_size_t content_length = nyoci_inbound_get_content_len(); if(content_length>(nyoci_inbound_get_packet_length()-4)) { fprintf(stderr, "INTERNAL ERROR: CONTENT_LENGTH LARGER THAN PACKET_LENGTH-4! (content_length=%u, packet_length=%u)\n",content_length,nyoci_inbound_get_packet_length()); gRet = ERRORCODE_UNKNOWN; goto bail; } if (delete_show_headers) { coap_dump_header( stdout, NULL, nyoci_inbound_get_packet(), nyoci_inbound_get_packet_length() ); } if(!coap_verify_packet((void*)nyoci_inbound_get_packet(), nyoci_inbound_get_packet_length())) { fprintf(stderr, "INTERNAL ERROR: CALLBACK GIVEN INVALID PACKET!\n"); gRet = ERRORCODE_UNKNOWN; goto bail; } if (statuscode != COAP_RESULT_202_DELETED) { fprintf(stderr, "delete: Result code = %d (%s)\n", statuscode, (statuscode < 0) ? nyoci_status_to_cstr( statuscode) : coap_code_to_cstr(statuscode)); } if(content && content_length) { char contentBuffer[500]; content_length = ((content_length > sizeof(contentBuffer) - 2) ? sizeof(contentBuffer) - 2 : content_length); memcpy(contentBuffer, content, content_length); contentBuffer[content_length] = 0; if(content_length && (contentBuffer[content_length - 1] == '\n')) contentBuffer[--content_length] = 0; printf("%s\n", contentBuffer); } } bail: if (gRet == ERRORCODE_INPROGRESS) { gRet = 0; } return NYOCI_STATUS_OK; } static nyoci_status_t resend_delete_request(const char* url) { nyoci_status_t status = 0; status = nyoci_outbound_begin(nyoci_get_current_instance(), COAP_METHOD_DELETE, COAP_TRANS_TYPE_CONFIRMABLE); require_noerr(status,bail); status = nyoci_outbound_set_uri(url, 0); require_noerr(status,bail); status = nyoci_outbound_send(); require_noerr(status,bail); gRet = ERRORCODE_INPROGRESS; bail: return status; } static nyoci_transaction_t send_delete_request( nyoci_t nyoci, const char* url ) { nyoci_transaction_t ret; gRet = ERRORCODE_INPROGRESS; ret = nyoci_transaction_init( NULL, NYOCI_TRANSACTION_ALWAYS_INVALIDATE, // Flags (void*)&resend_delete_request, &delete_response_handler, (void*)url ); nyoci_transaction_begin(nyoci, ret, 30*MSEC_PER_SEC); bail: return ret; } int tool_cmd_delete( nyoci_t nyoci, int argc, char* argv[] ) { previous_sigint_handler = signal(SIGINT, &signal_interrupt); nyoci_transaction_t transaction; char url[1000] = ""; if((2 == argc) && (0 == strcmp(argv[1], "--help"))) { printf("Help not yet implemented for this command.\n"); return ERRORCODE_HELP; } gRet = ERRORCODE_UNKNOWN; if (getenv("NYOCI_CURRENT_PATH")) { strncpy(url, getenv("NYOCI_CURRENT_PATH"), sizeof(url)); } if (argc == 2) { url_change(url, argv[1]); } else { fprintf(stderr, "Bad args.\n"); gRet = ERRORCODE_BADARG; goto bail; } require((transaction=send_delete_request(nyoci, url)), bail); gRet = ERRORCODE_INPROGRESS; while(ERRORCODE_INPROGRESS == gRet) { nyoci_plat_wait(nyoci, 1000); nyoci_plat_process(nyoci); } nyoci_transaction_end(nyoci, transaction); bail: signal(SIGINT, previous_sigint_handler); return gRet; }
2.09375
2
2024-11-18T20:50:44.826098+00:00
2021-11-09T15:13:14
4c6b151edca5b3ddf4667b7328d1d73b01d24dd2
{ "blob_id": "4c6b151edca5b3ddf4667b7328d1d73b01d24dd2", "branch_name": "refs/heads/master", "committer_date": "2021-11-09T15:13:14", "content_id": "bd1a3e949d0412d01182e34b4fe55901f51f915f", "detected_licenses": [ "MIT" ], "directory_id": "d5d4a050413ac580325ce4a03fd5041638e17154", "extension": "h", "filename": "gencode.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 240193718, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 8579, "license": "MIT", "license_type": "permissive", "path": "/程序/gencode.h", "provenance": "stackv2-0110.json.gz:225443", "repo_name": "yukihuang422/ECNU-CX0-compiler", "revision_date": "2021-11-09T15:13:14", "revision_id": "a20555192608c6b083863cf24f64d9ebde081bd3", "snapshot_id": "b974d21f1b015be79a6efb88a43ecf4b6371932c", "src_encoding": "UTF-8", "star_events_count": 3, "url": "https://raw.githubusercontent.com/yukihuang422/ECNU-CX0-compiler/a20555192608c6b083863cf24f64d9ebde081bd3/程序/gencode.h", "visit_date": "2021-12-03T06:10:23.426668" }
stackv2
#include "table.h" #define CODE_LEN_MAX 1000 /* 中间代码长度不得超过 1000 行 */ int code_index; int error_count = 0; int break_adr = -1; int continue_adr = -1; int switch_num; enum func { lit, opr, lod, sto, cal, ini, jmp, jpc, ast, ald }; /* 指令名 */ char *mnemonic[8]={ "lit", "opr", "lod", "sto", "cal", "ini", "jmp", "jpc" }; FILE *middle_code_file, *error_file, *stack_data_file; FILE *fin; char src_file_name[512]; /* PATH_MAX defined in limits.h and equals 1024(*nix) or 512(Windows) */ int show_code_lists = 1; /* 默认显示生成的中间代码 */ struct INSTRUCTION { enum func f; int lev; int adr; } code[CODE_LEN_MAX + 1]; extern int line; void error(int error_no) { // error_count++; // in function yyerror error_count has added it self. switch(error_no) { case 0: printf("character not defined."); fprintf(error_file, "character not defined."); break; case 1: printf("function not declared. "); fprintf(error_file, "function not declared. "); break; case 2: printf("function name has been used as a variable or constant. "); fprintf(error_file, "function name has been used as a variable or constant. "); break; case 3: printf("variable or constant cannot be used as a function. "); fprintf(error_file, "variable or constant cannot be used as a function. "); break; case 4: printf("function cannot be used in arithmetic or logic operations. "); fprintf(error_file, "function cannot be used in arithmetic or logic operations. "); break; case 5: printf("the name of identfier have been declared before. "); fprintf(error_file, "the name of identfier have been declared before. "); break; case 6: printf("Only variable can add or minus self."); fprintf(error_file, "Only variable can add or minus self."); break; case 7: printf("multiply exceeds the range of int"); fprintf(error_file, "multiply exceeds the range of int"); break; case 8: printf("divided by zero"); fprintf(error_file, "divided by zero"); break; case 9: printf("add operation exceeds the range of int"); fprintf(error_file, "add operation exceeds the range of int"); break; case 10: printf("continue should't used here"); fprintf(error_file, "continue should't used here"); break; case 11: printf("\n"); fprintf(error_file, "\n"); break; case 12: printf("wrong array"); break; case 31: printf("number exceeds 2147483647."); fprintf(error_file, "number exceeds 2147483647."); break; case 32: printf("stack overflow"); fprintf(error_file, "stack overflow."); break; default: printf("error%d", error_no); fprintf(error_file, "error%d", error_no); break; } yyerror(""); } void gen_middle_code(enum func f, int lev, int adr) { if(code_index > CODE_LEN_MAX) printf("Program too long.\n"); code[code_index].f = f; code[code_index].lev = lev; code[code_index++].adr = adr; } void print_middle_code() /* 打印所有生成代码 */ { int i; if(show_code_lists) { for(i = 1; i <= code_index - 1; ++i) { printf("%2d %5s %3d %5d\n", i, mnemonic[(int)code[i].f], code[i].lev, code[i].adr); fprintf(middle_code_file, "%2d %5s %3d %5d\n", i, mnemonic[(int)code[i].f], code[i].lev, code[i].adr); } } } int base(int lev, int b, int s[STACK_SIZE]) /* STACK_SIZE = 500 */ /* b 为基地址, lev 为层号 返回调用层的基地址 */ { int call_base = b; while(lev > 0){ call_base = s[call_base]; lev--; } return call_base; } void interpret() { int p = 0; /* 指令 index */ int b = 1; /* 基地址 */ int t = 0; /* 栈顶 */ struct INSTRUCTION ins; int s[STACK_SIZE]; printf("******** Start My Compiler *********\n"); s[0] = 0; s[1] = 0; s[2] = 0; s[3] = 0; do { ins = code[p]; p++; switch(ins.f) { case lit: t++; s[t] = ins.adr; break; case opr: switch(ins.adr) { case 0: t = b - 1; p = s[t + 3]; b = s[t + 2]; break; case 1: // -a s[t] = -s[t]; break; case 2: // + t--; if(s[t] > 0 && s[t + 1] > 0 && s[t] + s[t + 1] < 0) { error(9); exit(-1); } else if(s[t] < 0 && s[t + 1] < 0 && s[t] + s[t + 1] > 0) { error(9); exit(-1); } else { s[t] = s[t] + s[t + 1]; } break; case 3: // - t--; s[t] = s[t] - s[t + 1]; break; case 4: // * t--; if(s[t] > 0 && s[t + 1] > 0 && s[t] * s[t + 1] < 0) { error(7); exit(-1); } else if(s[t] < 0 && s[t + 1] < 0 && s[t] * s[t + 1] > 0) { error(7); exit(-1); } else { s[t] = s[t] * s[t + 1]; } break; case 5: // divide t--; if(s[t + 1] == 0) { error(8); exit(-1); } else s[t] = s[t] / s[t + 1]; break; case 6: // % t--; s[t] = s[t] % s[t + 1]; break; case 7: /* ODD, 奇数为1,偶数为0 */ s[t] = ((s[t] & 1) ? 1 : 0); break; case 8: /* eql */ t--; s[t] = ((s[t] == s[t + 1]) ? 1 : 0); break; case 9: /* neq */ t--; s[t] = ((s[t] != s[t + 1]) ? 1 : 0); break; case 10: t--; s[t] = ((s[t] < s[t + 1]) ? 1 : 0); break; case 11: t--; s[t] = ((s[t] >= s[t + 1]) ? 1 : 0); break; case 12: /* gtr */ t--; s[t] = ((s[t] > s[t + 1]) ? 1 : 0); break; case 13: t--; s[t] = ((s[t] <= s[t + 1]) ? 1 : 0); break; case 14: /* write */ printf("%d\n", s[t]); /* 输出栈顶内容 */ fprintf(stack_data_file, "%d\n", s[t]); t--; break; case 15: // XOR t--; s[t] = s[t] ^ s[t + 1]; break; case 16: /* read */ t++; printf("input: "); fprintf(stack_data_file, "input: "); scanf("%d", &s[t]); fprintf(stack_data_file, "%d", s[t]); break; case 17: /* or */ t--; s[t] = s[t] || s[t + 1]; break; case 18: /* and */ t--; s[t] = s[t] && s[t + 1]; break; case 19: /* not */ s[t] = (s[t] == 1) ? 0 : 1; break; case 20: /* case*/1;bap cfsmi if(s[t] == s[t-1]) s[t] = 1; else s[t] = 0; break; } break; case lod: t++; s[t] = s[base(ins.lev, b, s) + ins.adr]; break; case sto: s[base(ins.lev, b, s) + ins.adr] = s[t]; t--; break; case cal: s[t + 1] = base(ins.lev, b, s); s[t + 2] = b; s[t + 3] = p; b = t + 1; p = ins.adr; break; case ini: t = t + ins.adr; break; case jmp: p = ins.adr; break; case jpc: if(s[t] == 0) p = ins.adr; t--; break; case ast: s[base(ins.lev,b,s)+ins.adr+s[t-1]] = s[t]; //stack(); t -= 2; break; case ald: s[t] = s[base(ins.lev,b,s)+ins.adr+s[t]]; break; } } while(p != 0); printf("\n****** End My Compiler ********\n"); fclose(stack_data_file); }
2.59375
3
2024-11-18T20:50:45.068490+00:00
2018-10-02T17:39:25
69b016855d800453e0bf1374756f1b70d7a4a6f0
{ "blob_id": "69b016855d800453e0bf1374756f1b70d7a4a6f0", "branch_name": "refs/heads/master", "committer_date": "2018-10-02T17:39:25", "content_id": "4d4a4eeb06504717b8d04dcf9bfb94bb88a1d805", "detected_licenses": [ "MIT" ], "directory_id": "48cc107594d00f44a9d1e407658dcd3065e04a22", "extension": "c", "filename": "parsing_reading_info.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": 2264, "license": "MIT", "license_type": "permissive", "path": "/asm/parsing_reading_info.c", "provenance": "stackv2-0110.json.gz:225708", "repo_name": "bastienrinck/2016_Corewar", "revision_date": "2018-10-02T17:39:25", "revision_id": "fe52c44acf8cd97a8481ed5a458db0139fb2153a", "snapshot_id": "729636d1b7a0a30dfa6fb24209132da1058d54c3", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/bastienrinck/2016_Corewar/fe52c44acf8cd97a8481ed5a458db0139fb2153a/asm/parsing_reading_info.c", "visit_date": "2021-09-24T03:38:01.376478" }
stackv2
/* ** parsing_reading_info.c for parsing_reading_info.c in /home/romain/delivery/CPE_2016_corewar ** ** Made by Romain LANCIA ** Login <romain.lancia@epitech.eu@epitech.net> ** ** Started on Mon Mar 20 13:55:43 2017 Romain LANCIA ** Last update Thu Mar 30 10:04:55 2017 Thibaut Cornolti */ #include <stdio.h> #include <stdlib.h> #include "my.h" #include "asm.h" static void my_memncpy(void *dest, void *src, int n) { char *dests; char *srcs; int i; dests = dest; srcs = src; i = -1; while (++i < n) dests[i] = srcs[i]; } static void my_put_in_list(t_data **list, char inst, t_arg arg[3]) { t_data *elem; t_data *tmp; if ((elem = malloc(sizeof(t_data))) == NULL) return ; tmp = *list; while (tmp && tmp->next) tmp = tmp->next; elem->next = NULL; elem->inst = inst; my_memncpy(elem->arg, arg, sizeof(t_arg) * 3); if (tmp) tmp->next = elem; else *list = elem; } char get_inst(char *s) { const char *insts[16] = {"live", "ld", "st", "add", "sub", "and", "or", "xor", "zjmp", "ldi", "sti", "fork", "lld", "lldi", "lfork", "aff"}; int i; i = -1; if (!s) return (0); while (++i < 16) if (!my_strcmp(s, (char *) insts[i])) return (i + 1); return (0); } static int check_label(char *lname, t_label **babybel, int fill) { if (get_inst(lname)) return (0); lname[my_strlen(lname) - 1] = 0; if (check_good_label(lname)) { if (!fill) return (1); else if ((label(my_strdup(lname), babybel)) == 84) { my_puterror(lname); my_puterror(": Multiple definition of the same label.\n"); exit(0); } else return (1); } return (0); } int get_info_line(char *line, t_data **list, t_label **babybel, int fill) { int i; int t; char **tab; t_arg arg[3]; my_memset(arg, 0, sizeof(t_arg) * 3); if (!line || !line[0]) return (0); tab = my_strsplit(line, " ,\t"); i = 1; tab += check_label(tab[0], babybel, fill); if (!*tab) return (0); while (tab[i] != NULL && i <= 3) { arg[i - 1].type = verify_type_arg(tab[i], &t, *babybel); arg[i - 1].arg = t; i++; } my_put_in_list(list, get_inst(tab[0]), arg); decrease_label(*babybel, *list); return (0); }
2.625
3
2024-11-18T20:50:45.435159+00:00
2022-11-30T06:23:24
aefecaf1bce1c9535b7e003f75a50e4b9353b240
{ "blob_id": "aefecaf1bce1c9535b7e003f75a50e4b9353b240", "branch_name": "refs/heads/master", "committer_date": "2022-11-30T06:23:24", "content_id": "6da321326695807d26a9faec52ed351af32827fe", "detected_licenses": [ "MIT" ], "directory_id": "15f0514701a78e12750f68ba09d68095172493ee", "extension": "c", "filename": "10.c", "fork_events_count": 365, "gha_created_at": "2018-11-03T06:47:38", "gha_event_created_at": "2021-11-15T04:02:45", "gha_language": null, "gha_license_id": "MIT", "github_id": 155958163, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5490, "license": "MIT", "license_type": "permissive", "path": "/C/10.c", "provenance": "stackv2-0110.json.gz:225836", "repo_name": "strengthen/LeetCode", "revision_date": "2022-11-30T06:23:24", "revision_id": "3ffa6dcbeb787a6128641402081a4ff70093bb61", "snapshot_id": "5e38c8c9d3e8f27109b9124ae17ef8a4139a1518", "src_encoding": "UTF-8", "star_events_count": 936, "url": "https://raw.githubusercontent.com/strengthen/LeetCode/3ffa6dcbeb787a6128641402081a4ff70093bb61/C/10.c", "visit_date": "2022-12-04T21:35:17.872212" }
stackv2
__________________________________________________________________________________________________ sample 0 ms submission bool isMatch_helper(char *cachedResult, int sLen, int pLen, char *originS, char *originP, char * s, char * p) { int sOffset = s - originS; int pOffset = p - originP; int index = sOffset * pLen + pOffset; /* printf("cachedResult sLen:%d pLen:%d sOffset:%d pOffset:%d index:%d\n", sLen, pLen, sOffset, pOffset, index); */ if (cachedResult[index] != -1) { return cachedResult[index]; } // printf("s:%s p:%s\n", s, p); if (!*s && !*p) { cachedResult[index] = true; return cachedResult[index]; } if (!*p && *s) { cachedResult[index] = false; return cachedResult[index]; } if (!*s) { if (*(p+1) == '*') { cachedResult[index] = isMatch_helper(cachedResult, sLen, pLen, originS, originP, s, p+2); return cachedResult[index]; } else { cachedResult[index] = false; return cachedResult[index]; } } if (*(p+1) == '*') { if (*s == *p || *p == '.') { cachedResult[index] = (isMatch_helper(cachedResult, sLen, pLen, originS, originP, s, p+2) || isMatch_helper(cachedResult, sLen, pLen, originS, originP, s+1, p)); return cachedResult[index]; } else { cachedResult[index] = (isMatch_helper(cachedResult, sLen, pLen, originS, originP, s, p+2)); return cachedResult[index]; } } else { if (*s == *p || *p == '.') { cachedResult[index] = (isMatch_helper(cachedResult, sLen, pLen, originS, originP, s+1, p+1)); return cachedResult[index]; } } cachedResult[index] = false; return cachedResult[index]; } bool isMatch(char * s, char * p) { char *cachedResult; int sLen = strlen(s)+1; int pLen = strlen(p)+1; int aSize = sLen * pLen; // printf("sLen:%d pLen:%d aSize:%d", sLen, pLen, aSize); // printf("Allocating memory of size:%d\n", aSize); cachedResult = (char *) malloc(sizeof(char) * aSize); memset(cachedResult, -1, aSize); // printf("After initializing cachedResult\n"); bool result = isMatch_helper(cachedResult, sLen, pLen, s, p, s, p); free(cachedResult); return result; } __________________________________________________________________________________________________ sample 4 ms submission bool isMatch(char *s, char *p){ int i; int ls = strlen(s); int lp = strlen(p); bool* m = malloc((ls + 1) * sizeof(bool)); // init m[0] = true; for (i = 1; i <= ls; i++) { m[i] = false; } int ip; for (ip = 0; ip < lp; ip++) { if (ip + 1 < lp && p[ip + 1] == '*') { // do nothing } else if (p[ip] == '*') { char c = p[ip - 1]; for (i = 1; i <= ls; i++) { m[i] = m[i] || (m[i - 1] && (s[i - 1] == c || c == '.')); } } else { char c = p[ip]; for (i = ls; i > 0; i--) { m[i] = m[i - 1] && (s[i - 1] == c || c == '.'); } m[0] = false; } } bool ret = m[ls]; free(m); return ret; } __________________________________________________________________________________________________ sample 6524 kb submission bool isMatch(char* s, char* p) { if (*p == '\0') return *s == '\0'; if (*(p + 1) != '*') { return (*p == *s || (*p == '.' && *s != '\0')) && isMatch(s + 1, p + 1); } else { while (*p == *s || (*p == '.' && *s != '\0')) { if (isMatch(s, p + 2)) return true; ++s; } return isMatch(s, p + 2); } } __________________________________________________________________________________________________ sample 6592 kb submission bool matchFirstChar(const char *t, const char *p) { if (*t == *p || *p == '.' && *t != '\0') return true; else return false; } bool isMatch(char *t, char *p) { if (*p == '\0') return *t == '\0'; if (*(p+1) != '*') { if (matchFirstChar(t, p)) return isMatch(t+1, p+1); else return false; } else { if (isMatch(t, p+2)) return true; // else while (matchFirstChar(t, p)) { if (isMatch(t+1, p+2)) return true; ++t; } return false; } } __________________________________________________________________________________________________ sample 6604 kb submission bool isMatch(char* s, char* p) { char *prev, *cur; int first_match; int len; len = strlen(p); if (*p == '\0') { if (*s != '\0') { return false; } else { return true; } } if (*s == '\0') { if (len >= 2 && *(p + 1) == '*') { return isMatch(s, p + 2); } return false; } if (*p == '.' || *p == *s) { first_match = true; } else { first_match = false; } if (len >= 2 && *(p + 1) == '*') { return isMatch(s, p + 2) || (first_match && isMatch(s + 1, p)); } else { return first_match && isMatch(s + 1, p + 1); } } __________________________________________________________________________________________________
2.765625
3
2024-11-18T20:50:45.899536+00:00
2017-10-30T20:03:17
fc39b740675e38cea8ded8fad1656bf1d5fc0205
{ "blob_id": "fc39b740675e38cea8ded8fad1656bf1d5fc0205", "branch_name": "refs/heads/master", "committer_date": "2017-10-30T20:03:17", "content_id": "1f2067671ca8b16c84bb85fff19d01837e97a629", "detected_licenses": [ "MIT" ], "directory_id": "33b8fbee6a3d0d5c0f03faccd757c9e8e96a0059", "extension": "h", "filename": "sql_schema.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": 1036, "license": "MIT", "license_type": "permissive", "path": "/src/sql_schema.h", "provenance": "stackv2-0110.json.gz:226100", "repo_name": "justinhachemeister/tristramd", "revision_date": "2017-10-30T20:03:17", "revision_id": "636783c00b601780a22f1ebe8b705ff9cf9047a9", "snapshot_id": "7eda522696138fe75ba4768c4fc5d28847dd158f", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/justinhachemeister/tristramd/636783c00b601780a22f1ebe8b705ff9cf9047a9/src/sql_schema.h", "visit_date": "2020-04-13T13:54:54.693814" }
stackv2
#ifndef SQL_SCHEMA_H_ #define SQL_SCHEMA_H_ typedef void *(*sql_schema_alloc_cb)(void); typedef void (*sql_schema_free_cb)(void *); enum sql_type { SQL_TYPE_BOOL = 0, SQL_TYPE_SHORT = 1, SQL_TYPE_INT = 2, SQL_TYPE_LONG = 3, SQL_TYPE_SERIAL = 4, SQL_TYPE_STRING = 5, }; struct sql_schema { char *table_name; sql_schema_alloc_cb alloc_cb; sql_schema_free_cb free_cb; Eina_List *fields; }; struct sql_schema_field { char *field_name; enum sql_type type; unsigned int length; char required; void *default_value; }; #define SQL_ALLOC_CAST_CB(cb) (void *(*)(void))cb #define SQL_FREE_CAST_CB(cb) (void (*)(void *))cb struct sql_schema *sql_schema_new(const char *table_name, sql_schema_alloc_cb alloc_cb, sql_schema_free_cb free_cb); void sql_schema_free(struct sql_schema *schema); void schema_add_field(struct sql_schema *schema, const char *field_name, enum sql_type type, unsigned int length, char required, void *default_value); void schema_add_default_fields(struct sql_schema *schema); #endif
2.171875
2
2024-11-18T20:50:47.062493+00:00
2018-10-09T04:06:45
fdd20fa95bb4e31d4b8d081acfc3cf44290b11a4
{ "blob_id": "fdd20fa95bb4e31d4b8d081acfc3cf44290b11a4", "branch_name": "refs/heads/master", "committer_date": "2018-10-09T04:06:45", "content_id": "f4b578f06b27192511cfc1427e9a6803c50cdc22", "detected_licenses": [ "BSD-3-Clause", "MIT" ], "directory_id": "4c4fa620d2596107511a28344a8669e3a3882ca2", "extension": "c", "filename": "usb-test.c", "fork_events_count": 0, "gha_created_at": "2018-10-09T03:07:31", "gha_event_created_at": "2018-10-09T03:07:31", "gha_language": null, "gha_license_id": "NOASSERTION", "github_id": 152179854, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3546, "license": "BSD-3-Clause,MIT", "license_type": "permissive", "path": "/system/utest/usb/usb-test.c", "provenance": "stackv2-0110.json.gz:226878", "repo_name": "gwli/zircon", "revision_date": "2018-10-09T04:06:45", "revision_id": "89373ffafd812c36f9a2c85f748b584121fe7902", "snapshot_id": "84652564887bc09f7877249e1d123b36fd7d9225", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/gwli/zircon/89373ffafd812c36f9a2c85f748b584121fe7902/system/utest/usb/usb-test.c", "visit_date": "2020-03-31T11:30:43.971824" }
stackv2
// Copyright 2018 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <unittest/unittest.h> #include <zircon/device/usb-tester.h> #include <dirent.h> #include <fcntl.h> #include <unistd.h> #define USB_TESTER_DEV_DIR "/dev/class/usb-tester" #define ISOCH_MIN_PASS_PERCENT 80 #define ISOCH_MIN_PACKETS 10lu static zx_status_t open_test_device(int* out_fd) { DIR* d = opendir(USB_TESTER_DEV_DIR); if (d == NULL) { return ZX_ERR_BAD_STATE; } struct dirent* de; while ((de = readdir(d)) != NULL) { int fd = openat(dirfd(d), de->d_name, O_RDWR); if (fd < 0) { continue; } *out_fd = fd; closedir(d); return ZX_OK; } closedir(d); return ZX_ERR_NOT_FOUND; } static bool usb_bulk_loopback_test(void) { BEGIN_TEST; int dev_fd; if (open_test_device(&dev_fd) != ZX_OK) { unittest_printf_critical(" [SKIPPING]"); return true; } ASSERT_GE(dev_fd, 0, "invalid device fd"); usb_tester_params_t params = { .data_pattern = USB_TESTER_DATA_PATTERN_CONSTANT, .len = 64 * 1024 }; ASSERT_EQ(ioctl_usb_tester_bulk_loopback(dev_fd, &params), ZX_OK, "bulk loopback failed: USB_TESTER_DATA_PATTERN_CONSTANT 64 K"); params.data_pattern = USB_TESTER_DATA_PATTERN_RANDOM; ASSERT_EQ(ioctl_usb_tester_bulk_loopback(dev_fd, &params), ZX_OK, "bulk loopback failed: USB_TESTER_DATA_PATTERN_RANDOM 64 K"); close(dev_fd); END_TEST; } static bool usb_isoch_verify_result(usb_tester_params_t* params, usb_tester_result_t* result) { BEGIN_HELPER; ASSERT_GT(result->num_packets, 0lu, "didn't transfer any isochronous packets"); // Isochronous transfers aren't guaranteed, so just require a high enough percentage to pass. ASSERT_GE(result->num_packets, ISOCH_MIN_PACKETS, "num_packets is too low for a reliable result, should request more bytes"); double percent_passed = ((double)result->num_passed / result->num_packets) * 100; ASSERT_GE(percent_passed, ISOCH_MIN_PASS_PERCENT, "not enough isoch transfers succeeded"); END_HELPER; } static bool usb_isoch_loopback_test(void) { BEGIN_TEST; int dev_fd; if (open_test_device(&dev_fd) != ZX_OK) { unittest_printf_critical(" [SKIPPING]"); return true; } ASSERT_GE(dev_fd, 0, "Invalid device fd"); usb_tester_params_t params = { .data_pattern = USB_TESTER_DATA_PATTERN_CONSTANT, .len = 64 * 1024 }; char err_msg1[] = "isoch loopback failed: USB_TESTER_DATA_PATTERN_CONSTANT 64 K"; usb_tester_result_t result = {}; ASSERT_EQ(ioctl_usb_tester_isoch_loopback(dev_fd, &params, &result), (ssize_t)(sizeof(result)), err_msg1); ASSERT_TRUE(usb_isoch_verify_result(&params, &result), err_msg1); char err_msg2[] = "isoch loopback failed: USB_TESTER_DATA_PATTERN_RANDOM 64 K"; params.data_pattern = USB_TESTER_DATA_PATTERN_RANDOM; ASSERT_EQ(ioctl_usb_tester_isoch_loopback(dev_fd, &params, &result), (ssize_t)(sizeof(result)), err_msg2); ASSERT_TRUE(usb_isoch_verify_result(&params, &result), err_msg2); close(dev_fd); END_TEST; } BEGIN_TEST_CASE(usb_tests) RUN_TEST(usb_bulk_loopback_test) RUN_TEST(usb_isoch_loopback_test) END_TEST_CASE(usb_tests) int main(int argc, char** argv) { return unittest_run_all_tests(argc, argv) ? 0 : -1; }
2.34375
2
2024-11-18T20:50:47.273170+00:00
2020-05-04T23:07:57
31443283efeff8b05384efac343caabcd2b13d75
{ "blob_id": "31443283efeff8b05384efac343caabcd2b13d75", "branch_name": "refs/heads/master", "committer_date": "2020-05-04T23:07:57", "content_id": "42064e5b59840fce07b8457a0a7c4e45c6f6c484", "detected_licenses": [ "MIT" ], "directory_id": "7b8880f3ec5f7b6d5d621becf326803670ab51ea", "extension": "c", "filename": "HCData.c", "fork_events_count": 1, "gha_created_at": "2020-03-27T00:30:03", "gha_event_created_at": "2020-03-27T00:30:04", "gha_language": null, "gha_license_id": null, "github_id": 250403984, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 6193, "license": "MIT", "license_type": "permissive", "path": "/Source/Data/HCData.c", "provenance": "stackv2-0110.json.gz:227135", "repo_name": "dstoker-cricut/HollowCore", "revision_date": "2020-05-04T23:07:57", "revision_id": "87ecdd0640fa4504c42394ffc3039cfd809c81a9", "snapshot_id": "466c212809899996d2e3f9cdf573b6af3bbb735f", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/dstoker-cricut/HollowCore/87ecdd0640fa4504c42394ffc3039cfd809c81a9/Source/Data/HCData.c", "visit_date": "2022-06-04T22:44:32.269878" }
stackv2
// // HCData.c // Test // // Created by Matt Stoker on 1/19/19. // Copyright © 2019 HollowCore. All rights reserved. // #include "HCData_Internal.h" #include <string.h> #include <math.h> //---------------------------------------------------------------------------------------------------------------------------------- // MARK: - Object Type //---------------------------------------------------------------------------------------------------------------------------------- const HCObjectTypeData HCDataTypeDataInstance = { .base = { .ancestor = &HCObjectTypeDataInstance.base, .name = "HCData", }, .isEqual = (void*)HCDataIsEqual, .hashValue = (void*)HCDataHashValue, .print = (void*)HCDataPrint, .destroy = (void*)HCDataDestroy, }; HCType HCDataType = (HCType)&HCDataTypeDataInstance; //---------------------------------------------------------------------------------------------------------------------------------- // MARK: - Construction //---------------------------------------------------------------------------------------------------------------------------------- HCDataRef HCDataCreate() { return HCDataCreateWithBytes(0, NULL); } HCDataRef HCDataCreateWithBytes(HCInteger size, const HCByte* bytes) { HCDataRef self = calloc(sizeof(HCData), 1); HCDataInit(self, size, bytes); return self; } HCDataRef HCDataCreateWithBoolean(HCBoolean value) { return HCDataCreateWithBytes(sizeof(value), (HCByte*)&value); } HCDataRef HCDataCreateWithInteger(HCInteger value) { return HCDataCreateWithBytes(sizeof(value), (HCByte*)&value); } HCDataRef HCDataCreateWithReal(HCReal value) { return HCDataCreateWithBytes(sizeof(value), (HCByte*)&value); } void HCDataInit(void* memory, HCInteger size, const HCByte* data) { HCByte* dataCopy = malloc(size); if (data != NULL) { memcpy(dataCopy, data, size); } HCDataInitWithoutCopying(memory, size, dataCopy); } void HCDataInitWithoutCopying(void* memory, HCInteger size, HCByte* data) { HCObjectInit(memory); HCDataRef self = memory; self->base.type = HCDataType; self->size = size; self->data = data; } void HCDataDestroy(HCDataRef self) { free(self->data); } //---------------------------------------------------------------------------------------------------------------------------------- // MARK: - Object Polymorphic Functions //---------------------------------------------------------------------------------------------------------------------------------- HCBoolean HCDataIsEqual(HCDataRef self, HCDataRef other) { if (self->size != other->size) { return false; } return memcmp(self->data, other->data, self->size) == 0; } HCInteger HCDataHashValue(HCDataRef self) { HCInteger hash = 5381; for (HCInteger byteIndex = 0; byteIndex < self->size; byteIndex++) { HCByte b = self->data[byteIndex]; hash = ((hash << 5) + hash) + b; } return hash; } void HCDataPrint(HCDataRef self, FILE* stream) { fprintf(stream, "<%s@%p,size:%li>", self->base.type->name, self, (long)self->size); } //---------------------------------------------------------------------------------------------------------------------------------- // MARK: - Attributes //---------------------------------------------------------------------------------------------------------------------------------- HCBoolean HCDataIsEmpty(HCDataRef self) { return HCDataSize(self) == 0; } HCInteger HCDataSize(HCDataRef self) { return self->size; } const HCByte* HCDataBytes(HCDataRef self) { return self->data; } //---------------------------------------------------------------------------------------------------------------------------------- // MARK: - Conversion //---------------------------------------------------------------------------------------------------------------------------------- HCBoolean HCDataIsBoolean(HCDataRef self) { return self->size == (HCInteger)sizeof(HCBoolean) && (self->data[0] == 0 || self->data[0] == 1); } HCBoolean HCDataAsBoolean(HCDataRef self) { return self->size > (HCInteger)sizeof(HCBoolean) ? false : *(HCBoolean*)self->data; } HCBoolean HCDataIsInteger(HCDataRef self) { return self->size == (HCInteger)sizeof(HCInteger); } HCInteger HCDataAsInteger(HCDataRef self) { return self->size > (HCInteger)sizeof(HCInteger) ? 0 : *(HCInteger*)self->data; } HCBoolean HCDataIsReal(HCDataRef self) { return self->size == (HCInteger)sizeof(HCReal) && !isnan(*(HCReal*)self->data); } HCReal HCDataAsReal(HCDataRef self) { return self->size > (HCInteger)sizeof(HCReal) ? NAN : *(HCReal*)self->data; } //---------------------------------------------------------------------------------------------------------------------------------- // MARK: - Operations //---------------------------------------------------------------------------------------------------------------------------------- void HCDataClear(HCDataRef self) { HCDataRemoveBytes(self, self->size); } void HCDataAddBytes(HCDataRef self, HCInteger size, const HCByte* bytes) { self->data = realloc(self->data, self->size + size); if (bytes != NULL) { memcpy(self->data + self->size, bytes, size); } self->size += size; // TODO: Failable } void HCDataRemoveBytes(HCDataRef self, HCInteger size) { if (size <= 0) { return; } size = size > self->size ? 0 : self->size - size; self->data = realloc(self->data, size); self->size = size; // TODO: Failable } void HCDataAddBoolean(HCDataRef self, HCBoolean value) { HCDataAddBytes(self, sizeof(HCBoolean), (HCByte*)&value); } void HCDataRemoveBoolean(HCDataRef self) { HCDataRemoveBytes(self, sizeof(HCBoolean)); } void HCDataAddInteger(HCDataRef self, HCInteger value) { HCDataAddBytes(self, sizeof(HCInteger), (HCByte*)&value); } void HCDataRemoveInteger(HCDataRef self) { HCDataRemoveBytes(self, sizeof(HCInteger)); } void HCDataAddReal(HCDataRef self, HCReal value) { HCDataAddBytes(self, sizeof(HCReal), (HCByte*)&value); } void HCDataRemoveReal(HCDataRef self) { HCDataRemoveBytes(self, sizeof(HCReal)); }
2.734375
3
2024-11-18T20:50:48.161225+00:00
2023-01-11T22:54:07
09a072f22831d33ecefe0d8f7714202ff4f2f28e
{ "blob_id": "09a072f22831d33ecefe0d8f7714202ff4f2f28e", "branch_name": "refs/heads/master", "committer_date": "2023-01-11T22:54:07", "content_id": "6083e0353d6404ef3c859957dfe5e4956ef2f745", "detected_licenses": [ "MIT" ], "directory_id": "4edd539e79d33f7a08a4c928d113771e9dac0740", "extension": "c", "filename": "doors.c", "fork_events_count": 55, "gha_created_at": "2014-11-30T22:02:07", "gha_event_created_at": "2022-11-03T04:07:37", "gha_language": "C", "gha_license_id": "MIT", "github_id": 27351671, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 7862, "license": "MIT", "license_type": "permissive", "path": "/source/doors.c", "provenance": "stackv2-0110.json.gz:227397", "repo_name": "Olde-Skuul/doom3do", "revision_date": "2023-01-11T22:54:07", "revision_id": "8a5cdae476e09f2bedd2cc4dcd105dae4b35d4af", "snapshot_id": "84ae4f312e919d070dcb838f7765c5c1ad3f5efd", "src_encoding": "UTF-8", "star_events_count": 658, "url": "https://raw.githubusercontent.com/Olde-Skuul/doom3do/8a5cdae476e09f2bedd2cc4dcd105dae4b35d4af/source/doors.c", "visit_date": "2023-03-07T19:10:13.752129" }
stackv2
#include "Doom.h" /********************************** Local structures **********************************/ #define VDOORSPEED (6<<FRACBITS) /* Speed to open a vertical door */ #define VDOORWAIT ((TICKSPERSEC*14)/3) /* Door time to wait before closing 4.6 seconds */ typedef struct { sector_t *sector; /* Sector being modified */ Fixed topheight; /* Topmost height */ Fixed speed; /* Speed of door motion */ int direction; /* 1 = up, 0 = waiting at top, -1 = down */ Word topwait; /* tics to wait at the top */ /* (keep in case a door going down is reset) */ Word topcountdown; /* when it reaches 0, start going down */ vldoor_e type; /* Type of door */ } vldoor_t; /********************************** Think logic for doors **********************************/ static void T_VerticalDoor(vldoor_t *door) { result_e res; switch(door->direction) { case 0: /* Waiting or in stasis */ if (door->topcountdown>ElapsedTime) { door->topcountdown-=ElapsedTime; } else { door->topcountdown=0; /* Force zero */ switch(door->type) { case normaldoor: door->direction = -1; /* Time to go back down */ S_StartSound(&door->sector->SoundX,sfx_dorcls); break; case close30ThenOpen: door->direction = 1; S_StartSound(&door->sector->SoundX,sfx_doropn); } } break; case 2: /* INITIAL WAIT */ if (door->topcountdown>ElapsedTime) { door->topcountdown-=ElapsedTime; } else { door->topcountdown=0; /* Force zero */ if (door->type == raiseIn5Mins) { door->direction = 1; door->type = normaldoor; S_StartSound(&door->sector->SoundX,sfx_doropn); } } break; case -1: /* DOWN */ res = T_MovePlane(door->sector,door->speed, door->sector->floorheight,FALSE,TRUE,door->direction); if (res == pastdest) { /* Finished closing? */ switch(door->type) { case normaldoor: case close: door->sector->specialdata = 0; /* Remove it */ RemoveThinker(door); /* unlink and free */ break; case close30ThenOpen: door->direction = 0; /* Waiting */ door->topcountdown = (TICKSPERSEC*30); } } else if (res == crushed) { door->direction = 1; /* Move back up */ S_StartSound(&door->sector->SoundX,sfx_doropn); } break; case 1: /* UP */ res = T_MovePlane(door->sector,door->speed, door->topheight,FALSE,TRUE,door->direction); if (res == pastdest) { /* Fully opened? */ switch(door->type) { case normaldoor: door->direction = 0; /* wait at top */ door->topcountdown = door->topwait; /* Reset timer */ break; case close30ThenOpen: case open: door->sector->specialdata = 0; RemoveThinker(door); /* unlink and free */ } } } } /********************************** Move a door up/down and all around! **********************************/ Boolean EV_DoDoor(line_t *line,vldoor_e type) { Word secnum; Boolean rtn; sector_t *sec; vldoor_t *door; secnum = -1; rtn = FALSE; while ((secnum = P_FindSectorFromLineTag(line,secnum)) != -1) { sec = &sectors[secnum]; if (sec->specialdata) { /* Already something here? */ continue; } /* new door thinker */ rtn = TRUE; door = (vldoor_t *)AddThinker(T_VerticalDoor,sizeof(vldoor_t)); sec->specialdata = door; door->sector = sec; door->type = type; /* Save the type */ door->speed = VDOORSPEED; /* Save the speed */ door->topwait = VDOORWAIT; /* Save the initial delay */ switch(type) { case close: door->topheight = P_FindLowestCeilingSurrounding(sec); door->topheight -= 4*FRACUNIT; door->direction = -1; /* Down */ S_StartSound(&door->sector->SoundX,sfx_dorcls); break; case close30ThenOpen: door->topheight = sec->ceilingheight; door->direction = -1; /* Down */ S_StartSound(&door->sector->SoundX,sfx_dorcls); break; case normaldoor: case open: door->direction = 1; /* Up */ door->topheight = P_FindLowestCeilingSurrounding(sec); door->topheight -= 4*FRACUNIT; if (door->topheight != sec->ceilingheight) { S_StartSound(&door->sector->SoundX,sfx_doropn); } } } return rtn; } /********************************** Open a door manually, no tag value **********************************/ void EV_VerticalDoor(line_t *line,mobj_t *thing) { player_t *player; sector_t *sec; vldoor_t *door; /* Check for locks */ player = thing->player; /* Is this a player? */ if (player) { /* Only player's have trouble with locks */ Word i; i = -1; /* Don't quit! */ switch(line->special) { case 26: /* Blue Card Lock */ case 32: case 99: /* Blue Skull Lock */ case 106: if (!player->cards[it_bluecard] && !player->cards[it_blueskull]) { i = (line->special<99) ? it_bluecard : it_blueskull; } break; case 27: /* Yellow Card Lock */ case 34: case 105: /* Yellow Skull Lock */ case 108: if (!player->cards[it_yellowcard] && !player->cards[it_yellowskull]) { i = (line->special<105) ? it_yellowcard : it_yellowskull; } break; case 28: /* Red Card Lock */ case 33: case 100: /* Red Skull Lock */ case 107: if (!player->cards[it_redcard] && !player->cards[it_redskull]) { i = (line->special<100) ? it_redcard : it_redskull; } break; } if (i!=-1) { S_StartSound(&thing->x,sfx_oof); /* Play the sound */ stbar.tryopen[i] = TRUE; /* Trigger on status bar */ return; } } /* if the sector has an active thinker, use it */ sec = line->backsector; /* Get the sector pointer */ if (sec->specialdata) { door = (vldoor_t *)sec->specialdata; /* Use existing */ switch(line->special) { case 1: // ONLY FOR "RAISE" DOORS, NOT "OPEN"s case 26: // BLUE CARD case 27: // YELLOW CARD case 28: // RED CARD case 106: // BLUE SKULL case 108: // YELLOW SKULL case 107: // RED SKULL if (door->direction == -1) { /* Closing? */ door->direction = 1; /* go back up */ } else if (thing->player) { /* Only players make it close */ door->direction = -1; /* start going down immediately */ } return; /* Exit now */ } } /* for proper sound */ switch (line->special) { case 1: /* NORMAL DOOR SOUND */ case 31: S_StartSound(&sec->SoundX,sfx_doropn); break; default: /* LOCKED DOOR SOUND */ S_StartSound(&sec->SoundX,sfx_doropn); break; } /* new door thinker */ door = (vldoor_t *)AddThinker(T_VerticalDoor,sizeof(vldoor_t)); sec->specialdata = door; door->sector = sec; door->direction = 1; /* Going up! */ door->speed = VDOORSPEED; /* Set the speed */ door->topwait = VDOORWAIT; switch(line->special) { case 1: case 26: case 27: case 28: door->type = normaldoor; /* Normal open/close door */ break; case 31: case 32: case 33: case 34: door->type = open; /* Open forever */ } /* Find the top and bottom of the movement range */ door->topheight = P_FindLowestCeilingSurrounding(sec)-(4<<FRACBITS); } /********************************** Spawn a door that closes after 30 seconds **********************************/ void P_SpawnDoorCloseIn30 (sector_t *sec) { vldoor_t *door; door = (vldoor_t *)AddThinker(T_VerticalDoor,sizeof(vldoor_t)); sec->specialdata = door; sec->special = 0; door->sector = sec; door->direction = 0; /* Standard wait */ door->type = normaldoor; door->speed = VDOORSPEED; door->topcountdown = (30*TICKSPERSEC); } /********************************** Spawn a door that opens after 5 minutes **********************************/ void P_SpawnDoorRaiseIn5Mins(sector_t *sec) { vldoor_t *door; door = (vldoor_t *)AddThinker(T_VerticalDoor,sizeof(vldoor_t)); sec->specialdata = door; sec->special = 0; door->sector = sec; door->direction = 2; /* Initial wait */ door->type = raiseIn5Mins; door->speed = VDOORSPEED; door->topheight = P_FindLowestCeilingSurrounding(sec)-(4<<FRACBITS); door->topwait = VDOORWAIT; door->topcountdown = (5*60*TICKSPERSEC); }
2.28125
2
2024-11-18T20:50:53.479509+00:00
2023-02-16T18:40:06
e7f14cce61a414214188430963271d72f5e511c7
{ "blob_id": "e7f14cce61a414214188430963271d72f5e511c7", "branch_name": "refs/heads/main", "committer_date": "2023-02-16T18:40:06", "content_id": "8cd224678e4ec5b9bc95c9a858804c488d85aa03", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "fb6245383e7e7d53ab94b6eb2bb09469db466c58", "extension": "c", "filename": "mkdirs_open.c", "fork_events_count": 28, "gha_created_at": "2011-10-28T20:21:39", "gha_event_created_at": "2022-12-28T22:03:54", "gha_language": "C", "gha_license_id": "NOASSERTION", "github_id": 2667699, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4981, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/misc/mkdirs_open.c", "provenance": "stackv2-0110.json.gz:227657", "repo_name": "Unidata/LDM", "revision_date": "2023-02-16T18:40:06", "revision_id": "293344411b1a4fe35bd0e9c1eda8614a6d201d51", "snapshot_id": "99122b6e1fef032af263972be3b56eb83d3074fd", "src_encoding": "UTF-8", "star_events_count": 33, "url": "https://raw.githubusercontent.com/Unidata/LDM/293344411b1a4fe35bd0e9c1eda8614a6d201d51/misc/mkdirs_open.c", "visit_date": "2023-09-03T01:06:51.376173" }
stackv2
/* * See file ../COPYRIGHT for copying and redistribution conditions. */ #include "config.h" #include <log.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> /* O_RDONLY et al */ #include "mkdirs_open.h" #include <limits.h> /* PATH_MAX */ #ifndef PATH_MAX #define PATH_MAX 255 #endif /* !PATH_MAX */ #include <errno.h> #ifndef ENAMETOOLONG #define ENAMETOOLONG E2BIG /* punt */ #endif /* !ENAMETOOLONG */ #include <string.h> #ifndef NULL #define NULL 0 #endif #include <unistd.h> /* access */ /* * Ensures that a directory exists. Will create all necessary parent * directories. * * Arguments: * path Pointer to directory pathname. * mode File creation mode for directory and any parent directories. * Returns: * -1 Failure. errno is set. * 0 Success. */ int mkdirs( const char* const path, const mode_t mode) { int retCode = mkdir(path, mode); if (retCode != 0) { if (errno == EEXIST) { /* * The directory already exists (another process might just have * created it). This is still a "success". */ retCode = 0; } else if (errno == ENOENT) { /* * A necessary parent directory doesn't exist. * * Strip off the last parent directory in the path. */ char* ep = strrchr(path, '/'); size_t len = (size_t)(ep - path); char stripped[PATH_MAX+1]; log_assert(ep != NULL && ep != path); log_assert(len < PATH_MAX); /* * Copy up-to the last component in the path. */ (void)memcpy(stripped, path, len); stripped[len] = 0; /* * Ensure that the parent directory exists. */ retCode = mkdirs(stripped, mode); if (retCode == 0) retCode = mkdir(path, mode); } /* a parent directory doesn't exist */ } /* couldn't create directory */ return retCode; } /* * Like open(2), but will create components as necessary. * Returns valid file descriptor if successful, -1 on failure. */ int mkdirs_open( const char *path, int flags, mode_t mode) { int fd; fd = open(path, flags, mode); if(fd != -1) /* open suceeded */ return fd; /* else */ if(errno != ENOENT) /* not a problem we will fix here */ return -1; /* else */ if(!((unsigned int)flags & O_CREAT)) return -1; /* else, a component of the path prefix does not exist */ { char *ep; size_t len; char stripped[PATH_MAX+1]; ep = strrchr(path, '/'); if(ep == NULL || ep == path) return -1; /* can't happen ? */ /* else */ /* strip off last component in path */ len = (size_t)(ep - path); if(len >= PATH_MAX) { errno = ENAMETOOLONG; return -1; } (void)memcpy(stripped, path, len); stripped[len] = 0; if(mkdirs(stripped, (mode | 0111)) == -1) return -1; /* else */ } return open(path, flags, mode); } #if TEST_FIXTURE main(ac,av) int ac; char *av[]; { int fd; if(ac < 2) exit(1); fd = mkdirs_open(av[1] , O_WRONLY | O_CREAT | O_TRUNC, 0664); if(fd == -1) { perror(av[1]); exit(2); } (void) close(fd); exit(0); } #endif /* * Check to see if we have access to all components of 'path' * up to the last component. (Doesn't check the access of the full path) * If 'create' is no zero, attempt to create path components (directories) * as necessary. * Returns 0 if access is ok, -1 on error. */ int diraccess( const char *path, int access_m, int create) { char *ep; size_t len; char stripped[PATH_MAX+1]; ep = strrchr(path, '/'); if(ep == NULL || ep == path) return (0); /* else */ /* strip off last component in path */ len = (size_t)(ep - path); if(len >= PATH_MAX) { errno = ENAMETOOLONG; return -1; } (void)memcpy(stripped, path, len); stripped[len] = 0; /* Now we have something that looks like a directory */ if(access(stripped, (unsigned int)access_m | X_OK) == 0) return(0); /* else */ if(create && errno == ENOENT) { if(mkdirs(stripped, 0777) == 0) /* let the umask fix it */ return 0; } /* else */ return -1; }
2.765625
3
2024-11-18T20:50:53.533938+00:00
2012-06-01T01:26:52
7ab5f2d0d25ac25223632d98dd20c85bb229ec5c
{ "blob_id": "7ab5f2d0d25ac25223632d98dd20c85bb229ec5c", "branch_name": "refs/heads/master", "committer_date": "2012-06-01T01:26:52", "content_id": "a98ef9418c99cc1463c1fbb8d62ddc4471f8d549", "detected_licenses": [ "MIT" ], "directory_id": "cb948a504fabf42bdd1b2e580e3528ba16d999fe", "extension": "h", "filename": "box.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": 1944, "license": "MIT", "license_type": "permissive", "path": "/src/geom/box.h", "provenance": "stackv2-0110.json.gz:227785", "repo_name": "cabeen/snakes-on-a-sphere", "revision_date": "2012-06-01T01:26:52", "revision_id": "fd6f40efa6c2c4254b60ef59d83ca3aaf0b729bf", "snapshot_id": "1e1700a86404aa4bd82e664a082c2ee303d0de50", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/cabeen/snakes-on-a-sphere/fd6f40efa6c2c4254b60ef59d83ca3aaf0b729bf/src/geom/box.h", "visit_date": "2021-01-01T16:55:43.933048" }
stackv2
#ifndef BOX_H #define BOX_H #include "algebra.h" #include "interval.h" struct Box { Box() { x = Interval(); y = Interval(); z = Interval(); } Box(const Vector3 &a, const Vector3 &b){ x = Interval(a.x, b.x); y = Interval(a.y, b.y); z = Interval(a.z, b.z); } Box(const Interval &x, const Interval &y, const Interval &z) { this->x = x; this->y = y; this->z = z; } Box join(const Box &box) const { return Box(x.join(box.x), y.join(box.y), z.join(box.z)); } Box xfm(const Matrix4x4 &xfm) const { vector<Vector4> ps; ps.push_back(Vector4(x.min, y.min, z.min, 1)); ps.push_back(Vector4(x.min, y.min, z.max, 1)); ps.push_back(Vector4(x.min, y.max, z.min, 1)); ps.push_back(Vector4(x.min, y.max, z.max, 1)); ps.push_back(Vector4(x.max, y.min, z.min, 1)); ps.push_back(Vector4(x.max, y.min, z.max, 1)); ps.push_back(Vector4(x.max, y.max, z.min, 1)); ps.push_back(Vector4(x.max, y.max, z.max, 1)); Interval nx; Interval ny; Interval nz; for (int i = 0; i < ps.size(); i++) { Vector4 np = xfm * ps[i]; if (i == 0) { nx.min = nx.max = np.x; ny.min = ny.max = np.y; nz.min = nz.max = np.z; } else { nx.min = fmin(nx.min, np.x); nx.max = fmax(nx.max, np.x); ny.min = fmin(ny.min, np.y); ny.max = fmax(ny.max, np.y); nz.min = fmin(nz.min, np.z); nz.max = fmax(nz.max, np.z); } } return Box(nx, ny, nz); } Box growFraction(double f) const { return Box(x.growFraction(f), y.growFraction(f), z.growFraction(f)); } Interval x; Interval y; Interval z; }; #endif // BOX_H
2.65625
3
2024-11-18T20:50:54.201532+00:00
2019-10-30T21:57:41
4c283254e9a2c408fb1e7eac06aa7e2781ddd2ae
{ "blob_id": "4c283254e9a2c408fb1e7eac06aa7e2781ddd2ae", "branch_name": "refs/heads/master", "committer_date": "2019-10-30T21:57:41", "content_id": "87a1c6d6ec46bd0bb02eeea0eebe6594256da630", "detected_licenses": [ "MIT" ], "directory_id": "77e51321c7fc9db105a964450264a1d6675565fb", "extension": "c", "filename": "hello_world.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 201127816, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 982, "license": "MIT", "license_type": "permissive", "path": "/Entrega-2/software/niosLED/hello_world.c", "provenance": "stackv2-0110.json.gz:228302", "repo_name": "martimfj/Embarcados-Avancados", "revision_date": "2019-10-30T21:57:41", "revision_id": "a5a154975cee4ee61d39baccb42545b5e1c018a6", "snapshot_id": "8d733b494b284e42b176118ff3fd2194ffdc7839", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/martimfj/Embarcados-Avancados/a5a154975cee4ee61d39baccb42545b5e1c018a6/Entrega-2/software/niosLED/hello_world.c", "visit_date": "2020-07-01T09:32:18.953023" }
stackv2
#include <stdio.h> #include "system.h" #include <alt_types.h> #include <io.h> #include "altera_avalon_pio_regs.h" #include "sys/alt_irq.h" #include "altera_avalon_pio_regs.h" #include "altera_avalon_timer_regs.h" volatile int edge_capture; unsigned int flag = 1; unsigned int led = 0; unsigned int counter = 0; unsigned int *p_pio0 = (unsigned int *) PIO_0_BASE; void handleTimerInterrupt (void* context, alt_u32 id) { unsigned int factor = (IORD_32DIRECT(PIO_1_BASE, 0) & 0x0f) + 1; unsigned int flag = IORD_32DIRECT(PIO_1_BASE, 0) & 0x10; counter++; if(counter >= 10000/factor){ if (flag){ if (led <= 5){ *(p_pio0+0) = 0x01 << led++; } else{ led = 0; } } counter = 0; } IOWR_ALTERA_AVALON_TIMER_STATUS(TIMER_0_BASE, 0); // Clear the interrupt flag } int main(void){ alt_irq_register(TIMER_0_BASE, 0, handleTimerInterrupt); // Register the ISR for timer while(1){}; return 0; }
2.140625
2
2024-11-18T20:50:57.504773+00:00
2023-06-02T11:47:31
205466629b4ffb74047909d2206e1f40cc46ee5c
{ "blob_id": "205466629b4ffb74047909d2206e1f40cc46ee5c", "branch_name": "refs/heads/master", "committer_date": "2023-06-02T11:47:31", "content_id": "824234ca6f7431d1f600e5f40a0a19da95c1d1f4", "detected_licenses": [ "MIT", "Zlib", "Apache-2.0" ], "directory_id": "14c685102101327da349f7da83099e90101c690c", "extension": "c", "filename": "tuklib_exit.c", "fork_events_count": 11, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 14408419, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1584, "license": "MIT,Zlib,Apache-2.0", "license_type": "permissive", "path": "/Service/jni/lzma/common/tuklib_exit.c", "provenance": "stackv2-0110.json.gz:228691", "repo_name": "alanwoolley/innoextract-android", "revision_date": "2023-06-02T11:47:31", "revision_id": "d0a72015a4a7898e0b5a24cae8642a4028c4d24b", "snapshot_id": "a59647cfe675ca404f4b041b7bd0acbef139deee", "src_encoding": "UTF-8", "star_events_count": 23, "url": "https://raw.githubusercontent.com/alanwoolley/innoextract-android/d0a72015a4a7898e0b5a24cae8642a4028c4d24b/Service/jni/lzma/common/tuklib_exit.c", "visit_date": "2023-07-22T12:20:39.590781" }
stackv2
/////////////////////////////////////////////////////////////////////////////// // /// \file tuklib_exit.c /// \brief Close stdout and stderr, and exit // // Author: Lasse Collin // // This file has been put into the public domain. // You can do whatever you want with this file. // /////////////////////////////////////////////////////////////////////////////// #include "tuklib_common.h" #include <stdlib.h> #include <stdio.h> #include "tuklib_gettext.h" #include "tuklib_progname.h" #include "tuklib_exit.h" extern void tuklib_exit(int status, int err_status, int show_error) { if (status != err_status) { // Close stdout. If something goes wrong, // print an error message to stderr. const int ferror_err = ferror(stdout); const int fclose_err = fclose(stdout); if (ferror_err || fclose_err) { status = err_status; // If it was fclose() that failed, we have the reason // in errno. If only ferror() indicated an error, // we have no idea what the reason was. if (show_error) fprintf(stderr, "%s: %s: %s\n", progname, _("Writing to standard " "output failed"), fclose_err ? strerror(errno) : _("Unknown error")); } } if (status != err_status) { // Close stderr. If something goes wrong, there's // nothing where we could print an error message. // Just set the exit status. const int ferror_err = ferror(stderr); const int fclose_err = fclose(stderr); if (fclose_err || ferror_err) status = err_status; } exit(status); }
2.5625
3
2024-11-18T20:50:57.633582+00:00
2020-04-24T23:20:40
f2f5509133fd46d62341020f2077ba1ff3727283
{ "blob_id": "f2f5509133fd46d62341020f2077ba1ff3727283", "branch_name": "refs/heads/master", "committer_date": "2020-04-24T23:20:40", "content_id": "b2a8184f4a089d5ebe265a334499764a78af770d", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "48c2d779adc3ec016b996d1bb03c5f9b2605bb3f", "extension": "c", "filename": "oracle.c", "fork_events_count": 0, "gha_created_at": "2020-04-29T11:44:55", "gha_event_created_at": "2020-04-29T11:44:56", "gha_language": null, "gha_license_id": null, "github_id": 259910011, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2651, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/pwdalgos/oracle/oracle.c", "provenance": "stackv2-0110.json.gz:228820", "repo_name": "wqweto/tinycrypt", "revision_date": "2020-04-24T23:20:40", "revision_id": "b6100cf07b7355643085dda326c13dcfcc804077", "snapshot_id": "6aa72dab0fc553de87f7d925dd075fbc4347211b", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/wqweto/tinycrypt/b6100cf07b7355643085dda326c13dcfcc804077/pwdalgos/oracle/oracle.c", "visit_date": "2022-04-24T00:13:25.536111" }
stackv2
// Oracle 10 and 11 password algorithms // Odzhan #include <stdio.h> #include <string.h> #include <stdlib.h> #include <stdint.h> #include <openssl/sha.h> #include <openssl/des.h> #define MAX_USERNAME 31 #define MAX_PASSWORD 31 uint8_t pwd_key[]={0x01,0x23,0x45,0x67,0x89,0xab,0xcd,0xef}; // convert hexadecimal string to binary size_t hex2bin (void *bin, char hex[]) { size_t len, i; int x; uint8_t *p=(uint8_t*)bin; len = strlen (hex); if ((len & 1) != 0) { return 0; } for (i=0; i<len; i++) { if (isxdigit((int)hex[i]) == 0) { return 0; } } for (i=0; i<len / 2; i++) { sscanf (&hex[i * 2], "%2x", &x); p[i] = (uint8_t)x; } return len / 2; } // create password hash for oracle 10 char *oracle10_pwd (char *pwd, char *id) { wchar_t in[128]; size_t len, i, slen; uint8_t out[32], iv[8]; DES_key_schedule ks; static char pwd10[8+1]; memset (in, 0, sizeof in); memset (out, 0, sizeof out); slen=strlen (id); // convert the user name to Unicode big endian for (i=0, len=0; i<slen && i<MAX_USERNAME; i++) { in[len++] = (toupper (id[i]) << 8); } slen=strlen (pwd); // convert the password to Unicode, appending to user name for (i=0; i<slen && i<MAX_PASSWORD; i++) { in[len++] = (toupper (pwd[i]) << 8); } len <<= 1; memset (iv, 0, sizeof iv); DES_set_key ((DES_cblock*)pwd_key, &ks); DES_ncbc_encrypt ((uint8_t*)in, out, len, &ks, &iv, DES_ENCRYPT); DES_set_key ((DES_cblock*)iv, &ks); memset (iv, 0, sizeof iv); DES_ncbc_encrypt ((uint8_t*)in, out, len, &ks, &iv, DES_ENCRYPT); for (i=0; i<8; i++) { _snprintf (&pwd10[i*2], 2, "%02X", iv[i]); } return pwd10; } char *oracle11_pwd (char *pwd, uint8_t *salt) { size_t i, slen; SHA_CTX ctx; uint8_t sbin[128], out[SHA_DIGEST_LENGTH]; static char pwd11[32]; slen=hex2bin (sbin, salt); SHA1_Init (&ctx); SHA1_Update (&ctx, pwd, strlen (pwd)); SHA1_Update (&ctx, sbin, slen); SHA1_Final (out, &ctx); for (i=0; i<SHA_DIGEST_LENGTH; i++) { _snprintf (&pwd11[i*2], 2, "%02X", out[i]); } return pwd11; } int main (int argc, char *argv[]) { char *id, *pwd, *salt; if (argc != 3) { printf ("\n usage: oracle_pwd <password> <salt | user name>\n"); return 0; } pwd=argv[1]; id=argv[2]; salt=argv[2]; printf ("\n Oracle 10 : %s", oracle10_pwd (pwd, id)); printf ("\n Oracle 11 : %s\n", oracle11_pwd (pwd, salt)); return 0; }
2.9375
3
2024-11-18T20:50:57.823646+00:00
2019-01-27T22:12:57
aa412b55a6246e328822f9bfbb0e2b0a1af363bb
{ "blob_id": "aa412b55a6246e328822f9bfbb0e2b0a1af363bb", "branch_name": "refs/heads/master", "committer_date": "2019-01-27T22:12:57", "content_id": "05390288c2c5165423991ea4314decb06c913a33", "detected_licenses": [ "MIT" ], "directory_id": "6675b58389b73e2fa7ee9e3f857c509015946d7b", "extension": "c", "filename": "bbrndr.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 64562395, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3219, "license": "MIT", "license_type": "permissive", "path": "/src/bbrndr.c", "provenance": "stackv2-0110.json.gz:229079", "repo_name": "agorgl/energycore", "revision_date": "2019-01-27T22:12:57", "revision_id": "c428b393ebb4c80f90fb878fdcc5606bd656350c", "snapshot_id": "cdcc7b8060b9a32ad3cda4c665e43b397aaa496a", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/agorgl/energycore/c428b393ebb4c80f90fb878fdcc5606bd656350c/src/bbrndr.c", "visit_date": "2022-02-09T05:07:48.713826" }
stackv2
#include "bbrndr.h" #include <string.h> #include "opengl.h" #include "glutils.h" static const char* vs_src = GLSRC( layout (location = 0) in vec3 position; uniform mat4 proj; uniform mat4 view; uniform mat4 model; void main() { vec4 pos = proj * view * model * vec4(position, 1.0); gl_Position = pos; } ); static const char* fs_src = GLSRC( out vec4 color; void main() { color = vec4(0.0, 0.0, 1.0, 1.0); } ); static const GLuint box_indices[] = { 0, 1, 2, 1, 3, 2, 4, 6, 7, 7, 5, 4, 1, 5 ,7, 7, 3, 1, 0, 2, 6, 6, 4, 0, 5, 1, 0, 0, 4, 5, 7, 6, 2, 2, 3, 7 }; void bbox_rndr_init(struct bbox_rndr* st) { /* Build visualization shader */ st->vis_shdr = shader_from_srcs(vs_src, 0, fs_src); /* Create cube vao and empty vbo */ GLuint vao, vbo, ebo; glGenVertexArrays(1, &vao); glBindVertexArray(vao); glGenBuffers(1, &vbo); glBindBuffer(GL_ARRAY_BUFFER, vbo); glBufferData(GL_ARRAY_BUFFER, 24 * sizeof(float), 0, GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), 0); /* Create common indice buffer */ glGenBuffers(1, &ebo); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(box_indices), box_indices, GL_STATIC_DRAW); unsigned int indice_count = sizeof(box_indices) / sizeof(box_indices[0]); glBindVertexArray(0); /* Store state */ st->vao = vao; st->vbo = vbo; st->ebo = ebo; st->indice_count = indice_count; } void bbox_rndr_vis(struct bbox_rndr* st, float model[16], float view[16], float proj[16], float aabb_min[3], float aabb_max[3]) { glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); GLuint shdr = st->vis_shdr; glUseProgram(shdr); GLuint proj_mat_loc = glGetUniformLocation(shdr, "proj"); GLuint view_mat_loc = glGetUniformLocation(shdr, "view"); GLuint modl_mat_loc = glGetUniformLocation(shdr, "model"); glUniformMatrix4fv(proj_mat_loc, 1, GL_FALSE, proj); glUniformMatrix4fv(view_mat_loc, 1, GL_FALSE, view); glUniformMatrix4fv(modl_mat_loc, 1, GL_FALSE, model); bbox_rndr_render(st, aabb_min, aabb_max); glUseProgram(0); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); } void bbox_rndr_render(struct bbox_rndr* st, float aabb_min[3], float aabb_max[3]) { float verts[24] = { aabb_max[0], aabb_max[1], aabb_max[2], aabb_min[0], aabb_max[1], aabb_max[2], aabb_max[0], aabb_min[1], aabb_max[2], aabb_min[0], aabb_min[1], aabb_max[2], aabb_max[0], aabb_max[1], aabb_min[2], aabb_min[0], aabb_max[1], aabb_min[2], aabb_max[0], aabb_min[1], aabb_min[2], aabb_min[0], aabb_min[1], aabb_min[2], }; glBindBuffer(GL_ARRAY_BUFFER, st->vbo); glBufferData(GL_ARRAY_BUFFER, sizeof(verts), verts, GL_STATIC_DRAW); glBindVertexArray(st->vao); glDrawElements(GL_TRIANGLES, st->indice_count, GL_UNSIGNED_INT, 0); glBindVertexArray(0); } void bbox_rndr_destroy(struct bbox_rndr* st) { glDeleteBuffers(1, &st->ebo); glDeleteBuffers(1, &st->vbo); glDeleteVertexArrays(1, &st->vao); glDeleteProgram(st->vis_shdr); }
2.1875
2
2024-11-18T20:50:58.181132+00:00
2021-12-22T19:14:11
1c1a395083b1a3f2cd4a0f6ba2fd785ad46e647e
{ "blob_id": "1c1a395083b1a3f2cd4a0f6ba2fd785ad46e647e", "branch_name": "refs/heads/master", "committer_date": "2021-12-22T19:14:11", "content_id": "7d6777e1fd1fa09d9ec7481a19c0dbe69c17e79d", "detected_licenses": [ "MIT" ], "directory_id": "93829d20b5c78c2f50dbbf7df55c2a5bf6854aad", "extension": "h", "filename": "uwlkv.h", "fork_events_count": 5, "gha_created_at": "2020-02-03T12:00:15", "gha_event_created_at": "2021-02-02T09:13:19", "gha_language": "C++", "gha_license_id": "MIT", "github_id": 237954910, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3382, "license": "MIT", "license_type": "permissive", "path": "/src/include/uwlkv.h", "provenance": "stackv2-0110.json.gz:229469", "repo_name": "Gordon01/uWLKV", "revision_date": "2021-12-22T19:14:11", "revision_id": "004c30b959671ce9c54fd2fb56b23385fc219a15", "snapshot_id": "ba8ffbcfda1096d217ef5022ed2e01b710d639d0", "src_encoding": "UTF-8", "star_events_count": 24, "url": "https://raw.githubusercontent.com/Gordon01/uWLKV/004c30b959671ce9c54fd2fb56b23385fc219a15/src/include/uwlkv.h", "visit_date": "2022-01-03T05:22:51.459873" }
stackv2
#ifndef UWLKV_NVRAM_LIB #define UWLKV_NVRAM_LIB #include <stdint.h> /* You can change a storage type if you don't need big values for key or value to save some space */ typedef uint16_t uwlkv_key; /* Record key */ typedef int32_t uwlkv_value; /* Record value */ typedef uint32_t uwlkv_offset; /* NVRAM address. Can be reduced to match memory size and save some RAM */ typedef int(* uwlkv_erase)(void); /* NVRAM erase function prototype */ #define UWLKV_O_ERASE_STARTED (0) /* Offset of ERASE_STARTED flag */ #define UWLKV_O_ERASE_FINISHED (1) /* Offset of ERASE_FINISHED flag */ #define UWLKV_METADATA_SIZE (2) /* Number of bytes, that library use in the beginning of each area */ #define UWLKV_NVRAM_ERASE_STARTED (0xE2) /* Magic for ERASE_STARTED flag */ #define UWLKV_NVRAM_ERASE_FINISHED (0x3E) /* Magic for ERASE_FINISHED flag */ #define UWLKV_ENTRY_SIZE (sizeof(uwlkv_key) + sizeof(uwlkv_value)) #define UWLKV_MINIMAL_SIZE (UWLKV_ENTRY_SIZE + UWLKV_METADATA_SIZE) #define UWLKV_MAX_ENTRIES (20) /* Maximum amount of unique keys. Increases RAM consumption */ #define UWLKV_ERASED_BYTE_VALUE (0xFF) /* Value of erased byte of NVRAM */ typedef struct { uwlkv_key key; uwlkv_offset offset; } uwlkv_entry; /* You must provide an interface to access storage device. * Read/write functions should use logical address (starting from 0). * erase_main() should erase a main (large) area, without touching reserved area. * erase_reserve() should erase only a reserved area. */ typedef struct { int(* read)(uint8_t * data, uwlkv_offset start, uwlkv_offset size); int(* write)(uint8_t * data, uwlkv_offset start, uwlkv_offset size); uwlkv_erase erase_main; uwlkv_erase erase_reserve; uwlkv_offset size; /* Total size of provided memory */ uwlkv_offset reserved; /* Reserved area size in that memory */ } uwlkv_nvram_interface; typedef enum { UWLKV_E_SUCCESS, UWLKV_E_NOT_EXIST, /* Requested entry does not exist on NVRAM */ UWLKV_E_NVRAM_ERROR, /* NVRAM interface signalled an error during the operation */ UWLKV_E_NOT_STARTED, /* UWLKV haven't been initialized */ UWLKV_E_NO_SPACE, /* No free space in map for new entry */ UWLKV_E_WRONG_OFFSET, /* Provided offset is out of NVRAM bounds */ } uwlkv_error; typedef enum { UWLKV_MAIN, UWLKV_RESERVED } uwlkv_area; typedef enum { UWLKV_S_BLANK, /* NVRAM is fully erased (new) */ UWLKV_S_CLEAN, /* Last shutdown was clean */ UWLKV_S_MAIN_ERASE_INTERRUPTED, /* Main area erase was interrupted */ UWLKV_S_RESERVE_ERASE_INTERRUPTED /* Reserved area erase was interrupted */ } uwlkv_nvram_state; #ifdef __cplusplus extern "C" { #endif uwlkv_offset uwlkv_init(const uwlkv_nvram_interface * nvram_interface); uwlkv_key uwlkv_get_entries_number(void); uwlkv_key uwlkv_get_free_entries(void); uwlkv_error uwlkv_get_value(uwlkv_key key, uwlkv_value * value); uwlkv_error uwlkv_set_value(uwlkv_key key, uwlkv_value value); #ifdef __cplusplus } #endif #endif
2.75
3
2024-11-18T20:51:00.657361+00:00
2016-06-01T03:42:40
01b14dbd6112bb59a237270f47bb7647a40ca6d2
{ "blob_id": "01b14dbd6112bb59a237270f47bb7647a40ca6d2", "branch_name": "refs/heads/master", "committer_date": "2016-06-01T03:42:40", "content_id": "799a2b0eae35a06079fb5858d4bfa2770272aff3", "detected_licenses": [ "Apache-2.0" ], "directory_id": "8af517bdce08f6ff2476f46948bb38f64d321926", "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": 60059585, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 775, "license": "Apache-2.0", "license_type": "permissive", "path": "/src/main.c", "provenance": "stackv2-0110.json.gz:229988", "repo_name": "synthetixa/txt", "revision_date": "2016-06-01T03:42:40", "revision_id": "e488219c5e322c4b0e8b138d5b7170ca4e0ef885", "snapshot_id": "c731d8be5f6baf535cffc95b73b49e62337ddce5", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/synthetixa/txt/e488219c5e322c4b0e8b138d5b7170ca4e0ef885/src/main.c", "visit_date": "2021-01-20T17:32:58.493812" }
stackv2
#include "stdio.h" #include "stdlib.h" #include "ncurses.h" #include "string.h" #include "unistd.h" #include "../config.h" int main(int argc, char *argv[]) { initscr(); noecho(); keypad(stdscr, TRUE); WINDOW *top_win; WINDOW *win; WINDOW *bottom_win; int wy, wx, y, x, width, height; width = 100; height = 30; y = (LINES - height) / 2; x = (COLS - width) / 2; getmaxyx(win, wy, wx); top_win = newwin(3, width, 1, x); box(top_win, 0, 0); win = newwin(height, width, y, x); box(win, 0, 0); bottom_win = newwin(6, width, LINES - 7, x); box(bottom_win, 0, 0); mvwprintw(top_win, 1, (100 - strlen(PACKAGE_STRING)) / 2 , "%s", PACKAGE_STRING); curs_set(0); refresh(); wrefresh(win); wrefresh(top_win); wrefresh(bottom_win); sleep(60); delwin(win); endwin(); return 0; }
2.125
2
2024-11-18T20:51:01.112667+00:00
2019-01-03T03:13:44
ff8778797463032a7cec34fb0853fc22b62fe6d0
{ "blob_id": "ff8778797463032a7cec34fb0853fc22b62fe6d0", "branch_name": "refs/heads/master", "committer_date": "2019-01-03T03:13:44", "content_id": "6f8d0cf718940a02d8f5acf37d40f2f9bffb21b6", "detected_licenses": [ "Apache-2.0" ], "directory_id": "d86213ebb7b4ed411bda86f2acf37a5ec776e7ab", "extension": "c", "filename": "except.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": 1175, "license": "Apache-2.0", "license_type": "permissive", "path": "/except/except.c", "provenance": "stackv2-0110.json.gz:230503", "repo_name": "zzu-andrew/c_interface_reused", "revision_date": "2019-01-03T03:13:44", "revision_id": "d2e3df9ec2e74d68c3733b9c0f6233fb012baa9a", "snapshot_id": "35a77512d23ed80d07953f81d636bdac09d40f14", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/zzu-andrew/c_interface_reused/d2e3df9ec2e74d68c3733b9c0f6233fb012baa9a/except/except.c", "visit_date": "2021-10-09T20:16:02.698917" }
stackv2
#include "except.h" #include "../assert/assert.h" #include <stdio.h> #include <stdlib.h> #define T Except_T Except_Frame* Except_stack = NULL; void Except_raise(const T* e, const char* file, int line) { Except_Frame* p = Except_stack; assert(e); if (p == NULL) { fprintf(stderr, "Uncaught exception"); if (e->reason) { fprintf(stderr, "%s", e->reason); } else { fprintf(stderr, " ar 0x%p", e); } if (file && line > 0) { fprintf(stderr, "raised at %s:%d\n", file, line); } fprintf(stderr, "aborting...\n"); fflush(stderr); abort(); } p->exception = e; p->file = file; p->line = line; longjmp(p->env, Except_raised); } /* int main(int argc, char* argv[]) { TRY edit(argc, argv); ELSE fprintf(stderr, "An internal error has occured from there is " "no recovery.\nPlease report this error to " "Technical Support at 800-777-1234.\nNote the " "follow messing, which will help our support " "staff\nfind the cause of this error.\n\n"); RERAISE; END_TRY; return EXIT_SUCCESS; } */
2.328125
2
2024-11-18T20:51:01.281702+00:00
2023-08-11T00:15:06
1a0e89cb1a2148382c7546df46cfbb79c04a1e70
{ "blob_id": "1a0e89cb1a2148382c7546df46cfbb79c04a1e70", "branch_name": "refs/heads/master", "committer_date": "2023-08-11T00:15:06", "content_id": "ffc9e250dcf3e47f773c6bb2f3da121e5c104782", "detected_licenses": [ "MIT" ], "directory_id": "75403b8c79a2cdc0ed72b763a578b8012da312b7", "extension": "c", "filename": "for_bounded_loop1_false-unreach-call_true-termination.c", "fork_events_count": 3, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 242671954, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 524, "license": "MIT", "license_type": "permissive", "path": "/benchmarks/INV-SV/for_bounded_loop1_false-unreach-call_true-termination.c", "provenance": "stackv2-0110.json.gz:230761", "repo_name": "purdue-cap/DryadSynth", "revision_date": "2023-08-11T00:15:06", "revision_id": "12a2457d7513e92eab8960b459ff211940ce0fb4", "snapshot_id": "fd10abc38ac58edaf2868d4d78fab9ec424f0dc3", "src_encoding": "UTF-8", "star_events_count": 24, "url": "https://raw.githubusercontent.com/purdue-cap/DryadSynth/12a2457d7513e92eab8960b459ff211940ce0fb4/benchmarks/INV-SV/for_bounded_loop1_false-unreach-call_true-termination.c", "visit_date": "2023-08-16T09:45:32.116573" }
stackv2
extern void __VERIFIER_error() __attribute__ ((__noreturn__)); extern void __VERIFIER_assume(int); void __VERIFIER_assert(int cond) { if (!(cond)) { ERROR: __VERIFIER_error(); } return; } int __VERIFIER_nondet_int(); int main() { int i=0, x=0, y=0; int n=__VERIFIER_nondet_int(); if (!(n>0)) return 0; for(i=0; i<n; i++) { x = x-y; __VERIFIER_assert(x==0); y = __VERIFIER_nondet_int(); if (!(y!=0)) return 0; x = x+y; __VERIFIER_assert(x!=0); } __VERIFIER_assert(x==0); }
2.265625
2
2024-11-18T21:15:30.976460+00:00
2023-08-28T17:04:44
cca776b2e1a25ad57512084d803d31a1cd9b93d4
{ "blob_id": "cca776b2e1a25ad57512084d803d31a1cd9b93d4", "branch_name": "refs/heads/master", "committer_date": "2023-08-28T17:07:16", "content_id": "f85d35c08d20d920181184d7daafb809c3854d3e", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "7309a4d3579a04eecef51cb20238530ddfdd02ac", "extension": "c", "filename": "test.c", "fork_events_count": 40, "gha_created_at": "2014-04-08T20:01:51", "gha_event_created_at": "2023-09-12T09:21:01", "gha_language": null, "gha_license_id": null, "github_id": 18573042, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4056, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/community/lists/devel/att-5903/test.c", "provenance": "stackv2-0112.json.gz:89", "repo_name": "open-mpi/ompi-www", "revision_date": "2023-08-28T17:04:44", "revision_id": "e84f06fa5d2b47e7bdc76548271f9a7bc7a1a18b", "snapshot_id": "1f359491eaf705ea05fc36d051f08c24b6406501", "src_encoding": "UTF-8", "star_events_count": 4, "url": "https://raw.githubusercontent.com/open-mpi/ompi-www/e84f06fa5d2b47e7bdc76548271f9a7bc7a1a18b/community/lists/devel/att-5903/test.c", "visit_date": "2023-08-30T18:30:54.263248" }
stackv2
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <mpi.h> typedef struct _tstruct { char one[3]; long two; double three; short four; } TSTRUCT; int main(int argc, char *argv[]) { TSTRUCT tstruct; int mpi_size=0, mpi_rank=0; int sizes[4]; MPI_Aint offsets[4]; MPI_Datatype types[4]; MPI_Datatype mpitype; int status; MPI_Status mpistatus; // Initialize MPI if ((status = MPI_Init(&argc, &argv)) != MPI_SUCCESS) { printf("MPI_Init failed - %d.\n", status); (void)MPI_Abort(MPI_COMM_WORLD, status); abort(); } // Get size & rank info MPI_Comm_rank(MPI_COMM_WORLD, &mpi_rank); MPI_Comm_size(MPI_COMM_WORLD, &mpi_size); if(mpi_size != 2) { printf("This test program must be run with exactly '2' processes.\n"); (void)MPI_Abort(MPI_COMM_WORLD, 1); abort(); } // Sleep to try and get Process 1 output to appear first... just for convenience if(mpi_rank==1) sleep(1); // Initialize data that I will send from process 0 to process 1 memset(&tstruct, '\0', sizeof(TSTRUCT)); if(mpi_rank==0) { sprintf(tstruct.one, "22"); tstruct.two= 222; tstruct.three = 33.3; tstruct.four= 44; } // Build custom type structure sizes[0] = (int)sizeof(tstruct.one); sizes[1] = (int)sizeof(tstruct.two); sizes[2] = (int)sizeof(tstruct.three); sizes[3] = (int)sizeof(tstruct.four); offsets[0] = 0; offsets[1] = ((int)&tstruct.two) - ((int)&tstruct.one); offsets[2] = ((int)&tstruct.three) - ((int)&tstruct.one); offsets[3] = ((int)&tstruct.four) - ((int)&tstruct.one); types[0] = MPI_CHAR; types[1] = MPI_LONG; types[2] = MPI_DOUBLE; types[3] = MPI_SHORT; printf("%d: sizes '%d' '%d' '%d' '%d'\n", mpi_rank, sizes[0], sizes[1], sizes[2], sizes[3]); printf("%d: offsets '%d' '%d' '%d' '%d'\n", mpi_rank, offsets[0], offsets[1], offsets[2], offsets[3]); printf("%d: addresses '%d' '%d' '%d' '%d'\n", mpi_rank, &tstruct.one, &tstruct.two, &tstruct.three, &tstruct.four); if((status = MPI_Type_struct(4, &sizes[0], &offsets[0], &types[0], &mpitype)) != MPI_SUCCESS) { printf("MPI_Type_struct() failed - %d.\n", status); (void)MPI_Abort(MPI_COMM_WORLD, status); abort(); } if((status = MPI_Type_commit(&mpitype)) != MPI_SUCCESS) { printf("MPI_Type_struct() failed - %d.\n", status); (void)MPI_Abort(MPI_COMM_WORLD, status); abort(); } if(mpi_rank==0) { if((status = MPI_Send(&tstruct.one, 1/*count*/, mpitype, 1/*dest*/, 0/*tag*/, MPI_COMM_WORLD)) != MPI_SUCCESS) { printf("MPI_Send() failed - %d.\n", status); (void)MPI_Abort(MPI_COMM_WORLD, status); abort(); } } else { if((status = MPI_Recv(&tstruct.one, 1/*count*/, mpitype, 0/*source*/, MPI_ANY_TAG, MPI_COMM_WORLD, &mpistatus)) != MPI_SUCCESS) { printf("MPI_Recv() failed - %d.\n", status); (void)MPI_Abort(MPI_COMM_WORLD, status); abort(); } } // Print data printf("%d: one='%s' two='%d' three='%f' four='%d'\n", mpi_rank, tstruct.one, tstruct.two, tstruct.three, tstruct.four); MPI_Finalize(); return 1; }
2.46875
2
2024-11-18T21:15:31.029119+00:00
2018-04-02T15:52:59
fd9871d26f54b2430af169acf573b5f2cd169595
{ "blob_id": "fd9871d26f54b2430af169acf573b5f2cd169595", "branch_name": "refs/heads/master", "committer_date": "2018-04-02T15:52:59", "content_id": "a9ad0ccf82118a94f9f36aa965138e627e92f38e", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "85f9d7405b4ec27854f51ea4ba2ae389140cb6d5", "extension": "c", "filename": "common.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 127777649, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4199, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/lib/plugins/common/common.c", "provenance": "stackv2-0112.json.gz:219", "repo_name": "pwrapi/cray_pwrapi", "revision_date": "2018-04-02T15:52:59", "revision_id": "e303a841a7fcc9217a144a48e44cca05990ae066", "snapshot_id": "9028449f6093decf8007416a344016909b7af67f", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/pwrapi/cray_pwrapi/e303a841a7fcc9217a144a48e44cca05990ae066/lib/plugins/common/common.c", "visit_date": "2020-03-07T23:18:16.704694" }
stackv2
/* * Copyright (c) 2016-2018, Cray Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors * may be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * This file contains common functions for plugin functions. */ #include <stdlib.h> #include <limits.h> #include <string.h> #include <math.h> #include <cray-powerapi/types.h> #include <log.h> #include "common.h" /* * read_val_from_buf - Converts a single value in a character buffer to the * specified type. * * Argument(s): * * buf - The buffer containing string * val - Target memory to hold value * type - Target type to convert to * tspec - Target memory to hold timestamp of when data sample is taken. * If NULL, no timestamp is taken. * * Return Code(s): * * PWR_RET_SUCCESS - Upon SUCCESS * PWR_RET_FAILURE - Upon FAILURE */ int read_val_from_buf(const char *buf, void *val, val_type_t type, struct timespec *tspec) { int retval = PWR_RET_FAILURE; gchar *tmp_buf = NULL; TRACE2_ENTER("buf = %p, val = %p, type = %d, tspec = %p", buf, val, type, tspec); /* * Grab timestamp. If NULL no timestamp is taken. Timestamp is * nanoseconds since the Epoch. */ if (tspec != NULL) { if (clock_gettime(CLOCK_REALTIME, tspec)) { LOG_FAULT("clock_gettime() failed: %m"); goto done; } } /* * Copy buffer so we can modify it. */ tmp_buf = g_strdup(buf); if (tmp_buf == NULL) { LOG_FAULT("g_strdup() failed: %m"); goto done; } /* * Get rid of '\n' character if it exists. */ g_strstrip(tmp_buf); /* * Convert from string. */ switch (type) { case TYPE_UINT64: *(uint64_t *)val = strtoul(tmp_buf, NULL, 0); if (*(uint64_t *)val == LLONG_MIN || *(uint64_t *)val == LLONG_MAX) { LOG_FAULT("'%s' out of range", tmp_buf); goto done; } break; case TYPE_DOUBLE: *(double *)val = strtod(tmp_buf, NULL); if (*(double *)val == HUGE_VAL || *(double *)val == -HUGE_VAL) { LOG_FAULT("'%s' out of range", tmp_buf); goto done; } break; case TYPE_STRING: *(char **)val = (char *)g_strdup(tmp_buf); if (*(char **)val == NULL) { LOG_FAULT("g_strdup() failed: %m"); goto done; } break; default: LOG_FAULT("Invalid type %d", type); goto done; } retval = PWR_RET_SUCCESS; done: /* * Clean up and return. */ if (tmp_buf) g_free(tmp_buf); TRACE2_EXIT("retval = %d", retval); return retval; } int convert_double_to_uint64(const double *dvalue, uint64_t *ivalue) { int retval = PWR_RET_FAILURE; double dval = 0.0; uint64_t ival = 0; TRACE2_ENTER("dvalue = %p, ivalue = %p", dvalue, ivalue); dval = *dvalue; ival = dval; if ((double)ival == dval) { retval = PWR_RET_SUCCESS; *ivalue = ival; } TRACE2_EXIT("retval = %d, dval = %lf, ival = %lu", retval, dval, ival); return retval; }
2.15625
2
2024-11-18T21:15:31.657344+00:00
2012-12-03T22:56:05
54859e761c726f69ea0b83215cd62ea750ce4171
{ "blob_id": "54859e761c726f69ea0b83215cd62ea750ce4171", "branch_name": "refs/heads/master", "committer_date": "2012-12-03T22:56:05", "content_id": "cbf8cea8be749368e1411eb045da0768efdb70ec", "detected_licenses": [ "BSD-Source-Code" ], "directory_id": "d350566d5f0ee5abaad9dfbabb50438a857538f5", "extension": "c", "filename": "537sim.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": 3630, "license": "BSD-Source-Code", "license_type": "permissive", "path": "/a3/537sim.c", "provenance": "stackv2-0112.json.gz:733", "repo_name": "yyeap/cs537", "revision_date": "2012-12-03T22:56:05", "revision_id": "8c3e9f1ad31813a7fc8bc1142e52221fda731de6", "snapshot_id": "c168cbbe5c2e1a8660b35322f88c9ce5101c6cba", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/yyeap/cs537/8c3e9f1ad31813a7fc8bc1142e52221fda731de6/a3/537sim.c", "visit_date": "2021-01-19T10:42:22.423121" }
stackv2
/* Yuen Lye Yeap Lee Yerkes 537sim.c Contains implementation of simulator main loop and stuff. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "process.h" #include "stcf.h" #include "expq.h" #include "stats.h" #include "disk.h" #include "input.h" void (*add_process)(struct Process*); struct Process* (*get_process)(void); long (*get_timeslice)(long, int*); void (*init_q)(void); int main (int argc, char* argv[]){ struct Process* current_process; struct Process* temp_process; long clock = 0; long io = 0; long ts = 0; long ar = 0; long stepTime = 0; int reason; /*use STCF by default*/ add_process = stcf_add_process; get_process = stcf_get_process; get_timeslice = stcf_get_timeslice; init_q = stcf_init_q; if (2 < argc){ printf("ERROR: 537sim only takes one argument."); exit(-1); } /*use EXPQ algorithm functions if specified*/ /*if user passes bad parameter, just use STCF*/ if(!strncmp(argv[1], "expq", 4)){ add_process = expq_add_process; get_process = expq_get_process; get_timeslice = expq_get_timeslice; init_q = expq_init_q; printf("Running simulator with EXPQ\n"); } else { printf("Running simulator with STCF\n"); } init_stats(); init_disk(); init_q(); current_process = NULL; temp_process = NULL; reason = 0; while(1) { if (NULL != current_process) { clock++; update_io_remain(1); } io = get_IO_complete(); ts = get_timeslice(clock, &reason); ar = get_arrival(); /*EVENT simulation completed*/ if(ar == -1 && ts == -1) { /*display stats, destroy and exit*/ displayStats(clock); free(current_process); free(temp_process); exit(0); } if (ar <= clock) { if (current_process != NULL) { current_process = get_process(); current_process->cpu_remaining -= (ar - clock); current_process->lastRunTime += (ar - clock); add_process(current_process); } /* fetch new process from trace */ current_process = get_next_process(); add_process(current_process); } else { /* stepTime = min (io, ts, ar - clock) */ if (io <= ts && io <= (ar - clock)) { stepTime = io; } else if (ts <= io && ts <= (ar - clock)) { stepTime = ts; } else { stepTime = ar - clock; } if (stepTime == io && stepTime != -1) { temp_process = get_next_io(); add_process(temp_process); clock += stepTime + 1; } else if (stepTime == ts) { switch (reason) { case 0: temp_process = get_process(); temp_process->cpu_remaining -= ts + 1; temp_process->lastRunTime += ts; io_add_process(temp_process); clock += ts + 1; break; case 1: current_process = get_process(); updateStats(current_process, clock); break; case 2: temp_process = get_process(); temp_process->cpu_remaining -= ts; temp_process->lastRunTime += ts; add_process(temp_process); break; default: printf("Unexpected error\n"); exit(-1); } } } } return 0; }
2.953125
3
2024-11-18T21:15:32.049541+00:00
2017-12-16T03:55:06
5566afdab8dc8ea05bee18824dcecea361dde2e5
{ "blob_id": "5566afdab8dc8ea05bee18824dcecea361dde2e5", "branch_name": "refs/heads/master", "committer_date": "2017-12-16T03:55:06", "content_id": "45cce52903aecda4921d8f7adab59146afe858d5", "detected_licenses": [ "MIT" ], "directory_id": "24bc9fb80e514077f2445c501285ccf82ca12249", "extension": "c", "filename": "cli.c", "fork_events_count": 2, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 114431648, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 16087, "license": "MIT", "license_type": "permissive", "path": "/cli.c", "provenance": "stackv2-0112.json.gz:1375", "repo_name": "SebMiller/esp-cli", "revision_date": "2017-12-16T03:55:06", "revision_id": "de77919a8bb9a5e188f8c8198fe39658f79c3bde", "snapshot_id": "22c513b446ad10857c244dfd9eb0d12fce353810", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/SebMiller/esp-cli/de77919a8bb9a5e188f8c8198fe39658f79c3bde/cli.c", "visit_date": "2021-09-03T06:37:09.275233" }
stackv2
#include <stdio.h> #include <string.h> #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "cli.h" #include "cmd_run.h" #include "cmd_create.h" #define CLI_TASK_NAME CONFIG_CLI_TASK_NAME #define CLI_TASK_STACK CONFIG_CLI_TASK_STACK #define CLI_TASK_PRI CONFIG_CLI_TASK_PRI #if defined(CONFIG_CLI_ANSI_ESCAPE_CODE_ENABLED) #define CLI_ANSI_ESCAPE_CODE_ENABLED 1 #else #define CLI_ANSI_ESCAPE_CODE_ENABLED 0 #endif #if defined(CONFIG_CLI_HISTORY_ENABLED) && CLI_ANSI_ESCAPE_CODE_ENABLED==1 #define CLI_HISTORY_ENABLED 1 #else #define CLI_HISTORY_ENABLED 0 #endif #if CLI_HISTORY_ENABLED==1 #define CLI_HISTORY_LEN (CONFIG_CLI_HISTORY_LEN+1) #else #define CLI_HISTORY_LEN (1+1) #endif #define CLI_MAX_LENGTH CONFIG_CLI_MAX_LEN #define CLI_AUTOCOMPLETE_ENABLED CONFIG_CLI_AUTOCOMPLETE_ENABLED static char data_buff[CLI_HISTORY_LEN*CLI_MAX_LENGTH]; struct cli_status_s { bool inited; uint8_t delimiter; int current_length; int current_pos; int current_hist; bool insert; char* data[CLI_HISTORY_LEN]; vprintf_like_t log_print_func; flush_fc_t log_flush_func; vprintf_like_t cli_print_func; flush_fc_t cli_flush_func; TaskHandle_t task_handle; bool running_sync_command; }; static struct cli_status_s cli_status; extern cli_funct_info_t __cli_commands_start[], __cli_commands_end[]; int log_vprintf(const char* format, va_list args); int cli_output(const char* format, ...); void draw_cli(void); void clear_cli(void); void redraw_cli(void); void cli_task(void); int flush_default(void) { return fflush(NULL); } void esp_cli_init(cli_init_t init) { if ( cli_status.inited ) { cli_printf("WARNING!! Detected a second attempt to init the CLI.\nThe CLI has already been inited, so this attempt will be ignored.\n"); return; } esp_log_set_vprintf(log_vprintf); cli_status.delimiter = init.delimiter; cli_status.current_length = 0; cli_status.current_pos = 0; cli_status.current_hist = 0; cli_status.insert = false; for (int i=0 ; i<CLI_HISTORY_LEN ; i++) { cli_status.data[i] = data_buff+CLI_MAX_LENGTH*i; memset(cli_status.data[i], 0, CLI_MAX_LENGTH); } cli_status.log_print_func = init.log_print_func; cli_status.log_flush_func = init.log_flush_func; if ( init.cli_print_func != NULL ) { cli_status.cli_print_func = init.cli_print_func; } else { ESP_LOGE("CLI", "The CLI print function cannot be set to NULL."); } if ( init.cli_flush_func != NULL ) { cli_status.cli_flush_func = init.cli_flush_func; } else { ESP_LOGE("CLI", "The CLI flush function cannot be set to NULL."); } cli_status.running_sync_command = false; draw_cli(); xTaskCreate((TaskFunction_t)cli_task, CLI_TASK_NAME, CLI_TASK_STACK, NULL, CLI_TASK_PRI, &(cli_status.task_handle)); cli_status.inited = true; } /* Logging redirection */ int log_vprintf(const char* format, va_list args) { // Clear and draw CLI only if the logging is output on the same interface if ( cli_status.log_print_func == cli_status.cli_print_func && !cli_status.running_sync_command ) { clear_cli(); } int ret = 0; if ( cli_status.log_print_func != NULL ) { ret = cli_status.log_print_func(format, args); if ( cli_status.log_flush_func != NULL ) { cli_status.log_flush_func(); } } if ( cli_status.log_print_func == cli_status.cli_print_func && !cli_status.running_sync_command ) { draw_cli(); } return ret; } /* CLI printing */ int cli_printf(const char* format, ...) { va_list list; va_start(list, format); int ret = cli_vprintf(format, list); va_end(list); return ret; } int cli_vprintf(const char* format, va_list args) { if ( !cli_status.running_sync_command ) { clear_cli(); } int ret = cli_status.cli_print_func(format, args); if ( !cli_status.running_sync_command ) { draw_cli(); } return ret; } int cli_output(const char* format, ...) { va_list list; va_start(list, format); int ret = cli_status.cli_print_func(format, list); va_end(list); return ret; } void draw_cli(void) { cli_output("%c %.*s", cli_status.delimiter, cli_status.current_length, cli_status.data[cli_status.current_hist]); #if CLI_ANSI_ESCAPE_CODE_ENABLED==1 for (int i=cli_status.current_pos ; i<cli_status.current_length ; i++) { cli_output("\033[1D"); } #endif cli_status.cli_flush_func(); } void clear_cli(void) { #if CLI_ANSI_ESCAPE_CODE_ENABLED==1 cli_output(" "); int pos = cli_status.current_pos; while ( pos < cli_status.current_length ) { cli_output("\033[1C"); pos++; } for (int i=0 ; i<cli_status.current_length+2+1 ; i++) { cli_output("\033[1D\033[1D"); cli_output(" "); } cli_output("\033[1D"); #else cli_output("\r"); for (int i=0 ; i<CLI_MAX_LENGTH+2 ; i++) { cli_output(" "); } cli_output("\r"); #endif //CLI_ANSI_ESCAPE_CODE_ENABLED==1 } void redraw_cli(void) { clear_cli(); draw_cli(); } /* CLI manipulation */ void cli_add_char_at(int pos, uint8_t val, bool overwrite) { if (cli_status.current_length < CLI_MAX_LENGTH-1 && pos <= cli_status.current_length) { clear_cli(); #if CLI_HISTORY_ENABLED==1 if (cli_status.current_hist > 0) { memcpy(cli_status.data[0], cli_status.data[cli_status.current_hist], CLI_MAX_LENGTH); cli_status.current_hist = 0; } #endif //CLI_HISTORY_ENABLED==1 if (pos == cli_status.current_length) { overwrite = false; } if (!overwrite) { for (int i=cli_status.current_length ; i>=0 && i>pos ; i--) { cli_status.data[cli_status.current_hist][i] = cli_status.data[cli_status.current_hist][i-1]; } } cli_status.data[cli_status.current_hist][pos] = val; cli_status.current_pos++; if (!overwrite) { cli_status.current_length++; } draw_cli(); } } void cli_remove_char_at(int pos, bool move_back) { if (cli_status.current_length > 0 && ((move_back && cli_status.current_pos>0) || (!move_back && cli_status.current_pos>=0)) && pos < cli_status.current_length) { clear_cli(); #if CLI_HISTORY_ENABLED==1 if (cli_status.current_hist > 0) { memcpy(cli_status.data[0], cli_status.data[cli_status.current_hist], CLI_MAX_LENGTH); cli_status.current_hist = 0; } #endif //CLI_HISTORY_ENABLED==1 for (int i=pos ; i<cli_status.current_length-1 ; i++) { cli_status.data[cli_status.current_hist][i] = cli_status.data[cli_status.current_hist][i+1]; } cli_status.data[cli_status.current_hist][cli_status.current_length-1] = 0; if (move_back) { cli_status.current_pos--; } cli_status.current_length--; draw_cli(); } } #if CLI_HISTORY_ENABLED==1 void up_history() { if (cli_status.current_hist < CLI_HISTORY_LEN-1) { if (strlen((char*)cli_status.data[cli_status.current_hist+1]) > 0) { clear_cli(); cli_status.current_hist++; cli_status.current_length = strlen((char*)cli_status.data[cli_status.current_hist]); cli_status.current_pos = cli_status.current_length; draw_cli(); } } } void down_history() { if (cli_status.current_hist > 0) { clear_cli(); cli_status.current_hist--; cli_status.current_length = strlen((char*)cli_status.data[cli_status.current_hist]); cli_status.current_pos = cli_status.current_length; draw_cli(); } } #else void up_history() {} void down_history() {} #endif //CLI_HISTORY_ENABLED==1 #if CLI_AUTOCOMPLETE_ENABLED==1 int autocomplete (int tab_cnt) { if (strlen((char*)cli_status.data[cli_status.current_hist]) == 0) { return tab_cnt; } else { for (int i=0 ; i<cli_status.current_pos ; i++) { if ( cli_status.data[cli_status.current_hist][i] == ' ' ) { return tab_cnt; } } cli_funct_info_t* cmd_info; int res_cnt = 0; char* complete = NULL; for (cmd_info=__cli_commands_start ; cmd_info<__cli_commands_end ; cmd_info++) { if ( strncmp(cli_status.data[cli_status.current_hist], cmd_info->name, cli_status.current_pos) == 0 ) { if (res_cnt == 0) { if ( tab_cnt > 1 ) { cli_output("\n"); } else { complete = malloc( strlen(cmd_info->name) + 1 ); strcpy(complete, cmd_info->name); } } else if ( tab_cnt == 1 ) { int len1 = strlen(complete)+1; int len2 = strlen(cmd_info->name)+1; for (int i=0 ; i<len1 && i<len2 ; i++) { if (complete[i] != cmd_info->name[i]) { complete[i] = '\0'; break; } } } if ( tab_cnt > 1 ) { cli_printf("%s\n", cmd_info->name); } res_cnt++; } } redraw_cli(); if ( tab_cnt == 1 && complete != NULL ) { int len = strlen(complete); if (cli_status.current_pos < len) { tab_cnt = 0; } for (int i=cli_status.current_pos ; i<len ; i++) { cli_add_char_at(cli_status.current_pos, complete[i], false); } if (res_cnt == 1) { cli_add_char_at(cli_status.current_pos, ' ', false); } } if (complete != NULL) { free(complete); } return tab_cnt; } } #else int autocomplete (int tab_cnt) { return tab_cnt; } #endif //CLI_AUTOCOMPLETE_ENABLED==1 /* CLI task utilities */ void parse_cmd_line() { if (strlen((char*)cli_status.data[cli_status.current_hist]) == 0) { cli_output("\n"); redraw_cli(); } else { cli_output("\n"); clear_cli(); if (cli_status.current_hist > 0) { memcpy(cli_status.data[0], cli_status.data[cli_status.current_hist], CLI_MAX_LENGTH); } char* tmp = cli_status.data[CLI_HISTORY_LEN-1]; for (int i=CLI_HISTORY_LEN-1 ; i>0 ; i--) { cli_status.data[i] = cli_status.data[i-1]; } cli_status.data[0] = tmp; memset(cli_status.data[0], 0, CLI_MAX_LENGTH); cli_status.current_hist = 0; cli_status.current_length = strlen((char*)cli_status.data[cli_status.current_hist]); cli_status.current_pos = cli_status.current_length; int cmd_run_len = strlen(cli_status.data[1]); bool async = false; for (int i=cmd_run_len-1 ; i>0 ; i--) { if ( cli_status.data[1][i] == '&' ) { async = true; break; } else if ( cli_status.data[1][i] != ' ' ) { break; } } int ret; if ( async ) { ret = CLI_RUN_ASYNC(cli_status.data[1]); } else { cli_status.running_sync_command = true; ret = CLI_RUN(cli_status.data[1]); } if ( ret == CLI_CMD_RETURN_ASYNC_TIMEOUT || ret == CLI_CMD_RETURN_RUNTIME_ERROR ) { cli_printf("Error running the command...\n"); } else if ( ret == CLI_CMD_RETURN_CMD_NOT_FOUND ) { cli_printf("Command not found\n"); } cli_status.running_sync_command = false; redraw_cli(); } } #if CLI_ANSI_ESCAPE_CODE_ENABLED==1 #define SPECIAL_CMD_MAX_LEN 3 int process_special_command(uint8_t val) { static int special_cmd = 0; static uint8_t special_cmd_str[SPECIAL_CMD_MAX_LEN] = {0}; static uint8_t special_cmd_ptr = 0; special_cmd_str[special_cmd_ptr] = val; switch (special_cmd_str[special_cmd_ptr]) { case '[': { if (special_cmd_ptr == 0) { special_cmd = 1; } else { special_cmd = -1; } } break; case '2': { // followed by '~' is insert if (special_cmd_ptr != 1) { special_cmd = -1; } } case '3': { // followed by '~' is delete if (special_cmd_ptr != 1) { special_cmd = -1; } } break; case '~': { if (special_cmd_ptr == 2 && special_cmd_str[1] == '2') { // insert cli_status.insert = !cli_status.insert; special_cmd = 2; } else if (special_cmd_ptr == 2 && special_cmd_str[1] == '3') { // delete cli_remove_char_at(cli_status.current_pos, false); special_cmd = 2; } else { special_cmd = -1; } } break; case 'A': { // up arrow up_history(); special_cmd = 2; } break; case 'B': { // down arrow down_history(); special_cmd = 2; } break; case 'C': { // right arrow if (cli_status.current_pos < cli_status.current_length) { cli_status.current_pos++; } special_cmd = 2; } break; case 'D': { // left arrow if (cli_status.current_pos > 0) { cli_status.current_pos--; } special_cmd = 2; } break; case 0xff: { special_cmd_ptr--; // ignore this character } break; default: { special_cmd = -1; } break; } special_cmd_ptr++; if (special_cmd == 2) { // special command was executed, forget characters special_cmd_ptr = SPECIAL_CMD_MAX_LEN; } else if (special_cmd == -1) { // the string was not a special command for (int i=0 ; i<special_cmd_ptr ; i++) { cli_add_char_at(cli_status.current_pos, special_cmd_str[i], cli_status.insert); } special_cmd_ptr = SPECIAL_CMD_MAX_LEN; } if (special_cmd_ptr == SPECIAL_CMD_MAX_LEN) { // too many characters for a special command or command done for (int i=0 ; i<SPECIAL_CMD_MAX_LEN ; i++) { special_cmd_str[i] = 0; } special_cmd_ptr = 0; special_cmd = 0; redraw_cli(); } return special_cmd; } #else int process_special_command(uint8_t val) { return 0; } #endif //CLI_ANSI_ESCAPE_CODE_ENABLED==1 void process_char(uint8_t val) { static int special_cmd = 0; static int tab_count = 0; if (val == 0x08) { // backspace cli_remove_char_at(cli_status.current_pos-1, true); } if (val == 0x09) { // tab tab_count++; tab_count = autocomplete(tab_count); } else if (0x01 <= val && val <= 0xfe) { tab_count = 0; } if (val == 0x0A) { // new line parse_cmd_line(); } if (val == 0x0D) { // carriage return cli_printf("Carriage return\n"); } #if CLI_ANSI_ESCAPE_CODE_ENABLED==1 if (val == '[') { special_cmd = 1; } else #endif //CLI_ANSI_ESCAPE_CODE_ENABLED==1 if (0x20 <= val && val <= 0x7f) { if (!special_cmd) { cli_add_char_at(cli_status.current_pos, val, cli_status.insert); } } #if CLI_ANSI_ESCAPE_CODE_ENABLED==1 if (special_cmd) { special_cmd = process_special_command(val); } #endif //CLI_ANSI_ESCAPE_CODE_ENABLED==1 } /* CLI task */ void cli_task() { while (1) { uint8_t in = getchar(); process_char(in); vTaskDelay(pdMS_TO_TICKS(20)); } }
2.21875
2
2024-11-18T21:15:32.138840+00:00
2021-03-03T15:57:57
0864c696a765a1c4b1b6ffef15b82adc8e22eb65
{ "blob_id": "0864c696a765a1c4b1b6ffef15b82adc8e22eb65", "branch_name": "refs/heads/master", "committer_date": "2021-03-03T15:57:57", "content_id": "8a8fbc236278c004985510733a77f81110b49b33", "detected_licenses": [ "MIT" ], "directory_id": "9d7ba8760c454ba048bd80d9c5a580c273ee170a", "extension": "c", "filename": "main.c", "fork_events_count": 0, "gha_created_at": "2021-02-24T15:13:00", "gha_event_created_at": "2021-03-01T14:22:38", "gha_language": "C", "gha_license_id": "MIT", "github_id": 341940098, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 11356, "license": "MIT", "license_type": "permissive", "path": "/test/main.c", "provenance": "stackv2-0112.json.gz:1503", "repo_name": "florianchesneau/DevCommeLesPros-2021-Exo2", "revision_date": "2021-03-03T15:57:57", "revision_id": "50b280ab9f2f87cc211b24512fd050f05524829a", "snapshot_id": "02b43462ee0d5c2be7a22cfece11a8d41a96b0d9", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/florianchesneau/DevCommeLesPros-2021-Exo2/50b280ab9f2f87cc211b24512fd050f05524829a/test/main.c", "visit_date": "2023-03-17T11:20:01.749115" }
stackv2
#include "chiffrage.h" #include "test_harness/test_harness.h" #include <stdlib.h> #include <string.h> // Valeurs pour le harnais de test spécifiques à ce programme. int const tests_total = 68; int const test_column_width = 80; #define TAILLE_CHAINE 128 int main() { char clair[TAILLE_CHAINE], chiffre[TAILLE_CHAINE]; // Tests chiffre_ROT13 strcpy(clair, "a"); TEST(strcmp(chiffre_ROT13(clair), "n") == 0); strcpy(clair, "abcdefghijklmnopqrstuvwxyz"); TEST(strcmp(chiffre_ROT13(clair), "nopqrstuvwxyzabcdefghijklm") == 0); strcpy(clair, "aBcdEFghiJKLmnopQRSTuVwXyZ"); TEST(strcmp(chiffre_ROT13(clair), "nOpqRStuvWXYzabcDEFGhIjKlM") == 0); strcpy(clair, "A, a."); TEST(strcmp(chiffre_ROT13(clair), "N, n.") == 0); strcpy(clair, "Je laisse mes biens à ma soeur ? Non ! À mon neveu. Jamais sera payé le compte du tailleur. Rien aux pauvres."); TEST(strcmp(chiffre_ROT13(clair), "Wr ynvffr zrf ovraf à zn fbrhe ? Aba ! À zba arirh. Wnznvf fren cnlé yr pbzcgr qh gnvyyrhe. Evra nhk cnhierf.") == 0); // Tests dechiffre_ROT13. strcpy(chiffre, "n"); TEST(strcmp(dechiffre_ROT13(chiffre), "a") == 0); strcpy(chiffre, "nopqrstuvwxyzabcdefghijklm"); TEST(strcmp(dechiffre_ROT13(chiffre), "abcdefghijklmnopqrstuvwxyz") == 0); strcpy(chiffre, "nOpqRStuvWXYzabcDEFGhIjKlM"); TEST(strcmp(dechiffre_ROT13(chiffre), "aBcdEFghiJKLmnopQRSTuVwXyZ") == 0); strcpy(chiffre, "N, n."); TEST(strcmp(dechiffre_ROT13(chiffre), "A, a.") == 0); strcpy(chiffre, "Wr ynvffr zrf ovraf à zn fbrhe ? Aba ! À zba arirh. Wnznvf fren cnlé yr pbzcgr qh gnvyyrhe. Evra nhk cnhierf."); TEST(strcmp(dechiffre_ROT13(chiffre), "Je laisse mes biens à ma soeur ? Non ! À mon neveu. Jamais sera payé le compte du tailleur. Rien aux pauvres.") == 0); // Test chiffre_Cesar. strcpy(clair, "a"); TEST(strcmp(chiffre_Cesar(clair, 'a'), "a") == 0); strcpy(clair, "a"); TEST(strcmp(chiffre_Cesar(clair, 'c'), "c") == 0); strcpy(clair, "a"); TEST(strcmp(chiffre_Cesar(clair, 'z'), "z") == 0); strcpy(clair, "abcdefghijklmnopqrstuvwxyz"); TEST(strcmp(chiffre_Cesar(clair, 'a'), "abcdefghijklmnopqrstuvwxyz") == 0); strcpy(clair, "abcdefghijklmnopqrstuvwxyz"); TEST(strcmp(chiffre_Cesar(clair, 'c'), "cdefghijklmnopqrstuvwxyzab") == 0); strcpy(clair, "abcdefghijklmnopqrstuvwxyz"); TEST(strcmp(chiffre_Cesar(clair, 'z'), "zabcdefghijklmnopqrstuvwxy") == 0); strcpy(clair, "aBcdEFghiJKLmnopQRSTuVwXyZ"); TEST(strcmp(chiffre_Cesar(clair, 'a'), "aBcdEFghiJKLmnopQRSTuVwXyZ") == 0); strcpy(clair, "aBcdEFghiJKLmnopQRSTuVwXyZ"); TEST(strcmp(chiffre_Cesar(clair, 'c'), "cDefGHijkLMNopqrSTUVwXyZaB") == 0); strcpy(clair, "aBcdEFghiJKLmnopQRSTuVwXyZ"); TEST(strcmp(chiffre_Cesar(clair, 'z'), "zAbcDEfghIJKlmnoPQRStUvWxY") == 0); strcpy(clair, "A, a."); TEST(strcmp(chiffre_Cesar(clair, 'a'), "A, a.") == 0); strcpy(clair, "A, a."); TEST(strcmp(chiffre_Cesar(clair, 'c'), "C, c.") == 0); strcpy(clair, "A, a."); TEST(strcmp(chiffre_Cesar(clair, 'z'), "Z, z.") == 0); strcpy(clair, "Je laisse mes biens à ma soeur. Non à mon neveu. Jamais sera payé le compte du tailleur. Rien aux pauvres."); TEST(strcmp(chiffre_Cesar(clair, 'a'), "Je laisse mes biens à ma soeur. Non à mon neveu. Jamais sera payé le compte du tailleur. Rien aux pauvres.") == 0); strcpy(clair, "Je laisse mes biens à ma soeur. Non à mon neveu. Jamais sera payé le compte du tailleur. Rien aux pauvres."); TEST(strcmp(chiffre_Cesar(clair, 'c'), "Lg nckuug ogu dkgpu à oc uqgwt. Pqp à oqp pgxgw. Lcocku ugtc rcaé ng eqorvg fw vcknngwt. Tkgp cwz rcwxtgu.") == 0); strcpy(clair, "Je laisse mes biens à ma soeur. Non à mon neveu. Jamais sera payé le compte du tailleur. Rien aux pauvres."); TEST(strcmp(chiffre_Cesar(clair, 'z'), "Id kzhrrd ldr ahdmr à lz rndtq. Mnm à lnm mdudt. Izlzhr rdqz ozxé kd bnlosd ct szhkkdtq. Qhdm ztw oztuqdr.") == 0); // Tests dechiffre_Cesar. strcpy(chiffre, "a"); TEST(strcmp(dechiffre_Cesar(chiffre, 'a'), "a") == 0); strcpy(chiffre, "c"); TEST(strcmp(dechiffre_Cesar(chiffre, 'c'), "a") == 0); strcpy(chiffre, "z"); TEST(strcmp(dechiffre_Cesar(chiffre, 'z'), "a") == 0); strcpy(chiffre, "abcdefghijklmnopqrstuvwxyz"); TEST(strcmp(dechiffre_Cesar(chiffre, 'a'), "abcdefghijklmnopqrstuvwxyz") == 0); strcpy(chiffre, "cdefghijklmnopqrstuvwxyzab"); TEST(strcmp(dechiffre_Cesar(chiffre, 'c'), "abcdefghijklmnopqrstuvwxyz") == 0); strcpy(chiffre, "zabcdefghijklmnopqrstuvwxy"); TEST(strcmp(dechiffre_Cesar(chiffre, 'z'), "abcdefghijklmnopqrstuvwxyz") == 0); strcpy(chiffre, "aBcdEFghiJKLmnopQRSTuVwXyZ"); TEST(strcmp(dechiffre_Cesar(chiffre, 'a'), "aBcdEFghiJKLmnopQRSTuVwXyZ") == 0); strcpy(chiffre, "cDefGHijkLMNopqrSTUVwXyZaB"); TEST(strcmp(dechiffre_Cesar(chiffre, 'c'), "aBcdEFghiJKLmnopQRSTuVwXyZ") == 0); strcpy(chiffre, "zAbcDEfghIJKlmnoPQRStUvWxY"); TEST(strcmp(dechiffre_Cesar(chiffre, 'z'), "aBcdEFghiJKLmnopQRSTuVwXyZ") == 0); strcpy(chiffre, "A, a."); TEST(strcmp(dechiffre_Cesar(chiffre, 'a'), "A, a.") == 0); strcpy(chiffre, "C, c."); TEST(strcmp(dechiffre_Cesar(chiffre, 'c'), "A, a.") == 0); strcpy(chiffre, "Z, z."); TEST(strcmp(dechiffre_Cesar(chiffre, 'z'), "A, a.") == 0); strcpy(chiffre, "Je laisse mes biens à ma soeur. Non à mon neveu. Jamais sera payé le compte du tailleur. Rien aux pauvres."); TEST(strcmp(dechiffre_Cesar(chiffre, 'a'), "Je laisse mes biens à ma soeur. Non à mon neveu. Jamais sera payé le compte du tailleur. Rien aux pauvres.") == 0); strcpy(chiffre, "Lg nckuug ogu dkgpu à oc uqgwt. Pqp à oqp pgxgw. Lcocku ugtc rcaé ng eqorvg fw vcknngwt. Tkgp cwz rcwxtgu."); TEST(strcmp(dechiffre_Cesar(chiffre, 'c'), "Je laisse mes biens à ma soeur. Non à mon neveu. Jamais sera payé le compte du tailleur. Rien aux pauvres.") == 0); strcpy(chiffre, "Id kzhrrd ldr ahdmr à lz rndtq. Mnm à lnm mdudt. Izlzhr rdqz ozxé kd bnlosd ct szhkkdtq. Qhdm ztw oztuqdr."); TEST(strcmp(dechiffre_Cesar(chiffre, 'z'), "Je laisse mes biens à ma soeur. Non à mon neveu. Jamais sera payé le compte du tailleur. Rien aux pauvres.") == 0); // Tests chiffre_Vigenere. strcpy(clair, "a"); TEST(strcmp(chiffre_Vigenere(clair, "a"), "a") == 0); strcpy(clair, "abcdefghijklmnopqrstuvwxyz"); TEST(strcmp(chiffre_Vigenere(clair, "a"), "abcdefghijklmnopqrstuvwxyz") == 0); strcpy(clair, "abcdefghijklmnopqrstuvwxyz"); TEST(strcmp(chiffre_Vigenere(clair,"abc"), "acedfhgikjlnmoqprtsuwvxzya") == 0); strcpy(clair, "abcdefghijklmnopqrstuvwxyz"); TEST(strcmp(chiffre_Vigenere(clair,"zzz"), "zabcdefghijklmnopqrstuvwxy") == 0); strcpy(clair, "aBcdEFghiJKLmnopQRSTuVwXyZ"); TEST(strcmp(chiffre_Vigenere(clair, "a"), "aBcdEFghiJKLmnopQRSTuVwXyZ") == 0); strcpy(clair, "aBcdEFghiJKLmnopQRSTuVwXyZ"); TEST(strcmp(chiffre_Vigenere(clair, "abc"), "aCedFHgikJLNmoqpRTSUwVxZyA") == 0); strcpy(clair, "aBcdEFghiJKLmnopQRSTuVwXyZ"); TEST(strcmp(chiffre_Vigenere(clair, "zzz"), "zAbcDEfghIJKlmnoPQRStUvWxY") == 0); strcpy(clair, "A, a."); TEST(strcmp(chiffre_Vigenere(clair, "a"), "A, a.") == 0); strcpy(clair, "A, a."); TEST(strcmp(chiffre_Vigenere(clair, "abc"), "A, b.") == 0); strcpy(clair, "A, a."); TEST(strcmp(chiffre_Vigenere(clair, "zzz"), "Z, z.") == 0); strcpy(clair, "Je laisse mes biens à ma soeur ? Non ! À mon neveu ? Jamais ! Sera payé le compte du tailleur. Rien aux pauvres."); TEST(strcmp(chiffre_Vigenere(clair, "a"), "Je laisse mes biens à ma soeur ? Non ! À mon neveu ? Jamais ! Sera payé le compte du tailleur. Rien aux pauvres.") == 0); strcpy(clair, "Je laisse mes biens à ma soeur ? Non ! À mon neveu ? Jamais ! Sera payé le compte du tailleur. Rien aux pauvres."); TEST(strcmp(chiffre_Vigenere(clair, "abc"), "Jf najusf oet difps à nc spgus ? Poo ! À ooo pewgu ? Kcmbks ! Tgrb razé ne dqmqve ew tbklmgus. Tifp avz pbwvsgs.") == 0); strcpy(clair, "Je laisse mes biens à ma soeur ? Non ! À mon neveu ? Jamais ! Sera payé le compte du tailleur. Rien aux pauvres."); TEST(strcmp(chiffre_Vigenere(clair, "zzz"), "Id kzhrrd ldr ahdmr à lz rndtq ? Mnm ! À lnm mdudt ? Izlzhr ! Rdqz ozxé kd bnlosd ct szhkkdtq. Qhdm ztw oztuqdr.") == 0); // Tests dechiffre_Vigenere. strcpy(chiffre, "a"); TEST(strcmp(dechiffre_Vigenere(chiffre, "a"), "a") == 0); strcpy(chiffre, "abcdefghijklmnopqrstuvwxyz"); TEST(strcmp(dechiffre_Vigenere(chiffre, "a"), "abcdefghijklmnopqrstuvwxyz") == 0); strcpy(chiffre, "acedfhgikjlnmoqprtsuwvxzya"); TEST(strcmp(dechiffre_Vigenere(chiffre,"abc"), "abcdefghijklmnopqrstuvwxyz") == 0); strcpy(chiffre, "zabcdefghijklmnopqrstuvwxy"); TEST(strcmp(dechiffre_Vigenere(chiffre,"zzz"), "abcdefghijklmnopqrstuvwxyz") == 0); strcpy(chiffre, "aBcdEFghiJKLmnopQRSTuVwXyZ"); TEST(strcmp(dechiffre_Vigenere(chiffre, "a"), "aBcdEFghiJKLmnopQRSTuVwXyZ") == 0); strcpy(chiffre, "aCedFHgikJLNmoqpRTSUwVxZyA"); TEST(strcmp(dechiffre_Vigenere(chiffre, "abc"), "aBcdEFghiJKLmnopQRSTuVwXyZ") == 0); strcpy(chiffre, "zAbcDEfghIJKlmnoPQRStUvWxY"); TEST(strcmp(dechiffre_Vigenere(chiffre, "zzz"), "aBcdEFghiJKLmnopQRSTuVwXyZ") == 0); strcpy(chiffre, "A, a."); TEST(strcmp(dechiffre_Vigenere(chiffre, "a"), "A, a.") == 0); strcpy(chiffre, "A, b."); TEST(strcmp(dechiffre_Vigenere(chiffre, "abc"), "A, a.") == 0); strcpy(chiffre, "Z, z."); TEST(strcmp(dechiffre_Vigenere(chiffre, "zzz"), "A, a.") == 0); strcpy(chiffre, "Je laisse mes biens à ma soeur ? Non ! À mon neveu ? Jamais ! Sera payé le compte du tailleur. Rien aux pauvres."); TEST(strcmp(dechiffre_Vigenere(chiffre, "a"), "Je laisse mes biens à ma soeur ? Non ! À mon neveu ? Jamais ! Sera payé le compte du tailleur. Rien aux pauvres.") == 0); strcpy(chiffre, "Jf najusf oet difps à nc spgus ? Poo ! À ooo pewgu ? Kcmbks ! Tgrb razé ne dqmqve ew tbklmgus. Tifp avz pbwvsgs."); TEST(strcmp(dechiffre_Vigenere(chiffre, "abc"), "Je laisse mes biens à ma soeur ? Non ! À mon neveu ? Jamais ! Sera payé le compte du tailleur. Rien aux pauvres.") == 0); strcpy(chiffre, "Id kzhrrd ldr ahdmr à lz rndtq ? Mnm ! À lnm mdudt ? Izlzhr ! Rdqz ozxé kd bnlosd ct szhkkdtq. Qhdm ztw oztuqdr."); TEST(strcmp(dechiffre_Vigenere(chiffre, "zzz"), "Je laisse mes biens à ma soeur ? Non ! À mon neveu ? Jamais ! Sera payé le compte du tailleur. Rien aux pauvres.") == 0); // Tests chiffre_Vigenere_flux_texte. FILE *fichier_resultat = fopen("build/resultat.txt", "w"); FILE *fichier_clair = fopen("test/clair.txt", "r"); chiffre_Vigenere_flux_texte(fichier_resultat, fichier_clair, "agatha"); fclose(fichier_clair); fclose(fichier_resultat); TEST_FILE("build/resultat.txt", "test/chiffre.txt"); // Tets dechiffre_Vigenere_flux_texte. fichier_resultat = fopen("build/resultat.txt", "w"); FILE *fichier_chiffre = fopen("test/chiffre.txt", "r"); dechiffre_Vigenere_flux_texte(fichier_resultat, fichier_chiffre, "agatha"); fclose(fichier_chiffre); fclose(fichier_resultat); TEST_FILE("build/resultat.txt", "test/clair.txt"); return tests_total - tests_successful; }
2.53125
3
2024-11-18T21:15:32.271119+00:00
2020-01-17T08:53:50
4a37a4d9d360fe3684318776ff4e113bf0aba0db
{ "blob_id": "4a37a4d9d360fe3684318776ff4e113bf0aba0db", "branch_name": "refs/heads/master", "committer_date": "2020-01-17T08:53:50", "content_id": "6dadfb9577cc7aa346dbb65bc8fd3d675755f74b", "detected_licenses": [ "MIT" ], "directory_id": "7c441af6a3f71dd766edfc34919182227cbd8815", "extension": "c", "filename": "mystsword.c", "fork_events_count": 0, "gha_created_at": "2020-01-17T08:46:06", "gha_event_created_at": "2023-05-07T19:53:16", "gha_language": "JavaScript", "gha_license_id": "MIT", "github_id": 234507910, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2365, "license": "MIT", "license_type": "permissive", "path": "/mudlib/daemon/skill/mystsword.c", "provenance": "stackv2-0112.json.gz:1761", "repo_name": "angeluslove/es2", "revision_date": "2020-01-17T08:53:50", "revision_id": "9e24d6c0272231214f32699cbac23f4bbace370d", "snapshot_id": "a0c69e57522cb940346c6805fd85e19cc0bbbad1", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/angeluslove/es2/9e24d6c0272231214f32699cbac23f4bbace370d/mudlib/daemon/skill/mystsword.c", "visit_date": "2023-05-26T04:21:12.032453" }
stackv2
// mystsword.c #include <ansi.h> inherit SKILL; mapping *action = ({ ([ "name": "暮雪三叹", "action": "$N使一招「暮雪三叹」,手中$w急如骤雨般地刺向$n$l", "dodge": -30, "damage": 60, "damage_type": "刺伤" ]), ([ "name": "处子弄笛", "action": "$N身形一晃,一招「处子弄笛」向$n$l刺出一剑", "dodge": -20, "damage": 80, "damage_type": "刺伤" ]), ([ "name": "阳谷白练", "action": "$N舞动$w,一招「阳谷白练」挟著闪闪剑光刺向$n的$l", "dodge": -40, "damage_type": "刺伤" ]), ([ "name": "薰容逐电", "action": "$N手中$w一个圈转,使出「薰容逐电」中锋直进刺向$n的$l", "dodge": -30, "damage": 100, "damage_type": "刺伤" ]), }); int valid_learn(object me) { object ob; if( (int)me->query_skill("mystforce",1) < 30 ) return notify_fail("你的步玄心法火候还不够。\n"); if( (int)me->query("max_force") < 100 ) return notify_fail("你的内力不够,没有办法练小步玄剑。\n"); if( !(ob = me->query_temp("weapon")) || (string)ob->query("skill_type") != "sword" ) return notify_fail("你必须先找一把剑才能练剑法。\n"); return 1; } int valid_enable(string usage) { return usage=="sword" || usage=="parry"; } mapping query_action(object me, object weapon) { return action[random(sizeof(action))]; } int practice_skill(object me) { if( (int)me->query("kee") < 30 || (int)me->query("force") < 5 ) return notify_fail("你的内力或气不够,没有办法练习小步玄剑。\n"); me->receive_damage("kee", 30); me->add("force", -5); write("你按著所学练了一遍小步玄剑。\n"); return 1; }
2.609375
3
2024-11-18T21:15:35.857744+00:00
2021-03-17T07:29:19
f9d5ac9d698a200884f191771bab45da5b266181
{ "blob_id": "f9d5ac9d698a200884f191771bab45da5b266181", "branch_name": "refs/heads/master", "committer_date": "2021-03-17T07:29:19", "content_id": "d42db3c75c42f0da388b9ab4519738565faf06ce", "detected_licenses": [ "Apache-2.0", "curl" ], "directory_id": "546018757d22ae76154b87335db68e1cfabfedcb", "extension": "c", "filename": "io_k8s_api_certificates_v1_certificate_signing_request_list.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 346627883, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 7929, "license": "Apache-2.0,curl", "license_type": "permissive", "path": "/kubernetes/model/io_k8s_api_certificates_v1_certificate_signing_request_list.c", "provenance": "stackv2-0112.json.gz:1889", "repo_name": "zouxiaoliang/nerv-kubernetes-client-c", "revision_date": "2021-03-17T07:29:19", "revision_id": "07528948c643270fd757d38edc68da8c9628ee7a", "snapshot_id": "45f1bca75b6265395f144d71bf6866de7b69bc25", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/zouxiaoliang/nerv-kubernetes-client-c/07528948c643270fd757d38edc68da8c9628ee7a/kubernetes/model/io_k8s_api_certificates_v1_certificate_signing_request_list.c", "visit_date": "2023-03-16T09:31:03.072968" }
stackv2
#include <stdlib.h> #include <string.h> #include <stdio.h> #include "io_k8s_api_certificates_v1_certificate_signing_request_list.h" io_k8s_api_certificates_v1_certificate_signing_request_list_t *io_k8s_api_certificates_v1_certificate_signing_request_list_create( char *api_version, list_t *items, char *kind, io_k8s_apimachinery_pkg_apis_meta_v1_list_meta_t *metadata ) { io_k8s_api_certificates_v1_certificate_signing_request_list_t *io_k8s_api_certificates_v1_certificate_signing_request_list_local_var = malloc(sizeof(io_k8s_api_certificates_v1_certificate_signing_request_list_t)); if (!io_k8s_api_certificates_v1_certificate_signing_request_list_local_var) { return NULL; } io_k8s_api_certificates_v1_certificate_signing_request_list_local_var->api_version = api_version; io_k8s_api_certificates_v1_certificate_signing_request_list_local_var->items = items; io_k8s_api_certificates_v1_certificate_signing_request_list_local_var->kind = kind; io_k8s_api_certificates_v1_certificate_signing_request_list_local_var->metadata = metadata; return io_k8s_api_certificates_v1_certificate_signing_request_list_local_var; } void io_k8s_api_certificates_v1_certificate_signing_request_list_free(io_k8s_api_certificates_v1_certificate_signing_request_list_t *io_k8s_api_certificates_v1_certificate_signing_request_list) { if(NULL == io_k8s_api_certificates_v1_certificate_signing_request_list){ return ; } listEntry_t *listEntry; if (io_k8s_api_certificates_v1_certificate_signing_request_list->api_version) { free(io_k8s_api_certificates_v1_certificate_signing_request_list->api_version); io_k8s_api_certificates_v1_certificate_signing_request_list->api_version = NULL; } if (io_k8s_api_certificates_v1_certificate_signing_request_list->items) { list_ForEach(listEntry, io_k8s_api_certificates_v1_certificate_signing_request_list->items) { io_k8s_api_certificates_v1_certificate_signing_request_free(listEntry->data); } list_free(io_k8s_api_certificates_v1_certificate_signing_request_list->items); io_k8s_api_certificates_v1_certificate_signing_request_list->items = NULL; } if (io_k8s_api_certificates_v1_certificate_signing_request_list->kind) { free(io_k8s_api_certificates_v1_certificate_signing_request_list->kind); io_k8s_api_certificates_v1_certificate_signing_request_list->kind = NULL; } if (io_k8s_api_certificates_v1_certificate_signing_request_list->metadata) { io_k8s_apimachinery_pkg_apis_meta_v1_list_meta_free(io_k8s_api_certificates_v1_certificate_signing_request_list->metadata); io_k8s_api_certificates_v1_certificate_signing_request_list->metadata = NULL; } free(io_k8s_api_certificates_v1_certificate_signing_request_list); } cJSON *io_k8s_api_certificates_v1_certificate_signing_request_list_convertToJSON(io_k8s_api_certificates_v1_certificate_signing_request_list_t *io_k8s_api_certificates_v1_certificate_signing_request_list) { cJSON *item = cJSON_CreateObject(); // io_k8s_api_certificates_v1_certificate_signing_request_list->api_version if(io_k8s_api_certificates_v1_certificate_signing_request_list->api_version) { if(cJSON_AddStringToObject(item, "apiVersion", io_k8s_api_certificates_v1_certificate_signing_request_list->api_version) == NULL) { goto fail; //String } } // io_k8s_api_certificates_v1_certificate_signing_request_list->items if (!io_k8s_api_certificates_v1_certificate_signing_request_list->items) { goto fail; } cJSON *items = cJSON_AddArrayToObject(item, "items"); if(items == NULL) { goto fail; //nonprimitive container } listEntry_t *itemsListEntry; if (io_k8s_api_certificates_v1_certificate_signing_request_list->items) { list_ForEach(itemsListEntry, io_k8s_api_certificates_v1_certificate_signing_request_list->items) { cJSON *itemLocal = io_k8s_api_certificates_v1_certificate_signing_request_convertToJSON(itemsListEntry->data); if(itemLocal == NULL) { goto fail; } cJSON_AddItemToArray(items, itemLocal); } } // io_k8s_api_certificates_v1_certificate_signing_request_list->kind if(io_k8s_api_certificates_v1_certificate_signing_request_list->kind) { if(cJSON_AddStringToObject(item, "kind", io_k8s_api_certificates_v1_certificate_signing_request_list->kind) == NULL) { goto fail; //String } } // io_k8s_api_certificates_v1_certificate_signing_request_list->metadata if(io_k8s_api_certificates_v1_certificate_signing_request_list->metadata) { cJSON *metadata_local_JSON = io_k8s_apimachinery_pkg_apis_meta_v1_list_meta_convertToJSON(io_k8s_api_certificates_v1_certificate_signing_request_list->metadata); if(metadata_local_JSON == NULL) { goto fail; //model } cJSON_AddItemToObject(item, "metadata", metadata_local_JSON); if(item->child == NULL) { goto fail; } } return item; fail: if (item) { cJSON_Delete(item); } return NULL; } io_k8s_api_certificates_v1_certificate_signing_request_list_t *io_k8s_api_certificates_v1_certificate_signing_request_list_parseFromJSON(cJSON *io_k8s_api_certificates_v1_certificate_signing_request_listJSON){ io_k8s_api_certificates_v1_certificate_signing_request_list_t *io_k8s_api_certificates_v1_certificate_signing_request_list_local_var = NULL; // io_k8s_api_certificates_v1_certificate_signing_request_list->api_version cJSON *api_version = cJSON_GetObjectItemCaseSensitive(io_k8s_api_certificates_v1_certificate_signing_request_listJSON, "apiVersion"); if (api_version) { if(!cJSON_IsString(api_version)) { goto end; //String } } // io_k8s_api_certificates_v1_certificate_signing_request_list->items cJSON *items = cJSON_GetObjectItemCaseSensitive(io_k8s_api_certificates_v1_certificate_signing_request_listJSON, "items"); if (!items) { goto end; } list_t *itemsList; cJSON *items_local_nonprimitive; if(!cJSON_IsArray(items)){ goto end; //nonprimitive container } itemsList = list_create(); cJSON_ArrayForEach(items_local_nonprimitive,items ) { if(!cJSON_IsObject(items_local_nonprimitive)){ goto end; } io_k8s_api_certificates_v1_certificate_signing_request_t *itemsItem = io_k8s_api_certificates_v1_certificate_signing_request_parseFromJSON(items_local_nonprimitive); list_addElement(itemsList, itemsItem); } // io_k8s_api_certificates_v1_certificate_signing_request_list->kind cJSON *kind = cJSON_GetObjectItemCaseSensitive(io_k8s_api_certificates_v1_certificate_signing_request_listJSON, "kind"); if (kind) { if(!cJSON_IsString(kind)) { goto end; //String } } // io_k8s_api_certificates_v1_certificate_signing_request_list->metadata cJSON *metadata = cJSON_GetObjectItemCaseSensitive(io_k8s_api_certificates_v1_certificate_signing_request_listJSON, "metadata"); io_k8s_apimachinery_pkg_apis_meta_v1_list_meta_t *metadata_local_nonprim = NULL; if (metadata) { metadata_local_nonprim = io_k8s_apimachinery_pkg_apis_meta_v1_list_meta_parseFromJSON(metadata); //nonprimitive } io_k8s_api_certificates_v1_certificate_signing_request_list_local_var = io_k8s_api_certificates_v1_certificate_signing_request_list_create ( api_version ? strdup(api_version->valuestring) : NULL, itemsList, kind ? strdup(kind->valuestring) : NULL, metadata ? metadata_local_nonprim : NULL ); return io_k8s_api_certificates_v1_certificate_signing_request_list_local_var; end: if (metadata_local_nonprim) { io_k8s_apimachinery_pkg_apis_meta_v1_list_meta_free(metadata_local_nonprim); metadata_local_nonprim = NULL; } return NULL; }
2.0625
2
2024-11-18T21:15:35.910475+00:00
2021-10-29T09:05:24
5c24cf34974c478444b3a8dfe8f00c9d10189c94
{ "blob_id": "5c24cf34974c478444b3a8dfe8f00c9d10189c94", "branch_name": "refs/heads/master", "committer_date": "2021-10-29T09:05:24", "content_id": "efdc5600e4a0ab37879cef006b0d48fa7e7d94c4", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "1302f5c484b09bcf0022cfe2abac2ec9a47303bc", "extension": "c", "filename": "inv_cmap.c", "fork_events_count": 0, "gha_created_at": "2021-10-30T15:21:35", "gha_event_created_at": "2021-10-30T15:21:35", "gha_language": null, "gha_license_id": "BSD-3-Clause", "github_id": 422917164, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 14723, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/image/inv_cmap.c", "provenance": "stackv2-0112.json.gz:2018", "repo_name": "yabets/TwelveMonkeys", "revision_date": "2021-10-29T09:05:24", "revision_id": "511a29beb91a8fffd89287b0ae62820b43770afe", "snapshot_id": "350d796a666cdd069d47bab1ef88a9c1adfe8861", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/yabets/TwelveMonkeys/511a29beb91a8fffd89287b0ae62820b43770afe/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/image/inv_cmap.c", "visit_date": "2023-08-24T06:25:23.776740" }
stackv2
/* * This software is copyrighted as noted below. It may be freely copied, * modified, and redistributed, provided that the copyright notice is * preserved on all copies. * * There is no warranty or other guarantee of fitness for this software, * it is provided solely "as is". Bug reports or fixes may be sent * to the author, who may or may not act on them as he desires. * * You may not include this software in a program or other software product * without supplying the source, or without informing the end-user that the * source is available for no extra charge. * * If you modify this software, you should include a notice giving the * name of the person performing the modification, the date of modification, * and the reason for such modification. */ /* * inv_cmap.c - Compute an inverse colormap. * * Author: Spencer W. Thomas * EECS Dept. * University of Michigan * Date: Thu Sep 20 1990 * Copyright (c) 1990, University of Michigan * * $Id: inv_cmap.c,v 3.0.1.3 1992/04/30 14:07:28 spencer Exp $ */ #include <math.h> #include <stdio.h> static int bcenter, gcenter, rcenter; static long gdist, rdist, cdist; static long cbinc, cginc, crinc; static unsigned long *gdp, *rdp, *cdp; static unsigned char *grgbp, *rrgbp, *crgbp; static gstride, rstride; static long x, xsqr, colormax; static int cindex; #ifdef USE_PROTOTYPES static void maxfill( unsigned long *, long ); static int redloop( void ); static int greenloop( int ); static int blueloop( int ); #else static void maxfill(); static int redloop(); static int greenloop(); static int blueloop(); #endif /***************************************************************** * TAG( inv_cmap ) * * Compute an inverse colormap efficiently. * Inputs: * colors: Number of colors in the forward colormap. * colormap: The forward colormap. * bits: Number of quantization bits. The inverse * colormap will have (2^bits)^3 entries. * dist_buf: An array of (2^bits)^3 long integers to be * used as scratch space. * Outputs: * rgbmap: The output inverse colormap. The entry * rgbmap[(r<<(2*bits)) + (g<<bits) + b] * is the colormap entry that is closest to the * (quantized) color (r,g,b). * Assumptions: * Quantization is performed by right shift (low order bits are * truncated). Thus, the distance to a quantized color is * actually measured to the color at the center of the cell * (i.e., to r+.5, g+.5, b+.5, if (r,g,b) is a quantized color). * Algorithm: * Uses a "distance buffer" algorithm: * The distance from each representative in the forward color map * to each point in the rgb space is computed. If it is less * than the distance currently stored in dist_buf, then the * corresponding entry in rgbmap is replaced with the current * representative (and the dist_buf entry is replaced with the * new distance). * * The distance computation uses an efficient incremental formulation. * * Distances are computed "outward" from each color. If the * colors are evenly distributed in color space, the expected * number of cells visited for color I is N^3/I. * Thus, the complexity of the algorithm is O(log(K) N^3), * where K = colors, and N = 2^bits. */ /* * Here's the idea: scan from the "center" of each cell "out" * until we hit the "edge" of the cell -- that is, the point * at which some other color is closer -- and stop. In 1-D, * this is simple: * for i := here to max do * if closer then buffer[i] = this color * else break * repeat above loop with i := here-1 to min by -1 * * In 2-D, it's trickier, because along a "scan-line", the * region might start "after" the "center" point. A picture * might clarify: * | ... * | ... . * ... . * ... | . * . + . * . . * . . * ......... * * The + marks the "center" of the above region. On the top 2 * lines, the region "begins" to the right of the "center". * * Thus, we need a loop like this: * detect := false * for i := here to max do * if closer then * buffer[..., i] := this color * if !detect then * here = i * detect = true * else * if detect then * break * * Repeat the above loop with i := here-1 to min by -1. Note that * the "detect" value should not be reinitialized. If it was * "true", and center is not inside the cell, then none of the * cell lies to the left and this loop should exit * immediately. * * The outer loops are similar, except that the "closer" test * is replaced by a call to the "next in" loop; its "detect" * value serves as the test. (No assignment to the buffer is * done, either.) * * Each time an outer loop starts, the "here", "min", and * "max" values of the next inner loop should be * re-initialized to the center of the cell, 0, and cube size, * respectively. Otherwise, these values will carry over from * one "call" to the inner loop to the next. This tracks the * edges of the cell and minimizes the number of * "unproductive" comparisons that must be made. * * Finally, the inner-most loop can have the "if !detect" * optimized out of it by splitting it into two loops: one * that finds the first color value on the scan line that is * in this cell, and a second that fills the cell until * another one is closer: * if !detect then {needed for "down" loop} * for i := here to max do * if closer then * buffer[..., i] := this color * detect := true * break * for i := i+1 to max do * if closer then * buffer[..., i] := this color * else * break * * In this implementation, each level will require the * following variables. Variables labelled (l) are local to each * procedure. The ? should be replaced with r, g, or b: * cdist: The distance at the starting point. * ?center: The value of this component of the color * c?inc: The initial increment at the ?center position. * ?stride: The amount to add to the buffer * pointers (dp and rgbp) to get to the * "next row". * min(l): The "low edge" of the cell, init to 0 * max(l): The "high edge" of the cell, init to * colormax-1 * detect(l): True if this row has changed some * buffer entries. * i(l): The index for this row. * ?xx: The accumulated increment value. * * here(l): The starting index for this color. The * following variables are associated with here, * in the sense that they must be updated if here * is changed. * ?dist: The current distance for this level. The * value of dist from the previous level (g or r, * for level b or g) initializes dist on this * level. Thus gdist is associated with here(b)). * ?inc: The initial increment for the row. * ?dp: Pointer into the distance buffer. The value * from the previous level initializes this level. * ?rgbp: Pointer into the rgb buffer. The value * from the previous level initializes this level. * * The blue and green levels modify 'here-associated' variables (dp, * rgbp, dist) on the green and red levels, respectively, when here is * changed. */ void inv_cmap( colors, colormap, bits, dist_buf, rgbmap ) int colors, bits; unsigned char *colormap[3], *rgbmap; unsigned long *dist_buf; { int nbits = 8 - bits; colormax = 1 << bits; x = 1 << nbits; xsqr = 1 << (2 * nbits); /* Compute "strides" for accessing the arrays. */ gstride = colormax; rstride = colormax * colormax; maxfill( dist_buf, colormax ); for ( cindex = 0; cindex < colors; cindex++ ) { /* * Distance formula is * (red - map[0])^2 + (green - map[1])^2 + (blue - map[2])^2 * * Because of quantization, we will measure from the center of * each quantized "cube", so blue distance is * (blue + x/2 - map[2])^2, * where x = 2^(8 - bits). * The step size is x, so the blue increment is * 2*x*blue - 2*x*map[2] + 2*x^2 * * Now, b in the code below is actually blue/x, so our * increment will be 2*(b*x^2 + x^2 - x*map[2]). For * efficiency, we will maintain this quantity in a separate variable * that will be updated incrementally by adding 2*x^2 each time. */ /* The initial position is the cell containing the colormap * entry. We get this by quantizing the colormap values. */ rcenter = colormap[0][cindex] >> nbits; gcenter = colormap[1][cindex] >> nbits; bcenter = colormap[2][cindex] >> nbits; rdist = colormap[0][cindex] - (rcenter * x + x/2); gdist = colormap[1][cindex] - (gcenter * x + x/2); cdist = colormap[2][cindex] - (bcenter * x + x/2); cdist = rdist*rdist + gdist*gdist + cdist*cdist; crinc = 2 * ((rcenter + 1) * xsqr - (colormap[0][cindex] * x)); cginc = 2 * ((gcenter + 1) * xsqr - (colormap[1][cindex] * x)); cbinc = 2 * ((bcenter + 1) * xsqr - (colormap[2][cindex] * x)); /* Array starting points. */ cdp = dist_buf + rcenter * rstride + gcenter * gstride + bcenter; crgbp = rgbmap + rcenter * rstride + gcenter * gstride + bcenter; (void)redloop(); } } /* redloop -- loop up and down from red center. */ static int redloop() { int detect; int r; int first; long txsqr = xsqr + xsqr; static long rxx; detect = 0; /* Basic loop up. */ for ( r = rcenter, rdist = cdist, rxx = crinc, rdp = cdp, rrgbp = crgbp, first = 1; r < colormax; r++, rdp += rstride, rrgbp += rstride, rdist += rxx, rxx += txsqr, first = 0 ) { if ( greenloop( first ) ) detect = 1; else if ( detect ) break; } /* Basic loop down. */ for ( r = rcenter - 1, rxx = crinc - txsqr, rdist = cdist - rxx, rdp = cdp - rstride, rrgbp = crgbp - rstride, first = 1; r >= 0; r--, rdp -= rstride, rrgbp -= rstride, rxx -= txsqr, rdist -= rxx, first = 0 ) { if ( greenloop( first ) ) detect = 1; else if ( detect ) break; } return detect; } /* greenloop -- loop up and down from green center. */ static int greenloop( restart ) int restart; { int detect; int g; int first; long txsqr = xsqr + xsqr; static int here, min, max; static long ginc, gxx, gcdist; /* "gc" variables maintain correct */ static unsigned long *gcdp; /* values for bcenter position, */ static unsigned char *gcrgbp; /* despite modifications by blueloop */ /* to gdist, gdp, grgbp. */ if ( restart ) { here = gcenter; min = 0; max = colormax - 1; ginc = cginc; } detect = 0; /* Basic loop up. */ for ( g = here, gcdist = gdist = rdist, gxx = ginc, gcdp = gdp = rdp, gcrgbp = grgbp = rrgbp, first = 1; g <= max; g++, gdp += gstride, gcdp += gstride, grgbp += gstride, gcrgbp += gstride, gdist += gxx, gcdist += gxx, gxx += txsqr, first = 0 ) { if ( blueloop( first ) ) { if ( !detect ) { /* Remember here and associated data! */ if ( g > here ) { here = g; rdp = gcdp; rrgbp = gcrgbp; rdist = gcdist; ginc = gxx; } detect = 1; } } else if ( detect ) { break; } } /* Basic loop down. */ for ( g = here - 1, gxx = ginc - txsqr, gcdist = gdist = rdist - gxx, gcdp = gdp = rdp - gstride, gcrgbp = grgbp = rrgbp - gstride, first = 1; g >= min; g--, gdp -= gstride, gcdp -= gstride, grgbp -= gstride, gcrgbp -= gstride, gxx -= txsqr, gdist -= gxx, gcdist -= gxx, first = 0 ) { if ( blueloop( first ) ) { if ( !detect ) { /* Remember here! */ here = g; rdp = gcdp; rrgbp = gcrgbp; rdist = gcdist; ginc = gxx; detect = 1; } } else if ( detect ) { break; } } return detect; } /* blueloop -- loop up and down from blue center. */ static int blueloop( restart ) int restart; { int detect; register unsigned long *dp; register unsigned char *rgbp; register long bdist, bxx; register int b, i = cindex; register long txsqr = xsqr + xsqr; register int lim; static int here, min, max; static long binc; if ( restart ) { here = bcenter; min = 0; max = colormax - 1; binc = cbinc; } detect = 0; /* Basic loop up. */ /* First loop just finds first applicable cell. */ for ( b = here, bdist = gdist, bxx = binc, dp = gdp, rgbp = grgbp, lim = max; b <= lim; b++, dp++, rgbp++, bdist += bxx, bxx += txsqr ) { if ( *dp > bdist ) { /* Remember new 'here' and associated data! */ if ( b > here ) { here = b; gdp = dp; grgbp = rgbp; gdist = bdist; binc = bxx; } detect = 1; break; } } /* Second loop fills in a run of closer cells. */ for ( ; b <= lim; b++, dp++, rgbp++, bdist += bxx, bxx += txsqr ) { if ( *dp > bdist ) { *dp = bdist; *rgbp = i; } else { break; } } /* Basic loop down. */ /* Do initializations here, since the 'find' loop might not get * executed. */ lim = min; b = here - 1; bxx = binc - txsqr; bdist = gdist - bxx; dp = gdp - 1; rgbp = grgbp - 1; /* The 'find' loop is executed only if we didn't already find * something. */ if ( !detect ) for ( ; b >= lim; b--, dp--, rgbp--, bxx -= txsqr, bdist -= bxx ) { if ( *dp > bdist ) { /* Remember here! */ /* No test for b against here necessary because b < * here by definition. */ here = b; gdp = dp; grgbp = rgbp; gdist = bdist; binc = bxx; detect = 1; break; } } /* The 'update' loop. */ for ( ; b >= lim; b--, dp--, rgbp--, bxx -= txsqr, bdist -= bxx ) { if ( *dp > bdist ) { *dp = bdist; *rgbp = i; } else { break; } } /* If we saw something, update the edge trackers. */ return detect; } static void maxfill( buffer, side ) unsigned long *buffer; long side; { register unsigned long maxv = ~0L; register long i; register unsigned long *bp; for ( i = side * side * side, bp = buffer; i > 0; i--, bp++ ) *bp = maxv; }
2.375
2
2024-11-18T21:15:36.029035+00:00
2016-09-26T16:39:09
13eb2a8755ef878a0ae548fd01b0ba50b8d9a915
{ "blob_id": "13eb2a8755ef878a0ae548fd01b0ba50b8d9a915", "branch_name": "refs/heads/master", "committer_date": "2016-09-26T16:39:09", "content_id": "116433940fd04cd4be8b576478bfb3c8486f5fa6", "detected_licenses": [ "MIT" ], "directory_id": "d6f6a4084458ef4cb0ab9be24eb29a6fdd3d14c6", "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": 297, "license": "MIT", "license_type": "permissive", "path": "/main.c", "provenance": "stackv2-0112.json.gz:2146", "repo_name": "Prasoon1207/dynamic-hash-table", "revision_date": "2016-09-26T16:39:09", "revision_id": "de058793e330ca87c5846f7b3052febe5625616c", "snapshot_id": "27217ef1e508f13515618de08ba011d21897fce1", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Prasoon1207/dynamic-hash-table/de058793e330ca87c5846f7b3052febe5625616c/main.c", "visit_date": "2023-03-16T15:47:41.846041" }
stackv2
#include <stdio.h> #include "./hash-table.h" int main(int argc, char **argv) { if (argc != 2) { printf("Usage: ./hash_table <size of table>\n"); return -1; } int size = (int) strtol(argv[1], (char**) NULL, 10); hash_table *table = hash_init(size); hash_destroy(table); return 0; }
2.390625
2
2024-11-18T21:15:36.112150+00:00
2015-12-21T06:56:54
8386fdc86f4c71d607b58be0be88cd5e479fd1ee
{ "blob_id": "8386fdc86f4c71d607b58be0be88cd5e479fd1ee", "branch_name": "refs/heads/master", "committer_date": "2015-12-21T06:56:54", "content_id": "307675ca0a62659688fbc30906189bede5d7b21f", "detected_licenses": [ "Apache-2.0" ], "directory_id": "fe3939e260d0fa25dde549cf40c4da8c6cc9520b", "extension": "c", "filename": "auth.c", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 48212258, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 6230, "license": "Apache-2.0", "license_type": "permissive", "path": "/osdrv/ezcfg/ezcfg-0.1/libezcfg/src/basic/auth/auth.c", "provenance": "stackv2-0112.json.gz:2275", "repo_name": "zetalabs/hi3520d", "revision_date": "2015-12-21T06:56:54", "revision_id": "27374d155c4bcc1904d377dd3328f4d47b2cbc3d", "snapshot_id": "20969a2a3fa55aa4dd6b8caeb86610a4ad1e0576", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/zetalabs/hi3520d/27374d155c4bcc1904d377dd3328f4d47b2cbc3d/osdrv/ezcfg/ezcfg-0.1/libezcfg/src/basic/auth/auth.c", "visit_date": "2021-01-19T00:20:43.488086" }
stackv2
/* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */ /** * ============================================================================ * Project Name : ezbox configuration utilities * File Name : basic/auth/auth.c * * Description : implement authentications * * Copyright (C) 2008-2014 by ezbox-project * * History Rev Description * 2011-04-08 0.1 Write it from scratch * ============================================================================ */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <stddef.h> #include <stdarg.h> #include <errno.h> #include <ctype.h> #include <limits.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/time.h> #include <pthread.h> #include "ezcfg.h" #include "ezcfg-private.h" struct ezcfg_auth { struct ezcfg *ezcfg; char *type; /* type */ char *user; /* user */ char *realm; /* realm */ char *domain; /* domain */ char *secret; /* secret */ struct ezcfg_auth *next; /* link pointer */ }; /* * Private functions */ static bool auth_http_basic_is_valid(struct ezcfg_auth *auth) { if ((auth->user == NULL) || (auth->realm == NULL) || (auth->domain == NULL) || (auth->secret == NULL)) { return false; } return true; } static bool auth_http_digest_is_valid(struct ezcfg_auth *auth) { if ((auth->user == NULL) || (auth->realm == NULL) || (auth->domain == NULL) || (auth->secret == NULL)) { return false; } return true; } static bool auth_is_same(struct ezcfg_auth *a1, struct ezcfg_auth *a2) { if ((strcmp(a1->type, a2->type) == 0) && (strcmp(a1->user, a2->user) == 0) && (strcmp(a1->realm, a2->realm) == 0) && (strcmp(a1->domain, a2->domain) == 0) && (strcmp(a1->secret, a2->secret) == 0)) { return true; } return false; } /* * Public functions */ int ezcfg_auth_delete(struct ezcfg_auth *auth) { struct ezcfg *ezcfg; ASSERT(auth != NULL); ezcfg = auth->ezcfg; if (auth->type != NULL) { free(auth->type); } if (auth->user != NULL) { free(auth->user); } if (auth->realm != NULL) { free(auth->realm); } if (auth->domain != NULL) { free(auth->domain); } if (auth->secret != NULL) { free(auth->secret); } free(auth); /* decrease ezcfg library context reference */ if (ezcfg_dec_ref(ezcfg) != EZCFG_RET_OK) { EZDBG("ezcfg_dec_ref() failed\n"); } return EZCFG_RET_OK; } struct ezcfg_auth *ezcfg_auth_new(struct ezcfg *ezcfg) { struct ezcfg_auth *auth; ASSERT(ezcfg != NULL); /* increase ezcfg library context reference */ if (ezcfg_inc_ref(ezcfg) != EZCFG_RET_OK) { EZDBG("ezcfg_inc_ref() failed\n"); return NULL; } auth = (struct ezcfg_auth *)calloc(1, sizeof(struct ezcfg_auth)); if (auth == NULL) { err(ezcfg, "can not calloc auth\n"); /* decrease ezcfg library context reference */ if (ezcfg_dec_ref(ezcfg) != EZCFG_RET_OK) { EZDBG("ezcfg_dec_ref() failed\n"); } return NULL; } auth->ezcfg = ezcfg; return auth; } bool ezcfg_auth_set_type(struct ezcfg_auth *auth, char *type) { //struct ezcfg *ezcfg; char *p; ASSERT(auth != NULL); ASSERT(type != NULL); //ezcfg = auth->ezcfg; p = strdup(type); if (p == NULL) { return false; } if (auth->type != NULL) { free(auth->type); } auth->type = p; return true; } bool ezcfg_auth_set_user(struct ezcfg_auth *auth, char *user) { //struct ezcfg *ezcfg; char *p; ASSERT(auth != NULL); ASSERT(user != NULL); //ezcfg = auth->ezcfg; p = strdup(user); if (p == NULL) { return false; } if (auth->user != NULL) { free(auth->user); } auth->user = p; return true; } bool ezcfg_auth_set_realm(struct ezcfg_auth *auth, char *realm) { //struct ezcfg *ezcfg; char *p; ASSERT(auth != NULL); ASSERT(realm != NULL); //ezcfg = auth->ezcfg; p = strdup(realm); if (p == NULL) { return false; } if (auth->realm != NULL) { free(auth->realm); } auth->realm = p; return true; } bool ezcfg_auth_set_domain(struct ezcfg_auth *auth, char *domain) { //struct ezcfg *ezcfg; char *p; ASSERT(auth != NULL); ASSERT(domain != NULL); //ezcfg = auth->ezcfg; p = strdup(domain); if (p == NULL) { return false; } if (auth->domain != NULL) { free(auth->domain); } auth->domain = p; return true; } bool ezcfg_auth_set_secret(struct ezcfg_auth *auth, char *secret) { //struct ezcfg *ezcfg; char *p; ASSERT(auth != NULL); ASSERT(secret != NULL); //ezcfg = auth->ezcfg; p = strdup(secret); if (p == NULL) { return false; } if (auth->secret != NULL) { free(auth->secret); } auth->secret = p; return true; } bool ezcfg_auth_is_valid(struct ezcfg_auth *auth) { //struct ezcfg *ezcfg; ASSERT(auth != NULL); //ezcfg = auth->ezcfg; if (auth->type == NULL) { return false; } if (strcmp(auth->type, EZCFG_AUTH_TYPE_HTTP_BASIC_STRING) == 0) { return auth_http_basic_is_valid(auth); } else if (strcmp(auth->type, EZCFG_AUTH_TYPE_HTTP_DIGEST_STRING) == 0) { return auth_http_digest_is_valid(auth); } else { return false; } } bool ezcfg_auth_list_in(struct ezcfg_auth **list, struct ezcfg_auth *auth) { //struct ezcfg *ezcfg; struct ezcfg_auth *ap; ASSERT(list != NULL); ASSERT(auth != NULL); //ezcfg = auth->ezcfg; ap = *list; while (ap != NULL) { if (auth_is_same(ap, auth) == true) { return true; } ap = ap->next; } return false; } bool ezcfg_auth_list_insert(struct ezcfg_auth **list, struct ezcfg_auth *auth) { ASSERT(list != NULL); ASSERT(auth != NULL); auth->next = *list; *list = auth; return true; } void ezcfg_auth_list_delete(struct ezcfg_auth **list) { struct ezcfg_auth *ap; ASSERT(list != NULL); ap = *list; while (ap != NULL) { *list = ap->next; ezcfg_auth_delete(ap); ap = *list; } } bool ezcfg_auth_check_authorized(struct ezcfg_auth **list, struct ezcfg_auth *auth) { ASSERT(list != NULL); ASSERT(auth != NULL); if (auth->type == NULL) { /* unknown authentication type */ return false; } return ezcfg_auth_list_in(list, auth); }
2.375
2
2024-11-18T21:15:36.348428+00:00
2017-03-02T01:56:41
5cae69c7bdb8bc7c13edad8cd8cdf0b7a24c61a1
{ "blob_id": "5cae69c7bdb8bc7c13edad8cd8cdf0b7a24c61a1", "branch_name": "refs/heads/master", "committer_date": "2017-03-02T01:56:41", "content_id": "19e688f993f40ebcef06c8d3311a236cd18846c7", "detected_licenses": [ "MIT" ], "directory_id": "478c84d06d0686c63f996d3733dd43987ff774d3", "extension": "c", "filename": "test11.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": 946, "license": "MIT", "license_type": "permissive", "path": "/test11.c", "provenance": "stackv2-0112.json.gz:2534", "repo_name": "saprido/my_malloc", "revision_date": "2017-03-02T01:56:41", "revision_id": "001a0fb8d58c21adc315d03451da2ec4e8535a19", "snapshot_id": "1b3c528bb2ecdfca61b4272398cd38c39f2b3330", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/saprido/my_malloc/001a0fb8d58c21adc315d03451da2ec4e8535a19/test11.c", "visit_date": "2020-12-10T04:29:45.827693" }
stackv2
#include <stdlib.h> #include <stdio.h> #include <string.h> #include "mymalloc.h" struct something_ { int id; float value; struct something_* next; }; typedef struct something_ something; something* intialize (int i, float v) { something* temp = (something*)malloc(sizeof(temp)); temp->id = i; temp->value = v; temp->next = NULL; return temp; } int main(int argc, char** argv) { something* head = intialize(1, 1.23); // int count = 0; //something* ptr = head; something* ptr1 = intialize(2, 1.34); something* ptr2 = intialize(3, 4.34); something* ptr3 = intialize(4, 4.234); head->next = ptr1; ptr1->next = ptr2; ptr2->next = ptr3; /*for(count = 0; count<10; count++) { while(ptr!=NULL) { ptr = ptr->next; } something* temp = intialize(count, 2.34); ptr->next = temp; } */ //head = ptr; free(head); free(ptr1); free(ptr2); free(ptr3); return 0; }
3.28125
3
2024-11-18T21:15:36.520067+00:00
2019-12-02T18:33:28
32a5c88c2010231117157e8a4649cf887a93a822
{ "blob_id": "32a5c88c2010231117157e8a4649cf887a93a822", "branch_name": "refs/heads/master", "committer_date": "2019-12-02T18:33:28", "content_id": "374e4acf812faa805e36caa978702600836bead9", "detected_licenses": [ "MIT" ], "directory_id": "c6bf1786d6dd54c8ec2c1d03343eaed2f9e7b1f3", "extension": "c", "filename": "lp.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": 1329, "license": "MIT", "license_type": "permissive", "path": "/lp.c", "provenance": "stackv2-0112.json.gz:2790", "repo_name": "prajneya/xv6-public", "revision_date": "2019-12-02T18:33:28", "revision_id": "ef0a95075a0e1fa900336e96a04e4a8d2895ea2a", "snapshot_id": "4c08b8bde78b8592372651b0f0adc46b4326f744", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/prajneya/xv6-public/ef0a95075a0e1fa900336e96a04e4a8d2895ea2a/lp.c", "visit_date": "2022-03-23T00:55:37.008482" }
stackv2
#include "types.h" #include "user.h" #include "fcntl.h" #include "fs.h" #include "stat.h" struct proc_stat { int pid; // PID of each process int total_time; // Use suitable unit of time int runtime; // Use suitable unit of time int num_run; // number of time the process is executed int current_queue; // current assigned queue int ticks[5]; // number of ticks each process has received at each of the 5 priority queue }; int main(int argc, char *argv[]) { int j = 0; j = 0; int priorty = 60; if(argc<2){ printf(1,"provide the name for the lp"); exit(); } if(argc>=3){ priorty=atoi(argv[2]); printf(1, "priorty of %s changed from %d to %d\n", argv[1], set_priority(priorty), priorty); } printf(1, "process %s started\n", argv[1]); for (volatile int i = 0; i <= 1000000000; i++) { j++; i=j; } printf(1, "process %s ended\n", argv[1]); struct proc_stat p; getpinfo(&p); printf(1, "PINFO:\n"); printf(1, "pid:%d\n", p.pid); printf(1, "runtime:%d\n", p.runtime); printf(1, "total_time:%d\n", p.total_time); printf(1, "num_run:%d\n", p.num_run); printf(1, "current queue:%d\n", p.current_queue); for(int i=0; i<5; i++) printf(1, "ticks in queue %d = %d\n", i,p.ticks[i]); exit(); }
2.84375
3
2024-11-18T21:15:36.743059+00:00
2020-07-18T21:41:10
15343d6a24f78f57aa2bbf2cdc7e54cecada7ee2
{ "blob_id": "15343d6a24f78f57aa2bbf2cdc7e54cecada7ee2", "branch_name": "refs/heads/master", "committer_date": "2020-07-18T21:41:10", "content_id": "3856b369b21b9112add5d5573ac60265dfdd2bcb", "detected_licenses": [ "MIT" ], "directory_id": "83f97532f115774292e471a36c0710a3ff608bdb", "extension": "c", "filename": "1171 - Frequencia de numeros.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 176393559, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1007, "license": "MIT", "license_type": "permissive", "path": "/em C/Exercícios Resolvidos/Exercícios URI Resolvidos/Lista Uri 2 - Arrays e Strings/1171 - Frequencia de numeros.c", "provenance": "stackv2-0112.json.gz:3047", "repo_name": "GuilhermeEsdras/Estrutura-de-Dados", "revision_date": "2020-07-18T21:41:10", "revision_id": "e1f73d73f4bfbe829a727f672952938f60e2ea01", "snapshot_id": "a7ffaa2e5b0159461afac720afeeb6fb5f260d47", "src_encoding": "ISO-8859-1", "star_events_count": 0, "url": "https://raw.githubusercontent.com/GuilhermeEsdras/Estrutura-de-Dados/e1f73d73f4bfbe829a727f672952938f60e2ea01/em C/Exercícios Resolvidos/Exercícios URI Resolvidos/Lista Uri 2 - Arrays e Strings/1171 - Frequencia de numeros.c", "visit_date": "2021-07-14T10:41:38.554610" }
stackv2
#include <stdio.h> #define TAM 2001 int main(){ int N; scanf("%d", &N); int lista[TAM] = {0}, i, pos; for(; N > 0 ; N--) { /* Este for pede ao usuário que digite os valores que serão printados posteriormente, * e ao invés de adicionar estes elementos à uma lista, ele simplesmente incrementa +1 à posição daquele valor na lista. */ scanf("%d", &pos); lista[pos]++; } for( i = 0; i < TAM; i++ ) { /* Com este for é buscado se tem algum incremento na determinada posição na lista principal. * Ou seja, se o usuário digitou algum elemento naquela posição. * Se sim, o valor da posição será maior que 0, pois terá sido incrementado antes. * Então, o valor (posição) é printado, juntamente com a quantidade de incrementos (vezes digitado) */ if( lista[i] > 0) { printf("%d aparece %d vez(es)\n", i, lista[i]); } } return 0; }
3.546875
4
2024-11-18T21:15:38.849943+00:00
2019-10-21T13:38:27
287bfe6de95c129916f7d7f6823c7e4e84f219cc
{ "blob_id": "287bfe6de95c129916f7d7f6823c7e4e84f219cc", "branch_name": "refs/heads/master", "committer_date": "2019-10-21T13:38:27", "content_id": "849b11633b08b0852e33652faa83c6a291816bce", "detected_licenses": [ "MIT" ], "directory_id": "4e5b40e37b69517262cd3038f16f5f5f12d61cdf", "extension": "c", "filename": "ft_list_add.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 216575810, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1539, "license": "MIT", "license_type": "permissive", "path": "/sources/ft_list_add.c", "provenance": "stackv2-0112.json.gz:3819", "repo_name": "rmicolon/ft_list", "revision_date": "2019-10-21T13:38:27", "revision_id": "faef05ea351f8a0ea18f83d07be3b7fcdf31183a", "snapshot_id": "03ab7347018d8a36a4165d4d740508ee3826f63a", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/rmicolon/ft_list/faef05ea351f8a0ea18f83d07be3b7fcdf31183a/sources/ft_list_add.c", "visit_date": "2020-08-23T08:00:59.687697" }
stackv2
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_list_add.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: rmicolon <rmicolon@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/08/09 17:10:26 by rmicolon #+# #+# */ /* Updated: 2018/10/15 20:03:25 by rmicolon ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_list.h" /* ** ft__list_add - Insert a new entry between two known consecutive entries */ static inline void ft__list_add(t_list_head *new, t_list_head *prev, t_list_head *next) { prev->next = new; new->prev = prev; new->next = next; next->prev = new; } /* ** ft_list_add - Insert a new entry after the specified head */ inline void ft_list_add(t_list_head *new, t_list_head *head) { ft__list_add(new, head, head->next); } /* ** ft_list_add_tail - Insert a new entry before the specified head */ inline void ft_list_add_tail(t_list_head *new, t_list_head *head) { ft__list_add(new, head->prev, head); }
2.8125
3
2024-11-18T21:15:38.941024+00:00
2016-01-01T01:20:00
c7091fd41d74f66e98c9bc7022fcb5ede7207a86
{ "blob_id": "c7091fd41d74f66e98c9bc7022fcb5ede7207a86", "branch_name": "refs/heads/release", "committer_date": "2016-01-20T22:59:33", "content_id": "1e52eaf83cb2d3e949bdb613602fa9a6fad88be5", "detected_licenses": [], "directory_id": "842ede7c817bc33e9cc63e3a53b2269365a6d7fa", "extension": "h", "filename": "epd.h", "fork_events_count": 65, "gha_created_at": "2016-01-20T23:25:05", "gha_event_created_at": "2023-06-16T22:51:42", "gha_language": "C", "gha_license_id": "BSD-3-Clause", "github_id": 50067768, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4712, "license": "", "license_type": "permissive", "path": "/epd/epd.h", "provenance": "stackv2-0112.json.gz:3948", "repo_name": "ivmai/cudd", "revision_date": "2016-01-01T01:20:00", "revision_id": "f54f533303640afd5dbe47a05ebeabb3066f2a25", "snapshot_id": "863f4a48de1986a97d23ebcb2ee2a1e050055e51", "src_encoding": "UTF-8", "star_events_count": 97, "url": "https://raw.githubusercontent.com/ivmai/cudd/f54f533303640afd5dbe47a05ebeabb3066f2a25/epd/epd.h", "visit_date": "2023-06-24T01:40:46.808630" }
stackv2
/** @file @ingroup epd @brief The University of Colorado extended double precision package. @details Arithmetic functions with extended double precision. The floating point numbers manipulated by this package use an int to hold the exponent. The significand has the same precision as a standard double. @author In-Ho Moon @copyright@parblock Copyright (c) 1995-2015, Regents of the University of Colorado 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. Neither the name of the University of Colorado nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. @endparblock */ #ifndef EPD_H_ #define EPD_H_ #ifdef __cplusplus extern "C" { #endif /*---------------------------------------------------------------------------*/ /* Type declarations */ /*---------------------------------------------------------------------------*/ /** @brief The type of extended precision floating-point numbers. */ typedef struct EpDoubleStruct EpDouble; /*---------------------------------------------------------------------------*/ /* Function prototypes */ /*---------------------------------------------------------------------------*/ extern EpDouble *EpdAlloc(void); extern int EpdCmp(const void *key1, const void *key2); extern void EpdFree(EpDouble *epd); extern void EpdGetString(EpDouble const *epd, char *str); extern void EpdConvert(double value, EpDouble *epd); extern void EpdMultiply(EpDouble *epd1, double value); extern void EpdMultiply2(EpDouble *epd1, EpDouble const *epd2); extern void EpdMultiply2Decimal(EpDouble *epd1, EpDouble const *epd2); extern void EpdMultiply3(EpDouble const *epd1, EpDouble const *epd2, EpDouble *epd3); extern void EpdMultiply3Decimal(EpDouble const *epd1, EpDouble const *epd2, EpDouble *epd3); extern void EpdDivide(EpDouble *epd1, double value); extern void EpdDivide2(EpDouble *epd1, EpDouble const *epd2); extern void EpdDivide3(EpDouble const *epd1, EpDouble const *epd2, EpDouble *epd3); extern void EpdAdd(EpDouble *epd1, double value); extern void EpdAdd2(EpDouble *epd1, EpDouble const *epd2); extern void EpdAdd3(EpDouble const *epd1, EpDouble const *epd2, EpDouble *epd3); extern void EpdSubtract(EpDouble *epd1, double value); extern void EpdSubtract2(EpDouble *epd1, EpDouble const *epd2); extern void EpdSubtract3(EpDouble const *epd1, EpDouble const *epd2, EpDouble *epd3); extern void EpdPow2(int n, EpDouble *epd); extern void EpdPow2Decimal(int n, EpDouble *epd); extern void EpdNormalize(EpDouble *epd); extern void EpdNormalizeDecimal(EpDouble *epd); extern void EpdGetValueAndDecimalExponent(EpDouble const *epd, double *value, int *exponent); extern int EpdGetExponent(double value); extern int EpdGetExponentDecimal(double value); extern void EpdMakeInf(EpDouble *epd, int sign); extern void EpdMakeZero(EpDouble *epd, int sign); extern void EpdMakeNan(EpDouble *epd); extern void EpdCopy(EpDouble const *from, EpDouble *to); extern int EpdIsInf(EpDouble const *epd); extern int EpdIsZero(EpDouble const *epd); extern int EpdIsNan(EpDouble const *epd); extern int EpdIsNanOrInf(EpDouble const *epd); extern int IsInfDouble(double value); extern int IsNanDouble(double value); extern int IsNanOrInfDouble(double value); #ifdef __cplusplus } #endif #endif /* EPD_H_ */
2.09375
2
2024-11-18T21:15:39.239924+00:00
2019-04-11T12:43:41
4bc02d68b7bb59d0b3c3d30330c29a9b73751993
{ "blob_id": "4bc02d68b7bb59d0b3c3d30330c29a9b73751993", "branch_name": "refs/heads/master", "committer_date": "2019-04-11T12:43:41", "content_id": "d60713c4640288e6f5541cb45c8c3d919c594dae", "detected_licenses": [ "MIT" ], "directory_id": "d3aaa326aa784a7d06db9b1e26ae30162949ecbc", "extension": "c", "filename": "main.c", "fork_events_count": 0, "gha_created_at": "2019-04-14T01:47:31", "gha_event_created_at": "2019-04-14T01:47:31", "gha_language": null, "gha_license_id": "MIT", "github_id": 181247860, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 579, "license": "MIT", "license_type": "permissive", "path": "/示范例程/OLED_jy91_freecars/USER/main.c", "provenance": "stackv2-0112.json.gz:4210", "repo_name": "chenxiangang/stm32f4_modules", "revision_date": "2019-04-11T12:43:41", "revision_id": "74cc9c773cfb6ee7b889c72ae281ef9ee1a84c33", "snapshot_id": "b9a88acb816f5fa07524503e422ad7222e54f906", "src_encoding": "GB18030", "star_events_count": 1, "url": "https://raw.githubusercontent.com/chenxiangang/stm32f4_modules/74cc9c773cfb6ee7b889c72ae281ef9ee1a84c33/示范例程/OLED_jy91_freecars/USER/main.c", "visit_date": "2020-05-09T15:57:45.385719" }
stackv2
#include "sys.h" #include "delay.h" #include "usart.h" #include "led.h" #include "oled.h" #include "JY901_uart.h" #include "include.h" #include "FreeCars_uart.h" FLAG_Typedef flag; int a = 1; int main(void) { NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);//设置系统中断优先级分组2 delay_init(168); //初始化延时函数 uart_init(115200); //初始化串口波特率为115200 usart3_init(115200); OLED_Init(); LED_Init(); //初始化LED while(1) { push(0,a); uSendOnePage(); printf("hello world"); delay_ms(100); LED0=!LED0; } }
2.078125
2
2024-11-18T21:15:39.384371+00:00
2017-05-25T01:25:50
9a98b12639a6f688ba793ba5e16eba8dfa3ce601
{ "blob_id": "9a98b12639a6f688ba793ba5e16eba8dfa3ce601", "branch_name": "refs/heads/master", "committer_date": "2017-05-25T01:25:50", "content_id": "0a24ea77404c06de6d324890fe0743b6cee6ed79", "detected_licenses": [ "MIT" ], "directory_id": "158059c348e49112a06cdfb929a136c62aabc306", "extension": "h", "filename": "ListLib.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 92345623, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1754, "license": "MIT", "license_type": "permissive", "path": "/Include/List/ListLib.h", "provenance": "stackv2-0112.json.gz:4466", "repo_name": "vikvych/hierarchy_base", "revision_date": "2017-05-25T01:25:50", "revision_id": "fa2cfed8ca1ffe82b5665d4a615bd205849ae609", "snapshot_id": "f5be4066f7460593c719eb4e95991d65fbaf6907", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/vikvych/hierarchy_base/fa2cfed8ca1ffe82b5665d4a615bd205849ae609/Include/List/ListLib.h", "visit_date": "2021-01-22T02:17:50.921473" }
stackv2
#ifndef HIERARCHY_LIST_LIB_H #define HIERARCHY_LIST_LIB_H #include "ListT.h" #include "ListAlloc.h" #include "ListAppend.h" #include "ListClear.h" #include "ListDebug.h" #include "ListEach.h" #include "ListFirst.h" #include "ListFlush.h" #include "ListInsert.h" #include "ListUpsert.h" #include "ListIsEmpty.h" #include "ListIsExists.h" #include "ListLast.h" #include "ListPrepend.h" #include "ListRemove.h" #include "ListSize.h" #include "ListSort.h" #include "ListValue.h" extern const struct ListLibrary { void (*Init)(ListT *List); ListNodeT *(*NodeAlloc)(); ListT *(*Alloc)(); void (*Flush)(ListT *List); void (*Clear)(ListT *List); void (*Append)(ListT *List, ListNodeT *ListNode, void *Data); void (*Prepend)(ListT *List, ListNodeT *ListNode, void *Data); void (*Upsert)(ListT *List, ListNodeT *SearchNode, ListNodeT *InsertNode, void *Data); void (*Insert)(ListT *List, ListNodeT *SearchNode, ListNodeT *InsertNode, void *Data); void (*Sort)(ListT *List, ListSortCallbackT *SortCallback, void *Argument); ListNodeT *(*Each)(const ListT *List, bool ForwardDirection, ListEachCb *ApplyCallback, void *Argument); ListNodeT *(*First)(const ListT *List); ListNodeT *(*Last)(const ListT *List); SizeT (*Size)(const ListT *List); bool (*IsEmpty)(const ListT *List); void *(*Value)(const ListNodeT *ListNode); bool (*IsExists)(const ListT *List, const ListNodeT *ListNode); void (*Remove)(ListNodeT *ListNode); } ListLib; #endif
2.078125
2
2024-11-18T21:15:39.687055+00:00
2021-06-28T16:53:07
8d54cb8fc6a2f74973744fe5c949d964b5340d42
{ "blob_id": "8d54cb8fc6a2f74973744fe5c949d964b5340d42", "branch_name": "refs/heads/main", "committer_date": "2021-06-28T16:53:07", "content_id": "547e3ccc300faf2fbf1c371a38db635c0797e6ba", "detected_licenses": [ "MIT" ], "directory_id": "427f48b76d1b312cff7af2d9b535ea333e8d154e", "extension": "c", "filename": "numeric_complex_carg.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 381098552, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 792, "license": "MIT", "license_type": "permissive", "path": "/c/numeric_complex_carg.c", "provenance": "stackv2-0112.json.gz:4724", "repo_name": "rpuntaie/c-examples", "revision_date": "2021-06-28T16:53:07", "revision_id": "385b3c792e5b39f81a187870100ed6401520a404", "snapshot_id": "8925146dd1a59edb137c6240363e2794eccce004", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/rpuntaie/c-examples/385b3c792e5b39f81a187870100ed6401520a404/c/numeric_complex_carg.c", "visit_date": "2023-05-31T15:29:38.919736" }
stackv2
/* gcc -std=c17 -lc -lm -pthread -o ../_build/c/numeric_complex_carg.exe ./c/numeric_complex_carg.c && (cd ../_build/c/;./numeric_complex_carg.exe) https://en.cppreference.com/w/c/numeric/complex/carg */ #include <stdio.h> #include <complex.h> int main(void) { double complex z1 = 1.0+0.0*I; printf("phase angle of %.1f%+.1fi is %f\n", creal(z1), cimag(z1), carg(z1)); double complex z2 = 0.0+1.0*I; printf("phase angle of %.1f%+.1fi is %f\n", creal(z2), cimag(z2), carg(z2)); double complex z3 = -1.0+0.0*I; printf("phase angle of %.1f%+.1fi is %f\n", creal(z3), cimag(z3), carg(z3)); double complex z4 = conj(z3); // or CMPLX(-1, -0.0) printf("phase angle of %.1f%+.1fi (the other side of the cut) is %f\n", creal(z4), cimag(z4), carg(z4)); }
2.796875
3
2024-11-18T21:15:39.873624+00:00
2018-12-05T15:08:12
94a11659102003b408e3db7e0793305f404a7232
{ "blob_id": "94a11659102003b408e3db7e0793305f404a7232", "branch_name": "refs/heads/master", "committer_date": "2018-12-05T15:08:12", "content_id": "8bbad28045084f74d59f34e5e83e6ad4d6d8733c", "detected_licenses": [ "MIT" ], "directory_id": "d9f45aeb4382b328c22685ad0efab490e821d70a", "extension": "c", "filename": "pseudocode.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 152608005, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3898, "license": "MIT", "license_type": "permissive", "path": "/src/pseudocode.c", "provenance": "stackv2-0112.json.gz:4980", "repo_name": "Cronuswaters/mypas", "revision_date": "2018-12-05T15:08:12", "revision_id": "265d660dd3ac4545bf4a161d4548159d03bdc16a", "snapshot_id": "1d2301efcfe8ce781bca2b40f7cf053c8af86a2c", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Cronuswaters/mypas/265d660dd3ac4545bf4a161d4548159d03bdc16a/src/pseudocode.c", "visit_date": "2020-03-31T22:09:45.340269" }
stackv2
/**@<pseudocode.c>::**/ #include <stdio.h> #include <stdlib.h> #include <keywords.h> #include <pseudocode.h> FILE *source, *object; /* Create var label */ void mklabel(char *label){ fprintf(object, ".L %s\n",label); } /* Control pseudoinstructions */ void gofalse(size_t label){ fprintf(object, "\tjz .L %ld\n",label); } void jmp(size_t label){ fprintf(object, "\tjmp .L %ld\n",label); } void mklooplabel(size_t label){ fprintf(object, ".L %ld\n",label); } /* Move pseudoinstructions */ void push(char *suffix){ fprintf(object, "\tpush %%acc%s\n",suffix); } void pop(char *suffix){ fprintf(object, "\tpop %%acc%s\n",suffix); } void ld(char *var, char *suffix){ // Load (var -> acc) fprintf(object, "\tmov %s, %%acc%s\n",var,suffix); } void st(char *var, char *suffix){ // Store (acc -> var) fprintf(object, "\tmov %%acc%s, %s\n",suffix,var); } /* LAU pseudoinstructions */ // Add void addi(void){ // Add (integer) fprintf(object, "\taddi %%accl, %%(spl)\n"); } void fadd(void){ // Add (float) fprintf(object, "\tfadd %%accf, %%(spf)\n"); } void dfadd(void){ // Add (double) fprintf(object, "\tdfaff %%accdf, %%(spdf)\n"); } void subi(void){ // Subtract (integer) fprintf(object, "\tsubi %%accl, %%(spl)"); } void fsub(void){ // Subtract (float) fprintf(object, "\tfsub %%accf, %%(spf)\n"); } void dfsub(void){ // Subtract (double) fprintf(object, "\tdfsub %%accdf, %%(spdf)\n"); } void orb(){ // Bytewise OR (logical) fprintf(object, "\torb %%accb, %%(spb)\n"); } /* Macro-instruction add */ int add(int op, int size){ if(op == '+'){ switch(size){ case 1: addi(); break; case 2: fadd(); break; case 3: dfadd(); break; default: return -1; } } else if(op == '-'){ switch(size){ case 1: subi(); break; case 2: fsub(); break; case 3: dfsub(); break; default: return -1; } } else if(op == OR){ if(size == 4) orb(); else return -1; } else return -1; return 0; } // Mul void lmul(void){ // Multiply (integer) fprintf(object, "\tlmul %%accl, %%(spl)\n"); } void fmul(void){ // Multiply (float) fprintf(object, "\tfmul %%accf, %%(spf)\n"); } void dfmul(void){ // Multiply (double) fprintf(object, "\tdfmul %%accdf, %%(spdf)\n"); } void divl(void){ // Divide (integer, also has remainder) fprintf(object, "\tldiv %%accl, %%(spl)\n"); } void fdiv(void){ // Divide (float) fprintf(object, "\tfdiv %%accf, %%(spf)\n"); } void dfdiv(void){ // Divide (double) fprintf(object, "\tdfdiv %%accdf, %%(spdf)\n"); } void andb(void){ // Bytewise AND (logical) fprintf(object, "\tandb %%accb, %%(spb)\n"); } void accltof(void){ fprintf(object, "\tcvltof %%accl, %%accf\n"); } void spltof(void){ fprintf(object, "\tcvltof %%(spl), %%(spf)\n"); } /* Macro-instruction mul */ int mul(int op, int size){ if(op == '*'){ switch(size){ case 1: lmul(); break; case 2: fmul(); break; case 3: dfmul(); break; default: return -1; } } else if(op == '/'){ switch(size){ case 1: accltof(); case 2: fdiv(); break; case 3: dfdiv(); break; default: return -1; } } else if(op == DIV){ if(size == 1) divl(); else return -1; } else if(op == MOD){ if(size == 1){ divl(); ld("%%rmdr", "l"); } else return -1; }else if(op == AND){ if(size == 4) andb(); else return -1; } return 0; } // Unary operations void ineg(void){ // Negate (integer) fprintf(object, "\tineg %%accl\n"); } void fneg(void){ // Negate (float) fprintf(object, "\tfneg %%accf\n"); } void dfneg(void){ // Negate (double) fprintf(object, "\tdfneg %%accdf\n"); } void notb(void){ // Bytewise NOT (logical) fprintf(object, "\tnotb %%accb\n"); } /* Macro-instruction negate */ int negate(int size){ switch(size){ case 1: ineg(); break; case 2: fneg(); break; case 3: dfneg(); break; case 4: notb(); break; default: return -1; } return 0; }
2.921875
3
2024-11-18T21:15:40.074761+00:00
2017-12-13T14:01:42
570b98028170d5adb02c52a6c384ab7c391c8da7
{ "blob_id": "570b98028170d5adb02c52a6c384ab7c391c8da7", "branch_name": "refs/heads/master", "committer_date": "2017-12-13T14:01:42", "content_id": "43156a3517ec72d6680486cb5e7701653cee1249", "detected_licenses": [ "Apache-2.0" ], "directory_id": "2c7887d289d6b8698c60b6a7fb9be9925a6fef12", "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": 148142731, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2010, "license": "Apache-2.0", "license_type": "permissive", "path": "/zephyr/cs7ns2/adc/src/main.c", "provenance": "stackv2-0112.json.gz:5240", "repo_name": "simonq80/IoT-Patient-Monitor", "revision_date": "2017-12-13T14:01:42", "revision_id": "2c89b7de7504a5fb3f7f9dba58be3b79041bc56b", "snapshot_id": "9aa56ac927a0f7231f096c0cd85cca67037d138e", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/simonq80/IoT-Patient-Monitor/2c89b7de7504a5fb3f7f9dba58be3b79041bc56b/zephyr/cs7ns2/adc/src/main.c", "visit_date": "2020-03-28T10:45:51.784848" }
stackv2
#include <zephyr.h> #include <board.h> #include <device.h> #include <gpio.h> #include <misc/printk.h> #define AIN1 2 #define MAX_SAMPLES 16 #define ADC_REG_BASE 0x40007000 #define ADC_ENABLE_REG (ADC_REG_BASE + 0x500) #define ADC_TASK_START_REG (ADC_REG_BASE + 0x0) #define ADC_TASK_SAMPLE_REG (ADC_REG_BASE + 0x4) #define ADC_TASK_STOP_REG (ADC_REG_BASE + 0x8) #define ADC_EVENT_DONE_REG (ADC_REG_BASE + 0x108) #define ADC_CH0_PSELP_REG (ADC_REG_BASE + 0x510) #define ADC_CH0_CONFIG_REG (ADC_REG_BASE + 0x518) #define ADC_RESULT_PTR_REG (ADC_REG_BASE + 0x62C) #define ADC_RESULT_MAX_REG (ADC_REG_BASE + 0x630) #define ADC_RESULT_CNT_REG (ADC_REG_BASE + 0x634) volatile uint32_t * const adc_enable = ADC_ENABLE_REG; volatile uint32_t * const adc_task_start = ADC_TASK_START_REG; volatile uint32_t * const adc_task_sample = ADC_TASK_SAMPLE_REG; volatile uint32_t * const adc_task_stop = ADC_TASK_STOP_REG; volatile uint32_t * const adc_event_done = ADC_EVENT_DONE_REG; volatile uint32_t * const adc_ch1_pselp = ADC_CH0_PSELP_REG; volatile uint32_t * const adc_ch1_config = ADC_CH0_CONFIG_REG; volatile uint32_t * const adc_result_ptr = ADC_RESULT_PTR_REG; volatile uint32_t * const adc_result_max = ADC_RESULT_MAX_REG; volatile uint32_t * const adc_result_cnt = ADC_RESULT_CNT_REG; #define ADC_REFSEL_VDD_4 (1 << 12) #define ADC_TACQ_40 (5 << 16) uint16_t samples[MAX_SAMPLES]; void main(void) { printk("Preparing ADC\n"); *adc_ch1_pselp = AIN1; *adc_ch1_config = ADC_REFSEL_VDD_4 | ADC_TACQ_40; *adc_enable = 1; while (true) { k_sleep(6000); printk("\nSampling ... "); *adc_result_ptr = samples; *adc_result_max = MAX_SAMPLES; // clear DONE event *adc_event_done = 0; // trigger START task *adc_task_start = 1; // trigger SAMPLE task *adc_task_sample = 1; // delay at least 40uS k_sleep(100); *adc_task_stop = 1; // read from RAM at RESULT_PTR printk("stored: %d, value: %d\n", *adc_result_cnt, samples[0]); } }
2.515625
3
2024-11-18T21:15:40.205091+00:00
2020-08-08T09:50:39
8d7d1c4d416734e6374679a1bf1eaafd200ad875
{ "blob_id": "8d7d1c4d416734e6374679a1bf1eaafd200ad875", "branch_name": "refs/heads/master", "committer_date": "2020-08-08T09:50:39", "content_id": "7c0ab5320f06eaf9161d673e0c8f8144065adacd", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "c9797fdfce38f32bf11c9e9bd36218fbe46819ef", "extension": "c", "filename": "strl.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": 1933, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/src/strl.c", "provenance": "stackv2-0112.json.gz:5497", "repo_name": "zongyanggong/echidna", "revision_date": "2020-08-08T09:50:39", "revision_id": "862c1ef065e83b70666fdc9bc8e38a167f8bb57b", "snapshot_id": "444b89ea79df46924e8764a3366bb27fc41d1f45", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/zongyanggong/echidna/862c1ef065e83b70666fdc9bc8e38a167f8bb57b/src/strl.c", "visit_date": "2023-03-16T07:27:36.556379" }
stackv2
/* $OpenBSD: strlcat.c,v 1.19 2019/01/25 00:19:25 millert Exp $ */ /* $OpenBSD: strlcpy.c,v 1.16 2019/01/25 00:19:25 millert Exp $ */ /* * Copyright (c) 1998, 2015 Todd C. Miller <millert@openbsd.org> * * Permission to use, copy, modify, and 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. */ #include <sys/types.h> #include <string.h> size_t strlcat(char *dst, const char *src, size_t dsize) { const char *odst = dst; const char *osrc = src; size_t n = dsize; size_t dlen; if(!dst || !src) return 0; if(n == 0) return 0; while(n-- != 0 && *dst != '\0') dst++; dlen = dst - odst; n = dsize - dlen; if(n-- == 0) return (dlen + strlen(src)); while(*src != '\0') { if(n != 0) { *dst++ = *src; n--; } src++; } *dst = '\0'; return(dlen + (src - osrc)); } size_t strlcpy(char *dst, const char *src, size_t dsize) { const char *osrc = src; size_t nleft = dsize; if(!dst || !src) return 0; if(nleft == 0) return 0; while(--nleft != 0) { if((*dst++ = *src++) == '\0') break; } if(nleft == 0) { *dst = '\0'; while(*src++); } return(src - osrc - 1); }
2.296875
2
2024-11-18T21:15:40.354987+00:00
2020-09-08T02:52:56
aa12dcd936cad432b6ad5aa16fae153b988c8642
{ "blob_id": "aa12dcd936cad432b6ad5aa16fae153b988c8642", "branch_name": "refs/heads/master", "committer_date": "2020-09-08T02:52:56", "content_id": "63e978a79b1b1b96101453914f5e16de77da6bfb", "detected_licenses": [ "MIT" ], "directory_id": "efb25a20ecddb3a0a8795bc616069fc1a94e5375", "extension": "h", "filename": "timer.h", "fork_events_count": 0, "gha_created_at": "2020-08-21T06:55:08", "gha_event_created_at": "2020-08-24T02:16:20", "gha_language": "C", "gha_license_id": "MIT", "github_id": 289200355, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 9400, "license": "MIT", "license_type": "permissive", "path": "/sdk_k64f/components/timer/timer.h", "provenance": "stackv2-0112.json.gz:5627", "repo_name": "Sir-Branch/k64f-starter-template", "revision_date": "2020-09-08T02:52:56", "revision_id": "f8959fd185f090363d180d69f84c2727e37cbeeb", "snapshot_id": "f6119d67a4d661affca4ca8b5b72a971d0a65754", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/Sir-Branch/k64f-starter-template/f8959fd185f090363d180d69f84c2727e37cbeeb/sdk_k64f/components/timer/timer.h", "visit_date": "2022-12-18T22:24:58.356426" }
stackv2
/* * Copyright 2018 NXP * All rights reserved. * * * SPDX-License-Identifier: BSD-3-Clause */ #ifndef _TIMER_H_ #define _TIMER_H_ /*! * @addtogroup Timer_Adapter * @{ */ /*! * @brief The timer adapter component * * The timer adapter is built based on the timer SDK driver provided by the NXP * MCUXpresso SDK. The timer adapter could provide high accuracy timer for user. * Since callback function would be handled in ISR, and timer clock use high * accuracy clock, user can get accuracy millisecond timer. * * The timer adapter would be used with different HW timer modules like FTM, PIT, LPTMR. * But at the same time, only one HW timer module could be used. On different platforms, different * HW timer module would be used. For the platforms which have multiple HW timer modules, * one HW timer module would be selected as the default, but it is easy to change the default * HW timer module to another. Just two steps to switch the HW timer module: * 1.Remove the default HW timer module source file from the project * 2.Add the expected HW timer module source file to the project. * For example, in platform FRDM-K64F, there are two HW timer modules available, FTM and PIT. * FTM is used as the default HW timer, so ftm_adapter.c and timer.h is included in the project by * default. If PIT is expected to be used as the HW timer, ftm_adapter.c need to be removed from the * project and pit_adapter.c should be included in the project */ /************************************************************************************ ************************************************************************************* * Include ************************************************************************************* ***********************************************************************************/ #if defined(FSL_RTOS_FREE_RTOS) #include "FreeRTOS.h" #endif /************************************************************************************ ************************************************************************************* * Public types ************************************************************************************* ************************************************************************************/ /*! @brief HAL timer callback function. */ typedef void (*hal_timer_callback_t)(void* param); /*! @brief HAL timer status. */ typedef enum _hal_timer_status { kStatus_HAL_TimerSuccess = kStatus_Success, /*!< Success */ kStatus_HAL_TimerNotSupport = MAKE_STATUS(kStatusGroup_HAL_TIMER, 1), /*!< Not Support */ kStatus_HAL_TimerIsUsed = MAKE_STATUS(kStatusGroup_HAL_TIMER, 2), /*!< timer is used */ kStatus_HAL_TimerInvalid = MAKE_STATUS(kStatusGroup_HAL_TIMER, 3), /*!< timer is invalid */ kStatus_HAL_TimerOutOfRanger = MAKE_STATUS(kStatusGroup_HAL_TIMER, 4), /*!< timer is Out Of Ranger */ } hal_timer_status_t; /*! @brief HAL timer configuration structure for HAL timer setting. */ typedef struct _hal_timer_config { uint32_t timeout; /*!< Timeout of the timer, should use microseconds, for example: if set timeout to 1000, mean 1000 microseconds interval would generate timer timeout interrupt*/ uint32_t srcClock_Hz; /*!< Source clock of the timer */ uint8_t instance; /*!< Hardware timer module instance, for example: if you want use FTM0,then the instance is configured to 0, if you want use FTM2 hardware timer, then configure the instance to 2, detail information please refer to the SOC corresponding RM.Invalid instance value will cause initialization failure. */ } hal_timer_config_t; #define HAL_TIMER_HANDLE_SIZE (20U) /*! @brief HAL timer handle. */ typedef void* hal_timer_handle_t; #if defined(__GIC_PRIO_BITS) #define HAL_TIMER_ISR_PRIORITY (25U) #else #if defined(configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY) #define HAL_TIMER_ISR_PRIORITY (configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY) #else /* The default value 3 is used to support different ARM Core, such as CM0P, CM4, CM7, and CM33, etc. * The minimum number of priority bits implemented in the NVIC is 2 on these SOCs. The value of mininum * priority is 3 (2^2 - 1). So, the default value is 3. */ #define HAL_TIMER_ISR_PRIORITY (3U) #endif #endif /************************************************************************************ ************************************************************************************* * Public prototypes ************************************************************************************* ************************************************************************************/ #if defined(__cplusplus) extern "C" { #endif /* _cplusplus */ /*! * @brief Initializes the timer adapter module for a timer basic operation. * * @note This API should be called at the beginning of the application using the timer adapter. * For Initializes timer adapter, * @code * uint32_t halTimerHandleBuffer[((HAL_TIMER_HANDLE_SIZE + sizeof(uint32_t) - 1) / sizeof(uitn32_t))]; * hal_timer_handle_t halTimerHandle = (hal_timer_handle_t)&halTimerHandleBuffer[0]; * hal_timer_config_t halTimerConfig; * halTimerConfig.timeout = 1000; * halTimerConfig.srcClock_Hz = BOARD_GetTimeSrcClock(); * halTimerConfig.instance = 0; * HAL_TimerInit(halTimerHandle, &halTimerConfig); * @endcode * * @param halTimerHandle HAL timer adapter handle, the handle buffer with size #HAL_TIMER_HANDLE_SIZE * should be allocated at upper level. * The handle should be 4 byte aligned, because unaligned access does not support on some devices. * @param halTimerConfig A pointer to the HAL timer configuration structure * @retval kStatus_HAL_TimerSuccess The timer adapter module initialization succeed. * @retval kStatus_HAL_TimerOutOfRanger The timer adapter instance out of ranger. */ hal_timer_status_t HAL_TimerInit(hal_timer_handle_t halTimerHandle, hal_timer_config_t* halTimerConfig); /*! * @brief DeInitilizate the timer adapter module. * * @note This API should be called when not using the timer adapter anymore. * * @param halTimerHandle HAL timer adapter handle */ void HAL_TimerDeinit(hal_timer_handle_t halTimerHandle); /*! * @brief Enable the timer adapter module. * * @note This API should be called when enable the timer adapter. * * @param halTimerHandle HAL timer adapter handle */ void HAL_TimerEnable(hal_timer_handle_t halTimerHandle); /*! * @brief Disable the timer adapter module. * * @note This API should be called when disable the timer adapter. * * @param halTimerHandle HAL timer adapter handle */ void HAL_TimerDisable(hal_timer_handle_t halTimerHandle); /*! * @brief Install the timer adapter module callback function. * * @note This API should be called to when to install callback function for the timer.Since callback function * would be handled in ISR, and timer clock use high accuracy clock, user can get accuracy millisecond timer. * * @param halTimerHandle HAL timer adapter handle * @param callback The installed callback function by upper layer * @param callbackParam The callback function parameter */ void HAL_TimerInstallCallback(hal_timer_handle_t halTimerHandle, hal_timer_callback_t callback, void* callbackParam); /*! * @brief Get the timer count of the timer adapter. * * @note This API should be return the real-time timer counting value in a range from 0 to a * timer period, and return microseconds. * * @param halTimerHandle HAL timer adapter handle * @retval the real-time timer counting value and return microseconds. */ uint32_t HAL_TimerGetCurrentTimerCount(hal_timer_handle_t halTimerHandle); /*! * @brief Update the timeout of the timer adapter to generate timeout interrupt. * * @note This API should be called when need set the timeout of the timer interrupt.. * * @param halTimerHandle HAL timer adapter handle * @param Timeout Timeout time, should be used microseconds. * @retval kStatus_HAL_TimerSuccess The timer adapter module update timeout succeed. * @retval kStatus_HAL_TimerOutOfRanger The timer adapter set the timeout out of ranger. */ hal_timer_status_t HAL_TimerUpdateTimeout(hal_timer_handle_t halTimerHandle, uint32_t timeout); /*! * @brief Get maximum Timer timeout * * @note This API should to get maximum Timer timeout value to avoid overflow * * @param halTimerHandle HAL timer adapter handle * @retval get the real-time timer maximum timeout value and return microseconds. */ uint32_t HAL_TimerGetMaxTimeout(hal_timer_handle_t halTimerHandle); /*! * @brief Timer adapter power up function. * * @note This API should be called by low power module when system exit from sleep mode. * * @param halTimerHandle HAL timer adapter handle */ void HAL_TimerExitLowpower(hal_timer_handle_t halTimerHandle); /*! * @brief Timer adapter power down function. * * @note This API should be called by low power module before system enter into sleep mode. * * @param halTimerHandle HAL timer adapter handle */ void HAL_TimerEnterLowpower(hal_timer_handle_t halTimerHandle); #if defined(__cplusplus) } #endif /*! @}*/ #endif /* _TIMER_H_ */
2.09375
2
2024-11-18T21:15:40.693702+00:00
2021-05-06T12:48:13
51c6d0a982db605a8cfe66819463153a9122ae46
{ "blob_id": "51c6d0a982db605a8cfe66819463153a9122ae46", "branch_name": "refs/heads/main", "committer_date": "2021-05-06T12:48:13", "content_id": "f6f13abb24a22939ecb185af2cd0669deba5a1f5", "detected_licenses": [ "MIT" ], "directory_id": "31552192f8dc1c877131e17957a004b64476ff09", "extension": "c", "filename": "main.c", "fork_events_count": 1, "gha_created_at": "2021-05-06T11:31:45", "gha_event_created_at": "2021-05-29T20:24:06", "gha_language": "C", "gha_license_id": "MIT", "github_id": 364887321, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 295, "license": "MIT", "license_type": "permissive", "path": "/main.c", "provenance": "stackv2-0112.json.gz:5886", "repo_name": "mmusta/hello-world", "revision_date": "2021-05-06T12:48:13", "revision_id": "1369f14f4443c86675b9f9d680fae372f7753c49", "snapshot_id": "a6de7c75ba049547d582ac660dedaad8ff4c7686", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/mmusta/hello-world/1369f14f4443c86675b9f9d680fae372f7753c49/main.c", "visit_date": "2023-05-07T03:25:55.245950" }
stackv2
#include <stdio.h> #include <stdlib.h> #define NAME_SIZE 128 typedef char * String; void greet(); int main() { greet(); } void greet() { String name = malloc(NAME_SIZE); printf("Please enter your name: "); scanf("%s", name); printf("Greetings %s. Welcome back!", name); }
3
3
2024-11-18T21:15:41.013694+00:00
2023-08-31T07:33:29
c620bc77fb07582b8ada94bf3697a9ae5db2b087
{ "blob_id": "c620bc77fb07582b8ada94bf3697a9ae5db2b087", "branch_name": "refs/heads/master", "committer_date": "2023-08-31T07:33:29", "content_id": "18c56f98bebb022a4af0c234eb35c5e43ee70e3d", "detected_licenses": [ "MIT" ], "directory_id": "76007b83037e7b0e21996b3249df62c1c5a88ca4", "extension": "c", "filename": "common.c", "fork_events_count": 1, "gha_created_at": "2018-11-09T01:37:35", "gha_event_created_at": "2023-07-10T23:17:40", "gha_language": "C", "gha_license_id": "MIT", "github_id": 156793226, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1046, "license": "MIT", "license_type": "permissive", "path": "/asm/common.c", "provenance": "stackv2-0112.json.gz:6144", "repo_name": "dingjingmaster/demo", "revision_date": "2023-08-31T07:33:29", "revision_id": "a5767b166e9a8b27f440f32b7052a3a08e9cab16", "snapshot_id": "b84ad148bb1ef4e8c4302d54c4e3f1249a5b5c3f", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/dingjingmaster/demo/a5767b166e9a8b27f440f32b7052a3a08e9cab16/asm/common.c", "visit_date": "2023-08-31T08:51:38.315518" }
stackv2
/************************************************************************* > FileName: common.c > Author : DingJing > Mail : dingjing@live.cn > Created Time: 2022年01月05日 星期三 14时58分09秒 ************************************************************************/ #include <stdio.h> int get_int () { int d = 0; scanf ("%d", d); return d; } double get_double () { double d = 0; scanf ("%ld", d); return d; } void print_hello () { printf ("hello\n"); } void print_enter () { printf ("\n"); } void print_short (short i) { printf ("%d\n", i); } void print_int (int i) { printf ("%d\n", i); } void print_float (float f) { printf ("%f\n", f); } void print_double (double f) { printf ("%f\n", f); } void print_long (long i) { printf ("%ld\n", i); } void print_arr_int (int arr[], int len) { for (int i = 0; i < len; ++i) { printf ("%d ", arr[i]); } printf ("\n"); } void print_string (const char* s) { if (!s) return; printf ("%s\n", s); }
2.890625
3
2024-11-18T21:15:42.116652+00:00
2023-09-02T14:55:31
fbe7863c4934687b26c687238eb2fe0ba106b98f
{ "blob_id": "fbe7863c4934687b26c687238eb2fe0ba106b98f", "branch_name": "refs/heads/master", "committer_date": "2023-09-02T14:55:31", "content_id": "a539687c19c5c31ce2e798d730f85c6c98aa4f21", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "8838eb997879add5759b6dfb23f9a646464e53ca", "extension": "h", "filename": "auth.h", "fork_events_count": 325, "gha_created_at": "2015-03-29T15:27:48", "gha_event_created_at": "2023-09-14T16:58:34", "gha_language": "C", "gha_license_id": "BSD-2-Clause", "github_id": 33078138, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1734, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/src/include/net/lib/rpc/auth.h", "provenance": "stackv2-0112.json.gz:6530", "repo_name": "embox/embox", "revision_date": "2023-09-02T14:55:31", "revision_id": "98e3c06e33f3fdac10a29c069c20775568e0a6d1", "snapshot_id": "d6aacec876978522f01cdc4b8de37a668c6f4c80", "src_encoding": "UTF-8", "star_events_count": 1087, "url": "https://raw.githubusercontent.com/embox/embox/98e3c06e33f3fdac10a29c069c20775568e0a6d1/src/include/net/lib/rpc/auth.h", "visit_date": "2023-09-04T03:02:20.165042" }
stackv2
/** * @file * @brief * @date 02.06.12 * @author Ilia Vaprol */ #ifndef NET_LIB_RPC_AUTH_H_ #define NET_LIB_RPC_AUTH_H_ #include <stdint.h> /* Prototypes */ struct xdr; struct auth; #define AUTH_DATA_MAX_SZ 400 #define HOST_NAME_MAX_SZ 255 #define GIDS_MAX_SZ 16 /* Errors of a authentication */ enum auth_stat { AUTH_OK = 0, AUTH_BADCRED = 1, /* bad credentials (seal broken) */ AUTH_REJECTEDCRED = 2, /* client must begin new session */ AUTH_BADVERF = 3, /* bad verifier (seal broken) */ AUTH_REJECTEDVERF = 4, /* verifier expired or replayed */ AUTH_TOOWEAK = 5, /* rejected for security reasons */ AUTH_INVALIDRESP = 6, /* bogus response verifier */ AUTH_FAILED = 7, /* some unknown reason */ AUTH_MAX }; enum auth_flavor { AUTH_NULL = 0, AUTH_UNIX = 1, AUTH_SHORT = 2, AUTH_DES = 3 }; struct opaque_auth { enum auth_flavor flavor; char *data; uint32_t data_len; }; struct auth_ops { void (*destroy)(struct auth *); }; struct auth { struct opaque_auth cred; struct opaque_auth verf; const struct auth_ops *ops; }; struct authunix_parms { uint32_t stamp; char *host; uint32_t uid; uint32_t gid; uint32_t *gids; uint32_t gids_len; }; extern const struct opaque_auth __opaque_auth_null; /* Auth factory */ extern struct auth * auth_alloc(void); extern void auth_free(struct auth *ath); extern struct auth * authnone_create(void); extern struct auth * authunix_create(char *host, int uid, int gid, int user_gids_len, int *user_gids); extern void auth_destroy(struct auth *ath); extern int xdr_opaque_auth(struct xdr *xs, struct opaque_auth *oa); extern int xdr_authunix_parms(struct xdr *xs, struct authunix_parms *aup); #endif /* NET_LIB_RPC_AUTH_H_ */
2.171875
2
2024-11-18T21:15:42.196309+00:00
2023-08-23T04:46:46
989a76e1643becd33501858b8e358b5752b52885
{ "blob_id": "989a76e1643becd33501858b8e358b5752b52885", "branch_name": "refs/heads/master", "committer_date": "2023-08-23T04:46:46", "content_id": "4b58a4d0de264bf906e6d70cab558d3c0b928ce7", "detected_licenses": [ "MIT" ], "directory_id": "2c73a693c2b3c162eae2ab94f649d8c4494878ba", "extension": "c", "filename": "rotable2.c", "fork_events_count": 93, "gha_created_at": "2019-12-27T08:29:19", "gha_event_created_at": "2021-12-17T02:19:30", "gha_language": "C", "gha_license_id": "MIT", "github_id": 230403844, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 6361, "license": "MIT", "license_type": "permissive", "path": "/lua/src/rotable2.c", "provenance": "stackv2-0112.json.gz:6658", "repo_name": "openLuat/LuatOS", "revision_date": "2023-08-23T04:46:46", "revision_id": "4b29d5121ab4f7133630331e8502c526c7856897", "snapshot_id": "185e1e140aed908434168133571ddcafe98f4e12", "src_encoding": "UTF-8", "star_events_count": 378, "url": "https://raw.githubusercontent.com/openLuat/LuatOS/4b29d5121ab4f7133630331e8502c526c7856897/lua/src/rotable2.c", "visit_date": "2023-08-23T04:57:23.263539" }
stackv2
/** * rotable 实现 lua下的只读table, 用于通常只用于库的注册.</p> * 从原理上说, 是声明一个userdata内存块, 然后通过元表,将其伪装成table.<p/> * 因为元表是共享的,而userdata内存块也很小(小于30字节),而且不会与方法的数量有关, 节省大量内存. * */ #include <stddef.h> #include <string.h> #include <stdlib.h> #include "lua.h" #include "rotable2.h" /* The lookup code uses binary search on sorted `rotable_Reg` arrays * to find functions/methods. For a small number of elements a linear * search might be faster. */ #ifndef ROTABLE_BINSEARCH_MIN # define ROTABLE_BINSEARCH_MIN 5 #endif typedef struct { int n; } rotable; static char const unique_address[ 1 ] = { 0 }; static int reg_compare(void const* a, void const* b) { return strcmp( (char const*)a, ((const rotable_Reg_t*)b)->name ); } static int rotable_push_rovalue(lua_State *L, const rotable_Reg_t* q) { switch (q->value.type) { case LUA_TFUNCTION: lua_pushcfunction( L, q->value.value.func ); break; case LUA_TINTEGER: lua_pushinteger( L, q->value.value.intvalue ); break; case LUA_TSTRING: lua_pushstring( L, q->value.value.strvalue ); break; case LUA_TNUMBER: lua_pushnumber( L, q->value.value.numvalue ); break; case LUA_TLIGHTUSERDATA: lua_pushlightuserdata(L, q->value.value.ptr); break; default: return 0; } return 1; } static rotable* check_rotable( lua_State* L, int idx, char const* func ) { rotable* t = (rotable*)lua_touserdata( L, idx ); if( t ) { if( lua_getmetatable( L, idx ) ) { lua_pushlightuserdata( L, (void*)unique_address ); lua_rawget( L, LUA_REGISTRYINDEX ); if( !lua_rawequal( L, -1, -2 ) ) t = 0; lua_pop( L, 2 ); } } if( !t ) { char const* type = lua_typename( L, lua_type( L, idx ) ); if( lua_type( L, idx ) == LUA_TLIGHTUSERDATA ) { type = "light userdata"; } else if( lua_getmetatable( L, idx ) ) { lua_getfield( L, -1, "__name" ); lua_replace( L, -2 ); /* we don't need the metatable anymore */ if( lua_type( L, -1 ) == LUA_TSTRING ) type = lua_tostring( L, -1 ); } lua_pushfstring( L, "bad argument #%d to '%s' " "(rotable expected, got %s)", idx, func, type ); lua_error( L ); } return t; } static const rotable_Reg_t* find_key( const rotable_Reg_t* p, int n, char const* s ) { if( s ) { for( ; p->name != NULL; ++p ) { if( 0 == reg_compare( s, p ) ) return p; } } return 0; } static int rotable_func_index( lua_State* L ) { char const* s = lua_tostring( L, 2 ); const rotable_Reg_t* p = (const rotable_Reg_t*)lua_touserdata( L, lua_upvalueindex( 1 ) ); const rotable_Reg_t* p2 = p; int n = lua_tointeger( L, lua_upvalueindex( 2 ) ); p = find_key( p, n, s ); if( p ) { rotable_push_rovalue(L, p); } else { // 看看第一个方法是不是__index, 如果是的话, 调用之 if (p2->name != NULL && !strcmp("__index", p2->name)) { lua_pushcfunction(L, p2->value.value.func); lua_pushvalue(L, 2); lua_call(L, 1, 1); return 1; } lua_pushnil( L ); } return 1; } static int rotable_udata_index( lua_State* L ) { rotable* t = (rotable*)lua_touserdata( L, 1 ); char const* s = lua_tostring( L, 2 ); const rotable_Reg_t* p = 0; lua_getuservalue( L, 1 ); p = (const rotable_Reg_t*)lua_touserdata( L, -1 ); const rotable_Reg_t* p2 = p; p = find_key( p, t->n, s ); if( p ) { if (rotable_push_rovalue(L, p)) { return 1; } return 0; } else { // 看看第一个方法是不是__index, 如果是的话, 调用之 if (p2->name != NULL && !strcmp("__index", p2->name)) { lua_pushcfunction(L, p2->value.value.func); lua_pushvalue(L, 2); lua_call(L, 1, 1); return 1; } lua_pushnil( L ); } return 1; } static int rotable_udata_len( lua_State* L ) { lua_pushinteger( L, 0 ); return 1; } static int rotable_iter( lua_State* L ) { check_rotable( L, 1, "__pairs iterator" ); char const* key; const rotable_Reg_t* q = 0; const rotable_Reg_t* p = 0; int isnil = lua_isnil(L, 2); lua_getuservalue( L, 1 ); p = (const rotable_Reg_t*)lua_touserdata( L, -1 ); if (isnil) { lua_pushstring(L, p->name); rotable_push_rovalue(L, p); return 2; } key = lua_tostring(L, 2); for( q = p; q->name != NULL; ++q ) { if( 0 == reg_compare( key, q ) ) { ++q; break; } } if (q == NULL || q->name == NULL) { return 0; } lua_pushstring( L, q->name ); rotable_push_rovalue(L, q); return 2; } static int rotable_udata_pairs( lua_State* L ) { lua_pushcfunction( L, rotable_iter ); lua_pushvalue( L, 1 ); lua_pushnil( L ); return 3; } /** * 与lua_newlib对应的函数, 用于生成一个库table,区别是lua_newlib生成普通table,这个函数生成rotable. */ ROTABLE_EXPORT void rotable2_newlib( lua_State* L, void const* v ) { const rotable_Reg_t* reg = (const rotable_Reg_t*)v; rotable* t = (rotable*)lua_newuserdata( L, sizeof( *t ) ); lua_pushlightuserdata( L, (void*)unique_address ); lua_rawget( L, LUA_REGISTRYINDEX ); if( !lua_istable( L, -1 ) ) { lua_pop( L, 1 ); lua_createtable( L, 0, 5 ); lua_pushcfunction( L, rotable_udata_index ); lua_setfield( L, -2, "__index" ); lua_pushcfunction( L, rotable_udata_len ); lua_setfield( L, -2, "__len" ); lua_pushcfunction( L, rotable_udata_pairs ); lua_setfield( L, -2, "__pairs" ); lua_pushboolean( L, 0 ); lua_setfield( L, -2, "__metatable" ); lua_pushliteral( L, "rotable" ); lua_setfield( L, -2, "__name" ); lua_pushlightuserdata( L, (void*)unique_address ); lua_pushvalue( L, -2 ); lua_rawset( L, LUA_REGISTRYINDEX ); } lua_setmetatable( L, -2 ); #if LUA_VERSION_NUM < 503 t->p = reg; #else lua_pushlightuserdata( L, (void*)reg ); lua_setuservalue( L, -2 ); #endif } /** * 为自定义对象也生成rotable形式的元表, 这个形式比rotable_newlib需要更多内存,但起码是一个解决办法. */ ROTABLE_EXPORT void rotable2_newidx( lua_State* L, void const* v ) { lua_pushlightuserdata( L, (void*)v); lua_pushcclosure( L, rotable_func_index, 1 ); }
2.59375
3
2024-11-18T21:15:43.530271+00:00
2020-11-10T00:23:31
23653871215c0937dfcfcab7a8df85e5e04d06e5
{ "blob_id": "23653871215c0937dfcfcab7a8df85e5e04d06e5", "branch_name": "refs/heads/master", "committer_date": "2020-11-10T00:23:31", "content_id": "a7373cd610369aab0e88ca840c204f4c897f40f1", "detected_licenses": [ "Apache-2.0" ], "directory_id": "15e818aada2b18047fa895690bc1c2afda6d7273", "extension": "c", "filename": "isr_diag.c", "fork_events_count": 0, "gha_created_at": "2020-10-06T21:51:21", "gha_event_created_at": "2020-11-10T00:23:32", "gha_language": null, "gha_license_id": "Apache-2.0", "github_id": 301863147, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5050, "license": "Apache-2.0", "license_type": "permissive", "path": "/avionics/motor/firmware/isr_diag.c", "provenance": "stackv2-0112.json.gz:8076", "repo_name": "ghomsy/makani", "revision_date": "2020-11-10T00:23:31", "revision_id": "818ae8b7119b200a28af6b3669a3045f30e0dc64", "snapshot_id": "4ee34c4248fb0ac355f65aaed35718b1f5eabecf", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/ghomsy/makani/818ae8b7119b200a28af6b3669a3045f30e0dc64/avionics/motor/firmware/isr_diag.c", "visit_date": "2023-01-11T18:46:21.939471" }
stackv2
/* * Copyright 2020 Makani Technologies LLC * * 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 "avionics/motor/firmware/isr_diag.h" #include <signal.h> #include <stdint.h> #include "avionics/common/avionics_messages.h" #include "avionics/common/motor_foc_types.h" #include "avionics/motor/firmware/angle_meas.h" #include "common/barrier.h" #include "common/macros.h" typedef enum { kBufferIsrPrimary, kBufferIsrReserve, kBufferIo, kNumBuffers, } IsrDiagBufferOffsets; IsrDiagState g_isr_diag_state = { // Default to false so that motors don't automatically saturate the network. .isr_diag_enable = 0.0f, }; // Pointer to the buffer being filled by the ISR. static sig_atomic_t g_isr_buffer_ind = 0; // Keep track of the total number of samples from the ISR. This is fairly // convenient when reconstructing the data in addition to making the process // robust to out of order messages and clearly indicating dropped messages or // missing samples. static uint32_t g_total_samples = 0; static MotorIsrDiagMessage g_buffer[] = { { .total = 0, .num_samples = 0, .errors = {0}, .vbus = {0.0}, .ibus = {0.0}, .ia = {0.0}, .ib = {0.0}, .ic = {0.0}, .sin = {0}, .cos = {0}, .vab_ref = {0.0}, .vab_angle = {0.0}, }, { .total = 0, .num_samples = 0, .errors = {0}, .vbus = {0.0}, .ibus = {0.0}, .ia = {0.0}, .ib = {0.0}, .ic = {0.0}, .sin = {0}, .cos = {0}, .vab_ref = {0.0}, .vab_angle = {0.0}, }, { .total = 0, .num_samples = 0, .errors = {0}, .vbus = {0.0}, .ibus = {0.0}, .ia = {0.0}, .ib = {0.0}, .ic = {0.0}, .sin = {0}, .cos = {0}, .vab_ref = {0.0}, .vab_angle = {0.0}, } }; COMPILE_ASSERT(ARRAYSIZE(g_buffer) == kNumBuffers, g_buffer_should_be_length_kNumBuffers); // Log data to one of the buffers in g_buffer. If space is available, IsrDiagLog // will update the primary buffer with index g_isr_buffer_ind. If that buffer is // full, (g_isr_buffer_ind + kBufferIsrReserve) % kNumBuffers is used. This is // the next primary buffer such that it will continue to be filled after // IsrDiagGetMessage is called resulting in a continuous set of samples. void IsrDiagLog(uint32_t errors, uint32_t warnings, const MotorAngleMeas *angle_meas, const MotorState *motor_state, const FocVoltage *voltage_ab) { if (IsrDiagIsEnabled()) { uint32_t i_buffer = g_isr_buffer_ind; if (g_buffer[i_buffer].num_samples >= MOTOR_ISR_DIAG_MESSAGE_LENGTH) { // Overflow to the next primary ISR buffer. i_buffer = (i_buffer + kBufferIsrReserve) % kNumBuffers; } // Buffer data if space is available. uint32_t i_sample = g_buffer[i_buffer].num_samples; if (i_sample < MOTOR_ISR_DIAG_MESSAGE_LENGTH) { g_buffer[i_buffer].errors[i_sample] = errors; g_buffer[i_buffer].warnings[i_sample] = warnings; g_buffer[i_buffer].vbus[i_sample] = motor_state->v_bus; g_buffer[i_buffer].ibus[i_sample] = motor_state->i_bus; g_buffer[i_buffer].ia[i_sample] = motor_state->ia; g_buffer[i_buffer].ib[i_sample] = motor_state->ib; g_buffer[i_buffer].ic[i_sample] = motor_state->ic; g_buffer[i_buffer].sin[i_sample] = angle_meas->sin_m; g_buffer[i_buffer].cos[i_sample] = angle_meas->cos_m; g_buffer[i_buffer].vab_ref[i_sample] = voltage_ab->v_ref; g_buffer[i_buffer].vab_angle[i_sample] = voltage_ab->angle; // Update the number of samples in the buffer and total number of samples // neglecting the contents of the buffer. g_buffer[i_buffer].num_samples++; g_buffer[i_buffer].total = g_total_samples - i_sample; } ++g_total_samples; // Always increment the total number of samples. } } // Advance g_isr_buffer_ind and return a pointer to the buffer it was previously // indexing. MotorIsrDiagMessage *IsrDiagGetMessage() { // Reset the sample counter in the most recently transmitted buffer before // exposing it to the ISR. g_buffer[(g_isr_buffer_ind + kBufferIo) % kNumBuffers].num_samples = 0; // Advance buffers and return the last buffer to be filled by the ISR. A // memory barrier is used to enforce ordering instead of volatile because of // auto-generation issues. uint32_t last_isr_buffer_ind = g_isr_buffer_ind; MemoryBarrier(); g_isr_buffer_ind = (g_isr_buffer_ind + kBufferIsrReserve) % kNumBuffers; MemoryBarrier(); return &g_buffer[last_isr_buffer_ind]; }
2.09375
2
2024-11-18T21:15:43.643516+00:00
2020-03-24T13:24:54
9e0975070d561cd39625ab93bece4b218ee405c2
{ "blob_id": "9e0975070d561cd39625ab93bece4b218ee405c2", "branch_name": "refs/heads/master", "committer_date": "2020-03-24T13:24:54", "content_id": "b522a2295cae1ca29250d986ad3740e60b869033", "detected_licenses": [ "MIT" ], "directory_id": "e58c3c7281a612d3a1d4cd6e06fa7fb4ce67a5b4", "extension": "c", "filename": "getw.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 249255200, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1017, "license": "MIT", "license_type": "permissive", "path": "/Borland/CBuilder5/Source/RTL/source/io/getw.c", "provenance": "stackv2-0112.json.gz:8205", "repo_name": "TrevorDArcyEvans/Diving-Magpie-Software", "revision_date": "2020-03-24T13:24:54", "revision_id": "7ffcfef653b110e514d5db735d11be0aae9953ec", "snapshot_id": "b6e117e4c50030b208f5e2e9650fd169f7d6daac", "src_encoding": "UTF-8", "star_events_count": 3, "url": "https://raw.githubusercontent.com/TrevorDArcyEvans/Diving-Magpie-Software/7ffcfef653b110e514d5db735d11be0aae9953ec/Borland/CBuilder5/Source/RTL/source/io/getw.c", "visit_date": "2022-04-10T11:23:57.914631" }
stackv2
/*-----------------------------------------------------------------------* * filename - _getw.c * * function(s) * _getw - gets a word from a stream *-----------------------------------------------------------------------*/ /* * C/C++ Run Time Library - Version 10.0 * * Copyright (c) 1987, 2000 by Inprise Corporation * All Rights Reserved. * */ /* $Revision: 9.0 $ */ #include <stdio.h> /*---------------------------------------------------------------------* Name _getw - gets a word from a stream Usage #include <stdio.h> int _getw(FILE * stream); Prototype in stdio.h Description see getc *---------------------------------------------------------------------*/ int _RTLENTRY _EXPFUNC _getw(FILE *fp) { int c, res, i; char *p; for (i = 0, p = (char *)&res; i < sizeof(int); i++, p++) if ((c = getc(fp)) == EOF) return (EOF); else *p = (char)c; return(res); }
2.375
2