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:19:18.962330+00:00
2018-04-16T03:15:27
ffa2cb0b20f021f55e5ff5d747461c003c8ebc27
{ "blob_id": "ffa2cb0b20f021f55e5ff5d747461c003c8ebc27", "branch_name": "refs/heads/master", "committer_date": "2018-04-16T03:15:27", "content_id": "a3b75562b57b239f5eb7f1db70e47e4b756568bb", "detected_licenses": [ "MIT" ], "directory_id": "0496ca27a706e86ff37dfd7f3739e7a6684c0ea2", "extension": "h", "filename": "poly_utils.h", "fork_events_count": 0, "gha_created_at": "2018-03-20T02:05:00", "gha_event_created_at": "2018-03-20T02:05:00", "gha_language": null, "gha_license_id": null, "github_id": 125946674, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1294, "license": "MIT", "license_type": "permissive", "path": "/src/poly_utils.h", "provenance": "stackv2-0128.json.gz:308490", "repo_name": "trort/CarND-MPC-Project", "revision_date": "2018-04-16T03:15:27", "revision_id": "a1fc4476d2d0c57a467e42f669e064bae0f43071", "snapshot_id": "f5e5883a668a40410fc3f8a70ae04c2b5f6a7d88", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/trort/CarND-MPC-Project/a1fc4476d2d0c57a467e42f669e064bae0f43071/src/poly_utils.h", "visit_date": "2021-04-12T03:31:10.724783" }
stackv2
// // Created by trort on 4/1/18. // #ifndef MPC_POLY_UTILS_H #define MPC_POLY_UTILS_H #include "Eigen-3.3/Eigen/Core" #include "Eigen-3.3/Eigen/QR" // Evaluate a polynomial. inline double polyeval(Eigen::VectorXd coeffs, double x) { double result = 0.0; for (int i = 0; i < coeffs.size(); i++) { result += coeffs[i] * pow(x, i); } return result; } // Evaluate the derivative of a polynomial. inline double polyderivative(Eigen::VectorXd coeffs, double x) { double result = 0.0; for (int i = 1; i < coeffs.size(); i++) { result += i * coeffs[i] * pow(x, i - 1); } return result; } // Fit a polynomial. // Adapted from // https://github.com/JuliaMath/Polynomials.jl/blob/master/src/Polynomials.jl#L676-L716 inline Eigen::VectorXd polyfit(Eigen::VectorXd xvals, Eigen::VectorXd yvals, int order) { assert(xvals.size() == yvals.size()); assert(order >= 1 && order <= xvals.size() - 1); Eigen::MatrixXd A(xvals.size(), order + 1); for (int i = 0; i < xvals.size(); i++) { A(i, 0) = 1.0; } for (int j = 0; j < xvals.size(); j++) { for (int i = 0; i < order; i++) { A(j, i + 1) = A(j, i) * xvals(j); } } auto Q = A.householderQr(); auto result = Q.solve(yvals); return result; } #endif //MPC_POLY_UTILS_H
2.453125
2
2024-11-18T21:19:19.221818+00:00
2021-07-17T19:29:29
e94f185e1b696d09056c63a26ad66d3405f66656
{ "blob_id": "e94f185e1b696d09056c63a26ad66d3405f66656", "branch_name": "refs/heads/master", "committer_date": "2021-07-17T19:29:29", "content_id": "1ab979e696a19629a825234a6a009b80501ae03b", "detected_licenses": [ "MIT" ], "directory_id": "9183e0e802460059ef6ac3aa414eb94aee4e3805", "extension": "h", "filename": "lc_array.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 327522044, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1111, "license": "MIT", "license_type": "permissive", "path": "/include/liteco/lc_array.h", "provenance": "stackv2-0128.json.gz:308620", "repo_name": "OpenQUIC/liteco", "revision_date": "2021-07-17T19:29:29", "revision_id": "dd40527ed53a17462532eb42ea34d2bc6f948b92", "snapshot_id": "94c3f0ba79cc14f7b04656b2db97a5c83124244b", "src_encoding": "UTF-8", "star_events_count": 3, "url": "https://raw.githubusercontent.com/OpenQUIC/liteco/dd40527ed53a17462532eb42ea34d2bc6f948b92/include/liteco/lc_array.h", "visit_date": "2023-06-14T16:07:37.057631" }
stackv2
/* * Copyright (c) 2021 Gscienty <gaoxiaochuan@hotmail.com> * * Distributed under the MIT software license, see the accompanying * file LICENSE or https://www.opensource.org/licenses/mit-license.php . * */ #ifndef __LITECO_ARRAY_H__ #define __LITECO_ARRAY_H__ #include <stdint.h> #include <stddef.h> #include <sys/cdefs.h> #if __linux__ #include <malloc.h> #elif __APPLE__ #include <stdlib.h> #include <sys/malloc.h> #endif typedef struct liteco_array_s liteco_array_t; struct liteco_array_s { uint32_t ele_count; uint32_t ele_size; uint8_t payload[0]; }; #define liteco_array_get(arr, i) \ ((arr)->payload + ((arr)->ele_size * (i))) #ifdef __header_always_inline __header_always_inline liteco_array_t *liteco_array_create(uint32_t ele_count, uint32_t ele_size) { #else __always_inline liteco_array_t *liteco_array_create(uint32_t ele_count, uint32_t ele_size) { #endif liteco_array_t *arr = malloc(sizeof(liteco_array_t) + ele_count * ele_size); if (!arr) { return NULL; } arr->ele_count = ele_count; arr->ele_size = ele_size; return arr; } #endif
2.46875
2
2024-11-18T21:19:19.525302+00:00
2020-04-29T23:23:19
e66367ee722db3f7f020b2ef1bfbfd26025f1997
{ "blob_id": "e66367ee722db3f7f020b2ef1bfbfd26025f1997", "branch_name": "refs/heads/master", "committer_date": "2020-04-29T23:23:19", "content_id": "7de4ed3ab1464288c5ea6b658d302279f0b0cf74", "detected_licenses": [ "MIT" ], "directory_id": "7caa1206facfdf588dd86d9383d0518bc2561058", "extension": "h", "filename": "led_driver.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 236864961, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1039, "license": "MIT", "license_type": "permissive", "path": "/Lab7/Wright_RTOS_Lab7_SharedResource/src/Header_Files/led_driver.h", "provenance": "stackv2-0128.json.gz:308886", "repo_name": "derekwright29/RTOS", "revision_date": "2020-04-29T23:23:19", "revision_id": "fa4981fbd50ac1d70ed3ac960562013bd42ee87d", "snapshot_id": "8d24120eb39d6282a76176aad35eb16121329307", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/derekwright29/RTOS/fa4981fbd50ac1d70ed3ac960562013bd42ee87d/Lab7/Wright_RTOS_Lab7_SharedResource/src/Header_Files/led_driver.h", "visit_date": "2020-12-22T16:56:35.857521" }
stackv2
/* * led_driver.h * * Created on: Feb 27, 2020 * Author: goat */ #ifndef LED_DRIVER_H_ #define LED_DRIVER_H_ #include <stdint.h> #include "em_cmu.h" #include "em_acmp.h" #include "gpio.h" #include "buttons.h" #include "mycapsense.h" /** * LED Task Defines */ //Priority #define LED_TASK_PRIO 22u //task stack size to allocate #define LED_TASK_STK_SIZE 1024u //task stack CPU_STK LEDTaskStk[LED_TASK_STK_SIZE]; //task TCB OS_TCB LEDTaskTCB; /**************************** * Global Variables ****************************/ //Task function Prototype /** * LEDTask() * --------- * @description This function defines the operation of the LED Task * It keeps track of the button state and the cap_state, * and updates the LED outs accordingly. * */ void LEDTask (void); /** * create_led_task() * ---------------- * @description This function simply makes the OS call to start the LED task. * * @param None * * @return None * */ void create_led_task(void); #endif /* LED_DRIVER_H_ */
2
2
2024-11-18T21:19:21.441393+00:00
2014-06-01T15:32:26
516e028227c91d399310fc36699817a32ae877d2
{ "blob_id": "516e028227c91d399310fc36699817a32ae877d2", "branch_name": "refs/heads/master", "committer_date": "2014-06-01T15:32:26", "content_id": "aece57b0cce373f899eb5aaae394102f4d7c0d04", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "2c795ebeaf3fb106480f0d66c9a0c6060facb92e", "extension": "c", "filename": "esch_config.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": 10013, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/src/esch_config.c", "provenance": "stackv2-0128.json.gz:310065", "repo_name": "henrysher/esch", "revision_date": "2014-06-01T15:32:26", "revision_id": "32000aecebc6d373db24378739323cfafa299a5d", "snapshot_id": "278512cf245ab7f5dc96f219504dc7ae9a8065f3", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/henrysher/esch/32000aecebc6d373db24378739323cfafa299a5d/src/esch_config.c", "visit_date": "2021-01-02T22:16:55.882627" }
stackv2
#include "esch.h" #include "esch_debug.h" #include "esch_config.h" #include "esch_log.h" #include "esch_gc.h" #include <assert.h> #include <string.h> const char* ESCH_CONFIG_KEY_ALLOC = "common:alloc"; const char* ESCH_CONFIG_KEY_LOG = "common:log"; const char* ESCH_CONFIG_KEY_GC = "common:gc"; const char* ESCH_CONFIG_KEY_VECTOR_LENGTH = "vector:length"; const char* ESCH_CONFIG_KEY_VECTOR_ENLARGE = "vector:enlarge"; const char* ESCH_CONFIG_KEY_GC_NAIVE_SLOTS = "gc:naive:slots"; const char* ESCH_CONFIG_KEY_GC_NAIVE_ROOT = "gc:naive:root"; const char* ESCH_CONFIG_KEY_GC_NAIVE_ENLARGE = "gc:naive:enlarge"; static esch_error esch_config_destructor(esch_object* obj); static esch_error esch_config_new_as_object(esch_config*, esch_object** obj); struct esch_builtin_type esch_config_type = { { &(esch_meta_type.type), NULL, &(esch_log_do_nothing.log), NULL, NULL, }, { ESCH_VERSION, sizeof(esch_config), esch_config_new_as_object, esch_config_destructor, esch_type_default_non_copiable, esch_type_default_no_string_form, esch_type_default_no_doc, esch_type_default_no_iterator } }; /** * Create a new config object. * @param config Returned config object. * @return error code. ESCH_OK if success, others on error. */ esch_error esch_config_new(esch_log* log, esch_alloc* alloc, esch_config** config) { esch_error ret = ESCH_OK; esch_object* new_obj = NULL; esch_config* new_config = NULL; size_t size = 0; ESCH_CHECK_PARAM_PUBLIC(log != NULL); ESCH_CHECK_PARAM_PUBLIC(alloc != NULL); ESCH_CHECK_PARAM_PUBLIC(config != NULL); size = sizeof(esch_object) + sizeof(esch_config); ret = esch_alloc_realloc(alloc, NULL, size, (void**)&new_obj); ESCH_CHECK(ret == ESCH_OK, esch_global_log, "Can't create config", ESCH_ERROR_INVALID_PARAMETER); new_config = ESCH_CAST_FROM_OBJECT(new_obj, esch_config); ESCH_OBJECT_GET_TYPE(new_obj) = &(esch_config_type.type); ESCH_OBJECT_GET_ALLOC(new_obj) = alloc; ESCH_OBJECT_GET_LOG(new_obj) = log; ESCH_OBJECT_GET_GC(new_obj) = NULL; ESCH_OBJECT_GET_GC_ID(new_obj) = NULL; /* Can't get managed. */ /* Fill preset keys */ strncpy(new_config->config[0].key, ESCH_CONFIG_KEY_ALLOC, ESCH_CONFIG_KEY_LENGTH); new_config->config[0].type = ESCH_CONFIG_VALUE_TYPE_OBJECT; strncpy(new_config->config[1].key, ESCH_CONFIG_KEY_LOG, ESCH_CONFIG_KEY_LENGTH); new_config->config[1].type = ESCH_CONFIG_VALUE_TYPE_OBJECT; strncpy(new_config->config[2].key, ESCH_CONFIG_KEY_GC, ESCH_CONFIG_KEY_LENGTH); new_config->config[2].type = ESCH_CONFIG_VALUE_TYPE_OBJECT; strncpy(new_config->config[3].key, ESCH_CONFIG_KEY_VECTOR_LENGTH, ESCH_CONFIG_KEY_LENGTH); new_config->config[3].type = ESCH_CONFIG_VALUE_TYPE_INTEGER; new_config->config[3].data.int_value = 1; strncpy(new_config->config[4].key, ESCH_CONFIG_KEY_VECTOR_ENLARGE, ESCH_CONFIG_KEY_LENGTH); new_config->config[4].type = ESCH_CONFIG_VALUE_TYPE_INTEGER; new_config->config[4].data.int_value = ESCH_FALSE; strncpy(new_config->config[5].key, ESCH_CONFIG_KEY_GC_NAIVE_SLOTS, ESCH_CONFIG_KEY_LENGTH); new_config->config[5].type = ESCH_CONFIG_VALUE_TYPE_INTEGER; new_config->config[5].data.int_value = ESCH_GC_NAIVE_DEFAULT_SLOTS; strncpy(new_config->config[6].key, ESCH_CONFIG_KEY_GC_NAIVE_ROOT, ESCH_CONFIG_KEY_LENGTH); new_config->config[6].type = ESCH_CONFIG_VALUE_TYPE_OBJECT; new_config->config[6].data.obj_value = NULL; strncpy(new_config->config[7].key, ESCH_CONFIG_KEY_GC_NAIVE_ENLARGE, ESCH_CONFIG_KEY_LENGTH); new_config->config[7].type = ESCH_CONFIG_VALUE_TYPE_INTEGER; new_config->config[7].data.int_value = ESCH_FALSE; (*config) = new_config; new_config = NULL; Exit: if (new_config != NULL) { (void)esch_alloc_free(alloc, (void*)new_obj); } return ret; } /** * Get an integer value in configuration. * @param config Given config object. * @param key Given key of configuration. * @param value Returned integer value. * @return Error code. ESCH_ERROR_NOT_FOUND if not found. */ esch_error esch_config_get_int(esch_config* config, const char* key, int* value) { esch_error ret = ESCH_OK; size_t i = 0; ESCH_CHECK_PARAM_PUBLIC(config != NULL); ESCH_CHECK_PARAM_PUBLIC(key != NULL); ESCH_CHECK_PARAM_PUBLIC(value != NULL); ret = ESCH_ERROR_NOT_FOUND; for (i = 0; i < ESCH_CONFIG_ITEMS; ++i) { if (strcmp(config->config[i].key, key) == 0 && config->config[i].type == ESCH_CONFIG_VALUE_TYPE_INTEGER) { (*value) = config->config[i].data.int_value; ret = ESCH_OK; break; } } Exit: return ret; } /** * Set a new integer to given key. * @param config Given config object. * @param key String key. * @param obj New integer value. * @return Return code. ESCH_ERROR_NOT_FOUND if key is not found. */ esch_error esch_config_set_int(esch_config* config, const char* key, int value) { esch_error ret = ESCH_OK; size_t i = 0; ESCH_CHECK_PARAM_PUBLIC(config != NULL); ESCH_CHECK_PARAM_PUBLIC(key != NULL); ret = ESCH_ERROR_NOT_FOUND; for (i = 0; i < ESCH_CONFIG_ITEMS; ++i) { if (strcmp(config->config[i].key, key) == 0 && config->config[i].type == ESCH_CONFIG_VALUE_TYPE_INTEGER) { config->config[i].data.int_value = value; ret = ESCH_OK; break; } } Exit: return ret; } /** * Get a string value in configuration. * @param config Given config object. * @param key Given key of configuration. * @param value Returned integer value. * @return Error code. ESCH_ERROR_NOT_FOUND if not found. */ esch_error esch_config_get_str(esch_config* config, const char* key, char** value) { esch_error ret = ESCH_OK; size_t i = 0; ESCH_CHECK_PARAM_PUBLIC(config != NULL); ESCH_CHECK_PARAM_PUBLIC(key != NULL); ESCH_CHECK_PARAM_PUBLIC(value != NULL); ret = ESCH_ERROR_NOT_FOUND; for (i = 0; i < ESCH_CONFIG_ITEMS; ++i) { if (strcmp(config->config[i].key, key) == 0 && config->config[i].type == ESCH_CONFIG_VALUE_TYPE_STRING) { (*value) = config->config[i].data.str_value; ret = ESCH_OK; break; } } Exit: return ret; } /** * Set a new string to given key. * @param config Given config object. * @param key String key. * @param obj New string. Can be NULL. * @return Return code. ESCH_ERROR_NOT_FOUND if key is not found. */ esch_error esch_config_set_str(esch_config* config, const char* key, char* value) { esch_error ret = ESCH_OK; size_t i = 0; ESCH_CHECK_PARAM_PUBLIC(config != NULL); ESCH_CHECK_PARAM_PUBLIC(key != NULL); ret = ESCH_ERROR_NOT_FOUND; for (i = 0; i < ESCH_CONFIG_ITEMS; ++i) { if (strcmp(config->config[i].key, key) == 0 && config->config[i].type == ESCH_CONFIG_VALUE_TYPE_STRING) { strncmp(config->config[i].data.str_value, value, ESCH_CONFIG_VALUE_STRING_LENGTH); ret = ESCH_OK; break; } } Exit: return ret; } /** * Get an esch_object value in configuration. * @param config Given config object. * @param key Given key of configuration. * @param value Returned integer value. * @return Error code. ESCH_ERROR_NOT_FOUND if not found. */ esch_error esch_config_get_obj(esch_config* config, const char* key, esch_object** obj) { esch_error ret = ESCH_OK; size_t i = 0; ESCH_CHECK_PARAM_PUBLIC(config != NULL); ESCH_CHECK_PARAM_PUBLIC(key != NULL); ESCH_CHECK_PARAM_PUBLIC(obj != NULL); ret = ESCH_ERROR_NOT_FOUND; for (i = 0; i < ESCH_CONFIG_ITEMS; ++i) { if (strcmp(config->config[i].key, key) == 0 && config->config[i].type == ESCH_CONFIG_VALUE_TYPE_OBJECT) { (*obj) = config->config[i].data.obj_value; ret = ESCH_OK; break; } } Exit: return ret; } /** * Set a new object to given key. * @param config Given config object. * @param key String key. * @param obj New object. Can be NULL. * @return Return code. ESCH_ERROR_NOT_FOUND if key is not found. */ esch_error esch_config_set_obj(esch_config* config, const char* key, esch_object* obj) { esch_error ret = ESCH_OK; size_t i = 0; ESCH_CHECK_PARAM_PUBLIC(config != NULL); ESCH_CHECK_PARAM_PUBLIC(key != NULL); ret = ESCH_ERROR_NOT_FOUND; for (i = 0; i < ESCH_CONFIG_ITEMS; ++i) { if (strcmp(config->config[i].key, key) == 0 && config->config[i].type == ESCH_CONFIG_VALUE_TYPE_OBJECT) { config->config[i].data.obj_value = obj; ret = ESCH_OK; break; } } Exit: return ret; } static esch_error esch_config_new_as_object(esch_config* config, esch_object** obj) { esch_error ret = ESCH_OK; esch_config* new_config = NULL; esch_alloc* alloc = NULL; esch_log* log = NULL; esch_object* alloc_obj = NULL; esch_object* log_obj = NULL; ESCH_CHECK_PARAM_PUBLIC(config != NULL); log_obj = ESCH_CONFIG_GET_LOG(config); alloc_obj = ESCH_CONFIG_GET_ALLOC(config); ESCH_CHECK_PARAM_PUBLIC(log_obj != NULL); ESCH_CHECK_PARAM_PUBLIC(alloc_obj != NULL); log = ESCH_CAST_FROM_OBJECT(log_obj, esch_log); alloc = ESCH_CAST_FROM_OBJECT(alloc_obj, esch_alloc); ret = esch_config_new(log, alloc, &new_config); if (ret == ESCH_OK) { (*obj) = ESCH_CAST_TO_OBJECT(new_config); } Exit: return ret; } static esch_error esch_config_destructor(esch_object* obj) { (void)obj; /* Just do nothing */ return ESCH_OK; }
2.4375
2
2024-11-18T21:19:21.523363+00:00
2021-10-07T18:07:00
48f1f3af6ed4ce82650207f716465ddb547e8f87
{ "blob_id": "48f1f3af6ed4ce82650207f716465ddb547e8f87", "branch_name": "refs/heads/master", "committer_date": "2021-10-07T18:07:00", "content_id": "ed7c9f5e01bf9ad5cb5b41745fe21cab9751dfe1", "detected_licenses": [ "MIT" ], "directory_id": "ef2314811f877d266fb2bb8cf002bf3d7cea68eb", "extension": "c", "filename": "TreeListing.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": 23716, "license": "MIT", "license_type": "permissive", "path": "/src/lib/nhtty/Editor/TreeListing.c", "provenance": "stackv2-0128.json.gz:310196", "repo_name": "rhp7rholype/netzhaut", "revision_date": "2021-10-07T18:07:00", "revision_id": "a80cf764f768a4af79663ca851b23928f0375023", "snapshot_id": "5534b983aa6bb8916d2d39cf964818328c3faf36", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/rhp7rholype/netzhaut/a80cf764f768a4af79663ca851b23928f0375023/src/lib/nhtty/Editor/TreeListing.c", "visit_date": "2023-09-03T15:43:33.381387" }
stackv2
// LICENSE NOTICE ================================================================================== /** * netzhaut - Web Browser Engine * Copyright (C) 2020 The netzhaut Authors * Published under MIT */ // INCLUDE ========================================================================================= #include "TreeListing.h" #include "Editor.h" #include "../PseudoTerminal/PseudoTerminal.h" #include "../Common/Macro.h" #include NH_TTY_FLOW #include NH_TTY_DEFAULT_CHECK #include "../../nhcore/System/Memory.h" #include "../../nhcore/Common/Macro.h" #include NH_FLOW #include NH_CUSTOM_CHECK #include "../../nhencoding/Encodings/UTF32.h" #include "../../nhencoding/Encodings/UTF8.h" #include "../../nhencoding/Common/Macro.h" #include NH_ENCODING_FLOW #include NH_ENCODING_CUSTOM_CHECK #include <stddef.h> #include <unistd.h> #include <stdio.h> #include <string.h> #include <dirent.h> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> // HELPER ========================================================================================== static int nh_tty_isRegularFile( nh_tty_TreeListingNode *Node_p) { NH_TTY_BEGIN() if (Node_p->unsaved) {NH_TTY_END(NH_TRUE)} nh_encoding_UTF8String Path = nh_encoding_encodeUTF8(Node_p->Path.p, Node_p->Path.length); struct stat path_stat; stat(Path.p, &path_stat); nh_encoding_freeUTF8String(&Path); NH_TTY_END(S_ISREG(path_stat.st_mode)) } static void nh_tty_getNodeList( nh_List *List_p, nh_tty_TreeListingNode *Node_p) { NH_TTY_BEGIN() nh_appendToList(List_p, Node_p); if (!Node_p->open) {NH_TTY_SILENT_END()} for (int i = 0; i < Node_p->Children.size; ++i) { nh_tty_getNodeList(List_p, Node_p->Children.pp[i]); } NH_TTY_SILENT_END() } static nh_tty_TreeListingNode *nh_tty_getCurrentNode( nh_tty_TreeListing *Listing_p) { NH_TTY_BEGIN() int current = 0; nh_List Nodes = nh_initList(128); nh_tty_getNodeList(&Nodes, Listing_p->Root_p); nh_tty_TreeListingNode *Current_p = Nodes.pp[Listing_p->treeCurrent]; nh_freeList(&Nodes, NH_FALSE); NH_TTY_END(Current_p) } static nh_tty_TreeListingNode *nh_tty_getTreeListingNode( nh_tty_TreeListing *Listing_p, nh_encoding_UTF32String *Path_p) { NH_TTY_BEGIN() int current = 0; nh_List Nodes = nh_initList(128); nh_tty_getNodeList(&Nodes, Listing_p->Root_p); nh_tty_TreeListingNode *Result_p = NULL; for (int i = 0; i < Nodes.size; ++i) { if (nh_encoding_compareUTF32(((nh_tty_TreeListingNode*)Nodes.pp[i])->Path.p, Path_p->p)) { Result_p = Nodes.pp[i]; break; } } nh_freeList(&Nodes, NH_FALSE); NH_TTY_END(Result_p) } // CREATE ========================================================================================== static nh_tty_TreeListingNode *nh_tty_createTreeListingNode( nh_tty_TreeListingNode *Parent_p, nh_encoding_UTF32String Path, nh_tty_File *File_p) { NH_TTY_BEGIN() #include NH_TTY_CUSTOM_CHECK nh_tty_TreeListingNode *Node_p = nh_allocate(sizeof(nh_tty_TreeListingNode)); NH_TTY_CHECK_MEM(NULL, Node_p) #include NH_TTY_DEFAULT_CHECK Node_p->open = NH_FALSE; Node_p->unsaved = NH_FALSE; Node_p->Path = Path; Node_p->Children = nh_initList(16); Node_p->Parent_p = Parent_p; Node_p->File_p = File_p; NH_TTY_END(Node_p) } static NH_TTY_RESULT nh_tty_openNode( nh_tty_TreeListingNode *Node_p) { NH_TTY_BEGIN() NH_TTY_CHECK_NULL(Node_p) if (Node_p->Path.length <= 0 || Node_p->Children.size > 0 || nh_tty_isRegularFile(Node_p)) { NH_TTY_DIAGNOSTIC_END(NH_TTY_ERROR_BAD_STATE) } #ifdef __unix__ struct dirent **namelist_pp; nh_encoding_UTF8String CurrentPath = nh_encoding_encodeUTF8(Node_p->Path.p, Node_p->Path.length); int n = scandir(CurrentPath.p, &namelist_pp, 0, alphasort); if (n < 0) {NH_TTY_DIAGNOSTIC_END(NH_TTY_ERROR_BAD_STATE)} nh_encoding_freeUTF8String(&CurrentPath); for (int i = 0; i < n; ++i) { if (strcmp(namelist_pp[i]->d_name, ".") && strcmp(namelist_pp[i]->d_name, "..")) { nh_encoding_UTF32String NewPath = nh_encoding_initUTF32(128); nh_encoding_UTF32String FileName = nh_encoding_decodeUTF8(namelist_pp[i]->d_name, strlen(namelist_pp[i]->d_name), NULL); if (Node_p->Path.p[Node_p->Path.length - 1] != '/') { nh_encoding_appendUTF32(&NewPath, Node_p->Path.p, Node_p->Path.length); nh_encoding_appendUTF32Codepoint(&NewPath, '/'); nh_encoding_appendUTF32(&NewPath, FileName.p, FileName.length); } else { nh_encoding_appendUTF32(&NewPath, Node_p->Path.p, Node_p->Path.length); nh_encoding_appendUTF32(&NewPath, FileName.p, FileName.length); } nh_tty_TreeListingNode *New_p = nh_tty_createTreeListingNode(Node_p, NewPath, NULL); NH_TTY_CHECK_MEM(New_p) NH_CHECK(NH_TTY_ERROR_BAD_STATE, nh_appendToList(&Node_p->Children, New_p)) } free(namelist_pp[i]); } if (Node_p->Children.size == 0) { NH_TTY_CHECK(nh_tty_setCustomMessage( &nh_tty_getPseudoTerminal()->Tab_p->Tile_p->Status, NH_TTY_MESSAGE_EDITOR_EMPTY_DIRECTORY, Node_p->Path.p, Node_p->Path.length )) } free(namelist_pp); #elif defined(_WIN32) || defined(WIN32) printf("microsoft windows not supported\n"); exit(0); #endif Node_p->open = NH_TRUE; NH_TTY_END(NH_TTY_SUCCESS) } nh_tty_TreeListingNode *nh_tty_insertTreeListingNode( nh_tty_TreeListing *Listing_p, NH_ENCODING_UTF32 *name_p, int length) { NH_TTY_BEGIN() #include NH_TTY_CUSTOM_CHECK NH_TTY_CHECK_NULL(NULL, name_p) if (length <= 0) {NH_TTY_END(NULL)} nh_tty_TreeListingNode *Current_p = nh_tty_getCurrentNode(Listing_p); int offset = Current_p->Path.length; if (nh_tty_isRegularFile(Current_p)) { for (offset = Current_p->Path.length - 1; Current_p->Path.p[offset] != '/'; --offset); } offset = Current_p->Path.length - offset; nh_encoding_UTF32String Path = nh_encoding_initUTF32(128); nh_encoding_appendUTF32(&Path, Current_p->Path.p, Current_p->Path.length - offset); nh_encoding_appendUTF32Codepoint(&Path, '/'); nh_encoding_appendUTF32(&Path, name_p, length); nh_tty_TreeListingNode *New_p = NULL; if (!nh_tty_getTreeListingNode(Listing_p, &Path)) { if (Current_p->Children.size > 0) { New_p = nh_tty_createTreeListingNode(Current_p, Path, NULL); NH_CHECK(NULL, nh_appendToList(&Current_p->Children, New_p)) } else if (Current_p->Parent_p != NULL) { New_p = nh_tty_createTreeListingNode(Current_p->Parent_p, Path, NULL); NH_CHECK(NULL, nh_appendToList(&Current_p->Parent_p->Children, New_p)) } else {NH_TTY_END(NULL)} NH_TTY_CHECK_MEM(NULL, New_p) New_p->unsaved = NH_TRUE; nh_tty_renderTreeListing(Listing_p); } else { NH_TTY_CHECK(NULL, nh_tty_setDefaultMessage( &nh_tty_getPseudoTerminal()->Tab_p->Tile_p->Status, NH_TTY_MESSAGE_EDITOR_FILE_ALREADY_EXISTS )) nh_encoding_freeUTF32(&Path); } #include NH_TTY_DEFAULT_CHECK NH_TTY_END(New_p) } // INPUT =========================================================================================== static NH_TTY_RESULT nh_tty_removeFile( nh_tty_Status *Status_p, nh_tty_Editor *Editor_p) { NH_TTY_BEGIN() nh_tty_TreeListingNode *Node_p = nh_tty_getCurrentNode(&Editor_p->TreeListing); nh_encoding_UTF8String Path = nh_encoding_encodeUTF8(Node_p->Path.p, Node_p->Path.length); remove(Path.p); nh_encoding_freeUTF8String(&Path); NH_TTY_CHECK(nh_tty_setCustomMessage( Status_p, NH_TTY_MESSAGE_EDITOR_FILE_REMOVED, Node_p->Path.p, Node_p->Path.length )) NH_TTY_DIAGNOSTIC_END(NH_TTY_SUCCESS) } static NH_TTY_RESULT nh_tty_delete( nh_tty_Status *Status_p, nh_tty_Event Event, NH_BOOL *continue_p) { NH_TTY_BEGIN() if (Event.trigger != NH_WSI_TRIGGER_PRESS) {NH_TTY_DIAGNOSTIC_END(NH_TTY_SUCCESS)} NH_ENCODING_UTF32 c = Event.codepoint; if (c == 'y' || c == 'n') { Status_p->block = NH_FALSE; Status_p->args_p = NULL; Status_p->callback_f = NULL; if (c == 'n') { NH_TTY_CHECK(nh_tty_setDefaultMessage( Status_p, NH_TTY_MESSAGE_BINARY_QUERY_DELETE_INTERRUPTED )) } if (c == 'y') { // nh_tty_Program *Program_p = nh_tty_getCurrentProgram(&nh_tty_getPseudoTerminal()->Tab_p->Tile_p->Console); // nh_tty_removeFile(Status_p, Program_p->handle_p); // NH_TTY_CHECK(nh_tty_handleTreeListingInput( // Program_p, ((nh_tty_Editor*)Program_p->handle_p)->height, 'w' // )) } } NH_TTY_DIAGNOSTIC_END(NH_TTY_SUCCESS) } static NH_TTY_RESULT nh_tty_setCurrentToRoot( nh_tty_TreeListing *Listing_p, nh_Array *Programs_p) { NH_TTY_BEGIN() nh_tty_TreeListingNode *Current_p = nh_tty_getCurrentNode(Listing_p); if (Current_p->Children.size > 0) { for (nh_tty_TreeListingNode *Parent_p = Current_p; Parent_p = Parent_p->Parent_p;) { Parent_p->open = NH_FALSE; } Listing_p->Root_p = Current_p; } NH_TTY_CHECK(nh_tty_setCustomMessage( &nh_tty_getPseudoTerminal()->Tab_p->Tile_p->Status, NH_TTY_MESSAGE_EDITOR_NEW_ROOT, Listing_p->Root_p->Path.p, Listing_p->Root_p->Path.length )) NH_TTY_DIAGNOSTIC_END(NH_TTY_SUCCESS) } static NH_TTY_RESULT nh_tty_setParentToRoot( nh_tty_TreeListing *Listing_p, nh_Array *Programs_p) { NH_TTY_BEGIN() if (Listing_p->Root_p->Parent_p != NULL) { Listing_p->Root_p = Listing_p->Root_p->Parent_p; Listing_p->Root_p->open = NH_TRUE; } else { nh_encoding_UTF32String Path = nh_encoding_initUTF32(128); nh_encoding_appendUTF32(&Path, Listing_p->Root_p->Path.p, Listing_p->Root_p->Path.length); while (Path.p[Path.length - 1] != '/') {nh_encoding_removeUTF32Tail(&Path, 1);} if (Path.length > 1) {nh_encoding_removeUTF32Tail(&Path, 1);} nh_tty_TreeListingNode *OldRoot_p = Listing_p->Root_p; Listing_p->Root_p = nh_tty_createTreeListingNode(NULL, Path, NULL); NH_TTY_CHECK_MEM(Listing_p->Root_p) OldRoot_p->Parent_p = Listing_p->Root_p; NH_TTY_CHECK(nh_tty_openNode(Listing_p->Root_p)) NH_BOOL isChild = NH_FALSE; for (int i = 0; i < Listing_p->Root_p->Children.size; ++i) { nh_tty_TreeListingNode *Child_p = Listing_p->Root_p->Children.pp[i]; if (nh_encoding_compareUTF32(Child_p->Path.p, OldRoot_p->Path.p)) { nh_encoding_freeUTF32(&Child_p->Path); nh_free(Listing_p->Root_p->Children.pp[i]); Listing_p->Root_p->Children.pp[i] = OldRoot_p; isChild = NH_TRUE; break; } } if (!isChild) {NH_TTY_DIAGNOSTIC_END(NH_TTY_ERROR_BAD_STATE)} } NH_TTY_CHECK(nh_tty_setCustomMessage( &nh_tty_getPseudoTerminal()->Tab_p->Tile_p->Status, NH_TTY_MESSAGE_EDITOR_NEW_ROOT, Listing_p->Root_p->Path.p, Listing_p->Root_p->Path.length )) NH_TTY_DIAGNOSTIC_END(NH_TTY_SUCCESS) } static void nh_tty_updateTreeListingView( nh_tty_Program *Program_p, int key) { NH_TTY_BEGIN() switch (key) { case 'w' : for (int i = 0; i < Program_p->Views.size; ++i) { nh_tty_EditorView *View_p = Program_p->Views.pp[i]; if (View_p->treeListingCurrent > 0) {View_p->treeListingCurrent--;} else if (View_p->treeListingOffset > 0) {View_p->treeListingOffset--;} } break; case 's' : for (int i = 0; i < Program_p->Views.size; ++i) { nh_tty_EditorView *View_p = Program_p->Views.pp[i]; if (View_p->treeListingCurrent < View_p->height - 1) {View_p->treeListingCurrent++;} else {View_p->treeListingOffset++;} } break; } NH_TTY_SILENT_END() } static void nh_tty_moveCursorVertically( nh_tty_Program *Program_p, int key) { NH_TTY_BEGIN() nh_tty_FileEditor *FileEditor_p = &((nh_tty_Editor*)Program_p->handle_p)->FileEditor; nh_tty_TreeListing *Listing_p = &((nh_tty_Editor*)Program_p->handle_p)->TreeListing; nh_List Nodes = nh_initList(32); nh_tty_getNodeList(&Nodes, Listing_p->Root_p); switch (key) { case 'w' : case CTRL_KEY('w') : if (Listing_p->treeCurrent > 0) { Listing_p->treeCurrent--; nh_tty_updateTreeListingView(Program_p, 'w'); } break; case 's' : case CTRL_KEY('s') : if (Listing_p->treeCurrent < Nodes.size - 1) { Listing_p->treeCurrent++; nh_tty_updateTreeListingView(Program_p, 's'); } break; } nh_freeList(&Nodes, NH_FALSE); if (Listing_p->preview && FileEditor_p != NULL) { if (Listing_p->Preview_p != NULL) { nh_tty_closeFile(Program_p, Listing_p->Preview_p->File_p); Listing_p->Preview_p->File_p = NULL; Listing_p->Preview_p = NULL; } nh_tty_TreeListingNode *Current_p = nh_tty_getCurrentNode(Listing_p); if (Current_p->File_p == NULL && Current_p->Path.length > 0 && nh_tty_isRegularFile(Current_p)) { Current_p->File_p = nh_tty_openFile(Program_p, Current_p, NH_TRUE); Listing_p->Preview_p = Current_p; } } NH_TTY_SILENT_END() } NH_TTY_RESULT nh_tty_handleTreeListingInput( nh_tty_Program *Program_p, NH_ENCODING_UTF32 c) { NH_TTY_BEGIN() nh_tty_Editor *Editor_p = Program_p->handle_p; nh_List *Views_p = &Program_p->Views; nh_tty_FileEditor *FileEditor_p = &Editor_p->FileEditor; nh_tty_TreeListing *Listing_p = &Editor_p->TreeListing; nh_tty_TreeListingNode *Current_p = nh_tty_getCurrentNode(Listing_p); switch (c) { case 'w' : case 's' : case CTRL_KEY('w') : case CTRL_KEY('s') : nh_tty_moveCursorVertically(Program_p, c); break; case 'a' : case CTRL_KEY('a') : if (Listing_p->treeCurrent == 0) { nh_tty_setParentToRoot(Listing_p, Program_p->Programs_p); } else if (Current_p->Children.size > 0 && Current_p->open) { Current_p->open = NH_FALSE; } else if (Current_p->Children.size == 0 && Current_p->File_p != NULL && Current_p->Path.length > 0) { NH_TTY_CHECK(nh_tty_closeFile(Program_p, Current_p->File_p)) Current_p->File_p = NULL; } else if (Current_p->Children.size == 0 && Current_p->File_p != NULL) { NH_TTY_CHECK(nh_tty_closeFile(Program_p, Current_p->File_p)) nh_removeFromList2(&Current_p->Parent_p->Children, NH_TRUE, Current_p); NH_TTY_CHECK(nh_tty_handleTreeListingInput(Program_p, 'w')) } else { // delete ? nh_encoding_UTF32String Question = nh_encoding_initUTF32(128); int deleteLength; NH_ENCODING_UTF32 *delete_p = nh_tty_getMessage(NH_TTY_MESSAGE_BINARY_QUERY_DELETE, &deleteLength); NH_ENCODING_CHECK(NH_TTY_ERROR_BAD_STATE, nh_encoding_appendUTF32(&Question, delete_p, deleteLength)) NH_ENCODING_CHECK(NH_TTY_ERROR_BAD_STATE, nh_encoding_appendUTF32(&Question, Current_p->Path.p, Current_p->Path.length)) NH_TTY_CHECK(nh_tty_setBinaryQueryMessage(Question.p, Question.length, NULL, nh_tty_delete)) nh_encoding_freeUTF32(&Question); } break; case 'd' : case CTRL_KEY('d') : if (Listing_p->Preview_p != NULL) { Listing_p->Preview_p->File_p->readOnly = NH_FALSE; Listing_p->Preview_p = NULL; } else if (Current_p->Children.size > 0 && !Current_p->open) { Current_p->open = NH_TRUE; } else if (Current_p->Children.size == 0 && !nh_tty_isRegularFile(Current_p)) { NH_TTY_CHECK(nh_tty_openNode(Current_p)) } else if (Current_p->Children.size == 0 && nh_tty_isRegularFile(Current_p)) { if (Current_p->File_p == NULL) { Current_p->File_p = nh_tty_openFile(Program_p, Current_p, NH_FALSE); } else { NH_TTY_CHECK(nh_tty_writeFile(Current_p->File_p)) Current_p->unsaved = NH_FALSE; } } else { nh_tty_setCurrentToRoot(Listing_p, Program_p->Programs_p); Listing_p->treeCurrent = 0; for (int i = 0; i < Views_p->size; ++i) { nh_tty_EditorView *View_p = Views_p->pp[i]; View_p->treeListingCurrent = 0; View_p->treeListingOffset = 0; } } break; } NH_TTY_CHECK(nh_tty_renderTreeListing(Listing_p)) NH_TTY_END(NH_TTY_SUCCESS) } // RENDER ========================================================================================== static NH_TTY_RESULT nh_tty_renderTreeListingNode( nh_tty_TreeListingNode *Node_p, NH_BYTE *row_p) { NH_TTY_BEGIN() int offset = 0; nh_tty_TreeListingNode *Parent_p = Node_p->Parent_p; while (Parent_p != NULL && Parent_p->open) { offset += 2; Parent_p = Parent_p->Parent_p; } for (int i = 0; i < offset; i++) {row_p[i] = ' ';} if (Node_p->Path.length > 0) { NH_BYTE *p = NULL; int tmp = 0; for (int i = 0; i < Node_p->Path.length; ++i) { if (Node_p->Path.p[i] == '/') {tmp = i;} } tmp++; nh_encoding_UTF8String Name = nh_encoding_encodeUTF8(Node_p->Path.p + tmp, Node_p->Path.length - tmp); sprintf(row_p + offset, Name.p); nh_encoding_freeUTF8String(&Name); if (!nh_tty_isRegularFile(Node_p)) { row_p[strlen(row_p)] = '/'; } else if (Node_p->unsaved) { row_p[strlen(row_p)] = '*'; } } NH_TTY_DIAGNOSTIC_END(NH_TTY_SUCCESS) } static NH_TTY_RESULT nh_tty_renderTreeListingRow( nh_List *Nodes_p, nh_tty_TreeListingNode *Current_p, nh_String *Row_p, int row, int cols) { NH_TTY_BEGIN() nh_tty_TreeListingNode *Node_p = nh_getFromList(Nodes_p, row); if (Node_p != NULL) { NH_BYTE row_p[1024] = {'\0'}; NH_TTY_CHECK(nh_tty_renderTreeListingNode(Node_p, row_p)) if (Current_p == Node_p && row > 0) { NH_BYTE *p = row_p; while (*p == ' ') {p++;} p[-2] = '-'; p[-1] = '>'; } if (Node_p->File_p != NULL) { nh_appendToString(Row_p, "\e[1;1m", 6); } nh_appendFormatToString(Row_p, row_p); for (int i = 0; i < cols - strlen(row_p); ++i) { nh_appendToString(Row_p, " ", 1); } } NH_TTY_DIAGNOSTIC_END(NH_TTY_SUCCESS) } static int nh_tty_getTreeListingWidth( nh_tty_TreeListing *Listing_p) { NH_TTY_BEGIN() nh_List Nodes = nh_initList(64); nh_tty_getNodeList(&Nodes, Listing_p->Root_p); int width = 0; NH_BYTE row_p[1024] = {'\0'}; for (int i = 0; i < Nodes.size; ++i) { NH_TTY_CHECK(nh_tty_renderTreeListingNode(Nodes.pp[i], row_p)) if (strlen(row_p) > width) {width = strlen(row_p);} memset(row_p, 0, 1024); } nh_freeList(&Nodes, NH_FALSE); NH_TTY_END(width) } NH_TTY_RESULT nh_tty_renderTreeListing( nh_tty_TreeListing *Listing_p) { NH_TTY_BEGIN() nh_List Nodes = nh_initList(32); nh_tty_getNodeList(&Nodes, Listing_p->Root_p); nh_tty_TreeListingNode *Current_p = nh_tty_getCurrentNode(Listing_p); for (int i = 0; i < Listing_p->RenderLines.length; ++i) { nh_freeString(&((nh_String*)Listing_p->RenderLines.p)[i]); } nh_freeArray(&Listing_p->RenderLines); Listing_p->RenderLines = nh_initArray(sizeof(nh_String), Nodes.size); int width = nh_tty_getTreeListingWidth(Listing_p); for (int row = 0; row < Nodes.size; ++row) { nh_String *Line_p = nh_incrementArray(&Listing_p->RenderLines); *Line_p = nh_initString(128); NH_TTY_CHECK(nh_tty_renderTreeListingRow( &Nodes, Current_p, Line_p, row, width )) } nh_freeList(&Nodes, NH_FALSE); NH_TTY_DIAGNOSTIC_END(NH_TTY_SUCCESS) } // DRAW ============================================================================================ NH_TTY_RESULT nh_tty_drawTreeListingRow( nh_tty_Program *Program_p, nh_String *Row_p, int row) { NH_TTY_BEGIN() nh_tty_TreeListing *Listing_p = &((nh_tty_Editor*)Program_p->handle_p)->TreeListing; nh_tty_EditorView *View_p = Program_p->view_p; View_p->treeListingWidth = nh_tty_getTreeListingWidth(Listing_p); row += View_p->treeListingOffset; if (row < Listing_p->RenderLines.length) { nh_String *RenderLine_p = &((nh_String*)Listing_p->RenderLines.p)[row]; nh_appendToString(Row_p, RenderLine_p->p, RenderLine_p->length); } else { NH_BYTE whitespace_p[1024]; memset(whitespace_p, 32, 1024); nh_appendToString(Row_p, whitespace_p, View_p->treeListingWidth); } nh_appendToString(Row_p, "\e[0m", 4); NH_TTY_DIAGNOSTIC_END(NH_TTY_SUCCESS) } // CURSOR ========================================================================================== NH_TTY_RESULT nh_tty_setTreeListingCursor( nh_tty_Program *Program_p, nh_tty_File *File_p) { NH_TTY_BEGIN() nh_List Nodes = nh_initList(16); nh_tty_TreeListing *Listing_p = &((nh_tty_Editor*)Program_p->handle_p)->TreeListing; nh_tty_getNodeList(&Nodes, Listing_p->Root_p); for (int i = 0; i < Nodes.size; ++i) { if (((nh_tty_TreeListingNode*)Nodes.pp[i])->File_p == File_p) { if (Listing_p->treeCurrent < i) { int diff = i - Listing_p->treeCurrent; while (diff-- > 0) { nh_tty_moveCursorVertically(Program_p, CTRL_KEY('s')); } } else if (Listing_p->treeCurrent > i) { int diff = Listing_p->treeCurrent - i; while (diff-- > 0) { nh_tty_moveCursorVertically(Program_p, CTRL_KEY('w')); } } break; } } nh_freeList(&Nodes, NH_FALSE); NH_TTY_CHECK(nh_tty_renderTreeListing(Listing_p)) NH_TTY_DIAGNOSTIC_END(NH_TTY_SUCCESS) } // INIT ============================================================================================ nh_tty_TreeListing nh_tty_initTreeListing() { NH_TTY_BEGIN() nh_tty_TreeListing Listing; Listing.Root_p = nh_tty_createTreeListingNode(NULL, nh_encoding_initUTF32(0), NULL); Listing.treeCurrent = 0; Listing.RenderLines = nh_initArray(sizeof(nh_String), 255); Listing.preview = NH_FALSE; Listing.Preview_p = NULL; NH_BYTE wrkDir_p[2048]; memset(wrkDir_p, 0, 2048); getcwd(wrkDir_p, 2048); if (wrkDir_p != NULL) { Listing.Root_p->Path = nh_encoding_decodeUTF8(wrkDir_p, strlen(wrkDir_p), NULL); nh_tty_openNode(Listing.Root_p); nh_tty_renderTreeListing(&Listing); } NH_TTY_END(Listing) }
2.0625
2
2024-11-18T21:19:21.619555+00:00
2020-10-18T03:31:13
2fba62765c26834da2912ca92a8db70569b62272
{ "blob_id": "2fba62765c26834da2912ca92a8db70569b62272", "branch_name": "refs/heads/master", "committer_date": "2020-10-18T03:31:13", "content_id": "f9784cf7e0462ebe23287da36e1bfabed3f6a3c8", "detected_licenses": [ "MIT" ], "directory_id": "ea862fd4d26e10bfed795d67c590fddd1d250b8f", "extension": "c", "filename": "nnfile.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 258825459, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3125, "license": "MIT", "license_type": "permissive", "path": "/nnfile.c", "provenance": "stackv2-0128.json.gz:310327", "repo_name": "2NN300HU/2-Layer-Neural-Network", "revision_date": "2020-10-18T03:31:13", "revision_id": "7c44a85cf3befd2ff1eb9da5141ff9fa5ff04022", "snapshot_id": "d24e3be079312d592161bb7747e4b695c34dce89", "src_encoding": "UTF-8", "star_events_count": 5, "url": "https://raw.githubusercontent.com/2NN300HU/2-Layer-Neural-Network/7c44a85cf3befd2ff1eb9da5141ff9fa5ff04022/nnfile.c", "visit_date": "2022-12-27T17:55:18.438319" }
stackv2
#include "nnfile.h" FILE* imgfileopen(char* s) { FILE* fp; fp = fopen(s, "rb"); if (fp == NULL) { printf("Error : No image to train\n"); exit(1); } return fp; } FILE* lbfileopen(char* s) { FILE* fp; fp = fopen(s, "rb"); if (fp == NULL) { printf("Error : No label to train\n"); exit(1); } return fp; } void fileheaderread(FILE* fp) { unsigned long magicnumber = 0, casesize = 0, col = 0, row = 0; fread(&magicnumber, sizeof(unsigned long), 1, fp); magicnumber = ntohl(magicnumber); if (magicnumber == 2051) { printf("Reading Image file...\nmagic number: 0x%08X\n", magicnumber); fread(&casesize, sizeof(unsigned long), 1, fp); casesize = ntohl(casesize); printf("case size: %lu\n", casesize); fread(&row, sizeof(unsigned long), 1, fp); row = ntohl(row); fread(&col, sizeof(unsigned long), 1, fp); col = ntohl(col); printf("img size: %lu * %lu\n\n", col, row); } else if (magicnumber == 2049) { printf("Reading Label file...\nmagic number: 0x%08X\n", magicnumber); fread(&casesize, sizeof(unsigned long), 1, fp); casesize = ntohl(casesize); printf("case size: %lu\n\n", casesize); } else { printf("Error : Undefined magic number\n"); exit(0); } } void set(struct NeuralNetwork* nn, int ini, int nnsize[]) { if (ini == 0) { FILE* fp; fp = fopen(INIVAL, "rb"); if (fp == NULL) { printf("Error : No initialize value file\n"); exit(1); } printf("Loading initialize value file..."); for (int a = 0; a < nnsize[1]; a++) { for (int b = 0; b < nnsize[0]; b++) { fread(&nn->sy1.weight[a][b], sizeof(double), 1, fp); } fread(&nn->sy1.bias[a], sizeof(double), 1, fp); } for (int a = 0; a < nnsize[2]; a++) { for (int b = 0; b < nnsize[1]; b++) { fread(&nn->sy2.weight[a][b], sizeof(double), 1, fp); } fread(&nn->sy2.bias[a], sizeof(double), 1, fp); } } else if (ini == 1) { printf("initializing..."); for (int a = 0; a < nnsize[1]; a++) { for (int b = 0; b < nnsize[0]; b++) { nn->sy1.weight[a][b] = initialize(0, nnsize[0], nnsize[1]); } nn->sy1.bias[a] = initialize(0, nnsize[0], nnsize[1]); } for (int a = 0; a < nnsize[2]; a++) { for (int b = 0; b < nnsize[1]; b++) { nn->sy2.weight[a][b] = initialize(0, nnsize[1], nnsize[2]); } nn->sy2.bias[a] = initialize(0, nnsize[1], nnsize[2]); } } else { printf("Error: undefined initialize method value.\n"); } } void setsave(struct NeuralNetwork* nn, int nnsize[]) { FILE* fp; fp = fopen(INIVAL, "wb"); for (int a = 0; a < nnsize[1]; a++) { for (int b = 0; b < nnsize[0]; b++) { fwrite(&nn->sy1.weight[a][b], sizeof(double), 1, fp); } fwrite(&nn->sy1.bias[a], sizeof(double), 1, fp); } for (int a = 0; a < nnsize[2]; a++) { for (int b = 0; b < nnsize[1]; b++) { fwrite(&nn->sy2.weight[a][b], sizeof(double), 1, fp); } fwrite(&nn->sy2.bias[a], sizeof(double), 1, fp); } } void caseread(FILE* img, FILE* lb, struct readfile* r) { for (int a = 0; a < INPUT; a++) { fread(&r->input[a], sizeof(unsigned char), 1, img); } fread(&r->tag, sizeof(unsigned char), 1, lb); }
2.46875
2
2024-11-18T21:19:22.131464+00:00
2023-08-25T04:46:28
1e0b3225a551b3b77343a3062fc0a2c10b0680f0
{ "blob_id": "1e0b3225a551b3b77343a3062fc0a2c10b0680f0", "branch_name": "refs/heads/main", "committer_date": "2023-08-25T07:17:19", "content_id": "34670e12efc88178527f7dd322c3a82b264d26e9", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "dc7631ad46c850ad3b491c261c2da42edffabc4e", "extension": "c", "filename": "ccgxxf.c", "fork_events_count": 58, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 50835018, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3706, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/driver/tcpm/ccgxxf.c", "provenance": "stackv2-0128.json.gz:310973", "repo_name": "coreboot/chrome-ec", "revision_date": "2023-08-25T04:46:28", "revision_id": "0bbd46a5aa22eb824b21365f21f4811c9343ca1e", "snapshot_id": "6eab032c65da77f16a7de81da85921c2ca872ee2", "src_encoding": "UTF-8", "star_events_count": 66, "url": "https://raw.githubusercontent.com/coreboot/chrome-ec/0bbd46a5aa22eb824b21365f21f4811c9343ca1e/driver/tcpm/ccgxxf.c", "visit_date": "2023-08-25T08:30:03.833636" }
stackv2
/* Copyright 2022 The ChromiumOS Authors * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. * * Cypress CCGXXF PD chip driver source */ #include "ccgxxf.h" #include "console.h" #include "tcpm/tcpci.h" /* * TODO (b/236994474): Once the PD negotiation completes, CCGXXF chip stops * responding over I2C for about 10 seconds. As DRP is enabled, TCPM algorithm * constantly looks for any CC status changes even after negotiation completes. * Hence, cache the CC state and return the cached values in case of I2C * failures. This workaround will be removed once the fix is added in the * physical layer firmware of CCGXXF. */ struct ccgxxf_cc { bool good_cc; enum tcpc_cc_voltage_status cc1; enum tcpc_cc_voltage_status cc2; }; static struct ccgxxf_cc ccgxxf_cc_cache[CONFIG_USB_PD_PORT_MAX_COUNT]; static int ccgxxf_tcpci_tcpm_get_cc(int port, enum tcpc_cc_voltage_status *cc1, enum tcpc_cc_voltage_status *cc2) { int rv = tcpci_tcpm_get_cc(port, cc1, cc2); if (rv) { if (!ccgxxf_cc_cache[port].good_cc) return rv; *cc1 = ccgxxf_cc_cache[port].cc1; *cc2 = ccgxxf_cc_cache[port].cc2; } else { ccgxxf_cc_cache[port].good_cc = true; ccgxxf_cc_cache[port].cc1 = *cc1; ccgxxf_cc_cache[port].cc2 = *cc2; } return EC_SUCCESS; } static int ccgxxf_tcpci_tcpm_init(int port) { ccgxxf_cc_cache[port].good_cc = false; return tcpci_tcpm_init(port); } #ifdef CONFIG_USB_PD_TCPM_SBU static int ccgxxf_tcpc_set_sbu(int port, bool enable) { return tcpc_write(port, CCGXXF_REG_SBU_MUX_CTL, enable); } #endif #ifdef CONFIG_CMD_TCPC_DUMP static void ccgxxf_dump_registers(int port) { int fw_ver, fw_build; tcpc_dump_std_registers(port); /* Get the F/W version and build ID */ if (!tcpc_read16(port, CCGXXF_REG_FW_VERSION, &fw_ver) && !tcpc_read16(port, CCGXXF_REG_FW_VERSION_BUILD, &fw_build)) { ccprintf(" FW_VERSION(build.major.minor) = %d.%d.%d\n", fw_build & 0xFF, (fw_ver >> 8) & 0xFF, fw_ver & 0xFF); } } #endif int ccgxxf_reset(int port) { return tcpc_write16(port, CCGXXF_REG_FWU_COMMAND, CCGXXF_FWU_CMD_RESET); } const struct tcpm_drv ccgxxf_tcpm_drv = { .init = &ccgxxf_tcpci_tcpm_init, .release = &tcpci_tcpm_release, .get_cc = &ccgxxf_tcpci_tcpm_get_cc, #ifdef CONFIG_USB_PD_VBUS_DETECT_TCPC .check_vbus_level = &tcpci_tcpm_check_vbus_level, #endif .select_rp_value = &tcpci_tcpm_select_rp_value, .set_cc = &tcpci_tcpm_set_cc, .set_polarity = &tcpci_tcpm_set_polarity, #ifdef CONFIG_USB_PD_DECODE_SOP .sop_prime_enable = &tcpci_tcpm_sop_prime_enable, #endif .set_vconn = &tcpci_tcpm_set_vconn, .set_msg_header = &tcpci_tcpm_set_msg_header, .set_rx_enable = &tcpci_tcpm_set_rx_enable, .get_message_raw = &tcpci_tcpm_get_message_raw, .transmit = &tcpci_tcpm_transmit, .tcpc_alert = &tcpci_tcpc_alert, #ifdef CONFIG_USB_PD_DISCHARGE_TCPC .tcpc_discharge_vbus = &tcpci_tcpc_discharge_vbus, #endif .tcpc_enable_auto_discharge_disconnect = &tcpci_tcpc_enable_auto_discharge_disconnect, #ifdef CONFIG_USB_PD_DUAL_ROLE_AUTO_TOGGLE .drp_toggle = &tcpci_tcpc_drp_toggle, #endif .get_chip_info = &tcpci_get_chip_info, #ifdef CONFIG_USB_PD_PPC .get_snk_ctrl = &tcpci_tcpm_get_snk_ctrl, .set_snk_ctrl = &tcpci_tcpm_set_snk_ctrl, .get_src_ctrl = &tcpci_tcpm_get_src_ctrl, .set_src_ctrl = &tcpci_tcpm_set_src_ctrl, #endif #ifdef CONFIG_USB_PD_TCPM_SBU .set_sbu = &ccgxxf_tcpc_set_sbu, #endif #ifdef CONFIG_USB_PD_TCPC_LOW_POWER .enter_low_power_mode = &tcpci_enter_low_power_mode, #endif .set_bist_test_mode = &tcpci_set_bist_test_mode, .get_bist_test_mode = &tcpci_get_bist_test_mode, #ifdef CONFIG_CMD_TCPC_DUMP .dump_registers = &ccgxxf_dump_registers, #endif };
2.046875
2
2024-11-18T21:19:22.184448+00:00
2021-01-14T12:19:25
8b0e3e72340246b99050e12e8f2bf391cae1ce5f
{ "blob_id": "8b0e3e72340246b99050e12e8f2bf391cae1ce5f", "branch_name": "refs/heads/master", "committer_date": "2021-01-14T12:19:25", "content_id": "c034f27ef7efa23182a5b0cf2d519249bdfde0fc", "detected_licenses": [ "MIT" ], "directory_id": "f631ee899d2f1ec6efceee62bd4218807ab6da16", "extension": "c", "filename": "str.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 323398747, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2037, "license": "MIT", "license_type": "permissive", "path": "/libs/util/str.c", "provenance": "stackv2-0128.json.gz:311102", "repo_name": "m3sserschmitt/shell", "revision_date": "2021-01-14T12:19:25", "revision_id": "836cdfe3db0733130a8152ca45cf4343a4a46470", "snapshot_id": "2124ba0965d21887b4e04d8d86ef83446a094cd5", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/m3sserschmitt/shell/836cdfe3db0733130a8152ca45cf4343a4a46470/libs/util/str.c", "visit_date": "2023-02-20T23:18:47.959618" }
stackv2
#include <string.h> #include <stdlib.h> size_t str_count(const char *str_in, const char *str) { size_t count = 0; char *ptr = strstr(str_in, str); while (ptr) { ptr++; ptr = strstr(ptr, str); count++; } return count; } char **split(const char *str, const char *delim, int *count) { size_t total = str_count(str, delim); char **tokens = (char **)malloc((total + 2) * sizeof(char *)); char **token_ptr = tokens; char *buffer = (char *)malloc((strlen(str) + 1) * sizeof(char)); strcpy(buffer, str); char *token = strtok(buffer, delim); while (token) { *token_ptr = (char *)malloc((strlen(token) + 1) * sizeof(char)); strcpy(*token_ptr, token); token_ptr++; token = strtok(NULL, delim); } *token_ptr = NULL; if (count) { *count = token_ptr - tokens; } free(buffer); return tokens; } size_t rstrip(char *str, const char *chars) { size_t str_len = strlen(str); if (!str_len) { return 0; } size_t chars_count = strlen(chars); size_t offset; size_t i; for (offset = str_len - 1; offset >= 0; offset--) { for (i = 0; i < chars_count; i++) { if (str[offset] == chars[i]) { break; } } if (i == chars_count) { break; } } offset++; str[offset] = 0; return offset; } size_t strip(char *str, const char *chars) { size_t chars_count = strlen(chars); size_t str_len = strlen(str); size_t offset; size_t i; for (offset = 0; offset < str_len; offset++) { for (i = 0; i < chars_count; i++) { if (str[offset] == chars[i]) { break; } } if (i == chars_count) { break; } } if(offset) { strcpy(str, str + offset); } return rstrip(str, chars); }
3.25
3
2024-11-18T21:19:22.791885+00:00
2021-06-06T21:28:21
b22e08fea6f59128a038c4b06304d25fd86bd893
{ "blob_id": "b22e08fea6f59128a038c4b06304d25fd86bd893", "branch_name": "refs/heads/main", "committer_date": "2021-06-06T21:28:21", "content_id": "7d2864c7a0578affe40da61977e9a12ba823cce9", "detected_licenses": [ "MIT" ], "directory_id": "0b82e6c340618e23bcdc1b81562921e79f58a13b", "extension": "h", "filename": "rpi.h", "fork_events_count": 0, "gha_created_at": "2021-06-05T10:02:27", "gha_event_created_at": "2021-06-05T10:02:27", "gha_language": null, "gha_license_id": "MIT", "github_id": 374079844, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1667, "license": "MIT", "license_type": "permissive", "path": "/labs/3-bootloader/pi-side/libpi.small/rpi.h", "provenance": "stackv2-0128.json.gz:311893", "repo_name": "aym-v/cs140e-21spr", "revision_date": "2021-06-06T21:28:21", "revision_id": "cb8460f5e4517ed03d47db40f81dd25470e1dab6", "snapshot_id": "81f0ee46814778d8a3aa5169da035ca4c0068fd4", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/aym-v/cs140e-21spr/cb8460f5e4517ed03d47db40f81dd25470e1dab6/labs/3-bootloader/pi-side/libpi.small/rpi.h", "visit_date": "2023-05-23T11:57:08.921107" }
stackv2
#ifndef __SMALL_RPI_H__ #define __SMALL_RPI_H__ // engler, cs140e // helper routine definitions. // reboot the pi: call this so you don't have to pull the ttyserial // out/in to hard reset it. void rpi_reboot(void); // jump to <addr>: note, will return to the caller // of BRANCHTO. is defined in the file <start.s> void BRANCHTO(unsigned addr); // get current value of micro-second counter. unsigned timer_get_usec(void); // block for <ms> milliseconds. void delay_ms(unsigned ms); /**************************************************************** * simple memory read/write routines. */ // write the 32-bit value <v> to address <addr> // *(unsigned *)addr = v; void PUT32(unsigned addr, unsigned v); void put32(volatile void *addr, unsigned v); // write the 8-bite value <v> to address <addr> // *(unsigned char *)addr = v; void PUT8(unsigned addr, unsigned v); // read and return the 32-bit value at address <addr> // *(unsigned *)addr unsigned GET32(unsigned addr); unsigned get32(const volatile void *addr); /**************************************************************** * the UART hardware on the pi sends/receives bytes from the * ttyserial we have plugged into it. * * like most hardware: you have to initialize first. then * you can read/write. */ // initialize UART. MUST BE CALLED or bad things // will happen. void uart_init(void); // read 1 byte from UART. int uart_getc(void); // write 1 byte to UART void uart_putc(unsigned c); // does UART have data available? int uart_has_data(void); // null routine you can call to defeat compiler. void dummy(unsigned); // flush out the tx fifo void uart_flush_tx(void); #endif
2.203125
2
2024-11-18T21:19:25.916098+00:00
2021-01-11T13:40:44
a9d278ac69d17023d1214f853172ecbc77f02da2
{ "blob_id": "a9d278ac69d17023d1214f853172ecbc77f02da2", "branch_name": "refs/heads/master", "committer_date": "2021-01-11T13:40:44", "content_id": "12a5c080029eb4acd54ff6fe4fef84ceb68aedd0", "detected_licenses": [], "directory_id": "d6cca5444e830b6b69457f59d60b4e370d08a726", "extension": "c", "filename": "time.c", "fork_events_count": 0, "gha_created_at": "2020-02-23T08:27:10", "gha_event_created_at": "2021-01-11T13:40:45", "gha_language": "C", "gha_license_id": "BSD-3-Clause", "github_id": 242481849, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1583, "license": "", "license_type": "permissive", "path": "/sys/kern/time.c", "provenance": "stackv2-0128.json.gz:312546", "repo_name": "fengjixuchui/mimiker", "revision_date": "2021-01-11T13:40:44", "revision_id": "debb8bbf6bd059dfb550a903e4b22c687acdd79a", "snapshot_id": "98cdc9ef4b62cf90a966c2e419d0744fea6f893c", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/fengjixuchui/mimiker/debb8bbf6bd059dfb550a903e4b22c687acdd79a/sys/kern/time.c", "visit_date": "2021-01-13T20:14:18.533698" }
stackv2
#include <sys/errno.h> #include <sys/time.h> int do_clock_gettime(clockid_t clk, timespec_t *tp) { bintime_t bin; switch (clk) { case CLOCK_REALTIME: bin = bintime(); break; case CLOCK_MONOTONIC: bin = binuptime(); break; default: return EINVAL; } bt2ts(&bin, tp); return 0; } int do_clock_nanosleep(clockid_t clk, int flags, const timespec_t *rqtp, timespec_t *rmtp) { return ENOTSUP; } time_t tm2sec(tm_t *t) { if (t->tm_year < 70) return 0; const int32_t year_scale_s = 31536000, day_scale_s = 86400, hour_scale_s = 3600, min_scale_s = 60; time_t res = 0; static const int month_in_days[13] = {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334}; res += (time_t)month_in_days[t->tm_mon] * day_scale_s; /* Extra days from leap years which already past (EPOCH) */ res += (time_t)((t->tm_year + 1900) / 4 - (1970) / 4) * day_scale_s; res -= (time_t)((t->tm_year + 1900) / 100 - (1970) / 100) * day_scale_s; res += (time_t)((t->tm_year + 1900) / 400 - (1970) / 400) * day_scale_s; /* If actual year is a leap year and the leap day passed */ if (t->tm_mon > 1 && (t->tm_year % 4) == 0 && ((t->tm_year % 100) != 0 || (t->tm_year + 1900) % 400) == 0) res += day_scale_s; /* (t.tm_mday - 1) - cause days are in range [1-31] */ return (time_t)(t->tm_year - 70) * year_scale_s + (t->tm_mday - 1) * day_scale_s + t->tm_hour * hour_scale_s + t->tm_min * min_scale_s + t->tm_sec + res; }
2.59375
3
2024-11-18T21:19:26.121908+00:00
2017-06-07T18:20:28
c73d2a3eee3102e2a57032e529b1d57bdcea2c22
{ "blob_id": "c73d2a3eee3102e2a57032e529b1d57bdcea2c22", "branch_name": "refs/heads/master", "committer_date": "2017-06-07T18:20:28", "content_id": "040d167eb9328b60f72e04bfb3f641d9cf3d872b", "detected_licenses": [ "MIT" ], "directory_id": "bc34e846ec1e44dbe3ae111c5ede3a1ef8bd6b0d", "extension": "c", "filename": "first_nonrepeated_character.c", "fork_events_count": 0, "gha_created_at": "2017-03-21T22:41:07", "gha_event_created_at": "2017-06-07T18:20:29", "gha_language": "Python", "gha_license_id": null, "github_id": 85760814, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 941, "license": "MIT", "license_type": "permissive", "path": "/Arrays/first_nonrepeated_character.c", "provenance": "stackv2-0128.json.gz:312810", "repo_name": "Kunal57/Project_9498", "revision_date": "2017-06-07T18:20:28", "revision_id": "eaf31e0b9f5a76a5c90fe14a2c8e1fc9303ca8eb", "snapshot_id": "f28befa0d6f589c3952ed14c6ed07fb223fb0b61", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Kunal57/Project_9498/eaf31e0b9f5a76a5c90fe14a2c8e1fc9303ca8eb/Arrays/first_nonrepeated_character.c", "visit_date": "2021-01-18T04:09:12.258986" }
stackv2
// Write an efficient function to find the first non-repeated character in a string. For instance, the first non-repeated character in "total" is "o" and the first non-repeated character in "teeter" is "r". Discuss the efficiency of your algorithm. #include <stdio.h> struct hashtable{ int letter; int freq; }; int nonrepeat_character(char word[]); int main(void){ char word[] = "teeter"; printf("%c\n", nonrepeat_character(word)); return 0; } int nonrepeat_character(char word[]){ struct hashtable alpha[26]; for(int z = 0; z < 26; z++){ alpha[z].letter = 'a' + z; alpha[z].freq = 0; } for(int i = 0; word[i] != '\0'; i++){ int index = word[i] - 'a'; if((alpha[index].letter) == word[i]){ alpha[index].freq += 1; } } for(int x = 0; word[x] != '\0'; x++){ int index = word[x] - 'a'; if((alpha[index].freq) == 1){ return alpha[index].letter; } } return -1; }
3.6875
4
2024-11-18T21:19:26.327660+00:00
2021-01-18T16:29:03
e1dea0c2fddb6a44f42f47897335d15f382bd747
{ "blob_id": "e1dea0c2fddb6a44f42f47897335d15f382bd747", "branch_name": "refs/heads/main", "committer_date": "2021-01-18T16:29:03", "content_id": "c453d329fcf97a8dbf0bf35cde420dd027f7dc42", "detected_licenses": [ "Apache-2.0" ], "directory_id": "077c17273836b0ab2131c0e750eb622450b59389", "extension": "c", "filename": "pool.c", "fork_events_count": 0, "gha_created_at": "2020-12-17T00:21:16", "gha_event_created_at": "2020-12-17T00:21:17", "gha_language": null, "gha_license_id": "Apache-2.0", "github_id": 322135145, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2777, "license": "Apache-2.0", "license_type": "permissive", "path": "/src/server/pool.c", "provenance": "stackv2-0128.json.gz:313201", "repo_name": "hanssy130/HTTP-Server", "revision_date": "2021-01-18T16:29:03", "revision_id": "0a718eee3ef60b0aae918a63b349e5ecc5766872", "snapshot_id": "1101de18f133bbd1ce477bd1ee5631f893897851", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/hanssy130/HTTP-Server/0a718eee3ef60b0aae918a63b349e5ecc5766872/src/server/pool.c", "visit_date": "2023-02-19T13:30:19.205203" }
stackv2
#include <semaphore.h> #include "pool.h" void *dealer(void *vargp) { int sfd = ((int*)vargp)[0]; int id = ((int*)vargp)[1]; Config config = ((Config*)vargp)[2]; sem_t* config_mutex = ((sem_t**)vargp)[3]; for(;;){ // Check if server is running with processes // If yes, break. int cfd = dc_accept(sfd, NULL, NULL); sem_wait(config_mutex); fprintf(stderr, "%s %d is dealing with client fd %d\n",(config->concurr_opt == CONCURR_OPT_THREAD) ? "Thread" : "Process", id+1, cfd); char client_request[BUF_SIZE]; ssize_t request_len; while((request_len = dc_read(cfd, client_request, BUF_SIZE)) > 0) { fprintf(stderr, "============= Request received ========\n"); char file_name[BUF_SIZE]; strcat(file_name, config->root); sem_post(config_mutex); int request_code = parse_request(client_request, file_name, request_len); fprintf(stderr, "============= Request parsed ==========\n"); if (request_code) { respond(cfd, file_name, request_code, config, config_mutex); fprintf(stderr, "============= Responded =======\n"); } else { fprintf(stderr, "============= No response ========\n"); } } dc_close(cfd); } } void threadz(int sfd, Config config, sem_t* config_mutex) { pthread_t thread_id; int dealer_args_arr[config->connections][2]; for (int i = 0; i < config->connections; i++) { dealer_args_arr[i][0] = sfd; dealer_args_arr[i][1] = i; void * args_arr[4] = {dealer_args_arr[i][0], dealer_args_arr[i][1], config, config_mutex}; pthread_create(&thread_id, NULL, dealer, args_arr); } pthread_join(thread_id, NULL); // wait for the last thread to end } void processez(int sfd, Config config, sem_t* config_mutex) { pid_t child_pid, wpid; int ret, status; int dealer_args_arr[config->connections][2]; for (int i = 0; i < config->connections; i++) { dealer_args_arr[i][0] = sfd; dealer_args_arr[i][1] = i; child_pid = fork(); if(child_pid == -1) { perror("fork"); exit(EXIT_FAILURE); } else if(child_pid == 0) { //Child void * args_arr[4] = {dealer_args_arr[i][0], dealer_args_arr[i][1], config, config_mutex}; dealer(args_arr); break; } } do { wpid = waitpid(child_pid, &status, WUNTRACED); if (wpid == -1) { perror("waitpid"); exit(EXIT_FAILURE); } fprintf(stderr, "child exited, status=%d\n", WEXITSTATUS(status)); } while (!WIFEXITED(status) && !WIFSIGNALED(status)); }
2.671875
3
2024-11-18T21:19:26.415069+00:00
2022-10-09T10:50:16
e1884901e8a4de17bfa22d228ab307c381bf4373
{ "blob_id": "e1884901e8a4de17bfa22d228ab307c381bf4373", "branch_name": "refs/heads/master", "committer_date": "2022-10-09T10:50:16", "content_id": "5d495e4b82a05e59497af24e10c27ef31c866835", "detected_licenses": [ "MIT" ], "directory_id": "1b7bafe67501772928d9d6ff79ca77286f11784d", "extension": "c", "filename": "parser.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 223670296, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 9719, "license": "MIT", "license_type": "permissive", "path": "/src/parser.c", "provenance": "stackv2-0128.json.gz:313333", "repo_name": "borodust/libresect", "revision_date": "2022-10-09T10:50:16", "revision_id": "305cf234b9ade75d2ffcee66bf88563ba1e85d1a", "snapshot_id": "b729863f9061c559115eef10cc7648502280bab0", "src_encoding": "UTF-8", "star_events_count": 8, "url": "https://raw.githubusercontent.com/borodust/libresect/305cf234b9ade75d2ffcee66bf88563ba1e85d1a/src/parser.c", "visit_date": "2022-10-27T11:25:45.730676" }
stackv2
#include "../resect.h" #include "resect_private.h" #include <stdlib.h> #include <string.h> #include <clang-c/Index.h> /* * PARSER */ struct P_resect_parse_options { resect_collection args; resect_bool single; resect_bool diagnostics; resect_collection included_definition_patterns; resect_collection included_source_patterns; resect_collection excluded_definition_patterns; resect_collection excluded_source_patterns; resect_collection enforced_definition_patterns; resect_collection enforced_source_patterns; }; void resect_options_add(resect_parse_options opts, const char *key, const char *value) { resect_collection_add(opts->args, resect_string_from_c(key)); resect_collection_add(opts->args, resect_string_from_c(value)); } void resect_options_add_concat(resect_parse_options opts, const char *key, const char *value) { resect_collection_add(opts->args, resect_string_format("%s%s", key, value)); } resect_parse_options resect_options_create() { resect_parse_options opts = malloc(sizeof(struct P_resect_parse_options)); opts->args = resect_collection_create(); opts->single = resect_false; opts->diagnostics = resect_false; opts->included_definition_patterns = resect_collection_create(); opts->included_source_patterns = resect_collection_create(); opts->excluded_definition_patterns = resect_collection_create(); opts->excluded_source_patterns = resect_collection_create(); opts->enforced_definition_patterns = resect_collection_create(); opts->enforced_source_patterns = resect_collection_create(); resect_collection_add(opts->args, resect_string_from_c("-ferror-limit=0")); resect_collection_add(opts->args, resect_string_from_c("-fno-implicit-templates")); resect_collection_add(opts->args, resect_string_from_c("-fc++-abi=itanium")); return opts; } void resect_options_free(resect_parse_options opts) { resect_string_collection_free(opts->args); resect_string_collection_free(opts->included_definition_patterns); resect_string_collection_free(opts->included_source_patterns); resect_string_collection_free(opts->excluded_definition_patterns); resect_string_collection_free(opts->excluded_source_patterns); resect_string_collection_free(opts->enforced_definition_patterns); resect_string_collection_free(opts->enforced_source_patterns); free(opts); } void resect_options_include_definition(resect_parse_options opts, const char *name) { resect_collection_add(opts->included_definition_patterns, resect_string_from_c(name)); } void resect_options_include_source(resect_parse_options opts, const char *name) { resect_collection_add(opts->included_source_patterns, resect_string_from_c(name)); } void resect_options_exclude_definition(resect_parse_options opts, const char *name) { resect_collection_add(opts->excluded_definition_patterns, resect_string_from_c(name)); } void resect_options_exclude_source(resect_parse_options opts, const char *name) { resect_collection_add(opts->excluded_source_patterns, resect_string_from_c(name)); } void resect_options_enforce_definition(resect_parse_options opts, const char *name) { resect_collection_add(opts->enforced_definition_patterns, resect_string_from_c(name)); } void resect_options_enforce_source(resect_parse_options opts, const char *name) { resect_collection_add(opts->enforced_source_patterns, resect_string_from_c(name)); } resect_collection resect_options_get_included_definitions(resect_parse_options opts) { return opts->included_definition_patterns; } resect_collection resect_options_get_included_sources(resect_parse_options opts) { return opts->included_source_patterns; } resect_collection resect_options_get_excluded_definitions(resect_parse_options opts) { return opts->excluded_definition_patterns; } resect_collection resect_options_get_excluded_sources(resect_parse_options opts) { return opts->enforced_source_patterns; } resect_collection resect_options_get_enforced_definitions(resect_parse_options opts) { return opts->enforced_definition_patterns; } resect_collection resect_options_get_enforced_sources(resect_parse_options opts) { return opts->excluded_source_patterns; } void resect_options_add_include_path(resect_parse_options opts, const char *path) { resect_options_add(opts, "--include-directory", path); } void resect_options_add_framework_path(resect_parse_options opts, const char *framework) { resect_options_add_concat(opts, "-F", framework); } void resect_options_add_abi(resect_parse_options opts, const char *value) { resect_options_add_concat(opts, "-mabi=", value); } void resect_options_add_arch(resect_parse_options opts, const char *value) { resect_options_add_concat(opts, "-march=", value); } void resect_options_add_cpu(resect_parse_options opts, const char *value) { resect_options_add_concat(opts, "-mcpu=", value); } void resect_options_add_language(resect_parse_options opts, const char *lang) { resect_options_add_concat(opts, "--language=", lang); } void resect_options_add_define(resect_parse_options opts, const char *name, const char *value) { resect_string define = resect_string_format("-D%s=%s", name, value); resect_collection_add(opts->args, define); } void resect_options_add_standard(resect_parse_options opts, const char *standard) { resect_options_add_concat(opts, "--std=", standard); } void resect_options_add_target(resect_parse_options opts, const char *target) { resect_options_add_concat(opts, "--target=", target); } void resect_options_intrinsic(resect_parse_options opts, resect_option_intrinsic intrinsic) { if (intrinsic == RESECT_OPTION_INTRINSICS_NEON) { resect_options_add_concat(opts, "-mfpu=neon", ""); return; } char *intrinsic_name; switch (intrinsic) { case RESECT_OPTION_INTRINSICS_SSE: intrinsic_name = "sse"; break; case RESECT_OPTION_INTRINSICS_SSE2: intrinsic_name = "sse2"; break; case RESECT_OPTION_INTRINSICS_SSE3: intrinsic_name = "sse3"; break; case RESECT_OPTION_INTRINSICS_SSE41: intrinsic_name = "sse4.1"; break; case RESECT_OPTION_INTRINSICS_SSE42: intrinsic_name = "sse4.2"; break; case RESECT_OPTION_INTRINSICS_AVX: intrinsic_name = "avx"; break; case RESECT_OPTION_INTRINSICS_AVX2: intrinsic_name = "avx2"; break; default: return; } resect_options_add_concat(opts, "-m", intrinsic_name); } void resect_options_single_header(resect_parse_options opts) { opts->single = resect_true; } void resect_options_print_diagnostics(resect_parse_options opts) { opts->diagnostics = resect_true; } /* * UNIT */ struct P_resect_translation_unit { resect_collection declarations; resect_translation_context context; }; resect_collection resect_unit_declarations(resect_translation_unit unit) { return unit->declarations; } resect_language resect_unit_get_language(resect_translation_unit unit) { return resect_get_assumed_language(unit->context); } resect_translation_unit resect_parse(const char *filename, resect_parse_options options) { char **clang_argv; int clang_argc; if (options != NULL) { clang_argc = (int) resect_collection_size(options->args); clang_argv = malloc(clang_argc * sizeof(char *)); resect_iterator arg_iter = resect_collection_iterator(options->args); int i = 0; while (resect_iterator_next(arg_iter)) { resect_string arg = resect_iterator_value(arg_iter); clang_argv[i++] = (char *) resect_string_to_c(arg); } resect_iterator_free(arg_iter); } else { clang_argc = 0; clang_argv = NULL; } resect_translation_context context = resect_context_create(options); CXIndex index = clang_createIndex(0, options->diagnostics ? 1 : 0); enum CXTranslationUnit_Flags unitFlags = CXTranslationUnit_DetailedPreprocessingRecord | CXTranslationUnit_KeepGoing | CXTranslationUnit_SkipFunctionBodies | CXTranslationUnit_IncludeAttributedTypes | CXTranslationUnit_VisitImplicitAttributes; if (options->single) { unitFlags |= CXTranslationUnit_SingleFileParse; } CXTranslationUnit clangUnit = clang_parseTranslationUnit(index, filename, (const char *const *) clang_argv, clang_argc, NULL, 0, unitFlags); free(clang_argv); CXCursor cursor = clang_getTranslationUnitCursor(clangUnit); clang_visitChildren(cursor, resect_visit_context_child, context); clang_disposeTranslationUnit(clangUnit); clang_disposeIndex(index); resect_translation_unit result = malloc(sizeof(struct P_resect_translation_unit)); result->context = context; result->declarations = resect_create_decl_collection(context); return result; } void resect_free(resect_translation_unit result) { resect_set deallocated = resect_set_create(); resect_context_free(result->context, deallocated); resect_collection_free(result->declarations); resect_set_free(deallocated); free(result); }
2.015625
2
2024-11-18T21:19:26.798155+00:00
2020-08-09T09:39:46
35d66b7bc5167ce03d6df068c920e32cb959bae7
{ "blob_id": "35d66b7bc5167ce03d6df068c920e32cb959bae7", "branch_name": "refs/heads/master", "committer_date": "2020-08-09T09:39:46", "content_id": "1170cc2f5df820a988e4cba475c5ee675db748c4", "detected_licenses": [ "MIT" ], "directory_id": "b0d8667e056c9d0af5827b4659125f0dac0e5140", "extension": "h", "filename": "nat_flow.h", "fork_events_count": 10, "gha_created_at": "2017-06-26T22:08:23", "gha_event_created_at": "2022-01-26T09:19:46", "gha_language": "C", "gha_license_id": "MIT", "github_id": 95493612, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 864, "license": "MIT", "license_type": "permissive", "path": "/nf/unverified-nat/nat_flow.h", "provenance": "stackv2-0128.json.gz:313461", "repo_name": "vignat/vignat", "revision_date": "2020-08-09T09:39:46", "revision_id": "a280162f63432f14324516cb7b4c298f80bee338", "snapshot_id": "c55e9c99a66691295ba395e7233a225de8097640", "src_encoding": "UTF-8", "star_events_count": 76, "url": "https://raw.githubusercontent.com/vignat/vignat/a280162f63432f14324516cb7b4c298f80bee338/nf/unverified-nat/nat_flow.h", "visit_date": "2022-02-03T05:28:20.949309" }
stackv2
#pragma once #include <inttypes.h> #include <string.h> struct nat_flow_id { uint32_t src_addr; uint16_t src_port; uint32_t dst_addr; uint16_t dst_port; // To use DPDK maps, this type must have a power of 2 size, // so we make this 32-bit even though it only needs 8 uint32_t protocol; } __attribute__((__packed__)); static uint64_t nat_flow_id_hash(struct nat_flow_id id) { uint64_t hash = 17; hash = hash * 31 + id.src_addr; hash = hash * 31 + id.src_port; hash = hash * 31 + id.dst_addr; hash = hash * 31 + id.dst_port; hash = hash * 31 + id.protocol; return hash; } static bool nat_flow_id_eq(struct nat_flow_id left, struct nat_flow_id right) { return 1 - memcmp(&left, &right, sizeof(struct nat_flow_id)); } struct nat_flow { struct nat_flow_id id; uint8_t internal_device; uint16_t external_port; uint32_t last_packet_timestamp; };
2.328125
2
2024-11-18T21:19:26.921925+00:00
2012-01-29T23:53:42
797d0dcaffa8365a2b1cfea8ea5af5ca5bc4586c
{ "blob_id": "797d0dcaffa8365a2b1cfea8ea5af5ca5bc4586c", "branch_name": "refs/heads/master", "committer_date": "2012-01-29T23:53:42", "content_id": "d316cea9ea2301a9c0f15146552861bae9570813", "detected_licenses": [ "MIT" ], "directory_id": "b642c2ede0f494f197679090ea0ac8e849a00da4", "extension": "h", "filename": "stack.h", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 3300797, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 255, "license": "MIT", "license_type": "permissive", "path": "/src/stack.h", "provenance": "stackv2-0128.json.gz:313720", "repo_name": "jdpage/tarpit", "revision_date": "2012-01-29T23:53:42", "revision_id": "ab6be40128e41091b54eee74d7c476fd9a49f1c7", "snapshot_id": "b154de94079bbbcfb903bab50aea9111c8f42572", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/jdpage/tarpit/ab6be40128e41091b54eee74d7c476fd9a49f1c7/src/stack.h", "visit_date": "2021-01-15T22:29:30.323236" }
stackv2
#pragma once #include <stdint.h> typedef struct stack { uint32_t v; struct stack *next; } stack_t; stack_t *stack_push(stack_t *self, uint32_t val); stack_t *stack_pop(stack_t *self); int stack_size(stack_t *self); void stack_liberate(stack_t *self);
2.015625
2
2024-11-18T21:19:26.974513+00:00
2013-11-01T02:38:42
b343e3d79d084e40c695239cc9f52b0ece7453d3
{ "blob_id": "b343e3d79d084e40c695239cc9f52b0ece7453d3", "branch_name": "refs/heads/master", "committer_date": "2013-11-01T02:38:42", "content_id": "699483a4edcd1b747196ae3d30f10b7134ab0a1b", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "6327ff86914ea89795e33b050872688d9a2119a1", "extension": "h", "filename": "lib_eeprom.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 13330671, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1342, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/from-serial/lib_eeprom.h", "provenance": "stackv2-0128.json.gz:313851", "repo_name": "skeezix/zikburner", "revision_date": "2013-11-01T02:38:42", "revision_id": "d38e384b7737b65bacb6bf1cb33375dcf56560c8", "snapshot_id": "30c61490dd3d3b0d72a7aca59f17268730f31824", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/skeezix/zikburner/d38e384b7737b65bacb6bf1cb33375dcf56560c8/from-serial/lib_eeprom.h", "visit_date": "2021-01-06T20:41:15.780226" }
stackv2
#ifndef h_lib_eeprom_h #define h_lib_eeprom_h // reset() -- take eeprom to safe state; no reading/writing going on, directions are set up, etc. void eeprom_reset ( void ); // read against current address; assumes data directions are set right unsigned char eeprom_read ( void ); static inline void eeprom_setup_write ( void ) { DDRB = 0xFF; // data bus DDRD |= (1<<PD5); // data bus bit 8 } static inline void eeprom_setup_read ( void ) { DDRB = 0x00; // data bus DDRD &= ~(1<<PD5); // data bus bit 8 } // burn_slow() -- attempt to burn a buffer to the target device; it is 'slow' in the sense // where no attempt is made to burn rapidly using 'page write' or the like; it takes its // time. // // address -- target // p -- buffer // len -- len to iterate across buffer // // Returns >0 on success, 0 on error unsigned char eeprom_burn_slow ( unsigned int address, unsigned char *p, unsigned int len ); // compare() -- given a buffer and len, read starting at the given address and ensure // target device matches the buffer. // // Returns >0 on success (they match), 0 on error (something wasn't a match) unsigned char eeprom_compare ( unsigned int address, unsigned char *p, unsigned int len ); // dump() -- display hexdump to serial void eeprom_dump ( unsigned int address, unsigned int len ); #endif
2.375
2
2024-11-18T21:19:28.070388+00:00
2018-02-27T01:20:03
6ddc8acfc967048fe1c6c2c77c4c322bd412b441
{ "blob_id": "6ddc8acfc967048fe1c6c2c77c4c322bd412b441", "branch_name": "refs/heads/master", "committer_date": "2018-02-27T01:20:03", "content_id": "94cb6e4ce49cdfe3ae2906ee067d78715d36a171", "detected_licenses": [ "MIT" ], "directory_id": "3291b61bedfdec3cc6136692fad67aaf8440cc3e", "extension": "h", "filename": "errors.h", "fork_events_count": 0, "gha_created_at": "2018-02-27T01:17:35", "gha_event_created_at": "2018-02-27T01:17:35", "gha_language": null, "gha_license_id": "MIT", "github_id": 123053450, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 387, "license": "MIT", "license_type": "permissive", "path": "/lib/errors.h", "provenance": "stackv2-0128.json.gz:314371", "repo_name": "shtukas/lambda-zero", "revision_date": "2018-02-27T01:20:03", "revision_id": "d3b627688e78d2e32bf4aedbfcb6ca93fc1e4fd5", "snapshot_id": "517822c1e420050f20d7cab8bc7ca5e722c3ee6c", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/shtukas/lambda-zero/d3b627688e78d2e32bf4aedbfcb6ca93fc1e4fd5/lib/errors.h", "visit_date": "2021-01-24T10:27:46.663285" }
stackv2
#ifndef ERRORS_H #define ERRORS_H #include <stdlib.h> #include <stdio.h> typedef const char* strings[]; static inline void errorArray(int count, const char* strs[]) { for (int i = 0; i < count; i++) fputs(strs[i], stderr); } static inline void error(const char* type, const char* message) { errorArray(3, (strings){type, " error: ", message}); exit(1); } #endif
2.125
2
2024-11-18T21:19:28.254867+00:00
2021-10-27T14:46:07
3577a09e5f47c9e6417e9854bef508f0225d6795
{ "blob_id": "3577a09e5f47c9e6417e9854bef508f0225d6795", "branch_name": "refs/heads/master", "committer_date": "2021-10-27T14:51:13", "content_id": "339d9b12eb2876a74c3e6ac1d1ccb5b804481ef4", "detected_licenses": [ "MIT" ], "directory_id": "50838125c4fb8a0cee8a5119a5bdf6ba0dd0603d", "extension": "h", "filename": "led.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 190998115, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1178, "license": "MIT", "license_type": "permissive", "path": "/STM32_Source/Projects/Nixie_Clock/led/led.h", "provenance": "stackv2-0128.json.gz:314633", "repo_name": "lcc816/NixieClock", "revision_date": "2021-10-27T14:46:07", "revision_id": "294825dc42f7cd29133611a36761c16c32f488d8", "snapshot_id": "ab0ce0e42d4e833ccd05189a620710219af6946b", "src_encoding": "UTF-8", "star_events_count": 7, "url": "https://raw.githubusercontent.com/lcc816/NixieClock/294825dc42f7cd29133611a36761c16c32f488d8/STM32_Source/Projects/Nixie_Clock/led/led.h", "visit_date": "2021-11-30T21:44:23.337301" }
stackv2
/** ****************************************************************************** * @file led.h * @author Lichangchun * @version * @date 6-Sept-2017 * @brief ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __LED_H #define __LED_H /* Includes ------------------------------------------------------------------*/ #include "stm32f10x.h" /* Exported types ------------------------------------------------------------*/ /* Exported constants --------------------------------------------------------*/ /* Exported macro ------------------------------------------------------------*/ /* Exported define -----------------------------------------------------------*/ #define LED_PIN GPIO_Pin_13 #define LED_GPIO_PORT GPIOC #define LED_GPIO_CLK RCC_APB2Periph_GPIOC /* Exported functions ------------------------------------------------------- */ void LED_Init(void); void LED_Off(void); void LED_On(void); void LED_Flip(void); #endif /* __LED_H */
2.0625
2
2024-11-18T21:19:28.561694+00:00
2020-07-29T08:59:12
9e54aafc54fa1fa63a024cb7e8a2adf0d7a59492
{ "blob_id": "9e54aafc54fa1fa63a024cb7e8a2adf0d7a59492", "branch_name": "refs/heads/master", "committer_date": "2020-07-29T08:59:12", "content_id": "b37c09eccd6c98a3eaed649959733b66079ff2c2", "detected_licenses": [ "MIT" ], "directory_id": "8d7459d8801605d0516c461d3c4a71f38199c8be", "extension": "c", "filename": "args.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 277500159, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 248, "license": "MIT", "license_type": "permissive", "path": "/Section1/args.c", "provenance": "stackv2-0128.json.gz:315027", "repo_name": "mevljas/Programming-Language-C", "revision_date": "2020-07-29T08:59:12", "revision_id": "b1964288327bfc63bc64f763c6a22f5eb368c5e1", "snapshot_id": "1966d17669ea278811f9deb5586b9ca02469cdfb", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/mevljas/Programming-Language-C/b1964288327bfc63bc64f763c6a22f5eb368c5e1/Section1/args.c", "visit_date": "2022-11-23T16:27:18.491149" }
stackv2
#include<stdio.h> int main( int argc, char * args[]){ // Prvi argument je ime programa printf("Ime programa: %s\n", args[0]); // Pravi argumenti so od 1 do argc-1 for(int i=1; i<argc; i++) printf("%d. %s\n", i, args[i]); return 0; }
2.828125
3
2024-11-18T21:19:29.175257+00:00
2019-12-01T06:22:25
b8171dd0418876aff2a3c804c947418a55f0a213
{ "blob_id": "b8171dd0418876aff2a3c804c947418a55f0a213", "branch_name": "refs/heads/master", "committer_date": "2019-12-01T06:22:25", "content_id": "43fc5bdd4075fb657bc9e61d300f6dfb34011289", "detected_licenses": [ "Apache-2.0" ], "directory_id": "f0ee972868e2899e42be0252fe4e8320f7237bd8", "extension": "c", "filename": "mem.c", "fork_events_count": 1, "gha_created_at": "2022-11-20T13:08:07", "gha_event_created_at": "2022-11-20T13:08:08", "gha_language": null, "gha_license_id": "Apache-2.0", "github_id": 568412305, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4510, "license": "Apache-2.0", "license_type": "permissive", "path": "/emulator/sdk/hw/core/mem.c", "provenance": "stackv2-0128.json.gz:315158", "repo_name": "chcbaram/oroca_boy3", "revision_date": "2019-12-01T06:22:25", "revision_id": "6947545baff0d73f15523abb222053c3e5c6ac18", "snapshot_id": "b3d5f82e2233697cfc5d9532961de2b3649891e6", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/chcbaram/oroca_boy3/6947545baff0d73f15523abb222053c3e5c6ac18/emulator/sdk/hw/core/mem.c", "visit_date": "2023-03-16T02:55:41.988393" }
stackv2
/* * mem.c * * Created on: 2019. 11. 2. * Author: Baram */ #include "mem.h" //-- Internal Variables // static uint32_t __heap_start = SDRAM_ADDR_HEAP; static uint32_t __heap_limit = SDRAM_ADDR_HEAP + 16*1024*1024; //-- External Variables // //-- Internal Functions // static void *malloc_(size_t size); static void free_(void *ptr); static void *calloc_(size_t nmemb, size_t size); static void *realloc_(void *ptr, size_t size); //-- External Functions // void memInit(uint32_t addr, uint32_t length) { __heap_start = addr; __heap_limit = addr + length; } void *memMalloc(uint32_t size) { return malloc_(size); } void memFree(void *ptr) { free_(ptr); } void *memCalloc(size_t nmemb, size_t size) { return calloc_(nmemb, size); } void *memRealloc(void *ptr, size_t size) { return realloc_(ptr, size); } #include <unistd.h> #include <errno.h> static inline size_t word_align(size_t size) { return size + ((sizeof(size_t) - 1) & ~(sizeof(size_t) - 1)); } struct chunk { struct chunk *next, *prev; size_t size; int free; void *data; }; typedef struct chunk *Chunk; static caddr_t sbrk_(int incr) { static char *heap_end = (char *)0; static char *heap_limit = (char *)0; char *prev_heap_end; heap_limit = (char *)__heap_limit; if (heap_end == 0) heap_end = (char *)__heap_start; prev_heap_end = heap_end; if (heap_end + incr > heap_limit) { errno = ENOMEM; // not enough memory return (caddr_t) -1; } heap_end += incr; if ((int)heap_end%4 != 0) { heap_end += 4 - ((int)heap_end%4); } return (caddr_t) prev_heap_end; } static void *malloc_base() { static Chunk b = NULL; if (!b) { b = (Chunk)sbrk_(word_align(sizeof(struct chunk))); if (b == (void*) -1) { //_exit(127); while(1); } b->next = NULL; b->prev = NULL; b->size = 0; b->free = 0; b->data = NULL; } return b; } static Chunk malloc_chunk_find(size_t s, Chunk *heap) { Chunk c = (Chunk)malloc_base(); for (; c && (!c->free || c->size < s); *heap = c, c = c->next); return c; } static void malloc_merge_next(Chunk c) { c->size = c->size + c->next->size + sizeof(struct chunk); c->next = c->next->next; if (c->next) { c->next->prev = c; } } static void malloc_split_next(Chunk c, size_t size) { Chunk newc = (Chunk)((char*) c + size); newc->prev = c; newc->next = c->next; newc->size = c->size - size; newc->free = 1; newc->data = newc + 1; if (c->next) { c->next->prev = newc; } c->next = newc; c->size = size - sizeof(struct chunk); } static void *malloc_(size_t size) { if (!size) return NULL; size_t length = word_align(size + sizeof(struct chunk)); Chunk prev = NULL; Chunk c = malloc_chunk_find(size, &prev); if (!c) { Chunk newc = (Chunk)sbrk_(length); if (newc == (void*) -1) { return NULL; } newc->next = NULL; newc->prev = prev; newc->size = length - sizeof(struct chunk); newc->data = newc + 1; prev->next = newc; c = newc; } else if (length + sizeof(size_t) < c->size) { malloc_split_next(c, length); } c->free = 0; return c->data; } static void free_(void *ptr) { if (!ptr || ptr < malloc_base() || (caddr_t)ptr > sbrk_(0)) return; Chunk c = (Chunk) ptr - 1; if (c->data != ptr) return; c->free = 1; if (c->next && c->next->free) { malloc_merge_next(c); } if (c->prev->free) { malloc_merge_next(c = c->prev); } if (!c->next) { c->prev->next = NULL; sbrk_(- c->size - sizeof(struct chunk)); } } static void *calloc_(size_t nmemb, size_t size) { size_t length = nmemb * size; void *ptr = malloc_(length); if (ptr) { char *dst = ptr; for (size_t i = 0; i < length; *dst = 0, ++dst, ++i); } return ptr; } static void *realloc_(void *ptr, size_t size) { void *newptr = malloc_(size); if (newptr && ptr && ptr >= malloc_base() && ptr <= (void *)sbrk_(0)) { Chunk c = (Chunk) ptr - 1; if (c->data == ptr) { size_t length = c->size > size ? size : c->size; char *dst = newptr, *src = ptr; for (size_t i = 0; i < length; *dst = *src, ++src, ++dst, ++i); free_(ptr); } } return newptr; }
2.8125
3
2024-11-18T21:19:29.337599+00:00
2021-04-30T15:17:40
501cb8544bd8b0e67c3295033e63baf17412f5ec
{ "blob_id": "501cb8544bd8b0e67c3295033e63baf17412f5ec", "branch_name": "refs/heads/main", "committer_date": "2021-04-30T15:17:40", "content_id": "2198c4abf828fb2a0da86935ffeb27a676523d16", "detected_licenses": [ "MIT" ], "directory_id": "baa4f58fd26dbfdc9b7c6759a39f52ff5e2a1780", "extension": "c", "filename": "USRAT.c", "fork_events_count": 2, "gha_created_at": "2021-04-28T09:25:15", "gha_event_created_at": "2021-04-28T11:04:10", "gha_language": "Makefile", "gha_license_id": "MIT", "github_id": 362410312, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 750, "license": "MIT", "license_type": "permissive", "path": "/src/USRAT.c", "provenance": "stackv2-0128.json.gz:315288", "repo_name": "Prasadpokanati/Embedded-project", "revision_date": "2021-04-30T15:17:40", "revision_id": "e95fadc032d3ef1c53d493183a0724b2ef2df785", "snapshot_id": "e028f5013b146e201d20d16c9df3c46d441705f7", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Prasadpokanati/Embedded-project/e95fadc032d3ef1c53d493183a0724b2ef2df785/src/USRAT.c", "visit_date": "2023-04-13T23:55:04.604929" }
stackv2
#include <avr/io.h> #include "usart.h" /** * @brief A program to initialize the UART serial communication * * @param ubrr_value */ void UARTinit(uint16_t ubrr_value){ UBRR0L = ubrr_value; UBRR0H = (ubrr_value>>8)&(0x00ff); UART_CHARACTER_SIZE; // 8 bit size of data UART_ENABLED; //enable rx and tx of uart with interrupts } /** * @brief A function to read characters coming from other UART port * * @return char */ char UARTreadchar(){ while(UART_DATA_NOT_RECEIVED){ } return UDR0; } /** * @brief A function to write characters to send it to other UART port * * @param data */ void UARTwritecharacter(char data){ while(UART_DATA_NOT_WRITTEN){ } UDR0 = data; }
2.578125
3
2024-11-18T21:19:29.398755+00:00
2014-11-27T00:31:16
ed8460318d70088e32f585ccb845b790d1067f5a
{ "blob_id": "ed8460318d70088e32f585ccb845b790d1067f5a", "branch_name": "refs/heads/master", "committer_date": "2014-11-27T00:31:16", "content_id": "64d9262e63b46ec1a456e02cbd5abbdbbabda459", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "f8c61dec448da9a1b9365eeee089d72d591c5b7c", "extension": "c", "filename": "AnmapInit.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 27201930, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2774, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/src/AnmapInit.c", "provenance": "stackv2-0128.json.gz:315420", "repo_name": "CavendishAstrophysics/anmap", "revision_date": "2014-11-27T00:31:16", "revision_id": "efb611d7f80a3d14dc55e46cd01e8a622f6fd294", "snapshot_id": "c8a136f9ae32bb74b022ca14eac940b847286f6a", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/CavendishAstrophysics/anmap/efb611d7f80a3d14dc55e46cd01e8a622f6fd294/src/AnmapInit.c", "visit_date": "2021-01-25T09:00:21.380522" }
stackv2
/* * AnmapInit.c -- * * Routine to Initialise Anmap commands */ #include "tcl.h" #include "eqn.h" #include "string.h" /* * The following variable is a special hack that is needed in order for * Sun shared libraries to be used for Tcl. */ #ifdef NEED_MATHERR extern int matherr(); int *tclDummyMathPtr = (int *) matherr; #endif float *map_array; /* *---------------------------------------------------------------------- * * main -- * * This is the main program for the application. * * Results: * None: Tcl_Main never returns here, so this procedure never * returns either. * * Side effects: * Whatever the application does. * *---------------------------------------------------------------------- */ int main(argc, argv) int argc; /* Number of command-line arguments. */ char **argv; /* Values of command-line arguments. */ { Tcl_Main(argc, argv, Tcl_AppInit); return 0; /* Needed only to prevent compiler warning. */ } /* *---------------------------------------------------------------------- * * Tcl_AppInit -- * * This procedure performs application-specific initialization. * Most applications, especially those that incorporate additional * packages, will have their own version of this procedure. * * Results: * Returns a standard Tcl completion code, and leaves an error * message in interp->result if an error occurs. * * Side effects: * Depends on the startup script. * *---------------------------------------------------------------------- */ extern int anmap_Init _ANSI_ARGS_(( Tcl_Interp *interp )) ; extern int iocmd_Init _ANSI_ARGS_(( Tcl_Interp *interp )) ; int Tcl_AppInit(interp) Tcl_Interp *interp; /* Interpreter for application. */ { static eqn_funs *fun_list; static char anmap_initCmd[] = "set Xanmap 0 ; source /mrao/anmap_v7.5/etc/anmap.tcl"; /* * Setup Tcl Interpreter */ if (Tcl_Init(interp) == TCL_ERROR) { return TCL_ERROR; } /* * Setup Anmap commands */ if (anmap_Init( interp ) == TCL_ERROR) { return TCL_ERROR; } /* * Setup IO commands */ if (iocmd_Init( interp ) == TCL_ERROR) { return TCL_ERROR; } /* * Setup Catalogue commands */ if (imcat_Init( interp ) == TCL_ERROR) { return TCL_ERROR; } /* * Setup Graphic commands */ if (graphic_Init( interp ) == TCL_ERROR) { return TCL_ERROR; } /* * Setup function handling */ fun_list = add_standard_functions(NULL); set_input_functions(fun_list); /* * Perform anmap specific initialisation */ if (Tcl_Eval(interp, anmap_initCmd) == TCL_ERROR) { return TCL_ERROR; } tcl_RcFileName = "~/.tclrc"; return TCL_OK; }
2.28125
2
2024-11-18T21:19:29.712171+00:00
2022-11-03T02:16:22
4ac5068f68ccf846ba9d5f0733ccacf639259a2b
{ "blob_id": "4ac5068f68ccf846ba9d5f0733ccacf639259a2b", "branch_name": "refs/heads/master", "committer_date": "2022-11-03T02:16:22", "content_id": "6987aff4b55db78f6b8cc9b54c55c99e01c3f399", "detected_licenses": [ "BSD-2-Clause", "BSD-3-Clause" ], "directory_id": "7c950c165325a9c22f532b82c14d76d1dfc41a25", "extension": "c", "filename": "MemCpy.c", "fork_events_count": 0, "gha_created_at": "2019-07-26T06:19:55", "gha_event_created_at": "2022-11-03T02:16:23", "gha_language": "C++", "gha_license_id": "BSD-3-Clause", "github_id": 198958364, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3205, "license": "BSD-2-Clause,BSD-3-Clause", "license_type": "permissive", "path": "/Src/Efi/Lib/BaseLibrary/MemCpy.c", "provenance": "stackv2-0128.json.gz:315553", "repo_name": "fengjixuchui/SELoader", "revision_date": "2022-11-03T02:16:22", "revision_id": "5ed492e4caef0fe43465eda4af1d451990671cb2", "snapshot_id": "3cddde8b8dfc541f4d32cc5b2233bc8252bcfd42", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/fengjixuchui/SELoader/5ed492e4caef0fe43465eda4af1d451990671cb2/Src/Efi/Lib/BaseLibrary/MemCpy.c", "visit_date": "2022-11-10T03:18:51.811638" }
stackv2
/* * Copyright (c) 2017, Wind River Systems, Inc. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1) Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2) Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3) Neither the name of Wind River Systems nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Author: * Jia Zhang <zhang.jia@linux.alibaba.com> */ #include <Efi.h> #include "BaseLibrary.h" VOID * MemCpy(VOID *Destination, CONST VOID *Source, UINTN MaxLength) { UINTN UnalignedLen; #ifdef __x86_64__ register CHAR8 *d asm("rdi") = (CHAR8 *)Destination; register CHAR8 *s asm("rsi") = (CHAR8 *)Source; #else register CHAR8 *d asm("edi") = (CHAR8 *)Destination; register CHAR8 *s asm("esi") = (CHAR8 *)Source; #endif if (Destination == Source || !MaxLength) return Destination; asm volatile("cld"); /* To ensure there is at least one dword/qword before running the * faster dword/qword copy, choose THRESHOLD_SHORT_COPY dwords/qwords * as the threshold. */ if (MaxLength <= THRESHOLD_SHORT_COPY) { asm volatile(".align 2\n\t" "rep movsb\n\t" :: "c"(MaxLength), "S"(s), "D"(d) :"memory"); return Destination; } /* Handle unaligned case */ UnalignedLen = UNALIGNED(s); if (UnalignedLen && (UnalignedLen == UNALIGNED(d))) { UnalignedLen = sizeof(long) - UnalignedLen; MaxLength -= UnalignedLen; asm volatile(".align 2\n\t" "rep movsb\n\t" :: "c"(UnalignedLen), "S"(s), "D"(d) : "memory"); } /* Handle dword/qword copy */ #ifdef __x86_64__ asm volatile(".align 4\n\t" "rep movsq\n\t" #else asm volatile(".align 2\n\t" "rep movsl\n\t" #endif :: "c"((unsigned long)MaxLength / sizeof(long)), "S"(s), "D"(d) : "memory"); /* Handle the remaining bytes */ MaxLength &= sizeof(long) - 1; asm volatile(".align 2\n\t" "rep movsb\n\t" :: "c"(MaxLength), "S"(s), "D"(d) : "memory"); return Destination; }
2.078125
2
2024-11-18T21:19:29.790535+00:00
2021-01-24T21:44:43
5e74bee7682416dc30ec3d87f53ae743aea9babf
{ "blob_id": "5e74bee7682416dc30ec3d87f53ae743aea9babf", "branch_name": "refs/heads/master", "committer_date": "2021-01-24T21:44:43", "content_id": "7738c098663b2239611949a458e32f5c4544e708", "detected_licenses": [ "MIT" ], "directory_id": "fe58d0a75a93ecd06a9d098d44a4f6d6e01e922d", "extension": "c", "filename": "type.c", "fork_events_count": 0, "gha_created_at": "2020-10-07T00:55:32", "gha_event_created_at": "2021-01-24T21:44:45", "gha_language": "C", "gha_license_id": "NOASSERTION", "github_id": 301891705, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2675, "license": "MIT", "license_type": "permissive", "path": "/type.c", "provenance": "stackv2-0128.json.gz:315681", "repo_name": "quells/charmcc", "revision_date": "2021-01-24T21:44:43", "revision_id": "851e48654ebc0fc7e6f676ad5f0ed7dab34b69e6", "snapshot_id": "7115496f387ccae95e310aeac1af54d1b1010f8f", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/quells/charmcc/851e48654ebc0fc7e6f676ad5f0ed7dab34b69e6/type.c", "visit_date": "2023-06-03T02:21:34.460284" }
stackv2
#include "charmcc.h" Type *ty_int = &(Type){TY_INT, 4}; // signed 32-bit integer bool is_integer(Type *type) { return type->kind == TY_INT; } Type *copy_type(Type *type, MemManager *mm) { Type *copy = allocate(mm, sizeof(Type)); #if DEBUG_ALLOCS fprintf(stderr, "alloc copy of type %p\n", type); #endif *copy = *type; return copy; } Type *pointer_to(Type *base, MemManager *mm) { Type *type = allocate(mm, sizeof(Type)); #if DEBUG_ALLOCS fprintf(stderr, "alloc ptrty %p\n", type); #endif type->kind = TY_PTR; type->size = PTR_SIZE; type->base = base; return type; } Type *func_type(Type *return_type, MemManager *mm) { Type *type = allocate(mm, sizeof(Type)); #if DEBUG_ALLOCS fprintf(stderr, "alloc fn ty %p\n", type); #endif type->kind = TY_FUNC; type->return_type = return_type; return type; } Type *array_of(Type *base, int len, MemManager *mm) { Type *type = allocate(mm, sizeof(Type)); #if DEBUG_ALLOCS fprintf(stderr, "alloc array %p of %p\n", type, base); #endif type->kind = TY_ARRAY; type->size = base->size * len; type->base = base; type->array_len = len; return type; } void add_type(Node *node, MemManager *mm) { if (!node || node->type) { return; } add_type(node->lhs, mm); add_type(node->rhs, mm); add_type(node->condition, mm); add_type(node->consequence, mm); add_type(node->alternative, mm); add_type(node->initialize, mm); add_type(node->increment, mm); for (Node *n = node->body; n; n = n->next) { add_type(n, mm); } switch (node->kind) { case ND_ADD: case ND_SUB: case ND_MUL: case ND_DIV: case ND_NEG: node->type = node->lhs->type; return; case ND_ASSIGN: if (node->lhs->type->kind == TY_ARRAY) { error_tok(node->lhs->repr, "not an lvalue"); } node->type = node->lhs->type; return; case ND_EQ: case ND_NEQ: case ND_LT: case ND_LTE: case ND_NUM: case ND_FN_CALL: node->type = ty_int; return; case ND_VAR: node->type = node->var->type; return; case ND_ADDR: if (node->lhs->type->kind == TY_ARRAY) { node->type = pointer_to(node->lhs->type->base, mm); } else { node->type = pointer_to(node->lhs->type, mm); } return; case ND_DEREF: if (!node->lhs->type->base) { error_tok(node->repr, "invalid pointer dereference"); } node->type = node->lhs->type->base; return; default: break; } }
2.65625
3
2024-11-18T21:19:29.848382+00:00
2022-01-24T18:56:57
dddc7ec4aada7424a906fd8aec1cfba60afffff7
{ "blob_id": "dddc7ec4aada7424a906fd8aec1cfba60afffff7", "branch_name": "refs/heads/master", "committer_date": "2022-01-24T18:56:57", "content_id": "d6865d5399b1072963a6cc771983badc52d829bf", "detected_licenses": [ "MIT" ], "directory_id": "1018ad71e705af640d4dc8399da16aeefb4c2689", "extension": "c", "filename": "msd.c", "fork_events_count": 10, "gha_created_at": "2011-03-01T13:04:07", "gha_event_created_at": "2020-02-13T07:57:53", "gha_language": "C++", "gha_license_id": "MIT", "github_id": 1425990, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5203, "license": "MIT", "license_type": "permissive", "path": "/external/msd.c", "provenance": "stackv2-0128.json.gz:315812", "repo_name": "rantala/string-sorting", "revision_date": "2022-01-24T18:56:57", "revision_id": "56c7d3ff1abcfe253d714992c841ce17e311d567", "snapshot_id": "4b426663bb8839167816c14f347686d456fee1e6", "src_encoding": "UTF-8", "star_events_count": 41, "url": "https://raw.githubusercontent.com/rantala/string-sorting/56c7d3ff1abcfe253d714992c841ce17e311d567/external/msd.c", "visit_date": "2022-02-02T15:18:06.622672" }
stackv2
/* MSD radix sort with a fixed sized alphabet. S. Nilsson. Radix Sorting and Searching. PhD thesis, Department of Computer Science, Lund University, 1990. The code presented in this file has been tested with care but is not guaranteed for any purpose. The writer does not offer any warranties nor does he accept any liabilities with respect to the code. Stefan Nilsson, 8 jan 1997. Laboratory of Information Processing Science Helsinki University of Technology Stefan.Nilsson@hut.fi */ #include "routine.h" #include "nilsson.h" #include <stdlib.h> #define CHAR(s, p) s[p] typedef struct bucketrec { list head, tail; int size; /* size of list, 0 if already sorted */ } bucket; typedef struct stackrec { list head, tail; int size; /* size of list, 0 if already sorted */ int pos; /* current position in string */ } stack; static memory stackmem[1]; static stack *stackp; static void push(list head, list tail, int size, int pos) { stackp = (stack *) allocmem(stackmem, sizeof(struct stackrec)); stackp->head = head; stackp->tail = tail; stackp->size = size; stackp->pos = pos; } static stack *pop() { stack *temp; temp = stackp; stackp = (stack *) deallocmem(stackmem, sizeof(struct stackrec)); return temp; } static stack *top() { return stackp; } static boolean stackempty() { return !stackp; } /* Put a list of elements into a bucket. The minimum and maximum character seen so far (chmin, chmax) are updated when the bucket is updated for the first time. */ static void intobucket(bucket *b, list h, list t, int size, character ch, character *chmin, character *chmax) { if (!b->head) { b->head = h; b->tail = t; b->size = size; if (ch != '\0') { if (ch < *chmin) *chmin = ch; if (ch > *chmax) *chmax = ch; } } else { b->tail->next = h; b->tail = t; b->size += size; } } /* Put the list in a bucket onto the stack. If the list is small (contains at most INSERTBREAK elements) sort it using insertion sort. If both the the list on top of the stack and the list to be added to the stack are already sorted the new list is appended to the end of the list on the stack and no new stack record is created. */ static void ontostack(bucket *b, int pos) { b->tail->next = NULL; if (b->size <= INSERTBREAK) { if (b->size > 1) b->head = ListInsertsort(b->head, &b->tail, pos); b->size = 0; /* sorted */ } if (!b->size && !stackempty() && !top()->size) { top()->tail->next = b->head; top()->tail = b->tail; } else { push(b->head, b->tail, b->size, pos); b->size = 0; } b->head = NULL; } /* Traverse a list and put the elements into buckets according to the character in position pos. The elements are moved in blocks consisting of strings that have a common character in position pos. We keep track of the minimum and maximum nonzero characters encountered. In this way we may avoid looking at some empty buckets when we traverse the buckets in ascending order and push the lists onto the stack */ static void bucketing(list a, int pos) { static bucket b[CHARS]; bucket *bp; character ch, prevch; character chmin = CHARS-1, chmax = 0; list t = a, tn; int size = 1; prevch = CHAR(t->str, pos); for ( ; (tn = t->next); t = tn) { ch = CHAR(tn->str, pos); size++; if (ch == prevch) continue; intobucket(b+prevch, a, t, size-1, prevch, &chmin, &chmax); a = tn; prevch = ch; size = 1; } intobucket(b+prevch, a, t, size, prevch, &chmin, &chmax); if (b->head) { /* ch = '\0', end of string */ b->size = 0; /* already sorted */ ontostack(b, pos); } for (bp = b + chmin; bp <= b + chmax; bp++) if (bp->head) ontostack(bp, pos+1); } list MSD1(list a, int n) { list res = NULL; stack *s; if (n < 2) return a; initmem(stackmem, sizeof(struct stackrec), n/50); push(a, NULL, n, 0); while (!stackempty()) { s = pop(); if (!s->size) { /* sorted */ s->tail->next = res; res = s->head; continue; } bucketing(s->head, s->pos); } freemem(stackmem); return res; } void MSDsort(string strings[], size_t scnt) { list ptr, listnodes; size_t i; /* allocate memory based on the number of strings in the array */ ptr = listnodes = (list ) calloc(scnt, sizeof(struct listrec)); /* point the linked list nodes to the strings in the array */ for( i=0; i<scnt; i++) { listnodes[i].str = strings[i]; if (i<(scnt-1)) listnodes[i].next = &listnodes[i+1]; else listnodes[i].next = NULL; } /* sort */ listnodes = MSD1(listnodes, scnt); /* write the strings back into the array */ for (i = 0; i < scnt ; i++, listnodes=listnodes->next) strings[i] = listnodes->str; free(ptr); } void msd_nilsson(unsigned char **strings, size_t n) { return MSDsort(strings, n); } ROUTINE_REGISTER_SINGLECORE(msd_nilsson, "MSD Radix Sort by Stefan Nilsson")
3.21875
3
2024-11-18T21:19:30.077227+00:00
2018-04-22T21:17:27
f658d83d7f52de69a275981c067c30efe96219a8
{ "blob_id": "f658d83d7f52de69a275981c067c30efe96219a8", "branch_name": "refs/heads/master", "committer_date": "2018-04-22T21:17:27", "content_id": "df12df24d33561d203e5f1f7ad9052ab4ef54ce7", "detected_licenses": [ "MIT" ], "directory_id": "43aaeb33ce2be870c0638426ec45f12574df710f", "extension": "c", "filename": "linkedlist.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": 1179, "license": "MIT", "license_type": "permissive", "path": "/CNG213-DataStructures/2-Car-Wash-System-Simulator/Project_Lib/linkedlist.c", "provenance": "stackv2-0128.json.gz:316071", "repo_name": "metinkanca/Lectures", "revision_date": "2018-04-22T21:17:27", "revision_id": "a4dd6615691ce8d9d2bfec6910f6af108b741d7f", "snapshot_id": "50f1577d5b3806452c0d1ed63e6058d059ba948d", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/metinkanca/Lectures/a4dd6615691ce8d9d2bfec6910f6af108b741d7f/CNG213-DataStructures/2-Car-Wash-System-Simulator/Project_Lib/linkedlist.c", "visit_date": "2020-09-26T02:45:44.982033" }
stackv2
#include "linkedlist.h" MachineList* create_machineList() { // "ml" means machine list MachineList* machineL = (MachineList*) sMalloc(sizeof(MachineList)); machineL->size = 0; // Head is dummy node machineL->machineH = (Machine*) sMalloc(sizeof(Machine)); machineL->machineH->next = NULL; machineL->machineT = machineL->machineH; return machineL; } Machine* create_machine() { Machine* new_machine = (Machine*) sMalloc(sizeof(Machine)); new_machine->next = NULL; return new_machine; } void append_machine(MachineList* machineL) { machineL->machineT->next = create_machine(); machineL->machineT = machineL->machineT->next; machineL->machineT->id = machineL->size; machineL->machineT->carsFinished = create_carQueue(); machineL->machineT->carsInProcess = create_carQueue(); machineL->size++; } int is_idle(Machine* machine) { return !(machine->carsInProcess->size); } Car* car_in_process(Machine* machine) { if( is_idle(machine) ) return NULL; return machine->carsInProcess->front->next; } Machine* get_first_machine(MachineList* machineL) { return machineL->machineH->next; }
2.765625
3
2024-11-18T21:19:30.203206+00:00
2023-01-21T20:02:17
54ebd379940e3e72e9487fa3f8a8d2dce4b6ebee
{ "blob_id": "54ebd379940e3e72e9487fa3f8a8d2dce4b6ebee", "branch_name": "refs/heads/master", "committer_date": "2023-01-21T21:08:40", "content_id": "2cc0a712b9faf6c2f5d818ac3989ca88b63b1b8c", "detected_licenses": [ "BSD-2-Clause", "BSD-2-Clause-Views", "MIT" ], "directory_id": "7174f78433c2fb69457837e8f32ace37f357c7e3", "extension": "c", "filename": "binary2c.c", "fork_events_count": 12, "gha_created_at": "2018-09-14T21:21:28", "gha_event_created_at": "2023-01-21T20:38:37", "gha_language": "C", "gha_license_id": "BSD-2-Clause", "github_id": 148843047, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2464, "license": "BSD-2-Clause,BSD-2-Clause-Views,MIT", "license_type": "permissive", "path": "/tools/binary2c.c", "provenance": "stackv2-0128.json.gz:316204", "repo_name": "vvaltchev/tfblib", "revision_date": "2023-01-21T20:02:17", "revision_id": "99c8195761d6591254b8b847c3fd6adcf649e636", "snapshot_id": "3b62f622788bb5726a647bece91d4ddc91702ead", "src_encoding": "UTF-8", "star_events_count": 79, "url": "https://raw.githubusercontent.com/vvaltchev/tfblib/99c8195761d6591254b8b847c3fd6adcf649e636/tools/binary2c.c", "visit_date": "2023-02-02T09:51:13.102210" }
stackv2
/* SPDX-License-Identifier: BSD-2-Clause */ #include <stdio.h> #include <string.h> #include <stdbool.h> #include <stdlib.h> #include <ctype.h> #include <errno.h> #include <libgen.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> void show_help_and_exit(const char *appname) { printf("Usage:\n"); printf(" %s <BINARY FILE> <C OUTPUT FILE> <VARIABLE NAME>\n", appname); printf("\n"); exit(1); } bool check_var_name(const char *name) { const char *p = name; while (*p) { if (p == name) { if (!isalpha(*p) && *p != '_') return false; } else { if (!isalnum(*p) && *p != '_') return false; } p++; } return true; } void bin2c(FILE *src, FILE *dst, const char *fn, const char *var_name) { static unsigned char readbuf[4096]; size_t s; unsigned fs; unsigned bc = 0; int rc; struct stat statbuf; rc = fstat(fileno(src), &statbuf); if (rc != 0) { perror("fstat of the binary file failed"); return; } fs = statbuf.st_size; fprintf(dst, "const struct {\n\n"); fprintf(dst, " const char *filename;\n"); fprintf(dst, " unsigned int data_size;\n"); fprintf(dst, " unsigned char data[];\n\n"); fprintf(dst, "} %s = {\n\n", var_name); fprintf(dst, " \"%s\", /* file name */\n", fn); fprintf(dst, " %u, /* file size */\n\n", fs); fprintf(dst, " {"); do { s = fread(readbuf, 1, sizeof(readbuf), src); for (size_t i = 0; i < s; i++) { if (!(bc % 8)) fprintf(dst, "\n /* 0x%08x */ ", bc); bc++; fprintf(dst, "0x%02x%s", readbuf[i], bc < fs ? ", " : ""); } } while (s); fprintf(dst, "\n }\n"); fprintf(dst, "};\n\n"); } int main(int argc, char **argv) { FILE *src = NULL; FILE *dst = NULL; const char *var_name; if (argc != 4) show_help_and_exit(argv[0]); src = fopen(argv[1], "rb"); if (!src) { perror(argv[1]); return 1; } dst = fopen(argv[2], "wb"); if (!dst) { perror(argv[2]); return 1; } var_name = argv[3]; if (!check_var_name(var_name)) { fprintf(stderr, "Invalid C variable name '%s'\n", var_name); goto out; } fprintf(dst, "/* file: %s */\n", argv[1]); bin2c(src, dst, basename(argv[1]), var_name); out: if (src) fclose(src); if (dst) fclose(dst); return 0; }
2.875
3
2024-11-18T21:19:30.421260+00:00
2020-12-28T06:13:38
c2b63a562996da15c289affb850320b0a11f9295
{ "blob_id": "c2b63a562996da15c289affb850320b0a11f9295", "branch_name": "refs/heads/main", "committer_date": "2020-12-28T06:13:38", "content_id": "bac44c3cd7e61032b5b8c2a8ab5ff3972d977bbd", "detected_licenses": [ "MIT" ], "directory_id": "f75de83adc238bb0df98ce138a1c207add843dff", "extension": "c", "filename": "sendMsg.c", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 322867134, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 802, "license": "MIT", "license_type": "permissive", "path": "/send_message/sendMsg.c", "provenance": "stackv2-0128.json.gz:316463", "repo_name": "canpinaremre/STM32F4_UART", "revision_date": "2020-12-28T06:13:38", "revision_id": "f8e683c65c79fcfe6c8573bc1a3f19254e69b74a", "snapshot_id": "130367df1d4225369e8c0c4a76b189369cf1ee22", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/canpinaremre/STM32F4_UART/f8e683c65c79fcfe6c8573bc1a3f19254e69b74a/send_message/sendMsg.c", "visit_date": "2023-02-06T18:05:48.247728" }
stackv2
/* * @Author: canpinaremre * Purpose: To send messages via UART * Language: C */ #include <module/send_message/sendMsg.h> void sendInt(uint32_t myInt,UART_HandleTypeDef* huart,uint8_t newLine){ char sendBuffer[30]=""; sprintf(sendBuffer, "%lu", myInt); sendString(sendBuffer,huart,newLine); } void sendFloat(float myFloat,UART_HandleTypeDef* huart,uint8_t newLine){ char sendBuffer[30]=""; sprintf(sendBuffer, "%.2f", myFloat); sendString(sendBuffer,huart,newLine); } void sendString(char* myString,UART_HandleTypeDef* huart,uint8_t newLine){ char sendBuffer[60]=""; strncat(sendBuffer, myString, strlen(myString)); if(newLine) strncat(sendBuffer, "\r\n", strlen("\r\n")); HAL_UART_Transmit(huart, (uint8_t *)sendBuffer, strlen(sendBuffer), 10); }
2.5625
3
2024-11-18T21:19:30.690603+00:00
2020-09-06T20:03:41
9e118955586a6f633584eb2dae005881f547a1fa
{ "blob_id": "9e118955586a6f633584eb2dae005881f547a1fa", "branch_name": "refs/heads/master", "committer_date": "2020-09-06T20:05:23", "content_id": "81f77a4088ac2be176081ce6a09193d2967226d1", "detected_licenses": [ "BSD-3-Clause", "MIT", "Apache-2.0", "Zlib" ], "directory_id": "79c9646ab91435024955c0f6b2b9eacb69e9a4b4", "extension": "h", "filename": "utils.h", "fork_events_count": 4, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 291830737, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2583, "license": "BSD-3-Clause,MIT,Apache-2.0,Zlib", "license_type": "permissive", "path": "/include/dht/utils.h", "provenance": "stackv2-0128.json.gz:316723", "repo_name": "naturalpolice/libdht", "revision_date": "2020-09-06T20:03:41", "revision_id": "5e45c9bf32e21b118793d87717b7566486072a37", "snapshot_id": "670b98b76b420c43fae6f38bb9c2af0960ac59b5", "src_encoding": "UTF-8", "star_events_count": 15, "url": "https://raw.githubusercontent.com/naturalpolice/libdht/5e45c9bf32e21b118793d87717b7566486072a37/include/dht/utils.h", "visit_date": "2022-12-28T18:07:15.577415" }
stackv2
/* * Copyright (c) 2020 naturalpolice * SPDX-License-Identifier: MIT * * Licensed under the MIT License (see LICENSE). */ /*! * \file utils.h * \brief DHT utilities. */ #ifndef DHT_UTILS_H_ #define DHT_UTILS_H_ #ifdef __cplusplus extern "C" { #endif #ifdef _WIN32 typedef int socklen_t; #include <winsock2.h> #include <ws2ipdef.h> #else #include <sys/socket.h> #include <arpa/inet.h> #endif /*! * Return the hexadecimal representation of a 160-bit value. * * Formats the given binary info-hash into an hexadecimal string. The * string is returned in a statically allocated buffer, which subsequent * calls will overwrite and is therefore not reentrant. * * \param id The 160-bit value to convert. * \returns Hexadecimal string. */ const char *hex(const unsigned char id[20]); /*! * Convert a hexadecimal representation string to a 160-bit value. * * Scans the hexadecimal string \a s and converts it to a binary info-hash. * * \param s The hexadecimal string. * \param id The buffer into which the info-hash will be returned. * \returns 0 on success, -1 if the string is invalid. */ int from_hex(const char *s, unsigned char id[20]); /*! * Format socket address. * * Returns the socket address as a human-readable string. This function * supports \a AF_INET and \a AF_INET6 socket address families. The string * is returned in a statically allocated buffer, which subsequent calls will * overwrite, and is therefore not reentrant. * * \param sa The socket address * \param addrlen Length of the socket address structure * \returns The address string. */ const char *sockaddr_fmt(const struct sockaddr *sa, socklen_t addrlen); /*! * Compare two socket addresses. * * \param s1 First socket address. * \param s2 Second socket address. * \returns -1 if s1 < s2, 0 if s1 == s2, 1 if s1 > s2. */ int sockaddr_cmp(const struct sockaddr *s1, const struct sockaddr *s2); /*! * Format compact address information. * * Returns the given compact address address information as a human-readable * string. A compact address is a 4-byte IPv4 address in network byte order * followed by a 2-byte port number in network byte order, or a 16-byte IPv6 * address in network byte order followed by a 2-byte port number in network * byte order. * * \param ip The compact address string buffer * \param len Length of the compact address string. * \returns The address string of NULL if the compact address is invalid. */ const char *compactaddr_fmt(const unsigned char *ip, size_t len); #ifdef __cplusplus } #endif #endif /* DHT_UTILS_H_ */
2.40625
2
2024-11-18T21:19:31.161219+00:00
2022-11-15T19:14:47
634b40273aa3f1fb9363b4751690ffcc3f254d0e
{ "blob_id": "634b40273aa3f1fb9363b4751690ffcc3f254d0e", "branch_name": "refs/heads/master", "committer_date": "2022-11-15T19:14:47", "content_id": "3a137c49351e6da8978eefa4dbaad20d98901564", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "8c21c36b11504e110084273e7ec438a10073811c", "extension": "c", "filename": "summary.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 50181075, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 312, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/summary.c", "provenance": "stackv2-0128.json.gz:316980", "repo_name": "n-t-roff/rlcmp", "revision_date": "2022-11-15T19:14:47", "revision_id": "85391c2fd8bbe085152c1ce41d340ffde506a1ba", "snapshot_id": "824e050f4c2875da521907a51177fa03ca4b6f19", "src_encoding": "UTF-8", "star_events_count": 5, "url": "https://raw.githubusercontent.com/n-t-roff/rlcmp/85391c2fd8bbe085152c1ce41d340ffde506a1ba/summary.c", "visit_date": "2022-11-23T16:45:18.393419" }
stackv2
#include <stdint.h> #include <stdio.h> #include "summary.h" long total_file_count; off_t total_byte_count; short summary; void output_summary(void) { printf("%'ld files ", total_file_count); if (total_byte_count) printf("(%'jd bytes) ", (intmax_t)total_byte_count); printf("compared\n"); }
2.21875
2
2024-11-18T21:19:31.636040+00:00
2021-11-16T22:38:30
9f6d3c376109e4c368e8da56583031b2d056325c
{ "blob_id": "9f6d3c376109e4c368e8da56583031b2d056325c", "branch_name": "refs/heads/main", "committer_date": "2021-11-16T22:38:30", "content_id": "d43b140ee3ec5eb35e2b2b1e0de19062073c5b79", "detected_licenses": [ "MIT" ], "directory_id": "65c20b8a7d6d8e5c5c4668f8d65dcfcf201b2c31", "extension": "c", "filename": "command_table.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 428461459, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2323, "license": "MIT", "license_type": "permissive", "path": "/maman14/command_table.c", "provenance": "stackv2-0128.json.gz:317111", "repo_name": "itayperetz0/Assembler-Project", "revision_date": "2021-11-16T22:38:30", "revision_id": "d8a875951cbbef343c9a289ac6bf7d5ac12240dd", "snapshot_id": "f2334438d24c1a633ac340c7ed673421f439e244", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/itayperetz0/Assembler-Project/d8a875951cbbef343c9a289ac6bf7d5ac12240dd/maman14/command_table.c", "visit_date": "2023-09-04T15:11:34.313517" }
stackv2
/* * command_table.c * This file contains the information of all the commands in a table */ #include <string.h> #include "flags.h" #include "structs.h" #include "global_varaibles.h" /*This function sets all the commands in a command table */ void set_command_table (){ int i=0,j; strcpy(command_table[i++].name,"add"); strcpy(command_table[i++].name,"sub"); strcpy(command_table[i++].name,"and"); strcpy(command_table[i++].name,"or"); strcpy(command_table[i++].name,"nor"); strcpy(command_table[i++].name,"move"); strcpy(command_table[i++].name,"mvhi"); strcpy(command_table[i++].name,"mvlo"); strcpy(command_table[i++].name,"addi"); strcpy(command_table[i++].name,"subi"); strcpy(command_table[i++].name,"andi"); strcpy(command_table[i++].name,"ori"); strcpy(command_table[i++].name,"nori"); strcpy(command_table[i++].name,"bne"); strcpy(command_table[i++].name,"beq"); strcpy(command_table[i++].name,"blt"); strcpy(command_table[i++].name,"bgt"); strcpy(command_table[i++].name,"lb"); strcpy(command_table[i++].name,"sb"); strcpy(command_table[i++].name,"lw"); strcpy(command_table[i++].name,"sw"); strcpy(command_table[i++].name,"lh"); strcpy(command_table[i++].name,"sh"); strcpy(command_table[i++].name,"jmp"); strcpy(command_table[i++].name,"la"); strcpy(command_table[i++].name,"call"); strcpy(command_table[i++].name,"stop"); for(i=0 ,j=1;i<comm_tab_len ;i++){ if(i<move_place){/* R arithmetics commands*/ command_table[i].type = 'R'; command_table[i].opcode = 0; command_table[i].func = j++; if(i==4)/*last place of op_code = 0 so func code strat from 1 again*/ j=1; } else if(i<addi_place){/*R copy commands*/ command_table[i].type = 'R'; command_table[i].opcode = 1; command_table[i].func = j++; if(i==7)/*last place of R command so op code start from 10*/ j=10; } else if(i<jmp_place){ /* I commands*/ command_table[i].type = 'I'; command_table[i].opcode = j++; if(i==22)/*last place of I command so op code start from 30*/ j=30; } else{ if(i<stop_place){/* J commands*/ command_table[i].type = 'j'; command_table[i].opcode = j++; } else{/*stop command*/ command_table[i].type = 'j'; command_table[i].opcode = command_op_code; } } } }
2.640625
3
2024-11-18T21:19:31.705933+00:00
2022-08-29T12:49:17
1b95f920a3c82a04965a5f91ad9d01b017e29f21
{ "blob_id": "1b95f920a3c82a04965a5f91ad9d01b017e29f21", "branch_name": "refs/heads/master", "committer_date": "2022-08-29T12:49:17", "content_id": "a22e554f0ae05325b4625630569e9ab5daab390b", "detected_licenses": [ "MIT" ], "directory_id": "1287acc0ebb00d290804940f22210992606417cb", "extension": "h", "filename": "ACCTypes.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 530196024, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 12578, "license": "MIT", "license_type": "permissive", "path": "/1. Custom code applied in the wireless communication module/Bluetopia/profiles_ti/ACC/include/ACCTypes.h", "provenance": "stackv2-0128.json.gz:317243", "repo_name": "HyogeunShin/Wireless-System_NatComm22", "revision_date": "2022-08-29T12:49:17", "revision_id": "7bacdf47f319c11172da57a6d7f2570f192f8514", "snapshot_id": "9432badd92ae6e26e95d452404ba79032ad4c1d5", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/HyogeunShin/Wireless-System_NatComm22/7bacdf47f319c11172da57a6d7f2570f192f8514/1. Custom code applied in the wireless communication module/Bluetopia/profiles_ti/ACC/include/ACCTypes.h", "visit_date": "2023-04-13T16:51:39.825104" }
stackv2
/*****< acctypes.h >***********************************************************/ /* Copyright 2005 - 2014 Stonestreet One. */ /* All Rights Reserved. */ /* */ /* ACCTypes - Stonestreet One Bluetooth Stack Accelerometer (TI Proprietary) */ /* Service Types. */ /* */ /* Author: Tim Cook */ /* */ /*** MODIFICATION HISTORY *****************************************************/ /* */ /* mm/dd/yy F. Lastname Description of Modification */ /* -------- ----------- ------------------------------------------------*/ /* 08/03/11 T. Cook Initial creation. */ /******************************************************************************/ #ifndef __ACCTYPESH__ #define __ACCTYPESH__ #include "SS1BTGAT.h" /* Bluetooth Stack GATT API Prototypes/Constants. */ /* The following MACRO is a utility MACRO that assigns the TI */ /* Accelerometer Service 16 bit UUID to the specified UUID_16_t */ /* variable. This MACRO accepts one parameter which is the UUID_16_t*/ /* variable that is to receive the TI Accelerometer UUID Constant */ /* value. */ /* * NOTE * The UUID will be assigned into the UUID_16_t variable in */ /* Little-Endian format. */ #define TI_ACC_ASSIGN_ACC_SERVICE_UUID_16(_x) ASSIGN_BLUETOOTH_UUID_16((_x), 0xFF, 0xA0) /* The following MACRO is a utility MACRO that exist to compare a */ /* UUID 16 to the defined TI Accelerometer Service UUID in UUID16 */ /* form. This MACRO only returns whether the UUID_16_t variable is */ /* equal to the TI Accelerometer Service UUID (MACRO returns boolean */ /* result) NOT less than/greater than. The first parameter is the */ /* UUID_16_t variable to compare to the TI Accelerometer Service */ /* UUID. */ #define TI_ACC_COMPARE_ACC_SERVICE_UUID_TO_UUID_16(_x) COMPARE_BLUETOOTH_UUID_16_TO_CONSTANT((_x), 0xFF, 0xA0) /* The following defines the TI Accelerometer Service UUID that is */ /* used when building the TI Accelerometer Service Table. */ #define TI_ACC_SERVICE_BLUETOOTH_UUID_CONSTANT { 0xA0, 0xFF } /* The following MACRO is a utility MACRO that assigns the TI */ /* Accelerometer Service Enable Characteristic 16 bit UUID to the */ /* specified UUID_16_t variable. This MACRO accepts one parameter */ /* which is the UUID_16_t variable that is to receive the KFS Enable */ /* UUID Constant value. */ /* * NOTE * The UUID will be assigned into the UUID_16_t variable in */ /* Little-Endian format. */ #define TI_ACC_ASSIGN_ENABLE_UUID_16(_x) ASSIGN_BLUETOOTH_UUID_16((_x), 0xFF, 0xA1) /* The following MACRO is a utility MACRO that exist to compare a */ /* UUID 16 to the defined TI Accelerometer Service Enable */ /* Characteristic UUID in UUID16 form. This MACRO only returns */ /* whether the UUID_16_t variable is equal to the TI Accelerometer */ /* Service Enable Characteristic UUID (MACRO returns boolean result) */ /* NOT less than/greater than. The first parameter is the UUID_16_t */ /* variable to compare to the TI Accelerometer Service Enable */ /* Characteristic UUID. */ #define TI_ACC_COMPARE_ACC_ENABLE_UUID_TO_UUID_16(_x) COMPARE_BLUETOOTH_UUID_16_TO_CONSTANT((_x), 0xFF, 0xA1) /* The following defines the TI Accelerometer Service Enable */ /* Characteristic UUID that is used when building the TI */ /* Accelerometer Service Table. */ #define TI_ACC_ENABLE_CHARACTERISTIC_BLUETOOTH_UUID_CONSTANT { 0xA1, 0xFF } /* The following MACRO is a utility MACRO that assigns the TI */ /* Accelerometer Service Range Characteristic 16 bit UUID to the */ /* specified UUID_16_t variable. This MACRO accepts one parameter */ /* which is the UUID_16_t variable that is to receive the KFS Range */ /* UUID Constant value. */ /* * NOTE * The UUID will be assigned into the UUID_16_t variable in */ /* Little-Endian format. */ #define TI_ACC_ASSIGN_RANGE_UUID_16(_x) ASSIGN_BLUETOOTH_UUID_16((_x), 0xFF, 0xA2) /* The following MACRO is a utility MACRO that exist to compare a */ /* UUID 16 to the defined TI Accelerometer Service Range */ /* Characteristic UUID in UUID16 form. This MACRO only returns */ /* whether the UUID_16_t variable is equal to the TI Accelerometer */ /* Service Range Characteristic UUID (MACRO returns boolean result) */ /* NOT less than/greater than. The first parameter is the UUID_16_t */ /* variable to compare to the TI Accelerometer Service Range */ /* Characteristic UUID. */ #define TI_ACC_COMPARE_ACC_RANGE_UUID_TO_UUID_16(_x) COMPARE_BLUETOOTH_UUID_16_TO_CONSTANT((_x), 0xFF, 0xA2) /* The following defines the TI Accelerometer Service Range */ /* Characteristic UUID that is used when building the TI */ /* Accelerometer Service Table. */ #define TI_ACC_RANGE_CHARACTERISTIC_BLUETOOTH_UUID_CONSTANT { 0xA2, 0xFF } /* The following MACRO is a utility MACRO that assigns the TI */ /* Accelerometer Service X-Axis Characteristic 16 bit UUID to the */ /* specified UUID_16_t variable. This MACRO accepts one parameter */ /* which is the UUID_16_t variable that is to receive the KFS X-Axis */ /* UUID Constant value. */ /* * NOTE * The UUID will be assigned into the UUID_16_t variable in */ /* Little-Endian format. */ #define TI_ACC_ASSIGN_X_AXIS_UUID_16(_x) ASSIGN_BLUETOOTH_UUID_16((_x), 0xFF, 0xA3) /* The following MACRO is a utility MACRO that exist to compare a */ /* UUID 16 to the defined TI Accelerometer Service X-Axis */ /* Characteristic UUID in UUID16 form. This MACRO only returns */ /* whether the UUID_16_t variable is equal to the TI Accelerometer */ /* Service X-Axis Characteristic UUID (MACRO returns boolean result) */ /* NOT less than/greater than. The first parameter is the UUID_16_t */ /* variable to compare to the TI Accelerometer Service X-Axis */ /* Characteristic UUID. */ #define TI_ACC_COMPARE_ACC_X_AXIS_UUID_TO_UUID_16(_x) COMPARE_BLUETOOTH_UUID_16_TO_CONSTANT((_x), 0xFF, 0xA3) /* The following defines the TI Accelerometer Service X-Axis */ /* Characteristic UUID that is used when building the TI */ /* Accelerometer Service Table. */ #define TI_ACC_X_AXIS_CHARACTERISTIC_BLUETOOTH_UUID_CONSTANT { 0xA3, 0xFF } /* The following MACRO is a utility MACRO that assigns the TI */ /* Accelerometer Service Y-Axis Characteristic 16 bit UUID to the */ /* specified UUID_16_t variable. This MACRO accepts one parameter */ /* which is the UUID_16_t variable that is to receive the KFS Y-Axis */ /* UUID Constant value. */ /* * NOTE * The UUID will be assigned into the UUID_16_t variable in */ /* Little-Endian format. */ #define TI_ACC_ASSIGN_Y_AXIS_UUID_16(_x) ASSIGN_BLUETOOTH_UUID_16((_x), 0xFF, 0xA4) /* The following MACRO is a utility MACRO that exist to compare a */ /* UUID 16 to the defined TI Accelerometer Service Y-Axis */ /* Characteristic UUID in UUID16 form. This MACRO only returns */ /* whether the UUID_16_t variable is equal to the TI Accelerometer */ /* Service Y-Axis Characteristic UUID (MACRO returns boolean result) */ /* NOT less than/greater than. The first parameter is the UUID_16_t */ /* variable to compare to the TI Accelerometer Service Y-Axis */ /* Characteristic UUID. */ #define TI_ACC_COMPARE_ACC_Y_AXIS_UUID_TO_UUID_16(_x) COMPARE_BLUETOOTH_UUID_16_TO_CONSTANT((_x), 0xFF, 0xA4) /* The following defines the TI Accelerometer Service Y-Axis */ /* Characteristic UUID that is used when building the TI */ /* Accelerometer Service Table. */ #define TI_ACC_Y_AXIS_CHARACTERISTIC_BLUETOOTH_UUID_CONSTANT { 0xA4, 0xFF } /* The following MACRO is a utility MACRO that assigns the TI */ /* Accelerometer Service Z-Axis Characteristic 16 bit UUID to the */ /* specified UUID_16_t variable. This MACRO accepts one parameter */ /* which is the UUID_16_t variable that is to receive the KFS Z-Axis */ /* UUID Constant value. */ /* * NOTE * The UUID will be assigned into the UUID_16_t variable in */ /* Little-Endian format. */ #define TI_ACC_ASSIGN_Z_AXIS_UUID_16(_x) ASSIGN_BLUETOOTH_UUID_16((_x), 0xFF, 0xA5) /* The following MACRO is a utility MACRO that exist to compare a */ /* UUID 16 to the defined TI Accelerometer Service Z-Axis */ /* Characteristic UUID in UUID16 form. This MACRO only returns */ /* whether the UUID_16_t variable is equal to the TI Accelerometer */ /* Service Z-Axis Characteristic UUID (MACRO returns boolean result) */ /* NOT less than/greater than. The first parameter is the UUID_16_t */ /* variable to compare to the TI Accelerometer Service Z-Axis */ /* Characteristic UUID. */ #define TI_ACC_COMPARE_ACC_Z_AXIS_UUID_TO_UUID_16(_x) COMPARE_BLUETOOTH_UUID_16_TO_CONSTANT((_x), 0xFF, 0xA5) /* The following defines the TI Accelerometer Service Z-Axis */ /* Characteristic UUID that is used when building the TI */ /* Accelerometer Service Table. */ #define TI_ACC_Z_AXIS_CHARACTERISTIC_BLUETOOTH_UUID_CONSTANT { 0xA5, 0xFF } /* The following define the valid Enable Characteristic Values. */ #define TI_ACC_ENABLE_ACCELEROMETER_DISABLED 0x00 #define TI_ACC_ENABLE_ACCELEROMETER_ENABLE 0x01 /* The following defines the TI Accelerometer Service Enable */ /* Characterisitic Value Length. */ #define TI_ACC_ENABLE_VALUE_LENGTH (BYTE_SIZE) /* The following define the valid Range Characteristic Values. */ #define TI_ACC_RANGE_2G 20 #define TI_ACC_RANGE_8G 80 /* The following defines the TI Accelerometer Service Range */ /* Characterisitic Value Length. */ #define TI_ACC_RANGE_VALUE_LENGTH (WORD_SIZE) /* The following defines the TI Accelerometer Service Axis (X,Y or Z)*/ /* Characteristic Value Length. */ #define TI_ACC_AXIS_VALUE_LENGTH (BYTE_SIZE) /* The following defines the KFS GATT Service Flags MASK that should */ /* be passed into GATT_Register_Service when the KFS Service is */ /* registered. */ #define TI_ACC_SERVICE_FLAGS (GATT_SERVICE_FLAGS_LE_SERVICE|GATT_SERVICE_FLAGS_BR_EDR_SERVICE) #endif
2.078125
2
2024-11-18T21:19:32.286231+00:00
2017-11-14T22:10:53
077c98029b819f95fb274520d7e068ba925574f5
{ "blob_id": "077c98029b819f95fb274520d7e068ba925574f5", "branch_name": "refs/heads/master", "committer_date": "2017-11-14T22:10:53", "content_id": "a92322458b44782cc30be256e63fd409e76f4341", "detected_licenses": [ "MIT" ], "directory_id": "42e03a3a7d663a4d687e238723951d008263827a", "extension": "h", "filename": "PlatformDataTypes.h", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 47770693, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 898, "license": "MIT", "license_type": "permissive", "path": "/BlackfinAPI/include/PlatformDataTypes.h", "provenance": "stackv2-0128.json.gz:317898", "repo_name": "diegoangel/server-people-counter", "revision_date": "2017-11-14T22:10:53", "revision_id": "4d01131375ec986930fcd990a21084ac5fb65680", "snapshot_id": "cc46ecda86e3a518992bd723216a254c0e2301d7", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/diegoangel/server-people-counter/4d01131375ec986930fcd990a21084ac5fb65680/BlackfinAPI/include/PlatformDataTypes.h", "visit_date": "2021-01-24T00:03:35.574302" }
stackv2
/* * PlatformDataTypes.h * * Created on: 16 Sep 2009 * Author: Guy Burton */ #ifndef PLATFORMDATATYPES_H_ #define PLATFORMDATATYPES_H_ #ifdef linux #include <stdint.h> typedef unsigned short i_uint16; typedef short i_sint16; typedef uint32_t i_uint32; // unsigned long typedef int32_t i_sint32; // signed long typedef uint64_t i_uint64 ; // unsigned long long typedef int64_t i_sint64; // signed long long #else typedef unsigned __int16 i_uint16; typedef __int16 i_sint16; typedef unsigned __int32 i_uint32; typedef __int32 i_sint32; typedef unsigned __int64 i_uint64; typedef __int64 i_sint64; #endif #ifdef DEF_BIG_ENDIAN #include <byteswap.h> #define EndianSwap64(x) bswap_64(x) #define EndianSwap32(x) bswap_32(x) #define EndianSwap16(x) bswap_16(x) #else #define EndianSwap64(x) x #define EndianSwap32(x) x #define EndianSwap16(x) x #endif #endif /* PLATFORMDATATYPES_H_ */
2.15625
2
2024-11-18T21:19:32.421473+00:00
2019-06-06T20:08:01
e8552a876937b48c41c397a9539d8f348a76dcf5
{ "blob_id": "e8552a876937b48c41c397a9539d8f348a76dcf5", "branch_name": "refs/heads/master", "committer_date": "2019-06-06T20:08:01", "content_id": "4ce3836d023d44b7c27e8c17e2317d9defda0dac", "detected_licenses": [ "Apache-2.0" ], "directory_id": "f31d0a28d2e7bafa5b78f5159492bab842120a0b", "extension": "c", "filename": "main[1].c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 190642686, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5239, "license": "Apache-2.0", "license_type": "permissive", "path": "/main[1].c", "provenance": "stackv2-0128.json.gz:318029", "repo_name": "escobargabriel/Compact", "revision_date": "2019-06-06T20:08:01", "revision_id": "76e2b58499ab16571a1ba2f7cd51c0393f601ddd", "snapshot_id": "6a26c1d3caa42595ea89f69b36950091a9d7f000", "src_encoding": "ISO-8859-1", "star_events_count": 0, "url": "https://raw.githubusercontent.com/escobargabriel/Compact/76e2b58499ab16571a1ba2f7cd51c0393f601ddd/main[1].c", "visit_date": "2020-06-01T04:45:09.608468" }
stackv2
#include <stdio.h> #include <stdlib.h> #define tamanho 1000000 int main(void) { char sequencia[tamanho], caracter; int i, j, n, quantidade, repete = 0; /* ==========================PRIMEIRA DESCOMPACTAÇÃO========================== */ //inicializa arquivo de fluxo de dados para leitura FILE *arquivo_leitura; //Abre o arquivo para leitura, verificando se a operação foi bem sucedida if((arquivo_leitura = fopen("felis_catus","rb")) == NULL) { printf("Erro ao abrir arquivo compactado!\n"); exit(1); } //Atribui o conteudo enquanto existente do arquivo aberto para a string sequencia fscanf(arquivo_leitura, "%[^\n]", &sequencia); //fecha o arquivo após a leitura fclose(arquivo_leitura); //inicializa arquivo de fluxo para escrita FILE *arquivo_escrita; //verifica se a operação de abertura do arquivo foi bem sucedida if((arquivo_escrita = fopen("felis_catus.txt","w+")) == NULL) { printf("Erro ao abrir o primeiro arquivo para descompactacao!\n"); exit(1); } /*Efetua iteração de todo conteúdo da string "sequencia" buscando as combinações possíveis com 2 caracteres. As combinacoes de caracteres são substituidas por caracteres equivalentes de acordo com a tabela de equivalencia. '\n' '\n' AA . CC ; GG ( TT ? NN - AC * AG [ AT @ CA # CG $ CT % GA _ GC & GT + TA < TC > TG ] quant carac >=3 nº+caracter */ for(i=0; sequencia[i] != '\0'; i++) { //verifica se o caracter da posicao i é eu numero if(isdigit(sequencia[i]) != 0) { repete = atoi(sequencia+i); //imprime a quantidade "repete" do caracter que esta depois do numero j = 1; while(j<repete) { fprintf(arquivo_escrita, "%c", sequencia[i+1]); j++; } } //se não for número, imprime o caracter else { fprintf(arquivo_escrita, "%c", sequencia[i]); } } //fecha o arquivo apos a escrita fclose(arquivo_escrita); /* ===========================SEGUNDA DESCOMPACTAÇÃO=========================== */ //Abre o arquivo para leitura, verificando se a operação foi bem sucedida FILE *arquivo_leitura_2; if((arquivo_leitura_2 = fopen("felis_catus.txt","r")) == NULL) { printf("Erro ao abrir arquivo na segunda compactacao!\n"); exit(1); } //Atribui o conteudo enquanto existente do arquivo aberto para a string sequencia fscanf(arquivo_leitura_2, "%[^\n]", &sequencia); //fecha o arquivo após a leitura fclose(arquivo_leitura_2); //inicializa arquivo de fluxo para escrita FILE *arquivo_escrita_2; //verifica se a operação de abertura do arquivo foi bem sucedida if((arquivo_escrita_2 = fopen("felis_catus.txt","w+")) == NULL) { printf("Erro ao abrir arquivo!\n"); exit(1); } /*Efetua iteração de todo conteudo da string sequencia buscando caracteres repetidos. Os caracteres repetidos são substituidos pelo numero de repeticoes e o caracter repetido, desde que a repeticao seja maior ou igual a 3 */ for(i = 0; sequencia[i] != '\0'; i++) { if(sequencia[i] == '.') { fprintf(arquivo_escrita, "AA"); } else if(sequencia[i] == ';') { fprintf(arquivo_escrita, "CC"); } else if(sequencia[i] == '(') { fprintf(arquivo_escrita, "GG"); } else if(sequencia[i] == '?') { fprintf(arquivo_escrita, "TT"); } else if(sequencia[i] == '-') { fprintf(arquivo_escrita, "NN"); } else if(sequencia[i] == '*') { fprintf(arquivo_escrita, "AC"); } else if(sequencia[i] == '[') { fprintf(arquivo_escrita, "AG"); } else if(sequencia[i] == '@') { fprintf(arquivo_escrita, "AT"); } else if(sequencia[i] == '#') { fprintf(arquivo_escrita, "CA"); } else if(sequencia[i] == '$') { fprintf(arquivo_escrita, "CG"); } else if(sequencia[i] == '%') { fprintf(arquivo_escrita, "CT"); } else if(sequencia[i] == '_') { fprintf(arquivo_escrita, "GA"); } else if(sequencia[i] == '&') { fprintf(arquivo_escrita, "GC"); } else if(sequencia[i] == '+') { fprintf(arquivo_escrita, "GT"); } else if(sequencia[i] == '<') { fprintf(arquivo_escrita, "TA"); } else if(sequencia[i] == '>') { fprintf(arquivo_escrita, "TC"); } else if(sequencia[i] == ']' ) { fprintf(arquivo_escrita, "TG"); } else if(sequencia[i] == '\n') { fprintf(arquivo_escrita, "\n"); } else { fprintf(arquivo_escrita, "%c", sequencia[i]); } } //fecha o arquivo apos escrever fclose(arquivo_escrita_2); return 0; }
3.515625
4
2024-11-18T21:19:32.499166+00:00
2023-05-31T23:22:47
4e90edb8bc00603f6e5a334198c5179f3cd09901
{ "blob_id": "4e90edb8bc00603f6e5a334198c5179f3cd09901", "branch_name": "refs/heads/main", "committer_date": "2023-05-31T23:22:47", "content_id": "bb1180897671b1c692aac155cb1e36e527d8d268", "detected_licenses": [ "MIT" ], "directory_id": "4a727ce379e9d21826895699d09164cdac4836d5", "extension": "c", "filename": "sieve.c", "fork_events_count": 95, "gha_created_at": "2018-11-09T22:21:21", "gha_event_created_at": "2022-11-26T19:09:25", "gha_language": "C", "gha_license_id": "MIT", "github_id": 156924419, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 6898, "license": "MIT", "license_type": "permissive", "path": "/notes/session25/sieve.c", "provenance": "stackv2-0128.json.gz:318157", "repo_name": "RHIT-CSSE/csse332", "revision_date": "2023-05-31T23:22:47", "revision_id": "7b9e292381062d25934c18210e6bbe7241392cdc", "snapshot_id": "83e58d6c377e67d4cfcc37e2f20f18991c5063bf", "src_encoding": "UTF-8", "star_events_count": 10, "url": "https://raw.githubusercontent.com/RHIT-CSSE/csse332/7b9e292381062d25934c18210e6bbe7241392cdc/notes/session25/sieve.c", "visit_date": "2023-06-08T11:16:43.095931" }
stackv2
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <pthread.h> #define MAX_NUM 50 #define NUM_THREADS 3 /* This is an implementation of the famous sieve of eratosthenes algorithm which finds (small) prime numbers. The idea is pretty simple - we have the nums array which represents all the numbers we are going to consider up to our max. Initially we mark every element with 'P' because it could potentially be prime. We could start with only the knowledge that 0 1 are not prime and that 2 is prime, but to simplify lets assume that we know that 2 3 and 5 are prime. When we know a number is prime we iterate across the list of numbers, starting from a particular prime and marking all its multiples. So since I know 5 is prime I'll mark 10, 15, 20, etc. as composite ('C' in the nums array) - up to our max number. This is what the sieve_for function does. PART 1 (25 points) Right now we run sieve_for for 2 3 and 5 serially, but it would be better if we ran them in paralell on seperate threads. Modify sieve_for and use pthreads to start the 3 sieves in paralell. Your output should look something like this: starting sieve for 2 starting sieve for 3 starting sieve for 5 sieve 2 found composite 4 sieve 5 found composite 10 sieve 3 found composite 6 sieve 5 found composite 15 sieve 3 found composite 9 sieve 2 found composite 8 sieve 5 found composite 20 sieve 3 found composite 12 sieve 5 found composite 25 sieve 5 found composite 30 sieve 3 found composite 18 sieve 2 found composite 14 sieve 5 found composite 35 sieve 3 found composite 21 sieve 2 found composite 16 sieve 5 found composite 40 sieve 3 found composite 24 sieve 5 found composite 45 sieve for 5 finished sieve 3 found composite 27 sieve 2 found composite 22 sieve 3 found composite 33 sieve 3 found composite 36 sieve 2 found composite 26 sieve 3 found composite 39 sieve 2 found composite 28 sieve 3 found composite 42 sieve 2 found composite 32 sieve 3 found composite 48 sieve for 3 finished sieve 2 found composite 34 sieve 2 found composite 38 sieve 2 found composite 44 sieve 2 found composite 46 sieve for 2 finished primes are 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 49 PART 2 (15 points) This part is a little harder for the 15 points you get. You can see the output for PART 1 is not right. It thinks 49 is prime. The reason for this is after we identify another value as prime, we also need to start a sieve for that number. So after one of our sieve threads completes, we should start a new sieve thread for the next number > 5 we think is prime (7). Once our second thread finishes, we should start a sieve for the next prime that remains after 7, etc. To make things simple, we will run our 3 threads in batches, i.e., we start the first three threads for 2,3, and 5. Then we wait for them to finish before we launch the next batch of three threads for 7, 11, and 13. And so on after that in batches of three threads until we've started sieves for all primes less than MAX_NUM (we could actually stop a little sooner than that, but let's not be fancy). It should look like this: starting sieve for 2 starting sieve for 3 starting sieve for 5 sieve 2 found composite 4 sieve 3 found composite 6 sieve 5 found composite 10 sieve 3 found composite 9 sieve 5 found composite 15 sieve 2 found composite 8 sieve 3 found composite 12 sieve 5 found composite 20 sieve 5 found composite 25 sieve 3 found composite 18 sieve 5 found composite 30 sieve 2 found composite 14 sieve 3 found composite 21 sieve 5 found composite 35 sieve 2 found composite 16 sieve 3 found composite 24 sieve 5 found composite 40 sieve 3 found composite 27 sieve 5 found composite 45 sieve for 5 finished sieve 2 found composite 22 sieve 3 found composite 33 sieve 3 found composite 36 sieve 2 found composite 26 sieve 3 found composite 39 sieve 2 found composite 28 sieve 3 found composite 42 sieve 2 found composite 32 sieve 3 found composite 48 sieve for 3 finished sieve 2 found composite 34 sieve 2 found composite 38 sieve 2 found composite 44 sieve 2 found composite 46 sieve for 2 finished starting sieve for 7 starting sieve for 13 starting sieve for 11 sieve for 13 finished sieve for 11 finished sieve 7 found composite 49 sieve for 7 finished starting sieve for 17 starting sieve for 19 starting sieve for 23 sieve for 17 finished sieve for 23 finished sieve for 19 finished starting sieve for 29 sieve for 29 finished starting sieve for 31 sieve for 31 finished starting sieve for 37 sieve for 37 finished starting sieve for 41 sieve for 41 finished starting sieve for 43 sieve for 43 finished starting sieve for 47 sieve for 47 finished primes are 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 The fanciest solutions involve reusing the pthread_ts for our threads because we know we will only have NUM_THREADS parallel threads at once. But that approach can be a little tricky. Easier is probably to allocate a thread_t for each entry in nums, even though most of them will never actually be used. You can also make a special marking in the nums array (e.g. have 'P' for prime but we haven't sieved it, and 'S' for prime but the sieve has been created). You may also notice an unlikely bug - what would happen if the sieves for 2 and 5 ran so fast and the sieve for 3 ran so slow that by the time we need to start new threads 9 still looked prime? Don't worry about this bug. */ char nums[MAX_NUM]; void* sieve_for(long num) { printf("starting sieve for %ld\n", num); long current = num + num; while(current < MAX_NUM) { usleep(100); // a little wait to make the parallelism easier to notice if(nums[current] != 'C') printf("sieve %ld found composite %ld\n", num, current); nums[current] = 'C'; // C for composite current = current + num; } printf("sieve for %ld finished\n", num); return NULL; } int main(int argc, char **argv) { /* TODO: YOUR IMPLEMENTATION GOES HERE */ int i; pthread_t threads[NUM_THREADS]; long params[] = {2, 3, 5}; for(int i = 2; i < MAX_NUM; i++) { nums[i] = 'P'; //mark all numbers as potentially prime } // these are put in parallel in PART 1 sieve_for(2); sieve_for(3); sieve_for(5); // here's where you add your loop that starts batches of threads once other // threads finish when you do part 2 printf("primes are "); for(long i = 2; i < MAX_NUM; i++) { if(nums[i] == 'P') printf("%ld ", i); } printf("\n"); }
3.375
3
2024-11-18T21:19:32.972266+00:00
2017-03-06T17:45:34
c77a3d30f71394508a0ce6e6cf58e3942cb90099
{ "blob_id": "c77a3d30f71394508a0ce6e6cf58e3942cb90099", "branch_name": "refs/heads/master", "committer_date": "2017-03-06T17:45:34", "content_id": "46ed05e6ed2e20907e1486cea4f33b1309ecdbd9", "detected_licenses": [ "MIT" ], "directory_id": "04a1d1662537aeb624d4d08df965f8a3367fed36", "extension": "c", "filename": "common.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 73592169, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 19321, "license": "MIT", "license_type": "permissive", "path": "/src/common.c", "provenance": "stackv2-0128.json.gz:318418", "repo_name": "chibby0ne/client_server", "revision_date": "2017-03-06T17:45:34", "revision_id": "e628a60b33942e013becb627e5ed476e8dda0865", "snapshot_id": "f2f10da656aaf702506899ca19750d33d470c817", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/chibby0ne/client_server/e628a60b33942e013becb627e5ed476e8dda0865/src/common.c", "visit_date": "2020-07-31T21:15:14.512881" }
stackv2
#include "common.h" #include "client.h" #include "server.h" #include <sys/socket.h> #include <sys/types.h> #include <netdb.h> #include <string.h> #include <stdlib.h> #include <stdio.h> /** * Initializes the hints structure passed as parameters. according to the flag * parameters passed. The family choosen is unspecified i.e: could be either * IPv4 or IPv6, and the socket type choosen is a SOCK_STREAM. * * @param hints structure when the hints are hold * @param flag used to initialize the flags, for our purposes either SERVER or * CLIENT */ void initialize_hints(struct addrinfo *hints, int flag) { assert(flag == SERVER || flag == CLIENT); // initialize hints to 0 memset(hints, 0, sizeof(*hints)); hints->ai_family = AF_UNSPEC; hints->ai_socktype = SOCK_STREAM; if (flag == SERVER) { hints->ai_flags = AI_PASSIVE; } } /** * Invokes the getaddrinfo function to get the addressinfo structure res * obtained for the given hostname, the given port_number and the hints * structure passed. * Function fails and the program exits when there's an error with the * getaddrinfo function * * @param hostname hostname or IP address * @param port_number port number to listen/connect to * @param hints addrinfo structure that holds the hints for the type of * addrinfo structure we want * @param res resulting addrinfo structure using the parameters */ void get_addrinfo_list(const char *hostname, const char *port_number, struct addrinfo *hints, struct addrinfo **res) { assert(hostname != ""); printf("preparing addrinfo struct...\n"); // get the addrinfo structures list with the hints criteria int status = getaddrinfo(hostname, port_number, hints, res); if (status != 0) { fprintf(stderr, "get_addrinfo_list: %s\n", gai_strerror(status)); exit(EXIT_FAILURE); } assert(status == 0); } /** * * Finds and returns the first connectable socket using the addrinfo structure * provided. * It iterates over the available addrinfo structures pointed by res beginning * from res. * Function fails and exits the program if it could not find a connectable * * @param res addrinfo structure that includes the family, socket type and * protocol to be used for the socket * @return the connectable socket */ int find_connectable_socket(struct addrinfo *res) { assert(res != NULL); printf("creating socket...\n"); int socketfd; // iterate over the list of addrinfo structure until we find an addressinfo // that we can create a socket from and connect to its address. for (struct addrinfo *ai = res; ai != NULL; ai = ai->ai_next) { socketfd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol); // if the socket wasn't created, try with another addrinfo structure if (socketfd == -1) { perror("find_usable_socket-socket()"); continue; } if (connect_through_socket(socketfd, ai) == 0) { return socketfd; } } assert(socketfd == -1); fprintf(stderr, "Couldn't find a socket\n"); exit(EXIT_FAILURE); } /** * Finds and returns the first socket found from the addrinfo structure res * NOTE: This socket may or may not be connectable. For a connectable socket * @see find_connectable_socket * * @param res structure holding the chain of addrinfo strucutres containing the * parameters necessary for the creation of a socket * @return the socket */ int find_socket(struct addrinfo *res) { assert(res != NULL); printf("creating socket...\n"); int socketfd; /** * iterate over the list of addrinfo structure until we find an addressinfo * that we can create a socket from and connect to its address. */ for (struct addrinfo *ai = res; ai != NULL; ai = ai->ai_next) { socketfd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol); // if the socket wasn't created, try with another addrinfo structure if (socketfd == -1) { perror("find_socket-socket()"); continue; } else { return socketfd; } } assert(socketfd == -1); fprintf(stderr, "Couldn't find a socket\n"); exit(EXIT_FAILURE); } /** * Tries to connect the given socketfd using the information contained in res * * @return 0 on success, -1 otherwise */ static int connect_through_socket(int socketfd, struct addrinfo *res) { assert(socketfd != -1); assert(res != NULL); int ret = connect(socketfd, res->ai_addr, res->ai_addrlen); /** * if the socket was successfully connected we stop looking through the * list */ if (ret == 0) { return 0; } else { perror("connect_through_socket-connect()"); /** * close the file descriptor (socket is a file descriptor), as we * couldn't connect through it */ close(socketfd); return -1; } } /** * Helper function that prints the ip address from a struct addrinfo to stderr * * @param res pointer to structure holding the ip address */ static void print_ip(struct addrinfo *res) { char ipstr[INET6_ADDRSTRLEN]; if (res->ai_family == AF_INET) { struct sockaddr_in *ipv4 = (struct sockaddr_in *) res->ai_addr; inet_ntop(AF_INET, &(ipv4->sin_addr), ipstr, sizeof(ipstr)); } else { struct sockaddr_in6 *ipv6 = (struct sockaddr_in6 *) res->ai_addr; inet_ntop(AF_INET6, &(ipv6->sin6_addr), ipstr, sizeof(ipstr)); } fprintf(stderr, "%s\n", ipstr); } /** * Binds the given socket to the port PORT_NUMBER, that was specifed when * obtaining the res structure. * This function is mostly used when want to create a server, as it is necessary * to bind the socket before starting to listen to incomming connections. * Fails and exits the program if an error occure while calling the bind * function on the socket * * @param socketfd socket used for conections * @param res structure that holds the parameters required to bind socketfd */ void bind_socket(int socketfd, char *port, struct addrinfo *res) { assert(socketfd != -1); assert(res != NULL); printf("binding socket to port %s\n", port); int ret = bind(socketfd, res->ai_addr, res->ai_addrlen); if (ret == -1) { perror("bind_socket-bind()"); // if the port is not in use for we get from the kernel that it is in // use, it is because it takes a while for the kernel to release the // port again, but this forces it to release it if (errno == EADDRINUSE) { int yes = 1; if (setsockopt(socketfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1) { perror("setsockopt"); exit(1); } printf("freeing port %s...\n", port); } else { exit(EXIT_FAILURE); } } } /** * Listens to incomming using the socket socketfd, and holds a maximum number of * connections in queue of backlog * Fails and exits the program if there's an error while calling the listen * function on the socket * * @param socket used for incomming connections * @param backlog max number of incomming connections to be queued. */ void listen_socket(int socketfd, char *port, int backlog) { assert(socketfd != -1); printf("listening to port: %s\n", port); int ret = listen(socketfd, backlog); if (ret == -1) { perror("listen_socket-listen()"); exit(EXIT_FAILURE); } } /** * Wrapper for the accept function, that accepts an incoming connections from * the queue of incomming connections to socketfd, and stores the address of the * client into addr structure. It creates a socket with the accepted connnection * and the original socketfd remains open listening for more connections. * * @param socketfd listening socket that has a connection pending from a client * @param addr sockaddr_storage structure used to hold the address of the client * @return the new socket that is connected to the remote socket */ int accept_connection(int socketfd, struct sockaddr_storage *addr) { assert(socketfd != -1); printf("accepting connections...\n"); socklen_t addr_size = sizeof(*addr); int new_socket = accept(socketfd, (struct sockaddr *)addr, &addr_size); if (new_socket == -1) { assert(errno == ENOTSOCK); perror("accept_connection-accept()"); exit(EXIT_FAILURE); } assert(new_socket != -1); return new_socket; } /** * Handles the reception of messages from a either a client or a server, using a * connected socket contained inside object, that is of the given type. * In case there's an error, the function prints out an error message to * stderr describing the problem. * * @param object client or server containing the connected socket * @param type indicates whether the object is a CLIENT or SERVER type * @return error status of the recv function call */ static int receive_message(void *object, int type) { int status = 0; struct client_t *client; struct server_t *server; switch (type) { case CLIENT: client = (struct client_t *) object; status = recv(client->socket_connected, &(client->recv_buffer), BUFFER_SIZE, 0); break; case SERVER: server = (struct server_t *) object; status = recv(server->socket_connected, &(server->recv_buffer), BUFFER_SIZE, 0); break; default: fprintf(stderr, "This is an unsupported mode of operation\n"); exit(EXIT_FAILURE); } if (status == -1) { perror("receive_message-recv()"); } return status; } /** * Handles the sending of messages from either a client or a server, using a * connected socket contained insde boject, that is of the given type. * In case there's an error, the function prints out an error message to * stderr describing the problem. * * @param object client or server containing the connected socket * @param type indicates whether the object is a CLIENT or SERVER type * @return error status of the recv function call */ int send_message(void *object, int type) { int status; struct client_t *client; struct server_t *server; switch (type) { case CLIENT: client = (struct client_t *) object; status = send(client->socket_connected, &(client->send_buffer), BUFFER_SIZE, 0); break; case SERVER: server = (struct server_t *) object; status = send(server->socket_connected, &(server->send_buffer), BUFFER_SIZE, 0); break; default: fprintf(stderr, "This is an unsupported mode of operation\n"); exit(EXIT_FAILURE); } if (status == -1) { perror("send_message-send()"); } return status; } /** * Prints message to console, and prepends a "From server/client" depending on * which type of program it is running as i.e: if it is running as a client, * then the message must come from the server * * @param buffer char array where the message is stored * @param type CLIENT or SERVER int macros */ static void show_message(char *buffer, int type) { printf("%s %s", type == CLIENT ? "From server:" : "From client:", buffer); } /** * Reads strings from stdin and stores it in a buffer up to the EOF or the * newline character, if newline character is inputted it is also included in * the message stored in the buffer * * @param buffer char array whre the message is stored */ void read_stdin_to_buffer(char *buffer) { fgets(buffer, BUFFER_SIZE, stdin); } /** * Read strings from stdint and sends them throught the connected socket of the * given client. This is the function handled by the recv_thread. * * @param client a structure containing the server and the status used to break * from the main loop */ void *read_received_message_client(void *client_param) { struct client_recv_status_t *client_recv_status = (struct client_recv_status_t *) client_param; struct client_t *client = client_recv_status->client; int *status = client_recv_status->recv_status; do { *status = receive_message(client, CLIENT); show_message(client->recv_buffer, CLIENT); } while (*status > 0); return NULL; } /** * Read strings from stdint and sends them throught the connected socket of the * given server. This is the function handled by the recv_thread. * * @param server a structure containing the server and the status used to break * from the main loop */ void *read_received_message_server(void *server_param) { struct server_recv_status_t *server_recv_status = (struct server_recv_status_t *) server_param; struct server_t *server = server_recv_status->server; int *status = server_recv_status->recv_status; do { *status = receive_message(server, SERVER); show_message(server->recv_buffer, SERVER); } while (*status > 0); return NULL; } /** * Helper function used to create and return a string, which is a copy of the * string s but in which all alphabetical characters are lower case * * @param s string with characters in lower and/or upper case * @return string with characters in lower case */ static char *convert_to_lowercase(char *s) { size_t len = sizeof(s); char *new_s = (char *) malloc(len); for (u_int32_t i = 0; i < len; ++i) { new_s[i] = tolower(s[i]); } return new_s; } /** * Helper function used for showing fatal error messages on stderr */ static void print_error_exit() { fprintf(stderr, "Usage: client_server MODE [IP] [PORT]\nMODE: \"client\" or " "\"server\"\nIP: only used and required for client mode (could " "be IP or hostname)\nPORT: to select a specific port, else " "default port is 10000\n"); exit(EXIT_FAILURE); } /** * Checks if the string corresponds to a valid ip address * * @param s contains the ip address * @return 1 if s is valid, 0 otherwise */ static int is_valid_ip(char *s) { struct sockaddr_in sa; struct sockaddr_in6 sa6; int ret = inet_pton(AF_INET, s, &(sa.sin_addr)) || inet_pton(AF_INET6, s, &(sa6.sin6_addr)); return ret == 1; } /** * Checks if the s is a valid hostname * * @param s contains the hostname of the server to connect to * @return 1 if s is a valid hostname, 0 otherwise */ static int is_valid_hostname(char *s) { size_t len = sizeof(s); if (len > HOSTNAME_MAX_LENGTH) { return 0; } u_int32_t label_size = 0; for (u_int32_t i = 0; i < len; ++i) { if (s[i] == '.') { if (s[i - 1] == '.') { return 0; } label_size = 0; } else if (is_label_longer_than_allowed(label_size) || !is_valid_hostname_char(s[i])) { return 0; } label_size++; } return 1; } /** * Checks if label is longer than maximum allowed * * @param number of chars between the last dot (or beginning) and now * @return 1 if it longer than allowed, 0 otherwise */ static int is_label_longer_than_allowed(u_int32_t size_between_dots) { return size_between_dots > HOSTNAME_LABEL_MAX_LENGTH; } /** * Checks if c is a valid hostname character * * @param c character to check * @return 1 if c is a valid hostname char, 0 otherwise */ static int is_valid_hostname_char(char c) { return (isalpha(c) || c == '-' || c == '_' || c == '.'); } /** * Prints the command line parameters to stdout, including the executable name * * @param argc number of command line arguments (including the executable) * @param argv array of strings representing command line arguments */ static void print_cla(int argc, char *argv[]) { for (u_int32_t i = 1; i < argc; ++i) { printf("argv[%d] = %s\n", i, argv[i]); } } /** * Checks the command line arguments, validates them, and returns the mode * chosen for the current program. * * @param argc number of parameters (including executable name) * @param argv array of command line parameters * @return the mode to use the program (CLIENT or SERVER) */ int handle_input(int argc, char *argv[]) { int mode; if (argc < 2 || argc > 4) { print_cla(argc, argv); print_error_exit(); } else { if (strcmp("client", convert_to_lowercase(argv[1])) == 0) { mode = CLIENT; if (argc == 3) { if (!is_valid_ip(argv[2]) && !is_valid_hostname(argv[2])) { fprintf(stderr, "Not valid IP or hostname: %s\n", argv[2]); print_error_exit(); } } else if (argc == 4) { if (!is_valid_ip(argv[2]) && !is_valid_hostname(argv[2])) { fprintf(stderr, "Not valid IP or hostname: %s\n", argv[2]); print_error_exit(); } if (!is_valid_port(argv[3])) { fprintf(stderr, "Not valid port number: %s. Enter port " "number in range: %d - %d\n", argv[3], MIN_PORT_NUMBER, MAX_PORT_NUMBER); print_error_exit(); } } else { print_cla(argc, argv); print_error_exit(); } } else if (strcmp("server", convert_to_lowercase(argv[1])) == 0) { mode = SERVER; if (argc == 3 && !is_valid_port(argv[2])) { fprintf(stderr, "Not valid port number: %s. Enter port " "number in range: %d - %d\n", argv[2], MIN_PORT_NUMBER, MAX_PORT_NUMBER); print_error_exit(); } } else { fprintf(stderr, "Not a valid mode: %s\n", argv[1]); print_error_exit(); } } return mode; } /** * Utility function to aid in debugging of the addrinfo structure returned by * the call to getadrinfo. It prints all the IP address in the addrinfo chain. * * @param addrinfo structure returned by getaddrinfo() */ static void iterate_over_results(struct addrinfo *results) { u_int32_t i = 0; for (struct addrinfo *cur = results; cur != NULL ; cur = cur->ai_next, i++) { printf("Number %d:\n", i); print_ip(cur); } } /** * Checks if s is a valid port number (between 1024 and 49151) * * @param s port number * @return 1 if it is a valid port, 0 otherwise */ static int is_valid_port(char *s) { int val = atoi(s); if (val >= MIN_PORT_NUMBER && val <= MAX_PORT_NUMBER) { return 1; } return 0; } /** * Clear screen */ void clear_screen() { /* printf("\033c"); */ system("tput clear"); } /** * Move cursor to the last row of the terminal */ void move_cursor_to_last_row() { struct winsize w; ioctl(STDOUT_FILENO, TIOCGWINSZ, &w); char command[20]; strncpy(command, "tput cup ", 10); char buffer[10]; snprintf(buffer, 10, "%d %d", w.ws_row - 1, 0); strncat(command, buffer, 20); system(command); }
2.828125
3
2024-11-18T21:19:33.112449+00:00
2023-02-16T11:27:40
c980e21a2140e8fd4a411343d6372c42df359289
{ "blob_id": "c980e21a2140e8fd4a411343d6372c42df359289", "branch_name": "refs/heads/main", "committer_date": "2023-02-16T14:59:16", "content_id": "b60462da53e1ebd1a17cc46d4b1953cf92cd57ba", "detected_licenses": [ "Apache-2.0" ], "directory_id": "e8302c75d770d1608b317d6af5c483bbad6c0493", "extension": "h", "filename": "posix_arch_internal.h", "fork_events_count": 32, "gha_created_at": "2016-08-05T22:14:50", "gha_event_created_at": "2022-04-05T17:14:07", "gha_language": "C", "gha_license_id": "Apache-2.0", "github_id": 65052293, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 804, "license": "Apache-2.0", "license_type": "permissive", "path": "/arch/posix/include/posix_arch_internal.h", "provenance": "stackv2-0128.json.gz:318678", "repo_name": "intel/zephyr", "revision_date": "2023-02-16T11:27:40", "revision_id": "06d5bc51b580777079bb0b7e769e4127598ea5ee", "snapshot_id": "819362089aa44ae378a5558f3b222197aaa811f7", "src_encoding": "UTF-8", "star_events_count": 32, "url": "https://raw.githubusercontent.com/intel/zephyr/06d5bc51b580777079bb0b7e769e4127598ea5ee/arch/posix/include/posix_arch_internal.h", "visit_date": "2023-09-04T00:20:35.217393" }
stackv2
/* * Copyright (c) 2018 Oticon A/S * * SPDX-License-Identifier: Apache-2.0 */ #ifndef ZEPHYR_ARCH_POSIX_INCLUDE_POSIX_ARCH_INTERNAL_H_ #define ZEPHYR_ARCH_POSIX_INCLUDE_POSIX_ARCH_INTERNAL_H_ #include <zephyr/toolchain.h> #define PC_SAFE_CALL(a) pc_safe_call(a, #a) #ifdef __cplusplus extern "C" { #endif static inline void pc_safe_call(int test, const char *test_str) { /* LCOV_EXCL_START */ /* See Note1 */ if (unlikely(test)) { posix_print_error_and_exit("POSIX arch: Error on: %s\n", test_str); } /* LCOV_EXCL_STOP */ } #ifdef __cplusplus } #endif #endif /* ZEPHYR_ARCH_POSIX_INCLUDE_POSIX_ARCH_INTERNAL_H_ */ /* * Note 1: * * All checks for the host pthreads functions which are wrapped by PC_SAFE_CALL * are meant to never fail, and therefore will not be covered. */
2.109375
2
2024-11-18T21:19:33.321054+00:00
2023-06-30T12:45:39
ca4d185436cad39c11f953e3bfca7e99412fa9f3
{ "blob_id": "ca4d185436cad39c11f953e3bfca7e99412fa9f3", "branch_name": "refs/heads/master", "committer_date": "2023-06-30T12:45:39", "content_id": "b436d0a74efe5f0b55f365f09965e74bfa52aa27", "detected_licenses": [ "MIT" ], "directory_id": "aaba42e607e272f6b7ee1eabdb702705da1d2218", "extension": "h", "filename": "util.h", "fork_events_count": 9, "gha_created_at": "2020-02-12T20:50:49", "gha_event_created_at": "2023-06-30T12:45:40", "gha_language": "C", "gha_license_id": "MIT", "github_id": 240112492, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4760, "license": "MIT", "license_type": "permissive", "path": "/src/compiler/util.h", "provenance": "stackv2-0128.json.gz:318940", "repo_name": "gooofy/aqb", "revision_date": "2023-06-30T12:45:39", "revision_id": "bdaa005eb2ed04d16dfb6ccdc7f43e37883016b7", "snapshot_id": "36608afd63011e5056e230fe3921a272951011dd", "src_encoding": "UTF-8", "star_events_count": 70, "url": "https://raw.githubusercontent.com/gooofy/aqb/bdaa005eb2ed04d16dfb6ccdc7f43e37883016b7/src/compiler/util.h", "visit_date": "2023-08-31T08:52:30.441006" }
stackv2
#ifndef UTIL_H #define UTIL_H #include <assert.h> #include <stdio.h> #include <stdint.h> #ifdef __amigaos__ #include <intuition/intuition.h> #endif typedef char *string; typedef char bool; #define TRUE 1 #define FALSE 0 #define VERSION "0.9.0alpha1" #define PROGRAM_DATE "25.03.2023" #define COPYRIGHT "(C) 2020, 2021, 2022, 2023 by G. Bartsch" #define PROGRAM_NAME_SHORT "AQB" #define PROGRAM_NAME_LONG "AQB Amiga BASIC" #define LICENSE "Licensed under the MIT license." /* * endianness */ #if defined (__GLIBC__) #include <endian.h> #if (__BYTE_ORDER == __LITTLE_ENDIAN) #define AQB_LITTLE_ENDIAN #elif (__BYTE_ORDER == __BIG_ENDIAN) #define AQB_BIG_ENDIAN #elif (__BYTE_ORDER == __PDP_ENDIAN) #define AQB_BIG_ENDIAN #else #error "Unable to detect endianness for your target." #endif #elif defined(_BIG_ENDIAN) #define AQB_BIG_ENDIAN #elif defined(_LITTLE_ENDIAN) #define AQB_LITTLE_ENDIAN #elif defined(__sparc) || defined(__sparc__) \ || defined(_POWER) || defined(__powerpc__) \ || defined(__ppc__) || defined(__hpux) \ || defined(_MIPSEB) || defined(_POWER) \ || defined(__s390__) #define AQB_BIG_ENDIAN #elif defined(__i386__) || defined(__alpha__) \ || defined(__ia64) || defined(__ia64__) \ || defined(_M_IX86) || defined(_M_IA64) \ || defined(_M_ALPHA) || defined(__amd64) \ || defined(__amd64__) || defined(_M_AMD64) \ || defined(__x86_64) || defined(__x86_64__) \ || defined(_M_X64) #define AQB_LITTLE_ENDIAN #else #error "Unable to detect endianness for your target." #endif #ifdef AQB_LITTLE_ENDIAN #define ENDIAN_SWAP_16(data) ( (((data) >> 8) & 0x00FF) | (((data) << 8) & 0xFF00) ) #define ENDIAN_SWAP_32(data) ( (((data) >> 24) & 0x000000FF) | (((data) >> 8) & 0x0000FF00) | \ (((data) << 8) & 0x00FF0000) | (((data) << 24) & 0xFF000000) ) #define ENDIAN_SWAP_64(data) ( (((data) & 0x00000000000000ffLL) << 56) | \ (((data) & 0x000000000000ff00LL) << 40) | \ (((data) & 0x0000000000ff0000LL) << 24) | \ (((data) & 0x00000000ff000000LL) << 8) | \ (((data) & 0x000000ff00000000LL) >> 8) | \ (((data) & 0x0000ff0000000000LL) >> 24) | \ (((data) & 0x00ff000000000000LL) >> 40) | \ (((data) & 0xff00000000000000LL) >> 56)) #else #define ENDIAN_SWAP_16(data) (data) #define ENDIAN_SWAP_32(data) (data) #define ENDIAN_SWAP_64(data) (data) #endif static inline int roundUp(int numToRound, int multiple) { if (multiple == 0) return numToRound; int remainder = numToRound % multiple; if (remainder == 0) return numToRound; return numToRound + multiple - remainder; } /* * memory management */ typedef enum { UP_frontend, UP_types, UP_temp, UP_assem, UP_codegen, UP_env, UP_flowgraph, UP_linscan, UP_symbol, UP_regalloc, UP_liveness, UP_link, UP_ide, UP_options, UP_runChild, UP_numPools } U_poolId; void *U_poolAlloc (U_poolId pid, size_t size); void *U_poolCalloc (U_poolId pid, size_t nmemb, size_t len); void *U_poolNonChunkAlloc (U_poolId pid, size_t size); void *U_poolNonChunkCAlloc (U_poolId pid, size_t size); void U_poolNonChunkFree (U_poolId pid, void *mem); void U_poolReset (U_poolId pid); // frees all memory reserved through this pool, keeps pool itself intact for now allocations void U_memstat (void); /* * string support */ string String (U_poolId pid, const char *); // allocs mem + copies string string strconcat (U_poolId pid, const char *s1, const char*s2); // allocates mem for concatenated string string strprintf (U_poolId pid, const char *format, ...); // allocates mem for resulting string string strlower (U_poolId pid, const char *s); // allocates mem for resulting string string strupper (U_poolId pid, const char *s); // allocates mem for resulting string int strcicmp (string a, string b); // string ignore case compare void strserialize (FILE *out, string str); string strdeserialize (U_poolId pid, FILE *in); bool str2int (string str, int *i); /* * FFP - Motorola Fast Floating Point format support */ uint32_t encode_ffp (float f); float decode_ffp (uint32_t fl); void U_float2str(double v, char *buffer, int buf_len); /* * misc */ float U_getTime (void); void U_delay (uint16_t millis); #ifdef __amigaos__ bool U_request (struct Window *win, char *posTxt, char *negTxt, char* format, ...); #endif void U_init (void); void U_deinit (void); #endif
2.03125
2
2024-11-18T21:19:33.824857+00:00
2015-05-16T22:12:23
a4665791b3060e033f9fb0713eb0e4164912a322
{ "blob_id": "a4665791b3060e033f9fb0713eb0e4164912a322", "branch_name": "refs/heads/master", "committer_date": "2015-05-16T22:12:23", "content_id": "644f2b726f7849acb22740f0077ebfd799708e16", "detected_licenses": [ "BSD-4-Clause-UC" ], "directory_id": "59b6dac932e6627987d6a229fa5d16c7a8fe790a", "extension": "c", "filename": "ansi_parser.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": 3032, "license": "BSD-4-Clause-UC", "license_type": "permissive", "path": "/src/ansi_parser.c", "provenance": "stackv2-0128.json.gz:319070", "repo_name": "kyorlin2001/dalemud", "revision_date": "2015-05-16T22:12:23", "revision_id": "b92ba1bf4809826c465d774b179f3f856dbf9462", "snapshot_id": "0d081d21c07668f846466a0856fb6f613342a90c", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/kyorlin2001/dalemud/b92ba1bf4809826c465d774b179f3f856dbf9462/src/ansi_parser.c", "visit_date": "2020-03-16T09:27:36.412661" }
stackv2
/* *** DaleMUD ANSI_PARSER.C *** Parser ansi colors for act(); */ #include <stdio.h> #include <string.h> #include <ctype.h> #include <time.h> #include "ansi.h" #include "protos.h" extern long SystemFlags; /* $CMBFG, where M is modier, B is back group color and FG is fore $C0001 would be normal, black back, red fore. $C1411 would be bold, blue back, light yellow fore */ char *ansi_parse(char *code ) { static char m[MAX_STRING_LENGTH]; /* increased from 255 to MAX 2-18 msw */ char b[128],f[128]; if (!code) return(""); /* changed this from NULL to "" 2-18 msw */ /* do modifier */ switch(code[0]) { case '0':sprintf(m,"%s",MOD_NORMAL); break; case '1':sprintf(m,"%s",MOD_BOLD); break; case '2':sprintf(m,"%s",MOD_FAINT); break; /* not used in ansi that I know of */ case '3':sprintf(m,"%s",MOD_NORMAL); break; case '4':sprintf(m,"%s",MOD_UNDERLINE); break; case '5': sprintf(m,"%s",MOD_BLINK); break; case '6': sprintf(m,"%s",MOD_REVERSE); break; default: sprintf(m,"%s",MOD_NORMAL); break; } /* do back ground color */ switch(code[1]) { case '0': sprintf(b,"%s",BK_BLACK); break; case '1': sprintf(b,"%s",BK_RED); break; case '2': sprintf(b,"%s",BK_GREEN); break; case '3': sprintf(b,"%s",BK_BROWN); break; case '4': sprintf(b,"%s",BK_BLUE); break; case '5': sprintf(b,"%s",BK_MAGENTA); break; case '6': sprintf(b,"%s",BK_CYAN); break; case '7': sprintf(b,"%s",BK_LT_GRAY); break; default:sprintf(b,"%s",BK_BLACK); break; } /* do foreground color */ switch(code[2]) { case '0': switch(code[3]) { /* 00-09 */ case '0': sprintf(f,"%s",FG_BLACK); break; case '1': sprintf(f,"%s",FG_RED); break; case '2': sprintf(f,"%s",FG_GREEN); break; case '3': sprintf(f,"%s",FG_BROWN); break; case '4': sprintf(f,"%s",FG_BLUE); break; case '5': sprintf(f,"%s",FG_MAGENTA); break; case '6': sprintf(f,"%s",FG_CYAN); break; case '7': sprintf(f,"%s",FG_LT_GRAY); break; case '8': sprintf(f,"%s",FG_DK_GRAY); break; case '9': sprintf(f,"%s",FG_LT_RED); break; default: sprintf(f,"%s",FG_DK_GRAY); break; } break; case '1': switch(code[3]) { /* 10-15 */ case '0': sprintf(f,"%s",FG_LT_GREEN); break; case '1': sprintf(f,"%s",FG_YELLOW); break; case '2': sprintf(f,"%s",FG_LT_BLUE); break; case '3': sprintf(f,"%s",FG_LT_MAGENTA); break; case '4': sprintf(f,"%s",FG_LT_CYAN); break; case '5': sprintf(f,"%s",FG_WHITE); break; default: sprintf(f,"%s",FG_LT_GREEN); break; } break; default : sprintf(f,"%s",FG_LT_RED); break; } strcat(m,b); /* add back ground */ strcat(m,f); /* add foreground */ return(m); }
2.796875
3
2024-11-18T21:19:33.889028+00:00
2021-08-27T09:54:42
dd4145bc3bf931ea9c878ec05516da9159c9de3d
{ "blob_id": "dd4145bc3bf931ea9c878ec05516da9159c9de3d", "branch_name": "refs/heads/main", "committer_date": "2021-08-27T09:54:42", "content_id": "852e68c369cf0641e3e3aa0fc84468cccb8c6100", "detected_licenses": [ "MIT" ], "directory_id": "d344dfc90ec17c7d1d3f57f880d200f511357dec", "extension": "h", "filename": "LinkedList.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 398505498, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 176, "license": "MIT", "license_type": "permissive", "path": "/LinkedList.h", "provenance": "stackv2-0128.json.gz:319199", "repo_name": "amulya00/compression", "revision_date": "2021-08-27T09:54:42", "revision_id": "3880f75bae525b8be82435122e6e0d5cbcc3ee3a", "snapshot_id": "5960b85457630057199c944f9eff98283830f17b", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/amulya00/compression/3880f75bae525b8be82435122e6e0d5cbcc3ee3a/LinkedList.h", "visit_date": "2023-07-13T09:37:25.975199" }
stackv2
struct List { int pos; List *next; List(){ pos = -1; next = NULL; } List(int pos){ this->pos = pos; next = NULL; } };
2.484375
2
2024-11-18T21:19:34.565958+00:00
2019-12-17T10:48:22
afa05d7b3fd7552eb40b7b120edd9229629875d6
{ "blob_id": "afa05d7b3fd7552eb40b7b120edd9229629875d6", "branch_name": "refs/heads/master", "committer_date": "2019-12-17T10:48:22", "content_id": "c36dcb35aefdca2a3fea3fc4818541630d3ed5bd", "detected_licenses": [], "directory_id": "9c3bb98eb9d0a587a302bdfa811f7b5c6a5a0a37", "extension": "c", "filename": "LeetCode_155_425.c", "fork_events_count": 0, "gha_created_at": "2019-10-08T10:50:41", "gha_event_created_at": "2019-12-17T10:48:24", "gha_language": "Java", "gha_license_id": "Apache-2.0", "github_id": 213617423, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2835, "license": "", "license_type": "permissive", "path": "/Week 2/id_425/LeetCode_155_425.c", "provenance": "stackv2-0128.json.gz:319588", "repo_name": "chenlei65368/algorithm004-05", "revision_date": "2019-12-17T10:48:22", "revision_id": "60e9ef1051a1d0441ab1c5484a51ab77a306bf5b", "snapshot_id": "842db9d9017556656aef0eeb6611eec3991f6c90", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/chenlei65368/algorithm004-05/60e9ef1051a1d0441ab1c5484a51ab77a306bf5b/Week 2/id_425/LeetCode_155_425.c", "visit_date": "2020-08-07T23:09:30.548805" }
stackv2
/* * @lc app=leetcode.cn id=155 lang=c * * [155] 最小栈 * * https://leetcode-cn.com/problems/min-stack/description/ * * algorithms * Easy (50.26%) * Likes: 302 * Dislikes: 0 * Total Accepted: 50.1K * Total Submissions: 99.6K * Testcase Example: '["MinStack","push","push","push","getMin","pop","top","getMin"]\n' + '[[],[-2],[0],[-3],[],[],[],[]]' * * 设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。 * * * push(x) -- 将元素 x 推入栈中。 * pop() -- 删除栈顶的元素。 * top() -- 获取栈顶元素。 * getMin() -- 检索栈中的最小元素。 * * * 示例: * * MinStack minStack = new MinStack(); * minStack.push(-2); * minStack.push(0); * minStack.push(-3); * minStack.getMin(); --> 返回 -3. * minStack.pop(); * minStack.top(); --> 返回 0. * minStack.getMin(); --> 返回 -2. * * */ // @lc code=start // szh 2019-10-23 #define MAXSIZE 1600 typedef struct { int *data; int top; } MinStack; /** initialize your data structure here. */ MinStack* minStackCreate() { MinStack *s = (MinStack*)malloc( sizeof(MinStack)); s->data = (int *)malloc(MAXSIZE * sizeof(int)); s->top =-1; return s; } void minStackPush(MinStack* obj, int x) { if (obj -> top == MAXSIZE -1); else { if (obj ->top == -1){ obj-> top++; obj->data[obj->top++] = x; obj->data[obj->top] = x; } else{ //栈顶元素为当前栈中最小值,第二元素才为正常入栈的栈顶元素,即每加入一个元素即需占用两个位置。 int temp = obj->data[obj->top++]; obj->data[obj->top++] = x; obj->data[obj->top] = x<temp? x:temp; } } } void minStackPop(MinStack* obj) { if(obj->top == -1); else obj->top -= 2; } int minStackTop(MinStack* obj) { if(obj->top == -1) return; return obj->data[(obj->top)-1]; } int minStackGetMin(MinStack* obj) { if(obj->top == -1) return; return obj->data[obj->top]; } void minStackFree(MinStack* obj) { free(obj->data); obj->data = NULL; free(obj); obj = NULL;; } /** * Your MinStack struct will be instantiated and called as such: * MinStack* obj = minStackCreate(); * minStackPush(obj, x); * minStackPop(obj); * int param_3 = minStackTop(obj); * int param_4 = minStackGetMin(obj); * minStackFree(obj); */ /** * Your MinStack struct will be instantiated and called as such: * MinStack* obj = minStackCreate(); * minStackPush(obj, x); * minStackPop(obj); * int param_3 = minStackTop(obj); * int param_4 = minStackGetMin(obj); * minStackFree(obj); */ // @lc code=end
3.359375
3
2024-11-18T21:46:43.093824+00:00
2017-11-13T02:52:40
3f83eecf0f891d4debfe36552710024243bea559
{ "blob_id": "3f83eecf0f891d4debfe36552710024243bea559", "branch_name": "refs/heads/master", "committer_date": "2017-11-13T02:52:40", "content_id": "ba532ab9a5722bd07f8d408d097cc60f65d7fe1d", "detected_licenses": [ "MIT" ], "directory_id": "cf0c4330946dc0542014719873248983617e2c88", "extension": "h", "filename": "LEDs.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 82721228, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 878, "license": "MIT", "license_type": "permissive", "path": "/libraries/LEDs/LEDs.h", "provenance": "stackv2-0130.json.gz:34221", "repo_name": "kekedoujia/lightOS", "revision_date": "2017-11-13T02:52:40", "revision_id": "0dd354aa5c2865a29df049b29e50d9dd502f27cb", "snapshot_id": "a4963a9bcf5d4436eb3016f5c6051731050e52af", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/kekedoujia/lightOS/0dd354aa5c2865a29df049b29e50d9dd502f27cb/libraries/LEDs/LEDs.h", "visit_date": "2021-01-20T13:55:24.797212" }
stackv2
#pragma once #ifndef __LED_DRIVER__ #define __LED_DRIVER__ #if ARDUINO >= 100 #include <Arduino.h> #include "avr/pgmspace.h" // new include #else #include <WProgram.h> #include "avr/pgmspace.h" // new include #endif #include "TrapperConfig.h" #ifndef MAX_LED_NUMBER #define MAX_LED_NUMBER 5 #endif #define LED_FUNCTION_IDEL 0 #define LED_FUNCTION_ON 1 #define LED_FUNCTION_BLINK 3 typedef struct { int led; char status; char function; unsigned long interval; unsigned long shift_time; unsigned long expire; unsigned long start_time; } LED_Type; void LED_init(); int LED_run(); int LED_add(int led); int LED_blink(int led, unsigned long interval, int sync, unsigned long expire); int LED_status(int led); int LED_on(int led, unsigned long expire); int LED_off(int led); void LED_offAll(); #endif // !__LED_DRIVER__
2.0625
2
2024-11-18T21:46:43.316848+00:00
2020-07-30T18:30:14
398fdcb7e465bb63992e49ca6190440db5779460
{ "blob_id": "398fdcb7e465bb63992e49ca6190440db5779460", "branch_name": "refs/heads/master", "committer_date": "2020-07-30T18:30:14", "content_id": "d1cc962756b5c965bdff9f1ddffbd3fb0e87a82e", "detected_licenses": [ "MIT" ], "directory_id": "8ed882ef52cd9ff8cba68b0dbf1b06581c5965de", "extension": "h", "filename": "arm_gicv3.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": 799, "license": "MIT", "license_type": "permissive", "path": "/devices/interrupt-controller/arm-gicv3/arm_gicv3.h", "provenance": "stackv2-0130.json.gz:34609", "repo_name": "lzwgucas/popcorn", "revision_date": "2020-07-30T18:30:14", "revision_id": "6bc187ad041e0030ead3520ee5e823fb60437848", "snapshot_id": "4326d4f40e2af54d2b0f0e3c19caf40362e95ada", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/lzwgucas/popcorn/6bc187ad041e0030ead3520ee5e823fb60437848/devices/interrupt-controller/arm-gicv3/arm_gicv3.h", "visit_date": "2022-11-28T18:11:48.282174" }
stackv2
/* * Copyright (c) 2020 Sekhar Bhattacharya * * SPDX-License-Identifier: MIT */ #ifndef _ARM_GICV3_H_ #define _ARM_GICV3_H_ #include <sys/types.h> #include <kernel/irq_types.h> typedef struct { uintptr_t gicd_base; uintptr_t gicr_base; } arm_gicv3_t; extern irq_controller_dev_ops_t arm_gicv3_ops; #define ARM_GICV3_SPURIOUS_IRQ_ID (1023) void arm_gicv3_init(void *data); void arm_gicv3_enable_irq(void *data, irq_id_t id, irq_priority_t priority, irq_type_t type); void arm_gicv3_disable_irq(void *data, irq_id_t id); irq_id_t arm_gicv3_get_pending_irq(void *data); irq_id_t arm_gicv3_ack_irq(void *data); void arm_gicv3_end_irq(void *data, irq_id_t id); void arm_gicv3_done_irq(void *data, irq_id_t id); void arm_gicv3_clr_irq(void *data, irq_id_t id); #endif // _ARM_GICV3_H_
2.109375
2
2024-11-18T21:46:43.468262+00:00
2018-01-01T21:01:51
aba35a8d4ae7c297d91c0653245a5b478e16bca7
{ "blob_id": "aba35a8d4ae7c297d91c0653245a5b478e16bca7", "branch_name": "refs/heads/master", "committer_date": "2018-01-01T21:01:51", "content_id": "32d71c45c699b4a66ca65767112337cf6104558e", "detected_licenses": [ "MIT" ], "directory_id": "cb151d839e29ab8535334572b6c808b41045fead", "extension": "c", "filename": "toggle.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 84684186, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1551, "license": "MIT", "license_type": "permissive", "path": "/toggle.c", "provenance": "stackv2-0130.json.gz:34741", "repo_name": "snapfinger/retinal-seg", "revision_date": "2018-01-01T21:01:51", "revision_id": "8c464b9ca284cd5cd5a0a81099535eab8d9b7899", "snapshot_id": "22c858c6820e35607ca90cc7939d28a6d85f909e", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/snapfinger/retinal-seg/8c464b9ca284cd5cd5a0a81099535eab8d9b7899/toggle.c", "visit_date": "2021-03-27T17:35:00.880736" }
stackv2
/* implement the toggle mapping filter for gray-scale image toggle mapping: based on comparison between the input image g and its opening y and closing f h(x)=[TM(g)](x) =f b1 (g)(x), if f b1 (g)(x)-g(x)<=g(x)-f b2 (g)(x) or y b2 (g)(x), if f b1 (g)(x)-g(x)>g(x)-f b2 (g)(x) y b1 -> opening with structuring element b1 f b2 -> closing with structuring element b2 */ #include "VisXV4.h" /* VisX structure include file */ #include "Vutil.h" /* VisX utility header files */ #include <stdbool.h> VXparam_t par[] = { { "if=", 0, "opening input"}, { "ig=", 0, "closing input"}, { "bf=", 0, "original image"}, { "of=", 0, " output file"}, { 0, 0, 0} }; #define OPEN par[0].val #define CLOSE par[1].val #define ORIGIN par[2].val #define OVAL par[3].val main(argc, argv) int argc; char *argv[]; { Vfstruct (im); /* i/o image structure */ Vfstruct (tm); /* temp image structure */ Vfstruct (im_op); Vfstruct (im_cl); VXparse(&argc, &argv, par); Vfread(&im,ORIGIN); Vfread(&im_op,OPEN); Vfread(&im_cl,CLOSE); Vfembed(&tm,&im,0,0,0,0); //for toggle map output int y,x;//image index for(y=im.ylo;y<=im.yhi;y++){ for(x=im.xlo;x<=im.xhi;x++){ if(im_cl.u[y][x]-im.u[y][x]<=im.u[y][x]-im_op.u[y][x]){ tm.u[y][x]=im_cl.u[y][x]; }else{ tm.u[y][x]=im_op.u[y][x]; } } } fprintf(stderr,"toggle mapping filter done...\n"); Vfwrite(&tm, OVAL); exit(0); }
2.65625
3
2024-11-18T21:46:43.781372+00:00
2017-05-31T17:01:15
6a92a5bbc1b9dd2aea5bd6472cb6c7b30897c56a
{ "blob_id": "6a92a5bbc1b9dd2aea5bd6472cb6c7b30897c56a", "branch_name": "refs/heads/master", "committer_date": "2017-05-31T17:01:15", "content_id": "bdab133977c0f6b0dbda3f457b9d1ee85b4f94e0", "detected_licenses": [ "MIT" ], "directory_id": "1aca3804016c47c14f5c68a502a69341a67b71b1", "extension": "c", "filename": "Ohmmeter.c", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 92945884, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5764, "license": "MIT", "license_type": "permissive", "path": "/code/Ohmmeter.c", "provenance": "stackv2-0130.json.gz:35003", "repo_name": "Sherbieny/Ohmmeter-Pi", "revision_date": "2017-05-31T17:01:15", "revision_id": "0e8f3880105fbd60185318a9b300f85ff57c64a8", "snapshot_id": "b897035019fd29947ed280982b775d5e82c06841", "src_encoding": "UTF-8", "star_events_count": 3, "url": "https://raw.githubusercontent.com/Sherbieny/Ohmmeter-Pi/0e8f3880105fbd60185318a9b300f85ff57c64a8/code/Ohmmeter.c", "visit_date": "2021-01-23T04:58:49.177876" }
stackv2
/* * Practice: talking with ADC through I2C using dev/i2c.h * NOTE: In the schematic, it is said that the communication is through 4 bytes as follows: * 1) Byte 1: Slave select, contains 7bit slave select address and 1bit for read/write flag * 2) Byte 2: Pointer register byte (00 conversion, 01 config) * 3) Byte 3 & 4: config register bytes * more info regarding ADS1015 ADC device can be found in: https://cdn-shop.adafruit.com/datasheets/ads1015.pdf specially * from page 13 onwards * * But we do not need the first Byte as it is already covered by using write() and read() functions * */ #include <linux/i2c-dev.h> #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <fcntl.h> #include <sys/ioctl.h> #include <unistd.h> #include <inttypes.h> #include <math.h> #define R1_10K 10000 //10K resistance #define R1_100K 100000 //20K resistance #define R1_1M 1000000 //30K resistance #define V_IN 3.29 //Raspberry PI voltage #define ADDR 0x48 //This is the ADDR of ADS1015 according to i2cdetect, according to ADS1015 schematic page 14 Table 5, if //the ADDR pin is connected to GND, SLAVE address is 1001000 which is 0x48 int main(){ //Variables declarations int file; //file handler int adapter_nr = 1; //The i2c adapter we will talk to, in our case its i2c-1 char filename[20]; //The string containing the device name (/dev/i2c-1) int16_t result; // store the 16bit representation of the data read float voltage, resistance = 0.0; int read_check, write_check = 0; //error checking variables uint8_t write_buf[3]; //The writing buffer used to write the 3 bytes to the device, byte1: pointer register //byte2: bits[15-8] of the config register, byte3: bits[7-0] of the config register uint8_t read_buf[2]; //The reading buffer used to read from the ADS data register float bit_v = 6.144 / 2048; //Converter from binary to base10 decimal with respect to //the chosen gain amplifier (PGA = 6.144V) //Adding the adapter number to the device name, this step can be minimized by just writing a string "/dev/i2c-1/" //in the open function below replacing the filename array -- but I used it here for practice as it was used in //the Kernel.org dev-interface example https://www.kernel.org/doc/Documentation/i2c/dev-interface snprintf(filename, 19, "/dev/i2c-%d", adapter_nr); file = open(filename, O_RDWR);//opening for reading and writing if(file < 0){ printf("Error #1: error when opening file\n"); exit(1); } //Using ioctl - control device function http://man7.org/linux/man-pages/man2/ioctl.2.html //to specify with which address in the device we are going to communicate to int ioc; ioc = ioctl(file, I2C_SLAVE, ADDR); if(ioc < 0){ printf("Error #2: error when using ioctl\n"); exit(1); } //To do a single-shot conversion we send the configuration bytes 11010001 00000011 to config register at address 00000001 //Tables 6, 7, 8, and 9 explain these bits write_buf[0] = 1; // 00000001 points to the config register write_buf[1] = 0xD1; // writing 11010001 in second byte (tried 000 PGA for 6.144V gain) write_buf[2] = 0x03; // writing 00000011 in third byte read_buf[0] = 0; // initialize the reading buffer read_buf[1] = 0; //Starting the conversation: //Writing to ADS1015 write_check = write(file, write_buf, 3); //write to file the write_buf content, and write 3 bytes if(write_check != 3){ printf("Error #3: error when writing to device\n"); exit(1); } //Now we keep checking the OS bit (bit 15) which tells us if the device is doing a conversion or not //In reading mode, 0 = device is performing conversion, 1 = device not performing conversion while((read_buf[0] & 0x80) == 0){ // ANDing with 0x80 (10000000) to check bit 15 read_check = read(file, read_buf, 2); //Keep checking until bit 15 changes to 1, meanining conversion stopped if(read_check != 2){ printf("Error #4: error while reading data\n"); exit(1); } } //Now that the device finished conversion, we can start reading the data from ADS1015 //First change the pointer register to 0 which is the address of the conversion register, to read from it write_buf[0] = 0; write_check = write(file, write_buf, 1); if(write_check != 1){ printf("Error#5: error while writing to pointer register\n"); exit(1); } //Now we read the data that was converted read_check = read(file, read_buf, 2); //read 2 bytes from file(conv register) into read_buf if(read_check != 2){ printf("Error#6: error while reading the converted data\n"); exit(1); } //Combine the 2bytes into a 16bit integer result = read_buf[0] << 8 | read_buf[1]; //shift first byte by 8 bits and OR the second byte with the rest result = result >> 4; //It was mentioned in a driver that ADS1015 should be also shifted 4 bytes as it is 12bits if (result > 0x07FF) { // negative number - extend the sign to 16th bit result |= 0xF000; } //Printing Raw data for inspection // printf("The Raw Data in HEX is: %x\n\n", result); //Print the result to terminal // printf("Voltage Reading %f (V) \n", (float)result*bit_v); /////////////////////////////////////////////////////////// //saving the voltage in V format voltage = (float) result * bit_v; //Calculating R2 for 10K resistnce resistance = R1_10K * (1 / ((V_IN / voltage) - 1)); printf("\n================================Analysis==========================================\n\n"); printf("|\tVin\t|\tVout\t|\tR1\t\t|\tR2 Result\t|\n\n"); printf("|\t3.3 V\t|\t%.2f V\t|\t%d ohms\t|\t%.2f ohms\t|\n",voltage, R1_10K, resistance); /////////////////////////////////////////////////////////// //close the connection close(file); printf("\n\nEnd of Program\n"); return 0; }
2.9375
3
2024-11-18T21:46:43.926682+00:00
2016-09-20T10:11:22
57624407f4a9258e6d9ef878575ab0e4b8644aab
{ "blob_id": "57624407f4a9258e6d9ef878575ab0e4b8644aab", "branch_name": "refs/heads/master", "committer_date": "2016-09-20T10:11:22", "content_id": "53279c9c0471348903e8c19b810a502ffd76b51d", "detected_licenses": [ "Apache-2.0" ], "directory_id": "7f5937c840ea0a0a33270040b15b1ec882422c87", "extension": "c", "filename": "confound_accent.c", "fork_events_count": 2, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 39277782, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1929, "license": "Apache-2.0", "license_type": "permissive", "path": "/mud/magic/obj/confound_accent.c", "provenance": "stackv2-0130.json.gz:35262", "repo_name": "shentino/simud", "revision_date": "2016-09-20T10:11:22", "revision_id": "644b7d4f56bf8d4695442b8efcfd56e0a561fe21", "snapshot_id": "706fcaad7ca5dd87277e3788592144b0d803476d", "src_encoding": "UTF-8", "star_events_count": 3, "url": "https://raw.githubusercontent.com/shentino/simud/644b7d4f56bf8d4695442b8efcfd56e0a561fe21/mud/magic/obj/confound_accent.c", "visit_date": "2021-01-17T14:09:07.943177" }
stackv2
#include <object.h> #define V ({ 'a', 'e', 'i', 'o', 'u', 'w', 'y' }) #define C ({ 'b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'x', 'z' }) int duration; int original_duration; string query_name() { return "confound_object"; } int query_degree() { int x = 100 * duration / original_duration; if ( x > 50 ) x = 100 - x; if ( x < 10 ) return 10; if ( x < 40) return (x-10) * 3 + 10; return 100; } void set_duration(int x) { original_duration = duration = x; } void set_victim(object who) { move(who); who->set_env_var("accent",explode(object_name(),"#")[0]); call_out("do_tick",2); } void do_tick() { remove_call_out("do_tick"); duration -= 2; if( duration < 1 ) { destruct(this_object()); } else { if( random(1000) < query_degree() ) { string *msgs = ({ "Your mind is clouded.", "You feel confused.", "You are having trouble remembering things.", "You have the feeling that you just forgot something.", "You are confused.", "You can't remember..." }); msg_object(environment(this_object()), msgs[random(sizeof(msgs))] ); } } call_out("do_tick",2); } string destructor( object ob ) { msg_object(environment(this_object()), "~CBRTYour mind has become clear again.~CDEF"); environment(this_object())->remove_env_var("accent"); return 0; } string garble(string arg) { string out = ""; object ob = present_clone(this_object(), this_player()); int x, degree = 100; if( !ob ) debug(this_player()->query_name()+" is garbled.","magic"); else degree = ob->query_degree(); foreach( x in lower_case(arg) ) { if( random(100) > degree ) { out += to_string( ({ x }) ); continue; } if( member(V, x) != -1 ) out += to_string( ({ V[random(7)] }) ); else if( member(C, x) != -1 ) out += to_string( ({ C[random(19)] }) ); else if( out[<1] != ' ' ) out += " "; } return out; }
2.15625
2
2024-11-18T21:46:44.292744+00:00
2017-03-26T15:42:17
6e17edd11f507b938b3a97de7253da8ab3fd46bc
{ "blob_id": "6e17edd11f507b938b3a97de7253da8ab3fd46bc", "branch_name": "refs/heads/master", "committer_date": "2017-03-26T15:42:17", "content_id": "fee3294033a5e296b1d7f3bafefda3fd614744de", "detected_licenses": [ "MIT" ], "directory_id": "37debf972f2cb5d4390e21ddcd2479d9f0d8c982", "extension": "c", "filename": "1-16.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 65079216, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1767, "license": "MIT", "license_type": "permissive", "path": "/1/1-16.c", "provenance": "stackv2-0130.json.gz:35523", "repo_name": "weezybusy/KnR2", "revision_date": "2017-03-26T15:42:17", "revision_id": "3c8acc4f327afcc52ce8e41f534424a8c8f6fa4b", "snapshot_id": "2065311bae3d1992a8c9ef3421c8560a8ac8722f", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/weezybusy/KnR2/3c8acc4f327afcc52ce8e41f534424a8c8f6fa4b/1/1-16.c", "visit_date": "2020-05-30T23:24:14.582563" }
stackv2
/* * Exercise 1-16 * * Revise the main routine of the longest-line program so it will * correctly print the length of arbitrary long input lines, and * as much as possible of the text. */ #include <stdio.h> #define MAXLINE 15 int getline(char line[], int maxline); void copy(char to[], char from[]); int main(void) { int c; int count; int len; int max; char line[MAXLINE]; char longest[MAXLINE]; max = 0; count = 1; printf("%d) ", count); while ((len = getline(line, MAXLINE)) > 0) { if (len == (MAXLINE - 1) && line[MAXLINE - 2] != '\n') while ((c = getchar()) != EOF && c != '\n') ++len; if (len > max) { max = len; copy(longest, line); } printf("%d) ", ++count); } printf("---\n"); if (max > 0) { printf("The longest line is %d characters long:\n", max); printf("> %s", longest); /* print new line if longest line doesn't have it */ if (max >= (MAXLINE - 1) && longest[MAXLINE - 2] != '\n') printf("...\n"); } return 0; } int getline(char line[], int maxline) { int c; int i; for (i = 0; i < maxline - 1 && (c = getchar()) != EOF && c != '\n'; ++i) line[i] = c; if (c == '\n') { line[i] = c; ++i; } line[i] = '\0'; return i; } void copy(char to[], char from[]) { int i; i = 0; while ((to[i] = from[i]) != '\0') ++i; }
3.6875
4
2024-11-18T21:46:44.764805+00:00
2022-04-08T13:00:16
111187e447d71dbc79caecb0713d0c4efe8ebb0e
{ "blob_id": "111187e447d71dbc79caecb0713d0c4efe8ebb0e", "branch_name": "refs/heads/master", "committer_date": "2022-04-08T13:00:16", "content_id": "7d0136ba64e358ec86a78d0e21d0203f027093fd", "detected_licenses": [ "MIT" ], "directory_id": "671fcacac1ef886a04f3dd07c14091a4df436471", "extension": "c", "filename": "zipfdist.c", "fork_events_count": 6, "gha_created_at": "2020-02-05T09:55:56", "gha_event_created_at": "2023-02-16T15:20:43", "gha_language": "Python", "gha_license_id": "MIT", "github_id": 238417772, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 12584, "license": "MIT", "license_type": "permissive", "path": "/query/datagen/zipfdist.c", "provenance": "stackv2-0130.json.gz:36165", "repo_name": "Henning1/dogqc", "revision_date": "2022-04-08T13:00:16", "revision_id": "c92f3a69dc249f5f0a937e9e422636189877a1df", "snapshot_id": "cb80d7a7687d686ab3a0e694f2b909fac0d78cd6", "src_encoding": "UTF-8", "star_events_count": 20, "url": "https://raw.githubusercontent.com/Henning1/dogqc/c92f3a69dc249f5f0a937e9e422636189877a1df/query/datagen/zipfdist.c", "visit_date": "2022-05-02T03:12:11.916448" }
stackv2
//=================== file = genzipf.c ====================================== //= Program to generate data for join experimentation = //=-------------------------------------------------------------------------= //= Build: gcc zipfgen.c -lm -std=c99 -o zipfgen = //= Execute: ./zipfgen --mode 1 --nbuild 10000000 --nprobe 10000000 \ = //= --zalpha 0.75 --zn 10000000 --zsplit 1 = //=-------------------------------------------------------------------------= //= Execute: genzipf = //=========================================================================== //= adaptation: Henning Funke Oct '18 = //= TU Dortmund University = //=-------------------------------------------------------------------------= //= based on: = //= Author: Kenneth J. Christensen = //= University of South Florida = //= WWW: http://www.csee.usf.edu/~christen = //= Email: christen@csee.usf.edu = //= History: KJC (11/16/03) - Genesis (from genexp.c) = //=========================================================================== //----- Include files ------------------------------------------------------- #include <assert.h> // Needed for assert() macro #include <stdio.h> // Needed for printf() #include <stdlib.h> // Needed for exit() and ato*() #include <math.h> // Needed for pow() #include <time.h> #include <getopt.h> #include <stdint.h> #include <float.h> //----- Constants ----------------------------------------------------------- #define FALSE 0 // Boolean false #define TRUE 1 // Boolean true typedef struct { double alpha; int n; double c; double *sum_probs; int *labels; } zipf_dist; //----- Function prototypes ------------------------------------------------- int zipf(double alpha, int n); // Returns a Zipf random variable double rand_val(); zipf_dist* generate_zipf_dist ( double alpha, int n ); int sample_zipf_dist ( zipf_dist* d ); void free_zipf_dist ( zipf_dist* d); void random_permutation ( int* data, int n ); //===== Main program ======================================================== int main (int argc, char **argv) { // io vars FILE *fp_r; // File pointer to output file FILE *fp_s; // File pointer to output file // parameters double alpha; // Alpha parameter double n; // N parameter int num_build; // Number of values int num_probe; // Number of values int num_split; // Number of values int mode; // tmp vars int zipf_rv; // Zipf random variable int i; // Loop counter srand ( time ( NULL ) ); // get command line options int c; while (1) { static struct option long_options[] = { /* These options set a flag. */ {"mode", required_argument, 0, 'm'}, {"nbuild", required_argument, 0, 'b'}, {"nprobe", required_argument, 0, 'p'}, {"zalpha", required_argument, 0, 'a'}, {"zn", required_argument, 0, 'n'}, {"zsplit", required_argument, 0, 's'}, {"seed", required_argument, 0, 'r'}, {0, 0, 0, 0} }; /* getopt_long stores the option index here. */ int option_index = 0; c = getopt_long (argc, argv, "m:b:p:a:n:s:r:", long_options, &option_index); /* Detect the end of the options. */ if (c == -1) break; switch (c) { //printf("%s\n", c); case 0: /* If this option set a flag, do nothing else now. */ if (long_options[option_index].flag != 0) break; case 'm': mode = atoi(optarg); break; case 'b': num_build = atoi(optarg); break; case 'p': num_probe = atoi(optarg); break; case 'a': alpha = atof(optarg); break; case 'n': n = atof(optarg); break; case 's': num_split = atoi(optarg); break; case 'r': srand ( atoi(optarg) ); break; case '?': printf("mode ( short m ) - 1: zipf distributed build. 2: primary key build. 3: build with 32 instances of each key 4: build with 8 instances of each key.\n"); printf("nbuild ( short b ) - number of build elements\n"); printf("nprobe ( short p ) - number of probe elements\n"); printf("zalpha ( short a ) - alpha for zipf distributions\n"); printf("zn ( short n ) - N for zipf distributions\n"); printf("zsplit ( short s ) - number of zipf distributions\n"); printf("seed ( short r ) - random seed (time based if none given)\n"); return 0; default: abort (); } } // create/open the files fp_r = fopen("r_build.tbl", "w"); if (fp_r == NULL) { printf("ERROR in creating output file (%s) \n", "r_build.tbl"); exit(1); } fp_s = fopen("s_probe.tbl", "w"); if (fp_s == NULL) { printf("ERROR in creating output file (%s) \n", "s_probe.tbl"); exit(1); } int* build = malloc ( sizeof ( int ) * num_build ); int* probe = malloc ( sizeof ( int ) * num_probe ); //1: zipf distributed build. 2: primary key build. 3: build with 32 instances of each key 4: build with 8 instances of each key switch ( mode ) { case 1: ; // generate num_split distributions zipf_dist** ds = malloc ( sizeof ( zipf_dist* ) * num_split ); for ( int d=0; d<num_split; d++) { ds[d] = generate_zipf_dist ( alpha, n ); } // Generate and output zipf random variables for (i=0; i<num_build; i++) { zipf_rv = sample_zipf_dist ( ds [ i% num_split ] ); fprintf(fp_r, "%d|%i|\n", zipf_rv, i); } // Generate and output dense values for (i=0; i<num_probe; i++) { fprintf(fp_s, "%i|%i|\n", i, i); } // free distributions for ( int d=0; d<num_split; d++) { free_zipf_dist ( ds[d] ); } free ( ds ); break; case 2: // Generate build data for (i=0; i<num_build; i++) { build[i] = i; } random_permutation ( build, num_build ); // Output build data for (i=0; i<num_build; i++) { fprintf(fp_r, "%i|%i|\n", build[i], i); } // Output probe data for (i=0; i<num_probe; i++) { fprintf(fp_s, "%i|%i|\n", i, i); } break; case 3: { // Generate build data i = 0; int p = 0; while ( i < num_build ) { int j=0; while ( j < 32 & i < num_build ) { build[i] = p; j++; i++; } p++; } random_permutation ( build, num_build ); // Output build data for (i=0; i<num_build; i++) { fprintf(fp_r, "%i|%i|\n", build[i], i); } // Output probe data //for (i=0; i<num_probe; i++) { for (i=0; i<p; i++) { //fprintf(fp_s, "%i|%i|\n", rand() % num_probe, i); fprintf(fp_s, "%i|%i|\n", i, i); } } break; case 4: { // Generate build data i = 0; int p = 0; while ( i < num_build ) { int j=0; while ( j < 8 & i < num_build ) { build[i] = p; j++; i++; } p++; } random_permutation ( build, num_build ); // Output build data for (i=0; i<num_build; i++) { fprintf(fp_r, "%i|%i|\n", build[i], i); } // Output probe data //for (i=0; i<num_probe; i++) { for (i=0; i<p; i++) { //fprintf(fp_s, "%i|%i|\n", rand() % num_probe, i); fprintf(fp_s, "%i|%i|\n", i, i); } } break; } free ( build ); free ( probe ); fclose(fp_r); fclose(fp_s); } void random_permutation ( int* data, int n ) { for (int i = 1; i < n; i++) { int j, t; j = rand() % (n-i) + i; t = data[j]; data[j] = data[i]; data[i] = t; // Swap i and j } } zipf_dist* generate_zipf_dist( double alpha, int n ) { zipf_dist* d = malloc ( sizeof(zipf_dist) ); d->sum_probs = malloc ( sizeof(double) * n ); d->labels = malloc ( sizeof(int) * n ); d->alpha = alpha; d->n = n; for (int i=1; i<=n; i++) d->c = d->c + (1.0 / pow((double) i, alpha)); d->c = 1.0 / d->c; // Compute normalization constant and probabilities d->sum_probs[0] = 0; d->labels[0] = 0; for (int i=1; i<=d->n; i++) { d->sum_probs[i] = d->sum_probs[i-1] + d->c / pow((double) i, d->alpha); d->labels[i]=i; } //random permutation of labels random_permutation ( d->labels, n ); return d; } int sample_zipf_dist ( zipf_dist* d ) { // Pull a uniform random number (0 < z < 1) double z; int low, high, mid, zipf_value; do { z = rand_val(); } while ((z == 0) || (z == 1)); // Map z to the value low = 1, high = d->n, mid; do { mid = floor((low+high)/2); if (d->sum_probs[mid] >= z && d->sum_probs[mid-1] < z) { zipf_value = d->labels[mid]; break; } else if (d->sum_probs[mid] >= z) { high = mid-1; } else { low = mid+1; } } while (low <= high); // Assert that zipf_value is between 1 and N if(!((zipf_value >=1) && (zipf_value <= d->n))) { printf("error zipf_value: %i, n: %i\n", zipf_value, d->n ); } assert((zipf_value >=1) && (zipf_value <= d->n)); return(zipf_value); } void free_zipf_dist ( zipf_dist* d) { free ( d->sum_probs ); free ( d->labels ); free ( d ); } //=========================================================================== //= Function to generate Zipf (power law) distributed random variables = //= - Input: alpha and N = //= - Output: Returns with Zipf distributed random variable = //=========================================================================== int zipf(double alpha, int n) { static int first = TRUE; // Static first time flag static double c = 0; // Normalization constant static double *sum_probs; // Pre-calculated sum of probabilities static int *labels; double z; // Uniform random number (0 < z < 1) int zipf_value; // Computed exponential value to be returned int i; // Loop counter int low, high, mid; // Binary-search bounds // Compute normalization constant on first call only if (first == TRUE) { for (i=1; i<=n; i++) c = c + (1.0 / pow((double) i, alpha)); c = 1.0 / c; sum_probs = malloc((n+1)*sizeof(*sum_probs)); labels = malloc((n+1)*sizeof(*labels)); sum_probs[0] = 0; labels[0] = 0; for (i=1; i<=n; i++) { sum_probs[i] = sum_probs[i-1] + c / pow((double) i, alpha); labels[i]=i; } //random permutation of labels int *perm = labels; for (int i = 1; i < n; i++) { int j, t; j = rand() % (n-i) + i; t = perm[j]; perm[j] = perm[i]; perm[i] = t; // Swap i and j } first = FALSE; } // Pull a uniform random number (0 < z < 1) do { z = rand_val(0); } while ((z == 0) || (z == 1)); // Map z to the value low = 1, high = n, mid; do { mid = floor((low+high)/2); if (sum_probs[mid] >= z && sum_probs[mid-1] < z) { zipf_value = labels[mid]; break; } else if (sum_probs[mid] >= z) { high = mid-1; } else { low = mid+1; } } while (low <= high); // Assert that zipf_value is between 1 and N if(!((zipf_value >=1) && (zipf_value <= n))) { printf("error zipf_value: %i, n: %i\n", zipf_value, n ); } assert((zipf_value >=1) && (zipf_value <= n)); return(zipf_value); } double rand_val() { double div = RAND_MAX; return (rand() / div); }
2.4375
2
2024-11-18T21:46:46.771922+00:00
2021-08-25T09:09:11
96765089789eb142e454af7c52da9f6246216bc5
{ "blob_id": "96765089789eb142e454af7c52da9f6246216bc5", "branch_name": "refs/heads/main", "committer_date": "2021-08-31T14:29:02", "content_id": "735fe8964de8b6069647169a3a4e56abe63a5274", "detected_licenses": [ "Zlib" ], "directory_id": "4cff9c9a205376f0bdd80412c2921ee502b2ceff", "extension": "h", "filename": "altrace_playback.h", "fork_events_count": 7, "gha_created_at": "2021-06-28T20:28:57", "gha_event_created_at": "2021-08-31T14:29:03", "gha_language": "C", "gha_license_id": "Zlib", "github_id": 381153775, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3792, "license": "Zlib", "license_type": "permissive", "path": "/altrace_playback.h", "provenance": "stackv2-0130.json.gz:36424", "repo_name": "icculus/altrace", "revision_date": "2021-08-25T09:09:11", "revision_id": "dd572d92b514e835f4bed7bbeb487baf47b9c4bb", "snapshot_id": "e85f3e745c473217f487fa7990fc7586835841b6", "src_encoding": "UTF-8", "star_events_count": 7, "url": "https://raw.githubusercontent.com/icculus/altrace/dd572d92b514e835f4bed7bbeb487baf47b9c4bb/altrace_playback.h", "visit_date": "2023-07-16T11:09:25.156666" }
stackv2
/** * alTrace; a debugging tool for OpenAL. * * Please see the file LICENSE.txt in the source's root directory. * * This file written by Ryan C. Gordon. */ #ifndef _INCL_ALTRACE_PLAYBACK_H_ #define _INCL_ALTRACE_PLAYBACK_H_ #include "altrace_common.h" // We assume we can cast the 64-bit values in the tracefile into pointers. // It's my (untested) belief that you can record on a 32-bit platform and // play it back on a 64-bit system, but not the other way around. #ifndef __LP64__ #error This currently expects a 64-bit target. 32-bits unsupported. #endif #ifdef __cplusplus extern "C" { #endif typedef struct CallstackFrame { void *frame; const char *sym; } CallstackFrame; typedef struct CallerInfo { CallstackFrame callstack[MAX_CALLSTACKS]; int num_callstack_frames; int numargs; uint32 threadid; uint32 trace_scope; uint32 wait_until; off_t fdoffset; void *userdata; } CallerInfo; MAP_DECL(device, ALCdevice *, ALCdevice *); MAP_DECL(context, ALCcontext *, ALCcontext *); MAP_DECL(devicelabel, ALCdevice *, char *); MAP_DECL(contextlabel, ALCcontext *, char *); MAP_DECL(source, ALuint, ALuint); MAP_DECL(buffer, ALuint, ALuint); MAP_DECL(sourcelabel, ALuint, char *); MAP_DECL(bufferlabel, ALuint, char *); MAP_DECL(stackframe, void *, char *); MAP_DECL(threadid, uint64, uint32); #define ENTRYPOINT(ret,name,params,args,numargs,visitparams,visitargs) void visit_##name visitparams; #include "altrace_entrypoints.h" void visit_al_error_event(void *userdata, const ALenum err); void visit_alc_error_event(void *userdata, ALCdevice *device, const ALCenum err); void visit_device_state_changed_int(void *userdata, ALCdevice *dev, const ALCenum param, const ALCint newval); void visit_context_state_changed_enum(void *userdata, ALCcontext *ctx, const ALenum param, const ALenum newval); void visit_context_state_changed_float(void *userdata, ALCcontext *ctx, const ALenum param, const ALfloat newval); void visit_context_state_changed_string(void *userdata, ALCcontext *ctx, const ALenum param, const ALchar *str); void visit_listener_state_changed_floatv(void *userdata, ALCcontext *ctx, const ALenum param, const uint32 numfloats, const ALfloat *values); void visit_source_state_changed_bool(void *userdata, const ALuint name, const ALenum param, const ALboolean newval); void visit_source_state_changed_enum(void *userdata, const ALuint name, const ALenum param, const ALenum newval); void visit_source_state_changed_int(void *userdata, const ALuint name, const ALenum param, const ALint newval); void visit_source_state_changed_uint(void *userdata, const ALuint name, const ALenum param, const ALuint newval); void visit_source_state_changed_float(void *userdata, const ALuint name, const ALenum param, const ALfloat newval); void visit_source_state_changed_float3(void *userdata, const ALuint name, const ALenum param, const ALfloat newval1, const ALfloat newval2, const ALfloat newval3); void visit_buffer_state_changed_int(void *userdata, const ALuint name, const ALenum param, const ALint newval); void visit_eos(void *userdata, const ALboolean okay, const uint32 wait_until); int visit_progress(void *userdata, const off_t current, const off_t total); const char *alcboolString(const ALCboolean x); const char *alboolString(const ALCboolean x); const char *alcenumString(const ALCenum x); const char *alenumString(const ALCenum x); const char *litString(const char *str); const char *ptrString(const void *ptr); const char *ctxString(ALCcontext *ctx); const char *deviceString(ALCdevice *device); const char *sourceString(const ALuint name); const char *bufferString(const ALuint name); int process_tracelog(const char *filename, void *userdata); #ifdef __cplusplus } #endif #endif // end of altrace_playback.h ...
2.046875
2
2024-11-18T21:46:47.108169+00:00
2020-10-20T19:44:54
7887e1735e48388013315dd779871dff5b9caeed
{ "blob_id": "7887e1735e48388013315dd779871dff5b9caeed", "branch_name": "refs/heads/master", "committer_date": "2020-10-20T19:44:54", "content_id": "e25d81d5d2843853fe26c9be0724c708d1aab6fd", "detected_licenses": [ "MIT" ], "directory_id": "11b6bf957f3c2b1cf08c217014bb7f69ec713d8f", "extension": "c", "filename": "Flash.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 31555633, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 10734, "license": "MIT", "license_type": "permissive", "path": "/Processor_Peripherals/TI_MSP430x5/Flash.c", "provenance": "stackv2-0130.json.gz:36683", "repo_name": "adamj537/Code-Library", "revision_date": "2020-10-20T19:44:54", "revision_id": "3073332ef69d1d0a80e1a3b7e58bb8f5a00cf59f", "snapshot_id": "abf02d159d78f62cc38732f6587c23864ca6299c", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/adamj537/Code-Library/3073332ef69d1d0a80e1a3b7e58bb8f5a00cf59f/Processor_Peripherals/TI_MSP430x5/Flash.c", "visit_date": "2021-05-23T06:21:50.367234" }
stackv2
//***************************************************************************** // // MSP430_Flash.c - Driver for the flashctl Module of the CC3200. // //***************************************************************************** #ifdef __MSP430_HAS_FLASH__ // Include this only if we have flash. #include <msp430.h> // required by development platform #include <stdbool.h> // defines "bool", "true", "false" #include <stdint.h> // defines standard data types #include "Bitlogic.h" // handy defines that make life easier #include "MSP430_Flash.h" // header for this driver //***************************************************************************** // //! \brief Erase a single segment of the flash memory. //! //! For devices like MSP430i204x, if the specified segment is the information //! flash segment, the FLASH_unlockInfo API must be called prior to calling //! this API. //! //! \param flash_ptr is the pointer into the flash segment to be erased //! //! \return None // //***************************************************************************** void FlashMemSegmentErase (uint8_t *flash_ptr) { FCTL3 = FWKEY; // Clear Lock bit. FCTL1 = FWKEY | ERASE; // Set Erase bit. *flash_ptr = 0; // Dummy write to erase flash seg. while (FCTL3 & BUSY); // Wait for BUSY bit to clear. FCTL1 = FWKEY; // Clear ERASE bit. FCTL3 = FWKEY + LOCK; // Set LOCK bit. } //***************************************************************************** // //! \brief Erase a single bank of the flash memory. //! //! This function erases a single bank of the flash memory. This API will //! erase the entire flash if device contains only one flash bank. //! //! \param flash_ptr is a pointer into the bank to be erased //! //! \return None // //***************************************************************************** void FlashMemBankErase (uint8_t *flash_ptr) { FCTL3 = FWKEY; // Clear Lock bit. while (FCTL3 & BUSY); // Wait for BUSY bit to clear. FCTL1 = FWKEY | MERAS; // Set MERAS bit. *flash_ptr = 0; // Dummy write to erase flash seg. while (FCTL3 & BUSY); // Wait for BUSY bit to clear. FCTL1 = FWKEY; // Clear MERAS bit. FCTL3 = FWKEY | LOCK; // Set LOCK bit. } //***************************************************************************** // //! \brief Erase all flash memory. //! //! This function erases all the flash memory banks. For devices like //! MSP430i204x, this API erases main memory and information flash memory if //! the FLASH_unlockInfo API was previously executed (otherwise the information //! flash is not erased). Also note that erasing information flash memory in //! the MSP430i204x impacts the TLV calibration constants located at the //! information memory. //! //! \param flash_ptr is a pointer into the bank to be erased //! //! \return None // //***************************************************************************** void FlashMemMassErase (uint8_t *flash_ptr) { FCTL3 = FWKEY; // Clear Lock bit. while (FCTL3 & BUSY); // Wait for BUSY bit to clear. FCTL1 = FWKEY | MERAS | ERASE; // Set MERAS bit. *flash_ptr = 0; // Dummy write to erase Flash seg. while (FCTL3 & BUSY); // Wait for BUSY bit to clear. FCTL1 = FWKEY; // Clear MERAS bit. FCTL3 = FWKEY | LOCK; // Set LOCK bit. } //***************************************************************************** // //! \brief Erase check of the flash memory //! //! This function checks bytes in flash memory to make sure that they are in an //! erased state (are set to 0xFF). //! //! \param flash_ptr is the pointer to the starting location of the erase check //! \param numberOfBytes is the number of bytes to be checked //! //! \return TRUE if bytes are erased; FALSE otherwise // //***************************************************************************** BOOL FlashMemEraseCheck (uint8_t *flash_ptr, uint16_t numberOfBytes) { uint16_t i; // counter BOOL result = TRUE; // return value for (i = 0; i < numberOfBytes; i++) // Loop through each byte. { if ((*(flash_ptr + i)) != 0xFF) // If the byte isn't 0xFF (erased)... { result = FALSE; // ...then we fail. } } return result; // Return result. } //***************************************************************************** // //! \brief Write data into the flash memory in byte format, pass by reference //! //! This function writes a byte array of size count into flash memory. Assumes //! the flash memory is already erased and unlocked. FlashCtl_segmentErase can //! be used to erase a segment. //! //! \param data_ptr is the pointer to the data to be written //! \param flash_ptr is the pointer into which to write the data //! \param count number of times to write the value //! //! \return None // //***************************************************************************** void FlashMemWrite8 (uint8_t *data_ptr, uint8_t *flash_ptr, uint16_t count) { FCTL3 = FWKEY; // Clear Lock bit. FCTL1 = FWKEY | WRT; // Enable byte/word write mode. while (count > 0) // For each byte... { while (FCTL3 & BUSY); // Wait for BUSY bit to clear. *flash_ptr++ = *data_ptr++; // Write to flash. count--; // Decrement the counter. } FCTL1 = FWKEY; // Clear WRT bit. FCTL3 = FWKEY | LOCK; // Set LOCK bit. } //***************************************************************************** // //! \brief Write data into the flash memory in 16-bit word format, pass by //! reference //! //! This function writes a 16-bit word array of size count into flash memory. //! Assumes the flash memory is already erased and unlocked. //! FlashCtl_segmentErase can be used to erase a segment. //! //! \param data_ptr is the pointer to the data to be written //! \param flash_ptr is the pointer into which to write the data //! \param count number of times to write the value //! //! \return None // //***************************************************************************** void FlashMemWrite16 (uint16_t *data_ptr, uint16_t *flash_ptr, uint16_t count) { FCTL3 = FWKEY; // Clear Lock bit. FCTL1 = FWKEY | WRT; // Enable byte/word write mode. while (count > 0) // For each byte... { while (FCTL3 & BUSY); // Wait for BUSY bit to clear. *flash_ptr++ = *data_ptr++; // Write to flash. count--; // Decrement the counter. } FCTL1 = FWKEY; // Clear WRT bit. FCTL3 = FWKEY | LOCK; // Set LOCK bit. } //***************************************************************************** // //! \brief Write data into the flash memory in 32-bit word format, pass by //! reference //! //! This function writes a 32-bit array of size count into flash memory. //! Assumes the flash memory is already erased and unlocked. //! FlashCtl_segmentErase can be used to erase a segment. //! //! \param data_ptr is the pointer to the data to be written //! \param flash_ptr is the pointer into which to write the data //! \param count number of times to write the value //! //! \return None // //***************************************************************************** void FlashMemWrite32 (uint32_t *data_ptr, uint32_t *flash_ptr, uint16_t count) { FCTL3 = FWKEY; // Clear Lock bit. FCTL1 = FWKEY | BLKWRT; // Enable long-word write. while (count > 0) // For each byte... { while (FCTL3 & BUSY); // Wait for BUSY bit to clear. *flash_ptr++ = *data_ptr++; // Write to Flash. count--; // Decrement the counter. } FCTL1 = FWKEY; // Clear BLKWRT bit. FCTL3 = FWKEY | LOCK; // Set LOCK bit. } //***************************************************************************** // //! \brief Check FlashCtl status to see if it is currently busy erasing or //! programming //! //! This function checks the status register to determine if the flash memory //! is ready for writing. //! //! \param mask FLASHCTL status to read //! Mask value is the logical OR of any of the following: //! - \b FLASHCTL_READY_FOR_NEXT_WRITE //! - \b FLASHCTL_ACCESS_VIOLATION_INTERRUPT_FLAG //! - \b FLASHCTL_PASSWORD_WRITTEN_INCORRECTLY //! - \b FLASHCTL_BUSY //! //! \return Logical OR of any of the following: //! - \b FlashCtl_READY_FOR_NEXT_WRITE //! - \b FlashCtl_ACCESS_VIOLATION_INTERRUPT_FLAG //! - \b FlashCtl_PASSWORD_WRITTEN_INCORRECTLY //! - \b FlashCtl_BUSY //! \n indicating the status of the FlashCtl // //***************************************************************************** uint8_t FlashMemStatus (uint8_t mask) { return (FCTL3 & mask); } //***************************************************************************** // //! \brief Locks the information flash memory segment A //! //! This function is typically called after an erase or write operation on the //! information flash segment is performed by any of the other API functions in //! order to re-lock the information flash segment. //! //! \return None // //***************************************************************************** void FlashMemLockInfoA (void) { //Disable global interrupts while doing RMW operation on LOCKA bit. uint16_t gieStatus; gieStatus = __get_SR_register() & GIE; //Store current SR register __disable_interrupt(); //Disable global interrupt //Set the LOCKA bit in FCTL3. //Since LOCKA toggles when you write a 1 (and writing 0 has no effect), //read the register, XOR with LOCKA mask, mask the lower byte //and write it back. FCTL3 = FWKEY + ((FCTL3 ^ LOCKA) & 0xFF); //Reinstate SR register to restore global interrupt enable status __bis_SR_register(gieStatus); } //***************************************************************************** // //! \brief Unlocks the information flash memory segment A //! //! This function must be called before an erase or write operation on the //! information flash segment A is performed by any of the other API functions. //! //! \return None // //***************************************************************************** void FlashMemUnlockInfoA (void) { //Disable global interrupts while doing RMW operation on LOCKA bit uint16_t gieStatus; gieStatus = __get_SR_register() & GIE; //Store current SR register __disable_interrupt(); //Disable global interrupt //Clear the LOCKA bit in FCTL3. //Since LOCKA toggles when you write a 1 (and writing 0 has no effect), //read the register, mask the lower byte, and write it back. FCTL3 = FWKEY + (FCTL3 & 0xFF); //Reinstate SR register to restore global interrupt enable status __bis_SR_register(gieStatus); } #endif
2.34375
2
2024-11-18T21:46:47.243017+00:00
2020-06-20T02:30:20
b891b5315dc973569312758f08753210276e7cd3
{ "blob_id": "b891b5315dc973569312758f08753210276e7cd3", "branch_name": "refs/heads/master", "committer_date": "2020-06-20T02:30:20", "content_id": "b445aac6613d98fe5c34996a34af339980e01945", "detected_licenses": [ "MIT" ], "directory_id": "8f809535473f3c1d924dc1be1dd23464ee4c3ae8", "extension": "h", "filename": "provider.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": 868, "license": "MIT", "license_type": "permissive", "path": "/provider.h", "provenance": "stackv2-0130.json.gz:36811", "repo_name": "iforking/GoUI", "revision_date": "2020-06-20T02:30:20", "revision_id": "57faf36312986f15354c3fa9cd54fed7371bcb29", "snapshot_id": "92aa672a9524e8221d2b3192348880ff9ac736a0", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/iforking/GoUI/57faf36312986f15354c3fa9cd54fed7371bcb29/provider.h", "visit_date": "2023-03-30T11:57:11.088288" }
stackv2
#ifndef _BRIDGE_ #define _BRIDGE_ #include "c/common.h" typedef enum MenuType { container, //just a container item for sub items custom, standard, separator } MenuType; typedef struct WindowSettings{ const char* title; const char* webDir; const char* index; const char* url; int left; int top; int width; int height; int resizable; int debug; } WindowSettings; typedef struct MenuDef{ const char* title; const char* action; const char* key; struct MenuDef* children; int childrenCount; MenuType menuType; } MenuDef; static MenuDef* allocMenuDefArray(int count) { if(count == 0) { return NULL; } return (MenuDef*)malloc(sizeof(MenuDef)*count); } static void addChildMenu(MenuDef* children, MenuDef child, int index) { children[index] = child; } #endif
2.171875
2
2024-11-18T21:46:49.841193+00:00
2021-05-01T12:52:45
0322df884b374b14b9a808eba61ad756702d21bd
{ "blob_id": "0322df884b374b14b9a808eba61ad756702d21bd", "branch_name": "refs/heads/main", "committer_date": "2021-05-01T12:52:45", "content_id": "d4e3ab85fc68745eabd08f2105a77c86c40c3826", "detected_licenses": [ "Apache-2.0" ], "directory_id": "c435377d1827f631a745496bac9be94f3d5b7e02", "extension": "c", "filename": "task004.3.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 331269598, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 276, "license": "Apache-2.0", "license_type": "permissive", "path": "/task004.3.c", "provenance": "stackv2-0130.json.gz:37587", "repo_name": "akshitth20/cke", "revision_date": "2021-05-01T12:52:45", "revision_id": "d3b7f27cf342344b4bf9ce02bcef99494e78e2a8", "snapshot_id": "65e334d95ff66809ac88d335f3998ea40a513dec", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/akshitth20/cke/d3b7f27cf342344b4bf9ce02bcef99494e78e2a8/task004.3.c", "visit_date": "2023-04-17T08:29:51.049809" }
stackv2
//Define a multiline macro 'factorial' which takes a number as operand and prints the factorial of the given number #define factorial() int n,i=1,fac=1;\ scanf("%d",&n);\ while(i<=n)\ {fac=fac*i;\ i++;\ }\ printf("The factorial of %d is %d",n,fac); main() { factorial() }
3.125
3
2024-11-18T21:46:50.049888+00:00
2021-09-13T18:16:50
6fad3c35f6eaef4d0666619d884fef2f59020878
{ "blob_id": "6fad3c35f6eaef4d0666619d884fef2f59020878", "branch_name": "refs/heads/master", "committer_date": "2021-09-13T18:16:50", "content_id": "9a5c9cfbf4bab6eb827448b29f48c3613f1cfd9d", "detected_licenses": [ "MIT" ], "directory_id": "ae5ed8589ab9f2ac03b5a4ca3297c689f5ff3585", "extension": "c", "filename": "get-firmware.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": 465, "license": "MIT", "license_type": "permissive", "path": "/examples/get-firmware/get-firmware.c", "provenance": "stackv2-0130.json.gz:37846", "repo_name": "harryxiao/synccom-windows", "revision_date": "2021-09-13T18:16:50", "revision_id": "6c84cae0e1a3c571d92c87d777a3804b557e7df7", "snapshot_id": "f2f265a09840d1fedaab0a541d7d96d5460f6513", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/harryxiao/synccom-windows/6c84cae0e1a3c571d92c87d777a3804b557e7df7/examples/get-firmware/get-firmware.c", "visit_date": "2023-07-29T10:00:54.072556" }
stackv2
#include <windows.h> #include <stdio.h> #include "synccom.h" int main(void) { HANDLE h = 0; DWORD tmp; UINT32 firmware_revision = 0; h = CreateFile(L"\\\\.\\SYNCCOM0", GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); DeviceIoControl(h, SYNCCOM_GET_FIRMWARE, NULL, 0, &firmware_revision, sizeof(firmware_revision), &tmp, (LPOVERLAPPED)NULL); printf("Current firmware: 0x%8.8x\n", firmware_revision); CloseHandle(h); return 0; }
2.15625
2
2024-11-18T21:46:50.117863+00:00
2021-10-29T19:33:34
93e9a67ffad4730e73c36862b3843c05162713ab
{ "blob_id": "93e9a67ffad4730e73c36862b3843c05162713ab", "branch_name": "refs/heads/main", "committer_date": "2021-10-29T19:33:34", "content_id": "b567a262d5645971a5481b650e663ea1e3584f63", "detected_licenses": [ "MIT" ], "directory_id": "d6f4245de8d48703508b9b1430b042867625de68", "extension": "c", "filename": "assume.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": 429, "license": "MIT", "license_type": "permissive", "path": "/test/c/special/assume.c", "provenance": "stackv2-0130.json.gz:37975", "repo_name": "songfu1983/smack", "revision_date": "2021-10-29T19:33:34", "revision_id": "c7d0694f08cefb422ebcc67c23824727b06b370e", "snapshot_id": "7d6193a89aeda544638ef1f6b5cdddf6a7a1f910", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/songfu1983/smack/c7d0694f08cefb422ebcc67c23824727b06b370e/test/c/special/assume.c", "visit_date": "2023-08-23T03:11:27.907783" }
stackv2
#include "smack.h" #include <assert.h> // @expect verified // @flag --llvm-assumes=use int main(void) { unsigned int x = __VERIFIER_nondet_unsigned_int(); unsigned int y = __VERIFIER_nondet_unsigned_int(); // This assumption is used for verification, even though // integer-encoding=bit-vector is not enabled, the assertion will pass. __builtin_assume((x ^ y) == (y ^ x)); assert((x ^ y) == (y ^ x)); return 0; }
2.171875
2
2024-11-18T21:46:51.129859+00:00
2021-02-11T08:52:30
7c052abeaeef071afc172ebc4ac427c10485f6cf
{ "blob_id": "7c052abeaeef071afc172ebc4ac427c10485f6cf", "branch_name": "refs/heads/master", "committer_date": "2021-02-11T08:52:30", "content_id": "0505dca2d2ff8af7a945ac7b487ce692ec6b2ad0", "detected_licenses": [ "MIT" ], "directory_id": "e383539f3b79aa88c91394a0641d0dcc928f97ba", "extension": "c", "filename": "vs_print_windows.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 190197763, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4200, "license": "MIT", "license_type": "permissive", "path": "/src/vs/vs_print_windows.c", "provenance": "stackv2-0130.json.gz:38105", "repo_name": "iamtemazhe/corewar", "revision_date": "2021-02-11T08:52:30", "revision_id": "33a27a3f07fd4e83fdbb1d308237e49db825e3c1", "snapshot_id": "1a8a220f6641eebd91926194bd0cb244049c8f6e", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/iamtemazhe/corewar/33a27a3f07fd4e83fdbb1d308237e49db825e3c1/src/vs/vs_print_windows.c", "visit_date": "2021-06-22T16:33:07.411970" }
stackv2
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* vs_print_windows.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: jwinthei <jwinthei@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/07/25 16:47:11 by hgysella #+# #+# */ /* Updated: 2019/07/30 16:20:37 by jwinthei ### ########.fr */ /* */ /* ************************************************************************** */ #include "cw.h" #include "libft.h" #include <ncurses.h> static void print_map(t_cw *cw) { uint8_t raw; uint8_t col; uint32_t j; j = 0; raw = 1; col = 1; while (j < MEM_SIZE) { wattron(cw->vs.map, COLOR_PAIR(cw->map[j].v.col)); mvwprintw(cw->vs.map, raw, col++, "%02x", cw->map[j++].v.code); col += 2; if (col > MAP_X && raw++) col = 1; } } static void print_header_1(t_cw *cw) { uint8_t raw; raw = 10 + 4 * cw->num_of_champs; mvwprintw(cw->vs.header, raw, 1, "%s",\ "Live breakdown for current period :"); mvwprintw(cw->vs.header, raw += 3, 1, "%s",\ "Live breakdown for last period :"); wattron(cw->vs.header, COLOR_PAIR(COL_CODE)); mvwprintw(cw->vs.header, raw -= 2, 1, "%s",\ "[--------------------------------------------------]"); mvwprintw(cw->vs.header, raw += 3, 1, "%s",\ "[--------------------------------------------------]"); wattron(cw->vs.header, COLOR_PAIR(COL_TEXT) | A_BOLD); mvwprintw(cw->vs.header, raw += 2, 1, "%s : %-7d", "CYCLE_TO_DIE",\ cw->cycle_to_die); mvwprintw(cw->vs.header, raw += 2, 1, "%s : %u", "CYCLE_DELTA",\ CYCLE_DELTA); mvwprintw(cw->vs.header, raw += 2, 1, "%s : %u", "NBR_LIVE", NBR_LIVE); mvwprintw(cw->vs.header, raw += 2, 1, "%s : %u", "MAX_CHECKS", MAX_CHECKS); } static void print_header(t_cw *cw) { uint8_t raw; uint8_t i; i = 0; raw = 9; mvwprintw(cw->vs.header, 1, 1, "%s", "** PAUSED **"); mvwprintw(cw->vs.header, 3, 1, "%s %-4u", "Cycles/second limit :",\ 1000 - (cw->vs.delay * 10)); mvwprintw(cw->vs.header, 6, 1, "%s %-7u", "Cycle :", cw->cycles); mvwprintw(cw->vs.header, 8, 1, "%s %-7u", "Processes :", cw->num_of_cars); while (i < cw->num_of_champs) { mvwprintw(cw->vs.header, ++raw, 1, "%s%u : ", "Player -",\ cw->champ[i]->id); wattron(cw->vs.header, COLOR_PAIR(cw->champ[i]->id) | A_BOLD); mvwprintw(cw->vs.header, raw++, 14, "%.52s",\ cw->champ[i]->head.prog_name); wattron(cw->vs.header, COLOR_PAIR(COL_TEXT) | A_BOLD); mvwprintw(cw->vs.header, raw++, 5, "%s %21u", "Last live :",\ cw->champ[i]->last_live); mvwprintw(cw->vs.header, raw++, 5, "%s %7u",\ "Lives in current period :", cw->champ[i++]->lives); } print_header_1(cw); } static void print_menu(t_cw *cw) { mvwprintw(cw->vs.bkg, 68, 129, "%s", "MENU"); mvwprintw(cw->vs.bkg, 70, 16, "%s", "'Esc' for exit"); mvwprintw(cw->vs.bkg, 70, 55, "%s", "'Spase' for pause | run"); mvwprintw(cw->vs.bkg, 70, 95, "%s", "For step by step press 's'"); mvwprintw(cw->vs.bkg, 70, 135, "%s", "Speed 'q' | 'w' | 'e' | 'r'"); mvwprintw(cw->vs.bkg, 70, 175, "%s", "To turn on/off the audio press 'a'"); keypad(cw->vs.bkg, TRUE); } void vs_print_windows(t_cw *cw) { cw->vs.bkg = newwin(78, 254, 0, 0); cw->vs.map = newwin(66, 194, 1, 1); cw->vs.header = newwin(66, 57, 1, 196); cw->vs.aff = newwin(4, 252, 73, 1); cw->f.lg.vs_pause = 1; cw->vs.delay = 90; wbkgd(cw->vs.bkg, COLOR_PAIR(COL_BACK)); wbkgd(cw->vs.aff, COLOR_PAIR(COL_BACK)); wattron(cw->vs.header, COLOR_PAIR(COL_TEXT) | A_BOLD); print_map(cw); print_header(cw); print_menu(cw); nodelay(cw->vs.bkg, true); cbreak(); noecho(); wtimeout(cw->vs.bkg, cw->vs.delay); wrefresh(cw->vs.bkg); if (cw->f.lg.af) mvwprintw(cw->vs.bkg, 72, 129, "%s", "AFF"); }
2.03125
2
2024-11-18T21:46:51.213265+00:00
2019-06-26T04:09:06
07f1dd6780d277de4549155ebf3441c8ee4d4fc7
{ "blob_id": "07f1dd6780d277de4549155ebf3441c8ee4d4fc7", "branch_name": "refs/heads/master", "committer_date": "2019-06-26T04:09:06", "content_id": "3eb4f92951f9c3e32f29e6c3ce109a6fcec4ca90", "detected_licenses": [ "MIT" ], "directory_id": "e1f3dfcc6c4190a33f7fcba94985918ebfd9a441", "extension": "c", "filename": "main.c", "fork_events_count": 0, "gha_created_at": "2019-02-27T13:41:14", "gha_event_created_at": "2019-02-27T13:41:14", "gha_language": null, "gha_license_id": null, "github_id": 172922923, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5460, "license": "MIT", "license_type": "permissive", "path": "/wuziqi/main.c", "provenance": "stackv2-0130.json.gz:38234", "repo_name": "ppka2/c2019", "revision_date": "2019-06-26T04:09:06", "revision_id": "593d692a194511c03da85ea058427791f06462fc", "snapshot_id": "f5b223d08784524e8d26b8f29d40d2a13cbf9c9c", "src_encoding": "GB18030", "star_events_count": 0, "url": "https://raw.githubusercontent.com/ppka2/c2019/593d692a194511c03da85ea058427791f06462fc/wuziqi/main.c", "visit_date": "2021-06-25T00:26:46.791407" }
stackv2
#include"show.h" #include"userinput.h" #include"exam.h" #include"menu.h" #include"examasume.h" #include"input1.h" #include"assume.h" #include"window.h" int main() { int n; system("color 70");//控制台颜色 HWND hwnd = GetForegroundWindow(); SetWindowTextA(hwnd, "五子棋"); menu(); if (point == 1) { printf("1: using mouse\n"); printf("2: using keyboard\n"); scanf("%d", &n); switch (n) { case 1: point = 11;//用来传递用户选择 break; case 2: point = 12; break; default: break; } if (point == 11) { int x = 800; int y = 800; MoveWindow(hwnd, 0, 0, x, y, true); system("cls"); show(); printf("不要移动控制台,鼠标指向位置,空格下棋\n"); while (1) { if (_kbhit()) { system("cls"); ch = _getch(); setpoint(ch);//用户互相下棋 show(); printf("不要移动控制台,鼠标指向位置,空格下棋 \n \n\n\n\n\n\n"); switch (exam()) { case 2: printf("white is win"); getchar(); exit(1); break; case 4: printf("black is win"); getchar(); exit(1); break; default: break; } } } } if (point == 12) { show(); printf("a向左移动,d向右移动,w向上移动,s向下移动,空格下棋\n \n \n\n\n\n\n\n"); while (1) { if (_kbhit()) { ch = _getch(); input();//用户下棋 switch (exam()) { case 2: printf("white is win"); getchar(); exit(1); break; case 4: printf("black is win"); getchar(); exit(1); break; default: break; } system("cls"); // assume(); show(); printf("a向左移动,d向右移动,w向上移动,s向下移动,空格下棋\n \n \n\n\n\n\n\n"); Sleep(100); } } } } if (point == 2) { printf("1: using mouse\n"); printf("2: using keyboard\n"); scanf("%d", &n); switch (n) { case 1: point = 21; break; case 2: point = 22; break; default: break; } if (point == 22) { system("cls"); board[7][7] = 2;//默认电脑先下 show(); printf("◎为电脑上一步下的棋a向左移动,d向右移动,w向上移动,s向下移动,空格下棋\n \n \n\n\n\n\n\n"); while (1) { if (_kbhit()) { ch = _getch(); input1();//用户下棋 system("cls"); show(); printf("◎为电脑上一步下的棋a向左移动,d向右移动,w向上移动,s向下移动,空格下棋\n \n \n\n\n\n\n\n"); switch (exam()) { case 2: printf("white is win"); getchar(); system("pause"); exit(1); break; case 4: printf("black is win"); getchar(); system("pause"); exit(1); break; default: break; } system("cls"); if (ch == ' '&&first1 == 0) { if (first3 == 1) { board[temp_x][temp_y] = 2;//使电脑最近下的棋◎还原 first3 = 0; } first3 = 1; assume();//电脑下棋 show(); printf("◎为电脑上一步下的棋a向左移动,d向右移动,w向上移动,s向下移动,空格下棋\n \n \n\n\n\n\n\n"); switch (exam()) { case 2: printf("你被电脑打败了哈哈哈 \n \n \n\n\n\n\n\n"); getchar(); system("pause"); exit(1); break; case 4: printf("你战胜了电脑,流弊! \n \n \n\n\n\n\n\n"); getchar(); system("pause"); exit(1); break; default: break; } //getchar(); system("cls"); } show(); printf("◎为电脑上一步下的棋a向左移动,d向右移动,w向上移动,s向下移动,空格下棋\n \n \n\n\n\n\n\n"); } first1 = 1; } } if (point == 21) { board[7][7] = 2;//默认电脑先下 int x = 800; int y = 800; MoveWindow(hwnd, 0, 0, x, y, true); system("cls"); show(); printf("◎为电脑上一步下的棋,不要移动控制台,鼠标指向位置,空格下棋 \n \n \n\n\n\n\n\n "); while (1) { if (_kbhit()) { system("cls"); ch = _getch(); setpointhum(ch);//玩家下棋 show(); printf("◎为电脑上一步下的棋,不要移动控制台,鼠标指向位置,空格下棋 \n \n \n\n\n\n\n\n"); switch (exam()) { case 2: printf("white is win"); getchar(); system("pause"); exit(1); break; case 4: printf("black is win"); getchar(); system("pause"); exit(1); break; default: break; }; if (ch == ' '&&first1 == 0) { system("cls"); if (first3 == 1) { board[temp_x][temp_y] = 2;//还原◎提示的棋子 first3 = 0; } first3 = 1; assume(); show(); printf("◎为电脑上一步下的棋,不要移动控制台,鼠标指向位置,空格下棋 \n \n \n\n\n\n\n\n "); switch (exam()) { case 2: printf("你被电脑打败了哈哈哈 \n \n \n\n\n\n\n\n"); getchar(); system("pause"); exit(1); break; case 4: printf("你战胜了电脑,流弊! \n \n \n\n\n\n\n\n"); getchar(); system("pause"); exit(1); break; default: break; } } first1 = 1; } } } } }
2.515625
3
2024-11-18T21:46:51.739276+00:00
2022-04-10T15:03:07
54e038dd3dd770d42c91583e4e79843ead08157c
{ "blob_id": "54e038dd3dd770d42c91583e4e79843ead08157c", "branch_name": "refs/heads/master", "committer_date": "2022-04-10T15:03:07", "content_id": "d3d05f93bf79c0e14db559b437f3195916c1de7f", "detected_licenses": [ "Apache-2.0" ], "directory_id": "6ec209c1f6f3ca8017a5373ba2e85da38dfda90c", "extension": "c", "filename": "167.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 60593146, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 728, "license": "Apache-2.0", "license_type": "permissive", "path": "/array/167.c", "provenance": "stackv2-0130.json.gz:39016", "repo_name": "MingfeiPan/leetcode", "revision_date": "2022-04-10T15:03:07", "revision_id": "057d9f014cf207ab4e50e14e5a9e015724de1386", "snapshot_id": "a70192233f7112ce39cc7b09d782bdcc52d29d06", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/MingfeiPan/leetcode/057d9f014cf207ab4e50e14e5a9e015724de1386/array/167.c", "visit_date": "2022-05-09T01:40:39.599374" }
stackv2
/** * Return an array of size *returnSize. * Note: The returned array must be malloced, assume caller calls free(). */ int* twoSum(int* numbers, int numbersSize, int target, int* returnSize) { int* result = (int*)malloc(sizeof(int)*2); int index2 = numbersSize - 1; int index1 = 0; *returnSize = 2; while(index1 < index2) { if(target == (numbers[index1] + numbers[index2])) { result[0] = index1+1; result[1] = index2+1; return result; } while(index1 < index && target < (numbers[index1] + numbers[index2])) index2--; while(index1 < index2 && target > (numbers[index1] + numbers[index2])) index1++; } return result; }
3.4375
3
2024-11-18T21:46:52.373167+00:00
2023-07-21T05:49:53
5ae5d3f1db4f8e959a5dee61f82b5f19393faaee
{ "blob_id": "5ae5d3f1db4f8e959a5dee61f82b5f19393faaee", "branch_name": "refs/heads/master", "committer_date": "2023-07-21T11:16:09", "content_id": "2298d9bc0b43f7a6f22397a5fd2ec66714862a39", "detected_licenses": [ "MIT" ], "directory_id": "cd4eb25911d3e3b092aa97aaa7b8fbba6c3a0704", "extension": "h", "filename": "maybe.h", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 26949326, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 816, "license": "MIT", "license_type": "permissive", "path": "/lang/c/HaskellInC/maybe.h", "provenance": "stackv2-0130.json.gz:39145", "repo_name": "liuyang1/test", "revision_date": "2023-07-21T05:49:53", "revision_id": "9a154e0161a1a33baad53f7223ee72e702532001", "snapshot_id": "29bb142982d2ef0d79b71e8fe5f5e0d51ec5258e", "src_encoding": "UTF-8", "star_events_count": 9, "url": "https://raw.githubusercontent.com/liuyang1/test/9a154e0161a1a33baad53f7223ee72e702532001/lang/c/HaskellInC/maybe.h", "visit_date": "2023-08-05T08:56:50.526414" }
stackv2
typedef enum { Nothing = 0, Just, Left, Right, } MetaType; typedef enum { VT_int = 0, VT_int2int, } ValType; typedef struct MaybeX { MetaType type; ValType vtype; union { int val; int (*fnc)(int); } x; } MaybeX; /** * Either String Int */ typedef struct EitherX { MetaType type; ValType vtype; union { int val; char *msg; } x; } EitherX; #define SHOWMAYBEINTLEN 256 bool isNothing(MaybeX v); bool isJust(MaybeX v); bool equal(MaybeX a, MaybeX b); MaybeX JustInt(int v); MaybeX JustFnc(int (*fnc)(int)); MaybeX NothingX(); char *show(char *s, MaybeX v); MaybeX fmap(int (*func)(int), MaybeX v); MaybeX Applicative(MaybeX a, MaybeX b); bool isLeft(EitherX v); bool isRight(EitherX v); bool equalEither(EitherX v);
2.03125
2
2024-11-18T21:46:52.753242+00:00
2019-02-04T17:02:19
2e91b67a40085566f57f8934f53033f75b4dbc31
{ "blob_id": "2e91b67a40085566f57f8934f53033f75b4dbc31", "branch_name": "refs/heads/master", "committer_date": "2019-02-04T17:02:19", "content_id": "381c9728e1833d5aa1ede401065d8e9ee6dba2a5", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "66e02556644df9f34693c03b85b68957c4e8b296", "extension": "c", "filename": "heap.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": 1549, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/src/heap.c", "provenance": "stackv2-0130.json.gz:39534", "repo_name": "poobalan-arumugam/raft", "revision_date": "2019-02-04T17:02:19", "revision_id": "18404ded4e201a73858c099846fe6362a8900f8c", "snapshot_id": "d20be8db5bb67815c63ec75cd7afea7f50e57a70", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/poobalan-arumugam/raft/18404ded4e201a73858c099846fe6362a8900f8c/src/heap.c", "visit_date": "2020-04-24T02:13:48.331573" }
stackv2
#include "stdlib.h" #include "../include/raft.h" static void *raft__heap_malloc(void *data, size_t size) { (void)data; return malloc(size); } static void raft__free(void *data, void *ptr) { (void)data; free(ptr); } static void *raft__calloc(void *data, size_t nmemb, size_t size) { (void)data; return calloc(nmemb, size); } static void *raft__realloc(void *data, void *ptr, size_t size) { (void)data; return realloc(ptr, size); } static void *raft__aligned_alloc(void *data, size_t alignment, size_t size) { (void)data; return aligned_alloc(alignment, size); } struct raft_heap raft_heap__default = { NULL, /* data */ raft__heap_malloc, /* malloc */ raft__free, /* free */ raft__calloc, /* calloc */ raft__realloc, /* realloc */ raft__aligned_alloc /* aligned_alloc */ }; struct raft_heap *raft_heap__current = &raft_heap__default; void *raft_malloc(size_t size) { return raft_heap__current->malloc(raft_heap__current->data, size); } void raft_free(void *ptr) { raft_heap__current->free(raft_heap__current->data, ptr); } void *raft_calloc(size_t nmemb, size_t size) { return raft_heap__current->calloc(raft_heap__current->data, nmemb, size); } void *raft_realloc(void *ptr, size_t size) { return raft_heap__current->realloc(raft_heap__current->data, ptr, size); } void raft_heap_set(struct raft_heap *heap) { raft_heap__current = heap; } void raft_heap_set_default() { raft_heap__current = &raft_heap__default; }
2.828125
3
2024-11-18T21:46:53.001799+00:00
2021-03-17T07:29:19
d69f7fe4ceef27887dc15b047b30f460bff31664
{ "blob_id": "d69f7fe4ceef27887dc15b047b30f460bff31664", "branch_name": "refs/heads/master", "committer_date": "2021-03-17T07:29:19", "content_id": "770a3f51e92c07eb199fd5bc5ba9a5f1fa5c2737", "detected_licenses": [ "curl", "Apache-2.0" ], "directory_id": "546018757d22ae76154b87335db68e1cfabfedcb", "extension": "c", "filename": "test_io_k8s_api_rbac_v1_cluster_role.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 346627883, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2548, "license": "curl,Apache-2.0", "license_type": "permissive", "path": "/kubernetes/unit-test/test_io_k8s_api_rbac_v1_cluster_role.c", "provenance": "stackv2-0130.json.gz:39794", "repo_name": "zouxiaoliang/nerv-kubernetes-client-c", "revision_date": "2021-03-17T07:29:19", "revision_id": "07528948c643270fd757d38edc68da8c9628ee7a", "snapshot_id": "45f1bca75b6265395f144d71bf6866de7b69bc25", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/zouxiaoliang/nerv-kubernetes-client-c/07528948c643270fd757d38edc68da8c9628ee7a/kubernetes/unit-test/test_io_k8s_api_rbac_v1_cluster_role.c", "visit_date": "2023-03-16T09:31:03.072968" }
stackv2
#ifndef io_k8s_api_rbac_v1_cluster_role_TEST #define io_k8s_api_rbac_v1_cluster_role_TEST // the following is to include only the main from the first c file #ifndef TEST_MAIN #define TEST_MAIN #define io_k8s_api_rbac_v1_cluster_role_MAIN #endif // TEST_MAIN #include <stdlib.h> #include <string.h> #include <stdio.h> #include <stdbool.h> #include "../external/cJSON.h" #include "../model/io_k8s_api_rbac_v1_cluster_role.h" io_k8s_api_rbac_v1_cluster_role_t* instantiate_io_k8s_api_rbac_v1_cluster_role(int include_optional); #include "test_io_k8s_api_rbac_v1_aggregation_rule.c" #include "test_io_k8s_apimachinery_pkg_apis_meta_v1_object_meta.c" io_k8s_api_rbac_v1_cluster_role_t* instantiate_io_k8s_api_rbac_v1_cluster_role(int include_optional) { io_k8s_api_rbac_v1_cluster_role_t* io_k8s_api_rbac_v1_cluster_role = NULL; if (include_optional) { io_k8s_api_rbac_v1_cluster_role = io_k8s_api_rbac_v1_cluster_role_create( // false, not to have infinite recursion instantiate_io_k8s_api_rbac_v1_aggregation_rule(0), "0", "0", // false, not to have infinite recursion instantiate_io_k8s_apimachinery_pkg_apis_meta_v1_object_meta(0), list_create() ); } else { io_k8s_api_rbac_v1_cluster_role = io_k8s_api_rbac_v1_cluster_role_create( NULL, "0", "0", NULL, list_create() ); } return io_k8s_api_rbac_v1_cluster_role; } #ifdef io_k8s_api_rbac_v1_cluster_role_MAIN void test_io_k8s_api_rbac_v1_cluster_role(int include_optional) { io_k8s_api_rbac_v1_cluster_role_t* io_k8s_api_rbac_v1_cluster_role_1 = instantiate_io_k8s_api_rbac_v1_cluster_role(include_optional); cJSON* jsonio_k8s_api_rbac_v1_cluster_role_1 = io_k8s_api_rbac_v1_cluster_role_convertToJSON(io_k8s_api_rbac_v1_cluster_role_1); printf("io_k8s_api_rbac_v1_cluster_role :\n%s\n", cJSON_Print(jsonio_k8s_api_rbac_v1_cluster_role_1)); io_k8s_api_rbac_v1_cluster_role_t* io_k8s_api_rbac_v1_cluster_role_2 = io_k8s_api_rbac_v1_cluster_role_parseFromJSON(jsonio_k8s_api_rbac_v1_cluster_role_1); cJSON* jsonio_k8s_api_rbac_v1_cluster_role_2 = io_k8s_api_rbac_v1_cluster_role_convertToJSON(io_k8s_api_rbac_v1_cluster_role_2); printf("repeating io_k8s_api_rbac_v1_cluster_role:\n%s\n", cJSON_Print(jsonio_k8s_api_rbac_v1_cluster_role_2)); } int main() { test_io_k8s_api_rbac_v1_cluster_role(1); test_io_k8s_api_rbac_v1_cluster_role(0); printf("Hello world \n"); return 0; } #endif // io_k8s_api_rbac_v1_cluster_role_MAIN #endif // io_k8s_api_rbac_v1_cluster_role_TEST
2.25
2
2024-11-18T21:46:54.316984+00:00
2021-02-08T14:41:41
eb242bd757d54f5c895d933004ec83180adf3c24
{ "blob_id": "eb242bd757d54f5c895d933004ec83180adf3c24", "branch_name": "refs/heads/master", "committer_date": "2021-02-08T14:41:41", "content_id": "08b06673f13a23ebcf0bb6a0bac442a64d7f353e", "detected_licenses": [ "MIT" ], "directory_id": "bcb423efc8f0833c46363af9df990cb6b8370323", "extension": "c", "filename": "armstrong.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": 306, "license": "MIT", "license_type": "permissive", "path": "/Year 1/PSUC/Lab/Week 3/armstrong.c", "provenance": "stackv2-0130.json.gz:40184", "repo_name": "DoomDust7/CSE-MIT-Manipal", "revision_date": "2021-02-08T14:41:41", "revision_id": "2974f42b3793e3f36870c000c3104fabf33640fd", "snapshot_id": "ad384e0196000d5640b5b7679130432e73c9be56", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/DoomDust7/CSE-MIT-Manipal/2974f42b3793e3f36870c000c3104fabf33640fd/Year 1/PSUC/Lab/Week 3/armstrong.c", "visit_date": "2023-03-02T17:21:25.293508" }
stackv2
#include<stdio.h> #include<math.h> int main() { int num,digi,sum=0,a; printf("enter 3 digit number"); scanf("%d",&num); a=num; while(num>0) { digi=num%10; sum=sum+digi*digi*digi; num=num/10; } if(a==sum) { printf("%d is an armstrong number",sum); } else { printf("%d is not an armstrong number",sum); } }
2.8125
3
2024-11-18T21:46:54.484344+00:00
2019-04-11T17:36:55
31660dbcef6865b887e2a0f706a591a0c38a9441
{ "blob_id": "31660dbcef6865b887e2a0f706a591a0c38a9441", "branch_name": "refs/heads/master", "committer_date": "2019-04-11T17:36:55", "content_id": "c9dbe4a5f9bf1a9882c8a54edccee3140901427e", "detected_licenses": [ "Unlicense" ], "directory_id": "b6977b118fc346428cd004ac63046f5f69987e20", "extension": "c", "filename": "util2.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 128969932, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 15721, "license": "Unlicense", "license_type": "permissive", "path": "/cgi/util2.c", "provenance": "stackv2-0130.json.gz:40440", "repo_name": "fwtompa/e-corpusSE", "revision_date": "2019-04-11T17:36:55", "revision_id": "3eb13405d74f3d7544b4699bcdcf87864648b312", "snapshot_id": "16f771e9d26318cd30c9790f9b3eee3a15e67d02", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/fwtompa/e-corpusSE/3eb13405d74f3d7544b4699bcdcf87864648b312/cgi/util2.c", "visit_date": "2021-06-26T15:46:42.016913" }
stackv2
//File: util2.c //Location: ~/manuprobe/src/cgi #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include "util.h" #include "tags.h" #include "cgi.h" unsigned char* http_val (char* word, int m){ int x; for (x=0;x<=m;x++) { if (!strcmp(entries[x].name,word)) return(entries[x].val[0]?entries[x].val:NULL); } return(NULL); } unsigned char* http_nval (char* word, int m){ int x; unsigned char* val; val = http_val(word,m); if (val && strlen(val)>0) { x = atoi(val); sprintf(val,"%d",x); // make sure only numeric data is present return(val); } return(NULL); } void http_val_dump (int m, FILE* out){ int x; for (x=0;x<=m;x++) { fprintf(out,"[%s=%s];",entries[x].name,entries[x].val); } } void http_printf (char* text) { register int x; if (!text) return; for (x=0;text[x];x++) { if (text[x] == '<') printf("&lt;"); else if (text[x] == '&') printf("&amp;"); else putchar(text[x]); } } void semi2comma(unsigned char *str) { register int x; for(x=0;str[x+1];x++) if(str[x] == ';' && str[x+1] == ' ') str[x] = ','; } char* decodeUTF8(unsigned char* str) { register int x; register int p=0; int len; char* newstr; char* num; for (x=0;str[x];x++) len += (str[x]>127 ? 3 : 1); // 2-char codes for 6-char encoding if (len == strlen(str)) return(str); newstr = malloc((len+1)*sizeof(char)); num = malloc(7*sizeof(char)); for (x=0;str[x];x++) { if (str[x]>127) { if (str[x++] == 195) // c3 in hex sprintf(num,"&#%u;",str[x]-128+192); // x80 -> 192 else // c2 in hex sprintf(num,"&#%u;",str[x]-192+160); // xA0 -> 160 newstr[p] = 0; strcat(newstr,num); p += 6; } else newstr[p++] = str[x]; } newstr[p] = 0; return(newstr); } void writeLog(int m) { char* command; char* buffer = malloc(1000*sizeof(char)); int bufsize = 1000; FILE* pipeTemp; int p = 0; int x; char tempChar; command = malloc((strlen(USAGE_LOG)+strlen("echo REMOTE_ADDR=[$REMOTE_ADDR] HTTP_REFERER=[$HTTP_REFERER])") +1) *sizeof(char)); sprintf(command,"date"); pipeTemp = popen(command,"r"); while(tempChar = fgetc(pipeTemp)) { if(feof(pipeTemp)) break; buffer[p++] = (tempChar != '\n')?tempChar:' '; if (p > bufsize-2) { bufsize *= 2; buffer = (char *)realloc(buffer,sizeof(char)*bufsize); } } pclose(pipeTemp); sprintf(command,"echo REMOTE_ADDR=[$REMOTE_ADDR] HTTP_REFERER=[$HTTP_REFERER]"); pipeTemp = popen(command,"r"); while(tempChar = fgetc(pipeTemp)) { if(feof(pipeTemp)) break; buffer[p++] = (tempChar != '\n')?tempChar:' '; if (p > bufsize-2) { bufsize *= 2; buffer = (char *)realloc(buffer,sizeof(char)*bufsize); } } pclose(pipeTemp); for (x=0;x<=m;x++) { if (p + strlen(entries[x].name) + strlen(entries[x].val) + strlen("[=];") > bufsize-2) { bufsize *= 2; buffer = (char *)realloc(buffer,sizeof(char)*bufsize); } sprintf(&buffer[p],"[%s=%s];",entries[x].name,entries[x].val); p += strlen(entries[x].name) + strlen(entries[x].val) + strlen("[=];"); } buffer[p] = '\0'; pipeTemp = fopen(USAGE_LOG,"a"); fprintf(pipeTemp,"%s\n",buffer); fclose(pipeTemp); } int numWords(char* word) //returns an number of words, ie, ones delimited with op codes, +,-,| { int numWords=0; int aIndex=0; // a=array, arrayIndex int wIndex=0; // w=word , wordIndex int size=0; //current part size int lastEnd=0; //the end of last part int i; int j; if(!word) return 0; while(word[wIndex] != '\0'){ char currChar=word[wIndex]; if(currChar=='+' || currChar=='-' || currChar=='|' ){ numWords++; } wIndex++; } //for the last word numWords++; return (numWords); } /* N.B. using perl version in constructQueryNew for now char* constructQuery(char* word,char* macro,int numWords) { // construct query for SGREP char* toReturn = (char*)malloc( (strlen(word) + numWords*( max(strlen(" not equal "),strlen(" -e ''")) + strlen(macro)) + 1) * sizeof(char); // "not equal" represents the longest sgrep key word used int wIndex=0; int lastEnd; char currChar; char nextChar; int lastCheckIndex; int macroStart=0; char* opening = "(\""; char* closing = "\")"; char* tempStr = (char*)malloc(1*sizeof(char)); strcpy(toReturn," -e '"); // opening sequence for search while(word[wIndex] != '\0') { currChar = word[wIndex]; nextChar = word[wIndex+1]; //printf("wIndex=%d : currChar=%c : nextChar=%c<br>\n",wIndex,currChar,nextChar); fflush(stdout); if( currChar=='+' || currChar=='|' || currChar=='-' ) { if(macroStart){ strcat(toReturn,closing); macroStart=0; } //replacing the op char with any of these if(currChar=='+') strcat(toReturn," equal "); else if(currChar=='-') strcat(toReturn," not equal "); else if(currChar=='|') strcat(toReturn," or "); }else if( currChar=='(' ) { if( nextChar != '(' ){ strcat(toReturn,"("); strcat(toReturn,macro); strcat(toReturn,opening); macroStart=1; }else strcat(toReturn,"("); }else if( currChar==')' ){ if( lastCheckIndex==(wIndex-1) ) { strcat(toReturn,closing); //if the last char wasn't any of the parenthesis, or operators strcat(toReturn,")"); macroStart=0; }else strcat(toReturn,")"); }else{ sprintf(tempStr,"%c",currChar); if(!macroStart){ strcat(toReturn,macro); strcat(toReturn,opening); macroStart=1; } strcat(toReturn,tempStr); lastCheckIndex=wIndex; } if(lastCheckIndex != wIndex) lastCheckIndex=-1; //to check in the next loop, whether the last char was an ending of the word or not wIndex++; //printf("toReturn=%s<br>\n",toReturn); fflush(stdout); } //for the ending only if(macroStart){ strcat(toReturn,"\")' "); macroStart=0; }else strcat(toReturn,"' "); return toReturn; } */ char* orthonormal(char* in, int align){ // adjust text to normalize Latin spelling and remove quotes /* replacements: convert to lower case remove diacritics and ligatures (using charcode_list) normalize spelling */ // but preserve spacing so that offsets match source text /* pad shortened words with '\037' (Unit separator char) to avoid matching with blanks */ int ip; int op = 0; char* out; int i, j; char c; char pad = '\037'; int inTag = 0, inTagVal = 0; out = (char*) malloc((strlen(in)+1)*sizeof(char)); for (ip=0; in[ip]; ip++) { c = '\0'; if ((!inTag || inTagVal) && isalpha(in[ip])) c = tolower(in[ip]); else if(in[ip] == ' ') { out[op++] = in[ip]; // copy the blank itself, then pad while (align && op <= ip) out[op++] = pad; } else if (in[ip] == '<') { // preserve tag and attribute names inTag = 1; while (op < ip) out[op++] = pad; // first align out[op++] = in[ip]; } else if (inTag && !inTagVal && in[ip] == '>') { inTag = 0; out[op++] = in[ip]; } else if (inTag && !inTagVal && in[ip] == '"') { // start attribute value => normalize inTagVal = 1; out[op++] = in[ip]; } else if (inTag && inTagVal && in[ip] == '"') { // end attribute vale => align inTagVal = 0; while (op < ip) out[op++] = pad; // first align out[op++] = in[ip]; } else if (inTag && !inTagVal) out[op++] = in[ip]; // preserve chars in tags and outside attr vals else if (in[ip] == '&') { // check table for normalizations for (j=0; j < char_tbl_len - 1; j++) { // check every string if ((i = strncmp(char_tbl[j].charref,in+ip,strlen(char_tbl[j].charref))) == 0) { ip += strlen(char_tbl[j].charref) - 1; break; } if (i < 0) { // ordering => no later string can match j = char_tbl_len - 1; // signal no match by pointing to empty string break; } } if (j < char_tbl_len - 1) { // found a match c = char_tbl[j].norm; } else { while (in[ip] != ';') out[op++] = in[ip++]; // no normalization available out[op++] = ';'; } } else out[op++] = in[ip]; if (c != '\0') { // found alpha character // ae e // ci ti // d t (added July 2017) // h // j i // k c // m n // oe e // ph f // v u // y i switch(c) { case 'd': out[op++] = 't'; break; case 'e': if (op > 0 && (out[op-1] == 'a' || out[op-1] == 'o')) { while (op > 1 && (out[op-2] == 'a' || out[op-2] == 'o')) --op; // leave only one 'a' or 'o' out[op-1] = 'e'; // replace ae or oe by e. } else out[op++] = 'e'; break; case 'h': if (op > 0 && out[op-1] == 'p') out[op-1] = 'f'; else /* do nothing */; break; case 'i': case 'j': case 'y': if (op > 0 && out[op-1] == 'c') { if (op > 1 && out[op-2] == 't') op--; // handle "...tci..." else out[op-1] = 't'; } out[op++] = 'i'; break; case 'k': out[op++] = 'c'; break; case 'm': out[op++] = 'n'; break; case 'v': out[op++] = 'u'; break; default: out[op++] = c; } if (op > 1 && out[op-1] == out[op-2]) op--; // \l+ -> \l } } while (align && op < ip) out[op++] = pad; // pad with pad chars out[op] = '\0'; if (!align) { // do not insert alignment chars at the end of query for (op -= 1; op>0 && out[op] == pad; op--) out[op] = '\0'; } // printf("<pre>orthonormal: '%s' -> '%s'</pre>",in,out);fflush(stdout); return out; } void adjustOrtho(char* word) { // handle searches such as "philosophia" to also match "philosophiae" (normalized) // ae e // ci ti // oe e // ph f int pos = strlen(word)-1; switch (word[pos]) { case 'a': case 'o': word[pos] = 'e'; break; case 'c': // need to search for ti as well word[pos++] = 't'; word[pos++] = 'i'; word[pos] = '\0'; case 'p': word[pos] = 'f'; break; default: word[0] = '\0'; // no other word to find } return; } char* normalize(char* word, int indexed){ // remove all the spaces, except the ones in between double quotes or braces, // convert everything to lower case // convert parentheses inside quotes and all commas and apostrophes to codes // if searching an indexed text, apply orthographic normalization // indexed = 2 => apply orthographic normalization on extended word char* toReturn; char currChar; int wIndex=0; int rIndex=0; int inQuote=0; int in, out=-1; int size = strlen(word) + 2; // maximum size of returned string char* chars = "(),'"; int charCodes[4] // codes for chars above = {40, 41, 44, 39}; // in same order as chars char* codePos; int codeOffset; char encoded[6]; // room for "\#44;" for example char* normword; for(wIndex=0;word[wIndex];wIndex++) if (strchr(chars,word[wIndex])) size += 4; // add 4 for each toReturn = malloc(size*sizeof(char)); normword = indexed ? orthonormal(word,0) : word; //if (indexed){ //normword = orthonormal(word); // now make sure extra spaces do not hinder search //for(in=0;in <= strlen(normword);in++) { // remove duplicate blanks //if(in > 0 && normword[in]==' ' && normword[out] == ' ') continue; //normword[++out] = normword[in]; //} // printf("TESTING: orthonormal: '%s' (%d chars) -> '%s' (%d chars)<BR/>\n",word,(int)strlen(word),normword,(int)strlen(normword)); fflush(stdout); //} //else normword = word; for(wIndex=0;normword[wIndex];wIndex++){ currChar=tolower(normword[wIndex]); if(currChar=='\"') inQuote = 1 - inQuote; // flip the bit if(currChar!=' ' || inQuote) { codePos = strchr(chars,currChar); codeOffset = codePos ? codePos - chars : 0; if((inQuote && codePos && (codeOffset<2))|| codeOffset>1) { toReturn[rIndex] = '\0'; sprintf(encoded,"\\#%d;",charCodes[codeOffset]); strcat(toReturn,encoded); rIndex += 5; } else toReturn[rIndex++] = currChar; } } toReturn[rIndex] = '\0'; // terminate the string if (indexed == 2) { // perhaps need to adjust word ending adjustOrtho(toReturn); } // printf("TESTING: normalized search term: %s\n",toReturn); fflush(stdout); if (indexed) free(normword); // free space for normalized form of word return toReturn; } int nestingCheck(char* word,int* numWords) { // checks whether the double quotes and brackets are balanced, // op chars not nested and properly placed, ignores spaces int inBracket=0; int inQuote=0; int inWord=0; int wIndex=0; char currChar; int lastOpen=-1; // index of the last opening bracket int lastClose=-1; // index of last closing bracket int lastOpr=-1; // index of the last operator int lastQuote=-1; // index of last quotation mark int lastChar=-1; // index of any other non-blank character *numWords = 1; // count number of words (1 + number of ops) for(wIndex=0; word[wIndex]; wIndex++){ currChar=word[wIndex]; if(currChar=='\"'){ if( (!inQuote) && lastChar>lastOpr ) return 0; // e.g., + word "word" inQuote = 1 - inQuote; // flip the bit lastQuote=wIndex; }else if(currChar=='('){ if(lastChar>lastOpr) return 0; // e.g., + word ( inBracket++; lastOpen=wIndex; }else if(currChar==')'){ inBracket--; lastClose=wIndex; if (inBracket < 0) return 0; // too many right brackets }else if( !inQuote && (currChar=='+' || currChar=='-' || currChar=='|') ){ if(lastChar<0) return 0; // e.g., + word (at start of string) if(lastOpr>lastChar) return 0; // e.g., + + if(lastOpen>lastChar) return 0; // e.g., word ( + lastOpr=wIndex; (*numWords)++; }else if(currChar!=' ') { if(lastClose>lastOpr) return 0; // e.g., + ) word if( !inQuote && lastQuote>lastOpr) return 0; // e.g., + "word" word if( !inQuote && !inWord && lastChar>lastOpr) return 0; // e.g., + word word inWord = 1; lastChar=wIndex; }else if(!inQuote) inWord = 0; //printf("currChar=%c ----------<br>lastOpr=%d<br>lastOpen=%d<br>lastClose=%d<br>lastChar=%d<br>inQuote=%d<br>lastQuote=%d<br>\n",currChar,lastOpr,lastOpen,lastClose,lastChar,inQuote,lastQuote); fflush(stdout); } //final conditions if( lastOpr>lastChar ) return 0; // e.g., word + (at end of string) if( lastChar==-1 && lastQuote==-1 ) return 0; // no words at all (nor quoted blanks) return (!inBracket && !inQuote); }
2.6875
3
2024-11-18T21:46:54.685760+00:00
2021-08-19T19:47:22
6a2df3c513300359a24a36fe4b1607a983163291
{ "blob_id": "6a2df3c513300359a24a36fe4b1607a983163291", "branch_name": "refs/heads/master", "committer_date": "2021-08-19T19:47:22", "content_id": "25e1e31a3cc78050204de274b21539819234811a", "detected_licenses": [ "MIT" ], "directory_id": "637d5e94ad45e28c7888cf8628698b5772da7261", "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": 389624899, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 16698, "license": "MIT", "license_type": "permissive", "path": "/main.c", "provenance": "stackv2-0130.json.gz:40568", "repo_name": "Moudane69/DevCommeLesPros-2021-DevCommeLesPros-2021", "revision_date": "2021-08-19T19:47:22", "revision_id": "373b0822542ed10a91d84154dafa4c700c45c7dc", "snapshot_id": "e25ca2f47e95fb1a22bb48fcd928df78c9a57647", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Moudane69/DevCommeLesPros-2021-DevCommeLesPros-2021/373b0822542ed10a91d84154dafa4c700c45c7dc/main.c", "visit_date": "2023-07-12T10:49:02.073491" }
stackv2
#include "lib/luminyEat.h" #include <stdio.h> #include <stdlib.h> #include <string.h> int main() { char choix_1; char choix_2; char choix_3; char choix_4; char choix_5; int id_item; printf("Bienvenue dans le menu pricipale de LuminyEats\n") ; do { printf("[1].Pour vous connecté\n[2].Pour créer un compte\n[q].Pour quitter\n"); scanf("%c", &choix_1); viderBuffer(); switch (choix_1) { /***********************/ /* Pour vous connecter */ /***********************/ case '1': do { // type permet de faire le choix dans la switch suivante, id permet d'identifier la ligne dans le fichier CSV printf("Pour vous connecter, entrez votre numero de telephone: "); char *numeroTelephone ; numeroTelephone = malloc(sizeof(char)*10) ; scanf("%s" , numeroTelephone) ; int* id_type = connexion(numeroTelephone) ; viderBuffer(); if(id_type[1] == 1){ choix_2 = '1' ; } else if(id_type[1] == 2){ choix_2 = '2' ; } else if(id_type[1] == 3){ choix_2 = '3' ; } switch (choix_2) { case '1': // system("clear"); printf("Vous etes restaurateur\n"); ajoutHistorique(id_type[0], id_type[1] , "Connexion") ; do{ printf("[1].Pour supprimer \n[2].Pour item \n[3].Pour solde \n[q].Pour quitter \n[p].Pour precedent\n"); scanf("%c", &choix_3); viderBuffer(); switch (choix_3){ case 49: supprimerCompte(id_type[0], id_type[1]) ; ajoutHistorique(id_type[0], id_type[1] , "SupprimerCompte") ; printf("Vous avez supprimer votre compte\n"); return 0; case 50: printf("[1].Pour ajouter un item dans votre menu\n[2].Pour supprimer un item deja existant\n"); scanf("%c", &choix_5) ; switch (choix_5){ case '1': printf("Entrez l'id du item que vous voulez ajouter: \n") ; scanf("%d", &id_item) ; ajouterItem(id_type[0], id_item) ; ajoutHistorique(id_type[0], id_type[1] , "Ajouter Item") ; viderBuffer(); printf("Vous avez ajouter un item\n"); break; case '2': printf("Entrez l'id du item que vous voulez supprimer (Attention il faut au moins un item qui reste dans votre menu): \n") ; scanf("%d", &id_item) ; supprimerItem(id_type[0], id_item) ; ajoutHistorique(id_type[0], id_type[1] , "Supprimer Item") ; viderBuffer(); printf("Vous avez supprimer un item\n"); break; } break; case 51: afficherSoldeRestaurant(id_type[0]) ; ajoutHistorique(id_type[0], id_type[1] , "Afficher solde") ; printf("Votre solde\n"); break; case 'q': return 0; } }while(choix_3 != 'p'); break; case '2': // system("clear"); printf("Vous etes livreur\n"); ajoutHistorique(id_type[0], id_type[1] , "Connexion") ; do{ printf("[1].Pour supprimer \n[2].Pour modifier votre profile \n[3].Pour solde \n[q].Pour quitter \n[p].Pour precedent\n"); scanf("%c", &choix_3); viderBuffer(); switch (choix_3){ case '1': supprimerCompte(id_type[0], id_type[1]) ; ajoutHistorique(id_type[0], id_type[1] , "SupprimerCompte") ; printf("Vous avez supprimer votre compte\n"); return 0; case '2': // TODO: fonction qui prend comme argument l'id et permet de modifier la ligne dans le fichier livreur.csv printf("Vous avez modifier votre profile\n"); break; case '3': afficherSoldeLivreur(id_type[0]) ; ajoutHistorique(id_type[0], id_type[1] , "Afficher solde") ; printf("Votre solde\n"); break; case 'q': return 0; } }while(choix_3 != 'p'); break; case '3': // system("clear"); printf("Vous etes client\n"); ajoutHistorique(id_type[0], id_type[1] , "Connexion") ; do{ printf("[1].Pour supprimer \n[2].Pour modifier votre profile \n[3].Pour solde \n[4].Pour voir la liste des restaurants \n[5].Pour faire une commande \n[q].Pour quitter \n[p].Pour precedent\n"); scanf("%c", &choix_3); viderBuffer(); switch (choix_3){ case '1': supprimerCompte(id_type[0], id_type[1]) ; ajoutHistorique(id_type[0], id_type[1] , "SupprimerCompte") ; printf("Vous avez supprimer votre compte\n"); return 0; case '2': // TODO: fonction qui prend comme argument l'id et permet de modifier la ligne dans le fichier livreur.csv printf("Vous avez modifier votre profile\n"); break; case '3': printf("Votre solde\n"); afficherSoldeClient(id_type[0]) ; ajoutHistorique(id_type[0], id_type[1] , "Afficher solde") ; printf("\n") ; break; case '4': do{ printf("[1].Pour voir qui peut me livrer dans mon secteur\n[2].Pour voir les restaurants selon le type \n[3].Pour les deux \n[q].Pour quitter \n[p].Pour precedent\n"); scanf("%c", &choix_4); viderBuffer(); switch(choix_4){ case '1': afficherRestaurantCodePostal(id_type[0]) ; ajoutHistorique(id_type[0], id_type[1] , "Afficher restaurant par CP") ; break; case '2': printf("Entrer le type qui vous interesse\n") ; char typeClient_1[20] ; scanf("%s" , typeClient_1) ; afficherRestaurantType(typeClient_1) ; ajoutHistorique(id_type[0], id_type[1] , "Afficher restaurant par type") ; viderBuffer(); break; case '3': printf("Entrer le type qui vous interesse\n") ; char typeClient_2[20] ; scanf("%s" , typeClient_2) ; afficherRestaurantCodePostalType(id_type[0], typeClient_2) ; ajoutHistorique(id_type[0], id_type[1] , "Afficher restaurant par combinaisant") ; viderBuffer(); break; case 'q': return 0; } }while(choix_4 != 'p'); break; case '5': do{ printf("[1].Pour voir la liste des items(pas compris le but)\n[2].Pour ajouter un item \n[3].Pour enlever un item \n[4].Pour passer la commande \n[q].Pour quitter \n[p].Pour precedent\n"); scanf("%c", &choix_4); viderBuffer(); switch(choix_4){ // case '1': Pas compris a voir case '2': // liste ListeItems; // On peut faire un structure qui enregistre le nom de l'item et son prix donc liste des structs // TODO: fonction qui retourn une liste avec les items printf("Vous avez ajouté un item\n"); break; case '3': // TODO: fonction qui permet de supprimer un item de la liste des items (ajouter dans case 2) // if (list == NULL){ // break; // puisque la liste est vide //} printf("Vous avez enlevé un item\n"); break; case '4': // if (list == NULL){ // break; // puisque la liste est vide //} // TODO: fonction qui permet de faire faire la somme des prix des elements de la liste, afficher cette somme (total), crediter le montant du profile du client et payer le restaurant et le livreur printf("Vous avez passer la commande\n"); break; case 'q': return 0; } }while(choix_4 != 'p'); break; case 'q': return 0; } }while(choix_3 != 'p'); break; case 'q': return 0; } } while (choix_2 != 112); break; case '2': /************************/ /* Pour créer un compte */ /************************/ do{ printf("[1].Pour restaurateur \n[2].Pour livreur \n[3].Pour client \n[q].Pour quitter \n[p].Pour precedent\n"); scanf("%c", &choix_2); viderBuffer(); char nom[30] ; char codePostal[13]; char telephone[16]; char solde[13]; char menu[30]; char type[20] ; int l ; char id[13] ; char ingredients[40]; char deplacements[40]; char restaurant[30]; switch(choix_2){ case '1': // itoa(generateId("dataBase/tableRestaurants.csv"),id,10); sprintf(id , "%d" ,generateId("dataBase/tableRestaurants.csv")); printf("rentrer votre nom :\n"); scanf("%s", &nom); viderBuffer(); printf("rentrer votre code postal :\n"); scanf("%s", &codePostal); viderBuffer(); printf("rentrer votre telephone :\n"); scanf("%s", &telephone); viderBuffer(); printf("rentrer votre menu ( au moins 1 ) :\n"); scanf("%s", &menu); viderBuffer(); printf("rentrer votre type :\n"); scanf("%s", &type); viderBuffer(); ajoutRestaurateur(ajoutRestaurateurConstructeur( id , nom , codePostal , telephone , type , menu , "0" ), &l , "dataBase/tableRestaurants.csv");// solde = 0 au début ajoutHistorique(atoi(id), 1 , "Crée compte") ; printf("Vous avez creer un compte pour un restaurateur\n"); break; case '2': sprintf(id , "%d" , generateId("dataBase/tableLivreurs.csv")); printf("rentrer votre nom :\n"); scanf("%s", &nom); viderBuffer(); printf("rentrer les deplacements possibles :\n"); scanf("%s", &deplacements); viderBuffer(); printf("rentrer votre telephone :\n"); scanf("%s", &telephone); viderBuffer(); printf("rentrer votre restaurant :\n"); scanf("%s", &restaurant); viderBuffer(); ajoutLivreur(ajoutLivreurConstructeur( id , nom , telephone , deplacements , restaurant , "0" ), &l , "dataBase/tableLivreurs.csv");// solde = 0 au début ajoutHistorique(atoi(id), 2 , "Crée compte") ; printf("Vous avez creer un compte pour un livreur\n"); break; case '3': sprintf(id , "%d" , generateId("dataBase/tableClient.csv")); printf("rentrer votre nom :\n"); scanf("%s", &nom); viderBuffer(); printf("rentrer votre code postal :\n"); scanf("%s", &codePostal); viderBuffer(); printf("rentrer votre telephone :\n"); scanf("%s", &telephone); viderBuffer(); printf("rentrer votre solde en EURO :\n"); scanf("%s", &solde); viderBuffer(); ajoutClient(ajoutClientConstructeur( id , codePostal, telephone , solde , nom ), &l , "dataBase/tableClient.csv"); ajoutHistorique(atoi(id), 3 , "Crée compte") ; printf("Vous avez creer un compte pour un client\n"); break; case 'q': return 0; } }while(choix_2 != 'p'); break; } }while (choix_1 != 'q'); return 0; }
2.625
3
2024-11-18T21:46:54.852944+00:00
2016-03-30T21:20:32
58600343ab1824eb37b8507b0e11e0af05bc7a15
{ "blob_id": "58600343ab1824eb37b8507b0e11e0af05bc7a15", "branch_name": "refs/heads/master", "committer_date": "2016-03-30T21:20:32", "content_id": "1d54e0e8207f10cec05854cf7cf57bb56c73a7d5", "detected_licenses": [ "MIT" ], "directory_id": "8bce02aae905633144857994c316fe1cc82c5075", "extension": "c", "filename": "unix_socket.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": 2278, "license": "MIT", "license_type": "permissive", "path": "/tests/unix_socket.c", "provenance": "stackv2-0130.json.gz:40701", "repo_name": "ChaojiangLuo/libwsm", "revision_date": "2016-03-30T21:20:32", "revision_id": "34743a2240305b3c8f24a2f8e015371ecba57c94", "snapshot_id": "812a78a104f76d3eed579cd9eeae539f0d4a0728", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/ChaojiangLuo/libwsm/34743a2240305b3c8f24a2f8e015371ecba57c94/tests/unix_socket.c", "visit_date": "2023-03-15T20:57:29.682987" }
stackv2
/* Copyright (c) 2014 Martin Peres 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 <sys/socket.h> #include <stdio.h> #include <sys/un.h> #include <unistd.h> #include "unix_socket.h" int unix_socket_server_create(const char *path) { struct sockaddr_un addr; int fd; if ( (fd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) { perror("socket error"); return -1; } memset(&addr, 0, sizeof(addr)); addr.sun_family = AF_UNIX; strncpy(addr.sun_path, path, sizeof(addr.sun_path)-1); unlink(path); if (bind(fd, (struct sockaddr*)&addr, sizeof(addr)) == -1) { perror("bind error"); return -1; } if (listen(fd, 5) == -1) { perror("listen error"); return -1; } return fd; } int unix_socket_server_accept(int fd) { int client_fd; if ( (client_fd = accept(fd, NULL, NULL)) == -1) { perror("accept error"); return -1; } return client_fd; } int unix_socket_client_connect(const char *path) { struct sockaddr_un addr; int fd; if ( (fd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) { perror("socket error"); return -1; } memset(&addr, 0, sizeof(addr)); addr.sun_family = AF_UNIX; strncpy(addr.sun_path, path, sizeof(addr.sun_path)-1); if (connect(fd, (struct sockaddr*)&addr, sizeof(addr)) == -1) { perror("connect error"); return -1; } return fd; }
2.546875
3
2024-11-18T21:46:55.086957+00:00
2012-07-16T08:15:37
013c7955511355bfdfc5dda64bbe45c076dd96f2
{ "blob_id": "013c7955511355bfdfc5dda64bbe45c076dd96f2", "branch_name": "HEAD", "committer_date": "2012-07-16T08:15:57", "content_id": "59a97e390fa186eee243f27a96486140b5059bec", "detected_licenses": [ "Apache-2.0" ], "directory_id": "4eb2262e37ae207d3d7d0698a29de14562df81a1", "extension": "h", "filename": "tPLSocket.h", "fork_events_count": 2, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 4969931, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2155, "license": "Apache-2.0", "license_type": "permissive", "path": "/src/platform_layer/inc/tPLSocket.h", "provenance": "stackv2-0130.json.gz:40831", "repo_name": "Kudo/liblogger", "revision_date": "2012-07-16T08:15:37", "revision_id": "bdb5c534f83bb62d25778c099d0a8892ce088980", "snapshot_id": "fe75e7b00631b7f475b3286cb58a59ded2e8a7a0", "src_encoding": "UTF-8", "star_events_count": 7, "url": "https://raw.githubusercontent.com/Kudo/liblogger/bdb5c534f83bb62d25778c099d0a8892ce088980/src/platform_layer/inc/tPLSocket.h", "visit_date": "2016-09-05T11:43:40.419931" }
stackv2
/* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /** * \file Platform Layer for socket functions. * */ #ifndef __PLSOCKET_H__ #define __PLSOCKET_H__ #if defined(WIN32) || (_WIN32) /* Windows */ #include <winsock2.h> /** Abstract handle for socket. */ typedef SOCKET tPLSocket; #elif defined(__unix) || defined(__linux) || defined(__linux__) || defined(__MACH__) /* A Unix system */ /** Abstract handle for socket. */ typedef int tPLSocket; #else /* Unsupported platform. */ #endif /** Function to create a \b connected socket. * \param [in] server The log server. * \param [in] port The log server port. * \param [out] sock The socket handle. * \returns -1 on failure and \a sock will be -1 , or else 0 on success and sock will be non zero. * */ int PLCreateConnectedSocket(const char* server, int port, tPLSocket *sock); /** Send data over socket. * \param [in] tPLSocket The socket handle created via \ref CreateConnectedSocket. * \param [in] data The data to send. * \param [in] dataSize The size of data. * \return On success, the amount of bytes sent, -1 otherwise. * */ int PLSockSend(tPLSocket sock,const void* data,const int dataSize); /** Close the Socket. * \param [in,out] sock The socket handle created via \ref CreateConnectedSocket. * */ void PLDestroySocket(tPLSocket * sock); #endif // __PLSOCKET_H__
2.0625
2
2024-11-18T21:46:55.165153+00:00
2018-06-06T14:54:09
53da9890960bef4031c267b62032bacc1946080c
{ "blob_id": "53da9890960bef4031c267b62032bacc1946080c", "branch_name": "refs/heads/master", "committer_date": "2018-06-06T14:54:34", "content_id": "ad6452196901a7967f43062d7ad6b3a157d256a0", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "650546c9bec1bf8ad9b7b2b619d2274948f05227", "extension": "h", "filename": "board.h", "fork_events_count": 0, "gha_created_at": "2018-04-02T18:32:39", "gha_event_created_at": "2018-05-19T18:18:51", "gha_language": "C", "gha_license_id": "BSD-3-Clause", "github_id": 127796425, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4632, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/src/board.h", "provenance": "stackv2-0130.json.gz:40961", "repo_name": "khnsky/carcassonne", "revision_date": "2018-06-06T14:54:09", "revision_id": "3fe4a647bb6702576f75934c19cd326f12dae397", "snapshot_id": "806e4fbfcaed666ee154d89cd5bdafb7d01c17e2", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/khnsky/carcassonne/3fe4a647bb6702576f75934c19cd326f12dae397/src/board.h", "visit_date": "2021-05-26T06:07:14.792578" }
stackv2
#ifndef BOARD_H #define BOARD_H /** @file board.h */ #include "tile.h" #include "logic.h" #include <stdbool.h> #include <stddef.h> typedef tile*** board_t; typedef struct { board_t tiles; size_t size; } sized_board; /** * get size of the game board interactily. * @return size of the board */ size_t board_get_size_interactive(); /** * get size of the game board traversing trough file. * @param fliename name of the board file * @return size of the board, (return size of the current board, need to add margin) */ size_t board_get_size(const char*); /** * allocates a board and sets all tiles to empty (null). * remeber to free this, you can use {@code board_free} for this * @param [in] size size of a board side * @return board */ board_t board_alloc(size_t); /** * returns struct sized_board, sets size and allocates fields, parses board in auto mode. * arguements only used in auto mode * @param [in] mode game mode * @param [in] filename name of board file * @param [out] board sized_board pointer * @return success of operation */ bool board_init(gamemode, const char*, sized_board*); /** * inits board, exit on error. * @param [in] mode game mode * @param [in] filename name of the board file * @return initialized board */ sized_board board_init_exit_on_err(gamemode, const char*); /** * frees array of tile pointers * @param [in] board game board pointer */ void board_free(sized_board*); /** * check if board has no tiles on it. * @param [in] board game board * @return if board is empty */ bool board_is_empty(const sized_board*); /** * check if specified tile can be placed in specified place on board. * @param [in] board pointer to game board * @param [in] t tile pointer * @param [in] y y coordinate of placement * @param [in] x x coordinate of placement * @return if can place tile */ bool tile_can_place(const sized_board*, const tile*, size_t, size_t); /** * rotation in which tile can be placed in the cell * @param [in] board * @param [in] tile * @param h height at which to check if can place * @param w width at which to check * @param rotation with which tile can be placed, if tile can't be placed return ROT_NO */ rotation_t tile_can_place_rotated(const sized_board*, const tile*, size_t, size_t); /** * place tile in specified location. * @param [out] place * @param [in] t tile to place */ void tile_place(tile**, tile*); /** * assign tile pointers to board array based on specified file * @param [in] filename board file name * @param [in, out] board game board * @return success of operation */ bool board_parse(const char*, sized_board*); /** * prints out board. * @param board pointer to sized_board to print */ void board_print(const sized_board*); /** * prints the board with x on empty cells on which tile specified could be placed. * @param [in] board game board pointer * @param [in] t tile pointer */ void board_print_legal_moves(const sized_board*, tile*); /** * write board to file. * @param [in] board tile pointer array portraying board * @param [in] filename board file name * @return success of operation */ bool board_write(const sized_board*, const char*); /** * copy tiles from board src to board dest with offset h height and w width, * if dest board had allocated tiles they are not free - memory leak. * @param [in] src pointer to source board * @param [in] h height offset * @param [in] w width offset * @param [out] dest pointer to destination board */ void board_copy_offsetted(const sized_board*, ptrdiff_t, ptrdiff_t, sized_board*); /** * copy tiles from board src to board dest, * if dest board had allocated tiles they are not free - memory leak. * @param [in] src pointer to source board * @param [out] dest pointer to destination board */ void board_copy(const sized_board*, sized_board*); /** * move tiles on the board by h height and w width, * pointers to original board tiles become invalid. * @param [in] h height offset * @param [in] w width offset * @param [out] board with moved tiles */ void board_move(ptrdiff_t, ptrdiff_t, sized_board*); /** * resize board, * pointers to original board tiles become invalid. * @param [in] size new size of the board * @param [in, out] board to resize */ void board_resize(size_t, sized_board*); /** * checks if a specific tile has a neighbours * @param [in] board to resize * @param [in] row of a tile * @param [in] column of a tile * @return true is a tile has at elat 1 neighbour */ bool board_tileHasNeighbour(const sized_board* board, size_t i, size_t j); void board_trim(sized_board* board); #endif
2.40625
2
2024-11-18T21:46:55.903561+00:00
2012-08-24T07:22:03
534663fd2d559e4aa8a9c089b91eba77bb0bb725
{ "blob_id": "534663fd2d559e4aa8a9c089b91eba77bb0bb725", "branch_name": "refs/heads/master", "committer_date": "2012-08-24T07:33:11", "content_id": "d0b01551b3652b69f701f56b3e189ffa26c0c58c", "detected_licenses": [ "Apache-2.0" ], "directory_id": "cf90425309f1772b8a663e37a6725e8eb1c03644", "extension": "c", "filename": "call.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 56155945, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 7246, "license": "Apache-2.0", "license_type": "permissive", "path": "/src/call.c", "provenance": "stackv2-0130.json.gz:41733", "repo_name": "tizenorg/platform.core.api.call", "revision_date": "2012-08-24T07:22:03", "revision_id": "b1495a395a8f8bbc0ae1938084b8a6c659e86fd1", "snapshot_id": "1d38390178a257cf94a99e44fe6c81840d63e99d", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/tizenorg/platform.core.api.call/b1495a395a8f8bbc0ae1938084b8a6c659e86fd1/src/call.c", "visit_date": "2021-01-01T05:21:37.086938" }
stackv2
/* * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved * * 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 <stdio.h> #include <stdlib.h> #include <string.h> #include <call.h> #include <vconf.h> #include <vconf-keys.h> #include <dlog.h> #include <glib.h> #ifdef LOG_TAG #undef LOG_TAG #endif #define LOG_TAG "TIZEN_N_CALL" typedef struct _call_cb_data { call_state_e previous_state; // previous call state const void* state_changed_cb; // call_state_changed_cb void* user_data; // user data } call_cb_data; static bool is_registered = false; // whether vconf_notify_key_changed is registered or not static call_cb_data voice_call_cb = {CALL_STATE_IDLE, NULL, NULL}; static call_cb_data video_call_cb = {CALL_STATE_IDLE, NULL, NULL}; // Internal Macros #define CALL_CHECK_INPUT_PARAMETER(arg) \ if( arg == NULL ) \ { \ LOGE("[%s] INVALID_PARAMETER(0x%08x)", __FUNCTION__, CALL_ERROR_INVALID_PARAMETER); \ return CALL_ERROR_INVALID_PARAMETER; \ } // Callback function adapter static void __call_state_changed_cb_adapter(keynode_t *node, void* user_data) { call_state_e current_call_state = CALL_STATE_IDLE; // Check whether the state of voice call is changed if( voice_call_cb.state_changed_cb != NULL ) { if( call_get_voice_call_state(&current_call_state) == CALL_ERROR_NONE ) { if( voice_call_cb.previous_state != current_call_state ) { ((call_state_changed_cb)(voice_call_cb.state_changed_cb))(current_call_state, voice_call_cb.user_data); voice_call_cb.previous_state = current_call_state; } } } // Check whether the state of video call is changed if( video_call_cb.state_changed_cb != NULL ) { if( call_get_video_call_state(&current_call_state) == CALL_ERROR_NONE ) { if( video_call_cb.previous_state != current_call_state ) { ((call_state_changed_cb)(video_call_cb.state_changed_cb))(current_call_state, video_call_cb.user_data); video_call_cb.previous_state = current_call_state; } } } } int call_get_voice_call_state(call_state_e *call_state) { int vconf_value = 0; CALL_CHECK_INPUT_PARAMETER(call_state); if( vconf_get_int(VCONFKEY_CALL_STATE, &vconf_value) != 0 ) { LOGE("[%s] OPERATION_FAILED(0x%08x) : failed to get call state", __FUNCTION__, CALL_ERROR_OPERATION_FAILED); return CALL_ERROR_OPERATION_FAILED; } if( vconf_value == VCONFKEY_CALL_VOICE_CONNECTING ) { LOGI("[%s] The state of voice call is CALL_STATE_CONNECTING", __FUNCTION__); *call_state = CALL_STATE_CONNECTING; } else if( vconf_value == VCONFKEY_CALL_VOICE_ACTIVE ) { LOGI("[%s] The state of voice call is CALL_STATE_ACTIVE", __FUNCTION__); *call_state = CALL_STATE_ACTIVE; } else { LOGI("[%s] The state of voice call is CALL_STATE_IDLE", __FUNCTION__); *call_state = CALL_STATE_IDLE; } return CALL_ERROR_NONE; } int call_get_video_call_state(call_state_e *call_state) { int vconf_value = 0; CALL_CHECK_INPUT_PARAMETER(call_state); if( vconf_get_int(VCONFKEY_CALL_STATE, &vconf_value) != 0 ) { LOGE("[%s] OPERATION_FAILED(0x%08x) : failed to get call state", __FUNCTION__, CALL_ERROR_OPERATION_FAILED); return CALL_ERROR_OPERATION_FAILED; } if( vconf_value == VCONFKEY_CALL_VIDEO_CONNECTING ) { LOGI("[%s] The state of video call is CALL_STATE_CONNECTING", __FUNCTION__); *call_state = CALL_STATE_CONNECTING; } else if( vconf_value == VCONFKEY_CALL_VIDEO_ACTIVE ) { LOGI("[%s] The state of video call is CALL_STATE_ACTIVE", __FUNCTION__); *call_state = CALL_STATE_ACTIVE; } else { LOGI("[%s] The state of video call is CALL_STATE_IDLE", __FUNCTION__); *call_state = CALL_STATE_IDLE; } return CALL_ERROR_NONE; } int call_set_voice_call_state_changed_cb(call_state_changed_cb callback, void* user_data) { call_state_e voice_call_state = CALL_STATE_IDLE; CALL_CHECK_INPUT_PARAMETER(callback); if( call_get_voice_call_state(&voice_call_state) != CALL_ERROR_NONE ) { LOGE("[%s] OPERATION_FAILED(0x%08x) : fail to get the current state of voice call", __FUNCTION__, CALL_ERROR_OPERATION_FAILED); return CALL_ERROR_OPERATION_FAILED; } if( is_registered == false ) { if( vconf_notify_key_changed(VCONFKEY_CALL_STATE, (vconf_callback_fn)__call_state_changed_cb_adapter, NULL) != 0 ) { LOGE("[%s] OPERATION_FAILED(0x%08x) : fail to register callback function", __FUNCTION__, CALL_ERROR_OPERATION_FAILED); return CALL_ERROR_OPERATION_FAILED; } is_registered = true; } voice_call_cb.previous_state = voice_call_state; voice_call_cb.state_changed_cb = callback; voice_call_cb.user_data = user_data; return CALL_ERROR_NONE; } int call_unset_voice_call_state_changed_cb() { if( video_call_cb.state_changed_cb == NULL && is_registered == true ) { if( vconf_ignore_key_changed(VCONFKEY_CALL_STATE, (vconf_callback_fn)__call_state_changed_cb_adapter) != 0 ) { LOGE("[%s] OPERATION_FAILED(0x%08x) : fail to unregister callback function", __FUNCTION__, CALL_ERROR_OPERATION_FAILED); return CALL_ERROR_OPERATION_FAILED; } is_registered = false; } voice_call_cb.previous_state = CALL_STATE_IDLE; voice_call_cb.state_changed_cb = NULL; voice_call_cb.user_data = NULL; return CALL_ERROR_NONE; } int call_set_video_call_state_changed_cb(call_state_changed_cb callback, void* user_data) { call_state_e video_call_state = CALL_STATE_IDLE; CALL_CHECK_INPUT_PARAMETER(callback); if( call_get_video_call_state(&video_call_state) != CALL_ERROR_NONE ) { LOGE("[%s] OPERATION_FAILED(0x%08x) : fail to get the current state of video call", __FUNCTION__, CALL_ERROR_OPERATION_FAILED); return CALL_ERROR_OPERATION_FAILED; } if( is_registered == false ) { if( vconf_notify_key_changed(VCONFKEY_CALL_STATE, (vconf_callback_fn)__call_state_changed_cb_adapter, NULL) != 0 ) { LOGE("[%s] OPERATION_FAILED(0x%08x) : fail to register callback function", __FUNCTION__, CALL_ERROR_OPERATION_FAILED); return CALL_ERROR_OPERATION_FAILED; } is_registered = true; } video_call_cb.previous_state = video_call_state; video_call_cb.state_changed_cb = callback; video_call_cb.user_data = user_data; return CALL_ERROR_NONE; } int call_unset_video_call_state_changed_cb() { if( voice_call_cb.state_changed_cb == NULL && is_registered == true ) { if( vconf_ignore_key_changed(VCONFKEY_CALL_STATE, (vconf_callback_fn)__call_state_changed_cb_adapter) != 0 ) { LOGE("[%s] OPERATION_FAILED(0x%08x) : fail to unregister callback function", __FUNCTION__, CALL_ERROR_OPERATION_FAILED); return CALL_ERROR_OPERATION_FAILED; } is_registered = false; } video_call_cb.previous_state = CALL_STATE_IDLE; video_call_cb.state_changed_cb = NULL; video_call_cb.user_data = NULL; return CALL_ERROR_NONE; }
2.09375
2
2024-11-18T21:46:56.061068+00:00
2020-03-16T18:21:54
582a663645ff80574954e22c534c337ef05e2893
{ "blob_id": "582a663645ff80574954e22c534c337ef05e2893", "branch_name": "refs/heads/master", "committer_date": "2020-03-16T18:21:54", "content_id": "b77b1605e649e92d597cfc139d8f538fe76b502c", "detected_licenses": [ "Apache-2.0" ], "directory_id": "7d231cf89a41c959030100db25e57c40df5ac313", "extension": "c", "filename": "Debug_Serial_Init.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 247774802, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 646, "license": "Apache-2.0", "license_type": "permissive", "path": "/L21_AES_CODE/L21_AES/src/init/Debug_Serial_Init.c", "provenance": "stackv2-0130.json.gz:41861", "repo_name": "adithyayuri/AES-128_Encrypt", "revision_date": "2020-03-16T18:21:54", "revision_id": "c71fa5ef5283683b0a9f009907d025404a04b6d3", "snapshot_id": "1081ed76c4b63231c475fd6ac6eff5ba3b78e1a8", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/adithyayuri/AES-128_Encrypt/c71fa5ef5283683b0a9f009907d025404a04b6d3/L21_AES_CODE/L21_AES/src/init/Debug_Serial_Init.c", "visit_date": "2021-03-27T01:57:54.435619" }
stackv2
/* * debugSerialInit.c * * Created: 03-12-2017 04:21:33 PM * Author: YURI */ #include "Debug_Serial_Init.h" void debug_serial_init() { struct usart_config config_usart; usart_get_config_defaults(&config_usart); config_usart.baudrate = 9600; config_usart.mux_setting = EDBG_CDC_SERCOM_MUX_SETTING; config_usart.pinmux_pad0 = EDBG_CDC_SERCOM_PINMUX_PAD0; config_usart.pinmux_pad1 = EDBG_CDC_SERCOM_PINMUX_PAD1; config_usart.pinmux_pad2 = EDBG_CDC_SERCOM_PINMUX_PAD2; config_usart.pinmux_pad3 = EDBG_CDC_SERCOM_PINMUX_PAD3; stdio_serial_init(&usart_instance, EDBG_CDC_MODULE, &config_usart); usart_enable(&usart_instance); }
2.09375
2
2024-11-18T21:46:56.258416+00:00
2014-11-03T23:07:33
2bbbb269399b4946e6e92961e462783dcb135dbe
{ "blob_id": "2bbbb269399b4946e6e92961e462783dcb135dbe", "branch_name": "refs/heads/master", "committer_date": "2014-11-03T23:07:33", "content_id": "e78b53a1a6d84fdcd5fb5fa9afca9ad74f404d05", "detected_licenses": [ "MIT" ], "directory_id": "3b0fb5048dd4aff3b9f078fb01353799be95bda6", "extension": "c", "filename": "hjem2.c", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 14315349, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 197, "license": "MIT", "license_type": "permissive", "path": "/l2/hjem2.c", "provenance": "stackv2-0130.json.gz:42119", "repo_name": "Medeah/IMPR", "revision_date": "2014-11-03T23:07:33", "revision_id": "2806a58ca78da7a0891b940f81a882c3433750a0", "snapshot_id": "a9ad2c7a9fffb2f466be6c51694246bfecad350e", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Medeah/IMPR/2806a58ca78da7a0891b940f81a882c3433750a0/l2/hjem2.c", "visit_date": "2021-01-01T19:11:12.473619" }
stackv2
/* Programmeringsopgave 2 side 88 i Problem Solving and Program Design in C, seventh edition. */ #include <stdio.h> int main (void) { int n = 42; printf ("The value of n is %d.\n", n); }
3.03125
3
2024-11-18T21:46:56.359025+00:00
2021-11-25T22:27:12
18dd9738071a4a79b056220b33a54650d8c224e7
{ "blob_id": "18dd9738071a4a79b056220b33a54650d8c224e7", "branch_name": "refs/heads/master", "committer_date": "2021-11-25T22:27:12", "content_id": "8426b423ee6174aa4c629dbf93e4ce0e16fa65e3", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "bade93cbfc1f25160dfbe9493bfa83f853326475", "extension": "c", "filename": "mmu.c", "fork_events_count": 6, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 214182273, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 36859, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/mwc/romana/relic/b/kernel/i386/mmu.c", "provenance": "stackv2-0130.json.gz:42248", "repo_name": "gspu/Coherent", "revision_date": "2021-11-25T22:27:12", "revision_id": "299bea1bb52a4dcc42a06eabd5b476fce77013ef", "snapshot_id": "c8a9b956b1126ffc34df3c874554ee2eb7194299", "src_encoding": "UTF-8", "star_events_count": 26, "url": "https://raw.githubusercontent.com/gspu/Coherent/299bea1bb52a4dcc42a06eabd5b476fce77013ef/mwc/romana/relic/b/kernel/i386/mmu.c", "visit_date": "2021-12-01T17:49:53.618512" }
stackv2
/* * MMU dependent code for Coherent 386 * * Copyright (c) Ciaran O'Donnell, Bievres (FRANCE), 1991 */ #include <sys/coherent.h> #include <sys/clist.h> #include <errno.h> #include <sys/inode.h> #include <sys/seg.h> #include <signal.h> #include <sys/buf.h> #include <sys/alloc.h> #include <l.out.h> #include <ieeefp.h> /* These defines belong somewhere else: */ #define LOMEM 0x15 /* CMOS address of size in K of memory below 1MB. */ #define EXTMEM 0x17 /* CMOS address of size in K of memory above 1MB. */ #define ONE_K 1024 #define ONE_MEG 1048576 #define USE_NDATA 1 /* * DMA will not work to memory above 16M, so limit the amount of memory * above 1M to 15M. A much cleverer scheme should be implemented. */ int HACK_LIMIT = (15*ONE_MEG); /* * For 0 < i < 64, buddysize[i] is log(base 2) of nearest power of two * which is greater than or equal to i. */ char buddysize[64] = { -1, 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6 }; #define min(a, b) ((a) < (b) ? (a) : (b)) /* * Functions. * Import. * Export. * Local. */ void areacheck(); void areafree(); void areainit(); BLOCKLIST * arealloc(); int areasize(); cseg_t * c_alloc(); cseg_t * c_extend(); void c_free(); int c_grow(); int countsize(); void doload(); char * getPhysMem(); void i8086(); void idtinit(); void init_phy_seg(); void mchinit(); void msigend(); void msigstart(); void physMemInit(); SR *loaded(); unsigned int read16_cmos(); void segload(); void sunload(); void unload(); void valloc(); #define zero_fill(from, len) memset(from, 0, len) /* * "load" a handle "hp" to a segment into the space tree for a process */ void doload(srp) register SR *srp; { register int n; register cseg_t *pp; register int base1, flags; register int akey; pp = srp->sr_segp->s_vmem; flags = srp->sr_segp->s_flags; base1 = btocrd(srp->sr_base); n = btoc(srp->sr_size); /* * we load all pages */ /* a shm segment ref may be Read-Write or Read-Only */ if (srp->sr_flag & SRFRODT) akey = SEG_RO; else { switch (flags&(SFSYST|SFTEXT)) { case SFTEXT: akey = SEG_RO; break; case SFSYST: akey = SEG_SRW; break; default: akey = SEG_RW; break; } } do ptable1_v[base1++] = (*pp++ & ~SEG_NPL) | akey; while (--n); mmuupd(); } /* * unload a handle key "key" to a segment from the MMU hardware */ void unload(srp) register SR *srp; { register int n, base1; base1 = btocrd(srp->sr_base); n = btoc(srp->sr_size); do { ptable1_v[base1++] = SEG_ILL; } while (--n); mmuupd(); } /* * Allocate 'clicks_wanted' clicks of core space. * Returns physical segment descriptor if success, else NULL. * The physical segment descriptor is a table of page table entries * suitable for insertion into a page table. */ cseg_t * c_alloc(clicks_wanted) unsigned clicks_wanted; { unsigned pno; cseg_t *pp; register cseg_t *qp; /* Do we have enough free physical clicks for this request? */ if (clicks_wanted > allocno()) goto no_c_alloc; /* Allocate some space for the table to return. */ if ((pp = (cseg_t *)arealloc(clicks_wanted)) == 0) goto no_c_alloc; qp = pp; /* fill in entries in the requested table */ do { pno = *--sysmem.pfree; if (!pvalid(pno)) panic("c_alloc"); *qp++ = (clickseg(pno) & ~SEG_BITS) | SEG_PRE; } while (--clicks_wanted); return pp; no_c_alloc: return 0; } /* * Given an array "pp" containing "numClicks" click descriptors, * if "pp" is the click list for a user segment currently loaded * invalidate click entries for "pp" in the current page table * return each click in "pp" to the sysmem pool, if it came from there. * return the array "pp" to the buddy pool. */ void c_free(pp, numClicks) cseg_t *pp; unsigned numClicks; { unsigned pno; register cseg_t *qp; register int sz; SR *srp; if (srp = loaded(pp)) { unload(srp); srp->sr_segp = 0; } sz = numClicks; if (&sysmem.pfree[sz] > sysmem.efree) panic("c_free - nalloc"); qp = pp; do { if ((*qp & SEG_NPL) == 0) { pno = segclick(*qp); if (!pvalid(pno)) panic("c_free"); *sysmem.pfree++ = pno; } else { T_HAL(0x40000, printf("c_free NPL %x ", *qp)); } qp++; } while (--sz); areafree((BLOCKLIST *)pp, numClicks); } /* * Given a user virtual address, a physical address, and a byte * count, map the specified virtual address into the user data * page table for the current process. * * This is meant to be called from the console ioctl, KDMAPDISP. * The user virtual address must be click aligned. * The range of physical addresses must lie outside installed RAM * or within the "PHYS_MEM" pool. * * Return 1 on success, else 0. */ int mapPhysUser(virtAddr, physAddr, numBytes) { int ret = 0; SR * srp = u.u_segl + SIPDATA; SEG * sp = srp->sr_segp; cseg_t * pp = sp->s_vmem, * qp; int pno, clickOffset, numClicks, i; /* Check alignment. */ if ((virtAddr & (NBPC-1)) || (physAddr & (NBPC-1))) { T_HAL(0x40000, printf("mPU: failed alignment ")); goto mPUdone; } /* Check validity of range of virtual addresses. */ if (virtAddr < srp->sr_base || (virtAddr + numBytes) >= (srp->sr_base + srp->sr_size)) { T_HAL(0x40000, printf("mPU: bad vaddr ")); goto mPUdone; } /* Check validity of range of physical addresses. */ /* if not in PHYS_MEM pool... */ if (!physValid(physAddr, numBytes)) { /* get installed RAM physical addresses */ unsigned int physLow = ctob((read16_cmos(LOMEM) + 3) >> 2); unsigned int physHigh = ctob((read16_cmos(EXTMEM) + 3) >> 2) + ONE_MEG; T_HAL(0x40000, printf("physLow=%x physHigh=%x ", physLow, physHigh)); /* Fail if physical range overlaps installed base RAM. */ if (physAddr < physLow) { T_HAL(0x40000, printf("mPU: overlap base RAM ")); goto mPUdone; } /* Fail if physical range overlaps installed extended RAM. */ if (physAddr < physHigh && (physAddr + numBytes) >= ONE_MEG) { T_HAL(0x40000, printf("mPU: overlap extended RAM ")); goto mPUdone; } } /* * For each click in user data segment which is to be remapped * if current click was taken from sysmem pool * return current click to sysmem pool * write new physical address into current click entry * mark current click as not coming from sysmem pool * map current click into page table */ clickOffset = btocrd(virtAddr - srp->sr_base); numClicks = numBytes >> BPCSHIFT; for (qp = pp + clickOffset, i = 0; i < numClicks; i++, qp++) { if ((*qp & SEG_NPL) == 0) { pno = segclick(*qp); if (!pvalid(pno)) { T_HAL(0x40000, printf("mPU: bad release ")); } else { *sysmem.pfree++ = pno; T_HAL(0x40000, printf("mPU: freeing virtual click %x ", virtAddr + ctob(i))); } } else { T_HAL(0x40000, printf("mPU: rewriting virtual NPL click %x ", virtAddr + ctob(i))); } *qp = (physAddr + ctob(i)) | (SEG_RW | SEG_NPL); ptable1_v[btocrd(virtAddr) + i] = *qp; } mmuupd(); ret = 1; mPUdone: return ret; } /* * Add a click to a segment. * Enlarge buddy table for segment, if needed. * * Arguments: * pp points to segment reference table (segp->s_vmem, e.g.) * osz is old segment size, in clicks * * Return pointer to enlarged segment reference table, or NULL if failed. */ cseg_t * c_extend(pp, osz) register cseg_t *pp; int osz; { register cseg_t *pp1; register unsigned pno; register int i; SR *srp; /* Fail if no more free clicks available. */ if (sysmem.pfree < &sysmem.tfree[1]) goto no_c_extend; /* Don't grow segment beyond hardware segment size (4 megabytes). */ if (osz >= (NBPS/NBPC)) goto no_c_extend; if (srp = loaded(pp)) { unload(srp); srp->sr_segp = 0; } /* * If the old size was a power of 2, it has used up an entire * buddy area, so we will need to allocate more space. */ if (IS_POW2(osz)) { if ((pp1 = (cseg_t*) arealloc(osz+1))==0) goto no_c_extend; for (i=0; i < osz; i++) pp1[i] = pp[i]; areafree(pp, osz); pp = pp1; } for (i=osz; --i >= 0;) pp[i+1] = pp[i]; pno = *--sysmem.pfree; if (!pvalid(pno)) panic("c_extend"); pp[0] = clickseg(pno) | SEG_RW; return pp; no_c_extend: return 0; } /* * Given segment size in bytes, estimate total space needed * to keep track of the segment (I think - hws). * * return value is num_bytes plus some overhead... */ int countsize(num_bytes) int num_bytes; { int ret; if (num_bytes <= NBPC/sizeof(long)) ret = num_bytes+1; else ret = num_bytes + ((num_bytes + NBPC/sizeof(long) - 1) >> BPC1SHIFT) + 1; return ret; } /* * buddy allocation */ /* * Deallocate a segment descriptor area. * "sp" is not really a BLOCKLIST*, rather a cseg_t *. * "numClicks" is the number of clicks referenced in the area. */ void areafree(sp, numClicks) BLOCKLIST *sp; int numClicks; { register int n; /* adresse du buddy, taille du reste */ register int ix, nx; register BLOCKLIST *buddy; areacheck(2, sp); /* * Pointer "sp" points to an element in the sysmem table of * free clicks. * Integer "ix" is the index of "sp" into that table. * Will use "ix" to index into one or more buddy tables. */ ix = sp - sysmem.u.budtab; n = areasize(numClicks); do { /* "nx" is index of buddy element to the one at "ix". */ nx = BUDDY(ix, n); if (sysmem.budfree[nx>>WSHIFT] & 1<<(nx&(WCOUNT-1))) { /* coalesce two buddies */ buddy = sysmem.u.budtab + nx; if (buddy->kval != n) break; sysmem.budfree[nx>>WSHIFT] &= ~ (1<<(nx & (WCOUNT-1))); DELETE2(buddy); if (nx < ix) ix = nx; } else break; } while (++n < NBUDDY); sysmem.budfree[ix>>WSHIFT] |= 1 << (ix & (WCOUNT-1)); buddy = sysmem.u.budtab + ix; INSERT2(BLOCKLIST, buddy, &sysmem.bfree[n]); buddy->kval = n; areacheck(3, buddy); } /* * arealloc() * * Given size in "clicks" of a segment to manage, * return pointer to an array of enough descriptors. * If not enough free descriptors available, return 0. */ BLOCKLIST * arealloc(clicks) register int clicks; { register BLOCKLIST *sp; register BLOCKLIST *p, *q; register int size; BLOCKLIST *rsp; register int nx; areacheck(0, 0); size = areasize(clicks); /* * 1. Find little end, bloc p, free >= size */ for (q = p = sysmem.bfree + size;p->forw == p; size++, p++) if (p >= sysmem.bfree + NBUDDY - 1) { return(0); /* y en a pas */ } rsp = p->forw; DELETE2(rsp); nx = rsp - sysmem.u.budtab; sysmem.budfree[nx>>WSHIFT] &= ~(1 << (nx & (WCOUNT-1))); size = 1<<size; sp = rsp + size; /* buddy address */ while (p-- != q) { /* * 2.1 The block is too big, uncouple & free buddy */ sp -= (size >>= 1); nx = sp - sysmem.u.budtab; sysmem.budfree[nx>>WSHIFT] |= 1 << (nx & (WCOUNT-1)); INSERT2(BLOCKLIST, sp, p); sp->kval = p - sysmem.bfree; } areacheck(1, rsp); return rsp; } void areainit(n) { extern char __end[]; register int i; for (i=0; i < (1<<(NBUDDY-WSHIFT)); i++) sysmem.budfree[i] = 0; for (i=0; i<NBUDDY; i++) INIT2(&sysmem.bfree[i]); sysmem.u.budtab = (BLOCKLIST *)__end; n /= sizeof(BLOCKLIST); if (n > (1 << NBUDDY)) panic("areainit"); for (i=0; i<n; i++) areafree(&sysmem.u.budtab[i], sizeof(BLOCKLIST)/sizeof(long)); } /* * areasize() * * Do a log(base 2) calculation on n. * If n is zero, return -1. * * Else, consider the nearest power of two which is greater than or * equal to n * p/2 < n <= p * Then set p = 4 * (2**x). Note BLKSZ is 2. * Return max(x,0). * * If n is too large (more than 3F00), we will go beyond the limits of * table buddysize[]. * * In practice, n is the total number of clicks needed in a segment, * and the return value will be used to access a buddy system list. */ int areasize(n) register unsigned int n; { register int m; #ifdef FROTZ int ret, oldn = n; #endif if (n > 0x3F00) panic("areasize"); n = (n + (1 << BLKSZ) - 1) >> BLKSZ; m = n & 0x3F; #ifdef FROTZ if ((n >>= 6) == 0) ret = buddysize[m]; else { int index; index = n; if (m) index++; ret = buddysize[index] + 6; } return ret; #else if ((n >>= 6) == 0) return buddysize[m]; return buddysize[n + ((m!=0)?1:0)] + 6; #endif } #define MAXBUDDY 2048 #define CHECK(p) ((p>=&sysmem.bfree[0] && p<&sysmem.bfree[NBUDDY]) || \ (p>=sysmem.u.budtab && p<&sysmem.u.budtab[1<<NBUDDY])) void areacheck(flag, sp) register BLOCKLIST *sp; { register BLOCKLIST *next, *start; register int i, nx; if (sp) { if (&sysmem.u.budtab[sp-sysmem.u.budtab] != sp) printf("*check* %d %x %x\n", flag, sp, sysmem.u.budtab); } for (i=0; i<NBUDDY; i++) { start = next = &sysmem.bfree[i]; do { next = next->forw; if (!CHECK(next)) printf("next = %x (%d)\n", next, flag); if (next->back != start) printf("%x->forw->back != %x\n", next, start); if (next != &sysmem.bfree[i]) { if (next->kval != i) printf("bad kval %x, %d (%d)\n", next, next->kval, flag); nx = next - sysmem.u.budtab; if ((sysmem.budfree[nx>>WSHIFT] & (1 << (nx & (WCOUNT-1)))) == 0) printf("in bfree but not budfree %x (%d)\n", next, flag); } start = next; } while (next != &sysmem.bfree[i]); } } MAKESR(physMem, _physMem); int PHYS_MEM = 0; /* Number of bytes of contiguous RAM needed */ /* * A block of contiguous physical memory has been allocated for special * i/o devices. * Problem: clicks of physical memory are in reverse order in the * page table. * This routine reverses the page table entries for the pages * involved. It relies *heavily* on all pages having virtual addresses * in the FFCx xxxx segment. * * If all goes well, assign physAvailStart to the virtual address of * the beginning of the region, and physAvailBytes to the number of bytes * in the region. Otherwise, leave physAvailStart and physAvailBytes at 0. * * As memory is allocated, physAvailStart advances to point to the next * available byte of contiguous memory, physAvailBytes is decremented, * and physPoolStart remains set to the virtual address of the start of * the contiguous pool. */ static int physPoolStart; /* start of contiguous memory area */ static int physAvailStart; /* next free byte in contiguous memory area */ static int physAvailBytes; /* number of bytes in contiguous memory area */ /* * Check whether a range of physical addresses lies within the * pool of contiguous physical memory. */ int physValid(base, numBytes) unsigned int base, numBytes; { int vpool; int ret = 0; if (PHYS_MEM) { vpool = vtop(physPoolStart); T_HAL(0x40000, printf("PHYS_MEM phys addrs %x to %x ", vpool, vpool + PHYS_MEM)); if (base >= vpool && (base + numBytes) <= (vpool + PHYS_MEM)) ret = 1; } else { T_HAL(0x40000, printf("No PHYS_MEM ")); } T_HAL(0x40000, printf("physValid(%x, %x) = %d ", base, numBytes, ret)); return ret; } void physMemInit() { int m, vaddr; int err = 0, num_clicks = btoc(PHYS_MEM); int prevPaddr, paddr; /* * Going half way into page table for physMem * If entry and its complementary entry aren't both in top segment * Error exit (no phys mem will be available). * Get page table entries and swap them. */ for (m = 0; m < num_clicks/2; m++) { int m2 = num_clicks - 1 - m; /* complementary index */ /* compute virtual addresses */ int lo_addr = physMem.sr_base + ctob(m); int hi_addr = physMem.sr_base + ctob(m2); /* compute indices into page table (ptable1_v) */ int lo_p1ix = btocrd(lo_addr); int hi_p1ix = btocrd(hi_addr); /* fetch physical addresses from page table */ int lo_paddr = ptable1_v[lo_p1ix]; int hi_paddr = ptable1_v[hi_p1ix]; /* abort if either address is not in top segment */ if (btosrd(lo_addr) != 0x3FF) { err = 1; break; } if (btosrd(hi_addr) != 0x3FF) { err = 1; break; } /* exchange page table entries */ ptable1_v[lo_p1ix] = hi_paddr; ptable1_v[hi_p1ix] = lo_paddr; } /* * Final sanity check. * In case someone gets creative with startup code, check * again here that the memory is actually contiguous. */ prevPaddr = vtop(physMem.sr_base); for (m = 0; m < num_clicks - 1; m++) { paddr = vtop(physMem.sr_base + ctob(m + 1)); if (paddr - prevPaddr != NBPC) { err = 1; break; } prevPaddr = paddr; } if (!err) { physPoolStart = physAvailStart = physMem.sr_base; physAvailBytes = PHYS_MEM; } } /* * Return virtual address of block of contiguous physical memory. * If request cannot be granted, return 0. * * Expect physMem resource to be granted during load routine of device * drivers. Once allocated, memory is not returned to the physMem pool. */ char * getPhysMem(numBytes) unsigned int numBytes; { char * ret = NULL; if (numBytes <= physAvailBytes) { ret = (char *)physAvailStart; physAvailStart += numBytes; physAvailBytes -= numBytes; } else printf("getPhysMem failed - %d additional bytes " "PHYS_MEM needed\n", physAvailBytes - numBytes); return ret; } /* * Return virtual address of aligned block of contiguous physical memory. * Mainly for devices using the stupid Intel DMA hardware without * scatter/gather. * If request cannot be granted, return 0. * * Argument "align" says what physical boundary we need alignment on. * It must be a power of 2. * For 4k alignment, align = 4k, etc. * Sorry, but will throw away memory to get to the next acceptable address. * * Once allocated, memory is not returned to the physMem pool. */ char * getDmaMem(numBytes, align) unsigned int numBytes; unsigned int align; { char * ret = NULL; int wastedBytes, neededBytes; if (align == 0) { printf("getDmaMem(0) (?)\n"); goto getDmaMemDone; } if (!IS_POW2(align)) { printf("getDmaMem(%x) (?)\n", align); goto getDmaMemDone; } /* * Waste RAM from bottom of pool up to physical * address with desired alignment. */ wastedBytes = align - (vtop(physAvailStart) % align); neededBytes = numBytes + wastedBytes; if (neededBytes <= physAvailBytes) { ret = (char *)physAvailStart + wastedBytes; physAvailStart += neededBytes; physAvailBytes -= neededBytes; } else printf("getDmaMem failed - %d additional bytes " "PHYS_MEM needed\n", physAvailBytes - neededBytes); getDmaMemDone: return ret; } /***************/ #undef ptable1_v /* * pageDir is the physical address of the click in use for the page * directory, offset by ctob(SBASE - PBASE) */ #define pageDir ((long *)(&stext[ctob(-1)])) int total_clicks; /* How many clicks did we start with? */ void mchinit() { extern char __end[], __end_data[], stext[], __end_text[], sdata[]; extern int RAM0, RAMSIZE; int lo; /* Number of bytes of physical memory below 640K. */ int hi; /* Number of bytes of physical memory above 1M. */ register char *pe; register int zero = 0; register int i; register long *ptable1_v; register unsigned short base; int sysseg, codeseg, stackseg, ramseg, ptable1; int ptoff; /* An offset into pageDir[] */ #if USE_NDATA int dataseg[NDATA]; #else int dataseg; #endif int nalloc; extern char digtab[]; static SEG uinit; int budArenaBytes; /* number of bytes in buddy pool */ int kerBytes; /* number of bytes in kernel text and data */ /* * 1. * a. Relocate the data on a page boundary (4K bytes) the * bootstrap relocates it on a paragraph boundary (16 bytes) * * b. Verify that the data has been relocated correctly */ pe = __end_data; /* 1.a */ i = (((unsigned)__end_text+15) & ~15) - (unsigned)sdata; do { pe--; pe[0] = pe[i]; } while (pe != sdata); /* 1.b */ /* * Can now access the .data segment from C. * If not, next loop will hang the kernel. */ CHIRP('A'); while (digtab[0]!='0'); CHIRP('*'); /* Zero the bss. */ pe = __end_data; do *pe++ = zero; while (pe != __end); /* * Zero the level 0 page directory, which occupies the click * of virtual space immediately below kernel text. */ pe = (char *) pageDir; do *pe++ = zero; while (pe != stext); CHIRP('2'); /* * 3. Calculate total system memory. * Count the space used by the system and the page * descriptors, the interrupt stack, and the refresh work area * * a. initialize allocation area and adjust system size * to take allocation area and free page area into account */ /* * btoc(__end) - SBASE is the number of clicks in kernel text * plus data, rounded up. * PBASE is the starting physical click number of the kernel. * * Set sysmem.lo to the physical click address just past the kernel. */ DV(__end); kerBytes = __end - ((SBASE - PBASE)<<BPCSHIFT); DV(kerBytes); sysmem.lo = btoc(kerBytes); DV(sysmem.lo); /* * lo is the size in bytes of memory between the end of the kernel * and the end of memory below 640K. * hi is the size in bytes of memory over 1 Megabyte (Extended memory). * * Round the sizes from the CMOS down to the next click. This * compensates for systems where the CMOS reports sizes that are * not multiples of 4K. */ DV(read16_cmos(LOMEM)); lo = ctob(read16_cmos(LOMEM) >> 2) - ctob(sysmem.lo); DV(lo); DV(read16_cmos(EXTMEM)); hi = ctob(read16_cmos(EXTMEM) >> 2); DV(hi); /* * Sometimes, we die horribly if there is too much memory. * Artificially limit hi to HACK_LIMIT. */ if (hi > HACK_LIMIT) hi = HACK_LIMIT; /* clear base memory above the kernel */ CHIRP('z'); zero_fill(ctob(sysmem.lo+SBASE-PBASE), lo); CHIRP('Z'); /* clear extended memory */ zero_fill(ONE_MEG+ctob(SBASE-PBASE), hi); CHIRP('Y'); /* Record total memory for later use. */ total_mem = ctob(sysmem.lo) + lo + hi; DV(total_mem); /* * sysmem.pfree and relatives will keep track of a pool of 4k pages * assigned to processes, hereinafter known as the sysmem pool. * How many clicks can go into this pool? nalloc. * Allow NBPC for the click itself, a short for the sysmem pointer, * and SPLASH*sizeof(long) for buddy system overhead. */ nalloc = (lo+hi) / (sizeof(short) + SPLASH*sizeof(long) + NBPC); DV(nalloc); /* * ASSERT: * For the moment we want only to assure that the * BUDDY arena and the stack of free pages will fit below * 640K. */ budArenaBytes = SPLASH*nalloc*sizeof(long); DV(budArenaBytes); #define SIZEOF_FREE_PAGES ((btoc(hi) + btoc(lo))* sizeof(short)) T_PIGGY(0x800, { if (budArenaBytes + SIZEOF_FREE_PAGES >= lo) { panic("Too much memory"); } }); /* * Initialize the buddy system arena. This memory is used * for the compressed page tables. */ areainit(budArenaBytes); /* * Initialize the stack of free pages. * __end is the virtual address just past kernel data * Point sysmem.tfree to the lowest virtual address just above * the buddy pool, and initialize sysmem.pfree there. */ sysmem.tfree = sysmem.pfree = (unsigned short *)(__end + budArenaBytes); DV(sysmem.tfree); /* sysmem.hi is the physical click number just past high RAM */ sysmem.hi = btoc(hi+ONE_MEG); DV(sysmem.hi); /* base is the physical click number just past base RAM */ base = sysmem.lo + (lo>>BPCSHIFT); DV(base); /* * Adjust sysmem.lo to be the physical click number just above * not just the kernel, but above sysmem overhead as well. */ sysmem.lo = btoc(kerBytes + budArenaBytes + nalloc*sizeof(short)); DV(sysmem.lo); /* * sysmem.vaddre is the virtual address of the next click after the * kernel. */ sysmem.vaddre = ctob(sysmem.lo+SBASE-PBASE); DV(sysmem.vaddre); /* include in system area pages for arena, free area */ CHIRP('3'); /* * 4. * Free the memory from [end, 640) kilobytes * Free the memory from [1024, 16*1024) kilobytes * * We are building a stack of free pages bounded below * by sysmem.tfree and above by sysmem.efree. sysmem.pfree * is the top of the stack. The stack grows upwards. */ total_clicks = 0; /* * Initialize the sysmem table (phase 1 - base RAM). * Put base RAM above the kernel and sysmem overhead area into * sysmem pool. */ while (base > sysmem.lo) { *sysmem.pfree++ = --base; ++total_clicks; } /* * Initialize the sysmem table (phase 2 - extended RAM). * Put all extended RAM into the sysmem pool. */ base = btoc(ONE_MEG); while (base < sysmem.hi && total_clicks < nalloc) { *sysmem.pfree++ = base++; ++total_clicks; } DV(total_clicks); /* * Roundoff error may have made nalloc smaller than necessary. */ while(base < sysmem.hi) { if (sysmem.pfree + 1 >= sysmem.vaddre) break; *sysmem.pfree++ = base++; ++total_clicks; nalloc++; } DV(total_clicks); DV(nalloc); /* * sysmem.efree points just past the last pointer in the sysmem * table. */ sysmem.efree = sysmem.pfree; DV(sysmem.efree); DV(allocno()); T_PIGGY(0x800, { /* * ASSERT: The stack of free pages should end within a click * of the lowest available memory. */ if ((cseg_t *)ctob(sysmem.lo+SBASE-PBASE) < sysmem.efree) { panic("sysmem.lo is too low"); } if (sysmem.efree < (cseg_t *)ctob(sysmem.lo+SBASE-PBASE - 1)){ panic("sysmem.efree is too low"); } /* * ASSERT: There should be nalloc total_clicks. */ if (nalloc != total_clicks) { panic("nalloc != total_clicks "); } }); CHIRP('4'); /* * 5. allocate page entries and initialize level 0 ^'s * a. [ 00000000 .. 003FFFFF) user code segment * b. [ 00400000 .. 007FFFFF) user data & bss * c. [ 7FC00000 .. 7FFFFFFF) user stack *c.i.[ 80000000 .. 80FFFFFF) ram disk * d. [ FF800000 .. FFBFFFFF) pointers to level 1 page table * e. [ FFC00000 .. FFFFFFFF) system process addresses */ codeseg = clickseg(*--sysmem.pfree); /* 5.a */ pageDir[0x000] = codeseg | DIR_RW; #if USE_NDATA for (i = 0; i < NDATA; i++) { dataseg[i] = clickseg(*--sysmem.pfree); /* 5.b */ pageDir[0x001+i] = dataseg[i] | DIR_RW; } #else dataseg = clickseg(*--sysmem.pfree); /* 5.b */ pageDir[0x001] = dataseg | DIR_RW; #endif stackseg = clickseg(*--sysmem.pfree); /* 5.c */ pageDir[0x1FF] = stackseg | DIR_RW; /* * ptable1 is a handle for the click containing page table * entries for the page table. * * allocate a click for ptable1 * Then point at it from the page directory. */ ptable1 = clickseg(*--sysmem.pfree); /* 5.d */ pageDir[0x3FE] = ptable1 | DIR_RW; sysseg = clickseg(*--sysmem.pfree); /* 5.e */ pageDir[0x3FF] = sysseg | DIR_RW; CHIRP('5'); /* * 6. initialize level 2 ^'s to [5.d] */ ptable1_v = (long *)(ptable1 + ctob(SBASE-PBASE)); DV(pageDir); DV(ptable1_v); ptable1_v[0x000] = codeseg | SEG_SRW; #if USE_NDATA for (i = 0; i < NDATA; i++) ptable1_v[0x001+i] = dataseg[i] | SEG_SRW; #else ptable1_v[0x001] = dataseg | SEG_SRW; #endif ptable1_v[0x1FF] = stackseg| SEG_SRW; /* * This ram disk stuff should go away once the scheme * for allocating pieces of virtual memory space is in place. */ for (ptoff = btosrd(RAM0) & 0x3ff; ptoff < (btosrd(RAM0 + 2 * RAMSIZE) & 0x3ff); ++ptoff) { ramseg = clickseg(*--sysmem.pfree); /* 5.c.i */ pageDir[ptoff] = ramseg | DIR_RW; ptable1_v[ptoff] = ramseg | SEG_SRW; } ptable1_v[0x3FF] = sysseg | SEG_SRW; CHIRP('6'); /* * 7. * b. map kernel code and data * map ^ to: * c. level 0 page table * d. level 1 page table * e. I/O segments (video RAM, ...) */ ptable1_v = (long *)(sysseg + ctob(SBASE-PBASE)); /* 7.b */ DV(ptable1_v); for (i = PBASE; i <sysmem.lo; i++) ptable1_v[i-PBASE] = clickseg(i) | SEG_SRW; ptable1_v[0x3FE] = clickseg(PTABLE0_P) | SEG_SRW; /* 7.c */ ptable1_v[0x3FD] = ptable1 | SEG_SRW; /* 7.d */ init_phy_seg(ptable1_v, ROM-SBASE, 0x0000F0000); /* 7.e. */ init_phy_seg(ptable1_v, VIDEOa-SBASE,0x0000B0000); init_phy_seg(ptable1_v, VIDEOb-SBASE,0x0000B8000); CHIRP('7'); /* * 8. allocate and map U area */ uinit.s_flags = SFSYST|SFCORE; uinit.s_size = UPASIZE; uinit.s_vmem = c_alloc(btoc(UPASIZE)); ptable1_v[0x3FF] = *uinit.s_vmem | SEG_SRW; procq.p_segp[SIUSERP] = &uinit; CHIRP('8'); /* * 9. make FFC00000 and 00002000 map to the same address * to prevent the prefetch after the instruction turning on * paging from causing a page fault */ ptable1_v = (long *)(codeseg + ctob(SBASE-PBASE)); DV(ptable1_v); ptable1_v[PBASE] = clickseg(PBASE) | SEG_SRW; CHIRP('9'); /* * 10. load page table base address into MMU * fix up the interrupt vectors */ mmuupdnR0(); CHIRP('U'); idtinit(); CHIRP('I'); } typedef struct { unsigned short off_lo; unsigned short seg; unsigned short flags; unsigned short off_hi; } IDT; /* * ldtinit() * * Fix up descriptors which are hard to create properly at compile/link time. * Apply to idt and ldt. * * Swap 16-bit words at descriptor+2, descriptor+6. */ void idtinit() { extern IDT idt[], idtend[]; extern IDT ldt[], ldtend[]; extern IDT gdtFixBegin[], gdtFixEnd[]; register IDT *ip; register unsigned short tmp; for (ip = idt; ip < idtend; ip++) { tmp = ip->off_hi; ip->off_hi = ip->seg; ip->seg = tmp; } for (ip = ldt; ip < ldtend; ip++) { tmp = ip->off_hi; ip->off_hi = ip->seg; ip->seg = tmp; } for (ip = gdtFixBegin; ip < gdtFixEnd; ip++) { tmp = ip->off_hi; ip->off_hi = ip->seg; ip->seg = tmp; } } void init_phy_seg(ptable1_v, addr, base) long *ptable1_v; { register int i; for (i=0; i<btoc(0x10000); i++) { ptable1_v[addr+i] = base | SEG_SRW; base += NBPC; } } /* * Load up segmentation registers. */ SR ugmtab[NUSEG]; void segload() { register int i; register SR *start; /* * 1. unprogram the currently active UGM user segments * reset ugmtab */ for (start = &ugmtab[1]; start < &ugmtab[NUSEG]; start++) { if (start->sr_segp) unload(start); start->sr_segp = 0; } /* * 2. Load each segment in the p->p_region list into the MMU * Remember values in ugmtab. */ start = &ugmtab[1]; for (i = 1; i < NUSEG; i++) { if (u.u_segl[i].sr_segp) { *start = u.u_segl[i]; switch (i) { case SIPDATA: if (u.u_segl[SISTACK].sr_base) start->sr_size = min(start->sr_size, (long)u.u_segl[SISTACK].sr_base- u.u_segl[SISTACK].sr_size); break; case SISTACK: start->sr_base -= start->sr_size; break; } start->sr_segp = 0; if (SELF->p_segp[i]) { start->sr_segp = SELF->p_segp[i]; doload(start); } start++; } } /* 3. Update shm segment information. */ shmLoad(); } SR * loaded(pp) register cseg_t *pp; { register SR *start; for (start = ugmtab; start < ugmtab + NUSEG; start++) { if (start->sr_segp && start->sr_segp->s_vmem == pp) { return start; } } return 0; } MAKESR(r0stk, _r0stk); extern int tss_sp0; /* * General initialization */ void i8086() { unsigned csize, isize, ssize, allsize; caddr_t base; unsigned int calc_mem, boost; /* This is the first C code executed after paging is turned on. */ workPoolInit(); /* * Allocate contiguous physical memory if PHYS_MEM is patched * to a nonzero value. */ if (PHYS_MEM) { physMem.sr_size = (PHYS_MEM+NBPC-1)&~(NBPC-1); valloc(&physMem); physMemInit(); } /* * Allocate a click for ring 0 stack. */ r0stk.sr_size = NBPC; valloc(&r0stk); tss_sp0 = r0stk.sr_base + NBPC; /* * calc_mem is used for autosizing buffer cache and kalloc pool. * It is total_mem, limited below by 1 meg and above by 12 meg. * The upper limit is a temporary move to allow booting on 16 Meg * systems. * * "boost" is used in autosizing buffer cache and kalloc pool. * It is the number of megabytes of calc_mem above 1 meg, i.e., * a number between 0 and 11. */ if (total_mem < ONE_MEG) calc_mem = ONE_MEG; else if (total_mem > 12 * ONE_MEG) calc_mem = 12 * ONE_MEG; else calc_mem = total_mem; boost = (calc_mem - ONE_MEG) / ONE_MEG; /* * If the number of cache buffers was not explicitly set (i.e., !0) * then calculate the number of buffers using the simple heuristic: * 128 minimum + 400 per MB of available RAM (i.e., after 1MB) */ if (NBUF == 0) NBUF = 128 + (400 * boost); /* * If the amount of kalloc() space was not explicitly set (i.e., !0) * then calculate using the simple heuristic: * 64k minimum + 32k per MB of available RAM (i.e., after 1MB) */ if (ALLSIZE == 0) ALLSIZE = 65536 + (32768 * boost); blockp.sr_size = NBUF*BSIZE; valloc(&blockp); allocp.sr_size= allsize = NBUF*sizeof(BUF) + ALLSIZE; #if USE_SLOT allocp.sr_size += ssize = NSLOT * (sizeof(int) + slotsz); #else ssize = 0; #endif allocp.sr_size += isize = NINODE* sizeof(INODE); allocp.sr_size += csize = NCLIST* sizeof(CLIST); valloc(&allocp); base = allocp.sr_base; allkp = setarena(base, allsize); base += allsize; #if USE_SLOT slotp = (int *)base; base += ssize; #endif inodep = (INODE*) base; base += isize; clistp = (paddr_t)base; } /* * Allocate srp->sr_size bytes of physical memory, and map it into * virtual memory space. At the end, the struct at srp will describe * the new segment. */ void valloc(srp) SR *srp; { register int npage; /* * If we've run out of virtual memory space, panic(). * * A more graceful solution is needed, but valloc() does * not provide a return value. */ if (sysmem.vaddre + srp->sr_size > MAX_VADDR) { panic("valloc: out of virtual memory space"); } npage = btoc(srp->sr_size); srp->sr_base = sysmem.vaddre; srp->sr_segp->s_size = srp->sr_size; srp->sr_segp->s_vmem = c_alloc(npage); srp->sr_segp->s_flags = SFSYST|SFCORE; doload(srp); sysmem.vaddre += ctob(npage); } /* * See if the given process may fit in core. */ int testcore(pp) register PROC *pp; { return 1; } /* * Calculate segmentation for a * new program. If there is a stack segment * present merge it into the data segment and * relocate the argument list. * Make sure that the changes are reflected in the u.u_segl array * which sproto sets up. */ int mproto() { return 1; } int accdata(base, count) unsigned base, count; { SR *srp; srp = &u.u_segl[SIPDATA]; return base>=srp->sr_base && base+count <= srp->sr_base+srp->sr_size; } int accstack(base, count) unsigned base; { SR *srp; srp = &u.u_segl[SISTACK]; return base>=srp->sr_base-srp->sr_size && base+count<=srp->sr_base; } int acctext(base, count) unsigned base; { SR *srp; srp = &u.u_segl[SISTEXT]; return base>=srp->sr_base && base+count <= srp->sr_base+srp->sr_size; } printhex(v, max) unsigned long v; { register int i; for (i = max-1; i>=0; --i) putchar(digtab[(v >> (i*4)) & 0xF]); } /* Read a 16 byte number from the CMOS. */ unsigned int read16_cmos(addr) unsigned int addr; { unsigned char read_cmos(); return((read_cmos(addr+1)<<8) + read_cmos(addr)); } /* read16_cmos() */ int c_grow(sp, new_bytes) SEG *sp; int new_bytes; { register int i; register cseg_t *pp; int new_clicks, pno, nsize, old_clicks; SR *srp; T_PIGGY(0x8000000, printf("c_grow(sp: %x, new: %x)", sp, new_bytes);); new_clicks = btoc(new_bytes); old_clicks = btoc(sp->s_size); if (new_clicks == old_clicks) { goto ok_c_grow; } if (new_clicks < old_clicks) { printf("%s:can't contract segment\n",u.u_comm); goto no_c_grow; } if (new_clicks - old_clicks > allocno()) { goto no_c_grow; } T_PIGGY(0x8000000, printf("nc: %x, oc: %x,",new_clicks,old_clicks);); /* * Allocate a new descriptor vector if necessary. * pp is the element corresponding to the virtual address * "0"(sr_base) */ pp = sp->s_vmem; nsize = areasize(new_clicks); if (nsize != areasize(old_clicks) && !(pp = (cseg_t*)arealloc(new_clicks))) { T_PIGGY(0x8000000, printf("Can not allocate new descriptor.");); goto no_c_grow; } T_PIGGY(0x8000000, printf("new pp: %x", pp);); if (0 != (srp = loaded(sp->s_vmem))) { T_PIGGY(0x8000000, printf("unloading srp: %x, ", srp);); unload(srp); srp->sr_segp = 0; } /* * Allocate new descriptors. */ T_PIGGY(0x8000000, printf("new desc: [");); for (i = old_clicks; i < new_clicks; i++) { pno = *--sysmem.pfree; pp[i] = clickseg(pno) | SEG_RW; T_PIGGY(0x8000000, printf("%x, ", pp[i]);); } T_PIGGY(0x8000000, printf("]");); /* * Copy unchanged descriptors and free old vector if necessary. */ if (pp != sp->s_vmem) { T_PIGGY(0x8000000, printf("old desc: [");); for (i = 0; i < old_clicks; i++) { pp[i] = sp->s_vmem[i]; T_PIGGY(0x8000000, printf("%x, ", pp[i]);); } T_PIGGY(0x8000000, printf("]");); areafree((BLOCKLIST*)sp->s_vmem, old_clicks); } sp->s_vmem = pp; /* * clear the added clicks * * MAPIO macro - convert array of page descriptors, offset * into system global address. */ T_PIGGY(0x8000000, printf("dmaclear(%x, %x, 0)", ctob(new_clicks - old_clicks), MAPIO(sp->s_vmem, ctob(old_clicks)) ); ); /* T_PIGGY() */ dmaclear(ctob(new_clicks - old_clicks), MAPIO(sp->s_vmem, ctob(old_clicks)), 0); ok_c_grow: return 0; no_c_grow: return -1; }
2.046875
2
2024-11-18T21:46:56.553367+00:00
2021-06-30T09:01:23
db7eaeb6b75fc090a4f8c6307447ab348f9f0ad0
{ "blob_id": "db7eaeb6b75fc090a4f8c6307447ab348f9f0ad0", "branch_name": "refs/heads/master", "committer_date": "2021-06-30T09:44:52", "content_id": "6605649110edd0badfb5bbe674961c0fd9b7c38a", "detected_licenses": [ "Apache-2.0" ], "directory_id": "9ab827501dc72d525aebb2f607fc9a1ccdd6cce3", "extension": "c", "filename": "iconv.c", "fork_events_count": 0, "gha_created_at": "2021-07-15T02:05:23", "gha_event_created_at": "2021-07-15T09:08:36", "gha_language": null, "gha_license_id": "NOASSERTION", "github_id": 386132380, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3312, "license": "Apache-2.0", "license_type": "permissive", "path": "/c_src/iconv.c", "provenance": "stackv2-0130.json.gz:42506", "repo_name": "loongarch64/iconv", "revision_date": "2021-06-30T09:01:23", "revision_id": "50561f875cac193e371dcead5695951b59e132a3", "snapshot_id": "69d68d15104241f4bc41aeefbbf4dd6365b28c42", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/loongarch64/iconv/50561f875cac193e371dcead5695951b59e132a3/c_src/iconv.c", "visit_date": "2023-06-17T12:12:19.377553" }
stackv2
/* * Copyright (C) 2002-2021 ProcessOne, SARL. All Rights Reserved. * * 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 <erl_nif.h> #include <string.h> #include <iconv.h> #define OK 0 #define ERR_MEMORY_FAIL 1 static int load(ErlNifEnv* env, void** priv, ERL_NIF_TERM load_info) { return 0; } static int do_convert(ErlNifEnv* env, char *from, char *to, ErlNifBinary *string, ErlNifBinary *rstring) { char *stmp = (char *) string->data; char *rtmp = (char *) rstring->data; size_t outleft = rstring->size; size_t inleft = string->size; int invalid_utf8_as_latin1 = 0; iconv_t cd; /* Special mode: parse as UTF-8 if possible; otherwise assume it's Latin-1. Makes no difference when encoding. */ if (strcmp(from, "utf-8+latin-1") == 0) { from[5] = '\0'; invalid_utf8_as_latin1 = 1; } if (strcmp(to, "utf-8+latin-1") == 0) { to[5] = '\0'; } cd = iconv_open(to, from); if (cd == (iconv_t) -1) { if (enif_realloc_binary(rstring, string->size)) { memcpy(rstring->data, string->data, string->size); return OK; } else { return ERR_MEMORY_FAIL; } } while (inleft > 0) { if (iconv(cd, &stmp, &inleft, &rtmp, &outleft) == (size_t) -1) { if (invalid_utf8_as_latin1 && (*stmp & 0x80) && outleft >= 2) { /* Encode one byte of (assumed) Latin-1 into two bytes of UTF-8 */ *rtmp++ = 0xc0 | ((*stmp & 0xc0) >> 6); *rtmp++ = 0x80 | (*stmp & 0x3f); outleft -= 2; } stmp++; if (inleft > 0) inleft--; } } iconv_close(cd); if (enif_realloc_binary(rstring, rtmp - (char *) rstring->data)) { return OK; } else { return ERR_MEMORY_FAIL; } } static ERL_NIF_TERM convert(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) { ErlNifBinary from_bin, to_bin, string, rstring; char *from, *to; int rescode; if (argc == 3) { if (enif_inspect_iolist_as_binary(env, argv[0], &from_bin) && enif_inspect_iolist_as_binary(env, argv[1], &to_bin) && enif_inspect_iolist_as_binary(env, argv[2], &string)) { from = enif_alloc(from_bin.size + 1); to = enif_alloc(to_bin.size + 1); if (from && to && enif_alloc_binary(4*string.size, &rstring)) { memcpy(from, from_bin.data, from_bin.size); memcpy(to, to_bin.data, to_bin.size); from[from_bin.size] = '\0'; to[to_bin.size] = '\0'; rescode = do_convert(env, from, to, &string, &rstring); enif_free(from); enif_free(to); if (rescode == OK) { return enif_make_binary(env, &rstring); } else { enif_release_binary(&rstring); } } } } return enif_make_badarg(env); } static ErlNifFunc nif_funcs[] = { {"convert", 3, convert} }; ERL_NIF_INIT(iconv, nif_funcs, load, NULL, NULL, NULL)
2.03125
2
2024-11-18T21:46:57.773586+00:00
2020-08-03T17:56:28
b2fb4295a79031f4930c5521f1f8e043a2a5c8c6
{ "blob_id": "b2fb4295a79031f4930c5521f1f8e043a2a5c8c6", "branch_name": "refs/heads/master", "committer_date": "2020-08-03T17:56:28", "content_id": "0b5b7089af846df60485b8fef2ad2d05be3a5efa", "detected_licenses": [ "MIT" ], "directory_id": "3c39e92b7d2a81b9b94356ade7ae981be7d9f0bf", "extension": "c", "filename": "log_console.c", "fork_events_count": 0, "gha_created_at": "2020-08-02T03:26:59", "gha_event_created_at": "2020-08-02T16:32:49", "gha_language": "C", "gha_license_id": "MIT", "github_id": 284382667, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1229, "license": "MIT", "license_type": "permissive", "path": "/u-boot_u-boot_d0d07ba/src/opt/src/common/log_console.c", "provenance": "stackv2-0130.json.gz:43021", "repo_name": "adde9708/codeql-uboot", "revision_date": "2020-08-03T17:56:28", "revision_id": "0c56e6be2deb0c369f8e1e7e517656690abb0be3", "snapshot_id": "9b1d4d5c9fc340687c8ccc930b3d0a8e326e6554", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/adde9708/codeql-uboot/0c56e6be2deb0c369f8e1e7e517656690abb0be3/u-boot_u-boot_d0d07ba/src/opt/src/common/log_console.c", "visit_date": "2022-11-27T03:56:39.855516" }
stackv2
// SPDX-License-Identifier: GPL-2.0+ /* * Logging support * * Copyright (c) 2017 Google, Inc * Written by Simon Glass <sjg@chromium.org> */ #include <common.h> #include <log.h> DECLARE_GLOBAL_DATA_PTR; static int log_console_emit(struct log_device *ldev, struct log_rec *rec) { int fmt = gd->log_fmt; /* * The output format is designed to give someone a fighting chance of * figuring out which field is which: * - level is in CAPS * - cat is lower case and ends with comma * - file normally has a .c extension and ends with a colon * - line is integer and ends with a - * - function is an identifier and ends with () * - message has a space before it unless it is on its own */ if (fmt & (1 << LOGF_LEVEL)) printf("%s.", log_get_level_name(rec->level)); if (fmt & (1 << LOGF_CAT)) printf("%s,", log_get_cat_name(rec->cat)); if (fmt & (1 << LOGF_FILE)) printf("%s:", rec->file); if (fmt & (1 << LOGF_LINE)) printf("%d-", rec->line); if (fmt & (1 << LOGF_FUNC)) printf("%s()", rec->func); if (fmt & (1 << LOGF_MSG)) printf("%s%s", fmt != (1 << LOGF_MSG) ? " " : "", rec->msg); return 0; } LOG_DRIVER(console) = { .name = "console", .emit = log_console_emit, };
2.421875
2
2024-11-18T21:46:58.335775+00:00
2020-07-27T10:01:57
82521c419bd10e989f417ecdd52f909226a1de48
{ "blob_id": "82521c419bd10e989f417ecdd52f909226a1de48", "branch_name": "refs/heads/master", "committer_date": "2020-07-27T10:01:57", "content_id": "998263863e5aa01237e293549967822149b53866", "detected_licenses": [ "MIT" ], "directory_id": "89140516fa85842118d8497ba38be6bb4d602c11", "extension": "c", "filename": "console.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 269399184, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3553, "license": "MIT", "license_type": "permissive", "path": "/examples/console/console.c", "provenance": "stackv2-0130.json.gz:43280", "repo_name": "MichalBlk/FreeRTOS-Amiga", "revision_date": "2020-07-27T10:01:57", "revision_id": "d7ba51037e538b47322395f64642c46a12b30a03", "snapshot_id": "ff20ce915ff356aeeadec76884c6fac799cce0fe", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/MichalBlk/FreeRTOS-Amiga/d7ba51037e538b47322395f64642c46a12b30a03/examples/console/console.c", "visit_date": "2022-11-24T06:31:44.395076" }
stackv2
#include <stdarg.h> #include <stdio.h> #include <bitmap.h> #include <copper.h> #include <font.h> #include <palette.h> #include <sprite.h> #include <string.h> #include "console.h" #include "event.h" #include "data/lat2-08.c" #include "data/pointer.c" #include "data/screen.c" #define cons_width (screen_bm.width / 8) #define cons_height (screen_bm.height / console_font.height) #define cons_rowsize ((short)(screen_bm.bytesPerRow * console_font.height)) static struct { unsigned char *here; short x; short y; } cursor; /* * Copper configures hardware each frame (50Hz in PAL) to: * - set video mode to HIRES (640x256), * - display one bitplane, * - set background color to black, and foreground to white, * - set up mouse pointer palette, * - set sprite 0 to mouse pointer graphics, * - set other sprites to empty graphics, */ static void BuildCopperList(coplist_t *cp) { CopSetupScreen(cp, &screen_bm, MODE_HIRES, HP(0), VP(0)); CopSetupBitplanes(cp, &screen_bm, NULL); CopLoadColor(cp, 0, 0x000); CopLoadColor(cp, 1, 0xfff); CopLoadPal(cp, &pointer_pal, 16); CopLoadSprite(cp, 0, &pointer_spr); for (int i = 1; i < 8; i++) CopLoadSprite(cp, i, NULL); CopEnd(cp); } void ConsoleInit(void) { static COPLIST(cp, 40); EventQueueInit(); MouseInit(PushMouseEventFromISR, 0, 0, 319, 255); KeyboardInit(PushKeyEventFromISR); /* Set cursor to (0, 0) */ cursor.here = screen_bm.planes[0]; cursor.x = 0; cursor.y = 0; /* Tell copper where the copper list begins and enable copper DMA. */ BuildCopperList(cp); CopListActivate(cp); /* Set sprite position in upper-left corner of display window. */ SpriteUpdatePos(&pointer_spr, HP(0), VP(0)); /* Enable bitplane and sprite fetchers' DMA. */ EnableDMA(DMAF_RASTER | DMAF_SPRITE); } static inline void UpdateHere(void) { cursor.here = screen_bm.planes[0] + cons_rowsize * cursor.y + cursor.x; } void ConsoleMovePointer(short x, short y) { SpriteUpdatePos(&pointer_spr, HP(x), VP(y)); } void ConsoleSetCursor(short x, short y) { if (x < 0) cursor.x = 0; else if (x >= cons_width) cursor.x = cons_width - 1; else cursor.x = x; if (y < 0) cursor.y = 0; else if (y >= cons_height) cursor.y = cons_height - 1; else cursor.y = y; UpdateHere(); } void ConsoleGetCursor(short *xp, short *yp) { *xp = cursor.x; *yp = cursor.y; } #pragma GCC push_options #pragma GCC optimize("-O3") static void ConsoleDrawChar(int c) { unsigned char *src = console_font_glyphs + (c - 32) * console_font.height; unsigned char *dst = cursor.here++; for (short i = 0; i < console_font.height; i++) { *dst = *src++; dst += screen_bm.bytesPerRow; } } void ConsoleDrawCursor(void) { unsigned char *dst = cursor.here++; for (short i = 0; i < console_font.height; i++) { *dst = ~*dst; dst += screen_bm.bytesPerRow; } } #pragma GCC pop_options static void ConsoleNextLine(void) { for (short x = cursor.x; x < cons_width; x++) ConsoleDrawChar(' '); cursor.x = 0; if (++cursor.y >= cons_height) cursor.y = 0; UpdateHere(); } void ConsolePutChar(char c) { if (c < 32) { if (c == '\n') ConsoleNextLine(); } else { ConsoleDrawChar(c); if (++cursor.x >= cons_width) ConsoleNextLine(); } } void ConsoleWrite(const char *buf, size_t nbyte) { for (size_t i = 0; i < nbyte; i++) ConsolePutChar(*buf++); } void ConsolePrintf(const char *fmt, ...) { va_list ap; va_start(ap, fmt); kvprintf(ConsolePutChar, fmt, ap); va_end(ap); }
2.6875
3
2024-11-18T21:46:58.385974+00:00
2022-02-16T23:16:25
9cb162c3a705942cf8631412544022a7e1b4df51
{ "blob_id": "9cb162c3a705942cf8631412544022a7e1b4df51", "branch_name": "refs/heads/master", "committer_date": "2022-02-16T23:16:25", "content_id": "e5a999fe6ac2601c401119f754eb4b6e278fa29c", "detected_licenses": [ "Zlib" ], "directory_id": "38eabc5e53c62428f130f6cfa0bba04bd4e6b857", "extension": "h", "filename": "ImageView.h", "fork_events_count": 9, "gha_created_at": "2014-08-26T12:33:14", "gha_event_created_at": "2022-08-29T13:55:57", "gha_language": "C", "gha_license_id": "NOASSERTION", "github_id": 23350910, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3990, "license": "Zlib", "license_type": "permissive", "path": "/Sources/ObjectivelyMVC/ImageView.h", "provenance": "stackv2-0130.json.gz:43410", "repo_name": "jdolan/ObjectivelyMVC", "revision_date": "2022-02-16T23:16:25", "revision_id": "f1c4b3c8bf8a3a0a915f6dd39e52728d64d1ffe2", "snapshot_id": "2955978b14d27bfec71e7500c771b8b119984913", "src_encoding": "UTF-8", "star_events_count": 24, "url": "https://raw.githubusercontent.com/jdolan/ObjectivelyMVC/f1c4b3c8bf8a3a0a915f6dd39e52728d64d1ffe2/Sources/ObjectivelyMVC/ImageView.h", "visit_date": "2022-12-04T17:21:38.522049" }
stackv2
/* * ObjectivelyMVC: Object oriented MVC framework for OpenGL, SDL2 and GNU C. * Copyright (C) 2014 Jay Dolan <jay@jaydolan.com> * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * * 3. This notice may not be removed or altered from any source distribution. */ #pragma once #include <ObjectivelyMVC/Image.h> #include <ObjectivelyMVC/View.h> /** * @file * @brief ImageViews render an Image in the context of a View hierarchy. */ OBJECTIVELYMVC_EXPORT const EnumName GLBlendNames[]; typedef struct ImageView ImageView; typedef struct ImageViewInterface ImageViewInterface; /** * @brief ImageViews render an Image in the context of a View hierarchy. * @extends View */ struct ImageView { /** * @brief The superclass. */ View view; /** * @brief The interface. * @protected */ ImageViewInterface *interface; /** * @brief The blend function. */ struct { GLenum src, dst; } blend; /** * @brief The drawing color. */ SDL_Color color; /** * @brief The image. */ Image *image; /** * @brief The texture. */ GLuint texture; }; /** * @brief The ImageView interface. */ struct ImageViewInterface { /** * @brief The superclass interface. */ ViewInterface viewInterface; /** * @fn ImageView *ImageView::initWithFrame(ImageView *self, const SDL_Rect *frame) * @brief Initializes this ImageView with the specified frame. * @param self The ImageView. * @param frame The frame. * @return The initialized ImageView, or `NULL` on error. * @memberof ImageView */ ImageView *(*initWithFrame)(ImageView *self, const SDL_Rect *frame); /** * @fn ImageView *ImageView::initWithImage(ImageView *self, Image *image) * @brief Initializes this ImageView with the specified image. * @param self The ImageView. * @param image The Image. * @return The initialized ImageView, or `NULL` on error. * @memberof ImageView */ ImageView *(*initWithImage)(ImageView *self, Image *image); /** * @fn void ImageView::setImage(ImageView *self, Image *image); * @brief Sets the Image for this ImageView. * @param self The ImageView. * @param image An Image. * @memberof ImageView */ void (*setImage)(ImageView *self, Image *image); /** * @fn void ImageView::setImageWithResource(ImageView *self, const Resource *resource); * @brief Sets the Image for this ImageView with the given Resource. * @param self The ImageView. * @param resource An Image Resource. * @memberof ImageView */ void (*setImageWithResource)(ImageView *self, const Resource *resource); /** * @fn void ImageView::setImageWithResourceName(ImageView *self, const char *name); * @brief Sets the Image for this ImageView with the Resource by the given name. * @param self The ImageView. * @param name An Image Resource name. * @memberof ImageView */ void (*setImageWithResourceName)(ImageView *self, const char *name); /** * @fn void ImageView::setImageWithSurface(ImageView *self, SDL_Surface *surface) * @brief A convenience method to set this view's Image with a surface. * @param self The ImageView. * @param surface The surface. * @memberof ImageView */ void (*setImageWithSurface)(ImageView *image, SDL_Surface *surface); }; OBJECTIVELYMVC_EXPORT Class *_ImageView(void);
2.015625
2
2024-11-18T21:46:59.010337+00:00
2018-01-26T07:44:26
fcb8d91e88688aae3847c4ca98a8536653b4211a
{ "blob_id": "fcb8d91e88688aae3847c4ca98a8536653b4211a", "branch_name": "refs/heads/master", "committer_date": "2018-01-26T07:44:26", "content_id": "b9e8efbe7c9d8ec20c3f08eb14b00d5b8e5a9707", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "e1bd4c4b467ab0f698e2815f0fc9d165943abe8e", "extension": "c", "filename": "e1.20.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 113149132, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1251, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/Chapter1/e1.20.c", "provenance": "stackv2-0130.json.gz:43669", "repo_name": "ankitrgadiya/learn-c-adv", "revision_date": "2018-01-26T07:44:26", "revision_id": "a99b220ee1e5848743123a398bc1b2e7661fa185", "snapshot_id": "ca84a28454902d39430814a4625ac6c60e5ca4f6", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/ankitrgadiya/learn-c-adv/a99b220ee1e5848743123a398bc1b2e7661fa185/Chapter1/e1.20.c", "visit_date": "2021-09-05T10:05:49.215275" }
stackv2
/* * Exercise 1.20 * Write a program detab that replaces tabs in the input with the proper number * of blanks to space to the next tab stop. Assume a fixed set of tab stops, say * every n columns. Should n be a variable or a symbolic parameter? */ #include <stdio.h> #define MAXLINE 1000 // maxline size of line #define TABSTOP 8 // tab size int getstring (char s[], int lim); void detab (char s[]); /* gets input, detab it * and print it */ int main (void) { int len; char line[MAXLINE]; while ((len = getstring(line, MAXLINE)) > 0) { detab(line); printf("%s", line); } return 0; } /* read input into s */ int getstring (char s[], int lim) { int c, i; for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; i++) s[i] = c; if (c == '\n') { s[i] = c; i++; } s[i] = '\0'; return i; } /* replace tab character with * appropriate spaces */ void detab (char s[]) { int i, j, k; int tab; char temp[MAXLINE]; i = 0; j = 0; while (s[i] != '\0') { if (s[i] == '\t') { tab = TABSTOP - (j % TABSTOP); while (tab > 0) { temp[j] = ' '; j++; tab--; } } else { temp[j] = s[i]; j++; } i++; } for (k = 0; k < j; k++) s[k] = temp[k]; s[k] = '\0'; return ; }
3.71875
4
2024-11-18T21:46:59.272454+00:00
2019-07-24T16:59:37
3abfb54aa2f51c4e8faca2550ad01ae20a87091c
{ "blob_id": "3abfb54aa2f51c4e8faca2550ad01ae20a87091c", "branch_name": "refs/heads/master", "committer_date": "2019-07-24T16:59:37", "content_id": "f5703ae5a56b1b4c511336d3b48eb1e4abc94d27", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "f24e48592d519af6c15e8fd4c68e7e21746bc80e", "extension": "c", "filename": "read_write_complex.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 198677846, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 414, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/spearmint/read_write_complex.c", "provenance": "stackv2-0130.json.gz:43797", "repo_name": "chopralab/spear", "revision_date": "2019-07-24T16:59:37", "revision_id": "d45ffc907ab1730789413dd04afb347a26f35154", "snapshot_id": "2481187c69f779eee6efedae7847f2a2bcc26066", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/chopralab/spear/d45ffc907ab1730789413dd04afb347a26f35154/spearmint/read_write_complex.c", "visit_date": "2020-06-23T16:23:10.411151" }
stackv2
#include "spearmint.h" #include <stdio.h> int main(int argc, char** argv) { if (argc < 3) { printf("Please give 2 variables\n"); return 1; } if (spear_initialize_complex(argv[1]) == 0) { printf("%s\n", spear_get_error()); return 1; } if (spear_write_complex(argv[2]) == 0) { printf("%s\n", spear_get_error()); return 1; } return 0; }
2.125
2
2024-11-18T21:46:59.333311+00:00
2021-02-04T20:44:49
b058a73c69e49f74bae0f57de4ebac094a156903
{ "blob_id": "b058a73c69e49f74bae0f57de4ebac094a156903", "branch_name": "refs/heads/master", "committer_date": "2021-02-04T20:44:49", "content_id": "a654f84ce821642586ec62caec5ee309ed035815", "detected_licenses": [ "BSD-2-Clause", "BSD-3-Clause" ], "directory_id": "7294cc101aec0ec00dda9c36941c8273002a8434", "extension": "h", "filename": "kernel.h", "fork_events_count": 7, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 244081482, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2912, "license": "BSD-2-Clause,BSD-3-Clause", "license_type": "permissive", "path": "/Elysian/pac/kernel.h", "provenance": "stackv2-0130.json.gz:43926", "repo_name": "chr1s0x1/Elysian", "revision_date": "2021-02-04T20:44:49", "revision_id": "b0f79e6d74e79759036d1328ba4bbe6caff98282", "snapshot_id": "7f712f939224199b908f0fe468ce1808817ac704", "src_encoding": "UTF-8", "star_events_count": 35, "url": "https://raw.githubusercontent.com/chr1s0x1/Elysian/b0f79e6d74e79759036d1328ba4bbe6caff98282/Elysian/pac/kernel.h", "visit_date": "2023-02-25T10:00:31.028891" }
stackv2
// // kernel.h // Brandon Azad // #ifndef OOB_TIMESTAMP__KERNEL__H_ #define OOB_TIMESTAMP__KERNEL__H_ #include <mach/mach.h> #include <stdbool.h> #include <stdint.h> #ifdef KERNEL_EXTERN #define extern KERNEL_EXTERN #endif /* * kernel_base_address * * Description: * The kernel base address. This is usually 0xfffffff007004000 plus the kASLR slide. */ extern uint64_t kernel_base_address; /* * kernel_slide * * Description: * The kASLR slide. This is the difference between the static kernel base address and the * runtime location of the kernel base. */ extern uint64_t kernel_slide; /* * current_task * * Description: * The address of the current process's task struct in kernel memory. */ extern uint64_t current_task; /* * kernel_task * * Description: * The address of the real kernel_task struct in kernel memory. */ extern uint64_t kernel_task; /* * kernproc * * Description: * The address of the kernel's proc struct in kernel memory. */ extern uint64_t kernproc; /* * struct kernel_all_image_info_addr * * Description: * The struct pointed to by kernel_task TASK_DYLD_INFO all_image_info_addr. This struct * contains fields that are helpful to regain capabilities after the initial exploit has * finished. */ struct kernel_all_image_info_addr { // A magic value to identify this structure. #define KERNEL_ALL_IMAGE_INFO_ADDR_MAGIC 'KINF' uint32_t kernel_all_image_info_addr_magic; // The size of this structure. uint32_t kernel_all_image_info_addr_size; // The kernel base address. uint64_t kernel_base_address; // The address of kernproc. This is used to walk the process list. uint64_t kernproc; // The address of the page used for the PAC bypass. This is used to reconstruct the kernel // PAC bypass. uint64_t kernel_pac_bypass_page; }; /* * kernel_all_image_info_addr * * Description: * The address of the kernel_all_image_info_addr struct. */ extern uint64_t kernel_all_image_info_addr; /* * kernel_init * * Description: * Try to grab the kernel task port and initialize variables for a pre-exploited system. * * The kernel task port should export additional information in task_info(TASK_DYLD_INFO). The * all_image_info_addr field should be a pointer to a page of kernel memory containing a * kernel_all_image_info_addr struct at the start. The all_image_info_size field should * contain the kASLR slide. */ bool kernel_init(void); /* * kernel_ipc_port_lookup * * Description: * Look up the ipc_entry, ipc_port, and ip_kobject for the specified Mach port name in the * given task. */ bool kernel_ipc_port_lookup(uint64_t task, mach_port_name_t port_name, uint64_t *ipc_entry, uint64_t *ipc_port, uint64_t *ip_kobject); /* * kernel_current_thread * * Description: * Returns the address of the thread struct for the current thread. */ uint64_t kernel_current_thread(void); #undef extern #endif
2.1875
2
2024-11-18T21:46:59.401354+00:00
2021-07-09T19:58:55
0f6fdb8fab98b322b2a6ef85d3a85edcea95793c
{ "blob_id": "0f6fdb8fab98b322b2a6ef85d3a85edcea95793c", "branch_name": "refs/heads/master", "committer_date": "2021-07-09T19:58:55", "content_id": "10a992bb4a3e7c0039968c902715ad85e72c3744", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "ee002afcdc55912ec8df6bb9360097e0c7944ecb", "extension": "h", "filename": "ksem.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 384197656, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1880, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/rdb/Kernel/include/ksem.h", "provenance": "stackv2-0130.json.gz:44056", "repo_name": "ncomerci/TP-SO", "revision_date": "2021-07-09T19:58:55", "revision_id": "cc532fb6a59f90e0dbc3d45fae0107f10e95bb14", "snapshot_id": "5b0707f0ef0f91a85d21cdd9cb02b21502b0b346", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/ncomerci/TP-SO/cc532fb6a59f90e0dbc3d45fae0107f10e95bb14/rdb/Kernel/include/ksem.h", "visit_date": "2023-06-12T14:35:43.280448" }
stackv2
#ifndef _KSEM_H #define _KSEM_H #include <stdint.h> #define MAX_SEMAPHORES 40 #define MAX_PROCESSES_PER_SEMAPHORE 10 #define SEM_NAME_MAX_LENGTH 40 typedef int sem_id; // p1 sleep() // p2 sleep() // p3 sleep() // p4 post() // typedef enum {DEFAULT, PRIVILEGED} p_status_t; typedef struct sem_queue { char occupied; uint64_t pid; struct sem_queue * next; } sem_queue; typedef struct sem_t { char name[SEM_NAME_MAX_LENGTH]; uint32_t lock; uint64_t value; sem_queue processes[MAX_PROCESSES_PER_SEMAPHORE]; unsigned int processes_amount; //processes not closed unsigned int processes_size; //all processes unsigned int processes_waiting; sem_queue * first; sem_queue * last; p_status_t privileged; } sem_t; typedef struct sem_info { sem_id id; char name[SEM_NAME_MAX_LENGTH]; uint64_t value; uint64_t processes_waiting[MAX_PROCESSES_PER_SEMAPHORE]; unsigned int processes_waiting_amount; }sem_info; void spin_lock(uint32_t * lock); void spin_unlock(uint32_t * lock); sem_id ksem_open(char * name); sem_id ksem_init_open(char * name, uint64_t init_val); sem_id ksem_init_open_priv(char * name, uint64_t init_val); int ksem_wait(sem_id sem); int ksem_post(sem_id sem); int ksem_close(sem_id sem); int ksem_destroy(sem_id sem); int ksem_destroy_priv(sem_id sem); uint64_t ksem_getvalue(sem_id sem, int * sval); int ksem_get_semaphores_amount(unsigned int * size); int ksem_get_semaphores_info(sem_info * arr, unsigned int max_size, unsigned int * size); int sys_ksem(void * option, void * arg2, void * arg3, void * arg4); #endif
2.15625
2
2024-11-18T21:46:59.702392+00:00
2020-02-12T12:34:31
2f01a2451b5b85d3836913b25b7a3281d1543f1b
{ "blob_id": "2f01a2451b5b85d3836913b25b7a3281d1543f1b", "branch_name": "refs/heads/master", "committer_date": "2020-02-12T12:34:31", "content_id": "6755e9704b7eef4b64c4fa6715895b9264a88a9b", "detected_licenses": [ "MIT" ], "directory_id": "f8b6ca0460014c17282f1c503b3efe683545d366", "extension": "c", "filename": "ASTDumper.c", "fork_events_count": 2, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 235930183, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 8175, "license": "MIT", "license_type": "permissive", "path": "/src-c/src/AST/ASTDumper.c", "provenance": "stackv2-0130.json.gz:44316", "repo_name": "allen880117/NCTU-compiler-f19-hw4", "revision_date": "2020-02-12T12:34:31", "revision_id": "0e2f9ed1d5870ae9909222b10cc0c9757bc6d51d", "snapshot_id": "915289eec415cced94a459f6a96086a9ec0c3a85", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/allen880117/NCTU-compiler-f19-hw4/0e2f9ed1d5870ae9909222b10cc0c9757bc6d51d/src-c/src/AST/ASTDumper.c", "visit_date": "2022-04-04T09:50:34.590128" }
stackv2
#include "AST/ASTDumper.h" #include "core/list.h" #include "core/utils.h" #include <stdio.h> uint32_t g_indentation = 0u; const uint32_t kIndentionWidth = 2u; static void dumpProgramNode(AstNodeVisitor *visitor, ProgramNode *node) { fprintf(stdout, "%*s", g_indentation, ""); fprintf(stdout, "program <line: %u, col: %u> %s %s\n", node->location.line, node->location.col, node->name, node->type->getPTypeString(node->type, /* compactOrNot */ false)); g_indentation += kIndentionWidth; visitChildOfProgramNode(node, visitor); g_indentation -= kIndentionWidth; } static void dumpDeclarationNode(AstNodeVisitor *visitor, DeclarationNode *node) { fprintf(stdout, "%*s", g_indentation, ""); fprintf(stdout, "declaration <line: %u, col: %u>\n", node->location.line, node->location.col); g_indentation += kIndentionWidth; visitChildOfDeclarationNode(node, visitor); g_indentation -= kIndentionWidth; } static void dumpVariableNode(AstNodeVisitor *visitor, VariableNode *node) { fprintf(stdout, "%*s", g_indentation, ""); fprintf(stdout, "variable <line: %u, col: %u> %s %s\n", node->location.line, node->location.col, node->name, node->type->getPTypeString(node->type, /* compactOrNot */ false)); g_indentation += kIndentionWidth; visitChildOfVariableNode(node, visitor); g_indentation -= kIndentionWidth; } static void dumpConstantValueNode(AstNodeVisitor *visitor, ConstantValueNode *node) { fprintf(stdout, "%*s", g_indentation, ""); fprintf(stdout, "constant <line: %u, col: %u> ", node->location.line, node->location.col); fprintf(stdout, "%s\n", node->constant->getConstantValueString(node->constant)); } static const char *getFunctionPrototypeString(const FunctionNode *node) { const static size_t kBufferSize = 2148u; static char buffer[kBufferSize]; int position = snprintf( buffer, kBufferSize, "%s ", node->type->getPTypeString(node->type, /* compactOrNot */ false)); snprintf(buffer + position, kBufferSize - position, "(%s)", getParametersTypeString(node->parameters)); return buffer; } static void dumpFunctionNode(AstNodeVisitor *visitor, FunctionNode *node) { fprintf(stdout, "%*s", g_indentation, ""); fprintf(stdout, "function declaration <line: %u, col: %u> %s %s\n", node->location.line, node->location.col, node->name, getFunctionPrototypeString(node)); g_indentation += kIndentionWidth; visitChildOfFunctionNode(node, visitor); g_indentation -= kIndentionWidth; } static void dumpCompoundStatementNode(AstNodeVisitor *visitor, CompoundStatementNode *node) { fprintf(stdout, "%*s", g_indentation, ""); fprintf(stdout, "compound statement <line: %u, col: %u>\n", node->location.line, node->location.col); g_indentation += kIndentionWidth; visitChildOfCompoundStatementNode(node, visitor); g_indentation -= kIndentionWidth; } static void dumpAssignmentNode(AstNodeVisitor *visitor, AssignmentNode *node) { fprintf(stdout, "%*s", g_indentation, ""); fprintf(stdout, "assignment statement <line: %u, col: %u>\n", node->location.line, node->location.col); g_indentation += kIndentionWidth; visitChildOfAssignmentNode(node, visitor); g_indentation -= kIndentionWidth; } static void dumpPrintNode(AstNodeVisitor *visitor, PrintNode *node) { fprintf(stdout, "%*s", g_indentation, ""); fprintf(stdout, "print statement <line: %u, col: %u>\n", node->location.line, node->location.col); g_indentation += kIndentionWidth; visitChildOfPrintNode(node, visitor); g_indentation -= kIndentionWidth; } static void dumpReadNode(AstNodeVisitor *visitor, ReadNode *node) { fprintf(stdout, "%*s", g_indentation, ""); fprintf(stdout, "read statement <line: %u, col: %u>\n", node->location.line, node->location.col); g_indentation += kIndentionWidth; visitChildOfReadNode(node, visitor); g_indentation -= kIndentionWidth; } static void dumpVariableReferenceNode(AstNodeVisitor *visitor, VariableReferenceNode *node) { fprintf(stdout, "%*s", g_indentation, ""); fprintf(stdout, "variable reference <line: %u, col: %u> %s\n", node->location.line, node->location.col, node->name); ListNode *n; LIST_FOR_EACH(n, node->indices->begin(node->indices)) { fprintf(stdout, "%*s[\n", g_indentation, ""); g_indentation += kIndentionWidth; AstNode *idx_node = DEREF_LIST_NODE(n); idx_node->accept(idx_node, visitor); g_indentation -= kIndentionWidth; fprintf(stdout, "%*s]\n", g_indentation, ""); } } static void dumpBinaryOperatorNode(AstNodeVisitor *visitor, BinaryOperatorNode *node) { fprintf(stdout, "%*s", g_indentation, ""); fprintf(stdout, "binary operator <line: %u, col: %u> %s\n", node->location.line, node->location.col, kOpString[node->op]); g_indentation += kIndentionWidth; visitChildOfBinaryOperatorNode(node, visitor); g_indentation -= kIndentionWidth; } static void dumpUnaryOperatorNode(AstNodeVisitor *visitor, UnaryOperatorNode *node) { fprintf(stdout, "%*s", g_indentation, ""); fprintf(stdout, "unary operator <line: %u, col: %u> %s\n", node->location.line, node->location.col, kOpString[node->op]); g_indentation += kIndentionWidth; visitChildOfUnaryOperatorNode(node, visitor); g_indentation -= kIndentionWidth; } static void dumpIfNode(AstNodeVisitor *visitor, IfNode *node) { fprintf(stdout, "%*s", g_indentation, ""); fprintf(stdout, "if statement <line: %u, col: %u>\n", node->location.line, node->location.col); g_indentation += kIndentionWidth; node->condition->accept(node->condition, visitor); visitAstNodeList(node->body_statements, visitor); g_indentation -= kIndentionWidth; if (node->else_statements) { fprintf(stdout, "%*s", g_indentation, ""); fprintf(stdout, "else\n"); g_indentation += kIndentionWidth; visitAstNodeList(node->else_statements, visitor); g_indentation -= kIndentionWidth; } } static void dumpWhileNode(AstNodeVisitor *visitor, WhileNode *node) { fprintf(stdout, "%*s", g_indentation, ""); fprintf(stdout, "while statement <line: %u, col: %u>\n", node->location.line, node->location.col); g_indentation += kIndentionWidth; visitChildOfWhileNode(node, visitor); g_indentation -= kIndentionWidth; } static void dumpForNode(AstNodeVisitor *visitor, ForNode *node) { fprintf(stdout, "%*s", g_indentation, ""); fprintf(stdout, "for statement <line: %u, col: %u>\n", node->location.line, node->location.col); g_indentation += kIndentionWidth; visitChildOfForNode(node, visitor); g_indentation -= kIndentionWidth; } static void dumpReturnNode(AstNodeVisitor *visitor, ReturnNode *node) { fprintf(stdout, "%*s", g_indentation, ""); fprintf(stdout, "return statement <line: %u, col: %u>\n", node->location.line, node->location.col); g_indentation += kIndentionWidth; visitChildOfReturnNode(node, visitor); g_indentation -= kIndentionWidth; } static void dumpFunctionCallNode(AstNodeVisitor *visitor, FunctionCallNode *node) { fprintf(stdout, "%*s", g_indentation, ""); fprintf(stdout, "function call statement <line: %u, col: %u> %s\n", node->location.line, node->location.col, node->name); g_indentation += kIndentionWidth; visitChildOfFunctionCallNode(node, visitor); g_indentation -= kIndentionWidth; } AstNodeVisitor *newASTDumper(void) { ASTDumper *visitor = (ASTDumper *)myMalloc(sizeof(ASTDumper)); CONSTRUCT_VISITOR(visitor, dump); return (AstNodeVisitor *)visitor; } void freeASTDumper(void *ad) { free(ad); }
2.59375
3
2024-11-18T21:47:00.110356+00:00
2021-07-26T17:32:28
bebfa1bc29c47eb83df7c8ab85e02dbe3caa91c0
{ "blob_id": "bebfa1bc29c47eb83df7c8ab85e02dbe3caa91c0", "branch_name": "refs/heads/main", "committer_date": "2021-07-26T17:32:28", "content_id": "4334dde6436bbc682a4a70d21663149e117549ad", "detected_licenses": [ "MIT", "ISC" ], "directory_id": "fae45a23a885b72cd27c0ad1b918ad754b5de9fd", "extension": "c", "filename": "fiber.c", "fork_events_count": 3, "gha_created_at": "2021-02-27T13:57:16", "gha_event_created_at": "2021-07-19T15:38:30", "gha_language": "C", "gha_license_id": "MIT", "github_id": 342868949, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 16049, "license": "MIT,ISC", "license_type": "permissive", "path": "/benchmarks/server_delegation/libfiber/src/fiber.c", "provenance": "stackv2-0130.json.gz:44444", "repo_name": "bitslab/CompilerInterrupts", "revision_date": "2021-07-26T17:32:28", "revision_id": "053a105eaf176b85b4c0d5e796ac1d6ee02ad41b", "snapshot_id": "6678700651c7c83fd06451c94188716e37e258f0", "src_encoding": "UTF-8", "star_events_count": 3, "url": "https://raw.githubusercontent.com/bitslab/CompilerInterrupts/053a105eaf176b85b4c0d5e796ac1d6ee02ad41b/benchmarks/server_delegation/libfiber/src/fiber.c", "visit_date": "2023-06-24T18:09:43.148845" }
stackv2
/* * Copyright (c) 2012-2015, Brian Watling and other contributors * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ // #include "fiber.h" #include "fiber_manager.h" #include "mpmc_lifo.h" #include "fiber_cond.h" #include <errno.h> #include <string.h> #include <stdlib.h> #include <assert.h> #include <unistd.h> __thread volatile uint64_t rsp_before_del_call; fiber_mutex_t mutex; fiber_cond_t cond; lock_fifo_queue* lock_queue; volatile int num_of_fibers_finished = 0; void fiber_join_routine(fiber_t* the_fiber, void* result) { the_fiber->result = result; write_barrier();//make sure the result is available before changing the state fiber_manager_t* manager = fiber_manager_get(); manager->num_of_fibers_done++; if(the_fiber->detach_state != FIBER_DETACH_DETACHED) { const int old_state = atomic_exchange_int((int*)&the_fiber->detach_state, FIBER_DETACH_WAIT_FOR_JOINER); if(old_state == FIBER_DETACH_NONE) { //need to wait until another fiber joins this one fiber_manager_set_and_wait(manager, (void**)&the_fiber->join_info, the_fiber); } else if(old_state == FIBER_DETACH_WAIT_TO_JOIN) { //the joining fiber is waiting for us to finish fiber_t* const to_schedule = fiber_manager_clear_or_wait(manager, (void**)&the_fiber->join_info); to_schedule->result = the_fiber->result; to_schedule->state = FIBER_STATE_READY; fiber_manager_schedule(manager, to_schedule); } } the_fiber->state = FIBER_STATE_DONE; manager->done_fiber = the_fiber; fiber_manager_yield(manager); printf("ERROR %p %p\n", the_fiber, manager->maintenance_fiber); assert(0 && "should never get here"); } #ifdef FIBER_STACK_SPLIT __attribute__((__no_split_stack__)) #endif static void* fiber_go_function(void* param) { fiber_t* the_fiber = (fiber_t*)param; /* do maintenance - this is usually done after fiber_context_swap, but we do it here too since we are coming from a new place */ fiber_manager_do_maintenance(); void* const result = the_fiber->run_function(the_fiber->param); fiber_manager_t* manager = fiber_manager_get(); fiber_t* const current_fiber = manager->current_fiber; fiber_join_routine(current_fiber, result); return NULL; } mpmc_lifo_t fiber_free_fibers = MPMC_LIFO_INITIALIZER; volatile int global_id = -1; fiber_t* fiber_create_no_sched(size_t stack_size, fiber_run_function_t run_function, void* param, void* manager) { fiber_manager_t* new_fiber_manager = (fiber_manager_t*) manager; mpsc_fifo_node_t* const node = (mpsc_fifo_node_t*)spsc_lifo_trypop(&(new_fiber_manager->recyled_fibers)); //mpmc_lifo_pop(&fiber_free_fibers); fiber_t* ret = NULL; if(!node) { ret = calloc(1, sizeof(*ret)); if(!ret) { errno = ENOMEM; return NULL; } ret->mpsc_fifo_node = calloc(1, sizeof(*ret->mpsc_fifo_node)); if(!ret->mpsc_fifo_node) { free(ret); errno = ENOMEM; return NULL; } } else { ret = (fiber_t*)node->data; ret->mpsc_fifo_node = node; //we got an old fiber for re-use - destroy the old stack fiber_context_destroy(&ret->context); } assert(ret->mpsc_fifo_node); ret->run_function = run_function; ret->param = param; ret->state = FIBER_STATE_READY; ret->detach_state = FIBER_DETACH_NONE; ret->join_info = NULL; ret->result = NULL; ret->id += 1; ret->is_joining = 0; ret->fork_done = 0; ret->fork_parent = 0; ret->request_state = 0; ret->num_events = 0; ret->lock_ptr = 0; ret->my_manager = new_fiber_manager; if(FIBER_SUCCESS != fiber_context_init(&ret->context, stack_size, &fiber_go_function, ret)) { free(ret); return NULL; } return ret; } fiber_t* fiber_create_and_pin(size_t stack_size, fiber_run_function_t run_function, void* param, int is_server, int core_id) { fiber_manager_t* manager = fiber_managers[core_id]; if (!fiber_managers[core_id]->running){ pthread_mutex_lock(&manager_lock); pthread_cond_signal(&manager_cond[core_id]); pthread_mutex_unlock(&manager_lock); fiber_managers[core_id]->running = 1; } fiber_t* const ret = fiber_create_no_sched(stack_size, run_function, param, manager); if(ret) { if (is_server == 0){ ret->is_joining = 1; ret->my_id = global_id++; } if (is_server == 1){ ret->is_server = 1; next_server_id++; fiber_managers[core_id]->server_id = next_server_id; fiber_managers[core_id]->is_server = 1; fiber_managers[core_id]->this_server = ret; } fiber_manager_schedule(ret->my_manager, ret); } return ret; } fiber_t* server_create(size_t stack_size, fiber_run_function_t run_function, void* param, int server_core) { assert(server_core<TOTAL_NUM_OF_THREADS); // avoid creating server on the same thread as the main fiber assert(server_core != main_manager->core_id && "cannot create a server on the same thread as the main thread -- change main_manager_tindex in fiber_manager_init()"); return fiber_create_and_pin(stack_size, run_function, param, 1, server_core); } fiber_t* fiber_create(size_t stack_size, fiber_run_function_t run_function, void* param) { fiber_manager_t* manager = fiber_manager_assign(); fiber_t* const ret = fiber_create_no_sched(stack_size, run_function, param, manager); if(ret) { ret->is_joining = 1; ret->my_id = global_id++; fiber_manager_schedule(ret->my_manager, ret); } return ret; } fiber_t* server_fiber_fork() { fiber_t* ret = 0; // uint64_t rsp = 0; fiber_manager_t* manager = fiber_manager_get(); fiber_t* current_fiber = manager->current_fiber; current_fiber->fork_parent = 1; ret = fiber_create_no_sched(current_fiber->context.ctx_stack_size, current_fiber->run_function, current_fiber->param, manager); // for context switch uint64_t* rbp, rbx, r12, r13, r14, r15, rip; __asm__ volatile ( "movq %%rbp, %0 \n\t" "movq %%rbx, %1 \n\t" "movq %%r12, %2 \n\t" "movq %%r13, %3 \n\t" "movq %%r14, %4 \n\t" "movq %%r15, %5 \n\t" "leaq 0f(%%rip), %%rcx \n\t" "movq %%rcx, %6 \n\t" : "=m" (rbp), "=m" (rbx), "=m" (r12), "=m" (r13), "=m" (r14), "=m" (r15), "=m" (rip) : : "memory","rcx" ); // find the current rsp of child (based on the relative addr of parent rsp) // -16 is to skip the return address and rbp of the call frame uint64_t* child_rsp = ret->context.ctx_stack + ((void*)(rsp_before_del_call - 16) - current_fiber->context.ctx_stack); // only copy necessary parts of stack uint64_t stack_size_to_copy = ((uint64_t)current_fiber->context.ctx_stack + (uint64_t)current_fiber->context.ctx_stack_size) - (rsp_before_del_call - 16); memcpy(child_rsp, (void*)(rsp_before_del_call-16), stack_size_to_copy); // what is the diff btween stack memory addresses of child and parent uint64_t stack_displacement; stack_displacement = ret->context.ctx_stack - current_fiber->context.ctx_stack; /* change the ret address on the stack to address of label 6 */ *(child_rsp+1) = manager->this_server->ret_addrs[manager->this_server->req_fiber_index][0]; /* update the rbp on the child's stack */ *(child_rsp) = (((uint64_t)*child_rsp)+stack_displacement); uint64_t prev_frame_rbp = *(child_rsp); // because context_swap works this way in libfiber uint64_t* child_curr_frame_rbp = (uint64_t*)((uint64_t)rbp+stack_displacement); *--child_rsp = rip; *--child_rsp = child_curr_frame_rbp; *--child_rsp = rbx; *--child_rsp = r12; *--child_rsp = r13; *--child_rsp = r14; *--child_rsp = r15; ret->context.ctx_stack_pointer = child_rsp; current_fiber = manager->current_fiber; // parent if (current_fiber->fork_parent){ // change the return address for this fiber, so it returns to label 3 after it is done *(((uint64_t*)rsp_before_del_call)-1) = manager->this_server->ret_addrs[manager->this_server->req_fiber_index][1]; // change the rbp of the last frame uint64_t* child_prev_frame_rbp = (uint64_t*)(prev_frame_rbp); *child_prev_frame_rbp = (*child_prev_frame_rbp) + (stack_displacement); return ret; } // child starts from here __asm__ volatile ( "0:\n\t" : : : "memory" ); // jump to label 6, which makes the child return and continue running the server loop __asm__ __volatile__ ("popq %%rbp \n\t" "popq %%r15 \n\t" "jmp *%%r15" ::: "r15"); return 0; } fiber_t* fiber_fork() { fiber_t* ret; uint64_t rsp; __asm__ __volatile__ ("movq %%rsp, %0" : "=m" (rsp):: "memory"); // find the fiber that has called fork fiber_manager_t* manager; fiber_t* current_fiber; manager = fiber_manager_get(); current_fiber = manager->current_fiber; current_fiber->fork_parent = 1; // create a new fiber ret = fiber_create_no_sched(current_fiber->context.ctx_stack_size ,current_fiber->run_function, current_fiber->param, manager); void * start_of_current_stack = current_fiber->context.ctx_stack; void * start_of_new_stack = ret->context.ctx_stack; fiber_manager_schedule(manager, ret); uint64_t* rbp, rbx, r12, r13, r14, r15, rip; __asm__ volatile ( "movq %%rbp, %0 \n\t" "movq %%rbx, %1 \n\t" "movq %%r12, %2 \n\t" "movq %%r13, %3 \n\t" "movq %%r14, %4 \n\t" "movq %%r15, %5 \n\t" "leaq 0f(%%rip), %%rcx \n\t" "movq %%rcx, %6 \n\t" : "=m" (rbp), "=m" (rbx), "=m" (r12), "=m" (r13), "=m" (r14), "=m" (r15), "=m" (rip) : : "memory","rcx" ); // copy the current fiber context to the new fiber memcpy(start_of_new_stack, start_of_current_stack, current_fiber->context.ctx_stack_size); uint64_t* child_rsp = ret->context.ctx_stack + ((void*)rsp - current_fiber->context.ctx_stack); *--child_rsp = rip; *--child_rsp = rbp; *--child_rsp = rbx; *--child_rsp = r12; *--child_rsp = r13; *--child_rsp = r14; *--child_rsp = r15; ret->context.ctx_stack_pointer = child_rsp; __asm__ volatile ( "0:\n\t" : : : "memory" ); current_fiber = manager->current_fiber; // parent if (current_fiber->fork_parent){ return ret; } // child if (!current_fiber->fork_parent){ fiber_manager_do_maintenance(); return 0; } return ret; } fiber_t* fiber_create_from_thread() { fiber_t* ret; ret = calloc(1, sizeof(*ret)); if(!ret) { errno = ENOMEM; return NULL; } ret->mpsc_fifo_node = calloc(1, sizeof(*ret->mpsc_fifo_node)); if(!ret->mpsc_fifo_node) { free(ret); errno = ENOMEM; return NULL; } ret->state = FIBER_STATE_RUNNING; ret->detach_state = FIBER_DETACH_NONE; ret->join_info = NULL; ret->result = NULL; ret->id = 1; ret->is_joining = 0; ret->fork_done = 0; ret->fork_parent = 0; ret->request_state = 0; ret->lock_ptr = 0; if(FIBER_SUCCESS != fiber_context_init_from_thread(&ret->context)) { free(ret); return NULL; } return ret; } #include <stdio.h> int fiber_join(fiber_t* f, void** result) { assert(f); if(result) { *result = NULL; } if(f->detach_state == FIBER_DETACH_DETACHED) { return FIBER_ERROR; } const int old_state = atomic_exchange_int((int*)&f->detach_state, FIBER_DETACH_WAIT_TO_JOIN); if(old_state == FIBER_DETACH_NONE) { //need to wait till the fiber finishes fiber_manager_t* const manager = fiber_manager_get(); fiber_t* const current_fiber = manager->current_fiber; fiber_manager_set_and_wait(manager, (void**)&f->join_info, current_fiber); if(result) { *result = current_fiber->result; } current_fiber->result = NULL; } else if(old_state == FIBER_DETACH_WAIT_FOR_JOINER) { //the other fiber is waiting for us to join if(result) { *result = f->result; } fiber_t* const to_schedule = fiber_manager_clear_or_wait(fiber_manager_get(), (void**)&f->join_info); to_schedule->state = FIBER_STATE_READY; // fiber_manager_schedule(fiber_manager_get(), to_schedule); fiber_manager_schedule(to_schedule->my_manager, to_schedule); } else { //it's either WAIT_TO_JOIN or DETACHED - that's an error! return FIBER_ERROR; } return FIBER_SUCCESS; } int fiber_tryjoin(fiber_t* f, void** result) { assert(f); if(result) { *result = NULL; } if(f->detach_state == FIBER_DETACH_DETACHED) { return FIBER_ERROR; } if(f->detach_state == FIBER_DETACH_WAIT_FOR_JOINER) { //here we've read that the fiber is waiting to be joined. //if the fiber is still waiting to be joined after we atmically change its state, //then we can go ahead and wake it up. if the fiber's state has changed, we can //assume the fiber has been detached or has be joined by some other fiber const int old_state = atomic_exchange_int((int*)&f->detach_state, FIBER_DETACH_WAIT_TO_JOIN); if(old_state == FIBER_DETACH_WAIT_FOR_JOINER) { //the other fiber is waiting for us to join if(result) { *result = f->result; } fiber_t* const to_schedule = fiber_manager_clear_or_wait(fiber_manager_get(), (void**)&f->join_info); to_schedule->state = FIBER_STATE_READY; fiber_manager_schedule(fiber_manager_get(), to_schedule); return FIBER_SUCCESS; } } return FIBER_ERROR; } int server_fiber_switch_to(fiber_t* new_fiber) { fiber_manager_t* manager = fiber_manager_get(); fiber_manager_switch_to(manager, manager->current_fiber, new_fiber); return 1; } /* void fiber_push_and_wait_for_req_lock(int server_no){ push_and_wait_for_req_lock(server_no); } */ int fiber_yield() { fiber_manager_t* manager = fiber_manager_get(); //if(manager->current_fiber->is_server) // manager->current_fiber->state = FIBER_STATE_IS_SERVER; fiber_manager_yield(manager); return 1; } int fiber_detach(fiber_t* f) { if(!f) { return FIBER_ERROR; } const int old_state = atomic_exchange_int((int*)&f->detach_state, FIBER_DETACH_DETACHED); if(old_state == FIBER_DETACH_WAIT_FOR_JOINER || old_state == FIBER_DETACH_WAIT_TO_JOIN) { //wake up the fiber or the fiber trying to join it (this second case is a convenience, pthreads specifies undefined behaviour in that case) fiber_t* const to_schedule = fiber_manager_clear_or_wait(fiber_manager_get(), (void**)&f->join_info); to_schedule->state = FIBER_STATE_READY; fiber_manager_schedule(fiber_manager_get(), to_schedule); } else if(old_state == FIBER_DETACH_DETACHED) { return FIBER_ERROR; } return FIBER_SUCCESS; }
2.046875
2
2024-11-18T21:47:00.282503+00:00
2018-10-16T13:01:54
7776394914be6b2c7b1694efa3c8636be485547d
{ "blob_id": "7776394914be6b2c7b1694efa3c8636be485547d", "branch_name": "refs/heads/alpha", "committer_date": "2018-10-16T13:01:54", "content_id": "5e309e7c153bf040f46423a607794f7a04911dd5", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "2e720dbebd3ad729a98346f34c4656394a9dd94d", "extension": "c", "filename": "JavaMdsLib.c", "fork_events_count": 0, "gha_created_at": "2015-08-26T08:06:49", "gha_event_created_at": "2019-12-05T11:25:39", "gha_language": "C", "gha_license_id": "NOASSERTION", "github_id": 41412893, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3307, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/javatraverser2/java/mds/mdslib/JavaMdsLib.c", "provenance": "stackv2-0130.json.gz:44704", "repo_name": "AndreaRigoni/mdsplus", "revision_date": "2018-10-16T13:01:54", "revision_id": "ea7bd165e0e06e4f71ad9ad6369aace1dbffddcb", "snapshot_id": "673334aced07093f143b428848e4f70366336d00", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/AndreaRigoni/mdsplus/ea7bd165e0e06e4f71ad9ad6369aace1dbffddcb/javatraverser2/java/mds/mdslib/JavaMdsLib.c", "visit_date": "2021-05-23T20:58:23.205897" }
stackv2
#include <jni.h> #include "JavaMdsLib.h" #include <mdsdescrip.h> //descriptor* #include <mds_stdarg.h> //MDS_END_ARG #include <mdsshr.h> //MdsSerialize* #include <stdlib.h> //free #include <string.h> //strlen #include <mdstypes.h> //DTYPE extern int TdiIntrinsic(); extern int TdiEvaluate(); extern int MdsSerializeDscOut(struct descriptor const *in, struct descriptor_xd *out); extern int MdsSerializeDscIn(char const *in, struct descriptor_xd *out); static void RaiseException(JNIEnv * env, int status) { jclass cls = (*env)->FindClass(env, "mds/MdsException"); jmethodID constructor = (*env)->GetMethodID(env, cls, "<init>", "(I)V"); jobject exc = (*env)->NewObject(env, cls, constructor, status); (*env)->ExceptionClear(env); (*env)->Throw(env, exc); } int thisTdiExecute(int narg, struct descriptor *list[], struct descriptor_xd *out_ptr) { int status = 1; EMPTYXD(tmp); status = TdiIntrinsic(99, narg, list, &tmp); if (status & 1) status = TdiEvaluate(tmp.pointer, out_ptr MDS_END_ARG); MdsFree1Dx(&tmp, NULL); return status; } JNIEXPORT jbyteArray JNICALL Java_mds_mdslib_MdsLib_evaluate(JNIEnv * env, jobject obj __attribute__((unused)), jobject jexpr, jobjectArray args) { int status = 1; jsize i,j,jargdim; jbyteArray jarg,result = NULL; jsize nargs = args ? (*env)->GetArrayLength(env,args) : 0; struct descriptor* list[nargs+1]; char* const expr = (char*)(*env)->GetStringUTFChars(env, jexpr, 0); list[0] = &(struct descriptor){strlen(expr), DTYPE_T, CLASS_S, expr}; for(i = 0; i < nargs; ++i) { EMPTYXD(xd); jarg = (jbyteArray)((*env)->GetObjectArrayElement(env,args, i)); jargdim = (*env)->GetArrayLength(env,jarg); jbyte* jbytes = (*env)->GetByteArrayElements(env,jarg, 0); //printf("1-%d\n",(int)i); char* bytes = malloc(jargdim*sizeof(char)); //printf("2-%d\n",(int)i); for (j = 0; j < jargdim; j++) bytes[j] = jbytes[j]; //printf("3-%d\n",(int)i); status = MdsSerializeDscIn(bytes, &xd); //printf("4-%d\n",(int)i); free(bytes); //printf("5-%d\n",(int)i); (*env)->ReleaseByteArrayElements(env, jarg, jbytes, 0); //printf("6-%d\n",(int)i); if (!(status & 1)) break; list[i+1] = xd.pointer; } if ((status & 1)){ //printf("10-%d\n",(int)nargs); EMPTYXD(xd); status = thisTdiExecute(nargs+1, list, &xd); (*env)->ReleaseStringUTFChars(env, jexpr, expr); if ((status & 1)){ EMPTYXD(xds); //printf("11\n"); status = MdsSerializeDscOut(xd.pointer, &xds); if ((status & 1)){ //printf("12\n"); struct descriptor_a* bytes_d = (struct descriptor_a*)xds.pointer; if (bytes_d) { //printf("13\n"); int size = bytes_d->arsize; result = (*env)->NewByteArray(env, size); if (result) { //printf("14+%d\n",(int)size); char* bytes = (char*)bytes_d->pointer; jbyte* jbytes = malloc(size*sizeof(jbyte)); for (i = 0; i < size; i++) jbytes[i] = bytes[i]; (*env)->SetByteArrayRegion(env, result, 0, size, jbytes); free(jbytes); } } } MdsFree1Dx(&xds, NULL); } MdsFree1Dx(&xd, NULL); } if (!(status & 1)) RaiseException(env, status); return result; }
2.1875
2
2024-11-18T21:47:01.697252+00:00
2022-12-04T09:21:22
25339ada759fc03467ae914101cc9a4ecb2b2162
{ "blob_id": "25339ada759fc03467ae914101cc9a4ecb2b2162", "branch_name": "refs/heads/master", "committer_date": "2022-12-04T09:21:22", "content_id": "d1b4f721d7eef18f57f0e3396a7e2647a99f4aec", "detected_licenses": [ "MIT" ], "directory_id": "08f78d1ecbcd9f206df098094a30f1592d2b73a6", "extension": "c", "filename": "mem-test.c", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 247244909, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1198, "license": "MIT", "license_type": "permissive", "path": "/tests/mem-test.c", "provenance": "stackv2-0130.json.gz:45737", "repo_name": "RaZeR-RBI/wal-tools", "revision_date": "2022-12-04T09:21:22", "revision_id": "80a3d0c89aa02a120e34066fa21dc4ac50dc5e5f", "snapshot_id": "fcc57df72f06a781e4cdc25b723c1ab6b9488565", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/RaZeR-RBI/wal-tools/80a3d0c89aa02a120e34066fa21dc4ac50dc5e5f/tests/mem-test.c", "visit_date": "2022-12-08T03:01:14.379587" }
stackv2
#include <setjmp.h> #include <stdarg.h> #include <stddef.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "../common/io.h" #include "cmocka.h" void test_sptr_slice(void **state) { (void)state; unsigned char buffer[] = "abcdefg 1234567\0"; buffer[7] = 0; sptr_t p = {(unsigned char *)&buffer, 16}; sptr_t first_half = sptr_slice(p, 0, 8); assert_false(SPTR_IS_NULL(first_half)); assert_int_equal(first_half.size, 8); assert_string_equal(first_half.ptr, "abcdefg"); sptr_t second_half = sptr_slice(p, 8, 8); assert_false(SPTR_IS_NULL(second_half)); assert_int_equal(second_half.size, 8); assert_string_equal(second_half.ptr, "1234567"); assert_true(SPTR_IS_NULL(sptr_slice(p, 0, 17))); assert_true(SPTR_IS_NULL(sptr_slice(p, 8, 9))); assert_true(SPTR_IS_NULL(sptr_slice(p, 42, 1337))); } void test_xstrdup(void **state) { (void)state; char *s1 = "Hello, world!"; char *s2 = xstrdup(s1); assert_non_null(s2); assert_string_equal(s1, s2); assert_ptr_not_equal(s1, s2); } int main(void) { const struct CMUnitTest tests[] = { cmocka_unit_test(test_sptr_slice), cmocka_unit_test(test_xstrdup), }; return cmocka_run_group_tests(tests, NULL, NULL); }
2.640625
3
2024-11-18T21:47:02.002622+00:00
2021-05-11T14:24:35
e83080c0ebd9ff28b7177c097ddeb54c1044d5eb
{ "blob_id": "e83080c0ebd9ff28b7177c097ddeb54c1044d5eb", "branch_name": "refs/heads/main", "committer_date": "2021-05-11T14:24:35", "content_id": "0b05edfdd6535cf52710ee05b01e7b9ac8a85dfe", "detected_licenses": [ "Zlib" ], "directory_id": "a5a478b9b3229e0edd11334b2b7e25956aec56a9", "extension": "c", "filename": "02_basic_keyboard.c", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 366407375, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1190, "license": "Zlib", "license_type": "permissive", "path": "/examples/02_basic_keyboard.c", "provenance": "stackv2-0130.json.gz:46122", "repo_name": "mrfunkdude/fgl", "revision_date": "2021-05-11T14:24:35", "revision_id": "7e5f0e04ed990c6c0e4d97900eda373300f14937", "snapshot_id": "892124adf7f4da01be44ab2c70c4a237fa7561e6", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/mrfunkdude/fgl/7e5f0e04ed990c6c0e4d97900eda373300f14937/examples/02_basic_keyboard.c", "visit_date": "2023-04-19T23:34:16.083083" }
stackv2
#include "fgl.h" int main() { fgl_open_window(1024, 600, "fgl example 02 - basic keyboard input"); fgl_font fnt = fgl_load_font("res/font.ttf"); fgl_rec rec = (fgl_rec){ 1024/2, 600/2, 64, 64 }; int mode = 0; while (!fgl_is_window_closed()) { // updating square movement if (fgl_is_key_down(KEY_W)) rec.y -= 4; if (fgl_is_key_down(KEY_A)) rec.x -= 4; if (fgl_is_key_down(KEY_S)) rec.y += 4; if (fgl_is_key_down(KEY_D)) rec.x += 4; if (fgl_is_key_pressed(KEY_SPACE)) { mode++; if (mode > 1) { mode = 0; } } fgl_start_drawing(); fgl_set_background(FGL_WHITE); mode == 0 ? fgl_draw_rectangle(rec.x, rec.y, rec.w, rec.h, FGL_RED) : fgl_draw_rectangle_outline(rec.x, rec.y, rec.w, rec.h, FGL_RED); fgl_draw_text(fnt, "press the wasd keys to move the block around", 10, 10, 30, FGL_DARKGRAY); fgl_draw_text(fnt, "press space to see the outline of the block", 10, 50, 30, FGL_DARKGRAY); fgl_stop_drawing(); } fgl_close_window(); return 0; }
2.609375
3
2024-11-18T21:47:02.068850+00:00
2016-05-11T10:51:38
dba37fede719890923c4927f7e126f0d8994b8fa
{ "blob_id": "dba37fede719890923c4927f7e126f0d8994b8fa", "branch_name": "refs/heads/master", "committer_date": "2016-05-11T10:51:38", "content_id": "f52b6ac27fd5763a8b418b9dcae312a9db3f20ec", "detected_licenses": [ "MIT" ], "directory_id": "a271d13bbdffc8e442fe84cdfd82387e5e2f1c4f", "extension": "c", "filename": "jsonp.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 58536824, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3587, "license": "MIT", "license_type": "permissive", "path": "/jsonp.c", "provenance": "stackv2-0130.json.gz:46250", "repo_name": "slowforce/jsmnexample", "revision_date": "2016-05-11T10:51:38", "revision_id": "d96acbb2e2962e01027be75db98363624fc44648", "snapshot_id": "cf86136e4c28c5eed12e96c6eb53d8f9b07773ee", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/slowforce/jsmnexample/d96acbb2e2962e01027be75db98363624fc44648/jsonp.c", "visit_date": "2016-09-13T07:04:35.144769" }
stackv2
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <fcntl.h> #include "log.h" #include "jsmn.h" #include "parameters.h" #define MAX_JSON_TOKENS 256 typedef enum { START, KEY, VALUE, STOP } parse_state; char * read_parameters(char *filename) { char *buf=NULL; long length; FILE *fp = fopen(filename, "rb"); if (fp) { fseek(fp, 0, SEEK_END); length = ftell(fp); fseek(fp, 0, SEEK_SET); if ( (length < MIN_PARAMETER_FILE_LEN) || (length > MAX_PARAMETER_FILE_LEN) ) { fclose(fp); return NULL; } buf = malloc(length); if (buf) { fread(buf, 1, length, fp); fclose(fp); return buf; } fclose(fp); return NULL; } return NULL; } jsmntok_t * json_tokenise(char *js) { jsmn_parser parser; jsmn_init(&parser); unsigned int n = MAX_JSON_TOKENS; jsmntok_t *tokens = malloc(sizeof(jsmntok_t) * n); log_null(tokens); int ret = jsmn_parse(&parser, js, strlen(js), tokens, n); while (ret == JSMN_ERROR_NOMEM) { n = n * 2 + 1; tokens = realloc(tokens, sizeof(jsmntok_t) * n); log_null(tokens); ret = jsmn_parse(&parser, js, strlen(js), tokens, n); } if (ret == JSMN_ERROR_INVAL) log_die("jsmn_parse: invalid JSON string"); if (ret == JSMN_ERROR_PART) log_die("jsmn_parse: truncated JSON string"); return tokens; } int json_token_streq(char *js, jsmntok_t *t, char *s) { return (strncmp(js + t->start, s, t->end - t->start) == 0 && strlen(s) == (size_t) (t->end - t->start)); } char * json_token_tostr(char *js, jsmntok_t *t) { js[t->end] = '\0'; return js + t->start; } int main(void) { int rc; size_t i, j, ii; char *jsonpBuf=NULL; jsmntok_t *tokens=NULL; parse_state state = START; size_t object_tokens = 0; jsonpBuf = read_parameters("./parameters.json"); if (jsonpBuf == NULL) printf("READ parameter file failed\n"); tokens = json_tokenise(jsonpBuf); for (i=0, j=1; j>0; i++,j--) { jsmntok_t *t = &tokens[i]; if (t->type == JSMN_ARRAY || t->type == JSMN_OBJECT) j += (t->size*2); switch (state) { case START: if (t->type != JSMN_OBJECT) log_die("Invalid format: root element must be an object."); state = KEY; object_tokens = t->size; if (object_tokens == 0) state = STOP; break; case KEY: if (t->type == JSMN_STRING) { object_tokens--; char *key = json_token_tostr(jsonpBuf, t); printf("%s: ", key); state = VALUE; } else if (t->type == JSMN_OBJECT) { state = KEY; object_tokens += t->size; } break; case VALUE: if (t->type != JSMN_STRING && t->type != JSMN_PRIMITIVE && \ t->type != JSMN_OBJECT && t->type != JSMN_ARRAY) log_die("Invalid format: object values must be strings or primitives."); if (t->type == JSMN_STRING || t->type == JSMN_PRIMITIVE) { char *value = json_token_tostr(jsonpBuf, t); puts(value); } else if ((t->type == JSMN_OBJECT) || (t->type == JSMN_ARRAY)) { object_tokens += t->size; } state = KEY; if (object_tokens == 0) state = STOP; break; case STOP: // Just consume the tokens break; default: log_die("Invalid state %u", state); } } return 0; }
2.6875
3
2024-11-18T21:47:02.191226+00:00
2020-08-18T00:13:31
e54c210305817788502c4a48b9a89f58618c5b83
{ "blob_id": "e54c210305817788502c4a48b9a89f58618c5b83", "branch_name": "refs/heads/master", "committer_date": "2020-08-18T00:13:31", "content_id": "9ebaa43a7884556ec8bbbe8dc2319cd6c6f641c5", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "f4cca8cb899ccd9f39a609420b9d3cce69265303", "extension": "c", "filename": "simple-cli.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 126535686, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3132, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/languages/c/simple-cli/simple-cli.c", "provenance": "stackv2-0130.json.gz:46378", "repo_name": "charlesdaniels/teaching-learning", "revision_date": "2020-08-18T00:13:31", "revision_id": "d7732c8deeb38ed0f81893219870852c265a148a", "snapshot_id": "83d13528ba01d87af26253f8309f866e3eb3138e", "src_encoding": "UTF-8", "star_events_count": 3, "url": "https://raw.githubusercontent.com/charlesdaniels/teaching-learning/d7732c8deeb38ed0f81893219870852c265a148a/languages/c/simple-cli/simple-cli.c", "visit_date": "2021-04-15T08:39:29.004150" }
stackv2
/* Copyright (c) 2018, Charles Daniels * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /* * This program reads in integers from standard input, performs a simple * arithmetic operation on them, then outputs the result to standard out. * * It is intended to demonstrate correct handling of standard input, standard * output, and argument handling. */ #include "simple-cli.h" int main(int argc, char** argv) { int flag_s; int flag_q; char opt; char* line; size_t line_len; int line_val; line_len = 0; flag_s = 0; flag_q = 1; while ((opt = getopt (argc, argv, "sq:h")) != -1) { switch (opt) { case 's': flag_s = 1; break; case 'q': /* note that atoi() is a bad way to do this * because it has undefined behavior if * the argument cannot be converted */ flag_q = atoi(optarg); break; case 'h': printf("Read integers from standard input, "); printf("add the specified\nquantity "); printf("to each number and print it "); printf("to standard out.\n\n"); printf("-s . . . . . Subtract the quantity"); printf("instead of adding it.\n\n"); printf("-q [int] . . Specify quantity ("); printf("default: 1).\n\n"); printf("-h . . . . . display this message.\n"); } } while(getline(&line, &line_len, stdin) >= 0) { /* remove trailing newline */ for (int i = line_len; i >= 0; i--){ if (line[i] == '\n') { line[i] = '\0'; break; } } /* note that this is unsafe, as atoi has undefined behavior * on error */ line_val = atoi(line); printf("%i\n", line_val + ((flag_s) ? -1 : 1) * (flag_q)); } return 0; }
2.828125
3
2024-11-18T21:47:02.701632+00:00
2018-03-18T12:04:30
03bd8c317af1bc6c5e9ea83b2267b66db334a8ae
{ "blob_id": "03bd8c317af1bc6c5e9ea83b2267b66db334a8ae", "branch_name": "refs/heads/master", "committer_date": "2018-03-18T12:04:30", "content_id": "9517f0f8de17714bbcbc95f596cb2b8e1915b6c5", "detected_licenses": [ "MIT" ], "directory_id": "e2dd792911739ce78f67a3416efd7e38f385654e", "extension": "c", "filename": "hash.c", "fork_events_count": 0, "gha_created_at": "2017-11-02T13:31:47", "gha_event_created_at": "2018-03-18T12:10:11", "gha_language": "C", "gha_license_id": "MIT", "github_id": 109268787, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4574, "license": "MIT", "license_type": "permissive", "path": "/hash.c", "provenance": "stackv2-0130.json.gz:46506", "repo_name": "imhcyx/Gomoku", "revision_date": "2018-03-18T12:04:30", "revision_id": "40c748ce794abcf6df74ba9481b482a714386dd1", "snapshot_id": "76347f00d8880ad2bdf3a8f27bab2b14ac18ce32", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/imhcyx/Gomoku/40c748ce794abcf6df74ba9481b482a714386dd1/hash.c", "visit_date": "2021-09-09T17:19:49.770002" }
stackv2
/* * hash.c: Implementation of Hash Table * */ #include "hash.h" /* Zobrist's hashing method is used here */ #include "zobrist.h" /* hash table node definition */ typedef struct _hash_node { /* next node in this chain */ struct _hash_node *next; /* hash value */ HASHVALUE hash; /* current move count */ int move; /* current depth */ int depth; /* node type */ hash_type type; /* node value */ int value; } hash_node; /* chains in a hash bin (prime is preferred) */ #define HASHBIN_PRIME 65537 /* hash bin definition */ typedef struct { /* chains */ hash_node *node[HASHBIN_PRIME]; /* subscript = hash % HASHBIN_PRIME */ /* mutex for chains */ pthread_mutex_t mutex[HASHBIN_PRIME]; /* performance counter */ int count[HASHBIN_PRIME]; } hash_bin; /* hash bins */ static hash_bin m_hashbin[256]; /* subscript = high byte of hash */ /* initialized state */ static int m_init = 0; /* hash by board_t */ /* prototype in hash.h */ HASHVALUE hash_board(board_t board) { int i, j, piece; int index; HASHVALUE value = 0; /* iterate all points */ for (i=0; i<BOARD_W; i++) for (j=0; j<BOARD_H; j++) { piece = board[i][j]; if (piece) { index = i*BOARD_H+j; value ^= zobrist[index*piece]; } } return value; } /* apply delta and hash by board_t */ /* prototype in hash.h */ HASHVALUE hash_board_apply_delta(HASHVALUE oldvalue, board_t board, int newx, int newy, int piece, int remove) { int index; index = newx*BOARD_H+newy; board[newx][newy] = remove ? I_FREE : piece; return oldvalue ^ zobrist[index*piece]; } /* initialize hash table */ /* prototype in hash.h */ void hashtable_init() { int i, j; /* if not initialized */ if (!m_init) { /* clear structures */ memset(m_hashbin, 0, sizeof(m_hashbin)); /* initialize mutexes */ for (i=0; i<256; i++) for (j=0; j<HASHBIN_PRIME; j++) pthread_mutex_init(&m_hashbin[i].mutex[j], 0); m_init = 1; } } /* finalize hash table */ /* prototype in hash.h */ void hashtable_fini() { int i, j; hash_node *node, *next; /* return if finalized */ if (!m_init) return; /* iterate all chains in all bins */ for (i=0; i<256; i++) for (j=0; j<HASHBIN_PRIME; j++) { /* get root node */ node = m_hashbin[i].node[j]; #if 0 /* test only */ fprintf(stderr, "bin[%d][%d]: %d\n", i, j, m_hashbin[i].count[j]); #endif /* free all nodes */ while (node) { next = node->next; free(node); node = next; } /* destroy mutexes */ pthread_mutex_destroy(&m_hashbin[i].mutex[j]); } /* clear state */ m_init = 0; } /* store value to hash table */ /* prototype in hash.h */ /* thread-safe */ void hashtable_store(HASHVALUE hash, int move, int depth, hash_type type, int value) { int i, j; hash_node *node; /* calculate bin and chain number */ i = hash >> (sizeof(HASHVALUE)-1)*8; j = hash % HASHBIN_PRIME; /* lock chain */ pthread_mutex_lock(&m_hashbin[i].mutex[j]); /* allocate node */ node = malloc(sizeof(hash_node)); /* exit on error in malloc */ if (!node) return; /* fill stuffs */ node->hash = hash; node->move = move; node->depth = depth; node->type = type; node->value = value; /* insert as root node */ node->next = m_hashbin[i].node[j]; m_hashbin[i].node[j] = node; /* update counter */ m_hashbin[i].count[j]++; /* unlock chain */ pthread_mutex_unlock(&m_hashbin[i].mutex[j]); } /* look up value in hash table */ /* prototype in hash.h */ /* thread-safe */ int hashtable_lookup(HASHVALUE hash, int move, int depth, int alpha, int beta, int *pvalue) { int i, j; int result; hash_node *node; /* calculate bin and chain number */ i = hash >> (sizeof(HASHVALUE)-1)*8; j = hash % HASHBIN_PRIME; /* lock chain */ pthread_mutex_lock(&m_hashbin[i].mutex[j]); /* is empty chain */ if (!(node = m_hashbin[i].node[j])) { result = 0; goto _exit; } /* linear search */ while (node) { if (node->hash == hash && node->move == move && node->depth >= depth) { /* limit result by parameters */ if (node->type == hash_exact || (node->type == hash_alpha && node->value <= alpha) || (node->type == hash_beta && node->value >= beta)) { /* found */ *pvalue = node->value; result = 1; goto _exit; } } node = node->next; } /* not found */ result = 0; _exit: /* unlock chain */ pthread_mutex_unlock(&m_hashbin[i].mutex[j]); return result; }
2.9375
3
2024-11-18T21:47:02.987961+00:00
2021-09-29T17:05:26
a0ef4398f97b8e3a55bb077cf24e91eebb07dec9
{ "blob_id": "a0ef4398f97b8e3a55bb077cf24e91eebb07dec9", "branch_name": "refs/heads/master", "committer_date": "2021-09-29T17:05:26", "content_id": "3aa60534f5c1649909958cdf2a49e657461af9ba", "detected_licenses": [ "MIT" ], "directory_id": "79080a23aada9b5f6bcb4951a98e55f4262de888", "extension": "c", "filename": "pine.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 298722202, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1513, "license": "MIT", "license_type": "permissive", "path": "/src/pine.c", "provenance": "stackv2-0130.json.gz:46891", "repo_name": "strah19/Pine", "revision_date": "2021-09-29T17:05:26", "revision_id": "af95cec1e3ee3a9b75851be116df29b396a85ccd", "snapshot_id": "ad9c000cd0b409b82ea4118b79a0c90fbb7a74fa", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/strah19/Pine/af95cec1e3ee3a9b75851be116df29b396a85ccd/src/pine.c", "visit_date": "2023-08-10T17:17:18.147705" }
stackv2
/** * @file pine.c * @author strah19 * @date May 23 2021 * @version 1.0 * * @section LICENSE * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License, or (at your option) any later version. * * @section DESCRIPTION * * This file contains generic utility functions that can be * used across the project files. */ #include "../include/pine.h" #include <time.h> #include <stdio.h> #include <ctype.h> bool is_char_digit(char character) { return (character >= 48 && character <= 57); } bool is_char_good_for_variable_name(char character, uint32_t token_len) { return ((character >= 65 && character <= 90) || (character >= 97 && character <= 122) || character == '_' || (character >= 48 && character <= 57 && token_len > 1)) ? true : false; } void remove_whitespaces(char* s) { char* d = s; do while (isspace(*s)) s++; while (*d++ = *s++); } int maxim(int num1, int num2) { return (num1 > num2 ) ? num1 : num2; } int minim(int num1, int num2) { return (num1 > num2 ) ? num2 : num1; } static clock_t bench_mark_clock; void begin_debug_benchmark() { bench_mark_clock = clock(); } float end_debug_benchmark(const char* label) { clock_t end = clock(); double time_spent = (double)(end - bench_mark_clock); printf("Benchmark time for %s is %f ms.\n", label, time_spent); return (float) time_spent; }
2.65625
3
2024-11-18T21:47:03.247638+00:00
2023-08-25T10:13:54
8fae05824ffdfa5618feb87a7d7b86db4a992884
{ "blob_id": "8fae05824ffdfa5618feb87a7d7b86db4a992884", "branch_name": "refs/heads/master", "committer_date": "2023-08-25T10:13:54", "content_id": "a58cc1b12a654634a1095a3308f804344f2003b0", "detected_licenses": [ "MIT" ], "directory_id": "98e838b6e6401dc4aa43cfbf3eb8c5dcff37ab9b", "extension": "c", "filename": "rugged_revwalk.c", "fork_events_count": 229, "gha_created_at": "2010-09-10T16:18:17", "gha_event_created_at": "2023-09-04T13:56:50", "gha_language": "C", "gha_license_id": "MIT", "github_id": 901663, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 12978, "license": "MIT", "license_type": "permissive", "path": "/ext/rugged/rugged_revwalk.c", "provenance": "stackv2-0130.json.gz:47150", "repo_name": "libgit2/rugged", "revision_date": "2023-08-25T10:13:54", "revision_id": "fefa6e644fecacad1d56b98e787d344fd632836a", "snapshot_id": "a01cf74e9692dcdd49217f7178c667b13d420fc5", "src_encoding": "UTF-8", "star_events_count": 1258, "url": "https://raw.githubusercontent.com/libgit2/rugged/fefa6e644fecacad1d56b98e787d344fd632836a/ext/rugged/rugged_revwalk.c", "visit_date": "2023-08-31T14:27:08.896691" }
stackv2
/* * Copyright (C) the Rugged contributors. All rights reserved. * * This file is part of Rugged, distributed under the MIT license. * For full terms see the included LICENSE file. */ #include "rugged.h" extern VALUE rb_mRugged; extern VALUE rb_cRuggedObject; VALUE rb_cRuggedWalker; extern const rb_data_type_t rugged_object_type; static void rb_git_walk__free(git_revwalk *walk) { git_revwalk_free(walk); } VALUE rugged_walker_new(VALUE klass, VALUE owner, git_revwalk *walk) { VALUE rb_walk = Data_Wrap_Struct(klass, NULL, &rb_git_walk__free, walk); rugged_set_owner(rb_walk, owner); return rb_walk; } static void push_commit_oid(git_revwalk *walk, const git_oid *oid, int hide) { int error; if (hide) error = git_revwalk_hide(walk, oid); else error = git_revwalk_push(walk, oid); rugged_exception_check(error); } static void push_commit_ref(git_revwalk *walk, const char *ref, int hide) { int error; if (hide) error = git_revwalk_hide_ref(walk, ref); else error = git_revwalk_push_ref(walk, ref); rugged_exception_check(error); } static void push_commit_1(git_revwalk *walk, VALUE rb_commit, int hide) { if (rb_obj_is_kind_of(rb_commit, rb_cRuggedObject)) { git_object *object; TypedData_Get_Struct(rb_commit, git_object, &rugged_object_type, object); push_commit_oid(walk, git_object_id(object), hide); return; } Check_Type(rb_commit, T_STRING); if (RSTRING_LEN(rb_commit) == 40) { git_oid commit_oid; if (git_oid_fromstr(&commit_oid, RSTRING_PTR(rb_commit)) == 0) { push_commit_oid(walk, &commit_oid, hide); return; } } push_commit_ref(walk, StringValueCStr(rb_commit), hide); } static void push_commit(git_revwalk *walk, VALUE rb_commit, int hide) { if (rb_type(rb_commit) == T_ARRAY) { long i; for (i = 0; i < RARRAY_LEN(rb_commit); ++i) push_commit_1(walk, rb_ary_entry(rb_commit, i), hide); return; } push_commit_1(walk, rb_commit, hide); } /* * call-seq: * Walker.new(repository) -> walker * * Create a new +Walker+ instance able to walk commits found * in +repository+, which is a <tt>Rugged::Repository</tt> instance. */ static VALUE rb_git_walker_new(VALUE klass, VALUE rb_repo) { git_repository *repo; git_revwalk *walk; int error; Data_Get_Struct(rb_repo, git_repository, repo); error = git_revwalk_new(&walk, repo); rugged_exception_check(error); return rugged_walker_new(klass, rb_repo, walk);; } /* * call-seq: * walker.push(commit) -> nil * * Push one new +commit+ to start the walk from. +commit+ must be a * +String+ with the OID of a commit in the repository, or a <tt>Rugged::Commit</tt> * instance. * * More than one commit may be pushed to the walker (to walk several * branches simulataneously). * * Duplicate pushed commits will be ignored; at least one commit must have been * pushed as a starting point before the walk can begin. * * walker.push("92b22bbcb37caf4f6f53d30292169e84f5e4283b") */ static VALUE rb_git_walker_push(VALUE self, VALUE rb_commit) { git_revwalk *walk; Data_Get_Struct(self, git_revwalk, walk); push_commit(walk, rb_commit, 0); return Qnil; } static VALUE rb_git_walker_push_range(VALUE self, VALUE range) { git_revwalk *walk; Data_Get_Struct(self, git_revwalk, walk); rugged_exception_check(git_revwalk_push_range(walk, StringValueCStr(range))); return Qnil; } /* * call-seq: * walker.hide(commit) -> nil * * Hide the given +commit+ (and all its parents) from the * output in the revision walk. */ static VALUE rb_git_walker_hide(VALUE self, VALUE rb_commit) { git_revwalk *walk; Data_Get_Struct(self, git_revwalk, walk); push_commit(walk, rb_commit, 1); return Qnil; } /* * call-seq: * walker.sorting(sort_mode) -> nil * * Change the sorting mode for the revision walk. * * This will cause +walker+ to be reset. */ static VALUE rb_git_walker_sorting(VALUE self, VALUE ruby_sort_mode) { git_revwalk *walk; Data_Get_Struct(self, git_revwalk, walk); git_revwalk_sorting(walk, FIX2INT(ruby_sort_mode)); return Qnil; } /* * call-seq: * walker.simplify_first_parent() -> nil * * Simplify the walk to the first parent of each commit. */ static VALUE rb_git_walker_simplify_first_parent(VALUE self) { git_revwalk *walk; Data_Get_Struct(self, git_revwalk, walk); git_revwalk_simplify_first_parent(walk); return Qnil; } /* * call-seq: * walker.count -> Fixnum * * Returns the amount of objects a walker iterated over. If an argument or * block is given this method delegates to +Enumerable#count+. */ static VALUE rb_git_walker_count(int argc, VALUE *argv, VALUE self) { git_revwalk *walk; git_oid commit_oid; int error = 0; uint64_t count = 0; if (argc > 0 || rb_block_given_p()) return rb_call_super(argc, argv); Data_Get_Struct(self, git_revwalk, walk); while (((error = git_revwalk_next(&commit_oid, walk)) == 0) && ++count != UINT64_MAX); if (error != GIT_ITEROVER) rugged_exception_check(error); return ULONG2NUM(count); } /* * call-seq: * walker.reset -> nil * * Remove all pushed and hidden commits and reset the +walker+ * back into a blank state. */ static VALUE rb_git_walker_reset(VALUE self) { git_revwalk *walk; Data_Get_Struct(self, git_revwalk, walk); git_revwalk_reset(walk); return Qnil; } struct walk_options { VALUE rb_owner; VALUE rb_options; git_repository *repo; git_revwalk *walk; int oid_only; uint64_t offset, limit; }; static void load_walk_limits(struct walk_options *w, VALUE rb_options) { VALUE rb_value = rb_hash_lookup(rb_options, CSTR2SYM("offset")); if (!NIL_P(rb_value)) { Check_Type(rb_value, T_FIXNUM); w->offset = FIX2ULONG(rb_value); } rb_value = rb_hash_lookup(rb_options, CSTR2SYM("limit")); if (!NIL_P(rb_value)) { Check_Type(rb_value, T_FIXNUM); w->limit = FIX2ULONG(rb_value); } } static VALUE load_all_options(VALUE _payload) { struct walk_options *w = (struct walk_options *)_payload; VALUE rb_options = w->rb_options; VALUE rb_show, rb_hide, rb_sort, rb_simp, rb_oid_only; load_walk_limits(w, rb_options); rb_sort = rb_hash_lookup(rb_options, CSTR2SYM("sort")); if (!NIL_P(rb_sort)) { Check_Type(rb_sort, T_FIXNUM); git_revwalk_sorting(w->walk, FIX2INT(rb_sort)); } rb_show = rb_hash_lookup(rb_options, CSTR2SYM("show")); if (!NIL_P(rb_show)) { push_commit(w->walk, rb_show, 0); } rb_hide = rb_hash_lookup(rb_options, CSTR2SYM("hide")); if (!NIL_P(rb_hide)) { push_commit(w->walk, rb_hide, 1); } rb_simp = rb_hash_lookup(rb_options, CSTR2SYM("simplify")); if (RTEST(rb_simp)) { git_revwalk_simplify_first_parent(w->walk); } rb_oid_only = rb_hash_lookup(rb_options, CSTR2SYM("oid_only")); if (RTEST(rb_oid_only)) { w->oid_only = 1; } return Qnil; } static VALUE do_walk(VALUE _payload) { struct walk_options *w = (struct walk_options *)_payload; int error; git_oid commit_oid; while ((error = git_revwalk_next(&commit_oid, w->walk)) == 0) { if (w->offset > 0) { w->offset--; continue; } if (w->oid_only) { rb_yield(rugged_create_oid(&commit_oid)); } else { git_commit *commit; error = git_commit_lookup(&commit, w->repo, &commit_oid); rugged_exception_check(error); rb_yield( rugged_object_new(w->rb_owner, (git_object *)commit) ); } if (--w->limit == 0) break; } if (error != GIT_ITEROVER) rugged_exception_check(error); return Qnil; } /* * call-seq: * Rugged::Walker.walk(repo, options={}) { |commit| block } * * Create a Walker object, initialize it with the given options * and perform a walk on the repository; the lifetime of the * walker is bound to the call and it is immediately cleaned * up after the walk is over. * * The following options are available: * * - +sort+: Sorting mode for the walk (or an OR combination * of several sorting modes). * * - +show+: Tips of the repository that will be walked; * this is necessary for the walk to yield any results. * A tip can be a 40-char object ID, an existing +Rugged::Commit+ * object, a reference, or an +Array+ of several of these * (if you'd like to walk several tips in parallel). * * - +hide+: Same as +show+, but hides the given tips instead * so they don't appear on the walk. * * - +oid_only+: if +true+, the walker will yield 40-char OIDs * for each commit, instead of real +Rugged::Commit+ objects. * Defaults to +false+. * * - +simplify+: if +true+, the walk will be simplified * to the first parent of each commit. * * Example: * * Rugged::Walker.walk(repo, * show: "92b22bbcb37caf4f6f53d30292169e84f5e4283b", * sort: Rugged::SORT_DATE|Rugged::SORT_TOPO, * oid_only: true) do |commit_oid| * puts commit_oid * end * * generates: * * 92b22bbcb37caf4f6f53d30292169e84f5e4283b * 6b750d5800439b502de669465b385e5f469c78b6 * ef9207141549f4ffcd3c4597e270d32e10d0a6bc * cb75e05f0f8ac3407fb3bd0ebd5ff07573b16c9f * ... */ static VALUE rb_git_walk(int argc, VALUE *argv, VALUE self) { VALUE rb_repo, rb_options; struct walk_options w; int exception = 0; RETURN_ENUMERATOR(self, argc, argv); rb_scan_args(argc, argv, "10:", &rb_repo, &rb_options); Data_Get_Struct(rb_repo, git_repository, w.repo); rugged_exception_check(git_revwalk_new(&w.walk, w.repo)); w.rb_owner = rb_repo; w.rb_options = rb_options; w.oid_only = 0; w.offset = 0; w.limit = UINT64_MAX; if (!NIL_P(w.rb_options)) rb_protect(load_all_options, (VALUE)&w, &exception); if (!exception) rb_protect(do_walk, (VALUE)&w, &exception); git_revwalk_free(w.walk); if (exception) rb_jump_tag(exception); return Qnil; } static VALUE rb_git_walk_with_opts(int argc, VALUE *argv, VALUE self, int oid_only) { VALUE rb_options; struct walk_options w; RETURN_ENUMERATOR(self, argc, argv); rb_scan_args(argc, argv, "01", &rb_options); Data_Get_Struct(self, git_revwalk, w.walk); w.repo = git_revwalk_repository(w.walk); w.rb_owner = rugged_owner(self); w.rb_options = Qnil; w.oid_only = oid_only; w.offset = 0; w.limit = UINT64_MAX; if (!NIL_P(rb_options)) load_walk_limits(&w, rb_options); return do_walk((VALUE)&w); } /* * call-seq: * walker.each { |commit| block } * walker.each -> Enumerator * * Perform the walk through the repository, yielding each * one of the commits found as a <tt>Rugged::Commit</tt> instance * to +block+. * * If no +block+ is given, an +Enumerator+ will be returned. * * The walker must have been previously set-up before a walk can be performed * (i.e. at least one commit must have been pushed). * * walker.push("92b22bbcb37caf4f6f53d30292169e84f5e4283b") * walker.each { |commit| puts commit.oid } * * generates: * * 92b22bbcb37caf4f6f53d30292169e84f5e4283b * 6b750d5800439b502de669465b385e5f469c78b6 * ef9207141549f4ffcd3c4597e270d32e10d0a6bc * cb75e05f0f8ac3407fb3bd0ebd5ff07573b16c9f * ... */ static VALUE rb_git_walker_each(int argc, VALUE *argv, VALUE self) { return rb_git_walk_with_opts(argc, argv, self, 0); } /* * call-seq: * walker.each_oid { |commit| block } * walker.each_oid -> Enumerator * * Perform the walk through the repository, yielding each * one of the commit oids found as a <tt>String</tt> * to +block+. * * If no +block+ is given, an +Enumerator+ will be returned. * * The walker must have been previously set-up before a walk can be performed * (i.e. at least one commit must have been pushed). * * walker.push("92b22bbcb37caf4f6f53d30292169e84f5e4283b") * walker.each { |commit_oid| puts commit_oid } * * generates: * * 92b22bbcb37caf4f6f53d30292169e84f5e4283b * 6b750d5800439b502de669465b385e5f469c78b6 * ef9207141549f4ffcd3c4597e270d32e10d0a6bc * cb75e05f0f8ac3407fb3bd0ebd5ff07573b16c9f * ... */ static VALUE rb_git_walker_each_oid(int argc, VALUE *argv, VALUE self) { return rb_git_walk_with_opts(argc, argv, self, 1); } void Init_rugged_revwalk(void) { rb_cRuggedWalker = rb_define_class_under(rb_mRugged, "Walker", rb_cObject); rb_undef_alloc_func(rb_cRuggedWalker); rb_define_singleton_method(rb_cRuggedWalker, "new", rb_git_walker_new, 1); rb_define_singleton_method(rb_cRuggedWalker, "walk", rb_git_walk, -1); rb_define_method(rb_cRuggedWalker, "push", rb_git_walker_push, 1); rb_define_method(rb_cRuggedWalker, "push_range", rb_git_walker_push_range, 1); rb_define_method(rb_cRuggedWalker, "each", rb_git_walker_each, -1); rb_define_method(rb_cRuggedWalker, "each_oid", rb_git_walker_each_oid, -1); rb_define_method(rb_cRuggedWalker, "walk", rb_git_walker_each, -1); rb_define_method(rb_cRuggedWalker, "hide", rb_git_walker_hide, 1); rb_define_method(rb_cRuggedWalker, "reset", rb_git_walker_reset, 0); rb_define_method(rb_cRuggedWalker, "sorting", rb_git_walker_sorting, 1); rb_define_method(rb_cRuggedWalker, "simplify_first_parent", rb_git_walker_simplify_first_parent, 0); rb_define_method(rb_cRuggedWalker, "count", rb_git_walker_count, -1); }
2.53125
3
2024-11-18T21:47:04.121262+00:00
2018-12-08T15:21:28
bd8585601180b8bc5154ce341bef198fc5e19d5f
{ "blob_id": "bd8585601180b8bc5154ce341bef198fc5e19d5f", "branch_name": "refs/heads/master", "committer_date": "2018-12-08T15:21:28", "content_id": "f5d834464c420e5ef4b0c9fda45b24389d142776", "detected_licenses": [ "MIT" ], "directory_id": "8a4a6b8102855d17182b8de48ccad4c480280427", "extension": "h", "filename": "nopsys.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": 1660, "license": "MIT", "license_type": "permissive", "path": "/src/nopsys.h", "provenance": "stackv2-0130.json.gz:47411", "repo_name": "SmalltalkLand/nopsys", "revision_date": "2018-12-08T15:21:28", "revision_id": "242c10bed2c1bc151d1cdb00225abeb66a5f58f9", "snapshot_id": "8114fc7f4e4c0e210464479abdfe2ce813115746", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/SmalltalkLand/nopsys/242c10bed2c1bc151d1cdb00225abeb66a5f58f9/src/nopsys.h", "visit_date": "2021-10-08T06:00:43.796348" }
stackv2
#include "types.h" #define breakpoint() __asm("xchg %bx, %bx"); // a function that does *nothing*, but you can put a breakpoint on it with gdb like this: // (gdb) b fbreakpoint // so that it then works similarly to xchg bx, bx void fbreakpoint(); int nopsys_vm_main(void *image, uint image_length); __attribute__ ((noreturn)) void nopsys_exit(); uint8_t inb(uint16_t port); void outb(uint16_t port, uint8_t byte); void ints_init(); uint16_t get_CS(); void* get_CR2(); void enable_sse(); void enable_paging_using(void* page_dir); computer_t* current_computer(); uintptr_t computer_first_free_address(computer_t *computer); uint64_t current_microseconds(void); uint64_t current_seconds(void); void display_initialize_hardcoded(display_info_t *video_info); void display_initialize_from_mbi(display_info_t *video_info, multiboot_info_t *mbi); void fill_rectangle (display_info_t *display, int width, int height, int x, int y, uint color); void bitblt_32bit_to_fb(display_info_t *display, uint32_t *bitmap, int width, int height, int x, int y, uint32_t colormask); void console_initialize_stdout(); void console_set_debugging(bool debugging); void console_std_put_string(const char string[]); void console_std_put_char(char c); __attribute__ ((noreturn)) void serial_enter_debug_mode(); void serial_write(uchar a); void semaphore_signal_with_index(int i); void debug_print_call_stack(); #define BYTES_PER_LINE_PADDED(width, depth) ((((width) + 31) >> 5 << 2) * (depth)) #define BYTES_PER_LINE_FLOOR(width, depth) ((((width) >> 5) << 2) * (depth)) #define BYTES_PER_PIXEL(width, depth) (width * (depth>>3)) #define COLOR_GREEN 0x0E70
2.21875
2
2024-11-18T21:47:04.226112+00:00
2014-09-14T13:35:08
4d274903dc953a4503a440b7029f345d50964a44
{ "blob_id": "4d274903dc953a4503a440b7029f345d50964a44", "branch_name": "refs/heads/master", "committer_date": "2014-09-14T13:35:08", "content_id": "7934c9ce8797f48193dc3a9e828db2a05fd472ae", "detected_licenses": [ "MIT" ], "directory_id": "55c06adcd864e09e9334e920f5f1a2f90c12ae4c", "extension": "c", "filename": "bmp_intr.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 28634105, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2679, "license": "MIT", "license_type": "permissive", "path": "/src/bmp_intr.c", "provenance": "stackv2-0130.json.gz:47541", "repo_name": "timofonic/megadrive-demo-zombie", "revision_date": "2014-09-14T13:35:08", "revision_id": "de96dee23e387a47af43858e610eae3c98cda6d9", "snapshot_id": "d1400a96a45abd006cd86a630e15363e7597dd6a", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/timofonic/megadrive-demo-zombie/de96dee23e387a47af43858e610eae3c98cda6d9/src/bmp_intr.c", "visit_date": "2018-01-15T07:30:21.894248" }
stackv2
#include "config.h" #include "types.h" #include "memory.h" #include "vdp.h" #include "bmp_cmn.h" #include "bmp_intr.h" #include "vdp_tile.h" #include "vdp_pal.h" #include "vdp_bg.h" #include "tab_vram.h" u8 *bmp_buffer_0 = NULL; u8 *bmp_buffer_1 = NULL; // used for polygone drawing s16 *LeftPoly = NULL; s16 *RightPoly = NULL; u16 (*doBlit)(); void _bmp_init() { // release first if needed if (bmp_buffer_0) MEM_free(bmp_buffer_0); if (bmp_buffer_1) MEM_free(bmp_buffer_1); if (LeftPoly) MEM_free(LeftPoly); if (RightPoly) MEM_free(RightPoly); // tile map allocation bmp_buffer_0 = MEM_alloc(BMP_WIDTH * BMP_HEIGHT * sizeof(u8)); bmp_buffer_1 = MEM_alloc(BMP_WIDTH * BMP_HEIGHT * sizeof(u8)); // polygon edge buffer allocation //LeftPoly = MEM_alloc(BMP_HEIGHT * sizeof(s16)); //RightPoly = MEM_alloc(BMP_HEIGHT * sizeof(s16)); // need 64x64 cells sized plan VDP_setPlanSize(BMP_PLANWIDTH, BMP_PLANHEIGHT); // clear plan (complete tilemap) VDP_clearPlan(BMP_PLAN, 1); VDP_waitDMACompletion(); // set to -1 to force flags update on new BMP_setFlags(...) bmp_flags = -1; bmp_state = 0; // default bmp_buffer_read = bmp_buffer_0; bmp_buffer_write = bmp_buffer_1; } void _bmp_end() { // release memory if (bmp_buffer_0) { MEM_free(bmp_buffer_0); bmp_buffer_0 = NULL; } if (bmp_buffer_1) { MEM_free(bmp_buffer_1); bmp_buffer_1 = NULL; } if (LeftPoly) { MEM_free(LeftPoly); LeftPoly = NULL; } if (RightPoly) { MEM_free(RightPoly); RightPoly = NULL; } } void _bmp_setFlags(u16 value) { bmp_flags = value; // flag dependancies if (bmp_flags & BMP_ENABLE_EXTENDEDBLANK) bmp_flags |= BMP_ENABLE_BLITONBLANK; if (bmp_flags & BMP_ENABLE_BLITONBLANK) bmp_flags |= BMP_ENABLE_ASYNCFLIP; if (bmp_flags & BMP_ENABLE_ASYNCFLIP) bmp_flags |= BMP_ENABLE_WAITVSYNC; // clear pending task bmp_state &= ~(BMP_STAT_FLIPWAITING | BMP_STAT_BLITTING); } void _bmp_doFlip() { // wait for DMA completion if used otherwise VDP writes can be corrupted VDP_waitDMACompletion(); // copy tile buffer to VRAM if ((*doBlit)()) { u16 vscr; // display FPS if (HAS_FLAG(BMP_ENABLE_FPSDISPLAY)) BMP_showFPS(0); // switch displayed buffer if (READ_IS_FB0) vscr = ((BMP_PLANHEIGHT * BMP_YPIXPERTILE) * 0) / 2; else vscr = ((BMP_PLANHEIGHT * BMP_YPIXPERTILE) * 1) / 2; VDP_setVerticalScroll(BMP_PLAN, 0, vscr); // flip done bmp_state &= ~BMP_STAT_FLIPWAITING; } }
2.34375
2
2024-11-18T21:47:05.421197+00:00
2021-06-20T18:11:04
de7b4850021d087aa03874ed00acb5a89a7f5afb
{ "blob_id": "de7b4850021d087aa03874ed00acb5a89a7f5afb", "branch_name": "refs/heads/main", "committer_date": "2021-06-20T18:11:04", "content_id": "a468d6a5d040f92b0097063b16464e087d43c82f", "detected_licenses": [ "MIT" ], "directory_id": "3db22e1780ba3721c9f1f9423b53049305e443ef", "extension": "c", "filename": "stack.c", "fork_events_count": 1, "gha_created_at": "2021-04-01T19:19:52", "gha_event_created_at": "2021-04-05T19:15:32", "gha_language": "C", "gha_license_id": "MIT", "github_id": 353803686, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 799, "license": "MIT", "license_type": "permissive", "path": "/Lists/stack/stack.c", "provenance": "stackv2-0130.json.gz:48057", "repo_name": "CristinaNilvan/c-data-structures", "revision_date": "2021-06-20T18:11:04", "revision_id": "d7eb1aaa5f3e2691ad8d0ae24abc978d543db5b4", "snapshot_id": "a33d096a6e3793d53e861eb4cb47171b9b2ad9fb", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/CristinaNilvan/c-data-structures/d7eb1aaa5f3e2691ad8d0ae24abc978d543db5b4/Lists/stack/stack.c", "visit_date": "2023-06-03T10:49:50.969589" }
stackv2
#include <stdio.h> #include <stdlib.h> #include "stack.h" Node * createNode(int key) { Node * node = (Node *)malloc(sizeof(Node)); node->key = key; node->next = NULL; return node; } void initializeList(Node ** stack) { *stack = NULL; } void push(Node ** stack, int givenKey) { Node * node = createNode(givenKey); if (*stack == NULL) *stack = node; else { node->next = *stack; *stack = node; } } void pop(Node ** stack) { Node * toDelete; if (*stack != NULL) { toDelete = *stack; *stack = (*stack)->next; free(toDelete); } } void printList(Node * node) { if (node == NULL) { printf("\n"); return; } printf("%d ", node->key); printList(node->next); }
3.578125
4
2024-11-18T21:47:05.505718+00:00
2019-07-13T20:02:49
64823e8177d23003cee1fae86f1485e3a12dee70
{ "blob_id": "64823e8177d23003cee1fae86f1485e3a12dee70", "branch_name": "refs/heads/master", "committer_date": "2019-07-13T20:05:01", "content_id": "7868466425d967f4970fd0d94182a1795854863a", "detected_licenses": [ "Unlicense" ], "directory_id": "c9bd3fbdd2bb5ee66ca8d908f1ace46d7b6edb76", "extension": "c", "filename": "bidouill.c", "fork_events_count": 6, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 178410989, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 787, "license": "Unlicense", "license_type": "permissive", "path": "/myintros/bidouill.c", "provenance": "stackv2-0130.json.gz:48185", "repo_name": "miniupnp/DreamCastIntros", "revision_date": "2019-07-13T20:02:49", "revision_id": "33d760b82f64d0567b4038e9a3ee3707fee505a5", "snapshot_id": "bfad83d33d24d92600f9680adc80530baf93e81e", "src_encoding": "UTF-8", "star_events_count": 15, "url": "https://raw.githubusercontent.com/miniupnp/DreamCastIntros/33d760b82f64d0567b4038e9a3ee3707fee505a5/myintros/bidouill.c", "visit_date": "2023-08-22T18:54:44.260172" }
stackv2
#include <stdlib.h> #include <stdio.h> #include <memory.h> #define BUFFERSIZE 256 int main(int argc, char **argv) { FILE * in; FILE * out; unsigned char * buffer; int i; int n=BUFFERSIZE; buffer = (unsigned char *)malloc(BUFFERSIZE); printf("DTC\nUsage %s outfile infile\n",argv[0]); in=fopen(argv[2],"rb"); out=fopen(argv[1],"wb"); if((out==NULL) || (in==NULL)) { printf("Erreur d'ouverture des fichiers\n"); return 1; } while (n==BUFFERSIZE) { n = fread(buffer, 1, BUFFERSIZE, in); printf("%i octets lus... ",n); /* c'est ici que le bidouillage peut commencer ! */ for(i=0; i<n; i++) { buffer[i] *= 2; } /* fin du bidouillage ! */ printf("%i octet ecris.\n",fwrite(buffer, 1, n, out)); } fclose(out); fclose(in); free(buffer); return 0; }
3.078125
3
2024-11-18T21:47:05.631053+00:00
2017-04-03T09:54:21
489469269364a9141fb600626d1c3d4d0c3c284d
{ "blob_id": "489469269364a9141fb600626d1c3d4d0c3c284d", "branch_name": "refs/heads/master", "committer_date": "2017-04-03T09:54:21", "content_id": "17f03d205650cb733872d7ab57649ea9222e12fa", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "d94f17ff904a30546cc3575c91efd93b4bcaa965", "extension": "c", "filename": "splitpool.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 87059999, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 901, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/src/cmd/splitpool.c", "provenance": "stackv2-0130.json.gz:48314", "repo_name": "szhilkin/openvsx-2.0", "revision_date": "2017-04-03T09:54:21", "revision_id": "e6dbf87a4171ba0210ecd08c13d9e5fdeff9b70a", "snapshot_id": "c1d769883f53fbaf064fb3ad28ebb521e732ff3a", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/szhilkin/openvsx-2.0/e6dbf87a4171ba0210ecd08c13d9e5fdeff9b70a/src/cmd/splitpool.c", "visit_date": "2021-01-18T22:36:30.046015" }
stackv2
// Copyright © 2012 Coraid, Inc. // All rights reserved. #include <u.h> #include <libc.h> #include <bio.h> #include <ctype.h> #include <vsxcmds.h> enum { Maxbuf = 1024, }; static void usage(void) { fprint(2, "usage: %s pool [...]\n", argv0); exits("usage"); } static int splitpool(char *pool) { int n; char buf[Maxbuf]; Pool *p; p = getpoolstatus(pool); if (p == nil) return -1; freepool(p); n = readfile(buf, sizeof buf, "/n/xlate/pool/%s/split", pool); if (n < 0) return -1; if (n > 0) { buf[n] = '\0'; fprint(1, "Run on another VSX: /restorepool %s %s", pool, buf); } return 0; } void main(int argc, char **argv) { int i; ARGBEGIN { default: usage(); } ARGEND if (serieserr(argc, argv, Noto) < 0) errfatal("%r"); if (argc <= 0) usage(); for (i = 0; i < argc; i++) if (splitpool(argv[i]) < 0) errskip(argc - i, argv + i); exits(nil); }
2.1875
2
2024-11-18T21:47:06.493953+00:00
2019-10-30T04:33:43
1aad3b221c31cf3d59116f22f8d736e7858c183a
{ "blob_id": "1aad3b221c31cf3d59116f22f8d736e7858c183a", "branch_name": "refs/heads/master", "committer_date": "2019-10-30T04:33:43", "content_id": "3ede9755815421a59a7f2ba4b4400a1dc3b39fcf", "detected_licenses": [ "MIT" ], "directory_id": "f79ef81e6e4e989ed14ed0283a9737f731101aab", "extension": "c", "filename": "tcp.c", "fork_events_count": 4, "gha_created_at": "2019-11-16T13:54:01", "gha_event_created_at": "2019-11-16T13:54:02", "gha_language": null, "gha_license_id": "MIT", "github_id": 222106609, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5366, "license": "MIT", "license_type": "permissive", "path": "/Unix Family/Linux.Ownit/libnet/test/Ethernet/tcp.c", "provenance": "stackv2-0130.json.gz:48572", "repo_name": "TheWover/Family", "revision_date": "2019-10-30T04:33:43", "revision_id": "f3ed1713c6b71823d8236b80148b60982dd906e1", "snapshot_id": "9d5597eda68aeee5e99de993176b6bd1366b57f1", "src_encoding": "UTF-8", "star_events_count": 3, "url": "https://raw.githubusercontent.com/TheWover/Family/f3ed1713c6b71823d8236b80148b60982dd906e1/Unix Family/Linux.Ownit/libnet/test/Ethernet/tcp.c", "visit_date": "2020-09-11T15:11:21.601776" }
stackv2
/* * $Id: tcp.c,v 1.1.1.1 2000/05/25 00:28:49 route Exp $ * * libnet * tcp.c - Build a TCP packet at the link layer * * Copyright (c) 1998, 1999, 2000 Mike D. Schiffman <mike@infonexus.com> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #if (HAVE_CONFIG_H) #include "../../include/config.h" #endif #include "../libnet_test.h" int main(int argc, char *argv[]) { int c; u_long src_ip, dst_ip; u_short src_prt, dst_prt; u_char *cp; char errbuf[256]; char *device = NULL; struct libnet_link_int *l; printf("link layer TCP packet building/writing test\n"); src_ip = 0; dst_ip = 0; src_prt = 0; dst_prt = 0; while ((c = getopt(argc, argv, "i:d:s:")) != EOF) { switch (c) { /* * We expect the input to be of the form `ip.ip.ip.ip.port`. We * point cp to the last dot of the IP address/port string and * then seperate them with a NULL byte. The optarg now points to * just the IP address, and cp points to the port. */ case 'd': if (!(cp = strrchr(optarg, '.'))) { usage(argv[0]); } *cp++ = 0; dst_prt = (u_short)atoi(cp); if (!(dst_ip = libnet_name_resolve(optarg, 1))) { fprintf(stderr, "Bad destination IP address: %s\n", optarg); exit(1); } break; case 's': if (!(cp = strrchr(optarg, '.'))) { usage(argv[0]); } *cp++ = 0; src_prt = (u_short)atoi(cp); if (!(src_ip = libnet_name_resolve(optarg, 1))) { fprintf(stderr, "Bad source IP address: %s\n", optarg); exit(1); } break; case 'i': device = optarg; break; default: exit(EXIT_FAILURE); } } if (!src_ip || !src_prt || !dst_ip || !dst_prt || !device) { usage(argv[0]); exit(EXIT_FAILURE); } if ((l = libnet_open_link_interface(device, errbuf)) == NULL) { fprintf(stderr, "libnet_open_link_interface: %s\n", errbuf); exit(EXIT_FAILURE); } c = send_tcp(l, device, src_ip, src_prt, dst_ip, dst_prt); return (c == -1 ? EXIT_FAILURE : EXIT_SUCCESS); } int send_tcp(struct libnet_link_int *l, u_char *device, u_long src_ip, u_short src_prt, u_long dst_ip, u_short dst_prt) { int n; u_char *buf; if (libnet_init_packet(LIBNET_TCP_H + LIBNET_IP_H + LIBNET_ETH_H, &buf) == -1) { perror("no packet memory"); exit(EXIT_FAILURE); } /* * Ethernet header */ libnet_build_ethernet(enet_dst, enet_src, ETHERTYPE_IP, NULL, 0, buf); libnet_build_ip(LIBNET_TCP_H, 0, 242, 0, 64, IPPROTO_TCP, src_ip, dst_ip, NULL, 0, buf + LIBNET_ETH_H); libnet_build_tcp(src_prt, dst_prt, 111111, 999999, TH_SYN, 32767, 0, NULL, 0, buf + LIBNET_IP_H + LIBNET_ETH_H); libnet_do_checksum(buf + LIBNET_ETH_H, IPPROTO_IP, LIBNET_IP_H); libnet_do_checksum(buf + LIBNET_ETH_H, IPPROTO_TCP, LIBNET_TCP_H); n = libnet_write_link_layer(l, device, buf, LIBNET_ETH_H + LIBNET_IP_H + LIBNET_TCP_H); if (n != LIBNET_ETH_H + LIBNET_IP_H + LIBNET_TCP_H) { fprintf(stderr, "Oopz. Only wrote %d bytes\n", n); } else { printf("Wrote %d byte TCP packet through linktype %d\n", n, l->linktype); } libnet_destroy_packet(&buf); return (n); } void usage(u_char *name) { fprintf(stderr, "usage: %s -i interface -s source_ip.source_port" " -d destination_ip.destination_port\n", name); } /* EOF */
2.15625
2
2024-11-18T21:47:06.546262+00:00
2020-09-13T13:38:02
aeececde81b20ca01c250d34e0273947c3eadd4e
{ "blob_id": "aeececde81b20ca01c250d34e0273947c3eadd4e", "branch_name": "refs/heads/master", "committer_date": "2020-09-13T13:38:02", "content_id": "e98d36b1f34855c0e6467ebe9a2c14233eb61932", "detected_licenses": [ "MIT" ], "directory_id": "0efe233f552fe255f16608bc0b0104e183a4ab26", "extension": "c", "filename": "parseconf.c", "fork_events_count": 0, "gha_created_at": "2020-07-26T06:36:49", "gha_event_created_at": "2020-08-25T13:03:59", "gha_language": "C", "gha_license_id": null, "github_id": 282591717, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4273, "license": "MIT", "license_type": "permissive", "path": "/src/parseconf.c", "provenance": "stackv2-0130.json.gz:48701", "repo_name": "HONGYU-LEE/MiniFTP", "revision_date": "2020-09-13T13:38:02", "revision_id": "6e21e569716c91a34e51e7f8fa333ff49d38605f", "snapshot_id": "d24fa7fb2f420fe0ad01569d85c22f1d1e6227b3", "src_encoding": "GB18030", "star_events_count": 0, "url": "https://raw.githubusercontent.com/HONGYU-LEE/MiniFTP/6e21e569716c91a34e51e7f8fa333ff49d38605f/src/parseconf.c", "visit_date": "2022-12-18T05:41:21.831714" }
stackv2
#include"parseconf.h" #include"tunable.h" //建立配置项与变量的映射表 //bool类型 static struct parseconf_bool_setting { const char* p_setting_name; int* p_var; }parseconf_bool_array[] = { {"pasv_enable", &tunable_pasv_enable}, {"port_enable", &tunable_port_enable} }; //uint类型 static struct parseconf_uint_setting { const char* p_setting_name; unsigned int* p_var; }parseconf_uint_array[] = { {"listen_port", &tunable_listen_port}, {"max_clients", &tunable_max_clients}, {"max_per_ip", &tunable_max_per_ip}, {"accept_timeout", &tunable_accept_timeout}, {"connect_timeout", &tunable_connect_timeout}, {"idle_session_timeout", &tunable_idle_session_timeout}, {"data_connection_timeout", &tunable_data_connection_timeout}, {"chown_uploads", &tunable_chown_uploads}, {"local_umask", &tunable_local_umask}, {"upload_max_rate", &tunable_upload_max_rate}, {"download_max_rate", &tunable_download_max_rate} }; //字符类型 static struct parseconf_str_setting { const char* p_setting_name; const char** p_var; }parseconf_str_array[] = { {"listen_address", &tunable_listen_address} }; void parseconf_load_setting(const char *setting) { //分割变量名与值 pasv_enable=1; char key[MAX_KEY_VALUE_SIZE] = {0}; char value[MAX_KEY_VALUE_SIZE] = {0}; str_split(setting, key, value, '='); int list_size = sizeof(parseconf_str_array) / sizeof(struct parseconf_str_setting); int i; for(i = 0; i < list_size; i++) { if(strcmp(key, parseconf_str_array[i].p_setting_name) == 0) { const char** p_cur_setting = parseconf_str_array[i].p_var; //如果之前不为空,直接释放,防止内存泄漏 if(*p_cur_setting != NULL) { free((char*)(*p_cur_setting)); } *p_cur_setting = strdup(value);//自动开辟空间的深拷贝 return; } } list_size = sizeof(parseconf_bool_array) / sizeof(struct parseconf_bool_setting); for(i = 0; i < list_size; i++) { if(strcmp(key, parseconf_bool_array[i].p_setting_name) == 0) { str_to_upper(value); if(strcmp(value, "YES") == 0) { *parseconf_bool_array[i].p_var = 1; } else if(strcmp(value, "NO") == 0) { *parseconf_bool_array[i].p_var = 0; } else { printf("%d\n", strlen(value)); fprintf(stderr, "bad bool value in config file for : %s\n", key); exit(EXIT_FAILURE); } return; } } list_size = sizeof(parseconf_uint_array) / sizeof(struct parseconf_uint_setting); for(i = 0; i < list_size; i++) { if(strcmp(key, parseconf_uint_array[i].p_setting_name) == 0) { //0则认为默认 if(value[0] != '0') { *parseconf_uint_array[i].p_var = atoi(value); } return; } } } void parseconf_load_file(const char *path) { FILE* fp = fopen(path, "r"); if(fp == NULL) { ERR_EXIT("parseconf_load_file."); } char setting_line[MAX_SETTING_LINE] = { 0 }; while(fgets(setting_line, MAX_SETTING_LINE, fp) != NULL) { if(strlen(setting_line) == 0 || setting_line[0] == '#') { continue; } str_trim_crlf(setting_line); parseconf_load_setting(setting_line); memset(setting_line, 0, MAX_SETTING_LINE); } fclose(fp); } void parseconf_test() { parseconf_load_file("MiniFTP.conf"); printf("tunable_pasv_enable = %d\n", tunable_pasv_enable); printf("tunable_port_enable = %d\n", tunable_port_enable); printf("tunable_listen_port = %d\n", tunable_listen_port); printf("tunable_max_clients = %d\n", tunable_max_clients); printf("tunable_max_per_ip = %d\n", tunable_max_per_ip); printf("tunable_accept_timeout = %d\n", tunable_accept_timeout); printf("tunable_connect_timeout = %d\n", tunable_connect_timeout); printf("tunable_idle_session_timeout = %d\n", tunable_idle_session_timeout); printf("tunable_data_connection_timeout = %d\n", tunable_data_connection_timeout); printf("tunable_chown_uploads = %d\n", tunable_chown_uploads); printf("tunable_loacl_umask = %d\n", tunable_local_umask); printf("tunable_upload_max_rate = %d\n", tunable_upload_max_rate); printf("tunable_download_mas_rate = %d\n", tunable_download_max_rate); printf("tunable_listen_address = %s\n", tunable_listen_address); }
2.78125
3
2024-11-18T21:47:06.912073+00:00
2018-08-15T23:54:53
a0243d0781feba5bcfb619edbf95ca850772a76d
{ "blob_id": "a0243d0781feba5bcfb619edbf95ca850772a76d", "branch_name": "refs/heads/master", "committer_date": "2018-08-15T23:54:53", "content_id": "4c886cccc427cd5b55a169777d12d9a4e663183b", "detected_licenses": [ "MIT" ], "directory_id": "44d5f438d4c90e362754b522708f7333d9476ee2", "extension": "c", "filename": "shm_cnt.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": 1320, "license": "MIT", "license_type": "permissive", "path": "/Operating Systems/proj6/xv6-public-xv6-rev9/shm_cnt.c", "provenance": "stackv2-0130.json.gz:48829", "repo_name": "GavinOlson1/FSU_Projects", "revision_date": "2018-08-15T23:54:53", "revision_id": "455b8d345bcf7724962f6e7c57c652a1271ebace", "snapshot_id": "3276ac7596166c183808003a54db14aa28a77157", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/GavinOlson1/FSU_Projects/455b8d345bcf7724962f6e7c57c652a1271ebace/Operating Systems/proj6/xv6-public-xv6-rev9/shm_cnt.c", "visit_date": "2020-06-08T05:18:15.263385" }
stackv2
/* Test Harness for Shared Memory Implmentation */ /* ( Implmentation can be found in vm.c) */ /* Blake Kershaw */ /* COP4610 */ /* Assignment 6 */ #include "types.h" #include "user.h" #include "stat.h" #include "uspinlock.h" struct shm_cnt{ struct uspinlock lock; volatile int cnt; }; int main(){ int pid = fork(); if (pid < 0) { printf(1,"Fork failed\n"); exit(); } // Parent Process if (pid > 0){ struct shm_cnt *pbase; pbase = (struct shm_cnt *) shm_open(0xbeefbeef); int p; uinitlock(&pbase->lock); for(p = 0; p < 10000; p++){ uacquire(&pbase->lock); pbase->cnt += 1; urelease(&pbase->lock); } wait(); //the following should print 200000 printf(1,"pbase->cnt value: %d\n", pbase->cnt); shm_close(0xbeefbeef); exit(); } //end parent proccess // Child Process else{ sleep(1); struct shm_cnt *cbase; cbase = (struct shm_cnt *) shm_open(0xbeefbeef); int c; for(c = 0; c < 10000; c++){ uacquire(&cbase->lock); cbase->cnt +=1; urelease(&cbase->lock); } shm_close(0xbeefbeef); exit(); } //end child process return 0; }
2.875
3
2024-11-18T21:47:07.321697+00:00
2022-08-27T15:39:18
724ac226f77ae3211feede5f9b5a33b881e6cb77
{ "blob_id": "724ac226f77ae3211feede5f9b5a33b881e6cb77", "branch_name": "refs/heads/master", "committer_date": "2022-08-27T15:39:18", "content_id": "be62c4873a3ae3d6b0e4dc2e2dd805b480de7d72", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "f5e413e241b9862b94e22a46df5c91d10c4cfe1c", "extension": "h", "filename": "rdm_utility.h", "fork_events_count": 14, "gha_created_at": "2016-04-21T00:25:27", "gha_event_created_at": "2022-02-12T16:58:46", "gha_language": "HTML", "gha_license_id": "BSD-3-Clause", "github_id": 56729706, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3860, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/src/rdm/rdm_utility.h", "provenance": "stackv2-0130.json.gz:49472", "repo_name": "claudeheintz/LXSAMD21DMX", "revision_date": "2022-08-27T15:39:18", "revision_id": "e88cbd3036a0dfd46f0aea0e16be7012bd8b1636", "snapshot_id": "1098868b1256e3592463256dfbb5335a3813a92b", "src_encoding": "UTF-8", "star_events_count": 25, "url": "https://raw.githubusercontent.com/claudeheintz/LXSAMD21DMX/e88cbd3036a0dfd46f0aea0e16be7012bd8b1636/src/rdm/rdm_utility.h", "visit_date": "2022-09-28T07:12:22.920826" }
stackv2
/**************************************************************************/ /*! @file rdm_utility.h @author Claude Heintz @license BSD (see LXESP8266DMX.h) @copyright 2017 by Claude Heintz RDM support for DMX Driver for ESP32 defines constants and utility functions @section HISTORY v1.0 - First release */ /**************************************************************************/ /* RDM Packet format 0 Start Code 1 Sub Start Code 2 Message Length 3 Destination UID 4 5 6 7 8 9 Source UID 10 11 12 13 14 15 Transaction Number 16 Port ID/Response Type 17 Message Count 18 SubDevice MSB 19 SubDevice LSB 20 Command Class 21 Parameter id (PID) MSB 22 Parameter id (PID) LSB 23 Paramater Data Length 24 Variable length Data Message with zero parameter len is 24 bytes plus 2 byte checksum, 26 bytes total: byte[2] = 24 + byte[23] bytesSent = 26 + byte[23] */ #ifndef RDMutility_h #define RDMutility_h #ifdef __cplusplus extern "C" { #endif #include <inttypes.h> /***************************** defines *****************************/ // start codes #define RDM_START_CODE 0xCC #define RDM_SUB_START_CODE 0x01 // command classes #define RDM_DISCOVERY_COMMAND 0x10 #define RDM_DISC_COMMAND_RESPONSE 0x11 #define RDM_GET_COMMAND 0x20 #define RDM_GET_COMMAND_RESPONSE 0x21 #define RDM_SET_COMMAND 0x30 #define RDM_SET_COMMAND_RESPONSE 0x31 // response types #define RDM_RESPONSE_TYPE_ACK 0x00 // discovery-network management Parameter IDs (PID) #define RDM_DISC_UNIQUE_BRANCH 0x0001 #define RDM_DISC_MUTE 0x0002 #define RDM_DISC_UNMUTE 0x0003 // product information PIDs #define RDM_DEVICE_INFO 0x0060 #define RDM_DEVICE_START_ADDR 0x00F0 #define RDM_DEVICE_MODEL_DESC 0x0080 #define RDM_DEVICE_MFG_LABEL 0x0081 #define RDM_DEVICE_DEV_LABEL 0x0082 // control information PIDs #define RDM_IDENTIFY_DEVICE 0x1000 // packet heading constants #define RDM_PORT_ONE 0x01 #define RDM_ROOT_DEVICE 0x0000 // RDM packet byte indexes #define RDM_IDX_START_CODE 0 #define RDM_IDX_SUB_START_CODE 1 #define RDM_IDX_PACKET_SIZE 2 #define RDM_IDX_DESTINATION_UID 3 #define RDM_IDX_SOURCE_UID 9 #define RDM_IDX_TRANSACTION_NUM 15 #define RDM_IDX_PORT 16 #define RDM_IDX_RESPONSE_TYPE 16 #define RDM_IDX_MSG_COUNT 17 #define RDM_IDX_SUB_DEV_MSB 18 #define RDM_IDX_SUB_DEV_LSB 19 #define RDM_IDX_CMD_CLASS 20 #define RDM_IDX_PID_MSB 21 #define RDM_IDX_PID_LSB 22 #define RDM_IDX_PARAM_DATA_LEN 23 // packet sizes with and without checksum, an additional 2 bytes #define RDM_PKT_BASE_MSG_LEN 24 #define RDM_PKT_BASE_TOTAL_LEN 26 #define RDM_DISC_UNIQUE_BRANCH_PKTL 38 #define RDM_DISC_UNIQUE_BRANCH_MSGL 0x24 #define RDM_DISC_UNIQUE_BRANCH_PDL 0x0C // discover unique branch reply #define RDM_DISC_PREAMBLE_SEPARATOR 0xAA /***************************** functions *****************************/ /* * rdmChecksum calculates mod 0x10000 sum of bytes * this is used in an RDM packet as follows * bytes[len] = rdmChecksum[MSB] * bytes[len+1] = rdmChecksum[LSB] * */ uint16_t rdmChecksum(uint8_t* bytes, uint8_t len); /* * testRDMChecksum evaluates cksum and returns true if both * bytes[index] == cksum[MSB] * bytes[index+1] == cksum[LSB] * */ uint8_t testRDMChecksum(uint16_t cksum, uint8_t* data, uint8_t index); /* * validateRDMPacket tests the RDM start code in pdata[0] * then it calls rdmChecksum using the packet length * which is the third byte of packet * checksum = rdmChecksum( pdata, pdata[2] ) * validateRDMPacket returns the result of testRDMChecksum( checksum, pdata, pdata[2] ) * */ uint8_t validateRDMPacket(uint8_t* pdata); #ifdef __cplusplus } #endif #endif //RDMutility_h
2.0625
2
2024-11-18T21:47:07.390048+00:00
2016-05-25T15:51:09
4f7d63bfe1cda390f1cb9205c48cb24fbfdb9588
{ "blob_id": "4f7d63bfe1cda390f1cb9205c48cb24fbfdb9588", "branch_name": "refs/heads/master", "committer_date": "2016-05-25T15:51:09", "content_id": "2df167ee492cee84c8f4bfe7108ebf4b060641e7", "detected_licenses": [ "MIT" ], "directory_id": "c5cc0804b482fac88b5c11b4c15d6cdf8876e540", "extension": "c", "filename": "assignment_12.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": 1750, "license": "MIT", "license_type": "permissive", "path": "/assignment_12/assignment_12.c", "provenance": "stackv2-0130.json.gz:49600", "repo_name": "devarshar/Assignments_C", "revision_date": "2016-05-25T15:51:09", "revision_id": "4906cbe487ad1a7c33d7f64a0828d6d414828025", "snapshot_id": "490c54efc59fc0eeb441ba5e71a3957d328bf5d5", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/devarshar/Assignments_C/4906cbe487ad1a7c33d7f64a0828d6d414828025/assignment_12/assignment_12.c", "visit_date": "2021-06-01T00:49:26.660833" }
stackv2
/***************************************************** * NAME: assignment_12.c * * * * AUTHOR: Devarsh Ruparelia * * * * EMAIL: devarsh.ruparelia@gmail.com * * * * PURPOSE: Program to check if a number is prime * * or not. * * * * DATE: 03/05/2016 * * * *****************************************************/ #include <stdio.h> int main() { // Variable: int input_numb; int i = 2; // User Input: printf("Welcome to prime number checker program.\n"); printf("Enter a number to be checked: "); scanf("%d", &input_numb); // Input & Output: /******************************************************************* * For Loop components in (): * * Initialization/ Declaration, Condition Checking, Counter Modify * *******************************************************************/ for(i = 2; i < input_numb || input_numb == 2; i++){ if(input_numb % i == 0) { printf("The number, %d, is not prime.\n", input_numb); break; } else if(i == (input_numb - 1)) { printf("The number, %d, is prime.\n", input_numb); break; } } if (input_numb == 0 || input_numb == 1) { printf("Restart the program and enter a positive integer greater than 1.\n"); } printf("Processed completely.\n"); }
3.78125
4
2024-11-18T21:47:07.682087+00:00
2022-01-17T17:13:01
6ff933086f6c04a4780affd3e3cf4cb06dbbd270
{ "blob_id": "6ff933086f6c04a4780affd3e3cf4cb06dbbd270", "branch_name": "refs/heads/master", "committer_date": "2022-01-17T17:13:01", "content_id": "42d3b7da11fb6ed1f1a87a6d9e7a9eae37a28574", "detected_licenses": [ "MIT" ], "directory_id": "6bae42928b6661295bc4d68cbcf0639440c7ee59", "extension": "c", "filename": "dra_pulse.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 234803140, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3013, "license": "MIT", "license_type": "permissive", "path": "/gpio/dra_pulse.c", "provenance": "stackv2-0130.json.gz:50118", "repo_name": "sthaid/proj_diffraction", "revision_date": "2022-01-17T17:13:01", "revision_id": "77de00503c47a46e3d30a8aee26dc38a15c80a2f", "snapshot_id": "32644c52c5829040fb04f7f7498eed170b368c0a", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/sthaid/proj_diffraction/77de00503c47a46e3d30a8aee26dc38a15c80a2f/gpio/dra_pulse.c", "visit_date": "2022-01-19T19:35:39.352345" }
stackv2
#include <stdio.h> #include <stdint.h> #include <stdbool.h> #include <string.h> #include <signal.h> #include <math.h> #include <sys/time.h> #include <dra_gpio.h> #include <util_misc.h> // defines #define GPIO_INPUT_PIN 20 #define GPIO_OUTPUT_LED_PIN 21 // variables volatile bool done; // prototypes void get_pulse_rate(unsigned int intvl_us, double *gpio_read_rate, double *pulse_rate); void sigalrm_handler(int signum); char * stars(double value, int stars_max, double value_max); // ----------------- MAIN -------------------------------------------- int main(int argc, char **argv) { struct sigaction act; double gpio_read_rate, pulse_rate; // init dra_gpio capability if (gpio_init() != 0) { return 1; } set_gpio_pin_mode(GPIO_INPUT_PIN, PIN_MODE_INPUT); // register for SIGALRM memset(&act, 0, sizeof(act)); act.sa_handler = sigalrm_handler; sigaction(SIGALRM, &act, NULL); // loop forever while (true) { // get pulse rate, and print results get_pulse_rate(1000000, &gpio_read_rate, &pulse_rate); #if 0 printf("gpio_read_rate = %.3f pulse_rate = %.6f (units million/sec)\n", gpio_read_rate/1000000, pulse_rate/1000000); #else printf("%6.3f - %s\n", pulse_rate/1000000, stars(pulse_rate/1000000, 160, 1.0)); #endif // short delay usleep(500000); } // done return 0; } // ----------------- GET PULSE RATE ----------------------------------- void get_pulse_rate(unsigned int intvl_us, double *gpio_read_rate, double *pulse_rate) { struct itimerval new_value, old_value; uint64_t start_us, end_us; double intvl_secs; int v, v_last=0, pulse_cnt=0, read_cnt=0; // set interval timer, which will set the done flag memset(&new_value, 0, sizeof(new_value)); new_value.it_value.tv_sec = intvl_us / 1000000; new_value.it_value.tv_usec = intvl_us % 1000000; setitimer(ITIMER_REAL, &new_value, &old_value); // loop until done start_us = microsec_timer(); while (!done) { // read gpio input v = gpio_read(GPIO_INPUT_PIN); read_cnt++; // if detected rising edge then increment pulse_cnt if (v != 0 && v_last == 0) { pulse_cnt++; } v_last = v; } end_us = microsec_timer(); done = false; // calculate return rates intvl_secs = (end_us - start_us) / 1000000.; *gpio_read_rate = read_cnt / intvl_secs; *pulse_rate = pulse_cnt / intvl_secs; } void sigalrm_handler(int signum) { done = true; } char * stars(double value, int stars_max, double value_max) { static char stars[1000]; int len; bool overflow = false; len = nearbyint((value / value_max) * stars_max); if (len > stars_max) { len = stars_max; overflow = true; } memset(stars, '*', len); stars[len] = '\0'; if (overflow) { strcpy(stars+len, "..."); } return stars; }
3.015625
3
2024-11-18T21:47:08.037427+00:00
2017-03-06T23:57:27
ad25b9c219a6abe095a31babc289d7f92c6c1a55
{ "blob_id": "ad25b9c219a6abe095a31babc289d7f92c6c1a55", "branch_name": "refs/heads/master", "committer_date": "2017-03-06T23:57:27", "content_id": "d02490e30a05d3356d87a67933a3ec8adbe27839", "detected_licenses": [ "Apache-2.0" ], "directory_id": "523c11506c2d6914ee92dd6c64d1730120e686cd", "extension": "c", "filename": "p4ns_db.c", "fork_events_count": 0, "gha_created_at": "2017-01-12T23:19:28", "gha_event_created_at": "2019-07-05T06:20:54", "gha_language": "C", "gha_license_id": "Apache-2.0", "github_id": 78795949, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 7445, "license": "Apache-2.0", "license_type": "permissive", "path": "/modules/p4ns_common/module/src/p4ns_db.c", "provenance": "stackv2-0130.json.gz:50644", "repo_name": "herlenashavi/p4factory", "revision_date": "2017-03-06T23:57:27", "revision_id": "ef05d0a235617724a6fa23c861d2c003cdda7a11", "snapshot_id": "18d4b7955bbf811baea22f2167890671ed789c54", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/herlenashavi/p4factory/ef05d0a235617724a6fa23c861d2c003cdda7a11/modules/p4ns_common/module/src/p4ns_db.c", "visit_date": "2021-01-18T19:39:36.029269" }
stackv2
/* Copyright 2013-present Barefoot Networks, 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 <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <arpa/inet.h> #include <assert.h> #include <p4ns_common/p4ns_db.h> #define DB_CONNECT_TIMEOUT_SECS 1 typedef struct p4ns_port_s { uint16_t port_num; char iface[64]; } p4ns_port_t; typedef struct p4ns_config_s { char datapath_name[64]; uint64_t dpid; p4ns_tcp_over_ip_t listener; } p4ns_config_t; p4ns_db_cxt_t p4ns_db_connect(char *ipv4, uint16_t port) { struct timeval timeout = { DB_CONNECT_TIMEOUT_SECS, 0 }; redisContext *c = redisConnectWithTimeout(ipv4, port, timeout); if (c == NULL || c->err) { return NULL; } return c; } void p4ns_db_free(p4ns_db_cxt_t c){ redisFree(c); } int p4ns_db_has_datapath(p4ns_db_cxt_t c, const char *name) { redisReply *reply; reply = redisCommand(c, "EXISTS %s", name); int ret = (reply->integer == 1); freeReplyObject(reply); return ret; } int p4ns_db_add_datapath(p4ns_db_cxt_t c, const char *name, uint64_t dpid) { if(p4ns_db_has_datapath(c, name)) { return P4NSDB_ERROR_DATAPATH_EXISTS; } redisReply *reply; p4ns_config_t p4ns_config; memset(&p4ns_config, 0, sizeof(p4ns_config_t)); strncpy(p4ns_config.datapath_name, name, 64); p4ns_config.dpid = dpid; reply = redisCommand(c, "SET %s %b", name, (char *) &p4ns_config, sizeof(p4ns_config_t)); freeReplyObject(reply); return 0; } int p4ns_db_set_listener(p4ns_db_cxt_t c, const char *name, p4ns_tcp_over_ip_t *listener) { redisReply *reply1, *reply2; reply1 = redisCommand(c, "GET %s", name); if(!reply1->str) { freeReplyObject(reply1); return P4NSDB_ERROR_INVALID_DATAPATH; } p4ns_config_t *p4ns_config = (p4ns_config_t *) reply1->str; memcpy(&p4ns_config->listener, listener, sizeof(p4ns_tcp_over_ip_t)); reply2 = redisCommand(c, "SET %s %b", name, (char *) p4ns_config, sizeof(p4ns_config_t)); freeReplyObject(reply1); freeReplyObject(reply2); return 0; } int p4ns_db_get_listener(p4ns_db_cxt_t c, const char *name, p4ns_tcp_over_ip_t *listener) { redisReply *reply; reply = redisCommand(c, "GET %s", name); if(!reply->str) { freeReplyObject(reply); return P4NSDB_ERROR_INVALID_DATAPATH; } p4ns_config_t *p4ns_config = (p4ns_config_t *) reply->str; memcpy(listener, &p4ns_config->listener, sizeof(p4ns_tcp_over_ip_t)); freeReplyObject(reply); return 0; } static inline void get_ports_key(char *dest, const char *name) { sprintf(dest, ".%s.ports", name); } static inline void get_port_nums_key(char *dest, const char *name) { sprintf(dest, ".%s.port_nums", name); } static int has_port(p4ns_db_cxt_t c, const char *ports_key, const char *iface) { redisReply *reply; reply = redisCommand(c, "HEXISTS %s %s", ports_key, iface); int ret = (reply->integer == 1); freeReplyObject(reply); return ret; } static int has_port_num(p4ns_db_cxt_t c, const char *port_nums_key, uint16_t port_num) { redisReply *reply; reply = redisCommand(c, "SISMEMBER %s %d", port_nums_key, port_num); int ret = (reply->integer == 1); freeReplyObject(reply); return ret; } int p4ns_db_has_port(p4ns_db_cxt_t c, const char *name, const char *iface) { char ports_key[128]; get_ports_key(ports_key, name); if(!p4ns_db_has_datapath(c, name)) { /* datapath does not exist */ return 0; } return has_port(c, ports_key, iface); } int p4ns_db_has_port_num(p4ns_db_cxt_t c, const char *name, uint16_t port_num) { char port_nums_key[128]; get_port_nums_key(port_nums_key, name); if(!p4ns_db_has_datapath(c, name)) { /* datapath does not exist */ return 0; } return has_port_num(c, port_nums_key, port_num); } int p4ns_db_add_port(p4ns_db_cxt_t c, const char *name, const char *iface, uint16_t port_num) { redisReply *reply; char ports_key[128]; char port_nums_key[128]; get_ports_key(ports_key, name); get_port_nums_key(port_nums_key, name); if(!p4ns_db_has_datapath(c, name)) { /* datapath does not exist */ return P4NSDB_ERROR_INVALID_DATAPATH; } if(has_port(c, ports_key, iface)) { /* port exists */ return P4NSDB_ERROR_PORT_EXISTS; } if(has_port_num(c, port_nums_key, port_num)) { /* port num taken */ return P4NSDB_ERROR_PORT_NUM_TAKEN; } p4ns_port_t p4ns_port; memset(&p4ns_port, 0, sizeof(p4ns_port_t)); p4ns_port.port_num = port_num; strncpy(p4ns_port.iface, iface, 64); reply = redisCommand(c, "HSET %s %s %b", ports_key, iface, &p4ns_port, sizeof(p4ns_port_t)); assert(reply->integer == 1); freeReplyObject(reply); reply = redisCommand(c, "SADD %s %d", port_nums_key, port_num); assert(reply->integer == 1); freeReplyObject(reply); return 0; } int p4ns_db_del_port(p4ns_db_cxt_t c, const char *name, const char *iface) { redisReply *reply; char ports_key[128]; char port_nums_key[128]; get_ports_key(ports_key, name); get_port_nums_key(port_nums_key, name); if(!p4ns_db_has_datapath(c, name)) { /* datapath does not exist */ return P4NSDB_ERROR_INVALID_DATAPATH; } if(!has_port(c, ports_key, iface)) { /* port invalid */ return P4NSDB_ERROR_INVALID_PORT; } reply = redisCommand(c, "HGET %s %s", ports_key, iface); p4ns_port_t *p4ns_port = (p4ns_port_t *) reply->str; uint16_t port_num = p4ns_port->port_num; freeReplyObject(reply); reply = redisCommand(c, "HDEL %s %s", ports_key, iface); assert(reply->integer == 1); freeReplyObject(reply); reply = redisCommand(c, "SREM %s %d", port_nums_key, port_num); assert(reply->integer == 1); freeReplyObject(reply); return 0; } int p4ns_db_del_datapath(p4ns_db_cxt_t c, const char *name) { redisReply *reply; int success; char ports_key[128]; char port_nums_key[128]; get_ports_key(ports_key, name); get_port_nums_key(port_nums_key, name); reply = redisCommand(c, "DEL %s", name); success = (reply->integer == 1); freeReplyObject(reply); if (!success) return P4NSDB_ERROR_INVALID_DATAPATH; reply = redisCommand(c, "DEL %s", ports_key); freeReplyObject(reply); reply = redisCommand(c, "DEL %s", port_nums_key); freeReplyObject(reply); return 0; } int p4ns_db_get_first_port_num(p4ns_db_cxt_t c, const char *name, uint16_t *port_num) { redisReply *reply; if(!p4ns_db_has_datapath(c, name)) { /* datapath does not exist */ return P4NSDB_ERROR_INVALID_DATAPATH; } char port_nums_key[128]; get_port_nums_key(port_nums_key, name); *port_num = 0; int found = 1; while(found) { (*port_num)++; reply = redisCommand(c, "SISMEMBER %s %d", port_nums_key, *port_num); found = reply->integer; freeReplyObject(reply); } return 0; } int p4ns_db_flush(p4ns_db_cxt_t c) { redisReply *reply; reply = redisCommand(c, "FLUSHDB"); freeReplyObject(reply); return 0; }
2.34375
2