added
stringdate
2024-11-18 17:54:19
2024-11-19 03:39:31
created
timestamp[s]date
1970-01-01 00:04:39
2023-09-06 04:41:57
id
stringlengths
40
40
metadata
dict
source
stringclasses
1 value
text
stringlengths
13
8.04M
score
float64
2
4.78
int_score
int64
2
5
2024-11-18T17:55:23.219805+00:00
2021-04-29T13:54:41
d09fcdf1a27b8bc038d5283636241f72df2d0963
{ "blob_id": "d09fcdf1a27b8bc038d5283636241f72df2d0963", "branch_name": "refs/heads/master", "committer_date": "2021-04-30T06:13:20", "content_id": "5f1288abdc165e21b26842a032bf32d5b8c02997", "detected_licenses": [ "Apache-2.0" ], "directory_id": "969e182984952357a8c04365394d319ceac9bfd9", "extension": "c", "filename": "main.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 404705581, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2843, "license": "Apache-2.0", "license_type": "permissive", "path": "/LQ_CH32V103R8T6/3.用户手册/沁恒CH32V103/EVT/EXAM/TIM/One_Pulse/main.c", "provenance": "stackv2-0005.json.gz:15859", "repo_name": "88099981/omnidirectional", "revision_date": "2021-04-29T13:54:41", "revision_id": "aa3ca4eb13265edb3d2d9eb683853a779a39f7f8", "snapshot_id": "07087999036179ad9b8d17aa3ed2d10e6912fd25", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/88099981/omnidirectional/aa3ca4eb13265edb3d2d9eb683853a779a39f7f8/LQ_CH32V103R8T6/3.用户手册/沁恒CH32V103/EVT/EXAM/TIM/One_Pulse/main.c", "visit_date": "2023-07-22T11:02:44.828353" }
stackv2
/********************************** (C) COPYRIGHT ******************************* * File Name : main.c * Author : WCH * Version : V1.0.0 * Date : 2020/04/30 * Description : Main program body. *******************************************************************************/ #include "debug.h" /******************************************************************************* * Function Name : One_Pulse_Init * Description : Initializes TIM1 one pulse. * Input : arr: the period value. * psc: the prescaler value. * ccp: the pulse value. * Return : None *******************************************************************************/ void One_Pulse_Init( u16 arr, u16 psc, u16 ccp ) { GPIO_InitTypeDef GPIO_InitStructure; TIM_OCInitTypeDef TIM_OCInitStructure; TIM_ICInitTypeDef TIM_ICInitStructure; TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructure; RCC_APB2PeriphClockCmd( RCC_APB2Periph_GPIOA, ENABLE ); RCC_APB1PeriphClockCmd( RCC_APB1Periph_TIM2, ENABLE ); GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_Init( GPIOA, &GPIO_InitStructure ); GPIO_InitStructure.GPIO_Pin = GPIO_Pin_1; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPD; GPIO_Init( GPIOA, &GPIO_InitStructure); TIM_TimeBaseInitStructure.TIM_Period = arr; TIM_TimeBaseInitStructure.TIM_Prescaler = psc; TIM_TimeBaseInitStructure.TIM_ClockDivision = TIM_CKD_DIV1; TIM_TimeBaseInitStructure.TIM_CounterMode = TIM_CounterMode_Up; TIM_TimeBaseInit( TIM2, &TIM_TimeBaseInitStructure); TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM2; TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable; TIM_OCInitStructure.TIM_Pulse = ccp; TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High; TIM_OC1Init( TIM2, &TIM_OCInitStructure ); TIM_ICStructInit( &TIM_ICInitStructure ); TIM_ICInitStructure.TIM_Channel = TIM_Channel_2; TIM_ICInitStructure.TIM_ICPrescaler = TIM_ICPSC_DIV1; TIM_ICInitStructure.TIM_ICFilter = 0x00; TIM_ICInitStructure.TIM_ICPolarity = TIM_ICPolarity_Rising; TIM_ICInitStructure.TIM_ICSelection = TIM_ICSelection_DirectTI; TIM_ICInit( TIM2, &TIM_ICInitStructure ); TIM_SelectOnePulseMode( TIM2,TIM_OPMode_Single ); TIM_SelectInputTrigger( TIM2, TIM_TS_TI2FP2 ); TIM_SelectSlaveMode( TIM2, TIM_SlaveMode_Trigger ); } /******************************************************************************* * Function Name : main * Description : Main program. * Input : None * Return : None *******************************************************************************/ int main(void) { USART_Printf_Init(115200); printf("SystemClk:%d\r\n",SystemCoreClock); One_Pulse_Init( 200, 48000-1, 100 ); while(1); }
2.609375
3
2024-11-18T17:55:24.574495+00:00
2020-01-30T15:52:16
c45c1157497baecce10404af7c4d2d1c664336e2
{ "blob_id": "c45c1157497baecce10404af7c4d2d1c664336e2", "branch_name": "refs/heads/master", "committer_date": "2020-01-30T15:52:16", "content_id": "3d5b0c702cc57bb04ae266e75cb913661d7a6122", "detected_licenses": [ "MIT" ], "directory_id": "40de3da30239862f11a946166b50438174c2fd4e", "extension": "c", "filename": "shaldrin.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 237240459, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1585, "license": "MIT", "license_type": "permissive", "path": "/lib/wizards/garath/dguild/shaldrin.c", "provenance": "stackv2-0005.json.gz:16243", "repo_name": "vlehtola/questmud", "revision_date": "2020-01-30T15:52:16", "revision_id": "8bc3099b5ad00a9e0261faeb6637c76b521b6dbe", "snapshot_id": "f53b7205351f30e846110300d60b639d52d113f8", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/vlehtola/questmud/8bc3099b5ad00a9e0261faeb6637c76b521b6dbe/lib/wizards/garath/dguild/shaldrin.c", "visit_date": "2020-12-23T19:59:44.886028" }
stackv2
// Haste // // 12.04.02 - Garath int get_time(string str) { return random(2)+10; } int ep_cost() { return 150; } status resolve_skill(string str) { int dama; write("You mumble 's"'s stomach with a nasty sound!\n"); tell_object(target, this_player()->query_name()+ " brutally kicks you in the stomach! OUCH!\n"); say(capitalize(this_player()->query_name()) + " kicks "+ capitalize(target->query_name()) + " in the stomach!\n", target); } if(dama > 40) { dama=40; } if(this_player()->query_attack() != target) this_player()->attack_object(target); target->hit_with_spell(dama, "physical"); /* DISABLED due to abuse //Celtron if(!random(1000)) { this_player()->set_mastery("Offensive maneuvers",(this_player()->query_mastery()["Offensive maneuvers"] + 1)); } dama += (this_player()->query_mastery()["Offensive maneuvers"]/10); */ } fail_skill(str) { object target; if(!str) { write("Use kick at who?\n"); return 1; } if(random(100) < this_player()->query_skills("kick")) { resolve_skill(str); return 1; } target = present(str, environment(this_player())); if (!target) { write("You fail the skill.\n"); return; } write("You try to kick " + target->query_name() + ", but miss.\n"); tell_object(target, this_player()->query_name() + " tries to KICK you, but misses.\n"); say(capitalize(this_player()->query_name()) + " tries to kick " + target->query_name() + ", but misses.\n", target); target->attack_object(this_player()); this_player()->attack_object(target); }
2.0625
2
2024-11-18T17:55:24.637287+00:00
2017-05-10T09:50:21
18049c9864fdc075c49635c971b0aaa20003054b
{ "blob_id": "18049c9864fdc075c49635c971b0aaa20003054b", "branch_name": "refs/heads/arm", "committer_date": "2017-05-10T14:22:48", "content_id": "9ecb3d8591c00b8e686c215ce4cfa84eeb4fe76e", "detected_licenses": [ "Apache-2.0" ], "directory_id": "6af50a4b5b928211880dd9f1c6ce92c2afea828b", "extension": "c", "filename": "main.c", "fork_events_count": 0, "gha_created_at": "2016-12-16T09:52:08", "gha_event_created_at": "2020-02-04T19:16:46", "gha_language": "C", "gha_license_id": "Apache-2.0", "github_id": 76642373, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 8038, "license": "Apache-2.0", "license_type": "permissive", "path": "/tests/kernel/workq/work_queue/src/main.c", "provenance": "stackv2-0005.json.gz:16371", "repo_name": "erwango/zephyr", "revision_date": "2017-05-10T09:50:21", "revision_id": "162f4574c781ae17d3fecfd4ac10df111e90ae3c", "snapshot_id": "1c7aa447f613de76439291ba9dde1e4dc7c5786e", "src_encoding": "UTF-8", "star_events_count": 6, "url": "https://raw.githubusercontent.com/erwango/zephyr/162f4574c781ae17d3fecfd4ac10df111e90ae3c/tests/kernel/workq/work_queue/src/main.c", "visit_date": "2023-08-11T10:29:20.031948" }
stackv2
/* * Copyright (c) 2016 Intel Corporation * * SPDX-License-Identifier: Apache-2.0 */ #include <stdbool.h> #include <zephyr.h> #include <tc_util.h> #include <misc/util.h> #include <misc/nano_work.h> #define NUM_TEST_ITEMS 6 /* Each work item takes 100ms */ #define WORK_ITEM_WAIT 100 /* * Wait 50ms between work submissions, to ensure co-op and prempt * preempt thread submit alternatively. */ #define SUBMIT_WAIT 50 #define STACK_SIZE 1024 struct test_item { int key; struct k_delayed_work work; }; static char __stack co_op_stack[STACK_SIZE]; static struct test_item tests[NUM_TEST_ITEMS]; static int results[NUM_TEST_ITEMS]; static int num_results; static void work_handler(struct k_work *work) { struct test_item *ti = CONTAINER_OF(work, struct test_item, work); TC_PRINT(" - Running test item %d\n", ti->key); k_sleep(WORK_ITEM_WAIT); results[num_results++] = ti->key; } static void test_items_init(void) { int i; for (i = 0; i < NUM_TEST_ITEMS; i++) { tests[i].key = i + 1; k_work_init(&tests[i].work.work, work_handler); } } static void coop_work_main(int arg1, int arg2) { int i; ARG_UNUSED(arg1); ARG_UNUSED(arg2); /* Let the preempt thread submit the first work item. */ k_sleep(SUBMIT_WAIT / 2); for (i = 1; i < NUM_TEST_ITEMS; i += 2) { TC_PRINT(" - Submitting work %d from coop thread\n", i + 1); k_work_submit(&tests[i].work.work); k_sleep(SUBMIT_WAIT); } } static void test_items_submit(void) { int i; k_thread_spawn(co_op_stack, STACK_SIZE, (k_thread_entry_t)coop_work_main, NULL, NULL, NULL, K_PRIO_COOP(10), 0, 0); for (i = 0; i < NUM_TEST_ITEMS; i += 2) { TC_PRINT(" - Submitting work %d from preempt thread\n", i + 1); k_work_submit(&tests[i].work.work); k_sleep(SUBMIT_WAIT); } } static int check_results(int num_tests) { int i; if (num_results != num_tests) { TC_ERROR("*** work items finished: %d (expected: %d)\n", num_results, num_tests); return TC_FAIL; } for (i = 0; i < num_tests; i++) { if (results[i] != i + 1) { TC_ERROR("*** got result %d in position %d" " (expected %d)\n", results[i], i, i + 1); return TC_FAIL; } } return TC_PASS; } static int test_sequence(void) { TC_PRINT("Starting sequence test\n"); TC_PRINT(" - Initializing test items\n"); test_items_init(); TC_PRINT(" - Submitting test items\n"); test_items_submit(); TC_PRINT(" - Waiting for work to finish\n"); k_sleep((NUM_TEST_ITEMS + 1) * WORK_ITEM_WAIT); TC_PRINT(" - Checking results\n"); return check_results(NUM_TEST_ITEMS); } static void reset_results(void) { int i; for (i = 0; i < NUM_TEST_ITEMS; i++) results[i] = 0; num_results = 0; } static void resubmit_work_handler(struct k_work *work) { struct test_item *ti = CONTAINER_OF(work, struct test_item, work); k_sleep(WORK_ITEM_WAIT); results[num_results++] = ti->key; if (ti->key < NUM_TEST_ITEMS) { ti->key++; TC_PRINT(" - Resubmitting work\n"); k_work_submit(work); } } static int test_resubmit(void) { TC_PRINT("Starting resubmit test\n"); tests[0].key = 1; tests[0].work.work.handler = resubmit_work_handler; TC_PRINT(" - Submitting work\n"); k_work_submit(&tests[0].work.work); TC_PRINT(" - Waiting for work to finish\n"); k_sleep((NUM_TEST_ITEMS + 1) * WORK_ITEM_WAIT); TC_PRINT(" - Checking results\n"); return check_results(NUM_TEST_ITEMS); } static void delayed_work_handler(struct k_work *work) { struct test_item *ti = CONTAINER_OF(work, struct test_item, work); TC_PRINT(" - Running delayed test item %d\n", ti->key); results[num_results++] = ti->key; } static void test_delayed_init(void) { int i; for (i = 0; i < NUM_TEST_ITEMS; i++) { tests[i].key = i + 1; k_delayed_work_init(&tests[i].work, delayed_work_handler); } } static void coop_delayed_work_main(int arg1, int arg2) { int i; ARG_UNUSED(arg1); ARG_UNUSED(arg2); /* Let the preempt thread submit the first work item. */ k_sleep(SUBMIT_WAIT / 2); for (i = 1; i < NUM_TEST_ITEMS; i += 2) { TC_PRINT(" - Submitting delayed work %d from" " coop thread\n", i + 1); k_delayed_work_submit(&tests[i].work, (i + 1) * WORK_ITEM_WAIT); } } static int test_delayed_submit(void) { int i; k_thread_spawn(co_op_stack, STACK_SIZE, (k_thread_entry_t)coop_delayed_work_main, NULL, NULL, NULL, K_PRIO_COOP(10), 0, 0); for (i = 0; i < NUM_TEST_ITEMS; i += 2) { TC_PRINT(" - Submitting delayed work %d from" " preempt thread\n", i + 1); if (k_delayed_work_submit(&tests[i].work, (i + 1) * WORK_ITEM_WAIT)) { return TC_FAIL; } } return TC_PASS; } static void coop_delayed_work_cancel_main(int arg1, int arg2) { ARG_UNUSED(arg1); ARG_UNUSED(arg2); k_delayed_work_submit(&tests[1].work, WORK_ITEM_WAIT); TC_PRINT(" - Cancel delayed work from coop thread\n"); k_delayed_work_cancel(&tests[1].work); } static int test_delayed_cancel(void) { TC_PRINT("Starting delayed cancel test\n"); k_delayed_work_submit(&tests[0].work, WORK_ITEM_WAIT); TC_PRINT(" - Cancel delayed work from preempt thread\n"); k_delayed_work_cancel(&tests[0].work); k_thread_spawn(co_op_stack, STACK_SIZE, (k_thread_entry_t)coop_delayed_work_cancel_main, NULL, NULL, NULL, K_PRIO_COOP(10), 0, 0); TC_PRINT(" - Waiting for work to finish\n"); k_sleep(2 * WORK_ITEM_WAIT); TC_PRINT(" - Checking results\n"); return check_results(0); } static void delayed_resubmit_work_handler(struct k_work *work) { struct test_item *ti = CONTAINER_OF(work, struct test_item, work); results[num_results++] = ti->key; if (ti->key < NUM_TEST_ITEMS) { ti->key++; TC_PRINT(" - Resubmitting delayed work\n"); k_delayed_work_submit(&ti->work, WORK_ITEM_WAIT); } } static int test_delayed_resubmit(void) { TC_PRINT("Starting delayed resubmit test\n"); tests[0].key = 1; k_delayed_work_init(&tests[0].work, delayed_resubmit_work_handler); TC_PRINT(" - Submitting delayed work\n"); k_delayed_work_submit(&tests[0].work, WORK_ITEM_WAIT); TC_PRINT(" - Waiting for work to finish\n"); k_sleep((NUM_TEST_ITEMS + 1) * WORK_ITEM_WAIT); TC_PRINT(" - Checking results\n"); return check_results(NUM_TEST_ITEMS); } static void coop_delayed_work_resubmit(int arg1, int arg2) { int i; ARG_UNUSED(arg1); ARG_UNUSED(arg2); for (i = 0; i < NUM_TEST_ITEMS; i++) { volatile u32_t uptime; TC_PRINT(" - Resubmitting delayed work with 1 ms\n"); k_delayed_work_submit(&tests[0].work, 1); /* Busy wait 1 ms to force a clash with workqueue */ uptime = k_uptime_get_32(); while (k_uptime_get_32() == uptime) { } } } static int test_delayed_resubmit_fiber(void) { TC_PRINT("Starting delayed resubmit from coop thread test\n"); tests[0].key = 1; k_delayed_work_init(&tests[0].work, delayed_work_handler); k_thread_spawn(co_op_stack, STACK_SIZE, (k_thread_entry_t)coop_delayed_work_resubmit, NULL, NULL, NULL, K_PRIO_COOP(10), 0, 0); TC_PRINT(" - Waiting for work to finish\n"); k_sleep(NUM_TEST_ITEMS + 1); TC_PRINT(" - Checking results\n"); return check_results(1); } static int test_delayed(void) { TC_PRINT("Starting delayed test\n"); TC_PRINT(" - Initializing delayed test items\n"); test_delayed_init(); TC_PRINT(" - Submitting delayed test items\n"); if (test_delayed_submit() != TC_PASS) { return TC_FAIL; } TC_PRINT(" - Waiting for delayed work to finish\n"); k_sleep((NUM_TEST_ITEMS + 2) * WORK_ITEM_WAIT); TC_PRINT(" - Checking results\n"); return check_results(NUM_TEST_ITEMS); } void main(void) { int status = TC_FAIL; if (test_sequence() != TC_PASS) { goto end; } reset_results(); if (test_resubmit() != TC_PASS) { goto end; } reset_results(); if (test_delayed() != TC_PASS) { goto end; } reset_results(); if (test_delayed_resubmit() != TC_PASS) { goto end; } reset_results(); if (test_delayed_resubmit_fiber() != TC_PASS) { goto end; } reset_results(); if (test_delayed_cancel() != TC_PASS) { goto end; } status = TC_PASS; end: TC_END_RESULT(status); TC_END_REPORT(status); }
2.703125
3
2024-11-18T17:55:24.781764+00:00
2017-04-23T09:47:28
fbd4c07c99bdb98651f8cd5cbff0481cd1402a51
{ "blob_id": "fbd4c07c99bdb98651f8cd5cbff0481cd1402a51", "branch_name": "refs/heads/master", "committer_date": "2017-04-23T09:47:28", "content_id": "8536938a9b28628e02ca93c203f8cdd7153103a4", "detected_licenses": [ "Apache-2.0" ], "directory_id": "ea063b8bf34f7ef86050498a890be7b6b150a2e7", "extension": "c", "filename": "ikvmemcache.c", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 65516584, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 7657, "license": "Apache-2.0", "license_type": "permissive", "path": "/code/foundation/util/ikvmemcache.c", "provenance": "stackv2-0005.json.gz:16628", "repo_name": "JerryZhou/isee", "revision_date": "2017-04-23T09:47:28", "revision_id": "4d1413f9920098dec95fcfe6608bdc8be91fccb1", "snapshot_id": "7581a2b5c7b3ba0e9e8f8065b8be4aea4504bd3b", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/JerryZhou/isee/4d1413f9920098dec95fcfe6608bdc8be91fccb1/code/foundation/util/ikvmemcache.c", "visit_date": "2020-04-15T12:43:39.776957" }
stackv2
#include "foundation/util/ikvmemcache.h" #include "foundation/container/idict.h" #include "foundation/container/ireflist.h" /* make a cache */ ikvmemcache* ikvmemcachemake(size_t capacity) { ikvmemcache *cache = irefnew(ikvmemcache); cache->dict = idictmake(capacity>>3); cache->lru = ireflistmake(); return cache; } /* destructor */ void ikvmemcache_destructor(const struct imeta* meta, iptr o) { ikvmemcache* cache = icast(ikvmemcache, o); ikvmemcacheclear(cache); iassign(cache->lru, NULL); iassign(cache->dict, NULL); } /* clear all the node in the cache*/ void ikvmemcacheclear(ikvmemcache* cache) { ireflistremoveall(cache->lru); idictremoveall(cache->dict); } /* get the cache-size */ size_t ikvmemcachesize(const ikvmemcache *cache) { icheckret(cache, 0); return idictsize(cache->dict); } /* should update the weight */ static int _ikvmemcacheweight_change(ikvmemcache* cache, const ivar *key, ivar *oldvalue, ivar *newvalue) { icheckret(cache && oldvalue != newvalue, iino); icheckret(cache->fnweight, iino); icheckret(iflag_is(cache->flag, EnumKvMemCacheFlag_Weighted), iino); size_t oldweight = cache->weight; if (oldvalue) { cache->weight -= cache->fnweight(cache, key, oldvalue); } if (newvalue) { cache->weight += cache->fnweight(cache, key, newvalue); } return cache->weight > oldweight; } /* basic remove-entry */ void _ikvmemcache_remove_entry(ikvmemcache* cache, idictentry *entry) { /* remove from the lru */ irefjoint* joint = icast(irefjoint, entry->u); ireflistremovejoint(cache->lru, joint); /* update the weight */ _ikvmemcacheweight_change(cache, &entry->key, &entry->value, NULL); /* remove from the dict */ idictremoveentry(cache->dict, entry, NULL); } /* typedef the range-trim */ typedef int (*_ikv_range_end) (ikvmemcache* cache, size_t size); typedef void (*_ikv_range_eval) (ikvmemcache*cache, idictentry *entry); /* the only one ref */ static int _ikvmemcache_refone(idictentry *entry) { icheckret(entry, iiyes); if (!ivarissimple(&entry->value)) { irefptr ref = ivarcast(&entry->value, irefptr); return ref->_ref == 1; } return iino; } static size_t _ikvmemcache_trim_to(ikvmemcache* cache, size_t size, _ikv_range_end end, _ikv_range_eval eval) { icheckret(end && end(cache, size), 0); /*double-linked-list in circle */ irefjoint* node = ireflistlast(cache->lru); irefjoint* pre = NULL; int rangelimit = idictsize(cache->dict); idictentry* entry = NULL; size_t count = 0; /* the trimed-cache */ idict* toremoved = NULL; if (cache->fnenvicted && !iflag_is(cache->flag, EnumKvMemCacheFlag_SkipEnvicted)) { toremoved = idictmake(8); } /* reverse the lru-list */ while (end(cache, size) && rangelimit > 0) { if (node) { pre = node->pre; entry = icast(idictentry, node->value); if (!iflag_is(cache->flag, EnumKvMemCacheFlag_NotTrimTheRetained) || /* no need to track the retain */ (_ikvmemcache_refone(entry))) { /* track the retain-count is less equal than 1 */ /* the eval */ if (eval) { eval(cache, entry); } /* remove from the cache */ _ikvmemcache_remove_entry(cache, entry); /* the count ++ */ ++count; } /* pre-node */ node = pre; } else { break; } --rangelimit; } /* the triming call-back */ if (toremoved) { cache->fnenvicted(cache, toremoved); irefdelete(toremoved); } return count; } /* end the count of kv */ static int _ikv_end_count(ikvmemcache *cache, size_t size) { return idictsize(cache->dict) > size; } /* trim the cache to right size, return the trimed object counts */ size_t ikvmemcachetrimcount(ikvmemcache* cache, size_t trim) { return _ikvmemcache_trim_to(cache, trim, _ikv_end_count, NULL); } /* end the weight of kv */ static int _ikv_end_weight(ikvmemcache *cache, size_t size) { return cache->weight > size; } /* the weight-val */ size_t ikvmemcachetrimweight(ikvmemcache* cache, size_t weight) { return _ikvmemcache_trim_to(cache, weight, _ikv_end_weight, NULL); } /* update the joint in lru */ static void _ikvmemcacheupdateentry(ikvmemcache* cache, idictentry *entry) { irefjoint* joint = icast(irefjoint, entry->u); iretain(joint); ireflistremovejoint(cache->lru, joint); ireflistaddjoint(cache->lru, joint); irelease(joint); } /* should update the weight */ static void _ikvmemcacheweighteval(ikvmemcache* cache, const ivar *key, ivar *oldvalue, ivar *newvalue) { /* the truly weight cacl */ int changelager = _ikvmemcacheweight_change(cache, key, oldvalue, newvalue); /* the weight eval-trim */ if (changelager && iflag_is(cache->flag, EnumKvMemCacheFlag_AutoTrimToWeightCapacity)) { ikvmemcachetrimweight(cache, cache->capacityweight); } } /* get the value of cache, not need to release for ivar */ struct ivar * ikvmemcacheget(const ikvmemcache* cache, const struct ivar* key) { idictentry* entry = idictentryof(cache->dict, key); if (entry) { _ikvmemcacheupdateentry((ikvmemcache*)cache, entry); return &entry->value; } return NULL; } /* put the ivar in key */ int ikvmemcacheput(struct ikvmemcache* cache, const struct ivar *key, struct ivar *value) { idictentry* entry = idictentryof(cache->dict, key); int exits = iino; int changelager = iino; if (!entry) { entry = idictadd(cache->dict, key, value); entry->u = ireflistadd(cache->lru, irefcast(entry)); /* update the weight */ changelager = _ikvmemcacheweight_change(cache, key, NULL, value); } else { exits = iiok; /* resign the old-value */ ivar *oldvalue = ivardup(&entry->value); /* set the value*/ idictentysetvalue(entry, value); /* update the joint in lru */ _ikvmemcacheupdateentry((ikvmemcache*)cache, entry); /* update the weight */ changelager = _ikvmemcacheweight_change(cache, key, oldvalue, value); /* release the old-value */ iobjfree(oldvalue); } /* if add object and the flag is auto-triming */ if (!exits && iflag_is(cache->flag, EnumKvMemCacheFlag_AutoTrimToCountCapacity)) { ikvmemcachetrimcount(cache, cache->capacitycount); } /* the weight eval-trim */ if (changelager && iflag_is(cache->flag, EnumKvMemCacheFlag_AutoTrimToWeightCapacity)) { ikvmemcachetrimweight(cache, cache->capacityweight); } return exits; } /* remove the cache for key */ int ikvmemcacheremove(ikvmemcache* cache, const struct ivar *key) { idictentry* entry = idictentryof(cache->dict, key); if (entry) { _ikvmemcache_remove_entry(cache, entry); } return entry != NULL; } /* all keys in LRU-order returned in @param keys, return the keys-count */ size_t ikvmemcachekeys(const ikvmemcache* cache, struct iarray *keys) { irefjoint* joint = ireflistfirst(cache->lru); while (joint) { idictentry *entry = icast(idictentry, joint->value); if (entry) { iarrayadd(keys, &entry->key); } joint = joint->next; } return iarraylen(keys); }
2.265625
2
2024-11-18T17:55:24.869021+00:00
2016-04-26T09:14:42
55621d96769c73c6c6ef9bc2b25f90f82cab4b7c
{ "blob_id": "55621d96769c73c6c6ef9bc2b25f90f82cab4b7c", "branch_name": "refs/heads/master", "committer_date": "2016-04-26T09:14:42", "content_id": "f620eadfdb2b418df2b8b1b75f8698aa5f150b07", "detected_licenses": [ "MIT" ], "directory_id": "cdff64d5f1586e6de5f125c162f4807bc1b4ea4b", "extension": "h", "filename": "io.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2181, "license": "MIT", "license_type": "permissive", "path": "/include/qiniu/io.h", "provenance": "stackv2-0005.json.gz:16756", "repo_name": "caedmom/c-sdk-for-windows", "revision_date": "2016-04-26T09:14:42", "revision_id": "2823608ba1025a8aab1be0adcafa3ff14096ec55", "snapshot_id": "d17099418eb5f8fe24ff27e4486d54406115c463", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/caedmom/c-sdk-for-windows/2823608ba1025a8aab1be0adcafa3ff14096ec55/include/qiniu/io.h", "visit_date": "2021-01-12T00:24:55.319912" }
stackv2
/* ============================================================================ Name : io.h Author : Qiniu.com Copyright : 2012(c) Shanghai Qiniu Information Technologies Co., Ltd. Description : ============================================================================ */ #ifndef QINIU_IO_H #define QINIU_IO_H #include "http.h" #pragma pack(1) /*============================================================================*/ /* type Qiniu_Io_PutExtra */ typedef struct _Qiniu_Io_PutExtraParam { const char* key; // 必须以 "x:" 开始 const char* value; struct _Qiniu_Io_PutExtraParam* next; } Qiniu_Io_PutExtraParam; typedef struct _Qiniu_Io_PutExtra { Qiniu_Io_PutExtraParam* params; const char* mimeType; // 可选。在 uptoken 没有指定 DetectMime 时,用户客户端可自己指定 MimeType Qiniu_Uint32 crc32; Qiniu_Uint32 checkCrc32; // CheckCrc == 0: 表示不进行 crc32 校验 // CheckCrc == 1: 对于 Put 等同于 CheckCrc = 2;对于 PutFile 会自动计算 crc32 值 // CheckCrc == 2: 表示进行 crc32 校验,且 crc32 值就是上面的 Crc32 变量 } Qiniu_Io_PutExtra; /*============================================================================*/ /* type Qiniu_Io_PutRet */ typedef struct _Qiniu_Io_PutRet { const char* hash; // 如果 uptoken 没有指定 ReturnBody,那么返回值是标准的 PutRet 结构 const char* key; // 如果传入的key未指定(UNDEFINED_KEY),那么返回服务端自动生成的key } Qiniu_Io_PutRet; /*============================================================================*/ /* func Qiniu_Io_PutXXX */ #ifndef QINIU_UNDEFINED_KEY #define QINIU_UNDEFINED_KEY NULL #endif Qiniu_Error Qiniu_Io_PutFile( Qiniu_Client* self, Qiniu_Io_PutRet* ret, const char* uptoken, const char* key, const char* localFile, Qiniu_Io_PutExtra* extra); Qiniu_Error Qiniu_Io_PutBuffer( Qiniu_Client* self, Qiniu_Io_PutRet* ret, const char* uptoken, const char* key, const char* buf, size_t fsize, Qiniu_Io_PutExtra* extra); /*============================================================================*/ #pragma pack() #endif // QINIU_IO_H
2
2
2024-11-18T17:55:24.932970+00:00
2013-04-05T05:16:08
176f5628ee7faee66abf850a0a04fda2039d6506
{ "blob_id": "176f5628ee7faee66abf850a0a04fda2039d6506", "branch_name": "refs/heads/master", "committer_date": "2013-04-05T05:16:08", "content_id": "9824a4b7f1c7d5e038ad5d38268e3b5914de93d1", "detected_licenses": [ "MIT" ], "directory_id": "f59ac8cc7a86c3010c539aa1ad67f1ceb5f6994c", "extension": "c", "filename": "unsetf.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 6755812, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 930, "license": "MIT", "license_type": "permissive", "path": "/test/unsetf.c", "provenance": "stackv2-0005.json.gz:16885", "repo_name": "ldionne/cisp", "revision_date": "2013-04-05T05:16:08", "revision_id": "8a55989c17249e5892c944899eb2c748df41081d", "snapshot_id": "4fe3efb117eb461703a8cdcb34086815026b6971", "src_encoding": "UTF-8", "star_events_count": 7, "url": "https://raw.githubusercontent.com/ldionne/cisp/8a55989c17249e5892c944899eb2c748df41081d/test/unsetf.c", "visit_date": "2021-03-12T21:23:43.274981" }
stackv2
/** * This file contains unit tests for the `UNSETF` family of macros. */ #include <cisp/unsetf.h> #include <cisp/defclass.h> #include <cisp/setf.h> #define type CISP_DEFCLASS((setf b b) (setf c c) (setf d ~ ~ ~)) #define CISP_TOKEN_field (f i e l d) #define CISP_TOKEN_field2 (f i e l d 2) [[[ CISP_UNSETF(type, b) == CISP_DEFCLASS((setf c c) (setf d ~ ~ ~)) CISP_UNSETF(type, g) == type CISP_UNSETF(CISP_I_EMPTY_TYPE(), b) == CISP_I_EMPTY_TYPE() /* should replace the first matching field only */ CISP_UNSETF((CISP_FIELD(b, b)) (CISP_FIELD(b, b)), b) == (CISP_FIELD(b, b)) /* should work on field with a non C identifier value */ CISP_UNSETF(type, d) == CISP_DEFCLASS((setf b b) (setf c c)) /* should work with long tokens */ CISP_UNSETF(CISP_DEFCLASS((setf field value)), field) == CISP_I_EMPTY_TYPE() CISP_UNSETF(CISP_DEFCLASS((setf field value) (setf field2 value2)), field) == CISP_DEFCLASS((setf field2 value2)) ]]]
2.453125
2
2024-11-18T17:55:25.066493+00:00
2019-10-07T11:25:06
c0e3670c9fa05f1ec3607dbb56a0d14a4f834b19
{ "blob_id": "c0e3670c9fa05f1ec3607dbb56a0d14a4f834b19", "branch_name": "refs/heads/version1", "committer_date": "2019-10-07T11:25:06", "content_id": "d9dd8723a8b9365e9abe445aa2af7fb8bb072c31", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "e33831bae98bfc2191b7044f6df445c5f51f1226", "extension": "c", "filename": "fork1.c", "fork_events_count": 0, "gha_created_at": "2017-08-24T14:34:26", "gha_event_created_at": "2019-10-07T11:25:07", "gha_language": "Java", "gha_license_id": "BSD-3-Clause", "github_id": 101304652, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 91, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/languages/cprogs/fork1.c", "provenance": "stackv2-0005.json.gz:17013", "repo_name": "mimikaan/learntosolveit", "revision_date": "2019-10-07T11:25:06", "revision_id": "22022a70d3405b1b9a248d35ea3f0aab4135eace", "snapshot_id": "6dfae0bdb656d529956e5212446f431fe80d34ac", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/mimikaan/learntosolveit/22022a70d3405b1b9a248d35ea3f0aab4135eace/languages/cprogs/fork1.c", "visit_date": "2021-06-25T19:33:36.848098" }
stackv2
#include <stdio.h> int main() { int pid; pid = fork(); printf("%d \n",pid); }
2
2
2024-11-18T17:55:25.297544+00:00
2023-09-02T14:55:31
abe06e108636f38a56fa75b8c95613c8ba4edd6f
{ "blob_id": "abe06e108636f38a56fa75b8c95613c8ba4edd6f", "branch_name": "refs/heads/master", "committer_date": "2023-09-02T14:55:31", "content_id": "66b06d1160fbc72c0b81a369c6dd48038ddff62e", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "8838eb997879add5759b6dfb23f9a646464e53ca", "extension": "h", "filename": "math.h", "fork_events_count": 325, "gha_created_at": "2015-03-29T15:27:48", "gha_event_created_at": "2023-09-14T16:58:34", "gha_language": "C", "gha_license_id": "BSD-2-Clause", "github_id": 33078138, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1563, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/third-party/bsp/multiclet/include/math.h", "provenance": "stackv2-0005.json.gz:17397", "repo_name": "embox/embox", "revision_date": "2023-09-02T14:55:31", "revision_id": "98e3c06e33f3fdac10a29c069c20775568e0a6d1", "snapshot_id": "d6aacec876978522f01cdc4b8de37a668c6f4c80", "src_encoding": "UTF-8", "star_events_count": 1087, "url": "https://raw.githubusercontent.com/embox/embox/98e3c06e33f3fdac10a29c069c20775568e0a6d1/third-party/bsp/multiclet/include/math.h", "visit_date": "2023-09-04T03:02:20.165042" }
stackv2
#ifndef STDMATH #define STDMATH /* http://www.gnu.org/software/glibc/) */ #define M_E 2.7182818284590452354 /* e */ #define M_LOG2E 1.4426950408889634074 /* log_2 e */ #define M_LOG10E 0.43429448190325182765 /* log_10 e */ #define M_LN2 0.69314718055994530942 /* log_e 2 */ #define M_LN10 2.30258509299404568402 /* log_e 10 */ #define M_PI 3.14159265358979323846 /* pi */ #define M_PI_2 1.57079632679489661923 /* pi/2 */ #define M_PI_4 0.78539816339744830962 /* pi/4 */ #define M_1_PI 0.31830988618379067154 /* 1/pi */ #define M_2_PI 0.63661977236758134308 /* 2/pi */ #define M_2_SQRTPI 1.12837916709551257390 /* 2/sqrt(pi) */ #define M_SQRT2 1.41421356237309504880 /* sqrt(2) */ #define M_SQRT1_2 0.70710678118654752440 /* 1/sqrt(2) */ float sinf(float angle); float cosf(float angle); float tanf(float angle); float atanf(float arg); float expf(float x); float logf(float x); float log10f(float x); float sqrtf(float x); float powf(float x, float y); float frexpf(float x, int *exp); float ldexp(float x, int exp); float modff(float x, float *iptr); int mxmulf(unsigned N, float *R, float *A, float *B); #define floor(x) (((float)(int)(x))<(x))?((float)(int)(x)):((float)((int)(x)-1)) #define acos(x) (M_PI_2-atanf((x)/sqrtf(1-(x)*(x)))) #define cos(x) cosf(x) #define sqrt(x) sqrtf(x) #define fabs(x) (((x)>0)?(x):(0-(x))) #define abs(...) fabs(__VA_ARGS__) #define labs(...) fabs(__VA_ARGS__) #define frexp(...) frexpf(__VA_ARGS__) /*Should be double*/ #define log10(...) log10f(__VA_ARGS__) #define pow(...) powf(__VA_ARGS__) #endif
2.375
2
2024-11-18T17:55:25.706679+00:00
2023-07-14T10:13:16
5041033361d6b465fdc219e4aa6c4cb0264f3186
{ "blob_id": "5041033361d6b465fdc219e4aa6c4cb0264f3186", "branch_name": "refs/heads/master", "committer_date": "2023-07-14T10:13:16", "content_id": "e74e4f75dbe5a0ffa2c63970c1b1ac53af02afac", "detected_licenses": [ "Zlib", "Apache-2.0" ], "directory_id": "35ddd0f3036ac38423ded0435cd4b595f5dab31c", "extension": "c", "filename": "boot.c", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 138250652, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4109, "license": "Zlib,Apache-2.0", "license_type": "permissive", "path": "/src/micronix/stand/boot.c", "provenance": "stackv2-0005.json.gz:17909", "repo_name": "cm68/micronix", "revision_date": "2023-07-14T10:13:16", "revision_id": "6c3165f80f740f96fe4b402d4d87dfc9d8ec210b", "snapshot_id": "18854e545fefb077fbbfb8a4f4e19296ff258fdb", "src_encoding": "UTF-8", "star_events_count": 12, "url": "https://raw.githubusercontent.com/cm68/micronix/6c3165f80f740f96fe4b402d4d87dfc9d8ec210b/src/micronix/stand/boot.c", "visit_date": "2023-07-27T16:40:03.054677" }
stackv2
/* * it's a good idea to keep this below 4k, to prevent * any and all kinds of overlapping load insanity * * the global variables and register variables are to * get the footprint below 4k. */ #include <types.h> #include <sys/fs.h> #include <sys/dir.h> #include <obj.h> #ifdef __STDC__ #define INIT #else #define INIT = 0 #endif int inumber = 1; struct dsknod *inode INIT; /* * disk buffers - we need at most 2 to be valid at one time * we care about this for space reasons. */ union diskbuf { struct dsknod ibuf[16]; struct obj obj; UINT16 indir[256]; struct dir dir[32]; char bytes[512]; }; union diskbuf disk0 INIT; union diskbuf disk1 INIT; #define bytebuf disk0.bytes #define objbuf disk0.obj #define indirbuf disk1.indir #define inodebuf disk0.ibuf #define dirbuf disk1.dir char inputbuf[15] INIT; int (*loadbase)() = 0x1000; int loadptr = 0x1000; int loadsize = 0; char filecount = 0; int found = 0; exit() { int (*loadbase)(); loadbase = 0; (*loadbase)(); } /* * given an inode that has been read, read the executable into memory * we require that the inode be IFREG and ILARG, > 4k * buffers that need to be valid: indirbuf and objbuf. */ load() { register int *bnum; iget(); if (!readblock(inode->d_addr[0], indirbuf)) { outstr("read indir failed"); exit(); } bnum = indirbuf; if (!readblock(*bnum, &objbuf)) { outstr("read header failed"); exit(); } if (objbuf.ident == OBJECT) { loadbase = objbuf.textoff; loadptr = objbuf.textoff - 0x10; loadsize = objbuf.text + objbuf.data + 0x10; } else { loadsize = inode->d_size1; } outstr("Loading\n"); while (loadsize > 0) { if (!readblock(*bnum, loadptr)) { outstr("read object failed"); exit(); } bnum++; loadptr += 512; loadsize -= 512; } outstr("Entering\n"); out(0x41, 0); (*loadbase)(); } #ifdef __STDC__ outstr(char *s) #else outstr(s) register char *s; #endif { while (*s) { if (*s == '\n') { conout('\r'); } conout(*s++); } } /* * set inumber to the file we want to boot. if there is only one, * use it. * * XXX - only support first 32 files in the root directory * wouldn't be hard to fix, but probably not worth it * buffers in use: directory and inode */ select() { register struct dir *dirp; iget(); if (!readblock(inode->d_addr[0], dirbuf)) { outstr("read directory failed\n"); exit(); } outstr("Files:\n"); for (dirp = dirbuf; dirp < &dirbuf[32]; dirp++) { if ((dirp->name[0] != '.') && (dirp->ino != 0)) { inumber = dirp->ino; iget(); if ((inode->d_mode & (IALLOC|ILARG|IFMT)) != (IALLOC|ILARG)) continue; outstr(dirp->name); outstr("\n"); filecount++; found = inumber; } } inumber = found; if (filecount == 0) { outstr("No bootable files\n"); exit(); } if (filecount != 1) { while (1) { outstr("File to boot: "); readline(); dirp = dirbuf; for (dirp = dirbuf; dirp < &dirbuf[32]; dirp++) { if (strcmp(dirp->name, inputbuf) == 0) { inumber = dirp->ino; return; } } outstr("File not found\n"); } } } /* * read the inode inumber, and point at it. */ iget() { if (!readblock(2 + (inumber / 32), inodebuf)) { outstr("inode read failed\n"); } inode = &inodebuf[inumber % 32]; } #ifdef __STDC__ conout(UINT8 a) #else conout(a) UINT8 a; #endif { out(0x4f, 1); /* wait for txempty */ while (!(in(0x4d) & 0x20)) ; out(0x48, a); } UINT8 conin() { /* wait for rxready */ while (!(in(0x4d) & 0x1)) ; return in(0x48); } readline() { register char *s; char c; top: s = &inputbuf; while (s < (&inputbuf[sizeof(inputbuf)] - 1)) { *s = '\0'; c = conin(); if (c == '\b') { if (s != &inputbuf) { s--; outstr("\b \b"); } continue; } if (c == '\n' || c == '\r') { return; } if (c == 0x18) { outstr("\n"); goto top; } if ((c == 0x3) || (c == 0x7f)) { exit(); } conout(c); *s++ = c; } } main() { reset(); select(); load(); }
2.625
3
2024-11-18T17:55:26.150093+00:00
2021-08-29T05:54:51
a7c8d5d632c47d91139b265ccd293a06c86f4d30
{ "blob_id": "a7c8d5d632c47d91139b265ccd293a06c86f4d30", "branch_name": "refs/heads/master", "committer_date": "2021-08-29T05:54:51", "content_id": "926957b5b908f0c1dcab29dd895ea183a332b932", "detected_licenses": [ "MIT" ], "directory_id": "c73d11b2c6a110a0e65ce6ab8934cac03996bdc3", "extension": "c", "filename": "GoFeature.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 360782539, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 7086, "license": "MIT", "license_type": "permissive", "path": "/Gocator/GoSdk/GoSdk/Tools/GoFeature.c", "provenance": "stackv2-0005.json.gz:18037", "repo_name": "Logan-Shi/GO_SDK", "revision_date": "2021-08-29T05:54:51", "revision_id": "ff648a46f55b0acbba8fb35337cd1c23e13be777", "snapshot_id": "171d6ff134efe885d9965133dcd29a7c3f52ecd7", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Logan-Shi/GO_SDK/ff648a46f55b0acbba8fb35337cd1c23e13be777/Gocator/GoSdk/GoSdk/Tools/GoFeature.c", "visit_date": "2023-07-17T10:50:01.406926" }
stackv2
/** * @file GoFeature.c * * @internal * Copyright (C) 2017-2020 by LMI Technologies Inc. * Licensed under the MIT License. * Redistributed files must retain the above copyright notice. */ #include <GoSdk/Tools/GoFeatures.h> #include <GoSdk/Tools/GoFeature.h> #include <GoSdk/GoSensor.h> #include <GoSdk/GoUtils.h> kBeginClassEx(Go, GoFeature) kAddVMethod(GoFeature, kObject, VRelease) kAddVMethod(GoFeature, GoFeature, VInit) kAddVMethod(GoFeature, GoFeature, VRead) kAddVMethod(GoFeature, GoFeature, VWrite) kEndClassEx() GoFx(kStatus) GoFeature_Construct(GoFeature* feature, kType type, kObject sensor, kObject srcTool, kAlloc allocator) { kAlloc alloc = kAlloc_Fallback(allocator); kStatus status; kCheck(kAlloc_GetObject(alloc, type, feature)); if (!kSuccess(status = kType_VTableT(type, GoFeature)->VInit(*feature, type, sensor, srcTool, alloc))) { kAlloc_FreeRef(alloc, feature); } return status; } GoFx(kStatus) GoFeature_VInit(GoFeature feature, kType type, kObject sensor, kObject srcTool, kAlloc alloc) { kObjR(GoFeature, feature); kCheck(kObject_Init(feature, type, alloc)); kZero(obj->xml); kZero(obj->xmlItem); obj->name[0] = 0; obj->type[0] = 0; obj->sensor = sensor; obj->id = GO_FEATURE_UNASSIGNED_ID; obj->srcTool = srcTool; obj->enabled = kFALSE; obj->typeId = GO_FEATURE_EXTENSIBLE; //to Discuss H.Ware obj->dataType = GO_FEATURE_DATA_UNKNOWN; return kOK;//TO discuss H.Ware kERROR_UNIMPLEMENTED; //this function must be overriden by every feature } GoFx(kStatus) GoFeature_Init(GoFeature feature, kType type, GoFeatureType typeId, kObject sensor, kObject srcTool, GoFeatureDataType dataType, kAlloc alloc) { kObjR(GoFeature, feature); kCheck(kObject_Init(feature, type, alloc)); kZero(obj->xml); kZero(obj->xmlItem); obj->name[0] = 0; obj->type[0] = 0; obj->sensor = sensor; obj->id = GO_FEATURE_UNASSIGNED_ID; obj->srcTool = srcTool; obj->enabled = kFALSE; obj->typeId = typeId; obj->dataType = dataType; return kOK; } GoFx(kStatus) GoFeature_VRelease(GoFeature feature) { kObj(GoFeature, feature); kCheck(kObject_VRelease(feature)); return kOK; } GoFx(kStatus) GoFeature_VRead(GoFeature feature, kXml xml, kXmlItem item) { kObj(GoFeature, feature); kText64 tempStr; obj->xml = xml; obj->xmlItem = item; if(!kSuccess(kXml_Attr32s(xml, item, "id", &obj->id))) { obj->id = GO_FEATURE_UNASSIGNED_ID; } kCheck(kXml_ChildText(xml, item, "Name", obj->name, kCountOf(obj->name))); kCheck(kXml_ChildBool(xml, item, "Enabled", &obj->enabled)); kCheck(kXml_AttrText(xml, item, "dataType", tempStr, kCountOf(tempStr))); kCheck(GoFeatures_ParseDataType(tempStr, &obj->dataType)); kCheck(kStrCopy(obj->type, kCountOf(obj->type), kXml_ItemName(xml, item))); return kOK; } GoFx(kStatus) GoFeature_VWrite(GoFeature feature, kXml xml, kXmlItem item) { kObj(GoFeature, feature); kText64 tempStr; kCheck(kXml_SetAttr32s(xml, item, "id", obj->id)); kCheck(kXml_SetChildText(xml, item, "Name", obj->name)); kCheck(kXml_SetChildBool(xml, item, "Enabled", obj->enabled)); if (obj->dataType != GO_FEATURE_DATA_UNKNOWN) { kCheck(GoFeatures_FormatDataType(obj->dataType, tempStr, kCountOf(tempStr))); kCheck(kXml_SetAttrText(xml, item, "dataType", tempStr)); } kCheck(GoUtils_XmlMerge(obj->xml, obj->xmlItem, xml, item)); return kOK; } GoFx(kStatus) GoFeature_Read(GoFeature feature, kXml xml, kXmlItem item) { return kCast(GoFeatureVTable*, xkObject_VTable(feature))->VRead(feature, xml, item); } GoFx(kStatus) GoFeature_Write(GoFeature feature, kXml xml, kXmlItem item) { return kCast(GoFeatureVTable*, xkObject_VTable(feature))->VWrite(feature, xml, item); } GoFx(kBool) GoFeature_HasId(GoFeature feature) { kObj(GoFeature, feature); GoSensor_SyncConfig(obj->sensor); return (obj->id != GO_FEATURE_UNASSIGNED_ID); } GoFx(kStatus) GoFeature_ClearId(GoFeature feature) { kObj(GoFeature, feature); kCheckState(GoSensor_IsConfigurable(obj->sensor)); kCheck(GoSensor_CacheConfig(obj->sensor)); obj->id = GO_FEATURE_UNASSIGNED_ID; kCheck(GoSensor_SetConfigModified(obj->sensor)); return kOK; } GoFx(kStatus) GoFeature_SetId(GoFeature feature, k32u id) { kObj(GoFeature, feature); kCheckState(GoSensor_IsConfigurable(obj->sensor)); kCheck(GoSensor_CacheConfig(obj->sensor)); obj->id = (k32s) id; kCheck(GoSensor_SetConfigModified(obj->sensor)); return kOK; } GoFx(k32s) GoFeature_Id(GoFeature feature) { kObj(GoFeature, feature); GoSensor_SyncConfig(obj->sensor); return obj->id; } GoFx(const kChar*) GoFeature_Name(GoFeature feature) { kObj(GoFeature, feature); GoSensor_SyncConfig(obj->sensor); return obj->name; } GoFx(kStatus) GoFeature_SetName(GoFeature feature, const kChar* name) { kObj(GoFeature, feature); kCheckState(GoSensor_IsConfigurable(GoFeature_Sensor(feature))); kCheck(GoSensor_CacheConfig(GoFeature_Sensor(feature))); kCheck(kStrCopy(obj->name, kCountOf(obj->name), name)); kCheck(GoSensor_SetConfigModified(GoFeature_Sensor(feature))); return kOK; } GoFx(kObject) GoFeature_Sensor(GoFeature feature) { kObj(GoFeature, feature); return obj->sensor; } GoFx(kObject) GoFeature_SourceTool(GoFeature feature) { kObj(GoFeature, feature); GoSensor_SyncConfig(GoFeature_Sensor(feature)); return obj->srcTool; } GoFx(kStatus) GoFeature_Enable(GoFeature feature, kBool enable) { kObj(GoFeature, feature); kCheckState(GoSensor_IsConfigurable(GoFeature_Sensor(feature))); kCheck(GoSensor_CacheConfig(GoFeature_Sensor(feature))); obj->enabled = enable; kCheck(GoSensor_SetConfigModified(GoFeature_Sensor(feature))); return kOK; } GoFx(kBool) GoFeature_Enabled(GoFeature feature) { kObj(GoFeature, feature); GoSensor_SyncConfig(GoFeature_Sensor(feature)); return obj->enabled; } GoFx(const kChar*) GoFeature_Type(GoFeature feature) { kObj(GoFeature, feature); GoSensor_SyncConfig(GoFeature_Sensor(feature)); return obj->type; } GoFx(GoFeatureDataType) GoFeature_DataType(GoFeature feature) { kObj(GoFeature, feature); GoSensor_SyncConfig(GoFeature_Sensor(feature)); return obj->dataType; } GoFx(GoFeatureType) GoFeature_TypeId(GoFeature feature) { kObj(GoFeature, feature); GoSensor_SyncConfig(GoFeature_Sensor(feature)); return obj->typeId; }
2
2
2024-11-18T17:55:26.361339+00:00
2019-07-23T22:46:10
18c31810d3f84945f8ee7ec295b60801353269e2
{ "blob_id": "18c31810d3f84945f8ee7ec295b60801353269e2", "branch_name": "refs/heads/master", "committer_date": "2019-07-24T00:27:08", "content_id": "1d34603c484cfb6df54f859c615dcac8de50c9e7", "detected_licenses": [ "MIT" ], "directory_id": "69948b927477544c250ee6dd5bbd8fed26e06649", "extension": "c", "filename": "ReentrantLock.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3454, "license": "MIT", "license_type": "permissive", "path": "/src/aeten/concurrent/posix/ReentrantLock.c", "provenance": "stackv2-0005.json.gz:18165", "repo_name": "aneth-dev/aneth-core-c", "revision_date": "2019-07-23T22:46:10", "revision_id": "626fddf85797c5ca61b294beebb51926adb8c8b1", "snapshot_id": "e55895502fc6e3eac77df9bde9d9239f6811f3e7", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/aneth-dev/aneth-core-c/626fddf85797c5ca61b294beebb51926adb8c8b1/src/aeten/concurrent/posix/ReentrantLock.c", "visit_date": "2022-03-29T06:22:02.191947" }
stackv2
#include "ReentrantLock.h" #include <pthread.h> #include <errno.h> #define import #include "concurrent/Condition.h" #include "ReentrantLockCondition.h" /* @startuml(id=ReentrantLock) !include concurrent/Lock.c !include concurrent/Condition.c namespace aeten.concurrent.posix { class ReentrantLock implements aeten.concurrent.Lock { + {static} ReentrantLock() <<constructor>> # void finalize() <<override>> - mutex: pthread_mutex_t } } @enduml @startuml(id=ReentrantLockCondition) !include concurrent/Condition.c namespace aeten.concurrent.posix { class ReentrantLockCondition implements aeten.concurrent.Condition { + {static} ReentrantLockCondition(pthread_mutex_t *mutex) <<constructor>> - mutex: pthread_mutex_t* - cond: pthread_cond_t } } @enduml */ static struct timespec time_diff(struct timespec start, struct timespec end); void ReentrantLock_new(ReentrantLock* self) { pthread_mutex_t pthread_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutexattr_t mutex_init; bzero(&mutex_init, sizeof(pthread_mutexattr_t)); pthread_mutexattr_init(&mutex_init); pthread_mutexattr_settype(&mutex_init, PTHREAD_MUTEX_RECURSIVE_NP); pthread_mutex_init(&pthread_mutex, &mutex_init); self->_mutex = pthread_mutex; } void ReentrantLock_finalize(ReentrantLock* self) { pthread_mutex_destroy(&self->_mutex); } void ReentrantLock_lock(ReentrantLock* self) { pthread_mutex_lock(&self->_mutex); } bool ReentrantLock_tryLock(ReentrantLock* self) { return (pthread_mutex_trylock(&self->_mutex) == 0); } void ReentrantLock_unlock(ReentrantLock* self) { pthread_mutex_unlock(&self->_mutex); } Condition ReentrantLock_newCondition(ReentrantLock* self) { return Condition_cast(new_ReentrantLockCondition(&self->_mutex)); } void ReentrantLockCondition_new(ReentrantLockCondition* self, pthread_mutex_t *mutex) { self->_mutex = mutex; pthread_cond_t cond = PTHREAD_COND_INITIALIZER; self->_cond = cond; } void ReentrantLockCondition_await(ReentrantLockCondition* self) { pthread_cond_wait(&self->_cond, self->_mutex); } uint64_t ReentrantLockCondition_awaitNanos(ReentrantLockCondition* self, uint64_t nanosTimeout) { struct timespec from; check(clock_gettime(CLOCK_REALTIME, &from) == 0, Error, "%m (errno: %u)", errno); struct timespec end = { from.tv_sec, from.tv_nsec + nanosTimeout }; while (end.tv_nsec >= 1000000000) { end.tv_nsec -= 1000000000; ++end.tv_sec; } if (ReentrantLockCondition_awaitUntil(self, end)) { struct timespec now, rest; check(clock_gettime(CLOCK_REALTIME, &now) == 0, Error, "%m (errno: %u)", errno); rest = time_diff(from, now); return (rest.tv_sec * 1E9) + rest.tv_nsec; } return 0; } bool ReentrantLockCondition_awaitUntil(ReentrantLockCondition* self, struct timespec deadline) { switch (pthread_cond_timedwait(&self->_cond, self->_mutex, &deadline)) { case ETIMEDOUT: return false; case EINTR: throw(InterruptException); return true; default: return true; } } void ReentrantLockCondition_signal(ReentrantLockCondition* self) { pthread_cond_signal(&self->_cond); } void ReentrantLockCondition_signalAll(ReentrantLockCondition* self) { pthread_cond_broadcast(&self->_cond); } struct timespec time_diff(struct timespec start, struct timespec end) { struct timespec diff; diff.tv_sec = end.tv_sec - start.tv_sec; diff.tv_nsec = end.tv_nsec - start.tv_nsec; while (diff.tv_nsec < 0 ) { diff.tv_nsec += 1E9; --diff.tv_sec; } return diff; }
2.265625
2
2024-11-18T17:55:26.414032+00:00
2016-01-28T10:37:01
3a741359bc8c00a08383b50dbd389abf06634522
{ "blob_id": "3a741359bc8c00a08383b50dbd389abf06634522", "branch_name": "refs/heads/master", "committer_date": "2016-01-28T10:37:01", "content_id": "b072afae28934a6196c757f55b735dd9504a4be0", "detected_licenses": [ "MIT" ], "directory_id": "2a3293027967906f6f6fcdb94167ae155127a6ba", "extension": "h", "filename": "oakboot-private.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 50061600, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1884, "license": "MIT", "license_type": "permissive", "path": "/oakboot-private.h", "provenance": "stackv2-0005.json.gz:18293", "repo_name": "digistump/OakBoot", "revision_date": "2016-01-28T10:37:01", "revision_id": "e879bfed93e8eeda1cccf625089fb222e5f63442", "snapshot_id": "3d31231abb33159236a8df51fadb47ad60a6f7ea", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/digistump/OakBoot/e879bfed93e8eeda1cccf625089fb222e5f63442/oakboot-private.h", "visit_date": "2021-01-10T12:06:37.954609" }
stackv2
#ifndef __OAKBOOT_PRIVATE_H__ #define __OAKBOOT_PRIVATE_H__ ////////////////////////////////////////////////// // OakBoot by Erik Kettenburg/Digistump // Based on rBoot open source boot loader for ESP8266. // Copyright 2015 Richard A Burton // [email protected] // See license.txt for license terms. ////////////////////////////////////////////////// typedef int int32; typedef unsigned int uint32; typedef unsigned char uint8; #include "oakboot.h" #define NOINLINE __attribute__ ((noinline)) #define ROM_MAGIC 0xe9 #define ROM_MAGIC_NEW1 0xea #define ROM_MAGIC_NEW2 0x04 #define TRUE 1 #define FALSE 0 // buffer size, must be at least 0x10 (size of rom_header_new structure) #define BUFFER_SIZE 0x100 // esp8266 built in rom functions extern uint32 SPIRead(uint32 addr, void *outptr, uint32 len); extern uint32 SPIEraseSector(int); extern uint32 SPIWrite(uint32 addr, void *inptr, uint32 len); extern void ets_printf(char*, ...); extern void ets_delay_us(int); extern void ets_memset(void*, uint8, uint32); extern void ets_memcpy(void*, const void*, uint32); extern volatile uint32 PIN_OUT_SET; extern volatile uint32 PIN_OUT_CLEAR; extern volatile uint32 PIN_DIR_OUTPUT; // functions we'll call by address typedef void stage2a(uint32); typedef void usercode(void); // standard rom header typedef struct { // general rom header uint8 magic; uint8 count; uint8 flags1; uint8 flags2; usercode* entry; } rom_header; typedef struct { uint8* address; uint32 length; } section_header; // new rom header (irom section first) there is // another 8 byte header straight afterward the // standard header typedef struct { // general rom header uint8 magic; uint8 count; // second magic for new header uint8 flags1; uint8 flags2; uint32 entry; // new type rom, lib header uint32 add; // zero uint32 len; // length of irom section } rom_header_new; #endif
2.1875
2
2024-11-18T17:55:27.204585+00:00
2023-08-03T22:35:37
2fbf4748efbc0e0767b1847570ad7afa6331c345
{ "blob_id": "2fbf4748efbc0e0767b1847570ad7afa6331c345", "branch_name": "refs/heads/master", "committer_date": "2023-08-03T22:35:37", "content_id": "a3e4d5fc9c95f4729fdaf129221fcbe20638be2d", "detected_licenses": [ "Linux-OpenIB" ], "directory_id": "9bfd61f3ceaf77129b8c7b8441f1c129b2ecc3ea", "extension": "c", "filename": "remote_filecheck.c", "fork_events_count": 1, "gha_created_at": "2019-07-24T22:21:20", "gha_event_created_at": "2023-08-03T22:35:38", "gha_language": "C++", "gha_license_id": "NOASSERTION", "github_id": 198717167, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2082, "license": "Linux-OpenIB", "license_type": "permissive", "path": "/tests/function/src/support/remote_filecheck.c", "provenance": "stackv2-0005.json.gz:18677", "repo_name": "common-tools-interface/cti", "revision_date": "2023-08-03T22:35:37", "revision_id": "7822866160a1944f7fe8317a8e9910c54085f01d", "snapshot_id": "a2ca118f31f93bad3396d917913e7594dbdab035", "src_encoding": "UTF-8", "star_events_count": 8, "url": "https://raw.githubusercontent.com/common-tools-interface/cti/7822866160a1944f7fe8317a8e9910c54085f01d/tests/function/src/support/remote_filecheck.c", "visit_date": "2023-08-17T02:30:34.747033" }
stackv2
/******************************************************************************\ * * Copyright 2019-2020 Hewlett Packard Enterprise Development LP. * SPDX-License-Identifier: Linux-OpenIB ******************************************************************************/ #include <unistd.h> #include <sys/socket.h> #include <sys/stat.h> #include <arpa/inet.h> #include <netinet/in.h> #include <netdb.h> #include <stdio.h> #include <stdlib.h> #include <string.h> int main(int argc, char* argv[]) { if (argc != 4) { fprintf(stderr, "Invalid parameters\nExpected: SocketIP, SocketPort, Filepath\n"); return 1; } //Declare variables to store socket IP and port char* ip; int port; //Set variables to their respective values ip = argv[1]; sscanf(argv[2], "%d", &port); //Create socket int c_socket; int rc; struct addrinfo *node; struct addrinfo hints; memset(&hints, 0, sizeof(struct addrinfo)); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_NUMERICSERV; // get the addrinfo if ((rc = getaddrinfo(argv[1], argv[2], &hints, &node)) != 0) { fprintf(stderr, "Getaddrinfo failed: %s\n", gai_strerror(rc)); return 1; } if ((c_socket = socket(node->ai_family, node->ai_socktype, node->ai_protocol)) < 0) { fprintf(stderr, "Failed to create local socket\n"); return 1; } fprintf(stderr, "Connecting...\n"); fprintf(stderr, "Host: %s\n", argv[1]); fprintf(stderr, "Port: %d\n", atoi(argv[2])); if (connect(c_socket, node->ai_addr, node->ai_addrlen) < 0) { fprintf(stderr, "Failed to connect\n"); perror("ERROR:"); return 1; } fprintf(stderr, "CONNECTED\n"); fprintf(stderr, "Checking for %s...\n", argv[3]); struct stat buf; int r = stat(argv[3], &buf); if (r == 0) { // file found send(c_socket, "1", 1, 0); } else { // file not found send(c_socket, "0", 1, 0); } close(c_socket); return 0; }
2.4375
2
2024-11-18T17:55:27.941870+00:00
2023-04-09T11:12:27
007be48a673a685eff0bf63100e43e220a78cdc7
{ "blob_id": "007be48a673a685eff0bf63100e43e220a78cdc7", "branch_name": "refs/heads/master", "committer_date": "2023-04-09T11:12:27", "content_id": "e13c4f219fd8ad203792e9f82a6ea50367e1928b", "detected_licenses": [ "MIT" ], "directory_id": "4bd8f24c44fb4142e002a0463141c7ff33f3c5cc", "extension": "c", "filename": "orbit_plot1.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 251097527, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5170, "license": "MIT", "license_type": "permissive", "path": "/orbit_plot1.c", "provenance": "stackv2-0005.json.gz:18934", "repo_name": "jlprieur/pisco-papers", "revision_date": "2023-04-09T11:12:27", "revision_id": "f3fe2d0d41a16a561cdf80cf14afb7f07f52b892", "snapshot_id": "a016f9621ecaec96baea305753e58115338bb849", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/jlprieur/pisco-papers/f3fe2d0d41a16a561cdf80cf14afb7f07f52b892/orbit_plot1.c", "visit_date": "2023-04-14T21:47:25.369915" }
stackv2
/************************************************************************* * orbit_plot1 * To plot the curves rho(epoch), theta(epoch) and XY orbits in the sky plane * measurements only (and/without the orbit). * * * JLP * Version 12/01/2012 **************************************************************************/ #include <orbit_plot_utils.h> /****************** Main program **************************************/ int main(int argc, char *argv[]) { int status, npts_max, iformat, iplot, smoothed_values, nber_of_orbits; int resid_vectors; char measures_infile[64], plotfile[64], comments[81]; char orbit_file[64], plot_title[64]; printf("Program orbit_plot1 to plot raw data (measurements with/without orbit)\n"); status = -1; // General case (more than 6 arguments): assume that orbit parameters have been entered: if (argc >= 6) { strcpy(measures_infile, argv[1]); strcpy(plotfile, argv[2]); sscanf(argv[3], "%d,%d,%d", &iformat, &iplot, &resid_vectors); strcpy(orbit_file, argv[4]); strcpy(plot_title, argv[5]); if (argc == 7) { sscanf(argv[6], "%d", &nber_of_orbits); if(nber_of_orbits < 0 || nber_of_orbits > 3) { fprintf(stderr, "Fatal error: nber_of_orbits=%d\n", nber_of_orbits); return(-1); } } else { nber_of_orbits = 1; } if((iformat == 3) || (iformat == 4)) status = 0; // Case of 5 arguments only: assume that no orbit parameters have been entered: } else if (argc == 5) { strcpy(measures_infile, argv[1]); strcpy(plotfile, argv[2]); sscanf(argv[3], "%d,%d,%d", &iformat, &iplot, &resid_vectors); strcpy(plot_title, argv[4]); orbit_file[0] = '\0'; if((iformat > 0 && iformat < 4) || iformat == 5) status = 0; } printf("OK: argc=%d infile=%s plot_file=%s orbit_file=%s\n", argc, measures_infile, plotfile, orbit_file); printf("OK: iformat=%d iplot=%d resid_vectors=%d nber_of_orbits=%d\n", iformat, iplot, resid_vectors, nber_of_orbits); printf("OK: plot_title=%s\n", plot_title); // Handle errors: if(status) { printf("Error, syntax is: \norbit_plot1 infile extension_for_pst_files iformat,iplot,resid_vectors [file_with_orbital_elements, if iformat==3 or 4] title [nber_of_orbits]\n"); printf("iformat: 1=raw (from WDS)\n"); printf(" 2=corrected measures (from 1BIN.FOR of orbit_weight.c)\n"); printf(" 3=measures and ephemerids (from residuals_2.c)\n"); printf(" 4=raw or corrected measures and orbit\n"); printf(" 5=residuals (dx,dy) (from residuals_2.c)\n"); printf("iplot: 1=rho,theta 2=dx,dy 3=XY_full_orbit 4=XY_part_of_orbit\n"); printf("resid_vectors: 0 or 1 if residual vectors to be plotted (for XY orbit only)\n"); printf("Example: \norbit_plot1 A15971.205 tt 2,1,0 \"ADS 15971\" \n"); printf("Example: \norbit_plot1 A15971.205 tt 4,3,0 A15971_orbit.txt \"ADS 15971\"\n"); printf("Example: \norbit_plot1 A15971.205 tt 4,3,0 A15971_orbits.txt \"ADS 15971\" 2\n"); printf("Example: \norbit_plot1 A15971.205 tt 3,4,1 A15971_orbit.txt \"ADS 15971\"\n"); return(-1); } /* * iformat = 1: epoch, rho_O, theta_O, n_nights, author, aperture, instrument * iformat = 2: epoch, rho_O, theta_O, n_nights, author, aperture, weight * iformat = 3: epoch, rho_O, rho_C, Drho_O-C, theta_O, theta_C, Dtheta, author * iformat = 4: epoch, rho_O, theta_O, n_nights, author, aperture, ... * iformat = 5: epoch, Dx, Dy, n_nights, author, aperture, weight */ /* * iplot=1: plot rho vs epoch and theta vs epoch * iplot=2: plot dx vs epoch and dy vs epoch * iplot=3: plot XY_full_orbit * iplot=4: plot XY_part_of_orbit */ /* * resid_vectors=0 : do not plot residual vectors * resid_vectors=1 : plot residual vectors */ strcpy(comments,"Program orbit_plot1.c -- Version 23/07/2018"); status = orbit_get_npts_max(measures_infile, &npts_max); if(status) return(-1); /* Minimum of 1000 points when iformat=4 (since we want a full orbit) */ if((iformat == 3) || (iformat == 4)) npts_max = MAXI(1000,npts_max); /* strcpy(plotdev,"square/rho.ps"); */ /* Only useful for Drho, Dtheta, not relevant for Dx,Dy (i.e., when iformat=5) */ status = 0; switch (iplot) { case 1: if(iformat != 5) { orbit_plot_rho(measures_infile, comments, orbit_file, nber_of_orbits, npts_max, iformat, plotfile); orbit_plot_theta(measures_infile, comments, orbit_file, nber_of_orbits, npts_max, iformat, plotfile); } else { fprintf(stderr, "Fatal error: cannot plot rho,theta with dx,dy file !\n"); status = -1; } break; case 2: smoothed_values = 1; orbit_plot_Dx(measures_infile, comments, npts_max, plotfile, smoothed_values); orbit_plot_Dy(measures_infile, comments, npts_max, plotfile, smoothed_values); break; /* Plot orbit in the plane of the sky * Full orbit if iformat==3 or 4, or part of the orbit only in other cases */ case 3: case 4: orbit_plot_skyplane(measures_infile, comments, orbit_file, nber_of_orbits, npts_max, iformat, iplot, resid_vectors, plotfile, plot_title); break; default: fprintf(stderr, "Fatal error: unkown option: iplot=%d !\n", iplot); status = -1; break; } // EOF switch return(status); }
2.21875
2
2024-11-18T17:55:28.114093+00:00
2020-02-27T18:27:43
9e9535fa0fae586e1307fe54bcbf54629e870dc5
{ "blob_id": "9e9535fa0fae586e1307fe54bcbf54629e870dc5", "branch_name": "refs/heads/master", "committer_date": "2020-02-27T18:27:43", "content_id": "869eac39113196edd88e20a4a7a021cfe5d3184b", "detected_licenses": [ "BSD-3-Clause", "BSD-2-Clause" ], "directory_id": "da87c3c4568baf73eafba3bdd0398b721c14fa83", "extension": "c", "filename": "cs105.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 111293783, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2222, "license": "BSD-3-Clause,BSD-2-Clause", "license_type": "permissive", "path": "/lib/ds/codes/cs105.c", "provenance": "stackv2-0005.json.gz:19190", "repo_name": "gonter/hyx-tools", "revision_date": "2020-02-27T18:27:43", "revision_id": "4fefb2d99454f859e7ed452a8d8113aff068aefc", "snapshot_id": "d8b42fc1fb8a296924208838a8fcc196060d884f", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/gonter/hyx-tools/4fefb2d99454f859e7ed452a8d8113aff068aefc/lib/ds/codes/cs105.c", "visit_date": "2022-04-08T15:24:52.144996" }
stackv2
/* * File %dpp/codes/cs105.c * * CS_ET8: entity translation functions * * written: 1995-12-10: [email protected] * latest update: 1995-12-10 * */ #include <stdlib.h> #include <gg/fileio.h> #include <gg/strings.h> #include <gg/codes.h> /* ------------------------------------------------------------------------ */ char *cs_et8_code2entity (struct CS_ET8 *et8, int ch) { long rc; long offset; long *index; char *strings; long string_size; char *entity_name= (char *) 0; if (et8 == (struct CS_ET8 *) 0 || et8->CS_et8_error_flag != 0 /* table can't be used! */ || ch < 0x00 || ch > 0xFF ) goto END; /* load translation tables now if they are not already loaded */ if ((index= et8->CS_et8_index) == (long *) 0) { rc= read_file2buffer ((char **) &et8->CS_et8_index, et8->CS_et8_index_fnm, 1024L); #ifdef DEBUG fprintf (stderr, ">>> reading %s -> %ld diag=%d\n", et8->CS_et8_index_fnm, rc, gg_diagnose); #endif if (rc == -1L) { et8->CS_et8_error_flag= 1; goto END; } index= et8->CS_et8_index; } if ((strings= et8->CS_et8_string_buffer) == (char *) 0) { string_size= read_file2buffer (&et8->CS_et8_string_buffer, et8->CS_et8_string_fnm, MAX_CS_ET8_SIZE); #ifdef DEBUG fprintf (stderr, ">>> reading %s -> %ld diag=%d\n", fnm_str, rc, gg_diagnose); #endif if (string_size == -1L) { et8->CS_et8_error_flag= 2; goto END; } strings= et8->CS_et8_string_buffer; et8->CS_et8_string_size= string_size; } else string_size= et8->CS_et8_string_size; offset= index [ch]; #ifdef DEBUG fprintf (stderr, ">> offset= 0x%08lX\n", offset); #endif if (offset < 0L || offset >= string_size) goto END; #ifdef DEBUG fprintf (stderr, ">> is %c->%s\n", ch, &strings [offset]); #endif entity_name= &strings [offset]; END: if (entity_name == (char *) 0) { switch (ch) { case 0: entity_name= "null"; break; case '&': entity_name= "amp"; break; case '<': entity_name= "lt"; break; case '>': entity_name= "gt"; break; } } return entity_name; }
2.296875
2
2024-11-18T17:55:28.406679+00:00
2018-07-30T17:39:13
2ba1b269ce64b5a4c8fbb3e7291e5ebac1aa4af3
{ "blob_id": "2ba1b269ce64b5a4c8fbb3e7291e5ebac1aa4af3", "branch_name": "refs/heads/master", "committer_date": "2018-07-30T17:39:13", "content_id": "1ca9e2be792f295a4f7b722cf14c9bc96cf8cdf9", "detected_licenses": [ "Apache-2.0" ], "directory_id": "34f975a78fb2c80e8b82e327815dcf8ab283833e", "extension": "c", "filename": "zc-e.c", "fork_events_count": 0, "gha_created_at": "2018-04-04T14:55:03", "gha_event_created_at": "2018-07-30T17:39:14", "gha_language": "Objective-C", "gha_license_id": "Apache-2.0", "github_id": 128077947, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 12789, "license": "Apache-2.0", "license_type": "permissive", "path": "/recognizer/CPqDASR/Utils/zc-e.c", "provenance": "stackv2-0005.json.gz:19575", "repo_name": "CPqD/asr-sdk-ios", "revision_date": "2018-07-30T17:39:13", "revision_id": "936bd860b6b7b7e6f772ac0874335faab80bf5ed", "snapshot_id": "1a75faa9344d5b226e74037a09df74340b9e89de", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/CPqD/asr-sdk-ios/936bd860b6b7b7e6f772ac0874335faab80bf5ed/recognizer/CPqDASR/Utils/zc-e.c", "visit_date": "2020-03-08T10:38:01.604956" }
stackv2
/******************************************************************************* * Copyright 2017 CPqD. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy * of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. ******************************************************************************/ #include "zc-e.h" // With 16000 Hz samples, 16 buts per sample and a mono channel the buffer holds 10 seconds of audio const unsigned int kMainBufferSize = 320000; // Length of queue buffer in bytes (16000 samples/second) * (2 bytes / sample) * 250 ms const UInt32 kBufferSize = 8000; // Number of buffers of Audio Queue const unsigned int kNumberBuffers = 3; // Size of window in number of samples const unsigned int window_size = 100; // number of samples / window = (size of samples in bytes / number of bytes per sample) / size of samples window const unsigned int zero_cross_vector_size = (kMainBufferSize / 2) / window_size; // energy threshold . const int level_threshold = 2000; void * mymalloc_custom(size_t size) { void *p; if ( (p = malloc(size)) == NULL) { fprintf(stderr, "mymalloc_custom: failed to allocate %zu bytes", size); exit(1); } return p; } /** * Allocate buffers for zerocross counting. * * @param zc [i/o] zerocross work area * @param length [in] Cycle buffer size = Number of samples to hold */ void init_count_zc_e_custom(ZC *zc, int length) { /* data spool for header-margin */ zc->data = (SP16 *)mymalloc_custom(length * sizeof(SP16)); /* zero-cross location */ zc->is_zc = (int *)mymalloc_custom(length * sizeof(int)); zc->length = length; } /** * Initialize all parameters and buffers for zero-cross counting. * * @param zc [i/o] zerocross work area * @param c_trigger [in] Tgigger level threshold * @param c_length [in] Cycle buffer size = Number of samples to hold * @param c_offset [in] Static DC offset of input data */ void reset_count_zc_e_custom(ZC *zc, int c_trigger, int c_length, int c_offset) { int i; if (zc->length != c_length) { //log_warn("zerocross buffer length changed, re-allocate it"); free_count_zc_e_custom(zc); init_count_zc_e_custom(zc, c_length); } zc->trigger = c_trigger; zc->offset = c_offset; zc->zero_cross = 0; zc->is_trig = FALSE; zc->sign = ZC_POSITIVE; zc->top = 0; zc->valid_len = 0; for (i=0; i<c_length; i++){ zc->is_zc[i] = ZC_UNDEF; } } /** * End procedure: free all buffers. * * @param zc [i/o] zerocross work area */ void free_count_zc_e_custom(ZC *zc) { free(zc->is_zc); free(zc->data); } /** * Adding buf[0..step-1] to the cycle buffer and update the count of * zero cross. Also swap them with the oldest ones in the cycle buffer. * Also get the maximum level in the cycle buffer. * * @param zc [i/o] zerocross work area * @param buf [I/O] new samples, will be swapped by old samples when returned. * @param step [in] length of above. * * @return zero-cross count of the samples in the cycle buffer. */ int count_zc_e_custom(ZC *zc, SP16 *buf, int step) { int i; SP16 tmp, level; level = 0; for (i=0; i<step; i++) { // fprintf(stderr, "zerocross: %d, buf[%d]: %hd\n", zc->zero_cross, i, buf[i]); if (zc->is_zc[zc->top] == TRUE) { zc->zero_cross--; } zc->is_zc[zc->top] = FALSE; /* exchange old data and buf */ tmp = buf[i] + zc->offset; if (zc->is_trig) { if (zc->sign == ZC_POSITIVE && tmp < 0) { zc->zero_cross++; zc->is_zc[zc->top] = TRUE; zc->is_trig = FALSE; zc->sign = ZC_NEGATIVE; } else if (zc->sign == ZC_NEGATIVE && tmp > 0) { zc->zero_cross++; zc->is_zc[zc->top] = TRUE; zc->is_trig = FALSE; zc->sign = ZC_POSITIVE; } } if (abs(tmp) > zc->trigger) { zc->is_trig = TRUE; } if (abs(tmp) > level) level = abs(tmp); zc->data[zc->top] = buf[i]; zc->top++; if (zc->valid_len < zc->top) zc->valid_len = zc->top; if (zc->top >= zc->length) { zc->top = 0; } } zc->level = (int)level; return (zc->zero_cross); } void calculateZcVector( void *samples, unsigned int samples_offset, int *zero_cross_vector, unsigned int zero_cross_vector_size, unsigned int *zero_cross_vector_position, unsigned int start_margin, unsigned int window_size, int level_threshold ) { short *buffer = NULL; SP16 *currentBuffer = NULL; int num_samples; ZC zc; int c_length = start_margin ; // c_length = (int)(head_margin_msec * samples_in_msec); numero de amostras; start margin int zc_vector_first_invalid; buffer = (short *) samples; currentBuffer = buffer; num_samples = samples_offset / 2; zc_vector_first_invalid = (samples_offset / 2) / window_size; init_count_zc_e_custom(&zc, c_length); reset_count_zc_e_custom(&zc, level_threshold, c_length, 0); // Até então o for começava com i = *zero_cross_vector_position para não preencher o vetor desde o início toda vez, // dado que ele estaria preenchido em [0..*zero_cross_vector_position]. // No entanto ele calcula errado, aparentemente. // Portanto não temos escolha e recalculamos o vetor desde o início toda vez. int i; for (i = 0; i < zc_vector_first_invalid; ++i) { zero_cross_vector[i] = count_zc_e_custom(&zc, &(currentBuffer[i * window_size]), window_size); } *zero_cross_vector_position = zc_vector_first_invalid; free_count_zc_e_custom(&zc); } int hasSpeechStopped(int *zero_cross_vector, unsigned int zero_cross_vector_position, unsigned int *speech_start_position, unsigned int *speech_stop_position, unsigned int mainBufferSize) { // states: // 1: searching start of speech // 2: searching end of speech int state; int zc_threshold; int i; state = 1; zc_threshold = 60; int is_speech_stop; is_speech_stop = 0; unsigned int local_speech_start_window = 0; unsigned int local_speech_stop_window = 0; for (i = 0; i < zero_cross_vector_position; ++i) { switch (state) { case 1: if (zero_cross_vector[i] >= zc_threshold) { int is_speech_start; // 100 ms in 8k = 800 samples = 8 windows int j; if (i + 8 <= zero_cross_vector_position) { is_speech_start = 1; for (j = i + 1; j < i + 8; ++j) { if (zero_cross_vector[j] < zc_threshold) { is_speech_start = 0; break; } } if (is_speech_start) { local_speech_start_window = i; state = 2; i += 7; } } } break; case 2: if (zero_cross_vector[i] < zc_threshold) { // 500 ms in 8k = 4000 samples = 40 windows // 500 ms in 16k = 8000 samples = 80 windows int windows = (mainBufferSize == 320000) ? 160 : 80; int j; if (i + windows <= zero_cross_vector_position) { is_speech_stop = 1; for (j = i + 1; j < i + windows; ++j) { if (zero_cross_vector[j] >= zc_threshold) { is_speech_stop = 0; break; } } } } break; default: break; } if (is_speech_stop) { local_speech_stop_window = i; break; } } if (is_speech_stop) { *speech_start_position = local_speech_start_window; *speech_stop_position = local_speech_stop_window; } else { *speech_start_position = *speech_stop_position = UINT32_MAX; } return is_speech_stop; } void MyAudioQueueInputCallback( void *aqData, AudioQueueRef inAQ, AudioQueueBufferRef inBuffer, const AudioTimeStamp *inStartTime, UInt32 inNumPackets, const AudioStreamPacketDescription *inPacketDesc ) { // Pointer for convenience struct AQRecorderState *pAqData; pAqData = (struct AQRecorderState *) aqData; // main buffer void *_mainBuffer; // offset of main buffer unsigned int *_mainBufferOffset; // zero cross vector used to detect end of speech int *_zero_cross_vector; // Position of first non-valid elemtn in zero cross vector unsigned int *_zero_cross_vector_position; _mainBuffer = pAqData->mainBuffer; _mainBufferOffset = pAqData->mainBufferOffset; _zero_cross_vector = pAqData->zero_cross_vector; _zero_cross_vector_position = pAqData->zero_cross_vector_position; // Write in the main buffer. If there is no space left in main buffer, erase old samples from main buffer to fit new ones. if (*_mainBufferOffset + inBuffer->mAudioDataByteSize > pAqData->kMainBufferSize) { unsigned int difference; //difference = *_mainBufferOffset + inBuffer->mAudioDataByteSize - kMainBufferSize; difference = *_mainBufferOffset + inBuffer->mAudioDataByteSize - pAqData->kMainBufferSize; memmove(_mainBuffer, _mainBuffer + difference, *_mainBufferOffset - difference); *_mainBufferOffset -= difference; printf("overflow! data exceeded in %d bytes", difference); } memcpy(_mainBuffer + *_mainBufferOffset, inBuffer->mAudioData, inBuffer->mAudioDataByteSize); *_mainBufferOffset += inBuffer->mAudioDataByteSize; pAqData->audioBuffer = inBuffer->mAudioData; pAqData->lastLengthAudioBuffer = (int)inBuffer->mAudioDataByteSize; pAqData->callbackMethodImplementation(pAqData->callbackTarget, pAqData->callbackMethodSelector, (int)inBuffer->mAudioDataByteSize); // Enqueue buffer is running. if (pAqData->mIsRunning) { AudioQueueEnqueueBuffer(pAqData->mQueue, inBuffer, 0, NULL); } //Verify each two seconds if (*_mainBufferOffset >= 64000) { unsigned int speech_start_window; unsigned int speech_stop_window; // 2400 samples = (0,3 seconds) * (8000 samples / second) // 4800 samples = (0,3 seconds) * (16000 samples / second) //unsigned int samples = 4800; unsigned int samples = (pAqData->kMainBufferSize == 320000) ? 4800 : 2400; calculateZcVector(_mainBuffer, *_mainBufferOffset, _zero_cross_vector, zero_cross_vector_size, _zero_cross_vector_position, samples, window_size, level_threshold); if (hasSpeechStopped(_zero_cross_vector, *_zero_cross_vector_position, &speech_start_window, &speech_stop_window, pAqData->kMainBufferSize)) { pAqData->silenceCallbackMethodImplementation(pAqData->silenceCallbackTarget, pAqData->silenceCallbackMethodSelector, 1); } } }
2.296875
2
2024-11-18T17:55:28.846108+00:00
2019-12-20T17:13:43
52547dd91136cb9233baaf7f17f16ad404c86fa5
{ "blob_id": "52547dd91136cb9233baaf7f17f16ad404c86fa5", "branch_name": "refs/heads/master", "committer_date": "2019-12-20T17:13:43", "content_id": "c7ef04e4b11c76d00327fb1f94fb7ab49e079a98", "detected_licenses": [ "Apache-2.0" ], "directory_id": "1b1c347f119954e54a9ccfa4209323ed3f2095ae", "extension": "c", "filename": "main.c", "fork_events_count": 2, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 229290302, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4427, "license": "Apache-2.0", "license_type": "permissive", "path": "/v0.1/tests/system/blinky64/ws_blinky64/blinky64_3/src/main.c", "provenance": "stackv2-0005.json.gz:19959", "repo_name": "cloudxcc/Arduissimo", "revision_date": "2019-12-20T17:13:43", "revision_id": "25ad4d1830a65d7612198a16510764f41ade13c4", "snapshot_id": "b9aeadeb33b8f81f1d45cf754611fca305e31347", "src_encoding": "UTF-8", "star_events_count": 18, "url": "https://raw.githubusercontent.com/cloudxcc/Arduissimo/25ad4d1830a65d7612198a16510764f41ade13c4/v0.1/tests/system/blinky64/ws_blinky64/blinky64_3/src/main.c", "visit_date": "2020-11-27T03:46:24.349992" }
stackv2
// // Copyright 2019 Tobias Strauch, Munich, Bavaria, Germany // Licensed under the Apache License, Version 2.0, see LICENSE for details. // SPDX-License-Identifier: Apache-2.0 // #include "system.c" #define CYCLE 1000 #define OFFSET CYCLE / 64 void gpio6(int tag, int thisOffset) { int t, pwm, dir; t = 0; dir = 1; pwm = OFFSET * thisOffset; GPIO_6_OUT_SET = 0x1 << tag; GPIO_6_OUT_CLR = 0x1 << tag; while (1) { if (t == pwm) GPIO_6_OUT_SET = 0x1 << tag; if (t == CYCLE) { GPIO_6_OUT_CLR = 0x1 << tag; if (pwm == CYCLE) dir = -1; else if (pwm == 0) dir = 1; pwm += dir; t = 0; } else t += 1; }; } void gpio7(int tag, int thisOffset) { int t, pwm, dir; t = 0; dir = 1; pwm = OFFSET * thisOffset; GPIO_7_OUT_SET = 0x1 << tag; GPIO_7_OUT_CLR = 0x1 << tag; while (1) { if (t == pwm) GPIO_7_OUT_SET = 0x1 << tag; if (t == CYCLE) { GPIO_7_OUT_CLR = 0x1 << tag; if (pwm == CYCLE) dir = -1; else if (pwm == 0) dir = 1; pwm += dir; t = 0; } else t += 1; }; } void gpio6_0(int start_time) { if (start_time >= 0) { TC_START = 0xc0000000 + (((unsigned)&&gpio6_0_label >> 1) & 0x3ff); } else { gpio6_0_label: gpio6(0, 48); } } void gpio6_1(int start_time) { if (start_time >= 0) { TC_START = 0xc0000000 + (((unsigned)&&gpio6_1_label >> 1) & 0x3ff); } else { gpio6_1_label: gpio6(1, 49); } } void gpio6_2(int start_time) { if (start_time >= 0) { TC_START = 0xc0000000 + (((unsigned)&&gpio6_2_label >> 1) & 0x3ff); } else { gpio6_2_label: gpio6(2, 50); } } void gpio6_3(int start_time) { if (start_time >= 0) { TC_START = 0xc0000000 + (((unsigned)&&gpio6_3_label >> 1) & 0x3ff); } else { gpio6_3_label: gpio6(3, 51); } } void gpio6_4(int start_time) { if (start_time >= 0) { TC_START = 0xc0000000 + (((unsigned)&&gpio6_4_label >> 1) & 0x3ff); } else { gpio6_4_label: gpio6(4, 52); } } void gpio6_5(int start_time) { if (start_time >= 0) { TC_START = 0xc0000000 + (((unsigned)&&gpio6_5_label >> 1) & 0x3ff); } else { gpio6_5_label: gpio6(5, 53); } } void gpio6_6(int start_time) { if (start_time >= 0) { TC_START = 0xc0000000 + (((unsigned)&&gpio6_6_label >> 1) & 0x3ff); } else { gpio6_6_label: gpio6(6, 54); } } void gpio6_7(int start_time) { if (start_time >= 0) { TC_START = 0xc0000000 + (((unsigned)&&gpio6_7_label >> 1) & 0x3ff); } else { gpio6_7_label: gpio6(7, 55); } } void gpio7_0(int start_time) { if (start_time >= 0) { TC_START = 0xc0000000 + (((unsigned)&&gpio7_0_label >> 1) & 0x3ff); } else { gpio7_0_label: gpio7(0, 56); } } void gpio7_1(int start_time) { if (start_time >= 0) { TC_START = 0xc0000000 + (((unsigned)&&gpio7_1_label >> 1) & 0x3ff); } else { gpio7_1_label: gpio7(1, 57); } } void gpio7_2(int start_time) { if (start_time >= 0) { TC_START = 0xc0000000 + (((unsigned)&&gpio7_2_label >> 1) & 0x3ff); } else { gpio7_2_label: gpio7(2, 58); } } void gpio7_3(int start_time) { if (start_time >= 0) { TC_START = 0xc0000000 + (((unsigned)&&gpio7_3_label >> 1) & 0x3ff); } else { gpio7_3_label: gpio7(3, 59); } } void gpio7_4(int start_time) { if (start_time >= 0) { TC_START = 0xc0000000 + (((unsigned)&&gpio7_4_label >> 1) & 0x3ff); } else { gpio7_4_label: gpio7(4, 60); } } void gpio7_5(int start_time) { if (start_time >= 0) { TC_START = 0xc0000000 + (((unsigned)&&gpio7_5_label >> 1) & 0x3ff); } else { gpio7_5_label: gpio7(5, 61); } } void gpio7_6(int start_time) { if (start_time >= 0) { TC_START = 0xc0000000 + (((unsigned)&&gpio7_6_label >> 1) & 0x3ff); } else { gpio7_6_label: gpio7(6, 62); } } int main(void) { GPIO_6_DIR_SET = 0xff; GPIO_7_DIR_SET = 0xff; int CT = CA_CT; gpio6_0(CT); gpio6_1(CT); gpio6_2(CT); gpio6_3(CT); gpio6_4(CT); gpio6_5(CT); gpio6_6(CT); gpio6_7(CT); gpio7_0(CT); gpio7_1(CT); gpio7_2(CT); gpio7_3(CT); gpio7_4(CT); gpio7_5(CT); gpio7_6(CT); gpio7(7, 63); }
2.234375
2
2024-11-18T17:55:32.702256+00:00
2016-07-01T12:52:14
c007f25637259a9eea9a95ad214bcf689afccbea
{ "blob_id": "c007f25637259a9eea9a95ad214bcf689afccbea", "branch_name": "refs/heads/master", "committer_date": "2016-07-01T12:52:14", "content_id": "ab1641d411899f9a87861b92e81e1a2333995e98", "detected_licenses": [ "CC0-1.0" ], "directory_id": "f47e591253b77e813ae22748cc157521cceef9c0", "extension": "c", "filename": "main.c", "fork_events_count": 0, "gha_created_at": "2016-07-01T11:05:35", "gha_event_created_at": "2016-07-01T12:34:42", "gha_language": "C", "gha_license_id": null, "github_id": 62387249, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 416, "license": "CC0-1.0", "license_type": "permissive", "path": "/Atmel Studio/USER_APPLICATION6/USER_APPLICATION6/src/main.c", "provenance": "stackv2-0005.json.gz:20088", "repo_name": "rohitr16/ROBOTICS", "revision_date": "2016-07-01T12:52:14", "revision_id": "7fea0134f41ab87b3799e7c5a7ed2a2cd76195ef", "snapshot_id": "b1db1c4d171e7839855deac6178bb09f9c5ae0cd", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/rohitr16/ROBOTICS/7fea0134f41ab87b3799e7c5a7ed2a2cd76195ef/Atmel Studio/USER_APPLICATION6/USER_APPLICATION6/src/main.c", "visit_date": "2020-04-03T01:00:08.036866" }
stackv2
/** * \file * * \brief Empty user application template * */ /* * Include header files for all drivers that have been imported from * Atmel Software Framework (ASF). */ #include <avr/io.h> #include <util/delay.h> main (void) { DDRA=0xFF; while(1) { PORTA=0b01100000; _delay_ms(300); PORTA=0b00000000; _delay_ms(300); } // Insert application code here, after the board has been initialized. }
2.15625
2
2024-11-18T18:30:21.510427+00:00
2018-10-05T02:00:55
6bf6a21b108c9e0e396c40da56182b48d1b8698f
{ "blob_id": "6bf6a21b108c9e0e396c40da56182b48d1b8698f", "branch_name": "refs/heads/master", "committer_date": "2018-10-05T02:00:55", "content_id": "9562bc5ab35a918163a67897dcd9dc06e61c4262", "detected_licenses": [ "MIT" ], "directory_id": "06f999df1212b9e0583986728698366509e421c9", "extension": "c", "filename": "receive_bms.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3275, "license": "MIT", "license_type": "permissive", "path": "/boards/receive_bms/receive_bms.c", "provenance": "stackv2-0006.json.gz:531", "repo_name": "brycemann8334/MK_III-Code", "revision_date": "2018-10-05T02:00:55", "revision_id": "a2c5e49d4e74caaeb543aaa81258078d61eadfc0", "snapshot_id": "ab83e5dbfa696395e11cffd32f4f5f25838e7e9d", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/brycemann8334/MK_III-Code/a2c5e49d4e74caaeb543aaa81258078d61eadfc0/boards/receive_bms/receive_bms.c", "visit_date": "2020-05-16T12:50:53.094204" }
stackv2
#include <stdio.h> //for sprintf #include <stdlib.h> #include <string.h> #include <avr/io.h> #include <avr/interrupt.h> #include <util/delay.h> #include "can_api.h" #include "log_uart.h" //Global flag to transmit CAN volatile uint8_t gFlag = 0x00; volatile uint8_t msg_count = 0x00; uint8_t clock_prescale = 0x0A; volatile uint8_t ovf_count = 0x00; volatile uint8_t msg_voltages[8]; volatile uint8_t msg_temperatures[8]; //CAN message objects #define MOB_TEMPERATURES 0 #define MOB_VOLTAGES 1 void timer0_setup(){ sei(); //enable interrupts // Timer0 Overflow Interrupt Enabled TIMSK0 |= _BV(TOIE0); // Timer with 1024 prescaler TCCR0B |= _BV(CS02) | _BV(CS00); } ISR(TIMER0_OVF_vect){ ovf_count++; if (ovf_count > clock_prescale) { gFlag ^= 0x01; ovf_count = 0x00; } } ISR(CAN_INT_vect) { msg_count++; //adding this for troubleshooting throttle messages CANPAGE = (MOB_VOLTAGES << MOBNB0); if (bit_is_set(CANSTMOB,RXOK)) { msg_voltages[0] = CANMSG; msg_voltages[1] = CANMSG; msg_voltages[2] = CANMSG; msg_voltages[3] = CANMSG; msg_voltages[4] = CANMSG; msg_voltages[5] = CANMSG; msg_voltages[6] = CANMSG; msg_voltages[7] = CANMSG; CANSTMOB = 0x00; CAN_wait_on_receive(MOB_VOLTAGES, 0x13, 8, CAN_IDM_single); } CANPAGE = (MOB_TEMPERATURES << MOBNB0); if (bit_is_set(CANSTMOB,RXOK)) { msg_temperatures[0] = CANMSG; msg_temperatures[1] = CANMSG; msg_temperatures[2] = CANMSG; msg_temperatures[3] = CANMSG; msg_temperatures[4] = CANMSG; msg_temperatures[5] = CANMSG; msg_temperatures[6] = CANMSG; msg_temperatures[7] = CANMSG; CANSTMOB = 0x00; CAN_wait_on_receive(MOB_TEMPERATURES, 0x14, 8, CAN_IDM_single); } } //Suspension Strain or Air Control main int main(void){ timer0_setup(); LOG_init(); CAN_init(CAN_ENABLED); DDRB |= _BV(PB0); CAN_wait_on_receive(MOB_VOLTAGES, 0x13, 8, CAN_IDM_single); CAN_wait_on_receive(MOB_TEMPERATURES, 0x14, 8, CAN_IDM_single); while(1) { if(gFlag) { gFlag = 0x00; char disp_string_voltages[128]; //sprintf(disp_string,"%u messages received!",msg_count); sprintf(disp_string_voltages,"Voltage Message:\n%d\n%d\n%d\n%d\n%d\n%d\n%d\n%d", msg_voltages[0],msg_voltages[1],msg_voltages[2],msg_voltages[3], msg_voltages[4],msg_voltages[5],msg_voltages[6],msg_voltages[7]); LOG_println(disp_string_voltages,strlen(disp_string_voltages)); char disp_string_temperatures[128]; //sprintf(disp_string,"%u messages received!",msg_count); sprintf(disp_string_temperatures,"Temperature Message:\n%d\n%d\n%d\n%d\n%d\n%d\n%d\n%d", msg_temperatures[0],msg_temperatures[1],msg_temperatures[2],msg_temperatures[3], msg_temperatures[4],msg_temperatures[5],msg_temperatures[6],msg_temperatures[7]); LOG_println(disp_string_temperatures,strlen(disp_string_temperatures)); PORTB ^= _BV(PB0); } } }
2.203125
2
2024-11-18T18:30:21.698864+00:00
2017-03-27T19:54:13
238fca2256bc40ca693a0c94ce03106f78f1e01a
{ "blob_id": "238fca2256bc40ca693a0c94ce03106f78f1e01a", "branch_name": "refs/heads/master", "committer_date": "2017-03-27T19:54:13", "content_id": "8252e1a609b66971486bfb07333e29041bb00938", "detected_licenses": [ "Apache-2.0" ], "directory_id": "170cd9223fd9e6f5fa60c1f405cd74705efc0703", "extension": "c", "filename": "webkit-efl-extension-sample.c", "fork_events_count": 1, "gha_created_at": "2016-12-28T21:06:47", "gha_event_created_at": "2017-03-27T19:54:14", "gha_language": "C", "gha_license_id": null, "github_id": 77561378, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 10593, "license": "Apache-2.0", "license_type": "permissive", "path": "/src/webkit-efl-extension-sample.c", "provenance": "stackv2-0006.json.gz:659", "repo_name": "profusion/webkit-efl-sample", "revision_date": "2017-03-27T19:54:13", "revision_id": "a4f5a2ed69520f6d9f83cbd1d316b6c5f1977843", "snapshot_id": "36d3f9b34155fe6b53c56ced485abeaf1137a550", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/profusion/webkit-efl-sample/a4f5a2ed69520f6d9f83cbd1d316b6c5f1977843/src/webkit-efl-extension-sample.c", "visit_date": "2021-01-13T11:07:40.903004" }
stackv2
#include <stdio.h> #include <stdbool.h> #include <Ecore.h> #include <EWebKit_Extension.h> #include <JavaScriptCore/JavaScript.h> static double number_static_prop = 0.0; static JSClassRef example_class_ref = NULL; typedef struct _Example_Class_Data { Ecore_Timer *timer; JSContextRef ctx; JSValueRef timeout_cb; double tick; double number; } Example_Class_Data; static JSValueRef get_number_static_prop(JSContextRef ctx, JSObjectRef obj, JSStringRef propertyName, JSValueRef *exception) { return JSValueMakeNumber(ctx, number_static_prop); } static bool set_number_static_prop(JSContextRef ctx, JSObjectRef obj, JSStringRef propertyName, JSValueRef value, JSValueRef *exception) { double d = JSValueToNumber(ctx, value, exception); if (*exception) { fprintf(stderr, "Could not get the string value\n"); return false; } number_static_prop = d; return true; } static JSValueRef sum_array(JSContextRef ctx, JSObjectRef function, JSObjectRef obj, size_t argc, const JSValueRef argv[], JSValueRef* exception) { size_t len, i; JSObjectRef array; JSValueRef len_prop; JSStringRef prop_name; double sum = 0.0; if (!argc) { fprintf(stderr, "No arguments\n"); return NULL; } if (!JSValueIsArray(ctx, argv[0])) { fprintf(stderr, "The argument must be an array of numbers\n"); return NULL; } array = JSValueToObject(ctx, argv[0], exception); if (!array) { fprintf(stderr, "Could not Convert The array to object\n"); return NULL; } prop_name = JSStringCreateWithUTF8CString("length"); len_prop = JSObjectGetProperty(ctx, array, prop_name, exception); JSStringRelease(prop_name); if (JSValueIsUndefined(ctx, len_prop)) { fprintf(stderr, "Could not retrive the array's len\n"); return NULL; } len = (size_t)JSValueToNumber(ctx, len_prop, NULL); for (i = 0; i < len; i++) { JSValueRef value = JSObjectGetPropertyAtIndex(ctx, array, i, exception); if (!JSValueIsNumber(ctx, value)) { fprintf(stderr, "The element at index '%zu' is not a number!\n", i); return NULL; } sum += JSValueToNumber(ctx, value , NULL); } return JSValueMakeNumber(ctx, sum); } static JSValueRef convertToType(JSContextRef ctx, JSObjectRef obj, JSType type, JSValueRef* exception) { switch (type) { case kJSTypeString: { Example_Class_Data *priv_data = JSObjectGetPrivate(obj); char buf[32]; snprintf(buf, sizeof(buf), "Example Class {priv data: %g}", priv_data->number); JSStringRef string = JSStringCreateWithUTF8CString(buf); JSValueRef result = JSValueMakeString(ctx, string); JSStringRelease(string); return result; } default: return JSValueMakeNull(ctx); } } static JSValueRef example_function_cb(JSContextRef ctx, JSObjectRef function, JSObjectRef obj, size_t argc, const JSValueRef argv[], JSValueRef* exception) { JSValueRef value; JSStringRef str = JSStringCreateWithUTF8CString("This is a string generated by the exampleFunction()"); value = JSValueMakeString(ctx, str); JSStringRelease(str); return value; } static Eina_Bool _timeout(void *data) { JSValueRef arg; JSObjectRef obj = data; Example_Class_Data *priv_data = JSObjectGetPrivate(obj); JSObjectRef function = JSValueToObject(priv_data->ctx, priv_data->timeout_cb, NULL); arg = JSValueMakeNumber(priv_data->ctx, priv_data->tick); JSObjectCallAsFunction(priv_data->ctx, function, obj, 1, &arg, NULL); priv_data->tick++; return ECORE_CALLBACK_RENEW; } static JSValueRef register_timer_cb(JSContextRef ctx, JSObjectRef function, JSObjectRef obj, size_t argc, const JSValueRef argv[], JSValueRef *exception) { double timeout_time; Example_Class_Data *priv_data = JSObjectGetPrivate(obj); if (priv_data->timer) { fprintf(stderr, "Timer already registered\n"); return JSValueMakeBoolean(ctx, false); } if (argc < 2) { fprintf(stderr, "Missing arguments\n"); return JSValueMakeBoolean(ctx, false); } timeout_time = JSValueToNumber(ctx, argv[0], NULL); priv_data->timer = ecore_timer_add(timeout_time, _timeout, obj); if (!priv_data->timer) { fprintf(stderr, "Could not create the timer\n"); return JSValueMakeBoolean(ctx, false); } priv_data->timeout_cb = argv[1]; //Do not garbage collect priv_data->tick = 0; JSValueProtect(ctx, priv_data->timeout_cb); return JSValueMakeBoolean(ctx, true); } static JSValueRef unregister_timer_cb(JSContextRef ctx, JSObjectRef function, JSObjectRef obj, size_t argc, const JSValueRef argv[], JSValueRef* exception) { Example_Class_Data *priv_data = JSObjectGetPrivate(obj); if (priv_data->timer) { ecore_timer_del(priv_data->timer); priv_data->timer = NULL; JSValueUnprotect(ctx, priv_data->timeout_cb); priv_data->timeout_cb = NULL; return JSValueMakeBoolean(ctx, true); } return JSValueMakeBoolean(ctx, false); } static void register_function(JSContextRef ctx, JSObjectRef obj, const char *name, JSObjectCallAsFunctionCallback cb) { JSStringRef func_name = JSStringCreateWithUTF8CString(name); JSObjectSetProperty(ctx, obj, func_name, JSObjectMakeFunctionWithCallback(ctx, func_name, cb), kJSPropertyAttributeNone, NULL); JSStringRelease(func_name); } static JSObjectRef constructor(JSContextRef ctx, JSObjectRef constructor, size_t argc, const JSValueRef argv[], JSValueRef *exception) { JSObjectRef obj; obj = JSObjectMake(ctx, example_class_ref, NULL); register_function(ctx, obj, "exampleFunction", example_function_cb); register_function(ctx, obj, "registerTimer", register_timer_cb); register_function(ctx, obj, "unregisterTimer", unregister_timer_cb); return obj; } static JSValueRef get_property(JSContextRef ctx, JSObjectRef obj, JSStringRef prop_name, JSValueRef *exception) { if (!JSStringIsEqualToUTF8CString(prop_name, "instanceProperty")) return NULL; //try the static properties Example_Class_Data *priv_data = JSObjectGetPrivate(obj); return JSValueMakeNumber(ctx, priv_data->number); } static bool set_property(JSContextRef ctx, JSObjectRef obj, JSStringRef prop_name, JSValueRef value, JSValueRef *exception) { Example_Class_Data *priv_data; double d; if (!JSStringIsEqualToUTF8CString(prop_name, "instanceProperty")) return false; //try the static properties d = JSValueToNumber(ctx, value, exception); if (*exception) { fprintf(stderr, "Could not set the instanceProperty\n"); return true; } priv_data = JSObjectGetPrivate(obj); priv_data->number = d; return true; } static void initialize(JSContextRef ctx, JSObjectRef obj) { Example_Class_Data *priv_data = calloc(1, sizeof(Example_Class_Data)); priv_data->ctx = JSContextGetGlobalContext(ctx); JSObjectSetPrivate(obj, priv_data); } static void finalize(JSObjectRef obj) { Example_Class_Data *priv_data = JSObjectGetPrivate(obj); if (!priv_data) return; ecore_timer_del(priv_data->timer); free(priv_data); } static const JSStaticValue static_properties[] = { { "NumberStaticProperty", get_number_static_prop, set_number_static_prop, kJSPropertyAttributeDontDelete }, { 0, 0, 0, 0 } }; static const JSStaticFunction static_functions[] = { { "SumArrayStaticFunction", sum_array, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete }, { 0, 0, 0 } }; static const JSClassDefinition example_class = { 0, // version kJSClassAttributeNone, // attributes "ExampleClass", // className NULL, // parentClass static_properties, static_functions, initialize, finalize, NULL, //has property get_property, set_property, NULL, //deleteProperty NULL, //get property names NULL, constructor, NULL, //hasInstance convertToType }; //Javasript is ready to load new classes/properties static void on_window_object_cleared(Ewk_Page *page, void *data) { JSObjectRef js_global_obj, js_class_obj; JSGlobalContextRef js_context; JSStringRef str; js_context = ewk_page_js_global_context_get(page); EINA_SAFETY_ON_NULL_RETURN(js_context); js_global_obj = JSContextGetGlobalObject(js_context); example_class_ref = JSClassCreate(&example_class); js_class_obj = JSObjectMake(js_context, example_class_ref, NULL); str = JSStringCreateWithUTF8CString("ExampleClass"); JSObjectSetProperty(js_context, js_global_obj, str, js_class_obj, kJSPropertyAttributeNone, NULL); JSStringRelease(str); } static const struct EwkPageClient extension_page = { .version = 1, .data = NULL, .load_started = NULL, .load_finished = NULL, .window_object_cleared = on_window_object_cleared }; static void on_page_add(Ewk_Page *page, void *data) { ewk_page_client_register(page, &extension_page); } static void on_page_del(Ewk_Page *page, void *data) { ewk_page_client_unregister(page, &extension_page); } static struct EwkExtensionClient client_extension = { .version = 1, .data = NULL, .page_add = on_page_add, .page_del = on_page_del, .message_received = NULL }; //Automatically called by WebKit void ewk_extension_init(Ewk_Extension *extension) { if (!ewk_extension_client_add(extension, &client_extension)) fprintf(stderr, "Could not add the extension!\n"); }
2.453125
2
2024-11-18T19:20:29.533737+00:00
2023-08-01T17:54:29
37b85fb069e54d84a488b86879362302ac342da7
{ "blob_id": "37b85fb069e54d84a488b86879362302ac342da7", "branch_name": "refs/heads/master", "committer_date": "2023-08-01T17:54:29", "content_id": "29e33acf2632c7df854dd7b3728d103075c741ea", "detected_licenses": [ "MIT" ], "directory_id": "909df5e29f5249b7ee1b12a3668148f8b5436fd4", "extension": "c", "filename": "wtest.c", "fork_events_count": 15, "gha_created_at": "2009-06-16T22:24:23", "gha_event_created_at": "2022-07-23T19:10:57", "gha_language": "C", "gha_license_id": "MIT", "github_id": 229070, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 828, "license": "MIT", "license_type": "permissive", "path": "/src/wutils/wtest.c", "provenance": "stackv2-0006.json.gz:134224", "repo_name": "jezze/fudge", "revision_date": "2023-08-01T17:54:29", "revision_id": "7407284297b87c3005428adaaa1d1e0c55d4d6fe", "snapshot_id": "4d9965a87c937ee0bd8feb505179cc2bd61e655a", "src_encoding": "UTF-8", "star_events_count": 72, "url": "https://raw.githubusercontent.com/jezze/fudge/7407284297b87c3005428adaaa1d1e0c55d4d6fe/src/wutils/wtest.c", "visit_date": "2023-08-02T14:34:04.859847" }
stackv2
#include <fudge.h> #include <abi.h> static void onmain(unsigned int source, void *mdata, unsigned int msize) { channel_send(option_getdecimal("wm-service"), EVENT_WMMAP); while (channel_process()); channel_send(option_getdecimal("wm-service"), EVENT_WMUNMAP); } static void onwminit(unsigned int source, void *mdata, unsigned int msize) { char *data = "+ window id \"window\" title \"Test\"\n" " + layout id \"base\" in \"window\" flow \"vertical\" padding \"1\"\n" " + image in \"base\" mimetype \"image/pcx\" source \"initrd:data/giant.pcx\"\n"; channel_send_fmt0(option_getdecimal("wm-service"), EVENT_WMRENDERDATA, data); } void init(void) { option_add("wm-service", "12345"); channel_bind(EVENT_MAIN, onmain); channel_bind(EVENT_WMINIT, onwminit); }
2.0625
2
2024-11-18T19:20:29.585262+00:00
2021-07-18T09:39:47
bb075689da411a43d7af47c84aee708325e49185
{ "blob_id": "bb075689da411a43d7af47c84aee708325e49185", "branch_name": "refs/heads/master", "committer_date": "2021-07-18T09:39:47", "content_id": "d3c2ec979dbb8f5f43822e548be21856259ec28b", "detected_licenses": [ "Apache-2.0" ], "directory_id": "7a2a92de0b46c00f4ecbbfb7bed5e798a94d38cb", "extension": "h", "filename": "thread.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 369580802, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1300, "license": "Apache-2.0", "license_type": "permissive", "path": "/src/util/thread.h", "provenance": "stackv2-0006.json.gz:134352", "repo_name": "conquerw/cw_reactor", "revision_date": "2021-07-18T09:39:47", "revision_id": "d799fb5ac883f84edcb33b898ca2c67f8eff13b4", "snapshot_id": "8307452b5dfeec4c1a398539f374ed34ff7d4a1a", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/conquerw/cw_reactor/d799fb5ac883f84edcb33b898ca2c67f8eff13b4/src/util/thread.h", "visit_date": "2023-06-17T06:29:11.276159" }
stackv2
/*********************************************** * @addtogroup CITS * @{ * @file : thread.h * @brief : * @author: wangshaobo * @email : [email protected] * @date : 2019-05-10 10:43:51 ***********************************************/ //-------------------------------------------------- // Copyright (c) CITS //-------------------------------------------------- #ifndef _THREAD_H_ #define _THREAD_H_ #ifdef __cplusplus extern "C" { #endif #include <stdio.h> #include <unistd.h> #include <pthread.h> static inline int create_thread(void *(*func)(void *), void *para) { pthread_t pthread; int ret = pthread_create(&pthread, NULL, func, para); if(ret == 0) { printf("create_thread success!\n"); usleep(50 * 1000); } else { printf("create_thread fail!\n"); return -1; } pthread_detach(pthread); return 1; } static inline int create_thread2(pthread_t *pthread, void *(*func)(void *), void *para) { int ret = pthread_create(pthread, NULL, func, para); if(ret == 0) { printf("create_thread2 success!\n"); usleep(50 * 1000); } else { printf("create_thread2 fail!\n"); return -1; } pthread_detach(*pthread); return 1; } static inline void cancel_thread(pthread_t pthread) { pthread_cancel(pthread); } #ifdef __cplusplus } #endif #endif
2.4375
2
2024-11-18T19:22:10.758460+00:00
2014-03-21T18:19:47
60c7721f4ae91d29fe58f66b340813273a5198cd
{ "blob_id": "60c7721f4ae91d29fe58f66b340813273a5198cd", "branch_name": "refs/heads/master", "committer_date": "2014-03-21T18:19:47", "content_id": "568d290e8530a0f9242ba8d02268abf6070cc79d", "detected_licenses": [ "Unlicense" ], "directory_id": "fd64e83a7eacd4879a4f8d42fe40e56210432174", "extension": "c", "filename": "init.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 10521, "license": "Unlicense", "license_type": "permissive", "path": "/bfin_lib/src/init.c", "provenance": "stackv2-0006.json.gz:134480", "repo_name": "emergencyofstate/aleph", "revision_date": "2014-03-21T18:19:47", "revision_id": "fdb9b728cae11b19987f3692bf98ef90870a451f", "snapshot_id": "2806de80f112ee7e33d521a9da7801b6681bea70", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/emergencyofstate/aleph/fdb9b728cae11b19987f3692bf98ef90870a451f/bfin_lib/src/init.c", "visit_date": "2021-01-24T22:22:55.451385" }
stackv2
#include "bfin_core.h" #include "isr.h" #include "init.h" //------ global variables initialized here // SPORT0 DMA transmit buffer volatile s32 iTxBuf[4]; // SPORT0 DMA receive buffer volatile s32 iRxBuf[4]; //----- function definitions // initialize clocks void init_clocks(void) { //// check: // const u16 pll_ctl = *pPLL_CTL; // const u16 pll_div = *pPLL_DIV; // u8 dum = 0; // dum++; // dum++; // set MSEL = 20 for core clock of 108Mhz // *pPLL_CTL = 0x2800; /////// changing to 533Mhz part /// MSEL = 19 //// VCO = 19 * CLKIN = 513 *pPLL_CTL = 0x2600; ssync(); } // initialize EBI void init_EBIU(void) { // straight from the self-test example project // Initalize EBIU control registers to enable all banks *pEBIU_AMBCTL1 = 0xFFFFFF02; ssync(); // -- not sure why there is a read here, possibly anomaly 05000157? //temp = *pEBIU_AMBCTL1; //temp++; *pEBIU_AMGCTL = 0x00FF; ssync(); // Check if already enabled if( SDRS != ((*pEBIU_SDSTAT) & SDRS) ) { return; } //SDRAM Refresh Rate Control Register // *pEBIU_SDRRC = 0x01A0; // for 108Mhz system clock: *pEBIU_SDRRC = 835; //SDRAM Memory Bank Control Register *pEBIU_SDBCTL = 0x0025; //1.7 64 MB bank size // *pEBIU_SDBCTL = 0x0013; //1.6 and below 32 MB //SDRAM Memory Global Control Register *pEBIU_SDGCTL = 0x0091998d;//0x998D0491; ssync(); } // setup SPI0 -> AD1939 config */ void init_1939(void) { // u8 i; volatile u32 del; //// reset codec *pFIO_FLAG_D &= CODEC_RESET_MASK; del = 100; while(del--) { ;; } // del = 1000; while(del--) { ;; } *pFIO_FLAG_D |= (0xffff ^ CODEC_RESET_MASK); del = 10000; while(del--) { ;; } /// using the codec in standalone now, dont need SPI config return; /* //// TESTING: */ /* /// wait for the codec to reset */ /* /// from the datasheet, this could take an absolute maximum of (4096 / 6.9Mhz)s (?) */ /* /// we are using BF clock = 513 MHz, so: */ /* del = 308000; while(del--) { ;; } */ /* // set PF4 as slave select */ /* *pSPI_FLG = 0xFF10; */ /* // Set baud rate SCK = HCLK/(2*SPIBAUD) SCK = 2MHz */ /* *pSPI_BAUD = 16; */ /* // setup SPI: */ /* /// master, non-DMA mode, 8b transfers, MSB first, */ /* /// TX on buffer write, clock rising edge: */ /* //// this would give us the waveform we want but puts CS under hardware control */ /* // *pSPI_CTL = MSTR | TIMOD_BUF_TX; */ /* /// SPI controller can't do 24-bits transfers-- */ /* /// workaround: 8-bit transfers and manual slave select */ /* // ( see http://ez.analog.com/thread/1248 */ /* // SS from software : */ /* *pSPI_CTL = MSTR | CPHA | CPOL | TIMOD_BUF_TX; */ /* // enable SPI */ /* *pSPI_CTL = (*pSPI_CTL | SPE); */ /* ssync(); */ /* // loop over registers */ /* for(i=0; i<CODEC_1939_NUM_REGS; i++) { */ /* // select slave */ /* // *pFIO_FLAG_D &= CODEC_SS_MASK; */ /* // bring SS low (PF4) */ /* *pSPI_FLG = 0xef10; */ /* // send command byte */ /* spi_send_byte(CODEC_CMD_BYTE); */ /* // send register byte */ /* spi_send_byte(codec1939TxRegs[i][0]); */ /* /// send dta byte */ /* spi_send_byte(codec1939TxRegs[i][1]); */ /* // bring SS high (PF4) */ /* *pSPI_FLG = 0xff10; */ /* } */ } // init_1939 //--------------------------------------------------------------------// // init_spi_slave() // (re-)configure spi in slave mode to receive control data from avr32 void init_spi_slave(void) { int j; // don't attempt to drive the clock *pSPI_BAUD = 0; // reset the flags register? to defaults? *pSPI_FLG = 0xff00; // try clearing the rx error bit? (sticky - W1C) *pSPI_STAT |= 0x10; *pSPI_STAT |= 0x10; // slave mode, 16 bit transfers, MSB first, non-dma rx mode, overwrite (interrupt when SPI_RDBR is full) // phase: seems crazy but i think bfin and avr32 have opposite definitions of clock phase! oh lordy // *pSPI_CTL = CPHA | SIZE | GM; // actually need 8 bits to be compatible with SPI-boot //----->>>>> *pSPI_CTL = CPHA | GM; *pSPI_CTL = CPHA | GM | SZ; // enable transmit on MISO *pSPI_CTL |= EMISO; // enable spi (now in slave mode) *pSPI_CTL = (*pSPI_CTL | SPE); // clear the spi rx register by reading from it j = *pSPI_RDBR; // clear the rx error bit (sticky - W1C) *pSPI_STAT |= 0x10; } // configure sport0 for i2s mode with external clock void init_sport0(void) { // Sport0 receive configuration // External CLK, External Frame sync, MSB first, Active Low // 24-bit data, Stereo frame sync enable *pSPORT0_RCR1 = RFSR | RCKFE; *pSPORT0_RCR2 = SLEN_24 | RXSE | RSFSE; // Sport0 transmit configuration // External CLK, External Frame sync, MSB first, Active Low // 24-bit data, Secondary side enable, Stereo frame sync enable *pSPORT0_TCR1 = TFSR | TCKFE; *pSPORT0_TCR2 = SLEN_24 | TXSE | TSFSE; } // CONFIGURE sport1 [ to drive 3x AD5684 from DT1PRI ] void init_sport1(void) { u32 config; //----- note: edge selection is for *driving* the pins, sampled opposite //// TFS/clk driven w/ rising edge : TCKFE = 0 //// early frame sync : LATFS = 0 //// TFS active high : LTFS = 0 //// data-dependent TFS : DITFS = 0 //// internal clock : ITCLK = 1 //// internal TFS : ITFS = 1 //// frame sync required : TFSR = 1 //// no companding : TDTYPE = 00 //// MSB first : TLSBIT = 0 *pSPORT1_TCR1 = ITCLK | ITFS | TFSR; //----- note: edge selection is for *driving* the pins, sampled opposite //// TFS/clk driven w/ rising edge : TCKFE = 0 //// late frame sync : LATFS = 1 //// TFS active low : LTFS = 1 //// data-dependent TFS : DITFS = 0 //// internal clock : ITCLK = 1 //// internal TFS : ITFS = 1 //// frame sync required : TFSR = 1 //// no companding : TDTYPE = 00 //// MSB first : TLSBIT = 0 // *pSPORT1_TCR1 = ITCLK | ITFS | TFSR | LTFS | LATFS; //===== TEST: data-independent TFS // *pSPORT1_TCR1 = ITCLK | ITFS | DITFS; //// normal mode : TSFSE = 0 //// secondary side enabled : TXSE = 1 ///// 24-bit word length // *pSPORT1_TCR2 = 23 | TXSE ; //// 25-bit cause DACs need an extra cycle to recover, ugggh *pSPORT1_TCR2 = 24 | TXSE ; /// TEST: 32-bit word length // *pSPORT1_TCR2 = slen_32; // clock division: we want ~10Mhz, core clock is 108Mhz // tclk = sclk / ( 2 x (div + 1) // *pSPORT1_TCLKDIV = 5; /// DAC datasheet indicates we can go up to 50Mhz // here's 27 Mhz? /// this works fine in the triangle test *pSPORT1_TCLKDIV = 1; // ??? // *pSPORT1_TCLKDIV = 2; // *pSPORT1_TCLKDIV = 10; //// slower: // *pSPORT1_TCLKDIV = 100; //// slowest: // *pSPORT1_TCLKDIV = 0xffff; // we want frame syncs every 24 clocks, // FS period = clk period * (TFSDIV + 1) //// need an extra bit at the end for the DAC, grr // *pSPORT1_TFSDIV = 23; //// daisychain x2: // *pSPORT1_TFSDIV = 48; config = *pSPORT1_TCR1; /// enable sport1 ////// do this later for DMA /// *pSPORT1_TCR1 |= TSPEN; /// receive configuration: don't care? // *pSPORT1_RCR1 = RFSR | RCKFE; // *pSPORT1_RCR2 = SLEN_24 | RXSE | RSFSE; } // initialize DMA in autobuffer mode void init_DMA(void) { // Set up DMA1 to receive // Map DMA1 to Sport0 RX *pDMA1_PERIPHERAL_MAP = 0x1000; // Configure DMA1 // 32-bit transfers, Interrupt on completion, Autobuffer mode *pDMA1_CONFIG = WNR | WDSIZE_32 | DI_EN | FLOW_1; // Start address of data buffer *pDMA1_START_ADDR = (void *)iRxBuf; // DMA inner loop count *pDMA1_X_COUNT = 4; // Inner loop address increment *pDMA1_X_MODIFY = 4; // Set up DMA2 to transmit // Map DMA2 to Sport0 TX *pDMA2_PERIPHERAL_MAP = 0x2000; // Configure DMA2 // 32-bit transfers, Autobuffer mode *pDMA2_CONFIG = WDSIZE_32 | FLOW_1; // Start address of data buffer *pDMA2_START_ADDR = (void *)iTxBuf; // DMA inner loop count *pDMA2_X_COUNT = 4; // Inner loop address increment *pDMA2_X_MODIFY = 4; /// map dma4 to sport1 tx *pDMA4_PERIPHERAL_MAP = 0x4000; // configure DMA4 /// no interrupt on completion *pDMA4_CONFIG = WDSIZE_32 | FLOW_1; //*pDMA4_CONFIG = WDSIZE_32 | FLOW_1 | DI_EN; // Start address of data buffer *pDMA4_START_ADDR = (void *)(&cvTxBuf); // DMA inner loop count *pDMA4_X_COUNT = 1; // Inner loop address increment *pDMA4_X_MODIFY = 4; } // enable sport0 DMA void enable_DMA_sport0(void) { // enable DMAs *pDMA2_CONFIG = (*pDMA2_CONFIG | DMAEN); *pDMA1_CONFIG = (*pDMA1_CONFIG | DMAEN); // enable Sport0 TX and RX *pSPORT0_TCR1 = (*pSPORT0_TCR1 | TSPEN); *pSPORT0_RCR1 = (*pSPORT0_RCR1 | RSPEN); } // begin transfers with sport1 and dma4 void enable_DMA_sport1(void) { // enable DMAs *pDMA4_CONFIG = (*pDMA4_CONFIG | DMAEN); // enable sport1 tx *pSPORT1_TCR1 = (*pSPORT1_TCR1 | TSPEN); // *pSPORT1_RCR1 = (*pSPORT1_RCR1 | RSPEN); } // initialize programmable flags for button input void init_flags(void) { // inputs //// no gpio input // *pFIO_INEN = PF_IN; // outputs *pFIO_DIR = 0; *pFIO_DIR |= CODEC_RESET_UNMASK; *pFIO_DIR |= CODEC_RESET_UNMASK; *pFIO_DIR |= DAC_RESET_UNMASK; *pFIO_DIR |= READY_UNMASK; *pFIO_DIR |= LED3_UNMASK; *pFIO_DIR |= LED4_UNMASK; /* // edge-sensitive */ /* *pFIO_EDGE = 0x0f00; */ /* // both rise and fall */ /* *pFIO_BOTH = 0x0f00; */ /* // set interrupt mask */ /* *pFIO_MASKA_D = 0x0f00; */ } // assign interrupts void init_interrupts(void) { int i=0; // assign peripheral interrupts to core IDs *pSIC_IAR0 = 0xffffffff; // sport0 rx (dma1) -> ID4 = IVG11 // spi rx -> ID2 = IVG9 // sport1 tx -> ID3 = IVG10 // *pSIC_IAR1 = 0xff32ff2f; // *pSIC_IAR2 = 0xffffffff; // by default: // sport0 rx (dma1) -> ID2 = IVG9 // sport1 tx -> ID2 = IVG9 // spi rx -> ID3 = IVG10 // assign ISRs to interrupt vectors: //// ok, this ISR will serve both sports... *pEVT9 = sport0_rx_isr; *pEVT10 = spi_rx_isr; // *pEVT10 = sport1_tx_isr; // unmask in the core event processor asm volatile ("cli %0; bitset(%0, 9); bitset(%0, 10); sti %0; csync;": "+d"(i)); // unmask peripheral interrupts *pSIC_IMASK = 0x00003200; }
2.109375
2
2024-11-18T19:22:10.846010+00:00
2021-04-28T03:25:53
dec6cb241c0490533f846712f7ca305253aca153
{ "blob_id": "dec6cb241c0490533f846712f7ca305253aca153", "branch_name": "refs/heads/master", "committer_date": "2021-04-28T03:25:53", "content_id": "1846ff7a9c6924dc233911b4a099982dc8a61eb9", "detected_licenses": [ "MIT" ], "directory_id": "5b024145f586e1674a753e2fa1e25c77430ccc87", "extension": "c", "filename": "lcd_sf.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 335837753, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2715, "license": "MIT", "license_type": "permissive", "path": "/source/lcd/lcd_sf.c", "provenance": "stackv2-0006.json.gz:134609", "repo_name": "Jsfain/AVR-MP3", "revision_date": "2021-04-28T03:25:53", "revision_id": "6677b9e2f7eb785dfacaf9e0a41fe2f5386bc18b", "snapshot_id": "5b18c7f7b2de1f37ac6c04e51c8a2100a98bb0da", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Jsfain/AVR-MP3/6677b9e2f7eb785dfacaf9e0a41fe2f5386bc18b/source/lcd/lcd_sf.c", "visit_date": "2023-04-13T21:18:02.532755" }
stackv2
/* * File : LCD_SF.C * Author : Joshua Fain * Host Target : ATMega1280 * LCD : Gravitech 20x4 LCD with built-in HD44780 controller * License : MIT * Copyright (c) 2020, 2021 * * Implementation of LCD_SF.H */ #include <stdint.h> #include <avr/io.h> #include <util/delay.h> #include "lcd_base.h" #include "lcd_sf.h" #include "prints.h" /* ****************************************************************************** * FUNCTIONS ****************************************************************************** */ /* * ---------------------------------------------------------------------------- * READ ADDRESS COUNTER * * Description : Gets the value in the address counter. It does this by calling * lcd_readBusyAndAddr() and clearing the busy flag from its * returned value, leaving only the address counter value. * * Arguments : None * * Returns : Current value in the address counter. * ----------------------------------------------------------------------------- */ uint8_t lcd_readAddr (void) { // extract and return address. return (ADDRESS_MASK & lcd_readBusyAndAddr()); } /* * ---------------------------------------------------------------------------- * CURSOR RIGHT or LEFT SHIFT * * Description : Shift the cursor one position to the right or left, depending * on which function is called. These functions will call * lcd_cursorDisplayShift() with the appropriate arguments. * * Arguments : void * * Returns : void * ---------------------------------------------------------------------------- */ void lcd_rightShiftCursor (void) { lcd_cursorDisplayShift (CURSOR_SHIFT | RIGHT_SHIFT); } void lcd_leftShiftCursor (void) { lcd_cursorDisplayShift (CURSOR_SHIFT | LEFT_SHIFT); } /* * ---------------------------------------------------------------------------- * DISPLAY RIGHT or LEFT SHIFT * * Description : Shift the entire display one position to the right or left, * depending on which function is called. These functions will * call lcd_cursorDisplayShift() with the appropriate arguments. * * Arguments : void * * Returns : void * ---------------------------------------------------------------------------- */ void lcd_rightShiftDisplay (void) { lcd_cursorDisplayShift (DISPLAY_SHIFT | RIGHT_SHIFT); } void lcd_leftShiftDisplay (void) { lcd_cursorDisplayShift (DISPLAY_SHIFT | LEFT_SHIFT); }
2.46875
2
2024-11-18T19:43:11.841001+00:00
2016-04-26T21:06:52
da4597d69feac07038c1dca2613f134c7fd1899d
{ "blob_id": "da4597d69feac07038c1dca2613f134c7fd1899d", "branch_name": "refs/heads/master", "committer_date": "2016-04-26T21:06:52", "content_id": "024e2eb7b7bbd30cbd0b27b918428b25bcf162c4", "detected_licenses": [ "MIT" ], "directory_id": "19941e65b1ede67bd7c7775dbb5819398ec65281", "extension": "c", "filename": "parser.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3230, "license": "MIT", "license_type": "permissive", "path": "/src/lib/parsers/parser.c", "provenance": "stackv2-0007.json.gz:63274", "repo_name": "jbulow/ardp", "revision_date": "2016-04-26T21:06:52", "revision_id": "a756eb0b736d4f09d34b67de14d644608205de1f", "snapshot_id": "b7bb678c95b21210194abba0e9eed22c016856d3", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/jbulow/ardp/a756eb0b736d4f09d34b67de14d644608205de1f/src/lib/parsers/parser.c", "visit_date": "2021-05-15T01:59:59.869285" }
stackv2
ardp_status_t ardp_parser_create(); ardp_status_t ardp_parser_init( ardp_parser_config_t *cfg ); ardp_status_t ardp_parser_consume( ardp_token_t token ); ardp_status_t ardp_parser_set_parse_handler( void *fc ); ardp_status_t ardp_parser_set_error_handler( void *fc ); ardp_status_t ardp_parser_destroy(); ardp_parser_push( ( token ){RDF_BNODE, {1, 3}, "_:"} ); ardp_parser_pop(); struct _cursor { size_t line; size_t col; } cursor; struct _token { enum type; struct cursor pos; union { int i; double dbl; utf8 str; char chr; } value; } token; struct { const uint8_t *uri; const uint8_t *name; } ardp_rdf_turtle_prefix; struct _parser { bool ignore_types; // do not append informations about the type eg. ^^lang:@en bool expand_prefixes; int state; ardp_rdf_turtle_prefix *prefixes; // hold prefixes and base URI size_t n_prefixes; uint8_t *_Nullable base_uri; ardp_linked_list *tokens; // holds pseudo AST void ( *error )( struct cursor cur, token tok ); void ( *event )( token tok ); } parser; ardp_state_t ardp_parser_state() { return NULL; } ardp_status_t ardp_parser_set_base_uri( utf8 *_Nonnull uri ) { if ( uri is NULL ) { return 0; // TODO: should return the correct error value. } if ( ardp_parser_state() isnt ARDP_STATE_READY ) { return 0; // TODO: should return not ready err value } if ( parser->base_uri ) { free( parser->base_uri ); } // FIXME: should have copy function inside the 'string.h' string_header_t *hdr = string_hdr( uri ); memcpy( parser->base_uri, uri, hdr->len ); return 1; // TODO: should have proper return code } ardp_rdf_turtle_prefix_t *ardp_parser_prefix_find( const uint8_t *name, size_t len ) { if ( ardp_parser_state() isnt ARDP_STATUS_READY ) return -1; for ( size_t i = 0; i < prefix->n_prefixes; i++ ) { const uint8_t *const prefix_name = &parser->prefixes[i].name; if ( !memcmp( prefix_name, name, length ) ) return &parser->prefixes[i]; } } ardp_status_t ardp_parser_prefix_add( const uint8_t *name, const uint8_t *uri ) { if ( ardp_parser_state() isnt ARDP_STATUS_READY ) return -1; // TODO: meaningful state error ardp_rdf_turtle_prefix_t *const prefix = ardp_parser_prefix_find( name, strlen( name ) ); if ( prefix ) { uint8_t *old_predix_uri = ( uint8_t * )prefix->uri; prefix->uri = memcpy( parser->uri, uri, strlen( uri ) ); free( &old_prefix_uri ); } else { parser->prefixes = ( SerdPrefix * )realloc( parser->prefixes, ( ++parser->n_prefixes ) * sizeof( struct ardp_rdf_turtle_prefix ) ); parser->prefixes[parser->n_prefixes - 1].name = ardp_node_copy( name ); parser->prefixes[parser->n_prefixes - 1].uri = ardp_node_copy( uri ); } }
2.25
2
2024-11-18T19:43:11.911301+00:00
2008-08-08T16:15:41
5d7530540b9d0aa99ec7d20856c20265018836ac
{ "blob_id": "5d7530540b9d0aa99ec7d20856c20265018836ac", "branch_name": "refs/heads/master", "committer_date": "2008-08-08T16:15:41", "content_id": "ae2680e9c2c1d71def1c5d2837b8c3165cfab5da", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "06e0575d2518c9f17bcbbdf7ec47ebd95ad02020", "extension": "c", "filename": "ga.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 41063, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 9623, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/ga.c", "provenance": "stackv2-0007.json.gz:63402", "repo_name": "rpj/c-ga", "revision_date": "2008-08-08T16:15:41", "revision_id": "0f6cf3d96a441b6576f372283f34f1dafc750f15", "snapshot_id": "a50e9b526aa805f26c83a03d44d987a1806293a5", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/rpj/c-ga/0f6cf3d96a441b6576f372283f34f1dafc750f15/ga.c", "visit_date": "2016-09-11T02:17:05.516561" }
stackv2
/* gcc -g -lm -o ga ga.c * $Id: ga.c,v 1.5 2003/08/21 22:13:54 rjoseph Exp $ */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/stat.h> #include <sys/types.h> #include <fcntl.h> #include <math.h> #include <time.h> #include <string.h> typedef unsigned char uchar; int ga_pop_sort_cmp(const void *, const void *); uint ga_get_random(); uchar ga_sel_parent(uchar *, float *); char * bin2str(char *, char); float ga_fitness_all_ones(uchar); void ga_do_gen(uchar (*)(uchar *, float *), void (*)(uchar, uchar, uchar *), void (*)(uchar *), uchar *, float *, uchar *); void ga_crossover(uchar, uchar, uchar *); void ga_mutate(uchar *); void ga_eval_fitness(float (*)(uchar), uchar *, float *); void ga_gen_pop(uchar *); void ga_print_pop(uchar *); void help(char *); // icky globals unsigned long ga_mutation_count = 0, ga_crossover_count = 0, ga_generation_count = 0, POP_SIZE = 200, PRINT_MOD = 11, GEN_COUNT = 10000, DUMP_DATA = 0; double PROB_CROSS = 0.7, PROB_MUTATE = 0.01, CUTOFF_REQ = 0.03; #define OPT_STR "ahqds:p:c:m:r:g:M:C:l:L:" #ifdef DEBUG # define dprint(fmt, args...) fprintf(stderr, ">> " fmt, ## args); #else # define dprint(fmt, args...) #endif // start GA functions void ga_gen_pop(uchar *array) { char str; int i; srand(ga_get_random() * time(NULL)); srand48(ga_get_random() * time(NULL)); for (i = 0; i < POP_SIZE; i++) array[i] = (uchar)((rand() >> (rand() % 3)) & 0xFF); qsort(array, POP_SIZE, sizeof(uchar), ga_pop_sort_cmp); } void ga_eval_fitness(float (*func)(uchar), uchar *pop, float *fitness) { int i; for (i = 0; i < POP_SIZE; i++) fitness[i] = (*func)(pop[i]); } float ga_fitness_all_ones(uchar indiv) { return (indiv / 256.0); } int ga_pop_sort_cmp(const void *one, const void *two) { return (*((uchar *)one) - *((uchar *)two)); } void ga_do_gen(uchar (*fselp)(uchar *, float *), void (*fcross)(uchar, uchar, uchar *), void (*fmutate)(uchar *), uchar *cur_pop, float *fit, uchar *new_pop) { uchar *kids = (uchar *)(malloc(sizeof(uchar) * 2)); int i; for (i = 0; i < POP_SIZE; i += 2) { (*fcross)((*fselp)(cur_pop, fit), (*fselp)(cur_pop, fit), kids); (*fmutate)(kids); new_pop[i] = kids[0]; new_pop[i+1] = kids[1]; } qsort(new_pop, POP_SIZE, sizeof(uchar), ga_pop_sort_cmp); } void ga_crossover(uchar p1, uchar p2, uchar *ret) { int locus, i, mask = 0; double cross = drand48(); char str[256], str2[256]; uchar k1 = p1, k2 = p2; if (cross < PROB_CROSS) { ga_crossover_count++; locus = (drand48() * 7) + 1; for (i = 0; i < locus + 1; i++) mask += pow(2, i); // these are the actual crossovers, don't know if this // is correct, but it does actually do stuff, so it helps k1 = (p1 & ~mask) | (p2 & mask); k2 = (p2 & ~mask) | (p1 & mask); } ret[0] = k1; ret[1] = k2; } void ga_mutate(uchar *kids) { int locus, ndx; double mutate = drand48(); uchar b4; if (mutate < PROB_MUTATE) { ga_mutation_count++; locus = drand48() * 8; ndx = drand48() * 2; b4 = kids[ndx]; kids[ndx] = kids[ndx] ^ (int)(pow(2.0, (double)locus)); } } uchar ga_sel_parent(uchar *pop, float *fit) { double r1 = drand48(), sel_req; int sel; char parent; sel_req = (r1 + ((1.0 - r1) * 0.2)); if (sel_req > fit[POP_SIZE - 1]) sel_req = fit[POP_SIZE - 1]; while (1) { sel = (int)(drand48() * POP_SIZE); if (fit[sel] >= sel_req) return pop[sel]; } } // GA utility functions, not central to the GA unsigned int ga_get_random() { int fd, ret; fd = open("/dev/urandom", O_RDONLY); read(fd, &ret, sizeof(ret)); return (unsigned int)ret; } void ga_print_pop(uchar *pop) { int i; printf(" "); for (i = 0; i < PRINT_MOD; i++) printf(" %8d", i + 1); printf("\n"); printf(" +-----"); for (i = 5; i < PRINT_MOD * 9; i++) printf("-"); for (i = 0; i < POP_SIZE; i++) { if (!(i % PRINT_MOD)) printf("\n%3d | ", i); printf("%8d ", pop[i]); } printf("\n"); } // Regular util functions char *bin2str(char *bin, char num) { int i; char mask; for (i = 0; i < 8; i++) { mask = pow(2, i); bin[(7 - i)] = ((num & mask) ? '1': '0'); } bin[8] = '\0'; return bin; } void help(char *name) { printf( "Usage: %s [options]\n" "(C) 2003, Ryan Joseph <[email protected]>\n" "Anything that is a percentage can be floating point.\n\n" " -h This help\n" " -s Population size (%d)\n" " -p Number of columns to print in pop tables (%d)\n" " -r Cutoff percentage for most-fit individuals (%0.2f)\n" " -m Mutation probability as a percentage (%0.2f)\n" " -c Crossover probability as a percentage (%0.2f)\n" " -g Number of generations (%d)\n" " -a Automated mode, using steps set below\n" " -M Mutation stepping, percentage\n" " -C Crossover stepping, percentage\n" " -l Mutation limit, percentage\n" " -L Crossover limit, percentage\n" " -q Don't print population tables\n\n", name, POP_SIZE, PRINT_MOD, (CUTOFF_REQ * 100.0), (PROB_MUTATE * 100.0), (PROB_CROSS * 100.0), GEN_COUNT); exit(0); } int main(int argc, char **argv) { uchar *pop, *gen, *opop; float *fit; int i = 0, tot_inds, no_pop_tables = 0, automated = 0; double mutate_step = 0.1, crossover_step = 0.1, ms, cs, lm, ls; char c; printf("Command line: "); for (i; i < argc; i++) printf("%s ", argv[i]); printf("\n"); while ((c = getopt(argc, argv, OPT_STR)) != -1) { switch (c) { case 'h': help(argv[0]); break; case 's': POP_SIZE = atof(optarg); break; case 'p': PRINT_MOD = atoi(optarg); break; case 'r': CUTOFF_REQ = (atof(optarg) / 100.0); break; case 'm': PROB_MUTATE = (atof(optarg) / 100.0); break; case 'c': PROB_CROSS = (atof(optarg) / 100.0); break; case 'g': GEN_COUNT = atoi(optarg); break; case 'q': no_pop_tables = 1; break; case 'a': automated = 1; break; case 'M': mutate_step = (atof(optarg) / 100); break; case 'C': crossover_step = (atof(optarg) / 100); break; case 'l': lm = (atof(optarg) / 100); break; case 'L': ls = (atof(optarg) / 100); break; case 'd': DUMP_DATA = 1; break; default: break; } } if (!automated) lm = PROB_MUTATE + mutate_step, ls = PROB_CROSS + crossover_step; pop = (uchar *)(malloc(sizeof(uchar) * POP_SIZE)); gen = (uchar *)(malloc(sizeof(uchar) * POP_SIZE)); fit = (float *)(malloc(sizeof(float) * POP_SIZE)); for (ms = PROB_MUTATE, cs = PROB_CROSS; ms < lm || cs < ls;) { PROB_MUTATE = ms; PROB_CROSS = cs; if (automated) printf("\n----------\n"); printf("Generations: %3d\tPopulation Size: %3d\tCutoff Percentage: %0.6f%%\n", GEN_COUNT, POP_SIZE, (CUTOFF_REQ * 100.0)); printf("Crossover Probability: %3.2f%%\tMutation Probability: %3.6f%%\n", (PROB_CROSS * 100.0), (PROB_MUTATE * 100.0)); if (automated) printf("Mutation step [%0.2f], limit [%0.2f]\t" "Crossover step [%0.2f], limit [%0.2f]\n", mutate_step * 100, lm * 100, crossover_step * 100, ls * 100); ga_gen_pop(pop); opop = pop; if (!no_pop_tables) { printf("\nFirst population:\n"); ga_print_pop(pop); printf("\n"); } ga_eval_fitness(ga_fitness_all_ones, pop, fit); do { if (DUMP_DATA) { for (i = 0; i < POP_SIZE; i++) fprintf(stderr, "%d\t", pop[i]); fprintf(stderr, "\n"); } dprint("Generation: %12d\tMutations: %12d\t Crossovers: %12d\n", ga_generation_count, (ga_mutation_count * 2), (ga_crossover_count * 2)); ga_do_gen( ga_sel_parent, ga_crossover, ga_mutate, pop, fit, gen ); pop = gen; ga_eval_fitness(ga_fitness_all_ones, pop, fit); ga_generation_count++; } while (ga_generation_count < GEN_COUNT && pop[(int)(((float)(POP_SIZE * CUTOFF_REQ)) - 1)] != 255); if (!no_pop_tables) { printf("Final population:\n"); ga_print_pop(pop); printf("\n"); } tot_inds = ga_generation_count * POP_SIZE; printf("\nDone with %d generations (%d individuals)" "\n%d crossovers and %d mutations\n", ga_generation_count, tot_inds, ga_crossover_count, ga_mutation_count); printf("Used %0.1f%% of the allotted generations.\n\n", (((double)(ga_generation_count) / (double)GEN_COUNT) * 100.0)); printf("Real crossover percentage (set as %0.2f%%): %0.3f%%\n", (PROB_CROSS * 100.0), ((double)(ga_crossover_count * 2) / (double)tot_inds) * 100.0); printf("Real mutation percentage (set as %0.3f%%): %0.4f%%\n", (PROB_MUTATE * 100.0),((double)(ga_mutation_count * 2) / (double)tot_inds) * 100.0); for (i = 0; i < POP_SIZE && pop[i] < 255; i++) {} printf("Number of 'most-fit' individuals: %d (%0.5f%%)\n", (POP_SIZE - i), 100.0 - ((((double)(i + 1)) / POP_SIZE) * 100.0)); if (ms < lm) ms += mutate_step; if (cs < ls) cs += crossover_step; } free(opop); free(pop); free(fit); return 0; }
2.140625
2
2024-11-18T20:08:13.930756+00:00
2018-04-10T11:28:09
1f00b4411fd11f5fbe1b3e76389a0f72db95bf98
{ "blob_id": "1f00b4411fd11f5fbe1b3e76389a0f72db95bf98", "branch_name": "refs/heads/master", "committer_date": "2018-04-10T11:28:09", "content_id": "4e63876ded0301d81ce96c1a6bf392fc029de1dd", "detected_licenses": [ "MIT" ], "directory_id": "ec2396aea00cc397d598ae1fba67b667a99f8862", "extension": "c", "filename": "init_bis.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 128921034, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2027, "license": "MIT", "license_type": "permissive", "path": "/src/init_bis.c", "provenance": "stackv2-0007.json.gz:98038", "repo_name": "Rob2n/Night-Rider", "revision_date": "2018-04-10T11:28:09", "revision_id": "f4653f4f72f411709ea433678d7f33d18beb11de", "snapshot_id": "c4920b01a8aa27241a780187152468d912eb08b5", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Rob2n/Night-Rider/f4653f4f72f411709ea433678d7f33d18beb11de/src/init_bis.c", "visit_date": "2020-03-09T17:58:48.342203" }
stackv2
/* ** EPITECH PROJECT, 2018 ** init_bis ** File description: ** init_bis */ #include "../include/my.h" music_t *init_music(void) { music_t *music = malloc(sizeof(music_t)); music->song = sfMusic_createFromFile("sound/music.ogg"); sfMusic_setLoop(music->song, sfTrue); music->hit = sfMusic_createFromFile("sound/hit.ogg"); music->hit_side = sfMusic_createFromFile("sound/hit_side.ogg"); if (music->song != NULL) { sfMusic_play(music->song); } return (music); } gen_t *init_all(char **av) { gen_t *gen = malloc(sizeof(gen_t)); sfVideoMode mode = {1200, 600, 32}; game_object_t *object = init_objects(); music_t *sound = init_music(); char *map; map = path_to_str(av[1]); gen->mode = mode; gen->object = object; gen->sound = sound; gen->map = map; gen->game_on = 1; gen->framerate_limit = 60; gen->window = sfRenderWindow_create(gen->mode, "My Runner", sfResize | sfClose, NULL); sfRenderWindow_setFramerateLimit(gen->window, gen->framerate_limit); gen->clock = sfClock_create(); gen->clock2 = sfClock_create(); return (gen); } float inertia(float pos) { if (pos > 0) { return (-0.09); } if (pos < 0) { return (0.09); } return (0); } void create_score_bis(game_object_t *obj, sfFont *font) { obj->score = sfText_create(); obj->score_str = "00000"; sfText_setString(obj->score, obj->score_str); sfText_setFont(obj->score, font); sfText_setCharacterSize(obj->score, 30); } game_object_t create_score(char *str, sfVector2f pos_score) { game_object_t obj; sfFont *font = sfFont_createFromFile("font.ttf"); sfVector2f pos = {1000, 550}; sfVector2f pos2 = {1100, 550}; obj.text = sfText_create(); sfText_setString(obj.text, str); sfText_setFont(obj.text, font); sfText_setCharacterSize(obj.text, 30); create_score_bis(&obj, font); obj.obj_pos = pos_score; obj.pos = pos; obj.speedx = 0; obj.speedy = 0; obj.fptr = &move_sprite; obj.state = 0; obj.type = type_score; sfText_setPosition(obj.text, pos); sfText_setPosition(obj.score, pos2); return (obj); }
2.25
2
2024-11-18T20:08:14.207006+00:00
2017-08-19T22:51:56
cd1c795f1410b9ac2e3cf466dc8538de61f90248
{ "blob_id": "cd1c795f1410b9ac2e3cf466dc8538de61f90248", "branch_name": "refs/heads/master", "committer_date": "2017-08-19T22:51:56", "content_id": "5fd6137f8833aa0593227756b246755ecb03b2f9", "detected_licenses": [ "MIT" ], "directory_id": "d965c5488bc5066e127453fc5e45d333470302fc", "extension": "c", "filename": "sf2d_batch.c", "fork_events_count": 1, "gha_created_at": "2017-08-13T07:13:55", "gha_event_created_at": "2017-08-13T07:13:55", "gha_language": null, "gha_license_id": null, "github_id": 100160374, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4858, "license": "MIT", "license_type": "permissive", "path": "/libsf2d/source/sf2d_batch.c", "provenance": "stackv2-0007.json.gz:98166", "repo_name": "TricksterGuy/sf2dlib", "revision_date": "2017-08-19T22:51:56", "revision_id": "ce6f18e81176e9f9703b70d95ce1aa15a948c93d", "snapshot_id": "3e761a68b98b3807f118790fe48149661ef04fb4", "src_encoding": "UTF-8", "star_events_count": 16, "url": "https://raw.githubusercontent.com/TricksterGuy/sf2dlib/ce6f18e81176e9f9703b70d95ce1aa15a948c93d/libsf2d/source/sf2d_batch.c", "visit_date": "2021-01-16T19:24:08.094702" }
stackv2
#include "sf2d.h" #include <stdlib.h> #include <math.h> static sf2d_batch* current_batch = NULL; sf2d_batch* sf2d_create_batch(int size) { sf2d_batch* rt = calloc(1, sizeof(*rt)); if (!rt) return NULL; // Each texture drawn will be 2 triangles each with 3 vertices. rt->size = size * 6 * sizeof(sf2d_vertex_pos_tex); rt->vertices = linearAlloc(rt->size); if (!rt->vertices) { free(rt); return NULL; } return rt; } void sf2d_reset_batch(sf2d_batch* batch) { batch->index = 0; batch->start_index = 0; batch->bound = NULL; } void sf2d_start_batch(sf2d_batch* batch) { if (current_batch != NULL) return; sf2d_reset_batch(batch); current_batch = batch; } void sf2d_batch_texture(sf2d_texture* texture, int x, int y) { if (current_batch == NULL) return; // Out of space if (current_batch->index >= current_batch->size) return; if (current_batch->bound != texture) { if (current_batch->index - current_batch->start_index > 0) sf2d_flush_batch(current_batch); sf2d_bind_texture(texture, GPU_TEXUNIT0); current_batch->bound = texture; } sf2d_vertex_pos_tex* vertices = current_batch->vertices + current_batch->index; int w = texture->width; int h = texture->height; vertices[0].position = (sf2d_vector_3f){(float)x, (float)y, SF2D_DEFAULT_DEPTH}; vertices[1].position = (sf2d_vector_3f){(float)x, (float)y+h, SF2D_DEFAULT_DEPTH}; vertices[2].position = (sf2d_vector_3f){(float)x+w, (float)y, SF2D_DEFAULT_DEPTH}; vertices[3].position = (sf2d_vector_3f){(float)x+w, (float)y, SF2D_DEFAULT_DEPTH}; vertices[4].position = (sf2d_vector_3f){(float)x, (float)y+h, SF2D_DEFAULT_DEPTH}; vertices[5].position = (sf2d_vector_3f){(float)x+w, (float)y+h, SF2D_DEFAULT_DEPTH}; float u = texture->width/(float)texture->tex.width; float v = texture->height/(float)texture->tex.height; vertices[0].texcoord = (sf2d_vector_2f){0.0f, 0.0f}; vertices[1].texcoord = (sf2d_vector_2f){0.0f, v}; vertices[2].texcoord = (sf2d_vector_2f){ u, 0.0f}; vertices[3].texcoord = (sf2d_vector_2f){ u, 0.0f}; vertices[4].texcoord = (sf2d_vector_2f){0.0f, v}; vertices[5].texcoord = (sf2d_vector_2f){ u, v}; current_batch->index += 6; } void sf2d_batch_texture_part(sf2d_texture* texture, int x, int y, int tex_x, int tex_y, int tex_w, int tex_h) { if (current_batch == NULL) return; // Out of space if (current_batch->index >= current_batch->size) return; if (current_batch->bound != texture) { if (current_batch->index - current_batch->start_index > 0) sf2d_flush_batch(current_batch); sf2d_bind_texture(texture, GPU_TEXUNIT0); current_batch->bound = texture; current_batch->start_index = current_batch->index; } sf2d_vertex_pos_tex *vertices = current_batch->vertices + current_batch->index; vertices[0].position = (sf2d_vector_3f){(float)x, (float)y, SF2D_DEFAULT_DEPTH}; vertices[1].position = (sf2d_vector_3f){(float)x, (float)y+tex_h, SF2D_DEFAULT_DEPTH}; vertices[2].position = (sf2d_vector_3f){(float)x+tex_w, (float)y, SF2D_DEFAULT_DEPTH}; vertices[3].position = (sf2d_vector_3f){(float)x+tex_w, (float)y, SF2D_DEFAULT_DEPTH}; vertices[4].position = (sf2d_vector_3f){(float)x, (float)y+tex_h, SF2D_DEFAULT_DEPTH}; vertices[5].position = (sf2d_vector_3f){(float)x+tex_w, (float)y+tex_h, SF2D_DEFAULT_DEPTH}; float u0 = tex_x/(float)texture->tex.width; float v0 = tex_y/(float)texture->tex.height; float u1 = (tex_x+tex_w)/(float)texture->tex.width; float v1 = (tex_y+tex_h)/(float)texture->tex.height; vertices[0].texcoord = (sf2d_vector_2f){u0, v0}; vertices[1].texcoord = (sf2d_vector_2f){u0, v1}; vertices[2].texcoord = (sf2d_vector_2f){u1, v0}; vertices[3].texcoord = (sf2d_vector_2f){u1, v0}; vertices[4].texcoord = (sf2d_vector_2f){u0, v1}; vertices[5].texcoord = (sf2d_vector_2f){u1, v1}; current_batch->index += 6; } void sf2d_end_batch() { if (current_batch == NULL) return; if (current_batch->index - current_batch->start_index > 0) sf2d_flush_batch(current_batch); current_batch = NULL; } void sf2d_flush_batch() { if (current_batch == NULL) return; C3D_AttrInfo* attrInfo = C3D_GetAttrInfo(); AttrInfo_Init(attrInfo); AttrInfo_AddLoader(attrInfo, 0, GPU_FLOAT, 3); AttrInfo_AddLoader(attrInfo, 1, GPU_FLOAT, 2); C3D_BufInfo* bufInfo = C3D_GetBufInfo(); BufInfo_Init(bufInfo); BufInfo_Add(bufInfo, current_batch->vertices, sizeof(sf2d_vertex_pos_tex), 2, 0x10); C3D_DrawArrays(GPU_TRIANGLES, current_batch->start_index, current_batch->index - current_batch->start_index); current_batch->start_index = current_batch->index; } void sf2d_free_batch(sf2d_batch* batch) { linearFree(batch->vertices); free(batch); }
2.6875
3
2024-11-18T18:08:18.759805+00:00
2017-01-24T08:07:02
d0a40c3aecdc945d1566f0b1d104d48b1720feb2
{ "blob_id": "d0a40c3aecdc945d1566f0b1d104d48b1720feb2", "branch_name": "refs/heads/master", "committer_date": "2017-01-24T08:07:02", "content_id": "cb01d6c22b63e6d54d12618e183fee9b7b438cab", "detected_licenses": [ "Apache-2.0" ], "directory_id": "3d2d0b20ef6adaa554e9ecf1b958cf6620310f97", "extension": "c", "filename": "dslink.c", "fork_events_count": 0, "gha_created_at": "2016-09-26T23:16:19", "gha_event_created_at": "2016-09-26T23:16:19", "gha_language": null, "gha_license_id": null, "github_id": 69300620, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 16843, "license": "Apache-2.0", "license_type": "permissive", "path": "/sdk/src/dslink.c", "provenance": "stackv2-0007.json.gz:122170", "repo_name": "tanupoo/sdk-dslink-c", "revision_date": "2017-01-24T08:07:02", "revision_id": "01336aad2f7bd34811e1cda3b13f83dae5329d73", "snapshot_id": "fba109534539e8da2ff49e0bd2f00e9d9b231b66", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/tanupoo/sdk-dslink-c/01336aad2f7bd34811e1cda3b13f83dae5329d73/sdk/src/dslink.c", "visit_date": "2020-05-29T09:15:32.138008" }
stackv2
#define LOG_TAG "dslink" #include "dslink/log.h" #include <argtable3.h> #include <string.h> #include <wslay/wslay.h> #include <jansson.h> #include "dslink/handshake.h" #include "dslink/utils.h" #include "dslink/ws.h" #define SECONDS_TO_MILLIS(count) count * 1000 #define DSLINK_RESPONDER_MAP_INIT(var, type) \ responder->var = dslink_calloc(1, sizeof(Map)); \ if (!responder->var) { \ goto cleanup; \ } \ if (dslink_map_init(responder->var, \ dslink_map_##type##_cmp, \ dslink_map_##type##_key_len_cal, \ dslink_map_hash_key) != 0) { \ dslink_free(responder->var); \ responder->var = NULL; \ goto cleanup; \ } #define DSLINK_REQUESTER_MAP_INIT(var, type) \ requester->var = dslink_calloc(1, sizeof(Map)); \ if (!requester->var) { \ goto cleanup; \ } \ if (dslink_map_init(requester->var, \ dslink_map_##type##_cmp, \ dslink_map_##type##_key_len_cal, \ dslink_map_hash_key) != 0) { \ dslink_free(requester->var); \ requester->var = NULL; \ goto cleanup; \ } static inline void dslink_print_help() { printf("See --help for usage\n"); } static int dslink_parse_opts(int argc, char **argv, DSLinkConfig *config) { int ret = 0; json_t *json = NULL; struct arg_lit *help; struct arg_str *broker, *token, *log; struct arg_end *end; void *argTable[] = { help = arg_lit0("h", "help", "Displays this help menu"), broker = arg_str0("b", "broker", "url", "Sets the broker URL to connect to"), token = arg_str0("t", "token", NULL, "Sets the token"), log = arg_str0("l", "log", "log type", "Sets the logging level"), end = arg_end(5) }; if (arg_nullcheck(argTable) != 0) { return DSLINK_ALLOC_ERR; } int errs = arg_parse(argc, argv, argTable); if (help->count > 0) { printf("Usage: <opts>\n"); arg_print_glossary(stdout, argTable, " %-25s %s\n"); ret = 1; goto exit; } if (errs > 0) { dslink_print_help(); arg_print_errors(stdout, end, ":"); ret = 1; goto exit; } const char *brokerUrl; json = dslink_read_dslink_json(); if (broker->count > 0) { brokerUrl = broker->sval[0]; } else { json_t *str = dslink_json_raw_get_config(json, "broker"); if (json_is_string(str)) { brokerUrl = json_string_value(str); } else { brokerUrl = "http://127.0.0.1:8080/conn"; } } config->broker_url = dslink_url_parse(brokerUrl); if (token->count > 0) { config->token = token->sval[0]; } else if (json) { json_t *str = dslink_json_raw_get_config(json, "token"); if (str) { config->token = json_string_value(str); } } if (!config->broker_url) { log_fatal("Failed to parse broker url\n"); ret = 1; goto exit; } if (log->count > 0) { const char *lvl = log->sval[0]; if (dslink_log_set_lvl(lvl) != 0) { printf("Invalid log level: %s\n", lvl); dslink_print_help(); ret = 1; goto exit; } } else { json_t *lvl = dslink_json_raw_get_config(json, "log"); if (json_is_string(lvl)) { if (dslink_log_set_lvl(json_string_value(lvl)) != 0) { printf("Invalid log level: %s\n", json_string_value(lvl)); dslink_print_help(); ret = 1; goto exit; } } } exit: arg_freetable(argTable, sizeof(argTable) / sizeof(argTable[0])); if (json) { json_decref(json); } return ret; } static int dslink_init_responder(Responder *responder) { responder->super_root = dslink_node_create(NULL, "/", "node"); if (!responder->super_root) { goto cleanup; } DSLINK_RESPONDER_MAP_INIT(open_streams, uint32) DSLINK_RESPONDER_MAP_INIT(list_subs, str) DSLINK_RESPONDER_MAP_INIT(value_path_subs, str) DSLINK_RESPONDER_MAP_INIT(value_sid_subs, uint32) return 0; cleanup: if (responder->open_streams) { dslink_map_free(responder->open_streams); } if (responder->list_subs) { dslink_map_free(responder->list_subs); } if (responder->value_path_subs) { dslink_map_free(responder->value_path_subs); } if (responder->value_sid_subs) { dslink_map_free(responder->value_sid_subs); } if (responder->super_root) { dslink_node_tree_free(NULL, responder->super_root); } return DSLINK_ALLOC_ERR; } static int dslink_init_requester(Requester *requester) { DSLINK_REQUESTER_MAP_INIT(open_streams, uint32) DSLINK_REQUESTER_MAP_INIT(list_subs, str) DSLINK_REQUESTER_MAP_INIT(request_handlers, uint32) DSLINK_REQUESTER_MAP_INIT(value_handlers, uint32) requester->rid = dslink_malloc(sizeof(uint32_t)); *requester->rid = 0; requester->sid = dslink_malloc(sizeof(uint32_t)); *requester->sid = 0; return 0; cleanup: if (requester->open_streams) { dslink_map_free(requester->open_streams); } if (requester->list_subs) { dslink_map_free(requester->list_subs); } if (requester->value_handlers) { dslink_map_free(requester->value_handlers); } if (requester->rid) { dslink_free(requester->rid); } if (requester->sid) { dslink_free(requester->sid); } return DSLINK_ALLOC_ERR; } static int handle_config(DSLinkConfig *config, const char *name, int argc, char **argv) { memset(config, 0, sizeof(DSLinkConfig)); config->name = name; int ret = 0; if ((ret = dslink_parse_opts(argc, argv, config)) != 0) { if (ret == DSLINK_ALLOC_ERR) { log_fatal("Failed to allocate memory during argument parsing\n"); } return ret; } return ret; } int dslink_handle_key(DSLink *link) { int ret; if ((ret = dslink_handshake_key_pair_fs(&link->key, ".key")) != 0) { if (ret == DSLINK_CRYPT_KEY_DECODE_ERR) { log_fatal("Failed to decode existing key\n"); } else if (ret == DSLINK_OPEN_FILE_ERR) { log_fatal("Failed to write generated key to disk\n"); } else if (ret == DSLINK_CRYPT_KEY_PAIR_GEN_ERR) { log_fatal("Failed to generated key\n"); } else { log_fatal("Unknown error occurred during key handling: %d\n", ret); } } return ret; } void dslink_close(DSLink *link) { link->closing = 1; wslay_event_queue_close(link->_ws, WSLAY_CODE_NORMAL_CLOSURE, NULL, 0); uv_close((uv_handle_t*)&link->async_set,NULL); uv_close((uv_handle_t*)&link->async_get,NULL); uv_close((uv_handle_t*)&link->async_run,NULL); uv_stop(&link->loop); } static void dslink_link_clear(DSLink *link) { if (link->_ws) { wslay_event_context_free(link->_ws); } if (link->msg) { dslink_free(link->msg); } if (link->link_data) { json_decref(link->link_data); } if (link->dslink_json) { json_decref(link->dslink_json); } } void dslink_link_free(DSLink *link) { dslink_link_clear(link); dslink_free(link); } json_t *dslink_read_dslink_json() { json_error_t err; json_t *json = json_load_file("dslink.json", JSON_DECODE_ANY, &err); if (!json) { log_warn("Failed to load dslink.json: %s\n", err.text); return NULL; } if (!json_is_object(json)) { log_warn("Failed to load dslink.json: Root is not a JSON object.\n"); return NULL; } return json; } json_t *dslink_json_raw_get_config(json_t *json, const char *key) { if (!json_is_object(json)) { return NULL; } json_t *configs = json_object_get(json, "configs"); if (!json_is_object(configs)) { return NULL; } json_t *section = json_object_get(configs, key); if (!json_is_object(section)) { return NULL; } json_t *value = json_object_get(section, "value"); if (value) { return value; } json_t *defaultValue = json_object_get(section, "default"); if (defaultValue) { return defaultValue; } return NULL; } json_t *dslink_json_get_config(DSLink *link, const char *key) { if (!link) { return NULL; } return dslink_json_raw_get_config(link->dslink_json, key); } static int dslink_init_do(DSLink *link, DSLinkCallbacks *cbs) { link->closing = 0; link->msg = dslink_malloc(sizeof(uint32_t)); *link->msg = 0; json_t *handshake = NULL; char *dsId = NULL; Socket *sock = NULL; int ret = 0; if (dslink_handle_key(link) != 0) { ret = 1; goto exit; } if (link->is_responder) { link->responder = dslink_calloc(1, sizeof(Responder)); if (!link->responder) { log_fatal("Failed to create responder\n"); goto exit; } if (dslink_init_responder(link->responder) != 0) { log_fatal("Failed to initialize responder\n"); goto exit; } } if (link->is_requester) { link->requester = dslink_calloc(1, sizeof(Requester)); if (!link->requester) { log_fatal("Failed to create requester\n"); goto exit; } if (dslink_init_requester(link->requester) != 0) { log_fatal("Failed to initialize requester\n"); goto exit; } } link->dslink_json = dslink_read_dslink_json(); if (cbs->init_cb) { cbs->init_cb(link); } if ((ret = dslink_handshake_generate(link, &handshake, &dsId)) != 0) { log_fatal("Handshake failed: %d\n", ret); ret = 2; goto exit; } const char *uri = json_string_value(json_object_get(handshake, "wsUri")); const char *tKey = json_string_value(json_object_get(handshake, "tempKey")); const char *salt = json_string_value(json_object_get(handshake, "salt")); if (!(uri && ((tKey && salt) || link->config.token))) { log_fatal("Handshake didn't return the " "necessary parameters to complete\n"); ret = 2; goto exit; } if ((ret = dslink_handshake_connect_ws(link->config.broker_url, &link->key, uri, tKey, salt, dsId, link->config.token, &sock)) != 0) { log_fatal("Failed to connect to the broker: %d\n", ret); ret = 2; goto exit; } else { log_info("Successfully connected to the broker\n"); } link->_socket = sock; if (cbs->on_connected_cb) { cbs->on_connected_cb(link); } dslink_handshake_handle_ws(link, cbs->on_requester_ready_cb); log_warn("Disconnected from the broker\n") if (cbs->on_disconnected_cb) { cbs->on_disconnected_cb(link); } if (link->closing != 1) { ret = 2; } exit: if (link->is_responder) { if (link->responder->super_root) { dslink_node_tree_free(link, link->responder->super_root); } if (link->responder->open_streams) { dslink_map_free(link->responder->open_streams); dslink_free(link->responder->open_streams); } if (link->responder->list_subs) { dslink_map_free(link->responder->list_subs); dslink_free(link->responder->list_subs); } if (link->responder->value_path_subs) { dslink_map_free(link->responder->value_path_subs); dslink_free(link->responder->value_path_subs); } if (link->responder->value_sid_subs) { dslink_map_free(link->responder->value_sid_subs); dslink_free(link->responder->value_sid_subs); } dslink_free(link->responder); } if (link->is_requester) { if (link->requester->list_subs) { dslink_map_free(link->requester->list_subs); dslink_free(link->requester->list_subs); } if (link->requester->request_handlers) { dslink_map_free(link->requester->request_handlers); dslink_free(link->requester->request_handlers); } if (link->requester->open_streams) { dslink_map_free(link->requester->open_streams); dslink_free(link->requester->open_streams); } if (link->requester->value_handlers) { dslink_map_free(link->requester->value_handlers); dslink_free(link->requester->value_handlers); } if (link->requester->rid) { dslink_free(link->requester->rid); } if (link->requester->sid) { dslink_free(link->requester->sid); } dslink_free(link->requester); } mbedtls_ecdh_free(&link->key); DSLINK_CHECKED_EXEC(dslink_socket_close, sock); DSLINK_CHECKED_EXEC(dslink_free, dsId); DSLINK_CHECKED_EXEC(json_delete, handshake); return ret; } //thread-safe API async handle callbacks void dslink_async_get_node_value(uv_async_t *async_handle) { DSLinkAsyncGetData *async_data = (DSLinkAsyncGetData*)async_handle->data; DSLink *link = (DSLink*)(async_handle->loop->data); if(!link) { log_info("DSLink not found!\n"); } else { DSNode *node = dslink_node_get_path(link->responder->super_root,async_data->node_path); if(node) { if(async_data->callback) { async_data->callback(json_copy(node->value),async_data->callback_data); } } else { log_info("Node not found in the path\n"); } } //free async_data which is allocated in API func dslink_free(async_data->node_path); dslink_free(async_data); } void dslink_async_set_node_value(uv_async_t *async_handle) { DSLinkAsyncSetData *async_data = (DSLinkAsyncSetData*)async_handle->data; DSLink *link = (DSLink*)(async_handle->loop->data); if(!link) { log_warn("DSLink not found!\n"); } else { DSNode *node = dslink_node_get_path(link->responder->super_root,async_data->node_path); int ret; if(node) { //json value's ref count must be 1 and should not be used in the other thread anymore if(dslink_node_update_value(link,node,async_data->set_value) == 0) ret = 0; else ret = -1; } else { log_info("Node not found in the path\n"); ret = -1; } if(async_data->callback) { async_data->callback(ret,async_data->callback_data); } } //free async_data which is allocated in API func dslink_free(async_data->node_path); json_decref(async_data->set_value); dslink_free(async_data); } void dslink_async_run(uv_async_t *async_handle) { DSLinkAsyncRunData *async_data = (DSLinkAsyncRunData*)async_handle->data; DSLink *link = (DSLink*)(async_handle->loop->data); if(!link) { log_info("DSLink not found!\n"); } else { if(async_data->callback) { async_data->callback(link,async_data->callback_data); } } //free async_data which is allocated in API func dslink_free(async_data); } int dslink_init(int argc, char **argv, const char *name, uint8_t isRequester, uint8_t isResponder, DSLinkCallbacks *cbs) { DSLink *link = dslink_calloc(1, sizeof(DSLink)); uv_loop_init(&link->loop); link->loop.data = link; //thread-safe API async handle set if(uv_async_init(&link->loop, &link->async_get, dslink_async_get_node_value)) { log_warn("Async handle init error\n"); } if(uv_async_init(&link->loop, &link->async_set, dslink_async_set_node_value)) { log_warn("Async handle init error\n"); } if(uv_async_init(&link->loop, &link->async_run, dslink_async_run)) { log_warn("Async handle init error\n"); } link->is_responder = isResponder; link->is_requester = isRequester; if (handle_config(&link->config, name, argc, argv) != 0) { return 1; } int ret = 0; while (1) { ret = dslink_init_do(link, cbs); if (ret != 2) { log_info("%i\n", ret); break; } dslink_link_clear(link); dslink_sleep(SECONDS_TO_MILLIS(5)); log_info("Attempting to reconnect...\n"); } uv_close((uv_handle_t*)&link->async_set,NULL); uv_close((uv_handle_t*)&link->async_get,NULL); uv_close((uv_handle_t*)&link->async_run,NULL); uv_loop_close(&link->loop); dslink_link_free(link); return ret; }
2.078125
2
2024-11-18T18:09:49.683074+00:00
2023-05-02T12:17:20
e0626e5005c915af936f55ce75aad1046fffc1f4
{ "blob_id": "e0626e5005c915af936f55ce75aad1046fffc1f4", "branch_name": "refs/heads/master", "committer_date": "2023-05-02T12:17:20", "content_id": "f157ca45a9689a0379f68f159078da74a3706fad", "detected_licenses": [ "MIT" ], "directory_id": "512adc0ecb1b8a2dba6116a4366f7207a6dee4e7", "extension": "c", "filename": "icmp.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 330246223, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3186, "license": "MIT", "license_type": "permissive", "path": "/Linux/linuxNetCode/course10/icmp.c", "provenance": "stackv2-0007.json.gz:122427", "repo_name": "DayoWong0/Notes", "revision_date": "2023-05-02T12:17:20", "revision_id": "cc802cd78fe011794db12a606285937601773e74", "snapshot_id": "cceaef7c7c83db02d789c81b9fe6ed388db3daad", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/DayoWong0/Notes/cc802cd78fe011794db12a606285937601773e74/Linux/linuxNetCode/course10/icmp.c", "visit_date": "2023-05-07T11:28:07.402691" }
stackv2
//ip.h #ifndef _IP_H #define _IP_H #include <stdio.h> #include <signal.h> #include <arpa/inet.h> #include <sys/types.h> #include <sys/socket.h> #include <unistd.h> #include <netinet/in.h> #include <netinet/ip.h> #include <netinet/ip_icmp.h> #include <netdb.h> #include <stdlib.h> #include <string.h> #define PACKET_SIZE 4096 #define MAX_WAIT_TIME 5 #define DEST_ADDR "127.0.0.1" extern int errno; char sendpacket[PACKET_SIZE]; char recvpacket[PACKET_SIZE]; int sockfd,datalen=56; struct sockaddr_in dest_addr; void send_packet(); void recv_packet(); unsigned short cal_chksum(unsigned short * addr,int len); void showiphdr(struct ip *ip); void onTerm(); #endif int main(int argc,char *argv[]) { struct hostent *host; struct protoent *protocol; unsigned long inaddr=0L; if((protocol=getprotobyname("icmp"))==NULL) { perror("unknow protocol icmp"); exit(1); } if((sockfd=socket(AF_INET,SOCK_RAW,protocol->p_proto))<0){ perror("socket error"); exit(2); } bzero(&dest_addr,sizeof(dest_addr)); dest_addr.sin_family=AF_INET; inaddr=inet_addr(DEST_ADDR); memcpy((char*)&dest_addr.sin_addr,(char*)&inaddr,sizeof(inaddr)); send_packet(); recv_packet(); return 0; } void send_packet() { int i,packetsize; struct icmp *icmp; icmp=(struct icmp*)sendpacket; icmp->icmp_type=ICMP_ECHO; icmp->icmp_code=0; icmp->icmp_cksum=0; icmp->icmp_id=getpid(); icmp->icmp_seq=1; packetsize=8+datalen; //数据包的大小 icmp->icmp_cksum=cal_chksum((unsigned short*)icmp,packetsize); if((sendto(sockfd,sendpacket,packetsize,0,(struct sockaddr*)&dest_addr,sizeof(dest_addr)))<0){ perror("send ICMP packets error\n"); exit(3); } printf("send ICMP packet to %s\n",inet_ntoa(dest_addr.sin_addr)); } unsigned short cal_chksum(unsigned short *addr,int len) { int nleft=len; int sum=0; unsigned short *w=addr; unsigned short answer=0; while(nleft>1){ sum+=*w++; nleft-=2; } if(nleft==1){ *(unsigned char*)(&answer)=*(unsigned char*)w; sum+=answer; } sum=(sum>>16)+(sum&0xffff); sum+=(sum>>16); answer=~sum; return answer; } void recv_packet() { int n,fromlen,packet_no; struct sockaddr_in from; struct ip *ip; struct icmp *icmp; signal(SIGALRM,onTerm); while(1) { fromlen=sizeof(from); alarm(MAX_WAIT_TIME); if((n=recvfrom(sockfd,recvpacket,sizeof(recvpacket),0,(struct sockaddr*)&from,&fromlen))<0){ perror("Receive packet error"); continue; } ip=(struct ip *)recvpacket; showiphdr(ip); printf("len:%d",ip->ip_hl); icmp=(struct icmp*)(recvpacket+4*ip->ip_hl);//取ICMP报头 printf("ICMP TYPE=%d\n",icmp->icmp_type); } } void showiphdr(struct ip *ip) { printf("------IP HEADER------\n"); printf("version:%d\n",ip->ip_v); printf("header length:%d\n",ip->ip_hl); printf("type of service:%d\n",ip->ip_tos); printf("total length:%d\n",ip->ip_len); printf("identification:%d\n",ip->ip_id); printf("fragment offset field:%d\n",ip->ip_off); printf("time to live:%d\n",ip->ip_ttl); printf("protocol:%d\n",ip->ip_p); /*printf("checksum:%s\n",ip->ip_sum );*/ printf("source IP address:%s\n",inet_ntoa(ip->ip_src)); printf("destination IP address:%s\n",inet_ntoa(ip->ip_dst)); } void onTerm() { close(sockfd); exit(0); }
2.5
2
2024-11-18T18:09:57.108747+00:00
2020-04-14T23:31:04
1f0ab16890726ef06c408ab7ae8f6e5f8a73ae71
{ "blob_id": "1f0ab16890726ef06c408ab7ae8f6e5f8a73ae71", "branch_name": "refs/heads/master", "committer_date": "2020-04-14T23:31:04", "content_id": "6c46e37e9c8d1543a373a7e934f984afed9c1483", "detected_licenses": [ "MIT" ], "directory_id": "3f404df7edbee4f5f0491afaa69c10b43acd5bb8", "extension": "h", "filename": "filler.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 255751971, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1780, "license": "MIT", "license_type": "permissive", "path": "/include/filler.h", "provenance": "stackv2-0007.json.gz:122812", "repo_name": "BimManager/filler", "revision_date": "2020-04-14T23:31:04", "revision_id": "20295ce45b05d085434f51cf46e24e7f7fac5707", "snapshot_id": "29a5dbd73df3e9279dbefa6f1eec335a92870d2b", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/BimManager/filler/20295ce45b05d085434f51cf46e24e7f7fac5707/include/filler.h", "visit_date": "2022-04-17T04:12:33.132974" }
stackv2
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* filler.h :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: kkozlov <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/01/26 14:41:41 by kkozlov #+# #+# */ /* Updated: 2020/02/07 20:05:47 by kkozlov ### ########.fr */ /* */ /* ************************************************************************** */ #ifndef FILLER_H # define FILLER_H # include "libft.h" # define TRACE "./kkozlov.filler.trace" typedef struct s_piece { int rows; int cols; char **shape; } t_piece; typedef struct s_filler { char mytoken; char optoken; int rows; int cols; int **heatmap; } t_filler; typedef struct s_ply { int row; int col; } t_ply; void filler(void); t_filler *ft_fillernew(void); void ft_fillerdel(t_filler **filler); void ft_nbsparse(const char *line, int *a, int *b); void ft_tokensparse(t_filler *filler, const char *line); void ft_sizeparse(t_filler *filler, const char *line); void ft_heatmapupdate(t_filler *filler); void ft_heatmaprecalc(t_filler *filler); void ft_heatmapput(int fd, t_filler *filler); t_piece *ft_piecenew(void); void ft_piecedel(t_piece **piece); void ft_pieceplace(t_filler *filler, t_piece *piece); #endif
2.078125
2
2024-11-18T18:20:15.841715+00:00
2013-10-06T22:39:12
a50332579a5cf9017dd24ffe5c16662ca66f1b0b
{ "blob_id": "a50332579a5cf9017dd24ffe5c16662ca66f1b0b", "branch_name": "refs/heads/master", "committer_date": "2013-10-06T22:39:12", "content_id": "2cfce66a09334199d442a2fcb30dcb17a3a9ff9d", "detected_licenses": [ "Apache-2.0" ], "directory_id": "2df0b1b7160cd58f02190b86ae245f2f5a9d2232", "extension": "c", "filename": "spatial.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 13342607, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 12899, "license": "Apache-2.0", "license_type": "permissive", "path": "/ms/spatial.c", "provenance": "stackv2-0007.json.gz:133974", "repo_name": "gareth1brown/hainesfork", "revision_date": "2013-10-06T22:39:12", "revision_id": "bcddc22c2a97050d8e7a07021097388d447cf914", "snapshot_id": "1e3085f65494bc80b0516862555b1e333d81b11d", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/gareth1brown/hainesfork/bcddc22c2a97050d8e7a07021097388d447cf914/ms/spatial.c", "visit_date": "2021-01-21T00:16:24.943605" }
stackv2
// Copyright 2013 Tom SF Haines // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. #include "spatial.h" #include <stdlib.h> // The conveniance methods that handle all Spatial objects... Spatial Spatial_new(const SpatialType * type, DataMatrix * dm) { return type->init(dm); } void Spatial_delete(Spatial this) { const SpatialType * type = *(const SpatialType**)this; type->deinit(this); } const SpatialType * Spatial_type(Spatial this) { return *(const SpatialType**)this; } DataMatrix * Spatial_dm(Spatial this) { const SpatialType * type = *(const SpatialType**)this; return type->dm(this); } void Spatial_start(Spatial this, const float * centre, float range) { const SpatialType * type = *(const SpatialType**)this; type->start(this, centre, range); } int Spatial_next(Spatial this) { const SpatialType * type = *(const SpatialType**)this; return type->next(this); } // Implimentation of the brute force spatial indexer... typedef struct BruteForce BruteForce; struct BruteForce { const SpatialType * type; DataMatrix * dm; int next; }; Spatial BruteForce_new(DataMatrix * dm) { BruteForce * this = (BruteForce*)malloc(sizeof(BruteForce)); this->type = &BruteForceType; this->dm = dm; this->next = -1; return this; } void BruteForce_delete(Spatial this) { free(this); } DataMatrix * BruteForce_dm(Spatial self) { BruteForce * this = (BruteForce*)self; return this->dm; } void BruteForce_start(Spatial self, const float * centre, float range) { BruteForce * this = (BruteForce*)self; this->next = 0; } int BruteForce_next(Spatial self) { BruteForce * this = (BruteForce*)self; int ret = this->next; if (this->next>=0) { this->next += 1; if (this->next >= this->dm->exemplars) { this->next = -1; } } return ret; } const SpatialType BruteForceType = { "brute_force", "Does nothing - for every calculation all items in the data matrix will be considered. Only crazy people use this.", BruteForce_new, BruteForce_delete, BruteForce_dm, BruteForce_start, BruteForce_next, }; // Implimentation of the dual dimension iterator spatial indexer... typedef struct IterDual IterDual; struct IterDual { const SpatialType * type; DataMatrix * dm; int indices; // Number of indices that have a spatial component. int * original; // For each index its source in the dm object. int valid; // 1 if we are iterating, 0 if not. int * low; // Starting value for each index in the current range. int * pos; // Position in the current iteration. int * high; // Ending value for each index in the current range (exclusive). }; Spatial IterDual_new(DataMatrix * dm) { IterDual * this = (IterDual*)malloc(sizeof(IterDual)); this->type = &IterDualType; this->dm = dm; this->indices = 0; int i; for (i=0; i<this->dm->array->nd; i++) { if (this->dm->dt[i]!=DIM_FEATURE) this->indices += 1; } this->original = (int*)malloc(this->indices * sizeof(int)); this->indices = 0; for (i=0; i<this->dm->array->nd; i++) { if (this->dm->dt[i]!=DIM_FEATURE) { this->original[this->indices] = i; this->indices += 1; } } this->valid = 0; this->low = (int*)malloc(this->indices * sizeof(int)); this->pos = (int*)malloc(this->indices * sizeof(int)); this->high = (int*)malloc(this->indices * sizeof(int)); return this; } void IterDual_delete(Spatial self) { IterDual * this = (IterDual*)self; free(this->high); free(this->pos); free(this->low); free(this->original); free(this); } DataMatrix * IterDual_dm(Spatial self) { IterDual * this = (IterDual*)self; return this->dm; } void IterDual_start(Spatial self, const float * centre, float range) { IterDual * this = (IterDual*)self; // Go through and calculate low and high for each dimension, setting pos to low... int i; for (i=0; i<this->indices; i++) { int oi = this->original[i]; npy_intp size = this->dm->array->dimensions[oi]; if (this->dm->dt[oi]==DIM_DATA) { // No optimisation possible - just set it to the entire range... this->low[i] = 0; this->pos[i] = 0; this->high[i] = size; } else { // We can optimise, and iterate only part of this dimension of the datamatrix... float low = (centre[oi] - range) / this->dm->mult[oi]; float high = (centre[oi] + range) / this->dm->mult[oi]; this->low[i] = (int)ceil(low); if (this->low[i]<0) this->low[i] = 0; this->pos[i] = this->low[i]; this->high[i] = (int)ceil(high); if (this->high[i]>size) this->high[i] = size; } } // Indicate that we are in a valid state... this->valid = 1; } int IterDual_next(Spatial self) { IterDual * this = (IterDual*)self; if (this->valid==0) return -1; // Calculate the index for the current position... int ret = 0; int i; for (i=0; i<this->indices; i++) { int oi = this->original[i]; ret *= this->dm->array->dimensions[oi]; ret += this->pos[i]; } // Move to the next index... for (i=this->indices-1;; i--) { this->pos[i] += 1; if (this->pos[i]<this->high[i]) break; if (i==0) break; this->pos[i] = this->low[i]; } if (this->pos[0]>=this->high[0]) this->valid = 0; // Return the index... return ret; } const SpatialType IterDualType = { "iter_dual", "Limits the values to consider by using the dual dimensions in the data matrix, as for each of them a search range can be calculated to include all within the bound. Within the region defined its brute force however - if the dual dimensions don't limit the data enough it might make more sense to use a different structure. If there are no dual dimensions it ends up equivalent to brute force. Its typical use is when doing mean shift on images.", IterDual_new, IterDual_delete, IterDual_dm, IterDual_start, IterDual_next, }; // Implimentation of the KD-tree spatial indexer... typedef struct PosFeat PosFeat; struct PosFeat { int pos; float feat; }; int sort_pos_feat(const void * lhs, const void * rhs) { const PosFeat * l = (PosFeat*)lhs; const PosFeat * r = (PosFeat*)rhs; if (l->feat < r->feat) return -1; if (l->feat > r->feat) return 1; return 0; } typedef struct KDNode KDNode; struct KDNode { KDNode * parent; KDNode * child_low; KDNode * child_high; int low; // Range of values the tree covers in the indices array. int high; // Exclusive. float range[0]; // 2* number of features, with the low range indexed for feature i as range[i*2], and the high range [i*2+1]. }; typedef struct KDTree KDTree; struct KDTree { const SpatialType * type; DataMatrix * dm; int * indices; // All the indices - the nodes of the KD tree just have to store ranges into this, as we rearrange them during construction - allows for some fun optimisation tricks. KDNode * root; // Root of the tree. KDNode * targ; // For when iterating - allways a node we are searching. int offset; // Offset of iterating. const float * centre; // Bounding box of current iterations. float range; }; KDNode * KDNode_new(DataMatrix * dm, int * indices, int low, int high, int depth, PosFeat * scratch) { KDNode * this = (KDNode*)malloc(sizeof(KDNode) + dm->feats * 2 * sizeof(float)); // Basic initialisation... this->parent = NULL; this->child_low = NULL; this->child_high = NULL; this->low = low; this->high = high; // Calculate the range... float * fv = DataMatrix_fv(dm, indices[low], NULL); int i; for (i=0; i<dm->feats; i++) { this->range[i*2] = fv[i]; this->range[i*2+1] = fv[i]; } for (i=low+1; i<high; i++) { fv = DataMatrix_fv(dm, indices[i], NULL); int j; for (j=0; j<dm->feats; j++) { if (this->range[j*2]>fv[j]) this->range[j*2] = fv[j]; if (this->range[j*2+1]<fv[j]) this->range[j*2+1] = fv[j]; } } // Decide if we are going to divide further or not... if (depth>64) return this; if ((high-low)<6) return this; // Choose a division direction - the one with the largest range; possible condition for leaving as well... int split_feat = 0; float split_range = this->range[split_feat*2+1] - this->range[split_feat*2]; for (i=1; i<dm->feats; i++) { float range = this->range[i*2+1] - this->range[i*2]; if (range>split_range) { split_feat = i; split_range = range; } } if (split_range<1e-3) return this; // Sort the indices by the feature... for (i=low; i<high; i++) { scratch[i-low].pos = indices[i]; scratch[i-low].feat = DataMatrix_fv(dm, indices[i], NULL)[split_feat]; } qsort(scratch, high-low, sizeof(PosFeat), sort_pos_feat); for (i=low; i<high; i++) { indices[i] = scratch[i-low].pos; } // Do the split... int half = (low + high) / 2; this->child_low = KDNode_new(dm, indices, low, half, depth+1, scratch); this->child_high = KDNode_new(dm, indices, half, high, depth+1, scratch); // Assign parents... this->child_low->parent = this; this->child_high->parent = this; // Return... return this; } void KDNode_delete(KDNode * this) { if (this->child_low!=NULL) KDNode_delete(this->child_low); if (this->child_high!=NULL) KDNode_delete(this->child_high); free(this); } KDNode * KDNode_next_down(KDNode * this, DataMatrix * dm, const float * centre, float range) { int i; // If its a miss return null - we are not going this way... int within = 1; for (i=0; i<dm->feats; i++) { float req_low = centre[i] - range; float req_high = centre[i] + range; float bb_low = this->range[i*2]; float bb_high = this->range[i*2+1]; if (req_high<bb_low) return NULL; if (req_low>bb_high) return NULL; if (req_low>bb_low) within = 0; if (req_high<bb_high) within = 0; } // If the entire node is within the space return it - actual calculation is above... if (within!=0) return this; // If it has no children return it - we have got as close to the split line as we can... if (this->child_low==NULL) return this; // Check each child in turn... KDNode * ret = KDNode_next_down(this->child_low, dm, centre, range); if (ret!=NULL) return ret; return KDNode_next_down(this->child_high, dm, centre, range); } KDNode * KDNode_next_up(KDNode * this, DataMatrix * dm, const float * centre, float range) { while (this->parent!=NULL) { KDNode * child = this; this = this->parent; if (this->child_low==child) { KDNode * ret = KDNode_next_down(this->child_high, dm, centre, range); if (ret!=NULL) return ret; } } return NULL; } Spatial KDTree_new(DataMatrix * dm) { KDTree * this = (KDTree*)malloc(sizeof(KDTree)); this->type = &KDTreeType; this->dm = dm; this->indices = (int*)malloc(this->dm->exemplars * sizeof(int)); int i; for (i=0; i<this->dm->exemplars; i++) this->indices[i] = i; PosFeat * scratch = (PosFeat*)malloc(this->dm->exemplars * sizeof(PosFeat)); this->root = KDNode_new(this->dm, this->indices, 0, this->dm->exemplars, 0, scratch); free(scratch); this->targ = NULL; return this; } void KDTree_delete(Spatial self) { KDTree * this = (KDTree*)self; free(this->indices); KDNode_delete(this->root); free(this); } DataMatrix * KDTree_dm(Spatial self) { KDTree * this = (KDTree*)self; return this->dm; } void KDTree_start(Spatial self, const float * centre, float range) { KDTree * this = (KDTree*)self; this->targ = KDNode_next_down(this->root, this->dm, centre, range); this->offset = 0; this->centre = centre; this->range = range; } int KDTree_next(Spatial self) { KDTree * this = (KDTree*)self; if (this->targ==NULL) return -1; // Calculate the return... int ret = this->indices[this->targ->low + this->offset]; // Move to the next position... this->offset += 1; if ((this->offset+this->targ->low)>=this->targ->high) { this->targ = KDNode_next_up(this->targ, this->dm, this->centre, this->range); this->offset = 0; } // Return the return!.. return ret; } const SpatialType KDTreeType = { "kd_tree", "A standard kd-tree on the feature vectors - best choice if the data has no dual dimensions.", KDTree_new, KDTree_delete, KDTree_dm, KDTree_start, KDTree_next, }; // List of spatial indexing methods provide by the system... const SpatialType * ListSpatial[] = { &BruteForceType, &IterDualType, &KDTreeType, NULL }; // Dummy function, to make a warning go away because it was annoying me... void SpatialModule_IgnoreMe(void) { import_array(); }
2.25
2
2024-11-18T18:55:04.261572+00:00
2021-01-25T11:59:04
cd7ea51bac9d0244733ff0096897dbfb574b0605
{ "blob_id": "cd7ea51bac9d0244733ff0096897dbfb574b0605", "branch_name": "refs/heads/main", "committer_date": "2021-01-25T11:59:04", "content_id": "b0109d90284843cf4e5b0f82a4f3475171c51c48", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "a71f82439f75e01cc157b5ef6f9289369e1dadb2", "extension": "c", "filename": "demo2.c", "fork_events_count": 0, "gha_created_at": "2020-11-20T15:32:36", "gha_event_created_at": "2021-01-11T03:34:44", "gha_language": "C", "gha_license_id": "BSD-3-Clause", "github_id": 314594442, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 385, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/demo2.c", "provenance": "stackv2-0008.json.gz:2312", "repo_name": "mgrosvenor/evec", "revision_date": "2021-01-25T11:59:04", "revision_id": "7e8c8d75083ebd2a09f15b375cf6ab7a5b20cdd8", "snapshot_id": "6aaa3325a9627ef6d734e2e9f237b1d8b2c030e1", "src_encoding": "UTF-8", "star_events_count": 9, "url": "https://raw.githubusercontent.com/mgrosvenor/evec/7e8c8d75083ebd2a09f15b375cf6ab7a5b20cdd8/demo2.c", "visit_date": "2023-02-21T17:25:53.838739" }
stackv2
/* * Demo 2: * A demo showing EV extended functions in use. */ #include <stdio.h> #include "evec.h" int main(int argc, char** argv) { void* a = evinisz(128); evpsh(a, "Test"); evpsh(a, "Best"); evpsh(a, "Rest"); for(int i =0; i < evcnt(a); i++){ char* s = (char*)evidx(a,i); printf("%i: %s\n", i, s); } a = evfree(a); return 0; }
2.75
3
2024-11-18T18:57:41.693426+00:00
2013-09-22T22:46:40
e0c838431182440869ae98b08d0eacb55ffa928d
{ "blob_id": "e0c838431182440869ae98b08d0eacb55ffa928d", "branch_name": "refs/heads/master", "committer_date": "2013-09-22T22:46:40", "content_id": "f744af61a0353186c427a25fbe17f81807d8c35c", "detected_licenses": [ "MIT" ], "directory_id": "11e1cf3683b14f21af235e0569e024c343626c03", "extension": "c", "filename": "z2.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 13156269, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 361, "license": "MIT", "license_type": "permissive", "path": "/latex/src/av10/z2.c", "provenance": "stackv2-0008.json.gz:3720", "repo_name": "kikojumkd/SP", "revision_date": "2013-09-22T22:46:40", "revision_id": "217cf66bdce28342b211198bac28d4571311265c", "snapshot_id": "c334b34af6710af9fafe38b752c02fc139a69aad", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/kikojumkd/SP/217cf66bdce28342b211198bac28d4571311265c/latex/src/av10/z2.c", "visit_date": "2021-01-15T16:52:02.267157" }
stackv2
#include <stdio.h> #define MAX 100 int dolzina(char *s) { int i, len = 0; for (i = 0; s[i] != '\0'; i++) len++; return len; } int length(char *s) { if (*s == '\0') return 0; return 1 + length(s + 1); } int main() { char s[MAX]; printf("Vnesete ja tekstualna niza:\n"); gets(s); printf("Dolzina: %d i %d\n", dolzina(s), length(s)); return 0; }
3.09375
3
2024-11-18T18:57:41.880229+00:00
2014-09-09T19:28:19
9dd5173ab6f0eff29e05e8fe7396ca6b23789c76
{ "blob_id": "9dd5173ab6f0eff29e05e8fe7396ca6b23789c76", "branch_name": "refs/heads/master", "committer_date": "2014-09-09T19:28:19", "content_id": "a513a38a6eabd841055b6f2103981cefd015e52f", "detected_licenses": [ "MIT" ], "directory_id": "e00d688f71529f7b19ef52242859960256c54e1e", "extension": "c", "filename": "logout.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 23804737, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2343, "license": "MIT", "license_type": "permissive", "path": "/win32/c/logout.c", "provenance": "stackv2-0008.json.gz:3976", "repo_name": "richardneish/ltrdata", "revision_date": "2014-09-09T19:28:19", "revision_id": "9fffd93fa542421bc05c16972c72ea7fabdf2d3a", "snapshot_id": "752a5071f4d066ea8757b3e47032e0c78f22c074", "src_encoding": "ISO-8859-1", "star_events_count": 1, "url": "https://raw.githubusercontent.com/richardneish/ltrdata/9fffd93fa542421bc05c16972c72ea7fabdf2d3a/win32/c/logout.c", "visit_date": "2016-09-06T06:30:42.366858" }
stackv2
#include <stdlib.h> #define WIN32_LEAN_AND_MEAN #include <winstrct.h> #pragma comment(lib, "advapi32") #if defined(_DLL) && !defined(_WIN64) #pragma comment(lib, "minwcrt") #endif int WINAPI WinMain(HINSTANCE hCurInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { UINT uFlags = 0; BOOL displayhelp = FALSE; HANDLE hToken; DWORD dwReason = SHTDN_REASON_FLAG_PLANNED; TOKEN_PRIVILEGES TP; // Nice argument parse loop :) if (lpCmdLine ? lpCmdLine[0] ? (lpCmdLine[0]|0x02) == '/' : FALSE : FALSE) while ((++lpCmdLine)[0]) switch (lpCmdLine[0]|0x20) { case 'f': uFlags |= EWX_FORCE; break; case 'l': uFlags |= EWX_LOGOFF; break; case 'o': uFlags |= EWX_POWEROFF; break; case 'r': uFlags |= EWX_REBOOT; break; case 'h': uFlags |= EWX_SHUTDOWN; break; default: displayhelp = TRUE; } if (displayhelp) { MessageBox(NULL, "LOGOUT. User interface for the Win32 API function ExitWindowsEx.\r\n" "\r\n" "/L\tLog off (default)\r\n" "/H\tShut down\r\n" "/R\tReboot\r\n" "/F\tForce processes to terminate\r\n" "/O\tPower off\r\n" "\r\n", "Logout", MB_ICONINFORMATION | MB_TASKMODAL); return 0; } // I Windows NT måste vi aktivera rättigheten SE_SHUTDOWN_NAME. if (WinVer_WindowsNT) { if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &hToken)) { char *errmsg = win_error; MessageBox( NULL, errmsg, "Logout", MB_ICONSTOP | MB_TASKMODAL); LocalFree(errmsg); return 1; } TP.PrivilegeCount = 1; LookupPrivilegeValue("", SE_SHUTDOWN_NAME, &(TP.Privileges[0].Luid)); TP.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; if (!AdjustTokenPrivileges(hToken, FALSE, &TP, 0, NULL, NULL)) { char *errmsg = win_error; MessageBox(NULL, errmsg, "Logout", MB_ICONSTOP | MB_TASKMODAL); LocalFree(errmsg); return 1; } } // I Win32s kan man inte välja olika utloggningsmetoder. Bara 0 är // tillåtet. if (WinVer_Win32s) { uFlags = 0; dwReason = 0; } // Prova att logga ut och se vad som händer. Visa felmeddelande om det // inte fungerade. if (!ExitWindowsEx(uFlags, dwReason)) { MessageBox(NULL, win_error, "Logout", MB_ICONSTOP | MB_TASKMODAL); return 1; } else return 0; }
2.21875
2
2024-11-18T18:57:41.950876+00:00
2018-03-14T12:44:12
a5c4b5c229fa2791419b94da58913434ab89dce9
{ "blob_id": "a5c4b5c229fa2791419b94da58913434ab89dce9", "branch_name": "refs/heads/master", "committer_date": "2018-03-14T12:44:12", "content_id": "2b4ba62c14ae1f71bd6f90991d02fdf0c3986705", "detected_licenses": [ "MIT" ], "directory_id": "746d3cd0696fd3f784acf661812ef371a5ecebb7", "extension": "c", "filename": "6.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 108884383, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 840, "license": "MIT", "license_type": "permissive", "path": "/chapter11/exercises/6.c", "provenance": "stackv2-0008.json.gz:4104", "repo_name": "ygdm7/ProgrammingInCSolutions", "revision_date": "2018-03-14T12:44:12", "revision_id": "5812605683809c6517ca5eb733cfb14e2b21afa5", "snapshot_id": "5b80e5f36c5d8f78be70a45f64809383739e087d", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/ygdm7/ProgrammingInCSolutions/5812605683809c6517ca5eb733cfb14e2b21afa5/chapter11/exercises/6.c", "visit_date": "2021-09-09T08:55:36.038773" }
stackv2
// Exercise 6 from chapter 11 // These functions insert and remove entries from a doubly linked list. /* removeEntry can now remove an exact element of the list because the doublyEntry struct have pointers to the next and the previous list elements, making it possible to link them before removing the middle entry. */ struct doublyEntry { int value; struct doublyEntry *next; struct doublyEntry *previous; }; void insertEntry( struct doublyEntry *insert, struct doublyEntry *element ) { insert->next = element->next; insert->next->previous = insert; insert->previous = element; element->next = insert; } void removeEntry( struct doublyEntry *element ) { if( element->next != 0 ) element->next->previous = element->previous; if( element->previous != 0 ) element->previous->next = element->next; }
3.328125
3
2024-11-18T18:57:42.014966+00:00
2021-10-23T06:45:18
8743f1093a5199b2b0d90f4b24edf4ded9d0ef57
{ "blob_id": "8743f1093a5199b2b0d90f4b24edf4ded9d0ef57", "branch_name": "refs/heads/main", "committer_date": "2021-10-23T06:45:27", "content_id": "2181fc89b17ac74d448ac6a5a7b0b59bd78b598c", "detected_licenses": [ "Apache-2.0" ], "directory_id": "f8a5bc2f85509fc335f0e2e4feffa14cbb57ede3", "extension": "c", "filename": "prom_process_fds.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1686, "license": "Apache-2.0", "license_type": "permissive", "path": "/prom/src/prom_process_fds.c", "provenance": "stackv2-0008.json.gz:4232", "repo_name": "jpalpant/libprom", "revision_date": "2021-10-23T06:45:18", "revision_id": "e332b9a9fb896cd179369c2d0461a9e66e356bef", "snapshot_id": "e6dc9b9b26f800877e97c6e9c2d534548e452ef8", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/jpalpant/libprom/e332b9a9fb896cd179369c2d0461a9e66e356bef/prom/src/prom_process_fds.c", "visit_date": "2023-08-28T09:05:02.719547" }
stackv2
/** * Copyright 2019-2020 DigitalOcean Inc. * Copyright 2021 Jens Elkner <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <dirent.h> #include <string.h> // Public #include "prom_gauge.h" // Private #include "prom_errors.h" #include "prom_log.h" #include "prom_process_collector_t.h" int ppc_fds_new(prom_metric_t *m[], const char **label_keys) { if (m == NULL) return 0; m[PM_OPEN_FDS] = prom_gauge_new("process_open_fds", "Number of open file descriptors", 0, label_keys); return m[PM_OPEN_FDS] == NULL ? 0 : 1 << PM_OPEN_FDS; } static double ppc_fds_count(const char *path) { int count = 0; struct dirent *de; if (path == NULL) return NaN; DIR *d = opendir(path); if (d == NULL) { PROM_WARN(PROM_STDIO_OPEN_DIR_ERROR " '%s'", path); return NaN; } while ((de = readdir(d)) != NULL) { if (strcmp(".", de->d_name) == 0 || strcmp("..", de->d_name) == 0) continue; count++; } if (closedir(d)) PROM_WARN(PROM_STDIO_CLOSE_DIR_ERROR " '%s'", path); return count; } int ppc_fds_update(const char *path, prom_metric_t *m[], const char **lvals) { return gup(PM_OPEN_FDS, ppc_fds_count(path)); }
2.109375
2
2024-11-18T19:00:00.825737+00:00
2018-01-12T16:21:35
439fcf737aad946e5f4af87aaab416c3c7d136fd
{ "blob_id": "439fcf737aad946e5f4af87aaab416c3c7d136fd", "branch_name": "refs/heads/master", "committer_date": "2018-01-12T16:21:35", "content_id": "0445c9e45b7a86368654e63b19e7fafd2bd1af1b", "detected_licenses": [ "MIT" ], "directory_id": "c9d073d4c966119fe8865bc8188330ed32bf9d63", "extension": "h", "filename": "config.h", "fork_events_count": 21, "gha_created_at": "2016-07-16T01:15:48", "gha_event_created_at": "2020-04-29T22:49:14", "gha_language": "C++", "gha_license_id": "MIT", "github_id": 63459337, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1940, "license": "MIT", "license_type": "permissive", "path": "/include/tansa/config.h", "provenance": "stackv2-0008.json.gz:4360", "repo_name": "dennisss/tansa", "revision_date": "2018-01-12T16:21:35", "revision_id": "e6044af397f99b9b985ed56015e9e0be13d4b026", "snapshot_id": "7d8d6ab2ba2cb65d957d4a7faf998725bd5a33a7", "src_encoding": "UTF-8", "star_events_count": 39, "url": "https://raw.githubusercontent.com/dennisss/tansa/e6044af397f99b9b985ed56015e9e0be13d4b026/include/tansa/config.h", "visit_date": "2021-05-01T00:24:55.496906" }
stackv2
#ifndef TANSA_CONFIG_H #define TANSA_CONFIG_H #define VEHICLE_ASCENT_MS 0.2 #define VEHICLE_DESCENT_MS 0.3 /** * Contains client and server address for drone netcode. */ struct hardware_config { string clientAddress; string serverAddress; }; /** * Contains config info for drone */ struct vehicle_config { unsigned net_id; // The number printed on the physical unsigned chor_id; // The id between 1 and 6 respesenting which drone in the choreography it w unsigned lport; // Usually 14550 + id*10 unsigned rport; // For now always 14555 }; /** * State assigned to a vehicle controlled by a player */ enum PlayerVehicleState { /** * Vehicle disarmed and not doing anything * * Transitions to Ready upon arm() */ StateInit, /** * Arms the drone, transitions to Ready on completion */ StateArming, /** * Vehicle armed but doing nothing on the ground * * Once all vehicles are Ready, transitions to Takeoff on load of a JOCS file */ StateReady, /** * Vehicle going to starting point of first action * * If the starting point is on the ground, then: * - if the vehicle is on the ground, this is a no-op * - else this descends and lands without entering Landing state * * Transitions to Holding upon getting to the point */ StateTakeoff, /** * Hovers/sits in one place * * If in the air and 20 seconds have elapsed, transitions to Landing state * * Transitions to Takeoff upon load of a new JOCS file * * Transitions to Flying on play() */ StateHolding, /** * Performs the assigned actions * * After a pause(), on next safe point, transitions to Holding * * Transitions to Landing after completion of all actions */ StateFlying, /** * Landing at the current position and disarming * * Transitions to Init upon completion */ StateLanding, /** * Vehicle responding to a failure condition */ StateFailsafe }; #endif //TANSA_CONFIG_H
2.03125
2
2024-11-18T19:00:00.944155+00:00
2019-11-01T17:06:19
44f07a8620264f3d82e4898f9f3f03950b59a8c4
{ "blob_id": "44f07a8620264f3d82e4898f9f3f03950b59a8c4", "branch_name": "refs/heads/master", "committer_date": "2019-11-01T17:06:19", "content_id": "b95260af2391582b34bb9054f85ca42e52709b24", "detected_licenses": [ "MIT", "BSD-3-Clause" ], "directory_id": "5499e8b91353ef910d2514c8a57a80565ba6f05b", "extension": "c", "filename": "sherlock-uart.c", "fork_events_count": 2, "gha_created_at": "2019-11-24T05:08:59", "gha_event_created_at": "2022-10-13T13:47:02", "gha_language": "C++", "gha_license_id": "BSD-3-Clause", "github_id": 223695500, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 504, "license": "MIT,BSD-3-Clause", "license_type": "permissive", "path": "/zircon/kernel/target/arm64/boot-shim/sherlock-uart.c", "provenance": "stackv2-0008.json.gz:4488", "repo_name": "winksaville/fuchsia", "revision_date": "2019-11-01T17:06:19", "revision_id": "a0ec86f1d51ae8d2538ff3404dad46eb302f9b4f", "snapshot_id": "410f451b8dfc671f6372cb3de6ff0165a2ef30ec", "src_encoding": "UTF-8", "star_events_count": 3, "url": "https://raw.githubusercontent.com/winksaville/fuchsia/a0ec86f1d51ae8d2538ff3404dad46eb302f9b4f/zircon/kernel/target/arm64/boot-shim/sherlock-uart.c", "visit_date": "2022-11-01T11:57:38.343655" }
stackv2
// Copyright 2018 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <stdint.h> #include "debug.h" #define S905_UART_WFIFO (0x0) #define S905_UART_STATUS (0xc) #define S905_UART_STATUS_TXFULL (1 << 21) #define UARTREG(reg) (*(volatile uint32_t*)(0xff803000 + (reg))) void uart_pputc(char c) { while (UARTREG(S905_UART_STATUS) & S905_UART_STATUS_TXFULL) ; UARTREG(S905_UART_WFIFO) = c; }
2
2
2024-11-18T19:00:01.186320+00:00
2018-01-24T00:39:01
c621887cb52c2722d3b50cc3293689010f8d6e66
{ "blob_id": "c621887cb52c2722d3b50cc3293689010f8d6e66", "branch_name": "refs/heads/dev", "committer_date": "2018-01-24T00:39:01", "content_id": "1bc2e32d696b08696207b4fd566cc113dbbc35a2", "detected_licenses": [ "Unlicense" ], "directory_id": "89cc6ece96ca3264055ea7ccb252da648449eb77", "extension": "h", "filename": "echoTap.h", "fork_events_count": 22, "gha_created_at": "2011-07-28T17:10:07", "gha_event_created_at": "2018-03-22T23:14:19", "gha_language": "C", "gha_license_id": null, "github_id": 2119601, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4755, "license": "Unlicense", "license_type": "permissive", "path": "/dsp/echoTap.h", "provenance": "stackv2-0008.json.gz:4616", "repo_name": "monome/aleph", "revision_date": "2018-01-24T00:39:01", "revision_id": "2275cd49e6da26a3a11f7bd4a81e7cf52e400026", "snapshot_id": "a7f4682fb305bfe3355f10e18c04f2fc0f62bed0", "src_encoding": "UTF-8", "star_events_count": 42, "url": "https://raw.githubusercontent.com/monome/aleph/2275cd49e6da26a3a11f7bd4a81e7cf52e400026/dsp/echoTap.h", "visit_date": "2020-04-10T15:56:12.621386" }
stackv2
/* echoTap.h audio lib aleph These are 'slave' taps for creating echo effects/pitch shift They are indexed relative to a write head, not a buffer. They should do anti-aliased interpolated read */ #ifndef _ALEPH_ECHOTAP_H_ #define _ALEPH_ECHOTAP_H_ #include "fix.h" #include "fix32.h" #include "types.h" #include "buffer.h" #include "pan.h" #include "ricks_tricks.h" // ---- echoTap // Data structure for an 'echo tap' // echo is position relative to write tap // inc is tap speed along the buffer // echoWrap is where tap starts to wrap back // echoReset is where echo tap wraps back to typedef struct _echoTap { bufferTapN* tapWr; // pointer to write head s32 time; // delay time in subsamples (1/256 sample) s32 idx_last;// last position read from (for antialiasing) s32 speed; s32 max; s32 min; //check for zero crossing //This flag is used to set the type of envelope. //No longer to be used for equal-power x-fades s32 shape; //This flag sets the boundary behaviour //e.g wrap, oneshot or bounce s32 edgeBehaviour; s32 fadeLength; } echoTap; //the maximum number of samples to use for antialiased read #define MAX_ANTIALIAS 3 #define EDGE_ONESHOT 0 //if oneshot, then stop when grain hits a boundary #define EDGE_WRAP 1 //if wrap, then go back to the opposite boundary #define EDGE_BOUNCE 2 //if bounce, then flip the read head play direction when grain hits boundary #define SHAPE_TOPHAT 0 //tophat is FR32_MpAX between max and min, 0 elsewhere #define SHAPE_TRIANGLE 1 //triangle is linear ramp up to FR32_MAX from min to center, back down to zero from center to max #define SHAPE_LUMP 2 //grain_lump is 1 - (abs(x)) for -1 < x > 1 #define SHAPE_HALFWAVE 3 //shape fadeshort is FR32_MAX until the edges, then slopes down even slower void echoTap_next(echoTap* tap); // fixed grain envelope shapes fract32 echoTap_envelope(echoTap *tap); // intialize tap extern void echoTap_init(echoTap* tap, bufferTapN* tapWr); // interpolated cubic read static inline fract32 echoTap_read_interp_cubic(echoTap* echoTap, s32 time) { u32 samp0_index = (echoTap->tapWr->idx + echoTap->tapWr->loop - 3 - (time >> 8)); samp0_index = samp0_index % echoTap->tapWr->loop; fract32 *samp0 = (fract32*)echoTap->tapWr->buf->data + samp0_index; u32 buffSize = sizeof (fract32) * (u32) echoTap->tapWr->loop; fract32 *buffer = (fract32*)echoTap->tapWr->buf->data; fract32 *samp1 = (fract32*)__builtin_bfin_circptr (samp0, sizeof (fract32), buffer, buffSize); fract32 *samp2 = (fract32*)__builtin_bfin_circptr (samp1, sizeof (fract32), buffer, buffSize); fract32 *samp3 = (fract32*)__builtin_bfin_circptr (samp2, sizeof (fract32), buffer, buffSize); fract32 inter_sample = shl_fr1x32((time & 0xFF), 23); fract32 pre_fader; //Pick an interpolation method! - linear or cubic? /* pre_fader = pan_lin_mix(*samp2, *samp1, inter_sample); */ pre_fader = interp_bspline_fract32(inter_sample, *samp3, *samp2, *samp1, *samp0); return pre_fader; } // interpolated linear read static inline fract32 echoTap_read_interp_linear(echoTap* echoTap, s32 time) { u32 samp1_index = (echoTap->tapWr->idx + echoTap->tapWr->loop - 1 - (time >> 8)); samp1_index = samp1_index % echoTap->tapWr->loop; fract32 *samp1 = (fract32*)echoTap->tapWr->buf->data + samp1_index; u32 buffSize = sizeof (fract32) * (u32) echoTap->tapWr->loop; fract32 *buffer = (fract32*)echoTap->tapWr->buf->data; fract32 *samp2 = (fract32*)__builtin_bfin_circptr (samp1, sizeof (fract32), buffer, buffSize); fract32 inter_sample = shl_fr1x32((time & 0xFF), 23); fract32 pre_fader; pre_fader = pan_lin_mix(*samp2, *samp1, inter_sample); return pre_fader; } //#!gnuplot //plot cos(x*pi/2), sin(x*pi/2), 1 - x**2, 1 - (1 - x)**2 //fades x into y as pos slides from 0 to FR32_MAX static inline s32 equalPower_xfade (fract32 x, fract32 y, fract32 pos) { fract32 pos_2 = mult_fr1x32x32(pos, pos); fract32 amp_x = sub_fr1x32(FR32_MAX, pos_2); fract32 pos_bar = sub_fr1x32(FR32_MAX, pos); fract32 amp_y = sub_fr1x32(FR32_MAX, mult_fr1x32x32(pos_bar, pos_bar)); return add_fr1x32(mult_fr1x32x32(amp_x, x), mult_fr1x32x32(amp_y, y)); } static inline fract32 echoTap_boundToFadeRatio (echoTap* tap, s32 unbounded) { return (fract32) (max_fr1x32 (0, min_fr1x32 (tap->fadeLength, unbounded)) * (FR32_MAX / (max_fr1x32 (1, tap->fadeLength)))); } fract32 echoTap_read_xfade(echoTap* echoTap, s32 offset); #endif // h guard
2.1875
2
2024-11-18T19:32:42.283870+00:00
2020-12-23T08:36:28
a9e24bfa0c5e0a3e95c1dc8f9e01f26278161d03
{ "blob_id": "a9e24bfa0c5e0a3e95c1dc8f9e01f26278161d03", "branch_name": "refs/heads/main", "committer_date": "2020-12-23T08:36:28", "content_id": "e0b5fa694af6950f679981f2e88a864274b4e130", "detected_licenses": [ "CC0-1.0" ], "directory_id": "75e1d9446cb1fca5c6a79ad0ba7f38268df1161f", "extension": "c", "filename": "stock-buy-sell-once-maximum-profit.c", "fork_events_count": 1, "gha_created_at": "2020-12-24T19:12:54", "gha_event_created_at": "2020-12-24T19:12:54", "gha_language": null, "gha_license_id": "CC0-1.0", "github_id": 324221340, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 521, "license": "CC0-1.0", "license_type": "permissive", "path": "/C Programs/stock-buy-sell-once-maximum-profit.c", "provenance": "stackv2-0008.json.gz:14999", "repo_name": "muhammad-masood-ur-rehman/Skillrack", "revision_date": "2020-12-23T08:36:28", "revision_id": "71a25417c89d0efab40ee6229ccd758b26ae4312", "snapshot_id": "6e9b6d93680dfef6f40783f02ded8a0d4283c98a", "src_encoding": "UTF-8", "star_events_count": 4, "url": "https://raw.githubusercontent.com/muhammad-masood-ur-rehman/Skillrack/71a25417c89d0efab40ee6229ccd758b26ae4312/C Programs/stock-buy-sell-once-maximum-profit.c", "visit_date": "2023-02-03T16:45:54.462561" }
stackv2
Stock Buy & Sell Once - Maximum Profit Input: 7 50 100 40 60 70 50 80 Output: 50 #include<stdio.h> #include <stdlib.h> #define max(x,y) x>y? x: y #define min(x,y) x<y? x: y int main() { int n; scanf("%d",&n); int arr[n]; for(int i=0;i<n;++i)scanf("%d",&arr[i]); int maxProfit=0,currentProfit=0,mini=arr[0]; for(int i=1;i<n;++i){ currentProfit=arr[i]-mini; maxProfit=max(currentProfit,maxProfit); mini=min(arr[i],mini); } printf("%d",maxProfit); }
3.140625
3
2024-11-18T17:54:19.702944+00:00
2016-07-18T20:27:48
2f16c20095f3b3c8018a32b6964e0af98c9fda0d
{ "blob_id": "2f16c20095f3b3c8018a32b6964e0af98c9fda0d", "branch_name": "refs/heads/master", "committer_date": "2016-07-18T20:27:48", "content_id": "118123fd180e18ca25f77ae5ce18341d736f1823", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "3848970626587148dd932cdf3e54f5819d46cfc3", "extension": "h", "filename": "tls.h", "fork_events_count": 2, "gha_created_at": "2014-08-07T07:25:26", "gha_event_created_at": "2015-01-19T07:33:09", "gha_language": "Python", "gha_license_id": null, "github_id": 22712392, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1492, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/libsel4camkes/include/camkes/tls.h", "provenance": "stackv2-0009.json.gz:996", "repo_name": "smaccm/camkes-tool", "revision_date": "2016-07-18T20:27:48", "revision_id": "54ec7a85224b9b49a76029310742bba1b00732fd", "snapshot_id": "727b3735d67469e11124f796745f42e232d75663", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/smaccm/camkes-tool/54ec7a85224b9b49a76029310742bba1b00732fd/libsel4camkes/include/camkes/tls.h", "visit_date": "2020-05-21T23:08:27.790018" }
stackv2
/* * Copyright 2014, NICTA * * This software may be distributed and modified according to the terms of * the BSD 2-Clause license. Note that NO WARRANTY is provided. * See "LICENSE_BSD2.txt" for details. * * @TAG(NICTA_BSD) */ #ifndef _CAMKES_TLS_H_ #define _CAMKES_TLS_H_ /* Thread-local storage functionality for CAmkES. */ #include <assert.h> #include <sel4/sel4.h> #include <stdint.h> #include <utils/util.h> /* Extend this struct as required. */ typedef struct camkes_tls_t { seL4_CPtr tcb_cap; unsigned int thread_index; } camkes_tls_t; static inline camkes_tls_t * UNUSED camkes_get_tls(void) { /* We store TLS data in the same page as the thread's IPC buffer, but at * the start of the page. */ uintptr_t ipc_buffer = (uintptr_t)seL4_GetIPCBuffer(); /* Normally we would just use MASK here, but the verification C parser * doesn't like the GCC extension used in that macro. The following * assertion could be checked at compile-time, but then it appears in input * to the verification process that causes other problems. */ assert(PAGE_BITS_4K <= 31 && "mask shift is safe"); uintptr_t tls = ipc_buffer & ~MASK_UNSAFE(PAGE_BITS_4K); /* We should have enough room for the TLS data preceding the IPC buffer. */ assert(ipc_buffer - tls >= sizeof(camkes_tls_t)); /* We'd better be returning a valid pointer. */ assert(tls % __alignof__(camkes_tls_t) == 0); return (camkes_tls_t*)tls; } #endif
2.25
2
2024-11-18T17:54:19.806612+00:00
2019-08-25T02:51:30
9235194ba6a0bcc9a41b1dab59164f702eed3336
{ "blob_id": "9235194ba6a0bcc9a41b1dab59164f702eed3336", "branch_name": "refs/heads/development", "committer_date": "2019-09-28T22:27:54", "content_id": "ad8b1da9b6f56b8541452ccc488b93c66311efb1", "detected_licenses": [ "ISC" ], "directory_id": "93be5d831adfdc50cb4275e54e1741d0d1a2ea06", "extension": "c", "filename": "resolve.c", "fork_events_count": 65, "gha_created_at": "2017-10-01T23:18:26", "gha_event_created_at": "2019-06-22T01:01:21", "gha_language": "C", "gha_license_id": "ISC", "github_id": 105481619, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3275, "license": "ISC", "license_type": "permissive", "path": "/lib/ld/resolve.c", "provenance": "stackv2-0009.json.gz:1124", "repo_name": "reswitched/libtransistor", "revision_date": "2019-08-25T02:51:30", "revision_id": "e356d4b57259e24fed725af08d1bd21902475e14", "snapshot_id": "9b22a06b9244aac469e0c08f540196587e88ce2d", "src_encoding": "UTF-8", "star_events_count": 225, "url": "https://raw.githubusercontent.com/reswitched/libtransistor/e356d4b57259e24fed725af08d1bd21902475e14/lib/ld/resolve.c", "visit_date": "2021-05-16T03:26:54.866613" }
stackv2
#include<libtransistor/ld/internal.h> #include<libtransistor/types.h> #include<libtransistor/err.h> #include<libtransistor/util.h> #include<libtransistor/ld/ld.h> #include<libtransistor/ld/elf.h> #include<libtransistor/ld/module.h> #include<stdint.h> #include<stdlib.h> #include<string.h> static result_t ld_try_resolve_symbol(module_t *try_mod, const char *find_name, uint64_t find_name_hash, Elf64_Sym **def, module_t **defining_module, bool require_global) { if(require_global && !try_mod->input.is_global) { return LIBTRANSISTOR_ERR_TRNLD_COULD_NOT_RESOLVE_SYMBOL; } if(try_mod->symtab == NULL) { return LIBTRANSISTOR_ERR_TRNLD_COULD_NOT_RESOLVE_SYMBOL; } if(try_mod->strtab == NULL) { return LIBTRANSISTOR_ERR_TRNLD_COULD_NOT_RESOLVE_SYMBOL; } if(try_mod->hash != NULL) { uint32_t nbucket = try_mod->hash[0]; uint32_t nchain = try_mod->hash[1]; (void) nchain; uint32_t index = try_mod->hash[2 + (find_name_hash % nbucket)]; uint32_t *chains = try_mod->hash + 2 + nbucket; while(index != 0 && strcmp(find_name, try_mod->strtab + try_mod->symtab[index].st_name) != 0) { index = chains[index]; } if(index == STN_UNDEF) { return LIBTRANSISTOR_ERR_TRNLD_COULD_NOT_RESOLVE_SYMBOL; } Elf64_Sym *sym = &try_mod->symtab[index]; if(sym->st_shndx == SHN_UNDEF) { return LIBTRANSISTOR_ERR_TRNLD_COULD_NOT_RESOLVE_SYMBOL; } *def = sym; *defining_module = try_mod; return RESULT_OK; } return LIBTRANSISTOR_ERR_TRNLD_COULD_NOT_RESOLVE_SYMBOL; } result_t ld_resolve_load_symbol(module_t *find_mod, const char *find_name, Elf64_Sym **def, module_t **defining_module) { uint64_t find_name_hash = elf_hash_string(find_name); trn_list_foreach(&ld_module_list_head, i) { result_t r = ld_try_resolve_symbol(trn_list_entry(module_list_node_t, list, i)->module, find_name, find_name_hash, def, defining_module, true); if(r == LIBTRANSISTOR_ERR_TRNLD_COULD_NOT_RESOLVE_SYMBOL) { continue; } else { // this includes RESULT_OK return r; } } // use last-resort module if(find_mod != NULL) { return ld_try_resolve_symbol(find_mod, find_name, find_name_hash, def, defining_module, false); } return LIBTRANSISTOR_ERR_TRNLD_COULD_NOT_RESOLVE_SYMBOL; } result_t ld_resolve_dependency_symbol(module_t *find_mod, const char *find_name, Elf64_Sym **def, module_t **defining_module) { uint64_t find_name_hash = elf_hash_string(find_name); result_t r; r = ld_try_resolve_symbol(find_mod, find_name, find_name_hash, def, defining_module, false); if(r != LIBTRANSISTOR_ERR_TRNLD_COULD_NOT_RESOLVE_SYMBOL) { // this includes RESULT_OK return r; } trn_list_foreach(&find_mod->dependencies, i) { r = ld_try_resolve_symbol(trn_list_entry(module_list_node_t, list, i)->module, find_name, find_name_hash, def, defining_module, false); if(r == LIBTRANSISTOR_ERR_TRNLD_COULD_NOT_RESOLVE_SYMBOL) { continue; } else { // this includes RESULT_OK return r; } } trn_list_foreach(&find_mod->dependencies, i) { r = ld_resolve_dependency_symbol(trn_list_entry(module_list_node_t, list, i)->module, find_name, def, defining_module); if(r == LIBTRANSISTOR_ERR_TRNLD_COULD_NOT_RESOLVE_SYMBOL) { continue; } else { // this includes RESULT_OK return r; } } return LIBTRANSISTOR_ERR_TRNLD_COULD_NOT_RESOLVE_SYMBOL; }
2.03125
2
2024-11-18T17:54:19.870701+00:00
2019-05-18T13:46:54
78625e5e65cd5a47cf6bba141568ae5e3bb80ecb
{ "blob_id": "78625e5e65cd5a47cf6bba141568ae5e3bb80ecb", "branch_name": "refs/heads/master", "committer_date": "2019-05-18T13:46:54", "content_id": "38ba762edda82fceb809a7f80a61554a47805d1d", "detected_licenses": [ "Apache-2.0" ], "directory_id": "d17a6d263cb0739f40e524d9005958501b7d6014", "extension": "c", "filename": "exercise_01-22.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 169207776, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1476, "license": "Apache-2.0", "license_type": "permissive", "path": "/ch_01/exercise_01-22.c", "provenance": "stackv2-0009.json.gz:1252", "repo_name": "daltonvlm/the-c-programming-language-solutions", "revision_date": "2019-05-18T13:46:54", "revision_id": "523e637665175e7c49294f028ba11e905991c2e0", "snapshot_id": "587171d264803df65210419cfc7238fd17577cc5", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/daltonvlm/the-c-programming-language-solutions/523e637665175e7c49294f028ba11e905991c2e0/ch_01/exercise_01-22.c", "visit_date": "2020-04-21T00:50:55.428757" }
stackv2
/* * Write a program to "fold" long input lines into two or more shorter * lines after the last nonblank character that occurs before the n-th * column of input. Make sure your program does something intelligent with * very long lines, and if there are no blanks or tabs before the * specified column. */ #include <stdio.h> #define MAXCOLUMN 10 #define TABSTOP 5 int expand(char line[], int i, int lim); void print(char line[], int lim); int fold(char line[], int lim); int shift(char line[], int lim); main() { int i, lim, c; char line[MAXCOLUMN]; i = 0; while ((c = getchar()) != EOF) { line[i] = c; if ('\t' == c) { i = expand(line, i, MAXCOLUMN); if (MAXCOLUMN == i) { print(line, i); i = 0; } } else if ('\n' == c) { print(line, i); i = 0; } else if (0 == (++i % MAXCOLUMN)) { i = fold(line, i); print(line, i); i = shift(line, i); } } return 0; } int fold(char line[], int lim) { int i; for (i = lim - 1; i > 0 && ' ' == line[i]; i--) ; if (line[i] != ' ') { return i + 1; } return MAXCOLUMN; } void print(char line[], int lim) { int i; for(i = 0; i < lim; i++) { putchar(line[i]); } putchar('\n'); } int shift(char line[], int lim) { int i; for (i = 0; i < MAXCOLUMN - lim; i++) { line[i] = line[lim + i]; } return MAXCOLUMN - lim; } int expand(char line[], int i, int lim) { line[i] = ' '; for (i++; (i % TABSTOP) != 0 && i < lim; i++) { line[i] = ' '; } return i; }
3.5
4
2024-11-18T18:35:09.045065+00:00
2016-01-07T22:42:40
051c8211209cea95a3eac01b902a26d0ad31d770
{ "blob_id": "051c8211209cea95a3eac01b902a26d0ad31d770", "branch_name": "refs/heads/master", "committer_date": "2016-01-07T22:42:40", "content_id": "c970b6fb082bcfb1edc1927c66db003d3b21eb16", "detected_licenses": [ "MIT" ], "directory_id": "381e70bd1d6af4c65cb6ea145984500ca21195d1", "extension": "h", "filename": "color_effects.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 45366930, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1572, "license": "MIT", "license_type": "permissive", "path": "/motorcycle/color_effects.h", "provenance": "stackv2-0009.json.gz:93070", "repo_name": "xdumaine/esplora-neopixels", "revision_date": "2016-01-07T22:42:40", "revision_id": "449984527ff399b0f13aadab2e8288edaf0a8eb8", "snapshot_id": "4be314b0d99f712a431204ed385ea3f2f70f4bff", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/xdumaine/esplora-neopixels/449984527ff399b0f13aadab2e8288edaf0a8eb8/motorcycle/color_effects.h", "visit_date": "2021-01-10T01:19:09.433023" }
stackv2
struct RGB { byte r; byte g; byte b; }; RGB KTM_ORANGE = { 255, 42, 0 }; RGB KTM_BLACK = { 0, 0, 0 }; RGB BLUE = { 0, 0, 255 }; // Input a value 0 to 255 to get a color value. // The colours are a transition r - g - b - back to r. uint32_t wheelColor(Adafruit_NeoPixel &strip, byte wheelPos) { wheelPos = 255 - wheelPos; if(wheelPos < 85) { return strip.Color(255 - wheelPos * 3, 0, wheelPos * 3); } if(wheelPos < 170) { wheelPos -= 85; return strip.Color(0, wheelPos * 3, 255 - wheelPos * 3); } wheelPos -= 170; return strip.Color(wheelPos * 3, 255 - wheelPos * 3, 0); } // Fill the dots one after the other with a color void colorWipe(Adafruit_NeoPixel &strip, RGB rgb, uint8_t wait) { for(uint16_t i=0; i < strip.numPixels(); i++) { strip.setPixelColor(i, rgb.r, rgb.g, rgb.b); strip.show(); if (getButtonsState() == mode) { return; } delay(wait); } } void colorSet(Adafruit_NeoPixel &strip, RGB rgb) { for(uint16_t i = 0; i < strip.numPixels(); i++) { strip.setPixelColor(i, rgb.r, rgb.g, rgb.b); } strip.show(); delay(10); } // Slightly different, this makes the rainbow equally distributed throughout void rainbowCycle(Adafruit_NeoPixel &strip, uint8_t wait) { uint16_t i, j; for(j = 0; j < 256*5; j++) { // 5 cycles of all colors on wheel if (getButtonsState() == mode) { return; } for(i = 0; i < strip.numPixels(); i++) { strip.setPixelColor(i, wheelColor(strip, ((i * 256 / strip.numPixels()) + j) & 255)); } strip.show(); delay(wait); } }
2.71875
3
2024-11-18T18:35:09.201364+00:00
2021-01-02T02:11:39
2a4e1ac1a7ab292cde8468e5df2b43bdf422670b
{ "blob_id": "2a4e1ac1a7ab292cde8468e5df2b43bdf422670b", "branch_name": "refs/heads/master", "committer_date": "2021-01-02T02:11:39", "content_id": "c54091b464428db0353819f31aa42b5a490db914", "detected_licenses": [ "MIT" ], "directory_id": "abf432d562312760cfd28a97c43b9e1f97ab64f4", "extension": "c", "filename": "20.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 154999333, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 441, "license": "MIT", "license_type": "permissive", "path": "/C/20.c", "provenance": "stackv2-0009.json.gz:93199", "repo_name": "MilenaCarecho/LogicaDeProgramacao", "revision_date": "2021-01-02T02:11:39", "revision_id": "d48ec002a788b2032845a0dd8e7e88f06e46ac17", "snapshot_id": "8e46dae6e74d21397df9878ad06ff2c2c4dce7d2", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/MilenaCarecho/LogicaDeProgramacao/d48ec002a788b2032845a0dd8e7e88f06e46ac17/C/20.c", "visit_date": "2023-02-10T05:31:51.486842" }
stackv2
/** Escreva um algoritmo para criar um programa de ajuda para vendedores. A partir de um valor total lido, mostre:  O total a pagar com desconto de 10%;  O valor de cada parcela, no parcelamento de 3 x sem juros;  A comissão do vendedor, no caso de a venda ser a vista (5% sobre o valor com desconto)  A comissão do vendedor, no caso de a venda ser parcelada (5% sobre o valor total) **/ #include <stdio.h> int main () { }
2.375
2
2024-11-18T18:35:09.299869+00:00
2023-08-27T19:14:02
4c43b319229735ce44c5366de5957af56015af6e
{ "blob_id": "4c43b319229735ce44c5366de5957af56015af6e", "branch_name": "refs/heads/master", "committer_date": "2023-08-27T19:14:02", "content_id": "55c9e08696c0f35fe6c168b1e537de9f5b57d95f", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "7c857119fe1505b1d80d6e62969661c06dc1a2f4", "extension": "h", "filename": "PlatformLogo.h", "fork_events_count": 770, "gha_created_at": "2019-09-02T08:22:14", "gha_event_created_at": "2023-09-03T12:41:33", "gha_language": "C", "gha_license_id": "BSD-2-Clause", "github_id": 205810121, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2287, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/MdeModulePkg/Include/Protocol/PlatformLogo.h", "provenance": "stackv2-0009.json.gz:93327", "repo_name": "CloverHackyColor/CloverBootloader", "revision_date": "2023-08-27T19:14:02", "revision_id": "2711170df4f60b2ae5aa20add3e00f35cf57b7e5", "snapshot_id": "7042ca7dd6b513d22be591a295e49071ae1482ee", "src_encoding": "UTF-8", "star_events_count": 4734, "url": "https://raw.githubusercontent.com/CloverHackyColor/CloverBootloader/2711170df4f60b2ae5aa20add3e00f35cf57b7e5/MdeModulePkg/Include/Protocol/PlatformLogo.h", "visit_date": "2023-08-30T22:14:34.590134" }
stackv2
/** @file The Platform Logo Protocol defines the interface to get the Platform logo image with the display attribute. Copyright (c) 2015 - 2018, Intel Corporation. All rights reserved.<BR> SPDX-License-Identifier: BSD-2-Clause-Patent **/ #ifndef __PLATFORM_LOGO_H__ #define __PLATFORM_LOGO_H__ #include <Protocol/HiiImage.h> // // GUID for EDKII Platform Logo Protocol // #define EDKII_PLATFORM_LOGO_PROTOCOL_GUID \ { 0x53cd299f, 0x2bc1, 0x40c0, { 0x8c, 0x07, 0x23, 0xf6, 0x4f, 0xdb, 0x30, 0xe0 } } typedef struct _EDKII_PLATFORM_LOGO_PROTOCOL EDKII_PLATFORM_LOGO_PROTOCOL; typedef enum { EdkiiPlatformLogoDisplayAttributeLeftTop, EdkiiPlatformLogoDisplayAttributeCenterTop, EdkiiPlatformLogoDisplayAttributeRightTop, EdkiiPlatformLogoDisplayAttributeCenterRight, EdkiiPlatformLogoDisplayAttributeRightBottom, EdkiiPlatformLogoDisplayAttributeCenterBottom, EdkiiPlatformLogoDisplayAttributeLeftBottom, EdkiiPlatformLogoDisplayAttributeCenterLeft, EdkiiPlatformLogoDisplayAttributeCenter } EDKII_PLATFORM_LOGO_DISPLAY_ATTRIBUTE; /** Load a platform logo image and return its data and attributes. @param This The pointer to this protocol instance. @param Instance The visible image instance is found. @param Image Points to the image. @param Attribute The display attributes of the image returned. @param OffsetX The X offset of the image regarding the Attribute. @param OffsetY The Y offset of the image regarding the Attribute. @retval EFI_SUCCESS The image was fetched successfully. @retval EFI_NOT_FOUND The specified image could not be found. **/ typedef EFI_STATUS (EFIAPI *EDKII_PLATFORM_LOGO_GET_IMAGE)( IN EDKII_PLATFORM_LOGO_PROTOCOL *This, IN OUT UINT32 *Instance, OUT EFI_IMAGE_INPUT *Image, OUT EDKII_PLATFORM_LOGO_DISPLAY_ATTRIBUTE *Attribute, OUT INTN *OffsetX, OUT INTN *OffsetY ); struct _EDKII_PLATFORM_LOGO_PROTOCOL { EDKII_PLATFORM_LOGO_GET_IMAGE GetImage; }; extern EFI_GUID gEdkiiPlatformLogoProtocolGuid; #endif
2.21875
2
2024-11-18T18:35:09.463942+00:00
2018-06-01T19:26:05
6f056674b3bda2d1d4173b4404b252dd4c374c4d
{ "blob_id": "6f056674b3bda2d1d4173b4404b252dd4c374c4d", "branch_name": "refs/heads/master", "committer_date": "2018-06-01T19:26:05", "content_id": "52b73b93d04609c61e61576316a5d77ede236213", "detected_licenses": [ "Apache-2.0" ], "directory_id": "f2bf1d6b060b33d8cd63ef37da50a2f41c1ec4af", "extension": "c", "filename": "test_queue.c", "fork_events_count": 0, "gha_created_at": "2019-02-02T05:45:41", "gha_event_created_at": "2019-02-02T05:45:41", "gha_language": null, "gha_license_id": "Apache-2.0", "github_id": 168799156, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2787, "license": "Apache-2.0", "license_type": "permissive", "path": "/tests/test_queue.c", "provenance": "stackv2-0009.json.gz:93455", "repo_name": "DalavanCloud/rebar-c", "revision_date": "2018-06-01T19:26:05", "revision_id": "f1f7bd2cc35a3b32c56bced7dd06c305191a182a", "snapshot_id": "f9508584c0534af1955bc3f5b6d701c531bd5b9d", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/DalavanCloud/rebar-c/f1f7bd2cc35a3b32c56bced7dd06c305191a182a/tests/test_queue.c", "visit_date": "2020-04-20T10:48:25.898121" }
stackv2
#include <stdlib.h> #include <string.h> #include "test_queue.h" #include "../src/queue.h" #include "../src/rebar-xxd.h" void create_queue(void) { queue_t *q1 = rebar_queue_init(); queue_t *q2 = rebar_queue_init(); CU_ASSERT (q1 != NULL); CU_ASSERT (q2 != NULL); CU_ASSERT (q2 != q1); rebar_queue_delete(q1, NULL); rebar_queue_delete(q2, free); } #define NUMBER_OF_ELEMENTS 8 #define SIZE_OF_DATA 32 void do_the_works(void) { int element; queue_t *q = rebar_queue_init(); for (element = 0; element < NUMBER_OF_ELEMENTS; element++) { char *data = (char *) malloc(sizeof(char) * SIZE_OF_DATA); sprintf(data, "Element %d in queue", element); printf("push(%s, q)\n", data); rebar_queue_push(data, q); } for (element = 0; element < NUMBER_OF_ELEMENTS; element++) { void *data = rebar_queue_pop (q); printf("pop() element %d: %s\n", element, (char *) data); free(data); } for (element = 0; element < NUMBER_OF_ELEMENTS; element++) { char *data = (char *) malloc(sizeof(char) * SIZE_OF_DATA); sprintf(data, "Element %d in queue", element); printf("push(%s, q)\n", data); rebar_queue_push(data, q); } rebar_queue_print(q, SIZE_OF_DATA); void *queue_data = rebar_queue_peek(q); char test_data[SIZE_OF_DATA]; element = 0; sprintf(test_data, "Element %d in queue", element); CU_ASSERT (0 == memcmp(test_data, queue_data, strlen(queue_data))); queue_data = rebar_queue_pop(q); CU_ASSERT(NULL != queue_data); element = 0; sprintf(test_data, "Element %d in queue", element); CU_ASSERT (0 == memcmp(test_data, queue_data, strlen(queue_data))); free(queue_data); for (element = 1; element < NUMBER_OF_ELEMENTS; element++) { queue_data = rebar_queue_pop(q); sprintf(test_data, "Element %d in queue", element); printf("Element being removed %s\n", test_data); CU_ASSERT (0 == memcmp(test_data, queue_data, strlen(queue_data))); free(queue_data); } rebar_queue_delete(q, NULL); } void delete_queue(void) { int element; queue_t *q = rebar_queue_init(); for (element = 0; element < NUMBER_OF_ELEMENTS; element++) { char *data = (char *) malloc(sizeof(char) * SIZE_OF_DATA); sprintf(data, "Element %d in queue", element); printf("push(%s, q)\n", data); rebar_queue_push(data, q); } CU_ASSERT(0 == rebar_queue_delete(q, free)); } void add_queue_tests(CU_pSuite *suite) { CU_add_test(*suite, "create_queue", create_queue); CU_add_test(*suite, "do_the_works", do_the_works); CU_add_test(*suite, "delete_queue", delete_queue); }
2.8125
3
2024-11-18T18:43:47.374926+00:00
2020-01-21T15:52:30
2d33a491e5eb7fde2f0f54fe184ec0b75e5a8049
{ "blob_id": "2d33a491e5eb7fde2f0f54fe184ec0b75e5a8049", "branch_name": "refs/heads/master", "committer_date": "2020-01-21T15:52:30", "content_id": "c1b8143217248d269bc653001322bcdbe57f2659", "detected_licenses": [ "MIT", "BSD-3-Clause", "ISC" ], "directory_id": "13e012007ba1a95ce3214b3214476450f5663654", "extension": "h", "filename": "saf_matrixConv.h", "fork_events_count": 0, "gha_created_at": "2020-01-23T21:42:15", "gha_event_created_at": "2020-01-23T21:42:16", "gha_language": null, "gha_license_id": null, "github_id": 235892278, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 6245, "license": "MIT,BSD-3-Clause,ISC", "license_type": "permissive", "path": "/framework/modules/saf_utilities/saf_matrixConv.h", "provenance": "stackv2-0009.json.gz:149927", "repo_name": "Shalwaban/Spatial_Audio_Framework", "revision_date": "2020-01-21T15:52:30", "revision_id": "2d38756c55bade4620aabe95d83fcb3d8eee125c", "snapshot_id": "86d94bda482d72415b49a03b93293498a2323161", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/Shalwaban/Spatial_Audio_Framework/2d38756c55bade4620aabe95d83fcb3d8eee125c/framework/modules/saf_utilities/saf_matrixConv.h", "visit_date": "2020-12-20T00:02:09.326208" }
stackv2
/* * Copyright 2019 Leo McCormack * * 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. */ /* * Filename: saf_matrixConv.h * -------------------------- * Matrix convolver functions mostly stolen from some Matlab scripts by * Archontis Politis ;-) * (with permission of course) * * Dependencies: * saf_fft * Author, date created: * Leo McCormack, 06.04.2019 */ #ifndef SAF_MATRIXCOLV_H_INCLUDED #define SAF_MATRIXCOLV_H_INCLUDED #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <math.h> /* Included: * Matrix Convolver * y = H * x; looped/summed over in/output channels, applied block-by-block * where * y: nOutputChannels x blockSize * x: nInputChannels x blockSize * H: nOutputChannels x nInputChannels x filterLength * * Multi Convolver * y = H * x; looped over channels, applied block-by-block * where * y: nChannels x blockSize * x: nChannels x blockSize * H: nChannels x filterLength */ /* ========================================================================== */ /* Matrix Convolver */ /* ========================================================================== */ /* * Function: saf_matrixConv_create * ------------------------------- * Creates an instance of matrixConv * This is a matrix convolver intended for block-by-block processing. * * Input Arguments: * phMC - & address of matrixConv handle * hopSize - hop size in samples. * H - time-domain filters; FLAT: nCHout x nCHin x length_h * length_h - length of the filters * nCHin - number of input channels * nCHout - number of output channels * usePartFLAG - 0: normal fft-based convolution, 1: fft-based partitioned * convolution */ void saf_matrixConv_create(/* Input Arguments */ void ** const phMC, int hopSize, float* H, int length_h, int nCHin, int nCHout, int usePartFLAG); /* * Function: saf_matrixConv_destroy * -------------------------------- * Destroys an instance of matrixConv * * Input Arguments: * phMC - & address of matrixConv handle */ void saf_matrixConv_destroy(/* Input Arguments */ void ** const phMC); /* * Function: saf_matrixConv_apply * ------------------------------ * Performs the matrix convolution. * Note: if the number of input+output channels, the filters, or the hopsize * change: simply destroy and re-create the matrixConv instance * * Input Arguments: * hMC - matrixConv handle * inputSigs - input signals; FLAT: nCHin x hopSize * Output Arguments: * outputSigs - output signals; FLAT: nCHout x hopSize */ void saf_matrixConv_apply(/* Input Arguments */ void * const hMC, float* inputSigs, /* Output Arguments */ float* outputSigs); /* ========================================================================== */ /* Multi-Channel Convolver */ /* ========================================================================== */ /* * Function: saf_multiConv_create * ------------------------------ * Creates an instance of multiConv * This is a multi-channel convolver intended for block-by-block processing. * Note: nCH can just be 1, in which case this is simply a single-channel * convolver. * * Input Arguments: * phMC - & address of multiConv handle * hopSize - hop size in samples. * H - time-domain filters; FLAT: nCH x length_h * length_h - length of the filters * nCH - number of filters & input/output channels * usePartFLAG - 0: normal fft-based convolution, 1: fft-based partitioned * convolution */ void saf_multiConv_create(/* Input Arguments */ void ** const phMC, int hopSize, float* H, int length_h, int nCH, int usePartFLAG); /* * Function: saf_multiConv_destroy * ------------------------------- * Destroys an instance of multiConv * * Input Arguments: * phMC - & address of multiConv handle */ void saf_multiConv_destroy(/*Input Arguments*/ void ** const phMC); /* * Function: saf_multiConv_apply * ----------------------------- * Performs the multi-channel convolution * * Input Arguments: * hMC - multiConv handle * inputSigs - input signals; FLAT: nCH x hopSize * Output Arguments: * outputSigs - output signals; FLAT: nCH x hopSize */ void saf_multiConv_apply(/* Input Arguments */ void * const hMC, float* inputSigs, /* Output Arguments */ float* outputSigs); #ifdef __cplusplus }/* extern "C" */ #endif /* __cplusplus */ #endif /* SAF_MATRIXCOLV_H_INCLUDED */
2.15625
2
2024-11-18T18:43:47.506824+00:00
2015-01-27T16:59:40
55d7da560bc7dd5195ee3eaa45d9abf452a33005
{ "blob_id": "55d7da560bc7dd5195ee3eaa45d9abf452a33005", "branch_name": "refs/heads/master", "committer_date": "2015-01-27T16:59:40", "content_id": "a50744f1e81ac1f05b75da09e2399abb269cd39c", "detected_licenses": [ "ICU" ], "directory_id": "0641d87fac176bab11c613e64050330246569e5c", "extension": "c", "filename": "uprops.c", "fork_events_count": 2, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 9308333, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 14586, "license": "ICU", "license_type": "permissive", "path": "/tags/release-2-2-d02/source/common/uprops.c", "provenance": "stackv2-0009.json.gz:150055", "repo_name": "svn2github/libicu_full", "revision_date": "2015-01-27T16:59:40", "revision_id": "f1246dcb7fec5a23ebd6d36ff3515ff0395aeb29", "snapshot_id": "ecf883cedfe024efa5aeda4c8527f227a9dbf100", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/svn2github/libicu_full/f1246dcb7fec5a23ebd6d36ff3515ff0395aeb29/tags/release-2-2-d02/source/common/uprops.c", "visit_date": "2021-01-01T17:00:58.555108" }
stackv2
/* ******************************************************************************* * * Copyright (C) 2002, International Business Machines * Corporation and others. All Rights Reserved. * ******************************************************************************* * file name: uprops.h * encoding: US-ASCII * tab size: 8 (not used) * indentation:4 * * created on: 2002feb24 * created by: Markus W. Scherer * * Implementations for mostly non-core Unicode character properties * stored in uprops.icu. */ #include "unicode/utypes.h" #include "unicode/uchar.h" #include "unicode/uscript.h" #include "cstring.h" #include "unormimp.h" #include "uprops.h" /* helper definitions ------------------------------------------------------- */ #define CGJ 0x034f #define ZWNJ 0x200C #define ZWJ 0x200D /** * Unicode property names and property value names are compared * "loosely". Property[Value]Aliases.txt say: * "With loose matching of property names, the case distinctions, whitespace, * and '_' are ignored." * * This function does just that, for ASCII (char *) name strings. * It is almost identical to ucnv_compareNames() but also ignores * ASCII White_Space characters (U+0009..U+000d). * * @internal */ U_CAPI int32_t U_EXPORT2 uprv_comparePropertyNames(const char *name1, const char *name2) { int32_t rc; unsigned char c1, c2; for(;;) { /* Ignore delimiters '-', '_', and ASCII White_Space */ while((c1=(unsigned char)*name1)=='-' || c1=='_' || c1==' ' || c1=='\t' || c1=='\n' || c1=='\v' || c1=='\f' || c1=='\r' ) { ++name1; } while((c2=(unsigned char)*name2)=='-' || c2=='_' || c2==' ' || c2=='\t' || c2=='\n' || c2=='\v' || c2=='\f' || c2=='\r' ) { ++name2; } /* If we reach the ends of both strings then they match */ if((c1|c2)==0) { return 0; } /* Case-insensitive comparison */ if(c1!=c2) { rc=(int32_t)(unsigned char)uprv_tolower(c1)-(int32_t)(unsigned char)uprv_tolower(c2); if(rc!=0) { return rc; } } ++name1; ++name2; } } /* API functions ------------------------------------------------------------ */ U_CAPI void U_EXPORT2 u_charAge(UChar32 c, UVersionInfo versionArray) { if(versionArray!=NULL) { uint32_t version=u_getUnicodeProperties(c, 0)>>UPROPS_AGE_SHIFT; versionArray[0]=(uint8_t)(version>>4); versionArray[1]=(uint8_t)(version&0xf); versionArray[2]=versionArray[3]=0; } } U_CAPI UScriptCode U_EXPORT2 uscript_getScript(UChar32 c, UErrorCode *pErrorCode) { if(pErrorCode==NULL || U_FAILURE(*pErrorCode)) { return USCRIPT_INVALID_CODE; } if((uint32_t)c>0x10ffff) { *pErrorCode=U_ILLEGAL_ARGUMENT_ERROR; return USCRIPT_INVALID_CODE; } return (UScriptCode)(u_getUnicodeProperties(c, 0)&UPROPS_SCRIPT_MASK); } U_CAPI UBlockCode U_EXPORT2 ublock_getCode(UChar32 c) { uint32_t b; if((uint32_t)c>0x10ffff) { return UBLOCK_INVALID_CODE; } b=(u_getUnicodeProperties(c, 0)&UPROPS_BLOCK_MASK)>>UPROPS_BLOCK_SHIFT; if(b==0) { return UBLOCK_INVALID_CODE; } else { return (UBlockCode)b; } } U_CAPI UBool U_EXPORT2 u_hasBinaryProperty(UChar32 c, UProperty which) { uint32_t props; /* c is range-checked in the functions that are called from here */ switch(which) { case UCHAR_ALPHABETIC: /* Lu+Ll+Lt+Lm+Lo+Nl+Other_Alphabetic */ return (FLAG(u_charType(c))&(_Lu|_Ll|_Lt|_Lm|_Lo|_Nl))!=0 || (u_getUnicodeProperties(c, 1)&FLAG(UPROPS_OTHER_ALPHABETIC))!=0; case UCHAR_ASCII_HEX_DIGIT: return (u_getUnicodeProperties(c, 1)&FLAG(UPROPS_ASCII_HEX_DIGIT))!=0; case UCHAR_BIDI_CONTROL: return (u_getUnicodeProperties(c, 1)&FLAG(UPROPS_BIDI_CONTROL))!=0; case UCHAR_BIDI_MIRRORED: return u_isMirrored(c); case UCHAR_DASH: return (u_getUnicodeProperties(c, 1)&FLAG(UPROPS_DASH))!=0; case UCHAR_DEFAULT_IGNORABLE_CODE_POINT: /* <2060..206F, FFF0..FFFB, E0000..E0FFF>+Other_Default_Ignorable_Code_Point+(Cf+Cc+Cs-White_Space) */ if( (0x2060<=c && c<=0x206f) || (0xfff0<=c && c<=0xfffb) || (0xe0000<=c && c<=0xe0fff) ) { return TRUE; } props=u_getUnicodeProperties(c, 1); return (props&FLAG(UPROPS_OTHER_DEFAULT_IGNORABLE_CODE_POINT))!=0 || ((props&FLAG(UPROPS_WHITE_SPACE))==0 && (FLAG(u_charType(c))&(_Cf|_Cc|_Cs))!=0); case UCHAR_DEPRECATED: return (u_getUnicodeProperties(c, 1)&FLAG(UPROPS_DEPRECATED))!=0; case UCHAR_DIACRITIC: return (u_getUnicodeProperties(c, 1)&FLAG(UPROPS_DIACRITIC))!=0; case UCHAR_EXTENDER: return (u_getUnicodeProperties(c, 1)&FLAG(UPROPS_EXTENDER))!=0; case UCHAR_FULL_COMPOSITION_EXCLUSION: return unorm_internalIsFullCompositionExclusion(c); case UCHAR_GRAPHEME_BASE: /* * [0..10FFFF]-Cc-Cf-Cs-Co-Cn-Zl-Zp-Grapheme_Link-Grapheme_Extend-CGJ == * [0..10FFFF]-Cc-Cf-Cs-Co-Cn-Zl-Zp-Grapheme_Link-(Me+Mn+Mc+Other_Grapheme_Extend)-CGJ == * [0..10FFFF]-Cc-Cf-Cs-Co-Cn-Zl-Zp-Me-Mn-Mc-Grapheme_Link-Other_Grapheme_Extend-CGJ * * u_charType(c out of range) returns Cn so we need not check for the range */ return c!=CGJ && (FLAG(u_charType(c))&(_Cc|_Cf|_Cs|_Co|_Cn|_Zl|_Zp|_Me|_Mn|_Mc))==0 && ((u_getUnicodeProperties(c, 1)& (FLAG(UPROPS_GRAPHEME_LINK)|FLAG(UPROPS_OTHER_GRAPHEME_EXTEND)))==0); case UCHAR_GRAPHEME_EXTEND: /* Me+Mn+Mc+Other_Grapheme_Extend-Grapheme_Link-CGJ */ if(c==CGJ) { return FALSE; /* fastest check first */ } props=u_getUnicodeProperties(c, 1); return (props&FLAG(UPROPS_GRAPHEME_LINK))==0 && ((props&FLAG(UPROPS_OTHER_GRAPHEME_EXTEND))!=0 || (FLAG(u_charType(c))&(_Me|_Mn|_Mc))!=0); case UCHAR_GRAPHEME_LINK: return (u_getUnicodeProperties(c, 1)&FLAG(UPROPS_GRAPHEME_LINK))!=0; case UCHAR_HEX_DIGIT: return (u_getUnicodeProperties(c, 1)&FLAG(UPROPS_HEX_DIGIT))!=0; case UCHAR_HYPHEN: return (u_getUnicodeProperties(c, 1)&FLAG(UPROPS_HYPHEN))!=0; case UCHAR_ID_CONTINUE: /* ID_Start+Mn+Mc+Nd+Pc == Lu+Ll+Lt+Lm+Lo+Nl+Mn+Mc+Nd+Pc */ return (FLAG(u_charType(c))&(_Lu|_Ll|_Lt|_Lm|_Lo|_Nl|_Mn|_Mc|_Nd|_Pc))!=0; case UCHAR_ID_START: /* Lu+Ll+Lt+Lm+Lo+Nl */ return (FLAG(u_charType(c))&(_Lu|_Ll|_Lt|_Lm|_Lo|_Nl))!=0; case UCHAR_IDEOGRAPHIC: return (u_getUnicodeProperties(c, 1)&FLAG(UPROPS_IDEOGRAPHIC))!=0; case UCHAR_IDS_BINARY_OPERATOR: return (u_getUnicodeProperties(c, 1)&FLAG(UPROPS_IDS_BINARY_OPERATOR))!=0; case UCHAR_IDS_TRINARY_OPERATOR: return (u_getUnicodeProperties(c, 1)&FLAG(UPROPS_IDS_TRINARY_OPERATOR))!=0; case UCHAR_JOIN_CONTROL: return (u_getUnicodeProperties(c, 1)&FLAG(UPROPS_JOIN_CONTROL))!=0; case UCHAR_LOGICAL_ORDER_EXCEPTION: return (u_getUnicodeProperties(c, 1)&FLAG(UPROPS_LOGICAL_ORDER_EXCEPTION))!=0; case UCHAR_LOWERCASE: /* Ll+Other_Lowercase */ return u_charType(c)==U_LOWERCASE_LETTER || (u_getUnicodeProperties(c, 1)&FLAG(UPROPS_OTHER_LOWERCASE))!=0; case UCHAR_MATH: /* Sm+Other_Math */ return u_charType(c)==U_MATH_SYMBOL || (u_getUnicodeProperties(c, 1)&FLAG(UPROPS_OTHER_MATH))!=0; case UCHAR_NONCHARACTER_CODE_POINT: return (u_getUnicodeProperties(c, 1)&FLAG(UPROPS_NONCHARACTER_CODE_POINT))!=0; case UCHAR_QUOTATION_MARK: return (u_getUnicodeProperties(c, 1)&FLAG(UPROPS_QUOTATION_MARK))!=0; case UCHAR_RADICAL: return (u_getUnicodeProperties(c, 1)&FLAG(UPROPS_RADICAL))!=0; case UCHAR_SOFT_DOTTED: return (u_getUnicodeProperties(c, 1)&FLAG(UPROPS_SOFT_DOTTED))!=0; case UCHAR_TERMINAL_PUNCTUATION: return (u_getUnicodeProperties(c, 1)&FLAG(UPROPS_TERMINAL_PUNCTUATION))!=0; case UCHAR_UNIFIED_IDEOGRAPH: return (u_getUnicodeProperties(c, 1)&FLAG(UPROPS_UNIFIED_IDEOGRAPH))!=0; case UCHAR_UPPERCASE: /* Lu+Other_Uppercase */ return u_charType(c)==U_UPPERCASE_LETTER || (u_getUnicodeProperties(c, 1)&FLAG(UPROPS_OTHER_UPPERCASE))!=0; case UCHAR_WHITE_SPACE: return (u_getUnicodeProperties(c, 1)&FLAG(UPROPS_WHITE_SPACE))!=0; case UCHAR_XID_CONTINUE: return (u_getUnicodeProperties(c, 1)&FLAG(UPROPS_XID_CONTINUE))!=0; case UCHAR_XID_START: return (u_getUnicodeProperties(c, 1)&FLAG(UPROPS_XID_START))!=0; default: /* not a known binary property */ return FALSE; }; } U_CAPI UBool U_EXPORT2 u_isUAlphabetic(UChar32 c) { return u_hasBinaryProperty(c, UCHAR_ALPHABETIC); } U_CAPI UBool U_EXPORT2 u_isULowercase(UChar32 c) { return u_hasBinaryProperty(c, UCHAR_LOWERCASE); } U_CAPI UBool U_EXPORT2 u_isUUppercase(UChar32 c) { return u_hasBinaryProperty(c, UCHAR_UPPERCASE); } U_CAPI UBool U_EXPORT2 u_isUWhiteSpace(UChar32 c) { return u_hasBinaryProperty(c, UCHAR_WHITE_SPACE); } U_CAPI UBool U_EXPORT2 uprv_isRuleWhiteSpace(UChar32 c) { /* "white space" in the sense of ICU rule parsers: Cf+White_Space */ return u_charType(c)==U_FORMAT_CHAR || u_hasBinaryProperty(c, UCHAR_WHITE_SPACE); } U_CAPI int32_t U_EXPORT2 u_getIntPropertyValue(UChar32 c, UProperty which) { UErrorCode errorCode; int32_t i; int8_t type; if(which<UCHAR_BINARY_START) { return 0; /* undefined */ } else if(which<UCHAR_BINARY_LIMIT) { return (int32_t)u_hasBinaryProperty(c, which); } else if(which<UCHAR_INT_START) { return 0; /* undefined */ } else if(which<UCHAR_INT_LIMIT) { switch(which) { case UCHAR_BIDI_CLASS: return (int32_t)u_charDirection(c); case UCHAR_BLOCK: return (int32_t)ublock_getCode(c); case UCHAR_CANONICAL_COMBINING_CLASS: return u_getCombiningClass(c); case UCHAR_DECOMPOSITION_TYPE: return (int32_t)(u_getUnicodeProperties(c, 2)&UPROPS_DT_MASK); case UCHAR_EAST_ASIAN_WIDTH: return (int32_t)(u_getUnicodeProperties(c, 0)&UPROPS_EA_MASK)>>UPROPS_EA_SHIFT; case UCHAR_GENERAL_CATEGORY: return (int32_t)u_charType(c); case UCHAR_JOINING_GROUP: return (int32_t)(u_getUnicodeProperties(c, 2)&UPROPS_JG_MASK)>>UPROPS_JG_SHIFT; case UCHAR_JOINING_TYPE: /* * ArabicShaping.txt: * Note: Characters of joining type T and most characters of * joining type U are not explicitly listed in this file. * * Characters of joining type T can [be] derived by the following formula: * T = Mn + Cf - ZWNJ - ZWJ */ i=(int32_t)(u_getUnicodeProperties(c, 2)&UPROPS_JT_MASK)>>UPROPS_JT_SHIFT; if(i==0 && c!=ZWNJ && c!=ZWJ && (FLAG(u_charType(c))&(_Mn|_Cf))!=0) { i=(int32_t)U_JT_TRANSPARENT; } return i; case UCHAR_LINE_BREAK: /* * LineBreak.txt: * - Assigned characters that are not listed explicitly are given the value * "AL". * - Unassigned characters are given the value "XX". * ... * E000..F8FF;XX # <Private Use, First>..<Private Use, Last> * F0000..FFFFD;XX # <Plane 15 Private Use, First>..<Plane 15 Private Use, Last> * 100000..10FFFD;XX # <Plane 16 Private Use, First>..<Plane 16 Private Use, Last> */ i=(int32_t)(u_getUnicodeProperties(c, 0)&UPROPS_LB_MASK)>>UPROPS_LB_SHIFT; if(i==0 && (type=u_charType(c))!=0 && type!=(int8_t)U_PRIVATE_USE_CHAR) { i=(int32_t)U_LB_ALPHABETIC; } return i; case UCHAR_NUMERIC_TYPE: return (int32_t)GET_NUMERIC_TYPE(u_getUnicodeProperties(c, -1)); case UCHAR_SCRIPT: errorCode=U_ZERO_ERROR; return (int32_t)uscript_getScript(c, &errorCode); default: return 0; /* undefined */ } } else { return 0; /* undefined */ } } U_CAPI int32_t U_EXPORT2 u_getIntPropertyMinValue(UProperty which) { switch(which) { case UCHAR_BLOCK: return UBLOCK_INVALID_CODE; case UCHAR_SCRIPT: return USCRIPT_INVALID_CODE; default: return 0; /* undefined; and: all other properties have a minimum value of 0 */ } } U_CAPI int32_t U_EXPORT2 u_getIntPropertyMaxValue(UProperty which) { int32_t max; if(which<UCHAR_BINARY_START) { return 0; /* undefined */ } else if(which<UCHAR_BINARY_LIMIT) { return 1; /* maximum TRUE for all binary properties */ } else if(which<UCHAR_INT_START) { return 0; /* undefined */ } else if(which<UCHAR_INT_LIMIT) { switch(which) { case UCHAR_BIDI_CLASS: return (int32_t)U_CHAR_DIRECTION_COUNT-1; case UCHAR_BLOCK: max=(uprv_getMaxValues()&UPROPS_BLOCK_MASK)>>UPROPS_BLOCK_SHIFT; if(max==0) { max=(int32_t)UBLOCK_COUNT-1; } return max; case UCHAR_CANONICAL_COMBINING_CLASS: return 0xff; /* TODO do we need to be more precise, getting the actual maximum? */ case UCHAR_DECOMPOSITION_TYPE: return (int32_t)U_DT_COUNT-1; case UCHAR_EAST_ASIAN_WIDTH: return (int32_t)U_EA_COUNT-1; case UCHAR_GENERAL_CATEGORY: return (int32_t)U_CHAR_CATEGORY_COUNT-1; case UCHAR_JOINING_GROUP: return (int32_t)U_JG_COUNT-1; case UCHAR_JOINING_TYPE: return (int32_t)U_JT_COUNT-1; case UCHAR_LINE_BREAK: return (int32_t)U_LB_COUNT-1; case UCHAR_NUMERIC_TYPE: return (int32_t)U_NT_COUNT-1; case UCHAR_SCRIPT: max=uprv_getMaxValues()&UPROPS_SCRIPT_MASK; if(max==0) { max=(int32_t)USCRIPT_CODE_LIMIT-1; } return max; default: return 0; /* undefined */ } } else { return 0; /* undefined */ } }
2.125
2
2024-11-18T18:45:17.645609+00:00
2022-10-12T21:35:58
225d3af63b4e5150a447593735446a1c8bffb6e5
{ "blob_id": "225d3af63b4e5150a447593735446a1c8bffb6e5", "branch_name": "refs/heads/master", "committer_date": "2022-10-12T21:35:58", "content_id": "65e753bbd1f3b5fc83ecc8a021cedc45e2cad0c9", "detected_licenses": [ "Apache-2.0" ], "directory_id": "180159015288443579baa49f119132892431edd7", "extension": "c", "filename": "vectorAdd.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 150864925, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2818, "license": "Apache-2.0", "license_type": "permissive", "path": "/4th-VectorAdd-Pthread/vectorAdd.c", "provenance": "stackv2-0009.json.gz:150567", "repo_name": "amirsojoodi/GPGPU-Course", "revision_date": "2022-10-12T21:35:58", "revision_id": "94bcc35b444129d571356b28601fcb96a2e7d7b1", "snapshot_id": "ee9defe0fc1129f52999efb38f2cf69eb0be9338", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/amirsojoodi/GPGPU-Course/94bcc35b444129d571356b28601fcb96a2e7d7b1/4th-VectorAdd-Pthread/vectorAdd.c", "visit_date": "2022-10-13T16:32:06.465828" }
stackv2
#include <math.h> #include <pthread.h> #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #include <time.h> #define min(a, b) ((a) < (b) ? a : b) typedef struct argument { int *a; int *b; int *c; int tid; int size; int num_thread; } argument; void validate(int *a, int *b, int length) { for (int i = 0; i < length; ++i) { if (a[i] != b[i]) { printf("Different value detected at position: %d," "expected %d but get %d\n", i, a[i], b[i]); break; } } } void *naive_parallel_vector_add(void *arg) { argument targ = *(argument *)arg; int *a = targ.a, *b = targ.b, *c = targ.c; int si = (targ.size / targ.num_thread) * targ.tid; int ei = min(si + targ.size / targ.num_thread, targ.size); for (int i = si; i < ei; i++) { c[i] = a[i] * b[i]; c[i] += (int)cos(a[i] + b[i]); } pthread_exit(NULL); } void sequential_naive_vectorAdd(int *a, int *b, int *c, int size) { for (int i = 0; i < size; i++) { c[i] = a[i] * b[i]; c[i] += (int)cos(a[i] + b[i]); } } // vectorAddParallel Input_size thread int main(int argc, char *argv[]) { struct timeval start, end; int *a, *b, *c, *d; time_t t; if (argc != 3) { printf("Correct way to execute this program is:\n"); printf("./vectorAdd arraySize NumberOfThreads.\n"); return 1; } int size = atoi(argv[1]); int num_thread = atoi(argv[2]); pthread_t threads[num_thread]; argument arguments[num_thread]; a = (int *)malloc(sizeof(int) * size); b = (int *)malloc(sizeof(int) * size); c = (int *)malloc(sizeof(int) * size); d = (int *)malloc(sizeof(int) * size); srand((unsigned)time(&t)); for (int i = 0; i < size; i++) { a[i] = rand() % 100; b[i] = rand() % 100; c[i] = 0; d[i] = 0; } gettimeofday(&start, NULL); sequential_naive_vectorAdd(a, b, c, size); gettimeofday(&end, NULL); double diff = (end.tv_sec - start.tv_sec) * 1000000.0 + (end.tv_usec - start.tv_usec); printf("Naive VectorAdd time calculation duration: %.4fms\n", diff / 1000); gettimeofday(&start, NULL); for (int i = 0; i < num_thread; i++) { arguments[i].a = a; arguments[i].b = b; arguments[i].c = d; arguments[i].tid = i; arguments[i].size = size; arguments[i].num_thread = num_thread; pthread_create(&threads[i], 0, naive_parallel_vector_add, (void *)&arguments[i]); } int status; for (int i = 0; i < num_thread; ++i) { pthread_join(threads[i], (void *)&status); } gettimeofday(&end, NULL); diff = (end.tv_sec - start.tv_sec) * 1000000.0 + (end.tv_usec - start.tv_usec); printf("Parallel VectorAdd time calculation duration: %.4fms\n", diff / 1000); validate(c, d, size); free(a); free(b); free(c); free(d); return 0; }
3.03125
3
2024-11-18T18:45:17.801937+00:00
2021-10-27T13:59:57
4e40fceeb108a65b0dda9b3f60a6039c1a2249c0
{ "blob_id": "4e40fceeb108a65b0dda9b3f60a6039c1a2249c0", "branch_name": "refs/heads/master", "committer_date": "2021-10-27T13:59:57", "content_id": "532e202b38e3d8599f9a80ff4a35cb493ce08348", "detected_licenses": [ "MIT" ], "directory_id": "5f7d9303fbf0bd1bfa163456d12c452c79cf5ea4", "extension": "c", "filename": "led.c", "fork_events_count": 0, "gha_created_at": "2018-08-14T02:46:01", "gha_event_created_at": "2018-08-14T02:46:02", "gha_language": null, "gha_license_id": "MIT", "github_id": 144659737, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3290, "license": "MIT", "license_type": "permissive", "path": "/Documentation/CodeToBePorted/HardwareDrivers/top/LED/led.c", "provenance": "stackv2-0009.json.gz:150825", "repo_name": "fanzcsoft/T3000_CrossPlatform", "revision_date": "2021-10-27T13:59:57", "revision_id": "22d2657f70db134b104499c40ee79d077905ca26", "snapshot_id": "976d9190bd48fda4b00aeb18e344c9af2e0899f3", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/fanzcsoft/T3000_CrossPlatform/22d2657f70db134b104499c40ee79d077905ca26/Documentation/CodeToBePorted/HardwareDrivers/top/LED/led.c", "visit_date": "2023-08-09T03:40:35.782890" }
stackv2
#include "led.h" #include "spi.h" #define MAX_LEVEL 6 u8 LED_status[67]; u16 LED_Level[5][MAX_LEVEL]; u8 level; void LED_Init(void) { u8 i,j; GPIO_InitTypeDef GPIO_InitStructure; #ifdef BB RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_GPIOD | RCC_APB2Periph_GPIOE | RCC_APB2Periph_GPIOF | RCC_APB2Periph_GPIOG, ENABLE); GPIO_InitStructure.GPIO_Pin = GPIO_Pin_All; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_Init(GPIOE, &GPIO_InitStructure); GPIO_SetBits(GPIOE, GPIO_InitStructure.GPIO_Pin); GPIO_InitStructure.GPIO_Pin = GPIO_Pin_All; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_Init(GPIOF, &GPIO_InitStructure); GPIO_SetBits(GPIOF, GPIO_InitStructure.GPIO_Pin); GPIO_InitStructure.GPIO_Pin = GPIO_Pin_All; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_Init(GPIOG, &GPIO_InitStructure); GPIO_SetBits(GPIOG, GPIO_InitStructure.GPIO_Pin); GPIO_InitStructure.GPIO_Pin = GPIO_Pin_All; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_Init(GPIOD, &GPIO_InitStructure); GPIO_SetBits(GPIOD, GPIO_InitStructure.GPIO_Pin); GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0 | GPIO_Pin_1 | GPIO_Pin_2 | GPIO_Pin_15; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_Init(GPIOA, &GPIO_InitStructure); GPIO_SetBits(GPIOA, GPIO_Pin_0 | GPIO_Pin_1 | GPIO_Pin_2); GPIO_SetBits(GPIOA, GPIO_Pin_15); // DONT RESET ASIX #endif #ifdef TB RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOD | RCC_APB2Periph_GPIOE, ENABLE); GPIO_InitStructure.GPIO_Pin = GPIO_Pin_All; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_Init(GPIOE, &GPIO_InitStructure); GPIO_SetBits(GPIOE, GPIO_InitStructure.GPIO_Pin); GPIO_InitStructure.GPIO_Pin = GPIO_Pin_All; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_Init(GPIOD, &GPIO_InitStructure); GPIO_SetBits(GPIOD, GPIO_InitStructure.GPIO_Pin); #endif for(j = 0;j < 67;j++) LED_status[j] = 0; for(i = 0;i < 5;i++) for(j = 0;j < MAX_LEVEL;j++) LED_Level[i][j] = 0; } void Count_LED_Buffer(void) { u8 i,j; for(i = 0;i < MAX_LEVEL;i++) { for(j = 0;j < 67;j++) { if(LED_status[j] <= i) { LED_Level[j / 16][i] |= (0x01 << (j % 16)); } else { LED_Level[j / 16][i] &= ~(0x01 << (j % 16)); } } } } extern u8 Mini_Type; // 1ms void Refresh_LED(void) { #ifdef BB GPIO_Write(GPIOE,LED_Level[0][level]); GPIO_Write(GPIOF,LED_Level[1][level]); GPIO_Write(GPIOG,LED_Level[2][level]); GPIO_Write(GPIOD,LED_Level[3][level]); GPIO_WriteBit(GPIOA,GPIO_Pin_0,LED_Level[4][level] & 0x01); GPIO_WriteBit(GPIOA,GPIO_Pin_1,LED_Level[4][level] & 0x02); GPIO_WriteBit(GPIOA,GPIO_Pin_2,LED_Level[4][level] & 0x04); #endif #ifdef TB GPIO_Write(GPIOD,LED_Level[0][level]); LED_Level[1][level] &= 0xF3FF; LED_Level[1][level] |= 0xf000; GPIO_Write(GPIOE,LED_Level[1][level]); #endif if(level < 5) // 6 level { level++; } else level = 0; }
2.171875
2
2024-11-18T19:19:58.536143+00:00
2021-07-05T13:49:41
d96b40e21933c8e2f61856ef86148edd7867e457
{ "blob_id": "d96b40e21933c8e2f61856ef86148edd7867e457", "branch_name": "refs/heads/main", "committer_date": "2021-07-05T13:49:41", "content_id": "ee613dd386162eb4e08fdb9b50c26445a4f80492", "detected_licenses": [ "MIT" ], "directory_id": "a630d757ff9a609ce507aefc0f40b2a9597e1528", "extension": "c", "filename": "extend.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4436, "license": "MIT", "license_type": "permissive", "path": "/lily/test/extend.c", "provenance": "stackv2-0010.json.gz:24609", "repo_name": "VB6Hobbyst7/all-the-compilers", "revision_date": "2021-07-05T13:49:41", "revision_id": "7f834984f71054806bfec8604e02e86b99c0f831", "snapshot_id": "bd1910f2aaab23c12d798b4104eb5cd8295e7514", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/VB6Hobbyst7/all-the-compilers/7f834984f71054806bfec8604e02e86b99c0f831/lily/test/extend.c", "visit_date": "2023-06-11T00:17:28.368709" }
stackv2
/** library extend This provides extension functions to the testing suite. */ #include "lily.h" /** Begin autogen section. **/ const char *lily_extend_info_table[] = { "\0\0" ,"F\0render_string\0(String,String): Result[String,Boolean]" ,"F\0parse_string\0(String,String): Result[String,Boolean]" ,"F\0parse_expr\0(String,String): Result[String,String]" ,"F\0parse_rewind\0(String,String,String): String" ,"Z" }; void lily_extend__render_string(lily_state *); void lily_extend__parse_string(lily_state *); void lily_extend__parse_expr(lily_state *); void lily_extend__parse_rewind(lily_state *); lily_call_entry_func lily_extend_call_table[] = { NULL, lily_extend__render_string, lily_extend__parse_string, lily_extend__parse_expr, lily_extend__parse_rewind, }; /** End autogen section. **/ void noop_render(const char *to_render, void *data) { (void)data; (void)to_render; } static void run_interp(lily_state *s, int parse) { const char *context = lily_arg_string_raw(s, 0); const char *data = lily_arg_string_raw(s, 1); lily_config config; lily_config_init(&config); config.render_func = noop_render; lily_state *subinterp = lily_new_state(&config); lily_container_val *con; int result; if (parse) result = lily_parse_string(subinterp, context, data); else result = lily_render_string(subinterp, context, data); if (result == 0) { con = lily_push_failure(s); lily_push_string(s, lily_error_message(subinterp)); } else { con = lily_push_success(s); lily_push_boolean(s, 1); } lily_free_state(subinterp); lily_con_set_from_stack(s, con, 0); lily_return_top(s); } /** define render_string(context: String, to_interpret: String): Result[String, Boolean] This function processes `to_interpret` as a `String` containing template tags with `context` used as the filename. */ void lily_extend__render_string(lily_state *s) { run_interp(s, 0); } /** define parse_string(context: String, to_interpret: String): Result[String, Boolean] This function processes `to_interpret` as a `String` containing code with `context` used as the filename. */ void lily_extend__parse_string(lily_state *s) { run_interp(s, 1); } /** define parse_expr(context: String, to_interpret: String): Result[String, String] This function processes `to_interpret` as a single expression. The output is either an interpreter error or the result of interpolating the expression. */ void lily_extend__parse_expr(lily_state *s) { const char *context = lily_arg_string_raw(s, 0); char *data = (char *)lily_arg_string_raw(s, 1); lily_config config; lily_config_init(&config); config.render_func = noop_render; lily_state *subinterp = lily_new_state(&config); lily_container_val *con; const char *output; int result = lily_parse_expr(subinterp, context, data, &output); if (result == 0) { con = lily_push_failure(s); lily_push_string(s, lily_error_message(subinterp)); } else { con = lily_push_success(s); lily_push_string(s, output); } lily_free_state(subinterp); lily_con_set_from_stack(s, con, 0); lily_return_top(s); } /** define parse_rewind(context: String, prelude: String, to_interpret: String): String This function processes `prelude` once, then `to_interpret` twice. This checks if the error message from `to_interpret` is the same for each pass. */ void lily_extend__parse_rewind(lily_state *s) { const char *context = lily_arg_string_raw(s, 0); char *header = (char *)lily_arg_string_raw(s, 1); char *data = (char *)lily_arg_string_raw(s, 2); lily_msgbuf *msgbuf = lily_msgbuf_get(s); lily_config config; lily_config_init(&config); config.render_func = noop_render; lily_state *subinterp = lily_new_state(&config); lily_parse_string(subinterp, context, header); lily_parse_string(subinterp, context, data); lily_mb_add(msgbuf, lily_error_message(subinterp)); lily_parse_string(subinterp, context, data); lily_mb_add(msgbuf, lily_error_message(subinterp)); /* The prelude shouldn't fail, and the two passes both should. Return the output of both parses in case they fail for different reasons. */ lily_free_state(subinterp); lily_push_string(s, lily_mb_raw(msgbuf)); lily_return_top(s); }
2.671875
3
2024-11-18T19:19:58.646508+00:00
2020-12-12T22:05:04
aba915cfafa2959cb18032d8cd7682d8bb8c40a0
{ "blob_id": "aba915cfafa2959cb18032d8cd7682d8bb8c40a0", "branch_name": "refs/heads/master", "committer_date": "2020-12-12T22:05:04", "content_id": "cb0937c1d48b7fc3e53c894985b6392cdae804c2", "detected_licenses": [ "MIT" ], "directory_id": "d7ded8476b00fa1a68aaeb8ebefcd7a7d83f8053", "extension": "h", "filename": "server.h", "fork_events_count": 4, "gha_created_at": "2020-05-06T02:02:28", "gha_event_created_at": "2020-12-05T18:20:04", "gha_language": "C", "gha_license_id": "MIT", "github_id": 261628063, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1242, "license": "MIT", "license_type": "permissive", "path": "/{{cookiecutter.project_name}}/src/server.h", "provenance": "stackv2-0010.json.gz:24737", "repo_name": "BrianPugh/cookiecutter-esp32-webserver", "revision_date": "2020-12-12T22:05:04", "revision_id": "e4b60265864e25a4618183171c897de01e385771", "snapshot_id": "639b00d988cc32220b0fccad6ac756ea09cfb7d2", "src_encoding": "UTF-8", "star_events_count": 14, "url": "https://raw.githubusercontent.com/BrianPugh/cookiecutter-esp32-webserver/e4b60265864e25a4618183171c897de01e385771/{{cookiecutter.project_name}}/src/server.h", "visit_date": "2023-02-08T02:51:59.166940" }
stackv2
#ifndef PROJECT_SERVER_H__ #define PROJECT_SERVER_H__ #include "cJSON.h" #include "esp_err.h" #include "esp_http_server.h" #include "esp_log.h" #include "esp_system.h" #include "esp_vfs.h" #include "fcntl.h" #include "string.h" #define CONFIG_SERVER_SCRATCH_BUFSIZE (10240) typedef struct server_ctx { char base_path[ESP_VFS_PATH_MAX + 1]; char scratch[CONFIG_SERVER_SCRATCH_BUFSIZE]; } server_ctx_t; extern server_ctx_t *server_ctx; /*** * @brief Initialize and start the server * * Requires a wifi connection to be already established. * * @param[in] base_path Base path to a mounted filesystem to be available * in the server context. */ esp_err_t server_init(const char *base_path); /**** * @brief Register a handler for a route * @param[in] route the route e.g. "/api/v1/test" * @param[in] method like HTTP_GET, HTTP_POST, HTTP_DELETE, HTTP_PUT * @param[in] handler Callback to handle requests */ esp_err_t server_register(const char *route, httpd_method_t method, esp_err_t (*handler)(httpd_req_t *r)); /***** * @brief Gets the hostname from NVS. Sets NVS to default config value if not * found. * * @return Hostname. Must be freed by caller. NULL on error. */ char *get_hostname(); #endif
2.046875
2
2024-11-18T19:19:58.815884+00:00
2019-10-05T10:08:29
8d633a8c482db0fcb84c4edc3dde02691395f281
{ "blob_id": "8d633a8c482db0fcb84c4edc3dde02691395f281", "branch_name": "refs/heads/master", "committer_date": "2019-10-05T10:08:29", "content_id": "7894a26c23224e5b6ecf7b253a955f1dd95a6d33", "detected_licenses": [ "MIT" ], "directory_id": "c5d313b0be54baef0b40e72c427665fc3a05f5d1", "extension": "h", "filename": "score_board.h", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 212978567, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1134, "license": "MIT", "license_type": "permissive", "path": "/ex_06/score_board.h", "provenance": "stackv2-0010.json.gz:24993", "repo_name": "quan-dang/Artificial-Intelligence-Undergraduate-UoA", "revision_date": "2019-10-05T10:08:29", "revision_id": "b99416b5312bfd4c1f9b1f649c7122a6dfbeb173", "snapshot_id": "7444aa83c5e5aeae8ca11a4e1ed9d5cae8e409f7", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/quan-dang/Artificial-Intelligence-Undergraduate-UoA/b99416b5312bfd4c1f9b1f649c7122a6dfbeb173/ex_06/score_board.h", "visit_date": "2020-08-06T12:41:51.350627" }
stackv2
/** * @file score_board.h * @date 2016/10/21 * @author Yuta Kobiyama ([email protected]) * @brief score board object header. * @details * Artificial Intelligence, 6th Exercise\n * Copyright (C) 2016 System Intelligence Laboratory All Rights Reserved. */ #ifndef SCORE_BOARD_H #define SCORE_BOARD_H #include <stdbool.h> #include <stddef.h> #include "object.h" enum { MAX_COURSE_NUM = 8, MAX_STUDENT_NUM = 32, }; typedef bool (*FuncAddScore)(void*, char const*, double const*); typedef double (*FuncGetStudentAverage)(void const*, char const*); typedef size_t (*FuncGetStudentRank)(void const*, char const*); struct score_board { Object super; size_t course_num; size_t student_num; char student_names[MAX_STUDENT_NUM][MAX_STR_LEN]; double scores[MAX_STUDENT_NUM][MAX_COURSE_NUM]; double ranks[MAX_COURSE_NUM]; FuncGetName get_name; FuncAddScore add_score; FuncGetStudentAverage get_student_average; FuncGetStudentRank get_student_rank; }; typedef struct score_board ScoreBoard; extern ScoreBoard* construct_score_board(ScoreBoard*, char const*, size_t); #endif
2.171875
2
2024-11-18T19:19:58.866402+00:00
2021-04-16T16:42:02
f239c80926563e42f6a4371a3058a58b16665ea4
{ "blob_id": "f239c80926563e42f6a4371a3058a58b16665ea4", "branch_name": "refs/heads/main", "committer_date": "2021-04-16T16:42:02", "content_id": "519b072aa2e17c0c096c6d06fd101e55a6f04222", "detected_licenses": [ "BSL-1.0" ], "directory_id": "63f12a04bcf12a84a4834e92767a2bf3410021d7", "extension": "c", "filename": "main_rec_queue.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 358655061, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1407, "license": "BSL-1.0", "license_type": "permissive", "path": "/cli/main_rec_queue.c", "provenance": "stackv2-0010.json.gz:25121", "repo_name": "devxiaoyi/bocom-ipc", "revision_date": "2021-04-16T16:42:02", "revision_id": "f9298bafbfeb219b5dba40b65ab51ee7964637c4", "snapshot_id": "bf0b31c6d69568868679dc2707a65ddb26416578", "src_encoding": "UTF-8", "star_events_count": 3, "url": "https://raw.githubusercontent.com/devxiaoyi/bocom-ipc/f9298bafbfeb219b5dba40b65ab51ee7964637c4/cli/main_rec_queue.c", "visit_date": "2023-04-13T15:16:37.966302" }
stackv2
#include "bocom_ipc.h" #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <string.h> typedef struct { int a; char tmpMsg[30]; int b; } st_abc; int main() { Context queCtx = BOCOM_JoinQueue("MyVideoChannel"); if(NULL == queCtx) { printf("BOCOM_JoinChannel failed !\n"); return -1; } printf("BOCOM_JoinChannel success !\n"); unsigned int recLen = 0; //received data length #if 1 int i = 0; void *tmpMsg = malloc(100); if (tmpMsg == NULL) { printf("malloc is NULL\n"); return -1; } int reti = 0; while (1) { memset(tmpMsg, 0, 100); reti = BOCOM_RetrieveQueue(queCtx, tmpMsg, &recLen); printf("main rec IFrameBuff rec:%s len:%d ret:%d \n",tmpMsg,recLen,reti); usleep(100*1000); } #else int dataLen = 3 * 512 * 1024; void *tmpMsg = malloc(dataLen); if (tmpMsg == NULL) { printf("malloc is NULL\n"); return -1; } memset(tmpMsg, 0, dataLen); ErrorCode reti = BOCOM_RetrieveQueue(queCtx, tmpMsg, &recLen); printf("main rec IFrameBuff rec:%s ret:%d \n", tmpMsg, reti); FILE *fp = fopen("../test/1M-img_cp.png", "w+"); if (fp == NULL) { printf("fopen is NULL\n"); return -1; } fwrite(tmpMsg, 1, recLen, fp); fclose(fp); free(tmpMsg); #endif return 0; }
2.6875
3
2024-11-18T19:20:42.074041+00:00
2021-07-01T11:11:24
1a5f73b98edc98a16b64864e5c98ec4aa0a2a8c7
{ "blob_id": "1a5f73b98edc98a16b64864e5c98ec4aa0a2a8c7", "branch_name": "refs/heads/master", "committer_date": "2021-07-01T11:11:24", "content_id": "e5cc82bb5c99d2aff680df9c4920cab26aad76d6", "detected_licenses": [ "MIT" ], "directory_id": "0630a7addb90600293f0ee0787dd6ab0ac77b09a", "extension": "c", "filename": "F_Knapsack.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1073, "license": "MIT", "license_type": "permissive", "path": "/CS591/Greedy/F_Knapsack.c", "provenance": "stackv2-0010.json.gz:25507", "repo_name": "aritraaaa/Competitive_Programming", "revision_date": "2021-07-01T11:11:24", "revision_id": "ee7eadf51939a360d0b004d787ebabda583e92f0", "snapshot_id": "48ecd3b6e28549889160c04cdbd19a5ad06fa49b", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/aritraaaa/Competitive_Programming/ee7eadf51939a360d0b004d787ebabda583e92f0/CS591/Greedy/F_Knapsack.c", "visit_date": "2023-06-12T07:04:07.698239" }
stackv2
#include <stdio.h> #include <stdlib.h> #define MAX 100 typedef struct itemtype { int p,w; double r; }item; int cmpFunc(const void *a, const void *b) { return ((*(item *)a).r < (*(item *)b).r); } int main() { int capacity=20; int n=3; int i; double fracs[MAX]; for(i=0;i<n;i++) { fracs[i]=0.0; } int profits[]={25,24,15}; int weights[]={18,15,10}; item items[MAX]; for(i=0;i<n;i++) { items[i].p=profits[i]; items[i].w=weights[i]; items[i].r=(profits[i]*1.0/weights[i]); } qsort(items,n,sizeof(item),cmpFunc); //calculation begins here double curr=0; //current total profit is stored here for(i=0;i<n;i++) { if(capacity==0) break; else if(items[i].w<=capacity) { capacity-=items[i].w; fracs[i]=1.0; curr+=items[i].p; } else { //fractional fracs[i]=(capacity*1.0)/items[i].w; curr+=(fracs[i]*items[i].p); capacity=0; } } printf("TOTAL PROFIT: %f\n",curr); printf("FRACTIONS:-\nWGT\tPFT\tFRAC\n"); for(i=0;i<n;i++) printf("%d\t%d\t%.2f\n",items[i].w,items[i].p,fracs[i]); printf("\n"); return 0; }
3.34375
3
2024-11-18T19:28:56.473933+00:00
2019-02-13T12:50:28
c713c5d727698d4d49162898c1427a2f2b5caa52
{ "blob_id": "c713c5d727698d4d49162898c1427a2f2b5caa52", "branch_name": "refs/heads/master", "committer_date": "2019-02-13T12:50:28", "content_id": "057762ca2b7f531960035225e5132f6540a72572", "detected_licenses": [ "MIT" ], "directory_id": "a0983034ce126b807408722387a5c1404879d7f2", "extension": "c", "filename": "get_env.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 170503754, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 490, "license": "MIT", "license_type": "permissive", "path": "/src/env/get_env.c", "provenance": "stackv2-0010.json.gz:52028", "repo_name": "FlorianMarcon/PSU_42sh", "revision_date": "2019-02-13T12:50:28", "revision_id": "c8f6c3234e5cc46e255218981d6d23671e3d794e", "snapshot_id": "6e7b32851dd559d23465aec0cf147ea437f70b35", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/FlorianMarcon/PSU_42sh/c8f6c3234e5cc46e255218981d6d23671e3d794e/src/env/get_env.c", "visit_date": "2020-04-22T16:18:27.534327" }
stackv2
/* ** EPITECH PROJECT, 2017 ** 42sh ** File description: ** get_env */ #include "header_shell.h" char **get_env(linked_list_t *env) { char **new = malloc(sizeof(char *) * (len_list(env) + 1)); int i = -1; while (env != NULL) { i++; new[i] = malloc(my_strlen(((variable_t *)env->data)->name) + 1); new[i] = my_strcpy(new[i], ((variable_t *)env->data)->name); new[i] = my_strcat(new[i], ((variable_t *)env->data)->data); env = env->next; } new[++i] = NULL; return (new); }
2.578125
3
2024-11-18T19:29:41.940813+00:00
2018-07-30T02:45:40
b9bd57ad3bcbb39eca57af710855fc69d343cb02
{ "blob_id": "b9bd57ad3bcbb39eca57af710855fc69d343cb02", "branch_name": "refs/heads/master", "committer_date": "2018-07-30T02:45:40", "content_id": "778e03c4623f91a6d985af37437e0c8691a9fa0b", "detected_licenses": [ "MIT" ], "directory_id": "22c38b72b3f66e7e6f255af41d38cd28353cda4d", "extension": "c", "filename": "ncurses_init.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2487, "license": "MIT", "license_type": "permissive", "path": "/virtual_machine/src/ncurses_init.c", "provenance": "stackv2-0010.json.gz:52412", "repo_name": "KyleAMcKee/Corewar", "revision_date": "2018-07-30T02:45:40", "revision_id": "760195a227409f9f7f8f6ecaaa92c7bb013824f5", "snapshot_id": "1c4b4a2eccad374a4b5b48af2fa6eef25421841a", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/KyleAMcKee/Corewar/760195a227409f9f7f8f6ecaaa92c7bb013824f5/virtual_machine/src/ncurses_init.c", "visit_date": "2020-03-24T20:09:04.684099" }
stackv2
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ncurses_init.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: bpierce <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/06/17 12:18:43 by bpierce #+# #+# */ /* Updated: 2018/06/21 16:35:24 by bpierce ### ########.fr */ /* */ /* ************************************************************************** */ #include "corewar.h" /* ** Initializes Ncurses and draws initial screens */ void init_ncurses(t_corewar *core) { if (!core->flag.viz) return ; initscr(); noecho(); cbreak(); start_color(); init_ncurses_colors(); init_ncurses_bored(core); init_ncurses_playa(core); init_ncurses_infoz(core); scrollok(stdscr, TRUE); nodelay(stdscr, TRUE); curs_set(0); } /* ** ONLY 8 colors can appear at once, but many different color_pairs ** ** COLOR_BLACK ** COLOR_RED ** COLOR_GREEN ** COLOR_YELLOW ** COLOR_BLUE ** COLOR_MAGENTA ** COLOR_CYAN ** COLOR_WHITE */ void init_ncurses_colors(void) { init_color(COLOR_BLUE, 215, 800, 1000); init_color(COLOR_WHITE, 200, 200, 200); init_color(COLOR_YELLOW, 855, 530, 36); init_pair(P1, COLOR_GREEN, COLOR_BLACK); init_pair(P2, COLOR_BLUE, COLOR_BLACK); init_pair(P3, COLOR_RED, COLOR_BLACK); init_pair(P4, COLOR_MAGENTA, COLOR_BLACK); init_pair(P1B, COLOR_BLACK, COLOR_GREEN); init_pair(P2B, COLOR_BLACK, COLOR_BLUE); init_pair(P3B, COLOR_BLACK, COLOR_RED); init_pair(P4B, COLOR_BLACK, COLOR_MAGENTA); init_pair(DF, COLOR_WHITE, COLOR_BLACK); init_pair(DF_BAR, COLOR_WHITE, COLOR_WHITE); init_pair(INFOZ, COLOR_BLACK, COLOR_YELLOW); init_pair(ORANGE_STUFF, COLOR_YELLOW, COLOR_BLACK); init_pair(ORANGE_BAR, COLOR_YELLOW, COLOR_YELLOW); } int key_hit(t_corewar *core) { int ch; if ((ch = wgetch(core->ncur.infoz)) == ERR) { return (1); } else if (ch == ' ') { while ((ch = wgetch(core->ncur.infoz)) != ' ') ; } return (1); } void terminate_ncurses(t_corewar *core) { if (core->flag.viz) endwin(); }
2.1875
2
2024-11-18T19:57:14.523346+00:00
2021-03-07T09:49:50
78b94bb000c0e237af62182d4a715ef0fcfa6944
{ "blob_id": "78b94bb000c0e237af62182d4a715ef0fcfa6944", "branch_name": "refs/heads/master", "committer_date": "2021-03-07T09:49:50", "content_id": "3464ea3f38ede73dbcc1af3caf77c2368f381908", "detected_licenses": [ "MIT" ], "directory_id": "446d243e72846f8858fc97d6c251d8a2a808d71b", "extension": "c", "filename": "hello.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 220, "license": "MIT", "license_type": "permissive", "path": "/user/hello.c", "provenance": "stackv2-0010.json.gz:86169", "repo_name": "zijeric/MIT6.828", "revision_date": "2021-03-07T09:49:50", "revision_id": "9d569808573f5b1df04f22927f18507c004278c9", "snapshot_id": "f54a8767f507875f20316493830e7040c0dc634d", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/zijeric/MIT6.828/9d569808573f5b1df04f22927f18507c004278c9/user/hello.c", "visit_date": "2023-06-01T21:38:17.691479" }
stackv2
// hello, world #include <inc/lib.h> void umain(int argc, char **argv) { // 调用了cprintf(),注意这是lib/print.c中的cprintf cprintf("hello, world\n"); cprintf("i am environment %08x\n", thisenv->env_id); }
2.125
2
2024-11-18T19:57:14.627749+00:00
2022-09-08T19:13:21
ea86d4ff550bedc4feb5d07928298d6c6e51a74f
{ "blob_id": "ea86d4ff550bedc4feb5d07928298d6c6e51a74f", "branch_name": "refs/heads/master", "committer_date": "2022-09-08T19:13:21", "content_id": "dde99fd44350e641c66b930da6e626afc954d0dc", "detected_licenses": [ "MIT" ], "directory_id": "8c3acd02e7d686de1987ac707279ee4880944d07", "extension": "c", "filename": "memcache.c", "fork_events_count": 0, "gha_created_at": "2019-05-12T08:38:17", "gha_event_created_at": "2019-05-12T08:38:17", "gha_language": null, "gha_license_id": null, "github_id": 186230683, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3741, "license": "MIT", "license_type": "permissive", "path": "/memcache/memcache.c", "provenance": "stackv2-0010.json.gz:86425", "repo_name": "alex-bender/sdb", "revision_date": "2022-09-08T19:13:21", "revision_id": "85873d52aea44ead1ddc566cbf1114cf78067a42", "snapshot_id": "25240fc6b87d4e094a493a7fc60bcca1ad42ef8b", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/alex-bender/sdb/85873d52aea44ead1ddc566cbf1114cf78067a42/memcache/memcache.c", "visit_date": "2022-09-25T07:39:52.148814" }
stackv2
/* Copyleft 2011-2014 - mcsdb (aka memcache-SimpleDB) - pancake */ #include "mcsdb.h" McSdb *mcsdb_new(const char *file) { McSdb *ms; Sdb *s = sdb_new (NULL, file, 0); if (!s) return NULL; ms = R_NEW (McSdb); if (!ms) { sdb_free (s); return NULL; } ms->sdb = s; ms->time = sdb_now (); ms->gets = ms->sets = 0LL; ms->evictions = ms->hits = ms->misses = 0LL; ms->bread = ms->bwrite = 0LL; ms->nfds = ms->tfds = 0; return ms; } void mcsdb_flush(McSdb *ms) { sdb_reset (ms->sdb); } void mcsdb_free(McSdb *ms) { int i; for (i=0; i<ms->nfds; i++) net_close (ms->fds[i].fd); sdb_sync (ms->sdb); sdb_free (ms->sdb); free (ms); } char *mcsdb_incr(McSdb *ms, const char *key, ut64 val) { if (!sdb_num_exists (ms->sdb, key)) return NULL; if (sdb_num_inc (ms->sdb, key, val, 0) == 0LL) return NULL; ms->sets++; return sdb_get (ms->sdb, key, 0); } char *mcsdb_decr(McSdb *ms, const char *key, ut64 val) { if (!sdb_num_exists (ms->sdb, key)) return NULL; sdb_num_dec (ms->sdb, key, val, 0); ms->sets++; return sdb_get (ms->sdb, key, 0); } int mcsdb_set(McSdb *ms, const char *key, const char *value, ut64 exptime, ut32 cas) { int ret = sdb_set (ms->sdb, key, value, cas); sdb_expire_set (ms->sdb, key, exptime, cas); ms->sets++; return ret; } int mcsdb_add(McSdb *ms, const char *key, ut64 exptime, const char *body) { if (!sdb_exists (ms->sdb, key)) { sdb_set (ms->sdb, key, body, 0); sdb_expire_set (ms->sdb, key, exptime, 0); ms->sets++; ms->hits++; return 1; } ms->misses++; return 0; } void mcsdb_append(McSdb *ms, const char *key, ut64 exptime, const char *body) { int len = strlen (body); char *a, *b; a = sdb_get (ms->sdb, key, NULL); if (a) { int alen = strlen (a); b = malloc (1 + len + alen); memcpy (b, a, alen); strcpy (b+alen, body); sdb_set (ms->sdb, key, b, 0); free (b); free (a); } else sdb_set (ms->sdb, key, body, 0); sdb_expire_set (ms->sdb, key, exptime, 0); ms->sets++; } void mcsdb_prepend(McSdb *ms, const char *key, ut64 exptime, const char *body) { int len = strlen (body); char *a, *b; a = sdb_get (ms->sdb, key, 0); if (a) { int alen = strlen (a); b = malloc (1 + len + alen); strcpy (b, body); strcpy (b+len, a); sdb_set (ms->sdb, key, b, 0); free (b); free (a); } else sdb_set (ms->sdb, key, body, 0); sdb_expire_set (ms->sdb, key, exptime, 0); ms->sets++; } int mcsdb_replace(McSdb *ms, const char *key, ut64 exptime, const char *body) { if (sdb_exists (ms->sdb, key)) { sdb_set (ms->sdb, key, body, 0); sdb_expire_set (ms->sdb, key, exptime, 0); ms->sets++; ms->hits++; return 1; } ms->misses++; return 0; } /* NOT IMPLEMENTED "cas" is a check and set operation which means "store this data but only if no one else has updated since I last fetched it." */ // cas <key> <flags> <exptime> <bytes> <cas unqiue> [noreply]\r\n int mcsdb_cas(McSdb *ms, const char *key, const char *value, ut64 exptime, ut32 cas) { return mcsdb_set (ms, key, value, exptime, cas); } /* retrieval */ char *mcsdb_get(McSdb *ms, const char *key, ut64 *exptime, ut32 *cas) { ut32 n; char *s = sdb_get (ms->sdb, key, &n); if (s) ms->hits++; else ms->misses++; ms->gets++; if (cas) *cas = n; *exptime = sdb_expire_get (ms->sdb, key, NULL); return s; } int mcsdb_remove(McSdb *ms, const char *key, ut64 exptime) { if (!sdb_exists (ms->sdb, key)) return 0; if (exptime>0) { sdb_expire_set (ms->sdb, key, exptime, 0); return 0; } if (sdb_expire_get (ms->sdb, key, NULL) > 0) { ms->evictions++; } return sdb_unset (ms->sdb, key, 0); } int mcsdb_touch(McSdb *ms, const char *key, ut64 exptime) { if (!sdb_exists (ms->sdb, key)) { return 0; } return sdb_expire_set (ms->sdb, key, exptime, 0); }
2.1875
2
2024-11-18T19:57:14.765514+00:00
2022-05-10T07:05:18
ceda659d59a2196c67496f5b8153e9af9f797de4
{ "blob_id": "ceda659d59a2196c67496f5b8153e9af9f797de4", "branch_name": "refs/heads/master", "committer_date": "2022-05-10T07:05:18", "content_id": "0c6c819b61aee0b81b95e3bcc9c53978a3d7ebc5", "detected_licenses": [ "MIT", "BSD-2-Clause" ], "directory_id": "5ab892bcef191df40d45296c54ec5733583e9b8e", "extension": "c", "filename": "mremap_after_coalesce.c", "fork_events_count": 0, "gha_created_at": "2019-01-02T13:48:22", "gha_event_created_at": "2022-05-11T06:57:29", "gha_language": "C++", "gha_license_id": "NOASSERTION", "github_id": 163846697, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2136, "license": "MIT,BSD-2-Clause", "license_type": "permissive", "path": "/src/test/mremap_after_coalesce.c", "provenance": "stackv2-0010.json.gz:86681", "repo_name": "detailyang/rr", "revision_date": "2022-05-10T07:05:18", "revision_id": "29e2743017e2bea3af7efeec95b7dc98a2575d8a", "snapshot_id": "aa8e08d97503cf6b1e15415ec070711d25712ecf", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/detailyang/rr/29e2743017e2bea3af7efeec95b7dc98a2575d8a/src/test/mremap_after_coalesce.c", "visit_date": "2023-08-15T23:03:17.859355" }
stackv2
/* -*- Mode: C; tab-width: 8; c-basic-offset: 2; indent-tabs-mode: nil; -*- */ #include "util.h" int main(void) { size_t page_size = sysconf(_SC_PAGESIZE); int fd; void* map_addr; long end; /* Map a file that's (probably) not in a tmpfs */ fd = open("/bin/ls", O_RDONLY); end = lseek(fd, 0, SEEK_END); test_assert(end > 0); map_addr = mmap(NULL, ceil_page_size(end) + page_size, PROT_READ, MAP_PRIVATE, fd, 0); test_assert(MAP_FAILED != map_addr); test_assert(MAP_FAILED != mmap(map_addr, page_size, PROT_READ, MAP_PRIVATE | MAP_FIXED, fd, 0)); map_addr = mremap(map_addr, ceil_page_size(end) + page_size, ceil_page_size(end) + page_size*2, MREMAP_MAYMOVE); if (map_addr == MAP_FAILED && errno == EFAULT) { // This happens in a Debian 9 kernel (4.9.0-11-amd64) atomic_puts("Kernel didn't coalesce the mapping; skipping test"); atomic_puts("EXIT-SUCCESS"); return 0; } test_assert(MAP_FAILED != map_addr); /* Try again, shrinking this time */ fd = open("/bin/ls", O_RDONLY); end = lseek(fd, 0, SEEK_END); test_assert(end > 0); map_addr = mmap(NULL, ceil_page_size(end) + page_size*3, PROT_READ, MAP_PRIVATE, fd, 0); test_assert(MAP_FAILED != map_addr); test_assert(MAP_FAILED != mmap(map_addr, page_size, PROT_READ, MAP_PRIVATE | MAP_FIXED, fd, 0)); map_addr = mremap(map_addr, ceil_page_size(end) + page_size*2, ceil_page_size(end) + page_size, 0); test_assert(MAP_FAILED != map_addr); /* Try again, this time starting in the middle of a mapping */ fd = open("/bin/ls", O_RDONLY); end = lseek(fd, 0, SEEK_END); test_assert(end > 0); map_addr = mmap(NULL, ceil_page_size(end) + page_size*3, PROT_READ, MAP_PRIVATE, fd, 0); test_assert(MAP_FAILED != map_addr); test_assert(MAP_FAILED != mmap(map_addr, page_size*3, PROT_READ, MAP_PRIVATE | MAP_FIXED, fd, 0)); map_addr = mremap(map_addr + page_size, page_size*3, page_size, 0); test_assert(MAP_FAILED != map_addr); atomic_puts("EXIT-SUCCESS"); return 0; }
2.609375
3
2024-11-18T19:57:14.819593+00:00
2021-07-19T20:43:21
bd1aecddfe1b3dfcdcd835ba29d5c5c23f0dcc78
{ "blob_id": "bd1aecddfe1b3dfcdcd835ba29d5c5c23f0dcc78", "branch_name": "refs/heads/master", "committer_date": "2021-07-19T21:08:58", "content_id": "f8e664c270c956260f5d61d55f68a8d5e583f8cb", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "7c2fcebb50aa7628e9a7cc402e0bd1c1531617b2", "extension": "c", "filename": "motor_test.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 816, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/test/motor_test.c", "provenance": "stackv2-0010.json.gz:86810", "repo_name": "gcaurin/epos2", "revision_date": "2021-07-19T20:43:21", "revision_id": "0ff5904c3ef542cf2add8e7c859f04d22ec78736", "snapshot_id": "10b43563e2fc34be3d9f0a03b428d770f6798ac9", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/gcaurin/epos2/0ff5904c3ef542cf2add8e7c859f04d22ec78736/test/motor_test.c", "visit_date": "2023-06-17T15:02:39.909060" }
stackv2
#include "socketcan/socketcan.h" #include "canopen/canopen.h" #include "motor/motor.h" #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <inttypes.h> #include <stdbool.h> int main(void) { motor_init(); motor_enable(); sleep(1); printf("Run 50 [mm/sec]\n"); vel_set_speed_right(50); vel_set_speed_left(50); sleep(5); printf("Halt!\n"); motor_halt(); sleep(5); printf("Run, but not enabled!\n"); vel_set_speed(50, 0); sleep(5); printf("Run again, and rotate!\n"); motor_enable(); vel_set_speed(0, (2.0*3.14/10.0)*1000); // Speed [mm/sec], Rotation [mRad/sec] sleep(5); printf("Zero speed\n"); vel_set_speed(0, 0); sleep(5); /* printf("Possition mode!\n"); motor_setmode(Motor_mode_Position); pos_rotate_grad(180); */ motor_disable(); motor_close(); return 0; }
2.453125
2
2024-11-18T18:19:10.371710+00:00
2021-05-04T15:05:23
b693eaeb40d8e34807f8516cf1b5aec3c385c443
{ "blob_id": "b693eaeb40d8e34807f8516cf1b5aec3c385c443", "branch_name": "refs/heads/master", "committer_date": "2021-05-04T15:05:23", "content_id": "99234ed0f447304bc8cc25861099585ccaa0dbcf", "detected_licenses": [ "MIT" ], "directory_id": "bda4c363022b4973484c51d2aa4abe9c3ec3f857", "extension": "h", "filename": "sarsa_alpha_with_added_mu.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 8704, "license": "MIT", "license_type": "permissive", "path": "/Learning/sarsa-3d/bank-attack/sarsa_alpha_with_added_mu.h", "provenance": "stackv2-0011.json.gz:53791", "repo_name": "WildGenie/kite-power", "revision_date": "2021-05-04T15:05:23", "revision_id": "003bcd3e847ebcf6e2305900636d51518f13d669", "snapshot_id": "877cccbcd286ce38e4767196fafded3b6d162dea", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/WildGenie/kite-power/003bcd3e847ebcf6e2305900636d51518f13d669/Learning/sarsa-3d/bank-attack/sarsa_alpha_with_added_mu.h", "visit_date": "2023-04-29T02:06:10.574526" }
stackv2
#include <stdio.h> #include <math.h> #ifndef __sarsa__ #define __sarsa__ #define PI 3.1415926535897932384626433 #define num_saved_matrices 500 #define learning_episodes 500000 #define PENALTY -300.0 #define n_actions 3 // 0 diminuisco alpha, 1 rimango, 2 aumento #define n_bank 13 #define decision_time 1000 #define Gamma 0.9999999999 #define max_steps 10000000 #define s_alpha0 12 #ifndef n_alphas #define n_alphas 15 #endif // n bank 13, -10, -8, -4, -6, -2, -1, 0, 1, 2, 4, 6, 8, 10 double bank[n_bank] = {-0.174532925, -0.13962634016, -0.10471975512, -0.06981317008, -0.03490658504, -0.01745329252, 0., 0.01745329252, 0.03490658504, 0.06981317008, 0.10471975512, 0.13962634016, 0.174532925}; #define s_bank0 6 double Alpha = 0.5; // ordine di grandezza=h/tempo_episodio_in_sec(al minimo caduta) double epsilon = 0.05; void fill_Q_mat(FILE *Q_mat_file, double *Q, int episode){ for (int i=0; i<n_alphas; i++){ for (int j=0; j<n_bank; j++){ for (int ii=0; ii<n_actions; ii++){ for (int jj=0; jj<n_actions; jj++){ fprintf(Q_mat_file,"%d,", episode); fprintf(Q_mat_file,"%d,", i); fprintf(Q_mat_file,"%d,", j); fprintf(Q_mat_file,"%d,", ii); fprintf(Q_mat_file,"%d,", jj); fprintf(Q_mat_file,"%f\n", Q[j*n_actions*n_actions*n_alphas + jj*n_actions*n_alphas + i*n_actions + ii]); } } } } } void fill_Q_count(FILE *Q_mat_file, int *Q, int episode){ for (int i=0; i<n_alphas; i++){ for (int j=0; j<n_bank; j++){ for (int ii=0; ii<n_actions; ii++){ for (int jj=0; jj<n_actions; jj++){ fprintf(Q_mat_file,"%d,", episode); fprintf(Q_mat_file,"%d,", i); fprintf(Q_mat_file,"%d,", j); fprintf(Q_mat_file,"%d,", ii); fprintf(Q_mat_file,"%d,", jj); fprintf(Q_mat_file,"%d\n", Q[j*n_actions*n_actions*n_alphas + jj*n_actions*n_alphas + i*n_actions + ii]); } } } } } void load_matrix_3d(double * Q, char * name){ FILE *dat = fopen(name, "r"); // opens file for reading if (dat) { for (int i=0; i<n_alphas; i++){ for (int j=0; j<n_bank; j++){ for (int ii=0; ii<n_actions; ii++){ for (int jj=0; jj<n_actions; jj++){ fscanf(dat, "%lf ", &Q[j*n_actions*n_actions*n_alphas + jj*n_alphas*n_actions + i*n_actions + ii]); } } } } } else { printf("error loading file\n"); } fclose(dat); } void load_matrix_only_alpha(double * Q, char * name){ int idx_mu = 1; FILE *dat = fopen(name, "r"); // opens file for reading if (dat) { for (int i = 0; i < n_alphas; i++){ for (int j = 0; j < n_actions; j++){ // non ho messo 0 perche` per mu=0 e azione=0 la matrice e` tutta nulla! fscanf(dat, "%lf ", &Q[idx_mu*n_actions*n_actions*n_alphas + 0*n_alphas*n_actions + i*n_actions + j]); } } int kk = 0; int ll = 0; while(kk < n_bank){ ll = 0; while (ll < n_actions){ for (int i=0; i<n_alphas; i++){ for (int j=0; j<n_actions; j++){ if (kk == 0 && ll==0){ Q[kk*n_alphas*n_actions*n_actions + ll*n_alphas*n_actions + i*n_actions + j] = 0; } else if (kk == n_bank-1 && ll == n_actions-1){ Q[kk*n_alphas*n_actions*n_actions + ll*n_alphas*n_actions + i*n_actions + j] = 0; } else { Q[kk*n_alphas*n_actions*n_actions + ll*n_alphas*n_actions + i*n_actions + j] = \ Q[idx_mu*n_actions*n_actions*n_alphas + 0*n_alphas*n_actions + i*n_actions + j]; } } } ll++; } kk++; } } else { printf("error loading file\n"); } fclose(dat); } void print_mat(double * Q){ for (int j=0; j<n_bank; j++){ for (int jj=0; jj<n_actions; jj++){ printf("bank=%f, action=%d\n", bank[j], jj); for (int i=0; i<n_alphas; i++){ for (int ii=0; ii<n_actions; ii++){ printf("%f ", Q[j*n_actions*n_actions*n_alphas + jj*n_actions*n_alphas + i*n_actions + ii]); } printf("\n"); } printf("\n\n"); } } printf("\n\n"); } /* void save_matrix(double * Q, char * name){ FILE *dat = fopen(name, "w"); // opens new file for writing if (dat) { for (int kk = 0; kk < n_alphas; kk++){ for (int j = 0; j < n_actions; j++){ fprintf(dat, "%16.8e ", Q[kk*n_actions + j]); } } } fclose(dat); } void load_matrix(double * Q, char * name){ FILE *dat = fopen(name, "r"); // opens file for reading //"Qmatrix.dat" if (dat) { for (int kk = 0; kk < n_alphas; kk++){ for (int j=0; j<n_actions; j++){ fscanf(dat, "%lf", &Q[kk*n_actions + j] ); } } } else { printf("error loading file\n"); } fclose(dat); }*/ int check(int s_alpha, int s_bank, int a_alpha, int a_bank){ #ifdef DEBUGSARSA //printf("s_alpha %d\n", s_alpha); #endif int c = 0; int idx = s_bank*n_actions*n_actions*n_alphas + a_bank*n_actions*n_alphas + s_alpha*n_actions + a_alpha; if ( (idx >= n_actions*n_actions*n_alphas*n_bank || idx < 0)){ c = 1; } return c; } void initialize_Q(double * Q, double max_Q_value){ for (int i=0; i<n_alphas; i++){ for (int j=0; j<n_bank; j++){ for (int ii=0; ii<n_actions; ii++){ for (int jj=0; jj<n_actions; jj++){ if (i == 0 && ii == 0) Q[j*n_actions*n_actions*n_alphas + jj*n_alphas*n_actions + i*n_actions + ii] = 0; if (j == 0 && jj == 0) Q[j*n_actions*n_actions*n_alphas + jj*n_alphas*n_actions + i*n_actions + ii] = 0; if (i == n_alphas-1 && ii == n_actions-1) Q[j*n_actions*n_actions*n_alphas + jj*n_alphas*n_actions + i*n_actions + ii] = 0; if (j == n_bank-1 && jj == n_actions-1) Q[j*n_actions*n_actions*n_alphas + jj*n_alphas*n_actions + i*n_actions + ii] = 0; else Q[j*n_actions*n_actions*n_alphas + jj*n_alphas*n_actions + i*n_actions + ii] = max_Q_value; } } } } } void initialize_Q_count(int * Q, int value){ for (int i=0; i<n_bank*n_actions*n_alphas*n_actions; i++){ Q[i] = 0; } } int update_state(int s, int a){ int s1; if (a == 0){ s1 = s - 1; } else if (a == 1){ s1 = s; } else if (a == 2){ s1 = s + 1; } else { printf(" ===========================> UPDATE STATE ERROR!!!!!!!!"); s1 = 100; } return s1; } void select_action(double epsilon, double * Q, int s_alpha, int *a_alpha, int s_bank, int *a_bank){ double probab = (double)rand()/RAND_MAX; if (probab <= epsilon){ // random action if (s_alpha == 0){ *a_alpha = (rand() % 2) + 1; // random number between 1 and 2 (compresi) } else if (s_alpha == n_alphas-1){ *a_alpha = (rand() % 2); // random number da 0 a 2 } else { *a_alpha = rand() % 3; } if (s_bank == 0){ *a_bank = (rand() % 2) + 1; // random number between 1 and 2 (compresi) } else if (s_bank == n_bank-1){ *a_bank = (rand() % 2); // random number da 0 a 2 } else { *a_bank = rand() % 3; } } else { // GREEDY ACTION //printf("not random\n"); /* fix starting action for the search: 0 in any case, and 1 only if the starting state is the beginning of the array */ int starting_action_alpha = 1; int starting_action_mu = 1; *a_bank = starting_action_alpha; *a_alpha = starting_action_mu; int a_alpha_min = 0; int a_bank_min = 0; if (s_alpha == 0) { a_alpha_min = 1; } if (s_bank == 0) { a_bank_min = 1; } /* fix ending state: 3 (n_actions), NOT INCLUDED, in any state; 2 (n_actions -1) only if starting state is the last one in the array */ int a_alpha_max = n_actions; int a_bank_max = n_actions; if (s_alpha == n_alphas - 1) { a_alpha_max = n_actions - 1; } if (s_bank == n_bank - 1) { a_bank_max = n_actions - 1; } /* LOOP TO SEARCH NEXT ACTION */ //printf("a_alpha_min = %d, a_alpha_max=%d, a_bank_min=%d, a_bank_max=%d\n", a_alpha_min, a_alpha_max, a_bank_min, a_bank_max); for (int ii=a_alpha_min; ii<a_alpha_max; ii++){ for (int jj=a_bank_min; jj<a_bank_max; jj++){ if (Q[s_bank*n_actions*n_alphas*n_actions + jj*n_actions*n_alphas + s_alpha*n_actions + ii] > Q[s_bank*n_actions*n_alphas*n_actions + *a_bank*n_actions*n_alphas + s_alpha*n_actions + *a_alpha]) { *a_alpha = ii; *a_bank = jj; //printf("Modify! New alpha action=%d, new mu actions=%d\n", *a_alpha1, *a_mu1); } } } } //printf("chosen: a_alpha=%d, a_bank=%d\n", *a_alpha, *a_bank); } double expected_update(double * Q, int s_alpha, int a_alpha, int s_bank, int a_bank){ double update = 0; return update; } #endif
2.046875
2
2024-11-18T18:19:10.426847+00:00
2020-12-25T18:09:48
ae36bc87801f3a952b2b27dba7db059ddc43134a
{ "blob_id": "ae36bc87801f3a952b2b27dba7db059ddc43134a", "branch_name": "refs/heads/master", "committer_date": "2020-12-25T18:09:48", "content_id": "781be7adbedbacba2ed394c5236d017e9270ea8c", "detected_licenses": [ "MIT" ], "directory_id": "508b9e132a3f84e6fd04bf01cb8f126db337ca17", "extension": "c", "filename": "main.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 291405118, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 387, "license": "MIT", "license_type": "permissive", "path": "/Demo8/main.c", "provenance": "stackv2-0011.json.gz:53919", "repo_name": "Harrdy2018/CMake", "revision_date": "2020-12-25T18:09:48", "revision_id": "316c6e8817ce9c790d13836e2fed1daed7ef2500", "snapshot_id": "0c8550328601fb0c12203e1ad946dfb456bdacd9", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Harrdy2018/CMake/316c6e8817ce9c790d13836e2fed1daed7ef2500/Demo8/main.c", "visit_date": "2023-02-03T21:20:39.696813" }
stackv2
#include <stdio.h> #include <stdlib.h> #include "math/MathFunctions.h" int main(int argc, char *argv[]) { if(argc<3){ printf("Usage: %s base exponent\n", argv[0]); return 0; } double base=atof(argv[1]); int exponent=atoi(argv[2]); double result=power(base, exponent); printf("%g^%d is %g\n", base, exponent,result); return 0; }
2.734375
3
2024-11-18T18:44:09.372310+00:00
2023-08-16T08:49:18
89b0d5bfb9e280310f886b2aac52df93d392cd72
{ "blob_id": "89b0d5bfb9e280310f886b2aac52df93d392cd72", "branch_name": "refs/heads/master", "committer_date": "2023-08-16T08:49:18", "content_id": "fd4dac75a20b8afee3d194949baf3ac1830e1c35", "detected_licenses": [ "MIT" ], "directory_id": "e3acfc4f06840e23ef1185dcf367f40d3e3f59b4", "extension": "c", "filename": "07-env-order.c", "fork_events_count": 62, "gha_created_at": "2011-07-18T15:10:56", "gha_event_created_at": "2023-09-14T18:48:34", "gha_language": "OCaml", "gha_license_id": "MIT", "github_id": 2066905, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 329, "license": "MIT", "license_type": "permissive", "path": "/tests/regression/63-affeq/07-env-order.c", "provenance": "stackv2-0011.json.gz:93225", "repo_name": "goblint/analyzer", "revision_date": "2023-08-16T08:49:18", "revision_id": "69ee7163eef0bfbfd6a4f3b9fda7cea5ce9ab79f", "snapshot_id": "d62d3c610b86ed288849371b41c330c30678abc7", "src_encoding": "UTF-8", "star_events_count": 141, "url": "https://raw.githubusercontent.com/goblint/analyzer/69ee7163eef0bfbfd6a4f3b9fda7cea5ce9ab79f/tests/regression/63-affeq/07-env-order.c", "visit_date": "2023-08-16T21:58:53.013737" }
stackv2
//SKIP PARAM: --set ana.activated[+] affeq --set sem.int.signed_overflow assume_none int next; int main() { next = 0; // Due to a bug in the dim add function, t was always set to 0 in the following block int t; next = t; if (next == 0) { t = 10; } __goblint_check(t == 10); //UNKNOWN! }
2.1875
2
2024-11-18T18:44:09.443363+00:00
2019-01-26T01:57:58
9c403301d529cec3afe826c0626a3322f419aeeb
{ "blob_id": "9c403301d529cec3afe826c0626a3322f419aeeb", "branch_name": "refs/heads/master", "committer_date": "2019-01-26T01:57:58", "content_id": "905c1c96381a83cfb11d63d578518a9f6054ad3d", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "5702780e2da56d4aa74faf35eba56f30404bc30e", "extension": "c", "filename": "vfs.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 152760176, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5793, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/kernel/vfs/vfs.c", "provenance": "stackv2-0011.json.gz:93353", "repo_name": "TH3CHARLie/101NIX", "revision_date": "2019-01-26T01:57:58", "revision_id": "367b9fed1f2d1e99c12fe11225147f234c05a46c", "snapshot_id": "983cb6a708cf8db5396a35a2693e33892d80172f", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/TH3CHARLie/101NIX/367b9fed1f2d1e99c12fe11225147f234c05a46c/kernel/vfs/vfs.c", "visit_date": "2020-04-01T01:58:27.752695" }
stackv2
#include <zjunix/vfs/vfs.h> #include <zjunix/vfs/vfscache.h> #include <zjunix/vfs/fat32.h> #include <zjunix/vfs/ext2.h> #include <zjunix/log.h> #include <zjunix/slab.h> #include <zjunix/utils.h> #include <driver/vga.h> // TODO 根文件系统装载重构 // 公用全局变量 struct master_boot_record * MBR; struct dentry * root_dentry; struct dentry * pwd_dentry; struct vfsmount * root_mnt; struct vfsmount * pwd_mnt; //struct vfs_page* tempp; struct file_system_type * file_systems; // 虚拟文件系统初始化 // TODO init_mount_tree u32 init_vfs(){ u32 err; u8 i; err = init_file_systems(); // 初始化文件系统 if ( IS_ERR_VALUE(err) ){ log(LOG_FAIL, "init_file_systems()"); goto vfs_init_err; } log(LOG_OK, "init_file_systems()"); err = vfs_read_MBR(); // 读取主引导记录 if ( IS_ERR_VALUE(err) ){ log(LOG_FAIL, "vfs_read_MBR()"); goto vfs_init_err; } log(LOG_OK, "vfs_read_MBR()"); err = init_cache(); // 初始化公用缓存区域 if ( IS_ERR_VALUE(err) ){ log(LOG_FAIL, "init_cache()"); goto vfs_init_err; } log(LOG_OK, "init_cache()"); err = init_fat32(MBR->m_base[0]); // 第一个分区为FAT32,读取元数据 if ( IS_ERR_VALUE(err) ){ log(LOG_FAIL, "init_fat32()"); goto vfs_init_err; } log(LOG_OK, "init_fat32()"); u8 DEV_NAME[10] = "/dev/sda0"; for (i = 1; i < MBR->m_count; i++) { // 依次读取剩下的分区,分配设备名,注册文件系统 DEV_NAME[8] = '0' + i + 1; if (MBR->m_type[i] == PARTITION_TYPE_FAT32) { // 暂时未处理fat32 } else if (MBR->m_type[i] == PARTITION_TYPE_EXT2) { err = init_ext2(MBR->m_base[i], DEV_NAME); if (IS_ERR_VALUE(err)) { log(LOG_FAIL, "init_ext2()"); goto vfs_init_err; } log(LOG_OK, "init_ext2()"); } } print_file_systems(); return 0; vfs_init_err: kernel_printf_vfs_errno(err); // 发生错误,则打印错误代码 return err; } // 读取主引导记录并完善MBR相关信息 u32 vfs_read_MBR(){ u8 *ptr_lba; u8 *ptr_type; u8 part_type; u32 part_lba; // 从外存读入MBR信息 MBR = (struct master_boot_record*)kmalloc(sizeof(struct master_boot_record)); if (MBR == 0) return -ENOMEM; kernel_memset(MBR->m_data, 0, sizeof(u8) * SECTOR_SIZE); if (read_block(MBR->m_data, 0, 1)) // MBR在外存的0号扇区 goto vfs_read_MBR_err; // 完善MBR相关信息 ptr_lba = MBR->m_data + 446 + 8; ptr_type = MBR->m_data + 446 + 4; for (MBR->m_count = 0; MBR->m_count < DPT_MAX_ENTRY_COUNT; MBR->m_count++) { part_lba = get_u32(ptr_lba); part_type = *ptr_type; if (!part_lba) break; MBR->m_base[MBR->m_count] = part_lba; MBR->m_type[MBR->m_count] = part_type; ptr_lba += DPT_ENTRY_LEN; ptr_type += DPT_ENTRY_LEN; #ifdef DEBUG_VFS kernel_printf(" MBR[%d]: base: %d type: %x\n", MBR->m_count, part_lba, part_type); #endif } if (MBR->m_count == 0) { kernel_printf("[[MBR ERROR]]: Empty partition\n"); goto vfs_read_MBR_err; } else if (MBR->m_type[0] != PARTITION_TYPE_FAT32) { kernel_printf("[[MBR ERROR]]: First partition must be FAT32\n"); goto vfs_read_MBR_err; } return 0; vfs_read_MBR_err: kfree(MBR); return -EIO; } // 初始化文件系统 // TODO init_rootfs() u32 init_file_systems() { file_systems = (struct file_system_type *)kmalloc(sizeof(struct file_system_type)); if (file_systems == 0) return -ENOMEM; file_systems->name = "root_fs"; file_systems->next = NULL; INIT_LIST_HEAD(&file_systems->fs_supers); return 0; } // 根据不同的错误输出错误信息 void kernel_printf_vfs_errno(u32 err){ if (err == -EPERM) { kernel_printf("[[VFS ERROR]]: Operation not permitted\n"); } else if (err == -ENOENT) { kernel_printf("[[VFS ERROR]]: No such file or directory\n"); } else if (err == -EIO) { kernel_printf("[[VFS ERROR]]: I/O error\n"); } else if (err == -EBADF) { kernel_printf("[[VFS ERROR]]: Bad file number\n"); } else if (err == -ENOMEM) { kernel_printf("[[VFS ERROR]]: Out of memory\n"); } else if (err == -EFAULT) { kernel_printf("[[VFS ERROR]]: Bad address\n"); } else if (err == -EBUSY) { kernel_printf("[[VFS ERROR]]: Device or resource busy\n"); } else if (err == -EEXIST) { kernel_printf("[[VFS ERROR]]: File exists\n"); } else if (err == -ENODEV) { kernel_printf("[[VFS ERROR]]: No such device\n"); } else if (err == -ENOTDIR) { kernel_printf("[[VFS ERROR]]: Not a directory\n"); } else if (err == -EISDIR) { kernel_printf("[[VFS ERROR]]: Is a directory\n"); } else if (err == -EINVAL) { kernel_printf("[[VFS ERROR]]: Invalid argument\n"); } else if (err == -ENFILE) { kernel_printf("[[VFS ERROR]]: File table overflow\n"); } else if (err == -ENOSPC) { kernel_printf("[[VFS ERROR]]: No space left on device\n"); } else if (err == -ELOOP) { kernel_printf("[[VFS ERROR]]: Too many symbolic links encountered\n"); } else { kernel_printf("[[VFS ERROR]]: Unknown error\n"); } }
2.171875
2
2024-11-18T18:44:09.679506+00:00
2022-06-09T19:43:13
4b2df3b49acb345c33b25bcb22a66c15b4775ff9
{ "blob_id": "4b2df3b49acb345c33b25bcb22a66c15b4775ff9", "branch_name": "refs/heads/master", "committer_date": "2022-06-09T19:43:13", "content_id": "e56011e11b4f4a3a700afdf6da3136c08f628b38", "detected_licenses": [ "MIT" ], "directory_id": "64014c6a817eae339ee272067922c4c26a6d1459", "extension": "h", "filename": "util.h", "fork_events_count": 10, "gha_created_at": "2020-09-27T21:43:17", "gha_event_created_at": "2022-06-04T01:47:38", "gha_language": "C++", "gha_license_id": "NOASSERTION", "github_id": 299124547, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1584, "license": "MIT", "license_type": "permissive", "path": "/ext/mod-single-repo/nvm_malloc/src/util.h", "provenance": "stackv2-0011.json.gz:93738", "repo_name": "urcs-sync/Montage", "revision_date": "2022-06-09T19:43:13", "revision_id": "3384e50105348fab6d80e897bfb4a0efdd8aa825", "snapshot_id": "c91dbf3abd0f82c2f84ad40f152d992787fbdbd6", "src_encoding": "UTF-8", "star_events_count": 14, "url": "https://raw.githubusercontent.com/urcs-sync/Montage/3384e50105348fab6d80e897bfb4a0efdd8aa825/ext/mod-single-repo/nvm_malloc/src/util.h", "visit_date": "2023-07-06T15:26:36.356064" }
stackv2
/* Copyright (c) 2014 Tim Berning */ #ifndef UTIL_H_ #define UTIL_H_ #include <stdint.h> #include <stdio.h> #include <stdlib.h> uint64_t round_up(uint64_t num, uint64_t multiple); char identify_usage(void *ptr); void clflush(const void *ptr); void clflush_range(const void *ptr, uint64_t len); #ifdef HAS_CLFLUSHOPT void clflushopt(const void *ptr); void clflushopt_range(const void *ptr, uint64_t len); #endif #ifdef HAS_CLWB void clwb(const void *ptr); void clwb_range(const void *ptr, uint64_t len); #endif void sfence(); void mfence(); /* macros for persistency depending on instruction availability */ #ifdef IMMER_DISABLE_FLUSHING /* Completely disable flushes */ #define PERSIST(ptr) do { } while (0) #define PERSIST_RANGE(ptr, len) do { } while (0) #elif HAS_CLWB /* CLWB is the preferred instruction, not invalidating any cache lines */ #define PERSIST(ptr) do { clwb(ptr); } while (0) #define PERSIST_RANGE(ptr, len) do { clwb_range(ptr, len); } while (0) #elif HAS_CLFLUSHOPT /* CLFLUSHOPT is preferred over CLFLUSH as only dirty cache lines will be evicted */ #define PERSIST(ptr) do { clflushopt(ptr); } while (0) #define PERSIST_RANGE(ptr, len) do { clflushopt_range(ptr, len); } while (0) #else /* If neither CLWB nor CLFLUSHOPT are available, default to CLFLUSH */ #define PERSIST(ptr) do { mfence(); clflush(ptr); mfence(); } while (0) #define PERSIST_RANGE(ptr, len) do { mfence(); clflush_range(ptr, len); mfence(); } while (0) #endif #endif /* UTIL_H_ */
2.4375
2
2024-11-18T18:54:17.706651+00:00
2014-09-03T01:23:25
2995d1e55c1cdfcb8935c45fab80343963fba39f
{ "blob_id": "2995d1e55c1cdfcb8935c45fab80343963fba39f", "branch_name": "refs/heads/master", "committer_date": "2014-09-03T01:23:25", "content_id": "db61dbfc2f384291717dfb98c50a3241a636477f", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "d6f73470c747fa5046428e916cf6804e2ce9ad64", "extension": "h", "filename": "bignum.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 7612041, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1831, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/bignum.h", "provenance": "stackv2-0011.json.gz:127495", "repo_name": "rbur004/MacVAX-As", "revision_date": "2014-09-03T01:23:25", "revision_id": "7f55d31ffa76ca0a22d24e08bf4872e2401d739d", "snapshot_id": "43282c00bd080e3e690b64d686e8e5dfe0b036e4", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/rbur004/MacVAX-As/7f55d31ffa76ca0a22d24e08bf4872e2401d739d/bignum.h", "visit_date": "2021-01-20T08:14:15.155537" }
stackv2
#ifndef BIGNUM_H #define BIGNUM_H /*Function bignum1.c*/ Bignum *as_atof ( Bignum *a_big_number_p, char *numbuf, long radix, Ovf *ovfp ); Bignum *as_atoi ( Bignum *a_big_number_p, reg char *ccp, /* character cp */ long radix, Ovf *ovfp ); Ovf posovf ( reg chptr src ); long isclear ( reg chptr dst ); long isunequal ( reg chptr src1, reg chptr src2 ); Ovf numclear ( reg chptr dst ); Ovf numshift ( long n, /*number of bits being shifted*/ reg chptr dst, reg chptr src ); Ovf numaddd ( chptr dst, chptr src1, long val ); Ovf numaddv ( reg chptr dst, reg chptr src1, reg chptr src2 ); Ovf numnegate ( chptr dst, chptr src ); Ovf num1comp ( reg chptr dst, reg chptr src ); long slitflt ( Bignum number, /* number presented */ long argtype, /* what the instruction expects */ long *valuep ); #ifndef STANDALONE void bignumwrite ( Bignum number, long toconv /* one of TYP[QO FDGH] */ ); #endif STANDALONE /*Functions bignum2.c*/ Bignum *intconvert ( Bignum *a_big_number_p, Bignum number, long convto ); Bignum *floatconvert ( Bignum *a_big_number_p, Bignum number, long convto ); Bignum *bignumconvert ( Bignum *a_big_number_p, Bignum number, long toconv, Ovf *ovfp ); Bignum *bignumunpack ( Bignum *a_big_number_p, Bignum Packed, Ovf *ovfp ); Bignum *bignumpack ( Bignum *a_big_number_p, Bignum Unpacked, long toconv, Ovf *ovfp ); void mapnumber ( chptr chp1, chptr chp2, long nbytes, char *themap ); long upround ( reg Bignum *numberp, reg struct ty_bigdesc *p, long exponent ); #ifdef DEBUG void bignumprint ( Bignum number ); void numprintovf ( Ovf ovf ); #endif DEBUG /*Functions natof.c*/ Bignum *bigatof ( Bignum *a_big_number_p, reg char *str, /* r11 */ long radix /* TYPF ... TYPH */ ); #endif BIGNUM_H
2.265625
2
2024-11-18T18:54:17.876634+00:00
2008-11-03T11:28:06
ea70ec3ce0c4cb9bd15d34ce684dcb72ccde2cc2
{ "blob_id": "ea70ec3ce0c4cb9bd15d34ce684dcb72ccde2cc2", "branch_name": "refs/heads/master", "committer_date": "2008-11-03T11:28:06", "content_id": "aa261687e8d05bd46772d7b2a3b1ced7bf1a1fec", "detected_licenses": [ "BSD-3-Clause", "BSD-2-Clause" ], "directory_id": "cc0a48049c545193c9aa883f713620938fb39df7", "extension": "c", "filename": "protocol.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 10333, "license": "BSD-3-Clause,BSD-2-Clause", "license_type": "permissive", "path": "/src/tags/v05/modules/protocol.c", "provenance": "stackv2-0011.json.gz:127751", "repo_name": "qingchen1984/como", "revision_date": "2008-11-03T11:28:06", "revision_id": "38d4fddd8525310d9da63655adbf30ab6a0b0594", "snapshot_id": "ba96634bdb931acac4b6d11a0ad6cf060d261ee3", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/qingchen1984/como/38d4fddd8525310d9da63655adbf30ab6a0b0594/src/tags/v05/modules/protocol.c", "visit_date": "2020-03-23T11:40:02.333048" }
stackv2
/* * Copyright (c) 2004 Intel 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: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * $Id$ */ /* * Protocol module * * This module computes the number of packets and bytes per protocol. * Output: packets/bytes per protocol over 1s intervals * */ #include <stdio.h> #include <time.h> #include "module.h" #define FLOWDESC struct _proto_stat FLOWDESC { timestamp_t ts; uint64_t bytes[IPPROTO_MAX]; uint64_t pkts[IPPROTO_MAX]; }; static int meas_ivl = 1; /* measurement interval */ static timestamp_t init(__unused void *mem, __unused size_t msize, char *args[]) { int i; for (i = 0; args && args[i]; i++) { if (strstr(args[i], "interval")) { char * val = index(args[i], '=') + 1; meas_ivl = atoi(val); } } return TIME2TS(meas_ivl, 0); } static int update(pkt_t *pkt, void *fh, int isnew) { FLOWDESC *x = F(fh); if (isnew) { x->ts = pkt->ts; bzero(x->bytes, sizeof(x->bytes)); bzero(x->pkts, sizeof(x->pkts)); } x->bytes[IP(proto)] += H16(IP(len)); x->pkts[IP(proto)]++; return 0; } static ssize_t store(void *fh, char *buf, size_t len) { FLOWDESC *x = F(fh); int i; if (len < sizeof(FLOWDESC)) return -1; PUTH64(buf, x->ts); for (i = 0; i < IPPROTO_MAX; i++) PUTH64(buf, x->bytes[i]); for (i = 0; i < IPPROTO_MAX; i++) PUTH64(buf, x->pkts[i]); return sizeof(FLOWDESC); } static size_t load(char * buf, size_t len, timestamp_t * ts) { if (len < sizeof(FLOWDESC)) { ts = 0; return 0; } *ts = NTOHLL(((FLOWDESC *)buf)->ts); return sizeof(FLOWDESC); } #define PRINT_PLAIN 0 #define PRINT_PRETTY 1 #define PRINT_GNUPLOT 2 /* * Gnuplot 4.0 format. * * By default, this module will only plot the graph for TCP, UDP, ICNP and * ESP. All other protocols are considered in the OTHER column. * If a user desires to see the other protocols then it can send a query * with the option "include=<proto-number>" that would force print() to * add one line to the graph. * * Note that in gnuplot format we only consider the contribution of each * protocol in bytes. * */ #define GNUPLOTHDR \ "set terminal postscript eps color solid lw 1 \"Helvetica\" 14;" \ "set grid;" \ "set ylabel \"Percentage\";" \ "set xlabel \"Time (H:M UTC)\";" \ "set yrange [0:100];" \ "set autoscale xfix;" \ "set key outside;" \ "set xdata time;" \ "set timefmt \"%%s\";" \ "set format x \"%%H:%%M\";" #define GNUPLOTFOOTER "e\n" /* * -- do_header * * just to print header information */ static size_t do_header(char * const args[], char * s, int * fmt, uint8_t * proto, int * num_proto, int * granularity) { size_t len; int n; /* reset protocols array */ bzero(proto, IPPROTO_MAX); proto[0] = IPPROTO_TCP; proto[1] = IPPROTO_UDP; proto[2] = IPPROTO_ICMP; proto[3] = IPPROTO_ESP; *num_proto = 4; /* first call of print, process the arguments and return */ for (n = 0; args[n]; n++) { if (!strcmp(args[n], "format=plain")) { len = 0; *fmt = PRINT_PLAIN; } else if (!strcmp(args[n], "format=pretty")) { len = 0; *fmt = PRINT_PRETTY; } else if (!strcmp(args[n], "format=gnuplot")) { *fmt = PRINT_GNUPLOT; } else if (!strncmp(args[n], "include=", 8)) { char * wh; wh = index(args[n], '=') + 1; proto[*num_proto] = atoi(wh); *num_proto = *num_proto + 1; } else if (!strncmp(args[n], "granularity=", 12)) { char * val = index(args[n], '=') + 1; /* aggregate multiple records into one to reduce * communication messages. */ *granularity = MAX(atoi(val) / meas_ivl,1); } } if (*fmt == PRINT_GNUPLOT) { /* * we need to print the header but make sure that we * include/exclude all protocols. */ len = sprintf(s, GNUPLOTHDR); len += sprintf(s + len, "plot \"-\" using 1:%d with filledcurve x1 " "title \"Other\" lw 5", *num_proto + 2); for (n = *num_proto - 1; n >= 0; n--) { len += sprintf(s + len, ",\"-\" using 1:%d with filledcurve x1 " "title \"%s (%d)\" lw 5", n + 2, getprotoname(proto[n]), proto[n]); } len += sprintf(s + len, ";\n"); } return len; } static size_t print_plain(FLOWDESC * x, char * s) { size_t len; int i; len = sprintf(s, "%12u.%06u ", (uint) TS2SEC(x->ts), (uint) TS2USEC(x->ts)); for (i = 0; i < IPPROTO_MAX; i++) len += sprintf(s + len, "%3d %8lld %8lld ", i, x->bytes[i], x->pkts[i]); len += sprintf(s + len, "\n"); return len; } static size_t print_pretty(FLOWDESC * x, char * s, int num_proto, uint8_t * proto) { time_t ts; size_t len; uint64_t bytes_all, pkts_all; uint64_t bytes_chosen, pkts_chosen; float bytes_prct, pkts_prct; int i; ts = (time_t) TS2SEC(x->ts); len = sprintf(s, "%.24s ", asctime(localtime(&ts))); /* compute the sums of all bytes and packets */ bytes_all = pkts_all = 0; for (i = 0; i < IPPROTO_MAX; i++) { bytes_all += x->bytes[i]; pkts_all += x->pkts[i]; } if (bytes_all == 0) return 0; /* compute the sums of all bytes and packets of interest */ bytes_chosen = pkts_chosen = 0; for (i = 0; i < num_proto; i++) { bytes_prct = 100 * (float) x->bytes[proto[i]] / bytes_all; pkts_prct = 100 * (float) x->pkts[proto[i]] / pkts_all; len += sprintf(s + len, "%s %5.2f %5.2f ", getprotoname(proto[i]), bytes_prct, pkts_prct); bytes_chosen += x->bytes[proto[i]]; pkts_chosen += x->pkts[proto[i]]; } bytes_prct = 100 - (100 * (float) bytes_chosen / bytes_all); pkts_prct = 100 - (100 * (float) pkts_chosen / pkts_all); len += sprintf(s + len, "Other %5.2f %5.2f\n", bytes_prct, pkts_prct); return len; } static size_t print_gnuplot(FLOWDESC * x, char * s, int num_proto, uint8_t * proto) { size_t len; uint64_t bytes_all; float bytes_sofar; float bytes_prct; int i; len = sprintf(s, "%u ", (uint) TS2SEC(x->ts)); /* compute the sums of all bytes and packets */ bytes_all = 0; for (i = 0; i < IPPROTO_MAX; i++) bytes_all += x->bytes[i]; if (bytes_all == 0) return 0; /* compute the sums of all bytes and packets of interest */ bytes_sofar = 0; for (i = 0; i < num_proto; i++) { bytes_prct = 100 * (float) x->bytes[proto[i]] / bytes_all; len += sprintf(s + len, "%5.2f ", bytes_sofar + bytes_prct); bytes_sofar += bytes_prct; } len += sprintf(s + len, "100 \n"); return len; } static char * print(char *buf, size_t *len, __unused char * const args[]) { static char s[8192]; static uint8_t proto[256]; static int num_proto; static int fmt; static int granularity = 1; static int no_records = 0; static FLOWDESC values; FLOWDESC *x; int i; if (buf == NULL && args != NULL) { *len = do_header(args, s, &fmt, proto, &num_proto, &granularity); bzero(values.bytes, sizeof(values.bytes)); bzero(values.pkts, sizeof(values.pkts)); return s; } if (buf == NULL && args == NULL) { *len = 0; if (fmt == PRINT_GNUPLOT) *len = sprintf(s, GNUPLOTFOOTER); return s; } x = (FLOWDESC *) buf; values.ts = NTOHLL(x->ts); /* aggregate records if needed */ for (i = 0; i < IPPROTO_MAX; i++) { values.bytes[i] += NTOHLL(x->bytes[i]); values.pkts[i] += NTOHLL(x->pkts[i]); } no_records++; if (no_records % granularity != 0) { *len = 0; return s; } for (i = 0; i < IPPROTO_MAX; i++) { values.bytes[i] /= granularity; values.pkts[i] /= granularity; } if (fmt == PRINT_PLAIN) *len = print_plain(&values, s); else if (fmt == PRINT_PRETTY) *len = print_pretty(&values, s, num_proto, proto); else if (fmt == PRINT_GNUPLOT) *len = print_gnuplot(&values, s, num_proto, proto); bzero(values.bytes, sizeof(values.bytes)); bzero(values.pkts, sizeof(values.pkts)); return s; }; callbacks_t callbacks = { ca_recordsize: sizeof(FLOWDESC), ex_recordsize: 0, st_recordsize: sizeof(FLOWDESC), indesc: NULL, outdesc: NULL, init: init, check: NULL, hash: NULL, match: NULL, update: update, ematch: NULL, export: NULL, compare: NULL, action: NULL, store: store, load: load, print: print, replay: NULL };
2.1875
2
2024-11-18T18:54:18.125210+00:00
2019-11-26T08:11:16
0f5d21d398f5f340c4bc564aebbc3069c3324d01
{ "blob_id": "0f5d21d398f5f340c4bc564aebbc3069c3324d01", "branch_name": "refs/heads/master", "committer_date": "2019-11-26T08:11:16", "content_id": "e4273b28fb3d35fc2bb8d2ee46e1d0a8f7cf9192", "detected_licenses": [ "Apache-2.0" ], "directory_id": "82b23e02502bbc52cc95a31d8e279cd1c16b3c1e", "extension": "c", "filename": "power_meter_test.c", "fork_events_count": 1, "gha_created_at": "2019-11-22T01:05:24", "gha_event_created_at": "2019-11-22T01:05:25", "gha_language": null, "gha_license_id": "Apache-2.0", "github_id": 223294917, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2905, "license": "Apache-2.0", "license_type": "permissive", "path": "/components/general/power_meter/test/power_meter_test.c", "provenance": "stackv2-0011.json.gz:128008", "repo_name": "serenagrl/esp-iot-solution", "revision_date": "2019-11-26T08:11:16", "revision_id": "383eccec109c7aad39419456002c236b327b9286", "snapshot_id": "0cb5ea433550536e40cf9cba236e2500788798b5", "src_encoding": "UTF-8", "star_events_count": 5, "url": "https://raw.githubusercontent.com/serenagrl/esp-iot-solution/383eccec109c7aad39419456002c236b327b9286/components/general/power_meter/test/power_meter_test.c", "visit_date": "2020-09-14T23:35:38.031402" }
stackv2
// Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "iot_power_meter.h" #include "esp_log.h" #include "unity.h" #define PM_CF_IO_NUM 25 #define PM_CFI_IO_NUM 26 #define PM_CF_PCNT_UNIT PCNT_UNIT_0 #define PM_CFI_PCNT_UNIT PCNT_UNIT_1 #define PM_POWER_PARAM 1293699 #define PM_VOLTAGE_PARAM 102961 #define PM_CURRENT_PARAM 13670 static const char* TAG = "powermeter_test"; pm_handle_t pm_handle; static void read_value(void* arg) { pm_handle_t pm_handle = arg; for (int i = 0; i < 2; i++) { iot_powermeter_change_mode(pm_handle, PM_SINGLE_VOLTAGE); vTaskDelay(5000 / portTICK_RATE_MS); ESP_LOGI(TAG, "value of power:%d", iot_powermeter_read(pm_handle, PM_POWER)); ESP_LOGI(TAG, "value of voltage:%d", iot_powermeter_read(pm_handle, PM_VOLTAGE)); ESP_LOGI(TAG, "value of current:%d", iot_powermeter_read(pm_handle, PM_CURRENT)); iot_powermeter_change_mode(pm_handle, PM_SINGLE_CURRENT); vTaskDelay(5000 / portTICK_RATE_MS); ESP_LOGI(TAG, "value of power:%d", iot_powermeter_read(pm_handle, PM_POWER)); ESP_LOGI(TAG, "value of voltage:%d", iot_powermeter_read(pm_handle, PM_VOLTAGE)); ESP_LOGI(TAG, "value of current:%d", iot_powermeter_read(pm_handle, PM_CURRENT)); } vTaskDelete(NULL); } void power_meter_test() { printf("before power meter create, heap: %d\n", esp_get_free_heap_size()); pm_config_t pm_conf = { .power_io_num = PM_CF_IO_NUM, .power_pcnt_unit = PCNT_UNIT_0, .power_ref_param = PM_POWER_PARAM, .voltage_io_num = PM_CFI_IO_NUM, .voltage_pcnt_unit = PCNT_UNIT_1, .voltage_ref_param = PM_VOLTAGE_PARAM, .current_io_num = PM_CFI_IO_NUM, .current_pcnt_unit = PCNT_UNIT_1, .current_ref_param = PM_CURRENT_PARAM, .sel_io_num = 17, .sel_level = 0, .pm_mode = PM_SINGLE_VOLTAGE }; pm_handle = iot_powermeter_create(pm_conf); xTaskCreate(read_value, "read_value", 2048, pm_handle, 5, NULL); vTaskDelay(60000 / portTICK_RATE_MS); iot_powermeter_delete(pm_handle); printf("after power meter delete, heap: %d\n", esp_get_free_heap_size()); } TEST_CASE("Power meter test", "[power_meter][iot]") { power_meter_test(); }
2.15625
2
2024-11-18T19:03:54.036700+00:00
2019-07-21T23:23:32
f814c5964e4aa5a2e8160e505248d7eb396d833c
{ "blob_id": "f814c5964e4aa5a2e8160e505248d7eb396d833c", "branch_name": "refs/heads/master", "committer_date": "2019-07-21T23:23:32", "content_id": "1d93594bd132f41614c2d7d9b69554ed2f0a239b", "detected_licenses": [ "MIT" ], "directory_id": "c3f49a390ce4a68bc1da560077d11b7e1f340e4f", "extension": "c", "filename": "gps.c", "fork_events_count": 0, "gha_created_at": "2019-07-21T00:50:32", "gha_event_created_at": "2019-07-21T00:50:32", "gha_language": null, "gha_license_id": "MIT", "github_id": 197996118, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2635, "license": "MIT", "license_type": "permissive", "path": "/src/gps.c", "provenance": "stackv2-0012.json.gz:66", "repo_name": "justinnuwin/libgps", "revision_date": "2019-07-21T23:23:32", "revision_id": "a7ae425d63eabe6015f94e12cbc31a3df127c49d", "snapshot_id": "f393a0529ab2767221f065bbf19a56f02bea23f7", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/justinnuwin/libgps/a7ae425d63eabe6015f94e12cbc31a3df127c49d/src/gps.c", "visit_date": "2022-01-25T10:20:27.251639" }
stackv2
#include "gps.h" #include <stdio.h> #include <stdlib.h> #include <math.h> #include "nmea.h" #include "serial.h" gpgga_t gpgga; gprmc_t gprmc; extern void gps_init(void) { serial_init(); serial_config(); //Write commands } extern void gps_on(void) { //Write on } #define MAX(x, y) (((x) > (y)) ? (x) : (y)) // Compute the GPS location using decimal scale // returns 0 if using old data // returns 1 if using new data extern int gps_location(loc_t *coord) { char buffer[256]; int data_ready = serial_readln(buffer); if (!data_ready) { coord->hour = MAX(gpgga.hour, gprmc.hour); coord->minute = MAX(gpgga.minute, gprmc.minute); coord->second = MAX(gpgga.second, gprmc.second); coord->latitude = gpgga.latitude; coord->longitude = gpgga.longitude; coord->altitude = gpgga.altitude; coord->speed = gprmc.speed; coord->course = gprmc.course; } else { switch (nmea_get_message_type(buffer)) { case NMEA_GPGGA: nmea_parse_gpgga(buffer, &gpgga); gps_convert_deg_to_dec(&(gpgga.latitude), gpgga.lat, &(gpgga.longitude), gpgga.lon); coord->hour = gpgga.hour; coord->minute = gpgga.minute; coord->second = gpgga.second; coord->latitude = gpgga.latitude; coord->longitude = gpgga.longitude; coord->altitude = gpgga.altitude; break; case NMEA_GPRMC: nmea_parse_gprmc(buffer, &gprmc); coord->hour = gprmc.hour; coord->minute = gprmc.minute; coord->second = gprmc.second; coord->speed = gprmc.speed; coord->course = gprmc.course; break; } } return data_ready; } extern void gps_off(void) { //Write off serial_close(); } // Convert lat e lon to decimals (from deg) void gps_convert_deg_to_dec(double *latitude, char ns, double *longitude, char we) { double lat = (ns == 'N') ? *latitude : -1 * (*latitude); double lon = (we == 'E') ? *longitude : -1 * (*longitude); *latitude = gps_deg_dec(lat); *longitude = gps_deg_dec(lon); } double gps_deg_dec(double deg_point) { double ddeg; double sec = modf(deg_point, &ddeg)*60; int deg = (int)(ddeg/100); int min = (int)(deg_point-(deg*100)); double absdlat = round(deg * 1000000.); double absmlat = round(min * 1000000.); double absslat = round(sec * 1000000.); return round(absdlat + (absmlat/60) + (absslat/3600)) /1000000; }
2.875
3
2024-11-18T19:06:09.161648+00:00
2022-02-27T05:57:24
077a212a803536da9125efd0b01bc1d6d1022f66
{ "blob_id": "077a212a803536da9125efd0b01bc1d6d1022f66", "branch_name": "refs/heads/master", "committer_date": "2022-02-27T05:57:24", "content_id": "5b5eb2c7236b4c0bd8ff78feab3f6da70a09e58b", "detected_licenses": [ "MIT" ], "directory_id": "4ae693a814655469f58f2f5b933cfc56e3d5c315", "extension": "c", "filename": "hc05.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 242269564, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5055, "license": "MIT", "license_type": "permissive", "path": "/STM32_Resources/Bluetooth_Module_Test/Source_Code_(Lib)/HARDWARE/HC05/hc05.c", "provenance": "stackv2-0012.json.gz:1603", "repo_name": "Shuzhengz/Projects-Code", "revision_date": "2022-02-27T05:57:24", "revision_id": "1b9608004a682b1da4e31f3160736e5b2c52fb33", "snapshot_id": "b8389d9bd365b45c1f09157c75f27cecdf9ed43d", "src_encoding": "GB18030", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Shuzhengz/Projects-Code/1b9608004a682b1da4e31f3160736e5b2c52fb33/STM32_Resources/Bluetooth_Module_Test/Source_Code_(Lib)/HARDWARE/HC05/hc05.c", "visit_date": "2022-03-05T09:48:19.403676" }
stackv2
#include "delay.h" #include "usart.h" #include "usart3.h" #include "hc05.h" #include "led.h" #include "string.h" #include "math.h" ////////////////////////////////////////////////////////////////////////////////// //本程序只供学习使用,未经作者许可,不得用于其它任何用途 //ALIENTEK STM32开发板 //ATK-HC05蓝牙模块驱动代码 //正点原子@ALIENTEK //技术论坛:www.openedv.com //修改日期:2015/3/29 //版本:V1.1 //版权所有,盗版必究。 //Copyright(C) 广州市星翼电子科技有限公司 2009-2019 //All rights reserved //******************************************************************************** //V1.1 20140329 //修改LED的连接,原来接PC5,改为PA4,以兼容MiniSTM32开发板V3.0 ////////////////////////////////////////////////////////////////////////////////// //初始化ATK-HC05模块 //返回值:0,成功;1,失败. u8 HC05_Init(void) { u8 retry=10,t; u8 temp=1; GPIO_InitTypeDef GPIO_InitStructure; RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE); //使能PORTA GPIO_InitStructure.GPIO_Pin = GPIO_Pin_15; // 端口配置 GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU; //上拉输入 GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; //IO口速度为50MHz GPIO_Init(GPIOA, &GPIO_InitStructure); //根据设定参数初始化A15 GPIO_InitStructure.GPIO_Pin = GPIO_Pin_4; // 端口配置 GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP; //推挽输出 GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; //IO口速度为50MHz GPIO_Init(GPIOA, &GPIO_InitStructure); //根据设定参数初始化GPIOA4 GPIO_SetBits(GPIOA,GPIO_Pin_4); GPIO_PinRemapConfig(GPIO_Remap_SWJ_JTAGDisable,ENABLE); HC05_KEY=1; HC05_LED=1; usart3_init(9600); //初始化串口2为:9600,波特率. while(retry--) { HC05_KEY=1; //KEY置高,进入AT模式 delay_ms(10); u3_printf("AT\r\n"); //发送AT测试指令 HC05_KEY=0; //KEY拉低,退出AT模式 for(t=0;t<10;t++) //最长等待50ms,来接收HC05模块的回应 { if(USART3_RX_STA&0X8000)break; delay_ms(5); } if(USART3_RX_STA&0X8000) //接收到一次数据了 { temp=USART3_RX_STA&0X7FFF; //得到数据长度 USART3_RX_STA=0; if(temp==4&&USART3_RX_BUF[0]=='O'&&USART3_RX_BUF[1]=='K') { temp=0;//接收到OK响应 break; } } } if(retry==0)temp=1; //检测失败 return temp; } //获取ATK-HC05模块的角色 //返回值:0,从机;1,主机;0XFF,获取失败. u8 HC05_Get_Role(void) { u8 retry=0X0F; u8 temp,t; while(retry--) { HC05_KEY=1; //KEY置高,进入AT模式 delay_ms(10); u3_printf("AT+ROLE?\r\n"); //查询角色 for(t=0;t<20;t++) //最长等待200ms,来接收HC05模块的回应 { delay_ms(10); if(USART3_RX_STA&0X8000)break; } HC05_KEY=0; //KEY拉低,退出AT模式 if(USART3_RX_STA&0X8000) //接收到一次数据了 { temp=USART3_RX_STA&0X7FFF; //得到数据长度 USART3_RX_STA=0; if(temp==13&&USART3_RX_BUF[0]=='+')//接收到正确的应答了 { temp=USART3_RX_BUF[6]-'0';//得到主从模式值 break; } } } if(retry==0)temp=0XFF;//查询失败. return temp; } //ATK-HC05设置命令 //此函数用于设置ATK-HC05,适用于仅返回OK应答的AT指令 //atstr:AT指令串.比如:"AT+RESET"/"AT+UART=9600,0,0"/"AT+ROLE=0"等字符串 //返回值:0,设置成功;其他,设置失败. u8 HC05_Set_Cmd(u8* atstr) { u8 retry=0X0F; u8 temp,t; while(retry--) { HC05_KEY=1; //KEY置高,进入AT模式 delay_ms(10); u3_printf("%s\r\n",atstr); //发送AT字符串 HC05_KEY=0; //KEY拉低,退出AT模式 for(t=0;t<20;t++) //最长等待100ms,来接收HC05模块的回应 { if(USART3_RX_STA&0X8000)break; delay_ms(5); } if(USART3_RX_STA&0X8000) //接收到一次数据了 { temp=USART3_RX_STA&0X7FFF; //得到数据长度 USART3_RX_STA=0; if(temp==4&&USART3_RX_BUF[0]=='O')//接收到正确的应答了 { temp=0; break; } } } if(retry==0)temp=0XFF;//设置失败. return temp; } /////////////////////////////////////////////////////////////////////////////////////////////////// //通过该函数,可以利用USMART,调试接在串口3上的ATK-HC05模块 //str:命令串.(这里注意不再需要再输入回车符) void HC05_CFG_CMD(u8 *str) { u8 temp; u8 t; HC05_KEY=1; //KEY置高,进入AT模式 delay_ms(10); u3_printf("%s\r\n",(char*)str); //发送指令 for(t=0;t<50;t++) //最长等待500ms,来接收HC05模块的回应 { if(USART3_RX_STA&0X8000)break; delay_ms(10); } HC05_KEY=0; //KEY拉低,退出AT模式 if(USART3_RX_STA&0X8000) //接收到一次数据了 { temp=USART3_RX_STA&0X7FFF; //得到数据长度 USART3_RX_STA=0; USART3_RX_BUF[temp]=0; //加结束符 printf("\r\n%s",USART3_RX_BUF);//发送回应数据到串口1 } }
2.28125
2
2024-11-18T19:06:09.253139+00:00
2014-03-16T19:02:22
7e2d03208e92bc29518be68b239c7b15557e6326
{ "blob_id": "7e2d03208e92bc29518be68b239c7b15557e6326", "branch_name": "refs/heads/master", "committer_date": "2014-03-16T19:02:22", "content_id": "a9c71660cba5f99467f1ca43c6de1e2deb47e558", "detected_licenses": [ "MIT" ], "directory_id": "83ea0613aee07d6c668b34b83947f204254bc61e", "extension": "c", "filename": "set.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1636, "license": "MIT", "license_type": "permissive", "path": "/src/set.c", "provenance": "stackv2-0012.json.gz:1731", "repo_name": "vighneshbirodkar/vigredis", "revision_date": "2014-03-16T19:02:22", "revision_id": "f357fe65f42261151c101bbbb289136f84ff8d04", "snapshot_id": "507eb83f9f614bbd8d7a8fbb70f9587806dc0555", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/vighneshbirodkar/vigredis/f357fe65f42261151c101bbbb289136f84ff8d04/src/set.c", "visit_date": "2016-09-11T05:07:01.788655" }
stackv2
/* * an ordered set implementation * each element is stores in the sets dictionary as well as its skip_list */ #include"set.h" #include "dict.h" #include"skip_list.h" #include <stdlib.h> #include <stdio.h> #include "util.h" /* * initialization */ void set_init(set *s) { dict_init(&s->set_dict,VR_TYPE_DOUBLE); skip_list_init(&s->set_list); s->len = 0; } /* * adds `key` with `score` to `s` * if `key` existed its score is updated * returns * VR_ERR_OK if member was absent * VR_ERR_EXIST if member was present */ int set_add(set *s,char* key,int klen,double score) { int ret; double exp; vr_object *obj; obj = dict_get(&s->set_dict,key,klen,&exp); if( obj == NULL) { ret = dict_add_double(&s->set_dict,key,klen,score,VR_FLAG_NONE,-1); skip_list_insert(&s->set_list,score,key,klen); if(ret != VR_ERR_OK) printf("Fatal : Key which is not supposed to exists, does exist\n"); s->len = s->len + 1; //printf("set len = %d value = %lf\n",s->len,score); } else { if(VR_EQ(score,obj->value)) return VR_ERR_EXIST; skip_list_delete_with_key(&s->set_list,obj->value,key,klen); ret = dict_add_double(&s->set_dict,key,klen,score,VR_FLAG_NONE,-1); skip_list_insert(&s->set_list,score,key,klen); if(ret != VR_ERR_EXIST) printf("Fatal : Key which is supposed to exist, does not exist\n"); } return ret; } void set_print(set* s) { skip_list_print(&s->set_list); } void set_clear(set *s) { dict_clear(&s->set_dict); skip_list_clear(&s->set_list); }
3.0625
3
2024-11-18T19:27:05.241532+00:00
2020-03-19T13:50:10
9a23979d378f22770d255c7d0f08adeaaad2cd50
{ "blob_id": "9a23979d378f22770d255c7d0f08adeaaad2cd50", "branch_name": "refs/heads/master", "committer_date": "2020-03-19T13:50:10", "content_id": "964fef27055c2c4022a466211bced8ce0460457b", "detected_licenses": [ "MIT" ], "directory_id": "4edf16dd911e3e8a4d70e56cda144549958b5c5c", "extension": "c", "filename": "staticsinglelinklist.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 246052084, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 9071, "license": "MIT", "license_type": "permissive", "path": "/staticsinglelinklist.c", "provenance": "stackv2-0012.json.gz:180927", "repo_name": "Liuxingwei/data-structure-c99", "revision_date": "2020-03-19T13:50:10", "revision_id": "48ab0c6ddd1246129771ac35f7b4b20daaa36dff", "snapshot_id": "ead09f4096397635db44adf08628bf6a42b6a6b9", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Liuxingwei/data-structure-c99/48ab0c6ddd1246129771ac35f7b4b20daaa36dff/staticsinglelinklist.c", "visit_date": "2021-03-04T17:13:30.578018" }
stackv2
/** * 静态链表实现示例 * 数据元素为整型 */ #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #define OK true #define ERROR false /** * 线性表所能存储的元素的最大值(数组的定义长度) * 为方便测试边界情况,暂定义为较小的值 */ #define MAXSIZE 10 #define OUTFAIL(PARAM) \ printf("Function \"%s\" test fail. line is %d.\n", functionName, \ __LINE__); \ return PARAM; #define OUTSUCCESS(PARAM) \ printf("Function \"%s\" test success.\n", functionName); \ return PARAM; /** * 定义线性表所存储的元素类型 */ typedef int ElementType; /** * 定义需要同时获取「执行是否成功」标志类型 */ typedef bool Status; /** * 节点类型 */ typedef struct { ElementType value; int next; } Node; /** * 静态链表类型 */ typedef struct { Node nodes[MAXSIZE]; int length; } StaticSingleLinkList; /** * 初始化 listPointer 指向的静态链表 */ Status initList(StaticSingleLinkList *listPointer); /** * 为节点分配空间,返回新空间的位置索引 */ int mallocSsll(StaticSingleLinkList *listPointer); /** * 释放指定索引的节点空间 */ Status freeSsll(StaticSingleLinkList *listPointer, int index); /** * 判断线性表 list 是否为空。为空返回 true,不为空返回 false */ bool isEmpty(StaticSingleLinkList list); /** * 清空 listPointer 指针指向的线性表。执行成功返回 OK,失败返回 ERROR */ Status clearList(StaticSingleLinkList *listPointer); /** * 删除 listPointer 指针指向的线性表的第 index 个元素,并将删除的元素值放在 * elementPointer 指针指向的变量中 执行成功返回 OK,失败返回 ERROR */ Status deleteElement(StaticSingleLinkList *listPointer, int index, ElementType *elementPointer); /** * 计算线性表 list 的长度 */ int listLen(StaticSingleLinkList list); /** * 使用连续 count 个整数填 listPointer 指针指向的线性表,起始数值为 3。 * 用于在测试时初始化线性表 */ void setup(StaticSingleLinkList *listPointer, int count); /** * listPointer 函数的测试函数 */ void testInitList(); /** * mallocSsll 函数的测试函数 */ void testMallocSsll(); /** * freeSsll 函数的测试函数 */ void testFreeSsll(); /** * isEmpty 函数的测试函数 */ void testIsEmpty(); /** * deleteElement 函数的测试函数 */ void testDeleteElement(); /** * clearList 函数的测试函数 */ void testClearList(); /** * listLen 函数的测试函数 */ void testListLen(); Status initList(StaticSingleLinkList *listPointer) { int i; for (i = 0; i < MAXSIZE - 1; ++i) { listPointer->nodes[i].value = 0; listPointer->nodes[i].next = i + 1; } listPointer->nodes[i].value = 0; listPointer->nodes[i].next = 0; listPointer->length = 0; return OK; } int mallocSsll(StaticSingleLinkList *listPointer) { if (listPointer->nodes[0].next >= MAXSIZE - 1) { return 0; } int i = listPointer->nodes[0].next; listPointer->nodes[0].next = listPointer->nodes[i].next; return i; } Status freeSsll(StaticSingleLinkList *listPointer, int index) { if (index < 1 || index >= MAXSIZE - 1) { return ERROR; } Node node = listPointer->nodes[0]; while (MAXSIZE - 1 != node.next) { if (node.next == index) { return OK; } node = listPointer->nodes[node.next]; } listPointer->nodes[index].next = listPointer->nodes[0].next; listPointer->nodes[0].next = index; listPointer->nodes[index].value = 0; return OK; } bool isEmpty(StaticSingleLinkList list) { return 0 == list.length; } Status clearList(StaticSingleLinkList *listPointer) { return initList(listPointer); } Status deleteElement(StaticSingleLinkList *listPointer, int index, ElementType *valuePointer) { if (index < 1 || index > listLen(*listPointer)) { return ERROR; } int t, i; Node *n = &(listPointer->nodes[MAXSIZE - 1]); for (i = 1; i < index; ++i) { n = &(listPointer->nodes[n->next]); } t = n->next; n->next = listPointer->nodes[t].next; *valuePointer = listPointer->nodes[t].value; freeSsll(listPointer, t); return OK; } int listLen(StaticSingleLinkList list) { return list.length; } void main() { testInitList(); testMallocSsll(); testFreeSsll(); testIsEmpty(); testClearList(); testDeleteElement(); testListLen(); } void setup(StaticSingleLinkList *listPointer, int count) { int i; for (i = 0; i < MAXSIZE - 1; ++i) { listPointer->nodes[i].value = 0; listPointer->nodes[i].next = i + 1; } listPointer->nodes[i].value = 0; listPointer->nodes[i].next = 0; for (i = 1; i <= count; ++i) { listPointer->nodes[i].value = i + 2; } if (count > 0) { listPointer->nodes[MAXSIZE - 1].next = 1; listPointer->nodes[count].next = 0; } listPointer->nodes[0].next = i; listPointer->length = count; } void testInitList() { char functionName[] = "initList"; StaticSingleLinkList list; if (!initList(&list)) { OUTFAIL(); } if (0 != list.length) { OUTFAIL(); } int i; for (i = 1; i < MAXSIZE - 1; ++i) { if (i + 1 != list.nodes[i].next || 0 != list.nodes[i].value) { OUTFAIL(); } } if (0 != list.nodes[i].next || 0 != list.nodes[i].value) { OUTFAIL(); } OUTSUCCESS(); } void testMallocSsll() { char functionName[] = "mallocSsll"; StaticSingleLinkList list; setup(&list, 0); int newIndex = mallocSsll(&list); if (1 != newIndex) { OUTFAIL(); } if (2 != list.nodes[0].next) { OUTFAIL(); } setup(&list, 5); newIndex = mallocSsll(&list); if (6 != newIndex) { OUTFAIL(); } if (7 != list.nodes[0].next) { OUTFAIL(); } setup(&list, 8); newIndex = mallocSsll(&list); if (0 != newIndex) { OUTFAIL(); } if (9 != list.nodes[0].next) { OUTFAIL(); } OUTSUCCESS(); } void testFreeSsll() { char functionName[] = "freeSsll"; StaticSingleLinkList list; setup(&list, 0); if (freeSsll(&list, 0)) { OUTFAIL(); } if (freeSsll(&list, 9)) { OUTFAIL(); } if (!freeSsll(&list, 3) || 1 != list.nodes[0].next) { OUTFAIL(); } setup(&list, 5); if (!freeSsll(&list, 3) || 3 != list.nodes[0].next || 6 != list.nodes[3].next) { OUTFAIL(); } OUTSUCCESS(); } void testIsEmpty() { char functionName[] = "isEmpty"; StaticSingleLinkList list; list.length = 0; if (!isEmpty(list)) { OUTFAIL(); } list.length = 3; if (isEmpty(list)) { OUTFAIL(); } OUTSUCCESS(); } void testClearList() { char functionName[] = "clearList"; StaticSingleLinkList list; int i; setup(&list, 0); if (!clearList(&list)) { OUTFAIL(); } if (0 != list.length) { OUTFAIL(); } for (i = 0; i < MAXSIZE - 1; ++i) { if (i + 1 != list.nodes[i].next) { OUTFAIL(); } } if (0 != list.nodes[i].next) { OUTFAIL(); } setup(&list, 6); if (!clearList(&list)) { OUTFAIL(); } if (0 != list.length) { OUTFAIL(); } for (i = 0; i < MAXSIZE - 1; ++i) { if (i + 1 != list.nodes[i].next) { OUTFAIL(); } } if (0 != list.nodes[i].next) { OUTFAIL(); } OUTSUCCESS(); } void testDeleteElement() { char functionName[] = "deleteElement"; StaticSingleLinkList list; ElementType value; setup(&list, 5); if (deleteElement(&list, 0, &value)) { OUTFAIL(); } if (deleteElement(&list, 6, &value)) { OUTFAIL(); } if (!deleteElement(&list, 3, &value)) { OUTFAIL(); } if (5 != value) { OUTFAIL(); } if (1 != list.nodes[MAXSIZE - 1].next || 2 != list.nodes[1].next || 4 != list.nodes[2].next || 5 != list.nodes[4].next || 0 != list.nodes[5].next) { OUTFAIL(); } if (3 != list.nodes[0].next || 6 != list.nodes[3].next || 7 != list.nodes[6].next || 8 != list.nodes[7].next || 9 != list.nodes[8].next) { OUTFAIL(); } if (3 != list.nodes[1].value || 4 != list.nodes[2].value || 6 != list.nodes[4].value || 7 != list.nodes[5].value) { OUTFAIL(); } OUTSUCCESS(); } void testListLen() { char functionName[] = "listLen"; StaticSingleLinkList list; list.length = 0; if (0 != listLen(list)) { OUTFAIL(); } list.length = 5; if (5 != listLen(list)) { OUTFAIL(); } OUTSUCCESS(); }
3.515625
4
2024-11-18T19:27:06.313397+00:00
2020-01-13T10:29:58
c919c044db163768defc76b5e342946061b069b1
{ "blob_id": "c919c044db163768defc76b5e342946061b069b1", "branch_name": "refs/heads/master", "committer_date": "2020-01-13T10:29:58", "content_id": "633d1d8adcde4d511a8abde22692d415d921936a", "detected_licenses": [ "MIT" ], "directory_id": "25177caf80f8519f2ba34b0d394981db154eae54", "extension": "c", "filename": "main.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 328032664, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5992, "license": "MIT", "license_type": "permissive", "path": "/src/main.c", "provenance": "stackv2-0012.json.gz:181699", "repo_name": "mnassabain/BLASter", "revision_date": "2020-01-13T10:29:58", "revision_id": "8a3ef015d3751de977b08d3fbd482be8c8c4962e", "snapshot_id": "16585ea6a9de215288a8cefa58633f3cea9830d6", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/mnassabain/BLASter/8a3ef015d3751de977b08d3fbd482be8c8c4962e/src/main.c", "visit_date": "2023-02-12T10:31:14.773108" }
stackv2
#include <stdio.h> #include <getopt.h> #include "ast.h" #include "y.tab.h" #include "specParser.h" #include "symbolsTable.h" int DEBUG_LEX = 0; int opt_print_ast = 0; int opt_print_symbol_table = 0; extern FILE* yyin; extern FILE* zzin; extern ast arbre; extern ast specTree; extern symbolTable st; extern void lex_zzfree(); // lexer spec extern void lex_yyfree(); // lexer file char * output_file = NULL; FILE* output_d; int options(int argc, char** argv); int main (int argc, char** argv) { int idx = options(argc, argv); if (output_file != NULL) { output_d = fopen(output_file, "w"); if (output_d == NULL) { fprintf(stderr, "Unable to open file %s", output_file); return 1; } } else { output_d = stdout; } // Init table des symboles st = create_symbolt(); char* input_source = argv[idx]; char* specif_source = argv[idx+1]; FILE* input = fopen (input_source, "r"); // FILE* f = fopen ("exemple.c", "r"); if (input == NULL) { fprintf(stderr, "Unable to open file"); return 1; } yyin = input; printf("PARSING INPUT FILE ...\n"); yyparse(); // parse source code // Affichage de l'arbre if (opt_print_ast == 1) { printf("Tree before replacing :\n"); print_ast(arbre); } // print_code(arbre, 0); replace(arbre); if (opt_print_ast == 1) { printf("\nTree after replacing :\n"); print_ast(arbre); } // print_code(arbre, 0); if (opt_print_symbol_table == 1) { printf("\n****************** Table des symboles ******************\n"); display_symbolt(st); printf("**************** Fin table des symboles ****************\n"); } //////////////////////////////////////////////////////////////////////////// // FILE* spec = fopen ("spec.c", "r"); // FILE* f = fopen ("exemple.c", "r"); FILE* spec = fopen(specif_source, "r"); if (spec == NULL) { fprintf(stderr, "Unable to open file"); return 1; } zzin = spec; printf("\n\nPARSING SPEC FILE ...\n"); zzparse(); if (opt_print_ast == 1) { print_ast(specTree); } // print_code(specTree, 0); //////////////////////////////////////////////////////////////////////////// // / TESTING COMPARAISON // ast code = arbre->first_child->first_child->next->next->first_child; // // print_ast(code); // ast func = specTree->first_child->first_child->next->next->first_child->first_child; // // print_ast(func); // func = specTree->first_child; // ast ptr, res; // char* name; // while (func != NULL) { // name = func->first_child->first_child->id; // ptr = func->first_child->next->next->first_child->first_child; // printf("func name : %s\n", name); // // print_ast(ptr); // res = recursive_search(arbre, ptr); // while (res != NULL) { // printf("FOUND FUNCTION %s !!!!!!!!!\n", name); // ast new_func = new_node(AST_FUNC); // add_child_node(new_func, new_id(strdup(name))); // // ast arguments = new_list(AST_ARGS); // add_child_node(new_func, new_id(strdup("arguments"))); // replace_node(res, new_func); // res = recursive_search(arbre, ptr); // } // func = func->next; // } // if (compare_real(code, func) == 1) { // printf("SUCCESS\n"); // } else { // printf("FAILED\n"); // } //////////////////////////////////////////////////////////////////////////// // output print_code(arbre, 0); // Clean delete_node(arbre); delete_node(specTree); lex_zzfree(); lex_yyfree(); free_symbolt(st); fclose(input); fclose(spec); return 0; } int options (int argc, char** argv) { printf("\n888888b. 888 d8888 .d8888b. 888\n"); printf("888 \"88b 888 d88888 d88P Y88b 888\n"); printf("888 .88P 888 d88P888 Y88b. 888\n"); printf("8888888K. 888 d88P 888 \"Y888b. 888888 .d88b. 888d888\n"); printf("888 \"Y88b 888 d88P 888 \"Y88b. 888 d8P Y8b 888P\"\n"); printf("888 888 888 d88P 888 \"888 888 88888888 888\n"); printf("888 d88P 888 d8888888888 Y88b d88P Y88b. Y8b. 888\n"); printf("8888888P\" 88888888 d88P 888 \"Y8888P\" \"Y888 \"Y8888 888\n"); printf("\n888888888888888888888888888888888888888888888888888888888888888888\n\n"); int opt, optindex = 0; struct option options[] = { {"version", no_argument, 0, 'v' }, {"tos", no_argument, 0, 't' }, {"ast", no_argument, 0, 'a' }, {"output", no_argument, 0, 'o' } }; while((opt = getopt_long(argc, argv, "vtao:", options, &optindex)) != -1) { switch(opt) { case 'v': printf("Membres du projet:\n"); printf(" * CHRISTOFFEL Quentin\n"); printf(" * WENDLING Nicolas\n"); printf(" * NASSABAIN Marco\n"); break; case 't': // printf("option tos\n"); opt_print_symbol_table = 1; break; case 'a': // printf("option ast\n"); opt_print_ast = 1; break; case 'o': printf("option output with arg: %s\n", optarg); output_file = optarg; break; case '?': break; default: // printf("option non gérée\n"); abort(); } } if (argc - optind != 2) { fprintf(stderr, "Error: needs 2 arguments : input_file spec_file\n"); exit(1); } return optind; }
2.046875
2
2024-11-18T19:27:06.392063+00:00
2021-05-15T18:27:56
2efbd5edb7098c13042f31bf1145658ca3b5cfac
{ "blob_id": "2efbd5edb7098c13042f31bf1145658ca3b5cfac", "branch_name": "refs/heads/master", "committer_date": "2021-05-15T18:27:56", "content_id": "b4279cb155db1559490b5526f5ed957362a4fbd5", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "1cdab5d61d1f56885022718aa45079ff315e586b", "extension": "c", "filename": "blind2.c", "fork_events_count": 1, "gha_created_at": "2019-02-13T10:51:04", "gha_event_created_at": "2021-05-15T18:27:56", "gha_language": "C++", "gha_license_id": "BSD-3-Clause", "github_id": 170491521, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 11936, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/external/reference_impls/deep-shallow/blind2.c", "provenance": "stackv2-0012.json.gz:181828", "repo_name": "sacabench/sacabench", "revision_date": "2021-05-15T18:27:56", "revision_id": "e4cb5d3e1876e2ff66b60dc80ee49933ad502534", "snapshot_id": "a98ad021649e10535b57fd541033b0bc240306a9", "src_encoding": "UTF-8", "star_events_count": 16, "url": "https://raw.githubusercontent.com/sacabench/sacabench/e4cb5d3e1876e2ff66b60dc80ee49933ad502534/external/reference_impls/deep-shallow/blind2.c", "visit_date": "2021-06-05T14:46:58.932919" }
stackv2
/* >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> string sorting routine based on a blind tree 26-jun-01 ver 1.0 03-jul-01 ver 1.1 (get rid of node header) >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> */ #include <stdlib.h> #include <string.h> #include <stdio.h> #include "common.h" /* ================================================================== comment: it is a little triky how we handle the case in which there are two strings s1 s2 such that s1 is a prefix of s2. (the correct ordering is that s1 preceeds lexicographically s2) We proceed as follows. We insert the strings in order of increasing length so that s1 is inserted before s2. When s2 is inserted we put it in a leaf which is to the left of s1's leaf (obviously they have the same parent node). This is wrong acording to the alphabetic ordering but is done so that is there is a third string s3 which has s1 as a prefix we are certain that s3 meets s2's leaf and not s1's. When we traverse the trie to get the sorted string we check if there are two sibling with the same key and if so we invert them to get the correct ordering =================================================================== */ /* ------ external global variables ------- */ extern UChar *Text; // input string+ overshoot extern Int32 Text_size; // size of input string extern UChar *Upper_text_limit; // Text+Text_size /* ------- node of blind trie -------- */ typedef struct nodex { Int32 skip; UChar key; struct nodex *down; // first child struct nodex *right; // next brother } node; // -------- local global variables ------------------- #define BUFSIZE 1000 #define FREESIZE 5000 void *freearr[FREESIZE]; static node *bufn; static int bufn_num=0, free_num=0; static Int32 *Aux, Aux_written; node **Stack; int Stack_size; /* **************************************************************** routine for deep-sorting the suffixes a[0] ... a[n-1] knowing that they have a common prefix of length "depth" **************************************************************** */ void blind_ssort(Int32 *a, Int32 n, Int32 depth) { int neg_integer_cmp(const void *, const void *); node *find_companion(node *head, UChar *s); void insert_suffix(node *h, Int32 suf, int n, UChar mmchar); void traverse_trie(node *h); Int32 compare_suffixes(Int32 suf1, Int32 suf2, Int32 depth); void free_node_mem(); Int32 i,j,aj,lcp; node nh, *root, *h; // ---- sort suffixes in order of increasing length qsort(a,n, sizeof(Int32), neg_integer_cmp); // --- skip suffixes which have already reached the end-of-text for(j=0;j<n;j++) if(a[j]+depth < Text_size) break; if(j>=n-1) return; // everything is already sorted! // ------ init stack ------- Stack = (node **) malloc(n*sizeof(node *)); if(Stack==NULL) { fprintf(stderr,"Out of memory! (blind_ssort)\n"); exit(1); } // ------- init root with the first unsorted suffix nh.skip = -1; nh.right = NULL; nh.down = (void *) a[j]; root = &nh; // ------- insert suffixes a[j+1] ... a[n-1] for(i=j+1;i<n;i++) { h=find_companion(root, Text+a[i]); assert(h->skip==-1); assert(Stack_size<=i-j); aj=(Int32) h->down; assert(aj>a[i]); lcp = compare_suffixes(aj,a[i],depth); insert_suffix(root, a[i], lcp, Text[aj+lcp]); } // ---- traverse the trie and get suffixes in lexicographic order Aux=a; Aux_written = j; traverse_trie(root); assert(Aux_written==n); free_node_mem(); free(Stack); } /* *********************************************************************** this function traverses the trie rooted at head following the string s. Returns the leaf "corresponding" to the string s *********************************************************************** */ node *find_companion(node *head, UChar *s) { node *get_leaf(node *head); UChar c; node *p; int t; Stack_size = 0; // init stack while(head->skip >= 0) { Stack[Stack_size++] = head; t = head->skip; if(s+t>=Upper_text_limit) // s[t] does not exist: mismatch return get_leaf(head); c = s[t]; p = head->down; repeat: if(c==p->key) { // found branch corresponding to c head = p; continue; } else if(c<p->key) // no branch corresponding to c: mismatch return get_leaf(head); if((p=(p->right))==NULL) // no other branches: mismatch return get_leaf(head); goto repeat; // look at next branch } Stack[Stack_size++] = head; return head; } // this function returns a leaf below "head". // any leaf will do for the algorithm: we take the easiest to reach node *get_leaf(node *head) { assert(head->skip>=0); do { head = head->down; } while(head->skip>=0); return head; } __inline__ node *new_node__blind_ssort(void) { if(bufn_num-- == 0) { bufn = (node *) malloc(BUFSIZE * sizeof(node)); if(bufn==NULL) { fprintf(stderr,"Out of mem (new_node1)\n"); exit(1);} freearr[free_num++] = (void *) bufn; if(free_num>=FREESIZE) { fprintf(stderr,"Out of mem (new_node2)\n"); exit(1);} bufn_num = BUFSIZE-1; } return bufn++; } /* ***************************************************** insert a suffix in the trie rooted at *p. we know that the trie already contains a string which share the first n chars with suf ***************************************************** */ void insert_suffix(node *h, Int32 suf, int n, UChar mmchar) { Int32 t; UChar c, *s; node *p, **pp; s = Text + suf; #if 0 // ---------- find the insertion point while( (t=h->skip) < n) { if( t < 0) break; // insert "suf" just above *h c=s[t]; p=h->down; // in the list p there must be a branch corresponding to c repeat: if(c==p->key) { // found branch corresponding to c h = p; // go down continue; } if(c>p->key && p->right!=NULL) { p=p->right; goto repeat; } // no branch corresponding to c exists: this is a fatal error fprintf(stderr,"Error in blind_sort (insert_string)\n"); exit(1); } #else for(t=0;t<Stack_size;t++) { h=Stack[t]; if(h->skip<0 || h->skip>=n) break; } #endif assert(s[n]!=mmchar || h->skip==-1 || h->skip==n); // --------- insert a new node before node *h if necessary if(h->skip!=n) { p = new_node__blind_ssort(); // create and init new node p->key = mmchar; p->skip = h->skip; // p inherits skip and children of *h p->down = h->down; p->right = NULL; h->skip = n; h->down = p; // now *h has p as the only child } assert(h->skip==n); // -------- search the position of s[n] among *h offsprings c=s[n]; pp = &(h->down); while((*pp)!=NULL) { if((*pp)->key>=c) break; pp = &((*pp)->right); } // ------- insert new node containing suf p = new_node__blind_ssort(); p->skip = -1; p->key = c; p->right = *pp; *pp = p; p->down = (void *) suf; return; } /* ************************************************************ this procedures traverse the trie in depth first order so that the suffixes (stored in the leaf) are recovered in lexicographic order ************************************************************ */ void traverse_trie(node *h) { node *p, *nextp; if(h->skip<0) Aux[Aux_written++] = (Int32) h->down; else { p = h->down; assert(p!=NULL); do { nextp = p->right; if(nextp!=NULL) { assert(nextp->key>=p->key); // if there are 2 nodes with equal keys // they must be considered in inverted order if(nextp->key==p->key) { traverse_trie(nextp); traverse_trie(p); p = nextp->right; continue; } } traverse_trie(p); p=nextp; } while(p!=NULL); } } /* *********************************************************************** Function to compute the lcp of two strings originating from the *b1 and *b2 the parameter is the length of s1 (which is shortest than s2) if s1 is a prefix of s2 we return the length of s1 -1 The size of the unrolled loop must be at most equal to the costant Cmp_overshoot defined in common.h the function return the result of the comparison (+ or -) and writes in Cmp_done the number of comparisons done *********************************************************************** */ Int32 get_lcp_unrolled(UChar *b1, UChar *b2, Int32 cmp_limit) { Int32 cmp2do; UChar c1, c2; assert(b1 != b2); // execute blocks of 16 comparisons untill a difference // is found or we reach cmp_limit comparisons cmp2do = cmp_limit; do { // 1 c1 = *b1; c2 = *b2; if (c1 != c2) { break;} b1++; b2++; // 2 c1 = *b1; c2 = *b2; if (c1 != c2) { cmp2do -= 1; break; } b1++; b2++; // 3 c1 = *b1; c2 = *b2; if (c1 != c2) { cmp2do -= 2; break; } b1++; b2++; // 4 c1 = *b1; c2 = *b2; if (c1 != c2) { cmp2do -= 3; break; } b1++; b2++; // 5 c1 = *b1; c2 = *b2; if (c1 != c2) { cmp2do -= 4; break; } b1++; b2++; // 6 c1 = *b1; c2 = *b2; if (c1 != c2) { cmp2do -= 5; break; } b1++; b2++; // 7 c1 = *b1; c2 = *b2; if (c1 != c2) { cmp2do -= 6; break; } b1++; b2++; // 8 c1 = *b1; c2 = *b2; if (c1 != c2) { cmp2do -= 7; break; } b1++; b2++; // 9 c1 = *b1; c2 = *b2; if (c1 != c2) { cmp2do -= 8; break; } b1++; b2++; // 10 c1 = *b1; c2 = *b2; if (c1 != c2) { cmp2do -= 9; break; } b1++; b2++; // 11 c1 = *b1; c2 = *b2; if (c1 != c2) { cmp2do -= 10; break; } b1++; b2++; // 12 c1 = *b1; c2 = *b2; if (c1 != c2) { cmp2do -= 11; break; } b1++; b2++; // 13 c1 = *b1; c2 = *b2; if (c1 != c2) { cmp2do -= 12; break; } b1++; b2++; // 14 c1 = *b1; c2 = *b2; if (c1 != c2) { cmp2do -= 13; break; } b1++; b2++; // 15 c1 = *b1; c2 = *b2; if (c1 != c2) { cmp2do -= 14; break; } b1++; b2++; // 16 c1 = *b1; c2 = *b2; if (c1 != c2) { cmp2do -= 15; break; } b1++; b2++; cmp2do -= 16; } while(cmp2do>0); if(cmp_limit - cmp2do < cmp_limit) return cmp_limit-cmp2do; return cmp_limit-1; } /* ************************************************************************ this function returns the lcp between suf1 and suf2 (that is returns n such that suf1[n]!=suf2[n] but suf1[i]==suf2[i] for i=0..n-1 However, it is possible that suf1 is a prefix of suf2 (not vice-versa because of the initial sorting of suffixes in order of descreasing length) in this case the function returns n=length(suf1)-1. So in this case suf1[n]==suf2[n] (and suf1[n+1] does not exists). ************************************************************************ */ Int32 compare_suffixes(Int32 suf1, Int32 suf2, Int32 depth) { int limit; UChar *s1, *s2; assert(suf1>suf2); s1 = Text + depth +suf1; s2 = Text + depth +suf2; limit = Text_size - suf1 - depth; return depth + get_lcp_unrolled(s1 ,s2, limit); } /* ****************************************************************** comparison function used to sort suffixes in order of increasing length. Since suffixes are represented by their offset in the array, we sort these offsets in order of decreasing length. ****************************************************************** */ int neg_integer_cmp(const void *a, const void *b) { return *((Int32 *) b) - *((Int32 *) a); } // free memory used for trie nodes void free_node_mem() { int i; for(i=free_num-1;i>=0;i--) { assert(freearr[i]!=NULL); free(freearr[i]); } // clear counters bufn_num=free_num=0; }
2.90625
3
2024-11-18T19:27:06.671124+00:00
2019-06-27T00:49:40
d9bb62a083c67a06abb8403a2267cf24764f115d
{ "blob_id": "d9bb62a083c67a06abb8403a2267cf24764f115d", "branch_name": "refs/heads/master", "committer_date": "2019-06-27T00:49:40", "content_id": "a31c27c6b3329922d00c7d4ab4968151d63005b0", "detected_licenses": [ "BSD-3-Clause-Open-MPI" ], "directory_id": "7047c2ebf8d7944c6b4467560e190b184d54697d", "extension": "c", "filename": "daemon_init.c", "fork_events_count": 6, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 33182022, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2739, "license": "BSD-3-Clause-Open-MPI", "license_type": "permissive", "path": "/openmpi-1.2.4/opal/util/daemon_init.c", "provenance": "stackv2-0012.json.gz:182084", "repo_name": "NirantK/Text-Summarization", "revision_date": "2019-06-27T00:49:40", "revision_id": "45bfa88f77515e1e5c8c6c6b3c64aba4ef8e1575", "snapshot_id": "7afb7be3810ccfc1341758ce7899fb2e41b49d4c", "src_encoding": "UTF-8", "star_events_count": 3, "url": "https://raw.githubusercontent.com/NirantK/Text-Summarization/45bfa88f77515e1e5c8c6c6b3c64aba4ef8e1575/openmpi-1.2.4/opal/util/daemon_init.c", "visit_date": "2020-06-04T07:12:43.455919" }
stackv2
/* * Copyright (c) 2004-2005 The Trustees of Indiana University and Indiana * University Research and Technology * Corporation. All rights reserved. * Copyright (c) 2004-2005 The University of Tennessee and The University * of Tennessee Research Foundation. All rights * reserved. * Copyright (c) 2004-2005 High Performance Computing Center Stuttgart, * University of Stuttgart. All rights reserved. * Copyright (c) 2004-2005 The Regents of the University of California. * All rights reserved. * $COPYRIGHT$ * * Additional copyrights may follow * * $HEADER$ */ #include "opal_config.h" #ifdef HAVE_SYS_TYPES_H #include <sys/types.h> #endif #include <sys/stat.h> #include <fcntl.h> #ifdef HAVE_UNISTD_H #include <unistd.h> #endif #include <stdlib.h> #include "opal/util/daemon_init.h" #include "opal/constants.h" int opal_daemon_init(char *working_dir) { #if defined(HAVE_FORK) #ifndef __WINDOWS__ /* it seems that there is an entirely different way to write daemons in WINDOWS land. Firstly, they are called services and the way to go about it is to get a service handle annd then call CreateService() So, I am guessing that this piece of code is called only by UNIX versions */ pid_t pid; int fd; if ((pid = fork()) < 0) { return OPAL_ERROR; } else if (pid != 0) { exit(0); /* parent goes bye-bye */ } /* child continues */ #if defined(HAVE_SETSID) setsid(); /* become session leader */ #endif if (NULL != working_dir) { chdir(working_dir); /* change working directory */ } /* connect input to /dev/null */ fd = open("/dev/null", O_RDONLY); if(fd > STDIN_FILENO) { dup2(fd, STDIN_FILENO); close(fd); } /* connect outputs to /dev/null */ fd = open("/dev/null", O_RDWR|O_CREAT|O_TRUNC, 0666); if (fd >= 0) { dup2(fd, STDOUT_FILENO); dup2(fd, STDERR_FILENO); /* just to be safe, make sure we aren't trying * to close stdout or stderr! since we dup'd both * of them to the same fd, we can't just close it * since one of the two would still be open and * someone could attempt to use it. */ if(fd != STDOUT_FILENO && fd != STDERR_FILENO) { close(fd); } } else { return OPAL_ERR_FATAL; } return OPAL_SUCCESS; #else printf ("This function has not been implemented in windows yet, file %s line %d\n", __FILE__, __LINE__); abort(); #endif #else /* HAVE_FORK */ return OPAL_ERR_NOT_SUPPORTED; #endif }
2.28125
2
2024-11-18T19:27:07.315485+00:00
2021-04-08T17:24:07
815a9a08365a91dd677efa91966bc31d8b645b0e
{ "blob_id": "815a9a08365a91dd677efa91966bc31d8b645b0e", "branch_name": "refs/heads/master", "committer_date": "2021-04-08T17:24:07", "content_id": "8128046871ca322db88c884eb4bd85652a36af58", "detected_licenses": [ "MIT", "BSD-3-Clause" ], "directory_id": "fe27d4417ec8d360caf766b4acd10f5eaaffc5db", "extension": "c", "filename": "event_chooser.c", "fork_events_count": 2, "gha_created_at": "2017-11-06T17:14:59", "gha_event_created_at": "2017-12-23T01:10:51", "gha_language": "C", "gha_license_id": null, "github_id": 109725839, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 7046, "license": "MIT,BSD-3-Clause", "license_type": "permissive", "path": "/CCProf/PAPI/PAPI/src/utils/event_chooser.c", "provenance": "stackv2-0012.json.gz:182212", "repo_name": "proywm/CCProf", "revision_date": "2021-04-08T17:24:07", "revision_id": "20c43042142909dc782064e4250a5167767f7314", "snapshot_id": "ce3f2ce972fbe16d18ed6d707acb0cc2f2a9dadd", "src_encoding": "UTF-8", "star_events_count": 26, "url": "https://raw.githubusercontent.com/proywm/CCProf/20c43042142909dc782064e4250a5167767f7314/CCProf/PAPI/PAPI/src/utils/event_chooser.c", "visit_date": "2021-05-07T13:54:39.449222" }
stackv2
/** file event_chooser.c * @brief papi_event_chooser utility. * @page papi_event_chooser * @section NAME * papi_event_chooser - given a list of named events, * lists other events that can be counted with them. * * @section Synopsis * papi_event_chooser NATIVE | PRESET < event > < event > ... * * @section Description * papi_event_chooser is a PAPI utility program that reports information * about the current PAPI installation and supported preset events. * * @section Options * This utility has no command line options. * * @section Bugs * There are no known bugs in this utility. * If you find a bug, it should be reported to the * PAPI Mailing List at [email protected]. */ #include "papi_test.h" #include <stdio.h> #include <stdlib.h> int EventSet = PAPI_NULL; int retval; static char * is_derived( PAPI_event_info_t * info ) { if ( strlen( info->derived ) == 0 ) return ( "No" ); else if ( strcmp( info->derived, "NOT_DERIVED" ) == 0 ) return ( "No" ); else if ( strcmp( info->derived, "DERIVED_CMPD" ) == 0 ) return ( "No" ); else return ( "Yes" ); } static int add_remove_event( int EventSet, int evt ) { int retval; if ( ( retval = PAPI_add_event( EventSet, evt ) ) != PAPI_OK ) { //printf( "Error adding event.\n" ); } else { if ( ( retval = PAPI_remove_event( EventSet, evt ) ) != PAPI_OK ) { printf( "Error removing event.\n" ); } } return retval; } static int show_event_info( int evt ) { int k; int retval; PAPI_event_info_t info; if ( ( retval = PAPI_get_event_info( evt, &info ) ) == PAPI_OK ) { printf( "%s\t%#x\n |%s|\n", info.symbol, info.event_code, info.long_descr ); for( k = 0; k < ( int ) info.count; k++ ) { if ( strlen( info.name[k] ) ) { printf( " |Register Value[%d]: %#-10x %s|\n", k, info.code[k], info.name[k] ); } } } return retval; } static int native( int cidx ) { int i, j, k; int retval, added; PAPI_event_info_t info; j = 0; /* For platform independence, always ASK FOR the first event */ /* Don't just assume it'll be the first numeric value */ i = 0 | PAPI_NATIVE_MASK; retval=PAPI_enum_cmp_event( &i, PAPI_ENUM_FIRST, cidx ); if (retval==PAPI_ENOEVNT) { printf("Cannot find first event in component %d\n",cidx); } do { k = i; if ( PAPI_enum_cmp_event( &k, PAPI_NTV_ENUM_UMASKS, cidx) == PAPI_OK ) { if ( ( added = add_remove_event( EventSet, k ) ) == PAPI_OK ) { show_event_info( i ); do { retval = PAPI_get_event_info( k, &info ); if ( retval == PAPI_OK ) { printf( " %#-10x%s |%s|\n", info.event_code, strchr( info.symbol, ':' ), strchr( info.long_descr, ':' ) + 1 ); } } while ( PAPI_enum_cmp_event( &k, PAPI_NTV_ENUM_UMASKS, cidx ) == PAPI_OK ); j++; } } else { if ( ( added = add_remove_event( EventSet, i ) ) == PAPI_OK ) { show_event_info( i ); j++; } } if ( added == PAPI_OK ) { /* modifier = PAPI_NTV_ENUM_GROUPS returns event codes with a groups id for each group in which this native event lives, in bits 16 - 23 of event code terminating with PAPI_ENOEVNT at the end of the list. */ k = i; if ( PAPI_enum_cmp_event( &k, PAPI_NTV_ENUM_GROUPS, cidx ) == PAPI_OK ) { printf( "Groups: " ); do { printf( "%4d", ( ( k & PAPI_NTV_GROUP_AND_MASK ) >> PAPI_NTV_GROUP_SHIFT ) - 1 ); } while ( PAPI_enum_cmp_event( &k, PAPI_NTV_ENUM_GROUPS, cidx ) == PAPI_OK ); printf( "\n" ); } printf( "---------------------------------------------" "----------------------------\n" ); } } while ( PAPI_enum_cmp_event( &i, PAPI_ENUM_EVENTS, cidx ) == PAPI_OK ); printf( "------------------------------------------" "-------------------------------\n" ); printf( "Total events reported: %d\n", j ); test_pass( __FILE__, NULL, 0 ); exit( 1 ); } static int preset( void ) { int i, j = 0; int retval; PAPI_event_info_t info; printf( " Name Code " ); printf( "Deriv Description (Note)\n" ); /* For consistency, always ASK FOR the first event */ i = 0 | PAPI_PRESET_MASK; PAPI_enum_event( &i, PAPI_ENUM_FIRST ); do { retval = PAPI_add_event( EventSet, i ); if ( retval == PAPI_OK ) { if ( PAPI_get_event_info( i, &info ) == PAPI_OK ) { printf( "%-13s%#x %-5s%s", info.symbol, info.event_code, is_derived( &info ), info.long_descr ); if ( info.note[0] ) printf( " (%s)", info.note ); printf( "\n" ); } if ( ( retval = PAPI_remove_event( EventSet, i ) ) != PAPI_OK ) printf( "Error in PAPI_remove_event\n" ); j++; } } while ( PAPI_enum_event( &i, PAPI_PRESET_ENUM_AVAIL ) == PAPI_OK ); printf ( "-------------------------------------------------------------------------\n" ); printf( "Total events reported: %d\n", j ); test_pass( __FILE__, NULL, 0 ); exit( 1 ); } int main( int argc, char **argv ) { int i; int pevent,cevent; int cidx; const PAPI_hw_info_t *hwinfo = NULL; if ( argc < 3 ) { goto use_exit; } /* Set TESTS_QUIET variable */ tests_quiet( argc, argv ); /* Init PAPI library */ retval = PAPI_library_init( PAPI_VER_CURRENT ); if ( retval != PAPI_VER_CURRENT ) { test_fail( __FILE__, __LINE__, "PAPI_library_init", retval ); } retval = PAPI_set_debug( PAPI_VERB_ECONT ); if ( retval != PAPI_OK ) { test_fail( __FILE__, __LINE__, "PAPI_set_debug", retval ); } retval = papi_print_header( "Event Chooser: Available events " "which can be added with given events.\n", &hwinfo ); if ( retval != PAPI_OK ) { test_fail( __FILE__, __LINE__, "PAPI_get_hardware_info", 2 ); } retval = PAPI_create_eventset( &EventSet ); if ( retval != PAPI_OK ) { fprintf( stderr, "PAPI_create_eventset error\n" ); exit( 1 ); } retval = PAPI_event_name_to_code( argv[2], &cevent ); if ( retval != PAPI_OK ) { fprintf( stderr, "Event %s can't be found\n", argv[2] ); exit( 1 ); } cidx = PAPI_get_event_component(cevent); for( i = 2; i < argc; i++ ) { retval = PAPI_event_name_to_code( argv[i], &pevent ); if ( retval != PAPI_OK ) { fprintf( stderr, "Event %s can't be found\n", argv[i] ); exit( 1 ); } retval = PAPI_add_event( EventSet, pevent ); if ( retval != PAPI_OK ) { fprintf( stderr, "Event %s can't be counted with others %d\n", argv[i], retval ); exit( 1 ); } } if ( !strcmp( "NATIVE", argv[1] ) ) { native( cidx ); } else if ( !strcmp( "PRESET", argv[1] ) ) { preset( ); } else { goto use_exit; } exit( 0 ); use_exit: fprintf( stderr, "Usage: papi_event_chooser NATIVE|PRESET evt1 evt2 ... \n" ); exit( 1 ); }
2.703125
3
2024-11-18T19:27:07.384610+00:00
2020-02-04T14:25:27
a28b67f589b44d3e22ffbc11fdb774cc37090dee
{ "blob_id": "a28b67f589b44d3e22ffbc11fdb774cc37090dee", "branch_name": "refs/heads/master", "committer_date": "2020-02-04T14:25:27", "content_id": "f081ea7886d751b21c786d2000424a835ec54801", "detected_licenses": [ "MIT" ], "directory_id": "5f41d9f61168d13ba41f67588219ef566f1eb87b", "extension": "c", "filename": "main.c", "fork_events_count": 1, "gha_created_at": "2017-01-31T14:23:48", "gha_event_created_at": "2020-02-04T14:25:29", "gha_language": "C", "gha_license_id": "MIT", "github_id": 80527160, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 545, "license": "MIT", "license_type": "permissive", "path": "/src/micro/acceptance/missing_return_value/main.c", "provenance": "stackv2-0012.json.gz:182340", "repo_name": "tudinfse/intel_mpx_explained", "revision_date": "2020-02-04T14:25:27", "revision_id": "9a3d7b060742d8fe89c1b56898f2b2e3617b670b", "snapshot_id": "0671a667006bd43c436ddfc0c2cee43fa35d4db8", "src_encoding": "UTF-8", "star_events_count": 17, "url": "https://raw.githubusercontent.com/tudinfse/intel_mpx_explained/9a3d7b060742d8fe89c1b56898f2b2e3617b670b/src/micro/acceptance/missing_return_value/main.c", "visit_date": "2022-04-06T00:50:14.193509" }
stackv2
#include <iostream> #include <stdlib.h> #include <pthread.h> #include <vector> void* entry_pt(void*); void test(); using namespace std; #define NUM_THREADS 2 int main (int argc, char **argv) { std::vector<pthread_t> threads(NUM_THREADS); for(int i=0; i<NUM_THREADS; i++){ pthread_create(&threads[i], NULL, entry_pt, NULL); } for (int i=0; i<NUM_THREADS; i++){ pthread_join(threads[i], NULL); } cout << "done" << endl; return 0; } void* entry_pt(void* data) { test(); } void test() { cout << "called test" << endl; }
2.671875
3
2024-11-18T19:27:07.465448+00:00
2023-05-05T07:18:21
14343e454e1a3ff19ae01cc48c5125428aea4a36
{ "blob_id": "14343e454e1a3ff19ae01cc48c5125428aea4a36", "branch_name": "refs/heads/master", "committer_date": "2023-05-05T07:18:21", "content_id": "7630b9519e4971d3b0dd9f0a3e51cef58984cefd", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "ace570f65d70e6ce9461bcb81aaaac31c57ec111", "extension": "c", "filename": "i2c_lpc.c", "fork_events_count": 95, "gha_created_at": "2015-12-17T16:17:35", "gha_event_created_at": "2023-05-05T07:18:22", "gha_language": "C", "gha_license_id": "BSD-3-Clause", "github_id": 48184998, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1445, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/firmware/common/i2c_lpc.c", "provenance": "stackv2-0012.json.gz:182468", "repo_name": "greatscottgadgets/greatfet", "revision_date": "2023-05-05T07:18:21", "revision_id": "2409575d28fc7c9cae44c9085c7457ddfb54f893", "snapshot_id": "9ed060aec2d293844c0ac59612f09ecae9c7632b", "src_encoding": "UTF-8", "star_events_count": 273, "url": "https://raw.githubusercontent.com/greatscottgadgets/greatfet/2409575d28fc7c9cae44c9085c7457ddfb54f893/firmware/common/i2c_lpc.c", "visit_date": "2023-05-12T18:12:31.748720" }
stackv2
/* * This file is part of GreatFET */ #include "i2c_lpc.h" #include <libopencm3/lpc43xx/i2c.h> #include <stddef.h> #include <greatfet_core.h> #include <i2c_bus.h> #include <i2c.h> /* FIXME return i2c0 status from each function */ void i2c_lpc_start(i2c_bus_t* const bus, uint16_t _duty_cycle_count) { uint16_t duty_cycle_count = _duty_cycle_count; const uint32_t port = (uint32_t)bus->obj; i2c_init(port, duty_cycle_count); } void i2c_lpc_stop(i2c_bus_t* const bus) { const uint32_t port = (uint32_t)bus->obj; i2c_disable(port); } uint8_t i2c_lpc_read(i2c_bus_t* const bus, const uint_fast8_t slave_address, uint8_t* const data_rx, const size_t count_rx ) { const uint32_t port = (uint32_t)bus->obj; size_t i; bool ack = false; uint8_t status = 0; i2c_tx_start(port); i2c_tx_byte(port, (slave_address << 1) | I2C_READ); status = I2C0_STAT; for(i=0; i<count_rx; i++) { /* ACK each byte except the last */ ack = (i!=count_rx-1); data_rx[i] = i2c_rx_byte(port, ack); } i2c_stop(port); return status; } uint8_t i2c_lpc_write(i2c_bus_t* const bus, const uint_fast8_t slave_address, const uint8_t* const data_tx, const size_t count_tx ) { const uint32_t port = (uint32_t)bus->obj; size_t i; uint8_t status = 0; i2c_tx_start(port); i2c_tx_byte(port, (slave_address << 1) | I2C_WRITE); status = I2C0_STAT; for(i=0; i<count_tx; i++) { i2c_tx_byte(port, data_tx[i]); } i2c_stop(port); return status; }
2.5
2
2024-11-18T19:27:07.595185+00:00
2019-06-01T13:28:10
43d840647be71565fb7482c4cb69c2e0abe25ec8
{ "blob_id": "43d840647be71565fb7482c4cb69c2e0abe25ec8", "branch_name": "refs/heads/master", "committer_date": "2019-06-01T13:28:10", "content_id": "5a479ba507f19d1624e4013537b7d14b078d761e", "detected_licenses": [ "MIT" ], "directory_id": "e398a585764f16511a70d0ef33a3b61da0733b69", "extension": "h", "filename": "chroma.h", "fork_events_count": 0, "gha_created_at": "2019-06-01T12:58:11", "gha_event_created_at": "2019-06-01T12:58:11", "gha_language": null, "gha_license_id": null, "github_id": 189732991, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 19903, "license": "MIT", "license_type": "permissive", "path": "/3790.1830/src/video/displays/3dlabs/perm3/disp/dx/chroma.h", "provenance": "stackv2-0012.json.gz:182596", "repo_name": "MichaelDavidGK/WinDDK", "revision_date": "2019-06-01T13:28:10", "revision_id": "eea187e357d61569e67292ff705550887c4df908", "snapshot_id": "f9e4fc6872741ee742f8eace04b2b3a30b049495", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/MichaelDavidGK/WinDDK/eea187e357d61569e67292ff705550887c4df908/3790.1830/src/video/displays/3dlabs/perm3/disp/dx/chroma.h", "visit_date": "2020-05-30T12:26:40.125588" }
stackv2
/******************************Module*Header**********************************\ * * ******************* * * DX SAMPLE CODE * * ******************* * * Module Name: chroma.h * * Content: Chromakeying definitions and inline functions * * Copyright (c) 1994-1999 3Dlabs Inc. Ltd. All rights reserved. * Copyright (c) 1995-2002 Microsoft Corporation. All rights reserved. \*****************************************************************************/ #ifdef __CHROMA #pragma message ("FILE : "__FILE__" : Multiple inclusion") #endif #define __CHROMA //----------------------------------------------------------------------------- // // In this module we define the // // Get8888ScaledChroma // Get8888ZeroExtendedChroma // inline functions used to do texture chroma keying correctly. // // All other macros defined in this module are for internal module consumption // only. // //----------------------------------------------------------------------------- // Get the components for each of the colors // Put the value into the top bits of a byte. #define GET_RED_332(a) (((a) & 0xE0)) #define GET_GREEN_332(a) (((a) & 0x1C) << 3) #define GET_BLUE_332(a) (((a) & 0x03) << 6) #define GET_ALPHA_2321(a) (((a) & 0x80)) #define GET_RED_2321(a) (((a) & 0x60) << 1) #define GET_GREEN_2321(a) (((a) & 0x1C) << 3) #define GET_BLUE_2321(a) (((a) & 0x03) << 6) #define GET_ALPHA_5551(a) (((a) & 0x8000) >> 8) #define GET_RED_5551(a) (((a) & 0x7C00) >> 7) #define GET_GREEN_5551(a) (((a) & 0x03E0) >> 2) #define GET_BLUE_5551(a) (((a) & 0x001F) << 3) #define GET_RED_565(a) (((a) & 0xF800) >> 8) #define GET_GREEN_565(a) (((a) & 0x07E0) >> 3) #define GET_BLUE_565(a) (((a) & 0x001F) << 3) #define GET_ALPHA_4444(a) (((a) & 0xF000) >> 8) #define GET_RED_4444(a) (((a) & 0x0F00) >> 4) #define GET_GREEN_4444(a) (((a) & 0x00F0)) #define GET_BLUE_4444(a) (((a) & 0x000F) << 4) #define GET_ALPHA_8888(a) (((a) & 0xFF000000) >> 24) #define GET_RED_8888(a) (((a) & 0x00FF0000) >> 16) #define GET_GREEN_8888(a) (((a) & 0x0000FF00) >> 8) #define GET_BLUE_8888(a) (((a) & 0x000000FF)) // These macros assume that the passed value (a) contains no more than the // designated number of bits set i.e. 11111000 not 1111101 for a 5 bit color // The macro scales the number to match the internal color conversion of // Permedia3. #define P3SCALE_1_BIT(a) (((a) & 0x80) ? 0xFF : 0x0) #define P3SCALE_2_BIT(a) ((a) | (((a) & 0xC0) >> 2) \ | (((a) & 0xC0) >> 4) \ | (((a) & 0xC0) >> 6)) #define P3SCALE_3_BIT(a) ((a) | (((a) & 0xE0) >> 3) | (((a) & 0xC0) >> 6)) #define P3SCALE_4_BIT(a) ((a) | (((a) & 0xF0) >> 4)) #define P3SCALE_5_BIT(a) ((a) | (((a) & 0xE0) >> 5)) #define P3SCALE_6_BIT(a) ((a) | (((a) & 0xC0) >> 6)) #define P3SCALE_7_BIT(a) ((a) | (((a) & 0x80) >> 7)) #define P3SCALE_8_BIT(a) ((a)) #define P3REG_PLACE_RED(a) ((a)) #define P3REG_PLACE_GREEN(a) ((a) << 8) #define P3REG_PLACE_BLUE(a) ((a) << 16) #define P3REG_PLACE_ALPHA(a) ((a) << 24) // The scaling versions. #define GEN_332_KEY(a) (P3REG_PLACE_RED (P3SCALE_3_BIT(GET_RED_332 (a))) | \ P3REG_PLACE_GREEN(P3SCALE_3_BIT(GET_GREEN_332(a))) | \ P3REG_PLACE_BLUE (P3SCALE_2_BIT(GET_BLUE_332 (a)))) #define GEN_2321_KEY(a) (P3REG_PLACE_ALPHA(P3SCALE_1_BIT(GET_ALPHA_2321(a))) | \ P3REG_PLACE_RED (P3SCALE_2_BIT(GET_RED_2321 (a))) | \ P3REG_PLACE_GREEN(P3SCALE_3_BIT(GET_GREEN_2321(a))) | \ P3REG_PLACE_BLUE (P3SCALE_2_BIT(GET_BLUE_2321 (a)))) #define GEN_5551_KEY(a) (P3REG_PLACE_ALPHA(P3SCALE_1_BIT(GET_ALPHA_5551(a))) | \ P3REG_PLACE_RED (P3SCALE_5_BIT(GET_RED_5551 (a))) | \ P3REG_PLACE_GREEN(P3SCALE_5_BIT(GET_GREEN_5551(a))) | \ P3REG_PLACE_BLUE (P3SCALE_5_BIT(GET_BLUE_5551 (a)))) #define GEN_565_KEY(a) (P3REG_PLACE_RED (P3SCALE_5_BIT(GET_RED_565 (a))) | \ P3REG_PLACE_GREEN(P3SCALE_6_BIT(GET_GREEN_565(a))) | \ P3REG_PLACE_BLUE (P3SCALE_5_BIT(GET_BLUE_565 (a)))) #define GEN_4444_KEY(a) (P3REG_PLACE_ALPHA(P3SCALE_4_BIT(GET_ALPHA_4444(a))) | \ P3REG_PLACE_RED (P3SCALE_4_BIT(GET_RED_4444 (a))) | \ P3REG_PLACE_GREEN(P3SCALE_4_BIT(GET_GREEN_4444(a))) | \ P3REG_PLACE_BLUE (P3SCALE_4_BIT(GET_BLUE_4444 (a)))) #define GEN_8888_KEY(a) (P3REG_PLACE_ALPHA(P3SCALE_8_BIT(GET_ALPHA_8888(a))) | \ P3REG_PLACE_RED (P3SCALE_8_BIT(GET_RED_8888 (a))) | \ P3REG_PLACE_GREEN(P3SCALE_8_BIT(GET_GREEN_8888(a))) | \ P3REG_PLACE_BLUE (P3SCALE_8_BIT(GET_BLUE_8888 (a)))) // The shifting versions. #define GEN_332_SKEY(a) (P3REG_PLACE_RED (GET_RED_332 (a)) | \ P3REG_PLACE_GREEN(GET_GREEN_332(a)) | \ P3REG_PLACE_BLUE (GET_BLUE_332 (a))) #define GEN_2321_SKEY(a) (P3REG_PLACE_ALPHA(GET_ALPHA_2321(a)) | \ P3REG_PLACE_RED (GET_RED_2321 (a)) | \ P3REG_PLACE_GREEN(GET_GREEN_2321(a)) | \ P3REG_PLACE_BLUE (GET_BLUE_2321 (a))) #define GEN_5551_SKEY(a) (P3REG_PLACE_ALPHA(GET_ALPHA_5551(a)) | \ P3REG_PLACE_RED (GET_RED_5551 (a)) | \ P3REG_PLACE_GREEN(GET_GREEN_5551(a)) | \ P3REG_PLACE_BLUE (GET_BLUE_5551 (a))) #define GEN_565_SKEY(a) (P3REG_PLACE_RED (GET_RED_565 (a)) | \ P3REG_PLACE_GREEN(GET_GREEN_565(a)) | \ P3REG_PLACE_BLUE (GET_BLUE_565 (a))) #define GEN_4444_SKEY(a) (P3REG_PLACE_ALPHA(GET_ALPHA_4444(a)) | \ P3REG_PLACE_RED (GET_RED_4444 (a)) | \ P3REG_PLACE_GREEN(GET_GREEN_4444(a)) | \ P3REG_PLACE_BLUE (GET_BLUE_4444 (a))) // The luminance versions #define GEN_L8_KEY(a) (P3REG_PLACE_ALPHA(0xFF) | \ P3REG_PLACE_RED (GET_BLUE_8888 (a)) | \ P3REG_PLACE_GREEN(GET_BLUE_8888 (a)) | \ P3REG_PLACE_BLUE (GET_BLUE_8888 (a))) #define GEN_A8L8_KEY(a) (P3REG_PLACE_ALPHA(GET_GREEN_8888 (a)) | \ P3REG_PLACE_RED (GET_BLUE_8888 (a)) | \ P3REG_PLACE_GREEN(GET_BLUE_8888 (a)) | \ P3REG_PLACE_BLUE (GET_BLUE_8888 (a))) #define GEN_A4L4_KEY(a) (P3REG_PLACE_ALPHA(P3SCALE_4_BIT(GET_GREEN_4444 (a))) | \ P3REG_PLACE_RED (P3SCALE_4_BIT(GET_BLUE_4444 (a))) | \ P3REG_PLACE_GREEN(P3SCALE_4_BIT(GET_BLUE_4444 (a))) | \ P3REG_PLACE_BLUE (P3SCALE_4_BIT(GET_BLUE_4444 (a)))) //Note: No GEN_8888_SKEY - no difference in functionality. //----------------------------------------------------------------------------- // // __inline Get8888ScaledChroma // // Convert a FB Format color to a colorkey value. The value produced exactly // matches the value that the chip will read in from the Framebuffer (it will // scale the color into it's internal 8888 format). Non-null pPalEntries // indicates that color index should be converted to RGB{A} value. bUsePalAlpha // indicates whether Alpha channel of the palette should be used. bShift makes // the conversion use a shift instead of a scale, to match the shift option in // the P3. // //----------------------------------------------------------------------------- static __inline void Get8888ScaledChroma( P3_THUNKEDDATA* pThisDisplay, DWORD dwSurfFlags, DDPIXELFORMAT* pSurfPixFormat, DWORD InLowerBound, DWORD InUpperBound, DWORD* OutLowerBound, DWORD* OutUpperBound, DWORD* pPalEntries, BOOL bUsePalAlpha, BOOL bShift) { DDPIXELFORMAT* pPixFormat; DISPDBG((DBGLVL, "InLowerBound = 0x%08X", InLowerBound)); DISPDBG((DBGLVL, "InUpperBound = 0x%08X", InUpperBound)); // Get a pointer to the pixelformat data (not guaranteed to exist. // If it doesn't, we use the same format as the display. if (DDSurf_HasPixelFormat(dwSurfFlags)) { pPixFormat = pSurfPixFormat; } else { pPixFormat = &pThisDisplay->ddpfDisplay; } // Is the texture palette indexed? if (pPixFormat->dwFlags & DDPF_PALETTEINDEXED4 || pPixFormat->dwFlags & DDPF_PALETTEINDEXED8) { // Are we doing a lookup through the LUT? We won't be during a blit if (! pPalEntries) { *OutLowerBound = CHROMA_LOWER_ALPHA(FORMAT_PALETTE_32BIT(InLowerBound)); *OutUpperBound = CHROMA_UPPER_ALPHA(FORMAT_PALETTE_32BIT(InUpperBound)); DISPDBG((DBGLVL,"Keying of index: %d", InLowerBound)); } else { DWORD dwTrueColor; // ChromaKeying for paletted textures is done on the looked up // color, not the index. This means using a range is meaningless // and we have to lookup the color from the palette. Make sure // the user doesn't force us to access invalid memory. dwTrueColor = pPalEntries[(InLowerBound & 0xFF)]; DISPDBG((DBGLVL, "Texture lookup index: %d, ChromaColor: 0x%x", InLowerBound, dwTrueColor)); if (bUsePalAlpha) { *OutLowerBound = dwTrueColor; *OutUpperBound = dwTrueColor; } else { // Alpha channel of LUT will be set to FF *OutLowerBound = CHROMA_LOWER_ALPHA(dwTrueColor); *OutUpperBound = CHROMA_UPPER_ALPHA(dwTrueColor); } } return; } // Texture is RGB format if (pPixFormat->dwFlags & DDPF_RGB) { DWORD RedMask = pPixFormat->dwRBitMask; DWORD AlphaMask = pPixFormat->dwRGBAlphaBitMask; switch (pPixFormat->dwRGBBitCount) { // 8 Bit RGB Textures case 8: if (RedMask == 0xE0) { DISPDBG((DBGLVL," 3:3:2")); // Never any alpha if ( bShift ) { *OutLowerBound = CHROMA_LOWER_ALPHA(GEN_332_SKEY(InLowerBound)); *OutUpperBound = CHROMA_UPPER_ALPHA(GEN_332_SKEY(InUpperBound)); } else { *OutLowerBound = CHROMA_LOWER_ALPHA(GEN_332_KEY(InLowerBound)); *OutUpperBound = CHROMA_UPPER_ALPHA(GEN_332_KEY(InUpperBound)); } } else { DISPDBG((DBGLVL," 1:2:3:2")); if ( bShift ) { *OutLowerBound = GEN_2321_SKEY(InLowerBound); *OutUpperBound = GEN_2321_SKEY(InUpperBound); } else { *OutLowerBound = GEN_2321_KEY(InLowerBound); *OutUpperBound = GEN_2321_KEY(InUpperBound); } if (!AlphaMask) { *OutLowerBound = CHROMA_LOWER_ALPHA(*OutLowerBound); *OutUpperBound = CHROMA_UPPER_ALPHA(*OutUpperBound); } } break; // 16 Bit RGB Textures case 16: switch (RedMask) { case 0xf00: DISPDBG((DBGLVL," 4:4:4:4")); if ( bShift ) { *OutLowerBound = GEN_4444_SKEY(InLowerBound); *OutUpperBound = GEN_4444_SKEY(InUpperBound); } else { *OutLowerBound = GEN_4444_KEY(InLowerBound); *OutUpperBound = GEN_4444_KEY(InUpperBound); } break; case 0x7c00: DISPDBG((DBGLVL," 1:5:5:5")); if ( bShift ) { *OutLowerBound = GEN_5551_SKEY(InLowerBound); *OutUpperBound = GEN_5551_SKEY(InUpperBound); } else { *OutLowerBound = GEN_5551_KEY(InLowerBound); *OutUpperBound = GEN_5551_KEY(InUpperBound); } if (!AlphaMask) { *OutLowerBound = CHROMA_LOWER_ALPHA(*OutLowerBound); *OutUpperBound = CHROMA_UPPER_ALPHA(*OutUpperBound); } break; default: // Always supply full range of alpha values to ensure test // is done DISPDBG((DBGLVL," 5:6:5")); if ( bShift ) { *OutLowerBound = CHROMA_LOWER_ALPHA(GEN_565_SKEY(InLowerBound)); *OutUpperBound = CHROMA_UPPER_ALPHA(GEN_565_SKEY(InUpperBound)); } else { *OutLowerBound = CHROMA_LOWER_ALPHA(GEN_565_KEY(InLowerBound)); *OutUpperBound = CHROMA_UPPER_ALPHA(GEN_565_KEY(InUpperBound)); } break; } // switch (RedMask) break; // 32/24 Bit RGB Textures case 24: case 32: DISPDBG((DBGLVL," 8:8:8:8")); // If the surface isn't alpha'd then set a valid // range of alpha to catch all cases. // No change in behavior for shifting or scaling. if (!AlphaMask) { *OutLowerBound = CHROMA_LOWER_ALPHA(GEN_8888_KEY(InLowerBound)); *OutUpperBound = CHROMA_UPPER_ALPHA(GEN_8888_KEY(InUpperBound)); } else { *OutLowerBound = GEN_8888_KEY(InLowerBound); *OutUpperBound = GEN_8888_KEY(InUpperBound); } break; } // switch (pPixFormat->dwRGBBitCount) DISPDBG((DBGLVL, "OutLowerBound = 0x%08X", *OutLowerBound)); DISPDBG((DBGLVL, "OutUpperBound = 0x%08X", *OutUpperBound)); } // luminance formats else if (pPixFormat->dwFlags & DDPF_LUMINANCE) { if (pPixFormat->dwFlags & DDPF_ALPHAPIXELS) { if (pPixFormat->dwLuminanceBitCount == 16) { // 16 bit A8L8 *OutLowerBound = GEN_A8L8_KEY(InLowerBound); *OutUpperBound = GEN_A8L8_KEY(InUpperBound); } else { // 8 Bit A4L4 *OutLowerBound = GEN_A4L4_KEY(InLowerBound); *OutUpperBound = GEN_A4L4_KEY(InUpperBound); } } else { // 8 Bit L8 *OutLowerBound = GEN_L8_KEY(InLowerBound); *OutUpperBound = GEN_L8_KEY(InUpperBound); } } } // Get8888ScaledChroma //----------------------------------------------------------------------------- // // __inline Get8888ZeroExtendedChroma // //----------------------------------------------------------------------------- __inline void Get8888ZeroExtendedChroma( P3_THUNKEDDATA* pThisDisplay, DWORD dwSurfFlags, DDPIXELFORMAT* pSurfPixFormat, DWORD LowerBound, DWORD UpperBound, DWORD* OutLowerBound, DWORD* OutUpperBound) { DDPIXELFORMAT* pPixFormat; DWORD InLowerBound = LowerBound; DWORD InUpperBound = UpperBound; DISPDBG((DBGLVL, "InLowerBound = 0x%08X", InLowerBound)); DISPDBG((DBGLVL, "InUpperBound = 0x%08X", InUpperBound)); // Get a pointer to the pixelformat data (not guaranteed to exist. // If it doesn't, we use the same format as the display. if (DDSurf_HasPixelFormat(dwSurfFlags)) { pPixFormat = pSurfPixFormat; } else { pPixFormat = &pThisDisplay->ddpfDisplay; } { DWORD RedMask = pPixFormat->dwRBitMask; DWORD AlphaMask = pPixFormat->dwRGBAlphaBitMask; switch (pPixFormat->dwRGBBitCount) { // 8 Bit RGB Textures case 8: if (RedMask == 0xE0) { // Never any alpha *OutLowerBound = CHROMA_LOWER_ALPHA(FORMAT_332_32BIT_ZEROEXTEND(InLowerBound)); *OutUpperBound = CHROMA_UPPER_ALPHA(FORMAT_332_32BIT_ZEROEXTEND(InUpperBound)); } else { *OutLowerBound = FORMAT_2321_32BIT_ZEROEXTEND(InLowerBound); *OutUpperBound = FORMAT_2321_32BIT_ZEROEXTEND(InUpperBound); if (!AlphaMask) { *OutLowerBound = CHROMA_LOWER_ALPHA(*OutLowerBound); *OutUpperBound = CHROMA_UPPER_ALPHA(*OutUpperBound); } } break; // 16 Bit RGB Textures case 16: switch (RedMask) { case 0xf00: *OutLowerBound = (FORMAT_4444_32BIT_ZEROEXTEND(InLowerBound)); *OutUpperBound = (FORMAT_4444_32BIT_ZEROEXTEND(InUpperBound)); break; case 0x7c00: *OutLowerBound = FORMAT_5551_32BIT_ZEROEXTEND(InLowerBound); *OutUpperBound = FORMAT_5551_32BIT_ZEROEXTEND(InUpperBound); if (!AlphaMask) { *OutLowerBound = CHROMA_LOWER_ALPHA(*OutLowerBound); *OutUpperBound = CHROMA_UPPER_ALPHA(*OutUpperBound); } break; default: // Always supply full range of alpha values to ensure test // is done *OutLowerBound = CHROMA_LOWER_ALPHA(FORMAT_565_32BIT_ZEROEXTEND(InLowerBound)); *OutUpperBound = CHROMA_UPPER_ALPHA(FORMAT_565_32BIT_ZEROEXTEND(InUpperBound)); break; } break; // 32/24 Bit RGB Textures case 24: case 32: // If the surface isn't alpha'd then set a valid // range of alpha to catch all cases. if (!AlphaMask) { *OutLowerBound = CHROMA_LOWER_ALPHA(FORMAT_8888_32BIT_BGR(InLowerBound)); *OutUpperBound = CHROMA_UPPER_ALPHA(FORMAT_8888_32BIT_BGR(InUpperBound)); } else { *OutLowerBound = FORMAT_8888_32BIT_BGR(InLowerBound); *OutUpperBound = FORMAT_8888_32BIT_BGR(InUpperBound); } break; } // switch (pPixFormat->dwRGBBitCount) DISPDBG((DBGLVL, "OutLowerBound = 0x%08X", *OutLowerBound)); DISPDBG((DBGLVL, "OutUpperBound = 0x%08X", *OutUpperBound)); } } // Get8888ZeroExtendedChroma
2.03125
2
2024-11-18T19:27:08.315318+00:00
2020-06-15T17:57:17
c0171735a9c3fd11a21fb4aead75e7d5fe81858e
{ "blob_id": "c0171735a9c3fd11a21fb4aead75e7d5fe81858e", "branch_name": "refs/heads/master", "committer_date": "2020-06-15T17:57:17", "content_id": "714403098645972d257fd252d01600970197aa0b", "detected_licenses": [ "MIT" ], "directory_id": "c2275b1ff4206872c8b49c3c8c623fc060b49e10", "extension": "c", "filename": "ForLoopBubbleSort.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 270823827, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1293, "license": "MIT", "license_type": "permissive", "path": "/ForLoopBubbleSort.c", "provenance": "stackv2-0012.json.gz:183108", "repo_name": "Dkaban/CPractice", "revision_date": "2020-06-15T17:57:17", "revision_id": "9f0f7c85400ea8b8dd06d0555bd93873027fc678", "snapshot_id": "848d21f0f8ab2fec7d7ef1c97a7a0a0c5b52e1b4", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Dkaban/CPractice/9f0f7c85400ea8b8dd06d0555bd93873027fc678/ForLoopBubbleSort.c", "visit_date": "2022-11-02T04:37:20.596373" }
stackv2
// THE PROBLEM // *************************** // Creating a bubble sort using for loops in C // Print out the total number of swaps performed, along with first element and last element after sorting. // Solution Created By: Dustin Kaban // Date: June 15th, 2020 // *************************** #include <math.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <assert.h> #include <limits.h> #include <stdbool.h> void printDetails(int a[], int totalSwaps, int n) { printf("Array is sorted in %d swaps.\n",totalSwaps); printf("First Element: %d\n",a[0]); printf("Last Element: %d",a[n-1]); } void forLoopBubbleSort(int* a, int n) { int totalSwaps = 0; for(int i=0;i<n;i++) { int numSwaps = 0; for(int j=0;j<n-1;j++) { if(a[j] > a[j+1]) { int temp = a[j]; a[j] = a[j+1]; a[j+1] = temp; numSwaps++; totalSwaps++; } } if(numSwaps == 0) break; } printDetails(a, totalSwaps, n); } int main() { int n; scanf("%d", &n); int *a = malloc(sizeof(int) * n); for(int a_i = 0; a_i < n; a_i++){ scanf("%d",&a[a_i]); } forLoopBubbleSort(a,n); return 0; }
3.875
4
2024-11-18T19:27:08.578015+00:00
2020-03-26T08:06:47
8683ed8f9517684b2c4ca6f91030f3fc376e412c
{ "blob_id": "8683ed8f9517684b2c4ca6f91030f3fc376e412c", "branch_name": "refs/heads/master", "committer_date": "2020-03-26T08:06:47", "content_id": "009e5f43391eb53ba794b68abeaf51991b591dee", "detected_licenses": [ "MIT" ], "directory_id": "34fa261e36a3201c37ee747a0875631a6a8254c0", "extension": "h", "filename": "lcd.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3997, "license": "MIT", "license_type": "permissive", "path": "/driver/LCD_ili9341/lcd.h", "provenance": "stackv2-0012.json.gz:183364", "repo_name": "xsjames/tiny_posix", "revision_date": "2020-03-26T08:06:47", "revision_id": "a3638366032041433e53a118b805177f50e76bed", "snapshot_id": "d2433e9b6ad7a97af9b29a23aca100545007633e", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/xsjames/tiny_posix/a3638366032041433e53a118b805177f50e76bed/driver/LCD_ili9341/lcd.h", "visit_date": "2022-04-11T04:49:27.234869" }
stackv2
#ifndef __LCD_H #define __LCD_H #include <stdlib.h> #include <stdint.h> #include "tiny_posix.h" ////////////////////////////////////////////////////////////////////////////////// typedef uint8_t u8; typedef uint16_t u16; typedef uint32_t u32; //LCD驱动参数 extern uint16_t lcd_id; //LCD ID extern uint8_t dir_flag; //横屏还是竖屏控制:0,竖屏;1,横屏。 extern uint16_t lcd_width; //LCD 宽度 extern uint16_t lcd_height; //LCD 高度 extern uint16_t write_gramcmd; //写gram指令 extern uint16_t setxcmd; //设置x坐标指令 extern uint16_t setycmd; //设置y坐标指令 //LCD的画笔颜色和背景色 extern uint16_t BRUSH_COLOR;//默认红色 extern uint16_t BACK_COLOR; //背景颜色.默认为白色 ////////////////////////////////////////////////////////////////////////////////// //-----------------LCD背光端口定义---------------- #define LCD_BACK GPIO_FD(PORTF,10) //LCD背光 PF10 //A12作为数据命令区分线 设置时STM32内部会右移一位对齐 #define CMD_BASE ((uint32_t)(0x6C000000 | 0x00001FFE)) #define DATA_BASE ((uint32_t)(0x6C000000 | 0x00002000)) #define LCD_CMD ( * (uint16_t *) CMD_BASE ) #define LCD_DATA ( * (uint16_t *) DATA_BASE) //扫描方向定义 #define L2R_U2D 0 //从左到右,从上到下 #define L2R_D2U 1 //从左到右,从下到上 #define R2L_U2D 2 //从右到左,从上到下 #define R2L_D2U 3 //从右到左,从下到上 #define U2D_L2R 4 //从上到下,从左到右 #define U2D_R2L 5 //从上到下,从右到左 #define D2U_L2R 6 //从下到上,从左到右 #define D2U_R2L 7 //从下到上,从右到左 //颜色值定义 #define WHITE 0xFFFF #define BLACK 0x0000 #define RED 0xF800 #define GREEN 0x07E0 #define BLUE 0x001F #define BRED 0XF81F #define GRED 0XFFE0 #define GBLUE 0X07FF #define BROWN 0XBC40 #define BRRED 0XFC07 #define GRAY 0X8430 #define MAGENTA 0xF81F #define CYAN 0x7FFF #define YELLOW 0xFFE0 void LCD_WriteReg(uint16_t LCD_Reg, uint16_t LCD_Value); uint16_t LCD_ReadReg(uint16_t LCD_Reg); void LCD_WriteGRAM(void); void LCD_Init(void); //初始化 void LCD_DisplayOn(void); //开显示 void LCD_DisplayOff(void); //关显示 void LCD_Clear(uint16_t Color); //清屏 void LCD_SetCursor(uint16_t Xpos, uint16_t Ypos); //设置光标 void LCD_DrawPoint(uint16_t x,uint16_t y); //画点 void LCD_Color_DrawPoint(uint16_t x,uint16_t y,uint16_t color); //颜色画点 uint16_t LCD_GetPoint(uint16_t x,uint16_t y); //读点 void LCD_Open_Window(uint16_t X0,uint16_t Y0,uint16_t width,uint16_t height); void Set_Scan_Direction(uint8_t direction); void Set_Display_Mode(uint8_t mode); void LCD_Fill_onecolor(uint16_t sx,uint16_t sy,uint16_t ex,uint16_t ey,uint16_t color); //填充单个颜色 void LCD_Draw_Picture(uint16_t sx,uint16_t sy,uint16_t ex,uint16_t ey,uint16_t *color); //填充指定颜色 void LCD_DisplayChar(uint16_t x,uint16_t y,uint8_t word,uint8_t size); //显示一个字符 void LCD_DisplayString(uint16_t x,uint16_t y,uint8_t size,const char *p); //显示一个12/16/24字体字符串 void LCD_DisplayString_color(uint16_t x,uint16_t y,uint8_t size,const char *p,uint16_t brushcolor,uint16_t backcolor); //显示一个12/16/24字体自定义颜色的字符串 void LCD_DisplayNum(uint16_t x,uint16_t y,uint32_t num,uint8_t len,uint8_t size,uint8_t mode); //显示 数字 void LCD_DisplayNum_color(uint16_t x,uint16_t y,uint32_t num,uint8_t len,uint8_t size,uint8_t mode,uint16_t brushcolor,uint16_t backcolor); //显示自定义颜色数字 #endif
2.34375
2
2024-11-18T19:27:08.662158+00:00
2016-05-18T19:42:46
6dcf4df8384e315b29ac29d451972f72f6c9b536
{ "blob_id": "6dcf4df8384e315b29ac29d451972f72f6c9b536", "branch_name": "refs/heads/master", "committer_date": "2016-05-18T19:42:46", "content_id": "ad28176d91bb48f82e094e24e60639472472f078", "detected_licenses": [ "MIT" ], "directory_id": "de6604045fb627b86b6bb03c9f99fc69ed01a954", "extension": "c", "filename": "pg_concat_ws.c", "fork_events_count": 3, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 59128508, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1682, "license": "MIT", "license_type": "permissive", "path": "/pg/STRING/pg_concat_ws.c", "provenance": "stackv2-0012.json.gz:183492", "repo_name": "sfaroult/sqlite_libs", "revision_date": "2016-05-18T19:42:46", "revision_id": "c9d3937ce1756eab4c8d9dab5aede889393830e8", "snapshot_id": "a522433a39c6352c2fcc11f6d7369face2f600f8", "src_encoding": "UTF-8", "star_events_count": 7, "url": "https://raw.githubusercontent.com/sfaroult/sqlite_libs/c9d3937ce1756eab4c8d9dab5aede889393830e8/pg/STRING/pg_concat_ws.c", "visit_date": "2016-09-14T08:26:24.877481" }
stackv2
/* * Input : select concat_ws(',','test','complete'); Output : test,complete * */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <errno.h> #include <ksu_common.h> extern void pg_concat_ws(sqlite3_context * context, int argc, sqlite3_value ** argv) { int len = 0; //Required length int seplen; char *con; char *result; _ksu_check_arg_cnt(argc, 2, -1, "concat_ws"); //Check whether the separator is null if (sqlite3_value_type(argv[0]) == SQLITE_NULL) { sqlite3_result_null(context); return; } seplen = strlen((char *)sqlite3_value_text(argv[0])); int j; for (j = 1; j < argc; j++) { if (sqlite3_value_type(argv[j]) != SQLITE_NULL) { len = len + seplen + strlen((char *)sqlite3_value_text(argv[j])); } } if ((result = (char *)sqlite3_malloc(len + 1)) == NULL) { sqlite3_result_null(context); return; } con = (char *)sqlite3_value_text(argv[0]); int x; result[0] = '\0'; for (x = 1; x < argc; x++) { if (sqlite3_value_type(argv[x]) != SQLITE_NULL) { if (x > 1) { strcat(result, con); } strcat(result, (char *)sqlite3_value_text(argv[x])); } } sqlite3_result_text(context, (char *)result, -1, sqlite3_free); }
2.71875
3
2024-11-18T19:27:08.854823+00:00
2021-05-19T23:27:58
5a801c73b560b6609b8e7b872cebfda745ae8f27
{ "blob_id": "5a801c73b560b6609b8e7b872cebfda745ae8f27", "branch_name": "refs/heads/master", "committer_date": "2021-05-19T23:27:58", "content_id": "f583976c3083733bb29b04098f485097a1fa8f6b", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "c3f0281b88bf71eb1be515e3af43d70d83442bb7", "extension": "c", "filename": "control.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5073, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/engine/ps3/control.c", "provenance": "stackv2-0012.json.gz:183750", "repo_name": "dongp314/OpenBOR_PLUS", "revision_date": "2021-05-19T23:27:58", "revision_id": "5d6ec202f0e6513ebc657c61af057dd8e458440c", "snapshot_id": "416098cc70cf68de34f51f3d1a34b509b52f5e62", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/dongp314/OpenBOR_PLUS/5d6ec202f0e6513ebc657c61af057dd8e458440c/engine/ps3/control.c", "visit_date": "2023-05-02T05:40:04.058788" }
stackv2
/* * OpenBOR - http://www.LavaLit.com * ----------------------------------------------------------------------- * Licensed under the BSD license, see LICENSE in OpenBOR root for details. * * Copyright (c) 2004 - 2011 OpenBOR Team */ #include <string.h> #include <io/pad.h> #include "video.h" #include "globals.h" #include "control.h" #include "stristr.h" #include "sblaster.h" #include "openbor.h" #define PAD_START 1 #define PAD_END (BTN_NUM*MAX_BOR_PADS) #define ANAG_STAND 0x80 #define PAD_STICK_DEADZONE 0x70 static int usejoy; static int lastkey[MAX_BOR_PADS]; static padData paddata[MAX_BOR_PADS]; static const char *padnames[PAD_END + 1 + 1] = { "...", #define CONTROLNAMES(x) \ x" Up", \ x" Right", \ x" Down", \ x" Left", \ x" Square", \ x" Triangle", \ x" Cross", \ x" Circle", \ x" L2", \ x" R2", \ x" Start", \ x" Select", \ x" L1", \ x" R1", \ x" L3", \ x" R3", CONTROLNAMES("P3 1") CONTROLNAMES("P3 2") CONTROLNAMES("P3 3") CONTROLNAMES("P3 4") "undefined" }; static int flag_to_index(unsigned int flag) { int index = 0; unsigned int bit = 1; while (!((bit<<index)&flag) && index<31) ++index; return index; } void control_exit() { usejoy = 0; ioPadEnd(); } void control_init(int joy_enable) { usejoy = joy_enable; ioPadInit(MAX_BOR_PADS); } int control_usejoy(int enable) { usejoy = enable; return 0; } int control_getjoyenabled() { return usejoy; } int keyboard_getlastkey(void) { int i, ret=0; for (i=0; i<MAX_BOR_PADS; i++) { ret |= lastkey[i]; lastkey[i] = 0; } return ret; } void control_setkey(s_playercontrols * pcontrols, unsigned int flag, int key) { if (!pcontrols) return; pcontrols->settings[flag_to_index(flag)] = key; pcontrols->keyflags = pcontrols->newkeyflags = 0; } // Scan input for newly-pressed keys. // Return value: // 0 = no key was pressed // >0 = key code for pressed key // <0 = error int control_scankey() { static unsigned ready = 0; unsigned i, k=0; for (i=0; i<MAX_BOR_PADS; i++) { if (lastkey[i]) { k = 1 + i*BTN_NUM + flag_to_index(lastkey[i]); break; } } if (ready && k) { ready = 0; return k; } ready = (!k); return 0; } char * control_getkeyname(unsigned keycode) { if (keycode >= PAD_START && keycode <= PAD_END) return (char*)padnames[keycode]; return "..."; } void control_update(s_playercontrols ** playercontrols, int numplayers) { unsigned int k; unsigned int i; int player; int t; s_playercontrols * pcontrols; unsigned port[MAX_BOR_PADS]; padInfo padinfo; ioPadGetInfo (&padinfo); for (i = 0; i < MAX_BOR_PADS; i++) { port[i] = 0; if (padinfo.status[i]) { port[i] = getPad(i); } } for (player = 0; player < numplayers; player++) { pcontrols = playercontrols[player]; k = 0; for (i = 0; i < MAX_INPUT; i++) { t = pcontrols->settings[i]; if (t >= PAD_START && t <= PAD_END) { int portnum = (t-1) / BTN_NUM; int shiftby = (t-1) % BTN_NUM; if (portnum >= 0 && portnum < MAX_BOR_PADS) { if ((port[portnum] >> shiftby) & 1) k |= (1<<i); } } } pcontrols->kb_break = 0; pcontrols->newkeyflags = k & (~pcontrols->keyflags); pcontrols->keyflags = k; } } void control_rumble(s_playercontrols ** playercontrols, int player, int ratio, int msec) { padActParam actparam; actparam.small_motor = 1; actparam.large_motor = (255 * ratio) / 100; ioPadSetActDirect(player, &actparam); } unsigned int getPad(int port) { unsigned int btns = 0; ioPadGetData(port, &paddata[port]); if (control_getjoyenabled()) { if (paddata[port].ANA_L_V > ANAG_STAND + PAD_STICK_DEADZONE) btns |= PS3_DPAD_DOWN; else if (paddata[port].ANA_L_V < ANAG_STAND - PAD_STICK_DEADZONE) btns |= PS3_DPAD_UP; if (paddata[port].ANA_L_H < ANAG_STAND - PAD_STICK_DEADZONE) btns |= PS3_DPAD_LEFT; else if (paddata[port].ANA_L_H > ANAG_STAND + PAD_STICK_DEADZONE) btns |= PS3_DPAD_RIGHT; } if (paddata[port].BTN_SELECT) btns |= PS3_SELECT; if (paddata[port].BTN_START) btns |= PS3_START; if (paddata[port].BTN_UP) btns |= PS3_DPAD_UP; if (paddata[port].BTN_RIGHT) btns |= PS3_DPAD_RIGHT; if (paddata[port].BTN_DOWN) btns |= PS3_DPAD_DOWN; if (paddata[port].BTN_LEFT) btns |= PS3_DPAD_LEFT; if (paddata[port].BTN_TRIANGLE) btns |= PS3_TRIANGLE; if (paddata[port].BTN_CIRCLE) btns |= PS3_CIRCLE; if (paddata[port].BTN_CROSS) btns |= PS3_CROSS; if (paddata[port].BTN_SQUARE) btns |= PS3_SQUARE; if (paddata[port].BTN_L2) btns |= PS3_L2; if (paddata[port].BTN_R2) btns |= PS3_R2; if (paddata[port].BTN_L1) btns |= PS3_L1; if (paddata[port].BTN_R1) btns |= PS3_R1; if (paddata[port].BTN_L3) btns |= PS3_L3; if (paddata[port].BTN_R3) btns |= PS3_R3; return lastkey[port] = btns; }
2.203125
2
2024-11-18T19:27:10.027086+00:00
2015-06-25T08:16:46
fb9b5b324bc6cf550def02f99d07fd235ee691be
{ "blob_id": "fb9b5b324bc6cf550def02f99d07fd235ee691be", "branch_name": "refs/heads/master", "committer_date": "2015-06-25T08:16:46", "content_id": "013abdc8638a1e5bb65646d5f8ec949032d3d5c7", "detected_licenses": [ "Unlicense" ], "directory_id": "74552bb39f067e2137cd51dfa0a8f8d20559b75d", "extension": "c", "filename": "elettromagnetismo.c", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 17003984, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1166, "license": "Unlicense", "license_type": "permissive", "path": "/src/elettromagnetismo.c", "provenance": "stackv2-0012.json.gz:184390", "repo_name": "Adrenocortico/FormulePebble", "revision_date": "2015-06-25T08:16:46", "revision_id": "79626ff9b9813076fb0a07a74bbeb1e212da4e45", "snapshot_id": "46bd0a16c5a8dd4f51fbe55e51dcc5f037d99f75", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/Adrenocortico/FormulePebble/79626ff9b9813076fb0a07a74bbeb1e212da4e45/src/elettromagnetismo.c", "visit_date": "2020-05-29T12:25:57.420604" }
stackv2
#include "pebble.h" #include "elettromagnetismo.h" #define NUM_ELET_MENU_ITEMS 1 static Window *window; static SimpleMenuLayer *simple_menu_layer; static SimpleMenuSection menu_sections; static SimpleMenuItem elet_menu_items[NUM_ELET_MENU_ITEMS]; static void window_unload(Window *window) { simple_menu_layer_destroy(simple_menu_layer); window_destroy(window); } static void window_load(Window *window) { int num_a_items = 0; elet_menu_items[num_a_items++] = (SimpleMenuItem){ .title = "Forza di Coulomb", .subtitle = "F=k(|q1||q2|)/(d²)" }; menu_sections.num_items = NUM_ELET_MENU_ITEMS; menu_sections.items = elet_menu_items; Layer *window_layer = window_get_root_layer(window); GRect bounds = layer_get_frame(window_layer); simple_menu_layer = simple_menu_layer_create(bounds, window, &menu_sections, 1, NULL); layer_add_child(window_layer, simple_menu_layer_get_layer(simple_menu_layer)); } void show_elet_menu(){ window = window_create(); window_set_window_handlers(window, (WindowHandlers) { .load = window_load, .unload = window_unload, }); window_stack_push(window, true /* Animated */); }
2.125
2
2024-11-18T19:27:10.112530+00:00
2021-12-21T14:27:09
77dcb962cecc318c5b44cb2f5a0a66fe3dac4319
{ "blob_id": "77dcb962cecc318c5b44cb2f5a0a66fe3dac4319", "branch_name": "refs/heads/master", "committer_date": "2021-12-21T14:27:09", "content_id": "e2b587e2c2203d2293ce5752796fc8e32b128a0e", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "fead6fdd7f26bf55bb224a1d340b2c3897bf6bda", "extension": "c", "filename": "Edges.c", "fork_events_count": 9, "gha_created_at": "2016-11-24T15:39:42", "gha_event_created_at": "2017-12-18T18:49:15", "gha_language": "C", "gha_license_id": "BSD-3-Clause", "github_id": 74685939, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5555, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/src/lib_viaio/Edges.c", "provenance": "stackv2-0012.json.gz:184519", "repo_name": "lipsia-fmri/lipsia", "revision_date": "2021-12-21T14:27:09", "revision_id": "d3190204def34f952b899d3cb37c1a9cef5be6d8", "snapshot_id": "27f9986482b0256eb9f0c72307928bf49c0e9091", "src_encoding": "UTF-8", "star_events_count": 20, "url": "https://raw.githubusercontent.com/lipsia-fmri/lipsia/d3190204def34f952b899d3cb37c1a9cef5be6d8/src/lib_viaio/Edges.c", "visit_date": "2021-12-23T13:22:57.565590" }
stackv2
/* * $Id: Edges.c 3177 2008-04-01 14:47:24Z karstenm $ * * This file provides basic support for edges (the VEdges class). */ /* * Copyright 1993, 1994 University of British Columbia * * 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 appears in all copies and that both that * copyright notice and this permission notice appear in supporting * documentation. UBC makes no representations about the suitability of this * software for any purpose. It is provided "as is" without express or * implied warranty. * * Author: David Lowe, UBC Laboratory for Computational Intelligence */ /* From the Vista library: */ #include "viaio/Vlib.h" #include "viaio/file.h" #include "viaio/os.h" #include "viaio/VEdges.h" /* File identification string: */ VRcsId ("$Id: Edges.c 3177 2008-04-01 14:47:24Z karstenm $"); /* * VCreateEdges * * Allocates memory for a VEdges structure and initializes its fields. * Initially, this contains zero edges, so each edge must still * be created and added to this record. * Returns a pointer to the edges if successful, NULL otherwise. */ VEdges VCreateEdges (int nrows, int ncolumns, int nedge_fields, int npoint_fields) { VEdges edges; /* Check parameters: */ if (nrows < 1 || ncolumns < 1) VWarning ("VCreateEdges: Invalid number of rows or columns."); /* Allocate memory for the VEdges, its indices, and pixel values: */ edges = VMalloc (sizeof (VEdgesRec)); /* Initialize the VEdges: */ edges->nrows = nrows; edges->ncolumns = ncolumns; edges->attributes = VCreateAttrList (); edges->nedge_fields = nedge_fields; edges->npoint_fields = npoint_fields; edges->nedges = edges->npoints = 0; edges->first = edges->last = NULL; edges->free = NULL; return edges; } /* * VAddEdge * * Add an edge to the given Edges record. If the "copy" argument is * TRUE, then new space is allocated to copy the points and the fields * of this edge. Otherwise, a pointer is created to their current * location. * "npoints" is the number of points in this edge, and "closed" indicates * if this is a closed edge. */ VEdge VAddEdge (VEdges edges, VFloat *edge_fields, int npoints, VFloat *points, VBooleanPromoted closed, VBooleanPromoted copy) { VEdge edge = VMalloc (sizeof (VEdgeRec)); size_t fsize, psize, isize; int i; VPointer p; VFloat *pdata; /* Add the edge to the end of the current list of edges in order to maintain a consistent ordering of edges during IO. */ if (edges->last == NULL) edges->first = edge; else edges->last->next = edge; edges->last = edge; edge->next = NULL; edges->nedges += 1; edges->npoints += npoints; edge->npoints = npoints; edge->closed = closed; isize = sizeof (VFloat *) * npoints; /* Size of points index array. */ /* If copying data, enough space is allocated to hold everything. */ if (copy) { #ifndef __alpha fsize = sizeof (VFloat) * edges->nedge_fields; psize = sizeof (VFloat) * npoints * edges->npoint_fields; #else /* pointers must be quadword-aligned on a DEC alpha */ #define quadalign(a) ((((a)-1)/8+1)*8) fsize = quadalign(sizeof (VFloat) * edges->nedge_fields); psize = quadalign(sizeof (VFloat) * npoints * edges->npoint_fields); #endif p = VMalloc (fsize + psize + isize); edge->free = p; edge->edge_fields = (VFloat *) p; if (fsize > 0) memcpy (p, edge_fields, fsize); pdata = (VFloat *) ((char *) p + fsize); memcpy (pdata, points, psize); edge->point_index = (VFloat **) ((char *) p + fsize + psize); } else { p = VMalloc (isize); edge->free = p; edge->edge_fields = edge_fields; pdata = points; edge->point_index = (VFloat **) p; } /* Initialize index array into set of points. */ for (i = 0; i < npoints; i++) edge->point_index[i] = pdata + i * edges->npoint_fields; return edge; } /* * VCopyEdges * * Copy a VEdges object. */ VEdges VCopyEdges (VEdges src) { VEdges result; VEdge e; result = VCreateEdges (src->nrows, src->ncolumns, src->nedge_fields, src->npoint_fields); for (e = src->first; e != NULL; e = e->next) VAddEdge (result, e->edge_fields, e->npoints, e->point_index[0], e->closed, TRUE); if (VEdgesAttrList (result)) VDestroyAttrList (VEdgesAttrList (result)); if (VEdgesAttrList (src)) VEdgesAttrList (result) = VCopyAttrList (VEdgesAttrList (src)); return result; } /* * VDestroyEdges * * Frees memory occupied by set of edges. */ void VDestroyEdges (VEdges edges) { VEdge edge, next_edge; for (edge = edges->first; edge; edge = next_edge) { next_edge = edge->next; if (edge->free) VFree (edge->free); } if (edges->free) VFree (edges->free); VDestroyAttrList (edges->attributes); VFree (edges); } /* * VReadEdges * * Read a Vista data file, extract the edge sets from it, and return a list * of them. */ int VReadEdges (FILE *file, VAttrList *attributes, VEdges **edge_sets) { return VReadObjects (file, VEdgesRepn, attributes, (VPointer **) edge_sets); } /* * VWriteEdges * * Write a list of edge sets to a Vista data file. */ VBoolean VWriteEdges (FILE *file, VAttrList attributes, int nedge_sets, VEdges edge_sets[]) { return VWriteObjects (file, VEdgesRepn, attributes, nedge_sets, (VPointer *) edge_sets); }
2.296875
2
2024-11-18T19:27:10.254105+00:00
2023-06-01T16:34:30
797896bee5a9b2a4fca12689db6f576d4a5c4d72
{ "blob_id": "797896bee5a9b2a4fca12689db6f576d4a5c4d72", "branch_name": "refs/heads/master", "committer_date": "2023-06-01T16:34:30", "content_id": "3d312dabe2c7cf2466dc11d864ab40dcbc8b7bbd", "detected_licenses": [ "MIT", "Apache-2.0" ], "directory_id": "06399145c01341470e9eb3644b0376739fabd9c9", "extension": "c", "filename": "readstat_xport_write.c", "fork_events_count": 56, "gha_created_at": "2018-08-21T08:58:10", "gha_event_created_at": "2023-08-21T09:37:35", "gha_language": "C", "gha_license_id": "NOASSERTION", "github_id": 145536189, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 18277, "license": "MIT,Apache-2.0", "license_type": "permissive", "path": "/src/sas/readstat_xport_write.c", "provenance": "stackv2-0012.json.gz:184776", "repo_name": "Roche/pyreadstat", "revision_date": "2023-06-01T16:34:30", "revision_id": "03214b86bb8be8fd97910b37ff825f9d7531089a", "snapshot_id": "fad1823b5d0cb9cd060e45e7741ac2212140f59d", "src_encoding": "UTF-8", "star_events_count": 286, "url": "https://raw.githubusercontent.com/Roche/pyreadstat/03214b86bb8be8fd97910b37ff825f9d7531089a/src/sas/readstat_xport_write.c", "visit_date": "2023-08-09T07:44:36.516302" }
stackv2
#include <stdio.h> #include <stdlib.h> #include <time.h> #include "../readstat.h" #include "../readstat_writer.h" #include "readstat_sas.h" #include "readstat_xport.h" #include "readstat_xport_parse_format.h" #include "ieee.h" #define XPORT_DEFAULT_VERISON 8 #define RECORD_LEN 80 #if defined _MSC_VER #define restrict __restrict #endif static void copypad(char * restrict dst, size_t dst_len, const char * restrict src) { char *dst_end = dst + dst_len; while (dst < dst_end && *src) *dst++ = *src++; while (dst < dst_end) *dst++ = ' '; } static readstat_error_t xport_write_bytes(readstat_writer_t *writer, const void *bytes, size_t len) { return readstat_write_bytes_as_lines(writer, bytes, len, RECORD_LEN, ""); } static readstat_error_t xport_finish_record(readstat_writer_t *writer) { return readstat_write_line_padding(writer, ' ', RECORD_LEN, ""); } static readstat_error_t xport_write_record(readstat_writer_t *writer, const char *record) { size_t len = strlen(record); readstat_error_t retval = READSTAT_OK; retval = xport_write_bytes(writer, record, len); if (retval != READSTAT_OK) goto cleanup; retval = xport_finish_record(writer); if (retval != READSTAT_OK) goto cleanup; cleanup: return retval; } static readstat_error_t xport_write_header_record_v8(readstat_writer_t *writer, xport_header_record_t *xrecord) { char record[RECORD_LEN+1]; snprintf(record, sizeof(record), "HEADER RECORD*******%-8sHEADER RECORD!!!!!!!%-30d", xrecord->name, xrecord->num1); return xport_write_record(writer, record); } static readstat_error_t xport_write_header_record(readstat_writer_t *writer, xport_header_record_t *xrecord) { char record[RECORD_LEN+1]; snprintf(record, sizeof(record), "HEADER RECORD*******%-8sHEADER RECORD!!!!!!!" "%05d%05d%05d" "%05d%05d%05d", xrecord->name, xrecord->num1, xrecord->num2, xrecord->num3, xrecord->num4, xrecord->num5, xrecord->num6); return xport_write_record(writer, record); } static size_t xport_variable_width(readstat_type_t type, size_t user_width) { if (type == READSTAT_TYPE_STRING) return user_width; if (user_width >= XPORT_MAX_DOUBLE_SIZE || user_width == 0) return XPORT_MAX_DOUBLE_SIZE; if (user_width <= XPORT_MIN_DOUBLE_SIZE) return XPORT_MIN_DOUBLE_SIZE; return user_width; } static readstat_error_t xport_write_variables(readstat_writer_t *writer) { readstat_error_t retval = READSTAT_OK; int i; long offset = 0; int num_long_labels = 0; int any_has_long_format = 0; for (i=0; i<writer->variables_count; i++) { int needs_long_record = 0; readstat_variable_t *variable = readstat_get_variable(writer, i); size_t width = xport_variable_width(variable->type, variable->user_width); xport_namestr_t namestr = { .nvar0 = i+1, .nlng = width, .npos = offset, .niform = " ", .nform = " " }; if (readstat_variable_get_type_class(variable) == READSTAT_TYPE_CLASS_STRING) { namestr.ntype = SAS_COLUMN_TYPE_CHR; } else { namestr.ntype = SAS_COLUMN_TYPE_NUM; } copypad(namestr.nname, sizeof(namestr.nname), variable->name); copypad(namestr.nlabel, sizeof(namestr.nlabel), variable->label); if (variable->format[0]) { xport_format_t format; retval = xport_parse_format(variable->format, strlen(variable->format), &format, NULL, NULL); if (retval != READSTAT_OK) goto cleanup; copypad(namestr.nform, sizeof(namestr.nform), format.name); namestr.nfl = format.width; namestr.nfd = format.decimals; copypad(namestr.niform, sizeof(namestr.niform), format.name); namestr.nifl = format.width; namestr.nifd = format.decimals; if (strlen(format.name) > 8) { any_has_long_format = 1; needs_long_record = 1; } } else if (variable->display_width) { namestr.nfl = variable->display_width; } namestr.nfj = (variable->alignment == READSTAT_ALIGNMENT_RIGHT); if (writer->version == 8) { copypad(namestr.longname, sizeof(namestr.longname), variable->name); size_t label_len = strlen(variable->label); if (label_len > 40) { needs_long_record = 1; } namestr.labeln = label_len; } if (needs_long_record) { num_long_labels++; } offset += width; xport_namestr_bswap(&namestr); retval = xport_write_bytes(writer, &namestr, sizeof(xport_namestr_t)); if (retval != READSTAT_OK) goto cleanup; } retval = xport_finish_record(writer); if (retval != READSTAT_OK) goto cleanup; if (writer->version == 8 && num_long_labels) { xport_header_record_t header = { .name = "LABELV8", .num1 = num_long_labels }; if (any_has_long_format) { strcpy(header.name, "LABELV9"); } retval = xport_write_header_record_v8(writer, &header); if (retval != READSTAT_OK) goto cleanup; for (i=0; i<writer->variables_count; i++) { readstat_variable_t *variable = readstat_get_variable(writer, i); size_t label_len = strlen(variable->label); size_t name_len = strlen(variable->name); size_t format_len = strlen(variable->format); int has_long_label = 0; int has_long_format = 0; has_long_label = (label_len > 40); if (variable->format[0]) { xport_format_t format; retval = xport_parse_format(variable->format, strlen(variable->format), &format, NULL, NULL); if (retval != READSTAT_OK) goto cleanup; if (strlen(format.name) > 8) { has_long_format = 1; } } if (has_long_format) { uint16_t labeldef[5] = { i+1, name_len, label_len, format_len, format_len }; if (machine_is_little_endian()) { labeldef[0] = byteswap2(labeldef[0]); labeldef[1] = byteswap2(labeldef[1]); labeldef[2] = byteswap2(labeldef[2]); labeldef[3] = byteswap2(labeldef[3]); labeldef[4] = byteswap2(labeldef[4]); } retval = readstat_write_bytes(writer, labeldef, sizeof(labeldef)); if (retval != READSTAT_OK) goto cleanup; retval = readstat_write_string(writer, variable->name); if (retval != READSTAT_OK) goto cleanup; retval = readstat_write_string(writer, variable->label); if (retval != READSTAT_OK) goto cleanup; retval = readstat_write_string(writer, variable->format); if (retval != READSTAT_OK) goto cleanup; retval = readstat_write_string(writer, variable->format); if (retval != READSTAT_OK) goto cleanup; } else if (has_long_label) { uint16_t labeldef[3] = { i+1, name_len, label_len }; if (machine_is_little_endian()) { labeldef[0] = byteswap2(labeldef[0]); labeldef[1] = byteswap2(labeldef[1]); labeldef[2] = byteswap2(labeldef[2]); } retval = readstat_write_bytes(writer, labeldef, sizeof(labeldef)); if (retval != READSTAT_OK) goto cleanup; retval = readstat_write_string(writer, variable->name); if (retval != READSTAT_OK) goto cleanup; retval = readstat_write_string(writer, variable->label); if (retval != READSTAT_OK) goto cleanup; } } retval = xport_finish_record(writer); if (retval != READSTAT_OK) goto cleanup; } cleanup: return retval; } static readstat_error_t xport_write_first_header_record(readstat_writer_t *writer) { xport_header_record_t xrecord = { .name = "LIBRARY" }; if (writer->version == 8) { strcpy(xrecord.name, "LIBV8"); } return xport_write_header_record(writer, &xrecord); } static readstat_error_t xport_write_first_real_header_record(readstat_writer_t *writer, const char *timestamp) { char real_record[RECORD_LEN+1]; snprintf(real_record, sizeof(real_record), "%-8.8s" "%-8.8s" "%-8.8s" "%-8.8s" "%-8.8s" "%-24.24s" "%16.16s", "SAS", "SAS", "SASLIB", "6.06", "bsd4.2", "", timestamp); return xport_write_record(writer, real_record); } static readstat_error_t xport_write_member_header_record(readstat_writer_t *writer) { xport_header_record_t xrecord = { .name = "MEMBER", .num4 = 160, .num6 = 140 }; if (writer->version == 8) { strcpy(xrecord.name, "MEMBV8"); } return xport_write_header_record(writer, &xrecord); } static readstat_error_t xport_write_descriptor_header_record(readstat_writer_t *writer) { xport_header_record_t xrecord = { .name = "DSCRPTR" }; if (writer->version == 8) { strcpy(xrecord.name, "DSCPTV8"); } return xport_write_header_record(writer, &xrecord); } static readstat_error_t xport_write_member_record_v8(readstat_writer_t *writer, char *timestamp) { readstat_error_t retval = READSTAT_OK; char member_header[RECORD_LEN+1]; char *ds_name = "DATASET"; if (writer->table_name[0]) ds_name = writer->table_name; snprintf(member_header, sizeof(member_header), "%-8.8s" "%-32.32s" "%-8.8s" "%-8.8s" "%-8.8s" "%16.16s", "SAS", ds_name, "SASDATA", "6.06", "bsd4.2", timestamp); retval = xport_write_record(writer, member_header); return retval; } static readstat_error_t xport_write_member_record(readstat_writer_t *writer, char *timestamp) { if (writer->version == 8) return xport_write_member_record_v8(writer, timestamp); readstat_error_t retval = READSTAT_OK; char member_header[RECORD_LEN+1]; char *ds_name = "DATASET"; if (writer->table_name[0]) ds_name = writer->table_name; snprintf(member_header, sizeof(member_header), "%-8.8s" "%-8.8s" "%-8.8s" "%-8.8s" "%-8.8s" "%-24.24s" "%16.16s", "SAS", ds_name, "SASDATA", "6.06", "bsd4.2", "", timestamp); retval = xport_write_record(writer, member_header); return retval; } static readstat_error_t xport_write_file_label_record(readstat_writer_t *writer, char *timestamp) { char member_header[RECORD_LEN+1]; snprintf(member_header, sizeof(member_header), "%16.16s" "%16.16s" "%-40.40s" "%-8.8s", timestamp, "", writer->file_label, "" /* dstype? */); return xport_write_record(writer, member_header); } static readstat_error_t xport_write_namestr_header_record(readstat_writer_t *writer) { xport_header_record_t xrecord = { .name = "NAMESTR", .num2 = writer->variables_count }; if (writer->version == 8) { strcpy(xrecord.name, "NAMSTV8"); } return xport_write_header_record(writer, &xrecord); } static readstat_error_t xport_write_obs_header_record(readstat_writer_t *writer) { xport_header_record_t xrecord = { .name = "OBS" }; if (writer->version == 8) { strcpy(xrecord.name, "OBSV8"); } return xport_write_header_record(writer, &xrecord); } static readstat_error_t xport_format_timestamp(char *output, size_t output_len, time_t timestamp) { struct tm *ts = localtime(&timestamp); if (!ts) return READSTAT_ERROR_BAD_TIMESTAMP_VALUE; snprintf(output, output_len, "%02d%3.3s%02d:%02d:%02d:%02d", (unsigned int)ts->tm_mday % 100, _xport_months[ts->tm_mon], (unsigned int)ts->tm_year % 100, (unsigned int)ts->tm_hour % 100, (unsigned int)ts->tm_min % 100, (unsigned int)ts->tm_sec % 100 ); return READSTAT_OK; } static readstat_error_t xport_begin_data(void *writer_ctx) { readstat_writer_t *writer = (readstat_writer_t *)writer_ctx; readstat_error_t retval = READSTAT_OK; char timestamp[17]; retval = xport_format_timestamp(timestamp, sizeof(timestamp), writer->timestamp); if (retval != READSTAT_OK) goto cleanup; retval = xport_write_first_header_record(writer); if (retval != READSTAT_OK) goto cleanup; retval = xport_write_first_real_header_record(writer, timestamp); if (retval != READSTAT_OK) goto cleanup; retval = xport_write_record(writer, timestamp); if (retval != READSTAT_OK) goto cleanup; retval = xport_write_member_header_record(writer); if (retval != READSTAT_OK) goto cleanup; retval = xport_write_descriptor_header_record(writer); if (retval != READSTAT_OK) goto cleanup; retval = xport_write_member_record(writer, timestamp); if (retval != READSTAT_OK) goto cleanup; retval = xport_write_file_label_record(writer, timestamp); if (retval != READSTAT_OK) goto cleanup; retval = xport_write_namestr_header_record(writer); if (retval != READSTAT_OK) goto cleanup; retval = xport_write_variables(writer); if (retval != READSTAT_OK) goto cleanup; retval = xport_write_obs_header_record(writer); if (retval != READSTAT_OK) goto cleanup; cleanup: return retval; } static readstat_error_t xport_end_data(void *writer_ctx) { readstat_writer_t *writer = (readstat_writer_t *)writer_ctx; readstat_error_t retval = READSTAT_OK; retval = xport_finish_record(writer); return retval; } static readstat_error_t xport_write_row(void *writer_ctx, void *row, size_t row_len) { readstat_writer_t *writer = (readstat_writer_t *)writer_ctx; return xport_write_bytes(writer, row, row_len); } static readstat_error_t xport_write_double(void *row, const readstat_variable_t *var, double value) { char full_value[8]; int rc = cnxptiee(&value, CN_TYPE_NATIVE, full_value, CN_TYPE_XPORT); if (rc) return READSTAT_ERROR_CONVERT; memcpy(row, full_value, var->storage_width); return READSTAT_OK; } static readstat_error_t xport_write_float(void *row, const readstat_variable_t *var, float value) { return xport_write_double(row, var, value); } static readstat_error_t xport_write_int32(void *row, const readstat_variable_t *var, int32_t value) { return xport_write_double(row, var, value); } static readstat_error_t xport_write_int16(void *row, const readstat_variable_t *var, int16_t value) { return xport_write_double(row, var, value); } static readstat_error_t xport_write_int8(void *row, const readstat_variable_t *var, int8_t value) { return xport_write_double(row, var, value); } static readstat_error_t xport_write_string(void *row, const readstat_variable_t *var, const char *string) { memset(row, ' ', var->storage_width); if (string != NULL && string[0]) { size_t value_len = strlen(string); if (value_len > var->storage_width) return READSTAT_ERROR_STRING_VALUE_IS_TOO_LONG; memcpy(row, string, value_len); } return READSTAT_OK; } static readstat_error_t xport_write_missing_numeric(void *row, const readstat_variable_t *var) { char *row_bytes = (char *)row; row_bytes[0] = 0x2e; return READSTAT_OK; } static readstat_error_t xport_write_missing_string(void *row, const readstat_variable_t *var) { return xport_write_string(row, var, NULL); } static readstat_error_t xport_write_missing_tagged(void *row, const readstat_variable_t *var, char tag) { char *row_bytes = (char *)row; readstat_error_t error = sas_validate_tag(tag); if (error == READSTAT_OK) { row_bytes[0] = tag; } return error; } static readstat_error_t xport_metadata_ok(void *writer_ctx) { readstat_writer_t *writer = (readstat_writer_t *)writer_ctx; if (writer->version != 5 && writer->version != 8) return READSTAT_ERROR_UNSUPPORTED_FILE_FORMAT_VERSION; if (writer->table_name[0]) { if (writer->version == 8) { return sas_validate_name(writer->table_name, 32); } if (writer->version == 5) { return sas_validate_name(writer->table_name, 8); } } return READSTAT_OK; } readstat_error_t readstat_begin_writing_xport(readstat_writer_t *writer, void *user_ctx, long row_count) { if (writer->version == 0) writer->version = XPORT_DEFAULT_VERISON; writer->callbacks.metadata_ok = &xport_metadata_ok; writer->callbacks.write_int8 = &xport_write_int8; writer->callbacks.write_int16 = &xport_write_int16; writer->callbacks.write_int32 = &xport_write_int32; writer->callbacks.write_float = &xport_write_float; writer->callbacks.write_double = &xport_write_double; writer->callbacks.write_string = &xport_write_string; writer->callbacks.write_missing_string = &xport_write_missing_string; writer->callbacks.write_missing_number = &xport_write_missing_numeric; writer->callbacks.write_missing_tagged = &xport_write_missing_tagged; writer->callbacks.variable_width = &xport_variable_width; writer->callbacks.variable_ok = &sas_validate_variable; writer->callbacks.begin_data = &xport_begin_data; writer->callbacks.end_data = &xport_end_data; writer->callbacks.write_row = &xport_write_row; return readstat_begin_writing_file(writer, user_ctx, row_count); }
2.171875
2
2024-11-18T19:27:10.411918+00:00
2022-03-12T03:16:16
7af918820a30543321e4e4411aced67f2e0246fa
{ "blob_id": "7af918820a30543321e4e4411aced67f2e0246fa", "branch_name": "refs/heads/master", "committer_date": "2022-03-12T03:16:16", "content_id": "88ee5d30cb9802d299de5bb1f35fa740dd703eef", "detected_licenses": [ "MIT" ], "directory_id": "e912c5622fb8d5867cf7bf760d53871e79534310", "extension": "c", "filename": "test_pedal_rx.c", "fork_events_count": 14, "gha_created_at": "2019-10-26T14:28:35", "gha_event_created_at": "2022-12-27T16:14:18", "gha_language": "C", "gha_license_id": "MIT", "github_id": 217720818, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3234, "license": "MIT", "license_type": "permissive", "path": "/libraries/ms-helper/test/test_pedal_rx.c", "provenance": "stackv2-0012.json.gz:185032", "repo_name": "uw-midsun/firmware_xiv", "revision_date": "2022-03-12T03:16:16", "revision_id": "57f9ca57252d1d17bac4681a319272b160df23f1", "snapshot_id": "e96852380fe7aa8f5433b668f3fbbdffdef8de9b", "src_encoding": "UTF-8", "star_events_count": 14, "url": "https://raw.githubusercontent.com/uw-midsun/firmware_xiv/57f9ca57252d1d17bac4681a319272b160df23f1/libraries/ms-helper/test/test_pedal_rx.c", "visit_date": "2023-01-14T18:04:20.938144" }
stackv2
#include "pedal_rx.h" #include <stdbool.h> #include <stdint.h> #include "can.h" #include "can_msg_defs.h" #include "can_transmit.h" #include "delay.h" #include "event_queue.h" #include "interrupt.h" #include "log.h" #include "ms_test_helpers.h" #include "soft_timer.h" #include "status.h" #include "test_helpers.h" #include "unity.h" #define TEST_PEDAL_RX_CAN_DEVICE_ID 12 typedef enum { TEST_PEDAL_RX_CAN_RX = 0, TEST_PEDAL_RX_CAN_TX, TEST_PEDAL_RX_CAN_FAULT, TEST_PEDAL_RX_TIMEOUT } TestPedalCanEvent; #define TEST_PEDAL_RX_VALUE_THRESHOLD 0.01f #define TIMEOUT_MS 50 static CanStorage s_can_storage; static PedalRxStorage s_pedal_rx_storage; static PedalRxSettings s_pedal_rx_settings = { .timeout_event = TEST_PEDAL_RX_TIMEOUT, .timeout_ms = TIMEOUT_MS, }; void setup_test(void) { event_queue_init(); gpio_init(); interrupt_init(); soft_timer_init(); CanSettings can_settings = { .device_id = TEST_PEDAL_RX_CAN_DEVICE_ID, .bitrate = CAN_HW_BITRATE_125KBPS, .rx_event = TEST_PEDAL_RX_CAN_RX, .tx_event = TEST_PEDAL_RX_CAN_TX, .fault_event = TEST_PEDAL_RX_CAN_FAULT, .tx = { GPIO_PORT_A, 12 }, .rx = { GPIO_PORT_A, 11 }, .loopback = true, }; TEST_ASSERT_OK(can_init(&s_can_storage, &can_settings)); TEST_ASSERT_OK(pedal_rx_init(&s_pedal_rx_storage, &s_pedal_rx_settings)); } void teardown_test(void) {} void test_pedal_rx_receives_correct_values(void) { float throttle_float = 12.0f; float brake_float = 13.0f; uint32_t throttle_output = (uint32_t)(throttle_float); uint32_t brake_output = (uint32_t)(brake_float); // transmitting a message CAN_TRANSMIT_PEDAL_OUTPUT(throttle_output, brake_output); MS_TEST_HELPER_CAN_TX_RX(TEST_PEDAL_RX_CAN_TX, TEST_PEDAL_RX_CAN_RX); // making sure it received the correct values PedalValues values = pedal_rx_get_pedal_values(&s_pedal_rx_storage); TEST_ASSERT_EQUAL(brake_float, values.brake); TEST_ASSERT_EQUAL(throttle_float, values.throttle); } void test_pedal_rx_timeout_goes_off_if_pedal_messages_are_not_received_fast_enough(void) { float throttle_float = 12.0f; float brake_float = 13.0f; uint32_t throttle_output = (uint32_t)(throttle_float); uint32_t brake_output = (uint32_t)(brake_float); // we want to try at least twice to make sure the module clears its own fault for (uint8_t i = 0; i < 2; i++) { // transmitting a message CAN_TRANSMIT_PEDAL_OUTPUT(throttle_output, brake_output); MS_TEST_HELPER_CAN_TX_RX(TEST_PEDAL_RX_CAN_TX, TEST_PEDAL_RX_CAN_RX); PedalValues values = pedal_rx_get_pedal_values(&s_pedal_rx_storage); TEST_ASSERT_EQUAL(brake_float, values.brake); TEST_ASSERT_EQUAL(throttle_float, values.throttle); // delaying for more than timeout delay_ms(TIMEOUT_MS - 10); MS_TEST_HELPER_ASSERT_NO_EVENT_RAISED(); delay_ms(20); Event e = { 0 }; MS_TEST_HELPER_ASSERT_NEXT_EVENT(e, TEST_PEDAL_RX_TIMEOUT, 0); // values should be reported as 0 values = pedal_rx_get_pedal_values(&s_pedal_rx_storage); TEST_ASSERT_EQUAL(0, values.brake); TEST_ASSERT_EQUAL(0, values.throttle); // no further events should be raised delay_ms(TIMEOUT_MS + 10); MS_TEST_HELPER_ASSERT_NO_EVENT_RAISED(); } }
2.1875
2
2024-11-18T19:27:10.624263+00:00
2020-03-30T18:26:53
bd18bbb587ca64c8fbca03b8518977340ac4a30b
{ "blob_id": "bd18bbb587ca64c8fbca03b8518977340ac4a30b", "branch_name": "refs/heads/master", "committer_date": "2020-03-30T18:26:53", "content_id": "4d99ba3cbdfeb7b90abb1b69d436a030467e33d3", "detected_licenses": [ "MIT" ], "directory_id": "cee6109bafac80158b20d70a1bb62447f8b37be0", "extension": "c", "filename": "PasteManager.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 44316986, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1546, "license": "MIT", "license_type": "permissive", "path": "/src/win32/PasteManager.c", "provenance": "stackv2-0012.json.gz:185288", "repo_name": "voidware/sdltrswin", "revision_date": "2020-03-30T18:26:53", "revision_id": "0c74af4d23c715d3225be6c8f4b0357f8d9c6a15", "snapshot_id": "ab0e124512110a1241b23e6c2f7f6a182cadad96", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/voidware/sdltrswin/0c74af4d23c715d3225be6c8f4b0357f8d9c6a15/src/win32/PasteManager.c", "visit_date": "2021-01-10T01:33:20.590459" }
stackv2
#include <windows.h> #include "config.h" extern int trs_paste_started(); extern void trs_end_copy() ; static int charCount = 0; static unsigned char *pasteString; static int pasteStringLength = 0; static HANDLE hClipboardData; int PasteManagerGetChar(unsigned short *character) { if (charCount) { *character = pasteString[pasteStringLength - charCount]; charCount--; if (charCount) return(TRUE); else { GlobalUnlock(hClipboardData); CloseClipboard(); return(FALSE); } } else { return(FALSE); } } int PasteManagerStartPaste(void) { if (IsClipboardFormatAvailable(CF_TEXT)) { if (OpenClipboard(NULL)) { hClipboardData = GetClipboardData(CF_TEXT); pasteString = (unsigned char *)GlobalLock(hClipboardData); charCount = pasteStringLength = strlen(pasteString); trs_paste_started(); return TRUE; } else { pasteString = NULL; charCount = 0; return FALSE; } } else { pasteString = NULL; charCount = 0; return FALSE; } } void PasteManagerStartCopy(char *string) { HANDLE hCopyData; char *pchData; if (OpenClipboard(NULL)) { EmptyClipboard(); hCopyData = GlobalAlloc(GMEM_DDESHARE, strlen(string)+1); pchData = (char *)GlobalLock(hCopyData); strcpy(pchData, string); GlobalUnlock(hCopyData); SetClipboardData(CF_TEXT, hCopyData); CloseClipboard(); } trs_end_copy(); }
2.203125
2
2024-11-18T19:27:10.710992+00:00
2023-09-03T08:13:23
b58f143649d79b10db6c8ee58943a033b1fe78a8
{ "blob_id": "b58f143649d79b10db6c8ee58943a033b1fe78a8", "branch_name": "refs/heads/main", "committer_date": "2023-09-03T08:13:23", "content_id": "fa0382450f54965b42ca7c952a1cb9769f5dc222", "detected_licenses": [ "MIT" ], "directory_id": "fb0f9abad373cd635c2635bbdf491ea0f32da5ff", "extension": "c", "filename": "sgen-array-list.c", "fork_events_count": 5179, "gha_created_at": "2019-09-24T23:36:39", "gha_event_created_at": "2023-09-14T21:58:52", "gha_language": "C#", "gha_license_id": "MIT", "github_id": 210716005, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 6210, "license": "MIT", "license_type": "permissive", "path": "/src/mono/mono/sgen/sgen-array-list.c", "provenance": "stackv2-0012.json.gz:185416", "repo_name": "dotnet/runtime", "revision_date": "2023-09-03T08:13:23", "revision_id": "47bb554d298e1e34c4e3895d7731e18ad1c47d02", "snapshot_id": "f6fd23936752e202f8e4d6d94f3a4f3b0e77f58f", "src_encoding": "UTF-8", "star_events_count": 13765, "url": "https://raw.githubusercontent.com/dotnet/runtime/47bb554d298e1e34c4e3895d7731e18ad1c47d02/src/mono/mono/sgen/sgen-array-list.c", "visit_date": "2023-09-03T15:35:46.493337" }
stackv2
/** * \file * A pointer array list that doesn't require reallocs * * Copyright (C) 2016 Xamarin Inc * * Licensed under the MIT license. See LICENSE file in the project root for full license information. */ #ifdef HAVE_SGEN_GC #include <string.h> #include "mono/sgen/sgen-gc.h" #include "mono/sgen/sgen-array-list.h" static void sgen_array_list_grow (SgenArrayList *array, guint32 old_capacity) { const guint32 new_bucket = sgen_array_list_index_bucket (old_capacity); const guint32 growth = sgen_array_list_bucket_size (new_bucket); const guint32 new_capacity = old_capacity + growth; const guint32 new_bucket_size = sizeof (**array->entries) * growth; gpointer *entries; if (array->capacity >= new_capacity) return; if (array->mem_type != -1) entries = (gpointer*) sgen_alloc_internal_dynamic (new_bucket_size, array->mem_type, TRUE); else entries = (gpointer*) g_malloc0 (new_bucket_size); if (array->bucket_alloc_callback) array->bucket_alloc_callback (entries, new_bucket_size, TRUE); /* * The zeroing of the newly allocated bucket must be complete before storing * the new bucket pointer. */ mono_memory_write_barrier (); if (mono_atomic_cas_ptr ((volatile gpointer *)&array->entries [new_bucket], entries, NULL) == NULL) { /* * It must not be the case that we succeeded in setting the bucket * pointer, while someone else succeeded in changing the capacity. */ if (mono_atomic_cas_i32 ((volatile gint32 *)&array->capacity, (gint32)new_capacity, (gint32)old_capacity) != (gint32)old_capacity) g_assert_not_reached (); array->slot_hint = old_capacity; return; } /* Someone beat us to the allocation. */ if (array->bucket_alloc_callback) array->bucket_alloc_callback (entries, new_bucket_size, FALSE); if (array->mem_type != -1) sgen_free_internal_dynamic (entries, new_bucket_size, array->mem_type); else g_free (entries); } static guint32 sgen_array_list_find_unset (SgenArrayList *array, guint32 capacity) { if (!array->is_slot_set_func) { guint32 next_slot = array->next_slot; /* We can't lookup empty slots, use next_slot */ if (next_slot < capacity) return next_slot; } else { guint32 slot_hint = array->slot_hint; guint32 index; volatile gpointer *slot; SGEN_ARRAY_LIST_FOREACH_SLOT_RANGE(array, slot_hint, capacity, slot, index) { if (!array->is_slot_set_func (slot)) return index; } SGEN_ARRAY_LIST_END_FOREACH_SLOT_RANGE; SGEN_ARRAY_LIST_FOREACH_SLOT_RANGE (array, 0, slot_hint, slot, index) { if (!array->is_slot_set_func (slot)) return index; } SGEN_ARRAY_LIST_END_FOREACH_SLOT_RANGE; } return -1; } static void sgen_array_list_update_next_slot (SgenArrayList *array, guint32 new_index) { if (!array->set_slot_func) { /* * If we don't have a custom setter it means we don't have thread * safety requirements. */ if (new_index >= array->next_slot) array->next_slot = new_index + 1; } else { guint32 old_next_slot; /* Thread safe update */ do { old_next_slot = array->next_slot; if (new_index < old_next_slot) break; } while (mono_atomic_cas_i32 ((volatile gint32 *)&array->next_slot, (gint32)(new_index + 1), (gint32)old_next_slot) != (gint32)old_next_slot); } } /* * Extension for the array list that allows fast allocation and index based fetching * of long lived memory of various sizes, without the need of realloc. Not thread safe. */ guint32 sgen_array_list_alloc_block (SgenArrayList *array, guint32 slots_to_add) { guint32 new_index = array->next_slot; guint32 old_capacity = array->capacity; /* FIXME Don't allocate arrays that will be skipped */ /* There are no empty arrays between next_slot and capacity because we allocate incrementally */ while ((old_capacity - new_index) < slots_to_add) { sgen_array_list_grow (array, old_capacity); new_index = old_capacity; old_capacity = array->capacity; } SGEN_ASSERT (0, sgen_array_list_index_bucket (new_index) == sgen_array_list_index_bucket (new_index + slots_to_add - 1), "We failed to allocate a continuous block of slots"); array->next_slot = new_index + slots_to_add; /* The slot address will point to the allocated memory */ return new_index; } guint32 sgen_array_list_add (SgenArrayList *array, gpointer ptr, int data, gboolean increase_size_before_set) { guint32 index, capacity; volatile gpointer *slot; if (!array->capacity) sgen_array_list_grow (array, 0); retry: capacity = array->capacity; index = sgen_array_list_find_unset (array, capacity); if (index == -1) { sgen_array_list_grow (array, capacity); goto retry; } array->slot_hint = index; if (increase_size_before_set) { sgen_array_list_update_next_slot (array, index); mono_memory_write_barrier (); } slot = sgen_array_list_get_slot (array, index); if (array->set_slot_func) { if (!array->set_slot_func (slot, ptr, data)) goto retry; } else { *slot = ptr; } if (!increase_size_before_set) { mono_memory_write_barrier (); sgen_array_list_update_next_slot (array, index); } return index; } /* * Does a linear search through the pointer array to find `ptr`. Returns the index if * found, otherwise (guint32)-1. */ guint32 sgen_array_list_find (SgenArrayList *array, gpointer ptr) { volatile gpointer *slot; SGEN_ARRAY_LIST_FOREACH_SLOT (array, slot) { if (*slot == ptr) return __index; } SGEN_ARRAY_LIST_END_FOREACH_SLOT; return (guint32)-1; } gboolean sgen_array_list_default_cas_setter (volatile gpointer *slot, gpointer ptr, int data) { if (mono_atomic_cas_ptr (slot, ptr, NULL) == NULL) return TRUE; return FALSE; } gboolean sgen_array_list_default_is_slot_set (volatile gpointer *slot) { return *slot != NULL; } /* Removes all NULL pointers from the array. Not thread safe */ void sgen_array_list_remove_nulls (SgenArrayList *array) { guint32 start = 0; volatile gpointer *slot; gboolean skipped = FALSE; SGEN_ARRAY_LIST_FOREACH_SLOT (array, slot) { if (*slot) { *sgen_array_list_get_slot (array, start++) = *slot; if (skipped) *slot = NULL; } else { skipped = TRUE; } } SGEN_ARRAY_LIST_END_FOREACH_SLOT; mono_memory_write_barrier (); array->next_slot = start; array->slot_hint = start; } #endif
2.75
3
2024-11-18T19:27:10.804910+00:00
2018-07-16T10:55:29
f147230c747310e4dcb6b8194d5d6a2ff778ec42
{ "blob_id": "f147230c747310e4dcb6b8194d5d6a2ff778ec42", "branch_name": "refs/heads/master", "committer_date": "2019-09-20T23:34:39", "content_id": "78e23d2360af2a1abeff15b58a0db9df6070122a", "detected_licenses": [ "MIT" ], "directory_id": "28cd2d411f6ef5a1863c4e374af2ccb53e1058a6", "extension": "c", "filename": "printer.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 209896947, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1632, "license": "MIT", "license_type": "permissive", "path": "/sources/printer.c", "provenance": "stackv2-0012.json.gz:185545", "repo_name": "rsilva42/ft_script", "revision_date": "2018-07-16T10:55:29", "revision_id": "2e3c31c40d9c8e564e97575824b5a60f79b45154", "snapshot_id": "cbb32f2f5a6cbcccee44fb25353dab2e791751e7", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/rsilva42/ft_script/2e3c31c40d9c8e564e97575824b5a60f79b45154/sources/printer.c", "visit_date": "2020-07-29T17:15:21.390977" }
stackv2
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* printer.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: rsilva <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/07/15 20:19:44 by rsilva #+# #+# */ /* Updated: 2018/07/15 20:20:20 by rsilva ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_script.h" char *findshell(char **envp) { int i; i = 0; while (envp[i]) { if (!(ft_strncmp(envp[i], "SHELL=", 6))) return (envp[i] + 6); i++; } return ("/bin/sh"); } char *findname(char **av) { int i; i = 1; while (av[i]) { if (av[i][0] != '-') return (av[i]); i++; } return ("typescript"); } void print_start(char **av, int fd) { ft_putstr("Script started, output file is "); ft_putstr(findname(av)); ft_putstr("\n"); ft_putstr_fd("Script started on ", fd); ft_putstr_fd(get_time(), fd); } void print_end(char **av, int fd) { ft_putstr("\nScript done, output file is "); ft_putstr(findname(av)); ft_putstr("\n"); ft_putstr_fd("\nScript done on ", fd); ft_putstr_fd(get_time(), fd); }
2.546875
3
2024-11-18T19:27:10.865448+00:00
2021-11-30T07:54:29
0ddca5f15f15396bbc9efa6ce42baf0e603d6d01
{ "blob_id": "0ddca5f15f15396bbc9efa6ce42baf0e603d6d01", "branch_name": "refs/heads/huawei", "committer_date": "2021-11-30T08:51:54", "content_id": "fe95252d1df3e9dcb931052cd971053c11a42060", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "ce0de673362e0cc59631333b8efd97cb59dc2fcc", "extension": "h", "filename": "profile_on.h", "fork_events_count": 15, "gha_created_at": "2020-04-21T02:54:34", "gha_event_created_at": "2020-10-11T08:05:25", "gha_language": "C", "gha_license_id": "NOASSERTION", "github_id": 257463730, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 7461, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/src/ucs/profile/profile_on.h", "provenance": "stackv2-0012.json.gz:185673", "repo_name": "kunpengcompute/hucx", "revision_date": "2021-11-30T07:54:29", "revision_id": "92bb5a9ca9ab03519df378cd1f8185af6a9263ac", "snapshot_id": "cd8afa98fde8cc8ac6ed3f69f9a5f8c3d63e5359", "src_encoding": "UTF-8", "star_events_count": 10, "url": "https://raw.githubusercontent.com/kunpengcompute/hucx/92bb5a9ca9ab03519df378cd1f8185af6a9263ac/src/ucs/profile/profile_on.h", "visit_date": "2023-07-20T15:43:01.952669" }
stackv2
/** * Copyright (C) Mellanox Technologies Ltd. 2001-2018. ALL RIGHTS RESERVED. * * See file LICENSE for terms. */ #ifndef UCS_PROFILE_ON_H_ #define UCS_PROFILE_ON_H_ #include "profile_defs.h" #include <ucs/sys/compiler_def.h> #include <ucs/sys/preprocessor.h> #include <ucs/config/global_opts.h> BEGIN_C_DECLS /** @file profile_on.h */ /* Helper macro */ #define _UCS_PROFILE_RECORD(_type, _name, _param64, _param32, _loc_id_p) \ { \ if (*(_loc_id_p) != 0) { \ ucs_profile_record((_type), (_name), (_param64), (_param32), \ __FILE__, __LINE__, __FUNCTION__, (_loc_id_p)); \ } \ } /* Helper macro */ #define __UCS_PROFILE_CODE(_name, _loop_var) \ int _loop_var ; \ for (({ UCS_PROFILE_SCOPE_BEGIN(); _loop_var = 1;}); \ _loop_var; \ ({ UCS_PROFILE_SCOPE_END(_name); _loop_var = 0;})) /* Helper macro */ #define _UCS_PROFILE_CODE(_name, _var_suffix) \ __UCS_PROFILE_CODE(_name, UCS_PP_TOKENPASTE(loop, _var_suffix)) /** * Record a profiling event. * * @param _type Event type. * @param _name Event name. * @param _param32 Custom 32-bit parameter. * @param _param64 Custom 64-bit parameter. */ #define UCS_PROFILE(_type, _name, _param32, _param64) \ { \ static int loc_id = -1; \ _UCS_PROFILE_RECORD((_type), (_name), (_param32), (_param64), &loc_id); \ } /** * Record a profiling sample event. * * @param _name Event name. */ #define UCS_PROFILE_SAMPLE(_name) \ UCS_PROFILE(UCS_PROFILE_TYPE_SAMPLE, (_name), 0, 0) /** * Record a scope-begin profiling event. */ #define UCS_PROFILE_SCOPE_BEGIN() \ { \ UCS_PROFILE(UCS_PROFILE_TYPE_SCOPE_BEGIN, "", 0, 0); \ ucs_compiler_fence(); \ } /** * Record a scope-end profiling event. * * @param _name Scope name. */ #define UCS_PROFILE_SCOPE_END(_name) \ { \ ucs_compiler_fence(); \ UCS_PROFILE(UCS_PROFILE_TYPE_SCOPE_END, _name, 0, 0); \ } /** * Declare a profiled scope of code. * * Usage: * UCS_PROFILE_CODE(<name>) { * <code> * } * * @param _name Scope name. */ #define UCS_PROFILE_CODE(_name) \ _UCS_PROFILE_CODE(_name, UCS_PP_UNIQUE_ID) /** * Create a profiled function. * * Usage: * UCS_PROFILE_FUNC(<retval>, <name>, (a, b), int a, char b) * * @param _ret_type Function return type. * @param _name Function name. * @param _arglist List of argument *names* only. * @param ... Argument declarations (with types). */ #define UCS_PROFILE_FUNC(_ret_type, _name, _arglist, ...) \ static UCS_F_ALWAYS_INLINE _ret_type _name##_inner(__VA_ARGS__); \ \ _ret_type _name(__VA_ARGS__) { \ _ret_type _ret = _name##_inner _arglist; \ UCS_PROFILE_SCOPE_BEGIN(); \ UCS_PROFILE_SCOPE_END(#_name); \ return _ret; \ } \ static UCS_F_ALWAYS_INLINE _ret_type _name##_inner(__VA_ARGS__) /** * Create a profiled function whose return type is void. * * Usage: * UCS_PROFILE_FUNC_VOID(<name>, (a, b), int a, char b) * * @param _name Function name. * @param _arglist List of argument *names* only. * @param ... Argument declarations (with types). */ #define UCS_PROFILE_FUNC_VOID(_name, _arglist, ...) \ static UCS_F_ALWAYS_INLINE void _name##_inner(__VA_ARGS__); \ \ void _name(__VA_ARGS__) { \ UCS_PROFILE_SCOPE_BEGIN(); \ _name##_inner _arglist; \ UCS_PROFILE_SCOPE_END(#_name); \ } \ static UCS_F_ALWAYS_INLINE void _name##_inner(__VA_ARGS__) /* * Profile a function call, and specify explicit name string for the profile. * Useful when calling a function by a pointer. * * Usage: * UCS_PROFILE_NAMED_CALL("name", function, arg1, arg2) * * @param _name Name string for the profile. * @param _func Function name. * @param ... Function call arguments. */ #define UCS_PROFILE_NAMED_CALL(_name, _func, ...) \ ({ \ typeof(_func(__VA_ARGS__)) retval; \ UCS_PROFILE_SCOPE_BEGIN(); \ retval = _func(__VA_ARGS__); \ UCS_PROFILE_SCOPE_END(_name); \ retval; \ }) /* * Profile a function call. * * Usage: * UCS_PROFILE_CALL(function, arg1, arg2) * * @param _func Function name. * @param ... Function call arguments. */ #define UCS_PROFILE_CALL(_func, ...) \ UCS_PROFILE_NAMED_CALL(#_func, _func, ## __VA_ARGS__) /* * Profile a function call which does not return a value, and specify explicit * name string for the profile. Useful when calling a function by a pointer. * * Usage: * UCS_PROFILE_NAMED_CALL_VOID("name", function, arg1, arg2) * * @param _name Name string for the profile. * @param _func Function name. * @param ... Function call arguments. */ #define UCS_PROFILE_NAMED_CALL_VOID(_name, _func, ...) \ { \ UCS_PROFILE_SCOPE_BEGIN(); \ _func(__VA_ARGS__); \ UCS_PROFILE_SCOPE_END(_name); \ } /* * Profile a function call which does not return a value. * * Usage: * UCS_PROFILE_CALL_VOID(function, arg1, arg2) * * @param _func Function name. * @param ... Function call arguments. */ #define UCS_PROFILE_CALL_VOID(_func, ...) \ UCS_PROFILE_NAMED_CALL_VOID(#_func, _func, ## __VA_ARGS__) /* * Profile a new request allocation. * * @param _req Request pointer. * @param _name Allocation site name. * @param _param32 Custom 32-bit parameter. */ #define UCS_PROFILE_REQUEST_NEW(_req, _name, _param32) \ UCS_PROFILE(UCS_PROFILE_TYPE_REQUEST_NEW, (_name), (_param32), (uintptr_t)(_req)); /* * Profile a request progress event. * * @param _req Request pointer. * @param _name Event name. * @param _param32 Custom 32-bit parameter. */ #define UCS_PROFILE_REQUEST_EVENT(_req, _name, _param32) \ UCS_PROFILE(UCS_PROFILE_TYPE_REQUEST_EVENT, (_name), (_param32), (uintptr_t)(_req)); /* * Profile a request progress event with status check. * * @param _req Request pointer. * @param _name Event name. * @param _param32 Custom 32-bit parameter. * @param _status Status of the last progress event. */ #define UCS_PROFILE_REQUEST_EVENT_CHECK_STATUS(_req, _name, _param32, _status) \ if (!UCS_STATUS_IS_ERR(_status)) { \ UCS_PROFILE_REQUEST_EVENT((_req), (_name), (_param32)); \ } /* * Profile a request release. * * @param _req Request pointer. */ #define UCS_PROFILE_REQUEST_FREE(_req) \ UCS_PROFILE(UCS_PROFILE_TYPE_REQUEST_FREE, "", 0, (uintptr_t)(_req)); /* * Store a new record with the given data. * SHOULD NOT be used directly - use UCS_PROFILE macros instead. * * @param [in] type Location type. * @param [in] name Location name. * @param [in] param32 custom 32-bit parameter. * @param [in] param64 custom 64-bit parameter. * @param [in] file Source file name. * @param [in] line Source line number. * @param [in] function Calling function name. * @param [in,out] loc_id_p Variable used to maintain the location ID. */ void ucs_profile_record(ucs_profile_type_t type, const char *name, uint32_t param32, uint64_t param64, const char *file, int line, const char *function, volatile int *loc_id_p); /** * Reset the internal array of profiling locations. * Used for testing purposes only. */ void ucs_profile_reset_locations(); END_C_DECLS #endif
2.140625
2
2024-11-18T19:27:10.935686+00:00
2012-06-30T22:38:33
0321b9d97b20421669a83c88cabef1d99db80e32
{ "blob_id": "0321b9d97b20421669a83c88cabef1d99db80e32", "branch_name": "refs/heads/master", "committer_date": "2012-06-30T22:38:33", "content_id": "e46bfef560e5607de51f81d2f2eb415706ff3fbe", "detected_licenses": [ "MIT" ], "directory_id": "1587be5bbcd099beaa6136e5459e392610460d8f", "extension": "c", "filename": "bit_array.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 2715727, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1721, "license": "MIT", "license_type": "permissive", "path": "/crypto/des/trash/bit_array.c", "provenance": "stackv2-0012.json.gz:185801", "repo_name": "Fat-Zer/semestr-6", "revision_date": "2012-06-30T22:38:33", "revision_id": "a8747c358fc28b57335df3fc1f0ac000bc39a714", "snapshot_id": "f02af20a7fe81e0eb4329592946426435d301b98", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Fat-Zer/semestr-6/a8747c358fc28b57335df3fc1f0ac000bc39a714/crypto/des/trash/bit_array.c", "visit_date": "2021-01-20T10:13:56.015541" }
stackv2
#include <limits.h> #include <string.h> #include <stdlib.h> #include "bit_array.h" #define BA_ALLOC_T_BIT (CHAR_BIT*sizeof(ba_alloc_t)) #define BA_ALLOC_T_MASK ((ba_alloc_t)~0) #define BA_NUMBER_MASK (BA_ALLOC_T_BIT - 1) #define BA_NUMBER_SHIFT (3) // log2(BA_ALLOC_T_BIT) struct bit_array* alloc_bit_array(size_t nbits) { size_t arr_sz = bytes_for_store_bits(nbits); struct bit_array *rv = (struct bit_array*) malloc(arr_sz + sizeof(size_t)); rv->nbits = nbits; memset(rv->arr, 0, arr_sz); return rv; } void ba_set_bit(struct bit_array* ba, size_t bitn) { if(bitn < ba->nbits) { size_t pos = bitn >> BA_NUMBER_SHIFT; ba_alloc_t bit = 1<<(bitn & BA_NUMBER_MASK); ba->arr[pos]|=bit; } } void ba_reset_bit(struct bit_array* ba, size_t bitn) { if(bitn < ba->nbits) { size_t pos = bitn >> BA_NUMBER_SHIFT; ba_alloc_t bit = 1<<(bitn & BA_NUMBER_MASK); ba->arr[pos]&=~bit; } } bool ba_isset(struct bit_array* ba, size_t bitn) { bool rv = 0; if(bitn < ba->nbits) { size_t pos = bitn >> BA_NUMBER_SHIFT; ba_alloc_t bit = 1<<(bitn & BA_NUMBER_MASK); rv=ba->arr[pos] & bit; } return rv; } size_t bytes_for_store_bits(size_t nbits) { return ((nbits >> BA_NUMBER_SHIFT) + (BA_NUMBER_MASK & nbits?1:0)); } ba_alloc_t last_byte_mask(size_t nbits) { return (nbits & (BA_NUMBER_MASK)) ? ~0 : ~0 >> (BA_NUMBER_MASK - (nbits & BA_NUMBER_MASK)); } bool ba_is_all_set(struct bit_array* ba) { size_t i; size_t arr_sz = bytes_for_store_bits(ba->nbits); bool rv = 1; for(i=0; i<arr_sz-1; i++) if(BA_ALLOC_T_MASK & ~ba->arr[i]) { rv = 0; break; } if(rv) { ba_alloc_t lbm = last_byte_mask(ba->nbits); rv = ( (ba->arr[arr_sz-1] & lbm) == lbm); } return rv; }
2.765625
3
2024-11-18T19:27:10.994789+00:00
2023-08-25T13:17:54
2ed4407d3894637dc43f833698bbeed5848acaca
{ "blob_id": "2ed4407d3894637dc43f833698bbeed5848acaca", "branch_name": "refs/heads/main", "committer_date": "2023-08-25T13:17:54", "content_id": "ea5d217071b7915659bc3e151e6ec4b7678d2d03", "detected_licenses": [ "Apache-2.0" ], "directory_id": "cc91a1c30f6c5a176b225bdbf96c7bfd6dfeca52", "extension": "c", "filename": "deFloat16Test.c", "fork_events_count": 267, "gha_created_at": "2016-01-26T23:29:28", "gha_event_created_at": "2023-09-02T20:49:14", "gha_language": "C++", "gha_license_id": "Apache-2.0", "github_id": 50466830, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 19981, "license": "Apache-2.0", "license_type": "permissive", "path": "/framework/delibs/debase/deFloat16Test.c", "provenance": "stackv2-0012.json.gz:185929", "repo_name": "KhronosGroup/VK-GL-CTS", "revision_date": "2023-08-25T13:17:54", "revision_id": "a745d5c29c5609cb7805f59444520a7700cf39d1", "snapshot_id": "d07b2611dc3a258b5be4ff87c1fe55623f32bac1", "src_encoding": "UTF-8", "star_events_count": 454, "url": "https://raw.githubusercontent.com/KhronosGroup/VK-GL-CTS/a745d5c29c5609cb7805f59444520a7700cf39d1/framework/delibs/debase/deFloat16Test.c", "visit_date": "2023-08-31T19:34:48.447202" }
stackv2
/*------------------------------------------------------------------------- * drawElements Base Portability Library * ------------------------------------- * * Copyright 2017 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *//*! * \file * \brief Testing of deFloat16 functions. *//*--------------------------------------------------------------------*/ #include "deFloat16.h" #include "deRandom.h" DE_BEGIN_EXTERN_C static float getFloat32 (deUint32 sign, deUint32 biased_exponent, deUint32 mantissa) { union { float f; deUint32 u; } x; x.u = (sign << 31) | (biased_exponent << 23) | mantissa; return x.f; } static deFloat16 getFloat16 (deUint16 sign, deUint16 biased_exponent, deUint16 mantissa) { return (deFloat16) ((sign << 15) | (biased_exponent << 10) | mantissa); } static deFloat16 deFloat32To16RTZ (float val32) { return deFloat32To16Round(val32, DE_ROUNDINGMODE_TO_ZERO); } static deFloat16 deFloat32To16RTE (float val32) { return deFloat32To16Round(val32, DE_ROUNDINGMODE_TO_NEAREST_EVEN); } void deFloat16_selfTest (void) { /* 16-bit: 1 5 (0x00--0x1f) 10 (0x000--0x3ff) * 32-bit: 1 8 (0x00--0xff) 23 (0x000000--0x7fffff) */ deRandom rnd; int idx; deRandom_init(&rnd, 0xdeadbeefu-1); /* --- For rounding mode RTZ --- */ /* Zero */ DE_TEST_ASSERT(deFloat32To16RTZ(getFloat32(0, 0, 0)) == getFloat16(0, 0, 0)); DE_TEST_ASSERT(deFloat32To16RTZ(getFloat32(1, 0, 0)) == getFloat16(1, 0, 0)); /* Inf */ DE_TEST_ASSERT(deFloat32To16RTZ(getFloat32(0, 0xff, 0)) == getFloat16(0, 0x1f, 0)); DE_TEST_ASSERT(deFloat32To16RTZ(getFloat32(1, 0xff, 0)) == getFloat16(1, 0x1f, 0)); /* SNaN */ DE_TEST_ASSERT(deFloat32To16RTZ(getFloat32(0, 0xff, 1)) == getFloat16(0, 0x1f, 1)); DE_TEST_ASSERT(deFloat32To16RTZ(getFloat32(1, 0xff, 1)) == getFloat16(1, 0x1f, 1)); DE_TEST_ASSERT(deFloat32To16RTZ(getFloat32(0, 0xff, 0x3fffff)) == getFloat16(0, 0x1f, 0x1ff)); DE_TEST_ASSERT(deFloat32To16RTZ(getFloat32(1, 0xff, 0x3fffff)) == getFloat16(1, 0x1f, 0x1ff)); DE_TEST_ASSERT(deFloat32To16RTZ(getFloat32(0, 0xff, 0x0003ff)) == getFloat16(0, 0x1f, 1)); DE_TEST_ASSERT(deFloat32To16RTZ(getFloat32(1, 0xff, 0x0003ff)) == getFloat16(1, 0x1f, 1)); DE_TEST_ASSERT(deFloat32To16RTZ(getFloat32(0, 0xff, 0x123456)) == getFloat16(0, 0x1f, 0x123456 >> 13)); DE_TEST_ASSERT(deFloat32To16RTZ(getFloat32(1, 0xff, 0x123456)) == getFloat16(1, 0x1f, 0x123456 >> 13)); /* QNaN */ DE_TEST_ASSERT(deFloat32To16RTZ(getFloat32(0, 0xff, 0x400000)) == getFloat16(0, 0x1f, 0x200)); DE_TEST_ASSERT(deFloat32To16RTZ(getFloat32(1, 0xff, 0x400000)) == getFloat16(1, 0x1f, 0x200)); DE_TEST_ASSERT(deFloat32To16RTZ(getFloat32(0, 0xff, 0x7fffff)) == getFloat16(0, 0x1f, 0x3ff)); DE_TEST_ASSERT(deFloat32To16RTZ(getFloat32(1, 0xff, 0x7fffff)) == getFloat16(1, 0x1f, 0x3ff)); DE_TEST_ASSERT(deFloat32To16RTZ(getFloat32(0, 0xff, 0x4003ff)) == getFloat16(0, 0x1f, 0x200)); DE_TEST_ASSERT(deFloat32To16RTZ(getFloat32(1, 0xff, 0x4003ff)) == getFloat16(1, 0x1f, 0x200)); DE_TEST_ASSERT(deFloat32To16RTZ(getFloat32(0, 0xff, 0x723456)) == getFloat16(0, 0x1f, 0x723456 >> 13)); DE_TEST_ASSERT(deFloat32To16RTZ(getFloat32(1, 0xff, 0x723456)) == getFloat16(1, 0x1f, 0x723456 >> 13)); /* Denormalized */ for (idx = 0; idx < 256; ++idx) { deUint32 mantissa = deRandom_getUint32(&rnd); mantissa &= 0x7fffffu; /* Take the last 23 bits */ mantissa |= (mantissa == 0); /* Make sure it is not zero */ DE_TEST_ASSERT(deFloat32To16RTZ(getFloat32(0, 0, mantissa)) == getFloat16(0, 0, 0)); DE_TEST_ASSERT(deFloat32To16RTZ(getFloat32(1, 0, mantissa)) == getFloat16(1, 0, 0)); } /* Normalized -> zero */ /* Absolute value: minimal 32-bit normalized */ DE_TEST_ASSERT(deFloat32To16RTZ(getFloat32(0, 1, 0)) == getFloat16(0, 0, 0)); DE_TEST_ASSERT(deFloat32To16RTZ(getFloat32(1, 1, 0)) == getFloat16(1, 0, 0)); /* Absolute value: 2^-24 - e, extremely near minimal 16-bit denormalized */ DE_TEST_ASSERT(deFloat32To16RTZ(getFloat32(0, 127 - 25, 0x7fffff)) == getFloat16(0, 0, 0)); DE_TEST_ASSERT(deFloat32To16RTZ(getFloat32(1, 127 - 25, 0x7fffff)) == getFloat16(1, 0, 0)); for (idx = 0; idx < 256; ++idx) { deUint32 exponent = deRandom_getUint32(&rnd); deUint32 mantissa = deRandom_getUint32(&rnd); exponent = exponent % (127 - 25) + 1; /* Make sure >= 1, <= 127 - 25 */ mantissa &= 0x7fffffu; /* Take the last 23 bits */ DE_TEST_ASSERT(deFloat32To16RTZ(getFloat32(0, exponent, mantissa)) == getFloat16(0, 0, 0)); DE_TEST_ASSERT(deFloat32To16RTZ(getFloat32(1, exponent, mantissa)) == getFloat16(1, 0, 0)); } /* Normalized -> denormalized */ /* Absolute value: 2^-24, minimal 16-bit denormalized */ DE_TEST_ASSERT(deFloat32To16RTZ(getFloat32(0, 127 - 24, 0)) == getFloat16(0, 0, 1)); DE_TEST_ASSERT(deFloat32To16RTZ(getFloat32(1, 127 - 24, 0)) == getFloat16(1, 0, 1)); DE_TEST_ASSERT(deFloat32To16RTZ(getFloat32(0, 127 - 24, 1)) == getFloat16(0, 0, 1)); DE_TEST_ASSERT(deFloat32To16RTZ(getFloat32(1, 127 - 24, 1)) == getFloat16(1, 0, 1)); DE_TEST_ASSERT(deFloat32To16RTZ(getFloat32(0, 127 - 20, 0x123456)) == getFloat16(0, 0, 0x12)); DE_TEST_ASSERT(deFloat32To16RTZ(getFloat32(1, 127 - 20, 0x123456)) == getFloat16(1, 0, 0x12)); DE_TEST_ASSERT(deFloat32To16RTZ(getFloat32(0, 127 - 18, 0x654321)) == getFloat16(0, 0, 0x72)); DE_TEST_ASSERT(deFloat32To16RTZ(getFloat32(1, 127 - 18, 0x654321)) == getFloat16(1, 0, 0x72)); /* Absolute value: 2^-14 - 2^-24 = (2 - 2^-9) * 2^-15, maximal 16-bit denormalized */ DE_TEST_ASSERT(deFloat32To16RTZ(getFloat32(0, 127 - 15, 0x7fc000)) == getFloat16(0, 0, 0x3ff)); /* 0x7fc000: 0111 1111 1100 0000 0000 0000 */ DE_TEST_ASSERT(deFloat32To16RTZ(getFloat32(1, 127 - 15, 0x7fc000)) == getFloat16(1, 0, 0x3ff)); DE_TEST_ASSERT(deFloat32To16RTZ(getFloat32(0, 127 - 15, 0x7fc000 - 1)) == getFloat16(0, 0, 0x3fe)); DE_TEST_ASSERT(deFloat32To16RTZ(getFloat32(1, 127 - 15, 0x7fc000 - 1)) == getFloat16(1, 0, 0x3fe)); DE_TEST_ASSERT(deFloat32To16RTZ(getFloat32(0, 127 - 15, 0x7fc000 + 1)) == getFloat16(0, 0, 0x3ff)); DE_TEST_ASSERT(deFloat32To16RTZ(getFloat32(1, 127 - 15, 0x7fc000 + 1)) == getFloat16(1, 0, 0x3ff)); DE_TEST_ASSERT(deFloat32To16RTZ(getFloat32(0, 127 - 15, 0x7fffff)) == getFloat16(0, 0, 0x3ff)); DE_TEST_ASSERT(deFloat32To16RTZ(getFloat32(1, 127 - 15, 0x7fffff)) == getFloat16(1, 0, 0x3ff)); /* Normalized -> normalized */ /* Absolute value: 2^-14, minimal 16-bit normalized */ DE_TEST_ASSERT(deFloat32To16RTZ(getFloat32(0, 127 - 14, 0)) == getFloat16(0, 1, 0)); DE_TEST_ASSERT(deFloat32To16RTZ(getFloat32(1, 127 - 14, 0)) == getFloat16(1, 1, 0)); /* Absolute value: 65504 - 2^-23, extremely near maximal 16-bit normalized */ DE_TEST_ASSERT(deFloat32To16RTZ(getFloat32(0, 127 + 15, (0x3ff << 13) - 1)) == getFloat16(0, 0x1e, 0x3fe)); DE_TEST_ASSERT(deFloat32To16RTZ(getFloat32(1, 127 + 15, (0x3ff << 13) - 1)) == getFloat16(1, 0x1e, 0x3fe)); DE_TEST_ASSERT(deFloat32To16RTZ(getFloat32(0, 127 + 15, (0x3ff << 13) - 0x456)) == getFloat16(0, 0x1e, 0x3fe)); DE_TEST_ASSERT(deFloat32To16RTZ(getFloat32(1, 127 + 15, (0x3ff << 13) - 0x456)) == getFloat16(1, 0x1e, 0x3fe)); /* Absolute value: 65504, maximal 16-bit normalized */ DE_TEST_ASSERT(deFloat32To16RTZ(getFloat32(0, 127 + 15, 0x3ff << 13)) == getFloat16(0, 0x1e, 0x3ff)); DE_TEST_ASSERT(deFloat32To16RTZ(getFloat32(1, 127 + 15, 0x3ff << 13)) == getFloat16(1, 0x1e, 0x3ff)); for (idx = 0; idx < 256; ++idx) { deUint32 exponent = deRandom_getUint32(&rnd); deUint32 mantissa = deRandom_getUint32(&rnd); exponent = exponent % ((127 + 14) - (127 -14) + 1) + (127 - 14); /* Make sure >= 127 - 14, <= 127 + 14 */ mantissa &= 0x7fffffu; /* Take the last 23 bits */ DE_TEST_ASSERT(deFloat32To16RTZ(getFloat32(0, exponent, mantissa)) == getFloat16(0, (deUint16) (exponent + 15 - 127), (deUint16) (mantissa >> 13))); DE_TEST_ASSERT(deFloat32To16RTZ(getFloat32(1, exponent, mantissa)) == getFloat16(1, (deUint16) (exponent + 15 - 127), (deUint16) (mantissa >> 13))); } /* Normalized -> minimal/maximal normalized */ DE_TEST_ASSERT(deFloat32To16RTZ(getFloat32(0, 127 + 15, (0x3ff << 13) + 1)) == getFloat16(0, 0x1e, 0x3ff)); DE_TEST_ASSERT(deFloat32To16RTZ(getFloat32(1, 127 + 15, (0x3ff << 13) + 1)) == getFloat16(1, 0x1e, 0x3ff)); DE_TEST_ASSERT(deFloat32To16RTZ(getFloat32(0, 127 + 15, (0x3ff << 13) + 0x123)) == getFloat16(0, 0x1e, 0x3ff)); DE_TEST_ASSERT(deFloat32To16RTZ(getFloat32(1, 127 + 15, (0x3ff << 13) + 0x123)) == getFloat16(1, 0x1e, 0x3ff)); for (idx = 0; idx < 256; ++idx) { deUint32 exponent = deRandom_getUint32(&rnd); deUint32 mantissa = deRandom_getUint32(&rnd); exponent = exponent % (0xfe - (127 + 16) + 1) + (127 + 16); /* Make sure >= 127 + 16, <= 0xfe */ mantissa &= 0x7fffffu; /* Take the last 23 bits */ DE_TEST_ASSERT(deFloat32To16RTZ(getFloat32(0, exponent, mantissa)) == getFloat16(0, 0x1e, 0x3ff)); DE_TEST_ASSERT(deFloat32To16RTZ(getFloat32(1, exponent, mantissa)) == getFloat16(1, 0x1e, 0x3ff)); } /* --- For rounding mode RTE --- */ /* Zero */ DE_TEST_ASSERT(deFloat32To16RTE(getFloat32(0, 0, 0)) == getFloat16(0, 0, 0)); DE_TEST_ASSERT(deFloat32To16RTE(getFloat32(1, 0, 0)) == getFloat16(1, 0, 0)); /* Inf */ DE_TEST_ASSERT(deFloat32To16RTE(getFloat32(0, 0xff, 0)) == getFloat16(0, 0x1f, 0)); DE_TEST_ASSERT(deFloat32To16RTE(getFloat32(1, 0xff, 0)) == getFloat16(1, 0x1f, 0)); /* SNaN */ DE_TEST_ASSERT(deFloat32To16RTE(getFloat32(0, 0xff, 1)) == getFloat16(0, 0x1f, 1)); DE_TEST_ASSERT(deFloat32To16RTE(getFloat32(1, 0xff, 1)) == getFloat16(1, 0x1f, 1)); DE_TEST_ASSERT(deFloat32To16RTE(getFloat32(0, 0xff, 0x3fffff)) == getFloat16(0, 0x1f, 0x1ff)); DE_TEST_ASSERT(deFloat32To16RTE(getFloat32(1, 0xff, 0x3fffff)) == getFloat16(1, 0x1f, 0x1ff)); DE_TEST_ASSERT(deFloat32To16RTE(getFloat32(0, 0xff, 0x0003ff)) == getFloat16(0, 0x1f, 1)); DE_TEST_ASSERT(deFloat32To16RTE(getFloat32(1, 0xff, 0x0003ff)) == getFloat16(1, 0x1f, 1)); DE_TEST_ASSERT(deFloat32To16RTE(getFloat32(0, 0xff, 0x123456)) == getFloat16(0, 0x1f, 0x123456 >> 13)); DE_TEST_ASSERT(deFloat32To16RTE(getFloat32(1, 0xff, 0x123456)) == getFloat16(1, 0x1f, 0x123456 >> 13)); /* QNaN */ DE_TEST_ASSERT(deFloat32To16RTE(getFloat32(0, 0xff, 0x400000)) == getFloat16(0, 0x1f, 0x200)); DE_TEST_ASSERT(deFloat32To16RTE(getFloat32(1, 0xff, 0x400000)) == getFloat16(1, 0x1f, 0x200)); DE_TEST_ASSERT(deFloat32To16RTE(getFloat32(0, 0xff, 0x7fffff)) == getFloat16(0, 0x1f, 0x3ff)); DE_TEST_ASSERT(deFloat32To16RTE(getFloat32(1, 0xff, 0x7fffff)) == getFloat16(1, 0x1f, 0x3ff)); DE_TEST_ASSERT(deFloat32To16RTE(getFloat32(0, 0xff, 0x4003ff)) == getFloat16(0, 0x1f, 0x200)); DE_TEST_ASSERT(deFloat32To16RTE(getFloat32(1, 0xff, 0x4003ff)) == getFloat16(1, 0x1f, 0x200)); DE_TEST_ASSERT(deFloat32To16RTE(getFloat32(0, 0xff, 0x723456)) == getFloat16(0, 0x1f, 0x723456 >> 13)); DE_TEST_ASSERT(deFloat32To16RTE(getFloat32(1, 0xff, 0x723456)) == getFloat16(1, 0x1f, 0x723456 >> 13)); /* Denormalized */ for (idx = 0; idx < 256; ++idx) { deUint32 mantissa = deRandom_getUint32(&rnd); mantissa &= 0x7fffffu; /* Take the last 23 bits */ mantissa |= (mantissa == 0); /* Make sure it is not zero */ DE_TEST_ASSERT(deFloat32To16RTE(getFloat32(0, 0, mantissa)) == getFloat16(0, 0, 0)); DE_TEST_ASSERT(deFloat32To16RTE(getFloat32(1, 0, mantissa)) == getFloat16(1, 0, 0)); } /* Normalized -> zero and denormalized */ /* Absolute value: minimal 32-bit normalized */ DE_TEST_ASSERT(deFloat32To16RTE(getFloat32(0, 1, 0)) == getFloat16(0, 0, 0)); DE_TEST_ASSERT(deFloat32To16RTE(getFloat32(1, 1, 0)) == getFloat16(1, 0, 0)); DE_TEST_ASSERT(deFloat32To16RTE(getFloat32(0, 42, 0x7abcde)) == getFloat16(0, 0, 0)); DE_TEST_ASSERT(deFloat32To16RTE(getFloat32(1, 42, 0x7abcde)) == getFloat16(1, 0, 0)); for (idx = 0; idx < 256; ++idx) { deUint32 exponent = deRandom_getUint32(&rnd); deUint32 mantissa = deRandom_getUint32(&rnd); exponent = exponent % (127 - 26) + 1; /* Make sure >= 1, <= 127 - 26 */ mantissa &= 0x7fffffu; /* Take the last 23 bits */ DE_TEST_ASSERT(deFloat32To16RTE(getFloat32(0, exponent, mantissa)) == getFloat16(0, 0, 0)); DE_TEST_ASSERT(deFloat32To16RTE(getFloat32(1, exponent, mantissa)) == getFloat16(1, 0, 0)); } /* Absolute value: 2^-25, minimal 16-bit denormalized: 2^-24 */ /* The following six cases need to right shift mantissa (with leading 1) 10 bits --------------------> to here */ DE_TEST_ASSERT(deFloat32To16RTE(getFloat32(0, 127 - 25, 0)) == getFloat16(0, 0, 0)); /* XX XXXX XXXX 1 000 0000 0000 0000 0000 0000 */ /* Take the first 10 bits with RTE ------ 00 0000 0000 */ DE_TEST_ASSERT(deFloat32To16RTE(getFloat32(1, 127 - 25, 0)) == getFloat16(1, 0, 0)); DE_TEST_ASSERT(deFloat32To16RTE(getFloat32(0, 127 - 25, 1)) == getFloat16(0, 0, 1)); /* XX XXXX XXXX 1 000 0000 0000 0000 0000 0001 */ /* Take the first 10 bits with RTE ------ 00 0000 0001 */ DE_TEST_ASSERT(deFloat32To16RTE(getFloat32(1, 127 - 25, 1)) == getFloat16(1, 0, 1)); /* Absolute value: 2^-24 - e, extremely near minimal 16-bit denormalized */ DE_TEST_ASSERT(deFloat32To16RTE(getFloat32(0, 127 - 25, 0x7fffff)) == getFloat16(0, 0, 1)); DE_TEST_ASSERT(deFloat32To16RTE(getFloat32(1, 127 - 25, 0x7fffff)) == getFloat16(1, 0, 1)); /* Absolute value: 2^-24, minimal 16-bit denormalized */ /* The following (127 - 24) cases need to right shift mantissa (with leading 1) 9 bits -----------------> to here */ DE_TEST_ASSERT(deFloat32To16RTE(getFloat32(0, 127 - 24, 0)) == getFloat16(0, 0, 1)); /* X XXXX XXXX 1 000 0000 0000 0000 0000 0000 */ /* Take the first 10 bits with RTE ---------- 0 0000 0000 1 */ DE_TEST_ASSERT(deFloat32To16RTE(getFloat32(1, 127 - 24, 0)) == getFloat16(1, 0, 1)); DE_TEST_ASSERT(deFloat32To16RTE(getFloat32(0, 127 - 24, 1)) == getFloat16(0, 0, 1)); /* X XXXX XXXX 1 000 0000 0000 0000 0000 0001 */ /* Take the first 10 bits with RTE ---------- 0 0000 0000 1 */ DE_TEST_ASSERT(deFloat32To16RTE(getFloat32(1, 127 - 24, 1)) == getFloat16(1, 0, 1)); DE_TEST_ASSERT(deFloat32To16RTE(getFloat32(0, 127 - 24, 0x400000)) == getFloat16(0, 0, 2)); /* X XXXX XXXX 1 100 0000 0000 0000 0000 0000 */ /* Take the first 10 bits with RTE ---------- 0 0000 0000 2 */ DE_TEST_ASSERT(deFloat32To16RTE(getFloat32(1, 127 - 24, 0x400000)) == getFloat16(1, 0, 2)); DE_TEST_ASSERT(deFloat32To16RTE(getFloat32(0, 127 - 24, 0x400001)) == getFloat16(0, 0, 2)); /* X XXXX XXXX 1 100 0000 0000 0000 0000 0001 */ /* Take the first 10 bits with RTE ---------- 0 0000 0000 2 */ DE_TEST_ASSERT(deFloat32To16RTE(getFloat32(1, 127 - 24, 0x400001)) == getFloat16(1, 0, 2)); DE_TEST_ASSERT(deFloat32To16RTE(getFloat32(0, 127 - 24, 0x4fffff)) == getFloat16(0, 0, 2)); DE_TEST_ASSERT(deFloat32To16RTE(getFloat32(1, 127 - 24, 0x4fffff)) == getFloat16(1, 0, 2)); DE_TEST_ASSERT(deFloat32To16RTE(getFloat32(0, 127 - 20, 0x123456)) == getFloat16(0, 0, 0x12)); DE_TEST_ASSERT(deFloat32To16RTE(getFloat32(1, 127 - 20, 0x123456)) == getFloat16(1, 0, 0x12)); DE_TEST_ASSERT(deFloat32To16RTE(getFloat32(0, 127 - 18, 0x654321)) == getFloat16(0, 0, 0x73)); DE_TEST_ASSERT(deFloat32To16RTE(getFloat32(1, 127 - 18, 0x654321)) == getFloat16(1, 0, 0x73)); /* Absolute value: 2^-14 - 2^-24 = (2 - 2^-9) * 2^-15, maximal 16-bit denormalized */ DE_TEST_ASSERT(deFloat32To16RTE(getFloat32(0, 127 - 15, 0x7fc000)) == getFloat16(0, 0, 0x3ff)); /* 0x7fc000: 0111 1111 1100 0000 0000 0000 */ DE_TEST_ASSERT(deFloat32To16RTE(getFloat32(1, 127 - 15, 0x7fc000)) == getFloat16(1, 0, 0x3ff)); DE_TEST_ASSERT(deFloat32To16RTE(getFloat32(0, 127 - 15, 0x7fc000 - 1)) == getFloat16(0, 0, 0x3ff)); DE_TEST_ASSERT(deFloat32To16RTE(getFloat32(1, 127 - 15, 0x7fc000 - 1)) == getFloat16(1, 0, 0x3ff)); DE_TEST_ASSERT(deFloat32To16RTE(getFloat32(0, 127 - 15, 0x7fc000 + 1)) == getFloat16(0, 0, 0x3ff)); DE_TEST_ASSERT(deFloat32To16RTE(getFloat32(1, 127 - 15, 0x7fc000 + 1)) == getFloat16(1, 0, 0x3ff)); /* Normalized -> normalized */ DE_TEST_ASSERT(deFloat32To16RTE(getFloat32(0, 127 - 15, 0x7fe000)) == getFloat16(0, 1, 0)); /* 0x7fe000: 0111 1111 1110 0000 0000 0000 */ DE_TEST_ASSERT(deFloat32To16RTE(getFloat32(1, 127 - 15, 0x7fe000)) == getFloat16(1, 1, 0)); /* Absolute value: (2 - 2^-23) * 2^-15, extremely near 2^-14, minimal 16-bit normalized */ DE_TEST_ASSERT(deFloat32To16RTE(getFloat32(0, 127 - 15, 0x7fffff)) == getFloat16(0, 1, 0)); DE_TEST_ASSERT(deFloat32To16RTE(getFloat32(1, 127 - 15, 0x7fffff)) == getFloat16(1, 1, 0)); /* Absolute value: 2^-14, minimal 16-bit normalized */ DE_TEST_ASSERT(deFloat32To16RTE(getFloat32(0, 127 - 14, 0)) == getFloat16(0, 1, 0)); DE_TEST_ASSERT(deFloat32To16RTE(getFloat32(1, 127 - 14, 0)) == getFloat16(1, 1, 0)); DE_TEST_ASSERT(deFloat32To16RTE(getFloat32(0, 127 + 15, (0x3fe << 13) + (1 << 12))) == getFloat16(0, 0x1e, 0x3fe)); DE_TEST_ASSERT(deFloat32To16RTE(getFloat32(1, 127 + 15, (0x3fe << 13) + (1 << 12))) == getFloat16(1, 0x1e, 0x3fe)); /* Normalized -> minimal/maximal normalized */ DE_TEST_ASSERT(deFloat32To16RTE(getFloat32(0, 127 + 15, (0x3fe << 13) + (1 << 12) + 1)) == getFloat16(0, 0x1e, 0x3ff)); DE_TEST_ASSERT(deFloat32To16RTE(getFloat32(1, 127 + 15, (0x3fe << 13) + (1 << 12) + 1)) == getFloat16(1, 0x1e, 0x3ff)); /* Absolute value: 65504 - 2^-23, extremely near maximal 16-bit normalized */ DE_TEST_ASSERT(deFloat32To16RTE(getFloat32(0, 127 + 15, (0x3ff << 13) - 1)) == getFloat16(0, 0x1e, 0x3ff)); DE_TEST_ASSERT(deFloat32To16RTE(getFloat32(1, 127 + 15, (0x3ff << 13) - 1)) == getFloat16(1, 0x1e, 0x3ff)); /* Absolute value: 65504, maximal 16-bit normalized */ DE_TEST_ASSERT(deFloat32To16RTE(getFloat32(0, 127 + 15, 0x3ff << 13)) == getFloat16(0, 0x1e, 0x3ff)); DE_TEST_ASSERT(deFloat32To16RTE(getFloat32(1, 127 + 15, 0x3ff << 13)) == getFloat16(1, 0x1e, 0x3ff)); DE_TEST_ASSERT(deFloat32To16RTE(getFloat32(0, 127 + 15, (0x3ff << 13) + 1)) == getFloat16(0, 0x1e, 0x3ff)); DE_TEST_ASSERT(deFloat32To16RTE(getFloat32(1, 127 + 15, (0x3ff << 13) + 1)) == getFloat16(1, 0x1e, 0x3ff)); DE_TEST_ASSERT(deFloat32To16RTE(getFloat32(0, 127 + 15, (0x3ff << 13) + 0x456)) == getFloat16(0, 0x1e, 0x3ff)); DE_TEST_ASSERT(deFloat32To16RTE(getFloat32(1, 127 + 15, (0x3ff << 13) + 0x456)) == getFloat16(1, 0x1e, 0x3ff)); DE_TEST_ASSERT(deFloat32To16RTE(getFloat32(0, 127 + 15, (0x3ff << 13) + (1 << 12) - 1)) == getFloat16(0, 0x1e, 0x3ff)); DE_TEST_ASSERT(deFloat32To16RTE(getFloat32(1, 127 + 15, (0x3ff << 13) + (1 << 12) - 1)) == getFloat16(1, 0x1e, 0x3ff)); /* Normalized -> Inf */ DE_TEST_ASSERT(deFloat32To16RTE(getFloat32(0, 127 + 15, (0x3ff << 13) + (1 << 12))) == getFloat16(0, 0x1f, 0)); DE_TEST_ASSERT(deFloat32To16RTE(getFloat32(1, 127 + 15, (0x3ff << 13) + (1 << 12))) == getFloat16(1, 0x1f, 0)); /* Absolute value: maximal 32-bit normalized */ DE_TEST_ASSERT(deFloat32To16RTE(getFloat32(0, 127 + 15, 0x7fffff)) == getFloat16(0, 0x1f, 0)); DE_TEST_ASSERT(deFloat32To16RTE(getFloat32(1, 127 + 15, 0x7fffff)) == getFloat16(1, 0x1f, 0)); for (idx = 0; idx < 256; ++idx) { deUint32 exponent = deRandom_getUint32(&rnd); deUint32 mantissa = deRandom_getUint32(&rnd); exponent = exponent % (0xfe - (127 + 16) + 1) + (127 + 16); /* Make sure >= 127 + 16, <= 0xfe */ mantissa &= 0x7fffffu; /* Take the last 23 bits */ DE_TEST_ASSERT(deFloat32To16RTE(getFloat32(0, exponent, mantissa)) == getFloat16(0, 0x1f, 0)); DE_TEST_ASSERT(deFloat32To16RTE(getFloat32(1, exponent, mantissa)) == getFloat16(1, 0x1f, 0)); } } DE_END_EXTERN_C
2.453125
2
2024-11-18T19:40:36.104056+00:00
2021-05-12T10:10:27
6c8514edda3362edafd46c472921cebf8986db64
{ "blob_id": "6c8514edda3362edafd46c472921cebf8986db64", "branch_name": "refs/heads/main", "committer_date": "2021-05-12T10:10:27", "content_id": "6d313802997a96ea8435b0e973511ffab7b26b76", "detected_licenses": [ "MIT" ], "directory_id": "65b30f3a45fa3ed3d18c900b68242efbda0b44ed", "extension": "h", "filename": "conio.h", "fork_events_count": 0, "gha_created_at": "2021-08-23T12:46:59", "gha_event_created_at": "2021-08-23T12:46:59", "gha_language": null, "gha_license_id": "MIT", "github_id": 399100744, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1688, "license": "MIT", "license_type": "permissive", "path": "/Include/Linux/conio.h", "provenance": "stackv2-0012.json.gz:229034", "repo_name": "fujun750/c4droid-code", "revision_date": "2021-05-12T10:10:27", "revision_id": "794538264c33ea139b034a8871c261fff6a3e1c8", "snapshot_id": "c4cf5c7df0f5f2e8b9bac1af40b7fea69fe6a484", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/fujun750/c4droid-code/794538264c33ea139b034a8871c261fff6a3e1c8/Include/Linux/conio.h", "visit_date": "2023-04-20T17:33:20.159292" }
stackv2
/* * conio.h * C4droid自带这个头,所以使用C4droid运行可以忽略 * 这个头文件主要提供终端常用的getch和kbhit函数 * 如果使用其他Linux系统,需要这个头文件将它放在合适位置来引用 * * @Author: QAIU */ #ifndef CONIO_H #define CONIO_H #include <stdio.h> #include <time.h> #include <stdlib.h> #include <pthread.h> #include <termios.h> #include <unistd.h> #include <unistd.h> #include <fcntl.h> //读取单字符 https://my.oschina.net/yougui/blog/111345 static char getch() { struct termios oldt, newt; tcgetattr(STDIN_FILENO, &oldt); memcpy(&newt, &oldt, sizeof(newt)); newt.c_lflag &= ~(ICANON | ECHO | ECHOE | ECHOK | ECHONL | ECHOPRT | ECHOKE | ICRNL); tcsetattr(STDIN_FILENO, TCSANOW, &newt); char c=getchar(); tcsetattr(STDIN_FILENO, TCSANOW, &oldt); return c; } //判断输入 https://www.cnblogs.com/xiayong123/archive/2011/07/19/3717262.html static int kbhit(void) { struct termios oldt, newt; tcgetattr(STDIN_FILENO, &oldt); newt = oldt; newt.c_lflag &= ~(ICANON | ECHO); tcsetattr(STDIN_FILENO, TCSANOW, &newt); int oldf = fcntl(STDIN_FILENO, F_GETFL, 0); fcntl(STDIN_FILENO, F_SETFL, oldf | O_NONBLOCK); int ch = getchar(); tcsetattr(STDIN_FILENO, TCSANOW, &oldt); fcntl(STDIN_FILENO, F_SETFL, oldf); return (ch != EOF)? ungetc(ch, stdin),1:0; } static void gotoxy(int x, int y) { printf("\033[%d;%df", y, x); } static void _gotoxy(int x,int y) {gotoxy(x,y);} static void clrscr() { printf("\033[2J\033[0;0f"); } static void _clrscr() {clrscr();} static int _getch() {return getch();} static int _kbhit() {return kbhit();} #endif
2.453125
2
2024-11-18T19:40:36.886384+00:00
2018-01-14T11:13:39
f798b3fdeef5d88f4f1f510c38d0ddeefbf40ae5
{ "blob_id": "f798b3fdeef5d88f4f1f510c38d0ddeefbf40ae5", "branch_name": "refs/heads/master", "committer_date": "2018-01-14T11:13:39", "content_id": "5197f430ee7a98786a36446359ce16c4ad3d8ce6", "detected_licenses": [ "MIT" ], "directory_id": "224b6413fdde0a0175331dd606d10ed7956d2ab4", "extension": "h", "filename": "consumer.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 12148731, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3735, "license": "MIT", "license_type": "permissive", "path": "/runtime/tests/mca-api-common/consumer.h", "provenance": "stackv2-0012.json.gz:229418", "repo_name": "keryell/smecc", "revision_date": "2018-01-14T11:13:39", "revision_id": "ddb9361aba2887151ff001d96be6f2ef03ca1af2", "snapshot_id": "e405d215684df9a44e4ba395a9b083f69e805f20", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/keryell/smecc/ddb9361aba2887151ff001d96be6f2ef03ca1af2/runtime/tests/mca-api-common/consumer.h", "visit_date": "2021-01-20T23:03:28.033474" }
stackv2
/* Receive messages from node <PRODUCER_DOMAIN, PRODUCER_NODE, SEND_PORT> into <CONSUMER_DOMAIN, CONSUMER_NODE, RECEIVE_PORT> */ void consumer(mcapi_param_t *parameters) { #ifdef SMECY_VERBOSE fputs("Entering the consumer\n", stderr); #endif mcapi_info_t info; mcapi_endpoint_t data_transmit_endpoint; mcapi_endpoint_t data_receive_endpoint; mcapi_status_t status; // init node attributes. Not clear in which MCAPI version it is needed... /* It looks like in the Linux MCAPI implementation reference from MCA, even the 2.015 version looks like a V1 interface... */ #if (MCAPI_VERSION >= 2000) mcapi_node_attributes_t node_attributes; mcapi_node_init_attributes(&node_attributes, &status); MCAPI_CHECK_STATUS(status); /* 6 arguments in V.2 */ mcapi_initialize(CONSUMER_DOMAIN, CONSUMER_NODE, &node_attributes, parameters, &info, &status); MCAPI_TRACE_C("Host initialization V.2 done"); #else /* 5 arguments in V.1 */ mcapi_initialize(CONSUMER_DOMAIN, CONSUMER_NODE, parameters, &info, &status); MCAPI_TRACE_C("Host initialization V.1 done"); #endif MCAPI_CHECK_STATUS(status); /* First use communications with messages (connection-less mode) */ mcapi_endpoint_t msg_receive = mcapi_endpoint_create(RECEIVE_MSG_PORT, &status); MCAPI_CHECK_STATUS(status); for (int i = 0; i < N_MSG; i++) { /* Messages (ie for connection-less communications) have to be provided by the user in MCAPI: */ char buffer[100]; size_t received_size; mcapi_msg_recv(msg_receive, buffer, sizeof(buffer), &received_size, &status); MCAPI_CHECK_STATUS(status); /* Avoid later over-reading: */ buffer[sizeof(buffer) - 1] = '\0'; printf("Received %zd characters with a message: %s\n", received_size, buffer); } // Delete this endpoint which is useless now: mcapi_endpoint_delete(msg_receive, &status); MCAPI_CHECK_STATUS(status); MCAPI_TRACE_C("Communications with packets (connected mode)"); /* Then use communications with packets (connected mode) */ mcapi_endpoint_t pkt_receive = mcapi_endpoint_create(RECEIVE_PKT_PORT, &status); MCAPI_CHECK_STATUS(status); mcapi_pktchan_recv_hndl_t receive_gate; mcapi_request_t handle; // Let the sender do the connection and open for receive mcapi_pktchan_recv_open_i(&receive_gate, pkt_receive, &handle, &status); MCAPI_CHECK_STATUS(status); size_t size; // Wait for the completion of opening mcapi_wait(&handle, &size, MCAPI_TIMEOUT_INFINITE, &status); MCAPI_CHECK_STATUS(status); MCAPI_TRACE_C("Channel connected"); for (int i = 0; i < N_MSG; i++) { char *message; size_t received_size; mcapi_pktchan_recv(receive_gate, (void **)&message, &received_size, &status); MCAPI_CHECK_STATUS(status); printf("Received %zd characters with a packet: %*s\n", received_size, received_size, message); // Give back the memory message to the library: mcapi_pktchan_release(message, &status); MCAPI_CHECK_STATUS(status); } // Now we can close the receive side of the channel MCAPI_TRACE_C("Closing the consumer channel"); mcapi_pktchan_recv_close_i(receive_gate, &handle, &status); MCAPI_CHECK_STATUS(status); MCAPI_TRACE_C("Waiting for the closing"); mcapi_wait(&handle, &size, MCAPI_TIMEOUT_INFINITE, &status); MCAPI_CHECK_STATUS(status); // Remove useless the receiving endpoint MCAPI_TRACE_C("Delete the end point"); mcapi_endpoint_delete(pkt_receive, &status); MCAPI_CHECK_STATUS(status); /* Release the API use */ MCAPI_TRACE_C("Finalizing..."); mcapi_finalize(&status); MCAPI_CHECK_STATUS(status); #ifdef SMECY_VERBOSE fputs("Exiting the consumer\n", stderr); #endif }
2.34375
2
2024-11-18T19:52:23.603772+00:00
2021-10-10T17:01:47
d6c0a9413dbf07117312f2b78a45e32f5d6f595d
{ "blob_id": "d6c0a9413dbf07117312f2b78a45e32f5d6f595d", "branch_name": "refs/heads/master", "committer_date": "2021-10-10T17:01:47", "content_id": "b51c6bff4cb45a7ca39d346be3a59ffac387a4ed", "detected_licenses": [ "MIT" ], "directory_id": "061b6f22e04dc63243f8f9fef2cc7b131de38ac0", "extension": "c", "filename": "HashKeys.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 933, "license": "MIT", "license_type": "permissive", "path": "/didactic_engines/AikiChessBitboard/HashKeys.c", "provenance": "stackv2-0013.json.gz:26", "repo_name": "Chavelier/chess_programming", "revision_date": "2021-10-10T17:01:47", "revision_id": "198387d20fdaf29be8e9023c04c77e9b48d04843", "snapshot_id": "4e1aaf922065edf979efd6b98b2e8859cbf149e4", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Chavelier/chess_programming/198387d20fdaf29be8e9023c04c77e9b48d04843/didactic_engines/AikiChessBitboard/HashKeys.c", "visit_date": "2023-08-30T18:42:44.820897" }
stackv2
#include "stdio.h" #include "Definitions.h" U64 Generate_hashKey(const CHESS_BOARD *chessBoard) { int sq = 0; U64 finalKey = 0; int piece = EmptySquare; int index; int piece1 = EmptySquare; // pieces for(sq = 0; sq < 64; sq++) { for (index = 1; index <=12; index++) { if ((1ULL << sq) & chessBoard->pieces [index]) { piece = index; finalKey ^= PieceKeys [piece][sq]; } } } if(chessBoard->SideToMove == White) { finalKey ^= SideKey; } if(chessBoard->EnPassant_Square != No_Sq) { ASSERT(chessBoard->EnPassant_Square >=0 && chessBoard->EnPassant_Square < 64); //ASSERT(SqOnBoard(pos->enPas)); //ASSERT(RanksBrd[pos->enPas] == RANK_3 || RanksBrd[pos->enPas] == RANK_6); finalKey ^= PieceKeys [EmptySquare][chessBoard->EnPassant_Square]; } //ASSERT(pos->castlePerm>=0 && pos->castlePerm<=15); finalKey ^= CastleKeys [chessBoard->castlingPermission]; return finalKey; }
2.03125
2
2024-11-18T19:52:23.942879+00:00
2016-04-07T20:50:40
435c2ae88f83c68090a954cf1bcf5ddc5d5ca261
{ "blob_id": "435c2ae88f83c68090a954cf1bcf5ddc5d5ca261", "branch_name": "refs/heads/master", "committer_date": "2016-04-07T20:50:40", "content_id": "a1fdbc09c8e07677da1ee8683efceb87b7ab2b50", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "38acba9d74e3cfbc2e5c2cf23545ae0742ead8b6", "extension": "c", "filename": "main.c", "fork_events_count": 0, "gha_created_at": "2016-04-07T15:35:39", "gha_event_created_at": "2016-04-07T15:35:40", "gha_language": null, "gha_license_id": null, "github_id": 55706558, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 265, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/main.c", "provenance": "stackv2-0013.json.gz:411", "repo_name": "AldoCuriel/PRUEBA1", "revision_date": "2016-04-07T20:50:40", "revision_id": "2193e3804af081307784bc2cc965dec7c0a55d22", "snapshot_id": "05e8625d1bf4ba09fef31853b8ba14273b8efeca", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/AldoCuriel/PRUEBA1/2193e3804af081307784bc2cc965dec7c0a55d22/main.c", "visit_date": "2020-05-20T18:48:37.572189" }
stackv2
#include <stdio.h> int main(void) { int val1, val2; float res; int opc; printf(" 1-suma, 2-resta, 3-mult, 4-div\n"); scanf("%d",&opc); getchar(); printf("valor 1\n"); scanf("%d",&val1); printf("valor 2\n"); scanf("%d",&val2); return 0; }
2.640625
3