added
stringdate 2024-11-18 17:54:19
2024-11-19 03:39:31
| created
timestamp[s]date 1970-01-01 00:04:39
2023-09-06 04:41:57
| id
stringlengths 40
40
| metadata
dict | source
stringclasses 1
value | text
stringlengths 13
8.04M
| score
float64 2
4.78
| int_score
int64 2
5
|
---|---|---|---|---|---|---|---|
2024-11-18T22:11:41.558715+00:00 | 2021-11-14T09:45:57 | 7463ff2991ccca5fa0e0b965c3172a01aa44fb56 | {
"blob_id": "7463ff2991ccca5fa0e0b965c3172a01aa44fb56",
"branch_name": "refs/heads/main",
"committer_date": "2021-11-14T09:45:57",
"content_id": "561c2c340177516c8682c943e9eaa10a55e13dc2",
"detected_licenses": [
"MIT"
],
"directory_id": "a663253f86a6f010513c0206fbe62ffd37ce7e95",
"extension": "c",
"filename": "singly_linked_list.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 427630261,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3168,
"license": "MIT",
"license_type": "permissive",
"path": "/src/singly_linked_list.c",
"provenance": "stackv2-0087.json.gz:8918",
"repo_name": "m2enu/clang_linked_list",
"revision_date": "2021-11-14T09:45:57",
"revision_id": "49b87cec16d09f75b704292adcb30137f8edb6ae",
"snapshot_id": "8533c0331046ceaa412f324192cf567aaa399891",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/m2enu/clang_linked_list/49b87cec16d09f75b704292adcb30137f8edb6ae/src/singly_linked_list.c",
"visit_date": "2023-09-05T09:33:59.194282"
} | stackv2 | /**
* @file singly_linked_list.c
* @brief Implementation of Singly Linked List
* @author m2enu
* @par License
* https://github.com/m2enu/clang_linked_list/blob/main/LICENSE
*/
#include "singly_linked_list.h"
#include <stdint.h>
#include <stddef.h>
#include <stdlib.h>
#define ALLOC(x) malloc(x) /**< Macro for memory allocation */
#define FREE(x) free(x) /**< Macro for free */
#if defined(NDEBUG)
#define ASSERT(x)
#else
#include <assert.h>
#define ASSERT(x) assert(x)
#endif
SinglyLinkedListClass* SinglyLinkedListCreate(void)
{
SinglyLinkedListClass* pRet = ALLOC(sizeof(SinglyLinkedListClass));
if (pRet == NULL)
{
return NULL;
}
/* The 1st item of SinglyLinkedListClass.pItem is dummy. */
pRet->pItem = ALLOC(sizeof(SinglyLinkedListItem));
if (pRet->pItem == NULL)
{
return NULL;
}
pRet->NumberOfItems = 0u;
return pRet;
}
LinkedListError SinglyLinkedListAdd(SinglyLinkedListClass* pThis, void* pValueToAdd)
{
if ((pThis == NULL) || (pValueToAdd == NULL))
{
return LINKED_LIST_ERROR_PARAMETER;
}
/* Allocate new linked list */
SinglyLinkedListItem* pListToAdd = ALLOC(sizeof(SinglyLinkedListItem));
if (pListToAdd == NULL)
{
return LINKED_LIST_ERROR_NO_MEMORY;
}
pListToAdd->pNext = NULL;
pListToAdd->pValue = pValueToAdd;
/* Search the tail of linked list */
SinglyLinkedListItem* pItem = pThis->pItem;
while (pItem->pNext != NULL)
{
pItem = pItem->pNext;
}
/* Join the item at the tail of linked list */
pItem->pNext = pListToAdd;
pThis->NumberOfItems++;
return LINKED_LIST_ERROR_NONE;
}
LinkedListError SinglyLinkedListRemove(SinglyLinkedListClass* pThis, void* pValueToRemove)
{
if ((pThis == NULL) || (pValueToRemove == NULL))
{
return LINKED_LIST_ERROR_PARAMETER;
}
/* Search specified data from the list */
LinkedListError ret = LINKED_LIST_ERROR_NOT_FOUND;
SinglyLinkedListItem* pCurr = pThis->pItem->pNext;
SinglyLinkedListItem* pPrev = pThis->pItem;
while (pCurr!= NULL)
{
if (pCurr->pValue == pValueToRemove)
{
ASSERT(pThis->NumberOfItems > 0u);
ret = LINKED_LIST_ERROR_NONE;
pPrev->pNext = pCurr->pNext;
FREE(pCurr);
pCurr = pPrev->pNext;
pThis->NumberOfItems--;
}
else
{
pPrev = pCurr;
pCurr = pCurr->pNext;
}
}
return ret;
}
SinglyLinkedListItem* SinglyLinkedListHead(const SinglyLinkedListClass* pThis)
{
if (pThis == NULL)
{
return NULL;
}
return pThis->pItem->pNext;
}
SinglyLinkedListItem* SinglyLinkedListNext(const SinglyLinkedListItem* pItem)
{
if (pItem == NULL)
{
return NULL;
}
return pItem->pNext;
}
void* SinglyLinkedListValue(const SinglyLinkedListItem* pItem)
{
if (pItem == NULL)
{
return NULL;
}
return pItem->pValue;
}
uint32_t SinglyLinkedListNumberOfItems(const SinglyLinkedListClass* pThis)
{
return pThis->NumberOfItems;
}
| 3.28125 | 3 |
2024-11-18T22:11:41.907264+00:00 | 2019-08-21T14:29:25 | 972479954a26dd61a644e905e6a6c990b18aeca5 | {
"blob_id": "972479954a26dd61a644e905e6a6c990b18aeca5",
"branch_name": "refs/heads/master",
"committer_date": "2019-08-21T14:29:25",
"content_id": "0f8f87744766b71b1952467f17063da68dafe85e",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "321b073cd02acfb80dd3c4b46760567f3182773b",
"extension": "c",
"filename": "libpath.c",
"fork_events_count": 0,
"gha_created_at": "2018-04-04T14:27:13",
"gha_event_created_at": "2021-06-10T20:21:29",
"gha_language": "JavaScript",
"gha_license_id": "Apache-2.0",
"github_id": 128073978,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2708,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/CUTE/demo/c_lib/libpath.c",
"provenance": "stackv2-0087.json.gz:9176",
"repo_name": "Zichen-Wang/CUTE",
"revision_date": "2019-08-21T14:29:25",
"revision_id": "8feb2ef797e8ac868b9e89338b7871a04757c3b1",
"snapshot_id": "912d1518cb2ffa9ee889f12e7f1f6945206d5548",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/Zichen-Wang/CUTE/8feb2ef797e8ac868b9e89338b7871a04757c3b1/CUTE/demo/c_lib/libpath.c",
"visit_date": "2022-12-13T06:28:05.515375"
} | stackv2 | #include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX_NODE 4000000
struct GraphEdge {
int to, direction;
};
struct GraphEdgeSet {
struct GraphEdge *edges;
int total;
};
struct Path {
int *directions, length;
};
void build_path(
struct Path *path, int S, int T, struct GraphEdgeSet* graph,
int *que, int *dis, int *from_n, int *from_d,
int *forbidden
) {
int head = 0, tail = 1;
int sta, i;
que[head] = S;
dis[S] = 0;
while (head < tail) {
sta = que[head++];
if (sta == T)
break;
for (i = 0; i < graph[sta].total; i++) {
if (forbidden[graph[sta].edges[i].to] == 1)
continue;
if (dis[graph[sta].edges[i].to] > dis[sta] + 1) {
dis[graph[sta].edges[i].to] = dis[sta] + 1;
from_n[graph[sta].edges[i].to] = sta;
from_d[graph[sta].edges[i].to] = graph[sta].edges[i].direction;
que[tail++] = graph[sta].edges[i].to;
}
}
}
if (dis[T] == MAX_NODE + 1) {
path -> directions = NULL;
path -> length = 0;
return;
}
for (i = 0; i < tail; i++)
dis[que[i]] = MAX_NODE + 1;
path -> length = 0;
for (i = T; i != S; i = from_n[i])
path -> length++;
path -> directions = (int *)malloc(path -> length * sizeof(int));
int counter = path -> length - 1;
for (i = T; i != S; i = from_n[i]) {
path -> directions[counter] = from_d[i];
counter--;
}
}
struct Path *find(int* entities, int n, struct GraphEdgeSet* graph) {
struct Path *pattern = (struct Path *)malloc(n * (n - 1) / 2 * sizeof(struct Path));
int *que = (int *)malloc(MAX_NODE * sizeof(int));
int *dis = (int *)malloc(MAX_NODE * sizeof(int));
int *from_n = (int *)malloc(MAX_NODE * sizeof(int));
int *from_d = (int *)malloc(MAX_NODE * sizeof(int));
int *forbidden = (int *)malloc(MAX_NODE * sizeof(int));
int i, j, k;
for (i = 0; i < MAX_NODE; i++) {
dis[i] = MAX_NODE + 1;
forbidden[i] = 0;
}
int counter = 0;
for (i = 0; i < n; i++)
for (j = i + 1; j < n; j++) {
for (k = 0; k < n; k++)
if (k != i && k != j)
forbidden[entities[k]] = 1;
build_path(&pattern[counter], entities[i], entities[j], graph, que, dis, from_n, from_d, forbidden);
counter++;
for (k = 0; k < n; k++)
if (k != i && k != j)
forbidden[entities[k]] = 0;
}
free(que);
free(dis);
free(from_n);
free(from_d);
return pattern;
}
| 2.75 | 3 |
2024-11-18T22:11:41.977864+00:00 | 2021-09-01T22:37:46 | 7542fc0d755421e30c61a61083939f7d8163d2af | {
"blob_id": "7542fc0d755421e30c61a61083939f7d8163d2af",
"branch_name": "refs/heads/master",
"committer_date": "2021-09-01T22:37:46",
"content_id": "d57825e51b1617228ea3cd64ff11e1ae5b1d0574",
"detected_licenses": [
"MIT"
],
"directory_id": "980909a1bc2196b7a55fe7bf22c077381277c53c",
"extension": "h",
"filename": "satoshi-tx.h",
"fork_events_count": 0,
"gha_created_at": "2021-08-09T11:50:09",
"gha_event_created_at": "2021-08-16T20:25:01",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 394271045,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2596,
"license": "MIT",
"license_type": "permissive",
"path": "/include/satoshi-tx.h",
"provenance": "stackv2-0087.json.gz:9304",
"repo_name": "chehw/spv-node",
"revision_date": "2021-09-01T22:37:46",
"revision_id": "5ed222376eb3d78833756e079040773e67e1370e",
"snapshot_id": "c3e6c16a6eee62d8605bd550359d0f11024c6007",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/chehw/spv-node/5ed222376eb3d78833756e079040773e67e1370e/include/satoshi-tx.h",
"visit_date": "2023-07-15T13:45:58.099078"
} | stackv2 | #ifndef _SATOSHI_TX_H_
#define _SATOSHI_TX_H_
#include <stdio.h>
#ifdef __cplusplus
extern "C" {
#endif
#include "satoshi-types.h"
#include "sha.h"
/*****************************************
* satoshi_tx_sighash_type:
* sighash_all: default type, signs all txins and txouts.
* sighash_none: signs all txins, no txouts, allowing anyone to change output amounts. (an Unfilled Signed Cheque).
* sighash_single: sign all txins and txouts[cur_index] only. to ensure nobody can change txouts[cur_index]
*
* sighash_all | sighash_anyone_can_pay: signs txins[cur_index] and all txouts, allows anyone to add or remove other inputs.
* sighash_none | sighash_anyone_can_pay: signs txins[cur_index] only, allows anyone to add or remove other inputs or outputs.
* sighash_single | sighash_anyone_can_pay: signs txins[cur_index] and txouts[cur_index]. to ensure nobody can change txouts[cur_index], and allows anyone to add or remove other inputs.
*
*****************************************/
enum satoshi_tx_sighash_type
{
satoshi_tx_sighash_all = 1,
satoshi_tx_sighash_none = 2,
satoshi_tx_sighash_single = 3,
satoshi_tx_sighash_masks = 0x1f, // according to the current implementation in bitcoin-core
satoshi_tx_sighash_anyone_can_pay = 0x80
};
/*******************************************
* satoshi_rawtx:
* generate digest for sign / verify
*******************************************/
typedef struct satoshi_rawtx
{
satoshi_tx_t * tx; // attached tx
// internal states: pre-hash <-- sha(common_data)
sha256_ctx_t sha[2]; // sha[0]: for legacy, sha[1]: for segwit
satoshi_txin_t * txins; // raw_txins for legacy tx
int last_hashed_txin_index; // legacy tx states: pre-hashed index
uint256_t txouts_hash[1]; // segwit_v0: step 8
int (* get_digest)(struct satoshi_rawtx * rawtx,
ssize_t cur_index, // current txin index
uint32_t hash_type,
const satoshi_txout_t * utxo,
uint256_t * digest);
}satoshi_rawtx_t;
satoshi_rawtx_t * satoshi_rawtx_attach(satoshi_rawtx_t * rawtx, satoshi_tx_t * tx);
void satoshi_rawtx_detach(satoshi_rawtx_t * rawtx);
void satoshi_tx_dump(const satoshi_tx_t * tx);
/**
* @deprecated
* keep these functions for test use only
* @{
*/
int segwit_v0_tx_get_digest(const satoshi_tx_t * tx,
int cur_index, // txin index
uint32_t hash_type,
const satoshi_txout_t * utxo, // prevout
uint256_t * hash
);
int satoshi_tx_get_digest(
satoshi_tx_t * tx,
int txin_index,
uint32_t hash_type,
const satoshi_txout_t * utxo,
uint256_t * hash);
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif
| 2.34375 | 2 |
2024-11-18T22:11:42.116445+00:00 | 2016-10-18T03:57:10 | 301b22059bc6b6a7cb68c70cd6899b324fd9a817 | {
"blob_id": "301b22059bc6b6a7cb68c70cd6899b324fd9a817",
"branch_name": "refs/heads/master",
"committer_date": "2016-10-18T03:57:10",
"content_id": "521669b79809ef365e7fb654b46b1b66f787c9cf",
"detected_licenses": [
"MIT"
],
"directory_id": "2feb8b34d47cf1e420f88ab2ee857d1f6182a5e6",
"extension": "c",
"filename": "stdlib.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 65330655,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5707,
"license": "MIT",
"license_type": "permissive",
"path": "/kernel/lib/stdlib.c",
"provenance": "stackv2-0087.json.gz:9434",
"repo_name": "lazear/crunchy",
"revision_date": "2016-10-18T03:57:10",
"revision_id": "ecbd9dc196931e44f33be10cfb1d563b3573664c",
"snapshot_id": "b0d9c1ac340a396afad19a0b10b4f2527385ffd8",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/lazear/crunchy/ecbd9dc196931e44f33be10cfb1d563b3573664c/kernel/lib/stdlib.c",
"visit_date": "2021-03-27T16:02:55.068572"
} | stackv2 | /*
stdlib.c
===============================================================================
MIT License
Copyright (c) 2007-2016 Michael Lazear
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
===============================================================================
Implementation of stdlib for crunchy
*/
#include <types.h>
#include <ctype.h>
#include <stdlib.h>
/*double atof(char* s) {
double integer = 0;
double decimal = 0;
double divisor = 1.0;
double sign = 1.0;
bool fraction = false;
double tot = 0;
while (*s != '\0') {
if (isdigit(*s)) {
if(fraction) {
decimal = decimal*10 + (*s - '0');
divisor *= 10;
vga_puts(ftoa(decimal/divisor));
vga_putc('\n');
} else {
integer = (*s - '0');
//integer *= 10;
//integer += (*s - '0');
tot = tot*10 + integer;
vga_puts(ftoa(tot));
vga_putc('\n');
}
} else if (*s == '.') {
fraction = true;
vga_puts("Decimal found\n");
} else if (*s == '-') {
sign = -1.0;
} else {
//return sign * (integer + decimal/divisor);;
}
s++;
}
return sign * (tot + decimal/divisor);
}*/
# define PRECISION 5
// adapted from http://stackoverflow.com/questions/2302969/how-to-implement-char-ftoafloat-num-without-sprintf-library-function-i/2303011#2303011
char* ftoa(double num, char* str)
{
int whole_part = num;
int digit = 0, reminder =0;
int log_value = dlog10(num), index = log_value;
long wt =0;
//Initilise stirng to zero
memset(str, 0 ,20);
//Extract the whole part from float num
for(int i = 1 ; i < log_value + 2 ; i++)
{
wt = pow(10,i);
reminder = whole_part % wt;
digit = (reminder - digit) / (wt/10);
//Store digit in string
str[index--] = digit + 48; // ASCII value of digit = digit + 48
if (index == -1)
break;
}
index = log_value + 1;
str[index] = '.';
double fraction_part = num - whole_part;
double tmp1 = fraction_part, tmp =0;
//Extract the fraction part from num
for( int i= 1; i < PRECISION; i++)
{
wt = 10;
tmp = tmp1 * wt;
digit = tmp;
//Store digit in string
str[++index] = digit + 48; // ASCII value of digit = digit + 48
tmp1 = tmp - digit;
}
return str;
}
// log10 for doubles
int dlog10(double v) {
return (v >= 1000000000u) ? 9 : (v >= 100000000u) ? 8 :
(v >= 10000000u) ? 7 : (v >= 1000000u) ? 6 :
(v >= 100000u) ? 5 : (v >= 10000u) ? 4 :
(v >= 1000u) ? 3 : (v >= 100u) ? 2 : (v >= 10u) ? 1u : 0u;
}
// log10 for integers
int log10(int v) {
return (v >= 1000000000u) ? 9 : (v >= 100000000u) ? 8 :
(v >= 10000000u) ? 7 : (v >= 1000000u) ? 6 :
(v >= 100000u) ? 5 : (v >= 10000u) ? 4 :
(v >= 1000u) ? 3 : (v >= 100u) ? 2 : (v >= 10u) ? 1u : 0u;
}
uint32_t abs(int x) {
if (x < 0)
return x * -1;
return x;
}
// raise n^x
int pow(int n, int x) {
if (x = 0) return 1;
while(x-- > 1)
{
n = n * n;
}
return n;
}
// string to integer
int atoi(char* s) {
int num = 0;
int sign = 1;
if (s[0] == '-')
sign = -1;
for (int i = 0; i < strlen(s) && s[i] != '\0'; i++) {
if (isdigit(s[i]))
num = num*10 + (s[i] - '0');
}
return sign*num;
}
// unsigned integer to string
char* itoa(uint32_t num, char* buffer, int base) {
int i = 0;
//num = abs(num);
int len = 8;
if (base == 2)
len = 32;
if (num == 0 && base == 2) {
while(i < len)
buffer[i++] = '0';
buffer[i] = '\0';
return buffer;
}
/* if (num == 0 && base == 0) {
buffer[0] = '0';
buffer[1] = '\0';
return buffer;
}*/
// go in reverse order
while (num != 0 && len--) {
int remainder = num % base;
// case for hexadecimal
buffer[i++] = (remainder > 9)? (remainder - 10) + 'A' : remainder + '0';
num = num / base;
}
while(len-- && base != 10)
buffer[i++] = '0';
buffer[i] = '\0';
return strrev(buffer);
}
// signed integer to string
char* sitoa(int num, char* buffer, int base) {
int i = 0;
int sign = 1;
int len = 8;
//num = abs(num);
if (num == 0 || base == 0) {
buffer[0] = '0';
buffer[1] = '\0';
return buffer;
}
if (num < 0) {
sign = 0;
num = abs(num);
}
// go in reverse order
while (num != 0 && len--) {
int remainder = num % base;
// case for hexadecimal
buffer[i++] = (remainder > 9)? (remainder - 10) + 'A' : remainder + '0';
num = num / base;
}
// if (sign == 0) buffer[i++] = '-';
buffer[i] = '\0';
return strrev(buffer);
}
| 2.75 | 3 |
2024-11-18T22:11:42.206749+00:00 | 2021-01-12T02:38:57 | f4ea933a940897e00260c6c63fe274e658ec38a7 | {
"blob_id": "f4ea933a940897e00260c6c63fe274e658ec38a7",
"branch_name": "refs/heads/master",
"committer_date": "2021-01-12T02:38:57",
"content_id": "8b6786209ec8055adf50540565d0d174c00f60ef",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "9587eca706ebd57bb39cd5a214bf9245662850be",
"extension": "c",
"filename": "array-demo.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": 5593,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/algorithm/array-demo.c",
"provenance": "stackv2-0087.json.gz:9565",
"repo_name": "Lbys881/ForgotCLearning",
"revision_date": "2021-01-12T02:38:57",
"revision_id": "17daa0898a916b77fa66b9de3365c7e68b1f9321",
"snapshot_id": "2db4c7fed1a2b79721baad4c9b371b6cd59dbc56",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Lbys881/ForgotCLearning/17daa0898a916b77fa66b9de3365c7e68b1f9321/src/algorithm/array-demo.c",
"visit_date": "2023-02-17T12:25:23.776243"
} | stackv2 | //
// Created by forgot on 2019-07-30.
// 数组的使用例子
//
#include <stdio.h>
#include <locale.h>
#include <string.h>
#include <time.h>
void print_array1();
void print_array2();
void print_array3();
void print_string();
void print_string2();
char *getDateTime();
//int main() {
//// char *nowtime = getDateTime();
//// printf("%s\n", nowtime);
//
//// char str3[9] = "Let's go"; //若数组长度定义为8,打印会有乱码,9或以上才正常
//// printf("size:%d",strlen(str3));
//// printf(str3);
//
//
//// print_string();
//// print_string2();
//
//// print_array1();
//// print_array2();
// print_array3();
//
// return 0;
//}
// 获取当前系统时间
char *getDateTime() {
static char nowtime[20];
time_t rawtime;
struct tm *ltime;
time(&rawtime);
ltime = localtime(&rawtime);
strftime(nowtime, 20, "%Y-%m-%d %H:%M:%S", ltime);
return nowtime;
}
void print_string() {
// a[5]占用5个int的内存空间,当前长度为5,后面没赋值的默认为0
//需要注意的是,“不完全初始化”和“完全不初始化”不一样。如果“完全不初始化”,即只定义“int a[5];”而不初始化,那么各个元素的值就不是0了,
// 所有元素都是垃圾值。无法预估是什么值, 然而好像并不是,
//你也不能写成“int a[5]={};”。如果大括号中什么都不写,那就是极其严重的语法错误
// int a[5] = {1, 2};//这样定义,则数组后面 3 位默认为 0
int a[5]; //也都是 0,跟编译器有关?别纠结这些了
printf("a=%d\n", a[3]);
printf("a=%d\n", a[4]);
printf("a=%d\n", a[2]);
// 每个int占4个字节,直接打印 sizeof(a) 将输出20个字节,而不是数组长度 5
printf("sizeof(a)=%lu\n", sizeof(a));
printf("a 长度=%lu\n", sizeof(a) / sizeof(a[0]));
// 怎么不初始化,那么各个元素的值也是0? 好像不是,这值怎么回事?
int b[5];
for (int i = 0; i < 5; ++i) {
printf("b[%d]=%d\n", i, b[i]);
}
// 二维数组中的列,必须要声明数字。 行可以不声明
int c[][2] = {1, 2};
// 若数组只定义,但没有初始化,则行和列都需要声明数字
int d[2][2];
// int e[2][];//wrong
char str1[30] = "Let's go"; // 字符串长度:8;数组长度:30
// 存储字符串的数组一定比字符串长度多一个元素,以容纳下字符串终止符(空字符'\0')。因此,str1 数组能够存储的字符串最大长度是 29。
// 如果定义数组长度为 8,而不是 30,就会发生错误,因为它无法包含字符串终止符。
char str2[9] = {'L', 'e', 't', '\'', 's', ' ', 'g', 'o', '\0'};
printf("str1 = %s\n", str1);
printf("str2 = %s\n", str2);
// 如果在定义一个字符数组时,没有显式地指定长度,但使用了字符串字面量来对它进行初始化,该数组的长度会比字符串长度多 1。如下列所示:
char str3[] = " to London!"; // 字符串长度:11 (注意开头的空格);
for (int j = 0; j < 12; ++j) {
printf("str3[%d]=%c\n", j, str3[j]);
}
// 数组长度:12
// 这个每个英文字母和符号各占用一个字节,所以直接打印sizeof(str3)得到的就是数组长度
printf("str3.length = %lu\n", sizeof(str3));
// printf("str3.length = %d\n", sizeof(str3)/ sizeof(str3[0]));
char str4[] = "中文字节";
// 一个中文字占3字节,然后 '\0'一个字节,一共13个
printf("str4.length = %lu\n", sizeof(str4));
printf("str4.length = %lu\n", sizeof(str4) / sizeof("中"));
// setlocale(LC_ALL,"Chs");
// for (int j = 0; j < 4; ++j) {
// printf("str[%d]=%s\n", j, str4[j]);
// }
printf("str4=%s\n", str4);
printf("str4.length=%d\n", strlen(str4));
}
void print_string2() {
char *str1 = "http://see.xidian.edu.cn/cpp/u/shipin/";
char str2[100] = "http://see.xidian.edu.cn/cpp/u/shipin_liming/";
char str3[5] = "12345";
//strlen()函数求出的字符串长度为有效长度,既不包含字符串末尾结束符 ‘\0’,取决于实际字符串长度
//sizeof()操作符求出的长度包含字符串末尾的结束符 ‘\0’,且取决于数组长度
//当在函数内部使用sizeof()求解由函数的形参传入的字符数组的长度时,得到的结果为指针的长度,既对应变量的字节数,而不是字符串的长度,此处一定要小心。
//一般要用sizeof(str1)/sizeof(str[0])去求,但也不一定准
printf("strlen(str1)=%lu, sizeof(str1)=%d\n", strlen(str1), sizeof(str1));
printf("strlen(str2)=%lu, sizeof(str2)=%d\n", strlen(str2), sizeof(str2));
printf("strlen(str3)=%lu, sizeof(str3)=%d\n", strlen(str3), sizeof(str3));
}
//下标法打印数组
void print_array1() {
int a[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
for (int i = 0; i < 10; i++)
printf("%d", a[i]);
printf("\n");
}
//由数组名计算地址 打印数组,数组名就是它存储的地址,*就能打出地址所指向的变量
// 先去找数组索引,再去指针寻址找数据
void print_array2() {
int a[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
for (int i = 0; i < 10; i++)
printf("%d", *(a + i));
printf("\n");
}
//用指针变量指向数组元素 打印数组
//直接根据指针去寻址,再去数据
void print_array3() {
int a[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int *p;
for (p = a; p < (a + 10); p++)
printf("%d", *p);
printf("\n");
} | 3.25 | 3 |
2024-11-18T22:11:42.868685+00:00 | 2015-05-03T09:28:43 | 6555d09d415d5cc3192ee1a203f1722a04f1d455 | {
"blob_id": "6555d09d415d5cc3192ee1a203f1722a04f1d455",
"branch_name": "refs/heads/master",
"committer_date": "2015-05-03T09:28:43",
"content_id": "9f5f3b7ae0a63f3602516c491ee29b66aa36840e",
"detected_licenses": [
"MIT"
],
"directory_id": "4d676e4bb9e956c57d5d9dbd921d385def523c4f",
"extension": "h",
"filename": "closure.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 29463147,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2258,
"license": "MIT",
"license_type": "permissive",
"path": "/imp/closure.h",
"provenance": "stackv2-0087.json.gz:9952",
"repo_name": "wcy123/voba_value",
"revision_date": "2015-05-03T09:28:43",
"revision_id": "658a22db2b9c497c0deefd6a45190c59236fb964",
"snapshot_id": "8dff51f6630f3296561738b7e5fe16d986de9784",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/wcy123/voba_value/658a22db2b9c497c0deefd6a45190c59236fb964/imp/closure.h",
"visit_date": "2021-01-23T06:44:37.822167"
} | stackv2 | #pragma once
/** @file
closure
=======
\verbatim
+---------------------------+-------+
| data | type1 |
+---------------------------+-------+
| . value (61 bits) | 011 |
+-|-------------------------+-------+
|
| +----------------+------------+
`----> | funcp(64bits) |
+----------------+------------+
| size(64bits) |
+-----------------------------+
| voba_value_t a1 |
+-----------------------------+
| .... |
+-----------------------------+
\endverbatim
A \a closure is a pointer which points to an array .
*/
/** @brief the class object associated with \a closure */
extern voba_value_t voba_cls_closure;
/** @brief return the `i` th captured variable.*/
INLINE voba_value_t voba_closure_at(voba_value_t c,uint32_t i);
/** @brief set `i` th captured variable.*/
INLINE voba_value_t voba_closure_set_at(voba_value_t c,uint32_t i,voba_value_t v);
/** @brief the closure function*/
INLINE voba_func_t voba_closure_func(voba_value_t c);
/** @brief the tuple of all captured variables
@todo this function is redundent, or ::voba_closure_at,
::voba_closure_len are redundent.
*/
INLINE voba_value_t voba_closure_tuple(voba_value_t c);
/** @brief the number of captured closure variables*/
INLINE uint64_t voba_closure_len(voba_value_t c);
#define VOBA_MACRO_ARG2(n) ,voba_value_t a##n
/** @brief create a closure
\a f function pointer
\a a0 captured argument 0
@return a closure object
it is a set of functions created by a complicated macro, as below
@code{.c}
voba_value_t voba_make_closure_0(voba_value_t f);
voba_value_t voba_make_closure_1(voba_value_t f, voba_value_t a0);
voba_value_t voba_make_closure_2(voba_value_t f, voba_value_t a0,voba_value_t a1);
//...
voba_value_t voba_make_closure_20(voba_value_t f, voba_value_t a0,voba_value_t a1, ..., voba_value_t a19);
@endcode
*/
#define DECLARE_VOBA_MAKE_CLOSURE_N(n) \
INLINE voba_value_t voba_make_closure_##n \
(voba_func_t f VOBA_FOR_EACH_N(n)(VOBA_MACRO_ARG2, SPACE))
VOBA_FOR_EACH(DECLARE_VOBA_MAKE_CLOSURE_N,SEMI_COMMA);
| 2.21875 | 2 |
2024-11-18T22:11:43.982959+00:00 | 2020-08-28T10:50:09 | 0250eaf945e87fcad857f7c01b809795794f9549 | {
"blob_id": "0250eaf945e87fcad857f7c01b809795794f9549",
"branch_name": "refs/heads/master",
"committer_date": "2020-08-28T10:50:09",
"content_id": "e2be82096e82a3478cd11ccd582e846dce0aa520",
"detected_licenses": [
"MIT"
],
"directory_id": "f8dea1a5dc461280d149b1accb4a9e46d9b7b0b9",
"extension": "h",
"filename": "stack.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 261624790,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1438,
"license": "MIT",
"license_type": "permissive",
"path": "/stack.h",
"provenance": "stackv2-0087.json.gz:10210",
"repo_name": "zhangxm99/stack-calculator",
"revision_date": "2020-08-28T10:50:09",
"revision_id": "bc2d8c42f81b081c02e8f7f248a83c1f95844e6f",
"snapshot_id": "71eb81f078e1261a21919eeaebe46f802ee71aa7",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/zhangxm99/stack-calculator/bc2d8c42f81b081c02e8f7f248a83c1f95844e6f/stack.h",
"visit_date": "2022-12-06T07:02:16.872597"
} | stackv2 | #include <stdlib.h>
#include <stdio.h>
typedef float ElementType;
typedef struct SNode
{
int identifier; //to identify the data type ,0 is int, 1 is char
union
{
ElementType num;
char ch;
} Data;
struct SNode *Next;
} SNode;
typedef SNode *Stack;
/* creat a head node and return the pointer */
Stack CreatStack()
{
Stack S = (Stack)malloc(sizeof(SNode));
S -> Next = NULL;
return S;
}
/* to konw if it`s an empty stack*/
int IsEmpty(Stack S)
{
return (S -> Next == NULL);
}
/* push an integer into a stack */
void Push_num(ElementType item,Stack *S)
{
Stack new = (Stack)malloc(sizeof(SNode));
new->Next = *S;
new->identifier = 0;
new->Data.num = item;
*S = new;
}
/* push an character into a stack */
void Push_char(char item,Stack *S)
{
Stack new = (Stack)malloc(sizeof(SNode));
new->Next = *S;
new->identifier = 1;
new->Data.ch = item;
*S = new;
}
/* identify the data type */
int Identify_ele(Stack S){
return S->identifier;
}
/* pop out a integer element */
ElementType Pop_num(Stack *S){
ElementType num = (*S)->Data.num;
Stack temp = *S;
*S = (*S)->Next;
free(temp);
return num;
}
/* pop out a character */
char Pop_ch(Stack *S){
char ch = (*S)->Data.ch;
Stack temp = (*S);
*S = (*S)->Next;
free(temp);
return ch;
}
/* look the character */
char Look(Stack S){
return S->Data.ch;
} | 3.609375 | 4 |
2024-11-18T22:11:44.126265+00:00 | 2013-09-03T01:20:29 | 56f4a128f53d888340ca6261c521de9633adb5a9 | {
"blob_id": "56f4a128f53d888340ca6261c521de9633adb5a9",
"branch_name": "refs/heads/master",
"committer_date": "2013-09-03T01:20:29",
"content_id": "cc0b7bf1385e70c5592d5b4f6a6dba7d9b16c631",
"detected_licenses": [
"MIT"
],
"directory_id": "a00783714f4141f6bddf684884398011bc3c8680",
"extension": "c",
"filename": "server.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 2052612,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 7368,
"license": "MIT",
"license_type": "permissive",
"path": "/server.c",
"provenance": "stackv2-0087.json.gz:10339",
"repo_name": "kristopolous/similarcolors",
"revision_date": "2013-09-03T01:20:29",
"revision_id": "3be70ed7e4220f923b12ccf8bafa6d7fefd6756a",
"snapshot_id": "d495b9dc1321fd7afb6f127e13ba9b3d7aaaa3c1",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/kristopolous/similarcolors/3be70ed7e4220f923b12ccf8bafa6d7fefd6756a/server.c",
"visit_date": "2021-01-20T22:28:47.340112"
} | stackv2 | /*
* server.c
*
* Finding similar colors (matching images)
*
* See https://github.com/kristopolous/similarcolors for the latest version
*/
#include "common.h"
char **g_buffer;
int g_size = 64,
g_sig = 0,
g_curpoint = 0;
size_t *g_sizes;
struct client {
char
active, // active?
todo; // what to do
char
req[LARGE],
*current,
*ptr,
*end; // if requests need to be concatenated together
int sz;
int fd;
};
int
g_serverfd,
g_which;
fd_set
g_rg_fds,
g_wg_fds,
g_eg_fds;
struct client
g_dbase[SMALL],
*g_forsig;
jmp_buf g_ret;
extern context_t g_lastcontext;
void done(struct client*cur) {
shutdown(cur->fd, SHUT_RDWR);
cur->active = FALSE;
cur->todo = 0;
cur->fd = 0;
cur->ptr = cur->req;
}
void handle_bp(int in) {
int ix;
for(ix = 0;ix < SMALL;ix++) {
if(in == g_dbase[ix].fd) {
g_dbase[ix].active = FALSE;
g_dbase[ix].todo = 0;
g_dbase[ix].fd = 0;
break;
}
}
g_sig = 1;
}
void doquit(){
for(g_which = 0;g_which < SMALL;g_which++) {
if(g_dbase[g_which].active == TRUE) {
done(&g_dbase[g_which]);
}
}
for(g_which = 0;g_which < g_size;g_which++) {
free(g_buffer[g_which]);
}
free(g_sizes);
free(g_buffer);
db_close();
exit(0);
}
// Associates new connection with a database entry
void newconnection(int c) {
socklen_t addrlen;
struct sockaddr addr;
struct client*cur;
int g_which;
getpeername(c, &addr, &addrlen);
for(g_which = 0;g_which < SMALL;g_which++) {
if(g_dbase[g_which].active == FALSE) {
break;
}
}
cur = &g_dbase[g_which];
cur->active = TRUE;
cur->fd = c;
cur->todo |= READCLIENT;
cur->ptr = cur->req;
fcntl(c, F_SETFL, O_NONBLOCK);
return;
}
void swrite(int fd, char*buf, int len){
int sz = 0,
new_sz;
while(sz < len && !g_sig) {
new_sz = write(fd, buf + sz, len - sz);
if(new_sz == -1) {
usleep(1000);
} else {
sz += new_sz;
}
}
g_sig = 0;
}
void reset(struct client*t){
t->end = t->ptr = t->req;
t->sz = 0;
}
void format(resSet*res, output*out, int len) {
int ix;
memset(out, 0, sizeof(output));
sprintf((char*)out, "[");
for(ix = 0; ix < (len - 1); ix++) {
// uncompress((*res)[ix].name, uncomp);
sprintf((char*)out + strlen((char*)out), "\"%s\",", (*res)[ix].name);
}
// uncompress((*res)[ix].name, uncomp);
sprintf((char*)out + strlen((char*)out), "\"%s\"]", (*res)[ix].name);
}
int sread(struct client*t) {
int sz = 0, new_sz;
do {
new_sz = recv(t->fd, t->req + sz, LARGE - sz, 0);
sz += new_sz;
} while(new_sz > 0 && sz > 0 && !g_sig);
g_sig = 0;
t->current = t->ptr = t->req;
return sz;
}
int clean(struct client*t) {
// go back the null values if the size is right
for(; (t->ptr[0] == 0 && t->sz > 0); t->ptr ++, t->sz --);
// assign the current command
t->current = t->ptr;
// chop off the end
for(;t->ptr[0] > ' ';t->ptr++);
t->ptr[0] = 0;
// cut the size back
t->sz -= (t->ptr - t->current);
return(t->sz > 0);
}
int parse(char*toparse, ctx*ret) {
char *ptr;
ptr = toparse + 1;
ret->name = ptr;
while(*ret->name && *ret->name != ':') {
ret->name++;
}
if(ret->name[0] == ':') {
ret->name[0] = 0;
ret->name++;
} else {
ret->name = ptr;
ptr = 0;
}
memset(ret->context, 0, sizeof(context_t));
if(ptr) {
strncpy(ret->context, ptr, sizeof(context_t));
}
return 1;
}
// Some things can be enqueued
void sendstuff() {
struct client*t;
ctx c;
for(g_which = 0;g_which < SMALL;g_which++) {
if(g_dbase[g_which].active == TRUE) {
t = &g_dbase[g_which];
// Reading from the client
if(FD_ISSET(t->fd, &g_rg_fds)) {
t->sz = sread(t);
if(t->sz == 0) {
done(t);
} else {
t->todo |= WRITECLIENT;
t->todo &= ~READCLIENT;
}
}
if(FD_ISSET(t->fd, &g_wg_fds) && t->req[0] != 0) {
while(clean(t)){
switch(t->current[0]) {
case 'q':
doquit();
break;
case '+':
parse(t->current, &c);
insert(c.context, c.name);
break;
case '?':
{
output out;
resSet rs;
int len;
memset(rs, 0, sizeof(resSet));
parse(t->current, &c);
if(search(c.context, c.name, &rs, &len)) {
format(&rs, &out, len);
swrite(t->fd, out, strlen(out));
} else {
printf("(db) [%s] Not found: %s\n", c.context, c.name);
}
}
break;
case 's':
printf("fuck off\n");
break;
}
}
t->todo &= ~WRITECLIENT;
t->todo |= READCLIENT;
}
if(FD_ISSET(t->fd, &g_eg_fds)) {
done(t);
}
}
}
}
void doselect() {
int
hi,
i;
struct client *c;
FD_ZERO(&g_rg_fds);
FD_ZERO(&g_eg_fds);
FD_ZERO(&g_wg_fds);
FD_SET(g_serverfd, &g_rg_fds);
hi = g_serverfd;
for(i = 0;i < SMALL;i++) {
if(g_dbase[i].active == TRUE) {
c = &g_dbase[i];
if(c->todo & READCLIENT) {
FD_SET(c->fd, &g_rg_fds);
}
if(c->todo & WRITECLIENT) {
FD_SET(c->fd, &g_wg_fds);
}
FD_SET(c->fd, &g_eg_fds);
hi = GETMAX( c->fd, hi);
}
}
select(hi + 1, &g_rg_fds, &g_wg_fds, &g_eg_fds, 0);
}
void handle(int signal) {
longjmp(g_ret, 0);
}
void start_server(int argc, char*argv[]){
socklen_t addrlen;
int
ret,
ix,
port = 0;
struct sockaddr addr;
struct sockaddr_in proxy, *ptr;
struct hostent *gethostbyaddr();
char *progname = argv[0];
signal(SIGPIPE, handle_bp);
FD_ZERO(&g_rg_fds);
FD_ZERO(&g_eg_fds);
FD_ZERO(&g_wg_fds);
signal(SIGSEGV, handle);
addr.sa_family = AF_INET;
strcpy(addr.sa_data, "somename");
memset(g_dbase, 0, sizeof(g_dbase));
while(argc > 0) {
if(ISA("-P", "--port")) {
if(--argc) {
port = htons(atoi(*++argv));
}
}
else if(ISA("-H", "--help")) {
printf("%s\n", progname);
printf("\t-P --port\tWhat part to run on\n");
exit(0);
}
argv++;
if(argc)argc--;
}
if(!port) {
port = htons(8765);
}
proxy.sin_family = AF_INET;
proxy.sin_port = port;
proxy.sin_addr.s_addr = INADDR_ANY;
g_serverfd = socket(PF_INET, SOCK_STREAM, 0);
while(bind(g_serverfd, (struct sockaddr*)&proxy, sizeof(proxy)) < 0) {
proxy.sin_port += htons(1);
}
addrlen = sizeof(addr);
ret = getsockname(g_serverfd, &addr, &addrlen);
ptr = (struct sockaddr_in*)&addr;
listen(g_serverfd, SMALL);
printf("%d,%d,%d\n", ntohs(proxy.sin_port), g_size, getpid());
fflush(0);
g_buffer = (char**)malloc(sizeof(char*) * g_size);
g_sizes = (size_t*)malloc(sizeof(size_t) * g_size);
for(ix = 0; ix < g_size; ix++) {
g_buffer[ix] = (char*)malloc(sizeof(char) * (MEDIUM + 2));
memset(g_buffer[ix], 0, MEDIUM + 2);
}
//ret = daemon(0,0);
// This is the main loop
for(;;) {
doselect();
if(FD_ISSET(g_serverfd, &g_rg_fds)) {
newconnection(accept(g_serverfd, 0, 0));
}
setjmp(g_ret);
sendstuff();
}
}
| 2.4375 | 2 |
2024-11-18T22:11:44.260150+00:00 | 2019-05-09T07:25:55 | 3a45f322b31e5f9efdedd12df21a315fd24e35b3 | {
"blob_id": "3a45f322b31e5f9efdedd12df21a315fd24e35b3",
"branch_name": "refs/heads/master",
"committer_date": "2019-05-09T07:25:55",
"content_id": "312f9cd1e1321bcb0c06cd691bfece2d01edae5c",
"detected_licenses": [
"MIT"
],
"directory_id": "a965a6b3e36b2bdb546784d4fa6d4ecb20cfcb63",
"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": 165200640,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2445,
"license": "MIT",
"license_type": "permissive",
"path": "/main.c",
"provenance": "stackv2-0087.json.gz:10467",
"repo_name": "yuyahagi/c-compiler",
"revision_date": "2019-05-09T07:25:55",
"revision_id": "5d8f6510cc5b2ba7cf1846282740fce9f1208d39",
"snapshot_id": "e552e7875903275b69b4f8b43b9c884b73c5a214",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/yuyahagi/c-compiler/5d8f6510cc5b2ba7cf1846282740fce9f1208d39/main.c",
"visit_date": "2020-04-16T02:34:02.994029"
} | stackv2 | #include <assert.h>
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include "cc.h"
char *read_file(char *path) {
FILE *pf = fopen(path, "r");
if (!pf) {
fprintf(stderr, "Could not open %s: %s\n", path, strerror(errno));
exit(1);
}
if (fseek(pf, 0, SEEK_END ) == -1) {
fprintf(stderr, "Could not seek to the end of %s: %s\n", path, strerror(errno));
exit(1);
}
size_t filesize = ftell(pf);
if (fseek(pf, 0, SEEK_SET) == -1) {
fprintf(stderr, "Could not seek to the beginning of %s: %s\n", path, strerror(errno));
exit(1);
}
char *buf = malloc(filesize + 1);
fread(buf, filesize, 1, pf);
buf[filesize] = '\0';
fclose(pf);
return buf;
}
int main(int argc, char **argv) {
#pragma GCC diagnostic ignored "-Wpointer-to-int-cast"
if (argc != 2) {
fprintf(stderr, "Invalid number of arguments.\n");
return 1;
}
// Test.
if (strcmp(argv[1], "-test") == 0) {
runtest_util();
runtest_type();
return 0;
}
char *src = read_file(argv[1]);
// Tokenize and parse to abstract syntax tree.
tokenize(src);
program();
printf(".intel_syntax noprefix\n");
printf(".global main\n");
// Global variables.
for (int i = 0; i < globalvars->keys->len; i++) {
char *name = (char *)globalvars->keys->data[i];
Node *var = (Node *)globalvars->vals->data[i];
Type *type = var->type;
size_t siz = get_typesize(type);
if (var->declinit) {
assert(var->declinit->ty == ND_NUM);
assert(var->declinit->type->ty == INT);
printf(".data\n");
printf(".global %s\n", name);
printf("%s:\n", name);
printf(" .long %d\n", var->declinit->val);
}
else {
printf(".bss\n");
printf(".global %s\n", name);
printf("%s:\n", name);
printf(" .zero %zu\n", siz);
}
}
// String literals.
printf(".section .rodata\n");
for (int i = 0; i < strings->keys->len; i++) {
printf(".LC%d:\n", (int)strings->vals->data[i]);
printf(" .string \"%s\"\n", (char *)strings->keys->data[i]);
}
printf(".text\n");
for (int i = 0; i < funcdefs->len; i++) {
Node *func = (Node *)funcdefs->data[i];
gen_function(func);
++func;
}
return 0;
}
| 2.5 | 2 |
2024-11-18T22:11:46.249570+00:00 | 2022-04-28T04:37:03 | cd6a0cf9ebbdff472ec95314726f2503a26ed7f2 | {
"blob_id": "cd6a0cf9ebbdff472ec95314726f2503a26ed7f2",
"branch_name": "refs/heads/master",
"committer_date": "2022-04-28T04:37:03",
"content_id": "54cf27ef5f9f83af0ff22d25b10f069608233373",
"detected_licenses": [
"MIT"
],
"directory_id": "cf59b40f883a2e369f173e869ec509dba7e0be6e",
"extension": "c",
"filename": "sock.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 108055741,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1677,
"license": "MIT",
"license_type": "permissive",
"path": "/src/sock.c",
"provenance": "stackv2-0087.json.gz:10725",
"repo_name": "nickolasburr/keuka",
"revision_date": "2022-04-28T04:37:03",
"revision_id": "ffa22774fe08b5e035600ddef3844346d7ca7c48",
"snapshot_id": "23c141e638984ae7f48fbcad48120b2a659183a2",
"src_encoding": "UTF-8",
"star_events_count": 6,
"url": "https://raw.githubusercontent.com/nickolasburr/keuka/ffa22774fe08b5e035600ddef3844346d7ca7c48/src/sock.c",
"visit_date": "2022-05-24T17:14:00.937407"
} | stackv2 | /**
* sock.c
*
* Copyright (C) 2017 Nickolas Burr <nickolasburr@gmail.com>
*/
#include "sock.h"
/**
* Create TCP socket.
*/
int mksock (char *url, BIO *bp) {
int sockfd, port, status;
char hostname[256] = "";
char port_num[6] = "443";
char protocol[6] = "";
char *tmp_ptr = NULL;
struct hostent *host;
struct sockaddr_in dest_addr;
/**
* Remove trailing slash, if applicable.
*/
if (url[strlen(url)] == '/') {
url[strlen(url)] = '\0';
}
/**
* Protocol type (e.g. https).
*/
strncpy(protocol, url, (strchr(url, ':') - url));
/**
* Hostname (e.g. www.example.com)
*/
strncpy(hostname, strstr(url, "://") + 3, sizeof(hostname));
/**
* Port (if applicable).
*/
if (strchr(hostname, ':')) {
tmp_ptr = strchr(hostname, ':');
strncpy(port_num, tmp_ptr + NULL_BYTE, sizeof(port_num));
*tmp_ptr = '\0';
}
port = atoi(port_num);
/**
* Verify the hostname is resolvable.
*/
if (is_null(gethostbyname(hostname))) {
return -1;
}
host = gethostbyname(hostname);
/**
* Set TCP socket.
*/
sockfd = socket(AF_INET, SOCK_STREAM, 0);
dest_addr.sin_family = AF_INET;
dest_addr.sin_port = htons(port);
dest_addr.sin_addr.s_addr = *(long*)(host->h_addr);
/**
* Initialize the rest of the struct.
*/
memset(&(dest_addr.sin_zero), '\0', 8);
tmp_ptr = inet_ntoa(dest_addr.sin_addr);
status = connect(
sockfd,
(struct sockaddr*) &dest_addr,
sizeof(struct sockaddr)
);
/**
* Return error if we're not able to connect.
*/
if (is_error(status, -1)) {
BIO_printf(
bp,
"Error: Cannot connect to host %s [%s] on port %d.\n",
hostname,
tmp_ptr,
port
);
return -1;
}
return sockfd;
}
| 2.96875 | 3 |
2024-11-18T22:11:46.678749+00:00 | 2016-05-01T07:35:32 | 26f9d1547d8d21f9fb2b9aeea104f0b1ec32dc04 | {
"blob_id": "26f9d1547d8d21f9fb2b9aeea104f0b1ec32dc04",
"branch_name": "refs/heads/master",
"committer_date": "2016-05-01T07:35:32",
"content_id": "2d13305a680b04dd5d1e0f616e90c7bd0240c5e1",
"detected_licenses": [
"BSD-4-Clause-UC"
],
"directory_id": "23483ef7551bf1661312396f2f7a5b6a614d7c3b",
"extension": "c",
"filename": "Fibonacci.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 56612182,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 501,
"license": "BSD-4-Clause-UC",
"license_type": "permissive",
"path": "/Working/lab/vmm/Lab1/kern/Fibonacci.c",
"provenance": "stackv2-0087.json.gz:10983",
"repo_name": "faranahmad/COL331-Project",
"revision_date": "2016-05-01T07:35:32",
"revision_id": "734cf8dde6dc3eab2029ef534e9703e033a4319b",
"snapshot_id": "18a0a8b116463831bfe6a05e15a65da1c05d3733",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/faranahmad/COL331-Project/734cf8dde6dc3eab2029ef534e9703e033a4319b/Working/lab/vmm/Lab1/kern/Fibonacci.c",
"visit_date": "2021-05-31T16:37:17.931509"
} | stackv2 | #include <kern/UserProg.h>
#include <inc/stdio.h>
#include <inc/string.h>
int User_Fibonacci(int argc, char** argv)
{
if(argc == 1)
{
cprintf("Enter arguements\n");
return 0;
}
char *ptr;
long ret = strtol(argv[1],&ptr,10);
int a = 1;
int b = 1;
int c = 0;
int i;
int count=(int)ret;
if(count==0 || count == 1)
{
cprintf("Fibonacci required: 1\n");
}
else
{
for(i=2;i<count+1;i++)
{
c = a+b;
b = a;
a = c;
}
cprintf("Fibonacci required: %d\n",c);
}
return 0;
} | 2.9375 | 3 |
2024-11-18T22:11:51.579545+00:00 | 2021-11-15T18:05:57 | 9253c612f5eaa0224bde25492e9372f6a9479196 | {
"blob_id": "9253c612f5eaa0224bde25492e9372f6a9479196",
"branch_name": "refs/heads/master",
"committer_date": "2021-11-15T18:05:57",
"content_id": "239d61c71736a01c603ad4378f2dbac55d396eb0",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "6ec0ec5c90d405cde9b871a88404f342ddb2afdc",
"extension": "c",
"filename": "parsec_control.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 153067992,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3372,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/runtime/parsec/control/parsec_control.c",
"provenance": "stackv2-0087.json.gz:11242",
"repo_name": "ecrc/al4san",
"revision_date": "2021-11-15T18:05:57",
"revision_id": "93bc603d2b6262439a659ef98908839f678f1c95",
"snapshot_id": "253300a9b0a0e4d435eb3daa56fe38b56807e01e",
"src_encoding": "UTF-8",
"star_events_count": 9,
"url": "https://raw.githubusercontent.com/ecrc/al4san/93bc603d2b6262439a659ef98908839f678f1c95/runtime/parsec/control/parsec_control.c",
"visit_date": "2021-12-03T15:09:07.820322"
} | stackv2 | /**
*
* @file runtime_control.c
*
* @copyright 2012-2017 The University of Tennessee and The University of
* Tennessee Research Foundation. All rights reserved.
* @copyright 2012-2017 Bordeaux INP, CNRS (LaBRI UMR 5800), Inria,
* Univ. Bordeaux. All rights reserved.
* @copyright 2018 King Abdullah University of Science and Technology (KAUST).
* All rights reserved.
*
***
* @brief AL4SAN PaRSEC control routines
*
* AL4SAN is a software package provided by King Abdullah University of Science and Technology (KAUST)
*
*
* @author Reazul Hoque
* @author Mathieu Faverge
* @date 2017-01-12
* @version 1.1.0
* @author Rabab Alomairy
* @date 2019-02-06
*/
#include <stdio.h>
#include <stdlib.h>
#include "al4san_parsec.h"
#if defined(AL4SAN_USE_MPI)
#include <mpi.h>
#endif
/**
* Initialize AL4SAN
*/
int AL4SAN_Parsec_init( AL4SAN_context_t *al4san,
int ncpus,
int ncudas,
int nthreads_per_worker )
{
int hres = -1, default_ncores = -1;
int *argc = (int *)malloc(sizeof(int));
*argc = 0;
/* Initializing parsec context */
if( 0 < ncpus ) {
default_ncores = ncpus;
}
al4san->parallel_enabled = AL4SAN_TRUE;
al4san->schedopt = (void *)parsec_init(default_ncores, argc, NULL);
if(NULL != al4san->schedopt) {
al4san->nworkers = ncpus;
al4san->nthreads_per_worker = nthreads_per_worker;
hres = 0;
}
free(argc);
(void)ncudas;
return hres;
}
/**
* Finalize AL4SAN
*/
void AL4SAN_Parsec_finalize( AL4SAN_context_t *al4san )
{
parsec_context_t *parsec = (parsec_context_t*)al4san->schedopt;
parsec_fini(&parsec);
return;
}
/**
* To suspend the processing of new tasks by workers
*/
void AL4SAN_Parsec_pause( AL4SAN_context_t *al4san )
{
(void)al4san;
return;
}
/**
* This is the symmetrical call to AL4SAN_Parsec_pause,
* used to resume the workers polling for new tasks.
*/
void AL4SAN_Parsec_resume( AL4SAN_context_t *al4san )
{
(void)al4san;
return;
}
/**
* Barrier AL4SAN.
*/
void AL4SAN_Parsec_barrier( AL4SAN_context_t *al4san )
{
parsec_context_t *parsec = (parsec_context_t*)(al4san->schedopt);
// This will be a problem with the fake tasks inserted to detect end of DTD algorithms
parsec_context_wait( parsec );
return;
}
/**
* Display a progress information when executing the tasks
*/
void AL4SAN_Parsec_progress( AL4SAN_context_t *al4san )
{
(void)al4san;
return;
}
/**
* Thread rank.
*/
int AL4SAN_Parsec_thread_rank( AL4SAN_context_t *al4san )
{
(void)al4san;
return 0;
}
/**
* Thread rank.
*/
int AL4SAN_Parsec_thread_size( AL4SAN_context_t *al4san )
{
// TODO: fixme
//return vpmap_get_nb_total_threads();
(void)al4san;
return 1;
}
/**
* This returns the rank of this process
*/
int AL4SAN_Parsec_comm_rank( AL4SAN_context_t *al4san )
{
int rank = 0;
#if defined(AL4SAN_USE_MPI)
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
#endif
(void)al4san;
return rank;
}
/**
* This returns the size of the distributed computation
*/
int AL4SAN_Parsec_comm_size( AL4SAN_context_t *al4san )
{
int size = 0;
#if defined(AL4SAN_USE_MPI)
MPI_Comm_size(MPI_COMM_WORLD, &size);
#endif
(void)al4san;
return size;
}
| 2.046875 | 2 |
2024-11-18T22:11:51.848428+00:00 | 2020-09-07T07:23:22 | 405c2fb13e03436b232f441ea4e66d31fac677b2 | {
"blob_id": "405c2fb13e03436b232f441ea4e66d31fac677b2",
"branch_name": "refs/heads/master",
"committer_date": "2020-09-07T07:23:22",
"content_id": "6db8de526bac027f8268da061e8ee4df1e2dc471",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "a3e75545d380c65cfad89669fcc514e6b30ffd4d",
"extension": "h",
"filename": "misc.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": 2050,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/components/av/include/avutil/misc.h",
"provenance": "stackv2-0087.json.gz:11499",
"repo_name": "PDFxy/YoC-open",
"revision_date": "2020-09-07T07:23:22",
"revision_id": "adb04959298d556bb17bfca1946ec5509d39c8e0",
"snapshot_id": "021e448ec7550a800531b07b85e326a399cfd2db",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/PDFxy/YoC-open/adb04959298d556bb17bfca1946ec5509d39c8e0/components/av/include/avutil/misc.h",
"visit_date": "2022-12-07T20:42:15.931619"
} | stackv2 | /*
* Copyright (C) 2018-2020 Alibaba Group Holding Limited
*/
#ifndef __MISC_H__
#define __MISC_H__
#include "avutil/common.h"
#include "avutil/av_typedef.h"
__BEGIN_DECLS__
#define bswap16(x) \
((((x) >> 8) & 0xff) | (((x) & 0xff) << 8))
#define bswap32(x) \
((((x) & 0xff000000) >> 24) | (((x) & 0x00ff0000) >> 8) | \
(((x) & 0x0000ff00) << 8) | (((x) & 0x000000ff) << 24))
static inline int is_file_url(const char *name)
{
return strncmp(name, "file://", 7) == 0;
}
static inline int is_http_url(const char *name)
{
return strncmp(name, "http://", 7) == 0;
}
static inline int is_mem_url(const char *name)
{
return strncmp(name, "mem://", 6) == 0;
}
static inline int is_named_chunkfifo_url(const char *name)
{
return strncmp(name, "chunkfifo://", 12) == 0;
}
static inline int is_url(const char *name)
{
return is_file_url(name) || is_http_url(name) || is_mem_url(name) || is_named_chunkfifo_url(name);
}
/**
* @brief get codec id by tag val
* @param [in] tags
* @param [in] tag
* @return
*/
avcodec_id_t get_codec_id(const avcodec_tag_t *tags, uint32_t tag);
/**
* @brief get codec name
* @param [in] codec id
* @return "unknown" on error
*/
const char* get_codec_name(avcodec_id_t id);
/**
* @brief convert hex string to bytes
* @param [in] strhex : hex string
* @param [in] bytes
* @param [in] ibytes : length of the bytes
* @return 0/-1
*/
int bytes_from_hex(const char *strhex, uint8_t *bytes, size_t ibytes);
/**
* @brief clip a signed integer value into the -32768,32767(short)
* @param [in] v
* @return
*/
int16_t clip_int16(int v);
/**
* @brief extend the val to sign int
* @param [in] val
* @param [in] bits: bits of the val
* @return
*/
int sign_extend(int val, unsigned bits);
/**
* @brief four byte to str
* @param [in] val
* @return not null
*/
char* four_2_str(uint32_t val);
/**
* @brief crc8(x8+x2+x+1)
* @param [in] data
* @param [in] len
* @return 0 if ok
*/
uint8_t av_crc8(uint8_t *data, size_t len);
__END_DECLS__
#endif /* __MISC_H__ */
| 2.15625 | 2 |
2024-11-18T22:11:51.993331+00:00 | 2017-07-30T13:52:32 | 6bf448cf9f5c4ed31217fb47658f7ef97ff5a8d1 | {
"blob_id": "6bf448cf9f5c4ed31217fb47658f7ef97ff5a8d1",
"branch_name": "refs/heads/master",
"committer_date": "2017-07-30T13:52:32",
"content_id": "d929d6eb63cc2cb61ed6da72a2544c6e73fb1fdd",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "7975dc9f1c3550719c0f8f841ef5c533091ebbe8",
"extension": "c",
"filename": "pinon.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 97235283,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 241,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/howto/pinon.c",
"provenance": "stackv2-0087.json.gz:11756",
"repo_name": "marc-despland/alarm",
"revision_date": "2017-07-30T13:52:32",
"revision_id": "06fa62a490b57e012402c2f3dfd9c4c54e624070",
"snapshot_id": "edb00a8b44c3905ddd0f10a475eb1b7ff1f0e140",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/marc-despland/alarm/06fa62a490b57e012402c2f3dfd9c4c54e624070/howto/pinon.c",
"visit_date": "2021-03-19T14:50:07.513833"
} | stackv2 | #include <stdio.h>
#include <wiringPi.h>
int main (void)
{
printf ("Raspberry Pi blink\n") ;
if (wiringPiSetup () == -1)
return 1 ;
pinMode (1, OUTPUT) ; // aka BCM_GPIO pin 17
digitalWrite(1,1);
return 0 ;
}
| 2.0625 | 2 |
2024-11-18T22:11:54.377930+00:00 | 2022-11-25T14:31:40 | 5fd37fac7ab21c79f0c3bd76ad1898a614d0df77 | {
"blob_id": "5fd37fac7ab21c79f0c3bd76ad1898a614d0df77",
"branch_name": "refs/heads/main",
"committer_date": "2022-11-25T14:31:40",
"content_id": "eeb77a51803f8f5ef781ca09187c70fdbfd04d73",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "c6bbd226758134f7057e381234b14ab0e5f19410",
"extension": "h",
"filename": "rcel.h",
"fork_events_count": 0,
"gha_created_at": "2020-06-16T04:28:36",
"gha_event_created_at": "2022-11-25T14:31:42",
"gha_language": "C",
"gha_license_id": "BSD-3-Clause",
"github_id": 272609398,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4032,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/src/pj/inc/rcel.h",
"provenance": "stackv2-0087.json.gz:11884",
"repo_name": "kattkieru/Animator-Pro",
"revision_date": "2022-11-25T14:31:40",
"revision_id": "5a7a58a3386a6430a59b64432d31dc556c56315b",
"snapshot_id": "441328d06cae6b7175b0260f4ea1c425b36625e9",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/kattkieru/Animator-Pro/5a7a58a3386a6430a59b64432d31dc556c56315b/src/pj/inc/rcel.h",
"visit_date": "2023-08-05T04:34:00.462730"
} | stackv2 | #ifndef RCEL_H
#define RCEL_H
#ifndef STDTYPES_H
#include "stdtypes.h"
#endif
#ifndef RECTANG_H
#include "rectang.h"
#endif
#ifndef RASTCALL_H
#include "rastcall.h"
#endif
struct cmap;
#include "wndobody.h"
/* a minimal drawing cel designed to be compatible with a window and
* raster and window screen but smaller
* and less complicated for use as a memory rendering area and image
* processing buffer. It is a raster with a few extra fields added
* that are common to a window and window screen.
* It would be a lot easier to maintain things if windows and cels
* and screens used pointers to rasters but in the interest of speed
* the raster and it's library are full fields. and common fields
* are maintained in common positions. In this way all the items
* can be used in with the raster library protocall and be processed
* with the same rendering routines */
#define CEL_FIELDS \
struct cmap *cmap
typedef struct rcel {
RASTHDR_FIELDS; /* the raster for raster library */
union {
Rastbody hw;
char pad[sizeof(struct wndobody)];
} u;
CEL_FIELDS;
} Rcel;
/* items found in gfxlib.lib on rex side */
void pj_rcel_close(Rcel *rc);
void pj_rcel_free(Rcel *c);
Errcode pj_rcel_bytemap_open(Rasthdr *spec,Rcel *cel,LONG num_colors);
Errcode pj_rcel_bytemap_alloc(Rasthdr *spec,Rcel **pcel,LONG num_colors);
/* do not use close_rcel() or free_rcel() on results of make_virtual_rcel()
* no cleanup necessary */
Boolean pj_rcel_make_virtual(Rcel *rc, Rcel *root, Rectangle *toclip);
#ifndef REXLIB_CODE /* host side only */
#ifndef VDEVICE_H
#include "vdevice.h"
#endif
Rcel *center_virtual_rcel(Rcel *root, Rcel *virt, int width, int height);
Errcode open_display_rcel(Vdevice *vd, Rcel *cel,
USHORT width, USHORT height, SHORT mode);
Errcode alloc_display_rcel(Vdevice *vd, Rcel **pcel,
USHORT width, USHORT height, SHORT mode);
Errcode open_vd_rcel(Vdevice *vd, Rasthdr *spec, Rcel *cel,
LONG num_colors, UBYTE displayable);
Errcode alloc_vd_rcel(Vdevice *vd, Rasthdr *spec, Rcel **pcel,
LONG num_colors, UBYTE displayable);
/* REXLIB_CODE */ #endif
#ifdef PRIVATE_CODE
/****** rcel stuff in pj but not in graphics lib *******/
#ifndef PROCBLIT_H
#include "procblit.h"
#endif
Errcode valloc_bytemap(Raster **r, SHORT w, SHORT h);
Boolean need_fit_cel(Rcel *c);
void cfit_rcel(Rcel *c, struct cmap *dcmap);
void refit_rcel(Rcel *c, struct cmap *ncmap, struct cmap *ocmap);
Rcel *clone_rcel(Rcel *s);
Rcel *clone_any_rcel(Rcel *in);
void pj_rcel_copy(Rcel *s, Rcel *d);
Errcode valloc_ramcel(Rcel **pcel,SHORT w,USHORT h);
Errcode valloc_anycel(Rcel **pcel,SHORT w,USHORT h);
void set_one_val(Rcel *rc, UBYTE clearc, UBYTE destc);
void show_cel_a_sec(Rcel *cel);
Errcode move_rcel(Rcel *rc, Boolean fit_cel, Boolean one_color);
void zoom_cel(Rcel *c);
Errcode clip_celrect(Rcel *src, Rectangle *rect, Rcel **clip);
typedef void (*Celblit)
(Rcel *rcel, SHORT x, SHORT y, Rcel *d, SHORT dx, SHORT dy,
SHORT w, SHORT h, Tcolxldat *txd);
/* returns blit for current settings */
extern Celblit get_celblit(Boolean cfit);
/* returns "move" blit for settings */
extern Celblit get_celmove(Boolean cfit);
/* returns line processor */
extern Procline get_celprocline(Boolean cfit);
/* structure and functions for temporarily saving an rcel */
typedef struct rcel_save
{
enum {SSC_NONE = 0,SSC_CEL,SSC_FILE} where;
Rcel *saved_cel;
char saved_fname[16];
} Rcel_save;
/* save cel and record where in rcel_save structure */
Errcode temp_save_rcel(Rcel_save *sc, Rcel *cel);
/* same as above, report error */
Errcode report_temp_save_rcel(Rcel_save *sc, Rcel *cel);
/* restore cel from rcel_save structure */
Errcode temp_restore_rcel(Rcel_save *sc, Rcel *cel);
/* same as above, report error */
Errcode report_temp_restore_rcel(Rcel_save *sc, Rcel *cel);
/* PRIVATE_CODE */ #endif
#endif /* RCEL_H */
| 2.0625 | 2 |
2024-11-18T22:11:54.836127+00:00 | 2021-06-03T11:54:47 | 856341dcdc40cd64734503eb87e6aa35eeeb4734 | {
"blob_id": "856341dcdc40cd64734503eb87e6aa35eeeb4734",
"branch_name": "refs/heads/main",
"committer_date": "2021-06-03T11:54:47",
"content_id": "9158e62b0e9580cb79cb10cd896fd6e90dc578d5",
"detected_licenses": [
"MIT"
],
"directory_id": "f2af2c1812865e7e0d240c70cedd8fc7927957d0",
"extension": "c",
"filename": "read_seed.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 373489915,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 521,
"license": "MIT",
"license_type": "permissive",
"path": "/Project 2/Question1/read_seed.c",
"provenance": "stackv2-0087.json.gz:12400",
"repo_name": "imartinovic-dzaja/CS-3013-Projects",
"revision_date": "2021-06-03T11:54:47",
"revision_id": "73674546ad30f5d05a45faa6ddb6652eceb1bd27",
"snapshot_id": "b35e71d44c6e57f3b56b8428d36016da925fc773",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/imartinovic-dzaja/CS-3013-Projects/73674546ad30f5d05a45faa6ddb6652eceb1bd27/Project 2/Question1/read_seed.c",
"visit_date": "2023-05-07T11:48:43.418143"
} | stackv2 | #include <stdlib.h>
#include <stdio.h>
void read_seed(char* filepath, int* seed) {
FILE* fp;
if ((fp = fopen(filepath, "r")) == NULL) {
printf("Couldn't open file: %s\n", filepath);
exit(1);
}
int maxNumDigits = 20;
char stringNumber[maxNumDigits];
if (fgets(stringNumber, maxNumDigits, fp) == NULL) {
printf("Couldn't read line from file: %s\n", filepath);
exit(1);
}
*seed = atoi(stringNumber);
printf("Seed is: %s\n", stringNumber);
return;
}
| 3 | 3 |
2024-11-18T22:11:58.033490+00:00 | 2023-08-17T13:00:20 | 571a4867e1a7624165c9212b0d93fdb7231f627f | {
"blob_id": "571a4867e1a7624165c9212b0d93fdb7231f627f",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-31T07:43:37",
"content_id": "cd8284d6968ff5db4e844e97dfd660e7d4b29b6e",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "c9bc99866cfab223c777cfb741083be3e9439d81",
"extension": "c",
"filename": "mod_rcar_pd_sysc.c",
"fork_events_count": 165,
"gha_created_at": "2018-05-22T10:35:56",
"gha_event_created_at": "2023-09-13T14:27:10",
"gha_language": "C",
"gha_license_id": "NOASSERTION",
"github_id": 134399880,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 6637,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/product/rcar/module/rcar_pd_sysc/src/mod_rcar_pd_sysc.c",
"provenance": "stackv2-0087.json.gz:12657",
"repo_name": "ARM-software/SCP-firmware",
"revision_date": "2023-08-17T13:00:20",
"revision_id": "f6bcca436768359ffeadd84d65e8ea0c3efc7ef1",
"snapshot_id": "4738ca86ce42d82588ddafc2226a1f353ff2c797",
"src_encoding": "UTF-8",
"star_events_count": 211,
"url": "https://raw.githubusercontent.com/ARM-software/SCP-firmware/f6bcca436768359ffeadd84d65e8ea0c3efc7ef1/product/rcar/module/rcar_pd_sysc/src/mod_rcar_pd_sysc.c",
"visit_date": "2023-09-01T16:13:36.962036"
} | stackv2 | /*
* Renesas SCP/MCP Software
* Copyright (c) 2020-2021, Renesas Electronics Corporation. All rights
* reserved.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#include <rcar_pd_sysc.h>
#include <mod_rcar_pd_sysc.h>
#include <mod_system_power.h>
#include <mod_rcar_system.h>
#include <fwk_assert.h>
#include <fwk_id.h>
#include <fwk_log.h>
#include <fwk_macros.h>
#include <fwk_mm.h>
#include <fwk_module.h>
#include <fwk_module_idx.h>
#include <stdint.h>
/*
* Internal variables
*/
static struct rcar_sysc_ctx rcar_sysc_ctx;
/*
* Power domain driver interface
*/
static int pd_set_state(fwk_id_t pd_id, unsigned int state)
{
struct rcar_sysc_pd_ctx *pd_ctx;
int ret = FWK_SUCCESS;
pd_ctx = rcar_sysc_ctx.pd_ctx_table + fwk_id_get_element_idx(pd_id);
if (pd_ctx->config->always_on)
return FWK_E_SUPPORT;
switch (state) {
case MOD_PD_STATE_ON:
ret = rcar_sysc_power(pd_ctx, true);
pd_ctx->pd_driver_input_api->report_power_state_transition(
pd_ctx->bound_id, MOD_PD_STATE_ON);
break;
case MOD_PD_STATE_OFF:
ret = rcar_sysc_power(pd_ctx, false);
pd_ctx->pd_driver_input_api->report_power_state_transition(
pd_ctx->bound_id, MOD_PD_STATE_OFF);
break;
default:
FWK_LOG_ERR("[PD] Requested power state (%i) is not supported.", state);
return FWK_E_PARAM;
}
return ret;
}
static int pd_get_state(fwk_id_t pd_id, unsigned int *state)
{
struct rcar_sysc_pd_ctx *pd_ctx;
pd_ctx = rcar_sysc_ctx.pd_ctx_table + fwk_id_get_element_idx(pd_id);
rcar_sysc_power_get(pd_ctx, state);
return FWK_SUCCESS;
}
static int pd_reset(fwk_id_t pd_id)
{
return FWK_SUCCESS;
}
static int pd_sys_resume(void)
{
unsigned int pd_idx;
struct rcar_sysc_pd_ctx *pd_ctx;
fwk_id_t pd_id;
for (pd_idx = 0; pd_idx < rcar_sysc_ctx.pd_sysc_count; pd_idx++) {
pd_id = FWK_ID_ELEMENT(FWK_MODULE_IDX_RCAR_PD_SYSC, pd_idx);
pd_ctx = rcar_sysc_ctx.pd_ctx_table + fwk_id_get_element_idx(pd_id);
switch (pd_ctx->config->pd_type) {
case RCAR_PD_TYPE_DEVICE:
case RCAR_PD_TYPE_DEVICE_DEBUG:
case RCAR_PD_TYPE_SYSTEM:
if (pd_ctx->config->always_on)
rcar_sysc_power(pd_ctx, MOD_PD_STATE_ON);
break;
default:
break;
}
}
return FWK_SUCCESS;
}
static const struct mod_pd_driver_api pd_driver = {
.set_state = pd_set_state,
.get_state = pd_get_state,
.reset = pd_reset,
};
static const struct mod_rcar_system_drv_api api_system = {
.resume = pd_sys_resume,
};
/*
* Framework handlers
*/
static int rcar_sysc_mod_init(
fwk_id_t module_id,
unsigned int pd_count,
const void *unused)
{
rcar_sysc_ctx.pd_ctx_table =
fwk_mm_calloc(pd_count, sizeof(struct rcar_sysc_pd_ctx));
if (rcar_sysc_ctx.pd_ctx_table == NULL)
return FWK_E_NOMEM;
rcar_sysc_ctx.pd_sysc_count = pd_count;
return FWK_SUCCESS;
}
static int rcar_sysc_pd_init(
fwk_id_t pd_id,
unsigned int unused,
const void *data)
{
const struct mod_rcar_pd_sysc_config *config = data;
struct rcar_sysc_pd_ctx *pd_ctx;
if (config->pd_type >= RCAR_PD_TYPE_COUNT)
return FWK_E_DATA;
pd_ctx = rcar_sysc_ctx.pd_ctx_table + fwk_id_get_element_idx(pd_id);
pd_ctx->config = config;
pd_ctx->bound_id = FWK_ID_NONE;
switch (config->pd_type) {
case RCAR_PD_TYPE_DEVICE:
case RCAR_PD_TYPE_DEVICE_DEBUG:
case RCAR_PD_TYPE_SYSTEM:
if (config->always_on)
rcar_sysc_power(pd_ctx, true);
return FWK_SUCCESS;
case RCAR_PD_TYPE_ALWAYS_ON:
pd_ctx->current_state = MOD_PD_STATE_ON;
return FWK_SUCCESS;
default:
return FWK_E_SUPPORT;
}
}
static int rcar_sysc_bind(fwk_id_t id, unsigned int round)
{
struct rcar_sysc_pd_ctx *pd_ctx;
/* Nothing to do during the first round of calls where the power module
will bind to the power domains of this module. */
if ((round == 0) || fwk_id_is_type(id, FWK_ID_TYPE_MODULE))
return FWK_SUCCESS;
#if 0
/* In the case of the module, bind to the log component */
if (fwk_module_is_valid_module_id(id)) {
return fwk_module_bind(FWK_ID_MODULE(FWK_MODULE_IDX_LOG),
FWK_ID_API(FWK_MODULE_IDX_LOG, 0),
&rcar_sysc_ctx.log_api);
}
#endif
pd_ctx = rcar_sysc_ctx.pd_ctx_table + fwk_id_get_element_idx(id);
if (fwk_id_is_equal(pd_ctx->bound_id, FWK_ID_NONE))
return FWK_SUCCESS;
switch (fwk_id_get_module_idx(pd_ctx->bound_id)) {
case FWK_MODULE_IDX_POWER_DOMAIN:
return fwk_module_bind(
pd_ctx->bound_id,
mod_pd_api_id_driver_input,
&pd_ctx->pd_driver_input_api);
break;
case FWK_MODULE_IDX_SYSTEM_POWER:
return fwk_module_bind(
pd_ctx->bound_id,
mod_system_power_api_id_pd_driver_input,
&pd_ctx->pd_driver_input_api);
break;
default:
assert(false);
return FWK_E_SUPPORT;
}
}
static int rcar_sysc_process_bind_request(
fwk_id_t source_id,
fwk_id_t target_id,
fwk_id_t api_id,
const void **api)
{
struct rcar_sysc_pd_ctx *pd_ctx;
pd_ctx = rcar_sysc_ctx.pd_ctx_table + fwk_id_get_element_idx(target_id);
if (fwk_id_get_api_idx(api_id) == MOD_RCAR_PD_SYSC_API_TYPE_SYSTEM) {
*api = &api_system;
} else {
switch (pd_ctx->config->pd_type) {
case RCAR_PD_TYPE_SYSTEM:
case RCAR_PD_TYPE_DEVICE:
case RCAR_PD_TYPE_DEVICE_DEBUG:
case RCAR_PD_TYPE_ALWAYS_ON:
if (fwk_id_get_module_idx(source_id) ==
FWK_MODULE_IDX_POWER_DOMAIN) {
pd_ctx->bound_id = source_id;
*api = &pd_driver;
break;
}
if (fwk_id_get_module_idx(source_id) ==
FWK_MODULE_IDX_SYSTEM_POWER) {
*api = &pd_driver;
break;
}
assert(false);
return FWK_E_ACCESS;
default:
(void)pd_driver;
return FWK_E_SUPPORT;
}
}
return FWK_SUCCESS;
}
const struct fwk_module module_rcar_pd_sysc = {
.type = FWK_MODULE_TYPE_DRIVER,
.api_count = MOD_RCAR_PD_SYSC_API_COUNT,
.init = rcar_sysc_mod_init,
.element_init = rcar_sysc_pd_init,
.bind = rcar_sysc_bind,
.process_bind_request = rcar_sysc_process_bind_request,
};
| 2.171875 | 2 |
2024-11-18T22:11:58.884529+00:00 | 2020-02-01T18:05:59 | 3b9869a0285332c7f7422ce98f3fd61a39440168 | {
"blob_id": "3b9869a0285332c7f7422ce98f3fd61a39440168",
"branch_name": "refs/heads/master",
"committer_date": "2020-02-01T18:05:59",
"content_id": "d1a86c3d4985d36edeb94cc3c23c3ad4697fb803",
"detected_licenses": [
"MIT"
],
"directory_id": "5c4eeaf7098b90988f28f05e959082f10a2dd653",
"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": 143044512,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3994,
"license": "MIT",
"license_type": "permissive",
"path": "/src/babysteps/serial/serial.cydsn/main.c",
"provenance": "stackv2-0087.json.gz:12786",
"repo_name": "holla2040/hyatt",
"revision_date": "2020-02-01T18:05:59",
"revision_id": "b597b8aa38673bc88ec2e697c58381c0937d6c96",
"snapshot_id": "05b21f9687770966980781d30ef0a1c51fe6b2ca",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/holla2040/hyatt/b597b8aa38673bc88ec2e697c58381c0937d6c96/src/babysteps/serial/serial.cydsn/main.c",
"visit_date": "2020-03-24T21:40:33.238800"
} | stackv2 | /* This project duplicates works from
Barton Dring's Grbl_USB_Native project
https://github.com/bdring/Grbl_USB_Native */
/* also uartDisplay is connected to a nextion display
which has its own protocol, for example x.txt="111.222"\xFF\xFF\xFF
sets the nextion text field named 'x'. widgets 'y','m' and 'u' also
exists. Load the nextion display with psocSerialTest.HMI */
#include <stdio.h>
#include "project.h"
#define USBFS_DEVICE (0u)
#define USBUART_BUFFER_SIZE (64u)
#define LINE_STR_LENGTH (20u)
uint8 buffer[USBUART_BUFFER_SIZE]; // bytes received
void displayProcess(char c);
void usb_uart_write(uint8_t c) {
uint16 ctr = 0;
if (uartUsb_GetConfiguration() == 1) {
while (uartUsb_CDCIsReady() == 0u) {
ctr++; if (ctr > 400)
return; // prevent getting stuck
}
uartUsb_PutChar(c);
}
}
/*
void broadcast(uint8_t c) {
usb_uart_write(c);
uartWifi_PutChar(c);
uartKitprog_PutChar(c);
uartDisplay_PutChar(c);
}
*/
void usb_uart_check(){
uint16 count; // number of bytes received
if (uartUsb_IsConfigurationChanged() != 0u) {
/* Initialize IN endpoints when device is configured. */
if (uartUsb_GetConfiguration() != 0u) {
/* Enumeration is done, enable OUT endpoint to receive data
* from host. */
uartUsb_CDC_Init();
}
}
/* Service USB CDC when device is configured. */
if (uartUsb_GetConfiguration() != 0u) {
/* Check for input data from host. */
if (uartUsb_DataIsReady() != 0u) {
/* Read received data and re-enable OUT endpoint. */
count = uartUsb_GetAll(buffer);
if (count != 0u) {
for (int i = 0; i < count; i++) {
uartWifi_PutChar(buffer[i]);
uartKitprog_PutChar(buffer[i]);
displayProcess(buffer[i]);
}
}
}
}
}
void usb_uart_PutString(const char *s) {
uint16 ctr = 0;
if (uartUsb_GetConfiguration() == 1) {
while (uartUsb_CDCIsReady() == 0u) {
ctr++; if (ctr > 400)
return; // prevent getting stuck
}
uartUsb_PutString(s);
}
}
char displayBuffer[50];
void displayProcess(char c) {
if (c == '\r') {
uartDisplay_PutString(displayBuffer);
uartDisplay_PutString("\xff\xff\xff");
strcpy(displayBuffer,"");
} else {
char tmpstr[2];
tmpstr[0] = c;
tmpstr[1] = 0;
strcat(displayBuffer,tmpstr);
}
if (strlen(displayBuffer) > 48) {
strcpy(displayBuffer,"");
}
}
#if defined (__GNUC__)
/* Add an explicit reference to the floating point printf library */
/* to allow usage of the floating point conversion specifiers. */
/* This is not linked in by default with the newlib-nano library. */
asm (".global _printf_float");
#endif
int main(void) {
CyGlobalIntEnable;
uint8_t c;
uartUsb_Start(USBFS_DEVICE, uartUsb_5V_OPERATION);
uartKitprog_Start();
uartDisplay_Start();
uartWifi_Start();
strcpy(displayBuffer,"");
for(;;) {
usb_uart_check();
if ((c = uartKitprog_GetChar()) != 0) {
usb_uart_write(c);
uartWifi_PutChar(c);
displayProcess(c);
}
if ((c = uartDisplay_GetChar()) != 0) {
if ((c > 31 && c < 127) || c == '\r' || c == '\n') {
uartWifi_PutChar(c);
uartKitprog_PutChar(c);
usb_uart_write(c);
}
}
if ((c = uartWifi_GetChar()) != 0) {
uartKitprog_PutChar(c);
displayProcess(c);
usb_uart_write(c);
}
}
}
| 2.5 | 2 |
2024-11-18T22:11:59.084717+00:00 | 2021-10-18T02:29:27 | 215e1f04ce81b65ed2c0179274cdcee85f2c25de | {
"blob_id": "215e1f04ce81b65ed2c0179274cdcee85f2c25de",
"branch_name": "refs/heads/main",
"committer_date": "2021-10-18T02:29:27",
"content_id": "172a866f3c0402e0902779022781834161a1c828",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "594e668834154d33066c190415bb142b2d261471",
"extension": "h",
"filename": "simple_dataframe.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": 1283,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/kubot_duo_box/include/kubot_duo_box/simple_dataframe.h",
"provenance": "stackv2-0087.json.gz:13043",
"repo_name": "SYY-Robot/kubot_duo_box",
"revision_date": "2021-10-18T02:29:27",
"revision_id": "238670e953cc915ae190c8f92af9128cc1deed33",
"snapshot_id": "23e6ea38336f39bf0bb862c2a76da46f8a167de8",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/SYY-Robot/kubot_duo_box/238670e953cc915ae190c8f92af9128cc1deed33/kubot_duo_box/include/kubot_duo_box/simple_dataframe.h",
"visit_date": "2023-08-31T23:02:59.819153"
} | stackv2 | #ifndef KUBOT_SIMPLE_DATAFRAME_H_
#define KUBOT_SIMPLE_DATAFRAME_H_
#include "dataframe.h"
#include <string.h>
static const unsigned short MESSAGE_BUFFER_SIZE = 255;
#define FIX_HEAD 0x5A
struct Head
{
unsigned char flag; // 標頭, 固定 0X5A
unsigned char msg_id; // 消息ID, 表示消息具體作用,决定消息體格式
unsigned char length; // 消息體長度
};
struct Message
{
struct Head head;
unsigned char data[MESSAGE_BUFFER_SIZE];
unsigned char check;
unsigned char recv_count; //已經接收的字節數
Message() {}
Message(unsigned char msg_id, unsigned char *data = 0, unsigned char len = 0)
{
head.flag = FIX_HEAD;
head.msg_id = msg_id;
head.length = recv_count = len;
check = 0;
if (data != 0 && len != 0)
memcpy(this->data, data, len);
unsigned char *_send_buffer = (unsigned char *)this;
unsigned int i = 0;
for (i = 0; i < sizeof(head) + head.length; i++)
check += _send_buffer[i];
_send_buffer[sizeof(head) + head.length] = check;
}
};
enum RECEIVE_STATE
{
STATE_RECV_FIX = 0,
STATE_RECV_ID,
STATE_RECV_LEN,
STATE_RECV_DATA,
STATE_RECV_CHECK
};
#endif /* KUBOT_SIMPLE_DATAFRAME_H_ */ | 2.4375 | 2 |
2024-11-18T22:11:59.288664+00:00 | 2017-05-29T08:04:18 | 6b166cf6b644487b22e9c283baeac001e2ac5bee | {
"blob_id": "6b166cf6b644487b22e9c283baeac001e2ac5bee",
"branch_name": "refs/heads/master",
"committer_date": "2017-05-29T08:04:18",
"content_id": "ac7d10f409a6d0604f233e226fd26db3b0c92016",
"detected_licenses": [
"MIT"
],
"directory_id": "bef40c6b8f745e74197fa272d9505bc1006c02ff",
"extension": "c",
"filename": "binarySearch.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 86843503,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1253,
"license": "MIT",
"license_type": "permissive",
"path": "/2nd Class/BBM204_Software_Lab_2/algorithm_examples_in_c/binarySearch.c",
"provenance": "stackv2-0087.json.gz:13303",
"repo_name": "kursataktas/Hacettepe-Computer-Science-Assignments",
"revision_date": "2017-05-29T08:04:18",
"revision_id": "243ba93cf2c14989d1fc346cf1ec8dfea53961ba",
"snapshot_id": "087bfc49398e17e2f34b6a5a393afcd5c5f46bbb",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/kursataktas/Hacettepe-Computer-Science-Assignments/243ba93cf2c14989d1fc346cf1ec8dfea53961ba/2nd Class/BBM204_Software_Lab_2/algorithm_examples_in_c/binarySearch.c",
"visit_date": "2021-01-18T18:05:57.165207"
} | stackv2 |
void generateBinarySearch ( int left, int right );
float getTimeForBinarySearch( int arr[], int left, int right );
void fillArray( int arr[], int arrSize );
int binarySearch( int arr[], int left, int right, int value );
void generateBinarySearch ( int left, int right ) {
int arr[maxArrSize], value;
float time;
time = getTimeForBinarySearch(arr, left, right);
printf("%-10.4f", time);
}
float getTimeForBinarySearch( int arr[], int left, int right ) {
int result, i, value;
float total = 0.0;
clock_t start, stop;
for(i = 0; i < repeatTime; i++) {
value = rand();
fillArray(arr, right);
quickSort(arr, left, right);
start = clock();
result = binarySearch(arr, left, right, value);
stop = clock();
total += (float)(1000*(stop-start)/CLOCKS_PER_SEC);
}
total = (float) total / repeatTime;
return total;
}
int binarySearch( int arr[], int left, int right, int value ) {
int mid = 0;
while(left <= right) {
mid = floor((right - left) / 2) + left;
if(arr[mid] == value)
return mid;
if(value < arr[mid])
right = mid - 1;
else
left = mid + 1;
}
return FALSE;
}
| 2.921875 | 3 |
2024-11-18T22:11:59.655625+00:00 | 2021-10-22T12:35:10 | c8eb96259f762aae4de838bc124ef535b5ed9458 | {
"blob_id": "c8eb96259f762aae4de838bc124ef535b5ed9458",
"branch_name": "refs/heads/master",
"committer_date": "2021-10-22T12:35:10",
"content_id": "ac3587372d9ebfd28d7b20240fbc0241e49ba9f1",
"detected_licenses": [
"MIT"
],
"directory_id": "d7a2c64d16a1b46f03d94657a41f75f8654e7f7d",
"extension": "c",
"filename": "gui.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": 15610,
"license": "MIT",
"license_type": "permissive",
"path": "/gui.c",
"provenance": "stackv2-0087.json.gz:13690",
"repo_name": "CruiseCai/multi-sdr-gps-sim",
"revision_date": "2021-10-22T12:35:10",
"revision_id": "ec05d555e659fb6abba5465a3059a74ef9f90d75",
"snapshot_id": "7c39ec617a8069ed42e2e11ffb26fa6075ee1284",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/CruiseCai/multi-sdr-gps-sim/ec05d555e659fb6abba5465a3059a74ef9f90d75/gui.c",
"visit_date": "2023-09-02T03:20:03.262255"
} | stackv2 | /**
* multi-sdr-gps-sim generates a IQ data stream on-the-fly to simulate a
* GPS L1 baseband signal using a SDR platform like HackRF or ADLAM-Pluto.
*
* This file is part of the Github project at
* https://github.com/mictronics/multi-sdr-gps-sim.git
*
* Copyright © 2021 Mictronics
* Distributed under the MIT License.
*
*/
#include <stdio.h>
#include <termios.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <pthread.h>
#include <ncurses.h>
#include <panel.h>
#include <form.h>
#include "gps-sim.h"
#include "gps.h"
#include "gui.h"
static const int info_width = 50;
static const int info_height = 13;
static const int help_width = 50;
static const int help_height = 13;
static int max_x = 0;
static int max_y = 0;
static WINDOW *window[13] = {NULL};
static PANEL *panel[13] = {NULL};
static pthread_mutex_t gui_lock; // Mutex to lock access during GUI updates
static void gui_update() {
update_panels();
doupdate();
}
static void show_footer(WINDOW *win) {
wattron(win, COLOR_PAIR(2));
mvwprintw(win, max_y - STATUS_HEIGHT - 2, 10, "TAB or F1-F3 switch displays, 'x' Exit, 'i' Info, 'h' Help");
wattroff(win, COLOR_PAIR(2));
}
/* Show the window with a border and a label */
static void show_window(WINDOW *win, char *label) {
int startx, half_width, str_leng;
half_width = max_x / 2;
str_leng = (int) strlen(label);
startx = half_width - (str_leng / 2);
box(win, 0, 0);
// Header separator
mvwaddch(win, 2, 0, ACS_LTEE);
mvwhline(win, 2, 1, ACS_HLINE, max_x - 2);
mvwaddch(win, 2, max_x - 1, ACS_RTEE);
// Status separator
mvwaddch(win, max_y - STATUS_HEIGHT - 2, 0, ACS_LTEE);
mvwhline(win, max_y - STATUS_HEIGHT - 2, 1, ACS_HLINE, max_x - 2);
mvwaddch(win, max_y - STATUS_HEIGHT - 2, max_x - 1, ACS_RTEE);
// Header label
wattron(win, COLOR_PAIR(1));
mvwprintw(win, 1, startx, "%s", label);
wattroff(win, COLOR_PAIR(1));
show_footer(win);
doupdate();
}
//print the header info for LS fix result display
static void ls_show_header(void) {
wattron(window[LS_FIX], COLOR_PAIR(2));
mvwprintw(window[LS_FIX], 3, 1, "PRN AZ ELEV PRange dIon");
wattroff(window[LS_FIX], COLOR_PAIR(2));
wrefresh(window[TOP]);
}
static void show_heading(float degree) {
int bias;
int zero_y = 0; //coordinates of zero
int zero_x = 9;
//draw window outline
wborder(window[HEADING], '.', '.', '.', '.', '.', '.', '.', '.');
mvwaddch(window[HEADING], 0, 9, ACS_UARROW);
mvwprintw(window[HEADING], 1, 9, "0");
mvwprintw(window[HEADING], 6, 0, "<270");
mvwprintw(window[HEADING], 6, 16, "90>");
mvwprintw(window[HEADING], 11, 8, "180");
mvwaddch(window[HEADING], 12, 9, ACS_DARROW);
//wattron(window[HEADING],COLOR_PAIR(5)|A_BOLD);
mvwaddch(window[HEADING], 6, 9, ACS_DIAMOND);
//wattroff(window[HEADING],COLOR_PAIR(5)|A_BOLD);
//show window title
wattron(window[HEADING], COLOR_PAIR(11) | A_BOLD);
mvwprintw(window[HEADING], 4, 6, "DIRECTION");
wattroff(window[HEADING], COLOR_PAIR(11) | A_BOLD);
wattron(window[HEADING], COLOR_PAIR(13) | A_BOLD);
mvwprintw(window[HEADING], 8, 6, "%6.1f", degree);
wattroff(window[HEADING], COLOR_PAIR(13) | A_BOLD);
//calculate coordinates
bias = (int) (degree / 6);
//data is at top line,0~60
if ((bias >= 0) && (bias <= 9)) {
wattron(window[HEADING], COLOR_PAIR(12) | A_BOLD);
mvwaddch(window[HEADING], 0, 9 + bias, ACS_DIAMOND);
wattroff(window[HEADING], COLOR_PAIR(12) | A_BOLD);
}
//data is at right line 60~126
if ((bias >= 10) && (bias <= 20)) {
wattron(window[HEADING], COLOR_PAIR(12) | A_BOLD);
mvwaddch(window[HEADING], zero_y + bias - 9, zero_x + 9, ACS_DIAMOND);
wattroff(window[HEADING], COLOR_PAIR(12) | A_BOLD);
}
//data is at bottom line 132~180
if ((bias >= 21) && (bias <= 30)) {
wattron(window[HEADING], COLOR_PAIR(12) | A_BOLD);
mvwaddch(window[HEADING], zero_y + 12, 18 - (bias - 20), ACS_DIAMOND);
wattroff(window[HEADING], COLOR_PAIR(12) | A_BOLD);
}
//data is at bottom line 180~234
if ((bias >= 31) && (bias <= 39)) {
wattron(window[HEADING], COLOR_PAIR(12) | A_BOLD);
mvwaddch(window[HEADING], zero_y + 12, 9 + (-bias + 30), ACS_DIAMOND);
wattroff(window[HEADING], COLOR_PAIR(12) | A_BOLD);
}
//data is at left line 240~-300
if ((bias >= 40) && (bias <= 50)) {
wattron(window[HEADING], COLOR_PAIR(12) | A_BOLD);
mvwaddch(window[HEADING], 12 + (-bias + 39), 0, ACS_DIAMOND);
wattroff(window[HEADING], COLOR_PAIR(12) | A_BOLD);
}
//data is at left line 306~-360
if ((bias >= 51) && (bias <= 60)) {
wattron(window[HEADING], COLOR_PAIR(12) | A_BOLD);
mvwaddch(window[HEADING], 0, bias - 51, ACS_DIAMOND);
wattroff(window[HEADING], COLOR_PAIR(12) | A_BOLD);
}
if (window[TOP] == window[KF_FIX]) {
wrefresh(window[HEADING]);
}
}
static void show_vertical_speed(float height) {
wattron(window[HEIGHT], COLOR_PAIR(11) | A_BOLD);
mvwprintw(window[HEIGHT], 0, 0, "VERT SPEED");
wattroff(window[HEIGHT], COLOR_PAIR(11) | A_BOLD);
wattron(window[HEIGHT], COLOR_PAIR(13) | A_BOLD);
mvwprintw(window[HEIGHT], 1, 0, "%6.1f m/s", height);
wattroff(window[HEIGHT], COLOR_PAIR(13) | A_BOLD);
if (window[TOP] == window[KF_FIX]) {
wrefresh(window[HEIGHT]);
}
}
static void show_speed(float speed) {
wattron(window[SPEED], COLOR_PAIR(11) | A_BOLD);
mvwprintw(window[SPEED], 0, 3, "SPEED");
wattroff(window[SPEED], COLOR_PAIR(11) | A_BOLD);
wattron(window[SPEED], COLOR_PAIR(13) | A_BOLD);
mvwprintw(window[SPEED], 1, 0, "%6.1f km/h", speed);
wattroff(window[SPEED], COLOR_PAIR(13) | A_BOLD);
if (window[TOP] == window[KF_FIX]) {
wrefresh(window[SPEED]);
}
}
static void show_target(target_t *target) {
mvwprintw(window[TARGET], 0, 4, "Target:");
mvwprintw(window[TARGET], 1, 0, "Distance %9.1f m", target->distance);
mvwprintw(window[TARGET], 2, 0, "Direction %9.1f deg", target->bearing / 1000);
mvwprintw(window[TARGET], 3, 0, "Height %9.1f m", target->height);
mvwprintw(window[TARGET], 4, 0, "Longitude %9.6f deg", target->lon);
mvwprintw(window[TARGET], 5, 0, "Latitude %9.6f deg", target->lat);
if (window[TOP] == window[KF_FIX]) {
wnoutrefresh(window[TARGET]);
}
}
static void show_local(location_t *loc) {
mvwprintw(window[LOCATION], 0, 4, "Location:");
mvwprintw(window[LOCATION], 1, 0, "Longitude %9.6f deg", loc->lon);
mvwprintw(window[LOCATION], 2, 0, "Latitude %9.6f deg", loc->lat);
mvwprintw(window[LOCATION], 3, 0, "Height %9.1f m", loc->height);
if (window[TOP] == window[KF_FIX]) {
wnoutrefresh(window[LOCATION]);
}
}
static void eph_show_header(void) {
wattron(window[EPHEMERIS], COLOR_PAIR(2));
mvwprintw(window[EPHEMERIS], 3, 1, "PRN AZ ELEV EPH SIM ");
wattroff(window[EPHEMERIS], COLOR_PAIR(2));
wrefresh(window[TOP]);
}
static void init_windows(void) {
int info_x, info_y;
window[STATUS] = newwin(STATUS_HEIGHT, max_x - 2, max_y - STATUS_HEIGHT - 1, 1);
window[TRACK] = newwin(max_y, max_x, 0, 0);
window[LS_FIX] = newwin(max_y, max_x, 0, 0);
window[EPHEMERIS] = newwin(max_y, max_x, 0, 0);
window[KF_FIX] = newwin(max_y, max_x, 0, 0);
window[HEADING] = subwin(window[KF_FIX], HEAD_HEIGHT, HEAD_WIDTH, HEAD_Y, HEAD_X);
show_heading(0);
window[HEIGHT] = subwin(window[KF_FIX], 2, 12, HEAD_Y + 6, HEAD_X + 20);
show_vertical_speed(0);
window[SPEED] = subwin(window[KF_FIX], 2, 12, HEAD_Y + 6, HEAD_X - 12);
show_speed(0);
window[TARGET] = subwin(window[KF_FIX], 7, 26, 4, 30);
target_t t = {0};
show_target(&t);
window[LOCATION] = subwin(window[KF_FIX], 4, 26, 4, 2);
location_t l = {0};
show_local(&l);
/* setup info window */
info_x = (max_x - info_width) / 2;
info_y = (max_y - info_height) / 2;
window[INFO] = newwin(info_height, info_width, info_y, info_x);
box(window[INFO], 0, 0);
wattron(window[INFO], COLOR_PAIR(1));
mvwprintw(window[INFO], 1, 2, "Multi SDR GPS Simulator");
wattroff(window[INFO], COLOR_PAIR(1));
wattron(window[INFO], COLOR_PAIR(2));
mvwprintw(window[INFO], 3, 2, "https://github.com/Mictronics/multi-sdr-gps");
mvwprintw(window[INFO], 4, 2, "(c) Mictronics 2021");
mvwprintw(window[INFO], 5, 2, "Distributed under the MIT License");
mvwprintw(window[INFO], 7, 2, "Based on work from Takuji Ebinuma (gps-sdr-sim)");
mvwprintw(window[INFO], 8, 2, "and IvanKor.");
mvwprintw(window[INFO], info_height - 2, 2, "Press any key to return.");
wattroff(window[INFO], COLOR_PAIR(2));
/* setup help window */
info_x = (max_x - help_width) / 2;
info_y = (max_y - help_height) / 2;
window[HELP] = newwin(help_height, help_width, info_y, info_x);
box(window[HELP], 0, 0);
wattron(window[HELP], COLOR_PAIR(1));
mvwprintw(window[HELP], 1, 2, "Help");
wattroff(window[HELP], COLOR_PAIR(1));
mvwprintw(window[HELP], 2, 2, "w Increase altitude i Info");
mvwprintw(window[HELP], 3, 2, "s Decrease altitude h Help");
mvwprintw(window[HELP], 4, 2, "d Heading right x Exit");
mvwprintw(window[HELP], 5, 2, "a Heading left F1 Setup Window");
mvwprintw(window[HELP], 6, 2, "e Increase speed F2 Status Window");
mvwprintw(window[HELP], 7, 2, "q Decrease speed F3 Position Window");
mvwprintw(window[HELP], 8, 2, "t Increase TX gain");
mvwprintw(window[HELP], 9, 2, "g Decrease TX gain");
/* Attach a panel to each window
* Order is bottom up
*/
panel[TRACK] = new_panel(window[TRACK]);
panel[LS_FIX] = new_panel(window[LS_FIX]);
panel[KF_FIX] = new_panel(window[KF_FIX]);
panel[EPHEMERIS] = new_panel(window[EPHEMERIS]);
panel[INFO] = new_panel(window[INFO]);
panel[STATUS] = new_panel(window[STATUS]);
panel[HELP] = new_panel(window[HELP]);
hide_panel(panel[INFO]);
hide_panel(panel[HELP]);
/* Set up the user pointers to the next panel */
set_panel_userptr(panel[TRACK], panel[LS_FIX]);
set_panel_userptr(panel[LS_FIX], panel[KF_FIX]);
set_panel_userptr(panel[KF_FIX], panel[EPHEMERIS]);
set_panel_userptr(panel[EPHEMERIS], panel[TRACK]);
//Print title of each window
show_window(window[TRACK], "GPS Simulator Setup");
show_window(window[LS_FIX], "GPS Simulation Status");
show_window(window[EPHEMERIS], "Test");
show_window(window[KF_FIX], "Dynamic Position");
ls_show_header();
top_panel(panel[TRACK]);
panel[TOP] = panel[TRACK];
// Keep status window scrolling when adding lines
scrollok(window[STATUS], TRUE);
/* Update the stacking order.tracking_panel will be on the top*/
update_panels();
doupdate();
}
void gui_init(void) {
char ch;
pthread_mutex_init(&gui_lock, NULL);
pthread_mutex_lock(&gui_lock);
/* Initialize curses */
initscr();
getmaxyx(stdscr, max_y, max_x);
endwin();
/*check if the col and row meet the threshold */
if (max_y < ROW_THRD || max_x < COL_THRD) {
printf("Your console window size is %dx%d need 26x120\n", max_y, max_x);
printf("Do you still want to continue? [Y/N] ");
ch = getchar();
if ((ch != 'y') && (ch != 'Y')) {
exit(0);
}
}
/* redo the initialization */
initscr();
getmaxyx(stdscr, max_y, max_x);
start_color();
cbreak();
noecho();
curs_set(0); //no cursor
keypad(stdscr, TRUE);
timeout(100);
/* Initialize all the colors */
init_pair(1, COLOR_RED, COLOR_BLACK);
init_pair(2, COLOR_GREEN, COLOR_BLACK);
init_pair(3, COLOR_BLUE, COLOR_BLACK);
init_pair(4, COLOR_CYAN, COLOR_BLACK);
init_pair(5, COLOR_YELLOW, COLOR_BLACK);
init_pair(11, COLOR_BLUE, COLOR_BLACK);
init_pair(12, COLOR_RED, COLOR_BLACK);
init_pair(13, COLOR_RED, COLOR_WHITE);
init_pair(14, COLOR_BLACK, COLOR_RED);
init_windows();
pthread_mutex_unlock(&gui_lock);
}
void gui_destroy(void) {
pthread_mutex_unlock(&gui_lock); // Just in case
pthread_mutex_destroy(&gui_lock);
delwin(window[TRACK]);
delwin(window[LS_FIX]);
delwin(window[KF_FIX]);
delwin(window[INFO]);
delwin(window[HEADING]);
delwin(window[HEIGHT]);
delwin(window[SPEED]);
delwin(window[TARGET]);
delwin(window[LOCATION]);
delwin(window[EPHEMERIS]);
delwin(window[STATUS]);
delwin(window[HELP]);
endwin();
}
void gui_mvwprintw(window_panel_t w, int y, int x, const char * fmt, ...) {
pthread_mutex_lock(&gui_lock);
va_list args;
if (wmove(window[w], y, x) == ERR) {
return;
}
va_start(args, fmt);
vw_printw(window[w], fmt, args);
va_end(args);
// Refresh only what is printed on top panel, don't care about background
// updates.
wrefresh(window[TOP]);
pthread_mutex_unlock(&gui_lock);
}
void gui_status_wprintw(status_color_t clr, const char * fmt, ...) {
pthread_mutex_lock(&gui_lock);
va_list args;
va_start(args, fmt);
if (clr > 0) {
wattron(window[STATUS], COLOR_PAIR(clr));
}
vw_printw(window[STATUS], fmt, args);
if (clr > 0) {
wattroff(window[STATUS], COLOR_PAIR(clr));
}
va_end(args);
wrefresh(window[STATUS]);
pthread_mutex_unlock(&gui_lock);
}
void gui_colorpair(window_panel_t w, unsigned clr, attr_status_t onoff) {
pthread_mutex_lock(&gui_lock);
if (onoff == ON) {
wattron(window[w], COLOR_PAIR(clr));
} else {
wattroff(window[w], COLOR_PAIR(clr));
}
pthread_mutex_unlock(&gui_lock);
}
int gui_getch(void) {
int ch = getch();
/*
if (ch != -1) {
fprintf(stderr, "%i\n", ch);
}
*/
return ch;
}
void gui_top_panel(window_panel_t p) {
pthread_mutex_lock(&gui_lock);
top_panel(panel[p]);
panel[TOP] = panel[p];
window[TOP] = window[p];
// Status is alway the top most panel
top_panel(panel[STATUS]);
gui_update();
pthread_mutex_unlock(&gui_lock);
}
void gui_toggle_current_panel(void) {
pthread_mutex_lock(&gui_lock);
panel[TOP] = (PANEL *) panel_userptr(panel[TOP]);
top_panel(panel[TOP]);
window[TOP] = panel_window(panel[TOP]);
// Status is alway the top most panel
top_panel(panel[STATUS]);
gui_update();
pthread_mutex_unlock(&gui_lock);
}
void gui_show_panel(window_panel_t p, attr_status_t onoff) {
pthread_mutex_lock(&gui_lock);
if (onoff == ON) {
show_panel(panel[p]);
} else {
hide_panel(panel[p]);
}
gui_update();
pthread_mutex_unlock(&gui_lock);
}
void gui_show_speed(float speed) {
pthread_mutex_lock(&gui_lock);
show_speed(speed);
pthread_mutex_unlock(&gui_lock);
}
void gui_show_heading(float hdg) {
pthread_mutex_lock(&gui_lock);
show_heading(hdg);
pthread_mutex_unlock(&gui_lock);
}
void gui_show_vertical_speed(float vs) {
pthread_mutex_lock(&gui_lock);
show_vertical_speed(vs);
pthread_mutex_unlock(&gui_lock);
}
void gui_show_location(void *l) {
pthread_mutex_lock(&gui_lock);
show_local((location_t *) (l));
pthread_mutex_unlock(&gui_lock);
}
void gui_show_target(void *t) {
pthread_mutex_lock(&gui_lock);
show_target((target_t *) (t));
pthread_mutex_unlock(&gui_lock);
}
| 2.1875 | 2 |
2024-11-18T22:11:59.829253+00:00 | 2021-08-08T11:30:00 | 877ab5ed965c8a71a12197515077ab1b9ffca392 | {
"blob_id": "877ab5ed965c8a71a12197515077ab1b9ffca392",
"branch_name": "refs/heads/main",
"committer_date": "2021-08-08T11:30:00",
"content_id": "09588bb314210a6a00a11a67106d80ce69f96e5e",
"detected_licenses": [
"MIT"
],
"directory_id": "9a8aad74b3b5d374bb148a640c4fa0ee33382efa",
"extension": "c",
"filename": "046.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 363627495,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1267,
"license": "MIT",
"license_type": "permissive",
"path": "/problems/046/046.c",
"provenance": "stackv2-0087.json.gz:13821",
"repo_name": "melwyncarlo/ProjectEuler",
"revision_date": "2021-08-08T11:30:00",
"revision_id": "c4d30ed528ae6de82232f3d2044d608c6e8f1c37",
"snapshot_id": "614c4b4f5b2bcd23a4231fdb4fbfa282072d4623",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/melwyncarlo/ProjectEuler/c4d30ed528ae6de82232f3d2044d608c6e8f1c37/problems/046/046.c",
"visit_date": "2023-07-01T18:56:50.793733"
} | stackv2 | #include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* Copyright 2021 Melwyn Francis Carlo */
/* File Reference: http://www.naturalnumbers.org/primes.html */
int main()
{
int smallest_odd_composite_number = 0;
const int MAX_N = 1E5;
FILE *fp;
char prime_num[10];
const char* FILE_NAME = "problems/003/PrimeNumbers_Upto_1000000";
fp = fopen(FILE_NAME, "r");
int primes_list[MAX_N+1];
memset(&primes_list[0], 0, sizeof(primes_list));
while (fgets(prime_num, 10, fp) != NULL)
{
if (atoi(prime_num) > MAX_N)
break;
primes_list[atoi(prime_num)] = 1;
}
fclose(fp);
for (int i = 35; i < MAX_N; i += 2)
{
if (primes_list[i])
continue;
int j = 1;
int prime_found = 0;
while (++j < i)
{
if (!primes_list[j])
continue;
float b = sqrt((float)(i - j) / 2);
if (b == (int)b)
{
prime_found = 1;
break;
}
}
if (!prime_found)
{
smallest_odd_composite_number = i;
break;
}
}
printf("%d\n", smallest_odd_composite_number);
return 0;
}
| 3.171875 | 3 |
2024-11-18T22:12:01.250247+00:00 | 2022-05-19T08:55:47 | aba1ef37f409a86275cf3e732f2f486feb0a6bcf | {
"blob_id": "aba1ef37f409a86275cf3e732f2f486feb0a6bcf",
"branch_name": "refs/heads/master",
"committer_date": "2022-05-19T08:55:47",
"content_id": "c6b2d62abe45561667fe9fe52b44b55975a7c54b",
"detected_licenses": [
"MIT"
],
"directory_id": "9dab8cff2084b9adcf805c3885d05f7ff9a3d54a",
"extension": "c",
"filename": "session.c",
"fork_events_count": 0,
"gha_created_at": "2019-02-12T07:42:58",
"gha_event_created_at": "2019-02-12T07:43:00",
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 170274429,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3129,
"license": "MIT",
"license_type": "permissive",
"path": "/swclt_test/cases/session.c",
"provenance": "stackv2-0087.json.gz:14207",
"repo_name": "sibyakin/signalwire-c",
"revision_date": "2022-05-19T08:55:47",
"revision_id": "8a1b046dde54aae3e5e533b822ab5e71f7534afb",
"snapshot_id": "424b351da19579b3f7248a3ca59588785040e1f8",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/sibyakin/signalwire-c/8a1b046dde54aae3e5e533b822ab5e71f7534afb/swclt_test/cases/session.c",
"visit_date": "2023-01-12T21:29:01.184042"
} | stackv2 | /*
* Copyright (c) 2018 SignalWire, Inc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "swclt_test.h"
static SWCLT_HSTATE g_last_state_change;
static ks_cond_t *g_cond;
static void __on_sess_hmon_event(swclt_sess_t sess, swclt_hstate_change_t *state_change_info, const char *cb_data)
{
REQUIRE(!strcmp(cb_data, "bobo"));
ks_cond_lock(g_cond);
g_last_state_change = state_change_info->new_state;
ks_cond_broadcast(g_cond);
ks_cond_unlock(g_cond);
}
typedef void(*swclt_hstate_change_cb_t)(swclt_handle_base_t *ctx, swclt_hstate_change_t *state_change_request);
void test_session(ks_pool_t *pool)
{
swclt_sess_t sess;
swclt_sess_ctx_t *sess_ctx;
swclt_hmon_t hmon;
REQUIRE(!ks_cond_create(&g_cond, NULL));
/* Load the config we expect session to load */
REQUIRE(swclt_config_get_private_key_path(g_certified_config));
REQUIRE(swclt_config_get_client_cert_path(g_certified_config));
REQUIRE(swclt_config_get_cert_chain_path(g_certified_config));
REQUIRE(!swclt_sess_create(&sess, g_target_ident_str, g_certified_config));
/* Register a monitor to get to know when session comes online successfully */
REQUIRE(!swclt_hmon_register(&hmon, sess, __on_sess_hmon_event, "bobo"));
{
ks_handle_t next = 0;
uint32_t count = 0;
while (KS_STATUS_SUCCESS == ks_handle_enum_type(SWCLT_HTYPE_HMON, &next))
count++;
REQUIRE(count == 1);
}
ks_cond_lock(g_cond);
/* Now take the session onine */
REQUIRE(!swclt_sess_connect(sess));
ks_cond_wait(g_cond);
/* Should be online */
REQUIRE(g_last_state_change == SWCLT_HSTATE_ONLINE);
/* Now disconnect the session */
REQUIRE(!swclt_sess_disconnect(sess));
/* Should be offline now */
ks_cond_wait(g_cond);
REQUIRE(g_last_state_change == SWCLT_HSTATE_OFFLINE);
/* Now delete the monitor */
ks_handle_destroy(&hmon);
ks_cond_unlock(g_cond);
/* Go online again */
REQUIRE(!swclt_sess_connect(sess));
/* Wait for its low level handle state to be back to OK */
while (swclt_hstate_check(sess, NULL))
ks_sleep(1000);
/* Ok we're done */
ks_cond_destroy(&g_cond);
ks_handle_destroy(&sess);
}
| 2.28125 | 2 |
2024-11-18T22:12:01.407433+00:00 | 2020-09-07T18:45:10 | 5ae73f3f7904819f08c9ad29071a3bdc16daaf0e | {
"blob_id": "5ae73f3f7904819f08c9ad29071a3bdc16daaf0e",
"branch_name": "refs/heads/master",
"committer_date": "2020-09-07T18:45:10",
"content_id": "a6de44673b51b1f846f8fe8da341f7073107833b",
"detected_licenses": [
"MIT"
],
"directory_id": "6f88698a82bb4bb51160ebc5f9650e5ecccffb8e",
"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": null,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3062,
"license": "MIT",
"license_type": "permissive",
"path": "/04_SPIFLASH/04_SPIFLASH/main.c",
"provenance": "stackv2-0087.json.gz:14337",
"repo_name": "ottomc2/atmel-samd21",
"revision_date": "2020-09-07T18:45:10",
"revision_id": "596d464d0be03e5343488d44054241f876e8df24",
"snapshot_id": "44d0e550833103faed053e6d466e9b70d005d570",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ottomc2/atmel-samd21/596d464d0be03e5343488d44054241f876e8df24/04_SPIFLASH/04_SPIFLASH/main.c",
"visit_date": "2022-12-15T00:04:54.298707"
} | stackv2 | #include <atmel_start.h>
#include <stdbool.h>
#include <stdio.h>
#include "ext_flash.h"
// Debug Out IO Descriptor
struct io_descriptor *debug_io;
// Flags for UART Receive
volatile debug_io_receiving, debug_io_complete = false;
// Maximum Size of UART Message for Memory
#define MAX_MESSAGE_SIZE 64
// Char Array for UART Received Bytes
static uint8_t debug_io_received_bytes[MAX_MESSAGE_SIZE];
// Byte Counter
uint8_t debug_io_bytes_received_counter = 0;
/**
* UART Receive Callback function.
*
*/
static void debug_rx_cb(const struct usart_async_descriptor *const io_descr)
{
// Counters
uint8_t ch, count;
// Read a character
count = io_read(debug_io, &ch, 1);
// Now we're checking if we've received already
if (debug_io_receiving == false)
{
// Set the Receiving Flag
debug_io_receiving = true;
// Reset the Byte Counter
debug_io_bytes_received_counter = 0;
// Start filling the buffer
debug_io_received_bytes[debug_io_bytes_received_counter] = ch;
// Increment the Counter
debug_io_bytes_received_counter += count;
}
else
{
// Continue filling the buffer
debug_io_received_bytes[debug_io_bytes_received_counter] = ch;
// Increment the Counter
debug_io_bytes_received_counter += count;
// Check for end of string
if (ch == '\n')
{
// Set the Completion Flag
debug_io_complete = true;
}
}
}
/**
* Method for initialising UART
*
*/
static void init_com_port()
{
// Register the Callback Function
usart_async_register_callback(&DEBUGOUT, USART_ASYNC_RXC_CB, debug_rx_cb);
// Set the IO Descriptor
usart_async_get_io_descriptor(&DEBUGOUT, &debug_io);
// Enable ASYNC UART
usart_async_enable(&DEBUGOUT);
}
int main(void)
{
/* Initializes MCU, drivers and middleware */
atmel_start_init();
// Initialise COM Port
init_com_port();
// Initialise Serial Flash
EXTFLASH_init();
/* Replace with your application code */
while (1)
{
// Check if we're receiving
if (debug_io_receiving == true)
{
// Check if receive complete
if (debug_io_complete == true)
{
// Open Serial Flash
if (EXTFLASH_open())
{
// Erase First Block
if (EXTFLASH_erase(0, FLASH_ERASE_SECTOR_SIZE))
{
// Delay to allow erase
delay_ms(240);
}
// Buffer for Write Data
uint8_t wdata[MAX_MESSAGE_SIZE];
memcpy(&wdata[0], &debug_io_received_bytes[0], MAX_MESSAGE_SIZE);
// Attempt to Write Data
if (EXTFLASH_write(0, MAX_MESSAGE_SIZE, wdata))
{
// Buffer for Read Data
uint8_t rdata[MAX_MESSAGE_SIZE];
memset(rdata, 0x00, MAX_MESSAGE_SIZE);
// Attempt to Read Data
if (EXTFLASH_read(0, MAX_MESSAGE_SIZE, &rdata[0]))
{
// Response String
char *response = malloc(128);
sprintf(response, "Stored in memory: %s", rdata);
// Print to Console
io_write(debug_io, response, strlen(response));
}
}
}
// Reset Flags
debug_io_receiving = false;
debug_io_complete = false;
}
}
}
}
| 3.09375 | 3 |
2024-11-18T22:12:01.636420+00:00 | 2021-05-01T16:36:07 | 780647dafd1e4de63ad2f93767cedcad2280e9c4 | {
"blob_id": "780647dafd1e4de63ad2f93767cedcad2280e9c4",
"branch_name": "refs/heads/main",
"committer_date": "2021-05-01T16:36:07",
"content_id": "ea04c0ee20ef32733ccc4f4bdd0fb65910d8e380",
"detected_licenses": [
"MIT"
],
"directory_id": "1b40b1dc5b43bc72bf26df19cb227ac6c27ccbc5",
"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": null,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 16273,
"license": "MIT",
"license_type": "permissive",
"path": "/snake.X/main.c",
"provenance": "stackv2-0087.json.gz:14465",
"repo_name": "yetkinakyz/PIC18-Snake",
"revision_date": "2021-05-01T16:36:07",
"revision_id": "779cfbd1453c39af7dd0cff8de2ca33548a48d9e",
"snapshot_id": "296d48571912d87228ec88f267b9ad500ef8b6f8",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/yetkinakyz/PIC18-Snake/779cfbd1453c39af7dd0cff8de2ca33548a48d9e/snake.X/main.c",
"visit_date": "2023-04-24T03:27:58.749444"
} | stackv2 | /*
* Project Name: Snake Game Project with PIC18F46K22
*
* Authors: Yetkin AKYUZ (yetkin.akyuz@outlook.com)
*
* Created on December 29, 2020, 5:35 PM
*/
#include <stdio.h>
#include <stdlib.h>
#include <xc.h>
// *************** CONFIGURATIONS ***************
// CONFIG1H
#pragma config FOSC = INTIO67 // Oscillator Selection bits (Internal oscillator block)
#pragma config PLLCFG = OFF // 4X PLL Enable (Oscillator used directly)
#pragma config PRICLKEN = ON // Primary clock enable bit (Primary clock is always enabled)
#pragma config FCMEN = OFF // Fail-Safe Clock Monitor Enable bit (Fail-Safe Clock Monitor disabled)
#pragma config IESO = OFF // Internal/External Oscillator Switchover bit (Oscillator Switchover mode disabled)
// CONFIG2L
#pragma config PWRTEN = OFF // Power-up Timer Enable bit (Power up timer disabled)
#pragma config BOREN = SBORDIS // Brown-out Reset Enable bits (Brown-out Reset enabled in hardware only (SBOREN is disabled))
#pragma config BORV = 190 // Brown Out Reset Voltage bits (VBOR set to 1.90 V nominal)
// CONFIG2H
#pragma config WDTEN = OFF // Watchdog Timer Enable bits (Watch dog timer is always disabled. SWDTEN has no effect.)
#pragma config WDTPS = 32768 // Watchdog Timer Postscale Select bits (1:32768)
// CONFIG3H
#pragma config CCP2MX = PORTC1 // CCP2 MUX bit (CCP2 input/output is multiplexed with RC1)
#pragma config PBADEN = ON // PORTB A/D Enable bit (PORTB<5:0> pins are configured as analog input channels on Reset)
#pragma config CCP3MX = PORTB5 // P3A/CCP3 Mux bit (P3A/CCP3 input/output is multiplexed with RB5)
#pragma config HFOFST = ON // HFINTOSC Fast Start-up (HFINTOSC output and ready status are not delayed by the oscillator stable status)
#pragma config T3CMX = PORTC0 // Timer3 Clock input mux bit (T3CKI is on RC0)
#pragma config P2BMX = PORTD2 // ECCP2 B output mux bit (P2B is on RD2)
#pragma config MCLRE = EXTMCLR // MCLR Pin Enable bit (MCLR pin enabled, RE3 input pin disabled)
// CONFIG4L
#pragma config STVREN = ON // Stack Full/Underflow Reset Enable bit (Stack full/underflow will cause Reset)
#pragma config LVP = ON // Single-Supply ICSP Enable bit (Single-Supply ICSP enabled if MCLRE is also 1)
#pragma config XINST = OFF // Extended Instruction Set Enable bit (Instruction set extension and Indexed Addressing mode disabled (Legacy mode))
// CONFIG5L
#pragma config CP0 = OFF // Code Protection Block 0 (Block 0 (000800-003FFFh) not code-protected)
#pragma config CP1 = OFF // Code Protection Block 1 (Block 1 (004000-007FFFh) not code-protected)
#pragma config CP2 = OFF // Code Protection Block 2 (Block 2 (008000-00BFFFh) not code-protected)
#pragma config CP3 = OFF // Code Protection Block 3 (Block 3 (00C000-00FFFFh) not code-protected)
// CONFIG5H
#pragma config CPB = OFF // Boot Block Code Protection bit (Boot block (000000-0007FFh) not code-protected)
#pragma config CPD = OFF // Data EEPROM Code Protection bit (Data EEPROM not code-protected)
// CONFIG6L
#pragma config WRT0 = OFF // Write Protection Block 0 (Block 0 (000800-003FFFh) not write-protected)
#pragma config WRT1 = OFF // Write Protection Block 1 (Block 1 (004000-007FFFh) not write-protected)
#pragma config WRT2 = OFF // Write Protection Block 2 (Block 2 (008000-00BFFFh) not write-protected)
#pragma config WRT3 = OFF // Write Protection Block 3 (Block 3 (00C000-00FFFFh) not write-protected)
// CONFIG6H
#pragma config WRTC = OFF // Configuration Register Write Protection bit (Configuration registers (300000-3000FFh) not write-protected)
#pragma config WRTB = OFF // Boot Block Write Protection bit (Boot Block (000000-0007FFh) not write-protected)
#pragma config WRTD = OFF // Data EEPROM Write Protection bit (Data EEPROM not write-protected)
// CONFIG7L
#pragma config EBTR0 = OFF // Table Read Protection Block 0 (Block 0 (000800-003FFFh) not protected from table reads executed in other blocks)
#pragma config EBTR1 = OFF // Table Read Protection Block 1 (Block 1 (004000-007FFFh) not protected from table reads executed in other blocks)
#pragma config EBTR2 = OFF // Table Read Protection Block 2 (Block 2 (008000-00BFFFh) not protected from table reads executed in other blocks)
#pragma config EBTR3 = OFF // Table Read Protection Block 3 (Block 3 (00C000-00FFFFh) not protected from table reads executed in other blocks)
// CONFIG7H
#pragma config EBTRB = OFF // Boot Block Table Read Protection bit (Boot Block (000000-0007FFh) not protected from table reads executed in other blocks)
#define _XTAL_FREQ 64000000
// **************** PIN DEFINITIONS ****************
// BUTTONS
#define buttonRight PORTBbits.RB0
#define buttonLeft PORTBbits.RB1
#define buttonUp PORTBbits.RB2
#define buttonDown PORTBbits.RB3
// COLUMNS
#define PORTROW0 LATAbits.LATA1
#define PORTROW1 LATAbits.LATA2
#define PORTROW2 LATAbits.LATA3
#define PORTROW3 LATDbits.LATD3
#define PORTROW4 LATDbits.LATD4
#define PORTROW5 LATDbits.LATD5
#define PORTROW6 LATDbits.LATD6
#define PORTROW7 LATDbits.LATD7
// ROWS
#define PORTCOL0 LATEbits.LATE1
#define PORTCOL1 LATEbits.LATE2
#define PORTCOL2 LATCbits.LATC2
#define PORTCOL3 LATCbits.LATC3
#define PORTCOL4 LATCbits.LATC4
#define PORTCOL5 LATCbits.LATC5
#define PORTCOL6 LATCbits.LATC6
#define PORTCOL7 LATCbits.LATC7
// Column status lists
const unsigned char Col0[] = {1, 0, 0, 0, 0, 0, 0, 0};
const unsigned char Col1[] = {0, 1, 0, 0, 0, 0, 0, 0};
const unsigned char Col2[] = {0, 0, 1, 0, 0, 0, 0, 0};
const unsigned char Col3[] = {0, 0, 0, 1, 0, 0, 0, 0};
const unsigned char Col4[] = {0, 0, 0, 0, 1, 0, 0, 0};
const unsigned char Col5[] = {0, 0, 0, 0, 0, 1, 0, 0};
const unsigned char Col6[] = {0, 0, 0, 0, 0, 0, 1, 0};
const unsigned char Col7[] = {0, 0, 0, 0, 0, 0, 0, 1};
// Row status lists
const unsigned char Row0[] = {0, 1, 1, 1, 1, 1, 1, 1};
const unsigned char Row1[] = {1, 0, 1, 1, 1, 1, 1, 1};
const unsigned char Row2[] = {1, 1, 0, 1, 1, 1, 1, 1};
const unsigned char Row3[] = {1, 1, 1, 0, 1, 1, 1, 1};
const unsigned char Row4[] = {1, 1, 1, 1, 0, 1, 1, 1};
const unsigned char Row5[] = {1, 1, 1, 1, 1, 0, 1, 1};
const unsigned char Row6[] = {1, 1, 1, 1, 1, 1, 0, 1};
const unsigned char Row7[] = {1, 1, 1, 1, 1, 1, 1, 0};
// OSCILLATOR INITIALIZER FUNCTION
void OSCILLATOR(void) {
OSCCONbits.IRCF = 0x7; // INTERNAL OSCILLATOR
OSCTUNEbits.PLLEN = 1; // PLL is ON
}
// PIN MANAGER FUNCTION
void PIN_MANAGER(void) {
/**
TRISx registers
*/
TRISB = 0; //INPUT
TRISA = 1; //OUTPUT
TRISC = 1; //OUTPUT
TRISD = 1; //OUTPUT
TRISE = 1; //OUTPUT
/**
ANSELx registers
*/
ANSELA = 0; //DIGITAL IO
ANSELB = 0; //DIGITAL IO
ANSELC = 0; //DIGITAL IO
ANSELD = 0; //DIGITAL IO
ANSELE = 0; //DIGITAL IO
/**
WPUx registers
*/
WPUBbits.WPUB0 = 0;
WPUBbits.WPUB1 = 0;
WPUBbits.WPUB2 = 0;
WPUBbits.WPUB3 = 0;
}
// CLEAN THE BOARD FUNCTION
void BOARD_CLEAN(void) {
PORTCOL0 = 0;
PORTCOL1 = 0;
PORTCOL2 = 0;
PORTCOL3 = 0;
PORTCOL4 = 0;
PORTCOL5 = 0;
PORTCOL6 = 0;
PORTCOL7 = 0;
PORTROW0 = 1;
PORTROW1 = 1;
PORTROW2 = 1;
PORTROW3 = 1;
PORTROW4 = 1;
PORTROW5 = 1;
PORTROW6 = 1;
PORTROW7 = 1;
}
// LIGHT ALL OF THE LEDS FUNCTION
void BOARD_FULL(void) {
PORTCOL0 = 1;
PORTCOL1 = 1;
PORTCOL2 = 1;
PORTCOL3 = 1;
PORTCOL4 = 1;
PORTCOL5 = 1;
PORTCOL6 = 1;
PORTCOL7 = 1;
PORTROW0 = 0;
PORTROW1 = 0;
PORTROW2 = 0;
PORTROW3 = 0;
PORTROW4 = 0;
PORTROW5 = 0;
PORTROW6 = 0;
PORTROW7 = 0;
}
// LIGHT THE LEDS FUNCTION
void BOARD_LIGHT(unsigned char X, unsigned char Y) {
PORTCOL0 = Col0[X];
PORTCOL1 = Col1[X];
PORTCOL2 = Col2[X];
PORTCOL3 = Col3[X];
PORTCOL4 = Col4[X];
PORTCOL5 = Col5[X];
PORTCOL6 = Col6[X];
PORTCOL7 = Col7[X];
PORTROW0 = Row0[Y];
PORTROW1 = Row1[Y];
PORTROW2 = Row2[Y];
PORTROW3 = Row3[Y];
PORTROW4 = Row4[Y];
PORTROW5 = Row5[Y];
PORTROW6 = Row6[Y];
PORTROW7 = Row7[Y];
}
char BUTTON_CONTROL(char Direction) {
// *************** BUTTONS ****************
// The snake cannot go in the opposite direction on the same axis.
if (buttonRight && Direction != 'L'){
Direction = 'R';
}
else if (buttonLeft && Direction != 'R') {
Direction = 'L';
}
else if (buttonUp && Direction != 'D') {
Direction = 'U';
}
else if (buttonDown && Direction != 'U') {
Direction = 'D';
}
else {
//Nothing
}
__delay_ms(0.005);
return Direction;
}
void PRINT_SNAKE(double Cycle, int SnakeLength, unsigned char SnakeX[], unsigned char SnakeY[], int FoodX, int FoodY, char Direction) {
// *************** SNAKE DELAY CONTROL ***************
while(256 - ((0.1 * SnakeLength + 0.6) * Cycle) > 26) {
Cycle--;
}
for (int j = 0; j < Cycle; j = j++) {
Direction = BUTTON_CONTROL(Direction);
// *************** PRINT SNAKE ****************
for (int i = 0 ; i < SnakeLength; i++) {
Direction = BUTTON_CONTROL(Direction);
// Light the LEDs
BOARD_LIGHT(SnakeX[i], SnakeY[i]);
// Wait for 0.1 milliseconds
__delay_ms(0.1);
}
// Clean the board
BOARD_CLEAN();
// Wait for 0.5 milliseconds
__delay_ms(0.5);
// *************** PRINT FOOD ****************
// Light the LEDs
BOARD_LIGHT(FoodX, FoodY);
// Wait for 0.1 milliseconds
__delay_ms(0.1);
// Clean the board
BOARD_CLEAN();
}
}
// MAIN FUNCTION
int main(void) {
// System setup
OSCILLATOR();
PIN_MANAGER();
// Light all of the LEDs
BOARD_FULL();
// Wait for a second
__delay_ms(1000);
// Clean the board
BOARD_CLEAN();
// **************** GAME SETUP ****************
// Snake's coordinates. Maximum length of snake is 8 units.
unsigned char SnakeX[64] = {2,1,0};
unsigned char SnakeY[64] = {2,2,2};
// Snake's length (Begins with 3 units)
int SnakeLength = 3;
// Level variable
int level = 0;
int Lost = 0;
// Food Coordinates for each level
int FoodXList[64] = {6, 3, 5, 3, 7, 2, 5, 1, 4, 2, 4, 2, 6, 3, 4, 1, 2, 6, 3, 3, 1, 5, 6, 4, 3, 5, 4, 2, 5, 4, 2, 4, 6, 3, 5, 3, 7, 2, 5, 1, 4, 2, 4, 2, 6, 3, 4, 1, 2, 6, 3, 3, 1, 5, 6, 4, 3, 5, 4, 2, 5, 4, 2, 4};
int FoodYList[64] = {2, 6, 3, 3, 1, 5, 6, 4, 3, 5, 4, 2, 5, 4, 2, 4, 6, 3, 5, 3, 7, 2, 5, 1, 4, 2, 4, 2, 6, 3, 4, 1, 2, 6, 3, 3, 1, 5, 6, 4, 3, 5, 4, 2, 5, 4, 2, 4, 6, 3, 5, 3, 7, 2, 5, 1, 4, 2, 4, 2, 6, 3, 4, 1};
// Present food coordinates
int FoodX = FoodXList[level];
int FoodY = FoodYList[level];
// Directions (Begins with RIGHT)
char Direction = 'R';
// Delay parameters for PRINT_SNAKE()
double Cycle = 256;
// Clean the board
BOARD_CLEAN();
// Wait until any button is pressed
while (!buttonRight && !buttonLeft && !buttonUp && !buttonDown) {
PRINT_SNAKE(Cycle, SnakeLength, SnakeX, SnakeY, FoodX, FoodY, Direction);
}
while (buttonRight || buttonLeft || buttonUp || buttonDown);
__delay_ms(150);
// **************** GAME HAS STARTED ****************
while (1) {
// *************** EATING SELF ****************
// If head's and any part of tail have same coordinates, game is over. Snake ate itself, you lost.
for (int i = 1; i < SnakeLength - 1; i++) {
if (SnakeX[i] == SnakeX[0] && SnakeY[i] == SnakeY[0]) {
// Light all of the LEDs
BOARD_FULL();
// Wait for a second
__delay_ms(1000);
Lost = 1;
}
}
// *************** TAIL MOVEMENT CONTROL ****************
// Each part of tail gets the value of the part which is in front of it.
for (int i = SnakeLength - 1; i > 0; i--) {
Direction = BUTTON_CONTROL(Direction);
SnakeX[i] = SnakeX[i - 1];
SnakeY[i] = SnakeY[i - 1];
}
// *************** HEAD MOVEMENT CONTROL ****************
Direction = BUTTON_CONTROL(Direction);
switch(Direction) {
// Right
case 'R':
if (SnakeX[0] >= 7) {
//Lost = 1;
SnakeX[0] = 0;
}
else {
SnakeX[0] = SnakeX[0] + 1;
}
break;
// Left
case 'L':
if (SnakeX[0] < 1) {
//Lost = 1;
SnakeX[0] = 7;
}
else {
SnakeX[0] = SnakeX[0] - 1;
}
break;
// Up
case 'U':
if (SnakeY[0] >= 7) {
//Lost = 1;
SnakeY[0] = 0;
}
else {
SnakeY[0] = SnakeY[0] + 1;
}
break;
// Down
case 'D':
if (SnakeY[0] < 1) {
//Lost = 1;
SnakeY[0] = 7;
}
else {
SnakeY[0] = SnakeY[0] - 1;
}
break;
}
// *************** PRINT SNAKE AND FOOD ***************
PRINT_SNAKE(Cycle, SnakeLength, SnakeX, SnakeY, FoodX, FoodY, Direction);
// *************** EATING FOOD ****************
if ((FoodX == SnakeX[0]) && (FoodY == SnakeY[0])) {
// If snake and food have the same coordinates, increase the length of sneak.
// If the length is more than 7, game is over. You won.
if (++SnakeLength < 10000) {
// Level up
level++;
// New level food coordinates
FoodX = FoodXList[level];
FoodY = FoodYList[level];
// Add new part to snake
SnakeX[SnakeLength - 1] = 0;
SnakeY[SnakeLength - 1] = 0;
}
}
// Stop the game if we lost
if (Lost == 1) {
//Light all of the LEDs
BOARD_FULL();
__delay_ms(1000);
while (!buttonRight && !buttonLeft && !buttonUp && !buttonDown) {
PRINT_SNAKE(Cycle, SnakeLength, SnakeX, SnakeY, SnakeX[0], SnakeY[0], Direction);
}
__delay_ms(50);
while (buttonRight || buttonLeft || buttonUp || buttonDown);
__delay_ms(50);
//Clean the board
BOARD_CLEAN();
//Stop the game
break;
}
}
// Wait until any button is pressed
while (!buttonRight && !buttonLeft && !buttonUp && !buttonDown);
__delay_ms(150);
return 0;
}
| 2.046875 | 2 |
2024-11-18T22:12:02.731578+00:00 | 2020-06-16T11:23:25 | 67fee5f97fd2069254819454da4737b00fea933b | {
"blob_id": "67fee5f97fd2069254819454da4737b00fea933b",
"branch_name": "refs/heads/master",
"committer_date": "2020-06-16T11:23:25",
"content_id": "25038b6a836ecf0c5d9827af15cc0e4a7f54b349",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "5081b557412677135328593c060c0126ee2bcfc0",
"extension": "c",
"filename": "fit_mrq.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 272690951,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 6450,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/psrsalsa-1.0/src/prog/fit_mrq.c",
"provenance": "stackv2-0087.json.gz:15368",
"repo_name": "ruthhwj/Pulsar-Project",
"revision_date": "2020-06-16T11:23:25",
"revision_id": "18a7fcfbb3c57c2076f5008c8b8dc9e46454dc46",
"snapshot_id": "8621cfebb81989f5394e829757bb2cb58e4984c7",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/ruthhwj/Pulsar-Project/18a7fcfbb3c57c2076f5008c8b8dc9e46454dc46/psrsalsa-1.0/src/prog/fit_mrq.c",
"visit_date": "2022-11-03T22:02:02.920468"
} | stackv2 | #include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
#include "psrsalsa.h"
// Test function designed to test the function compute_covariance_matrix(), which is not used any further in this program.
double test_dydparam(long param, double *optimum_params, double x);
int main(int argc, char **argv)
{
int Read_Sigma, Use_Sigma, dolog, forceChi2, i, oneatatime, status, algorithm, showcovariance;
double sig_scale, tolerance;
long ndata;
double *data_x, *data_y, *data_sig;
fitfunc_collection_type function;
verbose_definition verbose;
int test_compute_covariance_matrix; // If set, compute_covariance_matrix() is tested, which is not used by this program, but it allows to test if this function behaves correctly
cleanVerboseState(&verbose);
/* int j, k, l; */
Read_Sigma = 0;
sig_scale = 1;
Use_Sigma = 1;
dolog = 0;
forceChi2 = 0;
oneatatime = 1;
test_compute_covariance_matrix = 0;
algorithm = 1;
showcovariance = 0;
tolerance = 1e-4;
if(argc < 2) {
fprintf(stderr, "Usage: fit_mrq [options] file\n\n");
fprintf(stderr, "-s Read three columns from file: x,y and sigma. Default is only x,y.\n");
fprintf(stderr, "-i Read three columns from file: x,y and sigma, but ignore take all sigma's equal to one.\n");
fprintf(stderr, "-a Scale errors by this fraction.\n");
show_fitfunctions_commandline_options(stderr, "-f", 6);
fprintf(stderr, "-l Take log of x and y data.\n");
fprintf(stderr, "-1 Force reduced chi2 to be one.\n");
fprintf(stderr, "-v verbose.\n");
fprintf(stderr, "-all Do fitting for all parameter simulteneously instead of one at a time. This makes the fitting faster, but less robust.\n");
fprintf(stderr, "-algorithm 1=GSL, 2=NR.\n");
fprintf(stderr, "-tol Stop itterating when changes in fit parameters are less than this fraction of its value [%.2e].\n", tolerance);
fprintf(stderr, "-covar\n");
return 0;
}else if(argc > 2) {
for(i = 1; i < argc-1; i++) {
if(strcmp(argv[i], "-s") == 0) {
Read_Sigma = 1;
}else if(strcmp(argv[i], "-f") == 0) {
/* Ignore parsing fitfunction, it will be dealt with later */
i++;
}else if(strcmp(argv[i], "-a") == 0 || strcmp(argv[i], "-A") == 0) {
sig_scale = atof(argv[i+1]);
i++;
}else if(strcmp(argv[i], "-algorithm") == 0) {
algorithm = atoi(argv[i+1]);
i++;
}else if(strcmp(argv[i], "-tolerance") == 0 || strcmp(argv[i], "-tol") == 0) {
tolerance = atof(argv[i+1]);
i++;
}else if(strcmp(argv[i], "-i") == 0 || strcmp(argv[i], "-I") == 0) {
Read_Sigma = 1;
Use_Sigma = 0;
}else if(strcmp(argv[i], "-l") == 0 || strcmp(argv[i], "-L") == 0) {
dolog = 1;
}else if(strcmp(argv[i], "-all") == 0) {
oneatatime = 0;
}else if(strcmp(argv[i], "-v") == 0) {
verbose.verbose = 1;
}else if(strcmp(argv[i], "-1") == 0) {
forceChi2 = 1;
}else if(strcmp(argv[i], "-test_compute_covariance_matrix") == 0) {
test_compute_covariance_matrix = 1;
}else if(strcmp(argv[i], "-covar") == 0) {
showcovariance = 1;
}
}
}
if(parse_commandline_fitfunctions(argc, argv, "-f", &function, verbose) == 0)
return 0;
// if(read_ascii_statdata_double(argv[argc-1], &ndata, &data_x, &data_y, &data_sig, Read_Sigma, sig_scale, dolog, dolog, 1) == 0)
// return 0;
verbose_definition verbose2;
copyVerboseState(verbose, &verbose2);
verbose2.verbose = 1;
int nrExpectedColumns;
if(Read_Sigma) {
nrExpectedColumns = 3;
}else {
nrExpectedColumns = 2;
}
if(read_ascii_column_double(argv[argc-1], 0, '#', nrExpectedColumns, 0, &ndata, 1, 1.0, dolog, &data_x, NULL, NULL, NULL, verbose2, 0) == 0)
return 0;
if(read_ascii_column_double(argv[argc-1], 0, '#', nrExpectedColumns, 0, &ndata, 2, 1.0, dolog, &data_y, NULL, NULL, NULL, verbose2, 0) == 0)
return 0;
if(Read_Sigma) {
if(read_ascii_column_double(argv[argc-1], 0, '#', nrExpectedColumns, 0, &ndata, 3, sig_scale, dolog, &data_sig, NULL, NULL, NULL, verbose2, 0) == 0)
return 0;
if(Use_Sigma == 0) {
for(i = 0; i < ndata; i++)
data_sig[i] = 1;
}
}else {
data_sig = NULL;
}
/*
printf("Showing %ld points\n", ndata);
for(i = 0; i < ndata; i++) {
printf("%e %e %e\n", data_x[i], data_y[i], data_sig[i]);
}
*/
if(fit_levmar(algorithm, &function, data_x, data_y, data_sig, ndata, oneatatime, forceChi2, 0, tolerance, 500, &status, 1, showcovariance, verbose) != 0) {
if(status) {
printerror(verbose.debug, "ERROR fit_mrq: Fit did not converge.");
return 0;
}
printwarning(verbose.debug, "WARNING fit_mrq: A warning was generated in fit_levmar().");
}
if(test_compute_covariance_matrix) {
// Fit should be a + b + c*x**2
int ok;
ok = 1;
if(function.nrfuncs != 3) {
ok = 0;
if(function.func[0].type != FUNC_POLYNOMAL || function.func[1].type != FUNC_POLYNOMAL || function.func[2].type != FUNC_POLYNOMAL)
ok = 0;
if(function.func[0].param[0] != 0.0 || function.func[1].param[0] != 1.0 || function.func[2].param[0] != 2.0)
ok = 0;
}
if(ok == 0) {
printerror(verbose.debug, "ERROR fit_mrq: Fit should be a + b + c*x**2 to do this test.");
return 0;
}
fflush(stdout);
printf("Fit function of correct type\n");
double optimum_params[3];
optimum_params[0] = function.func[0].value[0];
optimum_params[1] = function.func[0].value[1];
optimum_params[2] = function.func[0].value[2];
double covariance_matrix[3*3];
if(compute_covariance_matrix(3, optimum_params, test_dydparam, function.chi2, forceChi2, ndata, data_x, data_sig, covariance_matrix, verbose) != 0) {
printerror(verbose.debug, "ERROR fit_mrq: Covariance matrix couldn't be determined.");
return 0;
}
printf("According to compute_covariance_matrix() the errors should be (for chi2=%e):\n", function.chi2);
printf(" %e\n", sqrt(covariance_matrix[0*3+0]));
printf(" %e\n", sqrt(covariance_matrix[1*3+1]));
printf(" %e\n", sqrt(covariance_matrix[2*3+2]));
}
free(data_x);
free(data_y);
if(Read_Sigma)
free(data_sig);
return 0;
}
double test_dydparam(long param, double *optimum_params, double x)
{
if(param == 0) { // a -> 1.0
return 1.0;
}else if(param == 1) { // a*x -> x
return x;
}else if(param == 2) { // a*x^2 -> x^2
return x*x;
}
printf("Bug!!!!\n");
exit(0);
return 0;
}
| 2.265625 | 2 |
2024-11-18T22:12:02.814335+00:00 | 2022-11-03T19:53:33 | 9e52cae7209db57ba876b28820f1677c0bf06486 | {
"blob_id": "9e52cae7209db57ba876b28820f1677c0bf06486",
"branch_name": "refs/heads/master",
"committer_date": "2022-11-03T19:53:33",
"content_id": "e5fd9b0763c6ed2584b2056740c6a64801fb2ec5",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "1ff832389401454c2be121ff107f5096560611be",
"extension": "h",
"filename": "hash_table.h",
"fork_events_count": 0,
"gha_created_at": "2017-07-25T22:22:03",
"gha_event_created_at": "2022-11-03T19:53:35",
"gha_language": "C",
"gha_license_id": "Apache-2.0",
"github_id": 98354840,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2348,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/frontend/hash_table.h",
"provenance": "stackv2-0087.json.gz:15497",
"repo_name": "markdryan/subtilis",
"revision_date": "2022-11-03T19:53:33",
"revision_id": "5a33b921c840e9857feedfa11e9ad2750345177d",
"snapshot_id": "142a7e238e4174e64901e97078ba85ddb9cf6b49",
"src_encoding": "UTF-8",
"star_events_count": 10,
"url": "https://raw.githubusercontent.com/markdryan/subtilis/5a33b921c840e9857feedfa11e9ad2750345177d/frontend/hash_table.h",
"visit_date": "2023-08-07T06:31:28.485171"
} | stackv2 | /*
* Copyright (c) 2017 Mark Ryan
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef __SUBTILIS_HASH_TABLE_H
#define __SUBTILIS_HASH_TABLE_H
#include <stdbool.h>
#include <stdint.h>
#include "../common/error.h"
typedef struct subtilis_hashtable_t_ subtilis_hashtable_t;
typedef size_t (*subtilis_hashtable_func_t)(subtilis_hashtable_t *,
const void *);
typedef bool (*subtilis_hashtable_equal_t)(const void *, const void *);
typedef void (*subtilis_hashtable_free_t)(void *);
typedef struct subtilis_hashtable_node_t_ subtilis_hashtable_node_t;
struct subtilis_hashtable_t_ {
subtilis_hashtable_node_t **buckets;
size_t elements;
size_t num_buckets;
subtilis_hashtable_func_t hash_func;
subtilis_hashtable_equal_t equal_func;
subtilis_hashtable_free_t free_key;
subtilis_hashtable_free_t free_value;
};
subtilis_hashtable_t *subtilis_hashtable_new(size_t num_buckets,
subtilis_hashtable_func_t h_func,
subtilis_hashtable_equal_t eq_func,
subtilis_hashtable_free_t free_k,
subtilis_hashtable_free_t free_v,
subtilis_error_t *err);
void *subtilis_hashtable_find(subtilis_hashtable_t *h, const void *k);
void subtilis_hashtable_delete(subtilis_hashtable_t *h);
size_t subtilis_hashtable_perfection(subtilis_hashtable_t *h);
bool subtilis_hashtable_insert(subtilis_hashtable_t *h, void *k, void *v,
subtilis_error_t *err);
bool subtilis_hashtable_remove(subtilis_hashtable_t *h, const void *k);
void *subtilis_hashtable_extract(subtilis_hashtable_t *h, const void *k);
void subtilis_hashtable_reset(subtilis_hashtable_t *h);
size_t subtilis_hashtable_sdbm(subtilis_hashtable_t *h, const void *k);
size_t subtilis_hashtable_djb2(subtilis_hashtable_t *h, const void *k);
bool subtilis_hashtable_string_equal(const void *k1, const void *k2);
#endif
| 2.109375 | 2 |
2024-11-18T22:12:02.961930+00:00 | 2023-07-03T01:27:29 | 5a33bb418e05bf4d8ede3954ae023cfdba22a18c | {
"blob_id": "5a33bb418e05bf4d8ede3954ae023cfdba22a18c",
"branch_name": "refs/heads/master",
"committer_date": "2023-07-03T01:27:29",
"content_id": "1d4f77e7a863d9235afdcc657bdc68aa1fa4c2aa",
"detected_licenses": [
"MIT"
],
"directory_id": "382a4dacbf7d6e6da096ddac660ba7a40af350cf",
"extension": "h",
"filename": "lv_hal_indev.h",
"fork_events_count": 293,
"gha_created_at": "2019-08-14T06:17:29",
"gha_event_created_at": "2023-08-31T05:18:44",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 202286916,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 7580,
"license": "MIT",
"license_type": "permissive",
"path": "/src/lvgl/src/lv_hal/lv_hal_indev.h",
"provenance": "stackv2-0087.json.gz:15626",
"repo_name": "Xinyuan-LilyGO/TTGO_TWatch_Library",
"revision_date": "2023-07-03T01:27:29",
"revision_id": "6a07f3762a4d11c8e5c0c2d6f9340ee4fdaa5fcb",
"snapshot_id": "84b1a580ad931caac7407bf110fde5b9248be3c4",
"src_encoding": "UTF-8",
"star_events_count": 776,
"url": "https://raw.githubusercontent.com/Xinyuan-LilyGO/TTGO_TWatch_Library/6a07f3762a4d11c8e5c0c2d6f9340ee4fdaa5fcb/src/lvgl/src/lv_hal/lv_hal_indev.h",
"visit_date": "2023-08-18T15:36:22.029944"
} | stackv2 | /**
* @file lv_hal_indev.h
*
* @description Input Device HAL interface layer header file
*
*/
#ifndef LV_HAL_INDEV_H
#define LV_HAL_INDEV_H
#ifdef __cplusplus
extern "C" {
#endif
/*********************
* INCLUDES
*********************/
#include "../lv_conf_internal.h"
#include <stdbool.h>
#include <stdint.h>
#include "../lv_misc/lv_area.h"
#include "../lv_misc/lv_task.h"
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
struct _lv_obj_t;
struct _disp_t;
struct _lv_indev_t;
struct _lv_indev_drv_t;
/** Possible input device types*/
enum {
LV_INDEV_TYPE_NONE, /**< Uninitialized state*/
LV_INDEV_TYPE_POINTER, /**< Touch pad, mouse, external button*/
LV_INDEV_TYPE_KEYPAD, /**< Keypad or keyboard*/
LV_INDEV_TYPE_BUTTON, /**< External (hardware button) which is assigned to a specific point of the
screen*/
LV_INDEV_TYPE_ENCODER, /**< Encoder with only Left, Right turn and a Button*/
};
typedef uint8_t lv_indev_type_t;
/** States for input devices*/
enum { LV_INDEV_STATE_REL = 0, LV_INDEV_STATE_PR };
typedef uint8_t lv_indev_state_t;
enum {
LV_DRAG_DIR_HOR = 0x1, /**< Object can be dragged horizontally. */
LV_DRAG_DIR_VER = 0x2, /**< Object can be dragged vertically. */
LV_DRAG_DIR_BOTH = 0x3, /**< Object can be dragged in all directions. */
LV_DRAG_DIR_ONE = 0x4, /**< Object can be dragged only one direction (the first move). */
};
typedef uint8_t lv_drag_dir_t;
enum {
LV_GESTURE_DIR_TOP, /**< Gesture dir up. */
LV_GESTURE_DIR_BOTTOM, /**< Gesture dir down. */
LV_GESTURE_DIR_LEFT, /**< Gesture dir left. */
LV_GESTURE_DIR_RIGHT, /**< Gesture dir right. */
};
typedef uint8_t lv_gesture_dir_t;
/** Data structure passed to an input driver to fill */
typedef struct {
lv_point_t point; /**< For LV_INDEV_TYPE_POINTER the currently pressed point*/
uint32_t key; /**< For LV_INDEV_TYPE_KEYPAD the currently pressed key*/
uint32_t btn_id; /**< For LV_INDEV_TYPE_BUTTON the currently pressed button*/
int16_t enc_diff; /**< For LV_INDEV_TYPE_ENCODER number of steps since the previous read*/
lv_indev_state_t state; /**< LV_INDEV_STATE_REL or LV_INDEV_STATE_PR*/
} lv_indev_data_t;
/** Initialized by the user and registered by 'lv_indev_add()'*/
typedef struct _lv_indev_drv_t {
/**< Input device type*/
lv_indev_type_t type;
/**< Function pointer to read input device data.
* Return 'true' if there is more data to be read (buffered).
* Most drivers can safely return 'false' */
bool (*read_cb)(struct _lv_indev_drv_t * indev_drv, lv_indev_data_t * data);
/** Called when an action happened on the input device.
* The second parameter is the event from `lv_event_t`*/
void (*feedback_cb)(struct _lv_indev_drv_t *, uint8_t);
#if LV_USE_USER_DATA
lv_indev_drv_user_data_t user_data;
#endif
/**< Pointer to the assigned display*/
struct _disp_t * disp;
/**< Task to read the periodically read the input device*/
lv_task_t * read_task;
/**< Number of pixels to slide before actually drag the object*/
uint8_t drag_limit;
/**< Drag throw slow-down in [%]. Greater value means faster slow-down */
uint8_t drag_throw;
/**< At least this difference should between two points to evaluate as gesture */
uint8_t gesture_min_velocity;
/**< At least this difference should be to send a gesture */
uint8_t gesture_limit;
/**< Long press time in milliseconds*/
uint16_t long_press_time;
/**< Repeated trigger period in long press [ms] */
uint16_t long_press_rep_time;
} lv_indev_drv_t;
/** Run time data of input devices
* Internally used by the library, you should not need to touch it.
*/
typedef struct _lv_indev_proc_t {
lv_indev_state_t state; /**< Current state of the input device. */
union {
struct {
/*Pointer and button data*/
lv_point_t act_point; /**< Current point of input device. */
lv_point_t last_point; /**< Last point of input device. */
lv_point_t vect; /**< Difference between `act_point` and `last_point`. */
lv_point_t drag_sum; /*Count the dragged pixels to check LV_INDEV_DEF_DRAG_LIMIT*/
lv_point_t drag_throw_vect;
struct _lv_obj_t * act_obj; /*The object being pressed*/
struct _lv_obj_t * last_obj; /*The last object which was pressed (used by drag_throw and
other post-release event)*/
struct _lv_obj_t * last_pressed; /*The lastly pressed object*/
lv_gesture_dir_t gesture_dir;
lv_point_t gesture_sum; /*Count the gesture pixels to check LV_INDEV_DEF_GESTURE_LIMIT*/
/*Flags*/
uint8_t drag_limit_out : 1;
uint8_t drag_in_prog : 1;
lv_drag_dir_t drag_dir : 3;
uint8_t gesture_sent : 1;
} pointer;
struct {
/*Keypad data*/
lv_indev_state_t last_state;
uint32_t last_key;
} keypad;
} types;
uint32_t pr_timestamp; /**< Pressed time stamp*/
uint32_t longpr_rep_timestamp; /**< Long press repeat time stamp*/
/*Flags*/
uint8_t long_pr_sent : 1;
uint8_t reset_query : 1;
uint8_t disabled : 1;
uint8_t wait_until_release : 1;
} lv_indev_proc_t;
struct _lv_obj_t;
struct _lv_group_t;
/** The main input device descriptor with driver, runtime data ('proc') and some additional
* information*/
typedef struct _lv_indev_t {
lv_indev_drv_t driver;
lv_indev_proc_t proc;
struct _lv_obj_t * cursor; /**< Cursor for LV_INPUT_TYPE_POINTER*/
struct _lv_group_t * group; /**< Keypad destination group*/
const lv_point_t * btn_points; /**< Array points assigned to the button ()screen will be pressed
here by the buttons*/
} lv_indev_t;
/**********************
* GLOBAL PROTOTYPES
**********************/
/**
* Initialize an input device driver with default values.
* It is used to surly have known values in the fields ant not memory junk.
* After it you can set the fields.
* @param driver pointer to driver variable to initialize
*/
void lv_indev_drv_init(lv_indev_drv_t * driver);
/**
* Register an initialized input device driver.
* @param driver pointer to an initialized 'lv_indev_drv_t' variable (can be local variable)
* @return pointer to the new input device or NULL on error
*/
lv_indev_t * lv_indev_drv_register(lv_indev_drv_t * driver);
/**
* Update the driver in run time.
* @param indev pointer to a input device. (return value of `lv_indev_drv_register`)
* @param new_drv pointer to the new driver
*/
void lv_indev_drv_update(lv_indev_t * indev, lv_indev_drv_t * new_drv);
/**
* Get the next input device.
* @param indev pointer to the current input device. NULL to initialize.
* @return the next input devise or NULL if no more. Give the first input device when the parameter
* is NULL
*/
lv_indev_t * lv_indev_get_next(lv_indev_t * indev);
/**
* Read data from an input device.
* @param indev pointer to an input device
* @param data input device will write its data here
* @return false: no more data; true: there more data to read (buffered)
*/
bool _lv_indev_read(lv_indev_t * indev, lv_indev_data_t * data);
/**********************
* MACROS
**********************/
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif
| 2.484375 | 2 |
2024-11-18T22:12:03.240657+00:00 | 2014-10-31T15:24:17 | a54c97a075f47dc88263a8ce99d24fa50e69efce | {
"blob_id": "a54c97a075f47dc88263a8ce99d24fa50e69efce",
"branch_name": "refs/heads/master",
"committer_date": "2014-10-31T15:24:17",
"content_id": "4a9efd6cc7eca66227284ba3b3ba89a467c1e21f",
"detected_licenses": [
"ISC"
],
"directory_id": "9c0b23ec6942fd29b6e05e0458a0cd04b9ea38dd",
"extension": "c",
"filename": "aewm_event.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 16690,
"license": "ISC",
"license_type": "permissive",
"path": "/aewm_event.c",
"provenance": "stackv2-0087.json.gz:16012",
"repo_name": "r0j3r/aewm-fork",
"revision_date": "2014-10-31T15:24:17",
"revision_id": "36fc577b5bedcb9eb54096b23de6273fac061994",
"snapshot_id": "2051e08134141b287bd3975065ce8e9f6ecc8362",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/r0j3r/aewm-fork/36fc577b5bedcb9eb54096b23de6273fac061994/aewm_event.c",
"visit_date": "2020-06-02T10:57:49.631446"
} | stackv2 | /*-
* aewm: Copyright (c) 1998-2008 Decklin Foster. See README for license.
*/
#include <stdlib.h>
#include <stdio.h>
#include <sys/select.h>
#include <X11/Xatom.h>
#ifdef SHAPE
#include <X11/extensions/shape.h>
#endif
#include "aewm.h"
static void ev_btn_press(XButtonEvent *);
static void ev_btn_release(XButtonEvent *);
static void ev_cfg_req(XConfigureRequestEvent *);
static void ev_circ_req(XCirculateRequestEvent *);
static void ev_map_req(XMapRequestEvent *);
static void ev_unmap(XUnmapEvent *);
static void ev_destroy(XDestroyWindowEvent *);
static void ev_message(XClientMessageEvent *);
static void ev_prop_change(XPropertyEvent *);
static void ev_enter(XCrossingEvent *);
static void ev_cmap_change(XColormapEvent *);
static void ev_expose(XExposeEvent *);
#ifdef SHAPE
static void ev_shape_change(XShapeEvent *);
#endif
static void desk_switch_to(int new_desk);
/*
* This is a big hack to avoid blocking in Xlib, where we cannot safely
* handle signals. We use only the nonblocking function XCheckMaskEvent
* and do our own select() on the connection before waking up to hopefully
* grab the event that came in.
*
* If some other client barfed or the X server has a bug and invalid
* data is available on our connection, when Xlib processes the
* outstanding data on the connection, it will tell us no events are
* available, and we'll go back to sleep.
*
* If we do recieve a signal, we will wake up from select() and
* immediately fail. The signal handler will have set flags, and our
* caller will handle that error by aborting an operation or exiting
* entirely. (This is the reason for this function -- Xlib will restart
* a blocking call, leaving us unable to do anything about the signal
* flags).
*
* Because Xlib sucks, we can't use a nonblocking call without a mask,
* and so we simulate it by checking XPending before using XNextEvent
* (which blocks).
*
* For obvious reasons, this really ought to call pselect(), but
* it's not portable. Even if we did that, the signal could still be
* delivered while we're in Xlib. Basically, we are screwed until I port
* this to XCB. (In the meantime, I have at least never actually seen
* this race condition happen in real life.)
*/
Bool event_get_next(long mask, XEvent *ev)
{
int fd = ConnectionNumber(dpy);
fd_set rd;
while (!(mask ? XCheckMaskEvent(dpy, mask, ev)
: (XPending(dpy) && XNextEvent(dpy, ev) == Success))) {
FD_ZERO(&rd);
FD_SET(fd, &rd);
select(fd + 1, &rd, NULL, NULL, NULL);
if (timed_out || killed)
return False;
}
return True;
}
/* By the time we get an event, there is no guarantee the window still
* exists. Therefore ev_print might cause errors. We'll just live with it. */
void ev_loop(void)
{
XEvent ev;
while (event_get_next(NoEventMask, &ev)) {
IF_DEBUG(ev_print(ev));
switch (ev.type) {
case ButtonPress: ev_btn_press(&ev.xbutton); break;
case ButtonRelease: ev_btn_release(&ev.xbutton); break;
case ConfigureRequest: ev_cfg_req(&ev.xconfigurerequest); break;
case CirculateRequest: ev_circ_req(&ev.xcirculaterequest); break;
case MapRequest: ev_map_req(&ev.xmaprequest); break;
case UnmapNotify: ev_unmap(&ev.xunmap); break;
case DestroyNotify: ev_destroy(&ev.xdestroywindow); break;
case ClientMessage: ev_message(&ev.xclient); break;
case ColormapNotify: ev_cmap_change(&ev.xcolormap); break;
case PropertyNotify: ev_prop_change(&ev.xproperty); break;
case EnterNotify: ev_enter(&ev.xcrossing); break;
case Expose: ev_expose(&ev.xexpose); break;
#ifdef SHAPE
default:
if (shape && ev.type == shape_event)
ev_shape_change((XShapeEvent *)&ev);
break;
#endif
}
}
}
/* Someone clicked a button. If they clicked on a window, we want the button
* press, but if they clicked on the root, we're only interested in the button
* release. Thus, two functions.
*
* If it was on the root, we get the click by default. If it's on a window
* frame, we get it as well. If it's on a client window, it may still fall
* through to us if the client doesn't select for mouse-click events. The
* upshot of this is that you should be able to click on the blank part of a
* GTK window with Button2 to move it. */
static void ev_btn_press(XButtonEvent *e)
{
Client *c;
pressed = e->window;
if (FIND_CTX(e->window, frame_tab, &c))
cli_pressed(c, e->x, e->y, e->button);
}
static void ev_btn_release(XButtonEvent *e)
{
if (pressed == root && e->window == root) {
IF_DEBUG(cli_list());
switch (e->button) {
case Button1: fork_exec(opt_new[0]); break;
case Button2: fork_exec(opt_new[1]); break;
case Button3: fork_exec(opt_new[2]); break;
case Button4: fork_exec(opt_new[3]); break;
case Button5: fork_exec(opt_new[4]); break;
}
pressed = None;
}
}
/* Because we are redirecting the root window, we get ConfigureRequest events
* from both clients we're handling and ones that we aren't. For clients we
* manage, we need to adjust the frame and the client window, and for
* unmanaged windows we have to pass along everything unchanged.
*
* Most of the assignments here are going to be garbage, but only the ones
* that are masked in by e->value_mask will be looked at by the X server. */
static void ev_cfg_req(XConfigureRequestEvent *e)
{
Client *c;
Geom f;
XWindowChanges wc;
wc.x = e->x;
wc.y = e->y;
wc.width = e->width;
wc.height = e->height;
wc.sibling = e->above;
wc.stack_mode = e->detail;
if (FIND_CTX(e->window, cli_tab, &c)) {
if (!c->cfg_lock) {
if (c->zoomed && e->value_mask & (CWX|CWY|CWWidth|CWHeight)) {
c->zoomed = False;
atom_del(c->win, net_wm_state, XA_ATOM, net_wm_state_mv);
atom_del(c->win, net_wm_state, XA_ATOM, net_wm_state_mh);
}
if (e->value_mask & CWX) c->geom.x = e->x;
if (e->value_mask & CWY) c->geom.y = e->y;
if (e->value_mask & CWWidth) c->geom.w = e->width;
if (e->value_mask & CWHeight) c->geom.h = e->height;
IF_DEBUG(cli_print(c, "<cfg>"));
}
#ifdef SHAPE
if (e->value_mask & (CWWidth|CWHeight)) cli_shape_set(c);
#endif
cli_send_cfg(c);
wc.x = CX(c);
wc.y = CY(c);
XConfigureWindow(dpy, e->window, e->value_mask, &wc);
f = cli_frame_geom(c, c->geom);
wc.x = f.x;
wc.y = f.y;
wc.width = f.w;
wc.height = f.h;
wc.border_width = BW(c);
XConfigureWindow(dpy, c->frame, e->value_mask, &wc);
} else {
XConfigureWindow(dpy, e->window, e->value_mask, &wc);
}
}
/* The only window that we will circulate children for is the root (because
* nothing else would make sense). After a client requests that the root's
* children be circulated, the server will determine which window needs to be
* raised or lowered, and so all we have to do is make it so. */
static void ev_circ_req(XCirculateRequestEvent *e)
{
if (e->parent == root) {
if (e->place == PlaceOnBottom)
XLowerWindow(dpy, e->window);
else
XRaiseWindow(dpy, e->window);
}
}
/* Two possibilities if a client is asking to be mapped. One is that it's a new
* window, so we handle that if it isn't in our clients list anywhere. The
* other is that it already exists and wants to de-iconify, which is simple to
* take care of. */
static void ev_map_req(XMapRequestEvent *e)
{
Client *c;
if (FIND_CTX(e->window, cli_tab, &c)) {
cli_set_iconified(c, NormalState);
} else {
c = cli_new(e->window);
cli_map(c);
win_list_update();
}
}
/* We don't get to intercept Unmap events, so this is post mortem. If we
* caused the unmap ourselves earlier (explictly or by remapping), we will
* have set c->ign_unmap. If not, time to destroy the client.
*
* Because most clients unmap and destroy themselves at once, they're gone
* before we even get the Unmap event, never mind the Destroy one. Therefore
* we must be extra careful in do_remove. */
static void ev_unmap(XUnmapEvent *e)
{
Client *c;
if (FIND_CTX(e->window, cli_tab, &c)) {
if (c->ign_unmap) c->ign_unmap = False;
else cli_withdraw(c);
}
}
/* But a window can also go away when it's not mapped, in which case there is
* no Unmap event. */
static void ev_destroy(XDestroyWindowEvent *e)
{
Client *c;
if (FIND_CTX(e->window, cli_tab, &c))
cli_withdraw(c);
}
/* If a client wants to manipulate itself or another window it must send a
* special kind of ClientMessage. As of right now, this only responds to the
* ICCCM iconify message, but there are more in the EWMH that will be added
* later. */
static void ev_message(XClientMessageEvent *e)
{
Client *c;
if (e->window == root) {
if (e->message_type == net_cur_desk && e->format == 32)
desk_switch_to(e->data.l[0]);
else if (e->message_type == net_num_desks && e->format == 32)
ndesks = e->data.l[0];
} else if (FIND_CTX(e->window, cli_tab, &c)) {
if (e->message_type == wm_change_state && e->format == 32 &&
e->data.l[0] == IconicState) {
cli_set_iconified(c, IconicState);
} else if (e->message_type == net_active_window && e->format == 32) {
c->desk = cur_desk;
cli_set_iconified(c, NormalState);
cli_raise(c);
} else if (e->message_type == net_close_window && e->format == 32) {
cli_req_close(c);
}
}
}
/* If we have something copied to a variable, or displayed on the screen, make
* sure it is up to date. If redrawing the name is necessary, clear the window
* because Xft uses alpha rendering. */
static void ev_prop_change(XPropertyEvent *e)
{
Client *c;
long supplied;
if (FIND_CTX(e->window, cli_tab, &c)) {
if (e->atom == XA_WM_NAME || e->atom == net_wm_name) {
if (c->name) XFree(c->name);
c->name = win_name_get(c->win);
cli_frame_redraw(c);
} else if (e->atom == XA_WM_NORMAL_HINTS) {
XGetWMNormalHints(dpy, c->win, &c->size, &supplied);
} else if (e->atom == net_wm_state) {
cli_state_apply(c);
} else if (e->atom == net_wm_desk) {
if (atom_get(c->win, net_wm_desk, XA_CARDINAL, 0, &c->desk, 1,
NULL))
cli_map_apply(c);
}
}
}
/* Lazy focus-follows-mouse and colormap-follows-mouse policy. This does not,
* however, prevent focus stealing (it's lazy). It is not very efficient
* either; we can get a lot of enter events at once when flipping through a
* window stack on startup/desktop change. */
static void ev_enter(XCrossingEvent *e)
{
Client *c;
if (FIND_CTX(e->window, frame_tab, &c))
cli_focus(c);
}
/* More colormap policy: when a client installs a new colormap on itself, set
* the display's colormap to that. We do this even if it's not focused. */
static void ev_cmap_change(XColormapEvent *e)
{
Client *c;
if (e->new && FIND_CTX(e->window, cli_tab, &c)) {
c->cmap = e->colormap;
XInstallColormap(dpy, c->cmap);
}
}
/*
* We care about frame exposes for two reasons: redrawing the grip,
* and deciding when a client has finished mapping.
*
* Before the frame is initially exposed, we ignore ConfigureRequests.
* These are almost always from poorly-behaved clients that attempt
* to override the user's placement. Once the frame has appeared, it
* is generally safe to let clients move themselves. So we set a
* flag here for that.
*
* We will usually get multiple events at once (for each obscured
* region), so we don't do anything unless the count of remaining
* exposes is 0.
*/
static void ev_expose(XExposeEvent *e)
{
Client *c;
if (e->count == 0 && FIND_CTX(e->window, frame_tab, &c)) {
cli_frame_redraw(c);
c->cfg_lock = False;
}
}
#ifdef SHAPE
static void ev_shape_change(XShapeEvent *e)
{
Client *c;
if (FIND_CTX(e->window, cli_tab, &c))
cli_shape_set(c);
}
#endif
static void desk_switch_to(int new_desk)
{
unsigned int i;
Client *c;
cur_desk = new_desk;
atom_set(root, net_cur_desk, XA_CARDINAL, &cur_desk, 1);
for (i = 0; i < nwins; i++)
if (FIND_CTX(wins[i], frame_tab, &c) && !CLI_ON_CUR_DESK(c))
cli_hide(c);
while (i--)
if (FIND_CTX(wins[i], frame_tab, &c) && CLI_ON_CUR_DESK(c)
&& win_state_get(c->win) == NormalState)
cli_show(c);
}
#ifdef DEBUG
void ev_print(XEvent e)
{
Window w;
char *n;
switch (e.type) {
case ButtonPress: n = "BtnPress"; w = e.xbutton.window; break;
case ButtonRelease: n = "BtnRel"; w = e.xbutton.window; break;
case ClientMessage: n = "CliMsg"; w = e.xclient.window; break;
case ColormapNotify: n = "CmapNfy"; w = e.xcolormap.window; break;
case ConfigureNotify: n = "CfgNfy"; w = e.xconfigure.window; break;
case ConfigureRequest: n = "CfgReq"; w = e.xconfigurerequest.window;
break;
case CirculateRequest: n = "CircReq"; w = e.xcirculaterequest.window;
break;
case CreateNotify: n = "CreatNfy"; w = e.xcreatewindow.window; break;
case DestroyNotify: n = "DestrNfy"; w = e.xdestroywindow.window; break;
case EnterNotify: n = "EnterNfy"; w = e.xcrossing.window; break;
case Expose: n = "Expose"; w = e.xexpose.window; break;
case MapNotify: n = "MapNfy"; w = e.xmap.window; break;
case MapRequest: n = "MapReq"; w = e.xmaprequest.window; break;
case MappingNotify: n = "MapnNfy"; w = e.xmapping.window; break;
case MotionNotify: n = "MotiNfy"; w = e.xmotion.window; break;
case PropertyNotify: n = "PropNfy"; w = e.xproperty.window; break;
case ReparentNotify: n = "ParNfy"; w = e.xreparent.window; break;
case ResizeRequest: n = "ResizReq"; w = e.xresizerequest.window; break;
case UnmapNotify: n = "UnmapNfy"; w = e.xunmap.window; break;
default:
#ifdef SHAPE
if (shape && e.type == shape_event) {
n = "ShapeNfy"; w = ((XShapeEvent *)&e)->window;
break;
}
#endif
n = "?"; w = None; break;
}
win_print(w, n);
}
const char *cli_grav_str(Client *c)
{
if (!(c->size.flags & PWinGravity))
return "nw";
switch (c->size.win_gravity) {
case UnmapGravity: return "U";
case NorthWestGravity: return "NW";
case NorthGravity: return "N";
case NorthEastGravity: return "NE";
case WestGravity: return "W";
case CenterGravity: return "C";
case EastGravity: return "E";
case SouthWestGravity: return "SW";
case SouthGravity: return "S";
case SouthEastGravity: return "SE";
case StaticGravity: return "X";
default: return "?";
}
}
const char *cli_state_str(Client *c)
{
switch (win_state_get(c->win)) {
case NormalState: return "Nrm";
case IconicState: return "Ico";
case WithdrawnState: return "Wdr";
default: return "?";
}
}
void cli_print(Client *c, const char *label)
{
const char *s = cli_state_str(c);
printf("%9.9s: %#010lx [ ] %-32.32s ", label, c->win, c->name);
if (c->desk == DESK_ALL) printf("*");
else printf("%ld", c->desk);
printf(" %ldx%ld %s", c->geom.w, c->geom.h, s);
if (c->trans) printf(" tr");
if (c->shaded) printf(" sh");
if (c->zoomed) printf(" zm");
if (c->ign_unmap) printf(" ig");
printf("\n");
}
void win_print(Window w, const char *label)
{
Client *c;
if (w == root)
printf("%9.9s: %#010lx [r]\n", label, w);
else if (FIND_CTX(w, cli_tab, &c))
cli_print(c, label);
else if (FIND_CTX(w, frame_tab, &c))
printf("%9.9s: %#010lx [f] %-32.32s +%ld+%ld %s\n", label, w, c->name,
c->geom.x, c->geom.y, cli_grav_str(c));
else
printf("%9.9s: %#010lx [?]\n", label, w);
}
void cli_list(void)
{
Client *c;
unsigned int i;
for (i = 0; i < nwins; i++) {
if (FIND_CTX(wins[i], frame_tab, &c)) {
cli_print(c, "<list>");
win_print(c->frame, "<list>");
}
}
}
#endif
| 2.125 | 2 |
2024-11-18T22:12:03.297145+00:00 | 2020-08-13T08:27:25 | 24cebf6c0f824fe0c1a476b659cfbfefa8100033 | {
"blob_id": "24cebf6c0f824fe0c1a476b659cfbfefa8100033",
"branch_name": "refs/heads/master",
"committer_date": "2020-08-13T08:27:25",
"content_id": "71027b0a774bc87ebf5d8ce83dbc17f1920d75e5",
"detected_licenses": [
"BSL-1.0"
],
"directory_id": "9f8c6878ffbce4dbf985d6564a37aa1c8086d038",
"extension": "c",
"filename": "mib_cqi_pacer.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 277918328,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2359,
"license": "BSL-1.0",
"license_type": "permissive",
"path": "/mib_cqi_pacer.c",
"provenance": "stackv2-0087.json.gz:16141",
"repo_name": "mirazabal/Dynamic-buffer-TMC",
"revision_date": "2020-08-13T08:27:25",
"revision_id": "617e2196b5bf9718ce906da055cd6e8779a58221",
"snapshot_id": "28495479d71c0050781b00ffaa3bc57ab5a576cb",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/mirazabal/Dynamic-buffer-TMC/617e2196b5bf9718ce906da055cd6e8779a58221/mib_cqi_pacer.c",
"visit_date": "2022-12-02T10:28:05.545100"
} | stackv2 | #include "mib_cqi_pacer.h"
#include "mib_time.h"
#include <assert.h>
#include <stdio.h>
void mib_cqi_pacer_set(struct mib_cqi_pacer* p, int32_t channel_buffer, int32_t remaining)
{
assert(channel_buffer > -1 && remaining > -1);
printf("Into mib_cqi_pacer_set, channel_buffer = %d, remaining = %d \n",channel_buffer, remaining);
pthread_mutex_lock(&p->lock);
p->pack_to_send = channel_buffer > remaining ? channel_buffer - remaining : 1;
pthread_mutex_unlock(&p->lock);
printf("Packets to send per TTI = %u\n", p->pack_to_send);
printf("Changed at 11th case\n");
p->packets_tx = 0;
p->slack_last_time = mib_get_time_us();
}
uint32_t mib_cqi_pacer_get_total_tx(struct mib_cqi_pacer* p)
{
return p->pack_to_send;
}
uint32_t mib_cqi_pacer_get_opt(struct mib_cqi_pacer* p)
{
// if(p->remaining_to_send <= 0){
// printf("Into mib_cqi_pacer_get_opt with remaining_to_send = %d \n", p->remaining_to_send);
// return 0;
// }
int64_t now = mib_get_time_us();
int64_t time_ = now - p->slack_last_time;
float percentage_time = time_ / p->TTI + 0.33;
printf("percentage_time = %f, time_ = %ld \n", percentage_time, time_);
if(percentage_time > 6){
if(p->pack_to_send > 5){
pthread_mutex_lock(&p->lock);
p->pack_to_send = 0.75 * (float)p->pack_to_send;
pthread_mutex_unlock(&p->lock);
}
}
uint32_t theoretical_sent = (float)(p->pack_to_send) * percentage_time;
uint32_t ret_val = theoretical_sent > p->packets_tx ? theoretical_sent - p->packets_tx : 0;
//i if(now < p->slack_last_time + 0.5*p->TTI){
// ret_val = mib_clamp(p, p->pack_to_send / 10);
// } else if (now < p->slack_last_time + 0.75*p->TTI){
// ret_val = mib_clamp(p, 2 * p->pack_to_send / 10);
// } else {
// ret_val = p->remaining_to_send;
// }
printf("Into mib_cqi_pacer_get_opt, ret_val = %u, tx = %u theoretical = %u \n", ret_val, p->packets_tx, theoretical_sent);
return ret_val;
}
void mib_cqi_pacer_init(struct mib_cqi_pacer* p)
{
p->slack_last_time = mib_get_time_us();
p->pack_to_send = 5;
p->TTI = 10000.0;
p->packets_tx = 0;
pthread_mutex_init(&p->lock, NULL);
}
void mib_cqi_pacer_enqueue(struct mib_cqi_pacer* p, uint32_t number)
{
p->packets_tx += number;
printf("Into mib_cqi_pacer_enqueue number = %u, packet already sent = %d \n", number, p->packets_tx);
}
| 2.6875 | 3 |
2024-11-18T22:12:03.350379+00:00 | 2013-11-10T12:35:49 | 8615fb8843ef9ce745effb854081a2baaedf5749 | {
"blob_id": "8615fb8843ef9ce745effb854081a2baaedf5749",
"branch_name": "refs/heads/master",
"committer_date": "2013-11-10T12:35:49",
"content_id": "2d292272346944fd47221b20300a0f1cb6e0c6b6",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "2b80fa4cda75a5b45d40999d8af71a7349b792bd",
"extension": "h",
"filename": "darts.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": 8272,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/src/darts.h",
"provenance": "stackv2-0087.json.gz:16269",
"repo_name": "kyoungho-shin/libdarts",
"revision_date": "2013-11-10T12:35:49",
"revision_id": "3f7ffbadf1b917f0797c109434eb03d9f835819e",
"snapshot_id": "545bbe43d11952113f86a02e86ee6377882de004",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/kyoungho-shin/libdarts/3f7ffbadf1b917f0797c109434eb03d9f835819e/src/darts.h",
"visit_date": "2020-04-30T07:33:20.509247"
} | stackv2 | #ifndef __LIBDARTS_H__
#define __LIBDARTS_H__
#ifdef __cplusplus
extern "C" {
#endif
#include <stddef.h>
/**
Type of double array instance.
*/
typedef void* darts_t;
/**
Type of double array trie key.
*/
typedef char darts_key_type;
/**
Type of double array trie value.
*/
typedef int darts_value_type;
/*
<darts_result_pair_type> enables applications to get the lengths of the
matched keys in addition to the values.
*/
typedef struct {
darts_value_type value;
size_t length;
} darts_result_pair_type;
/**
darts_new() constructs an instance of double array trie.
*/
darts_t darts_new(void);
/**
darts_new() frees an allocated double array trie.
*/
void darts_delete(darts_t darts);
/**
darts_error() returns the internal error. It could be NULL if there is
no error.
*/
const char* darts_error(const darts_t darts);
/**
Returns version string of Darts.
*/
const char* darts_version(void);
/**
darts_set_array() calls darts_clear() in order to free memory allocated to the
old array and then sets a new array. This function is useful to set a memory-
mapped array.
Note that the array set by darts_set_array() is not freed in
darts_clear() and darts_delete().
darts_set_array() can also set the size of the new array but the size is not
used in search methods. So it works well even if the size is 0 or omitted.
Remember that darts_size() and darts_total_size() returns 0 in such a case.
*/
void darts_set_array(darts_t darts,
const void *ptr,
size_t size);
/**
darts_array() returns a pointer to the array of units.
*/
const void* darts_array(const darts_t darts);
/**
darts_clear() frees memory allocated to units and then initializes member
variables with 0 and NULLs. Note that darts_clear() does not free memory if
the array of units was set by darts_clear(). In such a case, `array_' is not
NULL and `buf_' is NULL.
*/
void darts_clear(darts_t darts);
/**
unit_size() returns the size of each unit. The size must be 4 bytes.
*/
size_t darts_unit_size(const darts_t darts);
/**
size() returns the number of units. It can be 0 if set_array() is used.
*/
size_t darts_size(const darts_t darts);
/**
total_size() returns the number of bytes allocated to the array of units.
It can be 0 if set_array() is used.
*/
size_t darts_total_size(const darts_t darts);
/**
nonzero_size() exists for compatibility. It always returns the number of
units because it takes long time to count the number of non-zero units.
*/
size_t darts_nonzero_size(const darts_t darts);
/**
darts_build() constructs a dictionary from given key-value pairs. If `lengths'
is NULL, `keys' is handled as an array of zero-terminated strings. If
`values' is NULL, the index in `keys' is associated with each key, i.e.
the ith key has (i - 1) as its value.
Note that the key-value pairs must be arranged in key order and the values
must not be negative. Also, if there are duplicate keys, only the first
pair will be stored in the resultant dictionary.
`progress_func' is a pointer to a callback function. If it is not NULL,
it will be called in darts_build() so that the caller can check the progress of
dictionary construction.
The return value of darts_build() is 0, and it indicates the success of the
operation. Otherwise, get error message from darts_error().
darts_build() uses another construction algorithm if `values' is not NULL. In
this case, Darts-clone uses a Directed Acyclic Word Graph (DAWG) instead
of a trie because a DAWG is likely to be more compact than a trie.
*/
int darts_build(darts_t darts,
size_t num_keys,
const darts_key_type*const* keys,
const size_t* lengths,
const darts_value_type* values,
int (*progress_func)(size_t, size_t));
/**
darts_open() reads an array of units from the specified file. And if it goes
well, the old array will be freed and replaced with the new array read
from the file. `offset' specifies the number of bytes to be skipped before
reading an array. `size' specifies the number of bytes to be read from the
file. If the `size' is 0, the whole file will be read.
darts_open() returns 0 iff the operation succeeds. Otherwise,
get error message from darts_error().
*/
int darts_open(darts_t darts,
const char* file_name,
const char* mode,
size_t offset,
size_t size);
/**
darts_save() writes the array of units into the specified file. `offset'
specifies the number of bytes to be skipped before writing the array.
darts_save() returns 0 iff the operation succeeds. Otherwise, it returns a
non-zero value.
*/
int darts_save(const darts_t darts,
const char* file_name,
const char* mode,
size_t offset);
/**
darts_exact_match_search() tests whether the given key exists or not, and
if it exists, its value and length are returned. Otherwise, the
value and the length of return value are set to -1 and 0 respectively.
Note that if `length' is 0, `key' is handled as a zero-terminated string.
`node_pos' specifies the start position of matching. This argument enables
the combination of exactMatchSearch() and traverse(). For example, if you
want to test "xyzA", "xyzBC", and "xyzDE", you can use traverse() to get
the node position corresponding to "xyz" and then you can use
exactMatchSearch() to test "A", "BC", and "DE" from that position.
Note that the length of `result' indicates the length from the `node_pos'.
In the above example, the lengths are { 1, 2, 2 }, not { 4, 5, 5 }.
*/
darts_value_type darts_exact_match_search(const darts_t darts,
const darts_key_type* key,
size_t length,
size_t node_pos);
/**
darts_exact_match_search_pair() returns a darts_result_pair instead.
*/
darts_result_pair_type darts_exact_match_search_pair(const darts_t darts,
const darts_key_type* key,
size_t length,
size_t node_pos);
/**
darts_common_prefix_search() searches for keys which match a prefix of the
given string. If `length' is 0, `key' is handled as a zero-terminated string.
The values and the lengths of at most `max_num_results' matched keys are
stored in `results'. commonPrefixSearch() returns the number of matched
keys. Note that the return value can be larger than `max_num_results' if
there are more than `max_num_results' matches. If you want to get all the
results, allocate more spaces and call commonPrefixSearch() again.
`node_pos' works as well as in exactMatchSearch().
*/
size_t darts_common_prefix_search(const darts_t darts,
const darts_key_type* key,
darts_result_pair_type* results,
size_t max_num_results,
size_t length,
size_t node_pos);
/**
In Darts-clone, a dictionary is a deterministic finite-state automaton
(DFA) and traverse() tests transitions on the DFA. The initial state is
`node_pos' and traverse() chooses transitions labeled key[key_pos],
key[key_pos + 1], ... in order. If there is not a transition labeled
key[key_pos + i], traverse() terminates the transitions at that state and
returns -2. Otherwise, traverse() ends without a termination and returns
-1 or a nonnegative value, -1 indicates that the final state was not an
accept state. When a nonnegative value is returned, it is the value
associated with the final accept state. That is, traverse() returns the
value associated with the given key if it exists. Note that traverse()
updates `node_pos' and `key_pos' after each transition.
*/
darts_value_type darts_traverse(const darts_t darts,
const darts_key_type* key,
size_t* node_pos,
size_t* key_pos,
size_t length);
#ifdef __cplusplus
}
#endif
#endif
| 2.46875 | 2 |
2024-11-18T22:12:03.426611+00:00 | 2017-11-16T02:03:04 | efc9d5fb9676219a13ee31a22a7d14e6203878de | {
"blob_id": "efc9d5fb9676219a13ee31a22a7d14e6203878de",
"branch_name": "refs/heads/master",
"committer_date": "2017-11-16T02:03:04",
"content_id": "77f6f88926c0b82e8f7e3e34007a08c9c96e5e90",
"detected_licenses": [
"MIT"
],
"directory_id": "e9c413fcad1e041b3a930ec7709985ff9bc5d52e",
"extension": "h",
"filename": "CppLibrary.h",
"fork_events_count": 0,
"gha_created_at": "2017-11-15T23:19:39",
"gha_event_created_at": "2017-11-16T02:03:06",
"gha_language": "C#",
"gha_license_id": null,
"github_id": 110898093,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1117,
"license": "MIT",
"license_type": "permissive",
"path": "/CppLibrary/CppLibrary/CppLibrary.h",
"provenance": "stackv2-0087.json.gz:16398",
"repo_name": "rogancarr/DotNetCppExample",
"revision_date": "2017-11-16T02:03:04",
"revision_id": "787e41086e2bdbeb973501457572d560e3a7d79b",
"snapshot_id": "20d377a7480e78d64f16e3313220bc6574371345",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/rogancarr/DotNetCppExample/787e41086e2bdbeb973501457572d560e3a7d79b/CppLibrary/CppLibrary/CppLibrary.h",
"visit_date": "2021-08-14T14:44:04.755143"
} | stackv2 | // CppLibrary.h - Contains declarations of functions and delegates
#pragma once
#ifndef _WINDOWS
#define __declspec(dllexport)
#endif
#ifdef CPPLIBRARY_EXPORTS
#define CPPLIBRARY_API __declspec(dllexport)
#else
#define CPPLIBRARY_API __declspec(dllimport)
#endif
// Get the number 1
extern "C" CPPLIBRARY_API int get_one();
// Add two numbers
extern "C" CPPLIBRARY_API int add_two_numbers(int i, int j);
// Call a function with two integers
typedef int(*TwoIntReduceDelegate)(int a, int b);
extern "C" CPPLIBRARY_API int external_call(TwoIntReduceDelegate addTwoNumbers, int i, int j);
// Call a function that reduces an array
typedef int(*ReduceIntArrayDelegate)(int v[], int v_size);
extern "C" CPPLIBRARY_API int external_reduce(ReduceIntArrayDelegate reduceFunc, int i[], int i_size);
// Call a function that reduces an array using a supplied C++ function
typedef int(*ReduceIntArrayWithFuncDelegate)(int v[], int v_size, int(*ReduceIntArray)(int v[], int v_size));
extern "C" CPPLIBRARY_API int external_reduce_with_callback(ReduceIntArrayWithFuncDelegate reduceHostFunc, int i[], int i_size);
| 2.265625 | 2 |
2024-11-18T22:12:04.110760+00:00 | 2017-09-14T23:03:28 | 5c42de4d6b10964d8e7ad830a94b316c4fa68ba3 | {
"blob_id": "5c42de4d6b10964d8e7ad830a94b316c4fa68ba3",
"branch_name": "refs/heads/master",
"committer_date": "2017-09-14T23:03:28",
"content_id": "d8a7ba68f81df8d24235a35521f91d1b919ab61c",
"detected_licenses": [
"MIT"
],
"directory_id": "8cfd4161acdef6a4bd48f69f009b980ff6681738",
"extension": "h",
"filename": "flow.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": 2302,
"license": "MIT",
"license_type": "permissive",
"path": "/src/flow.h",
"provenance": "stackv2-0087.json.gz:16785",
"repo_name": "praveenmunagapati/dmr_c",
"revision_date": "2017-09-14T23:03:28",
"revision_id": "52a8904b40c06dd2d01f7c3a07f76955a80ee3b6",
"snapshot_id": "033273f0cc54ae68a4071b1fb8281b4d66ee3a6e",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/praveenmunagapati/dmr_c/52a8904b40c06dd2d01f7c3a07f76955a80ee3b6/src/flow.h",
"visit_date": "2021-06-29T00:25:48.574140"
} | stackv2 | #ifndef DMR_C_FLOW_H
#define DMR_C_FLOW_H
/*
* Flow - walk the linearized flowgraph, simplifying it as we
* go along.
*
* Copyright (C) 2004 Linus Torvalds
*/
#include <lib.h>
#ifdef __cplusplus
extern "C" {
#endif
#define REPEAT_CSE 1
#define REPEAT_SYMBOL_CLEANUP 2
#define REPEAT_CFG_CLEANUP 3
struct entrypoint;
struct instruction;
extern int dmrC_simplify_flow(struct dmr_C *C, struct entrypoint *ep);
extern void dmrC_simplify_symbol_usage(struct dmr_C *C, struct entrypoint *ep);
extern void dmrC_simplify_memops(struct dmr_C *C, struct entrypoint *ep);
extern void dmrC_pack_basic_blocks(struct dmr_C *C, struct entrypoint *ep);
extern void dmrC_convert_instruction_target(struct dmr_C *C, struct instruction *insn, pseudo_t src);
extern void dmrC_cleanup_and_cse(struct dmr_C *C, struct entrypoint *ep);
extern int dmrC_simplify_instruction(struct dmr_C *C, struct instruction *);
extern void dmrC_kill_bb(struct dmr_C *C, struct basic_block *);
extern void dmrC_kill_use(struct dmr_C *C, pseudo_t *usep);
extern void dmrC_remove_use(struct dmr_C *C, pseudo_t *);
extern void dmrC_kill_insn(struct dmr_C *C, struct instruction *, int force);
static inline void dmrC_kill_instruction(struct dmr_C *C, struct instruction *insn)
{
dmrC_kill_insn(C, insn, 0);
}
static inline void dmrC_kill_instruction_force(struct dmr_C *C, struct instruction *insn)
{
dmrC_kill_insn(C, insn, 1);
}
extern void dmrC_kill_unreachable_bbs(struct dmr_C *C, struct entrypoint *ep);
void dmrC_check_access(struct dmr_C *C, struct instruction *insn);
void dmrC_convert_load_instruction(struct dmr_C *C, struct instruction *, pseudo_t);
void dmrC_rewrite_load_instruction(struct dmr_C *C, struct instruction *, struct pseudo_list *);
int dmrC_dominates(struct dmr_C *C, pseudo_t pseudo, struct instruction *insn, struct instruction *dom, int local);
extern void dmrC_clear_liveness(struct entrypoint *ep);
extern void dmrC_track_pseudo_liveness(struct dmr_C *C, struct entrypoint *ep);
extern void dmrC_track_pseudo_death(struct dmr_C *C, struct entrypoint *ep);
extern void dmrC_track_phi_uses(struct dmr_C *C, struct instruction *insn);
extern void dmrC_vrfy_flow(struct entrypoint *ep);
extern int dmrC_pseudo_in_list(struct pseudo_list *list, pseudo_t pseudo);
#ifdef __cplusplus
}
#endif
#endif
| 2.015625 | 2 |
2024-11-18T20:41:42.102984+00:00 | 2023-03-18T19:32:38 | 06c19e279d0607fc53f0d879e5c383d8471afff0 | {
"blob_id": "06c19e279d0607fc53f0d879e5c383d8471afff0",
"branch_name": "refs/heads/master",
"committer_date": "2023-03-18T19:32:38",
"content_id": "6fcc18c7e2ff671c63807bc8b7f05e90052bfd6b",
"detected_licenses": [
"MIT"
],
"directory_id": "f381861718a20bda54858182554eeb1b446e1c00",
"extension": "h",
"filename": "gfx.h",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 345470295,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3056,
"license": "MIT",
"license_type": "permissive",
"path": "/gfx.h",
"provenance": "stackv2-0091.json.gz:220",
"repo_name": "gameblabla/x68000_playground",
"revision_date": "2023-03-18T19:32:38",
"revision_id": "2183508e45c1dc7e8b98936650554ad338faa4df",
"snapshot_id": "2aef7214f8c604026d8de1aec72863fcbfd20ea0",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/gameblabla/x68000_playground/2183508e45c1dc7e8b98936650554ad338faa4df/gfx.h",
"visit_date": "2023-04-07T01:14:41.295118"
} | stackv2 | /* gfx.h, GVRAM Graphical function prototypes for the x68Launcher.
Copyright (C) 2020 John Snowdon
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stdint.h>
#define GFX_PAGE 0 // Active GVRAM page (only one page in 16bit colour mode)
#ifdef LOW_RESOLUTION
#define GFX_CRT_MODE 14 // 256x256 65535 colour
#define GFX_ROWS 256 // NUmbe of pixels in a row
#define GFX_COLS 256 // Number of pixels in a column
#define GFX_ROW_SIZE (GFX_COLS << 1) // NUmber of bytes in a row (pixels per row * 2)
#define GFX_COL_SIZE (GFX_ROWS << 1) // NUmber of bytes in a column
#define GFX_PIXEL_SIZE 2 // 2 bytes per pixel
#else
#define GFX_CRT_MODE 12 // 512x512 65535 colour
#define GFX_ROWS 512 // NUmbe of pixels in a row
#define GFX_COLS 512 // Number of pixels in a column
#define GFX_ROW_SIZE (GFX_COLS << 1) // NUmber of bytes in a row (pixels per row * 2)
#define GFX_COL_SIZE (GFX_ROWS << 1) // NUmber of bytes in a column
#define GFX_PIXEL_SIZE 2 // 2 bytes per pixel
#endif
#define GVRAM_START 0xC00000 // Start of graphics vram
#define GVRAM_END 0xC7FFFF // End of graphics vram
#define RGB_BLACK 0x0000 // Simple RGB definition for a black 16bit pixel (5551 representation?)
#define RGB_WHITE 0xFFFF // Simple RGB definition for a white 16bit pixel (5551 representation?)
uint16_t *gvram; // Pointer to a GVRAM location (which is always as wide as a 16bit word)
int crt_last_mode; // Store last active mode before this application runs
#define BITMAP_HEADER_SIZE 16
typedef struct tagBITMAP /* the structure for a bitmap. */
{
uint16_t width;
uint16_t height;
uint16_t sprite_width;
uint16_t sprite_height;
uint8_t encoding;
int totalsize_pixel;
int totalfilesz;
char bytespp;
char *pixels;
} BITMAP;
BITMAP bitmap_load(const char* path);
void bitmap_load_directly(const char* path);
/* **************************** */
/* Function prototypes */
/* **************************** */
uint8_t gfx_init();
uint8_t gfx_close();
void gfx_Clear();
uint8_t gvramBitmap(short x, short y, BITMAP *bmpdata);
uint8_t gvramBox(short x1, short y1, short x2, short y2, uint16_t grbi);
uint8_t gvramBoxFill(short x1, short y1, short x2, short y2, uint16_t grbi);
uint32_t gvramGetXYaddr(short x, short y);
uint8_t gvramPoint(short x, short y, uint16_t grbi);
uint8_t gvramScreenFill(uint16_t rgb);
uint8_t gvramScreenCopy(short x1, short y1, short x2, short y2, short x3, short y3);
| 2.171875 | 2 |
2024-11-18T20:55:27.956520+00:00 | 2023-06-26T18:38:18 | a85be999c3d250ed00e58e9653e6b9f65d672ab2 | {
"blob_id": "a85be999c3d250ed00e58e9653e6b9f65d672ab2",
"branch_name": "refs/heads/master",
"committer_date": "2023-06-26T18:38:18",
"content_id": "d219aa4927155b82c9b894fadd1feb98be19b823",
"detected_licenses": [
"MIT"
],
"directory_id": "e568fcf70d23481da18734c2a9d30c1b5d95b265",
"extension": "c",
"filename": "data_utils.c",
"fork_events_count": 5,
"gha_created_at": "2017-09-29T17:19:24",
"gha_event_created_at": "2023-06-26T11:31:15",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 105298729,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 7566,
"license": "MIT",
"license_type": "permissive",
"path": "/src/vtk_utils/data_utils.c",
"provenance": "stackv2-0092.json.gz:36150",
"repo_name": "rsachetto/MonoAlg3D_C",
"revision_date": "2023-06-26T18:38:18",
"revision_id": "69875c8d01469a55c2ece0f902614b8bf0bd98c7",
"snapshot_id": "0be1950a3c8f357d99ccd16e38f1da47ad7e9fe6",
"src_encoding": "UTF-8",
"star_events_count": 16,
"url": "https://raw.githubusercontent.com/rsachetto/MonoAlg3D_C/69875c8d01469a55c2ece0f902614b8bf0bd98c7/src/vtk_utils/data_utils.c",
"visit_date": "2023-07-09T08:18:48.118294"
} | stackv2 | //
// Created by sachetto on 01/11/18.
//
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#include "data_utils.h"
#define COMPRESED_BLOCK_SIZE 1 << 15
void calculate_blocks_and_compress_data(size_t total_data_size_before_compression,
size_t *total_data_size_after_compression, unsigned char *data_to_compress,
unsigned char **compressed_buffer, size_t *num_blocks,
size_t *block_size_uncompressed, size_t **block_sizes_compressed,
size_t *last_block_size, int compression_level) {
size_t block_size = COMPRESED_BLOCK_SIZE;
*total_data_size_after_compression = 0;
if(total_data_size_before_compression < COMPRESED_BLOCK_SIZE) {
block_size = total_data_size_before_compression;
}
assert(block_size);
(*block_size_uncompressed) = block_size;
size_t num_full_blocks = total_data_size_before_compression / block_size;
*last_block_size = total_data_size_before_compression % block_size;
*num_blocks = num_full_blocks + (*last_block_size ? 1 : 0);
*block_sizes_compressed = (size_t *)malloc(sizeof(size_t) * (*num_blocks));
size_t compressed_data_size = compressBound(total_data_size_before_compression);
*compressed_buffer = (unsigned char *)malloc(compressed_data_size);
unsigned char *data_to_compress_pointer = data_to_compress;
unsigned char *compressed_buffer_pointer = *compressed_buffer;
size_t uncompressed_data_size = (*block_size_uncompressed);
size_t local_compressed_data_size = compressBound(uncompressed_data_size);
for(size_t i = 0; i < *num_blocks; i++) {
if((i == *num_blocks - 1) && *last_block_size != 0) {
uncompressed_data_size = *last_block_size;
local_compressed_data_size = compressBound(uncompressed_data_size);
}
(*block_sizes_compressed)[i] =
compress_buffer(data_to_compress_pointer, uncompressed_data_size, compressed_buffer_pointer,
local_compressed_data_size, compression_level);
data_to_compress_pointer += uncompressed_data_size;
compressed_buffer_pointer += (*block_sizes_compressed)[i];
*total_data_size_after_compression += (*block_sizes_compressed)[i];
}
}
size_t uncompress_buffer(unsigned char const* compressed_data,
size_t compressed_size,
unsigned char* uncompressed_data,
size_t uncompressed_size)
{
uLongf us = (uLongf) (uncompressed_size);
Bytef* ud = uncompressed_data;
const Bytef* cd = compressed_data;
uLong cs = (uLong)(compressed_size);
// Call zlib's uncompress function.
if(uncompress(ud, &us, cd, cs) != Z_OK) {
printf("Zlib error while uncompressing data.\n");
return 0;
}
// Make sure the output size matched that expected.
if(us != (uLongf)uncompressed_size ) {
printf("Decompression produced incorrect size.\n Expected %zu and got %lu\n", uncompressed_size, us);
return 0;
}
return (size_t) us;
}
size_t compress_buffer(unsigned char const *uncompressed_data, size_t uncompressed_data_size,
unsigned char *compressed_data, size_t compressed_buffer_size, int level) {
uLongf cs = (uLongf)compressed_buffer_size;
Bytef *cd = compressed_data;
const Bytef *ud = uncompressed_data;
uLong us = (uLong)(uncompressed_data_size);
// Call zlib's compress function
if(compress2(cd, &cs, ud, us, level) != Z_OK) {
printf("Zlib error while compressing data.\n");
return 0;
}
return (size_t)(cs);
}
int invert_bytes(int data) {
int swapped = ((data >> 24) & 0xff) | // move byte 3 to byte 0
((data << 8) & 0xff0000) | // move byte 1 to byte 2
((data >> 8) & 0xff00) | // move byte 2 to byte 1
((data << 24) & 0xff000000); // byte 0 to byte 3
return swapped;
}
void read_binary_point(void *source, struct point_3d *p) {
int data = invert_bytes(*(int *)source);
p->x = *(float *)&(data);
source+=4;
data = invert_bytes(*(int *)source);
p->y = *(float *)&(data);
source+=4;
data = invert_bytes(*(int *)source);
p->z = *(float *)&(data);
}
sds write_binary_point(sds output_string, struct point_3d *p) {
float x = (float)p->x;
float y = (float)p->y;
float z = (float)p->z;
int a = *(int *)&(x);
int swapped = invert_bytes(a);
output_string = sdscatlen(output_string, &swapped, sizeof(int));
a = *(int *)&(y);
swapped = invert_bytes(a);
output_string = sdscatlen(output_string, &swapped, sizeof(int));
a = *(int *)&(z);
swapped = invert_bytes(a);
output_string = sdscatlen(output_string, &swapped, sizeof(int));
return output_string;
}
sds write_binary_line (sds output_string, struct line *l)
{
int a = 2;
int swapped = invert_bytes(a);
output_string = sdscatlen(output_string, &swapped, sizeof(int));
a = *(int *)&(l->source);
swapped = invert_bytes(a);
output_string = sdscatlen(output_string, &swapped, sizeof(int));
a = *(int *)&(l->destination);
swapped = invert_bytes(a);
output_string = sdscatlen(output_string, &swapped, sizeof(int));
return output_string;
}
size_t get_block_sizes_from_compressed_vtu_file(char *raw_data, size_t header_size, uint64_t *num_blocks, uint64_t *block_size_uncompressed, uint64_t *last_block_size, uint64_t **block_sizes_compressed) {
size_t offset = 0;
*num_blocks = 0;
memcpy(num_blocks, raw_data, header_size);
raw_data += header_size;
offset += header_size;
*block_size_uncompressed = 0;
memcpy(block_size_uncompressed, raw_data, header_size);
raw_data += header_size;
offset += header_size;
*last_block_size = 0;
memcpy(last_block_size, raw_data, header_size);
raw_data += header_size;
offset += header_size;
*block_sizes_compressed = (uint64_t*)calloc(*num_blocks, sizeof(uint64_t));
for(int i = 0; i < *num_blocks; i++) {
memcpy(*block_sizes_compressed + i, raw_data, header_size);
uint64_t tmp = 0;
memcpy(&tmp, raw_data, header_size);
raw_data += header_size;
offset += header_size;
}
return offset;
}
void get_data_block_from_compressed_vtu_file(const char *raw_data, void* values, uint64_t num_blocks, uint64_t block_size_uncompressed, uint64_t last_block_size, uint64_t *block_sizes_compressed) {
unsigned char* uncompressed_data = (unsigned char *)values;
unsigned char const* compressed_data = (unsigned char const*) raw_data;
for(int i = 0; i < num_blocks; i++) {
size_t uncompressed_size = block_size_uncompressed;
if(i == num_blocks - 1 && last_block_size != 0) {
uncompressed_size = last_block_size;
}
uncompress_buffer(compressed_data, block_sizes_compressed[i], uncompressed_data, uncompressed_size);
uncompressed_data += uncompressed_size;
compressed_data += block_sizes_compressed[i];
}
free(block_sizes_compressed);
}
void get_data_block_from_uncompressed_binary_vtu_file(char *raw_data, void* values, size_t header_size) {
uint64_t block_size = 0;
memcpy(&block_size, raw_data, header_size);
raw_data += header_size;
memcpy(values, raw_data, block_size);
}
| 2.734375 | 3 |
2024-11-18T20:55:28.076237+00:00 | 2021-06-08T14:15:18 | ce714efd06e8c03fd9ca873ccf8cd453b704c657 | {
"blob_id": "ce714efd06e8c03fd9ca873ccf8cd453b704c657",
"branch_name": "refs/heads/master",
"committer_date": "2021-06-08T14:15:18",
"content_id": "e3b4f6fb93ebddb71139b257ffb12186d3c6f162",
"detected_licenses": [
"MIT"
],
"directory_id": "37d8dd983f9e51f5adb3e885a8d3d23c3768931f",
"extension": "c",
"filename": "53. Factorial.c",
"fork_events_count": 0,
"gha_created_at": "2021-05-08T13:59:48",
"gha_event_created_at": "2021-05-13T17:27:38",
"gha_language": "C",
"gha_license_id": null,
"github_id": 365528283,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 315,
"license": "MIT",
"license_type": "permissive",
"path": "/Arithmetic Numerical/53. Factorial.c",
"provenance": "stackv2-0092.json.gz:36407",
"repo_name": "codewithsandy/C",
"revision_date": "2021-06-08T14:15:18",
"revision_id": "b929c5314a31df3acf4d9f29ffd3a467f565f1d0",
"snapshot_id": "a0cf187f3b6ce0a7cbae19102b5cdbeedad1f357",
"src_encoding": "UTF-8",
"star_events_count": 8,
"url": "https://raw.githubusercontent.com/codewithsandy/C/b929c5314a31df3acf4d9f29ffd3a467f565f1d0/Arithmetic Numerical/53. Factorial.c",
"visit_date": "2023-05-14T06:58:46.926317"
} | stackv2 | /* 52. Program to accept number and print it's factorial. */
#include<stdio.h>
#include<conio.h>
void main()
{
int i, fact=1, n;
clrscr();
printf("Enter number : ");
scanf("%d", &n);
for(i=1; i<=n; i++)
{
fact = fact*i;
}
printf("Factorial is: %d", fact);
getch();
} | 3.578125 | 4 |
2024-11-18T20:55:28.176698+00:00 | 2020-03-19T13:50:10 | 367c7cdcac1efdd0be204e5dff536e38a6d38e48 | {
"blob_id": "367c7cdcac1efdd0be204e5dff536e38a6d38e48",
"branch_name": "refs/heads/master",
"committer_date": "2020-03-19T13:50:10",
"content_id": "44d9a2164450cd7faa6e869cc54ff3bc88128977",
"detected_licenses": [
"MIT"
],
"directory_id": "4edf16dd911e3e8a4d70e56cda144549958b5c5c",
"extension": "c",
"filename": "singlelinklist.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": 13793,
"license": "MIT",
"license_type": "permissive",
"path": "/singlelinklist.c",
"provenance": "stackv2-0092.json.gz:36537",
"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/singlelinklist.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 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 Node {
ElementType value;
struct Node *next;
} Node;
/**
* 单链表类型,其中指针指向头节点(不存储数据)
*/
typedef struct {
Node *headNode;
int length;
} SingleLinkList;
/**
* 初始化 listPointer 指向的线性表。执行成功返回 OK,失败返回 ERROR
*/
Status initList(SingleLinkList *listPointer);
/**
* 判断线性表 list 是否为空。为空返回 true,不为空返回 false
*/
bool isEmpty(SingleLinkList list);
/**
* 清空 listPointer 指针指向的线性表。执行成功返回 OK,失败返回 ERROR
*/
Status clearList(SingleLinkList *listPointer);
/**
* 获取线性表 list 的第 index 个元素的值,放在 elementPointer 指针指向的变量中
* 执行成功返回 OK,失败返回 ERROR
*/
Status getElement(SingleLinkList list, int index, ElementType *valuePointer);
/**
* 在线性表 list 中查找与 element 相等的元素。以整数形式返回其位置,查找失败返回
* 0
*/
int locateElement(SingleLinkList list, ElementType value);
/**
* 将 element 插入到 listPointer 指针指向的线性表的第 index 个位置
* 执行成功返回 OK,执行失败返回 ERROR
*/
Status insertElement(SingleLinkList *listPointer, int index, ElementType value);
/**
* 将 element 追加到 listPointer 指针指向的线性表的末尾
* 执行成功返回 OK,执行失败返回 ERROR
*/
Status appendElement(SingleLinkList *listPointer, ElementType value);
/**
* 删除 listPointer 指针指向的线性表的第 index 个元素,并将删除的元素值放在
* elementPointer 指针指向的变量中 执行成功返回 OK,失败返回 ERROR
*/
Status deleteElement(SingleLinkList *listPointer, int index,
ElementType *valuePointer);
/**
* 计算线性表 list 的长度
*/
int listLen(SingleLinkList list);
/**
* 以头插的方式使用 valuesPointer 指向的数组的值,创建 listPointer
* 指针指向的线性表,由于无法自动计算数组长度,需要提供第三个参数指定要填充的元素个数
* 执行成功返回 OK,失败返回 ERROR
*/
Status createListHead(SingleLinkList *listPointer, ElementType *valuesPorinter,
int length);
/**
* 以尾插的方式使用 valuesPointer 指向的数组的值,创建 listPointer
* 指针指向的线性表,由于无法自动计算数组长度,需要提供第三个参数指定要填充的元素个数
* 执行成功返回 OK,失败返回 ERROR
*/
Status createListTail(SingleLinkList *listPointer, ElementType *valuesPorinter,
int length);
/**
* 使用连续 count 个整数填 listPointer 指针指向的线性表,起始数值为 3。
* 用于在测试时初始化线性表
*/
void setup(SingleLinkList *listPointer, int count);
/**
* initList 函数的测试函数
*/
void testInitList();
/**
* isEmpty 函数的测试函数
*/
void testIsEmpty();
/**
* clearList 函数的测试函数
*/
void testClearList();
/**
* getElement 函数的测试函数
*/
void testGetElement();
/**
* locateElement 函数的测试函数
*/
void testLocateElement();
/**
* insertElement 函数的测试函数
*/
void testInsertElement();
/**
* appendElement 函数的测试函数
*/
void testAppendElement();
/**
* deleteElement 函数的测试函数
*/
void testDeleteElement();
/**
* listLen 函数的测试函数
*/
void testListLen();
/**
* createListHead 函数的测试函数
*/
void testCreateListHead();
/**
* createListTail 函数的测试函数
*/
void testCreateListTail();
Status initList(SingleLinkList *listPointer) {
listPointer->length = 0;
listPointer->headNode = (Node *)malloc(sizeof(Node));
listPointer->headNode->next = NULL;
return OK;
}
bool isEmpty(SingleLinkList list) { return 0 == list.length; }
Status clearList(SingleLinkList *listPointer) {
int i;
Node *p, *n;
if (0 != listPointer->length) {
p = listPointer->headNode;
for (i = 1; i <= listPointer->length; ++i) {
n = p->next;
p->next = n->next;
free(n);
}
}
listPointer->length = 0;
return OK;
}
Status getElement(SingleLinkList list, int index, ElementType *valuePointer) {
if (index < 1 || index > list.length) {
return ERROR;
}
int i;
Node *p = list.headNode;
for (i = 1; i <= index; ++i) {
p = p->next;
}
*valuePointer = p->value;
return OK;
}
int locateElement(SingleLinkList list, ElementType value) {
int i;
Node *p = list.headNode;
for (i = 1; i <= list.length; ++i) {
if (p->next->value == value) {
return i;
}
p = p->next;
}
return 0;
}
Status insertElement(SingleLinkList *listPointer, int index,
ElementType value) {
if (index < 1 || index > listPointer->length + 1) {
return ERROR;
}
int i;
Node *p, *n;
p = listPointer->headNode;
for (i = 1; i < index; ++i) {
p = p->next;
}
n = (Node *)malloc(sizeof(Node));
n->value = value;
n->next = p->next;
p->next = n;
++listPointer->length;
return OK;
}
Status appendElement(SingleLinkList *listPointer, ElementType value) {
return insertElement(listPointer, listPointer->length + 1, value);
}
Status deleteElement(SingleLinkList *listPointer, int index,
ElementType *valuePointer) {
if (index < 1 || index > listPointer->length) {
return ERROR;
}
int i;
Node *p, *n;
p = listPointer->headNode;
for (i = 1; i < index; ++i) {
p = p->next;
}
n = p->next;
p->next = n->next;
*valuePointer = n->value;
free(n);
--listPointer->length;
return OK;
}
int listLen(SingleLinkList list) { return list.length; }
Status createListHead(SingleLinkList *listPointer, ElementType *valuesPointer,
int count) {
int i;
initList(listPointer);
for (i = 1; i <= count; ++i) {
insertElement(listPointer, 1, valuesPointer[i - 1]);
}
return OK;
}
Status createListTail(SingleLinkList *listPointer, ElementType *valuesPointer,
int count) {
int i;
initList(listPointer);
Node *p, *n;
p = listPointer->headNode;
for (i = 1; i <= count; ++i) {
n = (Node *)malloc(sizeof(Node));
n->value = valuesPointer[i - 1];
n->next = NULL;
p->next = n;
p = p->next;
++listPointer->length;
}
return OK;
}
int main() {
testInitList();
testIsEmpty();
testClearList();
testGetElement();
testLocateElement();
testInsertElement();
testAppendElement();
testDeleteElement();
testListLen();
testCreateListHead();
testCreateListTail();
}
void setup(SingleLinkList *listPointer, int count) {
int i;
Node *p, *n;
listPointer->headNode = p = (Node *)malloc(sizeof(Node));
p->next = NULL;
for (i = 0; i < count; ++i) {
n = (Node *)malloc(sizeof(Node));
n->value = i + 3;
n->next = NULL;
p = p->next = n;
}
listPointer->length = count;
}
void testInitList() {
char functionName[] = "initList";
SingleLinkList list;
if (!initList(&list)) {
OUTFAIL()
}
if (0 != list.length) {
OUTFAIL();
}
if (list.headNode->next != NULL) {
OUTFAIL();
}
OUTSUCCESS();
}
void testIsEmpty() {
char functionName[] = "isEmpty";
SingleLinkList list;
list.length = 0;
if (!isEmpty(list)) {
OUTFAIL();
}
list.length = 3;
if (isEmpty(list)) {
OUTFAIL();
}
OUTSUCCESS();
}
void testClearList() {
char functionName[] = "clearList";
SingleLinkList list;
setup(&list, 0);
if (!clearList(&list)) {
OUTFAIL();
}
if (0 != list.length) {
OUTFAIL();
}
if (NULL != list.headNode->next) {
OUTFAIL();
}
setup(&list, 3);
if (!clearList(&list)) {
OUTFAIL();
}
if (0 != list.length) {
OUTFAIL();
}
OUTSUCCESS();
}
void testGetElement() {
char functionName[] = "getElement";
SingleLinkList list;
ElementType value;
setup(&list, 5);
if (getElement(list, 0, &value)) {
OUTFAIL();
}
if (getElement(list, 6, &value)) {
OUTFAIL();
}
if (!getElement(list, 1, &value) || 3 != value) {
OUTFAIL();
}
if (!getElement(list, 3, &value) || 5 != value) {
OUTFAIL();
}
if (!getElement(list, 5, &value) || 7 != value) {
OUTFAIL();
}
OUTSUCCESS();
}
void testLocateElement() {
char functionName[] = "locateElement";
SingleLinkList list;
setup(&list, 5);
if (0 != locateElement(list, 0)) {
OUTFAIL();
}
if (0 != locateElement(list, 8)) {
OUTFAIL();
}
if (1 != locateElement(list, 3)) {
OUTFAIL();
}
if (3 != locateElement(list, 5)) {
OUTFAIL();
}
if (5 != locateElement(list, 7)) {
OUTFAIL();
}
OUTSUCCESS();
}
void testInsertElement() {
char functionName[] = "insertElement";
SingleLinkList list;
ElementType value;
int i;
setup(&list, 5);
if (insertElement(&list, 0, 2)) {
OUTFAIL();
}
if (insertElement(&list, 7, 8)) {
OUTFAIL();
}
if (!insertElement(&list, 1, 2) || 6 != list.length) {
OUTFAIL()
}
for (i = 1; i <= 6; ++i) {
if (!getElement(list, i, &value) || i + 1 != value) {
OUTFAIL();
}
}
if (!insertElement(&list, 7, 8) || 7 != list.length) {
OUTFAIL();
}
for (i = 1; i <= 6; ++i) {
if (!getElement(list, i, &value) || i + 1 != value) {
OUTFAIL();
}
}
if (!insertElement(&list, 4, 9) || 8 != list.length) {
OUTFAIL();
}
for (i = 1; i <= 3; ++i) {
if (!getElement(list, i, &value) || i + 1 != value) {
OUTFAIL();
}
}
if (!getElement(list, i, &value) || 9 != value) {
OUTFAIL();
}
for (++i; i <= 8; ++i) {
if (!getElement(list, i, &value) || i != value) {
OUTFAIL();
}
}
OUTSUCCESS();
}
void testAppendElement() {
char functionName[] = "appendElement";
SingleLinkList list;
ElementType value;
int i;
setup(&list, 5);
if (!appendElement(&list, 8) || 6 != list.length) {
OUTFAIL();
}
for (i = 1; i <= 6; ++i) {
if (!getElement(list, i, &value) || i + 2 != value) {
OUTFAIL();
}
}
OUTSUCCESS();
}
void testDeleteElement() {
char functionName[] = "deleteElement";
SingleLinkList list;
int i;
ElementType value;
setup(&list, 5);
if (deleteElement(&list, 0, &value)) {
OUTFAIL();
}
if (deleteElement(&list, 6, &value)) {
OUTFAIL();
}
if (!deleteElement(&list, 1, &value) || 4 != list.length) {
OUTFAIL();
}
if (3 != value) {
OUTFAIL();
}
for (i = 1; i <= 4; ++i) {
if (!getElement(list, i, &value) || i + 3 != value) {
OUTFAIL();
}
}
if (!deleteElement(&list, 4, &value) || 3 != list.length) {
OUTFAIL();
}
if (7 != value) {
OUTFAIL();
}
for (i = 1; i <= 3; ++i) {
if (!getElement(list, i, &value) || i + 3 != value) {
OUTFAIL();
}
}
if (!deleteElement(&list, 2, &value) || 2 != list.length) {
OUTFAIL();
}
if (5 != value) {
OUTFAIL();
}
if (!getElement(list, 1, &value) || 4 != value) {
OUTFAIL();
}
if (!getElement(list, 2, &value) || 6 != value) {
OUTFAIL();
}
OUTSUCCESS();
}
void testListLen() {
char functionName[] = "listLen";
SingleLinkList list;
setup(&list, 3);
if (3 != listLen(list)) {
OUTFAIL();
}
SingleLinkList list1;
setup(&list1, 8);
if (8 != listLen(list1)) {
OUTFAIL();
}
OUTSUCCESS();
}
void testCreateListHead() {
char functionName[] = "createListHead";
SingleLinkList list;
ElementType value, values[] = {1, 3, 5, 7, 9, 11};
int i;
if (!createListHead(&list, values, 6)) {
OUTFAIL();
}
if (6 != list.length) {
OUTFAIL();
}
for (i = 1; i <= list.length; ++i) {
if (!getElement(list, i, &value) || (6 - i) * 2 + 1 != value) {
OUTFAIL();
}
}
OUTSUCCESS();
}
void testCreateListTail() {
char functionName[] = "createListTail";
SingleLinkList list;
ElementType value, values[] = {1, 3, 5, 7, 9, 11};
int i;
if (!createListTail(&list, values, 6)) {
OUTFAIL();
}
if (6 != list.length) {
OUTFAIL();
}
for (i = 1; i <= list.length; ++i) {
if (!getElement(list, i, &value) || i * 2 - 1 != value) {
OUTFAIL();
}
}
OUTSUCCESS();
} | 3.484375 | 3 |
2024-11-18T20:55:28.394550+00:00 | 2022-08-04T22:49:38 | a4917680ef1418a79b3f955c34b90e49f6e50e8f | {
"blob_id": "a4917680ef1418a79b3f955c34b90e49f6e50e8f",
"branch_name": "refs/heads/master",
"committer_date": "2022-08-04T22:49:38",
"content_id": "6c4b5962be3080386c72cab65a62178a3ba7bd9c",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "198776b40bcd18cbd7bb8350183915d096844d54",
"extension": "c",
"filename": "zjs_dgram.c",
"fork_events_count": 29,
"gha_created_at": "2016-06-20T23:53:57",
"gha_event_created_at": "2019-05-31T22:37:24",
"gha_language": "C",
"gha_license_id": "NOASSERTION",
"github_id": 61588342,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 11267,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/zjs_dgram.c",
"provenance": "stackv2-0092.json.gz:36795",
"repo_name": "intel/zephyr.js",
"revision_date": "2022-08-04T22:49:38",
"revision_id": "b67b7dbd6b5a6f79cb6c8b705abedf7765cd460d",
"snapshot_id": "143066b4c87bbebe2917b1196f21acb380c202b3",
"src_encoding": "UTF-8",
"star_events_count": 98,
"url": "https://raw.githubusercontent.com/intel/zephyr.js/b67b7dbd6b5a6f79cb6c8b705abedf7765cd460d/src/zjs_dgram.c",
"visit_date": "2023-05-29T06:33:39.586487"
} | stackv2 | // Copyright (c) 2017, Linaro Limited.
#ifdef BUILD_MODULE_DGRAM
// Zephyr includes
#include <net/net_context.h>
#include <net/net_pkt.h>
#include <net/udp.h>
#if defined(CONFIG_NET_L2_BT)
#include <bluetooth/bluetooth.h>
#endif
// ZJS includes
#include "zjs_buffer.h"
#include "zjs_callbacks.h"
#include "zjs_net_config.h"
#include "zjs_util.h"
static jerry_value_t zjs_dgram_socket_prototype;
typedef struct dgram_handle {
struct net_context *udp_sock;
zjs_callback_id message_cb_id;
zjs_callback_id error_cb_id;
} dgram_handle_t;
#define CHECK(x) \
ret = (x); \
if (ret < 0) { \
ERR_PRINT("Error in " #x ": %d\n", ret); \
return zjs_error(#x); \
}
// FIXME: Quick hack to allow context into the regular CHECK while fixing build
// for call sites without JS binding context
#define CHECK_ALT(x) \
ret = (x); \
if (ret < 0) { \
ERR_PRINT("Error in " #x ": %d\n", ret); \
return zjs_error_context(#x, 0, 0); \
}
#define GET_STR(jval, buf) \
{ \
jerry_size_t str_sz = sizeof(buf); \
zjs_copy_jstring(jval, buf, &str_sz); \
}
// Parse textual address of given address family (IPv4/IPv6) and numeric
// port and fill in sockaddr. Returns ZJS_UNDEFINED if everything is OK,
// or error instance otherwise.
static jerry_value_t get_addr(sa_family_t family,
const jerry_value_t addr,
const jerry_value_t port,
struct sockaddr *sockaddr)
{
// requires: addr must be a string value, and port must be a number value
int ret;
// We employ the fact that port and address offsets are the same for IPv4&6
struct sockaddr_in *sockaddr_in = (struct sockaddr_in *)sockaddr;
sockaddr_in->sin_family = family;
sockaddr_in->sin_port = htons((int)jerry_get_number_value(port));
jerry_size_t str_len = 40;
char addr_str[str_len];
zjs_copy_jstring(addr, addr_str, &str_len);
CHECK_ALT(net_addr_pton(family, addr_str, &sockaddr_in->sin_addr));
return ZJS_UNDEFINED;
}
static void zjs_dgram_free_cb(void *native)
{
dgram_handle_t *handle = (dgram_handle_t *)native;
DBG_PRINT("zjs_dgram_free_cb: %p\n", handle);
if (!handle) {
return;
}
if (handle->udp_sock) {
int ret = net_context_put(handle->udp_sock);
if (ret < 0) {
ERR_PRINT("dgram: net_context_put: err: %d\n", ret);
}
}
zjs_remove_callback(handle->message_cb_id);
zjs_remove_callback(handle->error_cb_id);
zjs_free(handle);
}
static const jerry_object_native_info_t dgram_type_info = {
.free_cb = zjs_dgram_free_cb
};
// Copy data from Zephyr net_pkt chain into linear buffer
static char *net_pkt_gather(struct net_pkt *pkt, char *to)
{
struct net_buf *tmp = pkt->frags;
int header_len = net_pkt_appdata(pkt) - tmp->data;
net_buf_pull(tmp, header_len);
while (tmp) {
memcpy(to, tmp->data, tmp->len);
to += tmp->len;
tmp = net_pkt_frag_del(pkt, NULL, tmp);
}
return to;
}
// Zephyr "packet received" callback
static void udp_received(struct net_context *context,
struct net_pkt *net_pkt,
int status,
void *user_data)
{
DBG_PRINT("udp_received: %p, buf=%p, st=%d, appdatalen=%d, udata=%p\n",
context, net_pkt, status, net_pkt_appdatalen(net_pkt), user_data);
dgram_handle_t *handle = user_data;
if (handle->message_cb_id == -1)
return;
int recv_len = net_pkt_appdatalen(net_pkt);
sa_family_t family = net_pkt_family(net_pkt);
char addr_str[40];
void *addr;
if (family == AF_INET) {
addr = &NET_IPV4_HDR(net_pkt)->src;
} else {
addr = &NET_IPV6_HDR(net_pkt)->src;
}
net_addr_ntop(family, addr, addr_str, sizeof(addr_str));
zjs_buffer_t *buf;
ZVAL_MUTABLE buf_js = zjs_buffer_create(recv_len, &buf);
ZVAL rinfo = zjs_create_object();
if (buf) {
struct net_udp_hdr placeholder;
struct net_udp_hdr *hdr = net_udp_get_hdr(net_pkt, &placeholder);
zjs_obj_add_number(rinfo, "port", ntohs(hdr->src_port));
zjs_obj_add_string(rinfo, "family",
family == AF_INET ? "IPv4" : "IPv6");
zjs_obj_add_string(rinfo, "address", addr_str);
net_pkt_gather(net_pkt, buf->buffer);
net_pkt_unref(net_pkt);
} else {
// can't pass object with error flag as a JS arg
jerry_value_clear_error_flag(&buf_js);
}
jerry_value_t args[2] = { buf_js, rinfo };
zjs_signal_callback(handle->message_cb_id, args, sizeof(args));
}
static ZJS_DECL_FUNC(zjs_dgram_createSocket)
{
// args: address family
ZJS_VALIDATE_ARGS(Z_STRING);
int ret;
char type_str[8];
GET_STR(argv[0], type_str);
sa_family_t family;
if (strequal(type_str, "udp4"))
family = AF_INET;
else if (strequal(type_str, "udp6"))
family = AF_INET6;
else
return zjs_error("invalid argument");
struct net_context *udp_sock;
CHECK(net_context_get(family, SOCK_DGRAM, IPPROTO_UDP, &udp_sock));
jerry_value_t sockobj = zjs_create_object();
jerry_set_prototype(sockobj, zjs_dgram_socket_prototype);
dgram_handle_t *handle = zjs_malloc(sizeof(dgram_handle_t));
if (!handle)
return zjs_error("out of memory");
handle->udp_sock = udp_sock;
handle->message_cb_id = -1;
handle->error_cb_id = -1;
jerry_set_object_native_pointer(sockobj, handle, &dgram_type_info);
// Can't call this here due to bug in Zephyr - called in .bind() instead
//CHECK(net_context_recv(udp_sock, udp_received, K_NO_WAIT, handle));
return sockobj;
}
static ZJS_DECL_FUNC(zjs_dgram_sock_on)
{
// args: event name, callback
ZJS_VALIDATE_ARGS(Z_STRING, Z_FUNCTION Z_NULL);
ZJS_GET_HANDLE(this, dgram_handle_t, handle, dgram_type_info);
jerry_size_t str_sz = 32;
char event[str_sz];
zjs_copy_jstring(argv[0], event, &str_sz);
zjs_callback_id *cb_slot;
if (strequal(event, "message"))
cb_slot = &handle->message_cb_id;
else if (strequal(event, "error"))
cb_slot = &handle->error_cb_id;
else
return zjs_error("unsupported event type");
zjs_remove_callback(*cb_slot);
if (!jerry_value_is_null(argv[1]))
*cb_slot = zjs_add_callback(argv[1], this, handle, NULL);
return ZJS_UNDEFINED;
}
// Zephyr "packet sent" callback
static void udp_sent(struct net_context *context, int status, void *token,
void *user_data)
{
DBG_PRINT("udp_sent: %p, st=%d udata=%p\n", context, status, user_data);
if (user_data) {
ZVAL_MUTABLE rval = ZJS_UNDEFINED;
if (status != 0) {
char errbuf[8];
snprintf(errbuf, sizeof(errbuf), "%d", status);
rval = zjs_standard_error(NetworkError, errbuf, 0, 0);
// We need error object, not error value (JrS doesn't allow to
// pass the latter as a func argument).
jerry_value_clear_error_flag(&rval);
}
zjs_callback_id id = zjs_add_callback_once((jerry_value_t)user_data,
ZJS_UNDEFINED, NULL, NULL);
zjs_signal_callback(id, &rval, sizeof(rval));
}
}
static ZJS_DECL_FUNC(zjs_dgram_sock_send)
{
// NOTE: really argv[1] and argv[2] (offset and length) are supposed to be
// optional, which would require improvements to ZJS_VALIDATE_ARGS,
// but for now I'll leave them as required, as they were here before
// args: buffer, offset, length, port, address[, callback]
ZJS_VALIDATE_ARGS(Z_BUFFER, Z_NUMBER, Z_NUMBER, Z_NUMBER, Z_STRING,
Z_OPTIONAL Z_FUNCTION);
int ret;
ZJS_GET_HANDLE(this, dgram_handle_t, handle, dgram_type_info);
zjs_buffer_t *buf = zjs_buffer_find(argv[0]);
int offset = (int)jerry_get_number_value(argv[1]);
int len = (int)jerry_get_number_value(argv[2]);
if (offset + len > buf->bufsize) {
return zjs_error("offset/len beyond buffer end");
}
sa_family_t family = net_context_get_family(handle->udp_sock);
struct sockaddr sockaddr_buf;
jerry_value_t err = get_addr(family, argv[4], argv[3], &sockaddr_buf);
if (err != ZJS_UNDEFINED)
return err;
struct net_pkt *send_buf = net_pkt_get_tx(handle->udp_sock, K_NO_WAIT);
if (!send_buf) {
return zjs_error("no netbuf");
}
if (!net_pkt_append(send_buf, len, buf->buffer + offset, K_NO_WAIT)) {
return zjs_error("no data netbuf");
}
void *user_data = NULL;
if (argc > 5) {
user_data = (void *)argv[5];
}
CHECK(net_context_sendto(send_buf, &sockaddr_buf, sizeof(sockaddr_buf),
udp_sent, K_NO_WAIT, NULL, user_data));
return ZJS_UNDEFINED;
}
static ZJS_DECL_FUNC(zjs_dgram_sock_bind)
{
// NOTE: really argv[0] and argv[1] are supposed to be optional, but
// leaving them as they were here for now
// args: port, address
ZJS_VALIDATE_ARGS(Z_NUMBER, Z_STRING);
int ret;
ZJS_GET_HANDLE(this, dgram_handle_t, handle, dgram_type_info);
sa_family_t family = net_context_get_family(handle->udp_sock);
struct sockaddr sockaddr_buf;
jerry_value_t err = get_addr(family, argv[1], argv[0], &sockaddr_buf);
if (err != ZJS_UNDEFINED)
return err;
CHECK(net_context_bind(handle->udp_sock, &sockaddr_buf,
sizeof(sockaddr_buf)));
// See comment in createSocket() why this is called here
CHECK(net_context_recv(handle->udp_sock, udp_received, K_NO_WAIT, handle));
return ZJS_UNDEFINED;
}
static ZJS_DECL_FUNC(zjs_dgram_sock_close)
{
ZJS_GET_HANDLE(this, dgram_handle_t, handle, dgram_type_info);
zjs_dgram_free_cb((void *)handle);
return ZJS_UNDEFINED;
}
static void zjs_dgram_cleanup(void *native)
{
jerry_release_value(zjs_dgram_socket_prototype);
}
static const jerry_object_native_info_t dgram_module_type_info = {
.free_cb = zjs_dgram_cleanup
};
static jerry_value_t zjs_dgram_init()
{
zjs_net_config_default();
// create socket prototype object
zjs_native_func_t array[] = {
{ zjs_dgram_sock_on, "on" },
{ zjs_dgram_sock_send, "send" },
{ zjs_dgram_sock_bind, "bind" },
{ zjs_dgram_sock_close, "close" },
{ NULL, NULL }
};
zjs_dgram_socket_prototype = zjs_create_object();
zjs_obj_add_functions(zjs_dgram_socket_prototype, array);
// create module object
jerry_value_t dgram_obj = zjs_create_object();
zjs_obj_add_function(dgram_obj, "createSocket", zjs_dgram_createSocket);
// Set up cleanup function for when the object gets freed
jerry_set_object_native_pointer(dgram_obj, NULL, &dgram_module_type_info);
return dgram_obj;
}
JERRYX_NATIVE_MODULE(dgram, zjs_dgram_init)
#endif // BUILD_MODULE_DGRAM
| 2.21875 | 2 |
2024-11-18T20:55:28.732763+00:00 | 2016-08-07T02:19:10 | ebdb6fe8e75852bbbe12d06e365d3b95e17dc298 | {
"blob_id": "ebdb6fe8e75852bbbe12d06e365d3b95e17dc298",
"branch_name": "refs/heads/master",
"committer_date": "2016-08-07T02:19:10",
"content_id": "75f2c208f5493881168c442c09da23ba222b59ad",
"detected_licenses": [
"MIT"
],
"directory_id": "a3382a363f1c94d66c26ef40e76ef1d4683297c5",
"extension": "h",
"filename": "usb_san_cdc.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 65110990,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 12051,
"license": "MIT",
"license_type": "permissive",
"path": "/usb_san_cdc.h",
"provenance": "stackv2-0092.json.gz:37052",
"repo_name": "SanUSB-grupo/Exemplos-CCS",
"revision_date": "2016-08-07T02:19:10",
"revision_id": "30c41e31b309c9da7c784faca609a22e8a80149d",
"snapshot_id": "0abb86ef91738e296752fb17297a215183cf962d",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/SanUSB-grupo/Exemplos-CCS/30c41e31b309c9da7c784faca609a22e8a80149d/usb_san_cdc.h",
"visit_date": "2021-01-20T18:19:52.968047"
} | stackv2 | /////////////////////////////////////////////////////////////////////////
//// ////
//// usb_san_cdc.h ////
//////////////http://br.groups.yahoo.com/group/GrupoSanUSB///////////////
//api for the user:
#define usb_cdc_kbhit() (usb_cdc_get_buffer_status.got)
#define usb_cdc_putready() (usb_cdc_put_buffer_nextin<USB_CDC_DATA_IN_SIZE)
#define usb_cdc_connected() (usb_cdc_got_set_line_coding)
void usb_cdc_putc_fast(char c);
char usb_cdc_getc(void);
void usb_cdc_putc(char c);
//input.c ported to use CDC:
float get_float_usb();
signed long get_long_usb();
signed int get_int_usb();
void get_string_usb(char* s, int max);
BYTE gethex_usb();
BYTE gethex1_usb();
//functions automatically called by USB handler code
void usb_isr_tkn_cdc(void);
void usb_cdc_init(void);
void usb_isr_tok_out_cdc_control_dne(void);
void usb_isr_tok_in_cdc_data_dne(void);
void usb_isr_tok_out_cdc_data_dne(void);
void usb_cdc_flush_out_buffer(void);
//Tells the CCS PIC USB firmware to include HID handling code.
#DEFINE USB_HID_DEVICE FALSE
#DEFINE USB_CDC_DEVICE TRUE
#define USB_CDC_COMM_IN_ENDPOINT 1
#define USB_CDC_COMM_IN_SIZE 8
#define USB_EP1_TX_ENABLE USB_ENABLE_INTERRUPT
#define USB_EP1_TX_SIZE USB_CDC_COMM_IN_SIZE
//pic to pc endpoint config
#define USB_CDC_DATA_IN_ENDPOINT 2
#define USB_CDC_DATA_IN_SIZE 64
#define USB_EP2_TX_ENABLE USB_ENABLE_BULK
#define USB_EP2_TX_SIZE USB_CDC_DATA_IN_SIZE
//pc to pic endpoint config
#define USB_CDC_DATA_OUT_ENDPOINT 2
#define USB_CDC_DATA_OUT_SIZE 64
#define USB_EP2_RX_ENABLE USB_ENABLE_BULK
#define USB_EP2_RX_SIZE USB_CDC_DATA_OUT_SIZE
/////////////////////////////////////////////////////////////////////////////
//
// Include the CCS USB Libraries. See the comments at the top of these
// files for more information
//
/////////////////////////////////////////////////////////////////////////////
#ifndef __USB_PIC_PERIF__
#define __USB_PIC_PERIF__ 1
#endif
#if __USB_PIC_PERIF__
#if defined(__PCM__)
#error CDC requires bulk mode! PIC16C7x5 does not have bulk mode
#else
#include <pic18_usb.h> //Microchip 18Fxx5x hardware layer for usb.c
#endif
#else
#include <usbn960x.c> //National 960x hardware layer for usb.c
#endif
#include <usb_san_desc.h> //USB Configuration and Device descriptors for this UBS device
#include <usb.c> //handles usb setup tokens and get descriptor reports
struct {
int32 dwDTERrate; //data terminal rate, in bits per second
int8 bCharFormat; //num of stop bits (0=1, 1=1.5, 2=2)
int8 bParityType; //parity (0=none, 1=odd, 2=even, 3=mark, 4=space)
int8 bDataBits; //data bits (5,6,7,8 or 16)
} usb_cdc_line_coding;
//length of time, in ms, of break signal as we received in a SendBreak message.
//if ==0xFFFF, send break signal until we receive a 0x0000.
int16 usb_cdc_break;
int8 usb_cdc_encapsulated_cmd[8];
int8 usb_cdc_put_buffer[USB_CDC_DATA_IN_SIZE];
int1 usb_cdc_put_buffer_free;
#if USB_CDC_DATA_IN_SIZE>=0x100
int16 usb_cdc_put_buffer_nextin=0;
// int16 usb_cdc_last_data_packet_size;
#else
int8 usb_cdc_put_buffer_nextin=0;
// int8 usb_cdc_last_data_packet_size;
#endif
struct {
int1 got;
#if USB_CDC_DATA_OUT_SIZE>=0x100
int16 len;
int16 index;
#else
int8 len;
int8 index;
#endif
} usb_cdc_get_buffer_status;
int8 usb_cdc_get_buffer_status_buffer[USB_CDC_DATA_OUT_SIZE];
#if (defined(__PIC__))
#if __PIC__
//#locate usb_cdc_get_buffer_status_buffer=0x500+(2*USB_MAX_EP0_PACKET_LENGTH)+USB_CDC_COMM_IN_SIZE
#if USB_MAX_EP0_PACKET_LENGTH==8
#locate usb_cdc_get_buffer_status_buffer=0x500+24
#elif USB_MAX_EP0_PACKET_LENGTH==64
#locate usb_cdc_get_buffer_status_buffer=0x500+136
#else
#error CCS BUG WONT LET ME USE MATH IN LOCATE
#endif
#endif
#endif
int1 usb_cdc_got_set_line_coding;
struct {
int1 dte_present; //1=DTE present, 0=DTE not present
int1 active; //1=activate carrier, 0=deactivate carrier
int reserved:6;
} usb_cdc_carrier;
enum {USB_CDC_OUT_NOTHING=0, USB_CDC_OUT_COMMAND=1, USB_CDC_OUT_LINECODING=2, USB_CDC_WAIT_0LEN=3} __usb_cdc_state=0;
#byte INTCON=0xFF2
#bit INT_GIE=INTCON.7
//handle OUT token done interrupt on endpoint 0 [read encapsulated cmd and line coding data]
void usb_isr_tok_out_cdc_control_dne(void) {
debug_usb(debug_putc,"CDC %X ",__usb_cdc_state);
switch (__usb_cdc_state) {
//printf(putc_tbe,"@%X@\r\n", __usb_cdc_state);
case USB_CDC_OUT_COMMAND:
//usb_get_packet(0, usb_cdc_encapsulated_cmd, 8);
memcpy(usb_cdc_encapsulated_cmd, usb_ep0_rx_buffer,8);
#if USB_MAX_EP0_PACKET_LENGTH==8
__usb_cdc_state=USB_CDC_WAIT_0LEN;
usb_request_get_data();
#else
usb_put_0len_0();
__usb_cdc_state=0;
#endif
break;
#if USB_MAX_EP0_PACKET_LENGTH==8
case USB_CDC_WAIT_0LEN:
usb_put_0len_0();
__usb_cdc_state=0;
break;
#endif
case USB_CDC_OUT_LINECODING:
//usb_get_packet(0, &usb_cdc_line_coding, 7);
//printf(putc_tbe,"\r\n!GSLC FIN!\r\n");
memcpy(&usb_cdc_line_coding, usb_ep0_rx_buffer,7);
__usb_cdc_state=0;
usb_put_0len_0();
break;
default:
__usb_cdc_state=0;
usb_init_ep0_setup();
break;
}
}
//handle IN token on 0 (setup packet)
void usb_isr_tkn_cdc(void) {
//make sure the request goes to a CDC interface
if ((usb_ep0_rx_buffer[4] == 1) || (usb_ep0_rx_buffer[4] == 0)) {
//printf(putc_tbe,"!%X!\r\n", usb_ep0_rx_buffer[1]);
switch(usb_ep0_rx_buffer[1]) {
case 0x00: //send_encapsulated_command
__usb_cdc_state=USB_CDC_OUT_COMMAND;
usb_request_get_data();
break;
case 0x01: //get_encapsulated_command
memcpy(usb_ep0_tx_buffer, usb_cdc_encapsulated_cmd, 8);
usb_request_send_response(usb_ep0_rx_buffer[6]); //send wLength bytes
break;
case 0x20: //set_line_coding
debug_usb(debug_putc,"!GSLC!");
__usb_cdc_state=USB_CDC_OUT_LINECODING;
usb_cdc_got_set_line_coding=TRUE;
usb_request_get_data();
break;
case 0x21: //get_line_coding
memcpy(usb_ep0_tx_buffer, &usb_cdc_line_coding, sizeof(usb_cdc_line_coding));
usb_request_send_response(sizeof(usb_cdc_line_coding)); //send wLength bytes
break;
case 0x22: //set_control_line_state
usb_cdc_carrier=usb_ep0_rx_buffer[2];
usb_put_0len_0();
break;
case 0x23: //send_break
usb_cdc_break=make16(usb_ep0_rx_buffer[2],usb_ep0_rx_buffer[3]);
usb_put_0len_0();
break;
default:
usb_request_stall();
break;
}
}
}
//handle OUT token done interrupt on endpoint 3 [buffer incoming received chars]
void usb_isr_tok_out_cdc_data_dne(void) {
usb_cdc_get_buffer_status.got=TRUE;
usb_cdc_get_buffer_status.index=0;
#if (defined(__PIC__))
#if __PIC__
usb_cdc_get_buffer_status.len=usb_rx_packet_size(USB_CDC_DATA_OUT_ENDPOINT);
#else
usb_cdc_get_buffer_status.len=usb_get_packet_buffer(
USB_CDC_DATA_OUT_ENDPOINT,&usb_cdc_get_buffer_status_buffer[0],USB_CDC_DATA_OUT_SIZE);
#endif
#else
usb_cdc_get_buffer_status.len=usb_get_packet_buffer(
USB_CDC_DATA_OUT_ENDPOINT,&usb_cdc_get_buffer_status_buffer[0],USB_CDC_DATA_OUT_SIZE);
#endif
}
//handle IN token done interrupt on endpoint 2 [transmit buffered characters]
void usb_isr_tok_in_cdc_data_dne(void) {
if (usb_cdc_put_buffer_nextin) {
usb_cdc_flush_out_buffer();
}
//send a 0len packet if needed
// else if (usb_cdc_last_data_packet_size==USB_CDC_DATA_IN_SIZE) {
// usb_cdc_last_data_packet_size=0;
// printf(putc_tbe, "FL 0\r\n");
// usb_put_packet(USB_CDC_DATA_IN_ENDPOINT,0,0,USB_DTS_TOGGLE);
// }
else {
usb_cdc_put_buffer_free=TRUE;
//printf(putc_tbe, "FL DONE\r\n");
}
}
void usb_cdc_flush_out_buffer(void) {
if (usb_cdc_put_buffer_nextin) {
usb_cdc_put_buffer_free=FALSE;
//usb_cdc_last_data_packet_size=usb_cdc_put_buffer_nextin;
//printf(putc_tbe, "FL %U\r\n", usb_cdc_put_buffer_nextin);
usb_put_packet(USB_CDC_DATA_IN_ENDPOINT,usb_cdc_put_buffer,usb_cdc_put_buffer_nextin,USB_DTS_TOGGLE);
usb_cdc_put_buffer_nextin=0;
}
}
void usb_cdc_init(void) {
usb_cdc_line_coding.dwDTERrate=9600;
usb_cdc_line_coding.bCharFormat=0;
usb_cdc_line_coding.bParityType=0;
usb_cdc_line_coding.bDataBits=8;
(int8)usb_cdc_carrier=0;
usb_cdc_got_set_line_coding=FALSE;
usb_cdc_break=0;
usb_cdc_put_buffer_nextin=0;
usb_cdc_get_buffer_status.got=0;
usb_cdc_put_buffer_free=TRUE;
while(read_eeprom(0xfd));
}
////////////////// END USB CONTROL HANDLING //////////////////////////////////
////////////////// BEGIN USB<->RS232 CDC LIBRARY /////////////////////////////
char usb_cdc_getc(void) {
char c;
while (!usb_cdc_kbhit()) {}
c=usb_cdc_get_buffer_status_buffer[usb_cdc_get_buffer_status.index++];
if (usb_cdc_get_buffer_status.index >= usb_cdc_get_buffer_status.len) {
usb_cdc_get_buffer_status.got=FALSE;
usb_flush_out(USB_CDC_DATA_OUT_ENDPOINT, USB_DTS_TOGGLE);
}
return(c);
}
void usb_cdc_putc_fast(char c) {
int1 old_gie;
//disable global interrupts
old_gie=INT_GIE;
INT_GIE=0;
if (usb_cdc_put_buffer_nextin >= USB_CDC_DATA_IN_SIZE) {
usb_cdc_put_buffer_nextin=USB_CDC_DATA_IN_SIZE-1; //we just overflowed the buffer!
}
usb_cdc_put_buffer[usb_cdc_put_buffer_nextin++]=c;
//renable global interrupts
INT_GIE=old_gie;
/*
if (usb_tbe(USB_CDC_DATA_IN_ENDPOINT)) {
if (usb_cdc_put_buffer_nextin)
usb_cdc_flush_out_buffer();
}
*/
if (usb_cdc_put_buffer_free) {
usb_cdc_flush_out_buffer();
}
}
void usb_cdc_putc(char c) {
while (!usb_cdc_putready()) {
if (usb_cdc_put_buffer_free) {
usb_cdc_flush_out_buffer();
}
//delay_ms(500);
//printf(putc_tbe,"TBE=%U CNT=%U LST=%U\r\n",usb_tbe(USB_CDC_DATA_IN_ENDPOINT), usb_cdc_put_buffer_nextin, usb_cdc_last_data_packet_size);
}
usb_cdc_putc_fast(c);
}
#include <ctype.h>
BYTE gethex1_usb() {
char digit;
digit = usb_cdc_getc();
//usb_cdc_putc(digit);
if(digit<='9')
return(digit-'0');
else
return((toupper(digit)-'A')+10);
}
BYTE gethex_usb() {
int lo,hi;
hi = gethex1_usb();
lo = gethex1_usb();
if(lo==0xdd)
return(hi);
else
return( hi*16+lo );
}
void get_string_usb(char* s, int max) {
int len;
char c;
--max;
len=0;
do {
c=usb_cdc_getc();
if(c==8) { // Backspace
if(len>0) {
len--;
usb_cdc_putc(c);
usb_cdc_putc(' ');
usb_cdc_putc(c);
}
} else if ((c>=' ')&&(c<='~'))
if(len<max) {
s[len++]=c;
usb_cdc_putc(c);
}
} while(c!=13);
s[len]=0;
}
// stdlib.h is required for the ato_ conversions
// in the following functions
#ifdef _STDLIB
signed int get_int_usb() {
char s[5];
signed int i;
get_string_usb(s, 5);
i=atoi(s);
return(i);
}
signed long get_long_usb() {
char s[7];
signed long l;
get_string_usb(s, 7);
l=atol(s);
return(l);
}
float get_float_usb() {
char s[20];
float f;
get_string_usb(s, 20);
f = atof(s);
return(f);
}
#endif
| 2.046875 | 2 |
2024-11-18T20:55:29.737936+00:00 | 2023-01-31T12:43:06 | 541bca8ddf02a34c9dcfb20c28cc98f4c40d22fe | {
"blob_id": "541bca8ddf02a34c9dcfb20c28cc98f4c40d22fe",
"branch_name": "refs/heads/master",
"committer_date": "2023-01-31T12:43:06",
"content_id": "2751c27fbb3343e32a559bebb92eb4fb773740ff",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "e8ec930d559b2a9970cbeff369616ba67f60ab67",
"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": 204930963,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2284,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/io.h",
"provenance": "stackv2-0092.json.gz:37439",
"repo_name": "halderen/suitcase",
"revision_date": "2023-01-31T12:43:06",
"revision_id": "cc1841673b18048cc66377ce93862f891fb0473f",
"snapshot_id": "615d3ea9999d8fa6565d1b22a627c2664004843a",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/halderen/suitcase/cc1841673b18048cc66377ce93862f891fb0473f/io.h",
"visit_date": "2023-02-09T16:26:56.141046"
} | stackv2 | /*
* Copyright (c) 2022 A.W. van Halderen
* 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 ``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 BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef IO_H
#define IO_H
static inline int
readfully(int fd, char* buffer, int size)
{
int count;
int index = 0;
while(index < size) {
count = read(fd, &(buffer[index]), size - index);
if(count <= 0)
return (count < 0 ? -1 : 1);
index += count;
}
return 0;
}
static inline int
writefully(int fd, char* buffer, int size)
{
int count;
int index = 0;
while(index < size) {
count = write(fd, &(buffer[index]), size - index);
if(count < 0 && errno != EAGAIN && errno != EINTR)
return -1;
else
index += count;
}
return 0;
}
static inline int
readpartially(int fd, char* buffer, int* index, int size)
{
int count;
count = read(fd, &(buffer[*index]), size - *index);
if(count <= 0) {
*index = 0;
return 0;
}
*index += count;
if(*index >= size)
return 1;
else
return 0;
}
#endif
| 2.125 | 2 |
2024-11-18T20:55:30.370541+00:00 | 2018-11-28T14:22:51 | 52e0015e91caf76074536c34f69f928de86fc530 | {
"blob_id": "52e0015e91caf76074536c34f69f928de86fc530",
"branch_name": "refs/heads/master",
"committer_date": "2018-11-28T14:22:51",
"content_id": "bca31a4236ff2082c11e66f9465f489882b41829",
"detected_licenses": [
"MIT"
],
"directory_id": "f05973e44be1ce06d8a966dc10795a21d46d2e1e",
"extension": "c",
"filename": "port.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": 5709,
"license": "MIT",
"license_type": "permissive",
"path": "/FreeRTOSv10.1.1/FreeRTOS/Source/portable/GCC/RaspberryPi/port.c",
"provenance": "stackv2-0092.json.gz:37952",
"repo_name": "zeoneo/Raspberry-Pi",
"revision_date": "2018-11-28T14:22:51",
"revision_id": "110ad2e902a66f7eca01f2c30e908fa615328d41",
"snapshot_id": "ab73a974b7053b545dfa2caea7458095b3d2ba12",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/zeoneo/Raspberry-Pi/110ad2e902a66f7eca01f2c30e908fa615328d41/FreeRTOSv10.1.1/FreeRTOS/Source/portable/GCC/RaspberryPi/port.c",
"visit_date": "2020-04-09T02:29:08.350244"
} | stackv2 | /*
* Raspberry Pi Porting layer for FreeRTOS.
*/
#include "FreeRTOS.h"
#include "task.h"
#include "rpi-smartstart.h"
#include "rpi-irq.h"
/* Constants required to setup the task context. */
#define portINITIAL_SPSR ( ( portSTACK_TYPE ) 0x1f ) /* System mode, ARM mode, interrupts enabled. */
#define portTHUMB_MODE_BIT ( ( portSTACK_TYPE ) 0x20 )
#define portINSTRUCTION_SIZE ( ( portSTACK_TYPE ) 4 )
#define portNO_CRITICAL_SECTION_NESTING ( ( portSTACK_TYPE ) 0 )
#define portTIMER_PRESCALE ( ( unsigned long ) 0xF9 )
/*-----------------------------------------------------------*/
/* Setup the timer to generate the tick interrupts. */
static void prvSetupTimerInterrupt( void );
/*
* The scheduler can only be started from ARM mode, so
* vPortISRStartFirstSTask() is defined in portISR.c.
*/
extern void vPortISRStartFirstTask( void );
/*-----------------------------------------------------------*/
/*
* Initialise the stack of a task to look exactly as if a call to
* portSAVE_CONTEXT had been called.
*
* See header file for description.
*/
portSTACK_TYPE *pxPortInitialiseStack( portSTACK_TYPE *pxTopOfStack, pdTASK_CODE pxCode, void *pvParameters )
{
portSTACK_TYPE *pxOriginalTOS;
pxOriginalTOS = pxTopOfStack;
/* To ensure asserts in tasks.c don't fail, although in this case the assert
is not really required. */
pxTopOfStack--;
/* Setup the initial stack of the task. The stack is set exactly as
expected by the portRESTORE_CONTEXT() macro. */
/* First on the stack is the return address - which in this case is the
start of the task. The offset is added to make the return address appear
as it would within an IRQ ISR. */
*pxTopOfStack = ( portSTACK_TYPE ) pxCode + portINSTRUCTION_SIZE;
pxTopOfStack--;
*pxTopOfStack = ( portSTACK_TYPE ) 0xaaaaaaaa; /* R14 */
pxTopOfStack--;
*pxTopOfStack = ( portSTACK_TYPE ) pxOriginalTOS; /* Stack used when task starts goes in R13. */
pxTopOfStack--;
*pxTopOfStack = ( portSTACK_TYPE ) 0x12121212; /* R12 */
pxTopOfStack--;
*pxTopOfStack = ( portSTACK_TYPE ) 0x11111111; /* R11 */
pxTopOfStack--;
*pxTopOfStack = ( portSTACK_TYPE ) 0x10101010; /* R10 */
pxTopOfStack--;
*pxTopOfStack = ( portSTACK_TYPE ) 0x09090909; /* R9 */
pxTopOfStack--;
*pxTopOfStack = ( portSTACK_TYPE ) 0x08080808; /* R8 */
pxTopOfStack--;
*pxTopOfStack = ( portSTACK_TYPE ) 0x07070707; /* R7 */
pxTopOfStack--;
*pxTopOfStack = ( portSTACK_TYPE ) 0x06060606; /* R6 */
pxTopOfStack--;
*pxTopOfStack = ( portSTACK_TYPE ) 0x05050505; /* R5 */
pxTopOfStack--;
*pxTopOfStack = ( portSTACK_TYPE ) 0x00000000; /* R4 Must be zero see the align 8 issue in portSaveContext */
pxTopOfStack--;
*pxTopOfStack = ( portSTACK_TYPE ) 0x03030303; /* R3 */
pxTopOfStack--;
*pxTopOfStack = ( portSTACK_TYPE ) 0x02020202; /* R2 */
pxTopOfStack--;
*pxTopOfStack = ( portSTACK_TYPE ) 0x01010101; /* R1 */
pxTopOfStack--;
/* When the task starts it will expect to find the function parameter in
R0. */
*pxTopOfStack = ( portSTACK_TYPE ) pvParameters; /* R0 */
pxTopOfStack--;
/* The last thing onto the stack is the status register, which is set for
system mode, with interrupts enabled. */
*pxTopOfStack = ( portSTACK_TYPE ) portINITIAL_SPSR;
if( ( ( unsigned long ) pxCode & 0x01UL ) != 0x00 )
{
/* We want the task to start in thumb mode. */
*pxTopOfStack |= portTHUMB_MODE_BIT;
}
pxTopOfStack--;
/* Some optimisation levels use the stack differently to others. This
means the interrupt flags cannot always be stored on the stack and will
instead be stored in a variable, which is then saved as part of the
tasks context. */
*pxTopOfStack = portNO_CRITICAL_SECTION_NESTING;
return pxTopOfStack;
}
/*-----------------------------------------------------------*/
portBASE_TYPE xPortStartScheduler( void )
{
/* Start the timer that generates the tick ISR. Interrupts are disabled
here already. */
prvSetupTimerInterrupt();
/* Start the first task. */
vPortISRStartFirstTask();
/* Should not get here! */
return 0;
}
/*-----------------------------------------------------------*/
void vPortEndScheduler( void )
{
/* It is unlikely that the ARM port will require this function as there
is nothing to return to. */
}
/*-----------------------------------------------------------*/
/*
* This is the TICK interrupt service routine, note. no SAVE/RESTORE_CONTEXT here
* as thats done in the bottom-half of the ISR.
*
* See bt_interrupts.c in the RaspberryPi Drivers folder.
*/
void vTickISR (uint8_t coreNum, uint8_t nIRQ, void *pParam )
{
(void)coreNum;
(void)nIRQ;
(void)pParam;
xTaskIncrementTick();
#if configUSE_PREEMPTION == 1
vTaskSwitchContext();
#endif
}
/*
* Setup the timer 0 to generate the tick interrupts at the required frequency.
*/
extern void vFreeRTOS_ISR(void);
extern void vPortYieldProcessor(void);
static void prvSetupTimerInterrupt( void )
{
//unsigned long ulCompareMatch;
///* Calculate the match value required for our wanted tick rate. */
//ulCompareMatch = 1000000 / configTICK_RATE_HZ;
///* Protect against divide by zero. Using an if() statement still results
//in a warning - hence the #if. */
//#if portPRESCALE_VALUE != 0
//{
//ulCompareMatch /= ( portPRESCALE_VALUE + 1 );
//}
//#endif
DisableInterrupts();
irqRegisterHandler(0, 83, &vTickISR, &ClearLocalTimerIrq, NULL);
irqEnableHandler(0, 83);
//coreEnableIrq(64);
//TimerIrqSetup((1000000/configTICK_RATE_HZ), 0); // Peripheral clock is 1Mhz so divid by frequency we want
LocalTimerSetup((1000000 / configTICK_RATE_HZ), 0, 0);
EnableInterrupts();
}
/*-----------------------------------------------------------*/
| 2.59375 | 3 |
2024-11-18T20:55:31.903371+00:00 | 2020-06-17T01:21:06 | 8c6cf6be1f00e7c0bc2dcfcdcee615941b342983 | {
"blob_id": "8c6cf6be1f00e7c0bc2dcfcdcee615941b342983",
"branch_name": "refs/heads/master",
"committer_date": "2020-06-17T01:21:06",
"content_id": "e1c8a9f6fb223a9d965e466d0f92849c2e300bc7",
"detected_licenses": [
"MIT"
],
"directory_id": "117f69983b6f2ae635a7a2192bd50b016ded2ed6",
"extension": "c",
"filename": "ClientApp.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 263522403,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 27403,
"license": "MIT",
"license_type": "permissive",
"path": "/src/ClientApp.c",
"provenance": "stackv2-0092.json.gz:38339",
"repo_name": "lukeb10/Chess_AI",
"revision_date": "2020-06-17T01:21:06",
"revision_id": "f4975743d85038842d10143f22db92eebbde75a5",
"snapshot_id": "f88b7170d7942fd16b4a46b21fdbb4c307ab9ce6",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/lukeb10/Chess_AI/f4975743d85038842d10143f22db92eebbde75a5/src/ClientApp.c",
"visit_date": "2022-11-06T06:48:11.155650"
} | stackv2 | /* source code file for client gui */
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <gtk/gtk.h>
// for client
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <unistd.h>
//#include "server.h"
#include "ClientApp.h"
/* GLOBAL GTK WIDGETS */
/* login/register window */
GtkWidget *login_window ;
GtkWidget *login_vbox ;
GtkWidget *logo ; // queen chess icon
GtkWidget *username_label ;
GtkWidget *username_entry ; // if username DNE or password incorrect, display message here
GtkWidget *password_label ;
GtkWidget *password_entry ;
GtkWidget *login_btn ; // login button
GtkWidget *or_label ;
GtkWidget *create_btn ; // create new account button
/* friends list window */
GtkWidget *friends_window ;
GtkWidget *friends_vbox ;
GtkWidget *friends_hbox1 ; // top two buttons [chat, logout]
GtkWidget *friends_hbox2 ;
GtkWidget *chat_btn ;
GtkWidget *block_btn ;
GtkWidget *show_btn ;
GtkWidget *logout_btn1 ; // logout_btn2 in chat room window
GtkWidget *friends_label ;
GtkWidget *friends_display ;
GtkWidget *friends_entry ;
//GtkWidget *add_btn ;
//GtkWidget *delete_btn ;
GtkTextBuffer *friends_buffer ;
GtkWidget *friends_scroll ;
/* chat room window */
GtkWidget *chat_window ;
GtkWidget *chat_vbox ;
GtkWidget *chat_hbox1 ;
GtkWidget *chat_hbox2 ;
GtkWidget *chat_label ;
GtkWidget *friends_btn ;
GtkWidget *logout_btn2 ; // logout_btn1 in friends list window
GtkWidget *chat_display ;
GtkWidget *chat_entry ;
GtkWidget *send_btn ;
GtkWidget *refresh_btn ;
GtkTextBuffer *chat_buffer ;
GtkWidget *chat_scroll ;
#define BUFFSIZE 256
int SocketFD, PortNo, n;
struct sockaddr_in ServerAddress;
struct hostent *Server;
char SendBuf[256];
char RecvBuf[256];
const char *Program = NULL;
void FatalError(const char *ErrorMsg);
void write_socket();
void read_socket();
void close_session();
char *blockName[9];
static int blocked=0;
char friends[10][20];
gchar *u = NULL;
/* main program */
int main (int argc, char *argv[]) {
int h;
for(h=0; h<9; h++){
blockName[h] = (char*) malloc(sizeof(char) *99);
}
for (int i=0; i<10; i++)
{
friends[i][0] = '\0';
}
Program = argv[0];
printf("%s: Starting...\n", argv[0]);
if (argc < 3)
{
fprintf(stderr, "Usage: %s hostname port\n", Program);
exit(10);
}
Server = gethostbyname(argv[1]);
if (Server == NULL)
{
fprintf(stderr, "%s: no such host named '%s'\n", Program, argv[1]);
exit(10);
}
PortNo = atoi(argv[2]);
if (PortNo <= 2000)
{
fprintf(stderr, "%s: invalid port number %d, should be > 2000\n", Program, PortNo);
exit(10);
}
ServerAddress.sin_family = AF_INET;
ServerAddress.sin_port = htons(PortNo);
ServerAddress.sin_addr = *(struct in_addr*)Server->h_addr_list[0];
/*SocketFD = socket(AF_INET, SOCK_STREAM, 0);
if (SocketFD < 0)
{
FatalError("socket creation failed");
}
printf("%s: Connecting to the server at port %d...\n", Program, ntohs(ServerAddress.sin_port));
if (connect(SocketFD, (struct sockaddr*)&ServerAddress,sizeof(struct sockaddr_in)) < 0)
{
FatalError("connecting to server failed");
}
close_session();*/
// GTK
char msg[MAX_MSGLEN] ; // for chat interface
// TESTING //
int t = 0;
gtk_init(&argc, &argv) ; // initialize GTK libraries
t = LinkWidgets() ;
//char *friends[5] = {"Brian", "Nathan", "Luke", "Josh", "David"} ;
//display_friends(friends) ;
if (t == 1) {
exit(0) ;
}
Callbacks() ;
gtk_widget_show(login_window) ;
gtk_main() ; // wait for events
//free(blockName);
return 0 ;
}
/* external function declarations */
int LinkWidgets() { // return 0 for success, 1 for error
GtkBuilder *login, *chat, *friends ; // three different glade files
GError *error = NULL ;
/* build/link from login.glade file */
login = gtk_builder_new() ;
if (!gtk_builder_add_from_file(login, "../src/login.glade", &error)) {
g_warning("%s", error->message) ;
g_free(error) ;
return 1 ;
}
login_window = GTK_WIDGET(gtk_builder_get_object(login, "login_window")) ;
gtk_window_set_modal(GTK_WINDOW(login_window), true) ;
gtk_widget_set_size_request(GTK_WIDGET(login_window), WINDOW_WIDTH, WINDOW_HEIGHT) ;
gtk_builder_connect_signals(login, NULL) ;
login_vbox = GTK_WIDGET(gtk_builder_get_object(login, "login_vbox")) ;
logo = GTK_WIDGET(gtk_builder_get_object(login, "logo")) ;
username_label = GTK_WIDGET(gtk_builder_get_object(login, "username_label")) ;
username_entry = GTK_WIDGET(gtk_builder_get_object(login, "username_entry")) ;
password_label = GTK_WIDGET(gtk_builder_get_object(login, "password_label")) ;
password_entry = GTK_WIDGET(gtk_builder_get_object(login, "password_entry")) ;
login_btn = GTK_WIDGET(gtk_builder_get_object(login, "login_btn")) ;
or_label = GTK_WIDGET(gtk_builder_get_object(login, "or_label")) ;
create_btn = GTK_WIDGET(gtk_builder_get_object(login, "create_btn")) ;
g_object_unref(login) ;
error = NULL ;
/* build/link from friends.glade file */
friends = gtk_builder_new() ;
if (!gtk_builder_add_from_file(friends, "../src/friends.glade", &error)) {
g_warning("%s", error->message) ;
g_free(error) ;
return 1 ;
}
friends_window = GTK_WIDGET(gtk_builder_get_object(friends, "friends_window")) ;
gtk_window_set_modal(GTK_WINDOW(friends_window), true) ;
gtk_widget_set_size_request(GTK_WIDGET(friends_window), WINDOW_WIDTH, WINDOW_HEIGHT) ;
gtk_builder_connect_signals(friends, NULL) ;
friends_vbox = GTK_WIDGET(gtk_builder_get_object(friends, "friends_vbox")) ;
friends_hbox1 = GTK_WIDGET(gtk_builder_get_object(friends, "friends_hbox1")) ;
friends_hbox2 = GTK_WIDGET(gtk_builder_get_object(friends, "friends_hbox2")) ;
friends_label = GTK_WIDGET(gtk_builder_get_object(friends, "friends_label")) ;
friends_scroll = GTK_WIDGET(gtk_builder_get_object(friends, "friends_scroll")) ;
friends_display = GTK_WIDGET(gtk_builder_get_object(friends, "friends_display")) ;
gtk_text_view_set_editable(GTK_TEXT_VIEW(friends_display), false) ; // make friends list read-only
friends_buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(friends_display)) ;
friends_entry = GTK_WIDGET(gtk_builder_get_object(friends, "friends_entry")) ;
show_btn = GTK_WIDGET(gtk_builder_get_object(friends, "show_btn")) ;
//delete_btn = GTK_WIDGET(gtk_builder_get_object(friends, "delete_btn")) ;
block_btn = GTK_WIDGET(gtk_builder_get_object(friends, "block_btn")) ;
chat_btn = GTK_WIDGET(gtk_builder_get_object(friends, "chat_btn")) ;
logout_btn1 = GTK_WIDGET(gtk_builder_get_object(friends, "logout_btn1")) ;
g_object_unref(friends) ;
error = NULL ;
/* build/link from chat.glade file */
chat = gtk_builder_new() ;
if (!gtk_builder_add_from_file(chat, "../src/chat.glade", &error)) {
g_warning("%s", error->message) ;
g_free(error) ;
return 1 ;
}
chat_window = GTK_WIDGET(gtk_builder_get_object(chat, "chat_window")) ;
gtk_window_set_modal(GTK_WINDOW(chat_window), true) ;
gtk_widget_set_size_request(GTK_WIDGET(chat_window), WINDOW_WIDTH, WINDOW_HEIGHT) ;
gtk_builder_connect_signals(chat, NULL) ;
chat_vbox = GTK_WIDGET(gtk_builder_get_object(chat, "chat_vbox")) ;
chat_hbox1 = GTK_WIDGET(gtk_builder_get_object(chat, "chat_hbox1")) ;
chat_hbox2 = GTK_WIDGET(gtk_builder_get_object(chat, "chat_hbox2")) ;
chat_label = GTK_WIDGET(gtk_builder_get_object(chat, "chat_label")) ;
chat_scroll = GTK_WIDGET(gtk_builder_get_object(chat, "chat_scroll")) ;
chat_display = GTK_WIDGET(gtk_builder_get_object(chat, "chat_display")) ;
gtk_text_view_set_editable(GTK_TEXT_VIEW(chat_display), false) ; // make chat display read-only
chat_buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(chat_display)) ;
chat_entry = GTK_WIDGET(gtk_builder_get_object(chat, "chat_entry")) ;
send_btn = GTK_WIDGET(gtk_builder_get_object(chat, "send_btn")) ;
refresh_btn = GTK_WIDGET(gtk_builder_get_object(chat, "refresh_btn")) ;
friends_btn = GTK_WIDGET(gtk_builder_get_object(chat, "friends_btn")) ;
logout_btn2 = GTK_WIDGET(gtk_builder_get_object(chat, "logout_btn2")) ;
g_object_unref(chat) ;
error = NULL ;
return 0 ;
}
/* instantiate all event callbacks */
void Callbacks() {
/* login/register window callbacks */
g_signal_connect(login_btn, "clicked", G_CALLBACK(click_login), NULL) ;
g_signal_connect(create_btn, "clicked", G_CALLBACK(click_create), NULL) ;
g_signal_connect(login_window, "destroy", G_CALLBACK(EndProgram), NULL) ;
/* friends list window callbacks */
g_signal_connect(chat_btn, "clicked", G_CALLBACK(click_chat), NULL) ;
g_signal_connect(logout_btn1, "clicked", G_CALLBACK(EndProgram), NULL) ;
g_signal_connect(block_btn, "clicked", G_CALLBACK(click_block), NULL) ;
//g_signal_connect(add_btn, "clicked", G_CALLBACK(click_add), NULL) ;
//g_signal_connect(delete_btn, "clicked", G_CALLBACK(click_delete), NULL) ;
g_signal_connect(friends_window, "destroy", G_CALLBACK(EndProgram), NULL) ;
/* chat room window callbacks */
g_signal_connect(friends_btn, "clicked", G_CALLBACK(click_friends), NULL) ;
g_signal_connect(refresh_btn, "clicked", G_CALLBACK(click_refresh), NULL) ;
g_signal_connect(show_btn, "clicked", G_CALLBACK(display_friends), NULL) ;
g_signal_connect(logout_btn2, "clicked", G_CALLBACK(EndProgram), NULL) ;
g_signal_connect(send_btn, "clicked", G_CALLBACK(click_send), NULL) ;
g_signal_connect(chat_window, "destroy", G_CALLBACK(EndProgram), NULL) ;
}
/* conversion function from gchar to char */
void convert(const gchar *src, char dest[]) {sprintf(dest, "%s", src) ; }
/* callback function definitions */
static void display_friends(GtkWidget *widget, gpointer data) { // need to change this function once user struct is complete
/* int size ;
gchar *temp = NULL;
//for (size = 0; friends[size][0] != NULL; size++);
SocketFD = socket(AF_INET, SOCK_STREAM, 0);
if (SocketFD < 0)
FatalError("socket creation failed");
printf("%s: Connecting to the server at port %d...\n", Program, ntohs(ServerAddress.sin_port));
if (connect(SocketFD, (struct sockaddr*)&ServerAddress,sizeof(struct sockaddr_in)) < 0)
FatalError("connecting to server failed");
strcpy(SendBuf, "DISPLAY FRIENDS");
n = write(SocketFD, SendBuf, strlen(SendBuf));
if (n < 0)
FatalError("writing");
n = read(SocketFD, RecvBuf, BUFFSIZE-1);
if (n<0)
FatalError("reading");
RecvBuf[n] = 0;
strcpy(SendBuf, "ok");
n = write(SocketFD, SendBuf, strlen(SendBuf));
if (n<0)
FatalError("writing");
int index = 0;
for (int i=0; i<10; i++)
{
n = read(SocketFD, RecvBuf, BUFFSIZE-1);
if (n<0)
FatalError("reading");
RecvBuf[n] = 0;
if (strcmp(RecvBuf, "@") != 0)
{
if (index == 10)
index = 0;
strcpy(friends[index], RecvBuf);
index++;
}
strcpy(SendBuf, "got it");
n = write(SocketFD, SendBuf, strlen(SendBuf));
if (n<0)
FatalError("writing");
}
close(SocketFD);
*/
/*bool flag;
for (int i = 0; i < size; i++) {
flag = true;
temp = g_malloc(sizeof(friends[i])) ;
g_stpcpy(temp, friends[i]) ;
for(int j= 0; j<9; j++){
if(strcmp(friends[i], blockName[j])==0){
flag = false;
}
}
if (flag)
{
gtk_text_buffer_insert_at_cursor(friends_buffer, temp, (gint) strlen(temp)) ;
gtk_text_buffer_insert_at_cursor(friends_buffer, "\n", 1) ;
}
temp[0] = '\0' ;
g_free(temp) ;
}*/
/* int size ;
gchar *temp = NULL;
for (size = 0; friends[size] != NULL; size++);
bool flag;
for (int i = 0; i < size; i++) {
flag = true;
temp = g_malloc(sizeof(friends[i])) ;
g_stpcpy(temp, friends[i]) ;
for(int j= 0; j<9; j++){
if(strcmp(friends[i], blockName[j])==0){
flag = false;
}
}
if (flag)
{
gtk_text_buffer_insert_at_cursor(friends_buffer, temp, (gint) strlen(temp)) ;
gtk_text_buffer_insert_at_cursor(friends_buffer, "\n", 1) ;
}
temp[0] = '\0' ;
g_free(temp) ;
}*/
//gtk_text_buffer_insert_at_cursor(friends_buffer, u, (gint) strlen(u)) ;
//gtk_text_buffer_insert_at_cursor(friends_buffer, "\n", 1) ;
}
static void click_login(GtkWidget *widget, gpointer data) { // clicking "Existing User: LOGIN" button
/* check if username/password are valid
* if invalid, ask user to try again
* if valid, log in account, close login window, open friends list window
*/
const gchar *username, *password ;
bool uname, pword ; // whether or not username exists | whether or not password is correct
username = gtk_entry_get_text(GTK_ENTRY(username_entry)) ;
password = gtk_entry_get_text(GTK_ENTRY(password_entry)) ;
SocketFD = socket(AF_INET, SOCK_STREAM, 0);
if (SocketFD < 0)
FatalError("socket creation failed");
printf("%s: Connecting to the server at port %d...\n", Program, ntohs(ServerAddress.sin_port));
if (connect(SocketFD, (struct sockaddr*)&ServerAddress,sizeof(struct sockaddr_in)) < 0)
FatalError("connecting to server failed");
strcpy(SendBuf, "LOG IN");
n = write(SocketFD, SendBuf, strlen(SendBuf));
if (n < 0)
FatalError("writing to socket failed");
n = read(SocketFD, RecvBuf, BUFFSIZE-1);
if (n < 0)
FatalError("reading from socket failed");
RecvBuf[n] = 0;
printf("%s\n", RecvBuf);
convert(username, SendBuf);
n = write(SocketFD, SendBuf, strlen(SendBuf));
if (n < 0)
FatalError("writing to socket failed");
n = read(SocketFD, RecvBuf, BUFFSIZE-1);
if (n < 0)
FatalError("reading from socket failed");
RecvBuf[n] = 0;
convert(password, SendBuf);
n = write(SocketFD, SendBuf, strlen(SendBuf));
if (n < 0)
FatalError("writing to socket failed");
n = read(SocketFD, RecvBuf, BUFFSIZE-1);
if (n < 0)
FatalError("reading from socket failed");
RecvBuf[n] = 0;
if (strcmp(RecvBuf, "logged in") == 0)
{
close(SocketFD);
gtk_widget_show(friends_window) ;
//display_friends(friends) ;
gtk_widget_hide(login_window) ;
}
else
{
close(SocketFD);
gtk_entry_set_text(GTK_ENTRY(username_entry), "Password or Id is incorrect. Please try again.") ;
gtk_editable_select_region(GTK_EDITABLE(username_entry), 0, GTK_ENTRY(username_entry)->text_length) ;
}
/* uname = true ; // testing
pword = false ; // testing
||||||| merged common ancestors
uname = true ; // testing
pword = false ; // testing
=======
uname = true ; // testing
pword = true ; // testing
>>>>>>> 0e95025a096f7b7ff455816ad9aaac321e9773cf
// run functions to see if username exists OR if password is correct
if (uname && pword) { // valid
// //Check user login by entering username and password feilds
//if (strcpy(uname, XXX) == 0 && strcpy(pword, XXX) == 0){}
gtk_widget_show(friends_window) ;
//display_friends(friends) ;
gtk_widget_hide(login_window) ;
} else if (uname && !pword) { // password is incorrect
gtk_entry_set_text(GTK_ENTRY(username_entry), "Password is incorrect. Please try again.") ;
gtk_editable_select_region(GTK_EDITABLE(username_entry), 0, GTK_ENTRY(username_entry)->text_length) ;
} else if (!uname) { // username doesn't exist
gtk_entry_set_text(GTK_ENTRY(username_entry), "Username does not exist. Please try again.") ;
gtk_editable_select_region(GTK_EDITABLE(username_entry), 0, GTK_ENTRY(username_entry)->text_length) ;
<<<<<<< HEAD
} */
//}
//}
//g_strlcpy(u, username, strlen(username)) ;
}
static void click_create(GtkWidget *widget, gpointer data) { // clicking "New User: CREATE ACCOUNT" button
/* check if username exists
* if exists, ask user to try again
* if doesn't exist, create account, close login window, open friends list window
*/
const gchar *username, *password ;
bool uname ; // whether or username exists
username = gtk_entry_get_text(GTK_ENTRY(username_entry)) ;
password = gtk_entry_get_text(GTK_ENTRY(password_entry)) ;
// check if username exists
//uname = false ; // testing
/*if (!uname) {
// create account function
gtk_widget_show(friends_window) ;
// display_friends()
gtk_widget_hide(login_window) ;
} else {
gtk_entry_set_text(GTK_ENTRY(username_entry), "Username already exists. Please try again.") ;
gtk_editable_select_region(GTK_EDITABLE(username_entry), 0, GTK_ENTRY(username_entry)->text_length) ;
} */
SocketFD = socket(AF_INET, SOCK_STREAM, 0);
if (SocketFD < 0)
FatalError("socket creation failed");
printf("%s: Connecting to the server at port %d...\n", Program, ntohs(ServerAddress.sin_port));
if (connect(SocketFD, (struct sockaddr*)&ServerAddress,sizeof(struct sockaddr_in)) < 0)
FatalError("connecting to server failed");
strcpy(SendBuf, "CREATE ACCOUNT");
n = write(SocketFD, SendBuf, strlen(SendBuf));
if (n < 0)
FatalError("writing to socket failed");
n = read(SocketFD, RecvBuf, BUFFSIZE-1);
if (n < 0)
FatalError("reading from socket failed");
RecvBuf[n] = 0;
printf("%s\n", RecvBuf);
//printf("%s: response from server: %s\n", Program, RecvBuf);
if (strcmp(RecvBuf, "ok") == 0)
{
convert(username, SendBuf);
printf("%s\n", SendBuf);
n = write(SocketFD, SendBuf, strlen(SendBuf));
if (n < 0)
FatalError("writing to socket failed");
n = read(SocketFD, RecvBuf, BUFFSIZE-1);
if (n < 0)
FatalError("reading from socket failed");
RecvBuf[n] = 0;
if (strcmp(RecvBuf, "ok") == 0)
{
printf("id send successfully\n");
}
convert(password, SendBuf);
n = write(SocketFD, SendBuf, strlen(SendBuf));
if (n < 0)
FatalError("writing to socket failed");
n = read(SocketFD, RecvBuf, BUFFSIZE-1);
// already sent the id and pass
if (n < 0)
FatalError("reading from socket failed");
RecvBuf[n] = 0;
n = read(SocketFD, RecvBuf, BUFFSIZE-1);
if (n < 0)
FatalError("reading from socket failed");
RecvBuf[n] = 0;
printf("server returned... %s\n", RecvBuf);
strcpy(SendBuf, "ok");
n = write(SocketFD, SendBuf, BUFFSIZE-1);
if (n<0)
FatalError("writing");
printf("closing connection\n");
close(SocketFD);
gtk_widget_show(friends_window) ;
//display_friends();//userAccount[10]);
gtk_widget_hide(login_window) ;
/*if (strcmp(RecvBuf, "ACCOUNT ADDED") == 0)
{
printf("inside account added\n");
printf("closing connection\n");
close(SocketFD);
gtk_widget_show(friends_window) ;
//display_friends();//userAccount[10]);
gtk_widget_hide(login_window) ;
//display_friends();
}
else
{
printf("%s: Closing the connection...\n", Program);
close(SocketFD);
gtk_entry_set_text(GTK_ENTRY(username_entry), "Username already exists. Please try again.") ;
gtk_editable_select_region(GTK_EDITABLE(username_entry), 0, GTK_ENTRY(username_entry)->text_length) ;
}*/
}
//printf("%s: Closing the connection...\n", Program);
//close(SocketFD);
//g_strlcpy(u, username, strlen(username)) ;
}
static void click_chat(GtkWidget *widget, gpointer data) {
bool flag ;
/* user is on friends list = TRUE
* user is NOT on friends list = FALSE
*/
const gchar *username ;
username = gtk_entry_get_text(GTK_ENTRY(username_entry)) ;
if (strlen(username) == 0) { // if the user forgets to input a username
gtk_entry_set_text(GTK_ENTRY(friends_entry), "Please input a username to ADD/DELETE/CHAT.") ;
gtk_editable_select_region(GTK_EDITABLE(friends_entry), 0, GTK_ENTRY(friends_entry)->text_length) ;
}
// run delete function to get a value for flag
flag = true ; // testing
if (flag) {
// connect to other client to chat
gtk_widget_show(chat_window) ;
gtk_entry_set_text(GTK_ENTRY(chat_entry), "Max characters 0/256.") ;
gtk_widget_hide(friends_window) ;
} else {
gtk_entry_set_text(GTK_ENTRY(friends_entry), "Please input a username that is on your friends list.") ;
gtk_editable_select_region(GTK_EDITABLE(friends_entry), 0, GTK_ENTRY(friends_entry)->text_length) ;
}
}
static void click_friends(GtkWidget *widget, gpointer data) {
gtk_widget_show(friends_window) ;
//display_friends(friends) ;
gtk_widget_hide(chat_window) ;
}
static void click_block(GtkWidget *widget, gpointer data) {
const gchar *block ;
char *converter;
block = gtk_entry_get_text(GTK_ENTRY(friends_entry)) ;
if (strlen(block) == 0) { // if the user forgets to input a username
gtk_entry_set_text(GTK_ENTRY(friends_entry), "Please input a username to BLOCK.") ;
gtk_editable_select_region(GTK_EDITABLE(friends_entry), 0, GTK_ENTRY(friends_entry)->text_length) ;
}
//convert(block, converter);
//strcpy(blockName[blocked],converter);
//blocked++;
// send block to the server
SocketFD = socket(AF_INET, SOCK_STREAM, 0);
if (SocketFD < 0)
FatalError("socket creation failed");
printf("%s: Connecting to the server at port %d...\n", Program, ntohs(ServerAddress.sin_port));
if (connect(SocketFD, (struct sockaddr*)&ServerAddress,sizeof(struct sockaddr_in)) < 0)
FatalError("connecting to server failed");
strcpy(SendBuf, "BLOCK");
n = write(SocketFD, SendBuf, strlen(SendBuf));
if (n < 0)
FatalError("writing to datasocket failed");
n = read(SocketFD, RecvBuf, BUFFSIZE-1);
if (n < 0)
FatalError("reading from socket failed");
RecvBuf[n] = 0;
convert(block, SendBuf);
n = write(SocketFD, SendBuf, strlen(SendBuf));
if (n < 0)
FatalError("writing to datasocket failed");
printf("%s: Closing the connection...\n", Program);
close(SocketFD);
}
static void click_send(GtkWidget *widget, gpointer data) {
const gchar *message ;
message = gtk_entry_get_text(GTK_ENTRY(chat_entry)) ;
if (strlen(message) == 0) { // if message is empty
gtk_entry_set_text(GTK_ENTRY(chat_entry), "Please enter a valid message to send.") ;
gtk_editable_select_region(GTK_EDITABLE(chat_entry), 0, GTK_ENTRY(chat_entry)->text_length) ;
}
// send message to server function
//convert(message, SendBuf);
//write_socket();
SocketFD = socket(AF_INET, SOCK_STREAM, 0);
if (SocketFD < 0)
{
FatalError("socket creation failed");
}
printf("%s: Connecting to the server at port %d...\n", Program, ntohs(ServerAddress.sin_port));
if (connect(SocketFD, (struct sockaddr*)&ServerAddress,sizeof(struct sockaddr_in)) < 0)
{
FatalError("connecting to server failed");
}
strcpy(SendBuf, "SEND");
printf("%s: button is '%s'...\n", Program, SendBuf);
n = write(SocketFD, SendBuf, strlen(SendBuf));
if (n < 0)
{
FatalError("writing to socket failed");
}
n = read(SocketFD, RecvBuf, BUFFSIZE-1);
if (n < 0)
{
FatalError("reading from socket failed");
}
RecvBuf[n] = 0;
printf("%s: Received response: %s\n", Program, RecvBuf);
if (strcmp(RecvBuf, "ok") == 0)
{
convert(message, SendBuf);
printf("sending message\n");
n = write(SocketFD, SendBuf, strlen(SendBuf));
if (n < 0)
FatalError("writing to socket failed");
}
printf("%s: Closing the connection...\n", Program);
close(SocketFD);
// gtk_entry_set_text(GTK_ENTRY(chat_display), "%s: ", username) ;
//gtk_text_buffer_insert_at_cursor(chat_buffer, u, (gint) strlen(u)) ;
gtk_text_buffer_insert_at_cursor(chat_buffer, message, (gint) strlen(message)) ;
gtk_text_buffer_insert_at_cursor(chat_buffer, "\n", 1) ;
//gtk_text_view_set_buffer(GTK_TEXT_VIEW(chat_display), buffer) ; // not needed?
}
static void click_refresh(GtkWidget *widget, gpointer data) {
const gchar *message ;
// get message from server
// convert char to gchar
//read_socket();
SocketFD = socket(AF_INET, SOCK_STREAM, 0);
if (SocketFD < 0)
{
FatalError("socket creation failed");
}
printf("%s: Connecting to the server at port %d...\n", Program, ntohs(ServerAddress.sin_port));
if (connect(SocketFD, (struct sockaddr*)&ServerAddress,sizeof(struct sockaddr_in)) < 0)
{
FatalError("connecting to server failed");
}
strcpy(SendBuf, "REFRESH");
printf("%s: button is '%s'...\n", Program, SendBuf);
n = write(SocketFD, SendBuf, strlen(SendBuf));
if (n < 0)
{
FatalError("writing to socket failed");
}
n = read(SocketFD, RecvBuf, BUFFSIZE-1);
if (n < 0)
{
FatalError("reading from socket failed");
}
RecvBuf[n] = 0;
printf("%s: Received response: %s\n", Program, RecvBuf);
printf("%s: Closing the connection...\n", Program);
close(SocketFD);
message = g_malloc(sizeof(RecvBuf));
g_stpcpy(message, RecvBuf);
gtk_text_buffer_insert_at_cursor(chat_buffer, message, (gint) strlen(message)) ;
gtk_text_buffer_insert_at_cursor(chat_buffer, "\n", 1) ;
g_free(message);
}
static gboolean EndProgram(GtkWidget *widget, GdkEvent *event, gpointer data) {
/* If you return FALSE in the "delete_event" signal handler,
* GTK will emit the "destroy" signal. Returning TRUE means
* you don't want the window to be destroyed.
*
* This is useful for popping up 'are you sure you want to quit?'
* type diaglogs.
*/
/*gtk_widget_destroy(login_window) ;
gtk_widget_destroy(friends_window) ;
gtk_widget_destroy(chat_window) ;*/
gtk_main_quit() ;
return TRUE ;
}
void FatalError(const char *ErrorMsg)
{
fputs(Program, stderr);
fputs(": ", stderr);
perror(ErrorMsg);
fputs(Program, stderr);
fputs(": Exiting!\n", stderr);
exit(20);
}
void write_socket()
{
SocketFD = socket(AF_INET, SOCK_STREAM, 0);
if (SocketFD < 0)
{
FatalError("socket creation failed");
}
printf("%s: Connecting to the server at port %d...\n", Program, ntohs(ServerAddress.sin_port));
if (connect(SocketFD, (struct sockaddr*)&ServerAddress,sizeof(struct sockaddr_in)) < 0)
{
FatalError("connecting to server failed");
}
printf("%s: Sending message '%s'...\n", Program, SendBuf);
n = write(SocketFD, SendBuf, strlen(SendBuf));
if (n < 0)
{
FatalError("writing to socket failed");
}
close_session();
}
void read_socket()
{
SocketFD = socket(AF_INET, SOCK_STREAM, 0);
if (SocketFD < 0)
{
FatalError("socket creation failed");
}
printf("%s: Connecting to the server at port %d...\n", Program, ntohs(ServerAddress.sin_port));
if (connect(SocketFD, (struct sockaddr*)&ServerAddress,sizeof(struct sockaddr_in)) < 0)
{
FatalError("connecting to server failed");
}
printf("connected\n");
n = read(SocketFD, RecvBuf, BUFFSIZE-1);
if (n < 0)
{
FatalError("reading from socket failed");
}
//RecvBuf[n] = 0;
printf("%s: Received response: %s\n", Program, RecvBuf);
close_session();
}
void close_session()
{
printf("%s: Closing the connection...\n", Program);
close(SocketFD);
}
| 2.078125 | 2 |
2024-11-18T20:55:32.175847+00:00 | 2020-10-08T16:20:19 | 64649b0fffd8b52eb0c3c8e3ce868dfc4270aeda | {
"blob_id": "64649b0fffd8b52eb0c3c8e3ce868dfc4270aeda",
"branch_name": "refs/heads/main",
"committer_date": "2020-10-08T16:20:19",
"content_id": "884457fb8d30914a4414505da2e0a5a8187edc80",
"detected_licenses": [
"MIT"
],
"directory_id": "2f7c17258e9996dd991620ccfcde3a5b67e10812",
"extension": "c",
"filename": "file_disemvowel.c",
"fork_events_count": 0,
"gha_created_at": "2020-09-29T01:31:25",
"gha_event_created_at": "2020-09-29T01:31:34",
"gha_language": "Shell",
"gha_license_id": "MIT",
"github_id": 299473557,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2129,
"license": "MIT",
"license_type": "permissive",
"path": "/file_disemvowel/file_disemvowel.c",
"provenance": "stackv2-0092.json.gz:38856",
"repo_name": "umm-csci-3403-fall-2020/lab-4-beane-naber",
"revision_date": "2020-10-08T16:20:19",
"revision_id": "1c48ab99b7864effa3c68acbeebdd487bf012263",
"snapshot_id": "67eb90cd6928d5b2b74bec526cc6b6b74ce6efec",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/umm-csci-3403-fall-2020/lab-4-beane-naber/1c48ab99b7864effa3c68acbeebdd487bf012263/file_disemvowel/file_disemvowel.c",
"visit_date": "2022-12-24T04:02:22.995324"
} | stackv2 | #include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#define BUF_SIZE 1024
bool is_vowel(char c) { //Checks the given character if its a vowel or not
if (c == 'A' || c == 'a' || c == 'E' || c == 'e' || c == 'I' || c == 'i' || c == 'O' || c == 'o' || c == 'U' || c == 'u'){
return true;
} return false;
}
int copy_non_vowels(int num_chars, char* in_buf, char* out_buf) {
int index = 0;
for (int i=0; i < num_chars - 1; i++) { //go through all charcters given
if (is_vowel(in_buf[i]) == false){ //checks if those characters are vowels or not in the given in_buf
out_buf[index] = in_buf[i]; //sets the out_buf to the items we found that are not vowels
index++;
}
}
return index;
}
void disemvowel(FILE* inputFile, FILE* outputFile) {
char* in_buf = (char*)calloc(BUF_SIZE, sizeof(char)); // allocates memory for in_buf
char* out_buf = (char*)calloc(BUF_SIZE, sizeof(char)); //allocates memory for the out_buf like above
int b = BUF_SIZE;
int k = 0;
while (b == BUF_SIZE) {
b = (int)fread(in_buf, sizeof(char), BUF_SIZE, inputFile);
k = (int)copy_non_vowels(b, in_buf, out_buf);
fwrite(out_buf, sizeof(char), k, outputFile);
}
free(in_buf);
free(out_buf);
}
int main(int argc, char *argv[]) {
FILE *inputFile;
FILE *outputFile;
if (argc == 1) { // if we arent given an actual files, we take in what ever the user puts in the terminal
inputFile = stdin;
outputFile = stdout;
}
else if (argc == 2) { //if we are only given 1 file, we take that as the input and read it.
inputFile = fopen(argv[1], "r");
outputFile = stdout;
}
else if (argc == 3){ //if given two arguments, we take and read the first and take and write the second
inputFile = fopen(argv[1], "r");
outputFile = fopen(argv[2], "w");
} else {
printf("You have given me too many arguments! Please only give me at most two arguments."); //if we get two many, lets user know what they need to do instead and exits
exit(0);
}
disemvowel(inputFile, outputFile);
fclose(inputFile); //closes the file
fclose(outputFile);
return 0;
}
| 3.4375 | 3 |
2024-11-18T20:55:32.232597+00:00 | 2017-11-13T00:34:56 | 8ed08a727d2df0a10c007994cd2d108849c71246 | {
"blob_id": "8ed08a727d2df0a10c007994cd2d108849c71246",
"branch_name": "refs/heads/master",
"committer_date": "2017-11-13T00:34:56",
"content_id": "ded58f1ed8d631366730378ddfc76bfc9284c41d",
"detected_licenses": [
"PostgreSQL"
],
"directory_id": "d22bea08a867824c6562c2c26255753cc4eacd46",
"extension": "c",
"filename": "arbiter.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": 13210,
"license": "PostgreSQL",
"license_type": "permissive",
"path": "/contrib/arbiter/api/arbiter.c",
"provenance": "stackv2-0092.json.gz:38984",
"repo_name": "arssher/postgres_cluster",
"revision_date": "2017-11-13T00:34:56",
"revision_id": "e987d00c1ca4020996885f8af9e5df33cda9bd3e",
"snapshot_id": "885a267666fa7d1b44650f87f0bd75ea70ddb8bb",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/arssher/postgres_cluster/e987d00c1ca4020996885f8af9e5df33cda9bd3e/contrib/arbiter/api/arbiter.c",
"visit_date": "2020-03-23T10:26:26.842200"
} | stackv2 | #include <sys/socket.h>
#include <netinet/tcp.h>
#include <netdb.h>
#include <string.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <assert.h>
#include <time.h>
#include "postgres.h"
#include "arbiter.h"
#include "proto.h"
#include "arbiterlimits.h"
#include "sockhub/sockhub.h"
#ifdef TEST
// standalone test without postgres functions
#define palloc malloc
#define pfree free
#endif
#define COMMAND_BUFFER_SIZE 1024
#define RESULTS_SIZE 1024 // size in 32-bit numbers
typedef struct ArbiterConnData *ArbiterConn;
typedef struct ArbiterConnData
{
char *host; // use unix socket if host is NULL
int port;
int sock;
} ArbiterConnData;
static bool connected = false;
static int leader = 0;
static int connum = 0;
static ArbiterConnData conns[MAX_SERVERS];
static char *arbiter_unix_sock_dir;
typedef unsigned xid_t;
static void DiscardConnection()
{
if (connected)
{
close(conns[leader].sock);
conns[leader].sock = -1;
connected = false;
}
leader = (leader + 1) % connum;
fprintf(stderr, "pid=%d: next candidate is %s:%d (%d of %d)\n", getpid(), conns[leader].host, conns[leader].port, leader, connum);
}
static int arbiter_recv_results(ArbiterConn arbiter, int maxlen, xid_t *results)
{
ShubMessageHdr msg;
int recved;
int needed;
recved = 0;
needed = sizeof(ShubMessageHdr);
while (recved < needed)
{
int newbytes = read(arbiter->sock, (char*)&msg + recved, needed - recved);
if (newbytes == -1)
{
DiscardConnection();
elog(WARNING, "Failed to recv results header from arbiter");
return 0;
}
if (newbytes == 0)
{
DiscardConnection();
elog(WARNING, "Arbiter closed connection during recv");
return 0;
}
recved += newbytes;
}
recved = 0;
needed = msg.size;
assert(needed % sizeof(xid_t) == 0);
if (needed > maxlen * sizeof(xid_t))
{
elog(ERROR, "The message body will not fit into the results array");
return 0;
}
while (recved < needed)
{
int newbytes = read(arbiter->sock, (char*)results + recved, needed - recved);
if (newbytes == -1)
{
DiscardConnection();
elog(WARNING, "Failed to recv results body from arbiter");
return 0;
}
if (newbytes == 0)
{
DiscardConnection();
elog(WARNING, "Arbiter closed connection during recv");
return 0;
}
recved += newbytes;
}
return needed / sizeof(xid_t);
}
// Connects to the specified Arbiter.
static bool ArbiterConnect(ArbiterConn conn)
{
int sd;
if (conn->host == NULL)
{
// use a UNIX socket
struct sockaddr sock;
int len = offsetof(struct sockaddr, sa_data) + snprintf(sock.sa_data, sizeof(sock.sa_data), "%s/sh.unix", arbiter_unix_sock_dir);
sock.sa_family = AF_UNIX;
sd = socket(AF_UNIX, SOCK_STREAM, 0);
if (sd == -1)
{
DiscardConnection();
perror("failed to create a unix socket");
return false;
}
if (connect(sd, &sock, len) == -1)
{
DiscardConnection();
perror("failed to connect to the address");
close(sd);
return false;
}
conn->sock = sd;
return (connected = true);
}
else
{
// use an IP socket
struct addrinfo *addrs = NULL;
struct addrinfo hint;
char portstr[6];
struct addrinfo *a;
memset(&hint, 0, sizeof(hint));
hint.ai_socktype = SOCK_STREAM;
hint.ai_family = AF_INET;
snprintf(portstr, 6, "%d", conn->port);
hint.ai_protocol = getprotobyname("tcp")->p_proto;
if (getaddrinfo(conn->host, portstr, &hint, &addrs))
{
DiscardConnection();
perror("failed to resolve address");
return false;
}
for (a = addrs; a != NULL; a = a->ai_next)
{
int one = 1;
sd = socket(a->ai_family, a->ai_socktype, a->ai_protocol);
if (sd == -1)
{
perror("failed to create a socket");
continue;
}
setsockopt(sd, IPPROTO_TCP, TCP_NODELAY, &one, sizeof(one));
if (connect(sd, a->ai_addr, a->ai_addrlen) == -1)
{
perror("failed to connect to an address");
close(sd);
continue;
}
// success
freeaddrinfo(addrs);
conn->sock = sd;
return (connected = true);
}
freeaddrinfo(addrs);
}
DiscardConnection();
fprintf(stderr, "could not connect\n");
return false;
}
static bool arbiter_send_command(ArbiterConn arbiter, xid_t cmd, int argc, ...)
{
va_list argv;
int i;
int sent;
char buf[COMMAND_BUFFER_SIZE];
int datasize;
char *cursor = buf;
ShubMessageHdr *msg = (ShubMessageHdr*)cursor;
msg->chan = 0;
msg->code = MSG_FIRST_USER_CODE;
msg->size = sizeof(xid_t) * (argc + 1);
cursor += sizeof(ShubMessageHdr);
*(xid_t*)cursor = cmd;
cursor += sizeof(xid_t);
va_start(argv, argc);
for (i = 0; i < argc; i++)
{
*(xid_t*)cursor = va_arg(argv, xid_t);
cursor += sizeof(xid_t);
}
va_end(argv);
datasize = cursor - buf;
assert(msg->size + sizeof(ShubMessageHdr) == datasize);
assert(datasize <= COMMAND_BUFFER_SIZE);
sent = 0;
while (sent < datasize)
{
int newbytes = write(arbiter->sock, buf + sent, datasize - sent);
if (newbytes == -1)
{
DiscardConnection();
elog(ERROR, "Failed to send a command to arbiter");
return false;
}
sent += newbytes;
}
return true;
}
void ArbiterConfig(char *servers, char *sock_dir)
{
char *hstate, *pstate;
char *hostport, *host, *portstr;
int port;
int i;
for (i = 0; i < connum; i++)
if (conns[i].host)
free(conns[i].host);
connum = 0;
fprintf(stderr, "parsing '%s'\n", servers);
hostport = strtok_r(servers, ",", &hstate);
while (hostport)
{
fprintf(stderr, "hostport = '%s'\n", hostport);
host = strtok_r(hostport, ":", &pstate);
fprintf(stderr, "host = '%s'\n", hostport);
if (!host) break;
portstr = strtok_r(NULL, ":", &pstate);
fprintf(stderr, "portstr = '%s'\n", portstr);
if (portstr)
port = atoi(portstr);
else
port = 5431;
fprintf(stderr, "port = %d\n", port);
if (!sock_dir) {
conns[connum].host = strdup(host);
} else {
conns[connum].host = NULL;
}
conns[connum].port = port;
connum++;
hostport = strtok_r(NULL, ",", &hstate);
}
arbiter_unix_sock_dir = sock_dir;
}
static ArbiterConn GetConnection()
{
int tries = 3 * connum;
while (!connected && (tries > 0))
{
ArbiterConn c = conns + leader;
if (ArbiterConnect(c))
{
xid_t results[RESULTS_SIZE];
int reslen;
if (!arbiter_send_command(c, CMD_HELLO, 0))
{
tries--;
continue;
}
reslen = arbiter_recv_results(c, RESULTS_SIZE, results);
if ((reslen < 1) || (results[0] != RES_OK))
{
tries--;
continue;
}
}
else
{
int timeout_ms = 1000;
struct timespec timeout = {0, timeout_ms * 1000000};
nanosleep(&timeout, NULL);
tries--;
if (c->host)
{
elog(WARNING, "Failed to connect to arbiter at tcp %s:%d", c->host, c->port);
}
else
{
elog(WARNING, "Failed to connect to arbiter at unix socket");
}
}
}
if (!tries)
{
return NULL;
}
return conns + leader;
}
void ArbiterInitSnapshot(Snapshot snapshot)
{
if (snapshot->xip == NULL)
{
/*
* First call for this snapshot. Snapshot is same size whether or not
* we are in recovery, see later comments.
*/
snapshot->xip = (TransactionId *)
malloc(GetMaxSnapshotSubxidCount() * sizeof(TransactionId));
if (snapshot->xip == NULL)
ereport(ERROR,
(errcode(ERRCODE_OUT_OF_MEMORY),
errmsg("out of memory")));
Assert(snapshot->subxip == NULL);
snapshot->subxip = (TransactionId *)
malloc(GetMaxSnapshotSubxidCount() * sizeof(TransactionId));
if (snapshot->subxip == NULL)
ereport(ERROR,
(errcode(ERRCODE_OUT_OF_MEMORY),
errmsg("out of memory")));
}
}
TransactionId ArbiterStartTransaction(Snapshot snapshot, TransactionId *gxmin, int nParticipants)
{
int i;
xid_t xid;
int reslen;
xid_t results[RESULTS_SIZE];
ArbiterConn arbiter = GetConnection();
if (!arbiter) {
goto failure;
}
assert(snapshot != NULL);
// command
if (nParticipants) {
if (!arbiter_send_command(arbiter, CMD_BEGIN, 1, nParticipants)) goto failure;
} else {
if (!arbiter_send_command(arbiter, CMD_BEGIN, 0)) goto failure;
}
// results
reslen = arbiter_recv_results(arbiter, RESULTS_SIZE, results);
if (reslen < 5) goto failure;
if (results[0] != RES_OK) goto failure;
xid = results[1];
*gxmin = results[2];
ArbiterInitSnapshot(snapshot);
snapshot->xmin = results[3];
snapshot->xmax = results[4];
snapshot->xcnt = reslen - 5;
for (i = 0; i < snapshot->xcnt; i++)
{
snapshot->xip[i] = results[5 + i];
}
return xid;
failure:
DiscardConnection();
fprintf(stderr, "ArbiterStartTransaction: transaction failed to start\n");
return INVALID_XID;
}
void ArbiterGetSnapshot(TransactionId xid, Snapshot snapshot, TransactionId *gxmin)
{
int i;
int reslen;
xid_t results[RESULTS_SIZE];
ArbiterConn arbiter = GetConnection();
if (!arbiter) {
goto failure;
}
assert(snapshot != NULL);
// command
if (!arbiter_send_command(arbiter, CMD_SNAPSHOT, 1, xid)) goto failure;
// response
reslen = arbiter_recv_results(arbiter, RESULTS_SIZE, results);
if (reslen < 4) goto failure;
if (results[0] != RES_OK) goto failure;
*gxmin = results[1];
ArbiterInitSnapshot(snapshot);
snapshot->xmin = results[2];
snapshot->xmax = results[3];
snapshot->xcnt = reslen - 4;
for (i = 0; i < snapshot->xcnt; i++)
{
snapshot->xip[i] = results[4 + i];
}
return;
failure:
DiscardConnection();
elog(ERROR,
"ArbiterGetSnapshot: failed to"
" get the snapshot for xid = %d\n",
xid
);
}
XidStatus ArbiterSetTransStatus(TransactionId xid, XidStatus status, bool wait)
{
int reslen;
xid_t results[RESULTS_SIZE];
ArbiterConn arbiter = GetConnection();
if (!arbiter) {
goto failure;
}
switch (status)
{
case TRANSACTION_STATUS_COMMITTED:
if (!arbiter_send_command(arbiter, CMD_FOR, 2, xid, wait)) goto failure;
break;
case TRANSACTION_STATUS_ABORTED:
if (!arbiter_send_command(arbiter, CMD_AGAINST, 2, xid, wait)) goto failure;
break;
default:
assert(false); // should not happen
goto failure;
}
// response
reslen = arbiter_recv_results(arbiter, RESULTS_SIZE, results);
if (reslen != 1) goto failure;
switch (results[0])
{
case RES_TRANSACTION_COMMITTED:
return TRANSACTION_STATUS_COMMITTED;
case RES_TRANSACTION_ABORTED:
return TRANSACTION_STATUS_ABORTED;
case RES_TRANSACTION_INPROGRESS:
return TRANSACTION_STATUS_IN_PROGRESS;
default:
goto failure;
}
failure:
DiscardConnection();
fprintf(
stderr,
"ArbiterSetTransStatus: failed to vote"
" %s the transaction xid = %d\n",
(status == TRANSACTION_STATUS_COMMITTED) ? "for" : "against",
xid
);
return -1;
}
XidStatus ArbiterGetTransStatus(TransactionId xid, bool wait)
{
int reslen;
xid_t results[RESULTS_SIZE];
ArbiterConn arbiter = GetConnection();
if (!arbiter) {
goto failure;
}
// command
if (!arbiter_send_command(arbiter, CMD_STATUS, 2, xid, wait)) goto failure;
// response
reslen = arbiter_recv_results(arbiter, RESULTS_SIZE, results);
if (reslen != 1) goto failure;
switch (results[0])
{
case RES_TRANSACTION_COMMITTED:
return TRANSACTION_STATUS_COMMITTED;
case RES_TRANSACTION_ABORTED:
return TRANSACTION_STATUS_ABORTED;
case RES_TRANSACTION_INPROGRESS:
return TRANSACTION_STATUS_IN_PROGRESS;
case RES_TRANSACTION_UNKNOWN:
return TRANSACTION_STATUS_UNKNOWN;
default:
goto failure;
}
failure:
DiscardConnection();
fprintf(
stderr,
"ArbiterGetTransStatus: failed to get"
" the status of xid = %d\n",
xid
);
return -1;
}
int ArbiterReserve(TransactionId xid, int nXids, TransactionId *first)
{
xid_t xmin, xmax;
int count;
int reslen;
xid_t results[RESULTS_SIZE];
ArbiterConn arbiter = GetConnection();
if (!arbiter) {
goto failure;
}
// command
if (!arbiter_send_command(arbiter, CMD_RESERVE, 2, xid, nXids)) goto failure;
// response
reslen = arbiter_recv_results(arbiter, RESULTS_SIZE, results);
if (reslen != 3) goto failure;
if (results[0] != RES_OK) goto failure;
xmin = results[1];
xmax = results[2];
*first = xmin;
count = xmax - xmin + 1;
Assert(*first >= xid);
Assert(count >= nXids);
return count;
failure:
DiscardConnection();
fprintf(
stderr,
"ArbiterReserve: failed to reserve"
" %d transaction starting from = %d\n",
nXids, xid
);
return 0;
}
bool ArbiterDetectDeadLock(int port, TransactionId xid, void* data, int size)
{
int msg_size = size + sizeof(xid)*3;
int data_size = sizeof(ShubMessageHdr) + msg_size;
char* buf = (char*)malloc(data_size);
ShubMessageHdr* msg = (ShubMessageHdr*)buf;
xid_t* body = (xid_t*)(msg+1);
int sent;
int reslen;
xid_t results[RESULTS_SIZE];
ArbiterConn arbiter = GetConnection();
msg->chan = 0;
msg->code = MSG_FIRST_USER_CODE;
msg->size = msg_size;
*body++ = CMD_DEADLOCK;
*body++ = port;
*body++ = xid;
memcpy(body, data, size);
sent = 0;
while (sent < data_size)
{
int new_bytes = write(arbiter->sock, buf + sent, data_size - sent);
if (new_bytes == -1)
{
elog(ERROR, "Failed to send a command to arbiter");
return false;
}
sent += new_bytes;
}
reslen = arbiter_recv_results(arbiter, RESULTS_SIZE, results);
if (reslen != 1 || (results[0] != RES_OK && results[0] != RES_DEADLOCK))
{
fprintf(
stderr,
"ArbiterDetectDeadLock: failed"
" to check xid=%u for deadlock\n",
xid
);
return false;
}
return results[0] == RES_DEADLOCK;
}
| 2.234375 | 2 |
2024-11-18T20:55:32.523825+00:00 | 2023-08-22T19:06:25 | 1c84df2244519381ad7fc141ae0bc2d22e31aa21 | {
"blob_id": "1c84df2244519381ad7fc141ae0bc2d22e31aa21",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-22T19:06:25",
"content_id": "813ab2a948fdc68f3922385f55e548ac5088088a",
"detected_licenses": [
"MIT"
],
"directory_id": "d153de2407f635bbd2667a6b266354d532e80e85",
"extension": "c",
"filename": "compareProfiles.c",
"fork_events_count": 13,
"gha_created_at": "2021-03-08T16:45:37",
"gha_event_created_at": "2023-09-13T23:01:51",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 345726079,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5566,
"license": "MIT",
"license_type": "permissive",
"path": "/test/Dss-C/source/compareProfiles.c",
"provenance": "stackv2-0092.json.gz:39240",
"repo_name": "HydrologicEngineeringCenter/hec-dss",
"revision_date": "2023-08-22T19:06:25",
"revision_id": "8587bd5339ee9aa8519d1d0d17f3625419a63122",
"snapshot_id": "195845c6312f2d9fc508032b39179f457849ede1",
"src_encoding": "UTF-8",
"star_events_count": 26,
"url": "https://raw.githubusercontent.com/HydrologicEngineeringCenter/hec-dss/8587bd5339ee9aa8519d1d0d17f3625419a63122/test/Dss-C/source/compareProfiles.c",
"visit_date": "2023-08-30T11:56:27.416514"
} | stackv2 | #include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include "heclib.h"
#include "hecdss7.h"
#include "zdssMessages.h"
#include "hecdssInternal.h"
#include "TestDssC.h"
int compareDifferent(double *doubles, float *floats, int number, const char *str);
int compareProfiles (long long *ifltab, zStructTimeSeries* tss1, zStructTimeSeries* tss2, const char *str)
{
int status;
int one = 1;
int two = 2;
int i;
char mess[150];
// When comparing profiles, we'll have different data types - not an error.
status = compareTss(ifltab, tss1, tss2, str);
if (status != STATUS_OKAY) return status;
copyTwoStrings(mess, sizeof(mess), "compareProfiles Loc 1, numberDepths ", str);
checknumbers_(&tss1->profileDepthsNumber, &tss2->profileDepthsNumber, mess, &status, strlen(mess));
if (status != STATUS_OKAY) return status;
copyTwoStrings(mess, sizeof(mess), "compareProfiles Loc 2, numberTimes ", str);
checknumbers_(&tss1->numberValues, &tss2->numberValues, mess, &status, strlen(mess));
if (status != STATUS_OKAY) return status;
if (tss1->floatProfileDepths && tss2->floatProfileDepths) {
copyTwoStrings(mess, sizeof(mess), "compareProfiles Loc 3, floatDepths ", str);
checkfloats_(tss1->floatProfileDepths, tss2->floatProfileDepths, &tss2->profileDepthsNumber, mess, &status, strlen(mess));
if (status != STATUS_OKAY) return status;
}
else if (tss1->doubleProfileDepths && tss2->doubleProfileDepths) {
copyTwoStrings(mess, sizeof(mess), "compareProfiles Loc 3a, doubleDepths ", str);
checkdoubles_(tss1->doubleProfileDepths, tss2->doubleProfileDepths, &tss2->profileDepthsNumber, mess, &status, strlen(mess));
if (status != STATUS_OKAY) return status;
}
else if (tss1->floatProfileDepths && tss2->doubleProfileDepths) {
copyTwoStrings(mess, sizeof(mess), "compareProfiles Loc 3b, Depths ", str);
status = compareDifferent(tss2->doubleProfileDepths, tss1->floatProfileDepths, tss2->profileDepthsNumber, mess);
if (status != STATUS_OKAY) return status;
}
else if (tss2->floatProfileDepths && tss1->doubleProfileDepths) {
copyTwoStrings(mess, sizeof(mess), "compareProfiles Loc 3c, Depths ", str);
status = compareDifferent(tss1->doubleProfileDepths, tss2->floatProfileDepths, tss2->profileDepthsNumber, mess);
if (status != STATUS_OKAY) return status;
}
else {
copyTwoStrings(mess, sizeof(mess), "compareProfiles Loc 4, floatValues array miss-match ", str);
zmessage(ifltab, mess);
return -1;
}
i = tss1->profileDepthsNumber * tss1->numberValues;
if (tss1->floatProfileValues && tss2->floatProfileValues) {
copyTwoStrings(mess, sizeof(mess), "compareProfiles Loc 5, ProfileValues ", str);
checkfloats_(tss1->floatProfileValues, tss2->floatProfileValues, &i, mess, &status, strlen(mess));
if (status != STATUS_OKAY) return status;
}
else if (tss1->doubleProfileValues && tss2->doubleProfileValues) {
copyTwoStrings(mess, sizeof(mess), "compareProfiles Loc 5a, ProfileValues ", str);
checkdoubles_(tss1->doubleProfileValues, tss2->doubleProfileValues, &i, mess, &status, strlen(mess));
if (status != STATUS_OKAY) return status;
}
else if (tss1->floatProfileValues && tss2->doubleProfileValues) {
copyTwoStrings(mess, sizeof(mess), "compareProfiles Loc 5b, ProfileValues ", str);
status = compareDifferent(tss2->doubleProfileValues, tss1->floatProfileValues, i, mess);
if (status != STATUS_OKAY) return status;
}
else if (tss2->floatProfileValues && tss1->doubleProfileValues) {
copyTwoStrings(mess, sizeof(mess), "compareProfiles Loc 5c, ProfileValues ", str);
status = compareDifferent(tss1->doubleProfileValues, tss2->floatProfileValues, i, mess);
if (status != STATUS_OKAY) return status;
}
else {
if (!(!tss1->doubleProfileValues && !tss2->doubleProfileValues)) {
copyTwoStrings(mess, sizeof(mess), "compareProfiles Loc 10, doubleValues array miss-match ", str);
zmessage(ifltab, mess);
return -1;
}
}
if (tss1->unitsProfileDepths && tss2->unitsProfileDepths) {
copyTwoStrings(mess, sizeof(mess), "compareProfiles Loc 9, unitsProfileDepths ", str);
checkstring_(tss1->unitsProfileDepths, tss2->unitsProfileDepths, mess, &status, strlen(tss1->unitsProfileDepths), strlen(tss2->unitsProfileDepths), strlen(mess));
if (status != STATUS_OKAY) return status;
}
else {
if (!(!tss1->unitsProfileDepths && !tss2->unitsProfileDepths)) {
copyTwoStrings(mess, sizeof(mess), "compareProfiles Loc 10, unitsProfileDepths miss-match ", str);
zmessage(ifltab, mess);
return -1;
}
}
if (tss1->unitsProfileValues && tss2->unitsProfileValues) {
copyTwoStrings(mess, sizeof(mess), "compareProfiles Loc 11, unitsProfileValues ", str);
checkstring_(tss1->unitsProfileValues, tss2->unitsProfileValues, mess, &status, strlen(tss1->unitsProfileValues), strlen(tss2->unitsProfileValues), strlen(mess));
if (status != STATUS_OKAY) return status;
}
else {
if (!(!tss1->unitsProfileValues && !tss2->unitsProfileValues)) {
copyTwoStrings(mess, sizeof(mess), "compareProfiles Loc 12, unitsProfileValues miss-match ", str);
zmessage(ifltab, mess);
return -1;
}
}
return 0;
}
int compareDifferent(double *doubles, float *floats, int number, const char *str)
{
// Compare floats, as going from float to double might have round differences
float *dfloats;
int status;
dfloats = (float *)calloc(number, 4);
convertDataArray((void*)doubles, (void*)dfloats, number, 2, 1);
checkfloats_((void*)dfloats, (void*)floats, &number, str, &status, strlen(str));
free(dfloats);
return status;
}
| 2.140625 | 2 |
2024-11-18T20:55:32.642311+00:00 | 2020-07-17T11:26:22 | aca33981e9b80358894fa3b257a03f418b369f9f | {
"blob_id": "aca33981e9b80358894fa3b257a03f418b369f9f",
"branch_name": "refs/heads/master",
"committer_date": "2020-07-17T11:26:22",
"content_id": "d9567c1ab1643273335f3e3df600066ccd97f63f",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "fa5e1f01dd72057710a2b333b8aa2cd782483722",
"extension": "c",
"filename": "sec_sst_test_get.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 278277456,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 703,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/modules/security/keychain/test/sec_sst_test_get.c",
"provenance": "stackv2-0092.json.gz:39499",
"repo_name": "allentree/LoRaGW-SDK",
"revision_date": "2020-07-17T11:26:22",
"revision_id": "1675801538407753768e91774d857f2d7aa2ba7c",
"snapshot_id": "20df823930b866a1afb9be38ceeac8d44440e7a6",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/allentree/LoRaGW-SDK/1675801538407753768e91774d857f2d7aa2ba7c/modules/security/keychain/test/sec_sst_test_get.c",
"visit_date": "2022-11-21T04:02:13.501632"
} | stackv2 | #include <stdio.h>
#include "keychain.h"
/* try to get the item of other process
* can not get item of other process
* check if errno is KC_ERROR_ITEM_NOT_FOUND
*/
void main(void)
{
char *key = "test_key";
char secret[128];
uint32_t secret_len = 128;
uint32_t ret = 0;
kc_key_type_t key_type = 0;
if (kc_init()) {
printf("kc init failed\n");
return;
}
ret = kc_get_global_item(key, secret, &secret_len, &key_type);
if (ret != KC_ERROR_ITEM_NOT_FOUND) {
printf("kc test get other process item failed 0x%x\n", ret);
goto clean;
}
printf("test if can get the item of other process success\n");
clean:
kc_destroy();
}
| 2.578125 | 3 |
2024-11-18T20:55:32.722776+00:00 | 2019-10-04T15:13:55 | 741bfc2070dfd57cb4548afc295230410148f039 | {
"blob_id": "741bfc2070dfd57cb4548afc295230410148f039",
"branch_name": "refs/heads/master",
"committer_date": "2019-10-04T15:13:55",
"content_id": "89d2fd45e81e0616505f353bb346113f85c7835a",
"detected_licenses": [
"MIT"
],
"directory_id": "65b4b03b563f7685a143df6b792a0b612dc92d2a",
"extension": "h",
"filename": "text.h",
"fork_events_count": 3,
"gha_created_at": "2019-01-08T16:45:34",
"gha_event_created_at": "2019-07-04T03:44:19",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 164692619,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 624,
"license": "MIT",
"license_type": "permissive",
"path": "/whycpp_c/include/whycpp_c/text.h",
"provenance": "stackv2-0092.json.gz:39628",
"repo_name": "senior-sigan/WHY_CPP",
"revision_date": "2019-10-04T15:13:55",
"revision_id": "f9e2d060a782b9d72fb2c9f3ce580af00eb40779",
"snapshot_id": "094e411b2d781e767012ccd0ea59d248ceb83333",
"src_encoding": "UTF-8",
"star_events_count": 6,
"url": "https://raw.githubusercontent.com/senior-sigan/WHY_CPP/f9e2d060a782b9d72fb2c9f3ce580af00eb40779/whycpp_c/include/whycpp_c/text.h",
"visit_date": "2023-06-20T20:38:20.401022"
} | stackv2 | #pragma once
#include <whycpp/c_api.h>
#include <whycpp_c/color.h>
/**
* Prints a single char at a position with color
* @param ch is a symbol to print
* @param x
* @param y
* @param color
* @param size
* @param font
*/
WHYCPP_C_API
void PrintChar_C(char ch, int x, int y, RGBA_t color, int size);
/**
* Prints a string at a position with color
* @param str is a string to print
* @param x
* @param y
* @param color
* @param size
* @param spacing is a distance between chars in the string
* @param font
*/
WHYCPP_C_API
void PrintStr_C(const char* str, int x, int y, RGBA_t color, int size, int spacing);
| 2.234375 | 2 |
2024-11-18T20:55:33.230888+00:00 | 2019-02-23T11:14:38 | df4fb98f69dcee749b8cf031ef4bff04c0f51673 | {
"blob_id": "df4fb98f69dcee749b8cf031ef4bff04c0f51673",
"branch_name": "refs/heads/master",
"committer_date": "2019-02-23T11:14:38",
"content_id": "5e501177c766099ecf6b0fee635302bb0c3d3e31",
"detected_licenses": [
"MIT"
],
"directory_id": "60e1cd76871d782458e936e82887c6069bb15baf",
"extension": "c",
"filename": "Palindrome.c",
"fork_events_count": 0,
"gha_created_at": "2018-10-28T08:41:40",
"gha_event_created_at": "2018-11-17T07:01:44",
"gha_language": "Python",
"gha_license_id": "MIT",
"github_id": 155050982,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1952,
"license": "MIT",
"license_type": "permissive",
"path": "/LeetCode/LinkedLists/Palindrome.c",
"provenance": "stackv2-0092.json.gz:40143",
"repo_name": "prabhupant/daily-coding-problem",
"revision_date": "2019-02-23T11:14:38",
"revision_id": "b3775dd0ad823823e60100624ccf14235c446098",
"snapshot_id": "aad7b62aca8a378e13cf86e0c163eb6d5f69752e",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/prabhupant/daily-coding-problem/b3775dd0ad823823e60100624ccf14235c446098/LeetCode/LinkedLists/Palindrome.c",
"visit_date": "2020-04-03T05:36:21.323962"
} | stackv2 | /**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
void reverse(struct ListNode **head_ref)
{
struct ListNode *prev = NULL;
struct ListNode *curr = *head_ref;
struct ListNode *next;
while(curr != NULL)
{
next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
*head_ref = prev;
}
bool compareLists(struct ListNode *head1, struct ListNode *head2)
{
struct ListNode *temp1 = head1;
struct ListNode *temp2 = head2;
while(temp1 && temp2)
{
if(temp1->val == temp2->val)
{
temp1 = temp1->next;
temp2 = temp2->next;
}
else
{
return false;
}
}
if(temp1 == NULL && temp2 == NULL)
{
return true;
}
return false;
}
bool isPalindrome(struct ListNode* head) {
struct ListNode *slow_ptr = head;
struct ListNode *fast_ptr = head;
struct ListNode *second_half = head;
struct ListNode *prev_of_slow_ptr = head;
struct ListNode *mid_node = NULL;
bool res = true;
if(head != NULL && head->next != NULL)
{
while(fast_ptr != NULL && fast_ptr->next != NULL)
{
fast_ptr = fast_ptr->next->next;
prev_of_slow_ptr = slow_ptr;
slow_ptr = slow_ptr->next;
}
if(fast_ptr != NULL)
{
mid_node = slow_ptr;
slow_ptr = slow_ptr->next;
}
second_half = slow_ptr;
prev_of_slow_ptr->next = NULL;
reverse(&second_half);
res = compareLists(head, second_half);
reverse(&second_half);
if(mid_node != NULL)
{
prev_of_slow_ptr->next = mid_node;
mid_node->next = second_half;
}
else
{
prev_of_slow_ptr->next = second_half;
}
}
return res;
}
| 3.21875 | 3 |
2024-11-18T20:55:33.484161+00:00 | 2019-08-29T11:05:56 | 9d97122f69e61bf3aa1ee44fd91039ddd80ef517 | {
"blob_id": "9d97122f69e61bf3aa1ee44fd91039ddd80ef517",
"branch_name": "refs/heads/master",
"committer_date": "2019-08-29T11:05:56",
"content_id": "a586f1d8e34ba2a604457ac76cab7035c06dad6f",
"detected_licenses": [
"MIT"
],
"directory_id": "ca445c9791e2c5f42999bcee727070a7a1d82cad",
"extension": "c",
"filename": "main.c",
"fork_events_count": 0,
"gha_created_at": "2019-12-30T11:42:40",
"gha_event_created_at": "2019-12-30T11:42:41",
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 230905722,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 329,
"license": "MIT",
"license_type": "permissive",
"path": "/test/load_animation/main.c",
"provenance": "stackv2-0092.json.gz:40402",
"repo_name": "kmoe/sturmflut",
"revision_date": "2019-08-29T11:05:56",
"revision_id": "1ac9c736d2b3374834f32f485ae1958231951329",
"snapshot_id": "438cbeb441a55af52d8ee9d42bb02455bb2e152b",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/kmoe/sturmflut/1ac9c736d2b3374834f32f485ae1958231951329/test/load_animation/main.c",
"visit_date": "2020-12-02T05:32:49.640349"
} | stackv2 | #include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "../../image.h"
int main(int argc, char** argv) {
struct img_ctx* ctx;
struct img_animation* anim;
image_alloc(&ctx);
image_load_animation(&anim, "test.gif");
printf("Got %zu frames\n", anim->num_frames);
image_free_animation(anim);
image_free(ctx);
}
| 2.21875 | 2 |
2024-11-18T20:55:34.278224+00:00 | 2015-07-28T23:21:49 | 659b3b0cfa2f1f28378c34e87bb7280eefdb773b | {
"blob_id": "659b3b0cfa2f1f28378c34e87bb7280eefdb773b",
"branch_name": "refs/heads/master",
"committer_date": "2015-07-28T23:21:49",
"content_id": "f8fa585cebd305abd3f822f681a817e8a59780cd",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "72a0842c07f8aac51707d9f14dadc525159b6d46",
"extension": "c",
"filename": "gauss_mix.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 38988846,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 9591,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/c/gauss_mix.c",
"provenance": "stackv2-0092.json.gz:40659",
"repo_name": "madratman/riss_bingham",
"revision_date": "2015-07-28T23:21:49",
"revision_id": "d50ddb46d06a17ba5f6a2e0154e7d17af80f9a01",
"snapshot_id": "2c54e2408dabee71c03b972213dd5797e2215074",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/madratman/riss_bingham/d50ddb46d06a17ba5f6a2e0154e7d17af80f9a01/c/gauss_mix.c",
"visit_date": "2021-01-20T10:13:58.950981"
} | stackv2 |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
#include <time.h>
#include <math.h>
#include <float.h>
#include "bingham.h"
#include "bingham/util.h"
#include "bingham/gauss_mix.h"
static void gauss_mix_init(gauss_mix_t *gm, double **X, int npoints)
{
int i, k = gm->n, dims = gm->d;
// initialize means with k randomly chosen data points
int randIndex[k];
randperm(randIndex, npoints, k);
reorder_rows(gm->means, X, randIndex, k, dims);
// the initial estimates of the mixing probabilities are set to 1/k
for (i = 0; i < k; i++)
gm->weights[i] = 1.0 / (double)k;
// the covariances are initialized to 1/10 the global covariance.
// this is a completely aribitrary choice and can be changed. Original
// code set covariance to an isotropic gaussian with diagonal covariance
// for most cases the newer version converges faster.
double globMu[dims];
mean(globMu, X, npoints, dims);
double **globCovar = new_matrix2(dims, dims);
cov(globCovar, X, globMu, npoints, dims);
for (i = 0; i < k; i++) {
mult(gm->covs[i][0], globCovar[0], .1, dims*dims);
}
free_matrix2(globCovar);
}
// Indicators are indicator functions and will contain the assignments of each data point to
// the mixture components, as result of the E-step
static void compute_indicators(double **Indicators, double **X, int npoints, gauss_mix_t *gm)
{
int i, j, k = gm->n;
// having the initial means, covariances, and probabilities, we can
// initialize the (unnormalized) indicator functions following the standard EM equation
for (i = 0; i < k; i++)
for (j = 0; j < npoints; j++)
Indicators[i][j] = mvnpdf(X[j], gm->means[i], gm->covs[i], gm->d);
}
static double compute_log_likelihood(double **Indicators, gauss_mix_t *gm, double *W, int npoints)
{
double SumIndicators[npoints];
wmean(SumIndicators, Indicators, gm->weights, gm->n, npoints);
double loglike = 0.0;
double epsilon = 1e-50;
int i;
for (i = 0; i < npoints; i++)
loglike += W[i]*log(SumIndicators[i] + epsilon);
return loglike;
}
static double compute_description_length(double loglike, gauss_mix_t *gm, double W_tot)
{
int i, k = gm->n, dims = gm->d;
double npars = dims/2.0 + dims*(dims+1)/4.0; // actually npars/2
double sum_log_weights = 0.0;
for (i = 0; i < k; i++)
sum_log_weights += log(gm->weights[i]);
return -loglike + (npars*sum_log_weights) + (npars + 0.5)*k*log(W_tot);
}
static void remove_component(gauss_mix_t *gm, double **Indicators, int comp, int npoints)
{
int i, k = gm->n, dims = gm->d;
for (i = comp; i < k-1; i++) {
memcpy(gm->means[i], gm->means[i+1], dims*sizeof(double));
matrix_copy(gm->covs[i], gm->covs[i+1], dims, dims);
gm->weights[i] = gm->weights[i+1];
memcpy(Indicators[i], Indicators[i+1], npoints*sizeof(double));
}
free_matrix2(gm->covs[k-1]);
gm->n--;
mult(gm->weights, gm->weights, 1.0/sum(gm->weights, gm->n), gm->n);
}
static int update_component(gauss_mix_t *gm, int comp, double **Indicators, double **X, double *W, int npoints, double regularize)
{
int i, k = gm->n, dims = gm->d;
double epsilon = 1e-50;
double npars = dims/2.0 + dims*(dims+1)/4.0; // actually npars/2
double SumIndicators[npoints];
wmean(SumIndicators, Indicators, gm->weights, gm->n, npoints);
double P[npoints];
for (i = 0; i < npoints; i++)
P[i] = W[i] * gm->weights[comp] * Indicators[comp][i] / (epsilon + SumIndicators[i]);
// compute weighted mean and covariance
wmean(gm->means[comp], X, P, npoints, dims);
wcov(gm->covs[comp], X, P, gm->means[comp], npoints, dims);
for (i = 0; i < dims; i++)
gm->covs[comp][i][i] += regularize;
// this is the special part of the M step that is able to kill components
gm->weights[comp] = (sum(P,npoints) - npars) / sum(W, npoints);
if (gm->weights[comp] < 0)
gm->weights[comp] = 0;
mult(gm->weights, gm->weights, 1.0/sum(gm->weights,k), k);
// we now have to do some book-keeping if the current component was killed
if (gm->weights[comp] == 0) {
remove_component(gm, Indicators, comp, npoints);
return 1;
}
// if the component was not killed, we update the corresponding indicator variables...
for (i = 0; i < npoints; i++)
Indicators[comp][i] = mvnpdf(X[i], gm->means[comp], gm->covs[comp], dims);
return 0;
}
//---------------------------- EXTERNAL API -------------------------------//
gauss_mix_t *new_gauss_mix(int dims, int k)
{
int i;
gauss_mix_t *gm;
safe_calloc(gm, 1, gauss_mix_t);
gm->n = k;
gm->d = dims;
safe_calloc(gm->weights, k, double);
gm->means = new_matrix2(k, dims);
safe_calloc(gm->covs, k, double**);
for (i = 0; i < k; i++)
gm->covs[i] = new_matrix2(dims, dims);
return gm;
}
gauss_mix_t *gauss_mix_clone(gauss_mix_t *gm)
{
int i;
int k = gm->n;
int dims = gm->d;
gauss_mix_t *gm2;
safe_calloc(gm2, 1, gauss_mix_t);
gm2->n = k;
gm2->d = dims;
safe_calloc(gm2->weights, k, double);
memcpy(gm2->weights, gm->weights, k*sizeof(double));
gm2->means = matrix_clone(gm->means, k, dims);
safe_calloc(gm2->covs, k, double**);
for (i = 0; i < k; i++)
gm2->covs[i] = matrix_clone(gm->covs[i], dims, dims);
return gm2;
}
void free_gauss_mix(gauss_mix_t *gm)
{
if (gm->weights)
free(gm->weights);
if (gm->means)
free_matrix2(gm->means);
if (gm->covs) {
int i;
for (i = 0; i < gm->n; i++)
if (gm->covs[i])
free_matrix2(gm->covs[i]);
free(gm->covs);
}
free(gm);
}
gauss_mix_t *fit_gauss_mix(double **X, int npoints, int dims, double *w, unsigned int kmin, unsigned int kmax, double regularize, double th)
{
int i;
double W[npoints];
mult(W, w, npoints/sum(w,npoints), npoints); // normalize data weights
gauss_mix_t *gm = new_gauss_mix(dims, kmax); // kmax is the initial number of mixture components
gauss_mix_init(gm, X, npoints);
double **Indicators = new_matrix2(kmax, npoints);
compute_indicators(Indicators, X, npoints, gm);
double loglike = compute_log_likelihood(Indicators, gm, W, npoints);
double dl = compute_description_length(loglike, gm, sum(W,npoints));
// minimum description length seen so far, and corresponding parameter estimates
double minDL = dl;
gauss_mix_t *bestGM = gauss_mix_clone(gm);
while (1) {
while (1) {
int comp = 0;
// Since k may change during the process, we can not use a for loop
while (comp < gm->n) {
if (update_component(gm, comp, Indicators, X, W, npoints, regularize) == 0)
comp++;
//printf("gm->n = %d\n", gm->n);
}
// compute description length
double loglikeprev = loglike;
loglike = compute_log_likelihood(Indicators, gm, W, npoints);
dl = compute_description_length(loglike, gm, sum(W,npoints));
// check if new mixture is best
if (dl < minDL) {
minDL = dl;
free_gauss_mix(bestGM);
bestGM = gauss_mix_clone(gm);
}
printf("k = %d, dl = %f, loglike = %f, loglikeprev = %f\n", gm->n, dl, loglike, loglikeprev); //dbug
// check for convergence
if (fabs(loglike-loglikeprev) / loglikeprev < th)
break;
}
if (gm->n == kmin)
break;
// try removing smallest component
int comp = 0;
for (i = 1; i < gm->n; i++)
if (gm->weights[i] < gm->weights[comp])
comp = i;
remove_component(gm, Indicators, comp, npoints);
loglike = compute_log_likelihood(Indicators, gm, W, npoints);
printf("*** killed smallest ***\n"); //dbug
}
free_gauss_mix(gm);
free_matrix2(Indicators);
return bestGM;
}
//--------------------------- TESTING -----------------------//
#include "bingham/olf.h"
int main(int argc, char *argv[])
{
if (argc < 3) {
printf("usage: %s <pcd> <point_index>\n", argv[0]);
return 1;
}
pcd_t *pcd = load_pcd(argv[1]);
int point_index = atof(argv[2]);
int i;
int c = pcd->clusters[point_index];
int I[pcd->num_points];
int n = findeq(I, pcd->clusters, c, pcd->num_points);
double **Q = new_matrix2(2*n, 4);
double **X = new_matrix2(2*n, 3);
int cnt=0;
for (i = 0; i < pcd->num_points; i++) {
if (pcd->clusters[i] == c) {
memcpy(Q[cnt], pcd->quaternions[0][i], 4*sizeof(double));
memcpy(Q[cnt+1], pcd->quaternions[1][i], 4*sizeof(double));
X[cnt][0] = X[cnt+1][0] = pcd->points[0][i];
X[cnt][1] = X[cnt+1][1] = pcd->points[1][i];
X[cnt][2] = X[cnt+1][2] = pcd->points[2][i];
cnt += 2;
}
}
// compute weights
n *= 2;
double *q = pcd->quaternions[0][point_index];
double dq, qdot;
double w[n];
double r = .2;
for (i = 0; i < n; i++) {
qdot = fabs(dot(q, Q[i], 4));
dq = acos(MIN(qdot, 1.0));
w[i] = exp(-(dq/r)*(dq/r));
}
gauss_mix_t* gm = fit_gauss_mix(X, n, 3, w, 1, 20, 1e-15, 1e-4);
printf("n = %d\n", gm->n);
for (i = 0; i < gm->n; i++) {
printf("w[%d] = %f\n", i, gm->weights[i]);
printf("mu[%d] = [%f, %f, %f]\n", i, gm->means[i][0], gm->means[i][1], gm->means[i][2]);
printf("cov[%d] = [%f, %f, %f; %f, %f, %f; %f, %f, %f]\n", i, gm->covs[i][0][0], gm->covs[i][0][1], gm->covs[i][0][2],
gm->covs[i][1][0], gm->covs[i][1][1], gm->covs[i][1][2], gm->covs[i][2][0], gm->covs[i][2][1], gm->covs[i][2][2]);
}
return 0;
}
| 2.5 | 2 |
2024-11-18T20:55:34.412734+00:00 | 2017-04-26T18:49:16 | 022e53d47cadb0c0e2cc45ffa984924b2f6ec35d | {
"blob_id": "022e53d47cadb0c0e2cc45ffa984924b2f6ec35d",
"branch_name": "refs/heads/master",
"committer_date": "2017-04-26T18:49:16",
"content_id": "756fc00c958c679a6db3f8941b28a2dc9e270752",
"detected_licenses": [
"MIT"
],
"directory_id": "f04a417de407a744993ace0b7c1786a61edd2483",
"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": 72299784,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1292,
"license": "MIT",
"license_type": "permissive",
"path": "/src/lcd.h",
"provenance": "stackv2-0092.json.gz:40789",
"repo_name": "bildeyko/calc_sdk1.1",
"revision_date": "2017-04-26T18:49:16",
"revision_id": "c30e4b5f8c0f22816d49f09c797385a89248c9e9",
"snapshot_id": "423646e5bf131e0038224f4558c5d90ed4c3ccd7",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/bildeyko/calc_sdk1.1/c30e4b5f8c0f22816d49f09c797385a89248c9e9/src/lcd.h",
"visit_date": "2021-01-12T12:06:26.393635"
} | stackv2 | #ifndef _LCD_H
#define _LCD_H
// LCD DEFINE SYMBOLS
//--COMMAND CONSTANTS
#define CLEAR 0x01 //requires delay cylce of min 57 NOPs
#define HOME 0x02
#define ENTRY_MODE 0x04
#define DISPLAY_CTRL 0x08
#define SHIFT 0x10
#define FUNCTION_SET 0x20
#define RAM_CG 0x40
#define RAM_DD 0x80
#define BF_AC 0x80 //Read Busy flag (DB7) and AC (DB6-0)
//--COMMAND OPTIONS
#define INCR 0x02
#define DISPLAY_SHIFT 0x01
#define DISPLAY_ON 0x04
#define CURSOR_ON 0x02
#define BLINK 0x01
#define DISPLAY 0x08
#define RIGHT 0x04
#define EIGHT_BITS 0x10
#define TWO_LINE 0x08
//--
extern void InitLCD(void);
extern void LCD_Clear(void);
extern void LCD_Putch(char ch);
extern void SwitchCurPosControl(bit o);//Switches on/off the current
//position control when symbols are put through LCD_Putch() (on by default)
extern void LCD_SwitchCursor(bit cursor,bit blink);
extern void LCD_GotoXY(unsigned char x,bit y);
extern void LCD_Type(char *s);
extern void LCD_Print(unsigned char xdata *s, bit y, char last_position, char lenght);
extern void LCD_Print_char(unsigned char ch, unsigned char x, bit y);
extern void LCD_clean_data(bit y);
#endif //_LCD_H
| 2.046875 | 2 |
2024-11-18T20:55:36.039631+00:00 | 2023-08-03T08:26:23 | d16096c87fcbbd3c632db8473454408f77b2759d | {
"blob_id": "d16096c87fcbbd3c632db8473454408f77b2759d",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-03T08:26:23",
"content_id": "c13ba5d9ab51c5da03764e72d8ba14c4922c8ea3",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "d814998b62645aa8a5e4398932fdc6e2d7571c36",
"extension": "c",
"filename": "entity.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 26266464,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2476,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/3.0.1/entity.c",
"provenance": "stackv2-0092.json.gz:42072",
"repo_name": "jburguete/genetic",
"revision_date": "2023-08-03T08:26:23",
"revision_id": "52924f6b156fa5c04f0114fcc08f1feb05a1ccb7",
"snapshot_id": "d330f893e5c2dbd103325e7d3cec7ffcfbc4e1b0",
"src_encoding": "UTF-8",
"star_events_count": 4,
"url": "https://raw.githubusercontent.com/jburguete/genetic/52924f6b156fa5c04f0114fcc08f1feb05a1ccb7/3.0.1/entity.c",
"visit_date": "2023-08-14T02:22:06.348161"
} | stackv2 | /*
GENETIC - A simple genetic algorithm.
Copyright 2014, Javier Burguete Tolosa.
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 Javier Burguete Tolosa ``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 Javier Burguete Tolosa 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.
*/
/**
* \file entity.c
* \brief Source file to define the entity functions.
* \author Javier Burguete Tolosa.
* \copyright Copyright 2014 Javier Burguete Tolosa. All rights reserved.
*/
#define _GNU_SOURCE
#include <gsl/gsl_rng.h>
#include <glib.h>
#include "entity.h"
/**
* Function to create an entity.
*/
void
entity_new (Entity * entity, ///< Entity struct.
unsigned int genome_nbytes,
///< Number of bytes of the entity genome.
unsigned int id) ///< Identifier number.
{
entity->id = id;
// Aligning in 4 bytes
entity->nbytes = ((genome_nbytes + 3) / 4) * 4;
entity->genome = (char *) g_slice_alloc (entity->nbytes);
}
/**
* Function to init randomly the genome of an entity.
*/
void
entity_init (Entity * entity, ///< Entity struct.
gsl_rng * rng) ///< GSL random numbers generator.
{
unsigned int i;
for (i = 0; i < entity->nbytes; ++i)
entity->genome[i] = (char) gsl_rng_uniform_int (rng, 256);
}
/**
* Function to free the memory used by an entity.
*/
void
entity_free (Entity * entity) ///< Entity struct.
{
g_slice_free1 (entity->nbytes, entity->genome);
}
| 2.234375 | 2 |
2024-11-18T20:55:36.094467+00:00 | 2023-02-16T11:27:40 | d6cda524022b7f4acc18eb868a5bf559f71387aa | {
"blob_id": "d6cda524022b7f4acc18eb868a5bf559f71387aa",
"branch_name": "refs/heads/main",
"committer_date": "2023-02-16T14:59:16",
"content_id": "ccac33c609045b7ab67ff957eaab49d917d261b2",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "e8302c75d770d1608b317d6af5c483bbad6c0493",
"extension": "c",
"filename": "net_context.c",
"fork_events_count": 32,
"gha_created_at": "2016-08-05T22:14:50",
"gha_event_created_at": "2022-04-05T17:14:07",
"gha_language": "C",
"gha_license_id": "Apache-2.0",
"github_id": 65052293,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 56901,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/subsys/net/ip/net_context.c",
"provenance": "stackv2-0092.json.gz:42200",
"repo_name": "intel/zephyr",
"revision_date": "2023-02-16T11:27:40",
"revision_id": "06d5bc51b580777079bb0b7e769e4127598ea5ee",
"snapshot_id": "819362089aa44ae378a5558f3b222197aaa811f7",
"src_encoding": "UTF-8",
"star_events_count": 32,
"url": "https://raw.githubusercontent.com/intel/zephyr/06d5bc51b580777079bb0b7e769e4127598ea5ee/subsys/net/ip/net_context.c",
"visit_date": "2023-09-04T00:20:35.217393"
} | stackv2 | /** @file
* @brief Network context API
*
* An API for applications to define a network connection.
*/
/*
* Copyright (c) 2016 Intel Corporation
* Copyright (c) 2021 Nordic Semiconductor
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <zephyr/logging/log.h>
LOG_MODULE_REGISTER(net_ctx, CONFIG_NET_CONTEXT_LOG_LEVEL);
#include <zephyr/kernel.h>
#include <zephyr/random/rand32.h>
#include <string.h>
#include <errno.h>
#include <stdbool.h>
#include <zephyr/net/net_pkt.h>
#include <zephyr/net/net_ip.h>
#include <zephyr/net/socket.h>
#include <zephyr/net/net_context.h>
#include <zephyr/net/net_offload.h>
#include <zephyr/net/ethernet.h>
#include <zephyr/net/socketcan.h>
#include <zephyr/net/ieee802154.h>
#include "connection.h"
#include "net_private.h"
#include "ipv6.h"
#include "ipv4.h"
#include "udp_internal.h"
#include "tcp_internal.h"
#include "net_stats.h"
#if defined(CONFIG_NET_TCP)
#include "tcp.h"
#endif
#ifndef EPFNOSUPPORT
/* Some old versions of newlib haven't got this defined in errno.h,
* Just use EPROTONOSUPPORT in this case
*/
#define EPFNOSUPPORT EPROTONOSUPPORT
#endif
#define PKT_WAIT_TIME K_SECONDS(1)
#define NET_MAX_CONTEXT CONFIG_NET_MAX_CONTEXTS
static struct net_context contexts[NET_MAX_CONTEXT];
/* We need to lock the contexts array as these APIs are typically called
* from applications which are usually run in task context.
*/
static struct k_sem contexts_lock;
#if defined(CONFIG_NET_UDP) || defined(CONFIG_NET_TCP)
static int check_used_port(enum net_ip_protocol proto,
uint16_t local_port,
const struct sockaddr *local_addr)
{
int i;
for (i = 0; i < NET_MAX_CONTEXT; i++) {
if (!net_context_is_used(&contexts[i])) {
continue;
}
if (!(net_context_get_proto(&contexts[i]) == proto &&
net_sin((struct sockaddr *)&
contexts[i].local)->sin_port == local_port)) {
continue;
}
if (IS_ENABLED(CONFIG_NET_IPV6) &&
local_addr->sa_family == AF_INET6) {
if (net_sin6_ptr(&contexts[i].local)->sin6_addr == NULL) {
continue;
}
if (net_ipv6_addr_cmp(
net_sin6_ptr(&contexts[i].local)->
sin6_addr,
&((struct sockaddr_in6 *)
local_addr)->sin6_addr)) {
return -EEXIST;
}
} else if (IS_ENABLED(CONFIG_NET_IPV4) &&
local_addr->sa_family == AF_INET) {
if (net_sin_ptr(&contexts[i].local)->sin_addr == NULL) {
continue;
}
if (net_ipv4_addr_cmp(
net_sin_ptr(&contexts[i].local)->
sin_addr,
&((struct sockaddr_in *)
local_addr)->sin_addr)) {
return -EEXIST;
}
}
}
return 0;
}
static uint16_t find_available_port(struct net_context *context,
const struct sockaddr *addr)
{
uint16_t local_port;
do {
local_port = sys_rand32_get() | 0x8000;
} while (check_used_port(net_context_get_proto(context),
htons(local_port), addr) == -EEXIST);
return htons(local_port);
}
#else
#define check_used_port(...) 0
#define find_available_port(...) 0
#endif
bool net_context_port_in_use(enum net_ip_protocol proto,
uint16_t local_port,
const struct sockaddr *local_addr)
{
return check_used_port(proto, htons(local_port), local_addr) != 0;
}
#if defined(CONFIG_NET_CONTEXT_CHECK)
static int net_context_check(sa_family_t family, enum net_sock_type type,
uint16_t proto, struct net_context **context)
{
switch (family) {
case AF_INET:
case AF_INET6:
if (family == AF_INET && !IS_ENABLED(CONFIG_NET_IPV4)) {
NET_DBG("IPv4 disabled");
return -EPFNOSUPPORT;
}
if (family == AF_INET6 && !IS_ENABLED(CONFIG_NET_IPV6)) {
NET_DBG("IPv6 disabled");
return -EPFNOSUPPORT;
}
if (!IS_ENABLED(CONFIG_NET_UDP)) {
if (type == SOCK_DGRAM) {
NET_DBG("DGRAM socket type disabled.");
return -EPROTOTYPE;
}
if (proto == IPPROTO_UDP) {
NET_DBG("UDP disabled");
return -EPROTONOSUPPORT;
}
}
if (!IS_ENABLED(CONFIG_NET_TCP)) {
if (type == SOCK_STREAM) {
NET_DBG("STREAM socket type disabled.");
return -EPROTOTYPE;
}
if (proto == IPPROTO_TCP) {
NET_DBG("TCP disabled");
return -EPROTONOSUPPORT;
}
}
switch (type) {
case SOCK_DGRAM:
if (proto != IPPROTO_UDP) {
NET_DBG("Context type and protocol mismatch,"
" type %d proto %d", type, proto);
return -EPROTONOSUPPORT;
}
break;
case SOCK_STREAM:
if (proto != IPPROTO_TCP) {
NET_DBG("Context type and protocol mismatch,"
" type %d proto %d", type, proto);
return -EPROTONOSUPPORT;
}
break;
case SOCK_RAW:
break;
default:
NET_DBG("Unknown context type.");
return -EPROTOTYPE;
}
break;
case AF_PACKET:
if (!IS_ENABLED(CONFIG_NET_SOCKETS_PACKET)) {
NET_DBG("AF_PACKET disabled");
return -EPFNOSUPPORT;
}
if (type != SOCK_RAW && type != SOCK_DGRAM) {
NET_DBG("AF_PACKET only supports RAW and DGRAM socket "
"types.");
return -EPROTOTYPE;
}
break;
case AF_CAN:
if (!IS_ENABLED(CONFIG_NET_SOCKETS_CAN)) {
NET_DBG("AF_CAN disabled");
return -EPFNOSUPPORT;
}
if (type != SOCK_RAW) {
NET_DBG("AF_CAN only supports RAW socket type.");
return -EPROTOTYPE;
}
if (proto != CAN_RAW) {
NET_DBG("AF_CAN only supports RAW_CAN protocol.");
return -EPROTOTYPE;
}
break;
default:
NET_DBG("Unknown address family %d", family);
return -EAFNOSUPPORT;
}
if (!context) {
NET_DBG("Invalid context");
return -EINVAL;
}
return 0;
}
#endif /* CONFIG_NET_CONTEXT_CHECK */
int net_context_get(sa_family_t family, enum net_sock_type type, uint16_t proto,
struct net_context **context)
{
int i, ret;
if (IS_ENABLED(CONFIG_NET_CONTEXT_CHECK)) {
ret = net_context_check(family, type, proto, context);
if (ret < 0) {
return ret;
}
}
k_sem_take(&contexts_lock, K_FOREVER);
ret = -ENOENT;
for (i = 0; i < NET_MAX_CONTEXT; i++) {
if (net_context_is_used(&contexts[i])) {
continue;
}
memset(&contexts[i], 0, sizeof(contexts[i]));
/* FIXME - Figure out a way to get the correct network interface
* as it is not known at this point yet.
*/
if (!net_if_is_ip_offloaded(net_if_get_default())
&& proto == IPPROTO_TCP) {
if (net_tcp_get(&contexts[i]) < 0) {
break;
}
}
contexts[i].iface = -1;
contexts[i].flags = 0U;
atomic_set(&contexts[i].refcount, 1);
net_context_set_family(&contexts[i], family);
net_context_set_type(&contexts[i], type);
net_context_set_proto(&contexts[i], proto);
#if defined(CONFIG_NET_CONTEXT_RCVTIMEO)
contexts[i].options.rcvtimeo = K_FOREVER;
#endif
#if defined(CONFIG_NET_CONTEXT_SNDTIMEO)
contexts[i].options.sndtimeo = K_FOREVER;
#endif
if (IS_ENABLED(CONFIG_NET_IP)) {
(void)memset(&contexts[i].remote, 0, sizeof(struct sockaddr));
(void)memset(&contexts[i].local, 0, sizeof(struct sockaddr_ptr));
if (IS_ENABLED(CONFIG_NET_IPV6) && family == AF_INET6) {
struct sockaddr_in6 *addr6 =
(struct sockaddr_in6 *)&contexts[i].local;
addr6->sin6_port =
find_available_port(&contexts[i], (struct sockaddr *)addr6);
if (!addr6->sin6_port) {
ret = -EADDRINUSE;
break;
}
}
if (IS_ENABLED(CONFIG_NET_IPV4) && family == AF_INET) {
struct sockaddr_in *addr = (struct sockaddr_in *)&contexts[i].local;
addr->sin_port =
find_available_port(&contexts[i], (struct sockaddr *)addr);
if (!addr->sin_port) {
ret = -EADDRINUSE;
break;
}
}
}
if (IS_ENABLED(CONFIG_NET_CONTEXT_SYNC_RECV)) {
k_sem_init(&contexts[i].recv_data_wait, 1, K_SEM_MAX_LIMIT);
}
k_mutex_init(&contexts[i].lock);
contexts[i].flags |= NET_CONTEXT_IN_USE;
*context = &contexts[i];
ret = 0;
break;
}
k_sem_give(&contexts_lock);
if (ret < 0) {
return ret;
}
/* FIXME - Figure out a way to get the correct network interface
* as it is not known at this point yet.
*/
if (IS_ENABLED(CONFIG_NET_OFFLOAD) && net_if_is_ip_offloaded(net_if_get_default())) {
ret = net_offload_get(net_if_get_default(), family, type, proto, context);
if (ret < 0) {
(*context)->flags &= ~NET_CONTEXT_IN_USE;
*context = NULL;
return ret;
}
}
return 0;
}
int net_context_ref(struct net_context *context)
{
int old_rc = atomic_inc(&context->refcount);
return old_rc + 1;
}
int net_context_unref(struct net_context *context)
{
int old_rc = atomic_dec(&context->refcount);
if (old_rc != 1) {
return old_rc - 1;
}
k_mutex_lock(&context->lock, K_FOREVER);
if (context->conn_handler) {
if (IS_ENABLED(CONFIG_NET_TCP) || IS_ENABLED(CONFIG_NET_UDP) ||
IS_ENABLED(CONFIG_NET_SOCKETS_CAN) ||
IS_ENABLED(CONFIG_NET_SOCKETS_PACKET)) {
net_conn_unregister(context->conn_handler);
}
context->conn_handler = NULL;
}
net_context_set_state(context, NET_CONTEXT_UNCONNECTED);
context->flags &= ~NET_CONTEXT_IN_USE;
NET_DBG("Context %p released", context);
k_mutex_unlock(&context->lock);
return 0;
}
int net_context_put(struct net_context *context)
{
int ret = 0;
NET_ASSERT(context);
if (!PART_OF_ARRAY(contexts, context)) {
return -EINVAL;
}
k_mutex_lock(&context->lock, K_FOREVER);
if (IS_ENABLED(CONFIG_NET_OFFLOAD) &&
net_if_is_ip_offloaded(net_context_get_iface(context))) {
context->flags &= ~NET_CONTEXT_IN_USE;
ret = net_offload_put(net_context_get_iface(context), context);
goto unlock;
}
context->connect_cb = NULL;
context->recv_cb = NULL;
context->send_cb = NULL;
/* net_tcp_put() will handle decrementing refcount on stack's behalf */
net_tcp_put(context);
/* Decrement refcount on user app's behalf */
net_context_unref(context);
unlock:
k_mutex_unlock(&context->lock);
return ret;
}
/* If local address is not bound, bind it to INADDR_ANY and random port. */
static int bind_default(struct net_context *context)
{
sa_family_t family = net_context_get_family(context);
if (IS_ENABLED(CONFIG_NET_IPV6) && family == AF_INET6) {
struct sockaddr_in6 addr6;
if (net_sin6_ptr(&context->local)->sin6_addr) {
return 0;
}
addr6.sin6_family = AF_INET6;
memcpy(&addr6.sin6_addr, net_ipv6_unspecified_address(),
sizeof(addr6.sin6_addr));
addr6.sin6_port =
find_available_port(context,
(struct sockaddr *)&addr6);
return net_context_bind(context, (struct sockaddr *)&addr6,
sizeof(addr6));
}
if (IS_ENABLED(CONFIG_NET_IPV4) && family == AF_INET) {
struct sockaddr_in addr4;
if (net_sin_ptr(&context->local)->sin_addr) {
return 0;
}
addr4.sin_family = AF_INET;
addr4.sin_addr.s_addr = INADDR_ANY;
addr4.sin_port =
find_available_port(context,
(struct sockaddr *)&addr4);
return net_context_bind(context, (struct sockaddr *)&addr4,
sizeof(addr4));
}
if (IS_ENABLED(CONFIG_NET_SOCKETS_PACKET) && family == AF_PACKET) {
struct sockaddr_ll ll_addr;
if (net_sll_ptr(&context->local)->sll_addr) {
return 0;
}
ll_addr.sll_family = AF_PACKET;
ll_addr.sll_protocol = htons(ETH_P_ALL);
ll_addr.sll_ifindex = net_if_get_by_iface(net_if_get_default());
return net_context_bind(context, (struct sockaddr *)&ll_addr,
sizeof(ll_addr));
}
if (IS_ENABLED(CONFIG_NET_SOCKETS_CAN) && family == AF_CAN) {
struct sockaddr_can can_addr;
if (context->iface >= 0) {
return 0;
} else {
#if defined(CONFIG_NET_L2_CANBUS_RAW)
struct net_if *iface;
iface = net_if_get_first_by_type(
&NET_L2_GET_NAME(CANBUS_RAW));
if (!iface) {
return -ENOENT;
}
can_addr.can_ifindex = net_if_get_by_iface(iface);
context->iface = can_addr.can_ifindex;
#else
return -ENOENT;
#endif
}
can_addr.can_family = AF_CAN;
return net_context_bind(context, (struct sockaddr *)&can_addr,
sizeof(can_addr));
}
return -EINVAL;
}
int net_context_bind(struct net_context *context, const struct sockaddr *addr,
socklen_t addrlen)
{
int ret;
NET_ASSERT(addr);
NET_ASSERT(PART_OF_ARRAY(contexts, context));
/* If we already have connection handler, then it effectively
* means that it's already bound to an interface/port, and we
* don't support rebinding connection to new address/port in
* the code below.
* TODO: Support rebinding.
*/
if (context->conn_handler) {
return -EISCONN;
}
if (IS_ENABLED(CONFIG_NET_IPV6) && addr->sa_family == AF_INET6) {
struct net_if *iface = NULL;
struct in6_addr *ptr;
struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)addr;
if (addrlen < sizeof(struct sockaddr_in6)) {
return -EINVAL;
}
if (net_context_is_bound_to_iface(context)) {
iface = net_context_get_iface(context);
}
if (net_ipv6_is_addr_mcast(&addr6->sin6_addr)) {
struct net_if_mcast_addr *maddr;
maddr = net_if_ipv6_maddr_lookup(&addr6->sin6_addr,
&iface);
if (!maddr) {
return -ENOENT;
}
ptr = &maddr->address.in6_addr;
} else if (net_ipv6_is_addr_unspecified(&addr6->sin6_addr)) {
if (iface == NULL) {
iface = net_if_ipv6_select_src_iface(
&net_sin6(&context->remote)->sin6_addr);
}
ptr = (struct in6_addr *)net_ipv6_unspecified_address();
} else {
struct net_if_addr *ifaddr;
ifaddr = net_if_ipv6_addr_lookup(
&addr6->sin6_addr,
iface == NULL ? &iface : NULL);
if (!ifaddr) {
return -ENOENT;
}
ptr = &ifaddr->address.in6_addr;
}
if (!iface) {
NET_ERR("Cannot bind to %s",
net_sprint_ipv6_addr(&addr6->sin6_addr));
return -EADDRNOTAVAIL;
}
if (IS_ENABLED(CONFIG_NET_OFFLOAD) &&
net_if_is_ip_offloaded(iface)) {
net_context_set_iface(context, iface);
return net_offload_bind(iface,
context,
addr,
addrlen);
}
k_mutex_lock(&context->lock, K_FOREVER);
ret = 0;
net_context_set_iface(context, iface);
net_sin6_ptr(&context->local)->sin6_family = AF_INET6;
net_sin6_ptr(&context->local)->sin6_addr = ptr;
if (addr6->sin6_port) {
ret = check_used_port(AF_INET6, addr6->sin6_port,
addr);
if (!ret) {
net_sin6_ptr(&context->local)->sin6_port =
addr6->sin6_port;
} else {
NET_ERR("Port %d is in use!",
ntohs(addr6->sin6_port));
goto unlock_ipv6;
}
} else {
addr6->sin6_port =
net_sin6_ptr(&context->local)->sin6_port;
}
NET_DBG("Context %p binding to %s [%s]:%d iface %d (%p)",
context,
net_proto2str(AF_INET6,
net_context_get_proto(context)),
net_sprint_ipv6_addr(ptr),
ntohs(addr6->sin6_port),
net_if_get_by_iface(iface), iface);
unlock_ipv6:
k_mutex_unlock(&context->lock);
return ret;
}
if (IS_ENABLED(CONFIG_NET_IPV4) && addr->sa_family == AF_INET) {
struct sockaddr_in *addr4 = (struct sockaddr_in *)addr;
struct net_if *iface = NULL;
struct net_if_addr *ifaddr;
struct in_addr *ptr;
if (addrlen < sizeof(struct sockaddr_in)) {
return -EINVAL;
}
if (net_context_is_bound_to_iface(context)) {
iface = net_context_get_iface(context);
}
if (net_ipv4_is_addr_mcast(&addr4->sin_addr)) {
struct net_if_mcast_addr *maddr;
maddr = net_if_ipv4_maddr_lookup(&addr4->sin_addr,
&iface);
if (!maddr) {
return -ENOENT;
}
ptr = &maddr->address.in_addr;
} else if (addr4->sin_addr.s_addr == INADDR_ANY) {
if (iface == NULL) {
iface = net_if_ipv4_select_src_iface(
&net_sin(&context->remote)->sin_addr);
}
ptr = (struct in_addr *)net_ipv4_unspecified_address();
} else {
ifaddr = net_if_ipv4_addr_lookup(
&addr4->sin_addr,
iface == NULL ? &iface : NULL);
if (!ifaddr) {
return -ENOENT;
}
ptr = &ifaddr->address.in_addr;
}
if (!iface) {
NET_ERR("Cannot bind to %s",
net_sprint_ipv4_addr(&addr4->sin_addr));
return -EADDRNOTAVAIL;
}
if (IS_ENABLED(CONFIG_NET_OFFLOAD) &&
net_if_is_ip_offloaded(iface)) {
net_context_set_iface(context, iface);
return net_offload_bind(iface,
context,
addr,
addrlen);
}
k_mutex_lock(&context->lock, K_FOREVER);
ret = 0;
net_context_set_iface(context, iface);
net_sin_ptr(&context->local)->sin_family = AF_INET;
net_sin_ptr(&context->local)->sin_addr = ptr;
if (addr4->sin_port) {
ret = check_used_port(AF_INET, addr4->sin_port,
addr);
if (!ret) {
net_sin_ptr(&context->local)->sin_port =
addr4->sin_port;
} else {
NET_ERR("Port %d is in use!",
ntohs(addr4->sin_port));
goto unlock_ipv4;
}
} else {
addr4->sin_port =
net_sin_ptr(&context->local)->sin_port;
}
NET_DBG("Context %p binding to %s %s:%d iface %d (%p)",
context,
net_proto2str(AF_INET,
net_context_get_proto(context)),
net_sprint_ipv4_addr(ptr),
ntohs(addr4->sin_port),
net_if_get_by_iface(iface), iface);
unlock_ipv4:
k_mutex_unlock(&context->lock);
return ret;
}
if (IS_ENABLED(CONFIG_NET_SOCKETS_PACKET) &&
addr->sa_family == AF_PACKET) {
struct sockaddr_ll *ll_addr = (struct sockaddr_ll *)addr;
struct net_if *iface = NULL;
if (addrlen < sizeof(struct sockaddr_ll)) {
return -EINVAL;
}
if (ll_addr->sll_ifindex < 0) {
return -EINVAL;
}
iface = net_if_get_by_index(ll_addr->sll_ifindex);
if (!iface) {
NET_ERR("Cannot bind to interface index %d",
ll_addr->sll_ifindex);
return -EADDRNOTAVAIL;
}
if (IS_ENABLED(CONFIG_NET_OFFLOAD) &&
net_if_is_ip_offloaded(iface)) {
net_context_set_iface(context, iface);
return net_offload_bind(iface,
context,
addr,
addrlen);
}
k_mutex_lock(&context->lock, K_FOREVER);
net_context_set_iface(context, iface);
net_sll_ptr(&context->local)->sll_family = AF_PACKET;
net_sll_ptr(&context->local)->sll_ifindex =
ll_addr->sll_ifindex;
net_sll_ptr(&context->local)->sll_protocol =
ll_addr->sll_protocol;
net_sll_ptr(&context->local)->sll_addr =
net_if_get_link_addr(iface)->addr;
net_sll_ptr(&context->local)->sll_halen =
net_if_get_link_addr(iface)->len;
NET_DBG("Context %p bind to type 0x%04x iface[%d] %p addr %s",
context, htons(net_context_get_proto(context)),
ll_addr->sll_ifindex, iface,
net_sprint_ll_addr(
net_sll_ptr(&context->local)->sll_addr,
net_sll_ptr(&context->local)->sll_halen));
k_mutex_unlock(&context->lock);
return 0;
}
if (IS_ENABLED(CONFIG_NET_SOCKETS_CAN) && addr->sa_family == AF_CAN) {
struct sockaddr_can *can_addr = (struct sockaddr_can *)addr;
struct net_if *iface = NULL;
if (addrlen < sizeof(struct sockaddr_can)) {
return -EINVAL;
}
if (can_addr->can_ifindex < 0) {
return -EINVAL;
}
iface = net_if_get_by_index(can_addr->can_ifindex);
if (!iface) {
NET_ERR("Cannot bind to interface index %d",
can_addr->can_ifindex);
return -EADDRNOTAVAIL;
}
if (IS_ENABLED(CONFIG_NET_OFFLOAD) &&
net_if_is_ip_offloaded(iface)) {
net_context_set_iface(context, iface);
return net_offload_bind(iface,
context,
addr,
addrlen);
}
k_mutex_lock(&context->lock, K_FOREVER);
net_context_set_iface(context, iface);
net_context_set_family(context, AF_CAN);
net_can_ptr(&context->local)->can_family = AF_CAN;
net_can_ptr(&context->local)->can_ifindex =
can_addr->can_ifindex;
NET_DBG("Context %p binding to %d iface[%d] %p",
context, net_context_get_proto(context),
can_addr->can_ifindex, iface);
k_mutex_unlock(&context->lock);
return 0;
}
return -EINVAL;
}
static inline struct net_context *find_context(void *conn_handler)
{
int i;
for (i = 0; i < NET_MAX_CONTEXT; i++) {
if (!net_context_is_used(&contexts[i])) {
continue;
}
if (contexts[i].conn_handler == conn_handler) {
return &contexts[i];
}
}
return NULL;
}
int net_context_listen(struct net_context *context, int backlog)
{
ARG_UNUSED(backlog);
NET_ASSERT(PART_OF_ARRAY(contexts, context));
if (!net_context_is_used(context)) {
return -EBADF;
}
if (IS_ENABLED(CONFIG_NET_OFFLOAD) &&
net_if_is_ip_offloaded(net_context_get_iface(context))) {
return net_offload_listen(net_context_get_iface(context),
context, backlog);
}
k_mutex_lock(&context->lock, K_FOREVER);
if (net_tcp_listen(context) >= 0) {
k_mutex_unlock(&context->lock);
return 0;
}
k_mutex_unlock(&context->lock);
return -EOPNOTSUPP;
}
#if defined(CONFIG_NET_IPV4)
int net_context_create_ipv4_new(struct net_context *context,
struct net_pkt *pkt,
const struct in_addr *src,
const struct in_addr *dst)
{
if (!src) {
NET_ASSERT(((
struct sockaddr_in_ptr *)&context->local)->sin_addr);
src = ((struct sockaddr_in_ptr *)&context->local)->sin_addr;
}
if (net_ipv4_is_addr_unspecified(src)
|| net_ipv4_is_addr_mcast(src)) {
src = net_if_ipv4_select_src_addr(net_pkt_iface(pkt),
(struct in_addr *)dst);
/* If src address is still unspecified, do not create pkt */
if (net_ipv4_is_addr_unspecified(src)) {
NET_DBG("DROP: src addr is unspecified");
return -EINVAL;
}
}
net_pkt_set_ipv4_ttl(pkt, net_context_get_ipv4_ttl(context));
#if defined(CONFIG_NET_CONTEXT_DSCP_ECN)
net_pkt_set_ip_dscp(pkt, net_ipv4_get_dscp(context->options.dscp_ecn));
net_pkt_set_ip_ecn(pkt, net_ipv4_get_ecn(context->options.dscp_ecn));
#endif
return net_ipv4_create(pkt, src, dst);
}
#endif /* CONFIG_NET_IPV4 */
#if defined(CONFIG_NET_IPV6)
int net_context_create_ipv6_new(struct net_context *context,
struct net_pkt *pkt,
const struct in6_addr *src,
const struct in6_addr *dst)
{
if (!src) {
NET_ASSERT(((
struct sockaddr_in6_ptr *)&context->local)->sin6_addr);
src = ((struct sockaddr_in6_ptr *)&context->local)->sin6_addr;
}
if (net_ipv6_is_addr_unspecified(src)
|| net_ipv6_is_addr_mcast(src)) {
src = net_if_ipv6_select_src_addr(net_pkt_iface(pkt),
(struct in6_addr *)dst);
}
net_pkt_set_ipv6_hop_limit(pkt,
net_context_get_ipv6_hop_limit(context));
#if defined(CONFIG_NET_CONTEXT_DSCP_ECN)
net_pkt_set_ip_dscp(pkt, net_ipv6_get_dscp(context->options.dscp_ecn));
net_pkt_set_ip_ecn(pkt, net_ipv6_get_ecn(context->options.dscp_ecn));
#endif
return net_ipv6_create(pkt, src, dst);
}
#endif /* CONFIG_NET_IPV6 */
int net_context_connect(struct net_context *context,
const struct sockaddr *addr,
socklen_t addrlen,
net_context_connect_cb_t cb,
k_timeout_t timeout,
void *user_data)
{
struct sockaddr *laddr = NULL;
struct sockaddr local_addr __unused;
uint16_t lport, rport;
int ret;
NET_ASSERT(addr);
NET_ASSERT(PART_OF_ARRAY(contexts, context));
k_mutex_lock(&context->lock, K_FOREVER);
if (!net_context_is_used(context)) {
ret = -EBADF;
goto unlock;
}
if (addr->sa_family != net_context_get_family(context)) {
NET_ASSERT(addr->sa_family == net_context_get_family(context),
"Family mismatch %d should be %d",
addr->sa_family,
net_context_get_family(context));
ret = -EINVAL;
goto unlock;
}
if (IS_ENABLED(CONFIG_NET_SOCKETS_PACKET) &&
addr->sa_family == AF_PACKET) {
ret = -EOPNOTSUPP;
goto unlock;
}
if (net_context_get_state(context) == NET_CONTEXT_LISTENING) {
ret = -EOPNOTSUPP;
goto unlock;
}
if (IS_ENABLED(CONFIG_NET_IPV6) &&
net_context_get_family(context) == AF_INET6) {
struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)
&context->remote;
if (addrlen < sizeof(struct sockaddr_in6)) {
ret = -EINVAL;
goto unlock;
}
if (net_context_get_proto(context) == IPPROTO_TCP &&
net_ipv6_is_addr_mcast(&addr6->sin6_addr)) {
ret = -EADDRNOTAVAIL;
goto unlock;
}
memcpy(&addr6->sin6_addr, &net_sin6(addr)->sin6_addr,
sizeof(struct in6_addr));
addr6->sin6_port = net_sin6(addr)->sin6_port;
addr6->sin6_family = AF_INET6;
if (!net_ipv6_is_addr_unspecified(&addr6->sin6_addr)) {
context->flags |= NET_CONTEXT_REMOTE_ADDR_SET;
} else {
context->flags &= ~NET_CONTEXT_REMOTE_ADDR_SET;
}
rport = addr6->sin6_port;
/* The binding must be done after we have set the remote
* address but before checking the local address. Otherwise
* the laddr might not be set properly which would then cause
* issues when doing net_tcp_connect(). This issue was seen
* with socket tests and when connecting to loopback interface.
*/
ret = bind_default(context);
if (ret) {
goto unlock;
}
net_sin6_ptr(&context->local)->sin6_family = AF_INET6;
net_sin6(&local_addr)->sin6_family = AF_INET6;
net_sin6(&local_addr)->sin6_port = lport =
net_sin6((struct sockaddr *)&context->local)->sin6_port;
if (net_sin6_ptr(&context->local)->sin6_addr) {
net_ipaddr_copy(&net_sin6(&local_addr)->sin6_addr,
net_sin6_ptr(&context->local)->sin6_addr);
laddr = &local_addr;
}
} else if (IS_ENABLED(CONFIG_NET_IPV4) &&
net_context_get_family(context) == AF_INET) {
struct sockaddr_in *addr4 = (struct sockaddr_in *)
&context->remote;
if (addrlen < sizeof(struct sockaddr_in)) {
ret = -EINVAL;
goto unlock;
}
/* FIXME - Add multicast and broadcast address check */
memcpy(&addr4->sin_addr, &net_sin(addr)->sin_addr,
sizeof(struct in_addr));
addr4->sin_port = net_sin(addr)->sin_port;
addr4->sin_family = AF_INET;
if (addr4->sin_addr.s_addr) {
context->flags |= NET_CONTEXT_REMOTE_ADDR_SET;
} else {
context->flags &= ~NET_CONTEXT_REMOTE_ADDR_SET;
}
rport = addr4->sin_port;
ret = bind_default(context);
if (ret) {
goto unlock;
}
net_sin_ptr(&context->local)->sin_family = AF_INET;
net_sin(&local_addr)->sin_family = AF_INET;
net_sin(&local_addr)->sin_port = lport =
net_sin((struct sockaddr *)&context->local)->sin_port;
if (net_sin_ptr(&context->local)->sin_addr) {
net_ipaddr_copy(&net_sin(&local_addr)->sin_addr,
net_sin_ptr(&context->local)->sin_addr);
laddr = &local_addr;
}
} else {
ret = -EINVAL; /* Not IPv4 or IPv6 */
goto unlock;
}
if (IS_ENABLED(CONFIG_NET_OFFLOAD) &&
net_if_is_ip_offloaded(net_context_get_iface(context))) {
ret = net_offload_connect(
net_context_get_iface(context),
context,
addr,
addrlen,
cb,
timeout,
user_data);
goto unlock;
}
if (IS_ENABLED(CONFIG_NET_UDP) &&
net_context_get_type(context) == SOCK_DGRAM) {
if (cb) {
cb(context, 0, user_data);
}
ret = 0;
} else if (IS_ENABLED(CONFIG_NET_TCP) &&
net_context_get_type(context) == SOCK_STREAM) {
ret = net_tcp_connect(context, addr, laddr, rport, lport,
timeout, cb, user_data);
} else {
ret = -ENOTSUP;
}
unlock:
k_mutex_unlock(&context->lock);
return ret;
}
int net_context_accept(struct net_context *context,
net_tcp_accept_cb_t cb,
k_timeout_t timeout,
void *user_data)
{
int ret = 0;
NET_ASSERT(PART_OF_ARRAY(contexts, context));
if (!net_context_is_used(context)) {
return -EBADF;
}
k_mutex_lock(&context->lock, K_FOREVER);
if (IS_ENABLED(CONFIG_NET_OFFLOAD) &&
net_if_is_ip_offloaded(net_context_get_iface(context))) {
ret = net_offload_accept(
net_context_get_iface(context),
context,
cb,
timeout,
user_data);
goto unlock;
}
if ((net_context_get_state(context) != NET_CONTEXT_LISTENING) &&
(net_context_get_type(context) != SOCK_STREAM)) {
NET_DBG("Invalid socket, state %d type %d",
net_context_get_state(context),
net_context_get_type(context));
ret = -EINVAL;
goto unlock;
}
if (net_context_get_proto(context) == IPPROTO_TCP) {
ret = net_tcp_accept(context, cb, user_data);
goto unlock;
}
unlock:
k_mutex_unlock(&context->lock);
return ret;
}
static int get_context_priority(struct net_context *context,
void *value, size_t *len)
{
#if defined(CONFIG_NET_CONTEXT_PRIORITY)
*((uint8_t *)value) = context->options.priority;
if (len) {
*len = sizeof(uint8_t);
}
return 0;
#else
return -ENOTSUP;
#endif
}
static int get_context_proxy(struct net_context *context,
void *value, size_t *len)
{
#if defined(CONFIG_SOCKS)
struct sockaddr *addr = (struct sockaddr *)value;
if (!value || !len) {
return -EINVAL;
}
if (*len < context->options.proxy.addrlen) {
return -EINVAL;
}
*len = MIN(context->options.proxy.addrlen, *len);
memcpy(addr, &context->options.proxy.addr, *len);
return 0;
#else
return -ENOTSUP;
#endif
}
static int get_context_txtime(struct net_context *context,
void *value, size_t *len)
{
#if defined(CONFIG_NET_CONTEXT_TXTIME)
*((bool *)value) = context->options.txtime;
if (len) {
*len = sizeof(bool);
}
return 0;
#else
return -ENOTSUP;
#endif
}
static int get_context_rcvtimeo(struct net_context *context,
void *value, size_t *len)
{
#if defined(CONFIG_NET_CONTEXT_RCVTIMEO)
*((k_timeout_t *)value) = context->options.rcvtimeo;
if (len) {
*len = sizeof(k_timeout_t);
}
return 0;
#else
return -ENOTSUP;
#endif
}
static int get_context_sndtimeo(struct net_context *context,
void *value, size_t *len)
{
#if defined(CONFIG_NET_CONTEXT_SNDTIMEO)
*((k_timeout_t *)value) = context->options.sndtimeo;
if (len) {
*len = sizeof(k_timeout_t);
}
return 0;
#else
return -ENOTSUP;
#endif
}
static int get_context_rcvbuf(struct net_context *context,
void *value, size_t *len)
{
#if defined(CONFIG_NET_CONTEXT_RCVBUF)
*((int *)value) = context->options.rcvbuf;
if (len) {
*len = sizeof(int);
}
return 0;
#else
return -ENOTSUP;
#endif
}
static int get_context_sndbuf(struct net_context *context,
void *value, size_t *len)
{
#if defined(CONFIG_NET_CONTEXT_SNDBUF)
*((int *)value) = context->options.sndbuf;
if (len) {
*len = sizeof(int);
}
return 0;
#else
return -ENOTSUP;
#endif
}
static int get_context_dscp_ecn(struct net_context *context,
void *value, size_t *len)
{
#if defined(CONFIG_NET_CONTEXT_DSCP_ECN)
*((int *)value) = context->options.dscp_ecn;
if (len) {
*len = sizeof(int);
}
return 0;
#else
return -ENOTSUP;
#endif
}
/* If buf is not NULL, then use it. Otherwise read the data to be written
* to net_pkt from msghdr.
*/
static int context_write_data(struct net_pkt *pkt, const void *buf,
int buf_len, const struct msghdr *msghdr)
{
int ret = 0;
if (msghdr) {
int i;
for (i = 0; i < msghdr->msg_iovlen; i++) {
int len = MIN(msghdr->msg_iov[i].iov_len, buf_len);
ret = net_pkt_write(pkt, msghdr->msg_iov[i].iov_base,
len);
if (ret < 0) {
break;
}
buf_len -= len;
if (buf_len == 0) {
break;
}
}
} else {
ret = net_pkt_write(pkt, buf, buf_len);
}
return ret;
}
static int context_setup_udp_packet(struct net_context *context,
struct net_pkt *pkt,
const void *buf,
size_t len,
const struct msghdr *msg,
const struct sockaddr *dst_addr,
socklen_t addrlen)
{
int ret = -EINVAL;
uint16_t dst_port = 0U;
if (IS_ENABLED(CONFIG_NET_IPV6) &&
net_context_get_family(context) == AF_INET6) {
struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)dst_addr;
dst_port = addr6->sin6_port;
ret = net_context_create_ipv6_new(context, pkt,
NULL, &addr6->sin6_addr);
} else if (IS_ENABLED(CONFIG_NET_IPV4) &&
net_context_get_family(context) == AF_INET) {
struct sockaddr_in *addr4 = (struct sockaddr_in *)dst_addr;
dst_port = addr4->sin_port;
ret = net_context_create_ipv4_new(context, pkt,
NULL, &addr4->sin_addr);
}
if (ret < 0) {
return ret;
}
ret = bind_default(context);
if (ret) {
return ret;
}
ret = net_udp_create(pkt,
net_sin((struct sockaddr *)
&context->local)->sin_port,
dst_port);
if (ret) {
return ret;
}
ret = context_write_data(pkt, buf, len, msg);
if (ret) {
return ret;
}
return 0;
}
static void context_finalize_packet(struct net_context *context,
struct net_pkt *pkt)
{
/* This function is meant to be temporary: once all moved to new
* API, it will be up to net_send_data() to finalize the packet.
*/
net_pkt_cursor_init(pkt);
if (IS_ENABLED(CONFIG_NET_IPV6) &&
net_context_get_family(context) == AF_INET6) {
net_ipv6_finalize(pkt, net_context_get_proto(context));
} else if (IS_ENABLED(CONFIG_NET_IPV4) &&
net_context_get_family(context) == AF_INET) {
net_ipv4_finalize(pkt, net_context_get_proto(context));
}
}
static struct net_pkt *context_alloc_pkt(struct net_context *context,
size_t len, k_timeout_t timeout)
{
struct net_pkt *pkt;
#if defined(CONFIG_NET_CONTEXT_NET_PKT_POOL)
if (context->tx_slab) {
pkt = net_pkt_alloc_from_slab(context->tx_slab(), timeout);
if (!pkt) {
return NULL;
}
net_pkt_set_iface(pkt, net_context_get_iface(context));
net_pkt_set_family(pkt, net_context_get_family(context));
net_pkt_set_context(pkt, context);
if (net_pkt_alloc_buffer(pkt, len,
net_context_get_proto(context),
timeout)) {
net_pkt_unref(pkt);
return NULL;
}
return pkt;
}
#endif
pkt = net_pkt_alloc_with_buffer(net_context_get_iface(context), len,
net_context_get_family(context),
net_context_get_proto(context),
timeout);
if (pkt) {
net_pkt_set_context(pkt, context);
}
return pkt;
}
static void set_pkt_txtime(struct net_pkt *pkt, const struct msghdr *msghdr)
{
struct cmsghdr *cmsg;
for (cmsg = CMSG_FIRSTHDR(msghdr); cmsg != NULL;
cmsg = CMSG_NXTHDR(msghdr, cmsg)) {
if (cmsg->cmsg_len == CMSG_LEN(sizeof(uint64_t)) &&
cmsg->cmsg_level == SOL_SOCKET &&
cmsg->cmsg_type == SCM_TXTIME) {
uint64_t txtime = *(uint64_t *)CMSG_DATA(cmsg);
net_pkt_set_txtime(pkt, txtime);
break;
}
}
}
static int context_sendto(struct net_context *context,
const void *buf,
size_t len,
const struct sockaddr *dst_addr,
socklen_t addrlen,
net_context_send_cb_t cb,
k_timeout_t timeout,
void *user_data,
bool sendto)
{
const struct msghdr *msghdr = NULL;
struct net_if *iface;
struct net_pkt *pkt;
size_t tmp_len;
int ret;
NET_ASSERT(PART_OF_ARRAY(contexts, context));
if (!net_context_is_used(context)) {
return -EBADF;
}
if (sendto && addrlen == 0 && dst_addr == NULL && buf != NULL) {
/* User wants to call sendmsg */
msghdr = buf;
}
if (!msghdr && !dst_addr) {
return -EDESTADDRREQ;
}
if (IS_ENABLED(CONFIG_NET_IPV6) &&
net_context_get_family(context) == AF_INET6) {
const struct sockaddr_in6 *addr6 =
(const struct sockaddr_in6 *)dst_addr;
if (msghdr) {
addr6 = msghdr->msg_name;
addrlen = msghdr->msg_namelen;
if (!addr6) {
addr6 = net_sin6(&context->remote);
addrlen = sizeof(struct sockaddr_in6);
}
/* For sendmsg(), the dst_addr is NULL so set it here.
*/
dst_addr = (const struct sockaddr *)addr6;
}
if (addrlen < sizeof(struct sockaddr_in6)) {
return -EINVAL;
}
if (net_ipv6_is_addr_unspecified(&addr6->sin6_addr)) {
return -EDESTADDRREQ;
}
/* If application has not yet set the destination address
* i.e., by not calling connect(), then set the interface
* here so that the packet gets sent to the correct network
* interface. This issue can be seen if there are multiple
* network interfaces and we are trying to send data to
* second or later network interface.
*/
if (net_ipv6_is_addr_unspecified(
&net_sin6(&context->remote)->sin6_addr) &&
!net_context_is_bound_to_iface(context)) {
iface = net_if_ipv6_select_src_iface(&addr6->sin6_addr);
net_context_set_iface(context, iface);
}
} else if (IS_ENABLED(CONFIG_NET_IPV4) &&
net_context_get_family(context) == AF_INET) {
const struct sockaddr_in *addr4 =
(const struct sockaddr_in *)dst_addr;
if (msghdr) {
addr4 = msghdr->msg_name;
addrlen = msghdr->msg_namelen;
if (!addr4) {
addr4 = net_sin(&context->remote);
addrlen = sizeof(struct sockaddr_in);
}
/* For sendmsg(), the dst_addr is NULL so set it here.
*/
dst_addr = (const struct sockaddr *)addr4;
}
if (addrlen < sizeof(struct sockaddr_in)) {
return -EINVAL;
}
if (!addr4->sin_addr.s_addr) {
return -EDESTADDRREQ;
}
/* If application has not yet set the destination address
* i.e., by not calling connect(), then set the interface
* here so that the packet gets sent to the correct network
* interface. This issue can be seen if there are multiple
* network interfaces and we are trying to send data to
* second or later network interface.
*/
if (net_sin(&context->remote)->sin_addr.s_addr == 0U &&
!net_context_is_bound_to_iface(context)) {
iface = net_if_ipv4_select_src_iface(&addr4->sin_addr);
net_context_set_iface(context, iface);
}
} else if (IS_ENABLED(CONFIG_NET_SOCKETS_PACKET) &&
net_context_get_family(context) == AF_PACKET) {
struct sockaddr_ll *ll_addr = (struct sockaddr_ll *)dst_addr;
if (msghdr) {
ll_addr = msghdr->msg_name;
addrlen = msghdr->msg_namelen;
if (!ll_addr) {
ll_addr = (struct sockaddr_ll *)
(&context->remote);
addrlen = sizeof(struct sockaddr_ll);
}
/* For sendmsg(), the dst_addr is NULL so set it here.
*/
dst_addr = (const struct sockaddr *)ll_addr;
}
if (addrlen < sizeof(struct sockaddr_ll)) {
return -EINVAL;
}
iface = net_context_get_iface(context);
if (iface == NULL) {
if (ll_addr->sll_ifindex < 0) {
return -EDESTADDRREQ;
}
iface = net_if_get_by_index(ll_addr->sll_ifindex);
if (iface == NULL) {
NET_ERR("Cannot bind to interface index %d",
ll_addr->sll_ifindex);
return -EDESTADDRREQ;
}
}
if (net_context_get_type(context) == SOCK_DGRAM) {
context->flags |= NET_CONTEXT_REMOTE_ADDR_SET;
/* The user must set the protocol in send call */
/* For sendmsg() call, we might have set ll_addr to
* point to remote addr.
*/
if ((void *)&context->remote != (void *)ll_addr) {
memcpy((struct sockaddr_ll *)&context->remote,
ll_addr, sizeof(struct sockaddr_ll));
}
}
} else if (IS_ENABLED(CONFIG_NET_SOCKETS_CAN) &&
net_context_get_family(context) == AF_CAN) {
struct sockaddr_can *can_addr = (struct sockaddr_can *)dst_addr;
if (msghdr) {
can_addr = msghdr->msg_name;
addrlen = msghdr->msg_namelen;
if (!can_addr) {
can_addr = (struct sockaddr_can *)
(&context->remote);
addrlen = sizeof(struct sockaddr_can);
}
/* For sendmsg(), the dst_addr is NULL so set it here.
*/
dst_addr = (const struct sockaddr *)can_addr;
}
if (addrlen < sizeof(struct sockaddr_can)) {
return -EINVAL;
}
if (can_addr->can_ifindex < 0) {
/* The index should have been set in bind */
can_addr->can_ifindex =
net_can_ptr(&context->local)->can_ifindex;
}
if (can_addr->can_ifindex < 0) {
return -EDESTADDRREQ;
}
iface = net_if_get_by_index(can_addr->can_ifindex);
if (!iface) {
NET_ERR("Cannot bind to interface index %d",
can_addr->can_ifindex);
return -EDESTADDRREQ;
}
} else {
NET_DBG("Invalid protocol family %d",
net_context_get_family(context));
return -EINVAL;
}
if (msghdr && len == 0) {
int i;
for (i = 0; i < msghdr->msg_iovlen; i++) {
len += msghdr->msg_iov[i].iov_len;
}
}
iface = net_context_get_iface(context);
if (iface && !net_if_is_up(iface)) {
return -ENETDOWN;
}
pkt = context_alloc_pkt(context, len, PKT_WAIT_TIME);
if (!pkt) {
NET_ERR("Failed to allocate net_pkt");
return -ENOBUFS;
}
tmp_len = net_pkt_available_payload_buffer(
pkt, net_context_get_proto(context));
if (tmp_len < len) {
if (net_context_get_type(context) == SOCK_DGRAM) {
NET_ERR("Available payload buffer (%zu) is not enough for requested DGRAM (%zu)",
tmp_len, len);
ret = -ENOMEM;
goto fail;
}
len = tmp_len;
}
context->send_cb = cb;
context->user_data = user_data;
if (IS_ENABLED(CONFIG_NET_CONTEXT_PRIORITY)) {
uint8_t priority;
get_context_priority(context, &priority, NULL);
net_pkt_set_priority(pkt, priority);
}
/* If there is ancillary data in msghdr, then we need to add that
* to net_pkt as there is no other way to store it.
*/
if (msghdr && msghdr->msg_control && msghdr->msg_controllen) {
if (IS_ENABLED(CONFIG_NET_CONTEXT_TXTIME)) {
bool is_txtime;
get_context_txtime(context, &is_txtime, NULL);
if (is_txtime) {
set_pkt_txtime(pkt, msghdr);
}
}
}
if (IS_ENABLED(CONFIG_NET_OFFLOAD) &&
net_if_is_ip_offloaded(net_context_get_iface(context))) {
ret = context_write_data(pkt, buf, len, msghdr);
if (ret < 0) {
goto fail;
}
net_pkt_cursor_init(pkt);
if (sendto) {
ret = net_offload_sendto(net_context_get_iface(context),
pkt, dst_addr, addrlen, cb,
timeout, user_data);
} else {
ret = net_offload_send(net_context_get_iface(context),
pkt, cb, timeout, user_data);
}
} else if (IS_ENABLED(CONFIG_NET_UDP) &&
net_context_get_proto(context) == IPPROTO_UDP) {
ret = context_setup_udp_packet(context, pkt, buf, len, msghdr,
dst_addr, addrlen);
if (ret < 0) {
goto fail;
}
context_finalize_packet(context, pkt);
ret = net_send_data(pkt);
} else if (IS_ENABLED(CONFIG_NET_TCP) &&
net_context_get_proto(context) == IPPROTO_TCP) {
ret = context_write_data(pkt, buf, len, msghdr);
if (ret < 0) {
goto fail;
}
net_pkt_cursor_init(pkt);
ret = net_tcp_queue_data(context, pkt);
if (ret < 0) {
goto fail;
}
ret = net_tcp_send_data(context, cb, user_data);
} else if (IS_ENABLED(CONFIG_NET_SOCKETS_PACKET) &&
net_context_get_family(context) == AF_PACKET) {
ret = context_write_data(pkt, buf, len, msghdr);
if (ret < 0) {
goto fail;
}
net_pkt_cursor_init(pkt);
if (net_context_get_proto(context) == IPPROTO_RAW) {
char type = (NET_IPV6_HDR(pkt)->vtc & 0xf0);
/* Set the family to pkt if detected */
switch (type) {
case 0x60:
net_pkt_set_family(pkt, AF_INET6);
break;
case 0x40:
net_pkt_set_family(pkt, AF_INET);
break;
default:
/* Not IP traffic, let it go forward as it is */
break;
}
/* Pass to L2: */
ret = net_send_data(pkt);
} else {
net_if_queue_tx(net_pkt_iface(pkt), pkt);
}
} else if (IS_ENABLED(CONFIG_NET_SOCKETS_CAN) &&
net_context_get_family(context) == AF_CAN &&
net_context_get_proto(context) == CAN_RAW) {
ret = context_write_data(pkt, buf, len, msghdr);
if (ret < 0) {
goto fail;
}
net_pkt_cursor_init(pkt);
ret = net_send_data(pkt);
} else {
NET_DBG("Unknown protocol while sending packet: %d",
net_context_get_proto(context));
ret = -EPROTONOSUPPORT;
}
if (ret < 0) {
goto fail;
}
return len;
fail:
net_pkt_unref(pkt);
return ret;
}
int net_context_send(struct net_context *context,
const void *buf,
size_t len,
net_context_send_cb_t cb,
k_timeout_t timeout,
void *user_data)
{
socklen_t addrlen;
int ret = 0;
k_mutex_lock(&context->lock, K_FOREVER);
if (!(context->flags & NET_CONTEXT_REMOTE_ADDR_SET) ||
!net_sin(&context->remote)->sin_port) {
ret = -EDESTADDRREQ;
goto unlock;
}
if (IS_ENABLED(CONFIG_NET_IPV6) &&
net_context_get_family(context) == AF_INET6) {
addrlen = sizeof(struct sockaddr_in6);
} else if (IS_ENABLED(CONFIG_NET_IPV4) &&
net_context_get_family(context) == AF_INET) {
addrlen = sizeof(struct sockaddr_in);
} else if (IS_ENABLED(CONFIG_NET_SOCKETS_PACKET) &&
net_context_get_family(context) == AF_PACKET) {
ret = -EOPNOTSUPP;
goto unlock;
} else if (IS_ENABLED(CONFIG_NET_SOCKETS_CAN) &&
net_context_get_family(context) == AF_CAN) {
addrlen = sizeof(struct sockaddr_can);
} else {
addrlen = 0;
}
ret = context_sendto(context, buf, len, &context->remote,
addrlen, cb, timeout, user_data, false);
unlock:
k_mutex_unlock(&context->lock);
return ret;
}
int net_context_sendmsg(struct net_context *context,
const struct msghdr *msghdr,
int flags,
net_context_send_cb_t cb,
k_timeout_t timeout,
void *user_data)
{
int ret;
k_mutex_lock(&context->lock, K_FOREVER);
ret = context_sendto(context, msghdr, 0, NULL, 0,
cb, timeout, user_data, true);
k_mutex_unlock(&context->lock);
return ret;
}
int net_context_sendto(struct net_context *context,
const void *buf,
size_t len,
const struct sockaddr *dst_addr,
socklen_t addrlen,
net_context_send_cb_t cb,
k_timeout_t timeout,
void *user_data)
{
int ret;
k_mutex_lock(&context->lock, K_FOREVER);
ret = context_sendto(context, buf, len, dst_addr, addrlen,
cb, timeout, user_data, true);
k_mutex_unlock(&context->lock);
return ret;
}
enum net_verdict net_context_packet_received(struct net_conn *conn,
struct net_pkt *pkt,
union net_ip_header *ip_hdr,
union net_proto_header *proto_hdr,
void *user_data)
{
struct net_context *context = find_context(conn);
enum net_verdict verdict = NET_DROP;
NET_ASSERT(context);
NET_ASSERT(net_pkt_iface(pkt));
k_mutex_lock(&context->lock, K_FOREVER);
net_context_set_iface(context, net_pkt_iface(pkt));
net_pkt_set_context(pkt, context);
/* If there is no callback registered, then we can only drop
* the packet.
*/
if (!context->recv_cb) {
goto unlock;
}
if (net_context_get_proto(context) == IPPROTO_TCP) {
net_stats_update_tcp_recv(net_pkt_iface(pkt),
net_pkt_remaining_data(pkt));
}
#if defined(CONFIG_NET_CONTEXT_SYNC_RECV)
k_sem_give(&context->recv_data_wait);
#endif /* CONFIG_NET_CONTEXT_SYNC_RECV */
k_mutex_unlock(&context->lock);
context->recv_cb(context, pkt, ip_hdr, proto_hdr, 0, user_data);
verdict = NET_OK;
return verdict;
unlock:
k_mutex_unlock(&context->lock);
return verdict;
}
#if defined(CONFIG_NET_UDP)
static int recv_udp(struct net_context *context,
net_context_recv_cb_t cb,
k_timeout_t timeout,
void *user_data)
{
struct sockaddr local_addr = {
.sa_family = net_context_get_family(context),
};
struct sockaddr *laddr = NULL;
uint16_t lport = 0U;
int ret;
ARG_UNUSED(timeout);
if (context->conn_handler) {
net_conn_unregister(context->conn_handler);
context->conn_handler = NULL;
}
ret = bind_default(context);
if (ret) {
return ret;
}
if (IS_ENABLED(CONFIG_NET_IPV6) &&
net_context_get_family(context) == AF_INET6) {
if (net_sin6_ptr(&context->local)->sin6_addr) {
net_ipaddr_copy(&net_sin6(&local_addr)->sin6_addr,
net_sin6_ptr(&context->local)->sin6_addr);
laddr = &local_addr;
}
net_sin6(&local_addr)->sin6_port =
net_sin6((struct sockaddr *)&context->local)->sin6_port;
lport = net_sin6((struct sockaddr *)&context->local)->sin6_port;
} else if (IS_ENABLED(CONFIG_NET_IPV4) &&
net_context_get_family(context) == AF_INET) {
if (net_sin_ptr(&context->local)->sin_addr) {
net_ipaddr_copy(&net_sin(&local_addr)->sin_addr,
net_sin_ptr(&context->local)->sin_addr);
laddr = &local_addr;
}
lport = net_sin((struct sockaddr *)&context->local)->sin_port;
}
context->recv_cb = cb;
ret = net_conn_register(net_context_get_proto(context),
net_context_get_family(context),
context->flags & NET_CONTEXT_REMOTE_ADDR_SET ?
&context->remote : NULL,
laddr,
ntohs(net_sin(&context->remote)->sin_port),
ntohs(lport),
context,
net_context_packet_received,
user_data,
&context->conn_handler);
return ret;
}
#else
#define recv_udp(...) 0
#endif /* CONFIG_NET_UDP */
static enum net_verdict net_context_raw_packet_received(
struct net_conn *conn,
struct net_pkt *pkt,
union net_ip_header *ip_hdr,
union net_proto_header *proto_hdr,
void *user_data)
{
struct net_context *context = find_context(conn);
NET_ASSERT(context);
NET_ASSERT(net_pkt_iface(pkt));
/* If there is no callback registered, then we can only drop
* the packet.
*/
if (!context->recv_cb) {
return NET_DROP;
}
net_context_set_iface(context, net_pkt_iface(pkt));
net_pkt_set_context(pkt, context);
context->recv_cb(context, pkt, ip_hdr, proto_hdr, 0, user_data);
#if defined(CONFIG_NET_CONTEXT_SYNC_RECV)
k_sem_give(&context->recv_data_wait);
#endif /* CONFIG_NET_CONTEXT_SYNC_RECV */
return NET_OK;
}
static int recv_raw(struct net_context *context,
net_context_recv_cb_t cb,
k_timeout_t timeout,
struct sockaddr *local_addr,
void *user_data)
{
int ret;
ARG_UNUSED(timeout);
context->recv_cb = cb;
if (context->conn_handler) {
net_conn_unregister(context->conn_handler);
context->conn_handler = NULL;
}
ret = bind_default(context);
if (ret) {
return ret;
}
ret = net_conn_register(net_context_get_proto(context),
net_context_get_family(context),
NULL, local_addr, 0, 0,
context,
net_context_raw_packet_received,
user_data,
&context->conn_handler);
return ret;
}
int net_context_recv(struct net_context *context,
net_context_recv_cb_t cb,
k_timeout_t timeout,
void *user_data)
{
int ret;
NET_ASSERT(context);
if (!net_context_is_used(context)) {
return -EBADF;
}
k_mutex_lock(&context->lock, K_FOREVER);
if (IS_ENABLED(CONFIG_NET_OFFLOAD) &&
net_if_is_ip_offloaded(net_context_get_iface(context))) {
ret = net_offload_recv(
net_context_get_iface(context),
context, cb, timeout, user_data);
goto unlock;
}
if (IS_ENABLED(CONFIG_NET_UDP) &&
net_context_get_proto(context) == IPPROTO_UDP) {
ret = recv_udp(context, cb, timeout, user_data);
} else if (IS_ENABLED(CONFIG_NET_TCP) &&
net_context_get_proto(context) == IPPROTO_TCP) {
ret = net_tcp_recv(context, cb, user_data);
} else {
if (IS_ENABLED(CONFIG_NET_SOCKETS_PACKET) &&
net_context_get_family(context) == AF_PACKET) {
struct sockaddr_ll addr;
addr.sll_family = AF_PACKET;
addr.sll_ifindex =
net_sll_ptr(&context->local)->sll_ifindex;
addr.sll_protocol =
net_sll_ptr(&context->local)->sll_protocol;
addr.sll_halen =
net_sll_ptr(&context->local)->sll_halen;
memcpy(addr.sll_addr,
net_sll_ptr(&context->local)->sll_addr,
MIN(addr.sll_halen, sizeof(addr.sll_addr)));
ret = recv_raw(context, cb, timeout,
(struct sockaddr *)&addr, user_data);
} else if (IS_ENABLED(CONFIG_NET_SOCKETS_CAN) &&
net_context_get_family(context) == AF_CAN) {
struct sockaddr_can local_addr = {
.can_family = AF_CAN,
};
ret = recv_raw(context, cb, timeout,
(struct sockaddr *)&local_addr,
user_data);
if (ret == -EALREADY) {
/* This is perfectly normal for CAN sockets.
* The SocketCAN will dispatch the packet to
* correct net_context listener.
*/
ret = 0;
}
} else {
ret = -EPROTOTYPE;
}
}
if (ret < 0) {
goto unlock;
}
#if defined(CONFIG_NET_CONTEXT_SYNC_RECV)
if (!K_TIMEOUT_EQ(timeout, K_NO_WAIT)) {
int ret;
/* Make sure we have the lock, then the
* net_context_packet_received() callback will release the
* semaphore when data has been received.
*/
k_sem_reset(&context->recv_data_wait);
k_mutex_unlock(&context->lock);
ret = k_sem_take(&context->recv_data_wait, timeout);
k_mutex_lock(&context->lock, K_FOREVER);
if (ret == -EAGAIN) {
ret = -ETIMEDOUT;
goto unlock;
}
}
#endif /* CONFIG_NET_CONTEXT_SYNC_RECV */
unlock:
k_mutex_unlock(&context->lock);
return ret;
}
int net_context_update_recv_wnd(struct net_context *context,
int32_t delta)
{
int ret;
if (IS_ENABLED(CONFIG_NET_OFFLOAD) &&
net_if_is_ip_offloaded(net_context_get_iface(context))) {
return 0;
}
k_mutex_lock(&context->lock, K_FOREVER);
ret = net_tcp_update_recv_wnd(context, delta);
k_mutex_unlock(&context->lock);
return ret;
}
static int set_context_priority(struct net_context *context,
const void *value, size_t len)
{
#if defined(CONFIG_NET_CONTEXT_PRIORITY)
if (len > sizeof(uint8_t)) {
return -EINVAL;
}
context->options.priority = *((uint8_t *)value);
return 0;
#else
return -ENOTSUP;
#endif
}
static int set_context_txtime(struct net_context *context,
const void *value, size_t len)
{
#if defined(CONFIG_NET_CONTEXT_TXTIME)
if (len > sizeof(bool)) {
return -EINVAL;
}
context->options.txtime = *((bool *)value);
return 0;
#else
return -ENOTSUP;
#endif
}
static int set_context_proxy(struct net_context *context,
const void *value, size_t len)
{
#if defined(CONFIG_SOCKS)
struct sockaddr *addr = (struct sockaddr *)value;
if (len > NET_SOCKADDR_MAX_SIZE) {
return -EINVAL;
}
if (addr->sa_family != net_context_get_family(context)) {
return -EINVAL;
}
context->options.proxy.addrlen = len;
memcpy(&context->options.proxy.addr, addr, len);
return 0;
#else
return -ENOTSUP;
#endif
}
static int set_context_rcvtimeo(struct net_context *context,
const void *value, size_t len)
{
#if defined(CONFIG_NET_CONTEXT_RCVTIMEO)
if (len != sizeof(k_timeout_t)) {
return -EINVAL;
}
context->options.rcvtimeo = *((k_timeout_t *)value);
return 0;
#else
return -ENOTSUP;
#endif
}
static int set_context_sndtimeo(struct net_context *context,
const void *value, size_t len)
{
#if defined(CONFIG_NET_CONTEXT_SNDTIMEO)
if (len != sizeof(k_timeout_t)) {
return -EINVAL;
}
context->options.sndtimeo = *((k_timeout_t *)value);
return 0;
#else
return -ENOTSUP;
#endif
}
static int set_context_rcvbuf(struct net_context *context,
const void *value, size_t len)
{
#if defined(CONFIG_NET_CONTEXT_RCVBUF)
int rcvbuf_value = *((int *)value);
if (len != sizeof(int)) {
return -EINVAL;
}
if ((rcvbuf_value < 0) || (rcvbuf_value > UINT16_MAX)) {
return -EINVAL;
}
context->options.rcvbuf = (uint16_t) rcvbuf_value;
return 0;
#else
return -ENOTSUP;
#endif
}
static int set_context_sndbuf(struct net_context *context,
const void *value, size_t len)
{
#if defined(CONFIG_NET_CONTEXT_SNDBUF)
int sndbuf_value = *((int *)value);
if (len != sizeof(int)) {
return -EINVAL;
}
if ((sndbuf_value < 0) || (sndbuf_value > UINT16_MAX)) {
return -EINVAL;
}
context->options.sndbuf = (uint16_t) sndbuf_value;
return 0;
#else
return -ENOTSUP;
#endif
}
static int set_context_dscp_ecn(struct net_context *context,
const void *value, size_t len)
{
#if defined(CONFIG_NET_CONTEXT_DSCP_ECN)
int dscp_ecn = *((int *)value);
if (len != sizeof(int)) {
return -EINVAL;
}
if ((dscp_ecn < 0) || (dscp_ecn > UINT8_MAX)) {
return -EINVAL;
}
context->options.dscp_ecn = (uint8_t)dscp_ecn;
return 0;
#else
return -ENOTSUP;
#endif
}
int net_context_set_option(struct net_context *context,
enum net_context_option option,
const void *value, size_t len)
{
int ret = 0;
NET_ASSERT(context);
if (!PART_OF_ARRAY(contexts, context)) {
return -EINVAL;
}
k_mutex_lock(&context->lock, K_FOREVER);
switch (option) {
case NET_OPT_PRIORITY:
ret = set_context_priority(context, value, len);
break;
case NET_OPT_TXTIME:
ret = set_context_txtime(context, value, len);
break;
case NET_OPT_SOCKS5:
ret = set_context_proxy(context, value, len);
break;
case NET_OPT_RCVTIMEO:
ret = set_context_rcvtimeo(context, value, len);
break;
case NET_OPT_SNDTIMEO:
ret = set_context_sndtimeo(context, value, len);
break;
case NET_OPT_RCVBUF:
ret = set_context_rcvbuf(context, value, len);
break;
case NET_OPT_SNDBUF:
ret = set_context_sndbuf(context, value, len);
break;
case NET_OPT_DSCP_ECN:
ret = set_context_dscp_ecn(context, value, len);
break;
}
k_mutex_unlock(&context->lock);
return ret;
}
int net_context_get_option(struct net_context *context,
enum net_context_option option,
void *value, size_t *len)
{
int ret = 0;
NET_ASSERT(context);
if (!PART_OF_ARRAY(contexts, context)) {
return -EINVAL;
}
k_mutex_lock(&context->lock, K_FOREVER);
switch (option) {
case NET_OPT_PRIORITY:
ret = get_context_priority(context, value, len);
break;
case NET_OPT_TXTIME:
ret = get_context_txtime(context, value, len);
break;
case NET_OPT_SOCKS5:
ret = get_context_proxy(context, value, len);
break;
case NET_OPT_RCVTIMEO:
ret = get_context_rcvtimeo(context, value, len);
break;
case NET_OPT_SNDTIMEO:
ret = get_context_sndtimeo(context, value, len);
break;
case NET_OPT_RCVBUF:
ret = get_context_rcvbuf(context, value, len);
break;
case NET_OPT_SNDBUF:
ret = get_context_sndbuf(context, value, len);
break;
case NET_OPT_DSCP_ECN:
ret = get_context_dscp_ecn(context, value, len);
break;
}
k_mutex_unlock(&context->lock);
return ret;
}
void net_context_foreach(net_context_cb_t cb, void *user_data)
{
int i;
k_sem_take(&contexts_lock, K_FOREVER);
for (i = 0; i < NET_MAX_CONTEXT; i++) {
if (!net_context_is_used(&contexts[i])) {
continue;
}
k_mutex_lock(&contexts[i].lock, K_FOREVER);
cb(&contexts[i], user_data);
k_mutex_unlock(&contexts[i].lock);
}
k_sem_give(&contexts_lock);
}
const char *net_context_state(struct net_context *context)
{
switch (net_context_get_state(context)) {
case NET_CONTEXT_IDLE:
return "IDLE";
case NET_CONTEXT_CONNECTING:
return "CONNECTING";
case NET_CONTEXT_CONNECTED:
return "CONNECTED";
case NET_CONTEXT_LISTENING:
return "LISTENING";
}
return NULL;
}
void net_context_init(void)
{
k_sem_init(&contexts_lock, 1, K_SEM_MAX_LIMIT);
}
| 2.3125 | 2 |
2024-11-18T20:55:36.217785+00:00 | 2020-03-25T14:54:10 | 799d90135210eef19aeb8ab569606c279f84a0e5 | {
"blob_id": "799d90135210eef19aeb8ab569606c279f84a0e5",
"branch_name": "refs/heads/master",
"committer_date": "2020-04-15T20:53:21",
"content_id": "82d0fa48c9716b3d056a14dbc8811452299f4f80",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "9ef9233442de98582e5830ae26c032c510855d27",
"extension": "c",
"filename": "Utilities.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": 14311,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/mu_platform_nxp/Common/MU/MsGraphicsPkg/Library/SimpleUIToolKit/Utilities.c",
"provenance": "stackv2-0092.json.gz:42329",
"repo_name": "nlshipp/WinIoT-Coral-old",
"revision_date": "2020-03-25T14:54:10",
"revision_id": "c61b5ffde30cc1097ffe288ca45f0680e2c61020",
"snapshot_id": "af380bc7cdc0a9e531bd1326b36b15999cf461eb",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/nlshipp/WinIoT-Coral-old/c61b5ffde30cc1097ffe288ca45f0680e2c61020/mu_platform_nxp/Common/MU/MsGraphicsPkg/Library/SimpleUIToolKit/Utilities.c",
"visit_date": "2023-06-03T18:56:43.480583"
} | stackv2 | /** @file
Implements a Simple UI Toolkit utility functions.
Copyright (c) 2015 - 2018, Microsoft 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**/
#include "SimpleUIToolKitInternal.h"
#define MS_DEFAULT_FONT_SIZE MsUiGetStandardFontHeight () // Default font size is 32px high. (TODO - merge with MsDisplayEngine.h copy).
/**
Calculates the bitmap width and height of the specified text string based on the current font size & style.
@param[in] pString The string to measure.
@param[in] FontInfo Font information (defines size, style, etc.).
@param[in] BoundsLimit TRUE == bounding rectangle restriction, FALSE == no restrction (only limit is the total screen size).
@param[in out] Bounds On entry, contains the absolute bounds to be imposed on the string. On exit, contains the actual string bounds.
@param[out] MaxFontGlyphDescent Maximum font glyph descent (pixels) for the selected font.
@retval EFI_SUCCESS The operation completed successfully.
**/
EFI_STATUS
GetTextStringBitmapSize (IN CHAR16 *pString,
IN EFI_FONT_INFO *FontInfo,
IN BOOLEAN BoundsLimit,
IN EFI_HII_OUT_FLAGS HiiFlags,
IN OUT SWM_RECT *Bounds,
OUT UINT32 *MaxFontGlyphDescent)
{
EFI_STATUS Status = EFI_SUCCESS;
EFI_FONT_DISPLAY_INFO *StringInfo = NULL;
EFI_IMAGE_OUTPUT *BltBuffer = NULL;
EFI_HII_ROW_INFO *StringRowInfo = NULL;
UINTN RowInfoSize;
UINT32 RowIndex;
UINT16 Width, Height;
CHAR16 *xString;
// Calculate maximum width and height allowed by the specified bounding rectangle.
//
if (TRUE == BoundsLimit)
{
Width = (UINT16)(Bounds->Right - Bounds->Left + 1);
Height = (UINT16)(Bounds->Bottom - Bounds->Top + 1);
}
else
{
// Caller hasn't provided any boundary to enforce. Assume we have the whole screen.
//
ZeroMem (Bounds, sizeof(SWM_RECT));
Width = (UINT16)mUITGop->Mode->Info->HorizontalResolution;
Height = (UINT16)mUITGop->Mode->Info->VerticalResolution;
}
// Get the current preferred font size and style.
//
StringInfo = BuildFontDisplayInfoFromFontInfo (FontInfo);
if (NULL == StringInfo)
{
Status = EFI_OUT_OF_RESOURCES;
goto Exit;
}
StringInfo->FontInfoMask = EFI_FONT_INFO_ANY_FONT;
// If a null string was provided, return a standard single character-sizes rectangle. Null strings are used for UI padding/alignment.
//
if (NULL == pString || L'\0' == *pString)
{
xString = L" ";
// Bounds->Right = (Bounds->Left + MS_DEFAULT_FONT_SIZE); // Use for both width and height.
// Bounds->Bottom = (Bounds->Top + MS_DEFAULT_FONT_SIZE);
// goto CalcFontDescent;
} else {
xString = pString;
}
// Prepare string blitting buffer.
//
BltBuffer = (EFI_IMAGE_OUTPUT *) AllocatePool (sizeof (EFI_IMAGE_OUTPUT));
ASSERT (NULL != BltBuffer);
if (NULL == BltBuffer)
{
Status = EFI_OUT_OF_RESOURCES;
goto Exit;
}
// Fill out string blit buffer details.
//
BltBuffer->Width = Width;
BltBuffer->Height = Height;
BltBuffer->Image.Bitmap = AllocatePool (Width * Height * sizeof(EFI_GRAPHICS_OUTPUT_BLT_PIXEL));
ASSERT (NULL != BltBuffer->Image.Bitmap);
if (NULL == BltBuffer->Image.Bitmap)
{
Status = EFI_OUT_OF_RESOURCES;
goto Exit;
}
// Send in a NULL pointer so we can receive back width and height results.
//
StringRowInfo = (EFI_HII_ROW_INFO *)NULL;
RowInfoSize = 0;
mUITSWM->StringToWindow (mUITSWM,
mClientImageHandle,
HiiFlags,
xString,
StringInfo,
&BltBuffer,
0,
0,
&StringRowInfo,
&RowInfoSize,
(UINTN *)NULL
);
if (EFI_ERROR(Status))
{
DEBUG ((DEBUG_ERROR, "ERROR [SUIT]: Failed to calculate string bitmap size: %r.\n", Status));
goto Exit;
}
if (NULL == StringRowInfo || 0 == RowInfoSize)
{
goto Exit;
}
// Calculate the bounding rectangle around the text as rendered (note this it may be in multiple rows).
//
for (RowIndex=0, Width=0, Height=0 ; RowIndex < RowInfoSize ; RowIndex++)
{
Width = (UINT16)(Width < (UINT32)StringRowInfo[RowIndex].LineWidth ? (UINT32)StringRowInfo[RowIndex].LineWidth : Width);
Height += (UINT16)StringRowInfo[RowIndex].LineHeight;
}
// Adjust the caller's right and bottom bounding box limits based on the results.
//
Bounds->Right = (Bounds->Left + Width - 1);
Bounds->Bottom = (Bounds->Top + Height - 1);
DEBUG ((DEBUG_VERBOSE, "INFO [SUIT]: Calculated string bitmap size (Actual=L%d,R%d,T%d,B%d MaxWidth=%d MaxHeight=%d TextRows=%d).\n", Bounds->Left, Bounds->Right, Bounds->Top, Bounds->Bottom, Width, Height, RowInfoSize));
//CalcFontDescent:
// Determine the maximum font descent value from the font selected.
// TODO - Need a better way to determine this. Currently hard-coded based on knowledge of the custom registered fonts in the Simple Window Manager driver.
//
// if (StringInfo.FontInfo.FontSize == MsUiGetFixedFontHeight ()) {
*MaxFontGlyphDescent = 0;
// } else {
// *MaxFontGlyphDescent = (StringInfo.FontInfo.FontSize * 20) / 100;
// }
Exit:
// Free the buffers.
//
if (NULL != BltBuffer && NULL != BltBuffer->Image.Bitmap)
{
FreePool(BltBuffer->Image.Bitmap);
}
if (NULL != BltBuffer)
{
FreePool(BltBuffer);
}
if (NULL != StringRowInfo)
{
FreePool(StringRowInfo);
}
if (NULL != StringInfo)
{
FreePool (StringInfo);
}
return Status;
}
// Given two canvas, find the "control" that is in "this" list, and return the eqivalent control
// from "prev" list.
UIT_CANVAS_CHILD_CONTROL *
EFIAPI
GetEquivalentControl (IN UIT_CANVAS_CHILD_CONTROL *Control,
IN Canvas *src, // Canvas that has the source Control
IN Canvas *tgt) { // Canvas that has the target control
UIT_CANVAS_CHILD_CONTROL *pSrcChildControl = src->m_pControls;
UIT_CANVAS_CHILD_CONTROL *pTgtChildControl = tgt->m_pControls;
ControlBase *pSrcControlBase;
ControlBase *pTgtControlBase;
if (Control == NULL) {
return NULL;
}
while (pSrcChildControl != NULL) {
if (pTgtChildControl == NULL) {
DEBUG((DEBUG_ERROR, "%a control mismatch - Tgt = NULL\n", __FUNCTION__));
return NULL;
}
pSrcControlBase = (ControlBase *) pSrcChildControl->pControl;
pTgtControlBase = (ControlBase *) pTgtChildControl->pControl;
if (pSrcControlBase->ControlType != pTgtControlBase->ControlType) {
DEBUG((DEBUG_ERROR, "%a control mismatch. Src=%d, Tgt=%d\n",__FUNCTION__, pSrcControlBase->ControlType, pTgtControlBase->ControlType));
return NULL;
}
if (pSrcChildControl == Control) {
return pTgtChildControl;
}
pSrcChildControl = pSrcChildControl->pNext;
pTgtChildControl = pTgtChildControl->pNext;
}
if (pTgtChildControl != NULL) {
DEBUG((DEBUG_ERROR, "%a control mismatch - Srct = NULL\n", __FUNCTION__));
}
return NULL;
}
/**
Draws a rectangular outline to the screen at location and in the size, line width, and color specified.
@param[in] X Line X-coordinate starting position within Bitmap.
@param[in] Y Line Y-coordinate starting position within Bitmap.
@param[in] NumberOfPixels Number of pixels making up the line, extending from (X,Y) to the right.
@param[in] Color Line color.
@param[out] Bitmap Bitmap buffer that will be draw into.
@retval EFI_SUCCESS
**/
EFI_STATUS
EFIAPI
DrawRectangleOutline (IN UINT32 OrigX,
IN UINT32 OrigY,
IN UINT32 Width,
IN UINT32 Height,
IN UINT32 LineWidth,
IN EFI_GRAPHICS_OUTPUT_BLT_PIXEL *Color)
{
EFI_STATUS Status = EFI_SUCCESS;
if (NULL == mUITGop || NULL == Color)
{
Status = EFI_INVALID_PARAMETER;
goto Exit;
}
// For performance (and visual) reasons, it's better to render four individual "line" blits rather than a solid rectangle fill.
//
mUITSWM->BltWindow (mUITSWM,
mClientImageHandle,
Color,
EfiBltVideoFill,
0,
0,
OrigX,
OrigY,
Width,
LineWidth,
0
);
mUITSWM->BltWindow (mUITSWM,
mClientImageHandle,
Color,
EfiBltVideoFill,
0,
0,
OrigX,
(OrigY + Height - LineWidth),
Width,
LineWidth,
0
);
mUITSWM->BltWindow (mUITSWM,
mClientImageHandle,
Color,
EfiBltVideoFill,
0,
0,
OrigX,
OrigY,
LineWidth,
Height,
0
);
mUITSWM->BltWindow (mUITSWM,
mClientImageHandle,
Color,
EfiBltVideoFill,
0,
0,
(OrigX + Width - LineWidth),
OrigY,
LineWidth,
Height,
0
);
Exit:
return Status;
}
/**
Returns a copy of the FONT_INFO structure.
@param[in] FontInfo Pointer to callers FONT_INFO.
@retval NewFontInfo Copy of FONT_INFO. Caller must free.
NULL No memory resources available
**/
EFI_FONT_INFO *
EFIAPI
DupFontInfo (IN EFI_FONT_INFO *FontInfo)
{
EFI_FONT_INFO *NewFontInfo;
UINTN FontNameSize;
if (NULL == FontInfo) {
FontNameSize = 0;
} else {
FontNameSize = StrnLenS (FontInfo->FontName, MAX_FONT_NAME_SIZE) * sizeof(FontInfo->FontName[0]);
if (FontNameSize > MAX_FONT_NAME_SIZE) {
FontNameSize = 0;
}
}
NewFontInfo = AllocatePool (sizeof (EFI_FONT_INFO) + FontNameSize);
CopyMem (NewFontInfo, FontInfo, sizeof (EFI_FONT_INFO) + FontNameSize);
if (FontNameSize <= sizeof(FontInfo->FontName[0])) {
NewFontInfo->FontName[0] = '\0';
}
return NewFontInfo;
}
/**
Returns a new FontDisplayInfo populated with callers FontInfo.
@param[in] FontInfo Pointer to callers FONT_INFO.
@retval NewFontDisplayInfo New FontDisplayIfo with font from FontInfo
Caller must free.
NULL No Resources available
**/
EFI_FONT_DISPLAY_INFO *
EFIAPI
BuildFontDisplayInfoFromFontInfo (IN EFI_FONT_INFO *FontInfo)
{
EFI_FONT_DISPLAY_INFO *NewFontDisplayInfo;
UINTN FontNameSize;
if (NULL == FontInfo) {
FontNameSize = 0;
} else {
FontNameSize = StrnLenS (FontInfo->FontName, MAX_FONT_NAME_SIZE) * sizeof(FontInfo->FontName[0]);
if (FontNameSize > MAX_FONT_NAME_SIZE) {
FontNameSize = 0;
}
}
NewFontDisplayInfo = AllocateZeroPool (sizeof (EFI_FONT_DISPLAY_INFO) + FontNameSize);
if (NULL != NewFontDisplayInfo) {
CopyMem (&NewFontDisplayInfo->FontInfo, FontInfo, sizeof (EFI_FONT_INFO) + FontNameSize);
if (FontNameSize <= sizeof(FontInfo->FontName[0])) {
NewFontDisplayInfo->FontInfo.FontName[0] = L'\0';
}
}
return NewFontDisplayInfo;
} | 2.328125 | 2 |
2024-11-18T20:55:36.436123+00:00 | 2012-04-26T08:19:12 | 64fe8883e7f7e018b922892172bee22bbeaf9985 | {
"blob_id": "64fe8883e7f7e018b922892172bee22bbeaf9985",
"branch_name": "refs/heads/master",
"committer_date": "2012-04-26T08:19:12",
"content_id": "63018346f6794d6e441b3e3d7770798a4d5cef99",
"detected_licenses": [
"MIT"
],
"directory_id": "9357bed2ab063ec0d62774a22112bec3dd655ffd",
"extension": "h",
"filename": "HighScoreManager.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": 1334,
"license": "MIT",
"license_type": "permissive",
"path": "/source/HighScoreManager.h",
"provenance": "stackv2-0092.json.gz:42586",
"repo_name": "taparkins/Galaxulon",
"revision_date": "2012-04-26T08:19:12",
"revision_id": "6613e92861799eb16db42cb9cdc8f88179841c19",
"snapshot_id": "25cfb8a277f61dc128f87959b386565a7c09707d",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/taparkins/Galaxulon/6613e92861799eb16db42cb9cdc8f88179841c19/source/HighScoreManager.h",
"visit_date": "2023-03-20T20:17:38.883400"
} | stackv2 | // HighScoreManager.h
//
// Authors: Aric Parkinson, Spencer Phippen
// Date created: April 13, 2012
//
// Contains declarations of high score-related functions
#ifndef HIGHSCOREMANAGER_H
#define HIGHSCOREMANAGER_H
// Returns the Nth high score (ie, 0 is highest, 1 is next highest, and so on).
// Fills playerName with the null-terminated 3-character initials of the player
// associated with that score. Expects playerName to have size 4.
//
// If scoreN > 9, program fails (high scores saved to top 10)
int getNthHighScore(int scoreN, char* playerName);
// Initializes SRAM if it hasn't been done already. Call before reading or
// writing high scores.
void initSRAM();
// Initializes SRAM with easy scores to beat - used for debugging purposes
void initSRAM_easy();
// Saves the Nth high score for future access. Expects playerName to be 3
// characters.
//
// If scoreN > 9, program fails (high scores saved up to top 10)
void saveNthHighScore(int score, const char* playerName, int scoreN);
// Takes the provided high score, and inserts it into place N. It assumes that
// the score given is actually supposed to go in that slot. Other players in
// the list are shifted down - excluding the score SPH -- 2 Points.
void newHighScore(int score, const char* playerName, int scoreN);
#endif
| 2.34375 | 2 |
2024-11-18T20:55:36.695382+00:00 | 2022-07-28T18:42:05 | 83e7820f80d8fdb09ec796f2cdd15606b6b4f5e2 | {
"blob_id": "83e7820f80d8fdb09ec796f2cdd15606b6b4f5e2",
"branch_name": "refs/heads/master",
"committer_date": "2022-07-28T18:42:05",
"content_id": "cecd15d6791d076c2578e06a0cf823fd73f3ec5f",
"detected_licenses": [
"MIT"
],
"directory_id": "18e9c7d661584e1c7698670d60e0588ef353ebe1",
"extension": "c",
"filename": "by_get.c",
"fork_events_count": 0,
"gha_created_at": "2020-02-13T17:42:36",
"gha_event_created_at": "2020-03-13T10:46:13",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 240323111,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 978,
"license": "MIT",
"license_type": "permissive",
"path": "/pkg/urbit/jets/d/by_get.c",
"provenance": "stackv2-0092.json.gz:42845",
"repo_name": "botter-nidnul/urbit",
"revision_date": "2022-07-28T18:42:05",
"revision_id": "04645cbf08e2fb592975606adae3a20a2caf11bc",
"snapshot_id": "0b1ec5d7e67be473dfd8ddde176d5b421e177be7",
"src_encoding": "UTF-8",
"star_events_count": 9,
"url": "https://raw.githubusercontent.com/botter-nidnul/urbit/04645cbf08e2fb592975606adae3a20a2caf11bc/pkg/urbit/jets/d/by_get.c",
"visit_date": "2022-08-17T05:45:58.196564"
} | stackv2 | /* j/4/by_get.c
**
*/
#include "all.h"
/* functions
*/
u3_noun
u3qdb_get(u3_noun a,
u3_noun b)
{
if ( u3_nul == a ) {
return u3_nul;
}
else {
u3_noun n_a, lr_a;
u3_noun pn_a, qn_a;
u3x_cell(a, &n_a, &lr_a);
u3x_cell(n_a, &pn_a, &qn_a);
if ( (c3y == u3r_sing(b, pn_a)) ) {
return u3nc(u3_nul, u3k(qn_a));
}
else {
return ( c3y == u3qc_gor(b, pn_a) ) ? u3qdb_get(u3h(lr_a), b)
: u3qdb_get(u3t(lr_a), b);
}
}
}
u3_noun
u3wdb_get(u3_noun cor)
{
u3_noun a, b;
u3x_mean(cor, u3x_sam, &b, u3x_con_sam, &a, 0);
return u3qdb_get(a, b);
}
u3_weak
u3kdb_get(u3_noun a,
u3_noun b)
{
u3_noun c = u3qdb_get(a, b);
u3z(a); u3z(b);
if ( c3n == u3r_du(c) ) {
u3z(c);
return u3_none;
}
else {
u3_noun pro = u3k(u3t(c));
u3z(c);
return pro;
}
}
u3_noun
u3kdb_got(u3_noun a,
u3_noun b)
{
return u3x_good(u3kdb_get(a, b));
}
| 2 | 2 |
2024-11-18T20:55:36.858932+00:00 | 2017-12-16T15:25:35 | deb9e6cdc5e52d3ed211701f29610f7e996b870c | {
"blob_id": "deb9e6cdc5e52d3ed211701f29610f7e996b870c",
"branch_name": "refs/heads/master",
"committer_date": "2017-12-16T15:25:35",
"content_id": "ce257d35e65a1caa1efb8d899de3dd53335e5311",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "15acac13dd6399435801a90dc1b3720b92f186c6",
"extension": "c",
"filename": "box-test.c",
"fork_events_count": 0,
"gha_created_at": "2014-03-12T03:29:30",
"gha_event_created_at": "2017-12-16T15:25:36",
"gha_language": "C",
"gha_license_id": null,
"github_id": 17654186,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 333,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/adt/box-test.c",
"provenance": "stackv2-0092.json.gz:42973",
"repo_name": "nablang/nablang",
"revision_date": "2017-12-16T15:25:35",
"revision_id": "bc8e245902d6854153b0516df3021a5124f32a8e",
"snapshot_id": "84d4db34108c02ce615a517bd3dfb4dcc0542837",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/nablang/nablang/bc8e245902d6854153b0516df3021a5124f32a8e/adt/box-test.c",
"visit_date": "2021-08-30T06:59:23.757856"
} | stackv2 | #include "box.h"
#include <ccut.h>
void box_suite() {
ccut_test("box test") {
val_begin_check_memory();
Val box = nb_box_new(3);
assert_eq(true, nb_val_is_box(box));
assert_eq(3, nb_box_get(box));
nb_box_set(box, 4);
assert_eq(4, nb_box_get(box));
nb_box_delete(box);
val_end_check_memory();
}
}
| 2.140625 | 2 |
2024-11-18T20:55:36.988854+00:00 | 2023-07-31T07:24:56 | 03fe48978c42fa3ed17753415f4113dba5f702b7 | {
"blob_id": "03fe48978c42fa3ed17753415f4113dba5f702b7",
"branch_name": "refs/heads/master",
"committer_date": "2023-07-31T07:24:56",
"content_id": "fe00d92fb5840fba33b82788a976ced8867de568",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "d77abc372ef9104cb1db80347523713c75c6b194",
"extension": "c",
"filename": "vector_parser.c",
"fork_events_count": 11,
"gha_created_at": "2018-09-07T07:42:26",
"gha_event_created_at": "2019-12-23T08:52:55",
"gha_language": "C",
"gha_license_id": null,
"github_id": 147788989,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4996,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/SampleCode/StdDriver/CRYPTO_SHA/vector_parser.c",
"provenance": "stackv2-0092.json.gz:43231",
"repo_name": "OpenNuvoton/M2351BSP",
"revision_date": "2023-07-31T07:24:56",
"revision_id": "ed73bdd5bac5de58faa1c9b799665a734f168a6a",
"snapshot_id": "0a8f86be7b333938a53f7d07841bca616f02df33",
"src_encoding": "UTF-8",
"star_events_count": 17,
"url": "https://raw.githubusercontent.com/OpenNuvoton/M2351BSP/ed73bdd5bac5de58faa1c9b799665a734f168a6a/SampleCode/StdDriver/CRYPTO_SHA/vector_parser.c",
"visit_date": "2023-08-08T22:10:13.183590"
} | stackv2 | /**************************************************************************//**
* @file vector_parser.c
* @version V1.00
* @brief CRYPTO SHA test vector parser
*
* @note
* Copyright (C) 2016 M2351 Nuvoton Technology Corp. All rights reserved.
*****************************************************************************/
#include <stdio.h>
#include <string.h>
#include "NuMicro.h"
#include "vector_parser.h"
extern uint32_t g_u32VectorDataBase, g_u32VectorDataLimit;
static uint8_t *g_pu8FileBase;
static uint32_t g_u32FileIdx, g_u32FileSize;
static char g_pi8LineBuff[20 * 1024];
#ifdef __ICCARM__
#pragma data_alignment=32
uint8_t s_au8ShaDataPool[8192] ;
#else
static __attribute__((aligned(32))) uint8_t s_au8ShaDataPool[8192] ;
#endif
uint8_t *g_au8ShaData;
uint8_t g_au8ShaDigest[64];
int32_t g_i32DataLen;
void OpenTestVector(void);
int32_t GetLine(void);
int32_t IsHexChar(char c);
uint8_t char_to_hex(uint8_t c);
int32_t Str2Hex(uint8_t *str, uint8_t *hex, int swap);
int32_t Str2Dec(uint8_t *str);
int GetNextPattern(void);
void OpenTestVector(void)
{
/* Get test vector base */
g_pu8FileBase = (uint8_t *)&g_u32VectorDataBase;
#ifdef __ICCARM__
g_u32FileSize = 0x213f;
#else
/* Get vector size */
g_u32FileSize = (uint32_t)&g_u32VectorDataLimit - (uint32_t)&g_u32VectorDataBase;
#endif
g_u32FileIdx = 0;
}
static int32_t ReadFile(uint8_t *pu8Buff, int i32Len)
{
if(g_u32FileIdx + 1 >= g_u32FileSize)
return -1;
memcpy(pu8Buff, &g_pu8FileBase[g_u32FileIdx], (uint32_t)i32Len);
g_u32FileIdx += (uint32_t)i32Len;
return 0;
}
int32_t GetLine(void)
{
int i;
uint8_t ch;
if(g_u32FileIdx + 1 >= g_u32FileSize)
{
return -1;
}
memset(g_pi8LineBuff, 0, sizeof(g_pi8LineBuff));
for(i = 0; ; i++)
{
if(ReadFile(&ch, 1) < 0)
return 0;
if((ch == 0x0D) || (ch == 0x0A))
break;
g_pi8LineBuff[i] = ch;
}
while(1)
{
if(ReadFile(&ch, 1) < 0)
return 0;
if((ch != 0x0D) && (ch != 0x0A))
break;
}
g_u32FileIdx--;
return 0;
}
int32_t IsHexChar(char c)
{
if((c >= '0') && (c <= '9'))
return 1;
if((c >= 'a') && (c <= 'f'))
return 1;
if((c >= 'A') && (c <= 'F'))
return 1;
return 0;
}
uint8_t char_to_hex(uint8_t c)
{
if((c >= '0') && (c <= '9'))
return c - '0';
if((c >= 'a') && (c <= 'f'))
return c - 'a' + 10;
if((c >= 'A') && (c <= 'F'))
return c - 'A' + 10;
return 0;
}
int32_t Str2Hex(uint8_t *str, uint8_t *hex, int swap)
{
int i, count = 0, actual_len;
uint8_t val8;
while(*str)
{
if(!IsHexChar(*str))
{
return count;
}
val8 = char_to_hex(*str);
str++;
if(!IsHexChar(*str))
{
return count;
}
val8 = (uint8_t)((val8 << 4) | char_to_hex(*str));
str++;
hex[count] = val8;
count++;
}
actual_len = count;
for(; count % 4 ; count++)
hex[count] = 0;
if(!swap)
return actual_len;
// SWAP
for(i = 0; i < count; i += 4)
{
val8 = hex[i];
hex[i] = hex[i + 3];
hex[i + 3] = val8;
val8 = hex[i + 1];
hex[i + 1] = hex[i + 2];
hex[i + 2] = val8;
}
return actual_len;
}
int32_t Str2Dec(uint8_t *str)
{
int val32;
val32 = 0;
while(*str)
{
if((*str < '0') || (*str > '9'))
{
return val32;
}
val32 = (val32 * 10) + (*str - '0');
str++;
}
return val32;
}
int GetNextPattern(void)
{
int32_t line_num = 1;
uint8_t *p;
g_au8ShaData = (uint8_t *)s_au8ShaDataPool;
while(GetLine() == 0)
{
line_num++;
if(g_pi8LineBuff[0] == '#')
continue;
/* Get Length */
if(strncmp(g_pi8LineBuff, "Len", 3) == 0)
{
p = (uint8_t *)&g_pi8LineBuff[3];
while((*p < '0') || (*p > '9'))
p++;
g_i32DataLen = Str2Dec(p);
continue;
}
/* Get Msg data */
if(strncmp(g_pi8LineBuff, "Msg", 3) == 0)
{
p = (uint8_t *)&g_pi8LineBuff[3];
while(!IsHexChar(*p)) p++;
Str2Hex(p, &g_au8ShaData[0], 0);
continue;
}
/* Get golden result */
if(strncmp(g_pi8LineBuff, "MD", 2) == 0)
{
p = (uint8_t *)&g_pi8LineBuff[2];
while(!IsHexChar(*p)) p++;
Str2Hex(p, &g_au8ShaDigest[0], 1);
return 0;
}
}
return -1;
}
| 2.390625 | 2 |
2024-11-18T20:55:37.049768+00:00 | 2023-04-12T02:26:11 | 8e3eff40ea004d0e39fef4573859aab27ff40d08 | {
"blob_id": "8e3eff40ea004d0e39fef4573859aab27ff40d08",
"branch_name": "refs/heads/master",
"committer_date": "2023-04-12T02:26:11",
"content_id": "07911e0c366ccccd84f3b5c0f64cfad74a43c0fc",
"detected_licenses": [
"MIT"
],
"directory_id": "5ade2a129f55f5d871b9b14846d3126e9c6d2abc",
"extension": "c",
"filename": "ppWrite.c",
"fork_events_count": 126,
"gha_created_at": "2015-03-27T08:22:15",
"gha_event_created_at": "2023-04-12T02:26:13",
"gha_language": "MATLAB",
"gha_license_id": null,
"github_id": 32975069,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4149,
"license": "MIT",
"license_type": "permissive",
"path": "/BMI_modules/Online/parallelPort/ppWrite.c",
"provenance": "stackv2-0092.json.gz:43360",
"repo_name": "PatternRecognition/OpenBMI",
"revision_date": "2023-04-12T02:26:11",
"revision_id": "c0e56825366681ae576801af08eb5fe326a5afd8",
"snapshot_id": "b29970689de163315b6851e941eff6c237877de8",
"src_encoding": "UTF-8",
"star_events_count": 241,
"url": "https://raw.githubusercontent.com/PatternRecognition/OpenBMI/c0e56825366681ae576801af08eb5fe326a5afd8/BMI_modules/Online/parallelPort/ppWrite.c",
"visit_date": "2023-05-02T17:55:20.258316"
} | stackv2 | #include "mex.h"
#include <conio.h>
#include "ioPort.c"
#define pAddr prhs[0]
#define pData prhs[1]
#define pSleepTime prhs[2]
#define pDelayTime prhs[3]
/* ppWrite(IO_ADDR, Value) or ppWrite(IO_ADDR, Value, SleepTime) is used
to send a trigger value to the parallel port that has
approx. 10 milliseconds duration, maybe a bit longer. Before and after this interval,
the parallel port has to be set back to the value of 0.
ppWrite is usually called by a feedback routine during an BCI experiment.
Parallel port values are to be read by e.g. BrainVision Recorder.
As other triggers can be send during the 10ms interval, ppWrite has to check the
current value on the parallel port at the end of the 10ms before sending a value of 0.
This can unfortunately NOT be done by query to the parallel port directly (as
the parallel port ist full duplex), but only by storing the value in a static variable
called "portvalue".
ppWrite uses now the file ioPort.c for the io functionality. In ioPort
the parallel port is accesed in windows nt save way.
If you have problems with the parallelport see ioPort.c.
ToDo: Prevent funny things happening by securing a mutex lock to the access of the
static "portvalue".
Benjamin, Michael and Mikio 27.10.2006
edit Max Sagebaum 02.11.2007 Added nt save io functions
edit Max Sagebaum 16.05.2008 Enabled user to set the sleep time
edit Max Sagebaum 16.11.2011 Enabled user to set a delay
*/
typedef unsigned short ioaddr_t;
typedef unsigned char portvalue_t;
struct threadparams {
ioaddr_t portaddr;
portvalue_t sendvalue;
int sleepTime;
int delayTime;
HINSTANCE hLib;
};
static portvalue_t currentvalue = 0;
/* Thread that sets signal on parallel port to zero after 10 ms of sleeping */
DWORD WINAPI ThreadFunc( LPVOID lpParam )
{
int sleepTime;
int delayTime;
struct threadparams *p = lpParam;
ioaddr_t portaddr = p->portaddr;
portvalue_t sendvalue = p->sendvalue;
sleepTime = p->sleepTime;
delayTime = p->delayTime;
if(0 != delayTime) {
/* send a value to the parallel prot after the delay time. */
Sleep(delayTime);
Out32(portaddr,sendvalue);
currentvalue = sendvalue;
}
/* after sleeping 10msec: check, if the parallel port still shows the sent value
by checking the static "currentvalue".
If it does, set parallel port back to zero.
If it does not, hands off! ( it probably means that some other process has sent
a trigger to the parallel port in the meantime)
*/
Sleep(sleepTime);
/* ToDo: put mutex lock around the following three lines */
if (currentvalue == sendvalue) {
Out32(portaddr, 0);
currentvalue = 0;
}
else {
//mexPrintf("ppWrite: trigger overlap on parport detected.\n");
}
deleteLibrary(p->hLib);
free(p);
return 0;
}
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
struct threadparams *p;
if (nrhs < 2 && nrhs > 4)
mexErrMsgTxt("Two or three or four input arguments required");
if (nlhs>0)
mexErrMsgTxt("No output argument allowed");
p = malloc(sizeof(*p));
p->hLib = createLibrary();
/* get parameters from mex format and store into struct p */
p->portaddr= (unsigned short)*mxGetPr(pAddr);
p->sendvalue= (unsigned char)*mxGetPr(pData);
if(nrhs >= 3) {
p->sleepTime = (int)mxGetScalar(pSleepTime);
} else {
p->sleepTime = 10;
}
if(nrhs >= 4) {
p->delayTime = (int)mxGetScalar(pDelayTime);
} else {
p->delayTime = 0;
}
/* mexPrintf("Intent to write %d, current value is %d\n", p->sendvalue, currentvalue); */
/* ToDo: Put mutex lock around the following two lines */
/* Only set the value if the delay is zero, otherwise the thread will set the value */
if( 0 == p->delayTime) {
Out32(p->portaddr, p->sendvalue);
currentvalue = p->sendvalue;
}
/* mexPrintf("Wrote %d\n", p->sendvalue); */
/* Start thread that resets parport value to zero in 10ms */
CreateThread( NULL, 0, &ThreadFunc, (LPVOID) p, 0, 0);
}
| 2.515625 | 3 |
2024-11-18T20:55:37.424510+00:00 | 2021-09-08T06:12:40 | 1e9326abe3a31be974b06ab347b9d6912a9a3021 | {
"blob_id": "1e9326abe3a31be974b06ab347b9d6912a9a3021",
"branch_name": "refs/heads/main",
"committer_date": "2021-09-08T06:12:40",
"content_id": "4699d67e2ad519c050137885bb94dc8858a40deb",
"detected_licenses": [
"MIT"
],
"directory_id": "f726316bedf3cd02fa4ee66a92579f5fdea3ea4c",
"extension": "c",
"filename": "wait_example2.c",
"fork_events_count": 0,
"gha_created_at": "2021-09-08T04:44:22",
"gha_event_created_at": "2021-09-08T06:12:41",
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 404213459,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 994,
"license": "MIT",
"license_type": "permissive",
"path": "/forkwait/wait_example2.c",
"provenance": "stackv2-0092.json.gz:43489",
"repo_name": "amitsagargowda/Advanced-C-1",
"revision_date": "2021-09-08T06:12:40",
"revision_id": "3cb056e96afd167444fdd118e5087a322d502048",
"snapshot_id": "2fc7e3f92215f2a866916b9e1b6b2097b41049f9",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/amitsagargowda/Advanced-C-1/3cb056e96afd167444fdd118e5087a322d502048/forkwait/wait_example2.c",
"visit_date": "2023-08-01T08:12:08.803299"
} | stackv2 | /* This is another example of wait()
* Initially fork() > 0, so first "Hello from parent" is printed and fork() becomes zero and
* "Hello from child" is printed.
* wait(NULL) will block parent process until any of its children has finished.
* If child terminates before parent process reaches wait(NULL) then
* the child process turns to a zombie process until its parent waits on it and its released from memory.
*
* Email : abinashprabakaran@gmail.com
* Date : 31.08.2021
* Author : Abinash
*/
#include<stdio.h> /* required for printf */
#include<sys/wait.h> /* required for wait */
#include<unistd.h> /* required for fork */
/*main program */
int main()
{
if(fork()==0) /* child process */
printf("Hello from child\n");
else /* parent process */
{
printf("hello from parent\n");
wait(NULL); /* block parent process until any of its children has finished. */
printf("child has terminated\n");
}
printf("Bye\n");
return 0; /* program exited successfully */
}
| 3.671875 | 4 |
2024-11-18T20:55:37.528645+00:00 | 2021-11-09T08:13:13 | c2283e0a7182d93c24ca929c8b7e95b129d084ae | {
"blob_id": "c2283e0a7182d93c24ca929c8b7e95b129d084ae",
"branch_name": "refs/heads/master",
"committer_date": "2021-11-09T08:13:13",
"content_id": "311f9aebd622204ab8d093efbb664d0de5bf840a",
"detected_licenses": [
"MIT"
],
"directory_id": "089b21148cc7a44c004c976fbe09e34cdd7022c4",
"extension": "c",
"filename": "bmp.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 325695895,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2709,
"license": "MIT",
"license_type": "permissive",
"path": "/srcs/utils/bmp.c",
"provenance": "stackv2-0092.json.gz:43618",
"repo_name": "tkomatsu/miniRayTracer",
"revision_date": "2021-11-09T08:13:13",
"revision_id": "ce46c44a5c5da96810946ce3768fb805ae1fce3d",
"snapshot_id": "2aeda3d883880acd3ebcfb39e84379f34f084ea6",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/tkomatsu/miniRayTracer/ce46c44a5c5da96810946ce3768fb805ae1fce3d/srcs/utils/bmp.c",
"visit_date": "2023-09-05T22:14:00.245888"
} | stackv2 | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* bmp.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: tkomatsu <tkomatsu@student.42tokyo.jp> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/12/19 17:14:44 by tkomatsu #+# #+# */
/* Updated: 2020/12/28 18:36:47 by tkomatsu ### ########.fr */
/* */
/* ************************************************************************** */
#include "minirt.h"
void set_bmpheader(t_mlx mlx, t_fileheader *header, t_dibheader *dib)
{
header->file_type[0] = 0x42;
header->file_type[1] = 0x4D;
header->file_size = ((int)mlx.rx * (int)mlx.ry * 4) + 54;
header->reserved = 0x00000000;
header->pixel_data_offset = 0x36;
dib->header_size = 40;
dib->image_width = (int)mlx.rx;
dib->image_height = -1 * (int)mlx.ry;
dib->planes = 1;
dib->bit_per_pixel = 32;
dib->compression = 0;
dib->image_size = (int)mlx.rx * (int)mlx.ry * 4;
dib->x_pixels_per_meter = 2835;
dib->y_pixels_per_meter = 2835;
dib->total_colors = 0;
dib->important_colors = 0;
}
void write_bmpheader(int fd, t_fileheader header, t_dibheader dib)
{
write(fd, &header.file_type, 2);
write(fd, &header.file_size, 4);
write(fd, &header.reserved, 4);
write(fd, &header.pixel_data_offset, 4);
write(fd, &dib.header_size, 4);
write(fd, &dib.image_width, 4);
write(fd, &dib.image_height, 4);
write(fd, &dib.planes, 2);
write(fd, &dib.bit_per_pixel, 2);
write(fd, &dib.compression, 4);
write(fd, &dib.image_size, 4);
write(fd, &dib.x_pixels_per_meter, 4);
write(fd, &dib.y_pixels_per_meter, 4);
write(fd, &dib.total_colors, 4);
write(fd, &dib.important_colors, 4);
}
void write_bmpdata(int fd, t_mlx mlx, t_camera camera)
{
unsigned char *pixel_array;
int image_size;
int i;
int j;
image_size = (int)mlx.rx * (int)mlx.ry * 4;
if (!(pixel_array = ft_calloc(sizeof(unsigned char), image_size)))
return ;
i = 0;
j = 0;
while (j < image_size)
{
if (i % (camera.line_length / 4) < (int)mlx.rx)
{
pixel_array[j++] = camera.addr[i] & 255;
pixel_array[j++] = (camera.addr[i] & 255 << 8) >> 8;
pixel_array[j++] = (camera.addr[i] & 255 << 16) >> 16;
pixel_array[j++] = 0;
}
i++;
}
write(fd, pixel_array, image_size);
ft_free(pixel_array);
}
| 2.328125 | 2 |
2024-11-18T20:55:37.605772+00:00 | 2023-08-22T20:22:40 | 2cd9caf596898f61212199c52bede31f591a64f7 | {
"blob_id": "2cd9caf596898f61212199c52bede31f591a64f7",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-22T20:22:40",
"content_id": "f1565ad77db0e121e146fc74d3cc11878d128cb1",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "a5a99f646e371b45974a6fb6ccc06b0a674818f2",
"extension": "c",
"filename": "scimark2.c",
"fork_events_count": 3696,
"gha_created_at": "2013-06-26T14:09:07",
"gha_event_created_at": "2023-09-14T19:14:28",
"gha_language": "C++",
"gha_license_id": "Apache-2.0",
"github_id": 10969551,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2362,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/Validation/Performance/bin/scimark2.c",
"provenance": "stackv2-0092.json.gz:43749",
"repo_name": "cms-sw/cmssw",
"revision_date": "2023-08-22T20:22:40",
"revision_id": "19c178740257eb48367778593da55dcad08b7a4f",
"snapshot_id": "4ecd2c1105d59c66d385551230542c6615b9ab58",
"src_encoding": "UTF-8",
"star_events_count": 1006,
"url": "https://raw.githubusercontent.com/cms-sw/cmssw/19c178740257eb48367778593da55dcad08b7a4f/Validation/Performance/bin/scimark2.c",
"visit_date": "2023-08-23T21:57:42.491143"
} | stackv2 | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "Random.h"
#include "kernel.h"
#include "constants.h"
void print_banner(void);
int main(int argc, char *argv[]) {
/* default to the (small) cache-contained version */
double min_time = RESOLUTION_DEFAULT;
int FFT_size = FFT_SIZE;
int SOR_size = SOR_SIZE;
int Sparse_size_M = SPARSE_SIZE_M;
int Sparse_size_nz = SPARSE_SIZE_nz;
int LU_size = LU_SIZE;
/* run the benchmark */
double res[6] = {0.0};
Random R = new_Random_seed(RANDOM_SEED);
if (argc > 1) {
int current_arg = 1;
if (strcmp(argv[1], "-help") == 0 || strcmp(argv[1], "-h") == 0) {
fprintf(stderr, "Usage: [-large] [minimum_time]\n");
exit(0);
}
if (strcmp(argv[1], "-large") == 0) {
FFT_size = LG_FFT_SIZE;
SOR_size = LG_SOR_SIZE;
Sparse_size_M = LG_SPARSE_SIZE_M;
Sparse_size_nz = LG_SPARSE_SIZE_nz;
LU_size = LG_LU_SIZE;
current_arg++;
}
if (current_arg < argc) {
min_time = atof(argv[current_arg]);
}
}
print_banner();
printf("Using %10.2f seconds min time per kenel.\n", min_time);
res[1] = kernel_measureFFT(FFT_size, min_time, R);
res[2] = kernel_measureSOR(SOR_size, min_time, R);
res[3] = kernel_measureMonteCarlo(min_time, R);
res[4] = kernel_measureSparseMatMult(Sparse_size_M, Sparse_size_nz, min_time, R);
res[5] = kernel_measureLU(LU_size, min_time, R);
res[0] = (res[1] + res[2] + res[3] + res[4] + res[5]) / 5;
/* print out results */
printf("Composite Score: %8.2f\n", res[0]);
printf("FFT Mflops: %8.2f (N=%d)\n", res[1], FFT_size);
printf("SOR Mflops: %8.2f (%d x %d)\n", res[2], SOR_size, SOR_size);
printf("MonteCarlo: Mflops: %8.2f\n", res[3]);
printf("Sparse matmult Mflops: %8.2f (N=%d, nz=%d)\n", res[4], Sparse_size_M, Sparse_size_nz);
printf("LU Mflops: %8.2f (M=%d, N=%d)\n", res[5], LU_size, LU_size);
Random_delete(R);
return 0;
}
void print_banner() {
printf("** **\n");
printf("** SciMark2 Numeric Benchmark, see http://math.nist.gov/scimark **\n");
printf("** for details. (Results can be submitted to pozo@nist.gov) **\n");
printf("** **\n");
}
| 2.640625 | 3 |
2024-11-18T20:55:37.696466+00:00 | 2009-08-22T20:14:16 | 3e3f0ef058e458fe4c178f6efcdc7a5206d9aecf | {
"blob_id": "3e3f0ef058e458fe4c178f6efcdc7a5206d9aecf",
"branch_name": "refs/heads/master",
"committer_date": "2009-08-22T20:14:16",
"content_id": "36b4b5c802d71baeaf287e05a95137ff38d86046",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "7a1c1b528f60aeae7c852a08189ddc6ec2be3d15",
"extension": "c",
"filename": "gateway.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": 2352,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/platform/stepper-robot/gateway/gateway.c",
"provenance": "stackv2-0092.json.gz:43878",
"repo_name": "le7amdon/contiki-arduino-1",
"revision_date": "2009-08-22T20:14:16",
"revision_id": "b869879dcbef6043595da4a23ebbd420ab969921",
"snapshot_id": "1d6764654b2747f4b5ff8c41a511c957f91b83e9",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/le7amdon/contiki-arduino-1/b869879dcbef6043595da4a23ebbd420ab969921/platform/stepper-robot/gateway/gateway.c",
"visit_date": "2021-01-18T22:47:10.844673"
} | stackv2 | #include <stdio.h>
#include <sys/etimer.h>
#include <sys/process.h>
#include <sys/autostart.h>
#include <usb/usb-api.h>
#include <usb/cdc-acm.h>
#include <dev/leds.h>
#include <debug-uart.h>
#include <net/uip-fw-drv.h>
#include <dev/slip.h>
/* SLIP interface */
extern struct uip_fw_netif cc2420if;
static struct uip_fw_netif slipif =
{UIP_FW_NETIF(0,0,0,0, 255,255,255,255, slip_send)};
/* USB buffers */
static unsigned char input_buffer[128];
static unsigned char output_buffer[128];
static unsigned char interrupt_buffer[16];
#define DEV_TO_HOST 0x81
#define HOST_TO_DEV 0x02
void
slip_arch_init(unsigned long ubr)
{
}
void
slip_arch_writeb(unsigned char c)
{
while(usb_send_data(DEV_TO_HOST, &c, 1) != 1);
}
PROCESS(gateway_process, "Gateway process");
PROCESS_THREAD(gateway_process, ev , data)
{
static struct etimer timer;
PROCESS_BEGIN();
usb_set_user_process(process_current);
usb_setup();
usb_cdc_acm_setup();
uip_fw_default(&slipif);
uip_fw_register(&cc2420if);
process_start(&slip_process, NULL);
while(ev != PROCESS_EVENT_EXIT) {
PROCESS_WAIT_EVENT();
if (ev == PROCESS_EVENT_TIMER) {
leds_toggle(LEDS_YELLOW);
etimer_restart(&timer);
} else if (ev == PROCESS_EVENT_MSG) {
const struct usb_user_msg * const msg = data;
switch(msg->type) {
case USB_USER_MSG_TYPE_CONFIG:
printf("User config\n");
if (msg->data.config != 0) {
usb_setup_bulk_endpoint(DEV_TO_HOST,
input_buffer, sizeof(input_buffer));
usb_setup_bulk_endpoint(HOST_TO_DEV,
output_buffer, sizeof(output_buffer));
usb_setup_interrupt_endpoint(0x83,interrupt_buffer,
sizeof(interrupt_buffer));
etimer_set(&timer, CLOCK_SECOND);
} else {
etimer_stop(&timer);
usb_disable_endpoint(DEV_TO_HOST);
usb_disable_endpoint(HOST_TO_DEV);
usb_disable_endpoint(0x83);
}
break;
case USB_USER_MSG_TYPE_EP_OUT(2):
{
unsigned int len = msg->data.length;
/* printf("Received %d:\n", len); */
{
unsigned char ch;
unsigned int xfer;
while((xfer = usb_recv_data(HOST_TO_DEV, &ch, 1)) > 0) {
/* printf(" %02x",ch); */
if (slip_input_byte(ch)) break;
}
/* printf("\n"); */
}
}
break;
}
}
}
printf("USB test process exited\n");
PROCESS_END();
}
AUTOSTART_PROCESSES(&gateway_process);
| 2.34375 | 2 |
2024-11-18T20:55:39.453931+00:00 | 2019-01-26T16:25:38 | 6c3a4593795fea39d9863541b2b16ddbced90b26 | {
"blob_id": "6c3a4593795fea39d9863541b2b16ddbced90b26",
"branch_name": "refs/heads/master",
"committer_date": "2019-01-26T16:25:38",
"content_id": "80cc0c23becd69f7c924478258a4f8ef41e780df",
"detected_licenses": [
"BSL-1.0"
],
"directory_id": "c45ee0e3fbd233b49da8f9ef373ff199c12ef4c8",
"extension": "c",
"filename": "factorial.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": 152,
"license": "BSL-1.0",
"license_type": "permissive",
"path": "/software/launchpad/src/data_board/factorial.c",
"provenance": "stackv2-0092.json.gz:44136",
"repo_name": "VT-VCC/Sandbox",
"revision_date": "2019-01-26T16:25:38",
"revision_id": "9c2bffb144ab7e3d5a3bd86989802f28a146ad44",
"snapshot_id": "d3ee32b068e2f88fc2614f36736683a28e469a79",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/VT-VCC/Sandbox/9c2bffb144ab7e3d5a3bd86989802f28a146ad44/software/launchpad/src/data_board/factorial.c",
"visit_date": "2020-04-19T14:09:02.681317"
} | stackv2 | #include "data_board/factorial.h"
uint64_t factorial(uint64_t n) {
uint64_t tr = 1;
for (int i = 2; i <= n; ++i) {
tr *= i;
}
return tr;
}
| 2.21875 | 2 |
2024-11-18T20:55:39.771051+00:00 | 2019-09-22T19:51:28 | ee00ef1c1b5d177906042b92ff6fa52ecea86b72 | {
"blob_id": "ee00ef1c1b5d177906042b92ff6fa52ecea86b72",
"branch_name": "refs/heads/master",
"committer_date": "2019-09-22T19:51:28",
"content_id": "bb58c8219746b8cac827f026c393360090907dd4",
"detected_licenses": [
"MIT"
],
"directory_id": "965c60c5f734b6bc54f9033b924e5265f90d4f88",
"extension": "h",
"filename": "minishell.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 207152614,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2767,
"license": "MIT",
"license_type": "permissive",
"path": "/includes/minishell.h",
"provenance": "stackv2-0092.json.gz:44393",
"repo_name": "psprawka/Minishell",
"revision_date": "2019-09-22T19:51:28",
"revision_id": "e94d5418d132bdaadc4088f07fe3bb317f578cd1",
"snapshot_id": "46b978ef2ec1ef2f900007492e3b1e28de87a6dc",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/psprawka/Minishell/e94d5418d132bdaadc4088f07fe3bb317f578cd1/includes/minishell.h",
"visit_date": "2020-07-22T09:35:42.648943"
} | stackv2 | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* minishell.h :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: psprawka <psprawka@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/09/08 20:23:31 by psprawka #+# #+# */
/* Updated: 2019/09/22 21:28:05 by psprawka ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef _MINISHELL_H_
# define _MINISHELL_H_
# include <sys/select.h>
# include <stddef.h>
# include <stdbool.h>
# include <stdio.h>
# include <string.h>
# include <stdlib.h>
# include <unistd.h>
# include <dirent.h>
# include "libft/libft.h"
/*
** -> ENV_EXTENTION - defines how bigger than size g_shell.environ array is;
** this is done in order to avoid remalloc each time new variable is added.
** Let's say the size of the environ array equals 27 - an array will have
** 27 + ENV_EXTENTION slots in array. When there are twice less variables as
** ENV_EXTENTION in g_shell.environ, array is remalloced to a smaller size.
*/
#define CMD_NAME cmd_args[0]
#define ENV_PATH g_shell.path;
#define ENV_EXTENTION 10
#define ENV_EMPTY_SLOTS (g_shell.environ_elements < g_shell.environ_size - 1)
#define MAX_PATH_LEN 4096
typedef struct s_builtins
{
char *builtin_name;
int (*fct)(char **args);
} t_builtins;
typedef struct s_shell
{
char **environ;
int environ_size;
int environ_elements;
char **env_path;
bool exit;
} t_shell;
extern t_shell g_shell;
int display_prompt(void);
int get_input(char **input);
char **parse_input(char *input);
int error(int errnb, char *msg, int ret);
/*
** builtins/
*/
int builtin_cd(char **args);
int builtin_clear(char **args);
int builtin_echo(char **args);
int builtin_env(char **args);
int builtin_exit(char **args);
int builtin_pwd(char **args);
int builtin_setenv(char **args);
int builtin_unsetenv(char **args);
/*
** command/
*/
int command_execute_bin(char *cmd, char **cmd_args);
int command_execute_builtin(char *cmd, char **cmd_args);
int command_handle(char *cmds);
/*
** enviroment/
*/
int env_print(void);
int env_remalloc(int new_size);
int env_setup(char **envp);
/*
** shell/
*/
void shell_free(void);
int shell_setup(char **envp);
#endif | 2.390625 | 2 |
2024-11-18T20:55:39.894522+00:00 | 2020-08-15T14:11:32 | 835ab5cf062a49b348d8f9698b777dce65222bce | {
"blob_id": "835ab5cf062a49b348d8f9698b777dce65222bce",
"branch_name": "refs/heads/master",
"committer_date": "2020-08-15T14:11:32",
"content_id": "f7fc231f6e60f698d02ea8fa0f099fe067e12e06",
"detected_licenses": [
"Unlicense"
],
"directory_id": "ad41198ad433285c6066b4663ffc84ae579d799f",
"extension": "c",
"filename": "timer.c",
"fork_events_count": 5,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 105175420,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1001,
"license": "Unlicense",
"license_type": "permissive",
"path": "/sys/kern/timer.c",
"provenance": "stackv2-0092.json.gz:44651",
"repo_name": "matsud224/tinyos",
"revision_date": "2020-08-15T14:11:32",
"revision_id": "5ff5079c656913b809f8ee9091d931fc492d07de",
"snapshot_id": "aa5889760082bf99b94e8bbb26e02ffa15ba21b6",
"src_encoding": "UTF-8",
"star_events_count": 54,
"url": "https://raw.githubusercontent.com/matsud224/tinyos/5ff5079c656913b809f8ee9091d931fc492d07de/sys/kern/timer.c",
"visit_date": "2021-06-16T13:19:22.769012"
} | stackv2 | #include <kern/timer.h>
#include <kern/kernlib.h>
#include <kern/lock.h>
struct timer_entry {
struct timer_entry *next;
u32 expire;
void (*func)(const void *);
void *arg;
};
static struct timer_entry *timer_head = NULL;
void timer_start(u32 ticks, void (*func)(const void *), void *arg) {
struct timer_entry *t = malloc(sizeof(struct timer_entry));
t->expire = ticks;
t->func = func;
t->arg = arg;
t->next = NULL;
IRQ_DISABLE
struct timer_entry **p = &timer_head;
while(*p!=NULL) {
if(t->expire < (*p)->expire) {
(*p)->expire -= t->expire;
break;
}
t->expire -= (*p)->expire;
p = &((*p)->next);
}
t->next = *p;
*p = t;
IRQ_RESTORE
}
void timer_tick() {
if(timer_head == NULL)
return;
else
if(timer_head->expire > 0)
timer_head->expire--;
while(timer_head != NULL && timer_head->expire == 0) {
struct timer_entry *tmp = timer_head;
timer_head = timer_head->next;
(tmp->func)(tmp->arg);
free(tmp);
}
}
| 2.75 | 3 |
2024-11-18T20:55:39.995949+00:00 | 2015-10-11T22:27:15 | 2987da68adad8aaa954021ca0e01a5ebdf335d2a | {
"blob_id": "2987da68adad8aaa954021ca0e01a5ebdf335d2a",
"branch_name": "refs/heads/master",
"committer_date": "2015-10-11T22:27:15",
"content_id": "68f0f8683330ff330323be8b674cc32c62923367",
"detected_licenses": [
"MIT",
"BSD-2-Clause"
],
"directory_id": "b7b96e0bbcd07c2c0cbba364ea4c244f8aefc06b",
"extension": "h",
"filename": "xhash.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 42786667,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5261,
"license": "MIT,BSD-2-Clause",
"license_type": "permissive",
"path": "/src/xhash.h",
"provenance": "stackv2-0092.json.gz:44780",
"repo_name": "alipha/xhash",
"revision_date": "2015-10-11T22:27:15",
"revision_id": "3cf0120da30ce8c3c3dd13adc8ecd97df47f889b",
"snapshot_id": "ea635552986af57e03b9e9060baa95772aaf17d1",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/alipha/xhash/3cf0120da30ce8c3c3dd13adc8ecd97df47f889b/src/xhash.h",
"visit_date": "2021-01-25T04:53:11.445816"
} | stackv2 | /*
The MIT License (MIT)
Copyright (c) 2015 Kevin Spinar (Alipha)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#ifndef XHASH_H
#define XHASH_H
#include <stddef.h>
/*********************************************************************
*
* MODIFY THE BELOW SALT SO THAT YOUR APPLICATION WILL HAVE A UNIQUE
* SALT, MAKING PASSWORDS MORE DIFFICULT TO CRACK
* (You can use https://www.grc.com/passwords.htm to generate a value)
*
********************************************************************/
#define INTERNAL_SALT "AXHwyuIHKoC1jeOgl0Di2f3s9hSDpjOaVP8xD7X6bVu"
#define XHASH_MULTIPLIER_BITS 4
#define XHASH_MULTIPLIER (1 << XHASH_MULTIPLIER_BITS)
#define XHASH_DIGEST_BITS 6
#define XHASH_DIGEST_SIZE (1 << XHASH_DIGEST_BITS)
/* Besides the error codes, this is probably the only #define you'll use.
The size includes the terminating null. */
#define XHASH_BASE64_DIGEST_SIZE 89
#define XHASH_DEFAULT_MEMORY_BITS 22
#define XHASH_MIN_MEMORY_BITS (XHASH_MULTIPLIER_BITS + XHASH_DIGEST_BITS)
#define XHASH_MAX_MEMORY_BITS 31
#define XHASH_SUCCESS 0
#define XHASH_ERROR_NULL_HANDLE -1
#define XHASH_ERROR_HANDLE_NOT_INIT -2
/* memory_multiplier_bits must be between 10 and 31 inclusive. default is 22 */
#define XHASH_ERROR_INVALID_MEMORY_BITS -3
#define XHASH_ERROR_NULL_DIGEST -4
#define XHASH_ERROR_NULL_DATA -5
#define XHASH_ERROR_NULL_SALT -6
#define XHASH_ERROR_MALLOC_FAILED -7
#ifdef WIN32
#ifdef XHASH_BUILD_LIB
#define XHASH_EXPORT __declspec(dllexport)
#else
#define XHASH_EXPORT __declspec(dllimport)
#endif
#else
#define XHASH_EXPORT
#endif
/* Do not modify this struct yourself. Use xhash_init */
typedef struct xhash_settings
{
unsigned char *system_salt;
size_t system_salt_len;
size_t mixing_iterations;
size_t fill_amount;
size_t memory_blocks;
size_t memory_usage; /* Memory usage in bytes. The only member of this struct you'll probably use */
unsigned char *hash_array;
} xhash_settings;
#ifdef __cplusplus
extern "C" {
#endif
/* Call one of the init functions first, passing in a pointer to a xhash_settings struct to fill. */
/* Use a good source of randomness to generate at least 32 bytes for the system_salt.
Store the system_salt somewhere separate from the per-user salt.
Allocates (1 << memory_bits) bytes of memory and xhash will perform (1 << (memory_bits - 10)) iterations by default.
E.g., with the memory_bits default of 22, then 4 MB of memory is allocated and 4096 iterations are performed. */
XHASH_EXPORT
int xhash_init(xhash_settings *handle, const void *system_salt, size_t system_salt_len, size_t memory_bits, size_t additional_iterations);
XHASH_EXPORT
int xhash_init_defaults(xhash_settings *handle, const void *system_salt, size_t system_salt_len);
/* Hash the specified data with the specified salt and return the resulting hash in digest
(digest must point to an unsigned char[XHASH_DIGEST_SIZE]).
Use xhash_text for a friendlier interface when working with null-terminated passwords
and user salts.
May call xhash or xhash_text as many times as you'd like after calling
xhash_init or xhash_init_defaults and before calling xhash_free.
Pass 1 for free_after to avoid having to call xhash_free. You must then call xhash_init
again before calling xhash or xhash_text again. */
XHASH_EXPORT
int xhash(xhash_settings *handle, unsigned char *digest, const void *data, size_t data_len, const void *salt, size_t salt_len, int free_after);
/* Hashes the null-terminated password with the null-terminated user_salt and
returns a base64-encoded result into base64_digest.
(base64_digest must point to a char[XHASH_BASE64_DIGEST_SIZE]) */
XHASH_EXPORT
int xhash_text(xhash_settings *handle, char *base64_digest, const char *password, const char *user_salt, int free_after);
/* Frees the memory referenced by xhash_settings. Must call once per xhash_init and before
calling xhash_init again with the same xhash_settings handle.
Does not free the memory used by xhash_settings itself, if it was allocated dynamically
(But there's generally no reason to do so; the xhash_settings object should have
automatic or static scope.) */
XHASH_EXPORT
void xhash_free(xhash_settings *handle);
#ifdef __cplusplus
}
#endif
#endif
| 2.1875 | 2 |
2024-11-18T20:55:40.143592+00:00 | 2017-04-22T08:51:15 | 7ce38dcfcdb8685d7103df3a1b00959a83f8f435 | {
"blob_id": "7ce38dcfcdb8685d7103df3a1b00959a83f8f435",
"branch_name": "refs/heads/master",
"committer_date": "2017-04-22T08:51:15",
"content_id": "9ba445e01a482e09319fd1e0ea38fe806e97260d",
"detected_licenses": [
"MIT"
],
"directory_id": "2b87d2d60e5525cbdc56f6f54ac473ec4b920848",
"extension": "c",
"filename": "Uebung_C_4_4_queue.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": 1016,
"license": "MIT",
"license_type": "permissive",
"path": "/Uebungen/Uebung_C_4_4_queue.c",
"provenance": "stackv2-0092.json.gz:44908",
"repo_name": "iwanbolzern/hslu-mc-microcontroller-c",
"revision_date": "2017-04-22T08:51:15",
"revision_id": "1b408b1269987479d24e98e9f193e58d9bc3dcfe",
"snapshot_id": "47c76235a0260568bfd4bba1577de0d81c4460aa",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/iwanbolzern/hslu-mc-microcontroller-c/1b408b1269987479d24e98e9f193e58d9bc3dcfe/Uebungen/Uebung_C_4_4_queue.c",
"visit_date": "2021-03-27T19:55:09.118009"
} | stackv2 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: Uebung_C_4_4_queue.c
* Author: Iwan
*
* Created on 4. April 2017, 18:41
*/
#include <stdio.h>
#include <stdlib.h>
#include "Uebung_C_4_4_queue.h"
queueEntry_t* head = NULL;
queueEntry_t* tail = NULL;
void initialize(void) {
}
void enqueue(int msg) {
queueEntry_t* entry = (queueEntry_t*)malloc(sizeof(queueEntry_t));
entry->msg = msg;
entry->nextEntry = NULL;
if(tail != NULL) {
tail->nextEntry = entry;
}
if(head == NULL) {
head = entry;
}
tail = entry;
}
int dequeue(void) {
if(head == NULL) {
printf("Nothing to deqeue!!");
return -1;
}
queueEntry_t* entry = head;
int msg = entry->msg;
if(head == tail) {
tail = NULL;
}
head = head->nextEntry;
free(entry);
return msg;
}
| 3 | 3 |
2024-11-18T20:55:40.225232+00:00 | 2023-08-18T17:04:30 | 3a25c5f1b9988a51ddcc86fc1a6f836331364915 | {
"blob_id": "3a25c5f1b9988a51ddcc86fc1a6f836331364915",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-18T17:04:30",
"content_id": "d68930c037b52ff6c41d745143ff3c85ceb755ab",
"detected_licenses": [
"MIT"
],
"directory_id": "e7f43a909d0ee15c165259cf1031374ea99fa311",
"extension": "c",
"filename": "app.c",
"fork_events_count": 2,
"gha_created_at": "2018-12-16T10:11:51",
"gha_event_created_at": "2021-03-18T22:52:39",
"gha_language": "C#",
"gha_license_id": "MIT",
"github_id": 161988896,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 351,
"license": "MIT",
"license_type": "permissive",
"path": "/geral/book_programming_in_c/ex70/lib/app.c",
"provenance": "stackv2-0092.json.gz:45038",
"repo_name": "flaviogf/courses",
"revision_date": "2023-08-18T17:04:30",
"revision_id": "0a98b54f4ca4c00223fb445bace3b99fffffb35b",
"snapshot_id": "cfcfbc6a6dfc9f096ace2933af401b511738f084",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/flaviogf/courses/0a98b54f4ca4c00223fb445bace3b99fffffb35b/geral/book_programming_in_c/ex70/lib/app.c",
"visit_date": "2023-08-31T20:54:55.215979"
} | stackv2 | #include <stdio.h>
void multiplyBy2(float values[], int size)
{
for(int i = 0; i < size; ++i)
values[i] *= 2;
}
int main()
{
void multiplyBy2(float values[], int size);
float values[4] = { 1.2f, -3.7f, 6.2f, 8.55f };
multiplyBy2(values, 4);
for(int i = 0; i < 4; ++i)
printf("%.2f ", values[i]);
printf("\n");
return 0;
}
| 3.40625 | 3 |
2024-11-18T20:55:41.098295+00:00 | 2022-02-20T01:13:52 | 6515ff1a92a3c6c10ac74a07b0c178a1757a7dcf | {
"blob_id": "6515ff1a92a3c6c10ac74a07b0c178a1757a7dcf",
"branch_name": "refs/heads/master",
"committer_date": "2022-02-21T19:38:33",
"content_id": "239e0ba3f8a9a46f8904ee3c14100e11e409df01",
"detected_licenses": [
"MIT"
],
"directory_id": "ae8d0783918ca0476c4ea617fc014c7436538c5a",
"extension": "c",
"filename": "sparks.c",
"fork_events_count": 5,
"gha_created_at": "2017-10-03T19:47:08",
"gha_event_created_at": "2022-02-21T19:38:34",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 105695732,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1998,
"license": "MIT",
"license_type": "permissive",
"path": "/cqe-challenges/CROMU_00006/src/sparks.c",
"provenance": "stackv2-0092.json.gz:45296",
"repo_name": "GrammaTech/cgc-cbs",
"revision_date": "2022-02-20T01:13:52",
"revision_id": "797bd722ea544ab8205446dde13dcfdc059c0989",
"snapshot_id": "75c93cd2d33f794b33097a45f7b6417fb27acc25",
"src_encoding": "UTF-8",
"star_events_count": 9,
"url": "https://raw.githubusercontent.com/GrammaTech/cgc-cbs/797bd722ea544ab8205446dde13dcfdc059c0989/cqe-challenges/CROMU_00006/src/sparks.c",
"visit_date": "2022-03-18T07:07:47.271029"
} | stackv2 | #include <libcgc.h>
#include "libc.h"
#include "charter.h"
#include "sparks.h"
#include "data.h"
#include "block.h"
uint32* sparkles = NULL;
uint32 sparkle_count = 0;
void sparks(data_package data) {
uint32 candidate_count;
uint32 bar_buf[data.size];
__block uint32* bar_buf_ptr = (uint32*)bar_buf;
read(&candidate_count, sizeof(candidate_count));
if ((candidate_count == 0 && sparkle_count == 0) ||
(candidate_count > MAX_ALLOCATE_SIZE)) {
_terminate(-1);
}
if (candidate_count != 0) {
if (sparkles != NULL) {
deallocate(sparkles, sparkle_count );
}
sparkle_count = candidate_count;
#ifdef PATCHED
int alloc_error = allocate( (candidate_count + 1)*4, 0, (void**)&sparkles);
#else
int alloc_error = allocate(candidate_count + 1, 0, (void**)&sparkles);
#endif
if (alloc_error) _terminate(-1);
for (uint32 cur = 0; cur < sparkle_count; cur++) {
uint32 sparkle;
read(&sparkle, sizeof(sparkle));
sparkles[cur] = sparkle;
}
}
__block uint32 min = UINT32_MAX;
__block uint32 max = 0;
each(data, ^(uint32 idx, uint32 datum){
if (datum > max) max = datum;
if (datum < min) min = datum;
});
if (min == max) {
each(data, ^(uint32 cur, uint32 datum) {
bar_buf_ptr[cur] = sparkles[sparkle_count - 1];
});
} else {
double div = spark_divisor(max, min, sparkle_count);
each(data, ^(uint32 cur, uint32 datum){
uint32 idx = spark_pick_index(datum, min, div);
bar_buf_ptr[cur] = sparkles[idx];
});
}
transmit_all(STDOUT, (char*)(bar_buf), data.size * sizeof(uint32));
return;
}
double spark_divisor(uint32 max,
uint32 min,
uint32 sparkle_count) {
return ((double)max - (double)min) / (sparkle_count - 1);
}
uint32 spark_pick_index(uint32 datum,
uint32 min,
double divisor) {
return (uint32)(((double)datum - min) / divisor);
}
| 2.65625 | 3 |
2024-11-18T20:55:41.331429+00:00 | 2023-09-01T08:06:28 | 5eda002a68ca9a0e29ada73e97148bbdb7d503f8 | {
"blob_id": "5eda002a68ca9a0e29ada73e97148bbdb7d503f8",
"branch_name": "refs/heads/master",
"committer_date": "2023-09-01T10:45:38",
"content_id": "e5458af8615a850ce86b1c4f4426a279e852d102",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "eda03521b87da8bdbef6339b5b252472a5be8d23",
"extension": "h",
"filename": "link.h",
"fork_events_count": 3929,
"gha_created_at": "2018-12-02T19:28:41",
"gha_event_created_at": "2023-09-14T21:00:04",
"gha_language": "C++",
"gha_license_id": "BSD-2-Clause",
"github_id": 160083795,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 457,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/Userland/Libraries/LibC/link.h",
"provenance": "stackv2-0092.json.gz:45684",
"repo_name": "SerenityOS/serenity",
"revision_date": "2023-09-01T08:06:28",
"revision_id": "ef9b6c25fafcf4ef0b44a562ee07f6412aeb8561",
"snapshot_id": "6ba3ffb242ed76c9f335bd2c3b9a928329cd7d98",
"src_encoding": "UTF-8",
"star_events_count": 27256,
"url": "https://raw.githubusercontent.com/SerenityOS/serenity/ef9b6c25fafcf4ef0b44a562ee07f6412aeb8561/Userland/Libraries/LibC/link.h",
"visit_date": "2023-09-01T13:04:30.262106"
} | stackv2 | /*
* Copyright (c) 2021, Gunnar Beutner <gunnar@beutner.name>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#pragma once
#include <elf.h>
#include <limits.h>
#include <sys/cdefs.h>
__BEGIN_DECLS
struct dl_phdr_info {
ElfW(Addr) dlpi_addr;
char const* dlpi_name;
const ElfW(Phdr) * dlpi_phdr;
ElfW(Half) dlpi_phnum;
};
int dl_iterate_phdr(int (*callback)(struct dl_phdr_info* info, size_t size, void* data), void* data);
__END_DECLS
| 2.015625 | 2 |
2024-11-18T20:55:41.415936+00:00 | 2014-04-27T13:57:43 | ed02840025efa7c5b549503816206c3c7b5bb94c | {
"blob_id": "ed02840025efa7c5b549503816206c3c7b5bb94c",
"branch_name": "refs/heads/master",
"committer_date": "2014-04-27T13:57:43",
"content_id": "9bc85d026527fb9b95db39f49944dec72adb75ed",
"detected_licenses": [
"MIT"
],
"directory_id": "f7f5e39495655362b045c10723058ceb172d5a10",
"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": 1699,
"license": "MIT",
"license_type": "permissive",
"path": "/parser.c",
"provenance": "stackv2-0092.json.gz:45813",
"repo_name": "jeffreyjw/teststructure",
"revision_date": "2014-04-27T13:57:43",
"revision_id": "57860519b782c0f75e1aa35ac7dbdb3e8877faa8",
"snapshot_id": "cff902320f62d114c1017ddb2db18e361fabb156",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/jeffreyjw/teststructure/57860519b782c0f75e1aa35ac7dbdb3e8877faa8/parser.c",
"visit_date": "2016-09-06T08:27:22.899171"
} | stackv2 | #include "parser.h"
#include <stdlib.h>
PUBLIC Parser* parser_create(void)
{
Parser* parser = malloc(sizeof(Parser));
parser_init(parser);
return parser;
}
PRIVATE void parser_init(Parser* parser)
{
parser->type_string = mpc_new("type_string");
parser->suite = mpc_new("suite");
parser->language = mpc_new("mocha");
parser->function = mpc_new("function");
parser->comment = mpc_new("comment");
mpca_lang(MPCA_LANG_DEFAULT,
" \
type_string : '\"' /[a-zA-Z0-9_\\s\\.\\,]*/ '\"' ; \
function : \"function\" '(' ')' '{' (<suite>+|/[^\\}]*/) '}' ; \
comment : \"/**\" /[^(\\*\\/)]*/ \"*/\" ; \
suite : <comment>? \"it\" '(' <type_string> ',' <function> ')' /\\;?/ ; \
mocha : <suite> ; \
"
, parser->type_string,
parser->function,
parser->comment,
parser->suite,
parser->language);
}
PUBLIC void parser_parse(Parser* parser, const char* input)
{
printf("%s\n\n", input);
mpc_result_t r;
if (mpc_parse("<stdin>", input, parser->language, &r)) {
/* On Success Print the AST */
mpc_ast_print(r.output);
mpc_ast_delete(r.output);
} else {
/* Otherwise Print the Error */
mpc_err_print(r.error);
mpc_err_delete(r.error);
}
}
PUBLIC void parser_free(Parser* parser)
{
mpc_cleanup(5,
parser->type_string,
parser->suite,
parser->function,
parser->comment,
parser->language);
free(parser);
} | 2.5 | 2 |
2024-11-18T20:55:41.626923+00:00 | 2016-06-09T20:16:30 | c69861d3f111e9f039dce6974883b061b2eed8d9 | {
"blob_id": "c69861d3f111e9f039dce6974883b061b2eed8d9",
"branch_name": "refs/heads/master",
"committer_date": "2016-06-09T20:16:30",
"content_id": "582ec45ded41d735b02527abf80729910110bb7f",
"detected_licenses": [
"MIT"
],
"directory_id": "99269b35f71eefa99c66d5c084c1bec578c6c7f9",
"extension": "h",
"filename": "socket.h",
"fork_events_count": 4,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 60717026,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2399,
"license": "MIT",
"license_type": "permissive",
"path": "/socket.h",
"provenance": "stackv2-0092.json.gz:46197",
"repo_name": "gnachman/UDPBroadcast",
"revision_date": "2016-06-09T20:16:30",
"revision_id": "b5e014cb9ad0961b39e5d77cacafe497b0fe10ae",
"snapshot_id": "70e3ca3180653880a26c415a4983e4bd2194045e",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/gnachman/UDPBroadcast/b5e014cb9ad0961b39e5d77cacafe497b0fe10ae/socket.h",
"visit_date": "2021-01-16T21:51:00.621798"
} | stackv2 | #ifndef __SOCKET_H__
#define __SOCKET_H__
#include <stdio.h>
#include <arpa/inet.h>
// Return a nonzero value to stop listening.
typedef int ListenCallback(char *message,
int length,
struct sockaddr_storage *remoteAddress,
socklen_t remoteAddressSize,
void *usersData);
// Create a socket that is allowed to use the broadcast interface.
// Pass 1 in wantLoopback if you want to receive messages sent to the broadcast
// address on localhost.
int GetBroadcastSocket(unsigned char wantLoopback);
// Send a message to the broadcast address and close the socket.
int BroadcastToSocket(int sock, char *messge, size_t length, unsigned short broadcastPort);
// Change whether the socket listens on the loopback interface.
int SetSocketWantsLoopback(int sock, unsigned char loopback);
// Bind a port to a socket. Messages sent to the port will get queued and can
// be read later with ReceiveFromSocket().
int BindSocketToPort(int sock, unsigned short port);
// Returns the port the socket is bound to.
unsigned short GetSocketPort(int sock);
// Tries to receive a single message on a scoket opened with GetListenSocket().
// Returns nonzero if listening should stop, either because of an error or
// because the callback returned a nonzero value.
int ReceiveFromSocket(int sock, double timeout, ListenCallback *callback, void *userData);
// Sends a message to a socket
int SendToSocket(int sock,
char *message,
size_t length,
struct sockaddr_in *remoteAddress);
// Send a UDP message to the specified address. May not be a broadcast address.
int Send(char *message,
size_t length,
struct sockaddr_in *remoteAddress);
// Send a UDP broadcast locally containing "message". The `length` should not
// exceed 65507. Closes the socket.
int Broadcast(char *message,
size_t length,
unsigned short broadcastPort,
unsigned short sourcePort,
unsigned char wantLoopback);
// Starts a long-running server listening for UDP broadcasts. Returns nonzero
// on failure. Returns zero on success (when the callback tells it to exit).
// Invokes `callback` when a datagram is received.
int RunListenServer(unsigned short port, ListenCallback *callback);
#endif // _SOCKET_H__
| 2.40625 | 2 |
2024-11-18T20:55:41.700479+00:00 | 2016-05-30T10:20:15 | a82cd677516db9597bdc36ff7066b93f22cdb114 | {
"blob_id": "a82cd677516db9597bdc36ff7066b93f22cdb114",
"branch_name": "refs/heads/master",
"committer_date": "2016-05-30T10:20:15",
"content_id": "38eb7181cdff89466abd2c2ebdb927457276d581",
"detected_licenses": [
"MIT"
],
"directory_id": "853c95632e559e2d8b771b1ba503b15433463270",
"extension": "c",
"filename": "f1750a_util.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 57093106,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 21721,
"license": "MIT",
"license_type": "permissive",
"path": "/libgpl/libgpl/f1750a_util.c",
"provenance": "stackv2-0092.json.gz:46325",
"repo_name": "mitra/search-benchmark",
"revision_date": "2016-05-30T10:20:15",
"revision_id": "12bef7770bcf8f1fdbe78784b55c29361f37bfa9",
"snapshot_id": "e3e0974ab0ea25cb631c835bfbf3925c9c32ab12",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/mitra/search-benchmark/12bef7770bcf8f1fdbe78784b55c29361f37bfa9/libgpl/libgpl/f1750a_util.c",
"visit_date": "2021-01-01T03:38:37.155516"
} | stackv2 | /* $Id: f1750a_util.c,v 1.9 2011/07/18 17:46:04 alex Exp $ */
/*******************************************************************************
File:
f1750a_util.c
MIL-STD-1750A Floating Point Utilities.
Author: Alex Measday
Purpose:
The F1750A utilities are used to convert floating-point numbers between
the host CPU's native format and MIL-STD-1750A floating-point format.
The supported MIL-STD-1750A floating-point formats are a non-standard
16-bit representation and the standard 32- and 48-bit representations.
In the following, big-endian bit layouts, "M" is a mantissa bit and "E"
is an exponent bit. Both the mantissa and the exponent are treated as
twos-complement numbers; diagrams misleadingly show the most-significant
bit of the mantissa as a sign bit.
16-bit Representation (6-bit exponent ranging from -32 to +31;
10-bit mantissa ranging from -512 to +511)
MMMMMMMM MMEEEEEE
32-bit Representation (8-bit exponent ranging from -128 to +127;
24-bit mantissa ranging from -8,388,608
to +8,388,607)
MMMMMMMM MMMMMMMM MMMMMMMM EEEEEEEE
48-bit Representation (8-bit exponent ranging from -128 to +127;
40-bit mantissa ranging from -549,755,813,888
to +549,755,813,887)
MMMMMMMM MMMMMMMM MMMMMMMM EEEEEEEE
MMMMMMMM MMMMMMMM
In all representations, the radix point is immediately to the right of
the most-significant bit of the mantissa, giving a nominal range of:
-1.0 <= mantissa < +1.0
(Normalization of negative numbers produces a gap down in the negative
range.) Taking the radix point into account, the value of a floating-point
number in MIL-STD-1750A format equals:
mantissa * (2 ** exponent)
If you treat the full N bits of the mantissa as a signed integer,
the floating-point value can then be computed simply as:
mantissa * (2 ** (exponent - precision))
where the precision is one less than the width in bits of the mantissa.
Public Procedures:
double2f1750a() - converts a native double to MIL-STD-1750A format.
f1750a2double() - converts MIL-STD-1750A format to a native double.
*******************************************************************************/
#include "pragmatics.h" /* Compiler, OS, logging definitions. */
#include <math.h> /* Math library definitions. */
#include <stdio.h> /* Standard I/O definitions. */
#include <stdlib.h> /* Standard C Library definitions. */
#include "f1750a_util.h" /* 1750A floating point utilities. */
#define COMPLEMENT_40_BITS(mantissa) \
{ (mantissa)[0] = ~(mantissa)[0] & 0x00FFFFFF ; \
(mantissa)[1] = ~(mantissa)[1] & 0x0000FFFF ; \
}
#define INCREMENT_40_BITS(mantissa) \
{ (mantissa)[1]++ ; \
if (((mantissa)[1] & (1UL << 16)) == (1UL << 16)) (mantissa)[0]++ ;\
}
#define SHIFT_LEFT_40_BITS(mantissa) \
{ (mantissa)[0] <<= 1 ; (mantissa)[1] <<= 1 ; \
if (((mantissa)[1] & (1UL << 16)) == (1UL << 16)) \
(mantissa)[0] |= 0x00000001 ; \
}
#define SHIFT_RIGHT_40_BITS(mantissa) \
{ if ((mantissa)[0] & 0x00000001) \
(mantissa)[1] |= (1UL << 16) ; \
(mantissa)[0] >>= 1 ; (mantissa)[1] >>= 1 ; \
}
/*!*****************************************************************************
Procedure:
double2f1750a ()
Convert a Native Double to a MIL-STD-1750A Floating-Point Number.
Purpose:
The f1750a2double() function converts a floating-point number from
the host CPU's native floating-point format to MIL-STD-1750A format.
Invocation:
status = f1750a2double (value, numBits, &buffer) ;
where
<value> - I
is the floating-point number in the host CPU's native format.
<numBits> - I
is the number of bits in the MIL-STD-1750A-format number;
supported representations are 16-, 32-, and 48-bit numbers.
<buffer> - O
receives the MIL-STD-1750A-format number. The byte order
is always big-endian.
<status> - O
returns the conversion status, zero if the conversion was
successful and ERRNO otherwise.
*******************************************************************************/
errno_t double2f1750a (
# if PROTOTYPES
double value,
size_t numBits,
uint8_t *buffer)
# else
value, numBits, buffer)
double value ;
size_t numBits ;
uint8_t *buffer ;
# endif
{ /* Local variables. */
bool isNegative ;
double fraction, integer ;
int exponent ;
unsigned long mantissa[2] ;
if ((numBits != 16) && (numBits != 32) && (numBits != 48)) {
SET_ERRNO (EINVAL) ;
LGE "(double2f1750a) Invalid number of bits: %d\n", numBits) ;
return (errno) ;
} else if (buffer == NULL) {
SET_ERRNO (EINVAL) ;
LGE "(double2f1750a) NULL buffer: ") ;
return (errno) ;
}
/*******************************************************************************
Convert the host CPU value to a non-standard, 16-bit, 1750A floating-point
number.
*******************************************************************************/
if (numBits == 16) {
isNegative = (value < 0.0) ;
if (isNegative) value = -value ;
/* Break the absolute value into a fraction (0.5 < = f < 1.0) and a
power-of-two exponent. */
fraction = frexp (value, &exponent) ;
/* Get the 10 most-significant bits of the mantissa by truncating the result
of multiplying the fraction by 2**10. Only 9 bits are needed for the
1750A mantissa (since this is a positive number); the 10th bit is used
for rounding. */
mantissa[0] = (unsigned long) ldexp (fraction, 10) ;
/* If the least-significant bit is set, then round the mantissa upwards
by incrementing it. Then, shift the rounding bit out of the mantissa. */
if (mantissa[0] & 0x00000001) mantissa[0]++ ;
mantissa[0] >>= 1 ;
/* If the rounding overflowed into a new most-significant bit position,
then drop the least-significant bit and adjust the exponent. */
if (mantissa[0] & (1UL << 9)) {
mantissa[0] >>= 1 ;
exponent++ ;
}
/* If the floating-point value is negative, then negate the mantissa
using twos-complement arithmetic. */
if (isNegative) {
mantissa[0] = ~mantissa[0] ;
mantissa[0]++ ;
}
/* Normalize the mantissa. A 1750A floating-point number is normalized if
its two most-significant bits have opposite values. For a positive input
value, the twos-complement mantissa is already normalized (binary 01...).
Negative mantisssas with the two most-significant bits set (binary 11...)
must be shifted left and the exponent adjusted until binary "10" is in the
two most-significant bits. */
while ((mantissa[0] & (3UL << 8)) == (3UL << 8)) {
mantissa[0] <<= 1 ;
exponent-- ;
}
/* Restrict the exponent to its valid range and compute its twos-complement
representation. */
if (exponent > 31)
exponent = 31 ;
else if (exponent < -32)
exponent = -32 ;
if (exponent < 0) {
exponent = -exponent ;
exponent = ~exponent ;
exponent++ ;
}
/* Finally, construct the 1750A floating-point representation of the input
value. */
buffer[0] = (uint8_t) ((mantissa[0] >> 2) & 0x000000FF) ;
buffer[1] = (uint8_t) (((mantissa[0] & 0x00000003) << 6) |
(exponent & 0x0000003F)) ;
}
/*******************************************************************************
Convert the host CPU value to a 32-bit, 1750A floating-point number.
*******************************************************************************/
else if (numBits == 32) {
isNegative = (value < 0.0) ;
if (isNegative) value = -value ;
/* Break the absolute value into a fraction (0.5 < = f < 1.0) and a
power-of-two exponent. */
fraction = frexp (value, &exponent) ;
/* Get the 24 most-significant bits of the mantissa by truncating the result
of multiplying the fraction by 2**24. Only 23 bits are needed for the
1750A mantissa (since this is a positive number); the 24th bit is used
for rounding. */
mantissa[0] = (unsigned long) ldexp (fraction, 24) ;
/* If the least-significant bit is set, then round the mantissa upwards
by incrementing it. Then, shift the rounding bit out of the mantissa. */
if (mantissa[0] & 0x00000001) mantissa[0]++ ;
mantissa[0] >>= 1 ;
/* If the rounding overflowed into a new most-significant bit position,
then drop the least-significant bit and adjust the exponent. */
if (mantissa[0] & (1UL << 23)) {
mantissa[0] >>= 1 ;
exponent++ ;
}
/* If the floating-point value is negative, then negate the mantissa
using twos-complement arithmetic. */
if (isNegative) {
mantissa[0] = ~mantissa[0] ;
mantissa[0]++ ;
}
/* Normalize the mantissa. A 1750A floating-point number is normalized if
its two most-significant bits have opposite values. For a positive input
value, the twos-complement mantissa is already normalized (binary 01...).
Negative mantisssas with the two most-significant bits set (binary 11...)
must be shifted left and the exponent adjusted until binary "10" is in the
two most-significant bits. */
while ((mantissa[0] & (3UL << 22)) == (3UL << 22)) {
mantissa[0] <<= 1 ;
exponent-- ;
}
/* Restrict the exponent to its valid range and compute its twos-complement
representation. */
if (exponent > 127)
exponent = 127 ;
else if (exponent < -128)
exponent = -128 ;
if (exponent < 0) {
exponent = -exponent ;
exponent = ~exponent ;
exponent++ ;
}
/* Finally, construct the 1750A floating-point representation of the input
value. */
buffer[0] = (uint8_t) ((mantissa[0] >> 16) & 0x000000FF) ;
buffer[1] = (uint8_t) ((mantissa[0] >> 8) & 0x000000FF) ;
buffer[2] = (uint8_t) (mantissa[0] & 0x000000FF) ;
buffer[3] = (uint8_t) (exponent & 0x000000FF) ;
}
/*******************************************************************************
Convert the host CPU value to a 48-bit, 1750A floating-point number.
*******************************************************************************/
else if (numBits == 48) {
isNegative = (value < 0.0) ;
if (isNegative) value = -value ;
/* Break the absolute value into a fraction (0.5 < = f < 1.0) and a
power-of-two exponent. */
fraction = frexp (value, &exponent) ;
/* Get the 40 most-significant bits of the mantissa. Only 39 bits are needed
for the 1750A mantissa (since this is a positive number); the 40th bit is
used for rounding. The 24 most-significant bits are obtained by truncating
the result of multiplying the fraction by 2**24; these 24 bits are stored
in mantissa[0]. The truncated portion of the result is then multiplied by
2**16 to get the remaining 16 bits, which are stored in mantissa[1]. */
fraction = ldexp (fraction, 24) ;
mantissa[0] = (unsigned long) fraction ;
#if defined(HAVE_MODF) && !HAVE_MODF
# define modf(f,i) ((f) - (double) ((long) (f)))
#endif
mantissa[1] = (unsigned long) ldexp (modf (fraction, &integer), 16) ;
/* If the least-significant bit is set, then round the mantissa upwards
by incrementing it. Then, shift the rounding bit out of the mantissa. */
if (mantissa[1] & 0x00000001) INCREMENT_40_BITS (mantissa) ;
SHIFT_RIGHT_40_BITS (mantissa) ;
/* If the rounding overflowed into a new most-significant bit position,
then drop the least-significant bit and adjust the exponent. */
if (mantissa[0] & (1UL << 23)) {
SHIFT_RIGHT_40_BITS (mantissa) ;
exponent++ ;
}
/* If the floating-point value is negative, then negate the mantissa
using twos-complement arithmetic. */
if (isNegative) {
COMPLEMENT_40_BITS (mantissa) ;
INCREMENT_40_BITS (mantissa) ;
}
/* Normalize the mantissa. A 1750A floating-point number is normalized if
its two most-significant bits have opposite values. For a positive input
value, the twos-complement mantissa is already normalized (binary 01...).
Negative mantisssas with the two most-significant bits set (binary 11...)
must be shifted left and the exponent adjusted until binary "10" is in the
two most-significant bits. */
while ((mantissa[0] & (3UL << 22)) == (3UL << 22)) {
SHIFT_LEFT_40_BITS (mantissa) ;
exponent-- ;
}
/* Restrict the exponent to its valid range and compute its twos-complement
representation. */
if (exponent > 127)
exponent = 127 ;
else if (exponent < -128)
exponent = -128 ;
if (exponent < 0) {
exponent = -exponent ;
exponent = ~exponent ;
exponent++ ;
}
/* Finally, construct the 1750A floating-point representation of the input
value. */
buffer[0] = (uint8_t) ((mantissa[0] >> 16) & 0x000000FF) ;
buffer[1] = (uint8_t) ((mantissa[0] >> 8) & 0x000000FF) ;
buffer[2] = (uint8_t) (mantissa[0] & 0x000000FF) ;
buffer[3] = (uint8_t) (exponent & 0x000000FF) ;
buffer[4] = (uint8_t) ((mantissa[1] >> 8) & 0x000000FF) ;
buffer[5] = (uint8_t) (mantissa[1] & 0x000000FF) ;
}
return (0) ;
}
/*!*****************************************************************************
Procedure:
f1750a2double ()
Convert a MIL-STD-1750A Floating-Point Number to a Native Double.
Purpose:
The f1750a2double() function converts a floating-point number in
MIL-STD-1750A format to the host CPU's native floating-point format.
Invocation:
value = f1750a2double (numBits, buffer) ;
where
<numBits> - I
is the number of bits in the MIL-STD-1750A-format number;
supported representations are 16-, 32-, and 48-bit numbers.
<buffer> - I
is a buffer containing the MIL-STD-1750A-format number.
The bytes are assumed to be in big-endian order.
<value> - O
returns the floating-point number in the host CPU's native format.
*******************************************************************************/
double f1750a2double (
# if PROTOTYPES
size_t numBits,
uint8_t *buffer)
# else
numBits, buffer)
size_t numBits ;
uint8_t *buffer ;
# endif
{ /* Local variables. */
double value ;
int exponent, precision ;
long mantissa ;
if ((numBits != 16) && (numBits != 32) && (numBits != 48)) {
SET_ERRNO (EINVAL) ;
LGE "(f1750a2double) Invalid number of bits: %d\n", numBits) ;
return (0.0) ;
} else if (buffer == NULL) {
SET_ERRNO (EINVAL) ;
LGE "(f1750a2double) NULL buffer: ") ;
return (0.0) ;
}
/* Extract the mantissa and exponent to form the floating-point value. */
switch (numBits) {
case 16: /* 10 bits of mantissa, 6-bit exponent. */
mantissa = ((int8_t) buffer[0] << 2) | (buffer[1] >> 6) ;
if (buffer[1] & 0x20)
exponent = (int8_t) ((buffer[1] & 0x3F) | 0xC0) ;
else
exponent = buffer[1] & 0x3F ;
precision = 10 - 1 ;
value = ldexp ((double) mantissa, exponent - precision) ;
break ;
case 32: /* 24 bits of mantissa, 8-bit exponent. */
case 48: /* 24 bits of mantissa, 8-bit exponent, 16 bits of mantissa. */
default:
mantissa = (((long) ((int8_t) buffer[0])) << 16) |
((unsigned long) buffer[1] << 8) |
buffer[2] ;
exponent = (int8_t) buffer[3] ;
precision = 24 - 1 ;
value = ldexp ((double) mantissa, exponent - precision) ;
if (numBits == 48) { /* Add mantissa's 16 least-significant bits. */
mantissa = ((unsigned long) buffer[4] << 8) | buffer[5] ;
precision += 16 ;
value += ldexp ((double) mantissa, exponent - precision) ;
}
break ;
}
return (value) ;
}
#ifdef TEST
/*******************************************************************************
Test Program - examples are from the MIL-STD-1750A specification.
*******************************************************************************/
typedef struct Example16 {
uint8_t buffer[2] ;
char *result ;
} Example16 ;
static Example16 examples16[] = { /* Made these up myself! */
{{0x7F, 0xC0}, "0.9980469 x 2^0" },
{{0x7F, 0xDF}, "0.9980469 x 2^31" },
{{0x7F, 0xE0}, "0.9980469 x 2^-32" },
{{0x40, 0x00}, "0.5 x 2^0" },
{{0x40, 0x1F}, "0.5 x 2^31" },
{{0x40, 0x20}, "0.5 x 2^-32" },
{{0x00, 0x00}, "0.0 x 2^0" },
{{0x80, 0x00}, "-1.0 x 2^0" },
{{0x80, 0x1F}, "-1.0 x 2^31" },
{{0x80, 0x20}, "-1.0 x 2^-32" },
{{0xBF, 0xC0}, "-0.5019531 x 2^0" },
{{0xBF, 0xDF}, "-0.5019531 x 2^31" },
{{0xBF, 0xE0}, "-0.5019531 x 2^-32" },
{{0x9F, 0xC0}, "-0.7519531 x 2^0" },
{{0x9F, 0xDF}, "-0.7519531 x 2^31" },
{{0x9F, 0xE0}, "-0.7519531 x 2^-32" },
{{0xFF, 0xC0}, "-1.0 x 2^-9" },
{{0xFF, 0xDF}, "-1.0 x 2^22" },
{{0xFF, 0xE0}, "-1.0 x 2^-41" },
{{0, 0}, NULL}
} ;
typedef struct Example32 {
uint8_t buffer[4] ;
char *result ;
} Example32 ;
static Example32 examples32[] = { /* From TABLE III in MIL-STD-1750A. */
{{0x7F, 0xFF, 0xFF, 0x7F}, "0.9999998 x 2^127" },
{{0x40, 0x00, 0x00, 0x7F}, "0.5 x 2^127" },
{{0x50, 0x00, 0x00, 0x04}, "0.625 x 2^4" },
{{0x40, 0x00, 0x00, 0x01}, "0.5 x 2^1" },
{{0x40, 0x00, 0x00, 0x00}, "0.5 x 2^0" },
{{0x40, 0x00, 0x00, 0xFF}, "0.5 x 2^-1" },
{{0x40, 0x00, 0x00, 0x80}, "0.5 x 2^-128" },
{{0x00, 0x00, 0x00, 0x00}, "0.0 x 2^0" },
{{0x80, 0x00, 0x00, 0x00}, "-1.0 x 2^0" },
{{0xBF, 0xFF, 0xFF, 0x80}, "-0.5000001 x 2^-128" },
{{0x9F, 0xFF, 0xFF, 0x04}, "-0.7500001 x 2^4" },
{{0, 0, 0, 0}, NULL}
} ;
typedef struct Example48 {
uint8_t buffer[6] ;
char *result ;
} Example48 ;
static Example48 examples48[] = { /* From TABLE IV in MIL-STD-1750A. */
{{0x40, 0x00, 0x00, 0x7F, 0x00, 0x00}, " 0.5 x 2^127"},
{{0x40, 0x00, 0x00, 0x00, 0x00, 0x00}, " 0.5 x 2^0"},
{{0x40, 0x00, 0x00, 0xFF, 0x00, 0x00}, " 0.5 x 2^-1"},
{{0x40, 0x00, 0x00, 0x80, 0x00, 0x00}, " 0.5 x 2^-128"},
{{0x80, 0x00, 0x00, 0x7F, 0x00, 0x00}, " -1.0 x 2^127"},
{{0x80, 0x00, 0x00, 0x00, 0x00, 0x00}, " -1.0 x 2^0"},
{{0x80, 0x00, 0x00, 0xFF, 0x00, 0x00}, " -1.0 x 2^-1"},
{{0x80, 0x00, 0x00, 0x80, 0x00, 0x00}, " -1.0 x 2^-128"},
{{0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, " 0.0 x 2^0"},
{{0xA0, 0x00, 0x00, 0xFF, 0x00, 0x00}, "-0.75 x 2^-1"},
{{0, 0, 0, 0, 0, 0}, NULL}
} ;
int main (
int argc,
char *argv[])
{ /* Local variables. */
uint8_t buffer[6] ;
double mantissa, value ;
int exponent, i ;
printf ("1750A 16-bit Floating-Point:\n") ;
for (i = 0 ; examples16[i].result != NULL ; i++) {
value = f1750a2double (16, examples16[i].buffer) ;
mantissa = frexp (value, &exponent) ;
if (mantissa == -0.5) {
mantissa *= 2.0 ; exponent-- ;
}
double2f1750a (value, 16, buffer) ;
printf ("0x%02X%02X %11.8g x 2^%d\t(%s)\t(0x%02X%02X)\n",
buffer[0], buffer[1],
mantissa, exponent, examples16[i].result,
examples16[i].buffer[0], examples16[i].buffer[1]) ;
}
printf ("\n1750A 32-bit Floating-Point:\n") ;
for (i = 0 ; examples32[i].result != NULL ; i++) {
value = f1750a2double (32, examples32[i].buffer) ;
mantissa = frexp (value, &exponent) ;
if (mantissa == -0.5) {
mantissa *= 2.0 ; exponent-- ;
}
double2f1750a (value, 32, buffer) ;
printf ("0x%02X%02X%02X%02X %11.8g x 2^%d\t(%s)\t(0x%02X%02X%02X%02X)\n",
buffer[0], buffer[1], buffer[2], buffer[3],
mantissa, exponent, examples32[i].result,
examples32[i].buffer[0], examples32[i].buffer[1],
examples32[i].buffer[2], examples32[i].buffer[3]) ;
}
printf ("\n1750A 48-bit Floating-Point:\n") ;
for (i = 0 ; examples48[i].result != NULL ; i++) {
value = f1750a2double (48, examples48[i].buffer) ;
mantissa = frexp (value, &exponent) ;
if (mantissa == -0.5) {
mantissa *= 2.0 ; exponent-- ;
}
double2f1750a (value, 48, buffer) ;
printf ("0x%02X%02X%02X%02X%02X%02X %11.8g x 2^%d\t(%s)\t(0x%02X%02X%02X%02X%02X%02X)\n",
buffer[0], buffer[1], buffer[2],
buffer[3], buffer[4], buffer[5],
mantissa, exponent, examples48[i].result,
examples48[i].buffer[0], examples48[i].buffer[1],
examples48[i].buffer[2], examples48[i].buffer[3],
examples48[i].buffer[4], examples48[i].buffer[5]) ;
}
exit (0) ;
}
#endif
| 2.6875 | 3 |
2024-11-18T20:55:41.819902+00:00 | 2018-02-17T00:05:31 | 20d5999ff0638e7d0557104df6c4de14a40a3689 | {
"blob_id": "20d5999ff0638e7d0557104df6c4de14a40a3689",
"branch_name": "refs/heads/windows",
"committer_date": "2018-02-17T00:05:31",
"content_id": "146bbd5315089659fe806ff2befa76deef80f813",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "a7803d38c49c393009bd85ce54659bb8678840b8",
"extension": "c",
"filename": "llmputil.c",
"fork_events_count": 1,
"gha_created_at": "2017-10-21T16:00:43",
"gha_event_created_at": "2021-08-06T09:12:35",
"gha_language": "C",
"gha_license_id": "NOASSERTION",
"github_id": 107794254,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 9480,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/tools/shared/llmputil.c",
"provenance": "stackv2-0092.json.gz:46453",
"repo_name": "isuruf/flang",
"revision_date": "2018-02-17T00:05:31",
"revision_id": "e160efee8cd4603f57ad2fcab5f3ab42c6ada972",
"snapshot_id": "6f86265a529a22859f352bf4d528f6032c5d765e",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/isuruf/flang/e160efee8cd4603f57ad2fcab5f3ab42c6ada972/tools/shared/llmputil.c",
"visit_date": "2022-06-13T19:20:55.548223"
} | stackv2 | /*
* Copyright (c) 2017, NVIDIA CORPORATION. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/* llmputil.c: OpenMP utility routines for our LLVM compilers */
#include "gbldefs.h"
#include "global.h"
#include "error.h"
#include "llmputil.h"
#include "symtab.h"
#ifdef FE90
#include "dtypeutl.h"
#endif
/* Global container of uplevel pointers */
static struct {
LLUplevel *base; /* Pointer to the allocated array of items */
int size; /* Total size including unused items */
int avl; /* Total items in use */
} llmp_all_uplevels;
/* Global container of task pointers */
static struct {
LLTask *base; /* Pointer to the allocated array of items */
int size; /* Total size including unused items */
int avl; /* Total items in use */
} llmp_all_tasks;
static LLUplevel *
get_uplevel(int stblock_sptr)
{
int key;
LLUplevel *up;
assert(STYPEG(stblock_sptr) == ST_BLOCK, "Uplevel key must be an ST_BLOCK",
stblock_sptr, 4);
/* Index */
key = PARSYMSG(stblock_sptr);
/* Locate uplevel pointer */
up = NULL;
if (key <= llmp_all_uplevels.avl)
up = (LLUplevel *)(&llmp_all_uplevels.base[key]);
assert(up && key, "Could not locate uplevel instance for stblock",
stblock_sptr, 4);
return up;
}
LLUplevel *
llmp_create_uplevel(int stblock_sptr)
{
int key;
LLUplevel *up;
assert(STYPEG(stblock_sptr) == ST_BLOCK, "Uplevel key must be an ST_BLOCK",
stblock_sptr, 4);
/* Avoid processing an already created uplevel */
if (PARSYMSG(stblock_sptr))
return get_uplevel(stblock_sptr);
/* Make room if necessary */
if (llmp_all_uplevels.avl == 0) {
llmp_all_uplevels.avl = 2;
key = 1;
} else {
key = llmp_all_uplevels.avl;
++llmp_all_uplevels.avl;
}
NEED(llmp_all_uplevels.avl, llmp_all_uplevels.base, LLUplevel,
llmp_all_uplevels.size, llmp_all_uplevels.size + 8);
up = (LLUplevel *)(&llmp_all_uplevels.base[key]);
memset(up, 0, sizeof(LLUplevel));
/* Add key and map it to stblock */
PARSYMSP(stblock_sptr, key);
return up;
}
LLUplevel *
llmp_get_uplevel(int stblock_sptr)
{
return get_uplevel(stblock_sptr);
}
void
llmp_uplevel_set_dtype(LLUplevel *up, int dtype)
{
up->dtype = dtype;
}
/* Uniquely add shared_sptr to up */
int
llmp_add_shared_var(LLUplevel *up, int shared_sptr)
{
int i;
const int idx = up->vals_count;
/* Unique add: I really wanted to make this a hashset... */
for (i = 0; i < up->vals_count; ++i){
if (shared_sptr == 0)
break;
if (up->vals[i] == shared_sptr)
return 0;
}
++up->vals_count;
NEED(up->vals_count, up->vals, int, up->vals_size, up->vals_size + 8);
up->vals[idx] = shared_sptr;
return 1;
}
/* add 0 as placeholder for character len sptr for shared_sptr */
void
llmp_add_shared_var_charlen(LLUplevel *up, int shared_sptr)
{
int i;
const int idx = up->vals_count;
/* Unique add: I really wanted to make this a hashset... */
for (i = 0; i < up->vals_count; ++i)
if (up->vals[i] == shared_sptr) {
++up->vals_count;
NEED(up->vals_count, up->vals, int, up->vals_size, up->vals_size + 8);
up->vals[idx] = 0;
}
}
/* Return a new key (index) into our table of all uplevels */
int
llmp_get_next_key(void)
{
int key;
if (llmp_all_uplevels.avl == 0) {
llmp_all_uplevels.avl = 2;
key = 1;
} else {
key = llmp_all_uplevels.avl;
++llmp_all_uplevels.avl;
}
NEED(llmp_all_uplevels.avl, llmp_all_uplevels.base, LLUplevel,
llmp_all_uplevels.size, llmp_all_uplevels.size + 8);
return key;
}
/* Return the uplevel for a specific key (index into our table of uplevels) */
LLUplevel *
llmp_create_uplevel_bykey(int key)
{
LLUplevel *up;
assert(key <= llmp_all_uplevels.avl, "Invalid uplevel key", key, 4);
up = (LLUplevel *)(&llmp_all_uplevels.base[key]);
memset(up, 0, sizeof(LLUplevel));
return up;
}
void
llmp_reset_uplevel(void)
{
int i, j;
LLUplevel *up;
LLTask *task;
if (llmp_all_uplevels.avl) {
for (i = 1; i < llmp_all_uplevels.avl; ++i) {
up = (LLUplevel *)(&llmp_all_uplevels.base[i]);
if (up->vals_count)
FREE(up->vals);
}
FREE(llmp_all_uplevels.base);
memset(&llmp_all_uplevels, 0, sizeof(llmp_all_uplevels));
}
if (llmp_all_tasks.avl) {
for (i = 0; llmp_all_tasks.avl; ++i) {
task = (LLTask*)(&llmp_all_tasks.base[i]);
if (task->privs_count) {
FREE(task->privs);
}
FREE(llmp_all_tasks.base);
memset(&llmp_all_tasks, 0, sizeof(llmp_all_tasks));
}
}
llmp_all_uplevels.avl = 0;
llmp_all_tasks.avl = 0;
}
LLTask *
llmp_get_task(int scope_sptr)
{
int i;
for (i = 0; i < llmp_all_tasks.avl; ++i) {
LLTask *task = (LLTask *)&llmp_all_tasks.base[i];
if (task->scope_sptr == scope_sptr)
return task;
}
return NULL;
}
LLTask *
llmp_create_task(int scope_sptr)
{
int key;
LLTask *task;
NEED(llmp_all_tasks.avl + 1, llmp_all_tasks.base, LLTask, llmp_all_tasks.size,
llmp_all_tasks.size + 4);
task = (LLTask *)(&llmp_all_tasks.base[llmp_all_tasks.avl]);
++llmp_all_tasks.avl;
memset(task, 0, sizeof(LLTask));
task->actual_size = llmp_task_get_base_task_size();
task->scope_sptr = scope_sptr;
return task;
}
/* Return the size of an empty KMPC task (no shared variables):
* Pointer + Pointer + int32(+pad) +
* kmp_cmplrdata_t(data1) + kmp_cmplrdata_t(data2)
* see kmp.h
*/
int
llmp_task_get_base_task_size(void)
{
int pad = sizeof(void*) - sizeof(int);
#ifdef TARGET_WIN
return sizeof(void *) + sizeof(void *) + sizeof(int) +
pad + sizeof(void*)*2;
#else
return sizeof(void *) + sizeof(void *) + sizeof(int32_t) +
pad + sizeof(void*)*2;
#endif
}
/* Return the size of a KMPC equivalent task (base + size of privates) */
int
llmp_task_get_size(LLTask *task)
{
return task->actual_size;
}
/* Set the fnsptr that belongs to the outlined task */
void
llmp_task_set_fnsptr(LLTask *task, int task_sptr)
{
task->task_sptr = task_sptr;
}
/* Return the task object associated with 'task_sptr' */
LLTask *
llmp_task_get_by_fnsptr(int task_sptr)
{
int i;
LLTask *task;
for (i = 0; i < llmp_all_tasks.avl; ++i) {
LLTask *task = (LLTask *)&llmp_all_tasks.base[i];
if (task->task_sptr == task_sptr) {
return task;
}
}
return NULL;
}
int
llmp_task_add_private(LLTask *task, int shared_sptr, int private_sptr)
{
int pad = 0;
int size;
int align;
int offset = 0;
DTYPE dtype;
LLFirstPrivate *fp;
int idx = task->privs_count;
NEED(++task->privs_count, task->privs, LLFirstPrivate,
task->privs_size, task->privs_size + 4);
/* Create the private object */
fp = (LLFirstPrivate *)&(task->privs[idx]);
fp->private_sptr = private_sptr;
fp->shared_sptr = shared_sptr;
/* Bump up the size of the task to contain private_sptr */
#ifdef FE90
task->actual_size += size_of_var(private_sptr);
#else
dtype = DTYPEG(private_sptr);
if (dtype) {
size = zsize_of(dtype);
align = alignment(dtype);
pad = ALIGN(task->actual_size, align) - task->actual_size;
task->actual_size += pad;
}
offset = task->actual_size;
task->actual_size += size_of_sym(private_sptr);
#endif
return offset;
}
int
llmp_task_add_loopvar(LLTask *task, int num, int dtype)
/* put loop variables on task_alloc array after private vars */
{
int pad = 0;
int size;
int align;
int offset = 0;
#ifdef FE90
/* we add it to backend only */
#else
/* Bump up the size of the task to contain loop var and make sure
* it is integer*64 aligned.
*/
size = zsize_of(dtype) * num;
align = alignment(dtype);
pad = ALIGN(task->actual_size, align) - task->actual_size;
task->actual_size += pad;
offset = task->actual_size;
task->actual_size += size;
#endif
return offset;
}
void
llmp_task_add(int scope_sptr, int shared_sptr, int private_sptr)
{
LLTask *task;
assert(scope_sptr && STYPEG(scope_sptr) == ST_BLOCK,
"Task key must be a scope sptr (ST_BLOCK)", scope_sptr, 4);
task = llmp_get_task(scope_sptr);
if (!task)
task = llmp_create_task(scope_sptr);
llmp_task_add_private(task, shared_sptr, private_sptr);
}
int
llmp_task_get_private(const LLTask *task, int sptr, int encl)
{
int i;
for (i = 0; i < task->privs_count; ++i) {
const int pr = task->privs[i].private_sptr;
if (sptr == pr && TASKG(sptr)
#ifndef FE90
&& is_llvm_local_private(sptr)
#endif
)
return pr;
}
return 0;
}
/* should call in taskdup only */
INT
llmp_task_get_privoff(int sptr, const LLTask *task)
{
int i;
for (i = 0; i < task->privs_count; ++i) {
const int pr = task->privs[i].shared_sptr;
if (sptr == pr)
return ADDRESSG(task->privs[i].private_sptr);
}
return 0;
}
void
llmp_concur_add_shared_var(int stblock_sptr, int shared_sptr)
{
int dtype;
LLUplevel *up;
up = llmp_create_uplevel(stblock_sptr);
(void)llmp_add_shared_var(up, shared_sptr);
}
| 2.328125 | 2 |
2024-11-18T20:55:42.053928+00:00 | 2018-02-21T15:44:51 | bc2b4b64d81cb8193e0910df7caf6567bb19edf4 | {
"blob_id": "bc2b4b64d81cb8193e0910df7caf6567bb19edf4",
"branch_name": "refs/heads/master",
"committer_date": "2018-02-21T15:44:51",
"content_id": "8d6326477821e6158c192c58f408207223d12d3b",
"detected_licenses": [
"BSD-3-Clause",
"BSD-2-Clause"
],
"directory_id": "5c1c6fe8ad7c8e35e1e310c673c8f6dcb71eb39a",
"extension": "c",
"filename": "tdinterp.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 122355325,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 26305,
"license": "BSD-3-Clause,BSD-2-Clause",
"license_type": "permissive",
"path": "/src/tdinterp/tdinterp.c",
"provenance": "stackv2-0092.json.gz:46712",
"repo_name": "IPOL-Fork/iminterp",
"revision_date": "2018-02-21T15:44:51",
"revision_id": "f3ca130e2b7d849f236d1a46d23b4f35ab6596f0",
"snapshot_id": "64f5a0302e89c89562ed91553b7e3985f92cc1bd",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/IPOL-Fork/iminterp/f3ca130e2b7d849f236d1a46d23b4f35ab6596f0/src/tdinterp/tdinterp.c",
"visit_date": "2021-09-07T10:20:18.758299"
} | stackv2 | /**
* @file tdinterp.c
* @brief Roussos-Maragos interpolation by tensor-driven diffusion
* @author Pascal Getreuer <getreuer@gmail.com>
*
*
* This program is free software: you can use, modify and/or
* redistribute it under the terms of the simplified BSD License. You
* should have received a copy of this license along this program. If
* not, see <http://www.opensource.org/licenses/bsd-license.html>.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <fftw3.h>
#include "basic.h"
#include "finterp.h"
#include "tdinterp.h"
#include "conv.h"
/** @brief Compute the X-derivative for Weicker-Scharr scheme */
static void XDerivative(float *Dest, float *ConvTemp, const float *Src,
int Width, int Height)
{
int i, il, ir, y;
int iEnd;
for(y = 0, i = 0, iEnd = -1; y < Height; y++)
{
ConvTemp[i] = Src[i + 1] - Src[i];
i++;
for(iEnd += Width; i < iEnd; i++)
ConvTemp[i] = Src[i + 1] - Src[i - 1];
ConvTemp[i] = Src[i] - Src[i - 1];
i++;
}
for(y = 0, i = iEnd = 0; y < Height; y++)
{
il = (y > 0) ? -Width : 0;
ir = (y < Height - 1) ? Width : 0;
for(iEnd += Width; i < iEnd; i++)
Dest[i] = 0.3125f*ConvTemp[i]
+ 0.09375f*(ConvTemp[i + ir] + ConvTemp[i + il]);
}
}
/** @brief Compute the Y-derivative for Weicker-Scharr scheme */
static void YDerivative(float *Dest, float *ConvTemp, const float *Src,
int Width, int Height)
{
int i, il, ir, iEnd, y;
for(y = 0, i = iEnd = 0; y < Height; y++)
{
il = (y > 0) ? -Width : 0;
ir = (y < Height - 1) ? Width : 0;
for(iEnd += Width; i < iEnd; i++)
ConvTemp[i] = Src[i + ir] - Src[i + il];
}
for(y = 0, i = 0, iEnd = -1; y < Height; y++)
{
Dest[i] = 0.40625f*ConvTemp[i] + 0.09375f*ConvTemp[i + 1];
i++;
for(iEnd += Width; i < iEnd; i++)
Dest[i] = 0.3125f*ConvTemp[i]
+ 0.09375f*(ConvTemp[i + 1] + ConvTemp[i - 1]);
Dest[i] = 0.40625f*ConvTemp[i] + 0.09375f*ConvTemp[i - 1];
i++;
}
}
/** @brief Construct the tensor T */
static void ComputeTensor(float *Txx, float *Txy, float *Tyy,
float *uSmooth, float *ConvTemp, const float *u, int Width, int Height,
filter PreSmooth, filter PostSmooth, double K)
{
const float dt = 2;
const double KSquared = K*K;
const int NumPixels = Width*Height;
const int NumEl = 3*NumPixels;
boundaryext Boundary = GetBoundaryExt("sym");
double Tm, SqrtTm, Trace, Lambda1, Lambda2, EigVecX, EigVecY, Temp;
float ux, uy;
int i, iu, id, il, ir, x, y, Channel;
/* Set the tensor to zero and perform pre-smoothing on u. Note that it is
not safely portable to use memset for this purpose.
http://c-faq.com/malloc/calloc.html */
#ifdef _OPENMP
#pragma omp parallel sections private(i)
{ /* The following six operations can run in parallel */
#pragma omp section
{
for(i = 0; i < NumPixels; i++)
Txx[i] = 0.0f;
}
#pragma omp section
{
for(i = 0; i < NumPixels; i++)
Txy[i] = 0.0f;
}
#pragma omp section
{
for(i = 0; i < NumPixels; i++)
Tyy[i] = 0.0f;
}
#pragma omp section
{
SeparableConv2D(uSmooth,
ConvTemp, u,
PreSmooth, PreSmooth, Boundary, Width, Height, 1);
}
#pragma omp section
{
SeparableConv2D(uSmooth + NumPixels,
ConvTemp + NumPixels, u + NumPixels,
PreSmooth, PreSmooth, Boundary, Width, Height, 1);
}
#pragma omp section
{
SeparableConv2D(uSmooth + 2*NumPixels,
ConvTemp + 2*NumPixels, u + 2*NumPixels,
PreSmooth, PreSmooth, Boundary, Width, Height, 1);
}
}
#else
for(i = 0; i < NumPixels; i++)
Txx[i] = 0.0f;
for(i = 0; i < NumPixels; i++)
Txy[i] = 0.0f;
for(i = 0; i < NumPixels; i++)
Tyy[i] = 0.0f;
SeparableConv2D(uSmooth, ConvTemp, u,
PreSmooth, PreSmooth, Boundary, Width, Height, 3);
#endif
/* Compute the structure tensor */
for(Channel = 0; Channel < NumEl; Channel += NumPixels)
{
for(y = 0, i = 0; y < Height; y++)
{
iu = (y > 0) ? -Width : 0;
id = (y < Height - 1) ? Width : 0;
for(x = 0; x < Width; x++, i++)
{
il = (x > 0) ? -1 : 0;
ir = (x < Width - 1) ? 1 : 0;
ux = (uSmooth[i + ir + Channel]
- uSmooth[i + il + Channel]) / 2;
uy = (uSmooth[i + id + Channel]
- uSmooth[i + iu + Channel]) / 2;
Txx[i] += ux * ux;
Txy[i] += ux * uy;
Tyy[i] += uy * uy;
}
}
}
/* Perform the post-smoothing convolution with PostSmooth */
#ifdef _OPENMP
#pragma omp parallel sections
{
#pragma omp section
{
SeparableConv2D(Txx, ConvTemp, Txx,
PostSmooth, PostSmooth, Boundary, Width, Height, 1);
}
#pragma omp section
{
SeparableConv2D(Txy, ConvTemp + NumPixels, Txy,
PostSmooth, PostSmooth, Boundary, Width, Height, 1);
}
#pragma omp section
{
SeparableConv2D(Tyy, ConvTemp + 2*NumPixels, Tyy,
PostSmooth, PostSmooth, Boundary, Width, Height, 1);
}
}
#else
SeparableConv2D(Txx, ConvTemp, Txx,
PostSmooth, PostSmooth, Boundary, Width, Height, 1);
SeparableConv2D(Txy, ConvTemp, Txy,
PostSmooth, PostSmooth, Boundary, Width, Height, 1);
SeparableConv2D(Tyy, ConvTemp, Tyy,
PostSmooth, PostSmooth, Boundary, Width, Height, 1);
#endif
/* Refactor the structure tensor */
for(i = 0; i < NumPixels; i++)
{
/* Compute the eigenspectra */
Trace = 0.5*(Txx[i] + Tyy[i]);
Temp = sqrt(Trace*Trace - Txx[i]*Tyy[i] + Txy[i]*Txy[i]);
Lambda1 = Trace - Temp;
Lambda2 = Trace + Temp;
EigVecX = Txy[i];
EigVecY = Lambda1 - Txx[i];
Temp = sqrt(EigVecX*EigVecX + EigVecY*EigVecY);
if(Temp >= 1e-9)
{
EigVecX /= Temp;
EigVecY /= Temp;
Tm = KSquared/(KSquared + (Lambda1 + Lambda2));
SqrtTm = sqrt(Tm);
/* Construct new tensor from the spectra */
Txx[i] = (float)(dt*(SqrtTm*EigVecX*EigVecX + Tm*EigVecY*EigVecY));
Txy[i] = (float)(dt*((SqrtTm - Tm)*EigVecX*EigVecY));
Tyy[i] = (float)(dt*(SqrtTm*EigVecY*EigVecY + Tm*EigVecX*EigVecX));
}
else
{
Txx[i] = dt;
Txy[i] = 0.0f;
Tyy[i] = dt;
}
}
}
/** @brief Perform 5x5 Weicker-Scharr explicit diffusion steps */
static void DiffuseWithTensor(float *u, float *vx, float *vy,
float *SumX, float *SumY,
float *ConvTemp, const float *Txx, const float *Txy, const float *Tyy,
int Width, int Height, int DiffIter)
{
const int NumPixels = Width*Height;
int i, Channel, Step;
for(Channel = 0; Channel < 3; Channel++, u += NumPixels)
{
for(Step = 0; Step < DiffIter; Step++)
{
#ifdef _OPENMP
#pragma omp parallel
{
#pragma omp sections
{ /* XDerivative and YDerivative can run in parallel */
#pragma omp section
{
XDerivative(vx, ConvTemp, u, Width, Height);
}
#pragma omp section
{
YDerivative(vy, ConvTemp + NumPixels, u, Width, Height);
}
}
#pragma omp for schedule(static)
for(i = 0; i < NumPixels; i++)
{
SumX[i] = Txx[i]*vx[i] + Txy[i]*vy[i];
SumY[i] = Txy[i]*vx[i] + Tyy[i]*vy[i];
}
#pragma omp sections
{ /* XDerivative and YDerivative can run in parallel */
#pragma omp section
{
XDerivative(SumX, ConvTemp,
SumX, Width, Height);
}
#pragma omp section
{
YDerivative(SumY, ConvTemp + NumPixels,
SumY, Width, Height);
}
}
#pragma omp for schedule(static)
for(i = 0; i < NumPixels; i++)
u[i] += SumX[i] + SumY[i];
}
#else
XDerivative(vx, ConvTemp, u, Width, Height);
YDerivative(vy, ConvTemp, u, Width, Height);
for(i = 0; i < NumPixels; i++)
{
SumX[i] = Txx[i]*vx[i] + Txy[i]*vy[i];
SumY[i] = Txy[i]*vx[i] + Tyy[i]*vy[i];
}
XDerivative(SumX, ConvTemp, SumX, Width, Height);
YDerivative(SumY, ConvTemp, SumY, Width, Height);
for(i = 0; i < NumPixels; i++)
u[i] += SumX[i] + SumY[i];
#endif
}
}
}
/** @brief Sum aliases (used by MakePhi) */
static void SumAliases(float *u, int d, int Width, int Height)
{
const int BlockWidth = Width / d;
const int BlockHeight = Height / d;
const int StripSize = Width*BlockHeight;
float *Src, *Dest;
int k, x, y;
/* Sum along x for every y */
for(y = 0; y < Height; y++)
{
Dest = u + y*Width;
for(k = 1; k < d; k++)
{
Src = Dest + k*BlockWidth;
for(x = 0; x < BlockWidth; x++)
Dest[x] += Src[x];
}
}
/* Sum along y for 0 <= x < BlockWidth */
for(k = 1; k < d; k++)
{
Dest = u;
Src = u + Width*(k*BlockHeight);
for(y = 0; y < BlockHeight; y++)
{
for(x = 0; x < BlockWidth; x++)
Dest[x] += Src[x];
Dest += Width;
Src += Width;
}
}
/* Copy block [0, BlockWidth) x [0, BlockHeight) in the x direction*/
for(y = 0, Src = Dest = u; y < Height; y++, Src += Width)
{
for(k = 1, Dest += BlockWidth; k < d; k++, Dest += BlockWidth)
{
memcpy(Dest, Src, sizeof(float)*BlockWidth);
}
}
/* Copy strip [0, OutputWidth) x [0, InputHeight) in the y direction*/
for(k = 1, Dest = u + StripSize; k < d; k++, Dest += StripSize)
memcpy(Dest, u, sizeof(float)*StripSize);
}
/** @brief Precompute the function phi used in projections */
static void MakePhi(float *Phi, double PsfSigma, int d, int Width, int Height)
{
/* Number of terms to use in truncated sum, larger is more accurate */
const int NumOverlaps = 2;
const int NumPixels = Width*Height;
float *PhiLastRow;
float Sum, Sigma, Denom;
int i, x, y, t, k;
float *Temp;
Temp = (float *)Malloc(sizeof(float)*NumPixels);
/* Construct the Fourier transform of a Gaussian with spatial standard
* deviation d*PsfSigma. Using the Gaussian and the transform's
* separability, the result is formed as the tensor product of the 1D
* transforms. This significantly reduces the number of exp calls.
*/
if(PsfSigma == 0.0)
{
for(i = 0; i < NumPixels; i++)
Phi[i] = 1.0f;
}
else
{
Sigma = (float)(Width/(2*M_PI*d*PsfSigma));
Denom = 2*Sigma*Sigma;
PhiLastRow = Phi + Width*(Height - 1);
/* Construct the transform along x */
for(x = 0; x < Width; x++)
{
for(k = -NumOverlaps, Sum = 0; k < NumOverlaps; k++)
{
t = x + k*Width;
Sum += (float)exp(-(t*t)/Denom);
}
PhiLastRow[x] = Sum;
}
Sigma = (float)(Height/(2*M_PI*d*PsfSigma));
Denom = 2*Sigma*Sigma;
/* Construct the transform along y */
for(y = 0, i = 0; y < Height; y++, i += Width)
{
for(k = -NumOverlaps, Sum = 0; k < NumOverlaps; k++)
{
t = y + k*Height;
Sum += (float)exp(-(t*t)/Denom);
}
/* Tensor product */
for(x = 0; x < Width; x++)
Phi[x + i] = Sum*PhiLastRow[x];
}
}
/* Square all the elements so that Temp = abs(fft2(psf)).^2 */
for(i = 0; i < NumPixels; i++)
Temp[i] = Phi[i]*Phi[i];
SumAliases(Temp, d, Width, Height);
/* Obtain the projection kernel Phi in the Fourier domain */
for(i = 0; i < NumPixels; i++)
Phi[i] /= (float)sqrt(Temp[i] * NumPixels);
Free(Temp);
}
/** @brief Sum the Fourier aliases */
static void ImageSumAliases(float *u, int d, int Width, int Height,
int NumChannels)
{
const int BlockWidth = Width / d;
const int BlockWidth2 = 2*BlockWidth;
const int BlockHeight = Height / d;
const int StripSize = 2*Width*BlockHeight;
float *uChannel, *Src, *Dest;
int k, i, y, Channel;
for(Channel = 0; Channel < NumChannels; Channel++)
{
uChannel = u + 2*Width*Height*Channel;
/* Sum along x for every y */
for(y = 0; y < Height; y++)
{
Dest = uChannel + 2*Width*y;
for(k = 1; k < d; k++)
{
Src = Dest + 2*BlockWidth*k;
for(i = 0; i < BlockWidth2; i++)
Dest[i] += Src[i];
}
}
/* Sum along y for 0 <= x < BlockWidth */
for(k = 1; k < d; k++)
{
Dest = uChannel;
Src = uChannel + 2*Width*(BlockHeight*k);
for(y = 0; y < BlockHeight; y++)
{
for(i = 0; i < BlockWidth2; i++)
Dest[i] += Src[i];
Dest += 2*Width;
Src += 2*Width;
}
}
/* Copy block [0, BlockWidth) x [0, BlockHeight) in the x direction */
for(y = 0, Src = Dest = uChannel; y < Height; y++, Src += 2*Width)
{
for(k = 1, Dest += BlockWidth2; k < d; k++, Dest += BlockWidth2)
{
memcpy(Dest, Src, sizeof(float)*BlockWidth2);
}
}
/* Copy strip [0, OutputWidth) x [0, InputHeight) in the y direction */
for(k = 1, Dest = uChannel + StripSize; k < d; k++, Dest += StripSize)
memcpy(Dest, uChannel, sizeof(float)*StripSize);
}
}
/** @brief Complex multiply of Dest by Phi */
static void MultiplyByPhiInterleaved(float *Dest, const float *Phi,
int NumPixels, int NumChannels)
{
int i, Channel;
for(Channel = 0; Channel < NumChannels; Channel++, Dest += 2*NumPixels)
{
for(i = 0; i < NumPixels; i++)
{
Dest[2*i] *= Phi[i];
Dest[2*i + 1] *= Phi[i];
}
}
}
/** @brief Fill the redundant spectra in a Fourier transform */
static void MirrorSpectra(float *Dest, int Width, int Height, int NumChannels)
{
const int H = Width/2 + 1;
int i, sx, sy, x, y, Channel;
/* Fill in the redundant spectra */
for(Channel = 0, i = 0; Channel < NumChannels; Channel++)
{
for(y = 0; y < Height; y++)
{
sy = (y > 0) ? Height - y : 0;
sy = 2*Width*(sy + Height*Channel);
for(x = H, i += 2*H; x < Width; x++, i += 2)
{
sx = 2*(Width - x);
/* Set Dest(x,y,Channel) = conj(Dest(sx,sy,Channel)) */
Dest[i] = Dest[sx + sy];
Dest[i + 1] = -Dest[sx + sy + 1];
}
}
}
}
/** @brief Project u onto the solution set W_v */
static void Project(float *u, float *Temp, float *ConvTemp,
fftwf_plan ForwardPlan, fftwf_plan InversePlan, const float *u0,
const float *Phi, int ScaleFactor,
int OutputWidth, int OutputHeight, int Padding)
{
const int OutputNumPixels = OutputWidth*OutputHeight;
const int OutputNumEl = 3*OutputNumPixels;
int TransWidth, TransHeight, TransNumPixels;
int i, x, y, sx, sy, OffsetX, OffsetY, Channel;
TransWidth = OutputWidth + 2*Padding*ScaleFactor;
TransHeight = OutputHeight + 2*Padding*ScaleFactor;
if(TransWidth > 2*OutputWidth)
TransWidth = 2*OutputWidth;
if(TransHeight > 2*OutputHeight)
TransHeight = 2*OutputHeight;
TransNumPixels = TransWidth*TransHeight;
OffsetX = (TransWidth - OutputWidth)/2;
OffsetY = (TransHeight - OutputHeight)/2;
OffsetX -= OffsetX % ScaleFactor;
OffsetY -= OffsetY % ScaleFactor;
for(Channel = 0, i = 0; Channel < OutputNumEl; Channel += OutputNumPixels)
{
for(y = 0; y < TransHeight; y++)
{
sy = y - OffsetY;
while(1)
{
if(sy < 0)
sy = -1 - sy;
else if(sy >= OutputHeight)
sy = 2*OutputHeight - 1 - sy;
else
break;
}
for(x = 0; x < TransWidth; x++, i++)
{
sx = x - OffsetX;
while(1)
{
if(sx < 0)
sx = -1 - sx;
else if(sx >= OutputWidth)
sx = 2*OutputWidth - 1 - sx;
else
break;
}
Temp[i] = u[sx + OutputWidth*sy + Channel]
- u0[sx + OutputWidth*sy + Channel];
}
}
}
fftwf_execute(ForwardPlan);
MirrorSpectra(ConvTemp, TransWidth, TransHeight, 3);
MultiplyByPhiInterleaved(ConvTemp, Phi, TransNumPixels, 3);
ImageSumAliases(ConvTemp, ScaleFactor, TransWidth, TransHeight, 3);
MultiplyByPhiInterleaved(ConvTemp, Phi, TransNumPixels, 3);
fftwf_execute(InversePlan);
/* Subtract a halved version of Temp from u */
Temp += OffsetX + TransWidth*OffsetY;
for(Channel = 0, i = 0; Channel < 3; Channel++)
{
for(y = 0; y < OutputHeight; y++)
{
for(x = 0; x < OutputWidth; x++, i++)
{
u[i] -= Temp[x + TransWidth*y];
}
}
Temp += TransNumPixels;
}
}
static float ComputeDiff(const float *u, const float *uLast,
int OutputNumEl)
{
float Temp, Diff = 0;
int i;
for(i = 0; i < OutputNumEl; i++)
{
Temp = u[i] - uLast[i];
Diff += Temp*Temp;
}
return sqrt(Diff/OutputNumEl);
}
/**
* @brief Roussos-Maragos interpolation by tensor-driven diffusion
*
* @param u pointer to memory for holding the interpolated image
* @param OutputWidth, OutputHeight output image dimensions
* @param Input the input image
* @param InputWidth, InputHeight input image dimensions
* @param PsfSigma Gaussian PSF standard deviation
* @param K parameter for constructing the tensor
* @param Tol convergence tolerance
* @param MaxMethodIter maximum number of iterations
* @param DiffIter number of diffusion iterations per method iteration
*
* @return 1 on success, 0 on failure
*
* This routine implements the projected tensor-driven diffusion method of
* Roussos and Maragos. Following Tschumperle, a tensor T is formed from the
* eigenspectra of the image structure tensor, and the image is diffused as
* \f[ \partial_t u = \operatorname{div}(T \nabla u). \f]
* In this implementation, the fast 5x5 explicit filtering scheme proposed by
* Weickert and Scharr is used to evolve the diffusion. The diffusion is
* orthogonally projected onto the feasible set (the set of images for which
* convolution with the PSF followed by downsampling recovers the input image).
* Projection is done in the Fourier domain, this is the main computational
* bottleneck of the method (approximately 60% of the run time is spent in DFT
* transforms).
*
* Beware that this routine is relatively computationally intense, requiring
* around 2 to 20 seconds for outputs of typical sizes. Multithreading is
* applied in some computations if compiling with OpenMP. Multithreading
* appears to have little effect for smaller images but reduces run time by
* about 25% for larger images.
*/
int RoussosInterp(float *u, int OutputWidth, int OutputHeight,
const float *Input, int InputWidth, int InputHeight, double PsfSigma,
double K, float Tol, int MaxMethodIter, int DiffIter)
{
const int Padding = 5;
const int OutputNumPixels = OutputWidth*OutputHeight;
const int OutputNumEl = 3*OutputNumPixels;
float *u0 = NULL, *Txx = NULL, *Txy = NULL, *Tyy = NULL, *Temp = NULL,
*ConvTemp = NULL, *vx = NULL, *vy = NULL, *Phi = NULL, *uLast = NULL;
fftwf_plan ForwardPlan = 0, InversePlan = 0;
fftw_iodim Dims[2];
fftw_iodim HowManyDims[1];
filter PreSmooth = {NULL, 0, 0}, PostSmooth = {NULL, 0, 0};
float PreSmoothSigma, PostSmoothSigma, Diff;
unsigned long StartTime, StopTime;
int TransWidth, TransHeight, TransNumPixels;
int Iter, ScaleFactor, Success = 0;
ScaleFactor = OutputWidth / InputWidth;
PreSmoothSigma = 0.3f * ScaleFactor;
PostSmoothSigma = 0.4f * ScaleFactor;
TransWidth = OutputWidth + 2*Padding*ScaleFactor;
TransHeight = OutputHeight + 2*Padding*ScaleFactor;
if(TransWidth > 2*OutputWidth)
TransWidth = 2*OutputWidth;
if(TransHeight > 2*OutputHeight)
TransHeight = 2*OutputHeight;
TransNumPixels = TransWidth*TransHeight;
printf("Initial interpolation\n");
if(!FourierScale2d(u, OutputWidth, 0, OutputHeight, 0,
Input, InputWidth, InputHeight, 3, PsfSigma, BOUNDARY_HSYMMETRIC))
goto Catch;
else if(MaxMethodIter <= 0)
{
Success = 1;
goto Catch;
}
/* Allocate a fantastic amount of memory */
if(ScaleFactor <= 1
|| OutputWidth != ScaleFactor*InputWidth
|| OutputHeight != ScaleFactor*InputHeight
|| !(ConvTemp = (float *)fftwf_malloc(sizeof(float)*24*OutputNumPixels))
|| !(Temp = (float *)fftwf_malloc(sizeof(float)*12*OutputNumPixels))
|| !(Phi = (float *)Malloc(sizeof(float)*4*OutputNumPixels))
|| !(u0 = (float *)Malloc(sizeof(float)*3*OutputNumPixels))
|| !(uLast = (float *)Malloc(sizeof(float)*3*OutputNumPixels))
|| !(Txx = (float *)Malloc(sizeof(float)*OutputNumPixels))
|| !(Txy = (float *)Malloc(sizeof(float)*OutputNumPixels))
|| !(Tyy = (float *)Malloc(sizeof(float)*OutputNumPixels))
|| !(vx = (float *)Malloc(sizeof(float)*OutputNumPixels))
|| !(vy = (float *)Malloc(sizeof(float)*OutputNumPixels))
|| IsNullFilter(PreSmooth = GaussianFilter(PreSmoothSigma,
(int)ceil(2.5*PreSmoothSigma)))
|| IsNullFilter(PostSmooth = GaussianFilter(PostSmoothSigma,
(int)ceil(2.5*PostSmoothSigma))))
goto Catch;
/* All arrays in the main computation are in planar order so that data
access in convolutions and DFTs are more localized. */
HowManyDims[0].n = 3;
HowManyDims[0].is = TransNumPixels;
HowManyDims[0].os = TransNumPixels;
Dims[0].n = TransHeight;
Dims[0].is = TransWidth;
Dims[0].os = TransWidth;
Dims[1].n = TransWidth;
Dims[1].is = 1;
Dims[1].os = 1;
/* Create plans for the 2D DFT of Src (vectorized over channels).
* After applying the forward transform,
* Dest[2*(x + Width*(y + Height*k))] = real component of (x,y,k)th
* Dest[2*(x + Width*(y + Height*k)) + 1] = imag component of (x,y,k)th
* where for 0 <= x < Width/2 + 1, 0 <= y < Height.
*/
if(!(ForwardPlan = fftwf_plan_guru_dft_r2c(2, Dims, 1, HowManyDims,
Temp, (fftwf_complex *)ConvTemp, FFTW_ESTIMATE | FFTW_DESTROY_INPUT))
|| !(InversePlan = fftwf_plan_guru_dft_c2r(2, Dims, 1, HowManyDims,
(fftwf_complex *)ConvTemp, Temp, FFTW_ESTIMATE | FFTW_DESTROY_INPUT)))
goto Catch;
printf("Roussos-Maragos interpolation\n");
StartTime = Clock();
MakePhi(Phi, PsfSigma, ScaleFactor, TransWidth, TransHeight);
memcpy(u0, u, sizeof(float)*3*OutputNumPixels);
/* Projected tensor-driven diffusion main loop */
for(Iter = 1; Iter <= MaxMethodIter; Iter++)
{
memcpy(uLast, u, sizeof(float)*OutputNumEl);
ComputeTensor(Txx, Txy, Tyy, Temp, ConvTemp, u,
OutputWidth, OutputHeight, PreSmooth, PostSmooth, K);
DiffuseWithTensor(u, vx, vy, Temp, Temp + OutputNumPixels, ConvTemp,
Txx, Txy, Tyy, OutputWidth, OutputHeight, DiffIter);
Project(u, Temp, ConvTemp, ForwardPlan, InversePlan, u0, Phi,
ScaleFactor, OutputWidth, OutputHeight, Padding);
Diff = ComputeDiff(u, uLast, OutputNumEl);
if(Iter >= 2 && Diff <= Tol)
{
printf("Converged in %d iterations.\n", Iter);
break;
}
}
StopTime = Clock();
if(Diff > Tol)
printf("Maximum number of iterations exceeded.\n");
printf("CPU Time: %.3f s\n\n", 0.001*(StopTime - StartTime));
Success = 1;
Catch:
fftwf_destroy_plan(InversePlan);
fftwf_destroy_plan(ForwardPlan);
fftwf_cleanup();
Free(PostSmooth.Coeff);
Free(PreSmooth.Coeff);
Free(vy);
Free(vx);
Free(Tyy);
Free(Txy);
Free(Txx);
Free(uLast);
Free(u0);
Free(Phi);
if(Temp)
fftwf_free(Temp);
if(ConvTemp)
fftwf_free(ConvTemp);
return Success;
}
| 2.25 | 2 |
2024-11-18T20:55:42.641067+00:00 | 2019-07-15T19:53:28 | c80d4481a9bb5bfda87c644aeffb440298e6074f | {
"blob_id": "c80d4481a9bb5bfda87c644aeffb440298e6074f",
"branch_name": "refs/heads/master",
"committer_date": "2019-07-17T00:43:37",
"content_id": "cda3cc72d8c76ce608cc549f8ed591ec30a6ca53",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "56a7b6e3bd793f4dd49ba17cb6fdd7b54447ec1c",
"extension": "c",
"filename": "lens_quantile_bench.c",
"fork_events_count": 13,
"gha_created_at": "2016-02-25T19:25:14",
"gha_event_created_at": "2019-07-17T00:43:39",
"gha_language": "C",
"gha_license_id": "BSD-2-Clause",
"github_id": 52550804,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4295,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/test/lens_quantile_bench.c",
"provenance": "stackv2-0092.json.gz:47483",
"repo_name": "RAttab/optics",
"revision_date": "2019-07-15T19:53:28",
"revision_id": "d4189a4960ba4fc84b2b142cb146d1d4ace3d6a2",
"snapshot_id": "80d1341bff546a82ab5f4519a41c462e0bf43cdb",
"src_encoding": "UTF-8",
"star_events_count": 13,
"url": "https://raw.githubusercontent.com/RAttab/optics/d4189a4960ba4fc84b2b142cb146d1d4ace3d6a2/test/lens_quantile_bench.c",
"visit_date": "2020-05-21T22:59:27.105288"
} | stackv2 | /* lens_quantile_bench.c
Marina C., Jan 25, 20186
FreeBSD-style copyright and disclaimer apply
*/
#include "bench.h"
struct quantile_bench
{
struct optics *optics;
struct optics_lens *lens;
};
// -----------------------------------------------------------------------------
// record bench
// -----------------------------------------------------------------------------
void run_record_bench(struct optics_bench *b, void *data, size_t id, size_t n)
{
(void) id;
struct quantile_bench *bench = data;
optics_bench_start(b);
for (size_t i = 0; i < n; ++i)
optics_quantile_update(bench->lens, 50);
}
optics_test_head(lens_quantile_record_bench_st)
{
struct optics *optics = optics_create(test_name);
struct optics_lens *lens = optics_quantile_alloc(optics, "bob_the_quantile", 50, 0.90, 0.05);
struct quantile_bench bench = { optics, lens };
optics_bench_st(test_name, run_record_bench, &bench);
optics_close(optics);
}
optics_test_tail()
optics_test_head(lens_quantile_record_bench_mt)
{
assert_mt();
struct optics *optics = optics_create(test_name);
struct optics_lens *lens = optics_quantile_alloc(optics, "bob_the_quantile", 50, 0.90, 0.05);
struct quantile_bench bench = { optics, lens };
optics_bench_mt(test_name, run_record_bench, &bench);
optics_close(optics);
}
optics_test_tail()
// -----------------------------------------------------------------------------
// read bench
// -----------------------------------------------------------------------------
void run_read_bench(struct optics_bench *b, void *data, size_t id, size_t n)
{
(void) id;
struct quantile_bench *bench = data;
optics_epoch_t epoch = optics_epoch(bench->optics);
optics_bench_start(b);
for (size_t i = 0; i < n; ++i) {
struct optics_quantile value = {0};
optics_quantile_read(bench->lens, epoch, &value);
}
}
optics_test_head(lens_quantile_read_bench_st)
{
struct optics *optics = optics_create(test_name);
struct optics_lens *lens = optics_quantile_alloc(optics, "bob_the_quantile", 50, 0.90, 0.05);
struct quantile_bench bench = { optics, lens };
optics_bench_st(test_name, run_read_bench, &bench);
optics_close(optics);
}
optics_test_tail()
optics_test_head(lens_quantile_read_bench_mt)
{
assert_mt();
struct optics *optics = optics_create(test_name);
struct optics_lens *lens = optics_quantile_alloc(optics, "bob_the_quantile", 50, 0.90, 0.05);
struct quantile_bench bench = { optics, lens };
optics_bench_mt(test_name, run_read_bench, &bench);
optics_close(optics);
}
optics_test_tail()
// -----------------------------------------------------------------------------
// mixed bench
// -----------------------------------------------------------------------------
void run_mixed_bench(struct optics_bench *b, void *data, size_t id, size_t n)
{
struct quantile_bench *bench = data;
optics_epoch_t epoch = optics_epoch(bench->optics);
optics_bench_start(b);
if (!id) {
for (size_t i = 0; i < n; ++i) {
struct optics_quantile value = {0};
optics_quantile_read(bench->lens, epoch, &value);
}
}
else {
for (size_t i = 0; i < n; ++i)
optics_quantile_update(bench->lens, id);
}
}
optics_test_head(lens_quantile_mixed_bench_mt)
{
assert_mt();
struct optics *optics = optics_create(test_name);
struct optics_lens *lens = optics_quantile_alloc(optics, "bob_the_quantile", 50, 0.90, 0.05);
struct quantile_bench bench = { optics, lens };
optics_bench_mt(test_name, run_mixed_bench, &bench);
optics_close(optics);
}
optics_test_tail()
// -----------------------------------------------------------------------------
// setup
// -----------------------------------------------------------------------------
int main(void)
{
const struct CMUnitTest tests[] = {
cmocka_unit_test(lens_quantile_record_bench_st),
cmocka_unit_test(lens_quantile_record_bench_mt),
cmocka_unit_test(lens_quantile_read_bench_st),
cmocka_unit_test(lens_quantile_read_bench_mt),
cmocka_unit_test(lens_quantile_mixed_bench_mt)
};
return cmocka_run_group_tests(tests, NULL, NULL);
}
| 2.34375 | 2 |
2024-11-18T20:55:42.746113+00:00 | 2019-02-10T02:46:17 | e7f34223e9ace0804933736c937d09d43cb6d028 | {
"blob_id": "e7f34223e9ace0804933736c937d09d43cb6d028",
"branch_name": "refs/heads/master",
"committer_date": "2019-02-10T02:46:17",
"content_id": "011861e8360f3e3b8a5bb83574446c6e24ce8c32",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "6e747ddc6658b3e8cada4cc14269ba18d6f12322",
"extension": "c",
"filename": "SDLExVulkanRender.c",
"fork_events_count": 1,
"gha_created_at": "2018-09-08T04:18:36",
"gha_event_created_at": "2022-10-01T20:58:53",
"gha_language": "Python",
"gha_license_id": "Apache-2.0",
"github_id": 147900388,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 14343,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/YookaiC/Game/SDLEx/Vulkan/SDLExVulkanRender.c",
"provenance": "stackv2-0092.json.gz:47612",
"repo_name": "cn-s3bit/YookaiC",
"revision_date": "2019-02-10T02:46:17",
"revision_id": "5f4711ee4217544df9ebe683c1147db3b4c707d7",
"snapshot_id": "d0601e7df39e934bc93c5a323390ed615101f768",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/cn-s3bit/YookaiC/5f4711ee4217544df9ebe683c1147db3b4c707d7/YookaiC/Game/SDLEx/Vulkan/SDLExVulkanRender.c",
"visit_date": "2022-10-10T22:17:23.095803"
} | stackv2 | #include "SDLExVulkan.h"
#include "../Utils/MathUtils.h"
#include "../MathEx/MathEx.h"
#include "../Utils/ArrayList.h"
Vertex Vertices[6] = {
{ { 0.25f, -1.0f }, { 1.0f, 1.0f, 1.0f }, { 0.0f, 0.0f } },
{ { 0.25f, 1.0f }, { 1.0f, 1.0f, 1.0f }, { 0.0f, 1.0f } },
{ { 0.9f, 1.0f }, { 1.0f, 1.0f, 1.0f }, { 1.0f, 1.0f } },
{ { 0.25f, -1.0f }, { 1.0f, 1.0f, 1.0f }, { 0.0f, 0.0f } },
{ { 0.9f, -1.0f }, { 1.0f, 1.0f, 1.0f }, { 1.0f, 0.0f } },
{ { 0.9f, 1.0f }, { 1.0f, 1.0f, 1.0f }, { 1.0f, 1.0f } },
};
VkSemaphore imageAvailableSemaphore;
VkFence the_fence = VK_NULL_HANDLE;
ArrayList * batch_buffer;
#define VKRENDER_GLOBALS_INIT \
if (batch_buffer == NULL) {\
batch_buffer = create_array_list(sizeof(Vertices), 16u);\
}
unsigned sdlex_begin_frame() {
VKRENDER_GLOBALS_INIT
VkDevice device = get_vk_device();
SDLExVulkanSwapChain * swapchain = get_vk_swap_chain();
VkSemaphoreCreateInfo semaphoreInfo = { .sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO };
vkCreateSemaphore(device, &semaphoreInfo, NULL, &imageAvailableSemaphore);
unsigned imageIndex;
vkAcquireNextImageKHR(device, swapchain->SwapChain, SDL_MAX_SINT32,
imageAvailableSemaphore, VK_NULL_HANDLE, &imageIndex);
sdlex_render_init(swapchain, get_vk_pipeline(), 1);
VkSubmitInfo submitInfo = { .sType = VK_STRUCTURE_TYPE_SUBMIT_INFO };
VkPipelineStageFlags waitStages = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
submitInfo.pWaitDstStageMask = &waitStages;
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = &get_vk_swap_chain()->CommandBuffers[imageIndex];
submitInfo.pWaitSemaphores = &imageAvailableSemaphore;
submitInfo.waitSemaphoreCount = 1;
vkQueueSubmit(get_vk_queue(), 1, &submitInfo, VK_NULL_HANDLE);
vkQueueWaitIdle(get_vk_queue());
vkDestroySemaphore(device, imageAvailableSemaphore, NULL);
VkFenceCreateInfo ci = { .sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO };
vkCreateFence(device, &ci, NULL, &the_fence);
return imageIndex;
}
void sdlex_render_texture(unsigned imageIndex, SDL_Rect target) {
// TODO: Image Specificated Batching
VKRENDER_GLOBALS_INIT
VkExtent2D screenSize = get_vk_swap_chain()->SwapChainInfo.imageExtent;
#define MAP_POS_TO_VIEWPORT_X(val) sdlex_map_float((float)val, 0.0f, (float)screenSize.width, -1.0f, 1.0f)
#define MAP_POS_TO_VIEWPORT_Y(val) sdlex_map_float((float)val, 0.0f, (float)screenSize.height, -1.0f, 1.0f)
Vertices[0].Pos.X = Vertices[1].Pos.X = Vertices[3].Pos.X = MAP_POS_TO_VIEWPORT_X(target.x);
Vertices[2].Pos.X = Vertices[4].Pos.X = Vertices[5].Pos.X = MAP_POS_TO_VIEWPORT_X(target.x + target.w);
Vertices[0].Pos.Y = Vertices[3].Pos.Y = Vertices[4].Pos.Y = MAP_POS_TO_VIEWPORT_Y(target.y);
Vertices[1].Pos.Y = Vertices[2].Pos.Y = Vertices[5].Pos.Y = MAP_POS_TO_VIEWPORT_Y(target.y + target.h);
#undef MAP_POS_TO_VIEWPORT_X
#undef MAP_POS_TO_VIEWPORT_Y
append_array_list(batch_buffer, Vertices);
}
void sdlex_render_texture_ex(unsigned imageIndex, Vector2 position, Vector2 origin, float rotation, Vector2 scale) {
VKRENDER_GLOBALS_INIT
VkExtent2D screenSize = get_vk_swap_chain()->SwapChainInfo.imageExtent;
VkImageCreateInfo * currentTextureInfo = sdlex_get_current_texture_info(imageIndex);
Vector2 leftBottom = vector2_sub(position, origin);
Vector2 rightUpper = vector2_adds(leftBottom, (float)currentTextureInfo->extent.width, (float)currentTextureInfo->extent.height);
leftBottom = vector2_sub(leftBottom, position);
rightUpper = vector2_sub(rightUpper, position);
leftBottom.X *= scale.X;
leftBottom.Y *= scale.Y;
rightUpper.X *= scale.X;
rightUpper.Y *= scale.Y;
leftBottom = vector2_add(leftBottom, position);
rightUpper = vector2_add(rightUpper, position);
#define MAP_POS_TO_VIEWPORT_X(val) sdlex_map_float((float)val, 0.0f, (float)screenSize.width, -1.0f, 1.0f)
#define MAP_POS_TO_VIEWPORT_Y(val) sdlex_map_float((float)val, 0.0f, (float)screenSize.height, -1.0f, 1.0f)
Vertices[0].Pos.X = Vertices[1].Pos.X = Vertices[3].Pos.X = (leftBottom.X);
Vertices[2].Pos.X = Vertices[4].Pos.X = Vertices[5].Pos.X = (rightUpper.X);
Vertices[0].Pos.Y = Vertices[3].Pos.Y = Vertices[4].Pos.Y = (leftBottom.Y);
Vertices[1].Pos.Y = Vertices[2].Pos.Y = Vertices[5].Pos.Y = (rightUpper.Y);
Vertices[0].Pos = vector2_rotate_around(Vertices[0].Pos, position, rotation);
Vertices[1].Pos = vector2_rotate_around(Vertices[1].Pos, position, rotation);
Vertices[2].Pos = vector2_rotate_around(Vertices[2].Pos, position, rotation);
Vertices[3].Pos = vector2_rotate_around(Vertices[3].Pos, position, rotation);
Vertices[4].Pos = vector2_rotate_around(Vertices[4].Pos, position, rotation);
Vertices[5].Pos = vector2_rotate_around(Vertices[5].Pos, position, rotation);
Vertices[0].Pos.X = MAP_POS_TO_VIEWPORT_X(Vertices[0].Pos.X);
Vertices[1].Pos.X = MAP_POS_TO_VIEWPORT_X(Vertices[1].Pos.X);
Vertices[2].Pos.X = MAP_POS_TO_VIEWPORT_X(Vertices[2].Pos.X);
Vertices[3].Pos.X = MAP_POS_TO_VIEWPORT_X(Vertices[3].Pos.X);
Vertices[4].Pos.X = MAP_POS_TO_VIEWPORT_X(Vertices[4].Pos.X);
Vertices[5].Pos.X = MAP_POS_TO_VIEWPORT_X(Vertices[5].Pos.X);
Vertices[0].Pos.Y = MAP_POS_TO_VIEWPORT_Y(Vertices[0].Pos.Y);
Vertices[1].Pos.Y = MAP_POS_TO_VIEWPORT_Y(Vertices[1].Pos.Y);
Vertices[2].Pos.Y = MAP_POS_TO_VIEWPORT_Y(Vertices[2].Pos.Y);
Vertices[3].Pos.Y = MAP_POS_TO_VIEWPORT_Y(Vertices[3].Pos.Y);
Vertices[4].Pos.Y = MAP_POS_TO_VIEWPORT_Y(Vertices[4].Pos.Y);
Vertices[5].Pos.Y = MAP_POS_TO_VIEWPORT_Y(Vertices[5].Pos.Y);
#undef MAP_POS_TO_VIEWPORT_X
#undef MAP_POS_TO_VIEWPORT_Y
append_array_list(batch_buffer, Vertices);
}
void sdlex_render_texture_region_ex(unsigned imageIndex, Vector2 position, Vector2 origin, float rotation, Vector2 scale, SDL_Rect sourceRegion) {
VKRENDER_GLOBALS_INIT
VkExtent2D screenSize = get_vk_swap_chain()->SwapChainInfo.imageExtent;
Vector2 leftBottom = vector2_sub(position, origin);
Vector2 rightUpper = vector2_adds(leftBottom, (float)sourceRegion.w, (float)sourceRegion.h);
VkImageCreateInfo * textureInfo = sdlex_get_current_texture_info(imageIndex);
Vertices[0].TexCoord.X = Vertices[1].TexCoord.X = Vertices[3].TexCoord.X = (float)sourceRegion.x / textureInfo->extent.width;
Vertices[2].TexCoord.X = Vertices[4].TexCoord.X = Vertices[5].TexCoord.X = (float)(sourceRegion.x + sourceRegion.w) / textureInfo->extent.width;
Vertices[0].TexCoord.Y = Vertices[3].TexCoord.Y = Vertices[4].TexCoord.Y = (float)sourceRegion.y / textureInfo->extent.height;
Vertices[1].TexCoord.Y = Vertices[2].TexCoord.Y = Vertices[5].TexCoord.Y = (float)(sourceRegion.y + sourceRegion.h) / textureInfo->extent.height;
leftBottom = vector2_sub(leftBottom, position);
rightUpper = vector2_sub(rightUpper, position);
leftBottom.X *= scale.X;
leftBottom.Y *= scale.Y;
rightUpper.X *= scale.X;
rightUpper.Y *= scale.Y;
leftBottom = vector2_add(leftBottom, position);
rightUpper = vector2_add(rightUpper, position);
#define MAP_POS_TO_VIEWPORT_X(val) sdlex_map_float((float)val, 0.0f, (float)screenSize.width, -1.0f, 1.0f)
#define MAP_POS_TO_VIEWPORT_Y(val) sdlex_map_float((float)val, 0.0f, (float)screenSize.height, -1.0f, 1.0f)
Vertices[0].Pos.X = Vertices[1].Pos.X = Vertices[3].Pos.X = (leftBottom.X);
Vertices[2].Pos.X = Vertices[4].Pos.X = Vertices[5].Pos.X = (rightUpper.X);
Vertices[0].Pos.Y = Vertices[3].Pos.Y = Vertices[4].Pos.Y = (leftBottom.Y);
Vertices[1].Pos.Y = Vertices[2].Pos.Y = Vertices[5].Pos.Y = (rightUpper.Y);
Vertices[0].Pos = vector2_rotate_around(Vertices[0].Pos, position, rotation);
Vertices[1].Pos = vector2_rotate_around(Vertices[1].Pos, position, rotation);
Vertices[2].Pos = vector2_rotate_around(Vertices[2].Pos, position, rotation);
Vertices[3].Pos = vector2_rotate_around(Vertices[3].Pos, position, rotation);
Vertices[4].Pos = vector2_rotate_around(Vertices[4].Pos, position, rotation);
Vertices[5].Pos = vector2_rotate_around(Vertices[5].Pos, position, rotation);
Vertices[0].Pos.X = MAP_POS_TO_VIEWPORT_X(Vertices[0].Pos.X);
Vertices[1].Pos.X = MAP_POS_TO_VIEWPORT_X(Vertices[1].Pos.X);
Vertices[2].Pos.X = MAP_POS_TO_VIEWPORT_X(Vertices[2].Pos.X);
Vertices[3].Pos.X = MAP_POS_TO_VIEWPORT_X(Vertices[3].Pos.X);
Vertices[4].Pos.X = MAP_POS_TO_VIEWPORT_X(Vertices[4].Pos.X);
Vertices[5].Pos.X = MAP_POS_TO_VIEWPORT_X(Vertices[5].Pos.X);
Vertices[0].Pos.Y = MAP_POS_TO_VIEWPORT_Y(Vertices[0].Pos.Y);
Vertices[1].Pos.Y = MAP_POS_TO_VIEWPORT_Y(Vertices[1].Pos.Y);
Vertices[2].Pos.Y = MAP_POS_TO_VIEWPORT_Y(Vertices[2].Pos.Y);
Vertices[3].Pos.Y = MAP_POS_TO_VIEWPORT_Y(Vertices[3].Pos.Y);
Vertices[4].Pos.Y = MAP_POS_TO_VIEWPORT_Y(Vertices[4].Pos.Y);
Vertices[5].Pos.Y = MAP_POS_TO_VIEWPORT_Y(Vertices[5].Pos.Y);
#undef MAP_POS_TO_VIEWPORT_X
#undef MAP_POS_TO_VIEWPORT_Y
append_array_list(batch_buffer, Vertices);
}
void sdlex_end_frame(unsigned imageIndex) {
sdlex_render_flush(imageIndex);
VkPresentInfoKHR presentInfo = { .sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR };
VkSwapchainKHR * swapChains = &get_vk_swap_chain()->SwapChain;
presentInfo.swapchainCount = 1;
presentInfo.pSwapchains = swapChains;
presentInfo.pImageIndices = &imageIndex;
presentInfo.pResults = NULL;
vkQueuePresentKHR(get_vk_queue(), &presentInfo);
vkQueueWaitIdle(get_vk_queue());
vkDestroyFence(get_vk_device(), the_fence, NULL);
}
void sdlex_render_flush(unsigned imageIndex) {
VKRENDER_GLOBALS_INIT
if (batch_buffer->Size == 0)
return;
unsigned i = imageIndex;
SDLExVulkanSwapChain * swapchain = get_vk_swap_chain();
SDLExVulkanGraphicsPipeline * pipeline = get_vk_pipeline();
recreate_vertex_buffer(batch_buffer->Size);
VkCommandBufferBeginInfo beginInfo = { .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO };
beginInfo.flags = VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT;
int ret = vkBeginCommandBuffer(swapchain->CommandBuffers[i], &beginInfo);
if (ret != VK_SUCCESS) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
"Failed to Begin Recording Command Buffer: vkBeginCommandBuffer returns %d\n", ret);
}
VkRenderPassBeginInfo renderPassInfo = { .sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO };
renderPassInfo.renderPass = pipeline->RenderPass;
renderPassInfo.framebuffer = pipeline->FrameBuffers[i];
renderPassInfo.renderArea.offset.x = renderPassInfo.renderArea.offset.y = 0;
renderPassInfo.renderArea.extent = swapchain->SwapChainInfo.imageExtent;
VkClearValue clearColor = { 0.0f, 0.0f, 0.0f, 1.0f };
renderPassInfo.clearValueCount = 1;
renderPassInfo.pClearValues = &clearColor;
vkCmdBeginRenderPass(swapchain->CommandBuffers[i], &renderPassInfo, VK_SUBPASS_CONTENTS_INLINE);
vkCmdBindPipeline(swapchain->CommandBuffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline->GraphicsPipeline);
VkBuffer buffer = get_vk_vertex_buffer();
VkDeviceSize offset = 0;
vkCmdBindVertexBuffers(swapchain->CommandBuffers[i], 0, 1, &buffer, &offset);
vkCmdBindDescriptorSets(swapchain->CommandBuffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline->PipelineLayout, 0, 1, &pipeline->DescriptorSets[i], 0, NULL);
vkCmdDraw(swapchain->CommandBuffers[i], batch_buffer->Size * 6, 1, 0, 0);
vkCmdEndRenderPass(swapchain->CommandBuffers[i]);
if ((ret = vkEndCommandBuffer(swapchain->CommandBuffers[i])) != VK_SUCCESS) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
"Failed to Record Command Buffer: vkEndCommandBuffer returns %d\n", ret);
}
void * addr = request_vertex_buffer_memory();
SDL_memcpy4(addr, batch_buffer->_data, batch_buffer->ElementSize * batch_buffer->Size / 4);
flush_vertex_buffer_memory();
VkSubmitInfo submitInfo = { .sType = VK_STRUCTURE_TYPE_SUBMIT_INFO };
VkPipelineStageFlags waitStages = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
submitInfo.pWaitDstStageMask = &waitStages;
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = &get_vk_swap_chain()->CommandBuffers[imageIndex];
vkQueueSubmit(get_vk_queue(), 1, &submitInfo, the_fence);
vkWaitForFences(get_vk_device(), 1, &the_fence, VK_TRUE, SDL_MAX_SINT64);
vkResetFences(get_vk_device(), 1, &the_fence);
batch_buffer->Size = 0;
}
void sdlex_render_init(SDLExVulkanSwapChain * swapchain, SDLExVulkanGraphicsPipeline * pipeline, int clear) {
for (size_t i = 0; i < swapchain->ImageCount; i++) {
VkCommandBufferBeginInfo beginInfo = { .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO };
beginInfo.flags = VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT;
int ret = vkBeginCommandBuffer(swapchain->CommandBuffers[i], &beginInfo);
if (ret != VK_SUCCESS) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
"Failed to Begin Recording Command Buffer: vkBeginCommandBuffer returns %d\n", ret);
}
VkRenderPassBeginInfo renderPassInfo = { .sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO };
renderPassInfo.renderPass = pipeline->RenderPass;
renderPassInfo.framebuffer = pipeline->FrameBuffers[i];
renderPassInfo.renderArea.offset.x = renderPassInfo.renderArea.offset.y = 0;
renderPassInfo.renderArea.extent = swapchain->SwapChainInfo.imageExtent;
VkClearValue clearColor = { 0.0f, 0.0f, 0.0f, 1.0f };
renderPassInfo.clearValueCount = 1;
renderPassInfo.pClearValues = &clearColor;
vkCmdBeginRenderPass(swapchain->CommandBuffers[i], &renderPassInfo, VK_SUBPASS_CONTENTS_INLINE);
vkCmdBindPipeline(swapchain->CommandBuffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline->GraphicsPipeline);
if (clear) {
VkClearAttachment clearatt;
clearatt.clearValue = clearColor;
clearatt.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
clearatt.colorAttachment = 0;
VkClearRect clearrect;
clearrect.baseArrayLayer = 0;
clearrect.layerCount = 1;
clearrect.rect.offset.x = clearrect.rect.offset.y = 0;
clearrect.rect.extent = swapchain->SwapChainInfo.imageExtent;
vkCmdClearAttachments(swapchain->CommandBuffers[i], 1, &clearatt, 1, &clearrect);
}
else {
VkBuffer buffer = get_vk_vertex_buffer();
VkDeviceSize offset = 0;
vkCmdBindVertexBuffers(swapchain->CommandBuffers[i], 0, 1, &buffer, &offset);
vkCmdBindDescriptorSets(swapchain->CommandBuffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline->PipelineLayout, 0, 1, &pipeline->DescriptorSets[i], 0, NULL);
vkCmdDraw(swapchain->CommandBuffers[i], 6, 1, 0, 0);
}
vkCmdEndRenderPass(swapchain->CommandBuffers[i]);
if ((ret = vkEndCommandBuffer(swapchain->CommandBuffers[i])) != VK_SUCCESS) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
"Failed to Record Command Buffer: vkEndCommandBuffer returns %d\n", ret);
}
}
}
| 2.328125 | 2 |
2024-11-18T20:55:42.868843+00:00 | 2019-06-15T22:06:09 | 9d63b19481f93f49dab08d1151f60ba6851152da | {
"blob_id": "9d63b19481f93f49dab08d1151f60ba6851152da",
"branch_name": "refs/heads/master",
"committer_date": "2019-06-15T22:06:09",
"content_id": "729ff1e5f227bcd2bf63880269b7f664e5360ae4",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "b8d8d203f878f03171d5d9dd902e4bc5e8ee67e8",
"extension": "h",
"filename": "objects.h",
"fork_events_count": 2,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 129887399,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1832,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/objects.h",
"provenance": "stackv2-0092.json.gz:47740",
"repo_name": "zautomata/baseline",
"revision_date": "2019-06-15T22:06:09",
"revision_id": "fdce595c8a7fdaf55fc34029edaeecd1d24407db",
"snapshot_id": "15ed13a1116dfe99a9d64506d2f8bb6ad3fa5503",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/zautomata/baseline/fdce595c8a7fdaf55fc34029edaeecd1d24407db/objects.h",
"visit_date": "2020-03-11T08:34:13.098600"
} | stackv2 | /*
* Copyright (c) 2014 Mohamed Aslan <maslan@sce.carleton.ca>
*
* Permission to use, copy, modify, and 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.
*/
#ifndef _OBJECTS_H_
#define _OBJECTS_H_
#include <fcntl.h>
#include <time.h>
#define MAX_PARENTS 1
enum objtype {
O_FILE,
O_DIR,
O_COMMIT,
O_TAG
};
struct user {
char *name;
char *email;
time_t timestamp;
};
struct commit {
char *id;
char *dir;
struct user author;
struct user committer;
u_int8_t n_parents;
char *parents[MAX_PARENTS];
char *message;
};
struct dirent {
char *id;
char *name;
/* TODO: get rid of type */
enum {
T_FILE,
T_DIR
} type;
mode_t mode;
struct dirent *next;
};
struct dir {
char *id;
struct dir *parent;
struct dirent *children;
};
struct file {
char *id;
enum {
LOC_FS,
LOC_MEM
} loc;
union {
int fd;
char *buffer;
};
};
/* file ops */
struct file* baseline_file_new();
void baseline_file_free(struct file *);
/* commit ops */
struct commit* baseline_commit_new();
void baseline_commit_free(struct commit *);
/* dir ops */
struct dir* baseline_dir_new();
void baseline_dir_free(struct dir *);
void baseline_dir_append(struct dir *, struct dirent *);
#endif
| 2.15625 | 2 |
2024-11-18T20:55:45.744145+00:00 | 2019-01-10T23:37:11 | 814b6091044a5c78ac7b05966e32157f9d6a493c | {
"blob_id": "814b6091044a5c78ac7b05966e32157f9d6a493c",
"branch_name": "refs/heads/master",
"committer_date": "2019-01-10T23:37:11",
"content_id": "c76508b3e3be255ee63dfb756ffb0c8c660c9780",
"detected_licenses": [
"MIT"
],
"directory_id": "2f49f93c8464370ec1266efe11312662a542107b",
"extension": "c",
"filename": "event-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": 2134,
"license": "MIT",
"license_type": "permissive",
"path": "/event-database/src/event-parser.c",
"provenance": "stackv2-0092.json.gz:47997",
"repo_name": "skyformat99/event-database",
"revision_date": "2019-01-10T23:37:11",
"revision_id": "0f758dca9a00599e6200226609a696585c828327",
"snapshot_id": "416bb4a9593bcd1c6c89faf9b41f4e154d855162",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/skyformat99/event-database/0f758dca9a00599e6200226609a696585c828327/event-database/src/event-parser.c",
"visit_date": "2020-04-16T06:33:28.953234"
} | stackv2 | /*
* event-parser.c
*
* Created on: Jan 7, 2019
* Author: tommaso
*/
#include <string.h>
#include <jansson.h>
#include "event-engine.h"
#include "logger/log.h"
void parse_input_buffer (char* buffer, size_t len, char* response, size_t* response_length, void* ptr) {
log_debug("Parsing function");
event_engine_t* event_engine = ptr;
size_t parsed_commands_count;
command_t* commands[128];
*response_length = 0;
parsed_commands_count = event_engine_parse(event_engine, buffer, len, commands);
for (long unsigned int i = 0; i < parsed_commands_count; i++) {
command_t* command = commands[i];
log_debug("Command type: %d", command->type);
if (command->type == ADD_REDUCER) {
add_reducer_command_t* add_reducer_command = commands[i]->command_data;
// TODO: handler the return value correctly
event_engine_add_reducer(event_engine, add_reducer_command);
size_t l = strlen("\"OK\"\n");
memcpy(&response[*response_length], "\"OK\"\n", l);
*response_length += l;
}
if (command->type == ADD_EVENT) {
// TODO: handler the return value correctly
event_engine_dispatch_event(event_engine, (event_t*) command->command_data);
size_t l = strlen("\"OK\"\n");
memcpy(&response[*response_length], "\"OK\"\n", l);
*response_length += l;
} else if(command->type == GET_STATE) {
json_t* json = event_engine_get_reducer_state(event_engine, (char*) command->command_data);
if (json == NULL) {
log_warn("Unable to get state");
size_t l = strlen("{\"R\":\"ERROR\"}\n");
memcpy(&response[*response_length], "{\"R\":\"ERROR\"}\n", l);
*response_length += l;
} else {
char* state = json_dumps(json, JSON_COMPACT | JSON_ENCODE_ANY);
log_trace("State: %s", state);
size_t l = strlen(state);
memcpy(&response[*response_length], state, l);
*response_length += l;
memcpy(&response[*response_length], "\n", 1);
*response_length += 1;
json_decref(json);
free(state);
}
}
if (command->command_data) {
free(command->command_data);
}
}
log_debug("Response %.*s (%d)", *response_length, response, *response_length);
}
| 2.59375 | 3 |
2024-11-18T20:55:46.210899+00:00 | 2017-12-14T03:13:06 | f03ef3c1bba19ebb8b3515eded248cd11c3780ef | {
"blob_id": "f03ef3c1bba19ebb8b3515eded248cd11c3780ef",
"branch_name": "refs/heads/master",
"committer_date": "2017-12-14T03:13:06",
"content_id": "04bf2dc1022736d236322cfede9375e1c7c8edba",
"detected_licenses": [
"MIT"
],
"directory_id": "1924644bc1c87e947544b6a930b15d1ddc00be57",
"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": 113690152,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2622,
"license": "MIT",
"license_type": "permissive",
"path": "/13-dec/35.c/main.c",
"provenance": "stackv2-0092.json.gz:48126",
"repo_name": "kasiriveni/c-examples",
"revision_date": "2017-12-14T03:13:06",
"revision_id": "79f1c302d8069e17dae342739420602bb58315f8",
"snapshot_id": "f3824879d55987bfed73239d65d3692227a449f2",
"src_encoding": "UTF-8",
"star_events_count": 5,
"url": "https://raw.githubusercontent.com/kasiriveni/c-examples/79f1c302d8069e17dae342739420602bb58315f8/13-dec/35.c/main.c",
"visit_date": "2021-05-06T16:21:51.221273"
} | stackv2 | /*
* C Program for Depth First Binary Tree Search without using
* Recursion
*/
#include <stdio.h>
#include <stdlib.h>
struct node
{
int a;
struct node *left;
struct node *right;
int visited;
};
void generate(struct node **, int);
void DFS(struct node *);
void delete(struct node **);
int main()
{
struct node *head = NULL;
int choice = 0, num, flag = 0, key;
do
{
printf("\nEnter your choice:\n1. Insert\n2. Perform DFS Traversal\n3. Exit\nChoice: ");
scanf("%d", &choice);
switch(choice)
{
case 1:
printf("Enter element to insert: ");
scanf("%d", &num);
generate(&head, num);
break;
case 2:
DFS(head);
break;
case 3:
delete(&head);
printf("Memory Cleared\nPROGRAM TERMINATED\n");
break;
default:
printf("Not a valid input, try again\n");
}
} while (choice != 3);
return 0;
}
void generate(struct node **head, int num)
{
struct node *temp = *head, *prev = *head;
if (*head == NULL)
{
*head = (struct node *)malloc(sizeof(struct node));
(*head)->a = num;
(*head)->visited = 0;
(*head)->left = (*head)->right = NULL;
}
else
{
while (temp != NULL)
{
if (num > temp->a)
{
prev = temp;
temp = temp->right;
}
else
{
prev = temp;
temp = temp->left;
}
}
temp = (struct node *)malloc(sizeof(struct node));
temp->a = num;
temp->visited = 0;
if (temp->a >= prev->a)
{
prev->right = temp;
}
else
{
prev->left = temp;
}
}
}
void DFS(struct node *head)
{
struct node *temp = head, *prev;
printf("On DFS traversal we get:\n");
while (temp && !temp->visited)
{
if (temp->left && !temp->left->visited)
{
temp = temp->left;
}
else if (temp->right && !temp->right->visited)
{
temp = temp->right;
}
else
{
printf("%d ", temp->a);
temp->visited = 1;
temp = head;
}
}
}
void delete(struct node **head)
{
if (*head != NULL)
{
if ((*head)->left)
{
delete(&(*head)->left);
}
if ((*head)->right)
{
delete(&(*head)->right);
}
free(*head);
}
}
| 3.765625 | 4 |
2024-11-18T20:55:46.610619+00:00 | 2021-03-01T06:32:19 | 6f991440757636365c5f7ff6d9db8d838ebcaece | {
"blob_id": "6f991440757636365c5f7ff6d9db8d838ebcaece",
"branch_name": "refs/heads/master",
"committer_date": "2021-03-01T06:32:19",
"content_id": "f9e4111a226485e5f5427cda2b545e419e7ba83d",
"detected_licenses": [
"MIT"
],
"directory_id": "5bde85e828b76793e9769df81b90ef61888f74fb",
"extension": "h",
"filename": "graph_generate.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 320455663,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2539,
"license": "MIT",
"license_type": "permissive",
"path": "/ex4/johnson/src/graph_generate.h",
"provenance": "stackv2-0092.json.gz:48384",
"repo_name": "fyulingi/algorithm_experiment",
"revision_date": "2021-03-01T06:32:19",
"revision_id": "ba86d92d704266c577e1f19495ab381ffdd6774d",
"snapshot_id": "077d282e9457fe02146b878651dd2b2e3ec4f5d6",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/fyulingi/algorithm_experiment/ba86d92d704266c577e1f19495ab381ffdd6774d/ex4/johnson/src/graph_generate.h",
"visit_date": "2023-03-09T10:24:47.006291"
} | stackv2 | #ifndef MAIN_C_GRAPH_GENERATE_H
#define MAIN_C_GRAPH_GENERATE_H
#include <stdlib.h>
struct edge{
int v;
int w;
struct edge *next;
};
struct node{
int u;
struct edge *e;
struct node *next;
};
struct graph{ // 邻接表表示
int size;
int edge_num;
struct node *first;
struct node *last;
};
int *rand_num_generate(int n, int m)
// 生成 n 个互不相同的正整数, 范围在 0 - m-1
{
int i,j,temp;
int list[m];
int *vector=(int *)malloc(sizeof(int)*n);
for (i = 0; i < m; i++) {
list[i] = i;
}
for (i = 0; i < m; i++) {
j = i + rand() % (m - i);
temp = list[i];
list[i] = list[j];
list[j] = temp;
}
for (i = 0; i < n; i++) {
vector[i] = list[i];
}
return vector;
}
struct graph graph_generate(int n, int m, int a, int b)
// 生成 n 个节点, 每个节点 m 条边的无负值环的有向图
// 边的权值 [a, b]
{
struct graph G;
int i, j, k;
int *temp;
struct edge *ed;
struct node *no;
for(i = 0; i < n; i++){
if(i == 0) {
G.first = (struct node *) malloc(sizeof(struct node));
G.first->next = NULL;
G.first->u = i;
G.last = G.first;
no = G.first;
} else {
no = (struct node *) malloc(sizeof(struct node));
no->next = NULL;
no->u = i;
G.last->next = no;
G.last = no;
}
// 生成边
temp = rand_num_generate(m, n);
for(k = 0; k < m; k++){
if(k == 0){
no->e = (struct edge *)malloc(sizeof(struct edge));
ed = no->e;
ed->w = rand() % 51;
ed->next = NULL;
ed->v = temp[k];
} else{
ed->next = (struct edge *)malloc(sizeof(struct edge));
ed = ed->next;
ed->w = rand() % (b - a + 1) + a;
ed->next = NULL;
ed->v = temp[k];
}
}
free(temp);
}
G.size = n;
G.edge_num = n * m;
return G;
}
void graph_print(struct graph G, FILE *f)
{
int i;
struct node *no;
struct edge *ed;
no = G.first;
for(i = 0; i < G.size; i++){
ed = no->e;
while (ed != NULL){
fprintf(f, "(%d, %d, %d)\n", i+1, ed->v + 1, ed->w);
ed = ed->next;
}
no = no->next;
}
}
#endif //MAIN_C_GRAPH_GENERATE_H
| 3.09375 | 3 |
2024-11-18T20:55:46.691753+00:00 | 2012-07-05T06:20:54 | 4ad134d454d614276e8e8a2a0e065601bd10012c | {
"blob_id": "4ad134d454d614276e8e8a2a0e065601bd10012c",
"branch_name": "HEAD",
"committer_date": "2012-07-05T06:20:54",
"content_id": "c68f765a6819cb85cca49cff291229b95443c46a",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "b4b36c26891cb94f6ca1c9d05c013443f91a4739",
"extension": "c",
"filename": "canvas.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 4156239,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3430,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/fs/user/curses/canvas.c",
"provenance": "stackv2-0092.json.gz:48512",
"repo_name": "capel/brazos",
"revision_date": "2012-07-05T06:20:54",
"revision_id": "553f9d1d7f2c6e852d5e1f24e844d569115897cc",
"snapshot_id": "9bb72a0c25dd7afd65f3d4a10baa2b1beb575a61",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/capel/brazos/553f9d1d7f2c6e852d5e1f24e844d569115897cc/fs/user/curses/canvas.c",
"visit_date": "2016-09-11T14:59:56.369866"
} | stackv2 | #include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <bcurses.h>
#define INSIDE(_r, _x, _y) ((_x >= 0) && (_x <= _r->size_x) && (_y >= 0) && (_y <= _r->size_y))
#define HLINE '-'
#define VLINE '|'
#define CROSS '+'
struct canvas {
scr* s;
int base_x;
int base_y;
int size_x;
int size_y;
textbox * tb;
struct canvas * next;
};
void register_canvas(scr* s, canvas* c);
void register_next(canvas * c, canvas* next) {
c->next = next;
}
canvas* init_canvas(scr* s, int x1, int y1, int x2, int y2) {
canvas* r = malloc(sizeof(canvas));
r->s = s;
r->base_x = x1;
r->base_y = y1;
r->size_x = x2 - x1;
r->size_y = y2 - y1;
r->next = 0;
register_canvas(s, r);
return r;
}
void register_tb(canvas* c, textbox* tb) {
c->tb = tb;
}
int POS(scr* s, int x, int y);
int RPOS(canvas* r, int x, int y) {
return POS(r->s, x + r->base_x, y + r->base_y);
}
int PUT(scr* s, int x, int y, int ch);
int RPUT(canvas* r, int x, int y, int ch) {
return PUT(r->s, x + r->base_x, y + r->base_y, ch);
}
int ATTR(scr* s, int x, int y, unsigned attr);
int RATTR(canvas* r, int x, int y, unsigned attr) {
return ATTR(r->s, x + r->base_x, y + r->base_y, attr);
}
void draw_tb(textbox*);
void draw(canvas* c) {
if (!c) return;
if (c->tb) {
draw_tb(c->tb);
}
draw(c->next);
}
bool blank(canvas* r) {
for(int y = 0; y <= r->size_y; y++) {
for(int x = 0; x <= r->size_x; x++) {
RPUT(r, x, y, ' ');
RATTR(r, x, y, A_NORMAL);
}
}
return true;
}
bool forwards(canvas* c, int x, int y, int* _x, int* _y) {
x++;
if (!INSIDE(c, x, y)) {
x = 0;
y++;
}
if (!INSIDE(c, x, y)) {
return false;
}
*_x = x;
*_y = y;
return true;
}
bool draw_text_nowrap(canvas *r, int x, int y, const char* buf) {
size_t pos = 0;
while(buf[pos]) {
if (!INSIDE(r, x, y)) return false;
RPUT(r, x, y, buf[pos++]);
x++;
}
return true;
}
bool draw_text(canvas *r, int ix, int iy, const char* buf) {
size_t pos = 0;
int x = ix;
int y = iy;
while(buf[pos]) {
if (!forwards(r, x, y, &x, &y)) return false;
RPUT(r, x, y, buf[pos++]);
}
return true;
}
void draw_line_point(canvas* r, int x, int y, int p) {
int other = p == HLINE ? VLINE : HLINE;
RPUT(r, x, y, RPOS(r, x, y) == other ? CROSS : p);
}
bool draw_vline(canvas* r, int x, int y1, int y2) {
int min = y1 < y2 ? y1 : y2;
int max = y1 > y2 ? y1 : y2;
if (!INSIDE(r, x, min) || !INSIDE(r, x, max)) return false;
if (y1 == y2) {
draw_line_point(r, x, y1, VLINE);
return true;
}
for(int y = min; y <= max; y++) {
draw_line_point(r, x, y, VLINE);
}
return true;
}
bool draw_hline(canvas* r, int x1, int x2, int y) {
int min = x1 < x2 ? x1 : x2;
int max = x1 > x2 ? x1 : x2;
if (!INSIDE(r, min, y) || !INSIDE(r, max, y)) return false;
if (x1 == x2) {
draw_line_point(r, x1, y, HLINE);
return true;
}
for(int x = min; x <= max; x++) {
draw_line_point(r, x, y, HLINE);
}
return true;
}
bool draw_box(canvas* r, int x1, int y1, int x2, int y2) {
if (!INSIDE(r, x1, y1) || !INSIDE(r, x2, y2)) return false;
draw_vline(r, x1, y1, y2);
draw_vline(r, x2, y1, y2);
draw_hline(r, x1, x2, y1);
draw_hline(r, x1, x2, y2);
return true;
}
void dtor_textbox(textbox*);
void dtor_canvas(canvas* c) {
if (!c) return;
dtor_canvas(c->next);
dtor_textbox(c->tb);
free(c);
}
| 2.765625 | 3 |
2024-11-18T20:55:48.824147+00:00 | 2019-10-14T05:32:53 | 78979ff2d09813fc7afedc701f8a53cc2db8f6e4 | {
"blob_id": "78979ff2d09813fc7afedc701f8a53cc2db8f6e4",
"branch_name": "refs/heads/master",
"committer_date": "2019-10-14T05:32:53",
"content_id": "3e59c52a6ef334d5f6f842ac991b2eda1e38f26d",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "0c4bd1b977cc714a8a6b2839f51c4247ecfd32b1",
"extension": "c",
"filename": "perceptron_libs.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": 7668,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/C++/TinY-ANN/perceptron_libs.c",
"provenance": "stackv2-0092.json.gz:50182",
"repo_name": "ishine/neuralLOGIC",
"revision_date": "2019-10-14T05:32:53",
"revision_id": "3eb3b9980e7f7a7d87a77ef40b1794fb5137c459",
"snapshot_id": "281d498b40159308815cee6327e6cf79c9426b16",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ishine/neuralLOGIC/3eb3b9980e7f7a7d87a77ef40b1794fb5137c459/C++/TinY-ANN/perceptron_libs.c",
"visit_date": "2020-08-14T14:11:54.487922"
} | stackv2 | /*
* This file contains functions that you can use directly to
* create and train a neural network. Everything is allocated dynamically
* so you will have to free up memory at the end of your
* program. Feel free to modify and edit the code.
*
* Made by Tamás Imets
* Date: 18th of November, 2018
* Version: 0.1v
* Github: https://github.com/Imetomi
*
*/
#include "perceptron.h"
/* Prints the weight matrices in a neural net */
void print_net(NeuralNet *ann) {
Layer *iter;
for (iter = ann->input; iter != NULL; iter = iter->next) {
printf("\nLayer size = %d: ", iter->dim.h);
for (int i = 0; i < iter->dim.w; ++i) {
printf("%f ", iter->out[i]);
}
printf("\n");
for (int i = 0; i < iter->dim.h; ++i) {
for (int j = 0; j < iter->dim.w; ++j) {
printf("%f ", iter->weights[i][j]);
}
printf("\n");
}
printf("\n");
}
}
/* Free function for the whole neural net */
void free_net(NeuralNet *ann) {
Layer *iter = ann->input;
while (iter != NULL) {
Layer *next = iter->next;
free(iter->in);
free(iter->out);
free_float_2d(iter->weights, iter->dim.h);
free(iter);
iter = next;
}
free(ann);
}
/* Initializes a random weight matrix */
void init_weight_matrix(float **w, Dim dim) {
for (int i = 0; i < dim.h; i++) {
for (int j = 0; j < dim.w; ++j) {
w[i][j] = rand_float() - (float) 0.5;
}
}
}
/* Allocates memory and creates a neural net */
NeuralNet *create_net(Dim in, Dim out) {
NeuralNet *ann = (NeuralNet*) malloc(sizeof(NeuralNet));
ann->input = (Layer*) malloc(sizeof(Layer));
ann->output = (Layer*) malloc(sizeof(Layer));
ann->input->prev = NULL;
ann->input->next = ann->output;
ann->output->prev = ann->input;
ann->output->next = NULL;
ann->input->dim.h = in.h;
ann->input->dim.w = in.w;
ann->output->dim.h = out.h;
ann->output->dim.w = out.w;
ann->input->weights = allocate_float_2d(ann->input->dim.h, ann->input->dim.w);
ann->output->weights = allocate_float_2d(ann->output->dim.h, ann->output->dim.w);
ann->input->in = allocate_float_1d(ann->input->dim.w + ann->input->dim.h);
ann->input->out = allocate_float_1d(ann->input->dim.w + ann->input->dim.h);
ann->output->in = allocate_float_1d(ann->output->dim.h);
ann->output->out = allocate_float_1d(ann->output->dim.h);
init_weight_matrix(ann->input->weights, ann->input->dim);
init_weight_matrix(ann->output->weights, ann->output->dim);
fill_zero(ann->input->in, ann->input->dim.h);
fill_zero(ann->input->out, ann->input->dim.h);
fill_zero(ann->output->in, ann->output->dim.h);
fill_zero(ann->output->out, ann->output->dim.h);
return ann;
}
/* Adds a new layer to the neural nerwork */ /*
void add_hidden_layer(NeuralNet *ann, int layer_size) {
Layer *new = (Layer*) malloc(sizeof(Layer));
ann->input->dim.w = layer_size;
new->dim.h = layer_size;
new->dim.w = ann->input->next->dim.h;
new->in = allocate_float_1d(new->dim.w);
new->out = allocate_float_1d(new->dim.w);
fill_zero(new->in, new->dim.w);
fill_zero(new->out, new->dim.w);
free_float_2d(ann->input->weights, ann->input->dim.h);
free_float_2d(ann->input->next->weights, ann->input->next->dim.h);
free_float_1d(ann->input->in);
free_float_1d(ann->input->out);
new->weights = allocate_float_2d(new->dim.h, new->dim.w);
ann->input->weights = allocate_float_2d(ann->input->dim.h, ann->input->dim.w);
ann->input->next->weights = allocate_float_2d(ann->input->next->dim.h, ann->input->next->dim.w);
ann->input->in = allocate_float_1d(ann->input->dim.w);
ann->input->out = allocate_float_1d(ann->input->dim.w);
init_weight_matrix(ann->input->weights, ann->input->dim);
init_weight_matrix(ann->input->next->weights, ann->input->next->dim);
init_weight_matrix(new->weights, new->dim);
fill_zero(ann->input->in, ann->input->dim.w);
fill_zero(ann->input->out, ann->input->dim.w);
new->next = ann->input->next;
new->prev = ann->input;
ann->input->next = new;
ann->input->next->prev = new;
}
*/
/* Feeds forward data in the neural network*/
void feed_forward_net(NeuralNet *ann, float *X) {
for (int i = 0; i < ann->input->dim.w; ++i) {
float *r = get_row(ann->input->weights, ann->input->dim.h, i);
ann->input->in[i] = dot_product(X, r, ann->input->dim.h);
ann->input->out[i] = sigmoid(ann->input->in[i]);
free(r);
}
Layer *iter;
for (iter = ann->input->next; iter != NULL; iter=iter->next) {
for (int i = 0; i < iter->dim.w; ++i) {
float *r = get_row(iter->weights, iter->dim.h, i);
iter->in[i] = dot_product(iter->prev->out, r, iter->dim.h);
iter->out[i] = sigmoid(iter->in[i]);
free(r);
}
}
}
/* Trains the neural network */
void train_net(NeuralNet *ann, float **X, float **y, float *J, float *acc, Dim dim, int n_epoch) {
float *delta_second_layer = allocate_float_1d(ann->output->dim.h);
clock_t start, end;
start = clock();
for (int step = 0; step < n_epoch; ++step) {
float sum_err = 0;
int correct = 0;
for (int i = 0; i < dim.h; ++i) {
feed_forward_net(ann, X[i]);
if ((int) (ann->output->out[0] + 0.5) == (int) y[i][0])
correct++;
float error_last_layer = y[i][0] - ann->output->out[0];
float delta_last_layer = error_last_layer * sigmoid_der(ann->output->out[0]);
for (int j = 0; j < ann->output->dim.h; ++j) {
delta_second_layer[j] = ann->output->weights[j][0] * delta_last_layer * sigmoid_der(ann->output->prev->out[j]);
}
for (int j = 0; j < ann->output->dim.h; ++j) {
for (int k = 0; k < ann->output->dim.w; ++k) {
ann->output->weights[j][k] += delta_last_layer * ann->input->out[j];
}
}
for (int j = 0; j < ann->input->dim.h; ++j) {
for (int k = 0; k < ann->input->dim.w; ++k) {
ann->input->weights[j][k] += X[i][j] * delta_second_layer[k];
}
}
sum_err += error_last_layer * error_last_layer * (float) 0.5;
}
J[step] = sum_err;
acc[step] = (float) correct / (float) dim.h;
if (step % 50 == 0)
printf("Epoch: %d Error: %0.3f Accuracy: %0.3f\n", step, J[step], acc[step]);
}
free_float_1d(delta_second_layer);
end = clock();
float training_time = (float) (end-start) / CLOCKS_PER_SEC;
printf("Training took: %0.3f sec\n", training_time);
}
/* Testing accuracy on the given neural network */
void test_net(NeuralNet *ann, float **X, float **y, Dim dim) {
int correct = 0;
float rmse = 0;
float mae = 0;
for (int i = 0; i < dim.h - 1; ++i) {
feed_forward_net(ann, X[i]);
if ((int) (ann->output->out[0] + 0.5) == (int) y[i][0])
correct++;
rmse += (y[i][0] - ann->output->out[0]) * (y[i][0] - ann->output->out[0]);
mae += fabs((double) (y[i][0] - ann->output->out[0]));
}
rmse = (float) sqrt((double) (rmse / (float) dim.h));
mae = mae / (float) dim.h;
printf("\nTest Accuracy: %f Correct: %d Misclassified: %d\n",
(float) correct / (float) dim.h,
correct, dim.h - correct);
printf("Root Mean Squared Error: %f\n", rmse);
printf("Mean Absolute Error: %f\n", mae);
}
| 3.203125 | 3 |
2024-11-18T20:55:49.357506+00:00 | 2015-05-12T15:54:46 | c0c19f936a48ee90086f5a78b46c1c037bc65935 | {
"blob_id": "c0c19f936a48ee90086f5a78b46c1c037bc65935",
"branch_name": "refs/heads/master",
"committer_date": "2015-05-12T15:54:46",
"content_id": "951136ca7a2d548a5a0fc96ef489e7f72eb6c557",
"detected_licenses": [
"MIT"
],
"directory_id": "0bae42676f118cb64fef7b72ab2bf901de8920b4",
"extension": "c",
"filename": "noStarve.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 27149090,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1888,
"license": "MIT",
"license_type": "permissive",
"path": "/NoStarveMutex/noStarve.c",
"provenance": "stackv2-0092.json.gz:50312",
"repo_name": "PoloGarcia/Classical-Semaphores",
"revision_date": "2015-05-12T15:54:46",
"revision_id": "414c990ed3e9b7ef0e4e47f837e6ca5cf9cc6118",
"snapshot_id": "53ea1b399288318cc223b3bf54e67185309e2213",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/PoloGarcia/Classical-Semaphores/414c990ed3e9b7ef0e4e47f837e6ca5cf9cc6118/NoStarveMutex/noStarve.c",
"visit_date": "2021-01-22T11:42:30.344497"
} | stackv2 | #include "semaforos.h"
#include <sys/shm.h>
#include <sys/sem.h>
#include <time.h>
/*
mutex.wait()
room1 += 1
mutex.signal()
t1.wait()
room2 += 1
mutex.wait()
room1 -= 1
if room1 == 0:
mutex.signal()
t2.signal()
else:
mutex.signal()
t1.signal()
t2.wait()
room2 -= 1
# critical section
if room2 == 0:
t1.signal()
else:
t2.signal()
*/
void cliente(pelo_crece){
int semid, shmid;
key_t key;
struct rooms *Rooms;
if ( (key = ftok("/dev/null", 65)) == (key_t) -1 ) {
perror("ftok");
exit(-1);
}
if ( (semid = semget(key, 3, 0666)) < 0 ) {
perror("semget");
exit(-1);
}
if ( (shmid = shmget(key, sizeof(struct rooms), 0666)) < 0 ) {
perror("shmid");
exit(-1);
}
Rooms = shmat(shmid, NULL, 0);
while(1) {
mutex_wait(semid,MUTEX);
Rooms->room1 += 1;
printf("%i en el room 1\n",getpid());
mutex_signal(semid,MUTEX);
sem_wait(semid,T1,1);
Rooms->room2 += 1;
mutex_wait(semid,MUTEX);
Rooms->room1 -= 1;
if (Rooms->room1==0)
{
mutex_signal(semid,MUTEX);
sem_signal(semid,T2,1);
printf("%i dice: Vamonos al cuarto 2\n",getpid());
} else {
mutex_signal(semid,MUTEX);
sem_signal(semid,T1,1);
printf("%i dice: Me quedo en el cuarto 1\n",getpid());
}
sem_wait(semid,T2,1);
Rooms->room2 -= 1;
printf("%i dice: Estoy ejecutando mi seccion critica\n",getpid());
sleep(pelo_crece);
if (Rooms->room2 == 0)
{
sem_signal(semid,T1,1);
} else {
sem_signal(semid,T2,1);
}
}
shmdt(Rooms);
}
int main(int argc, char *argv[])
{
int pid,i;
if (argc != 2)
{
printf("forma de uso: %s [sleep time]\n",argv[0]);
}
for (i = 0; i < 5; ++i)
{
if ( (pid = fork()) < 0 ) {
perror("fork");
return -1;
} else if (pid == 0) {
cliente(atoi(argv[1]));
} else {
}
}
return 0;
} | 2.671875 | 3 |
2024-11-18T20:55:49.624903+00:00 | 2023-08-15T21:28:57 | 40f295fb7e95014ce088829c6cf479fa6da39617 | {
"blob_id": "40f295fb7e95014ce088829c6cf479fa6da39617",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-15T21:28:57",
"content_id": "85ae7f972187966a375c5553487d19e356139191",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "c8a669ab64463ea66eacc9e97e8647213b4ed26f",
"extension": "c",
"filename": "ometis.c",
"fork_events_count": 85,
"gha_created_at": "2019-08-09T20:58:44",
"gha_event_created_at": "2023-08-12T18:31:21",
"gha_language": "LLVM",
"gha_license_id": "Apache-2.0",
"github_id": 201539521,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 21425,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/ParMetis-4.0.3/libparmetis/ometis.c",
"provenance": "stackv2-0092.json.gz:50698",
"repo_name": "schism-dev/schism",
"revision_date": "2023-08-15T21:28:57",
"revision_id": "7edcd2486aadc830408524956a295cf23f4560ba",
"snapshot_id": "cc2c280fc72e7bb194d967ff95122bfc7477a6be",
"src_encoding": "UTF-8",
"star_events_count": 68,
"url": "https://raw.githubusercontent.com/schism-dev/schism/7edcd2486aadc830408524956a295cf23f4560ba/src/ParMetis-4.0.3/libparmetis/ometis.c",
"visit_date": "2023-08-17T12:31:52.325677"
} | stackv2 | /*!
* Copyright 1997, Regents of the University of Minnesota
*
* \file
* \brief This is the entry point of parallel ordering routines
*
* \date Started 8/1/2008
* \author George Karypis
* \version\verbatim $Id: ometis.c 10666 2011-08-04 05:22:36Z karypis $ \endverbatime
*
*/
#include <parmetislib.h>
/***********************************************************************************/
/*! This function is the entry point of the parallel ordering algorithm.
It simply translates the arguments to the tunable version. */
/***********************************************************************************/
int ParMETIS_V3_NodeND(idx_t *vtxdist, idx_t *xadj, idx_t *adjncy,
idx_t *numflag, idx_t *options, idx_t *order, idx_t *sizes,
MPI_Comm *comm)
{
idx_t status;
idx_t seed = (options != NULL && options[0] != 0 ? options[PMV3_OPTION_SEED] : -1);
idx_t dbglvl = (options != NULL && options[0] != 0 ? options[PMV3_OPTION_DBGLVL] : -1);
/* Check the input parameters and return if an error */
status = CheckInputsNodeND(vtxdist, xadj, adjncy, numflag, options, order, sizes, comm);
if (GlobalSEMinComm(*comm, status) == 0)
return METIS_ERROR;
ParMETIS_V32_NodeND(vtxdist, xadj, adjncy,
/*vwgt=*/NULL,
numflag,
/*mtype=*/NULL,
/*rtype=*/NULL,
/*p_nseps=*/NULL,
/*s_nseps=*/NULL,
/*ubfrac=*/NULL,
/*seed=*/(options==NULL || options[0] == 0 ? NULL : &seed),
/*dbglvl=*/(options==NULL || options[0] == 0 ? NULL : &dbglvl),
order, sizes, comm);
return METIS_OK;
}
/***********************************************************************************/
/*! This function is the entry point of the tunable parallel ordering algorithm.
This is the main ordering algorithm and implements a multilevel nested
dissection ordering approach.
*/
/***********************************************************************************/
int ParMETIS_V32_NodeND(idx_t *vtxdist, idx_t *xadj, idx_t *adjncy, idx_t *vwgt,
idx_t *numflag, idx_t *mtype, idx_t *rtype, idx_t *p_nseps, idx_t *s_nseps,
real_t *ubfrac, idx_t *seed, idx_t *idbglvl, idx_t *order, idx_t *sizes,
MPI_Comm *comm)
{
idx_t i, npes, mype, dbglvl, status, wgtflag=0;
ctrl_t *ctrl;
graph_t *graph, *mgraph;
idx_t *morder;
size_t curmem;
gkMPI_Comm_size(*comm, &npes);
gkMPI_Comm_rank(*comm, &mype);
/* Deal with poor vertex distributions */
if (GlobalSEMinComm(*comm, vtxdist[mype+1]-vtxdist[mype]) < 1) {
printf("Error: Poor vertex distribution (processor with no vertices).\n");
return METIS_ERROR;
}
status = METIS_OK;
gk_malloc_init();
curmem = gk_GetCurMemoryUsed();
/* Setup the ctrl */
ctrl = SetupCtrl(PARMETIS_OP_KMETIS, NULL, 1, 5*npes, NULL, NULL, *comm);
dbglvl = (idbglvl == NULL ? 0 : *idbglvl);
ctrl->dbglvl = dbglvl;
STARTTIMER(ctrl, ctrl->TotalTmr);
ctrl->dbglvl = 0;
/*=======================================================================*/
/*! Compute the initial k-way partitioning */
/*=======================================================================*/
/* Setup the graph */
if (*numflag > 0)
ChangeNumbering(vtxdist, xadj, adjncy, order, npes, mype, 1);
graph = SetupGraph(ctrl, 1, vtxdist, xadj, NULL, NULL, adjncy, NULL, 0);
/* Allocate workspace */
AllocateWSpace(ctrl, 10*graph->nvtxs);
/* Compute the partitioning */
ctrl->CoarsenTo = gk_min(vtxdist[npes]+1, 200*gk_max(npes, ctrl->nparts));
if (seed != NULL)
ctrl->seed = (*seed == 0 ? mype : (*seed)*mype);
Global_Partition(ctrl, graph);
/* Collapse the number of partitions to be from 0..npes-1 */
for (i=0; i<graph->nvtxs; i++)
graph->where[i] = graph->where[i]%npes;
ctrl->nparts = npes;
/* Put back the real vertex weights */
if (vwgt) {
gk_free((void **)&graph->vwgt, LTERM);
graph->vwgt = vwgt;
graph->free_vwgt = 0;
wgtflag = 2;
}
/*=======================================================================*/
/*! Move the graph according to the partitioning */
/*=======================================================================*/
STARTTIMER(ctrl, ctrl->MoveTmr);
mgraph = MoveGraph(ctrl, graph);
/* compute nvwgts for the moved graph */
SetupGraph_nvwgts(ctrl, mgraph);
STOPTIMER(ctrl, ctrl->MoveTmr);
/*=======================================================================*/
/*! Now compute an ordering of the moved graph */
/*=======================================================================*/
ctrl->optype = PARMETIS_OP_OMETIS;
ctrl->partType = ORDER_PARTITION;
ctrl->mtype = (mtype == NULL ? PARMETIS_MTYPE_GLOBAL : *mtype);
ctrl->rtype = (rtype == NULL ? PARMETIS_SRTYPE_2PHASE : *rtype);
ctrl->p_nseps = (p_nseps == NULL ? 1 : *p_nseps);
ctrl->s_nseps = (s_nseps == NULL ? 1 : *s_nseps);
ctrl->ubfrac = (ubfrac == NULL ? ORDER_UNBALANCE_FRACTION : *ubfrac);
ctrl->dbglvl = dbglvl;
ctrl->ipart = ISEP_NODE;
ctrl->CoarsenTo = gk_min(graph->gnvtxs-1,
gk_max(1500*npes, graph->gnvtxs/(5*NUM_INIT_MSECTIONS*npes)));
morder = imalloc(mgraph->nvtxs, "ParMETIS_NodeND: morder");
MultilevelOrder(ctrl, mgraph, morder, sizes);
/* Invert the ordering back to the original graph */
ProjectInfoBack(ctrl, graph, order, morder);
STOPTIMER(ctrl, ctrl->TotalTmr);
IFSET(dbglvl, DBG_TIME, PrintTimingInfo(ctrl));
IFSET(dbglvl, DBG_TIME, gkMPI_Barrier(ctrl->gcomm));
gk_free((void **)&morder, LTERM);
FreeGraph(mgraph);
FreeInitialGraphAndRemap(graph);
/* If required, restore the graph numbering */
if (*numflag > 0)
ChangeNumbering(vtxdist, xadj, adjncy, order, npes, mype, 0);
goto DONE; /* Remove the warning for now */
DONE:
FreeCtrl(&ctrl);
if (gk_GetCurMemoryUsed() - curmem > 0) {
printf("ParMETIS appears to have a memory leak of %zdbytes. Report this.\n",
(ssize_t)(gk_GetCurMemoryUsed() - curmem));
}
gk_malloc_cleanup(0);
return (int)status;
}
/*********************************************************************************/
/*!
This is the top level ordering routine.
\param order is the computed ordering.
\param sizes is the 2*nparts array that will store the sizes of each subdomains
and the sizes of the separators at each level. Note that the
top-level separator is stores at \c sizes[2*nparts-2].
*/
/*********************************************************************************/
void MultilevelOrder(ctrl_t *ctrl, graph_t *graph, idx_t *order, idx_t *sizes)
{
idx_t i, nparts, nvtxs, npes;
idx_t *perm, *lastnode, *morder, *porder;
graph_t *mgraph;
nvtxs = graph->nvtxs;
npes = 1<<log2Int(ctrl->npes); /* # of nested dissection levels = floor(log_2(npes)) */
perm = imalloc(nvtxs, "MultilevelOrder: perm");
lastnode = ismalloc(4*npes, -1, "MultilevelOrder: lastnode");
for (i=0; i<nvtxs; i++)
perm[i] = i;
lastnode[2] = graph->gnvtxs;
iset(nvtxs, -1, order);
/* This is used as a pointer to the end of the sizes[] array (i.e., >=nparts)
that has not yet been filled in so that the separator sizes of the succesive
levels will be stored correctly. It is used in LabelSeparatos() */
sizes[0] = 2*npes-1;
graph->where = ismalloc(nvtxs, 0, "MultilevelOrder: graph->where");
for (nparts=2; nparts<=npes; nparts*=2) {
ctrl->nparts = nparts;
Order_Partition_Multiple(ctrl, graph);
LabelSeparators(ctrl, graph, lastnode, perm, order, sizes);
CompactGraph(ctrl, graph, perm);
if (ctrl->CoarsenTo < 100*nparts) {
ctrl->CoarsenTo = 1.5*ctrl->CoarsenTo;
}
ctrl->CoarsenTo = gk_min(ctrl->CoarsenTo, graph->gnvtxs-1);
}
/*-----------------------------------------------------------------
/ Move the graph so that each processor gets its partition
-----------------------------------------------------------------*/
IFSET(ctrl->dbglvl, DBG_TIME, gkMPI_Barrier(ctrl->comm));
IFSET(ctrl->dbglvl, DBG_TIME, starttimer(ctrl->MoveTmr));
CommSetup(ctrl, graph);
graph->ncon = 1; /* needed for MoveGraph */
mgraph = MoveGraph(ctrl, graph);
/* Fill in the sizes[] array for the local part. Just the vtxdist of the mgraph */
for (i=0; i<npes; i++)
sizes[i] = mgraph->vtxdist[i+1]-mgraph->vtxdist[i];
porder = imalloc(graph->nvtxs, "MultilevelOrder: porder");
morder = imalloc(mgraph->nvtxs, "MultilevelOrder: morder");
IFSET(ctrl->dbglvl, DBG_TIME, gkMPI_Barrier(ctrl->comm));
IFSET(ctrl->dbglvl, DBG_TIME, stoptimer(ctrl->MoveTmr));
/* Find the local ordering */
if (ctrl->mype < npes)
LocalNDOrder(ctrl, mgraph, morder, lastnode[2*(npes+ctrl->mype)]-mgraph->nvtxs);
/* Project the ordering back to the before-move graph */
ProjectInfoBack(ctrl, graph, porder, morder);
/* Copy the ordering from porder to order using perm */
for (i=0; i<graph->nvtxs; i++) {
PASSERT(ctrl, order[perm[i]] == -1);
order[perm[i]] = porder[i];
}
FreeGraph(mgraph);
gk_free((void **)&perm, (void **)&lastnode, (void **)&porder, (void **)&morder, LTERM);
/* PrintVector(ctrl, 2*npes-1, 0, sizes, "SIZES"); */
}
/**************************************************************************/
/*! This is the top-level driver of the multiple multisection ordering
code. */
/***************************************************************************/
void Order_Partition_Multiple(ctrl_t *ctrl, graph_t *graph)
{
idx_t i, sid, iter, nvtxs, nparts, nlevels;
idx_t *xadj, *adjncy, *where, *gpwgts, *imap;
idx_t *bestseps, *bestwhere, *origwhere;
CommSetup(ctrl, graph);
nparts = ctrl->nparts;
nvtxs = graph->nvtxs;
xadj = graph->xadj;
adjncy = graph->adjncy;
bestseps = ismalloc(2*nparts, -1, "Order_Partition_Multiple: bestseps");
bestwhere = imalloc(nvtxs+graph->nrecv, "Order_Partition_Multiple: bestwhere");
origwhere = graph->where;
for (nlevels=-1, iter=0; iter<ctrl->p_nseps; iter++) {
graph->where = imalloc(nvtxs, "Order_Partition_Multiple: where");
icopy(nvtxs, origwhere, graph->where);
Order_Partition(ctrl, graph, &nlevels, 0);
where = graph->where;
gpwgts = graph->gpwgts;
/* Update the where[] vectors of the subdomains that improved */
for (i=0; i<nvtxs; i++) {
sid = (where[i] < nparts ? nparts + where[i] - (where[i]%2) : where[i]);
if (iter == 0 || bestseps[sid] > gpwgts[sid])
bestwhere[i] = where[i];
}
/* Update the size of the separators for those improved subdomains */
for (i=0; i<nparts; i+=2) {
sid = nparts+i;
if (iter == 0 || bestseps[sid] > gpwgts[sid])
bestseps[sid] = gpwgts[sid];
}
/* free all the memory allocated for coarsening/refinement, but keep
the setup fields so that they will not be re-computed */
FreeNonGraphNonSetupFields(graph);
}
graph->where = bestwhere;
AllocateNodePartitionParams(ctrl, graph);
ComputeNodePartitionParams(ctrl, graph);
for (i=0; i<nparts; i+=2)
PASSERT(ctrl, bestseps[nparts+i] == graph->gpwgts[nparts+i]);
gk_free((void **)&bestseps, &origwhere, LTERM);
/* PrintVector(ctrl, 2*nparts-1, 0, bestseps, "bestseps"); */
}
/**************************************************************************/
/*! The driver of the multilvelel separator finding algorithm */
/**************************************************************************/
void Order_Partition(ctrl_t *ctrl, graph_t *graph, idx_t *nlevels, idx_t clevel)
{
CommSetup(ctrl, graph);
graph->ncon = 1;
IFSET(ctrl->dbglvl, DBG_PROGRESS, rprintf(ctrl, "[%6"PRIDX" %8"PRIDX" %5"PRIDX" %5"PRIDX"][%"PRIDX"][%"PRIDX"]\n",
graph->gnvtxs, GlobalSESum(ctrl, graph->nedges), GlobalSEMin(ctrl, graph->nvtxs),
GlobalSEMax(ctrl, graph->nvtxs), ctrl->CoarsenTo,
GlobalSEMax(ctrl, imax(graph->nvtxs, graph->vwgt))));
if ((*nlevels != -1 && *nlevels == clevel) ||
(*nlevels == -1 &&
((graph->gnvtxs < 1.66*ctrl->CoarsenTo) ||
(graph->finer != NULL && graph->gnvtxs > graph->finer->gnvtxs*COARSEN_FRACTION)))) {
/* set the nlevels to where coarsening stopped */
*nlevels = clevel;
/* Compute the initial npart-way multisection */
InitMultisection(ctrl, graph);
if (graph->finer == NULL) { /* Do that only if no-coarsening took place */
AllocateNodePartitionParams(ctrl, graph);
ComputeNodePartitionParams(ctrl, graph);
switch (ctrl->rtype) {
case PARMETIS_SRTYPE_GREEDY:
KWayNodeRefine_Greedy(ctrl, graph, NGR_PASSES, ctrl->ubfrac);
break;
case PARMETIS_SRTYPE_2PHASE:
KWayNodeRefine2Phase(ctrl, graph, NGR_PASSES, ctrl->ubfrac);
break;
default:
errexit("Unknown rtype of %"PRIDX"\n", ctrl->rtype);
}
}
}
else { /* Coarsen it and then partition it */
switch (ctrl->mtype) {
case PARMETIS_MTYPE_LOCAL:
Match_Local(ctrl, graph);
break;
case PARMETIS_MTYPE_GLOBAL:
Match_Global(ctrl, graph);
break;
default:
errexit("Unknown mtype of %"PRIDX"\n", ctrl->mtype);
}
Order_Partition(ctrl, graph->coarser, nlevels, clevel+1);
ProjectPartition(ctrl, graph);
AllocateNodePartitionParams(ctrl, graph);
ComputeNodePartitionParams(ctrl, graph);
switch (ctrl->rtype) {
case PARMETIS_SRTYPE_GREEDY:
KWayNodeRefine_Greedy(ctrl, graph, NGR_PASSES, ctrl->ubfrac);
break;
case PARMETIS_SRTYPE_2PHASE:
KWayNodeRefine2Phase(ctrl, graph, NGR_PASSES, ctrl->ubfrac);
break;
default:
errexit("Unknown rtype of %"PRIDX"\n", ctrl->rtype);
}
}
}
/*********************************************************************************/
/*! This function is used to assign labels to the nodes in the separators.
It uses the appropriate entry in the lastnode array to select label boundaries
and adjusts it for the next level. */
/*********************************************************************************/
void LabelSeparators(ctrl_t *ctrl, graph_t *graph, idx_t *lastnode, idx_t *perm,
idx_t *order, idx_t *sizes)
{
idx_t i, nvtxs, nparts, sid; idx_t *where, *lpwgts, *gpwgts, *sizescan;
nparts = ctrl->nparts;
nvtxs = graph->nvtxs;
where = graph->where;
lpwgts = graph->lpwgts;
gpwgts = graph->gpwgts;
if (ctrl->dbglvl&DBG_INFO) {
if (ctrl->mype == 0) {
printf("SepWgts: ");
for (i=0; i<nparts; i+=2)
printf(" %"PRIDX" [%"PRIDX" %"PRIDX"]", gpwgts[nparts+i], gpwgts[i], gpwgts[i+1]);
printf("\n");
}
gkMPI_Barrier(ctrl->comm);
}
/* Compute the local size of the separator. This is required in case the
graph has vertex weights */
iset(2*nparts, 0, lpwgts);
for (i=0; i<nvtxs; i++)
lpwgts[where[i]]++;
sizescan = imalloc(2*nparts, "LabelSeparators: sizescan");
/* Perform a Prefix scan of the separator sizes to determine the boundaries */
gkMPI_Scan((void *)lpwgts, (void *)sizescan, 2*nparts, IDX_T, MPI_SUM, ctrl->comm);
gkMPI_Allreduce((void *)lpwgts, (void *)gpwgts, 2*nparts, IDX_T, MPI_SUM, ctrl->comm);
#ifdef DEBUG_ORDER
PrintVector(ctrl, 2*nparts, 0, lpwgts, "Lpwgts");
PrintVector(ctrl, 2*nparts, 0, sizescan, "SizeScan");
PrintVector(ctrl, 2*nparts, 0, lastnode, "LastNode");
#endif
/* Fillin the sizes[] array. See the comment on MultilevelOrder() on the
purpose of the sizes[0] value. */
for (i=nparts-2; i>=0; i-=2)
sizes[--sizes[0]] = gpwgts[nparts+i];
if (ctrl->dbglvl&DBG_INFO) {
if (ctrl->mype == 0) {
printf("SepSizes: ");
for (i=0; i<nparts; i+=2)
printf(" %"PRIDX" [%"PRIDX" %"PRIDX"]", gpwgts[nparts+i], gpwgts[i], gpwgts[i+1]);
printf("\n");
}
gkMPI_Barrier(ctrl->comm);
}
for (i=0; i<2*nparts; i++)
sizescan[i] -= lpwgts[i];
/* Assign the order[] values to the separator nodes */
for (i=0; i<nvtxs; i++) {
if (where[i] >= nparts) {
sid = where[i];
sizescan[sid]++;
PASSERT(ctrl, order[perm[i]] == -1);
order[perm[i]] = lastnode[sid] - sizescan[sid];
/*myprintf(ctrl, "order[%"PRIDX"] = %"PRIDX", %"PRIDX"\n", perm[i], order[perm[i]], sid); */
}
}
/* Update lastnode array */
icopy(2*nparts, lastnode, sizescan);
for (i=0; i<nparts; i+=2) {
lastnode[2*nparts+2*i] = sizescan[nparts+i]-gpwgts[nparts+i]-gpwgts[i+1];
lastnode[2*nparts+2*(i+1)] = sizescan[nparts+i]-gpwgts[nparts+i];
/*myprintf(ctrl, "lastnode: %"PRIDX" %"PRIDX"\n", lastnode[2*nparts+2*i], * lastnode[2*nparts+2*(i+1)]);*/
}
gk_free((void **)&sizescan, LTERM);
}
/*************************************************************************
* This function compacts a graph by removing the vertex separator
**************************************************************************/
void CompactGraph(ctrl_t *ctrl, graph_t *graph, idx_t *perm)
{
idx_t i, j, l, nvtxs, cnvtxs, cfirstvtx, nparts, npes;
idx_t *xadj, *adjncy, *adjwgt, *vtxdist, *where;
idx_t *cmap, *cvtxdist, *newwhere;
WCOREPUSH;
nparts = ctrl->nparts;
npes = ctrl->npes;
nvtxs = graph->nvtxs;
xadj = graph->xadj;
adjncy = graph->adjncy;
adjwgt = graph->adjwgt;
where = graph->where;
if (graph->cmap == NULL)
graph->cmap = imalloc(nvtxs+graph->nrecv, "CompactGraph: cmap");
cmap = graph->cmap;
vtxdist = graph->vtxdist;
/*************************************************************
* Construct the cvtxdist of the contracted graph. Uses the fact
* that lpwgts stores the local non separator vertices.
**************************************************************/
cnvtxs = isum(nparts, graph->lpwgts, 1);
cvtxdist = iwspacemalloc(ctrl, npes+1);
gkMPI_Allgather((void *)&cnvtxs, 1, IDX_T, (void *)cvtxdist, 1, IDX_T,
ctrl->comm);
MAKECSR(i, npes, cvtxdist);
#ifdef DEBUG_ORDER
PrintVector(ctrl, npes+1, 0, cvtxdist, "cvtxdist");
#endif
/*************************************************************
* Construct the cmap vector
**************************************************************/
cfirstvtx = cvtxdist[ctrl->mype];
/* Create the cmap of what you know so far locally */
for (cnvtxs=0, i=0; i<nvtxs; i++) {
if (where[i] < nparts) {
perm[cnvtxs] = perm[i];
cmap[i] = cfirstvtx + cnvtxs++;
}
}
CommInterfaceData(ctrl, graph, cmap, cmap+nvtxs);
/*************************************************************
* Finally, compact the graph
**************************************************************/
newwhere = imalloc(cnvtxs, "CompactGraph: newwhere");
cnvtxs = l = 0;
for (i=0; i<nvtxs; i++) {
if (where[i] < nparts) {
for (j=xadj[i]; j<xadj[i+1]; j++) {
PASSERT(ctrl, where[i] == where[adjncy[j]] || where[adjncy[j]] >= nparts);
if (where[i] == where[adjncy[j]]) {
adjncy[l] = cmap[adjncy[j]];
adjwgt[l++] = adjwgt[j];
}
}
xadj[cnvtxs] = l;
graph->vwgt[cnvtxs] = graph->vwgt[i];
newwhere[cnvtxs] = where[i];
cnvtxs++;
}
}
SHIFTCSR(i, cnvtxs, xadj);
gk_free((void **)&graph->match, (void **)&graph->cmap, (void **)&graph->lperm,
(void **)&graph->where, (void **)&graph->label, (void **)&graph->ckrinfo,
(void **)&graph->nrinfo, (void **)&graph->lpwgts, (void **)&graph->gpwgts,
(void **)&graph->sepind, (void **)&graph->peind,
(void **)&graph->sendptr, (void **)&graph->sendind,
(void **)&graph->recvptr, (void **)&graph->recvind,
(void **)&graph->imap, (void **)&graph->rlens, (void **)&graph->slens,
(void **)&graph->rcand, (void **)&graph->pexadj,
(void **)&graph->peadjncy, (void **)&graph->peadjloc, LTERM);
graph->nvtxs = cnvtxs;
graph->nedges = l;
graph->gnvtxs = cvtxdist[npes];
graph->where = newwhere;
icopy(npes+1, cvtxdist, graph->vtxdist);
WCOREPOP;
}
/*************************************************************************/
/*! This function orders the locally stored graph using MMD. The vertices
will be ordered from firstnode onwards. */
/*************************************************************************/
void LocalNDOrder(ctrl_t *ctrl, graph_t *graph, idx_t *order, idx_t firstnode)
{
idx_t i, j, nvtxs, firstvtx, lastvtx;
idx_t *xadj, *adjncy;
idx_t *perm, *iperm;
idx_t numflag=0, options[METIS_NOPTIONS];
IFSET(ctrl->dbglvl, DBG_TIME, starttimer(ctrl->SerialTmr));
WCOREPUSH;
nvtxs = graph->nvtxs;
xadj = graph->xadj;
adjncy = graph->adjncy;
firstvtx = graph->vtxdist[ctrl->mype];
lastvtx = graph->vtxdist[ctrl->mype+1];
/* Relabel the vertices so that they are in local index space */
for (i=0; i<nvtxs; i++) {
for (j=xadj[i]; j<xadj[i+1]; j++) {
PASSERT(ctrl, adjncy[j]>=firstvtx && adjncy[j]<lastvtx);
adjncy[j] -= firstvtx;
}
}
perm = iwspacemalloc(ctrl, nvtxs+5);
iperm = iwspacemalloc(ctrl, nvtxs+5);
METIS_SetDefaultOptions(options);
options[METIS_OPTION_NSEPS] = ctrl->s_nseps;
METIS_NodeND(&nvtxs, xadj, adjncy, graph->vwgt, options, perm, iperm);
for (i=0; i<nvtxs; i++) {
PASSERT(ctrl, iperm[i]>=0 && iperm[i]<nvtxs);
order[i] = firstnode+iperm[i];
}
WCOREPOP;
IFSET(ctrl->dbglvl, DBG_TIME, stoptimer(ctrl->SerialTmr));
}
| 2.046875 | 2 |
2024-11-18T20:55:50.008037+00:00 | 2021-09-29T18:02:34 | d9985b5306d12dbdae167de2ecff7c54310542fd | {
"blob_id": "d9985b5306d12dbdae167de2ecff7c54310542fd",
"branch_name": "refs/heads/main",
"committer_date": "2021-09-29T18:02:34",
"content_id": "d7bfcff121f0230b667ed4e304180f42cbb8b539",
"detected_licenses": [
"MIT"
],
"directory_id": "2e86de3fa6ae8b0aef97c985de433b4475b1a294",
"extension": "c",
"filename": "Assignment5DS.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 392778143,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1358,
"license": "MIT",
"license_type": "permissive",
"path": "/Assignment5DS.c",
"provenance": "stackv2-0092.json.gz:50955",
"repo_name": "ankushbhagat124/Practice-Code",
"revision_date": "2021-09-29T18:02:34",
"revision_id": "880ecc2f435de8d7ab4ba43cd10184aaa85ace37",
"snapshot_id": "491c217049d3b14da7cbd9d90f974724954bed11",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ankushbhagat124/Practice-Code/880ecc2f435de8d7ab4ba43cd10184aaa85ace37/Assignment5DS.c",
"visit_date": "2023-07-28T20:53:11.701836"
} | stackv2 | #include <stdio.h>
#define size 10
struct Stack
{
int a[size];
int top;
};
void push (struct Stack *s, int x)
{
if (s->top == size-1)
printf("Stack is Full!");
else
{
s->top = s->top + 1;
s->a[s->top] = x;
}
}
int pop (struct Stack *s)
{
if (s->top == -1)
{
printf("Stack is Empty!");
return -1;
}
else
{
int y = s->a[s->top];
s->top = s->top - 1;
return y;
}
}
void display (struct Stack s)
{
int i = s.top;
printf("Elements are: ");
while (i != -1)
{
printf("%d ", s.a[i]);
i--;
}
}
int main ()
{
struct Stack s;
s.top = -1;
int x, option;
do
{
printf("\nMENU Options:\n");
printf("1.Push\n");
printf("2.Pop\n");
printf("3.Display\n");
printf("4.EXIT\n");
scanf("%d", &option);
switch(option)
{
case 1: printf("Enter x: ");
scanf("%d", &x);
push(&s, x);
break;
case 2: x = pop(&s);
printf("%d is deleted from the stack.\n", x);
break;
case 3: display(s);
break;
}
}while (option != 4);
} | 3.96875 | 4 |
2024-11-18T20:55:50.167263+00:00 | 2016-05-13T17:11:40 | cf8355d9d4aa1c01c4261a07995764b09a32fac7 | {
"blob_id": "cf8355d9d4aa1c01c4261a07995764b09a32fac7",
"branch_name": "refs/heads/master",
"committer_date": "2016-05-13T17:12:29",
"content_id": "9589dbbe93fb0654a7dcdc2d2a3cea37bd2ba641",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "5c2674e36384de98742aba658b169664a1c74495",
"extension": "c",
"filename": "wcwidth-cmd.c",
"fork_events_count": 2,
"gha_created_at": "2016-11-15T03:35:42",
"gha_event_created_at": "2016-11-15T03:35:43",
"gha_language": null,
"gha_license_id": null,
"github_id": 73773006,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1688,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/wcwidth-cmd.c",
"provenance": "stackv2-0092.json.gz:51211",
"repo_name": "river24/wcwidth-cjk",
"revision_date": "2016-05-13T17:11:40",
"revision_id": "ac3a9ceb020c7499da0b347ec9918b87b253b7a8",
"snapshot_id": "f4e3974cc9f4acde6be91358410a69fa30fbd83e",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/river24/wcwidth-cjk/ac3a9ceb020c7499da0b347ec9918b87b253b7a8/wcwidth-cmd.c",
"visit_date": "2020-07-25T18:14:47.215335"
} | stackv2 | #define _XOPEN_SOURCE
#define is_little_endian() (1 == *(unsigned char *)&(const int){1})
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <alloca.h>
#include <locale.h>
#include <wchar.h>
void dump_bigendian(FILE *fp, void *p_in, int size) {
unsigned char *p;
int i;
for (p = p_in, i = 0; i < size; i++) {
fprintf(fp, " %02X", *(p + i));
}
}
void dump_littleendian(FILE *fp, void *p_in, int size) {
unsigned char *p;
int i;
for (p = p_in, i = size - 1; i >= 0; i--) {
fprintf(fp, " %02X", *(p + i));
}
}
int main(int argc, char **argv) {
int i;
int mb_consumed;
char *mb_p;
size_t mb_len;
char *mb_buf;
wchar_t wc;
int wc_width;
void (*dump)(FILE *fp, void *p_in, int size) =
is_little_endian() ? dump_littleendian : dump_bigendian;
if (argc < 2) {
printf("Usage: %s STRING [...]\n", argv[0]);
exit(1);
}
setlocale (LC_ALL, "");
mbtowc(NULL, NULL, 0);
mb_buf = alloca(MB_CUR_MAX + 1);
for (i = 1; i < argc; i++) {
mb_p = argv[i];
mb_len = strlen(mb_p);
while (mb_len > 0) {
mb_consumed = mbtowc(&wc, mb_p, mb_len);
if (mb_consumed == -1) {
fprintf(stderr,
"%s: ERROR: Invalid multibyte sequence: argv=%d, index=%d, bytes:",
argv[0],
i,
(int)(mb_p - argv[i])
);
dump_bigendian(stderr, mb_p, mb_len);
fputs("\n", stderr);
exit(1);
}
wc_width = wcwidth(wc);
strncpy(mb_buf, mb_p, mb_consumed);
mb_buf[mb_consumed] = '\0';
printf("%d", wc_width);
dump(stdout, &wc, sizeof(wchar_t));
printf("\t%s\n", mb_buf);
mb_p += mb_consumed;
mb_len -= mb_consumed;
}
}
exit(0);
}
| 2.84375 | 3 |
2024-11-18T20:55:50.452788+00:00 | 2016-04-29T09:50:35 | d33490b5fadd6ca5d7b71863880abcca2f540eea | {
"blob_id": "d33490b5fadd6ca5d7b71863880abcca2f540eea",
"branch_name": "refs/heads/master",
"committer_date": "2016-04-29T09:50:35",
"content_id": "0ddccd47644a83d947f03fcfffeef33c2df03215",
"detected_licenses": [
"MIT"
],
"directory_id": "bb728a0b81f55fb73f30d60a7e7dac1d3b67fa94",
"extension": "c",
"filename": "exo8.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 57373153,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2173,
"license": "MIT",
"license_type": "permissive",
"path": "/PSR/TP2/exo8.c",
"provenance": "stackv2-0092.json.gz:51341",
"repo_name": "pallamidessi/Courses",
"revision_date": "2016-04-29T09:50:35",
"revision_id": "ac5573cefc4c307c1a9f16a2c4e016a201dabece",
"snapshot_id": "7217ae49d7e3b202b3f411c4f37681ccaa3a0004",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/pallamidessi/Courses/ac5573cefc4c307c1a9f16a2c4e016a201dabece/PSR/TP2/exo8.c",
"visit_date": "2021-01-01T05:14:27.515061"
} | stackv2 |
/**
* \file exo8.c
* \author Pallamidessi joseph
* \version 1.0
* \date 16 octobre 2012
* \brief
*
* \details
*
*/
#include <sys/types.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <ctype.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N 20
#define M 50
/*transforme une chaine en une structure contenant un tableaux de mot,et une indication
* pour savoir s'il faut executer la commande suivante directement*/
typedef struct Commande{
char** cmd;
int cmd_suivante;
} str_commande,*commande;
commande decoupage(char* chaine){
int i=0,j=0,l=0,exec=0;
commande tab=(commande) malloc (sizeof(str_commande));
tab->cmd=(char**) malloc(N*sizeof(char*));
for(i=0;i<N;i++){
tab->cmd[i]=(char*) malloc(M*sizeof(char));
}
tab->cmd_suivante=0;
i=0,j=0,l=0; //on decoupe la cahine en mot (separateur " ",fin '\0')
while(chaine[i]!='\n'){
exec=1;
if(chaine[i]=='&'){ // le cas cmd&
tab->cmd_suivante=1;
i++;
exec=0;
}
if(chaine[i]==32){
tab->cmd[j][l]='\0';
j++;
i++;
l=0;
if(chaine[i]=='\n')
exec=0;
}
if(exec==1){
tab->cmd[j][l]=chaine[i];
l++;
i++;
}
}
tab->cmd[j][l]='\0';
j+=1;
tab->cmd[j]=(char*) NULL;
j-=1;
if((strcmp(tab->cmd[j],"&"))==0){ //le cas cmd &
printf("le test est vrai");
tab->cmd_suivante=1;
tab->cmd[j]=NULL;
}
return tab;
}
int main(int args,char* argv[]){
int i;
commande mot_decoupe;
FILE* pIN=fdopen(1,"r");
char entree[256];
pid_t pid_fils;
int status;
while(1){
fgets(entree,256,pIN);
mot_decoupe=decoupage(entree);
if(mot_decoupe->cmd_suivante==0){
if((pid_fils=fork())==0){
execvp(mot_decoupe->cmd[0],mot_decoupe->cmd);
printf("erreur\n");
break;
}
else
wait(NULL);
}
else{
if(fork()==0){
execvp(mot_decoupe->cmd[0],mot_decoupe->cmd);
printf("erreur\n");
break;
}
else
waitpid(pid_fils,&status,WNOHANG); //On fait un wait non bloquant
}
for(i=0;i<N;i++)
free(mot_decoupe->cmd[i]);
free(mot_decoupe);
}
return 0;
}
| 2.78125 | 3 |
2024-11-18T20:55:50.510883+00:00 | 2013-04-17T18:42:40 | b1728cc2dde83bce46bdffc32e07abfea4c88d13 | {
"blob_id": "b1728cc2dde83bce46bdffc32e07abfea4c88d13",
"branch_name": "refs/heads/master",
"committer_date": "2013-04-17T18:42:40",
"content_id": "ee827b56ea84ba1a6e04f39ef68f554f77574965",
"detected_licenses": [
"MIT"
],
"directory_id": "bb108c3ea7d235e6fee0575181b5988e6b6a64ef",
"extension": "c",
"filename": "printer.c",
"fork_events_count": 8,
"gha_created_at": "2012-03-23T04:23:01",
"gha_event_created_at": "2013-04-17T18:42:41",
"gha_language": "C",
"gha_license_id": null,
"github_id": 3805274,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3196,
"license": "MIT",
"license_type": "permissive",
"path": "/mame/src/emu/imagedev/printer.c",
"provenance": "stackv2-0092.json.gz:51469",
"repo_name": "clobber/MAME-OS-X",
"revision_date": "2013-04-17T18:42:40",
"revision_id": "ca11d0e946636bda042b6db55c82113e5722fc08",
"snapshot_id": "3c5e6058b2814754176f3c6dcf1b2963ca804fc3",
"src_encoding": "UTF-8",
"star_events_count": 15,
"url": "https://raw.githubusercontent.com/clobber/MAME-OS-X/ca11d0e946636bda042b6db55c82113e5722fc08/mame/src/emu/imagedev/printer.c",
"visit_date": "2021-01-20T05:31:15.086981"
} | stackv2 | /****************************************************************************
printer.c
Code for handling printer devices
****************************************************************************/
#include "emu.h"
#include "printer.h"
// device type definition
const device_type PRINTER = &device_creator<printer_image_device>;
//-------------------------------------------------
// printer_image_device - constructor
//-------------------------------------------------
printer_image_device::printer_image_device(const machine_config &mconfig, const char *tag, device_t *owner, UINT32 clock)
: device_t(mconfig, PRINTER, "Printer", tag, owner, clock),
device_image_interface(mconfig, *this)
{
}
//-------------------------------------------------
// printer_image_device - destructor
//-------------------------------------------------
printer_image_device::~printer_image_device()
{
}
//-------------------------------------------------
// device_config_complete - perform any
// operations now that the configuration is
// complete
//-------------------------------------------------
void printer_image_device::device_config_complete()
{
// inherit a copy of the static data
const printer_interface *intf = reinterpret_cast<const printer_interface *>(static_config());
if (intf != NULL)
*static_cast<printer_interface *>(this) = *intf;
// or initialize to defaults if none provided
else
{
memset(&m_online, 0, sizeof(m_online));
}
// set brief and instance name
update_names();
}
//-------------------------------------------------
// device_start - device-specific startup
//-------------------------------------------------
void printer_image_device::device_start()
{
m_online_func.resolve(m_online, *this);
}
/***************************************************************************
IMPLEMENTATION
***************************************************************************/
/*-------------------------------------------------
printer_is_ready - checks to see if a printer
is ready
-------------------------------------------------*/
int printer_image_device::is_ready()
{
return exists() != 0;
}
/*-------------------------------------------------
printer_output - outputs data to a printer
-------------------------------------------------*/
void printer_image_device::output(UINT8 data)
{
if (exists())
{
fwrite(&data, 1);
}
}
/*-------------------------------------------------
DEVICE_IMAGE_LOAD( printer )
-------------------------------------------------*/
bool printer_image_device::call_load()
{
/* send notify that the printer is now online */
if (!m_online_func.isnull())
m_online_func(TRUE);
/* we don't need to do anything special */
return IMAGE_INIT_PASS;
}
/*-------------------------------------------------
DEVICE_IMAGE_UNLOAD( printer )
-------------------------------------------------*/
void printer_image_device::call_unload()
{
/* send notify that the printer is now offline */
if (!m_online_func.isnull())
m_online_func(FALSE);
}
| 2.375 | 2 |
2024-11-18T20:55:50.725900+00:00 | 2023-06-17T17:46:23 | 28a293623f2b18c05b0c3e4bb953ff3841af4562 | {
"blob_id": "28a293623f2b18c05b0c3e4bb953ff3841af4562",
"branch_name": "refs/heads/master",
"committer_date": "2023-07-11T12:25:31",
"content_id": "dce1fe25384ee714d2aa942e4ef7f6e1ec0827d9",
"detected_licenses": [
"Unlicense"
],
"directory_id": "01ace0f357a25a895df67b2fe60020a9e9713766",
"extension": "h",
"filename": "recv.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 147276452,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1312,
"license": "Unlicense",
"license_type": "permissive",
"path": "/server/libkvpsync/recv.h",
"provenance": "stackv2-0092.json.gz:51597",
"repo_name": "Splintermail/splintermail-client",
"revision_date": "2023-06-17T17:46:23",
"revision_id": "029757f727e338d7c9fa251ea71a894097426146",
"snapshot_id": "10e7f370b6859e1ae5d75bdaa89f4f1d24e9bb81",
"src_encoding": "UTF-8",
"star_events_count": 4,
"url": "https://raw.githubusercontent.com/Splintermail/splintermail-client/029757f727e338d7c9fa251ea71a894097426146/server/libkvpsync/recv.h",
"visit_date": "2023-07-21T15:36:03.409326"
} | stackv2 | /* It is technically possible for a delete to cancel an update, then for a
duplicate of the update to appear and remain forever, so we prevent that by
leaving deletions in the data structure for a few minutes to ensure that no
stray network packet could be still circulating. We use the IPv4 max TTL
even though in practice that's a lot longer than a real packet can live. */
#define GC_DELAY 255
// kvpsync_recv_t is the receiver's side of kvp sync
typedef struct {
hashmap_t h; // maps dstr_t keys to dstr_t values
uint32_t recv_id; // randomly chosen at boot
uint32_t sync_id; // the send_id for a sync we've completed, or zero
bool initial_sync_acked;
xtime_t ok_expiry;
link_t gc; // recv_datum_t->gc
} kvpsync_recv_t;
derr_t kvpsync_recv_init(kvpsync_recv_t *r);
void kvpsync_recv_free(kvpsync_recv_t *r);
// process an incoming packet and configure the ack
// (pre-initial-syncs are acked with reset packets)
derr_t kvpsync_recv_handle_update(
kvpsync_recv_t *r, xtime_t now, kvp_update_t update, kvp_ack_t *ack
);
extern const dstr_t *UNSURE;
/* returns NULL, UNSURE, or an answer, and is only guaranteed to be valid
until the next call to handle_update() */
const dstr_t *kvpsync_recv_get_value(
kvpsync_recv_t *r, xtime_t now, const dstr_t key
);
| 2.09375 | 2 |
2024-11-18T20:55:51.120860+00:00 | 2021-02-01T16:54:30 | e2d7d90a48ec04cd378ea067be87a6506c6af071 | {
"blob_id": "e2d7d90a48ec04cd378ea067be87a6506c6af071",
"branch_name": "refs/heads/main",
"committer_date": "2021-02-01T16:54:30",
"content_id": "5001888cc53700067eca3ff57305f189a658a1b6",
"detected_licenses": [
"MIT"
],
"directory_id": "c72f4da813b0e0357141a9e110c66b3e79d9419c",
"extension": "c",
"filename": "lesson7_2.c",
"fork_events_count": 0,
"gha_created_at": "2021-01-24T10:29:23",
"gha_event_created_at": "2021-01-26T19:08:32",
"gha_language": "C",
"gha_license_id": null,
"github_id": 332420528,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 864,
"license": "MIT",
"license_type": "permissive",
"path": "/src/C-module/lesson-7/lesson7_2.c",
"provenance": "stackv2-0092.json.gz:51856",
"repo_name": "dark0ghost/cups-solutions",
"revision_date": "2021-02-01T16:54:30",
"revision_id": "45b7826b91eb66c9b8c766255efa8c1270874805",
"snapshot_id": "b57af3f12e74f8254828795e51f78d4b1f0fa687",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/dark0ghost/cups-solutions/45b7826b91eb66c9b8c766255efa8c1270874805/src/C-module/lesson-7/lesson7_2.c",
"visit_date": "2023-02-25T13:31:00.390914"
} | stackv2 | /**
Напишите функцию с названием printer. Функция принимает два указателя на целое число. Первый указатель указывает на начало массива, а второй на элемент, следующий за последним элементом массива.
Напишите код, который выводит каждый четвертый элемент массива, если он делится на 4 нацело.
Примените для вывода функцию printf("%ld\n", num), где num - это очередное число для вывода
**/
void printer(const long int* begin, const long int* end){
begin += 3;
for(; begin < end;){
if(*begin % 4 == 0)
printf("%ld ",*begin);
begin += 4;
}
} | 3.203125 | 3 |
2024-11-18T20:55:51.818862+00:00 | 2021-09-14T01:06:12 | 3257221a0c188cee4d611d6917baba340df0dce5 | {
"blob_id": "3257221a0c188cee4d611d6917baba340df0dce5",
"branch_name": "refs/heads/main",
"committer_date": "2021-09-14T01:06:12",
"content_id": "92bde0818c02553f26b55a40c1aacec5c4c60e8e",
"detected_licenses": [
"MIT"
],
"directory_id": "a68ba3fc0eb86b0ea1fa21152ba253eeee06b63e",
"extension": "c",
"filename": "Exerc7 Lista2Es.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 406155520,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 539,
"license": "MIT",
"license_type": "permissive",
"path": "/Sequencial Structures/Lista 2/Exerc7 Lista2Es.c",
"provenance": "stackv2-0092.json.gz:52243",
"repo_name": "whoiswelliton/Programming_Fundamentals",
"revision_date": "2021-09-14T01:06:12",
"revision_id": "63d41e0d14b67cc64d38b0188b583dd8f8ac2905",
"snapshot_id": "68e458ce5b1c36f24e82a09085445763be8aa322",
"src_encoding": "ISO-8859-1",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/whoiswelliton/Programming_Fundamentals/63d41e0d14b67cc64d38b0188b583dd8f8ac2905/Sequencial Structures/Lista 2/Exerc7 Lista2Es.c",
"visit_date": "2023-09-05T00:55:52.418712"
} | stackv2 | #include <stdio.h>
#include <stdlib.h>
/*
Faça um programa que leia o preço de uma mercadoria com diferença de um mês e calcule a taxa de
inflação (ou deflação) mensal dessa mercadoria.
*/
int main (void)
{
float MP, MA, Inflacao;
printf("Informe o valor da mercadoria no Mes Passado: ");
scanf("%f",&MP);
printf("Informe o valor da mercadoria no Mes Atual : ");
scanf("%f",&MA);
Inflacao=((MP - MA)*100)/MP;
printf("A taxa de inflacao ou deflacao e de: %.2f%%\n",Inflacao);
system("pause");
}
| 3.25 | 3 |
2024-11-18T20:55:52.889456+00:00 | 2016-11-27T02:47:34 | 4a5bd275e257c126d1dae2a7a1f3f92114761c2e | {
"blob_id": "4a5bd275e257c126d1dae2a7a1f3f92114761c2e",
"branch_name": "refs/heads/master",
"committer_date": "2016-11-27T02:47:34",
"content_id": "8bc89005a482392daff1ec4bf380f95a7e3bbf60",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "f720369e167889b8c65fb5c9f9ded80a8378a200",
"extension": "c",
"filename": "commands.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 50606707,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3202,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/src/tools/hterm/src/commands.c",
"provenance": "stackv2-0092.json.gz:52630",
"repo_name": "eugenecartwright/hthreads",
"revision_date": "2016-11-27T02:47:34",
"revision_id": "826c495dd855f8fcc1e12e1ac01845c2983ecf04",
"snapshot_id": "1aa2af6838738ad49376511333a7b546ba47fa86",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/eugenecartwright/hthreads/826c495dd855f8fcc1e12e1ac01845c2983ecf04/src/tools/hterm/src/commands.c",
"visit_date": "2020-04-06T07:00:23.582279"
} | stackv2 | #include <hterm.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
void reset_command( void *data, char *args )
{
hterm_t *term;
term = (hterm_t*)data;
term->bytes = 0;
term->received = 0;
clearok( curscr, TRUE );
hwin_clear( &term->scr );
hwin_refresh( &term->scr );
}
void clear_command( void *data, char *args )
{
hterm_t *term;
term = (hterm_t*)data;
clearok( curscr, TRUE );
hwin_clear( &term->scr );
hwin_refresh( &term->scr );
}
void quit_command( void *data, char *args )
{
hterm_t *term;
term = (hterm_t*)data;
term->exit = 1;
}
void listen_command( void *data, char *args )
{
int num;
int port;
char **opts;
hterm_t *term;
term = (hterm_t*)data;
port = 7284;
if( args != NULL ) port = atoi( args );
if(port == 0) hwin_addstr(&term->scr,"\nUsage: listen <port>\n");
if(port < 0) hwin_addstr(&term->scr,"\nInvalid port: must be 1 - 65535\n");
if( port > 0 )
{
hwin_printw( &term->scr, "\nListening on TCP/IP port %d\n\n", port );
hinput_listener( &term->input, port, recv_listen, term );
}
hwin_refresh( &term->scr );
}
void serial_command( void *data, char *args )
{
int i;
int fd;
int inv;
int num;
int baud;
char dev[4192];
char *save;
char *tokn;
char *next;
hterm_t *term;
term = (hterm_t*)data;
inv = 0;
strncpy( dev, "/dev/ttyS0", 4192 );
baud = 115200;
tokn = strtok_r( args, " \t\n\r", &save );
while( tokn != NULL )
{
if(strcmp(tokn, "--baud") == 0 || strcmp(tokn, "-b") == 0)
{
next = strtok_r( NULL, " \t\n\r", &save );
if( next == NULL ) { inv = 1; break; }
baud = atoi( next );
}
else if(strcmp(tokn, "--dev") == 0 || strcmp(tokn, "-d") == 0)
{
next = strtok_r( NULL, " \t\n\r", &save );
if( next == NULL ) { inv = 1; break; }
strncpy( dev, next, 4192 );
}
else
{
inv = 1;
break;
}
tokn = strtok_r( NULL, " \t\n\r", &save );
}
if( inv )
{
hwin_addstr(&term->scr, "\nUsage: serial --baud <baud> --dev <dev>\n");
}
else
{
hwin_addstr( &term->scr, "\nReceiving data on serial port\n" );
hwin_printw( &term->scr, "\tBaud: %d\n", baud );
hwin_printw( &term->scr, "\tDevice: \"%s\"\n", dev );
fd = hinput_serial( &term->input, dev, baud, recv_serial, term );
if( fd < 0 )
{
hwin_printw( &term->scr, "\tFailed: %s\n", strerror(errno) );
}
}
hwin_refresh( &term->scr );
}
void help_command_show( void *data, const char *fmt, ... )
{
hterm_t *term;
va_list args;
term = (hterm_t*)data;
va_start( args, fmt );
hwin_vprintw( &term->scr, fmt, args );
va_end( args );
}
void help_command( void *data, char *args)
{
hterm_t *term;
term = (hterm_t*)data;
hwin_clear( &term->scr );
hwin_printw( &term->scr, "Available Commands:\n" );
hcommand_help( &term->commands, help_command_show, term );
hwin_refresh( &term->scr );
}
| 2.4375 | 2 |
2024-11-18T20:55:53.837265+00:00 | 2017-06-30T21:32:06 | 0f9a5075341b25e25728734f481cda1433a54d4e | {
"blob_id": "0f9a5075341b25e25728734f481cda1433a54d4e",
"branch_name": "refs/heads/master",
"committer_date": "2017-06-30T21:32:06",
"content_id": "fd8d73da2def6fbdd9f57762f08e0ec2f7f35a00",
"detected_licenses": [
"MIT"
],
"directory_id": "4bd36db56cad5b790e01e48dd55be67a638222c2",
"extension": "h",
"filename": "functions.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 95925327,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 739,
"license": "MIT",
"license_type": "permissive",
"path": "/cpts_122/lab2_jan29/functions.h",
"provenance": "stackv2-0092.json.gz:53016",
"repo_name": "johnnydevriese/wsu_comp_sci",
"revision_date": "2017-06-30T21:32:06",
"revision_id": "1ece76ceb0551eb277499e3dff76d0181254bc8a",
"snapshot_id": "c1d2c7ff241a6673f8842aa44d2c4298b8c45f99",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/johnnydevriese/wsu_comp_sci/1ece76ceb0551eb277499e3dff76d0181254bc8a/cpts_122/lab2_jan29/functions.h",
"visit_date": "2020-12-03T02:18:47.356591"
} | stackv2 | #include<stdio.h>
#include<stdlib.h>
#include<string.h> //strcpy()
typedef struct node{
char * first_name[25] ;
char * last_name[25];
char * phone[10] ;
char * email[50];
char * title[25];
struct ContactNode *pNext ; //self referential to get to the next node in the linked list.
}ContactNode
//allocates dynamic memory
ContactNode *makeNode (char * first, char *last, char *number, char *address, char *job);
//use some of Andy's code. in order to get it to work
void insertFront(contactNode **pHead, char * first, char * las, char * number, char * address, char *job); // we link nodes
void printList (contact Node *pHead); // single star
int deleteNode(ContactNode **phead, char *first, char *last);
| 2.78125 | 3 |
2024-11-18T20:55:53.899330+00:00 | 2020-06-07T05:09:23 | 945a6b0b7b74f62906da83f418f6e5b90bbeecd0 | {
"blob_id": "945a6b0b7b74f62906da83f418f6e5b90bbeecd0",
"branch_name": "refs/heads/master",
"committer_date": "2020-06-07T05:09:23",
"content_id": "cda273614a154d46d1653ff6d46f65f61cb49892",
"detected_licenses": [
"MIT"
],
"directory_id": "884c92600f36c2f5a65263cb130062c13900b735",
"extension": "c",
"filename": "MemAddresses.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 267081181,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 478,
"license": "MIT",
"license_type": "permissive",
"path": "/CProgramming/src/Advanced/MemAddresses.c",
"provenance": "stackv2-0092.json.gz:53146",
"repo_name": "AkBo24/CProgramming",
"revision_date": "2020-06-07T05:09:23",
"revision_id": "66485386f99842100878418496e24e1d05e5383c",
"snapshot_id": "2b871cbbc9a20dfe94a53a5fb83cedb5375b4c52",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/AkBo24/CProgramming/66485386f99842100878418496e24e1d05e5383c/CProgramming/src/Advanced/MemAddresses.c",
"visit_date": "2022-10-09T16:06:00.143748"
} | stackv2 | /*
* MemAddresses.c
*
* Created on: May 26, 2020
* Author: akshaybodla
*/
#include <stdio.h>
#include <stdlib.h>
void memMain() {
puts("Memory Adresses!");
puts("Each variable points to a specific location that we can \naccess w/ the '&' symbol");
int memory = 9;
//access the location of memory with &memory
printf("\nFor instance the variable 'memory' is located at %p\n", &memory);
puts("As seen above the address is a 12 digit hexadecimal number");
}
| 3.21875 | 3 |
2024-11-18T20:55:53.966476+00:00 | 2021-02-13T08:10:53 | 3ea1f0748d3c3025a3eca196dbd12314b66e606a | {
"blob_id": "3ea1f0748d3c3025a3eca196dbd12314b66e606a",
"branch_name": "refs/heads/main",
"committer_date": "2021-02-13T08:10:53",
"content_id": "1d52d582f6a14182ece1bc3db41c86f3fb2b4e3d",
"detected_licenses": [
"MIT"
],
"directory_id": "2b46746191b725f53d5d9ace994674de1e3d12e4",
"extension": "c",
"filename": "ADTSet.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 338301934,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 21194,
"license": "MIT",
"license_type": "permissive",
"path": "/2020-lab-5-Data-Structures/modules/UsingAVL/ADTSet.c",
"provenance": "stackv2-0092.json.gz:53274",
"repo_name": "tech-gian/2020-Spring-Data-Structures",
"revision_date": "2021-02-13T08:10:53",
"revision_id": "261d28e8c6c1dd1f5b1e28f049a360465c5ebcea",
"snapshot_id": "c658652ce425f332e0043edf0dea865f4897fa0a",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/tech-gian/2020-Spring-Data-Structures/261d28e8c6c1dd1f5b1e28f049a360465c5ebcea/2020-lab-5-Data-Structures/modules/UsingAVL/ADTSet.c",
"visit_date": "2023-03-04T09:05:57.634220"
} | stackv2 | ///////////////////////////////////////////////////////////
//
// Υλοποίηση του ADT Set μέσω AVL Tree
//
///////////////////////////////////////////////////////////
#include <stdlib.h>
#include <assert.h>
#include "ADTSet.h"
// Υλοποιούμε τον ADT Set μέσω AVL, οπότε το struct set είναι ένα AVL Δέντρο.
struct set {
SetNode root; // η ρίζα, NULL αν είναι κενό δέντρο
int size; // μέγεθος, ώστε η set_size να είναι Ο(1)
CompareFunc compare; // η διάταξη
DestroyFunc destroy_value; // Συνάρτηση που καταστρέφει ένα στοιχείο του set
};
// Ενώ το struct set_node είναι κόμβος ενός AVL Δέντρου Αναζήτησης
struct set_node {
SetNode left, right; // Παιδιά
Pointer value; // Τιμή κόμβου
int height; // Ύψος που βρίσκεται ο κόμβος στο δέντρο
};
//// Συναρτήσεις που υλοποιούν επιπλέον λειτουργίες του AVL σε σχέση με ένα απλό BST /////////////////////////////////////
// Επιστρέφει τη max τιμή μεταξύ 2 ακεραίων
static int int_max(int a, int b) {
return (a > b) ? a : b ;
}
// Επιστρέφει το ύψος που βρίσκεται ο κόμβος στο δέντρο
static int node_height(SetNode node) {
if (!node) return 0;
return node->height;
}
// Ενημερώνει το ύψος ενός κόμβου
static void node_update_height(SetNode node) {
node->height = 1 + int_max(node_height(node->left), node_height(node->right));
}
// Επιστρέφει τη διαφορά ύψους μεταξύ αριστερού και δεξιού υπόδεντρου
static int node_balance(SetNode node) {
return node_height(node->left) - node_height(node->right);
}
// Rotations : Όταν η διαφορά ύψους μεταξύ αριστερού και δεξιού υπόδεντρου είναι
// μεγαλύτερη του 1 το δέντρο δεν είναι πια AVL. Υπάρχουν 4 διαφορετικά
// rotations που εφαρμόζονται ανάλογα με την περίπτωση για να αποκατασταθεί η
// ισορροπία. Η κάθε συνάρτηση παίρνει ως όρισμα τον κόμβο που πρέπει να γίνει
// rotate, και επιστρέφει τη ρίζα του νέου υποδέντρου.
// Single left rotation
static SetNode node_rotate_left(SetNode node) {
SetNode right_node = node->right;
SetNode left_subtree = right_node->left;
right_node->left = node;
node->right = left_subtree;
node_update_height(node);
node_update_height(right_node);
return right_node;
}
// Single right rotation
static SetNode node_rotate_right(SetNode node) {
SetNode left_node = node->left;
SetNode left_right = left_node->right;
left_node->right = node;
node->left = left_right;
node_update_height(node);
node_update_height(left_node);
return left_node;
}
// Double left-right rotation
static SetNode node_rotate_left_right(SetNode node) {
node->left = node_rotate_left(node->left);
return node_rotate_right(node);
}
// Double right-left rotation
static SetNode node_rotate_right_left(SetNode node) {
node->right = node_rotate_right(node->right);
return node_rotate_left(node);
}
// Επισκευή του AVL property αν δεν ισχύει
static SetNode node_repair_balance(SetNode node) {
node_update_height(node);
int balance = node_balance(node);
if (balance > 1) {
// το αριστερό υπόδεντρο είναι unbalanced
if (node_balance(node->left) >= 0)
return node_rotate_right(node);
else
return node_rotate_left_right(node);
} else if (balance < -1) {
// το δεξί υπόδεντρο είναι unbalanced
if (node_balance(node->right) <= 0)
return node_rotate_left(node);
else
return node_rotate_right_left(node);
}
// δεν χρειάστηκε να πραγματοποιηθεί rotation
return node;
}
//// Συναρτήσεις που είναι (σχεδόν) _ολόιδιες_ με τις αντίστοιχες της BST υλοποίησης ////////////////
//
// Είναι σημαντικό να κατανοήσουμε πρώτα τον κώδικα του BST πριν από αυτόν του AVL.
// Θα μπορούσαμε οργανώνοντας τον κώδικα διαφορετικά να επαναχρησιμοποιήσουμε τις συναρτήσεις αυτές.
//
// Οι διαφορές είναι σημειωμένες με "AVL" σε σχόλιο
// Δημιουργεί και επιστρέφει έναν κόμβο με τιμή value (χωρίς παιδιά)
//
static SetNode node_create(Pointer value) {
SetNode node = malloc(sizeof(*node));
node->left = NULL;
node->right = NULL;
node->value = value;
node->height = 1; // AVL
return node;
}
// Επιστρέφει τον κόμβο με τιμή ίση με value στο υποδέντρο με ρίζα node, διαφορετικά NULL
static SetNode node_find_equal(SetNode node, CompareFunc compare, Pointer value) {
// κενό υποδέντρο, δεν υπάρχει η τιμή
if (node == NULL)
return NULL;
// Το πού βρίσκεται ο κόμβος που ψάχνουμε εξαρτάται από τη διάταξη της τιμής
// value σε σχέση με την τιμή του τρέχοντος κόμβο (node->value)
//
int compare_res = compare(value, node->value); // αποθήκευση για να μην καλέσουμε την compare 2 φορές
if (compare_res == 0) // value ισοδύναμη της node->value, βρήκαμε τον κόμβο
return node;
else if (compare_res < 0) // value < node->value, ο κόμβος που ψάχνουμε είναι στο αριστερό υποδέντρο
return node_find_equal(node->left, compare, value);
else // value > node->value, ο κόμβος που ψάχνουμε είνια στο δεξιό υποδέντρο
return node_find_equal(node->right, compare, value);
}
// Επιστρέφει τον μικρότερο κόμβο του υποδέντρου με ρίζα node
static SetNode node_find_min(SetNode node) {
return node != NULL && node->left != NULL
? node_find_min(node->left) // Υπάρχει αριστερό υποδέντρο, η μικρότερη τιμή βρίσκεται εκεί
: node; // Αλλιώς η μικρότερη τιμή είναι στο ίδιο το node
}
// Επιστρέφει τον μεγαλύτερο κόμβο του υποδέντρου με ρίζα node
static SetNode node_find_max(SetNode node) {
return node != NULL && node->right != NULL
? node_find_max(node->right) // Υπάρχει δεξί υποδέντρο, η μεγαλύτερη τιμή βρίσκεται εκεί
: node; // Αλλιώς η μεγαλύτερη τιμή είναι στο ίδιο το node
}
// Επιστρέφει τον προηγούμενο (στη σειρά διάταξης) του κόμβου target στο υποδέντρο με ρίζα node,
// ή NULL αν ο target είναι ο μικρότερος του υποδέντρου. Το υποδέντρο πρέπει να περιέχει τον κόμβο
// target, οπότε δεν μπορεί να είναι κενό.
static SetNode node_find_previous(SetNode node, CompareFunc compare, SetNode target) {
if (node == target) {
// Ο target είναι η ρίζα του υποδέντρου, o προηγούμενός του είναι ο μεγαλύτερος του αριστερού υποδέντρου.
// (Aν δεν υπάρχει αριστερό παιδί, τότε ο κόμβος με τιμή value είναι ο μικρότερος του υποδέντρου, οπότε
// η node_find_max θα επιστρέψει NULL όπως θέλουμε.)
return node_find_max(node->left);
} else if (compare(target->value, node->value) < 0) {
// Ο target είναι στο αριστερό υποδέντρο, οπότε και ο προηγούμενός του είναι εκεί.
return node_find_previous(node->left, compare, target);
} else {
// Ο target είναι στο δεξί υποδέντρο, ο προηγούμενός του μπορεί να είναι επίσης εκεί, διαφορετικά
// ο προηγούμενός του είναι ο ίδιος ο node.
SetNode res = node_find_previous(node->right, compare, target);
return res != NULL ? res : node;
}
}
// Επιστρέφει τον επόμενο (στη σειρά διάταξης) του κόμβου target στο υποδέντρο με ρίζα node,
// ή NULL αν ο target είναι ο μεγαλύτερος του υποδέντρου. Το υποδέντρο πρέπει να περιέχει τον κόμβο
// target, οπότε δεν μπορεί να είναι κενό.
static SetNode node_find_next(SetNode node, CompareFunc compare, SetNode target) {
if (node == target) {
// Ο target είναι η ρίζα του υποδέντρου, o προηγούμενός του είναι ο μεγαλύτερος του αριστερού υποδέντρου.
// (Aν δεν υπάρχει αριστερό παιδί, τότε ο κόμβος με τιμή value είναι ο μικρότερος του υποδέντρου, οπότε
// η node_find_max θα επιστρέψει NULL όπως θέλουμε.)
return node_find_min(node->right);
} else if (compare(target->value, node->value) > 0) {
// Ο target είναι στο αριστερό υποδέντρο, οπότε και ο προηγούμενός του είναι εκεί.
return node_find_next(node->right, compare, target);
} else {
// Ο target είναι στο δεξί υποδέντρο, ο προηγούμενός του μπορεί να είναι επίσης εκεί, διαφορετικά
// ο προηγούμενός του είναι ο ίδιος ο node.
SetNode res = node_find_next(node->left, compare, target);
return res != NULL ? res : node;
}
}
// Αν υπάρχει κόμβος με τιμή ισοδύναμη της value, αλλάζει την τιμή του σε value, διαφορετικά προσθέτει
// νέο κόμβο με τιμή value. Επιστρέφει τη νέα ρίζα του υποδέντρου, και θέτει το *inserted σε true
// αν έγινε προσθήκη, ή false αν έγινε ενημέρωση.
static SetNode node_insert(SetNode node, CompareFunc compare, Pointer value, bool* inserted, Pointer* old_value) {
// Αν το υποδέντρο είναι κενό, δημιουργούμε νέο κόμβο ο οποίος γίνεται ρίζα του υποδέντρου
if (node == NULL) {
*inserted = true; // κάναμε προσθήκη
return node_create(value);
}
// Το πού θα γίνει η προσθήκη εξαρτάται από τη διάταξη της τιμής
// value σε σχέση με την τιμή του τρέχοντος κόμβου (node->value)
//
int compare_res = compare(value, node->value);
if (compare_res == 0) {
// βρήκαμε ισοδύναμη τιμή, κάνουμε update
*inserted = false;
*old_value = node->value;
node->value = value;
} else if (compare_res < 0) {
// value < node->value, συνεχίζουμε αριστερά.
node->left = node_insert(node->left, compare, value, inserted, old_value);
} else {
// value > node->value, συνεχίζουμε δεξιά
node->right = node_insert(node->right, compare, value, inserted, old_value);
}
return node_repair_balance(node); // AVL
}
// Αφαιρεί και αποθηκεύει στο min_node τον μικρότερο κόμβο του υποδέντρου με ρίζα node.
// Επιστρέφει τη νέα ρίζα του υποδέντρου.
static SetNode node_remove_min(SetNode node, SetNode* min_node) {
if (node->left == NULL) {
// Δεν έχουμε αριστερό υποδέντρο, οπότε ο μικρότερος είναι ο ίδιος ο node
*min_node = node;
return node->right; // νέα ρίζα είναι το δεξιό παιδί
} else {
// Εχουμε αριστερό υποδέντρο, οπότε η μικρότερη τιμή είναι εκεί. Συνεχίζουμε αναδρομικά
// και ενημερώνουμε το node->left με τη νέα ρίζα του υποδέντρου.
node->left = node_remove_min(node->left, min_node);
return node_repair_balance(node); // AVL
}
}
// Διαγράφει το κόμβο με τιμή ισοδύναμη της value, αν υπάρχει. Επιστρέφει τη νέα ρίζα του
// υποδέντρου, και θέτει το *removed σε true αν έγινε πραγματικά διαγραφή.
static SetNode node_remove(SetNode node, CompareFunc compare, Pointer value, bool* removed, Pointer* old_value) {
if (node == NULL) {
*removed = false; // κενό υποδέντρο, δεν υπάρχει η τιμή
return NULL;
}
int compare_res = compare(value, node->value);
if (compare_res == 0) {
// Βρέθηκε ισοδύναμη τιμή στον node, οπότε τον διαγράφουμε. Το πώς θα γίνει αυτό εξαρτάται από το αν έχει παιδιά.
*removed = true;
*old_value = node->value;
if (node->left == NULL) {
// Δεν υπάρχει αριστερό υποδέντρο, οπότε διαγράφεται απλά ο κόμβος και νέα ρίζα μπαίνει το δεξί παιδί
SetNode right = node->right; // αποθήκευση πριν το free!
free(node);
return right;
} else if (node->right == NULL) {
// Δεν υπάρχει δεξί υποδέντρο, οπότε διαγράφεται απλά ο κόμβος και νέα ρίζα μπαίνει το αριστερό παιδί
SetNode left = node->left; // αποθήκευση πριν το free!
free(node);
return left;
} else {
// Υπάρχουν και τα δύο παιδιά. Αντικαθιστούμε την τιμή του node με την μικρότερη του δεξιού υποδέντρου, η οποία
// αφαιρείται. Η συνάρτηση node_remove_min κάνει ακριβώς αυτή τη δουλειά.
SetNode min_right;
node->right = node_remove_min(node->right, &min_right);
// Σύνδεση του min_right στη θέση του node
min_right->left = node->left;
min_right->right = node->right;
free(node);
return node_repair_balance(min_right); // AVL
}
}
// compare_res != 0, συνεχίζουμε στο αριστερό ή δεξί υποδέντρο, η ρίζα δεν αλλάζει.
if (compare_res < 0)
node->left = node_remove(node->left, compare, value, removed, old_value);
else
node->right = node_remove(node->right, compare, value, removed, old_value);
return node_repair_balance(node); // AVL
}
// Καταστρέφει όλο το υποδέντρο με ρίζα node
static void node_destroy(SetNode node, DestroyFunc destroy_value) {
if (node == NULL)
return;
// πρώτα destroy τα παιδιά, μετά free το node
node_destroy(node->left, destroy_value);
node_destroy(node->right, destroy_value);
if (destroy_value != NULL)
destroy_value(node->value);
free(node);
}
//// Συναρτήσεις του ADT Set. Γενικά πολύ απλές, αφού καλούν τις αντίστοιχες node_* //////////////////////////////////
//
// Επίσης ολόιδιες με αυτές του BST-based Set
Set set_create(CompareFunc compare, DestroyFunc destroy_value) {
assert(compare != NULL); // LCOV_EXCL_LINE
// δημιουργούμε το stuct
Set set = malloc(sizeof(*set));
set->root = NULL; // κενό δέντρο
set->size = 0;
set->compare = compare;
set->destroy_value = destroy_value;
return set;
}
int set_size(Set set) {
return set->size;
}
void set_insert(Set set, Pointer value) {
bool inserted;
Pointer old_value;
set->root = node_insert(set->root, set->compare, value, &inserted, &old_value);
// Το size αλλάζει μόνο αν μπει νέος κόμβος. Στα updates κάνουμε destroy την παλιά τιμή
if (inserted)
set->size++;
else if (set->destroy_value != NULL)
set->destroy_value(old_value);
}
bool set_remove(Set set, Pointer value) {
bool removed;
Pointer old_value = NULL;
set->root = node_remove(set->root, set->compare, value, &removed, &old_value);
// Το size αλλάζει μόνο αν πραγματικά αφαιρεθεί ένας κόμβος
if (removed) {
set->size--;
if (set->destroy_value != NULL)
set->destroy_value(old_value);
}
return removed;
}
Pointer set_find(Set set, Pointer value) {
SetNode node = node_find_equal(set->root, set->compare, value);
return node == NULL ? NULL : node->value;
}
DestroyFunc set_set_destroy_value(Set vec, DestroyFunc destroy_value) {
DestroyFunc old = vec->destroy_value;
vec->destroy_value = destroy_value;
return old;
}
void set_destroy(Set set) {
node_destroy(set->root, set->destroy_value);
free(set);
}
SetNode set_first(Set set) {
return node_find_min(set->root);
}
SetNode set_last(Set set) {
return node_find_max(set->root);
}
SetNode set_previous(Set set, SetNode node) {
return node_find_previous(set->root, set->compare, node);
}
SetNode set_next(Set set, SetNode node) {
return node_find_next(set->root, set->compare, node);
}
Pointer set_node_value(Set set, SetNode node) {
return node->value;
}
SetNode set_find_node(Set set, Pointer value) {
return node_find_equal(set->root, set->compare, value);
}
// Συναρτήσεις που δεν υπάρχουν στο public interface αλλά χρησιμοποιούνται στα tests
// Ελέγχουν ότι το δέντρο είναι ένα σωστό AVL.
// LCOV_EXCL_START (δε μας ενδιαφέρει το coverage των test εντολών, και επιπλέον μόνο τα true branches εξετάζονται σε ένα επιτυχημένο test)
bool node_is_avl(SetNode node, CompareFunc compare) {
if (node == NULL)
return true;
// Ελέγχουμε την ιδιότητα:
// κάθε κόμβος είναι > αριστερό παιδί, > δεξιότερο κόμβο του αριστερού υποδέντρου, < δεξί παιδί, < αριστερότερο κόμβο του δεξιού υποδέντρου.
// Είναι ισοδύναμη με την BST ιδιότητα (κάθε κόμβος είναι > αριστερό υποδέντρο και < δεξί υποδέντρο) αλλά ευκολότερο να ελεγθεί.
bool res = true;
if(node->left != NULL)
res = res && compare(node->left->value, node->value) < 0 && compare(node_find_max(node->left)->value, node->value) < 0;
if(node->right != NULL)
res = res && compare(node->right->value, node->value) > 0 && compare(node_find_min(node->right)->value, node->value) > 0;
// Το ύψος είναι σωστό
res = res && node->height == 1 + int_max(node_height(node->left), node_height(node->right));
// Ο κόμβος έχει την AVL ιδιότητα
int balance = node_balance(node);
res = res && balance >= -1 && balance <= 1;
// Τα υποδέντρα είναι σωστά
res = res &&
node_is_avl(node->left, compare) &&
node_is_avl(node->right, compare);
return res;
}
bool set_is_proper(Set node) {
return node_is_avl(node->root, node->compare);
}
// LCOV_EXCL_STOP
//// Επιπλέον συναρτήσεις προς υλοποίηση στο Εργαστήριο 5
// Απλός τρόπος για Άσκηση 2
void set_visit(Set set, VisitFunc visit) {
// Διατρέχω το set από το πρώτο μέχρι το
// τελευταίο στοιχείο και καλώ την visit
for (SetNode node=set_first(set);
node!=SET_EOF;
node=set_next(set, node)) {
visit(set_node_value(set, node));
}
}
// Αποδοτικός τρόπος για Άσκηση 3
// Βοηθητική (αναδρομική συνάρτηση)
static void rec(SetNode node, VisitFunc visit) {
// Καλώ την rec για το αριστερό παιδί
if (node->left != NULL)
rec(node->left, visit);
// Καλώ την visit για το value
visit(node->value);
// Καλώ την rec για το δεξί παιδί
if (node->right != NULL)
rec(node->right, visit);
return;
}
// Αποδοτική set_visit
void set_visit_efficient(Set set, VisitFunc visit) {
// Απλά καλώ την rec, με όρισμα την ρίζα
rec(set->root, visit);
}
| 2.703125 | 3 |
2024-11-18T20:55:54.176934+00:00 | 2023-07-20T03:24:17 | 6a3ce42a7cea9f6a0004d4d959439b04def1febe | {
"blob_id": "6a3ce42a7cea9f6a0004d4d959439b04def1febe",
"branch_name": "refs/heads/master",
"committer_date": "2023-07-20T03:24:17",
"content_id": "eb3dd4e74e83f16336285f99dec9f658a9167a8e",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "865b94acf7c6314e362a3118b4be6e88673c0540",
"extension": "h",
"filename": "ble_stack_status.h",
"fork_events_count": 13,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 171448465,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2923,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/SampleCode/NuMaker-M03xBT/BLE/Source/Include/ble_stack_status.h",
"provenance": "stackv2-0092.json.gz:53531",
"repo_name": "OpenNuvoton/M031BSP",
"revision_date": "2023-07-20T03:24:17",
"revision_id": "8c2b331fdacd9e65351f8c6ec26c3fcba8a28cda",
"snapshot_id": "b275299c547a7a4bcca1a704cee8789e60d15efd",
"src_encoding": "UTF-8",
"star_events_count": 11,
"url": "https://raw.githubusercontent.com/OpenNuvoton/M031BSP/8c2b331fdacd9e65351f8c6ec26c3fcba8a28cda/SampleCode/NuMaker-M03xBT/BLE/Source/Include/ble_stack_status.h",
"visit_date": "2023-08-15T06:06:58.640419"
} | stackv2 | /**************************************************************************//**
* @file ble_stack_status.h
* @brief This file contains the functions of HOST to HCI interface.
*
*
* @defgroup ble_common BLE Common
* @{
* @details This file shows the common BLE definitions and functions. (ble_cmd.h, ble_event.h)
* @}
*****************************************************************************/
#ifndef _BLE_STACK_STATUS_H_
#define _BLE_STACK_STATUS_H_
#include "mcu_definition.h"
/**
* @ingroup ble_stack_definition
* @defgroup ble_Stack_Status BLE Stack Error Code Definition
* @{
* @details BLE Stack error code definition.
* @name BleStackStatus
* @brief Define different BleStackStatus type.
* @{
*/
typedef uint8_t BleStackStatus;
/** Successful command */
#define BLESTACK_STATUS_SUCCESS 0x00
/** Stack state is free indicates that LL and Host task is NOT running. */
#define BLESTACK_STATUS_FREE 0x01
/** Stack state busy. */
#define BLESTACK_STATUS_ERR_BUSY 0x02
/** Invalid parameter. */
#define BLESTACK_STATUS_ERR_INVALID_PARAM 0x03
/** Invalid state. */
#define BLESTACK_STATUS_ERR_INVALID_STATE 0x04
/** Invalid Host ID */
#define BLESTACK_STATUS_ERR_INVALID_HOSTID 0x05
/** Invalid count of Host Links. (MAX_NUM_CONN_HOST shall be less than or equal to BLE_SUPPORT_NUM_CONN_MAX) */
#define BLESTACK_STATUS_ERR_INVALID_HOSTCOUNT 0x06
/** Invalid command. */
#define BLESTACK_STATUS_ERR_INVALID_CMD 0x07
/** Invalid BLE handle. */
#define BLESTACK_STATUS_ERR_INVALID_HANDLE 0x08
/** Command timer busy */
#define BLESTACK_STATUS_ERR_TIMER_BUSY 0x09
/** Command feature not supported */
#define BLESTACK_STATUS_ERR_NOT_SUPPORTED 0x0A
/** Host peripheral database parsing is still in progress. */
#define BLESTACK_STATUS_ERR_DB_PARSING_IN_PROGRESS 0x0B
/** The other mandatory procedure is still in progress. */
#define BLESTACK_STATUS_ERR_OTHER_PROCEDURE_IN_PROGRESS 0x0C
/** Detecting a sequential protocol violation. Usually happens in there is an another GATT request already in progress please wait and retry.*/
#define BLESTACK_STATUS_ERR_SEQUENTIAL_PROTOCOL_VIOLATION 0x0D
/** Profile client configuration disable */
#define BLESTACK_STATUS_ERR_CLIENT_CONFIGURATION_DISABLE 0x0E
/** @} */
/** @} */
/** Marcro return BLE stack status if input status is not equal to BLESTACK_STATUS_SUCCESS.
*
* @param[in] status BLE stack status.
*/
#define BLESTACK_STATUS_CHECK(status) \
if (status != BLESTACK_STATUS_SUCCESS) \
{ \
return status; \
} \
#endif // _BLE_STACK_STATUS_H_
| 2.015625 | 2 |
2024-11-18T20:55:54.346022+00:00 | 2014-09-23T02:50:15 | da1953b9165d943419a7627e07942a33a469ee05 | {
"blob_id": "da1953b9165d943419a7627e07942a33a469ee05",
"branch_name": "refs/heads/master",
"committer_date": "2014-09-23T02:50:15",
"content_id": "b2cc8c787ce46756c30895f4ba58dd7f2e03c235",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "d21d86376212b74ed66102914ea11ba504c15b78",
"extension": "c",
"filename": "tracker_http_response_reader.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 24354466,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4980,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/deps/tracker-client/tracker_http_response_reader.c",
"provenance": "stackv2-0092.json.gz:53789",
"repo_name": "willemt/yabtorrent-cli",
"revision_date": "2014-09-23T02:50:15",
"revision_id": "39c0d5e8348d568ecf514335929140c3390545d6",
"snapshot_id": "061403ce985380e883cfd9d3e48d844656183931",
"src_encoding": "UTF-8",
"star_events_count": 4,
"url": "https://raw.githubusercontent.com/willemt/yabtorrent-cli/39c0d5e8348d568ecf514335929140c3390545d6/deps/tracker-client/tracker_http_response_reader.c",
"visit_date": "2021-01-19T16:52:00.135936"
} | stackv2 |
/**
* Copyright (c) 2011, Willem-Hendrik Thiart
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
* @file
* @brief Manage connection with tracker
* @author Willem Thiart himself@willemthiart.com
* @version 0.1
*/
#include <stdio.h>
#include <stdbool.h>
#include <assert.h>
#include <setjmp.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include "bencode.h"
#include "tracker_client.h"
#include "tracker_client_private.h"
static void __do_peer_list(
trackerclient_t* me,
bencode_t * list
)
{
const char *peerid, *ip;
long int port;
int peerid_len, ip_len;
port = 0;
while (bencode_list_has_next(list))
{
bencode_t dict;
bencode_list_get_next(list, &dict);
while (bencode_dict_has_next(&dict))
{
const char *key;
int klen;
bencode_t benk;
bencode_dict_get_next(&dict, &benk, &key, &klen);
if (!strncmp(key, "peer id", klen))
{
bencode_string_value(&benk, &peerid, &peerid_len);
}
else if (!strncmp(key, "ip", klen))
{
bencode_string_value(&benk, &ip, &ip_len);
}
else if (!strncmp(key, "port", klen))
{
bencode_int_value(&benk, &port);
}
}
if (peerid && ip && port != 0)
{
assert(peerid_len == 20);
// me->funcs.add_peer(me->caller, peerid, peerid_len, ip, ip_len, port);
}
else
{
assert(0);
}
}
}
int trackerclient_read_tracker_response(
trackerclient_t* me,
const char *buf,
int len
)
{
bencode_t ben;
bencode_init(&ben, buf, len);
if (!bencode_is_dict(&ben))
{
return 0;
}
while (bencode_dict_has_next(&ben))
{
int klen;
const char *key;
bencode_t benk;
if (0 == bencode_dict_get_next(&ben, &benk, &key, &klen))
{
// ERROR dict is invalid
return 0;
}
/* This key is OPTIONAL. If present, the dictionary MUST NOT contain
* any other keys. The peer should interpret this as if the attempt to
* join the torrent failed. The value is a human readable string
* containing an error message with the failure reason. */
if (!strncmp(key, "failure reason", klen))
{
int len;
const char *val;
bencode_string_value(&benk, &val, &len);
return 1;
}
/* A peer must send regular HTTP GET requests to the tracker to obtain
* an updated list of peers and update the tracker of its status. The
* value of this key indicated the amount of time that a peer should
* wait between to consecutive regular requests. This key is REQUIRED*/
else if (!strncmp(key, "interval", klen))
{
long int interval;
bencode_int_value(&benk, &interval);
}
/* This is an integer that indicates the number of seeders. This key is
* OPTIONAL. */
else if (!strncmp(key, "complete", klen))
{
long int ncomplete_peers;
bencode_int_value(&benk, &ncomplete_peers);
}
/* This is an integer that indicates the number of peers downloading
* the torrent. This key is OPTIONAL. */
else if (!strncmp(key, "incomplete", klen))
{
long int nincomplete_peers;
bencode_int_value(&benk, &nincomplete_peers);
}
/*
* This is a bencoded list of dictionaries containing a list of peers
* that must be contacted in order to download a file. This key is
* REQUIRED. It has the following structure: */
else if (!strncmp(key, "peers", klen))
{
/* compact=0 */
if (bencode_is_list(&benk))
{
__do_peer_list(me, &benk);
}
/* compact=1 */
/* use the bittorrent compact peer format listing */
else if (bencode_is_string(&benk))
{
int len, ii;
const unsigned char *val;
if (0 == bencode_string_value(&benk, (const char **) &val, &len))
{
// ERROR: string is invalid
return 0;
}
for (ii = 0; ii < len; ii += 6, val += 6)
{
char ip[32];
sprintf(ip, "%d.%d.%d.%d", val[0], val[1], val[2], val[3]);
if (!strcmp(ip,"0.0.0.0")) continue;
me->on_add_peer(me->callee, NULL, 0, ip, strlen(ip),
((int) val[4] << 8) | (int) val[5]);
}
}
}
}
return 1;
}
| 2.1875 | 2 |
2024-11-18T20:55:54.425260+00:00 | 2018-12-14T06:21:36 | 1caa5082d568b3b05b1f91821c6a9dc866e94b5e | {
"blob_id": "1caa5082d568b3b05b1f91821c6a9dc866e94b5e",
"branch_name": "refs/heads/master",
"committer_date": "2018-12-14T06:21:36",
"content_id": "6079efc8c12362d46f7d391f76699c11107f4a3b",
"detected_licenses": [
"MIT"
],
"directory_id": "7b9778cf6df54db8e16ed4f66bb696185928ee1a",
"extension": "h",
"filename": "elf_graph.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 86965779,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 8027,
"license": "MIT",
"license_type": "permissive",
"path": "/graph/graph_list/include/elf_graph.h",
"provenance": "stackv2-0092.json.gz:53918",
"repo_name": "matheushjs/ElfLibC",
"revision_date": "2018-12-14T06:21:36",
"revision_id": "a2ac085d9546319aab07c09dda3063cf441f7761",
"snapshot_id": "386a558630de7257226d8245e65f3ba306e266b2",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/matheushjs/ElfLibC/a2ac085d9546319aab07c09dda3063cf441f7761/graph/graph_list/include/elf_graph.h",
"visit_date": "2021-10-08T15:35:45.735042"
} | stackv2 | /*
* MIT License
*
* Copyright (c) 2018 Matheus H. J. Saldanha <mhjsaldanha@gmail.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#ifndef _ELF_GRAPH_LIST_H_
#define _ELF_GRAPH_LIST_H_
typedef struct _ElfGraph ElfGraph;
#include <stdio.h>
#include <stdbool.h>
#include <elf_list.h>
ElfGraph *elfGraph_new(int N, bool oriented);
void elfGraph_destroy(ElfGraph **graph_p);
int elfGraph_size(const ElfGraph *graph);
void elfGraph_addEdge(ElfGraph *graph, int src, int dest, int weight);
void elfGraph_removeEdge(ElfGraph *graph, int src, int dest);
void elfGraph_print(const ElfGraph *graph);
void elfGraph_printAdjacent(const ElfGraph *graph, int subjectVertex);
ElfGraph *elfGraph_transpose(const ElfGraph *graph);
void elfGraph_readFromFileVE(ElfGraph *graph, FILE *fp, int lim);
void elfGraph_readFromFileVEW(ElfGraph *graph, FILE *fp, int lim);
void elfGraph_DFS_src(const ElfGraph *graph, int src, int **pred_p, int **time_p, int **finish_p);
void elfGraph_DFS_all(const ElfGraph *graph, int **pred_p, int **time_p, int **finish_p);
void elfGraph_DFS_registerAfterFunc(const ElfGraph *graph, void (*func)(int vert, void *data), void *data);
ElfList **elfGraph_SCC(const ElfGraph *graph);
ElfGraph *elfGraph_MST_prim(const ElfGraph *graph);
ElfGraph *elfGraph_MST_kruskal(const ElfGraph *graph);
int elfGraph_dijkstra_withTarget(const ElfGraph *graph, int src, int tgt, int **pred_p);
int *elfGraph_BFS(const ElfGraph *graph, int src, int **dist_p);
/* DOCUMENTATION
ElfGraph
- Graph implemented with an adjacency list.
- Can be oriented or not.
- Size must be specified on instantiation.
- Double edges are not allowed (cannot be MULTIGRAPH).
ElfGraph *elfGraph_new(int N, bool oriented);
- Returns a graph with N vertixes, indexed from 0 to N-1.
- Graph is oriented if 'oriented' is true.
void elfGraph_destroy(ElfGraph **graph_p);
- Deallocates all the memory used by 'graph', and sets its pointer to NULL.
- 'graph' should be an ElfGraph* passed by reference (hence a double pointer).
int elfGraph_size(const ElfGraph *graph);
- Returns the amount of vertixes in the graph.
void elfGraph_addEdge(ElfGraph *graph, int src, int dest, int weight);
- Adds to the graph an edge from 'src' to 'dest'.
- If the graph is not oriented, the inverse direction is also added.
void elfGraph_removeEdge(ElfGraph *graph, int src, int dest);
- Removes, if exists, the edge going from 'src' to 'dest'.
- If the graph is not oriented, the inverse is also removed.
void elfGraph_print(const ElfGraph *graph);
- Prints the adjacency list of a graph
void elfGraph_printAdjacent(const ElfGraph *graph, int subjectVertex);
- Prints indexes of vertices that are adjacent to 'subjectVertex'.
ElfGraph *elfGraph_transpose(const ElfGraph *graph);
- Returns the transposed graph of 'graph.
- If 'graph' is not oriented, returns NULL.
void elfGraph_readFromFileVE(ElfGraph *graph, FILE *fp, int lim);
- Reads a sequence of 'lim' non-weighted edges from a file.
- Reads until EOF if 'lim' is -1.
- Will read any blank-character-separated sequence of integers,
following the order: source vertix - destiny vertix
- VE stands for vertix and edge
void elfGraph_readFromFileVEW(ElfGraph *graph, FILE *fp, int lim);
- Same as above, but also reads weights.
- VEW stands for vertix, edge and weight
void elfGraph_DFS_src(const ElfGraph *graph, int src, int **pred_p, int **time_p, int **finish_p);
- Performs a DFS in the graph, finding the time/path from all vertexes to 'src'.
- Args:
- graph: pointer to the graph in which to execute the DFS.
- src: number of vertex to start the DFS from.
- pred_p: if not NULL, receives the vector of predecessors.
- time_p: if not NULL, receives the vector of time visited.
- finish_p: if not NULL, receives the vector of time finished.
void elfGraph_DFS_all(const ElfGraph *graph, int **pred_p, int **time_p, int **finish_p);
- Performs a DFS in the graph, until all vertixes are visited once.
- Args:
graph: graph in which to execute the DFS.
pred_p: if not NULL, receives the vector of predecessors.
time_p: if not NULL, receives the vector of time visited.
finish_p: if not NULL, receives the vector of time finished.
void elfGraph_DFS_registerAfterFunc(const ElfGraph *graph, void (*func)(int vert, void *data), void *data);
- Registers a function to be executed in each vertix after all adjacent vertexes have
been visited.
- Once registered, the function is executed only for ONE DFS, meaning multiple DFS requires
multiple function registries.
- For each vertex N, func will be called as func(N, data);
- Args:
func: function to register.
data: data to be passed to 'func' when it's called.
ElfList **elfGraph_SCC(const ElfGraph *graph);
- SCC standing for Strongly Connected Components
- Finds all the strongly connected components of a graph.
Return:
A NULL-terminated array of lists, each of which contains a component.
If graph is undirected, return NULL.
ElfGraph *elfGraph_MST_prim(const ElfGraph *graph);
- Returns a Minimum Spanning Tree for the given graph.
- The graph is supposed to be connected. This function does not check whether the graph is
connected or not. If it isn't, the behavior is undefined.
- Given graph cannot be oriented.
- Given graph can be weighted or not.
- The Prim algorithm for finding MST is applied.
ElfGraph *elfGraph_MST_kruskal(const ElfGraph *graph);
- Returns a Minimum Spanning Tree for the given graph.
- The graph is supposed to be connected. This function does not check whether the graph is
connected or not. If it isn't, the behavior is undefined.
- Given graph cannot be oriented.
- Given graph can be weighted or not.
- The Kruskal algorithm for finding MST is applied.
- O(V*E), always worse than PRIM algorithm.
int elfGraph_dijkstra_withTarget(const ElfGraph *graph, int src, int tgt, int **predecessors);
- Performs the dijkstra algorithm in the graph, in order to find the shortest path from
vertex 'src' to vertex 'tgt'.
- Return:
- The distance between these vertexes. Will be INT_MAX if 'tgt' could not be reached
from 'src.
- pred_p: if this argument is not NULL, it receives the vector of predecessors
obtained during the algorithm.
int *elfGraph_BFS(const ElfGraph *graph, int src, int **dist_p);
- Performs a BFS in the graph, finding the distance/path from all vertexes to 'src'.
- Args:
- dist_p: If 'dist_p' is not NULL, store in it
- the vector of shortest distances to each vertex.
- - dist[i] == -1, vertex could not be reached from 'src'.
- - dist[i] != -1, shortest distance from 'src' to vertex i.
- Returns:
- Vector of predecessors generated by the BFS.
- pred[i] == i means the vertix could not be reached,
- with the exception of the source vertix, obviously
- pred[i] != i means vertix i could be visited and it's predecessor is pred[i]
- The predecessor vector must be freed by the client of the function.
*/
#endif
| 2.46875 | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.