added
stringdate 2024-11-18 17:54:19
2024-11-19 03:39:31
| created
timestamp[s]date 1970-01-01 00:04:39
2023-09-06 04:41:57
| id
stringlengths 40
40
| metadata
dict | source
stringclasses 1
value | text
stringlengths 13
8.04M
| score
float64 2
4.78
| int_score
int64 2
5
|
---|---|---|---|---|---|---|---|
2024-11-18T22:37:04.082152+00:00 | 2023-02-19T08:29:34 | f2842a40b7d33239399990de6707d2aa3eca8c3f | {
"blob_id": "f2842a40b7d33239399990de6707d2aa3eca8c3f",
"branch_name": "refs/heads/main",
"committer_date": "2023-02-19T08:29:34",
"content_id": "6b47ca0cdf596ab62a40bcf5fb5741fa73c788e1",
"detected_licenses": [
"MIT"
],
"directory_id": "87f9d23b64f0ed9585db8a728c0585ad82a3b9f2",
"extension": "c",
"filename": "dec2bin.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 603523680,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1513,
"license": "MIT",
"license_type": "permissive",
"path": "/dec2bin.c",
"provenance": "stackv2-0107.json.gz:90775",
"repo_name": "Schrausser/ConsoleApp_String",
"revision_date": "2023-02-19T08:29:34",
"revision_id": "d1eadb490a2240a6311a08877cfdf2bd50e4bbc7",
"snapshot_id": "60a1abbd5bf9e22acba03a43e691beddc212eb5c",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Schrausser/ConsoleApp_String/d1eadb490a2240a6311a08877cfdf2bd50e4bbc7/dec2bin.c",
"visit_date": "2023-04-12T10:32:19.218027"
} | stackv2 | //----------------------------------------------------------------------------------------| DEC2BIN von Dietmar Schrausser 2009
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <conio.h>
#include <math.h>
void _profil()
{
int lauf;
printf("\n");
printf("DEC2BIN [d]\n");
for(lauf=1;lauf<=17;lauf++)cprintf("\xC4"); printf("\n");
printf("[d] ..Dezimalzahl\n");
for(lauf=1;lauf<=17;lauf++)cprintf("\xC4"); printf("\n");
printf("DEC2BIN von Dietmar Schrausser\n");
printf("compiliert %s @ %s\n", __DATE__, __TIME__);
exit(1);
}
int main(int argc, char *argv[])
{
int iLauf,index=1, lng;
long int zahl_dec;
char zahl_bin[200], zahl_bin_1[200], tmp[1];
if(argc == 1) _profil();
lng=strlen(argv[1]);
//if(lng > 10) {printf("\nDezimalzahl > 1.00E+10 .0\n"); _profil();}
zahl_dec = atoi(argv[1]);
strcpy(zahl_bin," "); strcpy(zahl_bin_1," ");
for(iLauf = 1; iLauf <= (sizeof( zahl_dec ) * 8); iLauf++)
{
zahl_dec < 0 ? strcat(zahl_bin, "1") : strcat(zahl_bin, "0") ;
zahl_dec <<= 1; // left shift
}
//printf ("\n%s binaer = %s\n",argv[1], zahl_bin);
lng=strlen(zahl_bin); while (zahl_bin[index]!='1')index++;
for(iLauf = index; iLauf <= lng; iLauf++) {sprintf(tmp,"%c", zahl_bin[iLauf]); strcat(zahl_bin_1,tmp);}
printf ("\n%s binaer = %s\n",argv[1], zahl_bin_1);
//printf ("%s oktal = %o\n",argv[1], atoi(argv[1]));
//printf ("%s hexadezimal = %X\n",argv[1], atoi(argv[1]));
return 0;
} | 2.65625 | 3 |
2024-11-18T22:37:08.914322+00:00 | 2020-12-23T01:20:27 | a73a40b5b6850ea46f8e68148c1a3dc0b08bd050 | {
"blob_id": "a73a40b5b6850ea46f8e68148c1a3dc0b08bd050",
"branch_name": "refs/heads/master",
"committer_date": "2020-12-23T01:20:27",
"content_id": "205346db3862693f655f580ec11b2e8ef0bdbc54",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "8f7299378e548ff164bbcfa240275ee924f2eeff",
"extension": "h",
"filename": "segment.h",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 70995929,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 10859,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/include/hl7parser/segment.h",
"provenance": "stackv2-0107.json.gz:91161",
"repo_name": "once-ler/hl7parser-json",
"revision_date": "2020-12-23T01:20:27",
"revision_id": "73036888db8b2c7a272490a9b69ac39aa29af556",
"snapshot_id": "101f7e54e86f994746cedc32544dabddf8b71c68",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/once-ler/hl7parser-json/73036888db8b2c7a272490a9b69ac39aa29af556/include/hl7parser/segment.h",
"visit_date": "2021-01-11T03:36:23.924965"
} | stackv2 | #ifndef HL7PARSER_SEGMENT_H
#define HL7PARSER_SEGMENT_H
/**
* \file segment.h
*
* HL7 segment data types and functions.
*
* \internal
* Copyright (c) 2003-2013 Juan Jose Comellas <juanjo@comellas.org>
*/
/* ------------------------------------------------------------------------
Headers
------------------------------------------------------------------------ */
#include <hl7parser/config.h>
#include <hl7parser/defs.h>
#include <hl7parser/element.h>
#include <hl7parser/export.h>
#include <hl7parser/node.h>
#include <stdarg.h>
BEGIN_C_DECL()
/* ------------------------------------------------------------------------
Typedefs
------------------------------------------------------------------------ */
/**
* \struct HL7_Segment
* The structure of the HL7 segment tree is the following. Vertical
* arrows indicate a sibling relationship (i.e. elements of the same type).
* Horizontal arrows indicate a parent-child relationship (i.e. subelements).
*
* \code
* 0/Segment ID
* |
* 1/Field 0 -> Repetition 0 -> Component 0 -> Subcomponent 0
* | | | |
* | | | Subcomponent n
* | | |
* | | Component n -> Subcomponent 0
* | | |
* | | Subcomponent n
* | |
* | Repetition n -> Component 0 -> Subcomponent 0
* | | |
* | | Subcomponent n
* | |
* | Component n -> Subcomponent 0
* | |
* | Subcomponent n
* |
* n+1/Field n -> Repetition 0 -> Component 0 -> Subcomponent 0
* | | |
* | | Subcomponent n
* | |
* | Component n -> Subcomponent 0
* | |
* | Subcomponent n
* |
* Repetition n -> Component 0 -> Subcomponent 0
* | |
* | Subcomponent n
* |
* Component n -> Subcomponent 0
* |
* Subcomponent n
* \endcode
*
* As we see, when dealing with fields, we have to start the search in the
* second field (position 1) so that the indexes passed by the caller
* correspond to the actual positions of the elements.
*/
typedef struct HL7_Segment_Struct
{
/**
* Node of the segment in the message.
*/
HL7_Node *message_node;
/**
* First node of the segment tree. This node contains the segment ID.
*/
HL7_Node *head;
/**
* Memory allocator for the nodes of the segment tree.
*/
HL7_Allocator *allocator;
} HL7_Segment;
/* ------------------------------------------------------------------------
Function prototypes
------------------------------------------------------------------------ */
HL7_EXPORT int hl7_segment_create( HL7_Segment *segment, const char *segment_id,
HL7_Allocator *allocator );
HL7_EXPORT int hl7_segment_create_copy( HL7_Segment *dest, HL7_Segment *src,
const bool copy_elements );
HL7_EXPORT void hl7_segment_destroy( HL7_Segment *segment );
HL7_EXPORT void hl7_segment_id( HL7_Segment *segment, char *buffer, size_t length );
HL7_EXPORT HL7_Element *hl7_segment_field( HL7_Segment *segment,
const size_t field_pos );
HL7_EXPORT int hl7_segment_set_field( HL7_Segment *segment,
const size_t field_pos,
HL7_Element *element );
HL7_EXPORT HL7_Element *hl7_segment_repetition( HL7_Segment *segment,
const size_t field_pos,
const size_t repetition_pos );
HL7_EXPORT int hl7_segment_set_repetition( HL7_Segment *segment,
const size_t field_pos,
const size_t repetition_pos,
HL7_Element *element );
HL7_EXPORT HL7_Element *hl7_segment_component( HL7_Segment *segment,
const size_t field_pos,
const size_t component_pos );
HL7_EXPORT int hl7_segment_set_component( HL7_Segment *segment,
const size_t field_pos,
const size_t component_pos,
HL7_Element *element );
HL7_EXPORT HL7_Element *hl7_segment_component_rep( HL7_Segment *segment,
const size_t field_pos,
const size_t repetition_pos,
const size_t component_pos );
HL7_EXPORT int hl7_segment_set_component_rep( HL7_Segment *segment,
const size_t field_pos,
const size_t repetition_pos,
const size_t component_pos,
HL7_Element *element );
HL7_EXPORT HL7_Element *hl7_segment_subcomponent( HL7_Segment *segment,
const size_t field_pos,
const size_t component_pos,
const size_t subcomponent_pos );
HL7_EXPORT int hl7_segment_set_subcomponent( HL7_Segment *segment,
const size_t field_pos,
const size_t component_pos,
const size_t subcomponent_pos,
HL7_Element *element );
HL7_EXPORT HL7_Element *hl7_segment_subcomponent_rep( HL7_Segment *segment,
const size_t field_pos,
const size_t repetition_pos,
const size_t component_pos,
const size_t subcomponent_pos );
HL7_EXPORT int hl7_segment_set_subcomponent_rep( HL7_Segment *segment,
const size_t field_pos,
const size_t repetition_pos,
const size_t component_pos,
const size_t subcomponent_pos,
HL7_Element *element );
/**
* Returns the HL7 element of \a element_type from the \a segment in the position
* indicated by the variable arguments.
* \bug Should we return a null pointer or hl7_element_null()?
*/
HL7_EXPORT HL7_Element *hl7_segment_element( HL7_Segment *segment,
const HL7_Element_Type element_type, ... );
/**
* Returns the HL7 element of \a element_type from the \a segment in the position
* indicated by the variable argument list \a ap.
* \bug Should we return a null pointer or hl7_element_null()?
*/
HL7_EXPORT HL7_Element *hl7_segment_element_va( HL7_Segment *segment,
const HL7_Element_Type element_type,
va_list ap );
HL7_EXPORT int hl7_segment_set_element( HL7_Segment *segment, HL7_Element *source,
const HL7_Element_Type element_type, ... );
HL7_EXPORT int hl7_segment_set_element_int( HL7_Segment *segment, int value,
const HL7_Element_Type element_type, ... );
HL7_EXPORT int hl7_segment_set_element_date( HL7_Segment *segment, time_t value,
const bool include_time, const bool include_secs,
const HL7_Element_Type element_type, ... );
HL7_EXPORT int hl7_segment_set_element_va( HL7_Segment *segment, HL7_Element *source,
const HL7_Element_Type element_type,
va_list ap );
/**
* Returns the \c HL7_Node containing an element of \a element_type from the
* \a segment in the position indicated by the variable arguments.
* \return The \c HL7_Node in the indicate position if it exists; 0 if not.
*/
HL7_EXPORT HL7_Node *hl7_segment_node( HL7_Segment *segment,
const HL7_Element_Type element_type, ... );
/**
* Returns the \c HL7_Node containing an element of \a element_type from the
* \a segment in the position indicated by the variable argument list \a ap.
* \return The \c HL7_Node in the indicate position if it exists; 0 if not.
*
* \warning
*
* HL7 allows trailing optional items that have no value to be omitted.
* This causes an ambiguity because one same item can be interpreted in
* several ways when it is the first and only item present.
*
* e.g.: For HL7 the item in the third field (504599) is the same for
* these two examples:
*
* 1) AUT||504599^^||||0000190447|^||
* 2) AUT||504599||||0000190447|^||
*
* But for this parser it has two different representations:
*
* 1) First component of the third field
* 2) Third field
*
* \bug Resolve the ambiguity in the HL7 syntax. Ensure that we get the correct value
* in all the cases. This means that for the second example we should always get
* the "504599" value both by requesting the AUT.2 and the AUT.2.1 elements.
*/
HL7_EXPORT HL7_Node *hl7_segment_node_va( HL7_Segment *segment,
const HL7_Element_Type element_type, va_list ap );
END_C_DECL()
#endif /* HL7PARSER_SEGMENT_H */
| 2.1875 | 2 |
2024-11-18T22:37:09.077235+00:00 | 2023-08-24T08:38:57 | 4de418103c10378663cf2e613f281b5f869cf22f | {
"blob_id": "4de418103c10378663cf2e613f281b5f869cf22f",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-24T08:49:52",
"content_id": "f09b009254a2c7c4c3c8b45304ef65da22456d33",
"detected_licenses": [
"MIT"
],
"directory_id": "30c2631ed046d7662476b94fb7f5286c47377f60",
"extension": "c",
"filename": "plecs.c",
"fork_events_count": 456,
"gha_created_at": "2018-08-26T05:53:05",
"gha_event_created_at": "2023-09-05T16:01:58",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 146155284,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 58975,
"license": "MIT",
"license_type": "permissive",
"path": "/src/addons/plecs.c",
"provenance": "stackv2-0107.json.gz:91289",
"repo_name": "SanderMertens/flecs",
"revision_date": "2023-08-24T08:38:57",
"revision_id": "41fb856c4e1162f44b59d7881ef508d64d56bf10",
"snapshot_id": "a840093340f0d1eb2bd30ec1585296f81f2aab39",
"src_encoding": "UTF-8",
"star_events_count": 4731,
"url": "https://raw.githubusercontent.com/SanderMertens/flecs/41fb856c4e1162f44b59d7881ef508d64d56bf10/src/addons/plecs.c",
"visit_date": "2023-08-24T16:21:41.790084"
} | stackv2 | /**
* @file addons/plecs.c
* @brief Plecs addon.
*/
#include "flecs.h"
#ifdef FLECS_PLECS
ECS_COMPONENT_DECLARE(EcsScript);
#include "../private_api.h"
#include <ctype.h>
#define TOK_NEWLINE '\n'
#define TOK_USING "using"
#define TOK_MODULE "module"
#define TOK_WITH "with"
#define TOK_CONST "const"
#define TOK_PROP "prop"
#define TOK_ASSEMBLY "assembly"
#define STACK_MAX_SIZE (64)
typedef struct {
ecs_value_t value;
bool owned;
} plecs_with_value_t;
typedef struct {
const char *name;
const char *code;
ecs_entity_t last_predicate;
ecs_entity_t last_subject;
ecs_entity_t last_object;
ecs_id_t last_assign_id;
ecs_entity_t assign_to;
ecs_entity_t scope[STACK_MAX_SIZE];
ecs_entity_t default_scope_type[STACK_MAX_SIZE];
ecs_entity_t with[STACK_MAX_SIZE];
ecs_entity_t using[STACK_MAX_SIZE];
int32_t with_frames[STACK_MAX_SIZE];
plecs_with_value_t with_value_frames[STACK_MAX_SIZE];
int32_t using_frames[STACK_MAX_SIZE];
int32_t sp;
int32_t with_frame;
int32_t using_frame;
ecs_entity_t global_with;
ecs_entity_t assembly;
const char *assembly_start, *assembly_stop;
char *annot[STACK_MAX_SIZE];
int32_t annot_count;
ecs_vars_t vars;
char var_name[256];
ecs_entity_t var_type;
bool with_stmt;
bool scope_assign_stmt;
bool assign_stmt;
bool assembly_stmt;
bool assembly_instance;
bool isa_stmt;
bool decl_stmt;
bool decl_type;
bool var_stmt;
bool var_is_prop;
bool is_module;
int32_t errors;
} plecs_state_t;
static
int flecs_plecs_parse(
ecs_world_t *world,
const char *name,
const char *expr,
ecs_vars_t *vars,
ecs_entity_t script,
ecs_entity_t instance);
static void flecs_dtor_script(EcsScript *ptr) {
ecs_os_free(ptr->script);
ecs_vec_fini_t(NULL, &ptr->using_, ecs_entity_t);
int i, count = ptr->prop_defaults.count;
ecs_value_t *values = ptr->prop_defaults.array;
for (i = 0; i < count; i ++) {
ecs_value_free(ptr->world, values[i].type, values[i].ptr);
}
ecs_vec_fini_t(NULL, &ptr->prop_defaults, ecs_value_t);
}
static
ECS_MOVE(EcsScript, dst, src, {
flecs_dtor_script(dst);
dst->using_ = src->using_;
dst->prop_defaults = src->prop_defaults;
dst->script = src->script;
dst->world = src->world;
ecs_os_zeromem(&src->using_);
ecs_os_zeromem(&src->prop_defaults);
src->script = NULL;
src->world = NULL;
})
static
ECS_DTOR(EcsScript, ptr, {
flecs_dtor_script(ptr);
})
/* Assembly ctor to initialize with default property values */
static
void flecs_assembly_ctor(
void *ptr,
int32_t count,
const ecs_type_info_t *ti)
{
ecs_world_t *world = ti->hooks.ctx;
ecs_entity_t assembly = ti->component;
const EcsStruct *st = ecs_get(world, assembly, EcsStruct);
if (!st) {
ecs_err("assembly '%s' is not a struct, cannot construct", ti->name);
return;
}
const EcsScript *script = ecs_get(world, assembly, EcsScript);
if (!script) {
ecs_err("assembly '%s' is not a script, cannot construct", ti->name);
return;
}
if (st->members.count != script->prop_defaults.count) {
ecs_err("number of props (%d) of assembly '%s' does not match members"
" (%d), cannot construct", script->prop_defaults.count,
ti->name, st->members.count);
return;
}
const ecs_member_t *members = st->members.array;
int32_t i, m, member_count = st->members.count;
ecs_value_t *values = script->prop_defaults.array;
for (m = 0; m < member_count; m ++) {
const ecs_member_t *member = &members[m];
ecs_value_t *value = &values[m];
const ecs_type_info_t *mti = ecs_get_type_info(world, member->type);
if (!mti) {
ecs_err("failed to get type info for prop '%s' of assembly '%s'",
member->name, ti->name);
return;
}
for (i = 0; i < count; i ++) {
void *el = ECS_ELEM(ptr, ti->size, i);
ecs_value_copy_w_type_info(world, mti,
ECS_OFFSET(el, member->offset), value->ptr);
}
}
}
/* Assembly on_set handler to update contents for new property values */
static
void flecs_assembly_on_set(
ecs_iter_t *it)
{
if (it->table->flags & EcsTableIsPrefab) {
/* Don't instantiate assemblies for prefabs */
return;
}
ecs_world_t *world = it->world;
ecs_entity_t assembly = ecs_field_id(it, 1);
const char *name = ecs_get_name(world, assembly);
ecs_record_t *r = ecs_record_find(world, assembly);
const EcsComponent *ct = ecs_record_get(world, r, EcsComponent);
ecs_get(world, assembly, EcsComponent);
if (!ct) {
ecs_err("assembly '%s' is not a component", name);
return;
}
const EcsStruct *st = ecs_record_get(world, r, EcsStruct);
if (!st) {
ecs_err("assembly '%s' is not a struct", name);
return;
}
const EcsScript *script = ecs_record_get(world, r, EcsScript);
if (!script) {
ecs_err("assembly '%s' is missing a script", name);
return;
}
void *data = ecs_field_w_size(it, flecs_ito(size_t, ct->size), 1);
int32_t i, m;
for (i = 0; i < it->count; i ++) {
/* Create variables to hold assembly properties */
ecs_vars_t vars = {0};
ecs_vars_init(world, &vars);
/* Populate properties from assembly members */
const ecs_member_t *members = st->members.array;
for (m = 0; m < st->members.count; m ++) {
const ecs_member_t *member = &members[m];
ecs_value_t v = {0}; /* Prevent allocating value */
ecs_expr_var_t *var = ecs_vars_declare_w_value(
&vars, member->name, &v);
if (var == NULL) {
ecs_err("could not create prop '%s' for assembly '%s'",
member->name, name);
break;
}
/* Assign assembly property from assembly instance */
var->value.type = member->type;
var->value.ptr = ECS_OFFSET(data, member->offset);
var->owned = false;
}
/* Update script with new code/properties */
ecs_entity_t instance = it->entities[i];
ecs_script_update(world, assembly, instance, script->script, &vars);
ecs_vars_fini(&vars);
if (ecs_record_has_id(world, r, EcsFlatten)) {
ecs_flatten(it->real_world, ecs_childof(instance), NULL);
}
data = ECS_OFFSET(data, ct->size);
}
}
/* Delete contents of assembly instance */
static
void flecs_assembly_on_remove(
ecs_iter_t *it)
{
int32_t i;
for (i = 0; i < it->count; i ++) {
ecs_entity_t instance = it->entities[i];
ecs_script_clear(it->world, 0, instance);
}
}
/* Set default property values on assembly Script component */
static
int flecs_assembly_init_defaults(
ecs_world_t *world,
const char *name,
const char *expr,
const char *ptr,
ecs_entity_t assembly,
EcsScript *script,
plecs_state_t *state)
{
const EcsStruct *st = ecs_get(world, assembly, EcsStruct);
int32_t i, count = st->members.count;
const ecs_member_t *members = st->members.array;
ecs_vec_init_t(NULL, &script->prop_defaults, ecs_value_t, count);
for (i = 0; i < count; i ++) {
const ecs_member_t *member = &members[i];
ecs_expr_var_t *var = ecs_vars_lookup(&state->vars, member->name);
if (!var) {
char *assembly_name = ecs_get_fullpath(world, assembly);
ecs_parser_error(name, expr, ptr - expr,
"missing property '%s' for assembly '%s'",
member->name, assembly_name);
ecs_os_free(assembly_name);
return -1;
}
if (member->type != var->value.type) {
char *assembly_name = ecs_get_fullpath(world, assembly);
ecs_parser_error(name, expr, ptr - expr,
"property '%s' for assembly '%s' has mismatching type",
member->name, assembly_name);
ecs_os_free(assembly_name);
return -1;
}
ecs_value_t *pv = ecs_vec_append_t(NULL,
&script->prop_defaults, ecs_value_t);
pv->type = member->type;
pv->ptr = var->value.ptr;
var->owned = false; /* Transfer ownership */
}
return 0;
}
/* Create new assembly */
static
int flecs_assembly_create(
ecs_world_t *world,
const char *name,
const char *expr,
const char *ptr,
ecs_entity_t assembly,
char *script_code,
plecs_state_t *state)
{
const EcsStruct *st = ecs_get(world, assembly, EcsStruct);
if (!st || !st->members.count) {
char *assembly_name = ecs_get_fullpath(world, assembly);
ecs_parser_error(name, expr, ptr - expr,
"assembly '%s' has no properties", assembly_name);
ecs_os_free(assembly_name);
ecs_os_free(script_code);
return -1;
}
ecs_add_id(world, assembly, EcsAlwaysOverride);
EcsScript *script = ecs_get_mut(world, assembly, EcsScript);
flecs_dtor_script(script);
script->world = world;
script->script = script_code;
ecs_vec_reset_t(NULL, &script->using_, ecs_entity_t);
ecs_entity_t scope = ecs_get_scope(world);
if (scope && (scope = ecs_get_target(world, scope, EcsChildOf, 0))) {
ecs_vec_append_t(NULL, &script->using_, ecs_entity_t)[0] = scope;
}
int i, count = state->using_frame;
for (i = 0; i < count; i ++) {
ecs_vec_append_t(NULL, &script->using_, ecs_entity_t)[0] =
state->using[i];
}
if (flecs_assembly_init_defaults(
world, name, expr, ptr, assembly, script, state))
{
return -1;
}
ecs_modified(world, assembly, EcsScript);
ecs_set_hooks_id(world, assembly, &(ecs_type_hooks_t) {
.ctor = flecs_assembly_ctor,
.on_set = flecs_assembly_on_set,
.on_remove = flecs_assembly_on_remove,
.ctx = world
});
return 0;
}
/* Parser */
static
bool plecs_is_newline_comment(
const char *ptr)
{
if (ptr[0] == '/' && ptr[1] == '/') {
return true;
}
return false;
}
static
const char* plecs_parse_fluff(
const char *ptr)
{
do {
/* Skip whitespaces before checking for a comment */
ptr = ecs_parse_ws(ptr);
/* Newline comment, skip until newline character */
if (plecs_is_newline_comment(ptr)) {
ptr += 2;
while (ptr[0] && ptr[0] != TOK_NEWLINE) {
ptr ++;
}
}
/* If a newline character is found, skip it */
if (ptr[0] == TOK_NEWLINE) {
ptr ++;
}
} while (isspace(ptr[0]) || plecs_is_newline_comment(ptr));
return ptr;
}
static
ecs_entity_t plecs_lookup(
const ecs_world_t *world,
const char *path,
plecs_state_t *state,
ecs_entity_t rel,
bool is_subject)
{
ecs_entity_t e = 0;
if (!is_subject) {
ecs_entity_t oneof = 0;
if (rel) {
if (ecs_has_id(world, rel, EcsOneOf)) {
oneof = rel;
} else {
oneof = ecs_get_target(world, rel, EcsOneOf, 0);
}
if (oneof) {
return ecs_lookup_path_w_sep(
world, oneof, path, NULL, NULL, false);
}
}
int using_scope = state->using_frame - 1;
for (; using_scope >= 0; using_scope--) {
e = ecs_lookup_path_w_sep(
world, state->using[using_scope], path, NULL, NULL, false);
if (e) {
break;
}
}
}
if (!e) {
e = ecs_lookup_path_w_sep(world, 0, path, NULL, NULL, !is_subject);
}
return e;
}
/* Lookup action used for deserializing entity refs in component values */
static
ecs_entity_t plecs_lookup_action(
const ecs_world_t *world,
const char *path,
void *ctx)
{
return plecs_lookup(world, path, ctx, 0, false);
}
static
ecs_entity_t plecs_ensure_entity(
ecs_world_t *world,
plecs_state_t *state,
const char *path,
ecs_entity_t rel,
bool is_subject)
{
if (!path) {
return 0;
}
ecs_entity_t e = 0;
bool is_anonymous = !ecs_os_strcmp(path, "_");
bool is_new = false;
if (is_anonymous) {
path = NULL;
e = ecs_new_id(world);
is_new = true;
}
if (!e) {
e = plecs_lookup(world, path, state, rel, is_subject);
}
if (!e) {
is_new = true;
if (rel && flecs_get_oneof(world, rel)) {
/* If relationship has oneof and entity was not found, don't proceed
* with creating an entity as this can cause asserts later on */
char *relstr = ecs_get_fullpath(world, rel);
ecs_parser_error(state->name, 0, 0,
"invalid identifier '%s' for relationship '%s'", path, relstr);
ecs_os_free(relstr);
return 0;
}
ecs_entity_t prev_scope = 0;
ecs_entity_t prev_with = 0;
if (!is_subject) {
/* Don't apply scope/with for non-subject entities */
prev_scope = ecs_set_scope(world, 0);
prev_with = ecs_set_with(world, 0);
}
e = ecs_add_path(world, e, 0, path);
ecs_assert(e != 0, ECS_INTERNAL_ERROR, NULL);
if (prev_scope) {
ecs_set_scope(world, prev_scope);
}
if (prev_with) {
ecs_set_with(world, prev_with);
}
} else {
/* If entity exists, make sure it gets the right scope and with */
if (is_subject) {
ecs_entity_t scope = ecs_get_scope(world);
if (scope) {
ecs_add_pair(world, e, EcsChildOf, scope);
}
ecs_entity_t with = ecs_get_with(world);
if (with) {
ecs_add_id(world, e, with);
}
}
}
if (is_new) {
if (state->assembly && !state->assembly_instance) {
ecs_add_id(world, e, EcsPrefab);
}
if (state->global_with) {
ecs_add_id(world, e, state->global_with);
}
}
return e;
}
static
bool plecs_pred_is_subj(
ecs_term_t *term,
plecs_state_t *state)
{
if (term->src.name != NULL) {
return false;
}
if (term->second.name != NULL) {
return false;
}
if (ecs_term_match_0(term)) {
return false;
}
if (state->with_stmt) {
return false;
}
if (state->assign_stmt) {
return false;
}
if (state->isa_stmt) {
return false;
}
if (state->decl_type) {
return false;
}
return true;
}
/* Set masks aren't useful in plecs, so translate them back to entity names */
static
const char* plecs_set_mask_to_name(
ecs_flags32_t flags)
{
flags &= EcsTraverseFlags;
if (flags == EcsSelf) {
return "self";
} else if (flags == EcsUp) {
return "up";
} else if (flags == EcsDown) {
return "down";
} else if (flags == EcsCascade || flags == (EcsUp|EcsCascade)) {
return "cascade";
} else if (flags == EcsParent) {
return "parent";
}
return NULL;
}
static
char* plecs_trim_annot(
char *annot)
{
annot = ECS_CONST_CAST(char*, ecs_parse_ws(annot));
int32_t len = ecs_os_strlen(annot) - 1;
while (isspace(annot[len]) && (len > 0)) {
annot[len] = '\0';
len --;
}
return annot;
}
static
void plecs_apply_annotations(
ecs_world_t *world,
ecs_entity_t subj,
plecs_state_t *state)
{
(void)world;
(void)subj;
(void)state;
#ifdef FLECS_DOC
int32_t i = 0, count = state->annot_count;
for (i = 0; i < count; i ++) {
char *annot = state->annot[i];
if (!ecs_os_strncmp(annot, "@brief ", 7)) {
annot = plecs_trim_annot(annot + 7);
ecs_doc_set_brief(world, subj, annot);
} else if (!ecs_os_strncmp(annot, "@link ", 6)) {
annot = plecs_trim_annot(annot + 6);
ecs_doc_set_link(world, subj, annot);
} else if (!ecs_os_strncmp(annot, "@name ", 6)) {
annot = plecs_trim_annot(annot + 6);
ecs_doc_set_name(world, subj, annot);
} else if (!ecs_os_strncmp(annot, "@color ", 7)) {
annot = plecs_trim_annot(annot + 7);
ecs_doc_set_color(world, subj, annot);
}
}
#else
ecs_warn("cannot apply annotations, doc addon is missing");
#endif
}
static
int plecs_create_term(
ecs_world_t *world,
ecs_term_t *term,
const char *name,
const char *expr,
int64_t column,
plecs_state_t *state)
{
state->last_subject = 0;
state->last_predicate = 0;
state->last_object = 0;
state->last_assign_id = 0;
const char *pred_name = term->first.name;
const char *subj_name = term->src.name;
const char *obj_name = term->second.name;
if (!subj_name) {
subj_name = plecs_set_mask_to_name(term->src.flags);
}
if (!obj_name) {
obj_name = plecs_set_mask_to_name(term->second.flags);
}
if (!ecs_term_id_is_set(&term->first)) {
ecs_parser_error(name, expr, column, "missing predicate in expression");
return -1;
}
if (state->assign_stmt && !ecs_term_match_this(term)) {
ecs_parser_error(name, expr, column,
"invalid statement in assign statement");
return -1;
}
bool pred_as_subj = plecs_pred_is_subj(term, state);
ecs_entity_t pred = plecs_ensure_entity(world, state, pred_name, 0, pred_as_subj);
ecs_entity_t subj = plecs_ensure_entity(world, state, subj_name, pred, true);
ecs_entity_t obj = 0;
if (ecs_term_id_is_set(&term->second)) {
obj = plecs_ensure_entity(world, state, obj_name, pred,
!state->assign_stmt && !state->with_stmt);
if (!obj) {
return -1;
}
}
if (state->assign_stmt || state->isa_stmt) {
subj = state->assign_to;
}
if (state->isa_stmt && obj) {
ecs_parser_error(name, expr, column,
"invalid object in inheritance statement");
return -1;
}
if (state->isa_stmt) {
pred = ecs_pair(EcsIsA, pred);
}
if (subj == EcsVariable) {
subj = pred;
}
if (subj) {
ecs_id_t id;
if (!obj) {
id = term->id_flags | pred;
} else {
id = term->id_flags | ecs_pair(pred, obj);
state->last_object = obj;
}
state->last_assign_id = id;
state->last_predicate = pred;
state->last_subject = subj;
ecs_add_id(world, subj, id);
pred_as_subj = false;
} else {
if (!obj) {
/* If no subject or object were provided, use predicate as subj
* unless the expression explictly excluded the subject */
if (pred_as_subj) {
state->last_subject = pred;
subj = pred;
} else {
state->last_predicate = pred;
pred_as_subj = false;
}
} else {
state->last_predicate = pred;
state->last_object = obj;
pred_as_subj = false;
}
}
/* If this is a with clause (the list of entities between 'with' and scope
* open), add subject to the array of with frames */
if (state->with_stmt) {
ecs_assert(pred != 0, ECS_INTERNAL_ERROR, NULL);
ecs_id_t id;
if (obj) {
id = ecs_pair(pred, obj);
} else {
id = pred;
}
state->with[state->with_frame ++] = id;
} else {
if (subj) {
int32_t i, frame_count = state->with_frames[state->sp];
for (i = 0; i < frame_count; i ++) {
ecs_id_t id = state->with[i];
plecs_with_value_t *v = &state->with_value_frames[i];
if (v->value.type) {
void *ptr = ecs_get_mut_id(world, subj, id);
ecs_value_copy(world, v->value.type, ptr, v->value.ptr);
ecs_modified_id(world, subj, id);
} else {
ecs_add_id(world, subj, id);
}
}
}
}
/* If an id was provided by itself, add default scope type to it */
ecs_entity_t default_scope_type = state->default_scope_type[state->sp];
if (pred_as_subj && default_scope_type) {
ecs_add_id(world, subj, default_scope_type);
}
/* If annotations preceded the statement, append */
if (!state->decl_type && state->annot_count) {
if (!subj) {
ecs_parser_error(name, expr, column,
"missing subject for annotations");
return -1;
}
plecs_apply_annotations(world, subj, state);
}
return 0;
}
static
const char* plecs_parse_inherit_stmt(
const char *name,
const char *expr,
const char *ptr,
plecs_state_t *state)
{
if (state->isa_stmt) {
ecs_parser_error(name, expr, ptr - expr,
"cannot nest inheritance");
return NULL;
}
if (!state->last_subject) {
ecs_parser_error(name, expr, ptr - expr,
"missing entity to assign inheritance to");
return NULL;
}
state->isa_stmt = true;
state->assign_to = state->last_subject;
return ptr;
}
static
const char* plecs_parse_assign_var_expr(
ecs_world_t *world,
const char *name,
const char *expr,
const char *ptr,
plecs_state_t *state,
ecs_expr_var_t *var)
{
ecs_value_t value = {0};
if (state->last_assign_id) {
value.type = state->last_assign_id;
value.ptr = ecs_value_new(world, state->last_assign_id);
if (!var && state->assembly_instance) {
var = ecs_vars_lookup(&state->vars, state->var_name);
}
}
ptr = ecs_parse_expr(world, ptr, &value,
&(ecs_parse_expr_desc_t){
.name = name,
.expr = expr,
.lookup_action = plecs_lookup_action,
.lookup_ctx = state,
.vars = &state->vars
});
if (!ptr) {
if (state->last_assign_id) {
ecs_value_free(world, value.type, value.ptr);
}
goto error;
}
if (var) {
bool ignore = state->var_is_prop && state->assembly_instance;
if (!ignore) {
if (var->value.ptr) {
ecs_value_free(world, var->value.type, var->value.ptr);
var->value.ptr = value.ptr;
var->value.type = value.type;
}
} else {
ecs_value_free(world, value.type, value.ptr);
}
} else {
var = ecs_vars_declare_w_value(
&state->vars, state->var_name, &value);
if (!var) {
goto error;
}
}
state->var_is_prop = false;
return ptr;
error:
return NULL;
}
static
const char* plecs_parse_assign_expr(
ecs_world_t *world,
const char *name,
const char *expr,
const char *ptr,
plecs_state_t *state,
ecs_expr_var_t *var)
{
(void)world;
if (state->var_stmt) {
return plecs_parse_assign_var_expr(world, name, expr, ptr, state, var);
}
if (!state->assign_stmt) {
ecs_parser_error(name, expr, ptr - expr,
"unexpected value outside of assignment statement");
return NULL;
}
ecs_id_t assign_id = state->last_assign_id;
if (!assign_id) {
ecs_parser_error(name, expr, ptr - expr,
"missing type for assignment statement");
return NULL;
}
ecs_entity_t assign_to = state->assign_to;
if (!assign_to) {
assign_to = state->last_subject;
}
if (!assign_to) {
ecs_parser_error(name, expr, ptr - expr,
"missing entity to assign to");
return NULL;
}
ecs_entity_t type = ecs_get_typeid(world, assign_id);
if (!type) {
char *id_str = ecs_id_str(world, assign_id);
ecs_parser_error(name, expr, ptr - expr,
"invalid assignment, '%s' is not a type", id_str);
ecs_os_free(id_str);
return NULL;
}
if (assign_to == EcsVariable) {
assign_to = type;
}
void *value_ptr = ecs_get_mut_id(world, assign_to, assign_id);
ptr = ecs_parse_expr(world, ptr, &(ecs_value_t){type, value_ptr},
&(ecs_parse_expr_desc_t){
.name = name,
.expr = expr,
.lookup_action = plecs_lookup_action,
.lookup_ctx = state,
.vars = &state->vars
});
if (!ptr) {
return NULL;
}
ecs_modified_id(world, assign_to, assign_id);
return ptr;
}
static
const char* plecs_parse_assign_stmt(
ecs_world_t *world,
const char *name,
const char *expr,
const char *ptr,
plecs_state_t *state)
{
(void)world;
state->isa_stmt = false;
/* Component scope (add components to entity) */
if (!state->assign_to) {
if (!state->last_subject) {
ecs_parser_error(name, expr, ptr - expr,
"missing entity to assign to");
return NULL;
}
state->assign_to = state->last_subject;
}
if (state->assign_stmt) {
ecs_parser_error(name, expr, ptr - expr,
"invalid assign statement in assign statement");
return NULL;
}
state->assign_stmt = true;
/* Assignment without a preceding component */
if (ptr[0] == '{') {
ecs_entity_t type = 0;
/* If we're in a scope & last_subject is a type, assign to scope */
if (ecs_get_scope(world) != 0) {
type = ecs_get_typeid(world, state->last_subject);
if (type != 0) {
type = state->last_subject;
}
}
/* If type hasn't been set yet, check if scope has default type */
if (!type && !state->scope_assign_stmt) {
type = state->default_scope_type[state->sp];
}
/* If no type has been found still, check if last with id is a type */
if (!type && !state->scope_assign_stmt) {
int32_t with_frame_count = state->with_frames[state->sp];
if (with_frame_count) {
type = state->with[with_frame_count - 1];
}
}
if (!type) {
ecs_parser_error(name, expr, ptr - expr,
"missing type for assignment");
return NULL;
}
state->last_assign_id = type;
}
return ptr;
}
static
const char* plecs_parse_assign_with_stmt(
ecs_world_t *world,
const char *name,
const char *expr,
const char *ptr,
plecs_state_t *state)
{
int32_t with_frame = state->with_frame - 1;
if (with_frame < 0) {
ecs_parser_error(name, expr, ptr - expr,
"missing type in with value");
return NULL;
}
ecs_id_t id = state->with[with_frame];
ecs_id_record_t *idr = flecs_id_record_get(world, id);
const ecs_type_info_t *ti = idr->type_info;
if (!ti) {
char *typename = ecs_id_str(world, id);
ecs_parser_error(name, expr, ptr - expr,
"id '%s' in with value is not a type", typename);
ecs_os_free(typename);
return NULL;
}
plecs_with_value_t *v = &state->with_value_frames[with_frame];
v->value.type = ti->component;
v->value.ptr = ecs_value_new(world, ti->component);
v->owned = true;
if (!v->value.ptr) {
char *typename = ecs_id_str(world, id);
ecs_parser_error(name, expr, ptr - expr,
"failed to create value for '%s'", typename);
ecs_os_free(typename);
return NULL;
}
ptr = ecs_parse_expr(world, ptr, &v->value,
&(ecs_parse_expr_desc_t){
.name = name,
.expr = expr,
.lookup_action = plecs_lookup_action,
.lookup_ctx = state,
.vars = &state->vars
});
if (!ptr) {
return NULL;
}
return ptr;
}
static
const char* plecs_parse_assign_with_var(
const char *name,
const char *expr,
const char *ptr,
plecs_state_t *state)
{
ecs_assert(ptr[0] == '$', ECS_INTERNAL_ERROR, NULL);
ecs_assert(state->with_stmt, ECS_INTERNAL_ERROR, NULL);
char var_name[ECS_MAX_TOKEN_SIZE];
const char *tmp = ptr;
ptr = ecs_parse_token(name, expr, ptr + 1, var_name, 0);
if (!ptr) {
ecs_parser_error(name, expr, tmp - expr,
"unresolved variable '%s'", var_name);
return NULL;
}
ecs_expr_var_t *var = ecs_vars_lookup(&state->vars, var_name);
if (!var) {
ecs_parser_error(name, expr, ptr - expr,
"unresolved variable '%s'", var_name);
return NULL;
}
int32_t with_frame = state->with_frame;
state->with[with_frame] = var->value.type;
state->with_value_frames[with_frame].value = var->value;
state->with_value_frames[with_frame].owned = false;
state->with_frame ++;
return ptr;
}
static
const char* plecs_parse_var_as_component(
ecs_world_t *world,
const char *name,
const char *expr,
const char *ptr,
plecs_state_t *state)
{
ecs_assert(ptr[0] == '$', ECS_INTERNAL_ERROR, NULL);
ecs_assert(!state->var_stmt, ECS_INTERNAL_ERROR, NULL);
char var_name[ECS_MAX_TOKEN_SIZE];
const char *tmp = ptr;
ptr = ecs_parse_token(name, expr, ptr + 1, var_name, 0);
if (!ptr) {
ecs_parser_error(name, expr, tmp - expr,
"unresolved variable '%s'", var_name);
return NULL;
}
ecs_expr_var_t *var = ecs_vars_lookup(&state->vars, var_name);
if (!var) {
ecs_parser_error(name, expr, ptr - expr,
"unresolved variable '%s'", var_name);
return NULL;
}
if (!state->assign_to) {
ecs_parser_error(name, expr, ptr - expr,
"missing lvalue for variable assignment '%s'", var_name);
return NULL;
}
/* Use type of variable as component */
ecs_entity_t type = var->value.type;
ecs_entity_t assign_to = state->assign_to;
if (!assign_to) {
assign_to = state->last_subject;
}
void *dst = ecs_get_mut_id(world, assign_to, type);
if (!dst) {
char *type_name = ecs_get_fullpath(world, type);
ecs_parser_error(name, expr, ptr - expr,
"failed to obtain component for type '%s' of variable '%s'",
type_name, var_name);
ecs_os_free(type_name);
return NULL;
}
if (ecs_value_copy(world, type, dst, var->value.ptr)) {
char *type_name = ecs_get_fullpath(world, type);
ecs_parser_error(name, expr, ptr - expr,
"failed to copy value for variable '%s' of type '%s'",
var_name, type_name);
ecs_os_free(type_name);
return NULL;
}
ecs_modified_id(world, assign_to, type);
return ptr;
}
static
void plecs_push_using(
ecs_entity_t scope,
plecs_state_t *state)
{
for (int i = 0; i < state->using_frame; i ++) {
if (state->using[i] == scope) {
return;
}
}
state->using[state->using_frame ++] = scope;
}
static
const char* plecs_parse_using_stmt(
ecs_world_t *world,
const char *name,
const char *expr,
const char *ptr,
plecs_state_t *state)
{
if (state->isa_stmt || state->assign_stmt) {
ecs_parser_error(name, expr, ptr - expr,
"invalid usage of using keyword");
return NULL;
}
char using_path[ECS_MAX_TOKEN_SIZE];
const char *tmp = ptr + 1;
ptr = ecs_parse_token(name, expr, ptr + 5, using_path, 0);
if (!ptr) {
ecs_parser_error(name, expr, tmp - expr,
"expected identifier for using statement");
return NULL;
}
ecs_size_t len = ecs_os_strlen(using_path);
if (!len) {
ecs_parser_error(name, expr, tmp - expr,
"missing identifier for using statement");
return NULL;
}
/* Lookahead as * is not matched by parse_token */
if (ptr[0] == '*') {
using_path[len] = '*';
using_path[len + 1] = '\0';
len ++;
ptr ++;
}
ecs_entity_t scope;
if (len > 2 && !ecs_os_strcmp(&using_path[len - 2], ".*")) {
using_path[len - 2] = '\0';
scope = ecs_lookup_fullpath(world, using_path);
if (!scope) {
ecs_parser_error(name, expr, ptr - expr,
"unresolved identifier '%s' in using statement", using_path);
return NULL;
}
/* Add each child of the scope to using stack */
ecs_iter_t it = ecs_term_iter(world, &(ecs_term_t){
.id = ecs_childof(scope) });
while (ecs_term_next(&it)) {
int32_t i, count = it.count;
for (i = 0; i < count; i ++) {
plecs_push_using(it.entities[i], state);
}
}
} else {
scope = plecs_ensure_entity(world, state, using_path, 0, false);
if (!scope) {
ecs_parser_error(name, expr, ptr - expr,
"unresolved identifier '%s' in using statement", using_path);
return NULL;
}
plecs_push_using(scope, state);
}
state->using_frames[state->sp] = state->using_frame;
return ptr;
}
static
const char* plecs_parse_module_stmt(
ecs_world_t *world,
const char *name,
const char *expr,
const char *ptr,
plecs_state_t *state)
{
const char *expr_start = ecs_parse_ws_eol(expr);
if (expr_start != ptr) {
ecs_parser_error(name, expr, ptr - expr,
"module must be first statement of script");
return NULL;
}
char module_path[ECS_MAX_TOKEN_SIZE];
const char *tmp = ptr + 1;
ptr = ecs_parse_token(name, expr, ptr + 6, module_path, 0);
if (!ptr) {
ecs_parser_error(name, expr, tmp - expr,
"expected identifier for module statement");
return NULL;
}
ecs_component_desc_t desc = {0};
desc.entity = ecs_entity(world, { .name = module_path });
ecs_entity_t module = ecs_module_init(world, NULL, &desc);
if (!module) {
return NULL;
}
state->is_module = true;
state->sp ++;
state->scope[state->sp] = module;
ecs_set_scope(world, module);
return ptr;
}
static
const char* plecs_parse_with_stmt(
const char *name,
const char *expr,
const char *ptr,
plecs_state_t *state)
{
if (state->isa_stmt) {
ecs_parser_error(name, expr, ptr - expr,
"invalid with after inheritance");
return NULL;
}
if (state->assign_stmt) {
ecs_parser_error(name, expr, ptr - expr,
"invalid with in assign_stmt");
return NULL;
}
/* Add following expressions to with list */
state->with_stmt = true;
return ptr + 5;
}
static
const char* plecs_parse_assembly_stmt(
const char *name,
const char *expr,
const char *ptr,
plecs_state_t *state)
{
if (state->isa_stmt) {
ecs_parser_error(name, expr, ptr - expr,
"invalid with after inheritance");
return NULL;
}
if (state->assign_stmt) {
ecs_parser_error(name, expr, ptr - expr,
"invalid with in assign_stmt");
return NULL;
}
state->assembly_stmt = true;
return ptr + 9;
}
static
const char* plecs_parse_var_type(
ecs_world_t *world,
const char *name,
const char *expr,
const char *ptr,
plecs_state_t *state,
ecs_entity_t *type_out)
{
char prop_type_name[ECS_MAX_TOKEN_SIZE];
const char *tmp = ptr + 1;
ptr = ecs_parse_token(name, expr, ptr + 1, prop_type_name, 0);
if (!ptr) {
ecs_parser_error(name, expr, tmp - expr,
"expected type for prop declaration");
return NULL;
}
ecs_entity_t prop_type = plecs_lookup(world, prop_type_name, state, 0, false);
if (!prop_type) {
ecs_parser_error(name, expr, ptr - expr,
"unresolved property type '%s'", prop_type_name);
return NULL;
}
*type_out = prop_type;
return ptr;
}
static
const char* plecs_parse_const_stmt(
ecs_world_t *world,
const char *name,
const char *expr,
const char *ptr,
plecs_state_t *state)
{
ptr = ecs_parse_token(name, expr, ptr + 5, state->var_name, 0);
if (!ptr) {
return NULL;
}
ptr = ecs_parse_ws(ptr);
if (ptr[0] == ':') {
ptr = plecs_parse_var_type(
world, name, expr, ptr, state, &state->last_assign_id);
if (!ptr) {
return NULL;
}
ptr = ecs_parse_ws(ptr);
}
if (ptr[0] != '=') {
ecs_parser_error(name, expr, ptr - expr,
"expected '=' after const declaration");
return NULL;
}
state->var_stmt = true;
return ptr + 1;
}
static
const char* plecs_parse_prop_stmt(
ecs_world_t *world,
const char *name,
const char *expr,
const char *ptr,
plecs_state_t *state)
{
char prop_name[ECS_MAX_TOKEN_SIZE];
ptr = ecs_parse_token(name, expr, ptr + 5, prop_name, 0);
if (!ptr) {
return NULL;
}
ptr = ecs_parse_ws(ptr);
if (ptr[0] != ':') {
ecs_parser_error(name, expr, ptr - expr,
"expected ':' after prop declaration");
return NULL;
}
ecs_entity_t prop_type;
ptr = plecs_parse_var_type(world, name, expr, ptr, state, &prop_type);
if (!ptr) {
return NULL;
}
ecs_entity_t assembly = state->assembly;
if (!assembly) {
ecs_parser_error(name, expr, ptr - expr,
"unexpected prop '%s' outside of assembly", prop_name);
return NULL;
}
if (!state->assembly_instance) {
ecs_entity_t prop_member = ecs_entity(world, {
.name = prop_name,
.add = { ecs_childof(assembly) }
});
if (!prop_member) {
return NULL;
}
ecs_set(world, prop_member, EcsMember, {
.type = prop_type
});
}
if (ptr[0] != '=') {
ecs_parser_error(name, expr, ptr - expr,
"expected '=' after prop type");
return NULL;
}
ecs_os_strcpy(state->var_name, prop_name);
state->last_assign_id = prop_type;
state->var_stmt = true;
state->var_is_prop = true;
return plecs_parse_fluff(ptr + 1);
}
static
const char* plecs_parse_scope_open(
ecs_world_t *world,
const char *name,
const char *expr,
const char *ptr,
plecs_state_t *state)
{
state->isa_stmt = false;
if (state->assign_stmt) {
ecs_parser_error(name, expr, ptr - expr,
"invalid scope in assign_stmt");
return NULL;
}
state->sp ++;
ecs_entity_t scope = 0;
ecs_entity_t default_scope_type = 0;
if (!state->with_stmt) {
if (state->last_subject) {
scope = state->last_subject;
ecs_set_scope(world, state->last_subject);
/* Check if scope has a default child component */
ecs_entity_t def_type_src = ecs_get_target_for_id(world, scope,
0, ecs_pair(EcsDefaultChildComponent, EcsWildcard));
if (def_type_src) {
default_scope_type = ecs_get_target(
world, def_type_src, EcsDefaultChildComponent, 0);
}
} else {
if (state->last_object) {
scope = ecs_pair(
state->last_predicate, state->last_object);
ecs_set_with(world, scope);
} else {
if (state->last_predicate) {
scope = ecs_pair(EcsChildOf, state->last_predicate);
}
ecs_set_scope(world, state->last_predicate);
}
}
state->scope[state->sp] = scope;
state->default_scope_type[state->sp] = default_scope_type;
if (state->assembly_stmt) {
if (state->assembly) {
ecs_parser_error(name, expr, ptr - expr,
"invalid nested assembly");
return NULL;
}
state->assembly = scope;
state->assembly_stmt = false;
state->assembly_start = ptr;
}
} else {
state->scope[state->sp] = state->scope[state->sp - 1];
state->default_scope_type[state->sp] =
state->default_scope_type[state->sp - 1];
}
state->using_frames[state->sp] = state->using_frame;
state->with_frames[state->sp] = state->with_frame;
state->with_stmt = false;
ecs_vars_push(&state->vars);
return ptr;
}
static
const char* plecs_parse_scope_close(
ecs_world_t *world,
const char *name,
const char *expr,
const char *ptr,
plecs_state_t *state)
{
if (state->isa_stmt) {
ecs_parser_error(name, expr, ptr - expr,
"invalid '}' after inheritance statement");
return NULL;
}
if (state->assign_stmt) {
ecs_parser_error(name, expr, ptr - expr,
"unfinished assignment before }");
return NULL;
}
ecs_entity_t cur = state->scope[state->sp], assembly = state->assembly;
if (state->sp && (cur == state->scope[state->sp - 1])) {
/* Previous scope is also from the assembly, not found the end yet */
cur = 0;
}
if (cur && cur == assembly) {
ecs_size_t assembly_len = flecs_ito(ecs_size_t, ptr - state->assembly_start);
if (assembly_len) {
assembly_len --;
char *script = ecs_os_malloc_n(char, assembly_len + 1);
ecs_os_memcpy(script, state->assembly_start, assembly_len);
script[assembly_len] = '\0';
state->assembly = 0;
state->assembly_start = NULL;
if (flecs_assembly_create(world, name, expr, ptr, assembly, script, state)) {
return NULL;
}
} else {
ecs_parser_error(name, expr, ptr - expr, "empty assembly");
return NULL;
}
}
state->scope[state->sp] = 0;
state->default_scope_type[state->sp] = 0;
state->sp --;
if (state->sp < 0) {
ecs_parser_error(name, expr, ptr - expr, "invalid } without a {");
return NULL;
}
ecs_id_t id = state->scope[state->sp];
if (!id || ECS_HAS_ID_FLAG(id, PAIR)) {
ecs_set_with(world, id);
}
if (!id || !ECS_HAS_ID_FLAG(id, PAIR)) {
ecs_set_scope(world, id);
}
int32_t i, prev_with = state->with_frames[state->sp];
for (i = prev_with; i < state->with_frame; i ++) {
plecs_with_value_t *v = &state->with_value_frames[i];
if (!v->owned) {
continue;
}
if (v->value.type) {
ecs_value_free(world, v->value.type, v->value.ptr);
v->value.type = 0;
v->value.ptr = NULL;
v->owned = false;
}
}
state->with_frame = state->with_frames[state->sp];
state->using_frame = state->using_frames[state->sp];
state->last_subject = 0;
state->assign_stmt = false;
ecs_vars_pop(&state->vars);
return plecs_parse_fluff(ptr + 1);
}
static
const char *plecs_parse_plecs_term(
ecs_world_t *world,
const char *name,
const char *expr,
const char *ptr,
plecs_state_t *state)
{
ecs_term_t term = {0};
ecs_entity_t decl_id = 0;
if (state->decl_stmt) {
decl_id = state->last_predicate;
}
ptr = ecs_parse_term(world, name, expr, ptr, &term);
if (!ptr) {
return NULL;
}
if (flecs_isident(ptr[0])) {
state->decl_type = true;
}
if (!ecs_term_is_initialized(&term)) {
ecs_parser_error(name, expr, ptr - expr, "expected identifier");
return NULL; /* No term found */
}
if (plecs_create_term(world, &term, name, expr, (ptr - expr), state)) {
ecs_term_fini(&term);
return NULL; /* Failed to create term */
}
if (decl_id && state->last_subject) {
ecs_add_id(world, state->last_subject, decl_id);
}
state->decl_type = false;
ecs_term_fini(&term);
return ptr;
}
static
const char* plecs_parse_annotation(
const char *name,
const char *expr,
const char *ptr,
plecs_state_t *state)
{
do {
if(state->annot_count >= STACK_MAX_SIZE) {
ecs_parser_error(name, expr, ptr - expr,
"max number of annotations reached");
return NULL;
}
char ch;
const char *start = ptr;
for (; (ch = *ptr) && ch != '\n'; ptr ++) { }
int32_t len = (int32_t)(ptr - start);
char *annot = ecs_os_malloc_n(char, len + 1);
ecs_os_memcpy_n(annot, start, char, len);
annot[len] = '\0';
state->annot[state->annot_count] = annot;
state->annot_count ++;
ptr = plecs_parse_fluff(ptr);
} while (ptr[0] == '@');
return ptr;
}
static
void plecs_clear_annotations(
plecs_state_t *state)
{
int32_t i, count = state->annot_count;
for (i = 0; i < count; i ++) {
ecs_os_free(state->annot[i]);
}
state->annot_count = 0;
}
static
const char* plecs_parse_stmt(
ecs_world_t *world,
const char *name,
const char *expr,
const char *ptr,
plecs_state_t *state)
{
state->assign_stmt = false;
state->scope_assign_stmt = false;
state->isa_stmt = false;
state->with_stmt = false;
state->decl_stmt = false;
state->var_stmt = false;
state->last_subject = 0;
state->last_predicate = 0;
state->last_object = 0;
state->assign_to = 0;
state->last_assign_id = 0;
plecs_clear_annotations(state);
ptr = plecs_parse_fluff(ptr);
char ch = ptr[0];
if (!ch) {
goto done;
} else if (ch == '{') {
ptr = plecs_parse_fluff(ptr + 1);
goto scope_open;
} else if (ch == '}') {
goto scope_close;
} else if (ch == '-') {
ptr = plecs_parse_fluff(ptr + 1);
state->assign_to = ecs_get_scope(world);
state->scope_assign_stmt = true;
goto assign_stmt;
} else if (ch == '@') {
ptr = plecs_parse_annotation(name, expr, ptr, state);
if (!ptr) goto error;
goto term_expr;
} else if (!ecs_os_strncmp(ptr, TOK_USING " ", 5)) {
ptr = plecs_parse_using_stmt(world, name, expr, ptr, state);
if (!ptr) goto error;
goto done;
} else if (!ecs_os_strncmp(ptr, TOK_MODULE " ", 6)) {
ptr = plecs_parse_module_stmt(world, name, expr, ptr, state);
if (!ptr) goto error;
goto done;
} else if (!ecs_os_strncmp(ptr, TOK_WITH " ", 5)) {
ptr = plecs_parse_with_stmt(name, expr, ptr, state);
if (!ptr) goto error;
goto term_expr;
} else if (!ecs_os_strncmp(ptr, TOK_CONST " ", 6)) {
ptr = plecs_parse_const_stmt(world, name, expr, ptr, state);
if (!ptr) goto error;
goto assign_expr;
} else if (!ecs_os_strncmp(ptr, TOK_ASSEMBLY " ", 9)) {
ptr = plecs_parse_assembly_stmt(name, expr, ptr, state);
if (!ptr) goto error;
goto decl_stmt;
} else if (!ecs_os_strncmp(ptr, TOK_PROP " ", 5)) {
ptr = plecs_parse_prop_stmt(world, name, expr, ptr, state);
if (!ptr) goto error;
goto assign_expr;
} else {
goto term_expr;
}
term_expr:
if (!ptr[0]) {
goto done;
}
if (ptr[0] == '$' && !isspace(ptr[1])) {
if (state->with_stmt) {
ptr = plecs_parse_assign_with_var(name, expr, ptr, state);
if (!ptr) {
return NULL;
}
} else if (!state->var_stmt) {
goto assign_var_as_component;
}
} else if (!(ptr = plecs_parse_plecs_term(world, name, ptr, ptr, state))) {
goto error;
}
const char *tptr = ecs_parse_ws(ptr);
if (flecs_isident(tptr[0])) {
if (state->decl_stmt) {
ecs_parser_error(name, expr, (ptr - expr),
"unexpected ' ' in declaration statement");
goto error;
}
ptr = tptr;
goto decl_stmt;
}
next_term:
ptr = plecs_parse_fluff(ptr);
if (ptr[0] == ':' && ptr[1] == '-') {
ptr = plecs_parse_fluff(ptr + 2);
goto assign_stmt;
} else if (ptr[0] == ':') {
ptr = plecs_parse_fluff(ptr + 1);
goto inherit_stmt;
} else if (ptr[0] == ',') {
ptr = plecs_parse_fluff(ptr + 1);
goto term_expr;
} else if (ptr[0] == '{') {
if (state->assign_stmt) {
goto assign_expr;
} else if (state->with_stmt && !isspace(ptr[-1])) {
/* If this is a { in a with statement which directly follows a
* non-whitespace character, the with id has a value */
ptr = plecs_parse_assign_with_stmt(world, name, expr, ptr, state);
if (!ptr) {
goto error;
}
goto next_term;
} else {
ptr = plecs_parse_fluff(ptr + 1);
goto scope_open;
}
}
state->assign_stmt = false;
goto done;
decl_stmt:
state->decl_stmt = true;
goto term_expr;
inherit_stmt:
ptr = plecs_parse_inherit_stmt(name, expr, ptr, state);
if (!ptr) goto error;
/* Expect base identifier */
goto term_expr;
assign_stmt:
ptr = plecs_parse_assign_stmt(world, name, expr, ptr, state);
if (!ptr) goto error;
ptr = plecs_parse_fluff(ptr);
/* Assignment without a preceding component */
if (ptr[0] == '{') {
goto assign_expr;
}
/* Expect component identifiers */
goto term_expr;
assign_expr:
ptr = plecs_parse_assign_expr(world, name, expr, ptr, state, NULL);
if (!ptr) goto error;
ptr = plecs_parse_fluff(ptr);
if (ptr[0] == ',') {
ptr ++;
goto term_expr;
} else if (ptr[0] == '{') {
if (state->var_stmt) {
ecs_expr_var_t *var = ecs_vars_lookup(&state->vars, state->var_name);
if (var && var->value.type == ecs_id(ecs_entity_t)) {
ecs_assert(var->value.ptr != NULL, ECS_INTERNAL_ERROR, NULL);
/* The code contained an entity{...} variable assignment, use
* the assigned entity id as type for parsing the expression */
state->last_assign_id = *(ecs_entity_t*)var->value.ptr;
ptr = plecs_parse_assign_expr(world, name, expr, ptr, state, var);
goto done;
}
}
ecs_parser_error(name, expr, (ptr - expr),
"unexpected '{' after assignment");
goto error;
}
state->assign_stmt = false;
state->assign_to = 0;
goto done;
assign_var_as_component: {
ptr = plecs_parse_var_as_component(world, name, expr, ptr, state);
if (!ptr) {
goto error;
}
state->assign_stmt = false;
state->assign_to = 0;
goto done;
}
scope_open:
ptr = plecs_parse_scope_open(world, name, expr, ptr, state);
if (!ptr) goto error;
goto done;
scope_close:
ptr = plecs_parse_scope_close(world, name, expr, ptr, state);
if (!ptr) goto error;
goto done;
done:
return ptr;
error:
return NULL;
}
static
int flecs_plecs_parse(
ecs_world_t *world,
const char *name,
const char *expr,
ecs_vars_t *vars,
ecs_entity_t script,
ecs_entity_t instance)
{
const char *ptr = expr;
ecs_term_t term = {0};
plecs_state_t state = {0};
if (!expr) {
return 0;
}
state.scope[0] = 0;
ecs_entity_t prev_scope = ecs_set_scope(world, 0);
ecs_entity_t prev_with = ecs_set_with(world, 0);
if (ECS_IS_PAIR(prev_with) && ECS_PAIR_FIRST(prev_with) == EcsChildOf) {
ecs_set_scope(world, ECS_PAIR_SECOND(prev_with));
state.scope[0] = ecs_pair_second(world, prev_with);
} else {
state.global_with = prev_with;
}
ecs_vars_init(world, &state.vars);
if (script) {
const EcsScript *s = ecs_get(world, script, EcsScript);
if (!s) {
ecs_err("%s: provided script entity is not a script", name);
goto error;
}
if (s && ecs_has(world, script, EcsStruct)) {
state.assembly = script;
state.assembly_instance = true;
if (s->using_.count) {
ecs_os_memcpy_n(state.using, s->using_.array,
ecs_entity_t, s->using_.count);
state.using_frame = s->using_.count;
state.using_frames[0] = s->using_.count;
}
if (instance) {
ecs_set_scope(world, instance);
}
}
}
if (vars) {
state.vars.root.parent = vars->cur;
}
do {
expr = ptr = plecs_parse_stmt(world, name, expr, ptr, &state);
if (!ptr) {
goto error;
}
if (!ptr[0]) {
break; /* End of expression */
}
} while (true);
ecs_set_scope(world, prev_scope);
ecs_set_with(world, prev_with);
plecs_clear_annotations(&state);
if (state.is_module) {
state.sp --;
}
if (state.sp != 0) {
ecs_parser_error(name, expr, 0, "missing end of scope");
goto error;
}
if (state.assign_stmt) {
ecs_parser_error(name, expr, 0, "unfinished assignment");
goto error;
}
if (state.errors) {
goto error;
}
ecs_vars_fini(&state.vars);
return 0;
error:
ecs_vars_fini(&state.vars);
ecs_set_scope(world, state.scope[0]);
ecs_set_with(world, prev_with);
ecs_term_fini(&term);
return -1;
}
int ecs_plecs_from_str(
ecs_world_t *world,
const char *name,
const char *expr)
{
return flecs_plecs_parse(world, name, expr, NULL, 0, 0);
}
static
char* flecs_load_from_file(
const char *filename)
{
FILE* file;
char* content = NULL;
int32_t bytes;
size_t size;
/* Open file for reading */
ecs_os_fopen(&file, filename, "r");
if (!file) {
ecs_err("%s (%s)", ecs_os_strerror(errno), filename);
goto error;
}
/* Determine file size */
fseek(file, 0 , SEEK_END);
bytes = (int32_t)ftell(file);
if (bytes == -1) {
goto error;
}
rewind(file);
/* Load contents in memory */
content = ecs_os_malloc(bytes + 1);
size = (size_t)bytes;
if (!(size = fread(content, 1, size, file)) && bytes) {
ecs_err("%s: read zero bytes instead of %d", filename, size);
ecs_os_free(content);
content = NULL;
goto error;
} else {
content[size] = '\0';
}
fclose(file);
return content;
error:
ecs_os_free(content);
return NULL;
}
int ecs_plecs_from_file(
ecs_world_t *world,
const char *filename)
{
char *script = flecs_load_from_file(filename);
if (!script) {
return -1;
}
int result = ecs_plecs_from_str(world, filename, script);
ecs_os_free(script);
return result;
}
static
ecs_id_t flecs_script_tag(
ecs_entity_t script,
ecs_entity_t instance)
{
if (!instance) {
return ecs_pair_t(EcsScript, script);
} else {
return ecs_pair(EcsChildOf, instance);
}
}
void ecs_script_clear(
ecs_world_t *world,
ecs_entity_t script,
ecs_entity_t instance)
{
ecs_delete_with(world, flecs_script_tag(script, instance));
}
int ecs_script_update(
ecs_world_t *world,
ecs_entity_t e,
ecs_entity_t instance,
const char *script,
ecs_vars_t *vars)
{
ecs_assert(world != NULL, ECS_INTERNAL_ERROR, NULL);
ecs_assert(script != NULL, ECS_INTERNAL_ERROR, NULL);
int result = 0;
bool is_defer = ecs_is_deferred(world);
ecs_suspend_readonly_state_t srs;
ecs_world_t *real_world = NULL;
if (is_defer) {
ecs_assert(ecs_poly_is(world, ecs_world_t), ECS_INTERNAL_ERROR, NULL);
real_world = flecs_suspend_readonly(world, &srs);
ecs_assert(real_world != NULL, ECS_INTERNAL_ERROR, NULL);
}
ecs_script_clear(world, e, instance);
EcsScript *s = ecs_get_mut(world, e, EcsScript);
if (!s->script || ecs_os_strcmp(s->script, script)) {
s->script = ecs_os_strdup(script);
ecs_modified(world, e, EcsScript);
}
ecs_entity_t prev = ecs_set_with(world, flecs_script_tag(e, instance));
if (flecs_plecs_parse(world, ecs_get_name(world, e), script, vars, e, instance)) {
ecs_delete_with(world, ecs_pair_t(EcsScript, e));
result = -1;
}
ecs_set_with(world, prev);
if (is_defer) {
flecs_resume_readonly(real_world, &srs);
}
return result;
}
ecs_entity_t ecs_script_init(
ecs_world_t *world,
const ecs_script_desc_t *desc)
{
const char *script = NULL;
ecs_entity_t e = desc->entity;
ecs_check(world != NULL, ECS_INTERNAL_ERROR, NULL);
ecs_check(desc != NULL, ECS_INTERNAL_ERROR, NULL);
if (!e) {
if (desc->filename) {
e = ecs_new_from_path_w_sep(world, 0, desc->filename, "/", NULL);
} else {
e = ecs_new_id(world);
}
}
script = desc->str;
if (!script && desc->filename) {
script = flecs_load_from_file(desc->filename);
if (!script) {
goto error;
}
}
if (ecs_script_update(world, e, 0, script, NULL)) {
goto error;
}
if (script != desc->str) {
/* Safe cast, only happens when script is loaded from file */
ecs_os_free(ECS_CONST_CAST(char*, script));
}
return e;
error:
if (script != desc->str) {
/* Safe cast, only happens when script is loaded from file */
ecs_os_free(ECS_CONST_CAST(char*, script));
}
if (!desc->entity) {
ecs_delete(world, e);
}
return 0;
}
void FlecsScriptImport(
ecs_world_t *world)
{
ECS_MODULE(world, FlecsScript);
ECS_IMPORT(world, FlecsMeta);
ecs_set_name_prefix(world, "Ecs");
ECS_COMPONENT_DEFINE(world, EcsScript);
ecs_set_hooks(world, EcsScript, {
.ctor = ecs_default_ctor,
.move = ecs_move(EcsScript),
.dtor = ecs_dtor(EcsScript)
});
ecs_add_id(world, ecs_id(EcsScript), EcsTag);
ecs_add_id(world, ecs_id(EcsScript), EcsPrivate);
ecs_struct(world, {
.entity = ecs_id(EcsScript),
.members = {
{ .name = "using", .type = ecs_vector(world, {
.entity = ecs_entity(world, { .name = "UsingVector" }),
.type = ecs_id(ecs_entity_t)
}),
.count = 0
},
{ .name = "script", .type = ecs_id(ecs_string_t), .count = 0 }
}
});
}
#endif
| 2.1875 | 2 |
2024-11-18T22:37:10.696482+00:00 | 2022-05-29T15:20:26 | 8031d894dcefc837649d5fb0c65c0d72c338a0d4 | {
"blob_id": "8031d894dcefc837649d5fb0c65c0d72c338a0d4",
"branch_name": "refs/heads/master",
"committer_date": "2022-05-29T15:20:26",
"content_id": "552b753e2bf42eaead876574fb6d9a24a8a3fb05",
"detected_licenses": [
"MIT"
],
"directory_id": "e72c68557ff1ce689a69fd1ecef8ef77ad21d047",
"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": 243916563,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1911,
"license": "MIT",
"license_type": "permissive",
"path": "/code/_sem_1/recursive_fibonacci/main.c",
"provenance": "stackv2-0107.json.gz:91805",
"repo_name": "senior-sigan/omsu_cpp_course",
"revision_date": "2022-05-29T15:20:26",
"revision_id": "fa2d6aa672b1ddd2725b07dfd219d8e0fbac455f",
"snapshot_id": "c3124a5a34d7d9e6104f014193afef6dc7a1ab96",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/senior-sigan/omsu_cpp_course/fa2d6aa672b1ddd2725b07dfd219d8e0fbac455f/code/_sem_1/recursive_fibonacci/main.c",
"visit_date": "2022-06-15T13:15:02.503867"
} | stackv2 | #include "test.h"
// recursive_fib выдает N-ый член последовательности Фибоначчи.
// Правило последовательности:
// recursive_fib(0) == 0
// recursive_fib(1) == 1
// recursive_fib(2) == 1
// recursive_fib(n+1) = recursive_fib(n) + recursive_fib(n-1)
// !!! Функция должна использовать рекурсию
// Циклы for, while ЗАПРЕЩЕНЫ
int recursive_fib(int n) {
// Напиши меня!
return n;
}
void cli(void) {
// TODO: напиши меня
// 1. Запросите у пользователя целое число
// 2. Считайте с консоли число n
// 3. Обработайте возможный неверный ввод (отрицательное число)
// 4. Выведите пользователю результат recursive_fib(n)
}
void test(void) {
// Это тесты. НЕ УДАЛЯЙТЕ ИХ!
// Преподаватель будет грустить, если вы удалите тесты T_T.
// Тесты проверяют, что ваш код работает правильно.
// Если задача решена неправильно,
// то в консоли вы увидите ошибку и пояснение.
// Сдавайте лабу, когда устраните все ошибки в тестах.
// Если возникли трудности, то попросите преподавателя вам помочь ^_^.
ASSERT_INT(0, ==, recursive_fib(0));
ASSERT_INT(1, ==, recursive_fib(1));
ASSERT_INT(1, ==, recursive_fib(2));
ASSERT_INT(2, ==, recursive_fib(3));
ASSERT_INT(3, ==, recursive_fib(4));
ASSERT_INT(55, ==, recursive_fib(10));
ASSERT_INT(89, ==, recursive_fib(11));
ASSERT_INT(987, ==, recursive_fib(16));
}
int main(void) {
test();
cli();
return 0;
}
| 2.96875 | 3 |
2024-11-18T22:37:10.818693+00:00 | 2020-05-02T03:48:56 | 4d46be64fa600c023595d304f0a8c3345dd8e5c3 | {
"blob_id": "4d46be64fa600c023595d304f0a8c3345dd8e5c3",
"branch_name": "refs/heads/master",
"committer_date": "2020-05-02T03:48:56",
"content_id": "518d10c310d24113d9d8337d8b78e0d3889aa0a5",
"detected_licenses": [
"MIT"
],
"directory_id": "ee4838ceb10d677b8ca925e640185ebe5dc5d50c",
"extension": "c",
"filename": "jamdevices.c",
"fork_events_count": 2,
"gha_created_at": "2019-10-22T22:10:31",
"gha_event_created_at": "2019-10-22T22:10:31",
"gha_language": null,
"gha_license_id": "NOASSERTION",
"github_id": 216918566,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 6569,
"license": "MIT",
"license_type": "permissive",
"path": "/lib/jamlib/jamdevices.c",
"provenance": "stackv2-0107.json.gz:91934",
"repo_name": "donatKapesa/JAMScript",
"revision_date": "2020-05-02T03:48:56",
"revision_id": "fadf04ecb642b1cd6d173f09345b916ce422324e",
"snapshot_id": "f8c78c34330ced150cbdc9501130d40125462adc",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/donatKapesa/JAMScript/fadf04ecb642b1cd6d173f09345b916ce422324e/lib/jamlib/jamdevices.c",
"visit_date": "2020-08-24T22:28:49.574142"
} | stackv2 | /*
The MIT License (MIT)
Copyright (c) 2017 Muthucumaru Maheswaran
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/*
This module is responsible for interfacing with outside devices.
We can interface to FIFOs, or custom hardware like Analog-to-Digital convertors
using this module. This design is tested on a Raspberry Pi HAT for LTE
and other sensors.
*/
#include "jam.h"
#include "jamdevices.h"
jamdevtable_t *jdtable;
jamdevtypes_t *jdtypes;
//
// TODO: Revise the type table with a Hash table data structure.
//
/*
* This initializes the JAM Devices subsystem.
*/
void jamdev_init()
{
jdtable = (jamdevtable_t *)calloc(1, sizeof(jamdevtable_t));
jdtypes = (jamdevtypes_t *)calloc(1, sizeof(jamdevtypes_t));
jdtable->size = 0;
jdtypes->size = 0;
}
// Insert the type into the type table. If the type is already there, we overwrite
// the entry with the new specification. With a new entry, we will increment type entry
// size..
//
void jamdev_reg_callbacks(int type, jdcallbacki_f opencb, void *oarg, jdcallbackii_f readcb, void *rarg)
{
// TODO: hash table badly needed here!
jamtypeentry_t *jtype = (jamtypeentry_t *)calloc(1, sizeof(jamtypeentry_t));
jtype->type = type;
jtype->opencb = opencb;
jtype->oarg = oarg;
jtype->readcb = readcb;
jtype->rarg = rarg;
insert_jtypeentry(jdtypes, jtype);
}
void *bgreader(void *arg)
{
int oldtype;
pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &oldtype);
jamdeventry_t *jde = (jamdeventry_t *)arg;
jamtypeentry_t *jtype = get_jtypeentry(jde->type);
while(1) {
int x = jtype->readcb(jde->fd);
pqueue_enq(jde->dataq, &x, sizeof(x));
}
}
// Search the table for the same type and name, if found return fail
//
// create entry - put it in the table
// open the device using callback as part of the initialization
// create the thread to service the device
// pass the table entry to it the thread.
// thread runs the entry and pushes the data to the queue..
//
int jopen(int type, char *name, int mode)
{
// return fail if already open
if (check4open(type, name))
return -1;
jamtypeentry_t *jtype = get_jtypeentry(type);
jamdeventry_t *jdev = (jamdeventry_t *)calloc(1, sizeof(jamdeventry_t));
// fill up the entry
jdev->type = type;
jdev->name = name;
jdev->mode = mode;
jdev->dataq = pqueue_new(true); // TODO: check again.. should it be true?
// open the device...
int rval = jtype->opencb((void *)name);
if (rval >= 0)
{
jdev->fd = rval;
// insert the entry
int fid = insert_jdeventry(jdtable, jdev);
// create the thread for handling the request
pthread_create(&(jdev->tid), NULL, bgreader, (void *)jdev);
return fid;
} else
{
pqueue_delete(jdev->dataq);
free(jdev);
return -1;
}
}
// Read data from the queue.
// Blocks on the queue.. without blocking the JAMScript program...
//
int jread(int id, char *buf, int *len)
{
jamdeventry_t *jdev = get_jdeventry(jdtable, id);
// return -1 if the entry is not found
if (jdev == NULL)
return -1;
// Waits in a non blocking way...
nvoid_t *nv = pqueue_deq(jdev->dataq);
if (nv != NULL)
{
buf = (char *)nv->data;
free(nv);
*len = strlen(buf);
}
return strlen(buf);
}
// just free the entry and annul it.
// we need to terminate the handler thread before closing the entry
//
void jclose(int id)
{
}
// Push the data into the queue .. and return
// The handler is responsible for pulling the data
// from the queue and sending it on to the device..
// So there would be another thread..?
// The question is whether we could have just one thread for both
// reading and writing.. it just watches both sides using poll/select?
// Or have two different threads..
//
// This is not yet implemented!
//
int jwrite(int id, char *buf, int len)
{
return 0;
}
//
// Private functions...
//
//
// Search through the jdtypes table. if found overwrite the entry
//
void insert_jtypeentry(jamdevtypes_t *jdtypes, jamtypeentry_t *jtype)
{
int i;
for (i = 0; i < jdtypes->size; i++)
{
if (jdtypes->entries[i]->type == jtype->type)
{
free(jdtypes->entries[i]);
jdtypes->entries[i] = jtype;
return;
}
}
i = jdtypes->size++;
jdtypes->entries[i] = jtype;
}
bool check4open(int type, char *name)
{
int i;
for (i = 0; i < jdtable->size; i++)
{
if (jdtable->entries[i])
{
if (jdtable->entries[i]->type == type && strcmp(jdtable->entries[i]->name, name) == 0)
return true;
}
}
return false;
}
// Return the slot occupied by the new entry..
//
int insert_jdeventry(jamdevtable_t *jdtable, jamdeventry_t *jdev)
{
int i;
// insert in a blank spot if there is one..
for (i = 0; i < jdtable->size; i++)
{
if (!jdtable->entries[i])
{
// insert it here and return ..
jdtable->entries[i] = jdev;
return i;
}
}
// make a new entry and return...
i = jdtable->size++;
jdtable->entries[i] = jdev;
return i;
}
jamdeventry_t *get_jdeventry(jamdevtable_t *jdtable, int id)
{
return jdtable->entries[id];
}
jamtypeentry_t *get_jtypeentry(int type)
{
int i;
for (i = 0; i < jdtypes->size; i++)
{
if (jdtypes->entries[i]->type == type)
return jdtypes->entries[i];
}
return NULL;
}
| 2.3125 | 2 |
2024-11-18T22:37:11.135008+00:00 | 2023-01-11T23:43:12 | 2fcc76013c007c243bb97627d265b39421614ca4 | {
"blob_id": "2fcc76013c007c243bb97627d265b39421614ca4",
"branch_name": "refs/heads/master",
"committer_date": "2023-01-11T23:43:12",
"content_id": "0dcac6cdc2524fca408dd1200400908b3ae67291",
"detected_licenses": [
"ISC"
],
"directory_id": "f806c29d2ee80cc730300b36a7e7fbdfe42ed14e",
"extension": "c",
"filename": "server.c",
"fork_events_count": 4,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 7613062,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2388,
"license": "ISC",
"license_type": "permissive",
"path": "/src/libconnth/test/server.c",
"provenance": "stackv2-0107.json.gz:92451",
"repo_name": "noaaport/nbsp",
"revision_date": "2023-01-11T23:43:12",
"revision_id": "39ae50d2445df016cf69d54527d83dc1ac172338",
"snapshot_id": "3095cfcac6a8c39a67cc9b2fd42005587945f67d",
"src_encoding": "UTF-8",
"star_events_count": 6,
"url": "https://raw.githubusercontent.com/noaaport/nbsp/39ae50d2445df016cf69d54527d83dc1ac172338/src/libconnth/test/server.c",
"visit_date": "2023-08-14T03:47:01.348920"
} | stackv2 | #include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <err.h>
#include "../libconn.h"
#include "common.h"
static int init_conn_table(int *fd, int numfd);
static int free_conn_table(void);
static int process_connection(struct conn_table_st *ct, int i);
static struct conn_table_st *gconnt = NULL;
static int process_connection(struct conn_table_st *ct, int i){
int status = 0;
int n;
char buf[BUFSIZ];
int fd;
pid_t pid;
char *addr;
fd = conn_table_get_element_fd(ct, i);
pid = conn_table_get_element_pid(ct, i);
if(pid == -1){
addr = conn_table_get_element_ip(ct, i);
fprintf(stdout, "Connection from %s\n", addr);
}else
fprintf(stdout, "Connection from %d\n", pid);
if((n = read(fd, buf, BUFSIZ)) > 0){
buf[n] = '\0';
fprintf(stdout, "%s\n", buf);
strcpy(buf, "server: Received\n");
write(fd, buf, strlen(buf));
}else{
perror("read");
status = i;
}
return(status);
}
int main(void){
int fd[2];
int status = 0;
/*
* open the unix connection socket
*/
fd[0] = server_open_conn(SERVER_SOCKET, "dialer", 5);
if(fd[0] <= 0)
err(1, "server_open_conn()");
/*
* the network socket
*/
fd[1] = server_open_nconn(WMON_PORT, 5);
if(fd[1] == -1)
err(1, "server_open_nconn()");
status = init_conn_table(fd, 2);
while(status == 0){
status = poll_loop(gconnt);
fprintf(stdout, "status from poll loop: %d\n", status);
}
free_conn_table();
close(fd[0]);
close(fd[1]);
unlink(SERVER_SOCKET);
return(0);
}
static int init_conn_table(int *fd, int numfd){
int status = 0;
int i;
gconnt = conn_table_create(2, process_connection, NULL);
if(gconnt == NULL)
err(1, "conn_table_create");
status = conn_table_add_element(gconnt, fd[0], CONN_TYPE_SERVER_LOCAL,
0, NULL, NULL);
if(status == 0)
status = conn_table_add_element(gconnt, fd[1], CONN_TYPE_SERVER_NET,
0, NULL, NULL);
if(status == 0){
for(i = 2; (i <= numfd - 1) && (status == 0); +i)
status = conn_table_add_element(gconnt, fd[i], CONN_TYPE_APPLICATION,
0, NULL, NULL);
}
if(status != 0)
err(1, "conn_table_add_element");
return(status);
}
static int free_conn_table(void){
conn_table_destroy(gconnt);
gconnt = NULL;
return(0);
}
| 2.65625 | 3 |
2024-11-18T22:37:11.287772+00:00 | 2021-04-13T13:39:06 | f9374f5875da355246d50eb7a4f385a4271ab4c5 | {
"blob_id": "f9374f5875da355246d50eb7a4f385a4271ab4c5",
"branch_name": "refs/heads/main",
"committer_date": "2021-04-13T13:39:06",
"content_id": "eb73866a1fd88f50747226b7b141304b177e504f",
"detected_licenses": [
"MIT"
],
"directory_id": "cf56168422d8e53de830a232dc4481263f08a53c",
"extension": "c",
"filename": "p1.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": 798,
"license": "MIT",
"license_type": "permissive",
"path": "/projects/p1/C/p1.c",
"provenance": "stackv2-0107.json.gz:92583",
"repo_name": "rishabh-mitra/ncstate_ece566_spring2021",
"revision_date": "2021-04-13T13:39:06",
"revision_id": "2ee98bb19655a6f11d00c57e6e5d6274e3002e31",
"snapshot_id": "1078948aae3938eb09ebdfcc26672044c2201acb",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/rishabh-mitra/ncstate_ece566_spring2021/2ee98bb19655a6f11d00c57e6e5d6274e3002e31/projects/p1/C/p1.c",
"visit_date": "2023-04-06T04:28:59.834522"
} | stackv2 | #include <stdio.h>
#include <unistd.h>
#include "llvm-c/Core.h"
#include "llvm-c/BitReader.h"
#include "llvm-c/BitWriter.h"
LLVMModuleRef parseP1File(const char* InputFilename);
int
main (int argc, char ** argv)
{
if (argc < 3) {
fprintf(stdout,"Usage: %s filein.p1 fileout.bc\n",argv[0]);
return 0;
}
// Remember command line strings
const char * InputFilename = strdup(argv[1]);
const char * OutputFilename = strdup(argv[2]);
// Do the work
LLVMModuleRef M = parseP1File(InputFilename);
// If successful, produce LLVM bitcode
if (M != NULL) // if we get a valid module back
{
// Write module to file
LLVMWriteBitcodeToFile(M,OutputFilename);
}
else
{
printf("Errors. No module produced.\n");
return 1;
}
return 0;
}
| 2.609375 | 3 |
2024-11-18T22:37:11.395077+00:00 | 2019-02-21T13:10:43 | 987d9c88cd0627cabea88430e43496d5eb186b53 | {
"blob_id": "987d9c88cd0627cabea88430e43496d5eb186b53",
"branch_name": "refs/heads/master",
"committer_date": "2019-02-21T13:10:43",
"content_id": "8920eb4675ddb81d8dccb0b245811af4d2f68472",
"detected_licenses": [
"MIT"
],
"directory_id": "90d8ec1a37d0005b6c83a1829c22590ed22cb512",
"extension": "c",
"filename": "demo1.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 81713297,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 114,
"license": "MIT",
"license_type": "permissive",
"path": "/c/modern_compiler_implementation_in_c/c_source/demo1.c",
"provenance": "stackv2-0107.json.gz:92712",
"repo_name": "masterfish2015/my_project",
"revision_date": "2019-02-21T13:10:43",
"revision_id": "dfd340ba142a1e3adaa9d93e6ba677d0da840276",
"snapshot_id": "bd2b605c40392128b7b876c70f8ffe1d3e23f098",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/masterfish2015/my_project/dfd340ba142a1e3adaa9d93e6ba677d0da840276/c/modern_compiler_implementation_in_c/c_source/demo1.c",
"visit_date": "2020-04-05T08:09:11.958443"
} | stackv2 | #include<stdio.h>
int main(void)
{
int a;
printf("input a number:");
scanf("%d", &a);
return 0;
} | 2.234375 | 2 |
2024-11-18T22:37:12.282182+00:00 | 2017-06-27T12:16:57 | 20238860b756a629b6dc1711a318a3c841e93e98 | {
"blob_id": "20238860b756a629b6dc1711a318a3c841e93e98",
"branch_name": "refs/heads/master",
"committer_date": "2017-06-27T12:16:57",
"content_id": "c591b40465320c4216e571f69e4c164f7ffeb7dd",
"detected_licenses": [
"MIT"
],
"directory_id": "a8c3f08635b78e18c310b7ac1070f2e27fa7b0ae",
"extension": "c",
"filename": "jsmn.c",
"fork_events_count": 0,
"gha_created_at": "2017-06-21T12:35:15",
"gha_event_created_at": "2017-06-21T12:35:15",
"gha_language": null,
"gha_license_id": null,
"github_id": 95002236,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 15116,
"license": "MIT",
"license_type": "permissive",
"path": "/jsmn.c",
"provenance": "stackv2-0107.json.gz:93358",
"repo_name": "machste/jsmn",
"revision_date": "2017-06-27T12:16:57",
"revision_id": "0cc85d62be49c171054751ef6885616ee9fab1d3",
"snapshot_id": "768894f450af9f7469f226a71c51f0be45dbe881",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/machste/jsmn/0cc85d62be49c171054751ef6885616ee9fab1d3/jsmn.c",
"visit_date": "2021-01-13T06:15:23.212564"
} | stackv2 | #include <string.h>
#include "jsmn.h"
/**
* Allocates a fresh unused token from the token pull.
*/
static jsmn_Token *jsmn_alloc_token(jsmn_Factory *factory, size_t len) {
int i;
jsmn_Token *tok;
if (factory->toknext + (len - 1) >= factory->tokslen) {
return NULL;
}
for (i = 0; i < len; i++) {
tok = factory->toks + factory->toknext++;
tok->type = JSMN_UNDEFINED;
tok->data = NULL;
tok->length = -1;
tok->size = 0;
tok->parent = -1;
}
return tok - (len - 1);
}
/**
* Fills token type and boundaries.
*/
static void jsmn_fill_token(jsmn_Token *token, jsmntype_t type, const char *js,
int start, int end) {
token->type = type;
token->data = js + start;
token->length = end - start;
token->size = 0;
}
void jsmn_factory_init(jsmn_Factory *factory, jsmn_Token *toks, size_t len) {
factory->toks = toks;
factory->tokslen = len;
factory->toknext = 0;
factory->toksuper = -1;
}
static jsmn_Token *jsmn_prepare_append(jsmn_Factory *factory, const char *name)
{
jsmn_Token *token;
int n_tokens = 1;
// Does the append going to be within a supertoken
if (factory->toksuper != -1) {
// If the append is with in a object a label token is needed.
if (factory->toks[factory->toksuper].type == JSMN_OBJECT) {
if (name == NULL) {
// Exit with an error, if no name for a label token is defined
return NULL;
}
// Two tokens have to be appended a label and the actual token
n_tokens = 2;
}
}
// Allocate the needed tokens
token = jsmn_alloc_token(factory, n_tokens);
if (token == NULL) {
return NULL;
}
// Increment the size of the supertoken
if (factory->toksuper != -1) {
factory->toks[factory->toksuper].size++;
}
// Append label token
if (n_tokens == 2) {
int toklabel = token - factory->toks;
token->type = JSMN_LABEL;
token->data = name;
token->length = strlen(name);
token->size = 1;
// The parent token of the label will be the current supertoken
token->parent = factory->toksuper;
// Jump the the actual token
token++;
// The parent of the actual token will be the label token
token->parent = toklabel;
} else if (factory->toksuper != -1) {
// Within an array, set the current supertoken as parent
token->parent = factory->toksuper;
} else {
// As root token, set the parent to -1
token->parent = -1;
}
return token;
}
static int jsmn_start_sequence(jsmn_Factory *factory, jsmntype_t type,
const char *name)
{
jsmn_Token *token;
// Prepare the token
token = jsmn_prepare_append(factory, name);
if (token == NULL) {
return JSMN_ERROR_FACTORY;
}
// Append object token
token->type = type;
factory->toksuper = token - factory->toks;
return factory->toknext;
}
static int jsmn_end_sequence(jsmn_Factory *factory, jsmntype_t type)
{
jsmn_Token *supertoken;
// Check wheter there is a sequence (object or array) to end
if (factory->toksuper == -1) {
return JSMN_ERROR_FACTORY;
}
supertoken = factory->toks + factory->toksuper;
// Check the type of the to be ended sequence
if (supertoken->type != type) {
return JSMN_ERROR_FACTORY;
}
if (supertoken->parent != -1) {
// Found an other supertoken
supertoken = factory->toks + supertoken->parent;
// At this state the current supertoken must be a label or an array ...
if (supertoken->type == JSMN_LABEL || supertoken->type == JSMN_ARRAY) {
// ... set the supertoken of the factory to the parent of the
// current supertoken ...
factory->toksuper = supertoken->parent;
} else {
// ... otherwise there must be an error.
return JSMN_ERROR_FACTORY;
}
} else {
// There is no supertoken -> end of root sequence
factory->toksuper = -1;
}
return factory->toknext;
}
int jsmn_start_object(jsmn_Factory *factory, const char *name)
{
return jsmn_start_sequence(factory, JSMN_OBJECT, name);
}
int jsmn_end_object(jsmn_Factory *factory)
{
return jsmn_end_sequence(factory, JSMN_OBJECT);
}
int jsmn_start_array(jsmn_Factory *factory, const char *name)
{
return jsmn_start_sequence(factory, JSMN_ARRAY, name);
}
int jsmn_end_array(jsmn_Factory *factory)
{
return jsmn_end_sequence(factory, JSMN_ARRAY);
}
static int jsmn_append_simple(jsmn_Factory *factory, jsmntype_t type,
const char *name, const char *value)
{
jsmn_Token *token;
// Prepare the token
token = jsmn_prepare_append(factory, name);
if (token == NULL) {
return JSMN_ERROR_FACTORY;
}
// Append the data to the string or primitive token
token->type = type;
token->data = value;
if (value != NULL) {
token->length = strlen(value);
}
return factory->toknext;
}
int jsmn_append_string(jsmn_Factory *factory, const char *name,
const char *value)
{
return jsmn_append_simple(factory, JSMN_STRING, name, value);
}
int jsmn_append_primitive(jsmn_Factory *factory, const char *name,
const char *value)
{
return jsmn_append_simple(factory, JSMN_PRIMITIVE, name, value);
}
int jsmn_dump(jsmn_Token *t, jsmn_write_handle_t cb) {
if (t->type == JSMN_PRIMITIVE) {
cb(t->data, t->length);
return 1;
} else if (t->type == JSMN_LABEL || t->type == JSMN_STRING) {
cb("\"", 1);
if (t->length > 0) {
cb(t->data, t->length);
}
cb("\":", t->type == JSMN_LABEL ? 2 : 1);
return 1;
} else if (t->type == JSMN_OBJECT) {
int i;
int j = 0;
cb("{", 1);
for (i = 0; i < t->size; i++) {
j += jsmn_dump(t + 1 + j, cb);
j += jsmn_dump(t + 1 + j, cb);
if (i < t->size - 1) {
cb(",", 1);
}
}
cb("}", 1);
return j + 1;
} else if (t->type == JSMN_ARRAY) {
int i;
int j = 0;
cb("[", 1);
for (i = 0; i < t->size; i++) {
j += jsmn_dump(t + 1 + j, cb);
if (i < t->size - 1) {
cb(",", 1);
}
}
cb("]", 1);
return j + 1;
}
return 0;
}
void jsmn_parser_init(jsmn_Parser *parser, jsmn_Token *toks, size_t len) {
jsmn_factory_init((jsmn_Factory *)parser, toks, len);
parser->js = NULL;
parser->pos = 0;
}
/**
* Fills next available token with JSON primitive.
*/
static int jsmn_parse_primitive(jsmn_Parser *parser, const char *js,
size_t len) {
jsmn_Token *token;
jsmn_Factory *factory = (jsmn_Factory *)parser;
int start = parser->pos;
for (; parser->pos < len && js[parser->pos] != '\0'; parser->pos++) {
switch (js[parser->pos]) {
// In strict mode primitive must be followed by "," or "}" or "]"
case '\t' : case '\r' : case '\n' : case ' ' :
case ',' : case ']' : case '}' :
goto found;
}
if (js[parser->pos] < 32 || js[parser->pos] >= 127) {
parser->pos = start;
return JSMN_ERROR_INVAL;
}
}
// In strict mode primitive must be followed by a comma/object/array
parser->pos = start;
return JSMN_ERROR_PART;
found:
if (factory->toks == NULL) {
parser->pos--;
return 0;
}
token = jsmn_alloc_token(factory, 1);
if (token == NULL) {
parser->pos = start;
return JSMN_ERROR_NOMEM;
}
jsmn_fill_token(token, JSMN_PRIMITIVE, js, start, parser->pos);
token->parent = factory->toksuper;
parser->pos--;
return 0;
}
/**
* Fills next token with JSON string.
*/
static int jsmn_parse_string(jsmn_Parser *parser, const char *js, size_t len) {
jsmn_Token *token;
jsmn_Factory *factory = (jsmn_Factory *)parser;
int start = parser->pos;
parser->pos++;
// Skip starting quote
for (; parser->pos < len && js[parser->pos] != '\0'; parser->pos++) {
char c = js[parser->pos];
// Quote: end of string
if (c == '\"') {
jsmntype_t type;
if (factory->toks == NULL) {
return 0;
}
token = jsmn_alloc_token(factory, 1);
if (token == NULL) {
parser->pos = start;
return JSMN_ERROR_NOMEM;
}
// Check wheter string is a label or an ordinary value
type = JSMN_STRING;
if (factory->toks[factory->toksuper].type == JSMN_OBJECT) {
type = JSMN_LABEL;
}
jsmn_fill_token(token, type, js, start+1, parser->pos);
token->parent = factory->toksuper;
return 0;
}
// Backslash: Quoted symbol expected
if (c == '\\' && parser->pos + 1 < len) {
int i;
parser->pos++;
switch (js[parser->pos]) {
// Allowed escaped symbols
case '\"': case '/' : case '\\' : case 'b' :
case 'f' : case 'r' : case 'n' : case 't' :
break;
// Allows escaped symbol \uXXXX
case 'u':
parser->pos++;
for(i = 0; i < 4 && parser->pos < len && js[parser->pos] != '\0'; i++) {
// If it isn't a hex character we have an error
if(!((js[parser->pos] >= 48 && js[parser->pos] <= 57) || /* 0-9 */
(js[parser->pos] >= 65 && js[parser->pos] <= 70) || /* A-F */
(js[parser->pos] >= 97 && js[parser->pos] <= 102))) { /* a-f */
parser->pos = start;
return JSMN_ERROR_INVAL;
}
parser->pos++;
}
parser->pos--;
break;
// Unexpected symbol
default:
parser->pos = start;
return JSMN_ERROR_INVAL;
}
}
}
parser->pos = start;
return JSMN_ERROR_PART;
}
int jsmn_parse(jsmn_Parser *parser, const char *js, size_t len) {
jsmn_Factory *factory = (jsmn_Factory *)parser;
jsmn_Token *token;
jsmn_Token *tokens = factory->toks;
int count = factory->toknext;
int r;
int i;
if (parser->js == NULL) {
parser->js = js;
} else if (parser->js != js) {
// JSON string has been realocated, re-calculate old data pointers
int offset = js - parser->js;
for (i = 0; i < count; i++) {
if (tokens[i].data != NULL) {
tokens[i].data += offset;
}
}
parser->js = js;
}
// Parse JSON string
for (; parser->pos < len && js[parser->pos] != '\0'; parser->pos++) {
char c;
jsmntype_t type;
c = js[parser->pos];
switch (c) {
case '{': case '[':
count++;
if (tokens == NULL) {
break;
}
token = jsmn_alloc_token(factory, 1);
if (token == NULL)
return JSMN_ERROR_NOMEM;
if (factory->toksuper != -1) {
tokens[factory->toksuper].size++;
token->parent = factory->toksuper;
}
token->type = (c == '{' ? JSMN_OBJECT : JSMN_ARRAY);
token->data = js + parser->pos;
factory->toksuper = factory->toknext - 1;
break;
case '}': case ']':
if (tokens == NULL)
break;
type = (c == '}' ? JSMN_OBJECT : JSMN_ARRAY);
if (factory->toknext < 1) {
return JSMN_ERROR_INVAL;
}
token = &tokens[factory->toknext - 1];
for (;;) {
if (token->data != NULL && token->length == -1) {
if (token->type != type) {
return JSMN_ERROR_INVAL;
}
token->length = parser->pos - (token->data - js) + 1;
factory->toksuper = token->parent;
break;
}
if (token->parent == -1) {
if(token->type != type || factory->toksuper == -1) {
return JSMN_ERROR_INVAL;
}
break;
}
token = &tokens[token->parent];
}
break;
case '\"':
r = jsmn_parse_string(parser, js, len);
if (r < 0) return r;
count++;
if (factory->toksuper != -1 && tokens != NULL)
tokens[factory->toksuper].size++;
break;
case '\t' : case '\r' : case '\n' : case ' ':
break;
case ':':
factory->toksuper = factory->toknext - 1;
break;
case ',':
if (tokens != NULL && factory->toksuper != -1 &&
tokens[factory->toksuper].type != JSMN_ARRAY &&
tokens[factory->toksuper].type != JSMN_OBJECT) {
factory->toksuper = tokens[factory->toksuper].parent;
}
break;
// In strict mode primitives are: numbers and booleans
case '-': case '0': case '1' : case '2': case '3' : case '4':
case '5': case '6': case '7' : case '8': case '9':
case 't': case 'f': case 'n' :
// And they must not be keys of the object
if (tokens != NULL && factory->toksuper != -1) {
jsmn_Token *t = &tokens[factory->toksuper];
if (t->type == JSMN_OBJECT ||
(t->type == JSMN_STRING && t->size != 0)) {
return JSMN_ERROR_INVAL;
}
}
r = jsmn_parse_primitive(parser, js, len);
if (r < 0) return r;
count++;
if (factory->toksuper != -1 && tokens != NULL)
tokens[factory->toksuper].size++;
break;
// Unexpected char in strict mode
default:
return JSMN_ERROR_INVAL;
}
}
if (tokens != NULL) {
for (i = factory->toknext - 1; i >= 0; i--) {
// Unmatched opened object or array
if (tokens[i].data != NULL && tokens[i].length == -1) {
return JSMN_ERROR_PART;
}
}
}
return count;
}
| 2.828125 | 3 |
2024-11-18T22:37:12.345874+00:00 | 2023-01-25T20:07:48 | fdeb25c227adf4846a3e7e43045d0521b73654dd | {
"blob_id": "fdeb25c227adf4846a3e7e43045d0521b73654dd",
"branch_name": "refs/heads/master",
"committer_date": "2023-01-25T20:07:48",
"content_id": "d22646e6192c51e734bde19b72a8ec1a646003fa",
"detected_licenses": [
"MIT"
],
"directory_id": "ebae7773b24abb35b17146b47bdbde6b369f8800",
"extension": "c",
"filename": "usercopytest.c",
"fork_events_count": 0,
"gha_created_at": "2019-08-26T02:55:26",
"gha_event_created_at": "2019-09-04T06:58:10",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 204383960,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2426,
"license": "MIT",
"license_type": "permissive",
"path": "/app/usercopytest/usercopytest.c",
"provenance": "stackv2-0107.json.gz:93487",
"repo_name": "projectceladon/trusty_lk_trusty",
"revision_date": "2023-01-25T20:07:48",
"revision_id": "92a2cc14b28508f9aee6ed2dc53b659bff6366d2",
"snapshot_id": "f6afd7acb5bedf40908ac8df6604d49e99f6d339",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/projectceladon/trusty_lk_trusty/92a2cc14b28508f9aee6ed2dc53b659bff6366d2/app/usercopytest/usercopytest.c",
"visit_date": "2023-02-12T16:53:06.286945"
} | stackv2 | /*
* Copyright (c) 2015, Google Inc. All rights reserved
*
* 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 <assert.h>
#include <kernel/usercopy.h>
#include <lk/init.h>
#include <stdio.h>
#include <string.h>
static void usercopy_test(uint level)
{
int ret;
char testbuf1[16];
char testbuf2[16];
memset(testbuf1, 0x11, sizeof(testbuf1));
memset(testbuf2, 0x22, sizeof(testbuf2));
ret = copy_to_user((user_addr_t)(uintptr_t)testbuf2, testbuf1, sizeof(testbuf1));
ASSERT(ret == ERR_FAULT);
ASSERT(testbuf1[0] == 0x11);
ASSERT(testbuf2[0] == 0x22);
memset(testbuf1, 0x11, sizeof(testbuf1));
memset(testbuf2, 0x22, sizeof(testbuf2));
ret = copy_from_user(testbuf1, (user_addr_t)(uintptr_t)testbuf2, sizeof(testbuf1) - 1);
ASSERT(ret == ERR_FAULT);
ASSERT(testbuf1[0] == 0x00);
ASSERT(testbuf1[sizeof(testbuf1) - 2] == 0x00);
ASSERT(testbuf1[sizeof(testbuf1) - 1] == 0x11);
ASSERT(testbuf2[0] == 0x22);
memset(testbuf1, 0x11, sizeof(testbuf1));
memset(testbuf2, 0x22, sizeof(testbuf2));
ret = strlcpy_from_user(testbuf1, (user_addr_t)(uintptr_t)testbuf2, sizeof(testbuf1) - 1);
ASSERT(ret == ERR_FAULT);
ASSERT(testbuf1[0] == 0x00);
ASSERT(testbuf1[sizeof(testbuf1) - 2] == 0x00);
ASSERT(testbuf1[sizeof(testbuf1) - 1] == 0x11);
ASSERT(testbuf2[0] == 0x22);
printf("PASSED - %s\n", __func__);
}
LK_INIT_HOOK(usercopy_test, usercopy_test, LK_INIT_LEVEL_APPS);
| 2.0625 | 2 |
2024-11-18T22:37:12.441335+00:00 | 2017-10-03T23:56:24 | c62267a33d0aad130e2ad7c49465bea5fc341626 | {
"blob_id": "c62267a33d0aad130e2ad7c49465bea5fc341626",
"branch_name": "refs/heads/master",
"committer_date": "2017-10-03T23:56:24",
"content_id": "7f6cc91e293a2b49feb2dcaa1259cb2773a1d261",
"detected_licenses": [
"MIT"
],
"directory_id": "d805cdb7b92ef8d9e1fcb385ac3c953b6b56af2b",
"extension": "h",
"filename": "pubnub_coreapi.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 75879729,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 27559,
"license": "MIT",
"license_type": "permissive",
"path": "/libs/c-core/core/pubnub_coreapi.h",
"provenance": "stackv2-0107.json.gz:93615",
"repo_name": "BCCH-ENT/odg-controller-cpp",
"revision_date": "2017-10-03T23:56:24",
"revision_id": "d4376b73b393851bf290072352ba9aa6d02e1a6e",
"snapshot_id": "830d85b4fbf63cbab388dba908be328773ea765e",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/BCCH-ENT/odg-controller-cpp/d4376b73b393851bf290072352ba9aa6d02e1a6e/libs/c-core/core/pubnub_coreapi.h",
"visit_date": "2020-06-10T20:45:13.201168"
} | stackv2 | /* -*- c-file-style:"stroustrup"; indent-tabs-mode: nil -*- */
#if !defined INC_PUBNUB_COREAPI
#define INC_PUBNUB_COREAPI
#include "pubnub_api_types.h"
#include <stdbool.h>
/** @file pubnub_coreapi.h
This is the "Core" API of the Pubnub client library.
It has the functions that are present in all variants and
platforms and have the same interface in all of them.
For the most part, they have the same implementation in
all of them, too.
*/
/** Append this to a name of the channel to form the name of its
"presence" channel. A "presence" channel is a pseudo-channel on
which notifications of presence changes of a channel are announced
(sent by the Pubnub network). These notifications are JSON objects
with the following keys:
- "action": the event that happened, can be "leave", "join", "timeout",
"state-change"
- "timestamp": the timestamp of the moment the event happened
- "uuid": ID of the user that the event pertains to
- "occupancy": current number of present users in the channel
There is no special support for these (pseudo) channels in our
Pubnub client. If you wish to receive presence events, simply
append this suffix to the name of the channel and subscribe to
that "combined" name. For example, to receive presence events on
channel "my_channel", subscribe to "my_channel-pnpres".
Actually, you can subscribe to both a "regular" channel and a
"presence" channel at the same time, and you'll receive both the
presence events (on the "presence channel") and the published
messages (on the "regular" channel).
*/
#define PUBNUB_PRESENCE_SUFFIX "-pnpres"
/** Initialize a given pubnub context @p p to the @p publish_key and @p
subscribe_key. You can customize other parameters of the context by
the configuration function calls below.
@note The @p publish_key and @p subscribe key are expected to be
valid (ASCIIZ string) pointers throughout the use of context @p p,
that is, until either you call pubnub_done(), or the otherwise
stop using it (like when the whole software/ firmware stops
working). So, the contents of these keys are not copied to the
Pubnub context @p p.
@pre Call this after TCP initialization.
@pre @p subscribe_key can't be NULL
@param p The Context to initialize (use pubnub_alloc() to
obtain it)
@param publish_key The string of the key to use when publishing
messages (if you don't want to publish, you can pass NULL)
@param subscribe_key The string of the key to use when subscribing
to messages
@return Returns the @p p context
*/
pubnub_t* pubnub_init(pubnub_t *p, const char *publish_key, const char *subscribe_key);
/** Set the UUID identification of PubNub client context @p p to @p
uuid. Pass NULL to unset.
@note The @p uuid is expected to be valid (ASCIIZ string) pointers
throughout the use of context @p p, that is, until either you call
pubnub_done() on @p p, or the otherwise stop using it (like when
the whole software/ firmware stops working). So, the contents of
the @p uuid string is not copied to the Pubnub context @p p. */
void pubnub_set_uuid(pubnub_t *p, const char *uuid);
/** Get the UUID identification of PubNub client context @p p.
After pubnub_init(), it will return `NULL` until you change it
to non-`NULL` via pubnub_set_uuid().
*/
char const *pubnub_uuid_get(pubnub_t *p);
/** Set the authentication information of PubNub client context @p
p. Pass NULL to unset.
@note The @p auth is expected to be valid (ASCIIZ string) pointers
throughout the use of context @p p, that is, until either you call
pubnub_done() on @p p, or the otherwise stop using it (like when
the whole software/ firmware stops working). So, the contents of
the auth string is not copied to the Pubnub context @p p. */
void pubnub_set_auth(pubnub_t *p, const char *auth);
/** Returns the current authentication information for the
context @p p.
After pubnub_init(), it will return `NULL` until you change it
to non-`NULL` via pubnub_set_auth().
*/
char const *pubnub_auth_get(pubnub_t *p);
/** Cancel an ongoing API transaction. The outcome of the transaction
in progress, if any, will be #PNR_CANCELLED. */
void pubnub_cancel(pubnub_t *p);
/** Publish the @p message (in JSON format) on @p p channel, using the
@p p context. This actually means "initiate a publish
transaction".
You can't publish if a transaction is in progress in @p p context.
If transaction is not successful (@c PNR_PUBLISH_FAILED), you can
get the string describing the reason for failure by calling
pubnub_last_publish_result().
Keep in mind that the time token from the publish operation
response is _not_ parsed by the library, just relayed to the
user. Only time-tokens from the subscribe operation are parsed
by the library.
Also, for all error codes known at the time of this writing, the
HTTP error will be set also, so the result of the Pubnub operation
will not be @c PNR_OK (but you will still be able to get the
result code and the description).
@param p The pubnub context. Can't be NULL
@param channel The string with the channel (or comma-delimited list
of channels) to publish to.
@param message The message to publish, expected to be in JSON format
@return #PNR_STARTED on success, an error otherwise
*/
enum pubnub_res pubnub_publish(pubnub_t *p, const char *channel, const char *message);
/** Publish the @p message (in JSON format) on @p p channel, using the
@p p context, utilizing the v2 API. This actually means "initiate
a publish transaction".
Basically, this is an extension to the pubnub_publish() (v1),
with some additional options.
You can't publish if a transaction is in progress in @p p context.
@param p The pubnub context. Can't be NULL
@param channel The string with the channel (or comma-delimited list
of channels) to publish to.
@param message The message to publish, expected to be in JSON format
@param store_in_history If `false`, message will not be stored in
history of the channel
@param eat_after_reading If `true`, message will not be stored for
delayed or repeated retrieval or display
@return #PNR_STARTED on success, an error otherwise
*/
enum pubnub_res pubnub_publishv2(pubnub_t *p, const char *channel, const char *message, bool store_in_history, bool eat_after_reading);
/** Returns a pointer to an arrived message or other element of the
response to an operation/transaction. Message(s) arrive on finish
of a subscribe operation or history operation, while for some
other operations this will give access to the whole response,
or the next element of the response. That is documented in
the function that starts the operation.
Subsequent call to this function will return the next message (if
any). All messages are from the channel(s) the last operation was
for.
@note Context doesn't keep track of the channel(s) you subscribed
to. This is a memory saving design decision, as most users won't
change the channel(s) they subscribe too.
@param p The Pubnub context. Can't be NULL.
@return Pointer to the message, NULL on error
@see pubnub_subscribe
*/
char const* pubnub_get(pubnub_t *p);
/** Returns a pointer to an fetched subscribe operation/transaction's
next channel. Each transaction may hold a list of channels, and
this functions provides a way to read them. Subsequent call to
this function will return the next channel (if any).
@note You don't have to read all (or any) of the channels before
you start a new transaction.
@param pb The Pubnub context. Can't be NULL.
@return Pointer to the channel, NULL on error
@see pubnub_subscribe
@see pubnub_get
*/
char const *pubnub_get_channel(pubnub_t *pb);
/** Subscribe to @p channel and/or @p channel_group. This actually
means "initiate a subscribe operation/transaction". The outcome
will be retrieved by the "notification" API, which is different
for different platforms. There are two APIs that are widely
available - "sync" and "callback".
Messages published on @p channel and/or @p channel_group since the
last subscribe transaction will be fetched, unless this is the
first subscribe on this context after initialization or a serious
error. In that "first" case, this will just retrieve the current
time token, and that event is called "connect" in many pubnub
SDKs, but in C-core we don't treat it any different. For that
"first" case, you will receive a notification that subscribe has
finished OK, but there will be no messages in the reply.
The @p channel and @p channel_group strings may contain multiple
comma-separated channel (channel group) names, so only one call is
needed to fetch messages from multiple channels (channel groups).
If @p channel is NULL, then @p channel_group cannot be NULL and
you will subscribe only to the channel group(s). It goes both
ways: if @p channel_group is NULL, then @p channel cannot be NULL
and you will subscribe only to the channel(s).
You can't subscribe if a transaction is in progress on the context.
Also, you can't subscribe if there are unread messages in the
context (you read messages with pubnub_get()).
@param p The pubnub context. Can't be NULL
@param channel The string with the channel name (or comma-delimited list
of channel names) to subscribe to.
@param channel_group The string with the channel group name (or
comma-delimited list of channel group names) to subscribe to.
@return #PNR_STARTED on success, an error otherwise
@see pubnub_get
*/
enum pubnub_res pubnub_subscribe(pubnub_t *p, const char *channel, const char *channel_group);
/** Leave the @p channel. This actually means "initiate a leave
transaction". You should leave channel(s) when you want to
subscribe to another in the same context to avoid loosing
messages. Also, it is useful for tracking presence.
You can't leave if a transaction is in progress on the context.
@param p The Pubnub context. Can't be NULL.
@param channel The string with the channel name (or
comma-delimited list of channel names) to leave from.
@param channel_group The string with the channel group name (or
comma-delimited list of channel group names) to leave from.
@return #PNR_STARTED on success, an error otherwise
*/
enum pubnub_res pubnub_leave(pubnub_t *p, const char *channel, const char *channel_group);
/** Get the current Pubnub time token . This actually means "initiate
a time transaction". Since time token is in the response to most
Pubnub REST API calls, this is reserved mostly when you want to
get a high-quality seed for a random number generator, or some
such thing.
If transaction is successful, the gotten time will be the only
message you can get with pubnub_get(). It will be a (large) JSON
integer.
You can't get time if a transaction is in progress on the context.
@param p The Pubnub context. Can't be NULL.
@return #PNR_STARTED on success, an error otherwise
*/
enum pubnub_res pubnub_time(pubnub_t *p);
/** Get the message history for the @p channel. This actually
means "initiate a history transaction/operation".
If transaction is successful, the gotten messages will be
available via the pubnub_get(). Using pubnub_get() will give
you exactly three messages (or, rather, elements). The first will
be a JSON array of gotten messages, and the second and third will be
the timestamps of the first and the last message from that array.
Also, if you select to @c include_token, then the JSON array
you get will not be a simple array of gotten messages, but
rather an array of JSON objects, having keys `message` with
value the actual message, and `timetoken` with the time token
of that particular message.
You can't get history if a transaction is in progress on the context.
@param p The Pubnub context. Can't be NULL.
@param channel The string with the channel name to get message
history for. This _can't_ be a comma separated list of channels.
@param count Maximum number of messages to get. If there are less
than this available on the @c channel, you'll get less, but you
can't get more.
@param include_token If true, include the time token for every
gotten message
@return #PNR_STARTED on success, an error otherwise
*/
enum pubnub_res pubnub_history(pubnub_t *p, const char *channel, unsigned count, bool include_token);
/** Inform Pubnub that we're still working on @p channel and/or @p
channel_group. This actually means "initiate a heartbeat
transaction". It can be thought of as an update against the
"presence database".
If transaction is successful, the response will be a available
via pubnub_get() as one message, a JSON object. Following keys
are always present:
- "status": the HTTP status of the operation (200 OK, 40x error, etc.)
- "message": the string/message describing the status ("OK"...)
- "service": should be "Presence"
If @p channel is NULL, then @p channel_group cannot be NULL and
you will subscribe only to the channel group(s). It goes both ways:
if @p channel_group is NULL, then @p channel cannot be NULL and
you will subscribe only to the channel(s).
You can't get list of currently present users if a transaction is
in progress on the context.
@param p The Pubnub context. Can't be NULL.
@param channel The string with the channel name (or
comma-delimited list of channel names) to get presence info for.
@param channel_group The string with the channel name (or
comma-delimited list of channel group names) to get presence info for.
@return #PNR_STARTED on success, an error otherwise
*/
enum pubnub_res pubnub_heartbeat(pubnub_t *p, const char* channel, const char* channel_group);
/** Get the currently present users on a @p channel and/or @p
channel_group. This actually means "initiate a here_now
transaction". It can be thought of as a query against the
"presence database".
If transaction is successful, the response will be a available
via pubnub_get() as one message, a JSON object. Following keys
are always present:
- "status": the HTTP status of the operation (200 OK, 40x error, etc.)
- "message": the string/message describing the status ("OK"...)
- "service": should be "Presence"
If doing a query on a single channel, following keys are present:
- "uuids": an array of UUIDs of currently present users
- "occupancy": the number of currently present users in the channel
If doing a query on more channels, a key "payload" is present,
which is a JSON object whose keys are:
- "channels": a JSON object with keys being the names of the
channels and their values JSON objects with keys "uuids" and
"occupancy" with the meaning the same as for query on a single
channel
- "total_channels": the number of channels for which the
presence is given (in "payload")
- "total_occupancy": total number of users present in all channels
If @p channel is NULL, then @p channel_group cannot be NULL and
you will subscribe only to the channel group(s). It goes both ways:
if @p channel_group is NULL, then @p channel cannot be NULL and
you will subscribe only to the channel(s).
You can't get list of currently present users if a transaction is
in progress on the context.
@param p The Pubnub context. Can't be NULL.
@param channel The string with the channel name (or
comma-delimited list of channel names) to get presence info for.
@param channel_group The string with the channel name (or
comma-delimited list of channel group names) to get presence info for.
@return #PNR_STARTED on success, an error otherwise
*/
enum pubnub_res pubnub_here_now(pubnub_t *p, const char *channel, const char *channel_group);
/** Get the currently present users on all channel. This actually
means "initiate a global here_now transaction". It can be thought
of as a query against the "presence database".
If transaction is successful, the response will be the same
as for "multi-channel" response for pubnub_here_now(), if
we queried against all currently available channels.
You can't get list of currently present users if a transaction is
in progress on the context.
@param p The Pubnub context. Can't be NULL.
@return #PNR_STARTED on success, an error otherwise
*/
enum pubnub_res pubnub_global_here_now(pubnub_t *p);
/** Get the currently present users on a @p channel and/or @p
channel_group. This actually means "initiate a here_now
transaction". It can be thought of as a query against the
"presence database".
If transaction is successful, the response will be a available
via pubnub_get() as one message, a JSON object with keys:
- "status": the HTTP status of the operation (200 OK, 40x error, etc.)
- "message": the string/message describing the status ("OK"...)
- "service": should be "Presence"
- "payload": JSON object with a key "channels" which is an
array of channels this user is present in
You can't get channel presence for the user if a transaction is
in progress on the context.
@param p The Pubnub context. Can't be NULL.
@param uuid The UUID of the user to get the channel presence.
If NULL, the current UUID of the @c p context will be used.
@return #PNR_STARTED on success, an error otherwise
*/
enum pubnub_res pubnub_where_now(pubnub_t *p, const char *uuid);
/** Sets some state for the @p channel and/or @channel_group for a
user, identified by @p uuid. This actually means "initiate a set
state transaction". It can be thought of as an update against the
"presence database".
"State" has to be a JSON object (IOW, several "key-value" pairs).
If transaction is successful, the response will be a available
via pubnub_get() as one message, a JSON object with following keys:
- "status": the HTTP status of the operation (200 OK, 40x error, etc.)
- "message": the string/message describing the status ("OK"...)
- "service": should be "Presence"
- "payload" the state
This will set the same state to all channels identified by
@p channel and @p channel_group.
If @p channel is NULL, then @p channel_group cannot be NULL and
you will set state only to the channel group(s). It goes both
ways: if @p channel_group is NULL, then @p channel cannot be NULL
and you will set state only to the channel(s).
You can't set state of channels if a transaction is in progress on
the context.
@param p The Pubnub context. Can't be NULL.
@param channel The string with the channel name (or
comma-delimited list of channel names) to set state for.
@param channel_group The string with the channel name (or
comma-delimited list of channel group names) to set state for.
@param uuid The UUID of the user for which to set state for.
If NULL, the current UUID of the @c p context will be used.
@param state Has to be a JSON object
@return #PNR_STARTED on success, an error otherwise
*/
enum pubnub_res pubnub_set_state(pubnub_t *p, char const *channel, char const *channel_group, const char *uuid, char const *state);
/** Gets some state for the @p channel and/or @p channel_group for a
user, identified by @p uuid. This actually means "initiate a get
state transaction". It can be thought of as a query against the
"presence database".
If transaction is successful, the response will be a available
via pubnub_get() as one message, a JSON object with following keys:
- "status": the HTTP status of the operation (200 OK, 40x error, etc.)
- "message": the string/message describing the status ("OK"...)
- "service": should be "Presence"
- "payload": if querying against one channel the gotten state
(a JSON object), otherwise a JSON object with the key "channels"
whose value is a JSON object with keys the name of the channels
and their respective values JSON objects of the gotten state
If @p channel is NULL, then @p channel_group cannot be NULL and
you will get state only for the channel group(s). It goes both
ways: if @p channel_group is NULL, then @p channel cannot be NULL
and you will get state only for the channel(s).
You can't get state of channel(s) if a transaction is in progress
on the context.
@param p The Pubnub context. Can't be NULL.
@param channel The string with the channel name (or
comma-delimited list of channel names) to get state from.
@param channel_group The string with the channel name (or
comma-delimited list of channel group names) to get state from.
@param uuid The UUID of the user for which to get state for.
If NULL, the current UUID of the @p p context will be used.
@return #PNR_STARTED on success, an error otherwise
*/
enum pubnub_res pubnub_state_get(pubnub_t *p, char const *channel, char const *channel_group, const char *uuid);
/** Removes a @p channel_group and all its channels. This actually
means "initiate a remove_channel_group transaction". It can be
thought of as an update against the "channel group database".
If transaction is successful, the response will be a available via
pubnub_get_channel() as one "channel", a JSON object with keys:
- "service": should be "channel-registry"
- "status": the HTTP status of the operation (200 OK, 40x error, etc.)
- "error": true on error, false on success
- "message": the string/message describing the status ("OK"...)
You can't remove a channel group if a transaction is in progress
on the context.
@param p The Pubnub context. Can't be NULL.
@param channel_group The channel group to remove
@return #PNR_STARTED on success, an error otherwise
*/
enum pubnub_res pubnub_remove_channel_group(pubnub_t *p, char const *channel_group);
/** Removes a @p channel from the @p channel_group . This actually
means "initiate a remove_channel_from_channel_group
transaction". It can be thought of as an update against the
"channel group database".
You can't remove the last channel from a channel group. To do
that, remove the channel group itself.
If transaction is successful, the response will be a available via
pubnub_get_channel() as one "channel", a JSON object with keys:
- "service": should be "channel-registry"
- "status": the HTTP status of the operation (200 OK, 40x error, etc.)
- "error": true on error, false on success
- "message": the string/message describing the status ("OK"...)
You can't remove a channel from a channel group if a transaction
is in progress on the context.
@param p The Pubnub context. Can't be NULL.
@param channel_group The channel to remove
@param channel_group The channel group to remove from
@return #PNR_STARTED on success, an error otherwise
*/
enum pubnub_res pubnub_remove_channel_from_group(pubnub_t *p, char const *channel, char const *channel_group);
/** Adds a @p channel to the @p channel_group . This actually means
"initiate a add_channel_to_channel_group transaction". It can be
thought of as an update against the "channel group database".
If the channel group doesn't exist, this implicitly adds (creates)
it.
If transaction is successful, the response will be a available
via pubnub_get_channel() as one "channel", a JSON object with keys:
- "service": should be "channel-registry"
- "status": the HTTP status of the operation (200 OK, 40x error, etc.)
- "error": true on error, false on success
- "message": the string/message describing the status ("OK"...)
You can't add a channel to a channel group if a transaction
is in progress on the context.
@param p The Pubnub context. Can't be NULL.
@param channel The channel to add
@param channel_group The channel group to add to
@return #PNR_STARTED on success, an error otherwise
*/
enum pubnub_res pubnub_add_channel_to_group(pubnub_t *p, char const *channel, char const *channel_group);
/** Lists all channels of a @p channel_group. This actually
means "initiate a list_channel_group transaction". It can be
thought of as a query against the "channel group database".
If transaction is successful, the response will be a available via
pubnub_get_channel() as one "channel", a JSON object with keys:
- "service": should be "channel-registry"
- "status": the HTTP status of the operation (200 OK, 40x error, etc.)
- "error": true on error, false on success
- "payload": JSON object with keys "group" with value the string
of the channel group name and "channels" with value a JSON array
of strings with names of the channels that belong to the group
You can't remove a channel group if a transaction is in progress
on the context.
@param p The Pubnub context. Can't be NULL.
@param channel_group The channel group to list
@return #PNR_STARTED on success, an error otherwise
*/
enum pubnub_res pubnub_list_channel_group(pubnub_t *p, char const *channel_group);
/** Returns the result of the last transaction in the @p p context.
This _may_ block if using blocking I/O. It will _not_ block if using
non-blocking I/O.
@see pubnub_set_blocking_io
@see pubnub_set_non_blocking_io
*/
enum pubnub_res pubnub_last_result(pubnub_t *p);
/** Returns the HTTP reply code of the last transaction in the @p p
* context. */
int pubnub_last_http_code(pubnub_t *p);
/** Returns the string of the result of the last `publish` transaction,
as returned from Pubnub. If the last transaction is not a publish,
or there is some other error, it returns NULL. If the Publish
was successfull, it will return "Sent", otherwise a description
of the error.
*/
char const *pubnub_last_publish_result(pubnub_t *p);
/** Returns the string of the last received time token on the
@c p context. After pubnub_init() this should be "0".
@param p Pubnub context to get the last received time token from
@return A read only string of the last received time token
*/
char const *pubnub_last_time_token(pubnub_t *p);
/** Gets the origin to be used for the context @p p.
If setting of the origin is not enabled, this will return
the default origin.
@param p Pubnub context to get the origin from
@return A read only string of origin used for context @p p
*/
char const *pubnub_get_origin(pubnub_t *p);
/** Sets the origin to be used for the context @p p. If setting of
the origin is not enabled, this will fail. It may also fail if it
detects an invalid origin, but NULL is not an invalid origin - it
resets the origin to default.
@param p Pubnub context to set the origin for
@param origin The origin to use for context @p p. If NULL,
the default origin will be set
@return 0: success, -1: fail
*/
int pubnub_origin_set(pubnub_t *p, char const *origin);
#endif /* defined INC_PUBNUB_COREAPI */
| 2.03125 | 2 |
2024-11-18T22:37:12.663151+00:00 | 2018-09-28T22:05:06 | 7dc40b905be462b6f1f4b8d522c65a03317685ba | {
"blob_id": "7dc40b905be462b6f1f4b8d522c65a03317685ba",
"branch_name": "refs/heads/master",
"committer_date": "2018-09-28T22:05:06",
"content_id": "2e57bfa67eb44681201c3c39a780adf512d68ae6",
"detected_licenses": [
"MIT"
],
"directory_id": "39b2abd0fb1f7649e88f2bac8f7c222e31369041",
"extension": "c",
"filename": "msgrpc_svc_main.c",
"fork_events_count": 0,
"gha_created_at": "2018-09-26T19:40:45",
"gha_event_created_at": "2018-09-28T20:37:32",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 150480894,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1222,
"license": "MIT",
"license_type": "permissive",
"path": "/projects/07.0_blinkenlight_api/rpc_example2_msg/msgrpc_svc_main.c",
"provenance": "stackv2-0107.json.gz:94005",
"repo_name": "slcasner/BlinkenBone",
"revision_date": "2018-09-28T22:05:06",
"revision_id": "b73d579657717a2422f87c4cd4bc658fccc743a0",
"snapshot_id": "760c616bb7d1ab642e62d10f9834f2195ea38dbf",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/slcasner/BlinkenBone/b73d579657717a2422f87c4cd4bc658fccc743a0/projects/07.0_blinkenlight_api/rpc_example2_msg/msgrpc_svc_main.c",
"visit_date": "2020-03-29T23:37:31.869099"
} | stackv2 | /*
* Please do not edit this file.
* It was generated using rpcgen.
*/
#include "msgrpc.h"
#include <stdio.h>
#include <stdlib.h>
#include <rpc/pmap_clnt.h>
#include <string.h>
#include <memory.h>
#include <sys/socket.h>
#include <netinet/in.h>
#ifndef SIG_PF
#define SIG_PF void(*)(int)
#endif
int
main (int argc, char **argv)
{
register SVCXPRT *transp;
// entry to server stub
void messageprog_1(struct svc_req *rqstp, register SVCXPRT *transp) ;
pmap_unset (MESSAGEPROG, MESSAGEVERS);
transp = svcudp_create(RPC_ANYSOCK);
if (transp == NULL) {
fprintf (stderr, "%s", "cannot create udp service.");
exit(1);
}
if (!svc_register(transp, MESSAGEPROG, MESSAGEVERS, messageprog_1, IPPROTO_UDP)) {
fprintf (stderr, "%s", "unable to register (MESSAGEPROG, MESSAGEVERS, udp).");
exit(1);
}
transp = svctcp_create(RPC_ANYSOCK, 0, 0);
if (transp == NULL) {
fprintf (stderr, "%s", "cannot create tcp service.");
exit(1);
}
if (!svc_register(transp, MESSAGEPROG, MESSAGEVERS, messageprog_1, IPPROTO_TCP)) {
fprintf (stderr, "%s", "unable to register (MESSAGEPROG, MESSAGEVERS, tcp).");
exit(1);
}
svc_run ();
fprintf (stderr, "%s", "svc_run returned");
exit (1);
/* NOTREACHED */
}
| 2.234375 | 2 |
2024-11-18T22:37:12.743105+00:00 | 2021-05-01T20:56:23 | 3a4839b7e3af70e3bbd429125dce81202d8b49af | {
"blob_id": "3a4839b7e3af70e3bbd429125dce81202d8b49af",
"branch_name": "refs/heads/master",
"committer_date": "2021-05-01T20:56:23",
"content_id": "e80ccb187ea2f7fe1b22c59d40e8ea332d67d44f",
"detected_licenses": [
"MIT"
],
"directory_id": "0e3c059a4e21a8a5066dba04117cb87cac61f389",
"extension": "c",
"filename": "00.c",
"fork_events_count": 39,
"gha_created_at": "2015-04-28T14:04:29",
"gha_event_created_at": "2020-10-02T04:11:43",
"gha_language": "Python",
"gha_license_id": "MIT",
"github_id": 34734087,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1302,
"license": "MIT",
"license_type": "permissive",
"path": "/2020_3/projeto2/inputs/00.c",
"provenance": "stackv2-0107.json.gz:94137",
"repo_name": "damorim/compilers-cin",
"revision_date": "2021-05-01T20:56:23",
"revision_id": "e2f3a18e4cded92276b9def254452910f28faa50",
"snapshot_id": "fdc8e23d052cb8e1eb2db0f1edc43b6c62f55ea1",
"src_encoding": "UTF-8",
"star_events_count": 26,
"url": "https://raw.githubusercontent.com/damorim/compilers-cin/e2f3a18e4cded92276b9def254452910f28faa50/2020_3/projeto2/inputs/00.c",
"visit_date": "2021-07-08T09:19:24.062071"
} | stackv2 | // Int Expression type checking Test
// Test: return int
// Should Pass
int square(int num1) {
return num1 * num1;
}
int fatorial(int n) {
if (n > 0)
return fatorial(n-1) * n;
else
return 1;
}
float fsquare(float val) {
return val * val;
}
void doing(float f, int ik) {
return f;
}
int main () {
// Test: int op int
// Should Pass
int num = 2;
num = 3 + 2;
num = num - 2;
num = square(num) * num;
num = num / 3;
num = 2 + 5 * 3 / 2 - num * 4 / 3;
int num2 = 0;
num2 += 20 * num - fatorial(square(2));
num2 -= num;
num2 /= 10 / 3 + 2*3;
num2 *= 3 + num2;
// Test: float = int
// Should Pass
float t = num2;
t = fatorial(4);
t = num2*3 + num/2 - 4;
t = num2 / num * 3;
// Test: int = float
// Emit Warning - Possible loss of information (converting float to int)
int f = 2.0;
f = num + (2 - t);
f = fsquare(5) * t;
int hello = 450 + 5.0;
hello += 10.5;
hello *= hello / 5.0;
// Test: func. parameter type
// Should Pass
int x = square(4);
int y = fatorial(5);
int z = x * y;
// Emit Warning - possible loss of information (expecting int, passed float)
x = square(2.0);
y = fatorial(t);
z = square(fsquare(2)/2);
// Test: var = VOID
// Emit Error
int k = doing(t, x);
float u = (doing(4, 2) + 4)*2;
uv = 1.0;
return doing(2.0, x);
} | 3.1875 | 3 |
2024-11-18T22:37:13.066494+00:00 | 2019-07-01T13:36:16 | acdcae1c98e1124b0341e9a1bf1bd814e9cd351b | {
"blob_id": "acdcae1c98e1124b0341e9a1bf1bd814e9cd351b",
"branch_name": "refs/heads/master",
"committer_date": "2019-07-01T13:36:16",
"content_id": "1f7ddc91d8525d2057401a09116366f1266dcde8",
"detected_licenses": [
"PostgreSQL"
],
"directory_id": "d0963a1c994156d73ba2ab911cf720444c6873d1",
"extension": "c",
"filename": "path_utils.c",
"fork_events_count": 0,
"gha_created_at": "2019-08-04T18:30:35",
"gha_event_created_at": "2019-08-04T18:30:35",
"gha_language": null,
"gha_license_id": "NOASSERTION",
"github_id": 200528054,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4589,
"license": "PostgreSQL",
"license_type": "permissive",
"path": "/path_utils.c",
"provenance": "stackv2-0107.json.gz:94526",
"repo_name": "parimarjan/aqo",
"revision_date": "2019-07-01T13:36:16",
"revision_id": "d54c6b66f2d88fceb3bbb338064ff78fb8ba683a",
"snapshot_id": "948b43b39f0f14ba7be207794b18489e31d44209",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/parimarjan/aqo/d54c6b66f2d88fceb3bbb338064ff78fb8ba683a/path_utils.c",
"visit_date": "2020-06-29T11:54:16.149346"
} | stackv2 | #include "aqo.h"
#include "optimizer/optimizer.h"
/*****************************************************************************
*
* EXTRACTING PATH INFORMATION UTILITIES
*
*****************************************************************************/
/*
* Returns list of marginal selectivities using as an arguments for each clause
* (root, clause, 0, jointype, NULL).
* That is not quite correct for parameterized baserel and foreign key join
* cases, but nevertheless that is bearable.
*/
List *
get_selectivities(PlannerInfo *root,
List *clauses,
int varRelids,
JoinType jointype,
SpecialJoinInfo *sjinfo)
{
List *res = NIL;
ListCell *l;
double *elem;
foreach(l, clauses)
{
elem = palloc(sizeof(*elem));
*elem = clause_selectivity(root, lfirst(l), varRelids,
jointype, sjinfo);
res = lappend(res, elem);
}
return res;
}
/*
* Transforms given relids from path optimization stage format to list of
* an absolute (independent on query optimization context) relids.
*/
List *
get_list_of_relids(PlannerInfo *root, Relids relids)
{
int i;
RangeTblEntry *entry;
List *l = NIL;
if (relids == NULL)
return NIL;
i = -1;
while ((i = bms_next_member(relids, i)) >= 0)
{
entry = planner_rt_fetch(i, root);
l = lappend_int(l, entry->relid);
}
return l;
}
/*
* For given path returns the list of all clauses used in it.
* Also returns selectivities for the clauses throw the selectivities variable.
* Both clauses and selectivities returned lists are copies and therefore
* may be modified without corruption of the input data.
*/
List *
get_path_clauses(Path *path, PlannerInfo *root, List **selectivities)
{
List *inner;
List *inner_sel = NIL;
List *outer;
List *outer_sel = NIL;
List *cur;
List *cur_sel = NIL;
Assert(selectivities != NULL);
*selectivities = NIL;
if (path == NULL)
return NIL;
switch (path->type)
{
case T_NestPath:
case T_MergePath:
case T_HashPath:
cur = ((JoinPath *) path)->joinrestrictinfo;
/* Not quite correct to avoid sjinfo, but we believe in caching */
cur_sel = get_selectivities(root, cur, 0,
((JoinPath *) path)->jointype,
NULL);
outer = get_path_clauses(((JoinPath *) path)->outerjoinpath, root,
&outer_sel);
inner = get_path_clauses(((JoinPath *) path)->innerjoinpath, root,
&inner_sel);
*selectivities = list_concat(cur_sel,
list_concat(outer_sel, inner_sel));
return list_concat(list_copy(cur), list_concat(outer, inner));
break;
case T_UniquePath:
return get_path_clauses(((UniquePath *) path)->subpath, root,
selectivities);
break;
case T_GatherPath:
return get_path_clauses(((GatherPath *) path)->subpath, root,
selectivities);
break;
case T_MaterialPath:
return get_path_clauses(((MaterialPath *) path)->subpath, root,
selectivities);
break;
case T_ProjectionPath:
return get_path_clauses(((ProjectionPath *) path)->subpath, root,
selectivities);
break;
case T_SortPath:
return get_path_clauses(((SortPath *) path)->subpath, root,
selectivities);
break;
case T_GroupPath:
return get_path_clauses(((GroupPath *) path)->subpath, root,
selectivities);
break;
case T_UpperUniquePath:
return get_path_clauses(((UpperUniquePath *) path)->subpath, root,
selectivities);
break;
case T_AggPath:
return get_path_clauses(((AggPath *) path)->subpath, root,
selectivities);
break;
case T_GroupingSetsPath:
return get_path_clauses(((GroupingSetsPath *) path)->subpath, root,
selectivities);
break;
case T_WindowAggPath:
return get_path_clauses(((WindowAggPath *) path)->subpath, root,
selectivities);
break;
case T_SetOpPath:
return get_path_clauses(((SetOpPath *) path)->subpath, root,
selectivities);
break;
case T_LockRowsPath:
return get_path_clauses(((LockRowsPath *) path)->subpath, root,
selectivities);
break;
case T_LimitPath:
return get_path_clauses(((LimitPath *) path)->subpath, root,
selectivities);
break;
default:
cur = list_concat(list_copy(path->parent->baserestrictinfo),
path->param_info ?
list_copy(path->param_info->ppi_clauses) : NIL);
if (path->param_info)
cur_sel = get_selectivities(root, cur, path->parent->relid,
JOIN_INNER, NULL);
else
cur_sel = get_selectivities(root, cur, 0, JOIN_INNER, NULL);
*selectivities = cur_sel;
return cur;
break;
}
}
| 2.109375 | 2 |
2024-11-18T22:37:13.809633+00:00 | 2021-07-07T00:17:05 | 17d60db58ded027bbc48f5aec45b1e96f624866a | {
"blob_id": "17d60db58ded027bbc48f5aec45b1e96f624866a",
"branch_name": "refs/heads/master",
"committer_date": "2021-07-07T00:17:05",
"content_id": "1b8f58729a3c843c382210f979a351dbe6512a9d",
"detected_licenses": [
"MIT"
],
"directory_id": "79d4cf83c5e566ce5eee785a7045cacf0396f439",
"extension": "c",
"filename": "reptyr.c",
"fork_events_count": 0,
"gha_created_at": "2019-02-28T03:07:45",
"gha_event_created_at": "2023-01-06T00:09:05",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 173031542,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 8994,
"license": "MIT",
"license_type": "permissive",
"path": "/reptyr.c",
"provenance": "stackv2-0107.json.gz:95043",
"repo_name": "cypher386/reptyr",
"revision_date": "2021-07-07T00:17:05",
"revision_id": "af976129edc5280e230132b7d030ba0fbac6699f",
"snapshot_id": "55da00558ad3d1ee29fbdb311dd7df05c13094d6",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/cypher386/reptyr/af976129edc5280e230132b7d030ba0fbac6699f/reptyr.c",
"visit_date": "2023-01-09T20:39:52.372321"
} | stackv2 | /*
* Copyright (C) 2011 by Nelson Elhage
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/select.h>
#include <sys/ioctl.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <stdarg.h>
#include <termios.h>
#include <signal.h>
#include "reptyr.h"
#include "reallocarray.h"
#include "platform/platform.h"
static int verbose = 0;
void _debug(const char *pfx, const char *msg, va_list ap) {
if (pfx)
fprintf(stderr, "%s", pfx);
vfprintf(stderr, msg, ap);
fprintf(stderr, "\n");
}
void die(const char *msg, ...) {
va_list ap;
va_start(ap, msg);
_debug("[!] ", msg, ap);
va_end(ap);
exit(1);
}
void debug(const char *msg, ...) {
va_list ap;
if (!verbose)
return;
va_start(ap, msg);
_debug("[+] ", msg, ap);
va_end(ap);
}
void error(const char *msg, ...) {
va_list ap;
va_start(ap, msg);
_debug("[-] ", msg, ap);
va_end(ap);
}
void setup_raw(struct termios *save) {
struct termios set;
if (tcgetattr(0, save) < 0) {
fprintf(stderr, "Unable to read terminal attributes: %m");
return;
}
set = *save;
cfmakeraw(&set);
if (tcsetattr(0, TCSANOW, &set) < 0)
die("Unable to set terminal attributes: %m");
}
void resize_pty(int pty) {
struct winsize sz;
if (ioctl(0, TIOCGWINSZ, &sz) < 0) {
// provide fake size to workaround some problems
struct winsize defaultsize = {30, 80, 640, 480};
if (ioctl(pty, TIOCSWINSZ, &defaultsize) < 0) {
fprintf(stderr, "Cannot set terminal size\n");
}
return;
}
ioctl(pty, TIOCSWINSZ, &sz);
}
int writeall(int fd, const void *buf, ssize_t count) {
ssize_t rv;
while (count > 0) {
rv = write(fd, buf, count);
if (rv < 0) {
if (errno == EINTR)
continue;
return rv;
}
count -= rv;
buf += rv;
}
return 0;
}
volatile sig_atomic_t winch_happened = 0;
void do_winch(int signal) {
winch_happened = 1;
}
void do_proxy(int pty) {
char buf[4096];
ssize_t count;
fd_set set;
sigset_t mask;
sigset_t select_mask;
struct sigaction sa;
// Block WINCH while we're outside the select, but unblock it
// while we're inside:
sigemptyset(&mask);
sigaddset(&mask, SIGWINCH);
if (sigprocmask(SIG_BLOCK, &mask, NULL) == -1) {
fprintf(stderr, "sigprocmask: %m");
return;
}
sa.sa_handler = do_winch;
sa.sa_flags = 0;
sigemptyset(&sa.sa_mask);
sigaction(SIGWINCH, &sa, NULL);
resize_pty(pty);
while (1) {
if (winch_happened) {
winch_happened = 0;
resize_pty(pty);
}
FD_ZERO(&set);
FD_SET(0, &set);
FD_SET(pty, &set);
sigemptyset(&select_mask);
if (pselect(pty + 1, &set, NULL, NULL, NULL, &select_mask) < 0) {
if (errno == EINTR)
continue;
fprintf(stderr, "select: %m");
return;
}
if (FD_ISSET(0, &set)) {
count = read(0, buf, sizeof buf);
if (count < 0)
return;
writeall(pty, buf, count);
}
if (FD_ISSET(pty, &set)) {
count = read(pty, buf, sizeof buf);
if (count <= 0)
return;
writeall(1, buf, count);
}
}
}
void usage(char *me) {
fprintf(stderr, "Usage: %s [-s] PID\n", me);
fprintf(stderr, " %s -l|-L [COMMAND [ARGS]]\n", me);
fprintf(stderr, " -l Create a new pty pair and print the name of the slave.\n");
fprintf(stderr, " if there are command-line arguments after -l\n");
fprintf(stderr, " they are executed with REPTYR_PTY set to path of pty.\n");
fprintf(stderr, " -L Like '-l', but also redirect the child's stdio to the slave.\n");
fprintf(stderr, " -s Attach fds 0-2 on the target, even if it is not attached to a tty.\n");
fprintf(stderr, " -T Steal the entire terminal session of the target.\n");
fprintf(stderr, " [experimental] May be more reliable, and will attach all\n");
fprintf(stderr, " processes running on the terminal.\n");
fprintf(stderr, " -h Print this help message and exit.\n");
fprintf(stderr, " -v Print the version number and exit.\n");
fprintf(stderr, " -V Print verbose debug output.\n");
}
int main(int argc, char **argv) {
struct termios saved_termios;
int pty;
int opt;
int err;
int do_attach = 1;
int force_stdio = 0;
int do_steal = 0;
int unattached_script_redirection = 0;
while ((opt = getopt(argc, argv, "hlLsTvV")) != -1) {
switch (opt) {
case 'h':
usage(argv[0]);
return 0;
case 'l':
do_attach = 0;
break;
case 'L':
do_attach = 0;
unattached_script_redirection = 1;
break;
case 's':
force_stdio = 1;
break;
case 'T':
do_steal = 1;
break;
case 'v':
printf("This is reptyr version %s.\n", REPTYR_VERSION);
printf(" by Nelson Elhage <nelhage@nelhage.com>\n");
printf("http://github.com/nelhage/reptyr/\n");
return 0;
case 'V':
verbose = 1;
break;
default:
usage(argv[0]);
return 1;
}
if (opt == 'l' || opt == 'L') break; // the rest is a command line
}
if (do_attach && optind >= argc) {
fprintf(stderr, "%s: No pid specified to attach\n", argv[0]);
usage(argv[0]);
return 1;
}
if (!do_steal) {
if ((pty = get_pt()) < 0)
die("Unable to allocate a new pseudo-terminal: %m");
if (unlockpt(pty) < 0)
die("Unable to unlockpt: %m");
if (grantpt(pty) < 0)
die("Unable to grantpt: %m");
}
if (do_attach) {
char *endptr = NULL;
errno = 0;
long t = strtol(argv[optind], &endptr, 10);
if (errno == ERANGE)
die("Invalid pid: %m");
if (*endptr)
die("Invalid pid: must be integer");
/* check for overflow/underflow */
pid_t child = (pid_t)t;
if (child < t || t < 1) /* pids can't be < 1, so no *real* underflow check */
die("Invalid pid: %s", strerror(ERANGE));
if (do_steal) {
err = steal_pty(child, &pty);
} else {
err = attach_child(child, ptsname(pty), force_stdio);
}
if (err) {
fprintf(stderr, "Unable to attach to pid %d: %s\n", child, strerror(err));
if (err == EPERM) {
check_ptrace_scope();
}
return 1;
}
} else {
printf("Opened a new pty: %s\n", ptsname(pty));
fflush(stdout);
if (argc > 2) {
if (!fork()) {
setenv("REPTYR_PTY", ptsname(pty), 1);
if (unattached_script_redirection) {
int f;
setpgid(0, getppid());
setsid();
f = open(ptsname(pty), O_RDONLY, 0);
dup2(f, 0);
close(f);
f = open(ptsname(pty), O_WRONLY, 0);
dup2(f, 1);
dup2(f, 2);
close(f);
}
close(pty);
execvp(argv[2], argv + 2);
exit(1);
}
}
}
setup_raw(&saved_termios);
do_proxy(pty);
do {
errno = 0;
if (tcsetattr(0, TCSANOW, &saved_termios) && errno != EINTR)
die("Unable to tcsetattr: %m");
} while (errno == EINTR);
return 0;
}
| 2.03125 | 2 |
2024-11-18T22:37:14.057493+00:00 | 2021-02-01T17:27:12 | cb8be489a4eeed0ddf62424832f88960977faeda | {
"blob_id": "cb8be489a4eeed0ddf62424832f88960977faeda",
"branch_name": "refs/heads/master",
"committer_date": "2021-02-01T17:27:12",
"content_id": "774af8432a1f379a2dff834d15fcfd62d4d957c4",
"detected_licenses": [
"MIT"
],
"directory_id": "dc4df80060e74ad8c201c92bd20970b3823cc5ec",
"extension": "c",
"filename": "DC_Event.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": 3052,
"license": "MIT",
"license_type": "permissive",
"path": "/AURAE/AURAE/DC/DC_Event.c",
"provenance": "stackv2-0107.json.gz:95301",
"repo_name": "DreamcastNick/LMP3D",
"revision_date": "2021-02-01T17:27:12",
"revision_id": "d64b5dd2b8368c991e4c627ed6b72387ac721cb3",
"snapshot_id": "98412edae17428395a4c078b67eaad664923c1b1",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/DreamcastNick/LMP3D/d64b5dd2b8368c991e4c627ed6b72387ac721cb3/AURAE/AURAE/DC/DC_Event.c",
"visit_date": "2023-02-26T05:34:43.341474"
} | stackv2 |
#include <stdio.h>
#include <stdlib.h>
#ifdef DREAMCAST
#include <kos.h>
#include "AURAE/AURAE.h"
#include "AURAE/DC/DC.h"
#define PAD_R1 0x10000
#define PAD_L1 0x20000
void AURAE_Event_Update(AURAE_Event *event)
{
static int padbuf;
static int old_pad = 0;
static int new_pad;
static int end_pad;
int i;
for(i = 0;i < Button_Number;i++)
{
event->key[i] = 0;
}
maple_device_t *cont;
cont_state_t *state;
cont = maple_enum_type(0, MAPLE_FUNC_CONTROLLER);
state = (cont_state_t *)maple_dev_status(cont);
int padr = state->rtrig;
int padl = state->ltrig;
if(padr != 0) padr = 0x10000;
if(padl != 0) padl = 0x20000;
padbuf = state->buttons | padr | padl;
new_pad = padbuf & ~old_pad;
end_pad = (padbuf^old_pad)^new_pad;
old_pad = padbuf;
//DOWNW
if(padbuf & CONT_X)
event->key[Button_X] = AURAE_KEY_DOWNW;
if(padbuf & CONT_Y)
event->key[Button_Y] = AURAE_KEY_DOWNW;
if(padbuf & CONT_B)
event->key[Button_B] = AURAE_KEY_DOWNW;
if(padbuf & CONT_A)
event->key[Button_A] = AURAE_KEY_DOWNW;
if(padbuf & CONT_DPAD_LEFT)
event->key[Button_Left] = AURAE_KEY_DOWNW;
if(padbuf & CONT_DPAD_RIGHT)
event->key[Button_Right] = AURAE_KEY_DOWNW;
if(padbuf & CONT_DPAD_UP)
event->key[Button_Up] = AURAE_KEY_DOWNW;
if(padbuf & CONT_DPAD_DOWN)
event->key[Button_Down] = AURAE_KEY_DOWNW;
if(padbuf & PAD_R1)
event->key[Button_R1] = AURAE_KEY_DOWNW;
if(padbuf & PAD_L1)
event->key[Button_L1] = AURAE_KEY_DOWNW;
if(padbuf & CONT_START)
event->key[Button_Start] = AURAE_KEY_DOWNW;
//DOWN
if(new_pad & CONT_X)
event->key[Button_X] = AURAE_KEY_DOWN;
if(new_pad & CONT_Y)
event->key[Button_Y] = AURAE_KEY_DOWN;
if(new_pad & CONT_B)
event->key[Button_B] = AURAE_KEY_DOWN;
if(new_pad & CONT_A)
event->key[Button_A] = AURAE_KEY_DOWN;
if(new_pad & CONT_DPAD_LEFT)
event->key[Button_Left] = AURAE_KEY_DOWN;
if(new_pad & CONT_DPAD_RIGHT)
event->key[Button_Right] = AURAE_KEY_DOWN;
if(new_pad & CONT_DPAD_UP)
event->key[Button_Up] = AURAE_KEY_DOWN;
if(new_pad & CONT_DPAD_DOWN)
event->key[Button_Down] = AURAE_KEY_DOWN;
if(new_pad & PAD_R1)
event->key[Button_R1] = AURAE_KEY_DOWN;
if(new_pad & PAD_L1)
event->key[Button_L1] = AURAE_KEY_DOWN;
if(new_pad & CONT_START)
event->key[Button_Start] = AURAE_KEY_DOWN;
//UP
if(end_pad & CONT_X)
event->key[Button_X] = AURAE_KEY_UP;
if(end_pad & CONT_Y)
event->key[Button_Y] = AURAE_KEY_UP;
if(end_pad & CONT_B)
event->key[Button_B] = AURAE_KEY_UP;
if(end_pad & CONT_A)
event->key[Button_A] = AURAE_KEY_UP;
if(end_pad & CONT_DPAD_LEFT)
event->key[Button_Left] = AURAE_KEY_UP;
if(end_pad & CONT_DPAD_RIGHT)
event->key[Button_Right] = AURAE_KEY_UP;
if(end_pad & CONT_DPAD_UP)
event->key[Button_Up] = AURAE_KEY_UP;
if(end_pad & CONT_DPAD_DOWN)
event->key[Button_Down] = AURAE_KEY_UP;
if(end_pad & PAD_R1)
event->key[Button_R1] = AURAE_KEY_UP;
if(end_pad & PAD_L1)
event->key[Button_L1] = AURAE_KEY_UP;
if(end_pad & CONT_START)
event->key[Button_Start] = AURAE_KEY_UP;
}
#endif
| 2.390625 | 2 |
2024-11-18T22:37:14.233059+00:00 | 2017-03-12T18:51:39 | 583867221377e1b6181b578aee46f4080d900c5e | {
"blob_id": "583867221377e1b6181b578aee46f4080d900c5e",
"branch_name": "refs/heads/master",
"committer_date": "2017-03-12T18:51:39",
"content_id": "b21b60f6ab4ef1e451060278e7dc9dde27f00321",
"detected_licenses": [
"MIT"
],
"directory_id": "4a3f9ec0a4f095c8dd62f55770e03c3c2ec22f5e",
"extension": "h",
"filename": "lcd.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 84727714,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 7796,
"license": "MIT",
"license_type": "permissive",
"path": "/lcd.h",
"provenance": "stackv2-0107.json.gz:95557",
"repo_name": "jupi7er/STM32F4_Character_LCD",
"revision_date": "2017-03-12T18:51:39",
"revision_id": "27932e93e5032b345b936d2f238890e78d45ac53",
"snapshot_id": "405c5fffed8889cdc5a8a913a9576ecfeec7f209",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/jupi7er/STM32F4_Character_LCD/27932e93e5032b345b936d2f238890e78d45ac53/lcd.h",
"visit_date": "2020-05-22T21:49:29.843687"
} | stackv2 |
#ifndef lcd_INCLUDED_
#define lcd_INCLUDED_
#ifdef LCD_PORT_A
#define PIO_enable RCC->AHB1ENR |= 1<<0
#define PIO_SetOutput GPIOA->ODR
#define PIO_ClearOutput GPIOA->ODR
#define PIO_CfgOutput GPIOA->MODER
#endif
#ifdef LCD_PORT_B
#define PIO_enable RCC->AHB1ENR |= 1<<1
#define PIO_SetOutput GPIOB->ODR
#define PIO_ClearOutput GPIOB->ODR
#define PIO_CfgOutput GPIOB->MODER
#endif
#ifdef LCD_PORT_C
#define PIO_enable RCC->AHB1ENR |= 1<<2
#define PIO_SetOutput GPIOC->ODR
#define PIO_ClearOutput GPIOC->ODR
#define PIO_CfgOutput GPIOC->MODER
#endif
#ifdef LCD_PORT_D
#define PIO_enable RCC->AHB1ENR |= 1<<3
#define PIO_SetOutput GPIOD->ODR
#define PIO_ClearOutput GPIOD->ODR
#define PIO_CfgOutput GPIOD->MODER
#endif
#ifdef LCD_PORT_E
#define PIO_enable RCC->AHB1ENR |= 1<<4
#define PIO_SetOutput GPIOE->ODR
#define PIO_ClearOutput GPIOE->ODR
#define PIO_CfgOutput GPIOE->MODER
#endif
#define F_CPU 28000000
#define clcd_minDelay() cwait(F_CPU/10000)
#define clcd_Delay() cwait(F_CPU/1000)
void lcd_init(void);
void lcd_putchar(char ch);
void lcd_command(char cmd);
void lcd_gotoxy(char x, char y);
void lcd_clear(void);
void lcd_clear_line(char y);
void lcd_shift_left(char n);
void lcd_shift_right(char n);
void lcd_puts(int num);
void lcd_putsf(char* data);
void lcd_define_char(const char *pc,char char_code);
//=========================================================
void cwait (volatile int t) {
for (;t; t--);
}
// ============================================================================
void setD4567(char val)
{
PIO_ClearOutput &= ~((1<<LCD_DB4)|(1<<LCD_DB5)|(1<<LCD_DB6)|(1<<LCD_DB7));
if (val & 0x80)
PIO_SetOutput |=(1<<LCD_DB7);
if (val & 0x40)
PIO_SetOutput |=(1<<LCD_DB6);
if (val & 0x20)
PIO_SetOutput |=(1<<LCD_DB5);
if (val & 0x10)
PIO_SetOutput |=(1<<LCD_DB4);
}
// ============================================================================
void lcd_putchar(char ch)
{
PIO_SetOutput |=(1<<LCD_RS);
setD4567(ch);
PIO_SetOutput|=(1<<LCD_E);
clcd_minDelay();
PIO_ClearOutput &= ~(1<<LCD_E);
clcd_minDelay();
setD4567(ch<<4);
PIO_SetOutput|=(1<<LCD_E);
clcd_minDelay();
PIO_ClearOutput&= ~(1<<LCD_E);
clcd_Delay();
}
// ============================================================================
void lcd_command(char cmd) //Sends Command to LCD
{
PIO_ClearOutput&= ~(1<<LCD_RS);
setD4567(cmd);
PIO_SetOutput |=(1<<LCD_E);
clcd_minDelay();
PIO_ClearOutput&= ~(1<<LCD_E);
clcd_minDelay();
setD4567(cmd<<4);
PIO_SetOutput |=(1<<LCD_E);
clcd_minDelay();
PIO_ClearOutput &= ~(1<<LCD_E);
clcd_Delay();
}
// ============================================================================
void config_pin(int x)
{
switch (x)
{
case 0 :
{
PIO_CfgOutput &= 0xFFFFFFFC;
PIO_CfgOutput |= (0<<1 | 1<<0);
break;
}
case 1 :
{
PIO_CfgOutput &= 0xFFFFFFF3;
PIO_CfgOutput |= (0<<3 | 1<<2);
break;
}
case 2 :
{
PIO_CfgOutput &= 0xFFFFFFCF;
PIO_CfgOutput |= (0<<5 | 1<<4);
break;
}
case 3 :
{
PIO_CfgOutput &= 0xFFFFFF3F;
PIO_CfgOutput |= (0<<7 | 1<<6);
break;
}
case 4 :
{
PIO_CfgOutput &= 0xFFFFFCFF;
PIO_CfgOutput |= (0<<9 | 1<<8);
break;
}
case 5 :
{
PIO_CfgOutput &= 0xFFFFF3FF;
PIO_CfgOutput |= (0<<11 | 1<<10);
break;
}
case 6 :
{
PIO_CfgOutput &= 0xFFFFCFFF;
PIO_CfgOutput |= (0<<13 | 1<<12);
break;
}
case 7 :
{
PIO_CfgOutput &= 0xFFFF3FFF;
PIO_CfgOutput |= (0<<15 | 1<<14);
break;
}
case 8 :
{
PIO_CfgOutput &= 0xFFFCFFFF;
PIO_CfgOutput |= (0<<17 | 1<<16);
break;
}
case 9 :
{
PIO_CfgOutput &= 0xFFF3FFFF;
PIO_CfgOutput |= (0<<19 | 1<<18);
break;
}
case 10 :
{
PIO_CfgOutput &= 0xFFCFFFFF;
PIO_CfgOutput |= (0<<21 | 1<<20);
break;
}
case 11 :
{
PIO_CfgOutput &= 0xFF3FFFFF;
PIO_CfgOutput |= (0<<23 | 1<<22);
break;
}
case 12 :
{
PIO_CfgOutput &= 0xFCFFFFFF;
PIO_CfgOutput |= (0<<25 | 1<<24);
break;
}
case 13 :
{
PIO_CfgOutput &= 0xF3FFFFFF;
PIO_CfgOutput |= (0<<27 | 1<<26);
break;
}
case 14 :
{
PIO_CfgOutput &= 0xCFFFFFFF;
PIO_CfgOutput |= (0<<29 | 1<<28);
break;
}
case 15 :
{
PIO_CfgOutput &= 0x3FFFFFFF;
PIO_CfgOutput |= (0<<31 | 1<<30);
break;
}
}
}
void lcd_init()
{
PIO_enable;
config_pin(LCD_RS);
config_pin(LCD_E);
config_pin(LCD_DB4);
config_pin(LCD_DB5);
config_pin(LCD_DB6);
config_pin(LCD_DB7);
clcd_Delay();
setD4567(0);
setD4567((1<<5)|(1<<4));
PIO_SetOutput|=(1<<LCD_E);
clcd_minDelay();
PIO_ClearOutput &= ~(1<<LCD_E);
clcd_Delay();
setD4567((1<<5)|(1<<4));
PIO_SetOutput |=(1<<LCD_E);
clcd_minDelay();
PIO_ClearOutput &= ~(1<<LCD_E);
clcd_Delay();
setD4567(1<<5);
PIO_SetOutput |= (1<<LCD_E);
clcd_minDelay();
PIO_ClearOutput &= ~(1<<LCD_E);
clcd_Delay();
lcd_command(0x28);
lcd_command(0x0c);
clcd_Delay();
}
//=============================================================================
void lcd_gotoxy(char y, char x) //Cursor to X Y position
{
char DDRAMAddr;
x=x-1;
switch(y)
{
case 1: DDRAMAddr = 0x00+x; break;
case 2: DDRAMAddr = 0x40+x; break;
case 3: DDRAMAddr = 0x14+x; break;
case 4: DDRAMAddr = 0x54+x; break;
default: DDRAMAddr = 0x00+x;
}
lcd_command(1<<7 | DDRAMAddr);
}
// ============================================================================
void lcd_define_char(const char *pc,char char_code)
{
char a , i;
a = ((char_code<<3)|0x40) & 0xff;
for (i = 0; i < 8 ;i++)
{
lcd_command(a++);
clcd_Delay();
lcd_putchar(pc[i]);
clcd_Delay();
}
}
// ============================================================================
void lcd_clear(void) //Clears LCD
{
lcd_command(0x01);
lcd_command(0x02);
clcd_Delay();
clcd_Delay();
}
//============================================================
void lcd_shift_left(char n) //Scrol n of characters Right
{
char i;
for (i = 0 ; i < n ; i++)
{
lcd_command(0x1E);
clcd_Delay();
}
}
//========================================================
void lcd_shift_right(char n) //Scrol n of characters Left
{
char i;
for (i = 0 ; i < n ; i++)
{
lcd_command(0x18);
clcd_Delay();
}
}
// ============================================================================
void lcd_puts(int num)
{
int i,j;
char zero,ch[10];
if(num==0)
{
zero=num;
zero+=48;
lcd_putchar(zero);
}
else if(num>0)
{
for(i=0;num>0;i++)
{
ch[i]=num%10;
num/=10;
}
for(j=i-1;j>=0;j--)
{
ch[j]+=48;
lcd_putchar(ch[j]);
}
}
else if(num<0)
{
num*=-1;
for(i=0;num>0;i++)
{
ch[i]=num%10;
num/=10;
}
lcd_putchar('-');
for(j=i-1;j>=0;j--)
{
ch[j]+=48;
lcd_putchar(ch[j]);
}
}
}
//=============================================================================
void lcd_putsf(char* data) //Outputs string to LCD
{
char *p;
p = data;
if (!p)
return;
for(; *p ; )
{
lcd_putchar(*p);
p++;
}
}
//=============================================================
void Display_off(void)
{
lcd_command(0x08);
clcd_Delay();
}
//=============================================================
void Display_on(void)
{
lcd_command(0x0C);
clcd_Delay();
}
//=============================================================
void cursor_off(void)
{
lcd_command(0x0C);
clcd_Delay();
}
//=============================================================
void cursor_on(void)
{
lcd_command(0x0E);
clcd_Delay();
}
//=============================================================
void cursor_blink(void)
{
lcd_command(0x0F);
clcd_Delay();
}
#endif
| 2.25 | 2 |
2024-11-18T22:37:14.295155+00:00 | 2017-06-24T12:14:56 | 7ba64eeac737e8a154aba205ea332eb8a5a73117 | {
"blob_id": "7ba64eeac737e8a154aba205ea332eb8a5a73117",
"branch_name": "refs/heads/master",
"committer_date": "2017-06-24T12:14:56",
"content_id": "27c861ba63d8e882fe19c9c32d5cd66c26272816",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "8865a764b0244ad2605be7547b904cc765578d5f",
"extension": "c",
"filename": "token.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 93120247,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4780,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/token.c",
"provenance": "stackv2-0107.json.gz:95685",
"repo_name": "tedyu002/csv_practice",
"revision_date": "2017-06-24T12:14:56",
"revision_id": "8a946c5994631261b658cf152ed82c3641ef8595",
"snapshot_id": "47b83433cdc6492c898f2c8a275d5f6e7495ed68",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/tedyu002/csv_practice/8a946c5994631261b658cf152ed82c3641ef8595/src/token.c",
"visit_date": "2021-01-23T11:03:56.271373"
} | stackv2 | #include <errno.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include "token.h"
int
token_string_get(const char **src, char **string)
{
const char *beg = NULL;
const char *line_end = NULL;
const char *str_end = NULL;
char *tmp_str = NULL;
size_t tmp_str_len = 0;
if (src == NULL || string == NULL) {
errno = EINVAL;
return -1;
}
beg = *src;
while (*beg != '\0' && *beg != '\n' && *beg == ' ') {
beg++;
}
line_end = beg;
while (*line_end != '\0' && *line_end != '\n') {
line_end++;
}
str_end = line_end;
while (beg < str_end && isspace(*(str_end - 1))) {
str_end--;
}
tmp_str_len = str_end - beg;
if ((tmp_str = malloc((tmp_str_len + 1) * sizeof(char))) == NULL) {
return -1;
}
strncpy(tmp_str, beg, tmp_str_len);
tmp_str[tmp_str_len] = '\0';
*string = tmp_str;
*src = line_end + ((*line_end == '\0') ? 0 : 1);
return 0;
}
int
token_column_string_get(const char **src, char **string)
{
const char *beg = NULL;
const char *col_end = NULL;
const char *str_end = NULL;
bool quoted = false;
FILE *target_fp = NULL;
size_t target_size = 0;
char *target_buf = NULL;
int save_errno = 0;
if (src == NULL || string == NULL) {
errno = EINVAL;
return -1;
}
beg = *src;
while (*beg != '\0' && *beg != '\n' && *beg != ',' && (*beg == ' ' || iscntrl(*beg))) {
beg++;
}
if (*beg == '\0' || *beg == '\n' || *beg == ',') {
char *tmp_str = NULL;
if ((tmp_str = strdup("")) == NULL) {
return -1;
}
*string = tmp_str;
*src = beg;
return 0;
}
if (*beg == '"') {
quoted = true;
beg++;
}
if ((target_fp = open_memstream(&target_buf, &target_size)) == NULL) {
save_errno = ENOMEM;
goto end;
}
if (quoted) {
str_end = beg;
while (*str_end != '\0') {
if (*str_end == '"') {
if (*(str_end + 1) == '"') {
if (fputc('"', target_fp) == EOF) {
save_errno = ENOMEM;
goto end;
}
str_end += 2;
}
else {
quoted = false;
break;
}
}
else if (iscntrl(*str_end)) {
str_end++;
}
else {
if (fputc(*str_end, target_fp) == EOF) {
save_errno = ENOMEM;
goto end;
}
str_end++;
}
}
fclose(target_fp);
target_fp = NULL;
if (quoted) {
*src = str_end;
save_errno = EINVAL;
goto end;
}
*string = target_buf;
*src = str_end + 1;
target_buf = NULL;
}
else {
char *tmp_str = NULL;
size_t tmp_str_len = 0;
col_end = beg;
while (*col_end != '\0') {
if (*col_end == ',' || *col_end == '\n') {
break;
}
else if (*col_end == '"') {
*src = col_end + 1;
save_errno = EINVAL;
goto end;
}
col_end++;
}
str_end = col_end;
while (beg < str_end && (*(str_end - 1) == ' ' || iscntrl(*(str_end - 1)))) {
str_end--;
}
tmp_str_len = str_end - beg;
if ((tmp_str = malloc((tmp_str_len + 1) * sizeof(char))) == NULL) {
save_errno = ENOMEM;
goto end;
}
strncpy(tmp_str, beg, tmp_str_len);
tmp_str[tmp_str_len] = '\0';
*string = tmp_str;
*src = col_end;
}
end:
if (target_fp != NULL) {
fclose(target_fp);
target_fp = NULL;
}
if (target_buf != NULL) {
free(target_buf);
target_buf = NULL;
}
if (save_errno != 0) {
errno = save_errno;
return -1;
}
return 0;
}
int
token_formula_get(const char **src, char **string)
{
const char *beg = NULL;
const char *str_end = NULL;
char *tmp_str = NULL;
size_t tmp_str_len = 0;
if (src == NULL || string == NULL) {
errno = EINVAL;
return -1;
}
beg = *src;
while (*beg != '\0' && *beg == ' ') {
beg++;
}
if (*beg == '\0') {
*string = NULL;
return 0;
}
str_end = beg;
while (!(*str_end == '*' || *str_end == '+' ||
*str_end == '[' || *str_end == ']' ||
*str_end == ' ' || *str_end == '\0')) {
str_end++;
}
if (str_end == beg && *beg != '\0') {
str_end++;
}
tmp_str_len = str_end - beg;
if ((tmp_str = malloc((tmp_str_len + 1) * sizeof(char))) == NULL) {
return -1;
}
strncpy(tmp_str, beg, tmp_str_len);
tmp_str[tmp_str_len] = '\0';
*string = tmp_str;
*src = str_end;
return 0;
}
int
token_letter_get(const char **src, char *letter)
{
const char *tmp_src = NULL;
if (src == NULL || letter == NULL) {
errno = EINVAL;
return -1;
}
tmp_src = *src;
while (*tmp_src != '\0') {
if (*tmp_src == '\n') {
errno = EINVAL;
return -1;
}
else if (isspace(*tmp_src)) {
tmp_src++;
}
else {
*letter = *tmp_src;
*src = tmp_src + 1;
return 0;
}
}
errno = EINVAL;
return -1;
}
int
token_to_line_feed(const char **src)
{
const char *tmp_src = NULL;
if (src == NULL) {
errno = EINVAL;
return -1;
}
tmp_src = *src;
while (!(*tmp_src == '\0' || *tmp_src == '\n')) {
tmp_src++;
}
if (*tmp_src == '\n') {
tmp_src++;
}
*src = tmp_src;
return 0;
}
| 2.796875 | 3 |
2024-11-18T22:37:14.370241+00:00 | 2014-01-15T19:37:03 | e7f5a5d74389dd5594c32f16559620419fdd50c0 | {
"blob_id": "e7f5a5d74389dd5594c32f16559620419fdd50c0",
"branch_name": "refs/heads/master",
"committer_date": "2014-01-19T15:45:38",
"content_id": "aa69ee17add136ddcc4b3c49f55064e9dafba567",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "ab8ef0cf7c895dc510bb9ed9540fe830563a7ed7",
"extension": "c",
"filename": "bytes.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": 1982,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/zcl/buffers/bytes.c",
"provenance": "stackv2-0107.json.gz:95816",
"repo_name": "clach04/RaleighSL",
"revision_date": "2014-01-15T19:37:03",
"revision_id": "c0479296201a34ea647534ed8cbc523494776da2",
"snapshot_id": "d9539971fbc29ad5cde51027b5033b024b01be14",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/clach04/RaleighSL/c0479296201a34ea647534ed8cbc523494776da2/src/zcl/buffers/bytes.c",
"visit_date": "2023-03-15T20:53:50.410681"
} | stackv2 | /*
* 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 <zcl/global.h>
#include <zcl/atomic.h>
#include <zcl/bytes.h>
/* ============================================================================
* PUBLIC bytes methods
*/
z_bytes_t *z_bytes_alloc (size_t size) {
z_bytes_t *self;
uint8_t *buf;
buf = z_memory_alloc(z_global_memory(), uint8_t, sizeof(z_bytes_t) + size);
if (Z_MALLOC_IS_NULL(buf))
return(NULL);
self = Z_BYTES(buf);
z_byte_slice_set(&(self->slice), buf + sizeof(z_bytes_t), size);
self->refs = 1;
return(self);
}
z_bytes_t *z_bytes_acquire (z_bytes_t *self) {
if (self != NULL)
z_atomic_inc(&(self->refs));
return(self);
}
void z_bytes_free (z_bytes_t *self) {
if (self == NULL)
return;
if (z_atomic_dec(&(self->refs)) > 0)
return;
z_memory_free(z_global_memory(), self);
}
z_bytes_t *z_bytes_from_data (const void *data, size_t size) {
z_bytes_t *self;
self = z_bytes_alloc(size);
if (Z_MALLOC_IS_NULL(self))
return(NULL);
z_bytes_set(self, data, size);
return(self);
}
/* ============================================================================
* PRIVATE vtable-refs methods
*/
static void __bytes_inc_ref (void *object) {
z_bytes_acquire(Z_BYTES(object));
}
static void __bytes_dec_ref (void *object) {
z_bytes_free(Z_BYTES(object));
}
const z_vtable_refs_t z_vtable_bytes_refs = {
.inc_ref = __bytes_inc_ref,
.dec_ref = __bytes_dec_ref,
};
| 2.203125 | 2 |
2024-11-18T22:37:14.609778+00:00 | 2017-01-20T14:44:22 | c3b357ed96e3bb42094d3dfb401349d04bb9ce29 | {
"blob_id": "c3b357ed96e3bb42094d3dfb401349d04bb9ce29",
"branch_name": "refs/heads/master",
"committer_date": "2017-01-20T14:44:22",
"content_id": "6193aed77849b385cad64d3aa3371cd79bb659d6",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "91b6ed7f2aa7b644266f8514d5ef09b353380275",
"extension": "c",
"filename": "main.c",
"fork_events_count": 0,
"gha_created_at": "2017-02-01T17:22:13",
"gha_event_created_at": "2017-02-01T17:22:13",
"gha_language": null,
"gha_license_id": null,
"github_id": 80644361,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1151,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/examples/adc/main.c",
"provenance": "stackv2-0107.json.gz:96201",
"repo_name": "obiltschnig/LetMeCreateIoT",
"revision_date": "2017-01-20T14:44:22",
"revision_id": "2d6d43c753f47a8a08691307e9c558fe890fbec8",
"snapshot_id": "e946ea162cc4cd78344f171236023fdc2d27b8b5",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/obiltschnig/LetMeCreateIoT/2d6d43c753f47a8a08691307e9c558fe890fbec8/examples/adc/main.c",
"visit_date": "2020-12-31T05:39:47.694221"
} | stackv2 | #include <stdio.h>
#include <contiki.h>
#include <contiki-net.h>
#include "dev/leds.h"
#include "letmecreate/core/common.h"
#include "letmecreate/core/debug.h"
#include "letmecreate/core/adc.h"
#include <p32xxxx.h>
PROCESS(main_process, "Main process");
AUTOSTART_PROCESSES(&main_process);
/*---------------------------------------------------------------------------*/
PROCESS_THREAD(main_process, ev, data)
{
PROCESS_BEGIN();
INIT_NETWORK_DEBUG();
{
// Due to the way Contiki protothreads work this needs to be static,
// otherwise the data will be lost when switching to a different thread
static float voltage = 0.0f;
static uint16_t major = 0;
static uint16_t minor = 0;
PRINTF("===START===\n");
PRINTF("Starting loop\n");
while(1)
{
adc_get_value(MIKROBUS_1, &voltage);
major = (int)voltage;
minor = (int)((voltage - (float)major) * 100.0f);
PRINTF("Voltage: %i.%02i\n", major, minor);
}
}
PROCESS_END();
}
/*---------------------------------------------------------------------------*/
| 2.140625 | 2 |
2024-11-18T22:37:16.964473+00:00 | 2016-06-18T15:57:51 | dd20909b244911028ce4cc3a33a9a521a9d6a270 | {
"blob_id": "dd20909b244911028ce4cc3a33a9a521a9d6a270",
"branch_name": "refs/heads/master",
"committer_date": "2016-06-18T15:57:51",
"content_id": "c50913c86a5343375e2da06f6c082d348450cd6c",
"detected_licenses": [
"BSD-3-Clause",
"BSD-2-Clause"
],
"directory_id": "ebd36ccaf7ff6de47c733dcc9c630d4b14d14394",
"extension": "c",
"filename": "writer_fd.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 61048765,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2194,
"license": "BSD-3-Clause,BSD-2-Clause",
"license_type": "permissive",
"path": "/pgp/src/lib/writer_fd.c",
"provenance": "stackv2-0107.json.gz:96589",
"repo_name": "iper4497/codigo_c",
"revision_date": "2016-06-18T15:57:51",
"revision_id": "6ea1975441c8192899d78b0937abd4cc473e2c31",
"snapshot_id": "841757a8704c79fb0738e798fc20bffaefd745f3",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/iper4497/codigo_c/6ea1975441c8192899d78b0937abd4cc473e2c31/pgp/src/lib/writer_fd.c",
"visit_date": "2021-01-21T01:50:22.824288"
} | stackv2 | /*
* Copyright (c) 2005-2008 Nominet UK (www.nic.uk)
* All rights reserved.
* Contributors: Ben Laurie, Rachel Willmer. The Contributors have asserted
* their moral rights under the UK Copyright Design and Patents Act 1988 to
* be recorded as the authors of this copyright work.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License.
*
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/** \file
*/
#include <sys/types.h>
#include <sys/uio.h>
#include <unistd.h>
#include <openpgpsdk/create.h>
#include <openpgpsdk/final.h>
typedef struct
{
int fd;
} writer_fd_arg_t;
static ops_boolean_t fd_writer(const unsigned char *src,unsigned length,
ops_error_t **errors,
ops_writer_info_t *winfo)
{
writer_fd_arg_t *arg=ops_writer_get_arg(winfo);
int n=write(arg->fd,src,length);
if(n == -1)
{
OPS_SYSTEM_ERROR_1(errors,OPS_E_W_WRITE_FAILED,"write",
"file descriptor %d",arg->fd);
return ops_false;
}
if((unsigned)n != length)
{
OPS_ERROR_1(errors,OPS_E_W_WRITE_TOO_SHORT,
"file descriptor %d",arg->fd);
return ops_false;
}
return ops_true;
}
static void fd_destroyer(ops_writer_info_t *winfo)
{
free(ops_writer_get_arg(winfo));
}
/**
* \ingroup Core_WritersFirst
* \brief Write to a File
*
* Set the writer in info to be a stock writer that writes to a file
* descriptor. If another writer has already been set, then that is
* first destroyed.
*
* \param info The info structure
* \param fd The file descriptor
*
*/
void ops_writer_set_fd(ops_create_info_t *info,int fd)
{
writer_fd_arg_t *arg=malloc(sizeof *arg);
arg->fd=fd;
ops_writer_set(info,fd_writer,NULL,fd_destroyer,arg);
}
// EOF
| 2.21875 | 2 |
2024-11-18T22:37:17.056519+00:00 | 2018-08-06T05:21:05 | e504f60caa8a38898db3799a3b1b5ca9d760185a | {
"blob_id": "e504f60caa8a38898db3799a3b1b5ca9d760185a",
"branch_name": "refs/heads/master",
"committer_date": "2018-08-06T05:21:05",
"content_id": "280f94c74adf76ebd1ca0d3edc80bbe11e9ab022",
"detected_licenses": [
"MIT"
],
"directory_id": "410579c19899b130b7472f4f76e3cf1bf7e763d7",
"extension": "c",
"filename": "yolo_bb.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 141395458,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 12071,
"license": "MIT",
"license_type": "permissive",
"path": "/yolo_bb.c",
"provenance": "stackv2-0107.json.gz:96717",
"repo_name": "puffadder/YOLOv2_boundingbox_compute",
"revision_date": "2018-08-06T05:21:05",
"revision_id": "ea32cd32379de09bb0f716a39a51b7b4b1fd902d",
"snapshot_id": "d76bdc795a2fdf8074b85162c5caca20b76517de",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/puffadder/YOLOv2_boundingbox_compute/ea32cd32379de09bb0f716a39a51b7b4b1fd902d/yolo_bb.c",
"visit_date": "2020-03-23T09:33:34.789946"
} | stackv2 | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <float.h>
#define OUT_W (13) // width of final layer
#define OUT_H (13) // height of final layer
#define N_BOXES (5) // number of anchor boxes
#define ORIG_W (416)//(768)
#define ORIG_H (416)//(576)
#define NET_W (416)
#define NET_H (416)
#define BOX_STRIDE (OUT_W*OUT_H)
#define NUM_BB (OUT_W*OUT_H*N_BOXES) // total number of possible bounding boxes
//#define NUM_CLASSES (20) // total number of classes for tiny yolo voc
#define NUM_CLASSES (80) // total number of classes for tiny yolo
#define NUM_COORDS (4)
#define NUM_ENTRIES_PER_BOX (NUM_CLASSES+NUM_COORDS+1)
#define NUM_ENTRIES (OUT_W*OUT_H*(N_BOXES*(NUM_CLASSES+NUM_COORDS+1)))
#define PROB_THRESH (0.24) // Default value in darknet
#define NMS_THRESH (0.3) // Default value in darknet
typedef struct
{
float x, y, w, h;
}box;
typedef struct{
int index;
int class;
float **probs;
} sortable_bbox;
//float biases[10] = {1.08, 1.19, 3.42, 4.41, 6.63, 11.38, 9.42, 5.11, 16.62, 10.52}; // anchor box biases for tiny yolo voc
float biases[10] = {0.57273, 0.677385, 1.87446, 2.06253, 3.33843, 5.47434, 7.88282, 3.52778, 9.77052, 9.16828}; // anchor box biases for tiny yolo
void correct_region_boxes(box *boxes, int n, int w, int h, int netw, int neth, int relative);
void do_nms_sort(box *boxes, float **probs, int total, int classes, float thresh);
void draw_detections(int num, float thresh, box *boxes, float **probs, int classes);
float sigmoid(float value)
{
return 1./(1. + exp(-value));
}
void softmax(float *probs, float *output, int n)
{
int i;
float sum = 0;
float largest = -FLT_MAX;
for(i = 0; i < n; ++i){
if(probs[i] > largest) largest = probs[i];
}
for(i = 0; i < n; ++i){
float e = exp(probs[i] - largest);
sum += e;
output[i] = e;
}
for(i = 0; i < n; ++i){
output[i] /= sum;
}
}
int main()
{
int status = 0;
int i, j;
int row, col;
int n;
float *predictions = NULL;
box *boxes = NULL;
float **probs = NULL;
FILE *fp = fopen("outputs.bin", "rb");
if (!fp)
{
printf("Error: Unable to open input file: outputs.bin for reading!\n");
status = -1;
goto cleanup;
}
predictions = calloc(NUM_ENTRIES, sizeof(float));
if (!predictions)
{
printf("Error: Unable to allocate memory for predictions!\n");
status = -1;
goto cleanup;
}
if ((NUM_ENTRIES*sizeof(float)) > fread(predictions, 1, NUM_ENTRIES*sizeof(float), fp))
{
printf("Error: Unable to read predictions from input file!\n");
status = -1;
goto cleanup;
}
boxes = calloc(NUM_BB, sizeof(box));
if (!boxes)
{
printf("Error: Unable to allocate memory for bounding boxes!\n");
status = -1;
goto cleanup;
}
probs = calloc(NUM_BB, sizeof(float*));
if (!probs)
{
printf("Unable to allocate memory for output probablities!\n");
status = -1;
goto cleanup;
}
for (i = 0; i < NUM_BB; i++)
{
probs[i] = calloc(NUM_CLASSES+1, sizeof(float));
if (!probs[i])
{
printf("Unable to allocate memory for output probablities!\n");
status = -1;
goto cleanup;
}
}
for (i = 0; i < OUT_H*OUT_W; i++)
{
row = i / OUT_W;
col = i % OUT_W;
for (n = 0; n < N_BOXES; n++)
{
int index = n*OUT_W*OUT_H + i;
for (j = 0; j < NUM_CLASSES; j++)
{
probs[index][j] = 0;
}
// get region box
int box_index = i*N_BOXES*NUM_ENTRIES_PER_BOX + n*NUM_ENTRIES_PER_BOX;
boxes[index].x = (col + sigmoid(predictions[box_index + 0])) / OUT_W;
boxes[index].y = (row + sigmoid(predictions[box_index + 1])) / OUT_H;
boxes[index].w = exp(predictions[box_index + 2]) * biases[2*n + 0] / OUT_W;
boxes[index].h = exp(predictions[box_index + 3]) * biases[2*n + 1] / OUT_H;
float scale = sigmoid(predictions[box_index + 4]);
#ifdef ENABLE_DEBUG
printf("\t#obj_index: %d scale: %f\n", box_index, scale);
printf("\t#box_index: %d\n", box_index);
printf("\t#x: %f y: %f w: %f h: %f\n", boxes[index].x, boxes[index].y, boxes[index].w, boxes[index].h);
#endif
float softmax_preds[NUM_CLASSES];
softmax(&predictions[box_index + (NUM_COORDS+1)], softmax_preds, NUM_CLASSES);
float max = 0;
for (j = 0; j < NUM_CLASSES; j++)
{
#ifdef ENABLE_DEBUG
printf("\t\t#class: %d class_index: %d\n", j, class_index);
#endif
float prob = scale * softmax_preds[j];
probs[index][j] = (prob > PROB_THRESH) ? prob : 0;
#ifdef ENABLE_DEBUG
printf("\t\t\t#prob: %f\n", probs[index][j]);
#endif
if (prob > max) max = prob;
}
probs[index][NUM_CLASSES] = max;
#ifdef ENABLE_DEBUG
printf("\t#max prob: %f\n", max);
#endif
}
}
correct_region_boxes(boxes, NUM_BB, ORIG_W, ORIG_H, NET_W, NET_H, 1 /*relative*/);
if (NMS_THRESH) do_nms_sort(boxes, probs, NUM_BB, NUM_CLASSES, NMS_THRESH);
draw_detections(NUM_BB, PROB_THRESH, boxes, probs, NUM_CLASSES);
cleanup:
if (probs)
{
for (i = 0; i < NUM_BB; i++)
{
if (probs[i]) free(probs[i]);
}
free(probs);
}
if (boxes) free(boxes);
if (predictions) free(predictions);
if (fp) fclose(fp);
return status;
}
void correct_region_boxes(box *boxes, int n, int w, int h, int netw, int neth, int relative)
{
int i;
int new_w=0;
int new_h=0;
if (((float)netw/w) < ((float)neth/h)) {
new_w = netw;
new_h = (h * netw)/w;
} else {
new_h = neth;
new_w = (w * neth)/h;
}
for (i = 0; i < n; ++i){
box b = boxes[i];
b.x = (b.x - (netw - new_w)/2./netw) / ((float)new_w/netw);
b.y = (b.y - (neth - new_h)/2./neth) / ((float)new_h/neth);
b.w *= (float)netw/new_w;
b.h *= (float)neth/new_h;
if(!relative){
b.x *= w;
b.w *= w;
b.y *= h;
b.h *= h;
}
#ifdef ENABLE_DEBUG
printf("\t#new_box x: %f y: %f w: %f h: %f\n", b.x, b.y, b.w, b.h);
#endif
boxes[i] = b;
}
}
float overlap(float x1, float w1, float x2, float w2)
{
float l1 = x1 - w1/2;
float l2 = x2 - w2/2;
float left = l1 > l2 ? l1 : l2;
float r1 = x1 + w1/2;
float r2 = x2 + w2/2;
float right = r1 < r2 ? r1 : r2;
return right - left;
}
float box_intersection(box a, box b)
{
float w = overlap(a.x, a.w, b.x, b.w);
float h = overlap(a.y, a.h, b.y, b.h);
if(w < 0 || h < 0) return 0;
float area = w*h;
return area;
}
float box_union(box a, box b)
{
float i = box_intersection(a, b);
float u = a.w*a.h + b.w*b.h - i;
return u;
}
float box_iou(box a, box b)
{
return box_intersection(a, b)/box_union(a, b);
}
int nms_comparator(const void *pa, const void *pb)
{
sortable_bbox a = *(sortable_bbox *)pa;
sortable_bbox b = *(sortable_bbox *)pb;
float diff = a.probs[a.index][b.class] - b.probs[b.index][b.class];
if(diff < 0) return 1;
else if(diff > 0) return -1;
return 0;
}
void do_nms_sort(box *boxes, float **probs, int total, int classes, float thresh)
{
int i, j, k;
sortable_bbox *s = calloc(total, sizeof(sortable_bbox));
for(i = 0; i < total; ++i){
s[i].index = i;
s[i].class = 0;
s[i].probs = probs;
}
for(k = 0; k < classes; ++k){
for(i = 0; i < total; ++i){
s[i].class = k;
}
qsort(s, total, sizeof(sortable_bbox), nms_comparator);
for(i = 0; i < total; ++i){
if(probs[s[i].index][k] == 0) continue;
box a = boxes[s[i].index];
for(j = i+1; j < total; ++j){
box b = boxes[s[j].index];
if (box_iou(a, b) > thresh){
probs[s[j].index][k] = 0;
}
}
}
}
#ifdef ENABLE_DEBUG
printf("\t#Post nms probs:\n");
for (i=0; i<total; i++)
{
for (j=0; j<classes; j++)
{
printf("\t\t#[%d][%d] probs: %f\n", i, j, probs[i][k]);
}
}
#endif
free(s);
}
unsigned int read_class_names(char names[NUM_CLASSES][4096])
{
char *class_name;
ssize_t len = 0;
ssize_t read;
unsigned int class_num = 0;
unsigned int is_class_name_available;
FILE *fp = fopen("coco.names", "r");
if (!fp)
{
printf("Unable to read class name list. Will display label number instead.\n");
is_class_name_available = 0;
goto cleanup;
}
while ((read = getline(&class_name, &len, fp)) != -1) {
//printf("Retrieved line of length %zu: %s\n", read, class_name);
snprintf(names[class_num], read, "%s", class_name);
names[class_num++][read] = '\0';
}
is_class_name_available = 1;
cleanup:
free(class_name);
if (fp)
{
fclose(fp);
}
return is_class_name_available;
}
void draw_detections(int num, float thresh, box *boxes, float **probs, int classes)
{
int i, j;
char names[NUM_CLASSES][4096];
unsigned int is_class_name_available = read_class_names(names);
for (i = 0; i < num; i++)
{
char labelstr[4096] = {0};
int class = -1;
for (j = 0; j < classes; j++)
{
if (probs[i][j] > thresh)
{
if (class < 0)
{
if (is_class_name_available)
{
strcat(labelstr, names[j]);
}
else
{
printf("label #%d, ", j);
}
class = j;
}
else
{
if (is_class_name_available)
{
strcat(labelstr, ",");
strcat(labelstr, names[j]);
}
else
{
printf("label #%d, ", j);
}
}
if (is_class_name_available)
{
printf("%s: %.0f%%\n", names[j], probs[i][j]*100);
}
else
{
printf("\t prob: %f\n", probs[i][j]*100);
}
}
}
if (class >= 0)
{
int width = ORIG_W * 0.006;
int offset = class*123457 % classes;
//float red = get_color(2,offset,classes);
//float green = get_color(1,offset,classes);
//float blue = get_color(0,offset,classes);
//float rgb[3];
//rgb[0] = red;
//rgb[1] = green;
//rgb[2] = blue;
box b = boxes[i];
int left = (b.x-b.w/2.)*ORIG_W;
int right = (b.x+b.w/2.)*ORIG_W;
int top = (b.y-b.h/2.)*ORIG_H;
int bot = (b.y+b.h/2.)*ORIG_H;
if(left < 0) left = 0;
if(right > ORIG_W-1) right = ORIG_W-1;
if(top < 0) top = 0;
if(bot > ORIG_H-1) bot = ORIG_H-1;
printf("\tleft: %d right: %d top: %d bot: %d\n", left, right, top, bot);
}
}
}
| 2.21875 | 2 |
2024-11-18T22:37:17.449714+00:00 | 2019-12-21T08:34:46 | 0b561d933a167d29f41323bbd45445b22848b5b2 | {
"blob_id": "0b561d933a167d29f41323bbd45445b22848b5b2",
"branch_name": "refs/heads/master",
"committer_date": "2019-12-21T08:34:46",
"content_id": "40140769f092b9c86359c170e56923c113667b7e",
"detected_licenses": [
"MIT"
],
"directory_id": "524d13bf9f1166ba944e9597cc0f741e4a9bb3fc",
"extension": "c",
"filename": "log.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 114945769,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1070,
"license": "MIT",
"license_type": "permissive",
"path": "/lib/log/log.c",
"provenance": "stackv2-0107.json.gz:97105",
"repo_name": "mytchel/agatha",
"revision_date": "2019-12-21T08:34:46",
"revision_id": "c6831b8fe2d0d60939aa82777ceecc3a50a062ec",
"snapshot_id": "5020d177fb1e47db1ea7cb33821a652c182fa4c0",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/mytchel/agatha/c6831b8fe2d0d60939aa82777ceecc3a50a062ec/lib/log/log.c",
"visit_date": "2021-06-03T09:27:52.035513"
} | stackv2 | #include <types.h>
#include <err.h>
#include <sys.h>
#include <c.h>
#include <mesg.h>
#include <stdarg.h>
#include <string.h>
#include <proc0.h>
#include <log.h>
static bool setup = false;
static int log_eid;
int
log_init(char *name)
{
union proc0_req prq;
union proc0_rsp prp;
union log_req lrq;
union log_rsp lrp;
prq.get_resource.type = PROC0_get_resource;
prq.get_resource.resource_type = RESOURCE_type_log;
log_eid = kcap_alloc();
if (log_eid < 0) {
exit(ERR);
}
mesg_cap(CID_PARENT, &prq, &prp, log_eid);
if (prp.get_resource.ret != OK) {
exit(ERR);
}
lrq.reg.type = LOG_register;
snprintf(lrq.reg.name, sizeof(lrq.reg.name),
"%s", name);
if (mesg(log_eid, &lrq, &lrp) != OK || lrp.reg.ret != OK) {
return lrp.reg.ret;
}
setup = true;
return OK;
}
void
log(int level, char *fmt, ...)
{
union log_req rq;
union log_rsp rp;
va_list a;
if (!setup) return;
va_start(a, fmt);
vsnprintf(rq.log.mesg, sizeof(rq.log.mesg),
fmt, a);
va_end(a);
rq.log.type = LOG_log;
rq.log.level = level;
mesg(log_eid, &rq, &rp);
}
| 2.3125 | 2 |
2024-11-18T22:37:17.987107+00:00 | 2023-08-25T04:46:28 | f1c25c9606e922e467a216048cb331db44d6b1a6 | {
"blob_id": "f1c25c9606e922e467a216048cb331db44d6b1a6",
"branch_name": "refs/heads/main",
"committer_date": "2023-08-25T07:17:19",
"content_id": "dcbbcf4c935d60e86ef6e11718c161f2c04c8d45",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "dc7631ad46c850ad3b491c261c2da42edffabc4e",
"extension": "c",
"filename": "led.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": 2964,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/board/crota/led.c",
"provenance": "stackv2-0107.json.gz:97493",
"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/board/crota/led.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.
*/
/* Crota specific PWM LED settings. */
#include "charge_manager.h"
#include "charge_state.h"
#include "common.h"
#include "compile_time_macros.h"
#include "ec_commands.h"
#include "extpower.h"
#include "gpio.h"
#include "led_common.h"
#include "led_onoff_states.h"
#include "pwm.h"
#include "util.h"
#include <stdint.h>
#define BAT_LED_ON_LVL 100
#define BAT_LED_OFF_LVL 0
__override const int led_charge_lvl_1 = 5;
__override const int led_charge_lvl_2 = 96;
__override struct led_descriptor
led_bat_state_table[LED_NUM_STATES][LED_NUM_PHASES] = {
[STATE_CHARGING_LVL_1] = { { EC_LED_COLOR_WHITE,
LED_INDEFINITE } },
[STATE_CHARGING_LVL_2] = { { EC_LED_COLOR_WHITE,
LED_INDEFINITE } },
[STATE_CHARGING_FULL_CHARGE] = { { LED_OFF, LED_INDEFINITE } },
[STATE_DISCHARGE_S0] = { { LED_OFF, LED_INDEFINITE } },
[STATE_DISCHARGE_S0_BAT_LOW] = { { EC_LED_COLOR_AMBER,
LED_INDEFINITE } },
[STATE_DISCHARGE_S3] = { { LED_OFF, LED_INDEFINITE } },
[STATE_DISCHARGE_S5] = { { LED_OFF, LED_INDEFINITE } },
[STATE_BATTERY_ERROR] = { { EC_LED_COLOR_AMBER,
1 * LED_ONE_SEC },
{ LED_OFF, 1 * LED_ONE_SEC } },
[STATE_FACTORY_TEST] = { { EC_LED_COLOR_WHITE,
1 * LED_ONE_SEC },
{ LED_OFF, 1 * LED_ONE_SEC } },
};
const enum ec_led_id supported_led_ids[] = {
EC_LED_ID_BATTERY_LED,
};
const int supported_led_ids_count = ARRAY_SIZE(supported_led_ids);
__override void led_set_color_battery(enum ec_led_colors color)
{
/* There are two battery leds, LED1/LED2 are on MB side.
* All leds are OFF by default.
*/
int led1_duty, led2_duty;
led1_duty = led2_duty = BAT_LED_OFF_LVL;
switch (color) {
case EC_LED_COLOR_AMBER:
led1_duty = BAT_LED_ON_LVL;
break;
case EC_LED_COLOR_WHITE:
led2_duty = BAT_LED_ON_LVL;
break;
default: /* LED_OFF and other unsupported colors */
break;
}
pwm_set_duty(PWM_CH_LED1, led1_duty);
pwm_set_duty(PWM_CH_LED2, led2_duty);
}
void led_get_brightness_range(enum ec_led_id led_id, uint8_t *brightness_range)
{
brightness_range[EC_LED_COLOR_AMBER] = 1;
brightness_range[EC_LED_COLOR_WHITE] = 1;
}
int led_set_brightness(enum ec_led_id led_id, const uint8_t *brightness)
{
led_auto_control(led_id, 0);
if (brightness[EC_LED_COLOR_AMBER] != 0)
led_set_color_battery(EC_LED_COLOR_AMBER);
else if (brightness[EC_LED_COLOR_WHITE] != 0)
led_set_color_battery(EC_LED_COLOR_WHITE);
else
led_set_color_battery(LED_OFF);
return EC_SUCCESS;
}
__override enum led_states board_led_get_state(enum led_states desired_state)
{
/* Make sure when battery is pre-charging, the LED will blinking.
* Otherwise it will wait 30 seconds then blinking.
*/
if (led_pwr_get_state() == LED_PWRS_IDLE) {
if (extpower_is_present())
desired_state = STATE_BATTERY_ERROR;
}
return desired_state;
}
| 2.09375 | 2 |
2024-11-18T22:37:18.173455+00:00 | 2021-03-25T01:00:06 | 57b570ec2a045626bf126a622d736d8b082d3740 | {
"blob_id": "57b570ec2a045626bf126a622d736d8b082d3740",
"branch_name": "refs/heads/master",
"committer_date": "2021-03-25T01:00:06",
"content_id": "b959340f11d0f7dc51d0180978c2703fcb684ac7",
"detected_licenses": [
"MIT"
],
"directory_id": "68bcb12c7c6aa756ccfef8867d703d98c9a9ec39",
"extension": "h",
"filename": "page_frame.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 293081743,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1035,
"license": "MIT",
"license_type": "permissive",
"path": "/p4/page_frame.h",
"provenance": "stackv2-0107.json.gz:97754",
"repo_name": "zhaoyi3264/cs537",
"revision_date": "2021-03-25T01:00:06",
"revision_id": "0b74d951f1481d0d5a17189d45234068ecb765ff",
"snapshot_id": "d199a18736e4172fa17ade62f385bb96ec4d8f72",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/zhaoyi3264/cs537/0b74d951f1481d0d5a17189d45234068ecb765ff/p4/page_frame.h",
"visit_date": "2023-03-31T23:42:40.380934"
} | stackv2 | /*
* Page frame module
*
* Authors:
* - Zhang, Zhaoyi, zhaoyi, zzhang825
* - Li, Richard, richardl, tli354
*/
#ifndef PAGE_FRAME_H
#define PAGE_FRAME_H
typedef struct FPFN {
long ppn;
struct FPFN *next;
} FPFN;
typedef struct PFN {
long ppn;
unsigned long pid;
unsigned long vpn;
struct PFN *prev;
struct PFN *next;
int reference;
void *data;
} PFN;
typedef struct PF {
PFN *head;
PFN *tail;
FPFN *free_head;
FPFN *free_tail;
long capacity;
long count;
long size;
void *root;
PFN *hand;
} PF;
typedef struct IPTE {
long ppn;
PFN *pfn;
} IPTE;
IPTE *create_ipte(long ppn, PFN* pfn);
int compare_ipte(const void *a, const void *b);
PFN *create_pfn(long ppn, unsigned long pid, unsigned long vpn);
PF *create_pf(long capacity);
void add_fpfn(PF *pf, long ppn);
void delete_pfn_helper(PF *pf, PFN *pfn);
long delete_fpfn(PF *pf);
void add_pfn_helper(PF *pf, PFN *pfn);
long add_pfn(PF *pf, unsigned long pid, unsigned long vpn);
void delete_pfn(PF *pf, long ppn);
void print_pf(PF *pf);
#endif
| 2.203125 | 2 |
2024-11-18T22:37:18.265490+00:00 | 2020-11-09T17:59:49 | 9bc5029c39d3409fc0294cc307cb28674653ef61 | {
"blob_id": "9bc5029c39d3409fc0294cc307cb28674653ef61",
"branch_name": "refs/heads/main",
"committer_date": "2020-11-09T17:59:49",
"content_id": "94d2d42b8797b1f0278be5899c77a3fac21a3037",
"detected_licenses": [
"MIT"
],
"directory_id": "601707badc8408b3a12c66cb7bd9175e5859a32b",
"extension": "c",
"filename": "bitowe_2A.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": 245,
"license": "MIT",
"license_type": "permissive",
"path": "/0x00/bitowe_2A.c",
"provenance": "stackv2-0107.json.gz:97884",
"repo_name": "Follow64/lessons",
"revision_date": "2020-11-09T17:59:49",
"revision_id": "b6e05c4de0ceb6951614589cc42a1001f4e55c50",
"snapshot_id": "c522bbff9429948200a9cb7e03d5fe6d71d81586",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Follow64/lessons/b6e05c4de0ceb6951614589cc42a1001f4e55c50/0x00/bitowe_2A.c",
"visit_date": "2023-01-10T18:21:40.080999"
} | stackv2 | #include <stdio.h>
#include "bitowe_2_common.h"
//wczytanie N bajtow i wypisanie ciagow bitow parzystosci
int main(void){
printf("Podaj n: ");
scanf("%d", &bytes);
clear_buff();
get_n_bytes();
print_result();
return 0;
} | 2.1875 | 2 |
2024-11-18T22:37:19.210722+00:00 | 2023-08-14T10:04:45 | a967941ec96ec8b7f638120d58bef194a82ab1ce | {
"blob_id": "a967941ec96ec8b7f638120d58bef194a82ab1ce",
"branch_name": "refs/heads/main",
"committer_date": "2023-08-31T08:45:30",
"content_id": "4da9307d127f40f22367d4db84168789338902e9",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "f5f92640115787db74a3275ef5b6427f7ee03bf3",
"extension": "c",
"filename": "SSL_SESSION_to_bytes.c",
"fork_events_count": 33,
"gha_created_at": "2019-06-21T20:09:57",
"gha_event_created_at": "2023-09-14T15:52:05",
"gha_language": "C++",
"gha_license_id": "Apache-2.0",
"github_id": 193154690,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 726,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/bssl-compat/source/SSL_SESSION_to_bytes.c",
"provenance": "stackv2-0107.json.gz:98789",
"repo_name": "envoyproxy/envoy-openssl",
"revision_date": "2023-08-14T10:04:45",
"revision_id": "c225b23550acad038047d7fa2e6258aaeaeaf8a7",
"snapshot_id": "b4bd90d1b0c0ab0b383159a139e28efe8572426e",
"src_encoding": "UTF-8",
"star_events_count": 39,
"url": "https://raw.githubusercontent.com/envoyproxy/envoy-openssl/c225b23550acad038047d7fa2e6258aaeaeaf8a7/bssl-compat/source/SSL_SESSION_to_bytes.c",
"visit_date": "2023-09-05T07:26:20.469865"
} | stackv2 | #include <openssl/ssl.h>
#include <ossl.h>
/*
* https://github.com/google/boringssl/blob/098695591f3a2665fccef83a3732ecfc99acdcdd/src/include/openssl/ssl.h#L1698
* https://www.openssl.org/docs/man3.0/man3/i2d_SSL_SESSION.html
*/
int SSL_SESSION_to_bytes(const SSL_SESSION *in, uint8_t **out_data, size_t *out_len) {
if(in == NULL || out_data == NULL || out_len == NULL) {
return 0;
}
int buflen = ossl.ossl_i2d_SSL_SESSION(in, NULL);
if(buflen == 0) {
return 0;
}
unsigned char *buf = OPENSSL_malloc(buflen);
if(buf == NULL) {
return 0;
}
buflen = ossl.ossl_i2d_SSL_SESSION(in, &buf);
if(buflen == 0) {
return 0;
}
*out_data = buf - buflen;
*out_len = buflen;
return 1;
}
| 2.375 | 2 |
2024-11-18T22:37:19.573503+00:00 | 2018-04-05T14:28:14 | 1f0d946ab1d39dd930a3cac89581c1bbd306d3f4 | {
"blob_id": "1f0d946ab1d39dd930a3cac89581c1bbd306d3f4",
"branch_name": "refs/heads/master",
"committer_date": "2018-04-05T14:28:14",
"content_id": "f3a2ad9ff52854eab5ca08eae8f5d7b3f4faeedf",
"detected_licenses": [
"MIT"
],
"directory_id": "b39b0652150a981c9e08d63b78a5b8d57197601e",
"extension": "h",
"filename": "colormaps.h",
"fork_events_count": 0,
"gha_created_at": "2018-03-27T16:29:10",
"gha_event_created_at": "2018-03-27T16:29:10",
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 127015715,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2085,
"license": "MIT",
"license_type": "permissive",
"path": "/doom_py/src/vizdoom/src/r_data/colormaps.h",
"provenance": "stackv2-0107.json.gz:98918",
"repo_name": "jaekyeom/doom-py",
"revision_date": "2018-04-05T14:28:14",
"revision_id": "a7d08a0f2e92b0ba4be538e182791be4c5a11a1b",
"snapshot_id": "476026afd7dad6ecd47cf2633c745e3b09fa5c9c",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/jaekyeom/doom-py/a7d08a0f2e92b0ba4be538e182791be4c5a11a1b/doom_py/src/vizdoom/src/r_data/colormaps.h",
"visit_date": "2020-03-06T18:52:38.651857"
} | stackv2 | #ifndef __RES_CMAP_H
#define __RES_CMAP_H
void R_InitColormaps ();
void R_DeinitColormaps ();
DWORD R_ColormapNumForName(const char *name); // killough 4/4/98
void R_SetDefaultColormap (const char *name); // [RH] change normal fadetable
DWORD R_BlendForColormap (DWORD map); // [RH] return calculated blend for a colormap
extern BYTE *realcolormaps; // [RH] make the colormaps externally visible
extern size_t numfakecmaps;
struct FDynamicColormap
{
void ChangeFade (PalEntry fadecolor);
void ChangeColor (PalEntry lightcolor, int desaturate);
void ChangeColorFade (PalEntry lightcolor, PalEntry fadecolor);
void BuildLights ();
static void RebuildAllLights();
BYTE *Maps;
PalEntry Color;
PalEntry Fade;
int Desaturate;
FDynamicColormap *Next;
};
// For hardware-accelerated weapon sprites in colored sectors
struct FColormapStyle
{
PalEntry Color;
PalEntry Fade;
int Desaturate;
float FadeLevel;
};
enum
{
NOFIXEDCOLORMAP = -1,
INVERSECOLORMAP, // the inverse map is used explicitly in a few places.
};
struct FSpecialColormap
{
float ColorizeStart[3];
float ColorizeEnd[3];
BYTE Colormap[256];
PalEntry GrayscaleToColor[256];
};
extern TArray<FSpecialColormap> SpecialColormaps;
// some utility functions to store special colormaps in powerup blends
#define SPECIALCOLORMAP_MASK 0x00b60000
inline uint32 MakeSpecialColormap(int index)
{
assert(index >= 0 && index < 65536);
return index | SPECIALCOLORMAP_MASK;
}
inline bool IsSpecialColormap(uint32 map)
{
return (map & 0xFFFF0000) == SPECIALCOLORMAP_MASK;
}
inline int GetSpecialColormap(int blend)
{
return IsSpecialColormap(blend) ? blend & 0xFFFF : NOFIXEDCOLORMAP;
}
int AddSpecialColormap(float r1, float g1, float b1, float r2, float g2, float b2);
extern BYTE DesaturateColormap[31][256];
extern "C"
{
extern FDynamicColormap NormalLight;
}
extern bool NormalLightHasFixedLights;
FDynamicColormap *GetSpecialLights (PalEntry lightcolor, PalEntry fadecolor, int desaturate);
#endif
| 2.09375 | 2 |
2024-11-18T22:37:19.652340+00:00 | 2021-08-04T05:56:47 | 2e3d550111035232b1033a2d905814c832fedaef | {
"blob_id": "2e3d550111035232b1033a2d905814c832fedaef",
"branch_name": "refs/heads/main",
"committer_date": "2021-08-04T05:56:47",
"content_id": "6e5c9cf8f623fb44eb6b3c65e94c572bacf9cdd2",
"detected_licenses": [
"MIT"
],
"directory_id": "440c4d6af8fc5ae6939a96c393b286ae3c16aff2",
"extension": "h",
"filename": "Node.h",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 379146518,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 161,
"license": "MIT",
"license_type": "permissive",
"path": "/DataStructures/DoubleLinkedList/Node.h",
"provenance": "stackv2-0107.json.gz:99047",
"repo_name": "ZimCodes/self_learning_projects",
"revision_date": "2021-08-04T05:56:47",
"revision_id": "0d295ae31e6e11f17cc4e0ff6e6c5de4a3d07d5a",
"snapshot_id": "1a3c26a387fd4010ba29753cff8710a8c6a35a3a",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ZimCodes/self_learning_projects/0d295ae31e6e11f17cc4e0ff6e6c5de4a3d07d5a/DataStructures/DoubleLinkedList/Node.h",
"visit_date": "2023-06-29T19:12:31.727907"
} | stackv2 | #pragma once
struct Node
{
Node(int val,Node* parent);
void CleanUp();
bool Contains(int val);
void Remove(int val);
Node* parent, * child;
int value;
};
| 2.140625 | 2 |
2024-11-18T22:37:19.858563+00:00 | 2018-05-10T03:02:21 | 848f39e04fe2486bd380879207a38dde167b2b9d | {
"blob_id": "848f39e04fe2486bd380879207a38dde167b2b9d",
"branch_name": "refs/heads/master",
"committer_date": "2018-05-10T03:02:21",
"content_id": "1e35e0b42ade7bbfa28caf32dc49c66e628f45ce",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "f0f1b6e39dc4e4ab53472ba68e36550537f95470",
"extension": "c",
"filename": "ieee_status.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": 1548,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/math/ieee_status.c",
"provenance": "stackv2-0107.json.gz:99434",
"repo_name": "miRackModular/optimized-routines",
"revision_date": "2018-05-10T03:02:21",
"revision_id": "2f9e5ce5bbaaf3bf025dc17d123388a12d8ba6b9",
"snapshot_id": "1cfa167ba8b830478fda27329c47794250e202e9",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/miRackModular/optimized-routines/2f9e5ce5bbaaf3bf025dc17d123388a12d8ba6b9/math/ieee_status.c",
"visit_date": "2020-03-16T17:38:17.640927"
} | stackv2 | /*
* ieee_status.c
*
* Copyright (C) 2015, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* 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.
*
* This file is part of the Optimized Routines project
*/
#include "math_private.h"
__inline unsigned __ieee_status(unsigned bicmask, unsigned xormask)
{
#if defined __aarch64__ && defined __FP_FENV_EXCEPTIONS
unsigned status_word;
unsigned ret;
#ifdef __FP_FENV_ROUNDING
# define MASK (1<<27)|FE_IEEE_FLUSHZERO|FE_IEEE_MASK_ALL_EXCEPT|FE_IEEE_ALL_EXCEPT|FE_IEEE_ROUND_MASK
#else
# define MASK (1<<27)|FE_IEEE_FLUSHZERO|FE_IEEE_MASK_ALL_EXCEPT|FE_IEEE_ALL_EXCEPT
#endif
/* mask out read-only bits */
bicmask &= MASK;
xormask &= MASK;
/* modify the status word */
__asm__ __volatile__ ("mrs %0, fpsr" : "=r" (status_word));
ret = status_word;
status_word &= ~bicmask;
status_word ^= xormask;
__asm__ __volatile__ ("msr fpsr, %0" : : "r" (status_word));
/* and return what it used to be */
return ret;
#else
return 0;
#endif
}
| 2.140625 | 2 |
2024-11-18T22:37:20.184793+00:00 | 2023-06-10T18:58:33 | 72339b4d5ef06de82b34aac352c69436ca2f505e | {
"blob_id": "72339b4d5ef06de82b34aac352c69436ca2f505e",
"branch_name": "refs/heads/main",
"committer_date": "2023-06-10T18:58:33",
"content_id": "c2dda6d4723ada1d2177614dade2d096a3268a11",
"detected_licenses": [
"MIT"
],
"directory_id": "9819c45475d0cd2dd4748c809e6db173c18bff37",
"extension": "c",
"filename": "string_overflow.c",
"fork_events_count": 97,
"gha_created_at": "2018-08-23T04:43:10",
"gha_event_created_at": "2023-09-04T19:37:50",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 145801335,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 336,
"license": "MIT",
"license_type": "permissive",
"path": "/test/string_overflow.c",
"provenance": "stackv2-0107.json.gz:99694",
"repo_name": "GrapheneOS/hardened_malloc",
"revision_date": "2023-06-10T18:58:33",
"revision_id": "2d302f7d85944bcaa1ce6419a4c51732f76daaa6",
"snapshot_id": "8fe46cbba026b7d0ad7825eb3111f0a9746a3978",
"src_encoding": "UTF-8",
"star_events_count": 972,
"url": "https://raw.githubusercontent.com/GrapheneOS/hardened_malloc/2d302f7d85944bcaa1ce6419a4c51732f76daaa6/test/string_overflow.c",
"visit_date": "2023-08-23T21:51:23.120660"
} | stackv2 | #include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <malloc.h>
#include "test_util.h"
OPTNONE int main(void) {
char *p = malloc(16);
if (!p) {
return 1;
}
size_t size = malloc_usable_size(p);
memset(p, 'a', size);
printf("overflow by %zu bytes\n", strlen(p) - size);
return 0;
}
| 2.515625 | 3 |
2024-11-18T22:37:21.495442+00:00 | 2018-04-20T08:08:48 | 4924d898273fd9e536a39391b6ff5c51dd97ae3a | {
"blob_id": "4924d898273fd9e536a39391b6ff5c51dd97ae3a",
"branch_name": "refs/heads/master",
"committer_date": "2018-04-20T08:08:48",
"content_id": "9085f3c4c2ef54819cf9676d0cfa523b1bb9e20d",
"detected_licenses": [
"Unlicense"
],
"directory_id": "35fe118f7dd79c24cda201216daeeb33ef1f8eff",
"extension": "c",
"filename": "main.c",
"fork_events_count": 0,
"gha_created_at": "2020-03-08T00:30:19",
"gha_event_created_at": "2020-03-08T00:30:19",
"gha_language": null,
"gha_license_id": "Unlicense",
"github_id": 245727532,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3028,
"license": "Unlicense",
"license_type": "permissive",
"path": "/USDK/example_sources/pm_deepstandby/src/main.c",
"provenance": "stackv2-0107.json.gz:100341",
"repo_name": "ghsecuritylab/RTL00_WEB",
"revision_date": "2018-04-20T08:08:48",
"revision_id": "a999e4c2fd188d56130273432012bec502c4ccc1",
"snapshot_id": "207319f2948805d3e753f7b7f56ca7ad036e1cc7",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ghsecuritylab/RTL00_WEB/a999e4c2fd188d56130273432012bec502c4ccc1/USDK/example_sources/pm_deepstandby/src/main.c",
"visit_date": "2021-02-28T19:28:13.131821"
} | stackv2 | /*
* Routines to access hardware
*
* Copyright (c) 2015 Realtek Semiconductor Corp.
*
*/
#include "device.h"
#include "gpio_api.h" // mbed
#include "sleep_ex_api.h"
#include "diag.h"
#include "main.h"
#define GPIO_LED_PIN PC_5
#define GPIO_PUSHBT_PIN PA_5
// NOTICE: The pull condition may differnet on your board
PinName pull_down_list[] = {
PA_0, PA_1, PA_2, PA_3, PA_4, PA_5, PA_6, PA_7,
PB_0, PB_1, PB_3, PB_4, PB_5, PB_6, PB_7,
PC_0, PC_1, PC_2, PC_3, PC_4, PC_5, PC_6, PC_7, PC_8, PC_9,
PD_0, PD_1, PD_2, PD_3, PD_4, PD_5, PD_6, PD_7, PD_8, PD_9,
PE_0, PE_1, PE_2, PE_3, PE_4, PE_5, PE_6, PE_7, PE_8, PE_9, PE_A,
PF_1, PF_2, PF_3, PF_4, PF_5
};
// NOTICE: The pull condition may differnet on your board
PinName pull_up_list[] = {
PB_2,
PF_0,
PG_0, PG_1, PG_2, PG_3, PG_4, PG_5, PG_6, PG_7,
PH_0, PH_1, PH_2, PH_3, PH_4, PH_5, PH_6, PH_7,
PI_0, PI_1, PI_2, PI_3, PI_4, PI_5, PI_6, PI_7,
PJ_0, PJ_1, PJ_2, PJ_3, PJ_4, PJ_5, PJ_6,
PK_0, PK_1, PK_2, PK_3, PK_4, PK_5, PK_6
};
void gpio_pull_control()
{
int i;
gpio_t gpio_obj;
for (i=0; i < sizeof(pull_down_list) / sizeof(pull_down_list[0]); i++) {
gpio_init(&gpio_obj, pull_down_list[i]);
gpio_dir(&gpio_obj, PIN_INPUT);
gpio_mode(&gpio_obj, PullDown);
}
for (i=0; i < sizeof(pull_up_list) / sizeof(pull_up_list[0]); i++) {
gpio_init(&gpio_obj, pull_up_list[i]);
gpio_dir(&gpio_obj, PIN_INPUT);
gpio_mode(&gpio_obj, PullUp);
}
}
/**
* @brief Main program.
* @param None
* @retval None
*/
void main(void)
{
gpio_t gpio_led, gpio_btn;
int old_btn_state, new_btn_state;
DBG_INFO_MSG_OFF(_DBG_GPIO_);
// Init LED control pin
gpio_init(&gpio_led, GPIO_LED_PIN);
gpio_dir(&gpio_led, PIN_OUTPUT); // Direction: Output
gpio_mode(&gpio_led, PullNone); // No pull
// Initial Push Button pin
gpio_init(&gpio_btn, GPIO_PUSHBT_PIN);
gpio_dir(&gpio_btn, PIN_INPUT); // Direction: Input
gpio_mode(&gpio_btn, PullDown);
old_btn_state = new_btn_state = 0;
gpio_write(&gpio_led, 1);
DiagPrintf("Push button to sleep...\r\n");
while(1){
new_btn_state = gpio_read(&gpio_btn);
if (old_btn_state == 1 && new_btn_state == 0) {
gpio_write(&gpio_led, 0);
DiagPrintf("Sleep 8s... (Or wakeup by pushing button)\r\n");
//turn off log uart to avoid warning in gpio_pull_control()
sys_log_uart_off();
// Please note that the pull control is different in different board
// This example is a sample code for RTL Ameba Dev Board
gpio_pull_control();
standby_wakeup_event_add(STANDBY_WAKEUP_BY_STIMER, 8000, 0);
standby_wakeup_event_add(STANDBY_WAKEUP_BY_PA5, 0, 1);
deepstandby_ex();
DiagPrintf("This line should not be printed\r\n");
}
old_btn_state = new_btn_state;
}
}
| 2.34375 | 2 |
2024-11-18T22:37:21.616905+00:00 | 2019-07-29T13:17:53 | 490de699503c8a955dbd5512aa4c815358296b2b | {
"blob_id": "490de699503c8a955dbd5512aa4c815358296b2b",
"branch_name": "refs/heads/master",
"committer_date": "2019-07-29T13:17:53",
"content_id": "d76cd341393cb0e346fadaa09cdc62c0fa65a2f2",
"detected_licenses": [
"MIT"
],
"directory_id": "03f6fd1f193ff4b469a49d20615834a0921794c0",
"extension": "c",
"filename": "result.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": 840,
"license": "MIT",
"license_type": "permissive",
"path": "/ZeroJudger/result.c",
"provenance": "stackv2-0107.json.gz:100600",
"repo_name": "zjliang95/ZeroJudger",
"revision_date": "2019-07-29T13:17:53",
"revision_id": "38d580d64c29c886974b65dda9d5e6b01abdbcc0",
"snapshot_id": "be44e80c675484635ddf8509b20bb43050706e12",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/zjliang95/ZeroJudger/38d580d64c29c886974b65dda9d5e6b01abdbcc0/ZeroJudger/result.c",
"visit_date": "2022-03-01T10:39:41.247641"
} | stackv2 | #include <stdio.h>
#include "result.h"
const char *check_result(char *answer_file_name, char *output_file_name) {
FILE *answer_file, *output_file;
answer_file = fopen(answer_file_name, "r");
output_file = fopen(output_file_name, "r");
int ans, out;
const char * res;
res = "Accepted";
while (1) {
ans = fgetc(answer_file);
out = fgetc(output_file);
if (ans == EOF || out == EOF) { // 文件读取结束时,值为 EOF
if (ans != out) { // 如果两个文件没有同时结束,代表两个文件内容不同
res = "Wrong Answer";
}
goto END;
}
if (ans != out) {
res = "Wrong Answer";
goto END;
}
}
END:
fclose(answer_file);
fclose(output_file);
return res;
}
| 2.5 | 2 |
2024-11-18T22:48:43.844454+00:00 | 2020-03-01T23:58:30 | 72de80071757d0ded816a73262537c9f9e836dbc | {
"blob_id": "72de80071757d0ded816a73262537c9f9e836dbc",
"branch_name": "refs/heads/master",
"committer_date": "2020-03-01T23:58:30",
"content_id": "82fd84217e1c681cba640e58863dd6c9e734550e",
"detected_licenses": [
"MIT"
],
"directory_id": "53e86f2e846b8a60fa1910b7211f4fe71c72335d",
"extension": "c",
"filename": "interrupts.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": 2741,
"license": "MIT",
"license_type": "permissive",
"path": "/src/kernel/interrupts.c",
"provenance": "stackv2-0108.json.gz:75745",
"repo_name": "RobinHYuan/rpi3rtos",
"revision_date": "2020-03-01T23:58:30",
"revision_id": "fb92fbdd46c97b2f96b33e19da2b0e9907b8ba5c",
"snapshot_id": "ebcb69cbc1a5dc9977db5e0abe091e187517a9fc",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/RobinHYuan/rpi3rtos/fb92fbdd46c97b2f96b33e19da2b0e9907b8ba5c/src/kernel/interrupts.c",
"visit_date": "2023-03-20T20:38:44.679824"
} | stackv2 | /*
* MIT License
*
* Copyright (c) 2020 Richard Healy
*
* 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 "uart.h"
#include "irq.h"
#include "timer.h"
#include "kernel.h"
u64_t current_el0_irq(void) { return 0; }
u64_t current_el0_fiq(void) { return 0; }
void current_elx_irq(void) {
uart_puts("rpi3rtos::current_elx_irq(): An interrupt has occurred.\n");
if (*TIMER_CTL_AND_STATUS & TIMER_CTL_AND_STATUS_INT_FLG) {
uart_puts("rpi3rtos::current_elx_irq(): Timer has expired. Clear and reload.\n");
timer_clr_and_reload();
++kernel_get_pointer()->ticks;
}
//
//IRQ handler stub expects the following conditions after return:
// x0 Pointer to the kernel task SP where current task SP will be
// saved. If 0 skip.
// x1 kernel context stack pointer which will be restored.
//
if (kernel_get_pointer()->task) {
u64_t *sp_ptr = kernel_get_cur_task_sp_ptr();
u64_t sp = kernel_get_sp();
uart_puts("rpi3rtos::current_elx_irq(): ");
uart_puts("Interrupt handled. Switching to kernel task.\n");
asm volatile (
"mov x0, %0\n"
"mov x1, %1\n"
:: "r"(sp_ptr), "r"(sp) :
);
} else { //Task0 is kernel task. No need to switch.
uart_puts("rpi3rtos::current_elx_irq(): ");
uart_puts("Interrupt handled. Resuming kernel task.\n");
asm volatile (
"mov x0, 0\n"
"mov x1, 0\n"
);
}
return;
}
u64_t current_elx_fiq(void) { return 0; }
u64_t lower_aarch64_irq(void) { return 0; }
u64_t lower_aarch64_fiq(void) { return 0; }
u64_t lower_aarch32_irq(void) { return 0; }
u64_t lower_aarch32_fiq(void) { return 0; }
| 2.21875 | 2 |
2024-11-18T22:48:43.975074+00:00 | 2021-09-01T06:41:21 | 3517ccb30b4a9e6774d63c42c0f9ad821c72cc98 | {
"blob_id": "3517ccb30b4a9e6774d63c42c0f9ad821c72cc98",
"branch_name": "refs/heads/stable",
"committer_date": "2021-09-01T06:41:21",
"content_id": "ecb9be329f9ac50ad1469c2500091c2394a0a547",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "08fcc9ebc0a70f545cbc149385dfb9a4670eada8",
"extension": "c",
"filename": "seccomp_event.c",
"fork_events_count": 0,
"gha_created_at": "2021-09-01T13:20:48",
"gha_event_created_at": "2021-10-04T13:16:44",
"gha_language": null,
"gha_license_id": "Apache-2.0",
"github_id": 402068547,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 677,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/frida_mode/src/seccomp/seccomp_event.c",
"provenance": "stackv2-0108.json.gz:75874",
"repo_name": "Practical-Formal-Methods/AFLplusplus",
"revision_date": "2021-09-01T06:41:21",
"revision_id": "773baf9391ff5f1793deb7968366819e7fa07adc",
"snapshot_id": "5dc8f4ed334cbfa2ad63ef9755499a73ffe89a95",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/Practical-Formal-Methods/AFLplusplus/773baf9391ff5f1793deb7968366819e7fa07adc/frida_mode/src/seccomp/seccomp_event.c",
"visit_date": "2023-08-19T06:22:33.830060"
} | stackv2 | #include <stdint.h>
#include <stdio.h>
#include <sys/eventfd.h>
#include <unistd.h>
#include "debug.h"
#include "seccomp.h"
int seccomp_event_create(void) {
int fd = eventfd(0, 0);
if (fd < 0) { FATAL("seccomp_event_create"); }
return fd;
}
void seccomp_event_signal(int fd) {
uint64_t val = 1;
if (write(fd, &val, sizeof(uint64_t)) != sizeof(uint64_t)) {
FATAL("seccomp_event_signal");
}
}
void seccomp_event_wait(int fd) {
uint64_t val = 1;
if (read(fd, &val, sizeof(uint64_t)) != sizeof(uint64_t)) {
FATAL("seccomp_event_wait");
}
}
void seccomp_event_destroy(int fd) {
if (close(fd) < 0) { FATAL("seccomp_event_destroy"); }
}
| 2.1875 | 2 |
2024-11-18T22:48:44.493578+00:00 | 2021-05-24T17:35:45 | 0f23288cdcb33a8bc1c5c83c34d30f1cf01f2967 | {
"blob_id": "0f23288cdcb33a8bc1c5c83c34d30f1cf01f2967",
"branch_name": "refs/heads/main",
"committer_date": "2021-05-24T17:58:59",
"content_id": "8fa417909e1bf0314bfa10a092a2b0c1e98c4763",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "92db49455a00932bffe466a7d38b6083b44a9e70",
"extension": "h",
"filename": "mappinghashset.h",
"fork_events_count": 0,
"gha_created_at": "2021-06-06T22:49:47",
"gha_event_created_at": "2021-06-06T22:49:48",
"gha_language": null,
"gha_license_id": "BSD-2-Clause",
"github_id": 374479203,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 887,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/include/adt/mappinghashset.h",
"provenance": "stackv2-0108.json.gz:76262",
"repo_name": "dkegel-fastly/libfsm",
"revision_date": "2021-05-24T17:35:45",
"revision_id": "275f0abcf2b1164bb8f3a98c0e2dce41c5c1468a",
"snapshot_id": "1fa774a9ea6ca6be77840165706e4b3da6c9f3d9",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/dkegel-fastly/libfsm/275f0abcf2b1164bb8f3a98c0e2dce41c5c1468a/include/adt/mappinghashset.h",
"visit_date": "2023-05-09T03:43:32.177654"
} | stackv2 | /*
* Copyright 2019 Shannon F. Stewman
*
* See LICENCE for the full copyright terms.
*/
#ifndef ADT_MAPPINGHASHSET_H
#define ADT_MAPPINGHASHSET_H
struct fsm_alloc;
struct mapping_hashset;
struct mapping;
struct mapping_hashset_iter {
struct hashset_iter iter;
};
struct mapping_hashset *
mapping_hashset_create(const struct fsm_alloc *a,
unsigned long (*hash)(const void *a),
int (*cmp)(const void *a, const void *b));
void
mapping_hashset_free(struct mapping_hashset *hashset);
struct mapping *
mapping_hashset_add(struct mapping_hashset *hashset, struct mapping *item);
struct mapping *
mapping_hashset_find(const struct mapping_hashset *hashset, const struct mapping *item);
struct mapping *
mapping_hashset_first(const struct mapping_hashset *hashset, struct mapping_hashset_iter *it);
struct mapping *
mapping_hashset_next(struct mapping_hashset_iter *it);
#endif
| 2.125 | 2 |
2024-11-18T22:48:44.555379+00:00 | 2022-06-17T00:03:09 | 3c27104a78ef635497b8553cec8d42d2b3608bda | {
"blob_id": "3c27104a78ef635497b8553cec8d42d2b3608bda",
"branch_name": "refs/heads/master",
"committer_date": "2022-06-17T00:03:09",
"content_id": "5f5c4bcabfa23cc71032c7c814ac54d0cf19ea4a",
"detected_licenses": [
"MIT"
],
"directory_id": "4e5d99196144f58b17093f86a3bc15527d9662b9",
"extension": "h",
"filename": "esp32_manager_storage.h",
"fork_events_count": 3,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 206772417,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 6967,
"license": "MIT",
"license_type": "permissive",
"path": "/esp32_manager_storage.h",
"provenance": "stackv2-0108.json.gz:76391",
"repo_name": "pablobacho/esp32-manager",
"revision_date": "2022-06-17T00:03:09",
"revision_id": "8c7dc47c41d965148d28e9c7b643133271d200d6",
"snapshot_id": "ccbf4f7188b6c2c901fb46e8df8726146d4e0371",
"src_encoding": "UTF-8",
"star_events_count": 4,
"url": "https://raw.githubusercontent.com/pablobacho/esp32-manager/8c7dc47c41d965148d28e9c7b643133271d200d6/esp32_manager_storage.h",
"visit_date": "2022-06-26T23:05:08.821098"
} | stackv2 | /**
* esp32_manager_storage.h
*
* (C) 2019 - Pablo Bacho <pablo@pablobacho.com>
* This code is licensed under the MIT License.
*/
#ifndef _ESP32_MANAGER_STORAGE_H_
#define _ESP32_MANAGER_STORAGE_H_
#include <string.h>
#include <math.h>
#include "esp_system.h"
#include "esp_err.h"
#include "esp_log.h"
#include "nvs.h"
#include "nvs_flash.h"
#ifdef __cplusplus
extern "C" {
#endif
#define ESP32_MANAGER_NAMESPACES_SIZE CONFIG_ESP32_MANAGER_NAMESPACES_SIZE /*!< Maximum number of namespaces that can be registered */
#define ESP32_MANAGER_NAMESPACE_KEY_MAX_LENGTH 15 /*!< Maximum length of a namespace key */
#define ESP32_MANAGER_ENTRY_KEY_MAX_LENGTH 15 /*!< Maximum length of an entry key */
#define ESP32_MANAGER_ATTR_READ BIT0 /*!< READ flag */
#define ESP32_MANAGER_ATTR_WRITE BIT1 /*!< WRITE flag */
#define ESP32_MANAGER_ATTR_READWRITE (BIT1 | BIT0) /*!< READ & WRITE attributes. Meant for readability of the code because of both being commonly used together. */
#define ESP32_MANAGER_ATTR_NO_FLASH BIT3 /*!< Do not use flash/NVS */
/**
* Settings type.
*/
typedef enum {
i8, u8, i16, u16, i32, u32, i64, u64, flt, dbl,
multiple_choice, single_choice,
text, password,
blob, image
} esp32_manager_type_t;
#define ESP32_MANAGER_TYPE_WIFI_SSID_MAX_LENGTH 32
/**
* Settings entry
*/
typedef struct esp32_manager_entry {
const char * key; /*!< unique key to identify the entry */
const char * friendly; /*!< Friendly or human-readable name */
esp32_manager_type_t type; /*!< type */
void * value; /*!< pointer to the variable where the value of the setting is stored */
void * default_value; /*!< Default value */
uint32_t attributes; /*!< attributes */
esp_err_t (* from_string)(struct esp32_manager_entry *, char *); /*!< function to read value from string */
esp_err_t (* to_string)(struct esp32_manager_entry *, char *); /*!< function to write value to string */
esp_err_t (* html_form_widget)(char *, struct esp32_manager_entry *, size_t); /*!< funtion to generate html form field/widget */
} esp32_manager_entry_t;
/**
* Namespace handle.
*/
typedef struct {
const char * key; /*!< Namespace key */
const char * friendly; /*!< Namespace friendly or human-readable name */
esp32_manager_entry_t ** entries;
uint8_t size;
nvs_handle nvs_handle; /*!< NVS handle for this namespace */
} esp32_manager_namespace_t;
/**
* Array to store namespace objects
*/
extern esp32_manager_namespace_t * esp32_manager_namespaces[ESP32_MANAGER_NAMESPACES_SIZE];
/**
* @brief Initialize esp32_manager
*
* This function should be called only once.
*
* @return ESP_OK: success
* ESP_FAIL: error opening NVS
* ESP_ERR_NVS_PART_NOT_FOUND: NVS partition not found
*/
esp_err_t esp32_manager_storage_init();
/**
* @brief Register namespace with esp32_manager
*
* @param key key of the namespace
* @param friendly Friendly or human-readable name of the namespace
* @return handle to the namespace registered or null for error
*/
esp_err_t esp32_manager_register_namespace(esp32_manager_namespace_t * namespace);
/**
* @brief Register esp32 entry
*
* @param namespace pointer to the namespace the entry belongs to
* @param entry entry to be registered
* @return ESP_OK success
* ESP_ERR_NO_MEM no empty slots available for this entry
* ESP_ERR_INVALID_ARG namespace or entry pointers are not valid
*/
esp_err_t esp32_manager_register_entry(esp32_manager_namespace_t * namespace, esp32_manager_entry_t * entry);
/**
* @brief Default method for converting entry value to string
*
* @param entry Pointer to entry
* @param dest Output buffer
* @return ESP_OK success
* ESP_FAIL error
*/
esp_err_t esp32_manager_entry_to_string_default(esp32_manager_entry_t * entry, char * dest);
/**
* @brief Default method for converting string into entry value
*
* @param entry Pointer to entry
* @param source Input string
* @return ESP_OK success
* ESP_FAIL error
*/
esp_err_t esp32_manager_entry_from_string_default(esp32_manager_entry_t * entry, char * source);
/**
* @brief Commits all esp32 under a namespace to NVS for permanent storage
*
* @param namespace pointer to the namespace
* @return ESP_OK success
* ESP_FAIL error
* ESP_ERR_INVALID_ARG invalid handle
*/
esp_err_t esp32_manager_commit_to_nvs(esp32_manager_namespace_t * namespace);
/**
* @brief Read all esp32 under a namespace from NVS
*
* @param namespace pointer to the namespace
* @return ESP_OK success
* ESP_FAIL error
* ESP_ERR_INVALID_ARG invalid handle
*/
esp_err_t esp32_manager_read_from_nvs(esp32_manager_namespace_t * namespace);
/**
* @brief Erase all namespace content from NVS
*
* @param namespace pointer to the namespace
* @return ESP_OK success
* ESP_FAIL error
* ESP_ERR_INVALID_ARG invalid handle
*/
esp_err_t esp32_manager_namespace_nvs_erase(esp32_manager_namespace_t * namespace);
/**
* @brief Validate namespace pointer.
*
* Checks for null on:
* * namespace pointer
* * key (also max length)
* * friendly name
* * entries
*
* @param namespace pointer to namespace
* @return ESP_OK valid
* ESP_FAIL error
*/
esp_err_t esp32_manager_validate_namespace(esp32_manager_namespace_t * namespace);
/**
* @brief Validate entry pointer.
*
* Checks for null on:
* * entry pointer
* * key (also max length)
* * friendly name
* * value
* Remaining fields are optional and they can be NULL
*
* @param entry pointer to entry
* @return ESP_OK valid
* ESP_FAIL error
*/
esp_err_t esp32_manager_validate_entry(esp32_manager_entry_t * entry);
/**
* @brief Reset all entry values in a namespace to their defaults
*
* @param namespace pointer to the namespace
* @return ESP_OK success
* ESP_FAIL error
* ESP_ERR_INVALID_ARG invalid handle
*/
esp_err_t esp32_manager_reset_namespace(esp32_manager_namespace_t * namespace);
/**
* @brief Reset entry value to default
*
* @param namespace pointer to the namespace
* @return ESP_OK success
* ESP_FAIL error
* ESP_ERR_INVALID_ARG invalid handle
*/
esp_err_t esp32_manager_reset_entry(esp32_manager_entry_t * entry);
/**
* Checks whether a character x is a hexadecimal digit or not.
*/
#define ISHEX(x) ((x >= '0' && x <= '9') || (x >= 'a' && x <= 'f') || (x >= 'A' && x <= 'F'))
/**
* Returns the minimum value of 2 given.
*/
#define MIN(a,b) (((a)<(b))?(a):(b))
/**
* Returns the maximum value of 2 given.
*/
#define MAX(a,b) (((a)>(b))?(a):(b))
#ifdef __cplusplus
}
#endif
#endif // _ESP32_MANAGER_ENTRIES_H_ | 2.53125 | 3 |
2024-11-18T22:48:44.622605+00:00 | 2017-07-31T18:55:31 | 9e208898cf956ee8f85933cd67f591eeda5aa11a | {
"blob_id": "9e208898cf956ee8f85933cd67f591eeda5aa11a",
"branch_name": "refs/heads/master",
"committer_date": "2017-07-31T19:00:09",
"content_id": "f25d64142fb18d6ee8b8a2a5efdc50f74a80009f",
"detected_licenses": [
"MIT"
],
"directory_id": "891db9d12d5955ae37ae52ba732a26160af40aef",
"extension": "h",
"filename": "i2c.h",
"fork_events_count": 0,
"gha_created_at": "2017-10-20T07:40:52",
"gha_event_created_at": "2017-10-20T07:40:52",
"gha_language": null,
"gha_license_id": null,
"github_id": 107647429,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 718,
"license": "MIT",
"license_type": "permissive",
"path": "/inc/hal/i2c.h",
"provenance": "stackv2-0108.json.gz:76521",
"repo_name": "ToToL/nabgcc",
"revision_date": "2017-07-31T18:55:31",
"revision_id": "3e5ad0b1d975a2646a22dff5f0bcc957329ffca5",
"snapshot_id": "027fcc4c9c09d0ea6f0aca68872877a9db0a4a90",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ToToL/nabgcc/3e5ad0b1d975a2646a22dff5f0bcc957329ffca5/inc/hal/i2c.h",
"visit_date": "2021-07-15T10:34:50.653143"
} | stackv2 | /**
* @file i2c.h
* @author Violet - Initial version
* @author RedoX <dev@redox.ws> - 2015 - GCC Port, cleanup
* @date 2015/09/07
* @brief Manage the I2C low-level access
*/
#ifndef _I2C_H_
#define _I2C_H_
/* I2C Slave address */
#define CRX14_ADDR 0xA0
/* CRX14 settings */
#define I2C_WRITE_INSTR 0x00
#define I2C_READ_INSTR 0x01
#define CRX14_PARAMETER_REGISTER 0x00
#define CRX14_IO_FRAME_REGISTER 0x01
#define CRX14_AUTHENTICATE_REGISTER 0x02
#define CRX14_SLOT_MARKER_REGISTER 0x03
void init_i2c(void);
uint8_t write_i2c(uint8_t addr_i2c, uint8_t *data, uint8_t nb_byte);
uint8_t read_i2c(uint8_t addr_i2c, uint8_t *data, uint8_t nb_byte);
#endif
| 2.015625 | 2 |
2024-11-18T22:48:46.776535+00:00 | 2023-07-05T10:51:08 | e6f9bc7a51eded310075b6fdd3c07cf6dbda730e | {
"blob_id": "e6f9bc7a51eded310075b6fdd3c07cf6dbda730e",
"branch_name": "refs/heads/master",
"committer_date": "2023-07-05T10:51:08",
"content_id": "c82cb25596738f6d98aabf48e5a1c918fadf9754",
"detected_licenses": [
"ISC"
],
"directory_id": "9fee59f5f36ba5f4c5bbdc79cc1316935e9bcce2",
"extension": "c",
"filename": "gettime.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 245408925,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1945,
"license": "ISC",
"license_type": "permissive",
"path": "/microb/tools/gettime.c",
"provenance": "stackv2-0108.json.gz:77945",
"repo_name": "ligurio/snippets",
"revision_date": "2023-07-05T10:51:08",
"revision_id": "ae5457a5cdaa0a1fd83fcc1ed6c5d105489bb042",
"snapshot_id": "e95c83786943c3232fed48b7cf999bb80bb27c12",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/ligurio/snippets/ae5457a5cdaa0a1fd83fcc1ed6c5d105489bb042/microb/tools/gettime.c",
"visit_date": "2023-07-23T06:37:48.904476"
} | stackv2 | #include <time.h>
#include <sys/time.h>
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
// https://github.com/btorpey/clocks/blob/master/clocks.c
// http://repnop.org/carte/snippets/time.c
int main(int argc, char** argv)
{
printf("%25s\t%15s\t%15s\t%15s\n", "clock", "res (ns)", "secs", "nsecs");
struct timeval tv;
gettimeofday(&tv, NULL);
printf("%25s\t%15s\t%15ld\t", "gettimeofday","1,000", tv.tv_sec);
printf("%15ul\n", tv.tv_usec*1000);
#if _POSIX_TIMERS > 0
struct timespec x;
#ifdef CLOCK_REALTIME
clock_getres(CLOCK_REALTIME, &x);
printf("%25s\t%15ld", "CLOCK_REALTIME", x.tv_nsec);
clock_gettime(CLOCK_REALTIME, &x);
printf("\t%15ld\t%15ld\n", x.tv_sec, x.tv_nsec);
#endif
#ifdef CLOCK_REALTIME_COARSE
clock_getres(CLOCK_REALTIME_COARSE, &x);
printf("%25s\t%15ld", "CLOCK_REALTIME_COARSE", x.tv_nsec);
clock_gettime(CLOCK_REALTIME_COARSE, &x);
printf("\t%15ld\t%15ld\n", x.tv_sec, x.tv_nsec);
#endif
#ifdef CLOCK_REALTIME_HR
clock_getres(CLOCK_REALTIME_HR, &x);
printf("%25s\t%15ld", "CLOCK_REALTIME_HR", x.tv_nsec);
clock_gettime(CLOCK_REALTIME_HR, &x);
printf("\t%15ld\t%15ld\n", x.tv_sec, x.tv_nsec);
#endif
#ifdef CLOCK_MONOTONIC
clock_getres(CLOCK_MONOTONIC, &x);
printf("%25s\t%15ld", "CLOCK_MONOTONIC", x.tv_nsec);
clock_gettime(CLOCK_MONOTONIC, &x);
printf("\t%15ld\t%15ld\n", x.tv_sec, x.tv_nsec);
#endif
#ifdef CLOCK_MONOTONIC_RAW
clock_getres(CLOCK_MONOTONIC_RAW, &x);
printf("%25s\t%15ld", "CLOCK_MONOTONIC_RAW", x.tv_nsec);
clock_gettime(CLOCK_MONOTONIC_RAW, &x);
printf("\t%15ld\t%15ld\n", x.tv_sec, x.tv_nsec);
#endif
#ifdef CLOCK_MONOTONIC_COARSE
clock_getres(CLOCK_MONOTONIC_COARSE, &x);
printf("%25s\t%15ld", "CLOCK_MONOTONIC_COARSE", x.tv_nsec);
clock_gettime(CLOCK_MONOTONIC_COARSE, &x);
printf("\t%15ld\t%15ld\n", x.tv_sec, x.tv_nsec);
#endif
#endif
return 0;
}
| 2.5625 | 3 |
2024-11-18T22:48:46.973410+00:00 | 2017-10-02T07:13:13 | 89f652c20750f75d0b3e813e6ce230f72233ba7c | {
"blob_id": "89f652c20750f75d0b3e813e6ce230f72233ba7c",
"branch_name": "refs/heads/master",
"committer_date": "2017-10-02T07:13:13",
"content_id": "a02bd5f11a6d91979fddf5aa5bcf307e9d1180d1",
"detected_licenses": [
"MIT"
],
"directory_id": "8e5b38ca2bc2155951c55cde9998d2a83f45d890",
"extension": "c",
"filename": "SumaVectores.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 105507260,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1543,
"license": "MIT",
"license_type": "permissive",
"path": "/P1/SumaVectores/SumaVectores.c",
"provenance": "stackv2-0108.json.gz:78074",
"repo_name": "Ocete/Arquitectura-de-Computadores",
"revision_date": "2017-10-02T07:13:13",
"revision_id": "16fd183755210a3b00f5a268ea697c4e34707a82",
"snapshot_id": "c9b74ae71e7b2a5323c4a155db31a48dc6307e9a",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/Ocete/Arquitectura-de-Computadores/16fd183755210a3b00f5a268ea697c4e34707a82/P1/SumaVectores/SumaVectores.c",
"visit_date": "2021-07-06T11:00:53.901384"
} | stackv2 | /* SumaVectores.c
Suma de dos vectores:
v3 = v1 + v2
Para compilar usar (-lrt: real time library):
gcc -O2 SumaVectores.c -o SumaVectores –lrt
gcc -O2 –S SumaVectores.c –lrt //para generar el código ensamblador
Para ejecutar use: SumaVectoresC longitud
*/
#include <stdlib.h>
#include<stdio.h>
#include<time.h>
#define VECTOR_GLOBAL
#define MAX 67108864 //=2^26
double v1[MAX], v2[MAX], v3[MAX];
int main(int argc,char** argv){
int i;
struct timespec cgt1,cgt2;
double ncgt; //para tiempo de ejecución
//Leer argumento de entrada (nº de componentes del vector)
if (argc<2){
printf("Faltan nº componentes del vector \n");
exit(-1);
}
unsigned int N = atoi(argv[1]); // Máximo N =2^32 -1=4294967295 (sizeof(unsigned int) = 4 B)
if (N>MAX)
N=MAX;
//Inicializar vectores
for (i=0; i<N; i++){
v1[i] = N*0.1+ i*0.1; v2[i] = N*0.1 - i*0.1;
//los valores dependen de N
}
clock_gettime(CLOCK_REALTIME,&cgt1);
//Calcular suma de vectores
for (i=0; i<N; i++)
v3[i] = v1[i] + v2[i];
clock_gettime(CLOCK_REALTIME,&cgt2);
ncgt = (double) (cgt2.tv_sec - cgt1.tv_sec) +
(double) ((cgt2.tv_nsec - cgt1.tv_nsec)/(1.e+9));
//Imprimir resultado de la suma y el tiempo de ejecución
printf("Tiempo(seg.):%11.9f \t/ Tamaño Vectores:%u \t/"
"V1[0]+V2[0]=V3[0](%8.6f+%8.6f=%8.6f) / /"
"V1[%d]+V2[%d]=V3[%d](%8.6f+%8.6f=%8.6f) / \n",
ncgt, N, v1[0], v2[0], v3[0], N-1, N-1, N-1, v1[N-1], v2[N-1], v3[N-1]);
return 0;
}
| 3.109375 | 3 |
2024-11-18T22:48:47.791373+00:00 | 2012-09-07T23:03:42 | af27125c02380725ed684c3e7cfc52f412f32302 | {
"blob_id": "af27125c02380725ed684c3e7cfc52f412f32302",
"branch_name": "refs/heads/master",
"committer_date": "2012-09-07T23:03:42",
"content_id": "c444e0abe9a52509655c59be9708eb15dffc3b06",
"detected_licenses": [
"MIT"
],
"directory_id": "6b811c4e0a846b51ed80ac388b32aec209af2684",
"extension": "h",
"filename": "locale.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": 4562,
"license": "MIT",
"license_type": "permissive",
"path": "/inc/locale.h",
"provenance": "stackv2-0108.json.gz:78845",
"repo_name": "ezdiy/ccaprice",
"revision_date": "2012-09-07T23:03:42",
"revision_id": "2f569d1e0a21820a560f030e8eb0ab6c48c8a47d",
"snapshot_id": "cc0539eefe84d7548bf033b4480cf498280160ed",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ezdiy/ccaprice/2f569d1e0a21820a560f030e8eb0ab6c48c8a47d/inc/locale.h",
"visit_date": "2020-04-10T21:07:02.421319"
} | stackv2 | /*
* Copyright (C) 2012
* Dale Weiler
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#ifndef __CCAPRICE_LOCALE_HDR__
#define __CCAPRICE_LOCALE_HDR__
#include <ccaprice.h>
/*
* Standard says these need to be locale conformant
* We'll use a structure to define the ctype locale
* data.
*
* Note: The only implemented locale is the default
* C locale, future locales will come when required.
*/
typedef struct {
int (*fn_isalnum) (int);
int (*fn_isalpha) (int);
int (*fn_iscntrl) (int);
int (*fn_isdigit) (int);
int (*fn_isgraph) (int);
int (*fn_islower) (int);
int (*fn_isprint) (int);
int (*fn_ispunct) (int);
int (*fn_isspace) (int);
int (*fn_isupper) (int);
int (*fn_isxdigit)(int);
int (*fn_tolower) (int);
int (*fn_toupper) (int);
} ccaprice_ctypes_t;
/*
* Increase this number if more locales are ever required
* There is a high probability this number will have to be
* increased since there is simply too many languages and
* varations of languages on this earth. It seems like a
* sad waste when we have English. The universal everyone
* likes language that is viable for any situation. It's
* a pity others don't learn it. Oh well who cares? No one
* speaks properly these days, and many languages borrow
* from each other. For example English borrows a lot from
* old latin. I thought you should know this, it's nice to
* learn something new and interesting while reading source
* code comments. Anyways go learn English if you can't
* read this.
*/
#define __CCAPRICE_LOCALE_MAX 512
#define LC_ALL (1<<1)
#define LC_COLLATE (1<<2)
#define LC_CTYPE (1<<3)
#define LC_MONETARY (1<<4)
#define LC_NUMERIC (1<<5)
#define LC_TIME (1<<6)
/*
* setlocale() depends on two paramaters:
* -catageory
* -locale
*
* The category specifes which parts of the
* internal library change depending on the
* selected locale.
*
* The category can be any of the following
* -LC_ALL
* -LC_COLLATE
* -LC_CTYPE
* -LC_MONETARY
* -LC_NUMERIC
* -LC_TIME
*
* LC_ALL: changes the behaviour of the entire locale
* LC_COLLATE: only affects the behaviour of strcoll, and strxfrm
* LC_CTYPE: changes the behaviour in <ctype.h>
* LC_MONETARY affects the monetary formatting returned by localeconv
* LC_NUMERIC: affects _ONLY_ the decimal point on I/O operations and
* non-monetary information returned by localeconv()
* LC_TIME: only changes the behaviour of strftime.
*
* there is by default a "C" locale which is the minimal basic locale
* specified by ccaprice. A null string ("") or NULL should select the
* default enviroment locale.
*/
typedef struct lconv {
char *decimal_point;
char *thousands_sep;
char *grouping;
char *int_curr_symbol;
char *currency_symbol;
char *mon_decimal_point;
char *mon_thousands_sep;
char *mon_grouping;
char *positive_sign;
char *negative_sign;
char int_fract_digits;
char fract_digits;
char p_cs_precedes;
char n_cs_precedes;
char p_sep_by_space;
char n_sep_by_space;
char p_sign_posn;
char n_sign_posn;
} ccaprice_locale_c;
/*
* The order of data inside this structure matters:
* infact changing the ordering of this will break
* all ctype code. As well as all locale code.
*/
typedef struct {
ccaprice_ctypes_t ctype;
struct lconv lconv;
const char *ident; /* Name of the locale */
} ccaprice_locale_t;
__CCAPRICE_EXPORT struct lconv *localeconv();
__CCAPRICE_EXPORT char *setlocale (int, const char*);
#endif
| 2.03125 | 2 |
2024-11-18T22:48:48.305380+00:00 | 2016-09-05T09:16:49 | 4113f21f573fb6856a44e49bf9e8fb193fc752c0 | {
"blob_id": "4113f21f573fb6856a44e49bf9e8fb193fc752c0",
"branch_name": "refs/heads/master",
"committer_date": "2016-09-05T09:16:49",
"content_id": "e0a6fb7ea93e12e4e77a694b6375dd886b2e5cf6",
"detected_licenses": [
"MIT"
],
"directory_id": "6c5dad393ddabae535d69f3292df1422a9e03804",
"extension": "h",
"filename": "ESP8266_Data_Types.h",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 67348698,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 880,
"license": "MIT",
"license_type": "permissive",
"path": "/SwampControllerBaseV2/src/ESP8266/ESP8266_Data_Types.h",
"provenance": "stackv2-0108.json.gz:79230",
"repo_name": "jbagel2/stm32-f103-CortexM3-ESP8266-SwampController-Atollic",
"revision_date": "2016-09-05T09:16:49",
"revision_id": "add5fcd4352947d536ea7f76cbf381893104e4e3",
"snapshot_id": "273c03f7814df935b88c18e88f3429a6f384f709",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/jbagel2/stm32-f103-CortexM3-ESP8266-SwampController-Atollic/add5fcd4352947d536ea7f76cbf381893104e4e3/SwampControllerBaseV2/src/ESP8266/ESP8266_Data_Types.h",
"visit_date": "2020-09-10T19:22:08.402280"
} | stackv2 | /*
* ESP8266_Data_Types.h
*
* Created on: Mar 31, 2016
* Author: Jacob
*/
#ifndef ESP8266_DATA_TYPES_H_
#define ESP8266_DATA_TYPES_H_
#ifndef uint8_t
#include <stdint.h>
#endif
// Received Data Types ("1:PUMP:ZONE:ROOM:AUTOTEMP:HASH")
typedef struct
{
uint8_t command_int;
uint16_t pump_value;
uint8_t zone_num;
uint8_t room_num;
int8_t auto_temp;
char *hash_value;
}RX_FromESP_Command;
// Sent Data Types ("2:PUMP:ACTIVEZONES:ACTIVEROOMS:LINETEMPS:AMBIENTTEMP:AMBIENTHUMID:HASH")
typedef struct
{
uint8_t command_int;
float amb_temp;
float amb_humid;
char *hash_value;
uint8_t active_zones[20];
uint8_t acitve_zone_rooms[20][20];
float line_temps[];
}TX_ToESP_Command;
// Private Data Types
RX_FromESP_Command To_ESP_RXData_Struct(char *RX_String);
TX_ToESP_Command To_ESP_TXData_Struct(char *TX_String);
#endif /* ESP8266_DATA_TYPES_H_ */
| 2.046875 | 2 |
2024-11-18T22:48:49.820654+00:00 | 2020-03-19T16:15:58 | cae7feed71e4776f4697e37e3142f923f6e43522 | {
"blob_id": "cae7feed71e4776f4697e37e3142f923f6e43522",
"branch_name": "refs/heads/master",
"committer_date": "2020-03-19T16:15:58",
"content_id": "fe63ff9a483c2fa2431c4349eaa20040a9915cc3",
"detected_licenses": [
"MIT"
],
"directory_id": "f42c4fb8a135b11c6c83a10a166aa43b80739940",
"extension": "c",
"filename": "number_function.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 247141896,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3538,
"license": "MIT",
"license_type": "permissive",
"path": "/number_function.c",
"provenance": "stackv2-0108.json.gz:79489",
"repo_name": "andresvanegas19/printf",
"revision_date": "2020-03-19T16:15:58",
"revision_id": "de52c8829ae2dbf7379e5cce3142ab1b7f992a09",
"snapshot_id": "9c038ce7205585d08d6c08c89efa7f403c9dc407",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/andresvanegas19/printf/de52c8829ae2dbf7379e5cce3142ab1b7f992a09/number_function.c",
"visit_date": "2021-04-12T17:22:50.558657"
} | stackv2 | #include "holberton.h"
/**
* itoaa - is the function to convert int to string
* @arguments: is the list of the arguments the printf recive
* @buffer: where all the input save her
* @position: is the size of the input
* Return: the pointer with the size of the printf
*/
int itoaa(va_list arguments, char *buffer, int *position)
{
long int negative = 0, rem = 0, count = 0;
long int num = va_arg(arguments, int);
if (num == 00 || num == 0)
{
buffer[*position] = '0';
*position += 1;
return (0);
}
if (num < 0)
{
negative = 1;
num = -num;
}
while (num != 0)
{
rem = num % 10;
buffer[*position] = (rem > 9)
? (rem - 10) + 'A'
: rem + '0';
*position += 1;
num /= 10;
count++;
}
if (negative)
{
buffer[*position] = '-';
*position += 1;
count++;
}
reverse(buffer, position, count);
return (*position);
}
/**
* binary - is the function to convert binary to string
* @arguments: is the list of the arguments the printf recive
* @buffer: where all the input save her
* @position: is the size of the input
*
* Return: the pointer with the size of the printf
*/
int binary(va_list arguments, char *buffer, int *position)
{
unsigned int rem = 0, count = 0;
int num = va_arg(arguments, int);
if (num == 00 || num <= 0)
{
buffer[*position] = '0';
*position += 1;
return (0);
}
while (num != 0)
{
rem = num % 2;
buffer[*position] = (rem > 9)
? (rem - 10) + 'A'
: rem + '0';
*position += 1;
num /= 2;
count++;
}
reverse(buffer, position, count);
return (*position);
}
/**
* octal - is the function to convert octal to string
* @argum: is the list of the arguments the printf recive
* @buffer: where all the input save her
* @pos: is the size of the input
*
* Return: the pointer with the size of the printf
*/
int octal(va_list argum, char *buffer, int *pos)
{
unsigned int rem = 0, count = 0;
int num = va_arg(argum, int);
if (num == 00)
{
buffer[*pos] = '0';
*pos += 1;
return (0);
}
while (num != 0)
{
rem = num % 8;
buffer[*pos] = (rem > 9)
? (rem - 10) + 'A'
: rem + '0';
*pos += 1;
num /= 8;
count++;
}
reverse(buffer, pos, count);
return (*pos);
}
/**
* hexadown - is the function to convert int to hexadecimal string
* @argum: is the list of the arguments the printf recive
* @buffer: where all the input save her
* @pos: is the size of the input
*
* Return: the pointer with the size of the printf
*/
int hexadown(va_list argum, char *buffer, int *pos)
{
int rem = 0, count = 0;
int num = va_arg(argum, int);
if (num == 00)
{
buffer[*pos] = '0';
*pos += 1;
return (0);
}
while (num != 0)
{
rem = num % 16;
buffer[*pos] = (rem > 9)
? (rem - 10) + 'A'
: rem + '0';
*pos += 1;
num /= 16;
count++;
}
reverse(buffer, pos, count);
return (*pos);
}
/**
* hexaupper - is the function to convert int to hexadecimal string in format
* upper case.
*
* @argum: is the list of the arguments the printf recive
* @buffer: where all the input save her
* @pos: is the size of the input
*
* Return: the pointer with the size of the printf
*/
int hexaupper(va_list argum, char *buffer, int *pos)
{
unsigned int rem = 0, count = 0;
int num = va_arg(argum, int);
if (num == 00)
{
buffer[*pos] = '0';
*pos += 1;
return (0);
}
while (num != 0)
{
rem = num % 16;
buffer[*pos] = (rem > 9)
? (rem - 10) + 'A'
: rem + '0';
*pos += 1;
num /= 16;
count++;
}
string_todown(buffer, pos, count);
reverse(buffer, pos, count);
return (*pos);
}
| 3.25 | 3 |
2024-11-18T22:48:49.928947+00:00 | 2021-10-10T14:09:42 | 24335a3f929a9909610a1f0ddb86151a80e4f679 | {
"blob_id": "24335a3f929a9909610a1f0ddb86151a80e4f679",
"branch_name": "refs/heads/master",
"committer_date": "2021-10-10T14:09:42",
"content_id": "0e2650f5a7ae2ec217ec035ae833ac7231e067cb",
"detected_licenses": [
"BSL-1.0"
],
"directory_id": "c7f753dc8a3c9eb2258afacf7061d3cf0352be52",
"extension": "h",
"filename": "glass-value.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 187749620,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1213,
"license": "BSL-1.0",
"license_type": "permissive",
"path": "/c/apps/interpreter/inc/interpreter/glass-value.h",
"provenance": "stackv2-0108.json.gz:79617",
"repo_name": "samcoppini/C-Glass",
"revision_date": "2021-10-10T14:09:42",
"revision_id": "45044dc02c68f3ce986f58598ca9347661d48592",
"snapshot_id": "8c65a1a74ed3ab1b9b3410776fa4e7d6ba9c3184",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/samcoppini/C-Glass/45044dc02c68f3ce986f58598ca9347661d48592/c/apps/interpreter/inc/interpreter/glass-value.h",
"visit_date": "2021-10-24T15:32:54.691027"
} | stackv2 | #ifndef INTERPRETER_GLASS_VALUE_H
#define INTERPRETER_GLASS_VALUE_H
#include "interpreter/glass-instance.h"
#include <stdio.h>
struct CopyInterface;
struct String;
typedef enum ValueType {
VALUE_FUNCTION,
VALUE_INSTANCE,
VALUE_INPUT_FILE,
VALUE_NAME,
VALUE_NUMBER,
VALUE_OUTPUT_FILE,
VALUE_STRING,
} ValueType;
typedef struct GlassValue {
ValueType type;
union {
struct {
union {
GlassInstance inst;
FILE *file;
};
struct String *str;
};
double num;
};
} GlassValue;
extern const struct CopyInterface *VALUE_COPY_OPS;
GlassValue *new_func_value(GlassInstance inst, const struct String *name);
GlassValue *new_in_file_value(const struct String *name);
GlassValue *new_inst_value(GlassInstance inst);
GlassValue *new_name_value(const struct String *name);
GlassValue *new_number_value(double num);
GlassValue *new_out_file_value(const struct String *name);
GlassValue *new_str_value(const struct String *str);
GlassValue *copy_value(const GlassValue *val);
void free_glass_value(GlassValue *value);
struct String *value_get_string(const GlassValue *val);
#endif
| 2.171875 | 2 |
2024-11-18T22:48:50.247913+00:00 | 2015-04-30T10:20:32 | de4157600a59cd68e820f2f963169e2e0b6118a2 | {
"blob_id": "de4157600a59cd68e820f2f963169e2e0b6118a2",
"branch_name": "refs/heads/master",
"committer_date": "2015-04-30T10:20:32",
"content_id": "9aef1ae8c0e47b3c997add52e079c9521fe4346e",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "678b454f4767b18f0fc1dd6b7e8f7ea2bc02b242",
"extension": "c",
"filename": "ex04.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 25061516,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 342,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/C/AULA5/Caio/ex04.c",
"provenance": "stackv2-0108.json.gz:80007",
"repo_name": "GADS2014M/Exercicios",
"revision_date": "2015-04-30T10:20:32",
"revision_id": "da09c69db6b15fa220666de26aa2a7ab16ff6cc3",
"snapshot_id": "1dcc4697c25ef1e8947d2f712eddbf5c803e6fda",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/GADS2014M/Exercicios/da09c69db6b15fa220666de26aa2a7ab16ff6cc3/C/AULA5/Caio/ex04.c",
"visit_date": "2020-12-30T14:56:10.111132"
} | stackv2 | #include <stdio.h>
main () {
int i = 0;
char nome_completo[30], nome[16];
printf("Entre com um nome (\"nome sobrenome\"): ");
gets(nome_completo);
while ((nome_completo[i] != ' ') && (nome_completo[i] != '\0')) {
nome[i] = nome_completo[i];
i++;
}
nome[i] = '\0';
printf("\n%s", nome);
}
| 3.296875 | 3 |
2024-11-18T22:48:50.846652+00:00 | 2022-08-05T01:10:03 | ef3d83c398a15312b18ad547f894a593c45f191a | {
"blob_id": "ef3d83c398a15312b18ad547f894a593c45f191a",
"branch_name": "refs/heads/master",
"committer_date": "2022-08-05T01:10:03",
"content_id": "bef2420dbe4d2bdb3807c6e3069825948c5c81f9",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "d6dc6cefbfb71203ffcd7a76512515ff24ba5937",
"extension": "c",
"filename": "dyndnsd.c",
"fork_events_count": 0,
"gha_created_at": "2017-04-08T19:13:49",
"gha_event_created_at": "2022-05-21T19:57:05",
"gha_language": "C",
"gha_license_id": "BSD-3-Clause",
"github_id": 87657991,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4843,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/dyndnsd.c",
"provenance": "stackv2-0108.json.gz:80656",
"repo_name": "mario-campos/dyndnsd",
"revision_date": "2022-08-05T01:10:03",
"revision_id": "bfb9a8adcee76c9b31ac8403d968fb37573032ea",
"snapshot_id": "c9ec37645869f8c607f935bdffe417d5ac5b5ab2",
"src_encoding": "UTF-8",
"star_events_count": 16,
"url": "https://raw.githubusercontent.com/mario-campos/dyndnsd/bfb9a8adcee76c9b31ac8403d968fb37573032ea/dyndnsd.c",
"visit_date": "2022-09-07T17:18:47.396948"
} | stackv2 | #include <sys/cdefs.h>
#include <sys/queue.h>
#include <sys/wait.h>
#include <arpa/inet.h>
#include <assert.h>
#include <err.h>
#include <event.h>
#include <fcntl.h>
#include <grp.h>
#include <paths.h>
#include <pwd.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sysexits.h>
#include <syslog.h>
#include <unistd.h>
#include "dyndnsd.h"
#include "parser.h"
#include "rtm.h"
inline static void _free(char **);
static void usage(void);
static void handle_sigterm(int, short, void *);
static void handle_sigchld(int, short, void *);
static void process_event(int, short, void *);
static void drop_privilege(char *, char *);
static pid_t spawn(const char *, int, char *, char *, char *);
int
main(int argc, char *argv[])
{
int opt;
unsigned opts;
char *filename;
struct event ev_route, ev_signal;
struct dyndnsd this;
opts = 0;
filename = DYNDNSD_CONF_PATH;
openlog(getprogname(), LOG_PERROR | LOG_PID, LOG_DAEMON);
/* allocate route(4) socket before pledge(2) */
this.routefd = rtm_socket();
if (-1 == this.routefd)
errx(EX_UNAVAILABLE, "cannot create route(4) socket");
if (-1 == pledge("stdio rpath proc exec id getpw inet", NULL))
err(EX_OSERR, "pledge");
while (-1 != (opt = getopt(argc, argv, "hdnvf:"))) {
switch (opt) {
case 'd':
opts |= DYNDNSD_DEBUG_MODE;
break;
case 'h':
usage();
exit(EX_OK);
case 'f':
filename = optarg;
break;
case 'n':
opts |= DYNDNSD_VALID_MODE;
break;
case 'v':
puts(DYNDNSD_VERSION);
exit(EX_OK);
default:
usage();
exit(EX_USAGE);
}
}
if (-1 == (this.devnull = open(_PATH_DEVNULL, O_WRONLY|O_CLOEXEC)))
err(EX_OSFILE, "open");
if (NULL == (this.ast = parse(filename)))
errx(EX_DATAERR, "%s\n", parser_error);
if (opts & DYNDNSD_VALID_MODE)
exit(EX_OK);
if (0 == getuid())
drop_privilege(DYNDNSD_USER, DYNDNSD_GROUP);
if (!(opts & DYNDNSD_DEBUG_MODE) && -1 == daemon(0, 0))
err(EX_OSERR, "daemon");
if (-1 == pledge("stdio proc exec", NULL)) {
syslog(LOG_ERR, "pledge: %m");
exit(EX_OSERR);
}
syslog(LOG_DEBUG, "pledge: stdio proc exec");
event_init();
event_set(&ev_route, this.routefd, EV_READ|EV_PERSIST, process_event, &this);
event_add(&ev_route, NULL);
signal_set(&ev_signal, SIGTERM, handle_sigterm, &this);
signal_set(&ev_signal, SIGCHLD, handle_sigchld, NULL);
signal_add(&ev_signal, NULL);
event_dispatch();
}
inline static void
_free(char **p)
{
free(*p);
}
static void
process_event(int sig, short event, void *arg)
{
pid_t pid;
struct ast_if *aif;
struct ast_dn *adn;
struct rtm_newaddr rtm;
struct dyndnsd *this = arg;
if (-1 == rtm_consume(this->routefd, &rtm))
return;
SLIST_FOREACH(aif, &this->ast->aif_head, next) {
aif = SLIST_FIRST(&this->ast->aif_head);
if (strcmp(rtm.rtm_ifname, aif->name))
continue;
SLIST_FOREACH(adn, &aif->adn_head, next) {
pid = spawn(this->ast->run, this->devnull, adn->name, inet_ntoa(rtm.rtm_ifaddr), aif->name);
syslog(LOG_INFO, "%s %s %s %u", aif->name, inet_ntoa(rtm.rtm_ifaddr), adn->name, pid);
}
}
}
static void
usage(void)
{
fprintf(stderr, "usage: %s [-dhnv] [-f file]\n", getprogname());
}
static void __dead
handle_sigterm(int sig, short event, void *arg)
{
assert(arg);
struct dyndnsd *this = arg;
close(this->devnull);
close(this->routefd);
closelog();
exit(EX_OK);
}
static void
handle_sigchld(int sig, short event, void *arg)
{
wait(NULL);
}
static void
drop_privilege(char *username, char *groupname)
{
assert(username);
assert(groupname);
struct passwd *newuser;
struct group *newgroup;
if (NULL == (newgroup = getgrnam(groupname)))
err(EX_NOUSER, "getgrnam");
if (-1 == setgid(newgroup->gr_gid))
err(EX_OSERR, "setgid");
if (-1 == setgroups(1, &newgroup->gr_gid))
err(EX_OSERR, "setgroups");
if (NULL == (newuser = getpwnam(username)))
err(EX_NOUSER, "getpwnam");
if (-1 == setuid(newuser->pw_uid))
err(EX_OSERR, "setuid");
}
static pid_t
spawn(const char *cmd, int fd, char *domain, char *ipaddr, char *iface)
{
assert(cmd);
assert(fd >= 0);
assert(domain);
assert(ipaddr);
assert(iface);
pid_t pid;
char *envvar0 __attribute__((cleanup(_free)));
char *envvar1 __attribute__((cleanup(_free)));
char *envvar2 __attribute__((cleanup(_free)));
if (-1 == asprintf(&envvar0, "DYNDNSD_DOMAIN=%s", domain) ||
-1 == asprintf(&envvar1, "DYNDNSD_IPADDR=%s", ipaddr) ||
-1 == asprintf(&envvar2, "DYNDNSD_INTERFACE=%s", iface)) {
syslog(LOG_DEBUG, "asprintf: %m");
return -1;
}
pid = fork();
if (-1 == pid) {
syslog(LOG_DEBUG, "fork: %m");
return -1;
}
if (0 == pid) {
dup2(fd, STDIN_FILENO);
dup2(fd, STDOUT_FILENO);
dup2(fd, STDERR_FILENO);
setsid();
execle(_PATH_BSHELL, _PATH_BSHELL, "-c", cmd, NULL, (char*[]){envvar0, envvar1, envvar2, NULL});
}
return pid;
}
| 2.1875 | 2 |
2024-11-18T22:48:50.938159+00:00 | 2019-02-08T08:14:52 | 0e5b7c4293b1b55af622b75a72c211341197936b | {
"blob_id": "0e5b7c4293b1b55af622b75a72c211341197936b",
"branch_name": "refs/heads/master",
"committer_date": "2019-02-08T08:14:52",
"content_id": "e269b3e09bc4fff3f1b341baa940de00769fc9f2",
"detected_licenses": [
"MIT"
],
"directory_id": "a0898b7660de1a697706619f2e105adb4994b5ff",
"extension": "h",
"filename": "PbgProcID.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": 914,
"license": "MIT",
"license_type": "permissive",
"path": "/Source/PbgProcID.h",
"provenance": "stackv2-0108.json.gz:80787",
"repo_name": "qingdong163/kog",
"revision_date": "2019-02-08T08:14:52",
"revision_id": "7d45ba8ddc1b01987ccca416dbd7901a23f4412f",
"snapshot_id": "e12e297f41887461ccc2ea7411cc2d539be24581",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/qingdong163/kog/7d45ba8ddc1b01987ccca416dbd7901a23f4412f/Source/PbgProcID.h",
"visit_date": "2021-10-16T05:37:14.765339"
} | stackv2 | /*
* PbgProcID.h : プロシージャ定数の定義
*
*/
#ifndef PBGPROCID_INCLUDED
#define PBGPROCID_INCLUDED "プロシージャ定数の定義 : Version 0.01 : Update 2001/06/12"
/* [更新履歴]
* Version 0.01 : 2001/06/12 : 制作開始
*/
#include "PbgType.h"
/***** [ 定数 ] *****/
typedef enum tagPBG_PROCID {
PBGPROC_OK = 0x0000, // 正常終了
PBGPROC_TITLE = 0x0001, // タイトルに移行
PBGPROC_MAIN = 0x0002, // メインに移行
PBGPROC_MUSIC = 0x0003, // 音楽室に移行
PBGPROC_LOGO = 0x0004, // 西方ロゴに移行
PBGPROC_SELECT = 0x0005, // キャラ選択画面に移行
PBGPROC_ENDING = 0x0006, // エンディング
// PBGPROC_DISPWON1P = 0x007, // 1P側の勝ち表示
// PBGPROC_DISPWON2P = 0x008, // 2P側の勝ち表示
PBGPROC_CLOSE = 0xffff, // 閉じ
} PBG_PROCID;
#endif
| 2.125 | 2 |
2024-11-18T22:48:51.344410+00:00 | 2023-07-31T07:24:56 | f68a6d2c8b2233fe761e2035ca8f745d29a1e27f | {
"blob_id": "f68a6d2c8b2233fe761e2035ca8f745d29a1e27f",
"branch_name": "refs/heads/master",
"committer_date": "2023-07-31T07:24:56",
"content_id": "0a42cc84c0e4fc02c5350a86d863da6300fd605f",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "d77abc372ef9104cb1db80347523713c75c6b194",
"extension": "c",
"filename": "main.c",
"fork_events_count": 11,
"gha_created_at": "2018-09-07T07:42:26",
"gha_event_created_at": "2019-12-23T08:52:55",
"gha_language": "C",
"gha_license_id": null,
"github_id": 147788989,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 10395,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/SampleCode/StdDriver/EADC_ResultMonitor/main.c",
"provenance": "stackv2-0108.json.gz:81176",
"repo_name": "OpenNuvoton/M2351BSP",
"revision_date": "2023-07-31T07:24:56",
"revision_id": "ed73bdd5bac5de58faa1c9b799665a734f168a6a",
"snapshot_id": "0a8f86be7b333938a53f7d07841bca616f02df33",
"src_encoding": "UTF-8",
"star_events_count": 17,
"url": "https://raw.githubusercontent.com/OpenNuvoton/M2351BSP/ed73bdd5bac5de58faa1c9b799665a734f168a6a/SampleCode/StdDriver/EADC_ResultMonitor/main.c",
"visit_date": "2023-08-08T22:10:13.183590"
} | stackv2 | /**************************************************************************//**
* @file main.c
* @version V3.00
* @brief Monitor the conversion result of channel 2 by the digital compare function.
*
* @copyright (C) 2017 Nuvoton Technology Corp. All rights reserved.
******************************************************************************/
#include <stdio.h>
#include "NuMicro.h"
/*---------------------------------------------------------------------------------------------------------*/
/* Define global variables and constants */
/*---------------------------------------------------------------------------------------------------------*/
static volatile uint32_t s_u32AdcCmp0IntFlag;
static volatile uint32_t s_u32AdcCmp1IntFlag;
/*---------------------------------------------------------------------------------------------------------*/
/* Define functions prototype */
/*---------------------------------------------------------------------------------------------------------*/
int32_t main(void);
void EADC_FunctionTest(void);
void SYS_Init(void);
void UART0_Init(void);
void EADC3_IRQHandler(void);
void SYS_Init(void)
{
/* Set PF multi-function pins for XT1_OUT(PF.2) and XT1_IN(PF.3) */
SYS->GPF_MFPL = (SYS->GPF_MFPL & (~SYS_GPF_MFPL_PF2MFP_Msk)) | XT1_OUT_PF2;
SYS->GPF_MFPL = (SYS->GPF_MFPL & (~SYS_GPF_MFPL_PF3MFP_Msk)) | XT1_IN_PF3;
/*---------------------------------------------------------------------------------------------------------*/
/* Init System Clock */
/*---------------------------------------------------------------------------------------------------------*/
/* Enable HIRC clock (Internal RC 12MHz) */
CLK_EnableXtalRC(CLK_PWRCTL_HIRCEN_Msk);
/* Wait for HIRC clock ready */
CLK_WaitClockReady(CLK_STATUS_HIRCSTB_Msk);
/* Select HCLK clock source as HIRC and HCLK source divider as 1 */
CLK_SetHCLK(CLK_CLKSEL0_HCLKSEL_HIRC, CLK_CLKDIV0_HCLK(1));
/* Enable HXT clock (external XTAL 12MHz) */
CLK_EnableXtalRC(CLK_PWRCTL_HXTEN_Msk);
/* Wait for HXT clock ready */
CLK_WaitClockReady(CLK_STATUS_HXTSTB_Msk);
/* Enable PLL */
CLK->PLLCTL = CLK_PLLCTL_128MHz_HIRC;
/* Waiting for PLL stable */
CLK_WaitClockReady(CLK_STATUS_PLLSTB_Msk);
/* Select HCLK clock source as PLL and HCLK source divider as 2 */
CLK_SetHCLK(CLK_CLKSEL0_HCLKSEL_PLL, CLK_CLKDIV0_HCLK(2));
/* Enable UART module clock */
CLK_EnableModuleClock(UART0_MODULE);
/* Select UART module clock source as HXT and UART module clock divider as 1 */
CLK_SetModuleClock(UART0_MODULE, CLK_CLKSEL1_UART0SEL_HXT, CLK_CLKDIV0_UART0(1));
/* Enable EADC module clock */
CLK_EnableModuleClock(EADC_MODULE);
/* EADC clock source is 64MHz, set divider to 8, ADC clock is 64/8 MHz */
CLK_SetModuleClock(EADC_MODULE, 0, CLK_CLKDIV0_EADC(8));
/*---------------------------------------------------------------------------------------------------------*/
/* Init I/O Multi-function */
/*---------------------------------------------------------------------------------------------------------*/
/* Set multi-function pins for UART0 RXD and TXD */
SYS->GPB_MFPH = (SYS->GPB_MFPH & (~(UART0_RXD_PB12_Msk | UART0_TXD_PB13_Msk))) | UART0_RXD_PB12 | UART0_TXD_PB13;
/* Configure the GPB0 - GPB3 ADC analog input pins. */
SYS->GPB_MFPL = (SYS->GPB_MFPL & ~(SYS_GPB_MFPL_PB0MFP_Msk)) | EADC0_CH0_PB0;
SYS->GPB_MFPL = (SYS->GPB_MFPL & ~(SYS_GPB_MFPL_PB1MFP_Msk)) | EADC0_CH1_PB1;
SYS->GPB_MFPL = (SYS->GPB_MFPL & ~(SYS_GPB_MFPL_PB2MFP_Msk)) | EADC0_CH2_PB2;
SYS->GPB_MFPL = (SYS->GPB_MFPL & ~(SYS_GPB_MFPL_PB3MFP_Msk)) | EADC0_CH3_PB3;
/* Disable the GPB0 - GPB3 digital input path to avoid the leakage current. */
GPIO_DISABLE_DIGITAL_PATH(PB, BIT3 | BIT2 | BIT1 | BIT0);
}
void UART0_Init()
{
/*---------------------------------------------------------------------------------------------------------*/
/* Init UART */
/*---------------------------------------------------------------------------------------------------------*/
/* Configure UART0 and set UART0 baud rate */
UART_Open(UART0, 115200);
}
/*---------------------------------------------------------------------------------------------------------*/
/* EADC function test */
/*---------------------------------------------------------------------------------------------------------*/
void EADC_FunctionTest()
{
uint32_t u32TimeOutCnt;
printf("\n");
printf("+----------------------------------------------------------------------+\n");
printf("| EADC compare function (result monitor) sample code |\n");
printf("+----------------------------------------------------------------------+\n");
printf("\nIn this test, software will compare the conversion result of channel 2.\n");
/* Set input mode as single-end and enable the A/D converter */
EADC_Open(EADC, EADC_CTL_DIFFEN_SINGLE_END);
/* Configure the sample module 0 for analog input channel 2 and ADINT0 trigger source */
EADC_ConfigSampleModule(EADC, 0, EADC_ADINT0_TRIGGER, 2);
/* Enable EADC comparator 0. Compare condition: conversion result < 0x800; match Count=5 */
printf(" Set the compare condition of comparator 0: channel 2 is less than 0x800; match count is 5.\n");
EADC_ENABLE_CMP0(EADC, 0, EADC_CMP_CMPCOND_LESS_THAN, 0x800, 5);
/* Enable EADC comparator 1. Compare condition: conversion result >= 0x800; match Count=5 */
printf(" Set the compare condition of comparator 1 : channel 2 is greater than or equal to 0x800; match count is 5.\n");
EADC_ENABLE_CMP1(EADC, 0, EADC_CMP_CMPCOND_GREATER_OR_EQUAL, 0x800, 5);
/* Enable sample module 0 for ADINT0 */
EADC_ENABLE_SAMPLE_MODULE_INT(EADC, 0, BIT0);
/* Enable ADINT0 interrupt */
EADC_ENABLE_INT(EADC, BIT0);
/* Clear the A/D ADINT3 interrupt flag for safe */
EADC_CLR_INT_FLAG(EADC, EADC_STATUS2_ADIF3_Msk);
/* Enable sample module 0 for ADINT3 */
EADC_ENABLE_SAMPLE_MODULE_INT(EADC, 3, BIT0);
/* Enable ADINT3 interrupt */
EADC_ENABLE_INT(EADC, BIT3);
NVIC_EnableIRQ(EADC3_IRQn);
/* Clear the EADC comparator 0 interrupt flag for safe */
EADC_CLR_INT_FLAG(EADC, EADC_STATUS2_ADCMPF0_Msk);
/* Enable ADC comparator 0 interrupt */
EADC_ENABLE_CMP_INT(EADC, 0);
/* Clear the EADC comparator 1 interrupt flag for safe */
EADC_CLR_INT_FLAG(EADC, EADC_STATUS2_ADCMPF1_Msk);
/* Enable ADC comparator 1 interrupt */
EADC_ENABLE_CMP_INT(EADC, 1);
/* Reset the EADC interrupt indicator and trigger sample module 0 to start A/D conversion */
s_u32AdcCmp0IntFlag = 0;
s_u32AdcCmp1IntFlag = 0;
EADC_START_CONV(EADC, BIT0);
/* Wait EADC compare interrupt */
u32TimeOutCnt = SystemCoreClock; /* 1 second time-out */
while((s_u32AdcCmp0IntFlag == 0) && (s_u32AdcCmp1IntFlag == 0))
{
if(--u32TimeOutCnt == 0)
{
printf("Wait for EADC compare interrupt time-out!\n");
return;
}
}
/* Disable the sample module 0 interrupt */
EADC_DISABLE_SAMPLE_MODULE_INT(EADC, 0, BIT0);
/* Disable ADC comparator interrupt */
EADC_DISABLE_CMP_INT(EADC, 0);
EADC_DISABLE_CMP_INT(EADC, 1);
/* Disable compare function */
EADC_DISABLE_CMP0(EADC);
EADC_DISABLE_CMP1(EADC);
if(s_u32AdcCmp0IntFlag == 1)
{
printf("Comparator 0 interrupt occurs.\nThe conversion result of channel 2 is less than 0x800\n");
}
else
{
printf("Comparator 1 interrupt occurs.\nThe conversion result of channel 2 is greater than or equal to 0x800\n");
}
}
/*---------------------------------------------------------------------------------------------------------*/
/* EADC interrupt handler */
/*---------------------------------------------------------------------------------------------------------*/
void EADC3_IRQHandler(void)
{
if(EADC_GET_INT_FLAG(EADC, EADC_STATUS2_ADCMPF0_Msk))
{
s_u32AdcCmp0IntFlag = 1;
/* Clear the A/D compare flag 0 */
EADC_CLR_INT_FLAG(EADC, EADC_STATUS2_ADCMPF0_Msk);
}
if(EADC_GET_INT_FLAG(EADC, EADC_STATUS2_ADCMPF1_Msk))
{
s_u32AdcCmp1IntFlag = 1;
/* Clear the A/D compare flag 1 */
EADC_CLR_INT_FLAG(EADC, EADC_STATUS2_ADCMPF1_Msk);
}
EADC_CLR_INT_FLAG(EADC, EADC_STATUS2_ADIF3_Msk);
}
/*---------------------------------------------------------------------------------------------------------*/
/* Main Function */
/*---------------------------------------------------------------------------------------------------------*/
int32_t main(void)
{
/* Unlock protected registers */
SYS_UnlockReg();
/* Init System, IP clock and multi-function I/O */
SYS_Init();
/* Lock protected registers */
SYS_LockReg();
/* Init UART0 for printf */
UART0_Init();
/*---------------------------------------------------------------------------------------------------------*/
/* SAMPLE CODE */
/*---------------------------------------------------------------------------------------------------------*/
printf("\nSystem clock rate: %d Hz", SystemCoreClock);
/* EADC function test */
EADC_FunctionTest();
/* Reset EADC module */
SYS_ResetModule(EADC_RST);
/* Disable EADC IP clock */
CLK_DisableModuleClock(EADC_MODULE);
/* Disable External Interrupt */
NVIC_DisableIRQ(EADC3_IRQn);
printf("Exit EADC sample code\n");
while(1);
}
/*** (C) COPYRIGHT 2017 Nuvoton Technology Corp. ***/
| 2.09375 | 2 |
2024-11-18T22:48:51.473063+00:00 | 2018-05-05T16:20:49 | 6660995a851be6f25cd5ec3eca62c2f02c08e75f | {
"blob_id": "6660995a851be6f25cd5ec3eca62c2f02c08e75f",
"branch_name": "refs/heads/master",
"committer_date": "2018-05-05T16:20:49",
"content_id": "faf809e0473f82712d6a7bebcf1c9440e4ad7f72",
"detected_licenses": [
"MIT",
"NCSA",
"BSD-3-Clause"
],
"directory_id": "9a57b6283a7d8357a2ed46e0f69e2a269b33caf1",
"extension": "c",
"filename": "EVMModule.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 132134149,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 784,
"license": "MIT,NCSA,BSD-3-Clause",
"license_type": "permissive",
"path": "/capstone/arch/EVM/EVMModule.c",
"provenance": "stackv2-0108.json.gz:81304",
"repo_name": "BaDSeED-SEC/capstone-sys",
"revision_date": "2018-05-05T16:20:49",
"revision_id": "215d8776c370d993d9df9510cac04bed0e007ef5",
"snapshot_id": "874818388d30bc775b689aa6f1154cb82ba3351c",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/BaDSeED-SEC/capstone-sys/215d8776c370d993d9df9510cac04bed0e007ef5/capstone/arch/EVM/EVMModule.c",
"visit_date": "2020-03-15T11:59:35.542888"
} | stackv2 | /* Capstone Disassembly Engine */
/* By Nguyen Anh Quynh, 2018 */
#ifdef CAPSTONE_HAS_ARM
#include "../../cs_priv.h"
#include "EVMDisassembler.h"
#include "EVMInstPrinter.h"
#include "EVMMapping.h"
static cs_err init(cs_struct *ud)
{
// verify if requested mode is valid
if (ud->mode)
return CS_ERR_MODE;
ud->printer = EVM_printInst;
ud->printer_info = NULL;
ud->insn_id = EVM_get_insn_id;
ud->insn_name = EVM_insn_name;
ud->group_name = EVM_group_name;
ud->disasm = EVM_getInstruction;
return CS_ERR_OK;
}
static cs_err option(cs_struct *handle, cs_opt_type type, size_t value)
{
return CS_ERR_OK;
}
void EVM_enable(void)
{
cs_arch_init[CS_ARCH_EVM] = init;
cs_arch_option[CS_ARCH_EVM] = option;
// support this arch
all_arch |= (1 << CS_ARCH_EVM);
}
#endif
| 2.21875 | 2 |
2024-11-18T22:48:51.568573+00:00 | 2015-03-05T14:12:50 | 955005bb7aa1b19c7fb71e64bac2399a4eb91088 | {
"blob_id": "955005bb7aa1b19c7fb71e64bac2399a4eb91088",
"branch_name": "refs/heads/master",
"committer_date": "2015-03-05T14:12:50",
"content_id": "6a95b70beedfad4309e310fde3a27301843add2c",
"detected_licenses": [
"MIT"
],
"directory_id": "253887e47968a529fabab518b44fecfa8854a048",
"extension": "h",
"filename": "vm.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 31717041,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 7448,
"license": "MIT",
"license_type": "permissive",
"path": "/src/libseptvm/vm/vm.h",
"provenance": "stackv2-0108.json.gz:81436",
"repo_name": "krajzeg/september",
"revision_date": "2015-03-05T14:12:50",
"revision_id": "109f4deea8175119e7d7aae77e2de741308d7f36",
"snapshot_id": "c8196e95684e31f815f53c0ece6b4635a76af21c",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/krajzeg/september/109f4deea8175119e7d7aae77e2de741308d7f36/src/libseptvm/vm/vm.h",
"visit_date": "2021-01-19T10:22:44.167306"
} | stackv2 | #ifndef _SEP_VM_H
#define _SEP_VM_H
/*****************************************************************
**
** runtime/vm.h
**
** Virtual machine structures.
**
***************
** September **
*****************************************************************/
// ===============================================================
// Includes
// ===============================================================
#include "types.h"
#include "functions.h"
#include "objects.h"
#include "arrays.h"
#include "stack.h"
#include "module.h"
// ===============================================================
// Pre-defining structs
// ===============================================================
struct SepVM;
struct SepArray;
struct GarbageCollection;
struct ExecutionFrame;
struct ArgumentSource;
// ===============================================================
// Constants
// ===============================================================
// the maximum call depth allowed - the number of execution frames per VM
#define VM_FRAME_COUNT 1024
// ===============================================================
// Execution frame
// ===============================================================
typedef struct ExecutionFrame {
// the VM responsible for this frame
struct SepVM *vm;
// the module this frame comes from
SepModule *module;
// function for this frame
SepFunc *function;
// instruction pointer
CodeUnit *instruction_ptr;
// the data stack accessed by VM operations
SepStack *data;
// execution scope
SepV locals;
// return value from this frame
SepItem return_value;
// execution finished?
bool finished;
// execution called into another frame?
bool called_another_frame;
// an array of objects allocated in this frame
// all objects allocated within a frame have to be kept until
// the frame finishes execution, so they are added as GC roots
// during garbage collection
GenericArray gc_roots;
// These pointers are set up by the VM to make up a linked
// list of frames.
struct ExecutionFrame *next_frame;
struct ExecutionFrame *prev_frame;
} ExecutionFrame;
// Execute instructions from this frame, up to a given limit.
int frame_execute_instructions(ExecutionFrame *frame, int limit);
// Reads the next code unit from this frame.
CodeUnit frame_read(ExecutionFrame *frame);
// Read a constant from this frame's module.
SepV frame_constant(ExecutionFrame *frame, uint32_t index);
// Get a code block from this frame's module.
CodeBlock *frame_block(ExecutionFrame *frame, uint32_t index);
// Finalize this frame with a given return value.
void frame_return(ExecutionFrame *frame, SepItem return_value);
// Raise an exception inside a frame and finalizes it.
void frame_raise(ExecutionFrame *frame, SepV exception);
// Registers a value as a GC root to prevent it from being freed before its unused.
void frame_register(ExecutionFrame *frame, SepV value);
// Releases a value previously held in the frame's GC root table,
// making it eligible for garbage collection again.
void frame_release(ExecutionFrame *frame, SepV value);
// ===============================================================
// The virtual machine
// ===============================================================
typedef struct SepVM {
// the data stack shared by all execution frames
SepStack *data;
// the whole execution stack, with the main function of the main
// module at the bottom, and the current function at the top
ExecutionFrame frames[VM_FRAME_COUNT];
// how deep the frame currently executed is
int frame_depth;
} SepVM;
// Creates a new VM for running a specified September module.
SepVM *vm_create(SepModule *module);
// Runs the VM until it halts, either by finishing execution normally
// or terminating with an exception. Either way, whatever is the final
// result on the stack, is returned.
SepItem vm_run(SepVM *this);
// Initializes the root execution frame based on a module.
void vm_initialize_root_frame(SepVM *this, SepModule *module);
// Initializes a scope object for execution of a given function. This sets up
// the prototype chain for the scope to include the 'this'
// pointer, and the declaration scope of the function. It also sets up the
// 'locals' and 'this' properties.
void vm_initialize_scope(SepVM *this, SepFunc *func, SepObj *exec_scope, ExecutionFrame *exec_frame);
// Called instead of vm_initialize_scope when a custom scope object is to be used.
void vm_set_scope(ExecutionFrame *exec_frame, SepV custom_scope);
// Initializes an execution frame for running a given function.
// It takes as arguments the frame to initialize and the function to run within the frame.
// The execution scope should be set up separately afterwards using vm_initialize_scope/vm_set_scope.
void vm_initialize_frame(SepVM *this, ExecutionFrame *frame, SepFunc *func);
// Destroys a VM.
void vm_free(SepVM *this);
// ===============================================================
// Global access to VM instances
// ===============================================================
// Returns the VM currently used running in this thread. Only one SepVM instance is
// allowed per thread.
SepVM *vm_current();
// Returns the current execution frame in the current thread.
ExecutionFrame *vm_current_frame();
// ===============================================================
// Garbage collection
// ===============================================================
// Queues all the objects directly reachable from any of the currently running VMs for
// marking in the garbage collection process.
void vm_queue_gc_roots(struct GarbageCollection *gc);
// ===============================================================
// Invoking function calls from C code
// ===============================================================
// Makes a subcall from within a built-in function. The result of the subcall is then returned.
// Any number of arguments can be passed in, and they should be passed as SepVs.
SepItem vm_invoke(SepVM *this, SepV callable, uint8_t argument_count, ...);
// Makes a subcall, but runs the callable in a specified scope (instead of using a normal
// this + declaration scope + locals scope). Any arguments passed will be added to the
// scope you specify.
SepItem vm_invoke_in_scope(SepVM *this, SepV callable, SepV execution_scope, uint8_t argument_count, ...);
// Makes a subcall from within a built-in function. The result of the subcall is then returned.
// An argument source with the arguments of this call has to be provided.
SepItem vm_invoke_with_argsource(SepVM *this, SepV callable, SepV custom_scope, struct ArgumentSource *args);
// ===============================================================
// Resolving lazy values
// ===============================================================
// Uses the VM to resolve a lazy value.
SepV vm_resolve(SepVM *this, SepV lazy_value);
// Uses the VM to resolve a lazy value in a specified scope (instead
// of in its parent scope). Used together with SEPV_LITERALS allows
// resolving expressions like 'name' to the string "name".
SepV vm_resolve_in(SepVM *this, SepV lazy_value, SepV scope);
// Uses the VM to resolve a lazy value to the identifier that it names.
// This uses a special "Literals" scope in which every identifier resolves
// to itself.
SepV vm_resolve_as_literal(SepVM *this, SepV lazy_value);
/*****************************************************************/
#endif
| 2.328125 | 2 |
2024-11-18T22:48:54.631011+00:00 | 2020-04-06T03:01:34 | 8453c7f415e7f12176713ee798fc462e9b9426a5 | {
"blob_id": "8453c7f415e7f12176713ee798fc462e9b9426a5",
"branch_name": "refs/heads/master",
"committer_date": "2020-04-06T03:01:34",
"content_id": "115abdd3eed31d8ab8e851623ee213f4bbfb5324",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "e7c6f77ede337fee8f2af1d77e2bbf24627d2ec7",
"extension": "h",
"filename": "SceneModelNode.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": 4119,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/modules/Scene/include/DeepSea/Scene/Nodes/SceneModelNode.h",
"provenance": "stackv2-0108.json.gz:81821",
"repo_name": "blockspacer/DeepSea",
"revision_date": "2020-04-06T03:01:34",
"revision_id": "960237e3fff5dd4a7fa32cb4057a4397319bc279",
"snapshot_id": "3c2488e39bd1a85c8b02b7b53651ab6fb69153e9",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/blockspacer/DeepSea/960237e3fff5dd4a7fa32cb4057a4397319bc279/modules/Scene/include/DeepSea/Scene/Nodes/SceneModelNode.h",
"visit_date": "2021-05-24T18:19:57.018596"
} | stackv2 | /*
* Copyright 2019 Aaron Barany
*
* 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.
*/
#pragma once
#include <DeepSea/Core/Config.h>
#include <DeepSea/Scene/Nodes/Types.h>
#include <DeepSea/Scene/Export.h>
#ifdef __cplusplus
extern "C"
{
#endif
/**
* @file
* @brief Functions for creating and manipulating model nodes.
* @see dsSceneModelNode
*/
/**
* @brief The type name for a model node.
*/
DS_SCENE_EXPORT extern const char* const dsSceneModelNode_typeName;
/**
* @brief Gets the type of a model node.
* @return The type of a model node.
*/
DS_SCENE_EXPORT const dsSceneNodeType* dsSceneModelNode_type(void);
/**
* @brief Creates a scene model node.
*
* @remark The same item list name may appear multiple times in the model list, but the extra item
* list is expected to contain unique names.
*
* @remark errno will be set on failure.
* @param allocator The allocator to create the model node with.
* @param models The models to draw within the node. The array will be copied. It is expected that
* at least one model is provided.
* @param modelCount The number of models.
* @param extraItemLists List of item list names to add the node to. This is in addition to the list
* of draw lists from the models array, such as for cull lists. The array will be copied.
* @param extraItemListCount The number of item lists.
* @param resources The resources to keep a reference to.
* @param resourceCount The number of resources.
* @param bounds The bounding box for the model. If NULL, the model will never be culled.
* @return The model node or NULL if an error occurred.
*/
DS_SCENE_EXPORT dsSceneModelNode* dsSceneModelNode_create(dsAllocator* allocator,
const dsSceneModelInitInfo* models, uint32_t modelCount, const char** extraItemLists,
uint32_t extraItemListCount, dsSceneResources** resources, uint32_t resourceCount,
const dsOrientedBox3f* bounds);
/**
* @brief Creates a scene node as a base class of another node type.
*
* @remark The same item list name may appear multiple times in the model list, but the extra item
* list is expected to contain unique names.
*
* @remark errno will be set on failure.
* @param allocator The allocator to create the model node with.
* @param structSize The size of the struct.
* @param models The models to draw within the node. The array will be copied. It is expected that
* at least one model is provided.
* @param modelCount The number of models.
* @param extraItemLists List of item list names to add the node to. This is in addition to the list
* of draw lists from the models array, such as for cull lists. The array will be copied.
* @param extraItemListCount The number of item lists.
* @param resources The resources to keep a reference to.
* @param resourceCount The number of resources.
* @param bounds The bounding box for the model. If NULL, the model will never be culled.
* @return The model node or NULL if an error occurred.
*/
DS_SCENE_EXPORT dsSceneModelNode* dsSceneModelNode_createBase(dsAllocator* allocator,
size_t structSize, const dsSceneModelInitInfo* models, uint32_t modelCount,
const char** extraItemLists, uint32_t extraItemListCount, dsSceneResources** resources,
uint32_t resourceCount, const dsOrientedBox3f* bounds);
/**
* @brief Destroys a model node.
* @remark This should only be called as part of a subclass' destroy function, never to explicitly
* a model node instance since nodes are reference counted.
* @param node The node to destroy.
*/
DS_SCENE_EXPORT void dsSceneModelNode_destroy(dsSceneNode* node);
#ifdef __cplusplus
}
#endif
| 2.046875 | 2 |
2024-11-18T22:48:54.707119+00:00 | 2020-11-28T17:28:44 | 0c107fd65a37e7ba71ee2cafc0ef6c824a251ad6 | {
"blob_id": "0c107fd65a37e7ba71ee2cafc0ef6c824a251ad6",
"branch_name": "refs/heads/main",
"committer_date": "2020-11-28T17:28:44",
"content_id": "a827aab768c36fd07c044ba9218ff1db8e5f29de",
"detected_licenses": [
"MIT"
],
"directory_id": "a463bb0ae143987991f5fc267062265c581bff99",
"extension": "c",
"filename": "utils.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 316784297,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 9110,
"license": "MIT",
"license_type": "permissive",
"path": "/tuv/utils.c",
"provenance": "stackv2-0108.json.gz:81951",
"repo_name": "javalikescript/qjs-uv",
"revision_date": "2020-11-28T17:28:44",
"revision_id": "21f163c5613a6c3e638c5d4334672b673dd08389",
"snapshot_id": "be2d9299975a4af0c622ca182fa5e4f6cad4afc9",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/javalikescript/qjs-uv/21f163c5613a6c3e638c5d4334672b673dd08389/tuv/utils.c",
"visit_date": "2023-01-14T01:16:03.754623"
} | stackv2 |
/*
* QuickJS libuv bindings
*
* Copyright (c) 2019-present Saúl Ibarra Corretgé <s@saghul.net>
*
* 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 "utils.h"
#include "private.h"
#include "tjs.h"
#include <stdlib.h>
#include <string.h>
void tjs_assert(const struct AssertionInfo info) {
fprintf(stderr,
"%s:%s%s Assertion `%s' failed.\n",
info.file_line,
info.function,
*info.function ? ":" : "",
info.message);
fflush(stderr);
abort();
}
uv_loop_t *tjs_get_loop(JSContext *ctx) {
TJSRuntime *qrt = TJS_GetRuntime(ctx);
CHECK_NOT_NULL(qrt);
return TJS_GetLoop(qrt);
}
int tjs_obj2addr(JSContext *ctx, JSValueConst obj, struct sockaddr_storage *ss) {
JSValue js_ip;
JSValue js_port;
const char *ip;
uint32_t port;
int r;
js_ip = JS_GetPropertyStr(ctx, obj, "ip");
ip = JS_ToCString(ctx, js_ip);
JS_FreeValue(ctx, js_ip);
if (!ip) {
return -1;
}
js_port = JS_GetPropertyStr(ctx, obj, "port");
r = JS_ToUint32(ctx, &port, js_port);
JS_FreeValue(ctx, js_port);
if (r != 0) {
return -1;
}
memset(ss, 0, sizeof(*ss));
if (uv_inet_pton(AF_INET, ip, &((struct sockaddr_in *) ss)->sin_addr) == 0) {
ss->ss_family = AF_INET;
((struct sockaddr_in *) ss)->sin_port = htons(port);
} else if (uv_inet_pton(AF_INET6, ip, &((struct sockaddr_in6 *) ss)->sin6_addr) == 0) {
ss->ss_family = AF_INET6;
((struct sockaddr_in6 *) ss)->sin6_port = htons(port);
} else {
tjs_throw_errno(ctx, UV_EAFNOSUPPORT);
JS_FreeCString(ctx, ip);
return -1;
}
JS_FreeCString(ctx, ip);
return 0;
}
JSValue tjs_addr2obj(JSContext *ctx, const struct sockaddr *sa) {
char buf[INET6_ADDRSTRLEN + 1];
JSValue obj;
switch (sa->sa_family) {
case AF_INET: {
struct sockaddr_in *addr4 = (struct sockaddr_in *) sa;
uv_ip4_name(addr4, buf, sizeof(buf));
obj = JS_NewObjectProto(ctx, JS_NULL);
JS_DefinePropertyValueStr(ctx, obj, "family", JS_NewInt32(ctx, AF_INET), JS_PROP_C_W_E);
JS_DefinePropertyValueStr(ctx, obj, "ip", JS_NewString(ctx, buf), JS_PROP_C_W_E);
JS_DefinePropertyValueStr(ctx, obj, "port", JS_NewInt32(ctx, ntohs(addr4->sin_port)), JS_PROP_C_W_E);
return obj;
}
case AF_INET6: {
struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *) sa;
uv_ip6_name(addr6, buf, sizeof(buf));
obj = JS_NewObjectProto(ctx, JS_NULL);
JS_DefinePropertyValueStr(ctx, obj, "family", JS_NewInt32(ctx, AF_INET6), JS_PROP_C_W_E);
JS_DefinePropertyValueStr(ctx, obj, "ip", JS_NewString(ctx, buf), JS_PROP_C_W_E);
JS_DefinePropertyValueStr(ctx, obj, "port", JS_NewInt32(ctx, ntohs(addr6->sin6_port)), JS_PROP_C_W_E);
JS_DefinePropertyValueStr(ctx,
obj,
"flowinfo",
JS_NewInt32(ctx, ntohl(addr6->sin6_flowinfo)),
JS_PROP_C_W_E);
JS_DefinePropertyValueStr(ctx, obj, "scopeId", JS_NewInt32(ctx, addr6->sin6_scope_id), JS_PROP_C_W_E);
return obj;
}
default:
/* If we don't know the address family, don't raise an exception -- return undefined. */
return JS_UNDEFINED;
}
}
static void tjs_dump_obj(JSContext *ctx, FILE *f, JSValueConst val) {
const char *str = JS_ToCString(ctx, val);
if (str) {
fprintf(f, "%s\n", str);
JS_FreeCString(ctx, str);
} else {
fprintf(f, "[exception]\n");
}
}
void tjs_dump_error(JSContext *ctx) {
JSValue exception_val = JS_GetException(ctx);
tjs_dump_error1(ctx, exception_val);
JS_FreeValue(ctx, exception_val);
}
void tjs_dump_error1(JSContext *ctx, JSValueConst exception_val) {
int is_error = JS_IsError(ctx, exception_val);
tjs_dump_obj(ctx, stderr, exception_val);
if (is_error) {
JSValue val = JS_GetPropertyStr(ctx, exception_val, "stack");
if (!JS_IsUndefined(val))
tjs_dump_obj(ctx, stderr, val);
JS_FreeValue(ctx, val);
}
}
void tjs_call_handler(JSContext *ctx, JSValueConst func) {
JSValue ret, func1;
/* 'func' might be destroyed when calling itself (if it frees the
handler), so must take extra care */
func1 = JS_DupValue(ctx, func);
ret = JS_Call(ctx, func1, JS_UNDEFINED, 0, NULL);
JS_FreeValue(ctx, func1);
if (JS_IsException(ret))
tjs_dump_error(ctx);
JS_FreeValue(ctx, ret);
}
void JS_FreePropEnum(JSContext *ctx, JSPropertyEnum *tab, uint32_t len) {
uint32_t i;
if (tab) {
for (i = 0; i < len; i++)
JS_FreeAtom(ctx, tab[i].atom);
js_free(ctx, tab);
}
}
JSValue TJS_InitPromise(JSContext *ctx, TJSPromise *p) {
JSValue rfuncs[2];
p->p = JS_NewPromiseCapability(ctx, rfuncs);
if (JS_IsException(p->p))
return JS_EXCEPTION;
p->rfuncs[0] = JS_DupValue(ctx, rfuncs[0]);
p->rfuncs[1] = JS_DupValue(ctx, rfuncs[1]);
return JS_DupValue(ctx, p->p);
}
bool TJS_IsPromisePending(JSContext *ctx, TJSPromise *p) {
return !JS_IsUndefined(p->p);
}
void TJS_FreePromise(JSContext *ctx, TJSPromise *p) {
JS_FreeValue(ctx, p->rfuncs[0]);
JS_FreeValue(ctx, p->rfuncs[1]);
JS_FreeValue(ctx, p->p);
}
void TJS_FreePromiseRT(JSRuntime *rt, TJSPromise *p) {
JS_FreeValueRT(rt, p->rfuncs[0]);
JS_FreeValueRT(rt, p->rfuncs[1]);
JS_FreeValueRT(rt, p->p);
}
void TJS_ClearPromise(JSContext *ctx, TJSPromise *p) {
p->p = JS_UNDEFINED;
p->rfuncs[0] = JS_UNDEFINED;
p->rfuncs[1] = JS_UNDEFINED;
}
void TJS_MarkPromise(JSRuntime *rt, TJSPromise *p, JS_MarkFunc *mark_func) {
JS_MarkValue(rt, p->p, mark_func);
JS_MarkValue(rt, p->rfuncs[0], mark_func);
JS_MarkValue(rt, p->rfuncs[1], mark_func);
}
void TJS_SettlePromise(JSContext *ctx, TJSPromise *p, bool is_reject, int argc, JSValueConst *argv) {
JSValue ret = JS_Call(ctx, p->rfuncs[is_reject], JS_UNDEFINED, argc, argv);
for (int i = 0; i < argc; i++)
JS_FreeValue(ctx, argv[i]);
JS_FreeValue(ctx, ret); /* XXX: what to do if exception ? */
JS_FreeValue(ctx, p->rfuncs[0]);
JS_FreeValue(ctx, p->rfuncs[1]);
TJS_FreePromise(ctx, p);
}
void TJS_ResolvePromise(JSContext *ctx, TJSPromise *p, int argc, JSValueConst *argv) {
TJS_SettlePromise(ctx, p, false, argc, argv);
}
void TJS_RejectPromise(JSContext *ctx, TJSPromise *p, int argc, JSValueConst *argv) {
TJS_SettlePromise(ctx, p, true, argc, argv);
}
static inline JSValue tjs__settled_promise(JSContext *ctx, bool is_reject, int argc, JSValueConst *argv) {
JSValue promise, resolving_funcs[2], ret;
promise = JS_NewPromiseCapability(ctx, resolving_funcs);
if (JS_IsException(promise))
return JS_EXCEPTION;
ret = JS_Call(ctx, resolving_funcs[is_reject], JS_UNDEFINED, argc, argv);
for (int i = 0; i < argc; i++)
JS_FreeValue(ctx, argv[i]);
JS_FreeValue(ctx, ret);
JS_FreeValue(ctx, resolving_funcs[0]);
JS_FreeValue(ctx, resolving_funcs[1]);
return promise;
}
JSValue TJS_NewResolvedPromise(JSContext *ctx, int argc, JSValueConst *argv) {
return tjs__settled_promise(ctx, false, argc, argv);
}
JSValue TJS_NewRejectedPromise(JSContext *ctx, int argc, JSValueConst *argv) {
return tjs__settled_promise(ctx, true, argc, argv);
}
static void tjs__buf_free(JSRuntime *rt, void *opaque, void *ptr) {
js_free_rt(rt, ptr);
}
JSValue TJS_NewUint8Array(JSContext *ctx, uint8_t *data, size_t size) {
JSValue abuf = JS_NewArrayBuffer(ctx, data, size, tjs__buf_free, NULL, false);
if (JS_IsException(abuf))
return abuf;
TJSRuntime *qrt = TJS_GetRuntime(ctx);
CHECK_NOT_NULL(qrt);
JSValue buf = JS_CallConstructor(ctx, qrt->builtins.u8array_ctor, 1, &abuf);
JS_FreeValue(ctx, abuf);
return buf;
}
| 2.03125 | 2 |
2024-11-18T22:48:54.930327+00:00 | 2019-04-18T11:01:15 | 1e890944ed5d1187bf4e203104d9edce5ddc3e26 | {
"blob_id": "1e890944ed5d1187bf4e203104d9edce5ddc3e26",
"branch_name": "refs/heads/master",
"committer_date": "2019-04-18T11:01:15",
"content_id": "f6b02d5d788a13fb962a2edb666a2227de4bd0b3",
"detected_licenses": [
"MIT"
],
"directory_id": "be8464c4adc5da946660a8345a1adebf74f87f08",
"extension": "c",
"filename": "fcfs.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 182066905,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1910,
"license": "MIT",
"license_type": "permissive",
"path": "/xv6-public/fcfs.c",
"provenance": "stackv2-0108.json.gz:82212",
"repo_name": "JungDaeHan/Operating-System-assignment",
"revision_date": "2019-04-18T11:01:15",
"revision_id": "4a6f0795b5b065f8d1d71e8bdb89630d9e72d7ea",
"snapshot_id": "61ef9bbee16cdf5e0fdb1c0fcbeb29f957870139",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/JungDaeHan/Operating-System-assignment/4a6f0795b5b065f8d1d71e8bdb89630d9e72d7ea/xv6-public/fcfs.c",
"visit_date": "2020-05-15T03:21:58.801032"
} | stackv2 | #include "types.h"
#include "stat.h"
#include "user.h"
#define TEST_CHILD_NAME "p2_print_repeat"
#define TEST_CHILD_PRINTER 0
#define TEST_CHILD_SLEEPER 1
char* argv[][7] = {
{TEST_CHILD_NAME, "printer", "2000000", "400000", "0", "0" , 0},
{TEST_CHILD_NAME, "sleeper", "4000000", "400000", "400000", "1", 0},
};
void test_basic() {
int i;
for( i=0; i<5; i++) {
int pid = fork();
if (pid == 0) {
sleep(10); // wait for all children fork()ed
exec(TEST_CHILD_NAME, argv[TEST_CHILD_PRINTER]);
} else {
printf(1, "proc %d created\n", pid);
}
}
while(wait()!=-1); // wait all children
}
void test_sleep() {
int i;
for( i=0; i<5; i++) {
int pid = fork();
if (pid == 0) {
sleep(10); // wait for all children fork()ed
if (i == 0)
exec(TEST_CHILD_NAME, argv[TEST_CHILD_SLEEPER]);
else
exec(TEST_CHILD_NAME, argv[TEST_CHILD_PRINTER]);
} else {
printf(1, "proc %d created\n", pid);
}
}
while(wait()!=-1); // wait all children
}
int
main(int argc, char* argv[]) {
printf(1, "-----------test_basic----------\n");
test_basic();
printf(1, "-----------test_sleep----------\n");
test_sleep();
printf(1, "-----------test_finish----------\n");
exit();
}
| 2.59375 | 3 |
2024-11-18T22:48:55.349992+00:00 | 2023-08-22T19:34:56 | 759e7238ee36e256d58b22a60f18aacc516a32d0 | {
"blob_id": "759e7238ee36e256d58b22a60f18aacc516a32d0",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-22T19:34:56",
"content_id": "ebc05b45d0043a2392c0c757b04d85997a7408c3",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "0aa9dcb3cef817ec55eaa8fae2102106f939f594",
"extension": "c",
"filename": "ptmacosx_cf.c",
"fork_events_count": 15,
"gha_created_at": "2014-06-27T01:07:32",
"gha_event_created_at": "2023-06-28T20:53:49",
"gha_language": "C++",
"gha_license_id": "Apache-2.0",
"github_id": 21259864,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3802,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/control/midi/portmidi/porttime/ptmacosx_cf.c",
"provenance": "stackv2-0108.json.gz:82601",
"repo_name": "RTcmix/RTcmix",
"revision_date": "2023-08-22T19:34:56",
"revision_id": "4e89415929d7752f325b7813b5aae2a042c08e64",
"snapshot_id": "fd30a7d610b2b7b8688cbb5a6d77475201b8ad07",
"src_encoding": "UTF-8",
"star_events_count": 45,
"url": "https://raw.githubusercontent.com/RTcmix/RTcmix/4e89415929d7752f325b7813b5aae2a042c08e64/src/control/midi/portmidi/porttime/ptmacosx_cf.c",
"visit_date": "2023-08-30T23:23:48.806948"
} | stackv2 | /* ptmacosx.c -- portable timer implementation for mac os x */
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#include <CoreFoundation/CoreFoundation.h>
#import <mach/mach.h>
#import <mach/mach_error.h>
#import <mach/mach_time.h>
#import <mach/clock.h>
#include "porttime.h"
#define THREAD_IMPORTANCE 30
#define LONG_TIME 1000000000.0
static int time_started_flag = FALSE;
static CFAbsoluteTime startTime = 0.0;
static CFRunLoopRef timerRunLoop;
typedef struct {
int resolution;
PtCallback *callback;
void *userData;
} PtThreadParams;
void Pt_CFTimerCallback(CFRunLoopTimerRef timer, void *info)
{
PtThreadParams *params = (PtThreadParams*)info;
(*params->callback)(Pt_Time(), params->userData);
}
static void* Pt_Thread(void *p)
{
CFTimeInterval timerInterval;
CFRunLoopTimerContext timerContext;
CFRunLoopTimerRef timer;
PtThreadParams *params = (PtThreadParams*)p;
//CFTimeInterval timeout;
/* raise the thread's priority */
kern_return_t error;
thread_extended_policy_data_t extendedPolicy;
thread_precedence_policy_data_t precedencePolicy;
extendedPolicy.timeshare = 0;
error = thread_policy_set(mach_thread_self(), THREAD_EXTENDED_POLICY,
(thread_policy_t)&extendedPolicy,
THREAD_EXTENDED_POLICY_COUNT);
if (error != KERN_SUCCESS) {
mach_error("Couldn't set thread timeshare policy", error);
}
precedencePolicy.importance = THREAD_IMPORTANCE;
error = thread_policy_set(mach_thread_self(), THREAD_PRECEDENCE_POLICY,
(thread_policy_t)&precedencePolicy,
THREAD_PRECEDENCE_POLICY_COUNT);
if (error != KERN_SUCCESS) {
mach_error("Couldn't set thread precedence policy", error);
}
/* set up the timer context */
timerContext.version = 0;
timerContext.info = params;
timerContext.retain = NULL;
timerContext.release = NULL;
timerContext.copyDescription = NULL;
/* create a new timer */
timerInterval = (double)params->resolution / 1000.0;
timer = CFRunLoopTimerCreate(NULL, startTime+timerInterval, timerInterval,
0, 0, Pt_CFTimerCallback, &timerContext);
timerRunLoop = CFRunLoopGetCurrent();
CFRunLoopAddTimer(timerRunLoop, timer, CFSTR("PtTimeMode"));
/* run until we're told to stop by Pt_Stop() */
CFRunLoopRunInMode(CFSTR("PtTimeMode"), LONG_TIME, false);
CFRunLoopRemoveTimer(CFRunLoopGetCurrent(), timer, CFSTR("PtTimeMode"));
CFRelease(timer);
free(params);
return NULL;
}
PtError Pt_Start(int resolution, PtCallback *callback, void *userData)
{
// printf("Pt_Start() called\n");
// /* make sure we're not already playing */
if (time_started_flag) {
return ptAlreadyStarted;
}
PtThreadParams *params = (PtThreadParams*)malloc(sizeof(PtThreadParams));
pthread_t pthread_id;
startTime = CFAbsoluteTimeGetCurrent();
if (callback) {
params->resolution = resolution;
params->callback = callback;
params->userData = userData;
pthread_create(&pthread_id, NULL, Pt_Thread, params);
}
else {
free(params);
}
time_started_flag = TRUE;
return ptNoError;
}
PtError Pt_Stop()
{
// printf("Pt_Stop called\n");
CFRunLoopStop(timerRunLoop);
time_started_flag = FALSE;
return ptNoError;
}
int Pt_Started()
{
return time_started_flag;
}
PtTimestamp Pt_Time()
{
CFAbsoluteTime now = CFAbsoluteTimeGetCurrent();
return (PtTimestamp) ((now - startTime) * 1000.0);
}
| 2.640625 | 3 |
2024-11-18T22:48:55.528196+00:00 | 2020-05-16T06:11:21 | 32fce3df889f0f27f4b45cc440acb4ed4f626711 | {
"blob_id": "32fce3df889f0f27f4b45cc440acb4ed4f626711",
"branch_name": "refs/heads/master",
"committer_date": "2020-05-16T06:11:21",
"content_id": "a35f191909f0b6281614e35363bb73911f583b89",
"detected_licenses": [
"MIT"
],
"directory_id": "4a56b1d78920d5fda438e688d4ed7a1b01f66a02",
"extension": "c",
"filename": "resource_bunble_handler.c",
"fork_events_count": 3,
"gha_created_at": "2018-06-27T07:25:50",
"gha_event_created_at": "2020-05-15T20:20:12",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 138845316,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1482,
"license": "MIT",
"license_type": "permissive",
"path": "/src/api/resource_bunble_handler.c",
"provenance": "stackv2-0108.json.gz:82857",
"repo_name": "nomi-san/luacef",
"revision_date": "2020-05-16T06:11:21",
"revision_id": "9f35b62ae9952a1382fa38686abdb051a4ba8fd5",
"snapshot_id": "d3b9c6b48cefb589ac74cbd1e2c4f9365fd14a07",
"src_encoding": "UTF-8",
"star_events_count": 10,
"url": "https://raw.githubusercontent.com/nomi-san/luacef/9f35b62ae9952a1382fa38686abdb051a4ba8fd5/src/api/resource_bunble_handler.c",
"visit_date": "2022-07-15T14:15:57.342946"
} | stackv2 | #include "../luacef.h"
typedef struct luacef_resource_bundle_handler {
cef_base_t base;
int (CEF_CALLBACK *get_localized_string)(
struct luacef_resource_bundle_handler* self,
int string_id,
cef_string_t* string);
int (CEF_CALLBACK *get_data_resource)(
struct luacef_resource_bundle_handler* self,
int resource_id,
void** data,
size_t* data_size);
int (CEF_CALLBACK *get_data_resource_for_scale)(
struct luacef_resource_bundle_handler* self,
int resource_id,
cef_scale_factor_t scale_factor,
void** data,
size_t* data_size);
lua_State *L;
int ref;
} luacef_resource_bundle_handler;
const char
*_rbh_get_localized_string = "LocalizedString",
*_rbh_get_data_resource = "DataResource",
*_rbh_get_data_resource_for_scale = "DataResourceForScale";
int CEF_CALLBACK rbh_get_localized_string(
struct luacef_resource_bundle_handler* self,
int string_id,
cef_string_t* string)
{
return 0;
}
int CEF_CALLBACK rbh_get_data_resource(
struct luacef_resource_bundle_handler* self,
int resource_id,
void** data,
size_t* data_size)
{
return 0;
}
int CEF_CALLBACK rbh_get_data_resource_for_scale(
struct luacef_resource_bundle_handler* self,
int resource_id,
cef_scale_factor_t scale_factor,
void** data,
size_t* data_size)
{
return 0;
}
| 2.125 | 2 |
2024-11-18T22:48:55.617751+00:00 | 2020-05-02T20:53:15 | 92d6f3aa04c35dcf1b52428a538e244f5c42d290 | {
"blob_id": "92d6f3aa04c35dcf1b52428a538e244f5c42d290",
"branch_name": "refs/heads/master",
"committer_date": "2020-05-02T20:53:15",
"content_id": "9f88766a130b368db70a56e41a0e41bfd531ea2e",
"detected_licenses": [
"MIT"
],
"directory_id": "b03da9219d0b9045610e9a975ee139fdc953d268",
"extension": "h",
"filename": "session.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 260773118,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5955,
"license": "MIT",
"license_type": "permissive",
"path": "/sas-server/src/session.h",
"provenance": "stackv2-0108.json.gz:82990",
"repo_name": "fabianishere/sas",
"revision_date": "2020-05-02T20:53:15",
"revision_id": "84c15d77988fac5a173f766d866d90666b529bc1",
"snapshot_id": "4a39ba3687b0adc3dc90727aebdb11fdc2f3ccd4",
"src_encoding": "UTF-8",
"star_events_count": 4,
"url": "https://raw.githubusercontent.com/fabianishere/sas/84c15d77988fac5a173f766d866d90666b529bc1/sas-server/src/session.h",
"visit_date": "2022-05-26T01:02:37.036429"
} | stackv2 | #ifndef SAS_INTERNAL_SESSION_H
#define SAS_INTERNAL_SESSION_H
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <rxc/rxc.h>
#include <rxc/logic.h>
#include <sas/chunk.h>
#include <sas/transport.h>
#include <sas/server.h>
/**
* A client that is connected to the server and has established a session.
*/
struct sas_server_session {
/**
* The address of the client.
*/
struct sockaddr_in6 addr;
/**
* The state of the session.
*/
uint8_t state;
/**
* The accumulated sequence number of the current session.
*/
uint32_t seq;
/**
* The acknowledgment number.
*/
uint32_t ack;
/**
* The window size of the client.
*/
uint16_t send_window;
/**
* The window size of the server.
*/
uint16_t receive_window;
/**
* The pipeline that is used for this session.
*/
struct rxc_pipeline *pipeline;
/**
* The sink logic to control the sink.
*/
struct rxc_sink_logic *sink_logic;
/**
* The point in time when the session will timeout.
*/
time_t timeout;
/**
* The sample rate that is used.
*/
int32_t sample_rate;
/**
* The sample size that is used.
*/
int8_t sample_size;
/**
* The channels used.
*/
int8_t channels;
/**
* The codec that is used.
*/
uint8_t codec;
/**
* The file descriptor of the file to stream.
*/
int fd;
/**
* The next session at this hash table index.
*/
struct sas_server_session *next;
};
/**
* The table of active sessions in the server.
*/
struct sas_server_session_table {
/**
* The amount of active sessions in the hash table.
*/
int count;
/**
* The capacity of the session table.
*/
int capacity;
/**
* A hash table of active sessions.
*/
struct sas_server_session **table;
};
/**
* Find an active connection in the server.
*
* @param[in] server The server to find the session for.
* @param[in] addr The address of the session to look for.
* @return The connection details of the client or <code>NULL</code>
*/
struct sas_server_session * sas_server_session_find(const struct sas_server *server,
const struct sockaddr_in6 *addr);
/**
* Create a session for the specified address in the session hash table. When
* a session already exists, it is returned instead.
*
* @param[in] server The server to create the session for.
* @param[in] addr The address to create a session for.
* @return The newly created server session or <code>NULL</code> on allocation
* failure.
*/
struct sas_server_session * sas_server_session_get(struct sas_server *server,
const struct sockaddr_in6 *addr);
/**
* Forget the specified session.
*
* @param[in] server The server to forget the session for.
* @param[in] session The session to forget.
*/
void sas_server_session_delete(struct sas_server *server,
struct sas_server_session *session);
/**
* Send the given packet to the specified session.
*
* @param[in] server The server to use.
* @param[in] session The session to send the message to.
* @param[in] packet The packet to send.
* @return <code>0</code> on success, otherwise an error code.
*/
int sas_server_session_send(struct sas_server *server,
struct sas_server_session *session,
struct sas_transport_packet_header *packet);
/**
* Send the given chink of the given size to the specified session.
*
* @param[in] server The server to use.
* @param[in] session The session to send the message to.
* @param[in] chunk The chunk to send.
* @return <code>0</code> on success, otherwise an error code.
*/
int sas_server_session_send_chunk(struct sas_server *server,
struct sas_server_session *session,
struct sas_chunk *chunk);
/**
* Reset the specified session.
*
* @param[in] server The server to use.
* @param[in] session The session to reset.
* @param[in] fin Flag to mark the session as finished.
* @return <code>0</code> on success, otherwise an error code.
*/
int sas_server_session_reset(struct sas_server *server,
struct sas_server_session *session,
int fin);
/**
* Indicate an error to the session.
*
* @param[in] server The server that is running.
* @param[in] session The session to indicate the error to.
* @param[in] code The error code to send.
* @return <code>0</code> on success, otherwise an error code.
*/
int sas_server_session_error(struct sas_server *server,
struct sas_server_session *session,
int32_t code);
/**
* Send a SYN-ACK message to the client.
*
* @param[in] server The server that is running.
* @param[in] session The session to send the message to.
* @param[
* @return <code>0</code> on success, otherwise an error code.
*/
int sas_server_session_syn_ack(struct sas_server *server,
struct sas_server_session *session);
/**
* This function represents the state machine of a session and is invoked
* for every packet.
*
* @param[in] server The server that is handling the request.
* @param[in] session The session that received a packet.
* @param[in] header The packet header that was received.
* @param[in] count The number of bytes read.
*/
void sas_server_session_state_machine(struct sas_server *server,
struct sas_server_session *session,
struct sas_transport_packet_header *header,
size_t count);
#endif /* SAS_INTERNAL_SESSION_H */
| 2.28125 | 2 |
2024-11-18T22:48:55.815541+00:00 | 2016-11-02T22:02:08 | aef4335344a7a387432d482d01edfa740fba0807 | {
"blob_id": "aef4335344a7a387432d482d01edfa740fba0807",
"branch_name": "refs/heads/master",
"committer_date": "2016-11-02T22:02:08",
"content_id": "7aa2c1e030e0c4f206427cbc29c16fb4ee9a26d3",
"detected_licenses": [
"MIT"
],
"directory_id": "e3985e53eb5d63cb13a0758aa99ac099eaa6b9f5",
"extension": "c",
"filename": "file_io.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 57101189,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2923,
"license": "MIT",
"license_type": "permissive",
"path": "/src/file_io.c",
"provenance": "stackv2-0108.json.gz:83250",
"repo_name": "shnewto/symbolic-regression-c",
"revision_date": "2016-11-02T22:02:08",
"revision_id": "7636ad80b1897d8785e30ea335e3e73bcfa0bba6",
"snapshot_id": "535141ba997213169ff729e23e306f4910e11560",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/shnewto/symbolic-regression-c/7636ad80b1897d8785e30ea335e3e73bcfa0bba6/src/file_io.c",
"visit_date": "2022-11-28T10:13:38.524050"
} | stackv2 |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "global_memory.h"
#include "file_io.h"
//
void generate_results_table(
const fitness_function_s fitness_function,
population_ref * const population )
{
if( (*population) == NULL )
{
fprintf( stderr, "bad parameter in generate_results_table\n");
graceful_exit( EXIT_FAILURE );
}
const char file_name[] =
"results.txt";
FILE * stream = NULL;
stream = fopen( file_name, "w" );
if( stream == NULL )
{
fprintf( stderr, "failed to open %s\n", file_name );
graceful_exit( EXIT_FAILURE );
}
individual_s * individual = NULL;
individual = population_best_get( population );
for( unsigned long idx = 0; idx < fitness_function.data_point_count; ++idx )
{
// evaluate function on each input point
fprintf(
stream,
"%f\t%f\n",
node_evaluate(
individual->tree_root_node,
fitness_function.input[ idx ] ),
fitness_function.output[ idx ] );
}
fclose( stream );
}
//
void generate_data_set(
fitness_function_s * const fitness_function )
{
// Record of the x and f(x) values.
const char file_name[] = "regression-data-set.txt";
FILE* stream = fopen( file_name, "w" );
if( stream == NULL )
{
fprintf( stderr, "failed to open %s\n", file_name );
graceful_exit( EXIT_FAILURE );
}
unsigned long * idx = &fitness_function->data_point_count;
(*idx) = 0;
for( double x = DATA_SET_RANGE_MIN; x < DATA_SET_RANGE_MAX; x += DATA_SET_RANGE_STEP )
{
fitness_function->input[ (*idx) ] = x; // x
fitness_function->output[ (*idx) ]
= FUNCTION(x);
fprintf(
stream,
"%.2f %.2f\n",
fitness_function->input[ (*idx) ],
fitness_function->output[ (*idx) ] );
(*idx)++;
if( (*idx) > MAX_DATA_POINTS )
{
fprintf( stderr, "Data point count exceeded MAX_DATA_POINTS\n" );
graceful_exit( EXIT_FAILURE );
}
}
fclose( stream );
}
//
void print_individual_function(
const individual_s * const individual )
{
if( individual == NULL )
{
fprintf( stderr, "bad parameter in print_individual_function\n");
graceful_exit( EXIT_FAILURE );
}
const char file_name[] =
"function.txt";
FILE * stream = NULL;
stream = fopen( file_name, "w" );
if( stream == NULL )
{
fprintf( stderr, "failed to open %s\n", file_name );
graceful_exit( EXIT_FAILURE );
}
fprintf( stream, "f( x )\n" );
node_print_operations(
individual->tree_root_node,
stream,
1 );
fprintf( stream, "\n" );
fclose( stream );
}
| 2.453125 | 2 |
2024-11-18T22:48:55.972478+00:00 | 2023-08-30T18:12:56 | f766ce6ac0af67850883b42f21b8d6c1ac5e516d | {
"blob_id": "f766ce6ac0af67850883b42f21b8d6c1ac5e516d",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-30T18:12:56",
"content_id": "c0b1a70534146bd72cd8fe6a134c83e91e60ab71",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "6e1cde66aa5a649138babe297293962cdf97743e",
"extension": "c",
"filename": "check.c",
"fork_events_count": 328,
"gha_created_at": "2014-03-07T14:43:14",
"gha_event_created_at": "2023-08-26T14:32:33",
"gha_language": "C",
"gha_license_id": "NOASSERTION",
"github_id": 17516793,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1162,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/src/libtai/check.c",
"provenance": "stackv2-0108.json.gz:83511",
"repo_name": "SWI-Prolog/swipl-devel",
"revision_date": "2023-08-30T18:12:56",
"revision_id": "41ac4a569c8e6c3d3b93a21449403962e3de1ece",
"snapshot_id": "db56676481984addc09f4f228bc1c41f7f53759f",
"src_encoding": "UTF-8",
"star_events_count": 935,
"url": "https://raw.githubusercontent.com/SWI-Prolog/swipl-devel/41ac4a569c8e6c3d3b93a21449403962e3de1ece/src/libtai/check.c",
"visit_date": "2023-09-01T03:49:40.696481"
} | stackv2 | #include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "tai.h"
#include "leapsecs.h"
#include "caltime.h"
char line[100];
char *dayname[7] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" } ;
char out[101];
char x[TAI_PACK];
int
main(int argc, char **argv)
{
struct tai t;
struct tai t2;
struct caltime ct;
struct caltime ct2;
int weekday;
int yearday;
int i;
double packerr;
if (leapsecs_init() == -1)
printf("unable to init leapsecs\n");
while (fgets(line,sizeof line,stdin))
if (!caltime_scan(line,&ct))
printf("unable to parse\n");
else {
caltime_tai(&ct,&t);
caltime_utc(&ct2,&t,&weekday,&yearday);
tai_pack(x,&t);
tai_unpack(x,&t2);
tai_sub(&t2,&t2,&t);
packerr = tai_approx(&t2);
for (i = 0;i < TAI_PACK;++i)
printf("%2.2lx",(unsigned long) (unsigned char) x[i]);
if (packerr)
printf(" packerr=%f",packerr);
printf(" %03d %s",yearday,dayname[weekday]);
if (caltime_fmt((char *) 0,&ct2) + 1 < sizeof out) {
out[caltime_fmt(out,&ct2)] = 0;
printf(" %s",out);
}
printf("\n");
}
exit(0);
}
| 2.3125 | 2 |
2024-11-18T22:48:56.177837+00:00 | 2020-02-27T17:14:29 | 8ce311bb11a225c9a198c23f0d6a955b09a8ff9e | {
"blob_id": "8ce311bb11a225c9a198c23f0d6a955b09a8ff9e",
"branch_name": "refs/heads/master",
"committer_date": "2020-02-27T17:14:29",
"content_id": "e956662eaf963d33db68d377301ec6316bac336f",
"detected_licenses": [
"MIT"
],
"directory_id": "3237c5ea86182754f6aee48a71b2f068b8057c52",
"extension": "c",
"filename": "linked_list.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 144500443,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2524,
"license": "MIT",
"license_type": "permissive",
"path": "/linked_list.c",
"provenance": "stackv2-0108.json.gz:83640",
"repo_name": "mett29/algorithms_and_data_structures",
"revision_date": "2020-02-27T17:14:29",
"revision_id": "6f9f7cdfa5815488424f0f9b64dd4ae0f4b0f635",
"snapshot_id": "e010cd7ee7b9868678826d81484d23ef75624f63",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/mett29/algorithms_and_data_structures/6f9f7cdfa5815488424f0f9b64dd4ae0f4b0f635/linked_list.c",
"visit_date": "2020-03-26T04:22:11.179678"
} | stackv2 | #include <stdio.h>
#include <stdlib.h>
struct node {
int value;
struct node* next;
};
typedef struct node node;
void display_list(node* head) {
if (head == NULL) return;
printf("%i -> ", head->value);
display_list(head->next);
printf("\n");
}
node* insert_top(node* head, int value) {
// Create a new node
node* new_node = (node*)malloc(sizeof(node));
if (new_node == NULL) {
printf("Error creating a new node.\n");
exit(0);
}
new_node->value = value;
// Prepend the new node
new_node->next = head;
// Head is now pointing to the new node
head = new_node;
return head;
}
void insert_bottom(node* head, int value) {
// Go to the tail of the list
node *cursor = head;
while(cursor->next != NULL)
cursor = cursor->next;
// Create a new node
node* new_node = (node*)malloc(sizeof(node));
if (new_node == NULL) {
printf("Error creating a new node.\n");
exit(0);
}
// Append the new node
new_node->value = value;
cursor->next = new_node;
}
node* search_node(node* head, int value) {
node* cursor = head;
while(cursor->value != value) {
cursor = cursor->next;
if (cursor == NULL) break;
}
return cursor;
}
node* delete_node(node* head, int value) {
// If the value does not exist
if (search_node(head, value) == NULL) {
printf("The element does not exist.\n");
return head;
}
// If the node is the head
if (head->value == value) {
head = head->next;
return head;
}
// Else
node* cursor = head;
while(cursor->next->value != value)
cursor = cursor->next;
// If the node is at the end
if (cursor->next->next == NULL) {
cursor->next = NULL;
return head;
}
// Else if the node is in the middle
node* tmp = cursor->next;
cursor->next = tmp->next;
tmp->next = NULL;
free(tmp);
return head;
}
int main() {
node* head;
// Some tests
head = insert_top(head, 42);
display_list(head);
insert_bottom(head, 3);
insert_bottom(head, 27);
display_list(head);
head = delete_node(head, 3);
display_list(head);
insert_bottom(head, 50);
display_list(head);
head = delete_node(head, 42);
display_list(head);
head = insert_top(head, 42);
display_list(head);
head = delete_node(head, 50);
display_list(head);
head = delete_node(head, 12);
} | 3.890625 | 4 |
2024-11-18T22:48:56.347643+00:00 | 2017-10-15T13:03:00 | f33ae532ec5957801e6ef087bd93f0a765abb094 | {
"blob_id": "f33ae532ec5957801e6ef087bd93f0a765abb094",
"branch_name": "refs/heads/master",
"committer_date": "2017-10-15T13:03:00",
"content_id": "e190c1b623abe65cf236cf406cbc0f60b66805d9",
"detected_licenses": [
"MIT"
],
"directory_id": "052ff37164adc62a51f6bdabfdce2162d10fe9bb",
"extension": "h",
"filename": "UtilsMacros.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 99184541,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1678,
"license": "MIT",
"license_type": "permissive",
"path": "/WJBaseComponent/Classes/Macros/UtilsMacros.h",
"provenance": "stackv2-0108.json.gz:83897",
"repo_name": "CoderLawrence/WJBaseComponent",
"revision_date": "2017-10-15T13:03:00",
"revision_id": "664480b318e739e85f82f0d2ae3162bc7e842b3a",
"snapshot_id": "24cadb2044127e1b5acb2735c91e2d8616473f80",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/CoderLawrence/WJBaseComponent/664480b318e739e85f82f0d2ae3162bc7e842b3a/WJBaseComponent/Classes/Macros/UtilsMacros.h",
"visit_date": "2021-01-02T09:17:49.285598"
} | stackv2 | //
// UtilsMacros.h
// TodayNews
//
// Created by Lawrence on 2017/6/21.
// Copyright © 2017年 Lawrence. All rights reserved.
//
#ifndef UtilsMacros_h
#define UtilsMacros_h
//******************发布版本不输出调试信息********************
#ifdef DEBUG
#define NSLog(...) NSLog(__VA_ARGS__)
#define WJLog(foramt, ...) NSLog((@"文件名:%s\n" "函数名:%s " "行号 : %d\n" format), __FILE__, __FUNCTION__, __LINE__, ##__VA_ARGS__)
#else
#define NSLog(...) {}
#define WJLog(...) {}
#endif
//*****************字体相关宏******************************
#define UIFontSize(size) ([UIFont systemFontOfSize:size])
// ****************颜色相关***********************
///RGBA颜色设置
#define WJColor(r, g, b, a) ([UIColor colorWithRed:r/255.0f green:g/255.0f blue:b/255.0f alpha:a])
///背景灰色
#define WJGlobalColor (WJColor(245, 245, 245, 1))
///统一红色颜色
#define WJGlobalRadColor (WJColor(245.0f, 80.0f, 83.0f, 1.0f))
//十六进制颜色
#define WJHexColor(c) ([UIColor colorWithRed:((c>>16)&0xFF)/255.0f green:((c>>8)&0xFF)/255.0f blue:(c&0xFF)/255.0f alpha:1.0f])
#define WJHexColorA(c, a) ([UIColor colorWithRed:((c>>16)&0xFF)/255.0f green:((c>>8)&0xFF)/255.0f blue:(c&0xFF)/255.0f alpha:a])
// weak strong
#define __WEAKSELF(X) __weak __typeof(X) weakSelf = X;
#define __STRONGSELF(X) __strong __typeof(X) strongSelf = X;
//比较两个数的大小
#define MAXAB(A, B) ({__typeof(A) __a = (A); __typeof(B) __b = (B); __a > __b ? __a : __b;})
//判断字符串是否为空
#define KStringIsEmpty(str) ([str isKindOfClass:[NSNull class]] || str == nil || [str length] < 1 ? YES : NO)
#endif /* UtilsMacros_h */
| 2.0625 | 2 |
2024-11-18T22:48:56.433128+00:00 | 2014-07-02T16:57:49 | 7ceaa966398feafaeecd176635c49fdfb75d0732 | {
"blob_id": "7ceaa966398feafaeecd176635c49fdfb75d0732",
"branch_name": "refs/heads/master",
"committer_date": "2014-07-02T16:57:49",
"content_id": "3acb41fd90141749befa12705c37baa52f8e9c80",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "4bf023a48ab9c037c46985918d9f1b387d0126f7",
"extension": "c",
"filename": "ngx_security_phase.c",
"fork_events_count": 3,
"gha_created_at": "2014-05-06T14:52:10",
"gha_event_created_at": "2014-05-22T03:51:40",
"gha_language": "C",
"gha_license_id": null,
"github_id": 19498236,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2600,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/ngx_modsecurity/modsecurity-1.0.1/src/ngx_security_phase.c",
"provenance": "stackv2-0108.json.gz:84025",
"repo_name": "shajf/ngx_modsecurity",
"revision_date": "2014-07-02T16:57:49",
"revision_id": "21df506580939be9bac5fede5c55b23e9570ba0f",
"snapshot_id": "3f03e88ae414f72f7d591677f09cfe7011dfd950",
"src_encoding": "UTF-8",
"star_events_count": 4,
"url": "https://raw.githubusercontent.com/shajf/ngx_modsecurity/21df506580939be9bac5fede5c55b23e9570ba0f/ngx_modsecurity/modsecurity-1.0.1/src/ngx_security_phase.c",
"visit_date": "2016-09-06T13:54:47.500001"
} | stackv2 | /*
* =====================================================================================
* Copyright (C) 2014 jianfeng sha
*
* Filename: ngx_security_phase.c
*
* Description:
*
* Created: 05/27/14 16:30:15
*
* Author: jianfeng sha , csp001314@163.com
*
* =====================================================================================
*/
static ngx_int_t security_phase_post_read(ngx_http_request_t *r);
static ngx_int_t security_phase_server_rewrite(ngx_http_request_t *r);
static ngx_int_t security_phase_rewrite(ngx_http_request_t *r);
static ngx_int_t security_phase_preaccess(ngx_http_request_t *r);
static ngx_int_t security_phase_access(ngx_http_request_t *r);
static ngx_int_t security_phase_content(ngx_http_request_t *r);
static ngx_int_t security_phase_log(ngx_http_request_t *r);
static ngx_int_t set_phase_handler(ngx_http_core_main_conf_t *cmcf,int phase){
ngx_http_handler_pt *h;
h = ngx_array_push(&cmcf->phases[phase].handlers);
if(h == NULL){
return NGX_ERROR;
}
switch(phase){
case NGX_HTTP_POST_READ_PHASE:
*h = security_phase_post_read;
break;
case NGX_HTTP_SERVER_REWRITE_PHASE:
*h = security_phase_server_rewrite;
break;
case NGX_HTTP_REWRITE_PHASE:
*h = security_phase_rewrite;
break;
case NGX_HTTP_PREACCESS_PHASE:
*h = security_phase_preaccess;
break;
case NGX_HTTP_ACCESS_PHASE:
*h = security_phase_access;
break;
case NGX_HTTP_CONTENT_PHASE:
*h = security_phase_content;
break;
case NGX_HTTP_LOG_PHASE:
*h = security_phase_log;
break;
default:
return NGX_ERROR;
}
return NGX_OK;
}
ngx_int_t ngx_security_phase_setup(ngx_conf_t *conf){
ngx_http_handler_pt *h;
ngx_http_core_main_conf_t *cmcf;
ngx_int_t status;
cmcf = ngx_http_conf_get_module_main_conf(cf,ngx_http_core_module);
status = NGX_OK;
do{
status = set_phase_handler(cmcf,NGX_HTTP_POST_READ_PHASE);
if(status == NGX_ERROR) break;
status = set_phase_handler(cmcf,NGX_HTTP_SERVER_REWRITE_PHASE);
if(status == NGX_ERROR) break;
status = set_phase_handler(cmcf,NGX_HTTP_REWRITE_PHASE);
if(status == NGX_ERROR) break;
status = set_phase_handler(cmcf,NGX_HTTP_PREACCESS_PHASE);
if(status == NGX_ERROR) break;
status = set_phase_handler(cmcf,NGX_HTTP_ACCESS_PHASE);
if(status == NGX_ERROR) break;
status = set_phase_handler(cmcf,NGX_HTTP_CONTENT_PHASE);
if(status == NGX_ERROR) break;
status = set_phase_handler(cmcf,NGX_HTTP_LOG_PHASE);
if(status == NGX_ERROR) break;
}while(0);
return status;
}
| 2.140625 | 2 |
2024-11-18T22:48:57.075408+00:00 | 2021-08-06T17:21:01 | 5e698f006f32cc2d30fe49183d73fe69522686b8 | {
"blob_id": "5e698f006f32cc2d30fe49183d73fe69522686b8",
"branch_name": "refs/heads/main",
"committer_date": "2021-08-06T17:21:01",
"content_id": "9d688eddebe9ba08730ba22e1644207cfdf1b359",
"detected_licenses": [
"MIT"
],
"directory_id": "fa89b9d6192facde3991d6f8f2eab168b1e35fcb",
"extension": "c",
"filename": "stack.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 728,
"license": "MIT",
"license_type": "permissive",
"path": "/stack.c",
"provenance": "stackv2-0108.json.gz:84545",
"repo_name": "pfvelu/K-R-algorithms",
"revision_date": "2021-08-06T17:21:01",
"revision_id": "c4d85db1a37505b3da784466579ac814f9766e70",
"snapshot_id": "c1f044b82264040c53cd4f9c66aeb5a3888234f2",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/pfvelu/K-R-algorithms/c4d85db1a37505b3da784466579ac814f9766e70/stack.c",
"visit_date": "2023-07-09T23:45:08.189583"
} | stackv2 | #include <stdio.h>
#include "calc.h"
#define MAXVAL 100
int sp = 0;
double val[MAXVAL];
/* the following code implement a stack in C
a stack is a data structure that stores elements
following the last in, first out directive (LIFO)
meaning that the last element pushed in the stack
will be the first one to be popped out of it */
/* push: push f onto value stack */
void push(double f)
{
if (sp < MAXVAL){
val[sp++] = f;
}
else{
printf("error: stack full, can't push %g\n",f);
}
}
/* pop: pop and return top value from stack */
double pop(void)
{
if (sp > 0){
return val[--sp];
}
else {
printf("error: stack empty\n");
return 0.0;
}
} | 3.5625 | 4 |
2024-11-18T22:48:57.560839+00:00 | 2023-08-28T21:30:11 | a32dbdeaee26cffc1b07483b6939b766b8a55f83 | {
"blob_id": "a32dbdeaee26cffc1b07483b6939b766b8a55f83",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-28T21:30:11",
"content_id": "16d6dbbbae8396f270df0c37510cba398bcd0f70",
"detected_licenses": [
"MIT"
],
"directory_id": "aed47b5a4ea3af5cbacfc034c1565bd800e9461a",
"extension": "c",
"filename": "mean.c",
"fork_events_count": 53,
"gha_created_at": "2019-10-12T22:33:21",
"gha_event_created_at": "2023-03-02T21:35:56",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 214724629,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 361,
"license": "MIT",
"license_type": "permissive",
"path": "/src/CControl/Sources/Statistics/mean.c",
"provenance": "stackv2-0108.json.gz:84673",
"repo_name": "DanielMartensson/CControl",
"revision_date": "2023-08-28T21:30:11",
"revision_id": "25ce62ef3a0d87a55459fc9e7d4e1ee895d89ed9",
"snapshot_id": "a4dcfc13af8ef8266ac83f9ec0690848f5afd1b2",
"src_encoding": "UTF-8",
"star_events_count": 169,
"url": "https://raw.githubusercontent.com/DanielMartensson/CControl/25ce62ef3a0d87a55459fc9e7d4e1ee895d89ed9/src/CControl/Sources/Statistics/mean.c",
"visit_date": "2023-08-30T23:53:16.167470"
} | stackv2 | /*
* mean.c
*
* Created on: 26 juni 2021
* Author: Daniel Mårtensson
*/
#include "../../Headers/functions.h"
/*
* Compute the mean of vector x
* x[L] Vector with values
* L = Length of vector x
*/
float mean(float x[], size_t length) {
float s = 0.0f;
size_t i;
for (i = 0; i < length; i++) {
s += x[i];
}
return s / ((float)length);
}
| 2.875 | 3 |
2024-11-18T22:48:58.174706+00:00 | 2017-03-26T23:25:57 | fafe73ac9a105806ca598b866db4904554706361 | {
"blob_id": "fafe73ac9a105806ca598b866db4904554706361",
"branch_name": "refs/heads/master",
"committer_date": "2017-03-26T23:25:57",
"content_id": "afd54046a204a06510d9e305795df2559c266b8f",
"detected_licenses": [
"Zlib"
],
"directory_id": "1c4d3b5a11137f750f07851a772c490a22b2cb0c",
"extension": "c",
"filename": "gfmQuadtree.c",
"fork_events_count": 4,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 22835205,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 39766,
"license": "Zlib",
"license_type": "permissive",
"path": "/src/gfmQuadtree.c",
"provenance": "stackv2-0108.json.gz:85191",
"repo_name": "SirGFM/GFraMe",
"revision_date": "2017-03-26T23:25:57",
"revision_id": "4cc02182be905189a9aa04467d5bbf8640184cd3",
"snapshot_id": "08d58b1b3cea4502c7166fa27f4b93170000969a",
"src_encoding": "UTF-8",
"star_events_count": 13,
"url": "https://raw.githubusercontent.com/SirGFM/GFraMe/4cc02182be905189a9aa04467d5bbf8640184cd3/src/gfmQuadtree.c",
"visit_date": "2021-01-23T11:23:08.843630"
} | stackv2 | /**
* @file include/GFraMe/gfmQuadtree.h
*
* Interactive quadtree implementation to be used for collision detection; After
* initializing the root node (through a gfmQuadtree_initRoot call), there are
* two ways to add more nodes: using gfmQuadtree_collide* and
* gfmQuadtree_populate*;
* - The functions gfmQuadtree_populate* will adds a new 'object' (in the
* broader sense) to the quadtree, but doesn't collide anything;
* - gfmQuadtree_collide*, on the other hand, will adds a new 'object' to the
* quadtree and will collide it against every other object in it;
* Therefore, the proper way to use this would be to create the root node,
* populate it with all the static 'objects' (e.g., tilemap, particles, etc) and
* then add all the collideable 'objects';
* On success, gfmQuadtree_collide and gfmQuadtree_continue can return in one
* of a two ways:
* - GFMRV_QUADTREE_OVERLAPED: signs that an overlap just happened and should
* be handled; This returns prior to completely adding the 'object' to the
* tree, so gfmQuadtree_continue *must* be called afterward! Calling
* gfmQuadtree_getOverlaping will return both gfmObjects that overlaped; From
* those, one could call gfmObject_getChild to get the child 'object' (if any)
* and its type; If this child is a gfmSprite (that was correctly setuped),
* calling gfmSprite_getChild would return its 'sub-class'; This was a way to
* emulate (in a quite simple way) OOP in C;
* - GFMRV_QUADTREE_DONE: the 'object' was successfully added to the quadtree;
*/
#include <GFraMe/gfmAssert.h>
#include <GFraMe/gfmError.h>
#include <GFraMe/gfmGenericArray.h>
#include <GFraMe/gfmGroup.h>
#include <GFraMe/gfmHitbox.h>
#include <GFraMe/gfmObject.h>
#include <GFraMe/gfmQuadtree.h>
#include <GFraMe/gfmSprite.h>
#include <GFraMe/gfmTilemap.h>
#include <GFraMe/gfmTypes.h>
#include <stdlib.h>
#include <string.h>
static unsigned char gfmQt_defColors[(gfmType_max) * 3] =
{
/* red ,green, blue */
0x99 ,0xe5 , 0x50, /* quadtree_node (light green) */
0xac ,0x32 , 0x32, /* gfmType_object (red) */
0xcb ,0xdb , 0xfc, /* gfmType_sprite (lightest blue) */
0x00 ,0x00 , 0x00, /* gfmType_tilemap (isn't actually drawn) */
0x22 ,0x20 , 0x34, /* gfmType_group (isn't actually drawn) */
0xd7 ,0x7b , 0xba, /* gfmType_reserved_2 (pink) */
0x5f ,0xcd , 0xe4, /* gfmType_reserved_3 (light blue) */
0x6a ,0xbe , 0x30, /* gfmType_reserved_4 (green) */
0x76 ,0x42 , 0x8a, /* gfmType_reserved_5 (purple) */
0xfb ,0xf2 , 0x36, /* gfmType_reserved_6 (yellow) */
0xd9 ,0x57 , 0x63, /* gfmType_reserved_7 (light red) */
0xee ,0xc3 , 0x9a, /* gfmType_reserved_8 (beige) */
0x63 ,0x9b , 0xff, /* gfmType_reserved_9 (blue) */
0x8f ,0x97 , 0x4a, /* gfmType_reserved_10 (dirty yellow/green) */
0xff ,0xff , 0xff, /* gfmType_reserved_11 (white) */
0x80 ,0x72 , 0x15, /* gfmType_reserved_12 */
0x80 ,0x38 , 0x15, /* gfmType_reserved_13 */
0x00 ,0x39 , 0x26, /* gfmType_reserved_14 */
0x18 ,0x06 , 0x3a, /* gfmType_reserved_15 */
0x55 ,0x4a , 0x00, /* gfmType_reserved_16 */
0x55 ,0x4a , 0x00, /* gfmType_reserved_17 */
0x55 ,0x4a , 0x00, /* gfmType_reserved_18 */
0x55 ,0x4a , 0x00, /* gfmType_reserved_19 */
0x55 ,0x4a , 0x00, /* gfmType_reserved_20 */
0x55 ,0x4a , 0x00, /* gfmType_reserved_21 */
0x55 ,0x4a , 0x00, /* gfmType_reserved_22 */
0x55 ,0x4a , 0x00, /* gfmType_reserved_23 */
0x55 ,0x4a , 0x00, /* gfmType_reserved_24 */
0x55 ,0x4a , 0x00, /* gfmType_reserved_25 */
0x55 ,0x4a , 0x00, /* gfmType_reserved_26 */
0x55 ,0x4a , 0x00, /* gfmType_reserved_27 */
0x55 ,0x4a , 0x00, /* gfmType_reserved_28 */
};
/** Quadtree node type */
typedef struct stGFMQuadtree gfmQuadtree;
/** Quadtree nodes linked-list */
typedef struct stGFMQuadtreeLL gfmQuadtreeLL;
/** Stack of quadtree nodes */
typedef struct stGFMQuadtreeStack gfmQuadtreeStack;
/** Index of a child relative to its parent */
typedef enum enGFMQuadtreePosition gfmQuadtreePosition;
/** Define array of quadtree nodes */
gfmGenArr_define(gfmQuadtree);
/** Define array of quadtree linked-list nodes */
gfmGenArr_define(gfmQuadtreeLL);
/** Index of a child relative to its parent */
enum enGFMQuadtreePosition {
gfmQT_nw = 0,
gfmQT_ne,
gfmQT_sw,
gfmQT_se,
gfmQT_max,
};
/** Index of a child relative to its parent */
struct stGFMQuadtreeLL {
/** This nodes object */
gfmObject *pSelf;
/** The next node */
struct stGFMQuadtreeLL *pNext;
};
/** Stack of quadtree nodes */
struct stGFMQuadtreeStack {
/** The nodes that were pushed */
gfmQuadtree **ppStack;
/** Position where pushes may happen (pop happens on this - 1) */
int pushPos;
/** How many nodes this can handle */
int len;
};
/** Quadtree node type */
struct stGFMQuadtree {
/** The tree's sub-nodes */
gfmQuadtree *ppChildren[gfmQT_max];
/** List of all objects inside this node */
gfmQuadtreeLL *pNodes;
/** Center of the hitbox */
int centerX;
/** Center of the hitbox */
int centerY;
/** Half the hitbox's width */
int halfWidth;
/** Half the hitbox's height */
int halfHeight;
/** The node's depth */
int depth;
/** How many objects were added to this node */
int numObjects;
};
/** Quadtree's context, with the current stack and the the root node */
struct stGFMQuadtreeRoot {
/** How many nodes can a node have until it must subdivide */
int maxNodes;
/** How many depths the quadtree can have */
int maxDepth;
/** Whether this is a static quadtree (one that may be populated but
* colliding doesn't insert nodes */
int isStatic;
/** Pool of quadtree nodes */
gfmGenArr_var(gfmQuadtree, pQTPool);
/** Pool of quadtree LL nodes */
gfmGenArr_var(gfmQuadtreeLL, pQTLLPool);
/** List of collideables objects from a group */
gfmGroupNode *pGroupList;
/** The actual root node of the quadtree */
gfmQuadtree *pSelf;
/** List of available LL nodes */
gfmQuadtreeLL *pAvailable;
/** List of nodes to be collided */
gfmQuadtreeLL *pColliding;
/** Stack of nodes which the object must still be added to */
gfmQuadtreeStack stack;
/** Object being collided */
gfmObject *pObject;
/** The object that was just overlapped */
gfmObject *pOther;
};
/******************************************************************************/
/* */
/* Static functions */
/* */
/******************************************************************************/
/**
* Alloc a new quadtree linked-list node
*
* @param ppCtx The linked list node
* @return GFMRV_OK, GFMRV_ARGUMENTS_BAD, GFMRV_ALLOC_FAILED
*/
static gfmRV gfmQuadtreeLL_getNew(gfmQuadtreeLL **ppCtx) {
gfmRV rv;
// Sanitize arguments
ASSERT(ppCtx, GFMRV_ARGUMENTS_BAD);
ASSERT(!(*ppCtx), GFMRV_ARGUMENTS_BAD);
// Alloc it
*ppCtx = (gfmQuadtreeLL*)malloc(sizeof(gfmQuadtreeLL));
ASSERT(*ppCtx, GFMRV_ALLOC_FAILED);
// Clean it
memset(*ppCtx, 0x0, sizeof(gfmQuadtreeLL));
rv = GFMRV_OK;
__ret:
return rv;
}
/**
* Frees a quadtree linked-list node
*
* @param ppCtx The linked list node
* @return GFMRV_OK, GFMRV_ARGUMENTS_BAD
*/
static gfmRV gfmQuadtreeLL_free(gfmQuadtreeLL **ppCtx) {
gfmRV rv;
// Sanitize arguments
ASSERT(ppCtx, GFMRV_ARGUMENTS_BAD);
// Remove all of its pointers
memset(*ppCtx, 0x0, sizeof(gfmQuadtreeLL));
// Release the memory
free(*ppCtx);
*ppCtx = 0;
rv = GFMRV_OK;
__ret:
return rv;
}
/**
* Alloc a new quadtree structure
*
* @param ppCtx The quadtree
* @return GFMRV_OK, GFMRV_ARGUMENTS_BAD, GFMRV_ALLOC_FAILED
*/
static gfmRV gfmQuadtreeNode_getNew(gfmQuadtree **ppCtx) {
gfmRV rv;
// Sanitize arguments
ASSERT(ppCtx, GFMRV_ARGUMENTS_BAD);
ASSERT(!(*ppCtx), GFMRV_ARGUMENTS_BAD);
// Alloc it
*ppCtx = (gfmQuadtree*)malloc(sizeof(gfmQuadtree));
ASSERT(*ppCtx, GFMRV_ALLOC_FAILED);
// Clean it
memset(*ppCtx, 0x0, sizeof(gfmQuadtree));
rv = GFMRV_OK;
__ret:
return rv;
}
/**
* Frees a quadtree node
*
* @param ppCtx The quadtree node
* @return GFMRV_OK, GFMRV_ARGUMENTS_BAD
*/
static gfmRV gfmQuadtreeNode_free(gfmQuadtree **ppCtx) {
gfmRV rv;
// Sanitize arguments
ASSERT(ppCtx, GFMRV_ARGUMENTS_BAD);
// Remove all of its pointers
memset(*ppCtx, 0x0, sizeof(gfmQuadtree));
// Release the memory
free(*ppCtx);
*ppCtx = 0;
rv = GFMRV_OK;
__ret:
return rv;
}
/**
* Initialize a node according with its position relative to its parent
*
* @param pCtx The node to be initialized
* @param pParent The parent node
* @param pos The node's relative position
*/
static gfmRV gfmQuadtree_init(gfmQuadtree *pCtx, gfmQuadtree *pParent,
gfmQuadtreePosition pos) {
gfmQuadtreePosition i;
gfmRV rv;
int offX;
int offY;
// Sanitize arguments
ASSERT(pCtx, GFMRV_ARGUMENTS_BAD);
ASSERT(pParent, GFMRV_ARGUMENTS_BAD);
ASSERT(pos >= gfmQT_nw, GFMRV_ARGUMENTS_BAD);
ASSERT(pos < gfmQT_max, GFMRV_ARGUMENTS_BAD);
// Clear all children
i = gfmQT_nw;
while (i < gfmQT_max) {
pCtx->ppChildren[i] = 0;
i++;
}
// Clear the node's objects
pCtx->pNodes = 0;
pCtx->numObjects = 0;
// Set the node's depth
pCtx->depth = pParent->depth + 1;
// Set the node's dimensions (rounded up)
pCtx->halfWidth = pParent->halfWidth / 2 + (pParent->halfWidth % 2);
pCtx->halfHeight = pParent->halfHeight / 2 + (pParent->halfHeight % 2);
// Get the offset from the parent's position
switch (pos) {
case gfmQT_nw: {
offX = -pParent->halfWidth / 2;
offY = -pParent->halfHeight / 2;
} break;
case gfmQT_ne: {
offX = pParent->halfWidth / 2;
offY = -pParent->halfHeight / 2;
} break;
case gfmQT_sw: {
offX = -pParent->halfWidth / 2;
offY = pParent->halfHeight / 2;
} break;
case gfmQT_se: {
offX = pParent->halfWidth / 2;
offY = pParent->halfHeight / 2;
} break;
case gfmQT_max: {
ASSERT(0, GFMRV_INTERNAL_ERROR);
} break;
}
// Set the position
pCtx->centerX = pParent->centerX + offX;
pCtx->centerY = pParent->centerY + offY;
rv = GFMRV_OK;
__ret:
return rv;
}
/**
* Push a node into the stack, so it'll be checked later
*
* @param pCtx The quadtree's root/ctx
* @param pNode The node to be pushed
* @return GFMRV_OK, GFMRV_ARGUMENTS_BAD, GFMRV_QUADTREE_NOT_INITIALIZED,
* GFMRV_QUADTREE_STACK_OVERFLOW
*/
static gfmRV gfmQuadtree_pushNode(gfmQuadtreeRoot *pCtx, gfmQuadtree *pNode) {
gfmRV rv;
// Sanitize arguments
ASSERT(pCtx, GFMRV_ARGUMENTS_BAD);
ASSERT(pNode, GFMRV_ARGUMENTS_BAD);
// Check if initialized
ASSERT(pCtx->maxDepth > 0, GFMRV_QUADTREE_NOT_INITIALIZED);
// Check that pushed can still be done
ASSERT(pCtx->stack.pushPos < pCtx->stack.len,
GFMRV_QUADTREE_STACK_OVERFLOW);
// Push the node
pCtx->stack.ppStack[pCtx->stack.pushPos] = pNode;
pCtx->stack.pushPos++;
rv = GFMRV_OK;
__ret:
return rv;
}
/**
* Pop a node from the quadtree's context
*
* @param ppNode The popped node
* @param pCtx The quadtree's root/ctx
* @return GFMRV_OK, GFMRV_ARGUMENTS_BAD, GFMRV_QUADTREE_NOT_INITIALIZED,
* GFMRV_QUADTREE_EMPTY
*/
static gfmRV gfmQuadtree_popNode(gfmQuadtree **ppNode, gfmQuadtreeRoot *pCtx) {
gfmRV rv;
// Sanitize arguments
ASSERT(pCtx, GFMRV_ARGUMENTS_BAD);
ASSERT(ppNode, GFMRV_ARGUMENTS_BAD);
// Check if initialized
ASSERT(pCtx->maxDepth > 0, GFMRV_QUADTREE_NOT_INITIALIZED);
// Check if there are any nodes to be popped
ASSERT(pCtx->stack.pushPos > 0, GFMRV_QUADTREE_EMPTY);
// Pop the node
pCtx->stack.pushPos--;
*ppNode = pCtx->stack.ppStack[pCtx->stack.pushPos];
rv = GFMRV_OK;
__ret:
return rv;
}
/**
* Adds an object to a node
*
* @param pCtx The quadtree root context
* @param pNode The node where insertion should happen
* @param pObj The object to be added
* @return GFMRV_OK, GFMRV_ARGUMENTS_BAD, GFMRV_ALLOC_FAILED
*/
static gfmRV gfmQuadtree_insertObject(gfmQuadtreeRoot *pCtx, gfmQuadtree *pNode,
gfmObject *pObj) {
gfmQuadtreeLL *pQTLL;
gfmRV rv;
// Sanitize arguments
ASSERT(pCtx, GFMRV_ARGUMENTS_BAD);
ASSERT(pNode, GFMRV_ARGUMENTS_BAD);
ASSERT(pObj, GFMRV_ARGUMENTS_BAD);
// Retrieve a new linked-list node
if (pCtx->pAvailable) {
// Recycle a used node
pQTLL = pCtx->pAvailable;
pCtx->pAvailable = pCtx->pAvailable->pNext;
}
else {
// Retrieve a new node
gfmGenArr_getNextRef(gfmQuadtreeLL, pCtx->pQTLLPool, pCtx->maxNodes,
pQTLL, gfmQuadtreeLL_getNew);
gfmGenArr_push(pCtx->pQTLLPool);
}
// Add the object to the LL node
pQTLL->pSelf = pObj;
// Prepend the node to the list
pQTLL->pNext = pNode->pNodes;
pNode->pNodes = pQTLL;
// Increase the counter
pNode->numObjects++;
rv = GFMRV_OK;
__ret:
return rv;
}
/**
* Checks if a quadtree node overlaps an object
*
* @param pCtx The quadtree node
* @param pObj The gfmObject
* @return GFMRV_TRUE, GFMRV_FALSE, GFMRV_ARGUMENTS_BAD
*/
static gfmRV gfmQuadtree_overlap(gfmQuadtree *pCtx, gfmObject *pObj) {
gfmRV rv;
int cX, cY, dist, hWidth, hHeight, maxDist;
// Sanitize arguments
ASSERT(pCtx, GFMRV_ARGUMENTS_BAD);
ASSERT(pObj, GFMRV_ARGUMENTS_BAD);
// Get the object's dimensions
rv = gfmObject_getCenter(&cX, &cY, pObj);
ASSERT_NR(rv == GFMRV_OK);
rv = gfmObject_getDimensions(&hWidth, &hHeight, pObj);
ASSERT_NR(rv == GFMRV_OK);
// Get half the dimensions (rounded up)
hWidth = hWidth / 2 + (hWidth % 2);
hHeight = hHeight / 2 + (hHeight % 2);
// Check that they are overlaping (horizontally)
dist = cX - pCtx->centerX;
if (dist < 0) {
dist = -dist;
}
maxDist = hWidth + pCtx->halfWidth;
if (dist > maxDist) {
return GFMRV_FALSE;
}
//ASSERT(dist <= maxDist, GFMRV_FALSE);
// Check vertically...
dist = cY - pCtx->centerY;
if (dist < 0) {
dist = -dist;
}
maxDist = hHeight + pCtx->halfHeight;
if (dist > maxDist) {
return GFMRV_FALSE;
}
//ASSERT(dist <= maxDist, GFMRV_FALSE);
rv = GFMRV_TRUE;
__ret:
return rv;
}
/**
* Subdivides a quadtree
*
* @param pCtx The node to be subdivided
* @return GFMRV_OK, GFMRV_ARGUMENTS_BAD, GFMRV_ALLOC_FAILED
*/
static gfmRV gfmQuadtree_subdivide(gfmQuadtreeRoot *pCtx, gfmQuadtree *pNode) {
gfmQuadtree *pChild;
gfmQuadtreePosition i;
gfmRV rv;
// Sanitize arguments
ASSERT(pCtx, GFMRV_ARGUMENTS_BAD);
ASSERT(pNode, GFMRV_ARGUMENTS_BAD);
// Alloc and initialize all the children
i = gfmQT_nw;
while (i < gfmQT_max) {
gfmGenArr_getNextRef(gfmQuadtree, pCtx->pQTPool, 5, pChild,
gfmQuadtreeNode_getNew);
gfmGenArr_push(pCtx->pQTPool);
// Initialize the child
rv = gfmQuadtree_init(pChild, pNode, i);
ASSERT_NR(rv == GFMRV_OK);
// Set the node's child
pNode->ppChildren[i] = pChild;
// Go to the next one
i++;
}
// Insert every child to the tree it's contained
while (pNode->pNodes) {
gfmQuadtreeLL *pTmp;
// Get the current node
pTmp = pNode->pNodes;
// Add it to every child (that it overlaps)
i = gfmQT_nw;
while (i < gfmQT_max) {
// Get the current child
pChild = pNode->ppChildren[i];
// Check if the object collides this node
rv = gfmQuadtree_overlap(pChild, pTmp->pSelf);
if (rv == GFMRV_TRUE) {
// Add it to the child
rv = gfmQuadtree_insertObject(pCtx, pChild, pTmp->pSelf);
ASSERT_NR(rv == GFMRV_OK);
}
i++;
}
// Go to the next node
pNode->pNodes = pTmp->pNext;
// Prepend the node to the free list
pTmp->pNext = pCtx->pAvailable;
pCtx->pAvailable = pTmp;
}
rv = GFMRV_OK;
__ret:
return rv;
}
/******************************************************************************/
/* */
/* Public functions */
/* */
/******************************************************************************/
/**
* Alloc a new root quadtree
*
* @param ppCtx The root quadtree
* @return GFMRV_OK, GFMRV_ARGUMENTS_BAD, GFMRV_ALLOC_FAILED
*/
gfmRV gfmQuadtree_getNew(gfmQuadtreeRoot **ppCtx) {
gfmRV rv;
// Sanitize arguments
ASSERT(ppCtx, GFMRV_ARGUMENTS_BAD);
ASSERT(!(*ppCtx), GFMRV_ARGUMENTS_BAD);
// Alloc and clean it
*ppCtx = (gfmQuadtreeRoot*)malloc(sizeof(gfmQuadtreeRoot));
ASSERT(*ppCtx, GFMRV_ALLOC_FAILED);
memset(*ppCtx, 0x0, sizeof(gfmQuadtreeRoot));
rv = GFMRV_OK;
__ret:
return rv;
}
/**
* Release a quadtree's root and all its members
*
* @param ppCtx The quadtree root
* @return GFMRV_OK, GFMRV_ARGUMENTS_BAD
*/
gfmRV gfmQuadtree_free(gfmQuadtreeRoot **ppCtx) {
gfmRV rv;
// Sanitize arguments
ASSERT(ppCtx, GFMRV_ARGUMENTS_BAD);
ASSERT(*ppCtx, GFMRV_ARGUMENTS_BAD);
// Clean the quadtree
gfmQuadtree_clean(*ppCtx);
// Free the struct
free(*ppCtx);
*ppCtx = 0;
rv = GFMRV_OK;
__ret:
return rv;
}
/**
* Clean all memory used by the entire quadtree
*
* @param pCtx The quadtree root
* @return GFMRV_OK, GFMRV_ARGUMENTS_BAD
*/
gfmRV gfmQuadtree_clean(gfmQuadtreeRoot *pCtx) {
gfmRV rv;
// Sanitize arguments
ASSERT(pCtx, GFMRV_ARGUMENTS_BAD);
// Clean all generic arrays
gfmGenArr_clean(pCtx->pQTPool, gfmQuadtreeNode_free);
gfmGenArr_clean(pCtx->pQTLLPool, gfmQuadtreeLL_free);
// Clean the stack, if any
if (pCtx->stack.ppStack) {
free(pCtx->stack.ppStack);
}
memset(pCtx, 0x0, sizeof(gfmQuadtreeRoot));
rv = GFMRV_OK;
__ret:
return rv;
}
/**
* Clean up the previous state and ready the quadtree for collision
*
* @param pCtx The quadtree root context
* @param x The quadtree top-left position
* @param y The quadtree top-left position
* @param width The quadtree width
* @param height The quadtree height
* @param maxDepth How many levels can the quadtree branch
* @param maxNodes How many objects a subtree can have until it must split
* @return GFMRV_OK, GFMRV_ARGUMENTS_BAD, GFMRV_ALLOC_FAILED
*/
gfmRV gfmQuadtree_initRoot(gfmQuadtreeRoot *pCtx, int x, int y, int width,
int height, int maxDepth, int maxNodes) {
gfmQuadtreePosition i;
gfmRV rv;
// Sanitize argument
ASSERT(pCtx, GFMRV_ARGUMENTS_BAD);
ASSERT(width > 0, GFMRV_ARGUMENTS_BAD);
ASSERT(height > 0, GFMRV_ARGUMENTS_BAD);
ASSERT(maxDepth > 0, GFMRV_ARGUMENTS_BAD);
ASSERT(maxNodes > 0, GFMRV_ARGUMENTS_BAD);
// Set the quadtree's limits
pCtx->maxNodes = maxNodes;
pCtx->maxDepth = maxDepth;
// Reset all array
gfmGenArr_reset(pCtx->pQTPool);
gfmGenArr_reset(pCtx->pQTLLPool);
// Clear all dynamic list
pCtx->pAvailable = 0;
pCtx->pColliding = 0;
// Remove context object's
pCtx->pObject = 0;
pCtx->pOther = 0;
pCtx->pGroupList = 0;
/* Remove the static flag */
pCtx->isStatic = 0;
// Check that the stack is big enough
if (pCtx->stack.len < maxDepth * gfmQT_max) {
// Expand the stack so it's big enough
pCtx->stack.ppStack = (gfmQuadtree**)realloc(pCtx->stack.ppStack,
sizeof(gfmQuadtree*) * maxDepth * gfmQT_max);
ASSERT(pCtx->stack.ppStack, GFMRV_ALLOC_FAILED);
// Set the stack's size
pCtx->stack.len = maxDepth * gfmQT_max;
}
// Clear the stack
pCtx->stack.pushPos = 0;
// Retrieve the root from the qt pool
gfmGenArr_getNextRef(gfmQuadtree, pCtx->pQTPool, 5, pCtx->pSelf,
gfmQuadtreeNode_getNew);
gfmGenArr_push(pCtx->pQTPool);
// Initialize this node
i = gfmQT_nw;
while (i < gfmQT_max) {
pCtx->pSelf->ppChildren[i] = 0;
i++;
}
pCtx->pSelf->pNodes = 0;
pCtx->pSelf->depth = 0;
pCtx->pSelf->numObjects = 0;
pCtx->pSelf->centerX = x + width / 2;
pCtx->pSelf->centerY = y + height / 2;
// Round the dimension up
pCtx->pSelf->halfWidth = width / 2 + (width % 2);
pCtx->pSelf->halfHeight = height / 2 + (height % 2);
rv = GFMRV_OK;
__ret:
return rv;
}
/**
* Make the quadtree static
*
* @param [ in]pCtx The quadtree's root
* @return GFMRV_ARGUMENTS_BAD, GFMRV_QUADTREE_NOT_INITIALIZED, GFMRV_OK
*/
gfmRV gfmQuadtree_setStatic(gfmQuadtreeRoot *pCtx) {
gfmRV rv;
/* Sanitize arguments */
ASSERT(pCtx, GFMRV_ARGUMENTS_BAD);
/* Check if initialized */
ASSERT(pCtx->maxDepth > 0, GFMRV_QUADTREE_NOT_INITIALIZED);
pCtx->isStatic = 1;
rv = GFMRV_OK;
__ret:
return rv;
}
/**
* Adds a new gfmGroup to the quadtree, subdividing it as necessary and
* colliding with every possible node
*
* @param pCtx The quadtree's root
* @param pGrp The gfmGroup
* @return GFMRV_ARGUMENTS_BAD, GFMRV_QUADTREE_NOT_INITIALIZED,
* GFMRV_QUADTREE_OVERLAPED, GFMRV_QUADTREE_DONE
*/
gfmRV gfmQuadtree_collideGroup(gfmQuadtreeRoot *pCtx, gfmGroup *pGrp) {
gfmRV rv;
// Sanitize arguments
ASSERT(pCtx, GFMRV_ARGUMENTS_BAD);
ASSERT(pGrp, GFMRV_ARGUMENTS_BAD);
// Check if initialized
ASSERT(pCtx->maxDepth > 0, GFMRV_QUADTREE_NOT_INITIALIZED);
// Get the list of collideable objects
rv = gfmGroup_getCollideableList(&(pCtx->pGroupList), pGrp);
ASSERT(rv == GFMRV_OK || rv == GFMRV_GROUP_LIST_EMPTY, rv);
// Start the collision
if (rv == GFMRV_OK) {
// Clear the call stack
pCtx->stack.pushPos = 0;
// Clear any previous overlap
pCtx->pOther = 0;
rv = gfmQuadtree_continue(pCtx);
}
else {
rv = GFMRV_QUADTREE_DONE;
}
__ret:
return rv;
}
/**
* Adds a new gfmObject to the quadtree, subdividing it as necessary and
* colliding with every possible node
*
* @param pCtx The quadtree's root
* @param pObj The gfmObject
* @return GFMRV_ARGUMENTS_BAD, GFMRV_QUADTREE_NOT_INITIALIZED,
* GFMRV_QUADTREE_OVERLAPED, GFMRV_QUADTREE_DONE
*/
gfmRV gfmQuadtree_collideObject(gfmQuadtreeRoot *pCtx, gfmObject *pObj) {
gfmRV rv;
// Sanitize arguments
ASSERT(pCtx, GFMRV_ARGUMENTS_BAD);
ASSERT(pObj, GFMRV_ARGUMENTS_BAD);
// Check if initialized
ASSERT(pCtx->maxDepth > 0, GFMRV_QUADTREE_NOT_INITIALIZED);
// Check if this node overlaps the root
rv = gfmQuadtree_overlap(pCtx->pSelf, pObj);
if (rv != GFMRV_TRUE) {
rv = GFMRV_QUADTREE_DONE;
goto __ret;
}
//ASSERT(rv == GFMRV_TRUE, GFMRV_QUADTREE_DONE);
// Store the object to be added
pCtx->pObject = pObj;
// Clear the call stack
pCtx->stack.pushPos = 0;
// Clear any previous overlap
pCtx->pOther = 0;
// Push the root node to start colliding
rv = gfmQuadtree_pushNode(pCtx, pCtx->pSelf);
ASSERT_NR(rv == GFMRV_OK);
// Collide it
rv = gfmQuadtree_continue(pCtx);
__ret:
return rv;
}
/**
* Adds a new gfmSprite to the quadtree, subdividing it as necessary and
* colliding with every possible node
*
* @param pCtx The quadtree's root
* @param pObj The gfmObject
* @return GFMRV_ARGUMENTS_BAD, GFMRV_QUADTREE_NOT_INITIALIZED,
* GFMRV_QUADTREE_OVERLAPED, GFMRV_QUADTREE_DONE
*/
gfmRV gfmQuadtree_collideSprite(gfmQuadtreeRoot *pCtx, gfmSprite *pSpr) {
gfmObject *pObj;
gfmRV rv;
// Sanitize sprite (other checks are done in sub-functions)
ASSERT(pSpr, GFMRV_ARGUMENTS_BAD);
// Retrieve the sprite's object
rv = gfmSprite_getObject(&pObj, pSpr);
ASSERT_NR(rv == GFMRV_OK);
// Add it to the quadtree
rv = gfmQuadtree_collideObject(pCtx, pObj);
__ret:
return rv;
}
/**
* Adds a new gfmTilemap to the quadtree, subdividing it as necessary and
* colliding with every possible node
*
* @param pCtx The quadtree's root
* @param pTMap The gfmTilemap
* @return GFMRV_ARGUMENTS_BAD, GFMRV_QUADTREE_NOT_INITIALIZED,
* GFMRV_QUADTREE_OVERLAPED, GFMRV_QUADTREE_DONE
*/
gfmRV gfmQuadtree_collideTilemap(gfmQuadtreeRoot *pCtx, gfmTilemap *pTMap) {
return GFMRV_FUNCTION_NOT_IMPLEMENTED;
}
/**
* Populates a quadtree with a group's objects
*
* @param pCtx The quadtree's root
* @param pGrp The tilemap
* @return GFMRV_OK, GFMRV_ARGUMENTS_BAD, GFMRV_QUADTREE_NOT_INITIALIZED
*/
gfmRV gfmQuadtree_populateGroup(gfmQuadtreeRoot *pCtx, gfmGroup *pGrp) {
// TODO Simply iterate through every object and add it
return GFMRV_FUNCTION_NOT_IMPLEMENTED;
}
/**
* Add an object to the quadtree without collinding it against the tree's objs
*
* @param pCtx The quadtree's root
* @param pObj The gfmObject
* @return GFMRV_OK, GFMRV_ARGUMENTS_BAD, GFMRV_QUADTREE_NOT_INITIALIZED
*/
gfmRV gfmQuadtree_populateObject(gfmQuadtreeRoot *pCtx, gfmObject *pObj) {
gfmRV rv;
// Sanitize arguments
ASSERT(pCtx, GFMRV_ARGUMENTS_BAD);
ASSERT(pObj, GFMRV_ARGUMENTS_BAD);
// Check if initialized
ASSERT(pCtx->maxDepth > 0, GFMRV_QUADTREE_NOT_INITIALIZED);
// Check that the object overlaps the root node
rv = gfmQuadtree_overlap(pCtx->pSelf, pObj);
ASSERT(rv == GFMRV_TRUE, GFMRV_OK);
// Clear the call stack
pCtx->stack.pushPos = 0;
// Clear any previous overlap
pCtx->pOther = 0;
// Push the root node to start overlaping
rv = gfmQuadtree_pushNode(pCtx, pCtx->pSelf);
ASSERT_NR(rv == GFMRV_OK);
// Continue adding the object
while (pCtx->stack.pushPos > 0) {
gfmQuadtree *pNode;
// Pop the current node
rv = gfmQuadtree_popNode(&pNode, pCtx);
ASSERT_NR(rv == GFMRV_OK);
// If it has children, push its children
if (pNode->ppChildren[gfmQT_nw]) {
gfmQuadtreePosition i;
gfmQuadtree *pChild;
i = gfmQT_nw;
while (i < gfmQT_max) {
// Get the current child
pChild = pNode->ppChildren[i];
// Check if the object overlaps this node
rv = gfmQuadtree_overlap(pChild, pObj);
if (rv == GFMRV_TRUE) {
// Push it (so it will collide later)
rv = gfmQuadtree_pushNode(pCtx, pChild);
ASSERT_NR(rv == GFMRV_OK);
}
i++;
}
}
else {
// Check if adding the node will subdivide the tree and if it
// can still be subdivided
if (pNode->numObjects + 1 > pCtx->maxNodes &&
pNode->depth + 1 < pCtx->maxDepth) {
// Subdivide the tree
rv = gfmQuadtree_subdivide(pCtx, pNode);
ASSERT_NR(rv == GFMRV_OK);
// Push the node again so its children are overlapped/pushed
rv = gfmQuadtree_pushNode(pCtx, pNode);
ASSERT_NR(rv == GFMRV_OK);
}
else {
// Add the object to this node
rv = gfmQuadtree_insertObject(pCtx, pNode, pObj);
ASSERT_NR(rv == GFMRV_OK);
}
}
}
rv = GFMRV_OK;
__ret:
return rv;
}
/**
* Add a sprite to the quadtree without collinding it against the tree's objs
*
* @param pCtx The quadtree's root
* @param pSpr The gfmSprite
* @return GFMRV_OK, GFMRV_ARGUMENTS_BAD, GFMRV_QUADTREE_NOT_INITIALIZED
*/
gfmRV gfmQuadtree_populateSprite(gfmQuadtreeRoot *pCtx, gfmSprite *pSpr) {
gfmObject *pObj;
gfmRV rv;
// Sanitize sprite (other checks are done in sub-functions)
ASSERT(pSpr, GFMRV_ARGUMENTS_BAD);
// Retrieve the sprite's object
rv = gfmSprite_getObject(&pObj, pSpr);
ASSERT_NR(rv == GFMRV_OK);
// Add it to the quadtree
rv = gfmQuadtree_populateObject(pCtx, pObj);
__ret:
return rv;
}
/**
* Populates a quadtree with tilemap's areas
*
* @param pCtx The quadtree's root
* @param pTMap The tilemap
* @return GFMRV_OK, GFMRV_ARGUMENTS_BAD, GFMRV_QUADTREE_NOT_INITIALIZED
*/
gfmRV gfmQuadtree_populateTilemap(gfmQuadtreeRoot *pCtx, gfmTilemap *pTMap) {
gfmObject *pList;
gfmRV rv;
int len;
/* Sanitize arguments */
ASSERT(pCtx, GFMRV_ARGUMENTS_BAD);
ASSERT(pTMap, GFMRV_ARGUMENTS_BAD);
/* Get how many areas there are */
rv = gfmTilemap_getAreasLength(&len, pTMap);
ASSERT_NR(rv == GFMRV_OK);
rv = gfmTilemap_getArea(&pList, pTMap, 0);
ASSERT_NR(rv == GFMRV_OK);
rv = gfmHitbox_populateQuadtree((gfmHitbox*)pList, pCtx, len);
__ret:
return rv;
}
/**
* Return both objects that overlaped
*
* @param ppObj1 A object that just overlapped another
* @param ppObj2 A object that just overlapped another
* @param pCtx The quadtree's root
* @return GFMRV_OK, GFMRV_ARGUMENTS_BAD, GFMRV_QUADTREE_NO_OVERLAP
*/
gfmRV gfmQuadtree_getOverlaping(gfmObject **ppObj1, gfmObject **ppObj2,
gfmQuadtreeRoot *pCtx) {
gfmRV rv;
// Sanitize arguments
ASSERT(ppObj1, GFMRV_ARGUMENTS_BAD);
ASSERT(ppObj2, GFMRV_ARGUMENTS_BAD);
ASSERT(pCtx, GFMRV_ARGUMENTS_BAD);
// Check that an overlap just happened
ASSERT(pCtx->pOther, GFMRV_QUADTREE_NO_OVERLAP);
// Return both objects
*ppObj1 = pCtx->pObject;
*ppObj2 = pCtx->pOther;
rv = GFMRV_OK;
__ret:
return rv;
}
/**
* Continue colliding and adding the node to the quadtree
*
* @param pCtx The quadtree's root
* @return GFMRV_ARGUMENTS_BAD, GFMRV_QUADTREE_OPERATION_NOT_ACTIVE,
* GFMRV_QUADTREE_OVERLAPED, GFMRV_QUADTREE_DONE
*/
gfmRV gfmQuadtree_continue(gfmQuadtreeRoot *pCtx) {
gfmRV rv;
// Sanitize arguments
ASSERT(pCtx, GFMRV_ARGUMENTS_BAD);
// Check that the operation is active
ASSERT(pCtx->pGroupList || pCtx->pObject,
GFMRV_QUADTREE_OPERATION_NOT_ACTIVE);
// Continue adding the object
while (pCtx->stack.pushPos > 0 || pCtx->pColliding) {
gfmQuadtree *pNode;
// If we were colliding againts objects
if (pCtx->pColliding) {
gfmQuadtreeLL *pTmp;
// Retrieve the current object and update the list
pTmp = pCtx->pColliding;
pCtx->pColliding = pCtx->pColliding->pNext;
// Check if both objects overlaps
pCtx->pOther = pTmp->pSelf;
rv = gfmObject_isOverlaping(pCtx->pObject, pCtx->pOther);
// -- Exit point --
// If they did overlap, return with that status
if (rv == GFMRV_TRUE) {
return GFMRV_QUADTREE_OVERLAPED;
}
//ASSERT(rv != GFMRV_TRUE, GFMRV_QUADTREE_OVERLAPED);
}
else {
// Pop the current node
rv = gfmQuadtree_popNode(&pNode, pCtx);
ASSERT_NR(rv == GFMRV_OK);
// If it has children, push its children
if (pNode->ppChildren[gfmQT_nw]) {
gfmQuadtreePosition i;
gfmQuadtree *pChild;
i = gfmQT_nw;
while (i < gfmQT_max) {
// Get the current child
pChild = pNode->ppChildren[i];
// Check if the object overlaps this node
rv = gfmQuadtree_overlap(pChild, pCtx->pObject);
if (rv == GFMRV_TRUE) {
// Push it (so it will collide later)
rv = gfmQuadtree_pushNode(pCtx, pChild);
ASSERT_NR(rv == GFMRV_OK);
}
i++;
}
}
else {
// If it's static, collide against the node's children
if (pCtx->isStatic) {
pCtx->pColliding = pNode->pNodes;
}
// Otherwise, check if inserting the node would subdivide
// the node (and if there's still room for that
else if (pNode->numObjects + 1 > pCtx->maxNodes &&
pNode->depth + 1 < pCtx->maxDepth) {
// Subdivide the tree
rv = gfmQuadtree_subdivide(pCtx, pNode);
ASSERT_NR(rv == GFMRV_OK);
// Push the node again so its children are overlapped/pushed
rv = gfmQuadtree_pushNode(pCtx, pNode);
ASSERT_NR(rv == GFMRV_OK);
}
else {
// Otherwise, collide with its nodes
pCtx->pColliding = pNode->pNodes;
// Add the object to this node
// NOTE: It's added to the begin, so it won't overlap itself
rv = gfmQuadtree_insertObject(pCtx, pNode, pCtx->pObject);
ASSERT_NR(rv == GFMRV_OK);
}
}
}
}
// Check if there's another object from a group
if (pCtx->pGroupList) {
gfmSprite *pSpr;
while (pCtx->pGroupList) {
// Retrieve the next sprite...
rv = gfmGroup_getNextSprite(&pSpr, &(pCtx->pGroupList));
ASSERT(rv == GFMRV_OK, rv);
// Collide it!
rv = gfmQuadtree_collideSprite(pCtx, pSpr);
if (rv != GFMRV_QUADTREE_DONE) {
// If this sprite didn't finish, return its status
return rv;
}
// If this sprite didn't collide, go to the next
}
}
// If the loop stoped, the operation finished
pCtx->pObject = 0;
rv = GFMRV_QUADTREE_DONE;
__ret:
return rv;
}
/**
* Draw the quadtree to the screen.
*
* The object's type acts as index for the color. The first five colors are
* reserved to represent the framework's types. It loops at gfmType_max
* (currently 32).
*
* It's possible (and quite easy) to force different types to use the same
* color. The following bitmask combination can be used:
*
* 27 bits for dif. entities | 5 bits for the different types
* |---------------------------|-----|
*
* This way, the user may specify 27 different types, each of which may be used
* in any of 2^27 different entities.
* NOTE: This functions will be most likely slow!! Be careful when calling it!
*
* @param pQt The quadtree's root
* @param pCtx The game's context
* @param pColors The colors to be used; Must have 32 colors, each with RGB
* components; The first set is for quadtree nodes, while the
* others respect the types on gfmTypes.h
* @return GFMRV_OK, GFMRV_ARGUMENTS_BAD
*/
gfmRV gfmQuadtree_drawBounds(gfmQuadtreeRoot *pQt, gfmCtx *pCtx,
unsigned char *pColors) {
gfmRV rv;
// Sanitize arguments
ASSERT(pQt, GFMRV_ARGUMENTS_BAD);
ASSERT(pCtx, GFMRV_ARGUMENTS_BAD);
// If no color was set, use the default ones
if (pColors == 0) {
pColors = gfmQt_defColors;
}
// Clear the call stack
pQt->stack.pushPos = 0;
// Push the root node to start colliding
rv = gfmQuadtree_pushNode(pQt, pQt->pSelf);
ASSERT_NR(rv == GFMRV_OK);
// Iterate through all nodes
while (pQt->stack.pushPos > 0 || pQt->pColliding) {
gfmQuadtree *pNode;
unsigned char *pNodeColor;
// Pop the current node
rv = gfmQuadtree_popNode(&pNode, pQt);
ASSERT_NR(rv == GFMRV_OK);
// Get the colors for the qt node
pNodeColor = pColors;
// Draw the current node
rv = gfm_drawRect(pCtx, pNode->centerX - pNode->halfWidth,
pNode->centerY - pNode->halfHeight, pNode->halfWidth * 2,
pNode->halfHeight * 2, pNodeColor[0], pNodeColor[1],
pNodeColor[2]);
ASSERT_NR(rv == GFMRV_OK);
// If it has children, push its children
if (pNode->ppChildren[gfmQT_nw]) {
gfmQuadtreePosition i;
gfmQuadtree *pChild;
i = gfmQT_nw;
while (i < gfmQT_max) {
// Get the current child
pChild = pNode->ppChildren[i];
// Push it (so it will be drawn later)
rv = gfmQuadtree_pushNode(pQt, pChild);
ASSERT_NR(rv == GFMRV_OK);
i++;
}
}
else {
gfmQuadtreeLL *pTmp;
// Otherwise, draw its nodes
pTmp = pNode->pNodes;
while (pTmp) {
unsigned int type;
int height, width, x, y;
void *pChild;
// Get the object's child
rv = gfmObject_getChild(&pChild, (int*)&type, pTmp->pSelf);
ASSERT_NR(rv == GFMRV_OK);
if (type == gfmType_sprite) {
rv = gfmSprite_getChild(&pChild, (int*)&type,
(gfmSprite*)pChild);
ASSERT_NR(rv == GFMRV_OK);
if (type == gfmType_none) {
// If no custom type was specified, set it to sprite
type = gfmType_sprite;
}
}
else if (type == gfmType_none) {
// If no custom type was specified, set it to object
type = gfmType_object;
}
// Get the object's color
if (type >= gfmType_max)
type = (type % gfmType_max);
pNodeColor = pColors + type * 3;
// Get the object's position
rv = gfmObject_getPosition(&x, &y, pTmp->pSelf);
ASSERT_NR(rv == GFMRV_OK);
// Get the object's dimensions
rv = gfmObject_getDimensions(&width, &height, pTmp->pSelf);
ASSERT_NR(rv == GFMRV_OK);
// Draw the current node
rv = gfm_drawRect(pCtx, x, y, width, height, pNodeColor[0],
pNodeColor[1], pNodeColor[2]);
ASSERT_NR(rv == GFMRV_OK);
pTmp = pTmp->pNext;
}
}
}
rv = GFMRV_OK;
__ret:
return rv;
}
| 2.46875 | 2 |
2024-11-18T22:48:58.536426+00:00 | 2020-02-02T10:25:02 | 38b61af1b0b92e432e8e33e5ca870e9637209cea | {
"blob_id": "38b61af1b0b92e432e8e33e5ca870e9637209cea",
"branch_name": "refs/heads/master",
"committer_date": "2020-02-02T10:25:02",
"content_id": "39e4ed87030e94b7e2b827493ec75b1d9cfb01f4",
"detected_licenses": [
"MIT"
],
"directory_id": "fac1cedd69a722601c3c6f610b9d9deb3944c7ad",
"extension": "c",
"filename": "traildb_bench.c",
"fork_events_count": 1,
"gha_created_at": "2020-02-02T10:24:02",
"gha_event_created_at": "2020-02-02T10:24:03",
"gha_language": null,
"gha_license_id": null,
"github_id": 237753573,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 12328,
"license": "MIT",
"license_type": "permissive",
"path": "/util/traildb_bench.c",
"provenance": "stackv2-0108.json.gz:85320",
"repo_name": "yjh0502/traildb",
"revision_date": "2020-02-02T10:25:02",
"revision_id": "b70d9e98eac3b3887f0adc8fe2750b0d4d4b94a4",
"snapshot_id": "07b762b0b37b22c9a3a038d9b7faa68c6642c2b0",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/yjh0502/traildb/b70d9e98eac3b3887f0adc8fe2750b0d4d4b94a4/util/traildb_bench.c",
"visit_date": "2020-12-27T03:46:17.351224"
} | stackv2 | #define _DEFAULT_SOURCE
#include <string.h>
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#include <inttypes.h>
#include "traildb.h"
#include "tdb_profile.h"
#define REPORT_ERROR(fmt, ...) \
do { \
fprintf(stderr, (fmt), ##__VA_ARGS__); \
} while(0)
#define REPORT_WARNING(fmt, ...) \
do { \
fprintf(stderr, ("WARNING: " fmt), ##__VA_ARGS__); \
} while(0)
#define TIMED(msg, err, stmt) \
do { \
TDB_TIMER_DEF; \
TDB_TIMER_START; \
(err) = (stmt); \
TDB_TIMER_END("traildb_bench/" msg); \
} while(0)
/**
* super dirty hack to make the compiler happy
*
* also: https://www.youtube.com/watch?v=1dV_6EtfvkM
*/
static inline const char** const_quirk(char** argv) {
void* p;
memcpy(&p, &argv, sizeof(argv));
return p;
}
static void dump_hex(const char* raw, uint64_t length)
{
for(unsigned int i = 0; i+4 <= length; i += 4) {
printf("%02x%02x%02x%02x ",
raw[i+0], raw[i+1], raw[i+2], raw[i+3]);
}
for(uint64_t i = length - (length % 4); i < length; ++i) {
printf("%02x", raw[i]);
}
}
/**
* calls tdb_get_trail over the full tdb
*/
static int do_get_all_and_decode(const tdb* db, const char* path,
tdb_field* ids, unsigned int ids_length)
{
tdb_error err;
tdb_cursor* const c = tdb_cursor_new(db); assert(c);
uint64_t items_decoded = 0;
const uint64_t num_trails = tdb_num_trails(db);
for(uint64_t trail_id = 0; trail_id < num_trails; ++trail_id) {
err = tdb_get_trail(c, trail_id);
if(err) {
REPORT_ERROR("%s: failed to extract trail %" PRIu64 ". error=%i\n",
path, trail_id, err);
goto err;
}
const tdb_event* e;
while((e = tdb_cursor_next(c))) {
for(unsigned int j = 0; j < ids_length; ++j) {
uint64_t dummy;
const tdb_item item = e->items[ids[j]];
(void)tdb_get_item_value(db, item, &dummy);
++items_decoded;
}
}
}
printf("# items decoded: %" PRIu64 "\n", items_decoded);
err:
tdb_cursor_free(c);
return err;
}
static int cmd_get_all_and_decode(char** dbs, int argc)
{
for(int i = 0; i < argc; ++i) {
const char* path = dbs[i];
tdb* db = tdb_init();
int err = tdb_open(db, path);
if(err) {
printf("Error code %i while opening TDB at %s\n", err, path);
return 1;
}
const unsigned int nfields = (unsigned)tdb_num_fields(db) - 1u;
tdb_field ids[nfields];
for (unsigned int field_id = 0; field_id < nfields; ++field_id)
ids[field_id] = field_id;
TIMED("get_all", err, do_get_all_and_decode(db, path, ids, nfields));
tdb_close(db);
}
return 0;
}
static int resolve_fieldids(tdb_field** field_ids, const tdb* db,
const char** field_names, int names_length)
{
tdb_field* out = malloc((unsigned)names_length * sizeof(tdb_field));
assert(field_ids != NULL);
for(int i = 0; i < names_length; ++i)
{
const int err = tdb_get_field(db, field_names[i], &out[i]);
if(err) {
REPORT_ERROR("Could not find field name %s\n",
field_names[i]);
goto err;
}
}
*field_ids = out;
return 0;
err:
free(out);
return -1;
}
static int cmd_decode(const char* path, const char** field_names, int names_length)
{
tdb* db = tdb_init(); assert(db);
tdb_error err = tdb_open(db, path);
if(err) {
REPORT_ERROR("Failed to open TDB. error=%i\n", err);
return 1;
}
tdb_field* ids;
err = resolve_fieldids(&ids, db, field_names, names_length);
if(err)
goto out;
/** actual field names (except for timestamp) */
for(int i = 0; i < names_length; ++i) {
assert(ids[i] > 0 && "reading from timestamp column 0 not supported");
--ids[i];
}
TIMED("cmd_decode", err, do_get_all_and_decode(db, path, ids, (unsigned)names_length));
out:
tdb_close(db);
return err;
}
static int do_recode(tdb_cons* const cons, tdb* const db,
tdb_field* const field_ids, const int num_fieldids)
{
tdb_error err;
const uint64_t num_fields = tdb_num_fields(db);
const uint64_t num_trails = tdb_num_trails(db);
const char** const values = calloc(num_fields, sizeof(char*));
uint64_t* const value_lengths = calloc(num_fields, sizeof(uint64_t));
tdb_cursor* const c = tdb_cursor_new(db);
assert(values); assert(value_lengths); assert(c);
/*
* for each trail
* for each "record" in the timeline
* extract/decode the relevant fields that are in field_ids
* insert the record
*/
for(uint64_t trail_id = 0; trail_id < num_trails; ++trail_id) {
err = tdb_get_trail(c, trail_id);
if(err) {
REPORT_ERROR("Failed to get trail (trail_id=%" PRIu64 "). error=%i\n",
trail_id, err);
goto free_mem;
}
const tdb_event* e;
for(uint64_t ev_id = 0; (e = tdb_cursor_next(c)); ++ev_id) {
/* extract step */
for(int field = 0; field < num_fieldids; ++field) {
assert(0 < field_ids[field]);
assert(field_ids[field] <= e->num_items);
/** field ids start by '1' as column 0
historically is the timestamp
column. With tdb_event, the actual
fields are 0-indexed */
values[field] = tdb_get_item_value(
db, e->items[field_ids[field] - 1],
&value_lengths[field]);
}
err = tdb_cons_add(cons, tdb_get_uuid(db, trail_id),
e->timestamp, values, value_lengths);
if(err) {
REPORT_ERROR("Failed to append record (trail_id=%" PRIu64 ", ev_id=%" PRIu64 "). error=%i\n",
trail_id, ev_id, err);
goto free_mem;
}
}
}
free_mem:
tdb_cursor_free(c);
free(value_lengths);
free(values);
return err;
}
/**
* copies a subset of data from one DB into another one. The subset is
* given by field names
*/
static int cmd_recode(const char* output_path, const char* input,
const char** field_names, int names_length)
{
assert(names_length > 0);
tdb* const db = tdb_init(); assert(db);
int err = tdb_open(db, input);
if(err) {
REPORT_ERROR("Failed to open TDB. error=%i\n", err);
return 1;
}
tdb_field* field_ids;
err = resolve_fieldids(&field_ids, db, field_names, names_length);
if(err < 0) {
goto free_tdb;
}
tdb_cons* const cons = tdb_cons_init();
assert(cons);
err = tdb_cons_open(cons, output_path, field_names, (unsigned)names_length);
if(err) {
REPORT_ERROR("Failed to create TDB cons. error=%i\n", err);
goto free_ids;
}
TIMED("recode", err, do_recode(cons, db, field_ids, names_length));
if(err)
goto close_cons;
err = tdb_cons_finalize(cons);
if(err) {
REPORT_ERROR("Failed to finalize output DB. error=%i\n", err);
}
close_cons:
tdb_cons_close(cons);
free_ids:
free(field_ids);
free_tdb:
tdb_close(db);
return err;
}
static const char** duplicate_fieldids(const tdb* db)
{
const uint64_t num_fields = tdb_num_fields(db);
assert(num_fields <= TDB_MAX_NUM_FIELDS);
const char** fieldids = malloc(num_fields * sizeof(char*));
for(tdb_field i = 1; i < num_fields; ++i) {
char* field_id = strdup(tdb_get_field_name(db, i));
assert(field_id);
fieldids[i-1] = field_id;
}
return fieldids;
}
static int cmd_append_all(const char* output_path, const char* input)
{
tdb* db = tdb_init(); assert(db);
int err = tdb_open(db, input);
if(err) {
REPORT_ERROR("Failed to open TDB. error=%i\n", err);
return 1;
}
const uint64_t num_fields = tdb_num_fields(db) - 1;
const char** field_ids = duplicate_fieldids(db);
tdb_cons* cons = tdb_cons_init();
assert(cons);
err = tdb_cons_open(cons, output_path, field_ids, num_fields);
if(err) {
REPORT_ERROR("Failed to create TDB cons. error=%i\n", err);
goto free_fieldids;
}
TIMED("tdb_cons_append()", err, tdb_cons_append(cons, db));
if(err) {
REPORT_ERROR("Failed to append DB. error=%i\n", err);
goto close_cons;
}
err = tdb_cons_finalize(cons);
if(err) {
REPORT_ERROR("Failed to finalize output DB. error=%i\n", err);
goto close_cons;
}
printf("Successfully converted / rewritten DB.\n");
close_cons:
tdb_cons_close(cons);
free_fieldids:
/* to make the compiler not complain about casting const'ness away,
let's pull out this small, dirty trick */
for(uint64_t i = 0; i < num_fields; ++i) {
void* make_compiler_happy;
memcpy(&make_compiler_happy, field_ids + i, sizeof(void*));
free(make_compiler_happy);
}
free(field_ids);
tdb_close(db);
return err ? 1 : 0;
}
static void dump_trail(const tdb* db, const uint8_t* uuid, tdb_cursor* c)
{
#define HEX4 "%02x%02x%02x%02x"
printf("cookie " HEX4 HEX4 HEX4 HEX4 "\n",
uuid[0], uuid[1], uuid[2], uuid[3],
uuid[4], uuid[5], uuid[6], uuid[7],
uuid[8], uuid[9], uuid[10], uuid[11],
uuid[12], uuid[13], uuid[14], uuid[15]);
#undef HEX4
const tdb_event* e;
while((e = tdb_cursor_next(c))) {
printf("ts=%" PRIu64 ":\n", e->timestamp);
for(uint64_t i = 0; i < e->num_items; ++i) {
const char* name = tdb_get_field_name(
db, tdb_item_field(e->items[i]));
uint64_t v_len = 0;
const char* v = tdb_get_item_value(
db, e->items[i], &v_len);
printf(" %s=", name);
dump_hex(v, v_len);
putchar('\n');
}
putchar('\n');
}
}
static int cmd_dump(const char* db_path)
{
tdb* db = tdb_init(); assert(db);
int err = tdb_open(db, db_path);
if(err) {
REPORT_ERROR("Failed to open TDB at directory %s. error=%i\n",
db_path, err);
return 1;
}
tdb_cursor* const c = tdb_cursor_new(db);
const uint64_t num_trails = tdb_num_trails(db);
for(uint64_t trail_id = 0; trail_id < num_trails; ++trail_id) {
err = tdb_get_trail(c, trail_id);
if(err) {
REPORT_ERROR("Failed to decode trail %" PRIu64 ". error=%i\n",
trail_id, err);
goto out;
}
dump_trail(db, tdb_get_uuid(db, trail_id), c);
putchar('\n');
}
out:
tdb_cursor_free(c);
tdb_close(db);
return err;
}
static int cmd_info(const char* db_path)
{
tdb* db = tdb_init(); assert(db);
int err = tdb_open(db, db_path);
if(err) {
REPORT_ERROR("Failed to open TDB at directory %s. error=%i\n",
db_path, err);
return 1;
}
printf("DB at %s:\n"
" version: %" PRIu64 "\n"
" #trails: %" PRIu64 "\n"
" #events: %" PRIu64 "\n"
" #fields: %" PRIu64 "\n"
"\n"
" min timestamp: %" PRIu64 "\n"
" max timestamp: %" PRIu64 "\n",
db_path,
tdb_version(db),
tdb_num_trails(db),
tdb_num_events(db),
tdb_num_fields(db),
tdb_min_timestamp(db),
tdb_max_timestamp(db));
printf("\nColumns: \n");
printf(" field[00] = %s (implicit)\n", tdb_get_field_name(db, 0 ));
for(unsigned fid = 1; fid < tdb_num_fields(db); ++fid) {
printf(" field[%02u] = %s\n", fid, tdb_get_field_name(db, fid));
}
tdb_close(db);
return err;
}
static void print_help(void)
{
printf(
"Usage: traildb_bench <command> [<mode-specific options>*]\n"
"\n"
"Available commands:\n"
" decode-all <database directory>*\n"
" :: iterates over the complete DB, decoding\n"
" every value encountered\n"
" decode <database directory> <field name>+\n"
" :: iterates over the complete DB, decoding\n"
" the values of each given field\n"
" append-all <output path> <input path>\n"
" :: copies data from one DB into a new or\n"
" existing database. Has multiple use-cases,\n"
" such as: converting DB formats, merging DBs, etc..\n"
" Assumes DBs have identical fieldsets.\n"
" recode <output path> <input path> <column name>+\n"
" :: copies the given (sub)set of columns from the DB at\n"
" /input path/ into /output path/\n"
" info <path>\n"
" :: displays information on a TDB\n"
" dump <path>\n"
" :: dumps contents of a traildb in a most primitive way.\n"
);
}
#define IS_CMD(cmd, nargs) (strcmp(command, (cmd)) == 0 && argc >= (nargs + 2))
int main(int argc, char** argv)
{
if(argc < 2) {
print_help();
return 1;
}
const char* const command = argv[1];
const char** const cargv = const_quirk(argv);
if(IS_CMD("decode-all", 1)) {
return cmd_get_all_and_decode(argv + 2, argc - 2);
}
else if(IS_CMD("decode", 2)) {
return cmd_decode(argv[2], cargv + 3, argc - 3);
}
else if(IS_CMD("append-all", 2)) {
return cmd_append_all(argv[2], argv[3]);
}
else if(IS_CMD("recode", 3)) {
return cmd_recode(argv[2], argv[3], cargv + 4, argc - 4);
}
else if(IS_CMD("info", 1)) {
return cmd_info(argv[2]);
}
else if(IS_CMD("dump", 1)) {
return cmd_dump(argv[2]);
}
else {
print_help();
return 1;
}
return 0;
}
| 2.375 | 2 |
2024-11-18T22:48:58.719043+00:00 | 2023-07-15T08:46:45 | 7b1755c33840318b6e6c1d2a7defbd4c695f93df | {
"blob_id": "7b1755c33840318b6e6c1d2a7defbd4c695f93df",
"branch_name": "refs/heads/master",
"committer_date": "2023-07-15T08:46:45",
"content_id": "202f8a803557c2cfb6dce8ba636f86dbdfb69768",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "1098cc6b43f4be758d52d45ceb7a0adb82807abc",
"extension": "c",
"filename": "command.c",
"fork_events_count": 202,
"gha_created_at": "2012-04-03T12:26:23",
"gha_event_created_at": "2023-09-09T14:21:48",
"gha_language": "C",
"gha_license_id": "NOASSERTION",
"github_id": 3917698,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4039,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/group-function/command.c",
"provenance": "stackv2-0108.json.gz:85579",
"repo_name": "canboat/canboat",
"revision_date": "2023-07-15T08:46:45",
"revision_id": "81255ffa9d32147cfcdbb8279a43b552be890b92",
"snapshot_id": "78e2ae901e18744a4e8954a9070f49ac43451b3f",
"src_encoding": "UTF-8",
"star_events_count": 425,
"url": "https://raw.githubusercontent.com/canboat/canboat/81255ffa9d32147cfcdbb8279a43b552be890b92/group-function/command.c",
"visit_date": "2023-09-03T11:58:07.733885"
} | stackv2 | /*
(C) 2009-2023, Kees Verruijt, Harlingen, The Netherlands.
This file is part of CANboat.
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 <math.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
#include <time.h>
#include "common.h"
#include "license.h"
/*
, "NMEA - Command/Request/Acknowledge group function", 126208, false, 15, 2,
{ { "Function Code", 8, RES_LOOKUP, false, ",0=Request,1=Command,2=Acknowledge", "" }
, { "PGN", 24, RES_INTEGER, false, 0, "Commanded or requested PGN" }
, { "Priority", 4, 1, false, 0, "8 = leave priority unchanged" }
, { "Reserved", 4, 1, false, 0, "" }
, { "# of Commanded Parameters", 8, 1, false, 0, "How many parameter pairs will follow" }
, { "Parameter Index", 8, RES_INTEGER, false, 0, "First parameter index" }
, { "Parameter Value", 16, RES_INTEGER, false, 0, "First parameter new value" }
, { 0 }
}
*/
#define MAX_FIELDS 20
#define PACKED __attribute__((__packed__))
typedef struct
{
uint8_t functionCode;
uint8_t pgn[3];
int priority : 4;
int reserved : 4;
uint8_t count;
uint8_t parameters[MAX_FIELDS * 5];
} PACKED command_group_function_t;
void usage(char **argv, char **av)
{
if (av)
{
fprintf(stderr, "Unknown or invalid argument %s\n", av[0]);
}
fprintf(stderr, "Usage: %s <dest> <prio> <pgn> <field>=<value> ... | -version\n\n", argv[0]);
fprintf(stderr, " <field> is a decimal value\n");
fprintf(stderr, " <value> is a hexadecimal value; the length of the value defines how many bytes are encoded\n");
fprintf(stderr, " Maximum # of fields: %d\n\n", MAX_FIELDS);
fprintf(stderr, "This program uses PGN 126208 to command a device to set fields to a particular value.\n");
fprintf(stderr, "The use of this is thus completely dependent on what the device allows.\n\n" COPYRIGHT);
exit(1);
}
int main(int argc, char **argv)
{
int ac = argc;
char **av = argv;
long dest;
long pgn;
long prio;
size_t cnt = 0;
command_group_function_t command;
size_t i, bytes;
char *p, *e;
uint8_t *b;
uint32_t v;
char dateStr[DATE_LENGTH];
if (ac > 1 && strcasecmp(av[1], "-version") == 0)
{
printf("%s\n", VERSION);
}
if (ac < 5 || ac > 4 + MAX_FIELDS)
{
usage(argv, 0);
}
ac--, av++; /* lose the command name */
dest = strtol(av[0], 0, 10);
ac--, av++; /* lose the dest */
prio = strtol(av[0], 0, 10);
ac--, av++; /* lose the prio */
pgn = strtol(av[0], 0, 10);
ac--, av++; /* lose the pgn */
b = &command.parameters[0];
for (; ac; ac--, av++)
{
p = strchr(av[0], '=');
if (p)
{
p++;
*b++ = strtol(av[0], 0, 10);
v = strtoul(p, &e, 16);
for (i = (e - p) / 2; i; i--)
{
*b++ = (v & 255);
v = v >> 8;
}
cnt++;
}
else
{
usage(argv, av);
}
}
command.functionCode = 1;
command.pgn[0] = (pgn) &0xff;
command.pgn[1] = (pgn >> 8) & 0xff;
command.pgn[2] = (pgn >> 16);
command.priority = prio;
command.reserved = -1;
command.count = cnt;
bytes = b - (uint8_t *) &command;
printf("%s,2,126208,0,%lu,%zu", now(dateStr), dest, bytes);
for (i = 0; i < bytes; i++)
{
printf(",%02x", ((unsigned char *) &command)[i]);
}
printf("\n");
exit(0);
}
| 2.234375 | 2 |
2024-11-18T22:49:00.495975+00:00 | 2021-01-20T07:35:01 | 0b15130f0d496e9ae1b357e9bd948456f7b3b0e2 | {
"blob_id": "0b15130f0d496e9ae1b357e9bd948456f7b3b0e2",
"branch_name": "refs/heads/master",
"committer_date": "2021-01-20T07:35:01",
"content_id": "0d80fd98f8147bada75294ab87b2bcb827ece123",
"detected_licenses": [
"MIT"
],
"directory_id": "158b07cf07dbfef7050839e67f0d39f7b3a61583",
"extension": "c",
"filename": "api_support.c",
"fork_events_count": 0,
"gha_created_at": "2019-03-26T19:43:36",
"gha_event_created_at": "2019-03-26T19:43:36",
"gha_language": null,
"gha_license_id": null,
"github_id": 177857638,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 10538,
"license": "MIT",
"license_type": "permissive",
"path": "/src/api_support.c",
"provenance": "stackv2-0108.json.gz:86614",
"repo_name": "ArnCarveris/flecs",
"revision_date": "2021-01-20T07:35:01",
"revision_id": "e6399b65d994f361b4069e898679f5c7fb679f9a",
"snapshot_id": "36036cb3779421faf32d76a3f645337d3312cf4c",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/ArnCarveris/flecs/e6399b65d994f361b4069e898679f5c7fb679f9a/src/api_support.c",
"visit_date": "2021-06-21T11:02:58.137177"
} | stackv2 | #include "private_api.h"
/** Parse callback that adds type to type identifier for ecs_new_type */
static
int parse_type_action(
ecs_world_t *world,
const char *name,
const char *sig,
int64_t column,
ecs_sig_from_kind_t from_kind,
ecs_sig_oper_kind_t oper_kind,
ecs_sig_inout_kind_t inout_kind,
ecs_entity_t role,
const char *entity_id,
const char *source_id,
const char *trait_id,
const char *arg_name,
void *data)
{
ecs_vector_t **array = data;
(void)source_id;
(void)inout_kind;
if (arg_name) {
ecs_parser_error(name, sig, column,
"column names not supported in type expression");
return -1;
}
if (strcmp(entity_id, "0")) {
ecs_entity_t entity = 0;
if (from_kind != EcsFromOwned) {
if (!name) {
return -1;
}
ecs_parser_error(name, sig, column,
"source modifiers not supported for type expressions");
return -1;
}
entity = ecs_lookup_fullpath(world, entity_id);
if (!entity) {
if (!name) {
return -1;
}
ecs_parser_error(name, sig, column,
"unresolved identifier '%s'", entity_id);
return -1;
}
if (trait_id) {
ecs_entity_t trait = ecs_lookup_fullpath(world, trait_id);
if (!trait) {
ecs_parser_error(name, sig, column,
"unresolved trait identifier '%s'", trait_id);
return -1;
}
entity = ecs_entity_t_comb(entity, trait);
}
if (oper_kind == EcsOperAnd) {
ecs_entity_t* e_ptr = ecs_vector_add(array, ecs_entity_t);
*e_ptr = entity | role;
} else {
if (!name) {
return -1;
}
/* Only AND and OR operators are supported for type expressions */
ecs_parser_error(name, sig, column,
"invalid operator for type expression");
return -1;
}
}
return 0;
}
static
ecs_table_t* table_from_vec(
ecs_world_t *world,
ecs_vector_t *vec)
{
ecs_entity_t *array = ecs_vector_first(vec, ecs_entity_t);
int32_t count = ecs_vector_count(vec);
ecs_entities_t entities = {
.array = array,
.count = count
};
return ecs_table_find_or_create(world, &entities);
}
static
EcsType type_from_vec(
ecs_world_t *world,
ecs_vector_t *vec)
{
EcsType result = {0, 0};
ecs_table_t *table = table_from_vec(world, vec);
if (!table) {
return result;
}
result.type = table->type;
/* Create normalized type. A normalized type resolves all elements with an
* AND flag and appends them to the resulting type, where the default type
* maintains the original type hierarchy. */
ecs_vector_t *normalized = NULL;
ecs_entity_t *array = ecs_vector_first(vec, ecs_entity_t);
int32_t i, count = ecs_vector_count(vec);
for (i = 0; i < count; i ++) {
ecs_entity_t e = array[i];
if (ECS_HAS_ROLE(e, AND)) {
ecs_entity_t entity = e & ECS_COMPONENT_MASK;
const EcsType *type_ptr = ecs_get(world, entity, EcsType);
ecs_assert(type_ptr != NULL, ECS_INVALID_PARAMETER,
"flag must be applied to type");
ecs_vector_each(type_ptr->normalized, ecs_entity_t, c_ptr, {
ecs_entity_t *el = ecs_vector_add(&normalized, ecs_entity_t);
*el = *c_ptr;
})
}
}
/* Only get normalized type if it's different from the type */
if (normalized) {
ecs_entities_t normalized_array = ecs_type_to_entities(normalized);
ecs_table_t *norm_table = ecs_table_traverse_add(
world, table, &normalized_array, NULL);
result.normalized = norm_table->type;
ecs_vector_free(normalized);
} else {
result.normalized = result.type;
}
return result;
}
static
EcsType type_from_expr(
ecs_world_t *world,
const char *name,
const char *expr)
{
if (expr) {
ecs_vector_t *vec = ecs_vector_new(ecs_entity_t, 1);
ecs_parse_expr(world, name, expr, parse_type_action, &vec);
EcsType result = type_from_vec(world, vec);
ecs_vector_free(vec);
return result;
} else {
return (EcsType){0, 0};
}
}
/* If a name prefix is set with ecs_set_name_prefix, check if the entity name
* has the prefix, and if so remove it. This enables using prefixed names in C
* for components / systems while storing a canonical / language independent
* identifier. */
const char* ecs_name_from_symbol(
ecs_world_t *world,
const char *type_name)
{
const char *prefix = world->name_prefix;
if (type_name && prefix) {
ecs_size_t len = ecs_os_strlen(prefix);
if (!ecs_os_strncmp(type_name, prefix, len) &&
(isupper(type_name[len]) || type_name[len] == '_'))
{
if (type_name[len] == '_') {
return type_name + len + 1;
} else {
return type_name + len;
}
}
}
return type_name;
}
void ecs_set_symbol(
ecs_world_t *world,
ecs_entity_t e,
const char *name)
{
if (!name) {
return;
}
const char *e_name = ecs_name_from_symbol(world, name);
ecs_set(world, e, EcsName, {
.value = e_name,
.symbol = name
});
}
ecs_entity_t ecs_lookup_w_id(
ecs_world_t *world,
ecs_entity_t e,
const char *name)
{
if (e) {
if (name) {
/* Make sure name is the same */
const char *existing = ecs_get_name(world, e);
if (existing && strcmp(existing, name)) {
ecs_abort(ECS_INCONSISTENT_NAME, name);
}
if (!existing) {
ecs_set_symbol(world, e, name);
}
}
}
ecs_entity_t result = e;
if (!result) {
if (!name) {
/* If neither an id nor name is specified, return 0 */
return 0;
}
result = ecs_lookup(world, name);
}
return result;
}
/* -- Public functions -- */
ecs_type_t ecs_type_from_str(
ecs_world_t *world,
const char *expr)
{
EcsType type = type_from_expr(world, NULL, expr);
return type.normalized;
}
ecs_table_t* ecs_table_from_str(
ecs_world_t *world,
const char *expr)
{
if (expr) {
ecs_vector_t *vec = ecs_vector_new(ecs_entity_t, 1);
ecs_parse_expr(world, NULL, expr, parse_type_action, &vec);
ecs_table_t *result = table_from_vec(world, vec);
ecs_vector_free(vec);
return result;
} else {
return NULL;
}
}
ecs_entity_t ecs_new_entity(
ecs_world_t *world,
ecs_entity_t e,
const char *name,
const char *expr)
{
ecs_entity_t result = ecs_lookup_w_id(world, e, name);
if (!result) {
result = ecs_new(world, 0);
ecs_set_symbol(world, result, name);
}
EcsType type = type_from_expr(world, name, expr);
ecs_add_type(world, result, type.normalized);
return result;
}
ecs_entity_t ecs_new_prefab(
ecs_world_t *world,
ecs_entity_t e,
const char *name,
const char *expr)
{
ecs_entity_t result = ecs_lookup_w_id(world, e, name);
if (!result) {
result = ecs_new(world, 0);
ecs_set_symbol(world, result, name);
}
ecs_add_entity(world, result, EcsPrefab);
EcsType type = type_from_expr(world, name, expr);
ecs_add_type(world, result, type.normalized);
return result;
}
ecs_entity_t ecs_new_component(
ecs_world_t *world,
ecs_entity_t e,
const char *name,
size_t size,
size_t alignment)
{
ecs_assert(world != NULL, ECS_INVALID_PARAMETER, NULL);
assert(world->magic == ECS_WORLD_MAGIC);
bool in_progress = world->in_progress;
/* If world is in progress component may be registered, but only when not
* in multithreading mode. */
if (in_progress) {
ecs_assert(ecs_vector_count(world->workers) < 1,
ECS_INVALID_WHILE_ITERATING, NULL);
/* Component creation should not be deferred */
ecs_defer_end(world);
world->in_progress = false;
}
ecs_entity_t result = ecs_lookup_w_id(world, e, name);
if (!result) {
result = ecs_new_component_id(world);
ecs_set_symbol(world, result, name);
}
/* ecs_new_component_id does not add the scope, so add it explicitly */
ecs_entity_t scope = world->stage.scope;
if (scope) {
ecs_add_entity(world, result, ECS_CHILDOF | scope);
}
bool added = false;
EcsComponent *ptr = ecs_get_mut(world, result, EcsComponent, &added);
if (added) {
ptr->size = ecs_from_size_t(size);
ptr->alignment = ecs_from_size_t(alignment);
} else {
if (ptr->size != ecs_from_size_t(size)) {
ecs_abort(ECS_INVALID_COMPONENT_SIZE, name);
}
if (ptr->alignment != ecs_from_size_t(alignment)) {
ecs_abort(ECS_INVALID_COMPONENT_SIZE, name);
}
}
ecs_modified(world, result, EcsComponent);
if (e > world->stats.last_component_id && e < ECS_HI_COMPONENT_ID) {
world->stats.last_component_id = e + 1;
}
if (in_progress) {
world->in_progress = true;
ecs_defer_begin(world);
}
return result;
}
ecs_entity_t ecs_new_type(
ecs_world_t *world,
ecs_entity_t e,
const char *name,
const char *expr)
{
assert(world->magic == ECS_WORLD_MAGIC);
ecs_entity_t result = ecs_lookup_w_id(world, e, name);
if (!result) {
result = ecs_new_entity(world, 0, name, NULL);
}
EcsType type_parsed = type_from_expr(world, name, expr);
bool added = false;
EcsType *type = ecs_get_mut(world, result, EcsType, &added);
if (added) {
type->type = type_parsed.type;
type->normalized = type_parsed.normalized;
} else {
if (type->type != type_parsed.type) {
ecs_abort(ECS_ALREADY_DEFINED, name);
}
if (type->normalized != type_parsed.normalized) {
ecs_abort(ECS_ALREADY_DEFINED, name);
}
}
/* This will allow the type to show up in debug tools */
ecs_map_set(world->type_handles, (uintptr_t)type_parsed.type, &result);
return result;
}
| 2.28125 | 2 |
2024-11-18T22:49:00.946023+00:00 | 2013-08-20T06:09:22 | 161b623282576ab1791adb894b747212103170d8 | {
"blob_id": "161b623282576ab1791adb894b747212103170d8",
"branch_name": "refs/heads/master",
"committer_date": "2013-08-20T06:09:22",
"content_id": "da03fd50af6c8b8ec69aaf797661651a290eb86e",
"detected_licenses": [
"MIT"
],
"directory_id": "b88e5d0a2e374cdfe33a58d9923facf551822810",
"extension": "c",
"filename": "crack_2_2.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": 1065,
"license": "MIT",
"license_type": "permissive",
"path": "/crack_2_2.c",
"provenance": "stackv2-0108.json.gz:87000",
"repo_name": "xeostream/cracking-the-coding-interview",
"revision_date": "2013-08-20T06:09:22",
"revision_id": "306a499fce292ea60c33d73db76410f192825ae9",
"snapshot_id": "aa2741098ed3bbf91f46a76c63f377921f21e82b",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/xeostream/cracking-the-coding-interview/306a499fce292ea60c33d73db76410f192825ae9/crack_2_2.c",
"visit_date": "2016-09-06T17:40:53.761552"
} | stackv2 | #include <stdio.h>
#include <stdlib.h>
typedef struct list {
int data;
struct list *next;
}list;
list *init(int *, int);
void print(list *);
list *getnode(void);
void getN(list *, int *);
void printN(list *, int);
main()
{
int n = 10, position = 3;
int test[] = {3,2,1,3,5,6,2,6,3,1};
list *first = init(test, n);
printN(first, position);
getN(first, &position);
return 0;
}
list *init(int *test, int n)
{
list *nod, *p, *head;
int m;
for (m = 0; m < n; m++) {
nod = getnode();
nod->data = *test++;
if (m == 0) {
head = p = nod;
continue;
}
p->next = nod;
p = nod;
}
p->next = NULL;
return head;
}
list *getnode()
{
return (list *)malloc(sizeof(list));
}
void getN(list *head, int *position)
{
if (head->next != NULL)
getN(head->next, position);
(*position)--;
if (*position == 0)
printf("%d\n", head->data);
}
void printN(list *head, int n)
{
list *temp = head;
while (n >= 1 && temp->next) {
temp = temp->next;
n--;
}
while (temp) {
head = head->next;
temp = temp->next;
}
printf("%d\n", head->data);
} | 3.34375 | 3 |
2024-11-18T22:49:01.181514+00:00 | 2018-11-13T02:25:04 | 0ced613484bf2cd43279d35875b9e52d88533edb | {
"blob_id": "0ced613484bf2cd43279d35875b9e52d88533edb",
"branch_name": "refs/heads/master",
"committer_date": "2018-11-13T02:25:04",
"content_id": "4106c27e78189634ed55ea7e95a9e1fcf91d60fa",
"detected_licenses": [
"MIT"
],
"directory_id": "b2c3b6b6ed2c5330bc6b24125bf92ae58cad74b7",
"extension": "c",
"filename": "gdt.c",
"fork_events_count": 0,
"gha_created_at": "2018-10-08T18:51:00",
"gha_event_created_at": "2018-10-08T18:51:01",
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 152129988,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 8431,
"license": "MIT",
"license_type": "permissive",
"path": "/src/kernel/gdt.c",
"provenance": "stackv2-0108.json.gz:87386",
"repo_name": "dhinakg/Star",
"revision_date": "2018-11-13T02:25:04",
"revision_id": "ebc405bf5176df7b8f770173eefdfea648f51129",
"snapshot_id": "c07b2be2960e11fa5e9d2622996d7c260b79aa03",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/dhinakg/Star/ebc405bf5176df7b8f770173eefdfea648f51129/src/kernel/gdt.c",
"visit_date": "2020-03-31T10:18:11.098226"
} | stackv2 | /*
* File: gdt.c
*
* Copyright (c) 2017-2018 Sydney Erickson, John Davis
*
* 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 <main.h>
#include <kprint.h>
#include <string.h>
#include <kernel/gdt.h>
#include <kernel/tss.h>
// Function to load GDT, implemented in gdt.asm.
extern void _gdt_load(gdt_ptr_t *gdtPtr, uintptr_t offsets);
extern void _gdt_tss_load(uintptr_t offset);
// Represents the 32-bit GDT for the BSP and pointer to it. This is used as
// the system GDT on 32-bit systems and when starting up other processors,
static gdt_entry_t bspGdt32[GDT32_ENTRIES];
#ifdef X86_64
// Represents the 64-bit GDT for the BSP and pointer to it. Only used in 64-bit mode.
static gdt_entry_t bspGdt64[GDT64_ENTRIES];
#endif
// Task state segment. Used for switching from ring 3 tasks.
static tss_t bspTss;
/**
* Gets the BSP's 32-bit GDT.
*/
gdt_entry_t *gdt_get_bsp32(void) {
return bspGdt32;
}
#ifdef X86_64
/**
* Gets the BSP's 64-bit GDT.
*/
gdt_entry_t *gdt_get_bsp64(void) {
return bspGdt64;
}
#endif
/**
* Creates an entry in the GDT.
*/
static void gdt_set_descriptor(gdt_entry_t *gdt, uint8_t num, bool code, bool userMode, bool is64Bits) {
// Set up the descriptor base address.
gdt[num].BaseLow = 0;
gdt[num].BaseHigh = 0;
// Set up the descriptor limits.
gdt[num].LimitLow = 0xFFFF;
gdt[num].LimitHigh = 0xF;
// Set access bits.
gdt[num].Writeable = true;
gdt[num].DirectionConforming = false;
gdt[num].Executable = code;
gdt[num].DescriptorBit = true;
gdt[num].Privilege = userMode ? GDT_PRIVILEGE_USER : GDT_PRIVILEGE_KERNEL;
gdt[num].Present = true;
// Set flags.
gdt[num].ReservedZero = 0;
gdt[num].Is64Bits = is64Bits;
gdt[num].Is32Bits = !is64Bits;
gdt[num].IsLimit4K = true;
}
/**
* Creates the TSS entry in the GDT.
*/
static void gdt_set_tss(gdt_entry_t *gdt, uint8_t num, uintptr_t base, uint32_t size) {
// Set TSS base address.
gdt[num].BaseLow = (base & 0xFFFFFF);
gdt[num].BaseHigh = (base >> 24) & 0xFF;
// Set TSS size.
gdt[num].LimitLow = (size & 0xFFFF);
gdt[num].LimitHigh = (size >> 16) & 0x0F;
// Set access bits.
gdt[num].Accessed = true;
gdt[num].Writeable = false;
gdt[num].DirectionConforming = false;
gdt[num].Executable = true;
gdt[num].DescriptorBit = false;
gdt[num].Privilege = GDT_PRIVILEGE_USER;
gdt[num].Present = true;
// Set flags.
gdt[num].ReservedZero = 0;
gdt[num].Is64Bits = false;
gdt[num].Is32Bits = false;
gdt[num].IsLimit4K = false;
#ifdef X86_64
// Set high 32 bits of TSS address.
gdt[num+1].LimitLow = (base >> 32) & 0xFFFF;
gdt[num+1].BaseLow = (base >> 48) & 0xFFFF;
// Other address fields are zero.
gdt[num+1].BaseHigh = 0;
gdt[num+1].LimitHigh = 0;
// Set access bits.
gdt[num+1].Accessed = false;
gdt[num+1].Writeable = false;
gdt[num+1].DirectionConforming = false;
gdt[num+1].Executable = false;
gdt[num+1].DescriptorBit = false;
gdt[num+1].Privilege = 0;
gdt[num+1].Present = false;
// Set flags.
gdt[num+1].ReservedZero = 0;
gdt[num+1].Is64Bits = false;
gdt[num+1].Is32Bits = false;
gdt[num+1].IsLimit4K = false;
#endif
}
/**
* Sets the kernel ESP in the TSS.
*/
void gdt_tss_set_kernel_stack(tss_t *tss, uintptr_t stack) {
// If TSS specified is nothing, use the BSP TSS.
if (tss == NULL)
tss = &bspTss;
// Set stack.
#ifdef X86_64
tss->RSP0 = stack;
#else
tss->SS0 = GDT_KERNEL_DATA_OFFSET;
tss->ESP0 = stack;
#endif
}
/**
* Gets the kernel ESP in the TSS.
*/
uintptr_t gdt_tss_get_kernel_stack(tss_t *tss) {
// If TSS specified is nothing, use the BSP TSS.
if (tss == NULL)
tss = &bspTss;
// Return stack.
#ifdef X86_64
// 64-bit code here.
return tss->RSP0;
#else
return tss->ESP0;
#endif
}
/**
* Creates a GDT pointer.
* @param gdt The GDT.
* @param entries The number of entries in the GDT.
*/
gdt_ptr_t gdt_create_ptr(gdt_entry_t *gdt, uint8_t entries) {
return (gdt_ptr_t) { (sizeof(gdt_entry_t) * entries) - 1, gdt };
}
/**
* Loads a GDT.
* @param gdt The GDT.
* @param entries The number of entries in the GDT.
*/
void gdt_load(gdt_entry_t *gdt, uint8_t entries) {
// Load the GDT into the processor.
gdt_ptr_t gdtPtr = gdt_create_ptr(gdt, entries);
_gdt_load(&gdtPtr, GDT_KERNEL_DATA_OFFSET);
kprintf("\e[31mGDT: Loaded GDT at 0x%p.\e[0m\n", gdt);
}
/**
* Loads the TSS.
*/
void gdt_tss_load(tss_t *tss) {
// Load the TSS into the processor.
_gdt_tss_load(GDT_TSS_OFFSET);
kprintf("\e[31mGDT: Loaded TSS at 0x%p.\e[0m\n", tss);
}
/**
* Gets the GDT for the currently executing processor.
*/
gdt_entry_t *gdt_get(void) {
// Get GDT pointer.
gdt_ptr_t gdtPtr = { };
asm volatile ("sgdt %0" : "=g"(gdtPtr));
// Return GDT.
return gdtPtr.Table;
}
/**
* Gets the TSS for the currently executing processor.
*/
tss_t *gdt_tss_get(void) {
// Get current GDT.
gdt_entry_t *gdt = gdt_get();
// Get TSS offset.
uint16_t tssOffset = 0;
asm volatile ("str %%ax" : "=a"(tssOffset));
uint8_t tssIndex = tssOffset / sizeof(gdt_entry_t);
// Get TSS address.
uintptr_t tssAddress = ((uint32_t)(gdt[tssIndex].BaseLow)) | ((uint32_t)(gdt[tssIndex].BaseHigh) << 24);
#ifdef X86_64
tssAddress |= ((uint64_t)(gdt[tssIndex+1].LimitLow) << 32) | ((uint64_t)(gdt[tssIndex+1].BaseLow) << 48);
#endif
// Return TSS pointer.
return (tss_t*)tssAddress;
}
/**
* Fills the specified GDT.
* @param gdt The pointer to the GDT.
* @param is64Bits Whether or not the GDT is 64-bit.
* @param tss The pointer to a TSS, if any.
*/
void gdt_fill(gdt_entry_t *gdt, bool is64Bits, tss_t *tss) {
// Set null segment.
gdt[GDT_NULL_INDEX] = (gdt_entry_t) { };
// Set code and data segment for kernel.
gdt_set_descriptor(gdt, GDT_KERNEL_CODE_INDEX, true, false, is64Bits);
gdt_set_descriptor(gdt, GDT_KERNEL_DATA_INDEX, false, false, false);
// Set code and data segment for ring 3 (user mode).
gdt_set_descriptor(gdt, GDT_USER_CODE_INDEX, true, true, is64Bits);
gdt_set_descriptor(gdt, GDT_USER_DATA_INDEX, false, true, false);
// If a TSS was specified, add it too.
if (tss != NULL)
gdt_set_tss(gdt, GDT_TSS_INDEX, (uintptr_t)tss, sizeof(tss_t));
}
/**
* Initializes the BSP GDT and TSS.
*/
void gdt_init_bsp(void) {
// Zero out TSS.
kprintf("\e[31mGDT: Initializing TSS at 0x%p...\n", &bspTss);
memset(&bspTss, 0, sizeof(tss_t));
#ifdef X86_64
// Set initial kernel (ring 0) stack pointer.
bspTss.RSP0 = 0;
#else
// Set initial kernel (ring 0) info.
bspTss.SS0 = GDT_KERNEL_DATA_OFFSET;
bspTss.ESP0 = 0;
#endif
// Set up the 32-bit GDT.
kprintf("GDT: Initializing 32-bit GDT at 0x%p...\n", bspGdt32);
#ifdef X86_64
gdt_fill(bspGdt32, false, NULL);
// Set up the 64-bit GDT.
kprintf("GDT: Initializing 64-bit GDT at 0x%p...\n", bspGdt64);
gdt_fill(bspGdt64, true, &bspTss);
// Load 64-bit GDT.
gdt_load(bspGdt64, GDT64_ENTRIES);
#else
gdt_fill(bspGdt32, false, &bspTss);
// Load 32-bit GDT.
gdt_load(bspGdt32, GDT32_ENTRIES);
#endif
// Load TSS.
gdt_tss_load(&bspTss);
kprintf("\e[31mGDT: Initialized!\e[0m\n");
}
| 2.28125 | 2 |
2024-11-18T22:49:01.337017+00:00 | 2020-10-06T17:53:29 | 670e805a6cb420de00a897e5aff0d4201dde66ef | {
"blob_id": "670e805a6cb420de00a897e5aff0d4201dde66ef",
"branch_name": "refs/heads/master",
"committer_date": "2020-10-06T17:53:29",
"content_id": "999b66212cff67b579d20ba666e0a92d6e4e77b2",
"detected_licenses": [
"MIT"
],
"directory_id": "5b6f62d9e383041e7f6f07067b8584417f8f04d1",
"extension": "c",
"filename": "struct_com_malloc_realloc.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 246350522,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1151,
"license": "MIT",
"license_type": "permissive",
"path": "/Aula 06 - Exemplos/struct_com_malloc_realloc.c",
"provenance": "stackv2-0108.json.gz:87642",
"repo_name": "Diego-Lopes-Ferreira/Diego-Lopes-Ferreira-IF61D-UTFPR",
"revision_date": "2020-10-06T17:53:29",
"revision_id": "ed5e77c07a839612dc3b5d8805c6e2df6722cece",
"snapshot_id": "3a492af1f6867ff3b27277708dd893f3dd10f90d",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/Diego-Lopes-Ferreira/Diego-Lopes-Ferreira-IF61D-UTFPR/ed5e77c07a839612dc3b5d8805c6e2df6722cece/Aula 06 - Exemplos/struct_com_malloc_realloc.c",
"visit_date": "2022-12-25T22:59:06.414075"
} | stackv2 | #include <stdio.h>
#include <stdlib.h>
struct l{
int cod;
int quantidade;
char descricao[50];
float valorunit;
};
typedef struct l tp_lista;
int main(){
tp_lista *compras;
int i, qtd, fim;
qtd = 2;
if ((malloc(qtd * sizeof(tp_lista)) == NULL)){
printf("\nSem espaco de memoria\n");
exit(1);
}
compras = malloc(qtd * sizeof(tp_lista));
for(i = 0;i < qtd;i = i + 1){
printf("Codigo --> ");
scanf("%d",&compras[i].cod);
printf("Quantidade --> ");
scanf("%d",&compras[i].quantidade);
printf("Descricao --> ");
fflush(stdin);
gets(compras[i].descricao);
printf("Valor unitario --> ");
scanf("%f",&compras[i].valorunit);
printf("\nDeseja continuar? 1 para SIM ou 2 para NAO: ");
scanf("%d",&fim);
if(fim == 1){
realloc(compras,2 * sizeof(tp_lista));
qtd = qtd + 2;
}
system("cls");
}
for(i = 0;i < qtd;i = i + 1){
printf("\nCodigo ----------> %d", compras[i].cod);
printf("\nQuantidade ------> %d", compras[i].quantidade);
printf("\nDescricao -------> %s", compras[i].descricao);
printf("\nValor unitario --> %2.2f", compras[i].valorunit);
}
return 0;
} | 3.265625 | 3 |
2024-11-18T22:49:04.231071+00:00 | 2018-09-10T17:44:43 | 4583d172ea3afc115e1f5565cee9df7b51fa298b | {
"blob_id": "4583d172ea3afc115e1f5565cee9df7b51fa298b",
"branch_name": "refs/heads/master",
"committer_date": "2018-09-10T17:44:43",
"content_id": "c54f78d0a7c34df687a8ef3caa7fe7eb6fdacdb8",
"detected_licenses": [
"MIT"
],
"directory_id": "cd4fac45db93d1ab0d2892cb0b81cdb2455c2053",
"extension": "h",
"filename": "bfst_body.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 60921565,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2236,
"license": "MIT",
"license_type": "permissive",
"path": "/bfst_body.h",
"provenance": "stackv2-0108.json.gz:88028",
"repo_name": "fboucher9/bfst",
"revision_date": "2018-09-10T17:44:43",
"revision_id": "b29a79e29660b284f271ebc29b0cc273854e5f45",
"snapshot_id": "810577135bd8539fdb8e8cf6833421b2f826e8f8",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/fboucher9/bfst/b29a79e29660b284f271ebc29b0cc273854e5f45/bfst_body.h",
"visit_date": "2021-01-20T20:15:12.746184"
} | stackv2 | /* See LICENSE for license details. */
/*
Module: bfst_body.h
Description:
Management of global modules and dispatching of events to views and ttys.
*/
#include "bfst_ctxt.h"
#include "bfst_opts.h"
#include "bfst_display.h"
#include "bfst_font.h"
#include "bfst_font_list.h"
#include "bfst_color.h"
#include "bfst_ptr.h"
#include "bfst_ptr_show.h"
#include "bfst_draw.h"
#include "bfst_window.h"
#include "bfst_unique.h"
#include "bfst_tty_list.h"
#include "bfst_tab.h"
#include "bfst_view.h"
#include "bfst_view_list.h"
#include "bfst_focus.h"
#include "bfst_log.h"
#include "bfst_sel.h"
#include "bfst_child.h"
#include "bfst_utf8.h"
#include "bfst_tty.h"
#include "bfst_zombie.h"
#include "bfst_tools.h"
#include "bfst_key.h"
/*
Structure: bfst_body
Description:
Container of modules for 'body' scope. This is a structure of structures.
Comments:
- You may add members here that are at global scope or common to all views.
*/
struct bfst_body
{
/* Context */
struct bfst_body_ctxt o_body_ctxt;
/* Options */
struct bfst_options o_opts;
/* Per display or per screen information ... */
struct bfst_display o_display;
/* Per window information... */
struct bfst_view_list o_view_list;
/* Pointer shapes */
struct bfst_ptr o_ptr;
/* Unique identifier for lines */
struct bfst_unique o_unique;
/* Pointer to view with user input focus */
struct bfst_focus o_focus;
/* List of font names */
struct bfst_font_list o_font_list;
}; /* struct bfst_body */
/* Interface: */
/* Initialize module */
char
bfst_body_init(
struct bfst_body * const p_body,
struct bfst_options const * const p_options);
/* Cleanup module */
void
bfst_body_cleanup(
struct bfst_body * const p_body);
/* Main event handling loop */
void
bfst_body_run(
struct bfst_body * const p_body);
/* Select a custom font */
void
bfst_body_set_font(
struct bfst_view_ctxt const * const p_view_ctxt,
char const * const p_font_name);
/* Coordinate conversion */
int x2col(
struct bfst_tty * p_term,
int x);
/* Coordinate conversion */
int y2row(
struct bfst_tty * p_term,
int y);
/* end-of-file: bfst_body.h */
| 2 | 2 |
2024-11-18T22:49:05.188594+00:00 | 2019-08-28T23:51:07 | 159a6ab556c5cb5a1a5eb40094aa4adb2b78107e | {
"blob_id": "159a6ab556c5cb5a1a5eb40094aa4adb2b78107e",
"branch_name": "refs/heads/master",
"committer_date": "2019-08-28T23:51:07",
"content_id": "44fdee9b530c357359c1181a3f31630fd32dce64",
"detected_licenses": [
"MIT"
],
"directory_id": "cf8a6c37f71ce5edc59ad6c312802a7c13e0a73f",
"extension": "h",
"filename": "hi_types.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": 3444,
"license": "MIT",
"license_type": "permissive",
"path": "/drv/interdrv/cipher/buildin/patch/drivers/crypto/hisi-cipher/include/hi_types.h",
"provenance": "stackv2-0108.json.gz:88678",
"repo_name": "uouo00/TeamX4",
"revision_date": "2019-08-28T23:51:07",
"revision_id": "6c1fb79540e25d1a1d240d42e2e7cd39859382ee",
"snapshot_id": "66c6b4c297845eb17d40bf7ef5b16b183a39f858",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/uouo00/TeamX4/6c1fb79540e25d1a1d240d42e2e7cd39859382ee/drv/interdrv/cipher/buildin/patch/drivers/crypto/hisi-cipher/include/hi_types.h",
"visit_date": "2022-02-20T14:34:57.448530"
} | stackv2 | /******************************************************************************
Copyright (C), 2001-2011, Hisilicon Tech. Co., Ltd.
******************************************************************************
File Name : hi_types.h
Version : Initial Draft
Author : Hisilicon multimedia software group
Created : 2005/4/23
Last Modified :
Description : Common data types of the system.
Function List :
History :
******************************************************************************/
#ifndef __HI_TYPES_H__
#define __HI_TYPES_H__
#include <linux/types.h>
#ifdef __cplusplus
#if __cplusplus
extern "C" {
#endif
#endif /* __cplusplus */
/*--------------------------------------------------------------------------------------------------------------*
* Defintion of basic data types. The data types are applicable to both the application layer and kernel codes. *
*--------------------------------------------------------------------------------------------------------------*/
/*************************** Structure Definition ****************************/
/** \addtogroup Common_TYPE */
/** @{ */ /** <!-- [Common_TYPE] */
#define HI_VOID void
typedef unsigned char hi_uchar;
typedef unsigned char hi_u8;
typedef unsigned short hi_u16;
typedef unsigned int hi_u32;
typedef unsigned long hi_ulong;
typedef char hi_char;
typedef signed char hi_s8;
typedef short hi_s16;
typedef int hi_s32;
typedef long hi_slong;
typedef float hi_float;
typedef double hi_double;
typedef void hi_void;
typedef unsigned long hi_size_t;
typedef unsigned long hi_length_t;
typedef hi_u32 hi_handle;
typedef HI_BOOL hi_bool;
typedef HI_UINTPTR_T hi_uintptr_t;
#ifndef _M_IX86
typedef unsigned long long hi_u64;
typedef long long hi_s64;
#else
typedef __int64 hi_u64;
typedef __int64 hi_s64;
#endif
/** Constant Definition */
typedef enum {
HI_FALSE = 0,
HI_TRUE = 1,
} HI_BOOL;
#ifndef NULL
#define NULL 0L
#endif
#define HI_NULL 0L
#define HI_NULL_PTR 0L
#define HI_SUCCESS 0
#define HI_FAILURE (-1)
#define HI_INVALID_HANDLE (0xffffffff)
/**
define of HI_HANDLE :
bit31 bit0
|<---- 16bit --------->|<--- 8bit --->|<--- 8bit --->|
|--------------------------------------------------------------|
| HI_MOD_ID_E | mod defined data | chnID |
|--------------------------------------------------------------|
mod defined data: private data define by each module(for example: sub-mod id), usually, set to 0.
*/
#define HI_HANDLE_MAKEHANDLE(mod, privatedata, chnid) (hi_handle)( (((mod)& 0xffff) << 16) | ((((privatedata)& 0xff) << 8) ) | (((chnid) & 0xff)) )
#define HI_HANDLE_GET_MODID(handle) (((handle) >> 16) & 0xffff)
#define HI_HANDLE_GET_PriDATA(handle) (((handle) >> 8) & 0xff)
#define HI_HANDLE_GET_CHNID(handle) (((handle)) & 0xff)
/** @} */ /** <!-- ==== Structure Definition end ==== */
#ifdef __cplusplus
#if __cplusplus
}
#endif
#endif /* __cplusplus */
#endif /* __HI_TYPE_H__ */
| 2 | 2 |
2024-11-18T22:49:05.588834+00:00 | 2019-12-07T19:04:27 | 1baef2b4b545b1f398591ef770be227a78d3ef83 | {
"blob_id": "1baef2b4b545b1f398591ef770be227a78d3ef83",
"branch_name": "refs/heads/master",
"committer_date": "2019-12-07T19:04:27",
"content_id": "5243a84658632c9faef8cdb0005fa9460cbdfd88",
"detected_licenses": [
"MIT"
],
"directory_id": "27ca196c9f0769b36a7e70c2d93ab9d138f6ddb0",
"extension": "c",
"filename": "math_autotest.c",
"fork_events_count": 0,
"gha_created_at": "2020-02-02T16:11:12",
"gha_event_created_at": "2020-02-02T16:11:12",
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 237797765,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2810,
"license": "MIT",
"license_type": "permissive",
"path": "/src/math/tests/math_autotest.c",
"provenance": "stackv2-0108.json.gz:88936",
"repo_name": "vbursucianu/liquid-dsp",
"revision_date": "2019-12-07T19:04:27",
"revision_id": "f11733208e3d0da928a0dc2111cdb2b0c4817cef",
"snapshot_id": "db5d24223b36920a3aca18a524e8d167c702cd7a",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/vbursucianu/liquid-dsp/f11733208e3d0da928a0dc2111cdb2b0c4817cef/src/math/tests/math_autotest.c",
"visit_date": "2020-12-27T06:36:28.894365"
} | stackv2 | /*
* Copyright (c) 2007 - 2015 Joseph Gaeddert
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include "autotest/autotest.h"
#include "liquid.h"
//
// AUTOTEST: Q function
//
void autotest_Q()
{
float tol = 1e-6f;
CONTEND_DELTA(liquid_Qf(-4.0f), 0.999968329f, tol);
CONTEND_DELTA(liquid_Qf(-3.0f), 0.998650102f, tol);
CONTEND_DELTA(liquid_Qf(-2.0f), 0.977249868f, tol);
CONTEND_DELTA(liquid_Qf(-1.0f), 0.841344746f, tol);
CONTEND_DELTA(liquid_Qf( 0.0f), 0.5f, tol);
CONTEND_DELTA(liquid_Qf( 1.0f), 0.158655254f, tol);
CONTEND_DELTA(liquid_Qf( 2.0f), 0.022750132f, tol);
CONTEND_DELTA(liquid_Qf( 3.0f), 0.001349898f, tol);
CONTEND_DELTA(liquid_Qf( 4.0f), 0.000031671f, tol);
}
//
// AUTOTEST: sincf
//
void autotest_sincf()
{
float tol = 1e-3f;
CONTEND_DELTA(sincf(0.0f), 1.0f, tol);
}
//
// AUTOTEST: nextpow2
//
void autotest_nextpow2()
{
CONTEND_EQUALITY(liquid_nextpow2(1), 0);
CONTEND_EQUALITY(liquid_nextpow2(2), 1);
CONTEND_EQUALITY(liquid_nextpow2(3), 2);
CONTEND_EQUALITY(liquid_nextpow2(4), 2);
CONTEND_EQUALITY(liquid_nextpow2(5), 3);
CONTEND_EQUALITY(liquid_nextpow2(6), 3);
CONTEND_EQUALITY(liquid_nextpow2(7), 3);
CONTEND_EQUALITY(liquid_nextpow2(8), 3);
CONTEND_EQUALITY(liquid_nextpow2(9), 4);
CONTEND_EQUALITY(liquid_nextpow2(10), 4);
CONTEND_EQUALITY(liquid_nextpow2(11), 4);
CONTEND_EQUALITY(liquid_nextpow2(12), 4);
CONTEND_EQUALITY(liquid_nextpow2(13), 4);
CONTEND_EQUALITY(liquid_nextpow2(14), 4);
CONTEND_EQUALITY(liquid_nextpow2(15), 4);
CONTEND_EQUALITY(liquid_nextpow2(67), 7);
CONTEND_EQUALITY(liquid_nextpow2(179), 8);
CONTEND_EQUALITY(liquid_nextpow2(888), 10);
}
| 2.125 | 2 |
2024-11-18T22:49:05.672034+00:00 | 2018-01-23T23:54:32 | da05592036f1453fa8e4275102d96c4a539d0bef | {
"blob_id": "da05592036f1453fa8e4275102d96c4a539d0bef",
"branch_name": "refs/heads/master",
"committer_date": "2018-01-23T23:54:32",
"content_id": "5d00c1e3868a38a74bc660b3007c348799c79d2c",
"detected_licenses": [
"MIT"
],
"directory_id": "77a220d181cddcdde98b1be4327d87147bed2acb",
"extension": "c",
"filename": "psu_dsm_test.c",
"fork_events_count": 0,
"gha_created_at": "2018-04-03T16:05:53",
"gha_event_created_at": "2018-04-03T16:05:53",
"gha_language": null,
"gha_license_id": null,
"github_id": 127934065,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 793,
"license": "MIT",
"license_type": "permissive",
"path": "/psu_dsm_test.c",
"provenance": "stackv2-0108.json.gz:89067",
"repo_name": "DNALuo/DistributedSystem",
"revision_date": "2018-01-23T23:54:32",
"revision_id": "e3164540f3bc7988d473877886efb860d5a2ee4e",
"snapshot_id": "f7859ff7ebae268fd6050cc26be1f96a97585b8c",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/DNALuo/DistributedSystem/e3164540f3bc7988d473877886efb860d5a2ee4e/psu_dsm_test.c",
"visit_date": "2020-03-08T04:54:41.083737"
} | stackv2 | #include "psu_dsm.h"
#include <stdlib.h>
#include <time.h>
int
main (int argc, char *argv[])
{
srand(time(NULL));
psu_dsm_init();
// char host[16];
// strncpy(host, get_local_ip_addr(), 16);
// char host1[16];
// strncpy(host1, "130.203.16.29", 16);
psu_dsm_ptr_t ptr;
/* if(strncmp(host, host1, 16) == 0){
printf("machine 1\n");
ptr = psu_dsm_malloc("hello1", 100);
}
else{
printf("machine 2\n");
ptr = psu_dsm_malloc("world", 100);
}
*/
ptr = psu_dsm_malloc("hello", 100);
// char c = *((char *)ptr + 1);
//strncpy(ptr, "PLEASE", 10);
// *((char *)ptr) = 'H';
// *((char *)ptr + 1) = '\0';
// printf("content = %s", ptr); :wq
//
*((int *)ptr) = rand();
printf("ptr = %d\n", *((int *)ptr));
sleep(5);
printf("ptr = %d\n", *((int *)ptr));
return 0;
}
| 2.53125 | 3 |
2024-11-18T22:49:05.900252+00:00 | 2016-01-12T01:01:29 | 78e1798737e6fb17d19e9ea761b1d4f189b4e882 | {
"blob_id": "78e1798737e6fb17d19e9ea761b1d4f189b4e882",
"branch_name": "refs/heads/master",
"committer_date": "2016-01-12T01:01:29",
"content_id": "b53bc66d566ec16c480dbf28f9307e60bfdb92e8",
"detected_licenses": [
"MIT"
],
"directory_id": "25ef7e034d84344a18515d42e6498a1ba92ad352",
"extension": "h",
"filename": "syslog_debug.h",
"fork_events_count": 0,
"gha_created_at": "2015-12-18T13:24:53",
"gha_event_created_at": "2015-12-18T13:24:53",
"gha_language": null,
"gha_license_id": null,
"github_id": 48236655,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 838,
"license": "MIT",
"license_type": "permissive",
"path": "/collector/dsc/syslog_debug.h",
"provenance": "stackv2-0108.json.gz:89323",
"repo_name": "McStork/dsc",
"revision_date": "2016-01-12T01:01:29",
"revision_id": "0f6d3bd3d9b12322818e6108e00c95ed85f7e353",
"snapshot_id": "406071c5dd4545240846d93f4ee67711c6d85ff4",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/McStork/dsc/0f6d3bd3d9b12322818e6108e00c95ed85f7e353/collector/dsc/syslog_debug.h",
"visit_date": "2021-01-14T14:06:25.028105"
} | stackv2 | extern int debug_flag;
/* This syslog() macro normally calls the real syslog() function, unless
* debug_flag is on, in which case it does fprintf to stderr. It relies on
* the variable argument count feature of C99 macros. Unfortunately, C99 does
* not allow you to use 0 variable args, so where you would normally write
* syslog(p, "string"), you should instead write syslog(p, "%s", string).
*/
#define syslog(priority, format, ...) \
do { \
if (debug_flag) \
fprintf(stderr, format "\n", __VA_ARGS__); \
else \
(syslog)(priority, format, __VA_ARGS__); \
} while (0)
/* This dfprintf() macro won't call syslog(), only fprintf to stderr if
* debug_flag is on.
*/
#define dfprintf(lvl, format, ...) \
do { \
if (debug_flag > lvl) \
fprintf(stderr, format "\n", __VA_ARGS__); \
} while (0)
| 2.984375 | 3 |
2024-11-18T22:49:06.369728+00:00 | 2016-02-19T14:46:17 | 921a67411065a8129d466a30649dab96cbbc60d4 | {
"blob_id": "921a67411065a8129d466a30649dab96cbbc60d4",
"branch_name": "refs/heads/master",
"committer_date": "2016-02-19T14:46:17",
"content_id": "f34a0c34ed9660f276e4c2c3a3b5366a91a0886d",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "05003480912b9e829bde4d5f2bd0e3692ba26bba",
"extension": "c",
"filename": "aroma_zip.c",
"fork_events_count": 2,
"gha_created_at": "2016-01-16T12:56:08",
"gha_event_created_at": "2016-01-16T12:56:08",
"gha_language": null,
"gha_license_id": null,
"github_id": 49773311,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2098,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/libs/aroma_zip.c",
"provenance": "stackv2-0108.json.gz:89710",
"repo_name": "nkk71/AROMA-Installer",
"revision_date": "2016-02-19T14:46:17",
"revision_id": "4ee90868df963edc92f620e5a7f39770d6be0d34",
"snapshot_id": "1088d519c59c414a814baf49955e6dff8d3e489f",
"src_encoding": "UTF-8",
"star_events_count": 5,
"url": "https://raw.githubusercontent.com/nkk71/AROMA-Installer/4ee90868df963edc92f620e5a7f39770d6be0d34/src/libs/aroma_zip.c",
"visit_date": "2021-01-24T22:20:33.831807"
} | stackv2 | /*
* Copyright (C) 2011 Ahmad Amarullah ( http://amarullz.com/ )
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Descriptions:
* -------------
* minzip wrapper for AROMA Installer
*
*/
#include "../../libs/minzip/Zip.h"
#include "../aroma.h"
/*****************************[ GLOBAL VARIABLES ]*****************************/
static ZipArchive zip;
/*********************************[ FUNCTIONS ]********************************/
//-- AROMA ZIP Init
byte az_init(const char * filename) {
if (mzOpenZipArchive(filename, &zip) != 0) {
return 0;
}
mkdir(AROMA_TMP, 755);
return 1;
}
//-- AROMA ZIP Close
void az_close() {
mzCloseZipArchive(&zip);
}
//-- Extract To Memory
byte az_readmem(AZMEM * out, const char * zpath, byte bytesafe) {
char z_path[256];
snprintf(z_path, sizeof(z_path) - 1, "%s", zpath);
const ZipEntry * se = mzFindZipEntry(&zip, z_path);
if (se == NULL) {
return 0;
}
out->sz = se->uncompLen + (bytesafe ? 0 : 1);
out->data = malloc(out->sz);
//memset(out->data,0,out->sz);
if (!mzReadZipEntry(&zip, se, out->data, se->uncompLen)) {
free(out->data);
return 0;
}
if (!bytesafe) {
out->data[se->uncompLen] = '\0';
}
return 1;
}
//-- Extract To File
byte az_extract(const char * zpath, const char * dest) {
const ZipEntry * zdata = mzFindZipEntry(&zip, zpath);
if (zdata == NULL) {
return 0;
}
unlink(dest);
int fd = creat(dest, 0755);
if (fd < 0) {
return 0;
}
byte ok = mzExtractZipEntryToFile(&zip, zdata, fd);
close(fd);
return ok;
} | 2.15625 | 2 |
2024-11-18T22:49:13.462883+00:00 | 2019-03-04T17:08:45 | e3e258995758758d50747641803699becb990f20 | {
"blob_id": "e3e258995758758d50747641803699becb990f20",
"branch_name": "refs/heads/master",
"committer_date": "2019-03-04T17:08:45",
"content_id": "4b4a8e1fd72b2f34bc163968629b1f6532f05344",
"detected_licenses": [
"MIT"
],
"directory_id": "2f21b49a83ddc42eaef7967c97689a8edfccfd75",
"extension": "c",
"filename": "test_decode_dict.c",
"fork_events_count": 0,
"gha_created_at": "2019-03-04T17:09:53",
"gha_event_created_at": "2019-03-04T17:09:53",
"gha_language": null,
"gha_license_id": null,
"github_id": 173787539,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1596,
"license": "MIT",
"license_type": "permissive",
"path": "/test/test_decode_dict.c",
"provenance": "stackv2-0108.json.gz:90354",
"repo_name": "egobrain/libBERT",
"revision_date": "2019-03-04T17:08:45",
"revision_id": "90e05c5d52868f870f113a4c21462465dc826262",
"snapshot_id": "df2697b3f5d9e37a9ecd505eae391882504a118c",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/egobrain/libBERT/90e05c5d52868f870f113a4c21462465dc826262/test/test_decode_dict.c",
"visit_date": "2020-04-26T19:48:43.522105"
} | stackv2 | #include <bert/decoder.h>
#include <bert/errno.h>
#include "test.h"
#include <sys/types.h>
#include <fcntl.h>
#include <string.h>
#include <errno.h>
bert_decoder_t *decoder;
void test_read()
{
bert_data_t *data;
int result;
if ((result = bert_decoder_pull(decoder,&data)) != 1)
{
test_fail(bert_strerror(result));
}
if (data->type != bert_data_dict)
{
test_fail("bert_decoder_next did not decode a dict");
}
bert_dict_node_t *next_node = data->dict->head;
if (!next_node)
{
test_fail("bert_decoder_next failed to decode the first dict key->value pair");
}
if (next_node->next)
{
test_fail("bert_decoder_next decoded more than one dict key->value pair");
}
bert_data_t *key = next_node->key;
if (key->type != bert_data_int)
{
test_fail("bert_decoder_next did not decode an integer as the first dict key");
}
unsigned int expected_key = 1;
if (key->integer != expected_key)
{
test_fail("bert_decoder_next decoded %u as the first dict key, expected %u",key->integer,expected_key);
}
bert_data_t *value = next_node->value;
if (value->type != bert_data_int)
{
test_fail("bert_decoder_next did not decode an integer as the first dict value");
}
unsigned int expected_value = 2;
if (value->integer != expected_value)
{
test_fail("bert_decoder_next decoded %u as the first dict value, expected %u",value->integer,expected_value);
}
}
int main()
{
int fd;
decoder = bert_decoder_create();
fd = test_open_file("files/dict.bert");
bert_decoder_stream(decoder,fd);
test_read();
bert_decoder_destroy(decoder);
close(fd);
return 0;
}
| 2.40625 | 2 |
2024-11-18T22:49:13.688884+00:00 | 2021-05-22T23:01:23 | 2349217c32e1c470bb62b7c011e30a3fca950aae | {
"blob_id": "2349217c32e1c470bb62b7c011e30a3fca950aae",
"branch_name": "refs/heads/main",
"committer_date": "2021-05-22T23:01:23",
"content_id": "c9b0a2f59bc0250d688f3c2fda1c4824a4ccf616",
"detected_licenses": [
"MIT"
],
"directory_id": "4bc6057868d8f11328e3d65bf50540b91cd73a10",
"extension": "c",
"filename": "example.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 369920612,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 479,
"license": "MIT",
"license_type": "permissive",
"path": "/example.c",
"provenance": "stackv2-0108.json.gz:90614",
"repo_name": "mazoti/cgc",
"revision_date": "2021-05-22T23:01:23",
"revision_id": "a1341ea38b7f9a228f6214902c0dba8b1dbd2fc9",
"snapshot_id": "c81b87b296908daae87dc616afac66848890e36c",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/mazoti/cgc/a1341ea38b7f9a228f6214902c0dba8b1dbd2fc9/example.c",
"visit_date": "2023-05-03T22:32:37.691220"
} | stackv2 | /* That's all you need, include before everything in your program */
#include "garbage_collector.h"
/* -------------------------------------------------------------- */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void){
char* str;
str = (char*)calloc(1,14);
strcpy(str, "Hello World!\n");
/* You can call gc_clean if malloc/calloc returns NULL */
printf("%.*s", 14, str);
return 0;
/* The garbage will be collected when the program exits */
}
| 2.984375 | 3 |
2024-11-18T22:49:13.775892+00:00 | 2015-09-24T16:08:53 | fecb9ebc01df80e045efcb92864f8424841de59d | {
"blob_id": "fecb9ebc01df80e045efcb92864f8424841de59d",
"branch_name": "refs/heads/master",
"committer_date": "2015-09-24T16:08:53",
"content_id": "7147e49efca188ddf0758239ad56d576a4bfb39e",
"detected_licenses": [
"MIT"
],
"directory_id": "b48b0ec21c37b7feb9415af8b6319edb6806a81b",
"extension": "c",
"filename": "gpio_mod.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": 4091,
"license": "MIT",
"license_type": "permissive",
"path": "/examples/esp_iot/modules/gpio_mod.c",
"provenance": "stackv2-0108.json.gz:90742",
"repo_name": "LinhDNguyen/esp8266-dev",
"revision_date": "2015-09-24T16:08:53",
"revision_id": "af71c30af8456e8e88eb51ef365174b799bf2053",
"snapshot_id": "50a6576273346b525982c8f01927865eaee7c004",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/LinhDNguyen/esp8266-dev/af71c30af8456e8e88eb51ef365174b799bf2053/examples/esp_iot/modules/gpio_mod.c",
"visit_date": "2022-12-09T23:55:29.107762"
} | stackv2 | /* config.h
*
* Copyright (c) 2015, LinhNV <nvl1109 at gmail dot com>
* All rights reserved.
*
*/
#include "ets_sys.h"
#include "os_type.h"
#include "mem.h"
#include "osapi.h"
#include "user_interface.h"
#include "gpio_mod.h"
#include "config.h"
#include "debug.h"
static uint32_t gpio_no_pins[NUMBER_OF_GPIO_PIN] = {
PERIPHS_IO_MUX_GPIO0_U, // GPIO0
PERIPHS_IO_MUX_U0TXD_U, // GPIO1
PERIPHS_IO_MUX_GPIO2_U, // GPIO2
PERIPHS_IO_MUX_U0RXD_U, // GPIO3
PERIPHS_IO_MUX_GPIO4_U, // GPIO4
PERIPHS_IO_MUX_GPIO5_U, // GPIO5
0,
0,
0,
PERIPHS_IO_MUX_SD_DATA2_U, // GPIO9
PERIPHS_IO_MUX_SD_DATA3_U, // GPIO10
0,
PERIPHS_IO_MUX_MTDI_U, // GPIO12
PERIPHS_IO_MUX_MTCK_U, // GPIO13
PERIPHS_IO_MUX_MTMS_U, // GPIO14
PERIPHS_IO_MUX_MTDO_U // GPIO15
};
static uint32_t gpio_func_arr[NUMBER_OF_GPIO_PIN] = {
FUNC_GPIO0,
FUNC_GPIO1,
FUNC_GPIO2,
FUNC_GPIO3,
FUNC_GPIO4,
FUNC_GPIO5,
0,
0,
0,
FUNC_GPIO9,
FUNC_GPIO10,
0,
FUNC_GPIO12,
FUNC_GPIO13,
FUNC_GPIO14,
FUNC_GPIO15
};
static gpio_interrupt_callback gpio_interrupt_cb[NUMBER_OF_GPIO_PIN];
static void * gpio_interrupt_arg[NUMBER_OF_GPIO_PIN];
os_event_t gpio_interrupt_procTaskQueue[GPIO_CALLBACK_TASK_QUEUE_SIZE];
static bool isTaskCreated = false;
static void ICACHE_FLASH_ATTR gpio_intr_handler(int * dummy);
void ICACHE_FLASH_ATTR gpio_interrupt_cb_task(os_event_t *e);
void ICACHE_FLASH_ATTR
gpio_interrupt_cb_task(os_event_t *e) {
uint8_t i;
uint32_t cbmask = (uint32_t)e->par;
DBG_MSG("cbmask: 0x%X\r\n", cbmask);
for (i=0; i<NUMBER_OF_GPIO_PIN; ++i) {
if ((cbmask & BIT(i)) != 0) {
if (gpio_interrupt_cb[i] != NULL) {
gpio_interrupt_cb[i]((void *)gpio_interrupt_arg[i]);
}
}
}
}
void ICACHE_FLASH_ATTR gpio_function(uint8_t pin_no) {
DBG_MSG("pin_no: %d\r\n", pin_no);
if (pin_no >= NUMBER_OF_GPIO_PIN) return;
PIN_FUNC_SELECT(gpio_no_pins[pin_no], gpio_func_arr[pin_no]);
}
static void ICACHE_FLASH_ATTR gpio_intr_handler(int * dummy) {
uint32 gpio_status = GPIO_REG_READ(GPIO_STATUS_ADDRESS);
uint8_t i;
uint32_t cbmask = 0;
bool res;
//clear interrupt status for GPIO
GPIO_REG_WRITE(GPIO_STATUS_W1TC_ADDRESS, gpio_status);
for (i=0; i<NUMBER_OF_GPIO_PIN; ++i) {
if (gpio_status & BIT(i)) {
DBG_MSG("Interrupt %d\r\n", i);
cbmask |= BIT(i);
}
}
DBG_MSG("cbmask: 0x%X\r\n", cbmask);
res = system_os_post(GPIO_CALLBACK_TASK_PRIO, 0, (os_param_t)cbmask);
DBG_MSG("system_os_post result %d\r\n", res);
}
void ICACHE_FLASH_ATTR gpio_interrupt_start(void) {
if (isTaskCreated == false) {
system_os_task(gpio_interrupt_cb_task, GPIO_CALLBACK_TASK_PRIO, gpio_interrupt_procTaskQueue, GPIO_CALLBACK_TASK_QUEUE_SIZE);
isTaskCreated = true;
DBG_MSG("Create gpio interrupt callback task\r\n");
}
ETS_GPIO_INTR_DISABLE();
ETS_GPIO_INTR_ATTACH(gpio_intr_handler, NULL);
// enable interrupt for his GPIO
// GPIO_PIN_INTR_... defined in gpio.h
ETS_GPIO_INTR_ENABLE();
}
void ICACHE_FLASH_ATTR gpio_interrupt_stop(void) {
ETS_GPIO_INTR_ATTACH(NULL, NULL);
ETS_GPIO_INTR_DISABLE();
}
void ICACHE_FLASH_ATTR gpio_interrupt_install(uint8_t pin_no, GPIO_INT_TYPE type, gpio_interrupt_callback cb, void *arg) {
gpio_function(pin_no);
// All people repeat this mantra but I don't know what it means
gpio_register_set(GPIO_PIN_ADDR(pin_no),
GPIO_PIN_INT_TYPE_SET(GPIO_PIN_INTR_DISABLE) |
GPIO_PIN_PAD_DRIVER_SET(GPIO_PAD_DRIVER_DISABLE) |
GPIO_PIN_SOURCE_SET(GPIO_AS_PIN_SOURCE));
// clear gpio status. Say ESP8266EX SDK Programming Guide in 5.1.6. GPIO interrupt handler
GPIO_REG_WRITE(GPIO_STATUS_W1TC_ADDRESS, BIT(pin_no));
gpio_pin_intr_state_set(GPIO_ID_PIN(pin_no), type);
gpio_interrupt_cb[pin_no] = cb;
gpio_interrupt_arg[pin_no] = arg;
}
| 2.296875 | 2 |
2024-11-18T22:49:14.019575+00:00 | 2022-08-23T07:49:02 | 16cf5f5d7fd2584dab7ffa90ace8b57eac3aa122 | {
"blob_id": "16cf5f5d7fd2584dab7ffa90ace8b57eac3aa122",
"branch_name": "refs/heads/master",
"committer_date": "2022-08-23T07:49:02",
"content_id": "c6a0bd199f2e895694de4054275e29cdaf71cfef",
"detected_licenses": [
"MIT"
],
"directory_id": "55c5c8bd6bc8ac09f255921e053f058d33ca6201",
"extension": "c",
"filename": "main.c",
"fork_events_count": 14,
"gha_created_at": "2015-09-07T12:20:42",
"gha_event_created_at": "2017-04-09T01:12:02",
"gha_language": "Python",
"gha_license_id": null,
"github_id": 42051407,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5916,
"license": "MIT",
"license_type": "permissive",
"path": "/Clang/w3bfukk0r/main.c",
"provenance": "stackv2-0108.json.gz:91002",
"repo_name": "unixfreaxjp/malwaremustdie",
"revision_date": "2022-08-23T07:49:02",
"revision_id": "6f69c8e4a55335b6b60a23785e98087b605ddceb",
"snapshot_id": "6d4997a74ca378c5c0d1f2bfaeb8839c176097d0",
"src_encoding": "UTF-8",
"star_events_count": 136,
"url": "https://raw.githubusercontent.com/unixfreaxjp/malwaremustdie/6f69c8e4a55335b6b60a23785e98087b605ddceb/Clang/w3bfukk0r/main.c",
"visit_date": "2022-09-01T15:07:35.675468"
} | stackv2 | /*
* (C)opyright 2006 Nico Golde <nico@ngolde.de>
* (C)opyright 2006 Andreas Krennmair <ak@synflood.at>
* See LICENSE file for license details
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
#include <string.h>
#include "list.h"
#include "conn.h"
#include "url.h"
#include "http.h"
static void usage(char * argv0) {
fprintf(stderr, "%s " VERSION "\nusage: %s -f <wordsfile> [-p <host>:<port>] [-o <file>] <URL> [<URL> ...]\n",argv0,argv0);
fprintf(stderr, "options:\n"
"-h display this help\n"
"-f specify wordlist file\n"
"-v more verbose output\n"
"-u fake user agent header\n"
"-p specify proxy host and port\n"
"-o write output to file\n");
exit(EXIT_FAILURE);
}
int main(int argc, char * argv[]) {
char * wordfile = "words.txt";
char * url = NULL;
char * optstr = "f:hvuo:p:";
char * outfile = NULL;
uint16_t proxyport = 8080;
char * proxyhost = NULL;
char service[1024] = "";
wordlist_t * wl;
int c;
int status = 404;
int verbose = 0, fake_ua = 0;
time_t t1, t2;
FILE * logf = NULL;
t1 = time(NULL);
do {
c = getopt(argc,argv,optstr);
if (c < 0) continue; switch (c) {
case ':': /* fall-through */
case '?': /* missing option */
exit(EXIT_FAILURE);
case 'f':
wordfile = optarg;
break;
case 'h':
usage(argv[0]);
break;
case 'v':
verbose = 1;
break;
case 'u':
fake_ua = 1;
break;
case 'o':
outfile = optarg;
break;
case 'p':
proxyhost = optarg;
proxyport = getport(proxyhost);
break;
default:
fprintf(stderr,"%s: unknown option: -%c\n",argv[0],c);
exit(EXIT_FAILURE);
};
} while (c != -1);
if (optind >= argc) {
fprintf(stderr,"%s: missing URL\n",argv[0]);
usage(argv[0]);
}
if (!wordfile) {
fprintf(stderr,"%s: wordfile not specified\n",argv[0]);
usage(argv[0]);
}
if (outfile) {
logf = fopen(outfile,"w");
}
printf("Starting w3bfukk0r " VERSION "\n");
if (logf) {
fprintf(logf,"Starting w3bfukk0r " VERSION "\n");
}
wl = new_wordlist();
fill_wordlist_from_file(wl,wordfile);
/* code to demonstrate usage of connections: */
for (url=argv[optind];optind<argc;url=argv[++optind]) {
conn_t * conn = NULL;
url_t * u = parse_url(url);
word_t * e;
int local_count = 0;
char buf[1024];
char nice_url[1024];
char proxy_resource[1024];
ssize_t s;
int reconnect = 1, force_disconnect = 0;
unsigned long found_counter = 0;
if (!u) {
fprintf(stderr,"couldn't parse URL `%s'\n",url);
if (logf) {
fprintf(logf,"couldn't parse URL `%s'\n",url);
}
exit(EXIT_FAILURE);
}
url_to_str(nice_url,sizeof(nice_url),u);
if(proxyhost){
proxyresource(proxy_resource, sizeof(proxy_resource), nice_url, u->resource);
u->resource=strdup(proxy_resource);
}
printf("Scanning %s with %lu words from %s\n\n",nice_url,wl->count,wordfile);
if (logf) {
fprintf(logf,"Scanning %s with %lu words from %s\n\n",nice_url,wl->count,wordfile);
}
for (e=wl->top;e;e=e->next) {
char * word = e->word;
if (reconnect) {
if(u->protocol == PROTO_HTTP){
if(proxyhost)
conn = connect_plain(proxyhost, proxyport);
else
conn = connect_plain(u->host, u->port);
} else {
if(proxyhost)
conn = connect_ssl_proxy(proxyhost, proxyport, u->host, u->port);
else
conn = connect_ssl(u->host, u->port);
}
if (!conn) {
fprintf(stderr,"error: connection failed\n");
if (logf) {
fprintf(logf,"error: connection failed\n");
}
exit(EXIT_FAILURE);
}
reconnect = 0;
}
if (local_count < wl->count) {
send_head_request(conn, u, word, KEEPALIVE | (fake_ua ? FAKE_UA : 0));
} else {
send_head_request(conn, u, word, 0 | (fake_ua ? FAKE_UA : 0));
}
local_count++;
s=conn_readline(conn,buf,sizeof(buf)-1);
if (s > 0) {
buf[s] = '\0';
status=parse_http(buf);
if (status == 403) {
printf("Found %s%s/ (not public; HTTP %u)\n", nice_url, word, status);
if (logf) {
fprintf(logf,"Found %s%s/ (not public; HTTP %u)\n", nice_url, word, status);
}
++found_counter;
} else if(status >= 400 && status <= 499) {
if (verbose) {
printf("Does not exist: %s%s/ (HTTP %u)\n", nice_url, word, status);
if (logf) {
fprintf(logf,"Does not exist: %s%s/ (HTTP %u)\n", nice_url, word, status);
}
}
} else if(status >= 200 && status <= 299) {
printf("Found %s%s/ (HTTP %u)\n", nice_url, word, status);
if (logf) {
fprintf(logf,"Found %s%s/ (HTTP %u)\n", nice_url, word, status);
}
++found_counter;
} else {
if (verbose) {
printf("Other response code: %s%s/ (HTTP %u)\n",nice_url, word, status);
if (logf) {
fprintf(logf,"Other response code: %s%s/ (HTTP %u)\n",nice_url, word, status);
}
}
}
do {
s=conn_readline(conn,buf,sizeof(buf)-1);
buf[s] = '\0';
if (strcasecmp(buf,"connection: close\r\n")==0) {
force_disconnect = 1;
}
if(!strncasecmp(buf, "Server: ", 8))
snprintf(service, sizeof(service), "%s", get_service(buf));
} while ((s > 0) && (strcmp(buf,"\r\n")!=0));
}
if (local_count < wl->count && (s == 0 || force_disconnect)) {
force_disconnect = 0;
disconnect(conn);
reconnect = 1;
}
}
disconnect(conn);
free_url(u);
printf("\nFound %lu directories.\n",found_counter);
printf("Server runs: %s\n", strlen(service)>0 ? service : "can not be determined");
if (logf) {
fprintf(logf,"\nFound %lu directories.\n",found_counter);
fprintf(logf,"Server runs: %s\n", strlen(service)>0 ? service : "can not be determined");
}
}
t2 = time(NULL);
printf("Scan finished (%lu seconds).\n",t2-t1);
if (logf) {
fprintf(logf,"Scan finished (%lu seconds).\n",t2-t1);
fclose(logf);
}
delete_list(wl);
return 0;
}
| 2.078125 | 2 |
2024-11-18T22:49:14.114159+00:00 | 2018-12-10T07:13:55 | 8fefb9e9592a01db370d4483c649c71dc893f476 | {
"blob_id": "8fefb9e9592a01db370d4483c649c71dc893f476",
"branch_name": "refs/heads/master",
"committer_date": "2018-12-10T07:13:55",
"content_id": "16960cf07f5f26734ee7cd16c008fb8184ec5b47",
"detected_licenses": [
"MIT"
],
"directory_id": "a2b0d93354db1877ffc8689ec189c0bb9caa1bbd",
"extension": "c",
"filename": "thread.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 159257125,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3825,
"license": "MIT",
"license_type": "permissive",
"path": "/xv6-public/thread.c",
"provenance": "stackv2-0108.json.gz:91133",
"repo_name": "aidenZ1193/238-p3",
"revision_date": "2018-12-10T07:13:55",
"revision_id": "b8573780c33751d4238c691d4977a8ea367d0952",
"snapshot_id": "4c95021612ce6ea8b07726a5053582f77233707c",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/aidenZ1193/238-p3/b8573780c33751d4238c691d4977a8ea367d0952/xv6-public/thread.c",
"visit_date": "2020-04-08T10:09:54.061595"
} | stackv2 | #include "types.h"
#include "stat.h"
#include "spinlock.h"
#include "user.h"
#include "param.h"
#include "x86.h"
//#include "defs.h"
#include "mmu.h"
#include "proc.h"
// spinlock
struct thread_spinlock {
uint locked; // Is the lock held?
char *name; // Name of lock.
// struct cpu *cpu; // The cpu holding the lock.
// uint pcs[10]; // The call stack (an array of program counters)
// that locked the lock.
};
// mutex lock
struct thread_mutex{
uint locked; // Is the lock held?
char *name; // Name of lock.
// struct cpu *cpu; // The cpu holding the lock.
// uint pcs[10]; // The call stack (an array of program counters)
// that locked the lock.
};
//struct cpu* mycpu(void);
void thread_spin_init(struct thread_spinlock *lk, char* name);
void thread_spin_lock(struct thread_spinlock *lk);
void thread_spin_unlock(struct thread_spinlock *lk);
void thread_mutex_init(struct thread_mutex *m, char* name);
void thread_mutex_lock(struct thread_mutex *m);
void thread_mutex_unlock(struct thread_mutex *m);
// implementations from xv6 kernel
void thread_spin_init(struct thread_spinlock *lk, char* name){
lk->name = name;
lk->locked = 0;
// lk->cpu = 0;
}
void thread_spin_lock(struct thread_spinlock *lk){
//if(holding(lk)){
//}
while(xchg(&lk->locked, 1) != 0)
;
__sync_synchronize();
// Record info about lock acquisition for debugging.
//lk->cpu = cpu;
// lk->cpu = mycpu();
}
void thread_spin_unlock(struct thread_spinlock *lk){
// lk->pcs[0] = 0;
// lk->cpu = 0;
// Tell the C compiler and the processor to not move loads or stores
// past this point, to ensure that all the stores in the critical
// section are visible to other cores before the lock is released.
// Both the C compiler and the hardware may re-order loads and
// stores; __sync_synchronize() tells them both to not re-order.
__sync_synchronize();
// Release the lock.
lk->locked = 0;
}
void thread_mutex_init(struct thread_mutex *m, char* name){
m->name = name;
// m->locked = 0;
// m->cpu = 0;
}
void thread_mutex_lock(struct thread_mutex *m){
while(xchg(&m->locked, 1) != 0)
sleep(1);
__sync_synchronize();
//m->cpu = cpu;
// m->cpu = mycpu();
}
void thread_mutex_unlock(struct thread_mutex *m){
//m->pcs[0] = 0;
//m->cpu = 0;
__sync_synchronize();
m->locked = 0;
}
//struct thread_mutex lock;
char* name = "thread_mnutex";
struct thread_spinlock lk;
struct balance {
char name[32];
int amount;
};
volatile int total_balance = 0;
volatile unsigned int delay (unsigned int d) {
unsigned int i;
for (i = 0; i < d; i++) {
__asm volatile( "nop" ::: );
}
return i;
}
void do_work(void *arg){
int i;
int old;
struct balance *b = (struct balance*) arg;
printf(1, "Starting do_work: s:%s\n", b->name);
for (i = 0; i < b->amount; i++) {
//thread_mutex_lock(&lock);
thread_spin_lock(&lk);
old = total_balance;
delay(100000);
total_balance = old + 1;
//thread_mutex_unlock(&lock);
thread_spin_unlock(&lk);
}
printf(1, "Done s:%x\n", b->name);
thread_exit();
return;
}
int main(int argc, char *argv[]) {
struct balance b1 = {"b1", 3200};
struct balance b2 = {"b2", 2800};
//struct thread_mutex *lock;
//char* name = "thread_mnutex";
//thread_spinlock_init(&lock, name);
thread_spin_init(&lk, name);
void *s1, *s2;
int t1, t2, r1, r2;
s1 = malloc(4096);
s2 = malloc(4096);
t1 = thread_create(do_work, (void*)&b1, s1);
t2 = thread_create(do_work, (void*)&b2, s2);
r1 = thread_join();
r2 = thread_join();
printf(1, "Threads finished: (%d):%d, (%d):%d, shared balance:%d\n",
t1, r1, t2, r2, total_balance);
exit();
}
| 2.6875 | 3 |
2024-11-18T22:49:14.358555+00:00 | 2016-03-31T04:27:37 | 447ca4f7d258556896a870941c3b824fd217615f | {
"blob_id": "447ca4f7d258556896a870941c3b824fd217615f",
"branch_name": "refs/heads/master",
"committer_date": "2016-03-31T04:27:37",
"content_id": "3ba314a4008905db63881f676ec6f9b6fa818e27",
"detected_licenses": [
"MIT"
],
"directory_id": "679bf883973eee060c1f19346fd32d0662db7f69",
"extension": "h",
"filename": "utilities.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 49804706,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1626,
"license": "MIT",
"license_type": "permissive",
"path": "/Bounded-Buffer-Problem/inc/utilities.h",
"provenance": "stackv2-0108.json.gz:91390",
"repo_name": "adlawren/Unix-Programming-Experiments",
"revision_date": "2016-03-31T04:27:37",
"revision_id": "1699f1c37b6d1ec9b6b53cb86fbedb823222410b",
"snapshot_id": "fdb0fa9d1e500c62df53331d971a16961b034046",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/adlawren/Unix-Programming-Experiments/1699f1c37b6d1ec9b6b53cb86fbedb823222410b/Bounded-Buffer-Problem/inc/utilities.h",
"visit_date": "2020-12-30T20:05:53.200131"
} | stackv2 | #ifndef __UTILITIES_H__
#define __UTILITIES_H__
// std
#include "stdio.h"
// sys
#include "string.h"
#include "sys/mman.h"
#include "pthread.h"
// local
#include "product.h"
/** @brief Determines whether or not the contents of the two given strings are identical.
*
* @param str_a The first string for comparison.
*
* @param str_b The second string for comparison.
*
* @returns size_t One if the contents of the two strings are identical, zero otherwise.
*/
size_t strings_equal(char *str_a, char *str_b);
/** @brief Determines whether or not the contents of the two given products are identical.
*
* @param str_a The first product for comparison.
*
* @param str_b The second product for comparison.
*
* @returns size_t One if the contents of the two products are identical, zero otherwise.
*/
size_t products_equal(product_t *product_a, product_t *product_b);
/** @brief Prints the given string to stdout after locking a mutex.
*
* @param s String to be printed.
*
* @returns void.
*/
void atomic_print(char *s);
/** @brief Reads the numerical value associated with the given integer pointer after constructing a mutex to prohibit concurrent access to the pointer.
*
* @param i Pointer to an integer value.
*
* @returns int The value associated with the given integer pointer.
*/
int atomic_read(int *i);
/** @brief Decrements the numerical value associated with the given integer pointer after constructing a mutex to prohibit concurrent access to the pointer.
*
* @param i Pointer to an integer value.
*
* @returns void.
*/
void atomic_decrement(int *i);
#endif //__UTILITIES_H__
| 2.71875 | 3 |
2024-11-18T22:49:15.293283+00:00 | 2022-04-04T17:38:51 | f354330a954fd40408957af01f929912a3a53820 | {
"blob_id": "f354330a954fd40408957af01f929912a3a53820",
"branch_name": "refs/heads/master",
"committer_date": "2022-04-04T17:38:51",
"content_id": "bfdd8aaeae473f5a49ca682d526a8241a2f9f92c",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "4f01956df7fde276c607d7d50e56634c43fd0822",
"extension": "c",
"filename": "dsprt_c.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 85823408,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1066,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/Presentations/2016_GlazeEtAl_SfN/mFiles/Utilities/dsprt_c.c",
"provenance": "stackv2-0108.json.gz:91520",
"repo_name": "TheGoldLab/Analysis_Archived",
"revision_date": "2022-04-04T17:38:51",
"revision_id": "83ff0967df3542245939ed22c8250ea5534ef0ba",
"snapshot_id": "22bc9eb298ab07284672c9c5200ac323fa960dc6",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/TheGoldLab/Analysis_Archived/83ff0967df3542245939ed22c8250ea5534ef0ba/Presentations/2016_GlazeEtAl_SfN/mFiles/Utilities/dsprt_c.c",
"visit_date": "2022-04-30T09:23:53.453189"
} | stackv2 | /*=================================================================
*
* DDDM ALGORITHM FOR ESTIMATION OF POSTERIORS, ETC IN HMM
*
*/
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include "mex.h"
#include "matrix.h"
void dsprt_c(
double *LPRpr,
double *LLRpr,
double H,
int N
)
{
int n;
double J,L;
J = (1-H)/H;
L = 0;
for (n = 0; n < N; n++) {
L += log(J+exp(-L)) - log(J+exp(L)) + *(LLRpr+n);
*(LPRpr+n) = L;
}
}
void mexFunction( int nlhs, mxArray*plhs[],
int nrhs, const mxArray*prhs[])
/* VARIABLES ARE N, LPr, H, H0, alpha, J, H */
{
double *LPRpr, *LLRpr, H;
int N;
LLRpr = mxGetPr(prhs[0]);
H = mxGetScalar(prhs[1]);
N = mxGetM(prhs[0]);
plhs[0] = mxCreateDoubleMatrix(N, 1, mxREAL);
LPRpr = mxGetPr(plhs[0]);
/* Do the actual computations in a subroutine */
dsprt_c(LPRpr,LLRpr,H,N);
}
| 2.21875 | 2 |
2024-11-18T22:49:15.846129+00:00 | 2017-05-12T01:02:00 | 275e46d8b19bc7c54e851d09df8b938fb8e18d00 | {
"blob_id": "275e46d8b19bc7c54e851d09df8b938fb8e18d00",
"branch_name": "refs/heads/master",
"committer_date": "2017-05-12T01:02:00",
"content_id": "18805174cc2dd4f0cf61532714b98e3afa0f7f5c",
"detected_licenses": [
"MIT"
],
"directory_id": "1cf18abd7b9011a037adbf4b49dc6bd37d2dc839",
"extension": "c",
"filename": "expad.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": 1383,
"license": "MIT",
"license_type": "permissive",
"path": "/BookCode/chapters/01dobsonBOOKexamples/expad.c",
"provenance": "stackv2-0108.json.gz:92428",
"repo_name": "templeblock/Audio_programming_book_code",
"revision_date": "2017-05-12T01:02:00",
"revision_id": "3d318787d379f232a4edc113b6f7190201084674",
"snapshot_id": "5dc8b3f72e284783443b2d38471740fb2ed6ee71",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/templeblock/Audio_programming_book_code/3d318787d379f232a4edc113b6f7190201084674/BookCode/chapters/01dobsonBOOKexamples/expad.c",
"visit_date": "2021-06-16T14:02:21.747741"
} | stackv2 | /* expad.c generate exponential attack or decay breakpoint data */
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(int argc, char** argv)
{
int i,npoints;
double T,k,a;
double ystart,yend;
double dur,thisval,thisstep;
if(argc != 6){
fprintf(stderr,"insufficient arguments.\n");
fprintf(stderr,"Usage: expad duration npoints startval endval T\n");
return 1;
}
dur = atof(argv[1]);
if(dur <=0.0){
fprintf(stderr,"Error: duration must be positive.\n");
return 1;
}
npoints = atoi(argv[2]);
if(npoints <= 0){
fprintf(stderr,"Error: npoints must be positive!\n");
return 1;
}
ystart = atof(argv[3]);
yend = atof(argv[4]);
if(yend == ystart){
fprintf(stderr,"Warning: start and end values are the same!\n");
}
T = atof(argv[5]);
k = dur/npoints; /* npoints = "sample rate" */
a = exp(-k/T); /* T = time constant */
thisstep = 0.0;
thisval = ystart;
fprintf(stderr,"a = %.6lf\n",a);
/* make normalized curve, scale output to input values and range */
for(i=0;i < npoints;i++){
printf("%.4lf\t%.8lf\n",thisstep,thisval);
thisval = a * thisval + (1.0-a) * yend;
thisstep += k;
}
/* print final value */
printf("%.4lf\t%.8lf\n",thisstep,thisval);
fprintf(stderr,"done\n");
return 0;
}
/* EXERCISE! reduce the computations inside the loop */
| 3.15625 | 3 |
2024-11-18T22:49:15.951535+00:00 | 2018-03-01T19:02:47 | e455d88b389545fab002511c975fe05efb74f22a | {
"blob_id": "e455d88b389545fab002511c975fe05efb74f22a",
"branch_name": "refs/heads/master",
"committer_date": "2018-03-01T19:02:47",
"content_id": "cee746466ddcbcda4c47343840a5c793c6000eb4",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "e1ff4d684f0194e94bb34aa31ec76efad18ff481",
"extension": "c",
"filename": "tx.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": 15820,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/tx.c",
"provenance": "stackv2-0108.json.gz:92557",
"repo_name": "jpaetzel/viamillipede",
"revision_date": "2018-03-01T19:02:47",
"revision_id": "a6d798e0d6f9485d481be513683475e4c457c2aa",
"snapshot_id": "1bb0cda916bb855602bb2cad804b84d62dbd2f33",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/jpaetzel/viamillipede/a6d798e0d6f9485d481be513683475e4c457c2aa/tx.c",
"visit_date": "2021-04-26T23:38:28.335864"
} | stackv2 | #include "worker.h"
extern int gchecksums;
extern char* gcheckphrase;
int dispatch_idle_worker ( struct txconf_s * txconf ) {
int retcode =-1 ;
txstatus( txconf, 5);
int spins = 0;
int sleep_thief =0;
while( retcode < 0 ) {
pthread_mutex_lock( &(txconf->mutex) );
for( int worker_cursor = 0; (worker_cursor < txconf->worker_count) && (retcode < 0 ); worker_cursor++ ) {
if ( txconf->workers[worker_cursor].state == 'i' ) {
retcode = worker_cursor;
sleep_thief=0;
spins = 0 ;
}
}
assert( retcode < kthreadmax );
pthread_mutex_unlock (&(txconf->mutex));
if (retcode < 0 ) {
txstatus ( txconf , 29);
spins++;
whisper ( 91, "no workers available backing off spins: %i\n", spins );
sleep_thief ++;
//sleep_thief <<= 1;
usleep( sleep_thief );
}
} // we have a winner, return it
assert ( retcode < kthreadmax );
return (retcode);
}
void start_worker( struct txworker_s * txworker ) {
assert( txworker->id < kthreadmax );
pthread_mutex_lock(&(txworker->txconf_parent->mutex));
txworker->state='d';
pthread_mutex_unlock( &(txworker->txconf_parent->mutex) );
txstatus( txworker->txconf_parent, 6 );
}
//dump stdin in chunks
// this is single thread and should use memory at a drastic pace
void txingest (struct txconf_s * txconf ) {
int readsize;
int in_fd = STDIN_FILENO;
int foot_cursor =0;
unsigned long saved_checksum = 0xff;
int ingest_leg_counter = 0;
txconf->stream_total_bytes=0;
checkperror("nuisancse ingest err");
pthread_mutex_lock ( &(txconf->mutex) ) ;
while ( !txconf->done ) {
pthread_mutex_unlock ( &(txconf->mutex) ) ;
int worker = dispatch_idle_worker ( txconf );
assert ( (txconf->workers[worker].buffer) != NULL );
readsize = bufferfill ( in_fd ,(u_char *) (txconf->workers[worker].buffer) , kfootsize ) ;
whisper ( 8, "\ntxw:%02i read leg %i : fd:%i siz:%i\n",worker, ingest_leg_counter, in_fd, kfootsize);
assert ( readsize <= kfootsize );
if ( readsize > 0 ) {
//find the idle worker , lock it and dispatch as seprarte calls -- perhaps
txconf->workers[worker].pkt.size = readsize;
txconf->workers[worker].pkt.leg_id = ingest_leg_counter;
txconf->workers[worker].pkt.opcode=feed_more;
if ( gchecksums ) {
//expensive this code should only be used for developmend
txconf->workers[worker].pkt.checksum =
mix ( saved_checksum + ingest_leg_counter ,
txconf->workers[worker].buffer,
readsize);
saved_checksum = txconf->workers[worker].pkt.checksum;
} else {
txconf->workers[worker].pkt.checksum = 0;
}
start_worker ( &(txconf->workers[worker]) );
txconf->stream_total_bytes += readsize ;
} else {
whisper ( 4, "txingest no more stdin, send shutdown");
pthread_mutex_lock ( &(txconf->mutex) ) ;
txconf->done = 1;
pthread_mutex_unlock ( &(txconf->mutex) ) ;
int worker = dispatch_idle_worker ( txconf );
txconf->workers[worker].pkt.size=0;
txconf->workers[worker].pkt.leg_id = ingest_leg_counter;
txconf->workers[worker].pkt.opcode=end_of_millipede;
start_worker ( &(txconf->workers[worker]) );
}
ingest_leg_counter ++;
pthread_mutex_lock ( &(txconf->mutex) ) ;
}
txconf->done = 1;
pthread_mutex_unlock ( &(txconf->mutex) ) ;
whisper ( 4, "tx:ingest complete for %lu(bytes) in \n\n",txconf->stream_total_bytes);
txstatus( txconf, 5);
u_long usecbusy = stopwatch_stop( &(txconf->ticker),4 );
//bytes per usec - thats interesting
whisper (6, " %8.4f MBps\n" , ( txconf->stream_total_bytes *0.0000001) / (0.000001 * usecbusy ) );
}
int txpush ( struct txworker_s *txworker ) {
//push this buffer out the socket
int retcode = 1;
int writelen =-1;
int cursor=0 ;
txworker->state='a';// preAmble
write (txworker->sockfd , &txworker->pkt, sizeof(struct millipacket_s));
txworker->writeremainder = txworker->pkt.size;
assert ( txworker->writeremainder <= kfootsize );
while ( txworker->writeremainder && retcode ) {
int minedsize = MIN (MAXBSIZE,txworker->writeremainder);
txworker->state='P'; // 'P'ush
if ( chaos_fail () ) {
close (txworker->sockfd); // things fail sometimes
}
writelen = write(txworker->sockfd , ((txworker->buffer)+cursor) , minedsize ) ;
if ( errno != 0 ) { retcode = 0 ;};
checkperror (" write to socket" );
txworker->state='p'; // 'p'ush complete
txworker->writeremainder -= writelen;
cursor += writelen;
whisper (101, "txw:%02i psh leg:%lu.(+%i -%i) ",txworker->id,txworker->pkt.leg_id,writelen,txworker->writeremainder);
}
checkperror( "writesocket");
//assert ( writelen );
pthread_mutex_lock (&(txworker->txconf_parent->mutex));
if ( retcode == 1) {
assert ( txworker->writeremainder == 0 );
txworker->pkt.size=0; /// can't distroythis un less we are successful
txworker->state='i'; // idle ok
} else {
txworker->state='x'; // dead do not transmit more; save state and do it again
whisper ( 7, "rxw:%02i is dead\n", txworker->id);
}
pthread_mutex_unlock (&(txworker->txconf_parent->mutex));
return retcode;
}
int tx_tcp_connect_next ( struct txconf_s * txconf ) {
// pick a port/host from the list, cycleing through them
int chosen_target = txconf->target_port_cursor ++;
txconf->target_port_cursor %= txconf->target_port_count ;
assert ( txconf->target_port_cursor < txconf->target_port_count);
whisper ( 5, "tx: chosen target %s %d\n",
txconf->target_ports[ txconf->target_port_cursor].name ,
txconf->target_ports[ txconf->target_port_cursor].port );
return ( tcp_connect (
txconf->target_ports[ chosen_target ].name,
txconf->target_ports[ chosen_target].port
)
);
}
extern char * gcheckphrase;
int tx_start_net ( struct txworker_s *txworker ) {
///XXXXXchar hellophrase[]="yoes";
const char okphrase[]="ok";
int retcode;
char readback[2048];
txworker->state = 'c'; //connecting
txworker->sockfd = tx_tcp_connect_next ( txworker->txconf_parent );
unsigned int reconnect_fuse = kthreadmax;
while ( ( txworker->sockfd == -1 ) && (reconnect_fuse) ) {
pthread_mutex_lock ( &(txworker->txconf_parent->mutex) ) ;
if ( txworker->txconf_parent->done ) {
pthread_mutex_unlock ( &(txworker->txconf_parent->mutex) ) ;
txworker->state='f';
whisper ( 2, "txw:%02d ingest done reconnect not required anymore; giving up thread\n", txworker->id );
pthread_exit (0);
}
pthread_mutex_unlock ( &(txworker->txconf_parent->mutex) ) ;
pthread_mutex_lock ( &(txworker->mutex));
usleep ( 100 * 1000 );
whisper ( 5, "txw:%02ireconnecting\n", txworker->id);
txworker->sockfd = tx_tcp_connect_next ( txworker->txconf_parent );
// detect a dead connection and move on to the next port in the target map
// scary place to stall holding a lock, looking for a connect()
if ( txworker->sockfd > 0 ) {
//checkperror ("clearing nuisance error after recovery\n");
whisper (5, "txw:%02i reconnect success fd:%i\n",txworker->id, txworker->sockfd);
errno=0;
}
reconnect_fuse --;
}
if ( reconnect_fuse == 0 ) {
//die, we were unable to work thorugh the list and get a grip
txworker->state='f';
whisper ( 2, "txw:%02d reconnect fuse popped; giving up thread\n", txworker->id );
pthread_exit (0);
}
/*
starting sockets in parallel can flood the remote end trivially on high bw networks resulting in
this syndrome and a partially connnected graph
it looks like this on the remote side:
sonewconn: pcb 0xfffff8014ba261a8: Listen queue overflow: 10 already in queue awaiting acceptance (2 occurrences)
pid 4752 (viamillipede), uid 1001: exited on signal 6 (core dumped)
and refused connections on the Local
can the remote end talk?
this is lame but rudimentary q/a session will assert that the tcp stream is able to bear traffic
*/
whisper ( 18, "txw:%i send checkphrase:%s\n", txworker->id, gcheckphrase);
retcode = write (txworker->sockfd, gcheckphrase, 4);
checkperror ( "tx: phrase write fail");
whisper ( 18, "txw:%i expect ok \n", txworker->id);
retcode = read (txworker->sockfd, &readback, 2);
checkperror ("tx: read fail");
if ( bcmp ( okphrase, readback, 2 ) != 0 ) {
whisper ( 5, "txw: %i expected ok failure readlen:%i", txworker->id, retcode );
}
assert ( bcmp ( okphrase, readback, 2 ) == 0 );
whisper ( 13, "txw:%i online fd:%i\n", txworker->id, txworker->sockfd);
txworker->writeremainder=-88;
txstatus (txworker->txconf_parent,7);
pthread_mutex_unlock ( &(txworker->mutex));
return retcode;
}
void txworker_sm (struct txworker_s *txworker ) {
int done =0;
int retcode =-1;
char local_state = 0 ;
int state_spin =0;
int sleep_thief =0;
pthread_mutex_init ( &(txworker->mutex) , NULL ) ;
retcode = tx_start_net( txworker ) ;
assert (retcode > 0 );
whisper ( 11, "txw:%i idling fd:%i\n", txworker->id, txworker->sockfd);
pthread_mutex_lock ( &(txworker->mutex));
txworker->state = 'i'; //idle
pthread_mutex_unlock ( &(txworker->mutex));
txworker->pkt.size = 0 ;
txworker->pkt.leg_id=0;
txworker->pkt.preamble = preamble_cannon_ul;
checkperror( "worker buffer allocator");
while ( !done ) {
pthread_mutex_lock ( &(txworker->txconf_parent->mutex));
assert ( (txworker->id >= 0 ) && ( txworker->id < kthreadmax));
if ( (txworker->txconf_parent->done) ) {
/*p *((*((struct txworker_s *)txworker)).txconf_parent)
y cant lld inspect:
*/
whisper (4, "txw:%02i nothing left to do\n",txworker->id );
done = 1;
}
local_state = txworker->state;
pthread_mutex_unlock ( &(txworker->txconf_parent->mutex));
switch (local_state) {
/* valid states:
E: uninitialized
f: faulted; unble to connect
a: premable; we think we are talking to a villipede server
c: connecting; idle when connected ; die if we are done or cant connected to anything
d: dispatched buffer is loaded; now send it
Pp: pushing
i: idle but connected
x: disconnected, still bearing a buffer. attempt reconnection
n: not yet connected, new no buffer ??? connect => idle
*/
case 'i': break; //idle
restartcase:
case 'd':
if ( txpush ( txworker ) == 0) {
// retry this
whisper ( 3, "txw:%02i socket failed, scheduling retry leg:%lu\n", txworker->id , txworker->pkt.leg_id);
}
sleep_thief=0;
break;
case 'x':
//reinitialize socket and retry a dead worker
whisper ( 6, "txw:02%i starting recovery, preserved leg %lu \n", txworker->id , txworker->pkt.leg_id);
errno =0;
tx_start_net ( txworker);
goto restartcase;
break;
default: assert( -1 && "bad zoot");
}
state_spin ++;
if ( (state_spin % 30000) == 0 && ( txworker->state == 'i' ) ) {
//txstatus ( txworker -> txconf_parent,10 ) ;
whisper ( 9, "txw:%02i is lonely after %i spins \n", txworker->id, state_spin);
}
sleep_thief ++; // this Looks crazy ; but it's good for 30%
//XXX back off tuning tbd
// this works by allowing a context switch and permitting a dispatch ready thread to push
usleep ( sleep_thief );
} // while !done
whisper ( 8, "txw:%02i worker done", txworker->id);
} // txworker
void txlaunchworkers ( struct txconf_s * txconf) {
int worker_cursor = 0;
int ret;
checkperror ("nuicance before launch");
while ( worker_cursor < txconf->worker_count ) {
txconf->workers[worker_cursor].state = '0'; // unitialized
txconf->workers[worker_cursor].txconf_parent = txconf; // allow inpection/inception
txconf->workers[worker_cursor].pkt.leg_id = 0; //
txconf->workers[worker_cursor].pkt.size = -66; //
txconf->workers[worker_cursor].sockfd = -66; //
whisper( 16, "txw:%i launching ", worker_cursor);
txconf->workers[worker_cursor].state = 'L';
txconf->workers[worker_cursor].id = worker_cursor;
//allocate before thread launch
txconf->workers[worker_cursor].buffer = calloc ( 1,(size_t) kfootsize );
assert (txconf->workers[worker_cursor].buffer != NULL && "insufficient memory up front" );
//digression: pthreads murders all possible kittens stored in argument types
checkperror ("nuicance pthread error launch");
ret = pthread_create (
&(txconf->workers[worker_cursor].thread ),
NULL ,
//clang suggest this gibberish, why question?
(void *(* _Nonnull)(void *))&txworker_sm,
&(txconf->workers[worker_cursor])
);
checkperror ("pthread launch");
assert ( ret == 0 && "pthread launch");
worker_cursor++;
usleep ( 10 * 1000);
// 10ms standoff to increase the likelyhood that PCBs are available on the rx side
}
txstatus ( txconf, 5);
}
void txstatus ( struct txconf_s* txconf , int log_level) {
whisper ( log_level, "\nstate:leg-remainder(k)\n");
for ( int i=0; i < txconf->worker_count ; i++) {
if ( i % 8 == 0) { whisper ( log_level , " %02i \n" ,i ); }
whisper(log_level, "%c:%lu-%i\t",
txconf->workers[i].state,
txconf->workers[i].pkt.leg_id,
(txconf->workers[i].writeremainder) >> 10 //kbytes are sufficient
);
}
whisper ( log_level, "\n");
}
void txbusyspin ( struct txconf_s* txconf ) {
// wait until all legs are pushed; called after ingest is complete
// if there are launche/dispatched /pushing workers; hang here
int done =0;
int busy_cycles=0;
char instate='E'; //error uninitialized
while (!done) {
usleep ( 1000 ); // e^n backoff?
if ( (busy_cycles % 100) == 0 ) txstatus( txconf, 4 );
busy_cycles++;
int busy_workers = 0;
for ( int i =0; i < txconf->worker_count ; i++ ) {
//XXXXXpthread_mutex_lock ( &(txconf->workers[i].mutex) );
instate = txconf->workers[i].state ;
//pthread_mutex_unlock ( &(txconf->workers[i].mutex) );
if ( ( instate != 'i') && ( instate != 'f' )) {
busy_workers++;
break; // get out of here if there are busy workers
}
}
done = ( busy_workers == 0 ) ;
}
whisper ( 6, "\ntx: all workers idled after %i spins\n", busy_cycles);
}
struct txconf_s *gtxconf;
void wat ( ) {
struct txconf_s *txconf=gtxconf;
whisper ( 1, "\n%lu(mbytes) in ",txconf->stream_total_bytes >> 20);
u_long usecbusy = stopwatch_stop( &(txconf->ticker),2 );
whisper ( 1 , "\n" );
txstatus ( txconf, 1 );
//bytes per usec - thats interesting bytes to mb
whisper (1, "\n %8.4f MBps\n" , ( txconf->stream_total_bytes / ( 1.0 * usecbusy )) );
}
void partingshot() {
struct txconf_s *txconf=gtxconf;
wat ( );
whisper ( 2, "exiting after signal");
checkperror ( " signal caught");
exit (-6);
}
void init_workers ( struct txconf_s * txconf ) {
int wcursor=kthreadmax;
while ( wcursor -- ) {
txconf->workers[wcursor].id=wcursor;
txconf->workers[wcursor].txconf_parent=txconf;
txconf->workers[wcursor].state='E';
pthread_mutex_init ( &(txconf->workers[wcursor].mutex), NULL);
txconf->workers[wcursor].sockfd=0;
txconf->workers[wcursor].pkt.size=0;
txconf->workers[wcursor].pkt.leg_id=0;
txconf->workers[wcursor].writeremainder=0;
}
}
void tx (struct txconf_s * txconf) {
int retcode;
gtxconf = txconf;
checkperror (" nuicance tx 0");
//start control channel
stopwatch_start( &(txconf->ticker) );
signal (SIGINFO, &wat);
signal (SIGINT, &partingshot);
signal (SIGHUP, &partingshot);
checkperror (" nuicance tx 1");
pthread_mutex_init ( &(txconf->mutex), NULL ) ;
pthread_mutex_lock ( &(txconf->mutex) ) ;
checkperror (" nuicance tx 2");
txconf->done = 0;
pthread_mutex_unlock ( &(txconf->mutex) ) ;
init_workers( txconf );
checkperror (" nuicance tx 3");
txlaunchworkers( txconf );
txingest ( txconf );
txbusyspin ( txconf );
whisper ( 2, "all complete for %lu(bytes) in ",txconf->stream_total_bytes);
u_long usecbusy = stopwatch_stop( &(txconf->ticker),2 );
//bytes per usec - thats interesting ~== to mbps
whisper (1, " %05.3f MBps\n" , ( txconf->stream_total_bytes / ( 1.0 * usecbusy )) );
}
| 2.375 | 2 |
2024-11-18T22:49:16.122411+00:00 | 2021-11-25T22:27:12 | b75dd07ac9e4d8d131b6b4c0b59c3b800a597cd8 | {
"blob_id": "b75dd07ac9e4d8d131b6b4c0b59c3b800a597cd8",
"branch_name": "refs/heads/master",
"committer_date": "2021-11-25T22:27:12",
"content_id": "bb5bf9dc1ec74de249fd3c8a231653bae8dfd33c",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "bade93cbfc1f25160dfbe9493bfa83f853326475",
"extension": "c",
"filename": "hello.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": 2825,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/mwc/romana/relic/d/conf/tboot/Examples/hello.c",
"provenance": "stackv2-0108.json.gz:92814",
"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/d/conf/tboot/Examples/hello.c",
"visit_date": "2021-12-01T17:49:53.618512"
} | stackv2 | /* Test program for tertiary boot.
* These are simple tests I found useful in building and
* debugging boot library routines.
*
* La Monte H. Yarroll <piggy@mwc.com>, September 1991
*/
#include <ctype.h>
#include <canon.h>
#include <sys/types.h>
#include <sys/ino.h>
#include <sys/inode.h>
#include <sys/dir.h>
#include "tboot.h"
/* CMOS addresses */
#define LOMEM 0x15 /* Memory size below 1MB. */
#define EXTMEM 0x17 /* Memory size avove 1MB. */
main()
{
int i, k;
long j;
unsigned int tmp;
char letter;
char buffer[BLOCK];
char outbuff[LINESIZE]; /* Buffer for outputing numbers. */
char filename[LINESIZE]; /* Name of a file to look up. */
struct inode rootinode;
struct inode myinode;
struct direct dirent;
/* Test the output routines puts() and putchar(). */
puts("Hello world!\r\n");
/* Open "/" and print out the direct block file entries. */
iopen(&rootinode, (ino_t) 2);
/* Read each directory entry one at a time. */
for (i = 0; i < rootinode.i_size; i += sizeof(struct direct)) {
iread(&rootinode, (char *) &dirent, (fsize_t) i,
(uint16) sizeof(struct direct));
/* Canonicalize it. */
canino(dirent.d_ino);
/* NUL terminate the name. */
strncpy(outbuff,
dirent.d_name,
DIRSIZ);
outbuff[DIRSIZ] = '\0';
/* Print the file name. */
puts(outbuff);
puts(" ");
/* Print the inode number in hexadecimal. */
itobase((int) (dirent.d_ino), outbuff, 16);
puts(outbuff);
putchar(':');
}
/* Get some information from the CMOS. */
puts("\r\nLow memory: ");
print16(read16_cmos(LOMEM));
puts("K\r\n");
puts("Extended memory: ");
print16(read_cmos(EXTMEM, &tmp, 2));
puts("K\r\n");
puts("CMOS:\r\n");
for (i=0; i < 52; ++i) {
print16(i);
puts(": ");
print16(read_cmos(i));
puts(" ");
}
/* Test namei() by asking for a file name and looking it up. */
puts("\r\nPlease enter a file name: ");
gets(filename);
puts("\r\nThe inode number for that is: ");
itobase((int) namei(filename), outbuff, 16);
puts(outbuff);
if (0 == iopen(&myinode, namei(filename))) {
puts("\r\nCan't open ");
puts(filename);
puts(".\r\n");
}
/* Fetch selected blocks from the file. */
puts("\r\nPlease enter an hex offset (! to finish): ");
gets(outbuff);
while (outbuff[0] != '!') {
puts("\r\n");
i = basetoi(outbuff, 16);
iread(&myinode, buffer,
((fsize_t) i * (fsize_t) BLOCK) ,
(short) BLOCK);
buffer[BLOCK] = '\0';
puts(buffer);
puts("\r\nPlease enter an hex offset: ");
gets(outbuff);
}
puts("\r\nHit '!' to finish echo test.\r\n");
/* Echo characters until we get a '!' character.
* This tests the input routine getchar().
*/
while ((char) '!' != (letter = (char) getchar())) {
putchar(letter);
itobase((int) letter, outbuff, 16);
puts(outbuff);
putchar(':');
}
}
| 2.921875 | 3 |
2024-11-18T22:49:16.599883+00:00 | 2020-07-31T05:45:10 | 8a3eece6effd2657527d60f11bbed628a05e90cd | {
"blob_id": "8a3eece6effd2657527d60f11bbed628a05e90cd",
"branch_name": "refs/heads/AT",
"committer_date": "2020-07-31T05:45:10",
"content_id": "1fa06e69fbe537fe23e18bc493ccd15bec86f499",
"detected_licenses": [
"MIT"
],
"directory_id": "e368d28ab359f703b784b23280a98caa58d4fa72",
"extension": "c",
"filename": "us_transport.c",
"fork_events_count": 7,
"gha_created_at": "2020-04-13T03:18:22",
"gha_event_created_at": "2020-07-31T05:45:11",
"gha_language": "C",
"gha_license_id": null,
"github_id": 255220669,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 32256,
"license": "MIT",
"license_type": "permissive",
"path": "/component/common/drivers/usb/host/msc/src/us_transport.c",
"provenance": "stackv2-0108.json.gz:93073",
"repo_name": "Seeed-Studio/seeed-ambd-sdk",
"revision_date": "2020-07-31T05:45:10",
"revision_id": "3cc64f293f756ffb3cd379fffb972b7401cb0951",
"snapshot_id": "93b3f853142026b0bb15f320129f7e893c981ae1",
"src_encoding": "UTF-8",
"star_events_count": 12,
"url": "https://raw.githubusercontent.com/Seeed-Studio/seeed-ambd-sdk/3cc64f293f756ffb3cd379fffb972b7401cb0951/component/common/drivers/usb/host/msc/src/us_transport.c",
"visit_date": "2022-11-25T06:55:17.361575"
} | stackv2 | #include <platform_opts.h>
#ifdef CONFIG_USBH_MSC
#include "us_usb.h"
#include "us_debug.h"
#include "us_usual.h"
#include "us_transport.h"
#include "storage.h"
#include "us_os_wrap_via_osdep_api.h"
#include <quirks/quirks.h>
#include <scsi/scsi_cmnd.h>
#include <scsi/scsi_eh.h>
#include "osdep_service.h"
void usb_stor_show_sense(
unsigned char key,
unsigned char asc,
unsigned char ascq);
/* This is the completion handler which will wake us up when an URB
* completes.
*/
static void usb_stor_blocking_completion(struct urb *urb)
{
_sema *complete_sema = urb->context;
rtw_up_sema(complete_sema); // release control urb semaphore
}
/* This is the common part of the URB message submission code
*
* All URBs from the usb-storage driver involved in handling a queued scsi
* command _must_ pass through this function (or something like it) for the
* abort mechanisms to work properly.
*/
static int usb_stor_msg_common(struct us_data *us, int timeout)
{
_sema urb_done;
int status;
unsigned long expire;
/* don't submit URBs during abort processing */
if (test_bit(US_FLIDX_ABORTING, &us->dflags))
return -EIO;
/* set up data structures for the wakeup system */
rtw_init_sema(&urb_done, 0);
/* fill the common fields in the URB */
us->current_urb->context = &urb_done;
us->current_urb->transfer_flags = 0;
/* we assume that if transfer_buffer isn't us->iobuf then it
* hasn't been mapped for DMA. Yes, this is clunky, but it's
* easier than always having the caller tell us whether the
* transfer buffer has already been mapped. */
if (us->current_urb->transfer_buffer == us->iobuf)
us->current_urb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
us->current_urb->transfer_dma = us->iobuf_dma;
/* submit the URB */
status = usb_submit_urb(us->current_urb);
if (status) {
/* something went wrong */
rtw_free_sema(&urb_done);
return status;
}
/* since the URB has been submitted successfully, it's now okay
* to cancel it */
set_bit(US_FLIDX_URB_ACTIVE, &us->dflags);
/* did an abort occur during the submission? */
if (test_bit(US_FLIDX_ABORTING, &us->dflags)) {
/* cancel the URB, if it hasn't been cancelled already */
if (test_and_clear_bit(US_FLIDX_URB_ACTIVE, &us->dflags)) {
US_ERR("Cancelling URB\n");
usb_unlink_urb(us->current_urb);
}
}
/* wait for the completion of the URB */
expire = timeout ? timeout : 2000;
if (rtw_down_timeout_sema(&urb_done, expire) == _FAIL){
US_ERR("Wait urb time out!!");
usb_kill_urb(us->current_urb);
}
clear_bit(US_FLIDX_URB_ACTIVE, &us->dflags);
// free memory for sema
rtw_free_sema(&urb_done);
/* return the URB status */
return us->current_urb->status;
}
/*
* Transfer one control message, with timeouts, and allowing early
* termination. Return codes are usual -Exxx, *not* USB_STOR_XFER_xxx.
*/
int usb_stor_control_msg(struct us_data *us, unsigned int pipe,
u8 request, u8 requesttype, u16 value, u16 index,
void *data, u16 size, int timeout)
{
int status;
US_INFO("rq=%02x rqtype=%02x value=%04x index=%02x len=%d\n",
request, requesttype, value, index, size);
/* fill in the devrequest structure */
us->cr->bRequestType = requesttype;
us->cr->bRequest = request;
us->cr->wValue = cpu_to_le16(value);
us->cr->wIndex = cpu_to_le16(index);
us->cr->wLength = cpu_to_le16(size);
/* fill and submit the URB */
usb_fill_control_urb(us->current_urb, us->pusb_dev, pipe,
(unsigned char*) us->cr, data, size,
usb_stor_blocking_completion, NULL);
status = usb_stor_msg_common(us, timeout);
/* return the actual length of the data transferred if no error */
if (status == 0)
status = us->current_urb->actual_length;
return status;
}
/* This is a version of usb_clear_halt() that allows early termination and
* doesn't read the status from the device -- this is because some devices
* crash their internal firmware when the status is requested after a halt.
*
* A definitive list of these 'bad' devices is too difficult to maintain or
* make complete enough to be useful. This problem was first observed on the
* Hagiwara FlashGate DUAL unit. However, bus traces reveal that neither
* MacOS nor Windows checks the status after clearing a halt.
*
* Since many vendors in this space limit their testing to interoperability
* with these two OSes, specification violations like this one are common.
*/
int usb_stor_clear_halt(struct us_data *us, unsigned int pipe)
{
int result;
int endp = usb_pipeendpoint(pipe);
US_ENTER;
if (usb_pipein (pipe))
endp |= USB_DIR_IN;
result = usb_stor_control_msg(us, us->send_ctrl_pipe,
USB_REQ_CLEAR_FEATURE, USB_RECIP_ENDPOINT,
USB_ENDPOINT_HALT, endp,
NULL, 0, 3*SCSI_HZ);
if (result >= 0)
usb_reset_endpoint(us->pusb_dev, endp);
US_INFO("result = %d\n", result);
US_EXIT;
return result;
}
/*
* Interpret the results of a URB transfer
*
* This function prints appropriate debugging messages, clears halts on
* non-control endpoints, and translates the status to the corresponding
* USB_STOR_XFER_xxx return code.
*/
static int interpret_urb_result(struct us_data *us, unsigned int pipe,
unsigned int length, int result, unsigned int partial)
{
int res = USB_STOR_XFER_GOOD;
US_ENTER;
US_INFO("Status code %d; transferred %d/%d\n",result, partial, length);
switch (result) {
/* no error code; did we send all the data? */
case 0:
if (partial != length) {
US_WARN("Short transfer\n");
res = USB_STOR_XFER_SHORT;
break;
}
US_INFO("Transfer complete\n");
res = USB_STOR_XFER_GOOD;
break;
/* stalled */
case -EPIPE:
/* for control endpoints, (used by CB[I]) a stall indicates
* a failed command */
if (usb_pipecontrol(pipe)) {
US_ERR("Stall on control pipe\n");
res = USB_STOR_XFER_STALLED;
break;
}
/* for other sorts of endpoint, clear the stall */
US_ERR("Stall on bulk pipe(%d), execute clearing halt status.\n", pipe);
if (usb_stor_clear_halt(us, pipe) < 0){
res = USB_STOR_XFER_ERROR;
break;
}
res = USB_STOR_XFER_STALLED;
break;
/* babble - the device tried to send more than we wanted to read */
case -EOVERFLOW:
US_ERR("The device tried to send more than we wanted to read\n");
res = USB_STOR_XFER_LONG;
break;
/* the transfer was cancelled by abort, disconnect, or timeout */
case -ECONNRESET:
US_ERR("Transfer cancelled\n");
res = USB_STOR_XFER_ERROR;
break;
/* short scatter-gather read transfer */
case -EREMOTEIO:
US_ERR("Short read transfer\n");
res = USB_STOR_XFER_SHORT;
break;
/* abort or disconnect in progress */
case -EIO:
US_ERR("Abort or disconnect in progress\n");
res = USB_STOR_XFER_ERROR;
break;
/* the catch-all error case */
default:
US_ERR("Unknown error %d\n", result);
res = USB_STOR_XFER_ERROR;
}
US_EXIT;
return res;
}
/*
* Transfer one buffer via bulk pipe, without timeouts, but allowing early
* termination. Return codes are USB_STOR_XFER_xxx. If the bulk pipe
* stalls during the transfer, the halt is automatically cleared.
*/
int usb_stor_bulk_transfer_buf(struct us_data *us, unsigned int pipe,
void *buf, unsigned int length, unsigned int *act_len)
{
int result;
US_INFO("xfer %d bytes\n", length);
/* fill and submit the URB */
usb_fill_bulk_urb(us->current_urb, us->pusb_dev, pipe, buf, length,
usb_stor_blocking_completion, NULL);
result = usb_stor_msg_common(us, 0);
/* store the actual length of the data transferred */
if (act_len)
*act_len = us->current_urb->actual_length;
return interpret_urb_result(us, pipe, length, result,
us->current_urb->actual_length);
}
/***********************************************************************
* Transport routines
***********************************************************************/
/* There are so many devices that report the capacity incorrectly,
* this routine was written to counteract some of the resulting
* problems.
*/
static void last_sector_hacks(struct us_data *us, struct scsi_cmnd *srb)
{
UNUSED(us);
UNUSED(srb);
#if 0
struct gendisk *disk;
struct scsi_disk *sdkp;
u32 sector;
/* To Report "Medium Error: Record Not Found */
static unsigned char record_not_found[18] = {
[0] = 0x70, /* current error */
[2] = MEDIUM_ERROR, /* = 0x03 */
[7] = 0x0a, /* additional length */
[12] = 0x14 /* Record Not Found */
};
/* If last-sector problems can't occur, whether because the
* capacity was already decremented or because the device is
* known to report the correct capacity, then we don't need
* to do anything.
*/
if (!us->use_last_sector_hacks)
return;
/* Was this command a READ(10) or a WRITE(10)? */
if (srb->cmnd[0] != READ_10 && srb->cmnd[0] != WRITE_10)
goto done;
/* Did this command access the last sector? */
sector = (srb->cmnd[2] << 24) | (srb->cmnd[3] << 16) |
(srb->cmnd[4] << 8) | (srb->cmnd[5]);
disk = srb->request->rq_disk;
if (!disk)
goto done;
sdkp = scsi_disk(disk);
if (!sdkp)
goto done;
if (sector + 1 != sdkp->capacity)
goto done;
if (srb->result == SAM_STAT_GOOD && scsi_get_resid(srb) == 0) {
/* The command succeeded. We know this device doesn't
* have the last-sector bug, so stop checking it.
*/
us->use_last_sector_hacks = 0;
} else {
/* The command failed. Allow up to 3 retries in case this
* is some normal sort of failure. After that, assume the
* capacity is wrong and we're trying to access the sector
* beyond the end. Replace the result code and sense data
* with values that will cause the SCSI core to fail the
* command immediately, instead of going into an infinite
* (or even just a very long) retry loop.
*/
if (++us->last_sector_retries < 3)
return;
srb->result = SAM_STAT_CHECK_CONDITION;
memcpy(srb->sense_buffer, record_not_found,
sizeof(record_not_found));
}
done:
/* Don't reset the retry counter for TEST UNIT READY commands,
* because they get issued after device resets which might be
* caused by a failed last-sector access.
*/
if (srb->cmnd[0] != TEST_UNIT_READY)
us->last_sector_retries = 0;
#endif
}
/* Invoke the transport and basic error-handling/recovery methods
*
* This is used by the protocol layers to actually send the message to
* the device and receive the response.
*/
void usb_stor_invoke_transport(struct scsi_cmnd *srb, struct us_data *us)
{
int need_auto_sense;
int result;
US_ENTER;
/* send the command to the transport layer */
scsi_set_resid(srb, 0); // resid: number of bytes requested less actual transferred
result = us->transport(srb, us);
/* if the command gets aborted by the higher layers, we need to
* short-circuit all other processing
*/
if (test_bit(US_FLIDX_TIMED_OUT, &us->dflags)) {
US_ERR("Command was aborted\n");
srb->result = DID_ABORT << 16;
goto Handle_Errors;
}
/* if there is a transport error, reset and don't auto-sense */
if (result == USB_STOR_TRANSPORT_ERROR) {
US_ERR("Transport indicates error, resetting\n");
srb->result = DID_ERROR << 16;
goto Handle_Errors;
}
/* if the transport provided its own sense data, don't auto-sense */
if (result == USB_STOR_TRANSPORT_NO_SENSE) {
srb->result = SAM_STAT_CHECK_CONDITION;
last_sector_hacks(us, srb);
US_EXIT;
return;
}
srb->result = SAM_STAT_GOOD;
/* Determine if we need to auto-sense
*
* I normally don't use a flag like this, but it's almost impossible
* to understand what's going on here if I don't.
*/
need_auto_sense = 0;
/*
* If we're running the CB transport, which is incapable
* of determining status on its own, we will auto-sense
* unless the operation involved a data-in transfer. Devices
* can signal most data-in errors by stalling the bulk-in pipe.
*/
if ((us->protocol == USB_PR_CB || us->protocol == USB_PR_DPCM_USB) &&
srb->sc_data_direction != DMA_FROM_DEVICE) {
US_INFO("CB transport device requiring auto-sense\n");
need_auto_sense = 1;
}
/*
* If we have a failure, we're going to do a REQUEST_SENSE
* automatically. Note that we differentiate between a command
* "failure" and an "error" in the transport mechanism.
*/
if (result == USB_STOR_TRANSPORT_FAILED) {
US_INFO("Transport indicates command failure, invoke auto-sense\n");
need_auto_sense = 1;
}
/*
* Determine if this device is SAT by seeing if the
* command executed successfully. Otherwise we'll have
* to wait for at least one CHECK_CONDITION to determine
* SANE_SENSE support
*/
if (unlikely((srb->cmnd[0] == ATA_16 || srb->cmnd[0] == ATA_12) &&
result == USB_STOR_TRANSPORT_GOOD &&
!(us->fflags & US_FL_SANE_SENSE) &&
!(us->fflags & US_FL_BAD_SENSE) &&
!(srb->cmnd[2] & 0x20))) {
US_INFO("SAT supported, increasing auto-sense\n");
us->fflags |= US_FL_SANE_SENSE;
}
/*
* A short transfer on a command where we don't expect it
* is unusual, but it doesn't mean we need to auto-sense.
*/
if ((scsi_get_resid(srb) > 0) &&
!((srb->cmnd[0] == REQUEST_SENSE) ||
(srb->cmnd[0] == INQUIRY) ||
(srb->cmnd[0] == MODE_SENSE) ||
(srb->cmnd[0] == LOG_SENSE) ||
(srb->cmnd[0] == MODE_SENSE_10))) {
US_INFO("Unexpectedly short transfer\n");
}
/* Now, if we need to do the auto-sense, let's do it */
if (need_auto_sense) {
int temp_result;
struct scsi_eh_save ses; // save state (the old command)
int sense_size = US_SENSE_SIZE;
struct scsi_sense_hdr sshdr;
const u8 *scdd;
u8 fm_ili;
unsigned char sense_buff[SCSI_SENSE_BUFFERSIZE];
memset(sense_buff,0,SCSI_SENSE_BUFFERSIZE);
srb->sense_buffer = sense_buff;
/* device supports and needs bigger sense buffer */
if (us->fflags & US_FL_SANE_SENSE)
sense_size = ~0;
//Retry_Sense:
US_INFO("Issuing auto-REQUEST_SENSE\n");
scsi_eh_prep_cmnd(srb, &ses, NULL, 0, sense_size);
/* FIXME: we must do the protocol translation here */
if (us->subclass == USB_SC_RBC || us->subclass == USB_SC_SCSI ||
us->subclass == USB_SC_CYP_ATACB)
srb->cmd_len = 6;
else
srb->cmd_len = 12;
/* issue the auto-sense command */
scsi_set_resid(srb, 0);
temp_result = us->transport(srb, us);
/* let's clean up right away */
// restore the old set of parameter
scsi_eh_restore_cmnd(srb, &ses);
if (test_bit(US_FLIDX_TIMED_OUT, &us->dflags)) {
US_ERR("Auto-sense aborted\n");
srb->result = DID_ABORT << 16;
/* If SANE_SENSE caused this problem, disable it */
if (sense_size != US_SENSE_SIZE) {
us->fflags &= ~US_FL_SANE_SENSE;
us->fflags |= US_FL_BAD_SENSE;
}
goto Handle_Errors;
}
//
// /* Some devices claim to support larger sense but fail when
// * trying to request it. When a transport failure happens
// * using US_FS_SANE_SENSE, we always retry with a standard
// * (small) sense request. This fixes some USB GSM modems
// */
// if (temp_result == USB_STOR_TRANSPORT_FAILED &&
// sense_size != US_SENSE_SIZE) {
// USB_US_PRINTF("-- auto-sense failure, retry small sense\n");
// sense_size = US_SENSE_SIZE;
// us->fflags &= ~US_FL_SANE_SENSE;
// us->fflags |= US_FL_BAD_SENSE;
// goto Retry_Sense;
// }
//
/* Other failures */
if (temp_result != USB_STOR_TRANSPORT_GOOD) {
US_ERR("Auto-sense failed\n");
/* we skip the reset if this happens to be a
* multi-target device, since failure of an
* auto-sense is perfectly valid
*/
srb->result = DID_ERROR << 16;
if (!(us->fflags & US_FL_SCM_MULT_TARG))
goto Handle_Errors;
return;
}
//
/* If the sense data returned is larger than 18-bytes then we
* assume this device supports requesting more in the future.
* The response code must be 70h through 73h inclusive.
*/
if (srb->sense_buffer[7] > (US_SENSE_SIZE - 8) &&
!(us->fflags & US_FL_SANE_SENSE) &&
!(us->fflags & US_FL_BAD_SENSE) &&
(srb->sense_buffer[0] & 0x7C) == 0x70) {
US_INFO("SANE_SENSE support enabled\n");
us->fflags |= US_FL_SANE_SENSE;
/* Indicate to the user that we truncated their sense
* because we didn't know it supported larger sense.
*/
US_INFO("Sense data truncated to %d from %d\n",
US_SENSE_SIZE,
srb->sense_buffer[7] + 8);
srb->sense_buffer[7] = (US_SENSE_SIZE - 8);
}
scsi_normalize_sense(srb->sense_buffer, SCSI_SENSE_BUFFERSIZE,
&sshdr);
US_INFO("Result from auto-sense is %d\n",
temp_result);
US_INFO("Code: 0x%x, key: 0x%x, ASC: 0x%x, ASCQ: 0x%x\n",
sshdr.response_code, sshdr.sense_key,
sshdr.asc, sshdr.ascq);
usb_stor_show_sense(sshdr.sense_key, sshdr.asc, sshdr.ascq);
//
/* set the result so the higher layers expect this data */
srb->result = SAM_STAT_CHECK_CONDITION;
scdd = scsi_sense_desc_find(srb->sense_buffer,
SCSI_SENSE_BUFFERSIZE, 4);
fm_ili = (scdd ? scdd[3] : srb->sense_buffer[2]) & 0xA0;
//
/* We often get empty sense data. This could indicate that
* everything worked or that there was an unspecified
* problem. We have to decide which.
*/
if (sshdr.sense_key == 0 && sshdr.asc == 0 && sshdr.ascq == 0 &&
fm_ili == 0) {
/* If things are really okay, then let's show that.
* Zero out the sense buffer so the higher layers
* won't realize we did an unsolicited auto-sense.
*/
if (result == USB_STOR_TRANSPORT_GOOD) {
srb->result = SAM_STAT_GOOD;
srb->sense_buffer[0] = 0x0;
/* If there was a problem, report an unspecified
* hardware error to prevent the higher layers from
* entering an infinite retry loop.
*/
} else {
srb->result = DID_ERROR << 16;
if ((sshdr.response_code & 0x72) == 0x72)
srb->sense_buffer[1] = HARDWARE_ERROR;
else
srb->sense_buffer[2] = HARDWARE_ERROR;
}
}
} /* end of need_auto_sense*/
/*
* Some devices don't work or return incorrect data the first
* time they get a READ(10) command, or for the first READ(10)
* after a media change. If the INITIAL_READ10 flag is set,
* keep track of whether READ(10) commands succeed. If the
* previous one succeeded and this one failed, set the REDO_READ10
* flag to force a retry.
*/
if (unlikely((us->fflags & US_FL_INITIAL_READ10) &&
srb->cmnd[0] == READ_10)) {
if (srb->result == SAM_STAT_GOOD) {
set_bit(US_FLIDX_READ10_WORKED, &us->dflags);
} else if (test_bit(US_FLIDX_READ10_WORKED, &us->dflags)) {
clear_bit(US_FLIDX_READ10_WORKED, &us->dflags);
set_bit(US_FLIDX_REDO_READ10, &us->dflags);
}
/*
* Next, if the REDO_READ10 flag is set, return a result
* code that will cause the SCSI core to retry the READ(10)
* command immediately.
*/
if (test_bit(US_FLIDX_REDO_READ10, &us->dflags)) {
clear_bit(US_FLIDX_REDO_READ10, &us->dflags);
srb->result = DID_IMM_RETRY << 16;
srb->sense_buffer[0] = 0;
}
}
/* Did we transfer less than the minimum amount required? */
if ((srb->result == SAM_STAT_GOOD || srb->sense_buffer[2] == 0) &&
scsi_bufflen(srb) - scsi_get_resid(srb) < srb->underflow)
srb->result = DID_ERROR << 16;
last_sector_hacks(us, srb);
US_EXIT;
return;
/* Error and abort processing: try to resynchronize with the device
* by issuing a port reset. If that fails, try a class-specific
* device reset. */
Handle_Errors:
/* Set the RESETTING bit, and clear the ABORTING bit so that
* the reset may proceed. */
set_bit(US_FLIDX_RESETTING, &us->dflags);
clear_bit(US_FLIDX_ABORTING, &us->dflags);
/* We must release the device lock because the pre_reset routine
* will want to acquire it. */
rtw_mutex_put(&us->dev_mutex);
result = usb_stor_port_reset(us);
rtw_mutex_get(&us->dev_mutex);
if (result < 0) {
us->transport_reset(us);
}
clear_bit(US_FLIDX_RESETTING, &us->dflags);
last_sector_hacks(us, srb);
US_EXIT;
}
/*
* Bulk only transport
*/
/* Determine what the maximum LUN supported is */
int usb_stor_Bulk_max_lun(struct us_data *us)
{
int result;
/* issue the command */
us->iobuf[0] = 0;
result = usb_stor_control_msg(us, us->recv_ctrl_pipe,
US_BULK_GET_MAX_LUN,
USB_DIR_IN | USB_TYPE_CLASS |
USB_RECIP_INTERFACE,
0, us->ifnum, us->iobuf, 1, 5*SCSI_HZ);
US_INFO("GetMaxLUN command result is %d, data is %d\n",
result, us->iobuf[0]);
/* if we have a successful request, return the result */
if (result > 0)
return us->iobuf[0];
/*
* Some devices don't like GetMaxLUN. They may STALL the control
* pipe, they may return a zero-length result, they may do nothing at
* all and timeout, or they may fail in even more bizarrely creative
* ways. In these cases the best approach is to use the default
* value: only one LUN.
*/
return 0;
}
int usb_stor_Bulk_transport(struct scsi_cmnd *srb, struct us_data *us)
{
struct bulk_cb_wrap *bcb = (struct bulk_cb_wrap *) us->iobuf;
struct bulk_cs_wrap *bcs = (struct bulk_cs_wrap *) us->iobuf;
unsigned int transfer_length = scsi_bufflen(srb);
unsigned int residue;
int result;
int fake_sense = 0;
unsigned int cbwlen = US_BULK_CB_WRAP_LEN;
unsigned int act_cbwlen;
unsigned int cswlen = US_BULK_CS_WRAP_LEN;
unsigned int act_cswlen;
US_ENTER;
/* Take care of BULK32 devices; set extra byte to 0 */
if (unlikely(us->fflags & US_FL_BULK32)) {
cbwlen = 32;
us->iobuf[31] = 0;
}
/* set up the command wrapper */
bcb->Signature = cpu_to_le32(US_BULK_CB_SIGN);
bcb->DataTransferLength = cpu_to_le32(transfer_length);
bcb->Flags = srb->sc_data_direction == DMA_FROM_DEVICE?US_BULK_FLAG_IN : US_BULK_FLAG_OUT;
bcb->Tag = ++us->tag;
bcb->Lun = srb->lun;
// if (us->fflags & US_FL_SCM_MULT_TARG)
// bcb->Lun |= srb->device->id << 4;
bcb->Length = srb->cmd_len; // the length of command
/* copy the command payload */
memset(bcb->CDB, 0, sizeof(bcb->CDB));
memcpy(bcb->CDB, srb->cmnd, bcb->Length);
//2 COMMAND STAGE
/* send it to out endpoint */
US_INFO("Bulk Command S 0x%x T 0x%x L %d F %d Trg %d LUN %d CL %d\n",
le32_to_cpu(bcb->Signature), bcb->Tag,
le32_to_cpu(bcb->DataTransferLength), bcb->Flags,
(bcb->Lun >> 4), (bcb->Lun & 0x0F),
bcb->Length);
result = usb_stor_bulk_transfer_buf(us, us->send_bulk_pipe, bcb, cbwlen, &act_cbwlen);
US_INFO("Bulk command transfer result = %d,Transferred:%d/%d", result, act_cbwlen, cbwlen);
if (result != USB_STOR_XFER_GOOD){
US_ERR("Bolk out Command fail.\n");
US_EXIT;
return USB_STOR_TRANSPORT_ERROR;
}
//2 DATA STAGE
/* send/receive data payload, if there is any */
/* Some USB-IDE converter chips need a 100us delay between the
* command phase and the data phase. Some devices need a little
* more than that, probably because of clock rate inaccuracies. */
if (unlikely(us->fflags & US_FL_GO_SLOW))
udelay(125);
if (transfer_length) {
unsigned int pipe = srb->sc_data_direction == DMA_FROM_DEVICE ?
us->recv_bulk_pipe : us->send_bulk_pipe;
US_INFO("Bulk data transfer begin\n");
#if CONFIG_SG//scatter-gather DMA transfer
result = usb_stor_bulk_srb(us, pipe, srb);
#else //block DMA transfer
unsigned int partial;
result = usb_stor_bulk_transfer_buf(us, pipe, srb->sdb.data_buffer, \
transfer_length, &partial);
US_INFO("Bulk data transfer result: 0x%x;Transferred: %d/%d\n", result, \
partial,transfer_length);
#endif
if (result == USB_STOR_XFER_ERROR){
US_ERR("Bolk in/out data fail.\n");
US_EXIT;
return USB_STOR_TRANSPORT_ERROR;
}
/* If the device tried to send back more data than the
* amount requested, the spec requires us to transfer
* the CSW anyway. Since there's no point retrying the
* the command, we'll return fake sense data indicating
* Illegal Request, Invalid Field in CDB.
*/
if (result == USB_STOR_XFER_LONG)
fake_sense = 1;
}
memset(bcs, 0, sizeof(struct bulk_cs_wrap));
//2 STATUS STAGE
/* get CSW for device status */
US_INFO("Attempting to get CSW...\n");
result = usb_stor_bulk_transfer_buf(us, us->recv_bulk_pipe,
bcs, cswlen, &act_cswlen);
/* Some broken devices add unnecessary zero-length packets to the
* end of their data transfers. Such packets show up as 0-length
* CSWs. If we encounter such a thing, try to read the CSW again.
*/
if (result == USB_STOR_XFER_SHORT && cswlen == 0) {
US_ERR("Received 0-length CSW; retrying...\n");
memset(bcs, 0, sizeof(struct bulk_cs_wrap));
result = usb_stor_bulk_transfer_buf(us, us->recv_bulk_pipe,
bcs, US_BULK_CS_WRAP_LEN, &cswlen);
}
/* did the attempt to read the CSW fail? */
if (result == USB_STOR_XFER_STALLED) {
/* get the status again */
US_WARN("Attempting to get CSW (2nd try)...\n");
memset(bcs, 0, sizeof(struct bulk_cs_wrap));
result = usb_stor_bulk_transfer_buf(us, us->recv_bulk_pipe,
bcs, US_BULK_CS_WRAP_LEN, NULL);
}
/* if we still have a failure at this point, we're in trouble */
US_INFO("Bulk status result = %d; Received:%d/%d \n", \
result, act_cswlen, cswlen);
if (result != USB_STOR_XFER_GOOD){
US_ERR("Receive CWS fail.\n");
US_EXIT;
return USB_STOR_TRANSPORT_ERROR;
}
/* check bulk status */
residue = le32_to_cpu(bcs->Residue);
US_INFO("Bulk Status S 0x%x T 0x%x R %d Stat 0x%x\n",
le32_to_cpu(bcs->Signature), bcs->Tag,
residue, bcs->Status);
if (!(bcs->Tag == us->tag || (us->fflags & US_FL_BULK_IGNORE_TAG)) ||
bcs->Status > US_BULK_STAT_PHASE) {
US_ERR("Bulk logical error\n");
US_EXIT;
return USB_STOR_TRANSPORT_ERROR;
}
/* Some broken devices report odd signatures, so we do not check them
* for validity against the spec. We store the first one we see,
* and check subsequent transfers for validity against this signature.
*/
if (!us->bcs_signature) {
us->bcs_signature = bcs->Signature;
if (us->bcs_signature != cpu_to_le32(US_BULK_CS_SIGN)) {
US_INFO("Learnt BCS signature 0x%08X\n", le32_to_cpu(us->bcs_signature));
}
} else if (bcs->Signature != us->bcs_signature) {
US_ERR("Signature mismatch: got %08X, expecting %08X\n",
le32_to_cpu(bcs->Signature),
le32_to_cpu(us->bcs_signature));
US_EXIT;
return USB_STOR_TRANSPORT_ERROR;
}
/* try to compute the actual residue, based on how much data
* was really transferred and what the device tells us */
if (residue && !(us->fflags & US_FL_IGNORE_RESIDUE)) {
/* Heuristically detect devices that generate bogus residues
* by seeing what happens with INQUIRY and READ CAPACITY
* commands.
*/
if (bcs->Status == US_BULK_STAT_OK &&
scsi_get_resid(srb) == 0 &&
((srb->cmnd[0] == INQUIRY &&
transfer_length == 36) ||
(srb->cmnd[0] == READ_CAPACITY &&
transfer_length == 8))) {
us->fflags |= US_FL_IGNORE_RESIDUE;
} else {
residue = min(residue, transfer_length);
scsi_set_resid(srb, max(scsi_get_resid(srb),
(int) residue));
}
}
/* based on the status code, we report good or bad */
switch (bcs->Status) {
case US_BULK_STAT_OK:
/* device babbled -- return fake sense data */
if (fake_sense) {
memcpy(srb->sense_buffer,
usb_stor_sense_invalidCDB,
sizeof(usb_stor_sense_invalidCDB));
US_EXIT;
return USB_STOR_TRANSPORT_NO_SENSE;
}
/* command good -- note that data could be short */
US_INFO("SCSI command passed\n");
US_EXIT;
return USB_STOR_TRANSPORT_GOOD;
case US_BULK_STAT_FAIL:
US_ERR("SCSI command failed\n");
US_EXIT;
/* command failed */
return USB_STOR_TRANSPORT_FAILED;
case US_BULK_STAT_PHASE:
US_ERR("SCSI command phase error\n");
US_EXIT;
/* phase error -- note that a transport reset will be
* invoked by the invoke_transport() function
*/
return USB_STOR_TRANSPORT_ERROR;
default:
US_ERR("SCSI command status reserved\n");
US_EXIT;
break;
}
US_EXIT;
/* we should never get here, but if we do, we're in trouble */
return USB_STOR_TRANSPORT_ERROR;
}
/***********************************************************************
* Reset routines
***********************************************************************/
/* This is the common part of the device reset code.
*
* It's handy that every transport mechanism uses the control endpoint for
* resets.
*
* Basically, we send a reset with a 5-second timeout, so we don't get
* jammed attempting to do the reset.
*/
static int usb_stor_reset_common(struct us_data *us,
u8 request, u8 requesttype,
u16 value, u16 index, void *data, u16 size)
{
int result;
int result2;
if (test_bit(US_FLIDX_DISCONNECTING, &us->dflags)) {
US_ERR("No reset during disconnect\n");
return -EIO;
}
result = usb_stor_control_msg(us, us->send_ctrl_pipe,
request, requesttype, value, index, data, size,
5*SCSI_HZ);
if (result < 0) {
US_ERR("Soft reset failed: %d\n", result);
return result;
}
/* Give the device some time to recover from the reset,
* but don't delay disconnect processing. */
// wait_event_interruptible_timeout(us->delay_wait,
// test_bit(US_FLIDX_DISCONNECTING, &us->dflags),
// SCSI_HZ*6);
if (test_bit(US_FLIDX_DISCONNECTING, &us->dflags)) {
US_ERR("Reset interrupted by disconnect\n");
return -EIO;
} else {
udelay(SCSI_HZ*6);
}
US_INFO("Soft reset: clearing bulk-in endpoint halt\n");
result = usb_stor_clear_halt(us, us->recv_bulk_pipe);
US_INFO("Soft reset: clearing bulk-out endpoint halt\n");
result2 = usb_stor_clear_halt(us, us->send_bulk_pipe);
/* return a result code based on the result of the clear-halts */
if (result >= 0) {
result = result2;
}
if (result < 0) {
US_ERR("Soft reset failed\n");
} else {
US_INFO("Soft reset done\n");
}
return result;
}
#if 0
/* This issues a CB[I] Reset to the device in question
*/
#define CB_RESET_CMD_SIZE 12
int usb_stor_CB_reset(struct us_data *us)
{
memset(us->iobuf, 0xFF, CB_RESET_CMD_SIZE);
us->iobuf[0] = SEND_DIAGNOSTIC;
us->iobuf[1] = 4;
return usb_stor_reset_common(us, US_CBI_ADSC,
USB_TYPE_CLASS | USB_RECIP_INTERFACE,
0, us->ifnum, us->iobuf, CB_RESET_CMD_SIZE);
}
#endif
/* This issues a Bulk-only Reset to the device in question, including
* clearing the subsequent endpoint halts that may occur.
*/
int usb_stor_Bulk_reset(struct us_data *us)
{
return usb_stor_reset_common(us, US_BULK_RESET_REQUEST,
USB_TYPE_CLASS | USB_RECIP_INTERFACE,
0, us->ifnum, NULL, 0);
}
/* Issue a USB port reset to the device. The caller must not hold
* us->dev_mutex.
*/
int usb_stor_port_reset(struct us_data *us)
{
int result;
/*for these devices we must use the class specific method */
if (us->pusb_dev->quirks & USB_QUIRK_RESET) // The device can not be reset
return -EPERM;
#if 0
result = usb_lock_device_for_reset(us->pusb_dev, us->pusb_intf);
if (result < 0)
US_INFO("unable to lock device for reset: %d\n",
result);
else {
/* Were we disconnected while waiting for the lock? */
if (test_bit(US_FLIDX_DISCONNECTING, &us->dflags)) {
result = -EIO;
USB_US_PRINTF("No reset during disconnect\n");
} else {
result = usb_reset_device(us->pusb_dev);
US_INFO("usb_reset_device returns %d\n",
result);
}
usb_unlock_device(us->pusb_dev);
}
#endif
rtw_mutex_get(&us->dev_mutex);
// result = usb_reset_device(us->pusb_dev);
result = -1;
rtw_mutex_put(&us->dev_mutex);
return result;
}
#endif // CONFIG_USBH_MSC
| 2.140625 | 2 |
2024-11-18T22:49:16.770899+00:00 | 2022-02-08T18:21:30 | 36c9e6db81e308cb14169342bc4d55e6780dbf56 | {
"blob_id": "36c9e6db81e308cb14169342bc4d55e6780dbf56",
"branch_name": "refs/heads/master",
"committer_date": "2022-02-08T18:21:30",
"content_id": "8a76372245c84038b8784f6faae787caf4c166e4",
"detected_licenses": [
"MIT"
],
"directory_id": "d55fea61eff36e5145c8b060cc08c0c5eb8c20d7",
"extension": "h",
"filename": "accel.h",
"fork_events_count": 6,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 56177433,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2945,
"license": "MIT",
"license_type": "permissive",
"path": "/include/accel.h",
"provenance": "stackv2-0108.json.gz:93332",
"repo_name": "FreeRTOSHAL/fhal-driver",
"revision_date": "2022-02-08T18:21:30",
"revision_id": "7aeafca1aa7370e4d521ca76a2cd8f71f70fa51e",
"snapshot_id": "2afc7b04f68aa60881d5ef857037cd078cfd3ef3",
"src_encoding": "UTF-8",
"star_events_count": 9,
"url": "https://raw.githubusercontent.com/FreeRTOSHAL/fhal-driver/7aeafca1aa7370e4d521ca76a2cd8f71f70fa51e/include/accel.h",
"visit_date": "2022-04-03T13:02:17.154712"
} | stackv2 | /* SPDX-License-Identifier: MIT */
/*
* Author: Andreas Werner <kernel@andy89.org>
* Date: 2016
*/
#ifndef ACCEL_H_
#define ACCEL_H_
#include <stdint.h>
#include <stdbool.h>
#include <system.h>
#include <FreeRTOS.h>
#include <semphr.h>
#include <hal.h>
#include <vec.h>
/**
* \defgroup ACCEL Accelerator Subsystem
* \ingroup HAL
* \code
* #include <accel.h>
* \endcode
*
* This is the Accelerator Subsystem.
* \{
*/
/**
* Private Structure of Accelerator driver
*/
struct accel;
#ifdef CONFIG_ACCEL_MULTI
/**
* Function of Accelerator driver in Multi Driver implementation mode
*/
struct accel_ops {
struct accel *(*accel_init)(uint32_t index);
int32_t (*accel_deinit)(struct accel *accel);
int32_t (*accel_get)(struct accel *accel, struct vector *vector, TickType_t waittime);
int32_t (*accel_getISR)(struct accel *accel, struct vector *vector);
};
#endif
/**
* Generic Accelerator Interface
*/
struct accel_generic {
/**
* true = is init
* false = is not init
*/
bool init;
#ifdef CONFIG_INSTANCE_NAME
/**
* Name of Driver Instance for Debugging
*/
const char *name;
#endif
#ifdef CONFIG_ACCEL_THREAD_SAFE
/**
* Mutex
*/
OS_DEFINE_MUTEX_RECURSIVE(lock);
#endif
#ifdef CONFIG_ACCEL_MULTI
/**
* Ops of driver in Multi mode
*/
const struct accel_ops *ops;
#endif
};
#ifndef CONFIG_ACCEL_MULTI
/**
* Init Accelerator
* \param index Index of Accelerator
* \return Accelerator Instance or NULL on error
*/
struct accel *accel_init(uint32_t index);
/**
* Deinit Accelerator
* \param accel Accelerator Instance
* \return -1 on error 0 on ok
*/
int32_t accel_deinit(struct accel *accel);
/**
* Get Accelerator Value
* \param accel Accelerator Instance
* \param vector Values
* \param waittime max waittime in mutex or isr lock see xSemaphoreTake()
* \return -1 on error 0 on ok
*/
int32_t accel_get(struct accel *accel, struct vector *vector, TickType_t waittime);
/**
* Get Accelerator Value in Interrupt Service Routine
* \param accel Accelerator Instance
* \param vector Values
* \return -1 on error 0 on ok
*/
int32_t accel_getISR(struct accel *accel, struct vector *vector);
#else
inline struct accel *accel_init(uint32_t index) {
HAL_DEFINE_GLOBAL_ARRAY(accel);
struct accel_generic *a = (struct accel_generic *) HAL_GET_DEV(accel, index);
if (a == NULL) {
return NULL;
}
return a->ops->accel_init(index);
}
inline int32_t accel_deinit(struct accel *accel) {
struct accel_generic *a = (struct accel_generic *) accel;
return a->ops->accel_deinit(accel);
}
inline int32_t accel_get(struct accel *accel, struct vector *vector, TickType_t waittime) {
struct accel_generic *a = (struct accel_generic *) accel;
return a->ops->accel_get(accel, vector, waittime);
}
inline int32_t accel_getISR(struct accel *accel, struct vector *vector) {
struct accel_generic *a = (struct accel_generic *) accel;
return a->ops->accel_getISR(accel, vector);
}
#endif
/**\}*/
#endif
| 2.75 | 3 |
2024-11-18T22:49:16.960733+00:00 | 2020-12-06T06:09:24 | 78008b843f945aeb51341890161576747ae571c0 | {
"blob_id": "78008b843f945aeb51341890161576747ae571c0",
"branch_name": "refs/heads/master",
"committer_date": "2020-12-06T06:09:24",
"content_id": "a18ac5dd98a8dd3752eef8fab4bcd5ba7ea27056",
"detected_licenses": [
"MIT"
],
"directory_id": "22c521bf8db556e8fd51cccdd3eee5385321d8a6",
"extension": "c",
"filename": "processcount.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 296794604,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 479,
"license": "MIT",
"license_type": "permissive",
"path": "/fork_3/processcount.c",
"provenance": "stackv2-0108.json.gz:93591",
"repo_name": "PaletiKrishnasai/Operating_Systems",
"revision_date": "2020-12-06T06:09:24",
"revision_id": "e343b1407c56575046bd333d7bfd38269cf92582",
"snapshot_id": "15844db645db9362a8b1c2bf104613f1fe6c93b9",
"src_encoding": "UTF-8",
"star_events_count": 4,
"url": "https://raw.githubusercontent.com/PaletiKrishnasai/Operating_Systems/e343b1407c56575046bd333d7bfd38269cf92582/fork_3/processcount.c",
"visit_date": "2023-02-01T06:13:04.270068"
} | stackv2 | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
int main()
{
pid_t pid;
int count=0;
while(1)
{
pid = vfork();
if (pid == 0)
{
count++;
exit(0);
}
else if(pid == -1)
{
printf("Max Processes allowed :%d\n",count);
exit(-1);
}
}
return 0;
} | 2.640625 | 3 |
2024-11-18T22:49:17.052308+00:00 | 2018-01-20T14:34:02 | 54bbc4178d133e129e5824435e9f99faf6f57cda | {
"blob_id": "54bbc4178d133e129e5824435e9f99faf6f57cda",
"branch_name": "refs/heads/master",
"committer_date": "2018-01-20T14:34:02",
"content_id": "4c356334a78475b5b287e4ffb8db1e6d1bf2d1f2",
"detected_licenses": [
"MIT"
],
"directory_id": "cc5817996c05195db3c3819bb7590228fea3548d",
"extension": "c",
"filename": "objc_core.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 117515594,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1788,
"license": "MIT",
"license_type": "permissive",
"path": "/Sources/objc_core.c",
"provenance": "stackv2-0108.json.gz:93721",
"repo_name": "showxu/kvo",
"revision_date": "2018-01-20T14:34:02",
"revision_id": "79d76059018ce3ceafcebe819558b73a3932b821",
"snapshot_id": "73db44feb494299ea1fd945bc0608a43a0a59037",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/showxu/kvo/79d76059018ce3ceafcebe819558b73a3932b821/Sources/objc_core.c",
"visit_date": "2022-05-31T00:23:51.400123"
} | stackv2 | //
// objc.c
// kvo
//
//
#include "objc_core.h"
#include "stub.h"
#include <stdlib.h>
struct objc_super object_getSuper(id object) {
__auto_type cls = class_getSuperclass(object_getClass(object));
return (struct objc_super) {
.receiver = object,
#if !defined(__cplusplus) && !__OBJC2__
.class = cls
#else
.super_class = cls
#endif
/* super_class is the first class to search */
};
}
Class _Nullable
objc_createObservableClass(Class _Nonnull super, const char * _Nonnull name,
size_t extraBytes) {
// objc_duplicateClass(Class _Nonnull __unsafe_unretained original, const char * _Nonnull name, size_t extraBytes)
__auto_type observable = objc_getClass(name);
if (observable) return observable;
const __auto_type sel = sel_getUid("class");
observable = objc_allocateClassPair(super, name, 0);
__auto_type method = class_getClassMethod(super, sel);
if (observable != nil && method != nil) {
class_addMethod(object_getClass((id)observable),
sel,
(IMP)_class_impl_stub,
method_getTypeEncoding(method));
objc_registerClassPair(observable);
return observable;
}
return nil;
}
bool class_contains(Class class, SEL name) __attribute__((overloadable)) {
__auto_type count = (unsigned int)0;
__auto_type flag = false;
const __auto_type list = class_copyMethodList(class, &count);
if (!list) return flag;
for (__auto_type i = 0; i < count; i+= 1) {
const __auto_type sel = method_getName(list[i]);
if (sel_isEqual(sel, name)) {
flag = true;
goto cleanup;
}
}
cleanup:
free(list);
return flag;
}
| 2.03125 | 2 |
2024-11-18T22:49:17.183112+00:00 | 2022-10-24T21:59:50 | 1e12b7dc6c7f0efc1f7e4541b40ddb96eac796fe | {
"blob_id": "1e12b7dc6c7f0efc1f7e4541b40ddb96eac796fe",
"branch_name": "refs/heads/master",
"committer_date": "2022-10-24T21:59:50",
"content_id": "0bb23a012da654c87e802c6e4615ea8c13a562b4",
"detected_licenses": [
"Apache-2.0",
"BSD-3-Clause"
],
"directory_id": "5c470d41aaed95b5157808023b9de91e5e57790a",
"extension": "c",
"filename": "tcp_unix.c",
"fork_events_count": 4,
"gha_created_at": "2016-03-01T19:32:36",
"gha_event_created_at": "2022-10-24T21:59:51",
"gha_language": "C",
"gha_license_id": "Apache-2.0",
"github_id": 52904010,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 33913,
"license": "Apache-2.0,BSD-3-Clause",
"license_type": "permissive",
"path": "/src/osdep/unix/tcp_unix.c",
"provenance": "stackv2-0108.json.gz:93850",
"repo_name": "nkhorman/panda-imap",
"revision_date": "2022-10-24T21:59:50",
"revision_id": "01eaaa96c85c5791d5cffdf20c360b329bc44d88",
"snapshot_id": "d97687c6e7e51108baf058694b38787074c43e80",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/nkhorman/panda-imap/01eaaa96c85c5791d5cffdf20c360b329bc44d88/src/osdep/unix/tcp_unix.c",
"visit_date": "2022-10-28T16:28:00.494343"
} | stackv2 | /* ========================================================================
* Copyright 2008-2011 Mark Crispin
* ========================================================================
*/
/*
* Program: UNIX TCP/IP routines
*
* Author: Mark Crispin
*
* Date: 1 August 1988
* Last Edited: 29 August 2011
*
* Previous versions of this file were
*
* Copyright 1988-2008 University of Washington
*
* 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
*
*/
#include "ip_unix.c"
#undef write /* don't use redefined write() */
#ifndef NI_MAXHOST
#define NI_MAXHOST 1025
#endif
static tcptimeout_t tmoh = NIL; /* TCP timeout handler routine */
static long ttmo_open = 0; /* TCP timeouts, in seconds */
static long ttmo_read = 0;
static long ttmo_write = 0;
static long rshtimeout = 15; /* rsh timeout */
static char *rshcommand = NIL; /* rsh command */
static char *rshpath = NIL; /* rsh path */
static long sshtimeout = 15; /* ssh timeout */
static char *sshcommand = NIL; /* ssh command */
static char *sshpath = NIL; /* ssh path */
static long allowreversedns = T;/* allow reverse DNS lookup */
static long tcpdebug = NIL; /* extra TCP debugging telemetry */
static char *myClientAddr = NIL;/* client IP address */
static char *myClientHost = NIL;/* client DNS name */
static long myClientPort = -1; /* client port number */
static char *myServerAddr = NIL;/* server IP address */
static char *myServerHost = NIL;/* server DNS name */
static long myServerPort = -1; /* server port number */
extern long maxposint; /* get this from write.c */
/* Local function prototypes */
int tcp_socket_open (int family,void *adr,size_t adrlen,unsigned short port,
char *tmp,int *ctr,char *hst);
static char *tcp_getline_work (TCPSTREAM *stream,unsigned long *size,
long *contd);
long tcp_abort (TCPSTREAM *stream);
char *tcp_name (struct sockaddr *sadr,long flag);
char *tcp_name_valid (char *s);
/* TCP/IP manipulate parameters
* Accepts: function code
* function-dependent value
* Returns: function-dependent return value
*/
void *tcp_parameters (long function,void *value)
{
void *ret = NIL;
switch ((int) function) {
case SET_TIMEOUT:
tmoh = (tcptimeout_t) value;
case GET_TIMEOUT:
ret = (void *) tmoh;
break;
case SET_OPENTIMEOUT:
ttmo_open = (long) value;
case GET_OPENTIMEOUT:
ret = (void *) ttmo_open;
break;
case SET_READTIMEOUT:
ttmo_read = (long) value;
case GET_READTIMEOUT:
ret = (void *) ttmo_read;
break;
case SET_WRITETIMEOUT:
ttmo_write = (long) value;
case GET_WRITETIMEOUT:
ret = (void *) ttmo_write;
break;
case SET_ALLOWREVERSEDNS:
allowreversedns = (long) value;
case GET_ALLOWREVERSEDNS:
ret = (void *) allowreversedns;
break;
case SET_TCPDEBUG:
tcpdebug = (long) value;
case GET_TCPDEBUG:
ret = (void *) tcpdebug;
break;
case SET_RSHTIMEOUT:
rshtimeout = (long) value;
case GET_RSHTIMEOUT:
ret = (void *) rshtimeout;
break;
case SET_RSHCOMMAND:
if (rshcommand) fs_give ((void **) &rshcommand);
rshcommand = cpystr ((char *) value);
case GET_RSHCOMMAND:
ret = (void *) rshcommand;
break;
case SET_RSHPATH:
if (rshpath) fs_give ((void **) &rshpath);
rshpath = cpystr ((char *) value);
case GET_RSHPATH:
ret = (void *) rshpath;
break;
case SET_SSHTIMEOUT:
sshtimeout = (long) value;
case GET_SSHTIMEOUT:
ret = (void *) sshtimeout;
break;
case SET_SSHCOMMAND:
if (sshcommand) fs_give ((void **) &sshcommand);
sshcommand = cpystr ((char *) value);
case GET_SSHCOMMAND:
ret = (void *) sshcommand;
break;
case SET_SSHPATH:
if (sshpath) fs_give ((void **) &sshpath);
sshpath = cpystr ((char *) value);
case GET_SSHPATH:
ret = (void *) sshpath;
break;
}
return ret;
}
/* TCP/IP open
* Accepts: host name
* contact service name
* contact port number and optional silent flag
* Returns: TCP/IP stream if success else NIL
*/
TCPSTREAM *tcp_open (char *host,char *service,unsigned long port)
{
TCPSTREAM *stream = NIL;
int family;
int sock = -1;
int ctr = 0;
int silent = (port & NET_SILENT) ? T : NIL;
int *ctrp = (port & NET_NOOPENTIMEOUT) ? NIL : &ctr;
char *s,tmp[MAILTMPLEN];
char *hostname = NIL;
void *adr;
size_t adrlen;
void *cleanup = NIL;
struct servent *sv = NIL;
blocknotify_t bn = (blocknotify_t) mail_parameters (NIL,GET_BLOCKNOTIFY,NIL);
void *data,*next;
port &= 0xffff; /* erase flags */
/* lookup service */
if (service && (sv = getservbyname (service,"tcp")))
port = ntohs (sv->s_port);
/* The domain literal form is used (rather than simply the dotted decimal
as with other Unix programs) because it has to be a valid "host name"
in mailsystem terminology. */
/* look like domain literal? */
if (host[0] == '[' && host[(strlen (host))-1] == ']') {
strcpy (tmp,host+1); /* yes, copy number part */
tmp[(strlen (tmp))-1] = '\0';
if (adr = ip_stringtoaddr (tmp,&adrlen,&family)) {
(*bn) (BLOCK_TCPOPEN,NIL);
/* get an open socket for this system */
sock = tcp_socket_open (family,adr,adrlen,port,tmp,ctrp,
hostname = cpystr(host));
(*bn) (BLOCK_NONE,NIL);
fs_give ((void **) &adr);
}
else sprintf (tmp,"Bad format domain-literal: %.80s",host);
}
else { /* lookup host name */
if (tcpdebug) {
sprintf (tmp,"DNS resolution %.80s",host);
mm_log (tmp,TCPDEBUG);
}
(*bn) (BLOCK_DNSLOOKUP,NIL);/* quell alarms */
data = (*bn) (BLOCK_SENSITIVE,NIL);
if (!(s = ip_nametoaddr (host,&adrlen,&family,&hostname,&next,&cleanup)))
sprintf (tmp,"No such host as %.80s",host);
(*bn) (BLOCK_NONSENSITIVE,data);
(*bn) (BLOCK_NONE,NIL);
if (s) { /* DNS resolution won? */
if (tcpdebug) mm_log ("DNS resolution done",TCPDEBUG);
do {
(*bn) (BLOCK_TCPOPEN,NIL);
if (((sock = tcp_socket_open (family,s,adrlen,port,tmp,ctrp,
hostname)) < 0) &&
(s = ip_nametoaddr (NIL,&adrlen,&family,&hostname,&next,
&cleanup)) && !silent)
mm_log (tmp,WARN);
(*bn) (BLOCK_NONE,NIL);
} while ((sock < 0) && s);/* repeat until success or no more addreses */
}
ip_nametoaddr (NIL,NIL,NIL,NIL,NIL,&cleanup);
}
if (sock < 0) { /* lost? */
if (!silent) mm_log (tmp,ERROR);
if (hostname) fs_give ((void **) &hostname);
}
else { /* won */
stream = (TCPSTREAM *) memset (fs_get (sizeof (TCPSTREAM)),0,
sizeof (TCPSTREAM));
stream->port = port; /* port number */
/* init sockets */
stream->tcpsi = stream->tcpso = sock;
/* stash in the snuck-in byte */
if (stream->ictr = ctr) *(stream->iptr = stream->ibuf) = tmp[0];
stream->host = hostname; /* copy official host name */
if (tcpdebug) mm_log ("Stream open and ready for read",TCPDEBUG);
}
return stream; /* return success */
}
/* Open a TCP socket
* Accepts: protocol family
* address to connect to
* address length
* port
* scratch buffer
* pointer to "first byte read in" storage or NIL
* host name for error message
* Returns: socket if success, else -1 with error string in scratch buffer
*/
int tcp_socket_open (int family,void *adr,size_t adrlen,unsigned short port,
char *tmp,int *ctr,char *hst)
{
int i,ti,sock,flgs;
size_t len;
time_t now;
fd_set rfds,wfds,efds;
char buf[NI_MAXHOST];
struct timeval tmo;
struct sockaddr *sadr = ip_sockaddr (family,adr,adrlen,port,&len);
blocknotify_t bn = (blocknotify_t) mail_parameters (NIL,GET_BLOCKNOTIFY,NIL);
/* fetid Solaris */
void *data = (*bn) (BLOCK_SENSITIVE,NIL);
sprintf (tmp,"Trying IP address [%s]",ip_sockaddrtostring (sadr,buf));
mm_log (tmp,NIL);
/* make a socket */
if ((sock = socket (sadr->sa_family,SOCK_STREAM,0)) < 0) {
sprintf (tmp,"Unable to create TCP socket: %s",strerror (errno));
(*bn) (BLOCK_NONSENSITIVE,data);
}
else if (sock >= FD_SETSIZE) {/* unselectable sockets are useless */
sprintf (tmp,"Unable to create selectable TCP socket (%d >= %d)",
sock,FD_SETSIZE);
(*bn) (BLOCK_NONSENSITIVE,data);
close (sock);
sock = -1;
errno = EMFILE;
}
else { /* get current socket flags */
flgs = fcntl (sock,F_GETFL,0);
/* set non-blocking if want open timeout */
if (ctr) fcntl (sock,F_SETFL,flgs | FNDELAY);
/* open connection */
while ((i = connect (sock,sadr,len)) < 0 && (errno == EINTR));
(*bn) (BLOCK_NONSENSITIVE,data);
if (i < 0) switch (errno) { /* failed? */
case EAGAIN: /* DG brain damage */
case EINPROGRESS: /* what we expect to happen */
case EALREADY: /* or another form of it */
case EISCONN: /* restart after interrupt? */
case EADDRINUSE: /* restart after interrupt? */
break; /* well, not really, it was interrupted */
default:
sprintf (tmp,"Can't connect to %.80s,%u: %s",hst,(unsigned int) port,
strerror (errno));
close (sock); /* flush socket */
sock = -1;
}
if ((sock >= 0) && ctr) { /* want open timeout? */
now = time (0); /* open timeout */
ti = ttmo_open ? now + ttmo_open : 0;
tmo.tv_usec = 0;
FD_ZERO (&rfds); /* initialize selection vector */
FD_ZERO (&wfds);
FD_ZERO (&efds); /* handle errors too */
FD_SET (sock,&rfds); /* block for readable, writeable, or error */
FD_SET (sock,&wfds);
FD_SET (sock,&efds);
do { /* block under timeout */
tmo.tv_sec = ti ? ti - now : 0;
i = select (sock+1,&rfds,&wfds,&efds,ti ? &tmo : NIL);
now = time (0); /* fake timeout if interrupt & time expired */
if ((i < 0) && (errno == EINTR) && ti && (ti <= now)) i = 0;
} while ((i < 0) && (errno == EINTR));
if (i > 0) { /* success, make sure really connected */
/* restore blocking status */
fcntl (sock,F_SETFL,flgs);
/* This used to be a zero-byte read(), but that crashes Solaris */
/* get socket status */
if(FD_ISSET(sock,&rfds))
while (((i = *ctr = read (sock,tmp,1)) < 0) && (errno == EINTR));
}
if (i <= 0) { /* timeout or error? */
i = i ? errno : ETIMEDOUT;/* determine error code */
close (sock); /* flush socket */
sock = -1;
errno = i; /* return error code */
sprintf (tmp,"Connection failed to %.80s,%lu: %s",hst,
(unsigned long) port,strerror (errno));
}
}
}
fs_give ((void **) &sadr);
return sock; /* return the socket */
}
/* TCP/IP authenticated open
* Accepts: host name
* service name
* returned user name buffer
* Returns: TCP/IP stream if success else NIL
*/
#define MAXARGV 20
TCPSTREAM *tcp_aopen (NETMBX *mb,char *service,char *usrbuf)
{
TCPSTREAM *stream = NIL;
void *adr;
char host[MAILTMPLEN],tmp[MAILTMPLEN],*path,*argv[MAXARGV+1],*r;
int i,ti,pipei[2],pipeo[2];
size_t len;
time_t now;
struct timeval tmo;
fd_set fds,efds;
blocknotify_t bn = (blocknotify_t) mail_parameters (NIL,GET_BLOCKNOTIFY,NIL);
#ifdef SSHPATH /* ssh path defined yet? */
if (!sshpath) sshpath = cpystr (SSHPATH);
#endif
#ifdef RSHPATH /* rsh path defined yet? */
if (!rshpath) rshpath = cpystr (RSHPATH);
#endif
if (*service == '*') { /* want ssh? */
/* return immediately if ssh disabled */
if (!(sshpath && (ti = sshtimeout))) return NIL;
/* ssh command prototype defined yet? */
if (!sshcommand) sshcommand = cpystr ("%s %s -l %s exec /etc/r%sd");
}
/* want rsh? */
else if (rshpath && (ti = rshtimeout)) {
/* rsh command prototype defined yet? */
if (!rshcommand) rshcommand = cpystr ("%s %s -l %s exec /etc/r%sd");
}
else return NIL; /* rsh disabled */
/* look like domain literal? */
if (mb->host[0] == '[' && mb->host[i = (strlen (mb->host))-1] == ']') {
strcpy (host,mb->host+1); /* yes, copy without brackets */
host[i-1] = '\0';
/* validate domain literal */
if (adr = ip_stringtoaddr (host,&len,&i)) fs_give ((void **) &adr);
else {
sprintf (tmp,"Bad format domain-literal: %.80s",host);
mm_log (tmp,ERROR);
return NIL;
}
}
else {
strcpy (host,r = tcp_canonical (mb->host));
fs_give((void **) &r);
}
if (*service == '*') /* build ssh command */
sprintf (tmp,sshcommand,sshpath,host,
mb->user[0] ? mb->user : myusername (),service + 1);
else sprintf (tmp,rshcommand,rshpath,host,
mb->user[0] ? mb->user : myusername (),service);
if (tcpdebug) {
char msg[MAILTMPLEN];
sprintf (msg,"Trying %.100s",tmp);
mm_log (msg,TCPDEBUG);
}
/* parse command into argv */
for (i = 1,path = argv[0] = strtok_r (tmp," ",&r);
(i < MAXARGV) && (argv[i] = strtok_r (NIL," ",&r)); i++);
argv[i] = NIL; /* make sure argv tied off */
/* make command pipes */
if (pipe (pipei) < 0) return NIL;
if ((pipei[0] >= FD_SETSIZE) || (pipei[1] >= FD_SETSIZE) ||
(pipe (pipeo) < 0)) {
close (pipei[0]); close (pipei[1]);
return NIL;
}
(*bn) (BLOCK_TCPOPEN,NIL); /* quell alarm up here for NeXT */
if ((pipeo[0] >= FD_SETSIZE) || (pipeo[1] >= FD_SETSIZE) ||
((i = fork ()) < 0)) { /* make inferior process */
close (pipei[0]); close (pipei[1]);
close (pipeo[0]); close (pipeo[1]);
(*bn) (BLOCK_NONE,NIL);
return NIL;
}
if (!i) { /* if child */
alarm (0); /* never have alarms in children */
if (!fork ()) { /* make grandchild so it's inherited by init */
int cf; /* don't alter parent vars in case vfork() */
int maxfd = max (20,max (max(pipei[0],pipei[1]),max(pipeo[0],pipeo[1])));
dup2 (pipei[1],1); /* parent's input is my output */
dup2 (pipei[1],2); /* parent's input is my error output too */
dup2 (pipeo[0],0); /* parent's output is my input */
/* close all unnecessary descriptors */
for (cf = 3; cf <= maxfd; cf++) close (cf);
setpgrp (0,getpid ()); /* be our own process group */
_exit (execv (path,argv));/* now run it */
}
_exit (1); /* child is done */
}
grim_pid_reap (i,NIL); /* reap child; grandchild now owned by init */
close (pipei[1]); /* close child's side of the pipes */
close (pipeo[0]);
/* create TCP/IP stream */
stream = (TCPSTREAM *) memset (fs_get (sizeof (TCPSTREAM)),0,
sizeof (TCPSTREAM));
/* copy remote host name from argument */
stream->remotehost = cpystr (stream->host = cpystr (host));
stream->tcpsi = pipei[0]; /* init sockets */
stream->tcpso = pipeo[1];
stream->ictr = 0; /* init input counter */
stream->port = 0xffffffff; /* no port number */
ti += now = time (0); /* open timeout */
tmo.tv_usec = 0; /* initialize usec timeout */
FD_ZERO (&fds); /* initialize selection vector */
FD_ZERO (&efds); /* handle errors too */
FD_SET (stream->tcpsi,&fds); /* set bit in selection vector */
FD_SET (stream->tcpsi,&efds); /* set bit in error selection vector */
FD_SET (stream->tcpso,&efds); /* set bit in error selection vector */
do { /* block under timeout */
tmo.tv_sec = ti - now;
i = select (max (stream->tcpsi,stream->tcpso)+1,&fds,NIL,&efds,&tmo);
now = time (0); /* fake timeout if interrupt & time expired */
if ((i < 0) && (errno == EINTR) && ti && (ti <= now)) i = 0;
} while ((i < 0) && (errno == EINTR));
if (i <= 0) { /* timeout or error? */
sprintf (tmp,i ? "error in %s to IMAP server" :
"%s to IMAP server timed out",(*service == '*') ? "ssh" : "rsh");
mm_log (tmp,WARN);
tcp_close (stream); /* punt stream */
stream = NIL;
}
(*bn) (BLOCK_NONE,NIL);
/* return user name */
strcpy (usrbuf,mb->user[0] ? mb->user : myusername ());
return stream; /* return success */
}
/* TCP receive line
* Accepts: TCP stream
* Returns: text line string or NIL if failure
*/
char *tcp_getline (TCPSTREAM *stream)
{
unsigned long n,contd;
char *ret = tcp_getline_work (stream,&n,&contd);
if (ret && contd) { /* got a line needing continuation? */
STRINGLIST *stl = mail_newstringlist ();
STRINGLIST *stc = stl;
do { /* collect additional lines */
stc->text.data = (unsigned char *) ret;
stc->text.size = n;
stc = stc->next = mail_newstringlist ();
ret = tcp_getline_work (stream,&n,&contd);
} while (ret && contd);
if (ret) { /* stash final part of line on list */
stc->text.data = (unsigned char *) ret;
stc->text.size = n;
/* determine how large a buffer we need */
for (n = 0, stc = stl; stc; stc = stc->next) n += stc->text.size;
ret = fs_get (n + 1); /* copy parts into buffer */
for (n = 0, stc = stl; stc; n += stc->text.size, stc = stc->next)
memcpy (ret + n,stc->text.data,stc->text.size);
ret[n] = '\0';
}
mail_free_stringlist (&stl);/* either way, done with list */
}
return ret;
}
/* TCP receive line or partial line
* Accepts: TCP stream
* pointer to return size
* pointer to return continuation flag
* Returns: text line string, size and continuation flag, or NIL if failure
*/
static char *tcp_getline_work (TCPSTREAM *stream,unsigned long *size,
long *contd)
{
unsigned long n;
char *s,*ret,c,d;
*contd = NIL; /* assume no continuation */
/* make sure have data */
if (!tcp_getdata (stream)) return NIL;
for (s = stream->iptr, n = 0, c = '\0'; stream->ictr--; n++, c = d) {
d = *stream->iptr++; /* slurp another character */
if ((c == '\015') && (d == '\012')) {
ret = (char *) fs_get (n--);
memcpy (ret,s,*size = n); /* copy into a free storage string */
ret[n] = '\0'; /* tie off string with null */
return ret;
}
}
/* copy partial string from buffer */
memcpy ((ret = (char *) fs_get (n)),s,*size = n);
/* get more data from the net */
if (!tcp_getdata (stream)) fs_give ((void **) &ret);
/* special case of newline broken by buffer */
else if ((c == '\015') && (*stream->iptr == '\012')) {
stream->iptr++; /* eat the line feed */
stream->ictr--;
ret[*size = --n] = '\0'; /* tie off string with null */
}
else *contd = LONGT; /* continuation needed */
return ret;
}
/* TCP/IP receive buffer
* Accepts: TCP/IP stream
* size in bytes
* buffer to read into
* Returns: T if success, NIL otherwise
*/
long tcp_getbuffer (TCPSTREAM *stream,unsigned long size,char *s)
{
unsigned long n;
/* make sure socket still alive */
if (stream->tcpsi < 0) return NIL;
/* can transfer bytes from buffer? */
if (n = min (size,stream->ictr)) {
memcpy (s,stream->iptr,n); /* yes, slurp as much as we can from it */
s += n; /* update pointer */
stream->iptr +=n;
size -= n; /* update # of bytes to do */
stream->ictr -=n;
}
if (size) {
int i;
fd_set fds,efds;
struct timeval tmo;
time_t t = time (0);
blocknotify_t bn=(blocknotify_t) mail_parameters (NIL,GET_BLOCKNOTIFY,NIL);
(*bn) (BLOCK_TCPREAD,NIL);
while (size > 0) { /* until request satisfied */
time_t tl = time (0);
time_t now = tl;
time_t ti = ttmo_read ? now + ttmo_read : 0;
if (tcpdebug) mm_log ("Reading TCP buffer",TCPDEBUG);
tmo.tv_usec = 0;
FD_ZERO (&fds); /* initialize selection vector */
FD_ZERO (&efds); /* handle errors too */
/* set bit in selection vectors */
FD_SET (stream->tcpsi,&fds);
FD_SET (stream->tcpsi,&efds);
errno = NIL; /* initially no error */
do { /* block under timeout */
tmo.tv_sec = ti ? ti - now : 0;
i = select (stream->tcpsi+1,&fds,NIL,&efds,ti ? &tmo : NIL);
now = time (0); /* fake timeout if interrupt & time expired */
if ((i < 0) && (errno == EINTR) && ti && (ti <= now)) i = 0;
} while ((i < 0) && (errno == EINTR));
if (i) { /* non-timeout result from select? */
if (i > 0) /* read what we can */
while (((i = read (stream->tcpsi,s,(int) min (maxposint,size))) < 0)
&& (errno == EINTR));
if (i <= 0) { /* error seen? */
if (tcpdebug) {
char tmp[MAILTMPLEN];
if (i) sprintf (s = tmp,"TCP buffer read I/O error %d",errno);
else s = "TCP buffer read end of file";
mm_log (s,TCPDEBUG);
}
return tcp_abort (stream);
}
s += i; /* success, point at new place to write */
size -= i; /* reduce byte count */
if (tcpdebug) mm_log ("Successfully read TCP buffer",TCPDEBUG);
}
/* timeout, punt unless told not to */
else if (!tmoh || !(*tmoh) (now - t,now - tl)) {
if (tcpdebug) mm_log ("TCP buffer read timeout",TCPDEBUG);
return tcp_abort (stream);
}
}
(*bn) (BLOCK_NONE,NIL);
}
*s = '\0'; /* tie off string */
return LONGT;
}
/* TCP/IP receive data
* Accepts: TCP/IP stream
* Returns: T if success, NIL otherwise
*/
long tcp_getdata (TCPSTREAM *stream)
{
int i;
fd_set fds,efds;
struct timeval tmo;
time_t t = time (0);
blocknotify_t bn = (blocknotify_t) mail_parameters (NIL,GET_BLOCKNOTIFY,NIL);
if (stream->tcpsi < 0) return NIL;
(*bn) (BLOCK_TCPREAD,NIL);
while (stream->ictr < 1) { /* if nothing in the buffer */
time_t tl = time (0); /* start of request */
time_t now = tl;
time_t ti = ttmo_read ? now + ttmo_read : 0;
if (tcpdebug) mm_log ("Reading TCP data",TCPDEBUG);
tmo.tv_usec = 0;
FD_ZERO (&fds); /* initialize selection vector */
FD_ZERO (&efds); /* handle errors too */
FD_SET (stream->tcpsi,&fds);/* set bit in selection vectors */
FD_SET (stream->tcpsi,&efds);
errno = NIL; /* initially no error */
do { /* block under timeout */
tmo.tv_sec = ti ? ti - now : 0;
i = select (stream->tcpsi+1,&fds,NIL,&efds,ti ? &tmo : NIL);
now = time (0); /* fake timeout if interrupt & time expired */
if ((i < 0) && (errno == EINTR) && ti && (ti <= now)) i = 0;
} while ((i < 0) && (errno == EINTR));
if (i) { /* non-timeout result from select? */
/* read what we can */
if (i > 0) while (((i = read (stream->tcpsi,stream->ibuf,BUFLEN)) < 0) &&
(errno == EINTR));
if (i <= 0) { /* error seen? */
if (tcpdebug) {
char *s,tmp[MAILTMPLEN];
if (i) sprintf (s = tmp,"TCP data read I/O error %d",errno);
else s = "TCP data read end of file";
mm_log (s,TCPDEBUG);
}
return tcp_abort (stream);
}
stream->ictr = i; /* success, set new count and pointer */
stream->iptr = stream->ibuf;
if (tcpdebug) mm_log ("Successfully read TCP data",TCPDEBUG);
}
/* timeout, punt unless told not to */
else if (!tmoh || !(*tmoh) (now - t,now - tl)) {
if (tcpdebug) mm_log ("TCP data read timeout",TCPDEBUG);
return tcp_abort (stream);/* error or timeout no-continue */
}
}
(*bn) (BLOCK_NONE,NIL);
return T;
}
/* TCP/IP send string as record
* Accepts: TCP/IP stream
* string pointer
* Returns: T if success else NIL
*/
long tcp_soutr (TCPSTREAM *stream,char *string)
{
return tcp_sout (stream,string,(unsigned long) strlen (string));
}
/* TCP/IP send string
* Accepts: TCP/IP stream
* string pointer
* byte count
* Returns: T if success else NIL
*/
long tcp_sout (TCPSTREAM *stream,char *string,unsigned long size)
{
int i;
fd_set fds,efds;
struct timeval tmo;
time_t t = time (0);
blocknotify_t bn = (blocknotify_t) mail_parameters (NIL,GET_BLOCKNOTIFY,NIL);
if (stream->tcpso < 0) return NIL;
(*bn) (BLOCK_TCPWRITE,NIL);
while (size > 0) { /* until request satisfied */
time_t tl = time (0); /* start of request */
time_t now = tl;
time_t ti = ttmo_write ? now + ttmo_write : 0;
if (tcpdebug) mm_log ("Writing to TCP",TCPDEBUG);
tmo.tv_usec = 0;
FD_ZERO (&fds); /* initialize selection vector */
FD_ZERO (&efds); /* handle errors too */
FD_SET (stream->tcpso,&fds);/* set bit in selection vector */
FD_SET(stream->tcpso,&efds);/* set bit in error selection vector */
errno = NIL; /* block and write */
do { /* block under timeout */
tmo.tv_sec = ti ? ti - now : 0;
i = select (stream->tcpso+1,NIL,&fds,&efds,ti ? &tmo : NIL);
now = time (0); /* fake timeout if interrupt & time expired */
if ((i < 0) && (errno == EINTR) && ti && (ti <= now)) i = 0;
} while ((i < 0) && (errno == EINTR));
if (i) { /* non-timeout result from select? */
/* write what we can */
if (i > 0) while (((i = write (stream->tcpso,string,size)) < 0) &&
(errno == EINTR));
if (i <= 0) { /* error seen? */
if (tcpdebug) {
char tmp[MAILTMPLEN];
sprintf (tmp,"TCP write I/O error %d",errno);
mm_log (tmp,TCPDEBUG);
}
return tcp_abort (stream);
}
string += i; /* how much we sent */
size -= i; /* count this size */
if (tcpdebug) mm_log ("successfully wrote to TCP",TCPDEBUG);
}
/* timeout, punt unless told not to */
else if (!tmoh || !(*tmoh) (now - t,now - tl)) {
if (tcpdebug) mm_log ("TCP write timeout",TCPDEBUG);
return tcp_abort (stream);
}
}
(*bn) (BLOCK_NONE,NIL);
return T; /* all done */
}
/* TCP/IP close
* Accepts: TCP/IP stream
*/
void tcp_close (TCPSTREAM *stream)
{
tcp_abort (stream); /* nuke the stream */
/* flush host names */
if (stream->host) fs_give ((void **) &stream->host);
if (stream->remotehost) fs_give ((void **) &stream->remotehost);
if (stream->localhost) fs_give ((void **) &stream->localhost);
fs_give ((void **) &stream); /* flush the stream */
}
/* TCP/IP abort stream
* Accepts: TCP/IP stream
* Returns: NIL always
*/
long tcp_abort (TCPSTREAM *stream)
{
blocknotify_t bn = (blocknotify_t) mail_parameters (NIL,GET_BLOCKNOTIFY,NIL);
if (stream->tcpsi >= 0) { /* no-op if no socket */
(*bn) (BLOCK_TCPCLOSE,NIL);
close (stream->tcpsi); /* nuke the socket */
if (stream->tcpsi != stream->tcpso) close (stream->tcpso);
stream->tcpsi = stream->tcpso = -1;
}
(*bn) (BLOCK_NONE,NIL);
return NIL;
}
/* TCP/IP get host name
* Accepts: TCP/IP stream
* Returns: host name for this stream
*/
char *tcp_host (TCPSTREAM *stream)
{
/* use tcp_remotehost() if want guarantees */
return stream ? stream->host : "UNKNOWN";
}
/* TCP/IP get remote host name
* Accepts: TCP/IP stream
* Returns: host name for this stream
*/
char *tcp_remotehost (TCPSTREAM *stream)
{
if (!stream->remotehost) {
size_t sadrlen;
struct sockaddr *sadr = ip_newsockaddr (&sadrlen);
stream->remotehost = /* get socket's peer name */
getpeername (stream->tcpsi,sadr,(void *) &sadrlen) ?
cpystr (stream->host) : tcp_name (sadr,NIL);
fs_give ((void **) &sadr);
}
return stream->remotehost;
}
/* TCP/IP return port for this stream
* Accepts: TCP/IP stream
* Returns: port number for this stream
*/
unsigned long tcp_port (TCPSTREAM *stream)
{
return stream->port; /* return port number */
}
/* TCP/IP get local host name
* Accepts: TCP/IP stream
* Returns: local host name
*/
char *tcp_localhost (TCPSTREAM *stream)
{
if (!stream->localhost) {
size_t sadrlen;
struct sockaddr *sadr = ip_newsockaddr (&sadrlen);
stream->localhost = /* get socket's name */
((stream->port & 0xffff000) ||
getsockname (stream->tcpsi,sadr,(void *) &sadrlen)) ?
cpystr (mylocalhost ()) : tcp_name (sadr,NIL);
fs_give ((void **) &sadr);
}
return stream->localhost; /* return local host name */
}
/* TCP/IP get client host address (server calls only)
* Returns: client host address
*/
char *tcp_clientaddr ()
{
if (!myClientAddr) {
char buf[NI_MAXHOST];
size_t sadrlen;
struct sockaddr *sadr = ip_newsockaddr (&sadrlen);
if (getpeername (0,sadr,(void *) &sadrlen))
myClientAddr = cpystr ("UNKNOWN");
else { /* get stdin's peer name */
myClientAddr = cpystr (ip_sockaddrtostring (sadr,buf));
if (myClientPort < 0) myClientPort = ip_sockaddrtoport (sadr);
}
fs_give ((void **) &sadr);
}
return myClientAddr;
}
/* TCP/IP get client host name (server calls only)
* Returns: client host name
*/
char *tcp_clienthost ()
{
if (!myClientHost) {
char buf[NI_MAXHOST];
size_t sadrlen;
struct sockaddr *sadr = ip_newsockaddr (&sadrlen);
if (getpeername (0,sadr,(void *) &sadrlen)) {
char *s,*t,*v,tmp[MAILTMPLEN];
if ((s = getenv (t = "SSH_CLIENT")) ||
(s = getenv (t = "KRB5REMOTEADDR")) ||
(s = getenv (t = "SSH2_CLIENT"))) {
if (v = strchr (s,' ')) *v = '\0';
sprintf (v = tmp,"%.80s=%.80s",t,s);
}
else v = "UNKNOWN";
myClientHost = cpystr (v);
}
else { /* get stdin's peer name */
myClientHost = tcp_name (sadr,T);
if (!myClientAddr) myClientAddr = cpystr (ip_sockaddrtostring(sadr,buf));
if (myClientPort < 0) myClientPort = ip_sockaddrtoport (sadr);
}
fs_give ((void **) &sadr);
}
return myClientHost;
}
/* TCP/IP get client port number (server calls only)
* Returns: client port number
*/
long tcp_clientport ()
{
if (!myClientHost && !myClientAddr) tcp_clientaddr ();
return myClientPort;
}
/* TCP/IP get server host address (server calls only)
* Returns: server host address
*/
char *tcp_serveraddr ()
{
if (!myServerAddr) {
char buf[NI_MAXHOST];
size_t sadrlen;
struct sockaddr *sadr = ip_newsockaddr (&sadrlen);
if (getsockname (0,sadr,(void *) &sadrlen))
myServerAddr = cpystr ("UNKNOWN");
else { /* get stdin's name */
myServerAddr = cpystr (ip_sockaddrtostring (sadr,buf));
if (myServerPort < 0) myServerPort = ip_sockaddrtoport (sadr);
}
fs_give ((void **) &sadr);
}
return myServerAddr;
}
/* TCP/IP get server host name (server calls only)
* Returns: server host name
*/
char *tcp_serverhost ()
{
if (!myServerHost) { /* once-only */
char buf[NI_MAXHOST];
size_t sadrlen;
struct sockaddr *sadr = ip_newsockaddr (&sadrlen);
/* get stdin's name */
if (getsockname (0,sadr,(void *) &sadrlen))
myServerHost = cpystr (mylocalhost ());
else { /* get stdin's name */
myServerHost = tcp_name (sadr,NIL);
if (!myServerAddr) myServerAddr = cpystr (ip_sockaddrtostring(sadr,buf));
if (myServerPort < 0) myServerPort = ip_sockaddrtoport (sadr);
}
fs_give ((void **) &sadr);
}
return myServerHost;
}
/* TCP/IP get server port number (server calls only)
* Returns: server port number
*/
long tcp_serverport ()
{
if (!myServerHost && !myServerAddr) tcp_serveraddr ();
return myServerPort;
}
/* TCP/IP return canonical form of host name
* Accepts: host name
* Returns: canonical form of host name
*/
char *tcp_canonical (char *name)
{
char *ret,host[MAILTMPLEN];
blocknotify_t bn = (blocknotify_t) mail_parameters (NIL,GET_BLOCKNOTIFY,NIL);
void *data;
/* look like domain literal? */
if (name[0] == '[' && name[strlen (name) - 1] == ']') return name;
(*bn) (BLOCK_DNSLOOKUP,NIL); /* quell alarms */
data = (*bn) (BLOCK_SENSITIVE,NIL);
if (tcpdebug) {
sprintf (host,"DNS canonicalization %.80s",name);
mm_log (host,TCPDEBUG);
}
/* get canonical name */
if (!ip_nametoaddr (name,NIL,NIL,&ret,NIL,NIL)) ret = cpystr (name);
(*bn) (BLOCK_NONSENSITIVE,data);
(*bn) (BLOCK_NONE,NIL); /* alarms OK now */
if (tcpdebug) mm_log ("DNS canonicalization done",TCPDEBUG);
return ret;
}
/* TCP/IP return name from socket
* Accepts: socket
* verbose flag
* Returns: cpystr name
*/
char *tcp_name (struct sockaddr *sadr,long flag)
{
char *ret,*t,adr[MAILTMPLEN],tmp[MAILTMPLEN],buf[NI_MAXHOST];
sprintf (ret = adr,"[%.80s]",ip_sockaddrtostring (sadr,buf));
if (allowreversedns) {
blocknotify_t bn = (blocknotify_t)mail_parameters(NIL,GET_BLOCKNOTIFY,NIL);
void *data;
if (tcpdebug) {
sprintf (tmp,"Reverse DNS resolution %s",adr);
mm_log (tmp,TCPDEBUG);
}
(*bn) (BLOCK_DNSLOOKUP,NIL);/* quell alarms */
data = (*bn) (BLOCK_SENSITIVE,NIL);
/* translate address to name */
if (t = tcp_name_valid (ip_sockaddrtoname (sadr,buf))) {
/* produce verbose form if needed */
if (flag) sprintf (ret = tmp,"%s %s",t,adr);
else ret = t;
}
(*bn) (BLOCK_NONSENSITIVE,data);
(*bn) (BLOCK_NONE,NIL); /* alarms OK now */
if (tcpdebug) mm_log ("Reverse DNS resolution done",TCPDEBUG);
}
return cpystr (ret);
}
/* TCP/IP validate name
* Accepts: domain name
* Returns: name if valid, NIL otherwise
*/
char *tcp_name_valid (char *s)
{
int c;
char *ret,*tail;
/* must be non-empty and not too long */
if ((ret = (s && *s) ? s : NIL) && (tail = ret + NETMAXHOST)) {
/* must be alnum, dot, or hyphen */
while ((c = *s++) && (s <= tail) &&
(((c >= 'A') && (c <= 'Z')) || ((c >= 'a') && (c <= 'z')) ||
((c >= '0') && (c <= '9')) || (c == '-') || (c == '.')));
if (c) ret = NIL;
}
return ret;
}
/* TCP/IP check if client is given host name
* Accepts: candidate host name
* Returns: T if match, NIL otherwise
*/
long tcp_isclienthost (char *host)
{
int family;
size_t adrlen,sadrlen,len;
void *adr,*next;
char buf[NI_MAXHOST];
struct sockaddr *sadr;
void *cleanup = NIL;
long ret = NIL;
/* make sure that myClientAddr is set */
if (tcp_clienthost () && myClientAddr) {
/* get sockaddr of client */
for (adr = ip_nametoaddr (host,&adrlen,&family,NIL,&next,&cleanup);
adr && !ret;
adr = ip_nametoaddr (NIL,&adrlen,&family,NIL,&next,&cleanup)) {
/* build sockaddr of given address */
sadr = ip_sockaddr (family,adr,adrlen,1,&len);
if (!strcmp (myClientAddr,ip_sockaddrtostring (sadr,buf))) ret = LONGT;
fs_give ((void **) &sadr); /* done with client sockaddr */
}
ip_nametoaddr (NIL,NIL,NIL,NIL,NIL,&cleanup);
}
return ret;
}
/* Following statement must be at end of this module */
#undef fork /* undo any use of vfork() */
| 2.140625 | 2 |
2024-11-18T22:49:17.289751+00:00 | 2021-01-13T04:42:03 | 19c5d6a3b94129595a1e34d30783c8f56f21748d | {
"blob_id": "19c5d6a3b94129595a1e34d30783c8f56f21748d",
"branch_name": "refs/heads/master",
"committer_date": "2021-01-13T04:42:03",
"content_id": "dcab22cc242513dfdaed8a03a0a67fea95bf2f33",
"detected_licenses": [
"MIT"
],
"directory_id": "a9f6a3dfc2fb54547c5451d5c1380842aff45311",
"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": 26470544,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3317,
"license": "MIT",
"license_type": "permissive",
"path": "/AnimatronicFaceBoard/SlaveADC/main.c",
"provenance": "stackv2-0108.json.gz:93978",
"repo_name": "CmdrZin/chips_avr_examples",
"revision_date": "2021-01-13T04:42:03",
"revision_id": "d4b57a8efd6aff2a678adef4fd405e6359e891e6",
"snapshot_id": "e7b5403db501456f26f88909bc27d40ae20ba831",
"src_encoding": "UTF-8",
"star_events_count": 5,
"url": "https://raw.githubusercontent.com/CmdrZin/chips_avr_examples/d4b57a8efd6aff2a678adef4fd405e6359e891e6/AnimatronicFaceBoard/SlaveADC/main.c",
"visit_date": "2021-08-06T03:38:08.789930"
} | stackv2 | /*
* The MIT License (MIT)
*
* Copyright (c) 2017 Nels D. "Chip" Pearson (aka CmdrZin)
*
* 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.
*
* SlaveADC.c
*
* Created: 9/07/2017 0.01 ndp
* Author : Chip
*
* Target: ATmega164P, 20MHz
*
* This is the main() file for the SlaveADC board.
* It provides 8 channels of 10 bit ADC, a status LED, and two five pin I/O ports.
* Optional Audio and Serial hardware can be added.
*/
#include <avr/io.h>
#include <avr/interrupt.h>
#include <stdbool.h>
#include "sysTimer.h"
#include "mod_led.h"
#include "adc_support.h"
#include "twiSlave.h"
#include "core_functions.h"
#define SLAVE_ADRS 0x32
void mTest01();
void mTest02();
/*
* main()
*
* Each service manages their own time slice.
*
*/
int main(void)
{
uint8_t data;
st_init_tmr0();
mod_led_init();
adc_support_init();
twiSlaveInit(SLAVE_ADRS);
sei(); // Enable global interrupts.
twiSlaveEnable();
while(1)
{
adc_support_service(); // sample a channel each ms.
if( twiDataInReceiveBuffer() )
{
// NOTE: Master should wait at least 1ms after requesting data before reading it. No clock stretching.
data = twiReceiveByte();
switch(data)
{
// Read an ADC channel
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
twiClearOutput();
twiTransmitByte(adc_support_readChan(data));
break;
// Read ALL channels
case 8:
twiClearOutput();
for(int i=0; i<8; i++) {
twiTransmitByte(adc_support_readChan(i));
}
break;
case 0xF8:
core_get_build_date();
break;
case 0xF9:
core_get_build_time();
break;
case 0xFA:
core_get_version();
break;
default:
break;
}
}
// mTest01();
mTest02();
}
}
/*
* Simple LED test
*/
void mTest01()
{
static uint32_t lastTime = 0L;
static bool tFlag = true;
if((st_millis() - lastTime) > 100) {
lastTime = st_millis();
if(tFlag) {
mod_led_on();
tFlag = false;
} else {
mod_led_off();
tFlag = true;
}
}
}
/*
* ADC Read Pot test
* Light LED if any pot > 0x80;
*/
void mTest02()
{
mod_led_off();
for(int i=0; i<8; i++)
{
if(adc_support_readChan(i) > 0x80)
{
mod_led_on();
}
}
}
| 2.390625 | 2 |
2024-11-18T22:49:17.644967+00:00 | 2020-06-13T08:48:41 | 74a43ce6daac77ab9b123191a14f1ba64754d49d | {
"blob_id": "74a43ce6daac77ab9b123191a14f1ba64754d49d",
"branch_name": "refs/heads/master",
"committer_date": "2020-06-13T08:48:41",
"content_id": "6969deb6b6d2538b9b2ee2914fcc41144b5c30d4",
"detected_licenses": [
"MIT"
],
"directory_id": "da0bbfa2d95cfa3ab6e80dd01d25984d209ceab0",
"extension": "c",
"filename": "splitter.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 247510256,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4062,
"license": "MIT",
"license_type": "permissive",
"path": "/src/splitter.c",
"provenance": "stackv2-0108.json.gz:94496",
"repo_name": "AlessandroBorsoi/reti1",
"revision_date": "2020-06-13T08:48:41",
"revision_id": "4aa8b7f1c8cc7574a24724d6b9661bd113476ba7",
"snapshot_id": "2bec13ad77274f0a456425e084e7c7a97e7a880f",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/AlessandroBorsoi/reti1/4aa8b7f1c8cc7574a24724d6b9661bd113476ba7/src/splitter.c",
"visit_date": "2022-11-13T09:18:18.209137"
} | stackv2 | #include "splitter_private.h"
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <inttypes.h>
static upo_protocol_splitter_t create(char *input, long file_size);
static bool is_valid_input(const char *input);
static int get_number_count(const char *input, long file_size);
static size_t numbers_to_send(upo_protocol_splitter_t splitter, size_t output_size);
static int digits(uint64_t n);
upo_protocol_splitter_t upo_protocol_splitter_create(char *file_path)
{
FILE *file = fopen(file_path, "r");
if (file == NULL)
return NULL;
fseek(file, 0, SEEK_END);
long file_size = ftell(file);
fseek(file, 0, SEEK_SET);
char *input = malloc(file_size + 1);
fread(input, 1, file_size, file);
fclose(file);
input[file_size] = 0;
upo_protocol_splitter_t splitter = create(input, file_size + 1);
free(input);
return splitter;
}
void upo_protocol_splitter_destroy(upo_protocol_splitter_t *splitter)
{
if (splitter != NULL && *splitter != NULL)
{
(*splitter)->size = 0;
(*splitter)->current = 0;
if (upo_protocol_splitter_is_valid(*splitter))
free((*splitter)->numbers);
free(*splitter);
(*splitter) = NULL;
}
}
bool upo_protocol_splitter_is_valid(upo_protocol_splitter_t splitter)
{
if (splitter != NULL)
return splitter->numbers != NULL;
return false;
}
size_t upo_protocol_splitter_next(upo_protocol_splitter_t splitter, char *output, size_t output_size)
{
memset(output, '\0', output_size);
size_t to_send = numbers_to_send(splitter, output_size);
size_t index = 0;
if (to_send == 0)
{
strcpy(output, "0\n");
return 0;
}
index += sprintf(&output[index], "%zu ", to_send);
size_t start = splitter->current;
size_t end = start + to_send;
for (size_t i = start; i < end; i++)
if (i == end - 1)
index += sprintf(&output[index], "%" PRIu64 "\n", splitter->numbers[i]);
else
index += sprintf(&output[index], "%" PRIu64 " ", splitter->numbers[i]);
splitter->current = end;
return to_send;
}
upo_protocol_splitter_t create(char *input, long file_size)
{
upo_protocol_splitter_t splitter = malloc(sizeof(struct upo_protocol_splitter_s));
splitter->numbers = NULL;
splitter->size = 0;
splitter->current = 0;
if (is_valid_input(input))
{
int count = get_number_count(input, file_size);
splitter->numbers = malloc(count * sizeof(uint64_t));
splitter->size = count;
int i = 0;
char *delim = " \n";
char *token = strtok(input, delim);
while (token != NULL)
{
splitter->numbers[i] = strtoul(token, NULL, 10);
token = strtok(NULL, delim);
i++;
}
}
return splitter;
}
size_t numbers_to_send(const upo_protocol_splitter_t splitter, const size_t output_size)
{
size_t to_send = 0;
size_t buffer_size = 0;
size_t i = splitter->current;
while (i < splitter->size)
{
if (buffer_size + digits(to_send) + 1 == output_size)
return to_send;
if (buffer_size + digits(to_send) + 1 > output_size)
return to_send - 1;
buffer_size += digits(splitter->numbers[i]) + 1; // +1 for the space
i++;
to_send++;
}
return buffer_size + digits(to_send) + 1 > output_size ? to_send - 1 : to_send;
}
int get_number_count(const char *input, long file_size)
{
int count = 0;
for (int i = 0; i < file_size; i++)
{
if (isdigit(input[i]))
{
count++;
while (isdigit(input[i]))
i++;
}
}
return count;
}
bool is_valid_input(const char *input)
{
for (int i = 0; input[i] != '\0'; i++)
if (!isdigit(input[i]) && !isspace(input[i]))
return false;
return true;
}
int digits(uint64_t n)
{
int digits = 1;
while (n > 9)
{
n /= 10;
digits++;
}
return digits;
}
| 2.96875 | 3 |
2024-11-18T22:49:17.735832+00:00 | 2017-07-17T05:04:51 | 094fa08736a0a1da722ddb0bd0934b3819892d42 | {
"blob_id": "094fa08736a0a1da722ddb0bd0934b3819892d42",
"branch_name": "refs/heads/master",
"committer_date": "2017-07-17T05:04:51",
"content_id": "09ff7f3e6f60b9dbaab2ccab09e779c3e50f8a9b",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "db64d40b8ca4b9c7bcb91a7f31a24a24fe6dc7f9",
"extension": "c",
"filename": "mhdb-ref.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 97436849,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 681,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/mhdb-ref.c",
"provenance": "stackv2-0108.json.gz:94625",
"repo_name": "vixie/mhdb",
"revision_date": "2017-07-17T05:04:51",
"revision_id": "9568c31849ef7c07847a0eda7a00c09c21cab911",
"snapshot_id": "9b5be37c5b9b49523af7de4a1e39ec726fa2458a",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/vixie/mhdb/9568c31849ef7c07847a0eda7a00c09c21cab911/mhdb-ref.c",
"visit_date": "2021-01-01T06:29:28.538095"
} | stackv2 | #include <stdlib.h>
#include <string.h>
#include "mhdb.h"
int
main(int argc, char *argv[]) {
char *p1, *p2;
mhdb_t d1, d2;
int uid;
/* Here we call mhdb_path and mhdb_open separately (vs mh-add/mh-del)
* because if it's the same folder we don't want to open the database
* twice.
*/
p1 = mhdb_path(argv[1]);
p2 = mhdb_path(argv[2]);
d1 = mhdb_open(p1, mhdb_acc_exclusive);
d2 = (filenamecmp(p1, p2) == 0)
? d1
: mhdb_open(p2, mhdb_acc_exclusive);
free(p2);
free(p1);
uid = mhdb_get_uid(d1, argv[1]);
mhdb_delete_uid(d1, argv[1], uid);
uid = mhdb_assign_uid(d2, argv[2], (d1 == d2) ? uid : 0);
mhdb_close(d2);
if (d1 != d2)
mhdb_close(d1);
exit(0);
}
| 2.546875 | 3 |
2024-11-18T22:49:18.034132+00:00 | 2018-02-05T14:17:24 | 31713a81564101acb98e439b4fb6209cdad6b6ac | {
"blob_id": "31713a81564101acb98e439b4fb6209cdad6b6ac",
"branch_name": "refs/heads/master",
"committer_date": "2018-02-05T14:17:24",
"content_id": "6c3566fd33921f4777228047023a3a6660f2e44e",
"detected_licenses": [
"MIT"
],
"directory_id": "f4eee01e9c78778203acbb12eebb0bf48d2dc2ce",
"extension": "c",
"filename": "Hangman.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": 3476,
"license": "MIT",
"license_type": "permissive",
"path": "/Hangman.c",
"provenance": "stackv2-0108.json.gz:94755",
"repo_name": "ncharlton02/hangman-c",
"revision_date": "2018-02-05T14:17:24",
"revision_id": "80551309ceae62031b8e8933dd424355708aaa6d",
"snapshot_id": "f3fe4962ec5205c6e8b23be37fba4c2f27f570b8",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ncharlton02/hangman-c/80551309ceae62031b8e8933dd424355708aaa6d/Hangman.c",
"visit_date": "2022-02-09T02:34:03.240687"
} | stackv2 | #include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "Hangman.h"
#include "words.c"
#include "settings.c"
#include "util.c"
int main(){
//Clear the screengit
system("cls");
// Check if debug mode is enabled
checkDebug();
//Load Settings
loadSettings();
// Initialize variables
char* answer = getAnswer();
int answerlength = strlen(answer), lives = STARTING_LIVES;
int charsGuessed = 0, correctGuesses = 0, running = 1, won = 0;
char lettersGuessed[26];
char guess;
char output[answerlength];
//Initialize Game
for(int i =0; i < strlen(answer); i++){
output[i] = '_';
}
// Print debug info to the user
if (DEBUG){
printf("Answer: %s\n", answer);
printf("Highscore: %d\n", HIGHSCORE);
printf("Starting lives: %d\n", STARTING_LIVES);
printf("-----------------\n");
}
//Print Instructions to the user
printInstructions();
//Wait for the enter
waitForEnter();
system("cls");
//Reprint Instructions to the user
printInstructions();
//Main game loop
while (running){
//Print out the current score printf("%.*s\n", len, s + start);
printf("%.*s\n", answerlength, output);
printf("Guessed Letters: %.*s\n", charsGuessed, lettersGuessed);
printf("Lives: %d\n", lives);
//Print debug info to the user
if(DEBUG){
printf("Letters Guessed: %s\n", lettersGuessed);
printf("Chars Guessed: %d\n", charsGuessed);
}
// Get the guess from the user
while (1){
guess = toupper(getGuess());
printf("Guess: %c\n", guess);
// Check if its in the answer and hasn't been guessed
if (strcont(lettersGuessed, guess)){
printf("You have already guessed that!\n");
}else{
break;
}
}
//Add the letter guessed to the letters guessed
lettersGuessed[charsGuessed] = guess;
charsGuessed++;
//Check if the answer is right
if(strcont(answer, guess) == 1){
printf("Correct!\n");
correctGuesses++;
//Add Guess to the output
for(int i = 0; i < strlen(answer); i++){
if(answer[i] == guess)
output[i] = guess;
}
}else{
printf("Incorrect! You have lost a life!\n");
lives--;
}
//Win Condition
if(strcont(output, '_') == 0){
won = 1;
break;
}
//Lose Condition
if(lives < 1){
won = -1;
break;
}
//Clear the screen at the end of the turn
system("cls");
//Reprint Instructions to the user
printInstructions();
}
//Show Game Ended Screen
system("cls");
if(won == 1){
printf("You have guessed correctly!\n");
printf("Highscore: %d\n", HIGHSCORE);
if(lives > HIGHSCORE){
printf("You beat the highscore!\n");
HIGHSCORE = lives;
saveSettings();
}
printf("Answer: %s", answer);
}else if(won == -1){
printf("You have lost!\n");
printf("Answer: %s", answer);
}
//Wait for the user to quit
waitForEnter();
waitForEnter();
system("cls");
}
// Get the character guessed by the player
char getGuess(){
char guess;
printf("Guess a character!\n");
while (1){
scanf("%c", &guess);
if(guess == ';'){
system("cls");
exit(0);
}
// If the character is a letter, return it. If its not ask again
if (isalpha(guess)){
return guess;
}else if (guess != '\n'){ // if its a newline just skip it
printf("Not a character!\nGuess another character!\n");
}
}
}
void printInstructions(){
printf("Welcome to Hangman!\n");
printf("You have 5 guesses to guess the correct answer!\n");
printf("To Quit the game type';'\n");
printf("-----------------\n");
} | 3.28125 | 3 |
2024-11-18T22:49:18.103091+00:00 | 2022-05-16T16:55:22 | ea921c9f226670f05fa81740eca59694ccefffd4 | {
"blob_id": "ea921c9f226670f05fa81740eca59694ccefffd4",
"branch_name": "refs/heads/master",
"committer_date": "2022-05-16T16:55:22",
"content_id": "4975578ffeb59da3be1edb8753920353a2fc26bb",
"detected_licenses": [
"MIT"
],
"directory_id": "8041409b668a0780cb653705f0291fe0d49ce2ac",
"extension": "c",
"filename": "gsm.c",
"fork_events_count": 5,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 135595145,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5871,
"license": "MIT",
"license_type": "permissive",
"path": "/gsm.c",
"provenance": "stackv2-0108.json.gz:94884",
"repo_name": "shadlyd15/AirBootGSM",
"revision_date": "2022-05-16T16:55:22",
"revision_id": "cda2985ca0bb4ee903d4cae12c52642ac56b9ff8",
"snapshot_id": "fb877006d80e8f9a2f7d832d6ba03da116d32f23",
"src_encoding": "UTF-8",
"star_events_count": 9,
"url": "https://raw.githubusercontent.com/shadlyd15/AirBootGSM/cda2985ca0bb4ee903d4cae12c52642ac56b9ff8/gsm.c",
"visit_date": "2022-06-22T13:28:02.314091"
} | stackv2 |
#include <avr/io.h>
#include <util/delay.h>
#include <util/atomic.h>
#include "gsm.h"
#include "uart.h"
#include "watchdog.h"
#include "eeprom_addr.h"
#include "gsm_at_cmds.h"
volatile unsigned long g_seconds;
//NOTE: A unsigned long holds values from 0 to 4,294,967,295 (2^32 - 1). It will roll over to 0 after reaching its maximum value.
uint8_t get_tcp_trans_cmd(uint8_t * cmd){
if(cmd){
char ip_str[32];
char port_str[12];
memset(ip_str, 0x00, 32);
memset(port_str, 0x00, 12);
get_ota_server_ip_str(ip_str);
get_server_port_str(port_str);
sprintf(cmd, "%s%s,%s\r\n", AT_TCP_TRANS, ip_str, port_str);
return 1;
}
return 0;
}
uint8_t set_gsm_enable_config(uint8_t * port, uint8_t pin){
if(port){
eeprom_write_byte(GSM_REG_PORT_ADDR, port);
eeprom_write_byte(GSM_REG_PIN_ADDR, pin);
return 1;
}
return 0;
}
void set_ota_server_config(uint8_t * ip_addr, uint16_t port){
eeprom_write_byte(OTA_SERVER_IP_0, ip_addr[0]);
eeprom_write_byte(OTA_SERVER_IP_1, ip_addr[1]);
eeprom_write_byte(OTA_SERVER_IP_2, ip_addr[2]);
eeprom_write_byte(OTA_SERVER_IP_3, ip_addr[3]);
eeprom_write_byte(OTA_SERVER_PORT_H, port & 0xFF);
eeprom_write_byte(OTA_SERVER_PORT_L, port >> 8);
}
void change_pin_state(uint8_t *port, uint8_t pin, uint8_t value){
unsigned char * ddr = port - 1;
*ddr |= (1 << pin);
if(value){
*port |= (1 << pin);//make pin 13 high and power on the led
}
else{
*port &= ~(1 <<pin);//make pin 13 low and power off the led
}
}
void init_millis(){
TCCR1B |= 1<<CS10 | 1<<CS12;
TCNT1 = 0; //15625
}
unsigned long elapsed_seconds(){
if(TCNT1 > F_CPU / 1024){
g_seconds = g_seconds + 1;
TCNT1 = 0;
}
return g_seconds;
}
uint8_t find_sub_string(char* mainStr, uint8_t mainLen, char* subStr, uint8_t subLen){
uint8_t ans = NOT_OK;
uint8_t count = 0;
uint8_t offset = 0;
uint8_t i = 0;
for(i = 0; i < mainLen; i++){
if(mainStr[i] == subStr[count]){
count++;
offset++;
}
else{
count = 0;
}
if(count == (subLen-1)){
ans = OK;
return ans;
}
}
return ans;
}
uint8_t send_at_command(char * ATcommand, char * expected_resp, unsigned long timeout){
uint8_t x=0;
uint8_t answer = NOT_OK;
char response[SIZE_RESPONSE];
memset(response,'\0',SIZE_RESPONSE);
unsigned long start_time = elapsed_seconds();
uart_puts(ATcommand); // Send the AT command
do{ // this loop waits for the answer until timeouts
int ch = get_non_blocking_ch();
if(ch > -1){
char c = (char)ch;
response[x] = c;
x = ((x+1) % SIZE_RESPONSE);
if(strstr(response, expected_resp)){
answer = OK;
return answer;
}
else if(strstr(response, "ERROR")){
answer = NOT_OK;
return answer;
}
}
}
while(((unsigned long)(elapsed_seconds() - start_time) < timeout) || answer);
return answer;
}
void turn_modem_on(void){
uint8_t * port_addr = eeprom_read_byte(GSM_REG_PORT_ADDR);
uint8_t port_pin = eeprom_read_byte(GSM_REG_PIN_ADDR);
uint8_t high_level = eeprom_read_byte(GSM_REG_PIN_ON_LOGIC_ADDR);
change_pin_state(port_addr, port_pin, high_level);
}
void turn_modem_off(void){
uint8_t * port_addr = eeprom_read_byte(GSM_REG_PORT_ADDR);
uint8_t port_pin = eeprom_read_byte(GSM_REG_PIN_ADDR);
uint8_t high_level = eeprom_read_byte(GSM_REG_PIN_ON_LOGIC_ADDR);
change_pin_state(port_addr, port_pin, !high_level);
}
void get_ota_server_ip_str(char * ip_str){
uint8_t ip_1 = eeprom_read_byte(OTA_SERVER_IP_0);
uint8_t ip_2 = eeprom_read_byte(OTA_SERVER_IP_1);
uint8_t ip_3 = eeprom_read_byte(OTA_SERVER_IP_2);
uint8_t ip_4 = eeprom_read_byte(OTA_SERVER_IP_3);
sprintf(ip_str, "%d.%d.%d.%d", ip_1, ip_2, ip_3, ip_4);
}
void get_server_port_str(char * port_str){
uint8_t port_h = eeprom_read_byte(OTA_SERVER_PORT_H);
uint8_t port_l = eeprom_read_byte(OTA_SERVER_PORT_L);
uint16_t port = ((uint16_t)port_l << 8) | port_h;
sprintf(port_str, "%d", port);
}
uint8_t gsm_loop(void){
init_millis();
uint8_t ret_val = NOT_OK;
uint8_t gsm_state = INITIAL;
while(gsm_state != IDLE){
watchdogReset();
switch(gsm_state){
case INITIAL:{
turn_modem_on();
send_at_command(TCP_CLOSE, "OK", 2);
gsm_state = CHECK_PIN;
break;
}
case CHECK_PIN:{
if(send_at_command(AT_CHECK_PIN, "+CPIN: READY", 2)){
gsm_state = TURN_OFF_ECHO;
}
_delay_ms(1000);
break;
}
case TURN_OFF_ECHO:{
if(send_at_command(AT_ECHO_OFF, "OK", 2)){
gsm_state = CHECK_GSM;
}
_delay_ms(1000);
break;
}
case CHECK_SIGNAL:{
if(send_at_command(AT_CHECK_SIGNAL, "OK", 2)){
gsm_state = CHECK_GSM;
}
_delay_ms(1000);
break;
}
case CHECK_GSM:{
if(send_at_command(AT_CHECK_GSM, "+CREG: 0,1", 2)){
gsm_state = CHECK_GPRS;
}
_delay_ms(1000);
break;
}
case CHECK_GPRS:{
if(send_at_command(AT_CHECK_GPRS, "+CGATT: 1", 2)){
gsm_state = SET_PPP_LINK;
}
_delay_ms(1000);
break;
}
case SET_PPP_LINK:{
if(send_at_command(AT_SET_PPP_LINK, "OK", 2)){
gsm_state = CONNECT_TCP;
}
_delay_ms(1000);
break;
}
case CHECK_PPP_LINK:{
if(send_at_command(AT_CHECK_PPP_LINK, "+XIIC: 1,", 2)){
gsm_state = CONNECT_TCP;
}
_delay_ms(1000);
break;
}
case CONNECT_TCP:{
char AT_TCP_TRANS[128];
memset(AT_TCP_TRANS, 0x00, 128);
if(get_tcp_trans_cmd(AT_TCP_TRANS)){
if(send_at_command(AT_TCP_TRANS, "+TCPTRANS: OK", 5)){
gsm_state = IDLE;
return OK;
}
}
turn_modem_off();
_delay_ms(1000);
gsm_state = INITIAL;
break;
}
case IDLE:{
// uart_puts("GSM Loop Exits !!!\r\n");
ret_val = OK;
break;
}
default:{
break;
}
}
}
watchdogReset();
return NOT_OK;
}
| 2.546875 | 3 |
2024-11-18T22:49:18.304665+00:00 | 2018-03-15T03:22:59 | 662a0a9445add733ddd7f76d1b2addf8a3fa14b3 | {
"blob_id": "662a0a9445add733ddd7f76d1b2addf8a3fa14b3",
"branch_name": "refs/heads/master",
"committer_date": "2018-03-15T03:22:59",
"content_id": "faf36934381d9ab36e279bbcb542efe0891c6732",
"detected_licenses": [
"MIT"
],
"directory_id": "4378b9cc41d941d874e63dc51fbb2a98853cfe8a",
"extension": "h",
"filename": "stdint.h",
"fork_events_count": 0,
"gha_created_at": "2018-03-16T06:11:41",
"gha_event_created_at": "2018-03-16T06:11:41",
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 125471825,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1167,
"license": "MIT",
"license_type": "permissive",
"path": "/include/stdint.h",
"provenance": "stackv2-0108.json.gz:95014",
"repo_name": "tz70s/relibc",
"revision_date": "2018-03-15T03:22:59",
"revision_id": "a1baf1c92df4681fba75e31489c26cc1babfe4c1",
"snapshot_id": "d158edaa7b5ccd5acc1386241d3ce5f7b363e694",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/tz70s/relibc/a1baf1c92df4681fba75e31489c26cc1babfe4c1/include/stdint.h",
"visit_date": "2021-04-06T20:48:58.390442"
} | stackv2 | #ifndef _STDINT_H
#define _STDINT_H
#define INT8_MIN -0x80
#define INT8_MAX 0x7F
typedef signed char int8_t;
#define UINT8_MIN 0x00
#define UINT8_MAX 0xFF
typedef unsigned char uint8_t;
#define INT16_MIN -0x8000
#define INT16_MAX 0x7FFF
typedef signed short int16_t;
#define UINT16_MIN 0x0000
#define UINT16_MAX 0xFFFF
typedef unsigned short uint16_t;
#define INT32_MIN -0x80000000
#define INT32_MAX 0x7FFFFFFF
typedef signed long int32_t;
#define UINT32_MIN 0x00000000
#define UINT32_MAX 0xFFFFFFFF
typedef unsigned long uint32_t;
#define INT64_MIN -0x8000000000000000
#define INT64_MAX 0x7FFFFFFFFFFFFFFF
typedef signed long long int64_t;
#define UINT64_MIN 0x0000000000000000
#define UINT64_MAX 0xFFFFFFFFFFFFFFFF
typedef unsigned long long uint64_t;
#define INTPTR_MIN INT64_MIN
#define INTPTR_MAX INT64_MAX
typedef int64_t intptr_t;
#define UINTPTR_MIN UINT64_MIN
#define UINTPTR_MAX UINT64_MAX
typedef uint64_t uintptr_t;
#define INTMAX_MIN INT64_MIN
#define INTMAX_MAX INT64_MAX
typedef int64_t intmax_t;
#define UINTMAX_MIN UINT64_MIN
#define UINTMAX_MAX UINT64_MAX
typedef uint64_t uintmax_t;
#define SIZE_MAX UINT64_MAX
#endif /* _STDINT_H */
| 2.09375 | 2 |
2024-11-18T22:49:18.476178+00:00 | 2020-09-22T21:07:44 | f563b1e9ee5413ac7747cd1e878f3b143061eb3c | {
"blob_id": "f563b1e9ee5413ac7747cd1e878f3b143061eb3c",
"branch_name": "refs/heads/master",
"committer_date": "2020-09-22T21:07:44",
"content_id": "a67046af3a8fe37b47b374693af4667a5c16dbdc",
"detected_licenses": [],
"directory_id": "ac0b308bfd3c3e5c46ba28d2c4fe70f8516c9e7d",
"extension": "c",
"filename": "BulceWhilePrimeros10Números.c",
"fork_events_count": 0,
"gha_created_at": "2020-02-17T20:53:09",
"gha_event_created_at": "2020-02-17T20:53:09",
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 241205721,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 498,
"license": "",
"license_type": "permissive",
"path": "/While/BulceWhilePrimeros10Números.c",
"provenance": "stackv2-0108.json.gz:95143",
"repo_name": "Freddy875/C",
"revision_date": "2020-09-22T21:07:44",
"revision_id": "3cefc24fad613f70486197b0703d4cc433755e4a",
"snapshot_id": "299f2ccdb52fc77113fd5a6b8d3a907ee5c3d790",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Freddy875/C/3cefc24fad613f70486197b0703d4cc433755e4a/While/BulceWhilePrimeros10Números.c",
"visit_date": "2021-01-06T02:56:46.701022"
} | stackv2 | //CicloWhile Primeros 10 Números
#include <stdio.h>
int main(){
int iNumero = 1;
/*
while (iNumero <= 10){
printf("\nN%cmero %d",163,iNumero);
//iNumero++;
iNumero += 1;
}//fin while
*/
/*
while (iNumero <= 10){
printf("\nN%cmero %d",163,iNumero);
//iNumero++;
iNumero ++;
}//fin while
*/
while (iNumero <= 10){
printf("\nN%cmero %d",163,iNumero);
//iNumero++;
iNumero = iNumero + 1;
}//fin
return 0;
}//fin int main
| 2.875 | 3 |
2024-11-18T22:49:18.565252+00:00 | 2020-05-27T06:12:00 | 8289bda2961f6b1d52809fefbdef4152a4fb74c0 | {
"blob_id": "8289bda2961f6b1d52809fefbdef4152a4fb74c0",
"branch_name": "refs/heads/master",
"committer_date": "2020-05-27T11:04:37",
"content_id": "a9cfd13102e52b8623eaf15ef6bd51a0400ae0d0",
"detected_licenses": [
"MIT"
],
"directory_id": "9b943a52a2c9ccef16532e1e513382e20ad1f0b9",
"extension": "c",
"filename": "collision.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 226223464,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 7672,
"license": "MIT",
"license_type": "permissive",
"path": "/flecs-systems-physics/src/collision.c",
"provenance": "stackv2-0108.json.gz:95273",
"repo_name": "tang1024/flecs1.1_pong",
"revision_date": "2020-05-27T06:12:00",
"revision_id": "7d438aa18d207193eb4ad2aefabe2c95cb3d3a4d",
"snapshot_id": "810edb4237898a6d4f08781c6c819f2344dc4b21",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/tang1024/flecs1.1_pong/7d438aa18d207193eb4ad2aefabe2c95cb3d3a4d/flecs-systems-physics/src/collision.c",
"visit_date": "2022-08-24T05:25:44.202044"
} | stackv2 | #include <flecs_systems_physics.h>
#include <string.h>
#include <math.h>
/* -- Automatically add colliders to geometry entities with EcsCollider -- */
static
void add_rect_collider(
ecs_world_t *world,
ecs_entity_t entity,
ecs_entity_t ecs_entity(EcsPolygon8Collider),
float w,
float h)
{
ecs_set(world, entity, EcsPolygon8Collider, {
.points = {
{-w, -h},
{w, -h},
{w, h},
{-w, h},
{-w, -h}
},
.point_count = 5
});
}
void EcsAddColliderForSquare(ecs_rows_t *rows) {
ecs_world_t *world = rows->world;
ECS_COLUMN_COMPONENT(rows, EcsPolygon8Collider, 3);
int i;
for (i = 0; i < rows->count; i ++) {
EcsSquare *s = ecs_field(rows, EcsSquare, 1, i);
float w = s->size / 2.0;
add_rect_collider(
world, rows->entities[i], ecs_entity(EcsPolygon8Collider), w, w);
}
}
void EcsAddColliderForRectangle(ecs_rows_t *rows) {
ecs_world_t *world = rows->world;
ECS_COLUMN_COMPONENT(rows, EcsPolygon8Collider, 3);
int i;
for (i = 0; i < rows->count; i ++) {
EcsRectangle *s = ecs_field(rows, EcsRectangle, 1, i);
float w = s->width / 2.0;
float h = s->height / 2.0;
add_rect_collider(world, rows->entities[i], ecs_entity(EcsPolygon8Collider), w, h);
}
}
void EcsAddColliderForCircle(ecs_rows_t *rows) {
ecs_world_t *world = rows->world;
ECS_COLUMN_COMPONENT(rows, EcsCircleCollider, 3);
int i;
for (i = 0; i < rows->count; i ++) {
EcsCircle *s = ecs_field(rows, EcsCircle, 1, i);
ecs_set(world, rows->entities[i], EcsCircleCollider, {
.position = {0, 0},
.radius = s->radius
});
}
}
/* -- Add world colliders (colliders transformed to world space) -- */
void EcsAddPolygon8ColliderWorld(ecs_rows_t *rows) {
ecs_world_t *world = rows->world;
ECS_COLUMN_COMPONENT(rows, EcsPolygon8ColliderWorld, 2);
int i;
for (i = 0; i < rows->count; i ++) {
EcsPolygon8Collider *collider = ecs_field(rows, EcsPolygon8Collider, 1, i);
ecs_set_ptr(world, rows->entities[i], EcsPolygon8ColliderWorld, collider);
}
}
void EcsAddCircleColliderWorld(ecs_rows_t *rows) {
ecs_world_t *world = rows->world;
ECS_COLUMN_COMPONENT(rows, EcsCircleColliderWorld, 2);
int i;
for (i = 0; i < rows->count; i ++) {
EcsCircleCollider *collider = ecs_field(rows, EcsCircleCollider, 1, i);
ecs_set_ptr(world, rows->entities[i], EcsCircleColliderWorld, collider);
}
}
/* -- Transform colliders to world space -- */
void EcsTransformPolygon8Colliders(ecs_rows_t *rows) {
int i;
for (i = 0; i < rows->count; i ++) {
EcsMatTransform2D *m = ecs_field(rows, EcsMatTransform2D, 1, i);
EcsPolygon8Collider *c = ecs_field(rows, EcsPolygon8Collider, 2, i);
EcsPolygon8ColliderWorld *cw = ecs_field(rows, EcsPolygon8ColliderWorld, 3, i);
ecs_mat3x3_transform(m, c->points, cw->points, c->point_count);
cw->point_count = c->point_count;
}
}
void EcsTransformCircleColliders(ecs_rows_t *rows) {
int i;
for (i = 0; i < rows->count; i ++) {
EcsMatTransform2D *m = ecs_field(rows, EcsMatTransform2D, 1, i);
EcsCircleCollider *c = ecs_field(rows, EcsCircleCollider, 2, i);
EcsCircleColliderWorld *cw = ecs_field(rows, EcsCircleColliderWorld, 3, i);
ecs_mat3x3_transform(m, &c->position, &cw->position, 1);
}
}
typedef struct TestColliderParam {
ecs_entity_t entity;
ecs_type_t collider_component;
void *collider_data;
} TestColliderParam;
static
EcsPolygonCollider poly8_to_poly(
EcsPolygon8ColliderWorld *collider)
{
return (EcsPolygonCollider) {
.point_count = collider->point_count,
.points = collider->points
};
}
void create_collision(
ecs_world_t *world,
ecs_entity_t entity_1,
ecs_entity_t entity_2,
EcsCollision2D *collision_data,
ecs_entity_t ecs_entity(EcsCollision2D))
{
ecs_assert(entity_1 != entity_2, ECS_INTERNAL_ERROR, NULL);
collision_data->entity_1 = entity_1;
collision_data->entity_2 = entity_2;
ecs_set_ptr(world, 0, EcsCollision2D, collision_data);
}
void EcsTestColliders(ecs_rows_t *rows) {
TestColliderParam *param = rows->param;
ecs_world_t *world = rows->world;
ecs_type_t collider = ecs_column_type(rows, 1);
ECS_COLUMN_COMPONENT(rows, EcsPolygon8ColliderWorld, 2);
ECS_COLUMN_COMPONENT(rows, EcsCircleColliderWorld, 3);
ECS_COLUMN_COMPONENT(rows, EcsCollision2D, 4);
EcsCollision2D collision;
int i;
if (param->collider_component == TEcsPolygon8ColliderWorld) {
EcsPolygonCollider c1 = poly8_to_poly(param->collider_data);
if (collider == TEcsPolygon8ColliderWorld) {
for (i = 0; i < rows->count; i ++) {
EcsPolygonCollider c2 = poly8_to_poly(
ecs_field(rows, EcsPolygon8ColliderWorld, 1, i));
if (ecs_collider2d_poly(&c1, &c2, &collision)) {
create_collision(world, rows->entities[i], param->entity,
&collision, ecs_entity(EcsCollision2D));
}
}
} else if (collider == TEcsCircleColliderWorld) {
for (i = 0; i < rows->count; i ++) {
EcsCircleColliderWorld *c2 = ecs_field(rows, EcsCircleColliderWorld, 1, i);
if (ecs_collider2d_poly_circle(&c1, c2, &collision)) {
create_collision(world, rows->entities[i], param->entity,
&collision, ecs_entity(EcsCollision2D));
}
}
}
} else if (param->collider_component == TEcsCircleColliderWorld) {
EcsCircleColliderWorld *c1 = param->collider_data;
if (collider == TEcsPolygon8ColliderWorld) {
for (i = 0; i < rows->count; i ++) {
EcsPolygonCollider c2 = poly8_to_poly(ecs_field(rows, EcsPolygon8ColliderWorld, 1, i));
if (ecs_collider2d_circle_poly(c1, &c2, &collision)) {
create_collision(world, rows->entities[i], param->entity, &collision,
ecs_entity(EcsCollision2D));
}
}
} else if (collider == TEcsCircleColliderWorld) {
for (i = 0; i < rows->count; i ++) {
EcsCircleColliderWorld *c2 = ecs_field(rows, EcsCircleColliderWorld, 1, i);
if (ecs_collider2d_circle(c1, c2, &collision)) {
create_collision(world, rows->entities[i], param->entity,
&collision, ecs_entity(EcsCollision2D));
}
}
}
}
}
void EcsWalkColliders(ecs_rows_t *rows) {
ecs_world_t *world = rows->world;
ecs_type_t collider = ecs_column_type(rows, 1);
ecs_entity_t EcsTestColliders = ecs_column_entity(rows, 2);
int i;
for (i = 0; i < rows->count; i ++) {
void *data = _ecs_field(rows, 0, 1, i);
TestColliderParam param = {
.entity = rows->entities[i],
.collider_component = collider,
.collider_data = data
};
ecs_run_w_filter(
world,
EcsTestColliders,
rows->delta_time,
rows->frame_offset + i + 1,
0,
0,
¶m);
}
}
void EcsCleanCollisions(ecs_rows_t *rows) {
ecs_world_t *world = rows->world;
int i;
for (i = 0; i < rows->count; i ++) {
ecs_delete(world, rows->entities[i]);
}
}
| 2.578125 | 3 |
2024-11-18T22:49:18.653370+00:00 | 2020-05-05T23:30:37 | a2d1c0c3270089174e3ed53464b811880ec2651a | {
"blob_id": "a2d1c0c3270089174e3ed53464b811880ec2651a",
"branch_name": "refs/heads/master",
"committer_date": "2020-05-05T23:30:37",
"content_id": "205c9e4f454923248dc7d9dfaaab6087fcdda379",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "2d70fc747f7a187e157b9f7672b2b538e0e5b0c9",
"extension": "c",
"filename": "persistent-file.c",
"fork_events_count": 0,
"gha_created_at": "2020-05-07T16:21:38",
"gha_event_created_at": "2020-05-07T16:21:39",
"gha_language": null,
"gha_license_id": "Apache-2.0",
"github_id": 262100798,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1293,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/examples/file/persistent-file.c",
"provenance": "stackv2-0108.json.gz:95402",
"repo_name": "jtpereyda/honggfuzz",
"revision_date": "2020-05-05T23:30:37",
"revision_id": "b6c48bc62551cd2e62b5f73af59d13fd453f1045",
"snapshot_id": "f50b493d9590eadfc7f756112eb76b2edcc02d87",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/jtpereyda/honggfuzz/b6c48bc62551cd2e62b5f73af59d13fd453f1045/examples/file/persistent-file.c",
"visit_date": "2022-07-03T17:04:00.225077"
} | stackv2 | #ifdef __cplusplus
extern "C" {
#endif
#include <fcntl.h>
#include <libhfuzz/libhfuzz.h>
#include <setjmp.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include "magic.h"
/*
* Compile as:
* honggfuzz/hfuzz_cc/hfuzz-clang -I ./file-5.37/ honggfuzz/examples/file/persistent-file.c -o
* persistent-file ./file-5.37/src/.libs/libmagic.a -lz
*/
magic_t ms = NULL;
int LLVMFuzzerInitialize(int* argc, char*** argv) {
ms = magic_open(MAGIC_CONTINUE | MAGIC_CHECK | MAGIC_COMPRESS);
if (ms == NULL) {
fprintf(stderr, "magic_open() failed\n");
abort();
return 1;
}
const char* magic_file = "/usr/share/misc/magic.mgc";
if (*argc > 1) {
magic_file = (*argv)[1];
}
if (magic_load(ms, magic_file) == -1) {
fprintf(stderr, "magic_load() failed: %s\n", magic_error(ms));
magic_close(ms);
abort();
return 1;
}
return 0;
}
int LLVMFuzzerTestOneInput(const uint8_t* buf, size_t len) {
const char* type = magic_buffer(ms, buf, len);
if (type == NULL) {
printf("Type: [unknown]: %s\n", magic_error(ms));
} else {
printf("Type: '%s'\n", type);
}
return 0;
}
#ifdef __cplusplus
}
#endif
| 2.1875 | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.