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-18T19:35:31.224193+00:00 | 2013-12-31T17:52:27 | aae40ab81efbeae4574a348378d953c79c587132 | {
"blob_id": "aae40ab81efbeae4574a348378d953c79c587132",
"branch_name": "refs/heads/master",
"committer_date": "2013-12-31T17:52:27",
"content_id": "e3fcc78c82149e7da9303d0851938c17c30cffb2",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "89cade5f2b532f8a8facd0f90d06b87c01ce6291",
"extension": "c",
"filename": "rbfact.c",
"fork_events_count": 5,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 583345,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 20172,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/rbfact.c",
"provenance": "stackv2-0054.json.gz:25579",
"repo_name": "jarcec/rbclips",
"revision_date": "2013-12-31T17:52:27",
"revision_id": "dfeb9c7faf4c7f6f08967319b1519b033adbb82e",
"snapshot_id": "b17c5af9ec7ce4b016b8a534f71f8f13ce35f7fb",
"src_encoding": "UTF-8",
"star_events_count": 7,
"url": "https://raw.githubusercontent.com/jarcec/rbclips/dfeb9c7faf4c7f6f08967319b1519b033adbb82e/src/rbfact.c",
"visit_date": "2016-09-05T08:50:29.896833"
} | stackv2 | /*
* Copyright 2013 Jarek Jarcec Cecho <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stdlib.h>
#include <ruby.h>
#include "clips/clips.h"
#include "rbclips.h"
#include "rbfact.h"
#include "rbtemplate.h"
#include "rbconstraint.h"
#include "rbexception.h"
#include "rbbase.h"
#include "rbgeneric.h"
/* Definitions */
VALUE cl_cFact;
VALUE cl_cFactAddress;
//! Create ordered fact
VALUE cl_fact_initialize_ordered(VALUE, VALUE, VALUE);
//! Create nonordered fact
VALUE cl_fact_initialize_nonordered(VALUE, VALUE, VALUE);
//! to_s method for ordered fact
VALUE cl_fact_to_s_ordered(VALUE);
//! to_s method for nonordered fact
VALUE cl_fact_to_s_nonordered(VALUE);
//! Foreach method for creating nonordered fact
int cl_fact_initialize_nonordered_each(VALUE, VALUE, VALUE);
//! Foreach method for creating entries in internal hash
int cl_fact_initialize_nonordered_create_entries(VALUE, VALUE, VALUE);
//! Foreach method for string conversion
int cl_fact_to_s_nonordered_each(VALUE, VALUE, VALUE);
//! Foreach method for updating fact
int cl_fact_update_each(VALUE, VALUE, VALUE);
//! Define method for ordered fact
void cl_fact_define_instance_methods_ordered(VALUE, int);
//! Define method for nonordered fact
void cl_fact_define_instance_methods_nonordered(VALUE, int);
//! Foreach method for creating slot accessors (nonordered fact)
int cl_fact_define_instance_methods_attr_slot(VALUE, VALUE, VALUE);
//! Method body (block) for creating slot accessors (nonordered fact)
VALUE cl_fact_define_instance_methods_attr_slot_block(VALUE, VALUE, int, VALUE *);
//! Method body (block) for creationt set_slot accessors (nonordered fact)
VALUE cl_fact_define_instance_methods_attr_set_slot_block(VALUE, VALUE, int, VALUE *);
//! Foreach method for creation set_slot accessors(nonordered fact)
int cl_fact_define_instance_methods_attr_set_slot(VALUE, VALUE, VALUE);
/**
* Creating new object - wrap struct
*/
VALUE cl_fact_new(int argc, VALUE *argv, VALUE self)
{
cl_sFactWrap *wrap = calloc(1, sizeof(*wrap));
VALUE ret = Data_Wrap_Struct(self, NULL, free, wrap);
rb_obj_call_init(ret, argc, argv);
return ret;
}
/**
* Build and return back array with all facts
*/
VALUE cl_fact_all(VALUE self)
{
VALUE ret = rb_ary_new();
void *fact = NULL;
while( fact = GetNextFact(fact) )
{
char *templatename = GetDeftemplateName( FactDeftemplate(fact) );
if(strcmp(templatename, "initial-fact") == 0) continue;
// Creating the object
cl_sFactWrap *wrap = calloc(1, sizeof(*wrap));
VALUE obj = Data_Wrap_Struct(cl_cFact, NULL, free, wrap);
// Building it's content
wrap->ptr = fact;
CL_UPDATE(obj);
cl_fact_define_instance_methods(obj, FACT_FAMILY_READ|FACT_FAMILY_WRITE);
rb_ary_push(ret, obj);
}
// C'est tout
return ret;
}
/**
* Return only facts matching given criteria
* This is really simple approach, some more sofisticated
* way is desierable for the future.
*/
VALUE cl_fact_find(int argc, VALUE *argv, VALUE self)
{
if(argc != 1)
{
rb_raise(cl_eArgError, "Clips::Fact::find Wrong number of argumentse, please read manual for allowed values.");
return Qnil;
}
if(TYPE(argv[0]) != T_STRING && TYPE(argv[0]) != T_SYMBOL && rb_obj_class(argv[0]) != cl_cTemplate)
{
rb_raise(cl_eArgError, "Clips::Fact::find expects for first argument to be string, symbol or Template object, but '%s' have class '%s'.", CL_STR(argv[0]), CL_STR_CLASS(argv[0]));
return Qnil;
}
// I'm using fact that CLIPS are creating templates even for
// ordered facts, so task to find out if we're looking for this
// fact based on template is really simple and straightforward
// even for ordered facts.
char *template;
if(rb_obj_class(argv[0]) == cl_cTemplate)
{
template = CL_STR( rb_iv_get(argv[0], "@name") );
} else {
template = CL_STR(argv[0]);
}
VALUE ret = rb_ary_new();
void *fact = NULL;
while( fact = GetNextFact(fact) )
{
// Are we looking for this?
char *templatename = GetDeftemplateName( FactDeftemplate(fact) );
if(strcmp(template, templatename) != 0) continue;
// Creating the object
cl_sFactWrap *wrap = calloc(1, sizeof(*wrap));
VALUE obj = Data_Wrap_Struct(cl_cFact, NULL, free, wrap);
// Building it's content
wrap->ptr = fact;
CL_UPDATE(obj);
cl_fact_define_instance_methods(obj, FACT_FAMILY_READ|FACT_FAMILY_WRITE);
rb_ary_push(ret, obj);
}
// C'est tout
return ret;
}
/**
* Constructor - initialize
*/
VALUE cl_fact_initialize(VALUE self, VALUE first, VALUE second)
{
if(TYPE(first) == T_STRING && TYPE(second) == T_ARRAY)
{
return cl_fact_initialize_ordered(self, first, second);
}
if(rb_obj_class(first) == cl_cTemplate && TYPE(second) == T_HASH)
{
return cl_fact_initialize_nonordered(self, first, second);
}
rb_raise(cl_eArgError, "Clips::Fact#initialize expected two possibility of arguments String with Array or Template with Hash");
return Qnil;
}
/**
* Initialize an ordered fact
*/
VALUE cl_fact_initialize_ordered(VALUE self, VALUE first, VALUE second)
{
if( !cl_generic_check_clips_symbol(first) )
{
rb_raise(cl_eArgError, "Clips::Fact#initialize '%s' is not valid CLIPS symbol.", CL_STR(first));
return Qnil;
}
rb_iv_set(self, "@template", first);
rb_iv_set(self, "@slots", second);
// Define instance methods
cl_fact_define_instance_methods_ordered(self, FACT_FAMILY_READ|FACT_FAMILY_WRITE);
return Qtrue;
}
/**
* Initialize a nonordered fact
*/
VALUE cl_fact_initialize_nonordered(VALUE self, VALUE first, VALUE second)
{
if( TYPE( rb_funcall(first, cl_vIds.saved, 0) ) != T_TRUE)
{
rb_raise(cl_eArgError, "Clips::Fact#initialize template is not saved!.");
return ST_STOP;
}
rb_iv_set(self, "@template", first);
rb_iv_set(self, "@slots", rb_hash_new());
// Take all template slots and create entry in our internal slot hash
VALUE tslots = rb_iv_get(first, "@slots");
rb_hash_foreach(tslots, cl_fact_initialize_nonordered_create_entries, self);
// Go throw given hash and fill internal slots from it
rb_hash_foreach(second, cl_fact_initialize_nonordered_each, self);
// Define instance methods
cl_fact_define_instance_methods_nonordered(self, FACT_FAMILY_READ|FACT_FAMILY_WRITE);
return Qtrue;
}
/**
* Return slot list in case of ordered fact
*/
VALUE cl_fact_slots(VALUE self)
{
VALUE slots = rb_iv_get(self, "@slots");
return rb_ary_dup(slots);
}
/**
* Return value of given slot (nonordered fact)
*/
VALUE cl_fact_slot(VALUE self, VALUE slot)
{
VALUE template = rb_iv_get(self, "@template");
VALUE fslots = rb_iv_get(self, "@slots");
VALUE tslots = rb_iv_get(template, "@slots");
// Check if given slot really exists
VALUE c = rb_hash_lookup(tslots, slot);
if(NIL_P(c))
{
rb_raise(cl_eArgError, "Clips::Fact#slot Given slot '%s' don't exists", CL_STR(slot));
return Qnil;
}
return rb_hash_lookup(fslots, slot);
}
/**
* Method for changing slot value in nonordered fact
*/
VALUE cl_fact_set_slot(VALUE self, VALUE slot, VALUE newValue)
{
cl_sFactWrap *wrap = DATA_PTR(self);
if( !wrap )
{
rb_raise(cl_eUseError, "Oops, wrap structure don't exists!");
return Qnil;
}
VALUE template = rb_iv_get(self, "@template");
VALUE fslots = rb_iv_get(self, "@slots");
VALUE tslots = rb_iv_get(template, "@slots");
// Check if given slot really exists
VALUE c = rb_hash_lookup(tslots, slot);
if(NIL_P(c))
{
rb_raise(cl_eArgError, "Clips::Fact#set_slot Given slot '%s' don't exists", CL_STR(slot));
return Qnil;
}
// Save new value inside Ruby object
rb_hash_aset(fslots, slot, newValue);
// C'est tout
return Qtrue;
}
/**
* If it's ordered fact, returns name of fact, otherwise return template object.
* Basically return @template.
*/
VALUE cl_fact_template(VALUE self)
{
VALUE ret = rb_iv_get(self, "@template");
return rb_funcall(ret, cl_vIds.clone, 0);
}
/**
* Go throw each slot in template and create entry with nil value in our
* internal hash slot list. E.g. fill nil value to it
*/
int cl_fact_initialize_nonordered_create_entries(VALUE key, VALUE value, VALUE self)
{
VALUE slots = rb_iv_get(self, "@slots");
rb_hash_aset(slots, key, Qnil);
return ST_CONTINUE;
}
/**
* Set slots from given hash (maybe more check later) (constraints?)
*/
int cl_fact_initialize_nonordered_each(VALUE key, VALUE value, VALUE self)
{
if(TYPE(key) != T_STRING && TYPE(key) != T_SYMBOL)
{
rb_raise(cl_eArgError, "Clips::Fact#initialize slot assignement accept only strings or symbols as keys but '%s' have class '%s'.", CL_STR(key), CL_STR_CLASS(key));
return ST_STOP;
}
VALUE template = rb_iv_get(self, "@template");
VALUE slots = rb_iv_get(self, "@slots");
VALUE tslots = rb_iv_get(template, "@slots");
// Transfer type if necessary
if(TYPE(key) == T_STRING)
key = rb_funcall(key, cl_vIds.to_sym, 0);
// Does the slot exists in template?
VALUE c = rb_hash_lookup(tslots, key);
if( NIL_P(c) )
{
rb_raise(cl_eArgError, "Clips::Fact#initialize template don't have slot '%s'.", CL_STR(key));
return ST_STOP;
}
// It shouldn't be defined already
c = rb_hash_lookup(slots, key);
if( !NIL_P(c) )
{
rb_raise(cl_eArgError, "Clips::Fact#initialize slot '%s' already filled up.", CL_STR(key));
return ST_STOP;
}
rb_hash_aset(slots, key, value);
return ST_CONTINUE;
}
/**
* Return string reprezentation
*/
VALUE cl_fact_to_s(VALUE self)
{
VALUE ord = rb_funcall(self, cl_vIds.ordered, 0);
if(TYPE(ord) == T_TRUE) return cl_fact_to_s_ordered(self);
return cl_fact_to_s_nonordered(self);
}
/**
* to_s: Ordered variant
*/
VALUE cl_fact_to_s_ordered(VALUE self)
{
VALUE ret = rb_str_new2("(");
VALUE template = rb_iv_get(self, "@template");
VALUE slots = rb_iv_get(self, "@slots");
rb_str_cat2(ret, CL_STR(template));
// Non ordered slot
long len = RARRAY_LEN(slots);
int i;
for(i = 0; i < len; i++)
rb_str_catf(ret, " %s", CL_STR_ESCAPE(rb_ary_entry(slots, i)) );
rb_str_cat2(ret, ")");
return ret;
}
/**
* to_s: Nonordered variant
*/
VALUE cl_fact_to_s_nonordered(VALUE self)
{
VALUE ret = rb_str_new2("(");
VALUE template = rb_iv_get(self, "@template");
VALUE slots = rb_iv_get(self, "@slots");
VALUE tname = rb_iv_get(template, "@name");
rb_str_cat2(ret, CL_STR(tname));
rb_hash_foreach(slots, cl_fact_to_s_nonordered_each, ret);
rb_str_cat2(ret, ")");
return ret;
}
/**
* to_s: For each slot in hash
*/
int cl_fact_to_s_nonordered_each(VALUE key, VALUE value, VALUE target)
{
// Skip this slot, if it's value is nil
if(NIL_P(value))
return ST_CONTINUE;
// If its array ~= multifield value, do it one by one
if(TYPE(value) == T_ARRAY)
{
rb_str_catf(target, " (%s", CL_STR(key));
long len = RARRAY_LEN(value);
int i;
for(i = 0; i < len; i++)
rb_str_catf(target, " %s", CL_STR_ESCAPE(rb_ary_entry(value, i)) );
rb_str_cat2(target, ")");
return ST_CONTINUE;
}
// Normal object, convert it to string
rb_str_catf(target, " (%s %s)", CL_STR(key), CL_STR_ESCAPE(value));
return ST_CONTINUE;
}
/**
* Duplicate this object
*/
VALUE cl_fact_clone(VALUE self)
{
cl_sFactWrap *selfwrap = DATA_PTR(self);
cl_sFactWrap *wrap = calloc( 1, sizeof(*wrap) );
wrap->ptr = selfwrap->ptr;
VALUE ret = Data_Wrap_Struct(cl_cFact, NULL, free, wrap);
VALUE argv[2];
argv[0] = rb_iv_get(self, "@template");
argv[1] = rb_iv_get(self, "@slots");
rb_obj_call_init(ret, 2, argv);
return ret;
}
/**
* Represent this two objects same CLIPS fact?
*/
VALUE cl_fact_equal(VALUE a, VALUE b)
{
CL_EQUAL_CLASS(b, cl_cFact);
// This is outdated right now, but from unknown reason
// it have to be here, otherwise testcases are segmentating
// CL_UPDATE(a);
// CL_UPDATE(b);
CL_EQUAL_DEFINE;
CL_EQUAL_CHECK_IV("@template");
CL_EQUAL_CHECK_IV("@slots");
CL_EQUAL_DEFINE_WRAP(cl_sFactWrap);
CL_EQUAL_CHECK_PTR;
return Qtrue;
}
/**
* Save fact to CLIPS environment
*/
VALUE cl_fact_save(VALUE self)
{
cl_sFactWrap *wrap = DATA_PTR(self);
if( !wrap )
{
rb_raise(cl_eUseError, "Oops, wrap structure don't exists!");
return Qnil;
}
// Valid?
if ( !FactExistp(wrap->ptr) )
wrap->ptr = NULL;
// Is this fact already saved or not?
if( !wrap->ptr )
{
// No it's not, so we're creating new on
wrap->ptr = AssertString( CL_STR(self) );
} else {
// This fact is already saved, so we're making same approach
// as CLIPS itself - retracting current and asssert new one.
// Modify command is not suitable here, because it "forget"
// pointer to newly created fact.
if( !Retract(wrap->ptr) ) return Qfalse;
wrap->ptr = AssertString( CL_STR(self) );
}
return Qtrue;
}
/**
* Return True or False based on whether this object was
* already saved and/or if it change after last save.
*/
VALUE cl_fact_saved(VALUE self)
{
cl_sFactWrap *wrap = DATA_PTR(self);
if( !wrap )
{
rb_raise(cl_eUseError, "Oops, wrap structure don't exists!");
return Qnil;
}
if( !wrap->ptr ) return Qfalse;
// Valid?
if ( !FactExistp(wrap->ptr) )
{
wrap->ptr = NULL;
return Qfalse;
}
// Creating the object from CLIPS
cl_sFactWrap *wrap_clips = calloc(1, sizeof(*wrap_clips));
VALUE obj_clips = Data_Wrap_Struct(cl_cFact, NULL, free, wrap_clips);
wrap_clips->ptr = wrap->ptr;
CL_UPDATE(obj_clips);
// Return whether us and the CLIPS representation are the same
return rb_funcall(self, cl_vIds.eqq, 1, obj_clips);
}
/**
* Update inner structures from CLIPS environment
*/
VALUE cl_fact_update(VALUE self)
{
cl_sFactWrap *wrap = DATA_PTR(self);
if( !wrap )
{
rb_raise(cl_eUseError, "Oops, wrap structure don't exists!");
return Qnil;
}
// Valid?
if ( !FactExistp(wrap->ptr) )
{
wrap->ptr = NULL;
return Qtrue;
}
// Load template name
void *template = FactDeftemplate(wrap->ptr);
if( ((struct deftemplate*)template)->implied )
{
// Ordered fact
rb_iv_set(self, "@template", rb_str_new_cstr(GetDeftemplateName(template)) );
DATA_OBJECT slot;
if( !GetFactSlot(wrap->ptr, NULL, &slot) )
{
rb_raise(cl_eInternError, "Cannot get implied slot of ordered fact, wtf?");
return Qnil;
}
rb_iv_set(self, "@slots", cl_generic_convert_dataobject(slot) );
} else {
// Non ordered
VALUE template_obj = rb_funcall(cl_cTemplate, cl_vIds.load, 1, rb_str_new_cstr(GetDeftemplateName(template)));
rb_iv_set(self, "@template", template_obj);
VALUE value_slots = rb_hash_new();
rb_iv_set(self, "@slots", value_slots);
VALUE key_slots = rb_iv_get(template_obj, "@slots");
rb_hash_foreach(key_slots, cl_fact_update_each, self);
}
return Qtrue;
}
/**
* Foreach function that goes throw all slots and load it's values from
* CLIPS and store them inside object
*/
int cl_fact_update_each(VALUE key, VALUE value, VALUE self)
{
cl_sFactWrap *wrap = DATA_PTR(self);
if( !wrap )
{
rb_raise(cl_eUseError, "Oops, wrap structure don't exists!");
return ST_STOP;
}
DATA_OBJECT slot;
if( !GetFactSlot(wrap->ptr, CL_STR(key) , &slot) )
{
rb_raise(cl_eInternError, "Cannot get implied slot of ordered fact, wtf?");
return ST_STOP;
}
VALUE slots = rb_iv_get(self, "@slots");
rb_hash_aset(slots, key, cl_generic_convert_dataobject(slot));
return ST_CONTINUE;
}
/**
* Remove fact from CLIPS environment
*/
VALUE cl_fact_destroy(VALUE self)
{
cl_sFactWrap *wrap = DATA_PTR(self);
if( !wrap )
{
rb_raise(cl_eUseError, "Oops, wrap structure don't exists!");
return Qnil;
}
// if NULL return (don't rectract something that is not saved)
if( !wrap->ptr ) return Qfalse;
if ( !FactExistp(wrap->ptr) ) return Qfalse;
if( Retract(wrap->ptr) ) return Qtrue;
return Qfalse;
}
/**
* Is this fact ordered or non ordered?
*/
VALUE cl_fact_ordered(VALUE self)
{
VALUE name = rb_iv_get(self, "@template");
if(TYPE(name) == T_STRING) return Qtrue;
return Qfalse;
}
/**
* Define instance methods based on self's type
* (ordered or nonordered fact).
*/
void cl_fact_define_instance_methods(VALUE self, int family)
{
VALUE template = rb_iv_get(self, "@template");
if(TYPE(template) == T_STRING) cl_fact_define_instance_methods_ordered(self, family);
if(rb_obj_class(template) == cl_cTemplate) cl_fact_define_instance_methods_nonordered(self, family);
}
/**
* Define instance methods in case of ordered fact
*/
void cl_fact_define_instance_methods_ordered(VALUE self, int family)
{
if(family & FACT_FAMILY_READ)
{
// Define singleton methods
rb_define_singleton_method(self, "slots", cl_fact_slots, 0);
rb_define_singleton_method(self, "name", cl_fact_template, 0);
}
}
/**
* Define instance methods in case of nonordered fact
*/
void cl_fact_define_instance_methods_nonordered(VALUE self, int family)
{
if(family & FACT_FAMILY_READ)
{
// Define singleton methods
rb_define_singleton_method(self, "slot", cl_fact_slot, 1);
rb_define_singleton_method(self, "template", cl_fact_template, 0);
// Define slot accessors
VALUE template = rb_iv_get(self, "@template");
VALUE slots = rb_iv_get(template, "@slots");
rb_hash_foreach(slots, cl_fact_define_instance_methods_attr_slot, self);
}
if(family & FACT_FAMILY_WRITE)
{
// Define set_slot accessors
VALUE template = rb_iv_get(self, "@template");
VALUE slots = rb_iv_get(template, "@slots");
rb_define_singleton_method(self, "set_slot", cl_fact_set_slot, 2);
rb_hash_foreach(slots, cl_fact_define_instance_methods_attr_set_slot, self);
}
}
/**
* Block represenatation for wrapping set_slot(name,newValue) method (body)
*/
VALUE cl_fact_define_instance_methods_attr_set_slot_block(VALUE yield, VALUE ary, int argc, VALUE *argv)
{
if(argc != 1)
{
rb_raise(cl_eArgError, "Clips::Fact#set_slot slot '%s' called without any new value.", CL_STR(rb_ary_entry(ary, 1)));
return Qnil;
}
return rb_funcall(rb_ary_entry(ary, 0), rb_intern("set_slot"), 2, rb_ary_entry(ary, 1), argv[0]);
}
/**
* For each method for creating set_slot methods
*/
int cl_fact_define_instance_methods_attr_set_slot(VALUE key, VALUE value, VALUE self)
{
VALUE ary = rb_ary_new();
rb_ary_push(ary, self);
rb_ary_push(ary, key);
VALUE name = rb_sprintf("%s=", CL_STR(key));
rb_block_call(self, rb_intern("define_singleton_method"), 1, &name, cl_fact_define_instance_methods_attr_set_slot_block, ary);
return ST_CONTINUE;
}
/**
* Block represenatation for wrapping slot(name) method (body)
*/
VALUE cl_fact_define_instance_methods_attr_slot_block(VALUE yield, VALUE ary, int argc, VALUE *argv)
{
if(argc != 0)
{
rb_raise(cl_eArgError, "Clips::Fact#slot slot '%s' called with additional parameters.", CL_STR(rb_ary_entry(ary, 1)));
return Qnil;
}
return rb_funcall(rb_ary_entry(ary, 0), rb_intern("slot"), 1, rb_ary_entry(ary, 1));
}
/**
* For each method for creating slot attributes
*/
int cl_fact_define_instance_methods_attr_slot(VALUE key, VALUE value, VALUE self)
{
VALUE ary = rb_ary_new();
rb_ary_push(ary, self);
rb_ary_push(ary, key);
rb_block_call(self, rb_intern("define_singleton_method"), 1, &key, cl_fact_define_instance_methods_attr_slot_block, ary);
return ST_CONTINUE;
}
/**
* Return representation of our address
*/
VALUE cl_factaddress_to_s(VALUE self)
{
return rb_str_dup( rb_iv_get(self, "@to_s") );
}
| 2.390625 | 2 |
2024-11-18T19:35:33.847037+00:00 | 2019-04-10T11:15:13 | f82e6a33f84e5edfc9f2bc0790b5de637d94ce78 | {
"blob_id": "f82e6a33f84e5edfc9f2bc0790b5de637d94ce78",
"branch_name": "refs/heads/master",
"committer_date": "2019-04-10T11:15:13",
"content_id": "de8c7ef9c0e4fdccb9552e77bb6865cf1ad34de1",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "f66e2ad3fc0f8c88278c0997b156f5c6c8f77f28",
"extension": "h",
"filename": "CircleLinkedList.h",
"fork_events_count": 0,
"gha_created_at": "2019-04-11T08:40:38",
"gha_event_created_at": "2019-04-11T08:40:38",
"gha_language": null,
"gha_license_id": "Apache-2.0",
"github_id": 180750568,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1475,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/DataStructure/DataStructure-c/list/CircleLinkedList.h",
"provenance": "stackv2-0054.json.gz:25708",
"repo_name": "flyfire/Programming-Notes-Code",
"revision_date": "2019-04-10T11:15:13",
"revision_id": "4b1bdd74c1ba0c007c504834e4508ec39f01cd94",
"snapshot_id": "3b51b45f8760309013c3c0cc748311d33951a044",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/flyfire/Programming-Notes-Code/4b1bdd74c1ba0c007c504834e4508ec39f01cd94/DataStructure/DataStructure-c/list/CircleLinkedList.h",
"visit_date": "2020-05-07T18:00:49.757509"
} | stackv2 | #ifndef DATASTRUCTURE_C_CIRCLELINKEDLIST_H
#define DATASTRUCTURE_C_CIRCLELINKEDLIST_H
#include<stdio.h>
#include<stdlib.h>
//链表的小结点
typedef struct CircleLinkNodeTag {
struct CircleLinkNodeTag *next;
} CircleLinkNode;
//链表结构体
typedef struct {
CircleLinkNode head;
int size;
} CircleLinkList;
//编写针对链表结构体操作的API函数
#define CIRCLELINKLIST_TRUE 1
#define CIRCLELINKLIST_FALSE 0
//比较回调
typedef int(*COMPARE_CIRCLENODE)(CircleLinkNode *, CircleLinkNode *);
//打印回调
typedef void(*PRINT_CIRCLENODE)(CircleLinkNode *);
//初始化函数
CircleLinkList *Init_CircleLinkList();
//插入函数
void Insert_CircleLinkList(CircleLinkList *clist, int pos, CircleLinkNode *data);
//获得第一个元素
CircleLinkNode *Front_CircleLinkList(CircleLinkList *clist);
//根据位置删除
void RemoveByPos_CircleLinkList(CircleLinkList *clist, int pos);
//根据值去删除
void RemoveByValue_CircleLinkList(CircleLinkList *clist, CircleLinkNode *data, COMPARE_CIRCLENODE compare);
//获得链表的长度
int Size_CircleLinkList(CircleLinkList *clist);
//判断是否为空
int IsEmpty_CircleLinkList(CircleLinkList *clist);
//查找
int Find_CircleLinkList(CircleLinkList *clist, CircleLinkNode *data, COMPARE_CIRCLENODE compare);
//打印节点
void Print_CircleLinkList(CircleLinkList *clist, PRINT_CIRCLENODE print);
//释放内存
void FreeSpace_CircleLinkList(CircleLinkList *clist);
#endif
| 2.53125 | 3 |
2024-11-18T19:35:34.245396+00:00 | 2022-03-16T00:36:15 | f0362089ae5b4ed37ec848f000194c7df7e4efc3 | {
"blob_id": "f0362089ae5b4ed37ec848f000194c7df7e4efc3",
"branch_name": "refs/heads/master",
"committer_date": "2022-03-16T00:36:15",
"content_id": "0528eeb3c17475ae04232347723257ac31fab3e7",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "511a86ed875b66366e3541e1268750db01b9d843",
"extension": "c",
"filename": "fseqTest.c",
"fork_events_count": 2,
"gha_created_at": "2019-05-12T01:29:13",
"gha_event_created_at": "2021-07-29T01:55:37",
"gha_language": "C",
"gha_license_id": "BSD-3-Clause",
"github_id": 186198210,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 15765,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/fseqTest.c",
"provenance": "stackv2-0054.json.gz:25965",
"repo_name": "darbyjohnston/FSeq",
"revision_date": "2022-03-16T00:36:15",
"revision_id": "cda02f1793fe7f58b1b76aa6d427a3190226769a",
"snapshot_id": "0fe1adb71444eae6038d9169ac037e5bc6253bb4",
"src_encoding": "UTF-8",
"star_events_count": 16,
"url": "https://raw.githubusercontent.com/darbyjohnston/FSeq/cda02f1793fe7f58b1b76aa6d427a3190226769a/fseqTest.c",
"visit_date": "2022-05-15T00:23:03.028569"
} | stackv2 | // SPDX-License-Identifier: BSD-3-Clause
// Copyright (c) 2019-2021 Darby Johnston
// All rights reserved.
#include "fseq.h"
#include <assert.h>
#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#if defined(WIN32) || defined(_WIN32)
#include <direct.h>
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif // WIN32_LEAN_AND_MEAN
#include <windows.h>
#endif
#if defined(WIN32) || defined(_WIN32)
void fseqMkdir(const char* fileName)
{
int wlen = MultiByteToWideChar(CP_UTF8, 0, fileName, -1, NULL, 0);
wchar_t* wbuf = malloc(wlen * sizeof(wchar_t));
MultiByteToWideChar(CP_UTF8, 0, fileName, -1, wbuf, wlen);
_wmkdir(wbuf);
free(wbuf);
}
void fseqTouch(const char* fileName)
{
int wlen = MultiByteToWideChar(CP_UTF8, 0, fileName, -1, NULL, 0);
wchar_t* wbuf = malloc(wlen * sizeof(wchar_t));
MultiByteToWideChar(CP_UTF8, 0, fileName, -1, wbuf, wlen);
fclose(_wfopen(wbuf, L"w"));
free(wbuf);
}
#else
void fseqMkdir(const char* fileName)
{
mkdir(fileName, 0777);
}
void fseqTouch(const char* fileName)
{
fclose(fopen(fileName, "w"));
}
#endif
void test0()
{
struct FSeqFileNameSizes a;
fseqFileNameSizesInit(&a);
assert(0 == a.path);
assert(0 == a.base);
assert(0 == a.number);
assert(0 == a.extension);
}
void test1()
{
const char testData[][5][FSEQ_STRING_LEN] =
{
{ "", "", "", "", "" },
{ "/", "/", "", "", "" },
{ ".", "", ".", "", "" },
{ "/.", "/", ".", "", "" },
{ "\\", "\\", "", "", "" },
{ "\\\\", "\\\\", "", "", "" },
{ "\\\\.", "\\\\", ".", "", "" },
{ "\\\\.\\", "\\\\.\\", "", "", "" },
{ "0", "", "", "0", "" },
{ "/0", "/", "", "0", "" },
{ "/a/b/c1.ext", "/a/b/", "c", "1", ".ext" },
{ "/a/b/c10.ext", "/a/b/", "c", "10", ".ext" },
{ "/a/b/c100.ext", "/a/b/", "c", "100", ".ext" },
{ "/a/b/c0100.ext", "/a/b/", "c", "0100", ".ext" },
{ "/a/b/c-0100.ext", "/a/b/", "c-", "0100", ".ext" },
{ "C:\\a\\b\\c-0100.ext", "C:\\a\\b\\", "c-", "0100", ".ext" }
};
const size_t testDataSize = sizeof(testData) / sizeof(testData[0]);
for (size_t i = 0; i < testDataSize; ++i)
{
struct FSeqFileNameSizes sizes;
struct FSeqFileName fileName;
fseqFileNameSizesInit(&sizes);
fseqFileNameParseSizes(testData[i][0], &sizes, FSEQ_STRING_LEN, NULL);
fseqFileNameInit(&fileName);
fseqFileNameSplit2(testData[i][0], &sizes, &fileName);
printf("\"%s\": \"%s\" \"%s\" \"%s\" \"%s\"\n",
testData[i][0],
fileName.path,
fileName.base,
fileName.number,
fileName.extension);
assert(strlen(testData[i][1]) == sizes.path && 0 == memcmp(fileName.path, testData[i][1], sizes.path));
assert(strlen(testData[i][2]) == sizes.base && 0 == memcmp(fileName.base, testData[i][2], sizes.base));
assert(strlen(testData[i][3]) == sizes.number && 0 == memcmp(fileName.number, testData[i][3], sizes.number));
assert(strlen(testData[i][4]) == sizes.extension && 0 == memcmp(fileName.extension, testData[i][4], sizes.extension));
fseqFileNameDel(&fileName);
}
}
void test2()
{
const char negativeNumbers[FSEQ_STRING_LEN] = "render-1000.ext";
const char maxNumberDigits[FSEQ_STRING_LEN] = "9223372036854775807.ext";
const char maxNumberDigits2[FSEQ_STRING_LEN] = "9223372.ext";
struct FSeqFileNameOptions options;
struct FSeqFileNameSizes sizes;
struct FSeqFileName fileName;
fseqFileNameSizesInit(&sizes);
fseqFileNameParseSizes(negativeNumbers, &sizes, FSEQ_STRING_LEN, NULL);
fseqFileNameInit(&fileName);
fseqFileNameSplit2(negativeNumbers, &sizes, &fileName);
assert(0 == memcmp(fileName.path, "", sizes.path));
assert(0 == memcmp(fileName.base, "render-", sizes.base));
assert(0 == memcmp(fileName.number, "1000", sizes.number));
assert(0 == memcmp(fileName.extension, ".ext", sizes.extension));
fseqFileNameDel(&fileName);
fseqFileNameSizesInit(&sizes);
fseqFileNameParseSizes(maxNumberDigits, &sizes, FSEQ_STRING_LEN, NULL);
fseqFileNameInit(&fileName);
fseqFileNameSplit2(maxNumberDigits, &sizes, &fileName);
assert(0 == memcmp(fileName.path, "", sizes.path));
assert(0 == memcmp(fileName.base, "", sizes.base));
assert(0 == memcmp(fileName.number, "9223372036854775807", sizes.number));
assert(0 == memcmp(fileName.extension, ".ext", sizes.extension));
fseqFileNameDel(&fileName);
fseqFileNameSizesInit(&sizes);
fseqFileNameOptionsInit(&options);
fseqFileNameParseSizes(negativeNumbers, &sizes, FSEQ_STRING_LEN, &options);
fseqFileNameInit(&fileName);
fseqFileNameSplit2(negativeNumbers, &sizes, &fileName);
assert(0 == memcmp(fileName.path, "", sizes.path));
assert(0 == memcmp(fileName.base, "render-", sizes.base));
assert(0 == memcmp(fileName.number, "1000", sizes.number));
assert(0 == memcmp(fileName.extension, ".ext", sizes.extension));
fseqFileNameDel(&fileName);
options.negativeNumbers = FSEQ_TRUE;
fseqFileNameSizesInit(&sizes);
fseqFileNameParseSizes(negativeNumbers, &sizes, FSEQ_STRING_LEN, &options);
fseqFileNameInit(&fileName);
fseqFileNameSplit2(negativeNumbers, &sizes, &fileName);
assert(0 == memcmp(fileName.path, "", sizes.path));
assert(0 == memcmp(fileName.base, "render", sizes.base));
assert(0 == memcmp(fileName.number, "-1000", sizes.number));
assert(0 == memcmp(fileName.extension, ".ext", sizes.extension));
fseqFileNameDel(&fileName);
fseqFileNameSizesInit(&sizes);
fseqFileNameParseSizes(maxNumberDigits, &sizes, FSEQ_STRING_LEN, &options);
fseqFileNameInit(&fileName);
fseqFileNameSplit2(maxNumberDigits, &sizes, &fileName);
assert(0 == memcmp(fileName.path, "", sizes.path));
assert(0 == memcmp(fileName.base, "9223372036854775807", sizes.base));
assert(0 == memcmp(fileName.number, "", sizes.number));
assert(0 == memcmp(fileName.extension, ".ext", sizes.extension));
fseqFileNameDel(&fileName);
options.maxNumberDigits = 6;
fseqFileNameSizesInit(&sizes);
fseqFileNameParseSizes(maxNumberDigits2, &sizes, FSEQ_STRING_LEN, &options);
fseqFileNameInit(&fileName);
fseqFileNameSplit2(maxNumberDigits2, &sizes, &fileName);
assert(0 == memcmp(fileName.path, "", sizes.path));
assert(0 == memcmp(fileName.base, "9223372", sizes.base));
assert(0 == memcmp(fileName.number, "", sizes.number));
assert(0 == memcmp(fileName.extension, ".ext", sizes.extension));
fseqFileNameDel(&fileName);
}
void test3()
{
struct FSeqFileNameSizes a;
struct FSeqFileNameSizes b;
fseqFileNameSizesInit(&a);
fseqFileNameSizesInit(&b);
assert(fseqFileNameSizesCompare(&a, &b) != 0);
a.path = 1;
assert(fseqFileNameSizesCompare(&a, &b) == 0);
}
void test4()
{
struct FSeqFileName a;
fseqFileNameInit(&a);
assert(NULL == a.path);
assert(NULL == a.base);
assert(NULL == a.number);
assert(NULL == a.extension);
}
void test5()
{
struct FSeqFileName a;
fseqFileNameInit(&a);
fseqFileNameSplit("/tmp/seq.1.tif", &a, FSEQ_STRING_LEN, NULL);
assert(0 == memcmp("/tmp/", a.path, strlen(a.path)));
assert(0 == memcmp("seq.", a.base, strlen(a.base)));
assert(0 == memcmp("1", a.number, strlen(a.number)));
assert(0 == memcmp(".tif", a.extension, strlen(a.extension)));
fseqFileNameDel(&a);
assert(NULL == a.path);
assert(NULL == a.base);
assert(NULL == a.number);
assert(NULL == a.extension);
}
void test6()
{
char fileNameA[] = "/tmp/seq.1.tif";
char fileNameB[] = "/tmp/seq.2.tif";
struct FSeqFileNameSizes sizesA;
struct FSeqFileNameSizes sizesB;
int match = 0;
fseqFileNameSizesInit(&sizesA);
fseqFileNameParseSizes(fileNameA, &sizesA, FSEQ_STRING_LEN, NULL);
assert(5 == sizesA.path);
assert(4 == sizesA.base);
assert(1 == sizesA.number);
assert(4 == sizesA.extension);
fseqFileNameSizesInit(&sizesB);
fseqFileNameParseSizes(fileNameB, &sizesB, FSEQ_STRING_LEN, NULL);
assert(5 == sizesB.path);
assert(4 == sizesB.base);
assert(1 == sizesB.number);
assert(4 == sizesB.extension);
match = fseqFileNameMatch(fileNameA, &sizesA, fileNameB, &sizesB);
assert(match != 0);
}
void test7()
{
struct FSeqDirEntry entry;
char buf[FSEQ_STRING_LEN];
fseqDirEntryInit(&entry);
fseqDirEntryToString(&entry, buf, FSEQ_FALSE, FSEQ_STRING_LEN);
assert(0 == strlen(buf));
fseqDirEntryDel(&entry);
}
void test8()
{
struct FSeqDirEntry entry;
char buf[FSEQ_STRING_LEN];
fseqDirEntryInit(&entry);
fseqFileNameSplit("/tmp/seq.exr", &entry.fileName, FSEQ_STRING_LEN, NULL);
fseqDirEntryToString(&entry, buf, FSEQ_FALSE, FSEQ_STRING_LEN);
assert(0 == strcmp(buf, "seq.exr"));
fseqDirEntryToString(&entry, buf, FSEQ_TRUE, FSEQ_STRING_LEN);
assert(0 == strcmp(buf, "/tmp/seq.exr"));
fseqDirEntryDel(&entry);
}
void test9()
{
struct FSeqDirEntry entry;
char buf[FSEQ_STRING_LEN];
char buf2[FSEQ_STRING_LEN];
fseqDirEntryInit(&entry);
fseqFileNameSplit("/tmp/seq.1.exr", &entry.fileName, FSEQ_STRING_LEN, NULL);
fseqDirEntryToString(&entry, buf, FSEQ_FALSE, FSEQ_STRING_LEN);
assert(0 == strcmp(buf, "seq.0.exr"));
fseqDirEntryToString(&entry, buf, FSEQ_TRUE, FSEQ_STRING_LEN);
assert(0 == strcmp(buf, "/tmp/seq.0.exr"));
entry.frameMin = 1000;
entry.frameMax = 10000;
fseqDirEntryToString(&entry, buf, FSEQ_FALSE, FSEQ_STRING_LEN);
assert(0 == strcmp(buf, "seq.1000-10000.exr"));
fseqDirEntryToString(&entry, buf, FSEQ_TRUE, FSEQ_STRING_LEN);
assert(0 == strcmp(buf, "/tmp/seq.1000-10000.exr"));
entry.framePadding = 5;
fseqDirEntryToString(&entry, buf, FSEQ_FALSE, FSEQ_STRING_LEN);
assert(0 == strcmp(buf, "seq.01000-10000.exr"));
entry.frameMin = 0;
entry.frameMax = INT64_MAX;
entry.framePadding = 0;
fseqDirEntryToString(&entry, buf, FSEQ_FALSE, FSEQ_STRING_LEN);
snprintf(buf2, FSEQ_STRING_LEN, "seq.%" PRId64 "-%" PRId64 ".exr", (int64_t)0, INT64_MAX);
assert(0 == strcmp(buf, buf2));
fseqDirEntryToString(&entry, buf, FSEQ_TRUE, FSEQ_STRING_LEN);
snprintf(buf2, FSEQ_STRING_LEN, "/tmp/seq.%" PRId64 "-%" PRId64 ".exr", (int64_t)0, INT64_MAX);
assert(0 == strcmp(buf, buf2));
fseqDirEntryDel(&entry);
}
void test10()
{
struct FSeqDirEntry* entry = NULL;
fseqMkdir("tests");
fseqMkdir("tests/test9");
entry = fseqDirList("tests/test9", NULL, NULL);
assert(NULL == entry);
fseqDirListDel(entry);
}
void test11()
{
struct FSeqDirEntry* entry = NULL;
char buf[FSEQ_STRING_LEN];
fseqMkdir("tests");
fseqMkdir("tests/test10");
fseqTouch("tests/test10/file");
fseqTouch("tests/test10/seq.1.exr");
fseqTouch("tests/test10/seq.2.exr");
fseqTouch("tests/test10/seq.3.exr");
fseqTouch("tests/test10/seq.0001.tiff");
fseqTouch("tests/test10/seq.0002.tiff");
fseqTouch("tests/test10/seq.0003.tiff");
entry = fseqDirList("tests/test10", NULL, NULL);
assert(entry != NULL);
size_t matches = 0;
for (const struct FSeqDirEntry* i = entry; i != NULL; i = i->next)
{
fseqDirEntryToString(i, buf, FSEQ_FALSE, FSEQ_STRING_LEN);
if (0 == strcmp(buf, "file"))
{
++matches;
}
else if (0 == strcmp(buf, "seq.1-3.exr"))
{
++matches;
}
else if (0 == strcmp(buf, "seq.0001-0003.tiff"))
{
++matches;
}
}
assert(3 == matches);
fseqDirListDel(entry);
}
void test12()
{
struct FSeqDirEntry* entry = NULL;
struct FSeqDirOptions options;
char buf[FSEQ_STRING_LEN];
char buf2[FSEQ_STRING_LEN];
fseqDirOptionsInit(&options);
options.dotAndDotDotDirs = FSEQ_TRUE;
options.dotFiles = FSEQ_TRUE;
options.sequence = FSEQ_FALSE;
fseqMkdir("tests");
fseqMkdir("tests/test11");
fseqTouch("tests/test11/.dotfile");
fseqTouch("tests/test11/seq.1.exr");
fseqTouch("tests/test11/seq.2.exr");
fseqTouch("tests/test11/seq.3.exr");
snprintf(buf2, FSEQ_STRING_LEN, "tests/test11/large.%" PRId64 ".exr", INT64_MAX);
fseqTouch(buf2);
snprintf(buf2, FSEQ_STRING_LEN, "large.%" PRId64 ".exr", INT64_MAX);
entry = fseqDirList("tests/test11", &options, NULL);
assert(entry != NULL);
size_t matches = 0;
for (const struct FSeqDirEntry* i = entry; i != NULL; i = i->next)
{
fseqDirEntryToString(i, buf, FSEQ_FALSE, FSEQ_STRING_LEN);
if (0 == strcmp(buf, "."))
{
++matches;
}
else if (0 == strcmp(buf, ".."))
{
++matches;
}
else if (0 == strcmp(buf, ".dotfile"))
{
++matches;
}
else if (0 == strcmp(buf, "file"))
{
++matches;
}
else if (0 == strcmp(buf, "seq.1.exr"))
{
++matches;
}
else if (0 == strcmp(buf, "seq.2.exr"))
{
++matches;
}
else if (0 == strcmp(buf, "seq.3.exr"))
{
++matches;
}
else if (0 == strcmp(buf, buf2))
{
++matches;
}
}
assert(7 == matches);
fseqDirListDel(entry);
}
void test13()
{
const int count = 65536;
struct FSeqDirEntry* entry = NULL;
struct FSeqDirOptions options;
char buf[FSEQ_STRING_LEN];
char buf2[FSEQ_STRING_LEN];
fseqDirOptionsInit(&options);
options.dotAndDotDotDirs = FSEQ_TRUE;
options.dotFiles = FSEQ_FALSE;
options.sequence = FSEQ_TRUE;
fseqMkdir("tests");
fseqMkdir("tests/test12");
for (int i = 0; i < count; ++i)
{
snprintf(buf2, FSEQ_STRING_LEN, "tests/test12/large.%08d.exr", i);
fseqTouch(buf2);
}
snprintf(buf2, FSEQ_STRING_LEN, "large.%08d-%08d.exr", 0, count - 1);
entry = fseqDirList("tests/test12", &options, NULL);
assert(entry != NULL);
size_t matches = 0;
for (const struct FSeqDirEntry* i = entry; i != NULL; i = i->next)
{
fseqDirEntryToString(i, buf, FSEQ_FALSE, FSEQ_STRING_LEN);
if (0 == strcmp(buf, buf2))
{
++matches;
}
}
assert(1 == matches);
fseqDirListDel(entry);
}
void test14()
{
struct FSeqDirEntry* entry = NULL;
FSeqBool error = FSEQ_FALSE;
entry = fseqDirList("tests/dir4", NULL, &error);
assert(NULL == entry);
assert(FSEQ_TRUE == error);
fseqDirListDel(entry);
}
void test15()
{
struct FSeqDirEntry* entry = NULL;
char buf[FSEQ_STRING_LEN];
fseqMkdir("tests");
fseqMkdir("tests/测试文件夹");
fseqTouch("tests/测试文件夹/大平原_1.jpg");
fseqTouch("tests/测试文件夹/大平原_2.jpg");
entry = fseqDirList("tests/测试文件夹", NULL, NULL);
assert(entry != NULL);
size_t matches = 0;
for (const struct FSeqDirEntry* i = entry; i != NULL; i = i->next)
{
fseqDirEntryToString(i, buf, FSEQ_FALSE, FSEQ_STRING_LEN);
if (0 == strcmp(buf, "大平原_1-2.jpg"))
{
++matches;
}
}
assert(1 == matches);
fseqDirListDel(entry);
}
int main(int argc, char** argv)
{
test0();
test1();
test2();
test3();
test4();
test5();
test6();
test7();
test8();
test9();
test10();
test11();
test12();
test13();
test14();
test15();
return 0;
}
| 2.15625 | 2 |
2024-11-18T19:46:55.034534+00:00 | 2021-10-07T00:23:54 | 0e44bd82e004652d684f46abec3dc979def15e9b | {
"blob_id": "0e44bd82e004652d684f46abec3dc979def15e9b",
"branch_name": "refs/heads/master",
"committer_date": "2021-10-07T00:23:54",
"content_id": "9fd826fb4ce33e425fc88955f6abf5a53c92a285",
"detected_licenses": [
"MIT"
],
"directory_id": "d0ffcdb7cae5052dc06cb5cbc614de53e0dc1cd9",
"extension": "c",
"filename": "usart_impl.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 272264961,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 11920,
"license": "MIT",
"license_type": "permissive",
"path": "/src/device/usart_impl.c",
"provenance": "stackv2-0055.json.gz:34888",
"repo_name": "cristovaozr/vez-arch-bluepill",
"revision_date": "2021-10-07T00:23:54",
"revision_id": "b6f8370e39b426e4049e97ca6eab69182713c739",
"snapshot_id": "3646b2513204b6bbf88baaa90052ec134a0765e1",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/cristovaozr/vez-arch-bluepill/b6f8370e39b426e4049e97ca6eab69182713c739/src/device/usart_impl.c",
"visit_date": "2023-07-30T14:45:59.144581"
} | stackv2 | /**
* @author Cristóvão Zuppardo Rufino <[email protected]>
* @version 0.1
*
* @copyright Copyright Cristóvão Zuppardo Rufino (c) 2020-2021
* Please see LICENCE file to information regarding licensing
*/
#include "include/device/usart.h"
#include <stdint.h>
#include "include/errors.h"
#include "include/device/pool_op.h"
#include "stm32f103xb.h"
#include "stm32f1xx_ll_gpio.h"
#include "stm32f1xx_ll_bus.h"
#include "stm32f1xx_ll_usart.h"
#include "FreeRTOS.h"
#include "task.h"
#include "queue.h"
#include "semphr.h"
// Number of USARTs available
#define AVAILABLE_USARTS 3
struct usart_priv {
// TX pin
LL_GPIO_InitTypeDef tx_pin_config;
uint32_t tx_pin_apb2_grp1_periph;
GPIO_TypeDef *tx_pin_gpio;
// RX pin
LL_GPIO_InitTypeDef rx_pin_config;
uint32_t rx_pin_apb2_grp1_periph;
GPIO_TypeDef *rx_pin_gpio;
// USART
LL_USART_InitTypeDef config;
uint32_t apb2_grp1_periph;
uint32_t irqn;
USART_TypeDef *usart;
uint32_t index;
};
// Special structure to map RAM stuff for each usart_priv
struct usart_priv_rtos {
QueueHandle_t tx_queue;
QueueHandle_t rx_queue;
SemaphoreHandle_t mutex;
};
static const struct usart_priv usart1_priv = {
.tx_pin_config = {
.Pin = LL_GPIO_PIN_9,
.Mode = LL_GPIO_MODE_ALTERNATE,
.Speed = LL_GPIO_SPEED_FREQ_HIGH,
.OutputType = LL_GPIO_OUTPUT_PUSHPULL,
},
.tx_pin_apb2_grp1_periph = LL_APB2_GRP1_PERIPH_GPIOA,
.tx_pin_gpio = GPIOA,
.rx_pin_config = {
.Pin = LL_GPIO_PIN_10,
.Mode = LL_GPIO_MODE_FLOATING,
.Speed = LL_GPIO_SPEED_FREQ_HIGH,
.OutputType = LL_GPIO_OUTPUT_PUSHPULL,
},
.rx_pin_apb2_grp1_periph = LL_APB2_GRP1_PERIPH_GPIOA,
.rx_pin_gpio = GPIOA,
.config = {
.BaudRate = 115200,
.DataWidth = LL_USART_DATAWIDTH_8B,
.StopBits = LL_USART_STOPBITS_1,
.Parity = LL_USART_PARITY_NONE,
.TransferDirection = LL_USART_DIRECTION_TX_RX,
.HardwareFlowControl = LL_USART_HWCONTROL_NONE,
.OverSampling = LL_USART_OVERSAMPLING_16,
},
.apb2_grp1_periph = LL_APB2_GRP1_PERIPH_USART1,
.irqn = USART1_IRQn,
.usart = USART1,
.index = 0
};
static const struct usart_priv usart2_priv = {
.tx_pin_config = {
.Pin = LL_GPIO_PIN_2,
.Mode = LL_GPIO_MODE_ALTERNATE,
.Speed = LL_GPIO_SPEED_FREQ_HIGH,
.OutputType = LL_GPIO_OUTPUT_PUSHPULL,
},
.tx_pin_apb2_grp1_periph = LL_APB2_GRP1_PERIPH_GPIOA,
.tx_pin_gpio = GPIOA,
.rx_pin_config = {
.Pin = LL_GPIO_PIN_3,
.Mode = LL_GPIO_MODE_FLOATING,
.Speed = LL_GPIO_SPEED_FREQ_HIGH,
.OutputType = LL_GPIO_OUTPUT_PUSHPULL,
},
.rx_pin_apb2_grp1_periph = LL_APB2_GRP1_PERIPH_GPIOA,
.rx_pin_gpio = GPIOA,
.config = {
.BaudRate = 115200,
.DataWidth = LL_USART_DATAWIDTH_8B,
.StopBits = LL_USART_STOPBITS_1,
.Parity = LL_USART_PARITY_NONE,
.TransferDirection = LL_USART_DIRECTION_TX_RX,
.HardwareFlowControl = LL_USART_HWCONTROL_NONE,
.OverSampling = LL_USART_OVERSAMPLING_16,
},
.apb2_grp1_periph = LL_APB1_GRP1_PERIPH_USART2,
.irqn = USART2_IRQn,
.usart = USART2,
.index = 1
};
static const struct usart_priv usart3_priv = {
.tx_pin_config = {
.Pin = LL_GPIO_PIN_10,
.Mode = LL_GPIO_MODE_ALTERNATE,
.Speed = LL_GPIO_SPEED_FREQ_HIGH,
.OutputType = LL_GPIO_OUTPUT_PUSHPULL,
},
.tx_pin_apb2_grp1_periph = LL_APB2_GRP1_PERIPH_GPIOB,
.tx_pin_gpio = GPIOB,
.rx_pin_config = {
.Pin = LL_GPIO_PIN_11,
.Mode = LL_GPIO_MODE_FLOATING,
.Speed = LL_GPIO_SPEED_FREQ_HIGH,
.OutputType = LL_GPIO_OUTPUT_PUSHPULL,
},
.rx_pin_apb2_grp1_periph = LL_APB2_GRP1_PERIPH_GPIOB,
.rx_pin_gpio = GPIOB,
.config = {
.BaudRate = 115200,
.DataWidth = LL_USART_DATAWIDTH_8B,
.StopBits = LL_USART_STOPBITS_1,
.Parity = LL_USART_PARITY_NONE,
.TransferDirection = LL_USART_DIRECTION_TX_RX,
.HardwareFlowControl = LL_USART_HWCONTROL_NONE,
.OverSampling = LL_USART_OVERSAMPLING_16,
},
.apb2_grp1_periph = LL_APB1_GRP1_PERIPH_USART3,
.irqn = USART3_IRQn,
.usart = USART3,
.index = 2
};
static int32_t stm32f103xb_usart_2_3_init(const struct usart_device * const usart);
static int32_t stm32f103xb_usart_1_init(const struct usart_device * const usart);
static int32_t stm32f103xb_usart_write(const struct usart_device * const usart, const void *data, uint32_t size,
uint32_t timeout);
static int32_t stm32f103xb_usart_read(const struct usart_device * const usart, void *data, uint32_t size,
uint32_t timeout);
static int32_t stm32f103xb_usart_poll(const struct usart_device * const usart, enum poll_op op, void *answer);
static const struct usart_operations usart1_ops = {
.usart_init = stm32f103xb_usart_1_init,
.usart_write_op = stm32f103xb_usart_write,
.usart_read_op = stm32f103xb_usart_read,
.usart_poll_op = stm32f103xb_usart_poll,
};
static const struct usart_operations usart_2_3_ops = {
.usart_init = stm32f103xb_usart_2_3_init,
.usart_write_op = stm32f103xb_usart_write,
.usart_read_op = stm32f103xb_usart_read,
.usart_poll_op = stm32f103xb_usart_poll,
};
/*
* This array contains all FreeRTOS stuff because they cannot be inside the priv structure. If they
* were there they would **not** be writable.
*/
static struct usart_priv_rtos priv_rtos[AVAILABLE_USARTS];
const struct usart_device usart1 = {
.ops = &usart1_ops,
.priv = &usart1_priv,
};
const struct usart_device usart2 = {
.ops = &usart_2_3_ops,
.priv = &usart2_priv,
};
const struct usart_device usart3 = {
.ops = &usart_2_3_ops,
.priv = &usart3_priv,
};
// Implementation
static int32_t stm32f103xb_usart_2_3_init(const struct usart_device * const usart)
{
const struct usart_priv *priv = (const struct usart_priv *)usart->priv;
LL_APB1_GRP1_EnableClock(priv->apb2_grp1_periph); // Enables USART clock
// TX pin
LL_APB2_GRP1_EnableClock(priv->tx_pin_apb2_grp1_periph);
LL_GPIO_Init(priv->tx_pin_gpio, (LL_GPIO_InitTypeDef *)&priv->tx_pin_config);
// RX pin
LL_APB2_GRP1_EnableClock(priv->rx_pin_apb2_grp1_periph);
LL_GPIO_Init(priv->rx_pin_gpio, (LL_GPIO_InitTypeDef *)&priv->rx_pin_config);
// USART
LL_USART_Init(priv->usart, (LL_USART_InitTypeDef *)&priv->config);
LL_USART_ConfigAsyncMode(priv->usart);
LL_USART_Enable(priv->usart);
// Enables FreeRTOS queues and mutexes
priv_rtos[priv->index].tx_queue = xQueueCreate(64, sizeof(uint8_t));
priv_rtos[priv->index].rx_queue = xQueueCreate(64, sizeof(uint8_t));
priv_rtos[priv->index].mutex = xSemaphoreCreateMutex();
// Enables IRQ for USART
LL_USART_EnableIT_RXNE(priv->usart);
NVIC_SetPriority(priv->irqn, NVIC_EncodePriority(NVIC_GetPriorityGrouping(), 5, 0));
NVIC_EnableIRQ(priv->irqn);
return 0;
}
// This has to be different because the EnableClock for USART1 is different from USART2 and USART3
static int32_t stm32f103xb_usart_1_init(const struct usart_device * const usart)
{
const struct usart_priv *priv = (const struct usart_priv *)usart->priv;
LL_APB2_GRP1_EnableClock(priv->apb2_grp1_periph); // Enables USART clock
// TX pin
LL_APB2_GRP1_EnableClock(priv->tx_pin_apb2_grp1_periph);
LL_GPIO_Init(priv->tx_pin_gpio, (LL_GPIO_InitTypeDef *)&priv->tx_pin_config);
// RX pin
LL_APB2_GRP1_EnableClock(priv->rx_pin_apb2_grp1_periph);
LL_GPIO_Init(priv->rx_pin_gpio, (LL_GPIO_InitTypeDef *)&priv->rx_pin_config);
// USART
LL_USART_Init(priv->usart, (LL_USART_InitTypeDef *)&priv->config);
LL_USART_ConfigAsyncMode(priv->usart);
LL_USART_Enable(priv->usart);
priv_rtos[priv->index].tx_queue = xQueueCreate(64, sizeof(uint8_t));
priv_rtos[priv->index].rx_queue = xQueueCreate(64, sizeof(uint8_t));
priv_rtos[priv->index].mutex = xSemaphoreCreateMutex();
LL_USART_EnableIT_RXNE(priv->usart);
NVIC_SetPriority(priv->irqn, NVIC_EncodePriority(NVIC_GetPriorityGrouping(), 5, 0));
NVIC_EnableIRQ(priv->irqn);
return 0;
}
static int32_t stm32f103xb_usart_write(const struct usart_device * const usart, const void *data, uint32_t size,
uint32_t timeout)
{
const struct usart_priv *priv = (const struct usart_priv *)usart->priv;
const uint8_t *udata = (const uint8_t *)data;
uint32_t i;
if (priv_rtos[priv->index].tx_queue == NULL || priv_rtos[priv->index].mutex == NULL) {
return E_NOT_INITIALIZED;
}
xSemaphoreTake(priv_rtos[priv->index].mutex, portMAX_DELAY);
for(i = 0; i < size; i++) {
if (xQueueSend(priv_rtos[priv->index].tx_queue, &udata[i], timeout) == pdFAIL) {
break; // Timed-out. Must stop and return now. A timeout is not an error!
} else {
LL_USART_EnableIT_TXE(priv->usart);
}
}
xSemaphoreGive(priv_rtos[priv->index].mutex);
return (int32_t)i;
}
static int32_t stm32f103xb_usart_read(const struct usart_device * const usart, void *data, uint32_t size,
uint32_t timeout)
{
const struct usart_priv *priv = (const struct usart_priv *)usart->priv;
uint8_t *udata = (uint8_t *)data;
uint32_t i;
int32_t ret;
if (priv_rtos[priv->index].rx_queue == NULL || priv_rtos[priv->index].mutex == NULL) {
ret = E_NOT_INITIALIZED;
goto exit;
}
xSemaphoreTake(priv_rtos[priv->index].mutex, portMAX_DELAY);
for(i = 0; i < size; i++) {
if (xQueueReceive(priv_rtos[priv->index].rx_queue, &udata[i], timeout) == pdFAIL) {
ret = E_TIMEOUT;
goto exit;
}
}
ret = i;
exit:
xSemaphoreGive(priv_rtos[priv->index].mutex);
return ret;
}
static int32_t stm32f103xb_usart_poll(const struct usart_device * const usart, enum poll_op op, void *answer)
{
const struct usart_priv *priv = (const struct usart_priv *)usart->priv;
int32_t ret;
switch (op) {
case POLL_RX_QUEUE_SIZE: {
if (priv_rtos[priv->index].rx_queue == NULL) {
ret = E_NOT_INITIALIZED;
goto exit;
}
*((uint32_t *)answer) = uxQueueMessagesWaiting(priv_rtos[priv->index].rx_queue);
ret = E_SUCCESS;
break;
}
default:
ret = E_POLLOP_INVALID;
goto exit;
}
exit:
return ret;
}
// IRQ Handlers
static void USART_IRQHandler(const struct usart_device * const usart)
{
BaseType_t context_switch;
const struct usart_priv *priv = (const struct usart_priv *)usart->priv;
if (LL_USART_IsActiveFlag_TXE(priv->usart)) {
while (LL_USART_IsActiveFlag_TXE(priv->usart)) {
uint8_t byte;
if (xQueueReceiveFromISR(priv_rtos[priv->index].tx_queue, &byte, &context_switch) == pdFAIL) {
LL_USART_DisableIT_TXE(priv->usart);
break; // Queue empty and can safelly disable TXE
}
LL_USART_TransmitData8(priv->usart, byte);
}
}
if (LL_USART_IsActiveFlag_RXNE(priv->usart)) {
while(LL_USART_IsActiveFlag_RXNE(priv->usart)) {
uint8_t byte = LL_USART_ReceiveData8(priv->usart);
xQueueSendFromISR(priv_rtos[priv->index].rx_queue, &byte, &context_switch);
// Could not enqueue anymore because queue is full
}
}
portYIELD_FROM_ISR(context_switch);
}
/**
* @brief This function handles USART1 global interrupt.
*/
void USART1_IRQHandler(void)
{
USART_IRQHandler(&usart1);
}
/**
* @brief This function handles USART2 global interrupt.
*/
void USART2_IRQHandler(void)
{
USART_IRQHandler(&usart2);
}
/**
* @brief This function handles USART3 global interrupt.
*/
void USART3_IRQHandler(void)
{
USART_IRQHandler(&usart3);
}
| 2.421875 | 2 |
2024-11-18T19:46:55.101657+00:00 | 2018-03-02T05:36:21 | 47a0845f18a9bb2cfced6bdde61f310ca97da0df | {
"blob_id": "47a0845f18a9bb2cfced6bdde61f310ca97da0df",
"branch_name": "refs/heads/master",
"committer_date": "2018-03-02T05:36:21",
"content_id": "5111f192b237abe5df7ba1a66365d5404a62e769",
"detected_licenses": [
"MIT"
],
"directory_id": "b727e7ce9f48829673712581327f0ac909468e74",
"extension": "c",
"filename": "dump.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 120717568,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1747,
"license": "MIT",
"license_type": "permissive",
"path": "/dump.c",
"provenance": "stackv2-0055.json.gz:35017",
"repo_name": "Brianpan/xv6_for_education",
"revision_date": "2018-03-02T05:36:21",
"revision_id": "ab1745a536837ed1253579930bc9539bc14d6621",
"snapshot_id": "b4ed704bf09fa64adc3e42d7c60d1a8833873abb",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Brianpan/xv6_for_education/ab1745a536837ed1253579930bc9539bc14d6621/dump.c",
"visit_date": "2021-05-02T14:19:48.653727"
} | stackv2 | #include "types.h"
#include "stat.h"
#include "user.h"
#include "syscall.h"
#define PGSIZE 4096
void dump_mem()
{
/* Fork a new process to play with */
/* We don't have a good way to list all pids in the system
so forking a new process works for testing */
uint procMemSize = (uint) sbrk(0);
uint pid = fork();
if(pid == 0)
{
while(1)
{
sleep(5);
};
}
/* parent dumps memory of the child */
char *buf = malloc(PGSIZE);
memset(buf, 0, PGSIZE);
uint address = 0x0;
// VA is from 0 to p->sz
// based on allouvm -> mappages VA is the oldsz ( a = PGROUNDUP(oldsz); )
int reachText = 1;
int reachGuard = 0;
int reachStack = 0;
while( procMemSize > 0 )
{
memset(buf, 0, PGSIZE);
int flag = dump(pid, (void*) address, (void*)buf, PGSIZE);
if( flag < 0 )
printf(1, "size not matched!");
// define which part is Text, Guard Page, Stack, Heap
if(reachText == 1)
{
printf(1, "\n-------Text Page--------\n");
reachText = 0;
}
else if(reachGuard == 0 && flag == 1)
{
printf(1, "\n-------Guard Page--------\n");
reachGuard = 1;
}
else if(reachGuard == 1 && flag == 0)
{
printf(1, "\n-------Guard Page End User Stack Page--------\n");
reachGuard = 0;
reachStack = 1;
}
else if(reachStack == 1 && flag == 0)
{
printf(1, "\n-------User Stack End Heap Page--------\n");
reachStack = 0;
}
printf(1, "\n");
// print the address
int i;
for(i=0;i<PGSIZE/4;i++)
{
if(i%4 == 0)
{
printf(1, "\n");
printf(1, "0x%x: ", address);
}
uint val = *(uint*)(buf+i*4);
printf(1, "0x%x ", val);
address += 4;
}
// increment
procMemSize -= PGSIZE;
}
printf(1, "\n");
}
int main(int argc, char* argv[])
{
dump_mem();
exit();
} | 3.09375 | 3 |
2024-11-18T20:00:26.447556+00:00 | 2022-03-01T22:33:16 | 2853cf7ee245eaaffcd0ed509b307f3c5d690d15 | {
"blob_id": "2853cf7ee245eaaffcd0ed509b307f3c5d690d15",
"branch_name": "refs/heads/master",
"committer_date": "2022-12-12T17:03:27",
"content_id": "aad1514660728e85382d5f4ede045e83129a1f60",
"detected_licenses": [
"MIT"
],
"directory_id": "c7308b6f7534ec1d08d02ff7882020636f42a2cb",
"extension": "c",
"filename": "impl.c",
"fork_events_count": 10,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 2223381,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4751,
"license": "MIT",
"license_type": "permissive",
"path": "/src/cc1/out/impl.c",
"provenance": "stackv2-0055.json.gz:242855",
"repo_name": "bobrippling/ucc-c-compiler",
"revision_date": "2022-03-01T22:33:16",
"revision_id": "d0283673261bbd5d872057ee169378fdf349a6fa",
"snapshot_id": "0d8808a31bb8b0b6403d1e757b866753ac969e23",
"src_encoding": "UTF-8",
"star_events_count": 74,
"url": "https://raw.githubusercontent.com/bobrippling/ucc-c-compiler/d0283673261bbd5d872057ee169378fdf349a6fa/src/cc1/out/impl.c",
"visit_date": "2023-06-21T22:25:07.825365"
} | stackv2 | #include <stdio.h>
#include <stdarg.h>
#include <assert.h>
#include "../../util/util.h"
#include "../../util/platform.h"
#include "../decl.h"
#include "../op.h"
#include "../type_nav.h"
#include "../macros.h"
#include "val.h"
#include "asm.h"
#include "impl.h"
#include "write.h"
#include "out.h"
#include "virt.h"
void impl_comment(out_ctx *octx, const char *fmt, va_list l)
{
out_asm2(octx, P_NO_LIVEDUMP | P_NO_NL, "/* ");
out_asmv(octx, P_NO_LIVEDUMP | P_NO_INDENT | P_NO_NL, fmt, l);
out_asm2(octx, P_NO_LIVEDUMP | P_NO_INDENT, " */");
}
enum flag_cmp op_to_flag(enum op_type op)
{
switch(op){
#define OP(x) case op_ ## x: return flag_ ## x
OP(eq);
OP(ne);
OP(le);
OP(lt);
OP(ge);
OP(gt);
OP(signbit);
OP(no_signbit);
#undef OP
case op_multiply:
case op_divide:
case op_modulus:
case op_plus:
case op_minus:
case op_xor:
case op_or:
case op_and:
case op_orsc:
case op_andsc:
case op_shiftl:
case op_shiftr:
case op_not:
case op_bnot:
case op_unknown:
break;
}
ICE("invalid op");
return -1;
}
const char *flag_cmp_to_str(enum flag_cmp cmp)
{
switch(cmp){
CASE_STR_PREFIX(flag, eq);
CASE_STR_PREFIX(flag, ne);
CASE_STR_PREFIX(flag, le);
CASE_STR_PREFIX(flag, lt);
CASE_STR_PREFIX(flag, ge);
CASE_STR_PREFIX(flag, gt);
CASE_STR_PREFIX(flag, overflow);
CASE_STR_PREFIX(flag, no_overflow);
CASE_STR_PREFIX(flag, signbit);
CASE_STR_PREFIX(flag, no_signbit);
}
return NULL;
}
int impl_reg_is_callee_save(type *fnty, const struct vreg *r)
{
unsigned i, n;
const struct vreg *csaves;
csaves = impl_callee_save_regs(fnty, &n);
for(i = 0; i < n; i++)
if(vreg_eq(r, &csaves[i]))
return 1;
return 0;
}
const char *impl_val_str(const out_val *vs, int deref)
{
static char buf[VAL_STR_SZ];
return impl_val_str_r(buf, vs, deref);
}
static void impl_overlay_mem_reg(
out_ctx *octx,
unsigned memsz, unsigned nregs,
struct vreg regs[], int mem2reg,
const out_val *ptr)
{
const unsigned pws = platform_word_size();
struct vreg *cur_reg = regs;
unsigned reg_i = 0;
assert(ptr->type != V_SPILT && "possible mishandling of spilt register for mem/reg overlay");
if(memsz == 0){
out_val_release(octx, ptr);
return;
}
UCC_ASSERT(
nregs * pws >= memsz,
"not enough registers for memory overlay");
out_comment(octx,
"overlay, %s2%s(%u)",
mem2reg ? "mem" : "reg",
mem2reg ? "reg" : "mem",
memsz);
if(!mem2reg){
/* reserve all registers so we don't accidentally wipe before the spill */
for(reg_i = 0; reg_i < nregs; reg_i++)
v_reserve_reg(octx, ®s[reg_i]);
}
for(;; cur_reg++, reg_i++){
/* read/write whatever size is required */
type *this_ty;
unsigned this_sz;
if(cur_reg->is_float){
UCC_ASSERT(memsz >= 4, "float for memsz %u?", memsz);
this_ty = type_nav_btype(
cc1_type_nav,
memsz > 4 ? type_double : type_float);
}else{
this_ty = type_nav_MAX_FOR(cc1_type_nav, memsz, 0);
}
this_sz = type_size(this_ty, NULL);
UCC_ASSERT(this_sz <= memsz, "reading/writing too much memory");
ptr = out_change_type(octx, ptr, type_ptr_to(this_ty));
out_val_retain(octx, ptr);
if(mem2reg){
const out_val *fetched;
/* can use impl_deref, as we have a register already,
* and know that the memory is an lvalue and not a bitfield
*
* this means we can load straight into the desired register
*/
fetched = impl_deref(octx, ptr, cur_reg, NULL);
UCC_ASSERT(reg_i < nregs, "reg oob");
if(fetched->type != V_REG || !vreg_eq(&fetched->bits.regoff.reg, cur_reg)){
/* move to register */
v_freeup_reg(octx, cur_reg);
fetched = v_to_reg_given(octx, fetched, cur_reg);
}
out_flush_volatile(octx, fetched);
v_reserve_reg(octx, cur_reg); /* prevent changes */
}else{
const out_val *vreg = v_new_reg(octx, NULL, this_ty, cur_reg);
out_store(octx, ptr, vreg);
}
memsz -= this_sz;
/* early termination */
if(memsz == 0)
break;
/* increment our memory pointer */
ptr = out_change_type(
octx,
ptr,
type_ptr_to(type_nav_btype(cc1_type_nav, type_uchar)));
ptr = out_op(octx, op_plus,
ptr,
out_new_l(
octx,
type_nav_btype(cc1_type_nav, type_intptr_t),
pws));
}
out_val_release(octx, ptr);
/* done, unreserve all registers */
for(reg_i = 0; reg_i < nregs; reg_i++)
v_unreserve_reg(octx, ®s[reg_i]);
}
void impl_overlay_mem2regs(
out_ctx *octx,
unsigned memsz, unsigned nregs,
struct vreg regs[],
const out_val *ptr)
{
impl_overlay_mem_reg(octx, memsz, nregs, regs, 1, ptr);
}
void impl_overlay_regs2mem(
out_ctx *octx,
unsigned memsz, unsigned nregs,
struct vreg regs[],
const out_val *ptr)
{
impl_overlay_mem_reg(octx, memsz, nregs, regs, 0, ptr);
}
| 2.0625 | 2 |
2024-11-18T20:00:26.636264+00:00 | 2018-11-17T05:52:58 | 77e33bba07877c094a60c234b34ccc7206fd7a92 | {
"blob_id": "77e33bba07877c094a60c234b34ccc7206fd7a92",
"branch_name": "refs/heads/master",
"committer_date": "2018-11-17T05:52:58",
"content_id": "6a50c720180346e7bab57d9c2491dc86d89352d1",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "51051a7bb37da0ab7382a4fc1d13135d9657120d",
"extension": "c",
"filename": "updates.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": 5658,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/src/updates.c",
"provenance": "stackv2-0055.json.gz:242985",
"repo_name": "charygao/libportable",
"revision_date": "2018-11-17T05:52:58",
"revision_id": "6bc7b6f98a5740bf4a290c3ab5f09afde265dc0c",
"snapshot_id": "caf69bab36461619255e96956339fe42d39c67e2",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/charygao/libportable/6bc7b6f98a5740bf4a290c3ab5f09afde265dc0c/src/updates.c",
"visit_date": "2020-04-08T08:23:08.975430"
} | stackv2 | #include "inipara.h"
#include "winapis.h"
#include "share_lock.h"
#include <stdio.h>
#include <tlhelp32.h>
#include <shlobj.h>
#ifdef DISABLE_SAFE
static _NtCreateUserProcess sNtCreateUserProcess,
pNtCreateUserProcess;
static _CreateProcessInternalW sCreateProcessInternalW,
pCreateProcessInternalW;
#else
extern _NtCreateUserProcess sNtCreateUserProcess;
extern _NtCreateUserProcess pNtCreateUserProcess;
extern _CreateProcessInternalW sCreateProcessInternalW;
extern _CreateProcessInternalW pCreateProcessInternalW;
#endif
uint32_t WINAPI _getppid(void)
{
PROCESSENTRY32W pe32;
bool b_more;
uint32_t m_pid = GetCurrentProcessId();
HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0);
if( hSnapshot == INVALID_HANDLE_VALUE )
{
#ifdef _LOGDEBUG
logmsg("CreateToolhelp32Snapshot error %lu\n",GetLastError());
#endif
return 0;
}
b_more = Process32FirstW(hSnapshot,&pe32);
while (b_more)
{
if (m_pid == (uint32_t)pe32.th32ProcessID)
{
m_pid = (uint32_t)pe32.th32ParentProcessID;
break;
}
b_more = Process32NextW(hSnapshot,&pe32);
}
CloseHandle(hSnapshot);
return m_pid;
}
NTSTATUS WINAPI
NtCreateUserProcessFn(PHANDLE ProcessHandle,PHANDLE ThreadHandle,
ACCESS_MASK ProcessDesiredAccess,
ACCESS_MASK ThreadDesiredAccess,
POBJECT_ATTRIBUTES ProcessObjectAttributes,
POBJECT_ATTRIBUTES ThreadObjectAttributes,
ULONG CreateProcessFlags,
ULONG CreateThreadFlags,
PRTL_USER_PROCESS_PARAMETERS ProcessParameters,
PPS_CREATE_INFO CreateInfo,
PPS_ATTRIBUTE_LIST AttributeList)
{
NTSTATUS status = STATUS_ERROR;
bool fn = false;
if (is_browser(ProcessParameters->ImagePathName.Buffer))
{
if (ProcessParameters->CommandLine.Length > 1)
{
fn = is_browser(ProcessParameters->CommandLine.Buffer);
}
}
status = sNtCreateUserProcess(ProcessHandle, ThreadHandle,
ProcessDesiredAccess, ThreadDesiredAccess,
ProcessObjectAttributes, ThreadObjectAttributes,
CreateProcessFlags, CreateThreadFlags, ProcessParameters,
CreateInfo, AttributeList);
if (NT_SUCCESS(status))
{
if (fn)
{
#ifdef _LOGDEBUG
logmsg("firefox restart,new main_id is %lu!\n", GetProcessId(*ProcessHandle));
#endif
set_process_pid(GetProcessId(*ProcessHandle));
}
}
return status;
}
bool WINAPI
CreateProcessInternalFn(HANDLE hToken,
LPCWSTR lpApplicationName,
LPWSTR lpCommandLine,
LPSECURITY_ATTRIBUTES lpProcessAttributes,
LPSECURITY_ATTRIBUTES lpThreadAttributes,
bool bInheritHandles,
DWORD dwCreationFlags,
LPVOID lpEnvironment,
LPCWSTR lpCurrentDirectory,
LPSTARTUPINFOW lpStartupInfo,
LPPROCESS_INFORMATION lpProcessInformation,
PHANDLE hNewToken)
{
bool ret= false;
bool fn = false;
LPWSTR lpfile = lpCommandLine;
WCHAR lpFullPath[MAX_PATH+1]= {0};
if (lpApplicationName && wcslen(lpApplicationName)>1)
{
lpfile = (LPWSTR)lpApplicationName;
}
if (lpCommandLine && wcslen(lpCommandLine)>1)
{
fn = is_browser(lpCommandLine);
}
ret = sCreateProcessInternalW(hToken,lpApplicationName,lpCommandLine,lpProcessAttributes,
lpThreadAttributes,bInheritHandles,dwCreationFlags,
lpEnvironment,lpCurrentDirectory,
lpStartupInfo,lpProcessInformation,hNewToken);
if (ret)
{
if (fn)
{
#ifdef _LOGDEBUG
logmsg("firefox restart,new main_id is %lu!\n", lpProcessInformation->dwProcessId);
#endif
set_process_pid(lpProcessInformation->dwProcessId);
}
}
return ret;
}
bool WINAPI init_watch(void)
{
HMODULE hNtdll, hKernel;
DWORD ver = get_os_version();
hNtdll = GetModuleHandleW(L"ntdll.dll");
hKernel = GetModuleHandleW(L"kernel32.dll");
#ifndef DISABLE_SAFE
if (read_appint(L"General",L"SafeEx") > 0)
{
return true;
}
#endif
if (hNtdll == NULL || hKernel == NULL)
{
return false;
}
if (ver > 503) /* vista - win10 */
{
pNtCreateUserProcess = (_NtCreateUserProcess)GetProcAddress(hNtdll, "NtCreateUserProcess");
if (!creator_hook(pNtCreateUserProcess, NtCreateUserProcessFn, (LPVOID*)&sNtCreateUserProcess))
{
#ifdef _LOGDEBUG
logmsg("NtCreateUserProcess hook failed!\n");
#endif
return false;
}
}
else /* winxp-2003 */
{
pCreateProcessInternalW = (_CreateProcessInternalW)GetProcAddress(hKernel, "CreateProcessInternalW");
if (!creator_hook(pCreateProcessInternalW, CreateProcessInternalFn, (LPVOID*)&sCreateProcessInternalW))
{
#ifdef _LOGDEBUG
logmsg("pCreateProcessInternalW hook failed!\n");
#endif
return false;
}
}
return true;
}
| 2.078125 | 2 |
2024-11-18T20:26:00.981009+00:00 | 2019-03-21T06:52:03 | 33dc7c8528d46daaa1502f5124046ecc9054a610 | {
"blob_id": "33dc7c8528d46daaa1502f5124046ecc9054a610",
"branch_name": "refs/heads/master",
"committer_date": "2019-03-21T06:52:03",
"content_id": "bb6beec20a8e77831b481fcb658be357b8752a37",
"detected_licenses": [
"MIT"
],
"directory_id": "217b893ece6ce7e7d13a9a718c03a49842943ed0",
"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": 119136779,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2134,
"license": "MIT",
"license_type": "permissive",
"path": "/user/main.c",
"provenance": "stackv2-0056.json.gz:257324",
"repo_name": "eeyrw/stm32-midi-device",
"revision_date": "2019-03-21T06:52:03",
"revision_id": "aac4d13976a4949a6c6cf6b02d0f8b7b4ad27ae2",
"snapshot_id": "66bc2eef4e89d5cd84a2a82ffd709887fdc728c5",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/eeyrw/stm32-midi-device/aac4d13976a4949a6c6cf6b02d0f8b7b4ad27ae2/user/main.c",
"visit_date": "2021-10-24T01:13:22.048420"
} | stackv2 | //
// Created by YangYongbao on 2017/3/16.
//
#include "stm32f10x.h"
#include "stm32f10x_conf.h"
#include "FreeRTOS.h"
#include "task.h"
#include "uart_log.h"
#include "hal.h"
#include "usb_lib.h"
#include "usb_desc.h"
#include "usb_pwr.h"
extern __IO uint8_t Receive_Buffer[64];
extern __IO uint32_t Receive_length;
extern __IO uint32_t length;
uint8_t Send_Buffer[64];
uint32_t packet_sent = 1;
uint32_t packet_receive = 1;
void Delay(__IO uint32_t nCount)
{
for (; nCount != 0; nCount--)
;
}
void RCC_Configuration(void)
{
/* GPIOA, GPIOB clock enable */
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_GPIOC, ENABLE);
}
void GPIO_Configuration(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_13;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOC, &GPIO_InitStructure);
}
void vTaskFunction(void *pvParameters)
{
debug("start task");
while (1)
{
GPIO_ResetBits(GPIOC, GPIO_Pin_13);
debug("led on ");
vTaskDelay(100);
GPIO_SetBits(GPIOC, GPIO_Pin_13);
debug("led off ");
vTaskDelay(100);
}
}
void vTaskUsb(void *pvParameters)
{
while (1)
{
if (bDeviceState == CONFIGURED)
{
CDC_Receive_DATA();
/*Check to see if we have data yet */
if (Receive_length != 0)
{
if (packet_sent == 1)
CDC_Send_DATA((unsigned char *)Receive_Buffer, Receive_length);
Receive_length = 0;
}
}
}
}
int main()
{
// init uart log
uart_log_init();
RCC_Configuration();
GPIO_Configuration();
Set_System();
Set_USBClock();
USB_Interrupts_Config();
USB_Init();
debug("start main ");
const char *pcTextForTask1 = "Task1 is running\r\n";
xTaskCreate(vTaskFunction, "Task 1", 64, (void *)pcTextForTask1, 1, NULL);
xTaskCreate(vTaskUsb, "Task usb", 1024, NULL, 1, NULL);
vTaskStartScheduler();
while (1)
;
return 0;
} | 2.578125 | 3 |
2024-11-18T20:26:01.227823+00:00 | 2021-10-18T09:54:58 | 6851d3e537272de065417b8fd137fd245764b245 | {
"blob_id": "6851d3e537272de065417b8fd137fd245764b245",
"branch_name": "refs/heads/main",
"committer_date": "2021-10-18T09:54:58",
"content_id": "ae875d2db4200bec5f2f89360b39741b656bdb1c",
"detected_licenses": [
"MIT"
],
"directory_id": "b1f7b54161dbeebea764d11fcaaf8cacaa30f4e1",
"extension": "c",
"filename": "mx_strlen.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": 174,
"license": "MIT",
"license_type": "permissive",
"path": "/src/mx_strlen.c",
"provenance": "stackv2-0056.json.gz:257711",
"repo_name": "dbredykhyn/dblibmx",
"revision_date": "2021-10-18T09:54:58",
"revision_id": "45eb3d40e00b3b623e789c0d9b7475e8e7ad975b",
"snapshot_id": "844407b705b5918817340a0e53078f30bf08e5f1",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/dbredykhyn/dblibmx/45eb3d40e00b3b623e789c0d9b7475e8e7ad975b/src/mx_strlen.c",
"visit_date": "2023-09-03T18:33:30.843266"
} | stackv2 | #include "libmx.h"
int mx_strlen(const char *str) {
int length = 0;
if(str[0] == '\0') return length;
while (*str != '\0') {
length++;
str++;
}
return length;
}
| 2.28125 | 2 |
2024-11-18T20:26:01.404585+00:00 | 2021-10-03T00:46:42 | d45b7937f2fce4211912c24dec109e13cf6416d7 | {
"blob_id": "d45b7937f2fce4211912c24dec109e13cf6416d7",
"branch_name": "refs/heads/main",
"committer_date": "2021-10-03T00:46:42",
"content_id": "a1faf3f8af5ac2bc468e1e845bd92e9318d396ae",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "976dee047265578af17e8a53c4011e799cb24c34",
"extension": "h",
"filename": "logger.h",
"fork_events_count": 0,
"gha_created_at": "2021-10-01T08:24:28",
"gha_event_created_at": "2021-10-01T08:24:29",
"gha_language": null,
"gha_license_id": "Apache-2.0",
"github_id": 412386960,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2183,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/engine/src/core/logger.h",
"provenance": "stackv2-0056.json.gz:257970",
"repo_name": "Tekh-ops/kohi",
"revision_date": "2021-10-03T00:46:42",
"revision_id": "2b29ec8fbfd3c7168910d3f08576814152c05092",
"snapshot_id": "60686c500cc7dd21947d9358278068958b881e33",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Tekh-ops/kohi/2b29ec8fbfd3c7168910d3f08576814152c05092/engine/src/core/logger.h",
"visit_date": "2023-08-27T11:42:29.078221"
} | stackv2 | #pragma once
#include "defines.h"
#define LOG_WARN_ENABLED 1
#define LOG_INFO_ENABLED 1
#define LOG_DEBUG_ENABLED 1
#define LOG_TRACE_ENABLED 1
// Disable debug and trace logging for release builds.
#if KRELEASE == 1
#define LOG_DEBUG_ENABLED 0
#define LOG_TRACE_ENABLED 0
#endif
typedef enum log_level {
LOG_LEVEL_FATAL = 0,
LOG_LEVEL_ERROR = 1,
LOG_LEVEL_WARN = 2,
LOG_LEVEL_INFO = 3,
LOG_LEVEL_DEBUG = 4,
LOG_LEVEL_TRACE = 5
} log_level;
/**
* @brief Initializes logging system. Call twice; once with state = 0 to get required memory size,
* then a second time passing allocated memory to state.
*
* @param memory_requirement A pointer to hold the required memory size of internal state.
* @param state 0 if just requesting memory requirement, otherwise allocated block of memory.
* @return b8 True on success; otherwise false.
*/
b8 initialize_logging(u64* memory_requirement, void* state);
void shutdown_logging(void* state);
KAPI void log_output(log_level level, const char* message, ...);
// Logs a fatal-level message.
#define KFATAL(message, ...) log_output(LOG_LEVEL_FATAL, message, ##__VA_ARGS__);
#ifndef KERROR
// Logs an error-level message.
#define KERROR(message, ...) log_output(LOG_LEVEL_ERROR, message, ##__VA_ARGS__);
#endif
#if LOG_WARN_ENABLED == 1
// Logs a warning-level message.
#define KWARN(message, ...) log_output(LOG_LEVEL_WARN, message, ##__VA_ARGS__);
#else
// Does nothing when LOG_WARN_ENABLED != 1
#define KWARN(message, ...)
#endif
#if LOG_INFO_ENABLED == 1
// Logs a info-level message.
#define KINFO(message, ...) log_output(LOG_LEVEL_INFO, message, ##__VA_ARGS__);
#else
// Does nothing when LOG_INFO_ENABLED != 1
#define KINFO(message, ...)
#endif
#if LOG_DEBUG_ENABLED == 1
// Logs a debug-level message.
#define KDEBUG(message, ...) log_output(LOG_LEVEL_DEBUG, message, ##__VA_ARGS__);
#else
// Does nothing when LOG_DEBUG_ENABLED != 1
#define KDEBUG(message, ...)
#endif
#if LOG_TRACE_ENABLED == 1
// Logs a trace-level message.
#define KTRACE(message, ...) log_output(LOG_LEVEL_TRACE, message, ##__VA_ARGS__);
#else
// Does nothing when LOG_TRACE_ENABLED != 1
#define KTRACE(message, ...)
#endif | 2.328125 | 2 |
2024-11-18T20:26:01.474963+00:00 | 2015-10-21T02:24:55 | b66bd6532556a6cd2a1d898ea39151a293539926 | {
"blob_id": "b66bd6532556a6cd2a1d898ea39151a293539926",
"branch_name": "refs/heads/master",
"committer_date": "2015-10-21T02:24:55",
"content_id": "f44c192c2eb3562b9306c12224cd79be63c86086",
"detected_licenses": [
"MIT"
],
"directory_id": "4ec889227c79e28253dfbff5a6de7a2dd1047658",
"extension": "h",
"filename": "comm_internal.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 24946731,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 967,
"license": "MIT",
"license_type": "permissive",
"path": "/include/comm_internal.h",
"provenance": "stackv2-0056.json.gz:258099",
"repo_name": "Coderlane/c-longboard-api",
"revision_date": "2015-10-21T02:24:55",
"revision_id": "d33c69280fc3a346431c367961b2f5eaca4458db",
"snapshot_id": "0a6247516a432af3c098dbe2b13ea59b4ec293bb",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Coderlane/c-longboard-api/d33c69280fc3a346431c367961b2f5eaca4458db/include/comm_internal.h",
"visit_date": "2021-01-19T14:57:07.422646"
} | stackv2 | /**
* @file comm_internal.h
* @brief
* @author Travis Lane
* @version 0.0.1
* @date 2015-10-02
*/
#ifndef LONGBOARD_COMM_INTERNAL
#define LONGBOARD_COMM_INTERNAL
#include "comm.h"
typedef int (*lb_comm_generic_func)(struct lb_comm_t *);
typedef int (*lb_comm_get_float_func)(struct lb_comm_t*, float *out);
struct lb_comm_t {
enum lb_comm_type_t lbc_type;
void *lbc_ctx;
/** Function Pointers **/
lb_comm_generic_func lbc_delete_func;
lb_comm_generic_func lbc_open_func;
lb_comm_generic_func lbc_close_func;
lb_comm_get_float_func lbc_get_power_func;
};
struct lb_comm_bt_t {
const char *lbc_bt_addr;
int lbc_bt_socket;
};
struct lb_comm_t *lb_comm_new(enum lb_comm_type_t type, void *ctx);
int lb_comm_bt_delete(struct lb_comm_t *comm);
int lb_comm_bt_open(struct lb_comm_t *comm);
int lb_comm_bt_close(struct lb_comm_t *comm);
int lb_comm_bt_get_power(struct lb_comm_t *comm, float *out_power);
#endif /* LONGBOARD_COMM_INTERNAL */
| 2.328125 | 2 |
2024-11-18T20:59:38.491984+00:00 | 2015-10-08T11:00:20 | 5779ebc5e58f6a00c8e605d0575f8f89c0fdefd2 | {
"blob_id": "5779ebc5e58f6a00c8e605d0575f8f89c0fdefd2",
"branch_name": "refs/heads/master",
"committer_date": "2015-10-08T11:00:20",
"content_id": "4ce3a98e7d6ef3e851b73dfb9f9d0b065f4692fc",
"detected_licenses": [
"MIT"
],
"directory_id": "f10addf7be0d0921f669ea4df323fe860df4fb15",
"extension": "c",
"filename": "io_tests.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 42935697,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 827,
"license": "MIT",
"license_type": "permissive",
"path": "/tests/io_tests.c",
"provenance": "stackv2-0058.json.gz:41",
"repo_name": "ryutaroikeda/gatherers",
"revision_date": "2015-10-08T11:00:20",
"revision_id": "10248996c41f97b4e7e960c54a3fb187dd824772",
"snapshot_id": "7ba22a0c0d253d9ba6d1f72e3948016b55d2cd7c",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ryutaroikeda/gatherers/10248996c41f97b4e7e960c54a3fb187dd824772/tests/io_tests.c",
"visit_date": "2021-01-10T20:28:51.009230"
} | stackv2 | #include "minunit.h"
#include "io.h"
static char input[] = "hello world\nfarewell world\nthe end";
static int getChar(void) {
static char* p = input;
if (*p == '\0') { return '\0'; }
return *(p++);
}
static char* Test_GTGetLineExplicit()
{
char buf[256];
mu_assert(GTGetLineExplicit(&getChar, buf, 256) == 0, "GetLine error");
mu_assert(strcmp(buf, "hello world") == 0, "got wrong line");
mu_assert(GTGetLineExplicit(&getChar, buf, 256) == 0, "getline error");
mu_assert(strcmp(buf, "farewell world") == 0, "got wrong line");
mu_assert(GTGetLineExplicit(&getChar, buf, 256) == -1, "didn't report error");
mu_assert(strcmp(buf, "the end") == 0, "got wrong line");
return NULL;
}
static char* Test_All()
{
mu_suite_start();
mu_run_test(Test_GTGetLineExplicit);
return NULL;
}
RUN_TESTS(Test_All)
| 2.453125 | 2 |
2024-11-18T20:59:38.783301+00:00 | 2018-09-11T11:01:30 | 1645008fd475941abd92f6004abd801d9697adb5 | {
"blob_id": "1645008fd475941abd92f6004abd801d9697adb5",
"branch_name": "refs/heads/master",
"committer_date": "2018-09-11T11:01:30",
"content_id": "231412821879c9bfc5249d2edf011781c8814a61",
"detected_licenses": [
"MS-PL"
],
"directory_id": "a1be779f8efdb876334bb1e9940598461fde3982",
"extension": "c",
"filename": "disk.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 92953063,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3526,
"license": "MS-PL",
"license_type": "permissive",
"path": "/base/devices/disk/disk.c",
"provenance": "stackv2-0058.json.gz:297",
"repo_name": "tinashh2000/mtos",
"revision_date": "2018-09-11T11:01:30",
"revision_id": "359e7af050fbfd49d10f3154630500252c34450d",
"snapshot_id": "b7fd442555c4adceee34d4040f8e90243c2daf70",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/tinashh2000/mtos/359e7af050fbfd49d10f3154630500252c34450d/base/devices/disk/disk.c",
"visit_date": "2021-01-23T05:08:54.070216"
} | stackv2 | #define _MTOX_FILESYS
#include "disk.h"
UINT32 Disk_MaxOSID = 0;
#define STORDEV_VERIFYID(diskid) (diskid > 0 && diskid <= Disk_MaxOSID )
#include "disk.hxx"
BOOL StorageDevice_Inserted(STOR_DEV_DESC *sd) {
UINT32 c;
for (c=0;c<MAX_DRIVES;c++) {
if (Storage_Devices[c].OS_Id == 0) {
STOR_DEV *xsd = &Storage_Devices[c];
xsd->OS_Id = c + 1;
xsd->Flags = DISK_FLAG_INSERTED;
cprintf("<Disk Inserted %x,%i .....sz:%i,%x %x ", xsd->OS_Id, c, sizeof(STOR_DEV_DESC), ((char *)&xsd->OS_Id), ((char*)&xsd->BytesPerUnit));
memcpy(xsd,sd,sizeof(STOR_DEV_DESC));
// printf("<Disk Inserted %x,%c,>",xsd->OS_Id,c);
if ( Disk_MaxOSID < xsd->OS_Id ) Disk_MaxOSID = xsd->OS_Id;
// printf("<Disk Inserted %x,%c,>",xsd->OS_Id,c);
if (!FS_DontMountList(xsd->OS_Id)) {
cprintf("<Mount,,,>");
FS_Mount(xsd->OS_Id);
// FS_Mount(xsd->OS_Id);
cprintf("<Mount End>");
}
return true;
}
}
return false;
}
UINT32 StorageDevice_GetBytesPerUnit(STOR_DEVID diskid) {
STOR_DEV *xsd;
if (STORDEV_VERIFYID(diskid)) {
xsd = &Storage_Devices[diskid - 1];
// printf("<bbpu:%i,%i>",diskid,xsd->BytesPerUnit);
if (xsd->Flags & DISK_FLAG_INSERTED) {
return xsd->BytesPerUnit;
}
}
return 0;
}
BOOL StorageDevice_Removed(STOR_DEVID diskid) {
STOR_DEV *xsd = &Storage_Devices[diskid - 1];
if (STORDEV_VERIFYID(diskid) && xsd->Flags & DISK_FLAG_INSERTED) {
FS_Unmount(xsd->OS_Id);
xsd->Flags = 0;
return TRUE;
}
return FALSE;
}
LBAUNITS StorageDevice_Read(STOR_DEVID diskid,void *buffer,LBAUNIT LBAUnit,LBAUNITS numUnits) {
STOR_DEV *xsd = &Storage_Devices[diskid - 1];
if (STORDEV_VERIFYID(diskid) && xsd->Flags & DISK_FLAG_INSERTED) {
return xsd->Read(xsd->HardwareId,buffer,LBAUnit,numUnits);
}
return 0;
}
LBAUNITS StorageDevice_ReadAbs(STOR_DEVID diskid,void *buffer,UINT64 position,LBAUNITS size) {
STOR_DEV *xsd = &Storage_Devices[diskid - 1];
if (STORDEV_VERIFYID(diskid) && xsd->Flags & DISK_FLAG_INSERTED) {
UINT32 bpu = xsd->BytesPerUnit;
UINT64 npos = (position/bpu);
UINT32 nsize = (size+bpu-1)/bpu;
return xsd->Read(xsd->HardwareId,buffer,npos,nsize);
}
return 0;
}
LBAUNITS StorageDevice_Write(STOR_DEVID diskid, void *buffer, UINT64 LBAUnit, LBAUNITS numUnits) {
STOR_DEV *xsd = &Storage_Devices[diskid - 1];
if (STORDEV_VERIFYID(diskid) && xsd->Flags & DISK_FLAG_INSERTED) {
return xsd->Write(xsd->HardwareId,buffer,LBAUnit,numUnits);
}
return TRUE;
}
LBAUNITS StorageDevice_WriteAbs(STOR_DEVID diskid, void *buffer, UINT64 position, LBAUNITS size) {
STOR_DEV *xsd = &Storage_Devices[diskid - 1];
if (STORDEV_VERIFYID(diskid) && xsd->Flags & DISK_FLAG_INSERTED) {
UINT32 bpu = xsd->BytesPerUnit;
UINT64 npos = (position/bpu);
UINT32 nsize = (size+bpu-1)/bpu;
return xsd->Write(xsd->HardwareId,buffer,npos,nsize);
}
return TRUE;
}
BOOL StorageDevice_Sleep(STOR_DEVID diskid) {
STOR_DEV *xsd = &Storage_Devices[diskid - 1];
if (STORDEV_VERIFYID(diskid) && xsd->Flags & DISK_FLAG_INSERTED) {
Storage_Devices[diskid].Sleep(xsd->HardwareId);
}
return TRUE;
}
BOOL StorageDevice_Wakeup(STOR_DEVID diskid) {
STOR_DEV *xsd = &Storage_Devices[diskid - 1];
if (STORDEV_VERIFYID(diskid) && xsd->Flags & DISK_FLAG_INSERTED) {
Storage_Devices[diskid].Wake(xsd->HardwareId);
}
return TRUE;
}
BOOL StorageDevice_Eject(STOR_DEVID diskid) {
STOR_DEV *xsd = &Storage_Devices[diskid - 1];
if (STORDEV_VERIFYID(diskid) && xsd->Flags & DISK_FLAG_INSERTED) {
Storage_Devices[diskid].Eject(xsd->HardwareId);
}
return TRUE;
}
| 2.390625 | 2 |
2024-11-18T20:59:38.871032+00:00 | 2023-08-07T19:18:32 | 19bc3fd3396ffe40c8d42ed203dd196fff597e4b | {
"blob_id": "19bc3fd3396ffe40c8d42ed203dd196fff597e4b",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-07T19:18:32",
"content_id": "949c115acd5893a9a6cf83b5d3404de476ae226a",
"detected_licenses": [
"Apache-2.0",
"curl"
],
"directory_id": "e1d9c54e9925e30e388a255b53a93cccad0b94cb",
"extension": "c",
"filename": "v1_ingress_backend.c",
"fork_events_count": 47,
"gha_created_at": "2020-03-17T11:59:05",
"gha_event_created_at": "2023-09-07T20:07:00",
"gha_language": "C",
"gha_license_id": "Apache-2.0",
"github_id": 247958425,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3488,
"license": "Apache-2.0,curl",
"license_type": "permissive",
"path": "/kubernetes/model/v1_ingress_backend.c",
"provenance": "stackv2-0058.json.gz:425",
"repo_name": "kubernetes-client/c",
"revision_date": "2023-08-07T19:18:32",
"revision_id": "5ac5ff25e9809a92a48111b1f77574b6d040b711",
"snapshot_id": "dd4fd8095485c083e0f40f2b48159b1609a6141b",
"src_encoding": "UTF-8",
"star_events_count": 127,
"url": "https://raw.githubusercontent.com/kubernetes-client/c/5ac5ff25e9809a92a48111b1f77574b6d040b711/kubernetes/model/v1_ingress_backend.c",
"visit_date": "2023-08-13T10:51:03.702497"
} | stackv2 | #include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "v1_ingress_backend.h"
v1_ingress_backend_t *v1_ingress_backend_create(
v1_typed_local_object_reference_t *resource,
v1_ingress_service_backend_t *service
) {
v1_ingress_backend_t *v1_ingress_backend_local_var = malloc(sizeof(v1_ingress_backend_t));
if (!v1_ingress_backend_local_var) {
return NULL;
}
v1_ingress_backend_local_var->resource = resource;
v1_ingress_backend_local_var->service = service;
return v1_ingress_backend_local_var;
}
void v1_ingress_backend_free(v1_ingress_backend_t *v1_ingress_backend) {
if(NULL == v1_ingress_backend){
return ;
}
listEntry_t *listEntry;
if (v1_ingress_backend->resource) {
v1_typed_local_object_reference_free(v1_ingress_backend->resource);
v1_ingress_backend->resource = NULL;
}
if (v1_ingress_backend->service) {
v1_ingress_service_backend_free(v1_ingress_backend->service);
v1_ingress_backend->service = NULL;
}
free(v1_ingress_backend);
}
cJSON *v1_ingress_backend_convertToJSON(v1_ingress_backend_t *v1_ingress_backend) {
cJSON *item = cJSON_CreateObject();
// v1_ingress_backend->resource
if(v1_ingress_backend->resource) {
cJSON *resource_local_JSON = v1_typed_local_object_reference_convertToJSON(v1_ingress_backend->resource);
if(resource_local_JSON == NULL) {
goto fail; //model
}
cJSON_AddItemToObject(item, "resource", resource_local_JSON);
if(item->child == NULL) {
goto fail;
}
}
// v1_ingress_backend->service
if(v1_ingress_backend->service) {
cJSON *service_local_JSON = v1_ingress_service_backend_convertToJSON(v1_ingress_backend->service);
if(service_local_JSON == NULL) {
goto fail; //model
}
cJSON_AddItemToObject(item, "service", service_local_JSON);
if(item->child == NULL) {
goto fail;
}
}
return item;
fail:
if (item) {
cJSON_Delete(item);
}
return NULL;
}
v1_ingress_backend_t *v1_ingress_backend_parseFromJSON(cJSON *v1_ingress_backendJSON){
v1_ingress_backend_t *v1_ingress_backend_local_var = NULL;
// define the local variable for v1_ingress_backend->resource
v1_typed_local_object_reference_t *resource_local_nonprim = NULL;
// define the local variable for v1_ingress_backend->service
v1_ingress_service_backend_t *service_local_nonprim = NULL;
// v1_ingress_backend->resource
cJSON *resource = cJSON_GetObjectItemCaseSensitive(v1_ingress_backendJSON, "resource");
if (resource) {
resource_local_nonprim = v1_typed_local_object_reference_parseFromJSON(resource); //nonprimitive
}
// v1_ingress_backend->service
cJSON *service = cJSON_GetObjectItemCaseSensitive(v1_ingress_backendJSON, "service");
if (service) {
service_local_nonprim = v1_ingress_service_backend_parseFromJSON(service); //nonprimitive
}
v1_ingress_backend_local_var = v1_ingress_backend_create (
resource ? resource_local_nonprim : NULL,
service ? service_local_nonprim : NULL
);
return v1_ingress_backend_local_var;
end:
if (resource_local_nonprim) {
v1_typed_local_object_reference_free(resource_local_nonprim);
resource_local_nonprim = NULL;
}
if (service_local_nonprim) {
v1_ingress_service_backend_free(service_local_nonprim);
service_local_nonprim = NULL;
}
return NULL;
}
| 2.546875 | 3 |
2024-11-18T19:02:21.181749+00:00 | 2020-01-18T12:51:40 | 1638dcb625d9e65936e99dc87d5b3ef060941ad3 | {
"blob_id": "1638dcb625d9e65936e99dc87d5b3ef060941ad3",
"branch_name": "refs/heads/master",
"committer_date": "2020-01-18T12:51:40",
"content_id": "2c321789f0228f1e0f0aa9c793fcfefbe1f6abdb",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "34a95bc138e80d9cbf64389b04bbb5ec78374885",
"extension": "c",
"filename": "ngx_http_addition_filter_module.c",
"fork_events_count": 2,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 42237239,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 15284,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/src/http/modules/ngx_http_addition_filter_module.c",
"provenance": "stackv2-0058.json.gz:149633",
"repo_name": "deyimsf/nginx-1.9.4",
"revision_date": "2020-01-18T12:51:40",
"revision_id": "4ac42709c7a7d07c6a0b2d408a14a33f2e8834f1",
"snapshot_id": "25b24ac4dfb2bd4f8b4682bfffb38ad4c5184cac",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/deyimsf/nginx-1.9.4/4ac42709c7a7d07c6a0b2d408a14a33f2e8834f1/src/http/modules/ngx_http_addition_filter_module.c",
"visit_date": "2021-01-21T10:12:37.339054"
} | stackv2 |
/*
* Copyright (C) Igor Sysoev
* Copyright (C) Nginx, Inc.
*/
#include <ngx_config.h>
#include <ngx_core.h>
#include <ngx_http.h>
typedef struct {
ngx_str_t before_body;
ngx_str_t after_body;
ngx_hash_t types;
ngx_array_t *types_keys;
} ngx_http_addition_conf_t;
typedef struct {
ngx_uint_t before_body_sent;
} ngx_http_addition_ctx_t;
static void *ngx_http_addition_create_conf(ngx_conf_t *cf);
static char *ngx_http_addition_merge_conf(ngx_conf_t *cf, void *parent,
void *child);
static ngx_int_t ngx_http_addition_filter_init(ngx_conf_t *cf);
static ngx_command_t ngx_http_addition_commands[] = {
{ ngx_string("add_before_body"),
NGX_HTTP_MAIN_CONF|NGX_HTTP_SRV_CONF|NGX_HTTP_LOC_CONF|NGX_CONF_TAKE1,
ngx_conf_set_str_slot,
NGX_HTTP_LOC_CONF_OFFSET,
offsetof(ngx_http_addition_conf_t, before_body),
NULL },
{ ngx_string("add_after_body"),
NGX_HTTP_MAIN_CONF|NGX_HTTP_SRV_CONF|NGX_HTTP_LOC_CONF|NGX_CONF_TAKE1,
ngx_conf_set_str_slot,
NGX_HTTP_LOC_CONF_OFFSET,
offsetof(ngx_http_addition_conf_t, after_body),
NULL },
{ ngx_string("addition_types"),
NGX_HTTP_MAIN_CONF|NGX_HTTP_SRV_CONF|NGX_HTTP_LOC_CONF|NGX_CONF_1MORE,
ngx_http_types_slot,
NGX_HTTP_LOC_CONF_OFFSET,
offsetof(ngx_http_addition_conf_t, types_keys),
&ngx_http_html_default_types[0] },
ngx_null_command
};
static ngx_http_module_t ngx_http_addition_filter_module_ctx = {
NULL, /* preconfiguration */
ngx_http_addition_filter_init, /* postconfiguration */
NULL, /* create main configuration */
NULL, /* init main configuration */
NULL, /* create server configuration */
NULL, /* merge server configuration */
ngx_http_addition_create_conf, /* create location configuration */
ngx_http_addition_merge_conf /* merge location configuration */
};
ngx_module_t ngx_http_addition_filter_module = {
NGX_MODULE_V1,
&ngx_http_addition_filter_module_ctx, /* module context */
ngx_http_addition_commands, /* module directives */
NGX_HTTP_MODULE, /* module type */
NULL, /* init master */
NULL, /* init module */
NULL, /* init process */
NULL, /* init thread */
NULL, /* exit thread */
NULL, /* exit process */
NULL, /* exit master */
NGX_MODULE_V1_PADDING
};
static ngx_http_output_header_filter_pt ngx_http_next_header_filter;
static ngx_http_output_body_filter_pt ngx_http_next_body_filter;
static ngx_int_t
ngx_http_addition_header_filter(ngx_http_request_t *r)
{
ngx_http_addition_ctx_t *ctx;
ngx_http_addition_conf_t *conf;
if (r->headers_out.status != NGX_HTTP_OK || r != r->main) {
/*
* 这里表示,如果不是主请求,则不能发起子请求
* 所以这个过滤器不能做子请求嵌套,比如下面的例子:
* location /a.html {
* add_after_body /b.html;
* }
*
* location /b.html {
* add_after_body /c.html;
* }
*
* location /c.html {
* }
* 请求 curl http://127.0.0.1/a.html,只能输出
* a.html b.html
* 最后一个是不能输出的,因为请求第二个location的时候,已经不是主请求了,而是
* add_after_body /b.html
* 这一句发起的子请求,所以第二个location中的add_after_body指令已经失效了
*
*/
return ngx_http_next_header_filter(r);
}
conf = ngx_http_get_module_loc_conf(r, ngx_http_addition_filter_module);
if (conf->before_body.len == 0 && conf->after_body.len == 0) {
return ngx_http_next_header_filter(r);
}
/**
* 默认在下面的配置不起作用:
* location / {
* add_before_body /bb.html;
* return 200 "aaaa";
* }
* 是因为这里要匹配下响应头Content-Type类型,默认只有text/html才能通过
* 改变这里的规则可以用addition_types指令设置
*/
if (ngx_http_test_content_type(r, &conf->types) == NULL) {
return ngx_http_next_header_filter(r);
}
ctx = ngx_pcalloc(r->pool, sizeof(ngx_http_addition_ctx_t));
if (ctx == NULL) {
return NGX_ERROR;
}
ngx_http_set_ctx(r, ctx, ngx_http_addition_filter_module);
/*
* 因为有子请求所有这里不确定内容长度了,后续就只能使用chunk编码告诉客户端响应体的长度,
* 如果关闭chunk编码,那ngx就只能用短连接的方式来告知客户端响应体发送完毕
*/
ngx_http_clear_content_length(r);
ngx_http_clear_accept_ranges(r);
ngx_http_weak_etag(r);
return ngx_http_next_header_filter(r);
}
static ngx_int_t
ngx_http_addition_body_filter(ngx_http_request_t *r, ngx_chain_t *in)
{
ngx_int_t rc;
ngx_uint_t last;
ngx_chain_t *cl;
ngx_http_request_t *sr;
ngx_http_addition_ctx_t *ctx;
ngx_http_addition_conf_t *conf;
if (in == NULL || r->header_only) {
return ngx_http_next_body_filter(r, in);
}
ctx = ngx_http_get_module_ctx(r, ngx_http_addition_filter_module);
if (ctx == NULL) {
return ngx_http_next_body_filter(r, in);
}
conf = ngx_http_get_module_loc_conf(r, ngx_http_addition_filter_module);
if (!ctx->before_body_sent) {
ctx->before_body_sent = 1;
/*
* 在向客户端发送主请求的响应之前先发送一个前置子请求,这样客户端会先接收到子请求的数据
*/
if (conf->before_body.len) {
if (ngx_http_subrequest(r, &conf->before_body, NULL, &sr, NULL, 0)
!= NGX_OK)
{
return NGX_ERROR;
}
/*
* 前置子请求发送完毕后r->postponed链表的结构可能是如下状态:
* 图1: postponed r_pp代表当前请求r对应的ngx_http_postponed_request_t对象
* ----------
* | r_pp |
* ----------
* \
* -----------
* | before1 |
* -----------
*/
}
}
if (conf->after_body.len == 0) {
ngx_http_set_ctx(r, NULL, ngx_http_addition_filter_module);
/*
* 如果不需要发送后置子请求就直接调用下一个过滤器
*/
return ngx_http_next_body_filter(r, in);
}
last = 0;
/**
* 检查是否是请求群中最后一块数据
*/
for (cl = in; cl; cl = cl->next) {
if (cl->buf->last_buf) {
cl->buf->last_buf = 0;
cl->buf->sync = 1;
last = 1;
}
}
/*
* 先调用ngx_http_next_body_filter()方法将主请求的数据发给客户端,然后再发起后置子请求,这样
* 就可以保证后置子请求的数据发生排在主请求内容之后
*
* 这里是使用last这个标志位来保证的,last等于一就表示当前链表in中包含了请求r的所有响应数据,他调用
* 后续过滤器后就会把in中的数据输出到r->postponed的后面
*
*/
rc = ngx_http_next_body_filter(r, in);
/*
* 当执行完上面的方法后,r->postponed的状态图可能会像这样:
* 图2: postponed r_pp代表当前请求r对应的ngx_http_postponed_request_t对象
* ----------
* | r_pp |
* ----------
* \
* ----------- --------
* | before1 | ---> | data |
* ----------- --------
* 可以看到图2比图1多了一个data节点,这个节点的数据就是当前请求r输出的数据,因为有子请求before1的存在
* 所以他没有把数据直接输出到客户端,而是把数据暂存到了r->postpone链表的最后,只有before1的数据输出
* 完毕后才会输出data节点的数据。
*
* 如果在一开始就没有发起图1中的子请求before1,那么就代表r->postponed链表是NUL,这样也就不会出现一个
* data节点来暂存数据,而是和常规请求一样使用r->out来暂存没有发出去的数据。
*/
if (rc == NGX_ERROR || !last || conf->after_body.len == 0) {
/*
* 如果ngx_http_next_body_filter()方法都返回NGX_ERROR了那就不用发送after子请求了
*
* 如果不是后一个buf,那现在还是不发送after子请求,万一中间有一次过滤器返回NGX_ERROR那不就白发了吗
*
* 如果conf->after_body.len == 0也就不用发了,因为根本没有这个after指令.
*
* 另一个需要注意的是因为buf_lasf这个标记代表的是整个请求群的最后一块数据,所以这里也说明一个问题
* add_after_body这个指令不能再嵌套子请求中,比如下面的例子:
* location /main {
* return 200 "main-->>> ";
* add_after_body /sub1;
* }
*
* location /sub1 {
* reutrn 200 "sub1-->>> "
* add_after_body /sub2;
* }
*
* location /sub2 {
* reutrn 200 "sub2-->>> "
* }
* 当访问/main的时候,/sub1中的add_after_body指令是不起作用的,因为这个指令不能嵌套在子请求中
* 当访问/sub1的时候,/sub1中的add_after_body指令是可以发出去的,因为他没有嵌套在子请求中
*
*/
return rc;
}
/*
* 如果前面存在before1这个子请求,那么当下面的方法执行完毕后,对于postponed可能会是如下的状态:
* 图3: postponed r_pp代表当前请求r对应的ngx_http_postponed_request_t对象
* --------
* | r_pp |
* --------
* \
* ----------- -------- ----------
* | before1 | ---> | data | ---> | after1 |
* ----------- -------- ----------
* 其中data是一个数据节点,它里面存放了当前请求r中的所有响应数据
*
*
* 如果前面没有发起过前置子请求(before1),那么下面方法执行完毕后,postponed可能会是如下状态:
* 图4: postponed r_pp代表当前请求r对应的ngx_http_postponed_request_t对象
* --------
* | r_pp |
* --------
* \
* ----------
* | after1 |
* ----------
* 可以看到没有数据节点data的存在,因为前请求r的数据都输出到客户端或存放到r->out中了
*/
if (ngx_http_subrequest(r, &conf->after_body, NULL, &sr, NULL, 0)
!= NGX_OK)
{
return NGX_ERROR;
}
/*
* 如果当前请求既有前置请求,自己又有数据要输出,又有后置请求,那么在后续的执行过程中可能会有如下状态的postpoed链表:
* 图5: postponed r_pp代表当前请求r对应的ngx_http_postponed_request_t对象
* --------
* | r_pp |
* --------
* \
* +---------+ -------- ----------
* | before1 | ---> | data | ---> | after1 |
* +---------+ -------- ----------
* \
* --------
* | data |
* --------
* 其中before1是当前可以向客户端输出数据的之请求,他的数据会直接输出到客户端,不会产生一个data节点
* before1后面的data是请求r_pp要输出的数据
* after1下面的data是after1要输出的数据
* 他们的最终输出过程如下:
* before1 --> data(before1后的) --> data(after1下的)
*
*/
// 发送完子请求后把上下文置空就行了,这样这个请求后续就不会再走这个过滤器了
ngx_http_set_ctx(r, NULL, ngx_http_addition_filter_module);
/*
* 这里不需要再像其他模块那样调用ngx_http_next_body_filter()方法来结束,因为如果当前是子请求,那么
* 子请求有自己的一套结束流程,如果当前是父请求,那么在上面已经调用完ngx_http_next_body_filter()方法了
*
* 为什么要把父请求的最后一个buf->last_buf设置为0,如果不设置为0这里直接调用ngx_http_output_filter(r, NULL)不行吗?
* 或者说不设置最后一个buf->last_buf设置为0,而是这里直接使用上面的rc作为返回值?
*
* 答案是不行:
* 因为如果不把buf->last_buf设置为0,那么很有可能当这个父请求执行完毕后就直接关闭了(因为没有其它子请求了),如果父请求
* 都关闭了也就不可能在产生子请求了,所以才有了下面调用ngx_http_send_special()方法的动作.
*
* 前面为了发送after子请求需要先把主请求的数据发送完毕,但是又不能让后续的过滤器看到buf->last_buf标记(看到后请求就可能被关闭),
* 所以在发送之前把父请求的最后一个cl->buf->last_buf设置成了0,这样父请求即使把数据输出完毕了也不会去结束父请求.
* 当after子请求发送完毕后,通过调用ngx_http_send_special()方法来解除父请求的调用,ngx_http_send_special()
* 方法中会创建一个b->last_buf = 1的buf,然后调用ngx_http_output_filter()方法把这个buf传过去,此时父请求在将其所有的子
* 请求输出完毕后才可以正常结束.
*/
return ngx_http_send_special(r, NGX_HTTP_LAST);
}
static ngx_int_t
ngx_http_addition_filter_init(ngx_conf_t *cf)
{
ngx_http_next_header_filter = ngx_http_top_header_filter;
ngx_http_top_header_filter = ngx_http_addition_header_filter;
ngx_http_next_body_filter = ngx_http_top_body_filter;
ngx_http_top_body_filter = ngx_http_addition_body_filter;
return NGX_OK;
}
static void *
ngx_http_addition_create_conf(ngx_conf_t *cf)
{
ngx_http_addition_conf_t *conf;
conf = ngx_pcalloc(cf->pool, sizeof(ngx_http_addition_conf_t));
if (conf == NULL) {
return NULL;
}
/*
* set by ngx_pcalloc():
*
* conf->before_body = { 0, NULL };
* conf->after_body = { 0, NULL };
* conf->types = { NULL };
* conf->types_keys = NULL;
*/
return conf;
}
static char *
ngx_http_addition_merge_conf(ngx_conf_t *cf, void *parent, void *child)
{
ngx_http_addition_conf_t *prev = parent;
ngx_http_addition_conf_t *conf = child;
ngx_conf_merge_str_value(conf->before_body, prev->before_body, "");
ngx_conf_merge_str_value(conf->after_body, prev->after_body, "");
if (ngx_http_merge_types(cf, &conf->types_keys, &conf->types,
&prev->types_keys, &prev->types,
ngx_http_html_default_types)
!= NGX_OK)
{
return NGX_CONF_ERROR;
}
return NGX_CONF_OK;
}
| 2.296875 | 2 |
2024-11-18T19:02:21.291999+00:00 | 2021-02-25T03:26:58 | 07e4faa5c645fad17b06af5085b96277fe76ccef | {
"blob_id": "07e4faa5c645fad17b06af5085b96277fe76ccef",
"branch_name": "refs/heads/master",
"committer_date": "2021-02-25T03:26:58",
"content_id": "cb6cbb92076e242402539eae6620fa8ab76447e6",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "cc55b7076d852e98c374599b450836f9244fd7de",
"extension": "c",
"filename": "drv_ir.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 229898355,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1841,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/source/driver/drv_ir.c",
"provenance": "stackv2-0058.json.gz:149761",
"repo_name": "FuxFox/MCU",
"revision_date": "2021-02-25T03:26:58",
"revision_id": "ce4d9ab008079a070b5e45c2f29dda4f06816cc9",
"snapshot_id": "ceec73f73ac7a039d149e44d1f9e25a32efd5438",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/FuxFox/MCU/ce4d9ab008079a070b5e45c2f29dda4f06816cc9/source/driver/drv_ir.c",
"visit_date": "2021-07-10T08:31:32.653562"
} | stackv2 | /*******************************************************************************
* LICENSE : Apache 2.0
*
* History:
* <author> <time> <version> <desc>
* FuxFox 2020/06/23 15:52 V1.0 build this file
*
*******************************************************************************/
#ifndef DRV_IR_C
#define DRV_IR_C
#include "drv_ir.h"
#include "app_log.h"
#include "hal_gpio.h"
#include "hal_delay.h"
/*!*****************************************************************************
\brief initialize
\details
\param[in] void
\return void
******************************************************************************/
void drv_ir_init(drv_ir_instance_t* instance)
{
instance->pwm_driver.pwm_init();
instance->pwm_driver.pwm_switch(OFF);
}
static void drv_ir_send_byte(drv_ir_instance_t* instance, uint8_t byte)
{
uint8_t i;
#if DRV_IR_BIT_SEQUENCE_MSB_FIRST
for (i = 0x80; i; i >>= 1)
#else
for (i = 0x01; i ; i <<= 1)
#endif
{
instance->pwm_driver.pwm_switch(ON);
hal_delay_us((byte & i)? instance->protocol.logic_1_high
: instance->protocol.logic_0_high);
instance->pwm_driver.pwm_switch(OFF);
hal_delay_us((byte & i) ? instance->protocol.logic_1_low
: instance->protocol.logic_0_low);
}
}
void drv_ir_send(drv_ir_instance_t* instance, uint8_t* buff, uint8_t buff_len)
{
//start signal
instance->pwm_driver.pwm_switch(ON);
hal_delay_us(instance->protocol.start_high);
instance->pwm_driver.pwm_switch(OFF);
hal_delay_us(instance->protocol.start_low);
while (buff_len--)
{
drv_ir_send_byte(instance, *buff++);
}
instance->pwm_driver.pwm_switch(ON);
hal_delay_us(instance->protocol.logic_1_high);
instance->pwm_driver.pwm_switch(OFF);
hal_delay_us(instance->protocol.logic_1_low);
}
#endif // DRV_IR_C
| 2.15625 | 2 |
2024-11-18T19:02:21.346306+00:00 | 2018-12-28T22:00:39 | 5bdd684703504b79b066083d3d91b50e22d431fc | {
"blob_id": "5bdd684703504b79b066083d3d91b50e22d431fc",
"branch_name": "refs/heads/master",
"committer_date": "2018-12-28T22:00:39",
"content_id": "a76abd521f7b7281f7a51470116386f6d16607d3",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "79585044d17b4abca1e40c925b624ee029efecb4",
"extension": "c",
"filename": "ft_main_output.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 154335223,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1166,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/ft_main_output.c",
"provenance": "stackv2-0058.json.gz:149890",
"repo_name": "RietBurger/expertSystem",
"revision_date": "2018-12-28T22:00:39",
"revision_id": "38f0b0746d90a8859545765ce945b977045390c7",
"snapshot_id": "8078303d1044dd8b6166542bb2ad14817c3e2393",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/RietBurger/expertSystem/38f0b0746d90a8859545765ce945b977045390c7/src/ft_main_output.c",
"visit_date": "2020-04-02T10:20:44.364910"
} | stackv2 | #include "expert.h"
void ft_main_output(t_g *all)
{
int i, j, t;
char A, B;
A = 't';
B = 't';
i = j = 0;
while (all->stmts->next)
{
ft_putendl(all->stmts->stmt);
all->stmts = all->stmts->next;
}
ft_putendl("FINAL RESULTS REQUESTED: ");
if (all->results)
{
while (all->results[i])
{
j = 0;
while (all->facts[j])
{
if (all->results[i] == all->facts[j])
{
ft_putchar(all->results[i]);
ft_putendl(": TRUE");
t++;
}
j++;
}
i++;
}
}
/*
all->resultsc = ft_strlen(all->results);
ft_putnbr(all->resultsc);
ft_putchar('\n');
ft_putnbr(t);
ft_putchar('\n');
if (t == all->resultsc)
{
ft_putendl("no false results");
}
else {
t = 0;
while (all->undefined[t])
{
ft_putchar(all->undefined[t]);
ft_putendl(": UNDEFINED");
t++;
}
}
*/
ft_putstr("all FACTS: ");
ft_putendl(all->facts);
ft_putstr("all FIND: ");
ft_putendl(all->find);
ft_putstr("all RESULTS: ");
ft_putendl(all->results);
ft_putstr("all FALSE: ");
if (all->undefined != NULL)
ft_putendl(all->undefined);
else
ft_putendl("NONE");
if(A eqt orsym B eqt)
ft_putendl("true...");
else
ft_putendl("false...");
}
| 2.375 | 2 |
2024-11-18T19:02:21.461753+00:00 | 2022-05-05T23:11:35 | b6ad2a75f314fdc89265fbc4204215974d0bbf91 | {
"blob_id": "b6ad2a75f314fdc89265fbc4204215974d0bbf91",
"branch_name": "refs/heads/master",
"committer_date": "2022-05-06T04:59:41",
"content_id": "f044842cd9f0f7f6ded6c815f0cc9f6cc769cda1",
"detected_licenses": [
"MIT"
],
"directory_id": "ef7bebb49d6fa05978bdbfa7a75c89154ba24e5d",
"extension": "c",
"filename": "helpers.c",
"fork_events_count": 2,
"gha_created_at": "2018-01-02T08:04:22",
"gha_event_created_at": "2023-01-30T23:02:20",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 115990598,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 17381,
"license": "MIT",
"license_type": "permissive",
"path": "/src/helpers.c",
"provenance": "stackv2-0058.json.gz:150019",
"repo_name": "HMBSbige/kms-server",
"revision_date": "2022-05-05T23:11:35",
"revision_id": "d36420f4499c67bca1a656ec46a47b41f989eb44",
"snapshot_id": "1e0c55fc68b1ac123b68cd8488dd747bafab9e77",
"src_encoding": "UTF-8",
"star_events_count": 13,
"url": "https://raw.githubusercontent.com/HMBSbige/kms-server/d36420f4499c67bca1a656ec46a47b41f989eb44/src/helpers.c",
"visit_date": "2023-02-05T07:15:49.781108"
} | stackv2 | /*
* Helper functions used by other modules
*/
//#ifndef _GNU_SOURCE
//#define _GNU_SOURCE
//#endif
#ifndef _CRT_SECURE_NO_WARNINGS
#define _CRT_SECURE_NO_WARNINGS
#endif
#ifndef CONFIG
#define CONFIG "config.h"
#endif // CONFIG
#include CONFIG
#ifndef _WIN32
#include <errno.h>
#include <libgen.h>
#endif // _WIN32
#ifndef _MSC_VER
#include <getopt.h>
#else
#include "wingetopt.h"
#endif
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include "helpers.h"
#include "output.h"
#include "endian.h"
#include "shared_globals.h"
#ifndef NO_INTERNAL_DATA
#include "kmsdata.h"
#endif // NO_INTERNAL_DATA
#ifdef _WIN32
#include <shlwapi.h>
#endif // _WIN32
#if __APPLE__
#include <mach-o/dyld.h>
#endif // __APPLE__
#if (__GLIBC__ || __linux__) && defined(USE_AUXV)
#include <sys/auxv.h>
#endif
#if __FreeBSD__ || __FreeBSD_kernel__
#include <sys/sysctl.h>
#endif
/*
* UCS2 <-> UTF-8 functions
* All functions use little endian UCS2 since we only need it to communicate with Windows via RPC
*/
// Convert one character from UTF-8 to UCS2
// Returns 0xffff, if utf-8 evaluates to > 0xfffe (outside basic multilingual pane)
WCHAR utf8_to_ucs2_char(const unsigned char *input, const unsigned char **end_ptr)
{
*end_ptr = input;
if (input[0] == 0)
return (WCHAR)~0;
if (input[0] < 0x80) {
*end_ptr = input + 1;
return LE16(input[0]);
}
if ((input[0] & 0xE0) == 0xE0) {
if (input[1] == 0 || input[2] == 0)
return (WCHAR)~0;
*end_ptr = input + 3;
return
LE16((input[0] & 0x0F) << 12 |
(input[1] & 0x3F) << 6 |
(input[2] & 0x3F));
}
if ((input[0] & 0xC0) == 0xC0) {
if (input[1] == 0)
return (WCHAR)~0;
*end_ptr = input + 2;
return
LE16((input[0] & 0x1F) << 6 |
(input[1] & 0x3F));
}
return (WCHAR)~0;
}
// Convert one character from UCS2 to UTF-8
// Returns length of UTF-8 char (1, 2 or 3) or -1 on error (UTF-16 outside UCS2)
// char *utf8 must be large enough to hold 3 bytes
int ucs2_to_utf8_char(const WCHAR ucs2_le, char *utf8)
{
const WCHAR ucs2 = LE16(ucs2_le);
if (ucs2 < 0x80) {
utf8[0] = (char)ucs2;
utf8[1] = '\0';
return 1;
}
if (ucs2 >= 0x80 && ucs2 < 0x800) {
utf8[0] = (char)((ucs2 >> 6) | 0xC0);
utf8[1] = (char)((ucs2 & 0x3F) | 0x80);
utf8[2] = '\0';
return 2;
}
if (ucs2 >= 0x800 && ucs2 < 0xFFFF) {
if (ucs2 >= 0xD800 && ucs2 <= 0xDFFF) {
/* Ill-formed (UTF-16 ouside of BMP) */
return -1;
}
utf8[0] = ((ucs2 >> 12)) | 0xE0;
utf8[1] = ((ucs2 >> 6) & 0x3F) | 0x80;
utf8[2] = ((ucs2) & 0x3F) | 0x80;
utf8[3] = '\0';
return 3;
}
return -1;
}
// Converts UTF8 to UCS2. Returns size in bytes of the converted string or -1 on error
size_t utf8_to_ucs2(WCHAR* const ucs2_le, const char* const utf8, const size_t maxucs2, const size_t maxutf8)
{
const unsigned char* current_utf8 = (unsigned char*)utf8;
WCHAR* current_ucs2_le = ucs2_le;
for (; *current_utf8; current_ucs2_le++)
{
size_t size = (char*)current_utf8 - utf8;
if (size >= maxutf8) return (size_t)-1;
if (((*current_utf8 & 0xc0) == 0xc0) && (size >= maxutf8 - 1)) return (size_t)-1;
if (((*current_utf8 & 0xe0) == 0xe0) && (size >= maxutf8 - 2)) return (size_t)-1;
if (current_ucs2_le - ucs2_le >= (intptr_t)maxucs2 - 1) return (size_t)-1;
*current_ucs2_le = utf8_to_ucs2_char(current_utf8, ¤t_utf8);
current_ucs2_le[1] = 0;
if (*current_ucs2_le == (WCHAR)-1) return (size_t)-1;
}
return current_ucs2_le - ucs2_le;
}
// Converts UCS2 to UTF-8. Returns TRUE or FALSE
BOOL ucs2_to_utf8(const WCHAR* const ucs2_le, char* utf8, size_t maxucs2, size_t maxutf8)
{
char utf8_char[4];
const WCHAR* current_ucs2 = ucs2_le;
unsigned int index_utf8 = 0;
for (*utf8 = 0; *current_ucs2; current_ucs2++)
{
if (current_ucs2 - ucs2_le > (intptr_t)maxucs2) return FALSE;
int len = ucs2_to_utf8_char(*current_ucs2, utf8_char);
if (index_utf8 + len > maxutf8) return FALSE;
strncat(utf8, utf8_char, len);
index_utf8 += len;
}
return TRUE;
}
/* End of UTF-8 <-> UCS2 conversion */
// Checks, whether a string is a valid integer number between min and max. Returns TRUE or FALSE. Puts int value in *value
BOOL stringToInt(const char *const szValue, const unsigned int min, const unsigned int max, unsigned int *const value)
{
char *nextchar;
errno = 0;
long long result = vlmcsd_strtoll(szValue, &nextchar, 10);
if (errno || result < (long long)min || result >(long long)max || *nextchar)
{
return FALSE;
}
*value = (unsigned int)result;
return TRUE;
}
//Converts a String Guid to a host binary guid in host endianess
int_fast8_t string2UuidLE(const char *const restrict input, GUID *const restrict guid)
{
int i;
if (strlen(input) < GUID_STRING_LENGTH) return FALSE;
if (input[8] != '-' || input[13] != '-' || input[18] != '-' || input[23] != '-') return FALSE;
for (i = 0; i < GUID_STRING_LENGTH; i++)
{
if (i == 8 || i == 13 || i == 18 || i == 23) continue;
const char c = (char)toupper((int)input[i]);
if (c < '0' || c > 'F' || (c > '9' && c < 'A')) return FALSE;
}
char inputCopy[GUID_STRING_LENGTH + 1];
strncpy(inputCopy, input, GUID_STRING_LENGTH + 1);
inputCopy[8] = inputCopy[13] = inputCopy[18] = 0;
hex2bin((BYTE*)&guid->Data1, inputCopy, 8);
hex2bin((BYTE*)&guid->Data2, inputCopy + 9, 4);
hex2bin((BYTE*)&guid->Data3, inputCopy + 14, 4);
hex2bin(guid->Data4, input + 19, 16);
guid->Data1 = BS32(guid->Data1);
guid->Data2 = BS16(guid->Data2);
guid->Data3 = BS16(guid->Data3);
return TRUE;
}
__pure DWORD timeSpanString2Seconds(const char *const restrict argument)
{
char *unitId;
long long val = vlmcsd_strtoll(argument, &unitId, 10);
switch (toupper((int)*unitId))
{
case 'W':
val *= 7;
case 'D':
val *= 24;
case 'H':
val *= 60;
case 0:
case 'M':
val *= 60;
case 'S':
break;
default:
return 0;
}
if (*unitId && unitId[1]) return 0;
if (val < 1) val = 1;
return (DWORD)(val & UINT_MAX);
}
#if !IS_LIBRARY
//Checks a command line argument if it is numeric and between min and max. Returns the numeric value or exits on error
__pure unsigned int getOptionArgumentInt(const char o, const unsigned int min, const unsigned int max)
{
unsigned int result;
if (!stringToInt(optarg, min, max, &result))
{
printerrorf("Fatal: Option \"-%c\" must be numeric between %u and %u.\n", o, min, max);
exit(VLMCSD_EINVAL);
}
return result;
}
// Resets getopt() to start parsing from the beginning
void optReset(void)
{
#if __minix__ || defined(__BSD__) || defined(__APPLE__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__DragonFly__) || defined(__OpenBSD__)
optind = 1;
optreset = 1; // Makes newer BSD getopt happy
#elif defined(__UCLIBC__) // uClibc headers also define __GLIBC__ so be careful here
optind = 0; // uClibc seeks compatibility with GLIBC
#elif defined(__GLIBC__)
optind = 0; // Makes GLIBC getopt happy
#else // Standard for most systems
optind = 1;
#endif
}
#endif // !IS_LIBRARY
#if _WIN32 || __CYGWIN__
// Returns a static message buffer containing text for a given Win32 error. Not thread safe (same as strerror)
char* win_strerror(const int message)
{
#define STRERROR_BUFFER_SIZE 256
static char buffer[STRERROR_BUFFER_SIZE];
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_MAX_WIDTH_MASK, NULL, message, 0, buffer, STRERROR_BUFFER_SIZE, NULL);
return buffer;
}
#endif // _WIN32 || __CYGWIN__
/*
* parses an address in the form host:[port] in addr
* returns host and port in seperate strings
*/
void parseAddress(char *const addr, char** szHost, char** szPort)
{
*szHost = addr;
# ifndef NO_SOCKETS
*szPort = (char*)defaultport;
# else // NO_SOCKETS
*szPort = "1688";
# endif // NO_SOCKETS
char *lastcolon = strrchr(addr, ':');
char *firstcolon = strchr(addr, ':');
char *closingbracket = strrchr(addr, ']');
if (*addr == '[' && closingbracket) //Address in brackets
{
*closingbracket = 0;
(*szHost)++;
if (closingbracket[1] == ':')
*szPort = closingbracket + 2;
}
else if (firstcolon && firstcolon == lastcolon) //IPv4 address or hostname with port
{
*firstcolon = 0;
*szPort = firstcolon + 1;
}
}
// Initialize random generator (needs to be done in each thread)
void randomNumberInit()
{
# if _MSC_VER
srand(GetTickCount());
# else
struct timeval tv;
gettimeofday(&tv, NULL);
srand((unsigned int)(tv.tv_sec ^ tv.tv_usec));
# endif
}
// We always exit immediately if any OOM condition occurs
__noreturn void OutOfMemory(void)
{
errorout("Fatal: Out of memory");
exit(VLMCSD_ENOMEM);
}
void* vlmcsd_malloc(size_t len)
{
void* buf = malloc(len);
if (!buf) OutOfMemory();
return buf;
}
char* vlmcsd_strdup(const char* src)
{
# if _MSC_VER
char* dst = _strdup(src);
# else // !_MSC_VER
char* dst = strdup(src);
# endif
if (!dst) OutOfMemory();
return dst;
}
/*
* Converts hex digits to bytes in big-endian order.
* Ignores any non-hex characters
*/
void hex2bin(BYTE *const bin, const char *hex, const size_t maxbin)
{
static const char *const hexdigits = "0123456789ABCDEF";
char* nextchar;
size_t i;
for (i = 0; (i < 16) && utf8_to_ucs2_char((const unsigned char*)hex, (const unsigned char**)&nextchar) != (WCHAR)-1; hex = nextchar)
{
const char* pos = strchr(hexdigits, toupper((int)*hex));
if (!pos) continue;
if (!(i & 1)) bin[i >> 1] = 0;
bin[i >> 1] |= (char)(pos - hexdigits);
if (!(i & 1)) bin[i >> 1] <<= 4;
i++;
if (i >> 1 > maxbin) break;
}
}
__pure BOOL getArgumentBool(int_fast8_t *result, const char *const argument)
{
if (
!strncasecmp(argument, "true", 4) ||
!strncasecmp(argument, "on", 2) ||
!strncasecmp(argument, "yes", 3) ||
!strncasecmp(argument, "1", 1)
)
{
*result = TRUE;
return TRUE;
}
else if (
!strncasecmp(argument, "false", 5) ||
!strncasecmp(argument, "off", 3) ||
!strncasecmp(argument, "no", 2) ||
!strncasecmp(argument, "0", 1)
)
{
*result = FALSE;
return TRUE;
}
return FALSE;
}
#ifndef IS_LIBRARY
#ifndef NO_EXTERNAL_DATA
__noreturn static void dataFileReadError()
{
const int error = errno;
errorout("Fatal: Could not read %s: %s\n", fn_data, strerror(error));
exit(error);
}
__noreturn static void dataFileFormatError()
{
errorout("Fatal: %s is not a KMS data file version 2.x\n", fn_data);
exit(VLMCSD_EINVAL);
}
#endif // NO_EXTERNAL_DATA
#if !defined(DATA_FILE) || !defined(NO_SIGHUP)
void getExeName()
{
if (fn_exe != NULL) return;
# if (__GLIBC__ || __linux__) && defined(USE_AUXV)
fn_exe = (char*)getauxval(AT_EXECFN);
# elif (__ANDROID__ && __ANDROID_API__ < 16) || (__UCLIBC__ && __UCLIBC_MAJOR__ < 1 && !defined(NO_PROCFS)) // Workaround for older uclibc
char temp[PATH_MAX + 1];
if (realpath("/proc/self/exe", temp) == temp)
{
fn_exe = vlmcsd_strdup(temp);
}
# elif (__linux__ || __CYGWIN__) && !defined(NO_PROCFS)
fn_exe = realpath("/proc/self/exe", NULL);
# elif (__FreeBSD__ || __FreeBSD_kernel__)
int mib[4];
mib[0] = CTL_KERN;
mib[1] = KERN_PROC;
mib[2] = KERN_PROC_PATHNAME;
mib[3] = -1;
char path[PATH_MAX + 1];
size_t cb = sizeof(path);
if (!sysctl(mib, 4, path, &cb, NULL, 0))
{
fn_exe = vlmcsd_strdup(path);
}
# elif (__DragonFly__) && !defined(NO_PROCFS)
fn_exe = realpath("/proc/curproc/file", NULL);
# elif __NetBSD__ && !defined(NO_PROCFS)
fn_exe = realpath("/proc/curproc/exe", NULL);
# elif __sun__
fn_exe = getexecname();
# elif __APPLE__
char path[PATH_MAX + 1];
uint32_t size = sizeof(path);
if (_NSGetExecutablePath(path, &size) == 0)
{
fn_exe = vlmcsd_strdup(path);
}
# elif _WIN32
char path[512];
GetModuleFileName(GetModuleHandle(NULL), path, 512);
path[511] = 0;
fn_exe = vlmcsd_strdup(path);
# else
// Sorry no exe detection
# endif
}
#endif // defined(DATA_FILE) && defined(NO_SIGHUP)
#if !defined(DATA_FILE) && !defined(NO_EXTERNAL_DATA)
#ifdef _WIN32
static void getDefaultDataFile()
{
char fileName[MAX_PATH];
getExeName();
strncpy(fileName, fn_exe, MAX_PATH);
PathRemoveFileSpec(fileName);
strncat(fileName, "\\vlmcsd.kmd", MAX_PATH - 11);
fn_data = vlmcsd_strdup(fileName);
}
#else // !_WIN32
static void getDefaultDataFile()
{
char fileName[512];
getExeName();
if (!fn_exe)
{
fn_data = (char*)"/etc/vlmcsd.kmd";
return;
}
char* fn_exe_copy = vlmcsd_strdup(fn_exe);
strncpy(fileName, dirname(fn_exe_copy), 512);
free(fn_exe_copy);
strncat(fileName, "/vlmcsd.kmd", 500);
fn_data = vlmcsd_strdup(fileName);
}
#endif // !_WIN32
#endif // !defined(DATA_FILE) && !defined(NO_EXTERNAL_DATA)
void loadKmsData()
{
# ifndef NO_INTERNAL_DATA
KmsData = (PVlmcsdHeader_t)DefaultKmsData;
# endif // NO_INTERNAL_DATA
# ifndef NO_EXTERNAL_DATA
long size;
# ifndef NO_INTERNAL_DATA
size = (long)getDefaultKmsDataSize();
# endif // NO_INTERNAL_DATA
# ifndef DATA_FILE
if (!fn_data) getDefaultDataFile();
# endif // DATA_FILE
if (strcmp(fn_data, "-"))
{
FILE *file = fopen(fn_data, "rb");
if (!file)
{
# ifndef NO_INTERNAL_DATA
if (ExplicitDataLoad)
# endif // NO_INTERNAL_DATA
{
dataFileReadError();
}
}
else
{
if (fseek(file, 0, SEEK_END)) dataFileReadError();
size = ftell(file);
if (size == -1L) dataFileReadError();
KmsData = (PVlmcsdHeader_t)vlmcsd_malloc(size);
if (fseek(file, 0, SEEK_SET)) dataFileReadError();
const size_t bytesRead = fread(KmsData, 1, size, file);
if ((long)bytesRead != size) dataFileReadError();
fclose(file);
# if !defined(NO_LOG) && !defined(NO_SOCKETS)
if (!InetdMode) logger("Read KMS data file version %u.%u %s\n", (unsigned int)LE16(KmsData->MajorVer), (unsigned int)LE16(KmsData->MinorVer), fn_data);
# endif // NO_LOG
}
}
# endif // NO_EXTERNAL_DATA
# ifndef UNSAFE_DATA_LOAD
if (((BYTE*)KmsData)[size - 1] != 0) dataFileFormatError();
# endif // UNSAFE_DATA_LOAD
KmsData->MajorVer = LE16(KmsData->MajorVer);
KmsData->MinorVer = LE16(KmsData->MinorVer);
KmsData->AppItemCount = LE32(KmsData->AppItemCount);
KmsData->KmsItemCount = LE32(KmsData->KmsItemCount);
KmsData->SkuItemCount = LE32(KmsData->SkuItemCount);
KmsData->HostBuildCount = LE32(KmsData->HostBuildCount);
uint32_t i;
for (i = 0; i < vlmcsd_countof(KmsData->Datapointers); i++)
{
KmsData->Datapointers[i].Pointer = (BYTE*)KmsData + LE64(KmsData->Datapointers[i].Offset);
# ifndef UNSAFE_DATA_LOAD
if ((BYTE*)KmsData->Datapointers[i].Pointer > (BYTE*)KmsData + size) dataFileFormatError();
# endif // UNSAFE_DATA_LOAD
}
for (i = 0; i < KmsData->CsvlkCount; i++)
{
PCsvlkData_t csvlkData = &KmsData->CsvlkData[i];
csvlkData->EPid = (char*)KmsData + LE64(csvlkData->EPidOffset);
csvlkData->ReleaseDate = LE64(csvlkData->ReleaseDate);
# ifndef UNSAFE_DATA_LOAD
if (csvlkData->EPid > (char*)KmsData + size) dataFileFormatError();
# endif // UNSAFE_DATA_LOAD
# ifndef NO_RANDOM_EPID
csvlkData->GroupId = LE32(csvlkData->GroupId);
csvlkData->MinKeyId = LE32(csvlkData->MinKeyId);
csvlkData->MaxKeyId = LE32(csvlkData->MaxKeyId);
# endif // NO_RANDOM_EPID
}
for (i = 0; i < (uint32_t)KmsData->HostBuildCount; i++)
{
PHostBuild_t hostBuild = &KmsData->HostBuildList[i];
hostBuild->BuildNumber = LE32(hostBuild->BuildNumber);
hostBuild->Flags = LE32(hostBuild->Flags);
hostBuild->PlatformId = LE32(hostBuild->PlatformId);
hostBuild->ReleaseDate = LE64(hostBuild->ReleaseDate);
hostBuild->DisplayName = (char*)KmsData + LE64(hostBuild->DisplayNameOffset);
# ifndef UNSAFE_DATA_LOAD
if (hostBuild->DisplayName > (char*)KmsData + size) dataFileFormatError();
# endif // UNSAFE_DATA_LOAD
}
const uint32_t totalItemCount = KmsData->AppItemCount + KmsData->KmsItemCount + KmsData->SkuItemCount;
# ifndef NO_EXTERNAL_DATA
if (
memcmp(KmsData->Magic, "KMD", sizeof(KmsData->Magic)) ||
KmsData->MajorVer != 2
# ifndef UNSAFE_DATA_LOAD
||
sizeof(VlmcsdHeader_t) + totalItemCount * sizeof(VlmcsdData_t) >= ((uint64_t)size)
# endif //UNSAFE_DATA_LOAD
)
{
dataFileFormatError();
}
# endif // NO_EXTERNAL_DATA
for (i = 0; i < totalItemCount; i++)
{
PVlmcsdData_t item = &KmsData->AppItemList[i];
item->Name = (char*)KmsData + LE64(item->NameOffset);
# ifndef UNSAFE_DATA_LOAD
if (
item->Name >= (char*)KmsData + (uint64_t)size ||
(KmsData->AppItemCount && item->AppIndex >= KmsData->AppItemCount) ||
item->KmsIndex >= KmsData->KmsItemCount
)
{
dataFileFormatError();
}
# endif // UNSAFE_DATA_LOAD
}
}
#ifndef NO_SOCKETS
void exitOnWarningLevel(const int_fast8_t level)
{
if (ExitLevel >= level)
{
printerrorf("Fatal: Exiting on warning level %i or greater\n", (int)ExitLevel);
exit(-1);
}
}
#endif // !NO_SOCKETS
#endif // IS_LIBRARY
#if __ANDROID__ && !defined(USE_THREADS) // Bionic does not wrap these syscalls (intentionally because Google fears, developers don't know how to use it)
#ifdef __NR_shmget
int shmget(key_t key, size_t size, int shmflg)
{
return syscall(__NR_shmget, key, size, shmflg);
}
#endif // __NR_shmget
#ifdef __NR_shmat
void *shmat(int shmid, const void *shmaddr, int shmflg)
{
return (void *)syscall(__NR_shmat, shmid, shmaddr, shmflg);
}
#endif // __NR_shmat
#ifdef __NR_shmdt
int shmdt(const void *shmaddr)
{
return syscall(__NR_shmdt, shmaddr);
}
#endif // __NR_shmdt
#ifdef __NR_shmctl
int shmctl(int shmid, int cmd, /*struct shmid_ds*/void *buf)
{
return syscall(__NR_shmctl, shmid, cmd, buf);
}
#endif // __NR_shmctl
#endif // __ANDROID__ && !defined(USE_THREADS)
| 2.140625 | 2 |
2024-11-18T19:02:21.789055+00:00 | 2018-02-11T19:05:34 | 2e894bd623afce071d529465ea9f1cf93e0237ac | {
"blob_id": "2e894bd623afce071d529465ea9f1cf93e0237ac",
"branch_name": "refs/heads/master",
"committer_date": "2018-02-11T19:05:34",
"content_id": "f7fbf426454d813bde3403a9c9ce6196aa1abc4c",
"detected_licenses": [
"MIT"
],
"directory_id": "92b43b32a98f9bd24ce34b703d14512d06061353",
"extension": "h",
"filename": "shader.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 121157154,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2159,
"license": "MIT",
"license_type": "permissive",
"path": "/src/shader.h",
"provenance": "stackv2-0058.json.gz:150404",
"repo_name": "bakpakin/ldoomc",
"revision_date": "2018-02-11T19:05:34",
"revision_id": "4a4d9871ddfc3d3b3e14b85dfb9150f15af4e1d7",
"snapshot_id": "560e504178574ff65014a5f52cbe0d6510da3d48",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/bakpakin/ldoomc/4a4d9871ddfc3d3b3e14b85dfb9150f15af4e1d7/src/shader.h",
"visit_date": "2021-03-27T09:42:32.034941"
} | stackv2 | #ifndef SHADER_HEADER
#define SHADER_HEADER
#include "glfw.h"
typedef struct {
GLuint id;
GLint type;
} Shader;
typedef struct {
char * name;
GLenum type;
GLint size;
} ProgramAttribute;
typedef struct {
char * name;
GLenum type;
GLint size;
} ProgramUniform;
typedef struct {
GLuint id;
} Program;
/*
* Initializes a shader with the given source and type. Type must be one
* of GL_VERTEX_SHADER, GL_FRAGMENT_SHADER, or GL_GEOMETRY_SHADER.
*/
Shader * shader_init(Shader * s, const char * source, GLint type);
/*
* Initializes a shader by reading the source from the given file.
*/
Shader * shader_init_file(Shader * s, const char * path, GLint type);
/*
* Initializes a shader from a resource.
*/
Shader * shader_init_resource(Shader * s, const char * resource, GLint type);
/*
* Deinitializes the shader in the openGL context.
*/
void shader_deinit(Shader * s);
/*
* Initializes a program with a number of shaders. When the program is
* created, the shaders are detached but not destory. Shaders must be
* deinitialized separately.
*/
Program * program_init(Program * p, int shader_count, ...);
/*
* Initializes a program directly from the vertex shader source and the fragment shader source.
*/
Program * program_init_vertfrag(Program * p, const char * vert_source, const char * frag_source);
/*
* Initializes a program from a single source file with both the fragment and vertex shaders.
*/
Program * program_init_quick(Program * p, const char * source);
/*
* Initializes a progam from a simgle file. Use defines to define multiple shaders
* in one file. Surround the shaders with #ifdef VERTEX for the vertex shader,
* #ifdef FRAGMENT for the fragment shader, and #ifdef GEOMETRY geometry shaders.
* Programs initialized this way can only have one shader of each type. For more
* general loading, see program_init.
*/
Program * program_init_file(Program * p, const char * path);
/*
* Initializes a program from a named resource.
*/
Program * program_init_resource(Program * p, const char * resource);
/*
* Deinitializes a program.
*/
void program_deinit(Program * p);
#endif
| 2.1875 | 2 |
2024-11-18T19:02:28.597955+00:00 | 2017-01-30T07:28:29 | fbaad502ca068a544c42a52553489199dec7ba13 | {
"blob_id": "fbaad502ca068a544c42a52553489199dec7ba13",
"branch_name": "refs/heads/master",
"committer_date": "2017-01-30T07:28:29",
"content_id": "1836d3036e854cf3e6f21aeeb521fa5857ffc782",
"detected_licenses": [
"Unlicense"
],
"directory_id": "b5aba2557946913e56aa39754f7a9d07cd61025a",
"extension": "c",
"filename": "rtc.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 58046461,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1225,
"license": "Unlicense",
"license_type": "permissive",
"path": "/src/modules/common/rtc.c",
"provenance": "stackv2-0058.json.gz:151047",
"repo_name": "olegv142/NRF51PowerMon",
"revision_date": "2017-01-30T07:28:29",
"revision_id": "7f8e135219b1048923b459061fe7e635f1073c97",
"snapshot_id": "e17ca8d551fa0318a05cb174a96578d7ac61063c",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/olegv142/NRF51PowerMon/7f8e135219b1048923b459061fe7e635f1073c97/src/modules/common/rtc.c",
"visit_date": "2021-01-17T10:23:36.325984"
} | stackv2 | #include "rtc.h"
#include "clock.h"
#include "app_error.h"
#define RTC_OVERFLOW (RTC_COUNTER_COUNTER_Msk+1)
#define RTC_OFFSET(v) (v & ~RTC_COUNTER_COUNTER_Msk)
// The instance of nrf_drv_rtc for RTC0.
const nrf_drv_rtc_t g_rtc = NRF_DRV_RTC_INSTANCE(0);
static unsigned volatile g_rtc_last;
void rtc_initialize(nrf_drv_rtc_handler_t handler)
{
uint32_t err_code;
//Initialize RTC instance
err_code = nrf_drv_rtc_init(&g_rtc, NULL, handler);
APP_ERROR_CHECK(err_code);
//Start 32768Hz crystal clock
lf_osc_start();
//Power on RTC instance
nrf_drv_rtc_enable(&g_rtc);
}
unsigned rtc_current(void)
{
unsigned last = g_rtc_last;
unsigned ticks = nrf_drv_rtc_counter_get(&g_rtc);
unsigned offset = RTC_OFFSET(last);
unsigned last_ticks = RTC_WRAP(last);
/*
* The NFR tick counter is only 3 bytes wide. So we are going to take overflow into account
* The code must work correctly in case its executed concurrently in normal and IRQ context.
*/
if (ticks < RTC_OVERFLOW/4 && last_ticks > 3*RTC_OVERFLOW/4) {
offset += RTC_OVERFLOW;
}
return (g_rtc_last = ticks + offset);
}
void rtc_dummy_handler(nrf_drv_rtc_int_type_t int_type)
{
}
| 2.4375 | 2 |
2024-11-18T19:02:28.668503+00:00 | 2022-04-03T22:24:48 | 251a7d797b5b097a34d50a1b9c38df158301035f | {
"blob_id": "251a7d797b5b097a34d50a1b9c38df158301035f",
"branch_name": "refs/heads/stable",
"committer_date": "2022-04-03T22:24:48",
"content_id": "932cc5b970d43960981bec3d86fe57ed93ed3b31",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "02dc9a326dccc89cb726b379a085d415edd15213",
"extension": "h",
"filename": "tree.h",
"fork_events_count": 12,
"gha_created_at": "2020-05-05T07:45:57",
"gha_event_created_at": "2021-12-21T10:05:30",
"gha_language": "Python",
"gha_license_id": "Apache-2.0",
"github_id": 261392188,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 8183,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/include/tree.h",
"provenance": "stackv2-0058.json.gz:151175",
"repo_name": "AFLplusplus/Grammar-Mutator",
"revision_date": "2022-04-03T22:24:48",
"revision_id": "ff4e5a265daf5d88c4a636fb6a2c22b1d733db09",
"snapshot_id": "b09f7b18467e55ba960682bc0beea892615ece27",
"src_encoding": "UTF-8",
"star_events_count": 173,
"url": "https://raw.githubusercontent.com/AFLplusplus/Grammar-Mutator/ff4e5a265daf5d88c4a636fb6a2c22b1d733db09/include/tree.h",
"visit_date": "2022-05-15T15:13:02.045018"
} | stackv2 | #ifndef __TREE_H__
#define __TREE_H__
#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <string.h>
#include <stdbool.h>
#include "helpers.h"
#include "list.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef struct tree_node node_t;
struct tree_node {
uint32_t id; // node type
uint32_t rule_id; // rule id
// uint8_t *val_buf;
// size_t val_size;
BUF_VAR(uint8_t, val);
uint32_t val_len;
node_t *parent; // parent node
node_t **subnodes;
uint32_t subnode_count;
// The following two sizes are calculated by `node_get_size`
size_t recursion_edge_size; // the total number of recursion edges in the
// subtree
size_t non_term_size; // the number of non-terminal nodes in the subtree
};
typedef struct edge edge_t;
struct edge {
node_t *parent;
node_t *subnode;
size_t subnode_offset;
};
/**
* Create a node and allocate the memory
* @param id The type of the node
* @return A newly created node
*/
node_t *node_create(uint32_t id);
/**
* Create a node and allocate the memory
* @param id The type of the node
* @param rule_id The index of the grammar rule of this node
* @return A newly created node
*/
node_t *node_create_with_rule_id(uint32_t id, uint32_t rule_id);
/**
* Create a node and allocate the memory with a given value
* @param id The type of the node
* @param val_buf The buffer of the attached value
* @param val_len The size of the attached value
* @return A newly created node
*/
node_t *node_create_with_val(uint32_t id, const void *val_buf, size_t val_len);
/**
* Initialize the subnode array.
* @param node The node
* @param n The size of the subnode array
*/
void node_init_subnodes(node_t *node, size_t n);
/**
* Destroy the node and recursively free all memory
* @param node The node
*/
void node_free(node_t *node);
/**
* Destroy the node and free its memory but do not recurse
* and destroy the subnodes.
* This is dangerous and should only be used if you plan to
* manually free all the subnodes as well!
* @param node The node
*/
void node_free_only_self(node_t *node);
/**
* Set the concrete value for the node
* @param node The node
* @param val_buf The buffer of the attached value
* @param val_len The size of the attached value
*/
void node_set_val(node_t *node, const void *val_buf, size_t val_len);
/**
* Set i-th subnode. `i` should be less than the number of subnodes. (i.e., i <
* node->subnode_count)
* @param node The node
* @param i The index of the subnode
* @param subnode The added subnode
*/
void node_set_subnode(node_t *node, size_t i, node_t *subnode);
/**
* Clone a node, including all subnodes
* @param node The node
* @return A newly created node with the same data as `node`
*/
node_t *node_clone(node_t *node);
/**
* Compare recursively whether two nodes have the same values and subnodes
* @param node_a One node
* @param node_b Another node
* @return True (1) if two nodes are the same; otherwise, false (0)
*/
bool node_equal(node_t *node_a, node_t *node_b);
/**
* Calculate the total number of non-terminal subnodes and the total number of
* recursive edges in the tree
* @param node The root node of a tree
*/
void node_get_size(node_t *node);
/**
* Replace `subnode` in a stree (`root`) with `new_subnode`. Note that, this
* function will not destroy `subnode` and free its memory.
* @param root The root node of a tree
* @param subnode A subnode or the root node
* @param replace_node A new subnode that will be added
* @return True (1) if the subnode has been successfully replaced;
* otherwise, false (0)
*/
bool node_replace_subnode(node_t *root, node_t *subnode, node_t *new_subnode);
/**
* Uniformly pick a subnode in a tree (`node`). As we track the number of
* non-terminal nodes while adding the subnode (see `node_append_subnode`), for
* each node node in a tree, the probability of being selected is `1 / the
* number of non-terminal subnodes in the tree`.
*
* Alternative solution: We can first apply pre-order traversal on the tree
* and dump the tree to an array. Then, randomly pick an element in the array.
* @param node The root node of a tree
* @return The randomly picked subnode
*/
node_t *node_pick_non_term_subnode(node_t *node);
/**
* Similar to `node_pick_non_term_subnode`, this function uniformly picks a
* recursion edge, in which two end points have the same node type (i.e., `id`).
* @param node The root node of a tree
* @return The randomly picked recursion edge
*/
edge_t node_pick_recursion_edge(node_t *node);
/**
* Find the edge between the given `node` and its parent `node->parent`, if any
* @param node The root node of a tree
* @return The edge between the given node and its parent; otherwise, NULL
*/
edge_t node_get_parent_edge(node_t *node);
typedef struct tree {
node_t *root;
// uint8_t *data_buf;
// size_t data_size;
BUF_VAR(uint8_t, data);
size_t data_len; // data_len <= data_size
// uint8_t *ser_buf;
// size_t ser_size;
BUF_VAR(uint8_t, ser);
size_t ser_len; // ser_len <= ser_size
list_t *non_terminal_node_list;
list_t *recursion_edge_list;
} tree_t;
/**
* Create a tree and allocate the memory
* @return A newly created tree
*/
tree_t *tree_create();
/**
* Destroy the tree and free all memory
* @param tree The parsing tree
*/
void tree_free(tree_t *tree);
/**
* Convert a parsing tree into a concrete test case stored in the data buffer
* @param tree The parsing tree
*/
void tree_to_buf(tree_t *tree);
/**
* Parse the given buffer to construct a parsing tree
* @param data_buf The buffer of a test case
* @param data_size The size of the buffer
* @return A newly created tree
*/
tree_t *tree_from_buf(const uint8_t *data_buf, size_t data_size);
/**
* Serialize a given tree into binary data
* @param tree A given tree
*/
void tree_serialize(tree_t *tree);
/**
* Deserialize the data to recover a tree
* @param data_buf The buffer of a serialized tree
* @param data_size The size of the buffer
* @return A newly created tree
*/
tree_t *tree_deserialize(const uint8_t *data_buf, size_t data_size);
/**
* Clone a parsing tree
* @param tree The parsing tree
* @return A newly created tree with the same data as `tree`
*/
tree_t *tree_clone(tree_t *tree);
/**
* Compare whether two parsing trees have the same architecture, and
* corresponding nodes have the same values
* @param tree_a One paring tree
* @param tree_b Another parsing tree
* @return True (1) if two trees are the same; otherwise, false (0)
*/
bool tree_equal(tree_t *tree_a, tree_t *tree_b);
/**
* Calculate the size of a given tree (i.e., the total number of non-terminal
* nodes in a tree).
* @param tree A given tree
* @return The total number of non-terminal nodes in this tree
*/
size_t tree_get_size(tree_t *tree);
/**
* Get all recursion edges in the tree, and store them in a linked list
* @param tree A given tree
*/
void tree_get_recursion_edges(tree_t *tree);
/**
* Get all non-terminal nodes in the tree, and store them in a linked list
* @param tree A given tree
*/
void tree_get_non_terminal_nodes(tree_t *tree);
/**
* Read/Deserialize a tree from a file
* @param filename The path to the tree file
* @return The deserialized tree
*/
tree_t *read_tree_from_file(const char *filename);
/**
* Load/Parse a tree from a test case file
* @param filename The path to the fuzzing test case
* @return The parsed tree
*/
tree_t *load_tree_from_test_case(const char *filename);
/**
* Write/Serialize a tree to a file
* @param tree The tree to be written to the file
* @param filename The path to the tree file
*/
void write_tree_to_file(tree_t *tree, const char *filename);
/**
* Dump a tree to a test case file
* @param tree The tree to be written to the file
* @param filename The path to the test case file
*/
void dump_tree_to_test_case(tree_t *tree, const char *filename);
#ifdef __cplusplus
}
#endif
#endif
| 2.96875 | 3 |
2024-11-18T19:02:28.731405+00:00 | 2019-07-13T05:09:05 | 071b0a1516aa452ccedc755bd159f4035a6bb698 | {
"blob_id": "071b0a1516aa452ccedc755bd159f4035a6bb698",
"branch_name": "refs/heads/master",
"committer_date": "2019-07-13T05:09:05",
"content_id": "71bcb761e1d839828608cd7cdbc9f0321468106b",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "c77e4bb8b39c765fccfc0726b63d94589bfbdf0d",
"extension": "h",
"filename": "common.h",
"fork_events_count": 0,
"gha_created_at": "2019-07-05T02:14:38",
"gha_event_created_at": "2019-07-05T02:14:38",
"gha_language": null,
"gha_license_id": "Apache-2.0",
"github_id": 195324125,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 8283,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/include/common.h",
"provenance": "stackv2-0058.json.gz:151303",
"repo_name": "lanyuqingri/yodart",
"revision_date": "2019-07-13T05:09:05",
"revision_id": "f598363d042b0d9ce98f1d81c662992ef4fa5c31",
"snapshot_id": "d5911f163a0a667152d424108447f401b71f8de3",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/lanyuqingri/yodart/f598363d042b0d9ce98f1d81c662992ef4fa5c31/include/common.h",
"visit_date": "2020-06-20T11:51:01.120171"
} | stackv2 | #ifndef YODA_COMMON_H_
#define YODA_COMMON_H_
#include <node_api.h>
// Empty value so that macros here are able to return NULL or void
#define NAPI_RETVAL_NOTHING // Intentionally blank #define
#define GET_AND_THROW_LAST_ERROR(env) \
do { \
const napi_extended_error_info* error_info; \
napi_get_last_error_info((env), &error_info); \
bool is_pending; \
napi_is_exception_pending((env), &is_pending); \
/* If an exception is already pending, don't rethrow it */ \
if (!is_pending) { \
const char* error_message = error_info->error_message != NULL \
? error_info->error_message \
: "empty error message"; \
napi_throw_error((env), NULL, error_message); \
} \
} while (0)
#define NAPI_ASSERT_BASE(env, assertion, message, ret_val) \
do { \
if (!(assertion)) { \
napi_throw_error((env), NULL, \
"assertion (" #assertion ") failed: " message); \
return ret_val; \
} \
} while (0)
// Returns NULL on failed assertion.
// This is meant to be used inside napi_callback methods.
#define NAPI_ASSERT(env, assertion, message) \
NAPI_ASSERT_BASE(env, assertion, message, NULL)
// Returns empty on failed assertion.
// This is meant to be used inside functions with void return type.
#define NAPI_ASSERT_RETURN_VOID(env, assertion, message) \
NAPI_ASSERT_BASE(env, assertion, message, NAPI_RETVAL_NOTHING)
#define NAPI_CALL_BASE(env, the_call, ret_val) \
do { \
if ((the_call) != napi_ok) { \
GET_AND_THROW_LAST_ERROR((env)); \
return ret_val; \
} \
} while (0)
// Returns NULL if the_call doesn't return napi_ok.
#define NAPI_CALL(env, the_call) NAPI_CALL_BASE(env, the_call, NULL)
// Returns empty if the_call doesn't return napi_ok.
#define NAPI_CALL_RETURN_VOID(env, the_call) \
NAPI_CALL_BASE(env, the_call, NAPI_RETVAL_NOTHING)
#define DECLARE_NAPI_PROPERTY(name, func) \
{ (name), 0, (func), 0, 0, 0, napi_default, 0 }
#define DECLARE_NAPI_GETTER(name, func) \
{ (name), 0, 0, (func), 0, 0, napi_default, 0 }
#define SET_NAMED_METHOD(env, target, prop_name, handler) \
do { \
napi_status status; \
napi_value fn; \
status = napi_create_function(env, NULL, 0, handler, NULL, &fn); \
if (status != napi_ok) \
return NULL; \
\
status = napi_set_named_property(env, target, prop_name, fn); \
if (status != napi_ok) \
return NULL; \
} while (0);
#define GET_NAMED_STRING_PROPERTY(env, target, key, buf, len, res) \
do { \
napi_value nval; \
NAPI_CALL(env, napi_get_named_property(env, target, key, &nval)); \
NAPI_CALL(env, napi_get_value_string_utf8(env, nval, buf, len, res)); \
} while (0);
#define GET_NAMED_INT_PROPERTY(env, target, key, res) \
do { \
napi_value nval; \
NAPI_CALL(env, napi_get_named_property(env, target, key, &nval)); \
NAPI_CALL(env, napi_get_value_int32(env, nval, res)); \
} while (0);
#define NAPI_SET_CONSTANT(target, name) \
do { \
napi_value key; \
napi_value value; \
napi_create_string_utf8(env, #name, strlen(#name), &key); \
napi_create_int32(env, name, &value); \
napi_set_property(env, target, key, value); \
} while (0);
#define NAPI_GET_LAST_ERROR_MSG(env) \
({ \
const char* msg = nullptr; \
const napi_extended_error_info* error; \
if (napi_get_last_error_info(env, &error) == napi_ok) { \
msg = error->error_message; \
} \
msg; \
})
#define NAPI_COPY_STRING(env, value, size) \
({ \
char* str = nullptr; \
if ((napi_get_value_string_utf8(env, (value), NULL, 0, &(size)) == \
napi_ok) && \
((str = (char*)malloc(size + 1)) != nullptr)) { \
if (napi_get_value_string_utf8(env, (value), str, (size) + 1, NULL) != \
napi_ok) { \
free(str); \
str = nullptr; \
} else { \
str[size] = '\0'; \
} \
} \
str; \
})
#define NAPI_ASSIGN_STD_STRING(env, stdstr, value) \
({ \
size_t len = 0; \
char* s = NAPI_COPY_STRING(env, value, len); \
if (s) { \
(stdstr).assign(s, len); \
free(s); \
} \
len; \
})
#define NAPI_GET_PROPERTY(env, obj, ckey, nkey, expectedType) \
({ \
napi_value key = (nkey), value = nullptr; \
bool has = false; \
napi_valuetype type; \
if (((key || \
napi_create_string_utf8(env, (ckey), NAPI_AUTO_LENGTH, &key) == \
napi_ok)) && \
(napi_has_property(env, (obj), key, &has) == napi_ok) && has && \
(napi_get_property(env, (obj), key, &value) == napi_ok)) { \
if ((napi_typeof(env, value, &type) != napi_ok) || \
type != (expectedType)) { \
value = nullptr; \
} \
} \
value; \
})
#endif
| 2.4375 | 2 |
2024-11-18T19:02:28.898255+00:00 | 2016-11-20T08:36:38 | 5be8a864dd17f4d9b8003723bd2161f1ed44e9bb | {
"blob_id": "5be8a864dd17f4d9b8003723bd2161f1ed44e9bb",
"branch_name": "refs/heads/master",
"committer_date": "2016-11-20T08:36:38",
"content_id": "1c32e7740d844ce38938e8fed8253a067a60cca6",
"detected_licenses": [
"MIT"
],
"directory_id": "4bf1641d6d48ec6ab76ebb662427181a9b170c79",
"extension": "c",
"filename": "getenv_test.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 73897959,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 467,
"license": "MIT",
"license_type": "permissive",
"path": "/getenv/getenv_test.c",
"provenance": "stackv2-0058.json.gz:151562",
"repo_name": "disenone/aparsing",
"revision_date": "2016-11-20T08:36:38",
"revision_id": "7dbf9e7b4c74e01c4be468fff32b9207dfec9a21",
"snapshot_id": "5f61f804aa2a4dec2e5a2952caa450ed432d9e6d",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/disenone/aparsing/7dbf9e7b4c74e01c4be468fff32b9207dfec9a21/getenv/getenv_test.c",
"visit_date": "2020-07-12T22:20:20.387303"
} | stackv2 | // getenv example
#include <stdlib.h>
#include <stdio.h>
//GETENV_ADD=abc GETENV_NUM=2 ./getenv_test
int main (int argc, char **argv)
{
char *add, *num;
if((add = getenv("GETENV_ADD")))
printf("GETENV_ADD = %s\n", add);
else
printf("GETENV_ADD not found\n");
if((num = getenv("GETENV_NUM")))
{
int numi = atoi(num);
printf("GETENV_NUM = %d\n", numi);
}
else
printf("GETENV_NUM not found\n");
}
| 2.796875 | 3 |
2024-11-18T19:02:29.129335+00:00 | 2019-09-09T16:41:48 | 71a6a7e607a8fa5eb9f87d067cfa2d114372c9db | {
"blob_id": "71a6a7e607a8fa5eb9f87d067cfa2d114372c9db",
"branch_name": "refs/heads/master",
"committer_date": "2019-09-09T16:41:48",
"content_id": "75edea08141b86737f136b883bc4c3badce93890",
"detected_licenses": [
"MIT"
],
"directory_id": "1889abd8b9cdb457a425cbbac0b1616a1c4d3d95",
"extension": "c",
"filename": "mem.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 207356717,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1438,
"license": "MIT",
"license_type": "permissive",
"path": "/mem.c",
"provenance": "stackv2-0058.json.gz:151820",
"repo_name": "baselsayeh/chip-8_emulator",
"revision_date": "2019-09-09T16:41:48",
"revision_id": "80314d697b47d970d7c6abea7b2c1c90492c9332",
"snapshot_id": "8a6d2a0894d63d82f522e5b7a9b19545efba9258",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/baselsayeh/chip-8_emulator/80314d697b47d970d7c6abea7b2c1c90492c9332/mem.c",
"visit_date": "2020-07-22T22:50:48.205394"
} | stackv2 | #include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include "include/mem.h"
uint8_t mem_array[0x1000];
void init_mem() {
memset(&mem_array, 0x00, sizeof(mem_array));
}
void mem_store(uint16_t addr, uint16_t data, uint8_t len) {
if (len == 0 || len > 2) {
printf("Error: length is not 1 or 2, got %02X\n", len);
exit(-1);
}
if (addr == 0xFFF && len == 2) {
printf("Tried to write to 0xFFF with 2 bytes!!!\n", len);
exit(-1);
}
if (addr > 0xFFF) {
printf("Tried to write from 0x%04X, but it is not existant!!!\n", addr);
exit(-1);
}
if (len == 1)
mem_array[addr] = (data&0xFF);
else {
mem_array[addr] = (data&0xFF00)>>8;
mem_array[addr+1] = (data&0xFF);
}
}
uint16_t mem_load(uint16_t addr, uint8_t len) {
uint16_t ret_val = 0;
if (len == 0 || len > 2) {
printf("Error: length is not 1 or 2, got %02X\n", len);
exit(-1);
}
if (addr == 0xFFF && len == 2) {
printf("Tried to read to 0xFFF with 2 bytes!!!\n", len);
exit(-1);
}
if (addr > 0xFFF) {
printf("Tried to read from 0x%04X, but it is not existant!!!\n", addr);
exit(-1);
}
if (len == 1)
ret_val = mem_array[addr];
else {
ret_val = mem_array[addr]<<8;
ret_val |= mem_array[addr+1];
}
return ret_val;
}
| 2.9375 | 3 |
2024-11-18T19:02:29.255675+00:00 | 2020-01-27T17:41:05 | 1032ff34f2e91eeabd074a2c34744b6765dd5bf6 | {
"blob_id": "1032ff34f2e91eeabd074a2c34744b6765dd5bf6",
"branch_name": "refs/heads/master",
"committer_date": "2020-01-27T17:41:05",
"content_id": "f36104faf036d47823f08b019e7ac19cbb5edc47",
"detected_licenses": [
"MIT"
],
"directory_id": "41b7f7ffd7b490a7fe1f81dca7d24e30535bf439",
"extension": "c",
"filename": "2.c",
"fork_events_count": 9,
"gha_created_at": "2019-10-08T08:15:08",
"gha_event_created_at": "2020-01-26T22:41:45",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 213585818,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1129,
"license": "MIT",
"license_type": "permissive",
"path": "/kr/81585/2.c",
"provenance": "stackv2-0058.json.gz:151948",
"repo_name": "rgeorgiev583/sp-2019-2020",
"revision_date": "2020-01-27T17:41:05",
"revision_id": "6ca301e3d63c639d95d8e6659d105f480a39deb8",
"snapshot_id": "0515620107924be1cd082540e068ccc1642b6eeb",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/rgeorgiev583/sp-2019-2020/6ca301e3d63c639d95d8e6659d105f480a39deb8/kr/81585/2.c",
"visit_date": "2020-08-07T21:01:47.424563"
} | stackv2 | #include<unistd.h>
#include<stdlib.h>
#include<stdio.h>
#include<fcntl.h>
#include<wait.h>
void tr_without_args(const char* set1, const char* set2){
int e1 = fork();
if(e1==0){
execlp("tr", "tr", set1, set2, NULL);
}
else{
int status;
waitpid(e1, &status, 0);
}
}
void tr_with_args(const char* set1, const char* set2, const char* filename){
int e1=fork();
if(e1==0){
int fd[2];
if(pipe(fd) == -1){
perror("Pipe failure!");
exit(EXIT_FAILURE);
}
int e2=fork();
if(e2==0){
close(fd[0]);
dup2(fd[1], STDOUT_FILENO);
execlp("cat", "cat", filename, NULL);
}
else{
close(fd[1]);
dup2(fd[0], STDIN_FILENO);
waitpid(e2, NULL, 0);
execlp("tr", "tr", set1, set2, NULL);
}
}
else{
int status;
waitpid(e1, &status, 0);
}
}
int main(const int argc, const char** argv){
if(argc < 3){
perror("Invalid number of arguments!");
exit(EXIT_FAILURE);
}
const char* set1 = argv[1];
const char* set2 = argv[2];
if(argc == 3){
tr_without_args(set1, set2);
exit(EXIT_SUCCESS);
}
for(int i=3; i<argc; i++){
tr_with_args(set1, set2, argv[i]);
}
exit(EXIT_SUCCESS);
} | 2.984375 | 3 |
2024-11-18T19:02:29.316106+00:00 | 2018-04-27T05:12:07 | a383c00ce1e8853c9c27c69a314f41a1ee82cf36 | {
"blob_id": "a383c00ce1e8853c9c27c69a314f41a1ee82cf36",
"branch_name": "refs/heads/master",
"committer_date": "2018-04-27T05:12:07",
"content_id": "d3281a92fd56240909d102e449f5e076bb06f911",
"detected_licenses": [
"MIT"
],
"directory_id": "36998b36bfac26eff7dfeb83eaeb7b817cdc2588",
"extension": "c",
"filename": "io.c",
"fork_events_count": 0,
"gha_created_at": "2019-03-13T10:51:27",
"gha_event_created_at": "2019-03-13T10:51:32",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 175401878,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3583,
"license": "MIT",
"license_type": "permissive",
"path": "/OttoFuel/lib/io.c",
"provenance": "stackv2-0058.json.gz:152076",
"repo_name": "JaguarCN/modbus_rtu_master",
"revision_date": "2018-04-27T05:12:07",
"revision_id": "9d6f4f02418016834207ac16165887e8a2ab94a6",
"snapshot_id": "70051ad615b4e8809054651aceba6ba1baaf5876",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/JaguarCN/modbus_rtu_master/9d6f4f02418016834207ac16165887e8a2ab94a6/OttoFuel/lib/io.c",
"visit_date": "2020-04-28T16:11:43.639843"
} | stackv2 | #include <avr/io.h>
//---------------------- Pin Mapping ------------------------------------- Pin Mapping -----------
#define SETBIT(ADDRESS,BIT) (ADDRESS |= (1<<BIT))
#define CLEARBIT(ADDRESS,BIT) (ADDRESS &= ~(1<<BIT))
#define FLIPBIT(ADDRESS,BIT) (ADDRESS ^= (1<<BIT))
#define CHECKBIT(ADDRESS,BIT) (ADDRESS & (1<<BIT))
#define SETONLY(ADDRESS,BIT) (ADDRESS = (1<<BIT))
#define SETBITMASK(x,y) (x |= (y))
#define CLEARBITMASK(x,y) (x &= (~y))
#define FLIPBITMASK(x,y) (x ^= (y))
#define CHECKBITMASK(x,y) (x & (y))
#define VARFROMCOMB(x, y) x
#define BITFROMCOMB(x, y) y
#define C_SETBIT(comb) SETBIT(VARFROMCOMB(comb), BITFROMCOMB(comb))
#define C_CLEARBIT(comb) CLEARBIT(VARFROMCOMB(comb), BITFROMCOMB(comb))
#define C_FLIPBIT(comb) FLIPBIT(VARFROMCOMB(comb), BITFROMCOMB(comb))
#define C_CHECKBIT(comb) CHECKBIT(VARFROMCOMB(comb), BITFROMCOMB(comb))
#define LCD_LINES 4 /**< number of visible lines of the display */
#define LCD_DISP_LENGTH 20 /**< visible characters per line of the display */
#define LCD_DATA0_PORT PORTB /**< port for 4bit data bit 0 */
#define LCD_DATA1_PORT PORTD /**< port for 4bit data bit 1 */
#define LCD_DATA2_PORT PORTD /**< port for 4bit data bit 2 */
#define LCD_DATA3_PORT PORTD /**< port for 4bit data bit 3 */
#define LCD_DATA0_PIN 0 /**< pin for 4bit data bit 0 */
#define LCD_DATA1_PIN 7 /**< pin for 4bit data bit 1 */
#define LCD_DATA2_PIN 6 /**< pin for 4bit data bit 2 */
#define LCD_DATA3_PIN 5 /**< pin for 4bit data bit 3 */
#define LCD_RS_PORT PORTC /**< port for RS line */
#define LCD_RS_PIN 0 /**< pin for RS line */
#define LCD_RW_PORT PORTC /**< port for RW line */
#define LCD_RW_PIN 1 /**< pin for RW line */
#define LCD_E_PORT PORTC /**< port for Enable line */
#define LCD_E_PIN 2 /**< pin for Enable line */
//---------------------I/O Pin Define--------------------------------------I/O Pin Define-------------------
//Inputs
#define KEY_SET PIND, 4 // Key_SET in Schematic
#define KEY_ENT PIND, 3 // Key_EN in Schematic
#define KEY_UP PINB, 7 // Key_UP in Schematic
#define KEY_DN PINB, 6 // Key_DN in Schematic
#define DIR_KEY_SET DDRD, 4 // Key_SET in Schematic
#define DIR_KEY_ENT DDRD, 3 // Key_EN in Schematic
#define DIR_KEY_UP DDRB, 7 // Key_UP in Schematic
#define DIR_KEY_DN DDRB, 6 // Key_DN in Schematic
#define PORT_KEY_SET PORTD, 4 // Key_SET in Schematic
#define PORT_KEY_ENT PORTD, 3 // Key_EN in Schematic
#define PORT_KEY_UP PORTB, 7 // Key_UP in Schematic
#define PORT_KEY_DN PORTB, 6 // Key_DN in Schematic
//Port for LED
#define LED_HEATER PORTC, 3 //LED for Heater Status Indication (HTR_ON)
#define LED_PUMP PORTB, 1 //LED for Pump Status Indication (PUMP_ON)
//Direction for LED
#define DIR_LED_HEATER DDRC, 3 //LED for Heater Status Indication (HTR_ON)
#define DIR_LED_PUMP DDRB, 1 //LED for Pump Status Indication (PUMP_ON)
/*
// Control Line for Sampling Pump
#define PUMP PORTB, 2
// Direction for for Sampling Pump I/O Line
#define PUMP DDRB, 2
*/
// PWM OUT for Sampling Pump
#define PWM PORTB, 2
// Direction for PWM / Sampling Pump
#define DIR_PWM DDRB, 2
// Transmit Enable for MAX487 (RS485 Driver)
#define TX_EN PORTD, 2
// Direction for Transmit Enable for MAX487 (RS485 Driver)
#define DIR_TX_EN DDRD, 2
| 2.25 | 2 |
2024-11-18T19:02:29.404054+00:00 | 2023-09-04T20:58:04 | 15f5d5f38c3e992e070aba50bca938d28e251795 | {
"blob_id": "15f5d5f38c3e992e070aba50bca938d28e251795",
"branch_name": "refs/heads/main",
"committer_date": "2023-09-04T20:58:04",
"content_id": "0a6eb3615d31822dcf3d27b4478c6762e31fdf30",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "15567948b5c7495ca875f8ac77bfccb7cab91d8b",
"extension": "c",
"filename": "curve25519_solinas.c",
"fork_events_count": 3,
"gha_created_at": "2022-07-20T10:45:48",
"gha_event_created_at": "2023-09-11T21:02:47",
"gha_language": "TypeScript",
"gha_license_id": "Apache-2.0",
"github_id": 515941188,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 13879,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/test/manual-bridge/modmul/curve25519_solinas.c",
"provenance": "stackv2-0058.json.gz:152205",
"repo_name": "0xADE1A1DE/CryptOpt",
"revision_date": "2023-09-04T20:58:04",
"revision_id": "f127f0a50fd29e761868014eaf44cecbf5fc38e8",
"snapshot_id": "4dc4ff24291c2c8da64902448c23ed5225e2e1f7",
"src_encoding": "UTF-8",
"star_events_count": 32,
"url": "https://raw.githubusercontent.com/0xADE1A1DE/CryptOpt/f127f0a50fd29e761868014eaf44cecbf5fc38e8/test/manual-bridge/modmul/curve25519_solinas.c",
"visit_date": "2023-09-05T10:42:45.142914"
} | stackv2 | /* Autogenerated: 'src/ExtractionOCaml/solinas_reduction' --inline --static
* --use-value-barrier curve25519_solinas 64 '2^255 - 19' mulmod */
/* curve description: curve25519_solinas */
/* machine_wordsize = 64 (from "64") */
/* requested operations: mulmod */
/* s-c = 2^255 - [(1, 19)] (from "2^255 - 19") */
/* */
/* Computed values: */
/* */
#include <stdint.h>
typedef unsigned char fiat_curve25519_solinas_uint1;
typedef signed char fiat_curve25519_solinas_int1;
#if defined(__GNUC__) || defined(__clang__)
#define FIAT_CURVE25519_SOLINAS_FIAT_EXTENSION __extension__
#define FIAT_CURVE25519_SOLINAS_FIAT_INLINE __inline__
#else
#define FIAT_CURVE25519_SOLINAS_FIAT_EXTENSION
#define FIAT_CURVE25519_SOLINAS_FIAT_INLINE
#endif
FIAT_CURVE25519_SOLINAS_FIAT_EXTENSION typedef signed __int128
fiat_curve25519_solinas_int128;
FIAT_CURVE25519_SOLINAS_FIAT_EXTENSION typedef unsigned __int128
fiat_curve25519_solinas_uint128;
#if (-1 & 3) != 3
#error "This code only works on a two's complement system"
#endif
#if !defined(FIAT_CURVE25519_SOLINAS_NO_ASM) && \
(defined(__GNUC__) || defined(__clang__))
static __inline__ uint64_t
fiat_curve25519_solinas_value_barrier_u64(uint64_t a) {
__asm__("" : "+r"(a) : /* no inputs */);
return a;
}
#else
#endif
/*
* The function fiat_curve25519_solinas_cmovznz_u64 is a single-word conditional
* move.
*
* Postconditions:
* out1 = (if arg1 = 0 then arg2 else arg3)
*
* Input Bounds:
* arg1: [0x0 ~> 0x1]
* arg2: [0x0 ~> 0xffffffffffffffff]
* arg3: [0x0 ~> 0xffffffffffffffff]
* Output Bounds:
* out1: [0x0 ~> 0xffffffffffffffff]
*/
static FIAT_CURVE25519_SOLINAS_FIAT_INLINE void
fiat_curve25519_solinas_cmovznz_u64(uint64_t *out1,
fiat_curve25519_solinas_uint1 arg1,
uint64_t arg2, uint64_t arg3) {
fiat_curve25519_solinas_uint1 x1;
uint64_t x2;
uint64_t x3;
x1 = (!(!arg1));
x2 = ((fiat_curve25519_solinas_uint1)(0x0 - x1) &
UINT64_C(0xffffffffffffffff));
x3 = ((fiat_curve25519_solinas_value_barrier_u64(x2) & arg3) |
(fiat_curve25519_solinas_value_barrier_u64((~x2)) & arg2));
*out1 = x3;
}
/*
* The function fiat_curve25519_solinas_addcarryx_u64 is an addition with carry.
*
* Postconditions:
* out1 = (arg1 + arg2 + arg3) mod 2^64
* out2 = ⌊(arg1 + arg2 + arg3) / 2^64⌋
*
* Input Bounds:
* arg1: [0x0 ~> 0x1]
* arg2: [0x0 ~> 0xffffffffffffffff]
* arg3: [0x0 ~> 0xffffffffffffffff]
* Output Bounds:
* out1: [0x0 ~> 0xffffffffffffffff]
* out2: [0x0 ~> 0x1]
*/
static FIAT_CURVE25519_SOLINAS_FIAT_INLINE void
fiat_curve25519_solinas_addcarryx_u64(uint64_t *out1,
fiat_curve25519_solinas_uint1 *out2,
fiat_curve25519_solinas_uint1 arg1,
uint64_t arg2, uint64_t arg3) {
fiat_curve25519_solinas_uint128 x1;
uint64_t x2;
fiat_curve25519_solinas_uint1 x3;
x1 = ((arg1 + (fiat_curve25519_solinas_uint128)arg2) + arg3);
x2 = (uint64_t)(x1 & UINT64_C(0xffffffffffffffff));
x3 = (fiat_curve25519_solinas_uint1)(x1 >> 64);
*out1 = x2;
*out2 = x3;
}
/*
* The function fiat_curve25519_solinas_subborrowx_u64 is a subtraction with
* borrow.
*
* Postconditions:
* out1 = (-arg1 + arg2 + -arg3) mod 2^64
* out2 = -⌊(-arg1 + arg2 + -arg3) / 2^64⌋
*
* Input Bounds:
* arg1: [0x0 ~> 0x1]
* arg2: [0x0 ~> 0xffffffffffffffff]
* arg3: [0x0 ~> 0xffffffffffffffff]
* Output Bounds:
* out1: [0x0 ~> 0xffffffffffffffff]
* out2: [0x0 ~> 0x1]
*/
static FIAT_CURVE25519_SOLINAS_FIAT_INLINE void
fiat_curve25519_solinas_subborrowx_u64(uint64_t *out1,
fiat_curve25519_solinas_uint1 *out2,
fiat_curve25519_solinas_uint1 arg1,
uint64_t arg2, uint64_t arg3) {
fiat_curve25519_solinas_int128 x1;
fiat_curve25519_solinas_int1 x2;
uint64_t x3;
x1 = ((arg2 - (fiat_curve25519_solinas_int128)arg1) - arg3);
x2 = (fiat_curve25519_solinas_int1)(x1 >> 64);
x3 = (uint64_t)(x1 & UINT64_C(0xffffffffffffffff));
*out1 = x3;
*out2 = (fiat_curve25519_solinas_uint1)(0x0 - x2);
}
/*
* The function fiat_curve25519_solinas_mulx_u64 is a multiplication, returning
* the full double-width result.
*
* Postconditions:
* out1 = (arg1 * arg2) mod 2^64
* out2 = ⌊arg1 * arg2 / 2^64⌋
*
* Input Bounds:
* arg1: [0x0 ~> 0xffffffffffffffff]
* arg2: [0x0 ~> 0xffffffffffffffff]
* Output Bounds:
* out1: [0x0 ~> 0xffffffffffffffff]
* out2: [0x0 ~> 0xffffffffffffffff]
*/
static FIAT_CURVE25519_SOLINAS_FIAT_INLINE void
fiat_curve25519_solinas_mulx_u64(uint64_t *out1, uint64_t *out2, uint64_t arg1,
uint64_t arg2) {
fiat_curve25519_solinas_uint128 x1;
uint64_t x2;
uint64_t x3;
x1 = ((fiat_curve25519_solinas_uint128)arg1 * arg2);
x2 = (uint64_t)(x1 & UINT64_C(0xffffffffffffffff));
x3 = (uint64_t)(x1 >> 64);
*out1 = x2;
*out2 = x3;
}
/*
* The function fiat_curve25519_solinas_mulmod multiplies two field elements.
*
* Postconditions:
* evalf out1 mod
* 57896044618658097711785492504343953926634992332820282019728792003956564819949
* = (evalf arg1 * evalf arg2) mod
* 57896044618658097711785492504343953926634992332820282019728792003956564819949
*
* Input Bounds:
* arg1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~>
* 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] arg2: [[0x0 ~>
* 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~>
* 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] Output Bounds: out1: [[0x0
* ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~>
* 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]]
*/
void fiat_curve25519_solinas_mulmod(uint64_t out1[4], const uint64_t arg1[4],
const uint64_t arg2[4]) {
uint64_t x1;
uint64_t x2;
uint64_t x3;
uint64_t x4;
uint64_t x5;
uint64_t x6;
uint64_t x7;
uint64_t x8;
uint64_t x9;
uint64_t x10;
uint64_t x11;
uint64_t x12;
uint64_t x13;
uint64_t x14;
uint64_t x15;
uint64_t x16;
uint64_t x17;
uint64_t x18;
uint64_t x19;
uint64_t x20;
uint64_t x21;
uint64_t x22;
uint64_t x23;
uint64_t x24;
uint64_t x25;
uint64_t x26;
uint64_t x27;
uint64_t x28;
uint64_t x29;
uint64_t x30;
uint64_t x31;
uint64_t x32;
uint64_t x33;
fiat_curve25519_solinas_uint1 x34;
uint64_t x35;
fiat_curve25519_solinas_uint1 x36;
uint64_t x37;
uint64_t x38;
fiat_curve25519_solinas_uint1 x39;
uint64_t x40;
fiat_curve25519_solinas_uint1 x41;
uint64_t x42;
fiat_curve25519_solinas_uint1 x43;
uint64_t x44;
uint64_t x45;
fiat_curve25519_solinas_uint1 x46;
uint64_t x47;
fiat_curve25519_solinas_uint1 x48;
uint64_t x49;
fiat_curve25519_solinas_uint1 x50;
uint64_t x51;
fiat_curve25519_solinas_uint1 x52;
uint64_t x53;
fiat_curve25519_solinas_uint1 x54;
uint64_t x55;
uint64_t x56;
fiat_curve25519_solinas_uint1 x57;
uint64_t x58;
fiat_curve25519_solinas_uint1 x59;
uint64_t x60;
fiat_curve25519_solinas_uint1 x61;
uint64_t x62;
fiat_curve25519_solinas_uint1 x63;
uint64_t x64;
fiat_curve25519_solinas_uint1 x65;
uint64_t x66;
fiat_curve25519_solinas_uint1 x67;
uint64_t x68;
fiat_curve25519_solinas_uint1 x69;
uint64_t x70;
fiat_curve25519_solinas_uint1 x71;
uint64_t x72;
fiat_curve25519_solinas_uint1 x73;
uint64_t x74;
fiat_curve25519_solinas_uint1 x75;
uint64_t x76;
fiat_curve25519_solinas_uint1 x77;
uint64_t x78;
fiat_curve25519_solinas_uint1 x79;
uint64_t x80;
fiat_curve25519_solinas_uint1 x81;
uint64_t x82;
fiat_curve25519_solinas_uint1 x83;
uint64_t x84;
fiat_curve25519_solinas_uint1 x85;
uint64_t x86;
fiat_curve25519_solinas_uint1 x87;
uint64_t x88;
fiat_curve25519_solinas_uint1 x89;
uint64_t x90;
fiat_curve25519_solinas_uint1 x91;
uint64_t x92;
fiat_curve25519_solinas_uint1 x93;
uint64_t x94;
fiat_curve25519_solinas_uint1 x95;
uint64_t x96;
uint64_t x97;
uint64_t x98;
uint64_t x99;
uint64_t x100;
uint64_t x101;
uint64_t x102;
fiat_curve25519_solinas_uint1 x103;
uint64_t x104;
fiat_curve25519_solinas_uint1 x105;
uint64_t x106;
uint64_t x107;
uint64_t x108;
fiat_curve25519_solinas_uint1 x109;
uint64_t x110;
uint64_t x111;
uint64_t x112;
uint64_t x113;
fiat_curve25519_solinas_uint1 x114;
uint64_t x115;
fiat_curve25519_solinas_uint1 x116;
uint64_t x117;
fiat_curve25519_solinas_uint1 x118;
uint64_t x119;
fiat_curve25519_solinas_uint1 x120;
uint64_t x121;
uint64_t x122;
uint64_t x123;
uint64_t x124;
fiat_curve25519_solinas_uint1 x125;
uint64_t x126;
fiat_curve25519_solinas_uint1 x127;
uint64_t x128;
fiat_curve25519_solinas_uint1 x129;
uint64_t x130;
fiat_curve25519_solinas_uint1 x131;
uint64_t x132;
uint64_t x133;
uint64_t x134;
fiat_curve25519_solinas_uint1 x135;
uint64_t x136;
fiat_curve25519_solinas_uint1 x137;
uint64_t x138;
fiat_curve25519_solinas_uint1 x139;
uint64_t x140;
fiat_curve25519_solinas_uint1 x141;
fiat_curve25519_solinas_mulx_u64(&x1, &x2, (arg1[3]), (arg2[3]));
fiat_curve25519_solinas_mulx_u64(&x3, &x4, (arg1[3]), (arg2[2]));
fiat_curve25519_solinas_mulx_u64(&x5, &x6, (arg1[3]), (arg2[1]));
fiat_curve25519_solinas_mulx_u64(&x7, &x8, (arg1[3]), (arg2[0]));
fiat_curve25519_solinas_mulx_u64(&x9, &x10, (arg1[2]), (arg2[3]));
fiat_curve25519_solinas_mulx_u64(&x11, &x12, (arg1[2]), (arg2[2]));
fiat_curve25519_solinas_mulx_u64(&x13, &x14, (arg1[2]), (arg2[1]));
fiat_curve25519_solinas_mulx_u64(&x15, &x16, (arg1[2]), (arg2[0]));
fiat_curve25519_solinas_mulx_u64(&x17, &x18, (arg1[1]), (arg2[3]));
fiat_curve25519_solinas_mulx_u64(&x19, &x20, (arg1[1]), (arg2[2]));
fiat_curve25519_solinas_mulx_u64(&x21, &x22, (arg1[1]), (arg2[1]));
fiat_curve25519_solinas_mulx_u64(&x23, &x24, (arg1[1]), (arg2[0]));
fiat_curve25519_solinas_mulx_u64(&x25, &x26, (arg1[0]), (arg2[3]));
fiat_curve25519_solinas_mulx_u64(&x27, &x28, (arg1[0]), (arg2[2]));
fiat_curve25519_solinas_mulx_u64(&x29, &x30, (arg1[0]), (arg2[1]));
fiat_curve25519_solinas_mulx_u64(&x31, &x32, (arg1[0]), (arg2[0]));
fiat_curve25519_solinas_addcarryx_u64(&x33, &x34, 0x0, x28, x7);
fiat_curve25519_solinas_addcarryx_u64(&x35, &x36, x34, x26, x5);
x37 = (x36 + x18);
fiat_curve25519_solinas_addcarryx_u64(&x38, &x39, 0x0, x33, x13);
fiat_curve25519_solinas_addcarryx_u64(&x40, &x41, x39, x35, x8);
fiat_curve25519_solinas_addcarryx_u64(&x42, &x43, x41, x37, 0x0);
x44 = (x43 + x10);
fiat_curve25519_solinas_addcarryx_u64(&x45, &x46, 0x0, x30, x15);
fiat_curve25519_solinas_addcarryx_u64(&x47, &x48, x46, x38, x16);
fiat_curve25519_solinas_addcarryx_u64(&x49, &x50, x48, x40, x11);
fiat_curve25519_solinas_addcarryx_u64(&x51, &x52, x50, x42, x3);
fiat_curve25519_solinas_addcarryx_u64(&x53, &x54, x52, x44, 0x0);
x55 = (x54 + x2);
fiat_curve25519_solinas_addcarryx_u64(&x56, &x57, 0x0, x45, x21);
fiat_curve25519_solinas_addcarryx_u64(&x58, &x59, x57, x47, x19);
fiat_curve25519_solinas_addcarryx_u64(&x60, &x61, x59, x49, x14);
fiat_curve25519_solinas_addcarryx_u64(&x62, &x63, x61, x51, x6);
fiat_curve25519_solinas_addcarryx_u64(&x64, &x65, x63, x53, 0x0);
fiat_curve25519_solinas_addcarryx_u64(&x66, &x67, x65, x55, 0x0);
fiat_curve25519_solinas_addcarryx_u64(&x68, &x69, 0x0, x32, x23);
fiat_curve25519_solinas_addcarryx_u64(&x70, &x71, x69, x56, x24);
fiat_curve25519_solinas_addcarryx_u64(&x72, &x73, x71, x58, x22);
fiat_curve25519_solinas_addcarryx_u64(&x74, &x75, x73, x60, x17);
fiat_curve25519_solinas_addcarryx_u64(&x76, &x77, x75, x62, x9);
fiat_curve25519_solinas_addcarryx_u64(&x78, &x79, x77, x64, x1);
fiat_curve25519_solinas_addcarryx_u64(&x80, &x81, x79, x66, 0x0);
fiat_curve25519_solinas_addcarryx_u64(&x82, &x83, 0x0, x68, x29);
fiat_curve25519_solinas_addcarryx_u64(&x84, &x85, x83, x70, x27);
fiat_curve25519_solinas_addcarryx_u64(&x86, &x87, x85, x72, x25);
fiat_curve25519_solinas_addcarryx_u64(&x88, &x89, x87, x74, x20);
fiat_curve25519_solinas_addcarryx_u64(&x90, &x91, x89, x76, x12);
fiat_curve25519_solinas_addcarryx_u64(&x92, &x93, x91, x78, x4);
fiat_curve25519_solinas_addcarryx_u64(&x94, &x95, x93, x80, 0x0);
fiat_curve25519_solinas_mulx_u64(&x96, &x97, UINT8_C(0x26), x92);
fiat_curve25519_solinas_mulx_u64(&x98, &x99, UINT8_C(0x26), x90);
fiat_curve25519_solinas_mulx_u64(&x100, &x101, UINT8_C(0x26), x88);
fiat_curve25519_solinas_addcarryx_u64(&x102, &x103, 0x0, x82, x98);
fiat_curve25519_solinas_addcarryx_u64(&x104, &x105, x103, x84, x96);
fiat_curve25519_solinas_mulx_u64(&x106, &x111, UINT8_C(0x26), x94);
fiat_curve25519_solinas_addcarryx_u64(&x108, &x109, x105, x86, x106);
/** fiat_curve25519_solinas_mulx_u64(&x110, &x111, UINT8_C(0x26), x94); */
x112 = (x109 + x111);
fiat_curve25519_solinas_addcarryx_u64(&x113, &x114, 0x0, x31, x100);
fiat_curve25519_solinas_addcarryx_u64(&x115, &x116, x114, x102, x101);
fiat_curve25519_solinas_addcarryx_u64(&x117, &x118, x116, x104, x99);
fiat_curve25519_solinas_addcarryx_u64(&x119, &x120, x118, x108, x97);
x121 = (x120 + x112);
fiat_curve25519_solinas_mulx_u64(&x122, &x123, UINT8_C(0x26), x121);
fiat_curve25519_solinas_addcarryx_u64(&x124, &x125, 0x0, x113, x122);
fiat_curve25519_solinas_addcarryx_u64(&x126, &x127, x125, x115, 0x0);
fiat_curve25519_solinas_addcarryx_u64(&x128, &x129, x127, x117, 0x0);
fiat_curve25519_solinas_addcarryx_u64(&x130, &x131, x129, x119, 0x0);
fiat_curve25519_solinas_cmovznz_u64(&x132, x131, UINT8_C(0x0), UINT8_C(0x26));
x134 = x132 + x124;
out1[0] = x134;
out1[1] = x126;
out1[2] = x128;
out1[3] = x130;
}
| 2.5 | 2 |
2024-11-18T19:02:29.880116+00:00 | 2019-03-11T02:26:24 | b37af0a317d96c8e6fbbe44b9379c7aef148c55d | {
"blob_id": "b37af0a317d96c8e6fbbe44b9379c7aef148c55d",
"branch_name": "refs/heads/master",
"committer_date": "2019-03-11T02:26:24",
"content_id": "4d0c94fe95ee126d4fcb0997a28d01cefe1fb53c",
"detected_licenses": [
"MIT"
],
"directory_id": "1675b4f54cd89850530c783ad2f28d39c94d913f",
"extension": "c",
"filename": "merge-sort.c",
"fork_events_count": 0,
"gha_created_at": "2019-02-26T03:23:02",
"gha_event_created_at": "2019-02-26T03:23:02",
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 172630368,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3815,
"license": "MIT",
"license_type": "permissive",
"path": "/examples/merge-sort.c",
"provenance": "stackv2-0058.json.gz:152461",
"repo_name": "Naetw/linux-list",
"revision_date": "2019-03-11T02:26:24",
"revision_id": "414808938fdc929487132821b4a094387c07b64b",
"snapshot_id": "4d2f98af29e4b8e390b9f83f49beac78bb41bf71",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Naetw/linux-list/414808938fdc929487132821b4a094387c07b64b/examples/merge-sort.c",
"visit_date": "2020-04-25T07:58:06.863813"
} | stackv2 | #include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include "list.h"
#include "common.h"
/**
* split_front_back() - Split list into half
* @head: pointer to the head of list to be split
* @front: pointer to the head of list which receives first half
* @back: pointer to the head of list which receives second half
*
* At first, use fast/slow strategy to get the middle node. Cut it by
* list_cut_position, and then use list_splice to transform the ownership.
*/
static void split_front_back(struct list_head *head,
struct list_head *front,
struct list_head *back)
{
struct list_head *fast, *slow;
slow = head->next;
fast = slow->next;
while (fast != head) {
fast = fast->next;
if (fast == head) {
slow = slow->next; // make slow ((n / 2) + 1)th element (1-based)
break;
}
slow = slow->next;
fast = fast->next;
}
list_cut_position(front, head, slow->prev);
list_splice(head, back);
}
/**
* merge() - Merge two lists.
* @head: pointer to the head of list which receives sorted lists
* @front: pointer to the head of list to be merged
* @back: pointer to the head of list to be merged
*/
static void merge(struct list_head *head,
struct list_head *front,
struct list_head *back)
{
struct listitem *left, *right;
INIT_LIST_HEAD(head);
left = list_first_entry(front, struct listitem, list);
right = list_first_entry(back, struct listitem, list);
while (!list_empty(front) && !list_empty(back)) {
if (cmpint(&left->i, &right->i) < 0) {
list_move_tail(&left->list, head);
left = list_first_entry(front, struct listitem, list);
} else {
list_move_tail(&right->list, head);
right = list_first_entry(back, struct listitem, list);
}
}
list_splice_tail(!list_empty(front) ? front : back, head);
}
/**
* list_mergesort() - Sort the list
* @head: the list to sort
*
* This function implements "merge sort", which has O(nlog(n))
* complexity.
*/
static void list_mergesort(struct list_head *head)
{
if (head == NULL || list_empty(head) || list_is_singular(head)) {
return;
}
struct list_head list_front, list_back;
INIT_LIST_HEAD(&list_front);
INIT_LIST_HEAD(&list_back);
split_front_back(head, &list_front, &list_back);
list_mergesort(&list_front);
list_mergesort(&list_back);
merge(head, &list_front, &list_back);
}
int main(int argc, const char *argv[])
{
if (argc < 2) {
printf("Usage: %s input_size\n", argv[0]);
return -1;
}
struct list_head testlist;
struct listitem *item, *is = NULL;
size_t i, array_size = strtol(argv[1], NULL, 10);
uint16_t *values = (uint16_t *) malloc(sizeof(uint16_t) * array_size);
random_shuffle_array(values, (uint16_t) array_size);
INIT_LIST_HEAD(&testlist);
assert(list_empty(&testlist));
for (i = 0; i < array_size; i++) {
item = (struct listitem *) malloc(sizeof(*item));
assert(item);
item->i = values[i];
list_add_tail(&item->list, &testlist);
}
assert(!list_empty(&testlist));
qsort(values, array_size, sizeof(values[0]), cmpint);
struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start);
list_mergesort(&testlist);
clock_gettime(CLOCK_MONOTONIC, &end);
printf("%lf\t", time_diff(&start, &end));
i = 0;
list_for_each_entry_safe (item, is, &testlist, list) {
assert(item->i == values[i]);
list_del(&item->list);
free(item);
i++;
}
assert(i == array_size);
assert(list_empty(&testlist));
free(values);
return 0;
}
| 3.125 | 3 |
2024-11-18T19:02:30.577923+00:00 | 2023-07-12T02:05:34 | a3057024102dfa89680545c50c0b0f6547ab9c2f | {
"blob_id": "a3057024102dfa89680545c50c0b0f6547ab9c2f",
"branch_name": "refs/heads/master",
"committer_date": "2023-07-12T02:05:34",
"content_id": "bc1a09e185eb9898569de728df8eac2f7b9c7958",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "e88e6c9249a335b4fcdf76dd4d5859a7264989da",
"extension": "c",
"filename": "hash.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 153190279,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 239,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/hash.c",
"provenance": "stackv2-0058.json.gz:152974",
"repo_name": "bjtj/osl-c",
"revision_date": "2023-07-12T02:05:34",
"revision_id": "84151f23b91056b1c2eed09fbf53ee2c5cb7c6f7",
"snapshot_id": "060d8031c745c4f055afb8cfdd5dc2544138efd4",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/bjtj/osl-c/84151f23b91056b1c2eed09fbf53ee2c5cb7c6f7/src/hash.c",
"visit_date": "2023-07-23T22:53:06.581448"
} | stackv2 | #include "hash.h"
// http://stackoverflow.com/a/7666577
unsigned long osl_hash(const char * str) {
unsigned long hash = 0;
int c;
while ((c = *str++)) {
hash = ((hash << 5) + hash) + c; /* hash * 33 + c */
}
return hash;
}
| 2.296875 | 2 |
2024-11-18T19:02:30.723573+00:00 | 2020-09-07T05:22:09 | 1636c7bafe2913e8a53db465b6de2cbdd95e2920 | {
"blob_id": "1636c7bafe2913e8a53db465b6de2cbdd95e2920",
"branch_name": "refs/heads/master",
"committer_date": "2020-09-07T05:22:09",
"content_id": "0cae27a25402c63e9ac6615ec9c69441c2a90273",
"detected_licenses": [
"MIT"
],
"directory_id": "7d2f08fc30d9bc2838252d2637e917618c9b69d9",
"extension": "c",
"filename": "lexer.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 253780436,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 28099,
"license": "MIT",
"license_type": "permissive",
"path": "/lexer.c",
"provenance": "stackv2-0058.json.gz:153232",
"repo_name": "aviral1117/Compiler-Construction",
"revision_date": "2020-09-07T05:22:09",
"revision_id": "768ac56ceea59b4092788ec7b2af7e827f958e86",
"snapshot_id": "8b3729728a769c7447b3d705173d03b2a036d840",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/aviral1117/Compiler-Construction/768ac56ceea59b4092788ec7b2af7e827f958e86/lexer.c",
"visit_date": "2022-12-26T06:08:57.093744"
} | stackv2 | /* # Group 01
Aviral Sethi : 2016B3A70532P
SANJEET MALHOTRA : 2016B4A70601P
PRIYANKA VERMA : 2016B3A70492P
ANIRUDH VIJAY : 2016B3A70525P
*/
#include "lexer.h"
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int lno=1;
char buff[buff_size];
FILE *source = NULL;
int traceback=0;
int buffer_control=-1;
int buildhash=0;
hashnode* hashtable[hash_table_size] = {NULL};
/* For Implementer's Help
- If size of tr and ntr is changed do appropriate changes in insertinHash function's 2 for loops at the end.
- buffer_size and hash table size are defined in lexerDef.h
*/
char* tr[] = {/*0*/"INTEGER","REAL","BOOLEAN","OF","ARRAY","START","END","DECLARE","MODULE","DRIVER",
/*10*/"PROGRAM","GET_VALUE","PRINT","USE","WITH","PARAMETERS","TRUE","FALSE","TAKES","INPUT",
/*20*/"RETURNS","AND","OR","FOR","IN","SWITCH","CASE","BREAK","DEFAULT","WHILE",
/*30*/"ID","NUM","RNUM","PLUS","MINUS","MUL","DIV","LT","LE","GE",
/*40*/"GT","NE","EQ","DEF","ENDDEF","DRIVERDEF","DRIVERENDDEF","COLON","RANGEOP","SEMICOL",
/*50*/"COMMA","ASSIGNOP","SQBO","SQBC","BO","BC","COMMENTMARK","EPS","DOLLAR" /*58*/ };
/**** Array of Non Terminals****/
char* ntr[] = {"program", "moduleDeclarations","otherModules","moduleDeclaration","module",
"driverModule", "moduleDef","input_plist","ret","output_list","dataType","type",
"input_plist1","output_list1","statements","statement","ioStmt", "var","whichId",
"simpleStmt","assignmentStmt", "whichStmt","lvalueIDStmt","lvalueARRStmt","index",
"moduleReuseStmt","optional","idList","idList1","expression","expression1",
"logicalOp","expterm","expterm1","relationalOp","expfactor","expfactor1","op1","term",
"term1","op2","factor","declareStmt","condionalStmt","caseStmt",
"caseStmt1","value","default","iterativeStmt","range1","range2","aoBexpr","U","U1","unary_op",
"boolConstt","var_id_num"};
FILE *getStream(FILE *fp){
// load data equivalent to min(buff_size-traceback,EOF-fp_offset);
for(int i=traceback;i<buff_size;i++)
buff[i]=0;
fread(buff+traceback,1,buff_size-traceback,fp);
return fp;
}
void load(){
// to check if loading of new data is required in buffer from source file
if(buffer_control==buff_size || buffer_control==-1){
source = getStream(source);
buffer_control=0;
}
}
// Only for demonstration
void removeComments(char *testcaseFile){
int line=1;
char * cleanFile = "cleanFile_afterCommentRemoval.txt";
FILE *fin = fopen(testcaseFile,"r");
if(fin==NULL){
return;
}
else{
FILE *fout = fopen(cleanFile,"w");
if(fout==NULL)
return;
char c=0;
int flag=0;
c = fgetc(fin);
if(c!=EOF)
printf("%d ",line);
while(c != EOF){
if(c!='*' && c!=EOF){
fputc(c,fout);
if(c=='\n'){
line++;
printf("\n");
printf("%d ",line);
}
else
printf("%c",c);
}
else{
c = fgetc(fin);
if(c=='*'){
// comment starts
while(1){
c = fgetc(fin);
if(c==EOF){
flag=1;
break;
}
else if(c=='\n'){
line++;
printf("\n");
printf("%d ",line);
fputc(c,fout);
}
else if(c=='*'){
c = fgetc(fin);
if(c=='*'){
break;
}
else if(c==EOF){
flag=1;
printf("Warning: Comment Not Closed Properly Found only 1 * at the end\n");
break;
}
}
}
}
else{
printf("*");
fflush(stdout); // For the first * encountered
fputc('*',fout);
if(c!=EOF){
printf("%c",c);
fflush(stdout);
fputc(c,fout);
}
else{
flag=1;
break;
}
}
}
if(flag)
break;
c = fgetc(fin);
}
fflush(fout);
fflush(fin);
}
}
int hashvalue(char *value){
int hashvalue=0;
int length = strlen(value);
for(int i=0;i<length;i++) {
hashvalue=hashvalue*31 + value[i];
hashvalue=hashvalue%hash_table_size;
}
return hashvalue;
}
void insertinHash(char *value,int id,int tag){
// tag is 0 for lexer dependent strings else 1 while inserting
int a = hashvalue(value);
if(hashtable[a]==NULL){
//printf("%d",sizeof(hashnode));
hashtable[a] = (hashnode*)malloc(sizeof(hashnode));
hashtable[a]->id = id;
hashtable[a]->tag= tag;
hashtable[a]->next = NULL;
strcpy(hashtable[a]->value,value);
}
else{
hashnode* temp = hashtable[a];
while(temp->next != NULL)
temp = temp->next;
temp->next = (hashnode*)malloc(sizeof(hashnode));
(temp->next)->id = id;
strcpy((temp->next)->value,value);
(temp->next)->tag=tag;
(temp->next)->next= NULL;
}
}
int search(char *value,int tag){
int k = hashvalue(value);
hashnode * temp = hashtable[k];
while(temp!=NULL){
int a = strcmp(value,temp->value);
if(a==0 && tag==temp->tag)
return temp->id;
temp = temp->next;
}
return -1;
}
void fillhashTable(){
if(buildhash){
buffer_control=-1;
lno=1;
return;
}
insertinHash("integer",0,0);
insertinHash("real",1,0);
insertinHash("boolean",2,0);
insertinHash("of",3,0);
insertinHash("array",4,0);
insertinHash("start",5,0);
insertinHash("end",6,0);
insertinHash("declare",7,0);
insertinHash("module",8,0);
insertinHash("driver",9,0);
insertinHash("program",10,0);
insertinHash("get_value",11,0);
insertinHash("print",12,0);
insertinHash("use",13,0);
insertinHash("with",14,0);
insertinHash("parameters",15,0);
insertinHash("true",16,0);
insertinHash("false",17,0);
insertinHash("takes",18,0);
insertinHash("input",19,0);
insertinHash("returns",20,0);
insertinHash("AND",21,0);
insertinHash("OR",22,0);
insertinHash("for",23,0);
insertinHash("in",24,0);
insertinHash("switch",25,0);
insertinHash("case",26,0);
insertinHash("break",27,0);
insertinHash("default",28,0);
insertinHash("while",29,0);
/*
insertinHash("+",30);
insertinHash("-",31);
insertinHash("*",32);
insertinHash("/",33);
insertinHash("<",34);
insertinHash("<=",35);
insertinHash(">=",36);
insertinHash(">",37);
insertinHash("==",38);
insertinHash("!=",39);
insertinHash("<<",40);
insertinHash(">>",41);
insertinHash("<<<",42);
insertinHash(">>>",43);
insertinHash(":",44);
insertinHash("..",45);
insertinHash(";",46);
insertinHash(",",47);
insertinHash(":=",48);
insertinHash("[",49);
insertinHash("]",50);
insertinHash("(",51);
insertinHash(")",52);
*/
//printf("Here");
buildhash=1;
for(int i=0;i<57;i++)
insertinHash(ntr[i],i,1);
for(int i=0;i<59;i++)
insertinHash(tr[i],i,1);
}
int lexerDependencies(char *input){
// source is a global file pointer
if(source!=NULL){
fclose(source);
}
source = fopen(input,"r");
if(source==NULL){
printf("Error: Missing Source File or Error in Opening File\n");
fflush(stdout);
return -1;
}
fillhashTable();
return 0;
}
void printError(char lex[],int code,int len,int lno){
/*
lex : Is the problem string.
Code: Error Code
len : Length of string
lno : Line of actual code
*/
switch(code){
case 0:
printf("line: %d Lexical Error: Length of Identifier exceeded ---> Expected: Identifier of length <= 20, Got: '%s' of length %d\n", lno,lex,len);
break;
case 1:
printf("line: %d Lexical Error: Invalid Floating Point Numeral '%s' ---> Missing valid character after '.'\n",lno,lex);
break;
case 2:
printf("line: %d Lexical Error: Invalid Floating Point Numeral '%s' ---> Missing valid character after '%c', Expected a number between 0-9\n",lno,lex,lex[len-1]);
break;
case 10:
if(strlen(lex)>=2 && lex[0]=='.' && lex[1]>='0' && lex[1]<='9'){
printf("line: %d Lexical Error: Invalid Operator Encountered ---> '.' before %c, Add a '0' before '.' if a real number was desired\n",lno,lex[1]);
}
else{
//printf("Here");
printf("line: %d Lexical Error: Invalid Operator Encountered ---> '%c'\n",lno,lex[0]);
}
break;
case 11:
printf("line: %d Lexical Error: Invalid Character Encountered ---> '%s', No matching Tokenization Rule\n",lno,lex);
break;
case 12:
printf("line: %d Lexical Error: Invalid Character Encountered after '!' ---> '%c', Expected: '='\n",lno,lex[0]);
break;
}
}
token* getNextToken(){
// Gateway between lexer and parser
// Returns a new token from source code or Dollar token if EOF
// always call load() when doing buffer_control++ and reading a new character in switch case;
token* tk = (token*)malloc(sizeof(token));
tk->tag=-1;
load();
int start=0;
char c=' ';
int len=0; // Length of lexeme starts from 0 and not 1
char lexeme[300] = {0};
while(1){
if(c==0)
break;
load();
//for(int i=0;i<50;i++)
//printf("%c",buff[i]);
c = buff[buffer_control];
if(c==0)
break;
switch(c){
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
case 'g':
case 'h':
case 'i':
case 'j':
case 'k':
case 'l':
case 'm':
case 'n':
case 'o':
case 'p':
case 'q':
case 'r':
case 's':
case 't':
case 'u':
case 'v':
case 'w':
case 'x':
case 'y':
case 'z':
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
case 'G':
case 'H':
case 'I':
case 'J':
case 'K':
case 'L':
case 'M':
case 'N':
case 'O':
case 'P':
case 'Q':
case 'R':
case 'S':
case 'T':
case 'U':
case 'V':
case 'W':
case 'X':
case 'Y':
case 'Z':
// The lower if is not currently of major use
if(!start){
len = 0;
start=1;
}
else{
printf("Error : Identifier not completed earlier");
}
while((c>='a' && c<='z') || (c<='Z' && c>='A') || c=='_' || (c>='0' && c<='9')){
buffer_control++;
load();
lexeme[len]=c;
c = buff[buffer_control];
len++;
}
lexeme[len] = '\0';
if(len>20)
printError(lexeme,0,len,lno);
else{
//buffer_control--;
tk->tag=0; // for valid lexeme
strcpy(tk->lexeme,lexeme);
int a = search(lexeme,0);
if(a==-1)
strcpy(tk->token_t,"ID");
else
strcpy(tk->token_t,tr[a]);
tk->lno = lno;
}
lexeme[len] = 0;
start=0;
break;
case '\n':
lno++;
buffer_control++;
break;
case ' ':
//printf("In here");
buffer_control++;
break;
case '\t':
buffer_control++;
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
while(c>='0' && c<='9'){
buffer_control++;
load();
lexeme[len]=c;
c = buff[buffer_control];
len++; // holds the actual length till now
}
if(c=='.'){
buffer_control++;
load();
lexeme[len]=c;
c = buff[buffer_control];
if((c>='0' && c<='9')){
len++;
while(c>='0' && c<='9'){
buffer_control++;
load();
lexeme[len]=c;
len++; // holds the actual length till now
c = buff[buffer_control];
}
if(c=='e' || c=='E'){
int validflag=0;
buffer_control++;
load();
lexeme[len] = c; // for e or E
len++;
c = buff[buffer_control];
if(c=='+' || c=='-' || (c>='0' && c<='9')){
validflag=1;
}
else{
lexeme[len]='\0';
printError(lexeme,2,len,lno);
}
int validflag2=len;
int plusflag=0;
while(c=='+' || c=='-' || (c>='0' && c<='9')){
if((c>='0' && c<='9')){
plusflag=1;
}
buffer_control++;
load();
lexeme[len]=c;
len++;
c = buff[buffer_control];
if(c=='+' || c=='-'){
break;
}
}
if(validflag2==len-1 && !plusflag){
validflag=0;
lexeme[len]='\0';
printError(lexeme,2,len,lno);
}
//buffer_control--;
if(validflag){
lexeme[len] = '\0';
tk->tag = 2;
strcpy(tk->lexeme,lexeme);
tk->lno = lno;
strcpy(tk->token_t,"RNUM");
}
}
else{
lexeme[len] = '\0';
tk->tag = 1; // For numeral
(tk->value).b = strtof(lexeme, (char **)NULL);
strcpy(tk->lexeme,lexeme);
tk->lno = lno;
strcpy(tk->token_t,"RNUM");
}
}
else if(c=='.'){
if(buffer_control==0){
traceback=1;
buff[0]='.';
fseek(source,-1*buff_size,SEEK_CUR);
buffer_control=-1;
load();
}
else
buffer_control--;
lexeme[len] = '\0';
tk->tag = 1; // For numeral
(tk->value).a = (int) strtol(lexeme, (char **)NULL, 10);
strcpy(tk->lexeme,lexeme);
tk->lno = lno;
strcpy(tk->token_t,"NUM");
traceback=0;
}
else{
len++;
lexeme[len] = '\0';
printError(lexeme,1,len,lno);
}
}
else{
//buffer_control--;
lexeme[len] = '\0';
tk->tag = 1; // For numeral
(tk->value).a = (int) strtol(lexeme, (char **)NULL, 10);
strcpy(tk->lexeme,lexeme);
tk->lno = lno;
strcpy(tk->token_t,"NUM");
}
lexeme[len] = 0;
break;
case '+':
tk->tag=0;
strcpy(tk->lexeme,"+");
strcpy(tk->token_t,"PLUS");
tk->lno = lno;
buffer_control++;
break;
case '-':
tk->tag=0;
strcpy(tk->lexeme,"-");
strcpy(tk->token_t,"MINUS");
tk->lno = lno;
buffer_control++;
break;
case '*':
buffer_control++;
load();
c = buff[buffer_control];
int cflag=0;
if(c=='*'){
while(1){
//printf("Debugging");
buffer_control++;
load();
c = buff[buffer_control];
if(c==EOF){
break;
}
if(c=='\n')
lno++;
else if(cflag && c=='*' || c==0){
buffer_control++;
break;
}
else if(c=='*')
cflag=1;
else if(cflag)
cflag=0;
}
}
else{
tk->tag=0;
strcpy(tk->lexeme,"*");
strcpy(tk->token_t,"MUL");
tk->lno = lno;
}
break;
case '/':
tk->tag=0;
strcpy(tk->lexeme,"/");
strcpy(tk->token_t,"DIV");
tk->lno = lno;
buffer_control++;
break;
case '<':
buffer_control++;
load();
c = buff[buffer_control];
if(c=='<'){
buffer_control++;
load();
c = buff[buffer_control];
if(c=='<'){
tk->tag=0;
strcpy(tk->lexeme,"<<<");
strcpy(tk->token_t,"DRIVERDEF");
tk->lno = lno;
buffer_control++;
}
else{
tk->tag=0;
strcpy(tk->lexeme,"<<");
strcpy(tk->token_t,"DEF");
tk->lno = lno;
}
}
else if(c=='='){
tk->tag=0;
strcpy(tk->lexeme,"<=");
strcpy(tk->token_t,"LE");
tk->lno = lno;
buffer_control++;
}
else{
tk->tag=0;
strcpy(tk->lexeme,"<");
strcpy(tk->token_t,"LT");
tk->lno = lno;
}
//buffer_control--;
break;
case '>':
buffer_control++;
load();
c = buff[buffer_control];
if(c=='>'){
buffer_control++;
load();
c = buff[buffer_control];
//printf("%c %d",c,c);
if(c=='>'){
tk->tag=0;
strcpy(tk->lexeme,">>>");
strcpy(tk->token_t,"DRIVERENDDEF");
tk->lno = lno;
buffer_control++;
}
else{
tk->tag=0;
strcpy(tk->lexeme,">>");
strcpy(tk->token_t,"ENDDEF");
tk->lno = lno;
}
}
else if(c=='='){
tk->tag=0;
strcpy(tk->lexeme,">=");
strcpy(tk->token_t,"GE");
tk->lno = lno;
buffer_control++;
}
else{
tk->tag=0;
strcpy(tk->lexeme,">");
strcpy(tk->token_t,"GT");
tk->lno = lno;
}
//buffer_control--;
break;
case '=':
buffer_control++;
load();
c = buff[buffer_control];
if(c=='='){
tk->tag=0;
strcpy(tk->lexeme,"==");
strcpy(tk->token_t,"EQ");
tk->lno = lno;
buffer_control++;
}
else{
char arr[2]={'=','\0'};
printError(arr,10,1,lno);
}
break;
case ':':
buffer_control++;
load();
c = buff[buffer_control];
if(c=='='){
tk->tag=0;
strcpy(tk->lexeme,":=");
strcpy(tk->token_t,"ASSIGNOP");
tk->lno = lno;
buffer_control++;
}
else{
tk->tag=0;
strcpy(tk->lexeme,":");
strcpy(tk->token_t,"COLON");
tk->lno = lno;
}
break;
case ',':
tk->tag=0;
strcpy(tk->lexeme,",");
strcpy(tk->token_t,"COMMA");
tk->lno = lno;
buffer_control++;
break;
case ';':
tk->tag=0;
strcpy(tk->lexeme,";");
strcpy(tk->token_t,"SEMICOL");
tk->lno = lno;
buffer_control++;
break;
case '[':
tk->tag=0;
strcpy(tk->lexeme,"[");
strcpy(tk->token_t,"SQBO");
tk->lno = lno;
buffer_control++;
break;
case ']':
tk->tag=0;
strcpy(tk->lexeme,"]");
strcpy(tk->token_t,"SQBC");
tk->lno = lno;
buffer_control++;
break;
case '(':
tk->tag=0;
strcpy(tk->lexeme,"(");
strcpy(tk->token_t,"BO");
tk->lno = lno;
buffer_control++;
break;
case ')':
tk->tag=0;
strcpy(tk->lexeme,")");
strcpy(tk->token_t,"BC");
tk->lno = lno;
buffer_control++;
break;
case '!':
buffer_control++;
load();
c = buff[buffer_control];
if(c=='='){
tk->tag=0;
strcpy(tk->lexeme,"!=");
strcpy(tk->token_t,"NE");
tk->lno = lno;
buffer_control++;
}
else{
char arr[2]={c,'\0'};
printError(arr,12,1,lno);
}
break;
case '.':
buffer_control++;
load();
c = buff[buffer_control];
if(c=='.'){
tk->tag=0;
strcpy(tk->lexeme,"..");
strcpy(tk->token_t,"RANGEOP");
tk->lno = lno;
buffer_control++;
}
else{
char arr[3]={'.',c,'\0'};
printError(arr,10,1,lno);
}
break;
default:
buffer_control++;
char arr[2]={c,'\0'};
printError(arr,11,1,lno);
}
if(tk->tag!=-1)
break;
}
if(tk->tag==-1){
tk->lno = lno;
strcpy(tk->lexeme,"$");
strcpy(tk->token_t,"DOLLAR");
}
return tk;
}
void printToken(token *tk){
// To print tokens as required in Driver Option 2.
printf("%-30d\t %-30s \t%-30s",tk->lno,tk->lexeme,tk->token_t);
}
| 2.296875 | 2 |
2024-11-18T19:02:31.381520+00:00 | 2023-03-29T17:49:13 | b33fa8d954e98ce86860a9a10121254b651f7886 | {
"blob_id": "b33fa8d954e98ce86860a9a10121254b651f7886",
"branch_name": "refs/heads/master",
"committer_date": "2023-03-29T17:49:13",
"content_id": "9c15a27e6b26aec574f51b7e84287dc14ce0b819",
"detected_licenses": [
"BSD-3-Clause",
"BSD-2-Clause"
],
"directory_id": "30150f1bee89d731d68afffbfc19616b101c5fee",
"extension": "c",
"filename": "redblack.c",
"fork_events_count": 70,
"gha_created_at": "2014-02-24T21:08:37",
"gha_event_created_at": "2023-01-14T10:46:22",
"gha_language": "C",
"gha_license_id": "BSD-2-Clause",
"github_id": 17150823,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 8531,
"license": "BSD-3-Clause,BSD-2-Clause",
"license_type": "permissive",
"path": "/core/redblack.c",
"provenance": "stackv2-0058.json.gz:153488",
"repo_name": "pruten/shoebill",
"revision_date": "2023-03-29T17:49:13",
"revision_id": "a9b2af09c078c16d9b286067d72e3e6deaad9660",
"snapshot_id": "639aff7269ab07807506f9ce44358125d26f5a45",
"src_encoding": "UTF-8",
"star_events_count": 300,
"url": "https://raw.githubusercontent.com/pruten/shoebill/a9b2af09c078c16d9b286067d72e3e6deaad9660/core/redblack.c",
"visit_date": "2023-04-09T02:36:33.830844"
} | stackv2 | /*
* Copyright (c) 2013, Peter Rutenbar <[email protected]>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#include "shoebill.h"
// Create a new red-black tree
rb_tree* rb_new(alloc_pool_t *parent_pool, uint32_t sz)
{
alloc_pool_t *pool = p_new_pool(parent_pool);
rb_tree *tree = (rb_tree*)p_alloc(pool, sizeof(rb_tree));
tree->root = NULL;
tree->pool = pool;
tree->sz = sz;
return tree;
}
// Insert a new key/value into the tree
// (and return the old value if *old_value is non-null.)
// Returns true if the key already existed.
uint8_t rb_insert(rb_tree *tree, rb_key_t key, void *value, void *old_value)
{
const uint32_t alloc_size = sizeof(rb_node) + tree->sz;
rb_node **root = &tree->root;
// Special edge case: insert the root node if tree's empty
if (*root == NULL) {
*root = p_alloc(tree->pool, alloc_size);
(*root)->key = key;
memcpy(&(*root)[1], value, tree->sz);
return 0;
}
// traverse
rb_node **cur = root, *parent = NULL;
while (*cur) {
parent = *cur;
if (key < (*cur)->key) // left
cur = &((*cur)->left);
else if (key > (*cur)->key) // right
cur = &((*cur)->right);
else { // the key already exists
if (old_value)
memcpy(old_value, &(*cur)[1], tree->sz);
memcpy(&(*cur)[1], value, tree->sz);
return 1; // 1 => the key already existed
}
}
// insert
*cur = p_alloc(tree->pool, alloc_size);
(*cur)->parent = parent;
(*cur)->key = key;
(*cur)->is_red = 1;
memcpy(&(*cur)[1], value, tree->sz);
// resolve
rb_node *red = *cur;
while (red) {
rb_node *parent = red->parent;
if (red->is_red == 0) // if this node isn't actually red, return
break;
else if (!parent) // if this is the root node, return
break;
else if (!parent->is_red) // if the parent is black, then we're done.
break;
// otherwise, the parent is red - the grandparent must exist, and must be black
assert((red->parent->parent) && (!red->parent->parent->is_red));
rb_node *gparent = parent->parent;
rb_node *uncle = (gparent->left==parent)?gparent->right:gparent->left;
// 8 cases:
// LLr LRr RLr RRr (uncle is red)
if (uncle && (uncle->is_red)) {
uncle->is_red = 0;
parent->is_red = 0;
gparent->is_red = 1;
red = gparent;
continue ;
}
// uncle is black
rb_node **gparent_ptr;
if (gparent->parent) { // great-grandparent exists
rb_node *ggparent = gparent->parent;
gparent_ptr = (ggparent->left==gparent)? (&ggparent->left) : (&ggparent->right);
} else { // grandparent is root
gparent_ptr = root;
}
uint8_t mycase = ((gparent->left==parent)?0:1);
mycase = (mycase << 1) | ((parent->left==red)?0:1);
switch (mycase) {
case 0: {// LLb
rb_node *Br = parent->right;
*gparent_ptr = parent;
parent->right = gparent;
gparent->left = Br;
parent->is_red = 0;
gparent->is_red = 1;
parent->parent = gparent->parent;
gparent->parent = parent;
if (Br) Br->parent = gparent;
red = gparent->right; // gparent became red, gparent->left is black, check gparent->right
break ;
}
case 1: {// LRb
rb_node *Cl = red->left;
rb_node *Cr = red->right;
*gparent_ptr = red;
red->left = parent;
red->right = gparent;
parent->right = Cl;
gparent->left = Cr;
red->is_red = 0;
gparent->is_red = 1;
red->parent = gparent->parent;
parent->parent = red;
gparent->parent = red;
if (Cl) Cl->parent = parent;
if (Cr) Cr->parent = gparent;
red = gparent->right;
break ;
}
case 2: { // RLb
rb_node *Cr = red->right, *Cl = red->left;
*gparent_ptr = red;
red->left = gparent;
red->right = parent;
gparent->right = Cl;
parent->left = Cr;
red->is_red = 0;
gparent->is_red = 1;
red->parent = gparent->parent;
gparent->parent = red;
parent->parent = red;
if (Cr) Cr->parent = parent;
if (Cl) Cl->parent = gparent;
red = gparent->left;
break;
}
case 3: { // RRb
rb_node *Bl = parent->left;
*gparent_ptr = parent;
parent->left = gparent;
gparent->right = Bl;
parent->is_red = 0;
gparent->is_red = 1;
parent->parent = gparent->parent;
gparent->parent = parent;
if (Bl) Bl->parent = gparent;
red = gparent->left;
break;
}
}
}
(*root)->is_red = 0; // make double-sure root is red
return 0;
}
// Find a value given a key
uint8_t rb_find (rb_tree *tree, rb_key_t key, void *value)
{
rb_node *cur = tree->root;
while (cur) {
if (key < cur->key)
cur = cur->left;
else if (key > cur->key)
cur = cur->right;
else {
if (value)
memcpy(value, &cur[1], tree->sz);
return 1;
}
}
return 0;
}
uint8_t _rb_index (rb_node *cur, uint32_t *index, rb_node **result)
{
if (!cur)
return 0;
else if (_rb_index(cur->left, index, result) == 1)
return 1;
else if (0 == *index) {
*result = cur;
return 1;
}
--*index;
return _rb_index(cur->right, index, result);
}
// Do an in-order traversal, and retrieve the (index)th sorted key/value
uint8_t rb_index (rb_tree *tree, uint32_t index, rb_key_t *key, void *value)
{
rb_node *cur = tree->root, *result;
if (_rb_index(cur, &index, &result)) {
if (key)
*key = result->key;
if (value)
memcpy(value, &result[1], tree->sz);
return 1;
}
return 0;
}
// Count the number of nodes in the tree
static uint32_t _rb_count (rb_node *node)
{
if (!node)
return 0;
return 1 + _rb_count(node->left) + _rb_count(node->right);
}
uint32_t rb_count (rb_tree *tree)
{
return _rb_count(tree->root);
}
// Free all the nodes (and the rb_tree ptr itself)
void rb_free (rb_tree *tree)
{
p_free_pool(tree->pool);
}
| 2.46875 | 2 |
2024-11-18T19:02:31.453920+00:00 | 2022-03-14T09:49:15 | 780c9f1e743ce7dd66b259d659541bb1709571cf | {
"blob_id": "780c9f1e743ce7dd66b259d659541bb1709571cf",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-31T09:50:00",
"content_id": "72908f4e61370a0f882548132fa757c574915f43",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "e1cddfd754d952134e72dfd03522c5ea4fb6008e",
"extension": "c",
"filename": "ip_neighbor_watch.c",
"fork_events_count": 630,
"gha_created_at": "2017-07-07T16:29:40",
"gha_event_created_at": "2023-06-21T05:39:17",
"gha_language": "C",
"gha_license_id": "Apache-2.0",
"github_id": 96556718,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 6899,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/vnet/ip-neighbor/ip_neighbor_watch.c",
"provenance": "stackv2-0058.json.gz:153616",
"repo_name": "FDio/vpp",
"revision_date": "2022-03-14T09:49:15",
"revision_id": "f234b0d4626d7e686422cc9dfd25958584f4931e",
"snapshot_id": "0ad30fa1bec2975ffa6b66b45c9f4f32163123b6",
"src_encoding": "UTF-8",
"star_events_count": 1048,
"url": "https://raw.githubusercontent.com/FDio/vpp/f234b0d4626d7e686422cc9dfd25958584f4931e/src/vnet/ip-neighbor/ip_neighbor_watch.c",
"visit_date": "2023-08-31T16:09:04.068646"
} | stackv2 | /*
* ip_neighboor_watch.c; IP neighbor watching
*
* Copyright (c) 2019 Cisco and/or its affiliates.
* 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 <vnet/ip-neighbor/ip_neighbor.h>
#include <vnet/ip-neighbor/ip_neighbor_watch.h>
#include <vnet/ip/ip_types_api.h>
#include <vnet/ethernet/ethernet_types_api.h>
#include <vnet/ip-neighbor/ip_neighbor.api_enum.h>
#include <vnet/ip-neighbor/ip_neighbor.api_types.h>
#include <vlibmemory/api.h>
/**
* Database of registered watchers
* The key for a watcher is {type, sw_if_index, addreess}
* interface=~0 / address=all-zeros imples any.
*/
typedef struct ip_neighbor_watch_db_t_
{
mhash_t ipnwdb_hash;
} ip_neighbor_watch_db_t;
static ip_neighbor_watch_db_t ipnw_db;
static uword
ip_neighbor_event_process (vlib_main_t * vm,
vlib_node_runtime_t * rt, vlib_frame_t * f)
{
ip_neighbor_event_t *ipne, *ipnes = NULL;
uword event_type = ~0;
while (1)
{
vlib_process_wait_for_event (vm);
ipnes = vlib_process_get_event_data (vm, &event_type);
switch (event_type)
{
default:
vec_foreach (ipne, ipnes) ip_neighbor_handle_event (ipne);
break;
case ~0:
/* timeout - */
break;
}
vec_reset_length (ipnes);
}
return 0;
}
/* *INDENT-OFF* */
VLIB_REGISTER_NODE (ip_neighbor_event_process_node) = {
.function = ip_neighbor_event_process,
.type = VLIB_NODE_TYPE_PROCESS,
.name = "ip-neighbor-event",
};
/* *INDENT-ON* */
static clib_error_t *
want_ip_neighbor_events_reaper (u32 client_index)
{
ip_neighbor_key_t *key, *empty_keys = NULL;
ip_neighbor_watcher_t *watchers;
uword *v;
i32 pos;
/* walk the entire IP neighbour DB and removes the client's registrations */
/* *INDENT-OFF* */
mhash_foreach(key, v, &ipnw_db.ipnwdb_hash,
({
watchers = (ip_neighbor_watcher_t*) *v;
vec_foreach_index_backwards (pos, watchers) {
if (watchers[pos].ipw_client == client_index)
vec_del1(watchers, pos);
}
if (vec_len(watchers) == 0)
vec_add1 (empty_keys, *key);
}));
/* *INDENT-OFF* */
vec_foreach (key, empty_keys)
mhash_unset (&ipnw_db.ipnwdb_hash, key, NULL);
vec_free (empty_keys);
return (NULL);
}
VL_MSG_API_REAPER_FUNCTION (want_ip_neighbor_events_reaper);
static int
ip_neighbor_watch_cmp (const ip_neighbor_watcher_t * w1,
const ip_neighbor_watcher_t * w2)
{
return (0 == clib_memcmp (w1, w2, sizeof(*w1)));
}
void
ip_neighbor_watch (const ip_address_t * ip,
u32 sw_if_index,
const ip_neighbor_watcher_t * watch)
{
ip_neighbor_key_t key = {
.ipnk_ip = *ip,
.ipnk_sw_if_index = (sw_if_index == 0 ? ~0 : sw_if_index),
};
ip_neighbor_watcher_t *ipws = NULL;
uword *p;
p = mhash_get (&ipnw_db.ipnwdb_hash, &key);
if (p)
{
ipws = (ip_neighbor_watcher_t*) p[0];
if (~0 != vec_search_with_function (ipws, watch,
ip_neighbor_watch_cmp))
/* duplicate */
return;
}
vec_add1 (ipws, *watch);
mhash_set (&ipnw_db.ipnwdb_hash, &key, (uword) ipws, NULL);
}
void
ip_neighbor_unwatch (const ip_address_t * ip,
u32 sw_if_index,
const ip_neighbor_watcher_t * watch)
{
ip_neighbor_key_t key = {
.ipnk_ip = *ip,
.ipnk_sw_if_index = (sw_if_index == 0 ? ~0 : sw_if_index),
};
ip_neighbor_watcher_t *ipws = NULL;
uword *p;
u32 pos;
p = mhash_get (&ipnw_db.ipnwdb_hash, &key);
if (!p)
return;
ipws = (ip_neighbor_watcher_t*) p[0];
pos = vec_search_with_function (ipws, watch, ip_neighbor_watch_cmp);
if (~0 == pos)
return;
vec_del1 (ipws, pos);
if (vec_len(ipws) == 0)
mhash_unset (&ipnw_db.ipnwdb_hash, &key, NULL);
}
static void
ip_neighbor_signal (ip_neighbor_watcher_t *watchers,
index_t ipni,
ip_neighbor_event_flags_t flags)
{
ip_neighbor_watcher_t *watcher;
vec_foreach (watcher, watchers) {
ip_neighbor_event_t *ipne;
ipne = vlib_process_signal_event_data (vlib_get_main(),
ip_neighbor_event_process_node.index,
0, 1, sizeof(*ipne));
ipne->ipne_watch = *watcher;
ipne->ipne_flags = flags;
ip_neighbor_clone(ip_neighbor_get(ipni), &ipne->ipne_nbr);
}
}
void
ip_neighbor_publish (index_t ipni,
ip_neighbor_event_flags_t flags)
{
const ip_neighbor_t *ipn;
ip_neighbor_key_t key;
uword *p;
ipn = ip_neighbor_get (ipni);
clib_memcpy (&key, ipn->ipn_key, sizeof (key));
/* Search the DB from longest to shortest key */
p = mhash_get (&ipnw_db.ipnwdb_hash, &key);
if (p) {
ip_neighbor_signal ((ip_neighbor_watcher_t*) p[0], ipni, flags);
}
ip_address_reset (&key.ipnk_ip);
p = mhash_get (&ipnw_db.ipnwdb_hash, &key);
if (p) {
ip_neighbor_signal ((ip_neighbor_watcher_t*) p[0], ipni, flags);
}
key.ipnk_sw_if_index = ~0;
p = mhash_get (&ipnw_db.ipnwdb_hash, &key);
if (p) {
ip_neighbor_signal ((ip_neighbor_watcher_t*) p[0], ipni, flags);
}
}
static clib_error_t *
ip_neighbor_watchers_show (vlib_main_t * vm,
unformat_input_t * input,
vlib_cli_command_t * cmd)
{
ip_neighbor_watcher_t *watchers, *watcher;
ip_neighbor_key_t *key;
uword *v;
/* *INDENT-OFF* */
mhash_foreach(key, v, &ipnw_db.ipnwdb_hash,
({
watchers = (ip_neighbor_watcher_t*) *v;
ASSERT(vec_len(watchers));
vlib_cli_output (vm, "Key: %U", format_ip_neighbor_key, key);
vec_foreach (watcher, watchers)
vlib_cli_output (vm, " %U", format_ip_neighbor_watcher, watcher);
}));
/* *INDENT-ON* */
return (NULL);
}
/* *INDENT-OFF* */
VLIB_CLI_COMMAND (show_ip_neighbor_watchers_cmd_node, static) = {
.path = "show ip neighbor-watcher",
.function = ip_neighbor_watchers_show,
.short_help = "show ip neighbors-watcher",
};
/* *INDENT-ON* */
static clib_error_t *
ip_neighbor_watch_init (vlib_main_t * vm)
{
mhash_init (&ipnw_db.ipnwdb_hash,
sizeof (ip_neighbor_watcher_t *), sizeof (ip_neighbor_key_t));
return (NULL);
}
/* *INDENT-OFF* */
VLIB_INIT_FUNCTION (ip_neighbor_watch_init) =
{
.runs_after = VLIB_INITS("ip_neighbor_init"),
};
/* *INDENT-ON* */
/*
* fd.io coding-style-patch-verification: ON
*
* Local Variables:
* eval: (c-set-style "gnu")
* End:
*/
| 2.109375 | 2 |
2024-11-18T19:02:32.321222+00:00 | 2022-06-10T21:27:41 | c0ec281094f1365efa7a521ab97c0dfabf8ad8eb | {
"blob_id": "c0ec281094f1365efa7a521ab97c0dfabf8ad8eb",
"branch_name": "refs/heads/master",
"committer_date": "2022-06-10T21:27:41",
"content_id": "ba1d260e79f79b6581f906b8c6f0fd6d202f2203",
"detected_licenses": [
"MIT"
],
"directory_id": "973314e78f73fbc3c9f85c7d5906965434fe0b1d",
"extension": "h",
"filename": "internal-grain128.h",
"fork_events_count": 12,
"gha_created_at": "2019-12-31T22:36:30",
"gha_event_created_at": "2020-09-25T06:52:16",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 231153188,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4317,
"license": "MIT",
"license_type": "permissive",
"path": "/src/individual/Grain-128AEAD/internal-grain128.h",
"provenance": "stackv2-0058.json.gz:153745",
"repo_name": "rweather/lightweight-crypto",
"revision_date": "2022-06-10T21:27:41",
"revision_id": "fa4ec9a021b9233263de77e7dd971de8c9761495",
"snapshot_id": "a94e376dab758643d990570d8c9042d58f73c31a",
"src_encoding": "UTF-8",
"star_events_count": 56,
"url": "https://raw.githubusercontent.com/rweather/lightweight-crypto/fa4ec9a021b9233263de77e7dd971de8c9761495/src/individual/Grain-128AEAD/internal-grain128.h",
"visit_date": "2022-06-24T16:51:14.896518"
} | stackv2 | /*
* Copyright (C) 2020 Southern Storm Software, Pty Ltd.
*
* 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 LW_INTERNAL_GRAIN128_H
#define LW_INTERNAL_GRAIN128_H
#include "internal-util.h"
/**
* \file internal-grain128.h
* \brief Internal implementation of the Grain-128 stream cipher.
*
* References: https://grain-128aead.github.io/
*/
#ifdef __cplusplus
extern "C" {
#endif
/**
* \brief Representation of the state of Grain-128.
*
* Note: The specification numbers bits starting with the most significant,
* so bit 0 is in the highest bit of the first word of each field below.
*/
typedef struct
{
uint32_t lfsr[4]; /**< 128-bit LFSR state for Grain-128 */
uint32_t nfsr[4]; /**< 128-bit NFSR state for Grain-128 */
uint64_t accum; /**< 64-bit accumulator for authentication */
uint64_t sr; /**< 64-bit shift register for authentication */
unsigned char ks[16]; /**< Keystream block for auth or encrypt mode */
unsigned posn; /**< Current position within the keystream */
} grain128_state_t;
/**
* \brief Performs 32 rounds of Grain-128 in parallel.
*
* \param state Grain-128 state.
* \param x 32 bits of input to be incorporated into the LFSR state, or zero.
* \param x2 Another 32 bits to be incorporated into the NFSR state, or zero.
*/
void grain128_core
(grain128_state_t *state, uint32_t x, uint32_t x2);
/**
* \brief Generates 32 bits of pre-output data.
*
* \param state Grain-128 state.
*
* \return The generated 32 bits of pre-output data.
*/
uint32_t grain128_preoutput(const grain128_state_t *state);
/**
* \brief Sets up the initial Grain-128 state with the key and nonce.
*
* \param state Grain-128 state to be initialized.
* \param key Points to the 128-bit key.
* \param nonce Points to the 96-bit nonce.
*/
void grain128_setup
(grain128_state_t *state, const unsigned char *key,
const unsigned char *nonce);
/**
* \brief Authenticates data with Grain-128.
*
* \param state Grain-128 state.
* \param data Points to the data to be authenticated.
* \param len Length of the data to be authenticated.
*/
void grain128_authenticate
(grain128_state_t *state, const unsigned char *data,
unsigned long long len);
/**
* \brief Encrypts and authenticates data with Grain-128.
*
* \param state Grain-128 state.
* \param c Points to the ciphertext output buffer.
* \param m Points to the plaintext input buffer.
* \param len Length of the data to be encrypted.
*/
void grain128_encrypt
(grain128_state_t *state, unsigned char *c, const unsigned char *m,
unsigned long long len);
/**
* \brief Decrypts and authenticates data with Grain-128.
*
* \param state Grain-128 state.
* \param m Points to the plaintext output buffer.
* \param c Points to the ciphertext input buffer.
* \param len Length of the data to be decrypted.
*/
void grain128_decrypt
(grain128_state_t *state, unsigned char *m, const unsigned char *c,
unsigned long long len);
/**
* \brief Computes the final authentiation tag.
*
* \param state Grain-128 state.
*
* The final authentication tag is written to the first 8 bytes of state->ks.
*/
void grain128_compute_tag(grain128_state_t *state);
#ifdef __cplusplus
}
#endif
#endif
| 2.109375 | 2 |
2024-11-18T19:02:33.265047+00:00 | 2020-05-16T23:51:41 | 6cd374e7bff2730a806da6fc3af680c3fb8655b3 | {
"blob_id": "6cd374e7bff2730a806da6fc3af680c3fb8655b3",
"branch_name": "refs/heads/master",
"committer_date": "2020-05-16T23:51:41",
"content_id": "5ef32ef1774180915c80153b104e4108ccf4141a",
"detected_licenses": [
"MIT"
],
"directory_id": "883d9f82d718c0abda20ccad868285abed62e883",
"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": 264303179,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1665,
"license": "MIT",
"license_type": "permissive",
"path": "/src/hello/main.c",
"provenance": "stackv2-0058.json.gz:154130",
"repo_name": "ppmag/wasm-demo",
"revision_date": "2020-05-16T23:51:41",
"revision_id": "ea6f9c34de03a4a557e8c5e4c2df4411450145fe",
"snapshot_id": "d570817473466a0f4ce1e8cfe1107cade8bccf39",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ppmag/wasm-demo/ea6f9c34de03a4a557e8c5e4c2df4411450145fe/src/hello/main.c",
"visit_date": "2022-08-22T20:56:17.091898"
} | stackv2 | #include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "sodium.h"
/*
* print_hex() is a wrapper around sodium_bin2hex() which allocates
* temporary memory then immediately prints the result followed by \n
*/
static void
print_hex(const void *bin, const size_t bin_len)
{
char *hex;
size_t hex_size;
if (bin_len >= SIZE_MAX / 2) {
abort();
}
hex_size = bin_len * 2 + 1;
if ((hex = malloc(hex_size)) == NULL) {
abort();
}
/* the library supplies a few utility functions like the one below */
if (sodium_bin2hex(hex, hex_size, bin, bin_len) == NULL) {
abort();
}
puts(hex);
free(hex);
}
int main(int argc, char ** argv) {
unsigned char key[crypto_generichash_KEYBYTES_MAX];
unsigned char hash[crypto_generichash_BYTES];
unsigned char message[1024];
size_t message_len;
size_t key_len;
printf("Hello Sodium...\n");
sodium_init();
printf("Using libsodium %s\n", sodium_version_string());
puts("Example: crypto_generichash()\n\n");
strcpy(key, "_key_");
key_len = strlen(key);
printf("Key: %s\n", key);
strcpy(message, "_sample_message_");
message_len = strlen(message);
printf("Message: %s\n", message);
printf("Hashing message with: %s\n\n", crypto_generichash_primitive());
if (crypto_generichash(hash, sizeof hash, message, message_len,
key, key_len) != 0) {
puts("Couldn't hash the message, probably due to the key length");
} else {
printf("Hash: ");
print_hex(hash, sizeof hash);
}
return 0;
}
| 3.203125 | 3 |
2024-11-18T19:02:33.465799+00:00 | 2015-12-01T22:00:31 | 17d7ea56ed4147163d74dbec2e7c336b9a3b6dbe | {
"blob_id": "17d7ea56ed4147163d74dbec2e7c336b9a3b6dbe",
"branch_name": "refs/heads/master",
"committer_date": "2015-12-01T22:00:31",
"content_id": "6eec185a7902fcb6607440ae801f758885f60e6b",
"detected_licenses": [
"BSD-3-Clause",
"BSD-2-Clause"
],
"directory_id": "b12514cb7c3924d389ba3589b13f5c392be073a8",
"extension": "c",
"filename": "usart.c",
"fork_events_count": 0,
"gha_created_at": "2015-11-15T05:57:19",
"gha_event_created_at": "2015-11-15T05:57:19",
"gha_language": null,
"gha_license_id": null,
"github_id": 46206476,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1543,
"license": "BSD-3-Clause,BSD-2-Clause",
"license_type": "permissive",
"path": "/07-Threads/usart.c",
"provenance": "stackv2-0058.json.gz:154514",
"repo_name": "hanago/mini-arm-os",
"revision_date": "2015-12-01T22:00:31",
"revision_id": "004b18da6751614c32cedcacb5b1473f371c6e63",
"snapshot_id": "e0c0420d7f5fb0c62d1f70b3d2e9984675891708",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/hanago/mini-arm-os/004b18da6751614c32cedcacb5b1473f371c6e63/07-Threads/usart.c",
"visit_date": "2021-01-15T12:41:30.363699"
} | stackv2 | #include "usart.h"
#include <stdint.h>
#include "reg.h"
#include "string.h"
/* USART TXE Flag
* This flag is cleared when data is written to USARTx_DR and
* set when that data is transferred to the TDR
*/
void usart_init(void)
{
*(RCC_APB2ENR) |= (uint32_t) (0x00000001 | 0x00000004);
*(RCC_APB1ENR) |= (uint32_t) (0x00020000);
/* USART2 Configuration, Rx->PA3, Tx->PA2 */
*(GPIOA_CRL) = 0x00004B00;
*(GPIOA_CRH) = 0x44444444;
*(GPIOA_ODR) = 0x00000000;
*(GPIOA_BSRR) = 0x00000000;
*(GPIOA_BRR) = 0x00000000;
*(USART2_CR1) = 0x0000000C;
*(USART2_CR2) = 0x00000000;
*(USART2_CR3) = 0x00000000;
*(USART2_CR1) |= 0x2000;
}
/* Print */
void print_c(const char c){
while (!(*(USART2_SR) & USART_FLAG_TXE));
*(USART2_DR) = (c & 0xFF);
}
void print_str(const char *str)
{
while (*str) {
while (!(*(USART2_SR) & USART_FLAG_TXE));
*(USART2_DR) = (*str & 0xFF);
str++;
}
}
void print_int(int num)
{
print_str(itoa(num));
}
void print_u32(uint32_t num){
print_str("0x");
int i;
char byte;
for(i = 7; i >= 0; i--){
byte = (char)((num >> (i*4)) & 0x000F);
if(byte >= 10)
print_c(byte + 'A');
else
print_c(byte + '0');
}
}
/* Get */
char get_c() {
char c;
while(!(*(USART2_SR) & USART_FLAG_RXNE));
c = (char)(*(USART2_DR) & 0xFF);
print_c(c);
return c;
}
int get_str(char *buffer, int size) {
int i = 0;
char c = '\0';
while(c != 0xD){
c = get_c();
if(c != 0xD && i < size)
*(buffer+i++) = c;
}
*(buffer+i) = '\0';
print_c('\n');
return 1;
} | 2.921875 | 3 |
2024-11-18T19:02:36.272299+00:00 | 2020-12-31T19:22:05 | b4e0c46dc3eb68fa5a3cb3e33498044512c1c6ba | {
"blob_id": "b4e0c46dc3eb68fa5a3cb3e33498044512c1c6ba",
"branch_name": "refs/heads/master",
"committer_date": "2020-12-31T19:33:08",
"content_id": "6155bb812f8433fb5d2493c165d914bf159cc3f6",
"detected_licenses": [
"MIT"
],
"directory_id": "72a36ff85a550582400977bb795e271a9ecf1c59",
"extension": "c",
"filename": "input_int_variable.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": "/1st semester/intro to programming/lab-1/Lab1/input_int_variable.c",
"provenance": "stackv2-0058.json.gz:155286",
"repo_name": "ravinamani15/Assignments",
"revision_date": "2020-12-31T19:22:05",
"revision_id": "39370eb5befe7f34c12e8f0032be0985ee0434c3",
"snapshot_id": "b9704991ebadd0acc2a4d3fafdaca18679da61b9",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ravinamani15/Assignments/39370eb5befe7f34c12e8f0032be0985ee0434c3/1st semester/intro to programming/lab-1/Lab1/input_int_variable.c",
"visit_date": "2023-02-06T06:36:23.660446"
} | stackv2 | /********************************
*Filename: input_int_variable.c
*Description: This program illustrates the declaration of several integer variables and elementary arithmetic operations.
*********************************/
#include<stdio.h>
int main()
{
int num1;
printf("\n *** Program to illustrate input of an int variable *** \n");
printf("\n Enter a number: ");
scanf("%d",&num1); // This is the statement which reads an integer from the user and stores it in num1.
/*The scanf statement is often used to get input from the user.
The expression "&num1" is the address of num1.
Try entering LARGE values for num1. What is the largest value that is printed correctly? */
printf("Your number is %d",num1);
return 0;
}
| 3.875 | 4 |
2024-11-18T19:02:36.373894+00:00 | 2021-08-06T18:11:25 | 587681df4a768d15e47d287f73779a3ed80918ad | {
"blob_id": "587681df4a768d15e47d287f73779a3ed80918ad",
"branch_name": "refs/heads/main",
"committer_date": "2021-08-06T18:11:25",
"content_id": "e60242fdcf41181fca5c331c41dc266c545fc51c",
"detected_licenses": [
"MIT"
],
"directory_id": "7bc2ba0d10be0d1b2e2119d65c4bdf93527d906d",
"extension": "c",
"filename": "zombie-process.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 393463185,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 521,
"license": "MIT",
"license_type": "permissive",
"path": "/zombie-process.c",
"provenance": "stackv2-0058.json.gz:155414",
"repo_name": "RobertNeat/zombie-process",
"revision_date": "2021-08-06T18:11:25",
"revision_id": "78444058316b1ef9cd96610c10e639099db425d5",
"snapshot_id": "32971c1b5d770662ff200edbe286a7ca717acbf2",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/RobertNeat/zombie-process/78444058316b1ef9cd96610c10e639099db425d5/zombie-process.c",
"visit_date": "2023-07-04T09:54:32.572823"
} | stackv2 | #include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
const int MSH_LENGTH=80;
int main(int argc, char** argv)
{
pid_t child_pid, my_pid, parent_pid;
child_pid = fork();
parent_pid = getppid();
my_pid = getpid();
if(child_pid!=0 && child_pid>0){//parent process is killed
printf("Parent process dies,\n child process become zombie process for 3 seconds.\n");
exit(0);
}
else if(child_pid==0){
sleep(3); //3 second zombie process
}
system("ps");
} | 2.453125 | 2 |
2024-11-18T19:02:36.602309+00:00 | 2021-03-28T11:45:14 | 0713f44121fe23fb367a256048942390544afe69 | {
"blob_id": "0713f44121fe23fb367a256048942390544afe69",
"branch_name": "refs/heads/master",
"committer_date": "2021-03-28T11:45:14",
"content_id": "4629f2a7c928b11b0b3fa248725486f933214478",
"detected_licenses": [
"MIT"
],
"directory_id": "7dafcd60ad72c54b7e434ecfd8dccb344becf97d",
"extension": "c",
"filename": "Source.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 348263523,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 56755,
"license": "MIT",
"license_type": "permissive",
"path": "/RolltheBall/Source.c",
"provenance": "stackv2-0058.json.gz:155672",
"repo_name": "Dparlar33/Allegro-C",
"revision_date": "2021-03-28T11:45:14",
"revision_id": "7f27d186256735ed2c7213698b70ffbdca5f5a56",
"snapshot_id": "8df606c985ccfc646c6b43034ef726b34654acc1",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Dparlar33/Allegro-C/7f27d186256735ed2c7213698b70ffbdca5f5a56/RolltheBall/Source.c",
"visit_date": "2023-03-27T12:23:51.819177"
} | stackv2 | #include <stdio.h>
#include <allegro5/allegro.h>
#include <allegro5/allegro_primitives.h>
#include <allegro5/allegro_image.h>
#include <allegro5/allegro_audio.h>
#include <allegro5/allegro_acodec.h>
#include <allegro5/allegro_font.h>
#include <allegro5/allegro_ttf.h>
void level_1();
void level_2();
void level_3();
void level_4();
void destroy_all();
ALLEGRO_DISPLAY* display;
ALLEGRO_BITMAP* MainMenu = NULL;
ALLEGRO_BITMAP* Background = NULL;
ALLEGRO_BITMAP* creditsBackground = NULL;
ALLEGRO_BITMAP* next1 = NULL;
ALLEGRO_BITMAP* next2 = NULL;
ALLEGRO_BITMAP* next3 = NULL;
ALLEGRO_BITMAP* gameover = NULL;
ALLEGRO_BITMAP* begd = NULL;
ALLEGRO_BITMAP* begu = NULL;
ALLEGRO_BITMAP* leftup = NULL;
ALLEGRO_BITMAP* downright = NULL;
ALLEGRO_BITMAP* leftdown = NULL;
ALLEGRO_BITMAP* leftandright = NULL;
ALLEGRO_BITMAP* rightup = NULL;
ALLEGRO_BITMAP* upanddown = NULL;
ALLEGRO_BITMAP* upright = NULL;
ALLEGRO_BITMAP* graydr = NULL;
ALLEGRO_BITMAP* redd = NULL;
ALLEGRO_BITMAP* redl = NULL;
ALLEGRO_BITMAP* box = NULL;
ALLEGRO_BITMAP* graylr = NULL;
ALLEGRO_BITMAP* grayud = NULL;
ALLEGRO_SAMPLE* boxsound = NULL;
ALLEGRO_SAMPLE* playquit = NULL;
ALLEGRO_SAMPLE* clap = NULL;
ALLEGRO_SAMPLE_INSTANCE* clap1 = NULL;
ALLEGRO_SAMPLE_INSTANCE* boxsound1 = NULL;
ALLEGRO_SAMPLE_INSTANCE* playquit1 = NULL;
ALLEGRO_SAMPLE* theme = NULL;
ALLEGRO_FONT* font = NULL;
bool ongamingsc = 0, nextlevel = 0;
int levelsave = 1;
int main() {
ALLEGRO_EVENT_QUEUE* queue;
ALLEGRO_EVENT ev;
al_init_primitives_addon();
al_init_acodec_addon();
al_install_audio();
al_init_image_addon();
al_init_font_addon();
al_init_ttf_addon();
bool checkquit = 1, credits = 0;
float x, y;
al_init();
al_install_mouse();
al_reserve_samples(1);
if (!al_init()) {
return -1;
}
display = al_create_display(640, 480);
if (!display) {
return -1;
}
queue = al_create_event_queue();
al_register_event_source(queue, al_get_display_event_source(display));
al_register_event_source(queue, al_get_mouse_event_source());
MainMenu = al_load_bitmap("mainmenu.bmp");
creditsBackground = al_load_bitmap("credits.bmp");
playquit = al_load_sample("playquit.ogg");
playquit1 = al_create_sample_instance(playquit);
al_attach_sample_instance_to_mixer(playquit1, al_get_default_mixer());
theme = al_load_sample("theme.ogg");
al_wait_for_event(queue, &ev);
al_draw_bitmap(MainMenu, 0, 0, 0);
while (checkquit) {
al_wait_for_event(queue, &ev);
al_play_sample(theme, 1, 0, 1, ALLEGRO_PLAYMODE_LOOP, 0);
al_draw_bitmap(MainMenu, 0, 0, 0);
if (ev.type == ALLEGRO_EVENT_MOUSE_AXES) {
x = ev.mouse.x;
y = ev.mouse.y;
}
if (ev.type == ALLEGRO_EVENT_MOUSE_BUTTON_DOWN) {
if (ev.mouse.x > 277 && ev.mouse.y > 200 && ev.mouse.x < 361 && ev.mouse.y < 250) {
al_play_sample_instance(playquit1);
ongamingsc = 1;
}
if (ev.mouse.x > 35 && ev.mouse.y > 398 && ev.mouse.x < 156 && ev.mouse.y < 448) {
al_play_sample_instance(playquit1);
credits = 1;
}
if (ev.mouse.x > 278 && ev.mouse.y > 294 && ev.mouse.x < 362 && ev.mouse.y < 344) {
al_play_sample_instance(playquit1);
checkquit = 0;
}
}
while (credits) {
al_wait_for_event(queue, &ev);
al_draw_bitmap(creditsBackground, 0, 0, 0);
if (ev.type == ALLEGRO_EVENT_MOUSE_BUTTON_DOWN) {
if (ev.mouse.x > 427 && ev.mouse.y > 383 && ev.mouse.x < 583 && ev.mouse.y < 437) {
al_play_sample_instance(playquit1);
credits = 0;
}
}
al_flip_display();
}
while (ongamingsc) {
if (levelsave == 1) {
level_1();
}
if (levelsave == 2) {
level_2();
}
if (levelsave == 3) {
level_3();
}
if (levelsave == 4) {
level_4();
}
al_flip_display();
}
al_flip_display();
}
if (!checkquit) {
destroy_all();
}
return 42;
}
void level_1() {
ALLEGRO_EVENT_QUEUE* queue = NULL;
ALLEGRO_EVENT ev;
int board[16][2] = { {80,0} , {200,0}, {320,0}, {440,0},
{80,120}, {200,120}, {320,120}, {440,120},
{80,240}, {200,240}, {320,240}, {440,240},
{80,360}, {0}, {320,360}, {440,360} };
int space[1][2] = { 200,360 };
int final[4][2] = { {80,120}, {80,240}, {80,360}, {200,360}, };
int i, x = 0, y = 0, j, onlevel = 1, moves = 0;
bool boxistaken = 0, drop = 0, fixed = 0;
float xpos = 140;
float ypos = 60;
queue = al_create_event_queue();
playquit = al_load_sample("playquit.ogg");
playquit1 = al_create_sample_instance(playquit);
al_attach_sample_instance_to_mixer(playquit1, al_get_default_mixer());
boxsound = al_load_sample("boxsound.ogg");
boxsound1 = al_create_sample_instance(boxsound);
al_attach_sample_instance_to_mixer(boxsound1, al_get_default_mixer());
clap = al_load_sample("clap.ogg");
clap1 = al_create_sample_instance(clap);
al_attach_sample_instance_to_mixer(clap1, al_get_default_mixer());
theme = al_load_sample("theme.ogg");
Background = al_load_bitmap("gamingsc.bmp");
begd = al_load_bitmap("begd.bmp");
box = al_load_bitmap("board.bmp");
upanddown = al_load_bitmap("uddu.bmp");
upright = al_load_bitmap("upright.bmp");
leftandright = al_load_bitmap("lrrl.bmp");
redl = al_load_bitmap("redl.bmp");
graylr = al_load_bitmap("graylr.bmp");
font = al_load_font("arial.ttf", 28, 0);
next1 = al_load_bitmap("next1.bmp");
next2 = al_load_bitmap("next2.bmp");
next3 = al_load_bitmap("next3.bmp");
queue = al_create_event_queue();
al_register_event_source(queue, al_get_display_event_source(display));
al_register_event_source(queue, al_get_mouse_event_source());
while (onlevel && ongamingsc) {
al_draw_bitmap(Background, 0, 0, 0);
al_wait_for_event(queue, &ev);
al_draw_text(font, al_map_rgb(243, 197, 147), 28, 87, 0, "1");
al_draw_textf(font, al_map_rgb(243, 197, 147), 585, 83, 0, "%i", moves);
al_draw_filled_rectangle(space[0][0], space[0][1], space[0][0] + 120, board[0][1] + 120, al_map_rgb(17, 17, 17));
for (i = 1; i <= 12; i++) {
if (i == 4 || i == 8 || i == 9) {
continue;
}
al_draw_bitmap(box, board[i][0], board[i][1], 0);
}
al_draw_bitmap(begd, 80, 0, 0);
al_draw_bitmap(upanddown, board[4][0], board[4][1], 0);
al_draw_bitmap(upanddown, board[8][0], board[8][1], 0);
al_draw_bitmap(leftandright, board[9][0], board[9][1], 0);
al_draw_bitmap(upright, board[12][0], board[12][1], 0);
al_draw_bitmap(graylr, board[14][0], board[14][1], 0);
al_draw_bitmap(redl, board[15][0], board[15][1], 0);
al_draw_filled_circle(xpos, ypos, 18, al_map_rgb(157, 60, 1));
if (ev.type == ALLEGRO_EVENT_MOUSE_AXES) {
x = ev.mouse.x;
y = ev.mouse.y;
}
if (!((ev.mouse.x >= board[0][0] && ev.mouse.y >= board[0][1] && ev.mouse.x <= board[0][0] + 120 && ev.mouse.y <= board[0][1] + 120)
|| (ev.mouse.x >= board[15][0] && ev.mouse.y >= board[15][1] && ev.mouse.x <= board[15][0] + 120 && ev.mouse.y <= board[15][1] + 120)
|| (ev.mouse.x >= board[14][0] && ev.mouse.y >= board[14][1] && ev.mouse.x <= board[14][0] + 120 && ev.mouse.y <= board[14][1] + 120))) {
fixed = 1;
}
else { fixed = 0; }
if (ev.type == ALLEGRO_EVENT_MOUSE_BUTTON_DOWN) {
for (i = 0; i <= 15; i++) {
if (ev.mouse.x <= board[i][0] + 120 && ev.mouse.y <= board[i][1] + 120 && ev.mouse.x >= board[i][0] && ev.mouse.y >= board[i][1] && fixed) {
al_draw_filled_rectangle(board[i][0], board[i][1], board[i][0] + 120, board[i][1] + 120, al_map_rgb(17, 17, 17));
al_draw_filled_rectangle(x - 60, y - 60, x + 60, y + 60, al_map_rgb(184, 115, 51));
al_play_sample_instance(boxsound1);
boxistaken = 1;
j = i;
}
}
}
if (boxistaken) {
al_draw_filled_rectangle(board[j][0], board[j][1], board[j][0] + 120, board[j][1] + 120, al_map_rgb(17, 17, 17));
if (j == 9 || j == 14) {
al_draw_bitmap(leftandright, x - 60, y - 60, 0);
}
if (j == 4 || j == 8) {
al_draw_bitmap(upanddown, x - 60, y - 60, 0);
}
if (j == 12) {
al_draw_bitmap(upright, x - 60, y - 60, 0);
}
if (j == 1 || j == 2 || j == 3 || j == 5 || j == 6 || j == 7 || j == 10 || j == 11) {
al_draw_bitmap(box, x - 60, y - 60, 0);
}
if (ev.type == ALLEGRO_EVENT_MOUSE_BUTTON_UP) {
if (ev.mouse.x >= space[0][0] && ev.mouse.x <= space[0][0] + 120
&& ev.mouse.y >= space[0][1] && ev.mouse.y <= space[0][1] + 120
&& fixed)
{
drop = 1;
moves++;
}
if (ev.mouse.x >= board[j][0] + 120 && ev.mouse.x <= board[j][0] + 240 && ev.mouse.y >= board[j][1] && ev.mouse.y <= board[j][1] + 120 && drop) {
board[j][0] += 120;
space[0][0] -= 120;
}
if (ev.mouse.x <= board[j][0] && ev.mouse.x >= board[j][0] - 120 && ev.mouse.y >= board[j][1] && ev.mouse.y <= board[j][1] + 120 && drop) {
board[j][0] -= 120;
space[0][0] += 120;
}
if (ev.mouse.y >= board[j][1] + 120 && ev.mouse.y <= board[j][1] + 240 && ev.mouse.x >= board[j][0] && ev.mouse.x <= board[j][0] + 120 && drop) {
board[j][1] += 120;
space[0][1] -= 120;
}
if (ev.mouse.y <= board[j][1] && ev.mouse.y >= board[j][1] - 120 && ev.mouse.x >= board[j][0] && ev.mouse.x <= board[j][0] + 120 && drop) {
board[j][1] -= 120;
space[0][1] += 120;
}
boxistaken = 0;
drop = 0;
}
}
al_flip_display();
if (board[4][0] == final[0][0] && board[4][1] == final[0][1]
&& ((board[8][0] == final[1][0] && board[8][1] == final[1][1]) || (board[8][0] == final[2][0] && board[8][1] == final[2][1]))
&& ((board[12][0] == final[2][0] && board[12][1] == final[2][1]) || (board[8][0] == final[1][0] && board[8][1] == final[1][1]))
&& board[9][0] == final[3][0] && board[9][1] == final[3][1]) {
while (ypos <= 360) {
al_draw_bitmap(Background, 0, 0, 0);
for (j = 1; j <= 12; j++) {
if (j == 4 || j == 8) {
al_draw_bitmap(upanddown, board[j][0], board[j][1], 0);
}
if (j == 12) {
al_draw_bitmap(upright, board[j][0], board[j][1], 0);
}
if (j == 1 || j == 2 || j == 3 || j == 5 || j == 6 || j == 7 || j == 10 || j == 11) {
al_draw_bitmap(box, board[j][0], board[j][1], 0);
}
}
al_draw_bitmap(leftandright, 200, 360, 0);
al_draw_bitmap(begd, 80, 0, 0);
al_draw_bitmap(graylr, board[14][0], board[14][1], 0);
al_draw_bitmap(redl, board[15][0], board[15][1], 0);
al_draw_text(font, al_map_rgb(243, 197, 147), 28, 87, 0, "1");
al_draw_textf(font, al_map_rgb(243, 197, 147), 585, 83, 0, "%i", moves);
al_draw_filled_circle(xpos, ypos, 18, al_map_rgb(157, 60, 1));
ypos += 0.15;
al_flip_display();
}
while (xpos <= 142 || ypos <= 390) {
al_draw_bitmap(Background, 0, 0, 0);
for (j = 1; j <= 12; j++) {
if (j == 4 || j == 8) {
al_draw_bitmap(upanddown, board[j][0], board[j][1], 0);
}
if (j == 12) {
al_draw_bitmap(upright, board[j][0], board[j][1], 0);
}
if (j == 1 || j == 2 || j == 3 || j == 5 || j == 6 || j == 7 || j == 10 || j == 11) {
al_draw_bitmap(box, board[j][0], board[j][1], 0);
}
}
al_draw_bitmap(begd, 80, 0, 0);
al_draw_bitmap(leftandright, 200, 360, 0);
al_draw_bitmap(graylr, board[14][0], board[14][1], 0);
al_draw_bitmap(redl, board[15][0], board[15][1], 0);
al_draw_text(font, al_map_rgb(243, 197, 147), 28, 87, 0, "1");
al_draw_textf(font, al_map_rgb(243, 197, 147), 585, 83, 0, "%i", moves);
al_draw_filled_circle(xpos, ypos, 18, al_map_rgb(157, 60, 1));
if (ypos <= 390)
ypos += 0.15;
if (xpos <= 142)
xpos += 0.15;
al_flip_display();
}
while (xpos <= 214 || ypos <= 420) {
al_draw_bitmap(Background, 0, 0, 0);
for (j = 1; j <= 12; j++) {
if (j == 4 || j == 8) {
al_draw_bitmap(upanddown, board[j][0], board[j][1], 0);
}
if (j == 12) {
al_draw_bitmap(upright, board[j][0], board[j][1], 0);
}
if (j == 1 || j == 2 || j == 3 || j == 5 || j == 6 || j == 7 || j == 10 || j == 11) {
al_draw_bitmap(box, board[j][0], board[j][1], 0);
}
}
al_draw_bitmap(begd, 80, 0, 0);
al_draw_bitmap(leftandright, 200, 360, 0);
al_draw_bitmap(graylr, board[14][0], board[14][1], 0);
al_draw_bitmap(redl, board[15][0], board[15][1], 0);
al_draw_text(font, al_map_rgb(243, 197, 147), 28, 87, 0, "1");
al_draw_textf(font, al_map_rgb(243, 197, 147), 585, 83, 0, "%i", moves);
al_draw_filled_circle(xpos, ypos, 18, al_map_rgb(157, 60, 1));
if (ypos <= 420)
ypos += 0.15;
if (xpos <= 214)
xpos += 0.15;
al_flip_display();
}
while (xpos <= 513) {
al_draw_bitmap(Background, 0, 0, 0);
for (j = 1; j <= 12; j++) {
if (j == 4 || j == 8) {
al_draw_bitmap(upanddown, board[j][0], board[j][1], 0);
}
if (j == 12) {
al_draw_bitmap(upright, board[j][0], board[j][1], 0);
}
if (j == 1 || j == 2 || j == 3 || j == 5 || j == 6 || j == 7 || j == 10 || j == 11) {
al_draw_bitmap(box, board[j][0], board[j][1], 0);
}
}
al_draw_bitmap(begd, 80, 0, 0);
al_draw_bitmap(leftandright, 200, 360, 0);
al_draw_bitmap(graylr, board[14][0], board[14][1], 0);
al_draw_bitmap(redl, board[15][0], board[15][1], 0);
al_draw_text(font, al_map_rgb(243, 197, 147), 28, 87, 0, "1");
al_draw_textf(font, al_map_rgb(243, 197, 147), 585, 83, 0, "%i", moves);
al_draw_filled_circle(xpos, ypos, 18, al_map_rgb(157, 60, 1));
xpos += 0.15;
nextlevel = 1;
al_flip_display();
}
while (nextlevel) {
al_wait_for_event(queue, &ev);
al_play_sample_instance(clap1);
if (ev.type == ALLEGRO_EVENT_MOUSE_BUTTON_DOWN) {
if (ev.mouse.x < 475 && ev.mouse.x > 176 && ev.mouse.y < 440 && ev.mouse.y > 370) {
al_play_sample_instance(playquit1);
nextlevel = 0;
levelsave = 2;
onlevel = 0;
}
}
if (moves == 1) {
al_draw_bitmap(next3, 0, 0, 0);
}
if (moves < 4 && moves>1) {
al_draw_bitmap(next2, 0, 0, 0);
}
if (moves > 4) {
al_draw_bitmap(next1, 0, 0, 0);
}
al_flip_display();
}
}
if (ev.type == ALLEGRO_EVENT_MOUSE_BUTTON_DOWN) {
if (ev.mouse.x < 621 && ev.mouse.x > 576 && ev.mouse.y < 456 && ev.mouse.y > 413) {
al_clear_to_color(al_map_rgb(0, 0, 0));
al_play_sample_instance(playquit1);
al_draw_bitmap(MainMenu, 0, 0, 0);
onlevel = 0;
ongamingsc = 0;
}
}
}
}
void level_2() {
ALLEGRO_EVENT_QUEUE* queue = NULL;
ALLEGRO_EVENT ev;
int board[16][2] = { {80,0}, {200,0}, {0},{440,0},
{0}, {0}, {320,120}, {440,120},
{80,240}, {200,240}, {320,240}, {440,240},
{80,360}, {200,360}, {320,360}, {0} };
int space[4][2] = { {320,0}, {80,120}, {200,120}, {440,360} };
int final[7][2] = { {440,120}, {80,240}, {200,240}, {440,240}, {200,360}, {320,360}, {440,360} };
int i, x = 0, y = 0, j, onlevel = 1, moves = 0;
bool boxistaken = 0, drop = 0, fixed = 0;
nextlevel = 1;
float xpos = 140;
float ypos = 420;
queue = al_create_event_queue();
playquit = al_load_sample("playquit.ogg");
playquit1 = al_create_sample_instance(playquit);
al_attach_sample_instance_to_mixer(playquit1, al_get_default_mixer());
boxsound = al_load_sample("boxsound.ogg");
boxsound1 = al_create_sample_instance(boxsound);
al_attach_sample_instance_to_mixer(boxsound1, al_get_default_mixer());
clap = al_load_sample("clap.ogg");
clap1 = al_create_sample_instance(clap);
al_attach_sample_instance_to_mixer(clap1, al_get_default_mixer());
box = al_load_bitmap("board.bmp");
begu = al_load_bitmap("begu.bmp");
redd = al_load_bitmap("redd.bmp");
downright = al_load_bitmap("downright.bmp");
leftdown = al_load_bitmap("leftdown.bmp");
upright = al_load_bitmap("upright.bmp");
upanddown = al_load_bitmap("uddu.bmp");
leftandright = al_load_bitmap("lrrl.bmp");
leftup = al_load_bitmap("leftup.bmp");
font = al_load_font("arial.ttf", 28, 0);
Background = al_load_bitmap("gamingsc.bmp");
next1 = al_load_bitmap("next1.bmp");
next2 = al_load_bitmap("next2.bmp");
next3 = al_load_bitmap("next3.bmp");
al_register_event_source(queue, al_get_display_event_source(display));
al_register_event_source(queue, al_get_mouse_event_source());
al_wait_for_event(queue, &ev);
while (onlevel && ongamingsc) {
al_wait_for_event(queue, &ev);
al_draw_bitmap(Background, 0, 0, 0);
al_draw_text(font, al_map_rgb(243, 197, 147), 28, 87, 0, "2");
al_draw_textf(font, al_map_rgb(243, 197, 147), 585, 83, 0, "%i", moves);
//spaces
for (i = 0; i <= 3; i++) {
al_draw_filled_rectangle(space[i][0], space[i][1], space[i][0] + 120, space[i][1] + 120, al_map_rgb(17, 17, 17));
}
//boxes
for (i = 0; i <= 1; i++) {
al_draw_bitmap(box, board[i][0], board[i][1], 0);
}
for (i = 10; i <= 11; i++) {
al_draw_bitmap(upanddown, board[i][0], board[i][1], 0);
}
al_draw_bitmap(leftdown, board[9][0], board[9][1], 0);
al_draw_bitmap(downright, board[8][0], board[8][1], 0);
al_draw_bitmap(downright, board[6][0], board[6][1], 0);
al_draw_bitmap(leftandright, board[7][0], board[7][1], 0);
al_draw_bitmap(upright, board[13][0], board[13][1], 0);
al_draw_bitmap(leftup, board[14][0], board[14][1], 0);
al_draw_bitmap(redd, board[3][0], board[3][1], 0);
al_draw_bitmap(begu, board[12][0], board[12][1], 0);
al_draw_filled_circle(xpos, ypos, 18, al_map_rgb(157, 60, 1));
if (ev.type == ALLEGRO_EVENT_MOUSE_AXES) {
x = ev.mouse.x;
y = ev.mouse.y;
}
if (!((ev.mouse.x >= board[3][0] && ev.mouse.y >= board[3][1] && ev.mouse.x <= board[3][0] + 120 && ev.mouse.y <= board[3][1] + 120)
|| (ev.mouse.x >= board[12][0] && ev.mouse.y >= board[12][1] && ev.mouse.x <= board[12][0] + 120 && ev.mouse.y <= board[12][1] + 120))) {
fixed = 1;
}
else { fixed = 0; }
if (ev.type == ALLEGRO_EVENT_MOUSE_BUTTON_DOWN) {
for (i = 0; i <= 15; i++) {
if (ev.mouse.x <= board[i][0] + 120 && ev.mouse.y <= board[i][1] + 120 && ev.mouse.x >= board[i][0] && ev.mouse.y >= board[i][1] && fixed) {
al_draw_filled_rectangle(board[i][0], board[i][1], board[i][0] + 120, board[i][1] + 120, al_map_rgb(17, 17, 17));
al_draw_filled_rectangle(x - 60, y - 60, x + 60, y + 60, al_map_rgb(184, 115, 51));
al_play_sample_instance(boxsound1);
boxistaken = 1;
j = i;
}
}
}
if (boxistaken) {
al_draw_filled_rectangle(board[j][0], board[j][1], board[j][0] + 120, board[j][1] + 120, al_map_rgb(17, 17, 17));
if (j == 11 || j == 10) {
al_draw_bitmap(upanddown, x - 60, y - 60, 0);
}
if (j == 0 || j == 1) {
al_draw_bitmap(box, x - 60, y - 60, 0);
}
if (j == 6 || j == 8) {
al_draw_bitmap(downright, x - 60, y - 60, 0);
}
if (j == 9) {
al_draw_bitmap(leftdown, x - 60, y - 60, 0);
}
if (j == 7) {
al_draw_bitmap(leftandright, x - 60, y - 60, 0);
}
if (j == 14) {
al_draw_bitmap(leftup, x - 60, y - 60, 0);
}
if (j == 13) {
al_draw_bitmap(upright, x - 60, y - 60, 0);
}
if (ev.type == ALLEGRO_EVENT_MOUSE_BUTTON_UP) {
for (i = 0; i <= 3; i++) {
if (ev.mouse.x >= space[i][0] && ev.mouse.x <= space[i][0] + 120
&& ev.mouse.y >= space[i][1] && ev.mouse.y <= space[i][1] + 120
&& fixed)
{
drop = 1;
moves++;
}
if (ev.mouse.x >= board[j][0] + 120 && ev.mouse.x <= board[j][0] + 240 && ev.mouse.y >= board[j][1] && ev.mouse.y <= board[j][1] + 120 && drop) {
board[j][0] += 120;
space[i][0] -= 120;
}
if (ev.mouse.x <= board[j][0] && ev.mouse.x >= board[j][0] - 120 && ev.mouse.y >= board[j][1] && ev.mouse.y <= board[j][1] + 120 && drop) {
board[j][0] -= 120;
space[i][0] += 120;
}
if (ev.mouse.y >= board[j][1] + 120 && ev.mouse.y <= board[j][1] + 240 && ev.mouse.x >= board[j][0] && ev.mouse.x <= board[j][0] + 120 && drop) {
board[j][1] += 120;
space[i][1] -= 120;
}
if (ev.mouse.y <= board[j][1] && ev.mouse.y >= board[j][1] - 120 && ev.mouse.x >= board[j][0] && ev.mouse.x <= board[j][0] + 120 && drop) {
board[j][1] -= 120;
space[i][1] += 120;
}
}
boxistaken = 0;
drop = 0;
}
}
al_flip_display();
if (((board[8][0] == final[1][0] && board[8][1] == final[1][1]) || (board[6][0] == final[1][0] && board[6][1] == final[1][1]))
&& board[9][0] == final[2][0] && board[9][1] == final[2][1]
&& board[13][0] == final[4][0] && board[13][1] == final[4][1]
&& board[7][0] == final[5][0] && board[7][1] == final[5][1]
&& board[14][0] == final[6][0] && board[14][1] == final[6][1]
&& ((board[10][0] == final[3][0] && board[10][1] == final[3][1]) || (board[11][0] == final[3][0] && board[11][1] == final[3][1]))
&& ((board[10][0] == final[0][0] && board[10][1] == final[0][1]) || (board[11][0] == final[0][0] && board[11][1] == final[0][1]))) {
while (ypos >= 344) {
al_clear_to_color(al_map_rgb(17, 17, 17));
al_draw_bitmap(Background, 0, 0, 0);
al_draw_bitmap(upanddown, board[11][0], board[11][1], 0);
al_draw_bitmap(upanddown, board[10][0], board[10][1], 0);
al_draw_bitmap(box, board[0][0], board[0][1], 0);
al_draw_bitmap(box, board[1][0], board[1][1], 0);
al_draw_bitmap(downright, board[6][0], board[6][1], 0);
al_draw_bitmap(downright, board[8][0], board[8][1], 0);
al_draw_bitmap(leftdown, board[9][0], board[9][1], 0);
al_draw_bitmap(leftandright, board[7][0], board[7][1], 0);
al_draw_bitmap(leftup, board[14][0], board[14][1], 0);
al_draw_bitmap(upright, board[13][0], board[13][1], 0);
al_draw_bitmap(begu, 80, 360, 0);
al_draw_bitmap(redd, 440, 0, 0);
al_draw_text(font, al_map_rgb(243, 197, 147), 28, 87, 0, "1");
al_draw_textf(font, al_map_rgb(243, 197, 147), 585, 83, 0, "%i", moves);
al_draw_filled_circle(xpos, ypos, 18, al_map_rgb(157, 60, 1));
ypos -= 0.15;
al_flip_display();
}
while (ypos >= 306 || xpos <= 171) {
al_clear_to_color(al_map_rgb(17, 17, 17));
al_draw_bitmap(Background, 0, 0, 0);
al_draw_bitmap(upanddown, board[11][0], board[11][1], 0);
al_draw_bitmap(upanddown, board[10][0], board[10][1], 0);
al_draw_bitmap(box, board[0][0], board[0][1], 0);
al_draw_bitmap(box, board[1][0], board[1][1], 0);
al_draw_bitmap(downright, board[6][0], board[6][1], 0);
al_draw_bitmap(downright, board[8][0], board[8][1], 0);
al_draw_bitmap(leftdown, board[9][0], board[9][1], 0);
al_draw_bitmap(leftandright, board[7][0], board[7][1], 0);
al_draw_bitmap(leftup, board[14][0], board[14][1], 0);
al_draw_bitmap(upright, board[13][0], board[13][1], 0);
al_draw_bitmap(begu, 80, 360, 0);
al_draw_bitmap(redd, 440, 0, 0);
al_draw_text(font, al_map_rgb(243, 197, 147), 28, 87, 0, "1");
al_draw_textf(font, al_map_rgb(243, 197, 147), 585, 83, 0, "%i", moves);
al_draw_filled_circle(xpos, ypos, 18, al_map_rgb(157, 60, 1));
if (xpos <= 171) {
xpos += 0.15;
}
if (ypos >= 306) {
ypos -= 0.15;
}
al_flip_display();
}
while (xpos <= 225) {
al_clear_to_color(al_map_rgb(17, 17, 17));
al_draw_bitmap(Background, 0, 0, 0);
al_draw_bitmap(upanddown, board[11][0], board[11][1], 0);
al_draw_bitmap(upanddown, board[10][0], board[10][1], 0);
al_draw_bitmap(box, board[0][0], board[0][1], 0);
al_draw_bitmap(box, board[1][0], board[1][1], 0);
al_draw_bitmap(downright, board[6][0], board[6][1], 0);
al_draw_bitmap(downright, board[8][0], board[8][1], 0);
al_draw_bitmap(leftdown, board[9][0], board[9][1], 0);
al_draw_bitmap(leftandright, board[7][0], board[7][1], 0);
al_draw_bitmap(leftup, board[14][0], board[14][1], 0);
al_draw_bitmap(upright, board[13][0], board[13][1], 0);
al_draw_bitmap(begu, 80, 360, 0);
al_draw_bitmap(redd, 440, 0, 0);
al_draw_text(font, al_map_rgb(243, 197, 147), 28, 87, 0, "1");
al_draw_textf(font, al_map_rgb(243, 197, 147), 585, 83, 0, "%i", moves);
al_draw_filled_circle(xpos, ypos, 18, al_map_rgb(157, 60, 1));
if (xpos <= 225) {
xpos += 0.15;
}
al_flip_display();
}
while (ypos <= 351 || xpos <= 255) {
al_clear_to_color(al_map_rgb(17, 17, 17));
al_draw_bitmap(Background, 0, 0, 0);
al_draw_bitmap(upanddown, board[11][0], board[11][1], 0);
al_draw_bitmap(upanddown, board[10][0], board[10][1], 0);
al_draw_bitmap(box, board[0][0], board[0][1], 0);
al_draw_bitmap(box, board[1][0], board[1][1], 0);
al_draw_bitmap(downright, board[6][0], board[6][1], 0);
al_draw_bitmap(downright, board[8][0], board[8][1], 0);
al_draw_bitmap(leftdown, board[9][0], board[9][1], 0);
al_draw_bitmap(leftandright, board[7][0], board[7][1], 0);
al_draw_bitmap(leftup, board[14][0], board[14][1], 0);
al_draw_bitmap(upright, board[13][0], board[13][1], 0);
al_draw_bitmap(begu, 80, 360, 0);
al_draw_bitmap(redd, 440, 0, 0);
al_draw_text(font, al_map_rgb(243, 197, 147), 28, 87, 0, "1");
al_draw_textf(font, al_map_rgb(243, 197, 147), 585, 83, 0, "%i", moves);
al_draw_filled_circle(xpos, ypos, 18, al_map_rgb(157, 60, 1));
if (xpos <= 255) {
xpos += 0.15;
}
if (ypos <= 351) {
ypos += 0.15;
}
al_flip_display();
}
while (ypos <= 416 || xpos <= 275) {
al_clear_to_color(al_map_rgb(17, 17, 17));
al_draw_bitmap(Background, 0, 0, 0);
al_draw_bitmap(upanddown, board[11][0], board[11][1], 0);
al_draw_bitmap(upanddown, board[10][0], board[10][1], 0);
al_draw_bitmap(box, board[0][0], board[0][1], 0);
al_draw_bitmap(box, board[1][0], board[1][1], 0);
al_draw_bitmap(downright, board[6][0], board[6][1], 0);
al_draw_bitmap(downright, board[8][0], board[8][1], 0);
al_draw_bitmap(leftdown, board[9][0], board[9][1], 0);
al_draw_bitmap(leftandright, board[7][0], board[7][1], 0);
al_draw_bitmap(leftup, board[14][0], board[14][1], 0);
al_draw_bitmap(upright, board[13][0], board[13][1], 0);
al_draw_bitmap(begu, 80, 360, 0);
al_draw_bitmap(redd, 440, 0, 0);
al_draw_text(font, al_map_rgb(243, 197, 147), 28, 87, 0, "1");
al_draw_textf(font, al_map_rgb(243, 197, 147), 585, 83, 0, "%i", moves);
al_draw_filled_circle(xpos, ypos, 18, al_map_rgb(157, 60, 1));
if (xpos <= 275) {
xpos += 0.15;
}
if (ypos <= 416) {
ypos += 0.15;
}
al_flip_display();
}
while (xpos <= 473) {
al_clear_to_color(al_map_rgb(17, 17, 17));
al_draw_bitmap(Background, 0, 0, 0);
al_draw_bitmap(upanddown, board[11][0], board[11][1], 0);
al_draw_bitmap(upanddown, board[10][0], board[10][1], 0);
al_draw_bitmap(box, board[0][0], board[0][1], 0);
al_draw_bitmap(box, board[1][0], board[1][1], 0);
al_draw_bitmap(downright, board[6][0], board[6][1], 0);
al_draw_bitmap(downright, board[8][0], board[8][1], 0);
al_draw_bitmap(leftdown, board[9][0], board[9][1], 0);
al_draw_bitmap(leftandright, board[7][0], board[7][1], 0);
al_draw_bitmap(leftup, board[14][0], board[14][1], 0);
al_draw_bitmap(upright, board[13][0], board[13][1], 0);
al_draw_bitmap(begu, 80, 360, 0);
al_draw_bitmap(redd, 440, 0, 0);
al_draw_text(font, al_map_rgb(243, 197, 147), 28, 87, 0, "1");
al_draw_textf(font, al_map_rgb(243, 197, 147), 585, 83, 0, "%i", moves);
al_draw_filled_circle(xpos, ypos, 18, al_map_rgb(157, 60, 1));
if (xpos <= 478) {
xpos += 0.15;
}
al_flip_display();
}
while (ypos >= 368 || xpos <= 502) {
al_clear_to_color(al_map_rgb(17, 17, 17));
al_draw_bitmap(Background, 0, 0, 0);
al_draw_bitmap(upanddown, board[11][0], board[11][1], 0);
al_draw_bitmap(upanddown, board[10][0], board[10][1], 0);
al_draw_bitmap(box, board[0][0], board[0][1], 0);
al_draw_bitmap(box, board[1][0], board[1][1], 0);
al_draw_bitmap(downright, board[6][0], board[6][1], 0);
al_draw_bitmap(downright, board[8][0], board[8][1], 0);
al_draw_bitmap(leftdown, board[9][0], board[9][1], 0);
al_draw_bitmap(leftandright, board[7][0], board[7][1], 0);
al_draw_bitmap(leftup, board[14][0], board[14][1], 0);
al_draw_bitmap(upright, board[13][0], board[13][1], 0);
al_draw_bitmap(begu, 80, 360, 0);
al_draw_bitmap(redd, 440, 0, 0);
al_draw_text(font, al_map_rgb(243, 197, 147), 28, 87, 0, "1");
al_draw_textf(font, al_map_rgb(243, 197, 147), 585, 83, 0, "%i", moves);
al_draw_filled_circle(xpos, ypos, 18, al_map_rgb(157, 60, 1));
if (xpos <= 502) {
xpos += 0.15;
}
if (ypos >= 368) {
ypos -= 0.15;
}
al_flip_display();
}
while (ypos >= 50) {
al_clear_to_color(al_map_rgb(17, 17, 17));
al_draw_bitmap(Background, 0, 0, 0);
al_draw_bitmap(upanddown, board[11][0], board[11][1], 0);
al_draw_bitmap(upanddown, board[10][0], board[10][1], 0);
al_draw_bitmap(box, board[0][0], board[0][1], 0);
al_draw_bitmap(box, board[1][0], board[1][1], 0);
al_draw_bitmap(downright, board[6][0], board[6][1], 0);
al_draw_bitmap(downright, board[8][0], board[8][1], 0);
al_draw_bitmap(leftdown, board[9][0], board[9][1], 0);
al_draw_bitmap(leftandright, board[7][0], board[7][1], 0);
al_draw_bitmap(leftup, board[14][0], board[14][1], 0);
al_draw_bitmap(upright, board[13][0], board[13][1], 0);
al_draw_bitmap(begu, 80, 360, 0);
al_draw_bitmap(redd, 440, 0, 0);
al_draw_text(font, al_map_rgb(243, 197, 147), 28, 87, 0, "1");
al_draw_textf(font, al_map_rgb(243, 197, 147), 585, 83, 0, "%i", moves);
al_draw_filled_circle(xpos, ypos, 18, al_map_rgb(157, 60, 1));
ypos -= 0.15;
al_flip_display();
}
while (nextlevel) {
al_play_sample_instance(clap1);
al_wait_for_event(queue, &ev);
if (moves < 10) {
al_draw_bitmap(next3, 0, 0, 0);
}
if (moves < 13 && moves>10) {
al_draw_bitmap(next2, 0, 0, 0);
}
if (moves > 13) {
al_draw_bitmap(next1, 0, 0, 0);
}
if (ev.type == ALLEGRO_EVENT_MOUSE_BUTTON_DOWN) {
if (ev.mouse.x < 475 && ev.mouse.x > 176 && ev.mouse.y < 440 && ev.mouse.y > 375) {
nextlevel = 0;
onlevel = 0;
levelsave = 3;
}
}
al_flip_display();
}
}
if (ev.type == ALLEGRO_EVENT_MOUSE_BUTTON_DOWN) {
if (ev.mouse.x < 621 && ev.mouse.x > 576 && ev.mouse.y < 456 && ev.mouse.y > 413) {
al_clear_to_color(al_map_rgb(0, 0, 0));
al_play_sample_instance(playquit1);
al_draw_bitmap(MainMenu, 0, 0, 0);
onlevel = 0;
ongamingsc = 0;
}
}
}
}
void level_3() {
ALLEGRO_EVENT_QUEUE* queue = NULL;
ALLEGRO_EVENT ev;
int board[16][2] = { {80,0}, {0}, {320,0}, {440,0},
{80,120}, {0}, {320,120}, {440,120},
{80,240}, {200,240}, {320,240}, {440,240},
{80,360}, {0}, {320,360}, {440,360} };
int space[3][2] = { {200,0}, {200,120}, {200,360} };
int final[4][2] = { {200,0}, {320,0}, {80,120}, {80,240} };
int i, x = 0, y = 0, j, onlevel = 1, moves = 0;
bool boxistaken = 0, drop = 0, fixed = 0;
nextlevel = 1;
float xpos = 140;
float ypos = 420;
queue = al_create_event_queue();
playquit = al_load_sample("playquit.ogg");
playquit1 = al_create_sample_instance(playquit);
al_attach_sample_instance_to_mixer(playquit1, al_get_default_mixer());
boxsound = al_load_sample("boxsound.ogg");
boxsound1 = al_create_sample_instance(boxsound);
al_attach_sample_instance_to_mixer(boxsound1, al_get_default_mixer());
clap = al_load_sample("clap.ogg");
clap1 = al_create_sample_instance(clap);
al_attach_sample_instance_to_mixer(clap1, al_get_default_mixer());
font = al_load_font("arial.ttf", 24, 0);
Background = al_load_bitmap("gamingsc.bmp");
box = al_load_bitmap("board.bmp");
redl = al_load_bitmap("redl.bmp");
graydr = al_load_bitmap("graydr.bmp");
begu = al_load_bitmap("begu.bmp");
upanddown = al_load_bitmap("uddu.bmp");
downright = al_load_bitmap("downright.bmp");
leftup = al_load_bitmap("leftup.bmp");
leftandright = al_load_bitmap("lrrl.bmp");
next1 = al_load_bitmap("next1.bmp");
next2 = al_load_bitmap("next2.bmp");
next3 = al_load_bitmap("next3.bmp");
al_register_event_source(queue, al_get_display_event_source(display));
al_register_event_source(queue, al_get_mouse_event_source());
while (onlevel && ongamingsc) {
al_wait_for_event(queue, &ev);
al_draw_bitmap(Background, 0, 0, 0);
al_draw_text(font, al_map_rgb(243, 197, 147), 28, 87, 0, "3");
al_draw_textf(font, al_map_rgb(243, 197, 147), 585, 83, 0, "%i", moves);
//spaces
for (i = 0; i <= 2; i++) {
al_draw_filled_rectangle(space[i][0], space[i][1], space[i][0] + 120, space[i][1] + 120, al_map_rgb(17, 17, 17));
}
//boxes
al_draw_bitmap(graydr, board[0][0], board[0][1], 0);
al_draw_bitmap(leftandright, board[2][0], board[2][1], 0);
al_draw_bitmap(redl, board[3][0], board[3][1], 0);
al_draw_bitmap(leftandright, board[4][0], board[4][1], 0);
al_draw_bitmap(upanddown, board[6][0], board[6][1], 0);
al_draw_bitmap(box, board[7][0], board[7][1], 0);
al_draw_bitmap(box, board[11][0], board[11][1], 0);
al_draw_bitmap(box, board[15][0], board[15][1], 0);
al_draw_bitmap(box, board[14][0], board[14][1], 0);
al_draw_bitmap(upanddown, board[8][0], board[8][1], 0);
al_draw_bitmap(downright, board[9][0], board[9][1], 0);
al_draw_bitmap(leftup, board[10][0], board[10][1], 0);
al_draw_bitmap(begu, board[12][0], board[12][1], 0);
al_draw_filled_circle(xpos, ypos, 18, al_map_rgb(157, 60, 1));
if (ev.type == ALLEGRO_EVENT_MOUSE_AXES) {
x = ev.mouse.x;
y = ev.mouse.y;
}
if (!((ev.mouse.x >= board[3][0] && ev.mouse.y >= board[3][1] && ev.mouse.x <= board[3][0] + 120 && ev.mouse.y <= board[3][1] + 120)
|| (ev.mouse.x >= board[12][0] && ev.mouse.y >= board[12][1] && ev.mouse.x <= board[12][0] + 120 && ev.mouse.y <= board[12][1] + 120)
|| (ev.mouse.x >= board[0][0] && ev.mouse.y >= board[0][1] && ev.mouse.x <= board[0][0] + 120 && ev.mouse.y <= board[0][1] + 120))) {
fixed = 1;
}
else { fixed = 0; }
if (ev.type == ALLEGRO_EVENT_MOUSE_BUTTON_DOWN) {
for (i = 0; i <= 15; i++) {
if (ev.mouse.x <= board[i][0] + 120 && ev.mouse.y <= board[i][1] + 120 && ev.mouse.x >= board[i][0] && ev.mouse.y >= board[i][1] && fixed) {
al_draw_filled_rectangle(board[i][0], board[i][1], board[i][0] + 120, board[i][1] + 120, al_map_rgb(17, 17, 17));
al_draw_filled_rectangle(x - 60, y - 60, x + 60, y + 60, al_map_rgb(184, 115, 51));
al_play_sample_instance(boxsound1);
boxistaken = 1;
j = i;
}
}
}
if (boxistaken) {
al_draw_filled_rectangle(board[j][0], board[j][1], board[j][0] + 120, board[j][1] + 120, al_map_rgb(17, 17, 17));
if (j == 7 || j == 11 || j == 14 || j == 15) {
al_draw_bitmap(box, x - 60, y - 60, 0);
}
if (j == 2 || j == 4) {
al_draw_bitmap(leftandright, x - 60, y - 60, 0);
}
if (j == 8 || j == 6) {
al_draw_bitmap(upanddown, x - 60, y - 60, 0);
}
if (j == 9) {
al_draw_bitmap(downright, x - 60, y - 60, 0);
}
if (j == 10) {
al_draw_bitmap(leftup, x - 60, y - 60, 0);
}
if (ev.type == ALLEGRO_EVENT_MOUSE_BUTTON_UP) {
for (i = 0; i <= 2; i++) {
if (ev.mouse.x >= space[i][0] && ev.mouse.x <= space[i][0] + 120
&& ev.mouse.y >= space[i][1] && ev.mouse.y <= space[i][1] + 120
&& fixed)
{
drop = 1;
moves++;
}
if (ev.mouse.x >= board[j][0] + 120 && ev.mouse.x <= board[j][0] + 240 && ev.mouse.y >= board[j][1] && ev.mouse.y <= board[j][1] + 120 && drop) {
board[j][0] += 120;
space[i][0] -= 120;
}
if (ev.mouse.x <= board[j][0] && ev.mouse.x >= board[j][0] - 120 && ev.mouse.y >= board[j][1] && ev.mouse.y <= board[j][1] + 120 && drop) {
board[j][0] -= 120;
space[i][0] += 120;
}
if (ev.mouse.y >= board[j][1] + 120 && ev.mouse.y <= board[j][1] + 240 && ev.mouse.x >= board[j][0] && ev.mouse.x <= board[j][0] + 120 && drop) {
board[j][1] += 120;
space[i][1] -= 120;
}
if (ev.mouse.y <= board[j][1] && ev.mouse.y >= board[j][1] - 120 && ev.mouse.x >= board[j][0] && ev.mouse.x <= board[j][0] + 120 && drop) {
board[j][1] -= 120;
space[i][1] += 120;
}
}
boxistaken = 0;
drop = 0;
}
}
al_flip_display();
if (((board[2][0] == final[0][0] && board[2][1] == final[0][1]) || (board[4][0] == final[0][0] && board[4][1] == final[0][1]))
&& ((board[2][0] == final[1][0] && board[2][1] == final[1][1]) || (board[4][0] == final[1][0] && board[4][1] == final[1][1]))
&& ((board[6][0] == final[2][0] && board[6][1] == final[2][1]) || (board[8][0] == final[2][0] && board[8][1] == final[2][1]))
&& ((board[6][0] == final[3][0] && board[6][1] == final[3][1]) || (board[8][0] == final[3][0] && board[8][1] == final[3][1]))
) {
{
for (int i = 0; i < 3300; i++) {
al_clear_to_color(al_map_rgb(17, 17, 17));
al_draw_bitmap(Background, 0, 0, 0);
al_draw_text(font, al_map_rgb(243, 197, 147), 28, 87, 0, "3");
al_draw_textf(font, al_map_rgb(243, 197, 147), 585, 83, 0, "%i", moves);
al_draw_bitmap(graydr, board[0][0], board[0][1], 0);
al_draw_bitmap(leftandright, board[2][0], board[2][1], 0);
al_draw_bitmap(redl, board[3][0], board[3][1], 0);
al_draw_bitmap(leftandright, board[4][0], board[4][1], 0);
al_draw_bitmap(upanddown, board[6][0], board[6][1], 0);
al_draw_bitmap(box, board[7][0], board[7][1], 0);
al_draw_bitmap(box, board[11][0], board[11][1], 0);
al_draw_bitmap(box, board[15][0], board[15][1], 0);
al_draw_bitmap(box, board[14][0], board[14][1], 0);
al_draw_bitmap(upanddown, board[8][0], board[8][1], 0);
al_draw_bitmap(downright, board[9][0], board[9][1], 0);
al_draw_bitmap(leftup, board[10][0], board[10][1], 0);
al_draw_bitmap(begu, board[12][0], board[12][1], 0);
al_draw_filled_circle(xpos, ypos, 18, al_map_rgb(157, 60, 1));
ypos -= 0.1;
al_flip_display();
}
for (int i = 0; i < 300; i++) {
al_clear_to_color(al_map_rgb(17, 17, 17));
al_draw_bitmap(Background, 0, 0, 0);
al_draw_text(font, al_map_rgb(243, 197, 147), 28, 87, 0, "3");
al_draw_textf(font, al_map_rgb(243, 197, 147), 585, 83, 0, "%i", moves);
al_draw_bitmap(graydr, board[0][0], board[0][1], 0);
al_draw_bitmap(leftandright, board[2][0], board[2][1], 0);
al_draw_bitmap(redl, board[3][0], board[3][1], 0);
al_draw_bitmap(leftandright, board[4][0], board[4][1], 0);
al_draw_bitmap(upanddown, board[6][0], board[6][1], 0);
al_draw_bitmap(box, board[7][0], board[7][1], 0);
al_draw_bitmap(box, board[11][0], board[11][1], 0);
al_draw_bitmap(box, board[15][0], board[15][1], 0);
al_draw_bitmap(box, board[14][0], board[14][1], 0);
al_draw_bitmap(upanddown, board[8][0], board[8][1], 0);
al_draw_bitmap(downright, board[9][0], board[9][1], 0);
al_draw_bitmap(leftup, board[10][0], board[10][1], 0);
al_draw_bitmap(begu, board[12][0], board[12][1], 0);
al_draw_filled_circle(xpos, ypos, 18, al_map_rgb(157, 60, 1));
ypos -= 0.1;
xpos += 0.1;
al_flip_display();
}
for (int i = 0; i < 3300; i++) {
al_clear_to_color(al_map_rgb(17, 17, 17));
al_draw_bitmap(Background, 0, 0, 0);
al_draw_text(font, al_map_rgb(243, 197, 147), 28, 87, 0, "3");
al_draw_textf(font, al_map_rgb(243, 197, 147), 585, 83, 0, "%i", moves);
al_draw_bitmap(graydr, board[0][0], board[0][1], 0);
al_draw_bitmap(leftandright, board[2][0], board[2][1], 0);
al_draw_bitmap(redl, board[3][0], board[3][1], 0);
al_draw_bitmap(leftandright, board[4][0], board[4][1], 0);
al_draw_bitmap(upanddown, board[6][0], board[6][1], 0);
al_draw_bitmap(box, board[7][0], board[7][1], 0);
al_draw_bitmap(box, board[11][0], board[11][1], 0);
al_draw_bitmap(box, board[15][0], board[15][1], 0);
al_draw_bitmap(box, board[14][0], board[14][1], 0);
al_draw_bitmap(upanddown, board[8][0], board[8][1], 0);
al_draw_bitmap(downright, board[9][0], board[9][1], 0);
al_draw_bitmap(leftup, board[10][0], board[10][1], 0);
al_draw_bitmap(begu, board[12][0], board[12][1], 0);
al_draw_filled_circle(xpos, ypos, 18, al_map_rgb(157, 60, 1));
xpos += 0.1;
al_flip_display();
nextlevel = 1;
}
}
while (nextlevel) {
al_play_sample_instance(clap1);
al_wait_for_event(queue, &ev);
if (moves < 5) {
al_draw_bitmap(next3, 0, 0, 0);
}
if (moves < 10 && moves > 5); {
al_draw_bitmap(next2, 0, 0, 0);
}
if (moves > 10) {
al_draw_bitmap(next1, 0, 0, 0);
}
if (ev.type == ALLEGRO_EVENT_MOUSE_BUTTON_DOWN) {
if (ev.mouse.x < 475 && ev.mouse.x > 176 && ev.mouse.y < 440 && ev.mouse.y > 375) {
al_play_sample_instance(playquit1);
nextlevel = 0;
onlevel = 0;
levelsave = 4;
}
}
al_flip_display();
}
}
if (ev.type == ALLEGRO_EVENT_MOUSE_BUTTON_DOWN) {
if (ev.mouse.x < 621 && ev.mouse.x > 576 && ev.mouse.y < 456 && ev.mouse.y > 413) {
al_clear_to_color(al_map_rgb(0, 0, 0));
al_play_sample_instance(playquit1);
al_draw_bitmap(MainMenu, 0, 0, 0);
onlevel = 0;
ongamingsc = 0;
}
}
}
}
void level_4() {
ALLEGRO_EVENT_QUEUE* queue = NULL;
ALLEGRO_EVENT ev;
int board[16][2] = { {0}, {200,0}, {320,0}, {440,0},
{80,120}, {200,120}, {0}, {440,120},
{80,240}, {200,240}, {320,240}, {440,240},
{80,360}, {200,360}, {0}, {440,360} };
int space[3][2] = { {90,0}, {320,120}, {320,360} };
int final[5][2] = { {200,0}, {200,120}, {200,240}, {80,360}, {200,360} };
int i, x = 0, y = 0, j, moves = 0;
bool boxistaken = 0, drop = 0, fixed = 0, onlevel = 1;
float xpos = 140;
float ypos = 180;
queue = al_create_event_queue();
playquit = al_load_sample("playquit.ogg");
playquit1 = al_create_sample_instance(playquit);
al_attach_sample_instance_to_mixer(playquit1, al_get_default_mixer());
boxsound = al_load_sample("boxsound.ogg");
boxsound1 = al_create_sample_instance(boxsound);
al_attach_sample_instance_to_mixer(boxsound1, al_get_default_mixer());
clap = al_load_sample("clap.ogg");
clap1 = al_create_sample_instance(clap);
al_attach_sample_instance_to_mixer(clap1, al_get_default_mixer());
font = al_load_font("arial.ttf", 24, 0);
Background = al_load_bitmap("gamingsc.bmp");
box = al_load_bitmap("board.bmp");
graylr = al_load_bitmap("graylr.bmp");
grayud = al_load_bitmap("grayud.bmp");
begd = al_load_bitmap("begd.bmp");
redl = al_load_bitmap("redl.bmp");
downright = al_load_bitmap("downright.bmp");
upanddown = al_load_bitmap("uddu.bmp");
upright = al_load_bitmap("upright.bmp");
leftup = al_load_bitmap("leftup.bmp");
gameover = al_load_bitmap("gameover.bmp");
al_register_event_source(queue, al_get_display_event_source(display));
al_register_event_source(queue, al_get_mouse_event_source());
while (onlevel && ongamingsc) {
al_wait_for_event(queue, &ev);
al_draw_bitmap(Background, 0, 0, 0);
al_draw_text(font, al_map_rgb(243, 197, 147), 28, 87, 0, "4");
al_draw_textf(font, al_map_rgb(243, 197, 147), 585, 83, 0, "%i", moves);
//spaces
for (i = 0; i <= 2; i++) {
al_draw_filled_rectangle(space[i][0], space[i][1], space[i][0] + 120, space[i][1] + 120, al_map_rgb(17, 17, 17));
}
//boxes
al_draw_bitmap(box, board[9][0], board[9][1], 0);
al_draw_bitmap(box, board[10][0], board[10][1], 0);
al_draw_bitmap(box, board[11][0], board[11][1], 0);
al_draw_bitmap(downright, board[1][0], board[1][1], 0);
al_draw_bitmap(graylr, board[2][0], board[2][1], 0);
al_draw_bitmap(redl, board[3][0], board[3][1], 0);
al_draw_bitmap(begd, board[4][0], board[4][1], 0);
al_draw_bitmap(upanddown, board[5][0], board[5][1], 0);
al_draw_bitmap(upanddown, board[7][0], board[7][1], 0);
al_draw_bitmap(grayud, board[8][0], board[8][1], 0);
al_draw_bitmap(upanddown, board[15][0], board[15][1], 0);
al_draw_bitmap(upright, board[12][0], board[12][1], 0);
al_draw_bitmap(leftup, board[13][0], board[13][1], 0);
al_draw_filled_circle(xpos, ypos, 18, al_map_rgb(157, 60, 1));
if (ev.type == ALLEGRO_EVENT_MOUSE_AXES) {
x = ev.mouse.x;
y = ev.mouse.y;
}
if (!((ev.mouse.x >= board[2][0] && ev.mouse.y >= board[2][1] && ev.mouse.x <= board[2][0] + 120 && ev.mouse.y <= board[2][1] + 120)
|| (ev.mouse.x >= board[3][0] && ev.mouse.y >= board[3][1] && ev.mouse.x <= board[3][0] + 120 && ev.mouse.y <= board[3][1] + 120)
|| (ev.mouse.x >= board[4][0] && ev.mouse.y >= board[4][1] && ev.mouse.x <= board[4][0] + 120 && ev.mouse.y <= board[4][1] + 120)
|| (ev.mouse.x >= board[8][0] && ev.mouse.y >= board[8][1] && ev.mouse.x <= board[8][0] + 120 && ev.mouse.y <= board[8][1] + 120)
)) {
fixed = 1;
}
else { fixed = 0; }
if (ev.type == ALLEGRO_EVENT_MOUSE_BUTTON_DOWN) {
for (i = 0; i <= 15; i++) {
if (ev.mouse.x <= board[i][0] + 120 && ev.mouse.y <= board[i][1] + 120 && ev.mouse.x >= board[i][0] && ev.mouse.y >= board[i][1] && fixed) {
al_draw_filled_rectangle(board[i][0], board[i][1], board[i][0] + 120, board[i][1] + 120, al_map_rgb(17, 17, 17));
al_draw_filled_rectangle(x - 60, y - 60, x + 60, y + 60, al_map_rgb(184, 115, 51));
al_play_sample_instance(boxsound1);
boxistaken = 1;
j = i;
}
}
}
if (boxistaken) {
al_draw_filled_rectangle(board[j][0], board[j][1], board[j][0] + 120, board[j][1] + 120, al_map_rgb(17, 17, 17));
if (j == 9 || j == 10 || j == 11) {
al_draw_bitmap(box, x - 60, y - 60, 0);
}
if (j == 1) {
al_draw_bitmap(downright, x - 60, y - 60, 0);
}
if (j == 5 || j == 7 || j == 15) {
al_draw_bitmap(upanddown, x - 60, y - 60, 0);
}
if (j == 12) {
al_draw_bitmap(upright, x - 60, y - 60, 0);
}
if (j == 13) {
al_draw_bitmap(rightup, x - 60, y - 60, 0);
}
if (ev.type == ALLEGRO_EVENT_MOUSE_BUTTON_UP) {
for (i = 0; i <= 2; i++) {
if (ev.mouse.x >= space[i][0] && ev.mouse.x <= space[i][0] + 120
&& ev.mouse.y >= space[i][1] && ev.mouse.y <= space[i][1] + 120
&& fixed)
{
moves++;
drop = 1;
}
if (ev.mouse.x >= board[j][0] + 120 && ev.mouse.x <= board[j][0] + 240 && ev.mouse.y >= board[j][1] && ev.mouse.y <= board[j][1] + 120 && drop) {
board[j][0] += 120;
space[i][0] -= 120;
}
if (ev.mouse.x <= board[j][0] && ev.mouse.x >= board[j][0] - 120 && ev.mouse.y >= board[j][1] && ev.mouse.y <= board[j][1] + 120 && drop) {
board[j][0] -= 120;
space[i][0] += 120;
}
if (ev.mouse.y >= board[j][1] + 120 && ev.mouse.y <= board[j][1] + 240 && ev.mouse.x >= board[j][0] && ev.mouse.x <= board[j][0] + 120 && drop) {
board[j][1] += 120;
space[i][1] -= 120;
}
if (ev.mouse.y <= board[j][1] && ev.mouse.y >= board[j][1] - 120 && ev.mouse.x >= board[j][0] && ev.mouse.x <= board[j][0] + 120 && drop) {
board[j][1] -= 120;
space[i][1] += 120;
}
}
boxistaken = 0;
drop = 0;
}
}
al_flip_display();
if (board[1][0] == final[0][0] && board[1][1] == final[0][1]
&& ((board[5][0] == final[1][0] && board[5][1] == final[1][1]) || (board[7][0] == final[1][0] && board[7][1] == final[1][1]) || (board[15][0] == final[1][0] && board[15][1] == final[1][1]))
&& ((board[5][0] == final[2][0] && board[5][1] == final[2][1]) || (board[7][0] == final[2][0] && board[7][1] == final[2][1]) || (board[15][0] == final[2][0] && board[15][1] == final[2][1]))
&& board[12][0] == final[3][0] && board[12][1] == final[3][1]
&& board[13][0] == final[4][0] && board[13][1] == final[4][1]) {
for (int i = 0; i < 2100; i++) {
al_draw_bitmap(Background, 0, 0, 0);
al_draw_text(font, al_map_rgb(243, 197, 147), 28, 87, 0, "4");
al_draw_textf(font, al_map_rgb(243, 197, 147), 585, 83, 0, "%i", moves);
al_draw_bitmap(box, board[9][0], board[9][1], 0);
al_draw_bitmap(box, board[10][0], board[10][1], 0);
al_draw_bitmap(box, board[11][0], board[11][1], 0);
al_draw_bitmap(downright, board[1][0], board[1][1], 0);
al_draw_bitmap(graylr, board[2][0], board[2][1], 0);
al_draw_bitmap(redl, board[3][0], board[3][1], 0);
al_draw_bitmap(begd, board[4][0], board[4][1], 0);
al_draw_bitmap(upanddown, board[5][0], board[5][1], 0);
al_draw_bitmap(upanddown, board[7][0], board[7][1], 0);
al_draw_bitmap(grayud, board[8][0], board[8][1], 0);
al_draw_bitmap(upanddown, board[15][0], board[15][1], 0);
al_draw_bitmap(upright, board[12][0], board[12][1], 0);
al_draw_bitmap(leftup, board[13][0], board[13][1], 0);
al_draw_filled_circle(xpos, ypos, 18, al_map_rgb(157, 60, 1));
ypos += 0.1;
al_flip_display();
}
for (int i = 0; i < 300; i++) {
al_draw_bitmap(Background, 0, 0, 0);
al_draw_text(font, al_map_rgb(243, 197, 147), 28, 87, 0, "4");
al_draw_textf(font, al_map_rgb(243, 197, 147), 585, 83, 0, "%i", moves);
al_draw_bitmap(box, board[9][0], board[9][1], 0);
al_draw_bitmap(box, board[10][0], board[10][1], 0);
al_draw_bitmap(box, board[11][0], board[11][1], 0);
al_draw_bitmap(downright, board[1][0], board[1][1], 0);
al_draw_bitmap(graylr, board[2][0], board[2][1], 0);
al_draw_bitmap(redl, board[3][0], board[3][1], 0);
al_draw_bitmap(begd, board[4][0], board[4][1], 0);
al_draw_bitmap(upanddown, board[5][0], board[5][1], 0);
al_draw_bitmap(upanddown, board[7][0], board[7][1], 0);
al_draw_bitmap(grayud, board[8][0], board[8][1], 0);
al_draw_bitmap(upanddown, board[15][0], board[15][1], 0);
al_draw_bitmap(upright, board[12][0], board[12][1], 0);
al_draw_bitmap(leftup, board[13][0], board[13][1], 0);
al_draw_filled_circle(xpos, ypos, 18, al_map_rgb(157, 60, 1));
ypos += 0.1;
xpos += 0.1;
al_flip_display();
}
for (int i = 0; i < 600; i++) {
al_draw_bitmap(Background, 0, 0, 0);
al_draw_text(font, al_map_rgb(243, 197, 147), 28, 87, 0, "4");
al_draw_textf(font, al_map_rgb(243, 197, 147), 585, 83, 0, "%i", moves);
al_draw_bitmap(box, board[9][0], board[9][1], 0);
al_draw_bitmap(box, board[10][0], board[10][1], 0);
al_draw_bitmap(box, board[11][0], board[11][1], 0);
al_draw_bitmap(downright, board[1][0], board[1][1], 0);
al_draw_bitmap(graylr, board[2][0], board[2][1], 0);
al_draw_bitmap(redl, board[3][0], board[3][1], 0);
al_draw_bitmap(begd, board[4][0], board[4][1], 0);
al_draw_bitmap(upanddown, board[5][0], board[5][1], 0);
al_draw_bitmap(upanddown, board[7][0], board[7][1], 0);
al_draw_bitmap(grayud, board[8][0], board[8][1], 0);
al_draw_bitmap(upanddown, board[15][0], board[15][1], 0);
al_draw_bitmap(upright, board[12][0], board[12][1], 0);
al_draw_bitmap(leftup, board[13][0], board[13][1], 0);
al_draw_filled_circle(xpos, ypos, 18, al_map_rgb(157, 60, 1));
xpos += 0.1;
al_flip_display();
}
for (int i = 0; i < 300; i++) {
al_draw_bitmap(Background, 0, 0, 0);
al_draw_text(font, al_map_rgb(243, 197, 147), 28, 87, 0, "4");
al_draw_textf(font, al_map_rgb(243, 197, 147), 585, 83, 0, "%i", moves);
al_draw_bitmap(box, board[9][0], board[9][1], 0);
al_draw_bitmap(box, board[10][0], board[10][1], 0);
al_draw_bitmap(box, board[11][0], board[11][1], 0);
al_draw_bitmap(downright, board[1][0], board[1][1], 0);
al_draw_bitmap(graylr, board[2][0], board[2][1], 0);
al_draw_bitmap(redl, board[3][0], board[3][1], 0);
al_draw_bitmap(begd, board[4][0], board[4][1], 0);
al_draw_bitmap(upanddown, board[5][0], board[5][1], 0);
al_draw_bitmap(upanddown, board[7][0], board[7][1], 0);
al_draw_bitmap(grayud, board[8][0], board[8][1], 0);
al_draw_bitmap(upanddown, board[15][0], board[15][1], 0);
al_draw_bitmap(upright, board[12][0], board[12][1], 0);
al_draw_bitmap(leftup, board[13][0], board[13][1], 0);
al_draw_filled_circle(xpos, ypos, 18, al_map_rgb(157, 60, 1));
ypos -= 0.1;
xpos += 0.1;
al_flip_display();
}
for (int i = 0; i < 3000; i++) {
al_draw_bitmap(Background, 0, 0, 0);
al_draw_text(font, al_map_rgb(243, 197, 147), 28, 87, 0, "4");
al_draw_textf(font, al_map_rgb(243, 197, 147), 585, 83, 0, "%i", moves);
al_draw_bitmap(box, board[9][0], board[9][1], 0);
al_draw_bitmap(box, board[10][0], board[10][1], 0);
al_draw_bitmap(box, board[11][0], board[11][1], 0);
al_draw_bitmap(downright, board[1][0], board[1][1], 0);
al_draw_bitmap(graylr, board[2][0], board[2][1], 0);
al_draw_bitmap(redl, board[3][0], board[3][1], 0);
al_draw_bitmap(begd, board[4][0], board[4][1], 0);
al_draw_bitmap(upanddown, board[5][0], board[5][1], 0);
al_draw_bitmap(upanddown, board[7][0], board[7][1], 0);
al_draw_bitmap(grayud, board[8][0], board[8][1], 0);
al_draw_bitmap(upanddown, board[15][0], board[15][1], 0);
al_draw_bitmap(upright, board[12][0], board[12][1], 0);
al_draw_bitmap(leftup, board[13][0], board[13][1], 0);
al_draw_filled_circle(xpos, ypos, 18, al_map_rgb(157, 60, 1));
ypos -= 0.1;
al_flip_display();
}
for (int i = 0; i < 300; i++) {
al_draw_bitmap(Background, 0, 0, 0);
al_draw_text(font, al_map_rgb(243, 197, 147), 28, 87, 0, "4");
al_draw_textf(font, al_map_rgb(243, 197, 147), 585, 83, 0, "%i", moves);
al_draw_bitmap(box, board[9][0], board[9][1], 0);
al_draw_bitmap(box, board[10][0], board[10][1], 0);
al_draw_bitmap(box, board[11][0], board[11][1], 0);
al_draw_bitmap(downright, board[1][0], board[1][1], 0);
al_draw_bitmap(graylr, board[2][0], board[2][1], 0);
al_draw_bitmap(redl, board[3][0], board[3][1], 0);
al_draw_bitmap(begd, board[4][0], board[4][1], 0);
al_draw_bitmap(upanddown, board[5][0], board[5][1], 0);
al_draw_bitmap(upanddown, board[7][0], board[7][1], 0);
al_draw_bitmap(grayud, board[8][0], board[8][1], 0);
al_draw_bitmap(upanddown, board[15][0], board[15][1], 0);
al_draw_bitmap(upright, board[12][0], board[12][1], 0);
al_draw_bitmap(leftup, board[13][0], board[13][1], 0);
al_draw_filled_circle(xpos, ypos, 18, al_map_rgb(157, 60, 1));
ypos -= 0.1;
xpos += 0.1;
al_flip_display();
}
for (int i = 0; i < 2100; i++) {
al_draw_bitmap(Background, 0, 0, 0);
al_draw_text(font, al_map_rgb(243, 197, 147), 28, 87, 0, "4");
al_draw_textf(font, al_map_rgb(243, 197, 147), 585, 83, 0, "%i", moves);
al_draw_bitmap(box, board[9][0], board[9][1], 0);
al_draw_bitmap(box, board[10][0], board[10][1], 0);
al_draw_bitmap(box, board[11][0], board[11][1], 0);
al_draw_bitmap(downright, board[1][0], board[1][1], 0);
al_draw_bitmap(graylr, board[2][0], board[2][1], 0);
al_draw_bitmap(redl, board[3][0], board[3][1], 0);
al_draw_bitmap(begd, board[4][0], board[4][1], 0);
al_draw_bitmap(upanddown, board[5][0], board[5][1], 0);
al_draw_bitmap(upanddown, board[7][0], board[7][1], 0);
al_draw_bitmap(grayud, board[8][0], board[8][1], 0);
al_draw_bitmap(upanddown, board[15][0], board[15][1], 0);
al_draw_bitmap(upright, board[12][0], board[12][1], 0);
al_draw_bitmap(leftup, board[13][0], board[13][1], 0);
al_draw_filled_circle(xpos, ypos, 18, al_map_rgb(157, 60, 1));
xpos += 0.1;
nextlevel = 1;
al_flip_display();
}
while (nextlevel) {
al_play_sample_instance(clap1);
al_wait_for_event(queue, &ev);
al_draw_bitmap(gameover, 0, 0, 0);
if (ev.type == ALLEGRO_EVENT_MOUSE_BUTTON_DOWN) {
if (ev.mouse.x < 410 && ev.mouse.x > 200 && ev.mouse.y < 405 && ev.mouse.y > 364) {
al_play_sample_instance(playquit1);
nextlevel = 0;
}
}
al_flip_display();
}
onlevel = 0;
levelsave = 1;
ongamingsc = 0;
}
if (ev.type == ALLEGRO_EVENT_MOUSE_BUTTON_DOWN) {
if (ev.mouse.x < 621 && ev.mouse.x > 576 && ev.mouse.y < 456 && ev.mouse.y > 413) {
al_clear_to_color(al_map_rgb(0, 0, 0));
al_play_sample_instance(playquit1);
al_draw_bitmap(MainMenu, 0, 0, 0);
onlevel = 0;
ongamingsc = 0;
}
}
}
}
void destroy_all() {
al_destroy_bitmap(Background);
al_destroy_bitmap(MainMenu);
al_destroy_bitmap(next1);
al_destroy_bitmap(next2);
al_destroy_bitmap(next3);
al_destroy_bitmap(gameover);
al_destroy_bitmap(begd);
al_destroy_bitmap(begu);
al_destroy_bitmap(leftup);
al_destroy_bitmap(downright);
al_destroy_bitmap(leftandright);
al_destroy_bitmap(leftdown);
al_destroy_bitmap(upanddown);
al_destroy_bitmap(rightup);
al_destroy_bitmap(upright);
al_destroy_bitmap(graydr);
al_destroy_bitmap(graylr);
al_destroy_bitmap(grayud);
al_destroy_bitmap(redd);
al_destroy_bitmap(redl);
al_destroy_bitmap(box);
al_destroy_sample(theme);
al_destroy_sample(playquit);
al_destroy_sample(boxsound);
al_destroy_sample(clap);
al_destroy_sample_instance(playquit1);
al_destroy_sample_instance(boxsound1);
al_destroy_sample_instance(clap1);
al_destroy_font(font);
al_destroy_display(display);
} | 2.078125 | 2 |
2024-11-18T19:02:37.150081+00:00 | 2018-09-07T07:23:43 | 84e199647aaea45b389085ce56cb4fa17a702c7b | {
"blob_id": "84e199647aaea45b389085ce56cb4fa17a702c7b",
"branch_name": "refs/heads/master",
"committer_date": "2018-09-07T07:23:43",
"content_id": "1a7cd83c49392fd0f18710086c1b887be93476e1",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "7848fdc2a4991a6762d74dcb3f4532ca9dc3f80d",
"extension": "c",
"filename": "BEAssetsManager.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 131020625,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 6183,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/Pods/BohdiEngine/BohdiEngine/Classes/BEAssets/BEAssetsManager.c",
"provenance": "stackv2-0058.json.gz:156443",
"repo_name": "sunpaq/BEMac",
"revision_date": "2018-09-07T07:23:43",
"revision_id": "e89b67c3603c9bb719bda232062be2fd162dee36",
"snapshot_id": "6fb5712c951dfa8945778020fb052849bd6aed3a",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/sunpaq/BEMac/e89b67c3603c9bb719bda232062be2fd162dee36/Pods/BohdiEngine/BohdiEngine/Classes/BEAssets/BEAssetsManager.c",
"visit_date": "2020-03-13T07:11:53.322233"
} | stackv2 | //
// BEAssetsManager.c
// Sapindus
//
// Created by Sun YuLi on 16/4/30.
// Copyright © 2016年 oreisoft. All rights reserved.
//
#ifdef __APPLE__
#include "TargetConditionals.h"
#include <CoreFoundation/CoreFoundation.h>
#include <pthread.h>
static CFStringRef BundlePath = NULL;
#endif
#include "BEAssetsManager.h"
#if defined(__ANDROID__)
static AAssetManager* assetManager_ = null;
static ANativeWindow* window_ = null;
void MCFileSetAssetManager(AAssetManager* assetManager) { assetManager_ = assetManager; }
AAssetManager* MCFileGetAssetManager() { return assetManager_; }
#endif
int MCFileGetPath(const char* filename, char* buffer)
{
return MCFileGetPathFromBundle(NULL, filename, buffer);
}
int MCFileGetPathFromBundle(const char* bundlename, const char* filename, char* buffer)
{
if (isFilename(filename) == false) {
printf("MCFileGetPath - filename malformed: %s\n", filename);
return -1;
}
char basename[256] = {0};
char extension[64] = {0};
if (MCString_extensionFromFilename(filename, basename, extension) > 0) {
debug_log("MCFileGetPath - filename/basename/extension -> %s/%s/%s\n", filename, basename, extension);
} else {
debug_log("MCFileGetPath - filename/basename/no extension -> %s/%s\n", filename, basename);
}
#ifdef __ANDROID__
if (assetManager_ != null) {
const char* subpath;
if (strcmp(extension, "fsh") == 0) {
subpath = "shaders";
} else if (strcmp(extension, "vsh") == 0) {
subpath = "shaders";
} else if (strcmp(extension, "obj") == 0 || strcmp(extension, "mtl") == 0) {
subpath = "raw";
} else if (strcmp(extension, "png") == 0) {
subpath = "textures";
} else if (strcmp(extension, "jpg") == 0) {
subpath = "textures";
} else if (strcmp(extension, "tga") == 0) {
subpath = "textures";
} else if (strcmp(extension, "dds") == 0) {
subpath = "textures";
} else {
subpath = "raw";
error_log("can not detect(%s) use raw folder\n", extension);
}
char fullname[PATH_MAX] = {};
sprintf(fullname, "%s.%s", basename, extension);
AAssetDir* rootdir = AAssetManager_openDir(assetManager_, subpath);
if (rootdir) {
const char* name;
char fullpath[PATH_MAX] = {0};
while ((name=AAssetDir_getNextFileName(rootdir)) != NULL) {
if (strcmp(fullname, name) == 0) {
sprintf(fullpath, "%s/%s", subpath, name);
strcpy(buffer, fullpath);
}
}
}else{
error_log("can not find rootdir\n");
return -1;
}
}
return 0;
#else
if (BundlePath == NULL) {
//static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
//pthread_mutex_lock(&lock);
CFBundleRef bundle = NULL;
if (bundlename) {
CFStringRef bid = CFStringCreateWithCString(kCFAllocatorDefault, bundlename, kCFStringEncodingUTF8);
bundle = CFBundleGetBundleWithIdentifier(bid);
CFRelease(bid);
} else {
bundle = CFBundleGetMainBundle();
}
if (!bundle) {
error_log("BEAssetManager can not find bundle (%s)\n", bundlename);
//pthread_mutex_unlock(&lock);
return -1;
}
CFURLRef url = CFBundleCopyBundleURL(bundle);
if (!url) {
error_log("BEAssetManager can not find path of (%s).(%s)\n", basename, extension);
//pthread_mutex_unlock(&lock);
return -1;
}
BundlePath = CFURLCopyPath(url);
CFRelease(url);
//pthread_mutex_unlock(&lock);
}
char rootpath[PATH_MAX] = {0};
CFStringGetCString(BundlePath, rootpath, PATH_MAX, kCFStringEncodingUTF8);
#if TARGET_OS_OSX
strcat(rootpath, "Contents/Resources/");
strcat(rootpath, filename);
#else
strcat(rootpath, filename);
#endif
MCStringFillLimited(buffer, rootpath, strlen(rootpath));
return 0;
#endif
}
const char* MCFileCopyContentWithPathGetBufferSize(const char* filepath, off_t* buffsize)
{
#ifdef __ANDROID__
if (assetManager_ != null) {
debug_log("MCFileCopyContentWithPath %s\n", filepath);
AAsset* f = AAssetManager_open(assetManager_, filepath, AASSET_MODE_BUFFER);
if (f) {
const char* abuff = AAsset_getBuffer(f);
if (abuff) {
off_t size = AAsset_getLength(f);
char* buff = (char*)malloc((size + 1) * sizeof(char));
memcpy(buff, abuff, size);
buff[size] = NUL;
AAsset_close(f);
if (buffsize) {
*buffsize = size;
}
return buff;
}else{
error_log("MCFileCopyContentWithPath(%s) AAsset_getBuffer() failed\n", filepath);
}
}else{
error_log("MCFileCopyContentWithPath(%s) Android assetManager_ can not open\n", filepath);
}
}
error_log("MCFileCopyContent(%s) Android assetManager_ is null\n", filepath);
return null;
#else
char decodepath[PATH_MAX] = {0};
FILE* f = fopen(MCString_percentDecode(filepath, decodepath), "r");
if (f) {
fseek(f, 0, SEEK_END);
off_t size = ftell(f) + 1;
fseek(f, 0, SEEK_SET);
char* buffer = (char*)malloc(size);
if (!buffer) {
error_log("MCFileCopyContent(%s) can not alloc buffer\n", filepath);
return NULL;
}
memset(buffer, 0, size);
//copy
fread(buffer, 1, size, f);
fclose(f);
if (buffsize) {
*buffsize = size;
}
return buffer;
}else{
error_log("MCFileCopyContent(%s) fopen return null\n", filepath);
return NULL;
}
#endif
}
const char* MCFileCopyContentWithPath(const char* filepath)
{
return MCFileCopyContentWithPathGetBufferSize(filepath, NULL);
}
void MCFileReleaseContent(const char* buff)
{
free((void*)buff);
}
| 2.046875 | 2 |
2024-11-18T19:02:37.232175+00:00 | 2020-07-11T00:47:18 | 205dc97725702deeea46d0824bb6ce365c3a743b | {
"blob_id": "205dc97725702deeea46d0824bb6ce365c3a743b",
"branch_name": "refs/heads/master",
"committer_date": "2020-07-11T00:47:18",
"content_id": "61af0d6095d85fc6a4c66b4ce089c6da902e80ad",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "6a237621c06c52d3f93df0cd8306d5e5600df017",
"extension": "c",
"filename": "shuffle.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 146354542,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 6806,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/ECE264/HW09/shuffle.c",
"provenance": "stackv2-0058.json.gz:156571",
"repo_name": "cmz97/Purdue-ECE-Programming-Assignment-Archive",
"revision_date": "2020-07-11T00:47:18",
"revision_id": "4f54ff3db69e7d46e989af268c55fbeb2007576f",
"snapshot_id": "3b6eca22b0dd67709b643d9f81fe19dcb6f6c30f",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/cmz97/Purdue-ECE-Programming-Assignment-Archive/4f54ff3db69e7d46e989af268c55fbeb2007576f/ECE264/HW09/shuffle.c",
"visit_date": "2022-11-13T01:21:45.382003"
} | stackv2 | // Please modify this file as required
#include "shuffle.h"
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
// You can add more functions, structures, and vairables to this file.
// Helper functions must start with '_'.
//This is an example of a helper function.
//clean function whenever malloc fails in shuffle function
static void _error_clean()
{
exit(EXIT_FAILURE);
}
#ifdef TEST_DIV
void divide(CardDeck orig_deck, CardDeck* upper_deck, CardDeck* lower_deck)
{
//Dividing the desks into the way mentioned in the document - as lower and upper
//Use a loop from index i to orig_deck.size - 1
//starting from 1 -> size-1 copying into upper deck and lower decks
//strncpy((upper_deck[i]).cards, orig_deck.cards,i+1);
//update size of upper deck
//For example: upper_deck[i].size = i+1;
//update size of lower deck:
//For example: lower_deck[i].size = orig_deck.size -i -1;
for (int i=0; i<orig_deck.size-1; i++) {
strncpy((upper_deck[i]).cards, orig_deck.cards,i+1);
upper_deck[i].size = i+1;
strncpy((lower_deck[i]).cards, orig_deck.cards+i+1,orig_deck.size-i-1);
lower_deck[i].size = orig_deck.size -i - 1;
}
}
#endif
#ifdef TEST_INTER
//repeat holds the number of shuffles yet to be performed.
//after the interleave operation has been completed, you will recursively call
//repeat_shuffle(...) with a decremented value of repeat.
void interleave_Util(CardDeck*, CardDeck*, CardDeck*, int, int, int);
//CardDeck* combineDeck(CardDeck*,CardDeck*);
void interleave(CardDeck upper_deck, CardDeck lower_deck, int repeat)
{
// Follow instructions in the README, to understand the working of the recursive function.
// when the newly shuffled deck is complete:
//you will perform another k-1 rounds of shuffling with the new deck
// Tip: There should be no uncertainty in this function.
//If you think a random number generator is needed, you are on the wrong track.
// Tip: To copy the elements of one array from one array to another (e.g., the array of cards in a CardDeck),
//you could use memcpy(…).
//The = operator will simply copy the address, not the elements themselves.
CardDeck* handed = malloc(sizeof(CardDeck));
if (handed == NULL) {
fprintf(stderr, "maclloc fail\n");
_error_clean();
}
handed->size = 1;
interleave_Util(handed,&upper_deck,&lower_deck,0,0,repeat);
//printf("Here is the resulting shuffle upper and lower deck: \n");
//printDeck(*combineDeck(&upper_deck,&lower_deck));
free(handed);
}
//CardDeck* combineDeck(CardDeck* upper,CardDeck* lower)
//{
// int size = upper->size + lower->size;
// CardDeck * newCardDeck = malloc(sizeof(CardDeck));
// newCardDeck->size = size;
// for (int i=0; i<upper->size; i++) {
// newCardDeck->cards[i] = upper->cards[i];
// }
//
// for (int i=0; i<lower->size; i++) {
// newCardDeck->cards[i+upper->size] = lower->cards[i];
// }
//
// return newCardDeck;
//
//}
void interleave_Util(CardDeck* handed, CardDeck* upper_deck, CardDeck* lower_deck, int upper_ind, int lower_ind, int repeat)
{
if (upper_ind >= upper_deck->size) {
for (int i = lower_ind; i < lower_deck->size; i++) {
handed->cards[handed->size -1+i-lower_ind] = lower_deck->cards[i];
}
lower_ind = lower_deck->size - 1;
handed->size = lower_deck->size + upper_deck->size;
//printDeck(*handed);
repeat_shuffle(*handed,repeat-1);
//fprintf(stderr, "call\n");
return;
}
if (lower_ind >= lower_deck->size) {
for (int i = upper_ind; i < upper_deck->size; i++) {
handed->cards[handed->size -1+i-upper_ind] = upper_deck->cards[i];
}
upper_ind = upper_deck->size - 1;
handed->size = lower_deck->size + upper_deck->size;
//printDeck(*handed);
repeat_shuffle(*handed,repeat-1);
//fprintf(stderr, "call\n");
return;
}
CardDeck* newHanded = malloc(sizeof(CardDeck));
if (newHanded == NULL) {
fprintf(stderr, "maclloc fail\n");
_error_clean();
}
memcpy(newHanded,handed,sizeof(CardDeck));
newHanded->cards[newHanded->size-1] = upper_deck->cards[upper_ind];
newHanded->size++;
upper_ind++;
interleave_Util(newHanded,upper_deck,lower_deck,upper_ind,lower_ind,repeat);
upper_ind--;
memcpy(newHanded,handed,sizeof(CardDeck));
newHanded->cards[newHanded->size-1] = lower_deck->cards[lower_ind];
newHanded->size++;
lower_ind++;
interleave_Util(newHanded,upper_deck,lower_deck,upper_ind,lower_ind,repeat);
lower_ind--;
free(newHanded);
}
#endif
#ifdef TEST_SHUF
//repeat holds the number of shuffles that are yet to be performed.
void shuffle(CardDeck orig_deck, int repeat)
{
// declare a variable to hold the number of pairs
// we can say that we have only size-1 possibility of pairs
int numpairs = orig_deck.size - 1;
// if number of pairs == 0; return;
if (numpairs == 0) {
return;
}
// instantiate pointers to hold both upper and lower decks (after division)
// For example: CardDeck * upper_deck = NULL;
CardDeck * upper_deck = NULL;
CardDeck * lower_deck = NULL;
// allocate memory based on number of pairs
//For example: upper_deck = malloc(numpairs*sizeof(CardDeck));
upper_deck = malloc(numpairs*sizeof(CardDeck));
lower_deck = malloc(numpairs*sizeof(CardDeck));
if (upper_deck == NULL || lower_deck == NULL) {
fprintf(stderr, "maclloc fail\n");
_error_clean();
}
// call divideDeck to fill upper_deck and lower_deck
divide(orig_deck, upper_deck, lower_deck);
//run a loop through all the pairs
// for each pair of upper and lower deck call interleave()
// For example: interleave(upper_deck[i],lower_deck[i]);
for (int i = 0; i<numpairs; i++) {
interleave(upper_deck[i],lower_deck[i],repeat);
}
free(upper_deck);
free(lower_deck);
// free memory allocated to upper and lower deck.
}
#endif
#ifdef TEST_RSHUF
void repeat_shuffle(CardDeck orig_deck, int k)
{
//orig_deck contains a deck of cards, and it's size.
//printf("Shuffle:(orig_deck,%d)\n",k);
//If (k ≤ 0), no shuffling, print the only possible outcome.
if (k<=0) {
printDeck(orig_deck);
return;
}
//printDeck(orig_deck); and return
//TIP: Print only the results obtained after k rounds of shuffling
// call shuffle(orig_deck);
shuffle(orig_deck,k);
// TIP: In interleave(…), when the newly shuffled deck is complete,
//you will perform another k-1 rounds of shuffling with the new deck.
}
#endif
| 2.84375 | 3 |
2024-11-18T19:02:37.445719+00:00 | 2017-05-07T10:59:57 | 1a326c72b5eb09ac1588509a2bc1599a954941f0 | {
"blob_id": "1a326c72b5eb09ac1588509a2bc1599a954941f0",
"branch_name": "refs/heads/master",
"committer_date": "2017-05-07T10:59:57",
"content_id": "3628aabda8a980ae643b1092b48424a775e92171",
"detected_licenses": [
"Unlicense"
],
"directory_id": "2ba0ca0f8ad65c256eabb89e29bbf763ef7ee262",
"extension": "c",
"filename": "greedy.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 67682774,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1018,
"license": "Unlicense",
"license_type": "permissive",
"path": "/week01/pset1/greedy.c",
"provenance": "stackv2-0058.json.gz:156699",
"repo_name": "fazzolini/cs50x",
"revision_date": "2017-05-07T10:59:57",
"revision_id": "fbee01ebcb8539d66d457491cf06e1b3ec7f9523",
"snapshot_id": "7d2703ef8bb66a261db2ab693ad9849804294837",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/fazzolini/cs50x/fbee01ebcb8539d66d457491cf06e1b3ec7f9523/week01/pset1/greedy.c",
"visit_date": "2020-12-01T11:10:20.603351"
} | stackv2 | /**
* greedy.c
* this is part of CS50X pset1
*
* Otto Brut
* [email protected]
*
* version: 1.01
*
* Calculates how many coins of change you will get.
*/
#include <cs50.h>
#include <stdio.h>
int main(void)
{
// first deal with input
printf("O hai! ");
float raw_input;
do
{
printf("How much change is owed?\n");
raw_input = GetFloat();
}
while(raw_input < 0.0);
/**
* now it gets UGLY
* this is to deal with 4.2 * 100 = 419.999
* SERISLY, WAT DA FUK, C?!
*/
int thousands = (int)(raw_input * 1000);
int cents = thousands / 10;
int remainder = thousands % 10;
if (remainder == 9) cents++;
// while there is change
int result = 0;
while(cents)
{
if (cents >= 25)
{
cents -= 25;
result++;
} else if (cents >= 10)
{
cents -= 10;
result++;
} else if (cents >= 5)
{
cents -= 5;
result++;
} else if (cents >= 1)
{
cents -= 1;
result++;
}
}
// produce result to the user on screen
printf("%d\n", result);
} | 3.515625 | 4 |
2024-11-18T19:02:37.528736+00:00 | 2023-08-23T16:50:55 | 93126fc48b64fa361d64defbce34bebee191580a | {
"blob_id": "93126fc48b64fa361d64defbce34bebee191580a",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-23T16:50:55",
"content_id": "1a4722c61adb0811b766ba46bb58cca0a41c22b2",
"detected_licenses": [
"MIT"
],
"directory_id": "fbdc48c28e54fb33ae4842ef95ff63893902c99a",
"extension": "c",
"filename": "bayer.c",
"fork_events_count": 1226,
"gha_created_at": "2013-11-13T10:23:44",
"gha_event_created_at": "2023-09-14T07:18:15",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 14360940,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 43931,
"license": "MIT",
"license_type": "permissive",
"path": "/src/omv/imlib/bayer.c",
"provenance": "stackv2-0058.json.gz:156827",
"repo_name": "openmv/openmv",
"revision_date": "2023-08-23T16:50:55",
"revision_id": "8a90e070a88b7fc14c87a00351b9c4a213278419",
"snapshot_id": "44d4b79fc8693950a2e330e5e0fd95b5c36e230f",
"src_encoding": "UTF-8",
"star_events_count": 2150,
"url": "https://raw.githubusercontent.com/openmv/openmv/8a90e070a88b7fc14c87a00351b9c4a213278419/src/omv/imlib/bayer.c",
"visit_date": "2023-08-30T20:59:57.227603"
} | stackv2 | /*
* This file is part of the OpenMV project.
*
* Copyright (c) 2013-2021 Ibrahim Abdelkader <[email protected]>
* Copyright (c) 2013-2021 Kwabena W. Agyeman <[email protected]>
*
* This work is licensed under the MIT license, see the file LICENSE for details.
*
* Debayering Functions
*/
#include "imlib.h"
void imlib_debayer_line(int x_start, int x_end, int y_row, void *dst_row_ptr, pixformat_t pixfmt, image_t *src) {
int src_w = src->w, w_limit = src_w - 1, w_limit_m_1 = w_limit - 1;
int src_h = src->h, h_limit = src_h - 1, h_limit_m_1 = h_limit - 1;
int y_row_odd = y_row & 1;
int y = (y_row / 2) * 2;
uint8_t *rowptr_grgr_0, *rowptr_bgbg_1, *rowptr_grgr_2, *rowptr_bgbg_3;
// keep row pointers in bounds
if (y == 0) {
rowptr_bgbg_1 = src->data;
rowptr_grgr_2 = rowptr_bgbg_1 + ((src_h >= 2) ? src_w : 0);
rowptr_bgbg_3 = rowptr_bgbg_1 + ((src_h >= 3) ? (src_w * 2) : 0);
rowptr_grgr_0 = rowptr_grgr_2;
} else if (y == h_limit_m_1) {
rowptr_grgr_0 = src->data + ((y - 1) * src_w);
rowptr_bgbg_1 = rowptr_grgr_0 + src_w;
rowptr_grgr_2 = rowptr_bgbg_1 + src_w;
rowptr_bgbg_3 = rowptr_bgbg_1;
} else if (y >= h_limit) {
rowptr_grgr_0 = src->data + ((y - 1) * src_w);
rowptr_bgbg_1 = rowptr_grgr_0 + src_w;
rowptr_grgr_2 = rowptr_grgr_0;
rowptr_bgbg_3 = rowptr_bgbg_1;
} else {
// get 4 neighboring rows
rowptr_grgr_0 = src->data + ((y - 1) * src_w);
rowptr_bgbg_1 = rowptr_grgr_0 + src_w;
rowptr_grgr_2 = rowptr_bgbg_1 + src_w;
rowptr_bgbg_3 = rowptr_grgr_2 + src_w;
}
// If the image is an odd width this will go for the last loop and we drop the last column.
if (!y_row_odd) {
// even
for (int x = x_start, i = 0; x < x_end; x += 2, i += 2) {
uint32_t row_grgr_0, row_bgbg_1, row_grgr_2;
// keep pixels in bounds
if (x == 0) {
if (src_w >= 4) {
row_grgr_0 = *((uint32_t *) rowptr_grgr_0);
row_bgbg_1 = *((uint32_t *) rowptr_bgbg_1);
row_grgr_2 = *((uint32_t *) rowptr_grgr_2);
} else if (src_w >= 3) {
row_grgr_0 = *((uint16_t *) rowptr_grgr_0) | (*(rowptr_grgr_0 + 2) << 16);
row_bgbg_1 = *((uint16_t *) rowptr_bgbg_1) | (*(rowptr_bgbg_1 + 2) << 16);
row_grgr_2 = *((uint16_t *) rowptr_grgr_2) | (*(rowptr_grgr_2 + 2) << 16);
} else if (src_w >= 2) {
row_grgr_0 = *((uint16_t *) rowptr_grgr_0);
row_grgr_0 = (row_grgr_0 << 16) | row_grgr_0;
row_bgbg_1 = *((uint16_t *) rowptr_bgbg_1);
row_bgbg_1 = (row_bgbg_1 << 16) | row_bgbg_1;
row_grgr_2 = *((uint16_t *) rowptr_grgr_2);
row_grgr_2 = (row_grgr_2 << 16) | row_grgr_2;
} else {
row_grgr_0 = *(rowptr_grgr_0) * 0x01010101;
row_bgbg_1 = *(rowptr_bgbg_1) * 0x01010101;
row_grgr_2 = *(rowptr_grgr_2) * 0x01010101;
}
// The starting point needs to be offset by 1. The below patterns are actually
// rgrg, gbgb, rgrg, and gbgb. So, shift left and backfill the missing border pixel.
row_grgr_0 = (row_grgr_0 << 8) | __UXTB_RORn(row_grgr_0, 8);
row_bgbg_1 = (row_bgbg_1 << 8) | __UXTB_RORn(row_bgbg_1, 8);
row_grgr_2 = (row_grgr_2 << 8) | __UXTB_RORn(row_grgr_2, 8);
} else if (x == w_limit_m_1) {
row_grgr_0 = *((uint32_t *) (rowptr_grgr_0 + x - 2));
row_grgr_0 = (row_grgr_0 >> 8) | ((row_grgr_0 << 8) & 0xff000000);
row_bgbg_1 = *((uint32_t *) (rowptr_bgbg_1 + x - 2));
row_bgbg_1 = (row_bgbg_1 >> 8) | ((row_bgbg_1 << 8) & 0xff000000);
row_grgr_2 = *((uint32_t *) (rowptr_grgr_2 + x - 2));
row_grgr_2 = (row_grgr_2 >> 8) | ((row_grgr_2 << 8) & 0xff000000);
} else if (x >= w_limit) {
row_grgr_0 = *((uint16_t *) (rowptr_grgr_0 + x - 1));
row_grgr_0 = (row_grgr_0 << 16) | row_grgr_0;
row_bgbg_1 = *((uint16_t *) (rowptr_bgbg_1 + x - 1));
row_bgbg_1 = (row_bgbg_1 << 16) | row_bgbg_1;
row_grgr_2 = *((uint16_t *) (rowptr_grgr_2 + x - 1));
row_grgr_2 = (row_grgr_2 << 16) | row_grgr_2;
} else {
// get 4 neighboring rows
row_grgr_0 = *((uint32_t *) (rowptr_grgr_0 + x - 1));
row_bgbg_1 = *((uint32_t *) (rowptr_bgbg_1 + x - 1));
row_grgr_2 = *((uint32_t *) (rowptr_grgr_2 + x - 1));
}
int r_pixels_0, g_pixels_0, b_pixels_0;
switch (src->pixfmt) {
case PIXFORMAT_BAYER_BGGR: {
#if defined(ARM_MATH_DSP)
int row_02 = __UHADD8(row_grgr_0, row_grgr_2);
int row_1g = __UHADD8(row_bgbg_1, __PKHTB(row_bgbg_1, row_bgbg_1, 16));
r_pixels_0 = __UXTB16(__UHADD8(row_02, __PKHTB(row_02, row_02, 16)));
g_pixels_0 = __UXTB16(__UHADD8(row_1g, __PKHTB(row_1g, row_02, 8)));
b_pixels_0 = __UXTB16_RORn(__UHADD8(row_bgbg_1, __PKHBT(row_bgbg_1, row_bgbg_1, 16)), 8);
#else
int r0 = ((row_grgr_0 & 0xFF) + (row_grgr_2 & 0xFF)) >> 1;
int r2 = (((row_grgr_0 >> 16) & 0xFF) + ((row_grgr_2 >> 16) & 0xFF)) >> 1;
r_pixels_0 = (r2 << 16) | ((r0 + r2) >> 1);
int g0 = (row_grgr_0 >> 8) & 0xFF;
int g1 = (((row_bgbg_1 >> 16) & 0xFF) + (row_bgbg_1 & 0xFF)) >> 1;
int g2 = (row_grgr_2 >> 8) & 0xFF;
g_pixels_0 = (row_bgbg_1 & 0xFF0000) | ((((g0 + g2) >> 1) + g1) >> 1);
int b1 = (((row_bgbg_1 >> 24) & 0xFF) + ((row_bgbg_1 >> 8) & 0xFF)) >> 1;
b_pixels_0 = (b1 << 16) | ((row_bgbg_1 >> 8) & 0xFF);
#endif
break;
}
case PIXFORMAT_BAYER_GBRG: {
#if defined(ARM_MATH_DSP)
int row_02 = __UHADD8(row_grgr_0, row_grgr_2);
int row_1g = __UHADD8(row_bgbg_1, __PKHBT(row_bgbg_1, row_bgbg_1, 16));
r_pixels_0 = __UXTB16_RORn(__UHADD8(row_02, __PKHBT(row_02, row_02, 16)), 8);
g_pixels_0 = __UXTB16_RORn(__UHADD8(row_1g, __PKHBT(row_1g, row_02, 8)), 8);
b_pixels_0 = __UXTB16(__UHADD8(row_bgbg_1, __PKHTB(row_bgbg_1, row_bgbg_1, 16)));
#else
int r0 = (((row_grgr_0 >> 8) & 0xFF) + ((row_grgr_2 >> 8) & 0xFF)) >> 1;
int r2 = (((row_grgr_0 >> 24) & 0xFF) + ((row_grgr_2 >> 24) & 0xFF)) >> 1;
r_pixels_0 = r0 | (((r0 + r2) >> 1) << 16);
int g0 = (row_grgr_0 >> 16) & 0xFF;
int g1 = (((row_bgbg_1 >> 24) & 0xFF) + ((row_bgbg_1 >> 8) & 0xFF)) >> 1;
int g2 = (row_grgr_2 >> 16) & 0xFF;
g_pixels_0 = ((row_bgbg_1 >> 8) & 0xFF) | (((((g0 + g2) >> 1) + g1) >> 1) << 16);
int b1 = (((row_bgbg_1 >> 16) & 0xFF) + (row_bgbg_1 & 0xFF)) >> 1;
b_pixels_0 = b1 | (row_bgbg_1 & 0xFF0000);
#endif
break;
}
case PIXFORMAT_BAYER_GRBG: {
#if defined(ARM_MATH_DSP)
int row_02 = __UHADD8(row_grgr_0, row_grgr_2);
int row_1g = __UHADD8(row_bgbg_1, __PKHBT(row_bgbg_1, row_bgbg_1, 16));
r_pixels_0 = __UXTB16(__UHADD8(row_bgbg_1, __PKHTB(row_bgbg_1, row_bgbg_1, 16)));
g_pixels_0 = __UXTB16_RORn(__UHADD8(row_1g, __PKHBT(row_1g, row_02, 8)), 8);
b_pixels_0 = __UXTB16_RORn(__UHADD8(row_02, __PKHBT(row_02, row_02, 16)), 8);
#else
int r1 = (((row_bgbg_1 >> 16) & 0xFF) + (row_bgbg_1 & 0xFF)) >> 1;
r_pixels_0 = r1 | (row_bgbg_1 & 0xFF0000);
int g0 = (row_grgr_0 >> 16) & 0xFF;
int g1 = (((row_bgbg_1 >> 24) & 0xFF) + ((row_bgbg_1 >> 8) & 0xFF)) >> 1;
int g2 = (row_grgr_2 >> 16) & 0xFF;
g_pixels_0 = ((row_bgbg_1 >> 8) & 0xFF) | (((((g0 + g2) >> 1) + g1) >> 1) << 16);
int b0 = (((row_grgr_0 >> 8) & 0xFF) + ((row_grgr_2 >> 8) & 0xFF)) >> 1;
int b2 = (((row_grgr_0 >> 24) & 0xFF) + ((row_grgr_2 >> 24) & 0xFF)) >> 1;
b_pixels_0 = b0 | (((b0 + b2) >> 1) << 16);
#endif
break;
}
case PIXFORMAT_BAYER_RGGB: {
#if defined(ARM_MATH_DSP)
int row_02 = __UHADD8(row_grgr_0, row_grgr_2);
int row_1g = __UHADD8(row_bgbg_1, __PKHTB(row_bgbg_1, row_bgbg_1, 16));
r_pixels_0 = __UXTB16_RORn(__UHADD8(row_bgbg_1, __PKHBT(row_bgbg_1, row_bgbg_1, 16)), 8);
g_pixels_0 = __UXTB16(__UHADD8(row_1g, __PKHTB(row_1g, row_02, 8)));
b_pixels_0 = __UXTB16(__UHADD8(row_02, __PKHTB(row_02, row_02, 16)));
#else
int r1 = (((row_bgbg_1 >> 24) & 0xFF) + ((row_bgbg_1 >> 8) & 0xFF)) >> 1;
r_pixels_0 = (r1 << 16) | ((row_bgbg_1 >> 8) & 0xFF);
int g0 = (row_grgr_0 >> 8) & 0xFF;
int g1 = (((row_bgbg_1 >> 16) & 0xFF) + (row_bgbg_1 & 0xFF)) >> 1;
int g2 = (row_grgr_2 >> 8) & 0xFF;
g_pixels_0 = (row_bgbg_1 & 0xFF0000) | ((((g0 + g2) >> 1) + g1) >> 1);
int b0 = ((row_grgr_0 & 0xFF) + (row_grgr_2 & 0xFF)) >> 1;
int b2 = (((row_grgr_0 >> 16) & 0xFF) + ((row_grgr_2 >> 16) & 0xFF)) >> 1;
b_pixels_0 = (b2 << 16) | ((b0 + b2) >> 1);
#endif
break;
}
default: {
r_pixels_0 = 0;
g_pixels_0 = 0;
b_pixels_0 = 0;
break;
}
}
switch (pixfmt) {
case PIXFORMAT_BINARY: {
uint32_t *dst_row_ptr_32 = (uint32_t *) dst_row_ptr;
int y0 = ((r_pixels_0 * 38) + (g_pixels_0 * 75) + (b_pixels_0 * 15)) >> 7;
IMAGE_PUT_BINARY_PIXEL_FAST(dst_row_ptr_32, i, (y0 >> 7));
if (x != w_limit) {
IMAGE_PUT_BINARY_PIXEL_FAST(dst_row_ptr_32, i + 1, (y0 >> 23));
}
break;
}
case PIXFORMAT_GRAYSCALE: {
uint8_t *dst_row_ptr_8 = (uint8_t *) dst_row_ptr;
int y0 = ((r_pixels_0 * 38) + (g_pixels_0 * 75) + (b_pixels_0 * 15)) >> 7;
IMAGE_PUT_GRAYSCALE_PIXEL_FAST(dst_row_ptr_8, i, y0);
if (x != w_limit) {
IMAGE_PUT_GRAYSCALE_PIXEL_FAST(dst_row_ptr_8, i + 1, y0 >> 16);
}
break;
}
case PIXFORMAT_RGB565: {
uint16_t *dst_row_ptr_16 = (uint16_t *) dst_row_ptr;
int rgb565_0 = ((r_pixels_0 << 8) & 0xf800f800) |
((g_pixels_0 << 3) & 0x07e007e0) |
((b_pixels_0 >> 3) & 0x001f001f);
if (x == w_limit) {
// just put bottom
IMAGE_PUT_RGB565_PIXEL_FAST(dst_row_ptr_16, i, rgb565_0);
} else {
// put both
*((uint32_t *) (dst_row_ptr_16 + i)) = rgb565_0;
}
break;
}
default: {
break;
}
}
}
} else {
// odd
for (int x = x_start, i = 0; x < x_end; x += 2, i += 2) {
uint32_t row_bgbg_1, row_grgr_2, row_bgbg_3;
// keep pixels in bounds
if (x == 0) {
if (src_w >= 4) {
row_bgbg_1 = *((uint32_t *) rowptr_bgbg_1);
row_grgr_2 = *((uint32_t *) rowptr_grgr_2);
row_bgbg_3 = *((uint32_t *) rowptr_bgbg_3);
} else if (src_w >= 3) {
row_bgbg_1 = *((uint16_t *) rowptr_bgbg_1) | (*(rowptr_bgbg_1 + 2) << 16);
row_grgr_2 = *((uint16_t *) rowptr_grgr_2) | (*(rowptr_grgr_2 + 2) << 16);
row_bgbg_3 = *((uint16_t *) rowptr_bgbg_3) | (*(rowptr_bgbg_3 + 2) << 16);
} else if (src_w >= 2) {
row_bgbg_1 = *((uint16_t *) rowptr_bgbg_1);
row_bgbg_1 = (row_bgbg_1 << 16) | row_bgbg_1;
row_grgr_2 = *((uint16_t *) rowptr_grgr_2);
row_grgr_2 = (row_grgr_2 << 16) | row_grgr_2;
row_bgbg_3 = *((uint16_t *) rowptr_bgbg_3);
row_bgbg_3 = (row_bgbg_3 << 16) | row_bgbg_3;
} else {
row_bgbg_1 = *(rowptr_bgbg_1) * 0x01010101;
row_grgr_2 = *(rowptr_grgr_2) * 0x01010101;
row_bgbg_3 = *(rowptr_bgbg_3) * 0x01010101;
}
// The starting point needs to be offset by 1. The below patterns are actually
// rgrg, gbgb, rgrg, and gbgb. So, shift left and backfill the missing border pixel.
row_bgbg_1 = (row_bgbg_1 << 8) | __UXTB_RORn(row_bgbg_1, 8);
row_grgr_2 = (row_grgr_2 << 8) | __UXTB_RORn(row_grgr_2, 8);
row_bgbg_3 = (row_bgbg_3 << 8) | __UXTB_RORn(row_bgbg_3, 8);
} else if (x == w_limit_m_1) {
row_bgbg_1 = *((uint32_t *) (rowptr_bgbg_1 + x - 2));
row_bgbg_1 = (row_bgbg_1 >> 8) | ((row_bgbg_1 << 8) & 0xff000000);
row_grgr_2 = *((uint32_t *) (rowptr_grgr_2 + x - 2));
row_grgr_2 = (row_grgr_2 >> 8) | ((row_grgr_2 << 8) & 0xff000000);
row_bgbg_3 = *((uint32_t *) (rowptr_bgbg_3 + x - 2));
row_bgbg_3 = (row_bgbg_3 >> 8) | ((row_bgbg_1 << 8) & 0xff000000);
} else if (x >= w_limit) {
row_bgbg_1 = *((uint16_t *) (rowptr_bgbg_1 + x - 1));
row_bgbg_1 = (row_bgbg_1 << 16) | row_bgbg_1;
row_grgr_2 = *((uint16_t *) (rowptr_grgr_2 + x - 1));
row_grgr_2 = (row_grgr_2 << 16) | row_grgr_2;
row_bgbg_3 = *((uint16_t *) (rowptr_bgbg_3 + x - 1));
row_bgbg_3 = (row_bgbg_3 << 16) | row_bgbg_3;
} else {
// get 4 neighboring rows
row_bgbg_1 = *((uint32_t *) (rowptr_bgbg_1 + x - 1));
row_grgr_2 = *((uint32_t *) (rowptr_grgr_2 + x - 1));
row_bgbg_3 = *((uint32_t *) (rowptr_bgbg_3 + x - 1));
}
int r_pixels_1, g_pixels_1, b_pixels_1;
switch (src->pixfmt) {
case PIXFORMAT_BAYER_BGGR: {
#if defined(ARM_MATH_DSP)
int row_13 = __UHADD8(row_bgbg_1, row_bgbg_3);
int row_2g = __UHADD8(row_grgr_2, __PKHBT(row_grgr_2, row_grgr_2, 16));
r_pixels_1 = __UXTB16(__UHADD8(row_grgr_2, __PKHTB(row_grgr_2, row_grgr_2, 16)));
g_pixels_1 = __UXTB16_RORn(__UHADD8(row_2g, __PKHBT(row_2g, row_13, 8)), 8);
b_pixels_1 = __UXTB16_RORn(__UHADD8(row_13, __PKHBT(row_13, row_13, 16)), 8);
#else
int r2 = (((row_grgr_2 >> 16) & 0xFF) + (row_grgr_2 & 0xFF)) >> 1;
r_pixels_1 = (row_grgr_2 & 0xFF0000) | r2;
int g1 = (row_bgbg_1 >> 16) & 0xFF;
int g2 = (((row_grgr_2 >> 24) & 0xFF) + ((row_grgr_2 >> 8) & 0xFF)) >> 1;
int g3 = (row_bgbg_3 >> 16) & 0xFF;
g_pixels_1 = (((((g1 + g3) >> 1) + g2) >> 1) << 16) | ((row_grgr_2 >> 8) & 0xFF);
int b1 = (((row_bgbg_1 >> 8) & 0xFF) + ((row_bgbg_3 >> 8) & 0xFF)) >> 1;
int b3 = (((row_bgbg_1 >> 24) & 0xFF) + ((row_bgbg_3 >> 24) & 0xFF)) >> 1;
b_pixels_1 = (((b1 + b3) >> 1) << 16) | b1;
#endif
break;
}
case PIXFORMAT_BAYER_GBRG: {
#if defined(ARM_MATH_DSP)
int row_13 = __UHADD8(row_bgbg_1, row_bgbg_3);
int row_2g = __UHADD8(row_grgr_2, __PKHTB(row_grgr_2, row_grgr_2, 16));
r_pixels_1 = __UXTB16_RORn(__UHADD8(row_grgr_2, __PKHBT(row_grgr_2, row_grgr_2, 16)), 8);
g_pixels_1 = __UXTB16(__UHADD8(row_2g, __PKHTB(row_2g, row_13, 8)));
b_pixels_1 = __UXTB16(__UHADD8(row_13, __PKHTB(row_13, row_13, 16)));
#else
int r2 = (((row_grgr_2 >> 24) & 0xFF) + ((row_grgr_2 >> 8) & 0xFF)) >> 1;
r_pixels_1 = ((row_grgr_2 >> 8) & 0xFF) | (r2 << 16);
int g1 = (row_bgbg_1 >> 8) & 0xFF;
int g2 = (((row_grgr_2 >> 16) & 0xFF) + (row_grgr_2 & 0xFF)) >> 1;
int g3 = (row_bgbg_3 >> 8) & 0xFF;
g_pixels_1 = ((((g1 + g3) >> 1) + g2) >> 1) | (row_grgr_2 & 0xFF0000);
int b1 = ((row_bgbg_1 & 0xFF) + (row_bgbg_3 & 0xFF)) >> 1;
int b3 = (((row_bgbg_1 >> 16) & 0xFF) + ((row_bgbg_3 >> 16) & 0xFF)) >> 1;
b_pixels_1 = ((b1 + b3) >> 1) | (b3 << 16);
#endif
break;
}
case PIXFORMAT_BAYER_GRBG: {
#if defined(ARM_MATH_DSP)
int row_13 = __UHADD8(row_bgbg_1, row_bgbg_3);
int row_2g = __UHADD8(row_grgr_2, __PKHTB(row_grgr_2, row_grgr_2, 16));
r_pixels_1 = __UXTB16(__UHADD8(row_13, __PKHTB(row_13, row_13, 16)));
g_pixels_1 = __UXTB16(__UHADD8(row_2g, __PKHTB(row_2g, row_13, 8)));
b_pixels_1 = __UXTB16_RORn(__UHADD8(row_grgr_2, __PKHBT(row_grgr_2, row_grgr_2, 16)), 8);
#else
int r1 = ((row_bgbg_1 & 0xFF) + (row_bgbg_3 & 0xFF)) >> 1;
int r3 = (((row_bgbg_1 >> 16) & 0xFF) + ((row_bgbg_3 >> 16) & 0xFF)) >> 1;
r_pixels_1 = ((r1 + r3) >> 1) | (r3 << 16);
int g1 = (row_bgbg_1 >> 8) & 0xFF;
int g2 = (((row_grgr_2 >> 16) & 0xFF) + (row_grgr_2 & 0xFF)) >> 1;
int g3 = (row_bgbg_3 >> 8) & 0xFF;
g_pixels_1 = ((((g1 + g3) >> 1) + g2) >> 1) | (row_grgr_2 & 0xFF0000);
int b2 = (((row_grgr_2 >> 24) & 0xFF) + ((row_grgr_2 >> 8) & 0xFF)) >> 1;
b_pixels_1 = ((row_grgr_2 >> 8) & 0xFF) | (b2 << 16);
#endif
break;
}
case PIXFORMAT_BAYER_RGGB: {
#if defined(ARM_MATH_DSP)
int row_13 = __UHADD8(row_bgbg_1, row_bgbg_3);
int row_2g = __UHADD8(row_grgr_2, __PKHBT(row_grgr_2, row_grgr_2, 16));
r_pixels_1 = __UXTB16_RORn(__UHADD8(row_13, __PKHBT(row_13, row_13, 16)), 8);
g_pixels_1 = __UXTB16_RORn(__UHADD8(row_2g, __PKHBT(row_2g, row_13, 8)), 8);
b_pixels_1 = __UXTB16(__UHADD8(row_grgr_2, __PKHTB(row_grgr_2, row_grgr_2, 16)));
#else
int r1 = (((row_bgbg_1 >> 8) & 0xFF) + ((row_bgbg_3 >> 8) & 0xFF)) >> 1;
int r3 = (((row_bgbg_1 >> 24) & 0xFF) + ((row_bgbg_3 >> 24) & 0xFF)) >> 1;
r_pixels_1 = (((r1 + r3) >> 1) << 16) | r1;
int g1 = (row_bgbg_1 >> 16) & 0xFF;
int g2 = (((row_grgr_2 >> 24) & 0xFF) + ((row_grgr_2 >> 8) & 0xFF)) >> 1;
int g3 = (row_bgbg_3 >> 16) & 0xFF;
g_pixels_1 = (((((g1 + g3) >> 1) + g2) >> 1) << 16) | ((row_grgr_2 >> 8) & 0xFF);
int b2 = (((row_grgr_2 >> 16) & 0xFF) + (row_grgr_2 & 0xFF)) >> 1;
b_pixels_1 = (row_grgr_2 & 0xFF0000) | b2;
#endif
break;
}
default: {
r_pixels_1 = 0;
g_pixels_1 = 0;
b_pixels_1 = 0;
break;
}
}
switch (pixfmt) {
case PIXFORMAT_BINARY: {
uint32_t *dst_row_ptr_32 = (uint32_t *) dst_row_ptr;
int y1 = ((r_pixels_1 * 38) + (g_pixels_1 * 75) + (b_pixels_1 * 15)) >> 7;
IMAGE_PUT_BINARY_PIXEL_FAST(dst_row_ptr_32, i, (y1 >> 7));
if (x != w_limit) {
IMAGE_PUT_BINARY_PIXEL_FAST(dst_row_ptr_32, i + 1, (y1 >> 23));
}
break;
}
case PIXFORMAT_GRAYSCALE: {
uint8_t *dst_row_ptr_8 = (uint8_t *) dst_row_ptr;
int y1 = ((r_pixels_1 * 38) + (g_pixels_1 * 75) + (b_pixels_1 * 15)) >> 7;
IMAGE_PUT_GRAYSCALE_PIXEL_FAST(dst_row_ptr_8, i, y1);
if (x != w_limit) {
IMAGE_PUT_GRAYSCALE_PIXEL_FAST(dst_row_ptr_8, i + 1, y1 >> 16);
}
break;
}
case PIXFORMAT_RGB565: {
uint16_t *dst_row_ptr_16 = (uint16_t *) dst_row_ptr;
int rgb565_1 = ((r_pixels_1 << 8) & 0xf800f800) |
((g_pixels_1 << 3) & 0x07e007e0) |
((b_pixels_1 >> 3) & 0x001f001f);
if (x == w_limit) {
// just put bottom
IMAGE_PUT_RGB565_PIXEL_FAST(dst_row_ptr_16, i, rgb565_1);
} else {
// put both
*((uint32_t *) (dst_row_ptr_16 + i)) = rgb565_1;
}
break;
}
default: {
break;
}
}
}
}
}
// Does no bounds checking on the destination. Destination must be mutable.
void imlib_debayer_image(image_t *dst, image_t *src) {
int src_w = src->w, w_limit = src_w - 1, w_limit_m_1 = w_limit - 1;
int src_h = src->h, h_limit = src_h - 1, h_limit_m_1 = h_limit - 1;
// If the image is an odd height this will go for the last loop and we drop the last row.
for (int y = 0; y < src_h; y += 2) {
void *row_ptr_e = NULL, *row_ptr_o = NULL;
switch (dst->pixfmt) {
case PIXFORMAT_BINARY: {
row_ptr_e = IMAGE_COMPUTE_BINARY_PIXEL_ROW_PTR(dst, y);
row_ptr_o = IMAGE_COMPUTE_BINARY_PIXEL_ROW_PTR(dst, y + 1);
break;
}
case PIXFORMAT_GRAYSCALE: {
row_ptr_e = IMAGE_COMPUTE_GRAYSCALE_PIXEL_ROW_PTR(dst, y);
row_ptr_o = IMAGE_COMPUTE_GRAYSCALE_PIXEL_ROW_PTR(dst, y + 1);
break;
}
case PIXFORMAT_RGB565: {
row_ptr_e = IMAGE_COMPUTE_RGB565_PIXEL_ROW_PTR(dst, y);
row_ptr_o = IMAGE_COMPUTE_RGB565_PIXEL_ROW_PTR(dst, y + 1);
break;
}
}
uint8_t *rowptr_grgr_0, *rowptr_bgbg_1, *rowptr_grgr_2, *rowptr_bgbg_3;
// keep row pointers in bounds
if (y == 0) {
rowptr_bgbg_1 = src->data;
rowptr_grgr_2 = rowptr_bgbg_1 + ((src_h >= 2) ? src_w : 0);
rowptr_bgbg_3 = rowptr_bgbg_1 + ((src_h >= 3) ? (src_w * 2) : 0);
rowptr_grgr_0 = rowptr_grgr_2;
} else if (y == h_limit_m_1) {
rowptr_grgr_0 = src->data + ((y - 1) * src_w);
rowptr_bgbg_1 = rowptr_grgr_0 + src_w;
rowptr_grgr_2 = rowptr_bgbg_1 + src_w;
rowptr_bgbg_3 = rowptr_bgbg_1;
} else if (y >= h_limit) {
rowptr_grgr_0 = src->data + ((y - 1) * src_w);
rowptr_bgbg_1 = rowptr_grgr_0 + src_w;
rowptr_grgr_2 = rowptr_grgr_0;
rowptr_bgbg_3 = rowptr_bgbg_1;
} else {
// get 4 neighboring rows
rowptr_grgr_0 = src->data + ((y - 1) * src_w);
rowptr_bgbg_1 = rowptr_grgr_0 + src_w;
rowptr_grgr_2 = rowptr_bgbg_1 + src_w;
rowptr_bgbg_3 = rowptr_grgr_2 + src_w;
}
// If the image is an odd width this will go for the last loop and we drop the last column.
for (int x = 0; x < src_w; x += 2) {
uint32_t row_grgr_0, row_bgbg_1, row_grgr_2, row_bgbg_3;
// keep pixels in bounds
if (x == 0) {
if (src_w >= 4) {
row_grgr_0 = *((uint32_t *) rowptr_grgr_0);
row_bgbg_1 = *((uint32_t *) rowptr_bgbg_1);
row_grgr_2 = *((uint32_t *) rowptr_grgr_2);
row_bgbg_3 = *((uint32_t *) rowptr_bgbg_3);
} else if (src_w >= 3) {
row_grgr_0 = *((uint16_t *) rowptr_grgr_0) | (*(rowptr_grgr_0 + 2) << 16);
row_bgbg_1 = *((uint16_t *) rowptr_bgbg_1) | (*(rowptr_bgbg_1 + 2) << 16);
row_grgr_2 = *((uint16_t *) rowptr_grgr_2) | (*(rowptr_grgr_2 + 2) << 16);
row_bgbg_3 = *((uint16_t *) rowptr_bgbg_3) | (*(rowptr_bgbg_3 + 2) << 16);
} else if (src_w >= 2) {
row_grgr_0 = *((uint16_t *) rowptr_grgr_0);
row_grgr_0 = (row_grgr_0 << 16) | row_grgr_0;
row_bgbg_1 = *((uint16_t *) rowptr_bgbg_1);
row_bgbg_1 = (row_bgbg_1 << 16) | row_bgbg_1;
row_grgr_2 = *((uint16_t *) rowptr_grgr_2);
row_grgr_2 = (row_grgr_2 << 16) | row_grgr_2;
row_bgbg_3 = *((uint16_t *) rowptr_bgbg_3);
row_bgbg_3 = (row_bgbg_3 << 16) | row_bgbg_3;
} else {
row_grgr_0 = *(rowptr_grgr_0) * 0x01010101;
row_bgbg_1 = *(rowptr_bgbg_1) * 0x01010101;
row_grgr_2 = *(rowptr_grgr_2) * 0x01010101;
row_bgbg_3 = *(rowptr_bgbg_3) * 0x01010101;
}
// The starting point needs to be offset by 1. The below patterns are actually
// rgrg, gbgb, rgrg, and gbgb. So, shift left and backfill the missing border pixel.
row_grgr_0 = (row_grgr_0 << 8) | __UXTB_RORn(row_grgr_0, 8);
row_bgbg_1 = (row_bgbg_1 << 8) | __UXTB_RORn(row_bgbg_1, 8);
row_grgr_2 = (row_grgr_2 << 8) | __UXTB_RORn(row_grgr_2, 8);
row_bgbg_3 = (row_bgbg_3 << 8) | __UXTB_RORn(row_bgbg_3, 8);
} else if (x == w_limit_m_1) {
row_grgr_0 = *((uint32_t *) (rowptr_grgr_0 + x - 2));
row_grgr_0 = (row_grgr_0 >> 8) | ((row_grgr_0 << 8) & 0xff000000);
row_bgbg_1 = *((uint32_t *) (rowptr_bgbg_1 + x - 2));
row_bgbg_1 = (row_bgbg_1 >> 8) | ((row_bgbg_1 << 8) & 0xff000000);
row_grgr_2 = *((uint32_t *) (rowptr_grgr_2 + x - 2));
row_grgr_2 = (row_grgr_2 >> 8) | ((row_grgr_2 << 8) & 0xff000000);
row_bgbg_3 = *((uint32_t *) (rowptr_bgbg_3 + x - 2));
row_bgbg_3 = (row_bgbg_3 >> 8) | ((row_bgbg_1 << 8) & 0xff000000);
} else if (x >= w_limit) {
row_grgr_0 = *((uint16_t *) (rowptr_grgr_0 + x - 1));
row_grgr_0 = (row_grgr_0 << 16) | row_grgr_0;
row_bgbg_1 = *((uint16_t *) (rowptr_bgbg_1 + x - 1));
row_bgbg_1 = (row_bgbg_1 << 16) | row_bgbg_1;
row_grgr_2 = *((uint16_t *) (rowptr_grgr_2 + x - 1));
row_grgr_2 = (row_grgr_2 << 16) | row_grgr_2;
row_bgbg_3 = *((uint16_t *) (rowptr_bgbg_3 + x - 1));
row_bgbg_3 = (row_bgbg_3 << 16) | row_bgbg_3;
} else {
// get 4 neighboring rows
row_grgr_0 = *((uint32_t *) (rowptr_grgr_0 + x - 1));
row_bgbg_1 = *((uint32_t *) (rowptr_bgbg_1 + x - 1));
row_grgr_2 = *((uint32_t *) (rowptr_grgr_2 + x - 1));
row_bgbg_3 = *((uint32_t *) (rowptr_bgbg_3 + x - 1));
}
int r_pixels_0, g_pixels_0, b_pixels_0;
switch (src->pixfmt) {
case PIXFORMAT_BAYER_BGGR: {
#if defined(ARM_MATH_DSP)
int row_02 = __UHADD8(row_grgr_0, row_grgr_2);
int row_1g = __UHADD8(row_bgbg_1, __PKHTB(row_bgbg_1, row_bgbg_1, 16));
r_pixels_0 = __UXTB16(__UHADD8(row_02, __PKHTB(row_02, row_02, 16)));
g_pixels_0 = __UXTB16(__UHADD8(row_1g, __PKHTB(row_1g, row_02, 8)));
b_pixels_0 = __UXTB16_RORn(__UHADD8(row_bgbg_1, __PKHBT(row_bgbg_1, row_bgbg_1, 16)), 8);
#else
int r0 = ((row_grgr_0 & 0xFF) + (row_grgr_2 & 0xFF)) >> 1;
int r2 = (((row_grgr_0 >> 16) & 0xFF) + ((row_grgr_2 >> 16) & 0xFF)) >> 1;
r_pixels_0 = (r2 << 16) | ((r0 + r2) >> 1);
int g0 = (row_grgr_0 >> 8) & 0xFF;
int g1 = (((row_bgbg_1 >> 16) & 0xFF) + (row_bgbg_1 & 0xFF)) >> 1;
int g2 = (row_grgr_2 >> 8) & 0xFF;
g_pixels_0 = (row_bgbg_1 & 0xFF0000) | ((((g0 + g2) >> 1) + g1) >> 1);
int b1 = (((row_bgbg_1 >> 24) & 0xFF) + ((row_bgbg_1 >> 8) & 0xFF)) >> 1;
b_pixels_0 = (b1 << 16) | ((row_bgbg_1 >> 8) & 0xFF);
#endif
break;
}
case PIXFORMAT_BAYER_GBRG: {
#if defined(ARM_MATH_DSP)
int row_02 = __UHADD8(row_grgr_0, row_grgr_2);
int row_1g = __UHADD8(row_bgbg_1, __PKHBT(row_bgbg_1, row_bgbg_1, 16));
r_pixels_0 = __UXTB16_RORn(__UHADD8(row_02, __PKHBT(row_02, row_02, 16)), 8);
g_pixels_0 = __UXTB16_RORn(__UHADD8(row_1g, __PKHBT(row_1g, row_02, 8)), 8);
b_pixels_0 = __UXTB16(__UHADD8(row_bgbg_1, __PKHTB(row_bgbg_1, row_bgbg_1, 16)));
#else
int r0 = (((row_grgr_0 >> 8) & 0xFF) + ((row_grgr_2 >> 8) & 0xFF)) >> 1;
int r2 = (((row_grgr_0 >> 24) & 0xFF) + ((row_grgr_2 >> 24) & 0xFF)) >> 1;
r_pixels_0 = r0 | (((r0 + r2) >> 1) << 16);
int g0 = (row_grgr_0 >> 16) & 0xFF;
int g1 = (((row_bgbg_1 >> 24) & 0xFF) + ((row_bgbg_1 >> 8) & 0xFF)) >> 1;
int g2 = (row_grgr_2 >> 16) & 0xFF;
g_pixels_0 = ((row_bgbg_1 >> 8) & 0xFF) | (((((g0 + g2) >> 1) + g1) >> 1) << 16);
int b1 = (((row_bgbg_1 >> 16) & 0xFF) + (row_bgbg_1 & 0xFF)) >> 1;
b_pixels_0 = b1 | (row_bgbg_1 & 0xFF0000);
#endif
break;
}
case PIXFORMAT_BAYER_GRBG: {
#if defined(ARM_MATH_DSP)
int row_02 = __UHADD8(row_grgr_0, row_grgr_2);
int row_1g = __UHADD8(row_bgbg_1, __PKHBT(row_bgbg_1, row_bgbg_1, 16));
r_pixels_0 = __UXTB16(__UHADD8(row_bgbg_1, __PKHTB(row_bgbg_1, row_bgbg_1, 16)));
g_pixels_0 = __UXTB16_RORn(__UHADD8(row_1g, __PKHBT(row_1g, row_02, 8)), 8);
b_pixels_0 = __UXTB16_RORn(__UHADD8(row_02, __PKHBT(row_02, row_02, 16)), 8);
#else
int r1 = (((row_bgbg_1 >> 16) & 0xFF) + (row_bgbg_1 & 0xFF)) >> 1;
r_pixels_0 = r1 | (row_bgbg_1 & 0xFF0000);
int g0 = (row_grgr_0 >> 16) & 0xFF;
int g1 = (((row_bgbg_1 >> 24) & 0xFF) + ((row_bgbg_1 >> 8) & 0xFF)) >> 1;
int g2 = (row_grgr_2 >> 16) & 0xFF;
g_pixels_0 = ((row_bgbg_1 >> 8) & 0xFF) | (((((g0 + g2) >> 1) + g1) >> 1) << 16);
int b0 = (((row_grgr_0 >> 8) & 0xFF) + ((row_grgr_2 >> 8) & 0xFF)) >> 1;
int b2 = (((row_grgr_0 >> 24) & 0xFF) + ((row_grgr_2 >> 24) & 0xFF)) >> 1;
b_pixels_0 = b0 | (((b0 + b2) >> 1) << 16);
#endif
break;
}
case PIXFORMAT_BAYER_RGGB: {
#if defined(ARM_MATH_DSP)
int row_02 = __UHADD8(row_grgr_0, row_grgr_2);
int row_1g = __UHADD8(row_bgbg_1, __PKHTB(row_bgbg_1, row_bgbg_1, 16));
r_pixels_0 = __UXTB16_RORn(__UHADD8(row_bgbg_1, __PKHBT(row_bgbg_1, row_bgbg_1, 16)), 8);
g_pixels_0 = __UXTB16(__UHADD8(row_1g, __PKHTB(row_1g, row_02, 8)));
b_pixels_0 = __UXTB16(__UHADD8(row_02, __PKHTB(row_02, row_02, 16)));
#else
int r1 = (((row_bgbg_1 >> 24) & 0xFF) + ((row_bgbg_1 >> 8) & 0xFF)) >> 1;
r_pixels_0 = (r1 << 16) | ((row_bgbg_1 >> 8) & 0xFF);
int g0 = (row_grgr_0 >> 8) & 0xFF;
int g1 = (((row_bgbg_1 >> 16) & 0xFF) + (row_bgbg_1 & 0xFF)) >> 1;
int g2 = (row_grgr_2 >> 8) & 0xFF;
g_pixels_0 = (row_bgbg_1 & 0xFF0000) | ((((g0 + g2) >> 1) + g1) >> 1);
int b0 = ((row_grgr_0 & 0xFF) + (row_grgr_2 & 0xFF)) >> 1;
int b2 = (((row_grgr_0 >> 16) & 0xFF) + ((row_grgr_2 >> 16) & 0xFF)) >> 1;
b_pixels_0 = (b2 << 16) | ((b0 + b2) >> 1);
#endif
break;
}
default: {
r_pixels_0 = 0;
g_pixels_0 = 0;
b_pixels_0 = 0;
break;
}
}
switch (dst->pixfmt) {
case PIXFORMAT_BINARY: {
uint32_t *row_ptr_e_32 = (uint32_t *) row_ptr_e;
int y0 = ((r_pixels_0 * 38) + (g_pixels_0 * 75) + (b_pixels_0 * 15)) >> 7;
IMAGE_PUT_BINARY_PIXEL_FAST(row_ptr_e_32, x, (y0 >> 7));
if (x != w_limit) {
IMAGE_PUT_BINARY_PIXEL_FAST(row_ptr_e_32, x + 1, (y0 >> 23));
}
break;
}
case PIXFORMAT_GRAYSCALE: {
uint8_t *row_ptr_e_8 = (uint8_t *) row_ptr_e;
int y0 = ((r_pixels_0 * 38) + (g_pixels_0 * 75) + (b_pixels_0 * 15)) >> 7;
IMAGE_PUT_GRAYSCALE_PIXEL_FAST(row_ptr_e_8, x, y0);
if (x != w_limit) {
IMAGE_PUT_GRAYSCALE_PIXEL_FAST(row_ptr_e_8, x + 1, y0 >> 16);
}
break;
}
case PIXFORMAT_RGB565: {
uint16_t *row_ptr_e_16 = (uint16_t *) row_ptr_e;
int rgb565_0 = ((r_pixels_0 << 8) & 0xf800f800) |
((g_pixels_0 << 3) & 0x07e007e0) |
((b_pixels_0 >> 3) & 0x001f001f);
if (x == w_limit) {
// just put bottom
IMAGE_PUT_RGB565_PIXEL_FAST(row_ptr_e_16, x, rgb565_0);
} else {
// put both
*((uint32_t *) (row_ptr_e_16 + x)) = rgb565_0;
}
break;
}
}
if (y == h_limit) {
continue;
}
int r_pixels_1, g_pixels_1, b_pixels_1;
switch (src->pixfmt) {
case PIXFORMAT_BAYER_BGGR: {
#if defined(ARM_MATH_DSP)
int row_13 = __UHADD8(row_bgbg_1, row_bgbg_3);
int row_2g = __UHADD8(row_grgr_2, __PKHBT(row_grgr_2, row_grgr_2, 16));
r_pixels_1 = __UXTB16(__UHADD8(row_grgr_2, __PKHTB(row_grgr_2, row_grgr_2, 16)));
g_pixels_1 = __UXTB16_RORn(__UHADD8(row_2g, __PKHBT(row_2g, row_13, 8)), 8);
b_pixels_1 = __UXTB16_RORn(__UHADD8(row_13, __PKHBT(row_13, row_13, 16)), 8);
#else
int r2 = (((row_grgr_2 >> 16) & 0xFF) + (row_grgr_2 & 0xFF)) >> 1;
r_pixels_1 = (row_grgr_2 & 0xFF0000) | r2;
int g1 = (row_bgbg_1 >> 16) & 0xFF;
int g2 = (((row_grgr_2 >> 24) & 0xFF) + ((row_grgr_2 >> 8) & 0xFF)) >> 1;
int g3 = (row_bgbg_3 >> 16) & 0xFF;
g_pixels_1 = (((((g1 + g3) >> 1) + g2) >> 1) << 16) | ((row_grgr_2 >> 8) & 0xFF);
int b1 = (((row_bgbg_1 >> 8) & 0xFF) + ((row_bgbg_3 >> 8) & 0xFF)) >> 1;
int b3 = (((row_bgbg_1 >> 24) & 0xFF) + ((row_bgbg_3 >> 24) & 0xFF)) >> 1;
b_pixels_1 = (((b1 + b3) >> 1) << 16) | b1;
#endif
break;
}
case PIXFORMAT_BAYER_GBRG: {
#if defined(ARM_MATH_DSP)
int row_13 = __UHADD8(row_bgbg_1, row_bgbg_3);
int row_2g = __UHADD8(row_grgr_2, __PKHTB(row_grgr_2, row_grgr_2, 16));
r_pixels_1 = __UXTB16_RORn(__UHADD8(row_grgr_2, __PKHBT(row_grgr_2, row_grgr_2, 16)), 8);
g_pixels_1 = __UXTB16(__UHADD8(row_2g, __PKHTB(row_2g, row_13, 8)));
b_pixels_1 = __UXTB16(__UHADD8(row_13, __PKHTB(row_13, row_13, 16)));
#else
int r2 = (((row_grgr_2 >> 24) & 0xFF) + ((row_grgr_2 >> 8) & 0xFF)) >> 1;
r_pixels_1 = ((row_grgr_2 >> 8) & 0xFF) | (r2 << 16);
int g1 = (row_bgbg_1 >> 8) & 0xFF;
int g2 = (((row_grgr_2 >> 16) & 0xFF) + (row_grgr_2 & 0xFF)) >> 1;
int g3 = (row_bgbg_3 >> 8) & 0xFF;
g_pixels_1 = ((((g1 + g3) >> 1) + g2) >> 1) | (row_grgr_2 & 0xFF0000);
int b1 = ((row_bgbg_1 & 0xFF) + (row_bgbg_3 & 0xFF)) >> 1;
int b3 = (((row_bgbg_1 >> 16) & 0xFF) + ((row_bgbg_3 >> 16) & 0xFF)) >> 1;
b_pixels_1 = ((b1 + b3) >> 1) | (b3 << 16);
#endif
break;
}
case PIXFORMAT_BAYER_GRBG: {
#if defined(ARM_MATH_DSP)
int row_13 = __UHADD8(row_bgbg_1, row_bgbg_3);
int row_2g = __UHADD8(row_grgr_2, __PKHTB(row_grgr_2, row_grgr_2, 16));
r_pixels_1 = __UXTB16(__UHADD8(row_13, __PKHTB(row_13, row_13, 16)));
g_pixels_1 = __UXTB16(__UHADD8(row_2g, __PKHTB(row_2g, row_13, 8)));
b_pixels_1 = __UXTB16_RORn(__UHADD8(row_grgr_2, __PKHBT(row_grgr_2, row_grgr_2, 16)), 8);
#else
int r1 = ((row_bgbg_1 & 0xFF) + (row_bgbg_3 & 0xFF)) >> 1;
int r3 = (((row_bgbg_1 >> 16) & 0xFF) + ((row_bgbg_3 >> 16) & 0xFF)) >> 1;
r_pixels_1 = ((r1 + r3) >> 1) | (r3 << 16);
int g1 = (row_bgbg_1 >> 8) & 0xFF;
int g2 = (((row_grgr_2 >> 16) & 0xFF) + (row_grgr_2 & 0xFF)) >> 1;
int g3 = (row_bgbg_3 >> 8) & 0xFF;
g_pixels_1 = ((((g1 + g3) >> 1) + g2) >> 1) | (row_grgr_2 & 0xFF0000);
int b2 = (((row_grgr_2 >> 24) & 0xFF) + ((row_grgr_2 >> 8) & 0xFF)) >> 1;
b_pixels_1 = ((row_grgr_2 >> 8) & 0xFF) | (b2 << 16);
#endif
break;
}
case PIXFORMAT_BAYER_RGGB: {
#if defined(ARM_MATH_DSP)
int row_13 = __UHADD8(row_bgbg_1, row_bgbg_3);
int row_2g = __UHADD8(row_grgr_2, __PKHBT(row_grgr_2, row_grgr_2, 16));
r_pixels_1 = __UXTB16_RORn(__UHADD8(row_13, __PKHBT(row_13, row_13, 16)), 8);
g_pixels_1 = __UXTB16_RORn(__UHADD8(row_2g, __PKHBT(row_2g, row_13, 8)), 8);
b_pixels_1 = __UXTB16(__UHADD8(row_grgr_2, __PKHTB(row_grgr_2, row_grgr_2, 16)));
#else
int r1 = (((row_bgbg_1 >> 8) & 0xFF) + ((row_bgbg_3 >> 8) & 0xFF)) >> 1;
int r3 = (((row_bgbg_1 >> 24) & 0xFF) + ((row_bgbg_3 >> 24) & 0xFF)) >> 1;
r_pixels_1 = (((r1 + r3) >> 1) << 16) | r1;
int g1 = (row_bgbg_1 >> 16) & 0xFF;
int g2 = (((row_grgr_2 >> 24) & 0xFF) + ((row_grgr_2 >> 8) & 0xFF)) >> 1;
int g3 = (row_bgbg_3 >> 16) & 0xFF;
g_pixels_1 = (((((g1 + g3) >> 1) + g2) >> 1) << 16) | ((row_grgr_2 >> 8) & 0xFF);
int b2 = (((row_grgr_2 >> 16) & 0xFF) + (row_grgr_2 & 0xFF)) >> 1;
b_pixels_1 = (row_grgr_2 & 0xFF0000) | b2;
#endif
break;
}
default: {
r_pixels_1 = 0;
g_pixels_1 = 0;
b_pixels_1 = 0;
break;
}
}
switch (dst->pixfmt) {
case PIXFORMAT_BINARY: {
uint32_t *row_ptr_o_32 = (uint32_t *) row_ptr_o;
int y1 = ((r_pixels_1 * 38) + (g_pixels_1 * 75) + (b_pixels_1 * 15)) >> 7;
IMAGE_PUT_BINARY_PIXEL_FAST(row_ptr_o_32, x, (y1 >> 7));
if (x != w_limit) {
IMAGE_PUT_BINARY_PIXEL_FAST(row_ptr_o_32, x + 1, (y1 >> 23));
}
break;
}
case PIXFORMAT_GRAYSCALE: {
uint8_t *row_ptr_o_8 = (uint8_t *) row_ptr_o;
int y1 = ((r_pixels_1 * 38) + (g_pixels_1 * 75) + (b_pixels_1 * 15)) >> 7;
IMAGE_PUT_GRAYSCALE_PIXEL_FAST(row_ptr_o_8, x, y1);
if (x != w_limit) {
IMAGE_PUT_GRAYSCALE_PIXEL_FAST(row_ptr_o_8, x + 1, y1 >> 16);
}
break;
}
case PIXFORMAT_RGB565: {
uint16_t *row_ptr_o_16 = (uint16_t *) row_ptr_o;
int rgb565_1 = ((r_pixels_1 << 8) & 0xf800f800) |
((g_pixels_1 << 3) & 0x07e007e0) |
((b_pixels_1 >> 3) & 0x001f001f);
if (x == w_limit) {
// just put bottom
IMAGE_PUT_RGB565_PIXEL_FAST(row_ptr_o_16, x, rgb565_1);
} else {
// put both
*((uint32_t *) (row_ptr_o_16 + x)) = rgb565_1;
}
break;
}
}
}
}
}
| 2.4375 | 2 |
2024-11-18T19:02:37.880524+00:00 | 2018-11-19T18:45:55 | 75af4e0ec57b02018067f35d40edc1ac8fef644b | {
"blob_id": "75af4e0ec57b02018067f35d40edc1ac8fef644b",
"branch_name": "refs/heads/master",
"committer_date": "2018-11-19T18:45:55",
"content_id": "e305fd6455703f66a1e56dd0eda3f2bcfc5247eb",
"detected_licenses": [
"MIT"
],
"directory_id": "6d67122963c0f89d5c0bc9beede5980ca25bc18d",
"extension": "h",
"filename": "spawn_bag.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 131651029,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1191,
"license": "MIT",
"license_type": "permissive",
"path": "/engine/include/spawn_bag.h",
"provenance": "stackv2-0058.json.gz:157084",
"repo_name": "Seng3694/Tetris",
"revision_date": "2018-11-19T18:45:55",
"revision_id": "b8db8049c0a98dfb700f138d900c5ac97d44390e",
"snapshot_id": "5255d1d8c5fde0cf6bbd99de25e51d3c969ef20a",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Seng3694/Tetris/b8db8049c0a98dfb700f138d900c5ac97d44390e/engine/include/spawn_bag.h",
"visit_date": "2020-04-05T18:16:23.429867"
} | stackv2 | #ifndef ENGINE_SPAWN_BAG_H
#define ENGINE_SPAWN_BAG_H
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include "tetromino_type.h"
#include "common.h"
/**
* \brief A struct which holds 7 different tetromino types in a random order.
* http://tetris.wikia.com/wiki/Random_Generator
* \sa SpawnBag_Create()
* \sa SpawnBag_Destroy()
* \sa SpawnBag_Refill()
* \sa SpawnBag_GetNext()
*/
typedef struct
{
sbyte data[TETROMINO_TYPE_COUNT];
byte index;
} SpawnBag;
/**
* \brief Creates a new bag.
* \return The created bag.
* \sa SpawnBag_Destroy()
*/
SpawnBag* SpawnBag_Create(void);
/**
* \brief Destroys a new bag.
* \param bag The bag to destroy.
* \sa SpawnBag_Create()
*/
void SpawnBag_Destroy(SpawnBag* bag);
/**
* \brief Refills the bag with the 7 different types in a random order.
* \param bag The bag to refill.
*/
void SpawnBag_Refill(SpawnBag* bag);
/**
* \brief Returns the next type from the bag.
* If there are no more types left, SpawnBag_Refill() will be called to generate new ones.
* \param bag The bag to refill.
* \return A tetromino type.
* \sa SpawnBag_Refill()
*/
sbyte SpawnBag_GetNext(SpawnBag* bag);
#endif
| 2.578125 | 3 |
2024-11-18T19:02:37.949379+00:00 | 2020-12-30T02:50:13 | 343e0322e5454a68985e1f69195e636a687c70b7 | {
"blob_id": "343e0322e5454a68985e1f69195e636a687c70b7",
"branch_name": "refs/heads/master",
"committer_date": "2020-12-30T02:50:13",
"content_id": "6d1b40d859c1f526c8ae77f4672d05db1d6766ee",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "a76e7a06cc1ad0e17f63fce5a7a1125f970b1edd",
"extension": "c",
"filename": "demo4_int.c",
"fork_events_count": 15,
"gha_created_at": "2020-03-10T17:04:02",
"gha_event_created_at": "2020-04-24T00:00:27",
"gha_language": "C",
"gha_license_id": null,
"github_id": 246359776,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2275,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/codes/atmega16/demo4_int.c",
"provenance": "stackv2-0058.json.gz:157212",
"repo_name": "uLatinaPma-Mechatronics/Circuitos-4",
"revision_date": "2020-12-30T02:50:13",
"revision_id": "e732769d2b185627937eb54ffa53afce739b39b2",
"snapshot_id": "fc53b90536a36e40c292d9c45732a2d12e41c23a",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/uLatinaPma-Mechatronics/Circuitos-4/e732769d2b185627937eb54ffa53afce739b39b2/codes/atmega16/demo4_int.c",
"visit_date": "2021-03-09T17:01:43.877476"
} | stackv2 | /*
* atmega16_demo4_int.c
*
* Created: 12/15/2020 3:44:12 p. m.
* Author : pangoro24
*/
#define F_CPU 1000000UL
#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/delay.h>
volatile unsigned int analogResult = 0;
/*Interrupt Service Routine for INT0*/
ISR(INT0_vect)
{
PORTC|=(1<<PC3); /* Toggle PORTC */
_delay_ms(50); /* Software debouncing control delay */
}
ISR(INT1_vect)
{
PORTC|=(1<<PC4); /* Toggle PORTC */
_delay_ms(50); /* Software debouncing control delay */
}
ISR(INT2_vect)
{
PORTC|=(1<<PC7); /* Toggle PORTC */
_delay_ms(50); /* Software debouncing control delay */
}
ISR(ADC_vect) //interrupt function
{
//The ADC generates a 10-bit result
//which can be found in the ADC Result Registers, ADCH and ADCL
unsigned int binary_weighted_voltage_low = ADCL; //Read 8 low bits first
unsigned int binary_weighted_voltage_high = ((unsigned int)(ADCH << 8)); //Read 2 high bits
analogResult = binary_weighted_voltage_low | binary_weighted_voltage_high;
}
int main(void)
{
DDRC |= (1<<PC3)|(1<<PC4) |(1<<PC7); /* Set some PORT C as*/
PORTC |= 0x00; // Set pines at LOW
DDRD |= (1<<PD6);
PORTD &= ~(1<<PD6);
DDRA &= ~(1<<PA1); //Set the Data Direction Register for the POT to input
GICR |= (1<<INT1) | (1<<INT0) | (1<<INT2); /* Enable INTS*/
MCUCR |= (1<<ISC11) | (1<<ISC10) | (1<<ISC01) | (1<<ISC00); /* Trigger */
MCUCSR |= (1<<ISC2);
GIFR |= (1<<INTF1) | (1<<INTF0) | (1<<INTF2);
ADMUX =
(0 << REFS1) | (1 << REFS0) | // Sets ref. voltage to VCC
(0 << ADLAR) | // 0: right adjust, 1: left adjust
(0 << MUX4) | (0 << MUX3) | (0 << MUX2) | (0 << MUX1) | (1 << MUX0); // MUX bits ADC1; 0010, PA1
ADCSRA =
(1 << ADEN) | // Enable ADC
(1 << ADSC) | // Start Conversion (at setup)
(1 << ADATE) | // ENABLE Auto trigger
(0 << ADIF) | //
(1 << ADIE) | // ENABLE ADC interrupt flag
(1 << ADPS2) | (1 << ADPS1) | (0 << ADPS0); // set prescaler to 64
SFIOR =
(0<<ADTS2)| //Free running mode bit 2
(0<<ADTS1)| //Free running mode bit 1
(0<<ADTS0); //Free running mode bit 0
sei(); /* Enable Global Interrupt */
while(1){
//PORTD |= (1 << PD6);
if(analogResult>=800){
PORTD ^= (1 << PD6);
_delay_ms(200);
}
}
}
| 2.828125 | 3 |
2024-11-18T19:02:40.746345+00:00 | 2022-01-17T05:42:17 | 9a4ee975deb165edbf846e143e87eb9966d16a8f | {
"blob_id": "9a4ee975deb165edbf846e143e87eb9966d16a8f",
"branch_name": "refs/heads/master",
"committer_date": "2022-01-17T05:42:17",
"content_id": "f2f5022858e48adad0be0b0e0aef00a88509a9b1",
"detected_licenses": [
"MIT"
],
"directory_id": "07b391085556be7c9ef6b2177cddfd06441ace64",
"extension": "c",
"filename": "lex1.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 97265918,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 833,
"license": "MIT",
"license_type": "permissive",
"path": "/test/lex1.c",
"provenance": "stackv2-0058.json.gz:157982",
"repo_name": "naeioi/zcc",
"revision_date": "2022-01-17T05:42:17",
"revision_id": "2bb26dbb91957d280861e4971754c99737dc614d",
"snapshot_id": "6e87d3f308a2ed0fb625ca2966a212fb664bafe8",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/naeioi/zcc/2bb26dbb91957d280861e4971754c99737dc614d/test/lex1.c",
"visit_date": "2022-01-29T11:22:14.372648"
} | stackv2 | int a;
int b;
int program(int a,int b,int c)
{
int i;
int j;
i=0;
if(a>(b+c))
{
j=a+(b*c+1);
}
else
{
j=a;
}
while(i<=100)
{
i=j*2;
}
return i;
}
int demo(int a)
{
a=a+2;
return a*2;
}
void main(void)
{
int a;
int b;
int c;
a=3;
b=4;
c=2;
a=program(a,b,demo(c))
return;
}
/*** Lexicon
=-- Internal representation --=
struct token_st {
enum tk_class_en tk_class;
char *tk_str;
value_st *value;
};
enum tk_class_en {
// keywords
TK_INT,
TK_CHAR,
TK_VOID,
TK_RETURN,
// constant
TK_CONST_INT,
TK_CONST_CHAR,
TK_CONST_STRING,
// operator / delimiter
TK_OP,
// others
TK_IDENTIFIER
};
union value_st {
int i;
char c;
};
=-- Expect debug output --=
()
*/ | 2.5625 | 3 |
2024-11-18T19:02:40.869533+00:00 | 2013-09-14T03:46:25 | c58de236bf19709e795192f7e6d5e8fa4d28054a | {
"blob_id": "c58de236bf19709e795192f7e6d5e8fa4d28054a",
"branch_name": "refs/heads/master",
"committer_date": "2013-09-14T03:46:25",
"content_id": "190eea1e40110bf6b94df8bf24db8e6457c3f5f2",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "440a0565b9dfa6231f06e426167f0c11901fc890",
"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": null,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2542,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/dmget/utils.c",
"provenance": "stackv2-0058.json.gz:158110",
"repo_name": "ambarisha/dms",
"revision_date": "2013-09-14T03:46:25",
"revision_id": "ff090f193967a5dce3d9807322ccae0c10219993",
"snapshot_id": "ada0791f282aaeb175c76b873c07db08425b818f",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ambarisha/dms/ff090f193967a5dce3d9807322ccae0c10219993/dmget/utils.c",
"visit_date": "2016-08-04T09:08:14.575294"
} | stackv2 | #include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/socket.h>
#include "dm.h"
/* Utils for handling messages */
int
send_dmmsg(int socket, struct dmmsg msg)
{
printf("IN DMMSG\n");
int bufsize = sizeof(bufsize); // Buffer size
bufsize += 1; // Op
bufsize += msg.len; // Signal number
printf("About to send message\n");
char *sndbuf = (char *) malloc(bufsize);
if (sndbuf == NULL) {
fprintf(stderr, "send_dmmsg: malloc: insufficient memory\n");
return -1;
}
int i = 0;
memcpy(sndbuf + i, &bufsize, sizeof(bufsize));
i += sizeof(bufsize);
*(sndbuf + i) = msg.op;
i++;
if (msg.len != 0) {
memcpy(sndbuf + i, msg.buf, msg.len);
i += msg.len;
}
int nbytes = write(socket, sndbuf, bufsize);
perror("send_dmmsg write");
printf("%d bytes sent\n", nbytes);
free(sndbuf);
if (nbytes == -1) {
fprintf(stderr, "send_dmmsg: write: %s\n",
strerror(errno));
}
return (nbytes);
}
struct dmmsg *
recv_dmmsg(int sock)
{
int bufsize = 0;
int err;
struct dmmsg *msg = (struct dmmsg *) malloc(sizeof(struct dmmsg));
if (msg == NULL) {
fprintf(stderr, "send_dmmsg: malloc: insufficient memory\n");
return NULL;
}
err = read(sock, &bufsize, sizeof(bufsize));
if (err == 0) {
fprintf(stderr, "recv_dmmsg: remote end"
" closed connection\n");
goto error;
} else if (err == -1) {
fprintf(stderr, "recv_dmmsg: %s\n", strerror(errno));
goto error;
}
bufsize -= sizeof(bufsize);
err = read(sock, &(msg->op), sizeof(msg->op));
if (err == 0) {
fprintf(stderr, "recv_dmmsg: remote end"
" closed connection\n");
goto error;
} else if (err == -1) {
fprintf(stderr, "recv_dmmsg: %s\n", strerror(errno));
goto error;
}
bufsize -= sizeof(msg->op);
/* This is to accommodate for 0 length messages */
if (bufsize == 0) {
msg->len = 0;
msg->buf = NULL;
return msg;
}
msg->buf = (char *) malloc(bufsize);
if (msg == NULL) {
fprintf(stderr, "send_dmmsg: malloc: insufficient memory\n");
goto error;
}
msg->len = bufsize;
err = read(sock, msg->buf, bufsize);
if (err == 0) {
msg->len = 0;
fprintf(stderr,"recv_dmmsg: remote end"
" closed connection\n");
free(msg->buf);
free(msg);
return (NULL);
} else if (err == -1) {
fprintf(stderr, "recv_dmmsg: %s\n", strerror(errno));
free(msg->buf);
goto error;
}
return msg;
error:
free(msg);
return NULL;
}
void
free_dmmsg(struct dmmsg **msg)
{
if (*msg == NULL)
return;
free((*msg)->buf);
free(*msg);
*msg = NULL;
}
| 2.84375 | 3 |
2024-11-18T19:02:41.140886+00:00 | 2019-04-07T16:13:16 | 3fc28b198008112dfef8dcf97098c568e14a3552 | {
"blob_id": "3fc28b198008112dfef8dcf97098c568e14a3552",
"branch_name": "refs/heads/master",
"committer_date": "2019-04-07T16:13:16",
"content_id": "ff7bbe95b32550caea9903bfe758082dec2c7ea9",
"detected_licenses": [
"MIT"
],
"directory_id": "d01c30f36460c04638d6c796664ef6b4bbb03b5c",
"extension": "c",
"filename": "15 - ConcurrencyControl.c",
"fork_events_count": 0,
"gha_created_at": "2019-04-03T15:39:11",
"gha_event_created_at": "2019-04-04T13:29:27",
"gha_language": "C",
"gha_license_id": null,
"github_id": 179320389,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 704,
"license": "MIT",
"license_type": "permissive",
"path": "/15 - ConcurrencyControl.c",
"provenance": "stackv2-0058.json.gz:158497",
"repo_name": "yogeshCt3/System-Programming-in-C",
"revision_date": "2019-04-07T16:13:16",
"revision_id": "7bd4e9f140b258e681df1e33285b75d8d06fa6c6",
"snapshot_id": "6f937665cb85b8b762d5f632158c45178fb89e4e",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/yogeshCt3/System-Programming-in-C/7bd4e9f140b258e681df1e33285b75d8d06fa6c6/15 - ConcurrencyControl.c",
"visit_date": "2020-05-04T17:39:01.157765"
} | stackv2 | /*
Author » Yogesh K. Chhetri «
*/
// gcc -pthread -std=c99 "15 - assignJob.c"
// remove the [line a] and [line b] to see the difference
#include <unistd.h>
#include <pthread.h>
#include <stdio.h>
pthread_mutex_t lock;
int count = 0;
void *assignJob(){
pthread_mutex_lock(&lock); // [line a]
++count;
printf("Job %d started\n", count);
sleep(2); // context switching
printf("Job %d ended\n", count);
pthread_mutex_unlock(&lock); // [line b]
}
int main(){
pthread_t thread[10];
for(int i = 0; i < 10 ; i++){
pthread_create(&thread[i], NULL, &assignJob, NULL);
}
for(int i = 0 ; i < 10 ; i++){
pthread_join(thread[i], NULL);
}
return 0;
}
| 3.078125 | 3 |
2024-11-18T19:02:41.230861+00:00 | 2019-05-09T19:59:02 | 59da7c69426a5d4d8f9f58cc2ce8fd2daf251850 | {
"blob_id": "59da7c69426a5d4d8f9f58cc2ce8fd2daf251850",
"branch_name": "refs/heads/master",
"committer_date": "2019-05-09T19:59:02",
"content_id": "617b8775f0facbfe59c25c4446850b6192d06a2b",
"detected_licenses": [
"MIT"
],
"directory_id": "824637600eea42cd5f09e3c21ad8f720a63f7746",
"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": 178479829,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2634,
"license": "MIT",
"license_type": "permissive",
"path": "/main/main.c",
"provenance": "stackv2-0058.json.gz:158625",
"repo_name": "Guergeiro/BLOBS-Finder",
"revision_date": "2019-05-09T19:59:02",
"revision_id": "cce9e3bd5beb2ce630f491d8dfa85f470ecd0e0a",
"snapshot_id": "9a05adabf4f270d13336777ec6ec0782181a1756",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Guergeiro/BLOBS-Finder/cce9e3bd5beb2ce630f491d8dfa85f470ecd0e0a/main/main.c",
"visit_date": "2020-05-03T06:42:38.425120"
} | stackv2 | /*
* main.c
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "funcoes.h"
short menu() {
printf("1 - Ler de Ficheiro\n");
printf("2 - Calcular Blobs\n");
printf("3 - Mostrar Blobs ordenados pelo numero de pixeis\n");
printf("4 - Calcular imagem com mais blobs\n");
printf("5 - Determinar desvio padrão para todos os blobs calculados para cada imagem\n");
printf("6 - Determinar qual o blob com menor desvio padrão e a que imagem corresponde\n");
printf("0 - Sair \n");
printf("Qual a Opcao ");
short op;
scanf("%hu", &op);
return op;
}
void testarMem(char **argv) {
while (1) {
struct imagem *primeiraImagem = lerFicheiro(argv[2]);
calcularBlobs(primeiraImagem, atoi(argv[3]), atoi(argv[4]), atoi(argv[5]), atoi(argv[6]));
mostrarImagens(primeiraImagem);
sortImagens(primeiraImagem);
mostrarImagens(primeiraImagem);
mostrarImagemComMaisBlobs(primeiraImagem);
determinarDesvioPadrao(primeiraImagem);
determinarBlobMenorDesvioPadraoImagem(primeiraImagem);
destruirImagem(primeiraImagem);
}
}
int main(int argc, char **argv) {
if (argc != 8) {
printf("Numero parametros incorreto.\n");
return 1;
}
for (ushort cont = 0; cont < argc; cont++)
printf("parametros[%d] = [%s]\n", cont, argv[cont]);
if (!strcmp(argv[7], "MENUS")) {
struct imagem *primeiraImagem = NULL;
short op;
do {
op = menu();
switch (op) {
case 1:
primeiraImagem = lerFicheiro(argv[2]);
break;
case 2:
calcularBlobs(primeiraImagem, atoi(argv[3]), atoi(argv[4]), atoi(argv[5]), atoi(argv[6]));
mostrarImagens(primeiraImagem);
break;
case 3:
sortImagens(primeiraImagem);
mostrarImagens(primeiraImagem);
break;
case 4:
mostrarImagemComMaisBlobs(primeiraImagem);
break;
case 5:
determinarDesvioPadrao(primeiraImagem);
break;
case 6:
determinarBlobMenorDesvioPadraoImagem(primeiraImagem);
break;
case 0:
destruirImagem(primeiraImagem);
break;
default:
printf("Opcao invalida\n");
}
} while (op);
} else if (!strcmp(argv[7], "ALL")) {
struct imagem *primeiraImagem = lerFicheiro(argv[2]);
calcularBlobs(primeiraImagem, atoi(argv[3]), atoi(argv[4]), atoi(argv[5]), atoi(argv[6]));
sortImagens(primeiraImagem);
determinarDesvioPadrao(primeiraImagem);
mostrarImagens(primeiraImagem);
mostrarImagemComMaisBlobs(primeiraImagem);
determinarBlobMenorDesvioPadraoImagem(primeiraImagem);
destruirImagem(primeiraImagem);
} else if (!strcmp(argv[7], "MEM")) {
testarMem(argv);
} else {
printf("Opcao invalida. Escolhas: MENUS, ALL, MEM\n");
// tests
}
}
| 3.265625 | 3 |
2024-11-18T19:02:41.672867+00:00 | 2018-09-01T21:04:42 | 7e45ac8bb1ca6906e78f4d580fd77c209a5c3aad | {
"blob_id": "7e45ac8bb1ca6906e78f4d580fd77c209a5c3aad",
"branch_name": "refs/heads/master",
"committer_date": "2018-09-01T21:04:42",
"content_id": "a63d4a45164070955c0c445beebb2b52844ce09b",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "f8fdf1ba7875cb13d829cbe71d5e7836351fcd3c",
"extension": "c",
"filename": "app.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 141643030,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 6872,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/Trabajos Practicos/TP1/src/app.c",
"provenance": "stackv2-0058.json.gz:159010",
"repo_name": "rtirapegui/CESE-6Co2018_PCSE",
"revision_date": "2018-09-01T21:04:42",
"revision_id": "2e4776d66c16990ed9d8cefe8ae2bf99f5eba356",
"snapshot_id": "5cb409aa70658189440b5e44200a966d7bf24e09",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/rtirapegui/CESE-6Co2018_PCSE/2e4776d66c16990ed9d8cefe8ae2bf99f5eba356/Trabajos Practicos/TP1/src/app.c",
"visit_date": "2020-03-23T13:52:57.449851"
} | stackv2 | /*
* app.c
*
* Created on: 5/7/2018
* Author: rodrigo
*/
/*============================================================================
* Autor: Rodrigo Tirapegui
* Licencia:
* Fecha: 22/3/2018
*===========================================================================*/
/*==================[inlcusiones]============================================*/
#include <stdarg.h>
#include "app.h"
#include "sapi.h"
#include "ff.h" // <= Biblioteca FAT FS
/*==================[definiciones y macros]==================================*/
/*==================[definiciones de datos internos]=========================*/
/* RTC constantes */
#define RTC_INITIAL_YEAR 2018
#define RTC_INITIAL_MONTH 7
#define RTC_INITIAL_DAY 5
#define RTC_INITIAL_HOUR 0
#define RTC_INITIAL_MINUTE 0
#define RTC_INITIAL_SECOND 0
#define RTC_CONFIG_INTERVAL 2000 // In ms
/* SD constantes */
#define SD_TICK_INTERVAL 10 // In ms
#define SD_INIT_RETRIES_MAX 5
#define SD_FILE_NAME "Log.txt"
/* TASK constantes */
#define TASK_SAMPLING_DELAY 1000 // In ms
#define TASK_BUFF_SIZE 256
#define ASSERT_TICK_INTERVAL 500
/* SD variables */
static FATFS fs; // <-- FatFs work area needed for each volume
static FIL fp; // <-- File object needed for each open file
/*==================[definiciones de datos externos]=========================*/
/*==================[declaraciones de funciones internas]====================*/
/*==================[declaraciones de funciones externas]====================*/
/*==================[definiciones de funciones internas]=====================*/
/* RTC funciones */
static bool_t _rtcInit(void) {
bool_t ret;
/* Estructura del RTC */
rtc_t rtc = { 0 };
rtc.year = RTC_INITIAL_YEAR;
rtc.month = RTC_INITIAL_MONTH;
rtc.mday = RTC_INITIAL_DAY;
rtc.hour = RTC_INITIAL_HOUR;
rtc.min = RTC_INITIAL_MINUTE;
rtc.sec = RTC_INITIAL_SECOND;
/* Inicializar RTC */
ret = rtcConfig(&rtc);
if(ret)
delay(2000); // El RTC tarda en setear la hora, por eso el delay
return ret;
}
/* SD funciones */
static void diskTickHook(void *ptr) {
disk_timerproc(); // Disk timer process
}
static bool_t sdInit(void)
{
UINT nbytes;
uint8_t i;
// Inicializar interfaz SPI0
spiConfig( SPI0 );
// Inicializar el conteo de Ticks con resolucion de 10ms,
// con tickHook diskTickHook
tickConfig(10);
tickCallbackSet(diskTickHook, NULL);
// Configurar el area de trabajo en el disco por defecto
if(FR_OK == f_mount(&fs, "", 0)) {
return TRUE;
}
return FALSE;
}
/* ADC funciones */
static bool_t _adcInit(void) {
/* Inicializar AnalogIO */
/* Posibles configuraciones:
* ADC_ENABLE, ADC_DISABLE,
* ADC_ENABLE, ADC_DISABLE,
*/
adcConfig(ADC_ENABLE);
return TRUE;
}
/* MAIN TASK funciones */
/**
* \brief Formatea un string segun los parametros deseados y lo almacena en buff
*
* \param buff puntero al buffer donde almacenar el string formateado
*
* \return void Devuelve el numero de bytes escritos en el buffer
*
*/
uint32_t formatVariadicString(uint8_t *buf, uint32_t bufSize, const uint8_t* format, ...) {
int32_t size;
va_list arg;
va_start(arg, format);
size = vsnprintf(buf, bufSize, format, arg);
va_end(arg);
if(size < 0)
size = 0;
return (uint32_t) size;
}
/*==================[definiciones de funciones externas]=====================*/
bool_t appInit(void) {
// ---------- CONFIGURACIONES ------------------------------
// Inicializar y configurar la plataforma
boardConfig();
// Inicializar y configurar RTC
if(!_rtcInit())
return FALSE;
// Inicializar y configurar la memoria SD
if(!sdInit())
return FALSE;
// Inicializar y configurar el ADC
if(!_adcInit())
return FALSE;
return TRUE;
}
void appRun(void) {
uint8_t msg[TASK_BUFF_SIZE];
uint16_t adcSample_ch1, adcSample_ch2, adcSample_ch3;
uint32_t msgSize, msgWrittenSize;
rtc_t rtcTimestamp;
delay_t samplingDelay; // Variable de delays no bloqueantes
/* Inicializar Retardo no bloqueante con tiempo en ms */
delayConfig(&samplingDelay, TASK_SAMPLING_DELAY);
// ---------- REPETIR POR SIEMPRE --------------------------
while(TRUE)
{
/* Ejecutar TASK que compone el programa */
gpioWrite(LEDG, OFF); // Turn OFF LEDG
gpioWrite(LEDR, OFF); // Turn OFF LEDR
if (delayRead(&samplingDelay)){
// Muestrear los canales CH1, CH2 y CH3 del ADC
adcSample_ch1 = adcRead(CH1);
adcSample_ch2 = adcRead(CH2);
adcSample_ch3 = adcRead(CH3);
// Muestrear el RTC
rtcRead(&rtcTimestamp);
// Formatear mensaje a almacenar en la memoria SD de la siguiente manera
//
// CH1;CH2;CH3;YYYY/MM/DD_hh:mm:ss;
msgSize = formatVariadicString(msg, sizeof(msg),
"%u;%u;%u;%04u/%02u/%02u_%02u:%02u:%02u\r\n", adcSample_ch1,
adcSample_ch2,
adcSample_ch3,
rtcTimestamp.year,
rtcTimestamp.month,
rtcTimestamp.mday,
rtcTimestamp.hour,
rtcTimestamp.min,
rtcTimestamp.sec);
// Guardar el mensaje en la memoria SD
if(msgSize) {
if(FR_OK == f_open(&fp, SD_FILE_NAME, FA_WRITE | FA_OPEN_APPEND)) {
f_write(&fp, msg, (UINT) msgSize, (UINT) &msgWrittenSize);
f_close(&fp);
}
if(msgSize == msgWrittenSize) {
gpioWrite(LEDG, ON); // Turn ON LEDG if the write operation was successful
}
else {
gpioWrite(LEDR, ON); // Turn ON LEDR if the write operation was fail
f_close(&fp);
break;
}
}
delayConfig(&samplingDelay, TASK_SAMPLING_DELAY);
}
sleepUntilNextInterrupt();
}
}
void appAssert(void) {
while(TRUE) {
gpioWrite(LEDR, ON);
delay(ASSERT_TICK_INTERVAL);
gpioWrite(LEDR, OFF);
delay(ASSERT_TICK_INTERVAL);
}
}
/*==================[fin del archivo]========================================*/
| 2.46875 | 2 |
2024-11-18T19:02:42.058214+00:00 | 2023-08-17T16:08:06 | 0dc1c3600c35d8ac30bee4a315125f1d5aced653 | {
"blob_id": "0dc1c3600c35d8ac30bee4a315125f1d5aced653",
"branch_name": "refs/heads/main",
"committer_date": "2023-08-17T16:08:06",
"content_id": "fe07f5b465bb5c0f988579d2efb87f3d2c4e20a1",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "eecd5e4c50d8b78a769bcc2675250576bed34066",
"extension": "c",
"filename": "tsdiscgrad.c",
"fork_events_count": 169,
"gha_created_at": "2013-03-10T20:55:21",
"gha_event_created_at": "2023-03-29T11:02:58",
"gha_language": "C",
"gha_license_id": "NOASSERTION",
"github_id": 8691401,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 19975,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/src/ts/impls/implicit/discgrad/tsdiscgrad.c",
"provenance": "stackv2-0058.json.gz:159267",
"repo_name": "petsc/petsc",
"revision_date": "2023-08-17T16:08:06",
"revision_id": "9c5460f9064ca60dd71a234a1f6faf93e7a6b0c9",
"snapshot_id": "3b1a04fea71858e0292f9fd4d04ea11618c50969",
"src_encoding": "UTF-8",
"star_events_count": 341,
"url": "https://raw.githubusercontent.com/petsc/petsc/9c5460f9064ca60dd71a234a1f6faf93e7a6b0c9/src/ts/impls/implicit/discgrad/tsdiscgrad.c",
"visit_date": "2023-08-17T20:51:16.507070"
} | stackv2 | /*
Code for timestepping with discrete gradient integrators
*/
#include <petsc/private/tsimpl.h> /*I "petscts.h" I*/
#include <petscdm.h>
PetscBool DGCite = PETSC_FALSE;
const char DGCitation[] = "@article{Gonzalez1996,\n"
" title = {Time integration and discrete Hamiltonian systems},\n"
" author = {Oscar Gonzalez},\n"
" journal = {Journal of Nonlinear Science},\n"
" volume = {6},\n"
" pages = {449--467},\n"
" doi = {10.1007/978-1-4612-1246-1_10},\n"
" year = {1996}\n}\n";
typedef struct {
PetscReal stage_time;
Vec X0, X, Xdot;
void *funcCtx;
PetscBool gonzalez;
PetscErrorCode (*Sfunc)(TS, PetscReal, Vec, Mat, void *);
PetscErrorCode (*Ffunc)(TS, PetscReal, Vec, PetscScalar *, void *);
PetscErrorCode (*Gfunc)(TS, PetscReal, Vec, Vec, void *);
} TS_DiscGrad;
static PetscErrorCode TSDiscGradGetX0AndXdot(TS ts, DM dm, Vec *X0, Vec *Xdot)
{
TS_DiscGrad *dg = (TS_DiscGrad *)ts->data;
PetscFunctionBegin;
if (X0) {
if (dm && dm != ts->dm) PetscCall(DMGetNamedGlobalVector(dm, "TSDiscGrad_X0", X0));
else *X0 = ts->vec_sol;
}
if (Xdot) {
if (dm && dm != ts->dm) PetscCall(DMGetNamedGlobalVector(dm, "TSDiscGrad_Xdot", Xdot));
else *Xdot = dg->Xdot;
}
PetscFunctionReturn(PETSC_SUCCESS);
}
static PetscErrorCode TSDiscGradRestoreX0AndXdot(TS ts, DM dm, Vec *X0, Vec *Xdot)
{
PetscFunctionBegin;
if (X0) {
if (dm && dm != ts->dm) PetscCall(DMRestoreNamedGlobalVector(dm, "TSDiscGrad_X0", X0));
}
if (Xdot) {
if (dm && dm != ts->dm) PetscCall(DMRestoreNamedGlobalVector(dm, "TSDiscGrad_Xdot", Xdot));
}
PetscFunctionReturn(PETSC_SUCCESS);
}
static PetscErrorCode DMCoarsenHook_TSDiscGrad(DM fine, DM coarse, void *ctx)
{
PetscFunctionBegin;
PetscFunctionReturn(PETSC_SUCCESS);
}
static PetscErrorCode DMRestrictHook_TSDiscGrad(DM fine, Mat restrct, Vec rscale, Mat inject, DM coarse, void *ctx)
{
TS ts = (TS)ctx;
Vec X0, Xdot, X0_c, Xdot_c;
PetscFunctionBegin;
PetscCall(TSDiscGradGetX0AndXdot(ts, fine, &X0, &Xdot));
PetscCall(TSDiscGradGetX0AndXdot(ts, coarse, &X0_c, &Xdot_c));
PetscCall(MatRestrict(restrct, X0, X0_c));
PetscCall(MatRestrict(restrct, Xdot, Xdot_c));
PetscCall(VecPointwiseMult(X0_c, rscale, X0_c));
PetscCall(VecPointwiseMult(Xdot_c, rscale, Xdot_c));
PetscCall(TSDiscGradRestoreX0AndXdot(ts, fine, &X0, &Xdot));
PetscCall(TSDiscGradRestoreX0AndXdot(ts, coarse, &X0_c, &Xdot_c));
PetscFunctionReturn(PETSC_SUCCESS);
}
static PetscErrorCode DMSubDomainHook_TSDiscGrad(DM dm, DM subdm, void *ctx)
{
PetscFunctionBegin;
PetscFunctionReturn(PETSC_SUCCESS);
}
static PetscErrorCode DMSubDomainRestrictHook_TSDiscGrad(DM dm, VecScatter gscat, VecScatter lscat, DM subdm, void *ctx)
{
TS ts = (TS)ctx;
Vec X0, Xdot, X0_sub, Xdot_sub;
PetscFunctionBegin;
PetscCall(TSDiscGradGetX0AndXdot(ts, dm, &X0, &Xdot));
PetscCall(TSDiscGradGetX0AndXdot(ts, subdm, &X0_sub, &Xdot_sub));
PetscCall(VecScatterBegin(gscat, X0, X0_sub, INSERT_VALUES, SCATTER_FORWARD));
PetscCall(VecScatterEnd(gscat, X0, X0_sub, INSERT_VALUES, SCATTER_FORWARD));
PetscCall(VecScatterBegin(gscat, Xdot, Xdot_sub, INSERT_VALUES, SCATTER_FORWARD));
PetscCall(VecScatterEnd(gscat, Xdot, Xdot_sub, INSERT_VALUES, SCATTER_FORWARD));
PetscCall(TSDiscGradRestoreX0AndXdot(ts, dm, &X0, &Xdot));
PetscCall(TSDiscGradRestoreX0AndXdot(ts, subdm, &X0_sub, &Xdot_sub));
PetscFunctionReturn(PETSC_SUCCESS);
}
static PetscErrorCode TSSetUp_DiscGrad(TS ts)
{
TS_DiscGrad *dg = (TS_DiscGrad *)ts->data;
DM dm;
PetscFunctionBegin;
if (!dg->X) PetscCall(VecDuplicate(ts->vec_sol, &dg->X));
if (!dg->X0) PetscCall(VecDuplicate(ts->vec_sol, &dg->X0));
if (!dg->Xdot) PetscCall(VecDuplicate(ts->vec_sol, &dg->Xdot));
PetscCall(TSGetDM(ts, &dm));
PetscCall(DMCoarsenHookAdd(dm, DMCoarsenHook_TSDiscGrad, DMRestrictHook_TSDiscGrad, ts));
PetscCall(DMSubDomainHookAdd(dm, DMSubDomainHook_TSDiscGrad, DMSubDomainRestrictHook_TSDiscGrad, ts));
PetscFunctionReturn(PETSC_SUCCESS);
}
static PetscErrorCode TSSetFromOptions_DiscGrad(TS ts, PetscOptionItems *PetscOptionsObject)
{
TS_DiscGrad *dg = (TS_DiscGrad *)ts->data;
PetscFunctionBegin;
PetscOptionsHeadBegin(PetscOptionsObject, "Discrete Gradients ODE solver options");
{
PetscCall(PetscOptionsBool("-ts_discgrad_gonzalez", "Use Gonzalez term in discrete gradients formulation", "TSDiscGradUseGonzalez", dg->gonzalez, &dg->gonzalez, NULL));
}
PetscOptionsHeadEnd();
PetscFunctionReturn(PETSC_SUCCESS);
}
static PetscErrorCode TSView_DiscGrad(TS ts, PetscViewer viewer)
{
PetscBool iascii;
PetscFunctionBegin;
PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &iascii));
if (iascii) PetscCall(PetscViewerASCIIPrintf(viewer, " Discrete Gradients\n"));
PetscFunctionReturn(PETSC_SUCCESS);
}
static PetscErrorCode TSDiscGradIsGonzalez_DiscGrad(TS ts, PetscBool *gonzalez)
{
TS_DiscGrad *dg = (TS_DiscGrad *)ts->data;
PetscFunctionBegin;
*gonzalez = dg->gonzalez;
PetscFunctionReturn(PETSC_SUCCESS);
}
static PetscErrorCode TSDiscGradUseGonzalez_DiscGrad(TS ts, PetscBool flg)
{
TS_DiscGrad *dg = (TS_DiscGrad *)ts->data;
PetscFunctionBegin;
dg->gonzalez = flg;
PetscFunctionReturn(PETSC_SUCCESS);
}
static PetscErrorCode TSReset_DiscGrad(TS ts)
{
TS_DiscGrad *dg = (TS_DiscGrad *)ts->data;
PetscFunctionBegin;
PetscCall(VecDestroy(&dg->X));
PetscCall(VecDestroy(&dg->X0));
PetscCall(VecDestroy(&dg->Xdot));
PetscFunctionReturn(PETSC_SUCCESS);
}
static PetscErrorCode TSDestroy_DiscGrad(TS ts)
{
DM dm;
PetscFunctionBegin;
PetscCall(TSReset_DiscGrad(ts));
PetscCall(TSGetDM(ts, &dm));
if (dm) {
PetscCall(DMCoarsenHookRemove(dm, DMCoarsenHook_TSDiscGrad, DMRestrictHook_TSDiscGrad, ts));
PetscCall(DMSubDomainHookRemove(dm, DMSubDomainHook_TSDiscGrad, DMSubDomainRestrictHook_TSDiscGrad, ts));
}
PetscCall(PetscFree(ts->data));
PetscCall(PetscObjectComposeFunction((PetscObject)ts, "TSDiscGradGetFormulation_C", NULL));
PetscCall(PetscObjectComposeFunction((PetscObject)ts, "TSDiscGradSetFormulation_C", NULL));
PetscCall(PetscObjectComposeFunction((PetscObject)ts, "TSDiscGradIsGonzalez_C", NULL));
PetscCall(PetscObjectComposeFunction((PetscObject)ts, "TSDiscGradUseGonzalez_C", NULL));
PetscFunctionReturn(PETSC_SUCCESS);
}
static PetscErrorCode TSInterpolate_DiscGrad(TS ts, PetscReal t, Vec X)
{
TS_DiscGrad *dg = (TS_DiscGrad *)ts->data;
PetscReal dt = t - ts->ptime;
PetscFunctionBegin;
PetscCall(VecCopy(ts->vec_sol, dg->X));
PetscCall(VecWAXPY(X, dt, dg->Xdot, dg->X));
PetscFunctionReturn(PETSC_SUCCESS);
}
static PetscErrorCode TSDiscGrad_SNESSolve(TS ts, Vec b, Vec x)
{
SNES snes;
PetscInt nits, lits;
PetscFunctionBegin;
PetscCall(TSGetSNES(ts, &snes));
PetscCall(SNESSolve(snes, b, x));
PetscCall(SNESGetIterationNumber(snes, &nits));
PetscCall(SNESGetLinearSolveIterations(snes, &lits));
ts->snes_its += nits;
ts->ksp_its += lits;
PetscFunctionReturn(PETSC_SUCCESS);
}
static PetscErrorCode TSStep_DiscGrad(TS ts)
{
TS_DiscGrad *dg = (TS_DiscGrad *)ts->data;
TSAdapt adapt;
TSStepStatus status = TS_STEP_INCOMPLETE;
PetscInt rejections = 0;
PetscBool stageok, accept = PETSC_TRUE;
PetscReal next_time_step = ts->time_step;
PetscFunctionBegin;
PetscCall(TSGetAdapt(ts, &adapt));
if (!ts->steprollback) PetscCall(VecCopy(ts->vec_sol, dg->X0));
while (!ts->reason && status != TS_STEP_COMPLETE) {
PetscReal shift = 1 / (0.5 * ts->time_step);
dg->stage_time = ts->ptime + 0.5 * ts->time_step;
PetscCall(VecCopy(dg->X0, dg->X));
PetscCall(TSPreStage(ts, dg->stage_time));
PetscCall(TSDiscGrad_SNESSolve(ts, NULL, dg->X));
PetscCall(TSPostStage(ts, dg->stage_time, 0, &dg->X));
PetscCall(TSAdaptCheckStage(adapt, ts, dg->stage_time, dg->X, &stageok));
if (!stageok) goto reject_step;
status = TS_STEP_PENDING;
PetscCall(VecAXPBYPCZ(dg->Xdot, -shift, shift, 0, dg->X0, dg->X));
PetscCall(VecAXPY(ts->vec_sol, ts->time_step, dg->Xdot));
PetscCall(TSAdaptChoose(adapt, ts, ts->time_step, NULL, &next_time_step, &accept));
status = accept ? TS_STEP_COMPLETE : TS_STEP_INCOMPLETE;
if (!accept) {
PetscCall(VecCopy(dg->X0, ts->vec_sol));
ts->time_step = next_time_step;
goto reject_step;
}
ts->ptime += ts->time_step;
ts->time_step = next_time_step;
break;
reject_step:
ts->reject++;
accept = PETSC_FALSE;
if (!ts->reason && ts->max_reject >= 0 && ++rejections > ts->max_reject) {
ts->reason = TS_DIVERGED_STEP_REJECTED;
PetscCall(PetscInfo(ts, "Step=%" PetscInt_FMT ", step rejections %" PetscInt_FMT " greater than current TS allowed, stopping solve\n", ts->steps, rejections));
}
}
PetscFunctionReturn(PETSC_SUCCESS);
}
static PetscErrorCode TSGetStages_DiscGrad(TS ts, PetscInt *ns, Vec **Y)
{
TS_DiscGrad *dg = (TS_DiscGrad *)ts->data;
PetscFunctionBegin;
if (ns) *ns = 1;
if (Y) *Y = &(dg->X);
PetscFunctionReturn(PETSC_SUCCESS);
}
/*
This defines the nonlinear equation that is to be solved with SNES
G(U) = F[t0 + 0.5*dt, U, (U-U0)/dt] = 0
*/
/* x = (x+x')/2 */
/* NEED TO CALCULATE x_{n+1} from x and x_{n}*/
static PetscErrorCode SNESTSFormFunction_DiscGrad(SNES snes, Vec x, Vec y, TS ts)
{
TS_DiscGrad *dg = (TS_DiscGrad *)ts->data;
PetscReal norm, shift = 1 / (0.5 * ts->time_step);
PetscInt n;
Vec X0, Xdot, Xp, Xdiff;
Mat S;
PetscScalar F = 0, F0 = 0, Gp;
Vec G, SgF;
DM dm, dmsave;
PetscFunctionBegin;
PetscCall(SNESGetDM(snes, &dm));
PetscCall(VecDuplicate(y, &Xp));
PetscCall(VecDuplicate(y, &Xdiff));
PetscCall(VecDuplicate(y, &SgF));
PetscCall(VecDuplicate(y, &G));
PetscCall(VecGetLocalSize(y, &n));
PetscCall(MatCreate(PETSC_COMM_WORLD, &S));
PetscCall(MatSetSizes(S, PETSC_DECIDE, PETSC_DECIDE, n, n));
PetscCall(MatSetFromOptions(S));
PetscCall(MatSetUp(S));
PetscCall(MatAssemblyBegin(S, MAT_FINAL_ASSEMBLY));
PetscCall(MatAssemblyEnd(S, MAT_FINAL_ASSEMBLY));
PetscCall(TSDiscGradGetX0AndXdot(ts, dm, &X0, &Xdot));
PetscCall(VecAXPBYPCZ(Xdot, -shift, shift, 0, X0, x)); /* Xdot = shift (x - X0) */
PetscCall(VecAXPBYPCZ(Xp, -1, 2, 0, X0, x)); /* Xp = 2*x - X0 + (0)*Xmid */
PetscCall(VecAXPBYPCZ(Xdiff, -1, 1, 0, X0, Xp)); /* Xdiff = xp - X0 + (0)*Xdiff */
if (dg->gonzalez) {
PetscCall((*dg->Sfunc)(ts, dg->stage_time, x, S, dg->funcCtx));
PetscCall((*dg->Ffunc)(ts, dg->stage_time, Xp, &F, dg->funcCtx));
PetscCall((*dg->Ffunc)(ts, dg->stage_time, X0, &F0, dg->funcCtx));
PetscCall((*dg->Gfunc)(ts, dg->stage_time, x, G, dg->funcCtx));
/* Adding Extra Gonzalez Term */
PetscCall(VecDot(Xdiff, G, &Gp));
PetscCall(VecNorm(Xdiff, NORM_2, &norm));
if (norm < PETSC_SQRT_MACHINE_EPSILON) {
Gp = 0;
} else {
/* Gp = (1/|xn+1 - xn|^2) * (F(xn+1) - F(xn) - Gp) */
Gp = (F - F0 - Gp) / PetscSqr(norm);
}
PetscCall(VecAXPY(G, Gp, Xdiff));
PetscCall(MatMult(S, G, SgF)); /* S*gradF */
} else {
PetscCall((*dg->Sfunc)(ts, dg->stage_time, x, S, dg->funcCtx));
PetscCall((*dg->Gfunc)(ts, dg->stage_time, x, G, dg->funcCtx));
PetscCall(MatMult(S, G, SgF)); /* Xdot = S*gradF */
}
/* DM monkey-business allows user code to call TSGetDM() inside of functions evaluated on levels of FAS */
dmsave = ts->dm;
ts->dm = dm;
PetscCall(VecAXPBYPCZ(y, 1, -1, 0, Xdot, SgF));
ts->dm = dmsave;
PetscCall(TSDiscGradRestoreX0AndXdot(ts, dm, &X0, &Xdot));
PetscCall(VecDestroy(&Xp));
PetscCall(VecDestroy(&Xdiff));
PetscCall(VecDestroy(&SgF));
PetscCall(VecDestroy(&G));
PetscCall(MatDestroy(&S));
PetscFunctionReturn(PETSC_SUCCESS);
}
static PetscErrorCode SNESTSFormJacobian_DiscGrad(SNES snes, Vec x, Mat A, Mat B, TS ts)
{
TS_DiscGrad *dg = (TS_DiscGrad *)ts->data;
PetscReal shift = 1 / (0.5 * ts->time_step);
Vec Xdot;
DM dm, dmsave;
PetscFunctionBegin;
PetscCall(SNESGetDM(snes, &dm));
/* Xdot has already been computed in SNESTSFormFunction_DiscGrad (SNES guarantees this) */
PetscCall(TSDiscGradGetX0AndXdot(ts, dm, NULL, &Xdot));
dmsave = ts->dm;
ts->dm = dm;
PetscCall(TSComputeIJacobian(ts, dg->stage_time, x, Xdot, shift, A, B, PETSC_FALSE));
ts->dm = dmsave;
PetscCall(TSDiscGradRestoreX0AndXdot(ts, dm, NULL, &Xdot));
PetscFunctionReturn(PETSC_SUCCESS);
}
static PetscErrorCode TSDiscGradGetFormulation_DiscGrad(TS ts, PetscErrorCode (**Sfunc)(TS, PetscReal, Vec, Mat, void *), PetscErrorCode (**Ffunc)(TS, PetscReal, Vec, PetscScalar *, void *), PetscErrorCode (**Gfunc)(TS, PetscReal, Vec, Vec, void *), void *ctx)
{
TS_DiscGrad *dg = (TS_DiscGrad *)ts->data;
PetscFunctionBegin;
*Sfunc = dg->Sfunc;
*Ffunc = dg->Ffunc;
*Gfunc = dg->Gfunc;
PetscFunctionReturn(PETSC_SUCCESS);
}
static PetscErrorCode TSDiscGradSetFormulation_DiscGrad(TS ts, PetscErrorCode (*Sfunc)(TS, PetscReal, Vec, Mat, void *), PetscErrorCode (*Ffunc)(TS, PetscReal, Vec, PetscScalar *, void *), PetscErrorCode (*Gfunc)(TS, PetscReal, Vec, Vec, void *), void *ctx)
{
TS_DiscGrad *dg = (TS_DiscGrad *)ts->data;
PetscFunctionBegin;
dg->Sfunc = Sfunc;
dg->Ffunc = Ffunc;
dg->Gfunc = Gfunc;
dg->funcCtx = ctx;
PetscFunctionReturn(PETSC_SUCCESS);
}
/*MC
TSDISCGRAD - ODE solver using the discrete gradients version of the implicit midpoint method
Level: intermediate
Notes:
This is the implicit midpoint rule, with an optional term that guarantees the discrete
gradient property. This timestepper applies to systems of the form $u_t = S(u) \nabla F(u)$
where $S(u)$ is a linear operator, and $F$ is a functional of $u$.
.seealso: [](ch_ts), `TSCreate()`, `TSSetType()`, `TS`, `TSDISCGRAD`, `TSDiscGradSetFormulation()`
M*/
PETSC_EXTERN PetscErrorCode TSCreate_DiscGrad(TS ts)
{
TS_DiscGrad *th;
PetscFunctionBegin;
PetscCall(PetscCitationsRegister(DGCitation, &DGCite));
ts->ops->reset = TSReset_DiscGrad;
ts->ops->destroy = TSDestroy_DiscGrad;
ts->ops->view = TSView_DiscGrad;
ts->ops->setfromoptions = TSSetFromOptions_DiscGrad;
ts->ops->setup = TSSetUp_DiscGrad;
ts->ops->step = TSStep_DiscGrad;
ts->ops->interpolate = TSInterpolate_DiscGrad;
ts->ops->getstages = TSGetStages_DiscGrad;
ts->ops->snesfunction = SNESTSFormFunction_DiscGrad;
ts->ops->snesjacobian = SNESTSFormJacobian_DiscGrad;
ts->default_adapt_type = TSADAPTNONE;
ts->usessnes = PETSC_TRUE;
PetscCall(PetscNew(&th));
ts->data = (void *)th;
th->gonzalez = PETSC_FALSE;
PetscCall(PetscObjectComposeFunction((PetscObject)ts, "TSDiscGradGetFormulation_C", TSDiscGradGetFormulation_DiscGrad));
PetscCall(PetscObjectComposeFunction((PetscObject)ts, "TSDiscGradSetFormulation_C", TSDiscGradSetFormulation_DiscGrad));
PetscCall(PetscObjectComposeFunction((PetscObject)ts, "TSDiscGradIsGonzalez_C", TSDiscGradIsGonzalez_DiscGrad));
PetscCall(PetscObjectComposeFunction((PetscObject)ts, "TSDiscGradUseGonzalez_C", TSDiscGradUseGonzalez_DiscGrad));
PetscFunctionReturn(PETSC_SUCCESS);
}
/*@C
TSDiscGradGetFormulation - Get the construction method for S, F, and grad F from the
formulation $u_t = S \nabla F$ for `TSDISCGRAD`
Not Collective
Input Parameter:
. ts - timestepping context
Output Parameters:
+ Sfunc - constructor for the S matrix from the formulation
. Ffunc - functional F from the formulation
. Gfunc - constructor for the gradient of F from the formulation
- ctx - the user context
Calling sequence of `Sfunc`:
$ PetscErrorCode Sfunc(TS ts, PetscReal time, Vec u, Mat S, void *ctx)
Calling sequence of `Ffunc`:
$ PetscErrorCode Ffunc(TS ts, PetscReal time, Vec u, PetscScalar *F, void *ctx)
Calling sequence of `Gfunc`:
$ PetscErrorCode Gfunc(TS ts, PetscReal time, Vec u, Vec G, void *ctx)
Level: intermediate
.seealso: [](ch_ts), `TS`, `TSDISCGRAD`, `TSDiscGradSetFormulation()`
@*/
PetscErrorCode TSDiscGradGetFormulation(TS ts, PetscErrorCode (**Sfunc)(TS, PetscReal, Vec, Mat, void *), PetscErrorCode (**Ffunc)(TS, PetscReal, Vec, PetscScalar *, void *), PetscErrorCode (**Gfunc)(TS, PetscReal, Vec, Vec, void *), void *ctx)
{
PetscFunctionBegin;
PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
PetscAssertPointer(Sfunc, 2);
PetscAssertPointer(Ffunc, 3);
PetscAssertPointer(Gfunc, 4);
PetscUseMethod(ts, "TSDiscGradGetFormulation_C", (TS, PetscErrorCode(**Sfunc)(TS, PetscReal, Vec, Mat, void *), PetscErrorCode(**Ffunc)(TS, PetscReal, Vec, PetscScalar *, void *), PetscErrorCode(**Gfunc)(TS, PetscReal, Vec, Vec, void *), void *), (ts, Sfunc, Ffunc, Gfunc, ctx));
PetscFunctionReturn(PETSC_SUCCESS);
}
/*@C
TSDiscGradSetFormulation - Set the construction method for S, F, and grad F from the
formulation $u_t = S(u) \nabla F(u)$ for `TSDISCGRAD`
Not Collective
Input Parameters:
+ ts - timestepping context
. Sfunc - constructor for the S matrix from the formulation
. Ffunc - functional F from the formulation
. Gfunc - constructor for the gradient of F from the formulation
- ctx - optional context for the functions
Calling sequence of `Sfunc`:
$ PetscErrorCode Sfunc(TS ts, PetscReal time, Vec u, Mat S, void *ctx)
Calling sequence of `Ffunc`:
$ PetscErrorCode Ffunc(TS ts, PetscReal time, Vec u, PetscScalar *F, void *ctx)
Calling sequence of `Gfunc`:
$ PetscErrorCode Gfunc(TS ts, PetscReal time, Vec u, Vec G, void *ctx)
Level: intermediate
.seealso: [](ch_ts), `TSDISCGRAD`, `TSDiscGradGetFormulation()`
@*/
PetscErrorCode TSDiscGradSetFormulation(TS ts, PetscErrorCode (*Sfunc)(TS, PetscReal, Vec, Mat, void *), PetscErrorCode (*Ffunc)(TS, PetscReal, Vec, PetscScalar *, void *), PetscErrorCode (*Gfunc)(TS, PetscReal, Vec, Vec, void *), void *ctx)
{
PetscFunctionBegin;
PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
PetscValidFunction(Sfunc, 2);
PetscValidFunction(Ffunc, 3);
PetscValidFunction(Gfunc, 4);
PetscTryMethod(ts, "TSDiscGradSetFormulation_C", (TS, PetscErrorCode(*Sfunc)(TS, PetscReal, Vec, Mat, void *), PetscErrorCode(*Ffunc)(TS, PetscReal, Vec, PetscScalar *, void *), PetscErrorCode(*Gfunc)(TS, PetscReal, Vec, Vec, void *), void *), (ts, Sfunc, Ffunc, Gfunc, ctx));
PetscFunctionReturn(PETSC_SUCCESS);
}
/*@
TSDiscGradIsGonzalez - Checks flag for whether to use additional conservative terms in
discrete gradient formulation for `TSDISCGRAD`
Not Collective
Input Parameter:
. ts - timestepping context
Output Parameter:
. gonzalez - `PETSC_TRUE` when using the Gonzalez term
Level: advanced
.seealso: [](ch_ts), `TSDISCGRAD`, `TSDiscGradUseGonzalez()`
@*/
PetscErrorCode TSDiscGradIsGonzalez(TS ts, PetscBool *gonzalez)
{
PetscFunctionBegin;
PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
PetscAssertPointer(gonzalez, 2);
PetscUseMethod(ts, "TSDiscGradIsGonzalez_C", (TS, PetscBool *), (ts, gonzalez));
PetscFunctionReturn(PETSC_SUCCESS);
}
/*@
TSDiscGradUseGonzalez - Sets discrete gradient formulation with or without additional
conservative terms.
Not Collective
Input Parameters:
+ ts - timestepping context
- flg - `PETSC_TRUE` to use the Gonzalez term
Options Database Key:
. -ts_discgrad_gonzalez <flg> - use the Gonzalez term for the discrete gradient formulation
Level: intermediate
Notes:
Without `flg`, the discrete gradients timestepper is just backwards Euler.
.seealso: [](ch_ts), `TSDISCGRAD`
@*/
PetscErrorCode TSDiscGradUseGonzalez(TS ts, PetscBool flg)
{
PetscFunctionBegin;
PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
PetscTryMethod(ts, "TSDiscGradUseGonzalez_C", (TS, PetscBool), (ts, flg));
PetscFunctionReturn(PETSC_SUCCESS);
}
| 2.265625 | 2 |
2024-11-18T19:02:42.725461+00:00 | 2018-06-25T04:20:35 | 731bce9d5777b25ea3a714761d638eebf2d45157 | {
"blob_id": "731bce9d5777b25ea3a714761d638eebf2d45157",
"branch_name": "refs/heads/master",
"committer_date": "2018-06-25T04:20:35",
"content_id": "d720144beadef35c406bf831f4dccfd21fc5581d",
"detected_licenses": [
"MIT"
],
"directory_id": "8fafdeff167003be830a7ead6daaa6d58ebd6316",
"extension": "c",
"filename": "ctest_tests.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 126930407,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 13220,
"license": "MIT",
"license_type": "permissive",
"path": "/src/ctest_tests.c",
"provenance": "stackv2-0058.json.gz:159652",
"repo_name": "w7rus/trpo2018",
"revision_date": "2018-06-25T04:20:35",
"revision_id": "a2f137f7a719772cad279942b4977bd908fd7c1f",
"snapshot_id": "76798b5d14fb06d328114c16219584b58d3441c3",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/w7rus/trpo2018/a2f137f7a719772cad279942b4977bd908fd7c1f/src/ctest_tests.c",
"visit_date": "2021-04-18T22:17:13.384526"
} | stackv2 | #include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "quizrunner_changedir.h"
#include "quizrunner_closefile.h"
#include "quizrunner_createbuffer.h"
#include "quizrunner_openfile.h"
#include "quizrunner_writetobuffer.h"
#include "quizrunner_printlist.h"
#include "quizrunner_addlistelement.h"
#include "quizrunner_dataextract.h"
#include "quizrunner_dataexchange.h"
#include "quizrunner_datacompare.h"
#include "quizrunner_crlfbufferfix.h"
#include "ctest.h"
#define MAX_PATH (260)
#ifndef _QUIZRUNNER_NODESTRUCT_DEFINE
#define _QUIZRUNNER_NODESTRUCT_DEFINE
typedef struct node {
struct node * next;
struct node * prev;
char * data;
} node_t;
#endif
int debug = 0;
CTEST(file_operations, changedir_1) {
char dirpath[MAX_PATH] = "ctest_env";
const int result = quizrunner_changedir(dirpath, debug);
const int expected = 0;
ASSERT_EQUAL(expected, result);
}
CTEST(file_operations, changedir_2) {
char dirpath[MAX_PATH] = "\\/?*()<>|";
const int result = quizrunner_changedir(dirpath, debug);
const int expected = 1;
ASSERT_EQUAL(expected, result);
}
CTEST(file_operations, changedir_3) {
char dirpath[MAX_PATH] = "";
const int result = quizrunner_changedir(dirpath, debug);
const int expected = 1;
ASSERT_EQUAL(expected, result);
}
CTEST(file_operations, openfile_1) {
FILE * ptrFile = NULL;
const int result = quizrunner_openfile(&ptrFile, "test.txt", debug, "rb");
const int expected = 0;
ASSERT_EQUAL(expected, result);
}
CTEST(file_operations, openfile_2) {
FILE * ptrFile = NULL;
const int result = quizrunner_openfile(&ptrFile, "\\/?*()<>|", debug, "rb");
const int expected = 1;
ASSERT_EQUAL(expected, result);
}
CTEST(file_operations, openfile_3) {
FILE * ptrFile = NULL;
const int result = quizrunner_openfile(&ptrFile, "", debug, "rb");
const int expected = 1;
ASSERT_EQUAL(expected, result);
}
CTEST(file_operations, closefile_1) {
FILE * ptrFile = NULL;
const int result = quizrunner_closefile(&ptrFile, debug);;
const int expected = 1;
ASSERT_EQUAL(expected, result);
}
CTEST(file_operations, closefile_2) {
FILE * ptrFile = NULL;
quizrunner_openfile(&ptrFile, "test.txt", debug, "rb");
const int result = quizrunner_closefile(&ptrFile, debug);;
const int expected = 0;
ASSERT_EQUAL(expected, result);
}
CTEST(code_operations, createbuffer_1) {
FILE * ptrFile = NULL;
quizrunner_openfile(&ptrFile, "test.txt", debug, "rb");
unsigned long int ptrFileSize = 0;
char * ptrFileBuffer = NULL;
const int result = quizrunner_createbuffer(&ptrFile, &ptrFileSize, &ptrFileBuffer, debug);
const int expected = 0;
ASSERT_EQUAL(expected, result);
}
CTEST(code_operations, createbuffer_2) {
FILE * ptrFile = NULL;
quizrunner_openfile(&ptrFile, "410346.jpg", debug, "rb");
unsigned long int ptrFileSize = 0;
char * ptrFileBuffer = NULL;
const int result = quizrunner_createbuffer(&ptrFile, &ptrFileSize, &ptrFileBuffer, debug);
const int expected = 2;
ASSERT_EQUAL(expected, result);
}
CTEST(code_operations, createbuffer_3) {
FILE * ptrFile = NULL;
quizrunner_openfile(&ptrFile, "", debug, "rb");
unsigned long int ptrFileSize = 0;
char * ptrFileBuffer = NULL;
const int result = quizrunner_createbuffer(&ptrFile, &ptrFileSize, &ptrFileBuffer, debug);
const int expected = 1;
ASSERT_EQUAL(expected, result);
}
CTEST(code_operations, writetobuffer_1) {
FILE * ptrFile = NULL;
quizrunner_openfile(&ptrFile, "test.txt", debug, "rb");
unsigned long int ptrFileSize = 0;
char * ptrFileBuffer = NULL;
quizrunner_createbuffer(&ptrFile, &ptrFileSize, &ptrFileBuffer, debug);
unsigned long int ptrFileSizeRead = 0;
const int result = quizrunner_writetobuffer(&ptrFile, &ptrFileSize, &ptrFileSizeRead, &ptrFileBuffer, debug);
const int expected = 0;
ASSERT_EQUAL(expected, result);
}
CTEST(code_operations, writetobuffer_2) {
FILE * ptrFile = NULL;
quizrunner_openfile(&ptrFile, "", debug, "rb");
unsigned long int ptrFileSize = 0;
char * ptrFileBuffer = NULL;
quizrunner_createbuffer(&ptrFile, &ptrFileSize, &ptrFileBuffer, debug);
unsigned long int ptrFileSizeRead = 0;
const int result = quizrunner_writetobuffer(&ptrFile, &ptrFileSize, &ptrFileSizeRead, &ptrFileBuffer, debug);
const int expected = 1;
ASSERT_EQUAL(expected, result);
}
CTEST(code_operations, writetobuffer_3) {
FILE * ptrFile = NULL;
quizrunner_openfile(&ptrFile, "410346.jpg", debug, "rb");
unsigned long int ptrFileSize = 0;
char * ptrFileBuffer = NULL;
quizrunner_createbuffer(&ptrFile, &ptrFileSize, &ptrFileBuffer, debug);
unsigned long int ptrFileSizeRead = 0;
const int result = quizrunner_writetobuffer(&ptrFile, &ptrFileSize, &ptrFileSizeRead, &ptrFileBuffer, debug);
const int expected = 1;
ASSERT_EQUAL(expected, result);
}
CTEST(code_operations, printlist_1) {
node_t * head_listQuestion;
node_t * tail_listQuestion;
head_listQuestion = tail_listQuestion = malloc(sizeof(node_t));
head_listQuestion -> next = 0;
head_listQuestion -> prev = 0;
head_listQuestion -> data = 0;
const int result = quizrunner_printlist(head_listQuestion, debug);
const int expected = 0;
ASSERT_EQUAL(expected, result);
}
CTEST(code_operations, printlist_2) {
node_t * head_listQuestion;
node_t * tail_listQuestion;
head_listQuestion = tail_listQuestion = NULL;
const int result = quizrunner_printlist(head_listQuestion, debug);
const int expected = 1;
ASSERT_EQUAL(expected, result);
}
CTEST(code_operations, crlfbufferfix_1) {
FILE * ptrFile = NULL;
quizrunner_openfile(&ptrFile, "410346.jpg", debug, "rb");
unsigned long int ptrFileSize = 0;
char * ptrFileBuffer = NULL;
quizrunner_createbuffer(&ptrFile, &ptrFileSize, &ptrFileBuffer, debug);
unsigned long int ptrFileSizeRead = 0;
quizrunner_writetobuffer(&ptrFile, &ptrFileSize, &ptrFileSizeRead, &ptrFileBuffer, debug);
unsigned long int ptrFileSize_crlfbufferfix = 0;
char * ptrFileBuffer_crlfbufferfix = NULL;
const int result = quizrunner_crlfbufferfix(ptrFileSize, ptrFileBuffer, &ptrFileSize_crlfbufferfix, &ptrFileBuffer_crlfbufferfix, debug);
const int expected = 1;
ASSERT_EQUAL(expected, result);
}
CTEST(code_operations, crlfbufferfix_2) {
FILE * ptrFile = NULL;
quizrunner_openfile(&ptrFile, "", debug, "rb");
unsigned long int ptrFileSize = 0;
char * ptrFileBuffer = NULL;
quizrunner_createbuffer(&ptrFile, &ptrFileSize, &ptrFileBuffer, debug);
unsigned long int ptrFileSizeRead = 0;
quizrunner_writetobuffer(&ptrFile, &ptrFileSize, &ptrFileSizeRead, &ptrFileBuffer, debug);
unsigned long int ptrFileSize_crlfbufferfix = 0;
char * ptrFileBuffer_crlfbufferfix = NULL;
const int result = quizrunner_crlfbufferfix(ptrFileSize, ptrFileBuffer, &ptrFileSize_crlfbufferfix, &ptrFileBuffer_crlfbufferfix, debug);
const int expected = 1;
ASSERT_EQUAL(expected, result);
}
CTEST(code_operations, crlfbufferfix_3) {
FILE * ptrFile = NULL;
quizrunner_openfile(&ptrFile, "test.txt", debug, "rb");
unsigned long int ptrFileSize = 0;
char * ptrFileBuffer = NULL;
quizrunner_createbuffer(&ptrFile, &ptrFileSize, &ptrFileBuffer, debug);
unsigned long int ptrFileSizeRead = 0;
quizrunner_writetobuffer(&ptrFile, &ptrFileSize, &ptrFileSizeRead, &ptrFileBuffer, debug);
unsigned long int ptrFileSize_crlfbufferfix = 0;
char * ptrFileBuffer_crlfbufferfix = NULL;
const int result = quizrunner_crlfbufferfix(ptrFileSize, ptrFileBuffer, &ptrFileSize_crlfbufferfix, &ptrFileBuffer_crlfbufferfix, debug);
const int expected = 0;
ASSERT_EQUAL(expected, result);
}
CTEST(code_operations, dataextract_1) {
FILE * ptrFile = NULL;
quizrunner_openfile(&ptrFile, "test.txt", debug, "rb");
unsigned long int ptrFileSize = 0;
char * ptrFileBuffer = NULL;
quizrunner_createbuffer(&ptrFile, &ptrFileSize, &ptrFileBuffer, debug);
unsigned long int ptrFileSizeRead = 0;
quizrunner_writetobuffer(&ptrFile, &ptrFileSize, &ptrFileSizeRead, &ptrFileBuffer, debug);
quizrunner_closefile(&ptrFile, debug);
char ** quiz_detailsBuffer = 0;
quiz_detailsBuffer = malloc(sizeof(char *) * 4);
quiz_detailsBuffer[0] = NULL;
quiz_detailsBuffer[1] = NULL;
quiz_detailsBuffer[2] = NULL;
quiz_detailsBuffer[3] = NULL;
node_t * head_listQuestion;
node_t * tail_listQuestion;
head_listQuestion = tail_listQuestion = malloc(sizeof(node_t));
head_listQuestion -> next = 0;
head_listQuestion -> prev = 0;
head_listQuestion -> data = 0;
node_t * head_listAnswer;
node_t * tail_listAnswer;
head_listAnswer = tail_listAnswer = malloc(sizeof(node_t));
head_listAnswer -> next = 0;
head_listAnswer -> prev = 0;
head_listAnswer -> data = 0;
node_t * head_listInput;
node_t * tail_listInput;
head_listInput = tail_listInput = malloc(sizeof(node_t));
head_listInput -> next = 0;
head_listInput -> prev = 0;
head_listInput -> data = 0;
unsigned long int quiz_propAmount_Questions = 0;
unsigned long int quiz_propAmount_Answers = 0;
const int result = quizrunner_dataextract(ptrFileSize, &ptrFileBuffer, debug, &quiz_detailsBuffer, &tail_listQuestion, &tail_listAnswer, &quiz_propAmount_Questions, &quiz_propAmount_Answers);
const int expected = 0;
ASSERT_EQUAL(expected, result);
}
CTEST(code_operations, dataextract_2) {
FILE * ptrFile = NULL;
quizrunner_openfile(&ptrFile, "failtest01.txt", debug, "rb");
unsigned long int ptrFileSize = 0;
char * ptrFileBuffer = NULL;
quizrunner_createbuffer(&ptrFile, &ptrFileSize, &ptrFileBuffer, debug);
unsigned long int ptrFileSizeRead = 0;
quizrunner_writetobuffer(&ptrFile, &ptrFileSize, &ptrFileSizeRead, &ptrFileBuffer, debug);
quizrunner_closefile(&ptrFile, debug);
char ** quiz_detailsBuffer = 0;
quiz_detailsBuffer = malloc(sizeof(char *) * 4);
quiz_detailsBuffer[0] = NULL;
quiz_detailsBuffer[1] = NULL;
quiz_detailsBuffer[2] = NULL;
quiz_detailsBuffer[3] = NULL;
node_t * head_listQuestion;
node_t * tail_listQuestion;
head_listQuestion = tail_listQuestion = malloc(sizeof(node_t));
head_listQuestion -> next = 0;
head_listQuestion -> prev = 0;
head_listQuestion -> data = 0;
node_t * head_listAnswer;
node_t * tail_listAnswer;
head_listAnswer = tail_listAnswer = malloc(sizeof(node_t));
head_listAnswer -> next = 0;
head_listAnswer -> prev = 0;
head_listAnswer -> data = 0;
node_t * head_listInput;
node_t * tail_listInput;
head_listInput = tail_listInput = malloc(sizeof(node_t));
head_listInput -> next = 0;
head_listInput -> prev = 0;
head_listInput -> data = 0;
unsigned long int quiz_propAmount_Questions = 0;
unsigned long int quiz_propAmount_Answers = 0;
const int result = quizrunner_dataextract(ptrFileSize, &ptrFileBuffer, debug, &quiz_detailsBuffer, &tail_listQuestion, &tail_listAnswer, &quiz_propAmount_Questions, &quiz_propAmount_Answers);
const int expected = 2;
ASSERT_EQUAL(expected, result);
}
CTEST(code_operations, dataextract_3) {
FILE * ptrFile = NULL;
quizrunner_openfile(&ptrFile, "failtest01.txt", debug, "rb");
unsigned long int ptrFileSize = 0;
char * ptrFileBuffer = NULL;
quizrunner_createbuffer(&ptrFile, &ptrFileSize, &ptrFileBuffer, debug);
unsigned long int ptrFileSizeRead = 0;
quizrunner_writetobuffer(&ptrFile, &ptrFileSize, &ptrFileSizeRead, &ptrFileBuffer, debug);
quizrunner_closefile(&ptrFile, debug);
char ** quiz_detailsBuffer = 0;
quiz_detailsBuffer = NULL;
node_t * head_listQuestion;
node_t * tail_listQuestion;
head_listQuestion = tail_listQuestion = malloc(sizeof(node_t));
head_listQuestion -> next = 0;
head_listQuestion -> prev = 0;
head_listQuestion -> data = 0;
node_t * head_listAnswer;
node_t * tail_listAnswer;
head_listAnswer = tail_listAnswer = malloc(sizeof(node_t));
head_listAnswer -> next = 0;
head_listAnswer -> prev = 0;
head_listAnswer -> data = 0;
node_t * head_listInput;
node_t * tail_listInput;
head_listInput = tail_listInput = malloc(sizeof(node_t));
head_listInput -> next = 0;
head_listInput -> prev = 0;
head_listInput -> data = 0;
unsigned long int quiz_propAmount_Questions = 0;
unsigned long int quiz_propAmount_Answers = 0;
const int result = quizrunner_dataextract(ptrFileSize, &ptrFileBuffer, debug, &quiz_detailsBuffer, &tail_listQuestion, &tail_listAnswer, &quiz_propAmount_Questions, &quiz_propAmount_Answers);
const int expected = 1;
ASSERT_EQUAL(expected, result);
} | 2.484375 | 2 |
2024-11-18T19:02:43.179047+00:00 | 2016-05-15T17:40:42 | 041e38bb14ec21e076e59e253d034ebf18682dfb | {
"blob_id": "041e38bb14ec21e076e59e253d034ebf18682dfb",
"branch_name": "refs/heads/master",
"committer_date": "2016-05-15T17:40:42",
"content_id": "3b00e7b1e537103e45626a846042551f84e31aab",
"detected_licenses": [
"MIT"
],
"directory_id": "10e88f94ed3fc455905121bc91cf4c2eb34f5d47",
"extension": "c",
"filename": "w_hypot.c",
"fork_events_count": 6,
"gha_created_at": "2015-01-17T23:21:06",
"gha_event_created_at": "2016-05-15T17:44:22",
"gha_language": "C++",
"gha_license_id": null,
"github_id": 29409202,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 928,
"license": "MIT",
"license_type": "permissive",
"path": "/src/fdlibm/src/w_hypot.c",
"provenance": "stackv2-0058.json.gz:160038",
"repo_name": "truthcoin/truthcoin-cpp",
"revision_date": "2016-05-15T17:40:42",
"revision_id": "a85161e8a2bbb6bc4d0a5553403f0b8b1f9ac529",
"snapshot_id": "0a4dc7d33d5bb6f651380671597141952e27b3c3",
"src_encoding": "UTF-8",
"star_events_count": 35,
"url": "https://raw.githubusercontent.com/truthcoin/truthcoin-cpp/a85161e8a2bbb6bc4d0a5553403f0b8b1f9ac529/src/fdlibm/src/w_hypot.c",
"visit_date": "2021-01-18T06:46:39.325525"
} | stackv2 |
/* @(#)w_hypot.c 1.3 95/01/18 */
/*
* ====================================================
* Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
*
* Developed at SunSoft, a Sun Microsystems, Inc. business.
* Permission to use, copy, modify, and distribute this
* software is freely granted, provided that this notice
* is preserved.
* ====================================================
*/
/*
* wrapper FDLIBM_hypot(x,y)
*/
#include "fdlibm.h"
#ifdef __STDC__
double FDLIBM_hypot(double x, double y)/* wrapper hypot */
#else
double FDLIBM_hypot(x,y) /* wrapper hypot */
double x,y;
#endif
{
#ifdef _IEEE_LIBM
return FDLIBM___ieee754_hypot(x,y);
#else
double z;
z = FDLIBM___ieee754_hypot(x,y);
if(_LIB_VERSION == _IEEE_) return z;
if((!FDLIBM_finite(z))&&FDLIBM_finite(x)&&FDLIBM_finite(y))
return FDLIBM___kernel_standard(x,y,4); /* hypot overflow */
else
return z;
#endif
}
| 2.0625 | 2 |
2024-11-18T19:02:44.757940+00:00 | 2022-07-25T13:15:02 | 5cdf3558a48dd6bab475f4dcbc76cc60c39b2d43 | {
"blob_id": "5cdf3558a48dd6bab475f4dcbc76cc60c39b2d43",
"branch_name": "refs/heads/master",
"committer_date": "2022-07-25T13:15:02",
"content_id": "dfa65af3bad750833d4f617a90399c4273836118",
"detected_licenses": [
"CC0-1.0"
],
"directory_id": "5b3407d5dd7e9159c246461b43338a628d51d6d1",
"extension": "c",
"filename": "encoder.c",
"fork_events_count": 18,
"gha_created_at": "2019-04-02T07:46:00",
"gha_event_created_at": "2022-07-25T13:15:03",
"gha_language": "C",
"gha_license_id": "CC0-1.0",
"github_id": 179025654,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 10120,
"license": "CC0-1.0",
"license_type": "permissive",
"path": "/src/encoder.c",
"provenance": "stackv2-0058.json.gz:160810",
"repo_name": "bergzand/NanoCBOR",
"revision_date": "2022-07-25T13:15:02",
"revision_id": "1bc789705057c42be32aea17aeec97763aece3c7",
"snapshot_id": "dbba49098fd1efd73d010875384bc316a18789c9",
"src_encoding": "UTF-8",
"star_events_count": 43,
"url": "https://raw.githubusercontent.com/bergzand/NanoCBOR/1bc789705057c42be32aea17aeec97763aece3c7/src/encoder.c",
"visit_date": "2022-11-16T07:02:02.791775"
} | stackv2 | /*
* SPDX-License-Identifier: CC0-1.0
*/
/**
* @ingroup nanocbor
* @{
* @file
* @brief Minimalistic CBOR encoder implementation
*
* @author Koen Zandberg <[email protected]>
* @}
*/
#include <stddef.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include "nanocbor/config.h"
#include "nanocbor/nanocbor.h"
#include NANOCBOR_BYTEORDER_HEADER
void nanocbor_encoder_init(nanocbor_encoder_t *enc, uint8_t *buf, size_t len)
{
enc->len = 0;
enc->cur = buf;
enc->end = buf + len;
}
size_t nanocbor_encoded_len(nanocbor_encoder_t *enc)
{
return enc->len;
}
static int _fits(nanocbor_encoder_t *enc, size_t len)
{
enc->len += len;
return ((size_t)(enc->end - enc->cur) >= len) ? (int)len : NANOCBOR_ERR_END;
}
static int _fmt_single(nanocbor_encoder_t *enc, uint8_t single)
{
int res = _fits(enc, 1);
if (res == 1) {
*enc->cur++ = single;
}
return res;
}
int nanocbor_fmt_bool(nanocbor_encoder_t *enc, bool content)
{
uint8_t single = NANOCBOR_MASK_FLOAT
| (content ? NANOCBOR_SIMPLE_TRUE : NANOCBOR_SIMPLE_FALSE);
return _fmt_single(enc, single);
}
static int _fmt_uint64(nanocbor_encoder_t *enc, uint64_t num, uint8_t type)
{
unsigned extrabytes = 0;
if (num < NANOCBOR_SIZE_BYTE) {
type |= num;
}
else {
if (num > UINT32_MAX) {
/* Requires long size */
type |= NANOCBOR_SIZE_LONG;
extrabytes = sizeof(uint64_t);
}
else if (num > UINT16_MAX) {
/* At least word size */
type |= NANOCBOR_SIZE_WORD;
extrabytes = sizeof(uint32_t);
}
else if (num > UINT8_MAX) {
type |= NANOCBOR_SIZE_SHORT;
extrabytes = sizeof(uint16_t);
}
else {
type |= NANOCBOR_SIZE_BYTE;
extrabytes = sizeof(uint8_t);
}
}
int res = _fits(enc, extrabytes + 1);
if (res > 0) {
*enc->cur++ = type;
/* NOLINTNEXTLINE: user supplied function */
uint64_t benum = NANOCBOR_HTOBE64_FUNC(num);
memcpy(enc->cur, (uint8_t *)&benum + sizeof(benum) - extrabytes,
extrabytes);
enc->cur += extrabytes;
}
return res;
}
int nanocbor_fmt_uint(nanocbor_encoder_t *enc, uint64_t num)
{
return _fmt_uint64(enc, num, NANOCBOR_MASK_UINT);
}
int nanocbor_fmt_tag(nanocbor_encoder_t *enc, uint64_t num)
{
return _fmt_uint64(enc, num, NANOCBOR_MASK_TAG);
}
int nanocbor_fmt_int(nanocbor_encoder_t *enc, int64_t num)
{
if (num < 0) {
/* Always negative at this point */
num = -(num + 1);
return _fmt_uint64(enc, (uint64_t)num, NANOCBOR_MASK_NINT);
}
return nanocbor_fmt_uint(enc, (uint64_t)num);
}
int nanocbor_fmt_bstr(nanocbor_encoder_t *enc, size_t len)
{
return _fmt_uint64(enc, (uint64_t)len, NANOCBOR_MASK_BSTR);
}
int nanocbor_fmt_tstr(nanocbor_encoder_t *enc, size_t len)
{
return _fmt_uint64(enc, (uint64_t)len, NANOCBOR_MASK_TSTR);
}
static int _put_bytes(nanocbor_encoder_t *enc, const uint8_t *str, size_t len)
{
int res = _fits(enc, len);
if (res >= 0) {
memcpy(enc->cur, str, len);
enc->cur += len;
return NANOCBOR_OK;
}
return res;
}
int nanocbor_put_tstr(nanocbor_encoder_t *enc, const char *str)
{
size_t len = strlen(str);
nanocbor_fmt_tstr(enc, len);
return _put_bytes(enc, (const uint8_t *)str, len);
}
int nanocbor_put_tstrn(nanocbor_encoder_t *enc, const char *str, size_t len)
{
nanocbor_fmt_tstr(enc, len);
return _put_bytes(enc, (const uint8_t *)str, len);
}
int nanocbor_put_bstr(nanocbor_encoder_t *enc, const uint8_t *str, size_t len)
{
nanocbor_fmt_bstr(enc, len);
return _put_bytes(enc, str, len);
}
int nanocbor_fmt_array(nanocbor_encoder_t *enc, size_t len)
{
return _fmt_uint64(enc, (uint64_t)len, NANOCBOR_MASK_ARR);
}
int nanocbor_fmt_map(nanocbor_encoder_t *enc, size_t len)
{
return _fmt_uint64(enc, (uint64_t)len, NANOCBOR_MASK_MAP);
}
int nanocbor_fmt_array_indefinite(nanocbor_encoder_t *enc)
{
return _fmt_single(enc, NANOCBOR_MASK_ARR | NANOCBOR_SIZE_INDEFINITE);
}
int nanocbor_fmt_map_indefinite(nanocbor_encoder_t *enc)
{
return _fmt_single(enc, NANOCBOR_MASK_MAP | NANOCBOR_SIZE_INDEFINITE);
}
int nanocbor_fmt_end_indefinite(nanocbor_encoder_t *enc)
{
/* End is marked with float major and indefinite minor number */
return _fmt_single(enc, NANOCBOR_MASK_FLOAT | NANOCBOR_SIZE_INDEFINITE);
}
int nanocbor_fmt_null(nanocbor_encoder_t *enc)
{
return _fmt_single(enc, NANOCBOR_MASK_FLOAT | NANOCBOR_SIMPLE_NULL);
}
/* Double bit mask related defines */
#define DOUBLE_EXP_OFFSET (1023U)
#define DOUBLE_SIZE (64U)
#define DOUBLE_EXP_POS (52U)
#define DOUBLE_SIGN_POS (63U)
#define DOUBLE_EXP_MASK ((uint64_t)0x7FFU)
#define DOUBLE_SIGN_MASK ((uint64_t)1U << DOUBLE_SIGN_POS)
#define DOUBLE_EXP_IS_NAN (0x7FFU)
#define DOUBLE_IS_ZERO (~(DOUBLE_SIGN_MASK))
#define DOUBLE_FLOAT_LOSS (0x1FFFFFFFU)
/* float bit mask related defines */
#define FLOAT_EXP_OFFSET (127U)
#define FLOAT_SIZE (32U)
#define FLOAT_EXP_POS (23U)
#define FLOAT_EXP_MASK ((uint32_t)0xFFU)
#define FLOAT_SIGN_POS (31U)
#define FLOAT_FRAC_MASK (0x7FFFFFU)
#define FLOAT_SIGN_MASK ((uint32_t)1U << FLOAT_SIGN_POS)
#define FLOAT_EXP_IS_NAN (0xFFU)
#define FLOAT_IS_ZERO (~(FLOAT_SIGN_MASK))
/* Part where a float to halffloat leads to precision loss */
#define FLOAT_HALF_LOSS (0x1FFFU)
/* halffloat bit mask related defines */
#define HALF_EXP_OFFSET (15U)
#define HALF_SIZE (16U)
#define HALF_EXP_POS (10U)
#define HALF_EXP_MASK (0x1FU)
#define HALF_SIGN_POS (15U)
#define HALF_FRAC_MASK (0x3FFU)
#define HALF_SIGN_MASK ((uint16_t)(1U << HALF_SIGN_POS))
#define HALF_MASK_HALF (0xFFU)
/* Check special cases for single precision floats */
static bool _single_is_inf_nan(uint8_t exp)
{
return exp == FLOAT_EXP_IS_NAN;
}
static bool _single_is_zero(uint32_t num)
{
return (num & FLOAT_IS_ZERO) == 0;
}
static bool _single_in_range(uint8_t exp, uint32_t num)
{
/* Check if lower 13 bits of fraction are zero, if so we might be able to
* convert without precision loss */
if (exp <= (HALF_EXP_OFFSET + FLOAT_EXP_OFFSET)
&& exp >= ((-HALF_EXP_OFFSET + 1) + FLOAT_EXP_OFFSET)
&& ((num & FLOAT_HALF_LOSS) == 0)) {
return true;
}
return false;
}
static int _fmt_halffloat(nanocbor_encoder_t *enc, uint16_t half)
{
int res = _fits(enc, sizeof(uint16_t) + 1);
if (res > 0) {
*enc->cur++ = NANOCBOR_MASK_FLOAT | NANOCBOR_SIZE_SHORT;
*enc->cur++ = (half >> HALF_SIZE / 2);
*enc->cur++ = half & HALF_MASK_HALF;
res = sizeof(uint16_t) + 1;
}
return res;
}
#if __SIZEOF_DOUBLE__ != __SIZEOF_FLOAT__
/* Check special cases for single precision floats */
static bool _double_is_inf_nan(uint16_t exp)
{
return (exp == DOUBLE_EXP_IS_NAN);
}
static bool _double_is_zero(uint64_t num)
{
return (num & DOUBLE_IS_ZERO) == 0;
}
static bool _double_in_range(uint16_t exp, uint64_t num)
{
/* Check if lower 13 bits of fraction are zero, if so we might be able to
* convert without precision loss */
if (exp <= (DOUBLE_EXP_OFFSET + FLOAT_EXP_OFFSET)
&& exp >= (DOUBLE_EXP_OFFSET - FLOAT_EXP_OFFSET + 1)
&& ((num & DOUBLE_FLOAT_LOSS) == 0)) { /* First 29 bits must be zero */
return true;
}
return false;
}
#endif
int nanocbor_fmt_float(nanocbor_encoder_t *enc, float num)
{
/* Allow bitwise access to float */
uint32_t *unum = (uint32_t *)#
/* Retrieve exponent */
uint8_t exp = (*unum >> FLOAT_EXP_POS) & FLOAT_EXP_MASK;
if (_single_is_inf_nan(exp) || _single_is_zero(*unum)
|| _single_in_range(exp, *unum)) {
/* Copy sign bit */
uint16_t half = ((*unum >> (FLOAT_SIZE - HALF_SIZE)) & HALF_SIGN_MASK);
/* Shift exponent */
if (exp != FLOAT_EXP_IS_NAN && exp != 0) {
exp = exp + (uint8_t)(HALF_EXP_OFFSET - FLOAT_EXP_OFFSET);
}
/* Add exponent */
half |= ((exp & HALF_EXP_MASK) << HALF_EXP_POS)
| ((*unum >> (FLOAT_EXP_POS - HALF_EXP_POS)) & HALF_FRAC_MASK);
return _fmt_halffloat(enc, half);
}
/* normal float */
int res = _fits(enc, 1 + sizeof(float));
if (res > 0) {
*enc->cur++ = NANOCBOR_MASK_FLOAT | NANOCBOR_SIZE_WORD;
/* NOLINTNEXTLINE: user supplied function */
uint32_t bnum = NANOCBOR_HTOBE32_FUNC(*unum);
memcpy(enc->cur, &bnum, sizeof(bnum));
enc->cur += sizeof(float);
}
return res;
}
int nanocbor_fmt_double(nanocbor_encoder_t *enc, double num)
{
#if __SIZEOF_DOUBLE__ == __SIZEOF_FLOAT__
return nanocbor_fmt_float(enc, num);
#else
uint64_t *unum = (uint64_t *)#
uint16_t exp = (*unum >> DOUBLE_EXP_POS) & DOUBLE_EXP_MASK;
if (_double_is_inf_nan(exp) || _double_is_zero(*unum)
|| _double_in_range(exp, *unum)) {
/* copy sign bit over */
uint32_t single
= (*unum >> (DOUBLE_SIZE - FLOAT_SIZE)) & (FLOAT_SIGN_MASK);
/* Shift exponent */
if (exp != DOUBLE_EXP_IS_NAN && exp != 0) {
exp = exp + FLOAT_EXP_OFFSET - DOUBLE_EXP_OFFSET;
}
single |= ((exp & FLOAT_EXP_MASK) << FLOAT_EXP_POS)
| ((*unum >> (DOUBLE_EXP_POS - FLOAT_EXP_POS)) & FLOAT_FRAC_MASK);
float *fsingle = (float *)&single;
return nanocbor_fmt_float(enc, *fsingle);
}
int res = _fits(enc, 1 + sizeof(double));
if (res > 0) {
*enc->cur++ = NANOCBOR_MASK_FLOAT | NANOCBOR_SIZE_LONG;
/* NOLINTNEXTLINE: user supplied function */
uint64_t bnum = NANOCBOR_HTOBE64_FUNC(*unum);
memcpy(enc->cur, &bnum, sizeof(bnum));
enc->cur += sizeof(double);
}
return res;
#endif
}
int nanocbor_fmt_decimal_frac(nanocbor_encoder_t *enc, int32_t e, int32_t m)
{
int res = nanocbor_fmt_tag(enc, NANOCBOR_TAG_DEC_FRAC);
res += nanocbor_fmt_array(enc, 2);
res += nanocbor_fmt_int(enc, e);
res += nanocbor_fmt_int(enc, m);
return res;
}
| 2.734375 | 3 |
2024-11-18T19:02:44.934277+00:00 | 2020-08-18T10:43:36 | 2029f8407fd1cf47681a3d23210a590cca716983 | {
"blob_id": "2029f8407fd1cf47681a3d23210a590cca716983",
"branch_name": "refs/heads/master",
"committer_date": "2020-08-18T10:43:36",
"content_id": "788b30641e1bb2f0b1051487de4b2aa90c9e7993",
"detected_licenses": [
"MIT"
],
"directory_id": "9d52aced613fcafd22bdb93e8c2d65dc237531e0",
"extension": "c",
"filename": "passwd_scan.c",
"fork_events_count": 0,
"gha_created_at": "2020-08-17T13:29:35",
"gha_event_created_at": "2020-08-18T10:43:37",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 288187926,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 10613,
"license": "MIT",
"license_type": "permissive",
"path": "/src/scans/passwd_scan.c",
"provenance": "stackv2-0058.json.gz:161066",
"repo_name": "johnthesecond/enumy",
"revision_date": "2020-08-18T10:43:36",
"revision_id": "e22c767653ad4b3c784ec4d8ad1ddc21644b69ba",
"snapshot_id": "9c6e00ab600ea8708f3e1b7fd88fafdf6bc0c9d3",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/johnthesecond/enumy/e22c767653ad4b3c784ec4d8ad1ddc21644b69ba/src/scans/passwd_scan.c",
"visit_date": "2022-12-01T04:40:52.554741"
} | stackv2 | /*
The passwd scan is used to parse /etc/passwd, once parsed we can
run a few basic checks (seen below). And we use this parsed information
in other scans.
1. Report all users with UID 0
2. Report all users with GID 0
3. Report all users with out /nologin
3. Report all users with invalid home directory
4. Report all users where the login shell has weak permissions
5. Check to see if password hashes are stored here
*/
#include "file_system.h"
#include "results.h"
#include "scan.h"
#include "error_logger.h"
#include "main.h"
#include "vector.h"
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <limits.h>
/* ============================ PROTOTYPES ============================== */
char *PasswdLoc = "/etc/passwd";
/* ============================ PROTOTYPES ============================== */
vec_void_t *passwd_scan(All_Results *ar);
void free_users(vec_void_t *users);
static void check_uid(Parsed_Passwd_Line *current, All_Results *ar);
static void check_gid(Parsed_Passwd_Line *current, All_Results *ar);
static void check_login_shell(Parsed_Passwd_Line *current, All_Results *ar);
static void check_home_exists(Parsed_Passwd_Line *current, All_Results *ar);
static void check_password_hashes(Parsed_Passwd_Line *current, All_Results *ar);
static vec_void_t *parse_etc_passwd(All_Results *ar);
static bool parse_etc_passwd_line(char *current_line, Parsed_Passwd_Line *storage, All_Results *ar);
static bool parse_int(char *s, unsigned int *i_ptr);
/* ============================ FUNCTIONS ============================== */
/**
* This function will read and parse the /etc/passwd file and then run various
* scans against the contents of this file.
* @param ar Enumy's results struct
* @return Returns a vector containing pointers to Parsed_Passwd_line
*/
vec_void_t *passwd_scan(All_Results *ar)
{
/* Parse /etc/passwd */
vec_void_t *contents = parse_etc_passwd(ar);
if (!contents)
return NULL;
/* Loop threw each parsed /etc/passwd entry */
for (int i = 0; i < contents->length; i++)
{
check_uid((Parsed_Passwd_Line *)contents->data[i], ar);
check_gid((Parsed_Passwd_Line *)contents->data[i], ar);
check_login_shell((Parsed_Passwd_Line *)contents->data[i], ar);
check_home_exists((Parsed_Passwd_Line *)contents->data[i], ar);
check_password_hashes((Parsed_Passwd_Line *)contents->data[i], ar);
}
return contents;
}
/**
* Deallocates the memory used by calling passwd_scan
* @param users vector containing pointers to Parsed_Passwd_line
*/
void free_users(vec_void_t *users)
{
for (int i = 0; i < users->length; i++)
free(users->data[i]);
vec_deinit(users);
}
/* ============================ STATIC FUNCTIONS ============================== */
/* ============================ SCAN FUNCTIONS ============================== */
/**
* This function finds root users with UID root
* @param current This is the current /etc/passwd line that has been parsed
* @param ar enumy's results
*/
static void check_uid(Parsed_Passwd_Line *current, All_Results *ar)
{
if (current->uid == 0)
{
char buf[MAXSIZE * 2];
snprintf(buf, (MAXSIZE * 2) - 1, "Found an new root user with UID 0: %s", current->username);
add_issue(INFO, CTF, PasswdLoc, ar, buf, "");
}
}
/**
* This function finds root users with GID root
* @param current This is the current /etc/passwd line that has been parsed
* @param ar enumy's results
*/
static void check_gid(Parsed_Passwd_Line *current, All_Results *ar)
{
if (current->gid == 0)
{
char buf[MAXSIZE * 2];
snprintf(buf, (MAXSIZE * 2) - 1, "Found an new root user with GID 0: %s", current->username);
add_issue(INFO, CTF, PasswdLoc, ar, buf, "");
}
}
/**
* This function find users that can be logged into, shells that don't exist
* and shells that are writable
* @param current This is the current /etc/passwd line that has been parsed
* @param ar enumy's results
*/
static void check_login_shell(Parsed_Passwd_Line *current, All_Results *ar)
{
/* Check if we can login */
if (strstr(current->shell, "nologin") != NULL)
return;
char buf[MAXSIZE * 2];
snprintf(buf, (MAXSIZE * 2) - 1, "Found an new user that can be logged into: %s", current->username);
add_issue(INFO, CTF, PasswdLoc, ar, buf, "");
/* Check if the file exsts */
if (access(current->home, F_OK) == -1)
{
add_issue(HIGH, CTF, current->shell, ar, "Found a new user that can be logged into a shell that does not exist", "");
return;
}
/* allocate memory for stat buffer */
struct stat *stat_buf = malloc(sizeof(struct stat));
if (stat_buf == NULL)
{
log_fatal_errno("Failed to allocate memory for stat buffer", errno);
exit(EXIT_FAILURE);
}
/* Perform the stat */
if (stat(current->shell, stat_buf) != 0)
{
log_error_errno_loc(ar, "Failed to run stat on file", current->shell, errno);
free(stat_buf);
return;
}
/* Test if the login shell is writable */
if (stat_buf->st_mode & S_IWOTH)
add_issue(HIGH, CTF, current->shell, ar, "Found a that's login shell is writable", "");
free(stat_buf);
return;
}
/**
* Checks that the users home directory exists
* @param current This is the current /etc/passwd line that has been parsed
* @param ar enumy's results
*/
static void check_home_exists(Parsed_Passwd_Line *current, All_Results *ar)
{
if (access(current->home, F_OK) == -1)
add_issue(HIGH, CTF, current->home, ar, "Found a home directory that does not exist, but is attached to an existing user", current->username);
}
/**
* Checks to see if password hashes are stored in /etc/passwd
* @param current This is the current /etc/passwd line that has been parsed
* @param ar enumy's results
*/
static void check_password_hashes(Parsed_Passwd_Line *current, All_Results *ar)
{
if (strcmp("x", current->password) != 0)
add_issue(HIGH, CTF, PasswdLoc, ar, "Found password hashes in /etc/passwd", "");
}
/* ============================ PARSING FUNCTIONS ============================== */
/**
* This function will parse the contents of /etc/passwd and return a vector
* @param ar enumy's results
* @returns a pointer to a vector containing the Parsed_Passwd_Line or NULL on error
*/
static vec_void_t *parse_etc_passwd(All_Results *ar)
{
char current_line[MAXSIZE] = "";
FILE *fp;
/* Allocate memory for the vector */
vec_void_t *passwd_vec = malloc(sizeof(vec_void_t));
if (!passwd_vec)
{
log_fatal_errno("Failed to allocate memory for the passwd vector", errno);
exit(EXIT_FAILURE);
}
/* Initilize the vector */
vec_init(passwd_vec);
/* Open /etc/passwd */
fp = fopen(PasswdLoc, "r");
if (!fp)
{
log_error_errno_loc(ar, "Failed to open passwd file", PasswdLoc, errno);
vec_deinit(passwd_vec);
free(passwd_vec);
return NULL;
}
/* Loop through each line */
while (fgets(current_line, sizeof current_line, fp))
{
/* Allocate memory for the parsed line struct */
Parsed_Passwd_Line *current_parsed_line = (Parsed_Passwd_Line *)malloc(sizeof(Parsed_Passwd_Line));
if (!current_parsed_line)
{
log_fatal_errno("Failed to allocate memory for the parsed passwd line struct", errno);
exit(EXIT_FAILURE);
}
/* Actually parse the line */
if (parse_etc_passwd_line(current_line, (Parsed_Passwd_Line *)current_parsed_line, ar))
vec_push(passwd_vec, current_parsed_line);
else
free(current_parsed_line);
}
fclose(fp);
return passwd_vec;
}
/**
* This function will take a single line from /etc/password and tokenize the contents of the line
* into the storage struct.
* @param current_line The current line to parse
* @param storage The place to store the tokenized line
* @param ar All the results (needed for the logger)
*/
static bool parse_etc_passwd_line(char *current_line, Parsed_Passwd_Line *storage, All_Results *ar)
{
/* 0 :1 :2 :3 :4 :5 :6 */
/* username:password:UID:GID:User_comment:home_dir:command */
int token_n = 0;
int char_count = 0;
int line_len = strlen(current_line);
char temp_buff[MAXSIZE] = {'\0'};
for (int x = 0; x < line_len; x++)
{
/* Tokenize the line */
if (current_line[x] == ':')
{
/* Username */
if (token_n == 0)
strncpy(storage->username, temp_buff, sizeof(storage->username));
/* Password */
else if (token_n == 1)
strncpy(storage->password, temp_buff, sizeof(storage->password));
/* UID */
else if (token_n == 2)
{
if (!parse_int(temp_buff, &storage->uid))
{
log_error_loc(ar, "Failed to parse UID in /etc/passwd, integer underflow/overflow", current_line);
return false;
}
}
/* GID */
else if (token_n == 3)
{
if (!parse_int(temp_buff, &storage->gid))
{
log_error_loc(ar, "Failed to parse GID in /etc/passwd, integer underflow/overflow", current_line);
return false;
}
}
/* Home */
else if (token_n == 5)
strncpy(storage->home, temp_buff, sizeof(storage->home));
/* Reset ready for the next field */
char_count = 0;
token_n++;
memset(temp_buff, '\0', sizeof(temp_buff));
continue;
}
/* Copy the current character into the temp buffer */
temp_buff[char_count] = current_line[x];
char_count++;
/* Shell */
if ((token_n == 6) || (x == line_len - 1))
strncpy(storage->shell, temp_buff, sizeof(storage->shell));
}
return true;
}
/**
* This function will convert string represetation of an int and convert it
* into an unsigned int
* @param s The int represented as a string
* @param i_ptr The place to save the int
*/
static bool parse_int(char *s, unsigned int *i_ptr)
{
long int temp_int = strtol(s, NULL, 10);
if (temp_int == LONG_MIN)
return false;
*i_ptr = (unsigned int)temp_int;
return true;
} | 2.421875 | 2 |
2024-11-18T19:02:45.479382+00:00 | 2020-09-20T22:54:28 | 174d7e99821f86e4b1014330e645bf9edc9a1f65 | {
"blob_id": "174d7e99821f86e4b1014330e645bf9edc9a1f65",
"branch_name": "refs/heads/master",
"committer_date": "2020-09-20T22:54:28",
"content_id": "68b1ad931e5e875c78e0b6de7fa634a854108d25",
"detected_licenses": [
"MIT"
],
"directory_id": "66525f9680d72df0bcd380361067fed7aca38c21",
"extension": "c",
"filename": "MainWork.c",
"fork_events_count": 0,
"gha_created_at": "2020-09-20T21:22:29",
"gha_event_created_at": "2020-09-20T22:54:29",
"gha_language": "C",
"gha_license_id": null,
"github_id": 297165976,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 18595,
"license": "MIT",
"license_type": "permissive",
"path": "/PSoC_Creator/PSU_PSoC5/PowerSuplyUnit.cydsn/MainWork.c",
"provenance": "stackv2-0058.json.gz:161194",
"repo_name": "viordash/PSoC5-PowerSupplyUnit",
"revision_date": "2020-09-20T22:54:28",
"revision_id": "04e2f7eb837a4ba37e6003d324529adaade84564",
"snapshot_id": "b351285f4e123139090f451828479f4fb89abee8",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/viordash/PSoC5-PowerSupplyUnit/04e2f7eb837a4ba37e6003d324529adaade84564/PSoC_Creator/PSU_PSoC5/PowerSuplyUnit.cydsn/MainWork.c",
"visit_date": "2022-12-18T07:11:55.653284"
} | stackv2 | /* ========================================
*
* Copyright YOUR COMPANY, THE YEAR
* All Rights Reserved
* UNPUBLISHED, LICENSED SOFTWARE.
*
* CONFIDENTIAL AND PROPRIETARY INFORMATION
* WHICH IS THE PROPERTY OF your company.
*
* ========================================
*/
#include <stdio.h>
#include <stdlib.h>
#include "MainWork.h"
#include "LCD_Display.h"
#include "Temperature\TemperControl.h"
#include "MousePS2\MousePS2.h"
#include "Regulator\RegulatorTask.h"
#include "Storage.h"
#include "Sleep.h"
#define BtnOk_Pressed 0x02
#define BtnOk_LongPress 0x01
#define MultiJog_Rotated 0x01
#define MultiJog_FastRotate 0x02
TFunction MainWorkFunction;
TMainWork_Object MainWorkObj;
void ChangeState(TMainWorkState newState);
void ProtectiveBehaviorChanged(BOOL btnPressed);
BOOL ProtectiveBehaviorIndicator();
void RefreshDisplay();
BOOL RiseRatePowerUpChanged(BOOL btnRiseRatePowerUpPressed);
void ButtonOkPressed(BYTE value);
void ButtonOnOrChangePolarityPressed (BYTE value);
void MultiJogChangingValue(BYTE value);
BOOL TemperatureControl();
void ChangeValue(INT shiftValue);
void UpdateAllSetPoints();
BOOL ErrorIndicator();
BOOL CheckRegulatorStatusCore(BYTE status);
BOOL CheckRegulatorStatus();
void ClearRegulatorStatusAndErrors();
void MainWork_Init() {
EEPROMStorage_Start();
RegulatorControl_Write(0x0A);
MainWorkObj.State = mwsInit;
MainWorkObj.ChangedValue = cvVoltageA;
MainWorkObj.StabilizeModeA = smVoltageStab;
MainWorkObj.StabilizeModeB = smAmperageStab;
InitMouse();
IdleTimer_Init();
}
void MainWork_Task(){
ChangeState(mwsStart);
LoadFromStorage();
UpdateAllSetPoints();
TaskSleep(&MainWorkFunction, SYSTICK_mS(2000)); //waiting for start screen
ChangeState(mwsStandBy);
RefreshDisplay();
ResetErrorState();
Regulator_ChangeStabilizeMode();
Buttons_Read();
BYTE prevButtons = 0xFF;
while (TRUE) {
CheckRegulatorStatus();
BYTE bt = Buttons_Read();
if (prevButtons != bt) {
if (prevButtons & 0x08 || bt & 0x08) {
ProtectiveBehaviorChanged(bt & 0x08);
}
if (prevButtons & 0x04 || bt & 0x04) {
RiseRatePowerUpChanged(bt & 0x04);
}
if (prevButtons & (BtnOk_LongPress | BtnOk_Pressed) || bt & (BtnOk_LongPress | BtnOk_Pressed)) {
ButtonOkPressed(bt & (BtnOk_LongPress | BtnOk_Pressed));
}
if (!(prevButtons & 0x10) && bt & 0x10) {
ButtonOnOrChangePolarityPressed(bt & 0x10);
}
prevButtons = bt;
IdleTimer_Reset();
}
bt = MultiJog_Status_Read();
if (bt & MultiJog_Rotated) {
MultiJogChangingValue(bt);
}
if (!MouseHandler(NULL, NULL)){
if(!TemperatureControl()) {
if (!ErrorIndicator()) {
if(!ProtectiveBehaviorIndicator()) {
if (!IdleTimer_Handle()) {
}
}
}
}
}
if (MainWorkObj.State == mwsWorkStarting) {
if (GetElapsedPeriod(MainWorkObj.WorkStartingPeriod) >= SYSTICK_mS(50)) { //delay for switch on output relay
ChangeState(mwsWork);
}
}
TaskSleep(&MainWorkFunction, SYSTICK_mS(50));
}
}
void ChangeState(TMainWorkState newState){
TMainWorkState oldState = MainWorkObj.State;
MainWorkObj.State = newState;
if (newState == mwsWorkStarting) {
ClearRegulatorStatusAndErrors();
BYTE ctrl = 0x15;
if (MainWorkObj.StabilizeModeA == smAmperageStab) {
ctrl |= 0x20;
} else {
if (MainWorkObj.StabilizeModeA == smVoltageStab && MainWorkObj.StabilizeModeB == smVoltageStab) {
BYTE bt = Buttons_Read();
if (MainWorkObj.MousePresent && !(bt & 0x10)) {//change polarity
ctrl |= 0x40;
}
}
}
if (MainWorkObj.StabilizeModeB == smAmperageStab) {
ctrl |= 0x80;
}
RegulatorControl_Write(ctrl);
MainWorkObj.WorkStartingPeriod = GetTickCount();
} else if (newState != mwsWork) {
O_OUT_POLARITY_Write(FALSE);
RegulatorControl_Write(0x0A);
}
if (oldState == mwsWork && newState == mwsStandBy) {
SaveToStorage();
} else if (oldState == mwsErrGlb && newState != mwsErrGlb) {
O_Led_Error_Write(FALSE);
}
Regulator_WorkStateChanged(oldState, newState);
Display_WorkStateChanged(oldState, newState);
IdleTimer_Reset();
}
void ChangeOutputState() {
if (MainWorkObj.State == mwsWork || MainWorkObj.State == mwsErrGlb) {
ChangeState(mwsStandBy);
} else if (MainWorkObj.State == mwsStandBy) {
ChangeState(mwsWorkStarting);
}
}
/*>>>-------------- Protective Sensitivity-----------------*/
void ProtectiveBehaviorChanged(BOOL btnPressed) {
if (btnPressed == 0) {
MainWorkObj.ProtectiveSensitivity = psWeak;
O_Led_ProtectiveSensitivity_Write(TRUE);
UpdateAllSetPoints();
} else {
MainWorkObj.ProtectiveSensitivity = psNormal;
O_Led_ProtectiveSensitivity_Write(FALSE);
UpdateAllSetPoints();
}
}
BOOL ProtectiveBehaviorIndicator() {
static DWORD protectiveSensitivityFlashTick = 0;
if (MainWorkObj.ProtectiveSensitivity != psWeak) {
return FALSE;
}
if (GetElapsedPeriod(protectiveSensitivityFlashTick) < SYSTICK_mS(500)) {
return FALSE;
}
protectiveSensitivityFlashTick = GetTickCount();
O_Led_ProtectiveSensitivity_Write(!O_Led_ProtectiveSensitivity_Read());
return TRUE;
}
/*----------------- Protective Sensitivity --------------<<<*/
/*>>>-------------- Rise rate of voltage at power-up -----------------*/
BOOL RiseRatePowerUpChanged(BOOL btnRiseRatePowerUpPressed) {
BOOL res = FALSE;
if (btnRiseRatePowerUpPressed) {
O_Led_RiseRatePowerUp_Write(0);
MainWorkObj.RiseRatePowerUp = rrpuFast;
} else {
O_Led_RiseRatePowerUp_Write(0xFF);
MainWorkObj.RiseRatePowerUp = rrpuSlow;
}
res = TRUE;
return res;
}
/*----------------- Rise rate of voltage at power-up --------------<<<*/
/*>>>-------------- Button Ok pressed -----------------*/
void ButtonOkPressed (BYTE value) {
if (!value) {
return;
}
if (MainWorkObj.State == mwsStandBy || MainWorkObj.State == mwsWork) {
if (!(value & BtnOk_LongPress)) {
if(MainWorkObj.State == mwsStandBy && IsDisplayInChangingStabilizeMode()) {
ConfirmSelectionStabilize();
} else if(!IsDisplayInSelectionMode()) {
SelectValue();
} else {
ConfirmSelection();
}
} else if (MainWorkObj.State == mwsStandBy) {
if(!IsDisplayInChangingStabilizeMode()) {
SelectStabilizeMode();
}
}
} else if (MainWorkObj.State == mwsErrGlb) {
ResetErrorState();
}
}
/*----------------- Button Ok pressed --------------<<<*/
/*>>>-------------- Button On or Change polarity pressed -----------------*/
void ButtonOnOrChangePolarityPressed (BYTE value) {
if (!value) {
return;
}
if (!MainWorkObj.MousePresent) {
ChangeOutputState();
}
}
/*----------------- Button On or Change polarity pressed --------------<<<*/
/*>>>-------------- MultiJog Changing Value -----------------*/
void MultiJogChangingValue (BYTE value) {
static DWORD prevTick = 0;
if (GetElapsedPeriod(prevTick) < SYSTICK_mS(100)) {
return;
}
prevTick = GetTickCount();
INT i = MultiJog_GetCounter();
MultiJog_SetCounter(0);
if(IsDisplayInSelectionMode()) {
if (i > 0) {
SelectNextIndicator();
} else if (i < 0) {
SelectPrevIndicator();
}
} else if(IsDisplayInChangingStabilizeMode()) {
if (i > 0) {
SelectNextStabilizeIndicator();
} else if (i < 0) {
SelectPrevStabilizeIndicator();
}
} else {
INT mult = 1;
if (value & MultiJog_FastRotate) {
mult = 10;
}
if (i) {
ChangeValue((i * mult));
}
}
}
/*----------------- MultiJog Changing Value --------------<<<*/
/*>>>-------------- Mouse Changing Value -----------------*/
void MouseState(BOOL present) {
RequestToVisibileMousePresent(present);
MainWorkObj.MousePresent = present;
}
void MouseChangingValue(INT value) {
ChangeValue(value);
IdleTimer_Reset();
}
/*----------------- Mouse Changing Value --------------<<<*/
/*>>>-------------- Temperature Control -----------------*/
BOOL TemperatureControl() {
static DWORD temperatureScanTick = 0;
if (GetElapsedPeriod(temperatureScanTick) < SYSTICK_mS(5000)) {
return FALSE;
}
temperatureScanTick = GetTickCount();
TTemperature temperatures = CheckTemper();
RequestToChangeTemperatures(temperatures);
return TRUE;
}
/*----------------- Temperature Control --------------<<<*/
/*>>>-------------- Change values -----------------*/
void IncrementValue(PTElectrValue pElectrValue, INT shiftValue, TElectrValue max, TElectrValue min) {
TElectrValue electrValue = *pElectrValue;
electrValue += shiftValue;
if (shiftValue < 0) {
if (electrValue < min || electrValue > max) {
electrValue = min;
}
} else if (electrValue < min) {
electrValue = min;
} else if (electrValue > max) {
electrValue = max;
}
*pElectrValue = electrValue;
}
void ChangeValue(INT shiftValue) {
TChangedValue changedValue = MainWorkObj.ChangedValue;
if (changedValue == cvAmperageA) {
IncrementValue(&MainWorkObj.SetPointAmperageA, shiftValue, Amperage_MAX, Amperage_MIN);
Regulator_RequestToChangeSetPointAmperageA(MainWorkObj.SetPointAmperageA);
Display_RequestToChangeValue(svSetPointAmperageA, MainWorkObj.SetPointAmperageA);
} else if (changedValue == cvVoltageB) {
IncrementValue(&MainWorkObj.SetPointVoltageB, shiftValue, Voltage_MAX, Voltage_MIN);
Regulator_RequestToChangeSetPointVoltageB(MainWorkObj.SetPointVoltageB);
Display_RequestToChangeValue(svSetPointVoltageB, MainWorkObj.SetPointVoltageB);
} else if (changedValue == cvAmperageB) {
IncrementValue(&MainWorkObj.SetPointAmperageB, shiftValue, Amperage_MAX, Amperage_MIN);
Regulator_RequestToChangeSetPointAmperageB(MainWorkObj.SetPointAmperageB);
Display_RequestToChangeValue(svSetPointAmperageB, MainWorkObj.SetPointAmperageB);
} else { //cvVoltageA
IncrementValue(&MainWorkObj.SetPointVoltageA, shiftValue, Voltage_MAX, Voltage_MIN);
Regulator_RequestToChangeSetPointVoltageA(MainWorkObj.SetPointVoltageA);
Display_RequestToChangeValue(svSetPointVoltageA, MainWorkObj.SetPointVoltageA);
}
}
void UpdateAllSetPoints() {
Regulator_RequestToChangeSetPointVoltageA(MainWorkObj.SetPointVoltageA);
Regulator_RequestToChangeSetPointAmperageA(MainWorkObj.SetPointAmperageA);
Regulator_RequestToChangeSetPointVoltageB(MainWorkObj.SetPointVoltageB);
Regulator_RequestToChangeSetPointAmperageB(MainWorkObj.SetPointAmperageB);
}
/*----------------- Change values --------------<<<*/
/*>>>-------------- Errors -----------------*/
void ThrowException(PCHAR message) {
ChangeState(mwsErrGlb);
RequestToShowMessage(message, 0);
}
void ThrowErrorOverCore(TErrorOver setErrorOver, TErrorOver resetErrorOver) {
static TErrorOver prevErrorOver = ERROR_OVER_NONE;
prevErrorOver |= (setErrorOver & ~ERROR_OVER_URGENT_OFF);
prevErrorOver &= ~resetErrorOver;
Display_RequestToErrorOver(prevErrorOver);
if ((setErrorOver & ERROR_OVER_URGENT_OFF)
|| (MainWorkObj.StabilizeModeA == smVoltageStab && (prevErrorOver & (ERROR_OVER_HW_AMPERAGE_A | ERROR_OVER_SW_VOLTAGE_A | ERROR_OVER_SW_AMPERAGE_A)))
|| (MainWorkObj.StabilizeModeB == smVoltageStab && (prevErrorOver & (ERROR_OVER_HW_AMPERAGE_B | ERROR_OVER_SW_VOLTAGE_B | ERROR_OVER_SW_AMPERAGE_B)))) {
ChangeState(mwsErrGlb);
}
}
void ThrowErrorOver(TErrorOver setErrorOver, TErrorOver resetErrorOver) {
if (!CheckRegulatorStatusCore(RegulatorStatus_Read())) {//если есть HW ошибка то отображать только ее
ThrowErrorOverCore(setErrorOver, resetErrorOver);
}
}
void ResetErrorState() {
RegulatorStatus_Read();
ThrowErrorOverCore(ERROR_OVER_NONE, ~ERROR_OVER_NONE);
ChangeState(mwsStandBy);
}
BOOL ErrorIndicator() {
static DWORD errorFlashTick = 0;
if (MainWorkObj.State != mwsErrGlb) {
return FALSE;
}
if (GetElapsedPeriod(errorFlashTick) < SYSTICK_mS(150)) {
return FALSE;
}
errorFlashTick = GetTickCount();
O_Led_Error_Write(!O_Led_Error_Read());
return TRUE;
}
/*----------------- Errors --------------<<<*/
/*>>>-------------- Regulator state & status -----------------*/
BOOL CheckRegulatorStatusCore(BYTE status) {
if (status & 0x02) {
ThrowErrorOverCore(ERROR_OVER_HW_VOLTAGE_A | ERROR_OVER_URGENT_OFF, ERROR_OVER_NONE);
return TRUE;
}
if (status & 0x04) {
ThrowErrorOverCore(ERROR_OVER_HW_AMPERAGE_A | ERROR_OVER_URGENT_OFF, ERROR_OVER_NONE);
return TRUE;
}
if (status & 0x08) {
ThrowErrorOverCore(ERROR_OVER_HW_VOLTAGE_B | ERROR_OVER_URGENT_OFF, ERROR_OVER_NONE);
return TRUE;
}
if (status & 0x01) {
ThrowErrorOverCore(ERROR_OVER_HW_AMPERAGE_A, ERROR_OVER_NONE);
return TRUE;
}
if (status & 0x20) {
ThrowErrorOverCore(ERROR_OVER_HW_AMPERAGE_B, ERROR_OVER_NONE);
return TRUE;
}
if (status & 0x10) {
ThrowErrorOverCore(ERROR_OVER_HW_AMPERAGE_B | ERROR_OVER_URGENT_OFF, ERROR_OVER_NONE);
return TRUE;
}
return FALSE;
}
BOOL CheckRegulatorStatus() {
static BYTE prevStatus = 0;
BYTE status = RegulatorStatus_Read();
if (status == prevStatus || MainWorkObj.State != mwsWork) {
return FALSE;
}
prevStatus = status;
if (CheckRegulatorStatusCore(status)) {
return TRUE;
} else {
ThrowErrorOverCore(ERROR_OVER_NONE, ERROR_OVER_HW_AMPERAGE_A | ERROR_OVER_HW_AMPERAGE_B | ERROR_OVER_HW_VOLTAGE_A | ERROR_OVER_HW_VOLTAGE_B);
return FALSE;
}
}
void ClearRegulatorStatusAndErrors() {
RegulatorStatus_Read();
}
/*----------------- Regulator state & status --------------<<<*/
void RefreshDisplay() {
RequestToChangeScreen(dsWork);
Display_RequestToChangeValue(svMeasuredVoltageA, MainWorkObj.SetPointVoltageA);
Display_RequestToChangeValue(svSetPointVoltageA, MainWorkObj.SetPointVoltageA);
Display_RequestToChangeValue(svMeasuredAmperageA, MainWorkObj.SetPointAmperageA);
Display_RequestToChangeValue(svSetPointAmperageA, MainWorkObj.SetPointAmperageA);
Display_RequestToChangeValue(svMeasuredVoltageB, MainWorkObj.SetPointVoltageB);
Display_RequestToChangeValue(svSetPointVoltageB, MainWorkObj.SetPointVoltageB);
Display_RequestToChangeValue(svMeasuredAmperageB, MainWorkObj.SetPointAmperageB);
Display_RequestToChangeValue(svSetPointAmperageB, MainWorkObj.SetPointAmperageB);
RequestToFocusing(svMeasuredVoltageA);
if (MainWorkObj.StabilizeModeA == smAmperageStab) {
RequestToFocusingStabilize(ssmAmperageA);
} else {
RequestToFocusingStabilize(ssmVoltageA);
}
if (MainWorkObj.StabilizeModeB == smAmperageStab) {
RequestToFocusingStabilize(ssmAmperageB);
} else {
RequestToFocusingStabilize(ssmVoltageB);
}
RequestToRepaintTemperatures();
RequestToVisibileMousePresent(MainWorkObj.MousePresent);
RequestToRepaintMousePresent();
}
/*>>>-------------- Change Stabilize Mode -----------------*/
void MainWork_ChangeStabilizeMode(TSelectStabilizeMode selectedValue) {
if (selectedValue == ssmVoltageA) {
MainWorkObj.StabilizeModeA = smVoltageStab;
} else if (selectedValue == ssmAmperageA) {
MainWorkObj.StabilizeModeA = smAmperageStab;
} else if (selectedValue == ssmVoltageB) {
MainWorkObj.StabilizeModeB = smVoltageStab;
} else if (selectedValue == ssmAmperageB) {
MainWorkObj.StabilizeModeB = smAmperageStab;
}
Regulator_ChangeStabilizeMode();
}
/*----------------- Change Stabilize Mode --------------<<<*/
/*>>>-------------- Entering to Sleep Mode -----------------*/
BOOL MainWork_EnteringToSleepMode() {
if (MainWorkObj.State != mwsStandBy) {
return FALSE;
}
ChangeState(mwsPowerOff);
RequestToChangeScreen(dsPowerOff);
INT mouseX = INT_MIN;
INT mouseY = INT_MIN;
BYTE bt = Buttons_Read();
DWORD waitTimer = GetTickCount();
while (GetElapsedPeriod(waitTimer) < SYSTICK_mS(10000)) {
TaskSleep(&MainWorkFunction, SYSTICK_mS(50)); //display message
if (bt != Buttons_Read()) {
break;
}
MouseHandler(&mouseX, &mouseY);
if (mouseX != INT_MIN && mouseX != 0
&& mouseY != INT_MIN && mouseY != 0) {
break;
}
}
if (GetElapsedPeriod(waitTimer) >= SYSTICK_mS(10000)) {
Display_RequestToPowerOff();
TaskSleep(&MainWorkFunction, SYSTICK_mS(300)); //sleep display
return TRUE;
} else {
ChangeState(mwsStandBy);
RefreshDisplay();
return FALSE;
}
}
/*----------------- Entering to Sleep Mode --------------<<<*/
/* [] END OF FILE */
| 2.125 | 2 |
2024-11-18T19:02:45.608279+00:00 | 2023-08-16T12:50:05 | 23853c29f43200a08b5f14c57bd1f4fbc07a4d72 | {
"blob_id": "23853c29f43200a08b5f14c57bd1f4fbc07a4d72",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-16T12:50:05",
"content_id": "918b09324f7f7f70fc5ee389aae08e91201fc055",
"detected_licenses": [
"MIT"
],
"directory_id": "984383140e7ad43ea42d6a79c3797438ebcfe71e",
"extension": "c",
"filename": "ct_characters.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 167775750,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 766,
"license": "MIT",
"license_type": "permissive",
"path": "/lib/car/obj/src/ct_characters.c",
"provenance": "stackv2-0058.json.gz:161322",
"repo_name": "chlds/util",
"revision_date": "2023-08-16T12:50:05",
"revision_id": "6c9fac1fbacad7657f3f93d59798e4774e681988",
"snapshot_id": "8bc5815e3babce87199e0f2669c4068bfd630fed",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/chlds/util/6c9fac1fbacad7657f3f93d59798e4774e681988/lib/car/obj/src/ct_characters.c",
"visit_date": "2023-08-16T22:45:01.229839"
} | stackv2 | /* **** Notes
Count the number of Unicode characters based on UTF-8 to the terminating null character.
Remarks:
Refer at fn. ct_letters.
*/
# define CAR
# include "./../../../incl/config.h"
signed(__cdecl ct_characters(signed char(*argp))) {
/* **** DATA, BSS and STACK */
static signed const AL_80 = (0x80); // i.e., a sequential byte expressed in .io**.**** for the n-byte characters based on UTF-8.
auto signed r;
/* **** CODE/TEXT */
if(!argp) return(0x00);
if(!(*argp)) return(0x00);
r = nbytechar(*argp);
if(!(AL_80^(r))) {
printf("%s\n","<< Error at fn. nbytechar() returned with a sequential (0x80) byte");
return(0x00);
}
if(!r) {
printf("%s\n","<< Error at fn. nbytechar()");
return(r);
}
argp = (argp+(r));
return(0x01+(ct_characters(argp)));
}
| 2.46875 | 2 |
2024-11-18T19:02:45.738389+00:00 | 2022-06-04T13:57:28 | 723149fa8e33a433bf738235c9b71aa50e3a4c04 | {
"blob_id": "723149fa8e33a433bf738235c9b71aa50e3a4c04",
"branch_name": "refs/heads/master",
"committer_date": "2022-06-04T13:57:28",
"content_id": "6aca555588f6c98c97d2ff9b93491c7c5b66c775",
"detected_licenses": [
"MIT"
],
"directory_id": "4a3dce1d02b691138e816710d6929a41066776c5",
"extension": "h",
"filename": "rpair.h",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 179233886,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 548,
"license": "MIT",
"license_type": "permissive",
"path": "/util/rpair.h",
"provenance": "stackv2-0058.json.gz:161579",
"repo_name": "roy-tian/roylib",
"revision_date": "2022-06-04T13:57:28",
"revision_id": "4cffd2783ea6f4627150b0f73cdd0506115e0438",
"snapshot_id": "fbe8f4aaedff23bccc511617d57c7d0959ae9d3e",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/roy-tian/roylib/4cffd2783ea6f4627150b0f73cdd0506115e0438/util/rpair.h",
"visit_date": "2022-06-16T22:01:54.401713"
} | stackv2 | #ifndef ROYPAIR_H
#define ROYPAIR_H
#include "rpre.h"
struct RoyPair_ {
void * key;
void * value;
};
typedef struct RoyPair_ RoyPair;
RoyPair * roy_pair_new(void * key, void * value);
void * roy_pair_key(RoyPair * pair);
void * roy_pair_value(RoyPair * pair);
struct RoyCPair_ {
const void * key;
const void * value;
};
typedef struct RoyCPair_ RoyCPair;
RoyCPair * roy_cpair_new(const void * key, const void * value);
const void * roy_cpair_key(RoyCPair * pair);
const void * roy_cpair_value(RoyCPair * pair);
#endif // ROYPAIR_H
| 2.015625 | 2 |
2024-11-18T19:02:45.946986+00:00 | 2021-03-07T19:15:02 | d8de9cc7b448b4dfe0d0b585d51549190f1e2eb5 | {
"blob_id": "d8de9cc7b448b4dfe0d0b585d51549190f1e2eb5",
"branch_name": "refs/heads/master",
"committer_date": "2021-09-07T01:51:31",
"content_id": "b4b0254a0d17ab25ee8a53e59572aa6110217fda",
"detected_licenses": [
"MIT"
],
"directory_id": "45f7a073e1caadbacb5132ffb43b6b3bf3d18462",
"extension": "c",
"filename": "vk_render.c",
"fork_events_count": 0,
"gha_created_at": "2016-05-04T02:40:16",
"gha_event_created_at": "2021-03-21T00:09:59",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 58017369,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 13415,
"license": "MIT",
"license_type": "permissive",
"path": "/vulkan/vk_render.c",
"provenance": "stackv2-0058.json.gz:161964",
"repo_name": "nyeecola/mainCraft",
"revision_date": "2021-03-07T19:15:02",
"revision_id": "39b5653bdf79ca509052ce71c2c2282a76bea398",
"snapshot_id": "05686696e6235411bc46334a19335eb6b8234f0c",
"src_encoding": "UTF-8",
"star_events_count": 5,
"url": "https://raw.githubusercontent.com/nyeecola/mainCraft/39b5653bdf79ca509052ce71c2c2282a76bea398/vulkan/vk_render.c",
"visit_date": "2023-07-24T23:44:53.955074"
} | stackv2 | #include <stdlib.h>
#include "vk_descriptors.h"
#include "vk_render.h"
#include "vk_image.h"
#include "utils.h"
VkRenderPass
create_render_pass(VkDevice logical_device, VkFormat depth_format, struct swapchain_info state)
{
VkRenderPass render_pass;
VkResult result;
VkAttachmentDescription color_attachment = {
.format = state.surface_format.format,
.samples = VK_SAMPLE_COUNT_1_BIT,
.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR,
.storeOp = VK_ATTACHMENT_STORE_OP_STORE,
.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE,
.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE,
.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED,
.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR
};
VkAttachmentDescription depth_attachment = {
.format = depth_format,
.samples = VK_SAMPLE_COUNT_1_BIT,
.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR,
.storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE,
.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE,
.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE,
.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED,
.finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL
};
VkAttachmentReference color_attachment_ref = {
.attachment = 0,
.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL
};
VkAttachmentReference depth_attachment_ref = {
.attachment = 1,
.layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL
};
VkSubpassDescription subpass = {
.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS,
.colorAttachmentCount = 1,
.pColorAttachments = &color_attachment_ref,
.pDepthStencilAttachment = &depth_attachment_ref
};
/* This subpass needs wait for the clear-color operation and the operation
* of write pixels in the framebuffer have to wait this subpass
* */
VkSubpassDependency dependency = {
.srcSubpass = VK_SUBPASS_EXTERNAL,
.dstSubpass = 0,
.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT | VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT,
.srcAccessMask = 0,
.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT | VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT,
.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT,
};
/* Currently we only have one of each ^^; (except the attachment)
* But we may have more in the future...
* */
VkSubpassDescription subpasses[] = { subpass };
VkSubpassDependency subpasses_dependencies[] = { dependency };
VkAttachmentDescription attachments[] = { color_attachment, depth_attachment };
VkRenderPassCreateInfo render_pass_info = {
.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO,
.attachmentCount = array_size(attachments),
.pAttachments = attachments,
.subpassCount = array_size(subpasses),
.pSubpasses = subpasses,
.dependencyCount = array_size(subpasses_dependencies),
.pDependencies = subpasses_dependencies
};
result = vkCreateRenderPass(logical_device, &render_pass_info, NULL, &render_pass);
if (result != VK_SUCCESS) {
print_error("Failed to create render pass!");
return VK_NULL_HANDLE;
}
return render_pass;
}
VkShaderModule
create_shader_module(const VkDevice logical_device, const char *code, int64_t size) {
VkShaderModule shader_module;
VkResult result;
VkShaderModuleCreateInfo create_info = {
.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO,
.codeSize = size,
.pCode = (const uint32_t *) code
};
result = vkCreateShaderModule(logical_device, &create_info, NULL, &shader_module);
if (result != VK_SUCCESS) {
print_error("Failed to create shader module!");
return VK_NULL_HANDLE;
}
return shader_module;
}
int
create_graphics_pipeline(const VkDevice logical_device, struct swapchain_info *swapchain_info, struct vk_render *render)
{
static VkVertexInputAttributeDescription vertex_attribute_descriptions[3];
static VkVertexInputBindingDescription vertex_binding_description[2];
char *vert_shader_code, *frag_shader_code;
int64_t vert_size, frag_size;
VkPipeline pipeline;
VkResult result;
int ret = -1;
vert_shader_code = read_file("shaders/vert.spv", &vert_size);
if (!vert_shader_code)
goto return_error;
frag_shader_code = read_file("shaders/frag.spv", &frag_size);
if (!frag_shader_code)
goto destroy_vert_code;
VkShaderModule vert_shader_module = create_shader_module(logical_device, vert_shader_code, vert_size);
if (vert_shader_module == VK_NULL_HANDLE)
goto destroy_frag_code;
VkShaderModule frag_shader_module = create_shader_module(logical_device, frag_shader_code, frag_size);
if (frag_shader_module == VK_NULL_HANDLE)
goto destroy_vert_module;
get_vertex_binding_description(0, vertex_binding_description);
get_vertex_attribute_descriptions(0, 0, vertex_attribute_descriptions);
get_vec3_binding_description(1, VK_VERTEX_INPUT_RATE_INSTANCE, &vertex_binding_description[1]);
get_vec3_attribute_descriptions(1, 2, &vertex_attribute_descriptions[2]);
VkPipelineVertexInputStateCreateInfo vertex_input_info = {
.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO,
.vertexBindingDescriptionCount = array_size(vertex_binding_description),
.pVertexBindingDescriptions = vertex_binding_description,
.vertexAttributeDescriptionCount = array_size(vertex_attribute_descriptions),
.pVertexAttributeDescriptions = vertex_attribute_descriptions
};
VkPipelineShaderStageCreateInfo vert_shader_stage_info = {
.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO,
.stage = VK_SHADER_STAGE_VERTEX_BIT,
.module = vert_shader_module,
.pName = "main"
};
VkPipelineShaderStageCreateInfo frag_shader_stage_info = {
.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO,
.stage = VK_SHADER_STAGE_FRAGMENT_BIT,
.module = frag_shader_module,
.pName = "main"
};
VkPipelineShaderStageCreateInfo shader_stages[] = {
vert_shader_stage_info,
frag_shader_stage_info
};
VkPipelineInputAssemblyStateCreateInfo input_assembly = {
.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO,
.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST,
.primitiveRestartEnable = VK_FALSE
};
VkViewport viewport = {
.x = 0.0f,
.y = 0.0f,
.width = swapchain_info->extent.width,
.height = swapchain_info->extent.height,
.minDepth = 0.0f,
.maxDepth = 1.0f
};
VkRect2D scissor = {
.offset = {0, 0},
.extent = swapchain_info->extent
};
/* Now just fill the struct with the two above */
VkPipelineViewportStateCreateInfo viewport_state = {
.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO,
.viewportCount = 1,
.pViewports = &viewport,
.scissorCount = 1,
.pScissors = &scissor
};
/* The rasterization node of the pipeline */
VkPipelineRasterizationStateCreateInfo rasterizer = {
.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO,
.depthClampEnable = VK_FALSE,
.rasterizerDiscardEnable = VK_FALSE,
.polygonMode = VK_POLYGON_MODE_FILL,
.lineWidth = 1.0f,
.cullMode = VK_CULL_MODE_BACK_BIT,
// It needs to be counter clockwise for reason that I don't understand
//.frontFace = VK_FRONT_FACE_CLOCKWISE,
.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE,
.depthBiasEnable = VK_FALSE,
.depthBiasConstantFactor = 0.0f, // Optional
.depthBiasClamp = 0.0f, // Optional
.depthBiasSlopeFactor = 0.0f // Optional
};
// This is really related with multisampling anti aliasing
// but it requires a gpu feature be enabled
VkPipelineMultisampleStateCreateInfo multisampling = {
.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO,
.sampleShadingEnable = VK_FALSE,
.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT,
.minSampleShading = 1.0f, // Optional
.pSampleMask = NULL, // Optional
.alphaToCoverageEnable = VK_FALSE, // Optional
.alphaToOneEnable = VK_FALSE // Optional
};
VkPipelineColorBlendAttachmentState color_blend_attachment = {
.colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT |
VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT,
.blendEnable = VK_FALSE,
.srcColorBlendFactor = VK_BLEND_FACTOR_ONE, // Optional
.dstColorBlendFactor = VK_BLEND_FACTOR_ZERO, // Optional
.colorBlendOp = VK_BLEND_OP_ADD, // Optional
.srcAlphaBlendFactor = VK_BLEND_FACTOR_ONE, // Optional
.dstAlphaBlendFactor = VK_BLEND_FACTOR_ZERO, // Optional
.alphaBlendOp = VK_BLEND_OP_ADD // Optional
};
// This is the second struct of fixed function
VkPipelineColorBlendStateCreateInfo color_blending = {
.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO,
.logicOpEnable = VK_FALSE,
.logicOp = VK_LOGIC_OP_COPY, // Optional
.attachmentCount = 1,
.pAttachments = &color_blend_attachment,
.blendConstants[0] = 0.0f, // Optional
.blendConstants[1] = 0.0f, // Optional
.blendConstants[2] = 0.0f, // Optional
.blendConstants[3] = 0.0f, // Optional
};
VkPipelineLayoutCreateInfo pipeline_layout_info = {
.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO,
.setLayoutCount = 1,
.pSetLayouts = &render->descriptor_set_layout
};
result = vkCreatePipelineLayout(logical_device, &pipeline_layout_info, NULL, &render->pipeline_layout);
if (result != VK_SUCCESS) {
print_error("Failed to create pipeline layout!");
goto destroy_frag_module;
}
VkPipelineDepthStencilStateCreateInfo depth_stencil = {
.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO,
.depthTestEnable = VK_TRUE,
.depthWriteEnable = VK_TRUE,
.depthCompareOp = VK_COMPARE_OP_LESS,
.depthBoundsTestEnable = VK_FALSE,
.stencilTestEnable = VK_FALSE,
};
VkGraphicsPipelineCreateInfo pipeline_info = {
.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO,
.stageCount = array_size(shader_stages),
.pStages = shader_stages,
.pVertexInputState = &vertex_input_info,
.pInputAssemblyState = &input_assembly,
.pViewportState = &viewport_state,
.pRasterizationState = &rasterizer,
.pMultisampleState = &multisampling,
.pDepthStencilState = &depth_stencil,
.pColorBlendState = &color_blending,
.pDynamicState = NULL, // Optional
.renderPass = render->render_pass,
.layout = render->pipeline_layout,
.subpass = 0,
.basePipelineHandle = VK_NULL_HANDLE, // Optional
.basePipelineIndex = -1 // Optional
};
result = vkCreateGraphicsPipelines(logical_device, VK_NULL_HANDLE, 1, &pipeline_info, NULL, &pipeline);
if (result != VK_SUCCESS) {
vkDestroyPipelineLayout(logical_device, render->pipeline_layout, NULL);
print_error("Failed to create graphics pipeline!");
goto destroy_frag_module;
}
render->graphics_pipeline = pipeline;
ret = 0;
destroy_frag_module:
vkDestroyShaderModule(logical_device, frag_shader_module, NULL);
destroy_vert_module:
vkDestroyShaderModule(logical_device, vert_shader_module, NULL);
destroy_frag_code:
free(frag_shader_code);
destroy_vert_code:
free(vert_shader_code);
return_error:
return ret;
}
int
create_framebuffers(const VkDevice logical_device, struct vk_swapchain *swapchain, struct vk_render *render)
{
VkFramebuffer *framebuffers;
VkResult result;
int i;
framebuffers = malloc(sizeof(VkFramebuffer) * swapchain->images_count);
if (!framebuffers) {
print_error("Failed to allocated framebuffer vector!");
return -1;
}
for (i = 0; i < swapchain->images_count; i++) {
VkImageView attachments[] = { swapchain->image_views[i], render->depth_image_view };
VkFramebufferCreateInfo framebuffer_info = {
.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO,
.renderPass = render->render_pass,
.attachmentCount = array_size(attachments),
.pAttachments = attachments,
.width = swapchain->state.extent.width,
.height = swapchain->state.extent.height,
.layers = 1
};
result = vkCreateFramebuffer(logical_device, &framebuffer_info, NULL, &framebuffers[i]);
if (result != VK_SUCCESS) {
pprint_error("Failed to create framebuffer %u/%u!", i, swapchain->images_count);
break;
}
}
if (i != swapchain->images_count) {
framebuffers_cleanup(logical_device, framebuffers, i - 1);
return -1;
}
render->swapChain_framebuffers = framebuffers;
render->framebuffer_count = swapchain->images_count;
return 0;
}
void
framebuffers_cleanup(const VkDevice logical_device, VkFramebuffer *framebuffers, uint32_t size)
{
int i;
for (i = 0; i < size; i++)
vkDestroyFramebuffer(logical_device, framebuffers[i], NULL);
free(framebuffers);
}
int
create_depth_resources(struct vk_device *dev, struct vk_render *render, VkExtent2D swapchain_extent)
{
VkDeviceMemory depth_image_memory;
VkImageView depth_image_view;
VkImage depth_image;
int ret = -1;
ret = create_image(dev, swapchain_extent.width, swapchain_extent.height, render->depth_format,
VK_IMAGE_TILING_OPTIMAL, VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT,
VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, &depth_image, &depth_image_memory);
if (ret) {
print_error("Failed to create depth buffer image!");
goto return_error;
}
depth_image_view = create_image_view(dev->logical_device, depth_image, render->depth_format, VK_IMAGE_ASPECT_DEPTH_BIT);
if (depth_image_view == VK_NULL_HANDLE) {
print_error("Failed to create depth buffer image view!");
goto destroy_depth_image;
}
render->depth_image = depth_image;
render->depth_image_view = depth_image_view;
render->depth_image_memory = depth_image_memory;
return 0;
destroy_depth_image:
vkDestroyImage(dev->logical_device, depth_image, NULL);
vkFreeMemory(dev->logical_device, depth_image_memory, NULL);
return_error:
return ret;
}
| 2.3125 | 2 |
2024-11-18T19:02:47.503792+00:00 | 2019-02-24T04:08:56 | 16fa61d0c9e2bf52238891bebc60bc1ad272978b | {
"blob_id": "16fa61d0c9e2bf52238891bebc60bc1ad272978b",
"branch_name": "refs/heads/master",
"committer_date": "2019-02-25T00:44:52",
"content_id": "7aafdc05ec92e82b0d5b35b118a3fa6d7cfac72c",
"detected_licenses": [
"MIT"
],
"directory_id": "4d35254a5940840facc46f193ddf910f1e2e33b5",
"extension": "c",
"filename": "abc_alg_sequential.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 142528913,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3190,
"license": "MIT",
"license_type": "permissive",
"path": "/src/abc_alg/abc_alg_sequential.c",
"provenance": "stackv2-0058.json.gz:162094",
"repo_name": "matheushjs/ElfPSP_ParallelABC",
"revision_date": "2019-02-24T04:08:56",
"revision_id": "0692adb2a32f1d5780c462a2b4902e311f62e627",
"snapshot_id": "d232b19f339859952e7e6257ca5adb95b8832fd1",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/matheushjs/ElfPSP_ParallelABC/0692adb2a32f1d5780c462a2b4902e311f62e627/src/abc_alg/abc_alg_sequential.c",
"visit_date": "2020-03-24T06:27:33.186069"
} | stackv2 | #include <stdlib.h>
#include <string.h>
#include <math.h>
#include <movchain.h>
#include <hpchain.h>
#include <fitness/fitness.h>
#include <random.h>
#include "abc_alg.h"
#include "hive.h"
/******************************************/
/****** OTHER PROCEDURES ********/
/******************************************/
/* Performs the forager phase of the searching cycle
* Procedure idea:
* For each solution, generate a new one in the neighborhood
* replace the varied solution if it was improved
*/
static
void forager_phase(int hpSize){
int i;
for(i = 0; i < HIVE_nSols(); i++){
// Change a random element of the solution
Solution alt = HIVE_perturb_solution(i, hpSize);
HIVE_try_replace_solution(alt, i, hpSize);
}
}
/* Performs the onlooker phase of the searching cycle
* Procedure idea;
* Calculate the SUM of fitnesses for all solutions
* Fitness can be negative, so we add a BASE that is the lowest fitness found
* For each solution SOL, (SOL.fitness/SUM) is its probability PROB of being perturbed
* (PROB * nOnlookers) is the number of perturbations that should be generated
*/
static
void onlooker_phase(int hpSize){
int i, j;
int nOnlookers = COLONY_SIZE - (COLONY_SIZE * FORAGER_RATIO);
// Find the minimum (If no negative numbers, min should be 0)
double min = 0;
for(i = 0; i < HIVE_nSols(); i++){
double fit = Solution_fitness(HIVE_solution(i));
if(fit < min)
min = fit;
}
// Sum the 'normalized' fitnesses
double sum = 0;
for(i = 0; i < HIVE_nSols(); i++){
double fit = Solution_fitness(HIVE_solution(i));
sum += fit - min;
}
// For each solution, count the number of onlooker bees that should perturb it
// then perturb it.
for(i = 0; i < HIVE_nSols(); i++){
double norm = Solution_fitness(HIVE_solution(i)) - min;
double prob = norm / sum; // The probability of perturbing such solution
// Count number of onlookers that should perturb such solution
int nIter = round(prob * nOnlookers);
for(j = 0; j < nIter; j++){
// Change a random element of the solution
Solution alt = HIVE_perturb_solution(i, hpSize);
HIVE_try_replace_solution(alt, i, hpSize);
}
}
}
/* Performs the scout phase of the searching cycle
* Procedure idea:
* Find all the solutions whose idle_iterations exceeded the limit
* Replace such solutions by random solutions
*/
static
void scout_phase(int hpSize){
int i;
for(i = 0; i < HIVE_nSols(); i++){
int idle = Solution_idle_iterations(HIVE_solution(i));
if(idle > IDLE_LIMIT){
Solution sol = Solution_random(hpSize);
HIVE_force_replace_solution(sol, i);
}
}
}
Solution ABC_predict_structure(const HPElem * hpChain, int hpSize, int nCycles, PredResults *results){
HIVE_initialize();
FitnessCalc_initialize(hpChain, hpSize);
int i;
for(i = 0; i < nCycles; i++){
forager_phase(hpSize);
onlooker_phase(hpSize);
scout_phase(hpSize);
}
Solution retval = HIVE_best_sol();
if(results){
results->fitness = Solution_fitness(retval);
FitnessCalc_measures(Solution_chain(retval), &results->contactsH, &results->collisions, &results->bbGyration);
}
FitnessCalc_cleanup();
HIVE_destroy();
return retval;
}
| 2.328125 | 2 |
2024-11-18T19:02:48.390421+00:00 | 2020-12-09T19:59:36 | b57b6f18ff5e08091a6b28e74260b868bc3074fc | {
"blob_id": "b57b6f18ff5e08091a6b28e74260b868bc3074fc",
"branch_name": "refs/heads/master",
"committer_date": "2020-12-09T19:59:36",
"content_id": "0570df6eaf68b7868ee12027d80ad5427a079d65",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "96a3484c6a07c0e2d80cd00a0458b6c41c48d334",
"extension": "h",
"filename": "ll.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 300011946,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1329,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/ll.h",
"provenance": "stackv2-0058.json.gz:162607",
"repo_name": "bix-1/IFJ_BHKM",
"revision_date": "2020-12-09T19:59:36",
"revision_id": "e327bce1c5c506755486726f3e4cbe509700bd0a",
"snapshot_id": "603e223df603751a1f4f42ff6e350e5e5279013d",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/bix-1/IFJ_BHKM/e327bce1c5c506755486726f3e4cbe509700bd0a/ll.h",
"visit_date": "2023-01-28T01:27:03.463713"
} | stackv2 | /*
* Project: Compiler for imperative programing language IFJ20
*
* File: ll.h
* Brief: Header file for ll.h
*
* Authors: Hladký Tomáš [email protected]
* Kostolányi Adam [email protected]
* Makiš Jozef [email protected]
* Bartko Jakub [email protected]
*/
#ifndef LL_H
#define LL_H
#include "codegen.h" // instr_t
#include <stdbool.h> // list_is_empty
typedef struct {
instr_t * first;
instr_t * active;
instr_t * last;
} list_t;
// List functions
list_t * list_create();
void list_destroy (list_t **);
bool list_is_empty(list_t *);
int list_size (list_t *);
void list_add (list_t *, instr_t *);
instr_t * list_get_active (list_t *);
instr_t * list_get_next (list_t *);
// Instruction functions
instr_t * instr_create(); // creates empty instr
// if exists -- init; else create && init
void instr_init(instr_t **, instr_type_t);
void instr_set_type (instr_t *, instr_type_t);
int instr_get_type (instr_t *);
void instr_add_dest (instr_t *, elem_t *);
void instr_add_elem1 (instr_t *, elem_t *);
void instr_add_elem2 (instr_t *, elem_t *);
elem_t * instr_get_dest (instr_t *);
elem_t * instr_get_elem1 (instr_t *);
elem_t * instr_get_elem2 (instr_t *);
// Global variables
list_t * list;
extern symtable_t * symtable;
#endif
| 2.125 | 2 |
2024-11-18T19:02:49.268106+00:00 | 2020-12-08T15:02:23 | 9b6f28716778225ab2124ade5a977e10350c33ae | {
"blob_id": "9b6f28716778225ab2124ade5a977e10350c33ae",
"branch_name": "refs/heads/main",
"committer_date": "2020-12-08T15:02:23",
"content_id": "a0d3f29cead7110f149a5f55d5bc508998ef71db",
"detected_licenses": [
"MIT"
],
"directory_id": "0001dc06f4007330ce5de1c7105bc2873ad383cc",
"extension": "c",
"filename": "struct simples com typedef.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 319657172,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 759,
"license": "MIT",
"license_type": "permissive",
"path": "/codigos/struct simples com typedef.c",
"provenance": "stackv2-0058.json.gz:162735",
"repo_name": "RonaldoBilhar/linguagem-C",
"revision_date": "2020-12-08T15:02:23",
"revision_id": "e6d2977dd767e3ce980a529a009e1e43147828bf",
"snapshot_id": "5e386e87959b9260b01ad0e6d46772e095594712",
"src_encoding": "WINDOWS-1252",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/RonaldoBilhar/linguagem-C/e6d2977dd767e3ce980a529a009e1e43147828bf/codigos/struct simples com typedef.c",
"visit_date": "2023-01-23T22:11:15.460849"
} | stackv2 | #include<stdio.h>
typedef struct data{int Dia, Mes, Ano;} DATA; /*typedef faz com que "DATA" seja a mesma coisa que "strut data"*/
typedef struct pessoa{
char Nome[100]; /*"struct pessoa" é o mesmo que "PESSOA", por causa do typdef*/
int Idade;
float Salario;
struct data Nasc; /*poderiamos colocar a var Nasc como tipo "DATA"*/
}PESSOA;
void Mostrar(struct pessoa x){ /*poderiamos colocar como parametro "strust pessoa"*/
printf("Nome: %s\n",x.Nome);
printf("Idade: %d\n",x.Idade);
printf("Salario: %.2f\n",x.Salario);
printf("Data de nasc.: %d-%d-%d\n",x.Nasc.Dia,x.Nasc.Mes,x.Nasc.Ano);
}
main(){
PESSOA p={"Carlos",23,1823.54,{25,06,1999}}; /*poderiamos declarar a var p como sendo do tipo "struct pessoa"*/
Mostrar(p);
}
| 3.296875 | 3 |
2024-11-18T19:02:49.721346+00:00 | 2022-05-05T05:12:39 | 498b9bcbe1e9962e96c7ad7b81df8676c9a843bf | {
"blob_id": "498b9bcbe1e9962e96c7ad7b81df8676c9a843bf",
"branch_name": "refs/heads/master",
"committer_date": "2022-05-05T05:12:39",
"content_id": "a12cb0e3e77e5e5dbe1206dcbc7565e924deb186",
"detected_licenses": [
"MIT"
],
"directory_id": "65f2741294f3328a0a1c17269b7737e12ce325ee",
"extension": "c",
"filename": "anaoCommand.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 156813238,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 907,
"license": "MIT",
"license_type": "permissive",
"path": "/src/Quiet.X/Commands/anaoCommand.c",
"provenance": "stackv2-0058.json.gz:162992",
"repo_name": "callwyat/Quiet-Firmware",
"revision_date": "2022-05-05T05:12:39",
"revision_id": "864c210e44d368a4a683704841067717ebc8ac43",
"snapshot_id": "45ad64933fac6b4683e24e2316408252d29ae201",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/callwyat/Quiet-Firmware/864c210e44d368a4a683704841067717ebc8ac43/src/Quiet.X/Commands/anaoCommand.c",
"visit_date": "2022-05-12T15:15:53.355508"
} | stackv2 |
#include "../CLI/cli.h"
#include "../outputs.h"
#include "../constants.h"
#include "outputCommand.h"
#include <stdint.h>
#define ANAO_OFFSET 7
#define ANAO_CHANNELS 2
const OutputCommand_t anaoCommandSettings = DEFINE_OUTPUT_COMMAND_T(ANAO_CHANNELS, ANAO_OFFSET, ANAO_ERROR_GROUP);
void ANAOChannelModeCommand(CliHandle_t *handle, void *channel)
{
OutputChannelModeCommand(handle, anaoCommandSettings, channel);
}
void ANAOChannelValueCommand(CliHandle_t *handle, void *channel)
{
OutputChannelValueCommand(handle, anaoCommandSettings, channel);
}
CommandDefinition_t anaoChanCommands[] = {
DEFINE_COMMAND("VALU", ANAOChannelValueCommand),
DEFINE_COMMAND("MODE", ANAOChannelModeCommand),
};
CommandDefinition_t anaoCommands[] = {
DEFINE_COMMAND_W_BRANCH("CH", ANAOChannelValueCommand, anaoChanCommands),
};
CommandDefinition_t ANAOCommand = DEFINE_BRANCH("ANAO", anaoCommands);
| 2.03125 | 2 |
2024-11-18T19:02:49.839804+00:00 | 2020-12-17T19:59:56 | 8d716438d917039817dde88041c462457c4a4d26 | {
"blob_id": "8d716438d917039817dde88041c462457c4a4d26",
"branch_name": "refs/heads/master",
"committer_date": "2020-12-17T19:59:56",
"content_id": "1c821fc57f580a1b70a248dd5d6e3084e5895471",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "e36b6ab48b5c31e6715f2ebbc98ee15a02beb2c5",
"extension": "c",
"filename": "schemes.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": 8874,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/src/c_lib/lib/schemes.c",
"provenance": "stackv2-0058.json.gz:163122",
"repo_name": "ml-evs/mrsimulator",
"revision_date": "2020-12-17T19:59:56",
"revision_id": "6d844662938509a6849f6bfed02fa445e4b9ff11",
"snapshot_id": "da62139256894cdbc381b61fc487de9a7626b5a1",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ml-evs/mrsimulator/6d844662938509a6849f6bfed02fa445e4b9ff11/src/c_lib/lib/schemes.c",
"visit_date": "2023-02-06T20:48:45.380725"
} | stackv2 | // -*- coding: utf-8 -*-
//
// schemes.c
//
// @copyright Deepansh J. Srivastava, 2019-2020.
// Created by Deepansh J. Srivastava.
// Contact email = [email protected]
//
#include "schemes.h"
static inline void averaging_scheme_setup(MRS_averaging_scheme *scheme,
complex128 *exp_I_beta,
bool allow_fourth_rank) {
unsigned int allocate_size_2, allocate_size_4;
if (scheme->integration_volume == 0) { // positive octant
scheme->total_orientations = scheme->octant_orientations;
} else if (scheme->integration_volume == 1) { // positive hemisphere
scheme->total_orientations = 4 * scheme->octant_orientations;
} else if (scheme->integration_volume == 2) { // sphere
scheme->total_orientations = 8 * scheme->octant_orientations;
}
/* calculating exp(-Imα) at every orientation angle α form m=-4 to -1, where
* α is the azimuthal angle over the positive octant. The input α is in the
* form of phase exp(Iα). ............................................... */
/* ....................................................................... */
get_exp_Im_alpha(scheme->octant_orientations, allow_fourth_rank,
scheme->exp_Im_alpha);
/* ----------------------------------------------------------------------- */
/**
* Wigner matrices corresponding to the upper hemisphere.
*
* The wigner matrices are evaluated at every β orientation over the
* positive upper octant. Note, the β angles from this octant repeat for the
* other three octant in the upper hemisphere, therfore, only one set of
* second and fourth rank wigner matrices should suffice.
*/
// calculating the required space for storing wigner matrices.
allocate_size_2 = 25 * scheme->octant_orientations;
allocate_size_4 = 81 * scheme->octant_orientations;
if (scheme->integration_volume == 2) {
allocate_size_2 *= 2;
allocate_size_4 *= 2;
}
/* Second rank reduced wigner matrices at every β orientation from the
* positive upper octant. */
scheme->wigner_2j_matrices = malloc_double(allocate_size_2);
wigner_d_matrices_from_exp_I_beta(2, scheme->octant_orientations, exp_I_beta,
scheme->wigner_2j_matrices);
scheme->wigner_4j_matrices = NULL;
if (allow_fourth_rank) {
/* Fourth rank reduced wigner matrices at every β orientation from the
* positive upper octant. */
scheme->wigner_4j_matrices = malloc_double(allocate_size_4);
wigner_d_matrices_from_exp_I_beta(4, scheme->octant_orientations,
exp_I_beta, scheme->wigner_4j_matrices);
}
/**
* If averaging over a sphere is selected, then calculate the wigner matrices
* corresponding to the lower hemisphere.
*
* The wigner matrices only dependents on the β angles. Going from upper to
* the lower hemisphere, β -> β+π/2. This implies,
* cos(β+π/2) -> -cos(β)
* sin(β+π/2) -> sin(β)
*
* For evaluating the reduced wigner matrices from the lower hemisphere, the
* sign of cosine beta is changed. As before, the β angles from any octant
* from the lower hemisphere repeat for the other three octant in the lower
* hemisphere, therfore, only one set of second rank and fourth rank reduced
* wigner matrices should suffice. */
if (scheme->integration_volume == 2) {
/* cos(beta) is negative in the lower hemisphere */
cblas_dscal(scheme->octant_orientations, -1.0, (double *)exp_I_beta, 2);
/* Second rank reduced wigner matrices at every β orientation over an octant
* from the lower hemisphere */
wigner_d_matrices_from_exp_I_beta(
2, scheme->octant_orientations, exp_I_beta,
&scheme->wigner_2j_matrices[allocate_size_2]);
if (allow_fourth_rank) {
/* Fourth rank reduced wigner matrices at every β orientation. */
wigner_d_matrices_from_exp_I_beta(
4, scheme->octant_orientations, exp_I_beta,
&scheme->wigner_4j_matrices[allocate_size_4]);
}
}
free(exp_I_beta);
/* ----------------------------------------------------------------------- */
/* Setting up buffers and tables for processing the second rank tensors. . */
/* ....................................................................... */
/* w2 is the buffer for storing the frequencies calculated from the
* second rank tensors. */
scheme->w2 = malloc_complex128(5 * scheme->total_orientations);
scheme->w4 = NULL;
if (allow_fourth_rank) {
/* w4 is the buffer for storing the frequencies calculated from the
* fourth rank tensors. */
scheme->w4 = malloc_complex128(9 * scheme->total_orientations);
}
}
/* Free the memory from the mrsimulator plan associated with the spherical
* averaging scheme */
void MRS_free_averaging_scheme(MRS_averaging_scheme *scheme) {
free(scheme->amplitudes);
free(scheme->exp_Im_alpha);
free(scheme->w2);
free(scheme->w4);
free(scheme->wigner_2j_matrices);
free(scheme->wigner_4j_matrices);
}
/* Create a new orientation averaging scheme. */
MRS_averaging_scheme *MRS_create_averaging_scheme(
unsigned int integration_density, bool allow_fourth_rank,
unsigned int integration_volume) {
MRS_averaging_scheme *scheme = malloc(sizeof(MRS_averaging_scheme));
scheme->integration_density = integration_density;
scheme->integration_volume = integration_volume;
scheme->allow_fourth_rank = allow_fourth_rank;
scheme->octant_orientations =
((integration_density + 1) * (integration_density + 2)) / 2;
/* Calculate α, β, and weights over the positive octant. ................. */
/* ....................................................................... */
// The 4 * octant_orientations memory allocation is for m=-4, -3, -2, and -1
scheme->exp_Im_alpha = malloc_complex128(4 * scheme->octant_orientations);
complex128 *exp_I_beta = malloc_complex128(scheme->octant_orientations);
scheme->amplitudes = malloc_double(scheme->octant_orientations);
octahedron_averaging_setup(
integration_density,
&scheme->exp_Im_alpha[3 * scheme->octant_orientations], exp_I_beta,
scheme->amplitudes);
averaging_scheme_setup(scheme, exp_I_beta, allow_fourth_rank);
return scheme;
}
/* Create a new orientation averaging scheme. */
MRS_averaging_scheme *MRS_create_averaging_scheme_from_alpha_beta(
double *alpha, double *beta, double *weight, unsigned int n_angles,
bool allow_fourth_rank) {
MRS_averaging_scheme *scheme = malloc(sizeof(MRS_averaging_scheme));
scheme->octant_orientations = n_angles;
scheme->integration_volume = 0;
scheme->total_orientations = n_angles;
scheme->exp_Im_alpha = malloc_complex128(4 * scheme->total_orientations);
complex128 *exp_I_beta = malloc_complex128(scheme->total_orientations);
scheme->amplitudes = weight;
/* Calculate cos(α) + isin(α) from α. .................................... */
vm_cosine_I_sine(n_angles, alpha,
scheme->exp_Im_alpha[3 * scheme->octant_orientations]);
/* Calculate cos(β) + isin(β) from β. .................................... */
vm_cosine_I_sine(n_angles, beta, exp_I_beta);
averaging_scheme_setup(scheme, exp_I_beta, allow_fourth_rank);
return scheme;
}
/* ----------------------------------------------------------------------- */
/* fftw routine setup .................................................... */
/* ....................................................................... */
MRS_fftw_scheme *create_fftw_scheme(unsigned int total_orientations,
unsigned int number_of_sidebands) {
unsigned int size = total_orientations * number_of_sidebands;
int nssb = (int)number_of_sidebands;
MRS_fftw_scheme *fftw_scheme = malloc(sizeof(MRS_fftw_scheme));
fftw_scheme->vector =
(fftw_complex *)fftw_malloc(sizeof(fftw_complex) * size);
// malloc_complex128(plan->size);
// gettimeofday(&fft_setup_time, NULL);
// int fftw_thread = fftw_init_threads();
// if (fftw_thread == 0) {
// printf("failed to initialize fftw threading");
// }
// fftw_plan_with_nthreads(2);
fftw_scheme->the_fftw_plan =
fftw_plan_many_dft(1, &nssb, total_orientations, fftw_scheme->vector,
NULL, total_orientations, 1, fftw_scheme->vector, NULL,
total_orientations, 1, FFTW_FORWARD, FFTW_ESTIMATE);
// char *filename = "128_sidebands.wisdom";
// int status = fftw_export_wisdom_to_filename(filename);
// printf("file save status %i \n", status);
/* ----------------------------------------------------------------------- */
return fftw_scheme;
}
void MRS_free_fftw_scheme(MRS_fftw_scheme *fftw_scheme) {
fftw_destroy_plan(fftw_scheme->the_fftw_plan);
fftw_free(fftw_scheme->vector);
}
| 2.390625 | 2 |
2024-11-18T19:02:50.314082+00:00 | 2016-11-07T22:25:54 | ea73aea4b71df42f90145c4433a094e76fd2a0e1 | {
"blob_id": "ea73aea4b71df42f90145c4433a094e76fd2a0e1",
"branch_name": "refs/heads/master",
"committer_date": "2016-11-07T22:25:54",
"content_id": "7ec74a887ccce25437e00fda559a8740fa0482bc",
"detected_licenses": [
"MIT"
],
"directory_id": "0941f211692b917a4bd7fc793c001f1b4780ade8",
"extension": "c",
"filename": "extended.c",
"fork_events_count": 0,
"gha_created_at": "2016-10-22T23:00:47",
"gha_event_created_at": "2016-10-22T23:00:47",
"gha_language": null,
"gha_license_id": null,
"github_id": 71670360,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4321,
"license": "MIT",
"license_type": "permissive",
"path": "/tools/aif2pcm/extended.c",
"provenance": "stackv2-0058.json.gz:163510",
"repo_name": "fl4shk/pokeruby",
"revision_date": "2016-11-07T22:25:54",
"revision_id": "b363b9cb262993fb51d9e4db8450b9cb09786e30",
"snapshot_id": "e820f41ae29eda405d9f7528072b628e65a3fe07",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/fl4shk/pokeruby/b363b9cb262993fb51d9e4db8450b9cb09786e30/tools/aif2pcm/extended.c",
"visit_date": "2021-01-12T15:02:47.903508"
} | stackv2 | /* $Id: extended.c,v 1.8 2006/12/23 11:17:49 toad32767 Exp $ */
/*-
* Copyright (c) 2005, 2006 by Marco Trillo <[email protected]>
*
* Permission is hereby granted, free of charge, to any
* person obtaining a copy of this software and associated
* documentation files (the "Software"), to deal in the
* Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the
* Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice
* shall be included in all copies or substantial portions of
* the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
* KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
* WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
* OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <math.h>
#include <string.h>
/*
* Infinite & NAN values
* for non-IEEE systems
*/
#ifndef HUGE_VAL
#ifdef HUGE
#define INFINITE_VALUE HUGE
#define NAN_VALUE HUGE
#endif
#else
#define INFINITE_VALUE HUGE_VAL
#define NAN_VALUE HUGE_VAL
#endif
/*
* IEEE 754 Extended Precision
*
* Implementation here is the 80-bit extended precision
* format of Motorola 68881, Motorola 68882 and Motorola
* 68040 FPUs, as well as Intel 80x87 FPUs.
*
* See:
* http://www.freescale.com/files/32bit/doc/fact_sheet/BR509.pdf
*/
/*
* Exponent range: [-16383,16383]
* Precision for mantissa: 64 bits with no hidden bit
* Bias: 16383
*/
/*
* Write IEEE Extended Precision Numbers
*/
void
ieee754_write_extended(double in, unsigned char* out)
{
int sgn, exp, shift;
double fraction, t;
unsigned int lexp, hexp;
unsigned long low, high;
if (in == 0.0) {
memset(out, 0, 10);
return;
}
if (in < 0.0) {
in = fabs(in);
sgn = 1;
} else
sgn = 0;
fraction = frexp(in, &exp);
if (exp == 0 || exp > 16384) {
if (exp > 16384) /* infinite value */
low = high = 0;
else {
low = 0x80000000;
high = 0;
}
exp = 32767;
goto done;
}
fraction = ldexp(fraction, 32);
t = floor(fraction);
low = (unsigned long) t;
fraction -= t;
t = floor(ldexp(fraction, 32));
high = (unsigned long) t;
/* Convert exponents < -16382 to -16382 (then they will be
* stored as -16383) */
if (exp < -16382) {
shift = 0 - exp - 16382;
high >>= shift;
high |= (low << (32 - shift));
low >>= shift;
exp = -16382;
}
exp += 16383 - 1; /* bias */
done:
lexp = ((unsigned int) exp) >> 8;
hexp = ((unsigned int) exp) & 0xFF;
/* big endian */
out[0] = ((unsigned char) sgn) << 7;
out[0] |= (unsigned char) lexp;
out[1] = (unsigned char) hexp;
out[2] = (unsigned char) (low >> 24);
out[3] = (unsigned char) ((low >> 16) & 0xFF);
out[4] = (unsigned char) ((low >> 8) & 0xFF);
out[5] = (unsigned char) (low & 0xFF);
out[6] = (unsigned char) (high >> 24);
out[7] = (unsigned char) ((high >> 16) & 0xFF);
out[8] = (unsigned char) ((high >> 8) & 0xFF);
out[9] = (unsigned char) (high & 0xFF);
return;
}
/*
* Read IEEE Extended Precision Numbers
*/
double
ieee754_read_extended(unsigned char* in)
{
int sgn, exp;
unsigned long low, high;
double out;
/* Extract the components from the big endian buffer */
sgn = (int) (in[0] >> 7);
exp = ((int) (in[0] & 0x7F) << 8) | ((int) in[1]);
low = (((unsigned long) in[2]) << 24)
| (((unsigned long) in[3]) << 16)
| (((unsigned long) in[4]) << 8) | (unsigned long) in[5];
high = (((unsigned long) in[6]) << 24)
| (((unsigned long) in[7]) << 16)
| (((unsigned long) in[8]) << 8) | (unsigned long) in[9];
if (exp == 0 && low == 0 && high == 0)
return (sgn ? -0.0 : 0.0);
switch (exp) {
case 32767:
if (low == 0 && high == 0)
return (sgn ? -INFINITE_VALUE : INFINITE_VALUE);
else
return (sgn ? -NAN_VALUE : NAN_VALUE);
default:
exp -= 16383; /* unbias exponent */
}
out = ldexp((double) low, -31 + exp);
out += ldexp((double) high, -63 + exp);
return (sgn ? -out : out);
}
| 2.484375 | 2 |
2024-11-18T19:02:50.752373+00:00 | 2019-07-25T12:10:57 | 78984e693729c2901b266cf151d9b4d7a32a7d28 | {
"blob_id": "78984e693729c2901b266cf151d9b4d7a32a7d28",
"branch_name": "refs/heads/master",
"committer_date": "2019-07-25T12:10:57",
"content_id": "c77347c556f58e515dbd8b7961b923912b7b78bd",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "41955b793d22a845090e570b3e7375a0acb61186",
"extension": "c",
"filename": "restrictAssert.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 92730297,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1191,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/restrict/restrictAssert.c",
"provenance": "stackv2-0058.json.gz:164024",
"repo_name": "STB1019/SkullOfSummer",
"revision_date": "2019-07-25T12:10:57",
"revision_id": "1948d3238cf4bfe527327cfaef7e2ff4d26969e0",
"snapshot_id": "53e510996fad25b08d684ab68aaf0a2bbc7db435",
"src_encoding": "UTF-8",
"star_events_count": 5,
"url": "https://raw.githubusercontent.com/STB1019/SkullOfSummer/1948d3238cf4bfe527327cfaef7e2ff4d26969e0/restrict/restrictAssert.c",
"visit_date": "2021-06-06T09:51:19.037836"
} | stackv2 | #include <stdio.h>
#include <assert.h>
//compile it with gcc -O3 -o restrictAssert restrictAssert.c
int increase_with_no_restrict(int* a, int* b, int* c) {
*a = *a + *c;
*b = *b + *c;
}
int increase_with_restrict(int* restrict a, int* restrict b, int* restrict c) {
*a = *a + *c;
*b = *b + *c;
}
int main (int argc , char ** argv ) {
int v1 = 1;
int v2 = 2;
int v3 = 1;
// *********** contratto rispettato ****************
v1 = 1; v2 = 2; v3 = 1;
increase_with_no_restrict(&v1, &v2, &v3); //funziona sempre
assert(v1 == 2);
assert(v2 == 3);
v1 = 1; v2 = 2; v3 = 1;
increase_with_restrict(&v1, &v2, &v3);
assert(v1 == 2);
assert(v2 == 3);
// *************** contratto violato ****************
v1 = 1; v2 = 2; v3 = 1;
increase_with_no_restrict(&v1, &v2, &v1); //funziona sempre: non c'è restrict!
assert(v1 == 2);
assert(v2 == 4);
v1 = 1; v2 = 2; v3 = 1;
increase_with_restrict(&v1, &v2, &v1); //contratto di restrict violato!
//qui, quando incremento a, in realtà sto incrementando anche c!
assert(v1 == 2);
assert(v2 == 4); //questa assert fallisce perché *c non è 2, ma 1!
}
| 3.625 | 4 |
2024-11-18T19:02:50.854444+00:00 | 2018-09-04T06:32:56 | 4869b11c60d1ac04f97519ac63ada03ed5c0b25b | {
"blob_id": "4869b11c60d1ac04f97519ac63ada03ed5c0b25b",
"branch_name": "refs/heads/master",
"committer_date": "2018-09-04T06:33:16",
"content_id": "0c85f979622931fd527d222d791dc4e061d33c75",
"detected_licenses": [
"MIT"
],
"directory_id": "8434e1ee7d349fad96a6a5d340448415905e8911",
"extension": "c",
"filename": "main.c",
"fork_events_count": 0,
"gha_created_at": "2016-09-26T07:24:27",
"gha_event_created_at": "2016-11-10T02:42:18",
"gha_language": "C",
"gha_license_id": null,
"github_id": 69224184,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2641,
"license": "MIT",
"license_type": "permissive",
"path": "/lepcapy/src/main.c",
"provenance": "stackv2-0058.json.gz:164156",
"repo_name": "Revimal/lepcapy",
"revision_date": "2018-09-04T06:32:56",
"revision_id": "8ef9d02051d7b6ac6a1abf2a79d09bf2df1d13bc",
"snapshot_id": "6158dace2ab8adb4cb2511df8fd8cb7bbb242134",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/Revimal/lepcapy/8ef9d02051d7b6ac6a1abf2a79d09bf2df1d13bc/lepcapy/src/main.c",
"visit_date": "2021-01-13T09:12:31.510020"
} | stackv2 | #include "exception_ctrl.h"
#include "file_io_ctrl.h"
#include "net_io_ctrl.h"
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <sys/mman.h>
static inline void print_result(){
printf("\n[*] Replay Result\n");
printf("Total : %10lupkts\n", thread_file_get_cnt() + thread_file_get_dropped());
printf("Parsed : %10lupkts\n", thread_file_get_cnt());
printf("Filtered : %10lupkts\n", thread_file_get_dropped());
printf("Replayed : %10lupkts\n\n", thread_net_get_cnt());
}
int main(int argc, char *argv[])
{
int err_code = SUCCESS;
FILE *fp = NULL;
struct pcap_hdr_s p_pcap_hdr;
if(argc < 4){
printf("Usage : lepcapy [Dump file] [Interface Name] [IP Address]\n");
return err_code;
}
if(mlockall(MCL_FUTURE))
raise_except(ERR_CALL_LIBC(mlockall), -EMEM);
strncpy(env_pktm.if_name, argv[2], IFNAMSIZ - 1);
if((err_code = ipv4_parse_str(argv[3], &(env_pktm.ipv4_addr.daddr)))){
raise_except(ERR_CALL(ipv4_parse_str), err_code);
goto out_mlockall;
}
if(!(fp = fopen(argv[1], "rb"))){
raise_except(ERR_CALL_LIBC(fopen), -ENULL);
err_code = -ENULL;
goto out_file;
}
// TODO : Add .so ldr for custom toolkit
if((err_code = load_pcap_format(fp, &p_pcap_hdr))){
raise_except(ERR_CALL(load_pcap_format), err_code);
goto out_file;
}
printf("PCAP Version : %d.%d\n", p_pcap_hdr.version_major, p_pcap_hdr.version_minor);
if(p_pcap_hdr.network != 1){
raise_except(ERR_PROTO(not_ether, network), -EINVPF);
err_code = -EINVPF;
goto out_file;
}
__debug__chkpoint(routine_start);
queue_init();
alloc_pktm(p_pktm);
printf("\n[*] Start Replay...\n\n");
if((err_code = thread_file_io(fp))){
raise_except(ERR_CALL(thread_file_io), err_code);
goto out;
}
if((err_code = thread_net_io(thread_file_getthp()))){
raise_except(ERR_CALL(thread_net_io), err_code);
pthread_cancel(*thread_file_getthp());
goto out;
};
err_code = thread_file_join();
if(err_code){
__debug__chkpoint(err_thread_file);
raise_except(ERR_CALL(thread_file_join), err_code);
}
err_code = thread_net_join();
if(err_code){
__debug__chkpoint(err_thread_net);
raise_except(ERR_CALL(thread_net_join), err_code);
}
print_result();
out:
__debug__chkpoint(clean);
free_pktm(p_pktm);
out_file:
if(fclose(fp))
raise_except(ERR_CALL_LIBC(fclose), -EFIO);
out_mlockall:
munlockall();
return err_code;
}
| 2.09375 | 2 |
2024-11-18T19:02:51.240757+00:00 | 2018-02-27T09:47:44 | fdcec02933fe7e0be5f62970e2f45b770faba9a4 | {
"blob_id": "fdcec02933fe7e0be5f62970e2f45b770faba9a4",
"branch_name": "refs/heads/master",
"committer_date": "2018-02-27T09:47:44",
"content_id": "719c82b883cc643bf13dd0d0439fc237836504eb",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "39db0003b21257265286c0de7f4eeac2cb4dcf60",
"extension": "h",
"filename": "phy.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 124359807,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3239,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/fitp/pan/phy_layer/phy.h",
"provenance": "stackv2-0058.json.gz:164412",
"repo_name": "BeeeOn/fitplib",
"revision_date": "2018-02-27T09:47:44",
"revision_id": "71f8ab7ca2a35d97a9f56a9c8aac3b25fde0cb9f",
"snapshot_id": "aaf78191fedaae6775b8a579b04815f490be7568",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/BeeeOn/fitplib/71f8ab7ca2a35d97a9f56a9c8aac3b25fde0cb9f/fitp/pan/phy_layer/phy.h",
"visit_date": "2021-04-06T08:29:20.884679"
} | stackv2 | #ifndef MRF_PHY_LAYER_H
#define MRF_PHY_LAYER_H
#include <stdint.h>
#include <stdbool.h>
#include "common/phy_layer/constants.h"
// the crystal oscillator frequency (reference value is in data sheet)
#define FXTAL 12800
// maximum packet size on physical layer
// it is dependent on radio modul, for MRF89 it is 63
#define MAX_PHY_PAYLOAD_SIZE 63
/**
* Valid bands.
*/
enum bands {
BAND_863 = 0,
BAND_863_C950 = 1,
BAND_902 = 2,
BAND_915 = 3
};
/**
* Structure of parameters on physical layer.
*/
struct PHY_init_t {
uint8_t channel;
uint8_t band;
uint8_t bitrate;
uint8_t power;
// maximum value of noise when device is trying to send data
uint8_t cca_noise_threshold_max;
// minimum value of noise when device is trying to send data
uint8_t cca_noise_threshold_min;
};
/**
* @def PHY_init
* @brief initialize physical layer
* set band, channel, bitrate, power to radio
* set maximal threshold of noise(cca) when radio can send data
* @param params PHY_init_t values whitch be set on radio
* @return void
*/
void PHY_init (struct PHY_init_t *params);
/**
* @def PHY_stop
* @brief deactivate radio
* not implemented on devices without OS (protocol uses threads on linux)
* @see implementation for pan coordinator
* @return void
*/
void PHY_stop ();
/**
* @def PHY_set_freq
* @brief set frequenci used by radio
* @param band uint8_t band to set, value must be from enum bands
* @see bands
* @return boolean true if band is valid
*/
bool PHY_set_freq (uint8_t band);
/**
* @def PHY_set_channel
* @brief set channel used by radio
* @param channel uint8_t channel to set, value may be between 0 and 32 (for some bands and speeds only 25 allowed)
* @return boolean true if channel is valid
*/
bool PHY_set_channel (uint8_t channel);
/**
* @def PHY_set_bitrate
* @brief set bitrate used by radio
* @param bitrate uint8_t bitrate to set
* @return boolean true if bitrate is valid
*/
bool PHY_set_bitrate (uint8_t bitrate);
/**
* @def PHY_set_power
* @brief set power used by radio
* @param power uint8_t power to set, aviable values from 0 to 8
*
* can be used as macro from constants.h format TX_POWER_${value}_DB
* power hex macro
* 13 db 0x00 TX_POWER_13_DB
* 10 db 0x01 TX_POWER_10_DB
* 7 db 0x02 TX_POWER_7_DB
* 4 db 0x03 TX_POWER_4_DB
* 1 db 0x04 TX_POWER_1_DB
* -2 db 0x05 TX_POWER_N_2_DB
* -5 db 0x06 TX_POWER_N_5_DB
* -8 db 0x07 TX_POWER_N_8_DB
* @return true if power is valid
*/
bool PHY_set_power (uint8_t power);
/**
* @def PHY_get_noise
* @brief read actual value of noise from radio
* @return uint8_t noise value
*/
uint8_t PHY_get_noise ();
/**
* @def PHY_send
* @brief send raw data to air
* @param data uint8_t* data to be send
* @param len uint8_t data lenght
* @return void
*/
void PHY_send (const uint8_t * data, uint8_t len);
/**
* @def PHY_send_with_cca
* @brief send raw data to air wait to cca noise under specified level
* @param data uint8_t* data to be send
* @param len uint8_t data lenght
* @see PHY_init_t.cca_noise_threshold
* @see PHY_send
* @return void
*/
void PHY_send_with_cca (uint8_t * data, uint8_t len);
//uint8_t PHY_get_measured_noise();
#endif
| 2.1875 | 2 |
2024-11-18T19:02:51.626956+00:00 | 2023-08-04T13:11:02 | d1f219190bd2a28658ea70406751e314c7c0376e | {
"blob_id": "d1f219190bd2a28658ea70406751e314c7c0376e",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-04T13:11:02",
"content_id": "3a59ea2a0a05817984ec214e3da0100347703a6d",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "642ba1746fed0b722a127b8426eca987df6efc61",
"extension": "c",
"filename": "zmemory.c",
"fork_events_count": 171,
"gha_created_at": "2016-10-22T08:47:37",
"gha_event_created_at": "2023-09-14T17:48:03",
"gha_language": "C++",
"gha_license_id": "NOASSERTION",
"github_id": 71627569,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 15323,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/src/mesch/zmemory.c",
"provenance": "stackv2-0058.json.gz:164802",
"repo_name": "neuronsimulator/nrn",
"revision_date": "2023-08-04T13:11:02",
"revision_id": "b786c36d715ba0f6da1ba8bdf5d2338c939ecf51",
"snapshot_id": "23781d978fe9253b0e3543f41e27252532b35459",
"src_encoding": "UTF-8",
"star_events_count": 313,
"url": "https://raw.githubusercontent.com/neuronsimulator/nrn/b786c36d715ba0f6da1ba8bdf5d2338c939ecf51/src/mesch/zmemory.c",
"visit_date": "2023-08-09T00:13:11.123525"
} | stackv2 | #include <../../nrnconf.h>
/**************************************************************************
**
** Copyright (C) 1993 David E. Steward & Zbigniew Leyk, all rights reserved.
**
** Meschach Library
**
** This Meschach Library is provided "as is" without any express
** or implied warranty of any kind with respect to this software.
** In particular the authors shall not be liable for any direct,
** indirect, special, incidental or consequential damages arising
** in any way from use of the software.
**
** Everyone is granted permission to copy, modify and redistribute this
** Meschach Library, provided:
** 1. All copies contain this copyright notice.
** 2. All modified copies shall carry a notice stating who
** made the last modification and the date of such modification.
** 3. No charge is made for this software or works derived from it.
** This clause shall not be construed as constraining other software
** distributed on the same medium as this software, nor is a
** distribution fee considered a charge.
**
***************************************************************************/
/* Memory allocation and de-allocation for complex matrices and vectors */
#include <stdio.h>
#include "zmatrix.h"
static char rcsid[] = "zmemory.c,v 1.1 1997/12/04 17:56:13 hines Exp";
/* zv_zero -- zeros all entries of a complex vector
-- uses __zzero__() */
ZVEC *zv_zero(x)
ZVEC *x;
{
if ( ! x )
error(E_NULL,"zv_zero");
__zzero__(x->ve,x->dim);
return x;
}
/* zm_zero -- zeros all entries of a complex matrix
-- uses __zzero__() */
ZMAT *zm_zero(A)
ZMAT *A;
{
int i;
if ( ! A )
error(E_NULL,"zm_zero");
for ( i = 0; i < A->m; i++ )
__zzero__(A->me[i],A->n);
return A;
}
/* zm_get -- gets an mxn complex matrix (in ZMAT form) */
ZMAT *zm_get(m,n)
int m,n;
{
ZMAT *matrix;
u_int i;
if (m < 0 || n < 0)
error(E_NEG,"zm_get");
if ((matrix=NEW(ZMAT)) == (ZMAT *)NULL )
error(E_MEM,"zm_get");
else if (mem_info_is_on()) {
mem_bytes(TYPE_ZMAT,0,sizeof(ZMAT));
mem_numvar(TYPE_ZMAT,1);
}
matrix->m = m; matrix->n = matrix->max_n = n;
matrix->max_m = m; matrix->max_size = m*n;
#ifndef SEGMENTED
if ((matrix->base = NEW_A(m*n,complex)) == (complex *)NULL )
{
free(matrix);
error(E_MEM,"zm_get");
}
else if (mem_info_is_on()) {
mem_bytes(TYPE_ZMAT,0,m*n*sizeof(complex));
}
#else
matrix->base = (complex *)NULL;
#endif
if ((matrix->me = (complex **)calloc(m,sizeof(complex *))) ==
(complex **)NULL )
{ free(matrix->base); free(matrix);
error(E_MEM,"zm_get");
}
else if (mem_info_is_on()) {
mem_bytes(TYPE_ZMAT,0,m*sizeof(complex *));
}
#ifndef SEGMENTED
/* set up pointers */
for ( i=0; i<m; i++ )
matrix->me[i] = &(matrix->base[i*n]);
#else
for ( i = 0; i < m; i++ )
if ( (matrix->me[i]=NEW_A(n,complex)) == (complex *)NULL )
error(E_MEM,"zm_get");
else if (mem_info_is_on()) {
mem_bytes(TYPE_ZMAT,0,n*sizeof(complex));
}
#endif
return (matrix);
}
/* zv_get -- gets a ZVEC of dimension 'dim'
-- Note: initialized to zero */
ZVEC *zv_get(size)
int size;
{
ZVEC *vector;
if (size < 0)
error(E_NEG,"zv_get");
if ((vector=NEW(ZVEC)) == (ZVEC *)NULL )
error(E_MEM,"zv_get");
else if (mem_info_is_on()) {
mem_bytes(TYPE_ZVEC,0,sizeof(ZVEC));
mem_numvar(TYPE_ZVEC,1);
}
vector->dim = vector->max_dim = size;
if ((vector->ve=NEW_A(size,complex)) == (complex *)NULL )
{
free(vector);
error(E_MEM,"zv_get");
}
else if (mem_info_is_on()) {
mem_bytes(TYPE_ZVEC,0,size*sizeof(complex));
}
return (vector);
}
/* zm_free -- returns ZMAT & asoociated memory back to memory heap */
int zm_free(mat)
ZMAT *mat;
{
#ifdef SEGMENTED
int i;
#endif
if ( mat==(ZMAT *)NULL || (int)(mat->m) < 0 ||
(int)(mat->n) < 0 )
/* don't trust it */
return (-1);
#ifndef SEGMENTED
if ( mat->base != (complex *)NULL ) {
if (mem_info_is_on()) {
mem_bytes(TYPE_ZMAT,mat->max_m*mat->max_n*sizeof(complex),0);
}
free((char *)(mat->base));
}
#else
for ( i = 0; i < mat->max_m; i++ )
if ( mat->me[i] != (complex *)NULL ) {
if (mem_info_is_on()) {
mem_bytes(TYPE_ZMAT,mat->max_n*sizeof(complex),0);
}
free((char *)(mat->me[i]));
}
#endif
if ( mat->me != (complex **)NULL ) {
if (mem_info_is_on()) {
mem_bytes(TYPE_ZMAT,mat->max_m*sizeof(complex *),0);
}
free((char *)(mat->me));
}
if (mem_info_is_on()) {
mem_bytes(TYPE_ZMAT,sizeof(ZMAT),0);
mem_numvar(TYPE_ZMAT,-1);
}
free((char *)mat);
return (0);
}
/* zv_free -- returns ZVEC & asoociated memory back to memory heap */
int zv_free(vec)
ZVEC *vec;
{
if ( vec==(ZVEC *)NULL || (int)(vec->dim) < 0 )
/* don't trust it */
return (-1);
if ( vec->ve == (complex *)NULL ) {
if (mem_info_is_on()) {
mem_bytes(TYPE_ZVEC,sizeof(ZVEC),0);
mem_numvar(TYPE_ZVEC,-1);
}
free((char *)vec);
}
else
{
if (mem_info_is_on()) {
mem_bytes(TYPE_ZVEC,vec->max_dim*sizeof(complex)+
sizeof(ZVEC),0);
mem_numvar(TYPE_ZVEC,-1);
}
free((char *)vec->ve);
free((char *)vec);
}
return (0);
}
/* zm_resize -- returns the matrix A of size new_m x new_n; A is zeroed
-- if A == NULL on entry then the effect is equivalent to m_get() */
ZMAT *zm_resize(A,new_m,new_n)
ZMAT *A;
int new_m, new_n;
{
u_int i, new_max_m, new_max_n, new_size, old_m, old_n;
if (new_m < 0 || new_n < 0)
error(E_NEG,"zm_resize");
if ( ! A )
return zm_get(new_m,new_n);
if (new_m == A->m && new_n == A->n)
return A;
old_m = A->m; old_n = A->n;
if ( new_m > A->max_m )
{ /* re-allocate A->me */
if (mem_info_is_on()) {
mem_bytes(TYPE_ZMAT,A->max_m*sizeof(complex *),
new_m*sizeof(complex *));
}
A->me = RENEW(A->me,new_m,complex *);
if ( ! A->me )
error(E_MEM,"zm_resize");
}
new_max_m = max(new_m,A->max_m);
new_max_n = max(new_n,A->max_n);
#ifndef SEGMENTED
new_size = new_max_m*new_max_n;
if ( new_size > A->max_size )
{ /* re-allocate A->base */
if (mem_info_is_on()) {
mem_bytes(TYPE_ZMAT,A->max_m*A->max_n*sizeof(complex),
new_size*sizeof(complex));
}
A->base = RENEW(A->base,new_size,complex);
if ( ! A->base )
error(E_MEM,"zm_resize");
A->max_size = new_size;
}
/* now set up A->me[i] */
for ( i = 0; i < new_m; i++ )
A->me[i] = &(A->base[i*new_n]);
/* now shift data in matrix */
if ( old_n > new_n )
{
for ( i = 1; i < min(old_m,new_m); i++ )
MEM_COPY((char *)&(A->base[i*old_n]),
(char *)&(A->base[i*new_n]),
sizeof(complex)*new_n);
}
else if ( old_n < new_n )
{
for ( i = min(old_m,new_m)-1; i > 0; i-- )
{ /* copy & then zero extra space */
MEM_COPY((char *)&(A->base[i*old_n]),
(char *)&(A->base[i*new_n]),
sizeof(complex)*old_n);
__zzero__(&(A->base[i*new_n+old_n]),(new_n-old_n));
}
__zzero__(&(A->base[old_n]),(new_n-old_n));
A->max_n = new_n;
}
/* zero out the new rows.. */
for ( i = old_m; i < new_m; i++ )
__zzero__(&(A->base[i*new_n]),new_n);
#else
if ( A->max_n < new_n )
{
complex *tmp;
for ( i = 0; i < A->max_m; i++ )
{
if (mem_info_is_on()) {
mem_bytes(TYPE_ZMAT,A->max_n*sizeof(complex),
new_max_n*sizeof(complex));
}
if ( (tmp = RENEW(A->me[i],new_max_n,complex)) == NULL )
error(E_MEM,"zm_resize");
else {
A->me[i] = tmp;
}
}
for ( i = A->max_m; i < new_max_m; i++ )
{
if ( (tmp = NEW_A(new_max_n,complex)) == NULL )
error(E_MEM,"zm_resize");
else {
A->me[i] = tmp;
if (mem_info_is_on()) {
mem_bytes(TYPE_ZMAT,0,new_max_n*sizeof(complex));
}
}
}
}
else if ( A->max_m < new_m )
{
for ( i = A->max_m; i < new_m; i++ )
if ( (A->me[i] = NEW_A(new_max_n,complex)) == NULL )
error(E_MEM,"zm_resize");
else if (mem_info_is_on()) {
mem_bytes(TYPE_ZMAT,0,new_max_n*sizeof(complex));
}
}
if ( old_n < new_n )
{
for ( i = 0; i < old_m; i++ )
__zzero__(&(A->me[i][old_n]),new_n-old_n);
}
/* zero out the new rows.. */
for ( i = old_m; i < new_m; i++ )
__zzero__(A->me[i],new_n);
#endif
A->max_m = new_max_m;
A->max_n = new_max_n;
A->max_size = A->max_m*A->max_n;
A->m = new_m; A->n = new_n;
return A;
}
/* zv_resize -- returns the (complex) vector x with dim new_dim
-- x is set to the zero vector */
ZVEC *zv_resize(x,new_dim)
ZVEC *x;
int new_dim;
{
if (new_dim < 0)
error(E_NEG,"zv_resize");
if ( ! x )
return zv_get(new_dim);
if (new_dim == x->dim)
return x;
if ( x->max_dim == 0 ) /* assume that it's from sub_zvec */
return zv_get(new_dim);
if ( new_dim > x->max_dim )
{
if (mem_info_is_on()) {
mem_bytes(TYPE_ZVEC,x->max_dim*sizeof(complex),
new_dim*sizeof(complex));
}
x->ve = RENEW(x->ve,new_dim,complex);
if ( ! x->ve )
error(E_MEM,"zv_resize");
x->max_dim = new_dim;
}
if ( new_dim > x->dim )
__zzero__(&(x->ve[x->dim]),new_dim - x->dim);
x->dim = new_dim;
return x;
}
/* varying arguments */
#ifdef ANSI_C
#include <stdarg.h>
/* To allocate memory to many arguments.
The function should be called:
zv_get_vars(dim,&x,&y,&z,...,NULL);
where
int dim;
ZVEC *x, *y, *z,...;
The last argument should be NULL !
dim is the length of vectors x,y,z,...
returned value is equal to the number of allocated variables
Other gec_... functions are similar.
*/
int zv_get_vars(int dim,...)
{
va_list ap;
int i=0;
ZVEC **par;
va_start(ap, dim);
while ((par = va_arg(ap,ZVEC **))) { /* NULL ends the list*/
*par = zv_get(dim);
i++;
}
va_end(ap);
return i;
}
int zm_get_vars(int m,int n,...)
{
va_list ap;
int i=0;
ZMAT **par;
va_start(ap, n);
while ((par = va_arg(ap,ZMAT **))) { /* NULL ends the list*/
*par = zm_get(m,n);
i++;
}
va_end(ap);
return i;
}
/* To resize memory for many arguments.
The function should be called:
v_resize_vars(new_dim,&x,&y,&z,...,NULL);
where
int new_dim;
ZVEC *x, *y, *z,...;
The last argument should be NULL !
rdim is the resized length of vectors x,y,z,...
returned value is equal to the number of allocated variables.
If one of x,y,z,.. arguments is NULL then memory is allocated to this
argument.
Other *_resize_list() functions are similar.
*/
int zv_resize_vars(int new_dim,...)
{
va_list ap;
int i=0;
ZVEC **par;
va_start(ap, new_dim);
while ((par = va_arg(ap,ZVEC **))) { /* NULL ends the list*/
*par = zv_resize(*par,new_dim);
i++;
}
va_end(ap);
return i;
}
int zm_resize_vars(int m,int n,...)
{
va_list ap;
int i=0;
ZMAT **par;
va_start(ap, n);
while ((par = va_arg(ap,ZMAT **))) { /* NULL ends the list*/
*par = zm_resize(*par,m,n);
i++;
}
va_end(ap);
return i;
}
/* To deallocate memory for many arguments.
The function should be called:
v_free_vars(&x,&y,&z,...,NULL);
where
ZVEC *x, *y, *z,...;
The last argument should be NULL !
There must be at least one not NULL argument.
returned value is equal to the number of allocated variables.
Returned value of x,y,z,.. is VNULL.
Other *_free_list() functions are similar.
*/
int zv_free_vars(ZVEC **pv,...)
{
va_list ap;
int i=1;
ZVEC **par;
zv_free(*pv);
*pv = ZVNULL;
va_start(ap, pv);
while ((par = va_arg(ap,ZVEC **))) { /* NULL ends the list*/
zv_free(*par);
*par = ZVNULL;
i++;
}
va_end(ap);
return i;
}
int zm_free_vars(ZMAT **va,...)
{
va_list ap;
int i=1;
ZMAT **par;
zm_free(*va);
*va = ZMNULL;
va_start(ap, va);
while ((par = va_arg(ap,ZMAT **))) { /* NULL ends the list*/
zm_free(*par);
*par = ZMNULL;
i++;
}
va_end(ap);
return i;
}
#elif VARARGS
#include <varargs.h>
/* To allocate memory to many arguments.
The function should be called:
v_get_vars(dim,&x,&y,&z,...,NULL);
where
int dim;
ZVEC *x, *y, *z,...;
The last argument should be NULL !
dim is the length of vectors x,y,z,...
returned value is equal to the number of allocated variables
Other gec_... functions are similar.
*/
int zv_get_vars(va_alist) va_dcl
{
va_list ap;
int dim,i=0;
ZVEC **par;
va_start(ap);
dim = va_arg(ap,int);
while ((par = va_arg(ap,ZVEC **))) { /* NULL ends the list*/
*par = zv_get(dim);
i++;
}
va_end(ap);
return i;
}
int zm_get_vars(va_alist) va_dcl
{
va_list ap;
int i=0, n, m;
ZMAT **par;
va_start(ap);
m = va_arg(ap,int);
n = va_arg(ap,int);
while ((par = va_arg(ap,ZMAT **))) { /* NULL ends the list*/
*par = zm_get(m,n);
i++;
}
va_end(ap);
return i;
}
/* To resize memory for many arguments.
The function should be called:
v_resize_vars(new_dim,&x,&y,&z,...,NULL);
where
int new_dim;
ZVEC *x, *y, *z,...;
The last argument should be NULL !
rdim is the resized length of vectors x,y,z,...
returned value is equal to the number of allocated variables.
If one of x,y,z,.. arguments is NULL then memory is allocated to this
argument.
Other *_resize_list() functions are similar.
*/
int zv_resize_vars(va_alist) va_dcl
{
va_list ap;
int i=0, new_dim;
ZVEC **par;
va_start(ap);
new_dim = va_arg(ap,int);
while ((par = va_arg(ap,ZVEC **))) { /* NULL ends the list*/
*par = zv_resize(*par,new_dim);
i++;
}
va_end(ap);
return i;
}
int zm_resize_vars(va_alist) va_dcl
{
va_list ap;
int i=0, m, n;
ZMAT **par;
va_start(ap);
m = va_arg(ap,int);
n = va_arg(ap,int);
while ((par = va_arg(ap,ZMAT **))) { /* NULL ends the list*/
*par = zm_resize(*par,m,n);
i++;
}
va_end(ap);
return i;
}
/* To deallocate memory for many arguments.
The function should be called:
v_free_vars(&x,&y,&z,...,NULL);
where
ZVEC *x, *y, *z,...;
The last argument should be NULL !
There must be at least one not NULL argument.
returned value is equal to the number of allocated variables.
Returned value of x,y,z,.. is VNULL.
Other *_free_list() functions are similar.
*/
int zv_free_vars(va_alist) va_dcl
{
va_list ap;
int i=0;
ZVEC **par;
va_start(ap);
while ((par = va_arg(ap,ZVEC **))) { /* NULL ends the list*/
zv_free(*par);
*par = ZVNULL;
i++;
}
va_end(ap);
return i;
}
int zm_free_vars(va_alist) va_dcl
{
va_list ap;
int i=0;
ZMAT **par;
va_start(ap);
while ((par = va_arg(ap,ZMAT **))) { /* NULL ends the list*/
zm_free(*par);
*par = ZMNULL;
i++;
}
va_end(ap);
return i;
}
#endif
| 2.109375 | 2 |
2024-11-18T19:02:51.708867+00:00 | 2023-05-26T07:03:59 | fe56e7bed640bc44dfa6a46916bf12004b72c1be | {
"blob_id": "fe56e7bed640bc44dfa6a46916bf12004b72c1be",
"branch_name": "refs/heads/hx20-hx30",
"committer_date": "2023-05-26T07:03:59",
"content_id": "79ee9406e9a7c0d2e005095d92b62f363ccf9af3",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "f9e7d65cb784c01a0200145ba8d289afe41d4a56",
"extension": "h",
"filename": "usb_api.h",
"fork_events_count": 48,
"gha_created_at": "2022-01-12T00:11:14",
"gha_event_created_at": "2023-05-26T07:04:59",
"gha_language": "C",
"gha_license_id": "BSD-3-Clause",
"github_id": 447021040,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2478,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/include/usb_api.h",
"provenance": "stackv2-0058.json.gz:164931",
"repo_name": "FrameworkComputer/EmbeddedController",
"revision_date": "2023-05-26T07:03:59",
"revision_id": "f6d6b927eed71550d3475411cfc3e59abe5cef2a",
"snapshot_id": "ad7086769e87d0a4179eae96a7c9ff5e383ff54e",
"src_encoding": "UTF-8",
"star_events_count": 846,
"url": "https://raw.githubusercontent.com/FrameworkComputer/EmbeddedController/f6d6b927eed71550d3475411cfc3e59abe5cef2a/include/usb_api.h",
"visit_date": "2023-08-08T20:45:10.621169"
} | stackv2 | /* Copyright 2014 The Chromium OS Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*
* USB API definitions.
*
* This file includes definitions needed by common code that wants to control
* the state of the USB peripheral, but doesn't need to know about the specific
* implementation.
*/
#ifndef __CROS_EC_USB_API_H
#define __CROS_EC_USB_API_H
/*
* Initialize the USB peripheral, enabling its clock and configuring the DP/DN
* GPIOs correctly. This function is called via an init hook (unless the board
* defined CONFIG_USB_INHIBIT_INIT), but may need to be called again if
* usb_release is called. This function will call usb_connect by default
* unless CONFIG_USB_INHIBIT_CONNECT is defined.
*/
void usb_init(void);
/* Check if USB peripheral is enabled. */
int usb_is_enabled(void);
/*
* Enable the pullup on the DP line to signal that this device exists to the
* host and to start the enumeration process.
*/
void usb_connect(void);
/*
* Disable the pullup on the DP line. This causes the device to be disconnected
* from the host.
*/
void usb_disconnect(void);
/*
* Disconnect from the host by calling usb_disconnect and then turn off the USB
* peripheral, releasing its GPIOs and disabling its clock.
*/
void usb_release(void);
/*
* Returns true if USB device is currently suspended.
* Requires CONFIG_USB_SUSPEND to be defined.
*/
int usb_is_suspended(void);
/*
* Returns true if USB remote wakeup is currently enabled by host.
* Requires CONFIG_USB_SUSPEND to be defined, always return 0 if
* CONFIG_USB_REMOTE_WAKEUP is not defined.
*/
int usb_is_remote_wakeup_enabled(void);
/*
* Preserve in non-volatile memory the state of the USB hardware registers
* which cannot be simply re-initialized when powered up again.
*/
void usb_save_suspended_state(void);
/*
* Restore from non-volatile memory the state of the USB hardware registers
* which was lost by powering them down.
*/
void usb_restore_suspended_state(void);
/*
* Tell the host to wake up. Does nothing if CONFIG_USB_REMOTE_WAKEUP is not
* defined.
*
* Returns immediately, suspend status can be checked using usb_is_suspended.
*/
#ifdef CONFIG_USB_REMOTE_WAKEUP
void usb_wake(void);
#else
static inline void usb_wake(void) {}
#endif
/* Board-specific USB wake, for side-band wake, called by usb_wake above. */
void board_usb_wake(void);
#endif /* __CROS_EC_USB_API_H */
| 2.109375 | 2 |
2024-11-18T19:02:51.830900+00:00 | 2018-02-20T20:51:24 | c107fd1a00c1408fbc16f058712bfa8cc4bd9e36 | {
"blob_id": "c107fd1a00c1408fbc16f058712bfa8cc4bd9e36",
"branch_name": "refs/heads/master",
"committer_date": "2018-02-20T20:51:24",
"content_id": "324da70c3035296a71660098cfccc18e02d857c2",
"detected_licenses": [
"MIT"
],
"directory_id": "12c69f475d582ab01c8060f236c555ce8a4197cb",
"extension": "c",
"filename": "primeList.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 119591322,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1075,
"license": "MIT",
"license_type": "permissive",
"path": "/L05/primeList.c",
"provenance": "stackv2-0058.json.gz:165187",
"repo_name": "nbrooks7/CMDA3634",
"revision_date": "2018-02-20T20:51:24",
"revision_id": "ac54cef5c6858a31f49562f22adc68e7d90403f2",
"snapshot_id": "c974177e76ca234c1e8a534ee3437e436a83529e",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/nbrooks7/CMDA3634/ac54cef5c6858a31f49562f22adc68e7d90403f2/L05/primeList.c",
"visit_date": "2021-09-07T09:08:23.663625"
} | stackv2 | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
void main() {
int N;
printf("Enter an upper bound:");
scanf("%d",&N);
// make storage for flags
int *isPrime = (int*) malloc(N*sizeof(int));
// initialize, i.e. set everything 'true'
for (int n=0;n<N;n++){
isPrime[n]=1;
}
int sqrtN = (int) sqrt(N);
for (int i = 2; i<sqrtN; i++){
if (isPrime[i]){ //if i is prime
for (int j = i*i;j<N;j+=i){
isPrime[j] = 0; //set j not prime
}
}
}
//count the number of primes we found
int cnt = 0;
for (int n=0;n<N;n++){
if (isPrime[n]){
cnt++;
}
}
//make a list of them
int *primes = (int*) malloc(cnt*sizeof(int));
cnt = 0;
for (int n=0;n<N;n++){
if (isPrime[n]){
primes[cnt++] = n;
}
}
//print out what find
for (int n = 0; n <cnt; n++){
printf("The %d-th prime is %d\n",n, primes[n]);
}
//cleanup
free(isPrime);
free(primes);
}
| 3.515625 | 4 |
2024-11-18T19:02:55.458416+00:00 | 2013-02-18T01:19:24 | 077b7f7d3c370b77bcb2c3aaf15429444b16540a | {
"blob_id": "077b7f7d3c370b77bcb2c3aaf15429444b16540a",
"branch_name": "refs/heads/master",
"committer_date": "2013-02-18T01:19:24",
"content_id": "c5c10e27d8a0e8b23adb3ac98664bae987851099",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "0ff4f88bed6c524eddc45cdef217a9ece457376d",
"extension": "c",
"filename": "frame.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 8415805,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3975,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/libchimp/frame.c",
"provenance": "stackv2-0058.json.gz:170254",
"repo_name": "ged/chimp",
"revision_date": "2013-02-18T01:19:24",
"revision_id": "07a4bba413bd4af53a3b8f97d5f9b01c9b8b951a",
"snapshot_id": "7f1ddeb134ebcd01ac75d9daac2a16c994e9b3b3",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/ged/chimp/07a4bba413bd4af53a3b8f97d5f9b01c9b8b951a/libchimp/frame.c",
"visit_date": "2023-03-31T07:26:56.936503"
} | stackv2 | /*****************************************************************************
* *
* Copyright 2012 Thomas Lee *
* *
* 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 "chimp/frame.h"
#include "chimp/class.h"
#include "chimp/object.h"
#include "chimp/str.h"
ChimpRef *chimp_frame_class = NULL;
static ChimpRef *
_chimp_frame_init (ChimpRef *self, ChimpRef *args)
{
ChimpRef *locals;
ChimpRef *method;
if (!chimp_method_parse_args (args, "o", &method)) {
return NULL;
}
locals = chimp_hash_new ();
if (locals == NULL) {
return NULL;
}
CHIMP_FRAME(self)->method = method;
CHIMP_FRAME(self)->locals = locals;
if (CHIMP_METHOD_TYPE(method) == CHIMP_METHOD_TYPE_BYTECODE ||
CHIMP_METHOD_TYPE(method) == CHIMP_METHOD_TYPE_CLOSURE) {
ChimpRef *code;
size_t i;
if (CHIMP_METHOD_TYPE(method) == CHIMP_METHOD_TYPE_BYTECODE) {
code = CHIMP_METHOD(method)->bytecode.code;
}
else {
code = CHIMP_METHOD(method)->closure.code;
}
/* allocate ChimpVar entries in `locals` for each non-free var */
for (i = 0; i < CHIMP_ARRAY_SIZE(CHIMP_CODE(code)->vars); i++) {
ChimpRef *varname =
CHIMP_ARRAY_ITEM(CHIMP_CODE(code)->vars, i);
ChimpRef *var = chimp_var_new ();
if (!chimp_hash_put (CHIMP_FRAME(self)->locals, varname, var)) {
return CHIMP_FALSE;
}
}
if (CHIMP_METHOD_TYPE(method) == CHIMP_METHOD_TYPE_CLOSURE) {
ChimpRef *bindings = CHIMP_CLOSURE_METHOD(method)->bindings;
for (i = 0; i < CHIMP_HASH_SIZE(bindings); i++) {
ChimpRef *varname = CHIMP_HASH(bindings)->keys[i];
ChimpRef *value = CHIMP_HASH(bindings)->values[i];
if (!chimp_hash_put (CHIMP_FRAME(self)->locals, varname, value)) {
return CHIMP_FALSE;
}
}
}
}
return self;
}
static void
_chimp_frame_mark (ChimpGC *gc, ChimpRef *self)
{
CHIMP_SUPER (self)->mark (gc, self);
chimp_gc_mark_ref (gc, CHIMP_FRAME(self)->method);
chimp_gc_mark_ref (gc, CHIMP_FRAME(self)->locals);
}
chimp_bool_t
chimp_frame_class_bootstrap (void)
{
chimp_frame_class = chimp_class_new (
CHIMP_STR_NEW("frame"), chimp_object_class, sizeof(ChimpFrame));
if (chimp_frame_class == NULL) {
return CHIMP_FALSE;
}
CHIMP_CLASS(chimp_frame_class)->init = _chimp_frame_init;
CHIMP_CLASS(chimp_frame_class)->mark = _chimp_frame_mark;
chimp_gc_make_root (NULL, chimp_frame_class);
return CHIMP_TRUE;
}
ChimpRef *
chimp_frame_new (ChimpRef *method)
{
return chimp_class_new_instance (chimp_frame_class, method, NULL);
}
| 2.015625 | 2 |
2024-11-18T19:02:55.781697+00:00 | 2023-07-28T12:35:29 | 362c61e7a50113a4cb7f00b2b1f6adf3b63117b4 | {
"blob_id": "362c61e7a50113a4cb7f00b2b1f6adf3b63117b4",
"branch_name": "refs/heads/master",
"committer_date": "2023-07-28T12:35:29",
"content_id": "bb45e221ce7881e35a9af788d27b3de9be12fbf2",
"detected_licenses": [
"MIT"
],
"directory_id": "fd7c8d5d2ebb14e43346d8f0fc007509af9d14ca",
"extension": "c",
"filename": "i2c.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 188098777,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1662,
"license": "MIT",
"license_type": "permissive",
"path": "/todo/esp8266_custom/i2c.c",
"provenance": "stackv2-0058.json.gz:170511",
"repo_name": "a-v-s/libhalglue",
"revision_date": "2023-07-28T12:35:29",
"revision_id": "00bb4adc6851a7becaf6424bff9ebe1af94ef51b",
"snapshot_id": "f6b754eac86da750ab1bd6f7ee914b8ad8bad56b",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/a-v-s/libhalglue/00bb4adc6851a7becaf6424bff9ebe1af94ef51b/todo/esp8266_custom/i2c.c",
"visit_date": "2023-08-02T18:43:14.171423"
} | stackv2 | // https://github.com/BillyWoods/ESP8266-I2C-example/blob/master/main.c
#include <stdint.h>
#include <stdbool.h>
#include <stdlib.h>
#include "i2c.h"
#include "ets_sys.h"
#include "osapi.h"
#include "gpio.h"
#include "os_type.h"
#include "../driver/custom_i2c_master.h"
void i2c_init() {
custom_i2c_master_gpio_init();
custom_i2c_master_init();
}
int i2c_send(uint8_t i2c_addr, void* data, size_t size, bool nostop) {
int result = I2C_OK;
uint8_t i2c_addr_write = (i2c_addr << 1);
custom_i2c_master_start();
custom_i2c_master_writeByte(i2c_addr_write);
if (!custom_i2c_master_checkAck()) result = I2C_ANACK;
for (int i = 0 ; !result && i < size ; i++ ) {
custom_i2c_master_writeByte(((uint8_t*)(data))[i]);
if (!custom_i2c_master_checkAck()) result = I2C_DNACK;
}
if (!nostop && !result) custom_i2c_master_stop();
return result;
}
int i2c_recv(uint8_t i2c_addr, void* data, size_t size) {
int result = I2C_OK;
uint8_t i2c_addr_read = (i2c_addr << 1) + 1;
custom_i2c_master_start();
custom_i2c_master_writeByte(i2c_addr_read);
if (!custom_i2c_master_checkAck()) result = I2C_ANACK;
for(int i = 0; !result && i < size - 1; i++) {
((uint8_t*)(data))[i] = custom_i2c_master_readByte();
custom_i2c_master_send_ack();
if (!custom_i2c_master_checkAck()) result = I2C_DNACK;
}
// nack the final packet so that the slave releases SDA
((uint8_t*)(data))[size - 1] = custom_i2c_master_readByte();
custom_i2c_master_send_nack();
// we are nacking, so this should be nack
//if (!custom_i2c_master_checkAck()) result = I2C_DNACK;
custom_i2c_master_stop();
return result;
}
| 2.625 | 3 |
2024-11-18T19:02:55.939191+00:00 | 2016-03-02T22:04:07 | e502396fa435813ff52aa08b6a3b872bc42cca61 | {
"blob_id": "e502396fa435813ff52aa08b6a3b872bc42cca61",
"branch_name": "refs/heads/master",
"committer_date": "2016-03-02T22:04:07",
"content_id": "addd28a0555221786b1b51e02dd26706bc08928e",
"detected_licenses": [
"MIT"
],
"directory_id": "315162a0af0716c218d6bca5f10abf5b09a6c4e0",
"extension": "c",
"filename": "Collatz-BN.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 52988675,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 639,
"license": "MIT",
"license_type": "permissive",
"path": "/Collatz-BN.c",
"provenance": "stackv2-0058.json.gz:170639",
"repo_name": "iohzrd/Collatz-BN",
"revision_date": "2016-03-02T22:04:07",
"revision_id": "cac5eca59dd755323da312e0a6cb1a4d7268556c",
"snapshot_id": "3845d2447d6f4e0a9b60e6f7747d312f0dcbfeba",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/iohzrd/Collatz-BN/cac5eca59dd755323da312e0a6cb1a4d7268556c/Collatz-BN.c",
"visit_date": "2021-01-10T09:46:42.823300"
} | stackv2 | /* Collatz-BN.c - Created by iohzrd - 2016 */
#include<stdio.h>
#include<stdbool.h>
#include<gmp.h>
mpz_t n;
static mpz_t *collatz_length()
{
if (mpz_odd_p(n) == 0) //even
{
mpz_tdiv_q_ui(n, n, 2);
}
else if (mpz_even_p(n) == 0) //odd
{
mpz_mul_ui(n, n, 3);
mpz_add_ui(n, n, 1);
}
return (void *)n;
}
int main()
{
while(true)
{
unsigned long i = 1;
printf("Test # ");
gmp_scanf("%Zd", n);
while(mpz_cmp_ui(n, 1) == 1)
{
collatz_length(n);
++i;
}
printf("iterations before termination = %lu\n", i);
gmp_printf("N terminated at = %Zd\n", n);
}
mpz_clear(n);
}
| 3.4375 | 3 |
2024-11-18T19:02:56.044345+00:00 | 2017-06-30T21:33:35 | d518d7b6277c91cc62c2c3d28acf3cf13f609cb5 | {
"blob_id": "d518d7b6277c91cc62c2c3d28acf3cf13f609cb5",
"branch_name": "refs/heads/master",
"committer_date": "2017-06-30T21:33:35",
"content_id": "c461b123c89a163b69ed5c2b8e0ec7efd4ad055a",
"detected_licenses": [
"MIT"
],
"directory_id": "78159ed2a9aae778b2ff6cec02176005b05967fe",
"extension": "c",
"filename": "parse.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": 1339,
"license": "MIT",
"license_type": "permissive",
"path": "/parse.c",
"provenance": "stackv2-0058.json.gz:170767",
"repo_name": "moneytech/nail-lang",
"revision_date": "2017-06-30T21:33:35",
"revision_id": "dcbe23a15569f8da576e0efdf1a21ba556ff7ceb",
"snapshot_id": "a7efe177d5a7dfec25cadceba82bf8db16be6b7f",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/moneytech/nail-lang/dcbe23a15569f8da576e0efdf1a21ba556ff7ceb/parse.c",
"visit_date": "2020-11-27T07:21:37.457387"
} | stackv2 | #include "tokenize.h"
#include "object.h"
#include "stdlib.h"
#include "string.h"
#include "stdio.h"
int current = 0;
int unterminated_parens = 0;
nObj parse(list tokens) {
if(current == length(tokens)) {
current = 0;
if(unterminated_parens) {
puts("Parse error: unterminated parens");
exit(1);
}
return NULL;
}
nObj result;
Token* head = at(tokens,current);
current++;
switch(head->type) {
case TK_QUOTE:
result = new_empty_list();
result->typedata.head = new_sym("'");
result->typedata.head->next = parse(tokens);
return result;
case TK_LPAREN:
result = new_empty_list();
unterminated_parens++;
result->typedata.head = parse(tokens);
break;
case TK_RPAREN:
unterminated_parens--;
return NULL;
case TK_STR:
result = new_str((char*)head->value);
break;
case TK_SYM:
result = new_sym((char*)head->value);
break;
case TK_NUM:
result = new_num(*((float*)head->value));
break;
}
result->next = parse(tokens);
return result;
}
/*
int main() {
char buffer[100] = "";
while(1) {
fgets(buffer,100,stdin);
list tokens = tokenize(buffer);
nObj result = parse(tokens);
out_nObj(result);
putchar('\n');
free_tokens(tokens);
free_nObj(result);
}
}*/
| 2.5625 | 3 |
2024-11-18T19:02:56.382453+00:00 | 2013-11-22T17:28:14 | 4a9f6169f62fc5201b8d84b7532753d00ec22438 | {
"blob_id": "4a9f6169f62fc5201b8d84b7532753d00ec22438",
"branch_name": "refs/heads/master",
"committer_date": "2013-11-25T16:21:41",
"content_id": "79d6e4124432bc98147d942b3024290b39f1f912",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "c8a9028545de3dd050c01e74479219875324f618",
"extension": "h",
"filename": "malloc.h",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 14709926,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 806,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/bsd/sys/sys/malloc.h",
"provenance": "stackv2-0058.json.gz:171024",
"repo_name": "glommer/osv",
"revision_date": "2013-11-22T17:28:14",
"revision_id": "cf482bcca540bd06f12a478cf800fbb4bd000cb9",
"snapshot_id": "751d036b151ed547c3fea7995d9f8ca943ea33c1",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/glommer/osv/cf482bcca540bd06f12a478cf800fbb4bd000cb9/bsd/sys/sys/malloc.h",
"visit_date": "2021-01-17T17:54:48.860797"
} | stackv2 | #ifndef _BSD_MALLOC_H
#define _BSD_MALLOC_H
#include <bsd/porting/mmu.h>
#include <bsd/porting/netport.h>
// just our malloc impl.
#include <malloc.h>
#include "param.h" // BSD malloc includes this, so some files do not.
// Also differentiate from include/api/sys/param.h
#include "priority.h"
#ifdef __FBSDID
// But BSD malloc has extra parameters, that we will ignore. The third parameter though
// is important, since it can be asking us to zero memory. That one we honor
static inline void *__bsd_malloc(size_t size, int flags)
{
void *ptr = malloc(size);
if (!ptr)
return ptr;
if (flags & M_ZERO)
memset(ptr, 0, size);
return ptr;
}
#define malloc(x, y, z) __bsd_malloc(x, z)
#define free(x, y) free(x)
#define strdup(x, y) strdup(x)
#endif
#endif
| 2.03125 | 2 |
2024-11-18T19:02:56.505370+00:00 | 2020-08-03T17:56:28 | e11ed86172150ed7b34c32a29b5eb95b50859dd1 | {
"blob_id": "e11ed86172150ed7b34c32a29b5eb95b50859dd1",
"branch_name": "refs/heads/master",
"committer_date": "2020-08-03T17:56:28",
"content_id": "76f552527e37724acd4c52092da1432be6cae077",
"detected_licenses": [
"MIT"
],
"directory_id": "3c39e92b7d2a81b9b94356ade7ae981be7d9f0bf",
"extension": "c",
"filename": "sandbox_pch.c",
"fork_events_count": 0,
"gha_created_at": "2020-08-02T03:26:59",
"gha_event_created_at": "2020-08-02T16:32:49",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 284382667,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1632,
"license": "MIT",
"license_type": "permissive",
"path": "/u-boot_u-boot_d0d07ba/src/opt/src/drivers/pch/sandbox_pch.c",
"provenance": "stackv2-0058.json.gz:171153",
"repo_name": "adde9708/codeql-uboot",
"revision_date": "2020-08-03T17:56:28",
"revision_id": "0c56e6be2deb0c369f8e1e7e517656690abb0be3",
"snapshot_id": "9b1d4d5c9fc340687c8ccc930b3d0a8e326e6554",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/adde9708/codeql-uboot/0c56e6be2deb0c369f8e1e7e517656690abb0be3/u-boot_u-boot_d0d07ba/src/opt/src/drivers/pch/sandbox_pch.c",
"visit_date": "2022-11-27T03:56:39.855516"
} | stackv2 | // SPDX-License-Identifier: GPL-2.0+
/*
* Copyright 2018 Google LLC
*/
#include <common.h>
#include <dm.h>
#include <pch.h>
struct sandbox_pch_priv {
bool protect;
};
int sandbox_get_pch_spi_protect(struct udevice *dev)
{
struct sandbox_pch_priv *priv = dev_get_priv(dev);
return priv->protect;
}
static int sandbox_pch_get_spi_base(struct udevice *dev, ulong *sbasep)
{
*sbasep = 0x10;
return 0;
}
static int sandbox_pch_set_spi_protect(struct udevice *dev, bool protect)
{
struct sandbox_pch_priv *priv = dev_get_priv(dev);
priv->protect = protect;
return 0;
}
static int sandbox_pch_get_gpio_base(struct udevice *dev, u32 *gbasep)
{
*gbasep = 0x20;
return 0;
}
static int sandbox_pch_get_io_base(struct udevice *dev, u32 *iobasep)
{
*iobasep = 0x30;
return 0;
}
int sandbox_pch_ioctl(struct udevice *dev, enum pch_req_t req, void *data,
int size)
{
switch (req) {
case PCH_REQ_TEST1:
return -ENOSYS;
case PCH_REQ_TEST2:
return *(char *)data;
case PCH_REQ_TEST3:
*(char *)data = 'x';
return 1;
default:
return -ENOSYS;
}
}
static const struct pch_ops sandbox_pch_ops = {
.get_spi_base = sandbox_pch_get_spi_base,
.set_spi_protect = sandbox_pch_set_spi_protect,
.get_gpio_base = sandbox_pch_get_gpio_base,
.get_io_base = sandbox_pch_get_io_base,
.ioctl = sandbox_pch_ioctl,
};
static const struct udevice_id sandbox_pch_ids[] = {
{ .compatible = "sandbox,pch" },
{ }
};
U_BOOT_DRIVER(sandbox_pch_drv) = {
.name = "sandbox-pch",
.id = UCLASS_PCH,
.of_match = sandbox_pch_ids,
.ops = &sandbox_pch_ops,
.priv_auto_alloc_size = sizeof(struct sandbox_pch_priv),
};
| 2.3125 | 2 |
2024-11-18T19:02:57.094161+00:00 | 2019-05-28T10:33:33 | 9f728f098963b74003e112fafa369035bdfd1403 | {
"blob_id": "9f728f098963b74003e112fafa369035bdfd1403",
"branch_name": "refs/heads/master",
"committer_date": "2019-05-28T10:33:33",
"content_id": "fe0e5b500142a56769daf35c0fe03739074a6abc",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "3f46e3237caf39d5a12e3ae2794928ea8f50e954",
"extension": "c",
"filename": "task-syrk-par.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 86323547,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1663,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/src/examples/dpotrf/task-syrk-par.c",
"provenance": "stackv2-0058.json.gz:171539",
"repo_name": "NLAFET/pcp-runtime",
"revision_date": "2019-05-28T10:33:33",
"revision_id": "222736152bc9448e55fc32da5ca55281a92bb4d5",
"snapshot_id": "92ee7c52f55b276b1a3c5ced19f44a1e49f09d14",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/NLAFET/pcp-runtime/222736152bc9448e55fc32da5ca55281a92bb4d5/src/examples/dpotrf/task-syrk-par.c",
"visit_date": "2021-03-30T18:27:33.582935"
} | stackv2 | #include <stdlib.h>
#include <cblas.h>
#include "tasks.h"
void syrk_task_par_reconfigure(int nth)
{
// empty
}
void syrk_task_par_finalize(void)
{
// empty
}
void syrk_task_par(void *ptr, int nth, int me)
{
struct syrk_task_arg *arg = (struct syrk_task_arg*) ptr;
int n = arg->n;
int k = arg->k;
double *A21 = arg->A21;
double *A22 = arg->A22;
int ldA = arg->ldA;
// Balance the load by flops.
int part[nth + 1];
const int total_work = n * (n + 1) / 2;
const int ideal_part_work = total_work / nth;
part[0] = 0;
part[nth] = n;
for (int k = 1; k < nth; ++k) {
part[k] = part[k - 1];
int work = 0;
while (work < ideal_part_work && part[k] < n) {
work += n - part[k];
part[k] += 1;
}
}
const int my_first_col = part[me];
const int my_num_cols = part[me + 1] - part[me];
const int i1 = my_first_col;
const int i2 = i1 + my_num_cols;
const int m2 = n - i2;
// TODO Insert picture (see krnl_syrk in task_chol_par).
if (my_num_cols > 0) {
cblas_dsyrk(CblasColMajor, CblasLower, CblasNoTrans,
my_num_cols, k,
-1.0, A21 + i1, ldA,
1.0, A22 + i1 + my_first_col * ldA, ldA);
}
if (m2 > 0) {
cblas_dgemm(CblasColMajor, CblasNoTrans, CblasTrans,
m2, my_num_cols, k,
-1.0, A21 + i2, ldA,
A21 + my_first_col, ldA,
1.0, A22 + i2 + my_first_col * ldA, ldA);
}
}
| 2.21875 | 2 |
2024-11-18T19:02:57.375319+00:00 | 2021-10-21T10:32:40 | 8ca24f1e00f1b897f3aa1c3f060807a93a28b5f1 | {
"blob_id": "8ca24f1e00f1b897f3aa1c3f060807a93a28b5f1",
"branch_name": "refs/heads/master",
"committer_date": "2021-10-21T10:32:40",
"content_id": "8da3be07660186023aae87a25dee3446666152b0",
"detected_licenses": [
"Zlib"
],
"directory_id": "46b6ffc9cbfd59ee196d3cfbd09d3397784c496d",
"extension": "c",
"filename": "lfswrap.c",
"fork_events_count": 0,
"gha_created_at": "2021-11-08T17:00:11",
"gha_event_created_at": "2021-11-08T17:00:12",
"gha_language": null,
"gha_license_id": "Zlib",
"github_id": 425922596,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 13890,
"license": "Zlib",
"license_type": "permissive",
"path": "/mcu/lfswrap.c",
"provenance": "stackv2-0058.json.gz:171927",
"repo_name": "dp111/BBCSDL",
"revision_date": "2021-10-21T10:32:40",
"revision_id": "ad9155da1b9afc519098644387dd20610a181e9e",
"snapshot_id": "c7eb1ab09e283365d6178074a59f69c941b1b384",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/dp111/BBCSDL/ad9155da1b9afc519098644387dd20610a181e9e/mcu/lfswrap.c",
"visit_date": "2023-08-26T06:57:33.860681"
} | stackv2 | /* lfswrap.c -- Wrappers for LittleFS and other glue for the Pico.
Written 2021 by Eric Olson
This is free software released under the exact same terms as
stated in license.txt for the Basic interpreter. */
#define SDMOUNT "sdcard" // SD Card mount point
#define SDMLEN ( strlen (SDMOUNT) + 1 )
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pico/time.h>
#include "lfswrap.h"
#ifdef HAVE_LFS
#include "lfspico.h"
lfs_t lfs_root;
lfs_bbc_t lfs_root_context;
#endif
#ifdef HAVE_FAT
#ifdef HAVE_LFS // Both FAT and LFS
static inline bool isfat (const char *path)
{
if (( ! strncmp (path, "/"SDMOUNT, SDMLEN) ) &&
( ( path[SDMLEN] == '/' ) || ( path[SDMLEN] == '\0' ) ) ) return true;
return false;
}
static inline const char *fat_path (const char *path)
{
return path + SDMLEN;
}
typedef struct
{
bool bFAT;
union
{
FIL fat_ft;
lfs_file_t lfs_ft;
};
} multi_file;
static inline bool is_fatptr (FILE *fp)
{
return ((multi_file *)fp)->bFAT;
}
static inline void set_fatptr (FILE *fp, bool bFAT)
{
((multi_file *)fp)->bFAT = bFAT;
}
static inline FIL *fatptr (FILE *fp)
{
return &((multi_file *)fp)->fat_ft;
}
static inline lfs_file_t *lfsptr (FILE *fp)
{
return &((multi_file *)fp)->lfs_ft;
}
typedef struct
{
enum { dfLFS, dfRoot, dfFstRoot, dfFAT } df;
struct dirent de;
union
{
DIR fat_dt;
lfs_dir_t lfs_dt;
};
} dir_info;
static inline bool is_fatdir (DIR *dirp)
{
return (((dir_info *)dirp)->df == dfFAT);
}
static inline void set_fatdir (DIR *dirp, bool bFAT)
{
((dir_info *)dirp)->df = bFAT ? dfFAT : dfLFS;
}
static inline DIR * fatdir (DIR *dirp)
{
return &((dir_info *)dirp)->fat_dt;
}
static inline lfs_dir_t * lfsdir (DIR *dirp)
{
return &((dir_info *)dirp)->lfs_dt;
}
static inline struct dirent * deptr (DIR *dirp)
{
return &((dir_info *)dirp)->de;
}
#else // Only HAVE_FAT
static inline bool isfat (const char *path)
{
return true;
}
static inline const char *fat_path (const char *path)
{
return path;
}
typedef FIL multi_file;
static inline bool is_fatptr (FILE *fp)
{
return true;
}
static inline void set_fatptr (FILE *fp, bool bFAT)
{
}
static inline FIL *fatptr (FILE *fp)
{
return (FIL *)fp;
}
typedef struct
{
struct dirent de;
DIR fat_dt;
} dir_info;
static inline bool is_fatdir (DIR *dirp)
{
return true;
}
static inline void set_fatdir (DIR *dirp, bool bFAT)
{
}
static inline DIR * fatdir (DIR *dirp)
{
return &((dir_info *)dirp)->fat_dt;
}
static inline struct dirent * deptr (DIR *dirp)
{
return &((dir_info *)dirp)->de;
}
#endif
#else
#ifdef HAVE_LFS // Only HAVE_LFS
typedef lfs_file_t multi_file;
static inline void set_fatptr (FILE *fp, bool bFAT)
{
}
static inline lfs_file_t *lfsptr (FILE *fp)
{
return (lfs_file_t *)fp;
}
typedef struct
{
struct dirent de;
lfs_dir_t lfs_dt;
} dir_info;
static inline void set_fatdir (DIR *dirp, bool bFAT)
{
}
static inline lfs_dir_t * lfsdir (DIR *dirp)
{
return &((dir_info *)dirp)->lfs_dt;
}
static inline struct dirent * deptr (DIR *dirp)
{
return &((dir_info *)dirp)->de;
}
#endif
#endif
static int picoslash(char c)
{
if(c=='/'||c=='\\') return 1;
return 0;
}
static int picovert(char c)
{
if(picoslash(c)||c==0) return 1;
return 0;
}
static const char *picoedge(const char *p)
{
const char *q=p;
while(*q)
{
if(picoslash(*q)) return q+1;
q++;
}
return q;
}
static int picosame(const char *q,const char *p)
{
for(;;)
{
if(picovert(*p))
{
if(picovert(*q))
{
return 1;
} else {
return 0;
}
} else if(picovert(*q)) {
return 0;
} else if(*q!=*p) {
return 0;
}
q++; p++;
}
}
static void picorem(char *pcwd)
{
char *p=pcwd,*q=0;
while(*p)
{
if(picoslash(*p)) q=p;
p++;
}
if(q) *q=0;
else *pcwd=0;
}
static void picoadd(char *pcwd,const char *p)
{
char *q=pcwd;
while(*q) q++;
*q++='/';
while(!(picovert(*p))) *q++=*p++;
*q=0;
}
static char picocwd[260]="";
char *myrealpath(const char *restrict p, char *restrict r)
{
if(r==0) r=malloc(260);
if(r==0) return 0;
strcpy(r,picocwd);
if(picosame(p,"/"))
{
*r=0;
if(!*p) return r;
p++;
}
const char *f=picoedge(p);
while(f-p>0)
{
if(picosame(p,"/")||picosame(p,"./"))
{
} else if(picosame(p,"../"))
{
picorem(r);
} else {
picoadd(r,p);
}
p=f; f=picoedge(p);
}
return r;
}
static char picopath[260];
int mychdir(const char *p)
{
myrealpath(p,picopath);
#ifdef HAVE_FAT
if ( isfat (picopath) )
{
if ( f_chdir (fat_path (picopath)) != FR_OK ) return -1;
strcpy(picocwd,picopath);
return 0;
}
#endif
#ifdef HAVE_LFS
lfs_dir_t d;
if(lfs_dir_open(&lfs_root,&d,picopath)<0)
{
return -1;
}
lfs_dir_close(&lfs_root,&d);
strcpy(picocwd,picopath);
return 0;
#endif
}
int mymkdir(const char *p, mode_t m)
{
(void) m;
myrealpath(p,picopath);
#ifdef HAVE_FAT
if ( isfat (picopath) )
{
printf ("mkdir (%s)\n", picopath);
if ( f_mkdir (fat_path (picopath)) != FR_OK ) return -1;
return 0;
}
#endif
#ifdef HAVE_LFS
int r=lfs_mkdir(&lfs_root,picopath);
if(r<0) return -1;
return 0;
#endif
}
int myrmdir(const char *p)
{
myrealpath(p,picopath);
#ifdef HAVE_FAT
if ( isfat (picopath) )
{
if ( f_unlink (fat_path (picopath)) != FR_OK ) return -1;
return 0;
}
#endif
#ifdef HAVE_LFS
int r=lfs_remove(&lfs_root,picopath);
if(r<0) return -1;
return 0;
#endif
}
int mychmod(const char *p, mode_t m)
{
return 0;
}
char *mygetcwd(char *b, size_t s)
{
strncpy(b,picocwd,s);
return b;
}
long myftell(FILE *fp)
{
#ifdef HAVE_FAT
if ( is_fatptr (fp) )
{
return f_tell (fatptr (fp));
}
#endif
#ifdef HAVE_LFS
int r = lfs_file_tell(&lfs_root, lfsptr (fp));
if (r < 0) return -1;
return r;
#endif
}
int myfseek(FILE *fp, long offset, int whence)
{
#ifdef HAVE_FAT
if ( is_fatptr (fp) )
{
FIL *pf = fatptr (fp);
if (whence == SEEK_END) offset += f_size (pf);
else if (whence == SEEK_CUR) offset += f_tell (pf);
if ( f_lseek (pf, offset) != FR_OK ) return -1;
return 0;
}
#endif
#ifdef HAVE_LFS
int lfs_whence=LFS_SEEK_SET;
if(whence==SEEK_END) lfs_whence=LFS_SEEK_END;
else if(whence==SEEK_CUR) lfs_whence=LFS_SEEK_CUR;
int r=lfs_file_seek(&lfs_root,(void *)fp,offset,lfs_whence);
if(r<0) return -1;
return 0;
#endif
}
FILE *myfopen(char *p, char *mode)
{
#if defined(HAVE_FAT) || defined(HAVE_LFS)
FILE *fp = (FILE *) malloc (sizeof (multi_file));
if ( fp == NULL ) return NULL;
myrealpath(p,picopath);
#else
return NULL;
#endif
#ifdef HAVE_FAT
if ( isfat (picopath) )
{
unsigned char om = 0;
switch (mode[0])
{
case 'r':
om = FA_READ;
if ( mode[1] == '+' ) om |= FA_WRITE;
break;
case 'w':
om = FA_CREATE_ALWAYS | FA_WRITE;
if ( mode[1] == '+' ) om |= FA_READ;
break;
case 'a':
om = FA_OPEN_APPEND;
if ( mode[1] == '+' ) om |= FA_READ;
break;
}
if ( f_open (fatptr (fp), fat_path (picopath), om) != FR_OK )
{
free (fp);
return NULL;
}
set_fatptr (fp, true);
return fp;
}
#endif
#ifdef HAVE_LFS
enum lfs_open_flags of = 0;
switch (mode[0])
{
case 'r':
of = LFS_O_RDONLY;
if ( mode[1] == '+' ) of = LFS_O_RDWR;
break;
case 'w':
of = LFS_O_CREAT | LFS_O_TRUNC | LFS_O_WRONLY;
if ( mode[1] == '+' ) of = LFS_O_CREAT | LFS_O_TRUNC | LFS_O_RDWR;
break;
case 'a':
of = LFS_O_CREAT | LFS_O_TRUNC | LFS_O_RDONLY | LFS_O_APPEND;
if ( mode[1] == '+' ) of = LFS_O_CREAT | LFS_O_TRUNC | LFS_O_RDWR | LFS_O_APPEND;
break;
}
if ( lfs_file_open (&lfs_root, lfsptr (fp), picopath, of) < 0 )
{
free (fp);
return NULL;
}
set_fatptr (fp, false);
return fp;
#endif
}
int myfclose(FILE *fp)
{
#ifdef HAVE_FAT
if ( is_fatptr (fp) )
{
FRESULT fr = f_close (fatptr (fp));
free (fp);
return ( fr != FR_OK ) ? -1 : 0;
}
#endif
#ifdef HAVE_LFS
int r = lfs_file_close (&lfs_root, lfsptr (fp));
free (fp);
return ( r < 0 ) ? -1 : 0;
#endif
}
size_t myfread(void *ptr, size_t size, size_t nmemb, FILE *fp)
{
if (fp == stdin)
{
#undef fread
return fread(ptr, size, nmemb, stdin);
#define fread myfread
}
#ifdef HAVE_FAT
if ( is_fatptr (fp) )
{
unsigned int nbyte;
if (size == 1)
{
if ( f_read (fatptr (fp), ptr, nmemb, &nbyte) < FR_OK ) return nbyte;
}
else
{
for (int i = 0; i < nmemb; ++i)
{
FRESULT fr = f_read (fatptr (fp), ptr, size, &nbyte);
if ((fr != FR_OK) || (nbyte < size)) return i;
ptr += size;
}
}
return nmemb;
}
#endif
#ifdef HAVE_LFS
if (size == 1)
{
int r = lfs_file_read (&lfs_root, lfsptr (fp), (char *)ptr, nmemb);
if (r < 0) return 0;
return r;
}
for (int i = 0; i < nmemb; ++i)
{
if (lfs_file_read (&lfs_root, lfsptr (fp), (char *)ptr, size) < 0) return i;
ptr += size;
}
return nmemb;
#endif
}
size_t myfwrite(void *ptr, size_t size, size_t nmemb, FILE *fp)
{
if (fp == stdout || fp == stderr)
{
#undef fwrite
return fwrite (ptr, size, nmemb, stdout);
#define fwrite myfwrite
}
#ifdef HAVE_FAT
if ( is_fatptr (fp) )
{
unsigned int nbyte;
if (size == 1)
{
if ( f_write (fatptr (fp), ptr, nmemb, &nbyte) < FR_OK ) return nbyte;
}
else
{
for (int i = 0; i < nmemb; ++i)
{
FRESULT fr = f_write (fatptr (fp), ptr, size, &nbyte);
if ((fr != FR_OK) || (nbyte < size)) return i;
ptr += size;
}
}
return nmemb;
}
#endif
#ifdef HAVE_LFS
if (size == 1)
{
int r = lfs_file_write (&lfs_root, lfsptr (fp), (char *)ptr, nmemb);
if (r < 0) return 0;
return r;
}
for (int i = 0; i < nmemb; ++i)
{
if (lfs_file_write (&lfs_root, lfsptr (fp), (char *)ptr, size) < 0) return i;
ptr += size;
}
return nmemb;
#endif
}
int usleep(useconds_t usec)
{
sleep_us(usec);
return 0;
}
unsigned int sleep(unsigned int seconds)
{
sleep_ms(seconds*1000);
return 0;
}
DIR *myopendir(const char *name)
{
#if defined(HAVE_FAT) || defined(HAVE_LFS)
DIR *dirp = (DIR *) malloc (sizeof (dir_info));
if ( dirp == NULL ) return NULL;
myrealpath(name, picopath);
#else
return NULL;
#endif
#ifdef HAVE_FAT
if ( isfat (picopath) )
{
if ( picopath[7] == '\0' ) strcpy (&picopath[7], "/");
if ( f_opendir (fatdir(dirp), fat_path(picopath)) != FR_OK )
{
free (dirp);
return NULL;
}
set_fatdir (dirp, true);
return dirp;
}
#endif
#ifdef HAVE_LFS
if ( lfs_dir_open(&lfs_root, lfsdir(dirp), name) < 0 )
{
free (dirp);
return NULL;
}
set_fatdir (dirp, false);
#ifdef HAVE_FAT
if ( picopath[0] == '\0' )
{
((dir_info *)dirp)->df = dfFstRoot;
}
#endif
return (DIR *) dirp;
#endif
}
struct dirent *myreaddir(DIR *dirp)
{
if ( dirp == NULL ) return NULL;
#ifdef HAVE_FAT
if ( is_fatdir(dirp) )
{
FILINFO fi;
if ( f_readdir (fatdir(dirp), &fi) != FR_OK ) return NULL;
if ( fi.fname[0] == '\0' ) return NULL;
struct dirent *pde = deptr (dirp);
strncpy (pde->d_name, fi.fname, NAME_MAX);
if ( fi.fattrib & AM_DIR ) strcat (pde->d_name, "/");
return pde;
}
#endif
#ifdef HAVE_LFS
struct dirent *pde = deptr (dirp);
#ifdef HAVE_FAT
// Insert mount point as first root directory entry
if (((dir_info *)dirp)->df == dfFstRoot )
{
((dir_info *)dirp)->df = dfRoot;
strcpy (pde->d_name, SDMOUNT"/");
return pde;
}
#endif
struct lfs_info r;
if ( !lfs_dir_read (&lfs_root, lfsdir(dirp), &r) ) return NULL;
#ifdef HAVE_FAT
// Hide any root entry with the same name as the mount point
if ((((dir_info *)dirp)->df == dfRoot) && (!strcmp (r.name, SDMOUNT)))
{
if ( !lfs_dir_read (&lfs_root, lfsdir(dirp), &r) ) return NULL;
}
#endif
strncpy (pde->d_name, r.name, NAME_MAX);
if ( r.type == LFS_TYPE_DIR ) strcat (pde->d_name, "/");
return pde;
#endif
}
int myclosedir(DIR *dirp)
{
if ( dirp == NULL ) return -1;
#ifdef HAVE_FAT
if ( is_fatdir(dirp) )
{
FRESULT fr = f_closedir (fatdir(dirp));
free (dirp);
return ( fr != FR_OK ) ? -1 : 0;
}
#endif
#ifdef HAVE_LFS
lfs_dir_close (&lfs_root, lfsdir(dirp));
free (dirp);
return 0;
#endif
}
#ifdef HAVE_LFS
static struct lfs_config lfs_root_cfg = {
.context = &lfs_root_context,
.read = lfs_bbc_read,
.prog = lfs_bbc_prog,
.erase = lfs_bbc_erase,
.sync = lfs_bbc_sync,
.read_size = 1,
.prog_size = FLASH_PAGE_SIZE,
.block_size = FLASH_SECTOR_SIZE,
.block_count = ROOT_SIZE / FLASH_SECTOR_SIZE,
.cache_size = FLASH_PAGE_SIZE,
.cache_size = 256,
.lookahead_size = 32,
.block_cycles = 256
};
#endif
extern void waitconsole();
int mount (void)
{
int istat = 0;
#ifdef HAVE_LFS
struct lfs_bbc_config lfs_bbc_cfg =
{
.buffer=(uint8_t *)XIP_BASE+ROOT_OFFSET
};
lfs_bbc_createcfg(&lfs_root_cfg, &lfs_bbc_cfg);
int lfs_err = lfs_mount(&lfs_root, &lfs_root_cfg);
if (lfs_err)
{
lfs_format(&lfs_root, &lfs_root_cfg);
lfs_err = lfs_mount(&lfs_root, &lfs_root_cfg);
if (lfs_err)
{
waitconsole();
printf("unable for format littlefs\n");
istat |= 2;
}
}
#endif
#ifdef HAVE_FAT
static FATFS vol;
FRESULT fr = f_mount (&vol, "0:", 1);
if ( fr != FR_OK )
{
waitconsole();
printf ("Failed to mount SD card.\n");
istat |= 1;
}
#endif
return istat;
}
| 2.09375 | 2 |
2024-11-18T19:02:57.471454+00:00 | 2019-11-04T16:50:16 | c809e59541b3ff8adf186e290f831e347261a2e2 | {
"blob_id": "c809e59541b3ff8adf186e290f831e347261a2e2",
"branch_name": "refs/heads/master",
"committer_date": "2019-11-04T16:50:16",
"content_id": "920d5bbc8a9b32ba0c7f2f0409f9dd9b84f78f80",
"detected_licenses": [
"MIT"
],
"directory_id": "f3277b1c41eb85f4cf04ea0a3c1518700874dd50",
"extension": "c",
"filename": "problem3-hex-converter.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": 1057,
"license": "MIT",
"license_type": "permissive",
"path": "/2nd-term/Programming/Report2/problem3-hex-converter.c",
"provenance": "stackv2-0058.json.gz:172056",
"repo_name": "ntcho/CAU2019",
"revision_date": "2019-11-04T16:50:16",
"revision_id": "c8c462190fcf3ece0d8fa6159a45566c9db93b28",
"snapshot_id": "645de6d95963328e2ba2a7e1f76546fa65b8c805",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ntcho/CAU2019/c8c462190fcf3ece0d8fa6159a45566c9db93b28/2nd-term/Programming/Report2/problem3-hex-converter.c",
"visit_date": "2022-03-01T18:53:57.651574"
} | stackv2 | // 3번 문제
// 입력받은 3자리 10진수 n을 16진수로 표현하는 재귀함수 tohex(int n)
// 재귀함수를 이용해 16진수 표현을 출력하는 프로그램
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
void tohex(int);
int main() {
int n;
while (1) {
//printf("16진수로 출력할 3자리의 숫자 N을 입력하세요: ");
printf("Input 3 digit number N to print as hexadecimal: ");
int result = scanf("%d", &n);
if (result != 1) {
while (getchar() != '\n'); // clear input buffer
}
else if (n >= 100 && n < 1000) {
break;
}
else {
//printf("오류: 입력은 3자리 수여야 합니다.\n");
printf("Error: Input number should be a 3 digit number.\n");
}
};
//printf("%d 의 16진수 표현 = ", n);
printf("%d in hexadecimal = ", n);
tohex(n);
// 창 종료 방지
getch();
}
void tohex(int n) {
if (n >= 16) {
tohex(n / 16);
}
if (n % 16 < 10) {
printf("%d", n % 16);
}
else if (n % 16 >= 10 && n % 16 < 16) {
printf("%c", ((n % 16) - 10) + 'A');
}
} | 3.90625 | 4 |
2024-11-18T19:02:57.577774+00:00 | 2016-06-12T18:43:24 | 63ca382ce4d06e566b6904cdc3a2a3e7eb534f1b | {
"blob_id": "63ca382ce4d06e566b6904cdc3a2a3e7eb534f1b",
"branch_name": "refs/heads/master",
"committer_date": "2016-06-12T18:43:24",
"content_id": "b0252d994b0d0e0598a8a3a40fd5bce5f209c9c9",
"detected_licenses": [
"MIT"
],
"directory_id": "13a0a7b2e7781b83d0e4a740d044f518cfce25ff",
"extension": "c",
"filename": "wc.c",
"fork_events_count": 3,
"gha_created_at": "2016-03-09T14:21:38",
"gha_event_created_at": "2016-06-12T14:51:13",
"gha_language": "Shell",
"gha_license_id": null,
"github_id": 53503509,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1479,
"license": "MIT",
"license_type": "permissive",
"path": "/midterm/81170/wc.c",
"provenance": "stackv2-0058.json.gz:172184",
"repo_name": "rgeorgiev583/os-2015-2016",
"revision_date": "2016-06-12T18:43:24",
"revision_id": "125f566b66f8b7e35c010f56ddd9749cefcee077",
"snapshot_id": "5ef511c481cd974ebe02184b9340e74f1f5b185e",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/rgeorgiev583/os-2015-2016/125f566b66f8b7e35c010f56ddd9749cefcee077/midterm/81170/wc.c",
"visit_date": "2021-01-21T04:50:36.080513"
} | stackv2 | #include <fcntl.h>
#include <unistd.h>
#include <sys/wait.h>
#include <string.h>
#include <stdio.h>
// Implemented extra credit! (+1)
// Excellent implementation! stdin is not supported, though.
int main(int argc, char *argv[]) {
char c;
int read_count;
char option = '\0';
int startIndex = 1;
if (argc > 2) {
if (strcmp(argv[1], "-c") == 0) {
option = 'c';
startIndex = 2;
} else if (strcmp(argv[1], "-w") == 0) {
option = 'w';
startIndex = 2;
} else if (strcmp(argv[1], "-l") == 0) {
option = 'l';
startIndex = 2;
}
}
for (int i = startIndex; i < argc; ++i) {
if (!fork()) {
char *filename = argv[i];
int fd = open(filename, O_RDONLY);
int lines = 0;
int words = 0;
int chars = 0;
while ((read_count = read(fd, &c, 1))) {
if (c == ' ') {
words++;
} else if (c == '\n') {
lines++;
words++;
}
chars++;
}
if (option == 'c') {
printf("%d %s\n", chars, filename);
} else if (option == 'w') {
printf("%d %s\n", words, filename);
} else if (option == 'l') {
printf("%d %s\n", lines, filename);
} else {
printf("%d %d %d %s\n", lines, words, chars, filename);
}
close(fd);
return 0;
}
}
for (int i = startIndex; i < argc; ++i) {
int status;
wait(&status);
}
return 0;
}
// Total points for this task: 3/2
| 2.828125 | 3 |
2024-11-18T19:02:57.649058+00:00 | 2020-04-13T16:21:57 | 83e85589b8fcad9d194299a6dcc7460befd9d58c | {
"blob_id": "83e85589b8fcad9d194299a6dcc7460befd9d58c",
"branch_name": "refs/heads/master",
"committer_date": "2020-04-13T16:21:57",
"content_id": "720edb340908dd950eaf208a2cc8d3ac2c44b52d",
"detected_licenses": [
"MIT"
],
"directory_id": "6ee5312f77d693192d94c7bddff5ad9922003d7b",
"extension": "c",
"filename": "gtt_ext_types.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 143469007,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 375,
"license": "MIT",
"license_type": "permissive",
"path": "/src/gtt_ext_types.c",
"provenance": "stackv2-0058.json.gz:172314",
"repo_name": "MatrixOrbital/MatrixOrbitalGTTClientLibrary",
"revision_date": "2020-04-13T16:21:57",
"revision_id": "0f2478b2a45d7454ce154090bc41626d028d9f9a",
"snapshot_id": "aef1405297f33e0aaf6aeff45628b9e0d8cc6542",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/MatrixOrbital/MatrixOrbitalGTTClientLibrary/0f2478b2a45d7454ce154090bc41626d028d9f9a/src/gtt_ext_types.c",
"visit_date": "2021-08-05T17:13:33.495952"
} | stackv2 | #include <gtt_protocol.h>
#include <gtt_ext_types.h>
gtt_bytearray_l8 gtt_make_bytearray_l8(uint8_t length, uint8_t *data)
{
gtt_bytearray_l8 res;
res.length = length;
res.Data = data;
return res;
}
gtt_bytearray_l16 gtt_make_bytearray_l16(uint16_t length, uint8_t *data)
{
gtt_bytearray_l16 res;
res.length = length;
res.Data = data;
return res;
} | 2.03125 | 2 |
2024-11-18T19:02:57.866948+00:00 | 2022-01-10T13:00:40 | f1c3067388eadd353ecdac51230dc44e6b1abc9b | {
"blob_id": "f1c3067388eadd353ecdac51230dc44e6b1abc9b",
"branch_name": "refs/heads/master",
"committer_date": "2022-01-10T13:00:40",
"content_id": "d154c9357f897cb3b858f1325e4d72bb7ddae6d1",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "0526f33b40ce0ac8972b80c986fb3f7e8c0d1d6f",
"extension": "c",
"filename": "litl_merge.c",
"fork_events_count": 1,
"gha_created_at": "2020-12-03T10:44:35",
"gha_event_created_at": "2021-02-15T09:27:57",
"gha_language": "C",
"gha_license_id": "BSD-2-Clause",
"github_id": 318160265,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 8045,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/src/litl_merge.c",
"provenance": "stackv2-0058.json.gz:172572",
"repo_name": "trahay/LiTL",
"revision_date": "2022-01-10T13:00:40",
"revision_id": "909f55a9daf45f31820f81db8b90d64799f315cd",
"snapshot_id": "51172e8e194bc1e32bf8b6d81d9fed86c4687130",
"src_encoding": "UTF-8",
"star_events_count": 6,
"url": "https://raw.githubusercontent.com/trahay/LiTL/909f55a9daf45f31820f81db8b90d64799f315cd/src/litl_merge.c",
"visit_date": "2023-09-02T17:02:27.886485"
} | stackv2 | /* -*- c-file-style: "GNU" -*- */
/*
* Copyright © Télécom SudParis.
* See COPYING in top-level directory.
*/
#define _GNU_SOURCE
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include "litl_merge.h"
static litl_trace_merge_t* __arch;
static litl_trace_triples_t** __triples;
/*
* Sets a new name for the archive
*/
static void __litl_merge_set_archive_name(const char* filename) {
int res __attribute__ ((__unused__));
// check whether the file name was set. If no, set it by default trace name
if (filename == NULL )
res = asprintf(&__arch->filename, "/tmp/%s_%s", getenv("USER"),
"litl_archive_1");
if (asprintf(&__arch->filename, "%s", filename) == -1) {
perror("Error: Cannot set the filename for recording events!\n");
exit(EXIT_FAILURE);
}
}
/*
* Adds a trace header:
* - The number of traces
* - Triples: a file id, a file size, and an offset
*/
static void __litl_merge_add_archive_header() {
int trace_in, res __attribute__ ((__unused__));
litl_med_size_t trace_index, process_index, general_header_size,
process_header_size, global_header_size, nb_processes, total_nb_processes;
litl_buffer_t header_buffer;
total_nb_processes = 0;
global_header_size = 0;
general_header_size = sizeof(litl_general_header_t);
process_header_size = sizeof(litl_process_header_t);
// create an array of arrays of offsets
__triples = (litl_trace_triples_t **) malloc(
__arch->nb_traces * sizeof(litl_trace_triples_t *));
// read all header of traces and write them to the global header of the archive
for (trace_index = 0; trace_index < __arch->nb_traces; trace_index++) {
if ((trace_in = open(__arch->traces_names[trace_index], O_RDONLY)) < 0) {
fprintf(stderr, "[litl_merge] Cannot open %s to read its header\n",
__arch->traces_names[trace_index]);
exit(EXIT_FAILURE);
}
// read the trace header
header_buffer = (litl_buffer_t) malloc(general_header_size);
res = read(trace_in, header_buffer, general_header_size);
nb_processes = ((litl_general_header_t *) header_buffer)->nb_processes;
__triples[trace_index] = (litl_trace_triples_t *) malloc(
nb_processes * sizeof(litl_trace_triples_t));
// add a general header
if (trace_index == 0) {
sprintf((char*) ((litl_general_header_t *) __arch->buffer)->litl_ver,
"%s",
(char*) ((litl_general_header_t *) header_buffer)->litl_ver);
sprintf((char*) ((litl_general_header_t *) __arch->buffer)->sysinfo, "%s",
(char*) ((litl_general_header_t *) header_buffer)->sysinfo);
global_header_size += general_header_size;
__arch->buffer += general_header_size;
}
// read headers of processes
res = read(trace_in, __arch->buffer, nb_processes * process_header_size);
// find the trace size
if (nb_processes == 1) {
struct stat st;
if (fstat(trace_in, &st)) {
perror("Cannot apply fstat to the input trace files!");
exit(EXIT_FAILURE);
}
((litl_process_header_t *) __arch->buffer)->trace_size =
(litl_trace_size_t) st.st_size - general_header_size
- process_header_size;
}
for (process_index = 0; process_index < nb_processes; process_index++) {
__triples[trace_index][process_index].nb_processes = nb_processes;
__triples[trace_index][process_index].position = global_header_size
+ (process_index + 1) * process_header_size - sizeof(litl_offset_t);
__triples[trace_index][process_index].offset =
((litl_process_header_t *) __arch->buffer)->offset - general_header_size
- nb_processes * process_header_size;
__arch->buffer += process_header_size;
}
total_nb_processes += nb_processes;
global_header_size += nb_processes * process_header_size;
free(header_buffer);
close(trace_in);
}
// update the number of processes
((litl_general_header_t *) __arch->buffer_ptr)->nb_processes =
total_nb_processes;
res = write(__arch->f_handle, __arch->buffer_ptr, global_header_size);
__arch->general_offset += global_header_size;
__arch->buffer = __arch->buffer_ptr;
}
/*
* Creates and opens an archive for traces.
* Allocates memory for the buffer
*/
static void __litl_merge_init_archive(const char* arch_name,
char** traces_names, const int nb_traces) {
__arch = (litl_trace_merge_t *) malloc(sizeof(litl_trace_merge_t));
// allocate buffer for read/write ops
__arch->buffer_size = 16 * 1024 * 1024; // 16 MB
__arch->buffer_ptr = (litl_buffer_t) calloc(__arch->buffer_size, 1);
__arch->buffer = __arch->buffer_ptr;
__arch->nb_traces = nb_traces;
__arch->traces_names = traces_names;
__arch->general_offset = 0;
__litl_merge_set_archive_name(arch_name);
// create an archive for trace files in rw-r-r- mode (0644)
if ((__arch->f_handle = open(__arch->filename, O_WRONLY | O_CREAT, 0644))
< 0) {
fprintf(stderr, "[litl_merge] Cannot open %s archive\n", __arch->filename);
exit(EXIT_FAILURE);
}
// add a general archive header and also a set of process headers
__litl_merge_add_archive_header();
}
/*
* Merges trace files. This is a modified version of the cat implementation
* from the Kernighan & Ritchie book
*/
static void __litl_merge_create_archive() {
int trace_in, res;
litl_offset_t offset;
litl_med_size_t trace_index, process_index, nb_processes;
litl_trace_size_t header_offset, general_header_size, process_header_size;
general_header_size = sizeof(litl_general_header_t);
process_header_size = sizeof(litl_process_header_t);
for (trace_index = 0; trace_index < __arch->nb_traces; trace_index++) {
if ((trace_in = open(__arch->traces_names[trace_index], O_RDONLY)) < 0) {
fprintf(stderr, "[litl_merge] Cannot open %s\n",
__arch->traces_names[trace_index]);
exit(EXIT_FAILURE);
}
// update offsets of processes
nb_processes = __triples[trace_index][0].nb_processes;
for (process_index = 0; process_index < nb_processes; process_index++) {
lseek(__arch->f_handle, __triples[trace_index][process_index].position,
SEEK_SET);
offset = __triples[trace_index][process_index].offset
+ __arch->general_offset;
res = write(__arch->f_handle, &offset, sizeof(litl_offset_t));
lseek(__arch->f_handle, __arch->general_offset, SEEK_SET);
}
// merge traces
header_offset = general_header_size + nb_processes * process_header_size;
lseek(trace_in, header_offset, SEEK_SET);
// solution: Reading and writing blocks of data. Use the file size
// to deal with the reading of the last block from the
// traces
while (1) {
res = read(trace_in, __arch->buffer, __arch->buffer_size);
if (res < 0) {
perror("Cannot read the data from the traces!");
exit(EXIT_FAILURE);
}
res = write(__arch->f_handle, __arch->buffer, res);
__arch->general_offset += res;
if ((litl_size_t) res < __arch->buffer_size)
break;
}
close(trace_in);
}
}
/*
* Frees the allocated memory
*/
static void __litl_merge_finalize_archive() {
close(__arch->f_handle);
// free offsets
litl_med_size_t trace_index;
for (trace_index = 0; trace_index < __arch->nb_traces; trace_index++)
free(__triples[trace_index]);
free(__triples);
// free filenames
free(__arch->filename);
for (trace_index = 0; trace_index < __arch->nb_traces; trace_index++)
free(__arch->traces_names[trace_index]);
free(__arch->traces_names);
free(__arch->buffer_ptr);
__arch->buffer_ptr = NULL;
__arch = NULL;
}
void litl_merge_traces(const char* arch_name, char** traces_names,
const int nb_traces) {
__litl_merge_init_archive(arch_name, traces_names, nb_traces);
__litl_merge_create_archive();
__litl_merge_finalize_archive();
}
| 2.421875 | 2 |
2024-11-18T19:02:58.052210+00:00 | 2020-07-29T08:42:21 | b3ee06a815b0f5822c1b59112e8217cbfc6ea4cf | {
"blob_id": "b3ee06a815b0f5822c1b59112e8217cbfc6ea4cf",
"branch_name": "refs/heads/master",
"committer_date": "2020-07-29T08:42:21",
"content_id": "d53c5cdccae10106bd819fb367504a02cacd462f",
"detected_licenses": [
"MIT"
],
"directory_id": "c90c739fa3fb27f2afa456fe9cf8dea8bed34892",
"extension": "c",
"filename": "password_request_handler.c",
"fork_events_count": 2,
"gha_created_at": "2020-06-27T11:50:22",
"gha_event_created_at": "2020-07-29T08:42:22",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 275361656,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1705,
"license": "MIT",
"license_type": "permissive",
"path": "/server/src/requests/password_request_handler.c",
"provenance": "stackv2-0058.json.gz:172830",
"repo_name": "UBandera/uchat",
"revision_date": "2020-07-29T08:42:21",
"revision_id": "f95f852fe761b58e120740d3e0776a2e8c52e180",
"snapshot_id": "955344741742df14a7c829f9c41096b698c95e79",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/UBandera/uchat/f95f852fe761b58e120740d3e0776a2e8c52e180/server/src/requests/password_request_handler.c",
"visit_date": "2022-11-25T05:45:20.791239"
} | stackv2 | #include "server.h"
static gchar *password_send_response(void) {
cJSON *json = cJSON_CreateObject();
gchar *message = "Password has successfully sent.";
gchar *response = NULL;
cJSON_AddItemToObject(json,
"response_type",
cJSON_CreateNumber(RS_PASSWORD_SENT));
cJSON_AddItemToObject(json, "message", cJSON_CreateString(message));
response = cJSON_PrintUnformatted(json);
if (!response){
g_warning("Failed to print make request.\n");
}
cJSON_Delete(json);
return response;
}
static void send_response(gint status, t_client *client) {
gchar *response = NULL;
if (!status)
response = password_send_response();
else
response = mx_send_error_response(ER_SENT_PASS,
"Sending password error");
mx_send_data(client->data_out, response);
g_free(response);
}
void mx_password_request_handler(cJSON *root, t_client *client) {
if (cJSON_GetObjectItem(root, "phone")) {
gchar *phone = cJSON_GetObjectItem(root, "phone")->valuestring;
gint status = 0;
gchar *body = NULL;
gchar *password = mx_generate_password();
client->password = g_compute_checksum_for_string(
G_CHECKSUM_SHA256, password, strlen(password));
// body = mx_recovery_body("ARTEM", "asdf");
// status = mx_send_mail("[email protected]", body);
body = mx_create_sms_body(phone, password);
status = mx_send_sms(body);
send_response(status, client);
g_free(body);
g_free(password);
return;
}
g_warning("Not valid request\n");
}
| 2.09375 | 2 |
2024-11-18T19:02:58.363566+00:00 | 2017-08-21T09:04:18 | b72137ff8205d1126834d977ee2ee6b59e8f47de | {
"blob_id": "b72137ff8205d1126834d977ee2ee6b59e8f47de",
"branch_name": "refs/heads/master",
"committer_date": "2017-08-21T09:04:18",
"content_id": "82631f9c017b0f4a1e47b5f07b7618aa5449bd27",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "7bdd6a568a04320d258bd47d2cc312019964ea2a",
"extension": "c",
"filename": "xfstate.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 85082709,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 999,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/module/xfstate/xfstate.c",
"provenance": "stackv2-0058.json.gz:173086",
"repo_name": "xizonghu/xf",
"revision_date": "2017-08-21T09:04:18",
"revision_id": "f025708c3fc2a12b9c9e6b0a9c88b1690be0f165",
"snapshot_id": "db7cad48fedb37aca0b35f66a79221a167b9bf51",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/xizonghu/xf/f025708c3fc2a12b9c9e6b0a9c88b1690be0f165/module/xfstate/xfstate.c",
"visit_date": "2021-01-22T18:27:49.498056"
} | stackv2 | #include "xfconf.h"
#include "xfstate.h"
int XF_SMachCreate(XF_StateMachine *mach, XF_State *states[], uint8_t size) {
mach->states= states;
mach->sizeStates = size;
return 0;
}
int XF_SMachAddState(XF_StateMachine *mach, XF_State *state) {
uint8_t i = 0;
for(i = 0; i < mach->sizeStates; i++) {
if(0 != mach->states[i]) continue;
mach->states[i] = state;
return 0;
}
return -1;
}
int XF_SMachInitState(XF_StateMachine *mach, XF_State *state) {
mach->currState = state;
if(mach->currState->entry) mach->currState->entry();
return 0;
}
int XF_SMachTransitiveTo(XF_StateMachine *mach, XF_State *state) {
if(mach->currState->exit) mach->currState->exit();
mach->currState = state;
if(mach->currState->entry) mach->currState->entry();
return 0;
}
int XF_SMachSendMessage(XF_StateMachine *mach, XF_Message *msg) {
if(mach->currState->processMessage)
return mach->currState->processMessage(msg);
return 0;
} | 2.5 | 2 |
2024-11-18T19:02:58.839328+00:00 | 2019-11-29T16:27:26 | 7453c8cd1dde78fd5f4905bb599fb53738eb342e | {
"blob_id": "7453c8cd1dde78fd5f4905bb599fb53738eb342e",
"branch_name": "refs/heads/master",
"committer_date": "2019-11-29T16:27:26",
"content_id": "7f2b6f8d1c1015024d8b013d1375483a8aedc0de",
"detected_licenses": [
"MIT"
],
"directory_id": "5666d433591872572c549a3968022c91d1c888df",
"extension": "h",
"filename": "huff.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 224308715,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1802,
"license": "MIT",
"license_type": "permissive",
"path": "/huff.h",
"provenance": "stackv2-0058.json.gz:173214",
"repo_name": "Keaneyjo/C-Huffman-Tree-Encoder",
"revision_date": "2019-11-29T16:27:26",
"revision_id": "4b82dd3e3c500fa7c514a1aa2e69fde92cb56143",
"snapshot_id": "f0a8c249cad44546776a40c3921878f0049771a6",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Keaneyjo/C-Huffman-Tree-Encoder/4b82dd3e3c500fa7c514a1aa2e69fde92cb56143/huff.h",
"visit_date": "2020-09-19T22:04:14.329650"
} | stackv2 | // header file for Huffman coder
#ifndef HUFF_H
#define HUFF_H
#define NUM_CHARS 256
// node in a Huffman tree is either a compound char (internal node)
// or a simple char (leaf)
struct huffchar {
int freq;
int is_compound;
int seqno;
union {
struct {
struct huffchar * left;
struct huffchar * right;
} compound;
unsigned char c;
} u;
};
struct huffcoder {
int freqs[NUM_CHARS];
int code_lengths[NUM_CHARS];
unsigned long long codes[NUM_CHARS];
struct huffchar * tree;
};
// create a new huffcoder structure
struct huffcoder * huffcoder_new();
// count the frequency of characters in a file; set chars with zero
// frequency to one
void huffcoder_count(struct huffcoder * this, char * filename);
// using the character frequencies build the tree of compound
// and simple characters that are used to compute the Huffman codes
void huffcoder_build_tree(struct huffcoder * this);
// using the Huffman tree, build a table of the Huffman codes
// with the huffcoder object
void huffcoder_tree2table(struct huffcoder * this);
void recursive_tree_2table(struct huffcoder * this, struct huffchar * node, unsigned long long curr_code, int len);
unsigned long long reverse(unsigned long long curr_code, int code_length);
// print the Huffman codes for each character in order
void huffcoder_print_codes(struct huffcoder * this);
// encode the input file and write the encoding to the output file
void huffcoder_encode(struct huffcoder * this, char * input_filename,
char * output_filename);
struct huffchar * find_node(struct huffchar * this, int bit);
// decode the input file and write the decoding to the output file
void huffcoder_decode(struct huffcoder * this, char * input_filename,
char * output_filename);
#endif // HUFF_H
| 2.3125 | 2 |
2024-11-18T19:02:58.924445+00:00 | 2022-05-17T13:30:59 | 4e29a5764802053e0819ea3f7ae0806385375ae6 | {
"blob_id": "4e29a5764802053e0819ea3f7ae0806385375ae6",
"branch_name": "refs/heads/master",
"committer_date": "2022-05-17T13:31:08",
"content_id": "6af3c252fcb2272eb90cceffafcd00b32112f219",
"detected_licenses": [
"CC0-1.0"
],
"directory_id": "667d3b23c42d542c468993c789dde4e4745c5695",
"extension": "c",
"filename": "string.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 134198179,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 9587,
"license": "CC0-1.0",
"license_type": "permissive",
"path": "/tiny-script-interpreter/src/string.c",
"provenance": "stackv2-0058.json.gz:173343",
"repo_name": "nuta/archives",
"revision_date": "2022-05-17T13:30:59",
"revision_id": "3db15f62dc1b4497a8c9a39e32f997470653157f",
"snapshot_id": "ba72a63704af07415eb830631ca19c8e9006cc8e",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/nuta/archives/3db15f62dc1b4497a8c9a39e32f997470653157f/tiny-script-interpreter/src/string.c",
"visit_date": "2022-06-14T10:07:48.055078"
} | stackv2 | /// @file
/// @brief A string (in UTF-8) object.
#include "string.h"
#include "malloc.h"
#include "eval.h"
#include "gc.h"
#include "utils.h"
/// Searches haystack for needle.
/// @arg start The needle is searched from haystack{start].
/// @arg haystack The UTF-8 string.
/// @arg haystack_size The size in bytes of haystack.
/// @arg needle The UTF-8 string.
/// @arg needle_size The size in bytes of needle.
/// @returns The beginning of the first occurence in haystack if it is found
/// or NULL otherwise.
static char *search(const char *haystack, size_t start, size_t haystack_size, const char *needle, size_t needle_size) {
if (needle_size == 0) {
return NULL;
}
size_t pos = start;
for (;;) {
void *begin;
if ((begin = ena_memchr(&haystack[pos], needle[0], haystack_size - pos)) == NULL) {
break;
}
// Found the first character.
size_t offset = (uintptr_t) begin - (uintptr_t) haystack;
size_t remaining = haystack_size - offset;
if (remaining < needle_size) {
return NULL;
}
if (ena_memcmp(begin, needle, needle_size) == 0) {
return begin;
}
pos += offset;
}
return NULL;
}
/// Handles escape sequences and copy the string.
/// @arg str The string terminated by NUL.
/// @arg size The size of the string in bytes.
/// @returns The NUL-terminated newly allocated string.
static const char *handle_escape_sequence(const char *str, size_t size) {
char *str2 = ena_malloc(size + 1);
size_t str2_i = 0;
size_t str_i = 0;
while (str_i < size) {
if (str[str_i] == '\\') {
ENA_ASSERT(str_i + 1 <= size);
switch (str[str_i + 1]) {
case 't':
str2[str2_i] = '\t';
str_i += 2; // skip backslash and `t'
str2_i++;
goto next_char;
case 'n':
str2[str2_i] = '\n';
str_i += 2; // skip backslash and `n'
str2_i++;
goto next_char;
case '"':
str2[str2_i] = '"';
str_i += 2; // skip backslash and `"'
str2_i++;
goto next_char;
}
} else {
str2[str2_i] = str[str_i];
str2_i++;
str_i++;
}
next_char:;
}
str2[str2_i] = '\0';
return str2;
}
/// Validate if str is a valid UTF-8 sequence.
/// @arg str The byte sequence. It may contain NUL character.
/// @arg size The size of str in bytes.
/// @returns `true` if str is a valid UTF-8 sequence.
bool ena_utf8_validate(const char *str, size_t size) {
size_t i = 0;
for (;;) {
if (i >= size) {
break;
}
if (ena_isascii(str[i])) {
i++;
} else {
// TODO: Conform https://tools.ietf.org/html/rfc3629
i++;
}
}
return true;
}
/// Returns the length of UTF-8 string.
/// @arg str The byte sequence. It may contain NUL character.
/// @arg size The size of str in bytes.
/// @warning `str` must be a valid UTF-8 sequence.
/// @returns The length.
size_t ena_utf8_strlen(const char *str, size_t size) {
size_t i = 0;
size_t len = 0;
for (;;) {
if (i >= size) {
break;
}
int char_len;
if ((str[i] & 0xf8) == 0xf0) {
char_len = 4;
} else if ((str[i] & 0xf0) == 0xe0) {
char_len = 3;
} else if ((str[i] & 0xe0) == 0xc0) {
char_len = 2;
} else {
char_len = 1;
}
i += char_len;
len++;
}
return len;
}
/// Returns the character at the specified index.
/// @arg str The byte sequence.
/// @arg size The size of str in bytes.
/// @arg index The index.
/// @note O(n)
/// @warning `str` must be a valid UTF-8 sequence.
/// @returns The character at `index`.
uint32_t ena_utf8_char_at(const char *str, size_t size, size_t index) {
size_t i = 0;
for (;;) {
if (i >= size) {
break;
}
int char_len;
if ((str[i] & 0xf8) == 0xf0) {
char_len = 4;
if (index == 0) {
ENA_ASSERT(i + 3 < size);
return ((str[i + 0] & 0x07) << 18)
| ((str[i + 1] & 0x3f) << 12)
| ((str[i + 2] & 0x3f) << 6)
| (str[i + 3] & 0x3f);
}
} else if ((str[i] & 0xf0) == 0xe0) {
char_len = 3;
if (index == 0) {
ENA_ASSERT(i + 2 < size);
return ((str[i + 0] & 0x0f) << 12)
| ((str[i + 1] & 0x3f) << 6)
| (str[i + 2] & 0x3f);
}
} else if ((str[i] & 0xe0) == 0xc0) {
char_len = 2;
if (index == 0) {
ENA_ASSERT(i + 1 < size);
return ((str[i + 0] & 0x1f) << 6)
| (str[i + 1] & 0x3f);
}
} else {
char_len = 1;
if (index == 0) {
return str[i];
}
}
i += char_len;
index--;
}
return FFFD_CHAR;
}
// @note Assumes that `str` does not contain NUL (verified by utf8_validate()).
ena_value_t ena_create_string(struct ena_vm *vm, const char *str, size_t size) {
struct ena_string *obj = (struct ena_string *) ena_alloc_object(vm, ENA_T_STRING);
obj->flags = STRING_FLAG_IDENT;
if (!ena_utf8_validate(str, size)) {
RUNTIME_ERROR("Invalid utf-8 byte sequence.");
}
const char *buf = handle_escape_sequence(str, size);
obj->ident = ena_cstr2ident(vm, buf);
obj->str = ena_ident2cstr(vm, obj->ident);
obj->size_in_bytes = size;
ena_free((void *) buf);
return ENA_OBJ2VALUE(obj);
}
static ena_value_t concat(struct ena_vm *vm,
const char *str1, size_t str1_size,
const char *str2, size_t str2_size) {
size_t new_str_size = str1_size + str2_size;
char *new_str = ena_malloc(new_str_size + 1);
ena_memcpy(new_str, str1, str1_size);
ena_memcpy(&new_str[str1_size], str2, str2_size);
new_str[new_str_size] = '\0';
return ena_create_string(vm, new_str, new_str_size);
}
static ena_value_t string_concat(struct ena_vm *vm, ena_value_t self, ena_value_t *args, int num_args) {
ena_check_args(vm, "concat()", "s", args, num_args);
struct ena_string *self_str = (struct ena_string *) self;
struct ena_string *str = (struct ena_string *) args[0];
return concat(vm, self_str->str, self_str->size_in_bytes, str->str, str->size_in_bytes);
}
static ena_value_t string_contains(struct ena_vm *vm, ena_value_t self, ena_value_t *args, int num_args) {
ena_check_args(vm, "contains()", "s", args, num_args);
struct ena_string *self_str = (struct ena_string *) self;
struct ena_string *needle = (struct ena_string *) args[0];
char *pos = search(self_str->str, 0, self_str->size_in_bytes, needle->str, needle->size_in_bytes);
return (pos == NULL) ? ENA_FALSE : ENA_TRUE;
}
static ena_value_t string_find(struct ena_vm *vm, ena_value_t self, ena_value_t *args, int num_args) {
ena_check_args(vm, "find()", "s", args, num_args);
struct ena_string *self_str = (struct ena_string *) self;
struct ena_string *needle = (struct ena_string *) args[0];
char *pos = search(self_str->str, 0, self_str->size_in_bytes, needle->str, needle->size_in_bytes);
return ena_create_int(vm, (pos == NULL) ? -1 : (int) ((uintptr_t) pos - (uintptr_t) self_str->str));
}
static ena_value_t string_replace(struct ena_vm *vm, ena_value_t self, ena_value_t *args, int num_args) {
ena_check_args(vm, "replace()", "ss", args, num_args);
struct ena_string *self_str = (struct ena_string *) self;
struct ena_string *old_str = (struct ena_string *) args[0];
struct ena_string *new_str = (struct ena_string *) args[1];
struct ena_string *new_self = (struct ena_string *) ena_create_string(vm, "", 0);
size_t index = 0;
for (;;) {
if (index >= self_str->size_in_bytes) {
break;
}
char *pos = search(self_str->str, index, self_str->size_in_bytes,
old_str->str, old_str->size_in_bytes);
if (pos == NULL) {
break;
}
size_t match = (uintptr_t) pos - (uintptr_t) self_str->str;
// Copy substring before the matched position and append new_str.
new_self = (struct ena_string *) concat(vm, new_self->str, new_self->size_in_bytes, &self_str->str[index], match - index);
new_self = (struct ena_string *) concat(vm, new_self->str, new_self->size_in_bytes, new_str->str, new_str->size_in_bytes);
index = match + old_str->size_in_bytes;
}
// Copy trailing substring.
new_self = (struct ena_string *) concat(vm, new_self->str, new_self->size_in_bytes, &self_str->str[index], self_str->size_in_bytes - index);
return ENA_OBJ2VALUE(new_self);
}
struct ena_class *ena_create_string_class(struct ena_vm *vm) {
ena_value_t cls = ena_create_class(vm);
ena_define_method(vm, cls, "+", string_concat);
ena_define_method(vm, cls, "concat", string_concat);
ena_define_method(vm, cls, "contains", string_contains);
ena_define_method(vm, cls, "replace", string_replace);
ena_define_method(vm, cls, "find", string_find);
return ena_to_class_object(vm, cls);
}
| 3.109375 | 3 |
2024-11-18T19:02:59.025035+00:00 | 2019-09-03T09:00:26 | e39b5df967bb8c7d1587e95fbc635317d05dd9e9 | {
"blob_id": "e39b5df967bb8c7d1587e95fbc635317d05dd9e9",
"branch_name": "refs/heads/master",
"committer_date": "2019-09-03T09:00:26",
"content_id": "e0b23d1d7ae5553529295b3b88d6be52a4be4db9",
"detected_licenses": [
"MIT"
],
"directory_id": "5b44719471e4cfc29c875bfd0a33e3055cffa5d6",
"extension": "c",
"filename": "conv.c",
"fork_events_count": 2,
"gha_created_at": "2015-07-16T03:37:39",
"gha_event_created_at": "2016-04-08T00:37:59",
"gha_language": "D",
"gha_license_id": null,
"github_id": 39174792,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1326,
"license": "MIT",
"license_type": "permissive",
"path": "/stdlib/c/conv.c",
"provenance": "stackv2-0058.json.gz:173471",
"repo_name": "Mellow-Programming-Language/Mellow",
"revision_date": "2019-09-03T09:00:26",
"revision_id": "cca6cc6c3cb32716e29d8d8f48d1ce449e32adcd",
"snapshot_id": "0cc39b5c1a8b4e6119f8ace86527ceb476c7ea2a",
"src_encoding": "UTF-8",
"star_events_count": 4,
"url": "https://raw.githubusercontent.com/Mellow-Programming-Language/Mellow/cca6cc6c3cb32716e29d8d8f48d1ce449e32adcd/stdlib/c/conv.c",
"visit_date": "2020-12-28T20:54:48.404065"
} | stackv2 |
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include "conv.h"
#include "../mellow_internal.h"
void* cStringToString(struct CString* cstring)
{
const char* str = cstring->str;
uint32_t strLength = strlen(str);
// The length of the array of characters plus the bytes allocated to hold
// the ref-count plus the bytes allocated to hold the string length plus
// a byte to hold the null byte
const uint32_t totalSize = HEAD_SIZE + strLength + 1;
void* mellowString = malloc(totalSize);
// Clear the marking function
// TODO: Set this to the string marking algorithm
((uint64_t*)mellowString)[0] = 1;
// set the str-len to the length of the array of characters
((uint64_t*)mellowString)[1] = strLength;
// Copy the array of chars over
memcpy(mellowString + HEAD_SIZE, str, strLength);
// Add the null byte
((char*)mellowString)[totalSize-1] = '\0';
return mellowString;
}
struct CString* stringToCString(void* mellowString)
{
uint64_t strLength = ((uint64_t*)mellowString)[1] + 1;
char* str = (char*)malloc(sizeof(char) * strLength);
memcpy(str, mellowString + HEAD_SIZE, strLength);
struct CString* cstring = (struct CString*)malloc(sizeof(struct CString));
cstring->str = str;
return cstring;
}
| 2.734375 | 3 |
2024-11-18T19:02:59.664489+00:00 | 2021-03-21T17:28:02 | db975ca00e63164e8b4058d08b0d59a07d0451c6 | {
"blob_id": "db975ca00e63164e8b4058d08b0d59a07d0451c6",
"branch_name": "refs/heads/master",
"committer_date": "2021-03-21T17:28:02",
"content_id": "72ce025469fcbbb24bed624de6125c9f56a2e6b6",
"detected_licenses": [
"MIT"
],
"directory_id": "d2f239171309d303a098371432b2cd508650efce",
"extension": "h",
"filename": "struct.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": 456,
"license": "MIT",
"license_type": "permissive",
"path": "/src/struct.h",
"provenance": "stackv2-0058.json.gz:173727",
"repo_name": "laik/lex-yacc-SQL-parser",
"revision_date": "2021-03-21T17:28:02",
"revision_id": "ecbee32755ec2a69c16b4c58352a12d2ba5c8cfa",
"snapshot_id": "f935e2cc5584616cd53ef057a67ac6c23de7aaa9",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/laik/lex-yacc-SQL-parser/ecbee32755ec2a69c16b4c58352a12d2ba5c8cfa/src/struct.h",
"visit_date": "2023-04-02T02:53:56.317867"
} | stackv2 | /*
* Symbol Table element
* The Symbol Table is a list of entries
* that represent variables or functions
*/
typedef struct SymbTbl {
char *column; /* symbol name */
char *table;
int type; /* symbol type VAR|FNCT */
struct SymbTbl *next; /* list forward pointer */
} symbtbl;
/* global variables */
extern symbtbl *st; /* head of symbol table list */
/* function prototypes */
symbtbl *putsymb(char *,char *,int);
symbtbl *getsymb(char *);
| 2.515625 | 3 |
2024-11-18T19:03:01.717612+00:00 | 2016-04-07T17:28:06 | 47a044e4db83fab81e6e20bc7b8e8de1c7159b00 | {
"blob_id": "47a044e4db83fab81e6e20bc7b8e8de1c7159b00",
"branch_name": "refs/heads/master",
"committer_date": "2016-04-07T17:28:06",
"content_id": "6d41e6551857ca5a6455969d98d2c564353c7aaf",
"detected_licenses": [
"MIT"
],
"directory_id": "87ac39d87ab1cb552dfcb6ebf6a8e3ef5a70906b",
"extension": "c",
"filename": "fflush.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 49424847,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 403,
"license": "MIT",
"license_type": "permissive",
"path": "/fflush.c",
"provenance": "stackv2-0058.json.gz:173984",
"repo_name": "farwish/linux-io-program",
"revision_date": "2016-04-07T17:28:06",
"revision_id": "eeac274e4f21946b617188a21108d52267f519a1",
"snapshot_id": "392bf2769cd08f828ece5134bf51ddcf9152f21d",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/farwish/linux-io-program/eeac274e4f21946b617188a21108d52267f519a1/fflush.c",
"visit_date": "2021-01-10T12:09:30.498734"
} | stackv2 | #include <stdio.h>
/*
* fflush
*/
int main(int argc, char* argv[])
{
FILE* fp;
char buf[] = "hello\n";
fp = fopen(argv[1], "w+");
if (fp == NULL) {
printf("open file %s failure\n", argv[1]);
return -1;
}
printf("open file a.c success\n");
fputs(buf, fp);
fflush(fp);
while(1); // 如果buf没有换行符, 运行到这里, argv[1]文件依然没有内容
fclose(fp);
return 0;
}
| 2.84375 | 3 |
2024-11-18T19:53:03.015953+00:00 | 2020-08-17T15:29:55 | 2c438e5f1783cd024c0efffc4b1bb479017b6138 | {
"blob_id": "2c438e5f1783cd024c0efffc4b1bb479017b6138",
"branch_name": "refs/heads/master",
"committer_date": "2020-08-17T15:29:55",
"content_id": "6bc733b6307042bf2a1406c64343da7de67104aa",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "622563fcf876552261f554b44530c507758fb88b",
"extension": "c",
"filename": "RaspiCamTest.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 288203110,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5087,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/RaspiCamTest.c",
"provenance": "stackv2-0061.json.gz:59",
"repo_name": "bellx2/raspicam_cv",
"revision_date": "2020-08-17T15:29:55",
"revision_id": "8672e942d9d3b7a0e054ea429eb2b470fc974c14",
"snapshot_id": "70508733509d22f35195a70d670cc6ec056edb1e",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/bellx2/raspicam_cv/8672e942d9d3b7a0e054ea429eb2b470fc974c14/RaspiCamTest.c",
"visit_date": "2022-12-08T19:43:11.005837"
} | stackv2 | /*
Copyright (c) by Emil Valkov,
All rights reserved.
License: http://www.opensource.org/licenses/bsd-license.php
*/
#include <cv.h>
#include <highgui.h>
#include <stdio.h>
#include <unistd.h>
#include "RaspiCamCV.h"
int main(int argc, char *argv[ ]){
RASPIVID_CONFIG * config = (RASPIVID_CONFIG*)malloc(sizeof(RASPIVID_CONFIG));
config->width=320;
config->height=240;
config->bitrate=0; // zero: leave as default
config->framerate=0;
config->monochrome=0;
int opt;
while ((opt = getopt(argc, argv, "lxmh:v:r:e:")) != -1)
{
switch (opt)
{
case 'l': // large
config->width = 640;
config->height = 480;
break;
case 'x': // extra large
config->width = 960;
config->height = 720;
break;
case 'm': // monochrome
config->monochrome = 1;
break;
case 'h':
config->hflip = atoi(optarg);
break;
case 'v':
config->vflip = atoi(optarg);
break;
case 'r':
config->rotation = atoi(optarg);
break;
case 'e':
config->exposure = atoi(optarg);
break;
default:
fprintf(stderr, "Usage: %s [opt] \n", argv[0], opt);
fprintf(stderr, "-l: Large mode\n");
fprintf(stderr, "-x: Extra large mode\n");
fprintf(stderr, "-m: Monochrome mode\n");
fprintf(stderr, "-h: hFlip\n");
fprintf(stderr, "-v: vFlip\n");
fprintf(stderr, "-r: Rotate\n");
fprintf(stderr, "-e [-24~24]: Set Exposure\n");
exit(EXIT_FAILURE);
}
}
/*
Could also use hard coded defaults method: raspiCamCvCreateCameraCapture(0)
*/
RaspiCamCvCapture * capture = (RaspiCamCvCapture *) raspiCamCvCreateCameraCapture2(0, config);
free(config);
CvFont font;
double hScale=0.4;
double vScale=0.4;
int lineWidth=1;
cvInitFont(&font, CV_FONT_HERSHEY_SIMPLEX|CV_FONT_ITALIC, hScale, vScale, 0, lineWidth, 8);
cvNamedWindow("RaspiCamTest", 1);
int exit =0;
do {
IplImage* image = raspiCamCvQueryFrame(capture);
char text[200];
sprintf(
text
, "w=%.0f h=%.0f fps=%.0f bitrate=%.0f monochrome=%.0f"
, raspiCamCvGetCaptureProperty(capture, RPI_CAP_PROP_FRAME_WIDTH)
, raspiCamCvGetCaptureProperty(capture, RPI_CAP_PROP_FRAME_HEIGHT)
, raspiCamCvGetCaptureProperty(capture, RPI_CAP_PROP_FPS)
, raspiCamCvGetCaptureProperty(capture, RPI_CAP_PROP_BITRATE)
, raspiCamCvGetCaptureProperty(capture, RPI_CAP_PROP_MONOCHROME)
);
cvPutText (image, text, cvPoint(05, 40), &font, cvScalar(255, 255, 0, 0));
sprintf(text, "Press ESC to exit");
cvPutText (image, text, cvPoint(05, 80), &font, cvScalar(255, 255, 0, 0));
cvShowImage("RaspiCamTest", image);
char key = cvWaitKey(10);
switch(key)
{
case 27: // Esc to exit
exit = 1;
break;
case 60: // < (less than)
raspiCamCvSetCaptureProperty(capture, RPI_CAP_PROP_FPS, 25); // Currently NOOP
break;
case 62: // > (greater than)
raspiCamCvSetCaptureProperty(capture, RPI_CAP_PROP_FPS, 30); // Currently NOOP
break;
}
} while (!exit);
cvDestroyWindow("RaspiCamTest");
raspiCamCvReleaseCapture(&capture);
return 0;
}
#include "interface/mmal/mmal.h"
#include "interface/mmal/mmal_logging.h"
/**
* Convert a MMAL status return value to a simple boolean of success
* ALso displays a fault if code is not success
*
* @param status The error code to convert
* @return 0 if status is success, 1 otherwise
*/
int mmal_status_to_int(MMAL_STATUS_T status)
{
if (status == MMAL_SUCCESS)
return 0;
else
{
switch (status)
{
case MMAL_ENOMEM :
vcos_log_error("Out of memory");
break;
case MMAL_ENOSPC :
vcos_log_error("Out of resources (other than memory)");
break;
case MMAL_EINVAL:
vcos_log_error("Argument is invalid");
break;
case MMAL_ENOSYS :
vcos_log_error("Function not implemented");
break;
case MMAL_ENOENT :
vcos_log_error("No such file or directory");
break;
case MMAL_ENXIO :
vcos_log_error("No such device or address");
break;
case MMAL_EIO :
vcos_log_error("I/O error");
break;
case MMAL_ESPIPE :
vcos_log_error("Illegal seek");
break;
case MMAL_ECORRUPT :
vcos_log_error("Data is corrupt \attention FIXME: not POSIX");
break;
case MMAL_ENOTREADY :
vcos_log_error("Component is not ready \attention FIXME: not POSIX");
break;
case MMAL_ECONFIG :
vcos_log_error("Component is not configured \attention FIXME: not POSIX");
break;
case MMAL_EISCONN :
vcos_log_error("Port is already connected ");
break;
case MMAL_ENOTCONN :
vcos_log_error("Port is disconnected");
break;
case MMAL_EAGAIN :
vcos_log_error("Resource temporarily unavailable. Try again later");
break;
case MMAL_EFAULT :
vcos_log_error("Bad address");
break;
default :
vcos_log_error("Unknown status error");
break;
}
return 1;
}
}
| 2.515625 | 3 |
2024-11-18T19:53:03.084339+00:00 | 2021-10-24T07:26:07 | a8232adccae0c316aab20d3a2c3dbbb61e4263b7 | {
"blob_id": "a8232adccae0c316aab20d3a2c3dbbb61e4263b7",
"branch_name": "refs/heads/master",
"committer_date": "2021-10-24T07:26:07",
"content_id": "c2d22083eb991e0d07afe6bc8301ec7828996476",
"detected_licenses": [
"Zlib"
],
"directory_id": "b9ffc4003f9993e349463e9de0292566a3e3f042",
"extension": "h",
"filename": "libhzr.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": 3230,
"license": "Zlib",
"license_type": "permissive",
"path": "/src/include/libhzr.h",
"provenance": "stackv2-0061.json.gz:187",
"repo_name": "holdRoot/hzr",
"revision_date": "2021-10-24T07:26:07",
"revision_id": "5ef2e3d25bf910b8dcdc984fd2a38f47ddc5766e",
"snapshot_id": "b8d51d8b07dc2c280d656aedc35257c930d196c3",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/holdRoot/hzr/5ef2e3d25bf910b8dcdc984fd2a38f47ddc5766e/src/include/libhzr.h",
"visit_date": "2023-09-04T22:34:07.778283"
} | stackv2 | /*
* hzr - A Huffman + RLE compression library.
*
* Copyright (C) 2016 Marcus Geelnard
*
* This software is provided 'as-is', without any express or implied warranty.
* In no event will the authors be held liable for any damages arising from the
* use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software in
* a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*
*/
#ifndef LIBHZR_H_
#define LIBHZR_H_
#include <stddef.h> /* For size_t */
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief Return value for many libhzr functions.
*/
typedef enum {
HZR_FAIL = 0, /**< Failure (zero). */
HZR_OK = 1 /**< Success (non-zero). */
} hzr_status_t;
/**
* @brief Determine the maximum (worst case) size of an HZR encoded buffer.
* @param uncompressed_size Size of the uncompressed buffer in bytes.
* @returns The maximum size (in bytes) of the compressed buffer.
*/
size_t hzr_max_compressed_size(size_t uncompressed_size);
/**
* @brief Compress a buffer using the HZR compression scheme.
* @param in Input (uncompressed) buffer.
* @param in_size Size of the input buffer in bytes.
* @param[out] out Output (compressed) buffer.
* @param out_size Size of the output buffer in bytes.
* @param[out] encoded_size Size of the encoded data in bytes.
* @returns HZR_OK on success, else HZR_FAIL.
*/
hzr_status_t hzr_encode(const void* in,
size_t in_size,
void* out,
size_t out_size,
size_t* encoded_size);
/**
* @brief Verify that a buffer is a valid HZR encoded buffer.
* @param in Input (compressed) buffer.
* @param in_size Size of the input buffer in bytes.
* @param[out] decoded_size Size of the decoded data in bytes.
* @returns HZR_OK on success, else HZR_FAIL.
*
* If the provided buffer is a valid HZR encoded buffer, the size of the decoded
* buffer is returned in decoded_size.
*/
hzr_status_t hzr_verify(const void* in, size_t in_size, size_t* decoded_size);
/**
* @brief Decode an HZR encoded buffer.
* @param in Input (compressed) buffer.
* @param in_size Size of the input buffer in bytes.
* @param[out] out Output (uncompressed) buffer.
* @param out_size Size of the output buffer in bytes.
* @returns HZR_OK on success, else HZR_FAIL.
* @note It is expected that the input buffer is a valid HZR encoded buffer,
* which should be verified by calling hzr_verify() first.
*/
hzr_status_t hzr_decode(const void* in,
size_t in_size,
void* out,
size_t out_size);
#ifdef __cplusplus
}
#endif
#endif /* LIBHZR_H_ */
| 2.21875 | 2 |
2024-11-18T19:53:03.138080+00:00 | 2023-07-17T14:30:17 | a2e1d1687c7260bb66f33971d68917b9cc0ead76 | {
"blob_id": "a2e1d1687c7260bb66f33971d68917b9cc0ead76",
"branch_name": "refs/heads/master",
"committer_date": "2023-07-29T18:24:54",
"content_id": "9883f08ce8d86b9b454e4af3f5dafee611f539a8",
"detected_licenses": [
"MIT"
],
"directory_id": "87c8713ddf2a2dfc59725d8b05956156858c50f9",
"extension": "h",
"filename": "arg-val-itr.h",
"fork_events_count": 25,
"gha_created_at": "2012-09-11T17:13:27",
"gha_event_created_at": "2023-07-29T18:24:56",
"gha_language": "C++",
"gha_license_id": "MIT",
"github_id": 5767757,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1130,
"license": "MIT",
"license_type": "permissive",
"path": "/include/rtosc/arg-val-itr.h",
"provenance": "stackv2-0061.json.gz:315",
"repo_name": "fundamental/rtosc",
"revision_date": "2023-07-17T14:30:17",
"revision_id": "e74fc01ecb331a979296aefafea18d860c76b050",
"snapshot_id": "a2d4e5fb3bfb279194861fa764c12de27f26eacc",
"src_encoding": "UTF-8",
"star_events_count": 85,
"url": "https://raw.githubusercontent.com/fundamental/rtosc/e74fc01ecb331a979296aefafea18d860c76b050/include/rtosc/arg-val-itr.h",
"visit_date": "2023-08-06T21:40:58.310899"
} | stackv2 | #ifndef ARGVALITR_H
#define ARGVALITR_H
#include <rtosc/rtosc.h>
/*
* arg val iterators
*/
#ifdef __cplusplus
extern "C" {
#endif
/**
* Iterator over arg values
*
* Always use this iterator for iterating because it automatically skips
* to the next offset, even in case of arrays etc.
* Also, it walks through ranges, as if they were not existing.
*/
typedef struct
{
const rtosc_arg_val_t* av; //!< the arg val referenced
size_t i; //!< position of this arg val
int range_i; //!< position of this arg val in its range
} rtosc_arg_val_itr;
void rtosc_arg_val_itr_init(rtosc_arg_val_itr* itr,
const rtosc_arg_val_t* av);
//! this usually just returns the value from operand, except for range operands,
//! where the value is being interpolated
//! @param buffer Temporary. Don't access it afterwards.
const rtosc_arg_val_t* rtosc_arg_val_itr_get(
const rtosc_arg_val_itr* itr,
rtosc_arg_val_t* buffer);
//! @warning will loop forever on infinite ranges!
void rtosc_arg_val_itr_next(rtosc_arg_val_itr* itr);
#ifdef __cplusplus
};
#endif
#endif // ARGVALITR_H
| 2.375 | 2 |
2024-11-18T19:53:03.425581+00:00 | 2017-05-15T10:13:09 | 8e03aab119df58497eadad92a7cb8a5ebbfa56df | {
"blob_id": "8e03aab119df58497eadad92a7cb8a5ebbfa56df",
"branch_name": "refs/heads/master",
"committer_date": "2017-05-15T10:13:09",
"content_id": "56972dccb7f6f5cb2c6956e60e2a445c744c1be5",
"detected_licenses": [
"MIT"
],
"directory_id": "d348be0b3b41bb9d642252efca36b442571491ad",
"extension": "c",
"filename": "main.c",
"fork_events_count": 2,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 87836758,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 18732,
"license": "MIT",
"license_type": "permissive",
"path": "/main.c",
"provenance": "stackv2-0061.json.gz:571",
"repo_name": "limmh/mqtt_client",
"revision_date": "2017-05-15T10:13:09",
"revision_id": "adea20a5dbca4a710bba50780fab5443ab6a6df2",
"snapshot_id": "8658ad12f6a4db76d142b440083f6f8dd47b988d",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/limmh/mqtt_client/adea20a5dbca4a710bba50780fab5443ab6a6df2/main.c",
"visit_date": "2021-01-19T10:12:06.209309"
} | stackv2 | /*
MIT License
Copyright (c) 2017 MH Lim
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 <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "client.h"
#include "queue.h"
#include "utils.h"
#include <mosquitto.h>
#include <pthread.h>
#if defined _WIN32 || defined _WIN64
#include <Windows.h>
#define strcasecmp stricmp
#define sleep(n) Sleep(n * 1000)
#else
#include <unistd.h>
#include <strings.h>
#endif
typedef struct client_s
{
struct mosquitto *mqtt;
mqtt_client_info_s info;
queue_s *received;
pthread_mutex_t mutex;
bool run;
bool conn_lost;
} client_s;
static void generate_client_id(char *buffer, size_t buffer_size)
{
static const char pattern[] = "0123456789ABCDEFGHIJKLMNOPQSTUVWXYZabcdefghijklmnopqrstuvwxyz";
static const size_t pattern_size = (sizeof pattern)/(sizeof pattern[0]) - 1;
utils_generate_random_sequence(pattern, pattern_size, buffer, buffer_size);
}
static void init_username_password(mqtt_client_info_s *info)
{
if (info->username && !info->password) {
char *pwd = NULL;
printf("Enter a password: ");
utils_gets_quiet(&pwd);
info->password = mqtt_client_strdup(pwd);
utils_delete(pwd);
}
}
static const char *get_error_message(int error)
{
#if defined _WIN32 || defined _WIN64
static char buffer[512];
const size_t buffer_size = (sizeof buffer) / (sizeof buffer[0]);
DWORD flags = FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS;
DWORD lang = MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL);
FormatMessageA(flags, NULL, error, lang, buffer, buffer_size, NULL);
buffer[buffer_size - 1] = '\0';
return buffer;
#else
return strerror(error);
#endif
}
static void on_connect(struct mosquitto *m, void *obj, int rc)
{
client_s *c = (client_s*) obj;
printf("%s\n", mosquitto_connack_string(rc));
if (0 == rc)
printf("Successfully connected to %s (port %d).\n", c->info.server, c->info.port);
else
printf("Failed to connect to %s (port %d).\n", c->info.server, c->info.port);
}
static void on_disconnect(struct mosquitto *m, void *obj, int rc)
{
client_s *c = (client_s*) obj;
printf("Disconnection code: %d\n", rc);
if (0 == rc) {
c->conn_lost = false;
printf("Successfully disconnected from %s (port %d).\n", c->info.server, c->info.port);
} else {
c->conn_lost = true;
printf("Disconnected from %s (port %d).\n", c->info.server, c->info.port);
}
}
static void on_subscribe(struct mosquitto *m, void *obj, int mid, int qos_count, const int *granted_qos)
{
printf("Packet ID %d: The topic has been subscribed.\n", mid);
}
static void on_publish(struct mosquitto *m, void *obj, int mid)
{
printf("Packet ID %d: The message has been published.\n", mid);
}
static void client_received_data_delete(void *data)
{
struct mosquitto_message *msg = (struct mosquitto_message*) data;
free(msg->payload);
utils_delete(msg->topic);
memset(msg, 0, sizeof *msg);
}
static void on_message(struct mosquitto *m, void *obj, const struct mosquitto_message *msg)
{
client_s *c = (client_s*) obj;
struct mosquitto_message message;
message.payload = malloc(msg->payloadlen);
if (NULL == message.payload) {
printf("Message received: Out of memory error.\n");
return;
}
memcpy(message.payload, msg->payload, (size_t) msg->payloadlen);
message.topic = utils_strdup(msg->topic);
if (NULL == message.topic) {
free(message.payload);
printf("Message received: Out of memory.\n");
return;
}
message.payloadlen = msg->payloadlen;
message.mid = msg->mid;
message.qos = msg->qos;
message.retain = msg->retain;
queue_push_back(c->received, &message, sizeof message, client_received_data_delete);
}
static void on_unsubscribe(struct mosquitto *m, void *obj, int mid)
{
printf("Packet ID %d: The topic has been unsubscribed.\n", mid);
}
static void get_topic(char **input)
{
do {
printf("Topic: ");
utils_get_stdin(input);
} while (NULL == *input || '\0' == (*input)[0]);
}
static void get_message(char **input)
{
do {
printf("Message: ");
utils_get_stdin(input);
} while (NULL == *input);
}
static int get_qos(void)
{
long qos;
do {
char *input = NULL, *endptr = NULL;
qos = -1;
printf("QoS: ");
utils_get_stdin(&input);
if (input && '\0' != input[0]) {
qos = (int) strtol(input, &endptr, 10);
if (!endptr || '\0' != *endptr)
qos = -1;
}
utils_delete(input);
} while (qos < 0 || qos > 2);
return (int) qos;
}
static unsigned long get_count(void)
{
unsigned long count = 0;
do {
char *input = NULL;
printf("Count (default: 1): ");
utils_get_stdin(&input);
if (input)
count = ('\0' == input[0]) ? 1 : strtoul(input, NULL, 10);
utils_delete(input);
} while (count < 1);
return count;
}
static bool get_retain(void)
{
bool retain;
char *input = NULL;
for (;;) {
printf("Retain (Y/N): ");
utils_get_stdin(&input);
if (input) {
if (!strcasecmp(input, "y")) {
retain = true;
break;
} else if (!strcasecmp(input, "n")) {
retain = false;
break;
}
}
}
if (input)
utils_delete(input);
return retain;
}
static void get_binary_data(char **data)
{
for (;;) {
printf("Binary data (hexadecimal sequence without any space): ");
utils_get_stdin(data);
if (data && utils_hex_sequence_is_valid(*data))
break;
else
printf("Invalid hexadecimal sequence. Please try again.\n");
}
}
static void get_file_path(char **path)
{
for (;;) {
printf("File path: ");
utils_get_stdin(path);
if (path) {
FILE *fp = fopen(*path, "rb");
if (!fp) {
printf("%s\n", strerror(errno));
continue;
}
fclose(fp);
return;
}
}
}
static void client_cleanup(client_s *c)
{
mosquitto_destroy(c->mqtt);
mqtt_client_info_delete(&c->info);
pthread_mutex_destroy(&c->mutex);
queue_destroy(c->received);
memset(c, 0, sizeof *c);
}
static int client_init(int argc, char *argv[], client_s *c)
{
memset(c, 0, sizeof *c);
c->received = queue_create();
if (NULL == c->received) {
printf("Out of memory.\n");
return -1;
}
if (0 != pthread_mutex_init(&c->mutex, NULL)) {
queue_destroy(c->received);
printf("Failed to initialize mutex.\n");
return -2;
}
mqtt_client_info_init(&c->info);
if (!mqtt_client_parse_command_line(argc, argv, &c->info)) {
queue_destroy(c->received);
return -3;
}
if (NULL == c->info.client_id || '\0' == c->info.client_id[0]) {
char buffer[24];
if (c->info.client_id)
mqtt_client_free(c->info.client_id);
generate_client_id(buffer, (sizeof buffer) / (sizeof buffer[0]));
c->info.client_id = mqtt_client_strdup(buffer);
}
c->mqtt = mosquitto_new(c->info.client_id, c->info.clean_session, c);
if (NULL == c->mqtt) {
int error = errno;
pthread_mutex_destroy(&c->mutex);
queue_destroy(c->received);
printf("Error %d: %s\n", error, mosquitto_strerror(error));
return -4;
}
int mqtt_version;
switch (c->info.version) {
case mqtt_version_3_1:
mqtt_version = MQTT_PROTOCOL_V31;
break;
case mqtt_version_3_1_1:
default:
mqtt_version = MQTT_PROTOCOL_V311;
break;
}
mosquitto_opts_set(c->mqtt, MOSQ_OPT_PROTOCOL_VERSION, &mqtt_version);
int rc;
init_username_password(&c->info);
if (c->info.username && '\0' != c->info.username[0]) {
rc = mosquitto_username_pw_set(c->mqtt, c->info.username, c->info.password);
if (MOSQ_ERR_SUCCESS != rc)
printf("Error setting username and password. %s\n", mosquitto_strerror(rc));
}
if (c->info.will_topic) {
rc = mosquitto_will_set(c->mqtt, c->info.will_topic, strlen(c->info.will_message), c->info.will_message, c->info.will_qos, c->info.will_retain);
if (MOSQ_ERR_SUCCESS != rc)
printf("Error in will topic configuration. %s\n", mosquitto_strerror(rc));
}
bool valid_tls = (c->info.ca_cert && c->info.cert && c->info.private_key);
bool valid_normal = (NULL == c->info.ca_cert && NULL == c->info.cert && NULL == c->info.private_key);
if (!(valid_tls || valid_normal)) {
if (NULL == c->info.ca_cert)
printf("The CA certificate file is not specified.\n");
if (NULL == c->info.cert)
printf("The client certificate file is not specified.\n");
if (NULL == c->info.private_key)
printf("The client private key file is not specified.\n");
return -5;
}
if (valid_tls) {
rc = mosquitto_tls_set(c->mqtt, c->info.ca_cert, NULL, c->info.cert, c->info.private_key, NULL);
if (MOSQ_ERR_SUCCESS != rc) {
printf("Error in TLS configuration. %s\n", mosquitto_strerror(rc));
return -6;
}
int verify_server = c->info.verify_server ? 1 : 0;
const char *tls_version;
switch (c->info.tls_version) {
case tls_version_1_0:
tls_version = "tlsv1";
break;
case tls_version_1_1:
tls_version = "tlsv1.1";
break;
case tls_version_1_2:
default:
tls_version = "tlsv1.2";
break;
}
rc = mosquitto_tls_opts_set(c->mqtt, verify_server, tls_version, NULL);
if (MOSQ_ERR_SUCCESS != rc) {
printf("Error in setting TLS options. %s\n", mosquitto_strerror(rc));
return -7;
}
}
mosquitto_connect_callback_set(c->mqtt, on_connect);
mosquitto_disconnect_callback_set(c->mqtt, on_disconnect);
mosquitto_subscribe_callback_set(c->mqtt, on_subscribe);
mosquitto_message_callback_set(c->mqtt, on_message);
mosquitto_publish_callback_set(c->mqtt, on_publish);
mosquitto_unsubscribe_callback_set(c->mqtt, on_unsubscribe);
mosquitto_threaded_set(c->mqtt, true);
c->run = false;
c->conn_lost = false;
return 0;
}
static bool client_is_running(client_s *c)
{
pthread_mutex_lock(&c->mutex);
bool run = c->run;
pthread_mutex_unlock(&c->mutex);
return run;
}
static void client_set_running_status(client_s *c, bool status)
{
pthread_mutex_lock(&c->mutex);
c->run = status;
pthread_mutex_unlock(&c->mutex);
}
static int client_connect(client_s *c)
{
if (NULL == c->info.server) {
printf("The server is not specified.\n");
return -1;
}
printf("Connecting to %s (port %d) ...\n", c->info.server, c->info.port);
int rc = mosquitto_connect(c->mqtt, c->info.server, c->info.port, c->info.keep_alive);
if (MOSQ_ERR_SUCCESS == rc) {
printf("Connected to %s (port %d). Waiting for MQTT connection to establish.\n", c->info.server, c->info.port);
} else {
if (MOSQ_ERR_ERRNO == rc) {
rc = errno;
printf("Error %d: %s\n", rc, get_error_message(rc));
} else {
printf("Cannot connect to %s (port %d). Error %d: %s\n", c->info.server, c->info.port, rc, mosquitto_strerror(rc));
}
}
return rc;
}
static void client_disconnect(client_s *c)
{
mosquitto_disconnect(c->mqtt);
}
static void client_publish(client_s *c, const char *topic, const void *message, int message_size, int qos, bool retain)
{
int mid;
int rc = mosquitto_publish(c->mqtt, &mid, topic, message_size, message, qos, retain);
if (MOSQ_ERR_SUCCESS == rc)
printf("Packet ID %d: The message for the topic \"%s\" is being published.\n", mid, topic);
else
printf("Failed to publish the message for \"%s\". Error %d: %s\n", topic, rc, mosquitto_strerror(rc));
}
static void client_subscribe(client_s *c)
{
char *topic = NULL;
get_topic(&topic);
if (topic) {
int qos = get_qos();
int mid;
int rc = mosquitto_subscribe(c->mqtt, &mid, topic, qos);
if (MOSQ_ERR_SUCCESS == rc)
printf("Packet ID %d: The topic \"%s\" is being subscribed.\n", mid, topic);
else
printf("Failed to subscribe to %s. Error %d: %s\n", topic, rc, mosquitto_strerror(rc));
utils_delete(topic);
}
}
static void client_publish_message(client_s *c)
{
char *topic = NULL;
get_topic(&topic);
if (topic) {
int qos = get_qos();
bool retain = get_retain();
char *message = NULL;
get_message(&message);
if (message) {
unsigned long count = get_count();
for (unsigned long i = 0; i < count; ++i)
client_publish(c, topic, message, (int) strlen(message), qos, retain);
utils_delete(message);
}
utils_delete(topic);
}
}
static void client_publish_binary_data(client_s *c)
{
char *topic = NULL;
get_topic(&topic);
if (topic) {
int qos = get_qos();
bool retain = get_retain();
char *hex_seq = NULL;
get_binary_data(&hex_seq);
if (hex_seq) {
void *data = NULL;
size_t size = utils_hex_sequence_to_binary_data(hex_seq, &data);
if (data) {
unsigned long count = get_count();
for (unsigned long i = 0; i < count; ++i)
client_publish(c, topic, data, (int) size, qos, retain);
utils_delete(data);
}
utils_delete(hex_seq);
}
utils_delete(topic);
}
}
static void client_publish_file(client_s *c)
{
char *topic = NULL;
get_topic(&topic);
if (topic) {
int qos = get_qos();
bool retain = get_retain();
char *file_path = NULL;
get_file_path(&file_path);
if (file_path) {
void *message = NULL;
size_t size = utils_read_file(file_path, &message);
if (message) {
client_publish(c, topic, message, (int) size, qos, retain);
utils_delete(message);
}
utils_delete(file_path);
}
utils_delete(topic);
}
}
static void client_unsubscribe(client_s *c)
{
char *topic = NULL;
get_topic(&topic);
if (topic) {
int mid;
int rc = mosquitto_unsubscribe(c->mqtt, &mid, topic);
if (MOSQ_ERR_SUCCESS == rc)
printf("Packet ID %d: Topic \"%s\" is being unsubscribed.\n", mid, topic);
else
printf("Failed to unsubscribe the topic \"%s\". Error %d: %s\n", topic, rc, mosquitto_strerror(rc));
utils_delete(topic);
}
}
static void client_print_help(void)
{
printf("Commands\n");
printf("help - show this help message\n");
printf("publish - publish messages for a topic\n");
printf("subscribe - subscribe to a topic\n");
printf("unsubscribe - unsubscribe from a topic\n");
printf("binary - publish binary data for a topic\n");
printf("file - publish file contents for a topic\n");
printf("exit - disconnect and exit\n");
printf("quit - the same as exit\n");
}
static void client_run(client_s *c)
{
int run = 1;
while (run) {
char *input = NULL;
utils_get_stdin(&input);
if (!input)
continue;
if (!strcasecmp(input, "subscribe")) {
client_subscribe(c);
} else if (!strcasecmp(input, "publish")) {
client_publish_message(c);
} else if (!strcasecmp(input, "binary")) {
client_publish_binary_data(c);
} else if (!strcasecmp(input, "file")) {
client_publish_file(c);
} else if (!strcasecmp(input, "unsubscribe")) {
client_unsubscribe(c);
} else if (!strcasecmp(input, "exit") || !strcasecmp(input, "quit")) {
run = 0;
} else if ('\0' == input[0] || !strcasecmp(input, "help")) {
client_print_help();
} else {
printf("Unknown command: %s\n", input);
}
utils_delete(input);
}
}
static void *mqtt_thread(void *arg)
{
client_s *c = (client_s*) arg;
client_set_running_status(c, true);
bool running = true;
while (running) {
int rc = mosquitto_loop(c->mqtt, 1000, 1);
if (MOSQ_ERR_NO_CONN == rc || MOSQ_ERR_CONN_LOST == rc) {
if (c->conn_lost)
mosquitto_reconnect(c->mqtt);
}
running = client_is_running(c);
}
return arg;
}
static void write_message_to_file(FILE *fp, struct mosquitto_message *msg)
{
char buffer[512];
snprintf(buffer, (sizeof buffer) / (sizeof buffer[0]), "%s, Q%d, %d byte%s%s\n", msg->topic, msg->qos, msg->payloadlen, (msg->payloadlen > 1) ? "s" : "", (msg->retain) ? ", retain" : "");
buffer[(sizeof buffer) / (sizeof buffer[0]) - 1] = '\0';
fwrite(buffer, 1, strlen(buffer), fp);
fwrite(msg->payload, 1, msg->payloadlen, fp);
fwrite("\n\n", 1, 2, fp);
}
static void *output_thread(void *arg)
{
client_s *c = (client_s*) arg;
struct mosquitto_message *msg;
FILE *fp = fopen(c->info.client_id, "ab");
if (!fp) {
printf("Failed to to create or open %s. %s\n", c->info.client_id, strerror(errno));
printf("The messages will be output to the terminal.\n");
}
bool output_to_file = fp ? true : false;
if (fp) {
fclose(fp);
fp = NULL;
}
bool running;
do {
running = client_is_running(c);
sleep(1);
} while (!running);
if (output_to_file) {
while (running) {
fp = fopen(c->info.client_id, "ab");
if (fp) {
queue_pop_front(c->received, (void**) &msg);
while (msg) {
write_message_to_file(fp, msg);
client_received_data_delete(msg);
queue_delete_data(msg);
queue_pop_front(c->received, (void**) &msg);
}
fclose(fp);
fp = NULL;
}
sleep(1);
running = client_is_running(c);
}
} else {
while (running) {
queue_pop_front(c->received, (void**) &msg);
while (msg) {
write_message_to_file(stdout, msg);
client_received_data_delete(msg);
queue_delete_data(msg);
queue_pop_front(c->received, (void**) &msg);
}
sleep(1);
running = client_is_running(c);
}
}
return arg;
}
int main(int argc, char *argv[])
{
if (argc < 2) {
mqtt_client_print_usage(argv[0]);
return 0;
}
srand(time(NULL));
mosquitto_lib_init();
client_s client = {0};
int rc = client_init(argc - 1, &argv[1], &client);
if (0 != rc) {
mosquitto_lib_cleanup();
return -1;
}
printf("The client ID is %s.\n", client.info.client_id);
rc = client_connect(&client);
if (0 != rc) {
mosquitto_lib_cleanup();
return -2;
}
pthread_t thread_mqtt, thread_output;
if (0 != pthread_create(&thread_mqtt, NULL, mqtt_thread, &client)) {
printf("Failed to create the MQTT thread.\n");
client_cleanup(&client);
mosquitto_lib_cleanup();
return -3;
}
if (0 != pthread_create(&thread_output, NULL, output_thread, &client)) {
printf("Failed to create the output thread.\n");
client_set_running_status(&client, false);
pthread_join(thread_mqtt, NULL);
client_disconnect(&client);
client_cleanup(&client);
mosquitto_lib_cleanup();
return -4;
}
client_run(&client);
client_disconnect(&client);
client_set_running_status(&client, false);
pthread_join(thread_mqtt, NULL);
pthread_join(thread_output, NULL);
sleep(1);
client_cleanup(&client);
mosquitto_lib_cleanup();
printf("The client has been terminated.\n");
return 0;
}
| 2.546875 | 3 |
2024-11-18T19:53:05.031522+00:00 | 2017-06-04T16:36:15 | 57adc2299db6f52d79332f0160502b7bfe29227d | {
"blob_id": "57adc2299db6f52d79332f0160502b7bfe29227d",
"branch_name": "refs/heads/master",
"committer_date": "2017-06-04T16:36:15",
"content_id": "1ce1efac444c69e48caacf89fefe81d104ef1ec4",
"detected_licenses": [
"MIT"
],
"directory_id": "1944e8afd3f2fec67a981e27996147eed7c59318",
"extension": "h",
"filename": "strpool.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 13014323,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1349,
"license": "MIT",
"license_type": "permissive",
"path": "/src/strpool.h",
"provenance": "stackv2-0061.json.gz:1470",
"repo_name": "zenkj/lp",
"revision_date": "2017-06-04T16:36:15",
"revision_id": "36100e64a215182caa8debd23c82a66786d005f0",
"snapshot_id": "db23115156d5648c2450835b849b0e2ccd0a486c",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/zenkj/lp/36100e64a215182caa8debd23c82a66786d005f0/src/strpool.h",
"visit_date": "2021-01-22T22:53:22.314571"
} | stackv2 | #ifndef STRPOOL_H
#define STRPOOL_H
/*
* simple string pool.
* 1. can add string, query string by id
* 2. cannot remove string, so no need to manage the storage
*
*/
#define NOT_SP_ID -1
typedef struct {
int charcount; // current used count in the pool
int charsize; // size of the pool
char *pool; // the pool to store the strings
int idxcount; // string count
int idxsize; // index size
int *indexes; // string position list in the pool, in order
} lp_strpool;
// create a string pool
lp_strpool *strpool_init();
// destroy a string pool
void strpool_destroy(lp_strpool* sp);
// add a string into the string pool, return the id of the string
// if the string is already in the pool, just return the id of it
int strpool_add(lp_strpool* sp, const char* str);
#define strpool_getid(sp, str) strpool_add((sp), (str))
// do not implement remove-string in this simple version
// remove a string from the pool, if it exists in the pool
//void strpool_remove(lp_strpool* sp, const char* str);
// remove a string by its id, if it exists in the pool
//void strpool_removeid(lp_strpool* sp, int id);
// get a string from the pool, according to its id
const char* strpool_get(lp_strpool* sp, int id);
// for test
void strpool_print(lp_strpool *sp);
#endif //STRPOOL_H
| 2.375 | 2 |
2024-11-18T19:53:05.451199+00:00 | 2020-08-12T19:11:25 | 89d829c656fc3b83f779642f50aae75513d7f54a | {
"blob_id": "89d829c656fc3b83f779642f50aae75513d7f54a",
"branch_name": "refs/heads/master",
"committer_date": "2020-08-12T19:11:25",
"content_id": "5a86c9be0c3ac95d298ed9299c9f33045d2a1030",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "d1a211f8e3cf9daa4638e5611bc5d085d28e4eb7",
"extension": "h",
"filename": "algorithm_0.h",
"fork_events_count": 2,
"gha_created_at": "2016-01-01T01:52:45",
"gha_event_created_at": "2018-07-19T07:00:19",
"gha_language": "Haskell",
"gha_license_id": "BSD-2-Clause",
"github_id": 48867123,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 812,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/bankopak/algorithm_0.h",
"provenance": "stackv2-0061.json.gz:1856",
"repo_name": "diku-dk/openbanko",
"revision_date": "2020-08-12T19:11:25",
"revision_id": "5f8928dcd4b4faf55029667d29e1127b916a0db5",
"snapshot_id": "4137ff9008e55f339707d488c7727fec3945aeed",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/diku-dk/openbanko/5f8928dcd4b4faf55029667d29e1127b916a0db5/bankopak/algorithm_0.h",
"visit_date": "2022-12-05T21:24:57.859880"
} | stackv2 | #ifndef ALGORITHM_0_H
#define ALGORITHM_0_H
#include "bankopladeformat/bankopladeformat.h"
void a0_compress(FILE *out, FILE *in) {
struct board board;
struct banko_reader reader;
banko_reader_open(&reader, in);
while (banko_reader_board(&reader, &board) == 0) {
for (int row = 0; row < BOARD_ROWS; row++) {
for (int col = 0; col < BOARD_COLS; col++) {
fputc(board.cells[row][col], out);
}
}
}
banko_reader_close(&reader);
}
void a0_decompress(FILE *out, FILE *in) {
struct board board;
struct banko_writer writer;
banko_writer_open(&writer, out);
while (fread(&board.cells, sizeof(board.cells[0][0]),
BOARD_ROWS*BOARD_COLS, in) == BOARD_ROWS*BOARD_COLS) {
banko_writer_board(&writer, &board);
}
banko_writer_close(&writer);
}
#endif
| 2.265625 | 2 |
2024-11-18T19:53:06.185720+00:00 | 2023-06-07T17:01:51 | 5ff95dfb80d13a860084fab67a650543af60be40 | {
"blob_id": "5ff95dfb80d13a860084fab67a650543af60be40",
"branch_name": "refs/heads/main",
"committer_date": "2023-06-07T17:01:51",
"content_id": "54be6cb1e077eacc29a09b27f50ebd5a61fd7019",
"detected_licenses": [
"MIT",
"BSD-2-Clause"
],
"directory_id": "af901bc01d668ecd411549625208b07024df3ffd",
"extension": "c",
"filename": "names.c",
"fork_events_count": 128,
"gha_created_at": "2016-11-07T16:28:57",
"gha_event_created_at": "2023-08-31T13:11:13",
"gha_language": "R",
"gha_license_id": "NOASSERTION",
"github_id": 73098312,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4440,
"license": "MIT,BSD-2-Clause",
"license_type": "permissive",
"path": "/src/internal/names.c",
"provenance": "stackv2-0061.json.gz:2500",
"repo_name": "r-lib/rlang",
"revision_date": "2023-06-07T17:01:51",
"revision_id": "c55f6027928d3104ed449e591e8a225fcaf55e13",
"snapshot_id": "2784186a4dafb2fde7357c79514b3761803d0e66",
"src_encoding": "UTF-8",
"star_events_count": 355,
"url": "https://raw.githubusercontent.com/r-lib/rlang/c55f6027928d3104ed449e591e8a225fcaf55e13/src/internal/names.c",
"visit_date": "2023-09-06T03:23:47.522921"
} | stackv2 | #include <rlang.h>
#include <ctype.h>
#include "internal.h"
#include "decl/names-decl.h"
// 3 leading '.' + 1 trailing '\0' + 24 characters
#define MAX_IOTA_SIZE 28
r_obj* ffi_names_as_unique(r_obj* names, r_obj* quiet) {
return names_as_unique(names, r_lgl_get(quiet, 0));
}
// [[ export() ]]
r_obj* names_as_unique(r_obj* names, bool quiet) {
if (is_unique_names(names) && !any_has_suffix(names)) {
return names;
}
r_ssize n = r_length(names);
r_obj* new_names = KEEP(r_clone(names));
r_obj* const * v_new_names = r_chr_cbegin(new_names);
for (r_ssize i = 0; i < n; ++i) {
r_obj* elt = v_new_names[i];
// Set `NA` and dots values to "" so they get replaced by `...n`
// later on
if (needs_suffix(elt)) {
r_chr_poke(new_names, i, r_strs.empty);
continue;
}
// Strip `...n` suffixes
const char* nm = r_str_c_string(elt);
int pos = suffix_pos(nm);
if (pos >= 0) {
elt = Rf_mkCharLenCE(nm, pos, Rf_getCharCE(elt));
r_chr_poke(new_names, i, elt);
continue;
}
}
// Append all duplicates with a suffix
r_obj* dups = KEEP(chr_detect_dups(new_names));
const int* dups_ptr = r_lgl_cbegin(dups);
for (r_ssize i = 0; i < n; ++i) {
r_obj* elt = v_new_names[i];
if (elt != r_strs.empty && !dups_ptr[i]) {
continue;
}
const char* name = r_str_c_string(elt);
int size = strlen(name);
int buf_size = size + MAX_IOTA_SIZE;
R_CheckStack2(buf_size);
char buf[buf_size];
buf[0] = '\0';
memcpy(buf, name, size);
int remaining = buf_size - size;
int needed = snprintf(buf + size,
remaining,
"...%" R_PRI_SSIZE,
i + 1);
if (needed >= remaining) {
stop_large_name();
}
r_chr_poke(new_names, i, Rf_mkCharLenCE(buf, size + needed, Rf_getCharCE(elt)));
}
if (!quiet) {
names_inform_repair(names, new_names);
}
FREE(2);
return new_names;
}
static
bool is_unique_names(r_obj* names) {
if (r_typeof(names) != R_TYPE_character) {
r_abort("`names` must be a character vector.");
}
r_ssize n = r_length(names);
r_obj* const * v_names = r_chr_cbegin(names);
if (Rf_any_duplicated(names, FALSE)) {
return false;
}
for (r_ssize i = 0; i < n; ++i) {
r_obj* elt = v_names[i];
if (needs_suffix(elt)) {
return false;
}
}
return true;
}
static
bool any_has_suffix(r_obj* names) {
r_ssize n = r_length(names);
r_obj* const * v_names = r_chr_cbegin(names);
for (r_ssize i = 0; i < n; ++i) {
const char* elt = r_str_c_string(v_names[i]);
if (suffix_pos(elt) >= 0) {
return true;
}
}
return false;
}
static
ptrdiff_t suffix_pos(const char* name) {
int n = strlen(name);
const char* suffix_end = NULL;
int in_dots = 0;
bool in_digits = false;
for (const char* ptr = name + n - 1; ptr >= name; --ptr) {
char c = *ptr;
if (in_digits) {
if (c == '.') {
in_digits = false;
in_dots = 1;
continue;
}
if (isdigit(c)) {
continue;
}
goto done;
}
switch (in_dots) {
case 0:
if (isdigit(c)) {
in_digits = true;
continue;
}
goto done;
case 1:
case 2:
if (c == '.') {
++in_dots;
continue;
}
goto done;
case 3:
suffix_end = ptr + 1;
if (isdigit(c)) {
in_dots = 0;
in_digits = true;
continue;
}
goto done;
default:
r_stop_internal("Unexpected state.");
}}
done:
if (suffix_end) {
return suffix_end - name;
} else {
return -1;
}
}
static
bool needs_suffix(r_obj* str) {
return
str == r_strs.na ||
str == r_strs.dots ||
str == r_strs.empty ||
is_dotdotint(r_str_c_string(str));
}
static
bool is_dotdotint(const char* name) {
int n = strlen(name);
if (n < 3) {
return false;
}
if (name[0] != '.' || name[1] != '.') {
return false;
}
if (name[2] == '.') {
name += 3;
} else {
name += 2;
}
return (bool) strtol(name, NULL, 10);
}
static
void names_inform_repair(r_obj* old_names, r_obj* new_names) {
r_obj* call = KEEP(r_call3(r_sym("names_inform_repair"), old_names, new_names));
r_eval(call, rlang_ns_env);
FREE(1);
}
static
void stop_large_name(void) {
r_abort("Can't tidy up name because it is too large.");
}
| 2.4375 | 2 |
2024-11-18T19:53:06.249756+00:00 | 2021-02-20T18:33:34 | a65b3e83df1f7ca7c973108bf9c69128e45c4ba1 | {
"blob_id": "a65b3e83df1f7ca7c973108bf9c69128e45c4ba1",
"branch_name": "refs/heads/main",
"committer_date": "2021-02-20T18:33:34",
"content_id": "c9697da544bd0472985adc80043308d51b7a1927",
"detected_licenses": [
"MIT"
],
"directory_id": "4f9746e75ee8c1f29a1e89161096182ed7506795",
"extension": "c",
"filename": "Medir e definir um triângulo.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": 622,
"license": "MIT",
"license_type": "permissive",
"path": "/Exercícios em C/Medir e definir um triângulo.c",
"provenance": "stackv2-0061.json.gz:2628",
"repo_name": "gabrielle-nunes/Exercicios-em-C",
"revision_date": "2021-02-20T18:33:34",
"revision_id": "cb219c15999afe77ff1780fbfc91318409cb2a27",
"snapshot_id": "970cf5e187d0cf792436ba48d22430aa3f9603e0",
"src_encoding": "ISO-8859-1",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/gabrielle-nunes/Exercicios-em-C/cb219c15999afe77ff1780fbfc91318409cb2a27/Exercícios em C/Medir e definir um triângulo.c",
"visit_date": "2023-03-05T17:24:46.977371"
} | stackv2 | #include <stdio.h>
#include <stdlib.h>
#include <locale.h>
void main (){
setlocale(LC_ALL, "");
float ladoA, ladoB, ladoC;
printf("Digite as medidas dos três lados do triângulo:\n");
scanf("%f %f %f", &ladoA, &ladoB, &ladoC);
if (ladoA==0 && ladoB==0 && ladoC==0){
printf ("Esta medida não forma um triângulo.");
}
else{
if (ladoA==ladoB && ladoA==ladoC && ladoB==ladoC){
printf ("Este é um triângulo equilátero.");
}
else {
if (ladoA!=ladoB && ladoA!=ladoC && ladoB!= ladoC){
printf("Este é um triângulo escaleno.");
}
else {
printf("Este é um triângulo isósceles");
}
}
}
}
| 3.25 | 3 |
2024-11-18T19:53:06.563463+00:00 | 2023-06-21T22:55:38 | 36731bde1207c049208f3554df8ec1b709e8da39 | {
"blob_id": "36731bde1207c049208f3554df8ec1b709e8da39",
"branch_name": "refs/heads/master",
"committer_date": "2023-06-22T07:07:58",
"content_id": "c531edbb1d623e2391c16d001b5105a53dc40f72",
"detected_licenses": [
"Unlicense"
],
"directory_id": "cf111b440f33ba9741ff45c60ac33dfade24e2ac",
"extension": "c",
"filename": "c11-generic.c",
"fork_events_count": 1,
"gha_created_at": "2018-10-27T12:30:38",
"gha_event_created_at": "2023-06-22T07:08:00",
"gha_language": "JavaScript",
"gha_license_id": "Unlicense",
"github_id": 154962425,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 705,
"license": "Unlicense",
"license_type": "permissive",
"path": "/Snippets/C/c11-generic.c",
"provenance": "stackv2-0061.json.gz:2884",
"repo_name": "fredmorcos/attic",
"revision_date": "2023-06-21T22:55:38",
"revision_id": "36d5891a959cfc83f9eeef003b4e0b574dd7d7e1",
"snapshot_id": "cd08e951f56c3b256899ef5ca4ccd030d3185bc1",
"src_encoding": "UTF-8",
"star_events_count": 4,
"url": "https://raw.githubusercontent.com/fredmorcos/attic/36d5891a959cfc83f9eeef003b4e0b574dd7d7e1/Snippets/C/c11-generic.c",
"visit_date": "2023-07-05T10:03:58.115062"
} | stackv2 | /*
* gcc -Wall -Wextra -pedantic -std=c11 c11_generic.c -o c11_generic
*/
#include <stdio.h>
void print_int(int x) { printf("%d", x); }
void print_double(double x) { printf("%f", x); }
void print_str(const char x[static 1]) { printf("%s", x); }
void print_char(char x) { printf("%c", x); }
#define print(x) _Generic((x), \
int: print_int, double: print_double, \
char: print_char, default: print_str)((x))
int main(int argc, __attribute__((unused)) char *argv[argc + 1]) {
print(5);
print((char) '\n');
print(5.5);
print((char) '\n');
print("hello");
print((char) '\n');
return 0;
}
| 2.921875 | 3 |
2024-11-18T19:53:07.103972+00:00 | 2021-10-08T17:52:04 | 0627a28ca1a579bf86871d3c004b9f885c908b0d | {
"blob_id": "0627a28ca1a579bf86871d3c004b9f885c908b0d",
"branch_name": "refs/heads/main",
"committer_date": "2021-10-08T17:52:04",
"content_id": "eae441bd9f14005a63ac8aaed12426f1a923e458",
"detected_licenses": [
"MIT"
],
"directory_id": "9987fa7f5ab9ca076f07ec540bc0f46a921893d5",
"extension": "c",
"filename": "FCFS disk scheduling.c",
"fork_events_count": 0,
"gha_created_at": "2021-10-08T17:49:45",
"gha_event_created_at": "2021-10-08T17:52:05",
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 415079116,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 860,
"license": "MIT",
"license_type": "permissive",
"path": "/FCFS disk scheduling.c",
"provenance": "stackv2-0061.json.gz:3398",
"repo_name": "Adithyapanchaman/hacktoberfest2021-1",
"revision_date": "2021-10-08T17:52:04",
"revision_id": "cc01b99856bcd0571ca8225cb5702b27f4228515",
"snapshot_id": "ba5e449bf9e49b4bf8b99da28ebe53cf117872b3",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Adithyapanchaman/hacktoberfest2021-1/cc01b99856bcd0571ca8225cb5702b27f4228515/FCFS disk scheduling.c",
"visit_date": "2023-08-23T06:55:57.613867"
} | stackv2 | #include<stdio.h>
int main()
{
int queue[20],n,head,i,j,k,seek=0,max,diff;
float avg;
printf("Enter the max range of disk\n");
scanf("%d",&max);
printf("Enter the size of queue request\n");
scanf("%d",&n);
printf("Enter the queue of disk positions to be read\n");
for(i=1;i<=n;i++)
scanf("%d",&queue[i]);
printf("Enter the initial head position\n");
scanf("%d",&head);
queue[0]=head;
for(j=0;j<=n-1;j++)
{
diff=abs(queue[j+1]-queue[j]);
seek+=diff;
printf("Disk head moves from %d to %d with seek %d\n",queue[j],queue[j+1],diff);
}
printf("Total seek time is %d\n",seek);
return 0;
}
| 2.90625 | 3 |
2024-11-18T19:53:07.432698+00:00 | 2023-08-09T18:19:32 | f6aa22b9cbba60d9bda3882f51224ed7fa1b75a2 | {
"blob_id": "f6aa22b9cbba60d9bda3882f51224ed7fa1b75a2",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-09T18:19:32",
"content_id": "48d72046f2172b27f6acc29ea22d7009f551a665",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "a4a96286d9860e2661cd7c7f571d42bfa04c86cf",
"extension": "h",
"filename": "spi_struct.h",
"fork_events_count": 1,
"gha_created_at": "2020-01-23T18:05:37",
"gha_event_created_at": "2020-01-23T18:05:38",
"gha_language": null,
"gha_license_id": "Apache-2.0",
"github_id": 235855012,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 61024,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/components/soc/esp32p4/include/soc/spi_struct.h",
"provenance": "stackv2-0061.json.gz:3656",
"repo_name": "KollarRichard/esp-idf",
"revision_date": "2023-08-09T18:19:32",
"revision_id": "3befd5fff72aa6980514454a50233037718b611f",
"snapshot_id": "1a3c314b37c763bdd231d974c9e16b9c7588e42c",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/KollarRichard/esp-idf/3befd5fff72aa6980514454a50233037718b611f/components/soc/esp32p4/include/soc/spi_struct.h",
"visit_date": "2023-08-16T20:32:50.823995"
} | stackv2 | /**
* SPDX-FileCopyrightText: 2023 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Apache-2.0
*/
#pragma once
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
/** Group: User-defined control registers */
/** Type of cmd register
* Command control register
*/
typedef union {
struct {
/** conf_bitlen : R/W; bitpos: [17:0]; default: 0;
* Define the APB cycles of SPI_CONF state. Can be configured in CONF state.
*/
uint32_t conf_bitlen:18; //this field is only for GPSPI2
uint32_t reserved_18:5;
/** update : WT; bitpos: [23]; default: 0;
* Set this bit to synchronize SPI registers from APB clock domain into SPI module
* clock domain, which is only used in SPI master mode.
*/
uint32_t update:1;
/** usr : R/W/SC; bitpos: [24]; default: 0;
* User define command enable. An operation will be triggered when the bit is set.
* The bit will be cleared once the operation done.1: enable 0: disable. Can not be
* changed by CONF_buf.
*/
uint32_t usr:1;
uint32_t reserved_25:7;
};
uint32_t val;
} spi_cmd_reg_t;
/** Type of addr register
* Address value register
*/
typedef union {
struct {
/** usr_addr_value : R/W; bitpos: [31:0]; default: 0;
* Address to slave. Can be configured in CONF state.
*/
uint32_t usr_addr_value:32;
};
uint32_t val;
} spi_addr_reg_t;
/** Type of user register
* SPI USER control register
*/
typedef union {
struct {
/** doutdin : R/W; bitpos: [0]; default: 0;
* Set the bit to enable full duplex communication. 1: enable 0: disable. Can be
* configured in CONF state.
*/
uint32_t doutdin:1;
uint32_t reserved_1:2;
/** qpi_mode : R/W/SS/SC; bitpos: [3]; default: 0;
* Both for master mode and slave mode. 1: spi controller is in QPI mode. 0: others.
* Can be configured in CONF state.
*/
uint32_t qpi_mode:1;
/** opi_mode : R/W; bitpos: [4]; default: 0;
* Just for master mode. 1: spi controller is in OPI mode (all in 8-b-m). 0: others.
* Can be configured in CONF state.
*/
uint32_t opi_mode:1; //this field is only for GPSPI2
/** tsck_i_edge : R/W; bitpos: [5]; default: 0;
* In the slave mode, this bit can be used to change the polarity of tsck. 0: tsck =
* spi_ck_i. 1:tsck = !spi_ck_i.
*/
uint32_t tsck_i_edge:1;
/** cs_hold : R/W; bitpos: [6]; default: 1;
* spi cs keep low when spi is in done phase. 1: enable 0: disable. Can be
* configured in CONF state.
*/
uint32_t cs_hold:1;
/** cs_setup : R/W; bitpos: [7]; default: 1;
* spi cs is enable when spi is in prepare phase. 1: enable 0: disable. Can be
* configured in CONF state.
*/
uint32_t cs_setup:1;
/** rsck_i_edge : R/W; bitpos: [8]; default: 0;
* In the slave mode, this bit can be used to change the polarity of rsck. 0: rsck =
* !spi_ck_i. 1:rsck = spi_ck_i.
*/
uint32_t rsck_i_edge:1;
/** ck_out_edge : R/W; bitpos: [9]; default: 0;
* the bit combined with spi_mosi_delay_mode bits to set mosi signal delay mode. Can
* be configured in CONF state.
*/
uint32_t ck_out_edge:1;
uint32_t reserved_10:2;
/** fwrite_dual : R/W; bitpos: [12]; default: 0;
* In the write operations read-data phase apply 2 signals. Can be configured in CONF
* state.
*/
uint32_t fwrite_dual:1;
/** fwrite_quad : R/W; bitpos: [13]; default: 0;
* In the write operations read-data phase apply 4 signals. Can be configured in CONF
* state.
*/
uint32_t fwrite_quad:1;
/** fwrite_oct : R/W; bitpos: [14]; default: 0;
* In the write operations read-data phase apply 8 signals. Can be configured in CONF
* state.
*/
uint32_t fwrite_oct:1; //this field is only for GPSPI2
/** usr_conf_nxt : R/W; bitpos: [15]; default: 0;
* 1: Enable the DMA CONF phase of next seg-trans operation, which means seg-trans
* will continue. 0: The seg-trans will end after the current SPI seg-trans or this is
* not seg-trans mode. Can be configured in CONF state.
*/
uint32_t usr_conf_nxt:1; //this field is only for GPSPI2
uint32_t reserved_16:1;
/** sio : R/W; bitpos: [17]; default: 0;
* Set the bit to enable 3-line half duplex communication mosi and miso signals share
* the same pin. 1: enable 0: disable. Can be configured in CONF state.
*/
uint32_t sio:1;
uint32_t reserved_18:6;
/** usr_miso_highpart : R/W; bitpos: [24]; default: 0;
* read-data phase only access to high-part of the buffer spi_w8~spi_w15. 1: enable 0:
* disable. Can be configured in CONF state.
*/
uint32_t usr_miso_highpart:1;
/** usr_mosi_highpart : R/W; bitpos: [25]; default: 0;
* write-data phase only access to high-part of the buffer spi_w8~spi_w15. 1: enable
* 0: disable. Can be configured in CONF state.
*/
uint32_t usr_mosi_highpart:1;
/** usr_dummy_idle : R/W; bitpos: [26]; default: 0;
* spi clock is disable in dummy phase when the bit is enable. Can be configured in
* CONF state.
*/
uint32_t usr_dummy_idle:1;
/** usr_mosi : R/W; bitpos: [27]; default: 0;
* This bit enable the write-data phase of an operation. Can be configured in CONF
* state.
*/
uint32_t usr_mosi:1;
/** usr_miso : R/W; bitpos: [28]; default: 0;
* This bit enable the read-data phase of an operation. Can be configured in CONF
* state.
*/
uint32_t usr_miso:1;
/** usr_dummy : R/W; bitpos: [29]; default: 0;
* This bit enable the dummy phase of an operation. Can be configured in CONF state.
*/
uint32_t usr_dummy:1;
/** usr_addr : R/W; bitpos: [30]; default: 0;
* This bit enable the address phase of an operation. Can be configured in CONF state.
*/
uint32_t usr_addr:1;
/** usr_command : R/W; bitpos: [31]; default: 1;
* This bit enable the command phase of an operation. Can be configured in CONF state.
*/
uint32_t usr_command:1;
};
uint32_t val;
} spi_user_reg_t;
/** Type of user1 register
* SPI USER control register 1
*/
typedef union {
struct {
/** usr_dummy_cyclelen : R/W; bitpos: [7:0]; default: 7;
* The length in spi_clk cycles of dummy phase. The register value shall be
* (cycle_num-1). Can be configured in CONF state.
*/
uint32_t usr_dummy_cyclelen:8;
uint32_t reserved_8:8;
/** mst_wfull_err_end_en : R/W; bitpos: [16]; default: 1;
* 1: SPI transfer is ended when SPI RX AFIFO wfull error is valid in GP-SPI master
* FD/HD-mode. 0: SPI transfer is not ended when SPI RX AFIFO wfull error is valid in
* GP-SPI master FD/HD-mode.
*/
uint32_t mst_wfull_err_end_en:1;
/** cs_setup_time : R/W; bitpos: [21:17]; default: 0;
* (cycles+1) of prepare phase by spi clock this bits are combined with spi_cs_setup
* bit. Can be configured in CONF state.
*/
uint32_t cs_setup_time:5;
/** cs_hold_time : R/W; bitpos: [26:22]; default: 1;
* delay cycles of cs pin by spi clock this bits are combined with spi_cs_hold bit.
* Can be configured in CONF state.
*/
uint32_t cs_hold_time:5;
/** usr_addr_bitlen : R/W; bitpos: [31:27]; default: 23;
* The length in bits of address phase. The register value shall be (bit_num-1). Can
* be configured in CONF state.
*/
uint32_t usr_addr_bitlen:5;
};
uint32_t val;
} spi_user1_reg_t;
/** Type of user2 register
* SPI USER control register 2
*/
typedef union {
struct {
/** usr_command_value : R/W; bitpos: [15:0]; default: 0;
* The value of command. Can be configured in CONF state.
*/
uint32_t usr_command_value:16;
uint32_t reserved_16:11;
/** mst_rempty_err_end_en : R/W; bitpos: [27]; default: 1;
* 1: SPI transfer is ended when SPI TX AFIFO read empty error is valid in GP-SPI
* master FD/HD-mode. 0: SPI transfer is not ended when SPI TX AFIFO read empty error
* is valid in GP-SPI master FD/HD-mode.
*/
uint32_t mst_rempty_err_end_en:1;
/** usr_command_bitlen : R/W; bitpos: [31:28]; default: 7;
* The length in bits of command phase. The register value shall be (bit_num-1). Can
* be configured in CONF state.
*/
uint32_t usr_command_bitlen:4;
};
uint32_t val;
} spi_user2_reg_t;
/** Group: Control and configuration registers */
/** Type of ctrl register
* SPI control register
*/
typedef union {
struct {
uint32_t reserved_0:3;
/** dummy_out : R/W; bitpos: [3]; default: 0;
* 0: In the dummy phase, the FSPI bus signals are not output. 1: In the dummy phase,
* the FSPI bus signals are output. Can be configured in CONF state.
*/
uint32_t dummy_out:1;
uint32_t reserved_4:1;
/** faddr_dual : R/W; bitpos: [5]; default: 0;
* Apply 2 signals during addr phase 1:enable 0: disable. Can be configured in CONF
* state.
*/
uint32_t faddr_dual:1;
/** faddr_quad : R/W; bitpos: [6]; default: 0;
* Apply 4 signals during addr phase 1:enable 0: disable. Can be configured in CONF
* state.
*/
uint32_t faddr_quad:1;
/** faddr_oct : R/W; bitpos: [7]; default: 0;
* Apply 8 signals during addr phase 1:enable 0: disable. Can be configured in CONF
* state.
*/
uint32_t faddr_oct:1; //this field is only for GPSPI2
/** fcmd_dual : R/W; bitpos: [8]; default: 0;
* Apply 2 signals during command phase 1:enable 0: disable. Can be configured in CONF
* state.
*/
uint32_t fcmd_dual:1;
/** fcmd_quad : R/W; bitpos: [9]; default: 0;
* Apply 4 signals during command phase 1:enable 0: disable. Can be configured in CONF
* state.
*/
uint32_t fcmd_quad:1;
/** fcmd_oct : R/W; bitpos: [10]; default: 0;
* Apply 8 signals during command phase 1:enable 0: disable. Can be configured in CONF
* state.
*/
uint32_t fcmd_oct:1; //this field is only for GPSPI2
uint32_t reserved_11:3;
/** fread_dual : R/W; bitpos: [14]; default: 0;
* In the read operations, read-data phase apply 2 signals. 1: enable 0: disable. Can
* be configured in CONF state.
*/
uint32_t fread_dual:1;
/** fread_quad : R/W; bitpos: [15]; default: 0;
* In the read operations read-data phase apply 4 signals. 1: enable 0: disable. Can
* be configured in CONF state.
*/
uint32_t fread_quad:1;
/** fread_oct : R/W; bitpos: [16]; default: 0;
* In the read operations read-data phase apply 8 signals. 1: enable 0: disable. Can
* be configured in CONF state.
*/
uint32_t fread_oct:1; //this field is only for GPSPI2
uint32_t reserved_17:1;
/** q_pol : R/W; bitpos: [18]; default: 1;
* The bit is used to set MISO line polarity, 1: high 0, low. Can be configured in
* CONF state.
*/
uint32_t q_pol:1;
/** d_pol : R/W; bitpos: [19]; default: 1;
* The bit is used to set MOSI line polarity, 1: high 0, low. Can be configured in
* CONF state.
*/
uint32_t d_pol:1;
/** hold_pol : R/W; bitpos: [20]; default: 1;
* SPI_HOLD output value when SPI is idle. 1: output high, 0: output low. Can be
* configured in CONF state.
*/
uint32_t hold_pol:1;
/** wp_pol : R/W; bitpos: [21]; default: 1;
* Write protect signal output when SPI is idle. 1: output high, 0: output low. Can
* be configured in CONF state.
*/
uint32_t wp_pol:1;
uint32_t reserved_22:1;
/** rd_bit_order : R/W; bitpos: [24:23]; default: 0;
* In read-data (MISO) phase 1: LSB first 0: MSB first. Can be configured in CONF
* state.
*/
uint32_t rd_bit_order:2;
/** wr_bit_order : R/W; bitpos: [26:25]; default: 0;
* In command address write-data (MOSI) phases 1: LSB firs 0: MSB first. Can be
* configured in CONF state.
*/
uint32_t wr_bit_order:2;
uint32_t reserved_27:5;
};
uint32_t val;
} spi_ctrl_reg_t;
/** Type of ms_dlen register
* SPI data bit length control register
*/
typedef union {
struct {
/** ms_data_bitlen : R/W; bitpos: [17:0]; default: 0;
* The value of these bits is the configured SPI transmission data bit length in
* master mode DMA controlled transfer or CPU controlled transfer. The value is also
* the configured bit length in slave mode DMA RX controlled transfer. The register
* value shall be (bit_num-1). Can be configured in CONF state.
*/
uint32_t ms_data_bitlen:18;
uint32_t reserved_18:14;
};
uint32_t val;
} spi_ms_dlen_reg_t;
/** Type of misc register
* SPI misc register
*/
typedef union {
struct {
/** cs0_dis : R/W; bitpos: [0]; default: 0;
* SPI CS$n pin enable, 1: disable CS$n, 0: spi_cs$n signal is from/to CS$n pin. Can
* be configured in CONF state.
*/
uint32_t cs0_dis:1;
/** cs1_dis : R/W; bitpos: [1]; default: 1;
* SPI CS$n pin enable, 1: disable CS$n, 0: spi_cs$n signal is from/to CS$n pin. Can
* be configured in CONF state.
*/
uint32_t cs1_dis:1;
/** cs2_dis : R/W; bitpos: [2]; default: 1;
* SPI CS$n pin enable, 1: disable CS$n, 0: spi_cs$n signal is from/to CS$n pin. Can
* be configured in CONF state.
*/
uint32_t cs2_dis:1;
/** cs3_dis : R/W; bitpos: [3]; default: 1;
* SPI CS$n pin enable, 1: disable CS$n, 0: spi_cs$n signal is from/to CS$n pin. Can
* be configured in CONF state.
*/
uint32_t cs3_dis:1; //this field is only for GPSPI2
/** cs4_dis : R/W; bitpos: [4]; default: 1;
* SPI CS$n pin enable, 1: disable CS$n, 0: spi_cs$n signal is from/to CS$n pin. Can
* be configured in CONF state.
*/
uint32_t cs4_dis:1; //this field is only for GPSPI2
/** cs5_dis : R/W; bitpos: [5]; default: 1;
* SPI CS$n pin enable, 1: disable CS$n, 0: spi_cs$n signal is from/to CS$n pin. Can
* be configured in CONF state.
*/
uint32_t cs5_dis:1; //this field is only for GPSPI2
/** ck_dis : R/W; bitpos: [6]; default: 0;
* 1: spi clk out disable, 0: spi clk out enable. Can be configured in CONF state.
*/
uint32_t ck_dis:1;
/** master_cs_pol : R/W; bitpos: [12:7]; default: 0;
* In the master mode the bits are the polarity of spi cs line, the value is
* equivalent to spi_cs ^ spi_master_cs_pol. Can be configured in CONF state.
*/
uint32_t master_cs_pol:6; //This field for GPSPI3 is only 3-bit-width
uint32_t reserved_13:3;
/** clk_data_dtr_en : R/W; bitpos: [16]; default: 0;
* 1: SPI master DTR mode is applied to SPI clk, data and spi_dqs. 0: SPI master DTR
* mode is only applied to spi_dqs. This bit should be used with bit 17/18/19.
*/
uint32_t clk_data_dtr_en:1; //this field is only for GPSPI2
/** data_dtr_en : R/W; bitpos: [17]; default: 0;
* 1: SPI clk and data of SPI_DOUT and SPI_DIN state are in DTR mode, including master
* 1/2/4/8-bm. 0: SPI clk and data of SPI_DOUT and SPI_DIN state are in STR mode.
* Can be configured in CONF state.
*/
uint32_t data_dtr_en:1; //this field is only for GPSPI2
/** addr_dtr_en : R/W; bitpos: [18]; default: 0;
* 1: SPI clk and data of SPI_SEND_ADDR state are in DTR mode, including master
* 1/2/4/8-bm. 0: SPI clk and data of SPI_SEND_ADDR state are in STR mode. Can be
* configured in CONF state.
*/
uint32_t addr_dtr_en:1; //this field is only for GPSPI2
/** cmd_dtr_en : R/W; bitpos: [19]; default: 0;
* 1: SPI clk and data of SPI_SEND_CMD state are in DTR mode, including master
* 1/2/4/8-bm. 0: SPI clk and data of SPI_SEND_CMD state are in STR mode. Can be
* configured in CONF state.
*/
uint32_t cmd_dtr_en:1; //this field is only for GPSPI2
uint32_t reserved_20:3;
/** slave_cs_pol : R/W; bitpos: [23]; default: 0;
* spi slave input cs polarity select. 1: inv 0: not change. Can be configured in
* CONF state.
*/
uint32_t slave_cs_pol:1;
/** dqs_idle_edge : R/W; bitpos: [24]; default: 0;
* The default value of spi_dqs. Can be configured in CONF state.
*/
uint32_t dqs_idle_edge:1; //this field is only for GPSPI2
uint32_t reserved_25:4;
/** ck_idle_edge : R/W; bitpos: [29]; default: 0;
* 1: spi clk line is high when idle 0: spi clk line is low when idle. Can be
* configured in CONF state.
*/
uint32_t ck_idle_edge:1;
/** cs_keep_active : R/W; bitpos: [30]; default: 0;
* spi cs line keep low when the bit is set. Can be configured in CONF state.
*/
uint32_t cs_keep_active:1;
/** quad_din_pin_swap : R/W; bitpos: [31]; default: 0;
* 1: SPI quad input swap enable, swap FSPID with FSPIQ, swap FSPIWP with FSPIHD. 0:
* spi quad input swap disable. Can be configured in CONF state.
*/
uint32_t quad_din_pin_swap:1;
};
uint32_t val;
} spi_misc_reg_t;
/** Type of dma_conf register
* SPI DMA control register
*/
typedef union {
struct {
/** dma_outfifo_empty : RO; bitpos: [0]; default: 1;
* Records the status of DMA TX FIFO. 1: DMA TX FIFO is not ready for sending data. 0:
* DMA TX FIFO is ready for sending data.
*/
uint32_t dma_outfifo_empty:1;
/** dma_infifo_full : RO; bitpos: [1]; default: 1;
* Records the status of DMA RX FIFO. 1: DMA RX FIFO is not ready for receiving data.
* 0: DMA RX FIFO is ready for receiving data.
*/
uint32_t dma_infifo_full:1;
uint32_t reserved_2:16;
/** dma_slv_seg_trans_en : R/W; bitpos: [18]; default: 0;
* Enable dma segment transfer in spi dma half slave mode. 1: enable. 0: disable.
*/
uint32_t dma_slv_seg_trans_en:1;
/** slv_rx_seg_trans_clr_en : R/W; bitpos: [19]; default: 0;
* 1: spi_dma_infifo_full_vld is cleared by spi slave cmd 5. 0:
* spi_dma_infifo_full_vld is cleared by spi_trans_done.
*/
uint32_t slv_rx_seg_trans_clr_en:1;
/** slv_tx_seg_trans_clr_en : R/W; bitpos: [20]; default: 0;
* 1: spi_dma_outfifo_empty_vld is cleared by spi slave cmd 6. 0:
* spi_dma_outfifo_empty_vld is cleared by spi_trans_done.
*/
uint32_t slv_tx_seg_trans_clr_en:1;
/** rx_eof_en : R/W; bitpos: [21]; default: 0;
* 1: spi_dma_inlink_eof is set when the number of dma pushed data bytes is equal to
* the value of spi_slv/mst_dma_rd_bytelen[19:0] in spi dma transition. 0:
* spi_dma_inlink_eof is set by spi_trans_done in non-seg-trans or
* spi_dma_seg_trans_done in seg-trans.
*/
uint32_t rx_eof_en:1;
uint32_t reserved_22:5;
/** dma_rx_ena : R/W; bitpos: [27]; default: 0;
* Set this bit to enable SPI DMA controlled receive data mode.
*/
uint32_t dma_rx_ena:1;
/** dma_tx_ena : R/W; bitpos: [28]; default: 0;
* Set this bit to enable SPI DMA controlled send data mode.
*/
uint32_t dma_tx_ena:1;
/** rx_afifo_rst : WT; bitpos: [29]; default: 0;
* Set this bit to reset RX AFIFO, which is used to receive data in SPI master and
* slave mode transfer.
*/
uint32_t rx_afifo_rst:1;
/** buf_afifo_rst : WT; bitpos: [30]; default: 0;
* Set this bit to reset BUF TX AFIFO, which is used send data out in SPI slave CPU
* controlled mode transfer and master mode transfer.
*/
uint32_t buf_afifo_rst:1;
/** dma_afifo_rst : WT; bitpos: [31]; default: 0;
* Set this bit to reset DMA TX AFIFO, which is used to send data out in SPI slave DMA
* controlled mode transfer.
*/
uint32_t dma_afifo_rst:1;
};
uint32_t val;
} spi_dma_conf_reg_t;
/** Type of slave register
* SPI slave control register
*/
typedef union {
struct {
/** clk_mode : R/W; bitpos: [1:0]; default: 0;
* SPI clock mode bits. 0: SPI clock is off when CS inactive 1: SPI clock is delayed
* one cycle after CS inactive 2: SPI clock is delayed two cycles after CS inactive 3:
* SPI clock is alwasy on. Can be configured in CONF state.
*/
uint32_t clk_mode:2;
/** clk_mode_13 : R/W; bitpos: [2]; default: 0;
* {CPOL, CPHA},1: support spi clk mode 1 and 3, first edge output data B[0]/B[7]. 0:
* support spi clk mode 0 and 2, first edge output data B[1]/B[6].
*/
uint32_t clk_mode_13:1;
/** rsck_data_out : R/W; bitpos: [3]; default: 0;
* It saves half a cycle when tsck is the same as rsck. 1: output data at rsck posedge
* 0: output data at tsck posedge
*/
uint32_t rsck_data_out:1;
uint32_t reserved_4:4;
/** slv_rddma_bitlen_en : R/W; bitpos: [8]; default: 0;
* 1: SPI_SLV_DATA_BITLEN stores data bit length of master-read-slave data length in
* DMA controlled mode(Rd_DMA). 0: others
*/
uint32_t slv_rddma_bitlen_en:1;
/** slv_wrdma_bitlen_en : R/W; bitpos: [9]; default: 0;
* 1: SPI_SLV_DATA_BITLEN stores data bit length of master-write-to-slave data length
* in DMA controlled mode(Wr_DMA). 0: others
*/
uint32_t slv_wrdma_bitlen_en:1;
/** slv_rdbuf_bitlen_en : R/W; bitpos: [10]; default: 0;
* 1: SPI_SLV_DATA_BITLEN stores data bit length of master-read-slave data length in
* CPU controlled mode(Rd_BUF). 0: others
*/
uint32_t slv_rdbuf_bitlen_en:1;
/** slv_wrbuf_bitlen_en : R/W; bitpos: [11]; default: 0;
* 1: SPI_SLV_DATA_BITLEN stores data bit length of master-write-to-slave data length
* in CPU controlled mode(Wr_BUF). 0: others
*/
uint32_t slv_wrbuf_bitlen_en:1;
/** slv_last_byte_strb : R/SS; bitpos: [19:12]; default: 0;
* Represents the effective bit of the last received data byte in SPI slave FD and HD
* mode.
*/
uint32_t slv_last_byte_strb:8;
uint32_t reserved_20:2;
/** dma_seg_magic_value : R/W; bitpos: [25:22]; default: 10;
* The magic value of BM table in master DMA seg-trans.
*/
uint32_t dma_seg_magic_value:4; //this field is only for GPSPI2
/** slave_mode : R/W; bitpos: [26]; default: 0;
* Set SPI work mode. 1: slave mode 0: master mode.
*/
uint32_t slave_mode:1;
/** soft_reset : WT; bitpos: [27]; default: 0;
* Software reset enable, reset the spi clock line cs line and data lines. Can be
* configured in CONF state.
*/
uint32_t soft_reset:1;
/** usr_conf : R/W; bitpos: [28]; default: 0;
* 1: Enable the DMA CONF phase of current seg-trans operation, which means seg-trans
* will start. 0: This is not seg-trans mode.
*/
uint32_t usr_conf:1; //this field is only for GPSPI2
/** mst_fd_wait_dma_tx_data : R/W; bitpos: [29]; default: 0;
* In master full-duplex mode, 1: GP-SPI will wait DMA TX data is ready before
* starting SPI transfer. 0: GP-SPI does not wait DMA TX data before starting SPI
* transfer.
*/
uint32_t mst_fd_wait_dma_tx_data:1;
uint32_t reserved_30:2;
};
uint32_t val;
} spi_slave_reg_t;
/** Type of slave1 register
* SPI slave control register 1
*/
typedef union {
struct {
/** slv_data_bitlen : R/W/SS; bitpos: [17:0]; default: 0;
* The transferred data bit length in SPI slave FD and HD mode.
*/
uint32_t slv_data_bitlen:18;
/** slv_last_command : R/W/SS; bitpos: [25:18]; default: 0;
* In the slave mode it is the value of command.
*/
uint32_t slv_last_command:8;
/** slv_last_addr : R/W/SS; bitpos: [31:26]; default: 0;
* In the slave mode it is the value of address.
*/
uint32_t slv_last_addr:6;
};
uint32_t val;
} spi_slave1_reg_t;
/** Group: Clock control registers */
/** Type of clock register
* SPI clock control register
*/
typedef union {
struct {
/** clkcnt_l : R/W; bitpos: [5:0]; default: 3;
* In the master mode it must be equal to spi_clkcnt_N. In the slave mode it must be
* 0. Can be configured in CONF state.
*/
uint32_t clkcnt_l:6;
/** clkcnt_h : R/W; bitpos: [11:6]; default: 1;
* In the master mode it must be floor((spi_clkcnt_N+1)/2-1). In the slave mode it
* must be 0. Can be configured in CONF state.
*/
uint32_t clkcnt_h:6;
/** clkcnt_n : R/W; bitpos: [17:12]; default: 3;
* In the master mode it is the divider of spi_clk. So spi_clk frequency is
* system/(spi_clkdiv_pre+1)/(spi_clkcnt_N+1). Can be configured in CONF state.
*/
uint32_t clkcnt_n:6;
/** clkdiv_pre : R/W; bitpos: [21:18]; default: 0;
* In the master mode it is pre-divider of spi_clk. Can be configured in CONF state.
*/
uint32_t clkdiv_pre:4;
uint32_t reserved_22:9;
/** clk_equ_sysclk : R/W; bitpos: [31]; default: 1;
* In the master mode 1: spi_clk is eqaul to system 0: spi_clk is divided from system
* clock. Can be configured in CONF state.
*/
uint32_t clk_equ_sysclk:1;
};
uint32_t val;
} spi_clock_reg_t;
/** Type of clk_gate register
* SPI module clock and register clock control
*/
typedef union {
struct {
/** clk_en : R/W; bitpos: [0]; default: 0;
* Set this bit to enable clk gate
*/
uint32_t clk_en:1;
/** mst_clk_active : R/W; bitpos: [1]; default: 0;
* Set this bit to power on the SPI module clock.
*/
uint32_t mst_clk_active:1;
/** mst_clk_sel : R/W; bitpos: [2]; default: 0;
* This bit is used to select SPI module clock source in master mode. 1: PLL_CLK_80M.
* 0: XTAL CLK.
*/
uint32_t mst_clk_sel:1;
uint32_t reserved_3:29;
};
uint32_t val;
} spi_clk_gate_reg_t;
/** Group: Timing registers */
/** Type of din_mode register
* SPI input delay mode configuration
*/
typedef union {
struct {
/** din0_mode : R/W; bitpos: [1:0]; default: 0;
* the input signals are delayed by SPI module clock cycles, 0: input without delayed,
* 1: input with the posedge of clk_apb,2 input with the negedge of clk_apb, 3: input
* with the spi_clk. Can be configured in CONF state.
*/
uint32_t din0_mode:2;
/** din1_mode : R/W; bitpos: [3:2]; default: 0;
* the input signals are delayed by SPI module clock cycles, 0: input without delayed,
* 1: input with the posedge of clk_apb,2 input with the negedge of clk_apb, 3: input
* with the spi_clk. Can be configured in CONF state.
*/
uint32_t din1_mode:2;
/** din2_mode : R/W; bitpos: [5:4]; default: 0;
* the input signals are delayed by SPI module clock cycles, 0: input without delayed,
* 1: input with the posedge of clk_apb,2 input with the negedge of clk_apb, 3: input
* with the spi_clk. Can be configured in CONF state.
*/
uint32_t din2_mode:2;
/** din3_mode : R/W; bitpos: [7:6]; default: 0;
* the input signals are delayed by SPI module clock cycles, 0: input without delayed,
* 1: input with the posedge of clk_apb,2 input with the negedge of clk_apb, 3: input
* with the spi_clk. Can be configured in CONF state.
*/
uint32_t din3_mode:2;
/** din4_mode : R/W; bitpos: [9:8]; default: 0;
* the input signals are delayed by SPI module clock cycles, 0: input without delayed,
* 1: input with the posedge of clk_apb,2 input with the negedge of clk_apb, 3: input
* with the spi_clk. Can be configured in CONF state.
*/
uint32_t din4_mode:2; //this field is only for GPSPI2
/** din5_mode : R/W; bitpos: [11:10]; default: 0;
* the input signals are delayed by SPI module clock cycles, 0: input without delayed,
* 1: input with the posedge of clk_apb,2 input with the negedge of clk_apb, 3: input
* with the spi_clk. Can be configured in CONF state.
*/
uint32_t din5_mode:2; //this field is only for GPSPI2
/** din6_mode : R/W; bitpos: [13:12]; default: 0;
* the input signals are delayed by SPI module clock cycles, 0: input without delayed,
* 1: input with the posedge of clk_apb,2 input with the negedge of clk_apb, 3: input
* with the spi_clk. Can be configured in CONF state.
*/
uint32_t din6_mode:2; //this field is only for GPSPI2
/** din7_mode : R/W; bitpos: [15:14]; default: 0;
* the input signals are delayed by SPI module clock cycles, 0: input without delayed,
* 1: input with the posedge of clk_apb,2 input with the negedge of clk_apb, 3: input
* with the spi_clk. Can be configured in CONF state.
*/
uint32_t din7_mode:2; //this field is only for GPSPI2
/** timing_hclk_active : R/W; bitpos: [16]; default: 0;
* 1:enable hclk in SPI input timing module. 0: disable it. Can be configured in CONF
* state.
*/
uint32_t timing_hclk_active:1;
uint32_t reserved_17:15;
};
uint32_t val;
} spi_din_mode_reg_t;
/** Type of din_num register
* SPI input delay number configuration
*/
typedef union {
struct {
/** din0_num : R/W; bitpos: [1:0]; default: 0;
* the input signals are delayed by SPI module clock cycles, 0: delayed by 1 cycle, 1:
* delayed by 2 cycles,... Can be configured in CONF state.
*/
uint32_t din0_num:2;
/** din1_num : R/W; bitpos: [3:2]; default: 0;
* the input signals are delayed by SPI module clock cycles, 0: delayed by 1 cycle, 1:
* delayed by 2 cycles,... Can be configured in CONF state.
*/
uint32_t din1_num:2;
/** din2_num : R/W; bitpos: [5:4]; default: 0;
* the input signals are delayed by SPI module clock cycles, 0: delayed by 1 cycle, 1:
* delayed by 2 cycles,... Can be configured in CONF state.
*/
uint32_t din2_num:2;
/** din3_num : R/W; bitpos: [7:6]; default: 0;
* the input signals are delayed by SPI module clock cycles, 0: delayed by 1 cycle, 1:
* delayed by 2 cycles,... Can be configured in CONF state.
*/
uint32_t din3_num:2;
/** din4_num : R/W; bitpos: [9:8]; default: 0;
* the input signals are delayed by SPI module clock cycles, 0: delayed by 1 cycle, 1:
* delayed by 2 cycles,... Can be configured in CONF state.
*/
uint32_t din4_num:2; //this field is only for GPSPI2
/** din5_num : R/W; bitpos: [11:10]; default: 0;
* the input signals are delayed by SPI module clock cycles, 0: delayed by 1 cycle, 1:
* delayed by 2 cycles,... Can be configured in CONF state.
*/
uint32_t din5_num:2; //this field is only for GPSPI2
/** din6_num : R/W; bitpos: [13:12]; default: 0;
* the input signals are delayed by SPI module clock cycles, 0: delayed by 1 cycle, 1:
* delayed by 2 cycles,... Can be configured in CONF state.
*/
uint32_t din6_num:2; //this field is only for GPSPI2
/** din7_num : R/W; bitpos: [15:14]; default: 0;
* the input signals are delayed by SPI module clock cycles, 0: delayed by 1 cycle, 1:
* delayed by 2 cycles,... Can be configured in CONF state.
*/
uint32_t din7_num:2; //this field is only for GPSPI2
uint32_t reserved_16:16;
};
uint32_t val;
} spi_din_num_reg_t;
/** Type of dout_mode register
* SPI output delay mode configuration
*/
typedef union {
struct {
/** dout0_mode : R/W; bitpos: [0]; default: 0;
* The output signal $n is delayed by the SPI module clock, 0: output without delayed,
* 1: output delay for a SPI module clock cycle at its negative edge. Can be
* configured in CONF state.
*/
uint32_t dout0_mode:1;
/** dout1_mode : R/W; bitpos: [1]; default: 0;
* The output signal $n is delayed by the SPI module clock, 0: output without delayed,
* 1: output delay for a SPI module clock cycle at its negative edge. Can be
* configured in CONF state.
*/
uint32_t dout1_mode:1;
/** dout2_mode : R/W; bitpos: [2]; default: 0;
* The output signal $n is delayed by the SPI module clock, 0: output without delayed,
* 1: output delay for a SPI module clock cycle at its negative edge. Can be
* configured in CONF state.
*/
uint32_t dout2_mode:1;
/** dout3_mode : R/W; bitpos: [3]; default: 0;
* The output signal $n is delayed by the SPI module clock, 0: output without delayed,
* 1: output delay for a SPI module clock cycle at its negative edge. Can be
* configured in CONF state.
*/
uint32_t dout3_mode:1;
/** dout4_mode : R/W; bitpos: [4]; default: 0;
* The output signal $n is delayed by the SPI module clock, 0: output without delayed,
* 1: output delay for a SPI module clock cycle at its negative edge. Can be
* configured in CONF state.
*/
uint32_t dout4_mode:1; //this field is only for GPSPI2
/** dout5_mode : R/W; bitpos: [5]; default: 0;
* The output signal $n is delayed by the SPI module clock, 0: output without delayed,
* 1: output delay for a SPI module clock cycle at its negative edge. Can be
* configured in CONF state.
*/
uint32_t dout5_mode:1; //this field is only for GPSPI2
/** dout6_mode : R/W; bitpos: [6]; default: 0;
* The output signal $n is delayed by the SPI module clock, 0: output without delayed,
* 1: output delay for a SPI module clock cycle at its negative edge. Can be
* configured in CONF state.
*/
uint32_t dout6_mode:1; //this field is only for GPSPI2
/** dout7_mode : R/W; bitpos: [7]; default: 0;
* The output signal $n is delayed by the SPI module clock, 0: output without delayed,
* 1: output delay for a SPI module clock cycle at its negative edge. Can be
* configured in CONF state.
*/
uint32_t dout7_mode:1; //this field is only for GPSPI2
/** d_dqs_mode : R/W; bitpos: [8]; default: 0;
* The output signal SPI_DQS is delayed by the SPI module clock, 0: output without
* delayed, 1: output delay for a SPI module clock cycle at its negative edge. Can be
* configured in CONF state.
*/
uint32_t d_dqs_mode:1; //this field is only for GPSPI2
uint32_t reserved_9:23;
};
uint32_t val;
} spi_dout_mode_reg_t;
/** Group: Interrupt registers */
/** Type of dma_int_ena register
* SPI interrupt enable register
*/
typedef union {
struct {
/** dma_infifo_full_err_int_ena : R/W; bitpos: [0]; default: 0;
* The enable bit for SPI_DMA_INFIFO_FULL_ERR_INT interrupt.
*/
uint32_t dma_infifo_full_err_int_ena:1;
/** dma_outfifo_empty_err_int_ena : R/W; bitpos: [1]; default: 0;
* The enable bit for SPI_DMA_OUTFIFO_EMPTY_ERR_INT interrupt.
*/
uint32_t dma_outfifo_empty_err_int_ena:1;
/** slv_ex_qpi_int_ena : R/W; bitpos: [2]; default: 0;
* The enable bit for SPI slave Ex_QPI interrupt.
*/
uint32_t slv_ex_qpi_int_ena:1;
/** slv_en_qpi_int_ena : R/W; bitpos: [3]; default: 0;
* The enable bit for SPI slave En_QPI interrupt.
*/
uint32_t slv_en_qpi_int_ena:1;
/** slv_cmd7_int_ena : R/W; bitpos: [4]; default: 0;
* The enable bit for SPI slave CMD7 interrupt.
*/
uint32_t slv_cmd7_int_ena:1;
/** slv_cmd8_int_ena : R/W; bitpos: [5]; default: 0;
* The enable bit for SPI slave CMD8 interrupt.
*/
uint32_t slv_cmd8_int_ena:1;
/** slv_cmd9_int_ena : R/W; bitpos: [6]; default: 0;
* The enable bit for SPI slave CMD9 interrupt.
*/
uint32_t slv_cmd9_int_ena:1;
/** slv_cmda_int_ena : R/W; bitpos: [7]; default: 0;
* The enable bit for SPI slave CMDA interrupt.
*/
uint32_t slv_cmda_int_ena:1;
/** slv_rd_dma_done_int_ena : R/W; bitpos: [8]; default: 0;
* The enable bit for SPI_SLV_RD_DMA_DONE_INT interrupt.
*/
uint32_t slv_rd_dma_done_int_ena:1;
/** slv_wr_dma_done_int_ena : R/W; bitpos: [9]; default: 0;
* The enable bit for SPI_SLV_WR_DMA_DONE_INT interrupt.
*/
uint32_t slv_wr_dma_done_int_ena:1;
/** slv_rd_buf_done_int_ena : R/W; bitpos: [10]; default: 0;
* The enable bit for SPI_SLV_RD_BUF_DONE_INT interrupt.
*/
uint32_t slv_rd_buf_done_int_ena:1;
/** slv_wr_buf_done_int_ena : R/W; bitpos: [11]; default: 0;
* The enable bit for SPI_SLV_WR_BUF_DONE_INT interrupt.
*/
uint32_t slv_wr_buf_done_int_ena:1;
/** trans_done_int_ena : R/W; bitpos: [12]; default: 0;
* The enable bit for SPI_TRANS_DONE_INT interrupt.
*/
uint32_t trans_done_int_ena:1;
/** dma_seg_trans_done_int_ena : R/W; bitpos: [13]; default: 0;
* The enable bit for SPI_DMA_SEG_TRANS_DONE_INT interrupt.
*/
uint32_t dma_seg_trans_done_int_ena:1;
/** seg_magic_err_int_ena : R/W; bitpos: [14]; default: 0;
* The enable bit for SPI_SEG_MAGIC_ERR_INT interrupt.
*/
uint32_t seg_magic_err_int_ena:1; //this field is only for GPSPI2
/** slv_buf_addr_err_int_ena : R/W; bitpos: [15]; default: 0;
* The enable bit for SPI_SLV_BUF_ADDR_ERR_INT interrupt.
*/
uint32_t slv_buf_addr_err_int_ena:1;
/** slv_cmd_err_int_ena : R/W; bitpos: [16]; default: 0;
* The enable bit for SPI_SLV_CMD_ERR_INT interrupt.
*/
uint32_t slv_cmd_err_int_ena:1;
/** mst_rx_afifo_wfull_err_int_ena : R/W; bitpos: [17]; default: 0;
* The enable bit for SPI_MST_RX_AFIFO_WFULL_ERR_INT interrupt.
*/
uint32_t mst_rx_afifo_wfull_err_int_ena:1;
/** mst_tx_afifo_rempty_err_int_ena : R/W; bitpos: [18]; default: 0;
* The enable bit for SPI_MST_TX_AFIFO_REMPTY_ERR_INT interrupt.
*/
uint32_t mst_tx_afifo_rempty_err_int_ena:1;
/** app2_int_ena : R/W; bitpos: [19]; default: 0;
* The enable bit for SPI_APP2_INT interrupt.
*/
uint32_t app2_int_ena:1;
/** app1_int_ena : R/W; bitpos: [20]; default: 0;
* The enable bit for SPI_APP1_INT interrupt.
*/
uint32_t app1_int_ena:1;
uint32_t reserved_21:11;
};
uint32_t val;
} spi_dma_int_ena_reg_t;
/** Type of dma_int_clr register
* SPI interrupt clear register
*/
typedef union {
struct {
/** dma_infifo_full_err_int_clr : WT; bitpos: [0]; default: 0;
* The clear bit for SPI_DMA_INFIFO_FULL_ERR_INT interrupt.
*/
uint32_t dma_infifo_full_err_int_clr:1;
/** dma_outfifo_empty_err_int_clr : WT; bitpos: [1]; default: 0;
* The clear bit for SPI_DMA_OUTFIFO_EMPTY_ERR_INT interrupt.
*/
uint32_t dma_outfifo_empty_err_int_clr:1;
/** slv_ex_qpi_int_clr : WT; bitpos: [2]; default: 0;
* The clear bit for SPI slave Ex_QPI interrupt.
*/
uint32_t slv_ex_qpi_int_clr:1;
/** slv_en_qpi_int_clr : WT; bitpos: [3]; default: 0;
* The clear bit for SPI slave En_QPI interrupt.
*/
uint32_t slv_en_qpi_int_clr:1;
/** slv_cmd7_int_clr : WT; bitpos: [4]; default: 0;
* The clear bit for SPI slave CMD7 interrupt.
*/
uint32_t slv_cmd7_int_clr:1;
/** slv_cmd8_int_clr : WT; bitpos: [5]; default: 0;
* The clear bit for SPI slave CMD8 interrupt.
*/
uint32_t slv_cmd8_int_clr:1;
/** slv_cmd9_int_clr : WT; bitpos: [6]; default: 0;
* The clear bit for SPI slave CMD9 interrupt.
*/
uint32_t slv_cmd9_int_clr:1;
/** slv_cmda_int_clr : WT; bitpos: [7]; default: 0;
* The clear bit for SPI slave CMDA interrupt.
*/
uint32_t slv_cmda_int_clr:1;
/** slv_rd_dma_done_int_clr : WT; bitpos: [8]; default: 0;
* The clear bit for SPI_SLV_RD_DMA_DONE_INT interrupt.
*/
uint32_t slv_rd_dma_done_int_clr:1;
/** slv_wr_dma_done_int_clr : WT; bitpos: [9]; default: 0;
* The clear bit for SPI_SLV_WR_DMA_DONE_INT interrupt.
*/
uint32_t slv_wr_dma_done_int_clr:1;
/** slv_rd_buf_done_int_clr : WT; bitpos: [10]; default: 0;
* The clear bit for SPI_SLV_RD_BUF_DONE_INT interrupt.
*/
uint32_t slv_rd_buf_done_int_clr:1;
/** slv_wr_buf_done_int_clr : WT; bitpos: [11]; default: 0;
* The clear bit for SPI_SLV_WR_BUF_DONE_INT interrupt.
*/
uint32_t slv_wr_buf_done_int_clr:1;
/** trans_done_int_clr : WT; bitpos: [12]; default: 0;
* The clear bit for SPI_TRANS_DONE_INT interrupt.
*/
uint32_t trans_done_int_clr:1;
/** dma_seg_trans_done_int_clr : WT; bitpos: [13]; default: 0;
* The clear bit for SPI_DMA_SEG_TRANS_DONE_INT interrupt.
*/
uint32_t dma_seg_trans_done_int_clr:1;
/** seg_magic_err_int_clr : WT; bitpos: [14]; default: 0;
* The clear bit for SPI_SEG_MAGIC_ERR_INT interrupt.
*/
uint32_t seg_magic_err_int_clr:1; //this field is only for GPSPI2
/** slv_buf_addr_err_int_clr : WT; bitpos: [15]; default: 0;
* The clear bit for SPI_SLV_BUF_ADDR_ERR_INT interrupt.
*/
uint32_t slv_buf_addr_err_int_clr:1;
/** slv_cmd_err_int_clr : WT; bitpos: [16]; default: 0;
* The clear bit for SPI_SLV_CMD_ERR_INT interrupt.
*/
uint32_t slv_cmd_err_int_clr:1;
/** mst_rx_afifo_wfull_err_int_clr : WT; bitpos: [17]; default: 0;
* The clear bit for SPI_MST_RX_AFIFO_WFULL_ERR_INT interrupt.
*/
uint32_t mst_rx_afifo_wfull_err_int_clr:1;
/** mst_tx_afifo_rempty_err_int_clr : WT; bitpos: [18]; default: 0;
* The clear bit for SPI_MST_TX_AFIFO_REMPTY_ERR_INT interrupt.
*/
uint32_t mst_tx_afifo_rempty_err_int_clr:1;
/** app2_int_clr : WT; bitpos: [19]; default: 0;
* The clear bit for SPI_APP2_INT interrupt.
*/
uint32_t app2_int_clr:1;
/** app1_int_clr : WT; bitpos: [20]; default: 0;
* The clear bit for SPI_APP1_INT interrupt.
*/
uint32_t app1_int_clr:1;
uint32_t reserved_21:11;
};
uint32_t val;
} spi_dma_int_clr_reg_t;
/** Type of dma_int_raw register
* SPI interrupt raw register
*/
typedef union {
struct {
/** dma_infifo_full_err_int_raw : R/WTC/SS; bitpos: [0]; default: 0;
* 1: The current data rate of DMA Rx is smaller than that of SPI, which will lose the
* receive data. 0: Others.
*/
uint32_t dma_infifo_full_err_int_raw:1;
/** dma_outfifo_empty_err_int_raw : R/WTC/SS; bitpos: [1]; default: 0;
* 1: The current data rate of DMA TX is smaller than that of SPI. SPI will stop in
* master mode and send out all 0 in slave mode. 0: Others.
*/
uint32_t dma_outfifo_empty_err_int_raw:1;
/** slv_ex_qpi_int_raw : R/WTC/SS; bitpos: [2]; default: 0;
* The raw bit for SPI slave Ex_QPI interrupt. 1: SPI slave mode Ex_QPI transmission
* is ended. 0: Others.
*/
uint32_t slv_ex_qpi_int_raw:1;
/** slv_en_qpi_int_raw : R/WTC/SS; bitpos: [3]; default: 0;
* The raw bit for SPI slave En_QPI interrupt. 1: SPI slave mode En_QPI transmission
* is ended. 0: Others.
*/
uint32_t slv_en_qpi_int_raw:1;
/** slv_cmd7_int_raw : R/WTC/SS; bitpos: [4]; default: 0;
* The raw bit for SPI slave CMD7 interrupt. 1: SPI slave mode CMD7 transmission is
* ended. 0: Others.
*/
uint32_t slv_cmd7_int_raw:1;
/** slv_cmd8_int_raw : R/WTC/SS; bitpos: [5]; default: 0;
* The raw bit for SPI slave CMD8 interrupt. 1: SPI slave mode CMD8 transmission is
* ended. 0: Others.
*/
uint32_t slv_cmd8_int_raw:1;
/** slv_cmd9_int_raw : R/WTC/SS; bitpos: [6]; default: 0;
* The raw bit for SPI slave CMD9 interrupt. 1: SPI slave mode CMD9 transmission is
* ended. 0: Others.
*/
uint32_t slv_cmd9_int_raw:1;
/** slv_cmda_int_raw : R/WTC/SS; bitpos: [7]; default: 0;
* The raw bit for SPI slave CMDA interrupt. 1: SPI slave mode CMDA transmission is
* ended. 0: Others.
*/
uint32_t slv_cmda_int_raw:1;
/** slv_rd_dma_done_int_raw : R/WTC/SS; bitpos: [8]; default: 0;
* The raw bit for SPI_SLV_RD_DMA_DONE_INT interrupt. 1: SPI slave mode Rd_DMA
* transmission is ended. 0: Others.
*/
uint32_t slv_rd_dma_done_int_raw:1;
/** slv_wr_dma_done_int_raw : R/WTC/SS; bitpos: [9]; default: 0;
* The raw bit for SPI_SLV_WR_DMA_DONE_INT interrupt. 1: SPI slave mode Wr_DMA
* transmission is ended. 0: Others.
*/
uint32_t slv_wr_dma_done_int_raw:1;
/** slv_rd_buf_done_int_raw : R/WTC/SS; bitpos: [10]; default: 0;
* The raw bit for SPI_SLV_RD_BUF_DONE_INT interrupt. 1: SPI slave mode Rd_BUF
* transmission is ended. 0: Others.
*/
uint32_t slv_rd_buf_done_int_raw:1;
/** slv_wr_buf_done_int_raw : R/WTC/SS; bitpos: [11]; default: 0;
* The raw bit for SPI_SLV_WR_BUF_DONE_INT interrupt. 1: SPI slave mode Wr_BUF
* transmission is ended. 0: Others.
*/
uint32_t slv_wr_buf_done_int_raw:1;
/** trans_done_int_raw : R/WTC/SS; bitpos: [12]; default: 0;
* The raw bit for SPI_TRANS_DONE_INT interrupt. 1: SPI master mode transmission is
* ended. 0: others.
*/
uint32_t trans_done_int_raw:1;
/** dma_seg_trans_done_int_raw : R/WTC/SS; bitpos: [13]; default: 0;
* The raw bit for SPI_DMA_SEG_TRANS_DONE_INT interrupt. 1: spi master DMA
* full-duplex/half-duplex seg-conf-trans ends or slave half-duplex seg-trans ends.
* And data has been pushed to corresponding memory. 0: seg-conf-trans or seg-trans
* is not ended or not occurred.
*/
uint32_t dma_seg_trans_done_int_raw:1;
/** seg_magic_err_int_raw : R/WTC/SS; bitpos: [14]; default: 0;
* The raw bit for SPI_SEG_MAGIC_ERR_INT interrupt. 1: The magic value in CONF buffer
* is error in the DMA seg-conf-trans. 0: others.
*/
uint32_t seg_magic_err_int_raw:1; //this field is only for GPSPI2
/** slv_buf_addr_err_int_raw : R/WTC/SS; bitpos: [15]; default: 0;
* The raw bit for SPI_SLV_BUF_ADDR_ERR_INT interrupt. 1: The accessing data address
* of the current SPI slave mode CPU controlled FD, Wr_BUF or Rd_BUF transmission is
* bigger than 63. 0: Others.
*/
uint32_t slv_buf_addr_err_int_raw:1;
/** slv_cmd_err_int_raw : R/WTC/SS; bitpos: [16]; default: 0;
* The raw bit for SPI_SLV_CMD_ERR_INT interrupt. 1: The slave command value in the
* current SPI slave HD mode transmission is not supported. 0: Others.
*/
uint32_t slv_cmd_err_int_raw:1;
/** mst_rx_afifo_wfull_err_int_raw : R/WTC/SS; bitpos: [17]; default: 0;
* The raw bit for SPI_MST_RX_AFIFO_WFULL_ERR_INT interrupt. 1: There is a RX AFIFO
* write-full error when SPI inputs data in master mode. 0: Others.
*/
uint32_t mst_rx_afifo_wfull_err_int_raw:1;
/** mst_tx_afifo_rempty_err_int_raw : R/WTC/SS; bitpos: [18]; default: 0;
* The raw bit for SPI_MST_TX_AFIFO_REMPTY_ERR_INT interrupt. 1: There is a TX BUF
* AFIFO read-empty error when SPI outputs data in master mode. 0: Others.
*/
uint32_t mst_tx_afifo_rempty_err_int_raw:1;
/** app2_int_raw : R/WTC/SS; bitpos: [19]; default: 0;
* The raw bit for SPI_APP2_INT interrupt. The value is only controlled by software.
*/
uint32_t app2_int_raw:1;
/** app1_int_raw : R/WTC/SS; bitpos: [20]; default: 0;
* The raw bit for SPI_APP1_INT interrupt. The value is only controlled by software.
*/
uint32_t app1_int_raw:1;
uint32_t reserved_21:11;
};
uint32_t val;
} spi_dma_int_raw_reg_t;
/** Type of dma_int_st register
* SPI interrupt status register
*/
typedef union {
struct {
/** dma_infifo_full_err_int_st : RO; bitpos: [0]; default: 0;
* The status bit for SPI_DMA_INFIFO_FULL_ERR_INT interrupt.
*/
uint32_t dma_infifo_full_err_int_st:1;
/** dma_outfifo_empty_err_int_st : RO; bitpos: [1]; default: 0;
* The status bit for SPI_DMA_OUTFIFO_EMPTY_ERR_INT interrupt.
*/
uint32_t dma_outfifo_empty_err_int_st:1;
/** slv_ex_qpi_int_st : RO; bitpos: [2]; default: 0;
* The status bit for SPI slave Ex_QPI interrupt.
*/
uint32_t slv_ex_qpi_int_st:1;
/** slv_en_qpi_int_st : RO; bitpos: [3]; default: 0;
* The status bit for SPI slave En_QPI interrupt.
*/
uint32_t slv_en_qpi_int_st:1;
/** slv_cmd7_int_st : RO; bitpos: [4]; default: 0;
* The status bit for SPI slave CMD7 interrupt.
*/
uint32_t slv_cmd7_int_st:1;
/** slv_cmd8_int_st : RO; bitpos: [5]; default: 0;
* The status bit for SPI slave CMD8 interrupt.
*/
uint32_t slv_cmd8_int_st:1;
/** slv_cmd9_int_st : RO; bitpos: [6]; default: 0;
* The status bit for SPI slave CMD9 interrupt.
*/
uint32_t slv_cmd9_int_st:1;
/** slv_cmda_int_st : RO; bitpos: [7]; default: 0;
* The status bit for SPI slave CMDA interrupt.
*/
uint32_t slv_cmda_int_st:1;
/** slv_rd_dma_done_int_st : RO; bitpos: [8]; default: 0;
* The status bit for SPI_SLV_RD_DMA_DONE_INT interrupt.
*/
uint32_t slv_rd_dma_done_int_st:1;
/** slv_wr_dma_done_int_st : RO; bitpos: [9]; default: 0;
* The status bit for SPI_SLV_WR_DMA_DONE_INT interrupt.
*/
uint32_t slv_wr_dma_done_int_st:1;
/** slv_rd_buf_done_int_st : RO; bitpos: [10]; default: 0;
* The status bit for SPI_SLV_RD_BUF_DONE_INT interrupt.
*/
uint32_t slv_rd_buf_done_int_st:1;
/** slv_wr_buf_done_int_st : RO; bitpos: [11]; default: 0;
* The status bit for SPI_SLV_WR_BUF_DONE_INT interrupt.
*/
uint32_t slv_wr_buf_done_int_st:1;
/** trans_done_int_st : RO; bitpos: [12]; default: 0;
* The status bit for SPI_TRANS_DONE_INT interrupt.
*/
uint32_t trans_done_int_st:1;
/** dma_seg_trans_done_int_st : RO; bitpos: [13]; default: 0;
* The status bit for SPI_DMA_SEG_TRANS_DONE_INT interrupt.
*/
uint32_t dma_seg_trans_done_int_st:1;
/** seg_magic_err_int_st : RO; bitpos: [14]; default: 0;
* The status bit for SPI_SEG_MAGIC_ERR_INT interrupt.
*/
uint32_t seg_magic_err_int_st:1; //this field is only for GPSPI2
/** slv_buf_addr_err_int_st : RO; bitpos: [15]; default: 0;
* The status bit for SPI_SLV_BUF_ADDR_ERR_INT interrupt.
*/
uint32_t slv_buf_addr_err_int_st:1;
/** slv_cmd_err_int_st : RO; bitpos: [16]; default: 0;
* The status bit for SPI_SLV_CMD_ERR_INT interrupt.
*/
uint32_t slv_cmd_err_int_st:1;
/** mst_rx_afifo_wfull_err_int_st : RO; bitpos: [17]; default: 0;
* The status bit for SPI_MST_RX_AFIFO_WFULL_ERR_INT interrupt.
*/
uint32_t mst_rx_afifo_wfull_err_int_st:1;
/** mst_tx_afifo_rempty_err_int_st : RO; bitpos: [18]; default: 0;
* The status bit for SPI_MST_TX_AFIFO_REMPTY_ERR_INT interrupt.
*/
uint32_t mst_tx_afifo_rempty_err_int_st:1;
/** app2_int_st : RO; bitpos: [19]; default: 0;
* The status bit for SPI_APP2_INT interrupt.
*/
uint32_t app2_int_st:1;
/** app1_int_st : RO; bitpos: [20]; default: 0;
* The status bit for SPI_APP1_INT interrupt.
*/
uint32_t app1_int_st:1;
uint32_t reserved_21:11;
};
uint32_t val;
} spi_dma_int_st_reg_t;
/** Type of dma_int_set register
* SPI interrupt software set register
*/
typedef union {
struct {
/** dma_infifo_full_err_int_set : WT; bitpos: [0]; default: 0;
* The software set bit for SPI_DMA_INFIFO_FULL_ERR_INT interrupt.
*/
uint32_t dma_infifo_full_err_int_set:1;
/** dma_outfifo_empty_err_int_set : WT; bitpos: [1]; default: 0;
* The software set bit for SPI_DMA_OUTFIFO_EMPTY_ERR_INT interrupt.
*/
uint32_t dma_outfifo_empty_err_int_set:1;
/** slv_ex_qpi_int_set : WT; bitpos: [2]; default: 0;
* The software set bit for SPI slave Ex_QPI interrupt.
*/
uint32_t slv_ex_qpi_int_set:1;
/** slv_en_qpi_int_set : WT; bitpos: [3]; default: 0;
* The software set bit for SPI slave En_QPI interrupt.
*/
uint32_t slv_en_qpi_int_set:1;
/** slv_cmd7_int_set : WT; bitpos: [4]; default: 0;
* The software set bit for SPI slave CMD7 interrupt.
*/
uint32_t slv_cmd7_int_set:1;
/** slv_cmd8_int_set : WT; bitpos: [5]; default: 0;
* The software set bit for SPI slave CMD8 interrupt.
*/
uint32_t slv_cmd8_int_set:1;
/** slv_cmd9_int_set : WT; bitpos: [6]; default: 0;
* The software set bit for SPI slave CMD9 interrupt.
*/
uint32_t slv_cmd9_int_set:1;
/** slv_cmda_int_set : WT; bitpos: [7]; default: 0;
* The software set bit for SPI slave CMDA interrupt.
*/
uint32_t slv_cmda_int_set:1;
/** slv_rd_dma_done_int_set : WT; bitpos: [8]; default: 0;
* The software set bit for SPI_SLV_RD_DMA_DONE_INT interrupt.
*/
uint32_t slv_rd_dma_done_int_set:1;
/** slv_wr_dma_done_int_set : WT; bitpos: [9]; default: 0;
* The software set bit for SPI_SLV_WR_DMA_DONE_INT interrupt.
*/
uint32_t slv_wr_dma_done_int_set:1;
/** slv_rd_buf_done_int_set : WT; bitpos: [10]; default: 0;
* The software set bit for SPI_SLV_RD_BUF_DONE_INT interrupt.
*/
uint32_t slv_rd_buf_done_int_set:1;
/** slv_wr_buf_done_int_set : WT; bitpos: [11]; default: 0;
* The software set bit for SPI_SLV_WR_BUF_DONE_INT interrupt.
*/
uint32_t slv_wr_buf_done_int_set:1;
/** trans_done_int_set : WT; bitpos: [12]; default: 0;
* The software set bit for SPI_TRANS_DONE_INT interrupt.
*/
uint32_t trans_done_int_set:1;
/** dma_seg_trans_done_int_set : WT; bitpos: [13]; default: 0;
* The software set bit for SPI_DMA_SEG_TRANS_DONE_INT interrupt.
*/
uint32_t dma_seg_trans_done_int_set:1;
/** seg_magic_err_int_set : WT; bitpos: [14]; default: 0;
* The software set bit for SPI_SEG_MAGIC_ERR_INT interrupt.
*/
uint32_t seg_magic_err_int_set:1; //this field is only for GPSPI2
/** slv_buf_addr_err_int_set : WT; bitpos: [15]; default: 0;
* The software set bit for SPI_SLV_BUF_ADDR_ERR_INT interrupt.
*/
uint32_t slv_buf_addr_err_int_set:1;
/** slv_cmd_err_int_set : WT; bitpos: [16]; default: 0;
* The software set bit for SPI_SLV_CMD_ERR_INT interrupt.
*/
uint32_t slv_cmd_err_int_set:1;
/** mst_rx_afifo_wfull_err_int_set : WT; bitpos: [17]; default: 0;
* The software set bit for SPI_MST_RX_AFIFO_WFULL_ERR_INT interrupt.
*/
uint32_t mst_rx_afifo_wfull_err_int_set:1;
/** mst_tx_afifo_rempty_err_int_set : WT; bitpos: [18]; default: 0;
* The software set bit for SPI_MST_TX_AFIFO_REMPTY_ERR_INT interrupt.
*/
uint32_t mst_tx_afifo_rempty_err_int_set:1;
/** app2_int_set : WT; bitpos: [19]; default: 0;
* The software set bit for SPI_APP2_INT interrupt.
*/
uint32_t app2_int_set:1;
/** app1_int_set : WT; bitpos: [20]; default: 0;
* The software set bit for SPI_APP1_INT interrupt.
*/
uint32_t app1_int_set:1;
uint32_t reserved_21:11;
};
uint32_t val;
} spi_dma_int_set_reg_t;
/** Type of wn register
* SPI CPU-controlled buffer
*/
typedef union {
struct {
/** buf15 : R/W/SS; bitpos: [31:0]; default: 0;
* data buffer
*/
uint32_t buf:32;
};
uint32_t val;
} spi_wn_reg_t;
/** Group: Version register */
/** Type of date register
* Version control
*/
typedef union {
struct {
/** date : R/W; bitpos: [27:0]; default: 35680770;
* SPI register version.
*/
uint32_t date:28;
uint32_t reserved_28:4;
};
uint32_t val;
} spi_date_reg_t;
typedef struct {
volatile spi_cmd_reg_t cmd;
volatile spi_addr_reg_t addr;
volatile spi_ctrl_reg_t ctrl;
volatile spi_clock_reg_t clock;
volatile spi_user_reg_t user;
volatile spi_user1_reg_t user1;
volatile spi_user2_reg_t user2;
volatile spi_ms_dlen_reg_t ms_dlen;
volatile spi_misc_reg_t misc;
volatile spi_din_mode_reg_t din_mode;
volatile spi_din_num_reg_t din_num;
volatile spi_dout_mode_reg_t dout_mode;
volatile spi_dma_conf_reg_t dma_conf;
volatile spi_dma_int_ena_reg_t dma_int_ena;
volatile spi_dma_int_clr_reg_t dma_int_clr;
volatile spi_dma_int_raw_reg_t dma_int_raw;
volatile spi_dma_int_st_reg_t dma_int_st;
volatile spi_dma_int_set_reg_t dma_int_set;
uint32_t reserved_048[20];
volatile spi_wn_reg_t data_buf[16];
uint32_t reserved_0d8[2];
volatile spi_slave_reg_t slave;
volatile spi_slave1_reg_t slave1;
volatile spi_clk_gate_reg_t clk_gate;
uint32_t reserved_0ec;
volatile spi_date_reg_t date;
} spi_dev_t;
extern spi_dev_t GPSPI2;
extern spi_dev_t GPSPI3;
#ifndef __cplusplus
_Static_assert(sizeof(spi_dev_t) == 0xf4, "Invalid size of spi_dev_t structure");
#endif
#ifdef __cplusplus
}
#endif
| 2.171875 | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.