hexsha stringlengths 40 40 | size int64 5 1.05M | ext stringclasses 588
values | lang stringclasses 305
values | max_stars_repo_path stringlengths 3 363 | max_stars_repo_name stringlengths 5 118 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 10 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringdate 2015-01-01 00:00:35 2022-03-31 23:43:49 ⌀ | max_stars_repo_stars_event_max_datetime stringdate 2015-01-01 12:37:38 2022-03-31 23:59:52 ⌀ | max_issues_repo_path stringlengths 3 363 | max_issues_repo_name stringlengths 5 118 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 10 | max_issues_count float64 1 134k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 363 | max_forks_repo_name stringlengths 5 135 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 10 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringdate 2015-01-01 00:01:02 2022-03-31 23:27:27 ⌀ | max_forks_repo_forks_event_max_datetime stringdate 2015-01-03 08:55:07 2022-03-31 23:59:24 ⌀ | content stringlengths 5 1.05M | avg_line_length float64 1.13 1.04M | max_line_length int64 1 1.05M | alphanum_fraction float64 0 1 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
d41f1bddf93852f64865c7b032f2d411073295d7 | 95 | c | C | src/math/wasm/rintf.c | celifan/musl | f0e0a4e1ffc818ecf7e2062dae7fa0f6d7b3f407 | [
"MIT"
] | 5 | 2019-01-27T21:07:14.000Z | 2019-04-06T02:49:53.000Z | src/math/wasm/rintf.c | celifan/musl | f0e0a4e1ffc818ecf7e2062dae7fa0f6d7b3f407 | [
"MIT"
] | 2 | 2017-12-08T11:21:17.000Z | 2018-04-25T01:35:56.000Z | src/math/wasm/rintf.c | celifan/musl | f0e0a4e1ffc818ecf7e2062dae7fa0f6d7b3f407 | [
"MIT"
] | 2 | 2017-12-08T00:09:47.000Z | 2019-06-24T10:52:16.000Z | #include <math.h>
__attribute__((const)) float rintf(float x)
{
return __builtin_rintf(x);
}
| 13.571429 | 43 | 0.715789 |
1664ae94203548c69269c0495eae1097956d8948 | 347 | h | C | snake/Scene.h | xingrobin/CrazySnake | 2cc1519312e9ddd86684a51fdd3074a7ac99cfc9 | [
"Unlicense"
] | null | null | null | snake/Scene.h | xingrobin/CrazySnake | 2cc1519312e9ddd86684a51fdd3074a7ac99cfc9 | [
"Unlicense"
] | null | null | null | snake/Scene.h | xingrobin/CrazySnake | 2cc1519312e9ddd86684a51fdd3074a7ac99cfc9 | [
"Unlicense"
] | null | null | null | #ifndef SCENE_H
#define SCENE_H
#include "graphics.h"
#include "snake.h"
#include <string>
class Scene{
public:
Scene();
~Scene();
void init();
void start();
private:
void setDirectionByKeyMsg();
void reset();
void failed();
bool hasFailed;
bool hasHitKey;
int speed;
int score;
int maxscore;
Snake snake;
Apple aApple;
};
#endif
| 12.392857 | 29 | 0.691643 |
75a5f1868dd07f3636ea676f1919fa8d179ea748 | 37,943 | c | C | ocaml-4.12.0-runtime/runtime/major_gc.c | drjdn/ocaml_c_pkg | 50db2e4fdc7796cdec20ce1d4f9ca54944631c10 | [
"Unlicense"
] | null | null | null | ocaml-4.12.0-runtime/runtime/major_gc.c | drjdn/ocaml_c_pkg | 50db2e4fdc7796cdec20ce1d4f9ca54944631c10 | [
"Unlicense"
] | null | null | null | ocaml-4.12.0-runtime/runtime/major_gc.c | drjdn/ocaml_c_pkg | 50db2e4fdc7796cdec20ce1d4f9ca54944631c10 | [
"Unlicense"
] | null | null | null | /**************************************************************************/
/* */
/* OCaml */
/* */
/* Damien Doligez, projet Para, INRIA Rocquencourt */
/* */
/* Copyright 1996 Institut National de Recherche en Informatique et */
/* en Automatique. */
/* */
/* All rights reserved. This file is distributed under the terms of */
/* the GNU Lesser General Public License version 2.1, with the */
/* special exception on linking described in the file LICENSE. */
/* */
/**************************************************************************/
#define CAML_INTERNALS
#include <limits.h>
#include <math.h>
#include "caml/compact.h"
#include "caml/custom.h"
#include "caml/config.h"
#include "caml/fail.h"
#include "caml/finalise.h"
#include "caml/freelist.h"
#include "caml/gc.h"
#include "caml/gc_ctrl.h"
#include "caml/major_gc.h"
#include "caml/misc.h"
#include "caml/mlvalues.h"
#include "caml/roots.h"
#include "caml/skiplist.h"
#include "caml/signals.h"
#include "caml/weak.h"
#include "caml/memprof.h"
#include "caml/eventlog.h"
#ifdef _MSC_VER
Caml_inline double fmin(double a, double b) {
return (a < b) ? a : b;
}
#endif
#define MARK_STACK_INIT_SIZE 2048
typedef struct {
value block;
uintnat offset;
} mark_entry;
struct mark_stack {
mark_entry* stack;
uintnat count;
uintnat size;
};
uintnat caml_percent_free;
uintnat caml_major_heap_increment;
CAMLexport char *caml_heap_start;
char *caml_gc_sweep_hp;
int caml_gc_phase; /* always Phase_mark, Pase_clean,
Phase_sweep, or Phase_idle */
uintnat caml_allocated_words;
uintnat caml_dependent_size, caml_dependent_allocated;
double caml_extra_heap_resources;
uintnat caml_fl_wsz_at_phase_change = 0;
extern value caml_fl_merge; /* Defined in freelist.c. */
/* redarken_first_chunk is the first chunk needing redarkening, if NULL no
redarkening required */
static char *redarken_first_chunk = NULL;
static char *sweep_chunk, *sweep_limit;
static double p_backlog = 0.0; /* backlog for the gc speedup parameter */
int caml_gc_subphase; /* Subphase_{mark_roots,mark_main,mark_final} */
/**
Ephemerons:
During mark phase the list caml_ephe_list_head of ephemerons
is iterated by different pointers that follow the invariants:
caml_ephe_list_head ->* ephes_checked_if_pure ->* ephes_to_check ->* null
| | |
(1) (2) (3)
At the start of mark phase, (1) and (2) are empty.
In mark phase:
- the ephemerons in (1) have a data alive or none
(nb: new ephemerons are added in this part by weak.c)
- the ephemerons in (2) have at least a white key or are white
if ephe_list_pure is true, otherwise they are in an unknown state and
must be checked again.
- the ephemerons in (3) are in an unknown state and must be checked
At the end of mark phase, (3) is empty and ephe_list_pure is true.
The ephemeron in (1) and (2) will be cleaned (white keys and data
replaced by none or the ephemeron is removed from the list if it is white)
in clean phase.
In clean phase:
caml_ephe_list_head ->* ephes_to_check ->* null
| |
(1) (3)
In clean phase, (2) is not used, ephes_to_check is initialized at
caml_ephe_list_head:
- the ephemerons in (1) are clean.
- the ephemerons in (3) should be cleaned or removed if white.
*/
static int ephe_list_pure;
/** The ephemerons is pure if since the start of its iteration
no value have been darkened. */
static value *ephes_checked_if_pure;
static value *ephes_to_check;
int caml_major_window = 1;
double caml_major_ring[Max_major_window] = { 0. };
int caml_major_ring_index = 0;
double caml_major_work_credit = 0.0;
double caml_gc_clock = 0.0;
#ifdef DEBUG
static unsigned long major_gc_counter = 0;
#endif
void (*caml_major_gc_hook)(void) = NULL;
/* This function prunes the mark stack if it's about to overflow. It does so
by building a skiplist of major heap chunks and then iterating through the
mark stack and setting redarken_start/redarken_end on each chunk to indicate
the range that requires redarkening. */
static void mark_stack_prune (struct mark_stack* stk)
{
int entry;
uintnat mark_stack_count = stk->count;
mark_entry* mark_stack = stk->stack;
char* heap_chunk = caml_heap_start;
struct skiplist chunk_sklist = SKIPLIST_STATIC_INITIALIZER;
do {
caml_skiplist_insert(&chunk_sklist, (uintnat)heap_chunk,
(uintnat)(heap_chunk+Chunk_size(heap_chunk)));
heap_chunk = Chunk_next(heap_chunk);
} while( heap_chunk != NULL );
for( entry = 0; entry < mark_stack_count ; entry++ ) {
mark_entry me = mark_stack[entry];
value* block_op = Op_val(me.block);
uintnat chunk_addr = 0, chunk_addr_below = 0;
if( caml_skiplist_find_below(&chunk_sklist, (uintnat)me.block,
&chunk_addr, &chunk_addr_below)
&& me.block < chunk_addr_below ) {
if( Chunk_redarken_start(chunk_addr) > block_op ) {
Chunk_redarken_start(chunk_addr) = block_op;
}
if( Chunk_redarken_end(chunk_addr) < block_op ) {
Chunk_redarken_end(chunk_addr) = block_op;
}
if( redarken_first_chunk == NULL
|| redarken_first_chunk > (char*)chunk_addr ) {
redarken_first_chunk = (char*)chunk_addr;
}
}
}
caml_skiplist_empty(&chunk_sklist);
caml_gc_message(0x08, "Mark stack overflow.\n");
stk->count = 0;
}
static void realloc_mark_stack (struct mark_stack* stk)
{
mark_entry* new;
uintnat mark_stack_bsize = stk->size * sizeof(mark_entry);
if ( Wsize_bsize(mark_stack_bsize) < Caml_state->stat_heap_wsz / 64 ) {
caml_gc_message (0x08, "Growing mark stack to %"
ARCH_INTNAT_PRINTF_FORMAT "uk bytes\n",
(intnat) mark_stack_bsize * 2 / 1024);
new = (mark_entry*) caml_stat_resize_noexc ((char*) stk->stack,
2 * mark_stack_bsize);
if (new != NULL) {
stk->stack = new;
stk->size *= 2;
return;
}
}
caml_gc_message (0x08, "No room for growing mark stack. Pruning..\n");
mark_stack_prune(stk);
}
/* This function pushes the provided mark_entry [me] onto the current mark
stack [stk]. It first checks, if the block is small enough, whether there
are any fields we would actually do mark work on. If so then it enqueues
the entry. */
Caml_inline void mark_stack_push(struct mark_stack* stk, value block,
uintnat offset, intnat* work)
{
value v;
int i, block_wsz = Wosize_val(block), end;
mark_entry* me;
CAMLassert(Is_block(block) && Is_in_heap (block)
&& Is_black_val(block));
CAMLassert(Tag_val(block) != Infix_tag);
CAMLassert(Tag_val(block) < No_scan_tag);
#if defined(NO_NAKED_POINTERS) || defined(NAKED_POINTERS_CHECKER)
if (Tag_val(block) == Closure_tag) {
/* Skip the code pointers and integers at beginning of closure;
start scanning at the first word of the environment part. */
/* It might be the case that [mark_stack_push] has been called
while we are traversing a closure block but have not enough
budget to finish the block. In that specific case, we should not
update [m.offset] */
if (offset == 0)
offset = Start_env_closinfo(Closinfo_val(block));
CAMLassert(offset <= Wosize_val(block)
&& offset >= Start_env_closinfo(Closinfo_val(block)));
}
#endif
end = (block_wsz < 8 ? block_wsz : 8);
/* Optimisation to avoid pushing small, unmarkable objects such as [Some 42]
* into the mark stack. */
for (i = offset; i < end; i++) {
v = Field(block, i);
if (Is_block(v) && !Is_young(v))
/* found something to mark */
break;
}
if (i == block_wsz) {
/* nothing left to mark */
if( work != NULL ) {
/* we should take credit for it though */
*work -= Whsize_wosize(block_wsz - offset);
}
return;
}
if( work != NULL ) {
/* take credit for the work we skipped due to the optimisation.
we will take credit for the header later as part of marking. */
*work -= (i - offset);
}
offset = i;
if (stk->count == stk->size)
realloc_mark_stack(stk);
me = &stk->stack[stk->count++];
me->block = block;
me->offset = offset;
}
#if defined(NAKED_POINTERS_CHECKER) && defined(NATIVE_CODE)
static void is_naked_pointer_safe (value v, value *p);
#endif
void caml_darken (value v, value *p)
{
#ifdef NO_NAKED_POINTERS
if (Is_block(v) && !Is_young (v)) {
#else
if (Is_block(v) && Is_in_heap (v)) {
#endif
header_t h = Hd_val (v);
tag_t t = Tag_hd (h);
if (t == Infix_tag){
v -= Infix_offset_val(v);
h = Hd_val (v);
t = Tag_hd (h);
}
#ifdef NO_NAKED_POINTERS
/* We insist that naked pointers to outside the heap point to things that
look like values with headers coloured black. This is always
strictly necessary because the compactor relies on it. */
CAMLassert (Is_in_heap (v) || Is_black_hd (h));
#endif
CAMLassert (!Is_blue_hd (h));
if (Is_white_hd (h)){
ephe_list_pure = 0;
Hd_val (v) = Blackhd_hd (h);
if (t < No_scan_tag){
mark_stack_push(Caml_state->mark_stack, v, 0, NULL);
}
}
}
#if defined(NAKED_POINTERS_CHECKER) && defined(NATIVE_CODE)
else if (Is_block(v) && !Is_young(v)) {
is_naked_pointer_safe(v, p);
}
#endif
}
/* This function shrinks the mark stack back to the MARK_STACK_INIT_SIZE size
and is called at the end of a GC compaction to avoid a mark stack greater
than 1/32th of the heap. */
void caml_shrink_mark_stack () {
struct mark_stack* stk = Caml_state->mark_stack;
intnat init_stack_bsize = MARK_STACK_INIT_SIZE * sizeof(mark_entry);
mark_entry* shrunk_stack;
caml_gc_message (0x08, "Shrinking mark stack to %"
ARCH_INTNAT_PRINTF_FORMAT "uk bytes\n",
init_stack_bsize);
shrunk_stack = (mark_entry*) caml_stat_resize_noexc ((char*) stk->stack,
init_stack_bsize);
if (shrunk_stack != NULL) {
stk->stack = shrunk_stack;
stk->size = MARK_STACK_INIT_SIZE;
}else{
caml_gc_message (0x08, "Mark stack shrinking failed");
}
}
/* This function adds blocks in the passed heap chunk [heap_chunk] to
the mark stack. It returns 1 when the supplied chunk has no more
range to redarken. It returns 0 if there are still blocks in the
chunk that need redarkening because pushing them onto the stack
would make it grow more than a quarter full. This is to lower the
chance of triggering another overflow, which would be
wasteful. Subsequent calls will continue progress.
*/
static int redarken_chunk(char* heap_chunk, struct mark_stack* stk) {
value* p = Chunk_redarken_start(heap_chunk);
value* end = Chunk_redarken_end(heap_chunk);
while (p <= end) {
header_t hd = Hd_op(p);
if( Is_black_hd(hd) && Tag_hd(hd) < No_scan_tag ) {
if( stk->count < stk->size/4 ) {
mark_stack_push(stk, Val_op(p), 0, NULL);
} else {
/* Only fill up a quarter of the mark stack, we can resume later
for more if we need to */
Chunk_redarken_start(heap_chunk) = p;
return 0;
}
}
p += Whsize_hp(Hp_op(p));
}
Chunk_redarken_start(heap_chunk) =
(value*)(heap_chunk + Chunk_size(heap_chunk));
Chunk_redarken_end(heap_chunk) = 0;
return 1;
}
static void start_cycle (void)
{
CAMLassert (caml_gc_phase == Phase_idle);
CAMLassert (Caml_state->mark_stack->count == 0);
CAMLassert (redarken_first_chunk == NULL);
caml_gc_message (0x01, "Starting new major GC cycle\n");
caml_darken_all_roots_start ();
caml_gc_phase = Phase_mark;
caml_gc_subphase = Subphase_mark_roots;
ephe_list_pure = 1;
ephes_checked_if_pure = &caml_ephe_list_head;
ephes_to_check = &caml_ephe_list_head;
#ifdef DEBUG
++ major_gc_counter;
caml_heap_check ();
#endif
}
static void init_sweep_phase(void)
{
/* Phase_clean is done. */
/* Initialise the sweep phase. */
caml_gc_sweep_hp = caml_heap_start;
caml_fl_init_merge ();
caml_gc_phase = Phase_sweep;
sweep_chunk = caml_heap_start;
caml_gc_sweep_hp = sweep_chunk;
sweep_limit = sweep_chunk + Chunk_size (sweep_chunk);
caml_fl_wsz_at_phase_change = caml_fl_cur_wsz;
if (caml_major_gc_hook) (*caml_major_gc_hook)();
}
/* auxiliary function of mark_slice */
Caml_inline void mark_slice_darken(struct mark_stack* stk, value v, mlsize_t i,
int in_ephemeron, int *slice_pointers,
intnat *work)
{
value child;
header_t chd;
child = Field (v, i);
#ifdef NO_NAKED_POINTERS
if (Is_block (child) && ! Is_young (child)) {
#else
if (Is_block (child) && Is_in_heap (child)) {
#endif
CAML_EVENTLOG_DO (++ *slice_pointers);
chd = Hd_val (child);
if (Tag_hd (chd) == Forward_tag){
value f = Forward_val (child);
if ((in_ephemeron && Is_long(f)) ||
(Is_block (f)
&& (!Is_in_value_area(f) || Tag_val (f) == Forward_tag
|| Tag_val (f) == Lazy_tag
#ifdef FLAT_FLOAT_ARRAY
|| Tag_val (f) == Double_tag
#endif
))){
/* Do not short-circuit the pointer. */
}else{
/* The variable child is not changed because it must be mark alive */
Field (v, i) = f;
if (Is_block (f) && Is_young (f) && !Is_young (child)){
if(in_ephemeron) {
add_to_ephe_ref_table (Caml_state->ephe_ref_table, v, i);
} else {
add_to_ref_table (Caml_state->ref_table, &Field (v, i));
}
}
}
}
else if (Tag_hd(chd) == Infix_tag) {
child -= Infix_offset_val(child);
chd = Hd_val(child);
}
#ifdef NO_NAKED_POINTERS
/* See [caml_darken] for a description of this assertion. */
CAMLassert (Is_in_heap (child) || Is_black_hd (chd));
#endif
if (Is_white_hd (chd)){
ephe_list_pure = 0;
Hd_val (child) = Blackhd_hd (chd);
if( Tag_hd(chd) < No_scan_tag ) {
mark_stack_push(stk, child, 0, work);
} else {
*work -= 1; /* Account for header */
}
}
}
#if defined(NAKED_POINTERS_CHECKER) && defined(NATIVE_CODE)
else if (Is_block(child) && ! Is_young(child)) {
is_naked_pointer_safe(child, &Field (v, i));
}
#endif
}
static void mark_ephe_aux (struct mark_stack *stk, intnat *work,
int *slice_pointers)
{
value v, data, key;
header_t hd;
mlsize_t size, i;
v = *ephes_to_check;
hd = Hd_val(v);
CAMLassert(Tag_val (v) == Abstract_tag);
data = Field(v,CAML_EPHE_DATA_OFFSET);
if ( data != caml_ephe_none &&
Is_block (data) &&
#ifdef NO_NAKED_POINTERS
!Is_young(data) &&
#else
Is_in_heap (data) &&
#endif
Is_white_val (data)){
int alive_data = 1;
/* The liveness of the ephemeron is one of the condition */
if (Is_white_hd (hd)) alive_data = 0;
/* The liveness of the keys not caml_ephe_none is the other condition */
size = Wosize_hd (hd);
for (i = CAML_EPHE_FIRST_KEY; alive_data && i < size; i++){
key = Field (v, i);
ephemeron_again:
if (key != caml_ephe_none &&
Is_block (key) &&
#ifdef NO_NAKED_POINTERS
!Is_young(key)
#else
Is_in_heap(key)
#endif
){
if (Tag_val (key) == Forward_tag){
value f = Forward_val (key);
if (Is_long (f) ||
(Is_block (f) &&
(!Is_in_value_area(f) || Tag_val (f) == Forward_tag
|| Tag_val (f) == Lazy_tag
#ifdef FLAT_FLOAT_ARRAY
|| Tag_val (f) == Double_tag
#endif
))){
/* Do not short-circuit the pointer. */
}else{
Field (v, i) = key = f;
goto ephemeron_again;
}
}
if (Is_white_val (key)){
alive_data = 0;
}
}
}
*work -= Whsize_wosize(i);
if (alive_data){
mark_slice_darken(stk, v, CAML_EPHE_DATA_OFFSET, /*in_ephemeron=*/1,
slice_pointers, work);
} else { /* not triggered move to the next one */
ephes_to_check = &Field(v,CAML_EPHE_LINK_OFFSET);
return;
}
} else { /* a simily weak pointer or an already alive data */
*work -= 1;
}
/* all keys black or data none or black
move the ephemerons from (3) to the end of (1) */
if ( ephes_checked_if_pure == ephes_to_check ) {
/* corner case and optim */
ephes_checked_if_pure = &Field(v,CAML_EPHE_LINK_OFFSET);
ephes_to_check = ephes_checked_if_pure;
} else {
/* - remove v from the list (3) */
*ephes_to_check = Field(v,CAML_EPHE_LINK_OFFSET);
/* - insert it at the end of (1) */
Field(v,CAML_EPHE_LINK_OFFSET) = *ephes_checked_if_pure;
*ephes_checked_if_pure = v;
ephes_checked_if_pure = &Field(v,CAML_EPHE_LINK_OFFSET);
}
}
static void mark_slice (intnat work)
{
mark_entry me = {0, 0};
mlsize_t me_end = 0;
#ifdef CAML_INSTR
int slice_fields = 0; /** eventlog counters */
#endif /*CAML_INSTR*/
int slice_pointers = 0;
struct mark_stack* stk = Caml_state->mark_stack;
caml_gc_message (0x40, "Marking %"ARCH_INTNAT_PRINTF_FORMAT"d words\n", work);
caml_gc_message (0x40, "Subphase = %d\n", caml_gc_subphase);
while (1){
int can_mark = 0;
if (me.offset == me_end) {
if (stk->count > 0)
{
me = stk->stack[--stk->count];
me_end = Wosize_val(me.block);
can_mark = 1;
}
} else {
can_mark = 1;
}
if (work <= 0) {
if( can_mark ) {
mark_stack_push(stk, me.block, me.offset, NULL);
CAML_EVENTLOG_DO({
CAML_EV_COUNTER(EV_C_MAJOR_MARK_SLICE_REMAIN, me_end - me.offset);
});
}
break;
}
if( can_mark ) {
CAMLassert(Is_block(me.block) &&
Is_black_val (me.block) &&
Tag_val(me.block) < No_scan_tag);
mark_slice_darken(stk, me.block, me.offset++, /*in_ephemeron=*/ 0,
&slice_pointers, &work);
work--;
CAML_EVENTLOG_DO({
slice_fields++;
});
if( me.offset == me_end ) {
work--; /* Include header word */
}
} else if( redarken_first_chunk != NULL ) {
/* There are chunks that need to be redarkened because we
overflowed our mark stack */
if( redarken_chunk(redarken_first_chunk, stk) ) {
redarken_first_chunk = Chunk_next(redarken_first_chunk);
}
} else if (caml_gc_subphase == Subphase_mark_roots) {
CAML_EV_BEGIN(EV_MAJOR_MARK_ROOTS);
work = caml_darken_all_roots_slice (work);
CAML_EV_END(EV_MAJOR_MARK_ROOTS);
if (work > 0){
caml_gc_subphase = Subphase_mark_main;
}
} else if (*ephes_to_check != (value) NULL) {
/* Continue to scan the list of ephe */
mark_ephe_aux(stk,&work,&slice_pointers);
} else if (!ephe_list_pure){
/* We must scan again the list because some value have been darken */
ephe_list_pure = 1;
ephes_to_check = ephes_checked_if_pure;
}else{
switch (caml_gc_subphase){
case Subphase_mark_main: {
/* Subphase_mark_main is done.
Mark finalised values. */
CAML_EV_BEGIN(EV_MAJOR_MARK_MAIN);
caml_final_update_mark_phase ();
/* Complete the marking */
ephes_to_check = ephes_checked_if_pure;
CAML_EV_END(EV_MAJOR_MARK_MAIN);
caml_gc_subphase = Subphase_mark_final;
}
break;
case Subphase_mark_final: {
/** The set of unreachable value will not change anymore for
this cycle. Start clean phase. */
CAML_EV_BEGIN(EV_MAJOR_MARK_FINAL);
caml_gc_phase = Phase_clean;
caml_final_update_clean_phase ();
caml_memprof_update_clean_phase ();
if (caml_ephe_list_head != (value) NULL){
/* Initialise the clean phase. */
ephes_to_check = &caml_ephe_list_head;
} else {
/* Initialise the sweep phase. */
init_sweep_phase();
}
work = 0;
CAML_EV_END(EV_MAJOR_MARK_FINAL);
}
break;
default: CAMLassert (0);
}
}
}
CAML_EV_COUNTER(EV_C_MAJOR_MARK_SLICE_FIELDS, slice_fields);
CAML_EV_COUNTER(EV_C_MAJOR_MARK_SLICE_POINTERS, slice_pointers);
}
/* Clean ephemerons */
static void clean_slice (intnat work)
{
value v;
caml_gc_message (0x40, "Cleaning %"
ARCH_INTNAT_PRINTF_FORMAT "d words\n", work);
while (work > 0){
v = *ephes_to_check;
if (v != (value) NULL){
if (Is_white_val (v)){
/* The whole array is dead, remove it from the list. */
*ephes_to_check = Field (v, CAML_EPHE_LINK_OFFSET);
work -= 1;
}else{
caml_ephe_clean(v);
ephes_to_check = &Field (v, CAML_EPHE_LINK_OFFSET);
work -= Whsize_val (v);
}
}else{ /* End of list reached */
/* Phase_clean is done. */
/* Initialise the sweep phase. */
init_sweep_phase();
work = 0;
}
}
}
static void sweep_slice (intnat work)
{
char *hp;
header_t hd;
caml_gc_message (0x40, "Sweeping %"
ARCH_INTNAT_PRINTF_FORMAT "d words\n", work);
while (work > 0){
if (caml_gc_sweep_hp < sweep_limit){
hp = caml_gc_sweep_hp;
hd = Hd_hp (hp);
work -= Whsize_hd (hd);
caml_gc_sweep_hp += Bhsize_hd (hd);
switch (Color_hd (hd)){
case Caml_white:
caml_gc_sweep_hp =
(char *)caml_fl_merge_block(Val_hp (hp), sweep_limit);
break;
case Caml_blue:
/* Only the blocks of the free-list are blue. See [freelist.c]. */
caml_fl_merge = (value) Bp_hp (hp);
break;
default: /* gray or black */
CAMLassert (Color_hd (hd) == Caml_black);
Hd_hp (hp) = Whitehd_hd (hd);
break;
}
CAMLassert (caml_gc_sweep_hp <= sweep_limit);
}else{
sweep_chunk = Chunk_next (sweep_chunk);
if (sweep_chunk == NULL){
/* Sweeping is done. */
++ Caml_state->stat_major_collections;
work = 0;
caml_gc_phase = Phase_idle;
caml_request_minor_gc ();
}else{
caml_gc_sweep_hp = sweep_chunk;
sweep_limit = sweep_chunk + Chunk_size (sweep_chunk);
}
}
}
}
/* The main entry point for the major GC. Called about once for each
minor GC. [howmuch] is the amount of work to do:
-1 if the GC is triggered automatically
0 to let the GC compute the amount of work
[n] to make the GC do enough work to (on average) free [n] words
*/
void caml_major_collection_slice (intnat howmuch)
{
double p, dp, filt_p, spend;
intnat computed_work;
int i;
/*
Free memory at the start of the GC cycle (garbage + free list) (assumed):
FM = Caml_state->stat_heap_wsz * caml_percent_free
/ (100 + caml_percent_free)
Assuming steady state and enforcing a constant allocation rate, then
FM is divided in 2/3 for garbage and 1/3 for free list.
G = 2 * FM / 3
G is also the amount of memory that will be used during this cycle
(still assuming steady state).
Proportion of G consumed since the previous slice:
PH = caml_allocated_words / G
= caml_allocated_words * 3 * (100 + caml_percent_free)
/ (2 * Caml_state->stat_heap_wsz * caml_percent_free)
Proportion of extra-heap resources consumed since the previous slice:
PE = caml_extra_heap_resources
Proportion of total work to do in this slice:
P = max (PH, PE)
Here, we insert a time-based filter on the P variable to avoid large
latency spikes in the GC, so the P below is a smoothed-out version of
the P above.
Amount of marking work for the GC cycle:
MW = Caml_state->stat_heap_wsz * 100 / (100 + caml_percent_free)
+ caml_incremental_roots_count
Amount of sweeping work for the GC cycle:
SW = Caml_state->stat_heap_wsz
In order to finish marking with a non-empty free list, we will
use 40% of the time for marking, and 60% for sweeping.
Let MT be the time spent marking, ST the time spent sweeping, and TT
the total time for this cycle. We have:
MT = 40/100 * TT
ST = 60/100 * TT
Amount of time to spend on this slice:
T = P * TT = P * MT / (40/100) = P * ST / (60/100)
Since we must do MW work in MT time or SW work in ST time, the amount
of work for this slice is:
MS = P * MW / (40/100) if marking
SS = P * SW / (60/100) if sweeping
Amount of marking work for a marking slice:
MS = P * MW / (40/100)
MS = P * (Caml_state->stat_heap_wsz * 250
/ (100 + caml_percent_free)
+ 2.5 * caml_incremental_roots_count)
Amount of sweeping work for a sweeping slice:
SS = P * SW / (60/100)
SS = P * Caml_state->stat_heap_wsz * 5 / 3
This slice will either mark MS words or sweep SS words.
*/
if (caml_major_slice_begin_hook != NULL) (*caml_major_slice_begin_hook) ();
p = (double) caml_allocated_words * 3.0 * (100 + caml_percent_free)
/ Caml_state->stat_heap_wsz / caml_percent_free / 2.0;
if (caml_dependent_size > 0){
dp = (double) caml_dependent_allocated * (100 + caml_percent_free)
/ caml_dependent_size / caml_percent_free;
}else{
dp = 0.0;
}
if (p < dp) p = dp;
if (p < caml_extra_heap_resources) p = caml_extra_heap_resources;
p += p_backlog;
p_backlog = 0.0;
if (p > 0.3){
p_backlog = p - 0.3;
p = 0.3;
}
CAML_EV_COUNTER (EV_C_MAJOR_WORK_EXTRA,
(uintnat) (caml_extra_heap_resources * 1000000));
caml_gc_message (0x40, "ordered work = %"
ARCH_INTNAT_PRINTF_FORMAT "d words\n", howmuch);
caml_gc_message (0x40, "allocated_words = %"
ARCH_INTNAT_PRINTF_FORMAT "u\n",
caml_allocated_words);
caml_gc_message (0x40, "extra_heap_resources = %"
ARCH_INTNAT_PRINTF_FORMAT "uu\n",
(uintnat) (caml_extra_heap_resources * 1000000));
caml_gc_message (0x40, "raw work-to-do = %"
ARCH_INTNAT_PRINTF_FORMAT "du\n",
(intnat) (p * 1000000));
caml_gc_message (0x40, "work backlog = %"
ARCH_INTNAT_PRINTF_FORMAT "du\n",
(intnat) (p_backlog * 1000000));
for (i = 0; i < caml_major_window; i++){
caml_major_ring[i] += p / caml_major_window;
}
if (caml_gc_clock >= 1.0){
caml_gc_clock -= 1.0;
++caml_major_ring_index;
if (caml_major_ring_index >= caml_major_window){
caml_major_ring_index = 0;
}
}
if (howmuch == -1){
/* auto-triggered GC slice: spend work credit on the current bucket,
then do the remaining work, if any */
/* Note that the minor GC guarantees that the major slice is called in
automatic mode (with [howmuch] = -1) at least once per clock tick.
This means we never leave a non-empty bucket behind. */
spend = fmin (caml_major_work_credit,
caml_major_ring[caml_major_ring_index]);
caml_major_work_credit -= spend;
filt_p = caml_major_ring[caml_major_ring_index] - spend;
caml_major_ring[caml_major_ring_index] = 0.0;
}else{
/* forced GC slice: do work and add it to the credit */
if (howmuch == 0){
/* automatic setting: size of next bucket
we do not use the current bucket, as it may be empty */
int i = caml_major_ring_index + 1;
if (i >= caml_major_window) i = 0;
filt_p = caml_major_ring[i];
}else{
/* manual setting */
filt_p = (double) howmuch * 3.0 * (100 + caml_percent_free)
/ Caml_state->stat_heap_wsz / caml_percent_free / 2.0;
}
caml_major_work_credit += filt_p;
/* Limit work credit to 1.0 */
caml_major_work_credit = fmin(caml_major_work_credit, 1.0);
}
p = filt_p;
caml_gc_message (0x40, "filtered work-to-do = %"
ARCH_INTNAT_PRINTF_FORMAT "du\n",
(intnat) (p * 1000000));
if (caml_gc_phase == Phase_idle){
if (Caml_state->young_ptr == Caml_state->young_alloc_end){
/* We can only start a major GC cycle if the minor allocation arena
is empty, otherwise we'd have to treat it as a set of roots. */
CAML_EV_BEGIN(EV_MAJOR_ROOTS);
start_cycle ();
CAML_EV_END(EV_MAJOR_ROOTS);
}
p = 0;
goto finished;
}
if (p < 0){
p = 0;
goto finished;
}
if (caml_gc_phase == Phase_mark || caml_gc_phase == Phase_clean){
computed_work = (intnat) (p * ((double) Caml_state->stat_heap_wsz * 250
/ (100 + caml_percent_free)
+ caml_incremental_roots_count));
}else{
computed_work = (intnat) (p * Caml_state->stat_heap_wsz * 5 / 3);
}
caml_gc_message (0x40, "computed work = %"
ARCH_INTNAT_PRINTF_FORMAT "d words\n", computed_work);
if (caml_gc_phase == Phase_mark){
CAML_EV_COUNTER (EV_C_MAJOR_WORK_MARK, computed_work);
CAML_EV_BEGIN(EV_MAJOR_MARK);
mark_slice (computed_work);
CAML_EV_END(EV_MAJOR_MARK);
caml_gc_message (0x02, "!");
}else if (caml_gc_phase == Phase_clean){
clean_slice (computed_work);
caml_gc_message (0x02, "%%");
}else{
CAMLassert (caml_gc_phase == Phase_sweep);
CAML_EV_COUNTER (EV_C_MAJOR_WORK_SWEEP, computed_work);
CAML_EV_BEGIN(EV_MAJOR_SWEEP);
sweep_slice (computed_work);
CAML_EV_END(EV_MAJOR_SWEEP);
caml_gc_message (0x02, "$");
}
if (caml_gc_phase == Phase_idle){
CAML_EV_BEGIN(EV_MAJOR_CHECK_AND_COMPACT);
caml_compact_heap_maybe ();
CAML_EV_END(EV_MAJOR_CHECK_AND_COMPACT);
}
finished:
caml_gc_message (0x40, "work-done = %"
ARCH_INTNAT_PRINTF_FORMAT "du\n",
(intnat) (p * 1000000));
/* if some of the work was not done, take it back from the credit
or spread it over the buckets. */
p = filt_p - p;
spend = fmin (p, caml_major_work_credit);
caml_major_work_credit -= spend;
if (p > spend){
p -= spend;
p /= caml_major_window;
for (i = 0; i < caml_major_window; i++) caml_major_ring[i] += p;
}
Caml_state->stat_major_words += caml_allocated_words;
caml_allocated_words = 0;
caml_dependent_allocated = 0;
caml_extra_heap_resources = 0.0;
if (caml_major_slice_end_hook != NULL) (*caml_major_slice_end_hook) ();
}
/* This does not call [caml_compact_heap_maybe] because the estimates of
free and live memory are only valid for a cycle done incrementally.
Besides, this function itself is called by [caml_compact_heap_maybe].
*/
void caml_finish_major_cycle (void)
{
if (caml_gc_phase == Phase_idle){
p_backlog = 0.0; /* full major GC cycle, the backlog becomes irrelevant */
start_cycle ();
}
while (caml_gc_phase == Phase_mark) mark_slice (LONG_MAX);
while (caml_gc_phase == Phase_clean) clean_slice (LONG_MAX);
CAMLassert (caml_gc_phase == Phase_sweep);
CAMLassert (redarken_first_chunk == NULL);
while (caml_gc_phase == Phase_sweep) sweep_slice (LONG_MAX);
CAMLassert (caml_gc_phase == Phase_idle);
Caml_state->stat_major_words += caml_allocated_words;
caml_allocated_words = 0;
}
/* Call this function to make sure [bsz] is greater than or equal
to both [Heap_chunk_min] and the current heap increment.
*/
asize_t caml_clip_heap_chunk_wsz (asize_t wsz)
{
asize_t result = wsz;
uintnat incr;
/* Compute the heap increment as a word size. */
if (caml_major_heap_increment > 1000){
incr = caml_major_heap_increment;
}else{
incr = Caml_state->stat_heap_wsz / 100 * caml_major_heap_increment;
}
if (result < incr){
result = incr;
}
if (result < Heap_chunk_min){
result = Heap_chunk_min;
}
return result;
}
/* [heap_size] is a number of bytes */
void caml_init_major_heap (asize_t heap_size)
{
int i;
Caml_state->stat_heap_wsz =
caml_clip_heap_chunk_wsz (Wsize_bsize (heap_size));
Caml_state->stat_top_heap_wsz = Caml_state->stat_heap_wsz;
CAMLassert (Bsize_wsize (Caml_state->stat_heap_wsz) % Page_size == 0);
caml_heap_start =
(char *) caml_alloc_for_heap (Bsize_wsize (Caml_state->stat_heap_wsz));
if (caml_heap_start == NULL)
caml_fatal_error ("cannot allocate initial major heap");
Chunk_next (caml_heap_start) = NULL;
Caml_state->stat_heap_wsz = Wsize_bsize (Chunk_size (caml_heap_start));
Caml_state->stat_heap_chunks = 1;
Caml_state->stat_top_heap_wsz = Caml_state->stat_heap_wsz;
if (caml_page_table_add(In_heap, caml_heap_start,
caml_heap_start + Bsize_wsize (Caml_state->stat_heap_wsz))
!= 0) {
caml_fatal_error ("cannot allocate initial page table");
}
caml_fl_init_merge ();
caml_make_free_blocks ((value *) caml_heap_start,
Caml_state->stat_heap_wsz, 1, Caml_white);
caml_gc_phase = Phase_idle;
Caml_state->mark_stack = caml_stat_alloc_noexc(sizeof(struct mark_stack));
if (Caml_state->mark_stack == NULL)
caml_fatal_error ("not enough memory for the mark stack");
Caml_state->mark_stack->stack =
caml_stat_alloc_noexc(MARK_STACK_INIT_SIZE * sizeof(mark_entry));
if(Caml_state->mark_stack->stack == NULL)
caml_fatal_error("not enough memory for the mark stack");
Caml_state->mark_stack->count = 0;
Caml_state->mark_stack->size = MARK_STACK_INIT_SIZE;
caml_allocated_words = 0;
caml_extra_heap_resources = 0.0;
for (i = 0; i < Max_major_window; i++) caml_major_ring[i] = 0.0;
}
void caml_set_major_window (int w){
uintnat total = 0;
int i;
if (w == caml_major_window) return;
CAMLassert (w <= Max_major_window);
/* Collect the current work-to-do from the buckets. */
for (i = 0; i < caml_major_window; i++){
total += caml_major_ring[i];
}
/* Redistribute to the new buckets. */
for (i = 0; i < w; i++){
caml_major_ring[i] = total / w;
}
caml_major_window = w;
}
void caml_finalise_heap (void)
{
/* Finishing major cycle (all values become white) */
caml_empty_minor_heap ();
caml_gc_message (0x1, "Finishing major GC cycle (finalising heap)\n");
caml_finish_major_cycle ();
CAMLassert (caml_gc_phase == Phase_idle);
/* Finalising all values (by means of forced sweeping) */
caml_fl_init_merge ();
caml_gc_phase = Phase_sweep;
sweep_chunk = caml_heap_start;
caml_gc_sweep_hp = sweep_chunk;
sweep_limit = sweep_chunk + Chunk_size (sweep_chunk);
while (caml_gc_phase == Phase_sweep)
sweep_slice (LONG_MAX);
}
#if defined(NAKED_POINTERS_CHECKER) && defined(NATIVE_CODE)
#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
Caml_inline int safe_load(volatile header_t * p, header_t * result)
{
header_t v;
__try {
v = *p;
}
__except(GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION ?
EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) {
*result = 0xdeadbeef;
return 0;
}
*result = v;
return 1;
}
#else
Caml_inline int safe_load (header_t * addr, /*out*/ header_t * contents)
{
int ok;
header_t h;
intnat tmp;
asm volatile(
"leaq 1f(%%rip), %[tmp] \n\t"
"movq %[tmp], 0(%[handler]) \n\t"
"xorl %[ok], %[ok] \n\t"
"movq 0(%[addr]), %[h] \n\t"
"movl $1, %[ok] \n\t"
"1: \n\t"
"xorq %[tmp], %[tmp] \n\t"
"movq %[tmp], 0(%[handler])"
: [tmp] "=&r" (tmp), [ok] "=&r" (ok), [h] "=&r" (h)
: [addr] "r" (addr),
[handler] "r" (&(Caml_state->checking_pointer_pc)));
*contents = h;
return ok;
}
#endif
static void is_naked_pointer_safe (value v, value *p)
{
header_t h;
tag_t t;
/* The following conditions were checked by the caller */
CAMLassert(Is_block(v) && !Is_young(v) && !Is_in_heap(v));
if (! safe_load(&Hd_val(v), &h)) goto on_segfault;
t = Tag_hd(h);
if (t == Infix_tag) {
v -= Infix_offset_hd(h);
if (! safe_load(&Hd_val(v), &h)) goto on_segfault;
t = Tag_hd(h);
}
/* For the out-of-heap pointer to be considered safe,
* it should have a black header and its size should be < 2 ** 40
* words (128 GB). If not, we report a warning. */
if (Is_black_hd(h) && Wosize_hd(h) < (INT64_LITERAL(1) << 40))
return;
if (!Is_black_hd(h)) {
fprintf (stderr, "Out-of-heap pointer at %p of value %p has "
"non-black head (tag=%d)\n", p, (void*)v, t);
} else {
fprintf (stderr,
"Out-of-heap pointer at %p of value %p has "
"suspiciously large size: %" ARCH_INT64_PRINTF_FORMAT "u words\n",
p, (void*)v, Wosize_hd(h));
}
return;
on_segfault:
fprintf (stderr, "Out-of-heap pointer at %p of value %p. "
"Cannot read head.\n", p, (void*)v);
}
#endif
| 32.155085 | 80 | 0.620483 |
55d10ebcb963da7b4ee62d5f071b5aa80801d0ef | 398 | h | C | declare-interface-cpp/example-5/IDemo.h | gusenov/examples-cpp | 2cd0abe15bf534c917bcfbca70694daaa19c4612 | [
"MIT"
] | 12 | 2019-08-18T19:28:55.000Z | 2022-03-29T12:55:20.000Z | declare-interface-cpp/example-5/IDemo.h | gusenov/examples-cpp | 2cd0abe15bf534c917bcfbca70694daaa19c4612 | [
"MIT"
] | null | null | null | declare-interface-cpp/example-5/IDemo.h | gusenov/examples-cpp | 2cd0abe15bf534c917bcfbca70694daaa19c4612 | [
"MIT"
] | null | null | null | class IDemo
{
public:
virtual void OverrideMe() = 0;
// Альтернатива для виртуального деструктора - защищенный деструктор.
// Это отключит полиморфную деструкцию.
// См. "Guideline #4" в http://www.gotw.ca/publications/mill18.htm
// Защищенный невиртуальный конструктор позволяет избежать UB, если кто-то
// попытается удалить объект типа IDemo.
protected:
~IDemo() {}
};
| 23.411765 | 76 | 0.711055 |
55f579a72004b161253988398d232bfb6aca2fdf | 434 | h | C | Project/NodeTree/module.NodeTree/module.json/NTJSONReader.h | rlong/cocoa.lib.NodeTree | cb210a1b2f65c64d9ccc7a13d931508ee3a2fec1 | [
"Apache-2.0"
] | null | null | null | Project/NodeTree/module.NodeTree/module.json/NTJSONReader.h | rlong/cocoa.lib.NodeTree | cb210a1b2f65c64d9ccc7a13d931508ee3a2fec1 | [
"Apache-2.0"
] | null | null | null | Project/NodeTree/module.NodeTree/module.json/NTJSONReader.h | rlong/cocoa.lib.NodeTree | cb210a1b2f65c64d9ccc7a13d931508ee3a2fec1 | [
"Apache-2.0"
] | null | null | null | // https://github.com/rlong/cocoa.lib.NodeTree
//
// Copyright (c) 2015 Richard Long
//
// Released under the MIT license ( http://opensource.org/licenses/MIT )
//
#import <Foundation/Foundation.h>
#import "NTNodeTreeReaderDelegate.h"
@interface NTJSONReader : NSObject <NTNodeTreeReaderDelegate>
@property (nonatomic, strong) NSMutableArray* rootArray;
@property (nonatomic, strong) NSMutableDictionary* rootDictionary;
@end
| 24.111111 | 73 | 0.760369 |
d4d72c7b9fc43377d0a72190b3a1c52d06ebf21b | 1,579 | h | C | include/il2cpp/System/Linq/Enumerable/WhereEnumerableIterator_int_.h | martmists-gh/BDSP | d6326c5d3ad9697ea65269ed47aa0b63abac2a0a | [
"MIT"
] | 1 | 2022-01-15T20:20:27.000Z | 2022-01-15T20:20:27.000Z | include/il2cpp/System/Linq/Enumerable/WhereEnumerableIterator_int_.h | martmists-gh/BDSP | d6326c5d3ad9697ea65269ed47aa0b63abac2a0a | [
"MIT"
] | null | null | null | include/il2cpp/System/Linq/Enumerable/WhereEnumerableIterator_int_.h | martmists-gh/BDSP | d6326c5d3ad9697ea65269ed47aa0b63abac2a0a | [
"MIT"
] | null | null | null | #pragma once
#include "il2cpp.h"
void System_Linq_Enumerable_WhereEnumerableIterator_int____ctor (System_Linq_Enumerable_WhereEnumerableIterator_int__o* __this, System_Collections_Generic_IEnumerable_TSource__o* source, System_Func_TSource__bool__o* predicate, const MethodInfo* method_info);
System_Linq_Enumerable_Iterator_TSource__o* System_Linq_Enumerable_WhereEnumerableIterator_int___Clone (System_Linq_Enumerable_WhereEnumerableIterator_int__o* __this, const MethodInfo* method_info);
void System_Linq_Enumerable_WhereEnumerableIterator_int___Dispose (System_Linq_Enumerable_WhereEnumerableIterator_int__o* __this, const MethodInfo* method_info);
bool System_Linq_Enumerable_WhereEnumerableIterator_int___MoveNext (System_Linq_Enumerable_WhereEnumerableIterator_int__o* __this, const MethodInfo* method_info);
System_Collections_Generic_IEnumerable_TResult__o* System_Linq_Enumerable_WhereEnumerableIterator_int___Select_int_ (System_Linq_Enumerable_WhereEnumerableIterator_int__o* __this, System_Func_TSource__TResult__o* selector, const MethodInfo* method_info);
System_Collections_Generic_IEnumerable_TResult__o* System_Linq_Enumerable_WhereEnumerableIterator_int___Select_object_ (System_Linq_Enumerable_WhereEnumerableIterator_int__o* __this, System_Func_TSource__TResult__o* selector, const MethodInfo* method_info);
System_Collections_Generic_IEnumerable_TSource__o* System_Linq_Enumerable_WhereEnumerableIterator_int___Where (System_Linq_Enumerable_WhereEnumerableIterator_int__o* __this, System_Func_TSource__bool__o* predicate, const MethodInfo* method_info);
| 131.583333 | 259 | 0.920203 |
3def08e42dd60a9bf07429f2696d8c00d57ac0f3 | 1,676 | c | C | test/test_inflate_adler32.c | 9chu/zlib-ng | 43dbfd6709fb3a8028430ea30f3da88fbeb3ced9 | [
"Zlib"
] | 626 | 2018-12-02T20:47:47.000Z | 2022-03-31T22:02:04.000Z | test/test_inflate_adler32.c | 9chu/zlib-ng | 43dbfd6709fb3a8028430ea30f3da88fbeb3ced9 | [
"Zlib"
] | 907 | 2018-12-06T09:45:21.000Z | 2022-03-31T23:23:18.000Z | test/test_inflate_adler32.c | 9chu/zlib-ng | 43dbfd6709fb3a8028430ea30f3da88fbeb3ced9 | [
"Zlib"
] | 137 | 2018-12-08T19:06:41.000Z | 2022-03-30T02:51:08.000Z | /* GH-1066 - inflate small amount of data and validate with adler32 checksum. */
#include "zbuild.h"
#ifdef ZLIB_COMPAT
# include "zlib.h"
#else
# include "zlib-ng.h"
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
const char* original = "The quick brown fox jumped over the lazy dog";
z_const unsigned char compressed[] = {
0x78, 0x9c, 0x0b, 0xc9, 0x48, 0x55, 0x28, 0x2c, 0xcd, 0x4c, 0xce, 0x56, 0x48,
0x2a, 0xca, 0x2f, 0xcf, 0x53, 0x48, 0xcb, 0xaf, 0x50, 0xc8, 0x2a, 0xcd, 0x2d,
0x48, 0x4d, 0x51, 0xc8, 0x2f, 0x4b, 0x2d, 0x52, 0x28, 0xc9, 0x48, 0x55, 0xc8,
0x49, 0xac, 0xaa, 0x54, 0x48, 0xc9, 0x4f, 0x07, 0x00, 0x6b, 0x93, 0x10, 0x30
};
int main()
{
unsigned char uncompressed[1024];
PREFIX3(stream) strm;
memset(&strm, 0, sizeof(strm));
int ret = PREFIX(inflateInit2)(&strm, 32 + MAX_WBITS);
if (ret != Z_OK) {
fprintf(stderr, "inflateInit2() failed with code %d\n", ret);
return EXIT_FAILURE;
}
strm.next_in = compressed;
strm.avail_in = sizeof(compressed);
strm.next_out = uncompressed;
strm.avail_out = sizeof(uncompressed);
ret = PREFIX(inflate)(&strm, Z_NO_FLUSH);
if (ret != Z_STREAM_END) {
fprintf(stderr, "inflate() failed with code %d\n", ret);
return EXIT_FAILURE;
}
ret = PREFIX(inflateEnd)(&strm);
if (ret != Z_OK) {
fprintf(stderr, "inflateEnd() failed with code %d\n", ret);
return EXIT_FAILURE;
}
if (memcmp(uncompressed, original, MIN(strm.total_out, strlen(original))) != 0) {
fprintf(stderr, "expected output does not match\n");
return EXIT_FAILURE;
}
return 0;
}
| 27.933333 | 85 | 0.634248 |
5c2b63be75dc3b35c92d24d54b941121bde11dd4 | 638 | h | C | LLContainerComponent/Classes/Cards/View/LLCardTableView.h | lifuqing/LLContainerListViewController | 4fb26f4c897c34d24af69bdde59bb3a4121a8568 | [
"MIT"
] | null | null | null | LLContainerComponent/Classes/Cards/View/LLCardTableView.h | lifuqing/LLContainerListViewController | 4fb26f4c897c34d24af69bdde59bb3a4121a8568 | [
"MIT"
] | null | null | null | LLContainerComponent/Classes/Cards/View/LLCardTableView.h | lifuqing/LLContainerListViewController | 4fb26f4c897c34d24af69bdde59bb3a4121a8568 | [
"MIT"
] | null | null | null | //
// LLCardTableView.h
// LLContainerComponent
//
// Created by lifuqing on 2019/1/7.
//
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@class LLContainerCardsController, LLCardController;
@interface LLCardTableView : UITableView
@property (nonatomic, weak) NSArray<LLCardController *> *cardControllersArray;
@property (nonatomic, weak) LLContainerCardsController *cardsController;
///更新指定section缓存并刷新
- (void)reloadSection:(NSInteger)section;
///更新指定section组缓存并刷新
- (void)reloadSections:(NSIndexSet *)sections;
#pragma mark - 永久悬停功能
@property (nonatomic, strong) UIView *foreverSuspendHeader;
@end
NS_ASSUME_NONNULL_END
| 19.333333 | 78 | 0.783699 |
69f1142953235e917932ae346c73937495bdcf2f | 2,149 | h | C | headers/QmlFutures/QF.h | ihor-drachuk/QmlFutures | d4caf0c0db2af2eaf3267b11c6355520b01981fc | [
"MIT"
] | null | null | null | headers/QmlFutures/QF.h | ihor-drachuk/QmlFutures | d4caf0c0db2af2eaf3267b11c6355520b01981fc | [
"MIT"
] | null | null | null | headers/QmlFutures/QF.h | ihor-drachuk/QmlFutures | d4caf0c0db2af2eaf3267b11c6355520b01981fc | [
"MIT"
] | null | null | null | #pragma once
#include <QObject>
#include <memory>
#include <QmlFutures/Tools.h>
namespace QmlFutures {
//
// Singleton. Exposed to QML.
// Class for fast access to common things of QmlFutures.
//
class QF : public QObject, public Internal::Singleton<QF>
{
Q_OBJECT
friend class Init;
public:
enum class WatcherState {
Uninitialized,
Pending,
Running,
Paused,
Finished,
FinishedFulfilled,
FinishedCanceled
};
Q_ENUM(WatcherState);
enum class Comparison {
Equal,
NotEqual
};
Q_ENUM(Comparison);
enum class CombineTrigger {
Any,
All
};
Q_ENUM(CombineTrigger);
public:
QF();
~QF() override;
Q_INVOKABLE QVariant conditionObj(QObject* object);
Q_INVOKABLE QVariant conditionProp(QObject* object, const QString& propertyName, const QVariant& value, Comparison comparison);
Q_INVOKABLE QVariant createFuture(const QVariant& fulfilTrigger, const QVariant& cancelTrigger);
Q_INVOKABLE QVariant createTimedFuture(const QVariant& result, int time);
Q_INVOKABLE QVariant createTimedCanceledFuture(int time);
Q_INVOKABLE QVariant combine(QF::CombineTrigger trigger, const QVariant& context, const QVariant& sources);
private:
static void registerTypes();
struct CombineCtx;
struct FutureCtx;
struct TimedFutureCtx;
using FutureCtxPtr = std::shared_ptr<QF::FutureCtx>;
using CombineCtxPtr = std::shared_ptr<QF::CombineCtx>;
using TimedFutureCtxPtr = std::shared_ptr<QF::TimedFutureCtx>;
private:
static bool isNull(const QVariant& value);
static bool isCondition(const QVariant& value);
static bool isFuture(const QVariant& value);
static bool isCanceled(const QVariant& value);
static bool isFulfilled(const QVariant& value);
void recheckFulfilCond(FutureCtx*);
void recheckCancelCond(FutureCtx*);
void finishTimedFuture(TimedFutureCtx*);
void recheckFutureCond(FutureCtx*);
void recheckFutureCancelCond(FutureCtx*);
void recheckCombineCtx(CombineCtx*);
private:
QF_DECLARE_PIMPL
};
} // namespace QmlFutures
| 26.530864 | 131 | 0.709632 |
07bba1ef9ae8107c43e5e7b6d538542b32d7858f | 568 | h | C | Utils/objc-utils/UIKit/Label/MORollingView.h | moxian1993/Utils | d4960d228243e09446d6627e763ce56dd74f06c6 | [
"MIT"
] | null | null | null | Utils/objc-utils/UIKit/Label/MORollingView.h | moxian1993/Utils | d4960d228243e09446d6627e763ce56dd74f06c6 | [
"MIT"
] | null | null | null | Utils/objc-utils/UIKit/Label/MORollingView.h | moxian1993/Utils | d4960d228243e09446d6627e763ce56dd74f06c6 | [
"MIT"
] | null | null | null | //
// MORollingView.h
// Utils
//
// Created by Xian Mo on 2020/8/27.
// Copyright © 2020 Mo. All rights reserved.
//
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
/** 走马灯 */
@interface MORollingView : UIView
- (instancetype)initWithText:(NSString *)text
font:(UIFont *)font
textColor:(UIColor *)color
startLocation:(CGFloat) location
spacing:(CGFloat)spacing
speed:(CGFloat)speed;
- (void)start;
- (void)pause;
- (void)stop;
@end
NS_ASSUME_NONNULL_END
| 18.933333 | 47 | 0.586268 |
e093d33bac2baf5a418543e5ecac0c2c16ed04d6 | 2,193 | h | C | src/mxml/dom/Attributes.h | dkun7944/mxml | 6450e7cab88eb6ee0ac469f437047072e1868ea4 | [
"MIT"
] | 18 | 2016-05-22T00:55:28.000Z | 2021-03-29T08:44:23.000Z | src/mxml/dom/Attributes.h | dkun7944/mxml | 6450e7cab88eb6ee0ac469f437047072e1868ea4 | [
"MIT"
] | 6 | 2017-05-17T13:20:09.000Z | 2018-10-22T20:00:57.000Z | src/mxml/dom/Attributes.h | dkun7944/mxml | 6450e7cab88eb6ee0ac469f437047072e1868ea4 | [
"MIT"
] | 14 | 2016-05-12T22:54:34.000Z | 2021-10-19T12:43:16.000Z | // Copyright © 2016 Venture Media Labs.
//
// This file is part of mxml. The full mxml copyright notice, including
// terms governing use, modification, and redistribution, is contained in the
// file LICENSE at the root of the source code distribution tree.
#pragma once
#include "Clef.h"
#include "Key.h"
#include "Node.h"
#include "Optional.h"
#include "Time.h"
#include <cassert>
#include <vector>
namespace mxml {
namespace dom {
class Attributes : public Node {
public:
Attributes() : _divisions(1), _staves(1), _clefs(1), _keys(1), _time(), _start() {}
Optional<int> divisions() const {
return _divisions;
}
void setDivisions(Optional<int> divisions) {
_divisions = divisions;
}
Optional<int> staves() const {
return _staves;
}
void setStaves(Optional<int> staves);
const Clef* clef(int number) const {
if (number > 0 && number <= _clefs.size())
return _clefs[number - 1].get();
return nullptr;
}
Clef* clef(int number) {
if (number > 0 && number <= _clefs.size())
return _clefs[number - 1].get();
return nullptr;
}
void setClef(int number, std::unique_ptr<Clef>&& clef);
const Key* key(int number) const {
if (number > 0 && number <= _keys.size())
return _keys[number - 1].get();
return nullptr;
}
Key* key(int number) {
if (number > 0 && number <= _keys.size())
return _keys[number - 1].get();
return nullptr;
}
void setKey(int number, std::unique_ptr<Key> key);
const Time* time() const {
return _time.get();
}
Time* time() {
return _time.get();
}
void setTime(std::unique_ptr<Time> time) {
_time = std::move(time);
}
void setStart(time_t start) {
_start = start;
}
time_t start() const {
return _start;
}
private:
Optional<int> _divisions;
Optional<int> _staves;
std::vector<std::unique_ptr<Clef>> _clefs;
std::vector<std::unique_ptr<Key>> _keys;
std::unique_ptr<Time> _time;
time_t _start;
};
} // namespace dom
} // namespace mxml
| 24.640449 | 87 | 0.591427 |
6de7111fd7bdf628620d56cb99ec5b4afe552fa6 | 315 | h | C | PlugIns/IDEInterfaceBuilderCocoaIntegration/IBBindingSliceDelegate-Protocol.h | cameroncooke/XcodeHeaders | be955d30b5fc62c4312b354045b4561d164ebd9c | [
"MIT"
] | 1 | 2016-03-30T10:07:37.000Z | 2016-03-30T10:07:37.000Z | PlugIns/IDEInterfaceBuilderCocoaIntegration/IBBindingSliceDelegate-Protocol.h | cameroncooke/XcodeHeaders | be955d30b5fc62c4312b354045b4561d164ebd9c | [
"MIT"
] | null | null | null | PlugIns/IDEInterfaceBuilderCocoaIntegration/IBBindingSliceDelegate-Protocol.h | cameroncooke/XcodeHeaders | be955d30b5fc62c4312b354045b4561d164ebd9c | [
"MIT"
] | null | null | null | //
// Generated by class-dump 3.5 (64 bit).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by Steve Nygard.
//
#import "NSObject.h"
@class IBBindingSlice;
@protocol IBBindingSliceDelegate <NSObject>
- (void)bindingSlice:(IBBindingSlice *)arg1 didChangeExpansionState:(BOOL)arg2;
@end
| 21 | 83 | 0.714286 |
a32df63d7aba9d3d1b8e5f5737d09dc4d1e9e409 | 7,615 | h | C | include/X11/fonts/fntfil.h | tizenorg/framework.uifw.xorg.lib.libxfont | 3e1969f2133dfd2fac68f01b2b2aa460d86174d7 | [
"MIT"
] | null | null | null | include/X11/fonts/fntfil.h | tizenorg/framework.uifw.xorg.lib.libxfont | 3e1969f2133dfd2fac68f01b2b2aa460d86174d7 | [
"MIT"
] | null | null | null | include/X11/fonts/fntfil.h | tizenorg/framework.uifw.xorg.lib.libxfont | 3e1969f2133dfd2fac68f01b2b2aa460d86174d7 | [
"MIT"
] | null | null | null | /*
Copyright 1991, 1998 The Open Group
Permission to use, copy, modify, distribute, and sell this software and its
documentation for any purpose is hereby granted without fee, provided that
the above copyright notice appear in all copies and that both that
copyright notice and this permission notice appear in supporting
documentation.
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
OPEN GROUP 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.
Except as contained in this notice, the name of The Open Group shall not be
used in advertising or otherwise to promote the sale, use or other dealings
in this Software without prior written authorization from The Open Group.
*/
/*
* Author: Keith Packard, MIT X Consortium
*/
#ifndef _FONTFILE_H_
#define _FONTFILE_H_
#include <X11/fonts/fontxlfd.h>
typedef struct _FontEntry *FontEntryPtr;
typedef struct _FontTable *FontTablePtr;
typedef struct _FontName *FontNamePtr;
typedef struct _FontScaled *FontScaledPtr;
typedef struct _FontScalableExtra *FontScalableExtraPtr;
typedef struct _FontScalableEntry *FontScalableEntryPtr;
typedef struct _FontScaleAliasEntry *FontScaleAliasEntryPtr;
typedef struct _FontBitmapEntry *FontBitmapEntryPtr;
typedef struct _FontAliasEntry *FontAliasEntryPtr;
typedef struct _FontBCEntry *FontBCEntryPtr;
typedef struct _FontDirectory *FontDirectoryPtr;
typedef struct _FontRenderer *FontRendererPtr;
#define NullFontEntry ((FontEntryPtr) 0)
#define NullFontTable ((FontTablePtr) 0)
#define NullFontName ((FontNamePtr) 0)
#define NullFontScaled ((FontScaled) 0)
#define NullFontScalableExtra ((FontScalableExtra) 0)
#define NullFontscalableEntry ((FontScalableEntry) 0)
#define NullFontScaleAliasEntry ((FontScaleAliasEntry) 0)
#define NullFontBitmapEntry ((FontBitmapEntry) 0)
#define NullFontAliasEntry ((FontAliasEntry) 0)
#define NullFontBCEntry ((FontBCEntry) 0)
#define NullFontDirectory ((FontDirectoryPtr) 0)
#define NullFontRenderer ((FontRendererPtr) 0)
#define FONT_ENTRY_SCALABLE 0
#define FONT_ENTRY_SCALE_ALIAS 1
#define FONT_ENTRY_BITMAP 2
#define FONT_ENTRY_ALIAS 3
#define FONT_ENTRY_BC 4
#define MAXFONTNAMELEN 1024
#define MAXFONTFILENAMELEN 1024
#define FontDirFile "fonts.dir"
#define FontAliasFile "fonts.alias"
#define FontScalableFile "fonts.scale"
extern int FontFileNameCheck ( char *name );
extern int FontFileInitFPE ( FontPathElementPtr fpe );
extern int FontFileResetFPE ( FontPathElementPtr fpe );
extern int FontFileFreeFPE ( FontPathElementPtr fpe );
extern int FontFileOpenFont ( pointer client, FontPathElementPtr fpe,
Mask flags, char *name, int namelen,
fsBitmapFormat format, fsBitmapFormatMask fmask,
XID id, FontPtr *pFont, char **aliasName,
FontPtr non_cachable_font );
extern void FontFileCloseFont ( FontPathElementPtr fpe, FontPtr pFont );
extern int FontFileOpenBitmap ( FontPathElementPtr fpe, FontPtr *pFont,
int flags, FontEntryPtr entry,
fsBitmapFormat format,
fsBitmapFormatMask fmask );
extern int FontFileListFonts ( pointer client, FontPathElementPtr fpe,
char *pat, int len, int max,
FontNamesPtr names );
extern int FontFileStartListFonts ( pointer client, FontPathElementPtr fpe,
char *pat, int len, int max,
pointer *privatep, int mark_aliases );
extern int FontFileStartListFontsWithInfo ( pointer client,
FontPathElementPtr fpe,
char *pat, int len, int max,
pointer *privatep );
extern int FontFileListNextFontWithInfo ( pointer client,
FontPathElementPtr fpe,
char **namep, int *namelenp,
FontInfoPtr *pFontInfo,
int *numFonts, pointer private );
extern int FontFileStartListFontsAndAliases ( pointer client,
FontPathElementPtr fpe,
char *pat, int len, int max,
pointer *privatep );
extern int FontFileListNextFontOrAlias ( pointer client,
FontPathElementPtr fpe,
char **namep, int *namelenp,
char **resolvedp, int *resolvedlenp,
pointer private );
extern void FontFileRegisterLocalFpeFunctions ( void );
extern void CatalogueRegisterLocalFpeFunctions ( void );
extern FontEntryPtr FontFileAddEntry ( FontTablePtr table,
FontEntryPtr prototype );
extern Bool FontFileAddFontAlias ( FontDirectoryPtr dir, char *aliasName,
char *fontName );
extern Bool FontFileAddFontFile ( FontDirectoryPtr dir, char *fontName,
char *fileName );
extern int FontFileCountDashes ( char *name, int namelen );
extern FontEntryPtr FontFileFindNameInDir ( FontTablePtr table,
FontNamePtr pat );
extern FontEntryPtr FontFileFindNameInScalableDir ( FontTablePtr table,
FontNamePtr pat,
FontScalablePtr vals );
extern int FontFileFindNamesInDir ( FontTablePtr table, FontNamePtr pat,
int max, FontNamesPtr names );
extern int FontFileFindNamesInScalableDir ( FontTablePtr table,
FontNamePtr pat, int max,
FontNamesPtr names,
FontScalablePtr vals,
int alias_behavior, int *newmax );
extern void FontFileFreeDir ( FontDirectoryPtr dir );
extern void FontFileFreeEntry ( FontEntryPtr entry );
extern void FontFileFreeTable ( FontTablePtr table );
extern Bool FontFileInitTable ( FontTablePtr table, int size );
extern FontDirectoryPtr FontFileMakeDir ( const char *dirName, int size );
extern Bool FontFileMatchName ( char *name, int length, FontNamePtr pat );
extern char * FontFileSaveString ( char *s );
extern void FontFileSortDir ( FontDirectoryPtr dir );
extern void FontFileSortTable ( FontTablePtr table );
extern void FontDefaultFormat ( int *bit, int *byte, int *glyph, int *scan );
extern Bool FontFileRegisterRenderer ( FontRendererPtr renderer );
extern Bool FontFilePriorityRegisterRenderer ( FontRendererPtr renderer,
int priority );
extern FontRendererPtr FontFileMatchRenderer ( char *fileName );
extern Bool FontFileAddScaledInstance ( FontEntryPtr entry,
FontScalablePtr vals, FontPtr pFont,
char *bitmapName );
extern void FontFileSwitchStringsToBitmapPointers ( FontDirectoryPtr dir );
extern void FontFileRemoveScaledInstance ( FontEntryPtr entry, FontPtr pFont );
extern Bool FontFileCompleteXLFD ( FontScalablePtr vals, FontScalablePtr def );
extern FontScaledPtr FontFileFindScaledInstance ( FontEntryPtr entry,
FontScalablePtr vals,
int noSpecificSize );
extern Bool FontFileRegisterBitmapSource ( FontPathElementPtr fpe );
extern void FontFileUnregisterBitmapSource ( FontPathElementPtr fpe );
extern void FontFileEmptyBitmapSource ( void );
extern int FontFileMatchBitmapSource ( FontPathElementPtr fpe,
FontPtr *pFont, int flags,
FontEntryPtr entry,
FontNamePtr zeroPat,
FontScalablePtr vals,
fsBitmapFormat format,
fsBitmapFormatMask fmask,
Bool noSpecificSize );
extern int FontFileReadDirectory ( char *directory, FontDirectoryPtr *pdir );
extern Bool FontFileDirectoryChanged ( FontDirectoryPtr dir );
#endif /* _FONTFILE_H_ */
| 42.305556 | 79 | 0.75719 |
ef2abcf6847a94f83837ffe350bb4870b00fda37 | 30 | h | C | contrib/depends/SDKs/MacOSX10.11.sdk/System/Library/Frameworks/QuartzCore.framework/Versions/A/Headers/CVBase.h | Amity-Network/amity | 3e57379f01af4ca851079c8e469fbda7c8165b47 | [
"MIT"
] | null | null | null | contrib/depends/SDKs/MacOSX10.11.sdk/System/Library/Frameworks/QuartzCore.framework/Versions/A/Headers/CVBase.h | Amity-Network/amity | 3e57379f01af4ca851079c8e469fbda7c8165b47 | [
"MIT"
] | null | null | null | contrib/depends/SDKs/MacOSX10.11.sdk/System/Library/Frameworks/QuartzCore.framework/Versions/A/Headers/CVBase.h | Amity-Network/amity | 3e57379f01af4ca851079c8e469fbda7c8165b47 | [
"MIT"
] | 1 | 2021-08-13T21:12:07.000Z | 2021-08-13T21:12:07.000Z | #include <CoreVideo/CVBase.h>
| 15 | 29 | 0.766667 |
3711cccf083bf02936e5b382f19ba9688dea9830 | 33,313 | c | C | kern/drivers/dev/proc.c | goovdl/akaros | 26fafec0d2e65d16839316b1517de9cf86c53059 | [
"LPL-1.02"
] | null | null | null | kern/drivers/dev/proc.c | goovdl/akaros | 26fafec0d2e65d16839316b1517de9cf86c53059 | [
"LPL-1.02"
] | null | null | null | kern/drivers/dev/proc.c | goovdl/akaros | 26fafec0d2e65d16839316b1517de9cf86c53059 | [
"LPL-1.02"
] | null | null | null | /*
* This file is part of the UCB release of Plan 9. It is subject to the license
* terms in the LICENSE file found in the top-level directory of this
* distribution and at http://akaros.cs.berkeley.edu/files/Plan9License. No
* part of the UCB release of Plan 9, including this file, may be copied,
* modified, propagated, or distributed except according to the terms contained
* in the LICENSE file.
*/
//#define DEBUG
/* proc on plan 9 has lots of capabilities, some of which we might
* want for akaros:
* debug control
* event tracing
* process control (no need for signal system call, etc.)
* textual status
* rather than excise code that won't work, I'm bracketing it with
* #if 0 until we know we don't want it
*/
#include <vfs.h>
#include <kfs.h>
#include <slab.h>
#include <kmalloc.h>
#include <kref.h>
#include <string.h>
#include <stdio.h>
#include <assert.h>
#include <error.h>
#include <cpio.h>
#include <pmap.h>
#include <smp.h>
#include <arch/vmm/vmm.h>
enum {
Qdir,
Qtrace,
Qtracepids,
Qns,
Qargs,
Qctl,
Qfd,
Qfpregs,
Qkregs,
Qmem,
Qnote,
Qnoteid,
Qnotepg,
Qproc,
Qregs,
Qsegment,
Qstatus,
Qtext,
Qwait,
Qprofile,
Qsyscall,
Qcore,
};
enum {
CMclose,
CMclosefiles,
CMfixedpri,
CMhang,
CMkill,
CMnohang,
CMnoswap,
CMpri,
CMprivate,
CMprofile,
CMstart,
CMstartstop,
CMstartsyscall,
CMstop,
CMwaitstop,
CMwired,
CMtrace,
CMcore,
CMvminit,
CMvmstart,
CMvmkill,
};
enum {
Nevents = 0x4000,
Emask = Nevents - 1,
Ntracedpids = 1024,
STATSIZE = 8 + 1 + 10 + 1 + 6 + 2,
};
/*
* Status, fd, and ns are left fully readable (0444) because of their use in debugging,
* particularly on shared servers.
* Arguably, ns and fd shouldn't be readable; if you'd prefer, change them to 0000
*/
struct dirtab procdir[] = {
{"args", {Qargs}, 0, 0660},
{"ctl", {Qctl}, 0, 0660},
{"fd", {Qfd}, 0, 0444},
{"fpregs", {Qfpregs}, 0, 0000},
// {"kregs", {Qkregs}, sizeof(Ureg), 0600},
{"mem", {Qmem}, 0, 0000},
{"note", {Qnote}, 0, 0000},
{"noteid", {Qnoteid}, 0, 0664},
{"notepg", {Qnotepg}, 0, 0000},
{"ns", {Qns}, 0, 0444},
{"proc", {Qproc}, 0, 0400},
// {"regs", {Qregs}, sizeof(Ureg), 0000},
{"segment", {Qsegment}, 0, 0444},
{"status", {Qstatus}, STATSIZE, 0444},
{"text", {Qtext}, 0, 0000},
{"wait", {Qwait}, 0, 0400},
{"profile", {Qprofile}, 0, 0400},
{"syscall", {Qsyscall}, 0, 0400},
{"core", {Qcore}, 0, 0444},
};
static
struct cmdtab proccmd[] = {
{CMclose, "close", 2},
{CMclosefiles, "closefiles", 1},
{CMfixedpri, "fixedpri", 2},
{CMhang, "hang", 1},
{CMnohang, "nohang", 1},
{CMnoswap, "noswap", 1},
{CMkill, "kill", 1},
{CMpri, "pri", 2},
{CMprivate, "private", 1},
{CMprofile, "profile", 1},
{CMstart, "start", 1},
{CMstartstop, "startstop", 1},
{CMstartsyscall, "startsyscall", 1},
{CMstop, "stop", 1},
{CMwaitstop, "waitstop", 1},
{CMwired, "wired", 2},
{CMtrace, "trace", 0},
{CMcore, "core", 2},
{CMcore, "core", 2},
{CMcore, "core", 2},
{CMvminit, "vminit", 0},
{CMvmstart, "vmstart", 0},
{CMvmkill, "vmkill", 0},
};
/*
* struct qids are, in path:
* 5 bits of file type (qids above) (old comment said 4 here)
* 23 bits of process slot number + 1 (pid + 1 is stored)
* in vers,
* 32 bits of pid, for consistency checking
* If notepg, c->pgrpid.path is pgrp slot, .vers is noteid.
*/
#define QSHIFT 5 /* location in qid of proc slot # */
#define SLOTBITS 23 /* number of bits in the slot */
#define QIDMASK ((1<<QSHIFT)-1)
#define SLOTMASK (((1<<SLOTBITS)-1) << QSHIFT)
#define QID(q) ((((uint32_t)(q).path)&QIDMASK)>>0)
#define SLOT(q) (((((uint32_t)(q).path)&SLOTMASK)>>QSHIFT)-1)
#define PID(q) ((q).vers)
#define NOTEID(q) ((q).vers)
static void procctlreq(struct proc *, char *, int);
static int procctlmemio(struct proc *, uintptr_t, int, void *, int);
//static struct chan* proctext(struct chan*, struct proc*);
//static Segment* txt2data(struct proc*, Segment*);
//static int procstopped(void*);
static void mntscan(struct mntwalk *, struct proc *);
//static Traceevent *tevents;
static char *tpids, *tpidsc, *tpidse;
static spinlock_t tlock;
static int topens;
static int tproduced, tconsumed;
//static void notrace(struct proc*, int, int64_t);
//void (*proctrace)(struct proc*, int, int64_t) = notrace;
#if 0
static void profclock(Ureg * ur, Timer *)
{
Tos *tos;
if (up == NULL || current->state != Running)
return;
/* user profiling clock */
if (userureg(ur)) {
tos = (Tos *) (USTKTOP - sizeof(Tos));
tos->clock += TK2MS(1);
segclock(userpc(ur));
}
}
#endif
static int
procgen(struct chan *c, char *name, struct dirtab *tab, int unused, int s,
struct dir *dp)
{
struct qid qid;
struct proc *p;
char *ename;
int pid;
uint32_t path, perm, len;
if (s == DEVDOTDOT) {
mkqid(&qid, Qdir, 0, QTDIR);
devdir(c, qid, "#p", 0, eve, 0555, dp);
return 1;
}
if (c->qid.path == Qdir) {
if (s == 0) {
strncpy(get_cur_genbuf(), "trace", GENBUF_SZ);
mkqid(&qid, Qtrace, -1, QTFILE);
devdir(c, qid, get_cur_genbuf(), 0, eve, 0444, dp);
return 1;
}
if (s == 1) {
strncpy(get_cur_genbuf(), "tracepids", GENBUF_SZ);
mkqid(&qid, Qtracepids, -1, QTFILE);
devdir(c, qid, get_cur_genbuf(), 0, eve, 0444, dp);
return 1;
}
s -= 2;
if (name != NULL) {
/* ignore s and use name to find pid */
pid = strtol(name, &ename, 10);
if (pid <= 0 || ename[0] != '\0')
return -1;
p = pid2proc(pid);
if (!p)
return -1;
/* Need to update s, so that it's the correct 'index' for our proc
* (aka, the pid). We use s later when making the qid. */
s = pid;
} else {
/* This is a shitty iterator, and the list isn't guaranteed to give
* you the same ordering twice in a row. (procs come and go). */
p = pid_nth(s);
if (!p)
return -1;
pid = p->pid;
}
snprintf(get_cur_genbuf(), GENBUF_SZ, "%u", pid);
/*
* String comparison is done in devwalk so
* name must match its formatted pid.
*/
if (name != NULL && strcmp(name, get_cur_genbuf()) != 0) {
printk("pid-name mismatch, name: %s, pid %d\n", name, pid);
kref_put(&p->p_kref);
return -1;
}
mkqid(&qid, (s + 1) << QSHIFT, pid, QTDIR);
devdir(c, qid, get_cur_genbuf(), 0, p->user, DMDIR | 0555, dp);
kref_put(&p->p_kref);
return 1;
}
if (c->qid.path == Qtrace) {
strncpy(get_cur_genbuf(), "trace", GENBUF_SZ);
mkqid(&qid, Qtrace, -1, QTFILE);
devdir(c, qid, get_cur_genbuf(), 0, eve, 0444, dp);
return 1;
}
if (c->qid.path == Qtracepids) {
strncpy(get_cur_genbuf(), "tracepids", GENBUF_SZ);
mkqid(&qid, Qtracepids, -1, QTFILE);
devdir(c, qid, get_cur_genbuf(), 0, eve, 0444, dp);
return 1;
}
if (s >= ARRAY_SIZE(procdir))
return -1;
if (tab)
panic("procgen");
tab = &procdir[s];
/* path is everything other than the QID part. Not sure from the orig code
* if they wanted just the pid part (SLOTMASK) or everything above QID */
path = c->qid.path & ~QIDMASK; /* slot component */
if ((p = pid2proc(SLOT(c->qid))) == NULL)
return -1;
perm = 0444 | tab->perm;
#if 0
if (perm == 0)
perm = p->procmode;
else /* just copy read bits */
perm |= p->procmode & 0444;
#endif
len = tab->length;
#if 0
switch (QID(c->qid)) {
case Qwait:
len = p->nwait; /* incorrect size, but >0 means there's something to read */
break;
case Qprofile:
q = p->seg[TSEG];
if (q && q->profile) {
len = (q->top - q->base) >> LRESPROF;
len *= sizeof(*q->profile);
}
break;
}
#endif
mkqid(&qid, path | tab->qid.path, c->qid.vers, QTFILE);
devdir(c, qid, tab->name, len, p->user, perm, dp);
kref_put(&p->p_kref);
return 1;
}
#if 0
static void notrace(struct proc *, Tevent, int64_t)
{
}
static spinlock_t tlck = SPINLOCK_INITIALIZER_IRQSAVE;
static void _proctrace(struct proc *p, Tevent etype, int64_t ts)
{
Traceevent *te;
int tp;
ilock(&tlck);
if (p->trace == 0 || topens == 0 || tproduced - tconsumed >= Nevents) {
iunlock(&tlck);
return;
}
tp = tproduced++;
iunlock(&tlck);
te = &tevents[tp & Emask];
te->pid = p->pid;
te->etype = etype;
if (ts == 0)
te->time = todget(NULL);
else
te->time = ts;
te->core = m->machno;
}
void proctracepid(struct proc *p)
{
if (p->trace == 1 && proctrace != notrace) {
p->trace = 2;
ilock(&tlck);
tpidsc = seprint(tpidsc, tpidse, "%d %s\n", p->pid, p->text);
iunlock(&tlck);
}
}
#endif
static void procinit(void)
{
#if 0
if (conf.nproc >= (SLOTMASK >> QSHIFT) - 1)
printd("warning: too many procs for devproc\n");
addclock0link((void (*)(void))profclock, 113); /* Relative prime to HZ */
#endif
}
static struct chan *procattach(char *spec)
{
return devattach('p', spec);
}
static struct walkqid *procwalk(struct chan *c, struct chan *nc, char **name,
int nname)
{
return devwalk(c, nc, name, nname, 0, 0, procgen);
}
static int procstat(struct chan *c, uint8_t * db, int n)
{
return devstat(c, db, n, 0, 0, procgen);
}
/*
* none can't read or write state on other
* processes. This is to contain access of
* servers running as none should they be
* subverted by, for example, a stack attack.
*/
static void nonone(struct proc *p)
{
return;
#if 0
if (p == up)
return;
if (strcmp(current->user, "none") != 0)
return;
if (iseve())
return;
error(Eperm);
#endif
}
static struct chan *procopen(struct chan *c, int omode)
{
ERRSTACK(2);
struct proc *p;
struct pgrp *pg;
struct chan *tc;
int pid;
if (c->qid.type & QTDIR)
return devopen(c, omode, 0, 0, procgen);
if (QID(c->qid) == Qtrace) {
error("proc: Qtrace: not yet");
#if 0
if (omode != OREAD)
error(Eperm);
lock(&tlock);
if (waserror()) {
unlock(&tlock);
nexterror();
}
if (topens > 0)
error("already open");
topens++;
if (tevents == NULL) {
tevents = (Traceevent *) kzmalloc(sizeof(Traceevent) * Nevents,
KMALLOC_WAIT);
if (tevents == NULL)
error(Enomem);
tpids = kzmalloc(Ntracedpids * 20, KMALLOC_WAIT);
if (tpids == NULL) {
kfree(tpids);
tpids = NULL;
error(Enomem);
}
tpidsc = tpids;
tpidse = tpids + Ntracedpids * 20;
*tpidsc = 0;
tproduced = tconsumed = 0;
}
proctrace = _proctrace;
poperror();
unlock(&tlock);
c->mode = openmode(omode);
c->flag |= COPEN;
c->offset = 0;
return c;
#endif
}
if (QID(c->qid) == Qtracepids) {
error("Proc: Qtracepids: not yet");
#if 0
if (omode != OREAD)
error(Eperm);
c->mode = openmode(omode);
c->flag |= COPEN;
c->offset = 0;
return c;
#endif
}
if ((p = pid2proc(SLOT(c->qid))) == NULL)
error(Eprocdied);
//qlock(&p->debug);
if (waserror()) {
//qunlock(&p->debug);
kref_put(&p->p_kref);
nexterror();
}
pid = PID(c->qid);
if (p->pid != pid)
error(Eprocdied);
omode = openmode(omode);
switch (QID(c->qid)) {
case Qtext:
error("notyet");
/*
if (omode != OREAD)
error(Eperm);
tc = proctext(c, p);
tc->offset = 0;
poperror();
qunlock(&p->debug);
kref_put(&p->p_kref);
cclose(c);
return tc;
*/
case Qproc:
case Qsegment:
case Qprofile:
case Qfd:
if (omode != OREAD)
error(Eperm);
break;
case Qnote:
// if (p->privatemem)
error(Eperm);
break;
case Qmem:
// if (p->privatemem)
error(Eperm);
//nonone(p);
break;
case Qargs:
case Qnoteid:
case Qwait:
case Qregs:
case Qfpregs:
case Qkregs:
case Qsyscall:
case Qcore:
nonone(p);
break;
case Qns:
if (omode != OREAD)
error(Eperm);
c->aux = kzmalloc(sizeof(struct mntwalk), KMALLOC_WAIT);
break;
case Qstatus:
case Qctl:
break;
case Qnotepg:
error("not yet");
#if 0
nonone(p);
pg = p->pgrp;
if (pg == NULL)
error(Eprocdied);
if (omode != OWRITE || pg->pgrpid == 1)
error(Eperm);
c->pgrpid.path = pg->pgrpid + 1;
c->pgrpid.vers = p->noteid;
#endif
break;
default:
poperror();
//qunlock(&p->debug);
kref_put(&p->p_kref);
printk("procopen %#llux\n", c->qid.path);
error(Egreg);
}
/* Affix pid to qid */
// if (p->state != Dead)
c->qid.vers = p->pid;
/* make sure the process slot didn't get reallocated while we were playing */
//coherence();
/* TODO: think about what we really want here. In akaros, we wouldn't have
* our pid changed like that. */
if (p->pid != pid)
error(Eprocdied);
tc = devopen(c, omode, 0, 0, procgen);
poperror();
//qunlock(&p->debug);
kref_put(&p->p_kref);
return tc;
}
static int procwstat(struct chan *c, uint8_t * db, int n)
{
ERRSTACK(2);
error("procwwstat: not yet");
#if 0
struct proc *p;
struct dir *d;
if (c->qid.type & QTDIR)
error(Eperm);
if (QID(c->qid) == Qtrace)
return devwstat(c, db, n);
if ((p = pid2proc(SLOT(c->qid))) == NULL)
error(Eprocdied);
nonone(p);
d = NULL;
qlock(&p->debug);
if (waserror()) {
qunlock(&p->debug);
kref_put(&p->p_kref);
kfree(d);
nexterror();
}
if (p->pid != PID(c->qid))
error(Eprocdied);
if (strcmp(current->user, p->user) != 0 && strcmp(current->user, eve) != 0)
error(Eperm);
d = kzmalloc(sizeof(struct dir) + n, KMALLOC_WAIT);
n = convM2D(db, n, &d[0], (char *)&d[1]);
if (n == 0)
error(Eshortstat);
if (!emptystr(d->uid) && strcmp(d->uid, p->user) != 0) {
if (strcmp(current->user, eve) != 0)
error(Eperm);
else
kstrdup(&p->user, d->uid);
}
if (d->mode != ~0UL)
p->procmode = d->mode & 0777;
poperror();
qunlock(&p->debug);
kref_put(&p->p_kref);
kfree(d);
return n;
#endif
}
#if 0
static long procoffset(long offset, char *va, int *np)
{
if (offset > 0) {
offset -= *np;
if (offset < 0) {
memmove(va, va + *np + offset, -offset);
*np = -offset;
} else
*np = 0;
}
return offset;
}
static int procqidwidth(struct chan *c)
{
char buf[32];
return sprint(buf, "%lu", c->qid.vers);
}
int procfdprint(struct chan *c, int fd, int w, char *s, int ns)
{
int n;
if (w == 0)
w = procqidwidth(c);
n = snprint(s, ns,
"%3d %.2s %C %4ud (%.16llux %*lud %.2ux) %5ld %8lld %s\n", fd,
&"r w rw"[(c->mode & 3) << 1], c->dev->dc, c->devno,
c->qid.path, w, c->qid.vers, c->qid.type, c->iounit, c->offset,
c->name->s);
return n;
}
static int procfds(struct proc *p, char *va, int count, long offset)
{
ERRSTACK(2);
struct fgrp *f;
struct chan *c;
char buf[256];
int n, i, w, ww;
char *a;
/* print to buf to avoid holding fgrp lock while writing to user space */
if (count > sizeof buf)
count = sizeof buf;
a = buf;
qlock(&p->debug);
f = p->fgrp;
if (f == NULL) {
qunlock(&p->debug);
return 0;
}
lock(f);
if (waserror()) {
unlock(f);
qunlock(&p->debug);
nexterror();
}
n = readstr(0, a, count, p->dot->name->s);
n += snprint(a + n, count - n, "\n");
offset = procoffset(offset, a, &n);
/* compute width of qid.path */
w = 0;
for (i = 0; i <= f->maxfd; i++) {
c = f->fd[i];
if (c == NULL)
continue;
ww = procqidwidth(c);
if (ww > w)
w = ww;
}
for (i = 0; i <= f->maxfd; i++) {
c = f->fd[i];
if (c == NULL)
continue;
n += procfdprint(c, i, w, a + n, count - n);
offset = procoffset(offset, a, &n);
}
poperror();
unlock(f);
qunlock(&p->debug);
/* copy result to user space, now that locks are released */
memmove(va, buf, n);
return n;
}
#endif
static void procclose(struct chan *c)
{
if (QID(c->qid) == Qtrace) {
spin_lock(&tlock);
if (topens > 0)
topens--;
/* ??
if(topens == 0)
proctrace = notrace;
*/
spin_unlock(&tlock);
}
if (QID(c->qid) == Qns && c->aux != 0)
kfree(c->aux);
}
void int2flag(int flag, char *s)
{
if (flag == 0) {
*s = '\0';
return;
}
*s++ = '-';
if (flag & MAFTER)
*s++ = 'a';
if (flag & MBEFORE)
*s++ = 'b';
if (flag & MCREATE)
*s++ = 'c';
if (flag & MCACHE)
*s++ = 'C';
*s = '\0';
}
#if 0
static char *argcpy(char *s, char *p)
{
char *t, *tp, *te;
int n;
n = p - s;
if (n > 128)
n = 128;
if (n <= 0) {
t = kzmalloc(1, KMALLOC_WAIT);
*t = 0;
return t;
}
t = kzmalloc(n, KMALLOC_WAIT);
tp = t;
te = t + n;
while (tp + 1 < te) {
for (p--; p > s && p[-1] != 0; p--) ;
tp = seprint(tp, te, "%q ", p);
if (p == s)
break;
}
if (*tp == ' ')
*tp = 0;
return t;
}
static int procargs(struct proc *p, char *buf, int nbuf)
{
char *s;
if (p->setargs == 0) {
s = argcpy(p->args, p->args + p->nargs);
kfree(p->args);
p->nargs = strlen(s);
p->args = s;
p->setargs = 1;
}
return snprint(buf, nbuf, "%s", p->args);
}
static int eventsavailable(void *)
{
return tproduced > tconsumed;
}
#endif
static long procread(struct chan *c, void *va, long n, int64_t off)
{
ERRSTACK(5);
struct proc *p;
long l, r;
int i, j, navail, pid, rsize;
char flag[10], *sps, *srv, statbuf[512];
uintptr_t offset, u;
int tesz;
uint8_t *rptr;
struct mntwalk *mw;
if (c->qid.type & QTDIR) {
int nn;
printd("procread: dir\n");
nn = devdirread(c, va, n, 0, 0, procgen);
printd("procread: %d\n", nn);
return nn;
}
offset = off;
#if 0
if (QID(c->qid) == Qtrace) {
if (!eventsavailable(NULL))
return 0;
rptr = va;
tesz = BIT32SZ + BIT32SZ + BIT64SZ + BIT32SZ;
navail = tproduced - tconsumed;
if (navail > n / tesz)
navail = n / tesz;
while (navail > 0) {
PBIT32(rptr, tevents[tconsumed & Emask].pid);
rptr += BIT32SZ;
PBIT32(rptr, tevents[tconsumed & Emask].etype);
rptr += BIT32SZ;
PBIT64(rptr, tevents[tconsumed & Emask].time);
rptr += BIT64SZ;
PBIT32(rptr, tevents[tconsumed & Emask].core);
rptr += BIT32SZ;
tconsumed++;
navail--;
}
return rptr - (uint8_t *) va;
}
if (QID(c->qid) == Qtracepids)
if (tpids == NULL)
return 0;
else
return readstr(off, va, n, tpids);
#endif
if ((p = pid2proc(SLOT(c->qid))) == NULL)
error(Eprocdied);
if (p->pid != PID(c->qid)) {
kref_put(&p->p_kref);
error(Eprocdied);
}
switch (QID(c->qid)) {
default:
kref_put(&p->p_kref);
break;
#if 0
#warning check refcnting in here
case Qargs:
qlock(&p->debug);
j = procargs(p, current->genbuf, sizeof current->genbuf);
qunlock(&p->debug);
kref_put(&p->p_kref);
if (offset >= j)
return 0;
if (offset + n > j)
n = j - offset;
memmove(va, ¤t->genbuf[offset], n);
return n;
case Qsyscall:
if (p->syscalltrace == NULL)
return 0;
return readstr(offset, va, n, p->syscalltrace);
case Qcore:
i = 0;
ac = p->ac;
wired = p->wired;
if (ac != NULL)
i = ac->machno;
else if (wired != NULL)
i = wired->machno;
snprint(statbuf, sizeof statbuf, "%d\n", i);
return readstr(offset, va, n, statbuf);
case Qmem:
if (offset < KZERO
|| (offset >= USTKTOP - USTKSIZE && offset < USTKTOP)) {
r = procctlmemio(p, offset, n, va, 1);
kref_put(&p->p_kref);
return r;
}
if (!iseve()) {
kref_put(&p->p_kref);
error(Eperm);
}
/* validate kernel addresses */
if (offset < PTR2UINT(end)) {
if (offset + n > PTR2UINT(end))
n = PTR2UINT(end) - offset;
memmove(va, UINT2PTR(offset), n);
kref_put(&p->p_kref);
return n;
}
for (i = 0; i < nelem(conf.mem); i++) {
cm = &conf.mem[i];
/* klimit-1 because klimit might be zero! */
if (cm->kbase <= offset && offset <= cm->klimit - 1) {
if (offset + n >= cm->klimit - 1)
n = cm->klimit - offset;
memmove(va, UINT2PTR(offset), n);
kref_put(&p->p_kref);
return n;
}
}
kref_put(&p->p_kref);
error(Ebadarg);
case Qprofile:
s = p->seg[TSEG];
if (s == 0 || s->profile == 0)
error("profile is off");
i = (s->top - s->base) >> LRESPROF;
i *= sizeof(*s->profile);
if (offset >= i) {
kref_put(&p->p_kref);
return 0;
}
if (offset + n > i)
n = i - offset;
memmove(va, ((char *)s->profile) + offset, n);
kref_put(&p->p_kref);
return n;
case Qnote:
qlock(&p->debug);
if (waserror()) {
qunlock(&p->debug);
kref_put(&p->p_kref);
nexterror();
}
if (p->pid != PID(c->qid))
error(Eprocdied);
if (n < 1) /* must accept at least the '\0' */
error(Etoosmall);
if (p->nnote == 0)
n = 0;
else {
i = strlen(p->note[0].msg) + 1;
if (i > n)
i = n;
rptr = va;
memmove(rptr, p->note[0].msg, i);
rptr[i - 1] = '\0';
p->nnote--;
memmove(p->note, p->note + 1, p->nnote * sizeof(Note));
n = i;
}
if (p->nnote == 0)
p->notepending = 0;
poperror();
qunlock(&p->debug);
kref_put(&p->p_kref);
return n;
case Qproc:
if (offset >= sizeof(struct proc)) {
kref_put(&p->p_kref);
return 0;
}
if (offset + n > sizeof(struct proc))
n = sizeof(struct proc) - offset;
memmove(va, ((char *)p) + offset, n);
kref_put(&p->p_kref);
return n;
case Qregs:
rptr = (uint8_t *) p->dbgreg;
rsize = sizeof(Ureg);
regread:
if (rptr == 0) {
kref_put(&p->p_kref);
error(Enoreg);
}
if (offset >= rsize) {
kref_put(&p->p_kref);
return 0;
}
if (offset + n > rsize)
n = rsize - offset;
memmove(va, rptr + offset, n);
kref_put(&p->p_kref);
return n;
case Qkregs:
memset(&kur, 0, sizeof(Ureg));
setkernur(&kur, p);
rptr = (uint8_t *) & kur;
rsize = sizeof(Ureg);
goto regread;
case Qfpregs:
r = fpudevprocio(p, va, n, offset, 0);
kref_put(&p->p_kref);
return r;
case Qstatus:
if (offset >= STATSIZE) {
kref_put(&p->p_kref);
return 0;
}
if (offset + n > STATSIZE)
n = STATSIZE - offset;
sps = p->psstate;
if (sps == 0)
sps = statename[p->state];
memset(statbuf, ' ', sizeof statbuf);
j = 2 * KNAMELEN + 12;
snprint(statbuf, j + 1, "%-*.*s%-*.*s%-12.11s",
KNAMELEN, KNAMELEN - 1, p->text,
KNAMELEN, KNAMELEN - 1, p->user, sps);
for (i = 0; i < 6; i++) {
l = p->time[i];
if (i == TReal)
l = sys->ticks - l;
l = TK2MS(l);
readnum(0, statbuf + j + NUMSIZE * i, NUMSIZE, l, NUMSIZE);
}
/* ignore stack, which is mostly non-existent */
u = 0;
for (i = 1; i < NSEG; i++) {
s = p->seg[i];
if (s)
u += s->top - s->base;
}
readnum(0, statbuf + j + NUMSIZE * 6, NUMSIZE, u >> 10u, NUMSIZE); /* wrong size */
readnum(0, statbuf + j + NUMSIZE * 7, NUMSIZE, p->basepri, NUMSIZE);
readnum(0, statbuf + j + NUMSIZE * 8, NUMSIZE, p->priority,
NUMSIZE);
/*
* NIX: added # of traps, syscalls, and iccs
*/
readnum(0, statbuf + j + NUMSIZE * 9, NUMSIZE, p->ntrap, NUMSIZE);
readnum(0, statbuf + j + NUMSIZE * 10, NUMSIZE, p->nintr, NUMSIZE);
readnum(0, statbuf + j + NUMSIZE * 11, NUMSIZE, p->nsyscall,
NUMSIZE);
readnum(0, statbuf + j + NUMSIZE * 12, NUMSIZE, p->nicc, NUMSIZE);
readnum(0, statbuf + j + NUMSIZE * 13, NUMSIZE, p->nactrap,
NUMSIZE);
readnum(0, statbuf + j + NUMSIZE * 14, NUMSIZE, p->nacsyscall,
NUMSIZE);
memmove(va, statbuf + offset, n);
kref_put(&p->p_kref);
return n;
case Qsegment:
j = 0;
for (i = 0; i < NSEG; i++) {
sg = p->seg[i];
if (sg == 0)
continue;
j += sprint(statbuf + j, "%-6s %c%c %p %p %4d\n",
sname[sg->type & SG_TYPE],
sg->type & SG_RONLY ? 'R' : ' ',
sg->profile ? 'P' : ' ',
sg->base, sg->top, sg->ref);
}
kref_put(&p->p_kref);
if (offset >= j)
return 0;
if (offset + n > j)
n = j - offset;
if (n == 0 && offset == 0)
exhausted("segments");
memmove(va, &statbuf[offset], n);
return n;
case Qwait:
if (!canqlock(&p->qwaitr)) {
kref_put(&p->p_kref);
error(Einuse);
}
if (waserror()) {
qunlock(&p->qwaitr);
kref_put(&p->p_kref);
nexterror();
}
lock(&p->exl);
if (up == p && p->nchild == 0 && p->waitq == 0) {
unlock(&p->exl);
error(Enochild);
}
pid = p->pid;
while (p->waitq == 0) {
unlock(&p->exl);
rendez_sleep(&p->waitr, haswaitq, p);
if (p->pid != pid)
error(Eprocdied);
lock(&p->exl);
}
wq = p->waitq;
p->waitq = wq->next;
p->nwait--;
unlock(&p->exl);
poperror();
qunlock(&p->qwaitr);
kref_put(&p->p_kref);
n = snprint(va, n, "%d %lu %lud %lud %q",
wq->w.pid,
wq->w.time[TUser], wq->w.time[TSys], wq->w.time[TReal],
wq->w.msg);
kfree(wq);
return n;
#endif
case Qstatus:{
/* the extra 2 is paranoia */
char buf[8 + 1 + PROC_PROGNAME_SZ + 1 + 10 + 1 + 6 + 2];
snprintf(buf, sizeof(buf),
"%8d %-*s %-10s %6d", p->pid, PROC_PROGNAME_SZ,
p->progname, procstate2str(p->state),
p->ppid);
kref_put(&p->p_kref);
return readstr(off, va, n, buf);
}
case Qns:
//qlock(&p->debug);
if (waserror()) {
//qunlock(&p->debug);
kref_put(&p->p_kref);
nexterror();
}
if (p->pgrp == NULL || p->pid != PID(c->qid))
error(Eprocdied);
mw = c->aux;
if (mw->cddone) {
poperror();
//qunlock(&p->debug);
kref_put(&p->p_kref);
return 0;
}
mntscan(mw, p);
if (mw->mh == 0) {
mw->cddone = 1;
i = snprintf(va, n, "cd %s\n", p->dot->name->s);
poperror();
//qunlock(&p->debug);
kref_put(&p->p_kref);
return i;
}
int2flag(mw->cm->mflag, flag);
if (strcmp(mw->cm->to->name->s, "#M") == 0) {
srv = srvname(mw->cm->to->mchan);
i = snprintf(va, n, "mount %s %s %s %s\n", flag,
srv == NULL ? mw->cm->to->mchan->name->s : srv,
mw->mh->from->name->s,
mw->cm->spec ? mw->cm->spec : "");
kfree(srv);
} else
i = snprintf(va, n, "bind %s %s %s\n", flag,
mw->cm->to->name->s, mw->mh->from->name->s);
poperror();
//qunlock(&p->debug);
kref_put(&p->p_kref);
return i;
#if 0
case Qnoteid:
r = readnum(offset, va, n, p->noteid, NUMSIZE);
kref_put(&p->p_kref);
return r;
case Qfd:
r = procfds(p, va, n, offset);
kref_put(&p->p_kref);
return r;
#endif
}
error(Egreg);
return 0; /* not reached */
}
static void mntscan(struct mntwalk *mw, struct proc *p)
{
struct pgrp *pg;
struct mount *t;
struct mhead *f;
int best, i, last, nxt;
pg = p->pgrp;
rlock(&pg->ns);
nxt = 0;
best = (int)(~0U >> 1); /* largest 2's complement int */
last = 0;
if (mw->mh)
last = mw->cm->mountid;
for (i = 0; i < MNTHASH; i++) {
for (f = pg->mnthash[i]; f; f = f->hash) {
for (t = f->mount; t; t = t->next) {
if (mw->mh == 0 || (t->mountid > last && t->mountid < best)) {
mw->cm = t;
mw->mh = f;
best = mw->cm->mountid;
nxt = 1;
}
}
}
}
if (nxt == 0)
mw->mh = 0;
runlock(&pg->ns);
}
static long procwrite(struct chan *c, void *va, long n, int64_t off)
{
ERRSTACK(2);
struct proc *p, *t;
int i, id, l;
char *args;
uintptr_t offset;
if (c->qid.type & QTDIR)
error(Eisdir);
if ((p = pid2proc(SLOT(c->qid))) == NULL)
error(Eprocdied);
if (waserror()) {
kref_put(&p->p_kref);
nexterror();
}
if (p->pid != PID(c->qid))
error(Eprocdied);
offset = off;
switch (QID(c->qid)) {
#if 0
case Qargs:
if (n == 0)
error(Eshort);
if (n >= sizeof buf - strlen(p->text) - 1)
error(Etoobig);
l = snprintf(buf, sizeof buf, "%s [%s]", p->text, (char *)va);
args = kzmalloc(l + 1, KMALLOC_WAIT);
if (args == NULL)
error(Enomem);
memmove(args, buf, l);
args[l] = 0;
kfree(p->args);
p->nargs = l;
p->args = args;
p->setargs = 1;
break;
case Qmem:
if (p->state != Stopped)
error(Ebadctl);
n = procctlmemio(p, offset, n, va, 0);
break;
case Qregs:
if (offset >= sizeof(Ureg))
n = 0;
else if (offset + n > sizeof(Ureg))
n = sizeof(Ureg) - offset;
if (p->dbgreg == 0)
error(Enoreg);
setregisters(p->dbgreg, (char *)(p->dbgreg) + offset, va, n);
break;
case Qfpregs:
n = fpudevprocio(p, va, n, offset, 1);
break;
#endif
case Qctl:
procctlreq(p, va, n);
break;
default:
poperror();
kref_put(&p->p_kref);
error("unknown qid %#llux in procwrite\n", c->qid.path);
}
poperror();
kref_put(&p->p_kref);
return n;
}
struct dev procdevtab __devtab = {
'p',
"proc",
devreset,
procinit,
devshutdown,
procattach,
procwalk,
procstat,
procopen,
devcreate,
procclose,
procread,
devbread,
procwrite,
devbwrite,
devremove,
procwstat,
devpower,
devchaninfo,
};
#if 0
static struct chan *proctext(struct chan *c, struct proc *p)
{
ERRSTACK(2);
struct chan *tc;
Image *i;
Segment *s;
s = p->seg[TSEG];
if (s == 0)
error(Enonexist);
if (p->state == Dead)
error(Eprocdied);
lock(s);
i = s->image;
if (i == 0) {
unlock(s);
error(Eprocdied);
}
unlock(s);
lock(i);
if (waserror()) {
unlock(i);
nexterror();
}
tc = i->c;
if (tc == 0)
error(Eprocdied);
/* TODO: what do you want here? you can't get a kref and have the new val
* be 1. Here is the old code: if (kref_get(&tc->ref, 1) == 1 || ... ) */
if (kref_refcnt(&tc->ref, 1) == 1 || (tc->flag & COPEN) == 0
|| tc->mode != OREAD) {
cclose(tc);
error(Eprocdied);
}
if (p->pid != PID(c->qid)) {
cclose(tc);
error(Eprocdied);
}
poperror();
unlock(i);
return tc;
}
/* TODO: this will fail at compile time, since we don't have a proc-wide rendez,
* among other things, and we'll need to rewrite this for akaros */
void procstopwait(struct proc *p, int ctl)
{
ERRSTACK(2);
int pid;
if (p->pdbg)
error(Einuse);
if (procstopped(p) || p->state == Broken)
return;
if (ctl != 0)
p->procctl = ctl;
p->pdbg = up;
pid = p->pid;
qunlock(&p->debug);
current->psstate = "Stopwait";
if (waserror()) {
p->pdbg = 0;
qlock(&p->debug);
nexterror();
}
rendez_sleep(¤t->sleep, procstopped, p);
poperror();
qlock(&p->debug);
if (p->pid != pid)
error(Eprocdied);
}
#endif
static void procctlcloseone(struct proc *p, int fd)
{
// TODO: resolve this and sys_close
struct file *file = get_file_from_fd(&p->open_files, fd);
int retval = 0;
printd("%s %d\n", __func__, fd);
/* VFS */
if (file) {
put_file_from_fd(&p->open_files, fd);
kref_put(&file->f_kref); /* Drop the ref from get_file */
return;
}
/* 9ns, should also handle errors (bad FD, etc) */
retval = sysclose(fd);
return;
//sys_close(p, fd);
}
void procctlclosefiles(struct proc *p, int all, int fd)
{
int i;
if (all)
for (i = 0; i < NR_FILE_DESC_MAX; i++)
procctlcloseone(p, i);
else
procctlcloseone(p, fd);
}
static void procctlreq(struct proc *p, char *va, int n)
{
ERRSTACK(1);
int8_t irq_state = 0;
int npc, pri, core;
struct cmdbuf *cb;
struct cmdtab *ct;
int64_t time;
char *e;
cb = parsecmd(va, n);
if (waserror()) {
kfree(cb);
nexterror();
}
ct = lookupcmd(cb, proccmd, ARRAY_SIZE(proccmd));
switch (ct->index) {
case CMvmstart:
case CMvmkill:
default:
error("nope\n");
break;
case CMtrace:
systrace_trace_pid(p);
break;
case CMclose:
procctlclosefiles(p, 0, atoi(cb->f[1]));
break;
case CMclosefiles:
procctlclosefiles(p, 1, 0);
break;
#if 0
we may want this.Let us pause a proc.case CMhang:p->hang = 1;
break;
#endif
case CMkill:
p = pid2proc(strtol(cb->f[1], 0, 0));
if (!p)
error("No such proc\n");
enable_irqsave(&irq_state);
proc_destroy(p);
disable_irqsave(&irq_state);
proc_decref(p);
/* this is a little ghetto. it's not fully free yet, but we are also
* slowing it down by messing with it, esp with the busy waiting on a
* hyperthreaded core. */
spin_on(p->env_cr3);
break;
case CMvminit:
break;
}
poperror();
kfree(cb);
}
#if 0
static int procstopped(void *a)
{
struct proc *p = a;
return p->state == Stopped;
}
static int
procctlmemio(struct proc *p, uintptr_t offset, int n, void *va, int read)
{
KMap *k;
Pte *pte;
Page *pg;
Segment *s;
uintptr_t soff, l; /* hmmmm */
uint8_t *b;
uintmem pgsz;
for (;;) {
s = seg(p, offset, 1);
if (s == 0)
error(Ebadarg);
if (offset + n >= s->top)
n = s->top - offset;
if (!read && (s->type & SG_TYPE) == SG_TEXT)
s = txt2data(p, s);
s->steal++;
soff = offset - s->base;
if (waserror()) {
s->steal--;
nexterror();
}
if (fixfault(s, offset, read, 0, s->color) == 0)
break;
poperror();
s->steal--;
}
poperror();
pte = s->map[soff / PTEMAPMEM];
if (pte == 0)
panic("procctlmemio");
pgsz = m->pgsz[s->pgszi];
pg = pte->pages[(soff & (PTEMAPMEM - 1)) / pgsz];
if (pagedout(pg))
panic("procctlmemio1");
l = pgsz - (offset & (pgsz - 1));
if (n > l)
n = l;
k = kmap(pg);
if (waserror()) {
s->steal--;
kunmap(k);
nexterror();
}
b = (uint8_t *) VA(k);
b += offset & (pgsz - 1);
if (read == 1)
memmove(va, b, n); /* This can fault */
else
memmove(b, va, n);
poperror();
kunmap(k);
/* Ensure the process sees text page changes */
if (s->flushme)
memset(pg->cachectl, PG_TXTFLUSH, sizeof(pg->cachectl));
s->steal--;
if (read == 0)
p->newtlb = 1;
return n;
}
static Segment *txt2data(struct proc *p, Segment * s)
{
int i;
Segment *ps;
ps = newseg(SG_DATA, s->base, s->size);
ps->image = s->image;
kref_get(&ps->image->ref, 1);
ps->fstart = s->fstart;
ps->flen = s->flen;
ps->flushme = 1;
qlock(&p->seglock);
for (i = 0; i < NSEG; i++)
if (p->seg[i] == s)
break;
if (i == NSEG)
panic("segment gone");
qunlock(&s->lk);
putseg(s);
qlock(&ps->lk);
p->seg[i] = ps;
qunlock(&p->seglock);
return ps;
}
Segment *data2txt(Segment * s)
{
Segment *ps;
ps = newseg(SG_TEXT, s->base, s->size);
ps->image = s->image;
kref_get(&ps->image->ref, 1);
ps->fstart = s->fstart;
ps->flen = s->flen;
ps->flushme = 1;
return ps;
}
#endif
| 20.601732 | 87 | 0.575391 |
77573681f0bc6c4cb7a3576499ac863781ca5bbe | 602 | h | C | SoftUni/C++Programming/6.MemoryManagement/Lab/Task_2/ShopList.h | NikolovV/CPP-Language | a0b31f3cff0a764fee21546073338b2ca7f99979 | [
"MIT"
] | null | null | null | SoftUni/C++Programming/6.MemoryManagement/Lab/Task_2/ShopList.h | NikolovV/CPP-Language | a0b31f3cff0a764fee21546073338b2ca7f99979 | [
"MIT"
] | null | null | null | SoftUni/C++Programming/6.MemoryManagement/Lab/Task_2/ShopList.h | NikolovV/CPP-Language | a0b31f3cff0a764fee21546073338b2ca7f99979 | [
"MIT"
] | null | null | null | #ifndef SHOPLIST_H
#define SHOPLIST_H
class ShopList
{
public:
ShopList(){};
ShopList(unsigned int ID, std::string name) : _ID(ID), _itemName(name) {};
virtual ~ShopList() {};
bool operator==(const unsigned int &id) {if(this->_ID == id){return true;} return false;}
void set_ID(unsigned int ID) {this->_ID = ID;}
void set_name(std::string name) {this->_itemName = name;}
unsigned int get_ID() const {return this->_ID;}
std::string get_name() const {return this->_itemName;}
private:
unsigned int _ID;
std::string _itemName;
};
#endif /* SHOPLIST_H */ | 27.363636 | 93 | 0.651163 |
81cf7c564a683eb9561315cf6e291c3b1550bf08 | 4,201 | c | C | Openharmony v1.0/third_party/ltp/testcases/kernel/syscalls/chdir/chdir01.c | clkbit123/TheOpenHarmony | 0e6bcd9dee9f1a2481d762966b8bbd24baad6159 | [
"MIT"
] | 1 | 2022-02-15T08:51:55.000Z | 2022-02-15T08:51:55.000Z | hihope_neptune-oh_hid/00_src/v0.3/third_party/ltp/testcases/kernel/syscalls/chdir/chdir01.c | dawmlight/vendor_oh_fun | bc9fb50920f06cd4c27399f60076f5793043c77d | [
"Apache-2.0"
] | null | null | null | hihope_neptune-oh_hid/00_src/v0.3/third_party/ltp/testcases/kernel/syscalls/chdir/chdir01.c | dawmlight/vendor_oh_fun | bc9fb50920f06cd4c27399f60076f5793043c77d | [
"Apache-2.0"
] | null | null | null | /*
*
* Copyright (c) International Business Machines Corp., 2001
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
* the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/*
* NAME
* chdir01.c
*
* DESCRIPTION
* Check proper operation of chdir(): tests whether the
* system call can it change the current, working directory, and find a
* file there? Will it fail on a non-directory entry ?
*
* ALGORITHM
* Make a directory "Testdirectory", and create a file in it. cd into
* the directory and read the entry. It should be the file just
* created.
*
* USAGE: <for command-line>
* chdir01 [-c n] [-e] [-i n] [-I x] [-P x] [-t]
* where, -c n : Run n copies concurrently.
* -e : Turn on errno logging.
* -i n : Execute test n times.
* -I x : Execute test for x seconds.
* -P x : Pause for x seconds between iterations.
* -t : Turn on syscall timing.
*
* HISTORY
* 07/2001 Ported by Wayne Boyer
*
* RESTRICTIONS
* None
*/
#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
#include <errno.h>
#include <string.h>
#include <fcntl.h>
#include<sys/stat.h>
#include "test.h"
#include "safe_macros.h"
char *TCID = "chdir01";
int TST_TOTAL = 2;
void setup(void);
void cleanup(void);
static void checknames(char **, int, DIR *);
char testdir[40] = "";
int main(int ac, char **av)
{
DIR *ddir, *opendir();
int fd;
char *filname = "chdirtest";
char *filenames[3];
int lc;
tst_parse_opts(ac, av, NULL, NULL);
setup();
for (lc = 0; TEST_LOOPING(lc); lc++) {
tst_count = 0;
SAFE_CHDIR(cleanup, testdir);
fd = SAFE_CREAT(cleanup, filname, 0000);
SAFE_CLOSE(cleanup, fd);
if ((ddir = opendir(".")) == NULL)
tst_brkm(TBROK | TERRNO, cleanup, "opendir(.) failed");
filenames[0] = ".";
filenames[1] = "..";
filenames[2] = filname;
checknames(filenames, sizeof(filenames) / sizeof(filenames[0]),
ddir);
closedir(ddir);
TEST(chdir(filname));
if (TEST_RETURN != -1)
tst_resm(TFAIL, "call succeeded unexpectedly");
else if (TEST_ERRNO != ENOTDIR)
tst_resm(TFAIL | TTERRNO,
"failed unexpectedly; wanted ENOTDIR");
else
tst_resm(TPASS, "failed as expected with ENOTDIR");
SAFE_UNLINK(cleanup, filname);
SAFE_CHDIR(cleanup, "..");
/* ELOOP */
SAFE_SYMLINK(cleanup, "test_eloop1", "test_eloop2");
SAFE_SYMLINK(cleanup, "test_eloop2", "test_eloop1");
TEST(chdir("test_eloop1"));
if (TEST_RETURN != -1) {
tst_resm(TFAIL, "call succeeded unexpectedly");
} else if (TEST_ERRNO != ELOOP) {
tst_resm(TFAIL | TTERRNO,
"failed unexpectedly; wanted ELOOP");
} else {
tst_resm(TPASS, "failed as expected with ELOOP");
}
SAFE_UNLINK(cleanup, "test_eloop1");
SAFE_UNLINK(cleanup, "test_eloop2");
}
cleanup();
tst_exit();
}
void setup(void)
{
tst_sig(NOFORK, DEF_HANDLER, cleanup);
umask(0);
TEST_PAUSE;
tst_tmpdir();
sprintf(testdir, "Testdir.%d", getpid());
SAFE_MKDIR(cleanup, testdir, 0700);
}
void cleanup(void)
{
tst_rmdir();
}
void checknames(char **pfilnames, int fnamecount, DIR * ddir)
{
struct dirent *dir;
int i, found;
found = 0;
while ((dir = readdir(ddir)) != NULL) {
for (i = 0; i < fnamecount; i++) {
/*
* if dir->d_name is not null terminated it is a bug
* anyway
*/
if (strcmp(pfilnames[i], dir->d_name) == 0) {
tst_resm(TINFO, "Found file %s", dir->d_name);
found++;
}
}
}
if (found < fnamecount) {
tst_brkm(TFAIL, cleanup,
"Some files do not exist, but they must exist");
}
}
| 23.082418 | 81 | 0.645561 |
def591073886e3f0e3f52d0ca890dd02926eb5b6 | 2,527 | h | C | extensions/renderer/extension_port.h | xzhan96/chromium.src | 1bd0cf3997f947746c0fc5406a2466e7b5f6159e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 3 | 2018-02-22T18:06:56.000Z | 2021-08-28T12:49:27.000Z | extensions/renderer/extension_port.h | emilio/chromium.src | 1bd0cf3997f947746c0fc5406a2466e7b5f6159e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | extensions/renderer/extension_port.h | emilio/chromium.src | 1bd0cf3997f947746c0fc5406a2466e7b5f6159e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2017-08-16T08:15:01.000Z | 2018-03-27T00:07:30.000Z | // Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef EXTENSIONS_RENDERER_EXTENSION_PORT_H_
#define EXTENSIONS_RENDERER_EXTENSION_PORT_H_
#include <memory>
#include <vector>
#include "base/macros.h"
namespace content {
class RenderFrame;
}
namespace extensions {
struct Message;
class ScriptContext;
// A class representing information about a specific extension message port that
// handles sending related IPCs to the browser. Since global port IDs are
// assigned asynchronously, this object caches pending messages.
class ExtensionPort {
public:
ExtensionPort(ScriptContext* script_context, int local_id);
~ExtensionPort();
// Sets the global id of the port (that is, the id used in the browser
// process to send/receive messages). Any pending messages will be sent.
void SetGlobalId(int id);
// Posts a new message to the port. If the port is not initialized, the
// message will be queued until it is.
void PostExtensionMessage(std::unique_ptr<Message> message);
// Closes the port. If there are pending messages, they will still be sent
// assuming initialization completes (after which, the port will close).
void Close(bool close_channel);
int local_id() const { return local_id_; }
int global_id() const { return global_id_; }
bool initialized() const { return global_id_ != -1; }
private:
// Helper function to send the post message IPC.
void PostMessageImpl(content::RenderFrame* render_frame,
const Message& message);
// Sends the message to the browser that this port has been disconnected.
void SendDisconnected(content::RenderFrame* render_frame);
// The associated ScriptContext for this port. Since these objects are owned
// by a NativeHandler, this should always be valid.
ScriptContext* script_context_ = nullptr;
// The local id of the port (used within JS bindings).
int local_id_ = -1;
// The global id of the port (used by the browser process).
int global_id_ = -1;
// The queue of any pending messages to be sent once the port is initialized.
std::vector<std::unique_ptr<Message>> pending_messages_;
// Whether or not the port is disconnected.
bool is_disconnected_ = false;
// Whether to close the full message channel.
bool close_channel_ = false;
DISALLOW_COPY_AND_ASSIGN(ExtensionPort);
};
} // namespace extensions
#endif // EXTENSIONS_RENDERER_EXTENSION_PORT_H_
| 31.987342 | 80 | 0.747131 |
817f3771af3d4828b5943232ca9a1b689d2c647b | 914 | c | C | packages/PIPS/validation/Scilab/Scilab2C-2/src/c/cmuls.c | DVSR1966/par4all | 86b33ca9da736e832b568c5637a2381f360f1996 | [
"MIT"
] | 51 | 2015-01-31T01:51:39.000Z | 2022-02-18T02:01:50.000Z | packages/PIPS/validation/Scilab/Scilab2C-2/src/c/cmuls.c | DVSR1966/par4all | 86b33ca9da736e832b568c5637a2381f360f1996 | [
"MIT"
] | 7 | 2017-05-29T09:29:00.000Z | 2019-03-11T16:01:39.000Z | packages/PIPS/validation/Scilab/Scilab2C-2/src/c/cmuls.c | DVSR1966/par4all | 86b33ca9da736e832b568c5637a2381f360f1996 | [
"MIT"
] | 12 | 2015-03-26T08:05:38.000Z | 2022-02-18T02:01:51.000Z | /*
* Scilab ( http://www.scilab.org/ ) - This file is part of Scilab
* Copyright (C) 2008-2008 - INRIA - Arnaud TORSET
*
* This file must be used under the terms of the CeCILL.
* This source file is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at
* http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt
*
*/
#ifdef __STDC_VERSION__
# ifndef STDC
# define STDC
# endif
# if __STDC_VERSION__ >= 199901L
# ifndef STDC99
# define STDC99
# endif
# endif
#endif
#include "floatComplex.h"
#include "multiplication.h"
/*
** \function cmuls
** \brief Multiply 2 Complex numbers.
*/
floatComplex cmuls(floatComplex z1, floatComplex z2) {
#ifndef STDC99
return FloatComplex(z1.real*z2.real - z1.imag*z2.imag,
z1.real*z2.imag + z2.real*z1.imag);
#else
return z1 * z2;
#endif
}
| 21.761905 | 72 | 0.689278 |
b0ba0ddf531afe039419ce4fa997234b1bb0d5ca | 1,142 | h | C | MASConnecta/Classes/categories/NSString+MASConnecta.h | lsanches/MASConnecta | b9b7f2c0f75fea7666f206b7b6be22420fc22c04 | [
"MIT"
] | null | null | null | MASConnecta/Classes/categories/NSString+MASConnecta.h | lsanches/MASConnecta | b9b7f2c0f75fea7666f206b7b6be22420fc22c04 | [
"MIT"
] | 4 | 2017-03-30T17:26:51.000Z | 2018-03-21T22:33:32.000Z | MASConnecta/Classes/categories/NSString+MASConnecta.h | lsanches/MASConnecta | b9b7f2c0f75fea7666f206b7b6be22420fc22c04 | [
"MIT"
] | 2 | 2016-12-21T15:47:56.000Z | 2017-09-14T22:35:17.000Z | //
// NSString+MASConnecta.h
// MASConnecta
//
// Copyright (c) 2016 CA. All rights reserved.
//
// This software may be modified and distributed under the terms
// of the MIT license. See the LICENSE file for details.
//
#import <Foundation/Foundation.h>
@interface NSString (MASConnecta)
# pragma mark - Public
/**
*
*/
+ (NSString *)payloadWithString:(NSString *)message sentTime:(NSDate *)sentTime andObject:(MASObject *)masObject;
/**
* Message Payload Builder
*
* @param message <#message description#>
* @param type <#type description#>
* @param sentTime <#sentTime description#>
* @param masObject <#masObject description#>
* @param structureTopic <#structureTopic description#>
* @param topic <#topic description#>
* @param masObject <#masObject description#>
*
* @return The formatted Message
*/
+ (NSString *)payloadWithData:(NSData *)message type:(NSString *)type sentTime:(NSDate *)sentTime object:(MASObject *)masObject andTopic:(NSString *)topic;
/**
*
*/
+ (NSString *)structureTopic:(NSString *)topic forObject:(MASObject *)masObject;
@end
| 23.306122 | 155 | 0.676007 |
f73a593df29149c66130bf56bc12100afe757bc5 | 207 | h | C | code/engine.vc2008/xrManagedGameLib/API/Explosive.h | Rikoshet-234/xray-oxygen | eaac3fa4780639152684f3251b8b4452abb8e439 | [
"Apache-2.0"
] | 7 | 2018-03-27T12:36:07.000Z | 2020-06-26T11:31:52.000Z | code/engine.vc2008/xrManagedGameLib/API/Explosive.h | Rikoshet-234/xray-oxygen | eaac3fa4780639152684f3251b8b4452abb8e439 | [
"Apache-2.0"
] | 2 | 2018-05-26T23:17:14.000Z | 2019-04-14T18:33:27.000Z | code/engine.vc2008/xrManagedGameLib/API/Explosive.h | Rikoshet-234/xray-oxygen | eaac3fa4780639152684f3251b8b4452abb8e439 | [
"Apache-2.0"
] | 3 | 2020-06-26T11:41:44.000Z | 2021-09-29T19:35:04.000Z | #pragma once
#include "GameObject.h"
class CExplosiveItem;
namespace XRay
{
public ref class Explosive
{
CExplosiveItem* pGameObject;
public:
Explosive(GameObject^ pObject);
void Explode();
};
}; | 13.8 | 33 | 0.729469 |
7429c61997fc238ffa239c5c9bcf3443a4f29137 | 24,566 | c | C | libsel4vmm/src/platform/boot_guest.c | chrisguikema/seL4_libs | 1f6de1ca0b14c709151d1f1f7b55489dc48b18bf | [
"BSD-2-Clause"
] | null | null | null | libsel4vmm/src/platform/boot_guest.c | chrisguikema/seL4_libs | 1f6de1ca0b14c709151d1f1f7b55489dc48b18bf | [
"BSD-2-Clause"
] | null | null | null | libsel4vmm/src/platform/boot_guest.c | chrisguikema/seL4_libs | 1f6de1ca0b14c709151d1f1f7b55489dc48b18bf | [
"BSD-2-Clause"
] | null | null | null | /*
* Copyright 2017, Data61
* Commonwealth Scientific and Industrial Research Organisation (CSIRO)
* ABN 41 687 119 230.
*
* This software may be distributed and modified according to the terms of
* the GNU General Public License version 2. Note that NO WARRANTY is provided.
* See "LICENSE_GPLv2.txt" for details.
*
* @TAG(DATA61_GPL)
*/
/* Guest specific booting to do with elf loading and bootinfo
* manipulation */
#include <autoconf.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <cpio/cpio.h>
#include <elf/elf.h>
#include <sel4utils/mapping.h>
#include <vka/capops.h>
#include "vmm/debug.h"
#include "vmm/processor/platfeature.h"
#include "vmm/platform/boot_guest.h"
#include "vmm/platform/guest_memory.h"
#include "vmm/platform/e820.h"
#include "vmm/platform/bootinfo.h"
#include "vmm/platform/guest_vspace.h"
#include "vmm/platform/elf_helper.h"
#include "vmm/platform/acpi.h"
#include <sel4/arch/bootinfo_types.h>
#define VMM_VMCS_CR0_MASK (X86_CR0_PG | X86_CR0_PE)
#define VMM_VMCS_CR0_VALUE VMM_VMCS_CR0_MASK
// We need to own the PSE and PAE bits up until the guest has actually turned on paging,
// then it can control them
#define VMM_VMCS_CR4_MASK (X86_CR4_PSE | X86_CR4_PAE | X86_CR4_VMXE)
#define VMM_VMCS_CR4_VALUE (X86_CR4_PSE | X86_CR4_VMXE)
typedef struct boot_guest_cookie {
vmm_t *vmm;
FILE *file;
} boot_guest_cookie_t;
static int guest_elf_write_address(uintptr_t paddr, void *vaddr, size_t size, size_t offset, void *cookie) {
memcpy(vaddr, cookie + offset, size);
return 0;
}
static int guest_elf_read_address(uintptr_t paddr, void *vaddr, size_t size, size_t offset, void *cookie) {
memcpy(cookie + offset, vaddr, size);
return 0;
}
void vmm_plat_guest_elf_relocate(vmm_t *vmm, const char *relocs_filename) {
guest_image_t *image = &vmm->guest_image;
int delta = image->relocation_offset;
if (delta == 0) {
/* No relocation needed. */
return;
}
uintptr_t load_addr = image->link_paddr;
DPRINTF(1, "plat: relocating guest kernel from 0x%x --> 0x%x\n", (unsigned int)load_addr,
(unsigned int)(load_addr + delta));
/* Open the relocs file. */
DPRINTF(2, "plat: opening relocs file %s\n", relocs_filename);
size_t relocs_size = 0;
FILE *file = fopen(relocs_filename, "r");
if(!file) {
printf(COLOUR_Y "ERROR: Guest OS kernel relocation is required, but corresponding"
"%s was not found. This is most likely due to a Makefile"
"error, or configuration error.\n", relocs_filename);
panic("Relocation required but relocation data file not found.");
return;
}
fseek(file, 0, SEEK_END);
relocs_size = ftell(file);
fseek(file, 0, SEEK_SET);
/* The relocs file is the same relocs file format used by the Linux kernel decompressor to
* relocate the Linux kernel:
*
* 0 - zero terminator for 64 bit relocations
* 64 bit relocation repeated
* 0 - zero terminator for 32 bit relocations
* 32 bit relocation repeated
* <EOF>
*
* So we work backwards from the end of the file, and modify the guest kernel OS binary.
* We only support 32-bit relocations, and ignore the 64-bit data.
*
* src: Linux kernel 3.5.3 arch/x86/boot/compressed/misc.c
*/
uint32_t last_relocated_vaddr = 0xFFFFFFFF;
uint32_t num_relocations = relocs_size / sizeof(uint32_t) - 1;
for (int i = 0; ; i++) {
uint32_t vaddr;
/* Get the next relocation from the relocs file. */
uint32_t offset = relocs_size - (sizeof(uint32_t) * (i+1));
fseek(file, offset, SEEK_SET);
size_t result = fread(&vaddr, sizeof(uint32_t), 1, file);
ZF_LOGF_IF(result != 1, "Read failed unexpectedly");
if (!vaddr) {
break;
}
assert(i * sizeof(uint32_t) < relocs_size);
last_relocated_vaddr = vaddr;
/* Calculate the corresponding guest-physical address at which we have already
allocated and mapped the ELF contents into. */
assert(vaddr >= (uint32_t)image->link_vaddr);
uintptr_t guest_paddr = (uintptr_t)vaddr - (uintptr_t)image->link_vaddr +
(uintptr_t)(load_addr + delta);
// assert(vmm_guest_mem_check_elf_segment(resource, guest_paddr, guest_paddr + 4));
/* Perform the relocation. */
DPRINTF(5, " reloc vaddr 0x%x guest_addr 0x%x\n", (unsigned int)vaddr, (unsigned int)guest_paddr);
uint32_t addr;
vmm_guest_vspace_touch(&vmm->guest_mem.vspace, guest_paddr, sizeof(int),
guest_elf_read_address, &addr);
addr += delta;
vmm_guest_vspace_touch(&vmm->guest_mem.vspace, guest_paddr, sizeof(int),
guest_elf_write_address, &addr);
if (i && i % 50000 == 0) {
DPRINTF(2, " %u relocs done.\n", i);
}
}
DPRINTF(3, "plat: last relocated addr was %d\n", last_relocated_vaddr);
DPRINTF(2, "plat: %d kernel relocations completed.\n", num_relocations);
(void) last_relocated_vaddr;
if (num_relocations == 0) {
panic("Relocation required, but Kernel has not been build with CONFIG_RELOCATABLE.");
}
fclose(file);
}
static int vmm_guest_load_boot_module_continued(uintptr_t paddr, void *addr, size_t size, size_t offset, void *cookie) {
boot_guest_cookie_t *pass = ( boot_guest_cookie_t *) cookie;
fseek(pass->file, offset, SEEK_SET);
size_t result = fread(addr, size, 1, pass->file);
ZF_LOGF_IF(result != 1, "Read failed unexpectedly");
return 0;
}
int vmm_guest_load_boot_module(vmm_t *vmm, const char *name) {
uintptr_t load_addr = guest_ram_largest_free_region_start(&vmm->guest_mem);
printf("Loading boot module \"%s\" at 0x%x\n", name, (unsigned int)load_addr);
size_t initrd_size = 0;
FILE *file = fopen(name, "r");
if (!file) {
ZF_LOGE("Boot module \"%s\" not found.", name);
return -1;
}
fseek(file, 0, SEEK_END);
initrd_size = ftell(file);
fseek(file, 0, SEEK_SET);
if (!initrd_size) {
ZF_LOGE("Boot module has zero size. This is probably not what you want.");
return -1;
}
vmm->guest_image.boot_module_paddr = load_addr;
vmm->guest_image.boot_module_size = initrd_size;
guest_ram_mark_allocated(&vmm->guest_mem, load_addr, initrd_size);
boot_guest_cookie_t pass = { .vmm = vmm, .file = file};
vmm_guest_vspace_touch(&vmm->guest_mem.vspace, load_addr, initrd_size, vmm_guest_load_boot_module_continued, &pass);
printf("Guest memory after loading initrd:\n");
print_guest_ram_regions(&vmm->guest_mem);
fclose(file);
return 0;
}
static inline uint32_t vmm_plat_vesa_fbuffer_size(seL4_VBEModeInfoBlock_t *block) {
assert(block);
return ALIGN_UP(block->vbe_common.bytesPerScanLine * block->vbe12_part1.yRes, 65536);
}
static int make_guest_page_dir_continued(uintptr_t guest_phys, void *vaddr, size_t size, size_t offset, void *cookie) {
assert(offset == 0);
assert(size == BIT(seL4_PageBits));
/* Write into this frame as the init page directory: 4M pages, 1 to 1 mapping. */
uint32_t *pd = vaddr;
for (int i = 0; i < 1024; i++) {
/* Present, write, user, page size 4M */
pd[i] = (i << PAGE_BITS_4M) | 0x87;
}
return 0;
}
static int make_guest_page_dir(vmm_t *vmm) {
/* Create a 4K Page to be our 1-1 pd */
/* This is constructed with magical new memory that we will not tell Linux about */
uintptr_t pd = (uintptr_t)vspace_new_pages(&vmm->guest_mem.vspace, seL4_AllRights, 1, seL4_PageBits);
if (pd == 0) {
ZF_LOGE("Failed to allocate page for initial guest pd");
return -1;
}
printf("Guest page dir allocated at 0x%x. Creating 1-1 entries\n", (unsigned int)pd);
vmm->guest_image.pd = pd;
return vmm_guest_vspace_touch(&vmm->guest_mem.vspace, pd, BIT(seL4_PageBits), make_guest_page_dir_continued, NULL);
}
static int make_guest_cmd_line_continued(uintptr_t phys, void *vaddr, size_t size, size_t offset, void *cookie) {
/* Copy the string to this area. */
const char *cmdline = (const char*)cookie;
memcpy(vaddr, cmdline + offset, size);
return 0;
}
static int make_guest_cmd_line(vmm_t *vmm, const char *cmdline) {
/* Allocate command line from guest ram */
int len = strlen(cmdline);
uintptr_t cmd_addr = guest_ram_allocate(&vmm->guest_mem, len + 1);
if (cmd_addr == 0) {
ZF_LOGE("Failed to allocate guest cmdline (length %d)", len);
return -1;
}
printf("Constructing guest cmdline at 0x%x of size %d\n", (unsigned int)cmd_addr, len);
vmm->guest_image.cmd_line = cmd_addr;
vmm->guest_image.cmd_line_len = len;
return vmm_guest_vspace_touch(&vmm->guest_mem.vspace, cmd_addr, len + 1, make_guest_cmd_line_continued, (void*)cmdline);
}
static void make_guest_screen_info(vmm_t *vmm, struct screen_info *info) {
/* VESA information */
seL4_X86_BootInfo_VBE vbeinfo;
ssize_t result;
int error;
result = simple_get_extended_bootinfo(&vmm->host_simple, SEL4_BOOTINFO_HEADER_X86_VBE, &vbeinfo, sizeof(seL4_X86_BootInfo_VBE));
uintptr_t base = 0;
size_t fbuffer_size;
if (config_set(CONFIG_VMM_VESA_FRAMEBUFFER) && result != -1) {
/* map the protected mode interface at the same location we are told about it at.
* this is just to guarantee that it ends up within the segment addressable range */
uintptr_t pm_base = (vbeinfo.vbeInterfaceSeg << 4) + vbeinfo.vbeInterfaceOff;
error = 0;
if (pm_base > 0xc000) {
/* construct a page size and aligned region to map */
uintptr_t aligned_pm = ROUND_DOWN(pm_base, PAGE_SIZE_4K);
int size = vbeinfo.vbeInterfaceLen + (pm_base - aligned_pm);
size = ROUND_UP(size, PAGE_SIZE_4K);
error = vmm_map_guest_device_at(vmm, aligned_pm, aligned_pm, size);
}
if (error) {
ZF_LOGE("Failed to map vbe protected mode interface for VESA frame buffer. Disabling");
} else {
fbuffer_size = vmm_plat_vesa_fbuffer_size(&vbeinfo.vbeModeInfoBlock);
base = vmm_map_guest_device(vmm, vbeinfo.vbeModeInfoBlock.vbe20.physBasePtr, fbuffer_size, PAGE_SIZE_4K);
if (!base) {
ZF_LOGE("Failed to map base pointer for VESA frame buffer. Disabling");
}
}
}
if (base) {
info->orig_video_isVGA = 0x23; // Tell Linux it's a VESA mode
info->lfb_width = vbeinfo.vbeModeInfoBlock.vbe12_part1.xRes;
info->lfb_height = vbeinfo.vbeModeInfoBlock.vbe12_part1.yRes;
info->lfb_depth = vbeinfo.vbeModeInfoBlock.vbe12_part1.bitsPerPixel;
info->lfb_base = base;
info->lfb_size = fbuffer_size >> 16;
info->lfb_linelength = vbeinfo.vbeModeInfoBlock.vbe_common.bytesPerScanLine;
info->red_size = vbeinfo.vbeModeInfoBlock.vbe12_part2.redLen;
info->red_pos = vbeinfo.vbeModeInfoBlock.vbe12_part2.redOff;
info->green_size = vbeinfo.vbeModeInfoBlock.vbe12_part2.greenLen;
info->green_pos = vbeinfo.vbeModeInfoBlock.vbe12_part2.greenOff;
info->blue_size = vbeinfo.vbeModeInfoBlock.vbe12_part2.blueLen;
info->blue_pos = vbeinfo.vbeModeInfoBlock.vbe12_part2.blueOff;
info->rsvd_size = vbeinfo.vbeModeInfoBlock.vbe12_part2.rsvdLen;
info->rsvd_pos = vbeinfo.vbeModeInfoBlock.vbe12_part2.rsvdOff;
info->vesapm_seg = vbeinfo.vbeInterfaceSeg;
info->vesapm_off = vbeinfo.vbeInterfaceOff;
info->pages = vbeinfo.vbeModeInfoBlock.vbe12_part1.planes;
} else {
memset(info, 0, sizeof(*info));
}
}
static int make_guest_e820_map(struct e820entry *e820, guest_memory_t *guest_memory) {
int i;
int entry = 0;
printf("Constructing e820 memory map for guest with:\n");
print_guest_ram_regions(guest_memory);
/* Create an initial entry at 0 that is reserved */
e820[entry].addr = 0;
e820[entry].size = 0;
e820[entry].type = E820_RESERVED;
assert(guest_memory->num_ram_regions > 0);
for (i = 0; i < guest_memory->num_ram_regions; i++) {
/* Check for discontinuity. We need this check since we can have multiple
* regions that are contiguous if they have different allocation flags.
* However we are reporting ALL of this memory to the guest */
if (e820[entry].addr + e820[entry].size != guest_memory->ram_regions[i].start) {
/* Finish region. Unless it was zero sized */
if (e820[entry].size != 0) {
entry++;
assert(entry < E820MAX);
e820[entry].addr = e820[entry - 1].addr + e820[entry - 1].size;
e820[entry].type = E820_RESERVED;
}
/* Pad region */
e820[entry].size = guest_memory->ram_regions[i].start - e820[entry].addr;
/* Now start a new RAM region */
entry++;
assert(entry < E820MAX);
e820[entry].addr = guest_memory->ram_regions[i].start;
e820[entry].type = E820_RAM;
}
/* Increase region to size */
e820[entry].size = guest_memory->ram_regions[i].start - e820[entry].addr + guest_memory->ram_regions[i].size;
}
/* Create empty region at the end */
entry++;
assert(entry < E820MAX);
e820[entry].addr = e820[entry - 1].addr + e820[entry - 1].size;
e820[entry].size = 0x100000000ull - e820[entry].addr;
e820[entry].type = E820_RESERVED;
printf("Final e820 map is:\n");
for (i = 0; i <= entry; i++) {
printf("\t0x%x - 0x%x type %d\n", (unsigned int)e820[i].addr, (unsigned int)(e820[i].addr + e820[i].size), e820[i].type);
assert(e820[i].addr < e820[i].addr + e820[i].size);
}
return entry + 1;
}
static int make_guest_boot_info(vmm_t *vmm) {
/* TODO: Bootinfo struct needs to be allocated in location accessable by real mode? */
uintptr_t addr = guest_ram_allocate(&vmm->guest_mem, sizeof(struct boot_params));
if (addr == 0) {
ZF_LOGE("Failed to allocate %zu bytes for guest boot info struct", sizeof(struct boot_params));
return -1;
}
printf("Guest boot info allocated at %p. Populating...\n", (void*)addr);
vmm->guest_image.boot_info = addr;
/* Map in BIOS boot info structure. */
struct boot_params boot_info;
memset(&boot_info, 0, sizeof (struct boot_params));
/* Initialise basic bootinfo structure. Src: Linux kernel Documentation/x86/boot.txt */
boot_info.hdr.header = 0x53726448; /* Magic number 'HdrS' */
boot_info.hdr.boot_flag = 0xAA55; /* Magic number for Linux. */
boot_info.hdr.type_of_loader = 0xFF; /* Undefined loeader type. */
boot_info.hdr.code32_start = vmm->guest_image.load_paddr;
boot_info.hdr.kernel_alignment = vmm->guest_image.alignment;
boot_info.hdr.relocatable_kernel = true;
/* Set up screen information. */
/* Tell Guest OS about VESA mode. */
make_guest_screen_info(vmm, &boot_info.screen_info);
/* Create e820 memory map */
boot_info.e820_entries = make_guest_e820_map(boot_info.e820_map, &vmm->guest_mem);
/* Pass in the command line string. */
boot_info.hdr.cmd_line_ptr = vmm->guest_image.cmd_line;
boot_info.hdr.cmdline_size = vmm->guest_image.cmd_line_len;
/* These are not needed to be precise, because Linux uses these values
* only to raise an error when the decompression code cannot find good
* space. ref: GRUB2 source code loader/i386/linux.c */
boot_info.alt_mem_k = 0;//((32 * 0x100000) >> 10);
/* Pass in initramfs. */
if (vmm->guest_image.boot_module_paddr) {
boot_info.hdr.ramdisk_image = (uint32_t) vmm->guest_image.boot_module_paddr;
boot_info.hdr.ramdisk_size = vmm->guest_image.boot_module_size;
boot_info.hdr.root_dev = 0x0100;
boot_info.hdr.version = 0x0204; /* Report version 2.04 in order to report ramdisk_image. */
} else {
boot_info.hdr.version = 0x0202;
}
return vmm_guest_vspace_touch(&vmm->guest_mem.vspace, addr, sizeof(boot_info), guest_elf_write_address, &boot_info);
}
/* Init the guest page directory, cmd line args and boot info structures. */
void vmm_plat_init_guest_boot_structure(vmm_t *vmm, const char *cmdline) {
int UNUSED err;
err = make_guest_page_dir(vmm);
assert(!err);
err = make_guest_cmd_line(vmm, cmdline);
assert(!err);
err = make_guest_boot_info(vmm);
assert(!err);
err = make_guest_acpi_tables(vmm);
assert(!err);
}
void vmm_init_guest_thread_state(vmm_vcpu_t *vcpu) {
vmm_set_user_context(&vcpu->guest_state, USER_CONTEXT_EAX, 0);
vmm_set_user_context(&vcpu->guest_state, USER_CONTEXT_EBX, 0);
vmm_set_user_context(&vcpu->guest_state, USER_CONTEXT_ECX, 0);
vmm_set_user_context(&vcpu->guest_state, USER_CONTEXT_EDX, 0);
/* Entry point. */
printf("Initializing guest to start running at 0x%x\n", (unsigned int)vcpu->vmm->guest_image.entry);
vmm_guest_state_set_eip(&vcpu->guest_state, vcpu->vmm->guest_image.entry);
/* The boot_param structure. */
vmm_set_user_context(&vcpu->guest_state, USER_CONTEXT_ESI, vcpu->vmm->guest_image.boot_info);
/* Set the initial CR state */
vcpu->guest_state.virt.cr.cr0_mask = VMM_VMCS_CR0_MASK;
vcpu->guest_state.virt.cr.cr0_shadow = 0;
vcpu->guest_state.virt.cr.cr0_host_bits = VMM_VMCS_CR0_VALUE;
vcpu->guest_state.virt.cr.cr4_mask = VMM_VMCS_CR4_MASK;
vcpu->guest_state.virt.cr.cr4_shadow = 0;
vcpu->guest_state.virt.cr.cr4_host_bits = VMM_VMCS_CR4_VALUE;
/* Set the initial CR states */
vmm_guest_state_set_cr0(&vcpu->guest_state, vcpu->guest_state.virt.cr.cr0_host_bits);
vmm_guest_state_set_cr3(&vcpu->guest_state, vcpu->vmm->guest_image.pd);
vmm_guest_state_set_cr4(&vcpu->guest_state, vcpu->guest_state.virt.cr.cr4_host_bits);
/* Init guest OS vcpu state. */
vmm_vmcs_init_guest(vcpu);
}
/* TODO: Refactor and stop rewriting fucking elf loading code */
static int vmm_load_guest_segment(vmm_t *vmm, seL4_Word source_offset,
seL4_Word dest_addr, unsigned int segment_size, unsigned int file_size, FILE *file) {
int ret;
unsigned int page_size = vmm->page_size;
assert(file_size <= segment_size);
/* Allocate a cslot for duplicating frame caps */
cspacepath_t dup_slot;
ret = vka_cspace_alloc_path(&vmm->vka, &dup_slot);
if (ret) {
ZF_LOGE("Failed to allocate slot");
return ret;
}
size_t current = 0;
size_t remain = file_size;
while (current < segment_size) {
/* Retrieve the mapping */
seL4_CPtr cap;
cap = vspace_get_cap(&vmm->guest_mem.vspace, (void*)dest_addr);
if (!cap) {
ZF_LOGE("Failed to find frame cap while loading elf segment at %p", (void*)dest_addr);
return -1;
}
cspacepath_t cap_path;
vka_cspace_make_path(&vmm->vka, cap, &cap_path);
/* Copy cap and map into our vspace */
vka_cnode_copy(&dup_slot, &cap_path, seL4_AllRights);
void *map_vaddr = vspace_map_pages(&vmm->host_vspace, &dup_slot.capPtr, NULL, seL4_AllRights, 1, page_size, 1);
if (!map_vaddr) {
ZF_LOGE("Failed to map page into host vspace");
return -1;
}
/* Copy the contents of page from ELF into the mapped frame. */
size_t offset = dest_addr & ((BIT(page_size)) - 1);
void *copy_vaddr = map_vaddr + offset;
size_t copy_len = (BIT(page_size)) - offset;
if (remain > 0) {
if (copy_len > remain) {
/* Don't copy past end of data. */
copy_len = remain;
}
DPRINTF(5, "load page src %zu dest %p remain %zu offset %zu copy vaddr %p "
"copy len %zu\n", source_offset, (void*)dest_addr, remain, offset, copy_vaddr, copy_len);
fseek(file, source_offset, SEEK_SET);
size_t result = fread(copy_vaddr, copy_len, 1, file);
ZF_LOGF_IF(result != 1, "Read failed unexpectedly");
source_offset += copy_len;
remain -= copy_len;
} else {
memset(copy_vaddr, 0, copy_len);
}
dest_addr += copy_len;
current += copy_len;
/* Unamp the page and delete the temporary cap */
vspace_unmap_pages(&vmm->host_vspace, map_vaddr, 1, page_size, NULL);
vka_cnode_delete(&dup_slot);
}
return 0;
}
/* Load the actual ELF file contents into pre-allocated frames.
Used for both host and guest threads.
@param resource the thread structure for resource
@param elf_name the name of elf file
*/
/* TODO: refactor yet more elf loading code */
int vmm_load_guest_elf(vmm_t *vmm, const char *elfname, size_t alignment) {
int ret;
char elf_file[256];
elf_t elf;
DPRINTF(4, "Loading guest elf %s\n", elfname);
FILE *file = fopen(elfname, "r");
if (!file) {
ZF_LOGE("Guest elf \"%s\" not found.", elfname);
return -1;
}
ret = vmm_read_elf_headers(elf_file, vmm, file, sizeof(elf_file), &elf);
if(ret < 0) {
ZF_LOGE("Guest elf \"%s\" invalid.", elfname);
return -1;
}
unsigned int n_headers = elf_getNumProgramHeaders(&elf);
/* Find the largest guest ram region and use that for loading */
uintptr_t load_addr = guest_ram_largest_free_region_start(&vmm->guest_mem);
/* Round up by the alignemnt. We just hope its still in the memory region.
* if it isn't we will just fail when we try and get the frame */
load_addr = ROUND_UP(load_addr, alignment);
/* Calculate relocation offset. */
uintptr_t guest_kernel_addr = 0xFFFFFFFF;
uintptr_t guest_kernel_vaddr = 0xFFFFFFFF;
for (int i = 0; i < n_headers; i++) {
if (elf_getProgramHeaderType(&elf, i) != PT_LOAD) {
continue;
}
uint32_t addr = elf_getProgramHeaderPaddr(&elf, i);
if (addr < guest_kernel_addr) {
guest_kernel_addr = addr;
}
uint32_t vaddr = elf_getProgramHeaderVaddr(&elf, i);
if (vaddr < guest_kernel_vaddr) {
guest_kernel_vaddr = vaddr;
}
}
printf("Guest kernel is compiled to be located at paddr 0x%x vaddr 0x%x\n",
(unsigned int)guest_kernel_addr, (unsigned int)guest_kernel_vaddr);
printf("Guest kernel allocated 1:1 start is at paddr = 0x%x\n", (unsigned int)load_addr);
int guest_relocation_offset = (int)((int64_t)load_addr - (int64_t)guest_kernel_addr);
printf("Therefore relocation offset is %d (%s0x%x)\n",
guest_relocation_offset,
guest_relocation_offset < 0 ? "-" : "",
abs(guest_relocation_offset));
for (int i = 0; i < n_headers; i++) {
seL4_Word source_offset, dest_addr;
unsigned int file_size, segment_size;
/* Skip unloadable program headers. */
if (elf_getProgramHeaderType(&elf, i) != PT_LOAD) {
continue;
}
/* Fetch information about this segment. */
source_offset = elf_getProgramHeaderOffset(&elf, i);
file_size = elf_getProgramHeaderFileSize(&elf, i);
segment_size = elf_getProgramHeaderMemorySize(&elf, i);
dest_addr = elf_getProgramHeaderPaddr(&elf, i);
dest_addr += guest_relocation_offset;
if (!segment_size) {
/* Zero sized segment, ignore. */
continue;
}
/* Load this ELf segment. */
ret = vmm_load_guest_segment(vmm, source_offset, dest_addr, segment_size, file_size, file);
if (ret) {
return ret;
}
/* Record it as allocated */
guest_ram_mark_allocated(&vmm->guest_mem, dest_addr, segment_size);
}
/* Record the entry point. */
vmm->guest_image.entry = elf_getEntryPoint(&elf);
vmm->guest_image.entry += guest_relocation_offset;
/* Remember where we started loading the kernel to fix up relocations in future */
vmm->guest_image.load_paddr = load_addr;
vmm->guest_image.link_paddr = guest_kernel_addr;
vmm->guest_image.link_vaddr = guest_kernel_vaddr;
vmm->guest_image.relocation_offset = guest_relocation_offset;
vmm->guest_image.alignment = alignment;
printf("Guest memory layout after loading elf\n");
print_guest_ram_regions(&vmm->guest_mem);
fclose(file);
return 0;
}
| 39.242812 | 132 | 0.659489 |
dd328b55b77aa27f8d05906a23f5a96bdb6c1355 | 8,638 | c | C | TREE4OS2021/sistemioperativi/PTHREAD/NPROD_MCONS/NProdMConsKbuffer.c | andreazammarchi3/sistemi-operativi | 7742efd62e2467cebaeecb72294890dc9088ccbd | [
"MIT"
] | null | null | null | TREE4OS2021/sistemioperativi/PTHREAD/NPROD_MCONS/NProdMConsKbuffer.c | andreazammarchi3/sistemi-operativi | 7742efd62e2467cebaeecb72294890dc9088ccbd | [
"MIT"
] | null | null | null | TREE4OS2021/sistemioperativi/PTHREAD/NPROD_MCONS/NProdMConsKbuffer.c | andreazammarchi3/sistemi-operativi | 7742efd62e2467cebaeecb72294890dc9088ccbd | [
"MIT"
] | null | null | null | /* file: NProdNConsKBuffer.c
NProduttori e NConsumatori che si scambiano prodotti
mediante piu' Buffer implementati in una coda finita.
E' la versione efficente perche'
- utilizza due pthread_cond_var (una per Prod e una per Cons)
- sveglia i pthread solo quando hanno qualcosa da fare.
Nota Bene: la coda finita sfrutta la struttura dati buffer
dipendente dalle necessita' del programma applicativo
e definita nel file ../../COMMON/FINITE_QUEUE/userdefinedBuffer.h
la struttura dati FTQ definita nel file ../../COMMON/FINITE_QUEUE/finiteTailQueue.h
e le implementazioni delle funzioni init_FTQ() add_to_tail_FTQ() e remove_from_head_FTQ()
contenute nel file ../../COMMON/FINITE_QUEUE/finiteTailQueue.c
*/
#ifndef _THREAD_SAFE
#define _THREAD_SAFE
#endif
#ifndef _POSIX_C_SOURCE
#define _POSIX_C_SOURCE 200112L
#endif
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <pthread.h>
#include "printerror.h"
#include "DBGpthread.h"
/* dovremmo includere un percorso relativo,
ma preferisco definire un flag -I
per la directory con gli include
#include "../../COMMON/FINITE_QUEUE/userdefinedBuffer.h"
#include "../../COMMON/FINITE_QUEUE/finiteTailQueue.h"
*/
#include "userdefinedBuffer.h"
#include "finiteTailQueue.h"
/* settati per vedere output di debug
#define DEBUGSTAMPAAZIONI
*/
#define NUMPROD 15
#define NUMCONS 13
#define NUMBUFFER 5
/* dati da proteggere */
FTQ global_ftq; /* coda finita dei buffer */
/* variabili per la sincronizzazione */
pthread_mutex_t mutex;
pthread_cond_t condProd, condCons;
int numBufferPieni=0; /* 0 o 1 */
int numProdWaiting=0;
int numProdWaitingAndSignalled=0; /* deve essere <= #buffer vuoti */
int numConsWaiting=0;
int numConsWaitingAndSignalled=0; /* deve essere <= #buffer pieni */
void *Produttore (void *arg)
{
char Plabel[128];
char Plabelsignal[128];
int indice;
uint64_t valProdotto=0;
STRUCTUREDBUFFER buffer; /* il singolo buffer */
indice=*((int*)arg);
free(arg);
sprintf(Plabel,"P%d",indice);
sprintf(Plabelsignal,"P%d->C",indice);
while(1) {
/* QUI IL PRODUTTORE PRODUCE IL DATO, un intero.
supponiamo che il produttore impieghi circa
un secondo a produrre il dato
DBGsleep(1,Plabel);
printf("Prod %s PRODUCE dato %lu\n", Plabel, valProdotto+1 );
fflush(stdout);
*/
valProdotto++;
buffer.val=valProdotto;
DBGpthread_mutex_lock(&mutex,Plabel);
/* se tutti i buffer sono pieni allora il
produttore deve aspettare che un consumatore
lo risvegli dopo avere svuotato un posto.
In generale il problema e' che se ho NUMBUFFER buffer
ed ho numBufferPieni buffer pieni
ed ho (NUMBUFFER-numBufferPieni) buffer vuoti
ed ho numProdWaiting Produttori in coda
ed ho numProdWaitingAndSignalled Produttori
in coda e gia' abilitati a proseguire (cioe' signalled)
SE i Prod in Coda e signalled SONO >= dei buffer vuoti
cioe'
SE numProdWaitingAndSignalled >= (NUMBUFFER-numBufferPieni)
allora
NON POSSO FAR PROSEGUIRE dei Prod SENZA METTERLI NELLA CODA
*/
if( numProdWaitingAndSignalled >= (NUMBUFFER-numBufferPieni)){
#ifdef DEBUGSTAMPAAZIONI
printf("Prod %s ENTRA CODA\n",Plabel);fflush(stdout);
#endif
numProdWaiting++;
DBGpthread_cond_wait(&condProd,&mutex,Plabel);
numProdWaiting--;
numProdWaitingAndSignalled--;
}
#ifdef DEBUGSTAMPAAZIONI
else {
printf("Prod %s SALTA CODA\n",Plabel);fflush(stdout);
}
#endif
/* riempie il buffer col dato prodotto prima
in realta' per semplicita' incremento la var
*/
add_to_tail_FTQ( &global_ftq, buffer );
printf("Prod %s inserisce %lu \n", Plabel, buffer.val );
fflush(stdout);
numBufferPieni++;
/*
SE ho qualche Cons in coda non segnalato
(cioe' SE numConsWaitingAndSignalled < numConsWaiting )
E SE i Cons in Coda e signalled SONO < dei buffer pieni
(cioe' SE numConsWaitingAndSignalled < numBufferPieni) allora
POSSO ABILITARE altri Cons a proseguire e uscire dalla wait.
*/
if(
( numConsWaitingAndSignalled < numConsWaiting )
&&
( numConsWaitingAndSignalled < numBufferPieni )
) {
/* risveglio un Consumatore per svuotare un buffer */
DBGpthread_cond_signal(&condCons,Plabelsignal);
numConsWaitingAndSignalled++;
}
/* rilascio mutua esclusione */
DBGpthread_mutex_unlock(&mutex,Plabel);
}
pthread_exit(NULL);
}
void *Consumatore (void *arg)
{
char Clabel[128];
char Clabelsignal[128];
int indice;
uint64_t valPrelevato=0;
STRUCTUREDBUFFER buffer; /* il singolo buffer */
indice=*((int*)arg);
free(arg);
sprintf(Clabel,"C%d",indice);
sprintf(Clabelsignal,"C%d->P",indice);
while(1) {
DBGpthread_mutex_lock(&mutex,Clabel);
/* se tutti i buffer sono vuoti allora
aspettiamo che un Prod ci risvegli
In generale il problema e' che se ho NUMBUFFER buffer
ed ho numBufferPieni buffer pieni
ed ho numConsWaiting Cousumatori in coda
ed ho numConsWaitingAndSignalled Consumatori
in coda e gia' abilitati a proseguire (cioe' signalled)
SE i Cons in Coda e Signalled SONO >= dei buffer pieni
cioe'
SE numConsWaitingAndSignalled >= numBufferPieni
allora
NON POSSO FAR PROSEGUIRE dei Cons SENZA METTERLI NELLA CODA
*/
if( numConsWaitingAndSignalled >= numBufferPieni ) {
#ifdef DEBUGSTAMPAAZIONI
printf("Cons %s ENTRA CODA\n",Clabel);fflush(stdout);
#endif
numConsWaiting++;
DBGpthread_cond_wait(&condCons,&mutex,Clabel);
numConsWaiting--;
numConsWaitingAndSignalled--;
}
#ifdef DEBUGSTAMPAAZIONI
else {
printf("Cons %s SALTA CODA\n",Clabel);fflush(stdout);
}
#endif
/* prendo cio' che c'e' nel buffer */
remove_from_head_FTQ(&global_ftq, &buffer);
valPrelevato=buffer.val;
printf("Cons %s legge %lu \n", Clabel, valPrelevato );
fflush(stdout);
numBufferPieni--;
/*
SE i Prod in Coda e signalled SONO >= dei buffer vuoti
NON POSSO ABILITARE altri Prod in coda a proseguire
invece
SE ho qualche Prod in coda non segnalato
(cioe' SE numProdWaitingAndSignalled < numProdWaiting )
E SE i Prod in Coda e signalled SONO < dei buffer pieni
cioe'
SE numProdWaitingAndSignalled < (NUMBUFFER-numBufferPieni)
allora
POSSO ABILITARE altri Prod a proseguire e uscire dalla wait.
*/
if(
(numProdWaitingAndSignalled < numProdWaiting )
&&
(numProdWaitingAndSignalled < (NUMBUFFER-numBufferPieni))
)
{
/* risveglio 1 Prod per riempire il buffer svuotato */
DBGpthread_cond_signal(&condProd,Clabelsignal);
numProdWaitingAndSignalled++;
}
/* rilascio mutua esclusione */
DBGpthread_mutex_unlock(&mutex,Clabel);
/* fuori da mutua esclusione, uso il dato
supponiamo che ci voglia 1 secondo
printf("Cons %s USA dato %lu \n", Clabel, val );
fflush(stdout);
DBGsleep(1,Clabel);
*/
}
pthread_exit(NULL);
}
int main (int argc, char* argv[] )
{
pthread_t thProd[NUMPROD];
pthread_t thCons[NUMCONS];
int rc, i, *intptr;
void *ptr;
/* inizializzo la coda globale */
init_FTQ( NUMBUFFER, &global_ftq );
rc = pthread_cond_init(&condProd, NULL);
if( rc ) PrintERROR_andExit(rc,"pthread_cond_init failed");
rc = pthread_cond_init(&condCons, NULL);
if( rc ) PrintERROR_andExit(rc,"pthread_cond_init failed");
rc = pthread_mutex_init(&mutex, NULL);
if( rc ) PrintERROR_andExit(rc,"pthread_mutex_init failed");
/* all'inizio i Cons devono aspettare il primo Prod */
numBufferPieni=0; /* 0 o 1 */
numProdWaiting=0;
numProdWaitingAndSignalled=0;
numConsWaiting=0;
numConsWaitingAndSignalled=0;
for(i=0;i<NUMCONS;i++) {
intptr=malloc(sizeof(int));
if( !intptr ) { printf("malloc failed\n");exit(1); }
*intptr=i;
rc=pthread_create(&(thCons[i]),NULL,Consumatore,(void*)intptr);
if(rc) PrintERROR_andExit(rc,"pthread_create failed");
}
for(i=0;i<NUMPROD;i++) {
intptr=malloc(sizeof(int));
if( !intptr ) { printf("malloc failed\n");exit(1); }
*intptr=i;
rc=pthread_create(&(thProd[i]),NULL,Produttore,(void*)intptr);
if(rc) PrintERROR_andExit(rc,"pthread_create failed");
}
for(i=0;i<NUMPROD;i++) {
rc = pthread_join(thProd[i], &ptr );
if(rc) PrintERROR_andExit(rc,"pthread_join failed");
}
for(i=0;i<NUMCONS;i++) {
rc = pthread_join(thCons[i], &ptr );
if(rc) PrintERROR_andExit(rc,"pthread_join failed");
}
rc = pthread_mutex_destroy(&mutex);
if(rc) PrintERROR_andExit(rc,"pthread_mutex_destroy failed");
rc = pthread_cond_destroy(&condProd);
if(rc) PrintERROR_andExit(rc,"pthread_cond_destroy failed");
rc = pthread_cond_destroy(&condCons);
if(rc) PrintERROR_andExit(rc,"pthread_cond_destroy failed");
return(0);
}
| 28.045455 | 92 | 0.718801 |
6ee457c154d458fb959ea3c4704b0c34e826fee9 | 8,817 | h | C | kernel/lge/msm8226/sound/soc/msm/msm_audio_mvs.h | Uswer/LineageOS-14.1_jag3gds | 6fe76987fad4fca7b3c08743b067d5e79892e77f | [
"Apache-2.0"
] | 1 | 2020-06-01T10:53:47.000Z | 2020-06-01T10:53:47.000Z | kernel/lge/msm8226/sound/soc/msm/msm_audio_mvs.h | Uswer/LineageOS-14.1_jag3gds | 6fe76987fad4fca7b3c08743b067d5e79892e77f | [
"Apache-2.0"
] | 1 | 2020-05-28T13:06:06.000Z | 2020-05-28T13:13:15.000Z | kernel/lge/msm8226/sound/soc/msm/msm_audio_mvs.h | Uswer/LineageOS-14.1_jag3gds | 6fe76987fad4fca7b3c08743b067d5e79892e77f | [
"Apache-2.0"
] | null | null | null | /* Copyright (c) 2010-2011, The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
#ifndef __MSM_AUDIO_MVS_H
#define __MSM_AUDIO_MVS_H
#include <linux/msm_audio.h>
#include <linux/wakelock.h>
#include <linux/pm_qos.h>
#include <mach/msm_rpcrouter.h>
#include <mach/debug_mm.h>
#include <linux/slab.h>
#define AUDIO_GET_MVS_CONFIG _IOW(AUDIO_IOCTL_MAGIC, \
(AUDIO_MAX_COMMON_IOCTL_NUM + 0), unsigned)
#define AUDIO_SET_MVS_CONFIG _IOR(AUDIO_IOCTL_MAGIC, \
(AUDIO_MAX_COMMON_IOCTL_NUM + 1), unsigned)
#define AUDIO_SET_SCR_CONFIG _IOR(AUDIO_IOCTL_MAGIC, \
(AUDIO_MAX_COMMON_IOCTL_NUM + 2), unsigned)
#define AUDIO_SET_DTX_CONFIG _IOR(AUDIO_IOCTL_MAGIC, \
(AUDIO_MAX_COMMON_IOCTL_NUM + 3), unsigned)
/* MVS modes */
#define MVS_MODE_LINEAR_PCM 9
#define MVS_PROG 0x30000014
#define MVS_VERS 0x00030001
#define MVS_CLIENT_ID_VOIP 0x00000003 /* MVS_CLIENT_VOIP */
#define MVS_ACQUIRE_PROC 4
#define MVS_ENABLE_PROC 5
#define MVS_RELEASE_PROC 6
#define MVS_SET_PCM_MODE_PROC 9
#define MVS_EVENT_CB_TYPE_PROC 1
#define MVS_PACKET_UL_FN_TYPE_PROC 2
#define MVS_PACKET_DL_FN_TYPE_PROC 3
#define MVS_CB_FUNC_ID 0xAAAABBBB
#define MVS_UL_CB_FUNC_ID 0xBBBBCCCC
#define MVS_DL_CB_FUNC_ID 0xCCCCDDDD
/* MVS frame modes */
#define MVS_FRAME_MODE_PCM_UL 13
#define MVS_FRAME_MODE_PCM_DL 14
/* MVS context */
#define MVS_PKT_CONTEXT_ISR 0x00000001
/* Max voc packet size */
#define MVS_MAX_VOC_PKT_SIZE 320
#define VOIP_MAX_Q_LEN 20
#define MVS_MAX_Q_LEN 8
#define RPC_TYPE_REQUEST 0
#define RPC_TYPE_REPLY 1
#define RPC_STATUS_FAILURE 0
#define RPC_STATUS_SUCCESS 1
#define RPC_STATUS_REJECT 1
#define RPC_COMMON_HDR_SZ (sizeof(uint32_t) * 2)
#define RPC_REQUEST_HDR_SZ (sizeof(struct rpc_request_hdr))
#define RPC_REPLY_HDR_SZ (sizeof(uint32_t) * 3)
enum audio_mvs_state_type { AUDIO_MVS_CLOSED, AUDIO_MVS_OPENED,
AUDIO_MVS_PREPARING, AUDIO_MVS_ACQUIRE, AUDIO_MVS_ENABLED,
AUDIO_MVS_CLOSING
};
enum audio_mvs_event_type { AUDIO_MVS_COMMAND, AUDIO_MVS_MODE,
AUDIO_MVS_NOTIFY
};
enum audio_mvs_cmd_status_type { AUDIO_MVS_CMD_FAILURE, AUDIO_MVS_CMD_BUSY,
AUDIO_MVS_CMD_SUCCESS
};
enum audio_mvs_mode_status_type { AUDIO_MVS_MODE_NOT_AVAIL,
AUDIO_MVS_MODE_INIT, AUDIO_MVS_MODE_READY
};
enum audio_mvs_pkt_status_type { AUDIO_MVS_PKT_NORMAL, AUDIO_MVS_PKT_FAST,
AUDIO_MVS_PKT_SLOW
};
struct rpc_audio_mvs_acquire_args {
uint32_t client_id;
uint32_t cb_func_id;
};
struct audio_mvs_acquire_msg {
struct rpc_request_hdr rpc_hdr;
struct rpc_audio_mvs_acquire_args acquire_args;
};
struct rpc_audio_mvs_enable_args {
uint32_t client_id;
uint32_t mode;
uint32_t ul_cb_func_id;
uint32_t dl_cb_func_id;
uint32_t context;
};
struct audio_mvs_enable_msg {
struct rpc_request_hdr rpc_hdr;
struct rpc_audio_mvs_enable_args enable_args;
};
struct audio_mvs_release_msg {
struct rpc_request_hdr rpc_hdr;
uint32_t client_id;
};
struct audio_mvs_set_pcm_mode_msg {
struct rpc_request_hdr rpc_hdr;
uint32_t pcm_mode;
};
struct audio_mvs_set_pcmwb_mode_msg {
struct rpc_request_hdr rpc_hdr;
uint32_t pcmwb_mode;
};
struct audio_mvs_buffer {
uint8_t *voc_pkt;
uint32_t len;
};
union audio_mvs_event_data {
struct mvs_ev_command_type {
uint32_t event;
uint32_t client_id;
uint32_t cmd_status;
} mvs_ev_command_type;
struct mvs_ev_mode_type {
uint32_t event;
uint32_t client_id;
uint32_t mode_status;
uint32_t mode;
} mvs_ev_mode_type;
struct mvs_ev_notify_type {
uint32_t event;
uint32_t client_id;
uint32_t buf_dir;
uint32_t max_frames;
} mvs_ev_notify_type;
};
struct audio_mvs_cb_func_args {
uint32_t cb_func_id;
uint32_t valid_ptr;
uint32_t event;
union audio_mvs_event_data event_data;
};
struct audio_mvs_frame_info_hdr {
uint32_t frame_mode;
uint32_t mvs_mode;
uint32_t buf_free_cnt;
};
struct audio_mvs_ul_cb_func_args {
uint32_t cb_func_id;
uint32_t pkt_len;
uint32_t voc_pkt[MVS_MAX_VOC_PKT_SIZE / 4];
uint32_t valid_ptr;
uint32_t frame_mode;
uint32_t frame_mode_ignore;
struct audio_mvs_frame_info_hdr frame_info_hdr;
uint32_t pcm_frame;
uint32_t pcm_mode;
uint32_t pkt_len_ignore;
};
struct audio_mvs_ul_reply {
struct rpc_reply_hdr reply_hdr;
uint32_t valid_pkt_status_ptr;
uint32_t pkt_status;
};
struct audio_mvs_dl_cb_func_args {
uint32_t cb_func_id;
uint32_t valid_ptr;
uint32_t frame_mode;
uint32_t frame_mode_ignore;
struct audio_mvs_frame_info_hdr frame_info_hdr;
uint32_t pcm_frame;
uint32_t pcm_mode;
};
struct audio_mvs_dl_reply {
struct rpc_reply_hdr reply_hdr;
uint32_t voc_pkt[MVS_MAX_VOC_PKT_SIZE / 4];
uint32_t valid_frame_info_ptr;
uint32_t frame_mode;
uint32_t frame_mode_again;
struct audio_mvs_frame_info_hdr frame_info_hdr;
uint32_t pcm_frame;
uint32_t pcm_mode;
uint32_t valid_pkt_status_ptr;
uint32_t pkt_status;
};
struct audio_mvs_info_type {
enum audio_mvs_state_type state;
uint32_t frame_mode;
uint32_t mvs_mode;
uint32_t buf_free_cnt;
uint32_t pcm_frame;
uint32_t pcm_mode;
uint32_t out_sample_rate;
uint32_t out_channel_mode;
uint32_t out_weight;
uint32_t out_buffer_size;
int dl_play;
struct msm_rpc_endpoint *rpc_endpt;
uint32_t rpc_prog;
uint32_t rpc_ver;
uint32_t rpc_status;
unsigned int pcm_size;
unsigned int pcm_count;
unsigned int pcm_playback_irq_pos; /* IRQ position */
unsigned int pcm_playback_buf_pos; /* position in buffer */
unsigned int pcm_capture_size;
unsigned int pcm_capture_count;
unsigned int pcm_capture_irq_pos; /* IRQ position */
unsigned int pcm_capture_buf_pos; /* position in buffer */
uint32_t samp_rate;
uint32_t channel_mode;
uint8_t *mem_chunk;
struct snd_pcm_substream *playback_substream;
struct snd_pcm_substream *capture_substream;
struct audio_mvs_buffer in[MVS_MAX_Q_LEN];
uint32_t in_read;
uint32_t in_write;
struct audio_mvs_buffer out[MVS_MAX_Q_LEN];
uint32_t out_read;
uint32_t out_write;
struct task_struct *task;
wait_queue_head_t wait;
wait_queue_head_t prepare_wait;
wait_queue_head_t out_wait;
wait_queue_head_t in_wait;
struct mutex lock;
struct mutex prepare_lock;
struct mutex in_lock;
struct mutex out_lock;
struct wake_lock suspend_lock;
struct pm_qos_request pm_qos_req;
struct timer_list timer;
unsigned long expiry;
int ack_dl_count;
int ack_ul_count;
int prepare_ack;
int playback_start;
int capture_start;
unsigned long expiry_delta;
int mvs_enable;
int playback_enable;
int capture_enable;
int instance;
};
struct audio_voip_info_type {
enum audio_mvs_state_type state;
enum audio_mvs_state_type playback_state;
enum audio_mvs_state_type capture_state;
unsigned int pcm_playback_size;
unsigned int pcm_count;
unsigned int pcm_playback_irq_pos; /* IRQ position */
unsigned int pcm_playback_buf_pos; /* position in buffer */
unsigned int pcm_capture_size;
unsigned int pcm_capture_count;
unsigned int pcm_capture_irq_pos; /* IRQ position */
unsigned int pcm_capture_buf_pos; /* position in buffer */
struct snd_pcm_substream *playback_substream;
struct snd_pcm_substream *capture_substream;
struct audio_mvs_buffer in[VOIP_MAX_Q_LEN];
uint32_t in_read;
uint32_t in_write;
struct audio_mvs_buffer out[VOIP_MAX_Q_LEN];
uint32_t out_read;
uint32_t out_write;
wait_queue_head_t out_wait;
wait_queue_head_t in_wait;
struct mutex lock;
struct mutex prepare_lock;
struct wake_lock suspend_lock;
struct pm_qos_request pm_qos_req;
int playback_start;
int capture_start;
int instance;
};
enum msm_audio_pcm_frame_type {
MVS_AMR_SPEECH_GOOD, /* Good speech frame */
MVS_AMR_SPEECH_DEGRADED, /* Speech degraded */
MVS_AMR_ONSET, /* onset */
MVS_AMR_SPEECH_BAD, /* Corrupt speech frame (bad CRC) */
MVS_AMR_SID_FIRST, /* First silence descriptor */
MVS_AMR_SID_UPDATE, /* Comfort noise frame */
MVS_AMR_SID_BAD, /* Corrupt SID frame (bad CRC) */
MVS_AMR_NO_DATA, /* Nothing to transmit */
MVS_AMR_SPEECH_LOST, /* downlink speech lost */
};
enum msm_audio_dtx_mode_type { MVS_DTX_OFF, MVS_DTX_ON
};
struct msm_audio_mvs_config {
uint32_t mvs_mode;
uint32_t bit_rate;
};
extern struct snd_soc_dai_driver msm_mvs_dais[2];
extern struct snd_soc_codec_device soc_codec_dev_msm_mvs;
extern struct snd_soc_platform_driver msm_mvs_soc_platform;
extern struct snd_soc_platform_driver msm_voip_soc_platform;
#endif /* __MSM_AUDIO_MVS_H */
| 23.82973 | 75 | 0.797323 |
2d9c310290d4d5c7c6a29494f70e968be4cf96b7 | 3,854 | h | C | src/ostinato/odevva.h | saitofuyuki/icies2 | 7879532a6f795827d5cc9ea2d5ada753b25a18c5 | [
"Apache-2.0"
] | null | null | null | src/ostinato/odevva.h | saitofuyuki/icies2 | 7879532a6f795827d5cc9ea2d5ada753b25a18c5 | [
"Apache-2.0"
] | null | null | null | src/ostinato/odevva.h | saitofuyuki/icies2 | 7879532a6f795827d5cc9ea2d5ada753b25a18c5 | [
"Apache-2.0"
] | null | null | null | C ostinato/odevva.h --- Definition for IcIES/Development/VIO
C Maintainer: SAITO Fuyuki
C Created: Jan 20 2012
#ifdef HEADER_PROPERTY
#define _TSTAMP 'Time-stamp: <2013/09/30 09:52:16 fuyuki odevva.h>'
#define _FNAME 'ostinato/odevva.h'
#define _REV 'Snoopy0.9'
#endif /* HEADER_PROPERTY */
CCC_! MANIFESTO
C
C Copyright (C) 2010--2020
C Japan Agency for Marine-Earth Science and Technology,
C Ayako ABE-OUCHI
C
C Licensed under the Apache License, Version 2.0
C (https://www.apache.org/licenses/LICENSE-2.0)
C
CCC_* Definitions
#ifndef _ODEVVA_H
# define _ODEVVA_H
#include "odevel.h"
#include "olimit.h"
CCC_* Error
#define VIO_ERR_NO_UNIT -31
#define VIO_ERR_NO_RECORD -33 /* no record on direct mode */
#define VIO_ERR_EOF 64 /* end of file */
CCC_* arbitrary ID for access report
#define VIO_ACCESS_ID_MAX 4
CC #define INFO_NAN (_INT_MIN)
#define INFO_NAN (-_INT_MAX) /* gfortran 4.6 bug? */
CCC_* Attributes cluster
#define VIO_UNIT 1 /* file unit */
#define VIO_RECI 2 /* record (phisical) index */
#define VIO_LOGI 3 /* record (logical) index */
#define VIO_RECC 4 /* record (phisical) count */
#define VIO_LOGC 5 /* record (logical) count */
#define VIO_RLEN 6 /* record length */
#define VIO_RBYT 7 /* record length in bytes */
#define VIO_CINT 8 /* close/open interval */
#define VIO_CSTP 9 /* close/open steps */
#define VIO_PACT 10 /* action */
#define VIO_FORM 11 /* form */
#define VIO_PLCX 12 /* policy when exists */
#define VIO_PLCN 13 /* policy when not exists */
#define VIO_PLCU 14 /* policy for open/close */
#define VIO_ULOG 15 /* log unit */
#define VIO_UNRP 16 /* report unit (namelist form) */
#define VIO_IMPI 17 /* mpi rank */
#define VIO_NMPI 18 /* mpi size */
#define VIO_COMM 19 /* mpi communicator */
#define VIO_NRLG 20 /* report unit log */
#define VIO_KPOLICY_MAX 20
CCC_* Policies
#define VIO_ACTION_UNKNOWN 0
#define VIO_ACTION_READ 1
#define VIO_ACTION_WRITE 2
#define VIO_ACTION_RW 3
c
#define VIO_FORM_UNFORMATTED 0
#define VIO_FORM_FORMATTED 1
CCC_ + when exists
#define VIO_POLICY_X_ERR 0
#define VIO_POLICY_X_CLOBBER 1
#define VIO_POLICY_X_OVERWRITE 2
#define VIO_POLICY_X_APPEND 3
#define VIO_POLICY_X_IGNORE 4
CCC_ + when not exists
#define VIO_POLICY_N_ERR 0
#define VIO_POLICY_N_CREATE 1
#define VIO_POLICY_N_IGNORE 2
CCC_ + open/close timing
#define VIO_POLICY_U_COMMON 0
#define VIO_POLICY_U_FREE 1
#define VIO_POLICY_U_BLACK 2
#define VIO_POLICY_U_OPEN 3
CCC_ + length adjustment
#define VIO_POLICY_L_ERR 0
#define VIO_POLICY_L_EXTENSION 1
#define VIO_POLICY_L_SHRINKAGE 2
#define VIO_POLICY_L_COMMON 3
#define VIO_POLICY_L_OLD 4
CCC_* String policy cluster
CCC_ + format string (not stored in the cluster)
#define VIO_FORMAT_MAX 64
CCC_ + open clause id
#define VIO_CLAUSE_SIZE 4
#define VIO_CLAUSE_FORM(P) P(1:1)
#define VIO_CLAUSE_ACTION(P) P(2:2)
#define VIO_CLAUSE_STATUS(P) P(3:3)
#define VIO_CLAUSE_POS(P) P(4:4)
#define VIO_CLAUSE_FIRST(P) P(1:4)
#define VIO_CLAUSE_LATER(P) P(5:8)
CC 1:4 first open 5:8 second and later open
CCC_ + report tag (obsolete/reserved)
#define VIO_REPORT(P) P(VIO_REPORT_STT:VIO_REPORT_END)
#define VIO_REPORT_STT 10
#define VIO_REPORT_END 31
#define VIO_REPORT_MAX VIO_REPORT_END-VIO_REPORT_STT+1
CCC_ + file name
#define VIO_FILENAME(P) P(VIO_FILENAME_STT:VIO_FILENAME_END)
#define VIO_FILENAME_STT 33
#define VIO_FILENAME_END VIO_SPOLICY_LEN
#define VIO_SPOLICY_LEN OPT_FILENAME_MAX+VIO_FILENAME_STT-1
CCC_* Tag/Value types
#define KTYPE_SYSTEM 0
#define KTYPE_UNDEF 1
CCC_ + separators
#define KTYPE_SEP -1
#define KTYPE_GROUP -9
CCC_* End definitions
#endif /* _ODEVVA_H */
CCC_! FOOTER
C Local Variables:
C mode: fortran
C fff-style: "iciesShermy"
C End:
| 31.333333 | 67 | 0.732745 |
0c71cb8c9846299050e5958fc6d41ddc407b560e | 10,265 | h | C | common/libraries/hpm_sdk/middleware/hpm_math/nds_dsp/riscv_dsp_complex_math.h | hpmicro/rtt-bsp-hpm6750evkmini | 55e18a691aa386e3dce10b6c3d25d4a29a585213 | [
"BSD-3-Clause"
] | 8 | 2022-02-11T08:20:49.000Z | 2022-03-22T06:19:59.000Z | common/libraries/hpm_sdk/middleware/hpm_math/nds_dsp/riscv_dsp_complex_math.h | hpmicro/rtt-bsp-hpm6750evkmini | 55e18a691aa386e3dce10b6c3d25d4a29a585213 | [
"BSD-3-Clause"
] | 2 | 2022-03-22T03:22:45.000Z | 2022-03-22T06:09:13.000Z | common/libraries/hpm_sdk/middleware/hpm_math/nds_dsp/riscv_dsp_complex_math.h | hpmicro/rtt-bsp-hpm6750evkmini | 55e18a691aa386e3dce10b6c3d25d4a29a585213 | [
"BSD-3-Clause"
] | 2 | 2022-02-19T10:51:00.000Z | 2022-03-22T03:11:35.000Z | /**
* Copyright (C) 2021 Andes Technology Corporation
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the License);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.
*/
#ifndef __RISCV_DSP_COMPLEX_MATH_H__
#define __RISCV_DSP_COMPLEX_MATH_H__
/**
* @defgroup complex Complex Functions
* This set of functions operates on complex data vectors.
* The data in the input <code>src</code> vector and output <code>dst</code>
* are arranged in the array as: [real, imag, real, imag, real, imag, ...).
*/
#ifdef __cplusplus
extern "C"
{
#endif
#include "riscv_dsp_math_types.h"
// Complex Conjugate
/**
* @brief Conjugate the floating-potint complex vector.
* @param[in] *src the input complex vector.
* @param[out] *dst the output complex vector.
* @param[in] size size of the vectors.
* @return none.
*/
void riscv_dsp_cconj_f32(const float32_t *src, float32_t *dst, uint32_t size);
/**
* @brief Conjugate the q15 complex vector.
* @param[in] *src the input complex vector.
* @param[out] *dst the output complex vector.
* @param[in] size size of the vectors.
* @return none.
*
* The Q15 value INT16_MIN (0x8000) will be saturated to the maximum
* allowable positive value INT16_MAX.
*/
void riscv_dsp_cconj_q15(const q15_t *src, q15_t *dst, uint32_t size);
/**
* @brief Conjugate the q31 complex vector.
* @param[in] *src the input complex vector.
* @param[out] *dst the output complex vector.
* @param[in] size size of the vectors.
* @return none.
*
* The Q31 value INT32_MIN (0x80000000) will be saturated to the maximum
* allowable positive value INT32_MAX.
*/
void riscv_dsp_cconj_q31(const q31_t *src, q31_t *dst, uint32_t size);
// Complex Dot Product
/**
* @brief Compute the dot product of the floating-potint complex vector.
* @param[in] *src1 the first input complex vector.
* @param[in] *src2 the second input complex vector.
* @param[in] size size of the vectors.
* @param[out] *dst the output vector.
* @return none.
*/
void riscv_dsp_cdprod_f32(const float32_t *src1, const float32_t *src2, uint32_t size, float32_t *dst);
/**
* @brief Compute the dot product type2 of the floating-potint complex vector.
* @param[in] *src1 the first input complex vector.
* @param[in] *src2 the second input complex vector.
* @param[in] size size of the vectors.
* @param[out] *rout the real sum of the output.
* @param[out] *iout the imag sum of the output.
* @return none.
*/
void riscv_dsp_cdprod_typ2_f32(const float32_t *src1, const float32_t *src2, uint32_t size, float32_t *rout, float32_t *iout);
/**
* @brief Compute the dot product of the q15 complex vector.
* @param[in] *src1 the first input complex vector.
* @param[in] *src2 the second input complex vector.
* @param[in] size size of the vectors.
* @param[out] *dst the output vector.
* @return none.
*
* The multiplication outputs are in 1.15 x 1.15 = 2.30 format and
* finally output is shift into 3.13 format.
*/
void riscv_dsp_cdprod_q15(const q15_t *src1, const q15_t *src2, uint32_t size, q15_t *dst);
/**
* @brief Compute the dot product type2 of the q15 complex vector.
* @param[in] *src1 the first input complex vector.
* @param[in] *src2 the second input complex vector.
* @param[in] size size of the vectors.
* @param[out] *rout the real sum of the output.
* @param[out] *iout the imag sum of the output.
* @return none.
*
* The multiplication outputs are in 1.15 x 1.15 = 2.30 format and
* finally output is shift into q24 format.
*/
void riscv_dsp_cdprod_typ2_q15(const q15_t *src1, const q15_t *src2, uint32_t size, q31_t *rout, q31_t *iout);
/**
* @brief Compute the dot product of the q31 complex vector.
* @param[in] *src1 the first input complex vector.
* @param[in] *src2 the second input complex vector.
* @param[in] size size of the vectors.
* @param[out] *dst the output vector.
* @return none.
*
* The multiplication outputs are in 1.31 x 1.31 = 2.62 format and
* finally output is shift into 3.29 format.
*/
void riscv_dsp_cdprod_q31(const q31_t *src1, const q31_t *src2, uint32_t size, q31_t *dst);
/**
* @brief Compute the dot product type2 of the q31 complex vector.
* @param[in] *src1 the first input complex vector.
* @param[in] *src2 the second input complex vector.
* @param[in] size size of the vectors.
* @param[out] *rout the real sum of the output.
* @param[out] *iout the imag sum of the output.
* @return none.
*
* The multiplication outputs are in 1.31 x 1.31 = 2.62 format and
* finally output is shift into q48 format.
*/
void riscv_dsp_cdprod_typ2_q31(const q31_t *src1, const q31_t *src2, uint32_t size, q63_t *rout, q63_t *iout);
// Complex Magnitude
/**
* @brief Compute the magnitude of the floating-potint complex vector.
* @param[in] *src points to the input complex vector.
* @param[out] *dst points to the output complex vector.
* @param[in] size size of the vectors.
* @return none.
*/
void riscv_dsp_cmag_f32(const float32_t *src, float32_t *dst, uint32_t size);
/**
* @brief Compute the magnitude of the q15 complex vector.
* @param[in] *src points to the input complex vector.
* @param[out] *dst points to the output complex vector.
* @param[in] size size of the vectors.
* @return none.
*
* The multiplication outputs are in 1.15 x 1.15 = 2.30 format and
* finally output is shift into 2.14 format.
*/
void riscv_dsp_cmag_q15(const q15_t *src, q15_t *dst, uint32_t size);
/**
* @brief Compute the magnitude of the q31 complex vector.
* @param[in] *src points to the input complex vector.
* @param[out] *dst points to the output complex vector.
* @param[in] size size of the vectors.
* @return none.
*
* The multiplication outputs are in 1.31 x 1.31 = 2.62 format and
* finally output is shift into 2.30 format.
*/
void riscv_dsp_cmag_q31(const q31_t *src, q31_t *dst, uint32_t size);
// Complex Magnitude Squared
/**
* @brief Compute the magnitude squared of the floating-potint complex
* vector.
* @param[in] *src points to the input complex vector.
* @param[out] *dst points to the output complex vector.
* @param[in] size size of the vectors.
* @return none.
*/
void riscv_dsp_cmag_sqr_f32(const float32_t *src, float32_t *dst, uint32_t size);
/**
* @brief Compute the magnitude squared of the q15 complex vector.
* @param[in] *src points to the input complex vector.
* @param[out] *dst points to the output complex vector.
* @param[in] size size of the vectors.
* @return none.
*
* The multiplication outputs are in 1.15 x 1.15 = 2.30 format and
* finally output is shift into 3.13 format.
*/
void riscv_dsp_cmag_sqr_q15(const q15_t *src, q15_t *dst, uint32_t size);
/**
* @brief Compute the magnitude squared of the q31 complex vector.
* @param[in] *src points to the input complex vector.
* @param[out] *dst points to the output complex vector.
* @param[in] size size of the vectors.
* @return none.
*
* The multiplication outputs are in 1.31 x 1.31 = 2.62 format and
* finally output is shift into 3.29 format.
*/
void riscv_dsp_cmag_sqr_q31(const q31_t *src, q31_t *dst, uint32_t size);
// Complex Multiplication
/**
* @brief Multiply two folating-point complex vector.
* @param[in] *src1 the first input complex vector.
* @param[in] *src2 the second input complex vector.
* @param[out] *dst output complex vector.
* @param[in] size size of the vectors.
* @return none.
*/
void riscv_dsp_cmul_f32(const float32_t *src1, const float32_t *src2, float32_t *dst, uint32_t size);
/**
* @brief Multiply two q15 complex vector.
* @param[in] *src1 the first input complex vector.
* @param[in] *src2 the second input complex vector.
* @param[out] *dst output complex vector.
* @param[in] size size of the vectors.
* @return none.
*
* The multiplication outputs are in 1.15 x 1.15 = 2.30 format and
* finally output is shift into 3.13 format.
*/
void riscv_dsp_cmul_q15(const q15_t *src1, const q15_t *src2, q15_t *dst, uint32_t size);
/**
* @brief Multiply two q31 complex vector.
* @param[in] *src1 the first input complex vector.
* @param[in] *src2 the second input complex vector.
* @param[out] *dst output complex vector.
* @param[in] size size of the vectors.
* @return none.
*
* The multiplication outputs are in 1.31 x 1.31 = 2.62 format and
* finally output is shift into 3.29 format.
*/
void riscv_dsp_cmul_q31(const q31_t *src1, const q31_t *src2, q31_t *dst, uint32_t size);
// Complex-by-Real Multiplication
/**
* @brief Multiply the folating-point complex vector by a real vector.
* @param[in] *src the input complex vector.
* @param[in] *real the input real vector.
* @param[out] *dst output complex vector.
* @param[in] size size of the vectors.
* @return none.
*/
void riscv_dsp_cmul_real_f32(const float32_t *src, const float32_t *real, float32_t *dst, uint32_t size);
/**
* @brief Multiply the q15 complex vector by a real vector.
* @param[in] *src the input complex vector.
* @param[in] *real the input real vector.
* @param[out] *dst output complex vector.
* @param[in] size size of the vectors.
* @return none.
*
* Output results will be saturated in Q15 range [0x8000 0x7FFF].
*/
void riscv_dsp_cmul_real_q15(const q15_t *src, const q15_t *real, q15_t *dst, uint32_t size);
/**
* @brief Multiply the q31 complex vector by a real vector.
* @param[in] *src the input complex vector.
* @param[in] *real the input real vector.
* @param[out] *dst output complex vector.
* @param[in] size size of the vectors.
* @return none.
*
* Output results will be saturated in Q31 range[0x80000000 0x7FFFFFFF].
*/
void riscv_dsp_cmul_real_q31(const q31_t *src, const q31_t *real, q31_t *dst, uint32_t size);
#ifdef __cplusplus
}
#endif
#endif // __RISCV_DSP32_COMPLEX_MATH_H__
| 35.519031 | 126 | 0.709109 |
7cc81fd7c881fd4a7497d9bbf845fefaf977f21c | 349 | h | C | System/Library/CoreServices/SpringBoard/PrivateHeaders/_SBAppViewCrossfadeWrapperView.h | lechium/iPhoneOS_12.1.1_Headers | aac688b174273dfcbade13bab104461f463db772 | [
"MIT"
] | 12 | 2019-06-02T02:42:41.000Z | 2021-04-13T07:22:20.000Z | System/Library/CoreServices/SpringBoard/PrivateHeaders/_SBAppViewCrossfadeWrapperView.h | lechium/iPhoneOS_12.1.1_Headers | aac688b174273dfcbade13bab104461f463db772 | [
"MIT"
] | null | null | null | System/Library/CoreServices/SpringBoard/PrivateHeaders/_SBAppViewCrossfadeWrapperView.h | lechium/iPhoneOS_12.1.1_Headers | aac688b174273dfcbade13bab104461f463db772 | [
"MIT"
] | 3 | 2019-06-11T02:46:10.000Z | 2019-12-21T14:58:16.000Z | //
// Generated by class-dump 3.5 (64 bit).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by Steve Nygard.
//
#import "UIView.h"
@interface _SBAppViewCrossfadeWrapperView : UIView
{
}
+ (id)wrapperWithFrame:(struct CGRect)arg1; // IMP=0x00000001001600c8
- (void)setAlpha:(double)arg1; // IMP=0x000000010016012c
@end
| 19.388889 | 83 | 0.69914 |
914e23b891f9d5e164b37970e32da7eec8c3c84a | 7,622 | h | C | test/integration-tests/metafs/metafs_test_fixture.h | gye-ul/poseidonos | bce8fe2cd1f36ede8647446ecc4cf8a9749e6918 | [
"BSD-3-Clause"
] | 1 | 2022-03-08T13:08:53.000Z | 2022-03-08T13:08:53.000Z | test/integration-tests/metafs/metafs_test_fixture.h | gye-ul/poseidonos | bce8fe2cd1f36ede8647446ecc4cf8a9749e6918 | [
"BSD-3-Clause"
] | null | null | null | test/integration-tests/metafs/metafs_test_fixture.h | gye-ul/poseidonos | bce8fe2cd1f36ede8647446ecc4cf8a9749e6918 | [
"BSD-3-Clause"
] | null | null | null | /*
* BSD LICENSE
* Copyright (c) 2021 Samsung Electronics Corporation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Samsung Electronics Corporation nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#pragma once
#include "src/metafs/metafs.h"
#include "src/metafs/storage/mss.h"
#include <unordered_map>
#include <string>
#include <cstdio>
#include <cstdint>
#include <fstream>
#include <memory>
#include <stdexcept>
#include "test/unit-tests/telemetry/telemetry_client/telemetry_publisher_mock.h"
#include "test/unit-tests/array_models/interface/i_array_info_mock.h"
using ::testing::NiceMock;
namespace pos
{
class FileIo
{
public:
FileIo(void) = delete;
explicit FileIo(const std::string& fileName)
: fileName(fileName)
{
file.open(fileName, std::ios::binary | std::ios::in | std::ios::out | std::ios::ate);
}
virtual ~FileIo(void)
{
file.close();
}
virtual bool Write(void* const buf, const size_t byteOffset, const size_t byteSize)
{
file.seekp(byteOffset, file.beg);
file.write(static_cast<char*>(buf), byteSize);
if (!file.good())
{
return false;
}
return true;
}
virtual bool Read(void* buf, const size_t byteOffset, const size_t byteSize)
{
file.seekg(byteOffset);
file.read((char*)buf, byteSize);
if (!file.good())
{
return false;
}
return true;
}
private:
std::string fileName;
std::fstream file;
};
class TestMetaStorageSubsystem : public MetaStorageSubsystem
{
public:
explicit TestMetaStorageSubsystem(int arrayId) : MetaStorageSubsystem(arrayId)
{
fileNames.insert({MetaStorageType::SSD, "metafs_ssd.bin"});
fileNames.insert({MetaStorageType::NVRAM, "metafs_nvm.bin"});
for (auto& fileName : fileNames)
{
std::fstream create(fileName.second, std::ios::app);
create.close();
files.insert({fileName.first, std::make_shared<FileIo>(fileName.second)});
}
}
virtual ~TestMetaStorageSubsystem(void)
{
for (auto& fileName : fileNames)
std::remove(fileName.second.c_str());
}
POS_EVENT_ID CreateMetaStore(int arrayId, MetaStorageType mediaType, uint64_t capacity, bool formatFlag = false)
{
return POS_EVENT_ID::SUCCESS;
}
POS_EVENT_ID Open(void)
{
return POS_EVENT_ID::SUCCESS;
}
POS_EVENT_ID Close(void)
{
return POS_EVENT_ID::SUCCESS;
}
uint64_t GetCapacity(MetaStorageType mediaType)
{
return 0;
}
POS_EVENT_ID ReadPage(MetaStorageType mediaType, MetaLpnType metaLpn, void* buffer, MetaLpnType numPages)
{
return POS_EVENT_ID::SUCCESS;
}
POS_EVENT_ID WritePage(MetaStorageType mediaType, MetaLpnType metaLpn, void* buffer, MetaLpnType numPages)
{
return POS_EVENT_ID::SUCCESS;
}
bool IsAIOSupport(void)
{
return true;
}
POS_EVENT_ID ReadPageAsync(MssAioCbCxt* cb)
{
return POS_EVENT_ID::SUCCESS;
}
POS_EVENT_ID WritePageAsync(MssAioCbCxt* cb)
{
return POS_EVENT_ID::SUCCESS;
}
POS_EVENT_ID TrimFileData(MetaStorageType mediaType, MetaLpnType startLpn, void* buffer, MetaLpnType numPages)
{
return POS_EVENT_ID::SUCCESS;
}
LogicalBlkAddr TranslateAddress(MetaStorageType type, MetaLpnType theLpn)
{
return {};
}
POS_EVENT_ID DoPageIO(MssOpcode opcode, MetaStorageType mediaType, MetaLpnType metaLpn, void* buffer,
MetaLpnType numPages, uint32_t mpio_id, uint32_t tagid)
{
printf("DoPageIO, %s, mediaType: %d, startLpn: %ld, size: %ld, mpio_id: %d, tagid: %d, thread: %d\n",
((int)opcode == 0) ? "write" : "read ", (int)mediaType, metaLpn, numPages, mpio_id, tagid, sched_getcpu());
throw logic_error("not implemented");
return POS_EVENT_ID::SUCCESS;
}
POS_EVENT_ID DoPageIOAsync(MssOpcode opcode, MssAioCbCxt* cb)
{
bool result = true;
if (opcode == MssOpcode::Read)
result = files[cb->GetIoContext()->media]->Read(
cb->GetIoContext()->buf,
cb->GetIoContext()->metaLpn * BYTE_4K,
cb->GetIoContext()->lpnCnt * BYTE_4K);
else
result = files[cb->GetIoContext()->media]->Write(
cb->GetIoContext()->buf,
cb->GetIoContext()->metaLpn * BYTE_4K,
cb->GetIoContext()->lpnCnt * BYTE_4K);
if (!result)
{
std::cout << "the request was failed" << std::endl;
printf("DoPageIOAsync, %s, result: %s, mediaType: %d, startLpn: %ld, size: %ld, mpio_id: %d, tagid: %d, thread: %d\n",
((int)opcode == 0) ? "write" : "read ", (result == true) ? "good" : "fail",
(int)cb->GetIoContext()->media, cb->GetIoContext()->metaLpn, cb->GetIoContext()->lpnCnt,
cb->GetIoContext()->mpioId, cb->GetIoContext()->tagId, sched_getcpu());
}
cb->InvokeCallback();
return POS_EVENT_ID::SUCCESS;
}
private:
std::unordered_map<MetaStorageType, std::string> fileNames;
std::unordered_map<MetaStorageType, std::shared_ptr<FileIo>> files;
const size_t BYTE_4K = 4096;
};
class MetaFsTestFixture
{
public:
MetaFsTestFixture(void);
virtual ~MetaFsTestFixture(void);
protected:
NiceMock<MockIArrayInfo>* arrayInfo = nullptr;
MetaFs* metaFs = nullptr;
MetaFsManagementApi* mgmt = nullptr;
MetaFsFileControlApi* ctrl = nullptr;
MetaFsIoApi* io = nullptr;
MetaFsWBTApi* wbt = nullptr;
TestMetaStorageSubsystem* storage = nullptr;
NiceMock<MockTelemetryPublisher>* tpForMetaIo = nullptr;
NiceMock<MockTelemetryPublisher>* tpForMetafs = nullptr;
bool isLoaded = false;
int arrayId = INT32_MAX;
std::string arrayName = "";
PartitionLogicalSize ptnSize[PartitionType::TYPE_COUNT];
private:
void _SetArrayInfo(void);
void _SetThreadModel(void);
cpu_set_t _GetCpuSet(int from, int to);
};
} // namespace pos
| 32.995671 | 130 | 0.656389 |
c642c558d64996b44a3d2edf4e8e2240919cc21b | 1,546 | h | C | AppleDepth.framework/Headers/ADWarperMeshLensDistortionModel.h | wyndwarrior/iBrain | 36326f788a9a0934042c4240bd199c191cf7993e | [
"MIT"
] | 1 | 2022-01-20T07:47:41.000Z | 2022-01-20T07:47:41.000Z | AppleDepth.framework/Headers/ADWarperMeshLensDistortionModel.h | wyndwarrior/iBrain | 36326f788a9a0934042c4240bd199c191cf7993e | [
"MIT"
] | null | null | null | AppleDepth.framework/Headers/ADWarperMeshLensDistortionModel.h | wyndwarrior/iBrain | 36326f788a9a0934042c4240bd199c191cf7993e | [
"MIT"
] | null | null | null | // Headers generated with ktool v0.19.0
// https://github.com/kritantadev/ktool | pip3 install k2l
// Platform: IOS | Minimum OS: 15.0.0 | SDK: 15.0.0
#ifndef ADWARPERMESHLENSDISTORTIONMODEL_H
#define ADWARPERMESHLENSDISTORTIONMODEL_H
@class NSObject, NSString, NSData;
#import "ADLensDistortionModel-Protocol.h"
@interface ADWarperMeshLensDistortionModel : NSObject <ADLensDistortionModel>
{
ADWarperMesh _undistortMesh;
ADWarperMesh _distortMesh;
}
@property (readonly, copy) NSString *debugDescription;
@property (readonly, copy) NSString *description;
@property (readonly) NSUInteger hash;
@property (readonly) NSInteger height;
@property (readonly) Class superclass;
@property (readonly) NSUInteger type;
@property (readonly, retain) NSData *warperMesh;
@property (readonly) NSInteger width;
-(id)copyWithZone:(struct _NSZone *)arg0 ;
-(id)dictionaryRepresentation:(BOOL)arg0 ;
-(id)initWithDictionary:(id)arg0 ;
-(id)initWithWarperMesh:(id)arg0 type:(NSUInteger)arg1 width:(NSInteger)arg2 height:(NSInteger)arg3 ;
-(void)adjustForImageRotation:(NSInteger)arg0 forDimensions:(struct CGSize )arg1 ;
-(void)crop:(struct CGRect )arg0 fromDimensions:(struct CGSize )arg1 ;
-(void)distortPixels:(NSUInteger)arg0 undistortedPixels:(struct CGPoint *)arg1 withCameraCalibration:(id)arg2 outDistortedPixels:(struct CGPoint *)arg3 ;
-(void)scale:(float)arg0 ;
-(void)undistortPixels:(NSUInteger)arg0 distortedPixels:(struct CGPoint *)arg1 withCameraCalibration:(id)arg2 outUndistortedPixels:(struct CGPoint *)arg3 ;
@end
#endif | 33.608696 | 155 | 0.785252 |
0b461989e6973f332977c494a8105a6564ae5e50 | 2,105 | h | C | build/ImageMagick-7.1.0-2/IMDelegates/ghostscript-9.54.0/contrib/pcl3/src/pclcap.h | roMummy/imagemagick_lib_ios | 0e0e6fa77e06b471f5019d5b1b28caabd08d5e6a | [
"ImageMagick"
] | null | null | null | build/ImageMagick-7.1.0-2/IMDelegates/ghostscript-9.54.0/contrib/pcl3/src/pclcap.h | roMummy/imagemagick_lib_ios | 0e0e6fa77e06b471f5019d5b1b28caabd08d5e6a | [
"ImageMagick"
] | null | null | null | build/ImageMagick-7.1.0-2/IMDelegates/ghostscript-9.54.0/contrib/pcl3/src/pclcap.h | roMummy/imagemagick_lib_ios | 0e0e6fa77e06b471f5019d5b1b28caabd08d5e6a | [
"ImageMagick"
] | null | null | null | /******************************************************************************
File: $Id: pclcap.h,v 1.10 2000/11/19 07:05:17 Martin Rel $
Contents: Header for describing capabilities of PCL printers
Author: Martin Lottermoser, Greifswaldstrasse 28, 38124 Braunschweig,
Germany. E-mail: Martin.Lottermoser@t-online.de.
*******************************************************************************
* *
* Copyright (C) 2000 by Martin Lottermoser *
* All rights reserved *
* *
******************************************************************************/
#ifndef _pclcap_h /* Inclusion protection */
#define _pclcap_h
/*****************************************************************************/
#include "gdeveprn.h"
#include "pclgen.h"
/*****************************************************************************/
/* Identifiers for printers (26) */
typedef enum {
HPDeskJet,
HPDeskJetPlus,
HPDJPortable, /* belongs to the 3xx family (DJ3/4 p. 1) */
HPDJ310,
HPDJ320,
HPDJ340,
HPDJ400,
HPDJ500,
HPDJ500C,
HPDJ510, HPDJ520, /* may be treated identically (TRG500 p. 1-3) */
HPDJ540,
HPDJ550C,
HPDJ560C,
pcl3_generic_old,
HPDJ600,
HPDJ660C, HPDJ670C, /* programmatically identical (DJ6/8 p. 2) */
HPDJ680C,
HPDJ690C,
HPDJ850C, HPDJ855C,
/* HP refers to them collectively as "HP DJ85xC" (DJ6/8) */
HPDJ870C,
HPDJ890C,
HPDJ1120C,
pcl3_generic_new
} pcl_Printer;
/*****************************************************************************/
/* PCL printer description */
typedef struct {
pcl_Printer id;
pcl_Level level;
eprn_PrinterDescription desc;
} pcl_PrinterDescription;
extern const pcl_PrinterDescription pcl3_printers[];
/* This array is indexed by the values of 'pcl_Printer'. */
/*****************************************************************************/
extern void pcl3_fill_defaults(pcl_Printer printer, pcl_FileData *data);
/*****************************************************************************/
#endif /* Inclusion protection */
| 29.236111 | 79 | 0.47696 |
73929db4c9c26268f1a89df865f2d5c8a2a54d41 | 15,097 | c | C | code/client/snd_mix.c | raynorpat/xreal | 2fcbf9179fa22dc6e808bb65b879ac2ee7616ebd | [
"BSD-3-Clause"
] | 11 | 2016-06-03T07:46:15.000Z | 2021-09-09T19:35:32.000Z | code/client/snd_mix.c | raynorpat/xreal | 2fcbf9179fa22dc6e808bb65b879ac2ee7616ebd | [
"BSD-3-Clause"
] | 1 | 2016-10-14T23:06:19.000Z | 2016-10-14T23:06:19.000Z | code/client/snd_mix.c | raynorpat/xreal | 2fcbf9179fa22dc6e808bb65b879ac2ee7616ebd | [
"BSD-3-Clause"
] | 5 | 2016-10-13T04:43:58.000Z | 2019-08-24T14:03:35.000Z | /*
===========================================================================
Copyright (C) 1999-2005 Id Software, Inc.
Copyright (C) 2006 Robert Beckebans <trebor_7@users.sourceforge.net>
This file is part of XreaL source code.
XreaL source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
XreaL source code is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with XreaL source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
// snd_mix.c -- portable code to mix sounds for snd_dma.c
#include "client.h"
#include "snd_local.h"
#if idppc_altivec && !defined(MACOS_X)
#include <altivec.h>
#endif
static portable_samplepair_t paintbuffer[PAINTBUFFER_SIZE];
static int snd_vol;
int *snd_p;
int snd_linear_count;
short *snd_out;
#if !(defined(_MSC_VER) && id386)
void S_WriteLinearBlastStereo16(void)
{
int i;
int val;
for(i = 0; i < snd_linear_count; i += 2)
{
val = snd_p[i] >> 8;
if(val > 0x7fff)
snd_out[i] = 0x7fff;
else if(val < -32768)
snd_out[i] = -32768;
else
snd_out[i] = val;
val = snd_p[i + 1] >> 8;
if(val > 0x7fff)
snd_out[i + 1] = 0x7fff;
else if(val < -32768)
snd_out[i + 1] = -32768;
else
snd_out[i + 1] = val;
}
}
#else
// *INDENT-OFF*
__declspec( naked ) void S_WriteLinearBlastStereo16 (void)
{
__asm {
push edi
push ebx
mov ecx,ds:dword ptr[snd_linear_count]
mov ebx,ds:dword ptr[snd_p]
mov edi,ds:dword ptr[snd_out]
LWLBLoopTop:
mov eax,ds:dword ptr[-8+ebx+ecx*4]
sar eax,8
cmp eax,07FFFh
jg LClampHigh
cmp eax,0FFFF8000h
jnl LClampDone
mov eax,0FFFF8000h
jmp LClampDone
LClampHigh:
mov eax,07FFFh
LClampDone:
mov edx,ds:dword ptr[-4+ebx+ecx*4]
sar edx,8
cmp edx,07FFFh
jg LClampHigh2
cmp edx,0FFFF8000h
jnl LClampDone2
mov edx,0FFFF8000h
jmp LClampDone2
LClampHigh2:
mov edx,07FFFh
LClampDone2:
shl edx,16
and eax,0FFFFh
or edx,eax
mov ds:dword ptr[-4+edi+ecx*2],edx
sub ecx,2
jnz LWLBLoopTop
pop ebx
pop edi
ret
}
}
// *INDENT-ON*
#endif
void S_TransferStereo16(unsigned long *pbuf, int endtime)
{
int lpos;
int ls_paintedtime;
snd_p = (int *)paintbuffer;
ls_paintedtime = s_paintedtime;
while(ls_paintedtime < endtime)
{
// handle recirculating buffer issues
lpos = ls_paintedtime & ((dma.samples >> 1) - 1);
snd_out = (short *)pbuf + (lpos << 1);
snd_linear_count = (dma.samples >> 1) - lpos;
if(ls_paintedtime + snd_linear_count > endtime)
snd_linear_count = endtime - ls_paintedtime;
snd_linear_count <<= 1;
// write a linear blast of samples
S_WriteLinearBlastStereo16();
snd_p += snd_linear_count;
ls_paintedtime += (snd_linear_count >> 1);
if(CL_VideoRecording())
CL_WriteAVIAudioFrame((byte *) snd_out, snd_linear_count << 1);
}
}
/*
===================
S_TransferPaintBuffer
===================
*/
void S_TransferPaintBuffer(int endtime)
{
int out_idx;
int count;
int out_mask;
int *p;
int step;
int val;
unsigned long *pbuf;
pbuf = (unsigned long *)dma.buffer;
if(s_testsound->integer)
{
int i;
int count;
// write a fixed sine wave
count = (endtime - s_paintedtime);
for(i = 0; i < count; i++)
paintbuffer[i].left = paintbuffer[i].right = sin((s_paintedtime + i) * 0.1) * 20000 * 256;
}
if(dma.samplebits == 16 && dma.channels == 2)
{ // optimized case
S_TransferStereo16(pbuf, endtime);
}
else
{ // general case
p = (int *)paintbuffer;
count = (endtime - s_paintedtime) * dma.channels;
out_mask = dma.samples - 1;
out_idx = s_paintedtime * dma.channels & out_mask;
step = 3 - dma.channels;
if(dma.samplebits == 16)
{
short *out = (short *)pbuf;
while(count--)
{
val = *p >> 8;
p += step;
if(val > 0x7fff)
val = 0x7fff;
else if(val < -32768)
val = -32768;
out[out_idx] = val;
out_idx = (out_idx + 1) & out_mask;
}
}
else if(dma.samplebits == 8)
{
unsigned char *out = (unsigned char *)pbuf;
while(count--)
{
val = *p >> 8;
p += step;
if(val > 0x7fff)
val = 0x7fff;
else if(val < -32768)
val = -32768;
out[out_idx] = (val >> 8) + 128;
out_idx = (out_idx + 1) & out_mask;
}
}
}
}
/*
===============================================================================
CHANNEL MIXING
===============================================================================
*/
#if idppc_altivec
static void S_PaintChannelFrom16_altivec(channel_t * ch, const sfx_t * sc, int count, int sampleOffset, int bufferOffset)
{
int data, aoff, boff;
int leftvol, rightvol;
int i, j;
portable_samplepair_t *samp;
sndBuffer *chunk;
short *samples;
float ooff, fdata, fdiv, fleftvol, frightvol;
samp = &paintbuffer[bufferOffset];
if(ch->doppler)
{
sampleOffset = sampleOffset * ch->oldDopplerScale;
}
chunk = sc->soundData;
while(sampleOffset >= SND_CHUNK_SIZE)
{
chunk = chunk->next;
sampleOffset -= SND_CHUNK_SIZE;
if(!chunk)
{
chunk = sc->soundData;
}
}
if(!ch->doppler || ch->dopplerScale == 1.0f)
{
vector signed short volume_vec;
vector unsigned int volume_shift;
int vectorCount, samplesLeft, chunkSamplesLeft;
leftvol = ch->leftvol * snd_vol;
rightvol = ch->rightvol * snd_vol;
samples = chunk->sndChunk;
((short *)&volume_vec)[0] = leftvol;
((short *)&volume_vec)[1] = leftvol;
((short *)&volume_vec)[4] = leftvol;
((short *)&volume_vec)[5] = leftvol;
((short *)&volume_vec)[2] = rightvol;
((short *)&volume_vec)[3] = rightvol;
((short *)&volume_vec)[6] = rightvol;
((short *)&volume_vec)[7] = rightvol;
volume_shift = vec_splat_u32(8);
i = 0;
while(i < count)
{
/* Try to align destination to 16-byte boundary */
while(i < count && (((unsigned long)&samp[i] & 0x1f) || ((count - i) < 8) || ((SND_CHUNK_SIZE - sampleOffset) < 8)))
{
data = samples[sampleOffset++];
samp[i].left += (data * leftvol) >> 8;
samp[i].right += (data * rightvol) >> 8;
if(sampleOffset == SND_CHUNK_SIZE)
{
chunk = chunk->next;
samples = chunk->sndChunk;
sampleOffset = 0;
}
i++;
}
/* Destination is now aligned. Process as many 8-sample
chunks as we can before we run out of room from the current
sound chunk. We do 8 per loop to avoid extra source data reads. */
samplesLeft = count - i;
chunkSamplesLeft = SND_CHUNK_SIZE - sampleOffset;
if(samplesLeft > chunkSamplesLeft)
samplesLeft = chunkSamplesLeft;
vectorCount = samplesLeft / 8;
if(vectorCount)
{
vector unsigned char tmp;
vector short s0, s1, sampleData0, sampleData1;
vector signed int merge0, merge1;
vector signed int d0, d1, d2, d3;
vector unsigned char samplePermute0 = VECCONST_UINT8(0, 1, 4, 5, 0, 1, 4, 5, 2, 3, 6, 7, 2, 3, 6, 7);
vector unsigned char samplePermute1 = VECCONST_UINT8(8, 9, 12, 13, 8, 9, 12, 13, 10, 11, 14, 15, 10, 11, 14, 15);
vector unsigned char loadPermute0, loadPermute1;
// Rather than permute the vectors after we load them to do the sample
// replication and rearrangement, we permute the alignment vector so
// we do everything in one step below and avoid data shuffling.
tmp = vec_lvsl(0, &samples[sampleOffset]);
loadPermute0 = vec_perm(tmp, tmp, samplePermute0);
loadPermute1 = vec_perm(tmp, tmp, samplePermute1);
s0 = *(vector short *)&samples[sampleOffset];
while(vectorCount)
{
/* Load up source (16-bit) sample data */
s1 = *(vector short *)&samples[sampleOffset + 7];
/* Load up destination sample data */
d0 = *(vector signed int *)&samp[i];
d1 = *(vector signed int *)&samp[i + 2];
d2 = *(vector signed int *)&samp[i + 4];
d3 = *(vector signed int *)&samp[i + 6];
sampleData0 = vec_perm(s0, s1, loadPermute0);
sampleData1 = vec_perm(s0, s1, loadPermute1);
merge0 = vec_mule(sampleData0, volume_vec);
merge0 = vec_sra(merge0, volume_shift); /* Shift down to proper range */
merge1 = vec_mulo(sampleData0, volume_vec);
merge1 = vec_sra(merge1, volume_shift);
d0 = vec_add(merge0, d0);
d1 = vec_add(merge1, d1);
merge0 = vec_mule(sampleData1, volume_vec);
merge0 = vec_sra(merge0, volume_shift); /* Shift down to proper range */
merge1 = vec_mulo(sampleData1, volume_vec);
merge1 = vec_sra(merge1, volume_shift);
d2 = vec_add(merge0, d2);
d3 = vec_add(merge1, d3);
/* Store destination sample data */
*(vector signed int *)&samp[i] = d0;
*(vector signed int *)&samp[i + 2] = d1;
*(vector signed int *)&samp[i + 4] = d2;
*(vector signed int *)&samp[i + 6] = d3;
i += 8;
vectorCount--;
s0 = s1;
sampleOffset += 8;
}
if(sampleOffset == SND_CHUNK_SIZE)
{
chunk = chunk->next;
samples = chunk->sndChunk;
sampleOffset = 0;
}
}
}
}
else
{
fleftvol = ch->leftvol * snd_vol;
frightvol = ch->rightvol * snd_vol;
ooff = sampleOffset;
samples = chunk->sndChunk;
for(i = 0; i < count; i++)
{
aoff = ooff;
ooff = ooff + ch->dopplerScale;
boff = ooff;
fdata = 0;
for(j = aoff; j < boff; j++)
{
if(j == SND_CHUNK_SIZE)
{
chunk = chunk->next;
if(!chunk)
{
chunk = sc->soundData;
}
samples = chunk->sndChunk;
ooff -= SND_CHUNK_SIZE;
}
fdata += samples[j & (SND_CHUNK_SIZE - 1)];
}
fdiv = 256 * (boff - aoff);
samp[i].left += (fdata * fleftvol) / fdiv;
samp[i].right += (fdata * frightvol) / fdiv;
}
}
}
#endif
static void S_PaintChannelFrom16_scalar(channel_t * ch, const sfx_t * sc, int count, int sampleOffset, int bufferOffset)
{
int data, aoff, boff;
int leftvol, rightvol;
int i, j;
portable_samplepair_t *samp;
sndBuffer *chunk;
short *samples;
float ooff, fdata, fdiv, fleftvol, frightvol;
samp = &paintbuffer[bufferOffset];
if(ch->doppler)
{
sampleOffset = sampleOffset * ch->oldDopplerScale;
}
chunk = sc->soundData;
while(sampleOffset >= SND_CHUNK_SIZE)
{
chunk = chunk->next;
sampleOffset -= SND_CHUNK_SIZE;
if(!chunk)
{
chunk = sc->soundData;
}
}
if(!ch->doppler || ch->dopplerScale == 1.0f)
{
leftvol = ch->leftvol * snd_vol;
rightvol = ch->rightvol * snd_vol;
samples = chunk->sndChunk;
for(i = 0; i < count; i++)
{
data = samples[sampleOffset++];
samp[i].left += (data * leftvol) >> 8;
samp[i].right += (data * rightvol) >> 8;
if(sampleOffset == SND_CHUNK_SIZE)
{
chunk = chunk->next;
samples = chunk->sndChunk;
sampleOffset = 0;
}
}
}
else
{
fleftvol = ch->leftvol * snd_vol;
frightvol = ch->rightvol * snd_vol;
ooff = sampleOffset;
samples = chunk->sndChunk;
for(i = 0; i < count; i++)
{
aoff = ooff;
ooff = ooff + ch->dopplerScale;
boff = ooff;
fdata = 0;
for(j = aoff; j < boff; j++)
{
if(j == SND_CHUNK_SIZE)
{
chunk = chunk->next;
if(!chunk)
{
chunk = sc->soundData;
}
samples = chunk->sndChunk;
ooff -= SND_CHUNK_SIZE;
}
fdata += samples[j & (SND_CHUNK_SIZE - 1)];
}
fdiv = 256 * (boff - aoff);
samp[i].left += (fdata * fleftvol) / fdiv;
samp[i].right += (fdata * frightvol) / fdiv;
}
}
}
static void S_PaintChannelFrom16(channel_t * ch, const sfx_t * sc, int count, int sampleOffset, int bufferOffset)
{
#if idppc_altivec
if(com_altivec->integer)
{
// must be in a seperate function or G3 systems will crash.
S_PaintChannelFrom16_altivec(ch, sc, count, sampleOffset, bufferOffset);
return;
}
#endif
S_PaintChannelFrom16_scalar(ch, sc, count, sampleOffset, bufferOffset);
}
/*
===================
S_PaintChannels
===================
*/
void S_PaintChannels(int endtime)
{
int i;
int end;
int stream;
channel_t *ch;
sfx_t *sc;
int ltime, count;
int sampleOffset;
snd_vol = s_volume->value * 255;
//Com_Printf ("%i to %i\n", s_paintedtime, endtime);
while(s_paintedtime < endtime)
{
// if paintbuffer is smaller than DMA buffer
// we may need to fill it multiple times
end = endtime;
if(endtime - s_paintedtime > PAINTBUFFER_SIZE)
{
end = s_paintedtime + PAINTBUFFER_SIZE;
}
// clear the paint buffer and mix any raw samples...
Com_Memset(paintbuffer, 0, sizeof(paintbuffer));
for(stream = 0; stream < MAX_RAW_STREAMS; stream++)
{
if(s_rawend[stream] >= s_paintedtime)
{
// copy from the streaming sound source
const portable_samplepair_t *rawsamples = s_rawsamples[stream];
const int stop = (end < s_rawend[stream]) ? end : s_rawend[stream];
for(i = s_paintedtime; i < stop; i++)
{
const int s = i & (MAX_RAW_SAMPLES - 1);
paintbuffer[i - s_paintedtime].left += rawsamples[s].left;
paintbuffer[i - s_paintedtime].right += rawsamples[s].right;
}
}
}
// paint in the channels.
ch = s_channels;
for(i = 0; i < MAX_CHANNELS; i++, ch++)
{
if(!ch->thesfx || (ch->leftvol < 0.25 && ch->rightvol < 0.25))
{
continue;
}
ltime = s_paintedtime;
sc = ch->thesfx;
sampleOffset = ltime - ch->startSample;
count = end - ltime;
if(sampleOffset + count > sc->soundLength)
{
count = sc->soundLength - sampleOffset;
}
if(count > 0)
{
S_PaintChannelFrom16(ch, sc, count, sampleOffset, ltime - s_paintedtime);
}
}
// paint in the looped channels.
ch = loop_channels;
for(i = 0; i < numLoopChannels; i++, ch++)
{
if(!ch->thesfx || (!ch->leftvol && !ch->rightvol))
{
continue;
}
ltime = s_paintedtime;
sc = ch->thesfx;
if(sc->soundData == NULL || sc->soundLength == 0)
{
continue;
}
// we might have to make two passes if it
// is a looping sound effect and the end of
// the sample is hit
do
{
sampleOffset = (ltime % sc->soundLength);
count = end - ltime;
if(sampleOffset + count > sc->soundLength)
{
count = sc->soundLength - sampleOffset;
}
if(count > 0)
{
S_PaintChannelFrom16(ch, sc, count, sampleOffset, ltime - s_paintedtime);
ltime += count;
}
} while(ltime < end);
}
// transfer out according to DMA format
S_TransferPaintBuffer(end);
s_paintedtime = end;
}
}
| 23.963492 | 121 | 0.602106 |
ad8a86279274a6b55d151dfbe69f2fcfa20307dc | 575 | h | C | FCXUniversial/FCXUniversial/SKRating.h | FCXPods/FCXUniversial | 4faebfe4ea2990484e0a2c83080c0644d2f0fdc1 | [
"MIT"
] | null | null | null | FCXUniversial/FCXUniversial/SKRating.h | FCXPods/FCXUniversial | 4faebfe4ea2990484e0a2c83080c0644d2f0fdc1 | [
"MIT"
] | null | null | null | FCXUniversial/FCXUniversial/SKRating.h | FCXPods/FCXUniversial | 4faebfe4ea2990484e0a2c83080c0644d2f0fdc1 | [
"MIT"
] | 1 | 2018-08-23T15:29:05.000Z | 2018-08-23T15:29:05.000Z | //
// SKRating.h
// Tally
//
// Created by 冯 传祥 on 2017/7/29.
// Copyright © 2017年 冯 传祥. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface SKRating : NSObject
/**
* 调用评价
*
* @param appID 当前应用的appID
* @param finish 好评逻辑完成后的回调
*/
+ (void)startRating:(NSString*)appID
apppKey:(NSString *)appKey
controller:(UIViewController *)controller
finish:(void(^)(BOOL success))finish;
+ (void)goAppStore:(NSString*)appID controller:(UIViewController *)controller;//!<下载页
+ (void)goRating:(NSString *)appID;//!<评价页
@end
| 21.296296 | 85 | 0.652174 |
09895a198d3bcf851a6a35eb825d1d56f4578d6f | 9,079 | h | C | Generalizations/src/LocalOpt.h | nguyenthanhvuh/coloring | 52fcd27da85a857a439966b3928bb414dbb06aa3 | [
"MIT"
] | null | null | null | Generalizations/src/LocalOpt.h | nguyenthanhvuh/coloring | 52fcd27da85a857a439966b3928bb414dbb06aa3 | [
"MIT"
] | null | null | null | Generalizations/src/LocalOpt.h | nguyenthanhvuh/coloring | 52fcd27da85a857a439966b3928bb414dbb06aa3 | [
"MIT"
] | null | null | null |
/*
This functions "GREEDILY" assign colors to vertices.
It will return a VALID colors set results, but most certainly not OPTIMAL
TODO: do something like XRLF, only get 70% or so percent of the vertices colored
using greedy method. the 30 % left = > random
*/
int chooseV(const int color[], const int inColor[],const int &OPTION){
int chosenV=-1;
if(OPTION == MAX_DEG){
int maxTest=0,vAdjSize;
for(int i = 0;i<nVertices;++i){
if (color[i]==-1){//only choose UNcolored
vAdjSize=pVertices[i]->adj.size();
if (maxTest<vAdjSize){
maxTest=vAdjSize; chosenV=i;
}
}
}//for (i=0:nVertices)
}
if(OPTION==RANDOM_CHOOSE){
vector<int>availV;
for(int i = 0 ; i < nVertices ; ++i){
if(color[i]==-1) availV.push_back(i);
}
chosenV=availV.empty()?-1:availV[genrand_int32()%availV.size()];
}
if(OPTION==MAX_COLOR){
int maxC=-1;
for(int i = 0;i<nVertices;++i){
if (color[i]==-1){//only choose UNcolored
if (maxC<inColor[i]){
maxC=inColor[i]; chosenV=i;
}
}
}//for (i=0:nVertices)
}
return chosenV;
}
void getIG(int colorV[],const int &nVertices, const int &nEdges){
int nUnColored=nVertices;//nothing is colored yet
int currentColor=-1; //color Index starts with 0
//init
for(int i = 0 ; i < nVertices ;++i){colorV[i]=-1;}
vector<int>forbiddenSet;
int maxInForbidden, chosenV, vAdjSize, lowerC, upperC;
while(nUnColored> 0){
chosenV=chooseV(colorV,NULL,IG_OPT);
if(BB)assert(chosenV<nVertices);
if(chosenV==-1){
if(BB)printf("chosenV is -1 , break\n");
break; //break from while loop, nothing else to choose
}
forbiddenSet.clear();maxInForbidden=-1; //reset
vAdjSize=pVertices[chosenV]->adj.size();
for(int i = 0 ; i < vAdjSize ; ++i){
int aV = pVertices[chosenV]->adj.at(i); //adjacent Vertex
if(colorV[aV]!=-1){//if this neighbored is colored
if(BB)assert(chosenV!=aV);
if(BB)assert(weightMatrix[aV][chosenV]==weightMatrix[aV][chosenV]);
lowerC=colorV[aV]-weightMatrix[aV][chosenV] + 1;
if(lowerC<0)lowerC=0;
upperC=colorV[aV]+weightMatrix[aV][chosenV] - 1;
/* printf("lowerC %d , upperC %d, vertex %d , color %d, weight(%d,%d) is %d\n",
lowerC+1,upperC+1,aV+1,colorV[aV]+1,aV+1,chosenV+1,weightMatrix[aV][chosenV]);
*/
for(int j = lowerC ; j <= upperC ; ++j){
bool pushBack = true;
for(int g=0;g<forbiddenSet.size();++g){
if(forbiddenSet.at(g)==j){pushBack=false;break;}
}
if(pushBack){forbiddenSet.push_back(j);if(j>maxInForbidden)maxInForbidden=j;}
if(BB){//making sure no duplicates in forbiddenSet
for(int g=0;g<forbiddenSet.size();++g){
for(int g1=0;g1<forbiddenSet.size();++g1){
if(g!=g1){assert(forbiddenSet.at(g)!=forbiddenSet.at(g1));}
}
}
}
}//lowerC to upperC loop
}//if neighboris colored
}//end for all neighbor
//The following code block determines and assign the color to the chosen vertex (chosenV)
if(forbiddenSet.empty()){
currentColor=0;//no forbidden, assign the smallest, actually can be anything since no forbidden
}
else{
/*
Given a SORTED forbidden set, determines if the smallest number that is NOT in that forbidden set
e.g, forbiddenSet = "0 1 2 3 5 7 8 9 10 13 15"
the chosen color will be "4", since it's the smallest that's NOT in the forbidden set.
If the forbiddenSet = " 0 1 2 3 4 5 6 7 8 9 10 " , then the next color is 10+1 , or 11.
*/
//printVector("forbidden",forbiddenSet);
//since index start from 0, so even if the largest in forbidden is 0,
//that still means cannot consider that one lement
//this damn BUG costs me 4 HOURS !!!!
//the BUG itself is easy to fix but realizing the BUG was caused by this is not
//the damn bool tempA[] was exceeded and modified values from bool isColored[] !!!
int aSize = maxInForbidden+1;
bool tempA[aSize];
for(int g=0;g<aSize;++g){
tempA[g]=true;//consider these
}
for(int g=0;g<forbiddenSet.size();++g){
tempA[forbiddenSet.at(g)]=false ; // don't consider these
}
int TColor = -1;
for(int g=0;g<maxInForbidden;++g){
if(tempA[g]){TColor=g ; break;}
}
//determine current color
currentColor=TColor>-1?TColor:maxInForbidden+1;
//printf("currentColor %d\n",currentColor);
}
//assigning color
// if(colorV[chosenV]==-1 || isColored[chosenV]==false){
// printf("vertex %d already COLORED(%d), %d\n",chosenV+1,isColored[chosenV],colorV[chosenV]+1);
// };
if(BB)assert(currentColor!=-1);
colorV[chosenV]=currentColor;
nUnColored--;
//printf("%d, chosen %d colored %d\n",nUnColored,chosenV+1,colorV[chosenV]+1);
}//while
//if there's any uncolored, color it with the smallest color index
for(int i = 0 ; i < nVertices ;++i){if(colorV[i]==-1) colorV[i]=0; }
//get the "DISTINCT" colors, e.g., if the colors used are 1, 100,
//then the nColors is just 2 .
}
int IG(int bestConfigA[],const int &nVertices, const int &nEdges){
int colorV[nVertices], t_maxK=-1;
if(IG_OPT==MAX_DEG){
getIG(colorV,nVertices,nEdges);
t_maxK=getMaxK(colorV);
if(t_maxK<maxK){
maxK=t_maxK;
copyArray(colorV,bestConfigA);//copy to result vector
}
}
if(IG_OPT==RANDOM_CHOOSE){
for(int i = 0 ; i < 20; ++i){
getIG(colorV,nVertices,nEdges);
t_maxK=getMaxK(colorV);
if(BB)printf("iteration %d , maxK %d\n",i,t_maxK);
if(t_maxK<maxK){
maxK=t_maxK;
copyArray(colorV,bestConfigA);//copy to result vector
if(BB)printf("--- new maxK %d\n",maxK);
}
}//for i
}
baseScore_MaxK=maxK;
addPheromoneScore(maxK,0,bestConfigA);//0 conflict
// for(int i = 0 ; i < nVertices ;++i){
// printVector("",pVertices[i]->phColor);
// }
if(BB){int conflictsTable[nVertices]; assert(updateConflictTableW(colorV,conflictsTable)==0);}
int bestResult=getDistinctColors(bestConfigA);
if(BB)printf("*** Ig distinct colors %d, maxK %d\n",bestResult,maxK);
return bestResult;
}//end IG()
int localOpt(const int inColor[], int lColor[], const int &nVertices, const int &nEdges){
for(int i = 0 ; i < nVertices ;++i){lColor[i]=-1;}
int currentColor=-1; //color Index starts with 0
vector<int>forbiddenSet;
int chosenV,lowerC,upperC,nUnColored=nVertices,maxInForbidden,vAdjSize;
while(nUnColored> 0){
chosenV=chooseV(lColor,inColor,MAX_COLOR);
if(BB)assert(chosenV!=-1);
forbiddenSet.clear();maxInForbidden=-1; //reset
vAdjSize=pVertices[chosenV]->adj.size();
for(int i = 0 ; i < vAdjSize ; ++i){
int aV = pVertices[chosenV]->adj.at(i); //adjacent Vertex
if(lColor[aV]!=-1){//if this neighbored is colored
lowerC = 0 ; //smallest avail
int tmpD = lColor[aV]-weightMatrix[aV][chosenV] + 1; ;
if (lowerC<tmpD) lowerC=tmpD;
upperC=lColor[aV]+weightMatrix[aV][chosenV] - 1;
/* printf("lowerC %d , upperC %d, vertex %d , color %d, weight(%d,%d) is %d\n",
lowerC+1,upperC+1,aV+1,colorV[aV]+1,aV+1,chosenV+1,weightMatrix[aV][chosenV]);
*/
for(int j = lowerC ; j <= upperC ; ++j){
bool pushBack = true;
for(int g=0;g<forbiddenSet.size();++g){
if(forbiddenSet.at(g)==j){pushBack=false;break;}
}
if(pushBack){forbiddenSet.push_back(j);if(j>maxInForbidden)maxInForbidden=j;}
if(BB){//making sure no duplicates in forbiddenSet
for(int g=0;g<forbiddenSet.size();++g){
for(int g1=0;g1<forbiddenSet.size();++g1){
if(g!=g1){assert(forbiddenSet.at(g)!=forbiddenSet.at(g1));}
}
}
}
}//lowerC to upperC loop
}//if neighboris colored
}//end for all neighbor
if(forbiddenSet.empty()){
currentColor=0;//no forbidden, assign the smallest, actually can be anything since no forbidden
}
else{
int aSize = maxInForbidden+1;
bool tempA[aSize];
for(int g=0;g<aSize;++g){tempA[g]=true;}
for(int g=0;g<forbiddenSet.size();++g){tempA[forbiddenSet.at(g)]=false ; }
int TColor = -1;
for(int g=0;g<maxInForbidden;++g){
if(tempA[g]){TColor=g ; break;}
}
currentColor=TColor>-1?TColor:maxInForbidden+1;
}
lColor[chosenV]=currentColor;
nUnColored--;
}//while
//if there's any uncolored, color it with the smallest color index
for(int i = 0 ; i < nVertices ;++i){
if(lColor[i]==-1) lColor[i]=0;
}
if(BB){int tempConflicts[nVertices];assert(updateConflictTableW(lColor,tempConflicts)==0); }
return getMaxK(lColor);
}
| 25.360335 | 103 | 0.598524 |
b63d662efc7e615d41de33169c4c8fd1f8963cc4 | 192 | h | C | Target Support Files/AFDateHelper/AFDateHelper-umbrella.h | Rigelp79/BrandNewPeopleMon | c7078c7fcea1a82c1fcf68be666cdffd98ec92c6 | [
"MIT"
] | 34 | 2016-05-02T02:37:08.000Z | 2021-06-03T18:43:33.000Z | Target Support Files/AFDateHelper/AFDateHelper-umbrella.h | Rigelp79/BrandNewPeopleMon | c7078c7fcea1a82c1fcf68be666cdffd98ec92c6 | [
"MIT"
] | 1 | 2017-01-05T04:21:07.000Z | 2017-01-07T04:20:22.000Z | Target Support Files/AFDateHelper/AFDateHelper-umbrella.h | Rigelp79/BrandNewPeopleMon | c7078c7fcea1a82c1fcf68be666cdffd98ec92c6 | [
"MIT"
] | 6 | 2016-05-03T19:43:04.000Z | 2019-02-06T12:30:23.000Z | #ifdef __OBJC__
#import <UIKit/UIKit.h>
#endif
#import "DateHelper.h"
FOUNDATION_EXPORT double AFDateHelperVersionNumber;
FOUNDATION_EXPORT const unsigned char AFDateHelperVersionString[];
| 19.2 | 66 | 0.828125 |
b6460d900a2692c9f4e4219624cec04cd0230e1e | 282 | h | C | include/Likely.h | airekans/Tpool | 2ba21ca68588d90e738f35c6ddcc17bb8b1f3f1d | [
"MIT"
] | 13 | 2015-05-19T11:08:44.000Z | 2021-07-11T01:00:35.000Z | include/Likely.h | guker/Tpool | 2ba21ca68588d90e738f35c6ddcc17bb8b1f3f1d | [
"MIT"
] | 17 | 2015-01-04T15:16:51.000Z | 2015-04-16T04:43:38.000Z | include/Likely.h | guker/Tpool | 2ba21ca68588d90e738f35c6ddcc17bb8b1f3f1d | [
"MIT"
] | 11 | 2015-04-30T09:21:59.000Z | 2021-10-04T07:48:34.000Z | #ifndef _TPOOL_LIKELY_H_
#define _TPOOL_LIKELY_H_
#if defined(__GNUC__)
#define TPOOL_LIKELY(x) (__builtin_expect((x), 1))
#define TPOOL_UNLIKELY(x) (__builtin_expect((x), 0))
#else
#define TPOOL_LIKELY(x) (x)
#define TPOOL_UNLIKELY(x) (x)
#endif
#endif /* _TPOOL_LIKELY_H_ */
| 20.142857 | 52 | 0.741135 |
b677d8c29eed2f16703d6c444a7475560b4e419e | 894 | h | C | psutil/arch/aix/common.h | ulisesh/psutil | f7e898b0987f97352c7551bdd9b29b594e1236f6 | [
"BSD-3-Clause"
] | 8,285 | 2015-01-03T15:47:51.000Z | 2022-03-31T19:55:30.000Z | psutil/arch/aix/common.h | vsajip/psutil | 2597253a31bc9f49772242cd249f30331d58fd7c | [
"BSD-3-Clause"
] | 1,928 | 2016-11-28T17:13:18.000Z | 2022-03-31T21:43:19.000Z | psutil/arch/aix/common.h | vsajip/psutil | 2597253a31bc9f49772242cd249f30331d58fd7c | [
"BSD-3-Clause"
] | 1,496 | 2015-01-01T12:24:40.000Z | 2022-03-31T13:54:35.000Z | /*
* Copyright (c) 2017, Arnon Yaari
* All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#ifndef __PSUTIL_AIX_COMMON_H__
#define __PSUTIL_AIX_COMMON_H__
#include <sys/core.h>
#define PROCINFO_INCR (256)
#define PROCSIZE (sizeof(struct procentry64))
#define FDSINFOSIZE (sizeof(struct fdsinfo64))
#define KMEM "/dev/kmem"
typedef u_longlong_t KA_T;
/* psutil_kread() - read from kernel memory */
int psutil_kread(int Kd, /* kernel memory file descriptor */
KA_T addr, /* kernel memory address */
char *buf, /* buffer to receive data */
size_t len); /* length to read */
struct procentry64 *
psutil_read_process_table(
int * num /* out - number of processes read */
);
#endif /* __PSUTIL_AIX_COMMON_H__ */
| 27.9375 | 73 | 0.64877 |
16e6931f0d6dc9b9cc48b0e1b297085784648a7d | 1,090 | h | C | include/Clouds.h | CrustaShrimp/METAR | 002f63220067babdd5f2df9233a673eebb008c69 | [
"MIT"
] | 1 | 2020-03-15T21:29:13.000Z | 2020-03-15T21:29:13.000Z | include/Clouds.h | CrustaShrimp/METAR | 002f63220067babdd5f2df9233a673eebb008c69 | [
"MIT"
] | null | null | null | include/Clouds.h | CrustaShrimp/METAR | 002f63220067babdd5f2df9233a673eebb008c69 | [
"MIT"
] | null | null | null | //
// Copyright (c) 2018 James A. Chappell (rlrrlrll@gmail.com)
//
// METAR clouds decoder
//
#ifndef STORAGE_B_WEATHER_CLOUDS_H_
#define STORAGE_B_WEATHER_CLOUDS_H_
#include "defines.h"
#ifndef NO_STD
#include <memory>
#endif
namespace Storage_B
{
namespace Weather
{
class Clouds
{
public:
enum class cover
{
SKC,
CLR,
NSC,
FEW,
SCT,
BKN,
OVC
};
enum class type
{
undefined = -1,
TCU,
CB,
ACC
};
static
#ifndef NO_STD
std::shared_ptr<Clouds>
#else
Clouds *
#endif
Create(const char *str, bool temp = false);
virtual ~Clouds() = default;
virtual cover Cover() const = 0;
//
// Layer altitude in multiples of 100 feet or 30 meters
//
virtual int Altitude() const = 0;
virtual bool hasAltitude() const = 0;
virtual type CloudType() const = 0;
virtual bool hasCloudType() const = 0;
virtual bool Temporary() const = 0;
};
}
}
#endif
| 15.797101 | 61 | 0.547706 |
795a271b3900ed59fa447dfed15219557976c753 | 1,161 | h | C | weblayer/browser/page_impl.h | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 14,668 | 2015-01-01T01:57:10.000Z | 2022-03-31T23:33:32.000Z | weblayer/browser/page_impl.h | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 86 | 2015-10-21T13:02:42.000Z | 2022-03-14T07:50:50.000Z | weblayer/browser/page_impl.h | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,941 | 2015-01-02T11:32:21.000Z | 2022-03-31T16:35:46.000Z | // Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef WEBLAYER_BROWSER_PAGE_IMPL_H_
#define WEBLAYER_BROWSER_PAGE_IMPL_H_
#include "build/build_config.h"
#include "content/public/browser/page_user_data.h"
#include "weblayer/public/page.h"
#if defined(OS_ANDROID)
#include "base/android/scoped_java_ref.h"
#endif
namespace weblayer {
class PageImpl : public Page, public content::PageUserData<PageImpl> {
public:
PageImpl(const PageImpl&) = delete;
PageImpl& operator=(const PageImpl&) = delete;
~PageImpl() override;
#if defined(OS_ANDROID)
void SetJavaPage(JNIEnv* env,
const base::android::JavaParamRef<jobject>& java_page);
base::android::ScopedJavaGlobalRef<jobject> java_page() { return java_page_; }
#endif
private:
explicit PageImpl(content::Page& page);
friend class content::PageUserData<PageImpl>;
PAGE_USER_DATA_KEY_DECL();
#if defined(OS_ANDROID)
base::android::ScopedJavaGlobalRef<jobject> java_page_;
#endif
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_PAGE_IMPL_H_
| 25.8 | 80 | 0.756245 |
f90a1649208a71e8044ba1040af7d34814a67753 | 402 | h | C | rcr/robots/scribbler2/HS2State.h | titos-carrasco/Scribbler2-Cpp | 241b46617ad00099cb409593d90f17c2dbc8f0f8 | [
"MIT"
] | null | null | null | rcr/robots/scribbler2/HS2State.h | titos-carrasco/Scribbler2-Cpp | 241b46617ad00099cb409593d90f17c2dbc8f0f8 | [
"MIT"
] | null | null | null | rcr/robots/scribbler2/HS2State.h | titos-carrasco/Scribbler2-Cpp | 241b46617ad00099cb409593d90f17c2dbc8f0f8 | [
"MIT"
] | null | null | null | #ifndef HS2STATE_H
#define HS2STATE_H
#include <iostream>
#include <stdint.h>
namespace rcr {
namespace robots {
namespace scribbler2 {
class HS2State
{
public:
const uint8_t inPins;
const uint8_t outPins;
public:
HS2State( uint8_t inPins_, uint8_t outPins_ );
~HS2State();
friend std::ostream& operator<<( std::ostream& os, const HS2State& obj );
};
}}}
#endif // HS2STATE_H
| 15.461538 | 77 | 0.699005 |
58fce2dacfddd89f36e49bb147015eb13dfdd81a | 841 | h | C | examples/derivation/overload/account.h | PatrickTrentin88/intro_c-_qt | 1d73ef364711fac7b46cd3752258c0273c689835 | [
"MIT"
] | null | null | null | examples/derivation/overload/account.h | PatrickTrentin88/intro_c-_qt | 1d73ef364711fac7b46cd3752258c0273c689835 | [
"MIT"
] | null | null | null | examples/derivation/overload/account.h | PatrickTrentin88/intro_c-_qt | 1d73ef364711fac7b46cd3752258c0273c689835 | [
"MIT"
] | null | null | null | #ifndef ACCOUNT_H
#define ACCOUNT_H
#include <QDate>
#include <QString>
//start
class Account {
public:
Account(unsigned acctno, double bal, QString owner);
virtual ~Account() { }
virtual void deposit(double amt);
virtual QString toString() const;
virtual QString toString(char delimiter); /* Overloaded
function. */
protected:
unsigned m_AcctNo;
double m_Balance;
QString m_Owner;
};
class InsecureAccount: public Account {
public:
InsecureAccount(unsigned acctno, double bal, QString owner);
QString toString() const; /* Overrides base method
and hides toString(char). */
void deposit(double amt, QDate postDate); /* Does not
override any method, but hides all Account::deposit()
methods. */
};
//end
#endif // #ifndef ACCOUNT_H
| 26.28125 | 72 | 0.661118 |
0fb0bf1bd46684eccc25d914da9242a16ba2d788 | 2,507 | c | C | L09/deadlock.c | tcew/CMDA3634FA17 | f48e30ec58106b9fa5935b8696cc69dc79b6719f | [
"MIT"
] | 1 | 2019-06-18T16:45:21.000Z | 2019-06-18T16:45:21.000Z | L09/deadlock.c | tcew/CMDA3634FA17 | f48e30ec58106b9fa5935b8696cc69dc79b6719f | [
"MIT"
] | 1 | 2017-11-07T21:53:37.000Z | 2017-11-07T21:53:37.000Z | L09/deadlock.c | tcew/CMDA3634FA17 | f48e30ec58106b9fa5935b8696cc69dc79b6719f | [
"MIT"
] | 11 | 2017-09-27T20:27:51.000Z | 2022-01-25T13:04:13.000Z |
#include <stdio.h>
#include <stdlib.h>
#include "mpi.h"
void deadlockV1(){
MPI_Status status;
int rank, tag= 99;
double *recvBuffer = (double*) malloc(sizeof(double));
double *sendBuffer = (double*) malloc(sizeof(double));
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
// rank 0 and 1 try to send to each other
if(rank==0){
int dest = 1, source = 1;
MPI_Recv(recvBuffer, 1, MPI_DOUBLE, source, tag, MPI_COMM_WORLD,
&status);
MPI_Send(sendBuffer, 1, MPI_DOUBLE, dest, tag, MPI_COMM_WORLD);
}
if(rank==1){
int dest = 0, source = 0;
MPI_Recv(recvBuffer, 1, MPI_DOUBLE, source, tag, MPI_COMM_WORLD,
&status);
MPI_Send(sendBuffer, 1, MPI_DOUBLE, dest, tag, MPI_COMM_WORLD);
}
}
void undeadlockV1(){
MPI_Status status;
int rank, tag= 99;
double *recvBuffer = (double*) malloc(sizeof(double));
double *sendBuffer = (double*) malloc(sizeof(double));
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
// rank 0 and 1 try to send to each other
if(rank==0){
int dest = 1, source = 1;
MPI_Recv(recvBuffer, 1, MPI_DOUBLE, source, tag, MPI_COMM_WORLD,
&status);
MPI_Send(sendBuffer, 1, MPI_DOUBLE, dest, tag, MPI_COMM_WORLD);
}
if(rank==1){
int dest = 0, source = 0;
MPI_Send(sendBuffer, 1, MPI_DOUBLE, dest, tag, MPI_COMM_WORLD);
MPI_Recv(recvBuffer, 1, MPI_DOUBLE, source, tag, MPI_COMM_WORLD,
&status);
}
}
void undeadlockV2(){
MPI_Status status;
MPI_Request sendRequest, recvRequest;
int rank, tag= 99;
double *recvBuffer = (double*) malloc(sizeof(double));
double *sendBuffer = (double*) malloc(sizeof(double));
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
// rank 0 and 1 try to send to each other
if(rank==0){
int dest = 1, source = 1;
MPI_Irecv(recvBuffer, 1, MPI_DOUBLE, source, tag, MPI_COMM_WORLD,
&recvRequest);
MPI_Isend(sendBuffer, 1, MPI_DOUBLE, dest, tag, MPI_COMM_WORLD,
&sendRequest);
}
if(rank==1){
int dest = 0, source = 0;
MPI_Irecv(recvBuffer, 1, MPI_DOUBLE, source, tag, MPI_COMM_WORLD,
&recvRequest);
MPI_Isend(sendBuffer, 1, MPI_DOUBLE, dest, tag, MPI_COMM_WORLD,
&sendRequest);
}
/* block until message sent */
MPI_Wait(&sendRequest, &status);
/* block until message received */
MPI_Wait(&recvRequest, &status);
}
int main(int argc, char **argv){
MPI_Init(&argc, &argv);
// deadlockV1();
// undeadlockV1();
undeadlockV2();
MPI_Finalize();
exit(0);
return 0;
}
| 23.429907 | 69 | 0.649781 |
a79c216e949cb7a36357bab34e5b7e2aaaebf1d2 | 728 | h | C | ui/color/color_test_ids.h | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 14,668 | 2015-01-01T01:57:10.000Z | 2022-03-31T23:33:32.000Z | ui/color/color_test_ids.h | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 113 | 2015-05-04T09:58:14.000Z | 2022-01-31T19:35:03.000Z | ui/color/color_test_ids.h | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,941 | 2015-01-02T11:32:21.000Z | 2022-03-31T16:35:46.000Z | // Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_COLOR_COLOR_TEST_IDS_H_
#define UI_COLOR_COLOR_TEST_IDS_H_
#include "ui/color/color_id.h"
namespace ui {
// Test-only color IDs.
enum TestColorIds : ColorId {
kTestColorsStart = kUiColorsEnd,
kColorTest0 = kTestColorsStart,
kColorTest1,
kColorTest2,
kTestColorsEnd,
};
// Test-only color set IDs.
enum TestColorSetIds : ColorSetId {
kTestColorSetsStart = kUiColorSetsEnd,
kColorSetTest0 = kTestColorSetsStart,
kColorSetTest1,
kColorSetTest2,
kTestColorSetsEnd,
};
} // namespace ui
#endif // UI_COLOR_COLOR_TEST_IDS_H_
| 19.675676 | 73 | 0.762363 |
db2f1733e6bef8b64783cdfaac457650f20e54c2 | 4,201 | c | C | src/ble.c | cvetaevvitaliy/ZigBee-BLE-multiprotocol | 35eb3a55bf430978c30f9f51a34d74d45569182b | [
"Apache-2.0"
] | 1 | 2022-01-25T10:40:08.000Z | 2022-01-25T10:40:08.000Z | src/ble.c | cvetaevvitaliy/ZigBee-BLE-multiprotocol | 35eb3a55bf430978c30f9f51a34d74d45569182b | [
"Apache-2.0"
] | null | null | null | src/ble.c | cvetaevvitaliy/ZigBee-BLE-multiprotocol | 35eb3a55bf430978c30f9f51a34d74d45569182b | [
"Apache-2.0"
] | null | null | null | /**
* @brief This is part of the project 'Light Switch'
* @file 'ble.c'
* Copyright (c) Vitaliy Nimych <vitaliy.nimych@gmail.com>
* Created 06.10.2021
* License-Identifier: ???
**/
#include <zephyr/types.h>
#include <stddef.h>
#include <inttypes.h>
#include <errno.h>
#include <zephyr.h>
#include <sys/printk.h>
#include <bluetooth/bluetooth.h>
#include <bluetooth/hci.h>
#include <bluetooth/conn.h>
#include <bluetooth/uuid.h>
#include <bluetooth/gatt.h>
#include <bluetooth/gatt_dm.h>
#include <bluetooth/scan.h>
#include <bluetooth/services/bas_client.h>
#include <dk_buttons_and_leds.h>
#include <settings/settings.h>
/**
* Button to read the battery value
*/
#define KEY_READVAL_MASK DK_BTN1_MSK
#define BAS_READ_VALUE_INTERVAL (10 * MSEC_PER_SEC)
#define BLE_LOG "[ BLE ] "
static struct bt_conn *default_conn;
extern void zigbee_send(void);
static void scan_filter_match(struct bt_scan_device_info *device_info,
struct bt_scan_filter_match *filter_match,
bool connectable)
{
char addr[BT_ADDR_LE_STR_LEN];
bt_addr_le_to_str(device_info->recv_info->addr, addr, sizeof(addr));
if (device_info->recv_info->rssi > -52) {
printk(BLE_LOG "Filters matched. Address: %s RSSI: '%d'\n", addr, device_info->recv_info->rssi);
zigbee_send();
} else {
printk(BLE_LOG "Address: %s LOW RSSI: '%d'\n", addr, device_info->recv_info->rssi);
}
}
static void scan_filter_no_match(struct bt_scan_device_info *device_info,
bool connectable)
{
int err;
struct bt_conn *conn;
char addr[BT_ADDR_LE_STR_LEN];
#if 0
if (device_info->recv_info->rssi > -30) {
bt_addr_le_to_str(device_info->recv_info->addr, addr, sizeof(addr));
printk("Found %s RSSI; '%d'\n", addr, device_info->recv_info->rssi);
}
#endif
if (device_info->recv_info->adv_type == BT_GAP_ADV_TYPE_ADV_DIRECT_IND) {
bt_addr_le_to_str(device_info->recv_info->addr, addr,
sizeof(addr));
printk("Direct advertising received from %s\n", addr);
bt_scan_stop();
err = bt_conn_le_create(device_info->recv_info->addr,
BT_CONN_LE_CREATE_CONN,
device_info->conn_param, &conn);
if (!err) {
default_conn = bt_conn_ref(conn);
bt_conn_unref(conn);
}
}
}
BT_SCAN_CB_INIT(scan_cb, scan_filter_match, scan_filter_no_match,
NULL, NULL);
#define BT_UUID_THINGY_VAL \
BT_UUID_128_ENCODE(0x97BD89C7, 0xE74E, 0x7C53, 0x98B2, 0x4EAECAF43CA7)
#define BT_UUID_THINGY \
BT_UUID_DECLARE_128(BT_UUID_THINGY_VAL)
static void scan_init(void)
{
int err;
struct bt_le_scan_param scan_param = {
.type = BT_SCAN_TYPE_SCAN_ACTIVE,
.options = BT_LE_SCAN_OPT_FILTER_DUPLICATE,
.interval = 0x0010,
.window = 0x0010,
};
struct bt_scan_init_param scan_init = {
.connect_if_match = 0,
.scan_param = NULL,
.conn_param = BT_LE_CONN_PARAM_DEFAULT
};
bt_scan_init(&scan_init);
bt_scan_cb_register(&scan_cb);
err = bt_scan_filter_add(BT_SCAN_FILTER_TYPE_UUID, BT_UUID_DECLARE_16(0xFEE0));
if (err) {
printk(BLE_LOG "Scanning filters cannot be set (err %d)\n", err);
return;
}
err = bt_scan_filter_enable(BT_SCAN_UUID_FILTER, false);
if (err) {
printk(BLE_LOG "Filters cannot be turned on (err %d)\n", err);
}
}
void ble_init(void)
{
int err;
printk(BLE_LOG "Starting Bluetooth\n");
err = bt_enable(NULL);
if (err) {
printk("Bluetooth init failed (err %d)\n", err);
return;
}
printk(BLE_LOG "Bluetooth initialized\n");
if (IS_ENABLED(CONFIG_SETTINGS)) {
settings_load();
}
scan_init();
err = bt_scan_start(BT_SCAN_TYPE_SCAN_ACTIVE);
if (err) {
printk(BLE_LOG "Scanning failed to start (err %d)\n", err);
return;
}
printk(BLE_LOG "Scanning successfully started\n");
}
| 26.929487 | 104 | 0.626517 |
71c59870746d193da9b3409b159bc74f97ed8c86 | 684 | h | C | crazyflie_cpp/include/crazyflie_cpp/ITransport.h | netkimjh/crazyflie_ros | 2c5a5b403c878710679555b69149fcb4fc296316 | [
"MIT"
] | 2 | 2018-03-13T09:18:47.000Z | 2020-12-29T06:45:40.000Z | crazyflie_cpp/include/crazyflie_cpp/ITransport.h | netkimjh/crazyflie_ros | 2c5a5b403c878710679555b69149fcb4fc296316 | [
"MIT"
] | 3 | 2017-04-13T03:53:21.000Z | 2018-04-13T20:06:07.000Z | crazyflie_cpp/include/crazyflie_cpp/ITransport.h | netkimjh/crazyflie_ros | 2c5a5b403c878710679555b69149fcb4fc296316 | [
"MIT"
] | 10 | 2016-11-15T00:00:40.000Z | 2021-06-07T15:11:46.000Z | #pragma once
#include <stdint.h>
class ITransport
{
public:
struct Ack
{
Ack()
: ack(0)
, size(0)
{}
uint8_t ack:1;
uint8_t powerDet:1;
uint8_t retry:4;
uint8_t data[32];
uint8_t size;
}__attribute__((packed));
public:
virtual ~ITransport() {}
virtual void sendPacket(
const uint8_t* data,
uint32_t length,
Ack& result) = 0;
virtual void sendPacketNoAck(
const uint8_t* data,
uint32_t length) = 0;
virtual void send2PacketsNoAck(
const uint8_t* data,
uint32_t totalLength)
{
sendPacketNoAck(data, totalLength / 2);
sendPacketNoAck(data + totalLength / 2, totalLength / 2);
}
};
| 15.906977 | 61 | 0.624269 |
3b1ecb7b7e79f3af5005f8ca1d8835fbe62c33a2 | 554 | c | C | suiter/pre-templates/cecko.c | studenma/Suiter | ca982645cb5c349dc2f944364edfc191454754dc | [
"MIT"
] | null | null | null | suiter/pre-templates/cecko.c | studenma/Suiter | ca982645cb5c349dc2f944364edfc191454754dc | [
"MIT"
] | null | null | null | suiter/pre-templates/cecko.c | studenma/Suiter | ca982645cb5c349dc2f944364edfc191454754dc | [
"MIT"
] | null | null | null | /* Example using isxdigit by TechOnTheNet.com */
#include <stdio.h>
#include <assert.h>
int main(int argc, const char * argv[]) {
/* Define an expression */
int exp = 1;
/* Display the value of exp */
printf("Exp is %d\n", exp);
/* Assert should not exit in this case since exp is not 0 */
assert(exp);
/* Change expression to 0 */
exp = 0;
/* Display the value of exp */
printf("Exp is %d\n", exp);
/* In this case exp is 0 so assert will display an error and exit */
assert(exp);
return 0;
} | 21.307692 | 72 | 0.592058 |
7dc1879007b5565180e90ab92b393205240797b0 | 4,530 | h | C | oneflow/core/common/tensor_buffer.h | wangyuyue/oneflow | 0a71c22fe8355392acc8dc0e301589faee4c4832 | [
"Apache-2.0"
] | 3,285 | 2020-07-31T05:51:22.000Z | 2022-03-31T15:20:16.000Z | oneflow/core/common/tensor_buffer.h | duijiudanggecl/oneflow | d2096ae14cf847509394a3b717021e2bd1d72f62 | [
"Apache-2.0"
] | 2,417 | 2020-07-31T06:28:58.000Z | 2022-03-31T23:04:14.000Z | oneflow/core/common/tensor_buffer.h | duijiudanggecl/oneflow | d2096ae14cf847509394a3b717021e2bd1d72f62 | [
"Apache-2.0"
] | 520 | 2020-07-31T05:52:42.000Z | 2022-03-29T02:38:11.000Z | /*
Copyright 2020 The OneFlow Authors. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#ifndef ONEFLOW_CORE_COMMON_TENSOR_BUFFER_H_
#define ONEFLOW_CORE_COMMON_TENSOR_BUFFER_H_
#include "oneflow/core/common/shape.h"
#include "oneflow/core/common/data_type.h"
#include "oneflow/core/common/util.h"
#include "oneflow/core/memory/memory_allocator.h"
namespace oneflow {
inline void CheckTensorBufferDataType(DataType val) {
CHECK(val != DataType::kTensorBuffer && val != DataType::kOFRecord)
<< "TensorBuffer only support POD as internal data type.";
}
class TensorBuffer {
public:
struct Deleter {
void operator()(void* ptr) { MemoryAllocatorImpl::DeallocateUnPinnedHostMem(ptr); }
};
typedef std::unique_ptr<void, Deleter> BufferType;
OF_DISALLOW_COPY_AND_MOVE(TensorBuffer);
TensorBuffer()
: data_(nullptr), num_bytes_(0), shape_(Shape()), data_type_(DataType::kInvalidDataType) {}
virtual ~TensorBuffer() = default;
const Shape& shape() const { return shape_; }
DataType data_type() const { return data_type_; }
void set_data_type(DataType val) {
CheckTensorBufferDataType(val);
if (data_type_ == val) { return; }
if (val == DataType::kInvalidDataType) {
data_type_ = val;
return;
} else {
Resize(shape_, val);
}
}
template<typename T = void>
inline T* mut_data() {
if (data_ == nullptr) { return nullptr; }
CheckDataType<T>(data_type_);
return static_cast<T*>(data_.get());
}
template<typename T = void>
inline const T* data() const {
if (data_ == nullptr) { return nullptr; }
CheckDataType<T>(data_type_);
return static_cast<const T*>(data_.get());
}
void reset() {
shape_ = Shape();
data_.reset();
data_type_ = DataType::kInvalidDataType;
num_bytes_ = 0;
}
void reserve(size_t new_num_bytes) {
if (new_num_bytes <= num_bytes_) { return; }
data_.reset();
data_.reset(MemoryAllocatorImpl::AllocateUnPinnedHostMem(new_num_bytes));
num_bytes_ = new_num_bytes;
}
int64_t elem_cnt() const { return shape_.elem_cnt(); }
size_t nbytes() const { return elem_cnt() * GetSizeOfDataType(data_type_); }
size_t capacity() const { return num_bytes_; }
void Resize(const Shape& new_shape) { Resize(new_shape, data_type_); }
void Resize(const Shape& new_shape, DataType new_type) {
int64_t elem_cnt = new_shape.elem_cnt();
if (new_type == DataType::kInvalidDataType || elem_cnt == 0) { return; }
CheckTensorBufferDataType(new_type);
data_type_ = new_type;
shape_ = new_shape;
size_t new_num_bytes = elem_cnt * GetSizeOfDataType(new_type);
new_num_bytes = RoundUp(new_num_bytes, kTensorBufferAlignedSize);
if (new_num_bytes > num_bytes_) {
new_num_bytes =
std::max(new_num_bytes, RoundUp(num_bytes_ * growth_factor_, kTensorBufferAlignedSize));
reserve(new_num_bytes);
} else if (new_num_bytes < num_bytes_ * shrink_threshold_) {
data_.reset();
num_bytes_ = 0;
reserve(new_num_bytes);
}
}
void CopyFrom(const TensorBuffer& src) {
if (&src == this) { return; }
Resize(src.shape(), src.data_type());
memcpy(mut_data(), src.data(), nbytes());
}
void Swap(TensorBuffer* lhs) {
data_.swap(lhs->data_);
std::swap(num_bytes_, lhs->num_bytes_);
std::swap(shape_, lhs->shape_);
std::swap(data_type_, lhs->data_type_);
}
private:
// TODO(chengcheng)
static double growth_factor_;
static double shrink_threshold_;
static constexpr size_t kTensorBufferAlignedSize = 1024;
BufferType data_;
size_t num_bytes_;
Shape shape_;
DataType data_type_;
};
#define BUFFER_DATA_TYPE_SEQ OF_PP_MAKE_TUPLE_SEQ(TensorBuffer, DataType::kTensorBuffer)
template<>
struct GetDataType<TensorBuffer> : std::integral_constant<DataType, DataType::kTensorBuffer> {};
inline TensorBuffer GetTypeByDataType(std::integral_constant<DataType, DataType::kTensorBuffer>) {
return {};
}
} // namespace oneflow
#endif // ONEFLOW_CORE_COMMON_TENSOR_BUFFER_H_
| 30 | 98 | 0.713687 |
4794a12d1f2c3066f40b6f07549dc05ac3ab588c | 7,327 | c | C | franz/frame.c | krytarowski/franz-lisp-christos | 7f529800f415d583b4c1f0ae90dec19ad3fb1a8a | [
"BSD-4-Clause-UC"
] | 2 | 2021-08-17T08:05:11.000Z | 2021-08-17T08:07:14.000Z | franz/frame.c | krytarowski/franz-lisp-christos | 7f529800f415d583b4c1f0ae90dec19ad3fb1a8a | [
"BSD-4-Clause-UC"
] | null | null | null | franz/frame.c | krytarowski/franz-lisp-christos | 7f529800f415d583b4c1f0ae90dec19ad3fb1a8a | [
"BSD-4-Clause-UC"
] | 1 | 2019-07-15T16:38:53.000Z | 2019-07-15T16:38:53.000Z | /*-
* frame.c
* non local goto handlers
*
* (c) copyright 1982, Regents of the University of California
*/
#include <sys/cdefs.h>
#ifndef lint
#ifdef notdef
static char *rcsid
__attribute__((__unused__)) =
"Header: frame.c,v 1.3 87/12/14 16:51:52 sklower Exp";
#else
__RCSID("$Id: frame.c,v 1.6 2012/04/14 21:49:19 christos Exp $");
#endif
#endif
#include "global.h"
#include "frame.h"
/*
* This is a collection of routines for manipulating evaluation frames. Such
* frames are generated to mark the state of execution at a certain spot.
* They are created upon entry to prog, do, catch, errset and other misc.
* functions (such as eval when in *rset mode).
*
* As described in h/frame.h, each frame is identified by a class, which says
* who created the frame. The global variable errp points to the first
* (newest) frame on the stack. The standard way to create a frame is to say
*
* errp = Pushframe(class,arg1,arg2); / * create and link in new frame of
* give class * /
*
* poping the frame must be done explicity if the routine was not exited by a
* non-local goto. This is done by errp = Popframe();
*
* When a frame is created, it marks the current state on the runtime stack.
* Execution will continues after the Pushframe call with the value of the
* global variable 'retval' set to 0. Some time later control may be thrown
* up the stack and it will seem that Pushframe returned again. This time
* retval will contain a non-zero value indicating what caused the non-local
* jump. retval will have one of the values from C_???? in h/frame.h . It
* will not have just of the C_???? values, it will only have a value which
* makes sense. For example, coming out of a Pushframe(F_CATCH,tag,nil);
* retval will either be 0 (initially) or C_THROW, [and in addition it will
* already have been determined that the tag of the catch matches the tag
* being thrown, [[ this does not apply to GO's and PROG tags]] ].
*
* In doing throws, goto's, returns, or errors up the stack we are always
* conscious of the possiblity of unwind-protect sitting between where
* control starts and where it wants to get. Thus it may be necessary to
* save the state of the non-local jump, give control to the unwind-protect
* and have it continue the non-local jump.
*/
static struct frame *Inlthrow(int, lispval, lispval);
/*
* Inonlocalgo(class, arg1, arg2) :: do a general non-local goto.
* class - one of the C_???? in h/frame.h
* arg1 - tag in C_THROW, C_GO; value in C_RETURN
* arg2 - value in C_THROW;
* this handles GO's, THROW's, RETURN's but not errors, which have more
* state to throw and a lot of different things to do if there is no one
* to catch the error.
*
* This routine never returns.
*/
void
Inonlocalgo(int class, lispval arg1, lispval arg2)
{
struct frame *uwpframe;
lispval handy;
/*
* scan for something to match 'class', return if nothing found, or
* if we must first handle an unwind protect.
*/
while ((uwpframe = Inlthrow(class, arg1, arg2)) != NULL) {
/*
* build error frame description to be use to continue this
* throw
*/
protect(lispretval = handy = newdot());
handy->d.car = Veruwpt;
handy = handy->d.cdr = newdot();
handy->d.car = inewint(class); /* remember type */
handy = handy->d.cdr = newdot();
handy->d.car = arg1;
handy = handy->d.cdr = newdot();
handy->d.car = arg2;
retval = C_THROW;
Iretfromfr(uwpframe);
/* NOT REACHED */
}
/*
* nothing to go to, signal the appropriate error
*/
switch (class) {
case C_GO:
errorh1(Vermisc, "No prog to go to with this tag ",
nil, FALSE, 0, arg1);
/* NOT REACHED */
case C_RET:
errorh(Vermisc, "No prog to return from", nil, FALSE, 0);
/* NOT REACHED */
case C_THROW:
errorh1(Vermisc, "No catch for this tag ", nil, FALSE, 0,
arg1);
/* NOT REACHED */
default:
error("Internal Inonlocalgoto error", FALSE);
/* NOT REACHED */
}
}
/*
* Inlthrow(class,arg1,arg2) :: look up the stack for a form to handle
* a value of 'class' being thrown. If found, do the throw. If an
* unwind-protect must be done, then return a pointer to that frame
* first. If there is nothing to catch this throw, we return 0.
*/
static struct frame *
Inlthrow(int class, lispval arg1, lispval arg2)
{
struct frame *uwpframe = (struct frame *) 0;
struct frame *curp;
int pass = 1;
restart:
for (curp = errp; curp != (struct frame *) 0; curp = curp->olderrp) {
switch (curp->class) {
case F_PROG:
if (class == C_RET || class == C_GO) {
if (pass == 2)
return (uwpframe);
else {
lispretval = arg1;
retval = class;
Iretfromfr(curp);
/* NOT REACHED */
}
}
break;
case F_CATCH:
if ((pass == 1) && (curp->larg1 == Veruwpt)) {
uwpframe = curp;
pass = 2;
goto restart;
} else if (class == C_THROW
&& matchtags(arg1, curp->larg1)) {
if (pass == 2)
return (uwpframe);
else {
lispretval = arg2; /* value thrown */
retval = class;
Iretfromfr(curp);
/* NOT REACHED */
}
}
break;
case F_RESET:
if (class == C_RESET) {
if (pass == 2)
return (uwpframe);
else {
retval = class;
Iretfromfr(curp);
/* NOT REACHED */
}
}
break;
}
}
return ((struct frame *) 0); /* nobody wants it */
}
#ifndef tahoe
void
Iretfromfr(struct frame *fram)
{
xpopnames(fram->svbnp);
qretfromfr(fram);
}
#endif
/*
* matchtags :: return TRUE if there is any atom in common between the two
* tags. Either tag may be an atom or an list of atoms.
*/
int
matchtags(lispval tag1, lispval tag2)
{
int repeat1 = FALSE;
int repeat2 = FALSE;
lispval temp1 = tag1;
lispval temp2 = tag2;
lispval t1, t2;
if (TYPE(tag1) == ATOM) {
t1 = tag1;
} else {
t1 = tag1->d.car;
repeat1 = TRUE;
}
if (TYPE(tag2) == ATOM) {
t2 = tag2;
} else {
t2 = tag2->d.car;
repeat2 = TRUE;
}
loop:
if (t1 == t2)
return (TRUE);
if (repeat2) {
if ((temp2 = temp2->d.cdr) != nil) {
t2 = temp2->d.car;
goto loop;
}
}
if (repeat1) {
if ((temp1 = temp1->d.cdr) != nil) {
t1 = temp1->d.car;
if (repeat2) {
temp2 = tag2;
t2 = temp2->d.car;
goto loop;
} else
t2 = tag2;
goto loop;
}
}
return (FALSE);
}
/*
* framedump :: debugging routine to print the contents of the error
* frame
*
*/
lispval
Lframedump(void)
{
struct frame *curp;
printf("Frame dump\n");
for (curp = errp; curp != (struct frame *) 0; curp = curp->olderrp) {
printf("at %p is ", curp);
switch (curp->class) {
case F_PROG:
printf(" prog\n");
break;
case F_CATCH:
printf(" catching ");
printr(curp->larg1, stdout);
putchar('\n');
break;
case F_RESET:
printf(" reset \n");
break;
case F_EVAL:
printf(" eval: ");
printr(curp->larg1, stdout);
putchar('\n');
break;
case F_FUNCALL:
printf(" funcall: ");
printr(curp->larg1, stdout);
putchar('\n');
break;
case F_TO_FORT:
printf(" calling fortran:\n");
break;
case F_TO_LISP:
printf(" fortran calling lisp:\n");
break;
default:
printf(" unknown: %jd \n", (intmax_t)curp->class);
}
fflush(stdout);
}
printf("End of stack\n");
return (nil);
}
| 23.944444 | 77 | 0.630681 |
47b0bd01faf22fb3c123e381b0444d589e5f0eb7 | 4,498 | h | C | include/utils.h | lorenzosquadrani/plasticity | 6ae648fe537ebbff8432ec04beb58e4acac5871e | [
"MIT"
] | 5 | 2020-11-06T16:30:24.000Z | 2022-02-09T21:20:41.000Z | include/utils.h | Nico-Curti/plasticity | 8159871d0aa31b096788e5aab785a1a969725ddf | [
"MIT"
] | null | null | null | include/utils.h | Nico-Curti/plasticity | 8159871d0aa31b096788e5aab785a1a969725ddf | [
"MIT"
] | 4 | 2020-11-25T14:22:48.000Z | 2021-08-07T10:45:22.000Z | #ifndef __utils_h__
#define __utils_h__
#include <cmath> // M_PI
#include <climits> // std :: numeric_limits
#include <random> // std :: mt19937
#include <iostream> // std :: cout
#include <iomanip> // std :: setprecision
#include <algorithm> // std :: sort (if necessary)
#include <memory> // std :: unique_ptr (if necessary)
#include <string> // MSVC compatibility
#include <iterator> // std :: begin
#include <fmath.h> // fast math function
#include <chrono> // timing function
#ifdef DEBUG
#include <cassert>
#endif
// Usefull macro
/// @cond DEF
#ifdef _MSC_VER
#ifndef __unused
#define __unused
#endif
#ifdef LINKING_DLL // necessary for export of some symbols
#define DLLSPEC __declspec(dllimport)
#else
#define DLLSPEC __declspec(dllexport)
#endif
#else // Not Visual Studio Compiler
#ifndef __unused
#define __unused __attribute__((__unused__))
#endif
#define DLLSPEC
#endif
/// @endcond
// Usefull variables
#define PBWIDTH 20 ///< Width of the progress bar
static const std :: string FILL_VALUE = "█"; ///< fill value for the progress bar
static const std :: string NULL_VALUE = " "; ///< empty value for the progress bar
#ifdef _WIN32
#define RESET_COUT '\r' ///< Return carriage value in Window OS
#else
#define RESET_COUT "\r\x1B[K" ///< Return carriage value in Unix OS
#endif
// Usefull common variables
namespace utils
{
// Timing functions
/**
* @brief Return the current time (STD format).
*
* @details There are many specialization of this function according to different parallel environments.
*
* @return The current time as chrono timer value.
*
*/
std :: chrono :: time_point < std :: chrono :: high_resolution_clock > what_time_is_it_now ();
/**
* @brief Get the elapsed time from the start.
*
* @details This function is related to the what_time_is_it_now function and it returns
* the elapsed time as seconds. For an accurate computation the time evaluation is performed
* using milliseconds as template.
*
* @param start_time Starting time.
*
* @return The elapsed time as double.
*
*/
double elapsed_time (const std :: chrono :: time_point < std :: chrono :: high_resolution_clock > & start_time);
/**
* @brief Print progress bar
*
* @details This function is used to progressively print a progress bar
* with timer.
*
* @param i Current iteration value.
* @param num_iter Maximum number of iterations, i.e the width of the progress bar.
* @param timer Start time (the timer is reset at the end of the function).
*
*/
void print_progress (const int & i, const int & num_iter, std :: chrono :: time_point < std :: chrono :: high_resolution_clock > & timer);
// OS functions
/**
* @brief Check if the given file exists.
*
* @details This function tries to open the given file (portable solution)
* and return true/false according to the outcome of this action.
*
* @param filename Filename or path to check.
*
* @return True if the file exists. False otherwise.
*
*/
bool file_exists (const std :: string & filename);
} // end namespace utils
/**
* @brief Overload operator * between strings and integers
*
* @details This overload allows to multiply and thus replicate a string
* for a fixed number of times.
*
* @tparam Char string data type
* @tparam Traits Second general-string template type
* @tparam Allocator Third general-string template type
* @param s Input string to multiply.
* @param n Number of times to repeat the string.
*
* @return A string repeated n times.
*
*/
template < typename Char, typename Traits, typename Allocator >
std :: basic_string < Char, Traits, Allocator > operator * (const std :: basic_string < Char, Traits, Allocator > & s, std :: size_t n);
/**
* @brief Overload operator * between integers and strings
*
* @details This overload allows to multiply and thus replicate a string
* for a fixed number of times.
*
* @tparam Char string data type
* @tparam Traits Second general-string template type
* @tparam Allocator Third general-string template type
* @param n Number of times to repeat the string.
* @param s Input string to multiply.
*
* @return A string repeated n times.
*
*/
template < typename Char, typename Traits, typename Allocator >
std :: basic_string < Char, Traits, Allocator > operator * (std :: size_t n, const std :: basic_string < Char, Traits, Allocator > & s);
#endif // __utils_h__
| 27.937888 | 140 | 0.694531 |
2a6bead3873c5b90167561bd5a20723c67ea1288 | 517 | h | C | Example/Pods/BasisModule/BaseRouterManager/UploadClient.h | huangzhentong/KTBlueSDK | c18768e211528e4d071ed826209ba848fa1056d8 | [
"MIT"
] | null | null | null | Example/Pods/BasisModule/BaseRouterManager/UploadClient.h | huangzhentong/KTBlueSDK | c18768e211528e4d071ed826209ba848fa1056d8 | [
"MIT"
] | null | null | null | Example/Pods/BasisModule/BaseRouterManager/UploadClient.h | huangzhentong/KTBlueSDK | c18768e211528e4d071ed826209ba848fa1056d8 | [
"MIT"
] | null | null | null | //
// UploadModel.h
// BasisModule
//
// Created by huang on 2016/11/10.
// Copyright © 2016年 huang. All rights reserved.
//
#import "BaseClient.h"
#import <UIKit/UIKit.h>
@interface UploadClient : BaseClient
@property(nonatomic,copy) NSArray *files; //上传数据
@property(nonatomic,copy) NSArray *fileNames; //文件保存名
@property(nonatomic,copy) NSArray *mimeTypes; //上传类型 (默认image/jpg)
@property(nonatomic,copy) NSArray *names; //服务器文件名 (默认为upload)
@end
| 30.411765 | 81 | 0.636364 |
f1c5e1c3cdb38e039e49cb0799090349437b0b37 | 542 | h | C | iOSProject/iOSProject/Classes/Preview3/Toos/MJDownload/MJDownloadConst.h | xiaoyeZhang/iOSProject | d5288a8ad64ddc98c1d820c16fb5f66213bbbe8b | [
"MIT"
] | 5,272 | 2018-01-10T02:38:52.000Z | 2022-03-30T07:46:00.000Z | iOSProject/iOSProject/Classes/Preview3/Toos/MJDownload/MJDownloadConst.h | oneGain/iOSProject | 07f2268ab27487e1e876b54a6191593ff5fdf0da | [
"MIT"
] | 54 | 2018-01-25T02:29:13.000Z | 2021-07-07T01:40:23.000Z | iOSProject/iOSProject/Classes/Preview3/Toos/MJDownload/MJDownloadConst.h | oneGain/iOSProject | 07f2268ab27487e1e876b54a6191593ff5fdf0da | [
"MIT"
] | 1,541 | 2018-01-10T02:54:09.000Z | 2022-03-29T09:30:44.000Z | //
// MJDownloadConst.h
// MJDownloadExample
//
// Created by MJ Lee on 15/7/16.
// Copyright (c) 2015年 小码哥. All rights reserved.
//
#import <Foundation/Foundation.h>
/******** 通知 Begin ********/
/** 下载进度发生改变的通知 */
extern NSString * const MJDownloadProgressDidChangeNotification;
/** 下载状态发生改变的通知 */
extern NSString * const MJDownloadStateDidChangeNotification;
/** 利用这个key从通知中取出对应的MJDownloadInfo对象 */
extern NSString * const MJDownloadInfoKey;
#define MJDownloadNoteCenter [NSNotificationCenter defaultCenter]
/******** 通知 End ********/ | 28.526316 | 65 | 0.719557 |
cc4d0387a1a3c90f3fde9be44a13b86c5e33065d | 1,083 | h | C | Plugins/org.mitk.gui.qt.application/src/QmitkDefaultDropTargetListener.h | zhaomengxiao/MITK | a09fd849a4328276806008bfa92487f83a9e2437 | [
"BSD-3-Clause"
] | 1 | 2022-03-03T12:03:32.000Z | 2022-03-03T12:03:32.000Z | Plugins/org.mitk.gui.qt.application/src/QmitkDefaultDropTargetListener.h | zhaomengxiao/MITK | a09fd849a4328276806008bfa92487f83a9e2437 | [
"BSD-3-Clause"
] | 1 | 2021-12-22T10:19:02.000Z | 2021-12-22T10:19:02.000Z | Plugins/org.mitk.gui.qt.application/src/QmitkDefaultDropTargetListener.h | zhaomengxiao/MITK_lancet | a09fd849a4328276806008bfa92487f83a9e2437 | [
"BSD-3-Clause"
] | 1 | 2020-11-27T09:41:18.000Z | 2020-11-27T09:41:18.000Z | /*============================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center (DKFZ)
All rights reserved.
Use of this source code is governed by a 3-clause BSD license that can be
found in the LICENSE file.
============================================================================*/
#ifndef QMITKDEFAULTDROPTARGETLISTENER_H
#define QMITKDEFAULTDROPTARGETLISTENER_H
#include <org_mitk_gui_qt_application_Export.h>
#include <berryIDropTargetListener.h>
#include <QScopedPointer>
class QmitkDefaultDropTargetListenerPrivate;
/**
* \ingroup org_mitk_gui_qt_application
*/
class MITK_QT_APP QmitkDefaultDropTargetListener : public berry::IDropTargetListener
{
public:
QmitkDefaultDropTargetListener();
~QmitkDefaultDropTargetListener() override;
Events::Types GetDropTargetEventTypes() const override;
void DropEvent(QDropEvent* event) override;
private:
const QScopedPointer<QmitkDefaultDropTargetListenerPrivate> d;
};
#endif // QMITKDEFAULTDROPTARGETLISTENER_H
| 24.066667 | 84 | 0.698061 |
9a32c85c79f5eedf3a7183313b77fe1cc82d894e | 2,600 | h | C | src/struct.h | ChetSimpson/KAOS.Assembler | 4f61e3f859b76990dd78b56a99fe472e56b5684a | [
"MIT"
] | 2 | 2018-11-23T19:45:22.000Z | 2020-01-28T11:06:32.000Z | src/struct.h | ChetSimpson/KAOS.Assembler | 4f61e3f859b76990dd78b56a99fe472e56b5684a | [
"MIT"
] | null | null | null | src/struct.h | ChetSimpson/KAOS.Assembler | 4f61e3f859b76990dd78b56a99fe472e56b5684a | [
"MIT"
] | 1 | 2020-09-19T19:10:31.000Z | 2020-09-19T19:10:31.000Z | /*****************************************************************************
struct.h - Declarations for the struct handler
Copyright (C) 1996, 1997, 2014, 2018, by Chet Simpson, Et al.
This file is distributed under the MIT License. See notice at the end
of this file.
*****************************************************************************/
#ifndef STRUCT_H
#define STRUCT_H
#include "config.h"
#include "input.h"
typedef struct _element Element;
typedef struct _struct Struct;
/* Element entry */
struct _element
{
char name[MAX_LABELSIZE];
int offset; /* Offset into the structure of the element */
int size; /* Size of a single element */
int count; /* Number of elements */
Struct *child; /* Child structures */
Element *next;
};
/* Structure entry */
struct _struct
{
char name[MAX_LABELSIZE];
int size;
Element *el_head; /* First element in the list */
Element *el_tail; /* Last element in the list */
Struct *next;
};
void StructCreate(EnvContext *ctx, const char *structName);
void StructAddElement(EnvContext *ctx, const char *elementName, const char *elementType);
Struct *StructLookup(const char *);
Element *StructGetElement(const Struct *, const char *);
void UnionCreate(EnvContext *ctx, const char *unionName);
void UnionEnd(EnvContext *ctx);
#endif /* STRUCT_H */
/*****************************************************************************
Copyright (C) 1996, 1997, 2014, 2018, by Chet Simpson
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.
*****************************************************************************/
| 32.911392 | 89 | 0.656923 |
a8b69829e33cfab1bc5b11f63bdf8380f1df3055 | 916 | h | C | Conductor/scene/RelativeTransformSystem.h | haferflocken/ConductorEngine | 4914e419e5a736275e96d76eaa19b7aa56d69345 | [
"Zlib",
"BSD-2-Clause"
] | null | null | null | Conductor/scene/RelativeTransformSystem.h | haferflocken/ConductorEngine | 4914e419e5a736275e96d76eaa19b7aa56d69345 | [
"Zlib",
"BSD-2-Clause"
] | null | null | null | Conductor/scene/RelativeTransformSystem.h | haferflocken/ConductorEngine | 4914e419e5a736275e96d76eaa19b7aa56d69345 | [
"Zlib",
"BSD-2-Clause"
] | null | null | null | #pragma once
#include <ecs/System.h>
#include <scene/SceneTransformComponent.h>
namespace Scene
{
/**
* The RelativeTransformSystem updates the scene transforms of entities in parent/child relationships.
* An entity's transform is relative to their parent's transform.
*/
class RelativeTransformSystem final : public ECS::SystemTempl<
Util::TypeList<ECS::Entity>,
Util::TypeList<SceneTransformComponent>>
{
public:
RelativeTransformSystem() = default;
virtual ~RelativeTransformSystem() {}
void Update(const Unit::Time::Millisecond delta,
const Collection::ArrayView<ECSGroupType>& ecsGroups,
Collection::Vector<std::function<void(ECS::EntityManager&)>>& deferredFunctions);
private:
void ProcessUpdateBuffer(ECS::EntityManager& entityManager);
struct UpdateEntry
{
const ECS::Entity* m_entity;
SceneTransformComponent* m_component;
};
Collection::Vector<UpdateEntry> m_updateBuffer;
};
}
| 25.444444 | 102 | 0.776201 |
00f1991f250eb1296140ccac3f608ff77d7d42bd | 1,965 | h | C | src/video_scaler.h | suratovvlad/hls_encoder | 57dcd7ff620b473f5c9c677e0afc0eb1be88f567 | [
"MIT"
] | 1 | 2021-09-26T04:02:56.000Z | 2021-09-26T04:02:56.000Z | src/video_scaler.h | suratovvlad/hls_encoder | 57dcd7ff620b473f5c9c677e0afc0eb1be88f567 | [
"MIT"
] | null | null | null | src/video_scaler.h | suratovvlad/hls_encoder | 57dcd7ff620b473f5c9c677e0afc0eb1be88f567 | [
"MIT"
] | 1 | 2021-09-16T20:37:12.000Z | 2021-09-16T20:37:12.000Z | //
// Created by degree on 17.09.2021.
//
#ifndef HLS_ENCODER_VIDEO_SCALER_H
#define HLS_ENCODER_VIDEO_SCALER_H
struct video_scaler
{
video_scaler( const scaling_options& _scaling_options )
: m_scaling_options( _scaling_options )
{
m_scaler = sws_getContext(
m_scaling_options.source_width,
m_scaling_options.source_height,
m_scaling_options.source_pixel_format,
m_scaling_options.target_width,
m_scaling_options.target_height,
m_scaling_options.target_pixel_format,
SWS_BICUBIC,
NULL,
NULL,
NULL
);
}
~video_scaler()
{
sws_freeContext(m_scaler);
}
SwsContext* get()
{
return m_scaler;
}
void scale( const std::unique_ptr< frame >& input_frame, const std::unique_ptr< frame >& scaled_frame ) const
{
scaled_frame->get()->format = m_scaling_options.target_pixel_format;
scaled_frame->get()->width = m_scaling_options.target_width;
scaled_frame->get()->height = m_scaling_options.target_height;
av_image_alloc(
scaled_frame->get()->data,
scaled_frame->get()->linesize,
scaled_frame->get()->width,
scaled_frame->get()->height,
m_scaling_options.target_pixel_format,
16);
sws_scale( m_scaler,
(const uint8_t * const*) input_frame->get()->data, input_frame->get()->linesize,
0, m_scaling_options.source_height,
scaled_frame->get()->data, scaled_frame->get()->linesize);
scaled_frame->get()->quality = input_frame->get()->quality;
scaled_frame->get()->pts = input_frame->get()->pts;
}
private:
scaling_options m_scaling_options;
SwsContext* m_scaler;
};
#endif //HLS_ENCODER_VIDEO_SCALER_H
| 29.328358 | 113 | 0.596947 |
2f56b940967507773877344424ee2bb1d5439266 | 655 | c | C | Functions/passing_for_values.c | Daniel-0liver/Advanced-C-curse | b36be78a77286cc47111b3bdb3f1e90127aa5064 | [
"MIT"
] | null | null | null | Functions/passing_for_values.c | Daniel-0liver/Advanced-C-curse | b36be78a77286cc47111b3bdb3f1e90127aa5064 | [
"MIT"
] | null | null | null | Functions/passing_for_values.c | Daniel-0liver/Advanced-C-curse | b36be78a77286cc47111b3bdb3f1e90127aa5064 | [
"MIT"
] | null | null | null | #include <stdio.h>
int sum(int x, int y) {
int z = x + y;
puts("===> FUNCTION");
printf("&x = %p, x = %d\n", &x, x);
printf("&y = %p, y = %d\n", &y, y);
printf("&z = %p, z = %d\n\n", &z, z);
return z;
}
int main() {
int a = 10;
int b = 20;
int c;
puts("===> BEFORE CALL THE FUNCTION");
printf("&a = %p, a = %d\n", &a, a);
printf("&b = %p, b = %d\n", &b, b);
printf("&c = %p, c = %d\n\n", &c, c);
c = sum(a, b);
puts("===> AFTER CALL THE FUNCTION");
printf("&a = %p, a = %d\n", &a, a);
printf("&b = %p, b = %d\n", &b, b);
printf("&c = %p, c = %d\n\n", &c, c);
return 0;
} | 20.46875 | 42 | 0.392366 |
7a764e08a9f9b472cafbb330a5eaee0cb2aa5a43 | 1,451 | h | C | files/soko1/qutim_0.1.1/protocol/oscar/icq/tlv.h | truebsdorg/truebsdorg.github.io | 8663d8f6fae3b1bb1e2fb29614677f2863521951 | [
"BSD-4-Clause-UC"
] | null | null | null | files/soko1/qutim_0.1.1/protocol/oscar/icq/tlv.h | truebsdorg/truebsdorg.github.io | 8663d8f6fae3b1bb1e2fb29614677f2863521951 | [
"BSD-4-Clause-UC"
] | null | null | null | files/soko1/qutim_0.1.1/protocol/oscar/icq/tlv.h | truebsdorg/truebsdorg.github.io | 8663d8f6fae3b1bb1e2fb29614677f2863521951 | [
"BSD-4-Clause-UC"
] | null | null | null | /*
tlv
Copyright (c) 2008 by Rustam Chakin <qutim.develop@gmail.com>
***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************
*/
#ifndef TLV_H_
#define TLV_H_
#include <QString>
class QTcpSocket;
class icqBuffer;
class tlv
{
public:
tlv();
~tlv();
void setLe(bool f){ LE = f;}
void setType(quint16 t) { type = t; }
void setData(const QString &);
void setData(const QByteArray &);
void setData(const quint8 &);
void setData(const quint16 &);
void setData(const quint32 &);
quint16 getLength() const;
QByteArray getData() const;
inline QByteArray getTlvData() const { return data; }
inline quint16 getTlvLength() const { return length; }
inline quint16 getTlvType() const { return type; }
void readData(icqBuffer *);
private:
quint16 byteArrayToInt16(const QByteArray &) const;
quint16 type;
quint16 length;
QByteArray data;
bool LE;
};
#endif /*TLV_H_*/
| 28.45098 | 76 | 0.536182 |
a3f32de62b33f3a2a556c47321e82f04253ca1de | 63 | h | C | qtbase/include/QtSql/5.6.3/QtSql/private/qsql_ibase_p.h | wgnet/wds_qt | 8db722fd367d2d0744decf99ac7bafaba8b8a3d3 | [
"Apache-2.0"
] | 1 | 2020-04-30T15:47:35.000Z | 2020-04-30T15:47:35.000Z | qtbase/include/QtSql/5.6.3/QtSql/private/qsql_ibase_p.h | wgnet/wds_qt | 8db722fd367d2d0744decf99ac7bafaba8b8a3d3 | [
"Apache-2.0"
] | null | null | null | qtbase/include/QtSql/5.6.3/QtSql/private/qsql_ibase_p.h | wgnet/wds_qt | 8db722fd367d2d0744decf99ac7bafaba8b8a3d3 | [
"Apache-2.0"
] | null | null | null | #include "../../../../../src/sql/drivers/ibase/qsql_ibase_p.h"
| 31.5 | 62 | 0.603175 |
94686d73d0d44755df007496fc09bc7285e31e48 | 5,768 | h | C | c2019/subsystems/superstructure/superstructure.h | aakamishra/robot-code-public | 439864b4701fb2068a5c5932356cbc5aacc61d1d | [
"MIT"
] | 61 | 2017-01-22T04:38:32.000Z | 2022-03-07T00:04:37.000Z | c2019/subsystems/superstructure/superstructure.h | aakamishra/robot-code-public | 439864b4701fb2068a5c5932356cbc5aacc61d1d | [
"MIT"
] | 3 | 2018-06-28T05:34:57.000Z | 2019-01-16T15:46:22.000Z | c2019/subsystems/superstructure/superstructure.h | aakamishra/robot-code-public | 439864b4701fb2068a5c5932356cbc5aacc61d1d | [
"MIT"
] | 17 | 2017-05-12T15:32:03.000Z | 2021-12-09T12:49:38.000Z | #ifndef C2019_SUBSYSTEMS_SUPERSTRUCTURE_SUPERSTRUCTURE_H_
#define C2019_SUBSYSTEMS_SUPERSTRUCTURE_SUPERSTRUCTURE_H_
#include "c2019/subsystems/superstructure/cargo_intake/cargo_intake.h"
#include "c2019/subsystems/superstructure/cargo_intake/queue_types.h"
#include "c2019/subsystems/superstructure/elevator/elevator.h"
#include "c2019/subsystems/superstructure/elevator/queue_types.h"
#include "c2019/subsystems/superstructure/ground_hatch_intake/ground_hatch_intake.h"
#include "c2019/subsystems/superstructure/ground_hatch_intake/queue_types.h"
#include "c2019/subsystems/superstructure/hatch_intake/hatch_intake.h"
#include "c2019/subsystems/superstructure/hatch_intake/queue_types.h"
#include "c2019/subsystems/superstructure/queue_types.h"
#include "c2019/subsystems/superstructure/winch/queue_types.h"
#include "c2019/subsystems/superstructure/winch/winch.h"
#include "c2019/subsystems/superstructure/wrist/queue_types.h"
#include "c2019/subsystems/superstructure/wrist/wrist.h"
#include "muan/queues/queue_manager.h"
#include "muan/wpilib/queue_types.h"
namespace c2019 {
namespace superstructure {
// elevator constants
constexpr double kHatchShipForwardsHeight = 0.1;
constexpr double kHatchShipBackwardsHeight = 0.13;
constexpr double kHatchRocketFirstHeight = 0.1;
constexpr double kHatchRocketBackwardsHeight = 0.13;
constexpr double kHatchRocketSecondHeight = 0.987;
constexpr double kHatchRocketThirdHeight = 1.74;
constexpr double kHatchLoadingStationHeight = 0.089;
constexpr double kCargoShipForwardsHeight = 1.103;
constexpr double kCargoShipBackwardsHeight = 0.13;
constexpr double kCargoRocketFirstHeight = 0.093;
constexpr double kCargoRocketBackwardsHeight = 0.13;
constexpr double kCargoRocketSecondHeight = 0.928;
constexpr double kCargoRocketThirdHeight = 1.74;
constexpr double kGroundHeight = 0.;
constexpr double kHandoffHeight = 0.257;
constexpr double kSpitHeight = 0.;
constexpr double kStowHeight = 0.;
constexpr double kKissHeight = 1.39;
constexpr double kClimbHeight = 0.05;
constexpr double kCrawlerHeight = 1.6;
constexpr double kBustDown = 0.312;
constexpr double kElevatorSafeHeight = 0.71;
constexpr double kElevatorPassThroughHeight = 0.05;
constexpr double kElevatorHandoffTolerance = 2e-3;
constexpr double kElevatorWristHorizHeight = 0.05;
constexpr double kElevatorBoardHeight = 1.42;
constexpr double kElevatorRezeroCurrentThreshold = 3; // tune
// wrist constants
constexpr double kHatchForwardsAngle = 0.0;
constexpr double kHatchBackwardsAngle = 2.98;
constexpr double kCargoRocketFirstAngle = .87;
constexpr double kCargoRocketSecondAngle = .87;
constexpr double kCargoRocketThirdAngle = .87;
constexpr double kCargoRocketBackwardsAngle = M_PI;
constexpr double kCargoShipForwardsAngle = 0.0;
constexpr double kCargoShipBackwardsAngle = 2.98;
constexpr double kGroundAngle = 0.0;
constexpr double kHandoffAngle = 2.98;
constexpr double kStowAngle = 1.2;
constexpr double kBustDownAngle = 0.3;
constexpr double kWristSafeForwardsAngle = 1.3;
constexpr double kWristSafeBackwardsAngle = 2.65;
constexpr double kWristHandoffTolerance = 3. * (M_PI / 180.);
constexpr double kWristRezeroCurrentThreshold = 10; // tune
class Superstructure {
public:
Superstructure();
void Update();
private:
void SetGoal(const SuperstructureGoalProto& goal);
void GoToState(SuperstructureState state,
IntakeGoal intake = IntakeGoal::INTAKE_NONE);
void RunStateMachine();
void BoundGoal(double* elevator_goal, double* wrist_goal);
void Rezero();
void Autocrawl();
elevator::ElevatorGoalProto PopulateElevatorGoal();
wrist::WristGoalProto PopulateWristGoal();
ground_hatch_intake::GroundHatchIntakeGoalProto
PopulateGroundHatchIntakeGoal();
hatch_intake::HatchIntakeGoalProto PopulateHatchIntakeGoal();
cargo_intake::CargoIntakeGoalProto PopulateCargoIntakeGoal();
winch::WinchGoalProto PopulateWinchGoal();
c2019::cargo_intake::CargoIntake cargo_intake_;
c2019::elevator::Elevator elevator_;
c2019::ground_hatch_intake::GroundHatchIntake ground_hatch_intake_;
c2019::hatch_intake::HatchIntake hatch_intake_;
c2019::wrist::Wrist wrist_;
c2019::winch::Winch winch_;
cargo_intake::CargoIntakeStatusProto cargo_intake_status_;
elevator::ElevatorStatusProto elevator_status_;
ground_hatch_intake::GroundHatchIntakeStatusProto ground_hatch_intake_status_;
hatch_intake::HatchIntakeStatusProto hatch_intake_status_;
wrist::WristStatusProto wrist_status_;
winch::WinchStatusProto winch_status_;
SuperstructureStatusProto status_;
SuperstructureOutputProto output_;
SuperstructureGoalQueue::QueueReader goal_reader_;
SuperstructureInputQueue::QueueReader input_reader_;
SuperstructureStatusQueue* status_queue_;
SuperstructureOutputQueue* output_queue_;
muan::wpilib::DriverStationQueue::QueueReader ds_status_reader_;
double elevator_height_;
double wrist_angle_;
bool crawling_ = false;
bool high_gear_ = true;
bool crawler_down_ = false;
bool brake_ = false;
bool request_climb_ = false;
bool request_crawlers_ = false;
bool winch_right_ = false;
bool winch_left_ = false;
bool should_climb_ = false;
bool buddy_ = false;
int counter_ = 0;
bool force_backplate_ = false;
bool cargo_out_ = false;
bool climbing_ = false;
bool request_crawl_ = false;
bool pins_ = false;
bool rezero_mode_ = false;
bool elevator_rezeroed_;
bool wrist_rezeroed_;
double elevator_offset_ = 0.;
double wrist_offset_ = 0.;
double elevator_current_;
double wrist_current_;
SuperstructureState state_ = SuperstructureState::CALIBRATING;
IntakeGoal intake_goal_ = IntakeGoal::INTAKE_NONE;
};
} // namespace superstructure
} // namespace c2019
#endif // C2019_SUBSYSTEMS_SUPERSTRUCTURE_SUPERSTRUCTURE_H_
| 36.738854 | 84 | 0.812587 |
9479109e48e8e7485c7a049521685489ed390bb3 | 1,890 | c | C | gemcache.c | tleino/gemcache | 02dd5a683c2c035357ad2beb6106da71de439c52 | [
"0BSD"
] | null | null | null | gemcache.c | tleino/gemcache | 02dd5a683c2c035357ad2beb6106da71de439c52 | [
"0BSD"
] | null | null | null | gemcache.c | tleino/gemcache | 02dd5a683c2c035357ad2beb6106da71de439c52 | [
"0BSD"
] | null | null | null | #include "fetch.h"
#include "tcpbind.h"
#include "serve.h"
#include <stdlib.h>
#include <openssl/sha.h>
#include <string.h>
#include <stdio.h>
#include <limits.h>
#include <err.h>
#include <sys/stat.h>
#include <errno.h>
#include <libgen.h>
#include <sys/wait.h>
#include <unistd.h>
#include <syslog.h>
#include <sys/socket.h>
static char *
hash_url(const char *url)
{
static char hstr[128];
unsigned char hash[SHA_DIGEST_LENGTH + 1];
char *p;
int i;
SHA1((unsigned const char *) url, strlen(url), hash);
hash[SHA_DIGEST_LENGTH] = '\0';
p = hstr;
for (i = 0; i < SHA_DIGEST_LENGTH; i++) {
sprintf(p, "%02x", hash[i]);
p += 2;
}
*p = '\0';
return hstr;
}
char *
find_cache_file(const char *url)
{
char *home;
static char file[PATH_MAX];
char *path, *dn;
struct stat sb;
char *hash;
hash = hash_url(url);
home = getenv("HOME");
if (home == NULL)
err(1, "getenv HOME");
if (snprintf(file, sizeof(file), "%s/.gemcache/%s",
home, hash) >= sizeof(file))
errx(1, "bogus HOME variable?");
path = strdup(file);
if (path == NULL)
err(1, "strdup %s", file);
dn = dirname(path);
if (dn == NULL)
err(1, "dirname %s", file);
if (stat(dn, &sb) != 0) {
if (errno == ENOENT) {
warnx("create %s", dn);
if (mkdir(dn, 0700) != 0)
warnx("mkdir %s", dn);
} else
err(1, "stat %s", dn);
}
free(path);
return file;
}
void session(int);
int
main(int argc, char *argv[])
{
int sfd;
openlog(argv[0], 0, LOG_DAEMON);
sfd = tcpbind("0.0.0.0", 1965);
for (;;) {
int fd, status;
pid_t pid;
fd = serve(sfd);
if (fd < 0)
continue;
if ((pid = fork()) == 0) {
#if 0
alarm(10); /* session expire time */
#endif
#ifdef __OpenBSD__
setproctitle("session");
#endif
session(fd);
shutdown(fd, SHUT_RDWR);
close(fd);
_exit(0);
}
close(fd);
if (pid != -1)
wait(&status);
}
return 0;
}
| 16.578947 | 54 | 0.586243 |
ff2a80ba38b6b6107d3854048454c8f7296e91c5 | 1,366 | c | C | src/memory.c | CECapps/clox | fabd0037636242fdbe943763038220a846e08500 | [
"MIT"
] | null | null | null | src/memory.c | CECapps/clox | fabd0037636242fdbe943763038220a846e08500 | [
"MIT"
] | null | null | null | src/memory.c | CECapps/clox | fabd0037636242fdbe943763038220a846e08500 | [
"MIT"
] | null | null | null | #include <stdlib.h>
#include "common.h"
#include "memory.h"
#include "vm.h"
void* reallocate(void* previous, size_t oldSize, size_t newSize) {
if (newSize == 0) {
free(previous);
return NULL;
}
return realloc(previous, newSize);
}
static void freeObject(Obj* object) {
switch (object->type) {
case OBJ_FUNCTION: {
ObjFunction* function = (ObjFunction*)object;
freeChunk(&function->chunk);
FREE(ObjFunction, object);
break;
}
case OBJ_NATIVE:
FREE(ObjNative, object);
break;
case OBJ_STRING: {
ObjString* string = (ObjString*)object;
FREE_ARRAY(char, string->chars, string->length + 1);
FREE(ObjString, object);
break;
}
case OBJ_USERARRAY: {
ObjUserArray* ua = (ObjUserArray*)object;
freeValueArray(&ua->inner);
FREE(ObjUserArray, object);
break;
}
case OBJ_USERHASH: {
ObjUserHash* ht = (ObjUserHash*)object;
freeTable(&ht->table);
FREE(ObjUserHash, object);
break;
}
case OBJ_FILEHANDLE: {
FREE(ObjFileHandle, object);
break;
}
case OBJ_FERROR: {
FREE(ObjFunctionError, object);
break;
}
}
}
void freeObjects() {
Obj* object = vm.objects;
while (object != NULL) {
Obj* next = object->next;
freeObject(object);
object = next;
}
}
| 18.459459 | 66 | 0.600293 |
ff2f6c34c6e2e41761968f537eb4de81b90025e6 | 495 | h | C | OSArcGISRuntimeAdapter/OSArcGISRuntimeAdapter.h | OrdnanceSurvey/os-arcgis-runtime-adapter-ios | d51875800099a7c33c36ace1e11436fe39256838 | [
"Apache-2.0"
] | null | null | null | OSArcGISRuntimeAdapter/OSArcGISRuntimeAdapter.h | OrdnanceSurvey/os-arcgis-runtime-adapter-ios | d51875800099a7c33c36ace1e11436fe39256838 | [
"Apache-2.0"
] | null | null | null | OSArcGISRuntimeAdapter/OSArcGISRuntimeAdapter.h | OrdnanceSurvey/os-arcgis-runtime-adapter-ios | d51875800099a7c33c36ace1e11436fe39256838 | [
"Apache-2.0"
] | null | null | null | //
// OSArcGISRuntimeAdapter.h
// OSArcGISRuntimeAdapter
//
// Created by David Haynes on 03/02/2016.
// Copyright © 2016 Ordnance Survey. All rights reserved.
//
#import <UIKit/UIKit.h>
//! Project version number for OSArcGISRuntimeAdapter.
FOUNDATION_EXPORT double OSArcGISRuntimeAdapterVersionNumber;
//! Project version string for OSArcGISRuntimeAdapter.
FOUNDATION_EXPORT const unsigned char OSArcGISRuntimeAdapterVersionString[];
#import <OSArcGISRuntimeAdapter/OSWMTSBaseLayer.h>
| 27.5 | 76 | 0.80202 |
9e0d7132f3585ae357c7c6a3fba284514bf8ca41 | 1,788 | h | C | OutPutHeaders/HardWareItem.h | cocos543/WeChatTimeLineRobot | 1e93480e502e36ca9a21a506f481aa1fcb70ac4b | [
"MIT"
] | 106 | 2016-04-09T01:16:14.000Z | 2021-06-04T00:20:24.000Z | OutPutHeaders/HardWareItem.h | cocos543/WeChatTimeLineRobot | 1e93480e502e36ca9a21a506f481aa1fcb70ac4b | [
"MIT"
] | 2 | 2017-06-13T09:41:29.000Z | 2018-03-26T03:32:07.000Z | OutPutHeaders/HardWareItem.h | cocos543/WeChatTimeLineRobot | 1e93480e502e36ca9a21a506f481aa1fcb70ac4b | [
"MIT"
] | 58 | 2016-04-28T09:52:08.000Z | 2021-12-25T06:42:14.000Z | /**
* This header is generated by class-dump-z 0.2a.
* class-dump-z is Copyright (C) 2009 by KennyTM~, licensed under GPLv3.
*
* Source: (null)
*/
#import "WeChat-Structs.h"
#import "MMObject.h"
#import "NSCopying.h"
@class NSString;
@interface HardWareItem : MMObject <NSCopying> {
unsigned long uiHardWareShowType;
NSString* nsRankID;
NSString* nsRankTitle;
NSString* nsRankDisplay;
NSString* nsScoreTitle;
NSString* nsScoreDisplay;
NSString* nsTipDisplay;
NSString* nsColor;
NSString* nsHighLightColor;
NSString* nsLineColor;
NSString* nsHighLightLineColor;
NSString* nsFontColor;
NSString* nsChampionUsername;
NSString* nsDisplayUserName;
NSString* nsThumbUrl;
NSString* nsNotifyTitle;
unsigned long uiTimeStamp;
}
@property(assign, nonatomic) unsigned long uiTimeStamp;
@property(retain, nonatomic) NSString* nsNotifyTitle;
@property(retain, nonatomic) NSString* nsThumbUrl;
@property(retain, nonatomic) NSString* nsDisplayUserName;
@property(retain, nonatomic) NSString* nsChampionUsername;
@property(retain, nonatomic) NSString* nsFontColor;
@property(retain, nonatomic) NSString* nsHighLightLineColor;
@property(retain, nonatomic) NSString* nsLineColor;
@property(retain, nonatomic) NSString* nsHighLightColor;
@property(retain, nonatomic) NSString* nsColor;
@property(retain, nonatomic) NSString* nsTipDisplay;
@property(retain, nonatomic) NSString* nsScoreDisplay;
@property(retain, nonatomic) NSString* nsScoreTitle;
@property(retain, nonatomic) NSString* nsRankDisplay;
@property(retain, nonatomic) NSString* nsRankTitle;
@property(retain, nonatomic) NSString* nsRankID;
@property(assign, nonatomic) unsigned long uiHardWareShowType;
-(void).cxx_destruct;
-(BOOL)IsExpired;
-(BOOL)fromXML:(XmlReaderNode_t*)xml;
-(id)copyWithZone:(NSZone*)zone;
@end
| 31.928571 | 72 | 0.788031 |
7f248d043075259af6252c19cd48d161909f1990 | 1,078 | h | C | Pods/Headers/Public/FeedMedia/FMElapsedTimeLabel.h | feedfm/Tempo | 76294315560680f99ca551329f4fb08f0c1cd53a | [
"MIT"
] | null | null | null | Pods/Headers/Public/FeedMedia/FMElapsedTimeLabel.h | feedfm/Tempo | 76294315560680f99ca551329f4fb08f0c1cd53a | [
"MIT"
] | null | null | null | Pods/Headers/Public/FeedMedia/FMElapsedTimeLabel.h | feedfm/Tempo | 76294315560680f99ca551329f4fb08f0c1cd53a | [
"MIT"
] | null | null | null | //
// FMElapsedTimeLabel.h
// iOS-UI-SDK
//
// This class extends UILabel to automatically set its
// text to be the elapsed time of the currently playing
// song (and it is updated every .5 second), or the
// value of the textForNoTime property when
// no song is playing. The setText: call is stubbed out
// so that the text cannot be changed by the client.
//
// Created by Eric Lambrecht on 3/10/15.
// Copyright (c) 2015 Feed Media. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "FeedMediaCoreProxy.h"
/**
Label that updates its `text` property to reflect the
amount of time that has elapsed since the start of the current song or,
when no song is being played, a custom string.
The label displays the elapsed time in the format '0:00'.
When no song is playing, the label will set `text` to the value
of `textFoNoTime`.
*/
//NOT_IB_DESIGNABLE
@interface FMElapsedTimeLabel : UILabel
/**
The string that should be displayed when no song is being played.
*/
@property (strong, nonatomic) IBInspectable NSString *textForNoTime;
@end
| 25.666667 | 72 | 0.72449 |
36c352579d7b7acf6a739c3a7b6d01455b3b778e | 2,711 | c | C | CAN_motor_controller/Core/Src/uart.c | wjklimek1/CAN_motor_controller | 8830bf3f4ef2007305bab18ac33dedc332fa4741 | [
"MIT"
] | null | null | null | CAN_motor_controller/Core/Src/uart.c | wjklimek1/CAN_motor_controller | 8830bf3f4ef2007305bab18ac33dedc332fa4741 | [
"MIT"
] | null | null | null | CAN_motor_controller/Core/Src/uart.c | wjklimek1/CAN_motor_controller | 8830bf3f4ef2007305bab18ac33dedc332fa4741 | [
"MIT"
] | null | null | null | #include <stdint.h>
#include "stm32f103xb.h"
#include "uart.h"
//====================== initialization ========================//
/**
* @brief Initializes UART3 peripherial with PB10 as TX and PB11 as RX.
*
* Available baudrates are: 250kb/s, 500kb/s 1Mb/s
*
* @param[in] sys_core_clk value of system clock in MCU
* @param[in] baudrate baudrate of UART transmission
*/
void UART3_init(uint32_t sys_core_clk, uint32_t baudrate)
{
//configure UART3 GPIOs: PB10 - TX, PB11 - RX
RCC->APB2ENR |= RCC_APB2ENR_IOPBEN; //enable GPIOB clock
RCC->APB2ENR |= RCC_APB2ENR_AFIOEN; //enable alternate function clock
GPIOB->CRH &= ~(GPIO_CRH_MODE10_Msk | GPIO_CRH_CNF10_Msk | GPIO_CRH_MODE11_Msk | GPIO_CRH_CNF11_Msk); //reset MODE and CNF bits
GPIOB->CRH |= (0b11 << GPIO_CRH_MODE10_Pos | 0b10 << GPIO_CRH_CNF10_Pos); //set PB10 TX pin as AF push-pull output
GPIOB->CRH |= (0b00 << GPIO_CRH_MODE11_Pos | 0b01 << GPIO_CRH_CNF11_Pos); //set PB11 RX pin as floating input
//configure USART3 peripherial
RCC->APB1ENR |= RCC_APB1ENR_USART3EN; //enable peripherial clock
USART3->CR1 |= USART_CR1_UE; //enable peripherial
//configure baudrate
uint32_t uartdiv = (sys_core_clk / 2) / baudrate;
USART3->BRR = (((uartdiv / 16) << USART_BRR_DIV_Mantissa_Pos) | ((uartdiv % 16) << USART_BRR_DIV_Fraction_Pos)); //set baudrate configuration
USART3->CR1 |= USART_CR1_TE; //enable transmission - send idle frame at the beggining
}
//====================== send byte ========================//
/**
* @brief Transmits single byte through UART3.
*
* @param[in] tx_byte single byte to transmit through UART3
*/
void UART3_send_byte(uint8_t tx_byte)
{
while(!(USART3->SR & USART_SR_TXE)); //wait until last transmission is completed
USART3->DR = tx_byte; //write data to transmission register
}
//====================== send string ========================//
/**
* @brief Transmits string through UART3.
*
* @param[in] string pointer to char array terminated with 0.
*/
void UART3_print_string(char *string)
{
int i = 0;
while(*(string + i) != 0)
{
UART3_send_byte(*(string + i));
i++;
}
}
//====================== _putchar ========================//
/**
* @brief _putchar implementation for printf() support.
*
* @param[in] character single byte to transmit through UART3
*/
void _putchar(char character)
{
while(!(USART3->SR & USART_SR_TXE)); //wait until last transmission is completed
USART3->DR = character; //write data to transmission register
}
| 34.75641 | 172 | 0.605312 |
36d07beb23d4c00c9261fae0d361c5f157cbc679 | 52,633 | c | C | dlls/d3d11/texture.c | milo1023/winecx | 5c3fef5b8175fffa37962fb4df2a282a21201db0 | [
"MIT"
] | 3 | 2020-05-05T19:39:08.000Z | 2020-07-07T17:02:58.000Z | dlls/d3d11/texture.c | milo1023/winecx | 5c3fef5b8175fffa37962fb4df2a282a21201db0 | [
"MIT"
] | 2 | 2021-05-21T06:25:34.000Z | 2021-05-22T11:27:24.000Z | dlls/d3d11/texture.c | milo1023/winecx | 5c3fef5b8175fffa37962fb4df2a282a21201db0 | [
"MIT"
] | 2 | 2020-03-17T01:59:12.000Z | 2021-08-17T00:16:30.000Z | /*
* Copyright 2009 Henri Verbeet for CodeWeavers
* Copyright 2015 Józef Kucia for CodeWeavers
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
*
*/
#include "d3d11_private.h"
WINE_DEFAULT_DEBUG_CHANNEL(d3d11);
/* ID3D11Texture1D methods */
static inline struct d3d_texture1d *impl_from_ID3D11Texture1D(ID3D11Texture1D *iface)
{
return CONTAINING_RECORD(iface, struct d3d_texture1d, ID3D11Texture1D_iface);
}
static HRESULT STDMETHODCALLTYPE d3d11_texture1d_QueryInterface(ID3D11Texture1D *iface, REFIID iid, void **out)
{
struct d3d_texture1d *texture = impl_from_ID3D11Texture1D(iface);
TRACE("iface %p, iid %s, out %p.\n", iface, debugstr_guid(iid), out);
if (IsEqualGUID(iid, &IID_ID3D11Texture1D)
|| IsEqualGUID(iid, &IID_ID3D11Resource)
|| IsEqualGUID(iid, &IID_ID3D11DeviceChild)
|| IsEqualGUID(iid, &IID_IUnknown))
{
*out = iface;
IUnknown_AddRef(iface);
return S_OK;
}
if (IsEqualGUID(iid, &IID_ID3D10Texture1D)
|| IsEqualGUID(iid, &IID_ID3D10Resource)
|| IsEqualGUID(iid, &IID_ID3D10DeviceChild))
{
*out = &texture->ID3D10Texture1D_iface;
IUnknown_AddRef((IUnknown *)*out);
return S_OK;
}
if (texture->dxgi_surface)
{
TRACE("Forwarding to dxgi surface.\n");
return IUnknown_QueryInterface(texture->dxgi_surface, iid, out);
}
WARN("%s not implemented, returning E_NOINTERFACE.\n", debugstr_guid(iid));
*out = NULL;
return E_NOINTERFACE;
}
static ULONG STDMETHODCALLTYPE d3d11_texture1d_AddRef(ID3D11Texture1D *iface)
{
struct d3d_texture1d *texture = impl_from_ID3D11Texture1D(iface);
ULONG refcount = InterlockedIncrement(&texture->refcount);
TRACE("%p increasing refcount to %u.\n", texture, refcount);
if (refcount == 1)
{
ID3D11Device2_AddRef(texture->device);
wined3d_mutex_lock();
wined3d_texture_incref(texture->wined3d_texture);
wined3d_mutex_unlock();
}
return refcount;
}
static ULONG STDMETHODCALLTYPE d3d11_texture1d_Release(ID3D11Texture1D *iface)
{
struct d3d_texture1d *texture = impl_from_ID3D11Texture1D(iface);
ULONG refcount = InterlockedDecrement(&texture->refcount);
TRACE("%p decreasing refcount to %u.\n", texture, refcount);
if (!refcount)
{
ID3D11Device2 *device = texture->device;
wined3d_mutex_lock();
wined3d_texture_decref(texture->wined3d_texture);
wined3d_mutex_unlock();
/* Release the device last, it may cause the wined3d device to be
* destroyed. */
ID3D11Device2_Release(device);
}
return refcount;
}
static void STDMETHODCALLTYPE d3d11_texture1d_GetDevice(ID3D11Texture1D *iface, ID3D11Device **device)
{
struct d3d_texture1d *texture = impl_from_ID3D11Texture1D(iface);
TRACE("iface %p, device %p.\n", iface, device);
*device = (ID3D11Device *)texture->device;
ID3D11Device_AddRef(*device);
}
static HRESULT STDMETHODCALLTYPE d3d11_texture1d_GetPrivateData(ID3D11Texture1D *iface,
REFGUID guid, UINT *data_size, void *data)
{
struct d3d_texture1d *texture = impl_from_ID3D11Texture1D(iface);
IDXGISurface *dxgi_surface;
HRESULT hr;
TRACE("iface %p, guid %s, data_size %p, data %p.\n", iface, debugstr_guid(guid), data_size, data);
if (texture->dxgi_surface
&& SUCCEEDED(IUnknown_QueryInterface(texture->dxgi_surface, &IID_IDXGISurface, (void **)&dxgi_surface)))
{
hr = IDXGISurface_GetPrivateData(dxgi_surface, guid, data_size, data);
IDXGISurface_Release(dxgi_surface);
return hr;
}
return d3d_get_private_data(&texture->private_store, guid, data_size, data);
}
static HRESULT STDMETHODCALLTYPE d3d11_texture1d_SetPrivateData(ID3D11Texture1D *iface,
REFGUID guid, UINT data_size, const void *data)
{
struct d3d_texture1d *texture = impl_from_ID3D11Texture1D(iface);
IDXGISurface *dxgi_surface;
HRESULT hr;
TRACE("iface %p, guid %s, data_size %u, data %p.\n", iface, debugstr_guid(guid), data_size, data);
if (texture->dxgi_surface
&& SUCCEEDED(IUnknown_QueryInterface(texture->dxgi_surface, &IID_IDXGISurface, (void **)&dxgi_surface)))
{
hr = IDXGISurface_SetPrivateData(dxgi_surface, guid, data_size, data);
IDXGISurface_Release(dxgi_surface);
return hr;
}
return d3d_set_private_data(&texture->private_store, guid, data_size, data);
}
static HRESULT STDMETHODCALLTYPE d3d11_texture1d_SetPrivateDataInterface(ID3D11Texture1D *iface,
REFGUID guid, const IUnknown *data)
{
struct d3d_texture1d *texture = impl_from_ID3D11Texture1D(iface);
IDXGISurface *dxgi_surface;
HRESULT hr;
TRACE("iface %p, guid %s, data %p.\n", iface, debugstr_guid(guid), data);
if (texture->dxgi_surface
&& SUCCEEDED(IUnknown_QueryInterface(texture->dxgi_surface, &IID_IDXGISurface, (void **)&dxgi_surface)))
{
hr = IDXGISurface_SetPrivateDataInterface(dxgi_surface, guid, data);
IDXGISurface_Release(dxgi_surface);
return hr;
}
return d3d_set_private_data_interface(&texture->private_store, guid, data);
}
static void STDMETHODCALLTYPE d3d11_texture1d_GetType(ID3D11Texture1D *iface,
D3D11_RESOURCE_DIMENSION *resource_dimension)
{
TRACE("iface %p, resource_dimension %p.\n", iface, resource_dimension);
*resource_dimension = D3D11_RESOURCE_DIMENSION_TEXTURE1D;
}
static void STDMETHODCALLTYPE d3d11_texture1d_SetEvictionPriority(ID3D11Texture1D *iface, UINT eviction_priority)
{
FIXME("iface %p, eviction_priority %#x stub!\n", iface, eviction_priority);
}
static UINT STDMETHODCALLTYPE d3d11_texture1d_GetEvictionPriority(ID3D11Texture1D *iface)
{
FIXME("iface %p stub!\n", iface);
return 0;
}
static void STDMETHODCALLTYPE d3d11_texture1d_GetDesc(ID3D11Texture1D *iface, D3D11_TEXTURE1D_DESC *desc)
{
struct d3d_texture1d *texture = impl_from_ID3D11Texture1D(iface);
TRACE("iface %p, desc %p.\n", iface, desc);
*desc = texture->desc;
}
static const struct ID3D11Texture1DVtbl d3d11_texture1d_vtbl =
{
/* IUnknown methods */
d3d11_texture1d_QueryInterface,
d3d11_texture1d_AddRef,
d3d11_texture1d_Release,
/* ID3D11DeviceChild methods */
d3d11_texture1d_GetDevice,
d3d11_texture1d_GetPrivateData,
d3d11_texture1d_SetPrivateData,
d3d11_texture1d_SetPrivateDataInterface,
/* ID3D11Resource methods */
d3d11_texture1d_GetType,
d3d11_texture1d_SetEvictionPriority,
d3d11_texture1d_GetEvictionPriority,
/* ID3D11Texture1D methods */
d3d11_texture1d_GetDesc,
};
struct d3d_texture1d *unsafe_impl_from_ID3D11Texture1D(ID3D11Texture1D *iface)
{
if (!iface)
return NULL;
assert(iface->lpVtbl == &d3d11_texture1d_vtbl);
return CONTAINING_RECORD(iface, struct d3d_texture1d, ID3D11Texture1D_iface);
}
static inline struct d3d_texture1d *impl_from_ID3D10Texture1D(ID3D10Texture1D *iface)
{
return CONTAINING_RECORD(iface, struct d3d_texture1d, ID3D10Texture1D_iface);
}
/* IUnknown methods */
static HRESULT STDMETHODCALLTYPE d3d10_texture1d_QueryInterface(ID3D10Texture1D *iface, REFIID iid, void **out)
{
struct d3d_texture1d *texture = impl_from_ID3D10Texture1D(iface);
TRACE("iface %p, iid %s, out %p.\n", iface, debugstr_guid(iid), out);
return d3d11_texture1d_QueryInterface(&texture->ID3D11Texture1D_iface, iid, out);
}
static ULONG STDMETHODCALLTYPE d3d10_texture1d_AddRef(ID3D10Texture1D *iface)
{
struct d3d_texture1d *texture = impl_from_ID3D10Texture1D(iface);
TRACE("iface %p.\n", iface);
return d3d11_texture1d_AddRef(&texture->ID3D11Texture1D_iface);
}
static void STDMETHODCALLTYPE d3d_texture1d_wined3d_object_released(void *parent)
{
struct d3d_texture1d *texture = parent;
if (texture->dxgi_surface)
IUnknown_Release(texture->dxgi_surface);
wined3d_private_store_cleanup(&texture->private_store);
heap_free(texture);
}
static ULONG STDMETHODCALLTYPE d3d10_texture1d_Release(ID3D10Texture1D *iface)
{
struct d3d_texture1d *texture = impl_from_ID3D10Texture1D(iface);
TRACE("iface %p.\n", iface);
return d3d11_texture1d_Release(&texture->ID3D11Texture1D_iface);
}
/* ID3D10DeviceChild methods */
static void STDMETHODCALLTYPE d3d10_texture1d_GetDevice(ID3D10Texture1D *iface, ID3D10Device **device)
{
struct d3d_texture1d *texture = impl_from_ID3D10Texture1D(iface);
TRACE("iface %p, device %p.\n", iface, device);
ID3D11Device2_QueryInterface(texture->device, &IID_ID3D10Device, (void **)device);
}
static HRESULT STDMETHODCALLTYPE d3d10_texture1d_GetPrivateData(ID3D10Texture1D *iface,
REFGUID guid, UINT *data_size, void *data)
{
struct d3d_texture1d *texture = impl_from_ID3D10Texture1D(iface);
TRACE("iface %p, guid %s, data_size %p, data %p.\n", iface, debugstr_guid(guid), data_size, data);
return d3d11_texture1d_GetPrivateData(&texture->ID3D11Texture1D_iface, guid, data_size, data);
}
static HRESULT STDMETHODCALLTYPE d3d10_texture1d_SetPrivateData(ID3D10Texture1D *iface,
REFGUID guid, UINT data_size, const void *data)
{
struct d3d_texture1d *texture = impl_from_ID3D10Texture1D(iface);
TRACE("iface %p, guid %s, data_size %u, data %p.\n", iface, debugstr_guid(guid), data_size, data);
return d3d11_texture1d_SetPrivateData(&texture->ID3D11Texture1D_iface, guid, data_size, data);
}
static HRESULT STDMETHODCALLTYPE d3d10_texture1d_SetPrivateDataInterface(ID3D10Texture1D *iface,
REFGUID guid, const IUnknown *data)
{
struct d3d_texture1d *texture = impl_from_ID3D10Texture1D(iface);
TRACE("iface %p, guid %s, data %p.\n", iface, debugstr_guid(guid), data);
return d3d11_texture1d_SetPrivateDataInterface(&texture->ID3D11Texture1D_iface, guid, data);
}
/* ID3D10Resource methods */
static void STDMETHODCALLTYPE d3d10_texture1d_GetType(ID3D10Texture1D *iface,
D3D10_RESOURCE_DIMENSION *resource_dimension)
{
TRACE("iface %p, resource_dimension %p\n", iface, resource_dimension);
*resource_dimension = D3D10_RESOURCE_DIMENSION_TEXTURE1D;
}
static void STDMETHODCALLTYPE d3d10_texture1d_SetEvictionPriority(ID3D10Texture1D *iface, UINT eviction_priority)
{
FIXME("iface %p, eviction_priority %u stub!\n", iface, eviction_priority);
}
static UINT STDMETHODCALLTYPE d3d10_texture1d_GetEvictionPriority(ID3D10Texture1D *iface)
{
FIXME("iface %p stub!\n", iface);
return 0;
}
/* ID3D10Texture1D methods */
static HRESULT STDMETHODCALLTYPE d3d10_texture1d_Map(ID3D10Texture1D *iface, UINT sub_resource_idx,
D3D10_MAP map_type, UINT map_flags, void **data)
{
struct d3d_texture1d *texture = impl_from_ID3D10Texture1D(iface);
struct wined3d_map_desc wined3d_map_desc;
HRESULT hr;
TRACE("iface %p, sub_resource_idx %u, map_type %u, map_flags %#x, data %p.\n",
iface, sub_resource_idx, map_type, map_flags, data);
if (map_flags)
FIXME("Ignoring map_flags %#x.\n", map_flags);
wined3d_mutex_lock();
if (SUCCEEDED(hr = wined3d_resource_map(wined3d_texture_get_resource(texture->wined3d_texture), sub_resource_idx,
&wined3d_map_desc, NULL, wined3d_map_flags_from_d3d11_map_type(map_type))))
{
*data = wined3d_map_desc.data;
}
wined3d_mutex_unlock();
return hr;
}
static void STDMETHODCALLTYPE d3d10_texture1d_Unmap(ID3D10Texture1D *iface, UINT sub_resource_idx)
{
struct d3d_texture1d *texture = impl_from_ID3D10Texture1D(iface);
TRACE("iface %p, sub_resource_idx %u.\n", iface, sub_resource_idx);
wined3d_mutex_lock();
wined3d_resource_unmap(wined3d_texture_get_resource(texture->wined3d_texture), sub_resource_idx);
wined3d_mutex_unlock();
}
static void STDMETHODCALLTYPE d3d10_texture1d_GetDesc(ID3D10Texture1D *iface, D3D10_TEXTURE1D_DESC *desc)
{
struct d3d_texture1d *texture = impl_from_ID3D10Texture1D(iface);
D3D11_TEXTURE1D_DESC d3d11_desc;
TRACE("iface %p, desc %p.\n", iface, desc);
d3d11_texture1d_GetDesc(&texture->ID3D11Texture1D_iface, &d3d11_desc);
desc->Width = d3d11_desc.Width;
desc->MipLevels = d3d11_desc.MipLevels;
desc->ArraySize = d3d11_desc.ArraySize;
desc->Format = d3d11_desc.Format;
desc->Usage = d3d10_usage_from_d3d11_usage(d3d11_desc.Usage);
desc->BindFlags = d3d10_bind_flags_from_d3d11_bind_flags(d3d11_desc.BindFlags);
desc->CPUAccessFlags = d3d10_cpu_access_flags_from_d3d11_cpu_access_flags(d3d11_desc.CPUAccessFlags);
desc->MiscFlags = d3d10_resource_misc_flags_from_d3d11_resource_misc_flags(d3d11_desc.MiscFlags);
}
static const struct ID3D10Texture1DVtbl d3d10_texture1d_vtbl =
{
/* IUnknown methods */
d3d10_texture1d_QueryInterface,
d3d10_texture1d_AddRef,
d3d10_texture1d_Release,
/* ID3D10DeviceChild methods */
d3d10_texture1d_GetDevice,
d3d10_texture1d_GetPrivateData,
d3d10_texture1d_SetPrivateData,
d3d10_texture1d_SetPrivateDataInterface,
/* ID3D10Resource methods */
d3d10_texture1d_GetType,
d3d10_texture1d_SetEvictionPriority,
d3d10_texture1d_GetEvictionPriority,
/* ID3D10Texture1D methods */
d3d10_texture1d_Map,
d3d10_texture1d_Unmap,
d3d10_texture1d_GetDesc,
};
struct d3d_texture1d *unsafe_impl_from_ID3D10Texture1D(ID3D10Texture1D *iface)
{
if (!iface)
return NULL;
assert(iface->lpVtbl == &d3d10_texture1d_vtbl);
return CONTAINING_RECORD(iface, struct d3d_texture1d, ID3D10Texture1D_iface);
}
static const struct wined3d_parent_ops d3d_texture1d_wined3d_parent_ops =
{
d3d_texture1d_wined3d_object_released,
};
HRESULT d3d_texture1d_create(struct d3d_device *device, const D3D11_TEXTURE1D_DESC *desc,
const D3D11_SUBRESOURCE_DATA *data, struct d3d_texture1d **out)
{
struct wined3d_resource_desc wined3d_desc;
struct d3d_texture1d *texture;
unsigned int levels;
DWORD flags = 0;
HRESULT hr;
if (!(texture = heap_alloc_zero(sizeof(*texture))))
return E_OUTOFMEMORY;
texture->ID3D11Texture1D_iface.lpVtbl = &d3d11_texture1d_vtbl;
texture->ID3D10Texture1D_iface.lpVtbl = &d3d10_texture1d_vtbl;
texture->refcount = 1;
wined3d_private_store_init(&texture->private_store);
texture->desc = *desc;
levels = desc->MipLevels ? desc->MipLevels : wined3d_log2i(desc->Width) + 1;
texture->desc.MipLevels = levels;
wined3d_desc.resource_type = WINED3D_RTYPE_TEXTURE_1D;
wined3d_desc.format = wined3dformat_from_dxgi_format(desc->Format);
wined3d_desc.multisample_type = WINED3D_MULTISAMPLE_NONE;
wined3d_desc.multisample_quality = 0;
wined3d_desc.usage = wined3d_usage_from_d3d11(desc->Usage);
wined3d_desc.bind_flags = wined3d_bind_flags_from_d3d11(desc->BindFlags, desc->MiscFlags);
wined3d_desc.access = wined3d_access_from_d3d11(desc->Usage,
desc->Usage == D3D11_USAGE_DEFAULT ? 0 : desc->CPUAccessFlags);
wined3d_desc.width = desc->Width;
wined3d_desc.height = 1;
wined3d_desc.depth = 1;
wined3d_desc.size = 0;
if (desc->MiscFlags & D3D11_RESOURCE_MISC_GDI_COMPATIBLE)
flags |= WINED3D_TEXTURE_CREATE_GET_DC;
if (desc->MiscFlags & D3D11_RESOURCE_MISC_GENERATE_MIPS)
flags |= WINED3D_TEXTURE_CREATE_GENERATE_MIPMAPS;
wined3d_mutex_lock();
if (FAILED(hr = wined3d_texture_create(device->wined3d_device, &wined3d_desc,
desc->ArraySize, levels, flags, (struct wined3d_sub_resource_data *)data,
texture, &d3d_texture1d_wined3d_parent_ops, &texture->wined3d_texture)))
{
WARN("Failed to create wined3d texture, hr %#x.\n", hr);
wined3d_private_store_cleanup(&texture->private_store);
heap_free(texture);
wined3d_mutex_unlock();
if (hr == WINED3DERR_NOTAVAILABLE || hr == WINED3DERR_INVALIDCALL)
hr = E_INVALIDARG;
return hr;
}
if (desc->MipLevels == 1 && desc->ArraySize == 1)
{
IWineDXGIDevice *wine_device;
if (FAILED(hr = ID3D10Device1_QueryInterface(&device->ID3D10Device1_iface, &IID_IWineDXGIDevice,
(void **)&wine_device)))
{
ERR("Device should implement IWineDXGIDevice.\n");
wined3d_texture_decref(texture->wined3d_texture);
wined3d_mutex_unlock();
return E_FAIL;
}
hr = IWineDXGIDevice_create_surface(wine_device, texture->wined3d_texture, 0, NULL,
(IUnknown *)&texture->ID3D10Texture1D_iface, (void **)&texture->dxgi_surface);
IWineDXGIDevice_Release(wine_device);
if (FAILED(hr))
{
ERR("Failed to create DXGI surface, returning %#.x\n", hr);
texture->dxgi_surface = NULL;
wined3d_texture_decref(texture->wined3d_texture);
wined3d_mutex_unlock();
return hr;
}
}
wined3d_mutex_unlock();
ID3D11Device2_AddRef(texture->device = &device->ID3D11Device2_iface);
TRACE("Created texture %p.\n", texture);
*out = texture;
return S_OK;
}
/* ID3D11Texture2D methods */
static HRESULT STDMETHODCALLTYPE d3d11_texture2d_QueryInterface(ID3D11Texture2D *iface, REFIID riid, void **object)
{
struct d3d_texture2d *texture = impl_from_ID3D11Texture2D(iface);
TRACE("iface %p, riid %s, object %p.\n", iface, debugstr_guid(riid), object);
if (IsEqualGUID(riid, &IID_ID3D11Texture2D)
|| IsEqualGUID(riid, &IID_ID3D11Resource)
|| IsEqualGUID(riid, &IID_ID3D11DeviceChild)
|| IsEqualGUID(riid, &IID_IUnknown))
{
*object = &texture->ID3D11Texture2D_iface;
IUnknown_AddRef((IUnknown *)*object);
return S_OK;
}
else if (IsEqualGUID(riid, &IID_ID3D10Texture2D)
|| IsEqualGUID(riid, &IID_ID3D10Resource)
|| IsEqualGUID(riid, &IID_ID3D10DeviceChild))
{
*object = &texture->ID3D10Texture2D_iface;
IUnknown_AddRef((IUnknown *)*object);
return S_OK;
}
if (texture->dxgi_surface)
{
TRACE("Forwarding to dxgi surface.\n");
return IUnknown_QueryInterface(texture->dxgi_surface, riid, object);
}
WARN("%s not implemented, returning E_NOINTERFACE.\n", debugstr_guid(riid));
*object = NULL;
return E_NOINTERFACE;
}
static ULONG STDMETHODCALLTYPE d3d11_texture2d_AddRef(ID3D11Texture2D *iface)
{
struct d3d_texture2d *texture = impl_from_ID3D11Texture2D(iface);
ULONG refcount = InterlockedIncrement(&texture->refcount);
TRACE("%p increasing refcount to %u.\n", texture, refcount);
if (refcount == 1)
{
ID3D11Device2_AddRef(texture->device);
wined3d_mutex_lock();
wined3d_texture_incref(texture->wined3d_texture);
wined3d_mutex_unlock();
}
return refcount;
}
static ULONG STDMETHODCALLTYPE d3d11_texture2d_Release(ID3D11Texture2D *iface)
{
struct d3d_texture2d *texture = impl_from_ID3D11Texture2D(iface);
ULONG refcount = InterlockedDecrement(&texture->refcount);
TRACE("%p decreasing refcount to %u.\n", texture, refcount);
if (!refcount)
{
ID3D11Device2 *device = texture->device;
wined3d_mutex_lock();
wined3d_texture_decref(texture->wined3d_texture);
wined3d_mutex_unlock();
/* Release the device last, it may cause the wined3d device to be
* destroyed. */
ID3D11Device2_Release(device);
}
return refcount;
}
static void STDMETHODCALLTYPE d3d11_texture2d_GetDevice(ID3D11Texture2D *iface, ID3D11Device **device)
{
struct d3d_texture2d *texture = impl_from_ID3D11Texture2D(iface);
TRACE("iface %p, device %p.\n", iface, device);
*device = (ID3D11Device *)texture->device;
ID3D11Device_AddRef(*device);
}
static HRESULT STDMETHODCALLTYPE d3d11_texture2d_GetPrivateData(ID3D11Texture2D *iface,
REFGUID guid, UINT *data_size, void *data)
{
struct d3d_texture2d *texture = impl_from_ID3D11Texture2D(iface);
IDXGISurface *dxgi_surface;
HRESULT hr;
TRACE("iface %p, guid %s, data_size %p, data %p.\n", iface, debugstr_guid(guid), data_size, data);
if (texture->dxgi_surface
&& SUCCEEDED(IUnknown_QueryInterface(texture->dxgi_surface, &IID_IDXGISurface, (void **)&dxgi_surface)))
{
hr = IDXGISurface_GetPrivateData(dxgi_surface, guid, data_size, data);
IDXGISurface_Release(dxgi_surface);
return hr;
}
return d3d_get_private_data(&texture->private_store, guid, data_size, data);
}
static HRESULT STDMETHODCALLTYPE d3d11_texture2d_SetPrivateData(ID3D11Texture2D *iface,
REFGUID guid, UINT data_size, const void *data)
{
struct d3d_texture2d *texture = impl_from_ID3D11Texture2D(iface);
IDXGISurface *dxgi_surface;
HRESULT hr;
TRACE("iface %p, guid %s, data_size %u, data %p.\n", iface, debugstr_guid(guid), data_size, data);
if (texture->dxgi_surface
&& SUCCEEDED(IUnknown_QueryInterface(texture->dxgi_surface, &IID_IDXGISurface, (void **)&dxgi_surface)))
{
hr = IDXGISurface_SetPrivateData(dxgi_surface, guid, data_size, data);
IDXGISurface_Release(dxgi_surface);
return hr;
}
return d3d_set_private_data(&texture->private_store, guid, data_size, data);
}
static HRESULT STDMETHODCALLTYPE d3d11_texture2d_SetPrivateDataInterface(ID3D11Texture2D *iface,
REFGUID guid, const IUnknown *data)
{
struct d3d_texture2d *texture = impl_from_ID3D11Texture2D(iface);
IDXGISurface *dxgi_surface;
HRESULT hr;
TRACE("iface %p, guid %s, data %p.\n", iface, debugstr_guid(guid), data);
if (texture->dxgi_surface
&& SUCCEEDED(IUnknown_QueryInterface(texture->dxgi_surface, &IID_IDXGISurface, (void **)&dxgi_surface)))
{
hr = IDXGISurface_SetPrivateDataInterface(dxgi_surface, guid, data);
IDXGISurface_Release(dxgi_surface);
return hr;
}
return d3d_set_private_data_interface(&texture->private_store, guid, data);
}
static void STDMETHODCALLTYPE d3d11_texture2d_GetType(ID3D11Texture2D *iface,
D3D11_RESOURCE_DIMENSION *resource_dimension)
{
TRACE("iface %p, resource_dimension %p.\n", iface, resource_dimension);
*resource_dimension = D3D11_RESOURCE_DIMENSION_TEXTURE2D;
}
static void STDMETHODCALLTYPE d3d11_texture2d_SetEvictionPriority(ID3D11Texture2D *iface, UINT eviction_priority)
{
FIXME("iface %p, eviction_priority %#x stub!\n", iface, eviction_priority);
}
static UINT STDMETHODCALLTYPE d3d11_texture2d_GetEvictionPriority(ID3D11Texture2D *iface)
{
FIXME("iface %p stub!\n", iface);
return 0;
}
static void STDMETHODCALLTYPE d3d11_texture2d_GetDesc(ID3D11Texture2D *iface, D3D11_TEXTURE2D_DESC *desc)
{
struct d3d_texture2d *texture = impl_from_ID3D11Texture2D(iface);
struct wined3d_resource_desc wined3d_desc;
TRACE("iface %p, desc %p.\n", iface, desc);
*desc = texture->desc;
wined3d_mutex_lock();
wined3d_resource_get_desc(wined3d_texture_get_resource(texture->wined3d_texture), &wined3d_desc);
wined3d_mutex_unlock();
/* FIXME: Resizing swapchain buffers can cause these to change. We'd like
* to get everything from wined3d, but e.g. bind flags don't exist as such
* there (yet). */
desc->Width = wined3d_desc.width;
desc->Height = wined3d_desc.height;
desc->Format = dxgi_format_from_wined3dformat(wined3d_desc.format);
desc->SampleDesc.Count = wined3d_desc.multisample_type == WINED3D_MULTISAMPLE_NONE
? 1 : wined3d_desc.multisample_type;
desc->SampleDesc.Quality = wined3d_desc.multisample_quality;
}
static const struct ID3D11Texture2DVtbl d3d11_texture2d_vtbl =
{
/* IUnknown methods */
d3d11_texture2d_QueryInterface,
d3d11_texture2d_AddRef,
d3d11_texture2d_Release,
/* ID3D11DeviceChild methods */
d3d11_texture2d_GetDevice,
d3d11_texture2d_GetPrivateData,
d3d11_texture2d_SetPrivateData,
d3d11_texture2d_SetPrivateDataInterface,
/* ID3D11Resource methods */
d3d11_texture2d_GetType,
d3d11_texture2d_SetEvictionPriority,
d3d11_texture2d_GetEvictionPriority,
/* ID3D11Texture2D methods */
d3d11_texture2d_GetDesc,
};
struct d3d_texture2d *unsafe_impl_from_ID3D11Texture2D(ID3D11Texture2D *iface)
{
if (!iface)
return NULL;
assert(iface->lpVtbl == &d3d11_texture2d_vtbl);
return CONTAINING_RECORD(iface, struct d3d_texture2d, ID3D11Texture2D_iface);
}
/* IUnknown methods */
static inline struct d3d_texture2d *impl_from_ID3D10Texture2D(ID3D10Texture2D *iface)
{
return CONTAINING_RECORD(iface, struct d3d_texture2d, ID3D10Texture2D_iface);
}
static HRESULT STDMETHODCALLTYPE d3d10_texture2d_QueryInterface(ID3D10Texture2D *iface, REFIID riid, void **object)
{
struct d3d_texture2d *texture = impl_from_ID3D10Texture2D(iface);
TRACE("iface %p, riid %s, object %p.\n", iface, debugstr_guid(riid), object);
return d3d11_texture2d_QueryInterface(&texture->ID3D11Texture2D_iface, riid, object);
}
static ULONG STDMETHODCALLTYPE d3d10_texture2d_AddRef(ID3D10Texture2D *iface)
{
struct d3d_texture2d *texture = impl_from_ID3D10Texture2D(iface);
TRACE("iface %p.\n", iface);
return d3d11_texture2d_AddRef(&texture->ID3D11Texture2D_iface);
}
static void STDMETHODCALLTYPE d3d_texture2d_wined3d_object_released(void *parent)
{
struct d3d_texture2d *texture = parent;
if (texture->dxgi_surface) IUnknown_Release(texture->dxgi_surface);
wined3d_private_store_cleanup(&texture->private_store);
heap_free(texture);
}
static ULONG STDMETHODCALLTYPE d3d10_texture2d_Release(ID3D10Texture2D *iface)
{
struct d3d_texture2d *texture = impl_from_ID3D10Texture2D(iface);
TRACE("iface %p.\n", iface);
return d3d11_texture2d_Release(&texture->ID3D11Texture2D_iface);
}
/* ID3D10DeviceChild methods */
static void STDMETHODCALLTYPE d3d10_texture2d_GetDevice(ID3D10Texture2D *iface, ID3D10Device **device)
{
struct d3d_texture2d *texture = impl_from_ID3D10Texture2D(iface);
TRACE("iface %p, device %p.\n", iface, device);
ID3D11Device2_QueryInterface(texture->device, &IID_ID3D10Device, (void **)device);
}
static HRESULT STDMETHODCALLTYPE d3d10_texture2d_GetPrivateData(ID3D10Texture2D *iface,
REFGUID guid, UINT *data_size, void *data)
{
struct d3d_texture2d *texture = impl_from_ID3D10Texture2D(iface);
TRACE("iface %p, guid %s, data_size %p, data %p.\n", iface, debugstr_guid(guid), data_size, data);
return d3d11_texture2d_GetPrivateData(&texture->ID3D11Texture2D_iface, guid, data_size, data);
}
static HRESULT STDMETHODCALLTYPE d3d10_texture2d_SetPrivateData(ID3D10Texture2D *iface,
REFGUID guid, UINT data_size, const void *data)
{
struct d3d_texture2d *texture = impl_from_ID3D10Texture2D(iface);
TRACE("iface %p, guid %s, data_size %u, data %p.\n", iface, debugstr_guid(guid), data_size, data);
return d3d11_texture2d_SetPrivateData(&texture->ID3D11Texture2D_iface, guid, data_size, data);
}
static HRESULT STDMETHODCALLTYPE d3d10_texture2d_SetPrivateDataInterface(ID3D10Texture2D *iface,
REFGUID guid, const IUnknown *data)
{
struct d3d_texture2d *texture = impl_from_ID3D10Texture2D(iface);
TRACE("iface %p, guid %s, data %p.\n", iface, debugstr_guid(guid), data);
return d3d11_texture2d_SetPrivateDataInterface(&texture->ID3D11Texture2D_iface, guid, data);
}
/* ID3D10Resource methods */
static void STDMETHODCALLTYPE d3d10_texture2d_GetType(ID3D10Texture2D *iface,
D3D10_RESOURCE_DIMENSION *resource_dimension)
{
TRACE("iface %p, resource_dimension %p\n", iface, resource_dimension);
*resource_dimension = D3D10_RESOURCE_DIMENSION_TEXTURE2D;
}
static void STDMETHODCALLTYPE d3d10_texture2d_SetEvictionPriority(ID3D10Texture2D *iface, UINT eviction_priority)
{
FIXME("iface %p, eviction_priority %u stub!\n", iface, eviction_priority);
}
static UINT STDMETHODCALLTYPE d3d10_texture2d_GetEvictionPriority(ID3D10Texture2D *iface)
{
FIXME("iface %p stub!\n", iface);
return 0;
}
/* ID3D10Texture2D methods */
static HRESULT STDMETHODCALLTYPE d3d10_texture2d_Map(ID3D10Texture2D *iface, UINT sub_resource_idx,
D3D10_MAP map_type, UINT map_flags, D3D10_MAPPED_TEXTURE2D *mapped_texture)
{
struct d3d_texture2d *texture = impl_from_ID3D10Texture2D(iface);
struct wined3d_map_desc wined3d_map_desc;
HRESULT hr;
TRACE("iface %p, sub_resource_idx %u, map_type %u, map_flags %#x, mapped_texture %p.\n",
iface, sub_resource_idx, map_type, map_flags, mapped_texture);
if (map_flags)
FIXME("Ignoring map_flags %#x.\n", map_flags);
wined3d_mutex_lock();
if (SUCCEEDED(hr = wined3d_resource_map(wined3d_texture_get_resource(texture->wined3d_texture), sub_resource_idx,
&wined3d_map_desc, NULL, wined3d_map_flags_from_d3d11_map_type(map_type))))
{
mapped_texture->pData = wined3d_map_desc.data;
mapped_texture->RowPitch = wined3d_map_desc.row_pitch;
}
wined3d_mutex_unlock();
return hr;
}
static void STDMETHODCALLTYPE d3d10_texture2d_Unmap(ID3D10Texture2D *iface, UINT sub_resource_idx)
{
struct d3d_texture2d *texture = impl_from_ID3D10Texture2D(iface);
TRACE("iface %p, sub_resource_idx %u.\n", iface, sub_resource_idx);
wined3d_mutex_lock();
wined3d_resource_unmap(wined3d_texture_get_resource(texture->wined3d_texture), sub_resource_idx);
wined3d_mutex_unlock();
}
static void STDMETHODCALLTYPE d3d10_texture2d_GetDesc(ID3D10Texture2D *iface, D3D10_TEXTURE2D_DESC *desc)
{
struct d3d_texture2d *texture = impl_from_ID3D10Texture2D(iface);
D3D11_TEXTURE2D_DESC d3d11_desc;
TRACE("iface %p, desc %p\n", iface, desc);
d3d11_texture2d_GetDesc(&texture->ID3D11Texture2D_iface, &d3d11_desc);
desc->Width = d3d11_desc.Width;
desc->Height = d3d11_desc.Height;
desc->MipLevels = d3d11_desc.MipLevels;
desc->ArraySize = d3d11_desc.ArraySize;
desc->Format = d3d11_desc.Format;
desc->SampleDesc = d3d11_desc.SampleDesc;
desc->Usage = d3d10_usage_from_d3d11_usage(d3d11_desc.Usage);
desc->BindFlags = d3d10_bind_flags_from_d3d11_bind_flags(d3d11_desc.BindFlags);
desc->CPUAccessFlags = d3d10_cpu_access_flags_from_d3d11_cpu_access_flags(d3d11_desc.CPUAccessFlags);
desc->MiscFlags = d3d10_resource_misc_flags_from_d3d11_resource_misc_flags(d3d11_desc.MiscFlags);
}
static const struct ID3D10Texture2DVtbl d3d10_texture2d_vtbl =
{
/* IUnknown methods */
d3d10_texture2d_QueryInterface,
d3d10_texture2d_AddRef,
d3d10_texture2d_Release,
/* ID3D10DeviceChild methods */
d3d10_texture2d_GetDevice,
d3d10_texture2d_GetPrivateData,
d3d10_texture2d_SetPrivateData,
d3d10_texture2d_SetPrivateDataInterface,
/* ID3D10Resource methods */
d3d10_texture2d_GetType,
d3d10_texture2d_SetEvictionPriority,
d3d10_texture2d_GetEvictionPriority,
/* ID3D10Texture2D methods */
d3d10_texture2d_Map,
d3d10_texture2d_Unmap,
d3d10_texture2d_GetDesc,
};
struct d3d_texture2d *unsafe_impl_from_ID3D10Texture2D(ID3D10Texture2D *iface)
{
if (!iface)
return NULL;
assert(iface->lpVtbl == &d3d10_texture2d_vtbl);
return CONTAINING_RECORD(iface, struct d3d_texture2d, ID3D10Texture2D_iface);
}
static const struct wined3d_parent_ops d3d_texture2d_wined3d_parent_ops =
{
d3d_texture2d_wined3d_object_released,
};
static BOOL is_gdi_compatible_texture(const D3D11_TEXTURE2D_DESC *desc)
{
if (!(desc->Format == DXGI_FORMAT_B8G8R8A8_UNORM
|| desc->Format == DXGI_FORMAT_B8G8R8A8_TYPELESS
|| desc->Format == DXGI_FORMAT_B8G8R8A8_UNORM_SRGB))
return FALSE;
if (desc->Usage != D3D11_USAGE_DEFAULT)
return FALSE;
return TRUE;
}
static BOOL validate_texture2d_desc(const D3D11_TEXTURE2D_DESC *desc, D3D_FEATURE_LEVEL feature_level)
{
if (!validate_d3d11_resource_access_flags(D3D11_RESOURCE_DIMENSION_TEXTURE2D,
desc->Usage, desc->BindFlags, desc->CPUAccessFlags, feature_level))
return FALSE;
if (desc->MiscFlags & D3D11_RESOURCE_MISC_TEXTURECUBE
&& desc->ArraySize < 6)
{
WARN("Invalid array size %u for cube texture.\n", desc->ArraySize);
return FALSE;
}
if (desc->MiscFlags & D3D11_RESOURCE_MISC_GDI_COMPATIBLE
&& !is_gdi_compatible_texture(desc))
{
WARN("Incompatible description used to create GDI compatible texture.\n");
return FALSE;
}
if (desc->MiscFlags & D3D11_RESOURCE_MISC_GENERATE_MIPS
&& (~desc->BindFlags & (D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE)))
{
WARN("D3D11_RESOURCE_MISC_GENERATE_MIPS used without D3D11_BIND_RENDER_TARGET and "
"D3D11_BIND_SHADER_RESOURCE.\n");
return FALSE;
}
return TRUE;
}
HRESULT d3d_texture2d_create(struct d3d_device *device, const D3D11_TEXTURE2D_DESC *desc,
const D3D11_SUBRESOURCE_DATA *data, struct d3d_texture2d **out)
{
struct wined3d_resource_desc wined3d_desc;
struct d3d_texture2d *texture;
unsigned int levels;
DWORD flags = 0;
HRESULT hr;
if (!validate_texture2d_desc(desc, device->feature_level))
{
WARN("Failed to validate texture desc.\n");
return E_INVALIDARG;
}
if (!(texture = heap_alloc_zero(sizeof(*texture))))
return E_OUTOFMEMORY;
texture->ID3D11Texture2D_iface.lpVtbl = &d3d11_texture2d_vtbl;
texture->ID3D10Texture2D_iface.lpVtbl = &d3d10_texture2d_vtbl;
texture->refcount = 1;
wined3d_mutex_lock();
wined3d_private_store_init(&texture->private_store);
texture->desc = *desc;
wined3d_desc.resource_type = WINED3D_RTYPE_TEXTURE_2D;
wined3d_desc.format = wined3dformat_from_dxgi_format(desc->Format);
wined3d_desc.multisample_type = desc->SampleDesc.Count > 1 ? desc->SampleDesc.Count : WINED3D_MULTISAMPLE_NONE;
wined3d_desc.multisample_quality = desc->SampleDesc.Quality;
wined3d_desc.usage = wined3d_usage_from_d3d11(desc->Usage);
wined3d_desc.bind_flags = wined3d_bind_flags_from_d3d11(desc->BindFlags, desc->MiscFlags);
wined3d_desc.access = wined3d_access_from_d3d11(desc->Usage,
desc->Usage == D3D11_USAGE_DEFAULT ? 0 : desc->CPUAccessFlags);
wined3d_desc.width = desc->Width;
wined3d_desc.height = desc->Height;
wined3d_desc.depth = 1;
wined3d_desc.size = 0;
levels = desc->MipLevels ? desc->MipLevels : wined3d_log2i(max(desc->Width, desc->Height)) + 1;
if (desc->MiscFlags & D3D11_RESOURCE_MISC_GDI_COMPATIBLE)
flags |= WINED3D_TEXTURE_CREATE_GET_DC;
if (desc->MiscFlags & D3D11_RESOURCE_MISC_GENERATE_MIPS)
flags |= WINED3D_TEXTURE_CREATE_GENERATE_MIPMAPS;
if (FAILED(hr = wined3d_texture_create(device->wined3d_device, &wined3d_desc,
desc->ArraySize, levels, flags, (struct wined3d_sub_resource_data *)data,
texture, &d3d_texture2d_wined3d_parent_ops, &texture->wined3d_texture)))
{
WARN("Failed to create wined3d texture, hr %#x.\n", hr);
wined3d_private_store_cleanup(&texture->private_store);
heap_free(texture);
wined3d_mutex_unlock();
if (hr == WINED3DERR_NOTAVAILABLE || hr == WINED3DERR_INVALIDCALL)
hr = E_INVALIDARG;
return hr;
}
texture->desc.MipLevels = levels;
if (desc->MipLevels == 1 && desc->ArraySize == 1)
{
IWineDXGIDevice *wine_device;
if (FAILED(hr = ID3D10Device1_QueryInterface(&device->ID3D10Device1_iface, &IID_IWineDXGIDevice,
(void **)&wine_device)))
{
ERR("Device should implement IWineDXGIDevice.\n");
wined3d_texture_decref(texture->wined3d_texture);
wined3d_mutex_unlock();
return E_FAIL;
}
hr = IWineDXGIDevice_create_surface(wine_device, texture->wined3d_texture, 0, NULL,
(IUnknown *)&texture->ID3D10Texture2D_iface, (void **)&texture->dxgi_surface);
IWineDXGIDevice_Release(wine_device);
if (FAILED(hr))
{
ERR("Failed to create DXGI surface, returning %#.x\n", hr);
texture->dxgi_surface = NULL;
wined3d_texture_decref(texture->wined3d_texture);
wined3d_mutex_unlock();
return hr;
}
}
wined3d_mutex_unlock();
ID3D11Device2_AddRef(texture->device = &device->ID3D11Device2_iface);
TRACE("Created texture %p.\n", texture);
*out = texture;
return S_OK;
}
/* ID3D11Texture3D methods */
static inline struct d3d_texture3d *impl_from_ID3D11Texture3D(ID3D11Texture3D *iface)
{
return CONTAINING_RECORD(iface, struct d3d_texture3d, ID3D11Texture3D_iface);
}
static HRESULT STDMETHODCALLTYPE d3d11_texture3d_QueryInterface(ID3D11Texture3D *iface, REFIID riid, void **object)
{
struct d3d_texture3d *texture = impl_from_ID3D11Texture3D(iface);
TRACE("iface %p, riid %s, object %p.\n", iface, debugstr_guid(riid), object);
if (IsEqualGUID(riid, &IID_ID3D11Texture3D)
|| IsEqualGUID(riid, &IID_ID3D11Resource)
|| IsEqualGUID(riid, &IID_ID3D11DeviceChild)
|| IsEqualGUID(riid, &IID_IUnknown))
{
IUnknown_AddRef(iface);
*object = iface;
return S_OK;
}
else if (IsEqualGUID(riid, &IID_ID3D10Texture3D)
|| IsEqualGUID(riid, &IID_ID3D10Resource)
|| IsEqualGUID(riid, &IID_ID3D10DeviceChild))
{
IUnknown_AddRef(iface);
*object = &texture->ID3D10Texture3D_iface;
return S_OK;
}
WARN("%s not implemented, returning E_NOINTERFACE.\n", debugstr_guid(riid));
*object = NULL;
return E_NOINTERFACE;
}
static ULONG STDMETHODCALLTYPE d3d11_texture3d_AddRef(ID3D11Texture3D *iface)
{
struct d3d_texture3d *texture = impl_from_ID3D11Texture3D(iface);
ULONG refcount = InterlockedIncrement(&texture->refcount);
TRACE("%p increasing refcount to %u.\n", texture, refcount);
if (refcount == 1)
{
ID3D11Device2_AddRef(texture->device);
wined3d_mutex_lock();
wined3d_texture_incref(texture->wined3d_texture);
wined3d_mutex_unlock();
}
return refcount;
}
static void STDMETHODCALLTYPE d3d_texture3d_wined3d_object_released(void *parent)
{
struct d3d_texture3d *texture = parent;
wined3d_private_store_cleanup(&texture->private_store);
heap_free(parent);
}
static ULONG STDMETHODCALLTYPE d3d11_texture3d_Release(ID3D11Texture3D *iface)
{
struct d3d_texture3d *texture = impl_from_ID3D11Texture3D(iface);
ULONG refcount = InterlockedDecrement(&texture->refcount);
TRACE("%p decreasing refcount to %u.\n", texture, refcount);
if (!refcount)
{
ID3D11Device2 *device = texture->device;
wined3d_mutex_lock();
wined3d_texture_decref(texture->wined3d_texture);
wined3d_mutex_unlock();
/* Release the device last, it may cause the wined3d device to be
* destroyed. */
ID3D11Device2_Release(device);
}
return refcount;
}
static void STDMETHODCALLTYPE d3d11_texture3d_GetDevice(ID3D11Texture3D *iface, ID3D11Device **device)
{
struct d3d_texture3d *texture = impl_from_ID3D11Texture3D(iface);
TRACE("iface %p, device %p.\n", iface, device);
*device = (ID3D11Device *)texture->device;
ID3D11Device_AddRef(*device);
}
static HRESULT STDMETHODCALLTYPE d3d11_texture3d_GetPrivateData(ID3D11Texture3D *iface,
REFGUID guid, UINT *data_size, void *data)
{
struct d3d_texture3d *texture = impl_from_ID3D11Texture3D(iface);
TRACE("iface %p, guid %s, data_size %p, data %p.\n", iface, debugstr_guid(guid), data_size, data);
return d3d_get_private_data(&texture->private_store, guid, data_size, data);
}
static HRESULT STDMETHODCALLTYPE d3d11_texture3d_SetPrivateData(ID3D11Texture3D *iface,
REFGUID guid, UINT data_size, const void *data)
{
struct d3d_texture3d *texture = impl_from_ID3D11Texture3D(iface);
TRACE("iface %p, guid %s, data_size %u, data %p.\n", iface, debugstr_guid(guid), data_size, data);
return d3d_set_private_data(&texture->private_store, guid, data_size, data);
}
static HRESULT STDMETHODCALLTYPE d3d11_texture3d_SetPrivateDataInterface(ID3D11Texture3D *iface,
REFGUID guid, const IUnknown *data)
{
struct d3d_texture3d *texture = impl_from_ID3D11Texture3D(iface);
TRACE("iface %p, guid %s, data %p.\n", iface, debugstr_guid(guid), data);
return d3d_set_private_data_interface(&texture->private_store, guid, data);
}
static void STDMETHODCALLTYPE d3d11_texture3d_GetType(ID3D11Texture3D *iface,
D3D11_RESOURCE_DIMENSION *resource_dimension)
{
TRACE("iface %p, resource_dimension %p.\n", iface, resource_dimension);
*resource_dimension = D3D11_RESOURCE_DIMENSION_TEXTURE3D;
}
static void STDMETHODCALLTYPE d3d11_texture3d_SetEvictionPriority(ID3D11Texture3D *iface, UINT eviction_priority)
{
FIXME("iface %p, eviction_priority %#x stub!\n", iface, eviction_priority);
}
static UINT STDMETHODCALLTYPE d3d11_texture3d_GetEvictionPriority(ID3D11Texture3D *iface)
{
FIXME("iface %p stub!\n", iface);
return 0;
}
static void STDMETHODCALLTYPE d3d11_texture3d_GetDesc(ID3D11Texture3D *iface, D3D11_TEXTURE3D_DESC *desc)
{
struct d3d_texture3d *texture = impl_from_ID3D11Texture3D(iface);
TRACE("iface %p, desc %p.\n", iface, desc);
*desc = texture->desc;
}
static const struct ID3D11Texture3DVtbl d3d11_texture3d_vtbl =
{
/* IUnknown methods */
d3d11_texture3d_QueryInterface,
d3d11_texture3d_AddRef,
d3d11_texture3d_Release,
/* ID3D11DeviceChild methods */
d3d11_texture3d_GetDevice,
d3d11_texture3d_GetPrivateData,
d3d11_texture3d_SetPrivateData,
d3d11_texture3d_SetPrivateDataInterface,
/* ID3D11Resource methods */
d3d11_texture3d_GetType,
d3d11_texture3d_SetEvictionPriority,
d3d11_texture3d_GetEvictionPriority,
/* ID3D11Texture3D methods */
d3d11_texture3d_GetDesc,
};
/* ID3D10Texture3D methods */
static inline struct d3d_texture3d *impl_from_ID3D10Texture3D(ID3D10Texture3D *iface)
{
return CONTAINING_RECORD(iface, struct d3d_texture3d, ID3D10Texture3D_iface);
}
static HRESULT STDMETHODCALLTYPE d3d10_texture3d_QueryInterface(ID3D10Texture3D *iface, REFIID riid, void **object)
{
struct d3d_texture3d *texture = impl_from_ID3D10Texture3D(iface);
TRACE("iface %p, riid %s, object %p.\n", iface, debugstr_guid(riid), object);
return d3d11_texture3d_QueryInterface(&texture->ID3D11Texture3D_iface, riid, object);
}
static ULONG STDMETHODCALLTYPE d3d10_texture3d_AddRef(ID3D10Texture3D *iface)
{
struct d3d_texture3d *texture = impl_from_ID3D10Texture3D(iface);
TRACE("iface %p.\n", iface);
return d3d11_texture3d_AddRef(&texture->ID3D11Texture3D_iface);
}
static ULONG STDMETHODCALLTYPE d3d10_texture3d_Release(ID3D10Texture3D *iface)
{
struct d3d_texture3d *texture = impl_from_ID3D10Texture3D(iface);
TRACE("iface %p.\n", iface);
return d3d11_texture3d_Release(&texture->ID3D11Texture3D_iface);
}
static void STDMETHODCALLTYPE d3d10_texture3d_GetDevice(ID3D10Texture3D *iface, ID3D10Device **device)
{
struct d3d_texture3d *texture = impl_from_ID3D10Texture3D(iface);
TRACE("iface %p, device %p.\n", iface, device);
ID3D11Device2_QueryInterface(texture->device, &IID_ID3D10Device, (void **)device);
}
static HRESULT STDMETHODCALLTYPE d3d10_texture3d_GetPrivateData(ID3D10Texture3D *iface,
REFGUID guid, UINT *data_size, void *data)
{
struct d3d_texture3d *texture = impl_from_ID3D10Texture3D(iface);
TRACE("iface %p, guid %s, data_size %p, data %p.\n",
iface, debugstr_guid(guid), data_size, data);
return d3d_get_private_data(&texture->private_store, guid, data_size, data);
}
static HRESULT STDMETHODCALLTYPE d3d10_texture3d_SetPrivateData(ID3D10Texture3D *iface,
REFGUID guid, UINT data_size, const void *data)
{
struct d3d_texture3d *texture = impl_from_ID3D10Texture3D(iface);
TRACE("iface %p, guid %s, data_size %u, data %p.\n",
iface, debugstr_guid(guid), data_size, data);
return d3d_set_private_data(&texture->private_store, guid, data_size, data);
}
static HRESULT STDMETHODCALLTYPE d3d10_texture3d_SetPrivateDataInterface(ID3D10Texture3D *iface,
REFGUID guid, const IUnknown *data)
{
struct d3d_texture3d *texture = impl_from_ID3D10Texture3D(iface);
TRACE("iface %p, guid %s, data %p.\n", iface, debugstr_guid(guid), data);
return d3d_set_private_data_interface(&texture->private_store, guid, data);
}
static void STDMETHODCALLTYPE d3d10_texture3d_GetType(ID3D10Texture3D *iface,
D3D10_RESOURCE_DIMENSION *resource_dimension)
{
TRACE("iface %p, resource_dimension %p.\n", iface, resource_dimension);
*resource_dimension = D3D10_RESOURCE_DIMENSION_TEXTURE3D;
}
static void STDMETHODCALLTYPE d3d10_texture3d_SetEvictionPriority(ID3D10Texture3D *iface, UINT eviction_priority)
{
FIXME("iface %p, eviction_priority %u stub!\n", iface, eviction_priority);
}
static UINT STDMETHODCALLTYPE d3d10_texture3d_GetEvictionPriority(ID3D10Texture3D *iface)
{
FIXME("iface %p stub!\n", iface);
return 0;
}
static HRESULT STDMETHODCALLTYPE d3d10_texture3d_Map(ID3D10Texture3D *iface, UINT sub_resource_idx,
D3D10_MAP map_type, UINT map_flags, D3D10_MAPPED_TEXTURE3D *mapped_texture)
{
struct d3d_texture3d *texture = impl_from_ID3D10Texture3D(iface);
struct wined3d_map_desc wined3d_map_desc;
HRESULT hr;
TRACE("iface %p, sub_resource_idx %u, map_type %u, map_flags %#x, mapped_texture %p.\n",
iface, sub_resource_idx, map_type, map_flags, mapped_texture);
if (map_flags)
FIXME("Ignoring map_flags %#x.\n", map_flags);
wined3d_mutex_lock();
if (SUCCEEDED(hr = wined3d_resource_map(wined3d_texture_get_resource(texture->wined3d_texture), sub_resource_idx,
&wined3d_map_desc, NULL, wined3d_map_flags_from_d3d11_map_type(map_type))))
{
mapped_texture->pData = wined3d_map_desc.data;
mapped_texture->RowPitch = wined3d_map_desc.row_pitch;
mapped_texture->DepthPitch = wined3d_map_desc.slice_pitch;
}
wined3d_mutex_unlock();
return hr;
}
static void STDMETHODCALLTYPE d3d10_texture3d_Unmap(ID3D10Texture3D *iface, UINT sub_resource_idx)
{
struct d3d_texture3d *texture = impl_from_ID3D10Texture3D(iface);
TRACE("iface %p, sub_resource_idx %u.\n", iface, sub_resource_idx);
wined3d_mutex_lock();
wined3d_resource_unmap(wined3d_texture_get_resource(texture->wined3d_texture), sub_resource_idx);
wined3d_mutex_unlock();
}
static void STDMETHODCALLTYPE d3d10_texture3d_GetDesc(ID3D10Texture3D *iface, D3D10_TEXTURE3D_DESC *desc)
{
struct d3d_texture3d *texture = impl_from_ID3D10Texture3D(iface);
D3D11_TEXTURE3D_DESC d3d11_desc;
TRACE("iface %p, desc %p.\n", iface, desc);
d3d11_texture3d_GetDesc(&texture->ID3D11Texture3D_iface, &d3d11_desc);
desc->Width = d3d11_desc.Width;
desc->Height = d3d11_desc.Height;
desc->Depth = d3d11_desc.Depth;
desc->MipLevels = d3d11_desc.MipLevels;
desc->Format = d3d11_desc.Format;
desc->Usage = d3d10_usage_from_d3d11_usage(d3d11_desc.Usage);
desc->BindFlags = d3d10_bind_flags_from_d3d11_bind_flags(d3d11_desc.BindFlags);
desc->CPUAccessFlags = d3d10_cpu_access_flags_from_d3d11_cpu_access_flags(d3d11_desc.CPUAccessFlags);
desc->MiscFlags = d3d10_resource_misc_flags_from_d3d11_resource_misc_flags(d3d11_desc.MiscFlags);
}
static const struct ID3D10Texture3DVtbl d3d10_texture3d_vtbl =
{
/* IUnknown methods */
d3d10_texture3d_QueryInterface,
d3d10_texture3d_AddRef,
d3d10_texture3d_Release,
/* ID3D10DeviceChild methods */
d3d10_texture3d_GetDevice,
d3d10_texture3d_GetPrivateData,
d3d10_texture3d_SetPrivateData,
d3d10_texture3d_SetPrivateDataInterface,
/* ID3D10Resource methods */
d3d10_texture3d_GetType,
d3d10_texture3d_SetEvictionPriority,
d3d10_texture3d_GetEvictionPriority,
/* ID3D10Texture3D methods */
d3d10_texture3d_Map,
d3d10_texture3d_Unmap,
d3d10_texture3d_GetDesc,
};
struct d3d_texture3d *unsafe_impl_from_ID3D10Texture3D(ID3D10Texture3D *iface)
{
if (!iface)
return NULL;
assert(iface->lpVtbl == &d3d10_texture3d_vtbl);
return CONTAINING_RECORD(iface, struct d3d_texture3d, ID3D10Texture3D_iface);
}
struct d3d_texture3d *unsafe_impl_from_ID3D11Texture3D(ID3D11Texture3D *iface)
{
if (!iface)
return NULL;
assert(iface->lpVtbl == &d3d11_texture3d_vtbl);
return impl_from_ID3D11Texture3D(iface);
}
static const struct wined3d_parent_ops d3d_texture3d_wined3d_parent_ops =
{
d3d_texture3d_wined3d_object_released,
};
static HRESULT d3d_texture3d_init(struct d3d_texture3d *texture, struct d3d_device *device,
const D3D11_TEXTURE3D_DESC *desc, const D3D11_SUBRESOURCE_DATA *data)
{
struct wined3d_resource_desc wined3d_desc;
unsigned int levels;
DWORD flags = 0;
HRESULT hr;
if (desc->MiscFlags & D3D11_RESOURCE_MISC_GENERATE_MIPS
&& (~desc->BindFlags & (D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE)))
{
WARN("D3D11_RESOURCE_MISC_GENERATE_MIPS used without D3D11_BIND_RENDER_TARGET "
"and D3D11_BIND_SHADER_RESOURCE.\n");
return E_INVALIDARG;
}
texture->ID3D11Texture3D_iface.lpVtbl = &d3d11_texture3d_vtbl;
texture->ID3D10Texture3D_iface.lpVtbl = &d3d10_texture3d_vtbl;
texture->refcount = 1;
wined3d_mutex_lock();
wined3d_private_store_init(&texture->private_store);
texture->desc = *desc;
wined3d_desc.resource_type = WINED3D_RTYPE_TEXTURE_3D;
wined3d_desc.format = wined3dformat_from_dxgi_format(desc->Format);
wined3d_desc.multisample_type = WINED3D_MULTISAMPLE_NONE;
wined3d_desc.multisample_quality = 0;
wined3d_desc.usage = wined3d_usage_from_d3d11(desc->Usage);
wined3d_desc.bind_flags = wined3d_bind_flags_from_d3d11(desc->BindFlags, desc->MiscFlags);
wined3d_desc.access = wined3d_access_from_d3d11(desc->Usage,
desc->Usage == D3D11_USAGE_DEFAULT ? 0 : desc->CPUAccessFlags);
wined3d_desc.width = desc->Width;
wined3d_desc.height = desc->Height;
wined3d_desc.depth = desc->Depth;
wined3d_desc.size = 0;
levels = desc->MipLevels ? desc->MipLevels : wined3d_log2i(max(max(desc->Width, desc->Height), desc->Depth)) + 1;
if (desc->MiscFlags & D3D11_RESOURCE_MISC_GENERATE_MIPS)
flags |= WINED3D_TEXTURE_CREATE_GENERATE_MIPMAPS;
if (FAILED(hr = wined3d_texture_create(device->wined3d_device, &wined3d_desc,
1, levels, flags, (struct wined3d_sub_resource_data *)data, texture,
&d3d_texture3d_wined3d_parent_ops, &texture->wined3d_texture)))
{
WARN("Failed to create wined3d texture, hr %#x.\n", hr);
wined3d_private_store_cleanup(&texture->private_store);
wined3d_mutex_unlock();
if (hr == WINED3DERR_INVALIDCALL)
hr = E_INVALIDARG;
return hr;
}
wined3d_mutex_unlock();
texture->desc.MipLevels = levels;
ID3D11Device2_AddRef(texture->device = &device->ID3D11Device2_iface);
return S_OK;
}
HRESULT d3d_texture3d_create(struct d3d_device *device, const D3D11_TEXTURE3D_DESC *desc,
const D3D11_SUBRESOURCE_DATA *data, struct d3d_texture3d **texture)
{
struct d3d_texture3d *object;
HRESULT hr;
if (!(object = heap_alloc_zero(sizeof(*object))))
return E_OUTOFMEMORY;
if (FAILED(hr = d3d_texture3d_init(object, device, desc, data)))
{
WARN("Failed to initialize texture, hr %#x.\n", hr);
heap_free(object);
return hr;
}
TRACE("Created texture %p.\n", object);
*texture = object;
return S_OK;
}
| 34.558766 | 117 | 0.732829 |
d21eded8521bfd6ecc1c56279747c346089e286f | 1,378 | h | C | System/Library/Frameworks/AVKit.framework/AVKeyValueObserverCollection.h | lechium/tvOS135Headers | 46cd30d3f0f7962eaa0c3f925cd71f414c65e2ac | [
"MIT"
] | 2 | 2020-07-26T20:30:54.000Z | 2020-08-10T04:26:23.000Z | System/Library/Frameworks/AVKit.framework/AVKeyValueObserverCollection.h | lechium/tvOS135Headers | 46cd30d3f0f7962eaa0c3f925cd71f414c65e2ac | [
"MIT"
] | 1 | 2020-07-26T20:45:31.000Z | 2020-08-09T09:30:46.000Z | System/Library/Frameworks/AVKit.framework/AVKeyValueObserverCollection.h | lechium/tvOS135Headers | 46cd30d3f0f7962eaa0c3f925cd71f414c65e2ac | [
"MIT"
] | null | null | null | /*
* This header is generated by classdump-dyld 1.0
* on Sunday, June 7, 2020 at 11:24:38 AM Mountain Standard Time
* Operating System: Version 13.4.5 (Build 17L562)
* Image Source: /System/Library/Frameworks/AVKit.framework/AVKit
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos.
*/
@class NSMutableDictionary;
@interface AVKeyValueObserverCollection : NSObject {
NSMutableDictionary* _keyObserverMap;
id _rootObject;
}
@property (readonly) NSMutableDictionary * keyObserverMap; //@synthesize keyObserverMap=_keyObserverMap - In the implementation block
@property (readonly) id rootObject; //@synthesize rootObject=_rootObject - In the implementation block
-(void)dealloc;
-(void)invalidate;
-(void)observeValueForKeyPath:(id)arg1 ofObject:(id)arg2 change:(id)arg3 context:(void*)arg4 ;
-(id)rootObject;
-(id)initWithObservedObject:(id)arg1 ;
-(void)startObservingKeyPath:(id)arg1 options:(unsigned long long)arg2 block:(/*^block*/id)arg3 ;
-(void)stopObservingKeyPath:(id)arg1 ;
-(void)startObservingKeyPath:(id)arg1 options:(unsigned long long)arg2 selector:(SEL)arg3 ;
-(void)bindKeyPath:(id)arg1 toKeyPath:(id)arg2 nilNumber:(id)arg3 ;
-(void)bindKeyPath:(id)arg1 toKeyPath:(id)arg2 ;
-(void)bindKeyPath:(id)arg1 toBoolKeyPath:(id)arg2 ;
-(NSMutableDictionary *)keyObserverMap;
@end
| 39.371429 | 146 | 0.74746 |
9aa4decf2cd5bc0436a8e4eddbdd769f3ee8fc16 | 1,905 | h | C | modules/planning/lattice/trajectory_generation/lateral_trajectory_optimizer.h | JLBrother2016/apollo-planning-reading-nodes | b56cd7e04fad2d73e5c188c89c82400c6a51cada | [
"Apache-2.0"
] | 1 | 2021-09-07T15:36:08.000Z | 2021-09-07T15:36:08.000Z | modules/planning/lattice/trajectory_generation/lateral_trajectory_optimizer.h | jlcoo/apollo-planning-reading-nodes | b56cd7e04fad2d73e5c188c89c82400c6a51cada | [
"Apache-2.0"
] | null | null | null | modules/planning/lattice/trajectory_generation/lateral_trajectory_optimizer.h | jlcoo/apollo-planning-reading-nodes | b56cd7e04fad2d73e5c188c89c82400c6a51cada | [
"Apache-2.0"
] | 2 | 2019-08-15T09:14:32.000Z | 2019-09-03T14:07:24.000Z | /******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
/**
* @file
**/
#ifndef MODULES_PLANNING_LATTICE_LATERAL_TRAJECTORY_OPTIMIZER_H_
#define MODULES_PLANNING_LATTICE_LATERAL_TRAJECTORY_OPTIMIZER_H_
#include <array>
#include <memory>
#include <utility>
#include <vector>
#include "modules/planning/lattice/behavior/path_time_graph.h"
#include "modules/planning/lattice/trajectory1d/piecewise_jerk_trajectory1d.h"
#include "modules/planning/lattice/trajectory_generation/lateral_trajectory_optimizer_interface.h"
namespace apollo {
namespace planning {
// 侧面轨迹的优化器
class LateralTrajectoryOptimizer {
public:
LateralTrajectoryOptimizer() = default;
virtual ~LateralTrajectoryOptimizer() = default;
bool optimize(
const std::array<double, 3>& d_state,
const double delta_s,
const std::vector<std::pair<double, double>>& d_bounds);
PiecewiseJerkTrajectory1d GetOptimalTrajectory() const;
private:
std::vector<double> opt_d_;
std::vector<double> opt_d_prime_;
std::vector<double> opt_d_pprime_;
double delta_s_ = 0.0;
};
} // namespace planning
} // namespace apollo
#endif /* MODULES_PLANNING_LATTICE_LATERAL_TRAJECTORY_OPTIMIZER_H_ */
| 30.725806 | 98 | 0.704987 |
9ac493d6ab571132095dc21e0ffa1f8e9f1ec880 | 11,502 | h | C | src/protocols/bdx/BdxMessages.h | Seo-Young/connectedhomeip | 41700bd3fe73259227f974298958fc0dba763db3 | [
"Apache-2.0"
] | 1 | 2022-03-13T12:33:56.000Z | 2022-03-13T12:33:56.000Z | src/protocols/bdx/BdxMessages.h | Seo-Young/connectedhomeip | 41700bd3fe73259227f974298958fc0dba763db3 | [
"Apache-2.0"
] | null | null | null | src/protocols/bdx/BdxMessages.h | Seo-Young/connectedhomeip | 41700bd3fe73259227f974298958fc0dba763db3 | [
"Apache-2.0"
] | null | null | null | /*
*
* Copyright (c) 2020-2021 Project CHIP Authors
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @file
* This file defines structures and utility methods for working with BDX
* messages, mainly for writing to and reading from PacketBuffers.
*/
#pragma once
#include <lib/support/BitFlags.h>
#include <lib/support/BufferWriter.h>
#include <lib/support/CodeUtils.h>
#include <protocols/Protocols.h>
#include <system/SystemPacketBuffer.h>
namespace chip {
namespace bdx {
enum class MessageType : uint8_t
{
SendInit = 0x01,
SendAccept = 0x02,
ReceiveInit = 0x04,
ReceiveAccept = 0x05,
BlockQuery = 0x10,
Block = 0x11,
BlockEOF = 0x12,
BlockAck = 0x13,
BlockAckEOF = 0x14,
BlockQueryWithSkip = 0x15,
};
enum class StatusCode : uint16_t
{
kNone = 0x0000,
kOverflow = 0x0011,
kLengthTooLarge = 0x0012,
kLengthTooShort = 0x0013,
kLengthMismatch = 0x0014,
kLengthRequired = 0x0015,
kBadMessageContents = 0x0016,
kBadBlockCounter = 0x0017,
kUnexpectedMessage = 0x0018,
kTransferFailedUnknownError = 0x001F,
kFailureToSend = 0x0021,
kTransferMethodNotSupported = 0x0050,
kFileDesignatorUnknown = 0x0051,
kStartOffsetNotSupported = 0x0052,
kVersionNotSupported = 0x0053,
kUnknown = 0x005F,
};
enum class TransferControlFlags : uint8_t
{
// first 4 bits reserved for version
kSenderDrive = (1U << 4),
kReceiverDrive = (1U << 5),
kAsync = (1U << 6),
};
enum class RangeControlFlags : uint8_t
{
kDefLen = (1U),
kStartOffset = (1U << 1),
kWiderange = (1U << 4),
};
/**
* @brief
* Interface for defining methods that apply to all BDX messages.
*/
struct BdxMessage
{
/**
* @brief
* Parse data from an PacketBuffer into a BdxMessage struct.
*
* Note that this may store pointers that point into the passed PacketBuffer,
* so it is essential that the underlying PacketBuffer is not modified until after this
* struct is no longer needed.
*
* @param[in] aBuffer A PacketBufferHandle with a refernce to the PacketBuffer containing the data.
*
* @return CHIP_ERROR Return an error if the message format is invalid and/or can't be parsed
*/
CHECK_RETURN_VALUE
virtual CHIP_ERROR Parse(System::PacketBufferHandle aBuffer) = 0;
/**
* @brief
* Write the message fields to a buffer using the provided BufferWriter.
*
* It is up to the caller to use BufferWriter::Fit() to verify that the write was
* successful. This method will also not check for correctness or completeness for
* any of the fields - it is the caller's responsibility to ensure that the fields
* align with BDX specifications.
*
* @param aBuffer A BufferWriter object that will be used to write the message
*/
virtual Encoding::LittleEndian::BufferWriter & WriteToBuffer(Encoding::LittleEndian::BufferWriter & aBuffer) const = 0;
/**
* @brief
* Returns the size of buffer needed to write the message.
*/
virtual size_t MessageSize() const = 0;
#if CHIP_AUTOMATION_LOGGING
/**
* @brief
* Log all parameters for this message.
*/
virtual void LogMessage(bdx::MessageType messageType) const = 0;
#endif // CHIP_AUTOMATION_LOGGING
virtual ~BdxMessage() = default;
};
/*
* A structure for representing a SendInit or ReceiveInit message (both contain
* identical parameters).
*/
struct TransferInit : public BdxMessage
{
bool operator==(const TransferInit &) const;
// Proposed Transfer Control (required)
BitFlags<TransferControlFlags> TransferCtlOptions;
uint8_t Version = 0; ///< The highest version supported by the sender
// Range Control
BitFlags<RangeControlFlags> mRangeCtlFlags;
// All required
uint16_t MaxBlockSize = 0; ///< Proposed max block size to use in transfer
uint64_t StartOffset = 0; ///< Proposed start offset of data. 0 for no offset
uint64_t MaxLength = 0; ///< Proposed max length of data in transfer, 0 for indefinite
// File designator (required) and additional metadata (optional, TLV format)
// WARNING: there is no guarantee at any point that these pointers will point to valid memory. The Buffer field should be used
// to hold a reference to the PacketBuffer containing the data in order to ensure the data is not freed.
const uint8_t * FileDesignator = nullptr;
uint16_t FileDesLength = 0; ///< Length of file designator string (not including null-terminator)
const uint8_t * Metadata = nullptr;
size_t MetadataLength = 0;
// Retain ownership of the packet buffer so that the FileDesignator and Metadata pointers remain valid.
System::PacketBufferHandle Buffer;
CHIP_ERROR Parse(System::PacketBufferHandle aBuffer) override;
Encoding::LittleEndian::BufferWriter & WriteToBuffer(Encoding::LittleEndian::BufferWriter & aBuffer) const override;
size_t MessageSize() const override;
#if CHIP_AUTOMATION_LOGGING
void LogMessage(bdx::MessageType messageType) const override;
#endif // CHIP_AUTOMATION_LOGGING
};
using SendInit = TransferInit;
using ReceiveInit = TransferInit;
/*
* A structure for representing a SendAccept message.
*/
struct SendAccept : public BdxMessage
{
bool operator==(const SendAccept &) const;
// Transfer Control (required, only one should be set)
BitFlags<TransferControlFlags> TransferCtlFlags;
uint8_t Version = 0; ///< The agreed upon version for the transfer (required)
uint16_t MaxBlockSize = 0; ///< Chosen max block size to use in transfer (required)
// Additional metadata (optional, TLV format)
// WARNING: there is no guarantee at any point that this pointer will point to valid memory. The Buffer field should be used to
// hold a reference to the PacketBuffer containing the data in order to ensure the data is not freed.
const uint8_t * Metadata = nullptr;
size_t MetadataLength = 0;
// Retain ownership of the packet buffer so that the FileDesignator and Metadata pointers remain valid.
System::PacketBufferHandle Buffer;
CHIP_ERROR Parse(System::PacketBufferHandle aBuffer) override;
Encoding::LittleEndian::BufferWriter & WriteToBuffer(Encoding::LittleEndian::BufferWriter & aBuffer) const override;
size_t MessageSize() const override;
#if CHIP_AUTOMATION_LOGGING
void LogMessage(bdx::MessageType messageType) const override;
#endif // CHIP_AUTOMATION_LOGGING
};
/**
* A structure for representing ReceiveAccept messages.
*/
struct ReceiveAccept : public BdxMessage
{
bool operator==(const ReceiveAccept &) const;
// Transfer Control (required, only one should be set)
BitFlags<TransferControlFlags> TransferCtlFlags;
// Range Control
BitFlags<RangeControlFlags> mRangeCtlFlags;
// All required
uint8_t Version = 0; ///< The agreed upon version for the transfer
uint16_t MaxBlockSize = 0; ///< Chosen max block size to use in transfer
uint64_t StartOffset = 0; ///< Chosen start offset of data. 0 for no offset.
uint64_t Length = 0; ///< Length of transfer. 0 if length is indefinite.
// Additional metadata (optional, TLV format)
// WARNING: there is no guarantee at any point that this pointer will point to valid memory. The Buffer field should be used to
// hold a reference to the PacketBuffer containing the data in order to ensure the data is not freed.
const uint8_t * Metadata = nullptr;
size_t MetadataLength = 0;
// Retain ownership of the packet buffer so that the FileDesignator and Metadata pointers remain valid.
System::PacketBufferHandle Buffer;
CHIP_ERROR Parse(System::PacketBufferHandle aBuffer) override;
Encoding::LittleEndian::BufferWriter & WriteToBuffer(Encoding::LittleEndian::BufferWriter & aBuffer) const override;
size_t MessageSize() const override;
#if CHIP_AUTOMATION_LOGGING
void LogMessage(bdx::MessageType messageType) const override;
#endif // CHIP_AUTOMATION_LOGGING
};
/**
* A struct for representing messages contiaining just a counter field. Can be used to
* represent BlockQuery, BlockAck, and BlockAckEOF.
*/
struct CounterMessage : public BdxMessage
{
bool operator==(const CounterMessage &) const;
uint32_t BlockCounter = 0;
CHIP_ERROR Parse(System::PacketBufferHandle aBuffer) override;
Encoding::LittleEndian::BufferWriter & WriteToBuffer(Encoding::LittleEndian::BufferWriter & aBuffer) const override;
size_t MessageSize() const override;
#if CHIP_AUTOMATION_LOGGING
void LogMessage(bdx::MessageType messageType) const override;
#endif // CHIP_AUTOMATION_LOGGING
};
using BlockQuery = CounterMessage;
using BlockAck = CounterMessage;
using BlockAckEOF = CounterMessage;
/**
* A struct that represents a message containing actual data (Block, BlockEOF).
*/
struct DataBlock : public BdxMessage
{
bool operator==(const DataBlock &) const;
uint32_t BlockCounter = 0;
// WARNING: there is no guarantee at any point that this pointer will point to valid memory. The Buffer field should be used to
// hold a reference to the PacketBuffer containing the data in order to ensure the data is not freed.
const uint8_t * Data = nullptr;
size_t DataLength = 0;
// Retain ownership of the packet buffer so that the FileDesignator and Metadata pointers remain valid.
System::PacketBufferHandle Buffer;
CHIP_ERROR Parse(System::PacketBufferHandle aBuffer) override;
Encoding::LittleEndian::BufferWriter & WriteToBuffer(Encoding::LittleEndian::BufferWriter & aBuffer) const override;
size_t MessageSize() const override;
#if CHIP_AUTOMATION_LOGGING
void LogMessage(bdx::MessageType messageType) const override;
#endif // CHIP_AUTOMATION_LOGGING
};
using Block = DataBlock;
using BlockEOF = DataBlock;
struct BlockQueryWithSkip : public BdxMessage
{
bool operator==(const BlockQueryWithSkip &) const;
uint32_t BlockCounter = 0;
uint64_t BytesToSkip = 0;
CHIP_ERROR Parse(System::PacketBufferHandle aBuffer) override;
Encoding::LittleEndian::BufferWriter & WriteToBuffer(Encoding::LittleEndian::BufferWriter & aBuffer) const override;
size_t MessageSize() const override;
#if CHIP_AUTOMATION_LOGGING
void LogMessage(bdx::MessageType messageType) const override;
#endif // CHIP_AUTOMATION_LOGGING
};
} // namespace bdx
namespace Protocols {
template <>
struct MessageTypeTraits<bdx::MessageType>
{
static constexpr const Protocols::Id & ProtocolId() { return BDX::Id; }
};
} // namespace Protocols
} // namespace chip
| 36.056426 | 131 | 0.70579 |
82a3a05ad8d62912d51140e252d9bbf170def6b4 | 12,655 | c | C | src/loader.c | yuri1969/pgbouncer | f60acea0ee343e71fd8bf230d2c37260a7ad2c49 | [
"0BSD"
] | 1,535 | 2015-04-10T17:36:50.000Z | 2022-03-31T08:31:44.000Z | src/loader.c | RekGRpth/pgbouncer | 8eb4c356daa0fe75eb99a6c0c5bbcf912319aec1 | [
"0BSD"
] | 586 | 2015-04-10T09:46:47.000Z | 2022-03-30T18:52:03.000Z | src/loader.c | RekGRpth/pgbouncer | 8eb4c356daa0fe75eb99a6c0c5bbcf912319aec1 | [
"0BSD"
] | 374 | 2015-04-10T08:45:35.000Z | 2022-03-23T09:55:43.000Z | /*
* PgBouncer - Lightweight connection pooler for PostgreSQL.
*
* Copyright (c) 2007-2009 Marko Kreen, Skype Technologies OÜ
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
/*
* Config and auth file reading.
*/
#include "bouncer.h"
#include <usual/fileutil.h>
/*
* ConnString parsing
*/
/* just skip whitespace */
static char *cstr_skip_ws(char *p)
{
while (*p && *p == ' ')
p++;
return p;
}
/* parse parameter name before '=' */
static char *cstr_get_key(char *p, char **dst_p)
{
char *end;
p = cstr_skip_ws(p);
*dst_p = p;
while (*p && *p != '=' && *p != ' ')
p++;
end = p;
p = cstr_skip_ws(p);
/* fail if no '=' or empty name */
if (*p != '=' || *dst_p == end)
return NULL;
*end = 0;
return p + 1;
}
/* unquote the quoted value after first quote */
static char *cstr_unquote_value(char *p)
{
char *s = p;
while (1) {
if (!*p)
return NULL;
if (p[0] == '\'') {
if (p[1] == '\'')
p++;
else
break;
}
*s++ = *p++;
}
/* terminate actual value */
*s = 0;
/* return position after quote */
return p + 1;
}
/* parse value, possibly quoted */
static char *cstr_get_value(char *p, char **dst_p)
{
p = cstr_skip_ws(p);
if (*p == '\'') {
*dst_p = ++p;
p = cstr_unquote_value(p);
if (!p)
return NULL;
} else {
*dst_p = p;
while (*p && *p != ' ')
p++;
}
if (*p) {
/* if not EOL, cut value */
*p = 0;
p++;
}
/* disallow empty values */
if (*dst_p[0] == 0)
return NULL;
return p;
}
/*
* Get key=val pair from connstring. Returns position it stopped
* or NULL on error. EOF is signaled by *key = 0.
*/
static char * cstr_get_pair(char *p,
char **key_p,
char **val_p)
{
p = cstr_skip_ws(p);
*key_p = *val_p = p;
if (*p == 0)
return p;
/* read key */
p = cstr_get_key(p, key_p);
if (!p)
return NULL;
/* read value */
p = cstr_get_value(p, val_p);
if (!p)
return NULL;
log_noise("cstr_get_pair: \"%s\"=\"%s\"", *key_p, *val_p);
return cstr_skip_ws(p);
}
static bool set_autodb(const char *connstr)
{
char *tmp = strdup(connstr);
char *old = cf_autodb_connstr;
if (!tmp) {
log_error("no mem to change autodb_connstr");
return false;
}
cf_autodb_connstr = tmp;
if (old) {
if (strcmp(connstr, old) != 0)
tag_autodb_dirty();
free(old);
}
return true;
}
/* fill PgDatabase from connstr */
bool parse_database(void *base, const char *name, const char *connstr)
{
char *p, *key, *val;
PktBuf *msg;
PgDatabase *db;
struct CfValue cv;
int pool_size = -1;
int min_pool_size = -1;
int res_pool_size = -1;
int max_db_connections = -1;
int dbname_ofs;
int pool_mode = POOL_INHERIT;
char *tmp_connstr;
const char *dbname = name;
char *host = NULL;
int port = 5432;
char *username = NULL;
char *password = "";
char *auth_username = NULL;
char *client_encoding = NULL;
char *datestyle = NULL;
char *timezone = NULL;
char *connect_query = NULL;
char *appname = NULL;
cv.value_p = &pool_mode;
cv.extra = (const void *)pool_mode_map;
if (strcmp(name, "pgbouncer") == 0) {
log_error("database name \"%s\" is reserved", name);
return false;
}
if (strcmp(name, "*") == 0) {
return set_autodb(connstr);
}
tmp_connstr = strdup(connstr);
if (!tmp_connstr) {
log_error("out of memory");
return false;
}
p = tmp_connstr;
while (*p) {
p = cstr_get_pair(p, &key, &val);
if (p == NULL) {
log_error("syntax error in connection string");
goto fail;
} else if (!key[0]) {
break;
}
if (strcmp("dbname", key) == 0) {
dbname = val;
} else if (strcmp("host", key) == 0) {
host = strdup(val);
if (!host) {
log_error("out of memory");
goto fail;
}
} else if (strcmp("port", key) == 0) {
port = atoi(val);
if (port == 0) {
log_error("invalid port: %s", val);
goto fail;
}
} else if (strcmp("user", key) == 0) {
username = val;
} else if (strcmp("password", key) == 0) {
password = val;
} else if (strcmp("auth_user", key) == 0) {
auth_username = val;
} else if (strcmp("client_encoding", key) == 0) {
client_encoding = val;
} else if (strcmp("datestyle", key) == 0) {
datestyle = val;
} else if (strcmp("timezone", key) == 0) {
timezone = val;
} else if (strcmp("pool_size", key) == 0) {
pool_size = atoi(val);
} else if (strcmp("min_pool_size", key) == 0) {
min_pool_size = atoi(val);
} else if (strcmp("reserve_pool", key) == 0) {
res_pool_size = atoi(val);
} else if (strcmp("max_db_connections", key) == 0) {
max_db_connections = atoi(val);
} else if (strcmp("pool_mode", key) == 0) {
if (!cf_set_lookup(&cv, val)) {
log_error("invalid pool mode: %s", val);
goto fail;
}
} else if (strcmp("connect_query", key) == 0) {
connect_query = strdup(val);
if (!connect_query) {
log_error("out of memory");
goto fail;
}
} else if (strcmp("application_name", key) == 0) {
appname = val;
} else {
log_error("unrecognized connection parameter: %s", key);
goto fail;
}
}
db = add_database(name);
if (!db) {
log_error("cannot create database, no memory?");
goto fail;
}
/* tag the db as alive */
db->db_dead = false;
/* assuming not an autodb */
db->db_auto = false;
db->inactive_time = 0;
/* if updating old db, check if anything changed */
if (db->dbname) {
bool changed = false;
if (strcmp(db->dbname, dbname) != 0) {
changed = true;
} else if (!!host != !!db->host
|| (host && strcmp(host, db->host) != 0)) {
changed = true;
} else if (port != db->port) {
changed = true;
} else if (username && !db->forced_user) {
changed = true;
} else if (username && strcmp(username, db->forced_user->name) != 0) {
changed = true;
} else if (!username && db->forced_user) {
changed = true;
} else if (!!connect_query != !!db->connect_query
|| (connect_query && strcmp(connect_query, db->connect_query) != 0)) {
changed = true;
}
if (changed)
tag_database_dirty(db);
}
free(db->host);
db->host = host;
db->port = port;
db->pool_size = pool_size;
db->min_pool_size = min_pool_size;
db->res_pool_size = res_pool_size;
db->pool_mode = pool_mode;
db->max_db_connections = max_db_connections;
free(db->connect_query);
db->connect_query = connect_query;
if (db->startup_params) {
msg = db->startup_params;
pktbuf_reset(msg);
} else {
msg = pktbuf_dynamic(128);
if (!msg)
die("out of memory");
db->startup_params = msg;
}
pktbuf_put_string(msg, "database");
dbname_ofs = msg->write_pos;
pktbuf_put_string(msg, dbname);
if (client_encoding) {
pktbuf_put_string(msg, "client_encoding");
pktbuf_put_string(msg, client_encoding);
}
if (datestyle) {
pktbuf_put_string(msg, "datestyle");
pktbuf_put_string(msg, datestyle);
}
if (timezone) {
pktbuf_put_string(msg, "timezone");
pktbuf_put_string(msg, timezone);
}
if (appname) {
pktbuf_put_string(msg, "application_name");
pktbuf_put_string(msg, appname);
}
if (auth_username != NULL) {
db->auth_user = find_user(auth_username);
if (!db->auth_user) {
db->auth_user = add_user(auth_username, "");
}
} else if (db->auth_user) {
db->auth_user = NULL;
}
/* if user is forced, create fake object for it */
if (username != NULL) {
if (!force_user(db, username, password))
log_warning("db setup failed, trying to continue");
} else if (db->forced_user) {
log_warning("losing forced user not supported,"
" keeping old setting");
}
/* remember dbname */
db->dbname = (char *)msg->buf + dbname_ofs;
free(tmp_connstr);
return true;
fail:
free(tmp_connstr);
return false;
}
bool parse_user(void *base, const char *name, const char *connstr)
{
char *p, *key, *val, *tmp_connstr;
PgUser *user;
struct CfValue cv;
int pool_mode = POOL_INHERIT;
int max_user_connections = -1;
cv.value_p = &pool_mode;
cv.extra = (const void *)pool_mode_map;
tmp_connstr = strdup(connstr);
if (!tmp_connstr) {
log_error("out of memory");
return false;
}
p = tmp_connstr;
while (*p) {
p = cstr_get_pair(p, &key, &val);
if (p == NULL) {
log_error("syntax error in user settings");
goto fail;
} else if (!key[0]) {
break;
}
if (strcmp("pool_mode", key) == 0) {
if (!cf_set_lookup(&cv, val)) {
log_error("invalid pool mode: %s", val);
goto fail;
}
} else if (strcmp("max_user_connections", key) == 0) {
max_user_connections = atoi(val);
} else {
log_error("unrecognized user parameter: %s", key);
goto fail;
}
}
user = find_user(name);
if (!user) {
user = add_user(name, "");
if (!user) {
log_error("cannot create user, no memory?");
goto fail;
}
}
user->pool_mode = pool_mode;
user->max_user_connections = max_user_connections;
free(tmp_connstr);
return true;
fail:
free(tmp_connstr);
return false;
}
/*
* User file parsing
*/
/* find next " in string, skipping escaped ones */
static char *find_quote(char *p, bool start)
{
loop:
while (*p && *p != '"')
p++;
if (p[0] == '"' && p[1] == '"' && !start) {
p += 2;
goto loop;
}
return p;
}
/* string is unquoted while copying */
static void copy_quoted(char *dst, const char *src, int len)
{
char *end = dst + len - 1;
while (*src && dst < end) {
if (*src == '"')
src++;
*dst++ = *src++;
}
*dst = 0;
}
static void unquote_add_user(const char *username, const char *password)
{
char real_user[MAX_USERNAME];
char real_passwd[MAX_PASSWORD];
PgUser *user;
copy_quoted(real_user, username, sizeof(real_user));
copy_quoted(real_passwd, password, sizeof(real_passwd));
user = add_user(real_user, real_passwd);
if (!user)
log_warning("cannot create user, no memory");
}
static bool auth_loaded(const char *fn)
{
static bool cache_set = false;
static struct stat cache;
struct stat cur;
/* no file specified */
if (fn == NULL) {
memset(&cache, 0, sizeof(cache));
cache_set = true;
return false;
}
if (stat(fn, &cur) < 0)
memset(&cur, 0, sizeof(cur));
if (cache_set && cache.st_dev == cur.st_dev
&& cache.st_ino == cur.st_ino
&& cache.st_mode == cur.st_mode
&& cache.st_uid == cur.st_uid
&& cache.st_gid == cur.st_gid
&& cache.st_mtime == cur.st_mtime
&& cache.st_size == cur.st_size)
return true;
cache = cur;
cache_set = true;
return false;
}
bool loader_users_check(void)
{
if (auth_loaded(cf_auth_file))
return true;
return load_auth_file(cf_auth_file);
}
static void disable_users(void)
{
PgUser *user;
struct List *item;
statlist_for_each(item, &user_list) {
user = container_of(item, PgUser, head);
user->passwd[0] = 0;
}
}
/* load list of users from auth_file */
bool load_auth_file(const char *fn)
{
char *user, *password, *buf, *p;
/* No file to load? */
if (fn == NULL)
return false;
buf = load_file(fn, NULL);
if (buf == NULL) {
log_error("could not open auth_file %s: %s", fn, strerror(errno));
return false;
}
log_debug("loading auth_file: \"%s\"", fn);
disable_users();
p = buf;
while (*p) {
/* skip whitespace and empty lines */
while (*p && isspace(*p)) p++;
if (!*p)
break;
/* skip commented-out lines */
if (*p == ';') {
while (*p && *p != '\n') p++;
continue;
}
/* start of line */
if (*p != '"') {
log_error("broken auth file");
break;
}
user = ++p;
p = find_quote(p, false);
if (*p != '"') {
log_error("broken auth file");
break;
}
if (p - user >= MAX_USERNAME) {
log_error("username too long in auth file");
break;
}
*p++ = 0; /* tag username end */
/* get password */
p = find_quote(p, true);
if (*p != '"') {
log_error("broken auth file");
break;
}
password = ++p;
p = find_quote(p, false);
if (*p != '"') {
log_error("broken auth file");
break;
}
if (p - password >= MAX_PASSWORD) {
log_error("password too long in auth file");
break;
}
*p++ = 0; /* tag password end */
/* send them away */
unquote_add_user(user, password);
/* skip rest of the line */
while (*p && *p != '\n') p++;
}
free(buf);
return true;
}
| 21.233221 | 76 | 0.618886 |
19184c650caade96d360bf521eb8174eeb30612f | 2,338 | h | C | ios/Classes/Navigator/NavigatorPageRoute.h | wittyneko/flutter_thrio | 74abb6ec2ef0b75b026f5429ba4c1c11274085f5 | [
"MIT"
] | 231 | 2021-02-20T02:39:31.000Z | 2022-03-27T04:29:23.000Z | ios/Classes/Navigator/NavigatorPageRoute.h | wittyneko/flutter_thrio | 74abb6ec2ef0b75b026f5429ba4c1c11274085f5 | [
"MIT"
] | 41 | 2021-02-20T04:01:59.000Z | 2022-03-07T06:54:10.000Z | ios/Classes/Navigator/NavigatorPageRoute.h | wittyneko/flutter_thrio | 74abb6ec2ef0b75b026f5429ba4c1c11274085f5 | [
"MIT"
] | 28 | 2021-02-20T02:45:14.000Z | 2021-12-28T09:39:59.000Z | // The MIT License (MIT)
//
// Copyright (c) 2019 Hellobike Group
//
// 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.
#import <Foundation/Foundation.h>
#import "ThrioTypes.h"
#import "NavigatorRouteSettings.h"
NS_ASSUME_NONNULL_BEGIN
typedef enum : NSUInteger {
NavigatorRouteActionNone,
NavigatorRouteActionPush,
NavigatorRouteActionPop,
NavigatorRouteActionPopTo,
NavigatorRouteActionRemove,
} NavigatorRouteAction;
@interface NavigatorPageRoute : NSObject
+ (instancetype)routeWithSettings:(NavigatorRouteSettings *)settings;
- (instancetype)initWithSettings:(NavigatorRouteSettings *)settings;
- (void)addNotify:(NSString *)name params:(id _Nullable)params;
- (id _Nullable)removeNotify:(NSString *)name;
@property (nonatomic, strong, nullable) NavigatorPageRoute *prev;
@property (nonatomic, strong, nullable) NavigatorPageRoute *next;
@property (nonatomic, strong, readonly) NavigatorRouteSettings *settings;
@property (nonatomic, copy, readonly) NSDictionary *notifications;
/// The poppedResult passed in when the push method is called.
///
@property (nonatomic, copy, nullable) ThrioIdCallback poppedResult;
/// The current route was pushed by the engine with `fromEntrypoint`.
///
@property (nonatomic, copy, nullable) NSString *fromEntrypoint;
@end
NS_ASSUME_NONNULL_END
| 35.969231 | 79 | 0.77716 |
d2928440169547693ca81e93df8fd918061f6ccf | 489 | h | C | CommanderLifeCounter/RollADieViewController.h | VasiliyEgorov/Commander-Life-Counter | 1d2450a8387efc78db330b2db9e13218e2b42f5c | [
"MIT"
] | null | null | null | CommanderLifeCounter/RollADieViewController.h | VasiliyEgorov/Commander-Life-Counter | 1d2450a8387efc78db330b2db9e13218e2b42f5c | [
"MIT"
] | null | null | null | CommanderLifeCounter/RollADieViewController.h | VasiliyEgorov/Commander-Life-Counter | 1d2450a8387efc78db330b2db9e13218e2b42f5c | [
"MIT"
] | null | null | null | //
// RollADieViewController.h
// CommanderLifeCounter
//
// Created by Vasiliy Egorov on 14.07.17.
// Copyright © 2017 VasiliyEgorov. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "RandomData.h"
@interface RollADieViewController : UIViewController <RandomNumbersProtocol>
@property (strong, nonatomic) RandomData *rollData;
@property (strong, nonatomic) IBOutletCollection(UIView) NSArray *imageViewArray;
@property (weak, nonatomic) IBOutlet UILabel *textLabel;
@end
| 23.285714 | 81 | 0.766871 |
c5d78b0d86629de5068d6b0a72a709018e63f554 | 5,567 | h | C | dali/pipeline/operators/crop/crop_attr.h | kychennv/DALI | ae3f6dcd55a419c230e60f6bdfafbcde2250b9a1 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | dali/pipeline/operators/crop/crop_attr.h | kychennv/DALI | ae3f6dcd55a419c230e60f6bdfafbcde2250b9a1 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | dali/pipeline/operators/crop/crop_attr.h | kychennv/DALI | ae3f6dcd55a419c230e60f6bdfafbcde2250b9a1 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | // Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef DALI_PIPELINE_OPERATORS_CROP_CROP_ATTR_H_
#define DALI_PIPELINE_OPERATORS_CROP_CROP_ATTR_H_
#include <cmath>
#include <utility>
#include <vector>
#include "dali/core/common.h"
#include "dali/core/error_handling.h"
#include "dali/pipeline/operators/common.h"
#include "dali/pipeline/operators/operator.h"
#include "dali/util/crop_window.h"
namespace dali {
/**
* @brief Crop parameter and input size handling.
*
* Responsible for accessing image type, starting points and size of crop area.
*/
class CropAttr {
protected:
explicit inline CropAttr(const OpSpec &spec)
: spec__(spec)
, batch_size__(spec__.GetArgument<int>("batch_size")) {
int crop_h = 0, crop_w = 0;
bool has_crop_arg = spec__.HasArgument("crop");
bool has_crop_w_arg = spec__.ArgumentDefined("crop_w");
bool has_crop_h_arg = spec__.ArgumentDefined("crop_h");
is_whole_image_ = !has_crop_arg && !has_crop_w_arg && !has_crop_h_arg;
DALI_ENFORCE(has_crop_w_arg == has_crop_h_arg,
"`crop_w` and `crop_h` arguments must be provided together");
if (has_crop_arg) {
DALI_ENFORCE(!has_crop_h_arg && !has_crop_w_arg,
"`crop` argument is not compatible with `crop_h`, `crop_w`");
auto cropArg = spec.GetRepeatedArgument<float>("crop");
DALI_ENFORCE(cropArg.size() > 0 && cropArg.size() <= 2);
crop_h = static_cast<int>(cropArg[0]);
crop_w = static_cast<int>(cropArg.size() == 2 ? cropArg[1] : cropArg[0]);
DALI_ENFORCE(crop_h >= 0,
"Crop height must be greater than zero. Received: " +
std::to_string(crop_h));
DALI_ENFORCE(crop_w >= 0,
"Crop width must be greater than zero. Received: " +
std::to_string(crop_w));
}
crop_height_.resize(batch_size__, crop_h);
crop_width_.resize(batch_size__, crop_w);
crop_x_norm_.resize(batch_size__, 0.0f);
crop_y_norm_.resize(batch_size__, 0.0f);
crop_window_generators_.resize(batch_size__, {});
}
void ProcessArguments(const ArgumentWorkspace *ws, std::size_t data_idx) {
crop_x_norm_[data_idx] = spec__.GetArgument<float>("crop_pos_x", ws, data_idx);
crop_y_norm_[data_idx] = spec__.GetArgument<float>("crop_pos_y", ws, data_idx);
if (!is_whole_image_) {
if (crop_width_[data_idx] == 0) {
crop_width_[data_idx] = static_cast<int>(
spec__.GetArgument<float>("crop_w", ws, data_idx));
}
if (crop_height_[data_idx] == 0) {
crop_height_[data_idx] = static_cast<int>(
spec__.GetArgument<float>("crop_h", ws, data_idx));
}
}
crop_window_generators_[data_idx] =
[this, data_idx](int H, int W) {
CropWindow crop_window;
crop_window.h = crop_height_[data_idx];
crop_window.w = crop_width_[data_idx];
std::tie(crop_window.y, crop_window.x) =
CalculateCropYX(
crop_y_norm_[data_idx], crop_x_norm_[data_idx],
crop_window.h, crop_window.w,
H, W);
DALI_ENFORCE(crop_window.IsInRange(H, W));
return crop_window;
};
}
void ProcessArguments(const ArgumentWorkspace &ws) {
for (std::size_t data_idx = 0; data_idx < batch_size__; data_idx++) {
ProcessArguments(&ws, data_idx);
}
}
void ProcessArguments(const SampleWorkspace &ws) {
ProcessArguments(&ws, ws.data_idx());
}
const CropWindowGenerator& GetCropWindowGenerator(std::size_t data_idx) const {
DALI_ENFORCE(data_idx < crop_window_generators_.size());
return crop_window_generators_[data_idx];
}
/**
* @brief Calculate coordinate where the crop starts in pixels.
*/
std::pair<int, int> CalculateCropYX(float crop_y_norm, float crop_x_norm,
int crop_H, int crop_W,
int H, int W) {
DALI_ENFORCE(crop_y_norm >= 0.f && crop_y_norm <= 1.f,
"Crop coordinates need to be in range [0.0, 1.0]");
DALI_ENFORCE(crop_x_norm >= 0.f && crop_x_norm <= 1.f,
"Crop coordinates need to be in range [0.0, 1.0]");
DALI_ENFORCE(crop_W > 0 && crop_W <= W, "Invalid crop_width: " + std::to_string(crop_W)
+ " (image_width: " + std::to_string(W) + ")");
DALI_ENFORCE(crop_H > 0 && crop_H <= H, "Invalid crop_heigth: " + std::to_string(crop_H)
+ " (image_heigth: " + std::to_string(H) + ")");
const int crop_y = std::round(crop_y_norm * (H - crop_H));
const int crop_x = std::round(crop_x_norm * (W - crop_W));
return std::make_pair(crop_y, crop_x);
}
inline bool IsWholeImage() const {
return is_whole_image_;
}
std::vector<int> crop_height_;
std::vector<int> crop_width_;
std::vector<float> crop_x_norm_;
std::vector<float> crop_y_norm_;
std::vector<CropWindowGenerator> crop_window_generators_;
bool is_whole_image_ = false;
private:
OpSpec spec__;
std::size_t batch_size__;
};
} // namespace dali
#endif // DALI_PIPELINE_OPERATORS_CROP_CROP_ATTR_H_
| 35.458599 | 92 | 0.673612 |
303fede966fd0aa215d01faf34bcc26247779962 | 579 | c | C | gcc-gcc-7_3_0-release/gcc/testsuite/gcc.target/powerpc/bfp/scalar-cmp-exp-eq-0.c | best08618/asylo | 5a520a9f5c461ede0f32acc284017b737a43898c | [
"Apache-2.0"
] | 7 | 2020-05-02T17:34:05.000Z | 2021-10-17T10:15:18.000Z | gcc-gcc-7_3_0-release/gcc/testsuite/gcc.target/powerpc/bfp/scalar-cmp-exp-eq-0.c | best08618/asylo | 5a520a9f5c461ede0f32acc284017b737a43898c | [
"Apache-2.0"
] | null | null | null | gcc-gcc-7_3_0-release/gcc/testsuite/gcc.target/powerpc/bfp/scalar-cmp-exp-eq-0.c | best08618/asylo | 5a520a9f5c461ede0f32acc284017b737a43898c | [
"Apache-2.0"
] | 2 | 2020-07-27T00:22:36.000Z | 2021-04-01T09:41:02.000Z | /* { dg-do compile { target { powerpc*-*-* } } } */
/* { dg-skip-if "do not override -mcpu" { powerpc*-*-* } { "-mcpu=*" } { "-mcpu=power9" } } */
/* { dg-require-effective-target powerpc_p9vector_ok } */
/* { dg-options "-mcpu=power9" } */
/* This test should succeed on 32-bit and 64-bit configurations. */
#include <altivec.h>
int
compare_exponents_eq (double *exponent1_p, double *exponent2_p)
{
double exponent1 = *exponent1_p;
double exponent2 = *exponent2_p;
return scalar_cmp_exp_eq (exponent1, exponent2);
}
/* { dg-final { scan-assembler "xscmpexpdp" } } */
| 30.473684 | 94 | 0.651123 |
307dd551fa4c237c054ece445833b8b1213cc54b | 549 | h | C | CI/rule/pclint/pclint_include/include_linux/c++/4.8.2/java/io/VMObjectInputStream.h | chewaiwai/huaweicloud-sdk-c-obs | fbcd3dadd910c22af3a91aeb73ca0fee94d759fb | [
"Apache-2.0"
] | 22 | 2019-06-13T01:16:44.000Z | 2022-03-29T02:42:39.000Z | CI/rule/pclint/pclint_include/include_linux/c++/4.8.2/java/io/VMObjectInputStream.h | chewaiwai/huaweicloud-sdk-c-obs | fbcd3dadd910c22af3a91aeb73ca0fee94d759fb | [
"Apache-2.0"
] | 26 | 2019-09-20T06:46:05.000Z | 2022-03-11T08:07:14.000Z | CI/rule/pclint/pclint_include/include_linux/c++/4.8.2/java/io/VMObjectInputStream.h | chewaiwai/huaweicloud-sdk-c-obs | fbcd3dadd910c22af3a91aeb73ca0fee94d759fb | [
"Apache-2.0"
] | 14 | 2019-07-15T06:42:39.000Z | 2022-02-15T10:32:28.000Z |
// DO NOT EDIT THIS FILE - it is machine generated -*- c++ -*-
#ifndef __java_io_VMObjectInputStream__
#define __java_io_VMObjectInputStream__
#pragma interface
#include <java/lang/Object.h>
class java::io::VMObjectInputStream : public ::java::lang::Object
{
public: // actually package-private
VMObjectInputStream();
static ::java::lang::Object * allocateObject(::java::lang::Class *, ::java::lang::Class *, ::java::lang::reflect::Constructor *);
public:
static ::java::lang::Class class$;
};
#endif // __java_io_VMObjectInputStream__
| 24.954545 | 131 | 0.724954 |
cf247248e5af61cf34a6b5724f8ee10b0ff2b558 | 1,158 | h | C | src/images/fighters/enemyThree/EnemyThree_49.h | filmote/Karateka_Pokitto | 0448237eb5df93591955a1ca51ee066323cf90f3 | [
"BSD-3-Clause"
] | 1 | 2020-08-25T14:59:30.000Z | 2020-08-25T14:59:30.000Z | src/images/fighters/enemyThree/EnemyThree_49.h | filmote/Karateka_Pokitto | 0448237eb5df93591955a1ca51ee066323cf90f3 | [
"BSD-3-Clause"
] | null | null | null | src/images/fighters/enemyThree/EnemyThree_49.h | filmote/Karateka_Pokitto | 0448237eb5df93591955a1ca51ee066323cf90f3 | [
"BSD-3-Clause"
] | null | null | null | // Automatically generated file, do not edit.
#pragma once
const uint8_t EnemyThree_49[] = {
32, 13,
0xee,0xee,0xee,0xee,0xee,0xee,0xee,0xee,0xee,0x79,0x99,0x9e,0xee,0xee,0xee,0xee,
0xee,0xee,0xee,0xee,0xee,0xe7,0x99,0x99,0x00,0x99,0x99,0x99,0xee,0xee,0xee,0xee,
0xee,0xee,0xee,0xee,0xe7,0x99,0x99,0x99,0x00,0x99,0x99,0x99,0x9e,0xee,0xee,0xee,
0xee,0xee,0xee,0xee,0x79,0x99,0x99,0x90,0x09,0x99,0x99,0x99,0x99,0xee,0xee,0xee,
0xee,0xee,0xee,0xe7,0x99,0x99,0x99,0x90,0x09,0x99,0x99,0x99,0x99,0x9e,0xee,0x7e,
0xee,0xee,0xee,0x79,0x99,0x99,0x00,0x00,0x99,0x99,0x99,0x99,0x99,0xff,0x7e,0x7e,
0xee,0x7f,0x99,0x99,0x99,0x90,0x99,0x00,0x99,0x99,0x99,0x99,0x9f,0xff,0x77,0x7e,
0xe7,0xff,0x99,0x99,0x99,0x99,0x99,0x00,0x99,0x99,0x99,0x99,0x9f,0xff,0x77,0x7e,
0xe7,0xff,0x99,0x99,0x99,0x99,0x90,0x00,0x09,0x99,0x99,0x99,0xff,0xff,0x77,0x7e,
0xe7,0xf7,0x77,0x79,0x99,0x00,0x00,0x90,0x00,0x99,0x99,0x99,0xff,0xff,0x77,0x70,
0x7f,0xff,0xf9,0x99,0x99,0x99,0x99,0x99,0x00,0x99,0x99,0x99,0x99,0xff,0x77,0x70,
0x0f,0xff,0x99,0x99,0x99,0x99,0x99,0x90,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x0e,0xee,0xee,0xee,0xe0,0x00,0x00,0x00,0x0e
};
| 55.142857 | 80 | 0.782383 |
04ffa4ec230ef2dc8b4cb2d6e6c65ef07ddc1a89 | 1,868 | c | C | Lab4/code/kernel/proc.c | Software-Knowledge/2020-OS-Lab | b781583acfa9c267c17d2e642e869d569c0e01aa | [
"MIT"
] | null | null | null | Lab4/code/kernel/proc.c | Software-Knowledge/2020-OS-Lab | b781583acfa9c267c17d2e642e869d569c0e01aa | [
"MIT"
] | null | null | null | Lab4/code/kernel/proc.c | Software-Knowledge/2020-OS-Lab | b781583acfa9c267c17d2e642e869d569c0e01aa | [
"MIT"
] | 1 | 2021-01-19T14:52:26.000Z | 2021-01-19T14:52:26.000Z |
/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
proc.c
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Forrest Yu, 2005
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
#include "type.h"
#include "const.h"
#include "protect.h"
#include "proto.h"
#include "string.h"
#include "proc.h"
#include "global.h"
/*======================================================================*
sys_get_ticks
*======================================================================*/
PUBLIC int sys_get_ticks()
{
return ticks;
}
// 进程调度
PUBLIC void schedule(){
int t = 0;
while(1){
t = get_ticks();
p_proc_ready ++;
if(p_proc_ready >= proc_table + NR_TASKS){
p_proc_ready = proc_table;
}
if(p_proc_ready->waiting_semahore == 0 && p_proc_ready->ready_tick <= t){
break;
}
}
}
// 不分配时间片来切换,这部分被汇编调用
PUBLIC void sys_delay_c(int i){
p_proc_ready->ready_tick = get_ticks() + i / (1000 / HZ);
// delay则进行进程切换
schedule();
}
// 执行信号量P操作
PUBLIC void do_sys_p(SEMAPHORE* semaphore){
semaphore -> number--;
if(semaphore -> number < 0){
// 等待一个信号量
p_proc_ready->waiting_semahore = semaphore;
semaphore -> list[semaphore -> end] = p_proc_ready;
semaphore -> end = (semaphore -> end + 1) % SEMAPHORE_SIZE;
// 进行进程调度
schedule();
}
}
// 执行信号量V操作
PUBLIC void do_sys_v(SEMAPHORE* semaphore){
semaphore -> number ++;
if(semaphore -> number <= 0){
// 等待队列中的第一个进程取出来
PROCESS* p = semaphore -> list[semaphore -> start];
p -> waiting_semahore = 0;
semaphore -> start = (semaphore -> start + 1) % SEMAPHORE_SIZE;
}
}
| 26.309859 | 81 | 0.440578 |
318efd2b5f7888334a77daf1d5140c6ab42e885e | 17,435 | c | C | spu/vnc/host_io.c | raptoravis/cr19 | 4f5e7a1d44aadbb75160e64563e53c418cd330a6 | [
"MIT"
] | null | null | null | spu/vnc/host_io.c | raptoravis/cr19 | 4f5e7a1d44aadbb75160e64563e53c418cd330a6 | [
"MIT"
] | null | null | null | spu/vnc/host_io.c | raptoravis/cr19 | 4f5e7a1d44aadbb75160e64563e53c418cd330a6 | [
"MIT"
] | null | null | null | /* VNC Reflector
* Copyright (C) 2001-2003 HorizonLive.com, Inc. All rights reserved.
*
* This software is released under the terms specified in the file LICENSE,
* included. HorizonLive provides e-Learning and collaborative synchronous
* presentation solutions in a totally Web-based environment. For more
* information about HorizonLive, please see our website at
* http://www.horizonlive.com.
*
* This software was authored by Constantin Kaplinsky <const@ce.cctpu.edu.ru>
* and sponsored by HorizonLive.com, Inc.
*
* $Id: host_io.c,v 1.2 2005/08/11 20:10:33 brianp Exp $
* Asynchronous interaction with VNC host.
*/
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <zlib.h>
#include "rfblib.h"
#include "reflector.h"
#include "async_io.h"
#include "logging.h"
#include "translate.h"
#include "client_io.h"
#include "host_connect.h"
#include "host_io.h"
#include "encode.h"
static void host_really_activate(AIO_SLOT *slot);
static void fn_host_pass_newfbsize(AIO_SLOT *slot);
static void rf_host_msg(void);
static void rf_host_fbupdate_hdr(void);
static void rf_host_fbupdate_recthdr(void);
static void rf_host_fbupdate_raw(void);
static void rf_host_copyrect(void);
static void fn_host_add_client_rect(AIO_SLOT *slot);
static void rf_host_colormap_hdr(void);
static void rf_host_colormap_data(void);
static void rf_host_cuttext_hdr(void);
static void rf_host_cuttext_data(void);
static void fn_host_pass_cuttext(AIO_SLOT *slot);
static void reset_framebuffer(void);
static void request_update(int incr);
/*
* Implementation
*/
static AIO_SLOT *s_host_slot = NULL;
static AIO_SLOT *s_new_slot = NULL;
/* Prepare host I/O slot for operating in main protocol phase */
void host_activate(void)
{
if (s_host_slot == NULL) {
/* Just activate */
host_really_activate(cur_slot);
} else {
/* Let close hook do the work */
s_new_slot = cur_slot;
aio_close_other(s_host_slot, 0);
}
}
/* On-close hook */
void host_close_hook(void)
{
#ifdef CHROMIUM
CARD32 *g_framebuffer;
CARD16 g_fb_width, g_fb_height;
g_framebuffer = GetFrameBuffer(&g_fb_width, &g_fb_height);
#endif
if (cur_slot->type == TYPE_HOST_ACTIVE_SLOT) {
/* Close session file if open */
fbs_close_file();
/* Erase framebuffer contents, invalidate cache */
/* FIXME: Don't reset if there is a new connection, so the
framebuffer (of its new size) would be changed anyway? */
reset_framebuffer();
/* No active slot exist */
s_host_slot = NULL;
}
if (cur_slot->errread_f) {
if (cur_slot->io_errno) {
log_write(LL_ERROR, "Host I/O error, read: %s",
strerror(cur_slot->io_errno));
} else {
log_write(LL_ERROR, "Host I/O error, read");
}
} else if (cur_slot->errwrite_f) {
if (cur_slot->io_errno) {
log_write(LL_ERROR, "Host I/O error, write: %s",
strerror(cur_slot->io_errno));
} else {
log_write(LL_ERROR, "Host I/O error, write");
}
} else if (cur_slot->errio_f) {
log_write(LL_ERROR, "Host I/O error");
}
if (s_new_slot == NULL) {
log_write(LL_WARN, "Closing connection to host");
/* Exit event loop if framebuffer does not exist yet. */
if (g_framebuffer == NULL)
aio_close(1);
remove_active_file();
} else {
log_write(LL_INFO, "Closing previous connection to host");
host_really_activate(s_new_slot);
s_new_slot = NULL;
}
}
static void host_really_activate(AIO_SLOT *slot)
{
AIO_SLOT *saved_slot = cur_slot;
HOST_SLOT *hs = (HOST_SLOT *)slot;
log_write(LL_MSG, "Activating new host connection");
slot->type = TYPE_HOST_ACTIVE_SLOT;
s_host_slot = slot;
write_active_file();
perform_action("host_activate");
/* Allocate the framebuffer or extend its dimensions if necessary */
if (!alloc_framebuffer(hs->fb_width, hs->fb_height)) {
aio_close(1);
return;
}
/* Set default desktop geometry for new client connections */
g_screen_info.width = hs->fb_width;
g_screen_info.height = hs->fb_height;
/* If requested, open file to save this session and write the header */
fbs_open_file(hs->fb_width, hs->fb_height);
cur_slot = slot;
/* Reset zlib streams in the Tight decoder */
reset_tight_streams();
/* Request initial screen contents */
log_write(LL_DETAIL, "Requesting full framebuffer update");
request_update(0);
aio_setread(rf_host_msg, NULL, 1);
/* Notify clients about desktop geometry change */
aio_walk_slots(fn_host_pass_newfbsize, TYPE_CL_SLOT);
cur_slot = saved_slot;
}
/*
* Inform a client about new desktop geometry.
*/
static void fn_host_pass_newfbsize(AIO_SLOT *slot)
{
HOST_SLOT *hs = (HOST_SLOT *)cur_slot;
FB_RECT r;
r.enc = RFB_ENCODING_NEWFBSIZE;
r.x = r.y = 0;
r.w = hs->fb_width;
r.h = hs->fb_height;
fn_client_add_rect(slot, &r);
}
/***************************/
/* Processing RFB messages */
/***************************/
static void rf_host_msg(void)
{
int msg_id;
msg_id = (int)cur_slot->readbuf[0] & 0xFF;
switch(msg_id) {
case rfbFramebufferUpdate:
aio_setread(rf_host_fbupdate_hdr, NULL, 3);
break;
case rfbSetColourMapEntries:
aio_setread(rf_host_colormap_hdr, NULL, 5);
break;
case rfbBell:
log_write(LL_DETAIL, "Received Bell message from host");
fbs_write_data(cur_slot->readbuf, 1);
aio_setread(rf_host_msg, NULL, 1);
break;
case rfbServerCutText:
aio_setread(rf_host_cuttext_hdr, NULL, 7);
break;
default:
log_write(LL_ERROR, "Unknown server message type: %d", msg_id);
aio_close(0);
}
}
/********************************/
/* Handling framebuffer updates */
/********************************/
/* FIXME: Add state variables to the AIO_SLOT structure clone. */
static CARD16 rect_count;
static FB_RECT cur_rect;
static CARD16 rect_cur_row;
/**
* Called when we get a rfbFramebufferUpdate message.
*/
static void rf_host_fbupdate_hdr(void)
{
CARD8 hdr_buf[4];
rect_count = buf_get_CARD16(&cur_slot->readbuf[1]);
if (rect_count == 0xFFFF) {
log_write(LL_DETAIL, "Receiving framebuffer update");
} else {
log_write(LL_DETAIL, "Receiving framebuffer update, %d rectangle(s)",
rect_count);
}
hdr_buf[0] = 0;
memcpy(&hdr_buf[1], cur_slot->readbuf, 3);
fbs_spool_data(hdr_buf, 4);
if (rect_count) {
aio_setread(rf_host_fbupdate_recthdr, NULL, 12);
} else {
log_write(LL_DEBUG, "Requesting incremental framebuffer update");
request_update(1);
aio_setread(rf_host_msg, NULL, 1);
}
}
static void rf_host_fbupdate_recthdr(void)
{
HOST_SLOT *hs = (HOST_SLOT *)cur_slot;
#ifdef CHROMIUM
CARD32 *g_framebuffer;
CARD16 g_fb_width, g_fb_height;
g_framebuffer = GetFrameBuffer(&g_fb_width, &g_fb_height);
#endif
cur_rect.x = buf_get_CARD16(cur_slot->readbuf);
cur_rect.y = buf_get_CARD16(&cur_slot->readbuf[2]);
cur_rect.w = buf_get_CARD16(&cur_slot->readbuf[4]);
cur_rect.h = buf_get_CARD16(&cur_slot->readbuf[6]);
cur_rect.enc = buf_get_CARD32(&cur_slot->readbuf[8]);
fbs_spool_data(cur_slot->readbuf, 12);
/* Handle LastRect "encoding" first */
if (cur_rect.enc == RFB_ENCODING_LASTRECT) {
log_write(LL_DEBUG, "LastRect marker received from the host");
cur_rect.x = cur_rect.y = 0;
rect_count = 1;
fbupdate_rect_done();
return;
}
/* Ignore zero-size rectangles */
if (cur_rect.h == 0 || cur_rect.w == 0) {
log_write(LL_WARN, "Zero-size rectangle %dx%d at %d,%d (ignoring)",
(int)cur_rect.w, (int)cur_rect.h,
(int)cur_rect.x, (int)cur_rect.y);
fbupdate_rect_done();
return;
}
/* Handle NewFBSize "encoding", as a special case */
if (cur_rect.enc == RFB_ENCODING_NEWFBSIZE) {
log_write(LL_INFO, "New host desktop geometry: %dx%d",
(int)cur_rect.w, (int)cur_rect.h);
g_screen_info.width = hs->fb_width = cur_rect.w;
g_screen_info.height = hs->fb_height = cur_rect.h;
/* Reallocate the framebuffer if necessary */
if (!alloc_framebuffer(hs->fb_width, hs->fb_height)) {
aio_close(1);
return;
}
cur_rect.x = cur_rect.y = 0;
/* NewFBSize is always the last rectangle regardless of rect_count */
rect_count = 1;
fbupdate_rect_done();
return;
}
/* Prevent overflow of the framebuffer */
if (cur_rect.x >= g_fb_width || cur_rect.x + cur_rect.w > g_fb_width ||
cur_rect.y >= g_fb_height || cur_rect.y + cur_rect.h > g_fb_height) {
log_write(LL_ERROR, "Rectangle out of framebuffer bounds: %dx%d at %d,%d",
(int)cur_rect.w, (int)cur_rect.h,
(int)cur_rect.x, (int)cur_rect.y);
aio_close(0);
return;
}
/* Ok, now the rectangle seems correct */
log_write(LL_DEBUG, "Receiving rectangle %dx%d at %d,%d",
(int)cur_rect.w, (int)cur_rect.h,
(int)cur_rect.x, (int)cur_rect.y);
switch(cur_rect.enc) {
case RFB_ENCODING_RAW:
log_write(LL_DEBUG, "Receiving raw data, expecting %d byte(s)",
cur_rect.w * cur_rect.h * sizeof(CARD32));
rect_cur_row = 0;
aio_setread(rf_host_fbupdate_raw,
&g_framebuffer[cur_rect.y * (int)g_fb_width +
cur_rect.x],
cur_rect.w * sizeof(CARD32));
break;
case RFB_ENCODING_COPYRECT:
log_write(LL_DEBUG, "Receiving CopyRect instruction");
aio_setread(rf_host_copyrect, NULL, 4);
break;
case RFB_ENCODING_HEXTILE:
log_write(LL_DEBUG, "Receiving Hextile-encoded data");
setread_decode_hextile(&cur_rect);
break;
case RFB_ENCODING_TIGHT:
log_write(LL_DEBUG, "Receiving Tight-encoded data");
setread_decode_tight(&cur_rect);
break;
default:
log_write(LL_ERROR, "Unknown encoding: 0x%08lX",
(unsigned long)cur_rect.enc);
aio_close(0);
}
}
static void rf_host_fbupdate_raw(void)
{
int idx;
#ifdef CHROMIUM
CARD32 *g_framebuffer;
CARD16 g_fb_width, g_fb_height;
g_framebuffer = GetFrameBuffer(&g_fb_width, &g_fb_height);
#endif
fbs_spool_data(cur_slot->readbuf, cur_rect.w * sizeof(CARD32));
if (++rect_cur_row < cur_rect.h) {
/* Read next row */
idx = (cur_rect.y + rect_cur_row) * (int)g_fb_width + cur_rect.x;
aio_setread(rf_host_fbupdate_raw, &g_framebuffer[idx],
cur_rect.w * sizeof(CARD32));
} else {
/* Done with this rectangle */
fbupdate_rect_done();
}
}
static void rf_host_copyrect(void)
{
CARD32 *src_ptr;
CARD32 *dst_ptr;
int width/* = (int)g_fb_width*/;
int row;
#ifdef CHROMIUM
CARD32 *g_framebuffer;
CARD16 g_fb_width, g_fb_height;
g_framebuffer = GetFrameBuffer(&g_fb_width, &g_fb_height);
width = g_fb_width;
#endif
fbs_spool_data(cur_slot->readbuf, 4);
cur_rect.src_x = buf_get_CARD16(cur_slot->readbuf);
cur_rect.src_y = buf_get_CARD16(&cur_slot->readbuf[2]);
if ( cur_rect.src_x >= g_fb_width ||
cur_rect.src_x + cur_rect.w > g_fb_width ||
cur_rect.src_y >= g_fb_height ||
cur_rect.src_y + cur_rect.h > g_fb_height ) {
log_write(LL_ERROR,
"CopyRect from outside of the framebuffer: %dx%d from %d,%d",
(int)cur_rect.w, (int)cur_rect.h,
(int)cur_rect.src_x, (int)cur_rect.src_y);
aio_close(0);
return;
}
if (cur_rect.src_y > cur_rect.y) {
/* Copy rows starting from top */
src_ptr = &g_framebuffer[cur_rect.src_y * width + cur_rect.src_x];
dst_ptr = &g_framebuffer[cur_rect.y * width + cur_rect.x];
for (row = 0; row < cur_rect.h; row++) {
memmove(dst_ptr, src_ptr, cur_rect.w * sizeof(CARD32));
src_ptr += width;
dst_ptr += width;
}
} else {
/* Copy rows starting from bottom */
src_ptr = &g_framebuffer[(cur_rect.src_y + cur_rect.h - 1) * width +
cur_rect.src_x];
dst_ptr = &g_framebuffer[(cur_rect.y + cur_rect.h - 1) * width +
cur_rect.x];
for (row = 0; row < cur_rect.h; row++) {
memmove(dst_ptr, src_ptr, cur_rect.w * sizeof(CARD32));
src_ptr -= width;
dst_ptr -= width;
}
}
fbupdate_rect_done();
}
/********************************/
/* Functions called by decoders */
/********************************/
/*
* In the framebuffer, fill a rectangle with a specified color.
*/
void fill_fb_rect(FB_RECT *r, CARD32 color)
{
int x, y;
CARD32 *fb_ptr;
#ifdef CHROMIUM
CARD32 *g_framebuffer;
CARD16 g_fb_width, g_fb_height;
g_framebuffer = GetFrameBuffer(&g_fb_width, &g_fb_height);
#endif
fb_ptr = &g_framebuffer[r->y * (int)g_fb_width + r->x];
/* Fill the first row */
for (x = 0; x < r->w; x++)
fb_ptr[x] = color;
/* Copy the first row into all other rows */
for (y = 1; y < r->h; y++)
memcpy(&fb_ptr[y * g_fb_width], fb_ptr, r->w * sizeof(CARD32));
}
/*
* This function is called by decoders after the whole rectangle
* has been successfully decoded.
*/
void fbupdate_rect_done(void)
{
if (cur_rect.w != 0 && cur_rect.h != 0) {
log_write(LL_DEBUG, "Received rectangle ok");
/* Cached data for this rectangle is not valid any more */
invalidate_enc_cache(&cur_rect);
/* Save data in a file if necessary */
fbs_flush_data();
/* Queue this rectangle for each client */
aio_walk_slots(fn_host_add_client_rect, TYPE_CL_SLOT);
}
if (--rect_count) {
aio_setread(rf_host_fbupdate_recthdr, NULL, 12);
} else {
/* Done with the whole update */
aio_walk_slots(fn_client_send_rects, TYPE_CL_SLOT);
log_write(LL_DEBUG, "Requesting incremental framebuffer update");
request_update(1);
aio_setread(rf_host_msg, NULL, 1);
}
}
static void fn_host_add_client_rect(AIO_SLOT *slot)
{
fn_client_add_rect(slot, &cur_rect);
}
/*****************************************/
/* Handling SetColourMapEntries messages */
/*****************************************/
static void rf_host_colormap_hdr(void)
{
CARD16 num_colors;
log_write(LL_WARN, "Ignoring SetColourMapEntries message");
num_colors = buf_get_CARD16(&cur_slot->readbuf[3]);
if (num_colors > 0)
aio_setread(rf_host_colormap_data, NULL, num_colors * 6);
else
aio_setread(rf_host_msg, NULL, 1);
}
static void rf_host_colormap_data(void)
{
/* Nothing to do with colormap */
aio_setread(rf_host_msg, NULL, 1);
}
/***********************************/
/* Handling ServerCutText messages */
/***********************************/
/* FIXME: Add state variables to the AIO_SLOT structure clone. */
static size_t cut_len;
static CARD8 *cut_text;
static void rf_host_cuttext_hdr(void)
{
log_write(LL_DETAIL,
"Receiving ServerCutText message from host, %lu byte(s)",
(unsigned long)cut_len);
cut_len = (size_t)buf_get_CARD32(&cur_slot->readbuf[3]);
if (cut_len > 0)
aio_setread(rf_host_cuttext_data, NULL, cut_len);
else
rf_host_cuttext_data();
}
static void rf_host_cuttext_data(void)
{
cut_text = cur_slot->readbuf;
aio_walk_slots(fn_host_pass_cuttext, TYPE_CL_SLOT);
aio_setread(rf_host_msg, NULL, 1);
}
static void fn_host_pass_cuttext(AIO_SLOT *slot)
{
fn_client_send_cuttext(slot, cut_text, cut_len);
}
/*************************************/
/* Functions called from client_io.c */
/*************************************/
/* FIXME: Function naming. Have to invent consistent naming rules. */
void pass_msg_to_host(CARD8 *msg, size_t len)
{
AIO_SLOT *saved_slot = cur_slot;
if (s_host_slot != NULL) {
cur_slot = s_host_slot;
aio_write(NULL, msg, len);
cur_slot = saved_slot;
}
}
void pass_cuttext_to_host(CARD8 *text, size_t len)
{
AIO_SLOT *saved_slot = cur_slot;
CARD8 client_cuttext_hdr[8] = {
6, 0, 0, 0, 0, 0, 0, 0
};
if (s_host_slot != NULL) {
buf_put_CARD32(&client_cuttext_hdr[4], (CARD32)len);
cur_slot = s_host_slot;
aio_write(NULL, client_cuttext_hdr, sizeof(client_cuttext_hdr));
aio_write(NULL, text, len);
cur_slot = saved_slot;
}
}
/********************/
/* Helper functions */
/********************/
/*
* Clear the framebuffer, invalidate hextile cache.
*/
static void reset_framebuffer(void)
{
HOST_SLOT *hs = (HOST_SLOT *)cur_slot;
FB_RECT r;
#ifdef CHROMIUM
CARD32 *g_framebuffer;
CARD16 g_fb_width, g_fb_height;
g_framebuffer = GetFrameBuffer(&g_fb_width, &g_fb_height);
#else
log_write(LL_DETAIL, "Clearing framebuffer and cache");
memset(g_framebuffer, 0, g_fb_width * g_fb_height * sizeof(CARD32));
#endif
r.x = r.y = 0;
r.w = g_fb_width;
r.h = g_fb_height;
invalidate_enc_cache(&r);
/* Queue changed rectangle (the whole host screen) for each client */
r.w = hs->fb_width;
r.h = hs->fb_height;
aio_walk_slots(fn_host_add_client_rect, TYPE_CL_SLOT);
}
/*
* Send a FramebufferUpdateRequest for the whole screen
*/
static void request_update(int incr)
{
HOST_SLOT *hs = (HOST_SLOT *)cur_slot;
unsigned char fbupdatereq_msg[] = {
3, /* Message id */
0, /* Incremental if 1 */
0, 0, 0, 0, /* X position, Y position */
0, 0, 0, 0 /* Width, height */
};
fbupdatereq_msg[1] = (incr) ? 1 : 0;
buf_put_CARD16(&fbupdatereq_msg[6], hs->fb_width);
buf_put_CARD16(&fbupdatereq_msg[8], hs->fb_height);
log_write(LL_DEBUG, "Sending FramebufferUpdateRequest message");
aio_write(NULL, fbupdatereq_msg, sizeof(fbupdatereq_msg));
}
| 27.031008 | 78 | 0.659019 |
ab54d88cfa5225c48f3ec627c0cb4b984caccf23 | 927 | h | C | stage2/03-install-piaizu/files/fb/lib/bmp.h | TE-KarlKomierowski/pi-gen-ar-module | 19a36e5d22c8b18d73445c516b24bc6508224c28 | [
"BSD-3-Clause"
] | 4 | 2020-07-06T11:34:05.000Z | 2021-01-03T03:57:25.000Z | stage2/03-install-piaizu/files/fb/lib/bmp.h | TE-KarlKomierowski/pi-gen-ar-module | 19a36e5d22c8b18d73445c516b24bc6508224c28 | [
"BSD-3-Clause"
] | 1 | 2020-11-02T20:43:43.000Z | 2020-11-03T07:09:20.000Z | stage2/03-install-piaizu/files/fb/lib/bmp.h | TE-KarlKomierowski/pi-gen-ar-module | 19a36e5d22c8b18d73445c516b24bc6508224c28 | [
"BSD-3-Clause"
] | 4 | 2020-01-03T08:56:10.000Z | 2020-09-22T11:22:32.000Z | #pragma once
#include "container.h"
/**
*
* @param file filename to open, like logo.bmp
* @param bitmap bitmap that later can be used in a container
* @return Returns 0 on success, -1 on failure.
*
* Opens a .bmp file, decodes it and creates a gimp_bitmap_t bitmap
* that can be printed in a container.
*/
int bmp_open(const char *file, gimp_bitmap_t **bitmap);
/**
* @param path path to file
* @param file filename to open, like logo.bmp
* @param bitmap bitmap that later can be used in a container
* @return Returns 0 on success, -1 on failure.
*
* Opens a .bmp file, decodes it and creates a gimp_bitmap_t bitmap
* that can be printed in a container.
*/
int bmp_open_path(const char *path, const char *file, gimp_bitmap_t **bitmap);
/**
*
* @param bitmap bitmap to destroy and free
*
* Frees the bitmap and sets the pointer to null.
*/
void bmp_free(gimp_bitmap_t **bitmap);
| 28.090909 | 78 | 0.68932 |
396a55b8cda203d4995435d30088d8268e35e502 | 4,662 | h | C | games/2048/policies.h | Lenzebo/mcts_solver | c434a3024fb7b37ef9e7a4fb12985fb89110a350 | [
"MIT"
] | null | null | null | games/2048/policies.h | Lenzebo/mcts_solver | c434a3024fb7b37ef9e7a4fb12985fb89110a350 | [
"MIT"
] | null | null | null | games/2048/policies.h | Lenzebo/mcts_solver | c434a3024fb7b37ef9e7a4fb12985fb89110a350 | [
"MIT"
] | null | null | null | // MIT License
//
// Copyright (c) 2020 Lenzebo
//
// 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.
#pragma once
#include "2048.h"
#include "mcts/rollout/random_rollout.h"
namespace g2048 {
class FixedSequencePolicy
{
public:
static constexpr std::array<g2048::Actions, 4> ORDERING = {g2048::Actions::DOWN, g2048::Actions::RIGHT,
g2048::Actions::UP, g2048::Actions::LEFT};
[[nodiscard]] Actions getAction(const g2048::G2048State& state, const g2048::G2048Problem& problem) const;
private:
[[nodiscard]] g2048::Actions getAction(const zbo::MaxSizeVector<g2048::Actions, 4>& availableActions) const;
};
class BestPositionPolicy
{
public:
[[nodiscard]] Actions getAction(const g2048::G2048State& state, const g2048::G2048Problem& problem) const;
private:
struct Point
{
uint8_t x;
uint8_t y;
};
std::vector<std::vector<Point>> paths_;
[[nodiscard]] float getPositionalScore(const g2048::G2048State& state) const;
[[nodiscard]] float getOrderingScore(const g2048::G2048State& state) const;
[[nodiscard]] float getDifferenceScore(const g2048::G2048State& state) const;
[[nodiscard]] float getEmptyFieldsScore(const g2048::G2048State& state) const;
[[nodiscard]] float getCornerHighestScore(const g2048::G2048State& state) const;
[[nodiscard]] float getOrderingScoreAlongPath(const g2048::G2048State& state, const std::vector<Point>& path) const;
};
template <class Solver>
class MCTSPolicy
{
public:
MCTSPolicy(Solver& solver) : solver_(&solver) {}
[[nodiscard]] Actions getAction(const g2048::G2048State& state, const g2048::G2048Problem& problem) const
{
// try to find state in existing tree
const auto& tree = solver_->tree();
auto node = std::find_if(tree.begin(), tree.end(), [&state](const auto& node) { return node.state == state; });
if (node != tree.end())
{
auto action = solver_->runFromExistingTree(node->nodeId);
// solver_->printTopLevelUtilities();
return action;
}
return solver_->run(problem, state);
}
private:
Solver* solver_;
};
class MCRolloutPolicy : public mcts::RandomRolloutPolicy
{
public:
// NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)
MCRolloutPolicy(size_t iterations = 100, size_t depth = 100, const float discount = 0.99f)
: mcts::RandomRolloutPolicy(depth, discount)
{
iterations_ = iterations;
}
[[nodiscard]] float rolloutMultiple(const g2048::G2048State state, const g2048::G2048Problem& game)
{
float avg = 0;
for (size_t i = 0; i < iterations_; ++i) { avg += rollout(state, game); }
return avg / iterations_;
}
[[nodiscard]] g2048::Actions getAction(g2048::G2048State state, const g2048::G2048Problem& game)
{
auto actions = game.getAvailableActions(state);
g2048::Actions bestAction = actions[0];
float bestValue = 0;
for (auto action : actions)
{
g2048::G2048State cs = state;
auto val = game.performAction(action, cs);
if (!cs.isChanceNext())
{
// action didn't do anything, so we skip it
continue;
}
float value = val + rolloutMultiple(cs, game);
if (value > bestValue)
{
bestAction = action;
bestValue = value;
}
}
return bestAction;
}
private:
size_t iterations_;
};
} // namespace g2048 | 35.587786 | 120 | 0.655298 |
615f869a6de96eadb679b76aea0269938bd878e0 | 1,244 | h | C | linux-4.14.90-dev/linux-4.14.90/arch/cris/include/arch-v32/arch/hwregs/iop/asm/iop_reg_space_asm.h | bingchunjin/1806_SDK | d5ed0258fc22f60e00ec025b802d175f33da6e41 | [
"MIT"
] | 34 | 2019-07-19T20:44:15.000Z | 2022-03-07T12:09:00.000Z | linux-4.14.90-dev/linux-4.14.90/arch/cris/include/arch-v32/arch/hwregs/iop/asm/iop_reg_space_asm.h | bingchunjin/1806_SDK | d5ed0258fc22f60e00ec025b802d175f33da6e41 | [
"MIT"
] | 3 | 2021-09-06T09:14:42.000Z | 2022-03-27T08:09:54.000Z | linux-4.14.90-dev/linux-4.14.90/arch/cris/include/arch-v32/arch/hwregs/iop/asm/iop_reg_space_asm.h | bingchunjin/1806_SDK | d5ed0258fc22f60e00ec025b802d175f33da6e41 | [
"MIT"
] | 20 | 2021-10-22T02:21:23.000Z | 2022-03-31T04:55:35.000Z | /* SPDX-License-Identifier: GPL-2.0 */
/* Autogenerated Changes here will be lost!
* generated by ../gen_sw.pl Mon Apr 11 16:10:18 2005 iop_sw.cfg
*/
#define iop_version 0
#define iop_fifo_in0_extra 64
#define iop_fifo_in1_extra 128
#define iop_fifo_out0_extra 192
#define iop_fifo_out1_extra 256
#define iop_trigger_grp0 320
#define iop_trigger_grp1 384
#define iop_trigger_grp2 448
#define iop_trigger_grp3 512
#define iop_trigger_grp4 576
#define iop_trigger_grp5 640
#define iop_trigger_grp6 704
#define iop_trigger_grp7 768
#define iop_crc_par0 896
#define iop_crc_par1 1024
#define iop_dmc_in0 1152
#define iop_dmc_in1 1280
#define iop_dmc_out0 1408
#define iop_dmc_out1 1536
#define iop_fifo_in0 1664
#define iop_fifo_in1 1792
#define iop_fifo_out0 1920
#define iop_fifo_out1 2048
#define iop_scrc_in0 2176
#define iop_scrc_in1 2304
#define iop_scrc_out0 2432
#define iop_scrc_out1 2560
#define iop_timer_grp0 2688
#define iop_timer_grp1 2816
#define iop_timer_grp2 2944
#define iop_timer_grp3 3072
#define iop_sap_in 3328
#define iop_sap_out 3584
#define iop_spu0 3840
#define iop_spu1 4096
#define iop_sw_cfg 4352
#define iop_sw_cpu 4608
#define iop_sw_mpu 4864
#define iop_sw_spu0 5120
#define iop_sw_spu1 5376
#define iop_mpu 5632
| 27.043478 | 64 | 0.83119 |
e813c175301341abff00f6b2b2782cb8d35294ac | 725 | h | C | zircon/kernel/arch/x86/include/arch/x86/user_copy.h | OpenTrustGroup/fuchsia | 647e593ea661b8bf98dcad2096e20e8950b24a97 | [
"BSD-3-Clause"
] | 1 | 2019-04-21T18:02:26.000Z | 2019-04-21T18:02:26.000Z | zircon/kernel/arch/x86/include/arch/x86/user_copy.h | OpenTrustGroup/fuchsia | 647e593ea661b8bf98dcad2096e20e8950b24a97 | [
"BSD-3-Clause"
] | 16 | 2020-09-04T19:01:11.000Z | 2021-05-28T03:23:09.000Z | zircon/kernel/arch/x86/include/arch/x86/user_copy.h | OpenTrustGroup/fuchsia | 647e593ea661b8bf98dcad2096e20e8950b24a97 | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2016 The Fuchsia Authors
//
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file or at
// https://opensource.org/licenses/MIT
#ifndef ZIRCON_KERNEL_ARCH_X86_INCLUDE_ARCH_X86_USER_COPY_H_
#define ZIRCON_KERNEL_ARCH_X86_INCLUDE_ARCH_X86_USER_COPY_H_
#include <zircon/compiler.h>
#include <zircon/types.h>
__BEGIN_CDECLS
/* This function is used by arch_copy_from_user() and arch_copy_to_user().
* It should not be called anywhere except in the x86 usercopy
* implementation. */
zx_status_t _x86_copy_to_or_from_user(void *dst, const void *src, size_t len, void **fault_return);
__END_CDECLS
#endif // ZIRCON_KERNEL_ARCH_X86_INCLUDE_ARCH_X86_USER_COPY_H_
| 30.208333 | 99 | 0.802759 |
95a60e200ad3ed8adb304ecafc50c600be56e90b | 595 | h | C | node_modules/react-native-chart/RNChartAxisView.h | leechuanjun/TLReactNativeResearch | 25fa76e4f206060287d2a2a2079c4bbed1d61ebf | [
"MIT"
] | null | null | null | node_modules/react-native-chart/RNChartAxisView.h | leechuanjun/TLReactNativeResearch | 25fa76e4f206060287d2a2a2079c4bbed1d61ebf | [
"MIT"
] | null | null | null | node_modules/react-native-chart/RNChartAxisView.h | leechuanjun/TLReactNativeResearch | 25fa76e4f206060287d2a2a2079c4bbed1d61ebf | [
"MIT"
] | null | null | null | //
// RNChartPlotAxisView.h
// RNChart
//
// Created by Hyun Cho on 4/30/15.
// Copyright (c) 2015 Facebook. All rights reserved.
//
#import <UIKit/UIKit.h>
typedef NS_ENUM(NSInteger, AxisType) {
AxisTypeNone,
AxisTypeX,
AxisTypeY,
};
@class RNChartView;
@interface RNChartAxisView : UIView
- (id)initWithParent:(RNChartView*)parent axis:(AxisType)axis;
- (void)addLabels;
@property (nonatomic, weak) RNChartView* parentChartView;
@property (nonatomic, assign) AxisType axis;
@property (nonatomic, strong) UIFont* labelFont;
@property (nonatomic, strong) UIColor* labelTextColor;
@end
| 19.833333 | 62 | 0.742857 |
d758f46a4330977dd7cd3a667ede8f8998ef6614 | 2,359 | c | C | openair1/PHY/TOOLS/dfts_load.c | shadansari/onos-cu-cp | 16cbf4828bd11e4c7319e7a009a26b6f39fde628 | [
"Apache-2.0"
] | 6 | 2019-12-27T00:55:47.000Z | 2021-11-16T11:36:20.000Z | openair1/PHY/TOOLS/dfts_load.c | shadansari/onos-cu-cp | 16cbf4828bd11e4c7319e7a009a26b6f39fde628 | [
"Apache-2.0"
] | 2 | 2021-06-17T05:01:55.000Z | 2021-11-24T14:23:54.000Z | openair1/PHY/TOOLS/dfts_load.c | shadansari/onos-cu-cp | 16cbf4828bd11e4c7319e7a009a26b6f39fde628 | [
"Apache-2.0"
] | 15 | 2019-12-27T00:55:51.000Z | 2022-03-28T02:13:45.000Z | /*
* Licensed to the OpenAirInterface (OAI) Software Alliance under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The OpenAirInterface Software Alliance licenses this file to You under
* the OAI Public License, Version 1.1 (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.openairinterface.org/?page_id=698
*
* 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.
*-------------------------------------------------------------------------------
* For more information about the OpenAirInterface (OAI) Software Alliance:
* contact@openairinterface.org
*/
/*! \file openair1/PHY/CODING/coding_nr_load.c
* \brief: load library implementing coding/decoding algorithms
* \author Francois TABURET
* \date 2020
* \version 0.1
* \company NOKIA BellLabs France
* \email: francois.taburet@nokia-bell-labs.com
* \note
* \warning
*/
#define _GNU_SOURCE
#include <sys/types.h>
#include <stdlib.h>
#include <malloc.h>
#include "assertions.h"
#include "common/utils/LOG/log.h"
#define OAIDFTS_LOADER
#include "tools_defs.h"
#include "common/config/config_userapi.h"
#include "common/utils/load_module_shlib.h"
/* function description array, to be used when loading the dfts/idfts lib */
static loader_shlibfunc_t shlib_fdesc[2];
static char *arg[64]={"phytest","-O","cmdlineonly::dbgl0"};
int load_dftslib(void) {
char *ptr = (char*)config_get_if();
if ( ptr==NULL ) {// phy simulators, config module possibly not loaded
load_configmodule(3,(char **)arg,CONFIG_ENABLECMDLINEONLY) ;
logInit();
}
shlib_fdesc[0].fname = "dft";
shlib_fdesc[1].fname = "idft";
int ret=load_module_shlib("dfts",shlib_fdesc,sizeof(shlib_fdesc)/sizeof(loader_shlibfunc_t),NULL);
AssertFatal( (ret >= 0),"Error loading dftsc decoder");
dft = (dftfunc_t)shlib_fdesc[0].fptr;
idft = (idftfunc_t)shlib_fdesc[1].fptr;
return 0;
}
| 35.742424 | 103 | 0.703264 |
ba45140cf4c7c381acbfc96d65e1f35a99b04d4d | 1,076 | h | C | 0748-Shortest-Completing-Word/cpp_0748/Solution1.h | ooooo-youwillsee/leetcode | 07b273f133c8cf755ea40b3ae9df242ce044823c | [
"MIT"
] | 12 | 2020-03-18T14:36:23.000Z | 2021-12-19T02:24:33.000Z | 0748-Shortest-Completing-Word/cpp_0748/Solution1.h | ooooo-youwillsee/leetcode | 07b273f133c8cf755ea40b3ae9df242ce044823c | [
"MIT"
] | null | null | null | 0748-Shortest-Completing-Word/cpp_0748/Solution1.h | ooooo-youwillsee/leetcode | 07b273f133c8cf755ea40b3ae9df242ce044823c | [
"MIT"
] | null | null | null | //
// Created by ooooo on 2020/1/14.
//
#ifndef CPP_0748__SOLUTION1_H_
#define CPP_0748__SOLUTION1_H_
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
class Solution {
public:
bool check(string word, unordered_map<char, int> &m) {
unordered_map<char, int> wordMap;
for (const auto &c: word) wordMap[c]++;
for (const auto &entry :m) {
if (entry.second > wordMap[entry.first]) return false;
}
return true;
}
string shortestCompletingWord(string licensePlate, vector<string> &words) {
unordered_map<char, int> m;
for (const auto &item: licensePlate) {
char c = tolower(item);
if (c >= 'a' && c <= 'z') m[c]++;
}
int index = INT_MAX;
string ans = "";
for (int i = 0; i < words.size(); ++i) {
if (check(words[i], m)) {
if (ans.empty() || words[i].size() < ans.size()
|| (words[i].size() == ans.size() && i < index)) {
ans = words[i];
index = i;
}
}
}
return ans;
}
};
#endif //CPP_0748__SOLUTION1_H_
| 22.416667 | 77 | 0.574349 |
67b6d08e7f188d0aeb6b458ebfd504894169c1df | 1,212 | h | C | src/pragma/graphics/Material.h | vicutrinu/pragma-studios | 181fd14d072ccbb169fa786648dd942a3195d65a | [
"MIT"
] | null | null | null | src/pragma/graphics/Material.h | vicutrinu/pragma-studios | 181fd14d072ccbb169fa786648dd942a3195d65a | [
"MIT"
] | null | null | null | src/pragma/graphics/Material.h | vicutrinu/pragma-studios | 181fd14d072ccbb169fa786648dd942a3195d65a | [
"MIT"
] | null | null | null | #pragma once
#include <pragma/graphics/types.h>
#include <string>
#include <vector>
namespace pragma
{
class Material
{
public:
enum EType
{
eSolid = 0,
eReflect,
eRefract,
};
public:
Material (const char* aName, EType aType);
const std::string& GetName () const { return mName; }
bool HasDiffuse () const;
void SetDiffuseColor ( const Color& aColor ) { mDiffuseColor = aColor; }
const Color GetdiffuseColor () const { return mDiffuseColor; }
bool HasSpecular () const;
void SetSpecularColor( const Color& aColor ) { mSpecularColor = aColor; }
const Color GetSpecularColor() const { return mSpecularColor; }
EType GetType () const { return mType; }
private:
std::string mName;
EType mType;
Color mDiffuseColor;
Color mSpecularColor;
};
class MaterialLibrary
{
public:
MaterialLibrary ( size_t aMaxMaterials );
int AddMaterial ( const Material& aMaterial );
const Material& GetMaterial ( int aIndex ) const;
int GetMaterialIndex( const char* aName ) const;
private:
size_t mMaxMaterials;
std::vector<Material> mMaterials;
};
}
| 20.896552 | 79 | 0.638614 |
84662da1fe3dd3d5889c7f2828d9ff5d56e558c1 | 1,789 | c | C | server/src/api/handle_edit_chat.c | High-Voltaged/Ucode-Uchat | ce61241af5c518e8e60b7e016bcc90e01d0c9252 | [
"MIT"
] | null | null | null | server/src/api/handle_edit_chat.c | High-Voltaged/Ucode-Uchat | ce61241af5c518e8e60b7e016bcc90e01d0c9252 | [
"MIT"
] | null | null | null | server/src/api/handle_edit_chat.c | High-Voltaged/Ucode-Uchat | ce61241af5c518e8e60b7e016bcc90e01d0c9252 | [
"MIT"
] | null | null | null | #include "../../inc/server.h"
t_response_code db_modify_chat_name(int chat_id, const char* new_name) {
int chat_id_for_check = db_get_chat_id_by_name(new_name);
if (chat_id_for_check != -1) {
return R_CHAT_EXISTS;
}
char query[QUERY_LEN];
sprintf(query, "UPDATE `chats` SET `name` = '%s' WHERE `id` = '%d'", new_name, chat_id);
if (db_execute_query(query) != 0) {
return R_DB_FAILURE;
}
return R_SUCCESS;
}
void handle_edit_chat(const cJSON* chat_info, t_server_utils* utils) {
if (database_init() != 0) {
send_server_response(utils->ssl, R_DB_FAILURE, REQ_EDIT_CHAT);
return;
}
const cJSON *chat_id = cJSON_GetObjectItemCaseSensitive(chat_info, "chat_id");
const cJSON *new_name = cJSON_GetObjectItemCaseSensitive(chat_info, "chat_name");
if (!cJSON_IsString(new_name) || !cJSON_IsNumber(chat_id)) {
send_server_response(utils->ssl, R_JSON_FAILURE, REQ_EDIT_CHAT);
return;
}
if (!db_chat_exists(chat_id->valueint)) {
send_server_response(utils->ssl, R_CHAT_NOENT, REQ_EDIT_CHAT);
return;
}
if (!is_strlen_valid(new_name->valuestring, MIN_NAME_INPUT_LEN, MAX_NAME_INPUT_LEN)) {
send_server_response(utils->ssl, R_NAME_LEN_INVALID, REQ_EDIT_CHAT);
return;
}
if (!is_user_name_format_valid(new_name->valuestring)) {
send_server_response(utils->ssl, R_NAME_FORMAT_INVALID, REQ_EDIT_CHAT);
return;
}
t_response_code resp_code = 0;
if ((resp_code = db_modify_chat_name(chat_id->valueint, new_name->valuestring)) != R_SUCCESS) {
send_server_response(utils->ssl, resp_code, REQ_EDIT_CHAT);
return;
}
send_server_response(utils->ssl, R_SUCCESS, REQ_EDIT_CHAT);
}
| 30.844828 | 99 | 0.678032 |
3bb40ec8a6286e51d04e8e9b40fe66c31defb84a | 905 | h | C | include/sys/types.h | MrBad/cosiris | 2bb52efd58e705d3d5309c58ea0012a916a60b0e | [
"MIT"
] | 10 | 2017-09-12T00:37:33.000Z | 2021-01-20T07:04:32.000Z | include/sys/types.h | MrBad/cosiris | 2bb52efd58e705d3d5309c58ea0012a916a60b0e | [
"MIT"
] | null | null | null | include/sys/types.h | MrBad/cosiris | 2bb52efd58e705d3d5309c58ea0012a916a60b0e | [
"MIT"
] | 1 | 2021-06-25T17:18:13.000Z | 2021-06-25T17:18:13.000Z | #ifndef _TYPES_H
#define _TYPES_H
#include <stddef.h>
typedef unsigned long ulong_t;
//#define NULL ((void *) 0)
#define false 0
#define true 1
typedef unsigned char bool;
//typedef unsigned int size_t;
typedef int ssize_t;
#ifndef _uint32_t
#define _uint32_t
typedef unsigned int uint32_t;
#endif
typedef int int32_t;
typedef unsigned short int uint16_t;
typedef short int int16_t;
typedef unsigned char uint8_t;
typedef char int8_t;
typedef unsigned long long int uint64_t;
typedef long long int int64_t;
typedef int pid_t;
typedef unsigned int off_t;
typedef unsigned int time_t;
typedef unsigned short uid_t;
typedef unsigned char gid_t;
typedef unsigned short dev_t;
typedef unsigned short ino_t;
typedef unsigned short mode_t;
typedef unsigned short umode_t;
typedef unsigned char nlink_t;
dev_t makedev(int maj, int min);
unsigned int major(dev_t dev);
unsigned int minor(dev_t dev);
#endif
| 21.046512 | 40 | 0.79558 |
027a3542713f7042c6dbc52fa367d722e1bd9ce6 | 1,192 | c | C | old-external/jna/native/dll-callback.c | veriktig/scandium | 17b22f29d70b1a972271071f62017880e8e0b5c7 | [
"Apache-2.0"
] | null | null | null | old-external/jna/native/dll-callback.c | veriktig/scandium | 17b22f29d70b1a972271071f62017880e8e0b5c7 | [
"Apache-2.0"
] | null | null | null | old-external/jna/native/dll-callback.c | veriktig/scandium | 17b22f29d70b1a972271071f62017880e8e0b5c7 | [
"Apache-2.0"
] | null | null | null | /* Copyright (c) 2007-2012 Timothy Wall, All Rights Reserved
*
* The contents of this file is dual-licensed under 2
* alternative Open Source/Free licenses: LGPL 2.1 or later and
* Apache License 2.0. (starting with JNA version 4.0.0).
*
* You can freely decide which license you want to apply to
* the project.
*
* You may obtain a copy of the LGPL License at:
*
* http://www.gnu.org/licenses/licenses.html
*
* A copy is also included in the downloadable source code package
* containing JNA, in file "LGPL2.1".
*
* You may obtain a copy of the Apache License at:
*
* http://www.apache.org/licenses/
*
* A copy is also included in the downloadable source code package
* containing JNA, in file "AL2.0".
*/
/* Must use mingw64 to compile this assembly code. ml64 can't generate the
RIP-relative jumps we need.
*/
#define ASMFN(X) extern void asmfn ## X (); asm(".globl asmfn" #X "\n\
asmfn" #X ":\n\
jmp *fn+8*" #X "(%rip)")
#ifdef DEFINE_CALLBACKS
extern void (*fn[])();
ASMFN(0);ASMFN(1);ASMFN(2);ASMFN(3);ASMFN(4);ASMFN(5);ASMFN(6);ASMFN(7);
ASMFN(8);ASMFN(9);ASMFN(10);ASMFN(11);ASMFN(12);ASMFN(13);ASMFN(14);ASMFN(15);
#endif /* DEFINE_CALLBACKS */
| 33.111111 | 78 | 0.680369 |
f306ace6e4ce3e9cef756ddb7b060dc52a928ca7 | 14,366 | c | C | T1/main.c | lorenzofman/os | e49bd0cbd841628b65cd9e39dc60bfcede05b593 | [
"MIT"
] | null | null | null | T1/main.c | lorenzofman/os | e49bd0cbd841628b65cd9e39dc60bfcede05b593 | [
"MIT"
] | null | null | null | T1/main.c | lorenzofman/os | e49bd0cbd841628b65cd9e39dc60bfcede05b593 | [
"MIT"
] | null | null | null | #include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include "CSVGen.h"
#include "Benchmark.h"
#include "Disk.h"
#include "BufferQueueThread.h"
#include "DiskScheduler.h"
#include "Client.h"
#include "Utils.h"
#include "Types.h"
#include <stdarg.h>
#include <errno.h>
#include <limits.h>
#include <getopt.h>
/* Optimization parameters */
#define MESSAGES_WINDOW_SIZE 2048 /* One message uses only 32 bytes */
#define ELEVATOR_MESSAGES_WINDOW_SIZE 96 /* Elevator will look 96 requests before choosing the best one */
/* Convert string to integer (using base 10)*/
int ExtractInt(char* str)
{
char *endptr = NULL;
long number = strtol(str, &endptr, 10);
if (str == endptr ||
(errno == ERANGE && number == LONG_MIN) ||
(errno == ERANGE && number == LONG_MAX) ||
errno == EINVAL ||
(errno != 0 && number == 0))
{
printf("Error parsing input: \"%s\"\n", str);
exit(EXIT_FAILURE);
}
return number;
}
enum DiskMode {UnassignedDiskMode, CreateDiskMode, LoadDiskMode};
enum OPType {UnassignedOpType, ReadOpMode, WriteOpMode};
struct DiskOperation
{
enum DiskMode diskMode;
enum OPType opType;
char* readFilePath;
char* saveFilePath;
char* filePath;
bool useElevator;
bool randomAccess;
int cylinders;
int surfaces;
int sectorsPerTrack;
int blockSize;
int RPM;
int overheadTime;
int transferTime;
int seekTime;
int sectorInterleaving;
int seed;
int fileSize;
};
char* ExecuteDisk(int argc, char *argv[])
{
struct DiskOperation diskOperation;
diskOperation.diskMode = UnassignedDiskMode;
diskOperation.opType = UnassignedOpType;
diskOperation.saveFilePath = NULL;
diskOperation.readFilePath = NULL;
diskOperation.filePath = NULL;
diskOperation.useElevator = false;
diskOperation.randomAccess = false;
diskOperation.seed = 42;
diskOperation.fileSize =
diskOperation.cylinders =
diskOperation.surfaces =
diskOperation.sectorsPerTrack =
diskOperation.blockSize =
diskOperation.RPM =
diskOperation.overheadTime =
diskOperation.transferTime =
diskOperation.seekTime =
diskOperation.sectorInterleaving = -1;
static struct option long_options[] =
{
{"load", required_argument, NULL, 'l' },
{"save", required_argument, NULL, 's' },
{"read", no_argument, NULL, 'r' },
{"write", no_argument, NULL, 'w' },
{"create", no_argument, NULL, 'c' },
{"elevator", no_argument, NULL, 'e' },
{"random", no_argument, NULL, '0' },
{"cylinders", required_argument, NULL, '1'},
{"surfaces", required_argument, NULL, '2'},
{"sectorsPerTrack", required_argument, NULL, '3'},
{"blockSize", required_argument, NULL, '4'},
{"RPM", required_argument, NULL, '5'},
{"overheadTime", required_argument, NULL, '6'},
{"transferTime", required_argument, NULL, '7'},
{"seekTime", required_argument, NULL, '8'},
{"sectorInterleaving", required_argument, NULL, '9'},
{"filePath", required_argument, NULL, '!'},
{"seed", required_argument, NULL, '@'},
{"size", required_argument, NULL, '#'},
{NULL, 0, NULL, 0 }
};
int c;
int option_index = 0;
while ((c = getopt_long(argc, argv, "l:s:rwce01:2:3:4:5:6:7:8:9:!:#:@:#:", long_options, &option_index)) != -1)
{
switch (c)
{
case 'l':
if(diskOperation.diskMode != UnassignedDiskMode)
{
printf("Option already defined, use load or create, not both\n");
exit(EXIT_FAILURE);
}
diskOperation.readFilePath = optarg;
diskOperation.diskMode = LoadDiskMode;
break;
case 's':
diskOperation.saveFilePath = optarg;
break;
case 'r':
if(diskOperation.opType != UnassignedOpType)
{
printf("Option already defined, use read or write, not both\n");
}
diskOperation.opType = ReadOpMode;
break;
case 'w':
if(diskOperation.opType != UnassignedOpType)
{
printf("Option already defined, use read or write, not both\n");
}
diskOperation.opType = WriteOpMode;
break;
case 'c':
if(diskOperation.diskMode != UnassignedDiskMode)
{
printf("Option already defined, use load or create, not both\n");
}
diskOperation.diskMode = CreateDiskMode;
break;
case 'e':
diskOperation.useElevator = true;
break;
case '0':
diskOperation.randomAccess = true;
break;
case '1':
diskOperation.cylinders = ExtractInt(optarg);
break;
case '2':
diskOperation.surfaces = ExtractInt(optarg);
break;
case '3':
diskOperation.sectorsPerTrack = ExtractInt(optarg);
break;
case '4':
diskOperation.blockSize = ExtractInt(optarg);
break;
case '5':
diskOperation.RPM = ExtractInt(optarg);
break;
case '6':
diskOperation.overheadTime = ExtractInt(optarg);
break;
case '7':
diskOperation.transferTime = ExtractInt(optarg);
break;
case '8':
diskOperation.seekTime = ExtractInt(optarg);
break;
case '9':
diskOperation.sectorInterleaving = ExtractInt(optarg);
break;
case '!':
diskOperation.filePath = optarg;
break;
case '@':
diskOperation.seed = ExtractInt(optarg);
break;
case '#':
diskOperation.fileSize = ExtractInt(optarg);
break;
default:
printf("Other: %c, %s\n", c, optarg);
break;
}
}
struct Disk* disk = NULL;
if(diskOperation.diskMode == LoadDiskMode)
{
disk = CreateDiskFromFile(diskOperation.readFilePath);
}
else if (diskOperation.diskMode == CreateDiskMode)
{
if(diskOperation.blockSize == -1 || diskOperation.cylinders == -1 || diskOperation.surfaces == -1 || diskOperation.sectorsPerTrack == -1 || diskOperation.RPM == -1|| diskOperation.overheadTime == -1|| diskOperation.transferTime == -1)
{
printf("Missing arguments\n");
exit(EXIT_FAILURE);
}
int blocks = diskOperation.sectorsPerTrack * diskOperation.cylinders * diskOperation.surfaces;
disk = CreateDisk(blocks, diskOperation.blockSize, diskOperation.cylinders, diskOperation.surfaces, diskOperation.sectorsPerTrack, diskOperation.RPM, diskOperation.overheadTime, diskOperation.transferTime,(diskOperation.seekTime * 2)/diskOperation.cylinders);
}
if(diskOperation.sectorInterleaving == -1 || diskOperation.filePath == NULL || diskOperation.opType == UnassignedOpType || (diskOperation.fileSize == -1 && diskOperation.opType == ReadOpMode) || diskOperation.diskMode == UnassignedDiskMode)
{
printf("Missing arguments\n");
exit(EXIT_FAILURE);
}
struct BufferQueue* schedulerBufferQueue = CreateBufferThreaded(MESSAGES_WINDOW_SIZE);
struct DiskScheduler* diskScheduler = CreateDiskScheduler(disk, schedulerBufferQueue, diskOperation.sectorInterleaving, ELEVATOR_MESSAGES_WINDOW_SIZE, diskOperation.useElevator);
struct BufferQueue* clientBufferQueue = CreateBufferThreaded(MESSAGES_WINDOW_SIZE);
struct Client* client = CreateClient(clientBufferQueue);
pthread_t scheduler = StartDiskScheduler(diskScheduler);
if(diskOperation.randomAccess == true)
{
srand(diskOperation.seed);
}
if(diskOperation.opType == WriteOpMode)
{
CopyFileToDisk(client, diskScheduler, diskOperation.filePath, !diskOperation.randomAccess);
}
else
{
CopyFileFromDisk(client, diskScheduler, diskOperation.filePath, !diskOperation.randomAccess, diskOperation.fileSize);
}
StopDiskScheduler(diskScheduler);
if(diskOperation.saveFilePath != NULL)
{
WriteDiskToFile(disk, diskOperation.saveFilePath);
}
pthread_join(scheduler, NULL);
DestroyClient(client);
pthread_detach(scheduler);
DestroyDiskScheduler(diskScheduler);
return "";
}
char* ExecuteBenchmark(int argc, char *argv[])
{
static struct option long_options[] =
{
{"thread", no_argument, NULL, 't'},
{"bufferSize", required_argument, NULL, '0'},
{"blockSize", required_argument, NULL, '1'},
{"readers", required_argument, NULL, 'r'},
{"writers", required_argument, NULL, 'w'},
};
int bufferSize = 0, blockSize = 0, readers = 0, writers = 0;
bool useThreads = false;
int c, option_index = 0;
while ((c = getopt_long(argc, argv, "t0:1:r:w:", long_options, &option_index)) != -1)
{
switch (c)
{
case 't':
useThreads = true;
break;
case '0':
bufferSize = ExtractInt(optarg);
break;
case '1':
blockSize = ExtractInt(optarg);
break;
case 'r':
readers = ExtractInt(optarg);
break;
case 'w':
writers = ExtractInt(optarg);
break;
default:
break;
}
}
if(useThreads)
{
if(blockSize == 0 || bufferSize == 0 || readers == 0 || writers == 0)
{
printf("Missing arguments\n");
exit(EXIT_FAILURE);
}
int throughput = ThreadBenchmark(bufferSize, blockSize - 4, readers, writers);
if(throughput == 0)
{
return "Error\n";
}
char bufferSizeBuf[10], blockSizeBuf[10], throughputBuf[10];
FormattedBytes(bufferSize, bufferSizeBuf);
FormattedBytes(blockSize, blockSizeBuf);
FormattedBytes(throughput, throughputBuf);
printf("Buffersize: %s\n", bufferSizeBuf);
printf("Blocksize: %s\n", blockSizeBuf);
printf("R:%i W:%i\n", readers, writers);
printf("Throughput: %s/s\n", throughputBuf);
return "Threaded Benchmark succesfull\n";
}
else
{
if(bufferSize == 0 || blockSize == 0)
{
printf("Missing arguments\n");
exit(EXIT_FAILURE);
}
int throughput = Benchmark(bufferSize, blockSize - 4);
if(throughput == 0)
{
return "Error\n";
}
char bufferSizeBuf[10], blockSizeBuf[10], throughputBuf[10];
FormattedBytes(bufferSize, bufferSizeBuf);
FormattedBytes(blockSize, blockSizeBuf);
FormattedBytes(throughput, throughputBuf);
printf("Buffersize: %s Blocksize: %s Throughput: %s/s\n", bufferSizeBuf, blockSizeBuf, throughputBuf);
return "Threaded Benchmark succesfull\n";
}
return "Invalid parameter benchmark. Rerun with -t for threaded and -nt for non-threaded \n";
}
char* GenerateCSV(int argc, char *argv[])
{
static struct option long_options[] =
{
{"thread", no_argument, NULL, 't'},
{"minBufSize", required_argument, NULL, '0'},
{"maxBufSize", required_argument, NULL, '1'},
{"minBlockSize", required_argument, NULL, '2' },
{"readers", required_argument, NULL, 'r'},
{"writers", required_argument, NULL, 'w'}
};
int minBufSize = 0, maxBufSize = 0, minBlockSize = 0, readers = 0, writers = 0;
bool useThreads = false;
int c, option_index = 0;
while ((c = getopt_long(argc, argv, "t0:1:2:r:w:", long_options, &option_index)) != -1)
{
switch (c)
{
case 't':
useThreads = true;
break;
case '0':
minBufSize = ExtractInt(optarg);
break;
case '1':
maxBufSize = ExtractInt(optarg);
break;
case '2':
minBlockSize = ExtractInt(optarg);
break;
case 'r':
readers = ExtractInt(optarg);
break;
case 'w':
writers = ExtractInt(optarg);
break;
default:
break;
}
}
if(useThreads)
{
if(minBufSize == 0 || maxBufSize == 0 || minBlockSize == 0 || readers == 0 || writers == 0)
{
printf("Missing arguments\n");
exit(EXIT_FAILURE);
}
CSVThreaded(minBufSize, maxBufSize, minBlockSize, readers, writers);
}
else
{
if(minBufSize == 0 || maxBufSize == 0 || minBlockSize == 0)
{
printf("Missing arguments\n");
exit(EXIT_FAILURE);
}
CSVNonThreaded(minBufSize, maxBufSize, minBlockSize);
}
return "";
}
char* Execute(int argc, char *argv[])
{
static struct option long_options[] =
{
{"csv", no_argument, NULL, 'z'},
{"benchmark", no_argument, NULL, 'b'},
{"disk", no_argument, NULL, 'd'}
};
int option_index = 0;
int c = getopt_long(argc, argv, "zbd", long_options, &option_index);
switch (c)
{
case 'z':
return GenerateCSV(argc, argv);
case 'b':
return ExecuteBenchmark(argc - 1, argv + 1);
case 'd':
return ExecuteDisk(argc, argv);
default:
break;
}
return "No arguments passed to program\nYou can use --csv to generate a csv with benchmarks or --benchmark to run only one time. Also check --disk to copy files\n";
}
int main(int argc, char *argv[])
{
char* returnedMessage = Execute(argc, argv);
printf("%s", returnedMessage);
return 0;
} | 33.882075 | 267 | 0.565363 |
b36a783e95da9f5b0afc70087749fc577a2fffa7 | 239 | h | C | ZTWaterFlowLayout/Classes/ZTDecorationReusableView.h | sacrifice123/ZTWaterFlowLayout | ef330d135a47b4eb9759e452aa9f0e7bb4151aff | [
"MIT"
] | 1 | 2018-02-26T09:50:14.000Z | 2018-02-26T09:50:14.000Z | ZTWaterFlowLayout/Classes/ZTDecorationReusableView.h | sacrifice123/ZTWaterFlowLayout | ef330d135a47b4eb9759e452aa9f0e7bb4151aff | [
"MIT"
] | null | null | null | ZTWaterFlowLayout/Classes/ZTDecorationReusableView.h | sacrifice123/ZTWaterFlowLayout | ef330d135a47b4eb9759e452aa9f0e7bb4151aff | [
"MIT"
] | null | null | null | //
// ZTDecorationReusableView.h
// ZTLayout
//
// Created by zhangtao on 2018/2/24.
// Copyright © 2018年 zhangtao. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface ZTDecorationReusableView : UICollectionReusableView
@end
| 17.071429 | 62 | 0.732218 |
279450acfd82e583b0311d46c0d98b690aec6a09 | 1,336 | h | C | Examples/Channel9/Source/ChannelStripProcessor.h | MeijisIrlnd/airwindows | e2818f43711fa8b6f424d31824c35bb47bb82140 | [
"MIT"
] | 2 | 2021-03-02T05:14:39.000Z | 2022-03-19T01:47:57.000Z | Examples/Channel9/Source/ChannelStripProcessor.h | MeijisIrlnd/airwindows | e2818f43711fa8b6f424d31824c35bb47bb82140 | [
"MIT"
] | null | null | null | Examples/Channel9/Source/ChannelStripProcessor.h | MeijisIrlnd/airwindows | e2818f43711fa8b6f424d31824c35bb47bb82140 | [
"MIT"
] | null | null | null | /* ========================================
* Channel9 - Channel9.h
* Copyright (c) 2016 airwindows, All rights reserved
* ========================================
*/
#pragma once
#include <JuceHeader.h>
#include <map>
class ChannelStripProcessor : public juce::AudioSource
{
public:
enum MODE
{
NEVE, API, SSL, TEAC, MACKIE
};
enum PARAMETER
{
INPUT_GAIN,
OUTPUT_GAIN
};
ChannelStripProcessor();
~ChannelStripProcessor() override;
void switchMode(MODE m);
void setParam(PARAMETER p, float value);
void prepareToPlay(int samplesPerBlockExpected, double sampleRate) override;
void getNextAudioBlock(const juce::AudioSourceChannelInfo& bufferToFill) override;
void releaseResources() override;
private:
std::map<PARAMETER, float*> paramBindings;
MODE currentMode;
double sr;
uint32_t fpdL;
uint32_t fpdR;
double iirSampleLA;
double iirSampleRA;
double iirSampleLB;
double iirSampleRB;
double lastSampleAL;
double lastSampleBL;
double lastSampleCL;
double lastSampleAR;
double lastSampleBR;
double lastSampleCR;
long double biquadA[15];
long double biquadB[15];
double iirAmount;
double threshold;
double cutoff;
bool flip;
float A;
float B;
float C;
}; | 22.266667 | 86 | 0.634731 |
7e066183ef3a415c2e2da73b507112694cccb098 | 600 | c | C | src/main.c | miguelmoraperea/CommandInterpreter | 06b395f2bc171da1aaf466baee764c611e1db465 | [
"MIT"
] | null | null | null | src/main.c | miguelmoraperea/CommandInterpreter | 06b395f2bc171da1aaf466baee764c611e1db465 | [
"MIT"
] | null | null | null | src/main.c | miguelmoraperea/CommandInterpreter | 06b395f2bc171da1aaf466baee764c611e1db465 | [
"MIT"
] | null | null | null | /*****************************************************************************
* Module name: main.c
*
* First written on May 23, 2019 by Miguel.
*
*****************************************************************************/
#include <stdio.h>
#include "CommandInterpreter.h"
#define MAX_SIZE_OF_INPUT_LINE 128
int main(void)
{
char userInputLine[MAX_SIZE_OF_INPUT_LINE];
CommandInt_Init();
while(1)
{
printf("> ");
fgets(userInputLine, sizeof(userInputLine), stdin);
CommandInt_Handle(userInputLine);
}
return 0;
}
| 21.428571 | 79 | 0.453333 |
476fac03ec0e580a5041bf27d89547327cb8df93 | 31,011 | c | C | npo-17182/Spam/vdi.c | SteveDoyle2/nasa-cosmic | c8015a9851a04f0483b978d92c2cbaee31c81fe3 | [
"BSD-Source-Code"
] | 22 | 2015-03-14T07:26:35.000Z | 2021-06-16T12:23:17.000Z | npo-17182/Spam/vdi.c | SteveDoyle2/nasa-cosmic | c8015a9851a04f0483b978d92c2cbaee31c81fe3 | [
"BSD-Source-Code"
] | null | null | null | npo-17182/Spam/vdi.c | SteveDoyle2/nasa-cosmic | c8015a9851a04f0483b978d92c2cbaee31c81fe3 | [
"BSD-Source-Code"
] | 10 | 2016-02-12T22:18:47.000Z | 2020-11-08T17:46:54.000Z | /*************************************************************************
vdi.c 2.15 - Virtual Device Interface
This file contains the local implementation of the raster display
primtives used by spam, providing a measure of portability. This
file, as distributed, contains the code for using the Rastertech
Model 1/25, which may be used as an example in coding these routines
for other machines.
Notes:
1) Note that vdflush must be called at the end of any subroutine
calling these primitives. Vdflush ensures that the dma buffer
is flushed and that the cursor tracking is enabled. (These
routines will stop cursor tracking before writing to the
screen; this is necessary because the cursor is software-
defined and can't be going in this vdi implementation while the
screen is being updated. Vdflush may not be needed in other
implementations of vdi.)
2) Emptyb() is used below in a couple functions to force emptying
of the device-driver buffer. It is important sometimes (in
the scan function, for example) that commands be sent right
away for display timing reasons.
3) This interface doesn't explicitly allow for flushing button
buffers, and some devices (e.g., Rastertech) allow button
pushes to be queued which can cause problems. To alleviate
this, vdcuroff() flushes the button buffer.
4) Note that all arguments are passed by reference rather than
value (as is normal in C) so that this interface may be written
in FORTRAN, if preferred.
5) Each function, in the first comment line, contains information
for using the MIPL-defined "virtual frame buffer" interface.
If you have this, read the xdlib information file in the
distribution. Otherwise, you can ignore these comments.
Written by alan s mazer
Version 1.0, July 1984
*************************************************************************/
#include <stdio.h>
#include <signal.h>
#include "spam.h" /* See VDCURON for explanation of this. */
int buttons[16]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
int cursor_on; /* This is only needed for user-defined cursors. */
/* It allows vdi to turn off the cursor if */
/* necessary before writing to the screen. */
/*************************************************************************/
/* Vddevall - Use XDDALLOCATE - Same parameters */
/* Vddevall allocates a display device. This is not really needed in a */
/* single-user system, but is included here for MIPL compatibility and */
/* multi-user systems. */
/*************************************************************************/
vddevall(unit_addr,config1)
short int *unit_addr,*config1;
{
char ans[80];
int catchint();
rtinit("/dev/ra0",0,0); /* init rastertech for dma, default bufsiz. */
entgra();
cursor_on=0;
signal(SIGINT,catchint);
}
catchint()
{
vddevfre(&unit);
exit();
}
/*****************************************************************************/
/* Vddevact - Use XDDACTIVATE - Same parameters - Turn on/off access to */
/* display device specified by unit_addr. Included for MIPL compatibility */
/* only. */
/*****************************************************************************/
vddevact(unit_addr,flag_addr)
short int *unit_addr;
char *flag_addr;
{
}
/******************************************************************************/
/* Vddevcon - Use XDDCONFIGURE, et al. */
/* Vddevcon configures the display device as follows (these requirements are */
/* largely, but not totally, the default configuration set up using the MIPL */
/* XDDCONFIGURE subroutine): */
/* */
/* 1) Set the device for 512x512 full-color. This can be done with */
/* XDDCONFIGURE if you are using the MIPL interface. */
/* 2) Set all device-specific things. For example, on the Rastertech, reset */
/* debug mode, primitive-fill flag, etc. */
/* 3) Clear the clipping window, if any, and reset the display window. These */
/* are done by XDDCONFIGURE if you're using the MIPL interface. */
/* 4) Turn the cursor off, but set it up for automatic tracking of the digi- */
/* pad or trackball. Done by XDDCONFIGURE. */
/* 5) Reset lut mappings, image plane 1 to lut 1, etc. Done by XDDCONFIGURE. */
/* 6) Set up the graphics overlay plane for reading and writing as necessary, */
/* but turn off (only the latter is done by XDDCONFIGURE; use XDGCONNECT */
/* to use image plane 4 as the graphics overlay under the MIPL interface). */
/* 7) Initialize text-display support. This may involve font selection, */
/* rotation, and other aspects of text handling not changeable under this */
/* interface. Things like color and text size are set when they are used, */
/* using vdtxtsiz() and vdtext(). */
/******************************************************************************/
vddevcon(unit_addr,config2)
short int *unit_addr,*config2;
{
int i;
spchar(2,0,0); /* disable Rastertek keybd interrupt. */
for (i=0;i<16;i++) buttbl(i,0); /* Remove button-table macros. */
moddis(0); /* Switch to 512 x 512 mode. */
lutrte(0); /* map image planes to corr luts. */
cororg(0,0); /* reset screen origin. */
scrorg(0,0);
window(-256,-256,255,255); /* reset window. */
prmfil(0); /* turn off auto primitive filling. */
textre(); /* set default text font. */
delay(0); /* reset transmission delay. */
vecpat(65535); /* set for solid (not dashed) lines. */
pixfun(0); /* normal writes (no xor, and, etc.) */
pixclp(0); /* handle over/under-flows using mod. */
wrmask(255,7); /* enable all planes for write. */
rdmask(255); /* use all bits of each plane. */
rdmode(1); /* enable dma readback. */
vload(4,128,0,0); /* cross-hair color (red) in o-pln 0. */
ovrrd(0,1); /* enable reading of o-pln 0 (cursor) */
ovrrd(1,0); /* disable reading of o-pln 1 (hist) */
/*
/* cursor macros (autotracking setup)
/* The following lines implement our local cursor for the Rastertek. The
/* normal Rastertek cursor is a little large to be convenient. This can be
/* ignored if you're using a hardware cursor or have programmed your own
/* cursor.
*/
macdef(43); /* cross-hairs: draw new and erase old */
cmove(0,21); /* move to old pos */
ovrval(0,0); /* erase mode */
macro(42); /* draw cross-hair */
cmove(21,2); /* save digi-pad pos in reg 21 */
cmove(0,21); /* move to digi-pad pos */
ovrval(0,1); /* add mode */
macro(42); /* draw cross-hair */
macro(44); /* kill time ... */
cmove(22,0); /* save current cursor location. */
macend();
macdef(44); /* kill time macro */
macro(45);
macro(45);
macro(45);
macro(45);
macro(45);
macro(45);
macro(45);
macro(45);
macend();
macdef(45); /* kill time macro */
cmove(0,21);
cmove(0,21);
cmove(0,21);
cmove(0,21);
cmove(0,21);
macend();
}
/************************************************************************/
/* Vddevope - Use XDDOPEN - Same parameters */
/* Vddevope opens the display device for output. It's included here */
/* for MIPL compatibility only. */
/************************************************************************/
vddevope(unit_addr)
short int *unit_addr;
{
}
/************************************************************************/
/* Vddevfre - Use XDDFREE - Same parameters */
/* Vddevfre - deallocate and reinit device. Again, this is probably */
/* not necessary for single-user systems, but is included to fit into */
/* multi-user systems and for MIPL compatibility. */
/************************************************************************/
#include <sys/types.h>
#include <sys/timeb.h>
vddevfre(unit_addr)
short int *unit_addr;
{
struct timeb clock;
val8(0); /* erase the rgb planes. */
wrmask(255,7);
flood();
textc(36,0); /* set for jumbo text size. */
value(255,0,0); /* write NOT IN USE in random */
ftime(&clock); /* position. */
movabs(-80,200-(int)(clock.millitm*0.45));
text1("NOT IN USE");
spchar(2,1,1); /* reenable previously-disabled */
quit(); /* Rastertech coldstart interrupt key. */
rtclose();
}
/************************************************************************/
/* Vdlutrmp - Use XDLRAMP - Same parameters */
/* Set specified look-up table (1=red,2=green,3=blue) to "ramp" where */
/* 1st and 255th entry are 1 and 255, respectively. Section variable */
/* is for MIPL interface users only. */
/************************************************************************/
vdlutrmp(unit_addr,lut_addr,section_addr)
short int *unit_addr,*lut_addr,*section_addr;
{
int i=8;
i>>=(*lut_addr);
lutrmp(i,0,255,0,255);
}
/************************************************************************/
/* Vdzoom - Use XDLZOOM - Same parameters */
/* Set zoom. Note that this definition of the vdzoom primitive implies */
/* that zooms can be set independently. This is allowed under the MIPL */
/* interface, but not possible with the Rastertech, so all planes are */
/* zoomed with the same factor. Also, the only legal zooms on the */
/* Rastertek are 1, 2, 4, and 8. Planes are specified with the plane */
/* mask defined above. */
/************************************************************************/
vdzoom(unit_addr,plane_addr,zoom_addr)
short int *unit_addr,*plane_addr,*zoom_addr;
{
if (*zoom_addr!=1 && *zoom_addr!=2 && *zoom_addr!=4 && *zoom_addr!=8)
return(8);
zoom(*zoom_addr);
}
/****************************************************************************/
/* Vddispln - Use XDLCONNECT - Calling formats differ. */
/* The MIPL primitive XDLCONNECT allows any set of plane-LUT pairings. The */
/* VDDISPLN primitive is less device specific but less powerful, allowing */
/* any single plane to be mapped to all lookup tables. Since XDLCONNECT */
/* and VDDISPLN are not similar in capability, the parameters are not the */
/* same. See the documentation for XDLCONNECT for more information. */
/* The plane to display is specified with the plane mask defined above. */
/****************************************************************************/
vddispln(unit_addr,plane_addr)
short int *unit_addr,*plane_addr;
{
if (*plane_addr==0 || *plane_addr==7) lutrte(0); /* display all planes. */
else if (*plane_addr==4) lutrte(0x7e); /* map red to all luts. */
else if (*plane_addr==2) lutrte(0x75); /* map green to all luts. */
else if (*plane_addr==1) lutrte(0x53); /* map blue to all luts. */
emptyb(); /* ensures immediate change on screen */
}
/*****************************************************************************/
/* Vdcuron - Use XDCON - Same parameters - Turn cursor on. Note that the */
/* spam program as originally implemented allowed for box cursors. Neither */
/* this interface nor the MIPL interface allow for these. The global vars */
/* cursor_nl and cursor_ns contain the dimensions of the box area, and are */
/* both equal to 1 for a 11-line, 11-sample crosshair. If box cursors will */
/* work on your device, you can access these global variables by "including" */
/* spam.h (in C). */
/* The size of the box cursor is cursor_nl+2 lines by cursor_ns+2 */
/* samples. In this way, the box cursor actually surrounds the area of */
/* interest, and the cursor itself doesn't get in the way. The location of */
/* a box cursor is defined to be the coordinates (line, sample >=1) of the */
/* lowest, rightmost point in the enclosed area; that is, the location is */
/* not part of the cursor itself, but is just inside the lower-right corner */
/* of the cursor. */
/* When cursor_nl = cursor_ns = 1, the cursor is an 11 line, 11 sample */
/* crosshair, whose location is defined to be the intersection point. */
/* Cursor, form, and blink variables are for MIPL compatibility only. */
/*****************************************************************************/
vdcuron(unit_addr,cursor_addr,form_addr,blink_addr)
short int *unit_addr,*cursor_addr,*form_addr,*blink_addr;
{
macdef(42); /* macro for drawing cross-hair */
if (cursor_nl==1 && cursor_ns==1) { /* if no averaging (1x1 box) */
drwrel(5,0); /* use 11x11 cursor. */
movrel(-5,-5);
drwrel(0,10);
movrel(-5,-5);
drwrel(5,0);
}
else { /* otherwise, draw box. */
movrel(1,-1);
recrel(-cursor_ns-1,cursor_nl+1);
movrel(-1,1);
}
macend();
wrmask(0,16); /* write to o-plane 0 only. */
macro(42); /* draw cross_hair/box */
cmove(21,0); /* save current pos as old-pos */
buttbl(0,43); /* start digi-pad tracking */
flush(); /* flush button queue. */
emptyb();
cursor_on=1;
}
/*****************************************************************************/
/* Vdcuroff - Use XDCOFF - Same parameters */
/* Vdcuroff turns the cursor off. Cursor variable is for MIPL compatibility */
/* only. */
/*****************************************************************************/
vdcuroff(unit_addr,cursor_addr)
short int *unit_addr,*cursor_addr;
{
int i;
buttbl(0,0); /* disable digi-pad tracking */
ovrval(0,0); /* write zeroes to plane now */
cmove(0,21); /* current pos is now last pos */
macro(42); /* draw (erase) cross_hair/box */
wrmask(255,7); /* write to normal area again */
flush(); /* (See note 3 above.) */
for (i=0;i<16;i++) buttons[i]=0; /* (flushing button buffer) */
emptyb(); /* turn cursor off right now! */
cursor_on=0;
}
/*****************************************************************************/
/* Vdcurloc - Use XDCLOCATION - Same parameters - Return cursor location. */
/* Cursor location is returned as the line and sample of the pixel to */
/* the left and above the lower-right box corner for box cursors, and the */
/* cross-hair center for cross-hair cursors. Cursor variable is for MIPL */
/* compatibility only. */
/*****************************************************************************/
vdcurloc(unit_addr,cursor_addr,line_addr,sample_addr)
short int *unit_addr,*cursor_addr,*line_addr,*sample_addr;
{
int x,y;
readcr(2,&x,&y); /* devices only. */
*line_addr = 256-y; /* Rastertech returns location in Cartesian */
*sample_addr = x+257; /* coordinates where (0,0) is center. */
}
/**************************************************************************/
/* Vdswitch - Use XDXSWITCH - Same parameters - Check to see if the */
/* specified button has been pushed. Note that there is no provision for */
/* easily flushing the button buffer under either the MIPL interface or */
/* this one, so flushes are done with vdcuroff()'s. The value */
/* var is set if the specified button has been pushed. Dev is included */
/* for MIPL compatibility only. Up to 16 buttons are supported. */
/**************************************************************************/
vdswitch(unit_addr,dev_addr,switch_addr,value_addr)
short int *unit_addr,*dev_addr,*switch_addr,*value_addr;
{
int bn,x,y;
readbu(0,1,&bn,&x,&y);/* mode flag not applicable */
if (bn!=0) buttons[bn]=1; /* Make entry in table, if any. */
if (buttons[*switch_addr]) { /* if button has been pushed, reset */
buttons[*switch_addr]=0; /* button entry in table and return */
*value_addr=1; /* on. */
}
else *value_addr=0;
}
/****************************************************************************/
/* Vdtxtsiz - Use XDTSIZE - Same parameters */
/* Set height of text output in lines. This could also be contained within */
/* vdtext(). The scale argument is included for MIPL compatibility only. */
/****************************************************************************/
vdtxtsiz(size_addr,scale_addr)
short int *size_addr;
float *scale_addr;
{
int i;
i=(*size_addr)*16./7;
textc(i,0);
}
/*****************************************************************************/
/* Vdovron - Use XDGON - Same parameters */
/* Turn on overlay plane. The overlay plane should have been set up by */
/* vddevcon() above. The overlay plane is assumed on throughout spam. */
/*****************************************************************************/
vdovron(unit_addr)
short int *unit_addr;
{
ovrrd(1,1); /* enable reading of overlay plane 1. */
}
/*****************************************************************************/
/* Vdovroff - Use XDGOFF - Same parameters */
/* Turn off the overlay plane. */
/*****************************************************************************/
vdovroff(unit_addr)
short int *unit_addr;
{
ovrrd(1,0); /* disable reading of overlay plane 1. */
}
/*****************************************************************************/
/* Vdpixwri - Use XDIPIXELWRITE - Calling formats differ. */
/* This function sets a pixel at a specified location to a specified value. */
/* It differs from the MIPL implementation in that all planes are written to */
/* in one subroutine call, and that 2-byte rgb values are passed, rather */
/* than one 1-byte value. The plane is specified using the mask defined */
/* above. The pixel location is given by the line and sample stored in the */
/* y and x variables, respectively. */
/*****************************************************************************/
vdpixwri(unit_addr,plane_addr,x_addr,y_addr,r_addr,g_addr,b_addr)
short int *unit_addr,*plane_addr,*x_addr,*y_addr;
short int *r_addr,*g_addr,*b_addr;
{
if (cursor_on) vdcuroff(&unit,&c1);
wrmask(255,(int)*plane_addr); /* write only to specified plane(s). */
movabs(*x_addr-257,256-*y_addr); /* move to point specified. */
if (*plane_addr!=8) value((int)*r_addr,(int)*g_addr,(int)*b_addr);
if (*plane_addr>7) {
vload(5,(int)*r_addr,(int)*g_addr,(int)*b_addr);
if (*r_addr || *g_addr || *b_addr) ovrval(1,1);
else ovrval(1,0);
}
point(); /* color pixel in specified plane(s). */
}
/****************************************************************************/
/* Vdareawr - Use XDIAWSET, XDIAWWRITE - Calling formats differ. */
/* This function was formed by combining XDIAWSET & -WRITE above. It fills */
/* the specified window area with a stream of pixels. Any image plane(s) */
/* may be filled, but the same pixel stream must be sent to all. */
/* Plane is specified using mask defined above. N is the number of pixels */
/* to be sent. A points to the pixel buffer. Left, top, right, and bottom */
/* contain the starting sample, starting line, ending sample, and ending */
/* line, respectively. */
/****************************************************************************/
vdareawr(unit_addr,plane_addr,n_addr,a,
left_addr,top_addr,right_addr,bottom_addr)
short int *unit_addr,*plane_addr,*left_addr,*top_addr,*right_addr,*bottom_addr;
long int *n_addr;
char *a;
{
if (cursor_on) vdcuroff(&unit,&c1);
movabs((int)*left_addr-257,(int)256-*top_addr);
wrmask(255,(int)*plane_addr);
pixel8((int)*bottom_addr-*top_addr+1,(int)*right_addr-*left_addr+1,a);
}
/*************************************************************************/
/* Vdvector - Use XDIPOLYLINE - Calling formats differ. */
/* Vdvector plots a series of connected vectors to any combination of */
/* planes using the specified color(s). Planes are specified using */
/* mask defined above. N is the number of points given. Points are */
/* passed using the X and Y arrays, line coordinates in the Y array, and */
/* sample coordinates in the X array. */
/*************************************************************************/
vdvector(unit_addr,plane_addr,r_addr,g_addr,b_addr,n_addr,x_addr,y_addr)
short int *unit_addr,*plane_addr,*n_addr,*x_addr,*y_addr;
short int *r_addr,*g_addr,*b_addr;
{
int i;
if (cursor_on) vdcuroff(&unit,&c1);
wrmask(255,(int)*plane_addr);
if (*plane_addr!=8) value((int)*r_addr,(int)*g_addr,(int)*b_addr);
if (*plane_addr>7) {
vload(5,(int)*r_addr,(int)*g_addr,(int)*b_addr);
if (*r_addr || *g_addr || *b_addr) ovrval(1,1);
else ovrval(1,0);
}
movabs(-257+x_addr[0],256-y_addr[0]);
for (i=1;i<*n_addr;i++) drwabs(-257+x_addr[i],256-y_addr[i]);
}
/**************************************************************************/
/* Vdtext - Use XDTCOLOR, XDTTEXT - Calling formats differ. */
/* Vdtext writes text to any or all of the planes in the specified color. */
/* Planes are specified using the plane mask defined above. X and Y are */
/* the sample and line of the lower-left corner of the first character. */
/* N is the length of the text string. A is a pointer to the string. Loc */
/* can be ignored; it's for MIPL only. */
/**************************************************************************/
vdtext(unit_addr,plane_addr,r_addr,g_addr,b_addr,x_addr,y_addr,
loc_addr,n_addr,a)
short int *unit_addr,*plane_addr,*x_addr,*y_addr,*loc_addr,*n_addr;
short int *r_addr,*g_addr,*b_addr;
char *a;
{
if (cursor_on) vdcuroff(&unit,&c1);
wrmask(255,(int)*plane_addr);
if (*plane_addr!=8) value((int)*r_addr,(int)*g_addr,(int)*b_addr);
if (*plane_addr>7) {
vload(5,(int)*r_addr,(int)*g_addr,(int)*b_addr);
if (*r_addr || *g_addr || *b_addr) ovrval(1,1);
else ovrval(1,0);
}
movabs(*x_addr-257,256-*y_addr);
a[*n_addr]='\0';
text1(a);
}
/*************************************************************************/
/* Vdareafi - Use XDIAWSET, XDIFILL - Calling formats differ. */
/* Vdareafi fills the specified area of the specified plane(s) with the */
/* given color. Plane is specified using mask described above. */
/* Area is defined by starting sample, starting line, ending sample, and */
/* ending line, in order below. */
/*************************************************************************/
vdareafi(unit_addr,pln_addr,r_addr,g_addr,b_addr,
x1_addr,y1_addr,x2_addr,y2_addr)
short int *unit_addr,*pln_addr,*r_addr,*g_addr,*b_addr;
short int *x1_addr,*y1_addr,*x2_addr,*y2_addr;
{
if (cursor_on) vdcuroff(&unit,&c1);
wrmask(255,(int)*pln_addr);
prmfil(1);
if (*pln_addr!=8) value((int)*r_addr,(int)*g_addr,(int)*b_addr);
if (*pln_addr>7) {
vload(5,(int)*r_addr,(int)*g_addr,(int)*b_addr);
if (*r_addr || *g_addr || *b_addr) ovrval(1,1);
else ovrval(1,0);
}
movabs(*x1_addr-257,256-*y1_addr);
rectan(*x2_addr-257,256-*y2_addr);
prmfil(0);
}
/*************************************************************************/
/* Vdplncop - Use XDIAWSET, XDIICOPY - Calling formats differ. */
/* Copy area of one plane to area(s) of other plane(s). Planes are */
/* specified using the usual masks. Other arguments are p1x1, plane 1 */
/* starting sample, p1y1, plane1 starting line, p2x2, plane 2 ending */
/* sample, p2y2, plane 2 ending line, etc. */
/*************************************************************************/
vdplncop(unit_addr,plane1_addr,plane2_addr,
p1x1_addr,p1y1_addr,p1x2_addr,p1y2_addr,
p2x1_addr,p2y1_addr,p2x2_addr,p2y2_addr)
short int *unit_addr,*plane1_addr,*plane2_addr;
short int *p1x1_addr,*p1y1_addr,*p1x2_addr,*p1y2_addr;
short int *p2x1_addr,*p2y1_addr,*p2x2_addr,*p2y2_addr;
{
int r=0,g=0,b=0;
cload(11,*p1x1_addr-257,256-*p1y1_addr);
cload(12,*p1x2_addr-257,256-*p1y2_addr);
cload(13,*p2x1_addr-257,256-*p2y1_addr);
cload(14,*p2x2_addr-257,256-*p2y2_addr);
if (*plane2_addr & 4) r=1;
if (*plane2_addr & 2) g=1;
if (*plane2_addr & 1) b=1;
switch (*plane1_addr) {
case 4:
pmctl(0,0,0,0,1*r,1*g,1*b);
pixmov();
break;
case 2:
pmctl(0,0,0,0,2*r,2*g,2*b);
pixmov();
break;
case 1:
pmctl(0,0,0,0,3*r,3*g,3*b);
pixmov();
break;
}
}
/************************************************************************/
/* Vdsetwin - Use XDIDWSET - Calling formats differ. */
/* Set upper-left corner of the display window. This differs from the */
/* MIPL interface in that this requires that all image planes have the */
/* same display window; the display window for the overlay plane may be */
/* different. Left and top variables are sample and line of upper- */
/* left corner, respectively. */
/************************************************************************/
vdsetwin(unit_addr,plane_addr,left_addr,top_addr)
short int *unit_addr,*plane_addr,*left_addr,*top_addr;
{
if (*plane_addr!=8) scrorg(*left_addr-1,1-*top_addr);
if (*plane_addr>7) vload(16,*left_addr-1,1-*top_addr);
emptyb(); /* make sure change is sent immediately for scan function */
}
/**************************************************************************/
/* Vdlutwri - Use XDLWRITE - Same parameters - Writes values in array out */
/* to specified look-up table (1=red,2=green,3=blue). Ignore section */
/* argument; this is for MIPL only. */
/**************************************************************************/
vdlutwri(unit_addr,lut_addr,sect_addr,array)
short int *unit_addr,*lut_addr,*sect_addr,*array;
{
int i=8;
i>>=(*lut_addr);
lutrmp(i,0,255,0,255);
for (i=0;i<256;i++) if (array[i]!=i) {
if (*lut_addr==1) lutr((int)i,(int)array[i]);
else if (*lut_addr==2) lutg((int)i,(int)array[i]);
else if (*lut_addr==3) lutb((int)i,(int)array[i]);
}
}
/**************************************************************************/
/* Vdflush - no MIPL equivalent - Ensures that all graphics primitives */
/* are flushed from the dma buffer. May be done automatically by some */
/* systems. Also restarts cursor tracking. */
/**************************************************************************/
vdflush(unit_addr)
short int *unit_addr;
{
if (!cursor_on) vdcuron(&unit,&c1,&c0,&c0);
else emptyb();
}
/****************************************************************************/
/* Vdareard - Use XDIAWSET, XDIAWREAD - Calling formats differ. */
/* This function was formed by combining XDIAWSET & XDIAWREAD. It reads */
/* the pixel values within a specified window area and stores them in */
/* memory. You may read one plane at a time, but it is always good */
/* to allocate enough space for all three planes, unless you're really sure */
/* that your display device won't attempt to send more. Define the plane */
/* using the standard plane mask. N is the number of pixels to be sent. */
/* Red, Green, and Blue are the pixel buffers. Left, top, right and bottom */
/* contain the starting sample, starting line, ending sample, and ending */
/* line, respectively. Pixels may not be read from the overlay plane. */
/****************************************************************************/
vdareard(unit_addr,plane_addr,n_addr,red,green,blue,
left_addr,top_addr,right_addr,bottom_addr)
short int *unit_addr,*plane_addr,*left_addr,*top_addr,*right_addr,*bottom_addr;
long int *n_addr;
char *red,*green,*blue;
{
int nl;
nl = (*n_addr)/(*right_addr-*left_addr+1);
if (cursor_on) vdcuroff(&unit,&c1);
movabs((int)*left_addr-257,(int)256-*top_addr);
if (*plane_addr == 4) {
readf(1);
readw(nl,512,254,red,green,blue);
}
else if (*plane_addr == 2) {
readf(2);
readw(nl,512,254,green,red,blue);
}
else if (*plane_addr == 1) {
readf(3);
readw(nl,512,254,blue,red,green);
}
else {
readf(0);
readw(nl,512,254,red,green,blue);
}
emptyb();
}
/****************************************************************************/
/* vdwait(secs) - Routine kills time to avoid tying up system io (?!). */
/****************************************************************************/
vdwait(time_in_seconds)
float *time_in_seconds;
{
}
| 46.423653 | 80 | 0.508916 |
cc590599d6f73e341b6aecd3f6021718244c8bb2 | 329 | h | C | CocoaAsyncSocketTrain/IM_PacketHandle-master/ServerAsncSocket/ServerAsncSocket/TYHSocketManager.h | pogong/Trains | 025c45c82c6054bf79f9d32db1b5df2b98e37075 | [
"MIT"
] | null | null | null | CocoaAsyncSocketTrain/IM_PacketHandle-master/ServerAsncSocket/ServerAsncSocket/TYHSocketManager.h | pogong/Trains | 025c45c82c6054bf79f9d32db1b5df2b98e37075 | [
"MIT"
] | null | null | null | CocoaAsyncSocketTrain/IM_PacketHandle-master/ServerAsncSocket/ServerAsncSocket/TYHSocketManager.h | pogong/Trains | 025c45c82c6054bf79f9d32db1b5df2b98e37075 | [
"MIT"
] | null | null | null | //
// TYHSocketManager.h
// CocoaSyncSocket
//
// Created by 涂耀辉 on 16/12/28.
// Copyright © 2016年 涂耀辉. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
@interface TYHSocketManager : NSObject
@property (nonatomic,weak)UIImageView *recvImg;
+ (instancetype)share;
- (BOOL)accept;
@end
| 14.304348 | 47 | 0.705167 |
cc5b069d202e79209beaaa6c11704e3c3314336c | 704 | h | C | Internet/FMEP/fmepServer.h | ulri-me/ioLibrary_Driver | 37b2819e3b122d102656ae63fa6d62c025f1d70c | [
"MIT"
] | null | null | null | Internet/FMEP/fmepServer.h | ulri-me/ioLibrary_Driver | 37b2819e3b122d102656ae63fa6d62c025f1d70c | [
"MIT"
] | null | null | null | Internet/FMEP/fmepServer.h | ulri-me/ioLibrary_Driver | 37b2819e3b122d102656ae63fa6d62c025f1d70c | [
"MIT"
] | null | null | null | /**
@file fmepServer.h
@brief Define constants and functions related to server using fmep communication protocol.
*/
#ifndef __FMEP_SERVER_H__
#define __FMEP_SERVER_H__
#ifdef __cplusplus
extern "C" {
#endif
// Watchdog timer
//#define _FMEP_USE_WATCHDOG_
#define _FMEP_SERVER_DEBUG_
#define FMEP_SERVER_DATA_BUFFER_SIZE 2048
#define FMEP_SERVER_PORT 6400
// FMEP server list of possible statuses
#define FMEP_SERVER_STATUS_UNINITIALISED 0
#define FMEP_SERVER_STATUS_INITIALISED 1
// Functions declarations
void fmepServerTimeHandler(void);
void fmepServerConfigure(uint8_t ethernetSocketIndex);
void fmepServerHandle(void);
#ifdef __cplusplus
}
#endif
#endif | 21.333333 | 93 | 0.78125 |
cc8b4ad3cb487360fee998148cfeaa67ca4dfd93 | 19,671 | c | C | src/curl_json.c | TranscendComputing/TopStackMessageAgent | 97da381e932b5ad0257dbcb108ad32caa049f599 | [
"Apache-2.0"
] | null | null | null | src/curl_json.c | TranscendComputing/TopStackMessageAgent | 97da381e932b5ad0257dbcb108ad32caa049f599 | [
"Apache-2.0"
] | null | null | null | src/curl_json.c | TranscendComputing/TopStackMessageAgent | 97da381e932b5ad0257dbcb108ad32caa049f599 | [
"Apache-2.0"
] | null | null | null | /**
* collectd - src/curl_json.c
* Copyright (C) 2009 Doug MacEachern
* Copyright (C) 2006-2011 Florian octo Forster
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; only version 2 of the License is applicable.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* Authors:
* Doug MacEachern <dougm at hyperic.com>
* Florian octo Forster <octo at collectd.org>
**/
#include "collectd.h"
#include "common.h"
#include "plugin.h"
#include "configfile.h"
#include "utils_avltree.h"
#include "utils_complain.h"
#include <curl/curl.h>
#include <yajl/yajl_parse.h>
#if HAVE_YAJL_YAJL_VERSION_H
# include <yajl/yajl_version.h>
#endif
#if defined(YAJL_MAJOR) && (YAJL_MAJOR > 1)
# define HAVE_YAJL_V2 1
#endif
#define CJ_DEFAULT_HOST "localhost"
#define CJ_KEY_MAGIC 0x43484b59UL /* CHKY */
#define CJ_IS_KEY(key) ((key)->magic == CJ_KEY_MAGIC)
#define CJ_ANY "*"
#define COUCH_MIN(x,y) ((x) < (y) ? (x) : (y))
struct cj_key_s;
typedef struct cj_key_s cj_key_t;
struct cj_key_s /* {{{ */
{
char *path;
char *type;
char *instance;
unsigned long magic;
};
/* }}} */
struct cj_s /* {{{ */
{
char *instance;
char *host;
char *url;
char *user;
char *pass;
char *credentials;
_Bool verify_peer;
_Bool verify_host;
char *cacert;
CURL *curl;
char curl_errbuf[CURL_ERROR_SIZE];
yajl_handle yajl;
c_avl_tree_t *tree;
cj_key_t *key;
int depth;
struct {
union {
c_avl_tree_t *tree;
cj_key_t *key;
};
char name[DATA_MAX_NAME_LEN];
} state[YAJL_MAX_DEPTH];
};
typedef struct cj_s cj_t; /* }}} */
#if HAVE_YAJL_V2
typedef size_t yajl_len_t;
#else
typedef unsigned int yajl_len_t;
#endif
static int cj_read (user_data_t *ud);
static int cj_curl_perform (cj_t *db, CURL *curl);
static void cj_submit (cj_t *db, cj_key_t *key, value_t *value);
static size_t cj_curl_callback (void *buf, /* {{{ */
size_t size, size_t nmemb, void *user_data)
{
cj_t *db;
size_t len;
yajl_status status;
len = size * nmemb;
if (len <= 0)
return (len);
db = user_data;
if (db == NULL)
return (0);
status = yajl_parse(db->yajl, (unsigned char *) buf, len);
if (status == yajl_status_ok)
{
#if HAVE_YAJL_V2
status = yajl_complete_parse(db->yajl);
#else
status = yajl_parse_complete(db->yajl);
#endif
return (len);
}
#if !HAVE_YAJL_V2
else if (status == yajl_status_insufficient_data)
return (len);
#endif
if (status != yajl_status_ok)
{
unsigned char *msg =
yajl_get_error(db->yajl, /* verbose = */ 1,
/* jsonText = */ (unsigned char *) buf, (unsigned int) len);
ERROR ("curl_json plugin: yajl_parse failed: %s", msg);
yajl_free_error(db->yajl, msg);
return (0); /* abort write callback */
}
return (len);
} /* }}} size_t cj_curl_callback */
static int cj_get_type (cj_key_t *key)
{
const data_set_t *ds;
ds = plugin_get_ds (key->type);
if (ds == NULL)
{
static char type[DATA_MAX_NAME_LEN] = "!!!invalid!!!";
assert (key->type != NULL);
if (strcmp (type, key->type) != 0)
{
ERROR ("curl_json plugin: Unable to look up DS type \"%s\".",
key->type);
sstrncpy (type, key->type, sizeof (type));
}
return -1;
}
else if (ds->ds_num > 1)
{
static c_complain_t complaint = C_COMPLAIN_INIT_STATIC;
c_complain_once (LOG_WARNING, &complaint,
"curl_json plugin: The type \"%s\" has more than one data source. "
"This is currently not supported. I will return the type of the "
"first data source, but this will likely lead to problems later on.",
key->type);
}
return ds->ds[0].type;
}
/* yajl callbacks */
#define CJ_CB_ABORT 0
#define CJ_CB_CONTINUE 1
/* "number" may not be null terminated, so copy it into a buffer before
* parsing. */
static int cj_cb_number (void *ctx,
const char *number, yajl_len_t number_len)
{
char buffer[number_len + 1];
cj_t *db = (cj_t *)ctx;
cj_key_t *key = db->state[db->depth].key;
value_t vt;
int type;
int status;
if ((key == NULL) || !CJ_IS_KEY (key))
return (CJ_CB_CONTINUE);
memcpy (buffer, number, number_len);
buffer[sizeof (buffer) - 1] = 0;
type = cj_get_type (key);
status = parse_value (buffer, &vt, type);
if (status != 0)
{
NOTICE ("curl_json plugin: Unable to parse number: \"%s\"", buffer);
return (CJ_CB_CONTINUE);
}
cj_submit (db, key, &vt);
return (CJ_CB_CONTINUE);
} /* int cj_cb_number */
static int cj_cb_map_key (void *ctx, const unsigned char *val,
yajl_len_t len)
{
cj_t *db = (cj_t *)ctx;
c_avl_tree_t *tree;
tree = db->state[db->depth-1].tree;
if (tree != NULL)
{
cj_key_t *value;
char *name;
name = db->state[db->depth].name;
len = COUCH_MIN(len, sizeof (db->state[db->depth].name)-1);
sstrncpy (name, (char *)val, len+1);
if (c_avl_get (tree, name, (void *) &value) == 0)
db->state[db->depth].key = value;
else if (c_avl_get (tree, CJ_ANY, (void *) &value) == 0)
db->state[db->depth].key = value;
else
db->state[db->depth].key = NULL;
}
return (CJ_CB_CONTINUE);
}
static int cj_cb_string (void *ctx, const unsigned char *val,
yajl_len_t len)
{
cj_t *db = (cj_t *)ctx;
char str[len + 1];
/* Create a null-terminated version of the string. */
memcpy (str, val, len);
str[len] = 0;
/* No configuration for this string -> simply return. */
if (db->state[db->depth].key == NULL)
return (CJ_CB_CONTINUE);
if (!CJ_IS_KEY (db->state[db->depth].key))
{
NOTICE ("curl_json plugin: Found string \"%s\", but the configuration "
"expects a map here.", str);
return (CJ_CB_CONTINUE);
}
/* Handle the string as if it was a number. */
return (cj_cb_number (ctx, (const char *) val, len));
} /* int cj_cb_string */
static int cj_cb_start (void *ctx)
{
cj_t *db = (cj_t *)ctx;
if (++db->depth >= YAJL_MAX_DEPTH)
{
ERROR ("curl_json plugin: %s depth exceeds max, aborting.", db->url);
return (CJ_CB_ABORT);
}
return (CJ_CB_CONTINUE);
}
static int cj_cb_end (void *ctx)
{
cj_t *db = (cj_t *)ctx;
db->state[db->depth].tree = NULL;
--db->depth;
return (CJ_CB_CONTINUE);
}
static int cj_cb_start_map (void *ctx)
{
return cj_cb_start (ctx);
}
static int cj_cb_end_map (void *ctx)
{
return cj_cb_end (ctx);
}
static int cj_cb_start_array (void * ctx)
{
return cj_cb_start (ctx);
}
static int cj_cb_end_array (void * ctx)
{
return cj_cb_end (ctx);
}
static yajl_callbacks ycallbacks = {
NULL, /* null */
NULL, /* boolean */
NULL, /* integer */
NULL, /* double */
cj_cb_number,
cj_cb_string,
cj_cb_start_map,
cj_cb_map_key,
cj_cb_end_map,
cj_cb_start_array,
cj_cb_end_array
};
/* end yajl callbacks */
static void cj_key_free (cj_key_t *key) /* {{{ */
{
if (key == NULL)
return;
sfree (key->path);
sfree (key->type);
sfree (key->instance);
sfree (key);
} /* }}} void cj_key_free */
static void cj_tree_free (c_avl_tree_t *tree) /* {{{ */
{
char *name;
void *value;
while (c_avl_pick (tree, (void *) &name, (void *) &value) == 0)
{
cj_key_t *key = (cj_key_t *)value;
if (CJ_IS_KEY(key))
cj_key_free (key);
else
cj_tree_free ((c_avl_tree_t *)value);
sfree (name);
}
c_avl_destroy (tree);
} /* }}} void cj_tree_free */
static void cj_free (void *arg) /* {{{ */
{
cj_t *db;
DEBUG ("curl_json plugin: cj_free (arg = %p);", arg);
db = (cj_t *) arg;
if (db == NULL)
return;
if (db->curl != NULL)
curl_easy_cleanup (db->curl);
db->curl = NULL;
if (db->tree != NULL)
cj_tree_free (db->tree);
db->tree = NULL;
sfree (db->instance);
sfree (db->host);
sfree (db->url);
sfree (db->user);
sfree (db->pass);
sfree (db->credentials);
sfree (db->cacert);
sfree (db);
} /* }}} void cj_free */
/* Configuration handling functions {{{ */
static c_avl_tree_t *cj_avl_create(void)
{
return c_avl_create ((int (*) (const void *, const void *)) strcmp);
}
static int cj_config_add_key (cj_t *db, /* {{{ */
oconfig_item_t *ci)
{
cj_key_t *key;
int status;
int i;
if ((ci->values_num != 1)
|| (ci->values[0].type != OCONFIG_TYPE_STRING))
{
WARNING ("curl_json plugin: The `Key' block "
"needs exactly one string argument.");
return (-1);
}
key = (cj_key_t *) malloc (sizeof (*key));
if (key == NULL)
{
ERROR ("curl_json plugin: malloc failed.");
return (-1);
}
memset (key, 0, sizeof (*key));
key->magic = CJ_KEY_MAGIC;
if (strcasecmp ("Key", ci->key) == 0)
{
status = cf_util_get_string (ci, &key->path);
if (status != 0)
{
sfree (key);
return (status);
}
}
else
{
ERROR ("curl_json plugin: cj_config: "
"Invalid key: %s", ci->key);
return (-1);
}
status = 0;
for (i = 0; i < ci->children_num; i++)
{
oconfig_item_t *child = ci->children + i;
if (strcasecmp ("Type", child->key) == 0)
status = cf_util_get_string (child, &key->type);
else if (strcasecmp ("Instance", child->key) == 0)
status = cf_util_get_string (child, &key->instance);
else
{
WARNING ("curl_json plugin: Option `%s' not allowed here.", child->key);
status = -1;
}
if (status != 0)
break;
} /* for (i = 0; i < ci->children_num; i++) */
while (status == 0)
{
if (key->type == NULL)
{
WARNING ("curl_json plugin: `Type' missing in `Key' block.");
status = -1;
}
break;
} /* while (status == 0) */
/* store path in a tree that will match the json map structure, example:
* "httpd/requests/count",
* "httpd/requests/current" ->
* { "httpd": { "requests": { "count": $key, "current": $key } } }
*/
if (status == 0)
{
char *ptr;
char *name;
char ent[PATH_MAX];
c_avl_tree_t *tree;
if (db->tree == NULL)
db->tree = cj_avl_create();
tree = db->tree;
name = key->path;
ptr = key->path;
if (*ptr == '/')
++ptr;
name = ptr;
while (*ptr)
{
if (*ptr == '/')
{
c_avl_tree_t *value;
int len;
len = ptr-name;
if (len == 0)
break;
sstrncpy (ent, name, len+1);
if (c_avl_get (tree, ent, (void *) &value) != 0)
{
value = cj_avl_create ();
c_avl_insert (tree, strdup (ent), value);
}
tree = value;
name = ptr+1;
}
++ptr;
}
if (*name)
c_avl_insert (tree, strdup(name), key);
else
{
ERROR ("curl_json plugin: invalid key: %s", key->path);
status = -1;
}
}
return (status);
} /* }}} int cj_config_add_key */
static int cj_init_curl (cj_t *db) /* {{{ */
{
db->curl = curl_easy_init ();
if (db->curl == NULL)
{
ERROR ("curl_json plugin: curl_easy_init failed.");
return (-1);
}
curl_easy_setopt (db->curl, CURLOPT_NOSIGNAL, 1);
curl_easy_setopt (db->curl, CURLOPT_WRITEFUNCTION, cj_curl_callback);
curl_easy_setopt (db->curl, CURLOPT_WRITEDATA, db);
curl_easy_setopt (db->curl, CURLOPT_USERAGENT,
PACKAGE_NAME"/"PACKAGE_VERSION);
curl_easy_setopt (db->curl, CURLOPT_ERRORBUFFER, db->curl_errbuf);
curl_easy_setopt (db->curl, CURLOPT_URL, db->url);
if (db->user != NULL)
{
size_t credentials_size;
credentials_size = strlen (db->user) + 2;
if (db->pass != NULL)
credentials_size += strlen (db->pass);
db->credentials = (char *) malloc (credentials_size);
if (db->credentials == NULL)
{
ERROR ("curl_json plugin: malloc failed.");
return (-1);
}
ssnprintf (db->credentials, credentials_size, "%s:%s",
db->user, (db->pass == NULL) ? "" : db->pass);
curl_easy_setopt (db->curl, CURLOPT_USERPWD, db->credentials);
}
curl_easy_setopt (db->curl, CURLOPT_SSL_VERIFYPEER, (int) db->verify_peer);
curl_easy_setopt (db->curl, CURLOPT_SSL_VERIFYHOST,
(int) (db->verify_host ? 2 : 0));
if (db->cacert != NULL)
curl_easy_setopt (db->curl, CURLOPT_CAINFO, db->cacert);
return (0);
} /* }}} int cj_init_curl */
static int cj_config_add_url (oconfig_item_t *ci) /* {{{ */
{
cj_t *db;
int status = 0;
int i;
if ((ci->values_num != 1)
|| (ci->values[0].type != OCONFIG_TYPE_STRING))
{
WARNING ("curl_json plugin: The `URL' block "
"needs exactly one string argument.");
return (-1);
}
db = (cj_t *) malloc (sizeof (*db));
if (db == NULL)
{
ERROR ("curl_json plugin: malloc failed.");
return (-1);
}
memset (db, 0, sizeof (*db));
if (strcasecmp ("URL", ci->key) == 0)
{
status = cf_util_get_string (ci, &db->url);
if (status != 0)
{
sfree (db);
return (status);
}
}
else
{
ERROR ("curl_json plugin: cj_config: "
"Invalid key: %s", ci->key);
return (-1);
}
/* Fill the `cj_t' structure.. */
for (i = 0; i < ci->children_num; i++)
{
oconfig_item_t *child = ci->children + i;
if (strcasecmp ("Instance", child->key) == 0)
status = cf_util_get_string (child, &db->instance);
else if (strcasecmp ("Host", child->key) == 0)
status = cf_util_get_string (child, &db->host);
else if (strcasecmp ("User", child->key) == 0)
status = cf_util_get_string (child, &db->user);
else if (strcasecmp ("Password", child->key) == 0)
status = cf_util_get_string (child, &db->pass);
else if (strcasecmp ("VerifyPeer", child->key) == 0)
status = cf_util_get_boolean (child, &db->verify_peer);
else if (strcasecmp ("VerifyHost", child->key) == 0)
status = cf_util_get_boolean (child, &db->verify_host);
else if (strcasecmp ("CACert", child->key) == 0)
status = cf_util_get_string (child, &db->cacert);
else if (strcasecmp ("Key", child->key) == 0)
status = cj_config_add_key (db, child);
else
{
WARNING ("curl_json plugin: Option `%s' not allowed here.", child->key);
status = -1;
}
if (status != 0)
break;
}
if (status == 0)
{
if (db->tree == NULL)
{
WARNING ("curl_json plugin: No (valid) `Key' block "
"within `URL' block `%s'.", db->url);
status = -1;
}
if (status == 0)
status = cj_init_curl (db);
}
/* If all went well, register this database for reading */
if (status == 0)
{
user_data_t ud;
char cb_name[DATA_MAX_NAME_LEN];
if (db->instance == NULL)
db->instance = strdup("default");
DEBUG ("curl_json plugin: Registering new read callback: %s",
db->instance);
memset (&ud, 0, sizeof (ud));
ud.data = (void *) db;
ud.free_func = cj_free;
ssnprintf (cb_name, sizeof (cb_name), "curl_json-%s-%s",
db->instance, db->url);
plugin_register_complex_read (/* group = */ NULL, cb_name, cj_read,
/* interval = */ NULL, &ud);
}
else
{
cj_free (db);
return (-1);
}
return (0);
}
/* }}} int cj_config_add_database */
static int cj_config (oconfig_item_t *ci) /* {{{ */
{
int success;
int errors;
int status;
int i;
success = 0;
errors = 0;
for (i = 0; i < ci->children_num; i++)
{
oconfig_item_t *child = ci->children + i;
if (strcasecmp ("URL", child->key) == 0)
{
status = cj_config_add_url (child);
if (status == 0)
success++;
else
errors++;
}
else
{
WARNING ("curl_json plugin: Option `%s' not allowed here.", child->key);
errors++;
}
}
if ((success == 0) && (errors > 0))
{
ERROR ("curl_json plugin: All statements failed.");
return (-1);
}
return (0);
} /* }}} int cj_config */
/* }}} End of configuration handling functions */
static void cj_submit (cj_t *db, cj_key_t *key, value_t *value) /* {{{ */
{
value_list_t vl = VALUE_LIST_INIT;
char *host;
vl.values = value;
vl.values_len = 1;
if ((db->host == NULL)
|| (strcmp ("", db->host) == 0)
|| (strcmp (CJ_DEFAULT_HOST, db->host) == 0))
host = hostname_g;
else
host = db->host;
if (key->instance == NULL)
{
if ((db->depth == 0) || (strcmp ("", db->state[db->depth-1].name) == 0))
sstrncpy (vl.type_instance, db->state[db->depth].name, sizeof (vl.type_instance));
else
ssnprintf (vl.type_instance, sizeof (vl.type_instance), "%s-%s",
db->state[db->depth-1].name, db->state[db->depth].name);
}
else
sstrncpy (vl.type_instance, key->instance, sizeof (vl.type_instance));
sstrncpy (vl.host, host, sizeof (vl.host));
sstrncpy (vl.plugin, "curl_json", sizeof (vl.plugin));
sstrncpy (vl.plugin_instance, db->instance, sizeof (vl.plugin_instance));
sstrncpy (vl.type, key->type, sizeof (vl.type));
plugin_dispatch_values (&vl);
} /* }}} int cj_submit */
static int cj_curl_perform (cj_t *db, CURL *curl) /* {{{ */
{
int status;
long rc;
char *url;
yajl_handle yprev = db->yajl;
db->yajl = yajl_alloc (&ycallbacks,
#if HAVE_YAJL_V2
/* alloc funcs = */ NULL,
#else
/* alloc funcs = */ NULL, NULL,
#endif
/* context = */ (void *)db);
if (db->yajl == NULL)
{
ERROR ("curl_json plugin: yajl_alloc failed.");
db->yajl = yprev;
return (-1);
}
url = NULL;
curl_easy_getinfo(curl, CURLINFO_EFFECTIVE_URL, &url);
status = curl_easy_perform (curl);
if (status != 0)
{
ERROR ("curl_json plugin: curl_easy_perform failed with status %i: %s (%s)",
status, db->curl_errbuf, (url != NULL) ? url : "<null>");
yajl_free (db->yajl);
db->yajl = yprev;
return (-1);
}
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &rc);
/* The response code is zero if a non-HTTP transport was used. */
if ((rc != 0) && (rc != 200))
{
ERROR ("curl_json plugin: curl_easy_perform failed with "
"response code %ld (%s)", rc, url);
yajl_free (db->yajl);
db->yajl = yprev;
return (-1);
}
#if HAVE_YAJL_V2
status = yajl_complete_parse(db->yajl);
#else
status = yajl_parse_complete(db->yajl);
#endif
if (status != yajl_status_ok)
{
unsigned char *errmsg;
errmsg = yajl_get_error (db->yajl, /* verbose = */ 0,
/* jsonText = */ NULL, /* jsonTextLen = */ 0);
ERROR ("curl_json plugin: yajl_parse_complete failed: %s",
(char *) errmsg);
yajl_free_error (db->yajl, errmsg);
yajl_free (db->yajl);
db->yajl = yprev;
return (-1);
}
yajl_free (db->yajl);
db->yajl = yprev;
return (0);
} /* }}} int cj_curl_perform */
static int cj_read (user_data_t *ud) /* {{{ */
{
cj_t *db;
if ((ud == NULL) || (ud->data == NULL))
{
ERROR ("curl_json plugin: cj_read: Invalid user data.");
return (-1);
}
db = (cj_t *) ud->data;
db->depth = 0;
memset (&db->state, 0, sizeof(db->state));
db->state[db->depth].tree = db->tree;
db->key = NULL;
return cj_curl_perform (db, db->curl);
} /* }}} int cj_read */
void module_register (void)
{
plugin_register_complex_config ("curl_json", cj_config);
} /* void module_register */
/* vim: set sw=2 sts=2 et fdm=marker : */
| 23.306872 | 88 | 0.595445 |
d10ed59a6c2b5701293f6a574ab4858db3279e56 | 3,849 | h | C | llama/include/llama/ll_database.h | D3LL15/dllama | 70b2308de84ea0ffb3718d670c234645bc787cdd | [
"BSD-3-Clause"
] | null | null | null | llama/include/llama/ll_database.h | D3LL15/dllama | 70b2308de84ea0ffb3718d670c234645bc787cdd | [
"BSD-3-Clause"
] | null | null | null | llama/include/llama/ll_database.h | D3LL15/dllama | 70b2308de84ea0ffb3718d670c234645bc787cdd | [
"BSD-3-Clause"
] | null | null | null | /*
* ll_database.h
* LLAMA Graph Analytics
*
* Copyright 2014
* The President and Fellows of Harvard College.
*
* Copyright 2014
* Oracle Labs.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE UNIVERSITY 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 UNIVERSITY 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.
*/
#ifndef LL_DATABASE_H_
#define LL_DATABASE_H_
#include <string>
#include <vector>
#include "llama/ll_common.h"
#include "llama/ll_config.h"
#include "llama/ll_persistent_storage.h"
/**
* The database
*/
class ll_database {
public:
/**
* Create a new database instance, or load it if it exists
*
* @param dir the database directory (if it is a persistent database)
*/
ll_database(const char* dir = NULL) {
omp_set_num_threads(omp_get_max_threads());
_dir = IFE_LL_PERSISTENCE(dir == NULL ? "db" : dir, "");
IF_LL_PERSISTENCE(_storage = new ll_persistent_storage(_dir.c_str()));
_graph = new ll_writable_graph(this, IF_LL_PERSISTENCE(_storage,)
80 * 1000000 /* XXX */);
}
/**
* Destroy the in-memory representation of the database instance
*/
virtual ~ll_database() {
delete _graph;
IF_LL_PERSISTENCE(delete _storage);
}
/**
* Set the number of OpenMP threads
*
* @param n the number of threads
*/
void set_num_threads(int n) {
// XXX This really belongs to some global runtime
omp_set_num_threads(n);
}
/**
* Get the database directory, if this is a persistent database
*
* @return the database directory, or NULL if not persistent
*/
inline const char* directory() {
return IFE_LL_PERSISTENCE(_dir.c_str(), NULL);
}
#ifdef LL_PERSISTENCE
/**
* Get the persistent storage
*
* @return the persistent storage
*/
inline ll_persistent_storage* storage() {
return _storage;
}
ll_persistent_storage* reset_storage() {
delete _storage;
_storage = new ll_persistent_storage(_dir.c_str());
return _storage;
}
#endif
/**
* Get the graph
*
* @return the graph
*/
inline ll_writable_graph* graph() {
return _graph;
}
/**
* Get the loader config
*
* @return the loader config
*/
inline ll_loader_config* loader_config() {
return &_loader_config;
}
private:
/// The graph
ll_writable_graph* _graph;
/// The persistent storage
IF_LL_PERSISTENCE(ll_persistent_storage* _storage);
/// The database directory
std::string _dir;
/// The loader configuration
ll_loader_config _loader_config;
};
#endif
| 24.05625 | 78 | 0.711613 |
2fbb22a274d332af822b798b4f42c3e2755b1bd3 | 3,498 | c | C | src/Wheel.c | jamesljlster/Wheel | 40f89143a02d356f320c431f796e5fe9c350a9f5 | [
"MIT"
] | null | null | null | src/Wheel.c | jamesljlster/Wheel | 40f89143a02d356f320c431f796e5fe9c350a9f5 | [
"MIT"
] | null | null | null | src/Wheel.c | jamesljlster/Wheel | 40f89143a02d356f320c431f796e5fe9c350a9f5 | [
"MIT"
] | null | null | null | #include <stdio.h>
#include <string.h>
#include <time.h>
#include <libserialport.h>
#include "Wheel.h"
#include "debug.h"
#define WCTRL_HEAD_CHAR 'W'
#define WCTRL_BUFLEN 7
#define WCTRL_RESP_STR "WOK"
#define DEFAULT_TIMEOUT 200
#define WCTRL_MIN_SPEED 0
#define WCTRL_MAX_SPEED 510
int WCTRL_Init(WCTRL* wheelCtrlPtr, const char* deviceName, int baudrate, int timeout)
{
int iResult;
int respStrLen;
char ctrlBuf[WCTRL_BUFLEN + 1] = {0};
struct sp_port* serialPort;
LOG("Using device: %s, baudrate: %d", deviceName, baudrate);
// Get Port
iResult = sp_get_port_by_name(deviceName, &serialPort);
if(iResult != SP_OK)
{
return WCTRL_SERIAL_FAILED;
}
// Open Port
iResult = sp_open(serialPort, SP_MODE_READ_WRITE);
if(iResult != SP_OK)
{
sp_free_port(serialPort);
return WCTRL_SERIAL_FAILED;
}
// Set Baudrate
iResult = sp_set_baudrate(serialPort, baudrate);
if(iResult != SP_OK)
{
sp_close(serialPort);
sp_free_port(serialPort);
return WCTRL_SERIAL_FAILED;
}
// Set Bits of Byte
iResult = sp_set_bits(serialPort, 8);
if(iResult != SP_OK)
{
sp_close(serialPort);
sp_free_port(serialPort);
return WCTRL_SERIAL_FAILED;
}
// Get response
respStrLen = strlen(WCTRL_RESP_STR);
iResult = sp_blocking_read(serialPort, ctrlBuf, respStrLen, timeout);
if(iResult > 0)
{
ctrlBuf[iResult] = '\0';
}
LOG("Receive: %s", ctrlBuf);
if(iResult != respStrLen)
{
LOG("Serial read timeout!");
return WCTRL_TIMEOUT;
}
// Check response
if(strcmp(ctrlBuf, WCTRL_RESP_STR) != 0)
{
return WCTRL_WRONG_RESPONSE;
}
// Set serial port reference
*wheelCtrlPtr = (WCTRL)serialPort;
return WCTRL_NO_ERROR;
}
int WCTRL_Control(WCTRL wheelCtrl, int leftSpeed, int rightSpeed, int timeout)
{
int iResult;
char ctrlBuf[WCTRL_BUFLEN + 1] = {0};
struct sp_port* serialPort = (struct sp_port*)wheelCtrl;
int timeLeft;
struct timespec timeHold, tmpTime;
int respStrLen;
// Check if speed all legal
if(leftSpeed < WCTRL_MIN_SPEED || leftSpeed > WCTRL_MAX_SPEED)
{
return WCTRL_ILLEGAL_ARGUMENT;
}
if(rightSpeed < WCTRL_MIN_SPEED || rightSpeed > WCTRL_MAX_SPEED)
{
return WCTRL_ILLEGAL_ARGUMENT;
}
// Process Control String
sprintf(ctrlBuf, "%c%03d%03d", WCTRL_HEAD_CHAR, leftSpeed, rightSpeed);
// Get current time
clock_gettime(CLOCK_MONOTONIC, &timeHold);
// Output Control String
iResult = sp_blocking_write(serialPort, ctrlBuf, WCTRL_BUFLEN, timeout);
if(iResult < 0)
{
return WCTRL_SERIAL_FAILED;
}
// Get response
respStrLen = strlen(WCTRL_RESP_STR);
clock_gettime(CLOCK_MONOTONIC, &tmpTime);
tmpTime.tv_sec = tmpTime.tv_sec - timeHold.tv_sec;
tmpTime.tv_nsec = tmpTime.tv_nsec - timeHold.tv_nsec;
timeLeft = timeout - (tmpTime.tv_sec * 1000 + tmpTime.tv_nsec / 1000000);
LOG("timeLeft = %d", timeLeft);
if(timeLeft <= 0)
{
return WCTRL_TIMEOUT;
}
iResult = sp_blocking_read(serialPort, ctrlBuf, respStrLen, timeLeft);
if(iResult > 0)
{
ctrlBuf[iResult] = '\0';
}
LOG("Receive: %s", ctrlBuf);
if(iResult != respStrLen)
{
LOG("Serial read timeout!");
return WCTRL_TIMEOUT;
}
// Check response
if(strcmp(ctrlBuf, WCTRL_RESP_STR) != 0)
{
return WCTRL_WRONG_RESPONSE;
}
return WCTRL_NO_ERROR;
}
int WCTRL_Close(WCTRL wheelCtrl)
{
int iResult;
struct sp_port* serialPort = (struct sp_port*)wheelCtrl;
// Closing and Free Port
iResult = sp_close(serialPort);
sp_free_port(serialPort);
if(iResult != SP_OK)
{
return WCTRL_SERIAL_FAILED;
}
return WCTRL_NO_ERROR;
}
| 20.337209 | 86 | 0.722127 |
18ffa86b6b45f34ab017389d42f9c523f5c0fa48 | 1,257 | h | C | src/include/util/releaseheap.h | dark0z/Hoard | 5afe855606e60ba255915d5cd816474815fc8844 | [
"ECL-2.0",
"Apache-2.0"
] | 827 | 2015-01-13T20:39:45.000Z | 2022-03-29T06:31:59.000Z | src/include/util/releaseheap.h | dark0z/Hoard | 5afe855606e60ba255915d5cd816474815fc8844 | [
"ECL-2.0",
"Apache-2.0"
] | 41 | 2015-01-25T21:37:58.000Z | 2022-03-15T09:10:24.000Z | src/include/util/releaseheap.h | dark0z/Hoard | 5afe855606e60ba255915d5cd816474815fc8844 | [
"ECL-2.0",
"Apache-2.0"
] | 107 | 2015-01-19T20:41:53.000Z | 2022-01-25T16:30:38.000Z | // -*- C++ -*-
/*
The Hoard Multiprocessor Memory Allocator
www.hoard.org
Author: Emery Berger, http://www.emeryberger.com
Copyright (c) 1998-2020 Emery Berger
See the LICENSE file at the top-level directory of this
distribution and at http://github.com/emeryberger/Hoard.
*/
#ifndef HOARD_RELEASEHEAP_H
#define HOARD_RELEASEHEAP_H
#if defined(_WIN32)
#include <windows.h>
#else
// Assume UNIX
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/mman.h>
#endif
#include "heaplayers.h"
// #include "sassert.h"
namespace Hoard {
template <class SuperHeap>
class ReleaseHeap : public SuperHeap {
public:
enum { Alignment = SuperHeap::Alignment };
ReleaseHeap() {
// This heap is only safe for use when its superheap delivers
// page-aligned memory. Otherwise, it would run the risk of
// releasing memory that is still in use.
sassert<(Alignment % 4096 == 0)> ObjectsMustBePageAligned;
}
inline void free (void * ptr) {
// Tell the OS it can release memory associated with this object.
MmapWrapper::release (ptr, SuperHeap::getSize(ptr));
// Now give it to the superheap.
SuperHeap::free (ptr);
}
};
}
#endif
| 20.95 | 71 | 0.677804 |
946c0838f72bbcb9c073e3b6d67f87f5e80e1e06 | 329 | h | C | audio/common.h | milkdropper/BeatDrop | 53d83ee29841e0ae11bc4bd85f67cb09594762a2 | [
"BSD-3-Clause"
] | 43 | 2018-11-13T15:37:36.000Z | 2022-02-24T07:47:25.000Z | audio/common.h | milkdropper/BeatDrop | 53d83ee29841e0ae11bc4bd85f67cb09594762a2 | [
"BSD-3-Clause"
] | 6 | 2019-02-15T17:52:01.000Z | 2021-11-01T19:35:45.000Z | audio/common.h | milkdropper/BeatDrop | 53d83ee29841e0ae11bc4bd85f67cb09594762a2 | [
"BSD-3-Clause"
] | 12 | 2018-12-04T05:17:43.000Z | 2022-01-20T23:49:56.000Z | // common.h
#include <stdio.h>
#include <windows.h>
#include <mmsystem.h>
#include <mmdeviceapi.h>
#include <audioclient.h>
#include <avrt.h>
#include <functiondiscoverykeys_devpkey.h>
#include <mutex>
#include "log.h"
#include "cleanup.h"
#include "prefs.h"
#include "loopback-capture.h"
#include "audiobuf.h"
| 19.352941 | 43 | 0.693009 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.