added
stringdate
2024-11-18 17:54:19
2024-11-19 03:39:31
created
timestamp[s]date
1970-01-01 00:04:39
2023-09-06 04:41:57
id
stringlengths
40
40
metadata
dict
source
stringclasses
1 value
text
stringlengths
13
8.04M
score
float64
2
4.78
int_score
int64
2
5
2024-11-18T21:50:54.682523+00:00
2017-03-12T22:32:10
e61ff21bc433dbe79d33bbf5e523174fb8885221
{ "blob_id": "e61ff21bc433dbe79d33bbf5e523174fb8885221", "branch_name": "refs/heads/master", "committer_date": "2017-03-12T22:32:10", "content_id": "c8635204d0f62c25aff9be1a92bfca9e152f2af7", "detected_licenses": [ "MIT" ], "directory_id": "334408de542ac67466689ba665bb8a700dd9be8d", "extension": "c", "filename": "callbacks.c", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 152896942, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 670, "license": "MIT", "license_type": "permissive", "path": "/src/callbacks.c", "provenance": "stackv2-0138.json.gz:132392", "repo_name": "ssayin/city", "revision_date": "2017-03-12T22:32:10", "revision_id": "e89aec31179321634d6c5326e5344c0645576ffa", "snapshot_id": "31b0c6338447a10362c8ee2ea1717cd14674c82b", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/ssayin/city/e89aec31179321634d6c5326e5344c0645576ffa/src/callbacks.c", "visit_date": "2021-09-23T02:28:16.754077" }
stackv2
#include "include/city.h" #include <string.h> static int string_begins_with(const char* str, const char* match) { if (strlen(match) > strlen(str)) return 0; for (int i = 0; i < strlen(match); ++i) { if (str[i] != match[i]) { return 0; } } return 1; } int city_search_by_name(City* ptr, const char* name) { return string_begins_with(ptr->name, name); } int city_search_by_region(City* ptr, const char* region) { return string_begins_with(ptr->region, region); } City* city_print_step_next(City* ptr) { return ptr->next; } City* city_print_step_nextnext(City* ptr) { return ptr->nextnext; }
2.421875
2
2024-11-18T21:50:56.485733+00:00
2017-12-29T02:38:48
7e94a3f3d8ddcc1507291338af7b582a769d7b86
{ "blob_id": "7e94a3f3d8ddcc1507291338af7b582a769d7b86", "branch_name": "refs/heads/master", "committer_date": "2017-12-29T02:38:48", "content_id": "d7c1fc2878b34afa9d8229136c7b19f45a5a9916", "detected_licenses": [ "MIT" ], "directory_id": "b019a1dc9d93bbd551279e2d07c1aecf1e5cc7c8", "extension": "h", "filename": "mm.h", "fork_events_count": 3, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 109394744, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 476, "license": "MIT", "license_type": "permissive", "path": "/mm.h", "provenance": "stackv2-0138.json.gz:132648", "repo_name": "Neol-d2022/OpenSync-se106a", "revision_date": "2017-12-29T02:38:48", "revision_id": "a5a67d2462884de16cc7b001bc054ceabe70f37e", "snapshot_id": "298aa74d2f5c69284803e8f809e721d7e09c9204", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/Neol-d2022/OpenSync-se106a/a5a67d2462884de16cc7b001bc054ceabe70f37e/mm.h", "visit_date": "2021-09-03T02:54:18.553597" }
stackv2
#ifndef _MM_H_LOADED #define _MM_H_LOADED /* size_t */ #include <stddef.h> /* Request a memory block with s bytes */ void *Mmalloc(size_t s); /* Relocate memory block p to s bytes */ void *Mrealloc(void *p, size_t s); /* When the system is out of memory, the functions above will immediately crash the program, instead of return NULL */ /* Release memory block p */ void Mfree(void *p); /* DEBUG. Return the number of allocated memory blocks */ size_t MDebug(); #endif
2.0625
2
2024-11-18T21:50:56.728769+00:00
2023-08-09T12:19:02
7bbf49b2d98276df0de2c5c0e3606a7d013cef53
{ "blob_id": "7bbf49b2d98276df0de2c5c0e3606a7d013cef53", "branch_name": "refs/heads/master", "committer_date": "2023-08-09T12:19:02", "content_id": "d5a8e2ef9ba921a2551412b02e65deb7c8b1dfd6", "detected_licenses": [ "Unlicense" ], "directory_id": "e60b457a42892430eef7ead48ca55ad0a169b542", "extension": "h", "filename": "rsa.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 127428326, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4117, "license": "Unlicense", "license_type": "permissive", "path": "/src/2-rsa/rsa.h", "provenance": "stackv2-0138.json.gz:133039", "repo_name": "dannyniu/MySuiteA", "revision_date": "2023-08-09T12:19:02", "revision_id": "bec4fd480f07f3ab1b960f6e73d1493d2a0cdc33", "snapshot_id": "0d8de4c7ea0b19438c75da52c619433e880c477c", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/dannyniu/MySuiteA/bec4fd480f07f3ab1b960f6e73d1493d2a0cdc33/src/2-rsa/rsa.h", "visit_date": "2023-08-21T12:08:24.321341" }
stackv2
/* DannyNiu/NJF, 2021-01-13. Public Domain. */ #ifndef MySuiteA_rsa_h #define MySuiteA_rsa_h 1 #include "../1-integers/vlong.h" // -- For *ALL* working context data structures defined in this file -- // data model: SIP16 | ILP32 | LP64 // ----------+-------+-------+------ // align spec: 4 * n . // The structure is intentionally designed not in specification order, // this "array order" is intended to enable writing decryption/signing // operation in a single loop. // The CRT decryption/signing code assumes working variables w3 and w4 // can hold 3 factor-sized integers. It is further assumed that // each factor will be at least 512 bits. typedef struct { // CRT decryption/signing needs 3 modulus-sized and 3 factor-sized // vlongs. Key generation requires 4 modulus-sized vlongs. // It is guaranteed that the allocation of w1 thru w4 are contiguous, // although the placement of such contiguous region is undefined. uint32_t offset_w1, offset_w2, offset_w3, offset_w4, offset_w5; uint32_t count_primes_other, modulus_bits; uint32_t offset_n, offset_e, offset_d; uint32_t offset_q, offset_dQ; uint32_t offset_p, offset_dP, offset_qInv; } RSA_Priv_Base_Ctx_t; typedef struct { uint32_t offset_r, offset_d, offset_t; } RSA_OtherPrimeInfo_t; // // RSA Private Context Header. #define RSA_PRIV_CTX_HDR_T(...) \ struct { \ RSA_Priv_Base_Ctx_t base; \ RSA_OtherPrimeInfo_t primes_other[__VA_ARGS__]; \ } typedef RSA_PRIV_CTX_HDR_T() RSA_Priv_Ctx_Hdr_t; // The value of ${ [0].aux } is the size of modulus in bits. // The value of ${ [1].aux } is the number of primes. typedef CryptoParam_t RSA_Priv_Param_t[2]; // [!A-E-D!]: If c does not divide l, behavior is undefined. // // 2021-09-11: // The erroneous (2 + 4) is changed to (5 + 2). // (2 * 4) changed to VLONG_BITS_SIZE(17) // // 2022-02-13: // RSA_INTEGER_SIZE changed to VLONG_BITS_SIZE #define RSA_PRIV_CTX_PAYLOAD_SIZE_X(l,c) ( \ VLONG_BITS_SIZE((l) / (c)) * (3 * (c) - 1) + \ VLONG_BITS_SIZE((l)) * (5 + 2) + \ VLONG_BITS_SIZE(17) ) #define RSA_PRIV_CTX_PAYLOAD_SIZE(...) \ RSA_PRIV_CTX_PAYLOAD_SIZE_X(__VA_ARGS__) #define RSA_PRIV_CTX_SIZE_X(l,c) ( \ RSA_PRIV_CTX_PAYLOAD_SIZE(l,c) + \ sizeof(RSA_Priv_Base_Ctx_t) + \ sizeof(RSA_OtherPrimeInfo_t) * ((c) - 2) ) #define RSA_PRIV_CTX_SIZE(...) \ RSA_PRIV_CTX_SIZE_X(__VA_ARGS__) #define RSA_PRIV_CTX_T(l,c) \ struct { \ RSA_PRIV_CTX_HDR_T(c) header; \ uint8_t payload[RSA_PRIV_CTX_PAYLOAD_SIZE(l,c)]; \ } typedef struct { uint32_t offset_w1, offset_w2, offset_w3, offset_w4; uint32_t offset_n, offset_e, modulus_bits; } RSA_Pub_Ctx_Hdr_t; // The value of ${ [0].aux } is the size of modulus in bits. typedef CryptoParam_t RSA_Pub_Param_t[1]; #define RSA_PUB_CTX_PAYLOAD_SIZE(l) ( \ VLONG_BITS_SIZE((l)) * (4 + 1) + \ VLONG_BITS_SIZE(17) ) #define RSA_PUB_CTX_SIZE(l) ( \ RSA_PUB_CTX_PAYLOAD_SIZE(l) + \ sizeof(RSA_Pub_Ctx_Hdr_t) ) #define RSA_PUB_CTX_T(l) \ struct { \ RSA_Pub_Ctx_Hdr_t header; \ uint8_t payload[RSA_PUB_CTX_PAYLOAD_SIZE(l)]; \ } // If x is NULL, returns size estimate for its memory allocation; // otherwise, returns x on success and 0 (NULL) on failure. IntPtr rsa_keygen( RSA_Priv_Ctx_Hdr_t *restrict x, CryptoParam_t *restrict param, GenFunc_t prng_gen, void *restrict prng); // 2022-02-25: remove 1 obsolete note from 2021-05-15. vlong_t *rsa_enc(RSA_Pub_Ctx_Hdr_t *restrict x); vlong_t *rsa_fastdec(RSA_Priv_Ctx_Hdr_t *restrict x); #endif /* MySuiteA_rsa_h */
2.296875
2
2024-11-18T21:50:56.789479+00:00
2023-07-03T01:27:29
90a230490f4c090654470f9b230e169b6d7e73d9
{ "blob_id": "90a230490f4c090654470f9b230e169b6d7e73d9", "branch_name": "refs/heads/master", "committer_date": "2023-07-03T01:27:29", "content_id": "3d0435a2e03e8a953dd2b2a721a6945b2da7e629", "detected_licenses": [ "MIT" ], "directory_id": "382a4dacbf7d6e6da096ddac660ba7a40af350cf", "extension": "c", "filename": "lv_test_label.c", "fork_events_count": 293, "gha_created_at": "2019-08-14T06:17:29", "gha_event_created_at": "2023-08-31T05:18:44", "gha_language": "C", "gha_license_id": "MIT", "github_id": 202286916, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1335, "license": "MIT", "license_type": "permissive", "path": "/src/lvgl/tests/lv_test_widgets/lv_test_label.c", "provenance": "stackv2-0138.json.gz:133167", "repo_name": "Xinyuan-LilyGO/TTGO_TWatch_Library", "revision_date": "2023-07-03T01:27:29", "revision_id": "6a07f3762a4d11c8e5c0c2d6f9340ee4fdaa5fcb", "snapshot_id": "84b1a580ad931caac7407bf110fde5b9248be3c4", "src_encoding": "UTF-8", "star_events_count": 776, "url": "https://raw.githubusercontent.com/Xinyuan-LilyGO/TTGO_TWatch_Library/6a07f3762a4d11c8e5c0c2d6f9340ee4fdaa5fcb/src/lvgl/tests/lv_test_widgets/lv_test_label.c", "visit_date": "2023-08-18T15:36:22.029944" }
stackv2
/** * @file lv_test_label.c * */ /********************* * INCLUDES *********************/ #include "../../lvgl.h" #include "../lv_test_assert.h" #include "lv_test_label.h" #if LV_BUILD_TEST /********************* * DEFINES *********************/ /********************** * TYPEDEFS **********************/ /********************** * STATIC PROTOTYPES **********************/ static void create_copy(void); /********************** * STATIC VARIABLES **********************/ /********************** * MACROS **********************/ /********************** * GLOBAL FUNCTIONS **********************/ void lv_test_label(void) { lv_test_print(""); lv_test_print("==================="); lv_test_print("Start lv_label tests"); lv_test_print("==================="); #if LV_USE_LABEL create_copy(); #else lv_test_print("Skip label test: LV_USE_LABEL == 0"); #endif } /********************** * STATIC FUNCTIONS **********************/ static void create_copy(void) { lv_test_print(""); lv_test_print("Create a label"); lv_test_print("---------------------------"); lv_label_create(lv_scr_act(), NULL); #if LV_COLOR_DEPTH == 32 lv_test_assert_img_eq("lv_test_img32_label_1.png", "Create a label and leave the default settings"); #endif } #endif
2.46875
2
2024-11-18T21:50:56.952536+00:00
2020-06-07T12:52:37
dff72839d730400b770bf156657c0454fb45ef0c
{ "blob_id": "dff72839d730400b770bf156657c0454fb45ef0c", "branch_name": "refs/heads/master", "committer_date": "2020-06-07T12:52:37", "content_id": "99069267d8fbd29a501c9bbcf633085a32d5d0a2", "detected_licenses": [ "MIT", "BSD-3-Clause", "BSD-2-Clause" ], "directory_id": "75f02962b72bdf87fa57f229df731b85e654dd7c", "extension": "c", "filename": "Keyboard.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 168664124, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 8637, "license": "MIT,BSD-3-Clause,BSD-2-Clause", "license_type": "permissive", "path": "/src/Keyboard.c", "provenance": "stackv2-0138.json.gz:133425", "repo_name": "akrinke/scrupp", "revision_date": "2020-06-07T12:52:37", "revision_id": "501d346e4abc9df12e9e49b64097f5d7c63a1237", "snapshot_id": "7ab80c6116d1017a9e3e5c1d51b5d9a41fd351a1", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/akrinke/scrupp/501d346e4abc9df12e9e49b64097f5d7c63a1237/src/Keyboard.c", "visit_date": "2021-07-15T23:37:23.487240" }
stackv2
/* ** $Id$ ** Library to use the keyboard with Scrupp ** See Copyright Notice in COPYRIGHT */ #include "Main.h" #include "Keyboard.h" #include <SDL_keysym.h> #define E(name, val) \ lua_pushliteral(L, name); \ lua_pushinteger(L, val); \ lua_rawset(L, -3); \ lua_pushliteral(L, name); \ lua_rawseti(L, -2, val); static int Lua_Keyboard_enableUnicode(lua_State *L) { SDL_EnableUNICODE(1); return 0; } static int Lua_Keyboard_disableUnicode(lua_State *L) { SDL_EnableUNICODE(0); return 0; } static int Lua_Keyboard_unicodeIsEnabled(lua_State *L) { lua_pushboolean(L, SDL_EnableUNICODE(-1)); return 1; } static int Lua_Keyboard_keyIsDown(lua_State *L) { Uint8 *keystate = SDL_GetKeyState(NULL); Uint16 key; luaL_argcheck(L, lua_tostring(L, -1) != NULL, 1, "string expected"); lua_pushliteral(L, "Scrupp:key_table"); lua_rawget(L, LUA_REGISTRYINDEX); lua_pushvalue(L, -2); lua_rawget(L, -2); luaL_argcheck(L, !lua_isnil(L, -1), 1, "unknown key"); key = (Uint16) lua_tointeger(L, -1); if (key>1000) { key = key - 1000; lua_pushboolean(L, keystate[key] + keystate[key+1]); } else lua_pushboolean(L, keystate[key]); return 1; } static int Lua_Keyboard_setKeyRepeat(lua_State *L) { int delay = luaL_checkint(L, 1); int interval = luaL_checkint(L, 2); SDL_EnableKeyRepeat(delay, interval); return 0; } static const struct luaL_Reg keyboardlib [] = { {"enableUnicode", Lua_Keyboard_enableUnicode}, {"disableUnicode", Lua_Keyboard_disableUnicode}, {"unicodeIsEnabled", Lua_Keyboard_unicodeIsEnabled}, {"keyIsDown", Lua_Keyboard_keyIsDown}, {"setKeyRepeat", Lua_Keyboard_setKeyRepeat}, {NULL, NULL} }; int luaopen_keyboard(lua_State *L, const char *parent) { luaL_register(L, parent, keyboardlib); /* leaves table on top of stack */ /* create a table in the registry containing the mappings from key names to SDLK numbers and vice versa */ lua_newtable(L); /* at first: generate virtual entries for SHIFT, CTRL, ALT, META and SUPER these combine the left and right key this way you can write scrupp.keyIsDown("SHIFT") and test for LSHIFT and RSHIFT */ E("SHIFT", 1000 + SDLK_RSHIFT); E("CTRL", 1000 + SDLK_RCTRL); E("ALT", 1000 + SDLK_RALT); E("META", 1000 + SDLK_RMETA); E("SUPER", 1000 + SDLK_LSUPER); /* this generates table entries for every key in SDL_keysym.h */ E("UNKNOWN", SDLK_UNKNOWN); E("BACKSPACE", SDLK_BACKSPACE); E("TAB", SDLK_TAB); E("CLEAR", SDLK_CLEAR); E("RETURN", SDLK_RETURN); E("PAUSE", SDLK_PAUSE); E("ESCAPE", SDLK_ESCAPE); E("SPACE", SDLK_SPACE); E("!", SDLK_EXCLAIM); E("\"", SDLK_QUOTEDBL); E("#", SDLK_HASH); E("$", SDLK_DOLLAR); E("&", SDLK_AMPERSAND); E("'", SDLK_QUOTE); E("(", SDLK_LEFTPAREN); E(")", SDLK_RIGHTPAREN); E("*", SDLK_ASTERISK); E("+", SDLK_PLUS); E(",", SDLK_COMMA); E("-", SDLK_MINUS); E(".", SDLK_PERIOD); E("/", SDLK_SLASH); E("0", SDLK_0); E("1", SDLK_1); E("2", SDLK_2); E("3", SDLK_3); E("4", SDLK_4); E("5", SDLK_5); E("6", SDLK_6); E("7", SDLK_7); E("8", SDLK_8); E("9", SDLK_9); E(":", SDLK_COLON); E(";", SDLK_SEMICOLON); E("<", SDLK_LESS); E("=", SDLK_EQUALS); E(">", SDLK_GREATER); E("?", SDLK_QUESTION); E("@", SDLK_AT); /* Skip uppercase letters */ E("[", SDLK_LEFTBRACKET); E("\\", SDLK_BACKSLASH); E("]", SDLK_RIGHTBRACKET); E("^", SDLK_CARET); E("_", SDLK_UNDERSCORE); E("`", SDLK_BACKQUOTE); E("a", SDLK_a); E("b", SDLK_b); E("c", SDLK_c); E("d", SDLK_d); E("e", SDLK_e); E("f", SDLK_f); E("g", SDLK_g); E("h", SDLK_h); E("i", SDLK_i); E("j", SDLK_j); E("k", SDLK_k); E("l", SDLK_l); E("m", SDLK_m); E("n", SDLK_n); E("o", SDLK_o); E("p", SDLK_p); E("q", SDLK_q); E("r", SDLK_r); E("s", SDLK_s); E("t", SDLK_t); E("u", SDLK_u); E("v", SDLK_v); E("w", SDLK_w); E("x", SDLK_x); E("y", SDLK_y); E("z", SDLK_z); E("DELETE", SDLK_DELETE); /* End of ASCII mapped keysyms */ /* International keyboard syms */ E("WORLD_0", SDLK_WORLD_0); E("WORLD_1", SDLK_WORLD_1); E("WORLD_2", SDLK_WORLD_2); E("WORLD_3", SDLK_WORLD_3); E("WORLD_4", SDLK_WORLD_4); E("WORLD_5", SDLK_WORLD_5); E("WORLD_6", SDLK_WORLD_6); E("WORLD_7", SDLK_WORLD_7); E("WORLD_8", SDLK_WORLD_8); E("WORLD_9", SDLK_WORLD_9); E("WORLD_10", SDLK_WORLD_10); E("WORLD_11", SDLK_WORLD_11); E("WORLD_12", SDLK_WORLD_12); E("WORLD_13", SDLK_WORLD_13); E("WORLD_14", SDLK_WORLD_14); E("WORLD_15", SDLK_WORLD_15); E("WORLD_16", SDLK_WORLD_16); E("WORLD_17", SDLK_WORLD_17); E("WORLD_18", SDLK_WORLD_18); E("WORLD_19", SDLK_WORLD_19); E("WORLD_20", SDLK_WORLD_20); E("WORLD_21", SDLK_WORLD_21); E("WORLD_22", SDLK_WORLD_22); E("WORLD_23", SDLK_WORLD_23); E("WORLD_24", SDLK_WORLD_24); E("WORLD_25", SDLK_WORLD_25); E("WORLD_26", SDLK_WORLD_26); E("WORLD_27", SDLK_WORLD_27); E("WORLD_28", SDLK_WORLD_28); E("WORLD_29", SDLK_WORLD_29); E("WORLD_30", SDLK_WORLD_30); E("WORLD_31", SDLK_WORLD_31); E("WORLD_32", SDLK_WORLD_32); E("WORLD_33", SDLK_WORLD_33); E("WORLD_34", SDLK_WORLD_34); E("WORLD_35", SDLK_WORLD_35); E("WORLD_36", SDLK_WORLD_36); E("WORLD_37", SDLK_WORLD_37); E("WORLD_38", SDLK_WORLD_38); E("WORLD_39", SDLK_WORLD_39); E("WORLD_40", SDLK_WORLD_40); E("WORLD_41", SDLK_WORLD_41); E("WORLD_42", SDLK_WORLD_42); E("WORLD_43", SDLK_WORLD_43); E("WORLD_44", SDLK_WORLD_44); E("WORLD_45", SDLK_WORLD_45); E("WORLD_46", SDLK_WORLD_46); E("WORLD_47", SDLK_WORLD_47); E("WORLD_48", SDLK_WORLD_48); E("WORLD_49", SDLK_WORLD_49); E("WORLD_50", SDLK_WORLD_50); E("WORLD_51", SDLK_WORLD_51); E("WORLD_52", SDLK_WORLD_52); E("WORLD_53", SDLK_WORLD_53); E("WORLD_54", SDLK_WORLD_54); E("WORLD_55", SDLK_WORLD_55); E("WORLD_56", SDLK_WORLD_56); E("WORLD_57", SDLK_WORLD_57); E("WORLD_58", SDLK_WORLD_58); E("WORLD_59", SDLK_WORLD_59); E("WORLD_60", SDLK_WORLD_60); E("WORLD_61", SDLK_WORLD_61); E("WORLD_62", SDLK_WORLD_62); E("WORLD_63", SDLK_WORLD_63); E("WORLD_64", SDLK_WORLD_64); E("WORLD_65", SDLK_WORLD_65); E("WORLD_66", SDLK_WORLD_66); E("WORLD_67", SDLK_WORLD_67); E("WORLD_68", SDLK_WORLD_68); E("WORLD_69", SDLK_WORLD_69); E("WORLD_70", SDLK_WORLD_70); E("WORLD_71", SDLK_WORLD_71); E("WORLD_72", SDLK_WORLD_72); E("WORLD_73", SDLK_WORLD_73); E("WORLD_74", SDLK_WORLD_74); E("WORLD_75", SDLK_WORLD_75); E("WORLD_76", SDLK_WORLD_76); E("WORLD_77", SDLK_WORLD_77); E("WORLD_78", SDLK_WORLD_78); E("WORLD_79", SDLK_WORLD_79); E("WORLD_80", SDLK_WORLD_80); E("WORLD_81", SDLK_WORLD_81); E("WORLD_82", SDLK_WORLD_82); E("WORLD_83", SDLK_WORLD_83); E("WORLD_84", SDLK_WORLD_84); E("WORLD_85", SDLK_WORLD_85); E("WORLD_86", SDLK_WORLD_86); E("WORLD_87", SDLK_WORLD_87); E("WORLD_88", SDLK_WORLD_88); E("WORLD_89", SDLK_WORLD_89); E("WORLD_90", SDLK_WORLD_90); E("WORLD_91", SDLK_WORLD_91); E("WORLD_92", SDLK_WORLD_92); E("WORLD_93", SDLK_WORLD_93); E("WORLD_94", SDLK_WORLD_94); E("WORLD_95", SDLK_WORLD_95); /* Numeric keypad */ E("KP0", SDLK_KP0); E("KP1", SDLK_KP1); E("KP2", SDLK_KP2); E("KP3", SDLK_KP3); E("KP4", SDLK_KP4); E("KP5", SDLK_KP5); E("KP6", SDLK_KP6); E("KP7", SDLK_KP7); E("KP8", SDLK_KP8); E("KP9", SDLK_KP9); E("KP_PERIOD", SDLK_KP_PERIOD); E("KP_DIVIDE", SDLK_KP_DIVIDE); E("KP_MULTIPLY", SDLK_KP_MULTIPLY); E("KP_MINUS", SDLK_KP_MINUS); E("KP_PLUS", SDLK_KP_PLUS); E("KP_ENTER", SDLK_KP_ENTER); E("KP_EQUALS", SDLK_KP_EQUALS); /* Arrows + Home/End pad */ E("UP", SDLK_UP); E("DOWN", SDLK_DOWN); E("RIGHT", SDLK_RIGHT); E("LEFT", SDLK_LEFT); E("INSERT", SDLK_INSERT); E("HOME", SDLK_HOME); E("END", SDLK_END); E("PAGEUP", SDLK_PAGEUP); E("PAGEDOWN", SDLK_PAGEDOWN); /* Function keys */ E("F1", SDLK_F1); E("F2", SDLK_F2); E("F3", SDLK_F3); E("F4", SDLK_F4); E("F5", SDLK_F5); E("F6", SDLK_F6); E("F7", SDLK_F7); E("F8", SDLK_F8); E("F9", SDLK_F9); E("F10", SDLK_F10); E("F11", SDLK_F11); E("F12", SDLK_F12); E("F13", SDLK_F13); E("F14", SDLK_F14); E("F15", SDLK_F15); /* Key state modifier keys */ E("NUMLOCK", SDLK_NUMLOCK); E("CAPSLOCK", SDLK_CAPSLOCK); E("SCROLLOCK", SDLK_SCROLLOCK); E("RSHIFT", SDLK_RSHIFT); E("LSHIFT", SDLK_LSHIFT); E("RCTRL", SDLK_RCTRL); E("LCTRL", SDLK_LCTRL); E("RALT", SDLK_RALT); E("LALT", SDLK_LALT); E("RMETA", SDLK_RMETA); E("LMETA", SDLK_LMETA); E("LSUPER", SDLK_LSUPER); E("RSUPER", SDLK_RSUPER); E("MODE", SDLK_MODE); E("COMPOSE", SDLK_COMPOSE); /* Miscellaneous function keys */ E("HELP", SDLK_HELP); E("PRINT", SDLK_PRINT); E("SYSREQ", SDLK_SYSREQ); E("BREAK", SDLK_BREAK); E("MENU", SDLK_MENU); E("POWER", SDLK_POWER); E("EURO", SDLK_EURO); E("UNDO", SDLK_UNDO); lua_setfield(L, LUA_REGISTRYINDEX, "Scrupp:key_table"); return 1; }
2.28125
2
2024-11-18T21:50:57.710666+00:00
2021-09-14T01:06:12
cd9a97ce7039307972245c0f4b6bdbde4f0f4a37
{ "blob_id": "cd9a97ce7039307972245c0f4b6bdbde4f0f4a37", "branch_name": "refs/heads/main", "committer_date": "2021-09-14T01:06:12", "content_id": "7bd975786fbe80aaed643fdb343a99eeacbeddef", "detected_licenses": [ "MIT" ], "directory_id": "a68ba3fc0eb86b0ea1fa21152ba253eeee06b63e", "extension": "c", "filename": "Ex6Lista3ES.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 406155520, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2080, "license": "MIT", "license_type": "permissive", "path": "/Sequencial Structures/Lista 3 (2)/Ex6Lista3ES.c", "provenance": "stackv2-0138.json.gz:133812", "repo_name": "whoiswelliton/Programming_Fundamentals", "revision_date": "2021-09-14T01:06:12", "revision_id": "63d41e0d14b67cc64d38b0188b583dd8f8ac2905", "snapshot_id": "68e458ce5b1c36f24e82a09085445763be8aa322", "src_encoding": "ISO-8859-2", "star_events_count": 0, "url": "https://raw.githubusercontent.com/whoiswelliton/Programming_Fundamentals/63d41e0d14b67cc64d38b0188b583dd8f8ac2905/Sequencial Structures/Lista 3 (2)/Ex6Lista3ES.c", "visit_date": "2023-09-05T00:55:52.418712" }
stackv2
#include <stdio.h> #include <stdlib.h> /* Suponha que um caixa disponha apenas de cédulas de R$ 100, 10 e 1. Escreva um programa para ler o valor de uma conta e o valor fornecido pelo usuário para pagar essa conta, e calcule e troco. Calcular e mostrar a quantidade de cada tipo de cédula que o caixa deve fornecer como troco. Mostrar, também o valor da compra e do troco. */ int main (void) { char Continuar; float Ced1,Ced2,Ced3,Conta,Troco,Pago; do { system("cls"); printf("\n________________________________________________________________________________\n"); printf("Informe o Valor total da Conta: "); scanf("%f",&Conta); printf("\n________________________________________________________________________________\n"); printf("Informe o Quanto vai ser pago: "); scanf("%f",&Pago); system("cls"); Troco = Pago - Conta; if(Troco < 0) { printf("\n Conta Paga Parcialmente,SEM TROCO!"); printf("\n________________________________________________________________________________\n"); printf("\n Ainda Deve %.2f",Troco*-1); } else { Ced1= (int)Troco/100; Ced2= (int)Troco%100/10; Ced3= (int)Troco%10; printf("\n\nSeu troco %c: R$ %.2f",130,Troco); printf("\n\nTroco ="); if(Ced1 > 0) { printf("\n\n%.0f Notas de 100",Ced1); } if(Ced2 > 0) { printf("\n%.0f Notas de 10",Ced2); } if(Ced3 > 0) { printf("\n%.0f Notas de 1",Ced3); } } printf("\n_______________________________________________________________________________\n\n"); printf("\n Executar Novamente (S/s para Sim): "); fflush(stdin); scanf("%c",&Continuar); }while(Continuar == 's' || Continuar == 'S'); }
3.59375
4
2024-11-18T21:50:58.132564+00:00
2015-01-06T16:55:14
48a3ee2502cf341c8ae51a2d2234d6f406c1319b
{ "blob_id": "48a3ee2502cf341c8ae51a2d2234d6f406c1319b", "branch_name": "refs/heads/master", "committer_date": "2015-01-06T16:55:14", "content_id": "a9eb0b3729a3bc0cbf2ee68c96443fb29c3ee0cb", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "09ef8d57e6a8beea151c38b4ca32d8e7e49cde25", "extension": "h", "filename": "DDEXEC.H", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 28873033, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3517, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/DDEXEC.H", "provenance": "stackv2-0138.json.gz:134591", "repo_name": "OS2World/DEV-UTIL-DD", "revision_date": "2015-01-06T16:55:14", "revision_id": "f8e2c95ab418a06d1eccec180e8372689b5cb4d3", "snapshot_id": "24dc7d4f9f3ed7529a0c110a2567968f05697d77", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/OS2World/DEV-UTIL-DD/f8e2c95ab418a06d1eccec180e8372689b5cb4d3/DDEXEC.H", "visit_date": "2020-08-25T04:15:17.618873" }
stackv2
#define MSGSIZE 1024 #define MAXPATH 256 #define EXEC_NORMAL 0x00000000 #define EXEC_TRACED 0X00000001 #define EXEC_DETACHED 0X00000002 #define EXEC_RELATED 0X00000004 #define EXEC_FULLSCR 0X00000008 #define EXEC_FOREGRD 0x00000010 #define EXEC_TERMQ 0x00000020 #define EXEC_INHERIT 0x00000040 #define EXEC_REDIR 0x00000080 #define EXEC_RESTART 0x00000100 #define EXEC_WAIT 0x00000200 #define EXEC_DDT 0x80000000 #define EXEC_VERBOSE 0X40000000 #define EXEC_SILENT 0x20000000 #define SIZE_PIPE 512 typedef struct _DDEXEC { ULONG hQueue; PSZ pszDDD; ULONG ahPipe [12]; } DDEXEC; typedef DDEXEC * PDDEXEC; #define hPipeStdin DDExec.ahPipe[0] #define hPipeStdout DDExec.ahPipe[1] #define hPipeStderr DDExec.ahPipe[2] #define hStdin DDExec.ahPipe[3] #define hStdout DDExec.ahPipe[4] #define hStderr DDExec.ahPipe[5] #define hPipe1Read DDExec.ahPipe[6] #define hPipe1Write DDExec.ahPipe[7] #define hPipe2Read DDExec.ahPipe[8] #define hPipe2Write DDExec.ahPipe[9] #define hPipe3Read DDExec.ahPipe[10] #define hPipe3Write DDExec.ahPipe[11] #define phPipeStdin pDDExec->ahPipe[0] #define phPipeStdout pDDExec->ahPipe[1] #define phPipeStderr pDDExec->ahPipe[2] #define phStdin pDDExec->ahPipe[3] #define phStdout pDDExec->ahPipe[4] #define phStderr pDDExec->ahPipe[5] #define phPipe1Read pDDExec->ahPipe[6] #define phPipe1Write pDDExec->ahPipe[7] #define phPipe2Read pDDExec->ahPipe[8] #define phPipe2Write pDDExec->ahPipe[9] #define phPipe3Read pDDExec->ahPipe[10] #define phPipe3Write pDDExec->ahPipe[11] APIRET ExecPgmTitle(PCHAR PgmTitle, PCHAR PgmPathExe, PCHAR PgmParms, PPID pPid, PULONG pSel, PPID pTid, USHORT fHow); APIRET ddExec(PSZ pszTitle, PSZ pszExe, PSZ pszArgs, PPID pPid, PTID pTid, PDDEXEC pDDExec, ULONG lFlags); // Specifications on EXEC_REDIR // When specifying EXEC_REDIR two HFILEs are returned on the PgmTitle pointer // being the pipe to read the output from the started program (stdout & stderr) // and the pipe to write input to the program (stdin) // It is necessary to provide a PgmTitle with at least a strlen of 3 for // ExecPgmTitle to return the pipes (rc ERROR_MON_BUFFER_TOO_SMALL is returned // otherwise) // Since PgmTitle get's overwritten by the call, be sure not to pass a // global or static variable as the title (it will not be the same on return) // Use temp storage on the stack and copy the static/global string to this // variable. This way the PgmTitle will be reusable // EXEC_REDIR uses an intermediary CMD.EXE to provide redirection from stdin, // stdout and stderr. When you have more than 5 files open on the time // off the call the function cannot perform redirection and returns // ERROR_TOO_MANY_OPEN_FILES (see IBM OS/2 Extended Edition Version 1.2 // User Guide Volume 1: Base Operating System p.9-3) // EXEC_REDIR is compatible with EXEC_DETACHED and EXEC_TERMQ (tested) // and should work (not tested) with all other flags except of course EXEC_WAIT // The pipes will still be open even when the program dies, so it is necessary // to check when a program has dies. This is done by EXEC_TERMQ and DosReadQueue // when not specifying EXEC_DETACH, when EXEC_DETACHing the programmer needs // to DosCWait the EXEC_DETACHed pid. // see example redir.c at U:\KB\PTRACE // Note, when EXEC_REDIRing a C-program it's advisable to setbuf(stdout), NULL) // to prevent the C-runtime library from buffering the stdout-handle
2.109375
2
2024-11-18T21:50:58.488198+00:00
2020-03-25T18:03:26
f7dfb7939b6acfc7c670d7eeb9922c745e13704b
{ "blob_id": "f7dfb7939b6acfc7c670d7eeb9922c745e13704b", "branch_name": "refs/heads/master", "committer_date": "2020-03-25T18:03:26", "content_id": "063038b2eda0f7756bc06b86273a91ad65d999f4", "detected_licenses": [ "Apache-2.0" ], "directory_id": "a069fd4318106128316b689f2a64e8508b1191b5", "extension": "c", "filename": "EMG_prog.c", "fork_events_count": 0, "gha_created_at": "2019-08-02T20:50:00", "gha_event_created_at": "2020-03-25T18:03:28", "gha_language": null, "gha_license_id": "Apache-2.0", "github_id": 200296281, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2792, "license": "Apache-2.0", "license_type": "permissive", "path": "/EMG_prog.c", "provenance": "stackv2-0138.json.gz:134852", "repo_name": "abdosamer/graduation-project", "revision_date": "2020-03-25T18:03:26", "revision_id": "8955f20136eeb3392b8d22ae47f33d60920e562c", "snapshot_id": "6c53ff38aaaba3935bd3b6ed5364f63eb79595c0", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/abdosamer/graduation-project/8955f20136eeb3392b8d22ae47f33d60920e562c/EMG_prog.c", "visit_date": "2020-06-28T17:26:08.218367" }
stackv2
/****************************************************/ /* */ /* Author : Hassan Askar */ /* Date : 08/04/2019 */ /* Version : 1.0 V */ /* Description : EMG_Program */ /* */ /****************************************************/ /****************************************************************/ /*********************** STD LIB DIRECTIVES *********************/ /****************************************************************/ #include "STD_Types.h" #include "Bit_Math.h" #include "LBTY_int.h" /****************************************************************/ /*********************** Component DIRECTIVES *******************/ /****************************************************************/ #include "ADC_int.h" #include "TIM0_int.h" #include "USART_init.h" #include "EMG_config.h" #include "EMG_init.h" #include "EMG_private.h" /****************************************************************/ /*********************** Function Implementation ***************/ /****************************************************************/ /****************************************************************/ /* Description : This function used to initialize EMG */ /* Inputs : void */ /* return : void */ /****************************************************************/ u16 r; u8 *str , *s=" mV\n"; void EMG_voidInit(void) { ADC_voidInit(EMG_CHANNEL_NUMBER); ADC_voidEnable(); TIM0_init(); TIM0_enableOverflowinterrupt(); TIM0_SetTCNT0(124); } /****************************************************************/ /* Description : This function used to calc EMG & */ /* transmit the result */ /* Inputs : void */ /* Return : vois */ /****************************************************************/ /* Pre_condition : this function must be used after EMG */ /* initialized */ /****************************************************************/ void EMG_TIM0_SetCallBackOvf(pf address_cpy) { TIM0_SetCallBackOvf(address_cpy); } void EMG_voidCalcAndTransmit() { TIM0_SetTCNT0(100); r=(( ADC_u16ReadADC() * (5 / 1023))*1000); USART_TransmitString(itoa(r,str,10)); USART_TransmitString(s); } /***********************************************************************************************/ /************************************* END OF PROGRAM ******************************************/ /***********************************************************************************************/
2.203125
2
2024-11-18T21:50:59.154485+00:00
2017-02-17T12:14:53
bd8d1c402a59de0b609382afdc3da6605f16190e
{ "blob_id": "bd8d1c402a59de0b609382afdc3da6605f16190e", "branch_name": "refs/heads/master", "committer_date": "2017-02-17T12:14:53", "content_id": "f94b920f223fdf7d7c0690689ce294020748a9b4", "detected_licenses": [ "Unlicense" ], "directory_id": "317f727d5c57072c1b1a673f0b212c2cfcd0a7e7", "extension": "c", "filename": "main.c", "fork_events_count": 3, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 43809441, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 6066, "license": "Unlicense", "license_type": "permissive", "path": "/3if/alg/td-alg_4/src/main.c", "provenance": "stackv2-0138.json.gz:135111", "repo_name": "Lyrositor/insa", "revision_date": "2017-02-17T12:14:53", "revision_id": "71c8d8993881157f935769ad0290d6e1bd1626dd", "snapshot_id": "4fe7ecfa6007d0819f4ea49dcd4ac70e87e04e79", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/Lyrositor/insa/71c8d8993881157f935769ad0290d6e1bd1626dd/3if/alg/td-alg_4/src/main.c", "visit_date": "2021-01-17T15:15:29.889065" }
stackv2
#include <stdio.h> #include <string.h> #include <stdlib.h> typedef struct ht_table ht_table; typedef struct ht_cell ht_cell; typedef enum ht_cell_status ht_cell_status; ht_table * ht_init(int size); void ht_insert(ht_table * hash_table, char key[100], char value[100]); void ht_delete(ht_table * hash_table, char key[100]); ht_cell * ht_query(ht_table * hash_table, char key[100]); void ht_stats(ht_table * hash_table); void ht_destroy(ht_table * hash_table); unsigned int shift_rotate(unsigned int val, unsigned int n); unsigned int hash(char chaine[100], int m); void error(void); struct ht_table { int size; ht_cell * cells; }; enum ht_cell_status { EMPTY, USED, DELETED }; struct ht_cell { ht_cell_status status; char key[100]; char value[100]; }; int main(void) { int size; char lecture[100]; char key[100]; char val[100]; ht_table * hash_table; if (fscanf(stdin, "%99s", lecture) != 1) error(); while (strcmp(lecture, "bye") != 0) { if (strcmp(lecture, "init") == 0) { if (fscanf(stdin, "%99s", lecture) != 1) error(); size = atoi(lecture); hash_table = ht_init(size); } else if (strcmp(lecture, "insert") == 0) { if (fscanf(stdin, "%99s", lecture) != 1) error(); strcpy(key, lecture); if (fscanf(stdin, "%99s", lecture) != 1) error(); strcpy(val, lecture); ht_insert(hash_table, key, val); } else if (strcmp(lecture, "delete") == 0) { if (fscanf(stdin, "%99s", lecture) != 1) error(); strcpy(key, lecture); ht_delete(hash_table, key); } else if (strcmp(lecture, "query") == 0) { if (fscanf(stdin, "%99s", lecture) != 1) error(); strcpy(key, lecture); ht_cell * q = ht_query(hash_table, key); if (q == NULL || q->status == DELETED) { printf("Not found\r\n"); } else { printf("%s\r\n", q->value); } } else if (strcmp(lecture, "destroy") == 0) { ht_destroy(hash_table); } else if (strcmp(lecture, "stats") == 0) { ht_stats(hash_table); } if (fscanf(stdin, "%99s", lecture) != 1) error(); } return 0; } ht_table * ht_init(int size) { int i; ht_table * hash_table = malloc(sizeof(ht_table)); hash_table->size = size; hash_table->cells = (ht_cell *) malloc(size*sizeof(ht_cell)); for (i = 0; i < size; i++) { hash_table->cells[i].status = EMPTY; } return hash_table; } void ht_insert(ht_table * hash_table, char key[100], char value[100]) { unsigned int h_key = hash(key, hash_table->size); unsigned int i = h_key; ht_cell * q = ht_query(hash_table, key); for (;;) { if (hash_table->cells[i].status == EMPTY) { hash_table->cells[i].status = USED; strcpy(hash_table->cells[i].key, key); strcpy(hash_table->cells[i].value, value); break; } else if (hash_table->cells[i].status == USED && strcmp(hash_table->cells[i].key, key) == 0) { strcpy(hash_table->cells[i].value, value); break; } else if (hash_table->cells[i].status == DELETED) { if (q != NULL && (q->status == USED || q->status == DELETED)) { q->status = USED; strcpy(q->key, key); strcpy(q->value, value); break; } else { hash_table->cells[i].status = USED; strcpy(hash_table->cells[i].key, key); strcpy(hash_table->cells[i].value, value); break; } } i = (i + 1) % hash_table->size; if (i == h_key) { break; } } } void ht_delete(ht_table * hash_table, char key[100]) { ht_cell * q = ht_query(hash_table, key); if (q != NULL) { q->status = DELETED; } } ht_cell * ht_query(ht_table * hash_table, char key[100]) { unsigned int h_key = hash(key, hash_table->size); unsigned int i = h_key; for (;;) { if ((hash_table->cells[i].status == USED || hash_table->cells[i].status == DELETED) && strcmp(hash_table->cells[i].key, key) == 0) { return &hash_table->cells[i]; } i = (i + 1) % hash_table->size; if (i == h_key) { return NULL; } } } void ht_stats(ht_table * hash_table) { int empty = 0, deleted = 0, used = 0; int i; for (i = 0; i < hash_table->size; i++) { if (hash_table->cells[i].status == EMPTY) { empty++; } else if (hash_table->cells[i].status == USED) { used++; } else { deleted++; } } printf("size : %d\r\n", hash_table->size); printf("empty : %d\r\n", empty); printf("deleted : %d\r\n", deleted); printf("used : %d\r\n", used); } void ht_destroy(ht_table * hash_table) { free(hash_table->cells); free(hash_table); } /* encodage d'une chaine de caracteres sous la forme d'un entier non signe */ unsigned int shift_rotate(unsigned int val, unsigned int n) { n = n % (sizeof(unsigned int)*8); return (val << n) | (val >> (sizeof(unsigned int)*8 - n)); } /* fonction de hachage d'une chaine de caracteres */ unsigned int hash(char chaine[100], int m) { int i; unsigned int h = 0; for (i = 0; i < strlen(chaine); i++) { h = h + shift_rotate(chaine[i], i*7); } return h % m; } void error(void) { printf("input error\r\n"); exit(0); }
3.046875
3
2024-11-18T21:50:59.541267+00:00
2023-07-05T12:19:20
41aa21be6114741f33517237d9fb9a874b15e1e1
{ "blob_id": "41aa21be6114741f33517237d9fb9a874b15e1e1", "branch_name": "refs/heads/master", "committer_date": "2023-07-05T12:19:20", "content_id": "99f61eca3a87fbbe5cb23001192a160728db5e09", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "b71097386a6da0e3ca65f19a1906f0ebe11eac18", "extension": "c", "filename": "dtcore-strp.c", "fork_events_count": 44, "gha_created_at": "2011-09-07T11:19:46", "gha_event_created_at": "2023-06-26T12:04:46", "gha_language": "C", "gha_license_id": "NOASSERTION", "github_id": 2341061, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5037, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/test/dtcore-strp.c", "provenance": "stackv2-0138.json.gz:135240", "repo_name": "hroptatyr/dateutils", "revision_date": "2023-07-05T12:19:20", "revision_id": "c57828809a018061147bc806a058aa4c4b9c449a", "snapshot_id": "0584063e4a35c511ad3600c27efb2f4214af24c6", "src_encoding": "UTF-8", "star_events_count": 517, "url": "https://raw.githubusercontent.com/hroptatyr/dateutils/c57828809a018061147bc806a058aa4c4b9c449a/test/dtcore-strp.c", "visit_date": "2023-09-05T20:26:30.356886" }
stackv2
#if defined HAVE_CONFIG_H # include "config.h" #endif /* HAVE_CONFIG_H */ #include <stdio.h> #include <stdint.h> #include <inttypes.h> #include "dt-core.h" #define CHECK_RES(rc, pred, args...) \ if (pred) { \ fprintf(stderr, args); \ res = rc; \ } #define CHECK(pred, args...) \ CHECK_RES(1, pred, args) static int test_d_only_no_fmt(void) { static const char str[] = "2012-03-28"; struct dt_dt_s d; int res = 0; /* 2012-03-28 (using no format) */ fprintf(stderr, "testing %s ...\n", str); d = dt_strpdt(str, NULL, NULL); CHECK(d.sandwich, " IS A SANDWICH ... but should be not\n"); CHECK(!dt_sandwich_only_d_p(d), " TYPE is not a d-only\n"); CHECK(d.d.typ != DT_YMD, " TYPE DIFFERS %u ... should be %u\n", (unsigned int)d.d.typ, (unsigned int)DT_YMD); CHECK(d.t.u, " TIME COMPONENT NOT NAUGHT %" PRIu64 "\n", (uint64_t)d.t.u); CHECK(d.xxx, " FORMER DURATION BIT SET\n"); CHECK(d.neg, " NEGATED BIT SET\n"); CHECK(d.t.dur, " TIME DURATION BIT SET\n"); CHECK(d.t.neg, " TIME NEGATED BIT SET\n"); CHECK(d.d.ymd.y != 2012, " YEAR %u ... should be 2012\n", (unsigned int)d.d.ymd.y); CHECK(d.d.ymd.m != 3, " MONTH %u ... should be 3\n", (unsigned int)d.d.ymd.m); CHECK(d.d.ymd.d != 28, " DAY %u ... should be 28\n", (unsigned int)d.d.ymd.d); /* make sure the padding leaves no garbage, not fatal tho */ CHECK_RES(res, d.d.ymd.u & ~0x1fffff, " PADDING NOT NAUGHT %x\n", (unsigned int)(d.d.ymd.u & ~0x1fffff)); return res; } static int test_t_only_no_fmt(void) { static const char str[] = "12:34:56"; struct dt_dt_s d; int res = 0; /* 12:34:56 (using no format) */ fprintf(stderr, "testing %s ...\n", str); d = dt_strpdt(str, NULL, NULL); CHECK(!d.sandwich, " NOT A SANDWICH ... but should be\n"); CHECK(!dt_sandwich_only_t_p(d), " TYPE is not a t-only\n"); CHECK(d.typ != DT_SANDWICH_UNK, " TYPE DIFFERS %u ... should be %u\n", (unsigned int)d.typ, (unsigned int)DT_SANDWICH_UNK); CHECK(d.t.typ != DT_HMS, " TIME TYPE DIFFERS %u ... should be %u\n", (unsigned int)d.t.typ, (unsigned int)DT_HMS); CHECK(d.d.u, " DATE COMPONENT NOT NAUGHT %" PRIu64 "\n", (uint64_t)d.d.u); CHECK(d.xxx, " FORMER DURATION BIT SET\n"); CHECK(d.neg, " NEGATED BIT SET\n"); CHECK(d.t.dur, " TIME DURATION BIT SET\n"); CHECK(d.t.neg, " TIME DURATION BIT SET\n"); CHECK(d.t.hms.h != 12, " HOUR %u ... should be 12\n", (unsigned int)d.t.hms.h); CHECK(d.t.hms.m != 34, " MINUTE %u ... should be 34\n", (unsigned int)d.t.hms.m); CHECK(d.t.hms.s != 56, " SECOND %u ... should be 56\n", (unsigned int)d.t.hms.s); CHECK(d.t.hms.ns != 0, " NANOSECOND %u ... should be 0\n", (unsigned int)d.t.hms.ns); /* make sure the padding leaves no garbage */ CHECK_RES(res, d.t.hms.u & ~0x1f3f3f3fffffff, " PADDING NOT NAUGHT %x\n", (unsigned int)(d.t.hms.u & ~0x1f3f3f3fffffff)); return res; } static int test_dt_no_fmt(void) { static const char str[] = "2012-03-28 12:34:56"; struct dt_dt_s d; int res = 0; fprintf(stderr, "testing %s ...\n", str); d = dt_strpdt(str, NULL, NULL); CHECK(!d.sandwich, " NOT A SANDWICH ... but should be\n"); CHECK(!dt_sandwich_p(d), " TYPE is not a sandwich\n"); CHECK(d.d.typ != DT_YMD, " TYPE DIFFERS %u ... should be %u\n", (unsigned int)d.d.typ, (unsigned int)DT_YMD); CHECK(d.t.typ != DT_HMS, " TIME TYPE DIFFERS %u ... should be %u\n", (unsigned int)d.t.typ, (unsigned int)DT_HMS); CHECK(d.xxx, " FORMER DURATION BIT SET\n"); CHECK(d.neg, " NEGATED BIT SET\n"); CHECK(d.t.dur, " TIME DURATION BIT SET\n"); CHECK(d.t.neg, " TIME DURATION BIT SET\n"); CHECK(d.d.ymd.y != 2012, " YEAR %u ... should be 2012\n", (unsigned int)d.d.ymd.y); CHECK(d.d.ymd.m != 3, " MONTH %u ... should be 3\n", (unsigned int)d.d.ymd.m); CHECK(d.d.ymd.d != 28, " DAY %u ... should be 28\n", (unsigned int)d.d.ymd.d); CHECK(d.t.hms.h != 12, " HOUR %u ... should be 12\n", (unsigned int)d.t.hms.h); CHECK(d.t.hms.m != 34, " MINUTE %u ... should be 34\n", (unsigned int)d.t.hms.m); CHECK(d.t.hms.s != 56, " SECOND %u ... should be 56\n", (unsigned int)d.t.hms.s); CHECK(d.t.hms.ns != 0, " NANOSECOND %u ... should be 0\n", (unsigned int)d.t.hms.ns); /* make sure the padding leaves no garbage */ CHECK_RES(res, d.d.ymd.u & ~0x1fffff, " PADDING NOT NAUGHT %x\n", (unsigned int)(d.d.ymd.u & ~0x1fffff)); CHECK_RES(res, d.t.hms.u & ~0x1f3f3f3fffffff, " PADDING NOT NAUGHT %x\n", (unsigned int)(d.t.hms.u & ~0x1f3f3f3fffffff)); return res; } int main(void) { int res = 0; if (test_d_only_no_fmt() != 0) { res = 1; } if (test_t_only_no_fmt() != 0) { res = 1; } if (test_dt_no_fmt() != 0) { res = 1; } return res; } /* dtcore-strpd.c ends here */
2.609375
3
2024-11-18T21:51:00.920174+00:00
2016-09-29T20:00:22
e023881a79d4708fcb839224f83bf5526392fd97
{ "blob_id": "e023881a79d4708fcb839224f83bf5526392fd97", "branch_name": "refs/heads/master", "committer_date": "2016-09-29T20:00:22", "content_id": "4c5c908beb2d8250523dee97d9ac9603cafea05c", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "2e76b30ef1c144d449c66c6744addb2249890dad", "extension": "c", "filename": "error_rate.c", "fork_events_count": 0, "gha_created_at": "2016-09-29T04:17:22", "gha_event_created_at": "2016-09-29T04:17:23", "gha_language": null, "gha_license_id": null, "github_id": 69530053, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 699, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/error_rate.c", "provenance": "stackv2-0138.json.gz:135499", "repo_name": "LanKuDot/compute-pi", "revision_date": "2016-09-29T20:00:22", "revision_id": "5737771e205ad189abb07786734d5e7b771ff663", "snapshot_id": "7fe2b4b0008596e554d37ba3ffd6329e1f3c2f9c", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/LanKuDot/compute-pi/5737771e205ad189abb07786734d5e7b771ff663/error_rate.c", "visit_date": "2020-04-11T09:18:44.423029" }
stackv2
/* Run all cases and calculate the error rate */ #include <stdio.h> #include <stdlib.h> #include <math.h> #include "computepi.h" static double error_rate(double sample, double groundTruth) { return ((sample > groundTruth) ? (sample - groundTruth) : (groundTruth - sample)) / groundTruth; } int main(int argc, char *argv[]) { int N = atoi(argv[1]); printf("%.15lf,", error_rate(compute_pi_baseline(N), M_PI)); printf("%.15lf,", error_rate(compute_pi_openmp(N, 2), M_PI)); printf("%.15lf\n", error_rate(compute_pi_openmp(N, 4), M_PI)); // printf("%.15lf,", error_rate(compute_pi_baseline(N), M_PI)); // printf("%.15lf\n", error_rate(compute_pi_baseline(N), M_PI)); }
2.4375
2
2024-11-18T21:51:01.036021+00:00
2021-02-08T13:39:57
a6b5ac25e074df9bcf2aae77f8fedacf6e8bae98
{ "blob_id": "a6b5ac25e074df9bcf2aae77f8fedacf6e8bae98", "branch_name": "refs/heads/master", "committer_date": "2021-02-08T13:39:57", "content_id": "fa276549030f6a23b4c6ec55584ea8ae72c9a75d", "detected_licenses": [ "MIT" ], "directory_id": "c06c9e62f939cc3388c48c09468da02bab772f7e", "extension": "c", "filename": "Digit Frequency.c", "fork_events_count": 3, "gha_created_at": "2020-04-17T13:11:50", "gha_event_created_at": "2020-10-01T22:06:09", "gha_language": "C++", "gha_license_id": "MIT", "github_id": 256506570, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 543, "license": "MIT", "license_type": "permissive", "path": "/C - Hackerrank/Digit Frequency.c", "provenance": "stackv2-0138.json.gz:135628", "repo_name": "sambhav228/Data_Structure_Algorithm", "revision_date": "2021-02-08T13:39:57", "revision_id": "45d7b2603cd9a837bfe7626bfb4abada70f6f4d6", "snapshot_id": "2606da3ba9e34684ed6bd78b5d63bf7a15525211", "src_encoding": "UTF-8", "star_events_count": 3, "url": "https://raw.githubusercontent.com/sambhav228/Data_Structure_Algorithm/45d7b2603cd9a837bfe7626bfb4abada70f6f4d6/C - Hackerrank/Digit Frequency.c", "visit_date": "2023-03-06T08:12:53.648359" }
stackv2
// https://www.hackerrank.com/challenges/frequency-of-digits-1/problem #include <stdio.h> #include <string.h> #include <math.h> #include <stdlib.h> int main() { /* Enter your code here. Read input from STDIN. Print output to STDOUT */ char s[1000]; int arr[10] = {0}; scanf("%s",s); for(int i = 0; i < strlen(s); i ++) { int j = s[i] - 48; if( j >= 0 && j <= 9 ) { arr[j]++; } } for(int i = 0; i < 10; i ++) { printf("%d ", arr[i]); } return 0; }
3.09375
3
2024-11-18T21:51:01.466047+00:00
2021-03-08T05:12:39
1600a5b70839f3f622c0677897b7b4ad976b8ccc
{ "blob_id": "1600a5b70839f3f622c0677897b7b4ad976b8ccc", "branch_name": "refs/heads/master", "committer_date": "2021-03-08T05:12:39", "content_id": "b89b1ba5af067303205b8d548c1e5d593173d2bd", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "21775c243fb7f40b5fa503eddebeb470530d1fbc", "extension": "c", "filename": "json.c", "fork_events_count": 0, "gha_created_at": "2021-03-08T04:58:55", "gha_event_created_at": "2021-03-08T05:01:57", "gha_language": null, "gha_license_id": "BSD-2-Clause", "github_id": 345535579, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 10659, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/lib/json.c", "provenance": "stackv2-0138.json.gz:136148", "repo_name": "sambacha/siphon", "revision_date": "2021-03-08T05:12:39", "revision_id": "45b4625d87bbff029070e8e11cdc4c1aeab5c4fb", "snapshot_id": "a9db989ea8ec0fecc9414ce84ed64f723ab1344d", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/sambacha/siphon/45b4625d87bbff029070e8e11cdc4c1aeab5c4fb/lib/json.c", "visit_date": "2023-03-14T00:18:16.852835" }
stackv2
#include "../include/siphon/json.h" #include "parser.h" #include <assert.h> #include <ctype.h> #include <stdlib.h> static const uint8_t rng_non_ws[] = "\x00\x08\x0b\x0c\x0e\x1f\x21\xff"; #include "stack.h" #define STACK_ARR 0 #define STACK_OBJ 1 #define STACK_PUSH_ARR(p) STACK_PUSH_FALSE(p, SP_JSON_ESTACK) #define STACK_PUSH_OBJ(p) STACK_PUSH_TRUE(p, SP_JSON_ESTACK) #define STACK_IN_ARR(p) (STACK_TOP(p) == STACK_ARR) #define STACK_IN_OBJ(p) (STACK_TOP(p) == STACK_OBJ) #define STACK_POP_ARR(p) STACK_POP(p, STACK_ARR) #define STACK_POP_OBJ(p) STACK_POP(p, STACK_OBJ) #define KIND_MASK 0x00000F #define KIND_ANY 0x000000 #define KIND_KEY 0x000001 #define KIND_STRING 0x000002 #define KIND_NUMBER 0x000003 #define KIND_TRUE 0x000004 #define KIND_FALSE 0x000005 #define KIND_NULL 0x000006 #define ARRAY_MASK 0x0000F0 #define ARRAY_FIRST 0x000010 #define ARRAY_NEXT 0x000020 #define OBJECT_MASK 0x000F00 #define OBJECT_FIRST 0x000100 #define OBJECT_KEY 0x000200 #define OBJECT_SEP 0x000300 #define OBJECT_NEXT 0x000400 #define STACK_CS(p) (STACK_IN_OBJ(p) ? OBJECT_NEXT : ARRAY_NEXT) #define YIELD_CS(p) (p->depth ? STACK_CS(p) : DONE) #define YIELD_STACK(typ) YIELD(typ, YIELD_CS(p)) #define YIELD_IF_POP_ARR() \ do { \ if (pcmp_likely(STACK_POP_ARR(p))) { \ end++; \ p->off++; \ YIELD_STACK(SP_JSON_ARRAY_END); \ } \ } while (0) #define YIELD_IF_POP_OBJ() \ do { \ if (pcmp_likely(STACK_POP_OBJ(p))) { \ end++; \ p->off++; \ YIELD_STACK(SP_JSON_OBJECT_END); \ } \ } while (0) #define SKIP_WHITESPACE(done) \ do { \ end = pcmp_range16(end, len - p->off, rng_non_ws, sizeof rng_non_ws - 1); \ if (pcmp_unlikely(end == NULL)) { \ if (pcmp_unlikely(done)) { \ YIELD_ERROR(SP_JSON_ESYNTAX); \ } \ p->off = 0; \ return len; \ } \ p->off = end - m; \ } while (0) static ssize_t parse_string(SpJson *restrict p, const uint8_t *restrict m, size_t len, bool eof) { // matches escape sequences, ASCII control, quote, or start of UTF-8 sequence #ifdef SP_JSON_STRICT static const uint8_t rng_check[] = SP_UTF8_JSON_RANGE; #else static const uint8_t rng_check[] = "\\\\\x00\x1F\"\"\x7F\x7F"; #endif const uint8_t *start = m + p->mark; const uint8_t *end = m + p->off; ssize_t n; again: EXPECT_RANGE(rng_check, SP_JSON_MAX_STRING, eof, SP_JSON_ESYNTAX, SP_JSON_ESIZE); end = pcmp_range16(end, len - p->off, rng_check, sizeof rng_check - 1); if (end == NULL) { end = m + len; } p->off = end - m; EXPECT_MAX_OFFSET(SP_JSON_MAX_STRING, SP_JSON_ESIZE); n = sp_utf8_add_raw(&p->utf8, start, end - start); if (n < 0) { YIELD_ERROR(n); } start = end; p->mark += n; if (*end == '"') { end++; YIELD(SP_JSON_STRING, p->cs == KIND_KEY ? OBJECT_SEP : YIELD_CS(p)); } n = sp_utf8_json_decode(&p->utf8, end, len - p->off, 0); if (n == SP_UTF8_ETOOSHORT) { if (!eof) { n = (ssize_t)p->off; p->off = 0; p->mark = 0; return n; } n = SP_JSON_EESCAPE; } if (n < 0) { YIELD_ERROR(n); } end += n; start = end; p->off += n; p->mark += n; goto again; } static ssize_t parse_number(SpJson *restrict p, const uint8_t *restrict m, size_t len, bool eof) { // TODO: use better number parser static const uint8_t rng_non_num[] = "\x00\x2a\x2c\x2c\x2f\x2f\x3a\x44\x46\x64\x66\xff"; const uint8_t *end = m + p->off; EXPECT_RANGE(rng_non_num, 511, eof, SP_JSON_ESYNTAX, SP_JSON_ESIZE); size_t n = p->off - p->mark; char buf[512]; memcpy(buf, m + p->mark, n); buf[n] = '\0'; char *e; p->number = strtod(buf, &e); if (*e) { YIELD_ERROR(SP_JSON_ESYNTAX); } YIELD_STACK(SP_JSON_NUMBER); } static size_t parse_true(SpJson *restrict p, const uint8_t *restrict m, size_t len, bool eof) { static const uint8_t pre_true[] = "rue"; const uint8_t *end = m + p->off; EXPECT_PREFIX(pre_true, 0, eof, SP_JSON_ESYNTAX); YIELD_STACK(SP_JSON_TRUE); } static size_t parse_false(SpJson *restrict p, const uint8_t *restrict m, size_t len, bool eof) { static const uint8_t pre_false[] = "alse"; const uint8_t *end = m + p->off; EXPECT_PREFIX(pre_false, 0, eof, SP_JSON_ESYNTAX); YIELD_STACK(SP_JSON_FALSE); } static size_t parse_null(SpJson *restrict p, const uint8_t *restrict m, size_t len, bool eof) { static const uint8_t pre_null[] = "ull"; const uint8_t *end = m + p->off; EXPECT_PREFIX(pre_null, 0, eof, SP_JSON_ESYNTAX); YIELD_STACK(SP_JSON_NULL); } static ssize_t parse_any(SpJson *restrict p, const uint8_t *restrict m, size_t len, bool eof) { const uint8_t *end = m + p->off; SKIP_WHITESPACE(eof); switch (*end) { case '{': STACK_PUSH_OBJ(p); end = m + ++p->off; YIELD(SP_JSON_OBJECT, OBJECT_FIRST); case '[': STACK_PUSH_ARR(p); end = m + ++p->off; YIELD(SP_JSON_ARRAY, ARRAY_FIRST); case '"': sp_utf8_reset(&p->utf8); p->mark = ++p->off; p->cs = KIND_STRING; return parse_string(p, m, len, eof); case '-': case '.': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': p->mark = p->off++; p->cs = KIND_NUMBER; return parse_number(p, m, len, eof); case 't': p->off++; p->cs = KIND_TRUE; return parse_true(p, m, len, eof); case 'f': p->off++; p->cs = KIND_FALSE; return parse_false(p, m, len, eof); case 'n': p->off++; p->cs = KIND_NULL; return parse_null(p, m, len, eof); } YIELD_ERROR(SP_JSON_ESYNTAX); } static ssize_t parse_array(SpJson *restrict p, const uint8_t *restrict m, size_t len, bool eof) { const uint8_t *end = m + p->off; SKIP_WHITESPACE(eof); EXPECT_SIZE(1, eof, SP_JSON_ESYNTAX); switch (p->cs & ARRAY_MASK) { case ARRAY_FIRST: if (*end == ']') { YIELD_IF_POP_ARR(); } else { p->cs = KIND_ANY; return parse_any(p, m, len, eof); } break; case ARRAY_NEXT: switch (*end) { case ']': YIELD_IF_POP_ARR(); break; case ',': p->off++; p->cs = KIND_ANY; return parse_any(p, m, len, eof); } break; } YIELD_ERROR(SP_JSON_ESYNTAX); } static ssize_t parse_object(SpJson *restrict p, const uint8_t *restrict m, size_t len, bool eof) { const uint8_t *end = m + p->off; again: SKIP_WHITESPACE(eof); switch (p->cs & OBJECT_MASK) { case OBJECT_FIRST: EXPECT_SIZE(1, eof, SP_JSON_ESYNTAX); switch (*end) { case '}': YIELD_IF_POP_OBJ(); break; case '"': sp_utf8_reset(&p->utf8); p->mark = ++p->off; p->cs = KIND_KEY; return parse_string(p, m, len, eof); } break; case OBJECT_KEY: EXPECT_CHAR('"', eof, SP_JSON_ESYNTAX); sp_utf8_reset(&p->utf8); p->mark = p->off; p->cs = KIND_KEY; return parse_string(p, m, len, eof); case OBJECT_SEP: EXPECT_CHAR(':', eof, SP_JSON_ESYNTAX); p->cs = KIND_ANY; return parse_any(p, m, len, eof); case OBJECT_NEXT: EXPECT_SIZE(1, eof, SP_JSON_ESYNTAX); switch (*end) { case '}': YIELD_IF_POP_OBJ(); break; case ',': p->off++; end++; p->cs = OBJECT_KEY; goto again; } break; } YIELD_ERROR(SP_JSON_ESYNTAX); } static inline void init_values(SpJson *p) { p->number = 0.0; p->type = SP_JSON_NONE; p->cs = 0; p->off = 0; p->mark = 0; p->depth = 0; } void sp_json_init(SpJson *p) { assert(p != NULL); sp_utf8_init(&p->utf8); init_values(p); } void sp_json_reset(SpJson *p) { assert(p != NULL); sp_utf8_reset(&p->utf8); init_values(p); } void sp_json_final(SpJson *p) { assert(p != NULL); sp_utf8_final(&p->utf8); } ssize_t sp_json_next(SpJson *p, const void *restrict buf, size_t len, bool eof) { assert(p != NULL); p->type = SP_JSON_NONE; EXPECT_SIZE(1, eof, SP_JSON_ESYNTAX); if (p->cs & ARRAY_MASK) { return parse_array(p, buf, len, eof); } if (p->cs & OBJECT_MASK) { return parse_object(p, buf, len, eof); } switch (p->cs) { case KIND_ANY: return parse_any(p, buf, len, eof); case KIND_KEY: /* fallthrough */ case KIND_STRING: return parse_string(p, buf, len, eof); case KIND_NUMBER: return parse_number(p, buf, len, eof); case KIND_TRUE: return parse_true(p, buf, len, eof); case KIND_FALSE: return parse_false(p, buf, len, eof); case KIND_NULL: return parse_null(p, buf, len, eof); } YIELD_ERROR(SP_JSON_ESTATE); } bool sp_json_is_done(const SpJson *p) { assert(p != NULL); return IS_DONE(p->cs); } bool sp_json_in_object(const SpJson *p) { assert(p != NULL); return p->depth > 0 && STACK_IN_OBJ(p); } bool sp_json_is_key(const SpJson *p) { assert(p != NULL); return p->cs == OBJECT_SEP; } bool sp_json_in_array(const SpJson *p) { assert(p != NULL); return p->depth > 0 && STACK_IN_ARR(p); } uint8_t *sp_json_steal_string(SpJson *p, size_t *len, size_t *cap) { assert(p != NULL); return sp_utf8_steal(&p->utf8, len, cap); }
2.15625
2
2024-11-18T21:51:02.250858+00:00
2023-03-12T22:18:23
e5bf63d38eaf035f11d897497034a3c4d5724ae1
{ "blob_id": "e5bf63d38eaf035f11d897497034a3c4d5724ae1", "branch_name": "refs/heads/zephyr-v2.7.4", "committer_date": "2023-03-12T22:18:23", "content_id": "69305b73cb4582edd5f1c0020bbdfde5dee8d5f2", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "9d13589cf70df3b53b422e11bd15c678ecae429d", "extension": "c", "filename": "main.c", "fork_events_count": 2, "gha_created_at": "2018-10-20T21:42:30", "gha_event_created_at": "2023-04-01T19:16:33", "gha_language": "CMake", "gha_license_id": "BSD-3-Clause", "github_id": 153950898, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3656, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/samples/qt_project/src/main.c", "provenance": "stackv2-0138.json.gz:136926", "repo_name": "jorisoffouga/zephyr-application", "revision_date": "2023-03-12T22:18:23", "revision_id": "64cfeca3941ca514f7927b8b377efb6b87d91af3", "snapshot_id": "caa9072b592a0c6830ddfc73cb874b2c3eee0969", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/jorisoffouga/zephyr-application/64cfeca3941ca514f7927b8b377efb6b87d91af3/samples/qt_project/src/main.c", "visit_date": "2023-04-29T16:08:29.301350" }
stackv2
#include <zephyr.h> #include <device.h> #include <drivers/gpio.h> #include <drivers/uart.h> #include <sys/printk.h> #include <sys/__assert.h> #include <string.h> #include "util.h" #define LED_PORT DT_ALIAS_LED0_GPIOS_CONTROLLER #define LED0 DT_ALIAS_LED0_GPIOS_PIN #define LED1 DT_ALIAS_LED1_GPIOS_PIN #define LED2 DT_ALIAS_LED2_GPIOS_PIN #define LED3 DT_ALIAS_LED3_GPIOS_PIN #define UART_PORT "UART_2" #define SW_PORT DT_ALIAS_SW0_GPIOS_CONTROLLER #define SW_PIN DT_ALIAS_SW0_GPIOS_PIN #define EDGE (GPIO_INT_EDGE | GPIO_INT_ACTIVE_LOW) #define PULL_UP 0 /* size of stack area used by each thread */ #define STACKSIZE 1024 /* scheduling priority used by each thread */ #define PRIORITY 7 /* Callback function*/ typedef void (*callback_t)(struct device *port, struct gpio_callback *cb, uint32_t pins); static struct bridge_t bridge; static struct gpio_callback gpio_cb; /* Initialiase Fifo*/ K_FIFO_DEFINE(uart_fifo); /* Uart rx callback*/ static void uart_irq_callback(struct device *uart) { int rx; char buffer[255]; while (uart_irq_update(uart) && uart_irq_is_pending(uart)) { if (!uart_irq_rx_ready(uart)) { if (uart_irq_tx_ready(uart)) { /* Nothing to do*/ } else { /* Nothing to do*/ } /* Only the UART RX path is interrupt-enabled */ break; } /* Read character and send to mainthead with fifo */ rx = uart_fifo_read(uart, buffer, 1); struct fifo_data_t data = {.data = buffer}; size_t size = sizeof(struct fifo_data_t); char *mem_ptr = k_malloc(size); __ASSERT_NO_MSG(mem_ptr != 0); memcpy(mem_ptr, &data, size); k_fifo_put(&uart_fifo, mem_ptr); } } /* Gpio interrupt callback */ void gpio_callback(struct device *port, struct gpio_callback *cb, uint32_t pins) { struct bridge_t *dev = &bridge; gpio_pin_toggle(dev->gpio.handle, LED0); gpio_pin_toggle(dev->gpio.handle, LED1); gpio_pin_toggle(dev->gpio.handle, LED2); gpio_pin_toggle(dev->gpio.handle, LED3); } /* Thread */ static void MainThread(void) { struct bridge_t *dev = &bridge; struct device *sw_dev; callback_t gpioCallback = gpio_callback; /* Enable gpio interrupt */ sw_dev = device_get_binding(SW_PORT); __ASSERT_NO_MSG(sw_dev != NULL); gpio_pin_configure(sw_dev, SW_PIN, GPIO_DIR_IN | GPIO_INT | PULL_UP | EDGE); gpio_init_callback(&gpio_cb, gpioCallback, BIT(SW_PIN)); gpio_add_callback(sw_dev, &gpio_cb); gpio_pin_enable_callback(sw_dev, SW_PIN); /* Set LED pin as output */ dev->gpio.handle = device_get_binding(LED_PORT); __ASSERT_NO_MSG(dev->gpio.handle != NULL); gpio_pin_configure(dev->gpio.handle, LED0, GPIO_DIR_OUT); gpio_pin_configure(dev->gpio.handle, LED1, GPIO_DIR_OUT); gpio_pin_configure(dev->gpio.handle, LED2, GPIO_DIR_OUT); gpio_pin_configure(dev->gpio.handle, LED3, GPIO_DIR_OUT); /* uart setup */ dev->uart.handle = device_get_binding(UART_PORT); __ASSERT_NO_MSG(dev->uart.handle != NULL); uart_irq_rx_disable(dev->uart.handle); uart_irq_tx_disable(dev->uart.handle); uart_irq_callback_set(dev->uart.handle, uart_irq_callback); uart_irq_rx_enable(dev->uart.handle); while (1) { struct fifo_data_t *data = k_fifo_get(&uart_fifo, K_FOREVER); switch (*data->data) { case 0x30: gpio_pin_toggle(dev->gpio.handle, LED3); break; case 0x31: gpio_pin_toggle(dev->gpio.handle, LED0); break; case 0x32: gpio_pin_toggle(dev->gpio.handle, LED1); break; case 0x33: gpio_pin_toggle(dev->gpio.handle, LED2); break; default: break; } k_free(data); k_sleep(Z_TIMEOUT_TICKS(500)); } } /* Initialiase Thread */ K_THREAD_DEFINE(MainThread_id, STACKSIZE, MainThread, NULL, NULL, NULL, PRIORITY, 0, 0);
2.65625
3
2024-11-18T21:51:02.458539+00:00
2016-12-30T19:22:02
6ea196295d8de5877d11c5f147a68c3e551987fb
{ "blob_id": "6ea196295d8de5877d11c5f147a68c3e551987fb", "branch_name": "refs/heads/master", "committer_date": "2016-12-30T19:22:02", "content_id": "675ffdca9a5d17bb82c62f4dcc21caabed01089d", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "1034555b8beb176279c51479c22470904c4cbbf1", "extension": "c", "filename": "moarTime.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": 720, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/layers/shared/src/moarTime.c", "provenance": "stackv2-0138.json.gz:137183", "repo_name": "shkolnick-kun/moarstack", "revision_date": "2016-12-30T19:22:02", "revision_id": "43b3eb9cb5cf927e4c4c6c9865cd5d30287fe816", "snapshot_id": "e2dd103a586fda6125f4ebe66d7e86a494e23bb0", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/shkolnick-kun/moarstack/43b3eb9cb5cf927e4c4c6c9865cd5d30287fe816/layers/shared/src/moarTime.c", "visit_date": "2020-03-17T01:40:08.168426" }
stackv2
// // Created by svalov on 8/9/16. // #include <moarTime.h> #include <sys/time.h> #include <time.h> moarTime_T timeGetCurrent(){ struct timeval tv; // TODO switch to clock_gettime later int res = gettimeofday(&tv, NULL); if(0 == res){ moarTime_T seconds = tv.tv_sec; moarTime_T curTime = seconds * 1000 + tv.tv_usec / 1000; return curTime; } return (moarTime_T)-1; } moarTimeInterval_T timeGetDifference(moarTime_T first, moarTime_T second){ return first-second; } int timeCompare(moarTime_T first, moarTime_T second){ if(first == second) return 0; if(first < second) return -1; else return 1; } moarTime_T timeAddInterval(moarTime_T time, moarTimeInterval_T interval){ return time + interval; }
2.625
3
2024-11-18T21:51:03.021946+00:00
2021-09-09T01:41:50
35bf962d7bf492c8d28c694878225b9cf4a9a987
{ "blob_id": "35bf962d7bf492c8d28c694878225b9cf4a9a987", "branch_name": "refs/heads/master", "committer_date": "2021-09-09T01:41:50", "content_id": "f42ef85ea3166b0daa72161dcb11968ce0bd6878", "detected_licenses": [ "MIT" ], "directory_id": "5a23bbb2059e4a5b0f4698f9053636af050ff24b", "extension": "h", "filename": "tad_fantasma.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 295474174, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2193, "license": "MIT", "license_type": "permissive", "path": "/pac-man/tad_fantasma.h", "provenance": "stackv2-0138.json.gz:137441", "repo_name": "tiagoserique/pac-man", "revision_date": "2021-09-09T01:41:50", "revision_id": "fde7e481422eff948636d59a45b1e297c429ffb6", "snapshot_id": "47f6b3f6566bf9020cf598a0ddd40dc1879bce5c", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/tiagoserique/pac-man/fde7e481422eff948636d59a45b1e297c429ffb6/pac-man/tad_fantasma.h", "visit_date": "2023-07-18T15:20:23.973555" }
stackv2
#include <time.h> #include <unistd.h> #include "tad_pacman.h" #include "tad_lde.h" #define BLINKY 010 #define PINKY 020 #define INKY 030 #define CLYDE 040 #define COR_BLINKY 1 #define COR_CLYDE 3 #define COR_PINKY 8 #define COR_INKY 6 #define DELAY_FANTASMAS 9 #define LIMITE_DELAY_FANTASMAS 3 struct fantasma { int id; /* identifica qual eh o fantasma */ struct coord *alvo; /* valor da posicao do alvo referente ao ncurses */ struct coord *posicao; /* valor da posicao do fantasma referente ao ncurses */ int fugir; /* 1 se estiver fugindo, 0 se estiver perseguindo */ int comido; /* 1 se foi comido, 0 se nao */ struct lista *direcoesDisponiveis; /* lista uasda para as posicoes disponiveis */ int dirAtual; /* direcao em que ele estava seguindo */ }; /* cria fantasma */ struct fantasma *criaFantasma(int id, int linhaInicial, int colunaInicial); /* exibe o fantasma na tela */ void mostraFantasma(struct fantasma *fantasma, int versaoFantasma); /* faz o fantasma atravessar o mapa */ void fantasmaAtravessaMapa(struct fantasma *fantasma, int atributo); /* define o alvo de cada fantasma */ void defineAlvos(struct fantasma *fantasma, struct pacman *pacman, int direcaoPacman); /* faz a escolha de que direcao seguir */ int escolheDirecao(struct fantasma *fantasma, struct pacman *pacman, int direcaoPacman); /* retorna a direcao com a menor distancia ate o alvo*/ int direcaoComMenorDistancia(struct fantasma *fantasma); /* calcula a distancia entre a proxima posicao do fantasma e o alvo */ int calculaDistancia(int linha, int coluna, int linhaAlvo, int colunaAlvo); /* faz a movimentacao do fantasma */ void moveFantasma(struct fantasma *fantasma, int direcao); /* reinicia posicao dos fantasmas */ void reiniciaPosicaoFantasma(struct fantasma *fantasma); /* verifica e faz as alteracoes necessarias quando o fantasma foi comido */ int foiComido(struct fantasma *fantasma); /* define o comportamento dos fantasmas */ void fogeOuPersegue(struct fantasma *fantasma, struct pacman *pacman); /* destroi fantasma */ void destroiFantasma(struct fantasma *fantasma);
2.375
2
2024-11-18T21:51:03.618693+00:00
2014-09-10T17:05:36
ee95d34406d99de3558e7c65d5a0f65fa08b5090
{ "blob_id": "ee95d34406d99de3558e7c65d5a0f65fa08b5090", "branch_name": "refs/heads/master", "committer_date": "2014-09-10T17:05:36", "content_id": "784e3f6ab3766c9077a30608ee2301b61ced7948", "detected_licenses": [ "Apache-2.0" ], "directory_id": "eb723810d9538d36e4c4756ab9958793585cc977", "extension": "c", "filename": "dist_const_score.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": 689, "license": "Apache-2.0", "license_type": "permissive", "path": "/dist_const_score.c", "provenance": "stackv2-0138.json.gz:137700", "repo_name": "hsptools/cLinus", "revision_date": "2014-09-10T17:05:36", "revision_id": "e0c94ff8bb877e7425aa9edab78f91555d8b1528", "snapshot_id": "c47f422acea6b2fa1e72dfd9ee0d503eeb833b16", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/hsptools/cLinus/e0c94ff8bb877e7425aa9edab78f91555d8b1528/dist_const_score.c", "visit_date": "2021-01-19T14:58:39.057804" }
stackv2
#include <stdio.h> #include <math.h> #include "linus.h" double dist_const_score(LinusProtein *p,DcList *dclist, int size) { double edist = 0.0; int i; for(i=0;i<size;i++) { double dist = distance(&p->atoms[dclist[i].a1],&p->atoms[dclist[i].a2]); double dmax = dclist[i].d + dclist[i].dmax; double dmin = dclist[i].d - dclist[i].dmin; if(dist > dmax) { edist+= sqrt(dist-dmax); } else if(dist < dmax && dist > dmin) { edist += 0.0; } else if(dist < dmin) { edist += sqrt(dmin-dist); } } return edist; }
2.21875
2
2024-11-18T21:51:03.990371+00:00
2017-09-24T21:10:45
cad8512188d27fbabfbb7c21fa58ba46140397ba
{ "blob_id": "cad8512188d27fbabfbb7c21fa58ba46140397ba", "branch_name": "refs/heads/master", "committer_date": "2017-09-25T00:04:37", "content_id": "58ba1031c27e2c292380ddf6a0b43bbf48931f39", "detected_licenses": [ "Artistic-2.0" ], "directory_id": "17df654bc8b3ca4f0c0c1c14d0f1adea76a215fe", "extension": "h", "filename": "tcmath.h", "fork_events_count": 0, "gha_created_at": "2017-08-22T03:45:21", "gha_event_created_at": "2017-09-25T00:04:39", "gha_language": "C", "gha_license_id": null, "github_id": 101018503, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 8330, "license": "Artistic-2.0", "license_type": "permissive", "path": "/src/include/tcmath.h", "provenance": "stackv2-0138.json.gz:138088", "repo_name": "IanTayler/tenc", "revision_date": "2017-09-24T21:10:45", "revision_id": "1be1d278353c057bfc8c73cb334bf06ccafb3abe", "snapshot_id": "205b63283ddc8f49e89aaa2d97f8bfc65358a4bf", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/IanTayler/tenc/1be1d278353c057bfc8c73cb334bf06ccafb3abe/src/include/tcmath.h", "visit_date": "2021-01-19T16:41:37.797957" }
stackv2
/***************************************************************************** * Copyright (c) 2017 by Ian G. Tayler <[email protected]> * * This file is part of TenC. * * * * TenC is distributed as free software under the Artistic License 2.0. * * You should have received a copy of the license together with the source * * files for TenC. It should be in the main directory, in a file named * * 'LICENSE'. * *****************************************************************************/ #ifndef MATH_H #define MATH_H #include <stdbool.h> #include <math.h> #include "tensor.h" /** * \file include/tcmath.h * \author Ian G. Tayler * * \brief Defines mathematical functions for Tensors. */ /** * \brief Add two Tensor-s element-wise, save the result in the first one. * * \param tdest Tensor. One of the terms of the sum, and also the destination. * \param t2 Tensor. Same Shape as tdest. * * \note There is no return value. The result is saved in Tensor tdest. * Therefore, you will lose whatever information you had in tdest. * * \see tc_add_pure tc_add_and_free */ void tc_add(Tensor *tdest, Tensor *t2); /** * \brief Add two Tensor-s element-wise. Save the result in tdest, free t2 * * \param tdest Tensor. Destination. * \param t2 Tensor. Same Shape as tdest. Will be freed. * \see tc_add tc_add_pure */ void tc_add_and_free(Tensor *tdest, Tensor *t2); /** * \brief Add two Tensor-s element-wise, return a pointer to the sum-Tensor. * * \param t1 Tensor. * \param t2 Tensor. Same Shape as t1. * * \return Tensor (pointer) with the element-wise sum. * * \see tc_add_and_free tc_add */ Tensor *tc_add_pure(Tensor *t1, Tensor *t2); /** * \brief Subtract two Tensor-s element-wise, save the result in the first one. * * \param tdest Tensor. One of the terms of the subtraction, and also the * destination. * \param t2 Tensor. Same Shape as tdest. * * \note There is no return value. The result is saved in Tensor tdest. * Therefore, you will lose whatever information you had in tdest. * * \see tc_sub_pure tc_sub_and_free */ void tc_sub(Tensor *tdest, Tensor *t2); /** * \brief Subtract two Tensor-s element-wise. Save the result in tdest, free t2. * * \param tdest Tensor. Destination. * \param t2 Tensor. Same Shape as tdest. Will be freed. * \see tc_sub tc_sub_pure */ void tc_sub_and_free(Tensor *tdest, Tensor *t2); /** * \brief Subtract two Tensor-s element-wise, return a pointer to Tensor. * * \param t1 Tensor. * \param t2 Tensor. Same Shape as t1. * * \return Tensor (pointer) with the element-wise subtraction. * * \see tc_sub_and_free tc_sub */ Tensor *tc_sub_pure(Tensor *t1, Tensor *t2); /** * \brief Multiply two Tensor-s element-wise, save the result in the first one. * * \param tdest Tensor. One of the terms of the multiplication, and also the * destination. * \param t2 Tensor. Same Shape as tdest. * * \note There is no return value. The result is saved in Tensor tdest. * Therefore, you will lose whatever information you had in tdest. * * \see tc_mul_pure tc_mul_and_free */ void tc_mul(Tensor *tdest, Tensor *t2); /** * \brief Multiply two Tensor-s element-wise. Save the result in tdest, free t2. * * \param tdest Tensor. Destination. * \param t2 Tensor. Same Shape as tdest. Will be freed. * \see tc_mul tc_mul_pure */ void tc_mul_and_free(Tensor *tdest, Tensor *t2); /** * \brief Multiply two Tensor-s element-wise, return a pointer to Tensor. * * \param t1 Tensor. * \param t2 Tensor. Same Shape as t1. * * \return Tensor (pointer) with the element-wise multiplication. * * \see tc_mul_and_free tc_mul */ Tensor *tc_mul_pure(Tensor *t1, Tensor *t2); /** * \brief Divide two Tensor-s element-wise, save the result in the first one. * * \param tdest Tensor. One of the terms of the division, and also the * destination. * \param t2 Tensor. Same Shape as tdest. * * \note There is no return value. The result is saved in Tensor tdest. * Therefore, you will lose whatever information you had in tdest. * * \note For this function, division by 0 is the identity (i.e. x / 0 == x), but * prints a warning to stderr. * * \see tc_div_pure tc_div_and_free */ void tc_div(Tensor *tdest, Tensor *t2); /** * \brief Divide two Tensor-s element-wise. Save the result in tdest, free t2. * * \param tdest Tensor. Destination. * \param t2 Tensor. Same Shape as tdest. Will be freed. * * \note For this function, division by 0 is the identity (i.e. x / 0 == x), but * prints a warning to stderr. * \see tc_mul tc_mul_pure */ void tc_div_and_free(Tensor *tdest, Tensor *t2); /** * \brief Divide two Tensor-s element-wise, return a pointer to Tensor. * * \param t1 Tensor. * \param t2 Tensor. Same Shape as t1. * * \return Tensor (pointer) with the element-wise multiplication. * * \note For this function, division by 0 is the identity (i.e. x / 0 == x), but * prints a warning to stderr. * * \see tc_div_and_free tc_div */ Tensor *tc_div_pure(Tensor *t1, Tensor *t2); /** * \brief Sum every member of a Tensor. * * \param t Tensor. * * \return Float with the sum of every member of the Tensor. */ float tc_reduce_sum(Tensor *t); /** * \brief Multiply every member of a Tensor. * * \param t Tensor. * * \return Float with the product of every member of the Tensor. */ float tc_reduce_mul(Tensor *t); /** * \brief Reduce a Tensor to a float with a certain function. * * \param t Tensor. * \param fn Function that takes two floats and returns a float. * \param init Initial accumulator value. */ float tc_reduce_fn(Tensor *t, float (*fn)(float, float), float init); /* * \brief Compute the dot product of two Tensors. * * \param t1 Tensor. * \param t2 Tensor. * * \return Float. The result is reduce_sum(multiply_elementwise(t1, t2)). */ float tc_dot_product(Tensor *t1, Tensor *t2); /** * \brief Rectified Linear function. * * \note This is only the rectified linear function. It's called 'ReLU' to make * it more recognizable. * * \param x Input float. * * \return Float. 0 if x <= 0, x otherwise. */ float tc_relu(float x); /** * \brief Differentiation of tc_relu. * * \note Returns 1 for value 0. */ float tc_relu_diff(float x); /** * \brief Rectified Linear function up to 6. * * \note This is only the rectified linear function. It's called 'ReLU' to make * it more recognizable. * * \param x Input float. * * \return Float. 0 if x <= 0, x if x >= 6, x otherwise. */ float tc_relu6(float x); /** * \brief Differentiation of tc_relu6. * * \note Returns 1 for value 0 and 0 for value 6. */ float tc_relu6_diff(float x); /** * \brief Thin wrapper around tanhf in math.h */ float tc_tanh(float x); /** * \brief Differentiation of tanh. */ float tc_tanh_diff(float x); /** * \brief Logistic function. */ float tc_sigmoid(float x); /** * \brief Differentiation of the sigmoid function. */ float tc_sigmoid_diff(float x); /** * \brief Compare two floats. * * \param a First float to compare. * \param b Second float to compare. * \param places Amount of decimal places to consider. * * \return true if they're equal up to places decimal places, false otherwise. */ bool tc_near_equal_floats(float a, float b, int places); /** * \brief Compare two Tensors. * * Change the first Tensor so that in each place it will be 1.f if the two * Tensors were equal in that place, and 0.f if they weren't. * * \param t1 First Tensor to compare. * \param t2 Second Tensor to compare. * \param places Amount of decimal places to consider. * * \note This will modify the first Tensor. */ void tc_near_equal(Tensor *t1, Tensor *t2, int places); /** * \brief Compare all elements in a Tensor to a certain float. * * \param t Tensor. * \param value Float. * \param places Decimal places to consider. * * \return true if they are all near, false otherwise. */ bool tc_all_near(Tensor *t, float value, int places); /** * \brief Reduce a boolean Tensor to a boolean value. * * \param t Tensor to reduce. * \param places Number of places to consider. * * \note This function doesn't check its input is actually a boolean Tensor. All * values that aren't tc_near_equal_floats to 0.f considering places number of * places will taken as true. */ bool tc_reduce_all(Tensor *t, int places); #endif
2.390625
2
2024-11-18T21:51:04.056535+00:00
2019-06-27T00:49:40
325e9cb6a4fb62b8ed62ffe8dc729b6dffe9cb67
{ "blob_id": "325e9cb6a4fb62b8ed62ffe8dc729b6dffe9cb67", "branch_name": "refs/heads/master", "committer_date": "2019-06-27T00:49:40", "content_id": "3d1658f97b7a6a1059950a1e04231e84564df25f", "detected_licenses": [ "BSD-3-Clause-Open-MPI" ], "directory_id": "7047c2ebf8d7944c6b4467560e190b184d54697d", "extension": "c", "filename": "timer_linux_component.c", "fork_events_count": 6, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 33182022, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3697, "license": "BSD-3-Clause-Open-MPI", "license_type": "permissive", "path": "/openmpi-1.2.4/opal/mca/timer/linux/timer_linux_component.c", "provenance": "stackv2-0138.json.gz:138217", "repo_name": "NirantK/Text-Summarization", "revision_date": "2019-06-27T00:49:40", "revision_id": "45bfa88f77515e1e5c8c6c6b3c64aba4ef8e1575", "snapshot_id": "7afb7be3810ccfc1341758ce7899fb2e41b49d4c", "src_encoding": "UTF-8", "star_events_count": 3, "url": "https://raw.githubusercontent.com/NirantK/Text-Summarization/45bfa88f77515e1e5c8c6c6b3c64aba4ef8e1575/openmpi-1.2.4/opal/mca/timer/linux/timer_linux_component.c", "visit_date": "2020-06-04T07:12:43.455919" }
stackv2
/* * Copyright (c) 2004-2005 The Trustees of Indiana University and Indiana * University Research and Technology * Corporation. All rights reserved. * Copyright (c) 2004-2005 The University of Tennessee and The University * of Tennessee Research Foundation. All rights * reserved. * Copyright (c) 2004-2005 High Performance Computing Center Stuttgart, * University of Stuttgart. All rights reserved. * Copyright (c) 2004-2005 The Regents of the University of California. * All rights reserved. * $COPYRIGHT$ * * Additional copyrights may follow * * $HEADER$ */ #include "opal_config.h" #include "opal/mca/timer/timer.h" #include "opal/mca/timer/linux/timer_linux.h" #include "opal/constants.h" opal_timer_t opal_timer_linux_freq; static int opal_timer_linux_open(void); const opal_timer_base_component_1_0_0_t mca_timer_linux_component = { /* First, the mca_component_t struct containing meta information about the component itself */ { /* Indicate that we are a timer v1.0.0 component (which also implies a specific MCA version) */ OPAL_TIMER_BASE_VERSION_1_0_0, /* Component name and version */ "linux", OPAL_MAJOR_VERSION, OPAL_MINOR_VERSION, OPAL_RELEASE_VERSION, /* Component open and close functions */ opal_timer_linux_open, NULL }, /* Next the MCA v1.0.0 component meta data */ { /* Whether the component is checkpointable or not */ true }, }; static char * find_info(FILE* fp, char *str, char *buf, size_t buflen) { char *tmp; rewind(fp); while (NULL != fgets(buf, 1024, fp)) { if (strncmp(buf, str, strlen(str)) == 0) { /* we found the line. Now eat everything up to, including, and one past the : */ for (tmp = buf ; (*tmp != '\0') && (*tmp != ':') ; ++tmp) ; for ( ++tmp ; *tmp == ' ' ; ++tmp); if (NULL != tmp && '\0' != *tmp) { return tmp; } } } return NULL; } int opal_timer_linux_open(void) { FILE *fp; char *loc; float cpu_f; int ret; char buf[1024]; fp = fopen("/proc/cpuinfo", "r"); if (NULL == fp) { return OPAL_ERR_IN_ERRNO; } opal_timer_linux_freq = 0; if (0 == opal_timer_linux_freq) { /* first, look for a timebase field. probably only on PPC, but one never knows */ loc = find_info(fp, "timebase", buf, 1024); if (NULL != loc) { int freq; ret = sscanf(loc, "%d", &freq); if (1 == ret) { opal_timer_linux_freq = freq; } } } if (0 == opal_timer_linux_freq) { /* find the CPU speed - most timers are 1:1 with CPU speed */ loc = find_info(fp, "cpu MHz", buf, 1024); if (NULL != loc) { ret = sscanf(loc, "%f", &cpu_f); if (1 == ret) { /* numer is in MHz - convert to Hz and make an integer */ opal_timer_linux_freq = (opal_timer_t) cpu_f * 1000000; } } } if (0 == opal_timer_linux_freq) { /* look for the sparc way of getting cpu frequency */ loc = find_info(fp, "Cpu0ClkTck", buf, 1024); if (NULL != loc) { unsigned int freq; ret = sscanf(loc, "%x", &freq); if (1 == ret) { opal_timer_linux_freq = freq; } } } fclose(fp); return OPAL_SUCCESS; }
2.1875
2
2024-11-18T21:51:04.197891+00:00
2022-07-13T06:14:38
ff3c720cfd410eaaa7400ad893504d60fe0efe09
{ "blob_id": "ff3c720cfd410eaaa7400ad893504d60fe0efe09", "branch_name": "refs/heads/unstable", "committer_date": "2022-07-13T06:14:38", "content_id": "52d0db4c89c69c4fbcabd5859f0461b0f53edd41", "detected_licenses": [ "BSD-3-Clause", "BSD-2-Clause" ], "directory_id": "6745143949ea51b00b884c5cf2282f0363882a12", "extension": "h", "filename": "ticker.h", "fork_events_count": 3, "gha_created_at": "2018-04-18T18:50:57", "gha_event_created_at": "2023-03-13T19:58:36", "gha_language": "C", "gha_license_id": "BSD-3-Clause", "github_id": 130107902, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2258, "license": "BSD-3-Clause,BSD-2-Clause", "license_type": "permissive", "path": "/deps/jemalloc/include/jemalloc/internal/ticker.h", "provenance": "stackv2-0138.json.gz:138478", "repo_name": "madolson/redis", "revision_date": "2022-07-13T06:14:38", "revision_id": "599e59ebc57283f52c60a8de56ec5f44d053109a", "snapshot_id": "2d7d7167939f12fba78537386579f1fdbb5318c1", "src_encoding": "UTF-8", "star_events_count": 7, "url": "https://raw.githubusercontent.com/madolson/redis/599e59ebc57283f52c60a8de56ec5f44d053109a/deps/jemalloc/include/jemalloc/internal/ticker.h", "visit_date": "2023-09-02T09:11:37.957073" }
stackv2
#ifndef JEMALLOC_INTERNAL_TICKER_H #define JEMALLOC_INTERNAL_TICKER_H #include "jemalloc/internal/util.h" /** * A ticker makes it easy to count-down events until some limit. You * ticker_init the ticker to trigger every nticks events. You then notify it * that an event has occurred with calls to ticker_tick (or that nticks events * have occurred with a call to ticker_ticks), which will return true (and reset * the counter) if the countdown hit zero. */ typedef struct { int32_t tick; int32_t nticks; } ticker_t; static inline void ticker_init(ticker_t *ticker, int32_t nticks) { ticker->tick = nticks; ticker->nticks = nticks; } static inline void ticker_copy(ticker_t *ticker, const ticker_t *other) { *ticker = *other; } static inline int32_t ticker_read(const ticker_t *ticker) { return ticker->tick; } /* * Not intended to be a public API. Unfortunately, on x86, neither gcc nor * clang seems smart enough to turn * ticker->tick -= nticks; * if (unlikely(ticker->tick < 0)) { * fixup ticker * return true; * } * return false; * into * subq %nticks_reg, (%ticker_reg) * js fixup ticker * * unless we force "fixup ticker" out of line. In that case, gcc gets it right, * but clang now does worse than before. So, on x86 with gcc, we force it out * of line, but otherwise let the inlining occur. Ordinarily this wouldn't be * worth the hassle, but this is on the fast path of both malloc and free (via * tcache_event). */ #if defined(__GNUC__) && !defined(__clang__) \ && (defined(__x86_64__) || defined(__i386__)) JEMALLOC_NOINLINE #endif static bool ticker_fixup(ticker_t *ticker) { ticker->tick = ticker->nticks; return true; } static inline bool ticker_ticks(ticker_t *ticker, int32_t nticks) { ticker->tick -= nticks; if (unlikely(ticker->tick < 0)) { return ticker_fixup(ticker); } return false; } static inline bool ticker_tick(ticker_t *ticker) { return ticker_ticks(ticker, 1); } /* * Try to tick. If ticker would fire, return true, but rely on * slowpath to reset ticker. */ static inline bool ticker_trytick(ticker_t *ticker) { --ticker->tick; if (unlikely(ticker->tick < 0)) { return true; } return false; } #endif /* JEMALLOC_INTERNAL_TICKER_H */
2.703125
3
2024-11-18T21:51:11.102571+00:00
2023-08-07T19:18:32
9e5616c67b95169d3a2693f7bc7be92158cf0d6b
{ "blob_id": "9e5616c67b95169d3a2693f7bc7be92158cf0d6b", "branch_name": "refs/heads/master", "committer_date": "2023-08-07T19:18:32", "content_id": "d65ea2ca7eea04c49d1c419a88eceb33b3948a76", "detected_licenses": [ "Apache-2.0", "curl" ], "directory_id": "e1d9c54e9925e30e388a255b53a93cccad0b94cb", "extension": "c", "filename": "v1_service.c", "fork_events_count": 47, "gha_created_at": "2020-03-17T11:59:05", "gha_event_created_at": "2023-09-07T20:07:00", "gha_language": "C", "gha_license_id": "Apache-2.0", "github_id": 247958425, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5248, "license": "Apache-2.0,curl", "license_type": "permissive", "path": "/kubernetes/model/v1_service.c", "provenance": "stackv2-0138.json.gz:138998", "repo_name": "kubernetes-client/c", "revision_date": "2023-08-07T19:18:32", "revision_id": "5ac5ff25e9809a92a48111b1f77574b6d040b711", "snapshot_id": "dd4fd8095485c083e0f40f2b48159b1609a6141b", "src_encoding": "UTF-8", "star_events_count": 127, "url": "https://raw.githubusercontent.com/kubernetes-client/c/5ac5ff25e9809a92a48111b1f77574b6d040b711/kubernetes/model/v1_service.c", "visit_date": "2023-08-13T10:51:03.702497" }
stackv2
#include <stdlib.h> #include <string.h> #include <stdio.h> #include "v1_service.h" v1_service_t *v1_service_create( char *api_version, char *kind, v1_object_meta_t *metadata, v1_service_spec_t *spec, v1_service_status_t *status ) { v1_service_t *v1_service_local_var = malloc(sizeof(v1_service_t)); if (!v1_service_local_var) { return NULL; } v1_service_local_var->api_version = api_version; v1_service_local_var->kind = kind; v1_service_local_var->metadata = metadata; v1_service_local_var->spec = spec; v1_service_local_var->status = status; return v1_service_local_var; } void v1_service_free(v1_service_t *v1_service) { if(NULL == v1_service){ return ; } listEntry_t *listEntry; if (v1_service->api_version) { free(v1_service->api_version); v1_service->api_version = NULL; } if (v1_service->kind) { free(v1_service->kind); v1_service->kind = NULL; } if (v1_service->metadata) { v1_object_meta_free(v1_service->metadata); v1_service->metadata = NULL; } if (v1_service->spec) { v1_service_spec_free(v1_service->spec); v1_service->spec = NULL; } if (v1_service->status) { v1_service_status_free(v1_service->status); v1_service->status = NULL; } free(v1_service); } cJSON *v1_service_convertToJSON(v1_service_t *v1_service) { cJSON *item = cJSON_CreateObject(); // v1_service->api_version if(v1_service->api_version) { if(cJSON_AddStringToObject(item, "apiVersion", v1_service->api_version) == NULL) { goto fail; //String } } // v1_service->kind if(v1_service->kind) { if(cJSON_AddStringToObject(item, "kind", v1_service->kind) == NULL) { goto fail; //String } } // v1_service->metadata if(v1_service->metadata) { cJSON *metadata_local_JSON = v1_object_meta_convertToJSON(v1_service->metadata); if(metadata_local_JSON == NULL) { goto fail; //model } cJSON_AddItemToObject(item, "metadata", metadata_local_JSON); if(item->child == NULL) { goto fail; } } // v1_service->spec if(v1_service->spec) { cJSON *spec_local_JSON = v1_service_spec_convertToJSON(v1_service->spec); if(spec_local_JSON == NULL) { goto fail; //model } cJSON_AddItemToObject(item, "spec", spec_local_JSON); if(item->child == NULL) { goto fail; } } // v1_service->status if(v1_service->status) { cJSON *status_local_JSON = v1_service_status_convertToJSON(v1_service->status); if(status_local_JSON == NULL) { goto fail; //model } cJSON_AddItemToObject(item, "status", status_local_JSON); if(item->child == NULL) { goto fail; } } return item; fail: if (item) { cJSON_Delete(item); } return NULL; } v1_service_t *v1_service_parseFromJSON(cJSON *v1_serviceJSON){ v1_service_t *v1_service_local_var = NULL; // define the local variable for v1_service->metadata v1_object_meta_t *metadata_local_nonprim = NULL; // define the local variable for v1_service->spec v1_service_spec_t *spec_local_nonprim = NULL; // define the local variable for v1_service->status v1_service_status_t *status_local_nonprim = NULL; // v1_service->api_version cJSON *api_version = cJSON_GetObjectItemCaseSensitive(v1_serviceJSON, "apiVersion"); if (api_version) { if(!cJSON_IsString(api_version) && !cJSON_IsNull(api_version)) { goto end; //String } } // v1_service->kind cJSON *kind = cJSON_GetObjectItemCaseSensitive(v1_serviceJSON, "kind"); if (kind) { if(!cJSON_IsString(kind) && !cJSON_IsNull(kind)) { goto end; //String } } // v1_service->metadata cJSON *metadata = cJSON_GetObjectItemCaseSensitive(v1_serviceJSON, "metadata"); if (metadata) { metadata_local_nonprim = v1_object_meta_parseFromJSON(metadata); //nonprimitive } // v1_service->spec cJSON *spec = cJSON_GetObjectItemCaseSensitive(v1_serviceJSON, "spec"); if (spec) { spec_local_nonprim = v1_service_spec_parseFromJSON(spec); //nonprimitive } // v1_service->status cJSON *status = cJSON_GetObjectItemCaseSensitive(v1_serviceJSON, "status"); if (status) { status_local_nonprim = v1_service_status_parseFromJSON(status); //nonprimitive } v1_service_local_var = v1_service_create ( api_version && !cJSON_IsNull(api_version) ? strdup(api_version->valuestring) : NULL, kind && !cJSON_IsNull(kind) ? strdup(kind->valuestring) : NULL, metadata ? metadata_local_nonprim : NULL, spec ? spec_local_nonprim : NULL, status ? status_local_nonprim : NULL ); return v1_service_local_var; end: if (metadata_local_nonprim) { v1_object_meta_free(metadata_local_nonprim); metadata_local_nonprim = NULL; } if (spec_local_nonprim) { v1_service_spec_free(spec_local_nonprim); spec_local_nonprim = NULL; } if (status_local_nonprim) { v1_service_status_free(status_local_nonprim); status_local_nonprim = NULL; } return NULL; }
2.234375
2
2024-11-18T21:51:11.491584+00:00
2019-09-15T09:58:00
e7be07730b3c44e4d40a28a80a262b9d5df1cef0
{ "blob_id": "e7be07730b3c44e4d40a28a80a262b9d5df1cef0", "branch_name": "refs/heads/master", "committer_date": "2019-09-15T09:58:00", "content_id": "af4694004275313508f02e2c375f35e0e730bc42", "detected_licenses": [ "MIT" ], "directory_id": "2785e9b16e33292fbf56c17250d0b3b4cce5377d", "extension": "c", "filename": "validate_BST.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 149107631, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1494, "license": "MIT", "license_type": "permissive", "path": "/Interview_Questions/Trees_And_Graphs/validate_BST.c", "provenance": "stackv2-0138.json.gz:139127", "repo_name": "psprawka/Interview_Library", "revision_date": "2019-09-15T09:58:00", "revision_id": "bcd4c0daa8040b714be407fb425b20d13ba2ae9c", "snapshot_id": "c1cca347672bbd73cc12a700345549b0a4b4bfc4", "src_encoding": "UTF-8", "star_events_count": 3, "url": "https://raw.githubusercontent.com/psprawka/Interview_Library/bcd4c0daa8040b714be407fb425b20d13ba2ae9c/Interview_Questions/Trees_And_Graphs/validate_BST.c", "visit_date": "2020-03-28T20:50:42.073443" }
stackv2
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* validate_BST.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: psprawka <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/10/30 09:53:26 by psprawka #+# #+# */ /* Updated: 2018/10/30 10:16:02 by psprawka ### ########.fr */ /* */ /* ************************************************************************** */ /* ** Validate BST: Impplement a function to check if a BT is BST. ** Clarification: Can it have duplicates? If so in left or right subtree? */ #include "libft.h" #include <stdbool.h> typedef struct s_tree { struct s_tree *left; struct s_tree *right; void *data; } t_tree; bool validate_BST(t_tree *root) { if (!root) return (true); if (!((!root->left || root->left <= root) && (!root->right || root->right > root))) return (false); if (validate_BST(root->left) == false || validate_BST(root->right) == false) return (false); return (true); }
2.8125
3
2024-11-18T21:51:11.592138+00:00
2020-01-29T21:45:25
4ce0fc46dcc7bd71bb766a569f4a38a453e36ade
{ "blob_id": "4ce0fc46dcc7bd71bb766a569f4a38a453e36ade", "branch_name": "refs/heads/master", "committer_date": "2020-01-29T21:45:25", "content_id": "c4b6f14dcd14c1cf06f07704dac2a1d3b00dade1", "detected_licenses": [ "MIT" ], "directory_id": "995dd8ecf9ed79cbab3c87eada2687b1fe909134", "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": 6137, "license": "MIT", "license_type": "permissive", "path": "/pwm/main.c", "provenance": "stackv2-0138.json.gz:139256", "repo_name": "moneytech/bare_matal_rpi_zero", "revision_date": "2020-01-29T21:45:25", "revision_id": "e1bd658ab8e7fff42e0e684b7a62ed1016fd9bc6", "snapshot_id": "9698e8f4c4eb72a7e96d04999b17d414be910950", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/moneytech/bare_matal_rpi_zero/e1bd658ab8e7fff42e0e684b7a62ed1016fd9bc6/pwm/main.c", "visit_date": "2022-01-04T15:02:58.029002" }
stackv2
#include <stdint.h> #include <stdio.h> #include <string.h> #define IOREG(X) (*(volatile uint32_t *) (X)) // GPIO registers #define GPFSEL0 IOREG(0x20200000) #define GPFSEL1 IOREG(0x20200004) #define GPFSEL2 IOREG(0x20200008) #define GPFSEL3 IOREG(0x2020000C) #define GPFSEL4 IOREG(0x20200010) #define GPFSEL5 IOREG(0x20200014) #define GPF_INPUT 0U #define GPF_OUTPUT 1U #define GPF_ALT_0 4U #define GPF_ALT_1 5U #define GPF_ALT_2 6U #define GPF_ALT_3 7U #define GPF_ALT_4 3U #define GPF_ALT_5 2U // Mini UART registers #define AUX_IRQ IOREG(0x20215000) #define AUX_ENABLES IOREG(0x20215004) #define MU_IO IOREG(0x20215040) #define MU_IER IOREG(0x20215044) #define MU_IIR IOREG(0x20215048) #define MU_LCR IOREG(0x2021504C) #define MU_MCR IOREG(0x20215050) #define MU_LSR IOREG(0x20215054) #define MU_MSR IOREG(0x20215058) #define MU_SCRATCH IOREG(0x2021505C) #define MU_CNTL IOREG(0x20215060) #define MU_STAT IOREG(0x20215064) #define MU_BAUD IOREG(0x20215068) #define MU_LSR_TX_IDLE (1U << 6) #define MU_LSR_TX_EMPTY (1U << 5) #define MU_LSR_RX_RDY (1U) // System timer counter #define SYST_CLO IOREG(0x20003004) #define SYST_CHI IOREG(0x20003008) // PWM registers #define CM_PWMCTL IOREG(0x201010a0) #define CM_PWMDIV IOREG(0x201010a4) #define CM_PASSWD (0x5a000000) #define CM_PWMCTL_SRC_MASK (0xfU) #define CM_PWMCTL_SRC_OSC (1U) #define CM_PWMCTL_SRC_PLLA (4U) #define CM_PWMCTL_SRC_PLLC (5U) #define CM_PWMCTL_SRC_PLLD (6U) #define CM_PWMCTL_SRC_HDMI (7U) #define CM_PWMCTL_ENAB (1U<<4) #define CM_PWMCTL_KILL (1U<<5) #define CM_PWMCTL_BUSY (1U<<7) #define CM_PWMCTL_BUSYD (1U<<8) #define CM_PWMCTL_MASH_NONE (1U<<9) #define CM_PWMCTL_MASH_2STG (2U<<9) #define CM_PWMCTL_MASH_3STG (3U<<9) #define PWM (0x2020c000) typedef volatile struct _pwm_t { uint32_t CTL; uint32_t STA; uint32_t DMAC; uint32_t undef1; uint32_t RNG1; uint32_t DAT1; uint32_t FIF1; uint32_t undef2; uint32_t RNG2; uint32_t DAT2; } pwm_t; #define CTL_MSEN2 (1<<15) #define CTL_USEF2 (1<<13) #define CTL_POLA2 (1<<12) #define CTL_SBIT2 (1<<11) #define CTL_RPTL2 (1<<10) #define CTL_MODE2 (1<<9) #define CTL_PWEN2 (1<<8) #define CTL_MSEN1 (1<<7) #define CTL_CLRF1 (1<<6) #define CTL_USEF1 (1<<5) #define CTL_POLA1 (1<<4) #define CTL_SBIT1 (1<<3) #define CTL_RPTL1 (1<<2) #define CTL_MODE1 (1<<1) #define CTL_PWEN1 (1) #define STA_STA4 (1<<12) #define STA_STA3 (1<<11) #define STA_STA2 (1<<10) #define STA_STA1 (1<<9) #define STA_BERR (1<<8) #define STA_GAPO4 (1<<7) #define STA_GAPO3 (1<<6) #define STA_GAPO2 (1<<5) #define STA_GAPO1 (1<<4) #define STA_RERR1 (1<<3) #define STA_WERR1 (1<<2) #define STA_EMPT1 (1<<1) #define STA_FULL1 (1) #define DMAC_ENAB (1<<31) #define DMAC_PANIC (255<<8) #define DMAC_DREQ (255) // This function must be at the top of main.c !! extern uint32_t __bss_start, __bss_end; __attribute__((naked)) __attribute__((section(".startup"))) \ void Init_Machine(void) { // set CPSR __asm volatile("ldr r0, =0x000000d3"); __asm volatile("msr cpsr, r0"); // set stack pointer __asm volatile("ldr sp, =0x06400000"); // zero out .bss section for (uint32_t *dest = &__bss_start; dest < &__bss_end;) { *dest++ = 0; } __asm volatile("bl _start"); __asm volatile("b ."); } void init_uart() { // set GPIO14, GPIO15 to aternate function 5 GPFSEL1 = (GPF_ALT_5 << (3*4)) | (GPF_ALT_5 << (3*5)); // UART basic settings AUX_ENABLES = 1; MU_CNTL = 0; // mini uart disable MU_IER = 0; // disable receive/transmit interrupts MU_IIR = 0xC6; // enable FIFO(0xC0), clear FIFO(0x06) MU_MCR = 0; // set RTS to High // data and speed (mini uart is always parity none, 1 start bit 1 stop bit) MU_LCR = 3; // 8 bits MU_BAUD = 270; // 1115200 bps // enable transmit and receive MU_CNTL = 3; } volatile uint64_t systime(void) { uint64_t t; uint32_t chi; uint32_t clo; chi = SYST_CHI; clo = SYST_CLO; if (chi != SYST_CHI) { chi = SYST_CHI; clo = SYST_CLO; } t = chi; t = t << 32; t += clo; return t; } void delay_ms(uint32_t duration){ uint64_t end_time; end_time = systime() + duration * 1000; while(systime() < end_time); return; } void uart_putc(const unsigned char c) { while (!(MU_LSR & MU_LSR_TX_IDLE) && !(MU_LSR & MU_LSR_TX_EMPTY)); MU_IO = 0xffU & c; } void uart_print(const char *s) { while(*s) { uart_putc(*s++); } } #define TO_HEX(c) (((c) < 10) ? (c) + 0x30 : (c) - 10 + 0x61) void uart_put_hex(const unsigned char c) { uart_putc(TO_HEX(c >> 4)); uart_putc(TO_HEX(c & 0xfU)); } // PWM functions void init_pwm(pwm_t *pwm, uint32_t div) { // set GPIO18, 19 to ALT5 GPFSEL1 |= (GPF_ALT_5 << (3*8)) | (GPF_ALT_5 << (3*9)); // set up pwm clock CM_PWMCTL = CM_PASSWD | (CM_PWMCTL & (~CM_PWMCTL_ENAB)); // disable do {} while(CM_PWMCTL & CM_PWMCTL_BUSY); CM_PWMCTL = CM_PASSWD | CM_PWMCTL_MASH_NONE; CM_PWMCTL |= CM_PASSWD | CM_PWMCTL_SRC_OSC; // clock source = osc (19.2MHz) CM_PWMDIV = CM_PASSWD | (div << 12); // clock = 19.2MHz/div CM_PWMCTL |= CM_PASSWD | CM_PWMCTL_ENAB; } int main(int argc, char **argv) { pwm_t* pwm = (pwm_t*) (PWM); init_uart(); uart_print("\r\nPWM test. 50Hz signal is on GPIO18.\r\n"); delay_ms(1000); init_pwm(pwm, 192); // 19.2MHz/192 = 10KHz clock frequency // initialize pwm pwm->CTL = 0; // disable delay_ms(1); pwm->RNG1 = 2000; // 10KHz / 2000 = 50Hz output frequency pwm->CTL = CTL_MSEN1 | CTL_PWEN1; // pwm1 = mark:space mode, enabled // generate pwm output for servo (pulse width = 0.5ms .. 2.4ms, 50Hz) while(1) { for(int i = 60; i < 250; i++) { pwm->DAT1 = i; delay_ms(20); } for(int i = 250; i > 60; i--) { pwm->DAT1 = i; delay_ms(20); } } return 0; } void _start(void) { // when we get here: stack is initialised, bss is clear, data is copied // initialise the cpu and peripherals // now that we have a basic system up and running we can call main main(0, NULL); // we must not return for (;;) { } }
2.09375
2
2024-11-18T21:51:11.776734+00:00
2023-08-07T19:18:32
8535804803f87a676d0fcab53977f23490b77d2c
{ "blob_id": "8535804803f87a676d0fcab53977f23490b77d2c", "branch_name": "refs/heads/master", "committer_date": "2023-08-07T19:18:32", "content_id": "125f3d621987457ee0c7a8f609d82a15792c252a", "detected_licenses": [ "Apache-2.0", "curl" ], "directory_id": "e1d9c54e9925e30e388a255b53a93cccad0b94cb", "extension": "c", "filename": "v1_container_image.c", "fork_events_count": 47, "gha_created_at": "2020-03-17T11:59:05", "gha_event_created_at": "2023-09-07T20:07:00", "gha_language": "C", "gha_license_id": "Apache-2.0", "github_id": 247958425, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3239, "license": "Apache-2.0,curl", "license_type": "permissive", "path": "/kubernetes/model/v1_container_image.c", "provenance": "stackv2-0138.json.gz:139515", "repo_name": "kubernetes-client/c", "revision_date": "2023-08-07T19:18:32", "revision_id": "5ac5ff25e9809a92a48111b1f77574b6d040b711", "snapshot_id": "dd4fd8095485c083e0f40f2b48159b1609a6141b", "src_encoding": "UTF-8", "star_events_count": 127, "url": "https://raw.githubusercontent.com/kubernetes-client/c/5ac5ff25e9809a92a48111b1f77574b6d040b711/kubernetes/model/v1_container_image.c", "visit_date": "2023-08-13T10:51:03.702497" }
stackv2
#include <stdlib.h> #include <string.h> #include <stdio.h> #include "v1_container_image.h" v1_container_image_t *v1_container_image_create( list_t *names, long size_bytes ) { v1_container_image_t *v1_container_image_local_var = malloc(sizeof(v1_container_image_t)); if (!v1_container_image_local_var) { return NULL; } v1_container_image_local_var->names = names; v1_container_image_local_var->size_bytes = size_bytes; return v1_container_image_local_var; } void v1_container_image_free(v1_container_image_t *v1_container_image) { if(NULL == v1_container_image){ return ; } listEntry_t *listEntry; if (v1_container_image->names) { list_ForEach(listEntry, v1_container_image->names) { free(listEntry->data); } list_freeList(v1_container_image->names); v1_container_image->names = NULL; } free(v1_container_image); } cJSON *v1_container_image_convertToJSON(v1_container_image_t *v1_container_image) { cJSON *item = cJSON_CreateObject(); // v1_container_image->names if(v1_container_image->names) { cJSON *names = cJSON_AddArrayToObject(item, "names"); if(names == NULL) { goto fail; //primitive container } listEntry_t *namesListEntry; list_ForEach(namesListEntry, v1_container_image->names) { if(cJSON_AddStringToObject(names, "", (char*)namesListEntry->data) == NULL) { goto fail; } } } // v1_container_image->size_bytes if(v1_container_image->size_bytes) { if(cJSON_AddNumberToObject(item, "sizeBytes", v1_container_image->size_bytes) == NULL) { goto fail; //Numeric } } return item; fail: if (item) { cJSON_Delete(item); } return NULL; } v1_container_image_t *v1_container_image_parseFromJSON(cJSON *v1_container_imageJSON){ v1_container_image_t *v1_container_image_local_var = NULL; // define the local list for v1_container_image->names list_t *namesList = NULL; // v1_container_image->names cJSON *names = cJSON_GetObjectItemCaseSensitive(v1_container_imageJSON, "names"); if (names) { cJSON *names_local = NULL; if(!cJSON_IsArray(names)) { goto end;//primitive container } namesList = list_createList(); cJSON_ArrayForEach(names_local, names) { if(!cJSON_IsString(names_local)) { goto end; } list_addElement(namesList , strdup(names_local->valuestring)); } } // v1_container_image->size_bytes cJSON *size_bytes = cJSON_GetObjectItemCaseSensitive(v1_container_imageJSON, "sizeBytes"); if (size_bytes) { if(!cJSON_IsNumber(size_bytes)) { goto end; //Numeric } } v1_container_image_local_var = v1_container_image_create ( names ? namesList : NULL, size_bytes ? size_bytes->valuedouble : 0 ); return v1_container_image_local_var; end: if (namesList) { listEntry_t *listEntry = NULL; list_ForEach(listEntry, namesList) { free(listEntry->data); listEntry->data = NULL; } list_freeList(namesList); namesList = NULL; } return NULL; }
2.65625
3
2024-11-18T21:51:11.931258+00:00
2015-09-30T18:12:49
e4b2f3e4f32783e8de62aff43c86845ab49f80c6
{ "blob_id": "e4b2f3e4f32783e8de62aff43c86845ab49f80c6", "branch_name": "refs/heads/master", "committer_date": "2015-09-30T18:12:49", "content_id": "5157b82915da848abadabfe9ee8b15bc085193e3", "detected_licenses": [ "Unlicense" ], "directory_id": "1d201504615b58da4b39e660a9afdaa547e7c2dd", "extension": "c", "filename": "grading.c", "fork_events_count": 0, "gha_created_at": "2015-06-16T15:54:52", "gha_event_created_at": "2015-09-30T18:12:50", "gha_language": "C++", "gha_license_id": null, "github_id": 37540346, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 552, "license": "Unlicense", "license_type": "permissive", "path": "/Random/grading.c", "provenance": "stackv2-0138.json.gz:139645", "repo_name": "Mugurell/Learning", "revision_date": "2015-09-30T18:12:49", "revision_id": "835a295c060807be9b98ad9bfc3d80f12e2542f5", "snapshot_id": "6e9a20233c6abe4d8b30fadb0275988d6bff70b7", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/Mugurell/Learning/835a295c060807be9b98ad9bfc3d80f12e2542f5/Random/grading.c", "visit_date": "2021-01-19T18:10:43.330159" }
stackv2
/* Grading Program Requires: variables, data types, and numerical operators basic input/output logic (if statements, switch statements) Write a program that allows the user to enter the grade scored in a programming class (0-100). If the user scored a 100 then notify the user that they got a perfect score. ★ Modify the program so that if the user scored a 90-100 it informs the user that they scored an A ★★ Modify the program so that it will notify the user of their letter grade 0-59 F 60-69 D 70-79 C 80-89 B 90-100 A */
3.234375
3
2024-11-18T21:51:12.219348+00:00
2020-01-17T22:54:11
028463a255eab82920b88867973f3a5ef1481d97
{ "blob_id": "028463a255eab82920b88867973f3a5ef1481d97", "branch_name": "refs/heads/master", "committer_date": "2020-01-17T22:54:11", "content_id": "1424858c8f6062ae657b02bc6b4fd0be50c61310", "detected_licenses": [ "MIT" ], "directory_id": "95c16b6aa72d29f1d6e3f6020dfdd86ec5fb553e", "extension": "c", "filename": "string_to_list.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 218406333, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2463, "license": "MIT", "license_type": "permissive", "path": "/lab1_mem_mgmt_and_libs/compiler_optimization/string_to_list.c", "provenance": "stackv2-0138.json.gz:139903", "repo_name": "marwlod/op-sys", "revision_date": "2020-01-17T22:54:11", "revision_id": "42d00838228d792605890716185a344280d92855", "snapshot_id": "f8ae214067a633200e2e46a2a003a03d3f7ecc05", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/marwlod/op-sys/42d00838228d792605890716185a344280d92855/lab1_mem_mgmt_and_libs/compiler_optimization/string_to_list.c", "visit_date": "2020-08-30T14:16:38.966903" }
stackv2
#include <stdio.h> #include <stdlib.h> #include <time.h> #include "utils.c" struct digit { long dig; struct digit *next; }; // transforms number (123456) into list representing number (<root> 6->5->4->3->2->1 <tail>) struct digit *create_num_as_list(struct digit *a, long number) { if (!a) return NULL; struct digit *trav = a; trav->dig = number % 10; number = number / 10; while (number > 0) { trav->next = (struct digit *) malloc(sizeof(struct digit)); trav = trav->next; trav->dig = number % 10; number = number / 10; } trav->next = NULL; return a; } void free_list(struct digit *head) { struct digit *trav = head, *prev = NULL; while (trav) { prev = trav; trav = trav->next; free(prev); } } // adds up two lists representing numbers, e.g. (1<-2<-3) + (2<-3<-4) = (3<-5<-7), stores result in first list void add(struct digit *a, struct digit *b) { if (!a && !b) return; if (!a) { a = (struct digit *) calloc(1, sizeof(struct digit)); } struct digit *travadded = a, *travb = b; long leftover = 0, sum = 0; while (travb || leftover) { sum = travadded->dig + (travb ? travb->dig : 0) + leftover; travadded->dig = sum % 10; leftover = sum / 10; if (travb) travb = travb->next; // if still some more digits to add while no more digits in result if (!travadded->next && (travb || leftover)) { travadded->next = (struct digit *) calloc(1, sizeof(struct digit)); } travadded = travadded->next; } } int main() { struct digit *total = (struct digit *) malloc(sizeof(struct digit)); struct digit *to_add = (struct digit *) malloc(sizeof(struct digit)); total = create_num_as_list(total, 999); to_add = create_num_as_list(to_add, 123456); struct timespec start = {0,0}, end = {0,0}; clock_gettime(CLOCK_REALTIME, &start); // repeat a lot of times to make program last long, thus make it possible to notice potential compiler optimisation // (reduction of program execution duration) for (int i = 0; i < 5*M; i++) { add(total, to_add); } clock_gettime(CLOCK_REALTIME, &end); free_list(total); free_list(to_add); struct timespec duration = calc_duration(start, end); printf("Program duration was %ld secs and %ld nanos\n", duration.tv_sec, duration.tv_nsec); return 0; }
3.3125
3
2024-11-18T21:51:14.230687+00:00
2018-07-23T14:32:23
079b86f63a8704a2c8d4015ce824e6989c64bbe0
{ "blob_id": "079b86f63a8704a2c8d4015ce824e6989c64bbe0", "branch_name": "refs/heads/master", "committer_date": "2018-07-24T13:42:22", "content_id": "f69f9bf7d19d4ed63615d335d867cf2630bed378", "detected_licenses": [ "MIT" ], "directory_id": "1d8ac479f9b53b9d106cf321fd19835eb6ac4f0d", "extension": "h", "filename": "error.h", "fork_events_count": 0, "gha_created_at": "2018-07-12T17:22:27", "gha_event_created_at": "2018-07-24T14:03:40", "gha_language": null, "gha_license_id": "MIT", "github_id": 140744212, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2752, "license": "MIT", "license_type": "permissive", "path": "/error.h", "provenance": "stackv2-0138.json.gz:140943", "repo_name": "Project2100/crypto-sithis", "revision_date": "2018-07-23T14:32:23", "revision_id": "f6f531d1b1bd74b524634cee9862479647fa5e0c", "snapshot_id": "d9eea2f7cb439120ec535672a5704a2f9155f990", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Project2100/crypto-sithis/f6f531d1b1bd74b524634cee9862479647fa5e0c/error.h", "visit_date": "2020-03-22T22:18:05.374800" }
stackv2
/* * File: error.h * Author: Project2100 * Author: llde * Brief: Common includes for all headers * * * Implementation notes: * * - errno is thread-safe since C11: * http://en.cppreference.com/w/c/error/errno * - [WINAPI] GetLastError() is thread-safe: * https://msdn.microsoft.com/en-us/library/windows/desktop/ms679360(v=vs.85).aspx * - [WSA] WSAGetLastError() isn't specified to be thread-safe, but is * reported to be directly related to the former: * https://stackoverflow.com/questions/15586224/is-wsagetlasterror-just-an-alias-for-getlasterror * https://blogs.msdn.microsoft.com/oldnewthing/20050908-19/?p=34283/ * * * Created on 27 September 2017, 17:14 */ #ifndef SITH_COMMON_H #define SITH_COMMON_H #ifdef __cplusplus extern "C" { #endif //------------------------------------------------------------------------------ // INCLUDES #include "plat.h" #include <errno.h> //------------------------------------------------------------------------------ // DEFINITIONS #ifdef _WIN32 typedef struct sith_winerr { int en; DWORD winapi; int wsaapi; } ErrorCode; extern const ErrorCode SITH_E_NONE; extern const ErrorCode SITH_E_NOTFOUND; #define SITH_ISANERROR(code) (((code)).en!=SITH_E_NONE.en || ((code)).wsaapi!=SITH_E_NONE.wsaapi || ((code)).winapi!=SITH_E_NONE.winapi) #define SITH_E_COMPARE(code, target) (((code)).en==((target)).en && ((code)).wsaapi==((target)).wsaapi && ((code)).winapi==((target)).winapi) #elif defined __unix__ typedef int ErrorCode; #define SITH_E_NONE 0 #define SITH_E_NOTFOUND ENOENT #define SITH_ISANERROR(code) (((code)) != SITH_E_NONE) #define SITH_E_COMPARE(code, target) (((code)) == ((target))) #endif //------------------------------------------------------------------------------ // FUNCTIONS /** * Retrieves the current error code and prints a message composed by the * given string and a system message describing the error code to * the error stream. * * @param message */ void HandleErrorStatus(char* message); /** * Gets the last error occurred in the calling thread * * @return */ ErrorCode GetErrorCode(); /** * Resets the error state to no error (SITH_NO_ERROR). */ void ClearErrors(); /** * Checks if the calling thread has unhandled error states * * @return nonzero value if OK, 0 otherwise */ int isSystemAlright(); /** * Sets the calling thread's error state to code * * @param code */ void SetErrorCode(ErrorCode code); /** * Outputs the specified error code to the error stream * * Note: For the purposes of reporting OS failures, invoke HandleErrorStatus(); * * @param message * @param code */ void DisplayError(char* message, ErrorCode code); #ifdef __cplusplus } #endif #endif // SITH_COMMON_H
2.125
2
2024-11-18T21:51:15.103376+00:00
2016-11-06T03:10:47
2e4749e742ccb36de2e0c7bc80161cfc79d70708
{ "blob_id": "2e4749e742ccb36de2e0c7bc80161cfc79d70708", "branch_name": "refs/heads/master", "committer_date": "2016-11-06T03:10:47", "content_id": "bb6d64b54aef08ee6f7634f4d05cb727990042ab", "detected_licenses": [ "MIT", "BSD-2-Clause" ], "directory_id": "bcdf5410cd0d6188ee523e82b95fad77cf08128b", "extension": "c", "filename": "uecc.c", "fork_events_count": 0, "gha_created_at": "2016-11-07T10:06:55", "gha_event_created_at": "2016-11-07T10:06:56", "gha_language": null, "gha_license_id": null, "github_id": 73065689, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 10327, "license": "MIT,BSD-2-Clause", "license_type": "permissive", "path": "/lib/uecc.c", "provenance": "stackv2-0138.json.gz:141202", "repo_name": "mattcaswell/picotls", "revision_date": "2016-11-06T03:10:47", "revision_id": "cda840da3a6e064d32ff60cee8ec54a72a5cfd8c", "snapshot_id": "adab4f2d4be73526655748bd0e19cdeae3eb4ce3", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/mattcaswell/picotls/cda840da3a6e064d32ff60cee8ec54a72a5cfd8c/lib/uecc.c", "visit_date": "2020-12-24T12:13:14.967175" }
stackv2
/* * Copyright (c) 2016 DeNA Co., Ltd., Kazuho Oku * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include "drbg.h" #include "sha2.h" #include "uECC.h" #include "uECC_vli.h" #include "picotls.h" #include "picotls/minicrypto.h" #define SECP256R1_PRIVATE_KEY_SIZE 32 #define SECP256R1_PUBLIC_KEY_SIZE 65 /* including the header */ #define SECP256R1_SHARED_SECRET_SIZE 32 #define TYPE_UNCOMPRESSED_PUBLIC_KEY 4 struct st_secp256r1_key_exhchange_t { ptls_key_exchange_context_t super; uint8_t priv[SECP256R1_PRIVATE_KEY_SIZE]; uint8_t pub[SECP256R1_PUBLIC_KEY_SIZE]; }; static int secp256r1_on_exchange(ptls_key_exchange_context_t *_ctx, ptls_iovec_t *secret, ptls_iovec_t peerkey) { struct st_secp256r1_key_exhchange_t *ctx = (struct st_secp256r1_key_exhchange_t *)_ctx; uint8_t *secbytes = NULL; int ret; if (secret == NULL) { ret = 0; goto Exit; } if (peerkey.len != SECP256R1_PUBLIC_KEY_SIZE || peerkey.base[0] != TYPE_UNCOMPRESSED_PUBLIC_KEY) { ret = PTLS_ALERT_DECRYPT_ERROR; goto Exit; } if ((secbytes = (uint8_t *)malloc(SECP256R1_SHARED_SECRET_SIZE)) == NULL) { ret = PTLS_ERROR_NO_MEMORY; goto Exit; } if (!uECC_shared_secret(peerkey.base + 1, ctx->priv, secbytes, uECC_secp256r1())) { ret = PTLS_ALERT_DECRYPT_ERROR; goto Exit; } *secret = ptls_iovec_init(secbytes, SECP256R1_SHARED_SECRET_SIZE); ret = 0; Exit: if (ret != 0) free(secbytes); ptls_clear_memory(ctx->priv, sizeof(ctx->priv)); free(ctx); return ret; } static int secp256r1_create_key_exchange(ptls_key_exchange_context_t **_ctx, ptls_iovec_t *pubkey) { struct st_secp256r1_key_exhchange_t *ctx; if ((ctx = (struct st_secp256r1_key_exhchange_t *)malloc(sizeof(*ctx))) == NULL) return PTLS_ERROR_NO_MEMORY; ctx->super = (ptls_key_exchange_context_t){secp256r1_on_exchange}; ctx->pub[0] = TYPE_UNCOMPRESSED_PUBLIC_KEY; uECC_make_key(ctx->pub + 1, ctx->priv, uECC_secp256r1()); *_ctx = &ctx->super; *pubkey = ptls_iovec_init(ctx->pub, sizeof(ctx->pub)); return 0; } static int secp256r1_key_exchange(ptls_iovec_t *pubkey, ptls_iovec_t *secret, ptls_iovec_t peerkey) { uint8_t priv[SECP256R1_PRIVATE_KEY_SIZE], *pub = NULL, *secbytes = NULL; int ret; if (peerkey.len != SECP256R1_PUBLIC_KEY_SIZE || peerkey.base[0] != TYPE_UNCOMPRESSED_PUBLIC_KEY) { ret = PTLS_ALERT_DECRYPT_ERROR; goto Exit; } if ((pub = malloc(SECP256R1_PUBLIC_KEY_SIZE)) == NULL) { ret = PTLS_ERROR_NO_MEMORY; goto Exit; } if ((secbytes = malloc(SECP256R1_SHARED_SECRET_SIZE)) == NULL) { ret = PTLS_ERROR_NO_MEMORY; goto Exit; } pub[0] = TYPE_UNCOMPRESSED_PUBLIC_KEY; uECC_make_key(pub + 1, priv, uECC_secp256r1()); if (!uECC_shared_secret(peerkey.base + 1, priv, secbytes, uECC_secp256r1())) { ret = PTLS_ALERT_DECRYPT_ERROR; goto Exit; } *pubkey = ptls_iovec_init(pub, SECP256R1_PUBLIC_KEY_SIZE); *secret = ptls_iovec_init(secbytes, SECP256R1_SHARED_SECRET_SIZE); ret = 0; Exit: ptls_clear_memory(priv, sizeof(priv)); if (ret != 0) { free(secbytes); free(pub); } return ret; } struct st_ptls_minicrypto_identity_t { ptls_iovec_t name; uint8_t key[SECP256R1_PRIVATE_KEY_SIZE]; size_t num_certs; ptls_iovec_t certs[1]; }; static void free_identity(struct st_ptls_minicrypto_identity_t *identity) { size_t i; free(identity->name.base); for (i = 0; i != identity->num_certs; ++i) free(identity->certs[i].base); ptls_clear_memory(identity->key, sizeof(identity->key)); free(identity); } static int ascii_tolower(int ch) { return ('A' <= ch && ch <= 'Z') ? ch + 0x20 : ch; } static int ascii_streq_caseless(ptls_iovec_t x, ptls_iovec_t y) { size_t i; if (x.len != y.len) return 0; for (i = 0; i != x.len; ++i) if (ascii_tolower(x.base[i]) != ascii_tolower(y.base[i])) return 0; return 0; } static int secp256r1sha256_sign(void *data, ptls_buffer_t *outbuf, ptls_iovec_t input) { uint8_t hash[32], sig[64]; int ret; { /* calc hash */ cf_sha256_context ctx; cf_sha256_init(&ctx); cf_sha256_update(&ctx, input.base, input.len); cf_sha256_digest_final(&ctx, hash); ptls_clear_memory(&ctx, sizeof(ctx)); } /* sign */ uECC_sign(data, hash, sizeof(hash), sig, uECC_secp256r1()); /* encode using DER */ ptls_buffer_push_asn1_sequence(outbuf, { if ((ret = ptls_buffer_push_asn1_ubigint(outbuf, sig, 32)) != 0) goto Exit; if ((ret = ptls_buffer_push_asn1_ubigint(outbuf, sig + 32, 32)) != 0) goto Exit; }); ret = 0; Exit: ptls_clear_memory(hash, sizeof(hash)); ptls_clear_memory(sig, sizeof(sig)); return ret; } static int lookup_certificate(ptls_lookup_certificate_t *_self, ptls_t *tls, uint16_t *sign_algorithm, int (**signer)(void *sign_ctx, ptls_buffer_t *outbuf, ptls_iovec_t input), void **signer_data, ptls_iovec_t **certs, size_t *num_certs, const char *server_name, const uint16_t *signature_algorithms, size_t num_signature_algorithms) { ptls_minicrypto_lookup_certificate_t *self = (ptls_minicrypto_lookup_certificate_t *)_self; struct st_ptls_minicrypto_identity_t *identity; size_t i; if (self->count == 0) return PTLS_ALERT_HANDSHAKE_FAILURE; for (i = 0; i != num_signature_algorithms; ++i) if (signature_algorithms[i] == PTLS_SIGNATURE_ECDSA_SECP256R1_SHA256) goto FoundMatchingSig; return PTLS_ALERT_HANDSHAKE_FAILURE; FoundMatchingSig: if (server_name != NULL) { size_t server_name_len = strlen(server_name); for (i = 0; i != self->count; ++i) { identity = self->identities[i]; if (ascii_streq_caseless(ptls_iovec_init(server_name, server_name_len), identity->name)) goto FoundIdentity; } } identity = self->identities[0]; /* use default */ FoundIdentity: /* setup the rest */ *sign_algorithm = PTLS_SIGNATURE_ECDSA_SECP256R1_SHA256; *signer = secp256r1sha256_sign; *signer_data = identity->key; *certs = identity->certs; *num_certs = identity->num_certs; return 0; } void ptls_minicrypto_init_lookup_certificate(ptls_minicrypto_lookup_certificate_t *self) { *self = (ptls_minicrypto_lookup_certificate_t){{lookup_certificate}}; } void ptls_minicrypto_dispose_lookup_certificate(ptls_minicrypto_lookup_certificate_t *self) { size_t i; for (i = 0; i != self->count; ++i) free_identity(self->identities[i]); } int ptls_minicrypto_lookup_certificate_add_identity(ptls_minicrypto_lookup_certificate_t *self, const char *server_name, uint16_t signature_algorithm, ptls_iovec_t key, ptls_iovec_t *certs, size_t num_certs) { struct st_ptls_minicrypto_identity_t *identity = NULL, **list; int ret; /* check args */ if (!(signature_algorithm == PTLS_SIGNATURE_ECDSA_SECP256R1_SHA256 && key.len == sizeof(identity->key))) { ret = PTLS_ERROR_INCOMPATIBLE_KEY; goto Exit; } /* create new identity object */ if ((identity = (struct st_ptls_minicrypto_identity_t *)malloc(offsetof(struct st_ptls_minicrypto_identity_t, certs) + sizeof(identity->certs[0]) * num_certs)) == NULL) { ret = PTLS_ERROR_NO_MEMORY; goto Exit; } *identity = (struct st_ptls_minicrypto_identity_t){{NULL}}; if ((identity->name.base = (uint8_t *)strdup(server_name)) == NULL) { ret = PTLS_ERROR_NO_MEMORY; goto Exit; } identity->name.len = strlen(server_name); memcpy(identity->key, key.base, key.len); for (; identity->num_certs != num_certs; ++identity->num_certs) { if ((identity->certs[identity->num_certs].base = (uint8_t *)malloc(certs[identity->num_certs].len)) == NULL) { ret = PTLS_ERROR_NO_MEMORY; goto Exit; } memcpy(identity->certs[identity->num_certs].base, certs[identity->num_certs].base, certs[identity->num_certs].len); identity->certs[identity->num_certs].len = certs[identity->num_certs].len; } /* add to the list */ if ((list = realloc(self->identities, sizeof(self->identities[0]) * (self->count + 1))) == NULL) { ret = PTLS_ERROR_NO_MEMORY; goto Exit; } self->identities = list; self->identities[self->count++] = identity; ret = 0; Exit: if (ret != 0 && identity != NULL) free_identity(identity); return ret; } ptls_key_exchange_algorithm_t ptls_minicrypto_secp256r1 = {PTLS_GROUP_SECP256R1, secp256r1_create_key_exchange, secp256r1_key_exchange}; ptls_key_exchange_algorithm_t *ptls_minicrypto_key_exchanges[] = {&ptls_minicrypto_secp256r1, NULL};
2
2
2024-11-18T21:51:15.725682+00:00
2012-02-09T14:58:18
3e068b546860983dff4336eb54c6e9b905a8a807
{ "blob_id": "3e068b546860983dff4336eb54c6e9b905a8a807", "branch_name": "refs/heads/master", "committer_date": "2012-02-09T14:58:18", "content_id": "7d3b52eba0fb48242182e3a7628453ab1cd252d8", "detected_licenses": [ "MIT" ], "directory_id": "89d98e05bcda9007f5af2c093d5575d954ea2e02", "extension": "h", "filename": "lista.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 3397921, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 622, "license": "MIT", "license_type": "permissive", "path": "/Tarea1/lista.h", "provenance": "stackv2-0138.json.gz:141589", "repo_name": "sagmor/CC31A-Primavera-2007-UChile", "revision_date": "2012-02-09T14:58:18", "revision_id": "18287ce32060b3336f6c32a3fd965d9b36b39c9c", "snapshot_id": "1777400a6fd02275d00d71febb8a692680cb7551", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/sagmor/CC31A-Primavera-2007-UChile/18287ce32060b3336f6c32a3fd965d9b36b39c9c/Tarea1/lista.h", "visit_date": "2021-01-10T21:07:00.276879" }
stackv2
/* * Lista simplemente enlazada */ #ifndef LISTA_HEADER_SEEN #define LISTA_HEADER_SEEN struct nodo { struct nodo *next; void *value; }; typedef struct { struct nodo *header; struct nodo *current; } LISTA; /* inicializa una nueva lista vacía */ LISTA *init_l(); /* agrega el elemento p al comienzo de la lista l */ LISTA *cons_l(void *p, LISTA *l); /* Retorna el elemento más nuevo de la lista y se posiciona al comienzo */ void *first_l(LISTA *l); /* Retorna el elemento siguiente de la lista */ void *next_l(LISTA *l); /* Libera la lista completa */ void free_l(LISTA *l); #endif
2.5625
3
2024-11-18T21:51:15.970237+00:00
2020-12-20T14:44:33
1eeb26e7d6ce98e211f8ed99756593205932ea94
{ "blob_id": "1eeb26e7d6ce98e211f8ed99756593205932ea94", "branch_name": "refs/heads/master", "committer_date": "2020-12-20T14:44:33", "content_id": "322833339724acfb1e16b0fab70da2f14ad95eeb", "detected_licenses": [ "MIT" ], "directory_id": "f0139a7135c3454b6b3948259eb034661764ebb0", "extension": "c", "filename": "fat32.c", "fork_events_count": 2, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 182635287, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 28265, "license": "MIT", "license_type": "permissive", "path": "/src/fs/fat32.c", "provenance": "stackv2-0138.json.gz:141849", "repo_name": "sxysxy/Taurix", "revision_date": "2020-12-20T14:44:33", "revision_id": "478174a62ace8f66d43629d1226113f422bb68ce", "snapshot_id": "967b20ab945f16e9aefb5137530246f063180054", "src_encoding": "UTF-8", "star_events_count": 10, "url": "https://raw.githubusercontent.com/sxysxy/Taurix/478174a62ace8f66d43629d1226113f422bb68ce/src/fs/fat32.c", "visit_date": "2021-06-25T20:33:52.505470" }
stackv2
#include "fat32.h" static inline uint64 cluster2lba(FAT32Tool *fat, uint32 cluster) { uint64 data_lba = fat->fat_lba + fat->num_fat * fat->sectors_per_fat; return data_lba + (cluster-2) * fat->sectors_per_cluster; //(cluster-2)而不是cluster,因为前两个簇被保留了。FAT32只是保留前2个FAT表项,并不保留前两个簇。 //gtmd被wiki的中文翻译坑了。。。 } //将fat表第fatid项的值设置为newid,如果newid小于0则不改变fatid项上的数值,为0是空闲簇 //如果oldid不为空指针,会设置通过这个参数返回这个表项上原本的数值 static int set_fat_next(FAT32Tool *fat, uint32 fatid, uint32 *oldid, int newid) { uint64 lba = fat->fat_lba + fatid / 128; if(lba < fat->fat_lba || lba >= fat->fat_lba + fat->sectors_per_fat) return ERROR_TFS_INVALID_ARGUMENT; fat->fs.io.read_lba(lba, lba, fat->sector_buffer); uint32* fats = (uint32*)fat->sector_buffer; if(oldid) *oldid = fats[fatid % 128]; if(newid >= 0) { fats[fatid % 128] = newid; for(int i = 0; i < fat->num_fat; i++) { //写回修改后的fat表项 fat->fs.io.write_lba(lba + fat->sectors_per_fat * i, lba + fat->sectors_per_fat * i, fat->sector_buffer); } } return STATUS_SUCCESS; } static uint32 __find_next_free_item(FAT32Tool *fat) { static uint32 fatid = 0; //查找的起点 int wrapped = 0; //回头从前面找过的标记 while(1) { int flag = 0; uint64 lba = fat->fat_lba + fatid / 128; fat->fs.io.read_lba(lba, lba, fat->sector_buffer); uint32 *fats = (uint32*)fat->sector_buffer; int offset = 0; for(int i = fatid % 128; i < 128; i++) { if(!fats[i]) { flag = 1; offset = i; break; } else fatid++; } if(flag) { //已找到 return fatid; //返回fat表项的id,也即空闲簇的簇号 } else { lba++; if(lba == fat->fat_lba + fat->sectors_per_fat) { if(!wrapped) { fatid = 0; wrapped = 1; continue; } else { break; //确实没有空闲表项了 } } } } return 0; } //找到一个空闲表项(空闲簇),分配掉,返回编号,如果返回0表示fat表被分配完 static uint32 alloc_fat_item(FAT32Tool *fat) { const uint32 cluster = fat->fsinfo.next_free_cluster; if(cluster) { const uint64 lba = fat->fat_lba + cluster / 128; //因为一个扇区有128个FAT表项 fat->fs.io.read_lba(lba, lba, fat->sector_buffer); uint32 *fats = (uint32*)fat->sector_buffer; fats[cluster % 128] = FAT32_FILE_END; fat->fs.io.write_lba(lba, lba, fat->sector_buffer); //写回 fat->fsinfo.next_free_cluster = __find_next_free_item(fat); fat->fsinfo.free_clusters--; } return cluster; } int fat32_fstool_initialize(FAT32Tool *fat, FSIO io, uint64 start_lba, uint64 end_lba) { fat->fs.io = io; if(start_lba > end_lba) return ERROR_TFS_INVALID_ARGUMENT; fat->fs.start_lba = start_lba; fat->fs.end_lba = end_lba; fat->fs.create_file = fat32_create_file; fat->fs.delete_file = fat32_delete_file; fat->fs.makefs = fat32_makefs; fat->fs.enum_dir = fat32_enum_dir; fat->fs.query_file_info = fat32_query_file_info; fat->fs.create_file = fat32_create_file; fat->fs.delete_file = fat32_delete_file; fat->fs.fread = fat32_fread; fat->fs.fwrite = fat32_fwrite; fat->fs.fseek = fat32_fseek; fat->fs.sync_information = fat32_sync_information; FAT32Header header; fat->fs.io.read_lba(start_lba, start_lba, &header); fat->is_valid_fat32 = memcmp("FAT32", header.fat32, 5) == 0; fat->fat_lba = fat->fs.start_lba + header.num_reserved; fat->num_fat = header.num_fat; fat->sectors_per_fat = header.sectors_per_fat32; fat->sectors_per_cluster = header.sectors_per_clust; fat->root_dir_cluster = header.root_dir_start; //fat->root_dir_cluster = 0; //fsinfo if(header.fsinfo) { fat->fs.io.read_lba(start_lba + header.fsinfo, start_lba + header.fsinfo, &fat->fsinfo ); } if(fat->sectors_per_cluster > 8) { //大于8不支持鸭 return ERROR_TFS_UNSUPPORTED_FEATURE; } if(((uint64)fat->sectors_per_fat) * 512 / 4 > 0xfffffef) { return ERROR_TFS_NO_SPACE; //fat表表项太多 } return STATUS_SUCCESS; } int fat32_makefs(struct tagFSTool *fs) { FAT32Tool *fat = ((FAT32Tool*)fs); if(fs->end_lba - fs->start_lba + 1 < 4000) return ERROR_TFS_NO_SPACE; if(fs->end_lba - fs->start_lba + 1 > 0xffffffffu) //太大 return ERROR_TFS_NO_SPACE; { FAT32Header header; memset(&header, 0, sizeof(header)); memcpy(header.jmp, "\xeb\x58\x90", 3); memcpy(header.OEM, "tfstool", 8); header.bytes_per_sector = 512; //header.sectors_per_clust = 8; //4kb header.sectors_per_clust = 1; header.num_reserved = 32; header.num_fat = 2; //两个fat表 header.material = 0xf8; header.num_sectors = fs->end_lba - fs->start_lba + 1; //s <- end_lba - start_lba + 1 - num_reserved //t <- sectors_per_clust //num_fat = 2 //x <- sectors_per_fat32 //sectors_per_clust //s - 2 * x = x * (512/4) * t // x = s / (128*t + 2) header.sectors_per_fat32 = (uint32)(fs->end_lba - fs->start_lba + 1 - header.num_reserved) / (128*header.sectors_per_clust+2) - 1; if(header.sectors_per_fat32 < header.num_fat + 1) return ERROR_TFS_NO_SPACE; header.root_dir_start = 2; // header.fsinfo = 1; header.backup = 2; header.device_code = 0x80; memcpy(header.fat32, "FAT32", 5); header.aa55 = 0xaa55; fs->io.write_lba(fs->start_lba, fs->start_lba, &header); fs->io.write_lba(fs->start_lba+2, fs->start_lba+2, &header); //备份引导扇区 //fsinfo: fat->fsinfo.aa55 = 0xaa55; fat->fsinfo.x41615252 = 0x41615252; fat->fsinfo.x61417272 = 0x61417272; fat->fsinfo.free_clusters = (uint32)((fs->end_lba - fs->start_lba + 1) - header.sectors_per_fat32 * header.num_fat) / header.sectors_per_clust; //fat->fsinfo.next_free_cluster = header.root_dir_start + 1; fat->fsinfo.next_free_cluster = 5; fs->io.write_lba(fs->start_lba+1, fs->start_lba+1, &fat->fsinfo); } //在这之前fat结构体内的成员大都是不可用的 int e = fat32_fstool_initialize(fat, fs->io, fs->start_lba, fs->end_lba); //偷个懒,直接调用它... if(e) return e; { unsigned char init_fat[512]; memset(init_fat, 0, sizeof(init_fat)); //0号项 init_fat[0] = 0xf8; init_fat[1] = 0xff; init_fat[2] = 0xff; init_fat[3] = 0x0f; //1号项 init_fat[4] = 0xf8; init_fat[5] = 0xff; init_fat[6] = 0xff; init_fat[7] = 0x0f; //根目录项 init_fat[8] = 0xff; init_fat[9] = 0xff; init_fat[10] = 0xff; init_fat[11] = 0x0f; fs->io.write_lba(fat->fat_lba, fat->fat_lba, init_fat); //FAT1 fs->io.write_lba(fat->fat_lba + fat->sectors_per_fat, fat->fat_lba + fat->sectors_per_fat, init_fat); //FAT2 } return e; } //创建无文件的文件系统 #define CHECK_FS if(!fat->is_valid_fat32) {return ERROR_TFS_INVALID_FS; } #define HANDLE_CLUSTER(h) ((h) & 0x00000000ffffffffull) #define HANDLE_OFFSET(h) (((h) & 0xffffffff00000000ull) >> 32) #define MAKE_CLUSTER_OFFSET_HANDLE(cl, of) (((FileHandle)(of) << 32) | (cl)) //FileItem可被占用 #define ITEM_AVAILABLE(x) (x.attribute == 0 || x.dosname[0] == 0xe5) //将FileInfo指示的信息转变为Fat文件系统的文件信息,返回错误信息 static inline int FileInfoToFat(FileInfo *info, FAT32FileItem *item, uint32 first_cluster) { int name_len = strlen(info->name_char); int i; for(i = name_len - 1; ~i; i--) { if(info->name_char[i] == '.') { //找最后一个 . if(i <= 7) { if(name_len - i - 1 > 3) { return ERROR_TFS_INVALID_FILENAME; //扩展名太长 } else { break; } } else { return ERROR_TFS_INVALID_FILENAME; //文件名太长 } } } if(i < 0) { //没有扩展名 if(name_len > 8) return ERROR_TFS_INVALID_FILENAME; //太长 strcpy((char*)item->dosname, info->name_char); for(i = name_len; i < 8; i++) { //空格补齐 item->dosname[i] = ' '; } memset(item->dosname_ext, ' ', sizeof(item->dosname_ext)); } else { if(i > 8) return ERROR_TFS_INVALID_FILENAME; //太长 strncpy((char*)item->dosname, info->name_char, i); for(int j = i; j < 8; j++) item->dosname[j] = ' '; int ext_len = name_len - i - 1; strncpy((char*)item->dosname_ext, info->name_char+i+1, ext_len); for(int j = ext_len; j < 3; j++) item->dosname_ext[j] = ' '; //补空格 } item->attribute = 0; if(info->attributes & FILE_ATTRIBUTE_READONLY) item->attribute |= 0x01; if(info->attributes & FILE_ATTRIBUTE_HIDDEN) item->attribute |= 0x02; if(info->attributes & FILE_ATTRIBUTE_SYSTEM) item->attribute |= 0x04; if(info->is_directory) { item->attribute |= 0x10; } else { item->attribute |= 0x20; } if(info->attributes & FILE_ATTRIBUTE_DEVICE) item->attribute |= 0x40; item->create_time_ymd = (((info->created_year - 1980) & 0x7f) << 9) | (info->created_month << 5) | (info->created_day); item->create_time_hmsdiv2 = (info->created_hour << 11) | (info->created_minute << 5) | (info->created_second / 2); item->create_time_in2s = (info->created_second & 1) * 100; item->access_time_ymd = (((info->access_year - 1980) & 0x7f) << 9) | (info->access_month << 5) | (info->access_day); item->modify_time_ymd = (((info->modify_year - 1980) & 0x7f) << 9) | (info->modify_month << 5) | (info->modify_day); item->modify_time_hmsdiv2 = (info->modify_hour << 11) | (info->modify_minute << 5) | (info->modify_second / 2); if(info->file_size_in_bytes > 0xffffffffu) return ERROR_TFS_NO_SPACE; //文件太大。。。 item->file_size_in_byte = info->file_size_in_bytes; item->first_cluster_low = first_cluster & 0x0000ffff; item->first_cluster_hight = (first_cluster & 0xffff0000u) >> 16; return STATUS_SUCCESS; } //Fat32目录项 -> 标准FileInfo,无需返回值 void FileItemToFileInfo(FAT32Tool *fat, FAT32FileItem *item, FileInfo *info) { //size info->file_size_in_bytes = item->file_size_in_byte; int size_per_cluster = (512 * fat->sectors_per_cluster); info->file_occupies_in_bytes = item->file_size_in_byte % size_per_cluster ? (item->file_size_in_byte / size_per_cluster + 1) * size_per_cluster : item->file_size_in_byte; //attribute if(item->attribute & 0x10) { info->is_directory = 1; } else info->is_directory = 0; if(item->attribute & 0x40) info->attributes |= FILE_ATTRIBUTE_DEVICE; if(item->attribute & 0x01) info->attributes |= FILE_ATTRIBUTE_READONLY; if(item->attribute & 0x02) info->attributes |= FILE_ATTRIBUTE_HIDDEN; if(item->attribute & 0x04) info->attributes |= FILE_ATTRIBUTE_SYSTEM; //name int name_len = 8; for(name_len--; name_len >= 0 && item->dosname[name_len] == ' '; name_len--); name_len++; memcpy(info->name_char, (const void*)item->dosname, name_len); info->name_char[name_len] = 0; int ext_len = 3; for(ext_len--; ext_len>=0 && item->dosname_ext[ext_len] == ' '; ext_len--); ext_len++; if(ext_len) { strcat(info->name_char, "."); memcpy(info->name_char + name_len + 1, item->dosname_ext, ext_len); info->name_char[name_len + 1 + ext_len] = 0; } //TODO: 日期信息,太智障了不想做了。。。恶心死了 info->access_ymdhms = 0; info->modify_ymdhms = 0; info->created_ymdhms = 0; //return; } static inline uint64 __u64min(uint64 x, uint64 y) { return x < y ? x : y; } int fat32_create_file(struct tagFSTool *fs, FSHandle dir, FileInfo *info, FSHandle *handle) { FAT32Tool *fat = ((FAT32Tool*)fs); CHECK_FS int num = fat->sectors_per_cluster * 0x200 / 0x20; //单个簇内目录项个数 uint64 current_cluster; if(dir != FSTOOL_INVALID_HANDLE) { current_cluster = HANDLE_CLUSTER(dir); fs->io.read_lba(cluster2lba(fat, current_cluster), cluster2lba(fat, current_cluster) + fat->sectors_per_cluster - 1, fat->cluster_buffer); uint64 idx = HANDLE_OFFSET(dir); FAT32FileItem *items = (FAT32FileItem*) fat->cluster_buffer; if(idx >= num || idx < 0) return ERROR_TFS_INVALID_HANDLE; if(!(items[idx].attribute & 0x10)) { //不是目录项 return ERROR_TFS_INVALID_HANDLE; } current_cluster = items[idx].first_cluster_low | (items[idx].first_cluster_hight << 16); } else { current_cluster = fat->root_dir_cluster; } { fs->io.read_lba(cluster2lba(fat, current_cluster), cluster2lba(fat, current_cluster) + fat->sectors_per_cluster - 1, fat->cluster_buffer); FAT32FileItem *items = (FAT32FileItem *)fat->cluster_buffer; while(1) { int flag = 0; int i; for(i = 0; i < num; i++) { if(ITEM_AVAILABLE(items[i])) { flag = 1; break; } } if(flag) { //找到空目录项 uint32 free_cluster = alloc_fat_item(fat); //为新文件分配一个簇 if(!free_cluster) return ERROR_TFS_NO_SPACE; int err = FileInfoToFat(info, items+i, free_cluster); if(err) return err; fs->io.write_lba(cluster2lba(fat, current_cluster), cluster2lba(fat, current_cluster) + fat->sectors_per_cluster - 1, fat->cluster_buffer); if(handle) { *handle = MAKE_CLUSTER_OFFSET_HANDLE(current_cluster, i); //文件记录占用当前簇的第i个表项 } if(info->is_directory) { //创建的是子目录,在所创建的目录中创建'.'和'..'的文件记录 memset(fat->sector_buffer, 0, sizeof(fat->sector_buffer)); items = (FAT32FileItem *)fat->sector_buffer; memset(items, 0x20, sizeof(FAT32FileItem)); memset(items+1, 0x20, sizeof(FAT32FileItem)); items[0].dosname[0] = 0x2e; items[1].dosname[0] = 0x2e; items[1].dosname[1] = 0x2e; items[0].attribute = 0x10; items[1].attribute = 0x10; fs->io.write_lba(cluster2lba(fat, free_cluster), cluster2lba(fat, free_cluster), fat->sector_buffer); } return STATUS_SUCCESS; } else { uint32 next_cluster; set_fat_next(fat, current_cluster, &next_cluster, -1); if(FAT32_IS_END_CLUSTAR(next_cluster)) { uint32 free_cluster = alloc_fat_item(fat); //新开一个簇储存目录内的信息,那么下一次一定可以找得到。。。 if(!free_cluster) return ERROR_TFS_NO_SPACE; set_fat_next(fat, current_cluster, NULL, free_cluster); current_cluster = free_cluster; } else { current_cluster = next_cluster; } } } } return STATUS_SUCCESS; } //创建文件 int fat32_delete_file(struct tagFSTool *fs, FSHandle target) { FAT32Tool *fat = ((FAT32Tool*)fs); CHECK_FS int num = fat->sectors_per_cluster * 0x200 / 0x20; //单个簇内目录项个数 if(target == FSTOOL_INVALID_HANDLE) { return ERROR_TFS_INVALID_HANDLE; } uint64 current_cluster = HANDLE_CLUSTER(target); //进入目录所在簇,得到对应目录项 { fs->io.read_lba(cluster2lba(fat, current_cluster), cluster2lba(fat, current_cluster) + fat->sectors_per_cluster - 1, fat->cluster_buffer); uint64 idx = HANDLE_OFFSET(target); FAT32FileItem *items = (FAT32FileItem*) fat->cluster_buffer; if(idx >= num || idx < 0) return ERROR_TFS_INVALID_HANDLE; items[idx].dosname[0] = 0xe5; //标记删除 fs->io.write_lba(cluster2lba(fat, current_cluster), cluster2lba(fat, current_cluster) + fat->sectors_per_cluster - 1, fat->cluster_buffer); } return STATUS_SUCCESS; } //删除文件 int fat32_query_file_info(struct tagFSTool *fs, FSHandle file, FileInfo *info) { FAT32Tool *fat = ((FAT32Tool*)fs); CHECK_FS int num = fat->sectors_per_cluster * 0x200 / 0x20; //单个簇内目录项个数 if(file == FSTOOL_INVALID_HANDLE) { return ERROR_TFS_INVALID_HANDLE; } uint64 current_cluster = HANDLE_CLUSTER(file); { fs->io.read_lba(cluster2lba(fat, current_cluster), cluster2lba(fat, current_cluster) + fat->sectors_per_cluster - 1, fat->cluster_buffer); uint64 idx = HANDLE_OFFSET(file); FAT32FileItem *items = (FAT32FileItem*) fat->cluster_buffer; if(idx >= num || idx < 0) return ERROR_TFS_INVALID_HANDLE; FileItemToFileInfo(fat, &items[idx], info); } return STATUS_SUCCESS; } FSHandle fat32_enum_dir(struct tagFSTool *fs, FSHandle dir, FSHandle last, FileInfo *info){ FAT32Tool *fat = ((FAT32Tool*)fs); if(!fat->is_valid_fat32) return 0; int num = fat->sectors_per_cluster * 0x200 / 0x20; //单个簇内目录项个数 uint32 cluster; uint32 offset; if(FSTOOL_INVALID_HANDLE == last) { //第一次 if(dir != FSTOOL_INVALID_HANDLE) { uint64 current_cluster = dir ? HANDLE_CLUSTER(dir) : fat->root_dir_cluster; fs->io.read_lba(cluster2lba(fat, current_cluster), cluster2lba(fat, current_cluster) + fat->sectors_per_cluster - 1, fat->cluster_buffer); uint64 idx = HANDLE_OFFSET(dir); FAT32FileItem *items = (FAT32FileItem*) fat->cluster_buffer; if(idx >= num || idx < 0) return ERROR_TFS_INVALID_HANDLE; if(!(items[idx].attribute & 0x10)) //不是目录项 return FSTOOL_INVALID_HANDLE; current_cluster = items[idx].first_cluster_low | (items[idx].first_cluster_hight << 16); cluster = current_cluster; offset = 0; } else { cluster = fat->root_dir_cluster; offset = 0; } } else { //不是第一次,接着上次的Handle(last)往后 cluster = HANDLE_CLUSTER(last); offset = HANDLE_OFFSET(last) + 1; if(offset == num) { //跳到指向的下一块cluster uint32 next_cluster; set_fat_next(fat, cluster, &next_cluster, -1); cluster = next_cluster; if(FAT32_IS_END_CLUSTAR(cluster)) { //到目录项最后一个簇了 return FSTOOL_INVALID_HANDLE; } offset = 0; } } if(offset < 0 || offset >= num) return FSTOOL_INVALID_HANDLE; //判断是否到末尾 fs->io.read_lba(cluster2lba(fat, cluster), cluster2lba(fat, cluster) + fat->sectors_per_cluster - 1, fat->cluster_buffer); FAT32FileItem *items = (FAT32FileItem *)fat->cluster_buffer; if(items[offset].dosname[0] != 0xe5 && items[offset].attribute) { //有效 //返回指向它的句柄 if(info) { FileItemToFileInfo(fat, items + offset, info); } return MAKE_CLUSTER_OFFSET_HANDLE(cluster, offset); //返回指向下一个文件的句柄 } else { //无效 return FSTOOL_INVALID_HANDLE; } } //列举目录dir内文件(包括子目录),第一次last为NULL uint64 fat32_fread(struct tagFSTool *fs, FSHandle file, const void *buffer, uint64 buffer_size, FSHandle *offset_handle) { FAT32Tool *fat = ((FAT32Tool*)fs); if(!fat->is_valid_fat32) return 0; if(file == FSTOOL_INVALID_HANDLE) return 0; //复制粘贴过来的呀 uint64 file_size; uint32 cluster, foffset; { const int num = fat->sectors_per_cluster * 0x200 / 0x20; //单个簇内目录项个数 cluster = HANDLE_CLUSTER(file); fs->io.read_lba(cluster2lba(fat, cluster), cluster2lba(fat, cluster) + fat->sectors_per_cluster - 1, fat->cluster_buffer); uint64 idx = HANDLE_OFFSET(file); FAT32FileItem *items = (FAT32FileItem*) fat->cluster_buffer; if(idx >= num || idx < 0) return ERROR_TFS_INVALID_HANDLE; file_size = items[idx].file_size_in_byte; cluster = items[idx].first_cluster_low | (items[idx].first_cluster_hight << 16); foffset = 0; } const uint32 cluster_size = fat->sectors_per_cluster * 0x200; if(*offset_handle) { //从偏移位置继续 cluster = HANDLE_CLUSTER(*offset_handle); foffset = HANDLE_OFFSET(*offset_handle); } uint32 offset = foffset % cluster_size; //这个offset是簇内偏移量 uint64 buffer_offset = 0; //buffer_offset同时也等于已读取的字节数 int is_new = 0; //当前簇是整块的簇的标记 while(buffer_offset < buffer_size && foffset < file_size) { uint64 read_size = 0; //本次读取的大小 if(!is_new) { read_size = __u64min(buffer_size - buffer_offset, cluster_size - offset); //min(剩余数据量, 簇剩余空间) read_size = __u64min(read_size, file_size - foffset); //再与文件剩余字节数比较 } else { //整块的簇,直接从头开始读 read_size = __u64min(cluster_size, buffer_size - buffer_offset); read_size = __u64min(read_size, file_size - foffset); } fs->io.read_lba(cluster2lba(fat, cluster), cluster2lba(fat, cluster) + fat->sectors_per_cluster - 1, fat->cluster_buffer); memcpy((char*)buffer + buffer_offset, &fat->cluster_buffer[offset], read_size); offset = (uint32)(offset + read_size) % cluster_size; buffer_offset += read_size; if(buffer_offset >= buffer_size || foffset >= file_size) break; if(!offset) { //找下一块簇 uint32 next_cluster; set_fat_next(fat, cluster, &next_cluster, -1); if(FAT32_IS_END_CLUSTAR(next_cluster)) { //往后没有了 break; } else { cluster = next_cluster; } } } *offset_handle = MAKE_CLUSTER_OFFSET_HANDLE(cluster, foffset + buffer_offset); return buffer_offset; } //offset_handle组成: //簇号和相对于文件第0个字节的偏移量。 uint64 fat32_fwrite(struct tagFSTool *fs, FSHandle file, const void *data, uint64 data_size, FSHandle *offset_handle) { FAT32Tool *fat = ((FAT32Tool*)fs); if(!fat->is_valid_fat32) return 0; if(file == FSTOOL_INVALID_HANDLE) return 0; //复制粘贴过来的呀 uint64 file_size; uint32 cluster, foffset; { const int num = fat->sectors_per_cluster * 0x200 / 0x20; //单个簇内目录项个数 cluster = HANDLE_CLUSTER(file); fs->io.read_lba(cluster2lba(fat, cluster), cluster2lba(fat, cluster) + fat->sectors_per_cluster - 1, fat->cluster_buffer); uint64 idx = HANDLE_OFFSET(file); FAT32FileItem *items = (FAT32FileItem*) fat->cluster_buffer; if(idx >= num || idx < 0) return ERROR_TFS_INVALID_HANDLE; file_size = items[idx].file_size_in_byte; cluster = items[idx].first_cluster_low | (items[idx].first_cluster_hight << 16); foffset = 0; } const uint32 cluster_size = fat->sectors_per_cluster * 0x200; if(*offset_handle) { //从偏移位置继续 cluster = HANDLE_CLUSTER(*offset_handle); foffset = HANDLE_OFFSET(*offset_handle); } uint32 offset = foffset % cluster_size; //这个offset是簇内偏移量 uint64 buffer_offset = 0; //buffer_offset同时也等于已写入的字节数 int is_new = 0; //当前簇是新开的簇的标记 while(buffer_offset < data_size) { //int is_last = data_size - buffer_offset <= cluster_size; //当前簇是要写入的最后一块的标记 uint64 write_size = 0; //本次写入的大小 if(!is_new) { //先尽量把这个簇写满 fs->io.read_lba(cluster2lba(fat, cluster), cluster2lba(fat ,cluster) + fat->sectors_per_cluster - 1, fat->cluster_buffer); write_size = __u64min(data_size - buffer_offset, cluster_size - offset); //min(剩余数据量, 簇剩余空间) memcpy(&fat->cluster_buffer[offset], (char*)data + buffer_offset, write_size); } else { //新的簇,直接从头开始写 write_size = __u64min(cluster_size, data_size - buffer_offset); memcpy(fat->cluster_buffer, (char*)data + buffer_offset, write_size); } offset = (uint32)(offset + write_size) % cluster_size; fs->io.write_lba(cluster2lba(fat, cluster), cluster2lba(fat, cluster) + fat->sectors_per_cluster - 1, fat->cluster_buffer); buffer_offset += write_size; if(buffer_offset >= data_size) break; if(!offset && foffset >= file_size) { //新开块 uint32 new_cluster = alloc_fat_item(fat); if(!new_cluster) break; set_fat_next(fat, cluster, NULL, new_cluster); cluster = new_cluster; is_new = 1; } } //重算文件大小 uint32 add_bytes = data_size - (file_size - foffset); file_size += add_bytes; { uint32 tmp = HANDLE_CLUSTER(file), idx = HANDLE_OFFSET(file); fs->io.read_lba(cluster2lba(fat, tmp), cluster2lba(fat, tmp) + fat->sectors_per_cluster - 1, fat->cluster_buffer); FAT32FileItem *items = (FAT32FileItem*)fat->cluster_buffer; items[idx].file_size_in_byte = file_size; fs->io.write_lba(cluster2lba(fat, tmp), cluster2lba(fat, tmp) + fat->sectors_per_cluster - 1, fat->cluster_buffer); } *offset_handle = MAKE_CLUSTER_OFFSET_HANDLE(cluster, foffset + buffer_offset); return buffer_offset; } int fat32_fseek(struct tagFSTool *fs, FSHandle file, uint64 offset, FSHandle *offset_handle) { FAT32Tool *fat = ((FAT32Tool*)fs); CHECK_FS return ERROR_TFS_NO_IMPLEMENT; } //主要是同步fsinfo int fat32_sync_information(struct tagFSTool *fs) { FAT32Tool *fat = ((FAT32Tool*)fs); fat->fs.io.read_lba(fs->start_lba, fs->start_lba, fat->sector_buffer); FAT32Header *header = (FAT32Header *)fat->sector_buffer; fat->fs.io.write_lba(fs->start_lba + header->fsinfo, fs->start_lba + header->fsinfo, &fat->fsinfo); return STATUS_SUCCESS; }
2.78125
3
2024-11-18T21:51:49.264829+00:00
2023-01-09T16:20:48
1039a813f15ff76450943fb41448ebdcc1cad6e8
{ "blob_id": "1039a813f15ff76450943fb41448ebdcc1cad6e8", "branch_name": "refs/heads/master", "committer_date": "2023-01-09T16:20:48", "content_id": "2a4533bed1349458dcc5008471b1a008edcc0d28", "detected_licenses": [ "MIT" ], "directory_id": "94f9d3863c93f4a990ab87d4933e0498ed3e2ba1", "extension": "h", "filename": "DirectXTools.h", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 156447978, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 12647, "license": "MIT", "license_type": "permissive", "path": "/Visual Studio/DirectX/Arkanoid/DirectXTools.h", "provenance": "stackv2-0138.json.gz:142243", "repo_name": "Jeanmilost/Demos", "revision_date": "2023-01-09T16:20:48", "revision_id": "3300e056e88506757f3185ba94d6b2ac3da344af", "snapshot_id": "6401d7af4612e6a6a06b070a5e951457c1cdc069", "src_encoding": "ISO-8859-1", "star_events_count": 1, "url": "https://raw.githubusercontent.com/Jeanmilost/Demos/3300e056e88506757f3185ba94d6b2ac3da344af/Visual Studio/DirectX/Arkanoid/DirectXTools.h", "visit_date": "2023-01-28T19:51:05.670586" }
stackv2
#include <ddraw.h> #include <dinput.h> #define SafeRelease(x) if (x) { x->Release(); x=NULL;} //-------------------DIRECTDRAW---------------------- //-- Définit la résolution d'écran. const int ResolutionX=640; const int ResolutionY=480; //-- Définit les pointeurs DirectDraw globaux. LPDIRECTDRAW4 lpDD=NULL; LPDIRECTDRAWSURFACE4 lpDDSPrimary=NULL; LPDIRECTDRAWSURFACE4 lpDDSBack=NULL; //-- Définit : - le nombre d'images. // - le nombre de surfaces secondaires // (BufferSurfaces.) #define Buffer_Nbr 50 // -- Tableau à 2 dimensions définissant quel fichier // à charger selon la surface secondaire. char FileNames[Buffer_Nbr][256] = { "SprArka21.bmp", "Scene1.bmp", "Scene2.bmp", "Scene3.bmp", "Scene4.bmp", "Scene1.bmp" }; // -- Tableau de références pointeurs vers les // surfaces secondaires. LPDIRECTDRAWSURFACE4 lp_BufferSurfaceCaller[Buffer_Nbr]; //----------------DIRECTINPUT------------------------ //-- Définit les pointeurs DirectInputs globaux. LPDIRECTINPUT lpDI=NULL; //-- Définit les pointeurs clavier. LPDIRECTINPUTDEVICE pKeyboard=NULL; char KeyBuffer[256]; //-- Définit les pointeurs souris. LPDIRECTINPUTDEVICE pMouse=NULL; HANDLE Event=NULL; //-- Définit les registres d'états de la souris. int OldiDX=0, OldiDY=0, Delta=0; int iDX=0, iDY=0; BOOL ButtonDown[2]; // ************************************************** // * * // * Crée les BufferSurface et renvoie un pointeur * // * vers lesdites surfaces. * // * * // ************************************************** LPDIRECTDRAWSURFACE4 bitmap_surface(LPCTSTR file_name,RECT *dims=NULL) { HDC hdc; HBITMAP bit; LPDIRECTDRAWSURFACE4 surf; // Charge l'image. bit=(HBITMAP) LoadImage(NULL,file_name,IMAGE_BITMAP,0,0, LR_DEFAULTSIZE|LR_LOADFROMFILE); if (!bit) return NULL; // Definit les dimensions de l'image. BITMAP bitmap; GetObject( bit, sizeof(BITMAP), &bitmap ); int surf_width=bitmap.bmWidth; int surf_height=bitmap.bmHeight; // Crée la BufferSurface. HRESULT ddrval; DDSURFACEDESC2 ddsd; ZeroMemory(&ddsd,sizeof(ddsd)); ddsd.dwSize = sizeof(DDSURFACEDESC2); ddsd.dwFlags = DDSD_CAPS | DDSD_WIDTH | DDSD_HEIGHT ; ddsd.ddsCaps.dwCaps = DDSCAPS_OFFSCREENPLAIN; ddsd.dwWidth = surf_width; ddsd.dwHeight = surf_height; ddrval=lpDD->CreateSurface(&ddsd,&surf,NULL); if (ddrval!=DD_OK) { DeleteObject(bit); return NULL; } else { surf->GetDC(&hdc); // Crée un DC compatible. HDC bit_dc=CreateCompatibleDC(hdc); // Blitte l'interface dans la surface. SelectObject(bit_dc,bit); BitBlt(hdc,0,0,surf_width,surf_height,bit_dc,0,0,SRCCOPY); // Libère le DC. surf->ReleaseDC(hdc); DeleteDC(bit_dc); // Sauvegarde les dimensions du rectangle. if (dims) { dims->left=0; dims->top=0; dims->right=surf_width; dims->bottom=surf_height; } } // Libère le Bitmap. DeleteObject(bit); return surf; } // ************************************************** // * * // * Libère les objets DirectDraw. * // * * // ************************************************** void EraseDDraw() { // Libère les BufferSurfaces. for (int i=0;i<Buffer_Nbr;i++) SafeRelease(lp_BufferSurfaceCaller[i]); // Libère l'interface DDRAW. SafeRelease(lpDDSPrimary); SafeRelease(lpDD); } // ************************************************* // * * // * Dessine le papier peint de fond. * // * * // ************************************************* void BackGround(int Image_Number) { // Copie le BufferSurface représentant le fond // dans le BackBuffer. lpDDSBack->BltFast(0,0,lp_BufferSurfaceCaller[Image_Number],NULL,DDBLTFAST_WAIT); } // ************************************************* // * * // * Dessine un sprite à l'écran, en tenant compte * // * du clipping. * // * * // ************************************************* void Sprite(int X, int Y, int Left, int Right, int Top, int Bottom) { int ClippingX=0, ClippingY=0; RECT SpRect; SpRect.left=Left; SpRect.top=Top; SpRect.right=Right; SpRect.bottom=Bottom; // Vérifie et exécute si besoin est le clipping // du bord gauche. if (X<=0) { ClippingX=0-X; SpRect.left=Left+ClippingX; X=0; } // Vérifie et exécute si besoin est le clipping // du bord droite. if (X+(Right-Left)>=ResolutionX) { ClippingX=(X+(Right-Left))-ResolutionX; SpRect.right=Right-ClippingX; } // Vérifie et exécute si besoin est le clipping // du haut de l'écran. if (Y<=0) { ClippingY=0-Y; SpRect.top=Top+ClippingY; Y=0; } // Vérifie et exécute si besoin est le clipping // du bas de l'écran. if (Y+(Bottom-Top)>=ResolutionY) { ClippingY=(Y+(Bottom-Top))-ResolutionY; SpRect.bottom=Bottom-ClippingY; } if (&SpRect) { lpDDSBack->BltFast(X, Y, lp_BufferSurfaceCaller[0], &SpRect, DDBLTFAST_WAIT | DDBLTFAST_SRCCOLORKEY); } } // ************************************************** // * * // * Fonction servant à définir la clé de couleur * // * pour la copie du sprite (se trouve dans la * // * première surface du tableau.) * // * * // ************************************************** void DefineColorKey(LPDIRECTDRAWSURFACE4 KeySurface) { DDCOLORKEY key; key.dwColorSpaceHighValue=0; // Clé RGB a zero: key.dwColorSpaceLowValue=0; // NOIR. KeySurface->SetColorKey(DDCKEY_SRCBLT, &key); } // ************************************************** // * * // * Initialisation de DirectDraw. * // * * // ************************************************** BOOL InitDDraw(HWND hWndDD) { LPDIRECTDRAW pDD; // Libère les pointeurs d'image. ZeroMemory(lp_BufferSurfaceCaller,sizeof(lp_BufferSurfaceCaller)); // Crée l'objet DDRAW principal. if (DirectDrawCreate(NULL, &pDD, NULL)!=DD_OK) return FALSE; // Groupe l'interface DDRAW4 au projet. if (pDD->QueryInterface(IID_IDirectDraw4, (LPVOID *) & lpDD)!=DD_OK) return FALSE; // Définit le niveau coopératif. if (lpDD->SetCooperativeLevel(hWndDD, DDSCL_EXCLUSIVE | DDSCL_FULLSCREEN )!=DD_OK) return FALSE; // Définit le mode vidéo. if (lpDD->SetDisplayMode( 640, 480, 16, 0, 0)!=DD_OK) return FALSE; // Crée la surface primaire avec 1 BackBuffer. DDSURFACEDESC2 ddsd; DDSCAPS2 ddscaps; ZeroMemory(&ddsd,sizeof(ddsd)); ddsd.dwSize = sizeof( ddsd ); ddsd.dwFlags = DDSD_CAPS | DDSD_BACKBUFFERCOUNT; ddsd.ddsCaps.dwCaps = DDSCAPS_PRIMARYSURFACE | DDSCAPS_FLIP | DDSCAPS_COMPLEX; ddsd.dwBackBufferCount = 1; if (lpDD->CreateSurface( &ddsd, &lpDDSPrimary, NULL )!=DD_OK) return FALSE; // Attache le BackBuffer à la surface primaire. ddscaps.dwCaps=DDSCAPS_BACKBUFFER; if (lpDDSPrimary->GetAttachedSurface(&ddscaps,&lpDDSBack)!=DD_OK) return FALSE; // Charge l'image des modèles de sprites. lp_BufferSurfaceCaller[0]=bitmap_surface(FileNames[0]); if (!lp_BufferSurfaceCaller[0]) return FALSE; DefineColorKey(lp_BufferSurfaceCaller[0]); // Charger l'image de fond. lp_BufferSurfaceCaller[1]=bitmap_surface(FileNames[1]); if (!lp_BufferSurfaceCaller[1]) return FALSE; return TRUE; } // ************************************************** // * * // * Initialisation de DirectInput. * // * * // ************************************************** BOOL InitDInput(HINSTANCE hInstDI, HWND hWndDI) { // Ouvre l'objet DirectInput. if (DirectInput8Create(hInstDI, DIRECTINPUT_VERSION, IID_IDirectInput8A, (VOID**)&lpDI, NULL)!=DI_OK) return FALSE; // Crée l'interface clavier. if (lpDI->CreateDevice(GUID_SysKeyboard, &pKeyboard, NULL)!=DI_OK) return FALSE; if (pKeyboard->SetDataFormat(&c_dfDIKeyboard)!=DI_OK) return FALSE; if (pKeyboard->SetCooperativeLevel(hWndDI, DISCL_FOREGROUND | DISCL_NONEXCLUSIVE)!=DI_OK) return FALSE; if (pKeyboard->Acquire()!=DI_OK) return FALSE; // Crée l'interface souris. if (lpDI->CreateDevice(GUID_SysMouse, &pMouse, NULL)!=DI_OK) return FALSE; if (pMouse->SetDataFormat(&c_dfDIMouse)!=DI_OK) { SafeRelease(pMouse); return FALSE; } if (pMouse->SetCooperativeLevel(hWndDI, DISCL_FOREGROUND | DISCL_EXCLUSIVE)!=DI_OK) { SafeRelease(pMouse); return FALSE; } Event=CreateEvent(0, 0, 0, 0); if ( NULL == Event ) return FALSE; if (pMouse->SetEventNotification(Event)!=DI_OK) { SafeRelease(pMouse); return FALSE; } DIPROPDWORD dipwd= { { sizeof(DIPROPDWORD), sizeof(DIPROPHEADER), 0, DIPH_DEVICE, }, 32 }; if (pMouse->SetProperty(DIPROP_BUFFERSIZE, &dipwd.diph)!=DI_OK) { SafeRelease(pMouse); return FALSE; } if (pMouse->Acquire()!=DI_OK) return FALSE; return TRUE; } // ************************************************** // * * // * Libère les objets DINPUTS. * // * * // ************************************************** void EraseDInput() { if (pMouse) { pMouse->Unacquire(); pMouse->Release(); pMouse=NULL; } SafeRelease(lpDI); } // ************************************************** // * * // * Lit les données de la souris * // * * // ************************************************** BOOL ReadMouse() { OldiDX=iDX; OldiDY=iDY; BOOL bDone; DIDEVICEOBJECTDATA od; DWORD dwElements; HRESULT hr; BOOL Resultat=FALSE; // Attempt to read one data element. Continue as long as // device data is available. bDone = FALSE; while ( !bDone ) { dwElements = 1; hr = pMouse->GetDeviceData( sizeof(DIDEVICEOBJECTDATA), &od, &dwElements, 0 ); if (hr == DIERR_INPUTLOST) { pMouse->Acquire(); break; } // Unable to read data or no data available if ( FAILED(hr) || dwElements == 0) { break; } // look at the element to see what happened switch (od.dwOfs) { case DIMOFS_X: iDX+=od.dwData; Resultat=TRUE; break; case DIMOFS_Y: iDY+=od.dwData; Resultat=TRUE; break; case DIMOFS_BUTTON0: if ( od.dwData & 0x80 ) { bDone = TRUE; ButtonDown[0]=TRUE; Resultat=TRUE; } else ButtonDown[0]=FALSE; break; case DIMOFS_BUTTON1: if ( od.dwData & 0x80 ) { bDone = TRUE; ButtonDown[1]=TRUE; Resultat=TRUE; } else ButtonDown[1]=FALSE; break; } } return Resultat; } BOOL Button0() { return ButtonDown[0]; } BOOL Button1() { return ButtonDown[1]; } void InitAxes(int InitAxeX, int InitAxeY) { iDX=InitAxeX; iDY=InitAxeY; } int AxeX(int MinX, int MaxX) { if (iDX>MaxX) iDX=MaxX; if (iDX<MinX) iDX=MinX; return iDX; } int AxeY(int MinY, int MaxY) { if (iDY>MaxY) iDY=MaxY; if (iDY<MinY) iDY=MinY; return iDY; } // ************************************************** // * * // * Lit les données du clavier. * // * * // ************************************************** void ReadKeyboard() { if (pKeyboard->GetDeviceState(sizeof(KeyBuffer),(LPVOID)&KeyBuffer) == DIERR_INPUTLOST) { // Reacquiert le clavier et recommence. if (pKeyboard->Acquire() == DI_OK) pKeyboard->GetDeviceState(sizeof(KeyBuffer),(LPVOID)&KeyBuffer); } } // ************************************************** // * * // * Tests de fonctions du clavier. * // * * // ************************************************** #define KEYDOWN(buf, key) (buf[key] & 0x80) BOOL LSHIFT() { ReadKeyboard(); if (KEYDOWN(KeyBuffer, DIK_LSHIFT)) return TRUE; return FALSE; } BOOL RSHIFT() { ReadKeyboard(); if (KEYDOWN(KeyBuffer, DIK_RSHIFT)) return TRUE; return FALSE; } BOOL LEFT() { ReadKeyboard(); if (KEYDOWN(KeyBuffer, DIK_LEFT)) return TRUE; return FALSE; } BOOL RIGHT() { ReadKeyboard(); if (KEYDOWN(KeyBuffer, DIK_RIGHT)) return TRUE; return FALSE; } BOOL UP() { ReadKeyboard(); if (KEYDOWN(KeyBuffer, DIK_UP)) return TRUE; return FALSE; } BOOL SPACE() { ReadKeyboard(); if (KEYDOWN(KeyBuffer, DIK_SPACE)) return TRUE; return FALSE; }
2.140625
2
2024-11-18T21:51:50.491120+00:00
2021-04-15T14:11:21
261e352ee70ea8ae0397138971dfc9575bbfbba6
{ "blob_id": "261e352ee70ea8ae0397138971dfc9575bbfbba6", "branch_name": "refs/heads/main", "committer_date": "2021-04-15T14:11:21", "content_id": "a19a1dcd2bdf8c0beec48c97bf14355d6dfc5e25", "detected_licenses": [ "MIT" ], "directory_id": "043ea4d5da70c7acf5d78f8915d2b4a2dbc4d9cb", "extension": "c", "filename": "Aula 23 - Caracteres de escape.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 354628249, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 274, "license": "MIT", "license_type": "permissive", "path": "/Aula 23 - Caracteres de escape.c", "provenance": "stackv2-0138.json.gz:142373", "repo_name": "mcmarcelosp/Curso-em-C", "revision_date": "2021-04-15T14:11:21", "revision_id": "ed405c1e8f296d4164a300a1eaa1131944e353a7", "snapshot_id": "747a938577b668d0726b6d037be2f62fc0cc08e9", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/mcmarcelosp/Curso-em-C/ed405c1e8f296d4164a300a1eaa1131944e353a7/Aula 23 - Caracteres de escape.c", "visit_date": "2023-04-07T20:50:54.759073" }
stackv2
#include <stdio.h> #include <stdlib.h> /* Aula 23 caracteres de escape Quebra de linha -> \n Tabulação -> \t Aspa dupla -> \" Aspa simples -> \' Contrabarra -> \\ */ int main(){ printf("\n\n\tIsto e uma mensagem \\a ser impressa na tela.\n\n"); return 0; }
2.71875
3
2024-11-18T21:51:50.582716+00:00
2021-08-08T09:34:27
57ffb8d01c0e12d01a32024a46f3501a290a0e75
{ "blob_id": "57ffb8d01c0e12d01a32024a46f3501a290a0e75", "branch_name": "refs/heads/main", "committer_date": "2021-08-08T09:34:27", "content_id": "9f4737d95bb081a0d46eb43ec616609769e9e926", "detected_licenses": [ "Unlicense" ], "directory_id": "c793401ee5230e9ad0f502e9539b5770240e70d7", "extension": "c", "filename": "edwith8.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 390559872, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 328, "license": "Unlicense", "license_type": "permissive", "path": "/edwith8.c", "provenance": "stackv2-0138.json.gz:142501", "repo_name": "jungx1234/Cstudy", "revision_date": "2021-08-08T09:34:27", "revision_id": "910c8d688e8290a67b5537a9820b61af10ec6735", "snapshot_id": "9d821b55204e21c2ca2c9eaa0c100d8c77fc883e", "src_encoding": "UHC", "star_events_count": 0, "url": "https://raw.githubusercontent.com/jungx1234/Cstudy/910c8d688e8290a67b5537a9820b61af10ec6735/edwith8.c", "visit_date": "2023-07-01T19:21:27.946126" }
stackv2
#include <stdio.h> int main() { int grade; printf("학년은?"); scanf("%d", &grade); switch (grade) { case 1: printf("Freshman\n"); break; case 2: printf("Sophomore\n"); break; case 3: printf("Junior\n"); break; case 4: printf("Senior\n"); break; default:printf("잘못된 학년\n"); } return 0; }
3.296875
3
2024-11-18T21:51:50.656525+00:00
2019-07-05T13:26:35
618f8b87ca2592e41478e361548f137cd6c924f0
{ "blob_id": "618f8b87ca2592e41478e361548f137cd6c924f0", "branch_name": "refs/heads/master", "committer_date": "2019-07-05T13:26:35", "content_id": "ed9f350b5fe952878421678435386c803936fd0e", "detected_licenses": [ "MIT" ], "directory_id": "f07acf3594b21458f44e22a4c77451d900127474", "extension": "c", "filename": "AutoAimTask.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": 13430, "license": "MIT", "license_type": "permissive", "path": "/Tasks/Src/AutoAimTask.c", "provenance": "stackv2-0138.json.gz:142630", "repo_name": "tryingfly/RM_Infantry", "revision_date": "2019-07-05T13:26:35", "revision_id": "21d4b988e15440febabc32c6fb3946213c14d216", "snapshot_id": "9f98cca7d4f9793c973d753890673ab0775de48a", "src_encoding": "GB18030", "star_events_count": 0, "url": "https://raw.githubusercontent.com/tryingfly/RM_Infantry/21d4b988e15440febabc32c6fb3946213c14d216/Tasks/Src/AutoAimTask.c", "visit_date": "2020-06-16T05:01:35.393488" }
stackv2
/** ****************************************************************************** *FileName : AutoAimTask.c *Description : 自瞄程序 *Author : 管易恒 ****************************************************************************** * * Copyright (c) 2019 Team JiaoLong-ShanghaiJiaoTong University * All rights reserved. * ****************************************************************************** */ #include "includes.h" //#define AUTOAIM_DEBUG #ifndef DEBUG_MODE #ifdef USE_AUTOAIM #define USE_AUTOAIM_ANGLE //*****************************************声明变量******************************************// GMAngle_t aim,aim_rcd; //目标角度 GMAngle_t adjust; //校准发射变量 Coordinate_t enemy_gun,enemy_scope,scope_gun; //坐标 uint8_t Enemy_INFO[8],Tx_INFO[8]; //接收 uint8_t find_enemy=0,aim_mode=0,upper_mode; //aim_mode用于选择瞄准模式,0为手动瞄准,1为正常自瞄,2为打符,3暂无(吊射?) uint16_t aim_cnt=0; //自瞄分频延时变量 uint16_t auto_counter_fps = 1000; //检测帧率 int16_t current_yaw=0,current_pitch=0; //当前云台角度 int16_t receive_cnt=0,receive_rcd=0; //检测上位机信号帧数 int8_t track_cnt=60; //追踪变量 double rcd_yaw=0, rcd_pitch=0; uint8_t Pre_aim=0, clb=0,numState=1,colorAim; extern float AimPitchFix; extern float AimYawFix; extern int16_t nowFrictionLSpeed; extern int16_t FrictionLSpeedLow; extern int16_t FrictionLSpeedMid; extern int16_t FrictionLSpeedHigh; int16_t attack_mark; //for auto attack Aim_data center; //********************************************************************************************// //********************************自瞄初始化********************************// void InitAutoAim() { //开启AUTO_AIM_UART的DMA接收 if(HAL_UART_Receive_DMA(&AUTOAIM_UART,(uint8_t *)&Enemy_INFO,8)!= HAL_OK) { Error_Handler(); } //坐标变量初始化(不需要修改) enemy_scope.x=0; enemy_scope.y=0; enemy_scope.z=200; enemy_gun.x=0; enemy_gun.y=0; enemy_gun.z=200; //角度变量初始化(不需要修改) aim.yaw=0; aim.pitch=0; adjust.yaw=0.0f; adjust.pitch=-0.3f; //设置坐标初始值(根据不同安装情况调整这3个参数) scope_gun.x=0; scope_gun.y=-10; scope_gun.z=0; } //**************************************************************************// //*******************************UART回调函数********************************// void AutoAimUartRxCpltCallback() { //HAL_UART_AbortReceive(&AUTOAIM_UART); if(aim_mode == 2) { //串口数据解码 if(RX_ENEMY_START=='s'&&RX_ENEMY_END=='e') { aim.yaw=(float)((RX_ENEMY_X1<<8)|RX_ENEMY_X2)*k_coordinate; aim.pitch=(float)((RX_ENEMY_Y1<<8)|RX_ENEMY_Y2)*k_coordinate; enemy_scope.z=(float)((RX_ENEMY_Z1<<8)|RX_ENEMY_Z2)*k_distance; if(aim.yaw>100)aim.yaw-=200; if(aim.pitch>100)aim.pitch-=200; find_enemy=1; receive_cnt++; } } else if(aim_mode == 1) { if(RX_ENEMY_START=='s'&&RX_ENEMY_END=='e') { aim.yaw=-(float)( (((RX_ENEMY_YAW1<<8)|RX_ENEMY_YAW2)>0x7fff) ? (((RX_ENEMY_YAW1<<8)|RX_ENEMY_YAW2)-0xffff) : (RX_ENEMY_YAW1<<8)|RX_ENEMY_YAW2 )*k_angle; aim.pitch=(float)( (((RX_ENEMY_PITCH1<<8)|RX_ENEMY_PITCH2)>0x7fff) ? (((RX_ENEMY_PITCH1<<8)|RX_ENEMY_PITCH2)-0xffff) : (RX_ENEMY_PITCH1<<8)|RX_ENEMY_PITCH2 )*k_angle; aim.yaw-=adjust.yaw; aim.pitch+=adjust.pitch; MINMAX(aim.yaw,-15.0f,15.0f); MINMAX(aim.pitch,-10.0f,10.0f); //enemy_scope.z=350; find_enemy=1; receive_cnt++; } #ifdef AUTOAIM_DEBUG static DebugInfo_t debugInfo; debugInfo.start = 's'; debugInfo.data[0] = GMY.TargetAngle; debugInfo.data[1] = GMY.RealAngle; debugInfo.data[2] = aim.yaw; debugInfo.end = '\n'; static float fdata[3]; fdata[0] = GMY.TargetAngle; fdata[1] = GMY.RealAngle; fdata[2] = aim.yaw; if(aim_mode == 1)HAL_UART_Transmit_IT(&AUTOAIM_UART, (uint8_t*)&debugInfo, sizeof(debugInfo)); #endif /* AUTOAIM_DEBUG */ } HAL_UART_Receive_DMA(&AUTOAIM_UART,(uint8_t *)&Enemy_INFO,8); } //***************************************************************************// //*************************************CAN线主控板间通信*************************************// /* //用于英雄双云台 extern RC_Ctl_t RC_CtrlData; void CANTxINFO() { extern int16_t channelrcol; uint8_t stir_state= (channelrcol>0) ? (channelrcol * 7 / 661) : 0 ; CanTxMsgTypeDef pData; hcan1.pTxMsg = &pData; hcan1.pTxMsg->StdId = 0x300; //标头为0x300,注意检查是否配对及有无冲突情况 hcan1.pTxMsg->ExtId = 0; hcan1.pTxMsg->IDE = CAN_ID_STD; hcan1.pTxMsg->RTR = CAN_RTR_DATA; hcan1.pTxMsg->DLC = 0x08; switch(WorkState) { case STOP_STATE: hcan1.pTxMsg->Data[0] = 0xff; break; case PREPARE_STATE: hcan1.pTxMsg->Data[0] = 0x00; break; case NORMAL_STATE: hcan1.pTxMsg->Data[0] = 0x01; break; case ADDITIONAL_STATE_ONE: hcan1.pTxMsg->Data[0] = 0x02; break; case ADDITIONAL_STATE_TWO: hcan1.pTxMsg->Data[0] = 0x03; break; } switch(inputmode) { case REMOTE_INPUT: hcan1.pTxMsg->Data[1] = 0x01; break; case KEY_MOUSE_INPUT: hcan1.pTxMsg->Data[1] = 0x02; break; case STOP: hcan1.pTxMsg->Data[1] = 0x03; break; } hcan1.pTxMsg->Data[2] = (uint8_t)(stir_state); hcan1.pTxMsg->Data[3] = (uint8_t)RC_CtrlData.mouse.press_l; hcan1.pTxMsg->Data[4] = (uint8_t)RC_CtrlData.mouse.press_r; hcan1.pTxMsg->Data[5] = (uint8_t)(RC_CtrlData.key.v & 0xff); hcan1.pTxMsg->Data[6] = (uint8_t)((RC_CtrlData.key.v>>8) & 0xff); hcan1.pTxMsg->Data[7] = 0; if(can1_update == 1 && can1_type == 3) { HAL_NVIC_DisableIRQ(CAN1_RX0_IRQn); HAL_NVIC_DisableIRQ(CAN2_RX0_IRQn); HAL_NVIC_DisableIRQ(USART1_IRQn); HAL_NVIC_DisableIRQ(DMA2_Stream2_IRQn); HAL_NVIC_DisableIRQ(TIM6_DAC_IRQn); HAL_NVIC_DisableIRQ(TIM7_IRQn); #ifdef DEBUG_MODE HAL_NVIC_DisableIRQ(TIM1_UP_TIM10_IRQn); #endif if(HAL_CAN_Transmit_IT(&hcan1) != HAL_OK) { Error_Handler(); } can1_update = 0; #ifdef CAN11 can1_type = 1; #else #ifdef CAN12 can1_type = 2; #endif #endif HAL_NVIC_EnableIRQ(CAN1_RX0_IRQn); HAL_NVIC_EnableIRQ(CAN2_RX0_IRQn); HAL_NVIC_EnableIRQ(USART1_IRQn); HAL_NVIC_EnableIRQ(DMA2_Stream2_IRQn); HAL_NVIC_EnableIRQ(TIM7_IRQn); HAL_NVIC_EnableIRQ(TIM6_DAC_IRQn); #ifdef DEBUG_MODE HAL_NVIC_EnableIRQ(TIM1_UP_TIM10_IRQn); #endif } } */ //*******************************************************************************************// //****************************************坐标角度转换函数*************************************// //在时间中断中分频后调用该函数 void EnemyINFOProcess() { if(aim_mode == 1) { //坐标转换 enemy_gun.x=enemy_scope.x+scope_gun.x; enemy_gun.y=enemy_scope.y+scope_gun.y; enemy_gun.z=enemy_scope.z+scope_gun.z; //角度计算(计算消耗内存较多,不能放在2ms以下的时间中断内执行) aim.yaw=atan(enemy_gun.x/(enemy_gun.z*cos(GMP_ANGLE)-enemy_gun.y*sin(GMP_ANGLE)))/const_pi*180.0-adjust.yaw; aim.pitch=atan(enemy_gun.y/enemy_gun.z)/const_pi*180.0+adjust.pitch; } //追踪 if(((aim.yaw>0 && aim_rcd.yaw>0) || (aim.yaw<0 && aim_rcd.yaw<0))) { track_cnt--; MINMAX(track_cnt,0,60); } else { track_cnt=60; } } //*********************************************************************************************// //**************************普通模式自瞄控制函数****************************// float py=0.4, iy=0.02, dy=0.1; void AutoAimNormal() { MINMAX(aim.yaw,-15.0f,15.0f); MINMAX(aim.pitch,-10.0f,10.0f); if(find_enemy) { // if(aim_cnt<1) // { // GMY.TargetAngle+=(aim.yaw)/8; // GMY.TargetAngle+=(aim.yaw)/2; // GMP.TargetAngle+=(aim.pitch)/6; #ifdef INFANTRY5 static float yi = 0, lasty = 0; yi += aim.yaw; //auto attack attack_mark = aim.yaw * py + yi * iy + (aim.yaw-lasty) * dy; GMY.TargetAngle = GMY.RealAngle + attack_mark; // GMY.TargetAngle += aim.yaw * py + yi * iy + (aim.yaw-lasty) * dy; lasty = aim.yaw; GMP.TargetAngle = GMP.RealAngle + aim.pitch * 0.3f; if(nowFrictionLSpeed == FrictionLSpeedLow)GMP.TargetAngle += 2.0f; else if(nowFrictionLSpeed == FrictionLSpeedMid)GMP.TargetAngle += 0.25f; GMP.TargetAngle += AimPitchFix; GMY.TargetAngle += AimYawFix; #endif #ifdef INFANTRY4 static float yi = 0, lasty = 0; yi += aim.yaw; //auto attack attack_mark = aim.yaw * py + yi * iy + (aim.yaw-lasty) * dy; GMY.TargetAngle = GMY.RealAngle + attack_mark; //GMY.TargetAngle = GMY.RealAngle + aim.yaw * py + yi * iy + (aim.yaw-lasty) * dy; // GMY.TargetAngle += aim.yaw * py + yi * iy + (aim.yaw-lasty) * dy; lasty = aim.yaw; GMP.TargetAngle = GMP.RealAngle + aim.pitch * 0.3f; if(nowFrictionLSpeed == FrictionLSpeedLow)GMP.TargetAngle += 2.0f; else if(nowFrictionLSpeed == FrictionLSpeedMid)GMP.TargetAngle += 0.25f; GMP.TargetAngle += AimPitchFix; GMY.TargetAngle += AimYawFix; #endif #ifdef INFANTRY3 // if(aim.yaw < 1){ // GMY.TargetAngle = GMY.RealAngle + aim.yaw * 0.8; // }else{ // // } static float yi = 0, lasty = 0; yi += aim.yaw; //auto attack attack_mark = aim.yaw * py + yi * iy + (aim.yaw-lasty) * dy; GMY.TargetAngle = GMY.RealAngle + attack_mark; // GMY.TargetAngle = GMY.RealAngle + aim.yaw * py + yi * iy + (aim.yaw-lasty) * dy; // GMY.TargetAngle += aim.yaw * py + yi * iy + (aim.yaw-lasty) * dy; lasty = aim.yaw; GMP.TargetAngle = GMP.RealAngle + aim.pitch * 0.3f; if(nowFrictionLSpeed == FrictionLSpeedLow)GMP.TargetAngle += 2.0f; else if(nowFrictionLSpeed == FrictionLSpeedMid)GMP.TargetAngle += 0.25f; GMP.TargetAngle += AimPitchFix; GMY.TargetAngle += AimYawFix; #endif // aim_cnt++; // } // else // { find_enemy=0; // aim_cnt=0; // aim_rcd.yaw=aim.yaw; // aim_rcd.pitch=aim.pitch; } } //**************************************************************************// //**************************打符模式自瞄控制函数****************************// float num_now = 255.0f; void AutoAimBuff() { if(find_enemy) { //云台转向目标方向 #ifdef INFANTRY3 if(enemy_scope.z - num_now > 0.5f||enemy_scope.z - num_now < -0.5f) { aim_cnt = 0; } num_now = enemy_scope.z; #endif #ifdef INFANTRY5 if(enemy_scope.z - num_now > 0.5f || enemy_scope.z - num_now < -0.5f) { aim_cnt = 0; } num_now = enemy_scope.z; #endif if(aim_cnt==0) { rcd_yaw=aim.yaw; rcd_pitch=aim.pitch; GMY.TargetAngle=rcd_yaw; GMP.TargetAngle=rcd_pitch; aim_cnt++; } // else if(aim_cnt>=1 && aim_cnt<20) // { // GMY.TargetAngle+=aim_rcd.yaw/20; // GMP.TargetAngle+=aim_rcd.pitch/20; // aim_cnt++; // } else if(aim_cnt>0 && aim_cnt<5) { aim_cnt++; } //等待云台稳定 else if(aim_cnt>=5 && aim_cnt<10) { if(GMP.RealAngle<rcd_pitch-0.5)GMP.TargetAngle+=0.1; else if(GMP.RealAngle>rcd_pitch+0.5)GMP.TargetAngle-=0.1; aim_cnt++; } else if(aim_cnt>=10 && aim_cnt<40) { aim_cnt++; } //发射 else if(aim_cnt==40) { //ShootOneBullet(); #ifdef INFANTRY4 STIR.TargetAngle=STIR.RealAngle-90; #else STIR.TargetAngle=STIR.RealAngle-45; #endif aim_cnt++; } //等待云台稳定 else if(aim_cnt>=40&&aim_cnt<60) { aim_cnt++; } else { aim_cnt=0; find_enemy=0; } } } //**************************************************************************// uint32_t test_UART_Freq = 0; void Data_Pro(void) { if(aim_mode != 0) { center.yaw=GMY.RealAngle; center.pitch=GMP.RealAngle; if(aim_mode==1)center.state ='a'; else if(aim_mode==2)center.state ='e'; if(clb)center.mark=1; else center.mark=0; center.numState = numState; center.color = colorAim; upper_mode = aim_mode; center.end='\n'; } else { center.yaw=GMY.RealAngle; center.pitch=GMP.RealAngle; center.state ='a'; if(clb)center.mark=1; else center.mark=0; center.numState = numState; center.color = colorAim; upper_mode = aim_mode; center.end='\n'; } //HAL_UART_Transmit(&AUTOAIM_UART, (uint8_t*)&center ,sizeof (center), 100); HAL_UART_Transmit_DMA(&AUTOAIM_UART, (uint8_t*)&center ,sizeof (center)); //frequency is about 70hz //test_UART_Freq++; //clb=0; } //***************************上位机工作模式切换*****************************// void UpperStateFSM() { if(upper_mode != aim_mode && upper_mode != 0) { Tx_INFO[0] = 'c'; Tx_INFO[1] = aim_mode; Tx_INFO[2] = 'e'; HAL_UART_Transmit(&AUTOAIM_UART,Tx_INFO,3,0xff); upper_mode = aim_mode; } } //**************************************************************************// //***********************************自瞄控制*******************************// void AutoAimGMCTRL() { //UpperStateFSM(); Data_Pro(); switch(aim_mode) { case 1: //自瞄 { AutoAimNormal(); break; } case 2: //打符 { AutoAimBuff(); break; } default: break; } /************检测帧数*************/ if(receive_cnt == 0) auto_counter_fps = 1000; if(auto_counter_fps == 0) { receive_rcd = receive_cnt; receive_cnt = 0; auto_counter_fps = 1000; } /*********************************/ } //**************************************************************************// #endif /*USE_AUTOAIM*/ #endif /*DEBUG_MODE*/
2.15625
2
2024-11-18T21:51:50.735620+00:00
2018-07-18T07:25:30
007c3cd340c68f5f33eafabdfda429f8caa5ecb8
{ "blob_id": "007c3cd340c68f5f33eafabdfda429f8caa5ecb8", "branch_name": "refs/heads/master", "committer_date": "2018-07-18T07:25:30", "content_id": "aab3df939db143e6505135af4ee66af796a7e8ad", "detected_licenses": [ "MIT" ], "directory_id": "3eac6bdf5b81d9c480d2c7207ad5a6b7addcad96", "extension": "h", "filename": "hs_usart.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": 1149, "license": "MIT", "license_type": "permissive", "path": "/mcu/source/Drivers/hs_usart/hs_usart.h", "provenance": "stackv2-0138.json.gz:142759", "repo_name": "windoufu/dac200b", "revision_date": "2018-07-18T07:25:30", "revision_id": "6dfbb3f737211728e8202d48f8a5633449b69988", "snapshot_id": "a28b8cb2403403475b42c5538e2dce786220db78", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/windoufu/dac200b/6dfbb3f737211728e8202d48f8a5633449b69988/mcu/source/Drivers/hs_usart/hs_usart.h", "visit_date": "2021-09-18T18:20:27.244799" }
stackv2
#ifndef _HS_USART_H_ #define _HS_USART_H_ #include "Nano100Series.h" #define FRAME_BUF_LEN 128 typedef enum { RX_STATE_F_HEAD = 1, RX_STATE_F_LEN, RX_STATE_F_FINISH } RxState_t; #pragma pack(1) typedef struct { uint16_t header; uint16_t frame_len; uint16_t command; uint8_t cmd_type; uint16_t dat_len; uint8_t dat[FRAME_BUF_LEN-9]; }stFrame; #pragma pack() typedef struct { union { stFrame m_Frame; uint8_t Frame[FRAME_BUF_LEN]; }; volatile uint16_t FrameLen; volatile uint16_t FrameRecvLen; volatile RxState_t FrameState; } RxFrame_t; extern void hs_usart_init(void); extern void hs_usart_send_char(uint8_t data); extern void hs_usart_send_string(uint8_t *string); extern void hs_usart_send_data(uint8_t *data, uint16_t len); extern void hs_RxFrame_clear(void); extern void hs_RxFrame_insert_data(uint8_t data); extern void hs_RxFrame_update_rx_state(void); extern RxState_t hs_RxFrame_get_state(void); extern uint16_t hs_RxFrame_read_data(uint8_t *data); extern void hs_print_message(uint8_t *msg, uint16_t len); extern RxFrame_t RxFrame; #endif
2.03125
2
2024-11-18T21:51:52.774338+00:00
2019-04-18T03:55:32
ef23831900f1eede4e4be47dd6aeab83bcf37f65
{ "blob_id": "ef23831900f1eede4e4be47dd6aeab83bcf37f65", "branch_name": "refs/heads/master", "committer_date": "2019-04-18T03:55:32", "content_id": "9e3e8d75dc11813ee786dd63f9657cd7e04b318d", "detected_licenses": [ "Apache-2.0" ], "directory_id": "925b868eeee9d27bb792f50ac1a597d3cf44417a", "extension": "c", "filename": "rev.c", "fork_events_count": 0, "gha_created_at": "2019-04-18T03:45:23", "gha_event_created_at": "2019-04-18T03:45:24", "gha_language": null, "gha_license_id": null, "github_id": 182011832, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1135, "license": "Apache-2.0", "license_type": "permissive", "path": "/rev.c", "provenance": "stackv2-0138.json.gz:143663", "repo_name": "alvintpwang/cve-2019-6260", "revision_date": "2019-04-18T03:55:32", "revision_id": "6466325f9d2e9e7f43737bf353fd3c10e4fbec47", "snapshot_id": "046f12fe29e1b5f36979331bbca0a189062a860d", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/alvintpwang/cve-2019-6260/6466325f9d2e9e7f43737bf353fd3c10e4fbec47/rev.c", "visit_date": "2020-05-15T00:26:12.269356" }
stackv2
// SPDX-License-Identifier: Apache-2.0 // Copyright (C) 2018,2019 IBM Corp. #include "array.h" #include "rev.h" #include <assert.h> #include <stdint.h> struct bmc_silicon_rev { uint32_t rev; const char *name; }; static const struct bmc_silicon_rev bmc_silicon_revs[] = { { 0x02000303, "AST2400 A0" }, { 0x02010303, "AST2400 A1" }, { 0x04000303, "AST2500 A0" }, { 0x04010303, "AST2500 A1" }, { 0x04030303, "AST2500 A2" }, }; bool rev_is_supported(uint32_t rev) { int i; for (i = 0; i < ARRAY_SIZE(bmc_silicon_revs); i++) { if (rev == bmc_silicon_revs[i].rev) return true; } return false; } const char *rev_name(uint32_t rev) { int i; for (i = 0; i < ARRAY_SIZE(bmc_silicon_revs); i++) { if (rev == bmc_silicon_revs[i].rev) return bmc_silicon_revs[i].name; } return NULL; } static const uint8_t bmc_silicon_gens[] = { [ast_g4] = 0x02, [ast_g5] = 0x04, }; bool rev_is_generation(uint32_t rev, enum ast_generation gen) { assert(gen < ARRAY_SIZE(bmc_silicon_gens)); return rev >> 24 == bmc_silicon_gens[gen]; }
2.359375
2
2024-11-18T21:51:53.198643+00:00
2021-07-17T07:48:23
71d504616874ad7b93a0525ccd83126708b5c3a8
{ "blob_id": "71d504616874ad7b93a0525ccd83126708b5c3a8", "branch_name": "refs/heads/master", "committer_date": "2021-07-17T07:48:23", "content_id": "9959d985b68ea48f5eb77c81db477f4f093f6bdd", "detected_licenses": [ "MIT" ], "directory_id": "3fdf4d2b0ec2f2108a9604ebb6ba557ed48c2a76", "extension": "c", "filename": "wmtheme.c", "fork_events_count": 0, "gha_created_at": "2021-04-17T08:31:59", "gha_event_created_at": "2021-04-23T11:15:35", "gha_language": "C", "gha_license_id": "MIT", "github_id": 358825880, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 8792, "license": "MIT", "license_type": "permissive", "path": "/src/modules/wmtheme.c", "provenance": "stackv2-0138.json.gz:144179", "repo_name": "DarNCelsius/fastfetch", "revision_date": "2021-07-17T07:48:23", "revision_id": "6df453b71209e8a73dfef10d4ad33c12988b6fbe", "snapshot_id": "a86a56bb5cbbdeab3454f76604326bbebed9d901", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/DarNCelsius/fastfetch/6df453b71209e8a73dfef10d4ad33c12988b6fbe/src/modules/wmtheme.c", "visit_date": "2023-06-19T07:49:31.532555" }
stackv2
#include "fastfetch.h" #include <string.h> #define FF_WMTHEME_MODULE_NAME "WM Theme" #define FF_WMTHEME_NUM_FORMAT_ARGS 1 static void printWMTheme(FFinstance* instance, const char* theme) { if(instance->config.wmThemeFormat.length == 0) { ffPrintLogoAndKey(instance, FF_WMTHEME_MODULE_NAME, 0, &instance->config.wmThemeKey); puts(theme); } else { ffPrintFormatString(instance, FF_WMTHEME_MODULE_NAME, 0, &instance->config.wmThemeKey, &instance->config.wmThemeFormat, NULL, FF_WMTHEME_NUM_FORMAT_ARGS, (FFformatarg[]){ {FF_FORMAT_ARG_TYPE_STRING, theme} }); } } static void printWMThemeFromConfigFile(FFinstance* instance, const char* configFile, const char* themeRegex, const char* defaultValue) { FFstrbuf theme; ffStrbufInit(&theme); if(!ffParsePropFileConfig(instance, configFile, themeRegex, &theme)) { ffPrintError(instance, FF_WMTHEME_MODULE_NAME, 0, &instance->config.wmThemeKey, &instance->config.wmThemeFormat, FF_WMTHEME_NUM_FORMAT_ARGS, "Config file %s doesn't exist", configFile); ffStrbufDestroy(&theme); return; } if(theme.length == 0) { ffStrbufDestroy(&theme); if(defaultValue == NULL) { ffPrintError(instance, FF_WMTHEME_MODULE_NAME, 0, &instance->config.wmThemeKey, &instance->config.wmThemeFormat, FF_WMTHEME_NUM_FORMAT_ARGS, "Couldn't find WM theme in %s", configFile); return; } printWMTheme(instance, defaultValue); return; } // Remove Plasma-generated prefixes uint32_t idx = 0; idx = ffStrbufFirstIndexS(&theme, "qml_"); if(idx != theme.length) ffStrbufSubstrAfter(&theme, idx + 3); idx = ffStrbufFirstIndexS(&theme, "svg__"); if(idx != theme.length) ffStrbufSubstrAfter(&theme, idx + 4); printWMTheme(instance, theme.chars); ffStrbufDestroy(&theme); } static void printWMThemeFromSettings(FFinstance* instance, const char* dconfKey, const char* gsettingsSchemaName, const char* gsettingsPath, const char* gsettingsKey) { const char* theme = ffSettingsGet(instance, dconfKey, gsettingsSchemaName, gsettingsPath, gsettingsKey, FF_VARIANT_TYPE_STRING).strValue; if(theme == NULL || *theme == '\0') { ffPrintError(instance, FF_WMTHEME_MODULE_NAME, 0, &instance->config.wmThemeKey, &instance->config.wmThemeFormat, FF_WMTHEME_NUM_FORMAT_ARGS, "Couldn't find WM theme in DConf or GSettings"); return; } printWMTheme(instance, theme); } static void printGTKThemeAsWMTheme(FFinstance* instance) { const FFGTKResult* gtk = ffDetectGTK4(instance); if(gtk->theme.length > 0) { printWMTheme(instance, gtk->theme.chars); return; } gtk = ffDetectGTK3(instance); if(gtk->theme.length > 0) { printWMTheme(instance, gtk->theme.chars); return; } gtk = ffDetectGTK2(instance); if(gtk->theme.length > 0) { printWMTheme(instance, gtk->theme.chars); return; } ffPrintError(instance, FF_WMTHEME_MODULE_NAME, 0, &instance->config.wmThemeKey, &instance->config.wmThemeFormat, FF_WMTHEME_NUM_FORMAT_ARGS, "Couldn't detect GTK4/3/2 theme"); } static void printMutter(FFinstance* instance) { const char* theme = ffSettingsGet(instance, "/org/gnome/shell/extensions/user-theme/name", "org.gnome.shell.extensions.user-theme", NULL, "name", FF_VARIANT_TYPE_STRING).strValue; if(theme != NULL && *theme != '\0') { printWMTheme(instance, theme); return; } printGTKThemeAsWMTheme(instance); } static void printMuffin(FFinstance* instance) { const char* name = ffSettingsGet(instance, "/org/cinnamon/theme/name", "org.cinnamon.theme", NULL, "name", FF_VARIANT_TYPE_STRING).strValue; const char* theme = ffSettingsGet(instance, "/org/cinnamon/desktop/wm/preferences/theme", "org.cinnamon.desktop.wm.preferences", NULL, "theme", FF_VARIANT_TYPE_STRING).strValue; if(name == NULL && theme == NULL) { ffPrintError(instance, FF_WMTHEME_MODULE_NAME, 0, &instance->config.wmThemeKey, &instance->config.wmThemeFormat, FF_WMTHEME_NUM_FORMAT_ARGS, "Couldn't find muffin theme in GSettings / DConf"); return; } if(name == NULL) printWMTheme(instance, theme); else if(theme == NULL) printWMTheme(instance, name); else { FFstrbuf buffer; ffStrbufInit(&buffer); ffStrbufAppendS(&buffer, name); ffStrbufAppendS(&buffer, " ("); ffStrbufAppendS(&buffer, theme); ffStrbufAppendC(&buffer, ')'); printWMTheme(instance, buffer.chars); ffStrbufDestroy(&buffer); } } static void printXFWM4(FFinstance* instance) { const char* theme = ffSettingsGetXFConf(instance, "xfwm4", "/general/theme", FF_VARIANT_TYPE_STRING).strValue; if(theme == NULL) { ffPrintError(instance, FF_WMTHEME_MODULE_NAME, 0, &instance->config.wmThemeKey, &instance->config.wmThemeFormat, FF_WMTHEME_NUM_FORMAT_ARGS, "Couldn't find xfwm4::/general/theme in XFConf"); return; } printWMTheme(instance, theme); } static void printOpenbox(FFinstance* instance, const FFstrbuf* dePrettyName) { FFstrbuf absolutePath; ffStrbufInitA(&absolutePath, 64); ffStrbufAppendS(&absolutePath, instance->state.passwd->pw_dir); ffStrbufAppendC(&absolutePath, '/'); if(ffStrbufIgnCaseCompS(dePrettyName, "LXQT") == 0) ffStrbufAppendS(&absolutePath, ".config/openbox/lxqt-rc.xml"); else if(ffStrbufIgnCaseCompS(dePrettyName, "LXDE") == 0) ffStrbufAppendS(&absolutePath, ".config/openbox/lxde-rc.xml"); else ffStrbufAppendS(&absolutePath, ".config/openbox/rc.xml"); char* line = NULL; size_t len = 0; FILE* file = fopen(absolutePath.chars, "r"); if(file == NULL) { ffPrintError(instance, FF_WMTHEME_MODULE_NAME, 0, &instance->config.wmThemeKey, &instance->config.wmThemeFormat, FF_WMTHEME_NUM_FORMAT_ARGS, "Couldn't open \"%s\"", absolutePath.chars); ffStrbufDestroy(&absolutePath); return; } FFstrbuf theme; ffStrbufInitA(&theme, 256); while(getline(&line, &len, file) != -1) { if(strstr(line, "<theme>") != 0) break; } while(getline(&line, &len, file) != -1) { if(strstr(line, "<name>") != 0) { ffStrbufAppendS(&theme, line); ffStrbufRemoveStrings(&theme, 2, "<name>", "</name>"); ffStrbufTrimRight(&theme, '\n'); ffStrbufTrim(&theme, ' '); break; } if(strstr(line, "</theme>") != 0) // sanity check break; } if(line != NULL) free(line); fclose(file); if(theme.length == 0) ffPrintError(instance, FF_WMTHEME_MODULE_NAME, 0, &instance->config.wmThemeKey, &instance->config.wmThemeFormat, FF_WMTHEME_NUM_FORMAT_ARGS, "Couldn't find theme name in \"%s\"", absolutePath.chars); else printWMTheme(instance, theme.chars); ffStrbufDestroy(&theme); ffStrbufDestroy(&absolutePath); } void ffPrintWMTheme(FFinstance* instance) { const FFWMDEResult* result = ffDetectWMDE(instance); if(result->wmPrettyName.length == 0) { ffPrintError(instance, FF_WMTHEME_MODULE_NAME, 0, &instance->config.wmThemeKey, &instance->config.wmThemeFormat, FF_WMTHEME_NUM_FORMAT_ARGS, "WM Theme needs sucessfull WM detection"); return; } if(ffStrbufIgnCaseCompS(&result->wmPrettyName, "KWin") == 0 || ffStrbufIgnCaseCompS(&result->wmPrettyName, "KDE") == 0 || ffStrbufIgnCaseCompS(&result->wmPrettyName, "Plasma") == 0) printWMThemeFromConfigFile(instance, "kwinrc", "theme =", "Breeze"); else if(ffStrbufIgnCaseCompS(&result->wmPrettyName, "Xfwm4") == 0 || ffStrbufIgnCaseCompS(&result->wmPrettyName, "Xfwm") == 0) printXFWM4(instance); else if(ffStrbufIgnCaseCompS(&result->wmPrettyName, "Mutter") == 0) { if(ffStrbufIgnCaseCompS(&result->dePrettyName, "Gnome") == 0) printMutter(instance); else printGTKThemeAsWMTheme(instance); } else if(ffStrbufIgnCaseCompS(&result->wmPrettyName, "Muffin") == 0) printMuffin(instance); else if(ffStrbufIgnCaseCompS(&result->wmPrettyName, "Marco") == 0) printWMThemeFromSettings(instance, "/org/mate/Marco/general/theme", "org.mate.Marco.general", NULL, "theme"); else if(ffStrbufIgnCaseCompS(&result->wmPrettyName, "Openbox") == 0) printOpenbox(instance, &result->dePrettyName); else ffPrintError(instance, FF_WMTHEME_MODULE_NAME, 0, &instance->config.wmThemeKey, &instance->config.wmThemeFormat, FF_WMTHEME_NUM_FORMAT_ARGS, "Unknown WM: %s", result->wmPrettyName.chars); }
2.03125
2
2024-11-18T21:51:54.354168+00:00
2016-04-25T03:08:39
3cfbcc9485bf6c003f356e09ec5e9b184e4a12de
{ "blob_id": "3cfbcc9485bf6c003f356e09ec5e9b184e4a12de", "branch_name": "refs/heads/master", "committer_date": "2016-04-25T03:08:39", "content_id": "425dbb6485cd701fbdcb26a00231fc5ad460368b", "detected_licenses": [ "MIT" ], "directory_id": "aa6e0b1c20c7f29a26ef51eda0ec2fc8848c525c", "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": 50300282, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 7471, "license": "MIT", "license_type": "permissive", "path": "/Lab3_STM32F4Cube_ForLab4/Sources/main.c", "provenance": "stackv2-0138.json.gz:144567", "repo_name": "felixdube/microprocessor-systems", "revision_date": "2016-04-25T03:08:39", "revision_id": "fd3c36aed1093700a5259bb5c95a295b9dd2801f", "snapshot_id": "653fc71107b057cbcb9459645ad0a226fea8618f", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/felixdube/microprocessor-systems/fd3c36aed1093700a5259bb5c95a295b9dd2801f/Lab3_STM32F4Cube_ForLab4/Sources/main.c", "visit_date": "2020-04-13T23:18:58.718792" }
stackv2
/** ****************************************************************************** * File Name : main.c * Description : Main program subroutine * Author : Auguste Lalande, Felix Dube, Juan Morency Trudel * Version : 1.0.0 * Date : February 2016 ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include <stdlib.h> #include <stdio.h> #include <string.h> #include "stm32f4xx_hal.h" #include "supporting_functions.h" #include "lis3dsh.h" #include "accelerometer.h" #include "segment_controller.h" #include "system_clock.h" #include "kalmanFilter.h" #include "keypad.h" #include "lcd.h" #include "main.h" /* initialize variables */ kalmanState *xState; kalmanState *yState; kalmanState *zState; int debounce = 0; // used to debounced the keypad int keyLock = 1; // mutex for keypressed char input_Keypad; // button pressed by the user int flag_accPin = 0; // data ready flag for accelerometer int system_State = startState; // State of the state machine char input_angle[5] = "000"; //user input in a string float input_angle_float = 0; //User input angle in float int input_count = 0; // 7-segment display digit position float delta_angle = 100; // not initialized at 0 to avoid direct win int clear_display = 0; // boolean the prevents the lcd display te be updated every cycles /* Private variables ---------------------------------------------------------*/ /* Private function prototypes -----------------------------------------------*/ void SystemClock_Config (void); int main(void) { /* MCU Configuration----------------------------------------------------------*/ HAL_Init(); /* Configure the system clock */ SystemClock_Config(); /* Initialize accelerometer */ Accelerometer_Config(); Accelerometer_GPIO_Config(); Accelerometer_Interrupt_Config(); /* Initialize 7-segment display */ Display_GPIO_Config(); Display_TIM_Config(); /* Initialize Keypad*/ Keypad_Config(); initLCD(); /* configure LCD */ clearDisplay(); returnHome(); /* just makes sure that start writing at the right place */ LCD_WriteString(" Start"); /* The 2 initial space are for centering */ while (1){ /************************************************************************************************************/ /* Finite State Machine */ /* startState: Display current pitch and wait for the user to press # */ /* inputState: Wait for the user to enter an angle and to press # */ /* moveState: display the current pitch angle and wait for the user to move the board to the correct angle */ /* endState: the user win, the user input angle is displayed */ /************************************************************************************************************/ /*************** START STATE **************************/ /* start state, just display angle and wait for enter */ while (system_State == startState) { /* read accelerometer value */ if(flag_accPin){ ReadAcc(); flag_accPin = 0; } /* update the value to be displayed */ if (displayTimer) { display(pitch); displayTimer = 0; } /* read which keypad button is pressed */ input_Keypad = readKeypad(); if (input_Keypad == '#') { system_State = inputState; } } /************* INPUT STATE *****************/ /* input destination angle and press enter */ if (system_State == inputState){ /* update lcd display */ clearDisplay(); returnHome(); /* just makes sure that start writing at the right place */ LCD_WriteString(" Input Angle"); /* The 2 initial space are for centering */ } while (system_State == inputState) { /* update pitch value to be displayed */ if (displayTimer) { display(input_angle_float); displayTimer = 0; } /* read input from keypad */ input_Keypad = readKeypad(); if (input_Keypad == '#') { if(input_angle_float <= 180){ system_State = moveState; } else { clearDisplay(); returnHome(); /* just makes sure that start writing at the right place */ LCD_WriteString("Max Angle = 180"); /* The 2 initial space are for centering */ } } else if (input_Keypad != 'n' && input_Keypad != '*') { input_angle[input_count] = input_Keypad; input_count++; input_angle_float = atof(input_angle); //printf("%c\n",input_Keypad); //printf("%f\n",input_angle_float); if (input_count >= 3){ input_count = 0; } } } /**************** MOVESTATE *********************/ /* try to position the board at the right angle */ while (system_State == moveState) { /* read acceleration */ if(flag_accPin){ ReadAcc(); flag_accPin = 0; } /* update pitch value to be displayed */ if (displayTimer) { display(pitch); displayTimer = 0; } /* calculate error between goal and actual pitch value */ delta_angle = input_angle_float - pitch; /* check if goal acheived */ if(abs(delta_angle) <= 5) { system_State = endState; } else if (delta_angle > 0) { /* display something on LCD */ if(clear_display == 0){ clearDisplay(); clear_display = 1; returnHome(); /* just makes sure that start writing at the right place */ LCD_WriteString(" Go up"); /* The 2 initial space are for centering */ } } else { /* display something on LCD */ if(clear_display == 0){ clearDisplay(); clear_display = 1; returnHome(); /* just makes sure that start writing at the right place */ LCD_WriteString(" Go down"); /* The 2 initial space are for centering */ } } } /****** ENDSTATE *******/ /* display win message */ if (system_State == endState){ clear_display = 0; if(clear_display == 0){ clearDisplay(); clear_display = 1; } clearDisplay(); returnHome(); /* just makes sure that start writing at the right place */ LCD_WriteString(" Bravo Harsh"); /* The 2 initial space are for centering */ } while (system_State == endState) { /* set the pitch value displayed to the goal value */ if (displayTimer) { display(input_angle_float); displayTimer = 0; } } /* error checking */ if(system_State != 0 && system_State != 1 && system_State != 2 && system_State != 3){ system_State = 0; } } } /** * @brief Callback from the Timers * @param Timer handler * @retval None */ void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim) { digitTimer++; displayTimer = 1; } /** * @brief Callback from the external GPIO interupt * @param GPIO_Pin: pin on with the interupt occurs * @retval None */ void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin) { if (GPIO_Pin == accPin) { flag_accPin = 1; } }
2.953125
3
2024-11-18T21:51:54.554414+00:00
2015-05-23T17:29:05
1bc941294a387e279fee89d9ca09c65b06e85571
{ "blob_id": "1bc941294a387e279fee89d9ca09c65b06e85571", "branch_name": "refs/heads/master", "committer_date": "2015-05-23T17:29:05", "content_id": "372e270cf0daf617bfeea49db3b68df2f4bcb03f", "detected_licenses": [ "Artistic-2.0" ], "directory_id": "3226ca0264ba3fc6c3e6e3482e823b7014a8ef71", "extension": "c", "filename": "DoNothingThread.c", "fork_events_count": 0, "gha_created_at": "2015-05-20T02:41:00", "gha_event_created_at": "2015-05-20T02:41:00", "gha_language": null, "gha_license_id": null, "github_id": 35921516, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 672, "license": "Artistic-2.0", "license_type": "permissive", "path": "/speakers/miliox/samples/spawn_proc/DoNothingThread.c", "provenance": "stackv2-0138.json.gz:144696", "repo_name": "tel/lambdaconf-2015", "revision_date": "2015-05-23T17:29:05", "revision_id": "62396a8656df5e1e11a92c0fcfbb9398a10fd956", "snapshot_id": "01504e038f6c6c90fd07e4e1b9dc0b189409e56e", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/tel/lambdaconf-2015/62396a8656df5e1e11a92c0fcfbb9398a10fd956/speakers/miliox/samples/spawn_proc/DoNothingThread.c", "visit_date": "2020-04-01T13:40:45.769918" }
stackv2
#include <stdio.h> #include <stdlib.h> #include <mach/mach_time.h> #include <pthread.h> void* do_nothing_thread_main(void* ignored) { return NULL; } int main(int argc, char ** argv) { pthread_t tid = 0; uint64_t start = mach_absolute_time(); pthread_create(&tid, NULL, do_nothing_thread_main, NULL); pthread_join(tid, NULL); uint64_t elapsed = mach_absolute_time() - start; mach_timebase_info_data_t info; if (mach_timebase_info (&info) != KERN_SUCCESS) { printf ("mach_timebase_info failed\n"); } uint64_t nanosecs = elapsed * info.numer / info.denom; printf("deltaTime: %d\n", (int) nanosecs); return 0; }
2.734375
3
2024-11-18T21:51:55.124141+00:00
2023-07-13T14:53:27
7f45aa466e4200b9aa9bd2f6ab3ead32a6c920e4
{ "blob_id": "7f45aa466e4200b9aa9bd2f6ab3ead32a6c920e4", "branch_name": "refs/heads/master", "committer_date": "2023-07-13T14:53:27", "content_id": "3dd5d6a08909780a802e7bdb21facc5ba8766f0b", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "3d48e97f98f8c5871b60e05aab8a0d5bd45cffd9", "extension": "c", "filename": "powermodes.c", "fork_events_count": 188, "gha_created_at": "2018-05-13T12:14:58", "gha_event_created_at": "2023-07-18T08:51:36", "gha_language": "C", "gha_license_id": "BSD-3-Clause", "github_id": 133234028, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 14522, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/src/boot/ksdk1.1.0/powermodes.c", "provenance": "stackv2-0138.json.gz:145342", "repo_name": "physical-computation/Warp-firmware", "revision_date": "2023-07-13T14:53:27", "revision_id": "e5130824e266505947fd73f1bfdb33996190e637", "snapshot_id": "715a71ab52fd5428184ac65b7f4072b51ffd06ed", "src_encoding": "UTF-8", "star_events_count": 3, "url": "https://raw.githubusercontent.com/physical-computation/Warp-firmware/e5130824e266505947fd73f1bfdb33996190e637/src/boot/ksdk1.1.0/powermodes.c", "visit_date": "2023-07-23T13:01:33.818157" }
stackv2
#include <stdint.h> #include <stdlib.h> #include <string.h> #include "fsl_os_abstraction.h" #include "fsl_interrupt_manager.h" #include "fsl_power_manager.h" #include "fsl_gpio_driver.h" #include "fsl_llwu_hal.h" #include "fsl_smc_hal.h" #include "fsl_clock_manager.h" #include "fsl_sim_hal.h" #include "fsl_misc_utilities.h" #include "fsl_rtc_driver.h" #include "fsl_spi_master_driver.h" #include "config.h" #include "glaux.h" #include "warp.h" #include "gpio_pins.h" #include "devRV8803C7.h" /* * From KSDK power_manager_demo.c BEGIN>>> */ #if (!WARP_BUILD_ENABLE_DEVRV8803C7) static void setSleepRtcAlarm(uint32_t offsetSec) { rtc_datetime_t date; uint32_t seconds; // get date time and convert to seconds RTC_DRV_GetDatetime(0, &date); // convert to sec and add offset RTC_HAL_ConvertDatetimeToSecs(&date, &seconds); //TODO: should check for overflow... seconds += offsetSec; RTC_HAL_ConvertSecsToDatetime(&seconds, &date); // set the datetime for alarm if (RTC_DRV_SetAlarm(0, &date, true)) { //... } else { return; } } #endif void gpioDisableWakeUp(void) { /* * Disables interrupt on LLWU_Px. The BOARD_* defines are defined in warp.h */ PORT_HAL_SetPinIntMode(BOARD_SW_LLWU_BASE, BOARD_SW_LLWU_PIN, kPortIntDisabled); INT_SYS_DisableIRQ(BOARD_SW_LLWU_IRQ_NUM); } void gpioEnableWakeUp(void) { /* * To make assurance doubly sure, turn off RTC based on Errata 8068 / AN4503. * Revisit the need for this once we have more measurements: * * For KL03 chip errata 8068. See https://community.nxp.com/thread/350259, * combined with ideas from AN4503 page 2. * * Enabling this block will kill the RTC, which means no sleep routines, etc. */ volatile unsigned int dummyread; __asm("CPSID i"); /* Disable interrupts */ SIM->COPC=0x00; /* Disable COP watchdog */ dummyread = SIM->COPC; /* Read-after-write sequence */ /* * Errata 8068 fix */ SIM->SCGC6 |= SIM_SCGC6_RTC_MASK; /* Enable clock to RTC */ dummyread = SIM->SCGC6; /* Read-after-write sequence */ RTC->TSR = 0x00; /* Dummy write to RTC TSR per errata 8068 */ dummyread = RTC->TSR; /* Read-after-write sequence */ SIM->SCGC6 &= ~SIM_SCGC6_RTC_MASK; /* Disable clock to RTC */ dummyread = SIM->SCGC6; /* Read-after-write sequence */ /* * See also AN4503, Section 3.1.6. * * First, enable the PORTA clock but disable the PORTB clock. */ CLOCK_SYS_EnablePortClock(0); CLOCK_SYS_DisablePortClock(1); /* * * Next, make PTA0 switch from being SWD to being PTA0/LLWU_P7/IRQ0 * We don't need to revert this later, since waking up from VLLx is done * through a soft reset and that config is lost? (TODO: double check.) */ GPIO_DRV_Init(wakeupPins /* input pins */, NULL /* output pins */); PORT_HAL_SetMuxMode(PORTA_BASE, 0, kPortMuxAsGpio); /* * Enables any edge interrupt for the LLWU_Px pin */ PORT_HAL_SetPinIntMode(BOARD_SW_LLWU_BASE, BOARD_SW_LLWU_PIN, kPortIntEitherEdge); INT_SYS_EnableIRQ(BOARD_SW_LLWU_IRQ_NUM); /* * Redundant? Check. */ INT_SYS_EnableIRQ(LLWU_IRQn); LLWU_HAL_ClearExternalPinWakeupFlag(LLWU_BASE, (llwu_wakeup_pin_t)BOARD_SW_LLWU_EXT_PIN); /* * Configure LLWU_P7 as low-leakage wakeup source. * * See * * Kinetis SDK v.1.1 API Reference Manual Chapter 33. * * and * KL03 Sub-Family Reference Manual, Rev. 4, August, 2014, Chapter 19. * * Set to enable pin 7 (PTA0/IRQ0/LLWU_P7) as VLLx wakeup source, trigger on any edge. */ LLWU_HAL_SetExternalInputPinMode(LLWU_BASE, kLlwuExternalPinChangeDetect, (llwu_wakeup_pin_t)BOARD_SW_LLWU_EXT_PIN); USED(dummyread); } void updateClockManagerToRunMode(uint8_t cmConfigMode) { /* * If current config mode is RUN but CM is not, need to re-config it to RUN */ if ((cmConfigMode == CLOCK_CONFIG_INDEX_FOR_RUN) && (CLOCK_SYS_GetCurrentConfiguration() != CLOCK_CONFIG_INDEX_FOR_RUN)) { CLOCK_SYS_UpdateConfiguration(CLOCK_CONFIG_INDEX_FOR_RUN, kClockManagerPolicyForcible); } } void updateClockManagerToVlprMode(uint8_t cmConfigMode) { /* * If current config mode and CM are both RUN, need to re-config it to VLPR */ if ((cmConfigMode == CLOCK_CONFIG_INDEX_FOR_RUN) && (CLOCK_SYS_GetCurrentConfiguration() != CLOCK_CONFIG_INDEX_FOR_VLPR)) { CLOCK_SYS_UpdateConfiguration(CLOCK_CONFIG_INDEX_FOR_VLPR, kClockManagerPolicyForcible); } } void update_clock_mode(uint8_t cmConfigMode) { if (g_defaultClockConfigurations[cmConfigMode].mcgliteConfig.mcglite_mode == kMcgliteModeHirc48M) { CLOCK_SYS_UpdateConfiguration(CLOCK_CONFIG_INDEX_FOR_RUN, kClockManagerPolicyForcible); } else { updateClockManagerToRunMode(cmConfigMode); } } /* * From KSDK power_manager_demo.c <<END */ WarpStatus warpSetLowPowerMode(WarpPowerMode powerMode, uint32_t sleepSeconds) { uint8_t cmConfigMode = CLOCK_CONFIG_INDEX_FOR_RUN; power_manager_error_code_t status; switch (powerMode) { case kWarpPowerModeWAIT: { if (POWER_SYS_GetCurrentMode() == kPowerManagerVlpr) { return kWarpStatusPowerTransitionErrorVlpr2Wait; } #if (WARP_BUILD_ENABLE_DEVRV8803C7) /* * Program RV8803 external interrupt */ warpEnableI2Cpins(); setRTCCountdownRV8803C7(sleepSeconds, kWarpRV8803ExtTD_1HZ, true /* interupt_enable */); warpDisableI2Cpins(); gpioEnableWakeUp(); #else /* * In Glaux, because we have the external clock going to RTC_CLKIN, * we can actually have the RTC active in stop modes too. * * See footnote 5 of Table 7-2. "Module operation in low-power modes". * * TODO: Need to test Warp variant of firmware on Glaux HW and see if * we are able to wake from VLLS0. */ gpioDisableWakeUp(); setSleepRtcAlarm(sleepSeconds); #endif status = POWER_SYS_SetMode(powerMode, kPowerManagerPolicyAgreement); /* * After the mode transition returns (perhaps via interrupt handler) */ /* * For now, always go to VLPR upon completion of prior mode */ CLOCK_SYS_UpdateConfiguration(CLOCK_CONFIG_INDEX_FOR_VLPR, kClockManagerPolicyForcible); if (status != kPowerManagerSuccess) { return kWarpStatusErrorPowerSysSetmode; } break; } case kWarpPowerModeSTOP: { if (POWER_SYS_GetCurrentMode() == kPowerManagerVlpr) { return kWarpStatusPowerTransitionErrorVlpr2Stop; } #if (WARP_BUILD_ENABLE_DEVRV8803C7) /* * Program RV8803 external interrupt */ warpEnableI2Cpins(); setRTCCountdownRV8803C7(sleepSeconds, kWarpRV8803ExtTD_1HZ, true /* interupt_enable */); warpDisableI2Cpins(); gpioEnableWakeUp(); #else /* * In Glaux, because we have the external clock going to RTC_CLKIN, * we can actually have the RTC active in stop modes too. * * See footnote 5 of Table 7-2. "Module operation in low-power modes". * * TODO: Need to test Warp variant of firmware on Glaux HW and see if * we are able to wake from VLLS0. */ gpioDisableWakeUp(); setSleepRtcAlarm(sleepSeconds); #endif status = POWER_SYS_SetMode(powerMode, kPowerManagerPolicyAgreement); /* * For now, always go to VLPR upon completion of prior mode */ CLOCK_SYS_UpdateConfiguration(CLOCK_CONFIG_INDEX_FOR_VLPR, kClockManagerPolicyForcible); if (status != kPowerManagerSuccess) { return kWarpStatusErrorPowerSysSetmode; } break; } case kWarpPowerModeVLPR: { if(kPowerManagerVlpr != POWER_SYS_GetCurrentMode()) { if ( (cmConfigMode != CLOCK_CONFIG_INDEX_FOR_VLPR) && (CLOCK_SYS_GetCurrentConfiguration() != CLOCK_CONFIG_INDEX_FOR_VLPR) ) { CLOCK_SYS_UpdateConfiguration(CLOCK_CONFIG_INDEX_FOR_VLPR, kClockManagerPolicyForcible); } status = POWER_SYS_SetMode(powerMode, kPowerManagerPolicyAgreement); if (status != kPowerManagerSuccess) { return kWarpStatusErrorPowerSysSetmode; } } else { return kWarpStatusPowerTransitionErrorVlpr2Vlpr; } break; } case kWarpPowerModeVLPW: { if (POWER_SYS_GetCurrentMode() == kPowerManagerRun) { return kWarpStatusPowerTransitionErrorRun2Vlpw; } #if (WARP_BUILD_ENABLE_DEVRV8803C7) /* * Program RV8803 external interrupt */ warpEnableI2Cpins(); setRTCCountdownRV8803C7(sleepSeconds, kWarpRV8803ExtTD_1HZ, true /* interupt_enable */); warpDisableI2Cpins(); gpioEnableWakeUp(); #else /* * In Glaux, because we have the external clock going to RTC_CLKIN, * we can actually have the RTC active in stop modes too. * * See footnote 5 of Table 7-2. "Module operation in low-power modes". * * TODO: Need to test Warp variant of firmware on Glaux HW and see if * we are able to wake from VLLS0. */ gpioDisableWakeUp(); setSleepRtcAlarm(sleepSeconds); #endif status = POWER_SYS_SetMode(powerMode, kPowerManagerPolicyAgreement); if (POWER_SYS_GetCurrentMode() == kPowerManagerRun) { /* * For now, always go to VLPR upon completion of prior mode */ CLOCK_SYS_UpdateConfiguration(CLOCK_CONFIG_INDEX_FOR_VLPR, kClockManagerPolicyForcible); } if (status != kPowerManagerSuccess) { return kWarpStatusErrorPowerSysSetmode; } break; } case kWarpPowerModeVLPS: { #if (WARP_BUILD_ENABLE_DEVRV8803C7) /* * Program RV8803 external interrupt */ warpEnableI2Cpins(); setRTCCountdownRV8803C7(sleepSeconds, kWarpRV8803ExtTD_1HZ, true /* interupt_enable */); warpDisableI2Cpins(); gpioEnableWakeUp(); #else /* * In Glaux, because we have the external clock going to RTC_CLKIN, * we can actually have the RTC active in stop modes too. * * See footnote 5 of Table 7-2. "Module operation in low-power modes". * * TODO: Need to test Warp variant of firmware on Glaux HW and see if * we are able to wake from VLLS0. */ gpioDisableWakeUp(); setSleepRtcAlarm(sleepSeconds); #endif status = POWER_SYS_SetMode(powerMode, kPowerManagerPolicyAgreement); /* * After returning from RTC handler... */ if (POWER_SYS_GetCurrentMode() == kPowerManagerRun) { /* * For now, always go to VLPR upon completion of prior mode */ CLOCK_SYS_UpdateConfiguration(CLOCK_CONFIG_INDEX_FOR_VLPR, kClockManagerPolicyForcible); } if (status != kPowerManagerSuccess) { return kWarpStatusErrorPowerSysSetmode; } break; } case kWarpPowerModeRUN: { status = POWER_SYS_SetMode(powerMode, kPowerManagerPolicyAgreement); /* * In this case, we should return from POWER_SYS_SetMode() immediately * since we don't go to sleep. */ if (status != kPowerManagerSuccess) { return kWarpStatusErrorPowerSysSetmode; } else { CLOCK_SYS_UpdateConfiguration(CLOCK_CONFIG_INDEX_FOR_RUN, kClockManagerPolicyForcible); } break; } case kWarpPowerModeVLLS0: { #if (WARP_BUILD_ENABLE_DEVRV8803C7) /* * Program RV8803 external interrupt */ warpEnableI2Cpins(); setRTCCountdownRV8803C7(sleepSeconds, kWarpRV8803ExtTD_1HZ, true /* interupt_enable */); warpDisableI2Cpins(); /* * Since we wakeup via reset and we also turn these back on at reset: */ gpioEnableWakeUp(); #else /* * In Glaux, because we have the external clock going to RTC_CLKIN, * we can actually have the RTC active in stop modes too. * * See footnote 5 of Table 7-2. "Module operation in low-power modes". * * TODO: Need to test Warp variant of firmware on Glaux HW and see if * we are able to wake from VLLS0. */ gpioDisableWakeUp(); setSleepRtcAlarm(sleepSeconds); #endif status = POWER_SYS_SetMode(powerMode, kPowerManagerPolicyAgreement); /* * All the VLLSx sleeps can only wake up via a transition to * (soft) reset once their wakeup source fires. See, e.g., * AN4503 Figure 11. Therefore, if we get here, it must be that * POWER_SYS_SetMode() failed. */ return kWarpStatusErrorPowerSysSetmode; } case kWarpPowerModeVLLS1: { /* * TODO: this can be replaced using the internal RTC */ #if (WARP_BUILD_ENABLE_DEVRV8803C7) /* * Program RV8803 external interrupt */ warpEnableI2Cpins(); setRTCCountdownRV8803C7(sleepSeconds, kWarpRV8803ExtTD_1HZ, true /* interupt_enable */); warpDisableI2Cpins(); gpioEnableWakeUp(); #else /* * In Glaux, because we have the external clock going to RTC_CLKIN, * we can actually have the RTC active in stop modes too. * * See footnote 5 of Table 7-2. "Module operation in low-power modes". * * TODO: Need to test Warp variant of firmware on Glaux HW and see if * we are able to wake from VLLS0. */ gpioDisableWakeUp(); setSleepRtcAlarm(sleepSeconds); #endif status = POWER_SYS_SetMode(powerMode, kPowerManagerPolicyAgreement); /* * All the VLLSx sleeps can only wake up via a transition to * (soft) reset once their wakeup source fires. See, e.g., * AN4503 Figure 11. Therefore, if we get here, it must be that * POWER_SYS_SetMode() failed. */ return kWarpStatusErrorPowerSysSetmode; } case kWarpPowerModeVLLS3: { /* * TODO: this can be replaced using the internal RTC */ #if (WARP_BUILD_ENABLE_DEVRV8803C7) /* * Program RV8803 external interrupt */ warpEnableI2Cpins(); setRTCCountdownRV8803C7(sleepSeconds, kWarpRV8803ExtTD_1HZ, true /* interupt_enable */); warpDisableI2Cpins(); gpioEnableWakeUp(); #else /* * In Glaux, because we have the external clock going to RTC_CLKIN, * we can actually have the RTC active in stop modes too. * * See footnote 5 of Table 7-2. "Module operation in low-power modes". * * TODO: Need to test Warp variant of firmware on Glaux HW and see if * we are able to wake from VLLS0. */ gpioDisableWakeUp(); setSleepRtcAlarm(sleepSeconds); #endif status = POWER_SYS_SetMode(powerMode, kPowerManagerPolicyAgreement); /* * All the VLLSx sleeps can only wake up via a transition to * (soft) reset once their wakeup source fires. See, e.g., * AN4503 Figure 11. Therefore, if we get here, it must be that * POWER_SYS_SetMode() failed. */ return kWarpStatusErrorPowerSysSetmode; } default: { return kWarpStatusBadPowerModeSpecified; } } return kWarpStatusOK; }
2.09375
2
2024-11-18T21:51:55.251746+00:00
2019-10-17T17:45:10
3e51b7aa6399619ec9edbcbed00877aec1f05831
{ "blob_id": "3e51b7aa6399619ec9edbcbed00877aec1f05831", "branch_name": "refs/heads/master", "committer_date": "2019-10-17T17:45:10", "content_id": "7a2c0af420b9cafa07b38795f03045b10c2c7d3d", "detected_licenses": [ "MIT" ], "directory_id": "671c73e7bfc492f9853ccbc1e14e7ee5bc013948", "extension": "c", "filename": "SUM.C", "fork_events_count": 0, "gha_created_at": "2019-10-17T17:34:29", "gha_event_created_at": "2019-10-17T17:34:29", "gha_language": null, "gha_license_id": "MIT", "github_id": 215849830, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 175, "license": "MIT", "license_type": "permissive", "path": "/math/SUM.C", "provenance": "stackv2-0138.json.gz:145472", "repo_name": "shuvamkumar/c", "revision_date": "2019-10-17T17:45:10", "revision_id": "6c5c9e4445b6ecfb1e309f875e5ffec8f6dd2074", "snapshot_id": "4d3fc5763cda1dada2f7790b9fdaf893de01140b", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/shuvamkumar/c/6c5c9e4445b6ecfb1e309f875e5ffec8f6dd2074/math/SUM.C", "visit_date": "2020-08-18T23:53:19.486663" }
stackv2
#include<stdio.h> #include<conio.h> int main() { int a,b; printf("Enter 2 numbers"); scanf("%d %d",&a,&b); printf("Sum of the given numbers is : %d",a+b); getch(); return 0; }
2.578125
3
2024-11-18T21:51:55.461803+00:00
2015-03-10T08:34:45
f1ac7bb53d006586d9b8acfcdff6d1b64a9a53b1
{ "blob_id": "f1ac7bb53d006586d9b8acfcdff6d1b64a9a53b1", "branch_name": "refs/heads/master", "committer_date": "2015-03-10T08:34:45", "content_id": "f6e119802007f8e5a295f47d6a3092d6e214ae84", "detected_licenses": [ "Apache-2.0" ], "directory_id": "27ac23e4b496713d5d0ce999ff60c0c173d01b4d", "extension": "c", "filename": "kaa_profile_gen.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": 3111, "license": "Apache-2.0", "license_type": "permissive", "path": "/examples/c-sdk-sample/libs/kaa/src/gen/kaa_profile_gen.c", "provenance": "stackv2-0138.json.gz:145730", "repo_name": "bluetouch/kaa", "revision_date": "2015-03-10T08:34:45", "revision_id": "1daf014ad256a56255c87a7583ad8cafe50b7a14", "snapshot_id": "cff62308eb720246540644967c4c7973127c4f27", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/bluetouch/kaa/1daf014ad256a56255c87a7583ad8cafe50b7a14/examples/c-sdk-sample/libs/kaa/src/gen/kaa_profile_gen.c", "visit_date": "2020-12-25T10:08:37.560705" }
stackv2
/* * Copyright 2014-2015 CyberVision, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ # include <string.h> # include "../platform/stdio.h" # include "kaa_profile_gen.h" # include "../avro_src/avro/io.h" # include "../avro_src/encoding.h" # include "../utilities/kaa_mem.h" /* * AUTO-GENERATED CODE */ static void kaa_profile_profile_destroy(void* data) { if (data) { kaa_profile_profile_t* record = (kaa_profile_profile_t*)data; kaa_string_destroy(record->id); kaa_string_destroy(record->os_version); kaa_string_destroy(record->build); kaa_data_destroy(record); } } static void kaa_profile_profile_serialize(avro_writer_t writer, void* data) { if (data) { kaa_profile_profile_t* record = (kaa_profile_profile_t*)data; kaa_string_serialize(writer, record->id); avro_binary_encoding.write_long(writer, record->os); kaa_string_serialize(writer, record->os_version); kaa_string_serialize(writer, record->build); } } static size_t kaa_profile_profile_get_size(void* data) { if (data) { size_t record_size = 0; kaa_profile_profile_t* record = (kaa_profile_profile_t*)data; record_size += kaa_string_get_size(record->id); record_size += kaa_long_get_size((int64_t)record->os); record_size += kaa_string_get_size(record->os_version); record_size += kaa_string_get_size(record->build); return record_size; } return 0; } kaa_profile_profile_t* kaa_profile_profile_create() { kaa_profile_profile_t* record = (kaa_profile_profile_t*)KAA_CALLOC(1, sizeof(kaa_profile_profile_t)); if (record) { record->serialize = kaa_profile_profile_serialize; record->get_size = kaa_profile_profile_get_size; record->destroy = kaa_profile_profile_destroy; } return record; } kaa_profile_profile_t* kaa_profile_profile_deserialize(avro_reader_t reader) { kaa_profile_profile_t* record = (kaa_profile_profile_t*)KAA_MALLOC(sizeof(kaa_profile_profile_t)); if (record) { record->serialize = kaa_profile_profile_serialize; record->get_size = kaa_profile_profile_get_size; record->destroy = kaa_profile_profile_destroy; record->id = kaa_string_deserialize(reader); int64_t os_value; avro_binary_encoding.read_long(reader, &os_value); record->os = os_value; record->os_version = kaa_string_deserialize(reader); record->build = kaa_string_deserialize(reader); } return record; }
2
2
2024-11-18T21:51:55.709585+00:00
2023-07-17T17:25:58
b7062f6419703e73dbe24f512d677fa7dcd9bb48
{ "blob_id": "b7062f6419703e73dbe24f512d677fa7dcd9bb48", "branch_name": "refs/heads/master", "committer_date": "2023-07-17T17:25:58", "content_id": "e582ccb667e49c5522dbb73051ddcd8185f32d1f", "detected_licenses": [ "Apache-2.0" ], "directory_id": "d76510005376f12e0bf00af0dd0d3d0625dd8cdb", "extension": "c", "filename": "t.sys_ilb.c", "fork_events_count": 64, "gha_created_at": "2012-11-30T20:04:47", "gha_event_created_at": "2023-08-30T13:37:17", "gha_language": "C", "gha_license_id": "Apache-2.0", "github_id": 6944872, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3522, "license": "Apache-2.0", "license_type": "permissive", "path": "/arc/t.sys_ilb.c", "provenance": "stackv2-0138.json.gz:145990", "repo_name": "xtuml/mc", "revision_date": "2023-07-17T17:25:58", "revision_id": "07a977b3182f8bb4301cde987c07a4f1ba81c5ed", "snapshot_id": "c30f485aeb7c4b767308d11fe7e583a0bedf78b6", "src_encoding": "UTF-8", "star_events_count": 6, "url": "https://raw.githubusercontent.com/xtuml/mc/07a977b3182f8bb4301cde987c07a4f1ba81c5ed/arc/t.sys_ilb.c", "visit_date": "2023-07-21T19:21:18.330922" }
stackv2
/* * These routines provides a means to safely receive calls from interrupt * handlers or other tasks/threads/contexts. */ typedef void ( * interleaved_bridge_t )( void ); static interleaved_bridge_t interleaved_bridges[ ${te_ilb.define_name} ]; typedef struct { u4_t space[ (${te_ilb.data_define_name} + sizeof(u4_t) - 1) / sizeof(u4_t) ]; } ilb_data_t; static ilb_data_t ilb_data[ ${te_ilb.define_name} ]; static u1_t ilb_head = 0; static u1_t ilb_tail = 0; static bool ilb_empty = true; /* * Post a bridge routine for execution after any executing state * action completes. * Protect the data structures from being clobbered by another context * by disabling interrupts around the data access. * Return a pointer to the argument data used by this bridge operation. */ void * ${te_ilb.interleave_bridge}( void (vfp)(void) ) { void * ilb = 0; .if ( te_thread.enabled ) ${te_thread.mutex_lock}( SEMAPHORE_FLAVOR_ILB ); .end if ${disable_interrupts.result} if ( ( ilb_head == ilb_tail ) && ( true != ilb_empty ) ) { /* Overflowed array of interleaved bridges. */ ${te_callout.interleaved_bridge_overflow}(); } else { ilb_empty = false; ilb = (void *) &ilb_data[ ilb_head ]; interleaved_bridges[ ilb_head ] = vfp; /* Bump the head of the circular list. */ ilb_head = ( ilb_head == (${te_ilb.define_name} - 1) ) ? 0 : ilb_head + 1; } return ilb; } /* * Unlock the resource that is protecting our interleaved bridge. */ void ${te_ilb.interleave_bridge_done}( void ) { ${enable_interrupts.result} .if ( te_thread.enabled ) ${te_thread.mutex_unlock}( SEMAPHORE_FLAVOR_ILB ); ${te_thread.nonbusy_wake}( 0 ); /* Wake default thread to process. */ .end if } /* * Sequentially execute each of the bridge routines that have been * posted during the most recent executing state action. * Protect the data structures from being clobbered by another context * by disabling interrupts around the data access. */ bool ${te_ilb.dispatch}( void ) { bool rakedleaves = false; .if ( te_thread.enabled ) ${te_thread.mutex_lock}( SEMAPHORE_FLAVOR_ILB ); .end if ${disable_interrupts.result} if ( true != ilb_empty ) { do { ${enable_interrupts.result} .if ( te_thread.enabled ) ${te_thread.mutex_unlock}( SEMAPHORE_FLAVOR_ILB ); .end if rakedleaves = true; .if ( te_thread.serialize ) #ifdef ESCHER_SERIALIZE_DISPATCH ${te_thread.mutex_lock}( SEMAPHORE_FLAVOR_DISPATCH ); #endif .end if interleaved_bridges[ ilb_tail ](); /* Run with interrupts enabled. */ .if ( te_thread.serialize ) #ifdef ESCHER_SERIALIZE_DISPATCH ${te_thread.mutex_unlock}( SEMAPHORE_FLAVOR_DISPATCH ); #endif .end if .if ( te_thread.enabled ) ${te_thread.mutex_lock}( SEMAPHORE_FLAVOR_ILB ); .end if ${disable_interrupts.result} /* Bump the tail of the circular list. */ ilb_tail = ( ilb_tail == (${te_ilb.define_name} - 1) ) ? 0 : ilb_tail + 1; } while ( ilb_head != ilb_tail ); ilb_empty = true; } ${enable_interrupts.result} .if ( te_thread.enabled ) ${te_thread.mutex_unlock}( SEMAPHORE_FLAVOR_ILB ); .end if return rakedleaves; } /* * Get a pointer to the data for the current interleaved bridge. */ void * ${te_ilb.get_data}( void ) { void * ilb; .if ( te_thread.enabled ) ${te_thread.mutex_lock}( SEMAPHORE_FLAVOR_ILB ); .end if ilb = (void *) &ilb_data[ ilb_tail ]; .if ( te_thread.enabled ) ${te_thread.mutex_unlock}( SEMAPHORE_FLAVOR_ILB ); .end if return ilb; }
2.484375
2
2024-11-18T21:51:55.972423+00:00
2010-10-10T11:30:37
20c205e4c9f11892e1277b4b8d0529b65681ea1b
{ "blob_id": "20c205e4c9f11892e1277b4b8d0529b65681ea1b", "branch_name": "refs/heads/master", "committer_date": "2010-10-10T11:30:37", "content_id": "ec904085018391dfa900f166a11d97a800bb6db7", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "450ff8fcd04f109e31bcdc44622c30dfc295fc85", "extension": "h", "filename": "level.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 14550696, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1447, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/src/level.h", "provenance": "stackv2-0138.json.gz:146376", "repo_name": "Zirias/stoneage", "revision_date": "2010-10-10T11:30:37", "revision_id": "0c94d97ff9a5f6356b1243e123ee2e13cb1eb645", "snapshot_id": "6d07ade31c2b0087891b6b5038d6a6f586605d26", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/Zirias/stoneage/0c94d97ff9a5f6356b1243e123ee2e13cb1eb645/src/level.h", "visit_date": "2020-05-20T06:11:39.523348" }
stackv2
#ifndef STONEAGE_LEVEL_H #define STONEAGE_LEVEL_H #include "common.h" /** @file level.h * includes definition of class Level. */ /** number of builtin levels */ #define BUILTIN_LEVELS 3 struct Board; struct Entity; struct Resource; struct Level_impl; /** A class representing a level in the game. * This class is responsible for loading levels and initializing the Board * by creating the correspondent Entities. */ CLASS(Level) { INHERIT(Object); struct Level_impl *pimpl; /** Create entities for current level. * This function takes a pointer to an array of Entities and creates * them there according to the current level. All previous content of * the entities array is overwritten. * * It is the caller's responsibility to clean up the buffer before * passing it to this method! * * @param b The game's Board * @param buffer Poiner to an array of Entities to fill */ void FUNC(createEntities)(THIS, struct Board *b, struct Entity **buffer); /** Create a random level. */ void FUNC(random)(THIS); /** Load a builtin level. * Loads one of the hardcoded levels by index number. * @param num number of the level to load */ void FUNC(builtin)(THIS, int num); /** Load a level from a resource. * STUB * @param r the Resource to load the Level from */ void FUNC(load)(THIS, struct Resource *r); }; #endif
2.234375
2
2024-11-18T21:51:56.289519+00:00
2021-12-16T13:04:22
131614c8de6fbd2aefe0ea9835a827805403aab5
{ "blob_id": "131614c8de6fbd2aefe0ea9835a827805403aab5", "branch_name": "refs/heads/master", "committer_date": "2021-12-16T13:04:22", "content_id": "78b4fdee92fd096a933030cdee58660bab4a626a", "detected_licenses": [ "MIT" ], "directory_id": "ae57abcd8749d9dded05a17b437d11d64c75fbd9", "extension": "c", "filename": "timeCalculator.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 75947092, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 12404, "license": "MIT", "license_type": "permissive", "path": "/src/c/timeCalculator.c", "provenance": "stackv2-0138.json.gz:146765", "repo_name": "developer500/marathonSplit", "revision_date": "2021-12-16T13:04:22", "revision_id": "b88d5957e475afe321050a2b55eaf8ca38e9b19b", "snapshot_id": "717bf2e950223072a446f75376030d1109d6512d", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/developer500/marathonSplit/b88d5957e475afe321050a2b55eaf8ca38e9b19b/src/c/timeCalculator.c", "visit_date": "2022-01-02T18:23:16.008953" }
stackv2
#include <pebble.h> #include "timeCalculator.h" // Rollover happens when doing laps and there is 1 time band // no rollover is like a race multiple bands static bool s_noRollover = true; static time_tds s_startTime; static time_tds s_realStartTime; static time_tds s_pauseTime; static time_tds s_actualTimes[MAX_BANDS]; static int s_countDownBands = 0; static time_tds s_countDownBand[MAX_BANDS]; static time_tds s_totalBandTime; // required to forward declare. bool clearPausedFn(time_tds inCurrentTime); static void (*s_startFunctionP)(time_tds inCurrentTime); static bool (*s_pauseFunctionP)(time_tds inCurrentTime); int getCounDownBands() { return s_countDownBands; } time_tds getTimeForBand(int inCountDownBand) { return s_countDownBand[inCountDownBand]; } void setCountDownBands(time_tds countDownBandPtr[], int inNumBands) { s_countDownBands = inNumBands; for (int bandIndex = 0; bandIndex < inNumBands; bandIndex++) { s_countDownBand[bandIndex] = *countDownBandPtr; countDownBandPtr++; } } void setRollover(bool inHasRollover) { s_noRollover = !inHasRollover; } bool getIsStarted() { return s_startTime != 0; } bool getIsPaused() { return s_pauseTime != 0; } int getIndexOfFirstZeroActualTime() { for (int bandIndex = 0; bandIndex < MAX_BANDS ; bandIndex++) { if (s_actualTimes[bandIndex]==(time_tds)0) { return bandIndex; } } // could not be found. return -1; } int getIndexOfLastConfirmedBand() { int firstZeroActualBand = getIndexOfFirstZeroActualTime(); return firstZeroActualBand == -1 ? firstZeroActualBand : firstZeroActualBand -1; } time_tds getElapsedTime(time_tds inCurrentTime) { if (!getIsStarted()) { return (time_tds)0; } time_tds absoluteCurrentTime = getIsPaused() ? s_pauseTime : inCurrentTime; // eg 4:13:02 - current time or paused time. return absoluteCurrentTime - s_startTime; // eg 0:00:12 - 12 seconds since start was pressed. } time_tds getEstimatedBandTime(int inBandIndex) { return s_actualTimes[inBandIndex] == 0 ? s_countDownBand[inBandIndex] : s_actualTimes[inBandIndex]; } int getCurrrentBandAndSmallElapsed(time_tds inCurrentTime, time_tds* inOutSmallElapsd, bool inRoundForwards) { time_tds smallelapsedTime = getElapsedTime(inCurrentTime); int bandIndex = 0; time_tds estimatedBandTime = getEstimatedBandTime(bandIndex); while (smallelapsedTime >= estimatedBandTime) { bandIndex++; if (bandIndex==s_countDownBands) { if (s_noRollover) { bandIndex--; break; } } bandIndex %= s_countDownBands; smallelapsedTime -= estimatedBandTime; estimatedBandTime = getEstimatedBandTime(bandIndex); } if (inRoundForwards) { if (smallelapsedTime == getEstimatedBandTime(bandIndex)) { bandIndex++; if (bandIndex >= s_countDownBands) { if (s_noRollover) { bandIndex--; } else { bandIndex %= s_countDownBands; } } } } *inOutSmallElapsd = smallelapsedTime; return bandIndex; } time_tds getRemaingAndBandTime(time_tds inCurrentTime, time_tds (*inFunction)(time_tds inRemainingTime, int inBandIndex)) { if (!getIsStarted()) { return inFunction(s_countDownBand[0], 0); } time_tds smallElapsed = 0; int bandIndex = getCurrrentBandAndSmallElapsed(inCurrentTime, &smallElapsed, false); time_tds currentBandTime = s_countDownBand[bandIndex]; // if the bands are {4,3} then at t=0,7,14 elapsed will be 0 - when this happens make remaining 0 time_tds remainingTime = currentBandTime - smallElapsed; APP_LOG(APP_LOG_LEVEL_DEBUG, "Band >%d< Remaining >%d<", bandIndex,remainingTime ); return inFunction(remainingTime, bandIndex); } // If a runner is within this # of sec of the next band then jump forwards time_tds getMinimumJumpForwardTime(time_tds inCurrentBandTime) { // either 15 % or 25 sec which ever is bigger const time_tds ydSeconds = 250; const int lowPercent = 15; const int highPercent = 50; time_tds lowTime = inCurrentBandTime * lowPercent/ 100; time_tds highTime = inCurrentBandTime * highPercent / 100; time_tds retTime = lowTime; if (lowTime < ydSeconds) { retTime = ydSeconds; if (ydSeconds > highTime) { retTime = highTime; } } return retTime; } bool shouldJumpForwards(time_tds inSmallElapsed, int inBandIndex) { time_tds currentBandTime = s_countDownBand[inBandIndex]; time_tds remainingTime = currentBandTime - inSmallElapsed; if (remainingTime <= getMinimumJumpForwardTime(currentBandTime)) { return true; } if ((inBandIndex == (getIndexOfLastConfirmedBand() + 1)) && (inSmallElapsed > 200) ) { // within 20 seconds return true; } return false; } void setPaused(time_tds inCurrentTime) { s_pauseTime = inCurrentTime; } void clearPaused() { s_pauseTime = 0; } void populateActualTimes(time_tds inCurrentTime, time_tds inSmallElapsed, int inCurrentBand) { int firstZeroBand = getIndexOfFirstZeroActualTime(); if (firstZeroBand==-1) { APP_LOG(APP_LOG_LEVEL_ERROR, "Tried to populate actual times with no 1st zero band"); return; } bool jumpForwards = shouldJumpForwards(inSmallElapsed, inCurrentBand); if (!jumpForwards) { if ((firstZeroBand == 0) && (inCurrentBand==0)) { // The user pressed start then pressed start again quickly s_startTime = inCurrentTime; return; } if (inCurrentBand == firstZeroBand) { // Pressed start twice after crossing a band.. s_actualTimes[inCurrentBand-1] += inSmallElapsed; return; } } time_tds timeToDistribute = 0; int bandIndex = 0; for (bandIndex = firstZeroBand; bandIndex < inCurrentBand ; bandIndex++) { timeToDistribute += s_countDownBand[bandIndex]; } time_tds plannedTimeOverPeriod = timeToDistribute + (jumpForwards ? s_countDownBand[inCurrentBand] : 0); timeToDistribute += inSmallElapsed; // Jumping forwards means the current band is actually the next band. inCurrentBand += (jumpForwards ? 1 : 0); int lastBand = inCurrentBand -1; time_tds timeDistributed = 0; APP_LOG(APP_LOG_LEVEL_DEBUG, "======== Planned time over period >%d< %d", plannedTimeOverPeriod, timeToDistribute); for (bandIndex = firstZeroBand; bandIndex <= lastBand; bandIndex++) { s_actualTimes[bandIndex] = timeToDistribute * s_countDownBand[bandIndex] / plannedTimeOverPeriod; timeDistributed += s_actualTimes[bandIndex]; APP_LOG(APP_LOG_LEVEL_DEBUG, "Actual >%d< distributed >%d<", bandIndex, s_actualTimes[bandIndex]); } time_tds roundingError = timeToDistribute - timeDistributed; APP_LOG(APP_LOG_LEVEL_DEBUG, "Rounding %d", roundingError); for (bandIndex = lastBand; bandIndex > (lastBand - abs(roundingError)) ; bandIndex--) { time_tds roundingThisBand = roundingError > 0 ? 1 : -1; APP_LOG(APP_LOG_LEVEL_DEBUG, "Added %d to band %d", roundingThisBand, bandIndex); s_actualTimes[bandIndex] += roundingThisBand; } } void runningStartFn(time_tds inCurrentTime) { time_tds smallElapsed = 0; int currentBand = getCurrrentBandAndSmallElapsed(inCurrentTime, &smallElapsed, false); APP_LOG(APP_LOG_LEVEL_DEBUG, "Current >%d< small Elapsed >%d< last confirmed >%d<", inCurrentTime, smallElapsed, currentBand); populateActualTimes(inCurrentTime, smallElapsed, currentBand); // Did the user press reset which caused the clock to jump forwards and finish the set? if (getElapsedTime(inCurrentTime) >= s_totalBandTime) { setPaused(inCurrentTime); return; } clearPaused(); } void initialsetStartFn(time_tds inCurrentTime) { s_startTime = inCurrentTime; s_realStartTime = inCurrentTime; clearPaused(); s_startFunctionP = &runningStartFn; } bool initialPausedFn(time_tds inCurrentTime) { setPaused(inCurrentTime); s_pauseFunctionP = &clearPausedFn; return true; } bool clearPausedFn(time_tds inCurrentTime) { time_tds timeElapsedWhenPaused = inCurrentTime - s_pauseTime; s_startTime += timeElapsedWhenPaused; s_realStartTime += timeElapsedWhenPaused; clearPaused(); s_pauseFunctionP = &initialPausedFn; return false; } time_tds getActualTime(int inBandIndex) { return s_actualTimes[inBandIndex]; } void initDisplayTime() { s_startTime = 0; s_realStartTime = 0; s_pauseTime = 0; s_totalBandTime = 0; for (int bandIndex = 0; bandIndex < s_countDownBands; bandIndex++) { s_totalBandTime += s_countDownBand[bandIndex]; s_actualTimes[bandIndex] = (time_tds)0; } s_startFunctionP = &initialsetStartFn; s_pauseFunctionP = &initialPausedFn; } bool togglePaused(time_tds inCurrentTime) { return (*s_pauseFunctionP)(inCurrentTime); } time_tds getCurrentPlannedLapTime(time_tds inCurrentTime) { time_tds smallElapsed = 0; int bandIndex = getCurrrentBandAndSmallElapsed(inCurrentTime, &smallElapsed, true); return s_countDownBand[bandIndex]; } time_tds getTimeDiffFromPlanned() { time_tds plannedTime = 0; time_tds actualTime = 0; for (int bandIndex = 0; bandIndex < s_countDownBands ; bandIndex++) { plannedTime += s_countDownBand[bandIndex]; actualTime += s_actualTimes[bandIndex]; } return (actualTime - plannedTime); } int getCountDownBand(time_tds inCurrentTime) { time_tds smallElapsed = 0; int bandIndex = getCurrrentBandAndSmallElapsed(inCurrentTime, &smallElapsed, false); return s_countDownBands - bandIndex; } time_tds getRealElapsedTime(time_tds inCurrentTime) { if (!getIsStarted()) { return (time_tds)0; } time_tds absoluteCurrentTime = getIsPaused() ? s_pauseTime : inCurrentTime; // eg 4:13:02 - current time or paused time. return absoluteCurrentTime - s_realStartTime; // eg 0:00:12 - 12 seconds since start was pressed. } bool getIsFinished(time_tds inCurrentTime) { APP_LOG(APP_LOG_LEVEL_DEBUG, "GetIndex %d sCountDown %d", getIndexOfFirstZeroActualTime(), s_countDownBands); if (getIndexOfFirstZeroActualTime() == s_countDownBands) { return true; } return false; } time_tds getProjectedFinishTime(time_tds inCurrentTime) { time_tds smallElapsed = 0; int bandIndex = getCurrrentBandAndSmallElapsed(inCurrentTime, &smallElapsed, true); time_tds projectedFinishTime = getRealElapsedTime(inCurrentTime); for (; bandIndex < s_countDownBands; bandIndex++) { projectedFinishTime += s_countDownBand[bandIndex]; } return projectedFinishTime; } void addLap(time_tds inCurrentTime) { time_tds smallElapsed = 0; int bandIndex = getCurrrentBandAndSmallElapsed(inCurrentTime, &smallElapsed, false); time_tds newLapTime = s_countDownBand[bandIndex] - smallElapsed; s_countDownBands++; for (int bandIt = s_countDownBands-1; bandIt > (bandIndex+1); bandIt--) { s_countDownBand[bandIt] = s_countDownBand[bandIt-1]; } s_countDownBand[bandIndex] = smallElapsed; s_countDownBand[bandIndex + 1] = newLapTime; setStart(inCurrentTime); } time_tds getDisplayTimeFn(time_tds inRemainingTime, int inBandIndex) { // is the runner late getting to the split? if (inBandIndex > 0) { if ((inBandIndex-1) > getIndexOfLastConfirmedBand()) { time_tds currentBandTime = s_countDownBand[inBandIndex]; time_tds smallElapsed = currentBandTime - inRemainingTime; // is this 8% of the previous band? time_tds previousBandTimeFraction = s_countDownBand[inBandIndex-1] * 8 / 100; // or 10 whichever is higher if (previousBandTimeFraction<10) { previousBandTimeFraction=10; } if (smallElapsed <= previousBandTimeFraction) { // The runner is late - return -1 * smallElapsed; } } } return abs(inRemainingTime); } int getDisplayTime(time_tds inCurrentTime) { time_tds retTime = getRemaingAndBandTime(inCurrentTime, getDisplayTimeFn); // return retTime>=0 ? retTime/10 : (retTime-9)/10; return (retTime/10) % 1000; } time_tds getPercentCompleteTimes10Fn(time_tds inRemainingTime, int inBandIndex) { time_tds currentBandTime = s_countDownBand[inBandIndex]; return 1000 * (currentBandTime - inRemainingTime) / currentBandTime; } int getPercentCompleteTimes10(time_tds inCurrentTime) { return getRemaingAndBandTime(inCurrentTime, getPercentCompleteTimes10Fn); } void setStart(time_tds inCurrentTime) { (*s_startFunctionP)(inCurrentTime); }
2.484375
2
2024-11-18T21:51:58.289421+00:00
2015-01-24T10:46:50
7dc0d4531c87656b0d476a2b4e31f02efba69207
{ "blob_id": "7dc0d4531c87656b0d476a2b4e31f02efba69207", "branch_name": "refs/heads/master", "committer_date": "2015-01-24T10:46:50", "content_id": "ce00b9563b2970c412e99dd89efe5c1459ea12bb", "detected_licenses": [ "MIT" ], "directory_id": "399f23dfb7f9e5ff59dd83c6d04834a1db4df72e", "extension": "c", "filename": "string.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 16338871, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 165, "license": "MIT", "license_type": "permissive", "path": "/src/string.c", "provenance": "stackv2-0138.json.gz:147540", "repo_name": "chicyberwarrior/wos", "revision_date": "2015-01-24T10:46:50", "revision_id": "ebad1b22770798a1c583e2c02c2ba4698a449dd9", "snapshot_id": "6df769bbbe4a9377840daeec6fc73df718b30000", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/chicyberwarrior/wos/ebad1b22770798a1c583e2c02c2ba4698a449dd9/src/string.c", "visit_date": "2021-01-23T19:34:49.636203" }
stackv2
#include "string.h" #include "types.h" void memset(void *dest, int val, size_t len) { char *temp = (char *)dest; for ( ; len != 0; len--) *temp++ = val; }
2.3125
2
2024-11-18T21:51:58.493478+00:00
2018-07-11T11:40:14
9289855439be69ee530a513bcc8f614fcb0e0afb
{ "blob_id": "9289855439be69ee530a513bcc8f614fcb0e0afb", "branch_name": "refs/heads/master", "committer_date": "2018-07-11T11:40:14", "content_id": "69210d23c0bbcd50f2a9ba405209d532b2b9c64c", "detected_licenses": [ "MIT" ], "directory_id": "dd8da3aa401818453ee919c3236616911cc46b60", "extension": "c", "filename": "Led.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": 7504, "license": "MIT", "license_type": "permissive", "path": "/Software/Projects/F303K8/Board/Led.c", "provenance": "stackv2-0138.json.gz:147796", "repo_name": "jasonhaominglo/McuMiniSumoRobot", "revision_date": "2018-07-11T11:40:14", "revision_id": "32cdc587b705597104c1f4ff73aef7d1aabef10f", "snapshot_id": "cf871c5d0b13a25316a381b0b4b4cf21b2e731a1", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/jasonhaominglo/McuMiniSumoRobot/32cdc587b705597104c1f4ff73aef7d1aabef10f/Software/Projects/F303K8/Board/Led.c", "visit_date": "2022-02-03T15:42:45.695242" }
stackv2
/** * \file * \brief Implementation of a driver for the LEDs on the PRG_G board. * \author Erich Styger, [email protected] * * This module implements functions for the LEDs. */ #include "Platform.h" #include "Led.h" #include <stdbool.h> #if 0 /* not used */ #if PL_CONFIG_BOARD==PL_CONFIG_BOARD_ID_STM32_NUCLEO #include "stm32f3xx_hal.h" #endif #define LED0_On() HAL_GPIO_WritePin(GPIOB, GPIO_PIN_3, GPIO_PIN_SET) /*!< Turns the LED 0 on */ #if 0 #define LED1_On() HAL_GPIO_WritePin(GPIOF, GPIO_PIN_1, GPIO_PIN_RESET) /*!< Turns the LED 1 on */ #define LED2_On() HAL_GPIO_WritePin(GPIOF, GPIO_PIN_0, GPIO_PIN_RESET) /*!< Turns the LED 2 on */ #define LED3_On() HAL_GPIO_WritePin(GPIOB, GPIO_PIN_6, GPIO_PIN_RESET) /*!< Turns the LED 3 on */ #define LED4_On() HAL_GPIO_WritePin(GPIOB, GPIO_PIN_7, GPIO_PIN_RESET) /*!< Turns the LED 4 on */ #define LEDR_On() HAL_GPIO_WritePin(GPIOA, GPIO_PIN_9, GPIO_PIN_SET) /*!< Turns the red LED on */ #define LEDG_On() HAL_GPIO_WritePin(GPIOA, GPIO_PIN_12, GPIO_PIN_SET) /*!< Turns the green LED on */ #define LEDB_On() HAL_GPIO_WritePin(GPIOA, GPIO_PIN_10, GPIO_PIN_SET) /*!< Turns the blue LED on */ #endif #define LED0_Off() HAL_GPIO_WritePin(GPIOB, GPIO_PIN_3, GPIO_PIN_RESET) /*!< Turns the LED 0 off */ #if 0 #define LED1_Off() HAL_GPIO_WritePin(GPIOF, GPIO_PIN_1, GPIO_PIN_SET) /*!< Turns the LED 1 off */ #define LED2_Off() HAL_GPIO_WritePin(GPIOF, GPIO_PIN_0, GPIO_PIN_SET) /*!< Turns the LED 2 off */ #define LED3_Off() HAL_GPIO_WritePin(GPIOB, GPIO_PIN_6, GPIO_PIN_SET) /*!< Turns the LED 3 off */ #define LED4_Off() HAL_GPIO_WritePin(GPIOB, GPIO_PIN_7, GPIO_PIN_SET) /*!< Turns the LED 4 off */ #define LEDR_Off() HAL_GPIO_WritePin(GPIOA, GPIO_PIN_9, GPIO_PIN_RESET) /*!< Turns the red LED off */ #define LEDG_Off() HAL_GPIO_WritePin(GPIOA, GPIO_PIN_12, GPIO_PIN_RESET) /*!< Turns the green LED off */ #define LEDB_Off() HAL_GPIO_WritePin(GPIOA, GPIO_PIN_10, GPIO_PIN_RESET) /*!< Turns the blue LED off */ #endif #define LED0_Neg() HAL_GPIO_TogglePin(GPIOB, GPIO_PIN_3) /*!< Negates/toggles the LED 0 */ #if 0 #define LED1_Neg() HAL_GPIO_TogglePin(GPIOF, GPIO_PIN_1) /*!< Negates/toggles the LED 1 */ #define LED2_Neg() HAL_GPIO_TogglePin(GPIOF, GPIO_PIN_0) /*!< Negates/toggles the LED 2 */ #define LED3_Neg() HAL_GPIO_TogglePin(GPIOB, GPIO_PIN_6) /*!< Negates/toggles the LED 3 */ #define LED4_Neg() HAL_GPIO_TogglePin(GPIOB, GPIO_PIN_7) /*!< Negates/toggles the LED 4 */ #define LEDR_Neg() HAL_GPIO_TogglePin(GPIOA, GPIO_PIN_9) /*!< Negates/toggles the red LED */ #define LEDG_Neg() HAL_GPIO_TogglePin(GPIOA, GPIO_PIN_12) /*!< Negates/toggles the green LED */ #define LEDB_Neg() HAL_GPIO_TogglePin(GPIOA, GPIO_PIN_10) /*!< Negates/toggles the blue LED */ #endif #define LED0_Get() (HAL_GPIO_ReadPin(GPIOB, GPIO_PIN_3)==GPIO_PIN_SET?true:false) /*!< Return true if LED is turned on, false otherwise */ #if 0 #define LED1_Get() (HAL_GPIO_ReadPin(GPIOF, GPIO_PIN_1)==GPIO_PIN_SET?false:true) /*!< Return true if LED is turned on, false otherwise */ #define LED2_Get() (HAL_GPIO_ReadPin(GPIOF, GPIO_PIN_0)==GPIO_PIN_SET?false:true) /*!< Return true if LED is turned on, false otherwise */ #define LED3_Get() (HAL_GPIO_ReadPin(GPIOB, GPIO_PIN_6)==GPIO_PIN_SET?false:true) /*!< Return true if LED is turned on, false otherwise */ #define LED4_Get() (HAL_GPIO_ReadPin(GPIOB, GPIO_PIN_7)==GPIO_PIN_SET?false:true) /*!< Return true if LED is turned on, false otherwise */ #define LEDR_Get() (HAL_GPIO_ReadPin(GPIOA, GPIO_PIN_9)==GPIO_PIN_SET?true:false) /*!< Return true if LED is turned on, false otherwise */ #define LEDG_Get() (HAL_GPIO_ReadPin(GPIOA, GPIO_PIN_12)==GPIO_PIN_SET?true:false) /*!< Return true if LED is turned on, false otherwise */ #define LEDB_Get() (HAL_GPIO_ReadPin(GPIOA, GPIO_PIN_10)==GPIO_PIN_SET?true:false) /*!< Return true if LED is turned on, false otherwise */ #endif #define LED0_Put(on) HAL_GPIO_WritePin(GPIOB, GPIO_PIN_3, on?GPIO_PIN_SET:GPIO_PIN_RESET) /*!< Writes a boolean value to the LED 0 to turn it on or off */ #if 0 #define LED1_Put(on) HAL_GPIO_WritePin(GPIOF, GPIO_PIN_1, on?GPIO_PIN_RESET:GPIO_PIN_SET) /*!< Writes a boolean value to the LED 1 to turn it on or off */ #define LED2_Put(on) HAL_GPIO_WritePin(GPIOF, GPIO_PIN_0, on?GPIO_PIN_RESET:GPIO_PIN_SET) /*!< Writes a boolean value to the LED 2 to turn it on or off */ #define LED3_Put(on) HAL_GPIO_WritePin(GPIOB, GPIO_PIN_6, on?GPIO_PIN_RESET:GPIO_PIN_SET) /*!< Writes a boolean value to the LED 3 to turn it on or off */ #define LED4_Put(on) HAL_GPIO_WritePin(GPIOB, GPIO_PIN_7, on?GPIO_PIN_RESET:GPIO_PIN_SET) /*!< Writes a boolean value to the LED 4 to turn it on or off */ #define LEDR_Put(on) HAL_GPIO_WritePin(GPIOA, GPIO_PIN_9, on?GPIO_PIN_SET:GPIO_PIN_RESET) /*!< Writes a boolean value to the red LED to turn it on or off */ #define LEDG_Put(on) HAL_GPIO_WritePin(GPIOA, GPIO_PIN_12, on?GPIO_PIN_SET:GPIO_PIN_RESET) /*!< Writes a boolean value to the green LED to turn it on or off */ #define LEDB_Put(on) HAL_GPIO_WritePin(GPIOA, GPIO_PIN_10, on?GPIO_PIN_SET:GPIO_PIN_RESET) /*!< Writes a boolean value to the blue LED to turn it on or off */ #endif void LED_On(LED_LedId led) { switch(led) { case LED_LED0: LED0_On(); break; #if 0 case LED_LED1: LED1_On(); break; case LED_LED2: LED2_On(); break; case LED_LED3: LED3_On(); break; case LED_LED4: LED4_On(); break; case LED_LEDR: LEDR_On(); break; case LED_LEDG: LEDG_On(); break; case LED_LEDB: LEDB_On(); break; #endif default: break; } } void LED_Off(LED_LedId led) { switch(led) { case LED_LED0: LED0_Off(); break; #if 0 case LED_LED1: LED1_Off(); break; case LED_LED2: LED2_Off(); break; case LED_LED3: LED3_Off(); break; case LED_LED4: LED4_Off(); break; case LED_LEDR: LEDR_Off(); break; case LED_LEDG: LEDG_Off(); break; case LED_LEDB: LEDB_Off(); break; #endif default: break; } } void LED_Neg(LED_LedId led) { switch(led) { case LED_LED0: LED0_Neg(); break; #if 0 case LED_LED1: LED1_Neg(); break; case LED_LED2: LED2_Neg(); break; case LED_LED3: LED3_Neg(); break; case LED_LED4: LED4_Neg(); break; case LED_LEDR: LEDR_Neg(); break; case LED_LEDG: LEDG_Neg(); break; case LED_LEDB: LEDB_Neg(); break; #endif default: break; } } bool LED_Get(LED_LedId led) { switch(led) { case LED_LED0: return LED0_Get(); break; #if 0 case LED_LED1: return LED1_Get(); break; case LED_LED2: return LED2_Get(); break; case LED_LED3: return LED3_Get(); break; case LED_LED4: return LED4_Get(); break; case LED_LEDR: return LEDR_Get(); break; case LED_LEDG: return LEDG_Get(); break; case LED_LEDB: return LEDB_Get(); break; #endif default: break; } return false; /* default, error case */ } void LED_Put(LED_LedId led, bool on) { switch(led) { case LED_LED0: LED0_Put(on); break; #if 0 case LED_LED1: LED1_Put(on); break; case LED_LED2: LED2_Put(on); break; case LED_LED3: LED3_Put(on); break; case LED_LED4: LED4_Put(on); break; case LED_LEDR: LEDR_Put(on); break; case LED_LEDG: LEDG_Put(on); break; case LED_LEDB: LEDB_Put(on); break; #endif default: break; } } void LED_Init(void) { LED_Off(LED_LED0); #if 0 LED_Off(LED_LED1); LED_Off(LED_LED2); LED_Off(LED_LED3); LED_Off(LED_LED4); LED_Off(LED_LEDR); LED_Off(LED_LEDG); LED_Off(LED_LEDB); #endif } #endif
2.46875
2
2024-11-18T21:51:58.615177+00:00
2019-10-11T18:39:42
cb52aedacb44ae7734159b7caecdf7ed30d29490
{ "blob_id": "cb52aedacb44ae7734159b7caecdf7ed30d29490", "branch_name": "refs/heads/master", "committer_date": "2019-10-11T18:39:42", "content_id": "64f4b9f7717859074452a55e8731ae9945b2538a", "detected_licenses": [ "MIT" ], "directory_id": "3679455627086aade8a0038ab00ca83ec37aeaf8", "extension": "c", "filename": "type_cmp.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": 1074, "license": "MIT", "license_type": "permissive", "path": "/src/type_cmp.c", "provenance": "stackv2-0138.json.gz:147925", "repo_name": "stephensong/Fexl", "revision_date": "2019-10-11T18:39:42", "revision_id": "99765334309ad918bf4d4271f10505201e4a30b3", "snapshot_id": "60417a7f9a82cf4b192c56f83f11bdb9a4ef09b9", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/stephensong/Fexl/99765334309ad918bf4d4271f10505201e4a30b3/src/type_cmp.c", "visit_date": "2020-08-28T06:48:13.860101" }
stackv2
#include <num.h> #include <str.h> #include <value.h> #include <basic.h> #include <standard.h> #include <type_cmp.h> #include <type_num.h> #include <type_str.h> static value op_cmp(value f, int op(int)) { if (!f->L || !f->L->L) return 0; { value x = arg(f->L->R); value y = arg(f->R); if (x->T == type_num && y->T == type_num) f = boolean(op(num_cmp(get_num(x),get_num(y)))); else if (x->T == type_str && y->T == type_str) f = boolean(op(str_cmp(get_str(x),get_str(y)))); else f = hold(Qvoid); drop(x); drop(y); return f; } } static int lt(int x) { return x < 0; } static int le(int x) { return x <= 0; } static int eq(int x) { return x == 0; } static int ne(int x) { return x != 0; } static int ge(int x) { return x >= 0; } static int gt(int x) { return x > 0; } value type_lt(value f) { return op_cmp(f,lt); } value type_le(value f) { return op_cmp(f,le); } value type_eq(value f) { return op_cmp(f,eq); } value type_ne(value f) { return op_cmp(f,ne); } value type_ge(value f) { return op_cmp(f,ge); } value type_gt(value f) { return op_cmp(f,gt); }
2.53125
3
2024-11-18T21:51:59.002091+00:00
2018-06-08T11:54:28
39a16e707e6fc213eb7a1bfa07341789cf5d3fee
{ "blob_id": "39a16e707e6fc213eb7a1bfa07341789cf5d3fee", "branch_name": "refs/heads/master", "committer_date": "2018-06-08T11:54:28", "content_id": "9758af9cd0226eb32f39ceeec8f1bac1a5c179b6", "detected_licenses": [ "MIT" ], "directory_id": "f569fb842cb225affaabe991a51b30e1900053ee", "extension": "c", "filename": "socket_bind.c", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 132114831, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3474, "license": "MIT", "license_type": "permissive", "path": "/libsocket/src/c/socket_bind.c", "provenance": "stackv2-0138.json.gz:148310", "repo_name": "pribault/ft_ping", "revision_date": "2018-06-08T11:54:28", "revision_id": "accf713148480edaecba2027d100f3307df25930", "snapshot_id": "83fd023a4b899565126551570d30aff6684e5219", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/pribault/ft_ping/accf713148480edaecba2027d100f3307df25930/libsocket/src/c/socket_bind.c", "visit_date": "2020-03-15T11:09:54.736190" }
stackv2
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* socket_bind.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: pribault <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/04/16 14:13:41 by pribault #+# #+# */ /* Updated: 2018/04/28 17:50:01 by pribault ### ########.fr */ /* */ /* ************************************************************************** */ /* ** Copyright © 2018 <[email protected]> ** ** Permission is hereby granted, free of charge, to any person obtaining a ** copy of this software and associated documentation files (the “Software”), ** to deal in the Software without restriction, including without limitation ** the rights to use, copy, modify, merge, publish, distribute, sublicense, ** and/or sell copies of the Software, and to permit persons to whom the ** Software is furnished to do so, subject to the following conditions: ** ** The above copyright notice and this permission notice shall be included in ** all copies or substantial portions of the Software. ** ** THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL ** THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ** ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR ** OTHER DEALINGS IN THE SOFTWARE. */ #define LIBSOCKET_INTERNAL #include "libsocket.h" #include <errno.h> static void *init_addr(t_socket *msocket) { static struct sockaddr_in6 ipv6; static struct sockaddr_in ipv4; if (msocket->domain == IPV4) { ipv4.sin_family = msocket->domain; ipv4.sin_port = htons(msocket->port); ipv4.sin_addr.s_addr = INADDR_ANY; return (&ipv4); } else if (msocket->domain == IPV6) { ipv6.sin6_family = msocket->domain; ipv6.sin6_port = htons(msocket->port); ipv6.sin6_addr = in6addr_any; return (&ipv6); } return (NULL); } static int socket_bind_and_listen(t_socket *msocket) { void *addr; int n; if (!(addr = init_addr(msocket))) return (0); n = 1; if ((msocket->sockfd = socket(msocket->domain, msocket->protocol, 0)) < 0 || setsockopt(msocket->sockfd, SOL_SOCKET, SO_REUSEADDR, &n, sizeof(int)) < 0 || bind(msocket->sockfd, (void*)addr, (msocket->domain == IPV4) ? sizeof(struct sockaddr) : sizeof(struct sockaddr_in6)) < 0) return (0); if (msocket->protocol == TCP && listen(msocket->sockfd, msocket->queue_max) < 0) return (0); if (msocket->socket_bind) msocket->socket_bind(msocket); return (1); } int socket_bind(t_socket *socket, t_method method, char *port) { if ((socket->opt & SERVER_RUNNING)) return (0); socket->opt |= SERVER_RUNNING; socket->port = ft_atou(port); socket->protocol = method.protocol; socket->domain = method.domain; return (socket_bind_and_listen(socket)); }
2.109375
2
2024-11-18T21:52:01.505249+00:00
2015-03-12T05:41:44
6b677c49bc250d3dcf50fc4c436712372c6304bf
{ "blob_id": "6b677c49bc250d3dcf50fc4c436712372c6304bf", "branch_name": "refs/heads/master", "committer_date": "2015-03-12T05:41:44", "content_id": "33d533a2b5bf3ff5296e1aa79a9541287d6c26a4", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "b8382ed7cbbba58621218cc9bb986a8c17695a1e", "extension": "c", "filename": "obj.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 31897438, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1001, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/infix/obj.c", "provenance": "stackv2-0138.json.gz:148442", "repo_name": "cptaffe/shunting-yard", "revision_date": "2015-03-12T05:41:44", "revision_id": "943dca2ef4bd42ef8d832450def86dc47101bdeb", "snapshot_id": "78ae818e7acdf71691e26affb377bab654e5438d", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/cptaffe/shunting-yard/943dca2ef4bd42ef8d832450def86dc47101bdeb/infix/obj.c", "visit_date": "2020-06-04T01:35:53.808893" }
stackv2
// Copyright (c) 2015 Connor Taffe. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <infix_internal.h> #include <stdlib.h> #include <stdio.h> Obj *make_tobj(Operator op) { Obj *obj = calloc(sizeof(Obj), 1); obj->t = OP; obj->op = op; return obj; } Obj *make_iobj(int i) { Obj *obj = calloc(sizeof(Obj), 1); obj->t = INT; obj->i = i; return obj; } void free_obj(Obj *obj) { free(obj); } void print_obj(Obj *obj) { if (obj == NULL) { printf("()"); } else { if (obj->t == OP) { if (obj->op == ADD) { printf("+"); } else if (obj->op == SUB) { printf("-"); } else if (obj->op == MUL) { printf("*"); } else if (obj->op == DIV) { printf("/"); } else if (obj->op == LSHIFT) { printf("<<"); } else if (obj->op == RSHIFT) { printf(">>"); } else { // should never reach printf("?"); } } else if (obj->t == INT) { printf("%d", obj->i); } } }
2.859375
3
2024-11-18T21:52:01.885251+00:00
2014-09-01T20:16:34
dfde5adca4f1bd2e56960f45d701c71d31d5c3fa
{ "blob_id": "dfde5adca4f1bd2e56960f45d701c71d31d5c3fa", "branch_name": "refs/heads/master", "committer_date": "2014-09-01T20:16:34", "content_id": "50bc10a1315629172de10465959094f8e6d201b8", "detected_licenses": [ "Apache-2.0" ], "directory_id": "dc100e6e2d711d53f54f298a44ca63ce94350272", "extension": "c", "filename": "bmp2header_font.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 273790651, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5456, "license": "Apache-2.0", "license_type": "permissive", "path": "/serialGLCD/utility/bmp2header_font.c", "provenance": "stackv2-0138.json.gz:148570", "repo_name": "iorodeo/clearprep_prototype", "revision_date": "2014-09-01T20:16:34", "revision_id": "08b72bb2f90ac7421f8487a68d8468a90e784787", "snapshot_id": "bc0f9d11dd4627256e440eca8ead7cc2764666d9", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/iorodeo/clearprep_prototype/08b72bb2f90ac7421f8487a68d8468a90e784787/serialGLCD/utility/bmp2header_font.c", "visit_date": "2022-11-06T21:15:16.323371" }
stackv2
/* Copyright (c) 2010 Jennifer Holt 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. */ //bmp2header_font // by Jenn Holt //converts a bitmap picture containing N character images in the horizontal direction to a c header file of font data for Jenn Holt's sparkfun serial graphic LCD firmware //the input bitmap should be the height of your characters in the y direction and N*(width of your characters) in the x direction, where N is the number of characters in the font //Usage: bmp2header_font [width of character] [font space] [bitmap.bmp] > [file.h] //height of character is calculated from image, number of characters is int(bitmapwidth/characterwidth], if your image is a non-integral number of character widths wide, the extra will be ignored //outputs to stdout, use redirection to catch it in a file #include <stdlib.h> #include <stdio.h> #include <bmp.h> #include <string.h> int main(int argc, char **argv) { bitmap bmp; unsigned int y,w,h,Nrows,i,j,k,Nchars, charnum,char_w, char_bytes,font_size,font_space,firstbyte; unsigned char buff[128]; //buffer to hold a row of image data atexit(bmp_gc); if(argc==4) { if (!(bmp = bmp_load(argv[3]))) { fprintf(stderr,"Error creating image!\n"); return -2; } /* get the height and width of the image. */ w = bmp_get_width(bmp); h = bmp_get_height(bmp); //get font size data char_w = atoi(argv[1]); font_space = atoi(argv[2]); //verify font parameters //is size of character valid? //is number og bytes/character <=128? //check to make sure the character is not larger than the display if ( (char_w >128) || (h>64) ) { fprintf(stderr,"character is too large. max size is 128x64\n"); return -1; } //calculate the number of rows necessary(each row is 8 pixels tall) Nrows = h/8; //number of whole rows necessary if (h%8!=0) Nrows++; //a partial row counts too //calculate the number of characters in the image Nchars = (w/char_w); //calculate # of bytes per character char_bytes = Nrows*char_w; //calculate total number of bytes for font font_size = char_bytes*Nchars+3; //char_bytes repeated Nchars times +3 for font width,height,space //build font printf("static char text_array[%d] PROGMEM = {0x%.2x, 0x%.2x, 0x%.2x,\n",font_size,char_w,h,font_space); //print the array definition //now build image data firstbyte=0; //to get the right number of comma's in the array initilization for(charnum=0;charnum<Nchars;charnum++) //loop for each character in the image { for (i=0;i<Nrows;i++) //loop for each row { memset(buff,0x00,128); //clear all bytes in buffer for each new row for (j=0;j<char_w;j++) //loop for each byte in row { for(k=0;k<8;k++) //loop for each pixel in byte { //calculate the y coordinate of this bit(x coordinate is j+charnum*char_w) y = i*8+k; if (GetPixel(bmp,j+charnum*char_w,y)==0) //check if pixel is set { buff[j] |= ((unsigned char)1 << k); //set the pixel } } } //output row of data for (y=0;y<char_w;y++) { if (firstbyte==0) printf("0x%.2x",buff[y]); //write w bytes(1 for each x coordinate) else printf(", 0x%.2x",buff[y]); //write w bytes(1 for each x coordinate) firstbyte=1; } } printf("\n"); //print a newline to make the file pretty } printf("};\n"); //finish array definition } else { printf("Usage: bmp2header_font [character width in pixels] [spaceing in pixels] [infile.bmp] > header.h\n"); printf("Converts a 24bbp bitmap image with characters in the x direction into a header file array definition\n"); printf("for Jenn Holt's SparkFun graphical LCD firmware.\n"); printf("any pixel in the source identically equal to 0 is considered set in the font.\n"); } return 0; } int GetPixel(bitmap bmp,int x,int y) //returns pixel value from a bitmap { int pix; //integer to store pixel value 0x00RRGGBB int w,h,offset,padding; char *img; /* get the height and width of the image. */ w = bmp_get_width(bmp); h = bmp_get_height(bmp); /* get pointer to image data */ if (!(img = bmp_get_img(bmp))) { fprintf(stderr,"Cannot get image. Object does not exist\n"); } /*calculate offset to pixel of interest */ padding = (w % 4); //figure number of padding bytes offset = ((w*3+padding)*y + x*3); //3 bytes/pixel memcpy(&pix,(char*)(img+offset),3); //get data return pix; }
2.6875
3
2024-11-18T21:52:02.067875+00:00
2023-08-31T16:38:00
4c36ab730bce0ca8f1185ab60b0b4702a5b60b9e
{ "blob_id": "4c36ab730bce0ca8f1185ab60b0b4702a5b60b9e", "branch_name": "refs/heads/master", "committer_date": "2023-08-31T16:38:00", "content_id": "557655de4ebabd884950c33ec3eb51f2a404172b", "detected_licenses": [ "BSD-2-Clause", "BSD-2-Clause-Patent" ], "directory_id": "1efd2de8bf77ec00eb2fcaf5749278495946d920", "extension": "h", "filename": "common.h", "fork_events_count": 300, "gha_created_at": "2016-09-27T19:21:29", "gha_event_created_at": "2023-09-14T18:55:15", "gha_language": "C", "gha_license_id": "NOASSERTION", "github_id": 69390670, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 35006, "license": "BSD-2-Clause,BSD-2-Clause-Patent", "license_type": "permissive", "path": "/src/include/daos/common.h", "provenance": "stackv2-0138.json.gz:148833", "repo_name": "daos-stack/daos", "revision_date": "2023-08-31T16:38:00", "revision_id": "ed5eed5df43a68571afe123132a743824c02637a", "snapshot_id": "6f55bf3061fd830d5b8d28506e1295e2d3a27c38", "src_encoding": "UTF-8", "star_events_count": 631, "url": "https://raw.githubusercontent.com/daos-stack/daos/ed5eed5df43a68571afe123132a743824c02637a/src/include/daos/common.h", "visit_date": "2023-08-31T21:43:37.606145" }
stackv2
/** * (C) Copyright 2015-2023 Intel Corporation. * * SPDX-License-Identifier: BSD-2-Clause-Patent */ #ifndef __DAOS_COMMON_H__ #define __DAOS_COMMON_H__ #include <sys/time.h> #include <sys/types.h> #include <sys/param.h> #include <stdint.h> #include <inttypes.h> #include <unistd.h> #include <stdbool.h> #include <string.h> #include <ctype.h> #include <errno.h> #include <assert.h> #include <time.h> #include <stdlib.h> #include <stdio.h> #include <pthread.h> #include <byteswap.h> #include <daos_errno.h> #include <daos/debug.h> #include <gurt/hash.h> #include <gurt/common.h> #include <cart/api.h> #include <daos_types.h> #include <daos_obj.h> #include <daos_prop.h> #include <daos_security.h> #include <daos/profile.h> #include <daos/dtx.h> #include <daos/cmd_parser.h> #define DAOS_ON_VALGRIND D_ON_VALGRIND #define DF_OID DF_U64"."DF_U64 #define DP_OID(o) (o).hi, (o).lo #define DF_UOID DF_OID".%u.%u" #define DP_UOID(uo) DP_OID((uo).id_pub), (uo).id_shard, (uo).id_layout_ver #define DF_BOOL "%s" #define DP_BOOL(b) ((b) ? "true" : "false") #define DF_IOV "<%p, %zu/%zu>" #define DP_IOV(i) (i)->iov_buf, (i)->iov_len, (i)->iov_buf_len #define MAX_TREE_ORDER_INC 7 struct daos_node_overhead { /** Node size in bytes for tree with only */ int no_size; /** Order of node */ int no_order; }; /** Overheads for a tree */ struct daos_tree_overhead { /** Overhead for full size of leaf tree node */ struct daos_node_overhead to_leaf_overhead; /** Overhead for full size intermediate tree node */ int to_int_node_size; /** Overhead for dynamic tree nodes */ struct daos_node_overhead to_dyn_overhead[MAX_TREE_ORDER_INC]; /** Number of dynamic tree node sizes */ int to_dyn_count; /** Inline metadata size for each record */ int to_node_rec_msize; /** Dynamic metadata size of an allocated record. */ int to_record_msize; }; /** Points to a byte in an iov, in an sgl */ struct daos_sgl_idx { uint32_t iov_idx; /** index of iov */ daos_off_t iov_offset; /** byte offset of iov buf */ }; #define DF_SGL_IDX "{idx: %d, offset: "DF_U64"}" #define DP_SGL_IDX(i) (i)->iov_idx, (i)->iov_offset /* * add bytes to the sgl index offset. If the new offset is greater than or * equal to the indexed iov len, move the index to the next iov in the sgl. */ static inline void sgl_move_forward(d_sg_list_t *sgl, struct daos_sgl_idx *sgl_idx, uint64_t bytes) { sgl_idx->iov_offset += bytes; D_DEBUG(DB_TRACE, "Moving sgl index forward by %lu bytes." "Idx: "DF_SGL_IDX"\n", bytes, DP_SGL_IDX(sgl_idx)); /** move to next iov if necessary */ if (sgl_idx->iov_offset >= sgl->sg_iovs[sgl_idx->iov_idx].iov_buf_len) { sgl_idx->iov_idx++; sgl_idx->iov_offset = 0; D_DEBUG(DB_TRACE, "Moving to next iov in sgl\n"); } D_DEBUG(DB_TRACE, "Idx: "DF_SGL_IDX"\n", DP_SGL_IDX(sgl_idx)); } static inline void * sgl_indexed_byte(d_sg_list_t *sgl, struct daos_sgl_idx *sgl_idx) { D_DEBUG(DB_TRACE, "Idx: "DF_SGL_IDX"\n", DP_SGL_IDX(sgl_idx)); if (sgl_idx->iov_idx > sgl->sg_nr_out - 1) { D_DEBUG(DB_TRACE, "Index too high. Returning NULL\n"); return NULL; } return sgl->sg_iovs[sgl_idx->iov_idx].iov_buf + sgl_idx->iov_offset; } /* * If the byte count will exceed the current indexed iov, then move to * the next. */ static inline void sgl_test_forward(d_sg_list_t *sgl, struct daos_sgl_idx *sgl_idx, uint64_t bytes) { D_DEBUG(DB_TRACE, "Before Idx: "DF_SGL_IDX"\n", DP_SGL_IDX(sgl_idx)); if (sgl_idx->iov_offset + bytes > sgl->sg_iovs[sgl_idx->iov_idx].iov_len) { sgl_idx->iov_idx++; sgl_idx->iov_offset = 0; } D_DEBUG(DB_TRACE, "After Idx: "DF_SGL_IDX"\n", DP_SGL_IDX(sgl_idx)); } /* * Each thread has DF_UUID_MAX number of thread-local buffers for UUID strings. * Each debug message can have at most this many DP_UUIDs. * * DF_UUID prints the first eight characters of the string representation, * while DF_UUIDF prints the full 36-character string representation. DP_UUID() * matches both DF_UUID and DF_UUIDF. */ #define DF_UUID_MAX 8 #define DF_UUID "%.8s" #define DF_UUIDF "%s" char *DP_UUID(const void *uuid); /* For prefixes of error messages about a container */ #define DF_CONT DF_UUID"/"DF_UUID #define DP_CONT(puuid, cuuid) DP_UUID(puuid), DP_UUID(cuuid) #define DF_CONTF DF_UUIDF"/"DF_UUIDF #ifdef DAOS_BUILD_RELEASE #define DF_KEY "[%d]" #define DP_KEY(_key) (int)((_key)->iov_len) #define DF_DE "de[%zi]" #define DP_DE(_de) strnlen(_de, NAME_MAX) #else char * daos_key2str(daos_key_t *key); #define DF_KEY "[%d] '%s'" #define DP_KEY(key) (int)(key)->iov_len, daos_key2str(key) char * daos_de2str(const char *de); #define DF_DE "de'%s'" #define DP_DE(_de) daos_de2str(_de) #endif #define DF_RECX "["DF_X64"-"DF_X64"]" #define DP_RECX(r) (r).rx_idx, ((r).rx_idx + (r).rx_nr - 1) #define DF_IOM "{nr: %d, lo: "DF_RECX", hi: "DF_RECX"}" #define DP_IOM(m) (m)->iom_nr, DP_RECX((m)->iom_recx_lo), \ DP_RECX((m)->iom_recx_hi) static inline uint64_t daos_u64_hash(uint64_t val, unsigned int bits) { uint64_t hash = val; hash *= DGOLDEN_RATIO_PRIME_64; return hash >> (64 - bits); } static inline uint32_t daos_u32_hash(uint64_t key, unsigned int bits) { return (DGOLDEN_RATIO_PRIME_32 * key) >> (32 - bits); } #define LOWEST_BIT_SET(x) ((x) & ~((x) - 1)) static inline uint8_t isset_range(uint8_t *bitmap, uint32_t start, uint32_t end) { uint32_t index; for (index = start; index <= end; ++index) if (isclr(bitmap, index)) return 0; return 1; } static inline uint8_t isclr_range(uint8_t *bitmap, uint32_t start, uint32_t end) { uint32_t index; for (index = start; index <= end; ++index) if (isset(bitmap, index)) return 0; return 1; } static inline void clrbit_range(uint8_t *bitmap, uint32_t start, uint32_t end) { uint32_t index; for (index = start; index <= end; ++index) clrbit(bitmap, index); } static inline void setbit_range(uint8_t *bitmap, uint32_t start, uint32_t end) { uint32_t index; for (index = start; index <= end; ++index) setbit(bitmap, index); } static inline unsigned int daos_power2_nbits(unsigned int val) { unsigned int shift; for (shift = 1; (val >> shift) != 0; shift++); return val == LOWEST_BIT_SET(val) ? shift - 1 : shift; } static inline bool daos_uuid_valid(const uuid_t uuid) { return uuid && !uuid_is_null(uuid); } static inline bool daos_rank_list_valid(const d_rank_list_t *rl) { return rl && rl->rl_ranks && rl->rl_nr; } static inline uint64_t daos_get_ntime(void) { struct timespec tv; d_gettime(&tv); return ((uint64_t)tv.tv_sec * NSEC_PER_SEC + tv.tv_nsec); } static inline uint64_t daos_getntime_coarse(void) { struct timespec tv; clock_gettime(CLOCK_MONOTONIC_COARSE, &tv); return ((uint64_t)tv.tv_sec * NSEC_PER_SEC + tv.tv_nsec); } static inline uint64_t daos_wallclock_secs(void) { struct timespec now; int rc; rc = clock_gettime(CLOCK_REALTIME, &now); if (rc) { D_ERROR("clock_gettime failed, rc: %d, errno %d(%s).\n", rc, errno, strerror(errno)); return 0; } return now.tv_sec; } static inline uint64_t daos_getmtime_coarse(void) { struct timespec tv; clock_gettime(CLOCK_MONOTONIC_COARSE, &tv); return ((uint64_t)tv.tv_sec * 1000 + tv.tv_nsec / NSEC_PER_MSEC); } static inline uint64_t daos_getutime(void) { struct timespec tv; d_gettime(&tv); return d_time2us(tv); } static inline uint64_t daos_gettime_coarse(void) { struct timespec tv; clock_gettime(CLOCK_MONOTONIC_COARSE, &tv); return tv.tv_sec; } /** Function table for combsort and binary search */ typedef struct { void (*so_swap)(void *array, int a, int b); /** * For ascending order: * 0 array[a] == array[b] * 1 array[a] > array[b] * -1 array[a] < array[b] */ int (*so_cmp)(void *array, int a, int b); /** for binary search, returned value is the same as so_cmp() */ int (*so_cmp_key)(void *array, int i, uint64_t key); } daos_sort_ops_t; int daos_array_sort(void *array, unsigned int len, bool unique, daos_sort_ops_t *ops); int daos_array_find(void *array, unsigned int len, uint64_t key, daos_sort_ops_t *ops); int daos_array_find_le(void *array, unsigned int len, uint64_t key, daos_sort_ops_t *ops); int daos_array_find_ge(void *array, unsigned int len, uint64_t key, daos_sort_ops_t *ops); void daos_array_shuffle(void *arr, unsigned int len, daos_sort_ops_t *ops); int daos_sgls_copy_ptr(d_sg_list_t *dst, int dst_nr, d_sg_list_t *src, int src_nr); int daos_sgls_copy_data_out(d_sg_list_t *dst, int dst_nr, d_sg_list_t *src, int src_nr); int daos_sgls_copy_all(d_sg_list_t *dst, int dst_nr, d_sg_list_t *src, int src_nr); int daos_sgl_copy_data_out(d_sg_list_t *dst, d_sg_list_t *src); int daos_sgl_copy_data(d_sg_list_t *dst, d_sg_list_t *src); int daos_sgl_alloc_copy_data(d_sg_list_t *dst, d_sg_list_t *src); int daos_sgls_alloc(d_sg_list_t *dst, d_sg_list_t *src, int nr); int daos_sgl_merge(d_sg_list_t *dst, d_sg_list_t *src); daos_size_t daos_sgl_data_len(d_sg_list_t *sgl); daos_size_t daos_sgl_buf_size(d_sg_list_t *sgl); daos_size_t daos_sgls_buf_size(d_sg_list_t *sgls, int nr); daos_size_t daos_sgls_packed_size(d_sg_list_t *sgls, int nr, daos_size_t *buf_size); int daos_sgl_buf_extend(d_sg_list_t *sgl, int idx, size_t new_size); /** Move to next iov, it's caller's responsibility to ensure the idx boundary */ #define daos_sgl_next_iov(iov_idx, iov_off) \ do { \ (iov_idx)++; \ (iov_off) = 0; \ } while (0) /** Get the leftover space in an iov of sgl */ #define daos_iov_left(sgl, iov_idx, iov_off) \ ((sgl)->sg_iovs[iov_idx].iov_buf_len - (iov_off)) /** get remaining space in an iov, assuming that iov_len is used and * iov_buf_len is total in buf */ #define daos_iov_remaining(iov) ((iov).iov_buf_len > (iov).iov_len ? \ (iov).iov_buf_len - (iov).iov_len : 0) /** * Move sgl forward from iov_idx/iov_off, with move_dist distance. It is * caller's responsibility to check the boundary. */ #define daos_sgl_move(sgl, iov_idx, iov_off, move_dist) \ do { \ uint64_t moved = 0, step, iov_left; \ if ((move_dist) <= 0) \ break; \ while (moved < (move_dist)) { \ iov_left = daos_iov_left(sgl, iov_idx, iov_off); \ step = MIN(iov_left, (move_dist) - moved); \ (iov_off) += step; \ moved += step; \ if (daos_iov_left(sgl, iov_idx, iov_off) == 0) \ daos_sgl_next_iov(iov_idx, iov_off); \ } \ D_ASSERT(moved == (move_dist)); \ } while (0) /** * Consume buffer of length\a size for \a sgl with \a iov_idx and \a iov_off. * The consumed buffer location will be returned by \a iovs and \a iov_nr. */ #define daos_sgl_consume(sgl, iov_idx, iov_off, size, iovs, iov_nr) \ do { \ uint64_t consumed = 0, step, iov_left; \ uint32_t consume_idx = 0; \ if ((size) <= 0) \ break; \ while (consumed < (size)) { \ iov_left = daos_iov_left(sgl, iov_idx, iov_off); \ step = MIN(iov_left, (size) - consumed); \ iovs[consume_idx].iov_buf = \ (sgl)->sg_iovs[iov_idx].iov_buf + (iov_off); \ iovs[consume_idx].iov_len = step; \ iovs[consume_idx].iov_buf_len = step; \ consume_idx++; \ (iov_off) += step; \ consumed += step; \ if (daos_iov_left(sgl, iov_idx, iov_off) == 0) \ daos_sgl_next_iov(iov_idx, iov_off); \ } \ (iov_nr) = consume_idx; \ D_ASSERT(consumed == (size)); \ } while (0) #ifndef roundup #define roundup(x, y) ((((x) + ((y) - 1)) / (y)) * (y)) #endif #ifndef rounddown #define rounddown(x, y) (((x) / (y)) * (y)) #endif /** * Request a buffer of length \a bytes_needed from the sgl starting at * index \a idx. The length of the resulting buffer will be the number * of requested bytes if available in the indexed I/O vector or the max bytes * that can be taken from the indexed I/O vector. The index will be incremented * to point to just after the buffer returned. If the end of an I/O vector is * reached then the index will point to the beginning of the next. It is * possible for the index reach past the SGL. In this case the function will * return true, meaning the end was reached. * * @param[in] sgl sgl to be read from * @param[in] check_buf if true process on the sgl buf len instead of iov_len * @param[in/out] idx index into the sgl to start reading from * @param[in] buf_len_req number of bytes requested * @param[out] p_buf resulting pointer to buffer * @param[out] p_buf_len length of buffer * * @return true if end of SGL was reached */ bool daos_sgl_get_bytes(d_sg_list_t *sgl, bool check_buf, struct daos_sgl_idx *idx, size_t buf_len_req, uint8_t **p_buf, size_t *p_buf_len); typedef int (*daos_sgl_process_cb)(uint8_t *buf, size_t len, void *args); /** * Process bytes of an SGL. The process callback will be called for * each contiguous set of bytes provided in the SGL's I/O vectors. * * @param sgl sgl to process * @param check_buf if true process on the sgl buf len instead of iov_len * @param idx index to keep track of what's been processed * @param requested_bytes number of bytes to process * @param process_cb callback function for the processing * @param cb_args arguments for the callback function * * @return Result of the callback function. * Expectation is 0 is success. */ int daos_sgl_processor(d_sg_list_t *sgl, bool check_buf, struct daos_sgl_idx *idx, size_t requested_bytes, daos_sgl_process_cb process_cb, void *cb_args); char *daos_str_trimwhite(char *str); int daos_iov_copy(d_iov_t *dst, d_iov_t *src); int daos_iov_alloc(d_iov_t *iov, daos_size_t size, bool set_full); void daos_iov_free(d_iov_t *iov); bool daos_iov_cmp(d_iov_t *iov1, d_iov_t *iov2); void daos_iov_append(d_iov_t *iov, void *buf, uint64_t buf_len); #define daos_key_match(key1, key2) daos_iov_cmp(key1, key2) #if !defined(container_of) /* given a pointer @ptr to the field @member embedded into type (usually * * struct) @type, return pointer to the embedding instance of @type. */ # define container_of(ptr, type, member) \ ((type *)((char *)(ptr) - (char *)(&((type *)0)->member))) #endif #ifndef offsetof # define offsetof(typ, memb) ((long)((char *)&(((typ *)0)->memb))) #endif #ifndef ARRAY_SIZE #define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0])) #endif #ifndef MIN # define MIN(a, b) (((a) < (b)) ? (a) : (b)) #endif #ifndef MAX # define MAX(a, b) (((a) > (b)) ? (a) : (b)) #endif #ifndef min #define min(x, y) ((x) < (y) ? (x) : (y)) #endif #ifndef max #define max(x, y) ((x) > (y) ? (x) : (y)) #endif #ifndef min_t #define min_t(type, x, y) \ ({ type __x = (x); type __y = (y); __x < __y ? __x : __y; }) #endif #ifndef max_t #define max_t(type, x, y) \ ({ type __x = (x); type __y = (y); __x > __y ? __x : __y; }) #endif #define DAOS_UUID_STR_SIZE 37 /* 36 + 1 for '\0' */ /* byte swapper */ #define D_SWAP16(x) bswap_16(x) #define D_SWAP32(x) bswap_32(x) #define D_SWAP64(x) bswap_64(x) #define D_SWAP16S(x) do { *(x) = D_SWAP16(*(x)); } while (0) #define D_SWAP32S(x) do { *(x) = D_SWAP32(*(x)); } while (0) #define D_SWAP64S(x) do { *(x) = D_SWAP64(*(x)); } while (0) /** * Convert system errno to DER_* variant. Default error code for any non-defined * system errnos is DER_MISC (miscellaneous error). * * \param[in] err System error code * * \return Corresponding DER_* error code */ static inline int daos_errno2der(int err) { if (err < 0) { D_ERROR("error < 0 (%d)\n", err); return -DER_UNKNOWN; } switch (err) { case 0: return -DER_SUCCESS; case EPERM: case EACCES: return -DER_NO_PERM; case ENOMEM: return -DER_NOMEM; case EDQUOT: case ENOSPC: return -DER_NOSPACE; case EEXIST: return -DER_EXIST; case ENOENT: return -DER_NONEXIST; case ECANCELED: return -DER_CANCELED; case EBUSY: return -DER_BUSY; case EOVERFLOW: return -DER_OVERFLOW; case EBADF: return -DER_NO_HDL; case ENOSYS: return -DER_NOSYS; case ETIMEDOUT: return -DER_TIMEDOUT; case EWOULDBLOCK: return -DER_AGAIN; case EPROTO: return -DER_PROTO; case EINVAL: return -DER_INVAL; case ENOTDIR: return -DER_NOTDIR; case EIO: return -DER_IO; case EFAULT: case ENXIO: case ENODEV: default: return -DER_MISC; } } /** * Convert DER_ errno to system variant. Default error code for any non-defined * DER_ errnos is EIO (Input/Output error). * * \param[in] err DER_ error code * * \return Corresponding system error code */ static inline int daos_der2errno(int err) { if (err > 0) { D_ERROR("error > 0 (%d)\n", err); return EINVAL; } switch (err) { case -DER_SUCCESS: return 0; case -DER_NO_PERM: case -DER_EP_RO: case -DER_EP_OLD: return EPERM; case -DER_ENOENT: case -DER_NONEXIST: return ENOENT; case -DER_INVAL: case -DER_NOTYPE: case -DER_NOSCHEMA: case -DER_NOLOCAL: case -DER_NO_HDL: case -DER_IO_INVAL: return EINVAL; case -DER_KEY2BIG: case -DER_REC2BIG: return E2BIG; case -DER_EXIST: return EEXIST; case -DER_UNREACH: return EHOSTUNREACH; case -DER_NOSPACE: return ENOSPC; case -DER_ALREADY: return EALREADY; case -DER_DOS: case -DER_NOMEM: return ENOMEM; case -DER_TIMEDOUT: return ETIMEDOUT; case -DER_BUSY: case -DER_EQ_BUSY: return EBUSY; case -DER_AGAIN: return EAGAIN; case -DER_PROTO: return EPROTO; case -DER_IO: return EIO; case -DER_CANCELED: return ECANCELED; case -DER_OVERFLOW: return EOVERFLOW; case -DER_BADPATH: case -DER_NOTDIR: return ENOTDIR; case -DER_STALE: return ESTALE; case -DER_TX_RESTART: return ERESTART; default: return EIO; } }; static inline bool daos_crt_network_error(int err) { return err == -DER_HG || err == -DER_UNREACH || err == -DER_CANCELED || err == -DER_NOREPLY || err == -DER_OOG; } /** See crt_quiet_error. */ static inline bool daos_quiet_error(int err) { return crt_quiet_error(err); } #define daos_rank_list_dup d_rank_list_dup #define daos_rank_list_dup_sort_uniq d_rank_list_dup_sort_uniq #define daos_rank_list_filter d_rank_list_filter #define daos_rank_list_merge d_rank_list_merge #define daos_rank_list_alloc d_rank_list_alloc #define daos_rank_list_copy d_rank_list_copy #define daos_rank_list_shuffle d_rank_list_shuffle #define daos_rank_list_sort d_rank_list_sort #define daos_rank_list_find d_rank_list_find #define daos_rank_list_identical d_rank_list_identical #define daos_rank_in_rank_list d_rank_in_rank_list #define daos_rank_list_append d_rank_list_append void daos_fail_loc_set(uint64_t id); void daos_fail_loc_reset(void); void daos_fail_value_set(uint64_t val); void daos_fail_num_set(uint64_t num); uint64_t daos_shard_fail_value(uint16_t *shards, int nr); bool daos_shard_in_fail_value(uint16_t shard); int daos_fail_check(uint64_t id); uint64_t daos_fail_value_get(void); int daos_fail_init(void); void daos_fail_fini(void); /** * DAOS FAIL Mask * * fail loc 0-24 * [0-16] fail id * [16-24] fail group id used to index in cart injection array. * fail mode 24-32 * unused 32-64 **/ #define DAOS_FAIL_MASK_LOC (0x000000ffff) /* fail mode */ #define DAOS_FAIL_ONCE 0x1000000 #define DAOS_FAIL_SOME 0x2000000 #define DAOS_FAIL_ALWAYS 0x4000000 #define DAOS_FAIL_ID_MASK 0xffffff #define DAOS_FAIL_GROUP_MASK 0xff0000 #define DAOS_FAIL_GROUP_SHIFT 16 enum { DAOS_FAIL_UNIT_TEST_GROUP = 1, DAOS_FAIL_SYS_TEST_GROUP = 2, DAOS_FAIL_MAX_GROUP }; #define DAOS_FAIL_ID_GET(fail_loc) (fail_loc & DAOS_FAIL_ID_MASK) #define DAOS_FAIL_UNIT_TEST_GROUP_LOC \ (DAOS_FAIL_UNIT_TEST_GROUP << DAOS_FAIL_GROUP_SHIFT) #define DAOS_FAIL_SYS_TEST_GROUP_LOC \ (DAOS_FAIL_SYS_TEST_GROUP << DAOS_FAIL_GROUP_SHIFT) #define DAOS_FAIL_GROUP_GET(fail_loc) \ ((fail_loc & DAOS_FAIL_GROUP_MASK) >> DAOS_FAIL_GROUP_SHIFT) #define DAOS_SHARD_OBJ_UPDATE_TIMEOUT (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x01) #define DAOS_SHARD_OBJ_FETCH_TIMEOUT (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x02) #define DAOS_SHARD_OBJ_FAIL (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x03) #define DAOS_OBJ_UPDATE_NOSPACE (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x04) #define DAOS_SHARD_OBJ_RW_CRT_ERROR (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x05) #define DAOS_OBJ_REQ_CREATE_TIMEOUT (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x06) #define DAOS_SHARD_OBJ_UPDATE_TIMEOUT_SINGLE \ (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x07) #define DAOS_OBJ_SPECIAL_SHARD (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x08) #define DAOS_OBJ_TGT_IDX_CHANGE (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x09) #define DAOS_REBUILD_DROP_SCAN (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x0a) #define DAOS_REBUILD_NO_HDL (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x0b) #define DAOS_REBUILD_DROP_OBJ (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x0c) #define DAOS_REBUILD_UPDATE_FAIL (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x0d) #define DAOS_REBUILD_STALE_POOL (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x0e) #define DAOS_REBUILD_TGT_IV_UPDATE_FAIL (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x0f) #define DAOS_REBUILD_TGT_START_FAIL (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x10) #define DAOS_REBUILD_DISABLE (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x11) #define DAOS_REBUILD_TGT_SCAN_HANG (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x12) #define DAOS_REBUILD_TGT_REBUILD_HANG (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x13) #define DAOS_REBUILD_HANG (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x14) #define DAOS_REBUILD_TGT_SEND_OBJS_FAIL (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x15) #define DAOS_REBUILD_NO_REBUILD (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x16) #define DAOS_REBUILD_NO_UPDATE (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x17) #define DAOS_REBUILD_TGT_NOSPACE (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x18) #define DAOS_REBUILD_DELAY (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x19) #define DAOS_RDB_SKIP_APPENDENTRIES_FAIL (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x1a) #define DAOS_FORCE_REFRESH_POOL_MAP (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x1b) #define DAOS_FORCE_CAPA_FETCH (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x1e) #define DAOS_FORCE_PROP_VERIFY (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x1f) /** These faults simulate corruption over the network. Can be set on the client * or server side. */ #define DAOS_CSUM_CORRUPT_UPDATE (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x20) #define DAOS_CSUM_CORRUPT_FETCH (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x21) #define DAOS_CSUM_CORRUPT_UPDATE_AKEY (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x22) #define DAOS_CSUM_CORRUPT_FETCH_AKEY (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x23) #define DAOS_CSUM_CORRUPT_UPDATE_DKEY (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x24) #define DAOS_CSUM_CORRUPT_FETCH_DKEY (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x25) /** This fault simulates corruption on disk. Must be set on server side. */ #define DAOS_CSUM_CORRUPT_DISK (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x26) /** * This fault simulates shard open failure. Can be used to test EC degraded * update/fetch. */ #define DAOS_FAIL_SHARD_OPEN (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x27) /** * This fault simulates the EC aggregation boundary (agg_eph_boundry) moved * ahead, in that case need to redo the degraded fetch. */ #define DAOS_FAIL_AGG_BOUNDRY_MOVED (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x28) /** * This fault simulates the EC parity epoch difference in EC data recovery. */ #define DAOS_FAIL_PARITY_EPOCH_DIFF (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x29) #define DAOS_FAIL_SHARD_NONEXIST (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x2a) #define DAOS_DTX_COMMIT_SYNC (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x30) #define DAOS_DTX_LEADER_ERROR (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x31) #define DAOS_DTX_NONLEADER_ERROR (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x32) #define DAOS_DTX_LOST_RPC_REQUEST (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x33) #define DAOS_DTX_LOST_RPC_REPLY (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x34) #define DAOS_DTX_LONG_TIME_RESEND (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x35) #define DAOS_DTX_RESTART (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x36) #define DAOS_DTX_NO_READ_TS (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x37) #define DAOS_DTX_SPEC_EPOCH (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x38) #define DAOS_DTX_STALE_PM (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x39) #define DAOS_DTX_FAIL_IO (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x3a) #define DAOS_DTX_START_EPOCH (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x3b) #define DAOS_DTX_NO_BATCHED_CMT (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x3d) #define DAOS_DTX_NO_COMMITTABLE (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x3e) #define DAOS_DTX_MISS_COMMIT (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x3f) #define DAOS_VC_DIFF_REC (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x40) #define DAOS_VC_DIFF_DKEY (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x41) #define DAOS_VC_LOST_DATA (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x42) #define DAOS_VC_LOST_REPLICA (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x43) #define DAOS_DTX_MISS_ABORT (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x44) #define DAOS_DTX_SPEC_LEADER (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x45) #define DAOS_DTX_SRV_RESTART (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x46) #define DAOS_DTX_NO_RETRY (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x47) #define DAOS_DTX_RESEND_DELAY1 (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x48) #define DAOS_DTX_UNCERTAIN (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x49) #define DAOS_DTX_RESYNC_DELAY (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x4a) #define DAOS_DTX_FAIL_COMMIT (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x4b) #define DAOS_NVME_FAULTY (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x50) #define DAOS_NVME_WRITE_ERR (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x51) #define DAOS_NVME_READ_ERR (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x52) #define DAOS_NVME_ALLOCBUF_ERR (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x53) #define DAOS_NVME_WAL_TX_LOST (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x54) #define DAOS_POOL_CREATE_FAIL_CORPC (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x60) #define DAOS_POOL_DESTROY_FAIL_CORPC (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x61) #define DAOS_POOL_CONNECT_FAIL_CORPC (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x62) #define DAOS_POOL_DISCONNECT_FAIL_CORPC (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x63) #define DAOS_POOL_QUERY_FAIL_CORPC (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x64) #define DAOS_CONT_DESTROY_FAIL_CORPC (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x65) #define DAOS_CONT_CLOSE_FAIL_CORPC (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x66) #define DAOS_CONT_QUERY_FAIL_CORPC (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x67) #define DAOS_CONT_OPEN_FAIL (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x68) #define DAOS_POOL_FAIL_MAP_REFRESH (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x69) #define DAOS_CONT_G2L_FAIL (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x6a) /** interoperability failure inject */ #define FLC_SMD_DF_VER (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x70) #define FLC_POOL_DF_VER (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x71) #define DAOS_FAIL_LOST_REQ (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x72) #define DAOS_POOL_UPGRADE_CONT_ABORT (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x73) #define DAOS_POOL_FAIL_MAP_REFRESH_SERIOUSLY \ (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x73) #define DAOS_SHARD_OBJ_RW_DROP_REPLY (DAOS_FAIL_SYS_TEST_GROUP_LOC | 0x80) #define DAOS_OBJ_FETCH_DATA_LOST (DAOS_FAIL_SYS_TEST_GROUP_LOC | 0x81) #define DAOS_OBJ_TRY_SPECIAL_SHARD (DAOS_FAIL_SYS_TEST_GROUP_LOC | 0x82) #define DAOS_VOS_AGG_RANDOM_YIELD (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x90) #define DAOS_VOS_AGG_MW_THRESH (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x91) #define DAOS_VOS_NON_LEADER (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x92) #define DAOS_VOS_AGG_BLOCKED (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x93) #define DAOS_VOS_GC_CONT (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x94) #define DAOS_VOS_GC_CONT_NULL (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x95) #define DAOS_OBJ_SKIP_PARITY (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x96) #define DAOS_OBJ_FORCE_DEGRADE (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x97) #define DAOS_FORCE_EC_AGG (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x98) #define DAOS_FORCE_EC_AGG_FAIL (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x99) #define DAOS_FORCE_EC_AGG_PEER_FAIL (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x9a) #define DAOS_FAIL_TX_CONVERT (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x9b) #define DAOS_REBUILD_OBJ_FAIL (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x9c) #define DAOS_FAIL_POOL_CREATE_VERSION (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x9d) #define DAOS_FORCE_OBJ_UPGRADE (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x9e) #define DAOS_OBJ_FAIL_NVME_IO (DAOS_FAIL_UNIT_TEST_GROUP_LOC | 0x9f) #define DAOS_DTX_SKIP_PREPARE DAOS_DTX_SPEC_LEADER #define DAOS_FAIL_CHECK(id) daos_fail_check(id) static inline int __is_po2(unsigned long long val) { return !(val & (val - 1)); } #define IS_PO2(val) __is_po2((unsigned long long)(val)) bool daos_file_is_dax(const char *pathname); /* daos handle hash table */ struct daos_hhash_table { struct d_hhash *dht_hhash; }; extern struct daos_hhash_table daos_ht; /* daos handle hash table helpers */ int daos_hhash_init_feats(uint32_t feats); static inline int daos_hhash_init(void) { return daos_hhash_init_feats(D_HASH_FT_GLOCK | D_HASH_FT_LRU); } int daos_hhash_fini(void); struct d_hlink *daos_hhash_link_lookup(uint64_t key); void daos_hhash_link_insert(struct d_hlink *hlink, int type); void daos_hhash_link_getref(struct d_hlink *hlink); void daos_hhash_link_putref(struct d_hlink *hlink); bool daos_hhash_link_delete(struct d_hlink *hlink); #define daos_hhash_hlink_init(hlink, ops) d_hhash_hlink_init(hlink, ops) #define daos_hhash_link_empty(hlink) d_hhash_link_empty(hlink) #define daos_hhash_link_key(hlink, key) d_hhash_link_key(hlink, key) /* daos_recx_t overlap detector */ #define DAOS_RECX_OVERLAP(recx_1, recx_2) \ (((recx_1).rx_idx < (recx_2).rx_idx + (recx_2).rx_nr) && \ ((recx_2).rx_idx < (recx_1).rx_idx + (recx_1).rx_nr)) #define DAOS_RECX_PTR_OVERLAP(recx_1, recx_2) \ (((recx_1)->rx_idx < (recx_2)->rx_idx + (recx_2)->rx_nr) && \ ((recx_2)->rx_idx < (recx_1)->rx_idx + (recx_1)->rx_nr)) #define DAOS_RECX_ADJACENT(recx_1, recx_2) \ (((recx_1).rx_idx == (recx_2).rx_idx + (recx_2).rx_nr) || \ ((recx_2).rx_idx == (recx_1).rx_idx + (recx_1).rx_nr)) #define DAOS_RECX_PTR_ADJACENT(recx_1, recx_2) \ (((recx_1)->rx_idx == (recx_2)->rx_idx + (recx_2)->rx_nr) || \ ((recx_2)->rx_idx == (recx_1)->rx_idx + (recx_1)->rx_nr)) #define DAOS_RECX_END(recx) ((recx).rx_idx + (recx).rx_nr) #define DAOS_RECX_PTR_END(recx) ((recx)->rx_idx + (recx)->rx_nr) /** check if recx_1 is covered by recx_2 */ #define DAOS_RECX_COVERED(recx_1, recx_2) \ (((recx_1).rx_idx >= (recx_2).rx_idx) && \ (DAOS_RECX_END(recx_1) <= DAOS_RECX_END(recx_2))) /** * Merge \a src recx to \a dst recx. */ static inline void daos_recx_merge_with_offset_size(daos_recx_t *dst, uint64_t offset, uint64_t size) { uint64_t end; end = max(offset + size, DAOS_RECX_PTR_END(dst)); dst->rx_idx = min(offset, dst->rx_idx); dst->rx_nr = end - dst->rx_idx; } static inline void daos_recx_merge(daos_recx_t *src, daos_recx_t *dst) { daos_recx_merge_with_offset_size(dst, src->rx_idx, src->rx_nr); } static inline bool daos_recx_can_merge_with_offset_size(daos_recx_t *recx, uint64_t offset, uint64_t size) { return max(recx->rx_idx, offset) <= min(DAOS_RECX_END(*recx), offset + size); } static inline bool daos_recx_can_merge(daos_recx_t *src, daos_recx_t *dst) { return daos_recx_can_merge_with_offset_size(dst, src->rx_idx, src->rx_nr); } /* NVMe shared constants */ #define DAOS_NVME_NUMANODE_NONE -1 #define DAOS_NVME_MEM_PRIMARY 0 /** Size of (un)expected Mercury buffers */ #define DAOS_RPC_SIZE (20480) /* 20KiB */ /** * Threshold for inline vs bulk transfer * If the data size is smaller or equal to this limit, it will be transferred * inline in the request/reply. Otherwise, a RDMA transfer will be used. * Based on RPC size above and reserve 1KiB for RPC fields and cart/HG headers. */ #define DAOS_BULK_LIMIT (DAOS_RPC_SIZE - 1024) /* Reserve 1KiB for headers */ crt_init_options_t *daos_crt_init_opt_get(bool server, int crt_nr); int crt_proc_struct_dtx_id(crt_proc_t proc, crt_proc_op_t proc_op, struct dtx_id *dti); int crt_proc_daos_prop_t(crt_proc_t proc, crt_proc_op_t proc_op, daos_prop_t **data); int crt_proc_struct_daos_acl(crt_proc_t proc, crt_proc_op_t proc_op, struct daos_acl **data); bool daos_prop_valid(daos_prop_t *prop, bool pool, bool input); daos_prop_t *daos_prop_dup(daos_prop_t *prop, bool pool, bool input); int daos_prop_copy(daos_prop_t *prop_req, daos_prop_t *prop_reply); void daos_prop_fini(daos_prop_t *prop); int daos_prop_entry_copy(struct daos_prop_entry *entry, struct daos_prop_entry *entry_dup); daos_recx_t *daos_recx_alloc(uint32_t nr); void daos_recx_free(daos_recx_t *recx); static inline void daos_parse_ctype(const char *string, daos_cont_layout_t *type) { if (strcasecmp(string, "HDF5") == 0) *type = DAOS_PROP_CO_LAYOUT_HDF5; else if (strcasecmp(string, "POSIX") == 0) *type = DAOS_PROP_CO_LAYOUT_POSIX; else if (strcasecmp(string, "PYTHON") == 0) *type = DAOS_PROP_CO_LAYOUT_PYTHON; else if (strcasecmp(string, "SPARK") == 0) *type = DAOS_PROP_CO_LAYOUT_SPARK; else if (strcasecmp(string, "DATABASE") == 0 || strcasecmp(string, "DB") == 0) *type = DAOS_PROP_CO_LAYOUT_DATABASE; else if (strcasecmp(string, "ROOT") == 0 || strcasecmp(string, "RNTuple") == 0) *type = DAOS_PROP_CO_LAYOUT_ROOT; else if (strcasecmp(string, "SEISMIC") == 0 || strcasecmp(string, "DSG") == 0) *type = DAOS_PROP_CO_LAYOUT_SEISMIC; else if (strcasecmp(string, "METEO") == 0 || strcasecmp(string, "FDB") == 0) *type = DAOS_PROP_CO_LAYOUT_METEO; else *type = DAOS_PROP_CO_LAYOUT_UNKNOWN; } static inline void daos_unparse_ctype(daos_cont_layout_t ctype, char *string) { switch (ctype) { case DAOS_PROP_CO_LAYOUT_POSIX: strcpy(string, "POSIX"); break; case DAOS_PROP_CO_LAYOUT_HDF5: strcpy(string, "HDF5"); break; case DAOS_PROP_CO_LAYOUT_PYTHON: strcpy(string, "PYTHON"); break; case DAOS_PROP_CO_LAYOUT_SPARK: strcpy(string, "SPARK"); break; case DAOS_PROP_CO_LAYOUT_DATABASE: strcpy(string, "DATABASE"); break; case DAOS_PROP_CO_LAYOUT_ROOT: strcpy(string, "ROOT"); break; case DAOS_PROP_CO_LAYOUT_SEISMIC: strcpy(string, "SEISMIC"); break; case DAOS_PROP_CO_LAYOUT_METEO: strcpy(string, "METEO"); break; default: strcpy(string, "unknown"); break; } } static inline void daos_anchor_set_flags(daos_anchor_t *anchor, uint32_t flags) { anchor->da_flags = flags; } static inline uint32_t daos_anchor_get_flags(daos_anchor_t *anchor) { return anchor->da_flags; } static inline void daos_anchor_set_eof(daos_anchor_t *anchor) { anchor->da_type = DAOS_ANCHOR_TYPE_EOF; } static inline void daos_anchor_set_zero(daos_anchor_t *anchor) { anchor->da_type = DAOS_ANCHOR_TYPE_ZERO; } static inline bool daos_anchor_is_zero(daos_anchor_t *anchor) { return anchor->da_type == DAOS_ANCHOR_TYPE_ZERO; } /* default debug log file */ #define DAOS_LOG_DEFAULT "/tmp/daos.log" #ifdef NEED_EXPLICIT_BZERO /* Secure memory scrub */ static inline void explicit_bzero(void *s, size_t count) { memset(s, 0, count); asm volatile("" : : "r"(s) : "memory"); } #endif /* NEED_EXPLICIT_BZERO */ #endif /* __DAOS_COMMON_H__ */
2.203125
2
2024-11-18T21:52:02.313844+00:00
2014-12-08T07:20:39
e617b777dbd68ad2c55cb92e53b69cd355221d27
{ "blob_id": "e617b777dbd68ad2c55cb92e53b69cd355221d27", "branch_name": "refs/heads/master", "committer_date": "2014-12-08T07:20:39", "content_id": "ada4b33cc90bd3635a36014cbcc42b420aacb2cf", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "d3220d05b7e7ad34846e1227b3fdb21dd932f756", "extension": "c", "filename": "srv_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": 3525, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/srv_info.c", "provenance": "stackv2-0138.json.gz:149223", "repo_name": "supertanglang/WDUtils", "revision_date": "2014-12-08T07:20:39", "revision_id": "69057e92a5759487ef6bd62a85db24644759b42c", "snapshot_id": "94c459998f73ef9bcc94e9720750dcf3f0a33b51", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/supertanglang/WDUtils/69057e92a5759487ef6bd62a85db24644759b42c/srv_info.c", "visit_date": "2020-06-16T15:48:47.936031" }
stackv2
#include <windows.h> #include <stdio.h> #include <ctype.h> char ____DEVICE_BASENAME[128]; // // Get system error message string // PCSTR SystemMessage( DWORD nError) { static CHAR msg[256]; if (!FormatMessage( FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, nError, 0, msg, sizeof(msg), NULL)) { _snprintf(msg, sizeof(msg), "Unknown system error %lu (0x%08x)\n", nError, nError); } return msg; } DWORD WINAPI GetDriverConfig( PSTR sFileName, // driver file name PDWORD pStart) // driver state { SC_HANDLE hScManager; // Service Control Manager SC_HANDLE hService; // Service (= Driver) LPQUERY_SERVICE_CONFIG config = NULL; DWORD result; DWORD ret = ERROR_SUCCESS; if (sFileName) ZeroMemory(sFileName, MAX_PATH); if (pStart) *pStart = 0; // Connect to the Service Control Manager hScManager = OpenSCManager(NULL, NULL, 0); if (hScManager == NULL) { ret = GetLastError(); fprintf(stderr, "fail to connect scm: %s\n", SystemMessage(ret)); return ret; } // Open the driver entry in the service database hService = OpenService( hScManager, // Service control manager ____DEVICE_BASENAME, // service name SERVICE_QUERY_CONFIG); // service access mode if (hService == NULL) { ret = GetLastError(); fprintf(stderr, "fail to open service: %s\n", SystemMessage(ret)); goto cleanup; } // Get the length of config information if (!QueryServiceConfig(hService, NULL, 0, &result)) { ret = GetLastError(); if (ret == ERROR_INSUFFICIENT_BUFFER) ret = ERROR_SUCCESS; else { fprintf(stderr, "fail to get config info: %s\n", SystemMessage(ret)); goto cleanup; } } // allocate a required buffer config = (LPQUERY_SERVICE_CONFIG)LocalAlloc(LPTR, result); if (config == NULL) { ret = GetLastError(); fprintf(stderr, "fail to alloc: %s\n", SystemMessage(ret)); goto cleanup; } // get the config information if (!QueryServiceConfig(hService, config, result, &result)) { ret = GetLastError(); fprintf(stderr, "fail to query config: %s\n", SystemMessage(ret)); goto cleanup; } // copy information to output buffer if (sFileName) { if (strncmp(config->lpBinaryPathName, "\\??\\", 4) == 0) { // driver path is an absolute UNC path strncpy( sFileName, config->lpBinaryPathName + 4, MAX_PATH); } else if (config->lpBinaryPathName[0] == '\\' || (isalpha(config->lpBinaryPathName[0]) && config->lpBinaryPathName[1] == ':')) { // driver path is an absolute path strncpy(sFileName, config->lpBinaryPathName, MAX_PATH); } else { // driver path is relative to the SystemRoot DWORD len = GetWindowsDirectory(sFileName, MAX_PATH); if (len == 0 || len > MAX_PATH) { fprintf(stderr, ": %%SystemRoot%% is empty or too long.\n"); ret = ERROR_BAD_ENVIRONMENT; goto cleanup; } sprintf((sFileName + len), "\\%s", config->lpBinaryPathName); } } if (pStart) *pStart = config->dwStartType; cleanup: // Free service config buffer if (config) { LocalFree(config); } // Close the service object handle if (hService) { CloseServiceHandle(hService); } // Close handle to the service control manager. if (hScManager) { CloseServiceHandle(hScManager); } return ret; } int main(int argc, const char* argv[]) { CHAR sFileName[MAX_PATH]; DWORD Start; if(argc < 2) return 1; strcpy(____DEVICE_BASENAME, argv[1]); GetDriverConfig(sFileName, &Start); printf("%s\n", sFileName); return 0; }
2.453125
2
2024-11-18T21:52:02.552735+00:00
2018-05-14T01:33:49
ed48695567e9d8235bd97dfa37d6fd490202f749
{ "blob_id": "ed48695567e9d8235bd97dfa37d6fd490202f749", "branch_name": "refs/heads/master", "committer_date": "2018-05-14T01:33:49", "content_id": "7fcf893fd07c6740d4e46dc8f06dadac00f5a5e0", "detected_licenses": [ "Apache-2.0" ], "directory_id": "a4727cd05d69c04b4ffa9898c9d92590ff6f1300", "extension": "c", "filename": "example.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 133289159, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2110, "license": "Apache-2.0", "license_type": "permissive", "path": "/example.c", "provenance": "stackv2-0138.json.gz:149481", "repo_name": "Mogran/CameraHal", "revision_date": "2018-05-14T01:33:49", "revision_id": "7dfd99276397471e62882abc8e8dbfc7c34e0902", "snapshot_id": "45e605c979036db3b302e21152eea1d2d6b609be", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/Mogran/CameraHal/7dfd99276397471e62882abc8e8dbfc7c34e0902/example.c", "visit_date": "2020-03-17T04:47:39.586982" }
stackv2
#include "camerahal.h" camerahal_device_t camera; static const char device[] = { "/dev/video0" }; int main(int argc, char *argv[]) { camerahal_error_t err; printf("CameraHal Example \n"); if (argc < 0) { printf("[Usage] : ./example [Options]\n " " [Options] may be /dev/videoX\n" " X may 0,1,2,3,...\n"); return -1; } //device open err = camerahal_open(device, &camera); if (err != CAMHAL_SUCCESS) printf("open video failed\n"); else printf("open camera video success \n"); //get device cap err = camerahal_get_capability(&camera); if (err != CAMHAL_SUCCESS) { printf("camera, get cap failed\n"); } //get video fmtdesc err = camerahal_get_fmtdesc(&camera); if (err != CAMHAL_SUCCESS) { printf("camera, get cap failed\n"); } //get current frame format info err = camerahal_get_frame_format(&camera); if (err != CAMHAL_SUCCESS) { printf("camera, get current frame format failed\n"); } //set frame 640x480 err = camerahal_set_frame_format(&camera, 640, 480, V4L2_PIX_FMT_MJPEG); if (err != CAMHAL_SUCCESS) { printf("camera, get current frame format failed\n"); } //get current frame format info err = camerahal_get_frame_format(&camera); if (err != CAMHAL_SUCCESS) { printf("camera, get current frame format failed\n"); } //requeset buffer err = camerahal_requestbuffers(&camera, 4); if (err != CAMHAL_SUCCESS) { printf("camera, requeset buffers failed\n"); } //stream begin to caputre err = camerahal_stream_start(&camera); if (err != CAMHAL_SUCCESS) { printf("camera, stream open failed\n"); } //get picture frame one by one int count = 5; while (count--) { err = camerahal_get_streaming(&camera); if (err != CAMHAL_SUCCESS) { printf("camera, get one picture failed\n"); } sleep(1); } //sensor stop caputre err = camerahal_stream_stop(&camera); if (err != CAMHAL_SUCCESS) { printf("camera, stream open failed\n"); } //close device err = camerahal_close(&camera); if (err != CAMHAL_SUCCESS) printf("close video failed\n"); else printf("close camera video success \n"); return 0; }
2.484375
2
2024-11-18T21:52:04.181034+00:00
2022-11-14T10:07:26
61691e3740c3e37d6fb745aae0f40bcfc798db89
{ "blob_id": "61691e3740c3e37d6fb745aae0f40bcfc798db89", "branch_name": "refs/heads/master", "committer_date": "2022-11-14T10:07:26", "content_id": "50b1680deaacab9f2addd9e2cabb477604a40683", "detected_licenses": [ "MIT" ], "directory_id": "e8b4d2fb71f37cda050a600c0b566a1717a833b2", "extension": "c", "filename": "minikrt0.c", "fork_events_count": 1, "gha_created_at": "2018-05-23T22:23:42", "gha_event_created_at": "2022-11-14T10:07:27", "gha_language": "C++", "gha_license_id": "MIT", "github_id": 134631628, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 433, "license": "MIT", "license_type": "permissive", "path": "/02/MiNiK/src/minikrt0.c", "provenance": "stackv2-0138.json.gz:150386", "repo_name": "tomaszlach86/nokia-book", "revision_date": "2022-11-14T10:07:26", "revision_id": "d5a8515e9676b48cc9490aa03b17ced4edd8fd6c", "snapshot_id": "d3fa1060d47acc9aa5ce78a8192c7fabf227dadd", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/tomaszlach86/nokia-book/d5a8515e9676b48cc9490aa03b17ced4edd8fd6c/02/MiNiK/src/minikrt0.c", "visit_date": "2022-11-27T12:45:32.408167" }
stackv2
// Run-Time environment #include <stdio.h> #include <stdlib.h> #include <string.h> struct args { int data[16]; }; int __MINIK_read() { char line[32]; int val = 0; fgets(line, 19, stdin); line[31] = 0; sscanf(line, "%i", &val); return val; } void __MINIK_write(int x) { printf("%i\n", x); } int __MINIK_main(); int main() { int ret = __MINIK_main(); printf("%d\n", ret); return ret; }
2.328125
2
2024-11-18T21:52:05.206595+00:00
2016-06-02T23:25:36
09903862078e00d6847fd628c86f1f5398f28518
{ "blob_id": "09903862078e00d6847fd628c86f1f5398f28518", "branch_name": "refs/heads/master", "committer_date": "2016-06-02T23:25:36", "content_id": "59513334134ee4543dc2ba0077be5e176a7e4db3", "detected_licenses": [ "Apache-2.0" ], "directory_id": "962daae186afad97e1f848f3306f8393ecbd905a", "extension": "c", "filename": "test_case_straight_list.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 14175397, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1722, "license": "Apache-2.0", "license_type": "permissive", "path": "/test_case_straight_list.c", "provenance": "stackv2-0138.json.gz:151163", "repo_name": "fiuba-7541/elemental", "revision_date": "2016-06-02T23:25:36", "revision_id": "e435f979414f875ce462452ac546855388331f2a", "snapshot_id": "ff088cd2fa8a34543b3aae4c119bc5e3cad567a0", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/fiuba-7541/elemental/e435f979414f875ce462452ac546855388331f2a/test_case_straight_list.c", "visit_date": "2021-01-17T09:10:36.636487" }
stackv2
/* * ListaTestCase.c * * Created on: 02/04/2011 * Author: anibal */ #include "straight_list.h" #include "test_case_straight_list.h" #include "TDATestCase.h" void destruir_int(void* e); int copiar_int(void* destino, const void* origen); void destruir_string(void* e); int copiar_string(void* destino, const void* origen); void test_straight_list_fill_and_scan(){ straight_list_t l; straight_list_create(&l, sizeof(int), copiar_int, destruir_int); int i; for(i=0; i<100; i++){ straight_list_insert(&l, straight_list_next, &i); } assertFalse(straight_list_is_empty(&l)); straight_list_move(&l, straight_list_first); for(i=0; i<100; i++){ int j = 0; straight_list_get(&l, &j); straight_list_move(&l, straight_list_next); assertEqualsInt(i, j); } assertFalse(straight_list_is_empty(&l)); straight_list_clear(&l); assertTrue(straight_list_is_empty(&l)); } void test_straight_list_fill_and_empty(){ straight_list_t l; char** cadenas; char* cadena; int i=0; straight_list_create(&l, sizeof(char*), copiar_string, destruir_string); cadenas = (char**) malloc (5 * sizeof(char*)); for(i=0; i<5; i++){ cadenas[i] = (char*) malloc(16 * sizeof(char)); } strcpy(cadenas[0], "cadena 0"); strcpy(cadenas[1], "cadena 1"); strcpy(cadenas[2], "cadena 2"); strcpy(cadenas[3], "cadena 3"); strcpy(cadenas[4], "cadena 4"); for(i=0; i<5; i++){ straight_list_insert(&l, straight_list_next, cadenas+i); } straight_list_move(&l, straight_list_first); for(i=0; i<5; i++){ straight_list_get(&l, &cadena); assertEqualsString(cadenas[i], cadena); straight_list_delete(&l); } assertTrue(straight_list_is_empty(&l)); for(i=0; i<5; i++){ free(cadenas[i]); } free(cadenas); }
2.953125
3
2024-11-18T21:52:05.351344+00:00
2019-01-13T08:14:26
901a8f00e68a1e152621fe277ad0f0fecec300a9
{ "blob_id": "901a8f00e68a1e152621fe277ad0f0fecec300a9", "branch_name": "refs/heads/master", "committer_date": "2019-01-13T08:14:26", "content_id": "964a2156767163153368f1d3dbaf76ced1df727a", "detected_licenses": [ "Unlicense" ], "directory_id": "41ba7af5cc059c046bbcb5730ab3edf90babedf4", "extension": "c", "filename": "create_files.c", "fork_events_count": 1, "gha_created_at": "2019-01-07T09:46:30", "gha_event_created_at": "2019-01-07T09:46:30", "gha_language": null, "gha_license_id": "Unlicense", "github_id": 164411109, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3198, "license": "Unlicense", "license_type": "permissive", "path": "/src/create_files.c", "provenance": "stackv2-0138.json.gz:151422", "repo_name": "dustywind/osbench", "revision_date": "2019-01-13T08:14:26", "revision_id": "0e208352698206cb3bdd383df9e9eaf45642fd4e", "snapshot_id": "2c1a23f903eda3f5b6b266ea96d9a947d52baaf6", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/dustywind/osbench/0e208352698206cb3bdd383df9e9eaf45642fd4e/src/create_files.c", "visit_date": "2020-04-15T05:09:42.182577" }
stackv2
// This is free and unencumbered software released into the public domain. // For more information, see UNLICENSE. #include "common/time.h" #include <dirent.h> #include <fcntl.h> #include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> // Note: The maximum number of files in a folder for different file systems: // - 65534 (FAT32) // - 4294967295 (NTFS, ext4) #define NUM_FILES 65534 static double my_log2(double x) { static const double LOG2SCALE = 1.442695040888963; // 1.0 / log(2.0); return log(x) * LOG2SCALE; } static int num_hex_chars(int max_int) { int num_bits = (int)ceil(my_log2((double)max_int)); return (num_bits + 3) / 4; } static void to_hex(int x, char* str, const int str_len) { static const char TOHEX[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; str += str_len - 1; for (int i = 0; i < str_len; ++i) { *str-- = TOHEX[x & 15]; x = x >> 4; } } static void create_file(int dirfd, const char* file_name) { static const char FILE_DATA[32] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31 }; int fd = openat(dirfd, file_name, O_WRONLY | O_CREAT); if (fd == -1) { fprintf(stderr, "*** Unable to create file \"%s\"\n", file_name); exit(1); } size_t off = 0; while (off < sizeof(FILE_DATA)) { off += write(fd, (const void *) &FILE_DATA[off], sizeof(FILE_DATA) - off); } if (-1 == fsync(fd)) { fprintf(stderr, "*** Unable to sync file \"%s\"\n", file_name); exit(1); } close(fd); } static void delete_file(int dirfd, const char* file_name) { const int no_flags = 0; unlinkat(dirfd, file_name, no_flags); } static char *file_names[NUM_FILES]; int main(int argc, const char** argv) { //if (argc != 2) { // printf("Usage: %s root-folder\n", argv[0]); // exit(1); //} char *rootpath = "/root/tmp"; printf("Benchmark: Create/delete %d files...\n", NUM_FILES); fflush(stdout); int rootfd; DIR *dirp = opendir(rootpath); if (!dirp) { fprintf(stderr, "*** Unable to opend irectory \"%s\"\n", rootpath); exit(-1); } if ((rootfd = dirfd(dirp)) == -1) { perror("open rootpath"); } int hex_len = num_hex_chars(NUM_FILES -1); // Create a path string. for (size_t i = 0; i < NUM_FILES; i++) { size_t filename_len = num_hex_chars(NUM_FILES - 1); char* file_name = (char*)calloc(filename_len, 2); if (!file_name) { fprintf(stderr, "*** Out of memory!\n"); exit(1); } to_hex(i, file_name, hex_len); file_names[i] = file_name; } const double t0 = get_time(); for (int i = 0; i < NUM_FILES; ++i) { // Create the file. create_file(rootfd, file_names[i]); } for (int i = 0; i < NUM_FILES; ++i) { // Delete the file. delete_file(rootfd, file_names[i]); } double dt = get_time() - t0; printf("%f us / file\n", (dt * 1000000 / NUM_FILES)); fflush(stdout); for(size_t i = 0; i < NUM_FILES; i++) { free(file_names[i]); } if(closedir(dirp) == -1) { perror("closedir"); exit(-1); } return 0; }
2.78125
3
2024-11-18T21:52:06.159663+00:00
2023-01-05T16:43:25
272670df01e3a773f61eb404e11b3fb363c06121
{ "blob_id": "272670df01e3a773f61eb404e11b3fb363c06121", "branch_name": "refs/heads/master", "committer_date": "2023-01-05T17:02:26", "content_id": "725ab0d940bea3047797b7b003ba50eb8a1dcafa", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "e7df8a455a730a9750e9bac5dd2840434f1ba8bc", "extension": "c", "filename": "tcg2-get-eventlog.c", "fork_events_count": 13, "gha_created_at": "2018-08-22T02:56:39", "gha_event_created_at": "2023-01-05T17:02:27", "gha_language": "C", "gha_license_id": "BSD-2-Clause", "github_id": 145647849, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3836, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/example/tcg2-get-eventlog.c", "provenance": "stackv2-0138.json.gz:151811", "repo_name": "tpm2-software/tpm2-tcti-uefi", "revision_date": "2023-01-05T16:43:25", "revision_id": "f41e1e04b7937dbcb7517bbf5dd1361301a1d1ae", "snapshot_id": "01d67efb89f91f891e8afc49af6464e742d23fc9", "src_encoding": "UTF-8", "star_events_count": 22, "url": "https://raw.githubusercontent.com/tpm2-software/tpm2-tcti-uefi/f41e1e04b7937dbcb7517bbf5dd1361301a1d1ae/example/tcg2-get-eventlog.c", "visit_date": "2023-06-19T18:27:30.931762" }
stackv2
/* SPDX-License-Identifier: BSD-2 */ #ifndef EDK2_BUILD #include <efi/efi.h> #include <efi/efilib.h> #else #include <Uefi.h> #include <Library/UefiLib.h> #include <Library/ShellCommandLib.h> #endif #include <inttypes.h> #include <stdlib.h> #include <tss2/tss2_tpm2_types.h> #include "tcg2-protocol.h" #include "tcg2-util.h" #include "util.h" static void prettyprint_tpm12_event (TCG_PCR_EVENT *event) { Print (L"TCG_PCR_EVENT: 0x%" PRIxPTR "\n", (uintptr_t)event); Print (L" PCRIndex: %d\n", event->PCRIndex); Print (L" EventType: %s (0x%08" PRIx32 ")\n", eventtype_to_string (event->EventType), event->EventType); Print (L" Digest: \n"); DumpHex (4, 0, sizeof (event->Digest), &event->Digest); Print (L" EventSize: %d\n", event->EventSize); Print (L" Event: \n"); DumpHex (4, 0, event->EventSize, event->Event); } static TCG_PCR_EVENT* tpm12_event_next (TCG_PCR_EVENT *current, TCG_PCR_EVENT *last) { TCG_PCR_EVENT *next; if (current == last) return NULL; next = (TCG_PCR_EVENT*)((char*)(current + 1) + current->EventSize - 1); if (next > last) { Print (L"Error: current element is beyond the end of the log\n"); return NULL; } return next; } static void prettyprint_tpm12_eventlog (EFI_PHYSICAL_ADDRESS first, EFI_PHYSICAL_ADDRESS last) { TCG_PCR_EVENT *event_last, *event; event = (TCG_PCR_EVENT*) first; event_last = (TCG_PCR_EVENT*) last; if (event == NULL) { Print (L"TPM2 EventLog is empty."); return; } Print (L"TPM2 EventLog, EFI_TCG2_EVENT_LOG_FORMAT_TCG_1_2 format\n"); do { prettyprint_tpm12_event (event); } while ((event = tpm12_event_next (event, event_last)) != NULL); } static void prettyprint_tpm2_eventlog (EFI_PHYSICAL_ADDRESS first, EFI_PHYSICAL_ADDRESS last) { TCG_EVENT_HEADER2 *event = (TCG_EVENT_HEADER2*)first; TCG_EVENT_HEADER2 *event_last = (TCG_EVENT_HEADER2*)last; if (event == NULL) { Print (L"TPM2 EventLog is empty.\n"); return; } Print (L"TPM2 EventLog, EFI_TCG2_EVENT_LOG_FORMAT_TCG_2 format\n"); foreach_event2 (event, event_last, prettyprint_tpm2_event_callback, NULL); Print (L"TPM2 EventLog end\n"); } static void prettyprint_eventlog (EFI_PHYSICAL_ADDRESS first, EFI_PHYSICAL_ADDRESS last, EFI_TCG2_EVENT_LOG_FORMAT format) { switch (format) { case EFI_TCG2_EVENT_LOG_FORMAT_TCG_2: prettyprint_tpm2_eventlog (first, last); break; case EFI_TCG2_EVENT_LOG_FORMAT_TCG_1_2: prettyprint_tpm12_eventlog (first, last); break; default: Print (L"ERROR: Unknown format: 0x%" PRIx32 "\n", format); break; } } EFI_STATUS EFIAPI efi_main ( EFI_HANDLE ImageHandle, EFI_SYSTEM_TABLE *SystemTable ) { EFI_TCG2_PROTOCOL *tcg2_protocol; EFI_STATUS status; EFI_PHYSICAL_ADDRESS first, last; EFI_TCG2_EVENT_LOG_FORMAT format = 0; BOOLEAN trunc; #ifndef EDK2_BUILD InitializeLib (ImageHandle, SystemTable); #endif status = tcg2_get_protocol (&tcg2_protocol); if (EFI_ERROR (status)) return status; status = get_eventlog_format_high (tcg2_protocol, &format); if (EFI_ERROR (status)) return status; else if (format == 0) { Print (L"ERROR: TCG2 UEFI protocol doesn't support a log format " "known to this tool.\n"); return 1; } status = tcg2_get_eventlog (tcg2_protocol, format, &first, &last, &trunc); if (EFI_ERROR (status)) return status; if (trunc) Print (L"WARNING: Eventlog has been truncated\n"); prettyprint_eventlog (first, last, format); return status; }
2.375
2
2024-11-18T21:52:10.881405+00:00
2023-07-19T12:46:37
1237cc724fd494bac296bf11608ec7a61636a0c9
{ "blob_id": "1237cc724fd494bac296bf11608ec7a61636a0c9", "branch_name": "refs/heads/master", "committer_date": "2023-07-19T12:46:37", "content_id": "c25299661dae3cd4c0e2eccb3fd28685c0d7bc28", "detected_licenses": [ "Apache-2.0" ], "directory_id": "03f6ad21c4332b9b26dfb11ed04e63bdb9236b3c", "extension": "h", "filename": "sub_simd_x86.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 40577669, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 6159, "license": "Apache-2.0", "license_type": "permissive", "path": "/src/sub_simd_x86.h", "provenance": "stackv2-0138.json.gz:152333", "repo_name": "m1griffin/arrayfunc", "revision_date": "2023-07-19T12:46:37", "revision_id": "c04561c5d565ae8d3ee776783bfb34b242deca93", "snapshot_id": "ddf9ea9c8fa363f79babd788c8d0428ede8dfc60", "src_encoding": "UTF-8", "star_events_count": 3, "url": "https://raw.githubusercontent.com/m1griffin/arrayfunc/c04561c5d565ae8d3ee776783bfb34b242deca93/src/sub_simd_x86.h", "visit_date": "2023-08-05T00:09:27.530893" }
stackv2
//------------------------------------------------------------------------------ // Project: arrayfunc // Module: sub_simd_x86.h // Purpose: Calculate the sub of values in an array. // This file provides an SIMD version of the functions. // Language: C // Date: 1-Apr-2019 // Ver: 31-Oct-2021. // //------------------------------------------------------------------------------ // // Copyright 2014 - 2021 Michael Griffin <[email protected]> // // 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. // //------------------------------------------------------------------------------ void sub_signed_char_1_simd(Py_ssize_t arraylen, signed char *data1, signed char param); void sub_signed_char_2_simd(Py_ssize_t arraylen, signed char *data1, signed char param, signed char *data3); void sub_signed_char_3_simd(Py_ssize_t arraylen, signed char param, signed char *data2); void sub_signed_char_4_simd(Py_ssize_t arraylen, signed char param, signed char *data2, signed char *data3); void sub_signed_char_5_simd(Py_ssize_t arraylen, signed char *data1, signed char *data2); void sub_signed_char_6_simd(Py_ssize_t arraylen, signed char *data1, signed char *data2, signed char *data3); char sub_signed_char_1_simd_ovfl(Py_ssize_t arraylen, signed char *data1, signed char param); char sub_signed_char_2_simd_ovfl(Py_ssize_t arraylen, signed char *data1, signed char param, signed char *data3); char sub_signed_char_3_simd_ovfl(Py_ssize_t arraylen, signed char param, signed char *data2); char sub_signed_char_4_simd_ovfl(Py_ssize_t arraylen, signed char param, signed char *data2, signed char *data3); void sub_signed_short_1_simd(Py_ssize_t arraylen, signed short *data1, signed short param); void sub_signed_short_2_simd(Py_ssize_t arraylen, signed short *data1, signed short param, signed short *data3); void sub_signed_short_3_simd(Py_ssize_t arraylen, signed short param, signed short *data2); void sub_signed_short_4_simd(Py_ssize_t arraylen, signed short param, signed short *data2, signed short *data3); void sub_signed_short_5_simd(Py_ssize_t arraylen, signed short *data1, signed short *data2); void sub_signed_short_6_simd(Py_ssize_t arraylen, signed short *data1, signed short *data2, signed short *data3); char sub_signed_short_1_simd_ovfl(Py_ssize_t arraylen, signed short *data1, signed short param); char sub_signed_short_2_simd_ovfl(Py_ssize_t arraylen, signed short *data1, signed short param, signed short *data3); char sub_signed_short_3_simd_ovfl(Py_ssize_t arraylen, signed short param, signed short *data2); char sub_signed_short_4_simd_ovfl(Py_ssize_t arraylen, signed short param, signed short *data2, signed short *data3); void sub_signed_int_1_simd(Py_ssize_t arraylen, signed int *data1, signed int param); void sub_signed_int_2_simd(Py_ssize_t arraylen, signed int *data1, signed int param, signed int *data3); void sub_signed_int_3_simd(Py_ssize_t arraylen, signed int param, signed int *data2); void sub_signed_int_4_simd(Py_ssize_t arraylen, signed int param, signed int *data2, signed int *data3); void sub_signed_int_5_simd(Py_ssize_t arraylen, signed int *data1, signed int *data2); void sub_signed_int_6_simd(Py_ssize_t arraylen, signed int *data1, signed int *data2, signed int *data3); char sub_signed_int_1_simd_ovfl(Py_ssize_t arraylen, signed int *data1, signed int param); char sub_signed_int_2_simd_ovfl(Py_ssize_t arraylen, signed int *data1, signed int param, signed int *data3); char sub_signed_int_3_simd_ovfl(Py_ssize_t arraylen, signed int param, signed int *data2); char sub_signed_int_4_simd_ovfl(Py_ssize_t arraylen, signed int param, signed int *data2, signed int *data3); void sub_float_1_simd(Py_ssize_t arraylen, float *data1, float param); void sub_float_2_simd(Py_ssize_t arraylen, float *data1, float param, float *data3); void sub_float_3_simd(Py_ssize_t arraylen, float param, float *data2); void sub_float_4_simd(Py_ssize_t arraylen, float param, float *data2, float *data3); void sub_float_5_simd(Py_ssize_t arraylen, float *data1, float *data2); void sub_float_6_simd(Py_ssize_t arraylen, float *data1, float *data2, float *data3); char sub_float_1_simd_ovfl(Py_ssize_t arraylen, float *data1, float param); char sub_float_2_simd_ovfl(Py_ssize_t arraylen, float *data1, float param, float *data3); char sub_float_3_simd_ovfl(Py_ssize_t arraylen, float param, float *data2); char sub_float_4_simd_ovfl(Py_ssize_t arraylen, float param, float *data2, float *data3); char sub_float_5_simd_ovfl(Py_ssize_t arraylen, float *data1, float *data2); char sub_float_6_simd_ovfl(Py_ssize_t arraylen, float *data1, float *data2, float *data3); void sub_double_1_simd(Py_ssize_t arraylen, double *data1, double param); void sub_double_2_simd(Py_ssize_t arraylen, double *data1, double param, double *data3); void sub_double_3_simd(Py_ssize_t arraylen, double param, double *data2); void sub_double_4_simd(Py_ssize_t arraylen, double param, double *data2, double *data3); void sub_double_5_simd(Py_ssize_t arraylen, double *data1, double *data2); void sub_double_6_simd(Py_ssize_t arraylen, double *data1, double *data2, double *data3); char sub_double_1_simd_ovfl(Py_ssize_t arraylen, double *data1, double param); char sub_double_2_simd_ovfl(Py_ssize_t arraylen, double *data1, double param, double *data3); char sub_double_3_simd_ovfl(Py_ssize_t arraylen, double param, double *data2); char sub_double_4_simd_ovfl(Py_ssize_t arraylen, double param, double *data2, double *data3); char sub_double_5_simd_ovfl(Py_ssize_t arraylen, double *data1, double *data2); char sub_double_6_simd_ovfl(Py_ssize_t arraylen, double *data1, double *data2, double *data3);
2.03125
2
2024-11-18T21:52:10.952580+00:00
2019-10-04T22:55:10
3e6cda19e1ec08a23711046f6a6afb5d350af26d
{ "blob_id": "3e6cda19e1ec08a23711046f6a6afb5d350af26d", "branch_name": "refs/heads/master", "committer_date": "2019-10-04T22:55:10", "content_id": "9d9e381f459c163003ed276b7f39bbf5e9f34cad", "detected_licenses": [ "Apache-2.0" ], "directory_id": "5142f82be506c47a04e572091300979ad85d0220", "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": 212914462, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3085, "license": "Apache-2.0", "license_type": "permissive", "path": "/main.c", "provenance": "stackv2-0138.json.gz:152463", "repo_name": "moh008/moh008_lab1_part2", "revision_date": "2019-10-04T22:55:10", "revision_id": "01a372bc27c8ffca54a918be232853d56e765aee", "snapshot_id": "7ed7a1c8e6eabb201a9651c2aedca51cfd8ede10", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/moh008/moh008_lab1_part2/01a372bc27c8ffca54a918be232853d56e765aee/main.c", "visit_date": "2020-08-06T08:53:47.397966" }
stackv2
/* Lab Section: 021 * Assignment: Lab 1 Exercise 2 * * Created: 2019-10-04 오후 3:37:30 * Author : Minwhan Oh * * I acknowledge all content contained herein, excluding template * or example code, is my own original work. */ #include <avr/io.h> #include <avr/interrupt.h> #include "Timer.h" #include "io.c" enum States {Init, next_led, prev_led, stay_pr, released} state; unsigned char tmpB = 0x00; unsigned char button = 0x00; unsigned char cnt = 0x00; unsigned char score = 0x05; void Tick() { switch(state) {//state transition case Init: if(button) { state = Init; } else { state = next_led; cnt = 0x00; tmpB = 0x01; if(score == 0x09) { LCD_ClearScreen(); score = 0x05; LCD_Cursor(1); LCD_WriteData(score + '0'); } else { LCD_Cursor(1); LCD_WriteData(score + '0'); } } break; case next_led: if((tmpB == 0x04) && (cnt == 0x0A)) { state = prev_led; tmpB = tmpB >> 1; cnt = 0; } else if(button) { state = stay_pr; if((tmpB == 0x02) && (score < 0x09)) { score++; LCD_Cursor(1); LCD_WriteData(score + '0'); } else if((tmpB != 0x02) && (score > 0x00)) { score--; LCD_Cursor(1); LCD_WriteData(score + '0'); } else { LCD_Cursor(1); LCD_WriteData(score + '0'); break; } } else { state = next_led; } break; case prev_led: if((tmpB == 0x01) && (cnt == 0x0A)) { state = next_led; tmpB = tmpB << 1; cnt = 0; } else if(button) { state = stay_pr; if((tmpB == 0x02) && (score < 0x09)) { score++; LCD_Cursor(1); LCD_WriteData(score + '0'); } else if((tmpB != 0x02) && (score > 0x00)) { score--; LCD_Cursor(1); LCD_WriteData(score + '0'); } else { LCD_Cursor(1); LCD_WriteData(score + '0'); break; } } else { state = prev_led; } break; case stay_pr: if(!button) { state = released; } else { state = stay_pr; } break; case released: if(button) { state = Init; } else { state = released; } break; default: break; } switch(state) {//state action case Init: break; case next_led: if(cnt == 0x0A) { tmpB = tmpB << 1; cnt = 0; } else { cnt++; } break; case prev_led: if(cnt == 0x0A) { tmpB = tmpB >> 1; cnt = 0; } else { cnt++; } break; case stay_pr: if(score == 0x09) { LCD_DisplayString(1, "Victory"); } break; case released: break; default: break; } } void main() { DDRA = 0x00; PORTA = 0xFF; DDRB = 0xFF; PORTB = 0x00; DDRC = 0xFF; PORTC = 0x00; DDRD = 0xFF; PORTD = 0x00; TimerSet(30); TimerOn(); state = Init; LCD_init(); while (1) { button = ~PINA; Tick(); while(!TimerFlag){} TimerFlag = 0; PORTB = tmpB; } }
2.640625
3
2024-11-18T21:52:11.117515+00:00
2018-09-06T04:19:31
11761685d1306ed48850cfc670e1eb87019d3025
{ "blob_id": "11761685d1306ed48850cfc670e1eb87019d3025", "branch_name": "refs/heads/master", "committer_date": "2018-09-06T04:19:31", "content_id": "02af203afc996dbb70dd3cb39ee267f0e38bd054", "detected_licenses": [ "MIT" ], "directory_id": "134fca5b62ca6bac59ba1af5a5ebd271d9b53281", "extension": "c", "filename": "dkf5kRange.c", "fork_events_count": 2, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 147616821, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 412, "license": "MIT", "license_type": "permissive", "path": "/build/stx/support/tools/splint-3.1.2/test/dkf5kRange.c", "provenance": "stackv2-0138.json.gz:152591", "repo_name": "GunterMueller/ST_STX_Fork", "revision_date": "2018-09-06T04:19:31", "revision_id": "d891b139f3c016b81feeb5bf749e60585575bff7", "snapshot_id": "3ba5fb5482d9827f32526e3c32a8791c7434bb6b", "src_encoding": "UTF-8", "star_events_count": 3, "url": "https://raw.githubusercontent.com/GunterMueller/ST_STX_Fork/d891b139f3c016b81feeb5bf749e60585575bff7/build/stx/support/tools/splint-3.1.2/test/dkf5kRange.c", "visit_date": "2020-03-28T03:03:46.770962" }
stackv2
/*dkf5k*/ #include <stdlib.h> #include <stdio.h> int main() { char buffer[12] = "hello world"; int i; printf("Enter the character you want: "); scanf("%i", &i); if ( i >= sizeof(buffer)) { fprintf(stderr, "Error: %i is greater than or equal to the range which is %i", i, sizeof(buffer)); exit(0); } printf("You asked for character %i which is %c", i, buffer[i]); return 0; }
3.265625
3
2024-11-18T21:52:11.257057+00:00
2014-10-01T19:07:07
0df8361237b1b22a5414a754852fa5682640a614
{ "blob_id": "0df8361237b1b22a5414a754852fa5682640a614", "branch_name": "refs/heads/master", "committer_date": "2014-10-01T19:07:07", "content_id": "ceee95684c95ade5a742050b9ec1d8e16221c642", "detected_licenses": [ "BSD-3-Clause-Open-MPI" ], "directory_id": "ae7c18a47b72580fe4f48fafadafe6c79397c579", "extension": "c", "filename": "unpack.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 24691010, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 49740, "license": "BSD-3-Clause-Open-MPI", "license_type": "permissive", "path": "/src/buffer_ops/unpack.c", "provenance": "stackv2-0138.json.gz:152855", "repo_name": "jladd-mlnx/pmix", "revision_date": "2014-10-01T19:07:07", "revision_id": "f4e5fb124bd895b44e355da7482c1eecbdd5ec4f", "snapshot_id": "ee9d0b3a4213818e5c50db57025c1a3404f30fe8", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/jladd-mlnx/pmix/f4e5fb124bd895b44e355da7482c1eecbdd5ec4f/src/buffer_ops/unpack.c", "visit_date": "2021-01-22T23:21:02.328331" }
stackv2
/* * Copyright (c) 2004-2007 The Trustees of Indiana University and Indiana * University Research and Technology * Corporation. All rights reserved. * Copyright (c) 2004-2006 The University of Tennessee and The University * of Tennessee Research Foundation. All rights * reserved. * Copyright (c) 2004-2005 High Performance Computing Center Stuttgart, * University of Stuttgart. All rights reserved. * Copyright (c) 2004-2005 The Regents of the University of California. * All rights reserved. * Copyright (c) 2012 Los Alamos National Security, Inc. All rights reserved. * Copyright (c) 2014 Intel, Inc. All rights reserved. * $COPYRIGHT$ * * Additional copyrights may follow * * $HEADER$ */ #include "pmix_config.h" #include "src/util/error.h" #include "src/util/output.h" #include "src/buffer_ops/types.h" #include "src/buffer_ops/internal.h" int pmix_bfrop_unpack(pmix_buffer_t *buffer, void *dst, int32_t *num_vals, pmix_data_type_t type) { int rc, ret; int32_t local_num, n=1; pmix_data_type_t local_type; /* check for error */ if (NULL == buffer || NULL == dst || NULL == num_vals) { return PMIX_ERR_BAD_PARAM; } /* if user provides a zero for num_vals, then there is no storage allocated * so return an appropriate error */ if (0 == *num_vals) { PMIX_OUTPUT( ( pmix_bfrop_verbose, "pmix_bfrop_unpack: inadequate space ( %p, %p, %lu, %d )\n", (void*)buffer, dst, (long unsigned int)*num_vals, (int)type ) ); return PMIX_ERR_UNPACK_INADEQUATE_SPACE; } /** Unpack the declared number of values * REMINDER: it is possible that the buffer is corrupted and that * the BFROP will *think* there is a proper int32_t variable at the * beginning of the unpack region - but that the value is bogus (e.g., just * a byte field in a string array that so happens to have a value that * matches the int32_t data type flag). Therefore, this error check is * NOT completely safe. This is true for ALL unpack functions, not just * int32_t as used here. */ if (PMIX_BFROP_BUFFER_FULLY_DESC == buffer->type) { if (PMIX_SUCCESS != ( rc = pmix_bfrop_get_data_type(buffer, &local_type))) { *num_vals = 0; return rc; } if (PMIX_INT32 != local_type) { /* if the length wasn't first, then error */ *num_vals = 0; return PMIX_ERR_UNPACK_FAILURE; } } n=1; if (PMIX_SUCCESS != (rc = pmix_bfrop_unpack_int32(buffer, &local_num, &n, PMIX_INT32))) { *num_vals = 0; return rc; } /** if the storage provided is inadequate, set things up * to unpack as much as we can and to return an error code * indicating that everything was not unpacked - the buffer * is left in a state where it can not be further unpacked. */ if (local_num > *num_vals) { local_num = *num_vals; PMIX_OUTPUT( ( pmix_bfrop_verbose, "pmix_bfrop_unpack: inadequate space ( %p, %p, %lu, %d )\n", (void*)buffer, dst, (long unsigned int)*num_vals, (int)type ) ); ret = PMIX_ERR_UNPACK_INADEQUATE_SPACE; } else { /** enough or more than enough storage */ *num_vals = local_num; /** let the user know how many we actually unpacked */ ret = PMIX_SUCCESS; } /** Unpack the value(s) */ if (PMIX_SUCCESS != (rc = pmix_bfrop_unpack_buffer(buffer, dst, &local_num, type))) { *num_vals = 0; ret = rc; } return ret; } int pmix_bfrop_unpack_buffer(pmix_buffer_t *buffer, void *dst, int32_t *num_vals, pmix_data_type_t type) { int rc; pmix_data_type_t local_type; pmix_bfrop_type_info_t *info; PMIX_OUTPUT( ( pmix_bfrop_verbose, "pmix_bfrop_unpack_buffer( %p, %p, %lu, %d )\n", (void*)buffer, dst, (long unsigned int)*num_vals, (int)type ) ); /** Unpack the declared data type */ if (PMIX_BFROP_BUFFER_FULLY_DESC == buffer->type) { if (PMIX_SUCCESS != (rc = pmix_bfrop_get_data_type(buffer, &local_type))) { return rc; } /* if the data types don't match, then return an error */ if (type != local_type) { pmix_output(0, "PMIX bfrop:unpack: got type %d when expecting type %d", local_type, type); return PMIX_ERR_PACK_MISMATCH; } } /* Lookup the unpack function for this type and call it */ if (NULL == (info = (pmix_bfrop_type_info_t*)pmix_pointer_array_get_item(&pmix_bfrop_types, type))) { return PMIX_ERR_UNPACK_FAILURE; } return info->odti_unpack_fn(buffer, dst, num_vals, type); } /* UNPACK GENERIC SYSTEM TYPES */ /* * BOOL */ int pmix_bfrop_unpack_bool(pmix_buffer_t *buffer, void *dest, int32_t *num_vals, pmix_data_type_t type) { int ret; pmix_data_type_t remote_type; if (PMIX_BFROP_BUFFER_FULLY_DESC == buffer->type) { /* see what type was actually packed */ if (PMIX_SUCCESS != (ret = pmix_bfrop_peek_type(buffer, &remote_type))) { return ret; } } else { if (PMIX_SUCCESS != (ret = pmix_bfrop_get_data_type(buffer, &remote_type))) { return ret; } } if (remote_type == BFROP_TYPE_BOOL) { /* fast path it if the sizes are the same */ /* Turn around and unpack the real type */ if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_buffer(buffer, dest, num_vals, BFROP_TYPE_BOOL))) { } } else { /* slow path - types are different sizes */ UNPACK_SIZE_MISMATCH(bool, remote_type, ret); } return ret; } /* * INT */ int pmix_bfrop_unpack_int(pmix_buffer_t *buffer, void *dest, int32_t *num_vals, pmix_data_type_t type) { int ret; pmix_data_type_t remote_type; if (PMIX_BFROP_BUFFER_FULLY_DESC == buffer->type) { /* see what type was actually packed */ if (PMIX_SUCCESS != (ret = pmix_bfrop_peek_type(buffer, &remote_type))) { return ret; } } else { if (PMIX_SUCCESS != (ret = pmix_bfrop_get_data_type(buffer, &remote_type))) { return ret; } } if (remote_type == BFROP_TYPE_INT) { /* fast path it if the sizes are the same */ /* Turn around and unpack the real type */ if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_buffer(buffer, dest, num_vals, BFROP_TYPE_INT))) { } } else { /* slow path - types are different sizes */ UNPACK_SIZE_MISMATCH(int, remote_type, ret); } return ret; } /* * SIZE_T */ int pmix_bfrop_unpack_sizet(pmix_buffer_t *buffer, void *dest, int32_t *num_vals, pmix_data_type_t type) { int ret; pmix_data_type_t remote_type; if (PMIX_BFROP_BUFFER_FULLY_DESC == buffer->type) { /* see what type was actually packed */ if (PMIX_SUCCESS != (ret = pmix_bfrop_peek_type(buffer, &remote_type))) { return ret; } } else { if (PMIX_SUCCESS != (ret = pmix_bfrop_get_data_type(buffer, &remote_type))) { return ret; } } if (remote_type == BFROP_TYPE_SIZE_T) { /* fast path it if the sizes are the same */ /* Turn around and unpack the real type */ if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_buffer(buffer, dest, num_vals, BFROP_TYPE_SIZE_T))) { } } else { /* slow path - types are different sizes */ UNPACK_SIZE_MISMATCH(size_t, remote_type, ret); } return ret; } /* * PID_T */ int pmix_bfrop_unpack_pid(pmix_buffer_t *buffer, void *dest, int32_t *num_vals, pmix_data_type_t type) { int ret; pmix_data_type_t remote_type; if (PMIX_BFROP_BUFFER_FULLY_DESC == buffer->type) { /* see what type was actually packed */ if (PMIX_SUCCESS != (ret = pmix_bfrop_peek_type(buffer, &remote_type))) { return ret; } } else { if (PMIX_SUCCESS != (ret = pmix_bfrop_get_data_type(buffer, &remote_type))) { return ret; } } if (remote_type == BFROP_TYPE_PID_T) { /* fast path it if the sizes are the same */ /* Turn around and unpack the real type */ if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_buffer(buffer, dest, num_vals, BFROP_TYPE_PID_T))) { } } else { /* slow path - types are different sizes */ UNPACK_SIZE_MISMATCH(pid_t, remote_type, ret); } return ret; } /* UNPACK FUNCTIONS FOR NON-GENERIC SYSTEM TYPES */ /* * NULL */ int pmix_bfrop_unpack_null(pmix_buffer_t *buffer, void *dest, int32_t *num_vals, pmix_data_type_t type) { PMIX_OUTPUT( ( pmix_bfrop_verbose, "pmix_bfrop_unpack_null * %d\n", (int)*num_vals ) ); /* check to see if there's enough data in buffer */ if (pmix_bfrop_too_small(buffer, *num_vals)) { return PMIX_ERR_UNPACK_READ_PAST_END_OF_BUFFER; } /* unpack the data */ memcpy(dest, buffer->unpack_ptr, *num_vals); /* update buffer pointer */ buffer->unpack_ptr += *num_vals; return PMIX_SUCCESS; } /* * BYTE, CHAR, INT8 */ int pmix_bfrop_unpack_byte(pmix_buffer_t *buffer, void *dest, int32_t *num_vals, pmix_data_type_t type) { PMIX_OUTPUT( ( pmix_bfrop_verbose, "pmix_bfrop_unpack_byte * %d\n", (int)*num_vals ) ); /* check to see if there's enough data in buffer */ if (pmix_bfrop_too_small(buffer, *num_vals)) { return PMIX_ERR_UNPACK_READ_PAST_END_OF_BUFFER; } /* unpack the data */ memcpy(dest, buffer->unpack_ptr, *num_vals); /* update buffer pointer */ buffer->unpack_ptr += *num_vals; return PMIX_SUCCESS; } int pmix_bfrop_unpack_int16(pmix_buffer_t *buffer, void *dest, int32_t *num_vals, pmix_data_type_t type) { int32_t i; uint16_t tmp, *desttmp = (uint16_t*) dest; PMIX_OUTPUT( ( pmix_bfrop_verbose, "pmix_bfrop_unpack_int16 * %d\n", (int)*num_vals ) ); /* check to see if there's enough data in buffer */ if (pmix_bfrop_too_small(buffer, (*num_vals)*sizeof(tmp))) { return PMIX_ERR_UNPACK_READ_PAST_END_OF_BUFFER; } /* unpack the data */ for (i = 0; i < (*num_vals); ++i) { memcpy( &(tmp), buffer->unpack_ptr, sizeof(tmp) ); tmp = ntohs(tmp); memcpy(&desttmp[i], &tmp, sizeof(tmp)); buffer->unpack_ptr += sizeof(tmp); } return PMIX_SUCCESS; } int pmix_bfrop_unpack_int32(pmix_buffer_t *buffer, void *dest, int32_t *num_vals, pmix_data_type_t type) { int32_t i; uint32_t tmp, *desttmp = (uint32_t*) dest; PMIX_OUTPUT( ( pmix_bfrop_verbose, "pmix_bfrop_unpack_int32 * %d\n", (int)*num_vals ) ); /* check to see if there's enough data in buffer */ if (pmix_bfrop_too_small(buffer, (*num_vals)*sizeof(tmp))) { return PMIX_ERR_UNPACK_READ_PAST_END_OF_BUFFER; } /* unpack the data */ for (i = 0; i < (*num_vals); ++i) { memcpy( &(tmp), buffer->unpack_ptr, sizeof(tmp) ); tmp = ntohl(tmp); memcpy(&desttmp[i], &tmp, sizeof(tmp)); buffer->unpack_ptr += sizeof(tmp); } return PMIX_SUCCESS; } int pmix_bfrop_unpack_int64(pmix_buffer_t *buffer, void *dest, int32_t *num_vals, pmix_data_type_t type) { int32_t i; uint64_t tmp, *desttmp = (uint64_t*) dest; PMIX_OUTPUT( ( pmix_bfrop_verbose, "pmix_bfrop_unpack_int64 * %d\n", (int)*num_vals ) ); /* check to see if there's enough data in buffer */ if (pmix_bfrop_too_small(buffer, (*num_vals)*sizeof(tmp))) { return PMIX_ERR_UNPACK_READ_PAST_END_OF_BUFFER; } /* unpack the data */ for (i = 0; i < (*num_vals); ++i) { memcpy( &(tmp), buffer->unpack_ptr, sizeof(tmp) ); tmp = ntoh64(tmp); memcpy(&desttmp[i], &tmp, sizeof(tmp)); buffer->unpack_ptr += sizeof(tmp); } return PMIX_SUCCESS; } int pmix_bfrop_unpack_string(pmix_buffer_t *buffer, void *dest, int32_t *num_vals, pmix_data_type_t type) { int ret; int32_t i, len, n=1; char **sdest = (char**) dest; for (i = 0; i < (*num_vals); ++i) { if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_int32(buffer, &len, &n, PMIX_INT32))) { return ret; } if (0 == len) { /* zero-length string - unpack the NULL */ sdest[i] = NULL; } else { sdest[i] = (char*)malloc(len); if (NULL == sdest[i]) { return PMIX_ERR_OUT_OF_RESOURCE; } if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_byte(buffer, sdest[i], &len, PMIX_BYTE))) { return ret; } } } return PMIX_SUCCESS; } int pmix_bfrop_unpack_float(pmix_buffer_t *buffer, void *dest, int32_t *num_vals, pmix_data_type_t type) { int32_t i, n; float *desttmp = (float*) dest, tmp; int ret; char *convert; PMIX_OUTPUT( ( pmix_bfrop_verbose, "pmix_bfrop_unpack_float * %d\n", (int)*num_vals ) ); /* check to see if there's enough data in buffer */ if (pmix_bfrop_too_small(buffer, (*num_vals)*sizeof(float))) { return PMIX_ERR_UNPACK_READ_PAST_END_OF_BUFFER; } /* unpack the data */ for (i = 0; i < (*num_vals); ++i) { n=1; if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_string(buffer, &convert, &n, PMIX_STRING))) { return ret; } tmp = strtof(convert, NULL); memcpy(&desttmp[i], &tmp, sizeof(tmp)); free(convert); } return PMIX_SUCCESS; } int pmix_bfrop_unpack_double(pmix_buffer_t *buffer, void *dest, int32_t *num_vals, pmix_data_type_t type) { int32_t i, n; double *desttmp = (double*) dest, tmp; int ret; char *convert; PMIX_OUTPUT( ( pmix_bfrop_verbose, "pmix_bfrop_unpack_double * %d\n", (int)*num_vals ) ); /* check to see if there's enough data in buffer */ if (pmix_bfrop_too_small(buffer, (*num_vals)*sizeof(double))) { return PMIX_ERR_UNPACK_READ_PAST_END_OF_BUFFER; } /* unpack the data */ for (i = 0; i < (*num_vals); ++i) { n=1; if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_string(buffer, &convert, &n, PMIX_STRING))) { return ret; } tmp = strtod(convert, NULL); memcpy(&desttmp[i], &tmp, sizeof(tmp)); free(convert); } return PMIX_SUCCESS; } int pmix_bfrop_unpack_timeval(pmix_buffer_t *buffer, void *dest, int32_t *num_vals, pmix_data_type_t type) { int32_t i, n; int64_t tmp[2]; struct timeval *desttmp = (struct timeval *) dest, tt; int ret; PMIX_OUTPUT( ( pmix_bfrop_verbose, "pmix_bfrop_unpack_timeval * %d\n", (int)*num_vals ) ); /* check to see if there's enough data in buffer */ if (pmix_bfrop_too_small(buffer, (*num_vals)*sizeof(struct timeval))) { return PMIX_ERR_UNPACK_READ_PAST_END_OF_BUFFER; } /* unpack the data */ for (i = 0; i < (*num_vals); ++i) { n=2; if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_int64(buffer, tmp, &n, PMIX_INT64))) { return ret; } tt.tv_sec = tmp[0]; tt.tv_usec = tmp[1]; memcpy(&desttmp[i], &tt, sizeof(tt)); } return PMIX_SUCCESS; } int pmix_bfrop_unpack_time(pmix_buffer_t *buffer, void *dest, int32_t *num_vals, pmix_data_type_t type) { int32_t i, n; time_t *desttmp = (time_t *) dest, tmp; int ret; uint64_t ui64; /* time_t is a system-dependent size, so cast it * to uint64_t as a generic safe size */ PMIX_OUTPUT( ( pmix_bfrop_verbose, "pmix_bfrop_unpack_time * %d\n", (int)*num_vals ) ); /* check to see if there's enough data in buffer */ if (pmix_bfrop_too_small(buffer, (*num_vals)*(sizeof(uint64_t)))) { return PMIX_ERR_UNPACK_READ_PAST_END_OF_BUFFER; } /* unpack the data */ for (i = 0; i < (*num_vals); ++i) { n=1; if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_int64(buffer, &ui64, &n, PMIX_UINT64))) { return ret; } tmp = (time_t)ui64; memcpy(&desttmp[i], &tmp, sizeof(tmp)); } return PMIX_SUCCESS; } /* UNPACK FUNCTIONS FOR GENERIC PMIX TYPES */ /* * PMIX_DATA_TYPE */ int pmix_bfrop_unpack_data_type(pmix_buffer_t *buffer, void *dest, int32_t *num_vals, pmix_data_type_t type) { /* turn around and unpack the real type */ return pmix_bfrop_unpack_buffer(buffer, dest, num_vals, PMIX_DATA_TYPE_T); } /* * PMIX_BYTE_OBJECT */ int pmix_bfrop_unpack_byte_object(pmix_buffer_t *buffer, void *dest, int32_t *num, pmix_data_type_t type) { int ret; int32_t i, n, m=1; pmix_byte_object_t **dbyteptr; dbyteptr = (pmix_byte_object_t**)dest; n = *num; for(i=0; i<n; i++) { /* allocate memory for the byte object itself */ dbyteptr[i] = (pmix_byte_object_t*)malloc(sizeof(pmix_byte_object_t)); if (NULL == dbyteptr[i]) { return PMIX_ERR_OUT_OF_RESOURCE; } /* unpack object size in bytes */ if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_int32(buffer, &(dbyteptr[i]->size), &m, PMIX_INT32))) { return ret; } if (0 < dbyteptr[i]->size) { dbyteptr[i]->bytes = (uint8_t*)malloc(dbyteptr[i]->size); if (NULL == dbyteptr[i]->bytes) { return PMIX_ERR_OUT_OF_RESOURCE; } if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_byte(buffer, (dbyteptr[i]->bytes), &(dbyteptr[i]->size), PMIX_BYTE))) { return ret; } } else { /* be sure to init the bytes pointer to NULL! */ dbyteptr[i]->bytes = NULL; } } return PMIX_SUCCESS; } /* * PMIX_PSTAT */ int pmix_bfrop_unpack_pstat(pmix_buffer_t *buffer, void *dest, int32_t *num_vals, pmix_data_type_t type) { pmix_pstats_t **ptr; int32_t i, n, m; int ret; char *cptr; ptr = (pmix_pstats_t **) dest; n = *num_vals; for (i = 0; i < n; ++i) { /* allocate the new object */ ptr[i] = OBJ_NEW(pmix_pstats_t); if (NULL == ptr[i]) { return PMIX_ERR_OUT_OF_RESOURCE; } m=1; if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_buffer(buffer, &cptr, &m, PMIX_STRING))) { PMIX_ERROR_LOG(ret); return ret; } memmove(ptr[i]->node, cptr, strlen(cptr)); free(cptr); m=1; if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_buffer(buffer, &ptr[i]->rank, &m, PMIX_INT32))) { PMIX_ERROR_LOG(ret); return ret; } m=1; if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_buffer(buffer, &ptr[i]->pid, &m, PMIX_PID))) { PMIX_ERROR_LOG(ret); return ret; } m=1; if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_buffer(buffer, &cptr, &m, PMIX_STRING))) { PMIX_ERROR_LOG(ret); return ret; } memmove(ptr[i]->cmd, cptr, strlen(cptr)); free(cptr); m=1; if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_buffer(buffer, &ptr[i]->state[0], &m, PMIX_BYTE))) { PMIX_ERROR_LOG(ret); return ret; } m=1; if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_buffer(buffer, &ptr[i]->time, &m, PMIX_TIMEVAL))) { PMIX_ERROR_LOG(ret); return ret; } m=1; if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_buffer(buffer, &ptr[i]->priority, &m, PMIX_INT32))) { PMIX_ERROR_LOG(ret); return ret; } m=1; if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_buffer(buffer, &ptr[i]->num_threads, &m, PMIX_INT16))) { PMIX_ERROR_LOG(ret); return ret; } m=1; if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_float(buffer, &ptr[i]->vsize, &m, PMIX_FLOAT))) { PMIX_ERROR_LOG(ret); return ret; } m=1; if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_float(buffer, &ptr[i]->rss, &m, PMIX_FLOAT))) { PMIX_ERROR_LOG(ret); return ret; } m=1; if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_float(buffer, &ptr[i]->peak_vsize, &m, PMIX_FLOAT))) { PMIX_ERROR_LOG(ret); return ret; } m=1; if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_buffer(buffer, &ptr[i]->processor, &m, PMIX_INT16))) { PMIX_ERROR_LOG(ret); return ret; } m=1; if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_buffer(buffer, &ptr[i]->sample_time, &m, PMIX_TIMEVAL))) { PMIX_ERROR_LOG(ret); return ret; } } return PMIX_SUCCESS; } static int unpack_disk_stats(pmix_buffer_t *buffer, pmix_node_stats_t *ns) { int32_t i, m, n; int ret; pmix_diskstats_t *dk; uint64_t i64; /* unpack the number of disk stat objects */ m=1; if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_buffer(buffer, &n, &m, PMIX_INT32))) { PMIX_ERROR_LOG(ret); return ret; } /* unpack them */ for (i=0; i < n; i++) { dk = OBJ_NEW(pmix_diskstats_t); assert(dk); m=1; if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_buffer(buffer, &dk->disk, &m, PMIX_STRING))) { PMIX_ERROR_LOG(ret); OBJ_RELEASE(dk); return ret; } m=1; if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_buffer(buffer, &i64, &m, PMIX_UINT64))) { PMIX_ERROR_LOG(ret); OBJ_RELEASE(dk); return ret; } dk->num_reads_completed = i64; m=1; if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_buffer(buffer, &i64, &m, PMIX_UINT64))) { PMIX_ERROR_LOG(ret); OBJ_RELEASE(dk); return ret; } dk->num_reads_merged = i64; m=1; if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_buffer(buffer, &i64, &m, PMIX_UINT64))) { PMIX_ERROR_LOG(ret); OBJ_RELEASE(dk); return ret; } dk->num_sectors_read = i64; m=1; if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_buffer(buffer, &i64, &m, PMIX_UINT64))) { PMIX_ERROR_LOG(ret); OBJ_RELEASE(dk); return ret; } dk->milliseconds_reading = i64; m=1; if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_buffer(buffer, &i64, &m, PMIX_UINT64))) { PMIX_ERROR_LOG(ret); OBJ_RELEASE(dk); return ret; } dk->num_writes_completed = i64; m=1; if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_buffer(buffer, &i64, &m, PMIX_UINT64))) { PMIX_ERROR_LOG(ret); OBJ_RELEASE(dk); return ret; } dk->num_writes_merged = i64; m=1; if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_buffer(buffer, &i64, &m, PMIX_UINT64))) { PMIX_ERROR_LOG(ret); OBJ_RELEASE(dk); return ret; } dk->num_sectors_written = i64; m=1; if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_buffer(buffer, &i64, &m, PMIX_UINT64))) { PMIX_ERROR_LOG(ret); OBJ_RELEASE(dk); return ret; } dk->milliseconds_writing = i64; m=1; if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_buffer(buffer, &i64, &m, PMIX_UINT64))) { PMIX_ERROR_LOG(ret); OBJ_RELEASE(dk); return ret; } dk->num_ios_in_progress = i64; m=1; if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_buffer(buffer, &i64, &m, PMIX_UINT64))) { PMIX_ERROR_LOG(ret); OBJ_RELEASE(dk); return ret; } dk->milliseconds_io = i64; m=1; if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_buffer(buffer, &i64, &m, PMIX_UINT64))) { PMIX_ERROR_LOG(ret); OBJ_RELEASE(dk); return ret; } dk->weighted_milliseconds_io = i64; pmix_list_append(&ns->diskstats, &dk->super); } return PMIX_SUCCESS; } static int unpack_net_stats(pmix_buffer_t *buffer, pmix_node_stats_t *ns) { int32_t i, m, n; int ret; pmix_netstats_t *net; uint64_t i64; /* unpack the number of net stat objects */ m=1; if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_buffer(buffer, &n, &m, PMIX_INT32))) { PMIX_ERROR_LOG(ret); return ret; } /* unpack them */ for (i=0; i < n; i++) { net = OBJ_NEW(pmix_netstats_t); assert(net); m=1; if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_buffer(buffer, &net->net_interface, &m, PMIX_STRING))) { PMIX_ERROR_LOG(ret); OBJ_RELEASE(net); return ret; } m=1; if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_buffer(buffer, &i64, &m, PMIX_UINT64))) { PMIX_ERROR_LOG(ret); OBJ_RELEASE(net); return ret; } net->num_bytes_recvd = i64; m=1; if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_buffer(buffer, &i64, &m, PMIX_UINT64))) { PMIX_ERROR_LOG(ret); OBJ_RELEASE(net); return ret; } net->num_packets_recvd = i64; m=1; if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_buffer(buffer, &i64, &m, PMIX_UINT64))) { PMIX_ERROR_LOG(ret); OBJ_RELEASE(net); return ret; } net->num_recv_errs = i64; m=1; if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_buffer(buffer, &i64, &m, PMIX_UINT64))) { PMIX_ERROR_LOG(ret); OBJ_RELEASE(net); return ret; } net->num_bytes_sent = i64; m=1; if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_buffer(buffer, &i64, &m, PMIX_UINT64))) { PMIX_ERROR_LOG(ret); OBJ_RELEASE(net); return ret; } net->num_packets_sent = i64; m=1; if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_buffer(buffer, &i64, &m, PMIX_UINT64))) { PMIX_ERROR_LOG(ret); OBJ_RELEASE(net); return ret; } net->num_send_errs = i64; pmix_list_append(&ns->netstats, &net->super); } return PMIX_SUCCESS; } /* * PMIX_NODE_STAT */ int pmix_bfrop_unpack_node_stat(pmix_buffer_t *buffer, void *dest, int32_t *num_vals, pmix_data_type_t type) { pmix_node_stats_t **ptr; int32_t i, n, m; int ret; ptr = (pmix_node_stats_t **) dest; n = *num_vals; for (i = 0; i < n; ++i) { /* allocate the new object */ ptr[i] = OBJ_NEW(pmix_node_stats_t); if (NULL == ptr[i]) { return PMIX_ERR_OUT_OF_RESOURCE; } m=1; if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_float(buffer, &ptr[i]->la, &m, PMIX_FLOAT))) { PMIX_ERROR_LOG(ret); return ret; } m=1; if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_float(buffer, &ptr[i]->la5, &m, PMIX_FLOAT))) { PMIX_ERROR_LOG(ret); return ret; } m=1; if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_float(buffer, &ptr[i]->la15, &m, PMIX_FLOAT))) { PMIX_ERROR_LOG(ret); return ret; } m=1; if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_float(buffer, &ptr[i]->total_mem, &m, PMIX_FLOAT))) { PMIX_ERROR_LOG(ret); return ret; } m=1; if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_float(buffer, &ptr[i]->free_mem, &m, PMIX_FLOAT))) { PMIX_ERROR_LOG(ret); return ret; } m=1; if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_float(buffer, &ptr[i]->buffers, &m, PMIX_FLOAT))) { PMIX_ERROR_LOG(ret); return ret; } m=1; if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_float(buffer, &ptr[i]->cached, &m, PMIX_FLOAT))) { PMIX_ERROR_LOG(ret); return ret; } m=1; if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_float(buffer, &ptr[i]->swap_cached, &m, PMIX_FLOAT))) { PMIX_ERROR_LOG(ret); return ret; } m=1; if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_float(buffer, &ptr[i]->swap_total, &m, PMIX_FLOAT))) { PMIX_ERROR_LOG(ret); return ret; } m=1; if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_float(buffer, &ptr[i]->swap_free, &m, PMIX_FLOAT))) { PMIX_ERROR_LOG(ret); return ret; } m=1; if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_float(buffer, &ptr[i]->mapped, &m, PMIX_FLOAT))) { PMIX_ERROR_LOG(ret); return ret; } m=1; if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_buffer(buffer, &ptr[i]->sample_time, &m, PMIX_TIMEVAL))) { PMIX_ERROR_LOG(ret); return ret; } /* unpack the disk stat objects */ if (PMIX_SUCCESS != (ret = unpack_disk_stats(buffer, ptr[i]))) { PMIX_ERROR_LOG(ret); return ret; } /* unpack the net stat objects */ if (PMIX_SUCCESS != (ret = unpack_net_stats(buffer, ptr[i]))) { PMIX_ERROR_LOG(ret); return ret; } } return PMIX_SUCCESS; } /* * PMIX_VALUE */ int pmix_bfrop_unpack_value(pmix_buffer_t *buffer, void *dest, int32_t *num_vals, pmix_data_type_t type) { pmix_value_t **ptr; int32_t i, n, m; int ret; ptr = (pmix_value_t **) dest; n = *num_vals; for (i = 0; i < n; ++i) { /* allocate the new object */ ptr[i] = OBJ_NEW(pmix_value_t); if (NULL == ptr[i]) { return PMIX_ERR_OUT_OF_RESOURCE; } /* unpack the key and type */ m=1; if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_string(buffer, &ptr[i]->key, &m, PMIX_STRING))) { return ret; } m=1; if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_data_type(buffer, &ptr[i]->type, &m, PMIX_DATA_TYPE))) { return ret; } /* now unpack the right field */ m=1; switch (ptr[i]->type) { case PMIX_BOOL: if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_buffer(buffer, &ptr[i]->data.flag, &m, PMIX_BOOL))) { return ret; } break; case PMIX_BYTE: if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_buffer(buffer, &ptr[i]->data.byte, &m, PMIX_BYTE))) { return ret; } break; case PMIX_STRING: if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_buffer(buffer, &ptr[i]->data.string, &m, PMIX_STRING))) { return ret; } break; case PMIX_SIZE: if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_buffer(buffer, &ptr[i]->data.size, &m, PMIX_SIZE))) { return ret; } break; case PMIX_PID: if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_buffer(buffer, &ptr[i]->data.pid, &m, PMIX_PID))) { return ret; } break; case PMIX_INT: if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_buffer(buffer, &ptr[i]->data.integer, &m, PMIX_INT))) { return ret; } break; case PMIX_INT8: if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_buffer(buffer, &ptr[i]->data.int8, &m, PMIX_INT8))) { return ret; } break; case PMIX_INT16: if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_buffer(buffer, &ptr[i]->data.int16, &m, PMIX_INT16))) { return ret; } break; case PMIX_INT32: if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_buffer(buffer, &ptr[i]->data.int32, &m, PMIX_INT32))) { return ret; } break; case PMIX_INT64: if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_buffer(buffer, &ptr[i]->data.int64, &m, PMIX_INT64))) { return ret; } break; case PMIX_UINT: if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_buffer(buffer, &ptr[i]->data.uint, &m, PMIX_UINT))) { return ret; } break; case PMIX_UINT8: if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_buffer(buffer, &ptr[i]->data.uint8, &m, PMIX_UINT8))) { return ret; } break; case PMIX_UINT16: if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_buffer(buffer, &ptr[i]->data.uint16, &m, PMIX_UINT16))) { return ret; } break; case PMIX_UINT32: if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_buffer(buffer, &ptr[i]->data.uint32, &m, PMIX_UINT32))) { return ret; } break; case PMIX_UINT64: if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_buffer(buffer, &ptr[i]->data.uint64, &m, PMIX_UINT64))) { return ret; } break; case PMIX_BYTE_OBJECT: /* cannot use byte object unpack as it allocates memory, so unpack object size in bytes */ if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_int32(buffer, &(ptr[i]->data.bo.size), &m, PMIX_INT32))) { return ret; } if (0 < ptr[i]->data.bo.size) { ptr[i]->data.bo.bytes = (uint8_t*)malloc(ptr[i]->data.bo.size); if (NULL == ptr[i]->data.bo.bytes) { return PMIX_ERR_OUT_OF_RESOURCE; } if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_byte(buffer, ptr[i]->data.bo.bytes, &(ptr[i]->data.bo.size), PMIX_BYTE))) { return ret; } } else { ptr[i]->data.bo.bytes = NULL; } break; case PMIX_FLOAT: if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_buffer(buffer, &ptr[i]->data.fval, &m, PMIX_FLOAT))) { return ret; } break; case PMIX_DOUBLE: if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_buffer(buffer, &ptr[i]->data.dval, &m, PMIX_DOUBLE))) { return ret; } break; case PMIX_TIMEVAL: if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_buffer(buffer, &ptr[i]->data.tv, &m, PMIX_TIMEVAL))) { return ret; } break; case PMIX_FLOAT_ARRAY: if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_buffer(buffer, &ptr[i]->data.fval_array.size, &m, PMIX_INT32))) { return ret; } if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_buffer(buffer, ptr[i]->data.fval_array.data, &ptr[i]->data.fval_array.size, PMIX_FLOAT))) { return ret; } break; case PMIX_DOUBLE_ARRAY: if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_buffer(buffer, &ptr[i]->data.dval_array.size, &m, PMIX_INT32))) { return ret; } if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_buffer(buffer, ptr[i]->data.dval_array.data, &ptr[i]->data.dval_array.size, PMIX_DOUBLE))) { return ret; } break; case PMIX_STRING_ARRAY: if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_buffer(buffer, &ptr[i]->data.string_array.size, &m, PMIX_INT32))) { return ret; } if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_buffer(buffer, ptr[i]->data.string_array.data, &ptr[i]->data.string_array.size, PMIX_STRING))) { return ret; } break; case PMIX_BOOL_ARRAY: if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_buffer(buffer, &ptr[i]->data.flag_array.size, &m, PMIX_INT32))) { return ret; } if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_buffer(buffer, ptr[i]->data.flag_array.data, &ptr[i]->data.flag_array.size, PMIX_BOOL))) { return ret; } break; case PMIX_SIZE_ARRAY: if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_buffer(buffer, &ptr[i]->data.size_array.size, &m, PMIX_INT32))) { return ret; } if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_buffer(buffer, ptr[i]->data.size_array.data, &ptr[i]->data.size_array.size, PMIX_SIZE))) { return ret; } break; case PMIX_BYTE_ARRAY: if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_buffer(buffer, &ptr[i]->data.byte_array.size, &m, PMIX_INT32))) { return ret; } if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_buffer(buffer, ptr[i]->data.byte_array.data, &ptr[i]->data.byte_array.size, PMIX_BYTE))) { return ret; } break; case PMIX_INT_ARRAY: if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_buffer(buffer, &ptr[i]->data.integer_array.size, &m, PMIX_INT32))) { return ret; } if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_buffer(buffer, ptr[i]->data.integer_array.data, &ptr[i]->data.integer_array.size, PMIX_INT))) { return ret; } break; case PMIX_INT8_ARRAY: if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_buffer(buffer, &ptr[i]->data.int8_array.size, &m, PMIX_INT32))) { return ret; } if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_buffer(buffer, ptr[i]->data.int8_array.data, &ptr[i]->data.int8_array.size, PMIX_INT8))) { return ret; } break; case PMIX_INT16_ARRAY: if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_buffer(buffer, &ptr[i]->data.int16_array.size, &m, PMIX_INT32))) { return ret; } if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_buffer(buffer, ptr[i]->data.int16_array.data, &ptr[i]->data.int16_array.size, PMIX_INT16))) { return ret; } break; case PMIX_INT32_ARRAY: if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_buffer(buffer, &ptr[i]->data.int32_array.size, &m, PMIX_INT32))) { return ret; } if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_buffer(buffer, ptr[i]->data.int32_array.data, &ptr[i]->data.int32_array.size, PMIX_INT32))) { return ret; } break; case PMIX_INT64_ARRAY: if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_buffer(buffer, &ptr[i]->data.int64_array.size, &m, PMIX_INT32))) { return ret; } if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_buffer(buffer, ptr[i]->data.int64_array.data, &ptr[i]->data.int64_array.size, PMIX_INT64))) { return ret; } break; case PMIX_UINT_ARRAY: if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_buffer(buffer, &ptr[i]->data.uint_array.size, &m, PMIX_INT32))) { return ret; } if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_buffer(buffer, ptr[i]->data.uint_array.data, &ptr[i]->data.uint_array.size, PMIX_UINT))) { return ret; } break; case PMIX_UINT8_ARRAY: if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_buffer(buffer, &ptr[i]->data.uint8_array.size, &m, PMIX_INT32))) { return ret; } if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_buffer(buffer, ptr[i]->data.uint8_array.data, &ptr[i]->data.uint8_array.size, PMIX_UINT8))) { return ret; } break; case PMIX_UINT16_ARRAY: if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_buffer(buffer, &ptr[i]->data.uint16_array.size, &m, PMIX_INT32))) { return ret; } if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_buffer(buffer, ptr[i]->data.uint16_array.data, &ptr[i]->data.uint16_array.size, PMIX_UINT16))) { return ret; } break; case PMIX_UINT32_ARRAY: if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_buffer(buffer, &ptr[i]->data.uint32_array.size, &m, PMIX_INT32))) { return ret; } if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_buffer(buffer, ptr[i]->data.uint32_array.data, &ptr[i]->data.uint32_array.size, PMIX_UINT32))) { return ret; } break; case PMIX_UINT64_ARRAY: if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_buffer(buffer, &ptr[i]->data.uint64_array.size, &m, PMIX_INT32))) { return ret; } if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_buffer(buffer, ptr[i]->data.uint64_array.data, &ptr[i]->data.uint64_array.size, PMIX_UINT64))) { return ret; } break; case PMIX_PID_ARRAY: if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_buffer(buffer, &ptr[i]->data.pid_array.size, &m, PMIX_INT32))) { return ret; } if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_buffer(buffer, ptr[i]->data.pid_array.data, &ptr[i]->data.pid_array.size, PMIX_PID))) { return ret; } break; case PMIX_TIMEVAL_ARRAY: if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_buffer(buffer, &ptr[i]->data.tv_array.size, &m, PMIX_INT32))) { return ret; } if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_buffer(buffer, ptr[i]->data.tv_array.data, &ptr[i]->data.tv_array.size, PMIX_TIMEVAL))) { return ret; } break; default: pmix_output(0, "PACK-PMIX-VALUE: UNSUPPORTED TYPE"); return PMIX_ERROR; } } return PMIX_SUCCESS; } /* * PMIX_BUFFER */ int pmix_bfrop_unpack_buffer_contents(pmix_buffer_t *buffer, void *dest, int32_t *num_vals, pmix_data_type_t type) { pmix_buffer_t **ptr; int32_t i, n, m; int ret; size_t nbytes; ptr = (pmix_buffer_t **) dest; n = *num_vals; for (i = 0; i < n; ++i) { /* allocate the new object */ ptr[i] = OBJ_NEW(pmix_buffer_t); if (NULL == ptr[i]) { return PMIX_ERR_OUT_OF_RESOURCE; } /* unpack the number of bytes */ m=1; if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_sizet(buffer, &nbytes, &m, PMIX_SIZE))) { return ret; } m = nbytes; /* setup the buffer's data region */ if (0 < nbytes) { ptr[i]->base_ptr = (char*)malloc(nbytes); /* unpack the bytes */ if (PMIX_SUCCESS != (ret = pmix_bfrop_unpack_byte(buffer, ptr[i]->base_ptr, &m, PMIX_BYTE))) { return ret; } } ptr[i]->pack_ptr = ptr[i]->base_ptr + m; ptr[i]->unpack_ptr = ptr[i]->base_ptr; ptr[i]->bytes_allocated = nbytes; ptr[i]->bytes_used = m; } return PMIX_SUCCESS; }
2.09375
2
2024-11-18T21:52:13.527975+00:00
2015-02-03T21:19:40
2da190bf09a49ab4da15b26a15be70b72149b58d
{ "blob_id": "2da190bf09a49ab4da15b26a15be70b72149b58d", "branch_name": "refs/heads/master", "committer_date": "2015-02-03T21:19:40", "content_id": "105040da8cf3b4ccc489f23b323f1b1e85b366fa", "detected_licenses": [ "Apache-2.0" ], "directory_id": "171d04578c725c0884fd7abd820fa1eb25330247", "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": 30092443, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 787, "license": "Apache-2.0", "license_type": "permissive", "path": "/main.c", "provenance": "stackv2-0138.json.gz:153634", "repo_name": "mitre-cyber-academy/2012-binary-c", "revision_date": "2015-02-03T21:19:40", "revision_id": "10ecda7110d21e121831694f492cec6b2d25621c", "snapshot_id": "6266a98d2431175c2732f117bc0a3880eaebd5e8", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/mitre-cyber-academy/2012-binary-c/10ecda7110d21e121831694f492cec6b2d25621c/main.c", "visit_date": "2021-01-18T13:45:22.634209" }
stackv2
#include <stdio.h> #include <string.h> void crypt(const char* originalMessage, char* codedMessage, char key) { unsigned int size = strlen(originalMessage); unsigned int i = 0; for(i=0; i<size; i++){ codedMessage[i] = originalMessage[i]; codedMessage[i] ^= key; } codedMessage[i] = '\n'; } int main(int argc, char** argv) { unsigned int i = 0; char one[12] = "8.4,425#-.25"; char two[12] = "?>!\\%#(0608?"; char three[12] = ",\" LWQRWV''%"; char four[12] = "4!8\\2708=KVY"; char keys[8] = {'c', 's', 'q', 'r', 'a', 'f', 'o', 'h'}; char flag[13]; for(i=0; i<9; i++){ crypt(three, flag, keys[i]); if(strncmp(flag, "MCA", 3) == 0){ printf("Your flag: %s", flag); } } }
2.71875
3
2024-11-18T21:52:13.882277+00:00
2020-02-22T10:26:11
27b14e5eb102ee4787c251ff16ac2ef75b0f09cc
{ "blob_id": "27b14e5eb102ee4787c251ff16ac2ef75b0f09cc", "branch_name": "refs/heads/master", "committer_date": "2020-02-22T10:26:11", "content_id": "886f5b42735a59c00a69c471f2b27c46208ae51f", "detected_licenses": [ "Unlicense" ], "directory_id": "c5d1257a3081681e0eb935d30b250a8a0cd29641", "extension": "c", "filename": "lak_memory_linux.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 237546865, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 543, "license": "Unlicense", "license_type": "permissive", "path": "/examples/lak_memory/lak_memory_linux.c", "provenance": "stackv2-0138.json.gz:153893", "repo_name": "LAK132/graphics-notebook", "revision_date": "2020-02-22T10:26:11", "revision_id": "b7b04c416ba8c2dd9abc59c0e38a00f7d330e2aa", "snapshot_id": "24b293453da07e48d123f3a89d042eb10014041c", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/LAK132/graphics-notebook/b7b04c416ba8c2dd9abc59c0e38a00f7d330e2aa/examples/lak_memory/lak_memory_linux.c", "visit_date": "2020-12-26T15:08:47.269693" }
stackv2
#include "lak_memory.h" #include <sys/mman.h> void lak_array_malloc(lak_array_t *array, size_t size) { array->data = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0); array->size = size; } void lak_array_free(lak_array_t *array) { munmap(array->data, array->size); array->data = NULL; array->size = 0; } typedef struct { lak_array_t pointers; lak_array_t sizes; } lak_allocations_t; lak_array_t allocations; void *lak_malloc(size_t size) { } void lak_free(void *data) { }
2.359375
2
2024-11-18T21:52:14.006088+00:00
2021-05-03T01:10:25
0681d0b2fc45cb13a192d48235cde9d6e458d24d
{ "blob_id": "0681d0b2fc45cb13a192d48235cde9d6e458d24d", "branch_name": "refs/heads/master", "committer_date": "2021-05-03T01:10:25", "content_id": "67ce3ff924df54ba0ca9ad4421c1e88cf56c3430", "detected_licenses": [ "Apache-2.0" ], "directory_id": "09d792a135d4d5eb06af247452228a2538ee097f", "extension": "h", "filename": "pkcs1.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 282106322, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1620, "license": "Apache-2.0", "license_type": "permissive", "path": "/C/rsa_tools/pkcs1.h", "provenance": "stackv2-0138.json.gz:154023", "repo_name": "BabaH/code_samples", "revision_date": "2021-05-03T01:10:25", "revision_id": "d8ba06f0a35338ca8e362e4ecd604d16cb8ee74f", "snapshot_id": "dc727cdfeadf24d9a26ae0a806e2d05507803ff5", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/BabaH/code_samples/d8ba06f0a35338ca8e362e4ecd604d16cb8ee74f/C/rsa_tools/pkcs1.h", "visit_date": "2023-04-18T16:30:45.351172" }
stackv2
/** * @file pkcs1.h * @author Hidenori BABA ([email protected]) * @brief * * @copyright Copyright (c) 2020 Hidenori BABA * */ #include <stdio.h> #include <stdint.h> #include <stdbool.h> #include <string.h> #ifndef __PKCS1_H__ #define __PKCS1_H__ #define PKCS1_E_OK (0) #define PKCS1_E_PARAM (-1) #define PKCS1_E_RANGE (-2) #define PKCS1_E_VERIFY (-3) #define PKCS1_E_RESOURCE (-254) #define PKCS1_E_INTERNAL (-255) #ifdef PKCS1_TRACE #define PKCS1_DEBUG_TRACE (1) #endif /* PKCS1TRACE */ typedef struct { uint8_t *n; uint8_t *e; uint8_t *d; uint8_t *p; uint8_t *q; uint8_t *dp; uint8_t *dq; uint8_t *qinv; size_t n_len; size_t e_len; size_t d_len; size_t p_len; size_t q_len; size_t dp_len; size_t dq_len; size_t qinv_len; } RSA_TOOLS_PRIV_KEY_t; typedef struct { uint8_t *n; uint8_t *e; size_t n_len; size_t e_len; } RSA_TOOLS_PUB_KEY_t; int rsaep(RSA_TOOLS_PUB_KEY_t key, uint8_t *msg, size_t mlen, uint8_t *emsg, size_t *emlen); int rsadp(RSA_TOOLS_PRIV_KEY_t key, uint8_t *emsg, size_t emlen, uint8_t *msg, size_t *mlen, bool use_crt); int rsasp1(RSA_TOOLS_PRIV_KEY_t key, uint8_t *msg, size_t mlen, uint8_t *sig, size_t *slen, bool use_crt); int rsavp1(RSA_TOOLS_PUB_KEY_t key, uint8_t *msg, size_t mlen, uint8_t *sig, size_t *slen); int pkcs1_rsa_sign(RSA_TOOLS_PRIV_KEY_t key, uint8_t *msg, size_t mlen, uint8_t *sig, size_t *slen, bool use_crt); int pksc1_rsa_verify(RSA_TOOLS_PUB_KEY_t key, uint8_t *msg, size_t mlen, uint8_t *sig, size_t slen); #endif /* __PKCS1_H__ */
2.09375
2
2024-11-18T21:52:14.071924+00:00
2023-08-29T11:09:10
9c9ac28076566c475ec34eb6cd0b02283bf65143
{ "blob_id": "9c9ac28076566c475ec34eb6cd0b02283bf65143", "branch_name": "refs/heads/master", "committer_date": "2023-08-29T11:09:10", "content_id": "ef4c2b296c06dfe4b681dec19ce436793692b922", "detected_licenses": [ "BSD-3-Clause", "MIT", "Apache-2.0" ], "directory_id": "11269038e69d038803de79fc0c8a580eb4de0454", "extension": "c", "filename": "byte_buf.c", "fork_events_count": 9, "gha_created_at": "2020-02-28T22:18:04", "gha_event_created_at": "2023-08-31T16:10:29", "gha_language": "OCaml", "gha_license_id": "BSD-3-Clause", "github_id": 243864324, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5259, "license": "BSD-3-Clause,MIT,Apache-2.0", "license_type": "permissive", "path": "/Gillian-C/examples/amazon_bi/byte_buf.c", "provenance": "stackv2-0138.json.gz:154152", "repo_name": "GillianPlatform/Gillian", "revision_date": "2023-08-29T11:09:10", "revision_id": "86aa85086722120908cdfc4d429276a86719ff9d", "snapshot_id": "083f535aca37e4e9e96c0052152874c70a18ecf7", "src_encoding": "UTF-8", "star_events_count": 64, "url": "https://raw.githubusercontent.com/GillianPlatform/Gillian/86aa85086722120908cdfc4d429276a86719ff9d/Gillian-C/examples/amazon_bi/byte_buf.c", "visit_date": "2023-09-04T05:43:36.863585" }
stackv2
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ /* This file corresponds to the following commit: https://github.com/awslabs/aws-c-common/tree/bb797381f3468e6f076e53eddbb399a99f54f67b */ #include "byte_buf.h" int aws_byte_buf_init(struct aws_byte_buf *buf, size_t capacity) { buf->buffer = (capacity == 0) ? NULL : malloc(capacity); if (capacity != 0 && buf->buffer == NULL) { AWS_ZERO_STRUCT(*buf); return 1; } buf->len = 0; buf->capacity = capacity; // AWS_POSTCONDITION(aws_byte_buf_is_valid(buf)); return 0; } void aws_byte_buf_clean_up(struct aws_byte_buf *buf) { // AWS_PRECONDITION(aws_byte_buf_is_valid(buf)); if (buf->buffer) { free((void *)buf->buffer); } buf->buffer = NULL; buf->len = 0; buf->capacity = 0; } /** * Tests if the given aws_byte_cursor has at least len bytes remaining. If so, * *buf is advanced by len bytes (incrementing ->ptr and decrementing ->len), * and an aws_byte_cursor referring to the first len bytes of the original *buf * is returned. Otherwise, an aws_byte_cursor with ->ptr = NULL, ->len = 0 is * returned. * * Note that if len is above (SIZE_MAX / 2), this function will also treat it as * a buffer overflow, and return NULL without changing *buf. */ struct aws_byte_cursor aws_byte_cursor_advance(struct aws_byte_cursor *const cursor, const size_t length) { struct aws_byte_cursor rv; if (cursor->len > 2147483647 || length > 2147483647 || length > cursor->len) { rv.ptr = NULL; rv.len = 0; } else { rv.ptr = cursor->ptr; rv.len = length; cursor->ptr += length; cursor->len -= length; } return rv; } bool aws_byte_cursor_read(struct aws_byte_cursor *cur, void *dest, const size_t length) { // AWS_PRECONDITION(aws_byte_cursor_is_valid(cur)); // AWS_PRECONDITION(AWS_MEM_IS_WRITABLE(dest, len)); if (length == 0) { return 1; } struct aws_byte_cursor slice = aws_byte_cursor_advance(cur, length); if (slice.ptr) { memcpy(dest, slice.ptr, length); // AWS_POSTCONDITION(aws_byte_cursor_is_valid(cur)); // AWS_POSTCONDITION(AWS_MEM_IS_READABLE(dest, len)); return 1; } // AWS_POSTCONDITION(aws_byte_cursor_is_valid(cur)); return 0; } /** * Reads a single byte from cursor, placing it in *var. * * On success, returns true and updates the cursor pointer/length accordingly. * If there is insufficient space in the cursor, returns false, leaving the * cursor unchanged. */ bool aws_byte_cursor_read_u8(struct aws_byte_cursor *cur, uint8_t *var) { // AWS_PRECONDITION(aws_byte_cursor_is_valid(cur)); // AWS_PRECONDITION(AWS_MEM_IS_WRITABLE(var, 1)); bool rv = aws_byte_cursor_read(cur, var, 1); // AWS_POSTCONDITION(aws_byte_cursor_is_valid(cur)); return rv; } /** * Reads a 16-bit value in network byte order from cur, and places it in host * byte order into var. * * On success, returns true and updates the cursor pointer/length accordingly. * If there is insufficient space in the cursor, returns false, leaving the * cursor unchanged. */ bool aws_byte_cursor_read_be16(struct aws_byte_cursor *cur, uint16_t *var) { // AWS_PRECONDITION(aws_byte_cursor_is_valid(cur)); // AWS_PRECONDITION(AWS_OBJECT_PTR_IS_WRITABLE(var)); bool rv = aws_byte_cursor_read(cur, var, 2); if (aws_cryptosdk_likely(rv)) { *var = aws_ntoh16(*var); } // AWS_POSTCONDITION(aws_byte_cursor_is_valid(cur)); return rv; } /** * Reads a 32-bit value in network byte order from cur, and places it in host * byte order into var. * * On success, returns true and updates the cursor pointer/length accordingly. * If there is insufficient space in the cursor, returns false, leaving the * cursor unchanged. */ bool aws_byte_cursor_read_be32(struct aws_byte_cursor *cur, uint32_t *var) { // AWS_PRECONDITION(aws_byte_cursor_is_valid(cur)); // AWS_PRECONDITION(AWS_OBJECT_PTR_IS_ WRITABLE(var)); bool rv = aws_byte_cursor_read(cur, var, 4); if (aws_cryptosdk_likely(rv)) { *var = aws_ntoh32(*var); } // AWS_POSTCONDITION(aws_byte_cursor_is_valid(cur)); return rv; } /** * Reads as many bytes from cursor as size of buffer, and copies them to buffer. * * On success, returns true and updates the cursor pointer/length accordingly. * If there is insufficient space in the cursor, returns false, leaving the * cursor unchanged. */ bool aws_byte_cursor_read_and_fill_buffer(struct aws_byte_cursor *cur, struct aws_byte_buf *dest) { // AWS_PRECONDITION(aws_byte_cursor_is_valid(cur)); // AWS_PRECONDITION(aws_byte_buf_is_valid(dest)); if (aws_byte_cursor_read(cur, dest->buffer, dest->capacity)) { dest->len = dest->capacity; // AWS_POSTCONDITION(aws_byte_cursor_is_valid(cur)); // AWS_POSTCONDITION(aws_byte_buf_is_valid(dest)); return true; } // AWS_POSTCONDITION(aws_byte_cursor_is_valid(cur)); // AWS_POSTCONDITION(aws_byte_buf_is_valid(dest)); return false; }
2.953125
3
2024-11-18T21:52:14.554903+00:00
2018-12-06T09:32:40
4ee6df9a0adb0f618abe8a74d259114c62bca6d2
{ "blob_id": "4ee6df9a0adb0f618abe8a74d259114c62bca6d2", "branch_name": "refs/heads/master", "committer_date": "2018-12-06T09:32:40", "content_id": "aac129c81292166674cec13ecc6b947fd8cbe135", "detected_licenses": [ "MIT" ], "directory_id": "37bc077121ea77fba64c51e68e6add1f4c8d509e", "extension": "c", "filename": "queue_linked_list.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 131268360, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1720, "license": "MIT", "license_type": "permissive", "path": "/data_structure/inc/queue_linked_list.c", "provenance": "stackv2-0138.json.gz:154669", "repo_name": "Catboy96/language-learning-practice", "revision_date": "2018-12-06T09:32:40", "revision_id": "4712a069674339c9e85ffaf3717831b2bff89976", "snapshot_id": "9c22eaf3ed7d7392338732b37726a7ca6a0a7bb7", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Catboy96/language-learning-practice/4712a069674339c9e85ffaf3717831b2bff89976/data_structure/inc/queue_linked_list.c", "visit_date": "2020-03-13T20:11:10.368365" }
stackv2
// // Created by CYRO4S <[email protected]> on 2018/10/4. // from: https://www.geeksforgeeks.org/queue-set-2-linked-list-implementation/ // #include "queue_linked_list.h" #include <malloc.h> struct QueueNode* createNode(int key) { struct QueueNode *temp = (struct QueueNode*)malloc(sizeof(struct QueueNode)); temp->key = key; temp->next = NULL; return temp; } LinkedQueue* createQueue() { LinkedQueue* queue = (LinkedQueue*)malloc(sizeof(LinkedQueue)); queue->front = NULL; queue->rear = NULL; return queue; } void enqueue(LinkedQueue* queue, int key) { struct QueueNode *temp = createNode(key); // if queue is empty, // then new node is front and rear both if (queue->rear == NULL) { queue->front = queue->rear = temp; return; } // add the new node at the end of queue and change rear queue->rear->next = temp; queue->rear = temp; } struct QueueNode* dequeue(LinkedQueue* queue) { // queue is empty if (queue->front == NULL) return NULL; // store previous front and move front one node ahead struct QueueNode *temp = queue->front; queue->front = queue->front->next; // if front becomes NULL, then change rear also as NULL if (queue->front == NULL) queue->rear = NULL; return temp; } // main function for testing /* int main(int argc, char* argv[]) { LinkedQueue *queue = createQueue(); enqueue(queue, 10); enqueue(queue, 20); dequeue(queue); dequeue(queue); enqueue(queue, 30); enqueue(queue, 40); enqueue(queue, 50); struct QueueNode *node = dequeue(queue); if (node != NULL) printf("De-queued: %d", node->key); return 0; } */
3.5
4
2024-11-18T21:52:14.617708+00:00
2015-12-24T20:14:42
7433ff5203fbfc229b0687f7a50e1a2f8b95a93c
{ "blob_id": "7433ff5203fbfc229b0687f7a50e1a2f8b95a93c", "branch_name": "refs/heads/master", "committer_date": "2015-12-24T20:14:42", "content_id": "a9f14886a8fd20265f163fe594d5e1b70523950a", "detected_licenses": [ "MIT" ], "directory_id": "31ba1efd8035b9d51d0d8565df20bfb1871a5850", "extension": "c", "filename": "exec.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 52117235, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4530, "license": "MIT", "license_type": "permissive", "path": "/exec.c", "provenance": "stackv2-0138.json.gz:154799", "repo_name": "MokriyYuriy/xv6-mokriy", "revision_date": "2015-12-24T20:14:42", "revision_id": "45f56b52bf1793811b5fb8897e6a75651aeb803f", "snapshot_id": "e2bdbc5e0e4b91ed14da76b76408f9d91b333b66", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/MokriyYuriy/xv6-mokriy/45f56b52bf1793811b5fb8897e6a75651aeb803f/exec.c", "visit_date": "2021-01-10T16:26:20.377151" }
stackv2
#include "types.h" #include "param.h" #include "memlayout.h" #include "mmu.h" #include "proc.h" #include "defs.h" #include "x86.h" #include "elf.h" #define RECURSION_LIMIT 5 static int cleverexec(char *, char **, int); static char checkshebang(struct inode *); static int scriptexec(struct inode *, char *, char **, int); int exec(char *path, char **argv) { return cleverexec(path, argv, RECURSION_LIMIT); } static int cleverexec(char *path, char **argv, int recursion_limit) { char *s, *last; int i, off; uint argc, sz, sp, ustack[3+MAXARG+1]; struct elfhdr elf; struct inode *ip; struct proghdr ph; pde_t *pgdir, *oldpgdir; if(!recursion_limit) { return -1; } begin_op(); if((ip = namei(path)) == 0){ end_op(); return -1; } ilock(ip); pgdir = 0; // Check ELF header if(readi(ip, (char*)&elf, 0, sizeof(elf)) < sizeof(elf)) goto script; if(elf.magic != ELF_MAGIC) goto script; if((pgdir = setupkvm()) == 0) goto bad; // Load program into memory. sz = 0; for(i=0, off=elf.phoff; i<elf.phnum; i++, off+=sizeof(ph)){ if(readi(ip, (char*)&ph, off, sizeof(ph)) != sizeof(ph)) goto bad; if(ph.type != ELF_PROG_LOAD) continue; if(ph.memsz < ph.filesz) goto bad; if((sz = allocuvm(pgdir, sz, ph.vaddr + ph.memsz)) == 0) goto bad; if(loaduvm(pgdir, (char*)ph.vaddr, ip, ph.off, ph.filesz) < 0) goto bad; } iunlockput(ip); end_op(); ip = 0; // Allocate two pages at the next page boundary. // Make the first inaccessible. Use the second as the user stack. sz = PGROUNDUP(sz); if((sz = allocuvm(pgdir, sz, sz + 2*PGSIZE)) == 0) goto bad; clearpteu(pgdir, (char*)(sz - 2*PGSIZE)); sp = sz; // Push argument strings, prepare rest of stack in ustack. for(argc = 0; argv[argc]; argc++) { if(argc >= MAXARG) goto bad; sp = (sp - (strlen(argv[argc]) + 1)) & ~3; if(copyout(pgdir, sp, argv[argc], strlen(argv[argc]) + 1) < 0) goto bad; ustack[3+argc] = sp; } ustack[3+argc] = 0; ustack[0] = 0xffffffff; // fake return PC ustack[1] = argc; ustack[2] = sp - (argc+1)*4; // argv pointer sp -= (3+argc+1) * 4; if(copyout(pgdir, sp, ustack, (3+argc+1)*4) < 0) goto bad; // Save program name for debugging. for(last=s=path; *s; s++) if(*s == '/') last = s+1; safestrcpy(proc->name, last, sizeof(proc->name)); // Commit to the user image. oldpgdir = proc->pgdir; proc->pgdir = pgdir; proc->sz = sz; proc->tf->eip = elf.entry; // main proc->tf->esp = sp; switchuvm(proc); freevm(oldpgdir); return 0; bad: if(pgdir) freevm(pgdir); if(ip){ iunlockput(ip); end_op(); } return -1; script: return scriptexec(ip, path, argv, recursion_limit); } char checkshebang(struct inode *ip) { char fstr[2]; int ln = readi(ip, fstr, 0, 2); return ln >= 2 && fstr[0] == '#' && fstr[1] == '!'; } static int getaddargv(char *interpreter_path, char **newargv) { int curarg = 0, curlen = 0, i, firstnonspace = 0; for(i = 0; interpreter_path[i]; i++) { if(interpreter_path[i] == ' ') { if(curlen) { interpreter_path[i] = 0; newargv[curarg++] = interpreter_path + firstnonspace; curlen = 0; if(curarg == MAXARG){ return MAXARG; } } } else { if(curlen == 0){ firstnonspace = i; } curlen++; } } if(curlen){ newargv[curarg++] = interpreter_path + firstnonspace; } return curarg; } static int scriptexec(struct inode *ip, char *pathname, char **argv, int recursion_limit) { char *interpreter_path = 0, *addargv[MAXARG]; int ln, argc, i, res, size, addargc; if(!checkshebang(ip)){ goto bad; } interpreter_path = kalloc(); size = readi(ip, interpreter_path, 2, PGSIZE); iunlockput(ip); end_op(); ip = 0; for(ln = 0; ln < size && interpreter_path[ln] != '\n'; ln++) {} if(ln == size){ goto bad; } interpreter_path[ln] = 0; for(argc = 0; argv[argc]; argc++) {} addargc = getaddargv(interpreter_path, addargv); if(!addargc || addargc + argc >= MAXARG){ goto bad; } for(i = argc; i >= 0; i--) { argv[i + addargc] = argv[i]; } for(i = 0; i < addargc; i++) { argv[i] = addargv[i]; } pathname = argv[0]; res = cleverexec(pathname, argv, recursion_limit - 1); kfree(interpreter_path); return res; bad: if(ip){ iunlockput(ip); end_op(); } if(interpreter_path){ kfree(interpreter_path); } return -1; }
2.421875
2
2024-11-18T21:52:14.693214+00:00
2018-03-22T02:13:11
51495e6a7de1807451378a698d4ce84b1e63cdea
{ "blob_id": "51495e6a7de1807451378a698d4ce84b1e63cdea", "branch_name": "refs/heads/master", "committer_date": "2018-03-22T02:13:11", "content_id": "3a1510fc2356ba50c49a2be35ea0295cabdd0027", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "fa4deb7f4cbfc8083fbacd5ccdd5137850a76fe3", "extension": "c", "filename": "main_Z4_0.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": 3369, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/flexcan_transmit/flexcan_transmit_Z4_0/src/main_Z4_0.c", "provenance": "stackv2-0138.json.gz:154928", "repo_name": "cooper1025/mpc5748G_examples", "revision_date": "2018-03-22T02:13:11", "revision_id": "6ba2fd8cfa312d59036284e368a3cca2aba7df4b", "snapshot_id": "493b77a4990c8b6bb1e1e40f37af10c7fab2b258", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/cooper1025/mpc5748G_examples/6ba2fd8cfa312d59036284e368a3cca2aba7df4b/flexcan_transmit/flexcan_transmit_Z4_0/src/main_Z4_0.c", "visit_date": "2020-09-08T01:44:30.432641" }
stackv2
/*****************************************************************************/ /* FILE NAME: main_z4_0.c COPYRIGHT (c) NXP Semiconductors 2016 */ /* All Rights Reserved */ /* PLATFORM: DEVKIT-MPC5748G */ /* DESCRIPTION: Main C program for core 0 (e200z4a) to call FlexCAN functions*/ /* Project Continuously transmits the message "Hello" to the */ /* CAN0 (P5) port. */ /* Can be used with receive project on another board. */ /* Or observe the waveforms on pins of port P5 on board. */ /* */ /*****************************************************************************/ /* REV AUTHOR DATE DESCRIPTION OF CHANGE */ /* --- ----------- ---------- --------------------- */ /* 1.0 S Mihalik 19 Feb 2014 Initial Version */ /* 1.1 S Mihalik 12 Feb 2015 Removed unrequired SIUL ME_PCTL code */ /* 1.1 K Shah 01 Mar 2016 Ported to S23DS */ /*****************************************************************************/ #include "derivative.h" /* include peripheral declarations */ #include "can.h" #include "mode.h" #define KEY_VALUE1 0x5AF0ul #define KEY_VALUE2 0xA50Ful extern void xcptn_xmpl(void); void peri_clock_gating (void); /* Configure gating/enabling peripheral(CAN) clocks */ void hw_init(void) { #if defined(DEBUG_SECONDARY_CORES) uint32_t mctl = MC_ME.MCTL.R; #if defined(TURN_ON_CPU1) /* enable core 1 in all modes */ MC_ME.CCTL[2].R = 0x00FE; /* Set Start address for core 1: Will reset and start */ MC_ME.CADDR[2].R = 0x11d0000 | 0x1; #endif #if defined(TURN_ON_CPU2) /* enable core 2 in all modes */ MC_ME.CCTL[3].R = 0x00FE; /* Set Start address for core 2: Will reset and start */ MC_ME.CADDR[3].R = 0x13a0000 | 0x1; #endif MC_ME.MCTL.R = (mctl & 0xffff0000ul) | KEY_VALUE1; MC_ME.MCTL.R = mctl; /* key value 2 always from MCTL */ #endif /* defined(DEBUG_SECONDARY_CORES) */ } __attribute__ ((section(".text"))) /************************************ Main ***********************************/ int main(void) { uint32_t CAN_msg_count = 0; xcptn_xmpl (); /* Configure and Enable Interrupts */ peri_clock_gating(); /* Configure gating/enabling peripheral clocks(CANs) for modes*/ /* Configuration occurs after mode transition */ system160mhz(); /* sysclk=160MHz, dividers configured, mode trans*/ initCAN_0_tx(); /* Initialize FlexCAN 0 & one of its buffers for transmit*/ while (1) { TransmitMsg(); /* Transmit one message from a FlexCAN 0 buffer */ CAN_msg_count++; /* Increment CAN message counter */ SIUL2.MSCR[PA10].B.OBE = 1; /* Pad PA10 (10): OBE=1. On EVB enable low DS4 LED */ } return 0; } /******************************End of Main ***********************************/ void peri_clock_gating (void) { /* Configure gating/enabling peripheral clocks(CANs) for modes*/ MC_ME.RUN_PC[0].R = 0x00000000; /* Gate off clock for all RUN modes */ MC_ME.RUN_PC[1].R = 0x000000FE; /* configures peripheral clock for all RUN modes */ MC_ME.PCTL[70].B.RUN_CFG = 0x1; /* FlexCAN 0: select peripheral configuration RUN_PC[1] */ }
2.234375
2
2024-11-18T21:52:14.802617+00:00
2018-04-10T08:04:05
c1e2a2bfa95bb9a9cf89279e2a3395e47443a37b
{ "blob_id": "c1e2a2bfa95bb9a9cf89279e2a3395e47443a37b", "branch_name": "refs/heads/master", "committer_date": "2018-04-10T08:04:05", "content_id": "8e86b5822a5a6671f13c37366ebf5765750932a3", "detected_licenses": [ "MIT" ], "directory_id": "4e7ae8fcc98c6aecf3658c48cbfb262349389ad8", "extension": "c", "filename": "screen.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 91136672, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 573, "license": "MIT", "license_type": "permissive", "path": "/src/screen.c", "provenance": "stackv2-0138.json.gz:155056", "repo_name": "Keyaku/raspicture", "revision_date": "2018-04-10T08:04:05", "revision_id": "7664c78a3e5dca34452591a4a84e21a953645cb8", "snapshot_id": "deaf8033df33159bcb5e42e12bc542e6cf792a1a", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Keyaku/raspicture/7664c78a3e5dca34452591a4a84e21a953645cb8/src/screen.c", "visit_date": "2020-12-30T15:22:27.411600" }
stackv2
#include <stdio.h> #include "raspicture.h" #define DEFAULT_SCREEN 0 int init_dispmanx(DISPMANX_STATE_T *state) { int32_t success = 0; success = graphics_get_display_size( DEFAULT_SCREEN, &state->screen_width, &state->screen_height ); if (success < 0) { PRINT_ERR("Couldn't get display size. Make sure /usr/bin/tvservice is on.\n"); return -1; } printf("Created screen: %dx%d\n", state->screen_width, state->screen_height); return success; } int destroy_dispmanx(DISPMANX_STATE_T *state) { return 0; // FIXME: implement Dispmanx unloader }
2.28125
2
2024-11-18T21:52:15.032979+00:00
2018-05-20T20:06:55
40e6579cd6a6d9158abd813e515047e374ac0418
{ "blob_id": "40e6579cd6a6d9158abd813e515047e374ac0418", "branch_name": "refs/heads/master", "committer_date": "2018-05-20T20:06:55", "content_id": "e5be96a14690eaa5147e3b9552602c4b3df087c9", "detected_licenses": [ "Apache-2.0" ], "directory_id": "d023a4214e796ee137de2fe2232bc82bf1031040", "extension": "c", "filename": "scheduler_01.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 134182636, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 259, "license": "Apache-2.0", "license_type": "permissive", "path": "/ATtiny13/scheduler_01.c", "provenance": "stackv2-0138.json.gz:155314", "repo_name": "dr-ecker/AVRProgs", "revision_date": "2018-05-20T20:06:55", "revision_id": "45fd02dd25d4e1133a89be07aea176c3115fac5f", "snapshot_id": "8ac5b6c8e5e3b7ae33a86e56b1001843284ba3c7", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/dr-ecker/AVRProgs/45fd02dd25d4e1133a89be07aea176c3115fac5f/ATtiny13/scheduler_01.c", "visit_date": "2020-03-18T02:16:31.326471" }
stackv2
#include <avr/io.h> #define F_CPU 120000 #include <util/delay.h> int main (void) { DDRB = 0x1F; //set PB.0-4 as output pins TCCR0B=0x02; //Set Prescaler to 8 while (1) { if(TCNT0==0) { PORTB^=0x1F; //Toggle all outputs } } }
2.09375
2
2024-11-18T21:52:15.629223+00:00
2015-08-21T12:11:06
b087aa5e3207ef2d88fe1e64244a608a21428312
{ "blob_id": "b087aa5e3207ef2d88fe1e64244a608a21428312", "branch_name": "refs/heads/master", "committer_date": "2015-08-21T12:11:06", "content_id": "2f80e0e8dccb176e11794b753208e3dcbd7eb5f4", "detected_licenses": [ "MIT" ], "directory_id": "fa2afc6b8dd7d65ebbddd96d136358dd9cf80f2e", "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": 41152397, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1937, "license": "MIT", "license_type": "permissive", "path": "/src/main.c", "provenance": "stackv2-0138.json.gz:155969", "repo_name": "Brandon2255p/BMP180-STM32F0", "revision_date": "2015-08-21T12:11:06", "revision_id": "0b373ceae7b0ab5d31284ec8811f0c368da059f5", "snapshot_id": "be41cf11fec918b3efed05b2e43bb098e92192e2", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/Brandon2255p/BMP180-STM32F0/0b373ceae7b0ab5d31284ec8811f0c368da059f5/src/main.c", "visit_date": "2020-06-07T19:37:07.334047" }
stackv2
/* ** ** Main.c ** ** **********************************************************************/ /* Last committed: $Revision: 00 $ Last changed by: $Author: $ Last changed date: $Date: $ ID: $Id: $ **********************************************************************/ #include "stm32f0xx_conf.h" #include <stdio.h> #include "BMP180.h" struct bmp180_t Sensor1; int main(void) { uint32_t i; uint8_t data1, data2; uint16_t data16=0; int32_t pressure1, temperature; char debugString[1000]=""; ///PORT A for debugging via UART //USART 1 and 2 RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOA, ENABLE); GPIO_PinAFConfig(GPIOA, GPIO_PinSource0, GPIO_AF_1);//CTS2 GPIO_PinAFConfig(GPIOA, GPIO_PinSource1, GPIO_AF_1);//RTS2 GPIO_PinAFConfig(GPIOA, GPIO_PinSource2, GPIO_AF_1);//TX2 GPIO_PinAFConfig(GPIOA, GPIO_PinSource3, GPIO_AF_1);//RX2 GPIO_PinAFConfig(GPIOA, GPIO_PinSource6, GPIO_AF_1); // TIM3_CH1 GPIO_PinAFConfig(GPIOA, GPIO_PinSource9, GPIO_AF_1);//TX1 GPIO_PinAFConfig(GPIOA, GPIO_PinSource10, GPIO_AF_1);//RX1 GPIO_InitTypeDef GPIO_InitStruct; GPIO_InitStruct.GPIO_Pin =GPIO_Pin_0|GPIO_Pin_1|GPIO_Pin_2|GPIO_Pin_3|GPIO_Pin_6|GPIO_Pin_9|GPIO_Pin_10; GPIO_InitStruct.GPIO_Mode = GPIO_Mode_AF; GPIO_InitStruct.GPIO_Speed = GPIO_Speed_10MHz; GPIO_InitStruct.GPIO_OType = GPIO_OType_PP; GPIO_InitStruct.GPIO_PuPd = GPIO_PuPd_NOPULL; GPIO_Init(GPIOA, &GPIO_InitStruct); debugInit(); I2CInit(); debugSend("Mellow world\n"); read8(0xD0, &data2); _printfU("Sensor ID: ", data2); bmp180_get_calib_param(&Sensor1); getTemperature(&temperature, &Sensor1); _printfLngS("Temperature is ", (int32_t)temperature); getPressure(&pressure1, &Sensor1); _printfLngS("Pressure is ", (int32_t)pressure1); while(1) { } }
2.421875
2
2024-11-18T21:52:15.687835+00:00
2019-06-19T18:13:44
079e59364dcb5f616a37e5e3673ebccda213513c
{ "blob_id": "079e59364dcb5f616a37e5e3673ebccda213513c", "branch_name": "refs/heads/master", "committer_date": "2019-06-19T23:03:30", "content_id": "8a7c57c587cf00ef36b6455dea7bca6007733c0c", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "98c49475f1093066d8f4aab4a45b11d8a835d727", "extension": "c", "filename": "2gbb.c", "fork_events_count": 0, "gha_created_at": "2019-06-24T11:41:08", "gha_event_created_at": "2019-06-24T11:41:09", "gha_language": null, "gha_license_id": "NOASSERTION", "github_id": 193494168, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3300, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/firmware/2lib/2gbb.c", "provenance": "stackv2-0138.json.gz:156097", "repo_name": "9elements/vboot", "revision_date": "2019-06-19T18:13:44", "revision_id": "b021a9619722a397de9910bd0422b2e7c6ebb7f0", "snapshot_id": "0a05bf94c6c50ef959933590df52f1f74b0efbba", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/9elements/vboot/b021a9619722a397de9910bd0422b2e7c6ebb7f0/firmware/2lib/2gbb.c", "visit_date": "2020-06-09T19:35:33.947960" }
stackv2
/* Copyright 2019 The Chromium OS Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. * * GBB accessor functions. */ #include "2common.h" #include "2misc.h" static int vb2_gbb_read_key(struct vb2_context *ctx, uint32_t offset, uint32_t *size, struct vb2_packed_key **keyp, struct vb2_workbuf *wb) { struct vb2_workbuf wblocal = *wb; int rv; /* Check offset and size. */ if (offset < sizeof(struct vb2_gbb_header)) return VB2_ERROR_GBB_INVALID; if (*size < sizeof(**keyp)) return VB2_ERROR_GBB_INVALID; /* GBB header might be padded. Retrieve the vb2_packed_key header so we can find out what the real size is. */ *keyp = vb2_workbuf_alloc(&wblocal, sizeof(**keyp)); if (!*keyp) return VB2_ERROR_GBB_WORKBUF; rv = vb2ex_read_resource(ctx, VB2_RES_GBB, offset, *keyp, sizeof(**keyp)); if (rv) return rv; rv = vb2_verify_packed_key_inside(*keyp, *size, *keyp); if (rv) return rv; /* Deal with a zero-size key (used in testing). */ *size = (*keyp)->key_offset + (*keyp)->key_size; if (*size < sizeof(**keyp)) *size = sizeof(**keyp); /* Now that we know the real size of the key, retrieve the key data, and write it on the workbuf, directly after vb2_packed_key. */ *keyp = vb2_workbuf_realloc(&wblocal, sizeof(**keyp), *size); if (!*keyp) return VB2_ERROR_GBB_WORKBUF; rv = vb2ex_read_resource(ctx, VB2_RES_GBB, offset + sizeof(**keyp), (void *)*keyp + sizeof(**keyp), *size - sizeof(**keyp)); if (!rv) *wb = wblocal; return rv; } int vb2_gbb_read_root_key(struct vb2_context *ctx, struct vb2_packed_key **keyp, uint32_t *size, struct vb2_workbuf *wb) { struct vb2_gbb_header *gbb = vb2_get_gbb(ctx); uint32_t size_in = gbb->rootkey_size; int ret = vb2_gbb_read_key(ctx, gbb->rootkey_offset, &size_in, keyp, wb); if (size) *size = size_in; return ret; } int vb2_gbb_read_recovery_key(struct vb2_context *ctx, struct vb2_packed_key **keyp, uint32_t *size, struct vb2_workbuf *wb) { struct vb2_gbb_header *gbb = vb2_get_gbb(ctx); uint32_t size_in = gbb->recovery_key_size; int ret = vb2_gbb_read_key(ctx, gbb->recovery_key_offset, &size_in, keyp, wb); if (size) *size = size_in; return ret; } int vb2api_gbb_read_hwid(struct vb2_context *ctx, char *hwid, uint32_t *size) { struct vb2_gbb_header *gbb = vb2_get_gbb(ctx); uint32_t i; int ret; if (gbb->hwid_size == 0) { VB2_DEBUG("invalid HWID size %d\n", gbb->hwid_size); return VB2_ERROR_GBB_INVALID; } if (*size > VB2_GBB_HWID_MAX_SIZE) *size = VB2_GBB_HWID_MAX_SIZE; if (*size > gbb->hwid_size) *size = gbb->hwid_size; ret = vb2ex_read_resource(ctx, VB2_RES_GBB, gbb->hwid_offset, hwid, *size); if (ret) { VB2_DEBUG("read resource failure: %d\n", ret); return ret; } /* Count HWID size, and ensure that it fits in the given buffer. */ for (i = 0; i < *size; i++) { if (hwid[i] == '\0') { *size = i + 1; break; } } if (hwid[*size - 1] != '\0') return VB2_ERROR_INVALID_PARAMETER; return VB2_SUCCESS; } vb2_gbb_flags_t vb2api_gbb_get_flags(struct vb2_context *ctx) { struct vb2_gbb_header *gbb = vb2_get_gbb(ctx); return gbb->flags; }
2.296875
2
2024-11-18T21:52:16.224872+00:00
2023-04-20T08:33:55
3d87b626e3673b28c8c9a92e9a9a6e9be8b14055
{ "blob_id": "3d87b626e3673b28c8c9a92e9a9a6e9be8b14055", "branch_name": "refs/heads/master", "committer_date": "2023-04-20T08:33:55", "content_id": "dd25e5e1d3fbff0010d30964778ddca900128962", "detected_licenses": [ "MIT" ], "directory_id": "5409096061379d97b455896e02d9701dcf71868c", "extension": "c", "filename": "putaogan.c", "fork_events_count": 13, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 164323051, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1328, "license": "MIT", "license_type": "permissive", "path": "/clone/food/putaogan.c", "provenance": "stackv2-0138.json.gz:156355", "repo_name": "ttwings/WuXiaAndJiangHu_Godot", "revision_date": "2023-04-20T08:33:55", "revision_id": "997945b514c7a10527258e03225f4d0aa5cb0e9c", "snapshot_id": "610e2ccbe65a6f2d639dec3a5924eaeafc31e6ea", "src_encoding": "UTF-8", "star_events_count": 39, "url": "https://raw.githubusercontent.com/ttwings/WuXiaAndJiangHu_Godot/997945b514c7a10527258e03225f4d0aa5cb0e9c/clone/food/putaogan.c", "visit_date": "2023-05-04T21:38:33.451028" }
stackv2
// 神话世界·西游记·版本4.50 /* <SecCrypt CPL V3R05> */ inherit ITEM; void init(); void eat(); void create() { set_name("葡萄干", ({"putao gan", "gan"})); set_weight(300); if (clonep()) set_default_object(__FILE__); else { set("long", "葡萄干是西北边疆的特产,吃起来香甜可口.\n"); set("unit", "把"); set("value", 60); set("food_remaining", 4); set("food_supply", 10); } } void init() { add_action("do_chi", "eat"); } int do_chi(string arg) { if (!this_object()->id(arg)) return 0; if (this_player()->is_busy()) return notify_fail("你上一个动作还没有完成。\n"); if (!arg) return notify_fail("你要吃什么?\n"); if ((int)this_player()->query("food") >= (int)this_player()->max_food_capacity()) return notify_fail("你已经吃太饱了,再也塞不下任何东西了。\n"); message_vision("$N从兜里掏出把葡萄干,一颗一颗的塞到嘴里,\n一颗,一颗,又一颗...\n", this_player()); this_player()->add("food", 30); destruct(this_object()); return 1; }
2.296875
2
2024-11-18T21:52:16.299117+00:00
2015-12-15T23:53:21
17f9cbcb41682347bd8d3610656086a22f4a587a
{ "blob_id": "17f9cbcb41682347bd8d3610656086a22f4a587a", "branch_name": "refs/heads/master", "committer_date": "2015-12-15T23:53:21", "content_id": "100bacc267c9ee3bd4d30165dfb41966ce9c7ee2", "detected_licenses": [ "CC0-1.0" ], "directory_id": "5518f5a958b10ae9459fa5792d1a0b77c4c0a62f", "extension": "c", "filename": "motor.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 48068495, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 896, "license": "CC0-1.0", "license_type": "permissive", "path": "/motor.c", "provenance": "stackv2-0138.json.gz:156483", "repo_name": "Bytewerk/telepraesenzpanzer", "revision_date": "2015-12-15T23:53:21", "revision_id": "e79901cc82f3c8c4d19f974633f8b54883039dbf", "snapshot_id": "5f4a8290cc1f932211b6136be2bc332df65af959", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/Bytewerk/telepraesenzpanzer/e79901cc82f3c8c4d19f974633f8b54883039dbf/motor.c", "visit_date": "2021-01-13T01:00:43.097673" }
stackv2
#include <avr/io.h> #include "motor.h" void motor_init( void ) { PORTD &= ~(1<<PD4); PORTD &= ~(1<<PD5); PORTC &= ~(1<<PC2); PORTC &= ~(1<<PC3); DDRD |= (1<<PD4); // left motor DDRD |= (1<<PD5); // right motor DDRC |= (1<<PC2); // left motor direction output DDRC |= (1<<PC3); // right motor direction output } void motor_setDir( motor_e id, dir_e direction ) { if( id == M_LEFT ) { if( direction == M_FORWARD ) { PORTC &= ~(1<<PC2); } else { PORTC |= (1<<PC2); } } else if( id == M_RIGHT ) { if( direction == M_FORWARD ) { PORTC &= ~(1<<PC3); } else { PORTC |= (1<<PC3); } } } void motor_start( motor_e id ) { if( id == M_LEFT ) { PORTD |= (1<<PD4); } else if( id == M_RIGHT ) { PORTD |= (1<<PD5); } } void motor_stop( motor_e id ) { if( id == M_LEFT ) { PORTD &= ~(1<<PD4); } else if( id == M_RIGHT ) { PORTD &= ~(1<<PD5); } }
2.703125
3
2024-11-18T21:52:16.352841+00:00
2013-11-07T00:39:26
0cbbdb25fb758dd54940c2eabe103f73b996cb89
{ "blob_id": "0cbbdb25fb758dd54940c2eabe103f73b996cb89", "branch_name": "refs/heads/master", "committer_date": "2013-11-28T08:50:36", "content_id": "254d76365be9e6384a71c5ffbcbdfe5658a54cf4", "detected_licenses": [ "MIT" ], "directory_id": "6437a0e48a9d4b51d8f1910d171b037892e06747", "extension": "c", "filename": "responses.c", "fork_events_count": 1, "gha_created_at": "2012-06-13T14:44:04", "gha_event_created_at": "2013-11-07T01:07:03", "gha_language": "C", "gha_license_id": null, "github_id": 4652135, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2390, "license": "MIT", "license_type": "permissive", "path": "/src/responses.c", "provenance": "stackv2-0138.json.gz:156611", "repo_name": "mil/foo-wm", "revision_date": "2013-11-07T00:39:26", "revision_id": "a9df24bebc6e2299396a962e7ea4c8a35ea09b6d", "snapshot_id": "8f6a587e1265977b41ec6eca17cf6454a30d5e27", "src_encoding": "UTF-8", "star_events_count": 12, "url": "https://raw.githubusercontent.com/mil/foo-wm/a9df24bebc6e2299396a962e7ea4c8a35ea09b6d/src/responses.c", "visit_date": "2021-01-20T07:48:22.986405" }
stackv2
#include <string.h> #include <stdlib.h> #include <stdio.h> #include "foo-wm.h" #include "util.h" #include "tree.h" #include "responses.h" char * jsonMarks(void) { char * marksResponse = malloc(1024); sprintf(marksResponse, "{\"marks\":["); Mark *n = NULL; for(n = markTail; n; n = n -> previous) { sprintf(marksResponse, "%s%s\"%s\"", marksResponse, n != markTail ? "," : "", n -> name ); } sprintf(marksResponse, "%s]}", marksResponse); realloc(marksResponse, bytesUntilNull(marksResponse)); return marksResponse; } char * jsonTree(Node * node, int level) { if (!node) return "Foo"; char *buffer = malloc(5120), *label = "", *nestString = ""; /* Recursivly Crawl Children */ if (!isClient(node)) { nestString = malloc(5120); Node *n = NULL; int c = 0; int last = -1; for (n = node -> child; n; n = n -> next, last++) { } n = NULL; for (n = node -> child; n; n = n -> next, c++) { char *crawlResult = malloc(5120); crawlResult = jsonTree(n, level + 1); sprintf(nestString, "%s%s%s", c == 0 ? "" : nestString, crawlResult, c != last ? "," : ""); free(crawlResult); } } /* Determine Label for sprintf */ if (!isClient(node)) { switch (node -> layout) { case VERTICAL : label = ",\"layout\":\"vertical\""; break; case HORIZONTAL : label = ",\"layout\":\"horizontal\""; break; case GRID : label = ",\"layout\":\"grid\""; break; case MAX : label = ",\"layout\":\"max\""; break; case FLOAT : label = ",\"layout\":\"float\""; break; } } /* Print to the buffer */ sprintf(buffer, /* Type (Pointer) (?Layout) (?R/V/F) (?ChildFocus) */ "{ \"node\":\"%p\",\"id\":\"%p\",\"type\":\"%s\"%s%s%s%s,\"focus\":\"%p\",\"children\":[%s]}", node, node -> window, isClient(node) ? "client" : "container", label, node == rootNode ? ",\"root\":\"true\"" : "", node == focusedNode ? ",\"focus\":\"true\"" : "", node == viewNode ? ",\"view\":\"true\"" : "", node -> focus ? node -> focus : "", nestString ); /* If it was a container, we malloc'd room for nestString */ if (sizeof(nestString) > sizeof(char*)) free(nestString); realloc(buffer, bytesUntilNull(buffer)); return buffer; }
2.46875
2
2024-11-18T21:52:17.277401+00:00
2019-05-23T16:37:53
3b0e05e1b51488f34d0498a7b2463c2c43636a71
{ "blob_id": "3b0e05e1b51488f34d0498a7b2463c2c43636a71", "branch_name": "refs/heads/master", "committer_date": "2019-05-23T16:37:53", "content_id": "6384e6df097de4609bc7b833bd33aa67470351fb", "detected_licenses": [ "MIT" ], "directory_id": "7af24000854a3442229abf0e393f859ce265cbcc", "extension": "h", "filename": "binbag.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": 6123, "license": "MIT", "license_type": "permissive", "path": "/src/binbag.h", "provenance": "stackv2-0138.json.gz:157391", "repo_name": "roberttco/Restfully", "revision_date": "2019-05-23T16:37:53", "revision_id": "aa96b0557675379f72e42023c00e4205956ebf03", "snapshot_id": "ebabe1a530f16931e1ad663c9f975753522f1619", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/roberttco/Restfully/aa96b0557675379f72e42023c00e4205956ebf03/src/binbag.h", "visit_date": "2022-12-15T12:41:52.376819" }
stackv2
/// \file /// \brief Efficiently stores a growing array of character or binary strings (AKA string table) #ifndef ANALYTICSAPI_BINBAG_H #define ANALYTICSAPI_BINBAG_H #include "ds-config.h" #include <stdint.h> #include <cstdlib> #ifdef __cplusplus extern "C" { #endif // split string flags #define SF_NONE 0 #define SF_IGNORE_EMPTY 1 typedef struct _binbag { // allocated memory buffer range // We only allocate a single buffer and then grow as needed. Strings are inserted into the buffer consecutively. // An array of pointers is kept where each element points into this buffer for each string inserted. This array // is stored at the end of the allocated memory and thus the insertion for this array like a heap grows down (decrements). // When the buffer grows, the pointer array is copied to the new end of the buffer. // Memory layout: // [begin tail ][element 3 | 2 | 1 | 0 ](end) char *begin; char *end; // insertion point for new strings char *tail; // the start of the array of pointers to each string const char **elements; // parameters of the binbag double growth_rate; // the number of growths we did size_t growths; } binbag; /// \brief Allocate a new empty binbag DS_EXPORT binbag *binbag_create(size_t capacity_bytes, double growth_rate); DS_EXPORT binbag* binbag_split_string(int seperator, unsigned long flags, const char* str); //binbag* binbag_create_from_array(const char** arr, size_t count, double fill_space, double growth_rate); DS_EXPORT void binbag_free(binbag *bb); DS_EXPORT size_t binbag_resize(binbag *bb, size_t capacity); /// \brief Returns the bytes used for all the strings combined DS_EXPORT size_t binbag_byte_length(binbag *bb); DS_EXPORT size_t binbag_count(binbag* bb); /// \brief Returns the character capacity of the binbag not including space used for elements DS_EXPORT size_t binbag_capacity(binbag *bb); DS_EXPORT size_t binbag_free_space(binbag *bb); DS_EXPORT long binbag_insert(binbag *bb, const char *str); DS_EXPORT long binbag_insertn(binbag *bb, const char *str, int length); /// \brief Insert a string if not exists /// This function is the same as binbag_insert() but first it checks to see if it already exists in the binbag. If so, /// then the existing element is returned. DS_EXPORT long binbag_insert_distinct(binbag* bb, const char* str, int (*compar)(const char*,const char*)); DS_EXPORT long binbag_insert_distinct_n(binbag* bb, const char* str, size_t n, int (*compar)(const char*,const char*, size_t n)); DS_EXPORT void binbag_inplace_reverse(binbag *bb); //const unsigned char* binbag_binary_insert(const unsigned char* str, size_t len); DS_EXPORT const char *binbag_get(binbag *bb, long idx); // get the length of the string at the given index DS_EXPORT int binbag_strlen(binbag *bb, long idx); //const unsigned char* binbag_binary_get(int idx, size_t* len_out); /// \brief Find the ordinal index of the given string using the supplied comparison function (works with strcmp, strcasecmp, etc) DS_EXPORT long binbag_find(binbag *bb, const char* match, int (*compar)(const char*,const char*)); /// \brief Find the ordinal index of the given string DS_EXPORT long binbag_find_case(binbag *bb, const char* match); /// \brief Find the ordinal index of the given string using a case insensitive comparison DS_EXPORT long binbag_find_nocase(binbag *bb, const char* match); /// \brief Find the ordinal index of the given string with length DS_EXPORT long binbag_find_case_n(binbag *bb, const char* match, size_t n); /// \brief Find the ordinal index of the given string using a case insensitive comparison with length DS_EXPORT long binbag_find_nocase_n(binbag *bb, const char* match, size_t n); /// \brief Find the ordinal index of the given string using the supplied comparison function with length (works with strcmp, strcasecmp, etc) long binbag_find_n(binbag *bb, const char* match, size_t n, int (*compar)(const char*,const char*, size_t n)); /// \brief Compare function used to sort in ascending order DS_EXPORT int binbag_element_sort_asc (const void * _lhs, const void * _rhs); /// \brief Compare function used to sort in descending order DS_EXPORT int binbag_element_sort_desc (const void * _lhs, const void * _rhs); /// \brief Sort the binbag. /// You can use one of the existing sort routines for standard character sorting, binbag_element_sort_asc or binbag_element_sort_desc. DS_EXPORT binbag* binbag_sort(binbag *bb, int (*compar)(const void*,const void*)); /// \brief Sort the values and reduce memory usage by aliasing duplicates to the same string memory. /// This method does not eliminate duplicates, it keeps duplicates in the string table but after reduction these duplicates /// will point to the same C string in memory. This is useful for having semi-static lookup tables where duplicates are /// desired but you also want to save memory. //binbag* binbag_flyweight_reduce(binbag *bb, int (*compar)(const void*,const void*)); - not yet implemented /// \brief Reduce the binbag to only distinct string values. /// Values will also be sorted using binbag_element_sort_asc. DS_EXPORT binbag* binbag_distinct(binbag *bb); /// \brief Reduce the binbag to only distinct string values. /// Values will also be sorted. You can use one of the existing sort routines for standard character sorting, binbag_element_sort_asc or binbag_element_sort_desc. DS_EXPORT binbag* binbag_sort_distinct(binbag *bb, int (*compar)(const void*,const void*)); DS_EXPORT void binbag_debug_print(binbag* bb); DS_EXPORT const char **binbag_begin_iterator(binbag *bb); DS_EXPORT const char **binbag_end_iterator(binbag *bb); /// \brief This is the function that prints a string to the default console. /// This function prints using fputs(s, stdout) but it is given weak linking so you can override this function if you /// want to redirect debug print messages to another destination. int default_binbag_print(const char* str) __attribute__((weak)); #ifdef __cplusplus } #endif #endif //ANALYTICSAPI_BINBAG_H
2.671875
3
2024-11-18T21:52:17.359476+00:00
2022-08-22T19:03:28
90566188f004f88d3f6019e3411359b05575ef2f
{ "blob_id": "90566188f004f88d3f6019e3411359b05575ef2f", "branch_name": "refs/heads/master", "committer_date": "2022-08-22T19:03:28", "content_id": "091a49afd86666c7e0a1aa9ea58c1922610fd3fa", "detected_licenses": [ "Unlicense", "Zlib" ], "directory_id": "d91637e9d05bd0f7ccc44741abbbec21955b5010", "extension": "c", "filename": "errf.c", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 233625256, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1259, "license": "Unlicense,Zlib", "license_type": "permissive", "path": "/source/3ds/errf.c", "provenance": "stackv2-0138.json.gz:157523", "repo_name": "luigoalma/3ds_gpio", "revision_date": "2022-08-22T19:03:28", "revision_id": "e368e78f1ca9ecf340579e7d32058cabcbab099d", "snapshot_id": "f401f00dd3caa9c7d86e674424d06ec4de17efe2", "src_encoding": "UTF-8", "star_events_count": 17, "url": "https://raw.githubusercontent.com/luigoalma/3ds_gpio/e368e78f1ca9ecf340579e7d32058cabcbab099d/source/3ds/errf.c", "visit_date": "2022-08-30T17:02:34.241628" }
stackv2
#include <memset.h> #include <3ds/types.h> #include <3ds/result.h> #include <3ds/svc.h> #include <3ds/errf.h> #include <3ds/ipc.h> static Handle errfHandle; static int errfRefCount; Result errfInit(void) { Result rc = 0; if (errfRefCount++) return 0; rc = svcConnectToPort(&errfHandle, "err:f"); if (R_FAILED(rc)) errfExit(); return rc; } void errfExit(void) { if (--errfRefCount) return; svcCloseHandle(errfHandle); } static inline void getCommonErrorData(ERRF_FatalErrInfo* error, Result failure) { error->resCode = failure; svcGetProcessId(&error->procId, 0xFFFF8001); } void ERRF_ThrowResultNoRet(Result failure) { while (R_FAILED(errfInit())) { svcSleepThread(100000000LLU); } // manually inlined ERRF_Throw and adjusted to make smaller code output uint32_t *cmdbuf = getThreadCommandBuffer(); cmdbuf[0] = IPC_MakeHeader(0x1, 32, 0); _memset32_aligned(&cmdbuf[1], 0, sizeof(ERRF_FatalErrInfo)); ERRF_FatalErrInfo* error = (ERRF_FatalErrInfo*)&cmdbuf[1]; error->type = ERRF_ERRTYPE_GENERIC; error->pcAddr = (u32)__builtin_extract_return_addr(__builtin_return_address(0)); getCommonErrorData(error, failure); svcSendSyncRequest(errfHandle); errfExit(); for (;;) { svcSleepThread(10000000000LLU); // lighter loop } }
2.25
2
2024-11-18T21:52:17.429808+00:00
2020-08-25T20:38:15
5b1a07ee3b2ba5a601b3c42b3fced1eed2e89218
{ "blob_id": "5b1a07ee3b2ba5a601b3c42b3fced1eed2e89218", "branch_name": "refs/heads/master", "committer_date": "2020-08-25T20:38:15", "content_id": "694a885daa64be55fbc9f5ecaf7e1d7654d04d1b", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "a14d55701c73640a7fad21a8b4300da3b6140730", "extension": "c", "filename": "i106_decode_1553f1.c", "fork_events_count": 1, "gha_created_at": "2020-08-25T20:32:40", "gha_event_created_at": "2021-01-26T23:05:12", "gha_language": "C", "gha_license_id": "BSD-3-Clause", "github_id": 290317426, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5042, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/src/i106_decode_1553f1.c", "provenance": "stackv2-0138.json.gz:157652", "repo_name": "ijmyers/libirig106", "revision_date": "2020-08-25T20:38:15", "revision_id": "415d3c3bfc1ff6cb4a29674c866f2deff1071a9a", "snapshot_id": "1e88cec2febd094b02ee9866c414ad9b54a0e21a", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/ijmyers/libirig106/415d3c3bfc1ff6cb4a29674c866f2deff1071a9a/src/i106_decode_1553f1.c", "visit_date": "2023-02-22T18:56:30.884822" }
stackv2
/**************************************************************************** i106_decode_1553f1.c ****************************************************************************/ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "stdint.h" #include "irig106ch10.h" #include "i106_decode_1553f1.h" /* Function Declaration */ static void FillInMessagePointers(MS1553F1_Message *msg); I106Status I106_Decode_First1553F1(I106C10Header *header, void *buffer, MS1553F1_Message *msg){ // Set pointers to the beginning of the 1553 buffer msg->CSDW = (MS1553F1_CSDW *)buffer; // Check for no messages msg->MessageNumber = 0; if (msg->CSDW->MessageCount == 0) return I106_NO_MORE_DATA; // Check for too many messages. There was a problem with a recorder // that produced bad 1553 packets. These bad packets showed *huge* // message counts, and all the data was garbage. This test catches // this case. Sorry. 8-( if (msg->CSDW->MessageCount > 100000) return I106_BUFFER_OVERRUN; // Figure out the offset to the first 1553 message and // make sure it isn't beyond the end of the data buffer msg->DataLength = header->DataLength; msg->Offset = sizeof(MS1553F1_CSDW); if (msg->Offset >= msg->DataLength) return I106_BUFFER_OVERRUN; // Set the pointer to the first 1553 message msg->IPH = (MS1553F1_IPH *) ((char *)(buffer) + msg->Offset); // Check to make sure the data does run beyond the end of the buffer if ((msg->Offset + sizeof(MS1553F1_IPH) + msg->IPH->Length) > msg->DataLength) return I106_BUFFER_OVERRUN; // Get the other pointers FillInMessagePointers(msg); return I106_OK; } I106Status I106_Decode_Next1553F1(MS1553F1_Message *msg){ // Check for no more messages msg->MessageNumber++; if (msg->MessageNumber >= msg->CSDW->MessageCount) return I106_NO_MORE_DATA; // Figure out the offset to the next 1553 message and // make sure it isn't beyond the end of the data buffer msg->Offset += sizeof(MS1553F1_IPH) + msg->IPH->Length; if (msg->Offset >= msg->DataLength) return I106_BUFFER_OVERRUN; // Set pointer to the next 1553 data buffer msg->IPH = (MS1553F1_IPH *) ((char *)(msg->IPH) + sizeof(MS1553F1_IPH) + msg->IPH->Length); // Check to make sure the data does run beyond the end of the buffer if ((msg->Offset + sizeof(MS1553F1_IPH) + msg->IPH->Length) > msg->DataLength) return I106_BUFFER_OVERRUN; // Get the other pointers FillInMessagePointers(msg); return I106_OK; } void FillInMessagePointers(MS1553F1_Message *msg){ msg->CommandWord1 = (CommandWordUnion *)((char *)(msg->IPH) + sizeof(MS1553F1_IPH)); // Position of data and status response differ between transmit and receive // If not RT to RT if ((msg->IPH)->RT2RT == 0){ // Second command and status words not available msg->CommandWord2 = NULL; msg->StatusWord2 = NULL; // Figure out the word count msg->WordCount = MS1553WordCount(msg->CommandWord1); // Receive if (msg->CommandWord1->CommandWord.TR == 0){ msg->Data = (uint16_t *)msg->CommandWord1 + 1; msg->StatusWord1 = msg->Data + msg->WordCount; } // Transmit else { msg->StatusWord1 = (uint16_t *)msg->CommandWord1 + 1; msg->Data = (uint16_t *)msg->CommandWord1 + 2; } } // RT to RT else { msg->CommandWord2 = msg->CommandWord1 + 1; msg->WordCount = MS1553WordCount(msg->CommandWord2); msg->StatusWord2 = (uint16_t *)msg->CommandWord1 + 2; msg->Data = (uint16_t *)msg->CommandWord1 + 3; msg->StatusWord1 = (uint16_t *)msg->Data + msg->WordCount; } } char * GetCommandWord(unsigned int raw){ static char string[16]; CommandWord * command_word = (CommandWord *)&raw; sprintf(string, "%2d-%c-%2d-%2d", command_word->RT, command_word->TR ? 'T' : 'R', command_word->SubAddress, command_word->WordCount==0 ? 32 : command_word->WordCount); return &string[0]; } /* Return the number of word in a 1553 message taking into account mode codes */ int MS1553WordCount(const CommandWordUnion *command_word){ // If the subaddress is a mode code then find out number of data words if ((command_word->CommandWord.SubAddress == 0x0000) || (command_word->CommandWord.SubAddress == 0x001f)){ return (int)command_word->CommandWord.WordCount & 0x0010; } // If regular subaddress find out number of data words else { if (command_word->CommandWord.WordCount == 0) return 32; else return command_word->CommandWord.WordCount; } }
2.375
2
2024-11-18T21:52:17.744366+00:00
2014-12-03T20:29:00
1036924c1c56ffcb0c8444417b0f046eeab09b16
{ "blob_id": "1036924c1c56ffcb0c8444417b0f046eeab09b16", "branch_name": "refs/heads/master", "committer_date": "2014-12-03T20:29:00", "content_id": "173b9a648e97cae79eb7173698d58650329f497c", "detected_licenses": [ "MIT" ], "directory_id": "b665e617edc30ce87dc0a1b3f24fea12ce1c584a", "extension": "h", "filename": "minirpc-service.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": 2643, "license": "MIT", "license_type": "permissive", "path": "/minirpc-service.h", "provenance": "stackv2-0138.json.gz:157912", "repo_name": "moneytech/minirpc", "revision_date": "2014-12-03T20:29:00", "revision_id": "ccd2d51a7bdb6952b6845482eed6daedeaa1507b", "snapshot_id": "ac4af6d65eb9e2cb4ba89635798d9ae999943dd3", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/moneytech/minirpc/ccd2d51a7bdb6952b6845482eed6daedeaa1507b/minirpc-service.h", "visit_date": "2020-09-28T02:30:37.176710" }
stackv2
#ifndef MINIRPC_SERVICE_H_ #define MINIRPC_SERVICE_H_ #include <stddef.h> /* * This is the default Mini RPC service module. A service means a reigetered * RPC routine. This service module provides infrastructure to register,execute * service using multi-thread. To make it more flexible, the user is able to * call the service execution manually as well, and it means user could multiplex * the service execution with MRPC poll function in a single thread when thread * is not available */ struct mrpc_val; struct mrpc_service; struct mrpc_request; struct mrpc_service* mrpc_service_create( size_t sz , size_t min_slp_time , size_t max_slp_time , void* opaque ); /* Typically you don't have to call this function */ void mrpc_service_destroy( struct mrpc_service* ); typedef void (*mrpc_service_cb)( struct mrpc_service* , const struct mrpc_request* , void*, int* , struct mrpc_val* ); /* This function is _NOT_ thread safe, call it before you call mrpc_service_run_remote * and after you call mrpc_service_create in the same thread */ int mrpc_service_add( struct mrpc_service*, mrpc_service_cb cb , const char* method_name , void* udata ); /* Running the service in the caller thread */ void mrpc_service_run_once( struct mrpc_service* ); void mrpc_service_run( struct mrpc_service* ); /* Running the service in the remote thread, the user needs to * specify the thread number. This function will not block or * run any callback function inside of it. All the callback * function will be executed in back ground thread. */ int mrpc_service_run_remote( struct mrpc_service* , int thread_sz ); /* Call this function inside of the thread that call mrpc_service_run_remote * This function will block until all the thread join in the calling thread. * This function may deadlock if the user doesn't call mrpc_interrupt, the * service module will not call this function manually. A typical way is just * run the mrpc_run in main thread , and put this function right after it. * It is because MRPC take care of signal handling, so a Ctrl+Z/C/X can be * issued from user to _STOP_ the service , after that the mrpc_run will exit * automatically and service module _DO_ receive this interruption as well * internally . Then call mrpc_service_run_quit after mrpc_run is _ALWAYS_ * safe there. */ int mrpc_service_quit( struct mrpc_service* ); /* Utility */ /* Get opaque user data */ void* mrpc_service_get_udata( struct mrpc_service* ); #endif /* MINIRPC_SERVICE_H_ */
2.015625
2
2024-11-18T21:52:17.832961+00:00
2020-12-08T15:06:55
80640b01f592ef473250675d086cce68c9fb4404
{ "blob_id": "80640b01f592ef473250675d086cce68c9fb4404", "branch_name": "refs/heads/main", "committer_date": "2020-12-08T15:06:55", "content_id": "3da7713b407667b8984e20c4a2af4d0b107892c5", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "1464d42c09403ab7e7b6dd493d32067af7a4eb10", "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": 319674605, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1300, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/examples/rtc/main.c", "provenance": "stackv2-0138.json.gz:158041", "repo_name": "uriiy/NordicSnippets", "revision_date": "2020-12-08T15:06:55", "revision_id": "7757bc5ec10478751f24ba4748d7d184aaba83b4", "snapshot_id": "723b120465a69f511317bd2463f8e0c336281967", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/uriiy/NordicSnippets/7757bc5ec10478751f24ba4748d7d184aaba83b4/examples/rtc/main.c", "visit_date": "2023-01-27T13:45:33.645923" }
stackv2
#include <nrf.h> int main(void) { // Start LFCLK (32kHz) crystal oscillator. If you don't have crystal on your board, choose RCOSC instead. NRF_CLOCK->LFCLKSRC = CLOCK_LFCLKSRC_SRC_Xtal << CLOCK_LFCLKSRC_SRC_Pos; NRF_CLOCK->TASKS_LFCLKSTART = 1; while (NRF_CLOCK->EVENTS_LFCLKSTARTED == 0); NRF_CLOCK->EVENTS_LFCLKSTARTED = 0; // 32kHz timer period NRF_RTC0->PRESCALER = 0; // 30.5ms us compare value, generates EVENTS_COMPARE[0] NRF_RTC0->CC[0] = 1000; // Enable EVENTS_COMPARE[0] generation NRF_RTC0->EVTENSET = RTC_EVTENSET_COMPARE0_Enabled << RTC_EVTENSET_COMPARE0_Pos; // Enable IRQ on EVENTS_COMPARE[0] NRF_RTC0->INTENSET = RTC_INTENSET_COMPARE0_Enabled << RTC_INTENSET_COMPARE0_Pos; // Enable RTC IRQ and start the RTC NVIC_EnableIRQ(RTC0_IRQn); NRF_RTC0->TASKS_START = 1; while (1) { __WFE(); } } // This IRQ handler will trigger every 30.5 ms void RTC0_IRQHandler(void) { volatile uint32_t dummy; if (NRF_RTC0->EVENTS_COMPARE[0] == 1) { NRF_RTC0->EVENTS_COMPARE[0] = 0; // Increment compare value with 30.5 ms from current time. NRF_RTC0->CC[0] = NRF_RTC0->COUNTER + 1000; // Read back event register so ensure we have cleared it before exiting IRQ handler. dummy = NRF_RTC0->EVENTS_COMPARE[0]; dummy; } }
2.3125
2
2024-11-18T21:52:18.925019+00:00
2017-05-09T01:08:07
f1f30f5b72d5e040a4a93fc3232147c6d3559bd0
{ "blob_id": "f1f30f5b72d5e040a4a93fc3232147c6d3559bd0", "branch_name": "refs/heads/master", "committer_date": "2017-05-09T01:08:07", "content_id": "8077e126cf20e855b74d2d3495738a97d4a0b1ba", "detected_licenses": [ "CC0-1.0" ], "directory_id": "3c02fb266dce02969c002499393aec5a41557cf6", "extension": "c", "filename": "MST-Kruskal's-Algo.c", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 37217282, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1571, "license": "CC0-1.0", "license_type": "permissive", "path": "/Graph-Theory/MST-Kruskal's-Algo.c", "provenance": "stackv2-0138.json.gz:158690", "repo_name": "shohan4556/Ionic-Proton", "revision_date": "2017-05-09T01:08:07", "revision_id": "c44bf63ea40ed3c5bc4e4641f4882b046d87039c", "snapshot_id": "46c96f11649368993546d206c4c82dff80bb2d85", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/shohan4556/Ionic-Proton/c44bf63ea40ed3c5bc4e4641f4882b046d87039c/Graph-Theory/MST-Kruskal's-Algo.c", "visit_date": "2020-05-19T17:30:03.107376" }
stackv2
#include<cstdio> #include<iostream> #include<vector> #include<algorithm> #define N 100 using namespace std; int parent[N]; struct edge{ int u,v,weight; // pre, post,cost bool operator <(edge p)const{ // operator overloading used to sort the weight return weight<p.weight; } }; vector <edge>e; // create a vector e int find_par(int r) // return the parent of the node { if(parent[r]==r) return r; else{ parent[r]=find_par(parent[r]); return parent[r]; } } int mst(int n) { sort(e.begin(),e.end()); // sort as increasing order for(int i=1;i<=n;i++) parent[i]=i; // initialize same nodes as parent int count =0,s=0; for(int i=0;i<=(int)e.size();i++){ int u=find_par(e[i].u); int v=find_par(e[i].v); // union if(u!=v){ // parent are not same parent[u]=v; // link both parent count++; // counting how many edges are connected s+=e[i].weight; // sum weight if(count==n-1) // n-1 edges connected break; } } return s; // return sum } int main() { int n,m; // nodes and edge cin>>n>>m; for(int i=1;i<=m;i++){ int u,v,w; cin>>u>>v>>w; edge get; get.u=u; get.v=v; get.weight=w; e.push_back(get); // add data into vector } cout<<mst(n)<<endl; // pass nodes and connected edge should be n-1 and no cycle return 0; }
3.3125
3
2024-11-18T21:52:19.509252+00:00
2020-01-28T02:17:01
826603b33b32b12479163b70c70767111504435f
{ "blob_id": "826603b33b32b12479163b70c70767111504435f", "branch_name": "refs/heads/master", "committer_date": "2020-01-28T02:17:01", "content_id": "a52ddfe66d3a1f06866819a2a04febb267fd3999", "detected_licenses": [ "BSD-2-Clause", "BSD-3-Clause" ], "directory_id": "51baca18a6813c0f26b292012c5c89d2da284636", "extension": "c", "filename": "unistd.c", "fork_events_count": 0, "gha_created_at": "2020-01-28T02:36:03", "gha_event_created_at": "2020-01-28T02:36:04", "gha_language": null, "gha_license_id": "BSD-2-Clause", "github_id": 236642971, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 21045, "license": "BSD-2-Clause,BSD-3-Clause", "license_type": "permissive", "path": "/userland/atacama/lib/libc03/unistd/unistd.c", "provenance": "stackv2-0138.json.gz:159080", "repo_name": "luiz117/gramado", "revision_date": "2020-01-28T02:17:01", "revision_id": "c63dfcc95e078f7534d28aacb837c6dcbd38fbd8", "snapshot_id": "48c57d601b49cc9f4901abddb9c1cae5bdc168e7", "src_encoding": "UTF-8", "star_events_count": 3, "url": "https://raw.githubusercontent.com/luiz117/gramado/c63dfcc95e078f7534d28aacb837c6dcbd38fbd8/userland/atacama/lib/libc03/unistd/unistd.c", "visit_date": "2020-12-22T02:25:48.968525" }
stackv2
/* * File: unistd.c * * Unix standard. * * History: * 2019 - Created by Fred Nora. */ #include <sys/types.h> #include <sys/socket.h> #include <sys/mman.h> //#include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <limits.h> //#todo //nice() precisa disso. #include <sys/time.h> #include <sys/resource.h> //#test #include <pty.h> #include <utmp.h> #include <termios.h> //system calls. #include <stubs/gramado.h> #define UNISTD_SYSTEMCALL_FORK 71 #define UNISTD_SYSTEMCALL_EXIT 70 #define UNISTD_SYSTEMCALL_GETPID 85 #define UNISTD_SYSTEMCALL_GETPPID 81 //... // // ## TEST ## // int errno; //The <unistd.h> header shall declare the following external variables: char *optarg; int opterr, optind, optopt; //#todo //#define UNISTD_SYSTEMCALL_GETGID ?? /* //protótipo de função interna. void *unistd_system_call ( unsigned long ax, unsigned long bx, unsigned long cx, unsigned long dx ); */ /* ******************** * unistd_system_call: * System call usada pelo módulo stdio. * Função interna. * As funções padrão de stdio chamarão recursos do kernel atravéz dessa * rotina. * Interrupção de sistema, número 200, personalizada para stdio. * Chama vários serviços do Kernel com a mesma interrupção. * Essa é a chamada mais simples. * * Argumentos: * eax = arg1, o Número do serviço. * ebx = arg2. * ecx = arg3. * edx = arg4. */ /* void *unistd_system_call ( unsigned long ax, unsigned long bx, unsigned long cx, unsigned long dx ) { int Ret = 0; //System interrupt. asm volatile ( " int %1 \n" : "=a"(Ret) : "i"(0x80), "a"(ax), "b"(bx), "c"(cx), "d"(dx) ); return (void *) Ret; } */ /* * execv: * */ // #todo: Trabalhar o environment. // #isso é um teste char *__execv_environ[] = { NULL, NULL, NULL }; int execv (const char *path, char *const argv[] ) { return execve ( path, (char **) argv, __execv_environ ); } //#tod: usar a variavel environ padrão. /* int execv(const char* path, char* const argv[]) { return execve(path, argv, environ); } */ //Credits: serenity os /* int execvp(const char* filename, char* const argv[]) { int rc = execvpe(filename, argv, environ); dbg() << "execvp() about to return " << rc << " with errno=" << errno; return rc; } */ // unistd ? /* pid_t tcgetpgrp(int fd) { return ioctl(fd, TIOCGPGRP); } */ // unistd ? /* int tcsetpgrp(int fd, pid_t pgid) { return ioctl(fd, TIOCSPGRP, pgid); } */ //padrão libc. //int execve ( const char *path, char *const argv[], char *const envp[] ); int execve ( const char *filename, char *argv[], char *envp[] ) { //erro. int Status = 1; //unsigned long arg_address = (unsigned long) &argv[0]; // suprimindo dot-slash // The dot is the current directory and the // slash is a path delimiter. //if( filename[0] == '.' && filename[1] == '/' ) //{ // filename++; // filename++; // goto translate; //}; //suprimindo a barra. //if( *arg1 == '/' || // *arg1 == '\\' ) //{ // arg1++; //}; translate: // // ## BUG BUG // // Talvez nesse momento, ao transformar a string ele // corrompa o espaço reservado para o argumento seguinte. // vamos fazer um teste no quan a rotina não precise // acrescentar zeros. // // // correto é isso mesmo, // para não corromper o espaço dos argumentos no vetor, // teremos que transformar somente lá no kernel, pouco antes // de carregarmos o arquivo. // //Isso faz uma conversão de 'test.bin' em 'TEST BIN'. //Ok funcionou. //shell_fntos( (char *) arg1); //const char* isso não foi testado. //shell_fntos(filename); // #importante: // Isso deve chamar gramado_core_init_execve() na api. // #obs: // isso chamará uma rotina especial de execve, somente // usada no ambiente gramado core. // Essa é uma rotina alternativa que roda um processo usando os recursos // do processo init. execve: // Obs: // Se retornar o número do processo então podemos esperar por ele // chamando wait (ret); //#todo: // mudaremos esse número de chamada pra uma // que use o processo atual e não o init. Status = (int) gramado_system_call ( 248, (unsigned long) filename, // Nome (unsigned long) argv, // arg (endereço da linha de comando) (unsigned long) envp ); // env if ( Status == 0 ) { //Não houve erro. O aplicativo irá executar. // Nesse momento devemos usar um novo procedimento de janela. // Que vai enviar as mensagens de caractere para um terminal // específico, para que aplicativos que user aquele terminal // possam pegar essas mensgens de caractere. //#ifdef SHELL_VERBOSE //printf ("execve: Aplicativo inicializado\n"); //#endif // // ## teste ## // // saindo do shell. // // getpid... // waitforpid(?); //die("Exiting shell.bin\n"); //Saindo sem erro. //exit(0); //Saída elegante, retornando para o crt0. //ShellFlag = SHELLFLAG_EXIT; //ShellFlag = SHELLFLAG_FEEDTERMINAL; goto done; }else{ // Se estamos aqui é porque ouve erro // ainda não sabemos o tipo de erro. // Status indica o tipo de erro. // Se falhou significa que o aplicativo não vai executar, // então não mais o que fazer. //#importante: Error message. printf ("execve: O aplicativo nao foi inicializado\n"); //ShellFlag = SHELLFLAG_COMMANDLINE; goto fail; }; //fail. // Retornaremos. // Quem chamou essa rotina que tome a decisão // se entra em wait ou não. fail: Status = -1; //#importante: Error message. printf ("execve: fail \n"); done: return (int) Status; } ssize_t read_ttyList (int fd, const void *buf, size_t count) { if (fd<0) return -1; return (ssize_t) gramado_system_call ( 268, (unsigned long) fd, // dispositivo. (unsigned long) buf, (unsigned long) count ); } // o descritor seleciona uma tty em ttyList ssize_t write_ttyList (int fd, const void *buf, size_t count) { if (fd<0) return -1; return (ssize_t) gramado_system_call ( 269, (unsigned long) fd, // dispositivo. (unsigned long) buf, (unsigned long) count ); } // read on virtual console! // range: 0 ~ 3 ssize_t read_VC (int fd, const void *buf, size_t count) { if (fd<0) return -1; return (ssize_t) gramado_system_call ( 262, (unsigned long) fd, // dispositivo. (unsigned long) buf, (unsigned long) count ); } // write on virtual console! // range: 0 ~ 3 ssize_t write_VC (int fd, const void *buf, size_t count) { if (fd<0) return -1; return (ssize_t) gramado_system_call ( 263, (unsigned long) fd, // dispositivo. (unsigned long) buf, (unsigned long) count ); } //usam a lista de arquivos abertos do processo. p->Streams[i] ssize_t read (int fd, const void *buf, size_t count) { if (fd<0) return -1; return (ssize_t) gramado_system_call ( 260, (unsigned long) fd, // dispositivo. (unsigned long) buf, (unsigned long) count ); } //usam a lista de arquivos abertos do processo. p->Streams[i] ssize_t write (int fd, const void *buf, size_t count) { if (fd<0) return -1; return (ssize_t) gramado_system_call ( 261, (unsigned long) fd, // dispositivo. (unsigned long) buf, (unsigned long) count ); } /* ************************************* * exit: * Torna zombie a thread atual. * Mas o propósito é terminar sair do * programa, terminando o processo e * liberar os recursos que o processo estava usando. * #importante: * @todo: se o status for (1) devemos imprimir o conteúdo * de stderr na tela. * ?? Essa função também pertence à unistd */ void exit (int status){ // #importante: // #todo: // Se o status for (1) devemos imprimir o conteúdo // de stderr na tela. // 70 gramado_system_call ( UNISTD_SYSTEMCALL_EXIT, (unsigned long) status, (unsigned long) status, (unsigned long) status ); // Wait forever. while (1){ asm ("pause"); }; } /* ************************** * fast_fork: * Isso é uma systemcall especial usada somente para a * função fork(). Ela tem sua própria interrupção. * */ pid_t fast_fork ( unsigned long ax, unsigned long bx, unsigned long cx, unsigned long dx ) { pid_t Ret = 0; asm volatile ( " int %1 \n" : "=a"(Ret) : "i"(133), "a"(ax), "b"(bx), "c"(cx), "d"(dx) ); return (pid_t) Ret; } /* ************** * fork: * Essa implementação de fork() usa uma systemcall especial, usada * somente na função fork. Essa systemcall tem sua própria interrupção. * */ pid_t fork (void){ pid_t ret; ret = (pid_t) fast_fork (0,0,0,0); if ( ret == -1 ) { // #todo: // Configurar o errno. return (pid_t) ret; } if (ret == 0) { // We're the child in this part. return 0; } // Estamos no pai. // Vamos retornar o PID do filho. return (pid_t) ret; } /* ****************************** * sys_fork: * Essa é uma implementação da função fork() usando * a systemcall padrão com a interrupção do sistema. */ pid_t sys_fork (void){ pid_t ret; ret = (int) gramado_system_call ( UNISTD_SYSTEMCALL_FORK, (unsigned long) 0, (unsigned long) 0, (unsigned long) 0 ); if ( ret == -1 ) { // #todo: // Configurar o errno. return (pid_t) ret; } // We're the child in this part. if (ret == 0) { return 0; } // Estamos no pai. // Vamos retornar o PID do filho. return (pid_t) ret; } /* * setuid: * */ // SVr4, POSIX.1-2001. // Not quite compatible with the 4.4BSD call, which // sets all of the real, saved, and effective user IDs. int setuid ( uid_t uid ){ //#todo: ainda não temos a suystem call. //SYSTEMCALL_SETCURRENTUSERID return (uid_t) gramado_system_call ( 151, 0, 0, 0 ); } uid_t getuid (void){ return (uid_t) gramado_system_call ( 152, 0, 0, 0 ); } uid_t geteuid (void){ return -1; //return (uid_t) gramado_system_call ( ?, 0, 0, 0 ); } /* * getpid: * */ pid_t getpid (void){ return (pid_t) gramado_system_call ( UNISTD_SYSTEMCALL_GETPID, 0, 0, 0 ); } /* * getppid: * */ pid_t getppid (void){ return (pid_t) gramado_system_call ( UNISTD_SYSTEMCALL_GETPPID, 0, 0, 0 ); } /* * getgid: * */ gid_t getgid (void) { //SYSTEMCALL_GETCURRENTGROUPID return (gid_t) gramado_system_call ( 154, 0, 0, 0 ); } /* char* getwd(char* buf) { auto* p = getcwd(buf, PATH_MAX); return p; } */ /* int gettid() { //todo: use syscall!! } */ /* void sysbeep() { //todo: use syscall!! } */ /* * dup: * */ int dup (int oldfd){ return (int) gramado_system_call ( (unsigned long) oldfd, 0, 0, 0 ); } /* * dup2: * */ int dup2 (int oldfd, int newfd){ return (int) gramado_system_call ( (unsigned long) oldfd, (unsigned long) newfd, 0, 0 ); } /* * dup3: * */ int dup3 (int oldfd, int newfd, int flags){ return (int) gramado_system_call ( (unsigned long) oldfd, (unsigned long) newfd, (unsigned long) flags, 0 ); } //see: sys/resource.h int getpriority(int which, id_t who) { return -1; } //see: sys/resource.h int setpriority(int which, id_t who, int prio) { return -1; } /* * nice: * Change process priority. */ int nice (int inc) { return -1; //#todo //#todo /* int prio; errno = 0; prio = getpriority(PRIO_PROCESS, 0); if (prio == -1 && errno) return -1; if (setpriority(PRIO_PROCESS, 0, prio + incr) == -1) { if (errno == EACCES) errno = EPERM; return -1; } return getpriority(PRIO_PROCESS, 0); */ } /* * pause: * */ int pause (void){ return -1; //#todo } /* * mkdir: * */ int mkdir (const char *pathname, mode_t mode){ return -1; //#todo } /* * rmdir: * */ int rmdir (const char *pathname){ return -1; //#todo } /* * link: * */ //Links a name to a file. int link (const char *oldpath, const char *newpath){ return -1; //#todo } //#todo. int unlink(const char *pathname) { return (int) (-1); } /* * mlock: * */ int mlock (const void *addr, size_t len){ return -1; //#todo } /* * munlock: * */ int munlock (const void *addr, size_t len){ return -1; //#todo } /* * mlockall: * */ int mlockall (int flags){ return -1; //#todo } /* * munlockall: * */ int munlockall (void){ return -1; //#todo } /* * sysconf: * */ long sysconf (int name){ return -1; //#todo } /* * fsync: * */ int fsync (int fd){ return -1; //#todo } /* * fdatasync: * */ int fdatasync (int fd){ return -1; //#todo } // commit buffer cache to disk void sync(void) { //todo: use syscall!! } // commit buffer cache to disk int syncfs(int fd) { return -1; } /* ***************************************** * close: * SVr4, 4.3BSD, POSIX.1-2001. */ int close (int fd){ return (int) gramado_system_call ( 17, (unsigned long) fd, (unsigned long) fd, (unsigned long) fd ); } /* ************************************************** * pipe: * */ // good! int pipe ( int pipefd[2] ) { return (int) gramado_system_call ( 247, (unsigned long) pipefd, (unsigned long) pipefd, (unsigned long) pipefd ); } /* int pipe(int pipefd[2]) { return pipe2(pipefd, 0); } */ long fpathconf (int fildes, int name) { return -1; } long pathconf (const char *pathname, int name) { return -1; } //deletar. static char __libc_hostname[HOST_NAME_MAX]; static char __libc_username[HOST_NAME_MAX]; /* * __gethostname: * * */ //isso funciona. char __Hostname_buffer[64]; char *__gethostname (void) { gramado_system_call ( 801, (unsigned long) &__Hostname_buffer[0], (unsigned long) &__Hostname_buffer[0], (unsigned long) &__Hostname_buffer[0] ); return __Hostname_buffer; } /* ****************************** * gethostname * * */ //char *my__p; //See: http://man7.org/linux/man-pages/man2/sethostname.2.html // Passando para o kernel o buffer que está no app. int gethostname (char *name, size_t len){ int len_ret; len_ret = (int) gramado_system_call ( 801, (unsigned long) name, (unsigned long) name, (unsigned long) name ); return len_ret; } //See: http://man7.org/linux/man-pages/man2/sethostname.2.html int sethostname (const char *name, size_t len){ return (int) gramado_system_call ( 802, (unsigned long) name, (unsigned long) name, (unsigned long) name ); } char __Login_buffer[64]; //#todo char *getlogin (void) { //passamos um buffer para o kernel. gramado_system_call ( 803, (unsigned long) &__Login_buffer[0], (unsigned long) &__Login_buffer[0], (unsigned long) &__Login_buffer[0] ); //strcpy(__Login, "test"); return __Login_buffer; } //#todo int setlogin(const char *name) { //#todo: pegar retorno da função //return (int) gramado_system_call ( 804, (unsigned long) name, (unsigned long) name, (unsigned long) name ); return 0; //poderia retornar o size. } /* **************************** * getusername * */ // #todo //usar setlogin int getusername (char *name, size_t len) { int __len_ret; if ( len < 0 || len > HOST_NAME_MAX ) { printf ("getusername: len\n"); return -1; } //coloca no buffer interno __len_ret = (int) gramado_system_call ( 803, (unsigned long) name, (unsigned long) name, (unsigned long) name ); if ( __len_ret < 0 || __len_ret > HOST_NAME_MAX ) { printf ("getusername: __len_ret\n"); return -1; } if ( __len_ret > len ) { __len_ret = len; } return 0; } /* **************************** * setusername * */ // Um pequeno buffer foi passado pelo aplicativo. // O limite precisa ser respeitado. // #todo //usar setlogin int setusername (const char *name, size_t len){ size_t __name_len = strlen(name) + 1; // Limite dado pelo sistema. if (len < 0 || len >= HOST_NAME_MAX ) { printf ("setusername: *len\n"); return 1; } // Tamanho indicado pelo aplicativo. if ( __name_len > len ) { printf ("setusername: len\n"); return 1; } return (int) gramado_system_call ( 804, (unsigned long) name, (unsigned long) name, (unsigned long) name ); } /* ************** * ttyname: * */ //POSIX.1-2001, POSIX.1-2008, 4.2BSD. //ttyname, ttyname_r - return name of a terminal //If the file descriptor filedes is associated with a terminal device, //the ttyname function returns a pointer to a statically-allocated, //null-terminated string containing the file name of the terminal file. //The value is a null pointer if the file descriptor isn't associated //with a terminal, or the file name cannot be determined. // ok // então o buffer para esse nome deve ficar aqui na libc em ring3 // Onde o app pode ler. // Chamremos o kernel e diremos, coloque o nome aqui nesse buffer. //char __ttyname_buffer[64]; char *ttyname(int fd) { static char buf[PATH_MAX]; int rv; rv = ttyname_r (fd, buf, sizeof(buf)); if (rv != 0) { errno = rv; return NULL; } return buf; } //POSIX.1-2001, POSIX.1-2008, 4.2BSD. //ttyname, ttyname_r - return name of a terminal int ttyname_r(int fd, char *buf, size_t buflen) { return -1; } //#todo /* int ttyslot (void); int ttyslot (void) { return -1; } */ // POSIX.1-2001, POSIX.1-2008, SVr4, 4.3BSD. // isatty - test whether a file descriptor refers to a terminal // This function returns 1 if filedes is a file descriptor associated // with an open terminal device, and 0 otherwise. int isatty (int fd) { struct termios t; return ( tcgetattr(fd, &t) != -1 ); } /* int isatty(int fd) { struct termios dummy; return tcgetattr(fd, &dummy) == 0; } */ int getopt (int argc, char * const argv[], const char *optstring) { return -1; } //sys/stat.h /* int fstat(int fd, struct stat *buf); int fstat(int fd, struct stat *buf) { return -1; } */ //sys/stat.h /* int lstat(const char *path, struct stat *buf); int lstat(const char *path, struct stat *buf) { return (int) stat (path, buf); } */ //sys/stat.h /* int stat(const char *path, struct stat *buf); int stat(const char *path, struct stat *buf) { int i = open(path, 0); int ret = fstat(i, buf); close(i); return ret; } */ //POSIX.1-2001, POSIX.1-2008, SVr4, 4.3BSD. unsigned int alarm(unsigned int seconds) { return 0; } int brk(void *addr) { return -1; } //#todo: definir o tipo intptr_t /* void *sbrk(intptr_t increment); void *sbrk(intptr_t increment) { return NULL; } */ int execvp(const char *file, char *const argv[]) { return -1; } int execvpe(const char *file, char *const argv[], char *const envp[]) { return -1; } /* int chown(const char *pathname, uid_t owner, gid_t group); int chown(const char *pathname, uid_t owner, gid_t group) { return -1; } */ /* int fchown(int fd, uid_t owner, gid_t group); int fchown(int fd, uid_t owner, gid_t group) { return -1; } */ /* int lchown(const char *pathname, uid_t owner, gid_t group); int lchown(const char *pathname, uid_t owner, gid_t group) { return -1; } */ int chdir(const char *path) { return -1; } int fchdir(int fd) { return -1; } //sleep - sleep for a specified number of seconds unsigned int sleep(unsigned int seconds) { return 0; } //todo void _exit (int status) { //improvisando exit(0); } // // End. //
2.3125
2
2024-11-18T21:52:19.611567+00:00
2013-02-06T10:30:06
930f0d1017dccac3833d1e250b0b11f72e116534
{ "blob_id": "930f0d1017dccac3833d1e250b0b11f72e116534", "branch_name": "refs/heads/master", "committer_date": "2013-02-06T10:30:06", "content_id": "ec46630b472d118939c72b2b8b92c47e5f440a67", "detected_licenses": [ "MIT" ], "directory_id": "8e15ac379fe3745057a6ef0e29595aafcbfd73be", "extension": "c", "filename": "tmpcache_writeto.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": 3638, "license": "MIT", "license_type": "permissive", "path": "/src/tmpcache_writeto.c", "provenance": "stackv2-0138.json.gz:159209", "repo_name": "ma-everett/tmpcache", "revision_date": "2013-02-06T10:30:06", "revision_id": "ae88ed301a0dd4249cce88ebd4f2b70ccea191b7", "snapshot_id": "5633384b3592dd92efa429961dab7353fe858afe", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/ma-everett/tmpcache/ae88ed301a0dd4249cce88ebd4f2b70ccea191b7/src/tmpcache_writeto.c", "visit_date": "2020-12-24T13:44:53.586065" }
stackv2
/* tmpcache/tmpcache_writeto.c */ #include "../config.h" #include "utility.h" #include "cache.h" #include <zmq.h> #include <argtable2.h> struct arg_lit *delete; struct arg_lit *verbose, *help; struct arg_str *key; struct arg_file *netaddress0; struct arg_end *end; #define zmq_assertmsg(s,str) if ( ! (s) ) {\ fprintf(stderr,"%s - %s",(str),zmq_strerror(zmq_errno()));\ goto error; } int main (int argc, char **argv) { void *argtable[] = { delete = arg_lit0("d","delete","delete stored data"), help = arg_lit0("h","help","print this screen"), verbose = arg_lit0("v","verbose","tell me everything"), key = arg_str1(NULL,NULL,"key","data key"), netaddress0 = arg_file1(NULL,NULL,"address","tmpcache write network address "), end = arg_end(20), }; int32_t nerrors = arg_parse(argc,argv,argtable); if (help->count) { fprintf(stdout,"tmpcache writeto - version 0\n"); /*FIXME*/ arg_print_syntaxv(stdout,argtable,"\n\n"); arg_print_glossary (stdout,argtable,"%-25s %s\n"); goto finish; } if (verbose->count) { fprintf(stdout,"tmpcache writeto - version 0\n"); /*FIXME*/ int32_t major,minor,patch; zmq_version (&major,&minor,&patch); fprintf(stdout,"compiled with zmq support %d.%d.%d\n",major,minor,patch); goto finish; } if (nerrors) { arg_print_errors (stdout,end,""); arg_print_syntaxv(stdout,argtable,"\n\n"); goto finish; } void *ctx, *sock; ctx = zmq_ctx_new(); if (ctx == NULL) { goto finish; } sock = zmq_socket (ctx,ZMQ_PUSH); if (sock == NULL) { zmq_ctx_destroy (ctx); goto finish; } int32_t r = 0; r = zmq_connect (sock,netaddress0->filename[0]); zmq_assertmsg (r != -1,"connect failed"); zmq_msg_t msg_key; void *dkey = c_malloc (sizeof(char) * strlen(key->sval[0]), NULL); memcpy (dkey,key->sval[0],strlen(key->sval[0])); r = zmq_msg_init_data (&msg_key,dkey,strlen(key->sval[0]),c_free,NULL); zmq_assertmsg (r != -1,"init data failed"); zmq_msg_t msg_part; if (!delete->count) { char *buffer = c_malloc (sizeof(char) * (1024 * 1024),NULL); /* 1Mb */ if (buffer == NULL){ perror("Failed to allocate memory for buffer"); goto error; } memset (buffer,'\0',(1024 * 1024)); if (fgets (buffer,(1024 * 1024),stdin) == NULL){ perror("Failed to get from stdin"); goto error; } uint32_t len = strlen(buffer) - 1; char *data = c_malloc (sizeof(char) * len,NULL); memcpy (data,buffer,len); c_free (buffer,NULL); r = zmq_msg_init_data (&msg_part,data,len,c_free,NULL); zmq_assertmsg ((r != -1),"part init error"); } else { r = zmq_msg_init (&msg_part); zmq_assertmsg ((r != -1),"part init error"); } r = zmq_sendmsg (sock,&msg_key,ZMQ_SNDMORE); zmq_assertmsg (r != -1,"sendmsg key"); r = zmq_sendmsg (sock,&msg_part,0); zmq_assertmsg (r != -1,"sendmsg part"); r = zmq_msg_close (&msg_key); zmq_assertmsg (r != -1,"msg close key"); r = zmq_msg_close (&msg_part); zmq_assertmsg (r != -1,"msg close part"); error: r = zmq_disconnect (sock,netaddress0->filename[0]); if (r == -1) { fprintf(stderr,"disconnect failed - %s",zmq_strerror(zmq_errno())); } r = zmq_close (sock); if (r == -1) { fprintf(stderr,"close failed - %s",zmq_strerror(zmq_errno())); } r = zmq_ctx_destroy (ctx); if (r == -1) { fprintf(stderr,"ctx destroy failed - %s",zmq_strerror(zmq_errno())); } finish: arg_freetable(argtable,sizeof(argtable)/sizeof(argtable[0])); exit(0); }
2.21875
2
2024-11-18T21:52:19.709344+00:00
2018-09-25T18:21:40
93c861e969459438cb77bff1a8503bfb448e657c
{ "blob_id": "93c861e969459438cb77bff1a8503bfb448e657c", "branch_name": "refs/heads/master", "committer_date": "2018-09-25T18:21:40", "content_id": "934b4641f4058121aa37c50fd37df2e24883ee60", "detected_licenses": [ "MIT" ], "directory_id": "d356e3ff16d02ea041703c02dd1efcfdcce4f424", "extension": "c", "filename": "string_list.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 150308411, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3233, "license": "MIT", "license_type": "permissive", "path": "/src/string_list.c", "provenance": "stackv2-0138.json.gz:159338", "repo_name": "wdomitrz/telefony", "revision_date": "2018-09-25T18:21:40", "revision_id": "530ae849fc868016012d30b6555d5960cc487c17", "snapshot_id": "ec2523366533030a709396babeb644e0dd08f85d", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/wdomitrz/telefony/530ae849fc868016012d30b6555d5960cc487c17/src/string_list.c", "visit_date": "2020-03-29T20:21:28.967929" }
stackv2
/** @file * Implementacja operacji na liście słów z interfejsem w pliku * @ref string_list.h * * @author Witalis Domitrz <[email protected]> * @date 13.05.2018 */ #include <stdlib.h> #include <stdbool.h> #include <string.h> #include "string_list.h" void stringListDestroy(struct StringList const *stringList) { if (stringList == NULL) return; free((void *) stringList->val); stringListDestroy(stringList->next); free((void *) stringList); } /** * @brief Tworzy element listy * Tworzy element listy będący poprzednikiem @p next i z wartością @p val * @param next – wskaźnik na następnik nowotworzonego elementu; * @param val – wskaźnik na wartość nowotworzonego elementu. * @return Zwraca wskaźnik na nowoutworzony element, lub @c NULL gdy nie * udało się zaalokować pamięci. */ struct StringList *stringListElemCreate(struct StringList *next, char const *val) { struct StringList *newCharListList; // Alokacja nowej struktury newCharListList = malloc(sizeof(struct StringList)); if (newCharListList == NULL) return NULL; // Ustawienie parametrów newCharListList->val = val; newCharListList->next = next; // Zwrócenie nowej struktury return newCharListList; } struct StringList *stringListCreate(void) { // Pusty ciąg to wskaźnik na pierwszy element, który jest NULL-em return stringListElemCreate(NULL, NULL); } bool stringListAdd(struct StringList *stringList, char const *toAdd) { struct StringList *helper; int comparision; if (stringList == NULL) return false; // Znalezienie miejsca na nowy element comparision = 1; while (stringList->next != NULL && (comparision = strcmp(toAdd, stringList->next->val)) > 0) { stringList = stringList->next; } // Taki element już istnieje if (stringList->next != NULL && comparision == 0) { free((void *) toAdd); return true; } // Stworzenie nowego elementu helper = stringListElemCreate(stringList->next, toAdd); if (helper == NULL) return false; // Dodanie nowego elementu do listy stringList->next = helper; return true; } size_t stringListSize(struct StringList const *stringList) { size_t size = 0; // Sprawdzenie poprawności wejścia if (stringList == NULL) return 0; // Znalezienie długości while (stringList->next != NULL) { size++; stringList = stringList->next; } // Zwrócenie długości return size; } char const *const *stringListToStringsAndDestroy(struct StringList *stringList) { size_t size, i; char const **outList; struct StringList *helper; // Sprawdzenie poprawności wejścia if (stringList == NULL) return NULL; // Znalezienie rozmiaru listy size = stringListSize(stringList); // Zaalokowanie listy outList = malloc(size * sizeof(char *)); if (outList == NULL) return NULL; // Zwolnienie zerowego elementu listy helper = stringList; stringList = stringList->next; free(helper); // Przepisanie listy ze zwalnianiem jej i = 0; while (stringList != NULL) { // Przepisanie elementu outList[i++] = stringList->val; // Zwolnienie aktualnego elementu i skok do kolejnego helper = stringList; stringList = stringList->next; free(helper); } return outList; }
3.421875
3
2024-11-18T21:52:20.805257+00:00
2021-05-25T18:54:51
613f28c1d58fbabb71b9bf13c7329b6b8935e500
{ "blob_id": "613f28c1d58fbabb71b9bf13c7329b6b8935e500", "branch_name": "refs/heads/master", "committer_date": "2021-05-25T18:54:51", "content_id": "5eea6852a9e4efef923dfcf5827d9d2f39cfda02", "detected_licenses": [ "MIT", "CC0-1.0", "BSD-2-Clause" ], "directory_id": "830d155080fd1eee594100b0da76c8e178d0d76f", "extension": "c", "filename": "sys_write.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": 909, "license": "MIT,CC0-1.0,BSD-2-Clause", "license_type": "permissive", "path": "/src/kernel/sys/sys_write.c", "provenance": "stackv2-0138.json.gz:159729", "repo_name": "TheArduinoBoy/VisualOS", "revision_date": "2021-05-25T18:54:51", "revision_id": "1d51f9721feffa303b7ac8fd8ac5520ee5ee3732", "snapshot_id": "b09330c4860d1c634b6b75f5d2393150b6779214", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/TheArduinoBoy/VisualOS/1d51f9721feffa303b7ac8fd8ac5520ee5ee3732/src/kernel/sys/sys_write.c", "visit_date": "2023-06-09T19:53:00.922989" }
stackv2
/* * File: sys_write.c * Description: Writes a buffer to the corresponding descriptor * ***************************************************************************** * Copyright 2021 Scott Maday * Check the LICENSE file that came with this program for licensing terms */ #define __NEED_struct_iovec #include <stdio.h> #include <bits/alltypes.h> #include "shell/text.h" #include "shell/color.h" #include "log.h" #include "sys.h" uint64_t sys_write(int fd, char* buf, size_t count) { switch(fd) { case SYS_FD_STDOUT: { text_output_size(buf, count); return count; } case SYS_FD_STDERR: { log_output_size(buf, count); return count; } } return 0; } uint64_t sys_writev(int fd, struct iovec* vec, size_t vlen) { size_t total = 0; for(size_t i = 0; i < vlen; i++) { struct iovec* target = vec + i; total += sys_write(fd, target->iov_base, target->iov_len); } return total; }
2.828125
3
2024-11-18T22:02:35.767920+00:00
2023-07-10T19:21:33
dd2575f5885804607ef60aeca18ca76b88523522
{ "blob_id": "dd2575f5885804607ef60aeca18ca76b88523522", "branch_name": "refs/heads/develop", "committer_date": "2023-07-10T19:21:33", "content_id": "12bfb524b8bb5974eae51bbb409b15e95282905e", "detected_licenses": [ "MIT" ], "directory_id": "1c015973d4df0f85787c93c486ce7917c1f0af0d", "extension": "h", "filename": "debug.h", "fork_events_count": 43, "gha_created_at": "2017-12-22T03:51:02", "gha_event_created_at": "2023-09-04T05:38:49", "gha_language": "C", "gha_license_id": "MIT", "github_id": 115074220, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1874, "license": "MIT", "license_type": "permissive", "path": "/ext/agoo/debug.h", "provenance": "stackv2-0139.json.gz:107248", "repo_name": "ohler55/agoo", "revision_date": "2023-07-10T19:21:33", "revision_id": "20b47d51c1ea4b2660031f7b4bf7b9ed88413b4f", "snapshot_id": "73d4a876d79a2cd075d88f02a9260bccb031d1dd", "src_encoding": "UTF-8", "star_events_count": 853, "url": "https://raw.githubusercontent.com/ohler55/agoo/20b47d51c1ea4b2660031f7b4bf7b9ed88413b4f/ext/agoo/debug.h", "visit_date": "2023-08-31T23:12:22.615271" }
stackv2
// Copyright (c) 2018, Peter Ohler, All rights reserved. #ifndef AGOO_DEBUG_H #define AGOO_DEBUG_H #include <stdio.h> #include <stdlib.h> #include <string.h> #ifdef MEM_DEBUG #define AGOO_MALLOC(size) agoo_malloc(size, __FILE__, __LINE__) #define AGOO_CALLOC(count, size) agoo_calloc(count, size, __FILE__, __LINE__) #define AGOO_ALLOC(ptr, size) agoo_alloc(ptr, size, __FILE__, __LINE__) #define AGOO_REALLOC(ptr, size) agoo_realloc(ptr, size, __FILE__, __LINE__) #define AGOO_STRDUP(str) agoo_strdup(str, __FILE__, __LINE__) #define AGOO_STRNDUP(str, len) agoo_strndup(str, len, __FILE__, __LINE__) #define AGOO_FREE(ptr) agoo_free(ptr, __FILE__, __LINE__) #define AGOO_FREED(ptr) agoo_freed(ptr, __FILE__, __LINE__) #define AGOO_MEM_CHECK(ptr) agoo_mem_check(ptr, __FILE__, __LINE__) extern void* agoo_malloc(size_t size, const char *file, int line); extern void* agoo_calloc(size_t count, size_t size, const char *file, int line); extern void* agoo_realloc(void *ptr, size_t size, const char *file, int line); extern char* agoo_strdup(const char *str, const char *file, int line); extern char* agoo_strndup(const char *str, size_t len, const char *file, int line); extern void agoo_free(void *ptr, const char *file, int line); extern void agoo_freed(void *ptr, const char *file, int line); extern void agoo_alloc(const void *ptr, size_t size, const char *file, int line); extern void agoo_mem_check(void *ptr, const char *file, int line); #else #define AGOO_MALLOC(size) malloc(size) #define AGOO_CALLOC(count, size) calloc(count, size) #define AGOO_ALLOC(ptr, size) {} #define AGOO_REALLOC(ptr, size) realloc(ptr, size) #define AGOO_STRDUP(str) strdup(str) #define AGOO_STRNDUP(str, len) strndup(str, len) #define AGOO_FREE(ptr) free(ptr) #define AGOO_FREED(ptr) {} #define AGOO_MEM_CHECK(ptr) {} #endif extern void debug_report(); #endif /* AGOO_DEBUG_H */
2.265625
2
2024-11-18T22:02:35.891682+00:00
2018-05-09T16:56:18
e23a14571f98fdda473212e6b0ebba0938ee4bd7
{ "blob_id": "e23a14571f98fdda473212e6b0ebba0938ee4bd7", "branch_name": "refs/heads/master", "committer_date": "2018-05-09T16:57:52", "content_id": "0fac86fc9c964b1836f689f3fd17be7ea7485a70", "detected_licenses": [ "MIT" ], "directory_id": "ea0df21abb8b38fa9a5d7b9e376433da27f7c522", "extension": "c", "filename": "utl_frebyt.c", "fork_events_count": 3, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 43870594, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1052, "license": "MIT", "license_type": "permissive", "path": "/4I504 - Compilation/MIPS Analyzer/src/parsing/utl/utl_frebyt.c", "provenance": "stackv2-0139.json.gz:107376", "repo_name": "ghivert/Student-Projects", "revision_date": "2018-05-09T16:56:18", "revision_id": "43d7a61eac94365b3296ea09311f855ac00d71d1", "snapshot_id": "b5639837fc959fed9d88d91b4daf2dd30c6347e6", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/ghivert/Student-Projects/43d7a61eac94365b3296ea09311f855ac00d71d1/4I504 - Compilation/MIPS Analyzer/src/parsing/utl/utl_frebyt.c", "visit_date": "2021-01-17T18:04:16.836533" }
stackv2
/* ###--------------------------------------------------------------### */ /* file : utl_frebyt.c */ /* date : Apr 19 2004 */ /* version : v200 */ /* authors : Pirouz Bazagan Sabet */ /* description : Utility function */ /* ###--------------------------------------------------------------### */ #include <stdlib.h> #include <stdio.h> #include UTL_H /* ###--------------------------------------------------------------### */ /* function : utl_frebyt */ /* description : add an array to the table of available spaces */ /* called func. : utl_adduttyp */ /* ###--------------------------------------------------------------### */ void utl_frebyt (pt_byt, size) char *pt_byt; unsigned int size ; { struct uttyp *pt_typ ; unsigned int index ; if ((pt_byt != NULL) && (size > 0)) { index = size % UTL_BYT__TABLESIZE; pt_typ = utl_adduttyp (NULL, pt_byt, size); pt_typ->NEXT = UTL_FREBTAB [index]; UTL_FREBTAB [index] = pt_typ; } }
2.4375
2
2024-11-18T22:02:35.958588+00:00
2019-06-06T23:48:47
fe16b3e960abdb305ff878c8a249ccf42c386073
{ "blob_id": "fe16b3e960abdb305ff878c8a249ccf42c386073", "branch_name": "refs/heads/master", "committer_date": "2019-06-06T23:48:47", "content_id": "f9bf84f85c5958bb2d1a70eb447ad09c667ec73a", "detected_licenses": [ "MIT" ], "directory_id": "f47d09f661be9c8031229c95da011b6e2ad7d8eb", "extension": "c", "filename": "ms2SFSVector.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 147740276, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1872, "license": "MIT", "license_type": "permissive", "path": "/ms2SFSVector.c", "provenance": "stackv2-0139.json.gz:107504", "repo_name": "kr-colab/msUtils", "revision_date": "2019-06-06T23:48:47", "revision_id": "2c0d87747267094d2c797726cf71566526a4c216", "snapshot_id": "9c50d990cc881a3c7fd87a0f06fc0f2f5c2d7d4c", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/kr-colab/msUtils/2c0d87747267094d2c797726cf71566526a4c216/ms2SFSVector.c", "visit_date": "2022-01-26T19:15:15.618428" }
stackv2
/******* ms2SFSVector.c ******** converts ms output to SFS Vector representation. by convention fixed sites are treated as monomorphic ********************************/ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include "msGeneralStats.h" #define LINEBUF 1000000 void usage(); int maxSampleSize = 5000; int maxsites = 100000 ; int main(argc,argv) int argc; char *argv[]; { int nsam, i, howmany ; char **list, **cmatrix(), line[LINEBUF+1] ; FILE *fopen(), *pfin ; double *posit, rho, mig ; int segsites, count , nadv, npops,n1, n2; int nsites, derived_counts[maxSampleSize]; double ss; char dum[20], astr[100] ; /* read in first two lines of output (parameters and seed) */ pfin = stdin ; fgets( line, LINEBUF, pfin); sscanf(line," %s %d %d %s", dum, &nsam, &howmany, astr); fgets( line, LINEBUF, pfin); if( argc > 1 ) { nadv = atoi( argv[1] ) ; } list = cmatrix(nsam,maxsites+1); posit = (double *)malloc( maxsites*sizeof( double ) ) ; count=0; while( howmany-count++ ) { /* read in a sample */ do { fgets( line, LINEBUF, pfin); }while ( line[0] != '/' ); fscanf(pfin," segsites: %d", &segsites ); if( segsites >= maxsites){ maxsites = segsites + 10 ; posit = (double *)realloc( posit, maxsites*sizeof( double) ) ; biggerlist(nsam,maxsites, list) ; } if( segsites > 0) { fscanf(pfin," %s", astr); for( i=0; i<segsites ; i++) fscanf(pfin," %lf",posit+i) ; for( i=0; i<nsam;i++) fscanf(pfin," %s", list[i] ); } /* analyse sample ( do stuff with segsites and list) */ // printf("n1 n2 p1 p2\n"); getSiteFreqSpec(segsites,nsam,list,0,derived_counts); //print out the SFS header for(i=0;i<nsam;i++)printf("X_%d\t",i); printf("\n"); for(i=0;i<nsam;i++)printf("%d\t",derived_counts[i]); printf("\n"); printf("//\n"); } return(0); }
2.4375
2
2024-11-18T22:02:36.127627+00:00
2013-12-30T08:26:11
12610e606215f3ac0d271ec8ee5cec9c4901563e
{ "blob_id": "12610e606215f3ac0d271ec8ee5cec9c4901563e", "branch_name": "refs/heads/master", "committer_date": "2013-12-30T08:26:11", "content_id": "3908fdbe7e76f0d8849132847027775c664a63d5", "detected_licenses": [ "Unlicense" ], "directory_id": "62bbabe5820d2d10c0e7c22334ddebe9f161d631", "extension": "c", "filename": "xtrace.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": 1829, "license": "Unlicense", "license_type": "permissive", "path": "/src/xtrace.c", "provenance": "stackv2-0139.json.gz:107764", "repo_name": "sjchao/xtrace", "revision_date": "2013-12-30T08:26:11", "revision_id": "1075288fc98313e12b271b6d8b76d0e29548b0dd", "snapshot_id": "d1d80778c507ec507d38d1955436f2f9a5677120", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/sjchao/xtrace/1075288fc98313e12b271b6d8b76d0e29548b0dd/src/xtrace.c", "visit_date": "2016-09-01T21:56:40.026340" }
stackv2
#include <stdlib.h> #include <stdio.h> #include <sys/ptrace.h> #include <signal.h> #include <errno.h> #include <string.h> void getErrmsg(char*); int main(int argc, char** argv) { if (argc <= 1) { printf("Usage: xtrace pid\n"); return -1; } int pid = atoi(argv[1]); long ret = ptrace(PTRACE_ATTACH, pid, NULL, NULL); if (ret != 0) { char msg[100]; getErrmsg(msg); printf("Failed to attach to process %d\n\t%s\n", pid, msg); return -1; } printf("Attach to process %d\n", pid); ptrace(PTRACE_CONT, pid, NULL, NULL); int status; while (1) { printf("Wait process %d signal...\n", pid); waitpid(pid, &status, 0); if (WIFSTOPPED(status)) { siginfo_t siginfo; ptrace(PTRACE_GETSIGINFO, pid, NULL, &siginfo); printf("Receive signal\n\tsigno:%d pid:%d uid:%d\n", siginfo.si_signo, siginfo.si_pid, siginfo.si_uid); ptrace(PTRACE_CONT, pid, NULL, siginfo.si_signo); break; } } ptrace(PTRACE_DETACH, pid, NULL, NULL); printf("Detach from process %d\n", pid); return 0; } void getErrmsg(char* errmsg) { if (errmsg == NULL) { return; } char* msg; switch (errno) { case EBUSY: msg = "EBUSY: error with allocating or freeing a debug register."; break; case EFAULT: msg = "EFAULT: attempt to read from or write to an invalid area."; break; case EINVAL: msg = "EINVAL: attemp to set an invalid option."; break; case EIO: msg = "EIO: request is invalid."; break; case EPERM: msg = "EPERM: the specified process cannot be tarced, maybe you need more privileges."; break; case ESRCH: msg = "ESRCH: the specified process does not exist."; break; default: msg = "Unknown error"; break; } memcpy(errmsg, msg, strlen(msg)); }
2.671875
3
2024-11-18T22:02:36.231407+00:00
2016-01-15T19:18:26
2df5b22e6e68c083820e6ed6398828ede1fea035
{ "blob_id": "2df5b22e6e68c083820e6ed6398828ede1fea035", "branch_name": "refs/heads/master", "committer_date": "2016-01-15T19:18:26", "content_id": "fcb171094d9a1310ffaf2646c76cb91f2c63bb3a", "detected_licenses": [ "MIT" ], "directory_id": "387b2c3208310ad3a1e534efb92a004d12377448", "extension": "c", "filename": "tyran_symbol_table.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": 1606, "license": "MIT", "license_type": "permissive", "path": "/src/tyranscript/lib/tyran_symbol_table.c", "provenance": "stackv2-0139.json.gz:107895", "repo_name": "biddyweb/TyranEngine", "revision_date": "2016-01-15T19:18:26", "revision_id": "f1575c9d0346fd93aa73d0ed247a721e472e3d21", "snapshot_id": "38d090fe7bb47094a32cea456c50e9234b3ec394", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/biddyweb/TyranEngine/f1575c9d0346fd93aa73d0ed247a721e472e3d21/src/tyranscript/lib/tyran_symbol_table.c", "visit_date": "2021-01-18T10:11:47.832195" }
stackv2
#include <tyranscript/tyran_symbol_table.h> #include <tyranscript/tyran_symbol.h> #include <tyranscript/tyran_memory.h> #include <tyranscript/tyran_clib.h> #include <tyranscript/tyran_log.h> tyran_symbol_table* tyran_symbol_table_new(tyran_memory* memory) { tyran_symbol_table* table = TYRAN_MALLOC_NO_POOL_TYPE(memory, tyran_symbol_table); table->entries_max_count = 512; table->entries = TYRAN_MEMORY_CALLOC_TYPE_COUNT(memory, tyran_symbol_table_entry, table->entries_max_count); table->entry_count = 0; table->memory = memory; return table; } void tyran_symbol_table_free(tyran_symbol_table* table) { for (int i = 0; i < table->entry_count; ++i) { tyran_free((void*) table->entries[i].string); } tyran_free(table); } int tyran_symbol_table_find(tyran_symbol_table* table, const char* str) { for (int i = 0; i < table->entry_count; ++i) { if (tyran_strcmp(table->entries[i].string, str) == 0) { return i; } } return -1; } void tyran_symbol_table_add(tyran_symbol_table* table, tyran_symbol* symbol, const char* str) { int index = tyran_symbol_table_find(table, str); if (index == -1) { index = table->entry_count; TYRAN_ASSERT(table->entry_count < table->entries_max_count, "Out of memory"); table->entry_count++; tyran_symbol_table_entry* entry = &table->entries[index]; entry->string = tyran_strdup(table->memory, str); TYRAN_LOG("symbol_table set: #%d '%s'", index, entry->string); } symbol->hash = index; } const char* tyran_symbol_table_lookup(const tyran_symbol_table* table, const tyran_symbol* symbol) { return table->entries[symbol->hash].string; }
2.6875
3
2024-11-18T22:02:36.545954+00:00
2022-04-19T13:57:58
666fb69bb02fd58483e2be3dd94db697cd17cd86
{ "blob_id": "666fb69bb02fd58483e2be3dd94db697cd17cd86", "branch_name": "refs/heads/master", "committer_date": "2022-06-27T10:51:02", "content_id": "c50576b33addfdc383a75706ff9af1ba2ccb0847", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "99ffc8da5d27bd1fd7e1082da6911e1ff984dd2f", "extension": "h", "filename": "mod_morello_sensor_driver.h", "fork_events_count": 0, "gha_created_at": "2019-06-18T10:29:53", "gha_event_created_at": "2019-06-18T10:29:54", "gha_language": null, "gha_license_id": "NOASSERTION", "github_id": 192518458, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1162, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/product/morello/module/morello_sensor/src/mod_morello_sensor_driver.h", "provenance": "stackv2-0139.json.gz:108411", "repo_name": "brett-warren-arm/SCP-firmware", "revision_date": "2022-04-19T13:57:58", "revision_id": "a1f9172300e5cc3379773b7816b5a6793d35ccd1", "snapshot_id": "f1f6f555fb8aac149c027c53f0e7147d5979172d", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/brett-warren-arm/SCP-firmware/a1f9172300e5cc3379773b7816b5a6793d35ccd1/product/morello/module/morello_sensor/src/mod_morello_sensor_driver.h", "visit_date": "2022-10-01T15:45:20.867072" }
stackv2
/* * Arm SCP/MCP Software * Copyright (c) 2021, Arm Limited and Contributors. All rights reserved. * * SPDX-License-Identifier: BSD-3-Clause */ #ifndef MOD_MORELLO_SENSOR_DRIVER_H #define MOD_MORELLO_SENSOR_DRIVER_H #include <mod_morello_sensor.h> /*! * \brief Get the sampled value of the sensor * * \param value Sampled value of the sensor. * \param type Sensor type which should be sampled. * \param offset Instance of the sensor type which should be sampled. * * \retval ::FWK_SUCCESS Operation succeeded. * \return One of the other specific error codes described by the framework. */ int morello_sensor_lib_sample( int32_t *value, enum sensor_type type, int offset); /*! * \brief Trigger sampling of the sensor. * * \param type Sensor type which should be sampled. * * \retval NONE */ void morello_sensor_lib_trigger_sample(enum sensor_type type); /*! * \brief Intialize the sensor. * * \param msg Information regarding the sensor. * * \retval ::FWK_SUCCESS Operation succeeded. * \return One of the other specific error codes described by the framework. */ int morello_sensor_lib_init(uint32_t *msg); #endif
2.140625
2
2024-11-18T22:02:41.497184+00:00
2021-03-24T12:05:18
a9eb265c1d92de58b8b1c45489d0e5329b6dd042
{ "blob_id": "a9eb265c1d92de58b8b1c45489d0e5329b6dd042", "branch_name": "refs/heads/main", "committer_date": "2021-03-24T12:05:18", "content_id": "50b9727d061f4f35d0fa0da3a794a39503443d26", "detected_licenses": [ "MIT" ], "directory_id": "7edb1623b51db39907cbfff71375d0b93feedabc", "extension": "h", "filename": "cbl.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 349222685, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2310, "license": "MIT", "license_type": "permissive", "path": "/C/includes/cbl.h", "provenance": "stackv2-0139.json.gz:108933", "repo_name": "Unam3dd/CBL", "revision_date": "2021-03-24T12:05:18", "revision_id": "66089d79df3fb5965f549eaa26bcfa60c5b123f8", "snapshot_id": "dc08aabe8e8d464e169ca54725ae90c045ef357a", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/Unam3dd/CBL/66089d79df3fb5965f549eaa26bcfa60c5b123f8/C/includes/cbl.h", "visit_date": "2023-03-15T01:24:25.890506" }
stackv2
#pragma once #include <stdint.h> // utils.c int to_int(char *str); long long to_long_long(char *str); uint8_t int_to_str(int dec, char *buffer, size_t size); uint8_t long_long_to_str(long long dec, char *buffer, size_t size); char chr_to_lower(char c); char chr_to_upper(char c); int reverse_integer(int n); void convert_letter_in_upper(char *str); size_t string_len(char *str); // base16.c static char BASE16_TABLE[16] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; uint8_t hex_nibble(char c); uint8_t hex_encode(char *str, char *output, size_t output_size); uint8_t hex_decode(char *str, char *output, size_t output_size); // base32.c static char BASE32_TABLE[] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '2', '3', '4', '5', '6', '7'}; uint64_t get_base32_encoded_size(uint64_t len); uint64_t get_base32_decoded_size(uint64_t len); int return_index_base32(char c); uint8_t base32_encode(char *buffer, char *output, uint64_t size_output); uint8_t base32_decode(char *buffer, char *output, uint64_t size_output); // base64.c #define DECODING_TABLE_IS_NULL (DECODING_TABLE == NULL) static char BASE64_TABLE[] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'}; static unsigned char *DECODING_TABLE = NULL; uint64_t get_base64_padded_size(uint64_t len); uint64_t get_ascii_size_from_base64(uint64_t len); uint32_t base64_encode(char *buffer, char *output, uint64_t len_output_buffer); uint32_t base64_decode(char *buffer, char *output, uint64_t len_output_buffer); void make_decoding_table(void); void free_decoding_table(void);
2.25
2
2024-11-18T22:02:41.783403+00:00
2019-05-07T20:59:17
37804617ac183e89b3870dbea5b022b7dd757a0e
{ "blob_id": "37804617ac183e89b3870dbea5b022b7dd757a0e", "branch_name": "refs/heads/master", "committer_date": "2019-05-07T20:59:17", "content_id": "98a744ac1d6211560b23283b1ea88c9a6372a33d", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "0653d544fed62c4db586b831a8146ebf2f7b14b8", "extension": "h", "filename": "lmp_testbit.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 179370781, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 284, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/src/generic/lmp_testbit.h", "provenance": "stackv2-0139.json.gz:109193", "repo_name": "lpeterse/lmp", "revision_date": "2019-05-07T20:59:17", "revision_id": "39038886e016bec9fb76fcaa05f7560c8189e9d6", "snapshot_id": "6aa930329310ee26f07915669c1aaa62ad03ac8e", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/lpeterse/lmp/39038886e016bec9fb76fcaa05f7560c8189e9d6/src/generic/lmp_testbit.h", "visit_date": "2020-05-04T18:53:45.078579" }
stackv2
#ifndef LMP_TESTBIT inline size_t lmp_testbit( const lmp_limb_t *const restrict ap, const size_t an, const size_t bi) { size_t ai = bi / LMP_LIMB_W; size_t wi = bi % LMP_LIMB_W; return ai < an && (ap[ai] & (1 << wi)); } #endif
2.046875
2
2024-11-18T22:02:41.924535+00:00
2023-08-30T05:21:33
695eb114c3d948bd8ae8576a2f7ea880d8a25fa6
{ "blob_id": "695eb114c3d948bd8ae8576a2f7ea880d8a25fa6", "branch_name": "refs/heads/master", "committer_date": "2023-08-30T05:21:33", "content_id": "9de143e820fd187579521eff4a31943e7abd8abb", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "3b1223e5259c580cbf107d1f45960d9f08aff27f", "extension": "c", "filename": "test285.c", "fork_events_count": 11, "gha_created_at": "2018-02-24T21:36:31", "gha_event_created_at": "2023-01-24T08:36:57", "gha_language": "C", "gha_license_id": null, "github_id": 122781887, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 682, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/OS2/tests/test285/test285.c", "provenance": "stackv2-0139.json.gz:109455", "repo_name": "osfree-project/osfree", "revision_date": "2023-08-30T05:21:33", "revision_id": "04ba405e346948ef0ae1a1b483aeb76f044c50a0", "snapshot_id": "6be0fe3e2fb5ef577650b7a3a9eee1f38fb2eb8b", "src_encoding": "UTF-8", "star_events_count": 105, "url": "https://raw.githubusercontent.com/osfree-project/osfree/04ba405e346948ef0ae1a1b483aeb76f044c50a0/OS2/tests/test285/test285.c", "visit_date": "2023-09-02T21:38:29.849765" }
stackv2
#define INCL_GPIPATHS /* GPI Path functions */ #include <os2.h> int main(VOID) { HPS hps; /* presentation space handle */ POINTL ptlStart = { 0, 0 }; /* first vertex */ POINTL ptlTriangle[] = { 100, 100, 200, 0, 0, 0 }; /* vertices */ GpiBeginPath(hps, 1L); /* creates path */ GpiMove(hps, &ptlStart); GpiPolyLine(hps, 3L, ptlTriangle); GpiEndPath(hps); GpiModifyPath(hps, 1L, MPATH_STROKE); /* modifies path for wide line */ GpiFillPath(hps, 1L, FPATH_ALTERNATE); /* draws the wide line */ return 0; }
2.28125
2
2024-11-18T22:02:42.152914+00:00
2016-12-08T04:52:26
1e60b9b799469023075c00ea6534d75514b43f90
{ "blob_id": "1e60b9b799469023075c00ea6534d75514b43f90", "branch_name": "refs/heads/master", "committer_date": "2016-12-08T04:52:26", "content_id": "a61f24c57168d962118ff4362e2bafbfd76c4117", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "f96a001244df5f6379409b639f250ef60d363d17", "extension": "c", "filename": "stack.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 75903906, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1546, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/tinycalc/stack.c", "provenance": "stackv2-0139.json.gz:109713", "repo_name": "Dakta/tinycalc", "revision_date": "2016-12-08T04:52:26", "revision_id": "1c874eb380c83694babbc255b6a836a82ddc0b2b", "snapshot_id": "9a35b56756585391ff5b59eb4d9680e556d7daca", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Dakta/tinycalc/1c874eb380c83694babbc255b6a836a82ddc0b2b/tinycalc/stack.c", "visit_date": "2020-06-10T18:59:42.278160" }
stackv2
// // stack.c // tinycalc // // Created by Dakota Schneider on 12/2/16. // Copyright © 2016 Code From Above. All rights reserved. // #include "stack.h" #include <stdlib.h> Stack * newStack() { Stack * stack= malloc(sizeof(StackNode)); if (!stack) return NULL; stack->size = 0; stack->top = NULL; return stack; } StackNode * push(Stack * stack, TypeVal * val) { StackNode * node = malloc(sizeof(StackNode)); if (!node) return NULL; node->val = TypeVal_copy(val); node->prev = stack->top; stack->top = node; stack->size++; return node; } TypeVal * pop(Stack * stack) { if (stack->top != NULL) { TypeVal * val = stack->top->val; StackNode * prev = stack->top->prev; free(stack->top); stack->top = prev; stack->size--; return val; } else { // error condition, empty stack } return 0; } TypeVal * get(Stack * stack, intmax_t idx) { // stack overflow? if (idx >= stack->size) { return NULL; } // otherwise StackNode * node = stack->top; for (int i = 0; i < idx; i++) { node = node->prev; } return TypeVal_copy(node->val); } TypeVal * set(Stack * stack, intmax_t idx, TypeVal * val) { // stack overflow? if (idx >= stack->size) { return NULL; } // otherwise StackNode * node = stack->top; for (int i = 0; i < idx; i++) { node = node->prev; } return node->val = TypeVal_copy(val); }
3
3
2024-11-18T22:02:42.388794+00:00
2020-09-30T15:34:02
cefec8dfebb19fb276afa2a97b5600d195a74c82
{ "blob_id": "cefec8dfebb19fb276afa2a97b5600d195a74c82", "branch_name": "refs/heads/master", "committer_date": "2020-09-30T15:34:02", "content_id": "38ab69d255803f475450e6a30a6a5fa9df8c95d6", "detected_licenses": [ "MIT" ], "directory_id": "3ac78caf28163a075b51f3216f83a998e515f894", "extension": "h", "filename": "queue.h", "fork_events_count": 1, "gha_created_at": "2015-11-17T19:00:35", "gha_event_created_at": "2022-12-09T11:45:41", "gha_language": "C", "gha_license_id": null, "github_id": 46368605, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4717, "license": "MIT", "license_type": "permissive", "path": "/toys/cbox/messaging/mque/queue.h", "provenance": "stackv2-0139.json.gz:109973", "repo_name": "walrus7521/code", "revision_date": "2020-09-30T15:34:02", "revision_id": "29e07e4cfc904e9f1a4455ced202506e3807f74c", "snapshot_id": "566fe5b6f96e91577cf2147d5a8c6f3996dab08c", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/walrus7521/code/29e07e4cfc904e9f1a4455ced202506e3807f74c/toys/cbox/messaging/mque/queue.h", "visit_date": "2022-12-14T03:40:11.237082" }
stackv2
#ifndef QUEUE_H #define QUEUE_H #include <stdint.h> #include <stdbool.h> #include <string.h> enum enqueue_result { ENQUEUE_RESULT_SUCCESS, ENQUEUE_RESULT_FULL, }; enum dequeue_result { DEQUEUE_RESULT_SUCCESS, DEQUEUE_RESULT_EMPTY, }; #define ARRAY_LENGTH(A) (sizeof(A)/sizeof((A)[0])) #define QUEUE_DECLARATION(NAME, ITEM_TYPE, NUM_ITEMS) \ struct NAME { \ uint16_t read_idx; \ uint16_t write_idx; \ ITEM_TYPE items[NUM_ITEMS]; \ }; \ void NAME ## _init(struct NAME * p_queue); \ enum enqueue_result NAME ##_enqueue(struct NAME * p_queue, ITEM_TYPE * p_new_item); \ enum dequeue_result NAME ##_dequeue(struct NAME * p_queue, ITEM_TYPE * p_item_out); \ bool NAME ##_is_empty(struct NAME * p_queue); #define QUEUE_DEFINITION(NAME, ITEM_TYPE, NUM_ITEMS) \ void NAME ## _init(struct NAME * p_queue) \ { \ *p_queue = (struct NAME){ \ .read_idx = 0, \ .write_idx = 0, \ .items = {} \ }; \ } \ \ enum enqueue_result NAME ##_enqueue(struct NAME * p_queue, ITEM_TYPE * p_new_item) { \ uint16_t elements_in = p_queue->write_idx - p_queue->read_idx; \ \ size_t const capacity = ARRAY_LENGTH(p_queue->items); \ if (elements_in == capacity) { \ return ENQUEUE_RESULT_FULL; \ } \ \ uint16_t i = (p_queue->write_idx)++ & (capacity - 1); \ p_queue->items[i] = *p_new_item; \ return ENQUEUE_RESULT_SUCCESS; \ } \ \ enum dequeue_result NAME ##_dequeue(struct NAME * p_queue, ITEM_TYPE * p_item_out) { \ uint16_t elements_in = p_queue->write_idx - p_queue->read_idx; \ size_t const capacity = ARRAY_LENGTH(p_queue->items); \ \ if(elements_in == 0) { \ return DEQUEUE_RESULT_EMPTY; \ } \ \ uint16_t i = (p_queue->read_idx)++ & (capacity - 1); \ *p_item_out = p_queue->items[i]; \ \ return DEQUEUE_RESULT_SUCCESS; \ } \ \ bool NAME ##_is_empty(struct NAME * p_queue) { \ return ((p_queue->write_idx - p_queue->read_idx) == 0); \ } #endif
2.734375
3
2024-11-18T22:02:42.451535+00:00
2019-07-05T15:59:48
1f58bc5a1ad5c865fbf9d29702485afff4cbafea
{ "blob_id": "1f58bc5a1ad5c865fbf9d29702485afff4cbafea", "branch_name": "refs/heads/master", "committer_date": "2019-07-05T15:59:48", "content_id": "ac57ee0307220e7ea2b2141a2449e1a9f5dff44b", "detected_licenses": [ "MIT" ], "directory_id": "771f0672af49ab9e95d614c75ae591bb43baee9f", "extension": "c", "filename": "obj_rotatable_light.c", "fork_events_count": 0, "gha_created_at": "2019-01-22T12:40:41", "gha_event_created_at": "2019-05-13T19:39:48", "gha_language": "C", "gha_license_id": "MIT", "github_id": 166992155, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1009, "license": "MIT", "license_type": "permissive", "path": "/client/game/objects/main/light/obj_rotatable_light.c", "provenance": "stackv2-0139.json.gz:110102", "repo_name": "Coestaris/Zomboid2.0", "revision_date": "2019-07-05T15:59:48", "revision_id": "5632b3fafdb90afb48fb6bd0ee3bc3625aa5e39b", "snapshot_id": "3c8e4bff1e016874c38b64224662eddb7ccf40d8", "src_encoding": "UTF-8", "star_events_count": 4, "url": "https://raw.githubusercontent.com/Coestaris/Zomboid2.0/5632b3fafdb90afb48fb6bd0ee3bc3625aa5e39b/client/game/objects/main/light/obj_rotatable_light.c", "visit_date": "2020-04-17T22:22:39.107892" }
stackv2
// // Created by maxim on 2/8/19. // #include "obj_rotatable_light.h" void rotatableLight_update(gameObject_t* this, void* data) { rotatableLight_data_t* ld = (rotatableLight_data_t*) this->data; ld->obj->angle += ld->speed; ld->obj->pos = vec_add(this->pos, vec_mult(vec( cos(ld->obj->angle), sin(ld->obj->angle)), 40)); } void rotatableLight_init(gameObject_t* this) { rotatableLight_data_t* ld = (rotatableLight_data_t*) this->data; evqSubscribeEvent(this, EVT_Update, rotatableLight_update); scmPushObject(ld->obj); } gameObject_t* create_rotatableLight(vec_t pos, double speed, gameObject_t* light) { gameObject_t* this = object(); this->data = malloc(sizeof(rotatableLight_data_t)); rotatableLight_data_t* ld = (rotatableLight_data_t*) this->data; ld->speed = speed; ld->obj = light; light->pos = pos; this->pos = pos; light->angle = randAngle(); this->pos = pos; this->onInit = rotatableLight_init; return this; }
2.40625
2
2024-11-18T22:02:42.575171+00:00
2023-02-20T04:47:34
59a11c9755862848f0f86d5d5d7c879568b6e1cf
{ "blob_id": "59a11c9755862848f0f86d5d5d7c879568b6e1cf", "branch_name": "refs/heads/master", "committer_date": "2023-02-20T04:47:34", "content_id": "b9ec7126324c63f5eedbfcf0993392a06a738371", "detected_licenses": [ "BSD-3-Clause", "Apache-2.0" ], "directory_id": "5d10803709cf47332ad49a137a571c6bd2ff7129", "extension": "c", "filename": "fam_test.c", "fork_events_count": 18, "gha_created_at": "2011-12-19T12:48:13", "gha_event_created_at": "2023-02-20T04:47:35", "gha_language": "Shell", "gha_license_id": "NOASSERTION", "github_id": 3011899, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4989, "license": "BSD-3-Clause,Apache-2.0", "license_type": "permissive", "path": "/tests/fam_test.c", "provenance": "stackv2-0139.json.gz:110231", "repo_name": "mfranberg/libplinkio", "revision_date": "2023-02-20T04:47:34", "revision_id": "2a8ea561d666d3eb604843131d7578badc885d27", "snapshot_id": "ba2f6ecc69c37ba9257d663ae28b2b3a6411a5aa", "src_encoding": "UTF-8", "star_events_count": 44, "url": "https://raw.githubusercontent.com/mfranberg/libplinkio/2a8ea561d666d3eb604843131d7578badc885d27/tests/fam_test.c", "visit_date": "2023-03-08T06:36:15.116907" }
stackv2
#include <stdarg.h> #include <stddef.h> #include <setjmp.h> #include <stdlib.h> #include <stdio.h> #include <math.h> #include <cmockery.h> #include <fam.h> #include <fam.c> #include <fam_parse.c> #include "plink_txt_parse.c" #include "mock.h" /** * Tests that iids are correctly parsed. */ void test_parse_iid(void **state) { UNUSED_PARAM(state); const char *TEST_STRING = "F1"; pio_status_t status; char *iid = libplinkio_parse_str_( TEST_STRING, strlen( TEST_STRING ), &status ); assert_int_equal( status, PIO_OK ); assert_string_equal( iid, TEST_STRING ); free( iid ); } /** * Tests that sex is correctly parsed. */ void test_parse_sex(void **state) { UNUSED_PARAM(state); const char *TEST_STRING_MALE = "1"; const char *TEST_STRING_FEMALE = "2"; const char *TEST_STRING_UNKNOWN = "0"; pio_status_t status; enum sex_t sex; sex = libplinkio_parse_sex_( TEST_STRING_MALE, strlen( TEST_STRING_MALE ), &status ); assert_int_equal( status, PIO_OK ); assert_int_equal( sex, PIO_MALE ); sex = libplinkio_parse_sex_( TEST_STRING_FEMALE, strlen( TEST_STRING_FEMALE ), &status ); assert_int_equal( status, PIO_OK ); assert_int_equal( sex, PIO_FEMALE ); sex = libplinkio_parse_sex_( TEST_STRING_UNKNOWN, strlen( TEST_STRING_UNKNOWN ), &status ); assert_int_equal( status, PIO_OK ); assert_int_equal( sex, PIO_UNKNOWN ); } /** * Tests that a phenotype is correctly parsed. */ void test_parse_phenotype(void **state) { UNUSED_PARAM(state); const char *TEST_STRING_CONTROL = "1"; const char *TEST_STRING_CASE = "2"; const char *TEST_STRING_PHENOTYPE = "1.0"; const char *TEST_STRING_MISSING = "-9"; const char *TEST_STRING_MISSING_NA = "NA"; struct pio_sample_t sample; pio_status_t status; libplinkio_parse_phenotype_( TEST_STRING_CONTROL, strlen( TEST_STRING_CONTROL ), &sample, &status ); assert_int_equal( status, PIO_OK ); assert_int_equal( sample.affection, PIO_CONTROL ); libplinkio_parse_phenotype_( TEST_STRING_CASE, strlen( TEST_STRING_CASE ), &sample, &status ); assert_int_equal( status, PIO_OK ); assert_int_equal( sample.affection, PIO_CASE ); libplinkio_parse_phenotype_( TEST_STRING_PHENOTYPE, strlen( TEST_STRING_PHENOTYPE ), &sample, &status ); assert_int_equal( status, PIO_OK ); assert_int_equal( sample.affection, PIO_CONTINUOUS ); assert_true( fabs( sample.phenotype - 1.0 ) <= 1e-6 ); libplinkio_parse_phenotype_( TEST_STRING_MISSING, strlen( TEST_STRING_MISSING ), &sample, &status ); assert_int_equal( status, PIO_OK ); assert_int_equal( sample.affection, PIO_MISSING ); assert_true( fabs( sample.phenotype - (-9.0) ) <= 1e-6 ); libplinkio_parse_phenotype_( TEST_STRING_MISSING_NA, strlen( TEST_STRING_MISSING_NA ), &sample, &status ); assert_int_equal( status, PIO_OK ); assert_int_equal( sample.affection, PIO_MISSING ); assert_true( fabs( sample.phenotype - (-9.0) ) <= 1e-6 ); } /** * Tests the parsing of multiple samples. Since parse_samples uses * IO functions, we need to have mocked versions for these. */ void test_parse_multiple_samples(void **state) { UNUSED_PARAM(state); struct pio_sample_t person; struct pio_fam_file_t fam_file; mock_init( "F1 P1 0 0 1 1\nF1\t P2 0 0 2 2" ); assert_int_equal( fam_open( &fam_file, "" ), PIO_OK ); assert_int_equal( fam_num_samples( &fam_file ), 2 ); person = *fam_get_sample( &fam_file, 0 ); assert_string_equal( person.fid, "F1" ); assert_string_equal( person.iid, "P1" ); assert_string_equal( person.father_iid, "0" ); assert_string_equal( person.mother_iid, "0" ); assert_int_equal( person.sex, PIO_MALE ); assert_int_equal( person.affection, PIO_CONTROL ); person = *fam_get_sample( &fam_file, 1 ); assert_string_equal( person.fid, "F1" ); assert_string_equal( person.iid, "P2" ); assert_string_equal( person.father_iid, "0" ); assert_string_equal( person.mother_iid, "0" ); assert_int_equal( person.sex, PIO_FEMALE ); assert_int_equal( person.affection, PIO_CASE ); fam_close( &fam_file ); } /** * Cmockerys initial implementation couldn't handle realloc, * this test make sure that it works as intended. */ void test_utarray(void **state) { UNUSED_PARAM(state); UT_array *samples; struct pio_sample_t person1 = {0}; struct pio_sample_t person2 = {0}; utarray_new( samples, &LIBPLINKIO_SAMPLE_ICD_ ); utarray_push_back( samples, &person1 ); utarray_push_back( samples, &person2 ); utarray_free( samples ); } int main(int argc, char* argv[]) { UNUSED_PARAM(argc); UNUSED_PARAM(argv); const UnitTest tests[] = { unit_test( test_parse_iid ), unit_test( test_parse_sex ), unit_test( test_parse_phenotype ), unit_test( test_parse_multiple_samples ), unit_test( test_utarray ), }; return run_tests( tests ); }
2.171875
2
2024-11-18T22:02:42.663987+00:00
2018-08-28T20:51:36
2e49d1975b241e2e0f29292b9cdff0c7e523b6e9
{ "blob_id": "2e49d1975b241e2e0f29292b9cdff0c7e523b6e9", "branch_name": "refs/heads/master", "committer_date": "2018-08-28T20:51:36", "content_id": "12f9a9a39e47182e3cd841983b149c7b5d3fad24", "detected_licenses": [ "MIT" ], "directory_id": "8722e20e5de43c099dc44998853079eecb8cab92", "extension": "c", "filename": "meshConnectTri2D.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": 1290, "license": "MIT", "license_type": "permissive", "path": "/src/meshConnectTri2D.c", "provenance": "stackv2-0139.json.gz:110361", "repo_name": "alanngh/MATH5414FA18", "revision_date": "2018-08-28T20:51:36", "revision_id": "e2342276bde51e18a4154f2241bb5682d563ca4f", "snapshot_id": "c44c5898f636c1ed85b20f4a5e5a76f1d8e4d6a7", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/alanngh/MATH5414FA18/e2342276bde51e18a4154f2241bb5682d563ca4f/src/meshConnectTri2D.c", "visit_date": "2020-03-27T16:49:36.378348" }
stackv2
#include "mesh.h" typedef struct { int element; int face; int v1; int v2; }face_t; int compareFaces(const void *a, const void*b){ face_t *faceA = (face_t*) a; face_t *faceB = (face_t*) b; // assume that v1 is the 2nd digit if(faceA->v1 < faceB->v1) return -1; if(faceA->v1 > faceB->v1) return +1; if(faceA->v2 < faceB->v2) return -1; if(faceA->v2 > faceB->v2) return +1; return 0; } void meshConnectTri2D(mesh_t *mesh){ int sortNfaces = mesh->Nelements*mesh->Nfaces; face_t *faces = (face_t*) calloc(sortNfaces, sizeof(face_t)); for(int e=0;e<mesh->Nelements;++e){ for(int f=0;f<mesh->Nfaces;++f){ int id = e*mesh->Nfaces + f; faces[id].element = e; faces[id].face = f; faces[id].v1 = mesh->EToV[e*mesh->Nverts + f]; faces[id].v2 = mesh->EToV[e*mesh->Nverts + (f+1)%mesh->Nverts]; if(faces[id].v1 < faces[id].v2){ int tmp = faces[id].v1; faces[id].v1 = faces[id].v2; faces[id].v2 = tmp; } } } // sort by double face vertices qsort(faces, sortNfaces, sizeof(face_t), compareFaces); for(int f=0;f<mesh->Nfaces*mesh->Nelements;++f){ printf("f: %d => %d,%d (%d,%d)\n", f, faces[f].v1, faces[f].v2, faces[f].element, faces[f].face); } }
3
3