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:21:46.224403+00:00 | 2015-12-11T11:51:11 | fb65d7fdfa866d5d8606ff798a621bb1b775d7a6 | {
"blob_id": "fb65d7fdfa866d5d8606ff798a621bb1b775d7a6",
"branch_name": "refs/heads/master",
"committer_date": "2015-12-11T11:51:11",
"content_id": "53576686b1210c4b51fe980b43cfd0841f9b91dc",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "edbd4f8f29417765cb472601a6274e393814d21f",
"extension": "c",
"filename": "database.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 21015262,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5173,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/database/database.c",
"provenance": "stackv2-0123.json.gz:3748",
"repo_name": "dptechnics/DPT-Board-SERV",
"revision_date": "2015-12-11T11:51:11",
"revision_id": "3323ab8418bf3977efd54516578d49955d5ed271",
"snapshot_id": "1b1163d1eeb738761d6f25e9e2977c3b7e5c95f4",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/dptechnics/DPT-Board-SERV/3323ab8418bf3977efd54516578d49955d5ed271/database/database.c",
"visit_date": "2021-01-02T08:19:35.508252"
} | stackv2 | /*
* Copyright (c) 2014, Daan Pape
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* File: database.c
* Created on September 11, 2014, 11:00 AM
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sqlite3.h>
#include <stdbool.h>
#include <stdint.h>
#include "database.h"
#include "../config.h"
#include "../logger.h"
/* References to installed DAO modules for initializing*/
#include "../firmware/firmware_dao.h"
#include "../gpio/gpio_dao.h"
#include "db_keyvalue.h"
/*
* Create the database if it doesn't exist and migrate otherways.
*/
int dao_create_db(void) {
sqlite3 *db;
/* Check if the file exists */
if (access(conf->database, F_OK) != -1) {
/* The database file exists, check if it can be opened */
if (sqlite3_open(conf->database, &db) != SQLITE_OK) {
/* Remove the current file because it is corrupted */
log_message(LOG_INFO, "Removing corrupt database file\r\n");
remove(conf->database);
}
}
/* Open the existing database or create a new one */
if (sqlite3_open(conf->database, &db) != SQLITE_OK) {
return DB_ERR;
}
/* Initialize DAO modules */
if(dao_keyvalue_init(db) == DB_ERR) {
log_message(LOG_ERROR, "Could not successfully initialize keyvalue module database\r\n");
}
if(gpio_dao_init(db) == DB_ERR) {
log_message(LOG_ERROR, "Could not successfully initialize GPIO module database\r\n");
}
if(!firmware_dao_init()) {
log_message(LOG_ERROR, "Could not successfully initialize firmware module database\r\n");
}
/* Close the database */
sqlite3_close(db);
/* The database is successfully created */
return DB_OK;
}
/*
* Database closing helper
*/
inline void dao_finalize(sqlite3 *db, sqlite3_stmt* stmt) {
sqlite3_finalize(stmt);
sqlite3_close(db);
}
/*
* Create a database integer result
*/
db_int* dao_create_db_int(void) {
db_int* value = (db_int*) malloc(sizeof (db_int));
return value;
}
/*
* Destroy a database integer result
*/
void dao_destroy_db_int(db_int *value) {
free(value);
}
/*
* Create a database text result
*/
db_text* dao_create_db_text(void) {
db_text *value = (db_text*) malloc(sizeof (db_text));
value->value = NULL;
return value;
}
/*
* Destroy a database text result
*/
void dao_destroy_db_text(db_text *value) {
/* Free the string memory if any was reserved */
if (value->value != NULL) {
free(value->value);
}
free(value);
}
/**
* Easy SQL executer for one-line statements without external variables. The database
* must be open and it will not be closed by this function.
* @param db the database to use, the database must be open already.
* @param sql the sql statement to execute.
* @return DB_OK on success en DB_ERR on error.
*/
int dao_easy_exec(sqlite3 *db, const char* sql)
{
sqlite3_stmt *stmt;
int rc = DB_OK;
/* Try to prepare statement */
if (sqlite3_prepare_v2(db, sql, -1, &stmt, 0) != SQLITE_OK) {
/* Return with error */
log_message(LOG_ERROR, "Could not prepare SQL statement: %s\r\n", sqlite3_errmsg(db));
rc = DB_ERR;
goto finalize;
}
/* Try to execute the statement without callback */
while ((rc = sqlite3_step(stmt)) != SQLITE_DONE) {
switch (rc) {
case SQLITE_DONE:
break;
default:
log_message(LOG_ERROR, "Error while executing SQL statement: %s\r\n", sqlite3_errmsg(db));
rc = DB_ERR;
goto finalize;
break;
}
}
/* Success when we reach here */
rc = DB_OK;
finalize:
/* Finalize the statement */
sqlite3_finalize(stmt);
/* Return the value */
return rc;
}
| 2.203125 | 2 |
2024-11-18T22:21:46.363387+00:00 | 2017-11-04T18:28:41 | cdb8c877fb728664346698990a32ab06e6f0935c | {
"blob_id": "cdb8c877fb728664346698990a32ab06e6f0935c",
"branch_name": "refs/heads/master",
"committer_date": "2017-11-04T18:28:41",
"content_id": "bd6f1ce9ad5476b381c38c8024c0f2c930ff19a3",
"detected_licenses": [
"MIT"
],
"directory_id": "1b0c72b4bef14c8c561e25d3a0a959352765bebb",
"extension": "h",
"filename": "dict.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": 2887,
"license": "MIT",
"license_type": "permissive",
"path": "/src/dict.h",
"provenance": "stackv2-0123.json.gz:3877",
"repo_name": "styczynski/jnp1-task-2",
"revision_date": "2017-11-04T18:28:41",
"revision_id": "a88d0de09222839811f5fc4a3ca18db384523e23",
"snapshot_id": "00e5ed2b9a2cd75fd7838b3a775d9dcaeef8f536",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/styczynski/jnp1-task-2/a88d0de09222839811f5fc4a3ca18db384523e23/src/dict.h",
"visit_date": "2021-07-25T03:25:13.618867"
} | stackv2 | /*
* JNP-ZAD-2
*
* University of Warsaw 2017
*
* Contributors:
* @wikzan
* @styczynski
*/
#ifndef __DICT__
#define __DICT__
/*
* Creates new empty dictionary and returns its id.
*
* @returns id of newly created dictionary
*/
unsigned long dict_new();
/*
* Removes dictionary with given id.
* If no dictionary with such id exists then
* the function call has no effects.
*
* You cannot remove the global dictonary.
* This function called on its id has no effects.
*
* @param[in] id: id of dictionary
*/
void dict_delete(unsigned long id);
/*
* Returns count of elements contained in
* the dictionary with specified id.
* If no dictionary with such id exists then
* the function returns zero.
*
* @param[in] id : id of dictionary
* @returns size_t size of dictionary
*/
size_t dict_size(unsigned long id);
/*
* Puts a new record in the dictionary
* with a given id.
*
* If the given key or value is NULL then
* the function call has no effects.
*
* If no dictionary with such id exists then
* the function call has no effects.
*
* @param[in] id : id of dictionary
* @param[in] key : key of new entry
* @param[in] value : value of new entry
*/
void dict_insert(unsigned long id, const char* key, const char* value);
/*
* Removes record from the dictionary
* specified by id.
*
* If the given key does not exist in the dictionary
* the function call has no effects.
*
* If no dictionary with such id exists then
* the function call has no effects.
*
* @param[in] id : id of dictionary
* @param[in] key : key of entry that will be removed
*/
void dict_remove(unsigned long id, const char* key);
/*
* Returns the value saved under the specified key
* in the dictionary specified by id.
*
* If the given key does not exist in the dictionary
* the function searches the global dictionary.
*
* If no dictionary with such id exists then
* the function searches the global dictionary.
*
* If there's no such key in global dictionary
* then NULL is returned.
*
* @param[in] id : id of dictionary
* @param[in] key : key of entry that will be removed
* @returns pointer to the value saved under the given key
*/
const char* dict_find(unsigned long id, const char* key);
/*
* Clears the dictionary
* with a given id.
*
* All of its records will be removed.
*
* If no dictionary with such id exists then
* the function call has no effects.
*
* @param[in] id : id of dictionary to be removed
*/
void dict_clear(unsigned long id);
/*
* Copies records among two dictionaries.
*
* If one of the two dictionaries identified by
* given ids does not exist then the function call
* has no effects.
*
* @param[in] src_id : id of the source dictionary
* @param[in] dst_id : id of the destination dictionary
*/
void dict_copy(unsigned long src_id, unsigned long dst_id);
#endif // __DICT__ | 2.59375 | 3 |
2024-11-18T22:21:46.435987+00:00 | 2023-07-19T09:38:43 | 8c9439a1a1580925a400827ac218a6e9915bebbf | {
"blob_id": "8c9439a1a1580925a400827ac218a6e9915bebbf",
"branch_name": "refs/heads/master",
"committer_date": "2023-07-19T09:38:43",
"content_id": "42184765a1014254a4dbfa599563071cb765edb5",
"detected_licenses": [
"MIT"
],
"directory_id": "b2fdb318dfc757e54f90220eca79ac2e02dbf0d3",
"extension": "h",
"filename": "ptr.h",
"fork_events_count": 22,
"gha_created_at": "2016-10-26T15:11:32",
"gha_event_created_at": "2023-07-17T19:10:39",
"gha_language": "Python",
"gha_license_id": "NOASSERTION",
"github_id": 72015621,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2339,
"license": "MIT",
"license_type": "permissive",
"path": "/capnpy/ptr.h",
"provenance": "stackv2-0123.json.gz:4006",
"repo_name": "antocuni/capnpy",
"revision_date": "2023-07-19T09:38:43",
"revision_id": "618af51656836d6a183e6e8e7b5781074c5fbe85",
"snapshot_id": "bcb05768720855650045db54335600f9b7664070",
"src_encoding": "UTF-8",
"star_events_count": 46,
"url": "https://raw.githubusercontent.com/antocuni/capnpy/618af51656836d6a183e6e8e7b5781074c5fbe85/capnpy/ptr.h",
"visit_date": "2023-07-26T02:16:30.572447"
} | stackv2 | /* This is the implementation of the ptr.py logic in C. It is wrapped by
ptr.pxd and in turn by ptr.pyx. If you modify anything, make sure"
1. to update ptr.pxd and ptr.pyx accordingly
2. to keep ptr.py (the pure-python version) in sync
3. to add a test to test_ptr.py, so that we test the behavior in both versions
*/
enum _PTR_KIND {
PTR_STRUCT = 0,
PTR_LIST = 1,
PTR_FAR = 2
};
enum _PTR_LIST_SIZE {
PTR_LIST_SIZE_VOID = 0,
PTR_LIST_SIZE_BIT = 1,
PTR_LIST_SIZE_8 = 2,
PTR_LIST_SIZE_16 = 3,
PTR_LIST_SIZE_32 = 4,
PTR_LIST_SIZE_64 = 5,
PTR_LIST_SIZE_PTR = 6,
PTR_LIST_SIZE_COMPOSITE = 7
};
#define LONGBITS (sizeof(long)*8)
#define CAST_AS_SIGNED(x, bits) (((long)x) << (LONGBITS-bits) >> (LONGBITS-bits))
// generic pointer
#define PTR_NEW_GENERIC(kind, offset, extra) ((extra)<<32 | (offset)<<2 | (kind))
#define PTR_KIND(ptr) ((ptr) & 0x3)
#define PTR_OFFSET(ptr) (CAST_AS_SIGNED((ptr)>>2 & 0x3fffffff, 30))
#define PTR_EXTRA(ptr) ((ptr)>>32)
#define PTR_DEREF(ptr, ofs) ((ofs) + (PTR_OFFSET(ptr)+1)*8)
// struct pointer
#define PTR_NEW_STRUCT(offset, data_size, ptrs_size) \
((((long)ptrs_size) << 48) | \
(((long)data_size) << 32 & 0xffff00000000) | \
(((long)offset) << 2 & 0xfffffffc) | \
PTR_STRUCT)
#define PTR_STRUCT_DATA_SIZE(ptr) ((ptr)>>32 & 0xffff)
#define PTR_STRUCT_PTRS_SIZE(ptr) ((ptr)>>48 & 0xffff)
// list pointer
#define PTR_NEW_LIST(ptr_offset, size_tag, item_count) \
((((long)item_count) << 35) | \
(((long)size_tag) << 32 & 0x700000000) | \
(((long)ptr_offset) << 2 & 0xfffffffc) | \
PTR_LIST)
#define PTR_LIST_SIZE_TAG(ptr) ((ptr)>>32 & 0x7)
#define PTR_LIST_ITEM_COUNT(ptr) ((ptr)>>35 & 0x1fffffff)
// far pointer
#define PTR_NEW_FAR(landing_pad, offset, target) \
((((long)target) << 32) | \
(((long)offset) << 3 & 0xfffffff8) | \
(((long)landing_pad) << 2 & 0x4) | \
PTR_FAR)
#define PTR_FAR_LANDING_PAD(ptr) ((ptr)>>2 & 1)
#define PTR_FAR_OFFSET(ptr) ((ptr)>>3 & 0x1fffffff)
#define PTR_FAR_TARGET(ptr) ((ptr)>>32 & 0xffffffff)
#define ROUND_UP_TO_WORD(i) (((i) + (8 - 1)) & -8)
| 2.671875 | 3 |
2024-11-18T22:21:46.791457+00:00 | 2019-06-15T05:09:09 | 4def90bbbb661435511ab38ac3a5ab0ab717d328 | {
"blob_id": "4def90bbbb661435511ab38ac3a5ab0ab717d328",
"branch_name": "refs/heads/master",
"committer_date": "2019-06-15T05:09:09",
"content_id": "2ab6e2bd151f6e483606796e2bfe44e5346b17ab",
"detected_licenses": [
"MIT"
],
"directory_id": "4d27e0a338740f3f7992356cfcac243adbb443e8",
"extension": "c",
"filename": "partition.c",
"fork_events_count": 0,
"gha_created_at": "2017-05-16T22:38:51",
"gha_event_created_at": "2018-08-13T02:45:01",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 91510613,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4566,
"license": "MIT",
"license_type": "permissive",
"path": "/src/partition.c",
"provenance": "stackv2-0123.json.gz:4140",
"repo_name": "henry-malinowski/libsort",
"revision_date": "2019-06-15T05:09:09",
"revision_id": "1968fffb238a058ffc62e23b85485d62c1badb8e",
"snapshot_id": "03cf756fad6c2b95f9a01e036b6c571a0cf413d6",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/henry-malinowski/libsort/1968fffb238a058ffc62e23b85485d62c1badb8e/src/partition.c",
"visit_date": "2021-03-13T04:18:10.031501"
} | stackv2 | /**
* A C source file that includes several type agnostic array
* partitioning schemas.
*
* @copyright (C) 2017 Henry Malinowski <malinowski.henry@gmail.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include <malloc.h>
#include "../include/partition.h"
/**
* @brief Byte-wise swap two items of size \p size.
* This code is borrowed straight from the GCC qsort implementation of SWAP.
*/
#define SWAP(a, b, size) \
do \
{ \
size_t __size = (size); \
char *__a = (a), *__b = (b); \
do \
{ \
char __tmp = *__a; \
*__a++ = *__b; \
*__b++ = __tmp; \
} while (--__size > 0); \
} while (0)
/**
*
* @brief Copies (size) bytes from pointer b to pointer a.
*/
#define COPY(a, b, size) \
do \
{ \
size_t __size = (size); \
char *__a = (a), *__b = (b); \
do \
{ \
*__a++ = *__b++; \
} while (--__size > 0); \
} while (0)
int
partition_verify(const void* base, size_t nmbers, size_t size,
int (*cmp)(const void *, const void *), void* pivot)
{
const char* i = (char*) base;
const char* upper_limit = (char*) base + (nmbers * size);
/* check value less than the pivot */
while (i < (char*) pivot && i < upper_limit)
{
if (cmp(i, pivot) > 0)/* if true, a swap that needs to occur did not*/
return 0;
else
i += size;
}
/* skip of the pivot */
i += size;
while (i < upper_limit) {
if (cmp(i, pivot) <= 0)/* if true, a swap that needs to ocurr did not*/
return 0;
else
i += size;
}
return 1;
}
void*
partition_lomuto(void *base, size_t nmbers, size_t size,
int (*cmp)(const void *, const void *))
{
/*
* i: track where the pivot will end up (a.k.a. index)
* j: main iterator
* pivot: set as the right most element
*/
char* i = (char*) base;
char* j = (char*) base;
char* pivot = (char*)base + ((nmbers-1)*size);
/* perform Lomuto's partition up to the element right be fore the pivot */
while (j < pivot)
{
if (cmp(j, pivot) <= 0)
{
SWAP(i, j, size);
i += size;
}
j += size; /* increment j */
}
/* move the pivot to it's final location */
SWAP(pivot, i, size);
return i;
}
void*
partition_hoare(void *base, size_t nmbers, size_t size,
int (*cmp)(const void *, const void *))
{
char* i = (char*) base;
char* j = (char*) base + ((nmbers-1)*size);
char* pivot = malloc(size);
COPY(pivot, base, size);
//memcpy(pivot, base, size);
/* Perform Hoare's partitioning until pointers i and j meet. */
while (1) {
/* Find the leftmost element "greater than" or equal to the pivot */
while (cmp(i, pivot) < 0)
i += size;
/* Find the rightmost element "less than" or equal to the pivot */
while (cmp(j, pivot) > 0)
j -= size;
if (i < j) SWAP(i, j, size);
else break;
}
free(pivot);
return j;
}
| 2.84375 | 3 |
2024-11-18T22:21:46.870797+00:00 | 2021-04-30T04:53:13 | e346df17ed965703ae715c41cb9fe9fe6def039c | {
"blob_id": "e346df17ed965703ae715c41cb9fe9fe6def039c",
"branch_name": "refs/heads/main",
"committer_date": "2021-04-30T04:53:13",
"content_id": "278cbf6d00b0465e483344caa0e349a6ababf138",
"detected_licenses": [
"MIT"
],
"directory_id": "226db4cd37e59d742dcbeb128f272cb8a22ad81a",
"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": 362986281,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 7704,
"license": "MIT",
"license_type": "permissive",
"path": "/trisprof-dbg/main.c",
"provenance": "stackv2-0123.json.gz:4269",
"repo_name": "TheMindVirus/sprof",
"revision_date": "2021-04-30T04:53:13",
"revision_id": "0a97e3a05657e0bca76a71428f5b07b430b5b64e",
"snapshot_id": "dbf5ca89030e12baa318b4d0adbdbb72ead9d3b9",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/TheMindVirus/sprof/0a97e3a05657e0bca76a71428f5b07b430b5b64e/trisprof-dbg/main.c",
"visit_date": "2023-04-18T06:55:47.583759"
} | stackv2 | #include "main.h"
#include "shader.v"
#include "shader.f"
static void show_log(GLint shader);
static void show_program_log(GLint program);
static void init_ogl(PTRI_STATE_T state);
static void init_shaders(PTRI_STATE_T state);
static void draw_triangle(PTRI_STATE_T state);
static int get_mouse(PTRI_STATE_T state, int* outx, int* outy);
int main()
{
GLuint running = 1;
GLfloat test = 0.1;
printf("[TEST]: %d %f\n", running, test);
bcm_host_init();
memset(state, 0, sizeof(*state));
state->verbose = 1;
init_ogl(state);
init_shaders(state);
while (running)
{
int x, y, b = 0;
b = get_mouse(state, &x, &y);
if (b) { break; }
draw_triangle(state);
break;
}
return 0;
}
static void show_log(GLint shader)
{
char log[1024];
glGetShaderInfoLog(shader, sizeof(log), NULL, log);
printf("[INFO]: %s\n", log);
}
static void show_program_log(GLint program)
{
char log[1024];
glGetProgramInfoLog(program, sizeof(log), NULL, log);
printf("[INFO]: %s\n", log);
}
static void init_ogl(PTRI_STATE_T state)
{
int32_t success = 0;
EGLBoolean result = 0;
EGLint num_config = 0;
static EGL_DISPMANX_WINDOW_T native_window;
EGLConfig config;
DISPMANX_ELEMENT_HANDLE_T dispman_element;
DISPMANX_DISPLAY_HANDLE_T dispman_display;
DISPMANX_UPDATE_HANDLE_T dispman_update;
VC_RECT_T dst_rect;
VC_RECT_T src_rect;
static const EGLint attribute_list[] =
{
EGL_RED_SIZE, 8,
EGL_GREEN_SIZE, 8,
EGL_BLUE_SIZE, 8,
EGL_ALPHA_SIZE, 8,
EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
EGL_NONE
};
static const EGLint context_attributes[] =
{
EGL_CONTEXT_CLIENT_VERSION, 2,
EGL_NONE
};
state->display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
assert(state->display != EGL_NO_DISPLAY);
check();
result = eglInitialize(state->display, NULL, NULL);
assert(EGL_FALSE != result);
check();
result = eglChooseConfig(state->display, attribute_list, &config, 1, &num_config);
assert(EGL_FALSE != result);
check();
result = eglBindAPI(EGL_OPENGL_ES_API);
assert(EGL_FALSE != result);
check();
state->context = eglCreateContext(state->display, config, EGL_NO_CONTEXT, context_attributes);
assert(state->context != EGL_NO_CONTEXT);
check();
success = graphics_get_display_size(0, &state->screen_width, &state->screen_height);
assert(success >= 0);
dst_rect.x = 0;
dst_rect.y = 0;
dst_rect.width = state->screen_width;
dst_rect.height = state->screen_height;
src_rect.x = 0;
src_rect.y = 0;
src_rect.width = state->screen_width << 16;
src_rect.height = state->screen_height << 16;
dispman_display = vc_dispmanx_display_open(0);
dispman_update = vc_dispmanx_update_start(0);
dispman_element = vc_dispmanx_element_add(dispman_update, dispman_display,
0, &dst_rect, 0, &src_rect, DISPMANX_PROTECTION_NONE, 0, 0, 0);
native_window.element = dispman_element;
native_window.width = state->screen_width;
native_window.height = state->screen_height;
vc_dispmanx_update_submit_sync(dispman_update);
check();
state->surface = eglCreateWindowSurface(state->display, config, &native_window, NULL);
assert(state->surface != EGL_NO_SURFACE);
check();
result = eglMakeCurrent(state->display, state->surface, state->surface, state->context);
assert(EGL_FALSE != result);
check();
glClearColor(0.0, 0.0, 0.0, 0.0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
check();
}
static void init_shaders(PTRI_STATE_T state)
{
static const GLfloat vertex_data[] =
{
-1.0, -1.0, 1.0, 1.0,
1.0, -1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0,
-1.0, 1.0, 1.0, 1.0
};
if (state->verbose) { printf("[INFO]: %s\n", "Compiling Vertex Shader..."); }
state->vertex_shader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(state->vertex_shader, 1, &vertex_shader_source, 0);
glCompileShader(state->vertex_shader);
check(); if (state->verbose) { show_log(state->vertex_shader); }
if (state->verbose) { printf("[INFO]: %s\n", "Compiling Fragment Shader..."); }
state->fragment_shader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(state->fragment_shader, 1, &fragment_shader_source, 0);
glCompileShader(state->fragment_shader);
check(); if (state->verbose) { show_log(state->fragment_shader); }
if (state->verbose) { printf("[INFO]: %s\n", "Linking Shader Program..."); }
state->program = glCreateProgram();
glAttachShader(state->program, state->vertex_shader);
glAttachShader(state->program, state->fragment_shader);
glLinkProgram(state->program);
check(); if (state->verbose) { show_program_log(state->program); }
state->attribute_vertex = glGetAttribLocation(state->program, "vertex");
glClearColor(0.0, 0.0, 0.0, 0.0);
glGenBuffers(1, &state->vertex_buffer);
check();
glGenTextures(1, &state->texture); check();
glBindTexture(GL_TEXTURE_2D, state->texture); check();
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, state->screen_width, state->screen_height,
0, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, 0); check();
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
check();
glGenFramebuffers(1, &state->framebuffer); check();
glBindFramebuffer(GL_FRAMEBUFFER, state->framebuffer); check();
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D,
state->texture, 0); check();
glBindFramebuffer(GL_FRAMEBUFFER, 0); check();
glViewport(0, 0, state->screen_width, state->screen_height); check();
glBindBuffer(GL_ARRAY_BUFFER, state->vertex_buffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertex_data), vertex_data, GL_STATIC_DRAW);
glVertexAttribPointer(state->attribute_vertex, 4, GL_FLOAT, 0, 16, 0);
glEnableVertexAttribArray(state->attribute_vertex);
check();
}
static void draw_triangle(PTRI_STATE_T state)
{
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); check();
glBindBuffer(GL_ARRAY_BUFFER, state->vertex_buffer); check();
glUseProgram(state->program); check();
glBindTexture(GL_TEXTURE_2D, state->texture); check();
glDrawArrays(GL_TRIANGLE_FAN, 0, 4); check();
glBindBuffer(GL_ARRAY_BUFFER, 0);
glFlush();
glFinish(); check();
eglSwapBuffers(state->display, state->surface); check();
}
static int get_mouse(PTRI_STATE_T state, int* outx, int* outy)
{
static int fd = -1;
const int width = state->screen_width;
const int height = state->screen_height;
static int x = 800;
static int y = 400;
const int XSIGN = 1 << 4;
const int YSIGN = 1 << 5;
if (fd < 0) { fd = open("/dev/input/mouse0", O_RDONLY | O_NONBLOCK); }
if (fd >= 0)
{
struct { char buttons, dx, dy; } m;
while (1)
{
int bytes = read(fd, &m, sizeof(m));
if (bytes < (int)(sizeof(m))) { goto _exit; }
if (m.buttons & 8) { break; }
read(fd, &m, 1);
}
if (m.buttons & 3) { return m.buttons & 3; }
x += m.dx;
y += m.dy;
if (m.buttons & XSIGN) { x -= 256; }
if (m.buttons & YSIGN) { y -= 256; }
if (x < 0) { x = 0; }
if (y < 0) { y = 0; }
if (x > width) { x = width; }
if (y > height) { y = height; }
}
_exit:
if (outx) { *outx = x; }
if (outy) { *outy = y; }
return 0;
}
| 2.15625 | 2 |
2024-11-18T22:21:47.886317+00:00 | 2012-04-20T20:22:34 | 0c729f57b9797b55912c4b388af80b35abd85681 | {
"blob_id": "0c729f57b9797b55912c4b388af80b35abd85681",
"branch_name": "refs/heads/master",
"committer_date": "2012-04-20T20:22:34",
"content_id": "407d2aab9dadd136d3d3c383e89092dfeb73bc88",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "35ae9cc47056b42a51391db3a8ce14fea9a29beb",
"extension": "c",
"filename": "Parser_UTF32.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": 4428,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/Unicode/Parser_UTF32.c",
"provenance": "stackv2-0123.json.gz:4915",
"repo_name": "dreamsxin/101_browser",
"revision_date": "2012-04-20T20:22:34",
"revision_id": "cadb28c5bfaab40c4be97c1c39e4c97fca0ccfb9",
"snapshot_id": "54c974d881e31671af07e6d023ce3f31284f401d",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/dreamsxin/101_browser/cadb28c5bfaab40c4be97c1c39e4c97fca0ccfb9/src/Unicode/Parser_UTF32.c",
"visit_date": "2021-01-01T15:55:13.934901"
} | stackv2 | /*
* Copyright 2012 Wolfgang Keller
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "Unicode/Parser.h"
#include "Unicode/Parser_Util.h"
#include "MiniStdlib/MTAx_cstdlib.h" // for the conversation functions for endianness
#include <assert.h>
void utf32_StateInit(UTF32_State *out_pState, bool in_bigEndian)
{
out_pState->bigEndian = in_bigEndian;
utf32_StateReset(out_pState);
}
void utf32_StateReset(UTF32_State *out_pState)
{
out_pState->entryPoint = UTF32_EntryPoint_BeforeReading;
out_pState->readCount = 0;
}
ParseBlocker utf32_parse(
void *in_out_pParserState,
void *in_pReadState, ByteStreamReadInterface_v4 in_readInterface,
void *in_pWriteState, ByteStreamWriteInterface_v4 in_writeInterface)
{
UTF32_State *pUTF32State = (UTF32_State *) in_out_pParserState;
extern const UnicodeCodePoint cReplacementCharacter;
assert(in_readInterface.mpfRead != NULL);
assert(in_readInterface.commonByteStreamInterface.mpfGetStatus != NULL);
switch (pUTF32State->entryPoint)
{
case UTF32_EntryPoint_BeforeReading:
goto Label_EntryPoint_BeforeReading;
case UTF32_EntryPoint_WriteTerminalReplacementCharacter:
goto Label_EntryPoint_WriteTerminalReplacementCharacter;
case UTF32_EntryPoint_WriteCharacter:
goto Label_EntryPoint_WriteCharacter;
case UTF32_EntryPoint_Terminated:
goto Label_EntryPoint_Terminated;
}
assert(false);
while (1)
{
size_t rwCount;
pUTF32State->readCount = 0;
Label_EntryPoint_BeforeReading:
assert(pUTF32State->readCount < 4);
rwCount = in_readInterface.mpfRead(in_pReadState,
((uint8_t*) &pUTF32State->currentCodePoint)+pUTF32State->readCount,
4 - pUTF32State->readCount);
assert(rwCount <= 4u - pUTF32State->readCount);
pUTF32State->readCount += (uint8_t) rwCount;
if (0 == pUTF32State->readCount)
{
ByteStreamStatus_v4 status = in_readInterface.
commonByteStreamInterface.mpfGetStatus(in_pReadState);
assert(ByteStreamStatus_OK != status);
if (ByteStreamStatus_Terminated == status)
goto terminate;
else
{
pUTF32State->entryPoint = UTF32_EntryPoint_BeforeReading;
return ParseBlocker_Reader;
}
}
else if (4 != pUTF32State->readCount)
{
ByteStreamStatus_v4 status = in_readInterface.
commonByteStreamInterface.mpfGetStatus(in_pReadState);
assert(ByteStreamStatus_OK != status);
assert(pUTF32State->readCount < 4);
if (ByteStreamStatus_Terminated == status)
{
Label_EntryPoint_WriteTerminalReplacementCharacter:
// Write terminal replacement character
if (emitCodepoint(in_pWriteState, in_writeInterface,
cReplacementCharacter, &pUTF32State->entryPoint,
sizeof(UTF32_EntryPoint),
UTF32_EntryPoint_WriteTerminalReplacementCharacter))
return ParseBlocker_Writer;
goto terminate;
}
else
{
pUTF32State->entryPoint = UTF32_EntryPoint_BeforeReading;
return ParseBlocker_Reader;
}
}
if (pUTF32State->bigEndian)
pUTF32State->currentCodePoint = _byteswap_ulong(pUTF32State->currentCodePoint);
if ((pUTF32State->currentCodePoint >= 0xD800 &&
pUTF32State->currentCodePoint <= 0xDFFF) ||
pUTF32State->currentCodePoint >= 0x110000)
pUTF32State->currentCodePoint = cReplacementCharacter;
Label_EntryPoint_WriteCharacter:
if (emitCodepoint(in_pWriteState, in_writeInterface,
pUTF32State->currentCodePoint, &pUTF32State->entryPoint,
sizeof(UTF32_EntryPoint),
UTF32_EntryPoint_WriteCharacter))
return ParseBlocker_Writer;
}
terminate:
if (!ByteStreamStatus_Error == in_writeInterface.
commonByteStreamInterface.mpfGetStatus(in_pWriteState))
in_writeInterface.commonByteStreamInterface.mpfSetStatus(
in_pWriteState, ByteStreamStatus_Terminated);
pUTF32State->entryPoint = UTF32_EntryPoint_Terminated;
Label_EntryPoint_Terminated:
assert(ByteStreamStatus_Terminated == in_readInterface.
commonByteStreamInterface.mpfGetStatus(in_pReadState));
return ParseBlocker_Neither;
}
| 2.046875 | 2 |
2024-11-18T22:21:48.239024+00:00 | 2019-11-28T09:54:28 | 1c18939a0e306eb595446e4de8c3479886cc8b16 | {
"blob_id": "1c18939a0e306eb595446e4de8c3479886cc8b16",
"branch_name": "refs/heads/master",
"committer_date": "2019-11-28T09:54:28",
"content_id": "ea733596ad437a79683da0d4132ce8430899c5ca",
"detected_licenses": [
"MIT"
],
"directory_id": "1f9c6400485e1e284e0c9dbad9cea2ff897cb899",
"extension": "c",
"filename": "color.c",
"fork_events_count": 0,
"gha_created_at": "2019-11-28T09:49:32",
"gha_event_created_at": "2019-11-28T09:49:33",
"gha_language": null,
"gha_license_id": "NOASSERTION",
"github_id": 224621140,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1267,
"license": "MIT",
"license_type": "permissive",
"path": "/v6.0/45/beef/cw/user/color.c",
"provenance": "stackv2-0123.json.gz:5558",
"repo_name": "number201724/MS-DOS",
"revision_date": "2019-11-28T09:54:28",
"revision_id": "6624294eba6aec1be0f25ffb39986c16779e3b58",
"snapshot_id": "1eb13c56ff19071ceaa3a9ca57c04a9f628f342d",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/number201724/MS-DOS/6624294eba6aec1be0f25ffb39986c16779e3b58/v6.0/45/beef/cw/user/color.c",
"visit_date": "2020-09-20T23:52:54.617761"
} | stackv2 | /*
COW : Character Oriented Windows
color : default colors
SWAP TUNE NOTE : belongs in INIT module !!!!
*/
#define COW
#include <cow.h>
#include <uscreen.h>
#include <uisa.h>
#include <ucolor.h>
#include "screen.h"
#include "color.h"
extern SA PASCAL rgsa[]; /* isa -> sa */
#ifdef SCREEN_FFONT
extern WORD PASCAL mpisaffont[]; /* isa -> ffont */
#endif /*SCREEN_FFONT*/
PUBLIC VOID FARPUBLIC
SetIsaColor(isa, coFore, coBack)
/*
-- set colors for a given ISA
*/
ISA isa;
WORD coFore;
WORD coBack;
{
StartPublic();
AssertSz(coFore < 16 && coBack < 16, "SetSysColor invalid color");
rgsa[isa].u.draw.caSa = (BYTE) CaMake(coFore, coBack);
StopPublic();
}
PUBLIC VOID FARPUBLIC
GetIsaColor(isa, pcoFore, pcoBack)
/*
-- get colors for a given ISA
*/
ISA isa;
WORD * pcoFore;
WORD * pcoBack;
{
BYTE ca;
StartPublic();
ca = rgsa[isa].u.draw.caSa;
*pcoBack = (ca >> 4) & 15;
*pcoFore = ca & 15;
StopPublic();
}
PUBLIC VOID FARPUBLIC
SetIsaRgca(isa, rgcaFill)
ISA isa;
BYTE * rgcaFill;
{
StartPublic();
rgsa[isa].u.rgcaFill = rgcaFill; /* note : trashes ca */
StopPublic();
}
#ifdef SCREEN_FFONT
PUBLIC VOID FARPUBLIC
SetIsaFfont(isa, ffont)
ISA isa;
WORD ffont;
{
mpisaffont[isa] = ffont;
}
#endif /*SCREEN_FFONT*/
| 2.25 | 2 |
2024-11-18T22:21:48.577719+00:00 | 2021-08-13T09:33:08 | b3589fbbdbefdabe7e1b1ffad8e36c3f250475c7 | {
"blob_id": "b3589fbbdbefdabe7e1b1ffad8e36c3f250475c7",
"branch_name": "refs/heads/master",
"committer_date": "2021-08-13T09:33:08",
"content_id": "7a1338589d4d7bcc6369ee08e9da6f7abac6d23a",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "30fdedd9cf478e7a75697e98f75cd009b46c0b1d",
"extension": "c",
"filename": "scope.c",
"fork_events_count": 4,
"gha_created_at": "2019-06-11T07:56:29",
"gha_event_created_at": "2020-03-27T09:44:38",
"gha_language": "C",
"gha_license_id": "BSD-3-Clause",
"github_id": 191322275,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 12895,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/src/scope.c",
"provenance": "stackv2-0123.json.gz:5944",
"repo_name": "Mashpoe/heck",
"revision_date": "2021-08-13T09:33:08",
"revision_id": "e002dba45a47d2bb8174f8a01d00a247c9d69202",
"snapshot_id": "572943aa63eb5619e70d401334220a705d4de53a",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/Mashpoe/heck/e002dba45a47d2bb8174f8a01d00a247c9d69202/src/scope.c",
"visit_date": "2021-08-30T14:43:59.968993"
} | stackv2 | //
// scope.c
// Heck
//
// Created by Mashpoe on 7/6/19.
//
#include "vec.h"
#include <class.h>
#include <code_impl.h>
#include <error.h>
#include <function.h>
#include <print.h>
#include <scope.h>
#include <stdio.h>
heck_name* name_create(heck_code* c, heck_scope* parent, heck_idf_type type,
str_entry name_str)
{
heck_name* name = malloc(sizeof(heck_name));
heck_add_name(c, name);
name->type = type;
name->value.class_value = NULL; // will set all fields to NULL
name->parent = parent;
name->child_scope = NULL;
name->name_str = name_str;
name->flags = 0x0; // set all flags to 0
return name;
}
heck_scope* scope_create(heck_code* c, heck_scope* parent)
{
heck_scope* scope = malloc(sizeof(heck_scope));
heck_add_scope(c, scope);
scope->names = NULL;
// scope->decl_vec = NULL;
scope->var_inits = NULL;
scope->parent = parent;
scope->parent_nmsp = parent->parent_nmsp;
scope->parent_class = parent->parent_class;
scope->parent_func = parent->parent_func;
return scope;
}
heck_scope* scope_create_global(heck_code* c)
{
heck_scope* scope = malloc(sizeof(heck_scope));
heck_add_scope(c, scope);
scope->names = NULL;
// scope->decl_vec = NULL;
scope->var_inits = NULL;
scope->parent = NULL;
scope->parent_nmsp = scope;
scope->parent_class = NULL;
scope->parent_func = NULL;
return scope;
}
// void free_name_callback(str_entry key, void* value, void* user_ptr) {
// heck_name* name = value;
// // printf("free %s\n", key->value);
// switch(name->type) {
// case IDF_VARIABLE:
// // TODO: free variable
// break;
// case IDF_FUNCTION: {
// heck_func_list* func_list = &name->value.func_value;
// if (func_list->decl_vec != NULL) {
// size_t num_decls = vector_size(func_list->decl_vec);
// for (size_t i = 0; i < num_decls; ++i) {
// free_decl_data(&func_list->decl_vec[i]);
// }
// vector_free(func_list->decl_vec);
// }
// if (func_list->def_vec != NULL) {
// size_t num_defs = vector_size(func_list->def_vec);
// for (size_t i = 0; i < num_defs; ++i) {
// func_free(func_list->def_vec[i]);
// }
// vector_free(func_list->def_vec);
// break;
// }
// }
// case IDF_UNDECLARED_CLASS:
// case IDF_CLASS:
// // TODO: free class
// break;
// default:
// break;
// }
// }
// void scope_free(heck_scope* scope) {
// if (scope->names != NULL) {
// // free all items in the scope
// idf_map_iterate(scope->names, free_name_callback, NULL);
// // free the scope itself
// idf_map_free(scope->names);
// }
// if (scope->var_inits != NULL)
// vector_free(scope->var_inits);
// free(scope);
// }
// use this function only when parsing a declaration or definition
// finds a child of a scope, possibly multiple levels deep.
// if the child cannot be found, it may be implicitly declared.
// returns null on failure
heck_name* scope_get_child(heck_code* c, heck_scope* scope, heck_idf idf)
{
// the current name as we iterate through the idf
heck_name* name;
// try to iterate through the tree of names
int i = 0;
do
{
if (scope->names == NULL)
{
scope->names = idf_map_create();
}
else if (idf_map_get(scope->names, idf[i], (void*)&name))
{
// access modifiers won't matter until resolving
if (name->child_scope == NULL)
{
// return if there are no more children
if (idf[++i] == NULL)
return name;
// we need to create children, check the
// identifier type first
if (name->type == IDF_FUNCTION ||
name->type == IDF_VARIABLE)
return NULL;
// create a child, let the loop below do the
// rest of the work
name->child_scope = scope_create(c, scope);
scope = name->child_scope;
scope->names = idf_map_create();
}
else
{
// there is a child scope, so we can obviously
// continue
scope = name->child_scope;
// we can continue checking for children as long
// as they exist
continue;
}
}
// the above continue wasn't reached, so the child doesn't exist
// we'll just create one instead
for (;;)
{
name = name_create(c, scope, IDF_UNDECLARED, idf[i]);
idf_map_set(scope->names, idf[i], name);
if (idf[++i] == NULL)
return name;
// create a child scope
name->child_scope = scope_create(c, scope);
scope = name->child_scope;
scope->names = idf_map_create();
}
// we are done creating children
return name;
} while (idf[++i] != NULL);
// if this is reached, the children were found without implicit
// declarations
return name;
}
// "parent" is the scope we are requesting access from, "name" is the item we
// are requesting access to
bool name_accessible(const heck_scope* parent, const heck_name* name)
{
if (name->access == ACCESS_PUBLIC)
return true;
if (name->type == IDF_CLASS &&
parent->parent_class == name->child_scope->parent_class)
return true;
if (name->access == ACCESS_PRIVATE || name->access == ACCESS_PROTECTED)
{
// vec_size_t size =
// vector_size(&((heck_class*)parent->class)->friends); for
// (vec_size_t i = 0; i < size; ++i) {}
return false;
}
return false;
}
// this will be called by scope_resolve_idf. It will do the same thing as
// scope_resolve_idf, but it will stop once it gets to a variable. idf_ptr is an
// input and an output. It will increment the idf, e.g. ++(*idf_ptr), to either
// the last element or the first one that refers to the variable.
heck_name* scope_resolve_idf_name(heck_code* c, const heck_scope* parent,
heck_idf* idf_ptr, heck_file_pos* fp)
{
heck_idf idf = *idf_ptr;
// find the parent of the idf
heck_name* name;
while (parent->names == NULL ||
!idf_map_get(parent->names, idf[0], (void*)&name))
{
// we have likely reached the global scope if parent->parent ==
// NULL
if (parent->parent == NULL)
{
// printf("not found idf: %i, %s\n", idf[0]->hash,
// idf[0]->value);
heck_report_error(
c, fp, "unable to resolve identifier \"{s}\"",
idf[0]->value);
return NULL;
}
parent =
parent
->parent; // check for the identifier in the parent nmsp
}
// printf("found idf: %i, %s\n", idf[0]->hash, idf[0]->value);
/* we have found the parent of the identifier.
now find the identifier "children" if they exist */
while (idf[1] != NULL)
{
heck_scope* child_scope = name->child_scope;
if (child_scope != NULL)
{
if (idf_map_get(child_scope->names, idf[1],
(void*)&name))
{
if (!name_accessible(parent, name))
heck_report_error(
c, fp,
"identifier \"{I}\" cannot "
"be accessed from here",
*idf_ptr);
return NULL;
}
}
else if (name->type == IDF_VARIABLE)
{
// check if the name is an object
const heck_data_type* var_type =
name->value.var_value->data_type;
heck_class* var_class;
if (var_type == NULL)
{
heck_report_error(
c, fp,
"member access on variable \"{s}\" whose "
"type is unknown",
idf[0]->value);
return NULL;
}
else if (var_type->type_name == TYPE_CLASS)
{
// the class type is resolved when the
// variable's declaration is resolved, so we can
// access it here
var_class =
var_type->value.class_type.class_value;
// class members will be processed later.
// exit the function.
break;
}
else
{
// the variable is not an object and therefore
// has no children.
heck_report_error(
c, fp,
"member access is not permitted for this "
"type \"{I}\"",
*idf_ptr);
return NULL;
}
// increment to the next identifier
++idf;
}
else
{
// TODO: report error
return NULL;
}
++idf;
}
(*idf_ptr) = idf;
return name;
}
// calls socpe_resolve_idf_name, and returns NULL if the output idf is not the
// last element of the idf chain (meaning it returns NULL if the idf contains
// object member access)
heck_name* scope_resolve_idf(heck_code* c, const heck_scope* parent,
heck_idf idf, heck_file_pos* fp)
{
heck_idf tmp = idf;
heck_name* result = scope_resolve_idf_name(c, parent, &tmp, fp);
// check if scope_resolve_idf_name was able to reach the end of the
// heck_idf. If not, we cannot resolve the remaining items, which means
// there is an error and we will return NULL.
if (tmp != NULL && tmp[1] != NULL)
{
heck_report_error(c, fp, "invalid access to \"{I}\"", idf);
return NULL;
}
return result;
}
// heck_name* scope_resolve_value(heck_code* c, heck_scope* parent,
// heck_expr_value* value)
// {
// switch (value->context)
// {
// case CONTEXT_LOCAL:
// return scope_resolve_idf(parent, value->idf);
// case CONTEXT_THIS:
// if (parent->parent_class == NULL ||
// parent->parent_class->child_scope == NULL)
// return NULL;
// return scope_resolve_idf(
// parent->parent_class->child_scope, value->idf);
// case CONTEXT_GLOBAL:
// return scope_resolve_idf(c->global, value->idf);
// }
// }
// helper struct for resolve_name_callback
typedef struct resolve_name_data
{
heck_code* c;
bool success;
} resolve_name_data;
void resolve_name_callback(str_entry key, void* value, void* user_ptr)
{
heck_name* name = value;
resolve_name_data* data = user_ptr;
switch (name->type)
{
case IDF_FUNCTION:
{
data->success *= func_resolve_name(data->c, name);
break;
}
case IDF_UNDECLARED_CLASS:
data->success = false;
// fallthrough
case IDF_CLASS:
{
data->success *=
scope_resolve_names(data->c, name->child_scope);
// TODO: resolve operator overloads
break;
}
case IDF_UNDECLARED:
{
if (name->child_scope != NULL)
{
data->success *= scope_resolve_names(
data->c, name->child_scope);
}
}
}
}
bool scope_resolve_names(heck_code* c, heck_scope* scope)
{
if (scope->names == NULL)
return true; // nothing to resolve
resolve_name_data data = {.c = c, .success = true};
idf_map_iterate(scope->names, resolve_name_callback, (void*)&data);
return data.success;
}
// void scope_add_decl(heck_scope* scope, heck_stmt* decl) {
// if (scope->decl_vec == NULL)
// scope->decl_vec = vector_create();
// vector_add(&scope->decl_vec, decl);
// }
// this could be made into a macro as a ternary expression
//#define scope_is_class(scope) ((scope)->class == NULL ? false :
//(scope)->class->child_scope == (scope))
bool scope_is_class(heck_scope* scope)
{
if (scope->parent_class == NULL)
return false;
return scope->parent_class->child_scope == scope;
}
bool scope_var_is_init(heck_scope* scope, heck_name* var_name)
{
heck_variable* var_value = var_name->value.var_value;
if (var_value->value != NULL)
return true;
do
{
if (scope->var_inits != NULL)
{
vec_size_t num_inits = vector_size(scope->var_inits);
for (vec_size_t i = 0; i < num_inits; ++i)
{
if (scope->var_inits[i] == var_value)
return true;
}
}
if (scope == var_name->parent)
break;
scope = scope->parent;
// possibly remove "scope != NULL"
} while (scope != NULL);
return false;
}
// TODO: add vtables
// bool resolve_scope(heck_scope* scope, heck_scope* global) {
// if (scope->decl_vec == NULL)
// return true;
//
// bool result = true;
//
// vec_size_t size = vector_size(scope->decl_vec);
// for (vec_size_t i = 0; i < size; ++i) {
// heck_stmt* current = scope->decl_vec[i];
// if (!current->vtable->resolve(current, scope, global))
// result = false;
// }
//
// return result;
//}
void print_idf_map(str_entry key, void* value, void* user_ptr)
{
int indent = *(int*)user_ptr;
heck_name* name = (heck_name*)value;
switch (name->type)
{
case IDF_CONSTRUCTOR: // fallthrough
print_indent(indent);
printf("constructor:\n");
case IDF_FUNCTION:
print_func_decls(&name->value.func_value, key->value,
indent);
print_func_defs(&name->value.func_value, key->value,
indent);
return;
break;
case IDF_VARIABLE:
print_indent(indent);
printf("variable %s\n", key->value);
return;
break;
// TODO: eliminate redundancies
case IDF_UNDECLARED_CLASS: // fallthrough TODO: print undeclared
case IDF_CLASS:
{
print_class(name, key->value, indent);
break;
}
default:
{
for (int i = 0; i < indent; ++i)
{
printf("\t");
}
printf("scope %s {\n", key->value);
}
}
if (name->child_scope != NULL && name->child_scope->names != NULL)
{
++indent;
idf_map_iterate(name->child_scope->names, print_idf_map,
(void*)&indent);
--indent;
}
// closing bracket
for (int i = 0; i < indent; ++i)
{
printf("\t");
}
printf("}\n");
}
void print_scope(heck_scope* scope, int indent)
{
if (scope->names != NULL)
idf_map_iterate(scope->names, print_idf_map, (void*)&indent);
}
| 2.59375 | 3 |
2024-11-18T22:21:48.793150+00:00 | 2021-02-06T06:14:02 | 59b17bef786cd23123c153f60a1d003b7ab6821e | {
"blob_id": "59b17bef786cd23123c153f60a1d003b7ab6821e",
"branch_name": "refs/heads/main",
"committer_date": "2021-02-06T06:14:02",
"content_id": "839752d3a8a0a872685770597c2a514f837b2e7c",
"detected_licenses": [
"MIT"
],
"directory_id": "82b67ec73b76cc69e95d0143cdebf5e5fd63b4cc",
"extension": "c",
"filename": "0518 - Sum of two - Сумма двух.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 335319554,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 282,
"license": "MIT",
"license_type": "permissive",
"path": "/0000-0999/0518 - Sum of two - Сумма двух.c",
"provenance": "stackv2-0123.json.gz:6072",
"repo_name": "thelvir/E-Olymp",
"revision_date": "2021-02-06T06:14:02",
"revision_id": "2c7f69aa4f6dbfde237b25815e2f5762aa383e3b",
"snapshot_id": "64bc3b8e265a08aa0a2436af8e476cc7424c593f",
"src_encoding": "UTF-8",
"star_events_count": 4,
"url": "https://raw.githubusercontent.com/thelvir/E-Olymp/2c7f69aa4f6dbfde237b25815e2f5762aa383e3b/0000-0999/0518 - Sum of two - Сумма двух.c",
"visit_date": "2023-02-26T04:07:31.190113"
} | stackv2 | #include <stdio.h>
#include <stdlib.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main() {
int t,a,b,c,x;
scanf("%d", &t);
for(c=1;c<=t;c++){
scanf("%d %d",&a, &b);
x=a+b;
printf("%d\n",x);}
return 0;
}
| 2.96875 | 3 |
2024-11-18T22:21:49.048167+00:00 | 2021-03-15T08:50:26 | 1079fddd4a14a782df7a8ae0b563d570ee947838 | {
"blob_id": "1079fddd4a14a782df7a8ae0b563d570ee947838",
"branch_name": "refs/heads/master",
"committer_date": "2021-03-22T12:09:52",
"content_id": "0f1d8ff332437650409459f05285f69fb5265b2a",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "c01fe30c83296efe90153a7a20e118900c8363a0",
"extension": "h",
"filename": "jfr2wlib.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 52397097,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2908,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/source/include/jfr2wlib.h",
"provenance": "stackv2-0123.json.gz:6459",
"repo_name": "inniyah/jfs-fuzzy",
"revision_date": "2021-03-15T08:50:26",
"revision_id": "6ffd6f937d707f27c6845ecc197983506c164916",
"snapshot_id": "9534fa6497a96d028611f58200e02948e9aab921",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/inniyah/jfs-fuzzy/6ffd6f937d707f27c6845ecc197983506c164916/source/include/jfr2wlib.h",
"visit_date": "2021-07-15T02:46:39.642877"
} | stackv2 | /*********************************************************************/
/* */
/* jfr2wlib.h Version 2.01 Copyright (c) 1999-2000 Jan E. Mortensen */
/* */
/* JFS Inverse Compiler-functions. Converts a JFR-file to a JFW-file.*/
/* */
/* by Jan E. Mortensen email: jemor@inet.uni2.dk */
/* Lollandsvej 35 3.tv. */
/* DK-2000 Frederiksberg */
/* Denmark */
/* */
/*********************************************************************/
#ifndef jfr2wlibH
#define jfr2wlibH
int jfr2w_conv(char *de_fname, char *so_fname, char *sout_fname,
int out_mode, int ndigits,
int maxtext, int maxtree, int maxstack,
int rule_nos, int smode, int sw_comments);
/* Convert the .jfr-file <de_fname> to the .jfw-file <so_fname>. */
/* sout_fname: Redirect messages, normaly written to stdout, to */
/* <sout_fname>. If <sout_fname>==NULL write messages to */
/* stdout. */
/* out_mode : 0: overwrite <sout_fname>, */
/* 1: append to <sout_fname>. */
/* ndigits : max number of digits after decimal-point. */
/* if <ndigits>==0 then default (5). */
/* maxtext : Maximal number of chars in a single statement. */
/* if <maxtext>==0 then default (512). */
/* maxtree : Maximal number of nodes in jfg_tree. If <maxtree>==0 */
/* then default (128). */
/* maxstack : Size of conversion-stack. If <maxstack>==0 then */
/* default-size (64). */
/* rules_nos: 1: write rule-numbers in comment-lines. */
/* smode : 0: Write only the nessasary parentheses, */
/* 1: Write parentheses around all expressions. */
/* sw_comments: 1: write '|'-comments in case-statements. */
/* */
/* RETURN: */
/* 0: succes, */
/* 1: warnings, */
/* 2: errors, */
/* 3: fatal errors. */
#endif
| 2.078125 | 2 |
2024-11-18T22:21:49.113792+00:00 | 2013-11-20T17:07:00 | 16bb4bcbadbc6b8842055d8b36b562cd2e6e50e3 | {
"blob_id": "16bb4bcbadbc6b8842055d8b36b562cd2e6e50e3",
"branch_name": "refs/heads/master",
"committer_date": "2013-11-20T17:07:00",
"content_id": "0af5337ba1d02eff4c5f18ead48d5e8ea2b8a7a0",
"detected_licenses": [
"MIT"
],
"directory_id": "f4b569900aa005eae6ee5c2b5bb1281f5aae2495",
"extension": "c",
"filename": "bl_environment_test.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 14445512,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 628,
"license": "MIT",
"license_type": "permissive",
"path": "/test/bl_environment_test.c",
"provenance": "stackv2-0123.json.gz:6590",
"repo_name": "matthiaskraaz/binary-logger",
"revision_date": "2013-11-20T17:07:00",
"revision_id": "2251cf4c57225639fd94fe31b85b41a4d071baec",
"snapshot_id": "817b7d1458c73f110b32c340558719b0a802df66",
"src_encoding": "UTF-8",
"star_events_count": 4,
"url": "https://raw.githubusercontent.com/matthiaskraaz/binary-logger/2251cf4c57225639fd94fe31b85b41a4d071baec/test/bl_environment_test.c",
"visit_date": "2020-05-31T13:25:37.976078"
} | stackv2 | /* Binary logger by Matthias Kraaz. Creative commons. */
/** @file Adaption of binary logger to running inside a POSIX process for testing purposed. */
#include "bl_environment.h"
#include <unistd.h>
#include <assert.h>
#include <pthread.h>
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void bl_lock_producers(void)
{
int ok = pthread_mutex_lock( &mutex );
assert(ok == 0);
}
void bl_unlock_producers(void)
{
int ok = pthread_mutex_unlock( &mutex );
assert(ok == 0);
}
void bl_write(const uint8_t *buf, uint_fast8_t count)
{
int ok = write(STDOUT_FILENO, buf, (size_t)count);
assert(ok == count);
}
| 2.109375 | 2 |
2024-11-18T22:21:49.196011+00:00 | 2017-12-14T00:39:49 | 2448d2a90febc7aa4cd8bbe1d603002fede758f9 | {
"blob_id": "2448d2a90febc7aa4cd8bbe1d603002fede758f9",
"branch_name": "refs/heads/master",
"committer_date": "2017-12-14T00:39:49",
"content_id": "a32ec95e298114005213f46d25d9fa843d402445",
"detected_licenses": [
"BSD-2-Clause-Views"
],
"directory_id": "1a51a81288b600f1686578f62326f1627d806c03",
"extension": "c",
"filename": "string.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1516,
"license": "BSD-2-Clause-Views",
"license_type": "permissive",
"path": "/libc/string.c",
"provenance": "stackv2-0123.json.gz:6718",
"repo_name": "hyglvy/OS",
"revision_date": "2017-12-14T00:39:49",
"revision_id": "fefb4ab5d5a4b00c01534bf1a7929340e026b78f",
"snapshot_id": "4757f5545787d7c043cd3942e3580058553bf48b",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/hyglvy/OS/fefb4ab5d5a4b00c01534bf1a7929340e026b78f/libc/string.c",
"visit_date": "2020-04-24T20:21:35.485059"
} | stackv2 | #define MAXLEN 100
//static char* iterator;
#include <sys/defs.h>
int atoi(char *str)
{
int res = 0; // Initialize result
// Iterate through all characters of input string and
// update result
for (int i = 0; str[i] != '\0'; ++i)
res = res*10 + str[i] - '0';
// return result.
return res;
}
int strlen(char *s) {
int len = 0;
while(s[len] != '\0') {
len++;
}
return (len+1);
}
void strcpy(char *s1, char*s2) {
while((*s1++ = *s2++));
}
int strcmp(char *s1, char *s2) {
while(*s1 && (*s1 == *s2)) {
s1++;
s2++;
}
return *(const unsigned char*)s1 - *(const unsigned char*)s2;
}
int strcat(char *s1, const char *s2) {
while(*s1)
s1++;
while((*s1++ = *s2++));
return 0;
}
/*char *strtok(char *s, char tok) {
char *ret = (char *)kmalloc(sizeof(char) * MAXLEN);
int i = 0;
if(s != NULL) {
iterator = s;
}
else {
if(!*iterator) return NULL;
iterator++;
if(!*iterator) return NULL;
}
for(;*iterator != tok && *iterator; iterator++) {
ret[i] = *iterator;
i++;
}
return ret;
}*/
char *strrem(char *s, char tok) {
int len = strlen(s);
len-=3;
while(s[len] != tok && len >= 0) {
s[len] = '\0';
len--;
}
return s;
}
int memcpy(char *s1, char *s2, int size) {
int i = 0;
while(i < size) {
*s1 = *s2;
s1 ++;
s2 ++;
i++;
}
return i;
}
int memset(uint8_t *bufptr, int val, int size) {
int i = 0;
while(i < size) {
*(bufptr) = val;
bufptr++;
i++;
}
return i;
}
| 2.9375 | 3 |
2024-11-18T22:21:49.423345+00:00 | 2023-01-11T23:43:12 | 3ac9a89027137b7ce1c743dfb3340fcb8dd310c4 | {
"blob_id": "3ac9a89027137b7ce1c743dfb3340fcb8dd310c4",
"branch_name": "refs/heads/master",
"committer_date": "2023-01-11T23:43:12",
"content_id": "ec1017b5dab3cf69f6ab688f3332ee2272112329",
"detected_licenses": [
"ISC"
],
"directory_id": "f806c29d2ee80cc730300b36a7e7fbdfe42ed14e",
"extension": "c",
"filename": "strsplit.c",
"fork_events_count": 4,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 7613062,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3453,
"license": "ISC",
"license_type": "permissive",
"path": "/src/strsplit.c",
"provenance": "stackv2-0123.json.gz:6975",
"repo_name": "noaaport/nbsp",
"revision_date": "2023-01-11T23:43:12",
"revision_id": "39ae50d2445df016cf69d54527d83dc1ac172338",
"snapshot_id": "3095cfcac6a8c39a67cc9b2fd42005587945f67d",
"src_encoding": "UTF-8",
"star_events_count": 6,
"url": "https://raw.githubusercontent.com/noaaport/nbsp/39ae50d2445df016cf69d54527d83dc1ac172338/src/strsplit.c",
"visit_date": "2023-08-14T03:47:01.348920"
} | stackv2 | /*
* Copyright (c) 2005-2006 Jose F. Nieves <nieves@ltp.upr.clu.edu>
*
* See LICENSE
*
* $Id$
*/
#include <assert.h>
#include <string.h>
#include <stdlib.h>
#include "strsplit.h"
static struct strsplit_st *strsplit_init(int n, char *s);
static void strsplit(struct strsplit_st *strp, char *delim, int flags);
struct strsplit_st *strsplit_create(char *s, char *delim, int flags){
return(strsplit_recreate(s, delim, flags, NULL));
}
struct strsplit_st *strsplit_recreate(char *s, char *delim, int flags,
struct strsplit_st *strp){
struct strsplit_st *new_strp;
char *p;
int n; /* number of fields found */
int b; /* number of characters accumulated in a field */
if((s == NULL) || (*s == '\0'))
return(NULL);
/*
* Count the number of fields.
*/
n = 0;
p = s;
b = 0;
while(*p != '\0'){
if(strchr(delim, *p) != NULL){
if((b != 0) || (flags == STRSPLIT_FLAG_INCEMPTY))
++n;
b = 0;
}else
++b;
++p;
}
/*
* The last field.
*/
if((b != 0) || (flags == STRSPLIT_FLAG_INCEMPTY))
++n;
if((strp != NULL) && (strp->argc >= n) && (strlen(strp->sp) >= strlen(s)))
new_strp = strp;
else{
if(strp != NULL)
strsplit_delete(strp);
new_strp = strsplit_init(n, s);
}
strsplit(new_strp, delim, flags);
return(new_strp);
}
void strsplit_delete(struct strsplit_st *strp){
if(strp->sp != NULL){
free(strp->sp);
strp->sp = NULL;
}
if(strp->argv != NULL){
free(strp->argv);
strp->argv = NULL;
}
free(strp);
}
static struct strsplit_st *strsplit_init(int n, char *s){
struct strsplit_st *strp = NULL;
char *sp;
size_t s_size;
char **argv;
s_size = strlen(s);
sp = (char*)malloc(s_size + 1);
if(sp == NULL)
return(NULL);
strncpy(sp, s, s_size + 1);
argv = (char**)calloc(n, sizeof(char*));
if(argv == NULL){
free(sp);
return(NULL);
}
strp = (struct strsplit_st*)malloc(sizeof(struct strsplit_st));
if(strp == NULL){
free(argv);
free(sp);
return(NULL);
}
strp->sp = sp;
strp->argc = n;
strp->argv = argv;
return(strp);
}
static void strsplit(struct strsplit_st *strp, char *delim, int flags){
char *nextp;
char *p;
int n = 0;
nextp = strp->sp;
p = strp->sp;
do {
p = strsep(&nextp, delim);
if((*p != '\0') || (flags == STRSPLIT_FLAG_INCEMPTY))
strp->argv[n++] = p;
} while(nextp != NULL);
assert(strp->argc == n);
}
#if 0
/*
* Test
*/
#include <err.h>
#include <stdio.h>
static void strsplit_print(struct strsplit_st *strp);
static char buffer[128];
static int buffer_size = 128;
int main(int argc, char **argv){
int status = 0;
struct strsplit_st *strp = NULL;
int length;
char *fname;
FILE *f;
if(argc == 1)
errx(1, "Needs argument.");
fname = argv[1];
f = fopen(fname, "r");
if(f == NULL)
errx(1, "fopen");
while(fgets(buffer, buffer_size, f) != NULL){
length = strlen(buffer);
if(buffer[length - 1] == '\n')
buffer[length - 1] = '\0';
strp = strsplit_recreate(buffer, ",", 0, strp);
if(strp == NULL)
err(1, "strplit_create()");
strsplit_print(strp);
/* strsplit_delete(strp); */
}
strsplit_delete(strp);
fclose(f);
return(status);
}
static void strsplit_print(struct strsplit_st *strp){
int i;
for(i = 0; i < strp->argc; ++i)
fprintf(stdout, "%s:", strp->argv[i]);
fprintf(stdout, "\n");
}
#endif
| 2.953125 | 3 |
2024-11-18T22:21:50.873576+00:00 | 2020-08-14T14:03:11 | 1f5940847dd8fecc6384fe8c35da6572425abe7a | {
"blob_id": "1f5940847dd8fecc6384fe8c35da6572425abe7a",
"branch_name": "refs/heads/master",
"committer_date": "2020-08-14T14:03:11",
"content_id": "54999de22858ab9e251b1ff9dcf166233e7a0490",
"detected_licenses": [
"MIT"
],
"directory_id": "00845730e8c3f66af4687a44f93c46295ad91db3",
"extension": "c",
"filename": "code4.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 206923025,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1741,
"license": "MIT",
"license_type": "permissive",
"path": "/lab1/code4.c",
"provenance": "stackv2-0123.json.gz:7750",
"repo_name": "Yangfan-Jiang/High-Performance-Computing-Fall-2019",
"revision_date": "2020-08-14T14:03:11",
"revision_id": "b0292d17cbf1ce93e8df024a53721f94cefa95e4",
"snapshot_id": "57464fb7c5f7df14055da9108b782c0c191c7c0c",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Yangfan-Jiang/High-Performance-Computing-Fall-2019/b0292d17cbf1ce93e8df024a53721f94cefa95e4/lab1/code4.c",
"visit_date": "2022-11-30T11:29:00.250326"
} | stackv2 | #include<stdio.h>
#define MAX 4096
#define RIDX(i, j, dim) ((i)*(dim) + (j))
#define COPY(d, s) *(d) = *(s)
typedef struct{
int red;
int green;
int blue;
}pixel;
void rotate(int dim, pixel *src, pixel *dst)
{
int i, j;
for (i=0; i < dim; i+=32)
for (j=dim-1; j >= 0; j-=1) {
pixel *dptr = dst+RIDX(dim-1-j,i,dim);
pixel *sptr = src+RIDX(i,j,dim);
COPY(dptr , sptr); sptr += dim; COPY(dptr+1 , sptr); sptr += dim;
COPY(dptr+2 , sptr); sptr += dim; COPY(dptr+3 , sptr); sptr += dim;
COPY(dptr+4 , sptr); sptr += dim; COPY(dptr+5 , sptr); sptr += dim;
COPY(dptr+6 , sptr); sptr += dim; COPY(dptr+7 , sptr); sptr += dim;
COPY(dptr+8 , sptr); sptr += dim; COPY(dptr+9 , sptr); sptr += dim;
COPY(dptr+10, sptr); sptr += dim; COPY(dptr+11, sptr); sptr += dim;
COPY(dptr+12, sptr); sptr += dim; COPY(dptr+13, sptr); sptr += dim;
COPY(dptr+14, sptr); sptr += dim; COPY(dptr+15, sptr); sptr += dim;
COPY(dptr+16, sptr); sptr += dim; COPY(dptr+17, sptr); sptr += dim;
COPY(dptr+18, sptr); sptr += dim; COPY(dptr+19, sptr); sptr += dim;
COPY(dptr+20, sptr); sptr += dim; COPY(dptr+21, sptr); sptr += dim;
COPY(dptr+22, sptr); sptr += dim; COPY(dptr+23, sptr); sptr += dim;
COPY(dptr+24, sptr); sptr += dim; COPY(dptr+25, sptr); sptr += dim;
COPY(dptr+26, sptr); sptr += dim; COPY(dptr+27, sptr); sptr += dim;
COPY(dptr+28, sptr); sptr += dim; COPY(dptr+29, sptr); sptr += dim;
COPY(dptr+30, sptr); sptr += dim; COPY(dptr+31, sptr);
}
}
pixel src[MAX*MAX];
pixel dst[MAX*MAX];
int main()
{
int i;
for (i = 0; i < 20; i++)
rotate(MAX, src, dst);
return 0;
} | 3.171875 | 3 |
2024-11-18T22:21:51.114967+00:00 | 2017-07-15T20:15:36 | fb1a576ac9b47ebaef8b2eb1bb54ece29cda63c3 | {
"blob_id": "fb1a576ac9b47ebaef8b2eb1bb54ece29cda63c3",
"branch_name": "refs/heads/master",
"committer_date": "2017-07-15T20:15:36",
"content_id": "67d6db123302b035afc9a60f3c436fc59ebf80e0",
"detected_licenses": [
"MIT"
],
"directory_id": "0f4b65bdd99e642402d489fdd662a7dc1d1441f5",
"extension": "c",
"filename": "test2139.c",
"fork_events_count": 0,
"gha_created_at": "2017-07-15T18:41:20",
"gha_event_created_at": "2017-07-15T18:41:20",
"gha_language": null,
"gha_license_id": null,
"github_id": 97335407,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 805,
"license": "MIT",
"license_type": "permissive",
"path": "/testsuite/EXP_3/test2139.c",
"provenance": "stackv2-0123.json.gz:8141",
"repo_name": "matthiaskrgr/CF3",
"revision_date": "2017-07-15T20:15:36",
"revision_id": "981a49c2b1f0fb80e1d1778beb3f3ce8578338c3",
"snapshot_id": "157e4967f12a6e6a0eee0fa9421f7855d24047c5",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/matthiaskrgr/CF3/981a49c2b1f0fb80e1d1778beb3f3ce8578338c3/testsuite/EXP_3/test2139.c",
"visit_date": "2021-01-01T06:02:05.773732"
} | stackv2 |
/*
CF3
Copyright (c) 2015 ishiura-lab.
Released under the MIT license.
https://github.com/ishiura-compiler/CF3/MIT-LICENSE.md
*/
#include<stdio.h>
#include<stdint.h>
#include<stdlib.h>
#include"test1.h"
volatile int16_t x341 = 228;
void f0(void) {
uint64_t x342 = 1630847354110979LLU;
static volatile int64_t x343 = 10165056727LL;
int16_t x344 = 60;
volatile uint64_t t0 = 1861093797927529278LLU;
t0 = ((x341|x342)>>(x343>>x344));
if (t0 != 1630847354111207LLU) { NG(); } else { ; }
}
void f1(void) {
volatile int32_t x705 = -1;
uint32_t x706 = 26U;
uint32_t x707 = 5211U;
uint8_t x708 = 10U;
uint32_t t1 = 2007U;
t1 = ((x705|x706)>>(x707>>x708));
if (t1 != 134217727U) { NG(); } else { ; }
}
int main(void) {
f0();
f1();
return 0;
}
| 2.09375 | 2 |
2024-11-18T22:21:51.234172+00:00 | 2020-08-23T09:46:12 | 0f22b46765d22c117ab3938f5c06f6501bda77a0 | {
"blob_id": "0f22b46765d22c117ab3938f5c06f6501bda77a0",
"branch_name": "refs/heads/master",
"committer_date": "2020-08-23T09:46:12",
"content_id": "62f3dbeb00630eff4d27e9063333a1638a13b919",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "5a7d1f88e3fbf48588cf823c7901294244b30565",
"extension": "h",
"filename": "nx8bus.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 204151378,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1707,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/nx8bus.h",
"provenance": "stackv2-0123.json.gz:8272",
"repo_name": "HomeACcessoryKid/NX-8-alarm",
"revision_date": "2020-08-23T09:46:12",
"revision_id": "f4152ad6f4851c26791b46ca8df7253e9804725d",
"snapshot_id": "e75d73f3df310907fc6803f33877ae2208e8b673",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/HomeACcessoryKid/NX-8-alarm/f4152ad6f4851c26791b46ca8df7253e9804725d/nx8bus.h",
"visit_date": "2021-07-17T00:59:22.305472"
} | stackv2 | /** (c) 2019-2020 HomeACcessoryKid@gmail.com
* This is a driver for the NX8 bus based on a 4512 bus driver with a fixed address selected and that pin gets 0 V input
* The inhibit pin 15 is connected to a NPN driver with 10k collector to 12V bus power and by a base 180kohm to the tx pin
* The Zoutput pin 14 is connected to the bus dataline. So tx=0 is high-Z and tx=1 is zero out. The bus itself is 12v idle
* The rx pin is reading the bus by a divider of 10k to ground and 33k to the dataline
* Some credit goes to the softuart writers on which this is loosly based
*/
#ifndef NX8BUS_H_
#define NX8BUS_H_
#include <stdint.h>
#include <stdbool.h>
/**
* Calculate the CRC over a character string of len
* @param data character string
* @param len number of bytes in that string
* @return 16bit CRC
*/
uint16_t nx8bus_CRC(const uint8_t * data, int len);
/**
* Initialize nx8 bus and setup interrupt handler
* @param rx_pin GPIO pin number for RX
* @param tx_pin GPIO pin number for TX
* @return true if no errors occured otherwise false
*/
bool nx8bus_open(uint8_t rx_pin, uint8_t tx_pin);
/**
* Put command to nx8bus uart
* @param data 8 bit symbols which create a command plus content, without CRC
* @param len number of symbols without CRC
*/
void nx8bus_command(uint8_t * data, uint8_t len);
/**
* Check if data is available
* @return true if data is available otherwise false
*/
bool nx8bus_available();
/**
* Read current symbol from internal buffer if available.
*
* NOTE: This call is non blocking.
* NOTE: You have to check nx8bus_available() first.
* @return current two byte symbol if available otherwise 0
*/
uint16_t nx8bus_read();
#endif /* NX8BUS_H_ */
| 2.265625 | 2 |
2024-11-18T22:21:52.018829+00:00 | 2020-01-11T13:26:44 | d24ec959278f5fe6429420dc85adecd0b676bd06 | {
"blob_id": "d24ec959278f5fe6429420dc85adecd0b676bd06",
"branch_name": "refs/heads/master",
"committer_date": "2020-01-11T13:26:44",
"content_id": "a9669da1c077745a70a092945370a42971630082",
"detected_licenses": [
"MIT"
],
"directory_id": "e37abb2614594686404090f909ed5979b2e9436b",
"extension": "c",
"filename": "single_gyro.c",
"fork_events_count": 2,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 233233286,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2362,
"license": "MIT",
"license_type": "permissive",
"path": "/components/modules/single_gyro.c",
"provenance": "stackv2-0123.json.gz:8791",
"repo_name": "RMLiChuang/icra2020-firmware",
"revision_date": "2020-01-11T13:26:44",
"revision_id": "4db354cf53e0d999a7682412d9100062898bbf51",
"snapshot_id": "1d51ad8b075faf7b939d1513fd5caea1c83f0c10",
"src_encoding": "UTF-8",
"star_events_count": 4,
"url": "https://raw.githubusercontent.com/RMLiChuang/icra2020-firmware/4db354cf53e0d999a7682412d9100062898bbf51/components/modules/single_gyro.c",
"visit_date": "2020-12-09T07:16:44.156754"
} | stackv2 | /****************************************************************************
* Copyright (C) 2019 RoboMaster.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
***************************************************************************/
#include "single_gyro.h"
#include "errno.h"
gyro_can_send_t gyro_can_send = NULL;
int32_t single_gyro_can_send_register(gyro_can_send_t send) //单轴陀螺仪can发送程序注册
{
if (send != NULL)
{
gyro_can_send = send;
return RM_OK;
}
return -RM_INVAL;
}
int32_t single_gyro_set_stdid(struct single_gyro *gyro, uint32_t std_id)//设置单轴陀螺仪的can id
{
if(gyro == NULL)
{
return -RM_INVAL;
}
gyro->std_id = std_id;
return RM_OK;
}
int32_t single_gyro_update(struct single_gyro *gyro, uint32_t std_id, uint8_t can_rx_data[])//获取单轴陀螺仪的角度与角速度
{
if(gyro == NULL)
{
return -RM_INVAL;
}
if (std_id == gyro->std_id)
{
gyro->yaw_gyro_angle = 0.0001f * ((can_rx_data[0]) |
(can_rx_data[1] << 8));
gyro->yaw_gyro_rate = 0.0001f * ((can_rx_data[2]) |
(can_rx_data[3] << 8));
return RM_OK;
}
return RM_UNREGISTERED;
}
int32_t single_gyro_reset(struct single_gyro *gyro)
{
if(gyro == NULL)
{
return -RM_INVAL;
}
if(gyro_can_send != NULL)
{
uint8_t can_rx_data[8] = {0,1,2,3,4,5,6,7};
gyro_can_send(0x406, can_rx_data);
}
return RM_OK;
}
int32_t single_gyro_adjust(struct single_gyro *gyro)
{
if(gyro == NULL)
{
return -RM_INVAL;
}
if(gyro_can_send != NULL)
{
uint8_t can_rx_data[8] = {0,1,2,3,4,5,6,7};
gyro_can_send(0x408, can_rx_data);
return RM_OK;
}
return RM_UNREGISTERED;
}
| 2.15625 | 2 |
2024-11-18T22:21:52.145980+00:00 | 2021-12-10T01:58:39 | 93dfb1357852de3cba59626496086d37e0840ea3 | {
"blob_id": "93dfb1357852de3cba59626496086d37e0840ea3",
"branch_name": "refs/heads/master",
"committer_date": "2021-12-10T01:58:39",
"content_id": "0e73abde99cadd2cfd4f79605e40180b7df2464d",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "293fc161d5a0442544f5c3a912b26f24a115b28c",
"extension": "c",
"filename": "sql.c",
"fork_events_count": 23,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 218248127,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2860,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/cgi-bin/sql.c",
"provenance": "stackv2-0123.json.gz:9049",
"repo_name": "Ikaros-521/boa_cgi_html_mysql",
"revision_date": "2021-12-10T01:58:39",
"revision_id": "9b6a309ceca109ce802041f45e6f25aa1075d211",
"snapshot_id": "4557a2d73d927a3baca0185dba4bbb47ff35058a",
"src_encoding": "UTF-8",
"star_events_count": 64,
"url": "https://raw.githubusercontent.com/Ikaros-521/boa_cgi_html_mysql/9b6a309ceca109ce802041f45e6f25aa1075d211/cgi-bin/sql.c",
"visit_date": "2021-12-14T22:01:58.868789"
} | stackv2 | #include "sql.h"
#include <iomanip>
SQL::SQL(void)
{
conn = mysql_init(NULL);
if(NULL == conn)
{
printf("errno:%d error:%s\n",mysql_errno(conn),mysql_error(conn));
}
}
SQL::SQL(const char* ip,const char* user,const char* passwd,const char* database,uint16_t port)
{
conn = mysql_init(NULL);
if(NULL == conn)
{
printf("errno:%d error:%s\n",mysql_errno(conn),mysql_error(conn));
return;
}
connect(ip,user,passwd,database,port);
}
SQL::~SQL(void)
{
}
bool SQL::connect(const char* ip,const char* user,const char* passwd,const char* database,uint16_t port)
{
if(NULL == mysql_real_connect(conn,ip,user,passwd,database,port,NULL,0))
{
printf("---errno:%d error:%s\n",mysql_errno(conn),mysql_error(conn));
return false;
}
onAutoCommit();
return true;
}
void SQL::clearResult(void)
{
for(vector<vector<string> >::iterator it = result.begin(); it!=result.end(); it++)
{
it->clear();
}
result.clear();
}
void SQL::showResult(void)
{
for(vector<vector<string> >::iterator i = result.begin(); i!=result.end(); i++)
{
for(vector<string>::iterator j=i->begin(); j!=i->end(); j++)
{
cout << setw(12) << *j << " ";
}
cout << endl;
}
}
int SQL::insert(const char* cmd)
{
if(mysql_query(conn,cmd) != 0)
{
printf("errno:%d error:%s\n",mysql_errno(conn),mysql_error(conn));
return -1;
}
return mysql_affected_rows(conn);
}
int SQL::remove(const char* cmd)
{
if(mysql_query(conn,cmd) != 0)
{
printf("errno:%d error:%s\n",mysql_errno(conn),mysql_error(conn));
return -1;
}
return mysql_affected_rows(conn);
}
int SQL::update(const char* cmd)
{
if(mysql_query(conn,cmd) != 0)
{
printf("errno:%d error:%s\n",mysql_errno(conn),mysql_error(conn));
return -1;
}
return mysql_affected_rows(conn);
}
int SQL::select(const char* cmd)
{
MYSQL_RES *res;
MYSQL_ROW row;
if(mysql_query(conn,cmd) != 0)
{
printf("errno:%d error:%s\n",mysql_errno(conn),mysql_error(conn));
return -1;
}
int num_fields = mysql_field_count(conn);
if(num_fields == 0)
{
printf("errno:%d error:%s\n",mysql_errno(conn),mysql_error(conn));
return -1;
}
res = mysql_store_result(conn);
if(NULL == res)
{
printf("errno:%d error:%s\n",mysql_errno(conn),mysql_error(conn));
return -1;
}
clearResult();
int count = 0;
while((row = mysql_fetch_row(res)))
{
vector<string> arr;
for(int i=0; i<num_fields; i++)
{
string str(row[i]);
arr.push_back(str);
}
result.push_back(arr);
count++;
}
mysql_free_result(res);
return count;
}
bool SQL::offAutoCommit(void)
{
isAutoCommit = false;
return mysql_autocommit(conn,isAutoCommit);
}
bool SQL::onAutoCommit(void)
{
isAutoCommit = true;
return mysql_autocommit(conn,isAutoCommit);
}
bool SQL::getAutoCommit(void)
{
return isAutoCommit;
}
| 2.421875 | 2 |
2024-11-18T22:21:52.225312+00:00 | 2022-11-27T05:56:58 | d5a589849527db4c13ef0a44aef616176461a037 | {
"blob_id": "d5a589849527db4c13ef0a44aef616176461a037",
"branch_name": "refs/heads/master",
"committer_date": "2022-11-27T05:56:58",
"content_id": "dcf6074e9d33bcf2ad8fe11b9e1871bf966d685f",
"detected_licenses": [
"MIT"
],
"directory_id": "99153e5653a3e46548abc2763a6ffcfec2f3d65c",
"extension": "c",
"filename": "randu01s.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 34908369,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 525,
"license": "MIT",
"license_type": "permissive",
"path": "/CLAH/Chap13/randu01s.c",
"provenance": "stackv2-0123.json.gz:9179",
"repo_name": "jiangxincode/CppTest",
"revision_date": "2022-11-27T05:56:58",
"revision_id": "69c4269c2f089abf820e783cf136c5814aa4a605",
"snapshot_id": "3f7cc70341ce458e2a559b6e0b92d5dc4b8dc39c",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/jiangxincode/CppTest/69c4269c2f089abf820e783cf136c5814aa4a605/CLAH/Chap13/randu01s.c",
"visit_date": "2022-11-30T22:49:38.251580"
} | stackv2 | #include "../utility.h"
/**
* 函数名:randu01s
* 功能描述:生成(0,1)区间的均匀分布的随机序列
* 输入参数:L(生成随机序列的长度) u_ran(指向生成随机数序列的指针)
* 返回值:1:成功生成。0:生成失败。
*/
int randu01s(int L,double *u_ran)
{
int i;
srand((unsigned)time(0)); /* 用系统时钟做种子*/
for(i=0; i<L; i++)
{
u_ran[i]=rand()/(double)RAND_MAX; /* 生成(0,1)随机数,L次 */
}
return 1;
}
| 2.84375 | 3 |
2024-11-18T22:21:52.286349+00:00 | 2018-11-07T22:19:39 | 4a0dd2a11bf7dc41cee6b26465832e46b1c28784 | {
"blob_id": "4a0dd2a11bf7dc41cee6b26465832e46b1c28784",
"branch_name": "refs/heads/master",
"committer_date": "2018-11-07T22:19:39",
"content_id": "47a16abdecd8ca2c5594f61e125077345d11fec7",
"detected_licenses": [
"MIT"
],
"directory_id": "6e1f27a2a16d926451fdab3b3b786c1962b2fd5a",
"extension": "c",
"filename": "grayscale.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 156588893,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1335,
"license": "MIT",
"license_type": "permissive",
"path": "/arm-grayscale/cfopen/grayscale.c",
"provenance": "stackv2-0123.json.gz:9309",
"repo_name": "alanxoc3/undergrad",
"revision_date": "2018-11-07T22:19:39",
"revision_id": "3efe61f007c6bc35a9ea3a0d0d151d4e7ee56405",
"snapshot_id": "16d134ccb3a9ed5c6a641a595f1885c8d8c2f282",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/alanxoc3/undergrad/3efe61f007c6bc35a9ea3a0d0d151d4e7ee56405/arm-grayscale/cfopen/grayscale.c",
"visit_date": "2020-04-05T05:17:40.967577"
} | stackv2 | #include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#define PIX_OFF_BIT_OFF 10L
int main(int argc, char ** argv) {
FILE *img = fopen("img.bmp", "r+");
fseek(img, 0L, SEEK_END); // Get the length of the
int fileLen = ftell(img); // file in bytes.
unsigned int pixelDataOffset = 0;
fseek(img, PIX_OFF_BIT_OFF, SEEK_SET); // Reset to where the offset is.
fread(&pixelDataOffset, sizeof(unsigned int), 1, img);
fseek(img, pixelDataOffset, SEEK_SET); // Reset to where the offset is.
unsigned int pix_len = fileLen - pixelDataOffset;
unsigned char* fileMem = malloc(pix_len); // Allocate the pixels.
fread(fileMem, 1, pix_len, img);
int i;
for (i = 0; i < pix_len; i += 3) {
int average = (fileMem[i] + fileMem[i+1] + fileMem[i+2]) / 3;
fileMem[i] = (unsigned char) average;
fileMem[i+1] = (unsigned char) average;
fileMem[i+2] = (unsigned char) average;
//if (i % (3 * 3 * 3) == 0)
//printf("AVERAGE: %u, %u, %u\n", fileMem[i],
//fileMem[i+1],
//fileMem[i+2]);
}
fseek(img, pixelDataOffset, SEEK_SET); // Reset to where the offset is.
fwrite(fileMem, 1, pix_len, img);
printf("Pixel Data Offset = %u\n", pixelDataOffset);
printf("FILE LEN IN BYTES = %d\n", fileLen);
printf("PIX LEN IN BYTES = %d\n", pix_len);
fclose(img);
free(fileMem);
return 0;
}
| 3.125 | 3 |
2024-11-18T22:21:52.745244+00:00 | 2019-06-11T19:40:39 | e3fa546567607ca359161d7602936a9987a61ef1 | {
"blob_id": "e3fa546567607ca359161d7602936a9987a61ef1",
"branch_name": "refs/heads/master",
"committer_date": "2019-06-11T19:40:39",
"content_id": "592d6540f88929c7b1f6235a048fab1ddaa77df4",
"detected_licenses": [
"MIT"
],
"directory_id": "356327b6fbade3b02bb859a595db7c134b1e8d5c",
"extension": "c",
"filename": "mp.c",
"fork_events_count": 0,
"gha_created_at": "2019-06-11T19:19:19",
"gha_event_created_at": "2022-11-22T03:14:54",
"gha_language": "C++",
"gha_license_id": "MIT",
"github_id": 191435675,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2457,
"license": "MIT",
"license_type": "permissive",
"path": "/c8005/a1/src/mp.c",
"provenance": "stackv2-0123.json.gz:9568",
"repo_name": "DimitryRakhlei/BTECH",
"revision_date": "2019-06-11T19:40:39",
"revision_id": "fefe469bd7d1f4adbc70bdc57670e793ad4c31f6",
"snapshot_id": "8f6055ca298dcc9a8d53f6cf710c63e79e882e53",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/DimitryRakhlei/BTECH/fefe469bd7d1f4adbc70bdc57670e793ad4c31f6/c8005/a1/src/mp.c",
"visit_date": "2022-12-07T23:24:40.314343"
} | stackv2 | /*
*
=====================================================================================
*
* Filename: mp.c
*
* Description: A program which uses 4 processes to decompose 4 individual
numbers into prime multiples. Works in parallel.
*
* Version: 1.0
* Created: 01/22/2018 01:03:15 AM
* Revision: none
* Compiler: gcc
*
* Author: Dimitry Rakhlei
* Organization:
*
*
=====================================================================================
*/
#include "primedecompose.h"
#include <fcntl.h>
#include <gmp.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#define MAX_FACTORS 1024
// Globals
mpz_t dest[MAX_FACTORS]; // must be large enough to hold all the factors!
int main(int argc, char **argv) {
mpz_t n;
int i = 0, l = 0;
int childpid = -1;
clock_t start, end;
time_t t = time(NULL);
struct tm tm = *localtime(&t);
int timelog = 0;
if (argc == 6) {
if (strcmp(argv[5], "t") == 0) {
timelog = 1;
}
} else if (argc != 5) {
puts("Usage: ./pdec <number to be factored>");
return EXIT_SUCCESS;
}
if (timelog == 0) {
printf("\n\nStarting Test: %d-%d-%d %d:%d:%d\n", tm.tm_year + 1900,
tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
fflush(stdout);
}
int type = 0;
for (type = 1; type < 5; type++)
if ((childpid = fork()) <= 0)
break;
start = clock();
if (type == 1) {
mpz_init_set_str(n, argv[type], 10);
l = decompose(n, dest);
} else if (type == 2) {
mpz_init_set_str(n, argv[type], 10);
l = decompose(n, dest);
} else if (type == 3) {
mpz_init_set_str(n, argv[type], 10);
l = decompose(n, dest);
} else if (type == 4) {
mpz_init_set_str(n, argv[type], 10);
l = decompose(n, dest);
} else {
return EXIT_FAILURE;
}
end = clock();
double time_spent = (double)(end - start) / CLOCKS_PER_SEC;
if (timelog == 0) {
printf("\nThe Proc[%d] took %f seconds to execute.\n", type,
time_spent);
for (i = 0; i < l; i++) {
gmp_printf("%s%Zd", i ? " * " : "", dest[i]);
mpz_clear(dest[i]);
}
printf("\n");
}else {
printf("%f\n", time_spent);
}
return EXIT_SUCCESS;
}
| 2.828125 | 3 |
2024-11-18T22:21:56.135074+00:00 | 2023-08-31T21:49:30 | 7a15ce23e42dd36b33d25273d7f6d2e972037c7b | {
"blob_id": "7a15ce23e42dd36b33d25273d7f6d2e972037c7b",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-31T21:49:30",
"content_id": "5ad8a4e0847019da0d738d6ccf3d862c1ef79979",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "38fff7bdefd8d62a740d51329b50d0e1e49258bb",
"extension": "c",
"filename": "libyaml_dumper_fuzzer.c",
"fork_events_count": 2315,
"gha_created_at": "2016-07-20T19:39:50",
"gha_event_created_at": "2023-09-14T20:32:19",
"gha_language": "Shell",
"gha_license_id": "Apache-2.0",
"github_id": 63809205,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 9040,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/projects/libyaml/libyaml_dumper_fuzzer.c",
"provenance": "stackv2-0123.json.gz:9957",
"repo_name": "google/oss-fuzz",
"revision_date": "2023-08-31T21:49:30",
"revision_id": "f0275421f84b8f80ee767fb9230134ac97cb687b",
"snapshot_id": "026384c2ada61ef68b147548e830f60730c5e738",
"src_encoding": "UTF-8",
"star_events_count": 9438,
"url": "https://raw.githubusercontent.com/google/oss-fuzz/f0275421f84b8f80ee767fb9230134ac97cb687b/projects/libyaml/libyaml_dumper_fuzzer.c",
"visit_date": "2023-08-31T23:30:28.157702"
} | stackv2 | // Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "yaml.h"
#include "yaml_write_handler.h"
#include <assert.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef NDEBUG
#undef NDEBUG
#endif
#define MAX_DOCUMENTS 16
bool nodes_equal(yaml_document_t *document1, int index1,
yaml_document_t *document2, int index2, int level) {
const bool equal = true;
if (level++ > 1000)
return !equal;
yaml_node_t *node1 = yaml_document_get_node(document1, index1);
if (!node1)
return !equal;
yaml_node_t *node2 = yaml_document_get_node(document2, index2);
if (!node2)
return !equal;
if (node1->type != node2->type)
return !equal;
if (strcmp((char *)node1->tag, (char *)node2->tag) != 0)
return !equal;
switch (node1->type) {
case YAML_SCALAR_NODE:
if (node1->data.scalar.length != node2->data.scalar.length)
return !equal;
if (strncmp((char *)node1->data.scalar.value,
(char *)node2->data.scalar.value,
node1->data.scalar.length) != 0)
return !equal;
break;
case YAML_SEQUENCE_NODE:
if ((node1->data.sequence.items.top - node1->data.sequence.items.start) !=
(node2->data.sequence.items.top - node2->data.sequence.items.start))
return !equal;
for (int k = 0; k < (node1->data.sequence.items.top -
node1->data.sequence.items.start);
k++) {
if (!nodes_equal(document1, node1->data.sequence.items.start[k],
document2, node2->data.sequence.items.start[k], level))
return !equal;
}
break;
case YAML_MAPPING_NODE:
if ((node1->data.mapping.pairs.top - node1->data.mapping.pairs.start) !=
(node2->data.mapping.pairs.top - node2->data.mapping.pairs.start))
return !equal;
for (int k = 0;
k < (node1->data.mapping.pairs.top - node1->data.mapping.pairs.start);
k++) {
if (!nodes_equal(document1, node1->data.mapping.pairs.start[k].key,
document2, node2->data.mapping.pairs.start[k].key,
level))
return !equal;
if (!nodes_equal(document1, node1->data.mapping.pairs.start[k].value,
document2, node2->data.mapping.pairs.start[k].value,
level))
return !equal;
}
break;
default:
return !equal;
}
return equal;
}
bool documents_equal(yaml_document_t *document1, yaml_document_t *document2) {
const bool equal = true;
if ((document1->version_directive && !document2->version_directive) ||
(!document1->version_directive && document2->version_directive) ||
(document1->version_directive && document2->version_directive &&
(document1->version_directive->major !=
document2->version_directive->major ||
document1->version_directive->minor !=
document2->version_directive->minor)))
return !equal;
if ((document1->tag_directives.end - document1->tag_directives.start) !=
(document2->tag_directives.end - document2->tag_directives.start))
return !equal;
for (int k = 0;
k < (document1->tag_directives.end - document1->tag_directives.start);
k++) {
if ((strcmp((char *)document1->tag_directives.start[k].handle,
(char *)document2->tag_directives.start[k].handle) != 0) ||
(strcmp((char *)document1->tag_directives.start[k].prefix,
(char *)document2->tag_directives.start[k].prefix) != 0))
return !equal;
}
if ((document1->nodes.top - document1->nodes.start) !=
(document2->nodes.top - document2->nodes.start))
return !equal;
if (document1->nodes.top != document1->nodes.start) {
if (!nodes_equal(document1, 1, document2, 1, 0))
return !equal;
}
return equal;
}
bool copy_document(yaml_document_t *document_to,
yaml_document_t *document_from) {
bool error = true;
yaml_node_t *node;
yaml_node_item_t *item;
yaml_node_pair_t *pair;
if (!yaml_document_initialize(document_to, document_from->version_directive,
document_from->tag_directives.start,
document_from->tag_directives.end,
document_from->start_implicit,
document_from->end_implicit))
return !error;
for (node = document_from->nodes.start; node < document_from->nodes.top;
node++) {
switch (node->type) {
case YAML_SCALAR_NODE:
if (!yaml_document_add_scalar(
document_to, node->tag, node->data.scalar.value,
node->data.scalar.length, node->data.scalar.style))
goto out;
break;
case YAML_SEQUENCE_NODE:
if (!yaml_document_add_sequence(document_to, node->tag,
node->data.sequence.style))
goto out;
break;
case YAML_MAPPING_NODE:
if (!yaml_document_add_mapping(document_to, node->tag,
node->data.mapping.style))
goto out;
break;
default:
goto out;
}
}
for (node = document_from->nodes.start; node < document_from->nodes.top;
node++) {
switch (node->type) {
case YAML_SEQUENCE_NODE:
for (item = node->data.sequence.items.start;
item < node->data.sequence.items.top; item++) {
if (!yaml_document_append_sequence_item(
document_to, node - document_from->nodes.start + 1, *item))
goto out;
}
break;
case YAML_MAPPING_NODE:
for (pair = node->data.mapping.pairs.start;
pair < node->data.mapping.pairs.top; pair++) {
if (!yaml_document_append_mapping_pair(
document_to, node - document_from->nodes.start + 1, pair->key,
pair->value))
goto out;
}
break;
default:
break;
}
}
return error;
out:
yaml_document_delete(document_to);
return !error;
}
int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
if (size < 2)
return 0;
yaml_parser_t parser;
yaml_emitter_t emitter;
yaml_document_t document;
yaml_document_t documents[MAX_DOCUMENTS];
size_t document_number = 0;
int count = 0;
bool done = false;
bool equal = false;
bool is_canonical = data[0] & 1;
bool is_unicode = data[1] & 1;
data += 2;
size -= 2;
if (!yaml_parser_initialize(&parser))
return 0;
yaml_parser_set_input_string(&parser, data, size);
if (!yaml_emitter_initialize(&emitter))
return 0;
yaml_emitter_set_canonical(&emitter, is_canonical);
yaml_emitter_set_unicode(&emitter, is_unicode);
yaml_output_buffer_t out = {/*buf=*/NULL, /*size=*/0};
yaml_emitter_set_output(&emitter, yaml_write_handler, &out);
yaml_emitter_open(&emitter);
while (!done) {
if (!yaml_parser_load(&parser, &document)) {
equal = 1;
break;
}
done = (!yaml_document_get_root_node(&document));
if (!done) {
if (document_number >= MAX_DOCUMENTS) {
yaml_document_delete(&document);
equal = true;
break;
}
if (!copy_document(&documents[document_number++], &document)) {
yaml_document_delete(&document);
equal = true;
break;
}
if (!(yaml_emitter_dump(&emitter, &document) ||
(yaml_emitter_flush(&emitter) && 0))) {
equal = true;
break;
}
count++;
} else {
yaml_document_delete(&document);
}
}
yaml_parser_delete(&parser);
yaml_emitter_close(&emitter);
yaml_emitter_delete(&emitter);
if (!equal) {
count = 0;
done = false;
if (!yaml_parser_initialize(&parser))
goto error;
if (!out.buf) {
yaml_parser_delete(&parser);
goto error;
}
yaml_parser_set_input_string(&parser, out.buf, out.size);
while (!done) {
if (!yaml_parser_load(&parser, &document)) {
yaml_parser_delete(&parser);
goto error;
}
done = (!yaml_document_get_root_node(&document));
if (!done) {
if (!documents_equal(documents + count, &document)) {
yaml_parser_delete(&parser);
goto error;
}
count++;
}
yaml_document_delete(&document);
}
yaml_parser_delete(&parser);
}
for (int k = 0; k < document_number; k++) {
yaml_document_delete(documents + k);
}
error:
free(out.buf);
return 0;
}
| 2.046875 | 2 |
2024-11-18T22:21:56.404358+00:00 | 2019-11-29T13:27:11 | c74528f45259580ad933708923a52687ab124108 | {
"blob_id": "c74528f45259580ad933708923a52687ab124108",
"branch_name": "refs/heads/master",
"committer_date": "2019-11-29T13:27:11",
"content_id": "71698931279c3333bbe9463ae787268c8aa9b483",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "0b156327cb5db82797c551d4ea8501041107cb3d",
"extension": "c",
"filename": "ict2104_camera.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 213279901,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 7872,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/esp32-ai-thinker/components/src/ict2104_camera.c",
"provenance": "stackv2-0123.json.gz:10344",
"repo_name": "DtCarrot/ICT2104",
"revision_date": "2019-11-29T13:27:11",
"revision_id": "bf8677653bae8da0b77a1d90dc8d3b10c57e5044",
"snapshot_id": "e3f8b87c14bf02dd0f13843d29f22bbda1ce86d1",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/DtCarrot/ICT2104/bf8677653bae8da0b77a1d90dc8d3b10c57e5044/esp32-ai-thinker/components/src/ict2104_camera.c",
"visit_date": "2022-03-14T23:50:00.182433"
} | stackv2 | /*
* ict2104_camera.c
*
* Source file used to implement the methods
* required for initializing the camera,
* starting the image capture and sending image
* data to ESP32-CAM
*
*
*
*/
#include <esp_log.h>
#include <esp_wifi.h>
#include <esp_http_server.h>
#include "esp_http_client.h"
#include "esp_tls.h"
#include "ict2104_camera.h"
#include "ict2104_nvs.h"
#include "mbedtls/base64.h"
/*
*
* Define camera pin used for ESP32-CAM
*
*
*/
#define CAM_PIN_PWDN 32
#define CAM_PIN_RESET -1
#define CAM_PIN_XCLK 0
#define CAM_PIN_SIOD 26
#define CAM_PIN_SIOC 27
#define CAM_PIN_D7 35
#define CAM_PIN_D6 34
#define CAM_PIN_D5 39
#define CAM_PIN_D4 36
#define CAM_PIN_D3 21
#define CAM_PIN_D2 19
#define CAM_PIN_D1 18
#define CAM_PIN_D0 5
#define CAM_PIN_VSYNC 25
#define CAM_PIN_HREF 23
#define CAM_PIN_PCLK 22
static const char *TAG = "camera";
int img_quality;
int count = 0;
uint8_t camera_activated = 0;
typedef struct {
httpd_req_t *req;
size_t len;
} jpg_chunking_t;
/*
*
* Handle HTTP event
*
* Currently used for debugging
*
*/
esp_err_t _http_event_handler(esp_http_client_event_t *evt) {
switch(evt->event_id) {
case HTTP_EVENT_ERROR:
ESP_LOGD(TAG, "HTTP_EVENT_ERROR");
break;
case HTTP_EVENT_ON_CONNECTED:
ESP_LOGD(TAG, "HTTP_EVENT_ON_CONNECTED");
break;
case HTTP_EVENT_HEADER_SENT:
ESP_LOGD(TAG, "HTTP_EVENT_HEADER_SENT");
break;
case HTTP_EVENT_ON_HEADER:
ESP_LOGD(TAG, "HTTP_EVENT_ON_HEADER, key=%s, value=%s", evt->header_key, evt->header_value);
break;
case HTTP_EVENT_ON_DATA:
ESP_LOGD(TAG, "HTTP_EVENT_ON_DATA, len=%d", evt->data_len);
if (!esp_http_client_is_chunked_response(evt->client)) {
// Write out data
printf("%.*s", evt->data_len, (char*)evt->data);
}
break;
case HTTP_EVENT_ON_FINISH:
ESP_LOGD(TAG, "HTTP_EVENT_ON_FINISH");
break;
case HTTP_EVENT_DISCONNECTED:
ESP_LOGI(TAG, "HTTP_EVENT_DISCONNECTED");
int mbedtls_err = 0;
esp_err_t err = esp_tls_get_and_clear_last_error(evt->data, &mbedtls_err, NULL);
if (err != 0) {
ESP_LOGI(TAG, "Last esp error code: 0x%x", err);
ESP_LOGI(TAG, "Last mbedtls failure: 0x%x", mbedtls_err);
}
break;
}
return ESP_OK;
}
/*
* Main method used to initialize the camera pins,
* configuring the camera settings
* and checking if camera successfully initialized
*
* @returns esp_err_t if the camera failed to initialize
*
*/
esp_err_t main_camera_init() {
img_quality = (int) get_image_quality();
// Define the camera configuration
// pins and image quality
static camera_config_t camera_config = {
.pin_pwdn = CAM_PIN_PWDN,
.pin_reset = CAM_PIN_RESET,
.pin_xclk = CAM_PIN_XCLK,
.pin_sscb_sda = CAM_PIN_SIOD,
.pin_sscb_scl = CAM_PIN_SIOC,
.pin_d7 = CAM_PIN_D7,
.pin_d6 = CAM_PIN_D6,
.pin_d5 = CAM_PIN_D5,
.pin_d4 = CAM_PIN_D4,
.pin_d3 = CAM_PIN_D3,
.pin_d2 = CAM_PIN_D2,
.pin_d1 = CAM_PIN_D1,
.pin_d0 = CAM_PIN_D0,
.pin_vsync = CAM_PIN_VSYNC,
.pin_href = CAM_PIN_HREF,
.pin_pclk = CAM_PIN_PCLK,
.xclk_freq_hz = 20000000,
.ledc_timer = LEDC_TIMER_0,
.ledc_channel = LEDC_CHANNEL_0,
.pixel_format = PIXFORMAT_JPEG,//YUV422,GRAYSCALE,RGB565,JPEG
.frame_size = FRAMESIZE_SVGA,//QQVGA-QXGA Do not use sizes above QVGA when not JPEG
.jpeg_quality = 12, //0-63 lower number means higher quality
.fb_count = 1 //if more than one, i2s runs in continuous mode. Use only with JPEG
};
// if the img quality flag is 0,
// we use SVGA frame size
if(img_quality == 0) {
camera_config.frame_size = FRAMESIZE_SVGA;
} else {
// if the img quality flag is 0,
// we use VGA frame size which is lower resolution
// than FRAMESIZE_SVGA
camera_config.frame_size = FRAMESIZE_VGA;
}
ESP_LOGD(TAG, "Starting camera");
// Initialize the camera with configuration
esp_err_t err = esp_camera_init(&camera_config);
// Check if camera was initialized successfully
if (err != ESP_OK)
{
ESP_LOGE(TAG, "Camera Init Failed");
return err;
}
// set flag to indicate that camera is active
toggle_camera_status(1);
return ESP_OK;
}
/*
* Method used to reset the camera.
* Currently, it will be called after clicking
* the change image quality in UI
*
* @TODO: To be refactored to split up logic to reset camera
* and changing of image quality.
*
*
*/
void reset_camera() {
// Get the current image quality
uint8_t new_image_quality = get_image_quality();
// Configure the image quality
if(new_image_quality == 0) {
new_image_quality++;
} else {
new_image_quality = 0;
}
// Update the image quality setting in nvs storage
set_image_quality(new_image_quality);
// Toggle the camera status to 0
toggle_camera_status(0);
// Deinitialize ESP-32 camera
ESP_ERROR_CHECK(esp_camera_deinit());
// Reinitialize the ESP-32 Camera
ESP_ERROR_CHECK(main_camera_init());
}
/*
* Method to start the process of capturing image
* frame
*
* Note: main_camera_init() must be called first
*
*
*/
esp_err_t start_capture() {
// Continuously capture photo frame
while(1) {
camera_fb_t *fb = NULL;
esp_err_t res = ESP_OK;
size_t fb_len = 0;
int64_t fr_start = esp_timer_get_time();
// If the camera is inactive,
// we sleep and wait for 2000ms
if(get_camera_status() == 0) {
ESP_LOGI("Camera", "Camera undefined");
// Delay by 2000ms before next request
vTaskDelay(2000 / portTICK_PERIOD_MS);
continue;
}
// Get the frame buffer from the ESP32 Camera
fb = esp_camera_fb_get();
// Check if the camera capture have been successful
if (!fb)
{
ESP_LOGE(TAG, "Camera capture failed");
// Might want to trigger mqtt to send an error message when capturing video frame
return ESP_FAIL;
}
// Prepare the POST request to upload the frame buffer data
// using HTTP.
// Sends to the <remote ip>/upload with the buffer data
esp_http_client_config_t config = {
.url = "http://httpbin.org/get",
.event_handler = _http_event_handler,
};
esp_http_client_handle_t client = esp_http_client_init(&config);
// Set remote URL
esp_http_client_set_url(client, "http://192.168.43.210:8000/upload");
// Set HTTP method -> Set post in our case
esp_http_client_set_method(client, HTTP_METHOD_POST);
// Set the post data which is the buffer data together with the buffer length
esp_http_client_set_post_field(client, (const char *)fb->buf, fb->len);
ESP_LOGI(TAG, "Size: %d", fb->len);
// Set header content type
esp_http_client_set_header(client, "Content-Type", "image/jpg");
esp_err_t err = NULL;
// Execute HTTP POST Request
err = esp_http_client_perform(client);
// Check whether there is any error in invoking http request.
if (err == ESP_OK) {
// Get http status code and length
ESP_LOGI(TAG, "HTTP POST Status = %d, content_length = %d",
esp_http_client_get_status_code(client),
esp_http_client_get_content_length(client));
} else {
ESP_LOGE(TAG, "HTTP POST request failed: %s", esp_err_to_name(err));
}
// Clean up after sending each http message
esp_http_client_cleanup(client);
// Delay by 2000ms before next request
vTaskDelay(2000 / portTICK_PERIOD_MS);
}
return ESP_OK;
}
/*
*
* Getter / Setter method used to get the current camera status
*
*
*/
void toggle_camera_status(uint8_t status) {
camera_activated = status;
}
uint8_t get_camera_status() {
return camera_activated;
}
| 2.375 | 2 |
2024-11-18T22:21:56.485563+00:00 | 2015-04-18T00:50:59 | 5eea7b51d230d14b279ef434a7f2251397b2aed0 | {
"blob_id": "5eea7b51d230d14b279ef434a7f2251397b2aed0",
"branch_name": "refs/heads/master",
"committer_date": "2015-04-18T00:50:59",
"content_id": "371136b49a0fc48db06224b91c706cc62618c9b7",
"detected_licenses": [
"MIT"
],
"directory_id": "826d8ccc945757d497e055352769fc0845c97c77",
"extension": "c",
"filename": "parse.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 7174,
"license": "MIT",
"license_type": "permissive",
"path": "/src/parse.c",
"provenance": "stackv2-0123.json.gz:10472",
"repo_name": "deritchie/Fexl",
"revision_date": "2015-04-18T00:50:59",
"revision_id": "8c60df1b2ea5a57e5caa095494a511cc0307ed00",
"snapshot_id": "ea55913339baa5414c24d70e1bfa34f0ab0aaae8",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/deritchie/Fexl/8c60df1b2ea5a57e5caa095494a511cc0307ed00/src/parse.c",
"visit_date": "2021-01-18T00:19:18.003749"
} | stackv2 | #include <str.h>
#include <value.h>
#include <basic.h>
#include <buffer.h>
#include <ctype.h>
#include <die.h>
#include <input.h>
#include <output.h>
#include <parse.h>
#include <source.h>
#include <type_str.h>
#include <type_sym.h>
/*
Grammar:
[
exp => empty
exp => term exp
exp => ; exp
exp => \ sym exp
exp => \ sym = term exp
exp => \ sym == term exp
exp => \ = term exp
term => ( exp )
term => [ list ]
term => { tuple }
term => sym
list => empty
list => term list
list => ; exp
tuple => empty
tuple => term tuple
sym => name
sym => string
string => quote_string
string => tilde_string
]
The Fexl parser reads an expression from the input until it reaches -1 (end of
file) or the special token "\\". The \\ token stops the parser immediately, as
if it had reached end of file.
*/
static int ch; /* current character */
static unsigned long source_line; /* current line number */
static void syntax_error(const char *code, unsigned long line)
{
put_to_error();
put(code); put_error_location(line);
die(0);
}
static void skip(void)
{
ch = getd();
if (ch == '\n')
source_line++;
}
static void skip_line(void)
{
while (1)
{
if (ch == '\n' || ch == -1)
{
skip();
return;
}
else
skip();
}
}
static int at_white(void)
{
return isspace(ch) || ch == 0;
}
static void skip_white(void)
{
while (1)
{
if (!at_white() || ch == -1)
return;
else
skip();
}
}
static void skip_filler(void)
{
while (1)
{
if (ch == '#')
skip_line();
else if (at_white())
skip_white();
else
return;
}
}
/* Parse a name, or return 0 if we don't see one.
A name may contain just about anything, except for white space (including NUL)
and a few other special characters. This is the simplest rule that can work.
*/
static value parse_name(void)
{
buffer buf = 0;
unsigned long first_line = source_line;
while (1)
{
if (at_white()
|| ch == '\\'
|| ch == '(' || ch == ')'
|| ch == '[' || ch == ']'
|| ch == '{' || ch == '}'
|| ch == ';'
|| ch == '"'
|| ch == '~'
|| ch == '#'
|| ch == '='
|| ch == -1)
break;
buf = buf_add(buf,(char)ch);
skip();
}
if (!buf) return 0;
return Qsym(buf_finish(buf), first_line);
}
/* Collect a string up to an ending terminator. */
static string collect_string(
const char *end_data,
unsigned long end_len,
unsigned long first_line
)
{
unsigned long match_pos = 0;
buffer buf = 0;
while (match_pos < end_len)
{
if (ch == end_data[match_pos])
{
match_pos++;
skip();
}
else if (match_pos > 0)
{
/* Buffer the ones matched so far and start over. */
unsigned long i;
for (i = 0; i < match_pos; i++)
buf = buf_add(buf, end_data[i]);
match_pos = 0;
}
else if (ch == -1)
syntax_error("Unclosed string", first_line);
else
{
buf = buf_add(buf,(char)ch);
skip();
}
}
return buf_finish(buf);
}
static value parse_quote_string(void)
{
unsigned long first_line = source_line;
skip();
return Qstr(collect_string("\"",1,first_line));
}
static value parse_tilde_string(void)
{
buffer buf = 0;
unsigned long first_line = source_line;
while (1)
{
if (ch == -1 || isspace(ch))
break;
buf = buf_add(buf,(char)ch);
skip();
}
if (ch == -1 || buf == 0)
syntax_error("Incomplete string terminator", first_line);
skip();
{
string end = buf_finish(buf);
string content = collect_string(end->data, end->len, first_line);
str_free(end);
return Qstr(content);
}
}
static value parse_symbol(void)
{
if (ch == '"')
return parse_quote_string();
else if (ch == '~')
return parse_tilde_string();
else
return parse_name();
}
static value parse_term(void);
static value parse_exp(void);
static value parse_list(void)
{
value term;
skip_filler();
if (ch == ';')
{
skip();
return parse_exp();
}
term = parse_term();
if (term == 0) return hold(null);
return app(app(hold(cons),term),parse_list());
}
static value parse_tuple(void)
{
value pattern = hold(I);
value exp = hold(I);
while (1)
{
value term;
skip_filler();
term = parse_term();
if (term == 0) break;
pattern = A(pattern,hold(C));
exp = app(exp,term);
}
return Qsubst(pattern,exp);
}
static value parse_term(void)
{
value exp;
unsigned long first_line = source_line;
if (ch == '(') /* parenthesized expression */
{
skip();
exp = parse_exp();
if (ch != ')')
syntax_error("Unclosed parenthesis", first_line);
skip();
}
else if (ch == '[') /* list */
{
skip();
exp = parse_list();
if (ch != ']')
syntax_error("Unclosed bracket", first_line);
skip();
}
else if (ch == '{') /* tuple */
{
skip();
exp = parse_tuple();
if (ch != '}')
syntax_error("Unclosed brace", first_line);
skip();
}
else
exp = parse_symbol();
return exp;
}
/* Parse a lambda form following the initial '\' character. */
static value parse_lambda(unsigned long first_line)
{
value sym, def=0, exp;
char is_recursive = 0;
/* Parse the symbol (function parameter). */
skip_white();
if (ch == '=')
{
/* Resolve expression in a context. */
value context, label;
skip();
skip_white();
context = parse_term();
if (context == 0)
syntax_error("Missing context", first_line);
exp = parse_exp();
label = Qstr(str_new_data0(source_label ? source_label : ""));
return app(A(A(Q(type_resolve),label),exp),context);
}
sym = parse_name();
if (sym == 0)
syntax_error("Missing symbol after '\\'", first_line);
skip_filler();
first_line = source_line;
/* Parse the definition of the symbol if we see an '=' char. */
if (ch == '=')
{
skip();
if (ch == '=')
{
is_recursive = 1;
skip();
}
skip_filler();
def = parse_term();
if (def == 0)
syntax_error("Missing definition", first_line);
}
if (is_recursive)
def = app(hold(Y),lam(hold(sym),def));
/* Parse the body of the function and apply the definition if any. */
exp = lam(sym,parse_exp());
if (def)
exp = app(exp,def);
return exp;
}
/* Parse the next factor of an expression. Return 0 if no factor found. */
static value parse_factor(void)
{
skip_filler();
if (ch == -1)
return 0;
else if (ch == '\\')
{
unsigned long first_line = source_line;
skip();
if (ch == '\\')
{
ch = -1; /* Two backslashes simulates end of file. */
return 0;
}
else
return parse_lambda(first_line);
}
else if (ch == ';')
{
skip();
return parse_exp();
}
else
{
value factor = parse_term();
if (ch == '=')
syntax_error("Missing symbol declaration before '='", source_line);
return factor;
}
}
static value parse_exp(void)
{
value exp = 0;
while (1)
{
value factor = parse_factor();
if (factor == 0) break;
if (exp == 0)
exp = factor;
else
exp = app(exp,factor);
}
if (exp == 0) exp = hold(I);
return exp;
}
/* Parse the source stream. */
value parse_source(const char *label)
{
value exp;
const char *save = source_label;
source_label = label;
ch = 0;
source_line = 1;
exp = parse_exp();
if (ch != -1)
syntax_error("Extraneous input", source_line);
source_label = save;
return exp;
}
| 2.765625 | 3 |
2024-11-18T22:22:04.142057+00:00 | 2021-09-03T22:06:28 | 2c082a0b4fb2e79a83dac34cd7e318d241501032 | {
"blob_id": "2c082a0b4fb2e79a83dac34cd7e318d241501032",
"branch_name": "refs/heads/main",
"committer_date": "2021-09-03T22:06:28",
"content_id": "c66f61d36caa6510b07b49b832a1a8feb5a728f4",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "7113e36c5606a4de5c07a7d0671350bf7349361b",
"extension": "c",
"filename": "Linear_Search_Recursive.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 386179998,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 750,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/Resources/Search/Linear_Search_Recursive.c",
"provenance": "stackv2-0123.json.gz:10859",
"repo_name": "dallasbrooks/Optimization_Testing",
"revision_date": "2021-09-03T22:06:28",
"revision_id": "83e09cd46e9eb74c09fd1fcd8312adcbdf09f7e6",
"snapshot_id": "3f0fe17d7c2eff47659bf816548c05af4d3c8427",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/dallasbrooks/Optimization_Testing/83e09cd46e9eb74c09fd1fcd8312adcbdf09f7e6/Resources/Search/Linear_Search_Recursive.c",
"visit_date": "2023-07-08T00:56:45.560931"
} | stackv2 | #include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define N 25
#define M 250
void printArray(int arr[], int n);
int recursiveLinearSearch(int arr[], int n, int k, int x){
if(k >= n){
return -1;
}
return arr[k] == x ? k : recursiveLinearSearch(arr, n, k+1, x);
}
int main(){
srand(time(NULL));
int arr[N] = {0};
for(int a = 0; a < N; a++){
arr[a] = rand()%M;
}
int x = arr[rand()%N];
printArray(arr, N);
printf("Looking for %d\n", x);
int idx = recursiveLinearSearch(arr, N, 0, x);
if(idx != -1){
printf("Found %d at index %d\n", x, idx);
}else{
printf("Did not find %d\n", x);
}
return 0;
}
void printArray(int arr[], int n){
for(int a = 0; a < n; a++){
printf("%d ", arr[a]);
}
printf("\n");
}
| 3.28125 | 3 |
2024-11-18T22:22:04.230982+00:00 | 2021-03-07T17:58:26 | b443d593952b6c8392254489c1d115800073c82d | {
"blob_id": "b443d593952b6c8392254489c1d115800073c82d",
"branch_name": "refs/heads/master",
"committer_date": "2021-03-07T17:58:26",
"content_id": "cfab1cf0f20aad1e6acb985121e41c6761dcfe24",
"detected_licenses": [
"MIT"
],
"directory_id": "2fb49bcfdfe25566b19458ac642c1371471da2cf",
"extension": "h",
"filename": "functions.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 287312261,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 288,
"license": "MIT",
"license_type": "permissive",
"path": "/last-nite/casos/intro/functions.h",
"provenance": "stackv2-0123.json.gz:10987",
"repo_name": "A01066270/EstructuradeDatos",
"revision_date": "2021-03-07T17:58:26",
"revision_id": "a77d715d4ae6fa509232cbd2f441cfdb1bdb92a4",
"snapshot_id": "39ddccee8a07ca27df6efeb86da22e5654672845",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/A01066270/EstructuradeDatos/a77d715d4ae6fa509232cbd2f441cfdb1bdb92a4/last-nite/casos/intro/functions.h",
"visit_date": "2023-03-14T00:37:41.093641"
} | stackv2 | /*
* intro.h
* Author: pperezm
*/
#ifndef FUNCTIONS_H_
#define FUNCTIONS_H_
unsigned long fact(int n) {
return 0;
}
bool isPrime(int n) {
return false;
}
unsigned long sum(int arr[], int size) {
return 0;
}
void reverse(int arr[], int size) {
}
#endif /* FUNCTIONS_H_ */
| 2.09375 | 2 |
2024-11-18T22:22:04.460644+00:00 | 2017-08-02T00:15:14 | fd805b465b988cee6ae24878e631a9342654211c | {
"blob_id": "fd805b465b988cee6ae24878e631a9342654211c",
"branch_name": "refs/heads/master",
"committer_date": "2017-08-02T00:15:14",
"content_id": "02018ff0a3fe1e1f659ce85381298e99ef86479a",
"detected_licenses": [
"MIT"
],
"directory_id": "b4b6a3e4de55c60ddc187909364e8f1f0467ae40",
"extension": "c",
"filename": "initializers.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": 1174,
"license": "MIT",
"license_type": "permissive",
"path": "/tests/static_checking/initializers.c",
"provenance": "stackv2-0123.json.gz:11115",
"repo_name": "mgashraf/checkedc",
"revision_date": "2017-08-02T00:15:14",
"revision_id": "72b6ba50b06c7ab386333134e2b9d328760b17e8",
"snapshot_id": "979f55e105f7898f20c01abd7765a865191400a6",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/mgashraf/checkedc/72b6ba50b06c7ab386333134e2b9d328760b17e8/tests/static_checking/initializers.c",
"visit_date": "2021-01-02T08:59:36.173867"
} | stackv2 | // Feature tests of static checking of bounds declarations for variables with
// initializers.
//
// The following lines are for the LLVM test harness:
//
// RUN: %clang_cc1 -verify -fcheckedc-extension %s
#include <stdchecked.h>
// Check that declarations of automatic variables with Checked C bounds
// declarations or _Ptr types always have initializers.
extern void f() {
array_ptr<int> v1;
array_ptr<int> v2 = 0;
array_ptr<int> v3 : bounds(none);
array_ptr<int> v4 : bounds(none) = 0;
array_ptr<int> v5 : count(5) = 0;
array_ptr<int> v6 : count(5); // expected-error {{automatic variable 'v6' with bounds must have initializer}}
array_ptr<int> v7 : byte_count(5 * sizeof(int)) = 0;
array_ptr<int> v8 : byte_count(5 * sizeof(int)); // expected-error {{automatic variable 'v8' with bounds must have initializer}}
array_ptr<int> v9 : bounds(v9, v9 + 5) = 0;
array_ptr<int> v10 : bounds(v10, v10 + 5); // expected-error {{automatic variable 'v10' with bounds must have initializer}}
ptr<int> v20 = 0;
ptr<int> v21; // expected-error {{automatic variable 'v21' with _Ptr type must have initializer}}
}
| 2.4375 | 2 |
2024-11-18T22:22:04.745739+00:00 | 2020-03-26T12:54:14 | aef4c467cbe6e940ce9fbe205daa49b50c2da713 | {
"blob_id": "aef4c467cbe6e940ce9fbe205daa49b50c2da713",
"branch_name": "refs/heads/master",
"committer_date": "2020-03-26T12:55:08",
"content_id": "b66b4c4cd015e6313235d015c42e4a084d98c52c",
"detected_licenses": [
"MIT"
],
"directory_id": "0398f736aa89939fa085c3760f3742974469027a",
"extension": "h",
"filename": "Color.h",
"fork_events_count": 1,
"gha_created_at": "2020-03-26T12:47:24",
"gha_event_created_at": "2020-10-18T17:31:37",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 250256557,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 375,
"license": "MIT",
"license_type": "permissive",
"path": "/headerFiles/Color.h",
"provenance": "stackv2-0123.json.gz:11375",
"repo_name": "hendrikboeck/BlurImage_SPL-for-C",
"revision_date": "2020-03-26T12:54:14",
"revision_id": "fce520af64457401ae3a1348cfa43a468d61c660",
"snapshot_id": "efacc48c95c8a0532ae84b2a9cde77beba0da893",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/hendrikboeck/BlurImage_SPL-for-C/fce520af64457401ae3a1348cfa43a468d61c660/headerFiles/Color.h",
"visit_date": "2022-12-30T04:34:13.061727"
} | stackv2 | /*
* File: Color.h
* -------------
* Author: Hendrik Böck
*
*/
#ifndef COLOR_H_
#define COLOR_H_
struct ColorCDT {
int red;
int green;
int blue;
};
typedef struct ColorCDT *Color;
Color newColor(int red, int green, int blue);
Color newColorFromPixel(int pixel);
void deleteColor(Color color);
Color mergeColors(Color *colors, int colorsLength);
#endif | 2.1875 | 2 |
2024-11-18T22:22:04.806376+00:00 | 2022-04-30T21:15:56 | fa3b0d136beeccf6cb9c8c8d1a6e6b35d6bb5ed5 | {
"blob_id": "fa3b0d136beeccf6cb9c8c8d1a6e6b35d6bb5ed5",
"branch_name": "refs/heads/master",
"committer_date": "2022-04-30T21:15:56",
"content_id": "c1004e4906eb8abf40ba6bdb348ea35278216eca",
"detected_licenses": [
"MIT"
],
"directory_id": "6f247f5400c6a840b6dfcb12388116dc3bb7bd49",
"extension": "c",
"filename": "nv01post.c",
"fork_events_count": 103,
"gha_created_at": "2013-07-23T21:43:43",
"gha_event_created_at": "2022-12-07T01:35:18",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 11620001,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 6808,
"license": "MIT",
"license_type": "permissive",
"path": "/nva/nv01post.c",
"provenance": "stackv2-0123.json.gz:11503",
"repo_name": "envytools/envytools",
"revision_date": "2022-04-30T21:15:56",
"revision_id": "e11d670a70ae0455261ead53cdd09c321974cc64",
"snapshot_id": "c062fbc3b8af90d3df9c6e0f57e9abbfc5690d01",
"src_encoding": "UTF-8",
"star_events_count": 402,
"url": "https://raw.githubusercontent.com/envytools/envytools/e11d670a70ae0455261ead53cdd09c321974cc64/nva/nv01post.c",
"visit_date": "2023-08-26T23:44:47.131591"
} | stackv2 | /*
* Copyright (C) 2012 Marcelina Kościelnicka <mwk@0x04.net>
* All Rights Reserved.
*
* 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 (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
#include "nva.h"
#include <stdio.h>
#include <unistd.h>
void dac_write(int cnum, uint16_t addr, uint8_t val) {
nva_wr32(cnum, 0x609010, addr & 0xff);
nva_wr32(cnum, 0x609014, addr >> 8);
nva_wr32(cnum, 0x609018, val);
}
uint8_t dac_read(int cnum, uint16_t addr) {
nva_wr32(cnum, 0x609010, addr & 0xff);
nva_wr32(cnum, 0x609014, addr >> 8);
return nva_rd32(cnum, 0x609018);
}
int main(int argc, char **argv) {
if (nva_init()) {
fprintf (stderr, "PCI init failure!\n");
return 1;
}
int c;
int cnum =0;
while ((c = getopt (argc, argv, "c:")) != -1)
switch (c) {
case 'c':
sscanf(optarg, "%d", &cnum);
break;
}
if (cnum >= nva_cardsnum) {
if (nva_cardsnum)
fprintf (stderr, "No such card.\n");
else
fprintf (stderr, "No cards found.\n");
return 1;
}
/* ??? */
dac_write(cnum, 5, 0xff);
/* PMC.ENABLE */
nva_wr32(cnum, 0x200, 0);
nva_wr32(cnum, 0x200, 0x01011111);
/* PFB scanout config */
nva_wr32(cnum, 0x600200, 0x130);
nva_wr32(cnum, 0x600400, 0x0);
nva_wr32(cnum, 0x600500, 0x18);
nva_wr32(cnum, 0x600510, 0x88);
nva_wr32(cnum, 0x600520, 0xa0);
nva_wr32(cnum, 0x600530, 0x400);
nva_wr32(cnum, 0x600540, 0x3);
nva_wr32(cnum, 0x600550, 0x6);
nva_wr32(cnum, 0x600560, 0x1d);
nva_wr32(cnum, 0x600570, 0x300);
/* DAC scanout config */
dac_write(cnum, 4, 0x39);
dac_write(cnum, 5, 0x08);
/* VPLL */
dac_write(cnum, 0x18, 0x0a);
dac_write(cnum, 0x19, 0x35);
dac_write(cnum, 0x1a, 0x01);
dac_write(cnum, 0x1b, 0x01);
/* ??? */
dac_write(cnum, 0x1c, 0x00);
/* start it up */
nva_wr32(cnum, 0x6000c0, 0x00330000);
/* ??? */
nva_wr32(cnum, 0x001400, 0x1000);
nva_wr32(cnum, 0x001200, 0x1010);
nva_wr32(cnum, 0x400084, 0x01110100);
/* memory detection */
nva_wr32(cnum, 0x600000, 0x2);
nva_wr32(cnum, 0x1000000, 0xabcd0000);
nva_wr32(cnum, 0x1000004, 0xabcd0001);
nva_wr32(cnum, 0x100000c, 0xabcd0002);
nva_wr32(cnum, 0x1000010, 0xabcd0010);
nva_wr32(cnum, 0x1000014, 0xabcd0011);
nva_wr32(cnum, 0x100001c, 0xabcd0012);
if (nva_rd32(cnum, 0x100000c) == 0xabcd0002) {
printf("POSTing 4MB card\n");
nva_wr32(cnum, 0x600000, 0x10000202);
nva_wr32(cnum, 0x600040, 0x00900011);
nva_wr32(cnum, 0x600044, 0x00000003);
nva_wr32(cnum, 0x600080, 0x00010000);
dac_write(cnum, 4, 0x39);
} else if (nva_rd32(cnum, 0x1000004) == 0xabcd0001) {
printf("POSTing 2MB card\n");
nva_wr32(cnum, 0x600000, 0x10001201);
nva_wr32(cnum, 0x600040, 0x00400011);
nva_wr32(cnum, 0x600044, 0x00000002);
nva_wr32(cnum, 0x600080, 0x00010000);
dac_write(cnum, 4, 0x39);
} else if (nva_rd32(cnum, 0x1000000) == 0xabcd0000) {
printf("POSTing 1MB card\n");
nva_wr32(cnum, 0x600000, 0x10001100);
nva_wr32(cnum, 0x600040, 0x00400011);
nva_wr32(cnum, 0x600044, 0x00000002);
nva_wr32(cnum, 0x600080, 0x00010000);
dac_write(cnum, 4, 0x35);
} else {
printf("POST failure - memory didn't come up!\n");
return 1;
}
/* MPLL */
dac_write(cnum, 0x10, 0x0c);
dac_write(cnum, 0x11, 0x60);
dac_write(cnum, 0x12, 0x01);
dac_write(cnum, 0x13, 0x01);
/* AUDIO */
nva_wr32(cnum, 0x3000c0, 0x111);
/* ??? */
nva_wr32(cnum, 0x6c1f20, 0x332);
nva_wr32(cnum, 0x6c1f24, 0x3330333);
nva_wr32(cnum, 0x6c1f00, 1);
/* palette */
nva_wr32(cnum, 0x609000, 0);
int i;
for (i = 0; i < 256; i++) {
nva_wr32(cnum, 0x609004, ((i >> 5) & 7) * 255/7);
nva_wr32(cnum, 0x609004, ((i >> 2) & 7) * 255/7);
nva_wr32(cnum, 0x609004, ((i >> 0) & 3) * 255/3);
}
for (i = 0; i < 0x400000; i+=4)
nva_wr32(cnum, 0x1000000 + i, 0xcccccccc);
/* framebuffer*/
for (i = 0; i < 0x300 * 0x400; i++) {
int x = i & 0x3ff;
int y = i >> 10;
int col = 0;
if (x+y <= 32)
col = 3;
if (x-y >= 0x400-32)
col = 0x1c;
if (x-y <= -0x300+32)
col = 0xe0;
if (x+y >= 0x700-32)
col = 0xff;
nva_wr8(cnum, 0x1000000 + i, col);
}
/* PGRAPH */
nva_wr32(cnum, 0x4006a4, 0x07000111);
nva_wr32(cnum, 0x400080, 0x11111111);
nva_wr32(cnum, 0x400084, 0x11111000);
nva_wr32(cnum, 0x400088, 0x11111111);
nva_wr32(cnum, 0x40008c, 0x11111111);
nva_wr32(cnum, 0x400100, 0xffffffff);
nva_wr32(cnum, 0x400104, 0xffffffff);
nva_wr32(cnum, 0x400140, 0xffffffff);
nva_wr32(cnum, 0x400144, 0xffffffff);
nva_wr32(cnum, 0x400180, 0x00000010);
nva_wr32(cnum, 0x400190, 0x10010000);
for (i = 0; i < 18; i++) {
nva_wr32(cnum, 0x400400 + i * 4, 0);
nva_wr32(cnum, 0x400480 + i * 4, 0);
}
nva_wr32(cnum, 0x400450, 0);
nva_wr32(cnum, 0x400454, 0);
nva_wr32(cnum, 0x400460, 0x10);
nva_wr32(cnum, 0x400464, 0x3f0);
nva_wr32(cnum, 0x400468, 0x10);
nva_wr32(cnum, 0x40046c, 0x2f0);
nva_wr32(cnum, 0x400600, 0);
nva_wr32(cnum, 0x400604, 0);
nva_wr32(cnum, 0x400608, 0);
nva_wr32(cnum, 0x40060c, 0);
nva_wr32(cnum, 0x400610, 0);
nva_wr32(cnum, 0x400614, 0);
nva_wr32(cnum, 0x400618, 0);
nva_wr32(cnum, 0x40061c, 0);
nva_wr32(cnum, 0x400620, 0);
nva_wr32(cnum, 0x400624, 0);
nva_wr32(cnum, 0x400628, 0);
nva_wr32(cnum, 0x40062c, 0);
nva_wr32(cnum, 0x400630, 0);
nva_wr32(cnum, 0x400634, 0); /* XXX */
nva_wr32(cnum, 0x400640, 0);
nva_wr32(cnum, 0x400644, 0);
nva_wr32(cnum, 0x400648, 0);
nva_wr32(cnum, 0x40064c, 0);
nva_wr32(cnum, 0x400650, 0);
nva_wr32(cnum, 0x400654, 0);
nva_wr32(cnum, 0x400658, 0);
nva_wr32(cnum, 0x40065c, 0);
nva_wr32(cnum, 0x400660, 0);
nva_wr32(cnum, 0x400680, 0);
nva_wr32(cnum, 0x400684, 0);
nva_wr32(cnum, 0x400688, 0);
nva_wr32(cnum, 0x40068c, 0x02ff03ff);
nva_wr32(cnum, 0x400690, 0);
nva_wr32(cnum, 0x400694, 0);
nva_wr32(cnum, 0x400698, 0);
nva_wr32(cnum, 0x40069c, 0);
nva_wr32(cnum, 0x4006a0, 0);
for (i = 0; i < 14; i++)
nva_wr32(cnum, 0x400700 + i * 4, 0);
return 0;
}
| 2.328125 | 2 |
2024-11-18T22:22:04.897041+00:00 | 2018-11-12T04:54:27 | 65c4832fb740e86b4fd3d714769946817e837a33 | {
"blob_id": "65c4832fb740e86b4fd3d714769946817e837a33",
"branch_name": "refs/heads/master",
"committer_date": "2018-11-12T04:54:27",
"content_id": "51c235e0ba0e0150c1c009362f9206c5b7913576",
"detected_licenses": [
"MIT"
],
"directory_id": "509f8782ef6e9d5fd0e5f03349af8dc11ebc2c24",
"extension": "c",
"filename": "mem_aprox.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 123492976,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1499,
"license": "MIT",
"license_type": "permissive",
"path": "/mem_aprox.c",
"provenance": "stackv2-0123.json.gz:11633",
"repo_name": "tonyz0x0/RAM-and-Cache-Measurement",
"revision_date": "2018-11-12T04:54:27",
"revision_id": "d2bd344034c657872d2eaeaaea6cbb784087edb1",
"snapshot_id": "0a4da6d096a38d342b7b2f4457b1630b358fb89f",
"src_encoding": "UTF-8",
"star_events_count": 5,
"url": "https://raw.githubusercontent.com/tonyz0x0/RAM-and-Cache-Measurement/d2bd344034c657872d2eaeaaea6cbb784087edb1/mem_aprox.c",
"visit_date": "2022-02-20T04:22:24.706268"
} | stackv2 | #include <stdio.h>
#include <string.h>
#include <time.h>
#include <stdlib.h>
#define MB 1 << 20
#define SIZE 80
#define BLOCK (SIZE * (MB))
unsigned int ramSize = 0;
void estimate();
/*
* The main method is to continuously call malloc() and memset()
* to ask memory from operating system. When the physical memory is
* nearly occupied, the thrashing will occur and we will detect it by compare
* the time we spend on memset() between last time and this time. The total allocate memory is
* the approximated size of RAM.
*/
int main() {
estimate();
printf("The approximate RAM size is: %.2f GB | %d MB\n", ((double)ramSize / 1024.0), ramSize);
}
void estimate() {
double currentTime = 0, prevTime = 0;
int i = 0, j = 0;
clock_t begin;
void *arr[1000];
for (i = 0 ; i < 1000; i++) {
arr[i] = malloc(BLOCK);
if (arr[i] == NULL)
{
printf("\nOut of Memory!\n");
return;
}
prevTime = currentTime;
begin = clock();
for(j = 0; j < i; j++) {
memset(arr[j], 0, BLOCK);
}
currentTime = (double)(clock() - begin)/CLOCKS_PER_SEC;
ramSize += SIZE;
printf("Calculating...... RAM: %d MB, Previous Time : %lf, Current Time : %lf\n", ramSize, prevTime, currentTime);
if ((prevTime != 0) && ((2 * prevTime) < currentTime)) {
for (j = 0; j < i; j++) {
free(arr[j]);
}
break;
}
}
} | 3.28125 | 3 |
2024-11-18T22:22:05.067279+00:00 | 2023-09-03T08:13:23 | 51db30028c05223a7b6febf1ebfc0d50375b1268 | {
"blob_id": "51db30028c05223a7b6febf1ebfc0d50375b1268",
"branch_name": "refs/heads/main",
"committer_date": "2023-09-03T08:13:23",
"content_id": "4ffbc2f094d9ba4b303f2a02319f33cdec21be6a",
"detected_licenses": [
"MIT"
],
"directory_id": "fb0f9abad373cd635c2635bbdf491ea0f32da5ff",
"extension": "c",
"filename": "pal_hmac.c",
"fork_events_count": 5179,
"gha_created_at": "2019-09-24T23:36:39",
"gha_event_created_at": "2023-09-14T21:58:52",
"gha_language": "C#",
"gha_license_id": "MIT",
"github_id": 210716005,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3743,
"license": "MIT",
"license_type": "permissive",
"path": "/src/native/libs/System.Security.Cryptography.Native.Apple/pal_hmac.c",
"provenance": "stackv2-0123.json.gz:11890",
"repo_name": "dotnet/runtime",
"revision_date": "2023-09-03T08:13:23",
"revision_id": "47bb554d298e1e34c4e3895d7731e18ad1c47d02",
"snapshot_id": "f6fd23936752e202f8e4d6d94f3a4f3b0e77f58f",
"src_encoding": "UTF-8",
"star_events_count": 13765,
"url": "https://raw.githubusercontent.com/dotnet/runtime/47bb554d298e1e34c4e3895d7731e18ad1c47d02/src/native/libs/System.Security.Cryptography.Native.Apple/pal_hmac.c",
"visit_date": "2023-09-03T15:35:46.493337"
} | stackv2 | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#include "pal_hmac.h"
struct hmac_ctx_st
{
CCHmacAlgorithm appleAlgId;
CCHmacContext hmac;
};
void AppleCryptoNative_HmacFree(HmacCtx* pHmac)
{
if (pHmac != NULL)
{
free(pHmac);
}
}
static CCHmacAlgorithm PalAlgorithmToAppleAlgorithm(PAL_HashAlgorithm algorithm)
{
switch (algorithm)
{
case PAL_MD5:
return kCCHmacAlgMD5;
case PAL_SHA1:
return kCCHmacAlgSHA1;
case PAL_SHA256:
return kCCHmacAlgSHA256;
case PAL_SHA384:
return kCCHmacAlgSHA384;
case PAL_SHA512:
return kCCHmacAlgSHA512;
default:
// 0 is a defined value (SHA1) so "unknown" has to be something else
return UINT_MAX;
}
}
static int32_t GetHmacOutputSize(PAL_HashAlgorithm algorithm)
{
switch (algorithm)
{
case PAL_MD5:
return CC_MD5_DIGEST_LENGTH;
case PAL_SHA1:
return CC_SHA1_DIGEST_LENGTH;
case PAL_SHA256:
return CC_SHA256_DIGEST_LENGTH;
case PAL_SHA384:
return CC_SHA384_DIGEST_LENGTH;
case PAL_SHA512:
return CC_SHA512_DIGEST_LENGTH;
default:
return -1;
}
}
HmacCtx* AppleCryptoNative_HmacCreate(PAL_HashAlgorithm algorithm, int32_t* pcbHmac)
{
if (pcbHmac == NULL)
return NULL;
CCHmacAlgorithm appleAlgId = PalAlgorithmToAppleAlgorithm(algorithm);
if (appleAlgId == UINT_MAX)
{
*pcbHmac = -1;
return NULL;
}
HmacCtx* hmacCtx = (HmacCtx*)malloc(sizeof(HmacCtx));
if (hmacCtx == NULL)
return hmacCtx;
hmacCtx->appleAlgId = appleAlgId;
*pcbHmac = GetHmacOutputSize(algorithm);
return hmacCtx;
}
int32_t AppleCryptoNative_HmacInit(HmacCtx* ctx, uint8_t* pbKey, int32_t cbKey)
{
if (ctx == NULL || cbKey < 0)
return 0;
if (cbKey != 0 && pbKey == NULL)
return 0;
// No return value
CCHmacInit(&ctx->hmac, ctx->appleAlgId, pbKey, (size_t)cbKey);
return 1;
}
int32_t AppleCryptoNative_HmacUpdate(HmacCtx* ctx, uint8_t* pbData, int32_t cbData)
{
if (cbData == 0)
return 1;
if (ctx == NULL || pbData == NULL)
return 0;
// No return value
CCHmacUpdate(&ctx->hmac, pbData, (size_t)cbData);
return 1;
}
int32_t AppleCryptoNative_HmacFinal(HmacCtx* ctx, uint8_t* pbOutput)
{
if (ctx == NULL || pbOutput == NULL)
return 0;
// No return value
CCHmacFinal(&ctx->hmac, pbOutput);
return 1;
}
int32_t AppleCryptoNative_HmacCurrent(const HmacCtx* ctx, uint8_t* pbOutput)
{
if (ctx == NULL || pbOutput == NULL)
return 0;
HmacCtx dup = *ctx;
return AppleCryptoNative_HmacFinal(&dup, pbOutput);
}
int32_t AppleCryptoNative_HmacOneShot(PAL_HashAlgorithm algorithm,
const uint8_t* pKey,
int32_t cbKey,
const uint8_t* pBuf,
int32_t cbBuf,
uint8_t* pOutput,
int32_t cbOutput,
int32_t* pcbDigest)
{
if (pOutput == NULL || cbOutput <= 0 || pcbDigest == NULL)
return -1;
CCHmacAlgorithm ccAlgorithm = PalAlgorithmToAppleAlgorithm(algorithm);
*pcbDigest = GetHmacOutputSize(algorithm);
if (ccAlgorithm == UINT_MAX)
return -1;
if (cbOutput < *pcbDigest)
return -1;
CCHmac(ccAlgorithm, pKey, cbKey, pBuf, cbBuf, pOutput);
return 1;
}
| 2.390625 | 2 |
2024-11-18T22:22:05.248991+00:00 | 2020-08-02T20:23:15 | ca7b3d8f3f29aeeafff4488df5e85b371913fe30 | {
"blob_id": "ca7b3d8f3f29aeeafff4488df5e85b371913fe30",
"branch_name": "refs/heads/master",
"committer_date": "2020-08-02T20:23:15",
"content_id": "0bd7b311fff08400808640e1b92f3ca45ee379ab",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "971e9cb164ca5ca8bcc1b1da4d758b5e958d3c0f",
"extension": "h",
"filename": "print.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 201488401,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 30356,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/c/print.h",
"provenance": "stackv2-0123.json.gz:12018",
"repo_name": "lassik/upscheme",
"revision_date": "2020-08-02T20:23:15",
"revision_id": "61935bd866acb18902199bc4bc4cdd1760aa1ffc",
"snapshot_id": "7c54210eb5172976db38fcfb56a3bb5d2c0be46f",
"src_encoding": "UTF-8",
"star_events_count": 4,
"url": "https://raw.githubusercontent.com/lassik/upscheme/61935bd866acb18902199bc4bc4cdd1760aa1ffc/c/print.h",
"visit_date": "2021-07-21T03:44:49.147081"
} | stackv2 | extern void *memrchr(const void *s, int c, size_t n);
extern value_t instrsym;
extern value_t outstrsym;
struct printer_options {
int display; // Use `display` repr instead of `write` repr
int newline; // Write a newline at the end.
int shared; // 0=no cycle detection, 1=minimal cycles, 2=max cycles
int indent; // Write indented lines instead of one long line.
int width; // maximum line length when indenting, ignored when not
fixnum_t length; // truncate lists after N items and write "..."
fixnum_t level; // print only the outermost N levels of nested structure
};
struct printer {
int line;
int column;
int level;
unsigned int cycle_labels;
struct htable cycle_traversed;
struct printer_options opts;
};
// Printer state during one printer run
static struct printer pr;
static void outc(char c, struct ios *f)
{
ios_putc(c, f);
if (c == '\n')
pr.column = 0;
else
pr.column++;
}
static void outs(char *s, struct ios *f)
{
ios_puts(s, f);
pr.column += u8_strwidth(s);
}
static void outsn(char *s, struct ios *f, size_t n)
{
ios_write(f, s, n);
pr.column += u8_strwidth(s);
}
static int outindent(int n, struct ios *f)
{
int n0;
// move back to left margin if we get too indented
if (n > pr.opts.width - 12)
n = 2;
n0 = n;
ios_putc('\n', f);
pr.line++;
pr.column = n;
while (n) {
ios_putc(' ', f);
n--;
}
return n0;
}
void fl_print_chr(char c, struct ios *f) { outc(c, f); }
void fl_print_str(char *s, struct ios *f) { outs(s, f); }
void print_traverse(value_t v)
{
value_t *bp;
while (iscons(v)) {
if (ismarked(v)) {
bp = (value_t *)ptrhash_bp(&pr.cycle_traversed, (void *)v);
if (*bp == (value_t)HT_NOTFOUND)
*bp = fixnum(pr.cycle_labels++);
return;
}
mark_cons(v);
print_traverse(car_(v));
v = cdr_(v);
}
if (!ismanaged(v) || issymbol(v))
return;
if (ismarked(v)) {
bp = (value_t *)ptrhash_bp(&pr.cycle_traversed, (void *)v);
if (*bp == (value_t)HT_NOTFOUND)
*bp = fixnum(pr.cycle_labels++);
return;
}
if (isvector(v)) {
unsigned int i;
if (vector_size(v) > 0)
mark_cons(v);
for (i = 0; i < vector_size(v); i++)
print_traverse(vector_elt(v, i));
} else if (iscprim(v)) {
// don't consider shared references to e.g. chars
} else if (isclosure(v)) {
struct function *f;
mark_cons(v);
f = (struct function *)ptr(v);
print_traverse(f->bcode);
print_traverse(f->vals);
print_traverse(f->env);
} else {
struct cvalue *cv;
struct fltype *t;
assert(iscvalue(v));
cv = (struct cvalue *)ptr(v);
// don't consider shared references to ""
if (!cv_isstr(cv) || cv_len(cv) != 0)
mark_cons(v);
t = cv_class(cv);
if (t->vtable != NULL && t->vtable->print_traverse != NULL)
t->vtable->print_traverse(v);
}
}
static void print_symbol_name(struct ios *f, char *name)
{
int i, escape, charescape;
escape = charescape = 0;
if ((name[0] == '\0') || (name[0] == '.' && name[1] == '\0') ||
(name[0] == '#') || isnumtok(name, NULL))
escape = 1;
i = 0;
while (name[i]) {
if (!symchar(name[i])) {
escape = 1;
if (name[i] == '|' || name[i] == '\\') {
charescape = 1;
break;
}
}
i++;
}
if (escape) {
if (charescape) {
outc('|', f);
i = 0;
while (name[i]) {
if (name[i] == '|' || name[i] == '\\')
outc('\\', f);
outc(name[i], f);
i++;
}
outc('|', f);
} else {
outc('|', f);
outs(name, f);
outc('|', f);
}
} else {
outs(name, f);
}
}
/*
The following implements a simple pretty-printing algorithm. This is
an unlimited-width approach that doesn't require an extra pass.
It uses some heuristics to guess whether an expression is "small",
and avoids wrapping symbols across lines. The result is high
performance and nice output for typical code. Quality is poor for
pathological or deeply-nested expressions, but those are difficult
to print anyway.
*/
#define SMALL_STR_LEN 20
static int tinyp(value_t v)
{
if (issymbol(v))
return (u8_strwidth(symbol_name(v)) < SMALL_STR_LEN);
if (fl_isstring(v))
return (cv_len((struct cvalue *)ptr(v)) < SMALL_STR_LEN);
return (isfixnum(v) || isbuiltin(v) || v == FL_F || v == FL_T ||
v == FL_NIL || v == FL_EOF || iscprim(v));
}
static int smallp(value_t v)
{
if (tinyp(v))
return 1;
if (fl_isnumber(v))
return 1;
if (iscons(v)) {
if (tinyp(car_(v)) &&
(tinyp(cdr_(v)) || (iscons(cdr_(v)) && tinyp(car_(cdr_(v))) &&
cdr_(cdr_(v)) == NIL)))
return 1;
return 0;
}
if (isvector(v)) {
size_t s = vector_size(v);
return (s == 0 || (tinyp(vector_elt(v, 0)) &&
(s == 1 || (s == 2 && tinyp(vector_elt(v, 1))))));
}
return 0;
}
static int specialindent(value_t head)
{
// indent these forms 2 spaces, not lined up with the first argument
if (head == LAMBDA || head == TRYCATCH || head == definesym ||
head == defmacrosym || head == forsym)
return 2;
return -1;
}
static int lengthestimate(value_t v)
{
// get the width of an expression if we can do so cheaply
if (issymbol(v))
return u8_strwidth(symbol_name(v));
if (iscprim(v) && cp_class((struct cprim *)ptr(v)) == wchartype)
return 4;
return -1;
}
static int allsmallp(value_t v)
{
int n;
n = 1;
while (iscons(v)) {
if (!smallp(car_(v)))
return 0;
v = cdr_(v);
n++;
if (n > 25)
return n;
}
return n;
}
static int indentafter3(value_t head, value_t v)
{
// for certain X always indent (X a b c) after b
return ((head == forsym) && !allsmallp(cdr_(v)));
}
static int indentafter2(value_t head, value_t v)
{
// for certain X always indent (X a b) after a
return ((head == definesym || head == defmacrosym) &&
!allsmallp(cdr_(v)));
}
static int indentevery(value_t v)
{
value_t c;
// indent before every subform of a special form, unless every
// subform is "small"
c = car_(v);
if (c == LAMBDA || c == setqsym)
return 0;
if (c == IF) // TODO: others
return !allsmallp(cdr_(v));
return 0;
}
static int blockindent(value_t v)
{
// in this case we switch to block indent mode, where the head
// is no longer considered special:
// (a b c d e
// f g h i j)
return (allsmallp(v) > 9);
}
static void print_pair(struct ios *f, value_t v)
{
value_t cd, head;
char *op;
fixnum_t last_line;
int startpos, newindent, blk, n_unindented, n, si, ind, est, always,
nextsmall, thistiny, after2, after3;
op = NULL;
if (iscons(cdr_(v)) && cdr_(cdr_(v)) == NIL &&
!ptrhash_has(&pr.cycle_traversed, (void *)cdr_(v)) &&
(((car_(v) == QUOTE) && (op = "'")) ||
((car_(v) == BACKQUOTE) && (op = "`")) ||
((car_(v) == COMMA) && (op = ",")) ||
((car_(v) == COMMAAT) && (op = ",@")) ||
((car_(v) == COMMADOT) && (op = ",.")))) {
// special prefix syntax
unmark_cons(v);
unmark_cons(cdr_(v));
outs(op, f);
fl_print_child(f, car_(cdr_(v)));
return;
}
startpos = pr.column;
outc('(', f);
newindent = pr.column;
blk = blockindent(v);
n = ind = always = 0;
if (!blk)
always = indentevery(v);
head = car_(v);
after3 = indentafter3(head, v);
after2 = indentafter2(head, v);
n_unindented = 1;
while (1) {
cd = cdr_(v);
if (pr.opts.length >= 0 && n >= pr.opts.length && cd != NIL) {
outsn("...)", f, 4);
break;
}
last_line = pr.line;
unmark_cons(v);
fl_print_child(f, car_(v));
if (!iscons(cd) || ptrhash_has(&pr.cycle_traversed, (void *)cd)) {
if (cd != NIL) {
outsn(" . ", f, 3);
fl_print_child(f, cd);
}
outc(')', f);
break;
}
if (!pr.opts.indent || ((head == LAMBDA) && n == 0)) {
// never break line before lambda-list
ind = 0;
} else {
est = lengthestimate(car_(cd));
nextsmall = smallp(car_(cd));
thistiny = tinyp(car_(v));
ind =
(((pr.line > last_line) || (pr.column > pr.opts.width / 2 &&
!nextsmall && !thistiny && n > 0)) ||
(pr.column > pr.opts.width - 4) ||
(est != -1 && (pr.column + est > pr.opts.width - 2)) ||
((head == LAMBDA) && !nextsmall) ||
(n > 0 && always) ||
(n == 2 && after3) || (n == 1 && after2) ||
(n_unindented >= 3 && !nextsmall) ||
(n == 0 && !smallp(head)));
}
if (ind) {
newindent = outindent(newindent, f);
n_unindented = 1;
} else {
n_unindented++;
outc(' ', f);
if (n == 0) {
// set indent level after printing head
si = specialindent(head);
if (si != -1)
newindent = startpos + si;
else if (!blk)
newindent = pr.column;
}
}
n++;
v = cd;
}
}
static void cvalue_print(struct ios *f, value_t v);
static int write_cycle_prefix(struct ios *f, value_t v)
{
value_t label;
if ((label = (value_t)ptrhash_get(&pr.cycle_traversed, (void *)v)) !=
(value_t)HT_NOTFOUND) {
if (!ismarked(v)) {
pr.column += ios_printf(f, "#%ld#", numval(label));
return 1;
}
pr.column += ios_printf(f, "#%ld=", numval(label));
}
if (ismanaged(v))
unmark_cons(v);
return 0;
}
void fl_print_child(struct ios *f, value_t v)
{
char *name;
// fprintf(stderr, "fl_print_child\n");
if (pr.opts.level >= 0 && pr.level >= pr.opts.level &&
(iscons(v) || isvector(v) || isclosure(v))) {
outc('#', f);
return;
}
pr.level++;
switch (tag(v)) {
case TAG_NUM:
case TAG_NUM1:
pr.column += ios_printf(f, "%ld", numval(v));
break;
case TAG_SYM:
name = symbol_name(v);
if (pr.opts.display)
outs(name, f);
else if (ismanaged(v)) {
outsn("#:", f, 2);
outs(name, f);
} else
print_symbol_name(f, name);
break;
case TAG_FUNCTION:
if (v == FL_T) {
outsn("#t", f, 2);
} else if (v == FL_F) {
outsn("#f", f, 2);
} else if (v == FL_NIL) {
outsn("()", f, 2);
} else if (v == FL_EOF) {
outsn("#<eof>", f, 6);
} else if (isbuiltin(v)) {
if (!pr.opts.display)
outsn("#.", f, 2);
outs(builtin_names[uintval(v)], f);
} else {
assert(isclosure(v));
if (!pr.opts.display) {
struct function *fn;
char *data;
size_t i, sz;
if (write_cycle_prefix(f, v))
break;
fn = (struct function *)ptr(v);
outs("#fn(", f);
data = cvalue_data(fn->bcode);
sz = cvalue_len(fn->bcode);
for (i = 0; i < sz; i++)
data[i] += 48;
fl_print_child(f, fn->bcode);
for (i = 0; i < sz; i++)
data[i] -= 48;
outc(' ', f);
fl_print_child(f, fn->vals);
if (fn->env != NIL) {
outc(' ', f);
fl_print_child(f, fn->env);
}
if (fn->name != LAMBDA) {
outc(' ', f);
fl_print_child(f, fn->name);
}
outc(')', f);
} else {
outs("#<function>", f);
}
}
break;
case TAG_CPRIM:
if (v == UNBOUND)
outs("#<undefined>", f);
else
cvalue_print(f, v);
break;
case TAG_CVALUE:
case TAG_VECTOR:
case TAG_CONS:
if (!pr.opts.display && write_cycle_prefix(f, v))
break;
if (isvector(v)) {
int newindent, est, sz, i;
outc('[', f);
newindent = pr.column;
sz = vector_size(v);
for (i = 0; i < sz; i++) {
if (pr.opts.length >= 0 && i >= pr.opts.length &&
i < sz - 1) {
outsn("...", f, 3);
break;
}
fl_print_child(f, vector_elt(v, i));
if (i < sz - 1) {
if (!pr.opts.indent) {
outc(' ', f);
} else {
est = lengthestimate(vector_elt(v, i + 1));
if (pr.column > pr.opts.width - 4 ||
(est != -1 &&
(pr.column + est > pr.opts.width - 2)) ||
(pr.column > pr.opts.width / 2 &&
!smallp(vector_elt(v, i + 1)) &&
!tinyp(vector_elt(v, i))))
newindent = outindent(newindent, f);
else
outc(' ', f);
}
}
}
outc(']', f);
break;
}
if (iscvalue(v))
cvalue_print(f, v);
else
print_pair(f, v);
break;
}
pr.level--;
}
static void print_string(struct ios *f, char *str, size_t sz)
{
char buf[512];
size_t i = 0;
uint8_t c;
static char hexdig[] = "0123456789abcdef";
outc('"', f);
if (!u8_isvalid(str, sz)) {
// alternate print algorithm that preserves data if it's not UTF-8
for (i = 0; i < sz; i++) {
c = str[i];
if (c == '\\')
outsn("\\\\", f, 2);
else if (c == '"')
outsn("\\\"", f, 2);
else if (c >= 32 && c < 0x7f)
outc(c, f);
else {
outsn("\\x", f, 2);
outc(hexdig[c >> 4], f);
outc(hexdig[c & 0xf], f);
}
}
} else {
while (i < sz) {
size_t n = u8_escape(buf, sizeof(buf), str, &i, sz, 1, 0);
outsn(buf, f, n - 1);
}
}
outc('"', f);
}
int double_exponent(double d)
{
union ieee754_double dl;
dl.d = d;
return dl.ieee.exponent - IEEE754_DOUBLE_BIAS;
}
void snprint_real(char *s, size_t cnt, double r,
int width, // printf field width, or 0
int dec, // # decimal digits desired, recommend 16
// # of zeros in .00...0x before using scientific notation
// recommend 3-4 or so
int max_digs_rt,
// # of digits left of decimal before scientific notation
// recommend 10
int max_digs_lf)
{
int mag;
double fpart, temp;
char format[8];
char num_format[3];
int sz, keepz = 0;
s[0] = '\0';
if (width == -1) {
width = 0;
keepz = 1;
}
if (isnan(r)) {
if (sign_bit(r))
strncpy(s, "-nan", cnt);
else
strncpy(s, "nan", cnt);
return;
}
if (r == 0) {
strncpy(s, "0", cnt);
return;
}
num_format[0] = 'l';
num_format[2] = '\0';
mag = double_exponent(r);
mag = (int)(((double)mag) / LOG2_10 + 0.5);
if (r == 0)
mag = 0;
if ((mag > max_digs_lf - 1) || (mag < -max_digs_rt)) {
num_format[1] = 'e';
temp = r / pow(10, mag); /* see if number will have a decimal */
fpart = temp - floor(temp); /* when written in scientific notation */
} else {
num_format[1] = 'f';
fpart = r - floor(r);
}
if (fpart == 0)
dec = 0;
if (width == 0) {
snprintf(format, 8, "%%.%d%s", dec, num_format);
} else {
snprintf(format, 8, "%%%d.%d%s", width, dec, num_format);
}
sz = snprintf(s, cnt, format, r);
/* trim trailing zeros from fractions. not when using scientific
notation, since we might have e.g. 1.2000e+100. also not when we
need a specific output width */
if (width == 0 && !keepz) {
if (sz > 2 && fpart && num_format[1] != 'e') {
while (s[sz - 1] == '0') {
s[sz - 1] = '\0';
sz--;
}
// don't need trailing .
if (s[sz - 1] == '.') {
s[sz - 1] = '\0';
sz--;
}
}
}
// TODO. currently 1.1e20 prints as 1.1000000000000000e+20; be able to
// get rid of all those zeros.
}
static numerictype_t sym_to_numtype(value_t type);
// 'weak' means we don't need to accurately reproduce the type, so
// for example #int32(0) can be printed as just 0. this is used
// printing in a context where a type is already implied, e.g. inside
// an array.
static void cvalue_printdata(struct ios *f, void *data, size_t len,
value_t type, int weak)
{
if (type == bytesym) {
unsigned char ch = *(unsigned char *)data;
if (pr.opts.display)
outc(ch, f);
else if (weak)
pr.column += ios_printf(f, "#x%hhx", ch);
else
pr.column += ios_printf(f, "#byte(#x%hhx)", ch);
} else if (type == wcharsym) {
char seq[8];
uint32_t wc = *(uint32_t *)data;
size_t nb = u8_toutf8(seq, sizeof(seq), &wc, 1);
seq[nb] = '\0';
if (pr.opts.display) {
// TODO: better multibyte handling
if (wc == 0)
ios_putc(0, f);
else
outs(seq, f);
} else {
outsn("#\\", f, 2);
if (wc == 0x00)
outsn("nul", f, 3);
else if (wc == 0x07)
outsn("alarm", f, 5);
else if (wc == 0x08)
outsn("backspace", f, 9);
else if (wc == 0x09)
outsn("tab", f, 3);
// else if (wc == 0x0A) outsn("linefeed", f, 8);
else if (wc == 0x0A)
outsn("newline", f, 7);
else if (wc == 0x0B)
outsn("vtab", f, 4);
else if (wc == 0x0C)
outsn("page", f, 4);
else if (wc == 0x0D)
outsn("return", f, 6);
else if (wc == 0x1B)
outsn("esc", f, 3);
// else if (wc == 0x20) outsn("space", f, 5);
else if (wc == 0x7F)
outsn("delete", f, 6);
else if (iswprint(wc))
outs(seq, f);
else
pr.column += ios_printf(f, "x%04x", (int)wc);
}
} else if (type == floatsym || type == doublesym) {
char buf[64];
double d;
int ndec;
if (type == floatsym) {
d = (double)*(float *)data;
ndec = 8;
} else {
d = *(double *)data;
ndec = 16;
}
if (!DFINITE(d)) {
char *rep;
if (isnan(d))
rep = sign_bit(d) ? "-nan.0" : "+nan.0";
else
rep = sign_bit(d) ? "-inf.0" : "+inf.0";
if (type == floatsym && !pr.opts.display && !weak)
pr.column += ios_printf(f, "#%s(%s)", symbol_name(type), rep);
else
outs(rep, f);
} else if (d == 0) {
if (1 / d < 0)
outsn("-0.0", f, 4);
else
outsn("0.0", f, 3);
if (type == floatsym && !pr.opts.display && !weak)
outc('f', f);
} else {
int hasdec;
snprint_real(buf, sizeof(buf), d, 0, ndec, 3, 10);
hasdec = (strpbrk(buf, ".eE") != NULL);
outs(buf, f);
if (!hasdec)
outsn(".0", f, 2);
if (type == floatsym && !pr.opts.display && !weak)
outc('f', f);
}
} else if (type == uint64sym
#ifdef BITS64
|| type == ulongsym
#endif
) {
uint64_t ui64 = *(uint64_t *)data;
if (weak || pr.opts.display)
pr.column += ios_printf(f, "%llu", ui64);
else
pr.column += ios_printf(f, "#%s(%llu)", symbol_name(type), ui64);
} else if (issymbol(type)) {
// handle other integer prims. we know it's smaller than uint64
// at this point, so int64 is big enough to capture everything.
numerictype_t nt = sym_to_numtype(type);
if (nt == N_NUMTYPES) {
pr.column += ios_printf(f, "#<%s>", symbol_name(type));
} else {
int64_t i64 = conv_to_int64(data, nt);
if (weak || pr.opts.display)
pr.column += ios_printf(f, "%lld", i64);
else
pr.column +=
ios_printf(f, "#%s(%lld)", symbol_name(type), i64);
}
} else if (iscons(type)) {
if (car_(type) == arraysym) {
value_t eltype = car(cdr_(type));
size_t cnt, elsize, i;
if (iscons(cdr_(cdr_(type)))) {
cnt = toulong(car_(cdr_(cdr_(type))), "length");
elsize = cnt ? len / cnt : 0;
} else {
// incomplete array type
int junk;
elsize = ctype_sizeof(eltype, &junk);
cnt = elsize ? len / elsize : 0;
}
if (eltype == bytesym) {
if (pr.opts.display) {
ios_write(f, data, len);
/*
char *nl = memrchr(data, '\n', len);
if (nl)
pr.column = u8_strwidth(nl+1);
else
pr.column += u8_strwidth(data);
*/
} else {
print_string(f, (char *)data, len);
}
return;
} else if (eltype == wcharsym) {
// TODO wchar
} else {
}
if (!weak) {
if (eltype == uint8sym) {
outsn("#vu8(", f, 5);
} else {
outsn("#array(", f, 7);
fl_print_child(f, eltype);
if (cnt > 0)
outc(' ', f);
}
} else {
outc('[', f);
}
for (i = 0; i < cnt; i++) {
if (i > 0)
outc(' ', f);
cvalue_printdata(f, data, elsize, eltype, 1);
data = (char *)data + elsize;
}
if (!weak)
outc(')', f);
else
outc(']', f);
} else if (car_(type) == enumsym) {
int n = *(int *)data;
value_t syms = car(cdr_(type));
assert(isvector(syms));
if (!weak) {
outsn("#enum(", f, 6);
fl_print_child(f, syms);
outc(' ', f);
}
if (n >= (int)vector_size(syms)) {
cvalue_printdata(f, data, len, int32sym, 1);
} else {
fl_print_child(f, vector_elt(syms, n));
}
if (!weak)
outc(')', f);
}
}
}
static void cvalue_print(struct ios *f, value_t v)
{
struct cvalue *cv = (struct cvalue *)ptr(v);
void *data = cptr(v);
value_t label;
if (cv_class(cv) == builtintype) {
void *fptr = *(void **)data;
label = (value_t)ptrhash_get(&reverse_dlsym_lookup_table, cv);
if (label == (value_t)HT_NOTFOUND) {
pr.column +=
ios_printf(f, "#<builtin @#x%08zx>", (size_t)(builtin_t)fptr);
} else {
if (pr.opts.display) {
outs(symbol_name(label), f);
} else {
outsn("#fn(", f, 4);
outs(symbol_name(label), f);
outc(')', f);
}
}
} else if (cv_class(cv)->vtable != NULL &&
cv_class(cv)->vtable->print != NULL) {
cv_class(cv)->vtable->print(v, f);
} else {
value_t type = cv_type(cv);
size_t len = iscprim(v) ? cv_class(cv)->size : cv_len(cv);
cvalue_printdata(f, data, len, type, 0);
}
}
void print_with_options(struct ios *f, value_t v,
struct printer_options *opts)
{
memcpy(&pr.opts, opts, sizeof(pr.opts));
// TODO
if (pr.opts.width < 80)
pr.opts.width = 80;
// TODO
pr.opts.level = -1;
pr.opts.length = -1;
pr.level = 0;
pr.cycle_labels = 0;
if (pr.opts.shared)
print_traverse(v);
pr.line = pr.column = 0;
fl_print_child(f, v);
if (pr.opts.newline) {
ios_putc('\n', f);
pr.line++;
pr.column = 0;
}
if (pr.opts.level >= 0 || pr.opts.length >= 0) {
memset(consflags, 0,
4 * bitvector_nwords(heapsize / sizeof(struct cons)));
}
if ((iscons(v) || isvector(v) || isfunction(v) || iscvalue(v)) &&
!fl_isstring(v) && v != FL_T && v != FL_F && v != FL_NIL) {
htable_reset(&pr.cycle_traversed, 32);
}
}
void display_defaults(struct ios *f, value_t v)
{
struct printer_options opts;
memset(&opts, 0, sizeof(opts));
opts.display = 1;
opts.shared = 1;
opts.length = -1;
opts.level = -1;
print_with_options(f, v, &opts);
}
void write_simple_defaults(struct ios *f, value_t v)
{
struct printer_options opts;
memset(&opts, 0, sizeof(opts));
print_with_options(f, v, &opts);
}
void write_defaults_indent(struct ios *f, value_t v)
{
struct printer_options opts;
memset(&opts, 0, sizeof(opts));
opts.shared = 1;
opts.indent = 1;
opts.length = -1;
opts.level = -1;
print_with_options(f, v, &opts);
}
void fl_print(struct ios *f, value_t v)
{
struct printer_options opts;
value_t pl;
memset(&opts, 0, sizeof(opts));
// *print-readably*
opts.display = (symbol_value(printreadablysym) == FL_F);
// *print-pretty*
opts.indent = (symbol_value(printprettysym) != FL_F);
// *print-width*
pl = symbol_value(printwidthsym);
if (isfixnum(pl))
opts.width = numval(pl);
else
opts.width = -1;
// *print-length*
pl = symbol_value(printlengthsym);
if (isfixnum(pl))
opts.length = numval(pl);
else
opts.length = -1;
// *print-level*
pl = symbol_value(printlevelsym);
if (isfixnum(pl))
opts.level = numval(pl);
else
opts.level = -1;
print_with_options(f, v, &opts);
}
static value_t writelike(struct printer_options *opts, const char *proc_name,
value_t *args, uint32_t nargs)
{
value_t val;
struct ios *ios;
if (nargs < 1 || nargs > 2)
argcount(proc_name, nargs, 1);
val = args[0];
if (nargs == 2)
ios = fl_toiostream(args[1], proc_name);
else
ios = fl_toiostream(symbol_value(outstrsym), proc_name);
print_with_options(ios, val, opts);
return val;
}
static value_t builtin_display(value_t *args, uint32_t nargs)
{
struct printer_options opts;
memset(&opts, 0, sizeof(opts));
opts.display = 1;
opts.shared = 1;
return writelike(&opts, "display", args, nargs);
}
static value_t builtin_displayln(value_t *args, uint32_t nargs)
{
struct printer_options opts;
memset(&opts, 0, sizeof(opts));
opts.display = 1;
opts.shared = 1;
opts.newline = 1;
return writelike(&opts, "displayln", args, nargs);
}
static value_t builtin_write(value_t *args, uint32_t nargs)
{
struct printer_options opts;
memset(&opts, 0, sizeof(opts));
opts.shared = 1;
opts.display = (symbol_value(printreadablysym) == FL_F);
return writelike(&opts, "write", args, nargs);
}
static value_t builtin_writeln(value_t *args, uint32_t nargs)
{
struct printer_options opts;
memset(&opts, 0, sizeof(opts));
opts.shared = 1;
opts.newline = 1;
return writelike(&opts, "writeln", args, nargs);
}
static value_t builtin_write_shared(value_t *args, uint32_t nargs)
{
struct printer_options opts;
memset(&opts, 0, sizeof(opts));
opts.shared = 2;
return writelike(&opts, "write-shared", args, nargs);
}
static value_t builtin_write_simple(value_t *args, uint32_t nargs)
{
struct printer_options opts;
memset(&opts, 0, sizeof(opts));
return writelike(&opts, "write-simple", args, nargs);
}
static value_t builtin_newline(value_t *args, uint32_t nargs)
{
struct ios *ios;
if (nargs > 1)
argcount("newline", nargs, 1);
if (nargs == 1)
ios = fl_toiostream(args[0], "newline");
else
ios = fl_toiostream(symbol_value(outstrsym), "newline");
ios_putc('\n', ios);
return FL_T;
}
static struct builtinspec printfunc_info[] = {
{ "display", builtin_display },
{ "displayln", builtin_displayln },
{ "write", builtin_write },
{ "writeln", builtin_writeln },
{ "write-shared", builtin_write_shared },
{ "write-simple", builtin_write_simple },
{ "newline", builtin_newline },
{ NULL, NULL }
};
void print_init(void)
{
htable_new(&pr.cycle_traversed, 32);
assign_global_builtins(printfunc_info);
}
| 2.5 | 2 |
2024-11-18T22:22:05.372867+00:00 | 2020-12-30T09:15:17 | 97de0599a8a394f269d2cb33977ea8eaad8c1ab6 | {
"blob_id": "97de0599a8a394f269d2cb33977ea8eaad8c1ab6",
"branch_name": "refs/heads/master",
"committer_date": "2020-12-30T09:15:17",
"content_id": "5a35a351cdc0f65c22a0d943952978dc009f366d",
"detected_licenses": [
"MIT"
],
"directory_id": "9135087be1626955056f1775e308247088467171",
"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": 294295548,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 41195,
"license": "MIT",
"license_type": "permissive",
"path": "/src/板子测试程序/User_NB_KL36_V3.6_Test_20200906-2/Debug/srcc/main.c",
"provenance": "stackv2-0123.json.gz:12148",
"repo_name": "qiuyeyijian/Embed",
"revision_date": "2020-12-30T09:15:17",
"revision_id": "ff4b9fca473e66c7624a48256bebc143a980e822",
"snapshot_id": "6e4cec18fa1e418c487fbadd1962e809cea5f83f",
"src_encoding": "GB18030",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/qiuyeyijian/Embed/ff4b9fca473e66c7624a48256bebc143a980e822/src/板子测试程序/User_NB_KL36_V3.6_Test_20200906-2/Debug/srcc/main.c",
"visit_date": "2023-02-09T08:34:52.372741"
} | stackv2 | //======================================================================
//文件名称:main.c(应用工程主函数)
//框架提供:苏大arm技术中心(sumcu.suda.edu.cn)
//版本更新:2017.08:1.0, 2019.1:A.10
//功能描述:见本工程的<01_Doc>文件夹下Readme.txt文件
//======================================================================
#define GLOBLE_VAR
#include "includes.h" //包含总头文件
//【根据实际需要增删】初始化程序后,重新烧录126扇区的值
//----------------------------------------------------------------------
//----------------------------------------------------------------------
//【根据实际需要增删】声明使用到的内部函数
//main.c使用的内部函数声明处
void userData_init(UserData *data); //初始化用户帧结构体data
void userData_get(UserData *data); //给用户帧结构体data赋值
void LCD_Showfirst(); //初始化LCD的显示,主要是标签
void ArrayCpy(uint8_t * dest,uint8_t*source,uint16_t len);
void main_Dly_ms(uint32_t ms);
void main_TimeStamp();
void Test_9_PeripheralUnit();
//----------------------------------------------------------------------
//主函数,一般情况下可以认为程序从此开始运行(实际上有启动过程见书稿)
int main(void)
{
//(1)启动部分(开头)======
//(1.1)声明main函数使用的局部变量
uint16_t mi,mj; //主程序使用到的16位循环变量
int mTsi; //记录当前触摸按键次数
uint8_t mSendFlag; //发送数据标志位;1:发送;0:不发送
uint8_t mRetdata[100]; //存放uecom初始化返回的结果
uint16_t mUserLen; //需要发送的字节长度
uint16_t mFlashLen; //需要存储flash的字节长度
uint64_t mRecvCount; //收到的次数
uint8_t mString[30]; //数字转文本使用的临时数组
uint8_t mCmd[2]; //存储命令
uint8_t mflag; //主循环使用的标志判断变量
uint8_t mWriteFlashFlag; //表明是否需要将数据写入flash
uint8_t mLinkCount; //表明基站连接次数
int mLCD_RefreshFlag; //LCD显示刷新标志
uint8_t mSendData[1000]; //待发送数据缓冲区
uint16_t mSendLen; //待发送数据的长度
uint8_t mLBS[30]; //存储LBS定位信息
uint8_t mSec; //存放运行时长,单位:秒
uint8_t mSecOld; //存放运行时长,单位:秒
uint16_t mSendFreq;
uint16_t mSendFreqOld;
uint8_t mUE_infor[40]; //存储UE信息
uint8_t mUpdateUE_flag; //标志位,需要更新模组信息
//(1.2)【不变】关总中断
DISABLE_INTERRUPTS;
//(1.3)给主程序的临时变量赋初值
mTsi=0; //清空触摸按键次数
mSendFlag = 1; //默认终端发送数据
mWriteFlashFlag = 0; //默认不写入flash
mLinkCount=0; //基站连接次数=0
mUserLen = sizeof(UserData); //获得需要发送的字节长度
mFlashLen = sizeof(FlashData); //获得存入flash的字节长度
mRecvCount = 0; //清空接收次数
mLCD_RefreshFlag=0; //LCD显示刷新标志
mSendLen=0;
mSec=0;
mSecOld=0;
mSendFreq=0;
mSendFreqOld=0;
mUpdateUE_flag=1; //标志位,需要更新模组信息
//(1.4)给全局变量赋初值
ArrayCpy(gTimeString,(uint8_t *)"0000-00-00 00:00:00\0",20);
gCount=0;
gUserData.touchNum=0;
//(1.5)用户外设模块初始化
uecom_power(UECOM_OFF);
gpio_init(LIGHT_RED,GPIO_OUTPUT,LIGHT_ON); //初始化红灯
gpio_init(GPIO_TSI,GPIO_INPUT,1); //GPIO模拟触摸
uart_init(UART_UE,115200); //用户串口初始化
timer_init(TIMER_USER,20); //用户计时器初始化
flash_init(); //初始化flash
LCD_Init(); //初始化LCD
adc_init(AD_LIGHT,0); //初始化AD光照模块
adc_init(AD_MCU_TEMP,0); //初始化AD芯片温度模块
//【画瓢处1】-初始化
//(1.6)使能模块中断
timer_enable_int(TIMER_USER); //使能LPTMR中断
//(1.7)【不变】开总中断
ENABLE_INTERRUPTS;
//(1.6)使能模块中断
timer_enable_int(TIMER_USER); //开启定时器中断
//(1.8)给通信模组供电
uecom_power(UECOM_ON);
printf("AHL-IoT-GEC start... \r\n");
//(1.9)【根据实际需要增删】 主循环前的初始化操作
//向Flash最后一个扇区写用户参数
printf("flash_erase and write... \r\n");
flash_erase(MCU_SECTOR_NUM-1); //擦除最后一个扇区
//向最后一个扇区写数据
flash_write((MCU_SECTOR_NUM-1),28,sizeof(FlashData),
(uint8_t *)flashInit);
printf("flash_erase and write...OK \r\n");
//(1.9.1)读取flash中的配置信息至gFlashData;初始化用户帧数据gUserData
//读取Flash中126扇区的参数信息到gFlashData中
flash_read_logic((uint8_t*)(&gFlashData),
(MCU_SECTOR_NUM-1),28,sizeof(FlashData));
userData_init(&gUserData); //初始化用户帧结构体gUserData
LCD_Showfirst(); //LCD显示初始内容
//(1.9.2)判断复位状态,并将复位状态数据存储到flash中(注意不影响原有数据)
if (IS_POWERON_RESET) //冷复位,置零
gFlashData.resetCount = 0;
else //热复位,则加1
{
gFlashData.resetCount++;
flash_read_logic((uint8_t*)gcRecvBuf,(MCU_SECTOR_NUM-1),0,MCU_SECTORSIZE);
flash_erase(MCU_SECTOR_NUM-1);
ArrayCpy(((uint8_t*)gcRecvBuf+166),(uint8_t*)(gFlashData.resetCount),4);
flash_write((MCU_SECTOR_NUM-1),0,MCU_SECTORSIZE,(uint8_t*)gcRecvBuf);
}
//(1.9.3)初始化通信模组,并在LCD上显示初始化过程
//LCD上一行最多显示28个字节
printf("金葫芦提示:进行通信模组初始化... \r\n");
for(;;) //初始化通信模组循环
{
//通信模组上电并等待延时等待约12秒
uecom_power(UECOM_ON); //给通信模组供电
main_Dly_ms(3000); //延时6s
LCD_ShowString(6,300,BLUE,GRAY,"AHL Init . uecom_power ");
printf("金葫芦提示:AHL Init . 给通信模组供电 \r\n");
main_Dly_ms(3000); //延时6s
//通信模组初始化,包括联网和建立网络连接过程
//初始化通信模组
LCD_ShowString(6,300,BLUE,GRAY,"AHL Init .. uecom_init ");
printf("金葫芦提示:AHL Init .. 初始化通信模组 \r\n");
mflag =uecom_init();
if(mflag)
{
if (mflag==1)
LCD_ShowString(6,300,BLUE,GRAY,"AHL Init .. AT Error ");
printf("金葫芦提示:AHL Init .. AT指令错误!\r\n");
if (mflag==2)
LCD_ShowString(6,300,BLUE,GRAY,"AHL Init .. SIM Error ");
printf("金葫芦提示:AHL Init .. 读SIM卡错误!\r\n");
uecom_power(UECOM_OFF); //通信模组重启
continue;
}
//显示设备的IMSI号
uecom_modelInfo(mRetdata); //获取通信模组信息
LCD_ShowString(60,85,BLUE,GRAY,(char *)mRetdata+20);
//与基站建立连接
LCD_ShowString(6,300,BLUE,GRAY,"AHL Init ... uecom_linkBase ");
printf("AHL Init ... 与基站建立连接 \r\n");
mflag =uecom_linkBase();
while(mflag)
{
mflag =uecom_linkBase();
mLinkCount++; //连接次数+1
LCD_ShowString(6,300,BLUE,GRAY,(char *)IntConvertToStr(mLinkCount,mString));
printf("与基站建立连接次数:%d\r\n",mLinkCount);
if(mLinkCount>10) //与基站连接次数
{
mLinkCount=0;
uecom_power(UECOM_OFF); //通信模组重启
main_Dly_ms(2000); //延时
uecom_power(UECOM_REBOOT); //通信模组重启
main_Dly_ms(2000); //延时
mflag =uecom_init();
break;
}
}
if(mflag)
{
LCD_ShowString(6,300,BLUE,GRAY,"AHL Init ...link base Error ");
uecom_power(UECOM_OFF); //通信模组重启
main_Dly_ms(1000); //延时
uecom_power(UECOM_REBOOT); //通信模组重启
main_Dly_ms(1000); //延时
continue;
}
//显示信号强度和小区号(基站号)位置信息 LBS
for(mi=0;mi<5;mi++)
{
mflag = uecom_baseInfo(mRetdata);
if(mflag)
{
main_Dly_ms(1000);
continue;
}
ArrayCpy(mLBS,mRetdata+1,19); //位置信息保存在mLBS中备用
LCD_ShowString(60,131,BLUE,GRAY,(char *)mRetdata+1); //基站位置
LCD_ShowString(170,150,BLUE,GRAY,
(char *)IntConvertToStr(mRetdata[0],(uint8_t*)mString));
}
//与服务器建立连接
LCD_ShowString(6,300,BLUE,GRAY,"AHL Init ....uecom_linkCS ");
printf("AHL Init .... 与云平台建立连接 \r\n");
mflag =uecom_linkCS((uint8_t*)gFlashData.serverIP,(uint8_t*)gFlashData.serverPort);
if(mflag)
{
LCD_ShowString(6,300,BLUE,GRAY,"AHL....Link CS-Monitor Error");
uecom_power(UECOM_REBOOT); //通信模组重启
continue;
}
LCD_ShowString(6,300,BLUE,GRAY,"AHL Init ..... Successfully ");
printf("AHL Init ..... Successfully \r\n");
break;
}
uecom_getTime(gTimeString); //获取基站时间
LCD_ShowString(49,209,BLUE,GRAY,(char *)gTimeString); //在LCD上显示当前时间
printf("NB-IoT communication OK! \n");
//(1)启动部分(结尾)======
printf("Go to Main Loop\r\n");
//(2)主循环部分(开头)======
for(;;)
{
main_loop:
//取秒个位的ASCII码,进行判断
mSec=gTimeString[18];
if (mSec==mSecOld) continue; //一秒未到,回到循环开始处,继续循环
Test_9_PeripheralUnit();
//(2.1)一秒到达之后进行的操作
mSecOld=mSec; //mSecOld变量更新
//在LCD上显示当前时间、控制红灯闪烁、向PC机输出时间
LCD_ShowString(49,209,BLUE,GRAY,(char *)gTimeString); //在LCD上显示当前时间
gpio_reverse(LIGHT_RED); //红灯每秒闪烁一次
printf("当前时间为:%s\r\n",gTimeString);
//(2.1.3)判断是否到达发送数据的时间
mSendFreq++;
if (mSendFreq-mSendFreqOld>=gFlashData.sendFrequencySec)
{
mSendFreqOld=mSendFreq;
mSendFlag = 1; //发送标志置1;
printf("%d 秒时间到,发送一帧数据!\r\n",(int)gFlashData.sendFrequencySec);
printf("\r\n");
}
mj=0;
for (mi=0;mi<3000;mi++)
mj=mj+gpio_get(GPIO_TSI);
if (mj<2000)
{
mTsi++;
printf("触摸次数 = %d\r\n", mTsi);
LCD_ShowString(40,189,BLUE,GRAY,(char *)IntConvertToStr(mTsi,mString)); //LCD上显示TSI触摸次数
printf("\r\n");
if ((mTsi-gUserData.touchNum)>=3)
{
mSendFlag = 1;
printf("触摸三次,发送一帧数据!\r\n");
printf("\r\n");
gUserData.touchNum=mTsi;
printf("触摸次数 ============= %d\n", mTsi);
printf("\r\n");
}
}
//(2.3)若需要执行发送数据操作,则进行下列操作
if(mSendFlag == 1)
{
//(2.3.1)更新用户数据为最新数据
userData_get(&gUserData); //给用户帧结构体gUserData赋值
if(mUpdateUE_flag==1)
{
mUpdateUE_flag=0;
uecom_modelInfo(mUE_infor); //传回UE信息
ArrayCpy(gUserData.IMEI,mUE_infor,15);
ArrayCpy(gUserData.IMSI,mUE_infor+20,15);
uecom_baseInfo(mUE_infor);
gUserData.signalPower = mUE_infor[0];
ArrayCpy(gUserData.lbs_location,mUE_infor+1,19);
}
//(2.3.2)根据命令,获得需要发送的数据
if(gFlashData.frameCmd[0]=='U'&&gFlashData.frameCmd[1]=='0')
{
mSendLen = mUserLen;
ArrayCpy(gUserData.cmd,gFlashData.frameCmd,2);
ArrayCpy(mSendData,(uint8_t *)&gUserData,mSendLen);
}
else if(gFlashData.frameCmd[0]=='U'&&gFlashData.frameCmd[1]=='1')
{
ArrayCpy(mSendData,gFlashData.frameCmd,2);
ArrayCpy(mSendData+2,gUserData.IMSI,15);
//【20200816】
main_TimeStamp(); //给gUserData.currentTime赋值
ArrayCpy(mSendData+17,(uint8_t *)&gUserData.currentTime,8);
ArrayCpy(mSendData+25,(uint8_t *)&gUserData.mcuTemp,4);
ArrayCpy(mSendData+29,(uint8_t *)&gUserData.signalPower,1);
ArrayCpy(mSendData+30,(uint8_t *)&gUserData.bright,2);
ArrayCpy(mSendData+32,(uint8_t *)&gUserData.touchNum,2);
ArrayCpy(mSendData+34,gUserData.lbs_location,25);
//【画瓢处3】更改“U1”命令发送的数据
}
//(2.3.3)显示信号强度
LCD_ShowString(170,150,BLUE,GRAY," ");
LCD_ShowString(170,150,BLUE,GRAY,
(char *)IntConvertToStr(gUserData.signalPower,(uint8_t *)mString));
mLBS[20]='\0';
gUserData.serverIP[13]='\0';
gUserData.IMSI[15]='\0';
printf("信号强度:%d\n\n",gUserData.signalPower);
printf("LBS号:%s\r\n\n",mLBS);
printf("接收次数:%d\n\n",mRecvCount);
printf("IP:PT %s : %s\n\n",gFlashData.serverIP,gFlashData.serverPort);
printf("Frep(s):%d\n\n",gFlashData.sendFrequencySec);
printf("IMSI:%s\n\n",gUserData.IMSI);
//(2.3.4)UE模块发送数据
LCD_ShowString(6,300,BLUE,GRAY,"AHL Send . ");
mflag = uecom_linkCS(gFlashData.serverIP,gFlashData.serverPort);
//【20200818】 发送前确定连接云服务器是否成功,以避免假发送
uint8_t temp=0 ; //连接云服务器次数
if(temp<3&&(mflag!=0))
{
mflag = uecom_linkCS(gFlashData.serverIP,gFlashData.serverPort);
LCD_ShowString(6,300,BLUE,GRAY,"AHL....Link CS-Monitor Error");
uecom_power(UECOM_REBOOT); //通信模组重启
temp++;
}
//【20200818】 三次连接失败,重新初始化
if(mflag!=0)
{
printf("多次连接CS_monitor失败,重新初始化\r\n");
}
//结构体的地址可直接强制转为数组的地址
mflag = uecom_send(mSendLen,mSendData);
LCD_ShowString(6,300,BLUE,GRAY,(char *)"AHL Send .. ");
//if(mflag) goto main_loop_1; //数据发送失败,LCD显示提示
LCD_ShowString(6,300,BLUE,GRAY,(char *)"AHL Send Successfully ");
goto main_loop_2;
main_loop_1:
//数据发送失败提示
switch(mflag)
{
case 1:
LCD_ShowString(6,300,BLUE,GRAY,(char *)"Send Error:Send Not Start ");
break;
case 2:
LCD_ShowString(6,300,BLUE,GRAY,(char *)"Send Error:Send Data Not OK ");
break;
}
//重新初始化
LCD_ShowString(6,300,BLUE,GRAY,(char *)"AHL Reinit . ");
uecom_power(UECOM_OFF); //通信模组重启
main_Dly_ms(3000); //延时
uecom_power(UECOM_REBOOT); //通信模组重启
main_Dly_ms(3000); //延时
uecom_init();
main_Dly_ms(100);
//进行两次初始化(防错)
LCD_ShowString(6,300,BLUE,GRAY,(char *)"AHL Reinit .. ");
if(uecom_init())
LCD_ShowString(6,300,BLUE,GRAY,(char *)"uecom init success ");
else
LCD_ShowString(6,300,BLUE,GRAY,(char *)"uecom init fail ");
if(uecom_linkBase())
LCD_ShowString(6,300,BLUE,GRAY,(char *)"link base success ");
else
LCD_ShowString(6,300,BLUE,GRAY,(char *)"link base fail ");
uecom_getTime(gTimeString); //获取基站时间
mflag = uecom_linkCS(gFlashData.serverIP,gFlashData.serverPort);
int i=0 ; //连接云服务器次数
if(i<3&&(mflag!=0))
{
mflag = uecom_linkCS(gFlashData.serverIP,gFlashData.serverPort);
i++;
}
if(mflag)
LCD_ShowString(6,300,BLUE,GRAY,"AHL Reinit .... Fail ");
else
{
LCD_ShowString(6,300,BLUE,GRAY,"AHL Reinit .... Success ");
//重新初始化成功后进行数据发送
LCD_ShowString(6,300,BLUE,GRAY,"AHL Send . ");
//结构体的地址可直接强制转为数组的地址
mflag = uecom_send(mSendLen,mSendData);
LCD_ShowString(6,300,BLUE,GRAY,"AHL Send .. ");
if(mflag) goto main_loop_1; //数据发送失败,LCD显示提示
LCD_ShowString(6,300,BLUE,GRAY,"AHL Send Successfully ");
}
goto main_loop_2;
main_loop_2:
mSendFlag = 0; //修改发送标记
mSendLen=0;
}
//=====================================发送流程结尾===================================================================
//=====================================回发流程开始==================================================================
//(2.4)判断是否接收到服务器发来数据,回发
//没收到
if (gcRecvLen<=0) goto main_loop; //非更新操作的数据
//收到一个完整的帧(即gcRecvLen>0),数据在gcRecvBuf,字节数为gcRecvLen
mRecvCount++; //接收次数+1
mflag = 0xff;
mSendLen = 0; //发送数据字节数变量
mWriteFlashFlag = 0; //
mLCD_RefreshFlag=1; //LCD显示刷新标志
LCD_ShowString(6,300,BLUE,GRAY,"AHL Recv one frame ");
printf("收到一帧\n");
printf("\r\n");
ArrayCpy(mCmd,gcRecvBuf,2); //命令
ArrayCpy(mSendData,gcRecvBuf,2); //发送数据
//根据命令字节进行处理,为发送数据做准备----------------------
if(mCmd[0]=='A'&&mCmd[1]=='0') //读取flash中的所有信息
{
mSendLen = mFlashLen+2;
ArrayCpy(mSendData+2,(uint8_t*)(&gFlashData),mFlashLen);
}
else if(mCmd[0]=='A'&&mCmd[1]=='1') //读取flash中的产品信息
{
mSendLen = 145;
ArrayCpy(mSendData+2,gFlashData.equipName,mSendLen-2);
}
else if(mCmd[0]=='A'&&mCmd[1]=='2') //读取flash中的服务器信息
{
mSendLen = 22;
ArrayCpy(mSendData+2,gFlashData.serverIP,mSendLen-2);
}
else if(mCmd[0]=='A'&&mCmd[1]=='3') //读取用户存入flash的信息
{
mSendLen = 10;
ArrayCpy(mSendData+2,(uint8_t*)(&gFlashData.sendFrequencySec),mSendLen-2);
}
else if(mCmd[0]=='B'&&mCmd[1]=='0') //更改flash中的所有信息
{
ArrayCpy((uint8_t *)(gFlashData.equipName),(uint8_t*)&(gcRecvBuf[2]),mFlashLen);
mWriteFlashFlag = 1;
mSendLen = 9;
ArrayCpy((uint8_t *)mSendData+2,(uint8_t *)"success",mSendLen-2);
}
else if(mCmd[0]=='B'&&mCmd[1]=='1') //更改flash中的产品信息
{
ArrayCpy((uint8_t *)(gFlashData.equipName),(uint8_t*)&(gcRecvBuf[2]),124);
mWriteFlashFlag = 1;
mSendLen = 9;
ArrayCpy((uint8_t *)mSendData+2,(uint8_t *)"success",mSendLen-2);
}
else if(mCmd[0]=='B'&&mCmd[1]=='2') //更改flash中的服务器信息
{
ArrayCpy((uint8_t *)(gFlashData.serverIP),(uint8_t*)&(gcRecvBuf[2]),30);
mWriteFlashFlag = 1;
mSendLen = 9;
ArrayCpy((uint8_t *)mSendData+2,(uint8_t *)"success",mSendLen-2);
}
else if(mCmd[0]=='B'&&mCmd[1]=='3') //更改用户存入flash的信息
{
ArrayCpy((uint8_t *)(&gFlashData.sendFrequencySec),(uint8_t*)&(gcRecvBuf[2]),8);
mWriteFlashFlag = 1;
mSendLen = 9;
ArrayCpy((uint8_t *)mSendData+2,(uint8_t *)"success",mSendLen-2);
}
else if(mCmd[0]=='U'&&mCmd[1]=='0') //获取“U0”命令要发送的数据
{
ArrayCpy(gFlashData.frameCmd,mCmd,2);
if(gcRecvLen == mUserLen) //若为整帧数据
{
mWriteFlashFlag =1;
ArrayCpy((uint8_t*)(&gUserData),gcRecvBuf,mUserLen);
ArrayCpy(gFlashData.equipName,gUserData.equipName,30);
ArrayCpy(gFlashData.equipID,gUserData.equipID,20);
ArrayCpy(gFlashData.equipType,gUserData.equipType,20);
ArrayCpy(gFlashData.vendor,gUserData.vendor,30);
ArrayCpy(gFlashData.userName,gUserData.userName,20);
ArrayCpy(gFlashData.phone,gUserData.phone,11);
ArrayCpy(gFlashData.serverIP,gUserData.serverIP,15);
ArrayCpy(gFlashData.serverPort,gUserData.serverPort,5);
gFlashData.sendFrequencySec = gUserData.sendFrequencySec;
gFlashData.resetCount = gUserData.resetCount;
ArrayCpy(gFlashData.frameCmd,gUserData.cmd,2);
//【画瓢处2】-执行操作
}
}
else if(mCmd[0]=='U'&&mCmd[1]=='1') //获取“U1”命令要发送的数据
{
ArrayCpy(gFlashData.frameCmd,mCmd,2);
if(gcRecvLen == 59)
{
ArrayCpy(gUserData.cmd,gcRecvBuf,2);
ArrayCpy(gUserData.IMSI,gcRecvBuf+2,15);
ArrayCpy((uint8_t *)&gUserData.currentTime,gcRecvBuf+17,8);
ArrayCpy((uint8_t *)&gUserData.mcuTemp,gcRecvBuf+25,4);
ArrayCpy((uint8_t *)&gUserData.signalPower,gcRecvBuf+29,1);
ArrayCpy((uint8_t *)&gUserData.bright,gcRecvBuf+30,2);
ArrayCpy((uint8_t *)&gUserData.touchNum,gcRecvBuf+32,2);
ArrayCpy(gUserData.lbs_location,gcRecvBuf+34,25);
}
}
if (mSendLen>0) //若有需要发送的数据
{
mflag = uecom_send(mSendLen,mSendData); //数据发送
}
gcRecvLen = 0; //接收数据长度清零,表明已经读取
if(mflag==0)
LCD_ShowString(6,300,BLUE,GRAY,"AHL Reply Successfully ");
else if(mflag == 0xff)
LCD_ShowString(6,300,BLUE,GRAY,"AHL Recv Successfully ");
else
LCD_ShowString(6,300,BLUE,GRAY,"Send Error:Send Data Not OK ");
//判断是否需要写flash
if(mWriteFlashFlag == 1)
{
flash_read_logic((uint8_t*)gcRecvBuf,(MCU_SECTOR_NUM-1),0,MCU_SECTORSIZE);
flash_erase(MCU_SECTOR_NUM-1);
ArrayCpy(((uint8_t*)gcRecvBuf+28),(uint8_t*)(&gFlashData),mFlashLen);
flash_write((MCU_SECTOR_NUM-1),0,MCU_SECTORSIZE,(uint8_t*)gcRecvBuf);
mWriteFlashFlag = 0;
}
//
if (mLCD_RefreshFlag==1)
{
LCD_Showfirst(); //更新LCD上的显示
mLCD_RefreshFlag=0;
//补充显示显示设备的IMSI号、基站位置信息、接收次数
uecom_modelInfo(mRetdata); //获取通信模组信息
LCD_ShowString(60,85,BLUE,GRAY,(char *)mRetdata+20);
LCD_ShowString(60,131,BLUE,GRAY,(char *)mLBS); //基站位置
LCD_ShowString(90,251,BLUE,GRAY,(char *)IntConvertToStr(mRecvCount,mString));
}
}
//图形化编程之主循环流程扫描分支添加处【Graphic12】*/
}
//======以下为主函数调用的子函数======
//=====================================================================
//函数名称:showState
//函数返回:无
//参数说明:无
//功能概要:测试功能构件函数
//=====================================================================
void Test_9_PeripheralUnit()
{
uint8_t mString[30];
//加速度传感器使用的变量
uint8_t xyzData[6]; //x、y、z轴倾角,均占两个字节
uint16_t xdata,ydata,zdata; //x轴倾角
uint8_t checkdata; //ADLX345的验证数据,正确接收为0xe5
//(1)测试彩灯
//一种彩灯颜色占3个字节,按grb顺序
uint8_t grbw[12]={0xFF,0x00,0x00,0x00,0xFF,0x00,0x00,0x00,0xFF,0xFF,0xFF,0xFF};
uint8_t rwgb[12]={0x00,0xFF,0x00,0xFF,0xFF,0xFF,0xFF,0x00,0x00,0x00,0x00,0xFF};
uint8_t black[12]={0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};
static char OutputCtl=0;
OutputCtl++;
if (OutputCtl>=4) OutputCtl=1;
WS_Init(COLORLIGHT);
//(1)彩灯测试数据
switch (OutputCtl)
{
case 1:
printf("点亮彩灯\r\n\r\n");
WS_SendOnePix(COLORLIGHT,grbw,4);
break;
case 2:
printf("熄灭彩灯\r\n\r\n");
WS_SendOnePix(COLORLIGHT,black,4);
break;
case 3:
printf("改变彩灯颜色\r\n\r\n");
WS_SendOnePix(COLORLIGHT,rwgb,4);
break;
default:
break;
}
//(2)蜂鸣器测试数据
switch (OutputCtl)
{
case 1:
printf("蜂鸣器发出声音\r\n\r\n");
gpio_init(BEEF,GPIO_OUTPUT,1);
break;
case 2:
printf("蜂鸣器停止发出声音\r\n\r\n");
gpio_init(BEEF,GPIO_OUTPUT,0);
break;
case 3:
printf("蜂鸣器发出声音\r\n\r\n");
gpio_init(BEEF,GPIO_OUTPUT,1);
break;
default:
break;
}
//(3)振动马达测试
switch (OutputCtl)
{
case 1:
printf("马达开始振动\r\n\r\n");
gpio_init(MOTOR,GPIO_OUTPUT,1);
break;
case 2:
printf("马达停止振动\r\n\r\n");
gpio_init(MOTOR,GPIO_OUTPUT,0);
break;
case 3:
printf("马达再次振动\n\0");
gpio_init(MOTOR,GPIO_OUTPUT,1);
break;
default:
break;
}
//(4)数码管测试数据
TM1637_Init(TM1637_CLK,TM1637_DIO);
switch (OutputCtl)
{
case 1:
printf("显示1234\r\n\r\n");
TM1637_Display(1,1,2,1,3,1,4,1);
break;
case 2:
printf("显示4321\r\n\r\n");
TM1637_Display(4,1,3,1,2,1,1,1);
break;
case 3:
printf("显示8888\r\n\r\n");
TM1637_Display(8,1,8,1,8,1,8,1);
break;
default:
break;
}
//(5)红外寻迹测试数据
gpio_init(RAY_RIGHT,GPIO_INPUT,0); //初始化红外循迹传感器两个引脚 设置为低电平输入
gpio_init(RAY_LEFT,GPIO_INPUT,0);
gpio_pull(RAY_RIGHT,0);
gpio_pull(RAY_LEFT,0);
if (gpio_get(RAY_LEFT))
{
printf("左侧红外:有物体\r\n\r\n");
LCD_ShowString(6,253,BLACK,GRAY,"[RAY-L] ");
}
else
{
printf("左侧红外:无物体\r\n\r\n");
}
if (gpio_get(RAY_RIGHT))
{
printf("右侧红外:有物体\r\n\r\n");
LCD_ShowString(66,253,BLACK,GRAY,"[RAY-R] ");
}
else
{
printf("右侧红外:无物体\r\n\r\n");
}
// (6)人体红外测试数据
gpio_init(RAY_HUMAN,GPIO_INPUT,0); //初始化红灯和人体红外传感器模块
gpio_pull(RAY_HUMAN,0);
if (gpio_get(RAY_HUMAN))
{
printf("红外:监测有人\r\n\r\n");
LCD_ShowString(126,253,BLACK,GRAY,"[RAY] ");
}
else
{
printf("红外:监测无人\r\n\r\n");
}
//(7)Button测试数据
gpio_init(Button1,GPIO_OUTPUT,0);
gpio_init(Button3,GPIO_INPUT,0);
gpio_pull(Button3,1);
if (gpio_get(Button3)==0)
{
printf("S301-------------\r\n\r\n");
LCD_ShowString(6,253,BLACK,GRAY,"[S301] ");
goto Test_9_PeripheralUnit_1;
}
gpio_init(Button4,GPIO_INPUT,0);
gpio_pull(Button4,1);
if (gpio_get(Button4)==0)
{
printf("S302-------------\r\n\r\n");
LCD_ShowString(6,253,BLACK,GRAY,"[S302] ");
goto Test_9_PeripheralUnit_1;
}
gpio_init(Button3,GPIO_OUTPUT,0);
gpio_init(Button2,GPIO_INPUT,0);
gpio_pull(Button2,1);
if (gpio_get(Button2)==0)
{
printf("S303-------------\r\n\r\n");
LCD_ShowString(6,253,BLACK,GRAY,"[S303] ");
goto Test_9_PeripheralUnit_1;
}
gpio_init(Button4,GPIO_OUTPUT,0);
gpio_init(Button2,GPIO_INPUT,0);
gpio_pull(Button2,1);
if (gpio_get(Button2)==0)
{
printf("S304-------------\r\n\r\n");
LCD_ShowString(6,253,BLACK,GRAY,"[S304] ");
goto Test_9_PeripheralUnit_1;
}
Test_9_PeripheralUnit_1:
//(8)声音传感器测试数据
adc_init(ADCSound,16); //初始化ADC,ADC引脚为GEC_48(PTB_NUM|1),采样精度16
printf("采集声音AD值为:%d\n",adc_read(ADCSound));//输出声音传感器ADC值
LCD_ShowString(186,253,BLACK,GRAY,(char *)" ");
LCD_ShowString(186,253,BLACK,GRAY,(char *)IntConvertToStr(adc_read(ADCSound),mString));
//(9)加速度传感器测试数据
adlx345_init(i2cAcceleration,0x0B,0x08,0x08,0x80,0x00,0x00,0x05);//初始化ADLX345(J2端口)
adlx345_read1(0x00,&checkdata); //读取adxl345校验数据
adlx345_init(0,0x0B,0x08,0x08,0x80,0x00,0x00,0x05);//初始化ADLX345(J2端口)
adlx345_read1(0x00,&checkdata); //读取adxl345校验数据
main_Dly_ms(5);
adlx345_readN(0x32,xyzData,6); //读倾角传感器数值
xdata = (xyzData[1]<<8)+xyzData[0]; //x方向倾角
ydata = (xyzData[3]<<8)+xyzData[2]; //y方向倾角
zdata = (xyzData[5]<<8)+xyzData[4]; //z方向倾角
printf("输出x方向倾角:%d\r\n\r\n",xdata); //输出x方向倾角
printf("输出y方向倾角:%d\r\n\r\n",ydata); //输出y方向倾角
printf("输出z方向倾角:%d\n\r\n\r\n",zdata); //输出z方向倾角
LCD_ShowString(90,278,BLACK,GRAY,(char *)IntConvertToStr(xdata,mString));
LCD_ShowString(140,278,BLACK,GRAY,(char *)IntConvertToStr(ydata,mString));
LCD_ShowString(190,278,BLACK,GRAY,(char *)IntConvertToStr(zdata,mString));
}
//=====================================================================
//函数名称:userData_init
//函数返回:无
//参数说明:data:需要初始化的结构体数据
//功能概要:初始化用户帧结构体data
//=====================================================================
void userData_init(UserData *data) //初始化用户帧结构体
{
uint8_t mString[10];
ArrayCpy(data->cmd,(uint8_t *)"U0",2);
ArrayCpy(gFlashData.frameCmd,data->cmd,2);
data->sn = 0;
ArrayCpy(data->serverIP,gFlashData.serverIP,15);
ArrayCpy(data->serverPort,gFlashData.serverPort,5);
data->currentTime = gFlashData.productTime;
data->resetCount = gFlashData.resetCount;
data->sendFrequencySec = gFlashData.sendFrequencySec;
ArrayCpy(data->userName,gFlashData.userName,20);
//[2018.8.18] 发送的软件版本取BIOS
uecom_version(mString);//??????????????????????
ArrayCpy(data->softVer,mString,4);
ArrayCpy(data->equipName,gFlashData.equipName,30);
ArrayCpy(data->equipID,gFlashData.equipID,20);
ArrayCpy(data->equipType,gFlashData.equipType,20);
ArrayCpy(data->vendor,gFlashData.vendor,30);
ArrayCpy(data->phone,gFlashData.phone,11);
data->touchNum = 0;
ArrayCpy(data->cmd,gFlashData.frameCmd,2);
//【画瓢处2】-初始化数据
}
//=====================================================================
//函数名称:userData_get
//函数返回:无
//参数说明:data:需要赋值的结构体数据
//功能概要:给用户帧结构体data赋值
//=====================================================================
void userData_get(UserData *data) //给用户帧结构体data赋值
{
uint16_t brightAD,mcu_temp_AD;
char mStr[6];
float mcu_temp;
static uint32_t sn = 0;
data->sn = sn++;
//获取mcu温度
mcu_temp_AD = adc_read(AD_MCU_TEMP); //读取mcu温度通道AD值
mcu_temp=TempTrans(mcu_temp_AD); //温度回归
LCD_ShowString(150,105,BLUE,GRAY,(char *)FloatConvertToStr(mcu_temp,1,mStr)); //LCD上显示芯片温度
data->mcuTemp =(int32_t) (mcu_temp*10);
printf("芯片温度=%6.2f\r\n",mcu_temp);
printf("\r\n");
//获取光照强度
brightAD = adc_read(AD_LIGHT);
data->bright = brightAD;
main_TimeStamp(); //给gUserData.currentTime赋值
//【画瓢处1】-数据获取
}
//=====================================================================
//函数名称:LCD_Showfirst
//函数返回:无
//参数说明:无
//功能概要:初始化LCD上电显示的内容
//=====================================================================
void LCD_Showfirst()
{
uint8_t temp[30] = {0};
//uint8_t tempertature[6];
//(1)设置全局底色为灰色
LCD_DrawSurface(0,0,240,320,GRAY); //240*320像素LCD
//(2)设置第一区(标题区)
LCD_aotu(2,2,238,38,1); //LCD指定区域凸起
LCD_ShowString(66,15,RED,GRAY,"金葫芦IoT-GEC"); //红字
wdog_feed();
//(3)设置第二区(与通信无关区)
LCD_aotu(2,43,238,123,0); //LCD指定区域凹下
//显示型号
LCD_ShowString(6,45,BLACK,GRAY,"[Type] ");
uecom_typeGet(temp);
temp[20]=0;
LCD_ShowString(60,45,BLUE,GRAY,(char *)temp);
//显示BIOS软件版本
wdog_feed();
LCD_ShowString(6,65,BLACK,GRAY,"[BIOS] ");
uecom_version(temp); //取uecom版本号(作为BIOS版本号)
LCD_ShowString(58,65,BLUE,GRAY,(char *)temp); //显示BIOS软件版本
//显示user软件版本
LCD_ShowString(120,65,BLACK,GRAY,"[USER] ");
ArrayCpy(temp,gFlashData.softVer,4);
temp[5]=0;
LCD_ShowString(172,65,BLUE,GRAY,(char *)temp);
//显示IMSI提示
LCD_ShowString(6,85,BLACK,GRAY,"[IMSI] ");
//显示MCU温度
LCD_ShowString(6,105,BLACK,GRAY,"[MCU_temperature] ");
//(4)设置第三区(与通信相关)
LCD_aotu(2,127,238,228,1); //LCD指定区域凸起
LCD_ShowString(6,131,BLACK,GRAY,"[LBS] ");
LCD_ShowString(6,149,BLACK,GRAY,"[Signal strength(%)] ");
//显示IP:PT (IP:PORT)
LCD_ShowString(6,169,BLACK,GRAY,"[IP:PT] ");
ArrayCpy(temp,gFlashData.serverIP,15);
temp[15]=0;
LCD_ShowString(65,169,BLUE,GRAY,(char *)temp);
LCD_ShowString(185,169,BLUE,GRAY,":");
ArrayCpy(temp,gFlashData.serverPort,5);
temp[5]=0;
LCD_ShowString(195,169,BLUE,GRAY,(char *)temp);
//显示发送频率
LCD_ShowString(6,189,BLACK,GRAY,"TSI: Freq(s): ");
LCD_ShowString(180,189,BLUE,GRAY," ");
LCD_ShowString(180,189,BLUE,GRAY,
(char *)IntConvertToStr(gFlashData.sendFrequencySec,temp));
LCD_ShowString(40,189,BLUE,GRAY,"0"); //显示TSI次数初值0
LCD_ShowString(6,209,BLACK,GRAY,"Time: ");
LCD_ShowString(49,209,BLUE,GRAY,"0000-00-00 00:00:00" );
LCD_aotu(2,232,238,271,0); //LCD指定区域凹下
LCD_ShowString(6,235,BLACK,GRAY,"5-year flow fee(2020-2024) ");
LCD_ShowString(6,253,BLACK,GRAY,"RecvCount: ");
//(5)设置第四区(运行状态显示区)
LCD_aotu(2,275,238,317,1); //LCD指定区域凸起
LCD_ShowString(6,278,BLACK,GRAY,"Run State: ");
}
//图形化编程之main文件子函数添加处【Graphic13】
//=====================================================================
//函数名称:ArrayCpy
//函数返回:无
//参数说明:dest:复制后存放的数组;source:被复制的数组;len:复制的长度
//功能概要:从源数组复制指定长度的内容到目标数组
//=====================================================================
void ArrayCpy(uint8_t * dest,uint8_t*source,uint16_t len)
{
for(uint16_t r=0;r<len;r++) dest[r]=source[r];
}
void main_Dly_ms(uint32_t ms)
{
for(uint32_t i= 0; i < (6000*ms); i++) __asm("nop");
}
void main_TimeStamp()
{
//年月日时分秒 十进制
uint16_t tyear,tmonth,tday,thour,tmin,tsec;
uint16_t i;
uint64_t timestamp; //时间戳
uint8_t st[20];
//每月份之前的天数,闰年另计
uint16_t MonthDay[12]={31,59,90,120,151,181,212,243,273,304,334,365};
timestamp=0;
//将年份化为十进制
for (i=0;i<=3;i++) st[i]=gTimeString[i]-0x30;
tyear=st[0]*1000+st[1]*100+st[2]*10+st[3];
//将月份化为十进制
for (i=5;i<=6;i++) st[i]=gTimeString[i]-0x30;
tmonth=st[5]*10+st[6];
//将天化为十进制
for (i=8;i<=9;i++) st[i]=gTimeString[i]-0x30;
tday=st[8]*10+st[9];
//将时化为十进制
for (i=11;i<=12;i++) st[i]=gTimeString[i]-0x30;
thour=st[11]*10+st[12];
//将分化为十进制
for (i=14;i<=15;i++) st[i]=gTimeString[i]-0x30;
tmin=st[14]*10+st[15];
//将秒化为十进制
for (i=17;i<=18;i++) st[i]=gTimeString[i]-0x30;
tsec=st[17]*10+st[18];
//计算之前年份的秒数
for(i=1970;i<tyear;i++)
{
if(i%4)
timestamp+=31536000;
else
timestamp+=31622400;
}
//计算之前月份的秒数
if(tmonth>12) return;
if(tmonth>2 && tyear%4)
timestamp+=MonthDay[tmonth-2]*24*3600;
else if(tmonth>2 && (tyear%4==0))
timestamp+=(MonthDay[tmonth-2]+1)*24*3600;
else if(tmonth==2)
timestamp+=31*24*3600;
else
timestamp+=0;
//计算当前天的秒数
if(tday>1) timestamp+=(tday-1)*24*3600;
timestamp+=(thour*3600)+(tmin*60)+tsec;
gUserData.currentTime=timestamp;
}
/*
知识要素:
1.main.c是一个具体的实例,执行相关程序流程不会涉及任何环境,芯片问题。
该文件所有代码均不会涉及具体的硬件和环境,它通过调用相关构件来实现与硬件
系统的交互。
2.本文件共有两类代码,一类为【根据实际需要增删】,此类代码根据具体
项目需求进行更改;另一类为【不变】,此类代码与具体项目无关,是通用的,
无需根据具体项目进行更改。
3.本文件对宏GLOBLE_VAR进行了定义, 所以在包含"includes.h"头文件时
会定义全局变量,在其他文件中包含"includes.h"头文件时,仅声明该头文件中
的全局变量。
*/
| 2.34375 | 2 |
2024-11-18T22:22:05.451268+00:00 | 2017-12-11T14:17:37 | 53bfe0278fb4d3e92667f5368d20f6cd548e653b | {
"blob_id": "53bfe0278fb4d3e92667f5368d20f6cd548e653b",
"branch_name": "refs/heads/master",
"committer_date": "2017-12-11T14:17:37",
"content_id": "c91dd09ce1b07d5939e5dd1188db4b7627574aef",
"detected_licenses": [
"MIT"
],
"directory_id": "659912363a09fa2487cdee77e80bfae12d78caa6",
"extension": "c",
"filename": "fstack_protector_all.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 105525588,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 416,
"license": "MIT",
"license_type": "permissive",
"path": "/Labo_2/fstack_protector_all.c",
"provenance": "stackv2-0123.json.gz:12279",
"repo_name": "Muscaw/SeS",
"revision_date": "2017-12-11T14:17:37",
"revision_id": "7adaf43625c3c6d48d6fd2feb167148258d8ad16",
"snapshot_id": "473209acb7cbff7433cb2411bba4ca69d94d09a1",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Muscaw/SeS/7adaf43625c3c6d48d6fd2feb167148258d8ad16/Labo_2/fstack_protector_all.c",
"visit_date": "2021-08-28T07:04:41.299348"
} | stackv2 | /*
* (C) Copyright 2000
* Wolfgang Denk, DENX Software Engineering, wd@denx.de.
*
* SPDX-License-Identifier: GPL-2.0+
*/
#include <stdio.h>
#include <stdlib.h>
unsigned char localBufferOverflow (void)
{
unsigned char val [16];
int i;
for (i=0; i< 40; i++)
{
val[i] = 'a';
}
return val[0];
}
int main (int argc, char * const argv[])
{
printf("Value[0] = %c\n", localBufferOverflow());
return 0;
}
| 2.84375 | 3 |
2024-11-18T22:22:05.888259+00:00 | 2019-09-30T15:06:16 | 816414e977cc5f62573f98bd23118546e4986cc2 | {
"blob_id": "816414e977cc5f62573f98bd23118546e4986cc2",
"branch_name": "refs/heads/master",
"committer_date": "2019-09-30T15:06:16",
"content_id": "6d5a8dba5974a1f6f5325206fd2300c8e0a01377",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "dda8e991f487f5849ca3c64a312bb20bccd8cac4",
"extension": "c",
"filename": "crawl_folders.c",
"fork_events_count": 2,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 1839294,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3575,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/sbr/crawl_folders.c",
"provenance": "stackv2-0123.json.gz:12667",
"repo_name": "mcr/nmh",
"revision_date": "2019-09-30T15:06:16",
"revision_id": "e9d8f9d13bb4396be20832b2c1ec003f3edbe9ed",
"snapshot_id": "cf897f44612be9b7d8f4bd12d4921e5e3ae18937",
"src_encoding": "UTF-8",
"star_events_count": 6,
"url": "https://raw.githubusercontent.com/mcr/nmh/e9d8f9d13bb4396be20832b2c1ec003f3edbe9ed/sbr/crawl_folders.c",
"visit_date": "2021-03-12T19:56:01.610850"
} | stackv2 | /* crawl_folders.c -- crawl folder hierarchy
*
* This code is Copyright (c) 2008, by the authors of nmh. See the
* COPYRIGHT file in the root directory of the nmh distribution for
* complete copyright information.
*/
#include "h/mh.h"
#include "concat.h"
#include "error.h"
#include "crawl_folders.h"
#include "h/utils.h"
struct crawl_context {
int max; /* how many folders we currently can hold in
* the array `folders', increased by
* CRAWL_NUMFOLDERS at a time */
char **folders; /* the array of folders */
int start;
int foldp;
};
/*
* Add the folder name into the
* list in a sorted fashion.
*/
static void
add_folder (char *fold, struct crawl_context *crawl)
{
int i, j;
/* if necessary, reallocate the space for folder names */
if (crawl->foldp >= crawl->max) {
crawl->max += CRAWL_NUMFOLDERS;
crawl->folders = mh_xrealloc (crawl->folders,
crawl->max * sizeof(char *));
}
for (i = crawl->start; i < crawl->foldp; i++)
if (strcmp (fold, crawl->folders[i]) < 0) {
for (j = crawl->foldp - 1; j >= i; j--)
crawl->folders[j + 1] = crawl->folders[j];
crawl->foldp++;
crawl->folders[i] = fold;
return;
}
crawl->folders[crawl->foldp++] = fold;
}
static void
add_children (char *name, struct crawl_context *crawl)
{
char *prefix, *child;
struct stat st;
struct dirent *dp;
DIR * dd;
int child_is_folder;
if (!(dd = opendir (name))) {
admonish (name, "unable to read directory ");
return;
}
if (strcmp (name, ".") == 0) {
prefix = mh_xstrdup("");
} else {
prefix = concat(name, "/", NULL);
}
while ((dp = readdir (dd))) {
/* If the system supports it, try to skip processing of children we
* know are not directories or symlinks. */
child_is_folder = -1;
#if defined(HAVE_STRUCT_DIRENT_D_TYPE)
if (dp->d_type == DT_DIR) {
child_is_folder = 1;
} else if (dp->d_type != DT_LNK && dp->d_type != DT_UNKNOWN) {
continue;
}
#endif
if (!strcmp (dp->d_name, ".") || !strcmp (dp->d_name, "..")) {
continue;
}
child = concat(prefix, dp->d_name, NULL);
/* If we have no d_type or d_type is DT_LNK or DT_UNKNOWN, stat the
* child to see what it is. */
if (child_is_folder == -1) {
child_is_folder = (stat (child, &st) != -1 && S_ISDIR(st.st_mode));
}
if (child_is_folder) {
/* add_folder saves child in the list, don't free it */
add_folder (child, crawl);
} else {
free (child);
}
}
closedir (dd);
free(prefix);
}
static void
crawl_folders_body (struct crawl_context *crawl,
char *dir, crawl_callback_t *callback, void *baton)
{
int i;
int os = crawl->start;
int of = crawl->foldp;
crawl->start = crawl->foldp;
add_children (dir, crawl);
for (i = crawl->start; i < crawl->foldp; i++) {
char *fold = crawl->folders[i];
int crawl_children = 1;
if (callback != NULL) {
crawl_children = callback (fold, baton);
}
if (crawl_children) {
crawl_folders_body (crawl, fold, callback, baton);
}
}
crawl->start = os;
crawl->foldp = of;
}
void
crawl_folders (char *dir, crawl_callback_t *callback, void *baton)
{
struct crawl_context *crawl;
NEW(crawl);
crawl->max = CRAWL_NUMFOLDERS;
crawl->start = crawl->foldp = 0;
crawl->folders = mh_xmalloc (crawl->max * sizeof(*crawl->folders));
crawl_folders_body (crawl, dir, callback, baton);
/* Note that we "leak" the folder names, on the assumption that the caller
* is using them. */
free (crawl->folders);
free (crawl);
}
| 2.734375 | 3 |
2024-11-18T22:22:06.044382+00:00 | 2018-08-03T12:52:59 | 92e0cab5815bf227191a7378163947ea58166f16 | {
"blob_id": "92e0cab5815bf227191a7378163947ea58166f16",
"branch_name": "refs/heads/master",
"committer_date": "2018-08-03T16:38:50",
"content_id": "2c49a3344bcc017d917b8d80b046881d0558d99b",
"detected_licenses": [
"MIT"
],
"directory_id": "5d0234c3b7edeeaaa2aae3d5d32d468ab04fb0bb",
"extension": "c",
"filename": "main.c",
"fork_events_count": 14,
"gha_created_at": "2014-08-17T22:54:51",
"gha_event_created_at": "2018-08-03T16:38:51",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 23052321,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 816,
"license": "MIT",
"license_type": "permissive",
"path": "/src/run_hist/main.c",
"provenance": "stackv2-0123.json.gz:12924",
"repo_name": "uluyol/xmenu",
"revision_date": "2018-08-03T12:52:59",
"revision_id": "2d6fa09401490de87727ec9da8f9ae8b2cdb1e7d",
"snapshot_id": "999f9c561ecb7dbd782f4e005a81007495be2ed7",
"src_encoding": "UTF-8",
"star_events_count": 36,
"url": "https://raw.githubusercontent.com/uluyol/xmenu/2d6fa09401490de87727ec9da8f9ae8b2cdb1e7d/src/run_hist/main.c",
"visit_date": "2021-01-22T03:05:24.681797"
} | stackv2 | #include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "history.h"
static HistSlice history;
bool inhistory(const char *s) {
for (size_t i = 0; i < history.len; i++) {
if (strcmp(s, history.arr[i].s) == 0) {
return true;
}
}
return false;
}
int main(int argc, const char **argv) {
if (argc != 2) {
fprintf(stderr, "usage: %s /path/to/history/file\n", argv[0]);
return 1;
}
if (loadhist(&history, argv[1]) != 0) {
return 1;
}
for (size_t i = 0; i < history.len; i++) {
printf("%s", history.arr[i].s);
}
char *buf = NULL;
size_t cap = 0;
size_t len = 0;
while ((len = getline(&buf, &cap, stdin)) != (size_t)(-1)) {
if (!inhistory(buf)) {
printf("%s", buf);
}
}
free(buf);
return 0;
} | 2.453125 | 2 |
2024-11-18T22:22:06.118881+00:00 | 2020-09-07T02:35:49 | 7466cd7fafb493511883cc5b628b68ae74ce0aa3 | {
"blob_id": "7466cd7fafb493511883cc5b628b68ae74ce0aa3",
"branch_name": "refs/heads/master",
"committer_date": "2020-09-07T02:35:50",
"content_id": "51ab2377731a9780a1c3a5b8e34ae905ae43d439",
"detected_licenses": [
"MIT"
],
"directory_id": "00e49c2ed2f768f6836e1f048774cab5f0330f2d",
"extension": "c",
"filename": "symmetry.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 293403489,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 862,
"license": "MIT",
"license_type": "permissive",
"path": "/102architect_2017/src/symmetry.c",
"provenance": "stackv2-0123.json.gz:13052",
"repo_name": "ltabis/epitech-projects",
"revision_date": "2020-09-07T02:35:49",
"revision_id": "e38b3f00a4ac44c969d5e4880cd65084dc2c870a",
"snapshot_id": "9925d446fec06b3d3110e6233600246577b4cf82",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/ltabis/epitech-projects/e38b3f00a4ac44c969d5e4880cd65084dc2c870a/102architect_2017/src/symmetry.c",
"visit_date": "2022-12-08T17:54:08.234635"
} | stackv2 | /*
** EPITECH PROJECT, 2017
** symmetrie.c
** File description:
** symmetrie functions for the 102architect project
*/
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "../include/proto.h"
#define PI 3.14159265
float **do_symmetry(int rot)
{
double ar = rot;
unsigned int j = 0;
unsigned int i = 0;
float **rotate_matrix = malloc(sizeof(float) * 3);
ar = ar * PI / 180;
if (rotate_matrix == NULL)
exit(84);
for (i = 0; i < 3; i++) {
rotate_matrix[i] = malloc(sizeof(float) * 3);
if (rotate_matrix[i] == NULL)
exit(84);
for (j = 0; j < 3; j++) {
rotate_matrix[i][j] = 0;
}
}
for (i = 0; i < 3; i++)
rotate_matrix[i][i] = 1;
rotate_matrix[0][0] = cos(2 * ar);
rotate_matrix[0][1] = sin(2 * ar);
rotate_matrix[1][0] = sin(2 * ar);
rotate_matrix[1][1] = -cos(2 * ar);
return (rotate_matrix);
}
| 3.0625 | 3 |
2024-11-18T22:22:07.329126+00:00 | 2020-05-31T11:04:00 | 7a5a76cd8b30f8216f50c3c736309eb29c9978db | {
"blob_id": "7a5a76cd8b30f8216f50c3c736309eb29c9978db",
"branch_name": "refs/heads/master",
"committer_date": "2020-05-31T11:04:00",
"content_id": "2f024f28378c062e08c5edfaa4fcb8576951be98",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "a0aec8445d45660b0a1ff951596b0be80825b711",
"extension": "c",
"filename": "gpu_mem_util.c",
"fork_events_count": 1,
"gha_created_at": "2018-09-30T17:03:21",
"gha_event_created_at": "2020-05-31T11:04:01",
"gha_language": "C",
"gha_license_id": "BSD-2-Clause",
"github_id": 150987216,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 833,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/rpi3b-meaty-skeleton/kernel/graphics/gpu_mem_util.c",
"provenance": "stackv2-0123.json.gz:13826",
"repo_name": "zeoneo/rpi3b-bare-metal",
"revision_date": "2020-05-31T11:04:00",
"revision_id": "a8330f51c88ef6dfced4d5ec54ab9d5e8c351a57",
"snapshot_id": "8ab9a9ebf531a39b4da45241feb5860a787fbfc6",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/zeoneo/rpi3b-bare-metal/a8330f51c88ef6dfced4d5ec54ab9d5e8c351a57/rpi3b-meaty-skeleton/kernel/graphics/gpu_mem_util.c",
"visit_date": "2021-07-13T14:19:17.056129"
} | stackv2 | #include <graphics/gpu_mem_util.h>
struct __attribute__((__packed__, aligned(1))) EMITDATA
{
uint8_t byte1;
uint8_t byte2;
uint8_t byte3;
uint8_t byte4;
};
void emit_uint8_t(uint8_t **list, uint8_t d)
{
*((*list)++) = d;
}
void emit_uint16_t(uint8_t **list, uint16_t d)
{
struct EMITDATA *data = (struct EMITDATA *)&d;
*((*list)++) = (*data).byte1;
*((*list)++) = (*data).byte2;
}
void emit_uint32_t(uint8_t **list, uint32_t d)
{
struct EMITDATA *data = (struct EMITDATA *)&d;
*((*list)++) = (*data).byte1;
*((*list)++) = (*data).byte2;
*((*list)++) = (*data).byte3;
*((*list)++) = (*data).byte4;
}
void emit_float(uint8_t **list, float f)
{
struct EMITDATA *data = (struct EMITDATA *)&f;
*((*list)++) = (*data).byte1;
*((*list)++) = (*data).byte2;
*((*list)++) = (*data).byte3;
*((*list)++) = (*data).byte4;
} | 2.453125 | 2 |
2024-11-18T22:22:08.879104+00:00 | 2023-06-04T09:19:36 | 3a715ee6a2f028af82c2ffa2e5908a74a4afa678 | {
"blob_id": "3a715ee6a2f028af82c2ffa2e5908a74a4afa678",
"branch_name": "refs/heads/master",
"committer_date": "2023-06-04T09:19:36",
"content_id": "7639b60efe245bf7716aee711816eab92d4aa110",
"detected_licenses": [
"MIT"
],
"directory_id": "873b3289e7e2c5945687454d01214db3290a4240",
"extension": "c",
"filename": "E.c",
"fork_events_count": 8,
"gha_created_at": "2019-12-29T13:43:37",
"gha_event_created_at": "2022-05-25T15:36:33",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 230755863,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 303,
"license": "MIT",
"license_type": "permissive",
"path": "/UESTC-Programming-Course/Grade 1/Chapter 8/Homework 2/E.c",
"provenance": "stackv2-0123.json.gz:13958",
"repo_name": "HeRaNO/ChickenRibs",
"revision_date": "2023-06-04T09:19:36",
"revision_id": "ff6f1bfad4e3e86294784f32de99abbea001e25a",
"snapshot_id": "ad8dbbc4163af3db22fdcd59dae94830e5f5726c",
"src_encoding": "UTF-8",
"star_events_count": 17,
"url": "https://raw.githubusercontent.com/HeRaNO/ChickenRibs/ff6f1bfad4e3e86294784f32de99abbea001e25a/UESTC-Programming-Course/Grade 1/Chapter 8/Homework 2/E.c",
"visit_date": "2023-06-08T16:45:00.271629"
} | stackv2 | #include <stdio.h>
#include <string.h>
int main()
{
char a[100],b[100];int n,i;
puts("Enter a first and last name: ");
scanf("%s",a);scanf("%s",b);
n=strlen(b);
printf("You entered the name: ");
for (i=0;i<n;i++) putchar(b[i]);
putchar(',');putchar(' ');putchar(a[0]);putchar('.');
return 0;
}
| 2.796875 | 3 |
2024-11-18T22:22:08.950168+00:00 | 2017-02-16T04:18:07 | baf1c8aa4ffdd3c7a7fb3ef2c09908a0c4709f75 | {
"blob_id": "baf1c8aa4ffdd3c7a7fb3ef2c09908a0c4709f75",
"branch_name": "refs/heads/master",
"committer_date": "2017-02-16T04:18:07",
"content_id": "dff433a8d912781da284072dd16d3a4f6029d218",
"detected_licenses": [
"MIT"
],
"directory_id": "9caa91d05fe9754fc67392f86ded6c0072a29f80",
"extension": "c",
"filename": "secure_types.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 56798327,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2008,
"license": "MIT",
"license_type": "permissive",
"path": "/src/connection/secure_types.c",
"provenance": "stackv2-0123.json.gz:14088",
"repo_name": "AdvancingWorldsInitiative/World-311",
"revision_date": "2017-02-16T04:18:07",
"revision_id": "2cb5f1567f61280a06629de327a700a6384946d2",
"snapshot_id": "4e40eb9104c872a29a97d12ab4fca25cebec81cf",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/AdvancingWorldsInitiative/World-311/2cb5f1567f61280a06629de327a700a6384946d2/src/connection/secure_types.c",
"visit_date": "2021-01-18T20:34:15.190584"
} | stackv2 | #include "secure_types.h"
#include <string.h>
int Secure_GenKeys(Secure_PubKey pub, Secure_PrivKey priv)
{
if(crypto_box_keypair(pub, priv))
{
Error_Print("Unable to generate keypair.\n");
return -1;
}
return 0;
}
int Secure_GenSharedKey(Secure_SharedKey sharedkey, Secure_PubKey peer,
Secure_PrivKey priv)
{
if(crypto_box_beforenm(sharedkey, peer, priv))
{
Error_Print("Unable to generate a shared key.\n");
return -1;
}
return 0;
}
int Secure_GenNonce(Secure_Nonce nonce)
{
randombytes_buf(nonce, SECURE_NONCE_SIZE);
return 0;
}
Secure_Session *Secure_NewSession()
{
Secure_Session *out = (Secure_Session*)malloc(sizeof(Secure_Session));
memset(out, 0, sizeof(Secure_Session));
return out;
}
Secure_PubKey Secure_NewPubKey()
{
return (Secure_PubKey)malloc(SECURE_PUBKEY_SIZE);
}
Secure_PrivKey Secure_NewPrivKey()
{
return (Secure_PrivKey)malloc(SECURE_PRIVKEY_SIZE);
}
Secure_SharedKey Secure_NewSharedKey()
{
return (Secure_SharedKey)malloc(SECURE_SHAREDKEY_SIZE);
}
Secure_Nonce Secure_NewNonce()
{
return (Secure_Nonce)malloc(SECURE_NONCE_SIZE);
}
Secure_PlainText Secure_NewPlainText(size_t len)
{
return (Secure_PlainText)malloc(len);
}
Secure_CipherText Secure_NewCipherText(size_t plaintextsize)
{
return (uint8_t*)malloc(plaintextsize + SECURE_CIPHER_OVERHEAD);
}
void Secure_FreeSession(Secure_Session *session)
{
free(session->key);
free(session->nonce);
free(session);
}
void Secure_FreePubKey(Secure_PubKey pub)
{
free(pub);
}
void Secure_FreePrivKey(Secure_PrivKey priv)
{
free(priv);
}
void Secure_FreeKeyPair(Secure_PubKey pub, Secure_PrivKey priv)
{
Secure_FreePubKey(pub);
Secure_FreePrivKey(priv);
}
void Secure_FreeNonce(Secure_Nonce nonce)
{
free(nonce);
}
void Secure_FreePlainText(Secure_PlainText plaintext)
{
free(plaintext);
}
void Secure_FreeCipherText(Secure_CipherText ciphertext)
{
free(ciphertext);
}
| 2.453125 | 2 |
2024-11-18T22:22:09.037657+00:00 | 2021-01-31T11:33:49 | 4a332a86d38b99f6b4ed54ea60bfb4c2eb61dcc6 | {
"blob_id": "4a332a86d38b99f6b4ed54ea60bfb4c2eb61dcc6",
"branch_name": "refs/heads/master",
"committer_date": "2021-01-31T11:33:49",
"content_id": "7c95db0c3e531cb6a7a81ce3d63e53de3fa0a172",
"detected_licenses": [
"MIT"
],
"directory_id": "2288eaf386e772b4e127453445b501b017634da4",
"extension": "c",
"filename": "type_interface.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 301354984,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2782,
"license": "MIT",
"license_type": "permissive",
"path": "/src/type_interface.c",
"provenance": "stackv2-0123.json.gz:14216",
"repo_name": "fkretlow/libdsa",
"revision_date": "2021-01-31T11:33:49",
"revision_id": "2b1666f830098976cb153025e71fb0715da6a261",
"snapshot_id": "a245ee7484aa2a580db826915d9d87360e5fda57",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/fkretlow/libdsa/2b1666f830098976cb153025e71fb0715da6a261/src/type_interface.c",
"visit_date": "2023-02-24T16:43:17.719226"
} | stackv2 | /*************************************************************************************************
*
* type_interface.c
*
* Implementations of generic operations on objects specified by the given type interface that
* make use of the functions stored in the given type interface.
*
* A couple of pre-defined type interfaces for primitive types. Should be expanded.
*
************************************************************************************************/
#include "check.h"
#include "str.h"
#include "type_interface.h"
void *t_allocate(const t_intf *T, size_t n)
{
void *obj = malloc(n * T->size);
check_alloc(obj);
return obj;
error:
return NULL;
}
void t_copy(const t_intf *T, void *dest, const void *src)
{
if (T->copy) {
T->copy(dest, src);
} else {
memmove(dest, src, T->size);
}
}
void t_move(const t_intf *T, void *dest, void *src)
{
if (T->move) {
T->move(dest, src);
} else {
memmove(dest, src, T->size);
memset(src, 0, T->size);
}
}
int t_swap(const t_intf *T, void *a, void *b)
{
if (T->swap) {
T->swap(a, b);
} else {
void *temp = malloc(T->size);
check_alloc(temp);
t_move(T, temp, a);
t_move(T, a, b);
t_move(T, b, temp);
free(temp);
}
return 0;
error:
return -1;
}
void t_destroy(const t_intf *T, void *obj)
{
if (T->destroy) T->destroy(obj);
}
int t_compare(const t_intf *T, const void *a, const void *b)
{
return T->compare(a, b);
}
uint32_t t_hash(const t_intf *T, const void *obj)
{
if (T->hash) {
return T->hash(obj);
} else {
return jenkins_hash(obj, T->size);
}
}
void t_print(const t_intf *T, FILE *stream, const void *obj)
{
if (T->print) T->print(stream, obj);
}
/* Predefined type interfaces: */
t_intf str_type = {
.size = sizeof(str),
.copy = str_copy_to,
.destroy = str_destroy,
.compare = str_compare,
.hash = str_hash,
.print = str_print
};
/* Built-in types */
int int_compare(const void *a, const void *b)
{
return *(int*)a - *(int*)b;
/* return *(int*)a < *(int*)b ? -1 : *(int*)a > *(int*)b ? 1 : 0; */
}
uint32_t int_hash(const void *i)
{
return jenkins_hash(i, sizeof(int));
}
void int_print(FILE *stream, const void *i)
{
fprintf(stream, "%d", *(int*)i);
}
t_intf int_type = {
.size = sizeof(int),
.copy = NULL,
.destroy = NULL,
.compare = int_compare,
.hash = int_hash,
.print = int_print
};
int pointer_compare(const void *a, const void *b)
{
return a < b ? -1 : a > b ? 1 : 0;
}
t_intf pointer_type = {
.size = sizeof(void*),
.copy = NULL,
.destroy = NULL,
.compare = pointer_compare,
.hash = NULL,
.print = NULL
};
| 2.75 | 3 |
2024-11-18T22:22:09.447299+00:00 | 2021-11-08T23:38:01 | e137441bba89acde086b569cabd6599ff209c590 | {
"blob_id": "e137441bba89acde086b569cabd6599ff209c590",
"branch_name": "refs/heads/main",
"committer_date": "2021-11-08T23:38:01",
"content_id": "8a918991efb43a115fda23e6ee170b7d72c87469",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "403f9b277d5a80f283eb8da2ab73e1bf6cfb09e8",
"extension": "c",
"filename": "idtLoader.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 418716040,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1398,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/Kernel/interruptions/idtLoader.c",
"provenance": "stackv2-0123.json.gz:14606",
"repo_name": "camilaDiToro/Kernel-Pure64",
"revision_date": "2021-11-08T23:38:01",
"revision_id": "2d94b13c2dee56c8395f92f55b6c78a2da061bb3",
"snapshot_id": "f2c14110ded61262ee8ffd35ccc909b093a00e9c",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/camilaDiToro/Kernel-Pure64/2d94b13c2dee56c8395f92f55b6c78a2da061bb3/Kernel/interruptions/idtLoader.c",
"visit_date": "2023-08-26T07:28:05.409978"
} | stackv2 | #include <stdint.h>
#include <idtLoader.h>
#include <defs.h>
#include <interrupts.h>
#pragma pack(push) // Current lineup push
#pragma pack (1) // Align the following structures to 1 byte
// Interrupt descriptor
typedef struct {
uint16_t offset_l, selector;
uint8_t cero, access;
uint16_t offset_m;
uint32_t offset_h, other_cero;
} DESCR_INT;
#pragma pack(pop) // Reset the current alignment
DESCR_INT * idt = (DESCR_INT *) 0; // 255 entry IDT
static void setup_IDT_entry (int index, uint64_t offset);
void load_idt() {
// Disable interrupts
_cli();
// Exceptions
setup_IDT_entry (0x00, (uint64_t)&_exception0Handler);
setup_IDT_entry (0x06, (uint64_t)&_exception6Handler);
// Hardware Interrupts
setup_IDT_entry (0x20, (uint64_t)&_irq00Handler); // timer tick
setup_IDT_entry (0x21, (uint64_t)&_irq01Handler); // keyboard
// Software Interrupts
setup_IDT_entry (0x80, (uint64_t)&_sysCallHandler);
// 1111 1100 timer-tick and keyboard
picMasterMask(0xFC);
picSlaveMask(0xFF);
// Enable interrupts
_sti();
}
static void setup_IDT_entry (int index, uint64_t offset) {
idt[index].selector = 0x08;
idt[index].offset_l = offset & 0xFFFF;
idt[index].offset_m = (offset >> 16) & 0xFFFF;
idt[index].offset_h = (offset >> 32) & 0xFFFFFFFF;
idt[index].access = ACS_INT;
idt[index].cero = 0;
idt[index].other_cero = (uint64_t) 0;
} | 2.65625 | 3 |
2024-11-18T22:22:09.774021+00:00 | 2023-08-24T07:58:02 | 2b042d9ba5066677235b20088a2e6d2beed0e63a | {
"blob_id": "2b042d9ba5066677235b20088a2e6d2beed0e63a",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-24T07:58:02",
"content_id": "8b6159114a0545b25d1031addb59b8a9757e1a2f",
"detected_licenses": [
"MIT"
],
"directory_id": "cb9ffece95cef31e363b55d9e07e21cc22a446eb",
"extension": "h",
"filename": "event.h",
"fork_events_count": 0,
"gha_created_at": "2022-10-08T03:25:12",
"gha_event_created_at": "2023-08-12T08:28:55",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 547652064,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 938,
"license": "MIT",
"license_type": "permissive",
"path": "/src/event.h",
"provenance": "stackv2-0123.json.gz:14993",
"repo_name": "ktabata/suika2",
"revision_date": "2023-08-24T07:58:02",
"revision_id": "b7f9812c5171a3ed035d4eef8fb81971f5816415",
"snapshot_id": "9cfef91eff89e37aa5a012c03823537b746773b3",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/ktabata/suika2/b7f9812c5171a3ed035d4eef8fb81971f5816415/src/event.h",
"visit_date": "2023-08-24T16:18:09.471296"
} | stackv2 | /* -*- coding: utf-8; tab-width: 8; indent-tabs-mode: t; -*- */
/*
* Suika 2
* Copyright (C) 2016, TABATA Keiichi. All rights reserved.
*/
/*
* [Changes]
* - 2016/05/27 作成
* - 2016/06/22 分割
*/
#ifndef SUIKA_EVENT_H
#define SUIKA_EVENT_H
#include "types.h"
/*
* キーコード
*/
enum key_code {
KEY_CONTROL,
KEY_SPACE,
KEY_RETURN,
KEY_UP,
KEY_DOWN,
KEY_ESCAPE,
KEY_C,
};
/*
* マウスボタン
*/
enum mouse_button {
MOUSE_LEFT,
MOUSE_RIGHT,
};
/*
* イベントハンドラ
* - platform.hの実装から呼び出される
*/
bool on_event_init(void);
void on_event_cleanup(void);
bool on_event_frame(int *x, int *y, int *w, int *h);
void on_event_key_press(int key);
void on_event_key_release(int key);
void on_event_mouse_press(int button, int x, int y);
void on_event_mouse_release(int button, int x, int y);
void on_event_mouse_move(int x, int y);
void on_event_mouse_scroll(int n);
#endif
| 2.015625 | 2 |
2024-11-18T22:22:09.867133+00:00 | 2021-08-23T21:54:46 | 84c5301099295b249eb8b8d84aa6d7fe3dbf05f6 | {
"blob_id": "84c5301099295b249eb8b8d84aa6d7fe3dbf05f6",
"branch_name": "refs/heads/main",
"committer_date": "2021-08-23T21:54:46",
"content_id": "a24edc88bb3daaa5ed3a66479d45365e37ff61b5",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "c90fbf19e5eb9957392d838840e3945da0fb8f30",
"extension": "c",
"filename": "Translational_drone_constr_h_fun_jac_uxt_zt.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": 6559,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/position_mpc/c_generated_code/Translational_drone_constraints/Translational_drone_constr_h_fun_jac_uxt_zt.c",
"provenance": "stackv2-0123.json.gz:15123",
"repo_name": "BaosaiWang/quadrotor_mpc_acados",
"revision_date": "2021-08-23T21:54:46",
"revision_id": "9ca50ecc0a852ba5f9464df0ccd5d40e3ebfc295",
"snapshot_id": "a1e526cf2020ed37d085633b88a86ff7b6049b35",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/BaosaiWang/quadrotor_mpc_acados/9ca50ecc0a852ba5f9464df0ccd5d40e3ebfc295/position_mpc/c_generated_code/Translational_drone_constraints/Translational_drone_constr_h_fun_jac_uxt_zt.c",
"visit_date": "2023-07-15T01:17:57.252648"
} | stackv2 | /* This file was automatically generated by CasADi.
The CasADi copyright holders make no ownership claim of its contents. */
#ifdef __cplusplus
extern "C" {
#endif
/* How to prefix internal symbols */
#ifdef CASADI_CODEGEN_PREFIX
#define CASADI_NAMESPACE_CONCAT(NS, ID) _CASADI_NAMESPACE_CONCAT(NS, ID)
#define _CASADI_NAMESPACE_CONCAT(NS, ID) NS ## ID
#define CASADI_PREFIX(ID) CASADI_NAMESPACE_CONCAT(CODEGEN_PREFIX, ID)
#else
#define CASADI_PREFIX(ID) Translational_drone_constr_h_fun_jac_uxt_zt_ ## ID
#endif
#include <math.h>
#ifndef casadi_real
#define casadi_real double
#endif
#ifndef casadi_int
#define casadi_int int
#endif
/* Add prefix to internal symbols */
#define casadi_clear CASADI_PREFIX(clear)
#define casadi_copy CASADI_PREFIX(copy)
#define casadi_f0 CASADI_PREFIX(f0)
#define casadi_s0 CASADI_PREFIX(s0)
#define casadi_s1 CASADI_PREFIX(s1)
#define casadi_s2 CASADI_PREFIX(s2)
#define casadi_s3 CASADI_PREFIX(s3)
#define casadi_s4 CASADI_PREFIX(s4)
#define casadi_s5 CASADI_PREFIX(s5)
#define casadi_sq CASADI_PREFIX(sq)
/* Symbol visibility in DLLs */
#ifndef CASADI_SYMBOL_EXPORT
#if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__)
#if defined(STATIC_LINKED)
#define CASADI_SYMBOL_EXPORT
#else
#define CASADI_SYMBOL_EXPORT __declspec(dllexport)
#endif
#elif defined(__GNUC__) && defined(GCC_HASCLASSVISIBILITY)
#define CASADI_SYMBOL_EXPORT __attribute__ ((visibility ("default")))
#else
#define CASADI_SYMBOL_EXPORT
#endif
#endif
casadi_real casadi_sq(casadi_real x) { return x*x;}
void casadi_clear(casadi_real* x, casadi_int n) {
casadi_int i;
if (x) {
for (i=0; i<n; ++i) *x++ = 0;
}
}
void casadi_copy(const casadi_real* x, casadi_int n, casadi_real* y) {
casadi_int i;
if (y) {
if (x) {
for (i=0; i<n; ++i) *y++ = *x++;
} else {
for (i=0; i<n; ++i) *y++ = 0.;
}
}
}
static const casadi_int casadi_s0[10] = {6, 1, 0, 6, 0, 1, 2, 3, 4, 5};
static const casadi_int casadi_s1[9] = {5, 1, 0, 5, 0, 1, 2, 3, 4};
static const casadi_int casadi_s2[3] = {0, 0, 0};
static const casadi_int casadi_s3[5] = {1, 1, 0, 1, 0};
static const casadi_int casadi_s4[8] = {11, 1, 0, 4, 1, 2, 3, 4};
static const casadi_int casadi_s5[3] = {1, 0, 0};
/* Translational_drone_constr_h_fun_jac_uxt_zt:(i0[6],i1[5],i2[],i3[])->(o0,o1[11x1,4nz],o2[1x0]) */
static int casadi_f0(const casadi_real** arg, casadi_real** res, casadi_int* iw, casadi_real* w, int mem) {
casadi_real *rr, *ss;
casadi_real w0, w1, w2, w3, w4, w5, *w6=w+6;
/* #0: @0 = input[1][1] */
w0 = arg[1] ? arg[1][1] : 0;
/* #1: @1 = sq(@0) */
w1 = casadi_sq( w0 );
/* #2: @2 = input[1][2] */
w2 = arg[1] ? arg[1][2] : 0;
/* #3: @3 = sq(@2) */
w3 = casadi_sq( w2 );
/* #4: @1 = (@1+@3) */
w1 += w3;
/* #5: @3 = input[1][3] */
w3 = arg[1] ? arg[1][3] : 0;
/* #6: @4 = sq(@3) */
w4 = casadi_sq( w3 );
/* #7: @1 = (@1+@4) */
w1 += w4;
/* #8: @4 = input[1][4] */
w4 = arg[1] ? arg[1][4] : 0;
/* #9: @5 = sq(@4) */
w5 = casadi_sq( w4 );
/* #10: @1 = (@1+@5) */
w1 += w5;
/* #11: @1 = sqrt(@1) */
w1 = sqrt( w1 );
/* #12: output[0][0] = @1 */
if (res[0]) res[0][0] = w1;
/* #13: @6 = zeros(11x1,4nz) */
casadi_clear(w6, 4);
/* #14: @0 = (2.*@0) */
w0 = (2.* w0 );
/* #15: @1 = (2.*@1) */
w1 = (2.* w1 );
/* #16: @0 = (@0/@1) */
w0 /= w1;
/* #17: (@6[0] = @0) */
for (rr=w6+0, ss=(&w0); rr!=w6+1; rr+=1) *rr = *ss++;
/* #18: @2 = (2.*@2) */
w2 = (2.* w2 );
/* #19: @2 = (@2/@1) */
w2 /= w1;
/* #20: (@6[1] = @2) */
for (rr=w6+1, ss=(&w2); rr!=w6+2; rr+=1) *rr = *ss++;
/* #21: @3 = (2.*@3) */
w3 = (2.* w3 );
/* #22: @3 = (@3/@1) */
w3 /= w1;
/* #23: (@6[2] = @3) */
for (rr=w6+2, ss=(&w3); rr!=w6+3; rr+=1) *rr = *ss++;
/* #24: @4 = (2.*@4) */
w4 = (2.* w4 );
/* #25: @4 = (@4/@1) */
w4 /= w1;
/* #26: (@6[3] = @4) */
for (rr=w6+3, ss=(&w4); rr!=w6+4; rr+=1) *rr = *ss++;
/* #27: output[1][0] = @6 */
casadi_copy(w6, 4, res[1]);
return 0;
}
CASADI_SYMBOL_EXPORT int Translational_drone_constr_h_fun_jac_uxt_zt(const casadi_real** arg, casadi_real** res, casadi_int* iw, casadi_real* w, int mem){
return casadi_f0(arg, res, iw, w, mem);
}
CASADI_SYMBOL_EXPORT int Translational_drone_constr_h_fun_jac_uxt_zt_alloc_mem(void) {
return 0;
}
CASADI_SYMBOL_EXPORT int Translational_drone_constr_h_fun_jac_uxt_zt_init_mem(int mem) {
return 0;
}
CASADI_SYMBOL_EXPORT void Translational_drone_constr_h_fun_jac_uxt_zt_free_mem(int mem) {
}
CASADI_SYMBOL_EXPORT int Translational_drone_constr_h_fun_jac_uxt_zt_checkout(void) {
return 0;
}
CASADI_SYMBOL_EXPORT void Translational_drone_constr_h_fun_jac_uxt_zt_release(int mem) {
}
CASADI_SYMBOL_EXPORT void Translational_drone_constr_h_fun_jac_uxt_zt_incref(void) {
}
CASADI_SYMBOL_EXPORT void Translational_drone_constr_h_fun_jac_uxt_zt_decref(void) {
}
CASADI_SYMBOL_EXPORT casadi_int Translational_drone_constr_h_fun_jac_uxt_zt_n_in(void) { return 4;}
CASADI_SYMBOL_EXPORT casadi_int Translational_drone_constr_h_fun_jac_uxt_zt_n_out(void) { return 3;}
CASADI_SYMBOL_EXPORT casadi_real Translational_drone_constr_h_fun_jac_uxt_zt_default_in(casadi_int i){
switch (i) {
default: return 0;
}
}
CASADI_SYMBOL_EXPORT const char* Translational_drone_constr_h_fun_jac_uxt_zt_name_in(casadi_int i){
switch (i) {
case 0: return "i0";
case 1: return "i1";
case 2: return "i2";
case 3: return "i3";
default: return 0;
}
}
CASADI_SYMBOL_EXPORT const char* Translational_drone_constr_h_fun_jac_uxt_zt_name_out(casadi_int i){
switch (i) {
case 0: return "o0";
case 1: return "o1";
case 2: return "o2";
default: return 0;
}
}
CASADI_SYMBOL_EXPORT const casadi_int* Translational_drone_constr_h_fun_jac_uxt_zt_sparsity_in(casadi_int i) {
switch (i) {
case 0: return casadi_s0;
case 1: return casadi_s1;
case 2: return casadi_s2;
case 3: return casadi_s2;
default: return 0;
}
}
CASADI_SYMBOL_EXPORT const casadi_int* Translational_drone_constr_h_fun_jac_uxt_zt_sparsity_out(casadi_int i) {
switch (i) {
case 0: return casadi_s3;
case 1: return casadi_s4;
case 2: return casadi_s5;
default: return 0;
}
}
CASADI_SYMBOL_EXPORT int Translational_drone_constr_h_fun_jac_uxt_zt_work(casadi_int *sz_arg, casadi_int* sz_res, casadi_int *sz_iw, casadi_int *sz_w) {
if (sz_arg) *sz_arg = 6;
if (sz_res) *sz_res = 4;
if (sz_iw) *sz_iw = 0;
if (sz_w) *sz_w = 10;
return 0;
}
#ifdef __cplusplus
} /* extern "C" */
#endif
| 2.09375 | 2 |
2024-11-18T22:22:10.017193+00:00 | 2023-05-05T02:26:49 | 6b36e402fb280c48626c430b19e02c0ac484e613 | {
"blob_id": "6b36e402fb280c48626c430b19e02c0ac484e613",
"branch_name": "refs/heads/master",
"committer_date": "2023-05-05T02:26:49",
"content_id": "acceaf74ad623fcd54e744f9cd793dd5bee77864",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "5efe877bf5ebc9da1e7edb8efabb66b88a78cee4",
"extension": "h",
"filename": "ComponentName.h",
"fork_events_count": 64,
"gha_created_at": "2018-05-14T21:53:46",
"gha_event_created_at": "2023-03-20T23:15:23",
"gha_language": "C",
"gha_license_id": "BSD-3-Clause",
"github_id": 133425750,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3709,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/DcpmPkg/driver/Protocol/Driver/ComponentName.h",
"provenance": "stackv2-0123.json.gz:15380",
"repo_name": "intel/ipmctl",
"revision_date": "2023-05-05T02:26:49",
"revision_id": "c75bd840ea7820c8f93a5488fcff75d08beedd51",
"snapshot_id": "342996a882ea7f4d3abf06fd175ec5d5673829b3",
"src_encoding": "UTF-8",
"star_events_count": 176,
"url": "https://raw.githubusercontent.com/intel/ipmctl/c75bd840ea7820c8f93a5488fcff75d08beedd51/DcpmPkg/driver/Protocol/Driver/ComponentName.h",
"visit_date": "2023-08-11T03:49:16.000607"
} | stackv2 | /*
* Copyright (c) 2018, Intel Corporation.
* SPDX-License-Identifier: BSD-3-Clause
*/
#ifndef _COMPONENT_NAME_H_
#define _COMPONENT_NAME_H_
/**
Retrieves a Unicode string that is the user-readable name of the EFI Driver.
@param pThis A pointer to the EFI_COMPONENT_NAME_PROTOCOL2 instance.
@param pLanguage A pointer to an ASCII string containing the ISO 639-2 or the
RFC 4646 language code. This is the language of the driver name that the caller
is requesting, and it must match one of the languages specified
in SupportedLanguages. The number of languages supported by a
driver is up to the driver writer.
@param ppDriverName A pointer to the Unicode string to return. This Unicode string
is the name of the driver specified by pThis in the language
specified by Language.
@retval EFI_SUCCESS The Unicode string for the Driver specified by pThis
and the language specified by pLanguage was returned
in ppDriverName.
@retval EFI_INVALID_PARAMETER pLanguage is NULL.
@retval EFI_INVALID_PARAMETER ppDriverName is NULL.
@retval EFI_UNSUPPORTED The driver specified by pThis does not support the
language specified by pLanguage.
**/
EFI_STATUS
EFIAPI
NvmDimmDriverComponentNameGetDriverName (
IN EFI_COMPONENT_NAME2_PROTOCOL *pThis,
IN CHAR8 *pLanguage,
OUT CHAR16 **ppDriverName
);
/**
Retrieves a Unicode string that is the user readable name of the controller
that is being managed by an EFI Driver.
@param pThis A pointer to the EFI_COMPONENT_NAME2_PROTOCOL instance.
@param ControllerHandle The handle of a controller that the driver specified by
This is managing. This handle specifies the controller
whose name is to be returned.
@param ChildHandle The handle of the child controller to retrieve the name for.
This is an optional parameter that may be NULL. It
will be NULL for device drivers. It will also be NULL
for a bus drivers that wish to retrieve the name of the
bus controller. It will not be NULL for a bus driver
that wishes to retrieve the name of a child controller.
@param pLanguage A pointer to a three character ISO 639-2 language
identifier. This is the language of the controller name
that the caller is requesting, and it must match one
of the languages specified in SupportedLanguages. The
number of languages supported by a driver is up to the
driver writer.
@param ppControllerName A pointer to the Unicode string to return. This Unicode
string is the name of the controller specified by
ControllerHandle and ChildHandle in the language specified
by Language, from the point of view of the driver specified by This.
@retval EFI_SUCCESS The Unicode string for the user-readable name in the
language specified by Language for the driver specified by This was returned in DriverName.
@retval EFI_INVALID_PARAMETER ControllerHandle is NULL.
@retval EFI_INVALID_PARAMETER ChildHandle is not NULL and it is not a valid EFI_HANDLE.
@retval EFI_INVALID_PARAMETER Language is NULL.
@retval EFI_INVALID_PARAMETER ControllerName is NULL.
@retval EFI_UNSUPPORTED The driver specified by This is not currently managing
the controller specified by ControllerHandle and ChildHandle.
@retval EFI_UNSUPPORTED The driver specified by This does not support the
language specified by Language.
**/
EFI_STATUS
EFIAPI
NvmDimmDriverComponentNameGetControllerName (
IN EFI_COMPONENT_NAME2_PROTOCOL *pThis,
IN EFI_HANDLE ControllerHandle,
IN EFI_HANDLE ChildHandle OPTIONAL,
IN CHAR8 *pLanguage,
OUT CHAR16 **ppControllerName
);
#endif /* _COMPONENT_NAME_H_ */
| 2.203125 | 2 |
2024-11-18T22:22:10.473116+00:00 | 2016-05-06T22:40:29 | 8d791b4e22965f32902537e2fb6dcf838c4d302c | {
"blob_id": "8d791b4e22965f32902537e2fb6dcf838c4d302c",
"branch_name": "refs/heads/master",
"committer_date": "2016-05-06T22:40:29",
"content_id": "b970048d1eb1cd08a17e6a6a13c10d8cd88587c7",
"detected_licenses": [
"MIT"
],
"directory_id": "035406ea20ff25b4b4c457fa0e0c7d6d3d74e15a",
"extension": "c",
"filename": "healthbar.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 58121484,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1517,
"license": "MIT",
"license_type": "permissive",
"path": "/src/healthbar.c",
"provenance": "stackv2-0123.json.gz:15638",
"repo_name": "h4xxel/birdie26",
"revision_date": "2016-05-06T22:40:29",
"revision_id": "a41bae4a85d30c875d414174c13cd797be79de1d",
"snapshot_id": "af23da030b207b70455022c27dc7d9b148ac02a8",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/h4xxel/birdie26/a41bae4a85d30c875d414174c13cd797be79de1d/src/healthbar.c",
"visit_date": "2016-09-14T02:37:20.202671"
} | stackv2 | #include "healthbar.h"
#include "main.h"
#include "ailib.h"
static void _calculate_one(MOVABLE_ENTRY *entry, DARNIT_TILE *tile, int x_pos, int id) {
float arne;
int w;
arne = ((float) entry->hp) / entry->hp_max;
w = arne * 128;
d_render_tile_set(tile, 0, id * 2);
d_render_tile_set(tile, 1, id * 2 + 1);
d_render_tile_move(tile, 0, x_pos, 0);
d_render_tile_move(tile, 1, x_pos + w, 0);
d_render_tile_size_set(tile, 0, w, 16);
d_render_tile_size_set(tile, 1, 128 - w, 16);
d_render_tile_tilesheet_coord_set(tile, 0, 0, id * 16, w, 16);
d_render_tile_tilesheet_coord_set(tile, 1, 128 + w, 16 * id, 128 - w, 16);
}
void healthbar_calculate() {
/* This will be retardedly slow */
int i, id;
for (i = 0; i < s->movable.movables; i++) {
id = _get_player_id(&s->movable.movable[i]);
if (id < 0)
continue;
_calculate_one(&s->movable.movable[i], s->healthbar.bar[id], 160 * id, id);
s->healthbar.hp[id] = s->movable.movable[i].hp;
}
}
void healthbar_init() {
s->healthbar.ts = d_render_tilesheet_load("res/healthbars.png", 128, 16, DARNIT_PFORMAT_RGB5A1);
s->healthbar.bar[0] = d_render_tile_new(2, s->healthbar.ts);
s->healthbar.bar[1] = d_render_tile_new(2, s->healthbar.ts);
s->healthbar.bar[2] = d_render_tile_new(2, s->healthbar.ts);
s->healthbar.bar[3] = d_render_tile_new(2, s->healthbar.ts);
}
void healthbar_draw() {
int i;
healthbar_calculate();
d_render_offset(0, 0);
for (i = 0; i < 4; i++)
if (s->healthbar.hp[i])
d_render_tile_draw(s->healthbar.bar[i], 2);
}
| 2.171875 | 2 |
2024-11-18T22:22:10.558677+00:00 | 2015-05-24T17:34:49 | 7d4f5f3987c03ce376ce92d0318b96a49accf7fc | {
"blob_id": "7d4f5f3987c03ce376ce92d0318b96a49accf7fc",
"branch_name": "refs/heads/master",
"committer_date": "2015-05-24T17:34:49",
"content_id": "29f2ae2839bc4609dcf364b51f77dd4ff794d5a5",
"detected_licenses": [
"MIT"
],
"directory_id": "d0861150d87208c39236daec5f8c3edb4406147a",
"extension": "c",
"filename": "lua_collisionpair.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": 5215,
"license": "MIT",
"license_type": "permissive",
"path": "/lua/lua_collisionpair.c",
"provenance": "stackv2-0123.json.gz:15767",
"repo_name": "plunch/geng",
"revision_date": "2015-05-24T17:34:49",
"revision_id": "d086075f68e53b1bbbe8334664de889ee5c21e0a",
"snapshot_id": "e0664f31d515ef1f80dfbb7fad73b3c73d3be849",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/plunch/geng/d086075f68e53b1bbbe8334664de889ee5c21e0a/lua/lua_collisionpair.c",
"visit_date": "2021-05-29T12:14:52.350171"
} | stackv2 | #include "lua_collisionpair.h"
#include <stdlib.h>
#include <string.h>
#include <lualib.h>
#include <lauxlib.h>
#include <chipmunk/chipmunk.h>
#include "lua_vector.h"
#include "lua_object.h"
#include "lua_colliders.h"
#define TYPE_NAME "collpair"
collision_pair* luaG_checkcollpair(lua_State* L, int index)
{
collision_pair* c;
luaL_checktype(L, index, LUA_TUSERDATA);
c = (collision_pair*)luaL_checkudata(L, index, TYPE_NAME);
if (c == NULL) luaL_typerror(L, index, TYPE_NAME);
return c;
}
collision_pair* luaG_pushcollpair(lua_State* l, void* data)
{
collision_pair* c = (collision_pair*)lua_newuserdata(l,
sizeof(collision_pair));
luaL_getmetatable(l, TYPE_NAME);
lua_setmetatable(l, -2);
c->data = data;
return c;
}
static int lua_collpair_get_elasticity(lua_State* l)
{
collision_pair* p = luaG_checkcollpair(l, 1);
lua_pushnumber(l, cpArbiterGetElasticity(p->data));
return 1;
}
static int lua_collpair_set_elasticity(lua_State* l)
{
collision_pair* p = luaG_checkcollpair(l, 1);
if (p->current != COLL_PRESOLVE) {
luaL_error(l, "Setting elasticity outside of a preSolve \
callback will not have an effect");
}
cpArbiterSetElasticity(p->data, luaL_checknumber(l, 2));
return 1;
}
static int lua_collpair_get_friction(lua_State* l)
{
collision_pair* p = luaG_checkcollpair(l, 1);
lua_pushnumber(l, cpArbiterGetFriction(p->data));
return 1;
}
static int lua_collpair_set_friction(lua_State* l)
{
collision_pair* p = luaG_checkcollpair(l, 1);
if (p->current != COLL_PRESOLVE) {
luaL_error(l, "Setting friction outside of a preSolve \
callback will not have an effect");
}
cpArbiterSetFriction(p->data, luaL_checknumber(l, 2));
return 1;
}
static int lua_collpair_get_surfvel(lua_State* l)
{
collision_pair* p = luaG_checkcollpair(l, 1);
cpVect* v = luaG_pushvect(l);
*v = cpArbiterGetSurfaceVelocity(p->data);
return 1;
}
static int lua_collpair_set_surfvel(lua_State* l)
{
collision_pair* p = luaG_checkcollpair(l, 1);
if (p->current != COLL_PRESOLVE) {
luaL_error(l, "Setting surface velocity outside of a preSolve \
callback will not have an effect");
}
cpVect* v = luaG_checkvect(l, 2);
cpArbiterSetSurfaceVelocity(p->data, *v);
return 1;
}
static int lua_collpair_get_impulse_f(lua_State* l)
{
collision_pair* p = luaG_checkcollpair(l, 1);
cpVect* v = luaG_pushvect(l);
*v = cpArbiterTotalImpulseWithFriction(p->data);
return 1;
}
static int lua_collpair_get_impulse(lua_State* l)
{
collision_pair* p = luaG_checkcollpair(l, 1);
cpVect* v = luaG_pushvect(l);
*v = cpArbiterTotalImpulse(p->data);
return 1;
}
static int lua_collpair_get_ke(lua_State* l)
{
collision_pair* p = luaG_checkcollpair(l, 1);
if(p->current != COLL_POSTSOLVE) {
luaL_error(l, "Can only be called from a postStep callback");
}
lua_pushnumber(l, cpArbiterTotalKE(p->data));
return 1;
}
static int lua_collpair_get_objects(lua_State* l)
{
collision_pair* p = luaG_checkcollpair(l, 1);
CP_ARBITER_GET_BODIES(p->data, a, b);
luaG_pushobject(l, cpBodyGetUserData(a));
luaG_pushobject(l, cpBodyGetUserData(b));
return 2;
}
static int lua_collpair_get_shapes(lua_State* l)
{
collision_pair* p = luaG_checkcollpair(l, 1);
collider* a = luaG_pushcoll(l);
collider* b = luaG_pushcoll(l);
cpArbiterGetShapes(p->data, &a->shape, &b->shape);
return 2;
}
static int lua_collpair_get_contact_count(lua_State* l)
{
collision_pair* p = luaG_checkcollpair(l, 1);
lua_pushnumber(l, cpArbiterGetCount(p->data));
return 1;
}
static int lua_collpair_get_point(lua_State* l)
{
collision_pair* p = luaG_checkcollpair(l, 1);
cpVect* v = luaG_pushvect(l);
*v = cpArbiterGetNormal(p->data, luaL_optint(l, 2, 0));
return 1;
}
static int lua_collpair_get_normal(lua_State* l)
{
collision_pair* p = luaG_checkcollpair(l, 1);
cpVect* v = luaG_pushvect(l);
*v = cpArbiterGetPoint(p->data, luaL_optint(l, 2, 0));
return 1;
}
static int lua_collpair_get_depth(lua_State* l)
{
collision_pair* p = luaG_checkcollpair(l, 1);
lua_pushnumber(l, cpArbiterGetDepth(p->data, luaL_optint(l, 2, 0)));
return 1;
}
static const luaL_reg methods [] = {
{"get_elasticity", lua_collpair_get_elasticity},
{"get_friction", lua_collpair_get_friction},
{"get_surfvel", lua_collpair_get_surfvel},
{"set_elasticity", lua_collpair_set_elasticity},
{"set_friction", lua_collpair_set_friction},
{"set_surfvel", lua_collpair_set_surfvel},
{"get_impulse", lua_collpair_get_impulse_f},
{"get_impulse_without_friction", lua_collpair_get_impulse},
{"get_ke", lua_collpair_get_ke},
{"get_objects", lua_collpair_get_objects},
{"get_colliders", lua_collpair_get_shapes},
{"contact_count", lua_collpair_get_contact_count},
{"contact_point", lua_collpair_get_point},
{"contact_normal", lua_collpair_get_normal},
{"contact_depth", lua_collpair_get_depth},
{NULL, NULL}
};
static const luaL_reg meta_methods [] = {
{NULL, NULL}
};
int register_collpair(lua_State* L)
{
luaL_openlib(L, TYPE_NAME, methods, 0);
luaL_newmetatable(L, TYPE_NAME);
luaL_openlib(L, 0, meta_methods, 0);
lua_pushliteral(L, "__index");
lua_pushvalue(L, -3);
lua_rawset(L, -3);
lua_pushliteral(L, "__metatable");
lua_pushvalue(L, -3);
lua_rawset(L, -3);
lua_pop(L, 1);
return 1;
}
| 2.09375 | 2 |
2024-11-18T22:22:11.391332+00:00 | 2016-06-12T05:55:11 | 67fa30873ce937dcef1fc4203233a43a4489d2d9 | {
"blob_id": "67fa30873ce937dcef1fc4203233a43a4489d2d9",
"branch_name": "refs/heads/master",
"committer_date": "2016-06-12T05:55:11",
"content_id": "7a4bbcff6b613d74f9aff8c71b248db48e2f81dd",
"detected_licenses": [
"MIT"
],
"directory_id": "dac9b584823464c14734a771dc5a99576532e6e4",
"extension": "c",
"filename": "main.c",
"fork_events_count": 5,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 60937134,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3461,
"license": "MIT",
"license_type": "permissive",
"path": "/yuv/main.c",
"provenance": "stackv2-0123.json.gz:16669",
"repo_name": "Akagi201/ffmpeg-player",
"revision_date": "2016-06-12T05:55:11",
"revision_id": "4f73092c2cd52313e2fddcf8046bdc19f143c391",
"snapshot_id": "1e61b04a883bcd87e32a6da2a3c1066806e0fe7a",
"src_encoding": "UTF-8",
"star_events_count": 7,
"url": "https://raw.githubusercontent.com/Akagi201/ffmpeg-player/4f73092c2cd52313e2fddcf8046bdc19f143c391/yuv/main.c",
"visit_date": "2021-01-17T20:00:07.355841"
} | stackv2 | /**
* Simplest Video Play SDL2 (SDL2 play RGB/YUV)
* This software plays RGB/YUV raw video data using SDL2.
* SDL is a wrapper of low-level API (Direct3D, OpenGL).
* Use SDL is much easier than directly call these low-level API.
*
* The process is shown as follows:
*
* [Init]
* SDL_Init(): Init SDL.
* SDL_CreateWindow(): Create a Window.
* SDL_CreateRenderer(): Create a Render.
* SDL_CreateTexture(): Create a Texture.
*
* [Loop to Render data]
* SDL_UpdateTexture(): Set Texture's data.
* SDL_RenderCopy(): Copy Texture to Render.
* SDL_RenderPresent(): Show.
*/
#include <stdio.h>
#include <SDL2/SDL.h>
const int bpp = 12;
int screen_w = 500, screen_h = 500;
const int pixel_w = 320, pixel_h = 180;
unsigned char buffer[pixel_w * pixel_h * bpp / 8];
//Refresh Event
#define REFRESH_EVENT (SDL_USEREVENT + 1)
#define BREAK_EVENT (SDL_USEREVENT + 2)
int thread_exit = 0;
int refresh_video(void *opaque) {
thread_exit = 0;
while (!thread_exit) {
SDL_Event event;
event.type = REFRESH_EVENT;
SDL_PushEvent(&event);
SDL_Delay(40);
}
thread_exit = 0;
//Break
SDL_Event event;
event.type = BREAK_EVENT;
SDL_PushEvent(&event);
return 0;
}
int main(int argc, char *argv[]) {
if (SDL_Init(SDL_INIT_VIDEO)) {
printf("Could not initialize SDL - %s\n", SDL_GetError());
return -1;
}
SDL_Window *screen;
//SDL 2.0 Support for multiple windows
screen = SDL_CreateWindow("Simplest Video Play SDL2", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
screen_w, screen_h, SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE);
if (!screen) {
printf("SDL: could not create window - exiting:%s\n", SDL_GetError());
return -1;
}
SDL_Renderer *sdlRenderer = SDL_CreateRenderer(screen, -1, 0);
Uint32 pixformat = 0;
//IYUV: Y + U + V (3 planes)
//YV12: Y + V + U (3 planes)
pixformat = SDL_PIXELFORMAT_IYUV;
SDL_Texture *sdlTexture = SDL_CreateTexture(sdlRenderer, pixformat, SDL_TEXTUREACCESS_STREAMING, pixel_w, pixel_h);
FILE *fp = NULL;
fp = fopen("test_yuv420p_320x180.yuv", "rb+");
if (fp == NULL) {
printf("cannot open this file\n");
return -1;
}
SDL_Rect sdlRect;
SDL_Thread *refresh_thread = SDL_CreateThread(refresh_video, NULL, NULL);
SDL_Event event;
while (1) {
//Wait
SDL_WaitEvent(&event);
if (event.type == REFRESH_EVENT) {
if (fread(buffer, 1, pixel_w * pixel_h * bpp / 8, fp) != pixel_w * pixel_h * bpp / 8) {
// Loop
fseek(fp, 0, SEEK_SET);
fread(buffer, 1, pixel_w * pixel_h * bpp / 8, fp);
}
SDL_UpdateTexture(sdlTexture, NULL, buffer, pixel_w);
//FIX: If window is resize
sdlRect.x = 0;
sdlRect.y = 0;
sdlRect.w = screen_w;
sdlRect.h = screen_h;
SDL_RenderClear(sdlRenderer);
SDL_RenderCopy(sdlRenderer, sdlTexture, NULL, &sdlRect);
SDL_RenderPresent(sdlRenderer);
} else if (event.type == SDL_WINDOWEVENT) {
//If Resize
SDL_GetWindowSize(screen, &screen_w, &screen_h);
} else if (event.type == SDL_QUIT) {
thread_exit = 1;
} else if (event.type == BREAK_EVENT) {
break;
}
}
SDL_Quit();
return 0;
}
| 3.078125 | 3 |
2024-11-18T22:22:11.541737+00:00 | 2020-05-21T21:47:27 | b7079dca49b66baee3241c04819d85a0a4bc8164 | {
"blob_id": "b7079dca49b66baee3241c04819d85a0a4bc8164",
"branch_name": "refs/heads/master",
"committer_date": "2020-05-21T21:47:27",
"content_id": "efe4de9f14eb6598559b9849b5f4282ae3c5091d",
"detected_licenses": [
"MIT"
],
"directory_id": "33879b907a0053b6de05eec4cda14fb93047ea8b",
"extension": "h",
"filename": "lcd.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 265887849,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1198,
"license": "MIT",
"license_type": "permissive",
"path": "/lcd/lcd.h",
"provenance": "stackv2-0123.json.gz:16798",
"repo_name": "freddieb/lafortuna-gravity-runner",
"revision_date": "2020-05-21T21:47:27",
"revision_id": "ef63ddaf52459bc29621e03af7b9e3fe919f29f5",
"snapshot_id": "089f95d630ad0ce3ec7aa0bdec060c117f726ef1",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/freddieb/lafortuna-gravity-runner/ef63ddaf52459bc29621e03af7b9e3fe919f29f5/lcd/lcd.h",
"visit_date": "2022-07-18T18:35:02.660972"
} | stackv2 | /* Author: Steve Gunn
* Licence: This work is licensed under the Creative Commons Attribution License.
* View this license at http://creativecommons.org/about/licenses/
*/
#include <avr/io.h>
#include <stdint.h>
#define LCDWIDTH 240
#define LCDHEIGHT 320
/* Colour definitions RGB565 */
#define WHITE 0xFFFF
#define BLACK 0x0000
#define BLUE 0x001F
#define GREEN 0x07E0
#define CYAN 0x07FF
#define RED 0xF800
#define MAGENTA 0xF81F
#define YELLOW 0xFFE0
typedef enum {North, West, South, East} orientation;
typedef struct {
uint16_t width, height;
orientation orient;
uint16_t x, y;
uint16_t foreground, background;
} lcd;
extern lcd display;
typedef struct {
uint16_t left, right;
uint16_t top, bottom;
} rectangle;
void init_lcd();
void lcd_brightness(uint8_t i);
void set_orientation(orientation o);
void set_frame_rate_hz(uint8_t f);
void clear_screen();
void fill_rectangle(rectangle r, uint16_t col);
void fill_rectangle_indexed(rectangle r, uint16_t* col);
void display_char(char c);
void display_string(char *str);
void display_string_xy(char *str, uint16_t x, uint16_t y);
| 2.609375 | 3 |
2024-11-18T22:22:11.655939+00:00 | 2014-11-04T23:15:22 | 3f3ffa967239603e994f3bce3e76bf856c4df2dd | {
"blob_id": "3f3ffa967239603e994f3bce3e76bf856c4df2dd",
"branch_name": "refs/heads/master",
"committer_date": "2014-11-04T23:15:22",
"content_id": "c4bb0809b551c2646fce7c944cae078e6bbad925",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "70214efa2467f6c567b805dc923c0d288bf92733",
"extension": "c",
"filename": "ex23.c",
"fork_events_count": 5,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 26249164,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 15978,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/src/ts/examples/tutorials/ex23.c",
"provenance": "stackv2-0123.json.gz:16927",
"repo_name": "OpenCMISS-Dependencies/petsc",
"revision_date": "2014-11-04T23:15:22",
"revision_id": "5334b1442d9dabf795f2fdda92d0f565f35ff948",
"snapshot_id": "0684cd59bb9bddb6be03f27f2e9c183ad476b208",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/OpenCMISS-Dependencies/petsc/5334b1442d9dabf795f2fdda92d0f565f35ff948/src/ts/examples/tutorials/ex23.c",
"visit_date": "2021-01-17T10:08:25.370917"
} | stackv2 | static char help[] = "Cahn-Hilliard-2d problem for constant mobility and triangular elements.\n\
Runtime options include:\n\
-xmin <xmin>\n\
-xmax <xmax>\n\
-ymin <ymin>\n\
-gamma <gamma>\n\
-theta_c <theta_c>\n\
-implicit <0,1> treat theta_c*M_0*u explicitly/implicitly\n\n";
/*
Run with for example: -pc_type mg -pc_mg_galerkin -T .01 -da_grid_x 65 -da_grid_y 65 -pc_mg_levels 4 -ksp_type fgmres -snes_atol 1.e-14 -mat_no_inode
*/
#include <petscts.h>
#include <petscdmda.h>
typedef struct {
PetscReal dt,T; /* Time step and end time */
DM da;
Mat M; /* Mass matrix */
Mat S; /* stiffness matrix */
Mat M_0;
Vec q,u,work1;
PetscScalar gamma,theta_c; /* physics parameters */
PetscReal xmin,xmax,ymin,ymax;
PetscBool tsmonitor;
PetscInt implicit; /* Evaluate theta_c*Mo*u impliicitly or explicitly */
} AppCtx;
PetscErrorCode GetParams(AppCtx*);
PetscErrorCode SetVariableBounds(DM,Vec,Vec);
PetscErrorCode SetUpMatrices(AppCtx*);
PetscErrorCode FormIFunction(TS,PetscReal,Vec,Vec,Vec,void*);
PetscErrorCode FormIJacobian(TS,PetscReal,Vec,Vec,PetscReal,Mat,Mat,void*);
PetscErrorCode SetInitialGuess(Vec,AppCtx*);
PetscErrorCode Update_q(TS);
PetscErrorCode Monitor(TS,PetscInt,PetscReal,Vec,void*);
#undef __FUNCT__
#define __FUNCT__ "main"
int main(int argc, char **argv)
{
PetscErrorCode ierr;
Vec x,r; /* Solution and residual vectors */
TS ts; /* Timestepping object */
AppCtx user; /* Application context */
Vec xl,xu; /* Upper and lower bounds on variables */
Mat J;
PetscInitialize(&argc,&argv, (char*)0, help);
/* Get physics and time parameters */
ierr = GetParams(&user);CHKERRQ(ierr);
/* Create a 2D DA with dof = 2 */
ierr = DMDACreate2d(PETSC_COMM_WORLD,DM_BOUNDARY_NONE,DM_BOUNDARY_NONE,DMDA_STENCIL_BOX,-4,-4,PETSC_DECIDE,PETSC_DECIDE,2,1,NULL,NULL,&user.da);CHKERRQ(ierr);
/* Set Element type (triangular) */
ierr = DMDASetElementType(user.da,DMDA_ELEMENT_P1);CHKERRQ(ierr);
/* Set x and y coordinates */
ierr = DMDASetUniformCoordinates(user.da,user.xmin,user.xmax,user.ymin,user.ymax,0.0,1.0);CHKERRQ(ierr);
/* Get global vector x from DM and duplicate vectors r,xl,xu */
ierr = DMCreateGlobalVector(user.da,&x);CHKERRQ(ierr);
ierr = VecDuplicate(x,&r);CHKERRQ(ierr);
ierr = VecDuplicate(x,&xl);CHKERRQ(ierr);
ierr = VecDuplicate(x,&xu);CHKERRQ(ierr);
if (!user.implicit) {
ierr = VecDuplicate(x,&user.q);CHKERRQ(ierr);
}
/* Get mass,stiffness, and jacobian matrix structure from the da */
ierr = DMSetMatType(user.da,MATAIJ);CHKERRQ(ierr);
ierr = DMCreateMatrix(user.da,&user.M);CHKERRQ(ierr);
ierr = DMCreateMatrix(user.da,&user.S);CHKERRQ(ierr);
ierr = DMCreateMatrix(user.da,&J);CHKERRQ(ierr);
/* Form the mass,stiffness matrices and matrix M_0 */
ierr = SetUpMatrices(&user);CHKERRQ(ierr);
/* Create timestepping solver context */
ierr = TSCreate(PETSC_COMM_WORLD,&ts);CHKERRQ(ierr);
ierr = TSSetProblemType(ts,TS_NONLINEAR);CHKERRQ(ierr);
/* Set Function evaluation and jacobian evaluation routines */
ierr = TSSetIFunction(ts,r,FormIFunction,(void*)&user);CHKERRQ(ierr);
ierr = TSSetIJacobian(ts,J,J,FormIJacobian,(void*)&user);CHKERRQ(ierr);
ierr = TSSetType(ts,TSBEULER);CHKERRQ(ierr);
/* ierr = TSThetaSetTheta(ts,1.0);CHKERRQ(ierr);*/ /* Explicit Euler */
ierr = TSSetDuration(ts,PETSC_DEFAULT,user.T);CHKERRQ(ierr);
/* Set lower and upper bound vectors */
ierr = SetVariableBounds(user.da,xl,xu);CHKERRQ(ierr);
ierr = TSVISetVariableBounds(ts,xl,xu);CHKERRQ(ierr);
ierr = SetInitialGuess(x,&user);CHKERRQ(ierr);
if (!user.implicit) {
ierr = TSSetApplicationContext(ts,&user);CHKERRQ(ierr);
ierr = TSSetSolution(ts,x);CHKERRQ(ierr);
ierr = Update_q(ts);CHKERRQ(ierr);
ierr = TSSetPostStep(ts,Update_q);
}
if (user.tsmonitor) {
ierr = TSMonitorSet(ts,Monitor,&user,NULL);CHKERRQ(ierr);
}
ierr = TSSetInitialTimeStep(ts,0.0,user.dt);CHKERRQ(ierr);
ierr = TSSetFromOptions(ts);CHKERRQ(ierr);
/* Run the timestepping solver */
ierr = TSSolve(ts,x);CHKERRQ(ierr);
ierr = VecDestroy(&x);CHKERRQ(ierr);
ierr = VecDestroy(&r);CHKERRQ(ierr);
ierr = VecDestroy(&xl);CHKERRQ(ierr);
ierr = VecDestroy(&xu);CHKERRQ(ierr);
if (!user.implicit) {
ierr = VecDestroy(&user.q);CHKERRQ(ierr);
ierr = VecDestroy(&user.u);CHKERRQ(ierr);
ierr = VecDestroy(&user.work1);CHKERRQ(ierr);
ierr = MatDestroy(&user.M_0);CHKERRQ(ierr);
}
ierr = MatDestroy(&user.M);CHKERRQ(ierr);
ierr = MatDestroy(&user.S);CHKERRQ(ierr);
ierr = MatDestroy(&J);CHKERRQ(ierr);
ierr = DMDestroy(&user.da);CHKERRQ(ierr);
ierr = TSDestroy(&ts);CHKERRQ(ierr);
PetscFinalize();
return 0;
}
#undef __FUNCT__
#define __FUNCT__ "Update_q"
PetscErrorCode Update_q(TS ts)
{
PetscErrorCode ierr;
AppCtx *user;
Vec x;
PetscScalar *q_arr,*w_arr;
PetscInt i,n;
PetscScalar scale;
PetscFunctionBeginUser;
ierr = TSGetApplicationContext(ts,&user);CHKERRQ(ierr);
ierr = TSGetSolution(ts,&x);CHKERRQ(ierr);
ierr = VecStrideGather(x,1,user->u,INSERT_VALUES);CHKERRQ(ierr);
ierr = MatMult(user->M_0,user->u,user->work1);CHKERRQ(ierr);
scale = -(1.0 - user->implicit)*user->theta_c;
ierr = VecScale(user->work1,scale);CHKERRQ(ierr);
ierr = VecGetLocalSize(user->u,&n);CHKERRQ(ierr);
ierr = VecGetArray(user->q,&q_arr);CHKERRQ(ierr);
ierr = VecGetArray(user->work1,&w_arr);CHKERRQ(ierr);
for (i=0; i<n; i++) q_arr[2*i+1] = w_arr[i];
ierr = VecRestoreArray(user->q,&q_arr);CHKERRQ(ierr);
ierr = VecRestoreArray(user->work1,&w_arr);CHKERRQ(ierr);
PetscFunctionReturn(0);
}
#undef __FUNCT__
#define __FUNCT__ "SetInitialGuess"
PetscErrorCode SetInitialGuess(Vec X,AppCtx *user)
{
PetscErrorCode ierr;
PetscScalar *x;
PetscInt n,i;
PetscRandom rand;
PetscScalar value;
PetscFunctionBeginUser;
ierr = PetscRandomCreate(PETSC_COMM_WORLD,&rand);CHKERRQ(ierr);
ierr = PetscRandomSetFromOptions(rand);CHKERRQ(ierr);
ierr = VecGetLocalSize(X,&n);CHKERRQ(ierr);
ierr = VecGetArray(X,&x);CHKERRQ(ierr);
/* Set initial guess, only set value for 2nd dof */
for (i=0; i<n/2; i++) {
ierr = PetscRandomGetValue(rand,&value);CHKERRQ(ierr);
x[2*i+1] = -0.4 + 0.05*value*(value - 0.5);
}
ierr = VecRestoreArray(X,&x);CHKERRQ(ierr);
ierr = PetscRandomDestroy(&rand);CHKERRQ(ierr);
PetscFunctionReturn(0);
}
static void Gausspoints(PetscScalar *xx,PetscScalar *yy,PetscScalar *w,PetscScalar *x,PetscScalar *y)
{
xx[0] = 2.0/3.0*x[0] + 1.0/6.0*x[1] + 1.0/6.0*x[2];
xx[1] = 1.0/6.0*x[0] + 2.0/3.0*x[1] + 1.0/6.0*x[2];
xx[2] = 1.0/6.0*x[0] + 1.0/6.0*x[1] + 2.0/3.0*x[2];
yy[0] = 2.0/3.0*y[0] + 1.0/6.0*y[1] + 1.0/6.0*y[2];
yy[1] = 1.0/6.0*y[0] + 2.0/3.0*y[1] + 1.0/6.0*y[2];
yy[2] = 1.0/6.0*y[0] + 1.0/6.0*y[1] + 2.0/3.0*y[2];
*w = PetscAbsScalar(x[0]*(y[2]-y[1]) + x[2]*(y[1]-y[0]) + x[1]*(y[0]-y[2]))/6.0;
}
static void ShapefunctionsT3(PetscScalar *phi,PetscScalar phider[][2],PetscScalar xx,PetscScalar yy,PetscScalar *x,PetscScalar *y)
{
PetscScalar area,a1,a2,a3,b1,b2,b3,c1,c2,c3,pp;
/* Area of the triangle */
area = 1.0/2.0*PetscAbsScalar(x[0]*(y[2]-y[1]) + x[2]*(y[1]-y[0]) + x[1]*(y[0]-y[2]));
a1 = x[1]*y[2]-x[2]*y[1]; a2 = x[2]*y[0]-x[0]*y[2]; a3 = x[0]*y[1]-x[1]*y[0];
b1 = y[1]-y[2]; b2 = y[2]-y[0]; b3 = y[0]-y[1];
c1 = x[2]-x[1]; c2 = x[0]-x[2]; c3 = x[1]-x[0];
pp = 1.0/(2.0*area);
/* shape functions */
phi[0] = pp*(a1 + b1*xx + c1*yy);
phi[1] = pp*(a2 + b2*xx + c2*yy);
phi[2] = pp*(a3 + b3*xx + c3*yy);
/* shape functions derivatives */
phider[0][0] = pp*b1; phider[0][1] = pp*c1;
phider[1][0] = pp*b2; phider[1][1] = pp*c2;
phider[2][0] = pp*b3; phider[2][1] = pp*c3;
}
#undef __FUNCT__
#define __FUNCT__ "FormIFunction"
PetscErrorCode FormIFunction(TS ts,PetscReal t, Vec X,Vec Xdot,Vec F,void *ctx)
{
PetscErrorCode ierr;
AppCtx *user=(AppCtx*)ctx;
PetscFunctionBeginUser;
ierr = MatMult(user->M,Xdot,F);CHKERRQ(ierr);
ierr = MatMultAdd(user->S,X,F,F);CHKERRQ(ierr);
if (!user->implicit) {
ierr = VecAXPY(F,1.0,user->q);CHKERRQ(ierr);
}
PetscFunctionReturn(0);
}
#undef __FUNCT__
#define __FUNCT__ "FormIJacobian"
PetscErrorCode FormIJacobian(TS ts, PetscReal t, Vec X, Vec Xdot, PetscReal a, Mat J,Mat B,void *ctx)
{
PetscErrorCode ierr;
AppCtx *user =(AppCtx*)ctx;
static PetscBool copied = PETSC_FALSE;
PetscFunctionBeginUser;
/* for active set method the matrix does not get changed, so do not need to copy each time,
if the active set remains the same for several solves the preconditioner does not need to be rebuilt*/
if (!copied) {
ierr = MatCopy(user->S,J,DIFFERENT_NONZERO_PATTERN);CHKERRQ(ierr);
ierr = MatAXPY(J,a,user->M,DIFFERENT_NONZERO_PATTERN);CHKERRQ(ierr);
copied = PETSC_TRUE;
}
ierr = MatAssemblyBegin(J,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
ierr = MatAssemblyEnd(J,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
/* ierr = MatView(*J,0);CHKERRQ(ierr); */
/* SETERRQ(PETSC_COMM_WORLD,1,"Stopped here\n"); */
PetscFunctionReturn(0);
}
#undef __FUNCT__
#define __FUNCT__ "SetVariableBounds"
PetscErrorCode SetVariableBounds(DM da,Vec xl,Vec xu)
{
PetscErrorCode ierr;
PetscScalar ***l,***u;
PetscInt xs,xm,ys,ym;
PetscInt j,i;
PetscFunctionBeginUser;
ierr = DMDAVecGetArrayDOF(da,xl,&l);CHKERRQ(ierr);
ierr = DMDAVecGetArrayDOF(da,xu,&u);CHKERRQ(ierr);
ierr = DMDAGetCorners(da,&xs,&ys,NULL,&xm,&ym,NULL);CHKERRQ(ierr);
for (j=ys; j < ys+ym; j++) {
for (i=xs; i < xs+xm; i++) {
l[j][i][0] = -PETSC_INFINITY;
l[j][i][1] = -1.0;
u[j][i][0] = PETSC_INFINITY;
u[j][i][1] = 1.0;
}
}
ierr = DMDAVecRestoreArrayDOF(da,xl,&l);CHKERRQ(ierr);
ierr = DMDAVecRestoreArrayDOF(da,xu,&u);CHKERRQ(ierr);
PetscFunctionReturn(0);
}
#undef __FUNCT__
#define __FUNCT__ "GetParams"
PetscErrorCode GetParams(AppCtx *user)
{
PetscErrorCode ierr;
PetscBool flg;
PetscFunctionBeginUser;
/* Set default parameters */
user->tsmonitor = PETSC_FALSE;
user->xmin = 0.0; user->xmax = 1.0;
user->ymin = 0.0; user->ymax = 1.0;
user->T = 0.2; user->dt = 0.0001;
user->gamma = 3.2E-4; user->theta_c = 1;
user->implicit = 0;
ierr = PetscOptionsGetBool(NULL,"-monitor",&user->tsmonitor,NULL);CHKERRQ(ierr);
ierr = PetscOptionsGetReal(NULL,"-xmin",&user->xmin,&flg);CHKERRQ(ierr);
ierr = PetscOptionsGetReal(NULL,"-xmax",&user->xmax,&flg);CHKERRQ(ierr);
ierr = PetscOptionsGetReal(NULL,"-ymin",&user->ymin,&flg);CHKERRQ(ierr);
ierr = PetscOptionsGetReal(NULL,"-ymax",&user->ymax,&flg);CHKERRQ(ierr);
ierr = PetscOptionsGetScalar(NULL,"-gamma",&user->gamma,&flg);CHKERRQ(ierr);
ierr = PetscOptionsGetScalar(NULL,"-theta_c",&user->theta_c,&flg);CHKERRQ(ierr);
ierr = PetscOptionsGetInt(NULL,"-implicit",&user->implicit,&flg);CHKERRQ(ierr);
PetscFunctionReturn(0);
}
#undef __FUNCT__
#define __FUNCT__ "SetUpMatrices"
PetscErrorCode SetUpMatrices(AppCtx *user)
{
PetscErrorCode ierr;
PetscInt nele,nen,i;
const PetscInt *ele;
Vec coords;
const PetscScalar *_coords;
PetscScalar x[3],y[3],xx[3],yy[3],w;
PetscInt idx[3];
PetscScalar phi[3],phider[3][2];
PetscScalar eM_0[3][3],eM_2[3][3];
Mat M = user->M;
Mat S = user->S;
PetscScalar gamma = user->gamma,theta_c=user->theta_c;
PetscInt implicit = user->implicit;
PetscFunctionBeginUser;
/* Get ghosted coordinates */
ierr = DMGetCoordinatesLocal(user->da,&coords);CHKERRQ(ierr);
ierr = VecGetArrayRead(coords,&_coords);CHKERRQ(ierr);
/* Get local element info */
ierr = DMDAGetElements(user->da,&nele,&nen,&ele);CHKERRQ(ierr);
for (i=0; i < nele; i++) {
idx[0] = ele[3*i]; idx[1] = ele[3*i+1]; idx[2] = ele[3*i+2];
x[0] = _coords[2*idx[0]]; y[0] = _coords[2*idx[0]+1];
x[1] = _coords[2*idx[1]]; y[1] = _coords[2*idx[1]+1];
x[2] = _coords[2*idx[2]]; y[2] = _coords[2*idx[2]+1];
ierr = PetscMemzero(xx,3*sizeof(PetscScalar));CHKERRQ(ierr);
ierr = PetscMemzero(yy,3*sizeof(PetscScalar));CHKERRQ(ierr);
Gausspoints(xx,yy,&w,x,y);
eM_0[0][0]=eM_0[0][1]=eM_0[0][2]=0.0;
eM_0[1][0]=eM_0[1][1]=eM_0[1][2]=0.0;
eM_0[2][0]=eM_0[2][1]=eM_0[2][2]=0.0;
eM_2[0][0]=eM_2[0][1]=eM_2[0][2]=0.0;
eM_2[1][0]=eM_2[1][1]=eM_2[1][2]=0.0;
eM_2[2][0]=eM_2[2][1]=eM_2[2][2]=0.0;
PetscInt m;
for (m=0; m<3; m++) {
ierr = PetscMemzero(phi,3*sizeof(PetscScalar));CHKERRQ(ierr);
phider[0][0]=phider[0][1]=0.0;
phider[1][0]=phider[1][1]=0.0;
phider[2][0]=phider[2][1]=0.0;
ShapefunctionsT3(phi,phider,xx[m],yy[m],x,y);
PetscInt j,k;
for (j=0;j<3;j++) {
for (k=0;k<3;k++) {
eM_0[k][j] += phi[j]*phi[k]*w;
eM_2[k][j] += phider[j][0]*phider[k][0]*w + phider[j][1]*phider[k][1]*w;
}
}
}
PetscInt row,cols[6],r;
PetscScalar vals[6];
for (r=0;r<3;r++) {
row = 2*idx[r];
/* Insert values in the mass matrix */
cols[0] = 2*idx[0]+1; vals[0] = eM_0[r][0];
cols[1] = 2*idx[1]+1; vals[1] = eM_0[r][1];
cols[2] = 2*idx[2]+1; vals[2] = eM_0[r][2];
ierr = MatSetValuesLocal(M,1,&row,3,cols,vals,ADD_VALUES);CHKERRQ(ierr);
/* Insert values in the stiffness matrix */
cols[0] = 2*idx[0]; vals[0] = eM_2[r][0];
cols[1] = 2*idx[1]; vals[1] = eM_2[r][1];
cols[2] = 2*idx[2]; vals[2] = eM_2[r][2];
ierr = MatSetValuesLocal(S,1,&row,3,cols,vals,ADD_VALUES);CHKERRQ(ierr);
row = 2*idx[r]+1;
cols[0] = 2*idx[0]; vals[0] = -eM_0[r][0];
cols[1] = 2*idx[0]+1; vals[1] = gamma*eM_2[r][0]-implicit*theta_c*eM_0[r][0];
cols[2] = 2*idx[1]; vals[2] = -eM_0[r][1];
cols[3] = 2*idx[1]+1; vals[3] = gamma*eM_2[r][1]-implicit*theta_c*eM_0[r][1];
cols[4] = 2*idx[2]; vals[4] = -eM_0[r][2];
cols[5] = 2*idx[2]+1; vals[5] = gamma*eM_2[r][2]-implicit*theta_c*eM_2[r][2];
/* Insert values in matrix M for 2nd dof */
ierr = MatSetValuesLocal(S,1,&row,6,cols,vals,ADD_VALUES);CHKERRQ(ierr);
}
}
ierr = DMDARestoreElements(user->da,&nele,&nen,&ele);CHKERRQ(ierr);
ierr = VecRestoreArrayRead(coords,&_coords);CHKERRQ(ierr);
ierr = MatAssemblyBegin(M,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
ierr = MatAssemblyEnd(M,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
ierr = MatAssemblyBegin(S,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
ierr = MatAssemblyEnd(S,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
if (!implicit) {
/* Create ISs to extract matrix M_0 from M */
PetscInt n,rstart;
IS isrow,iscol;
ierr = MatGetLocalSize(M,&n,NULL);CHKERRQ(ierr);
ierr = MatGetOwnershipRange(M,&rstart,NULL);CHKERRQ(ierr);
ierr = ISCreateStride(PETSC_COMM_WORLD,n/2,rstart,2,&isrow);CHKERRQ(ierr);
ierr = ISCreateStride(PETSC_COMM_WORLD,n/2,rstart+1,2,&iscol);CHKERRQ(ierr);
/* Extract M_0 from M */
ierr = MatGetSubMatrix(M,isrow,iscol,MAT_INITIAL_MATRIX,&user->M_0);CHKERRQ(ierr);
ierr = VecCreate(PETSC_COMM_WORLD,&user->u);CHKERRQ(ierr);
ierr = VecSetSizes(user->u,n/2,PETSC_DECIDE);CHKERRQ(ierr);
ierr = VecSetFromOptions(user->u);CHKERRQ(ierr);
ierr = VecDuplicate(user->u,&user->work1);CHKERRQ(ierr);
ierr = ISDestroy(&isrow);CHKERRQ(ierr);
ierr = ISDestroy(&iscol);CHKERRQ(ierr);
}
PetscFunctionReturn(0);
}
#undef __FUNCT__
#define __FUNCT__ "Monitor"
PetscErrorCode Monitor(TS ts,PetscInt steps,PetscReal time,Vec x,void *mctx)
{
PetscErrorCode ierr;
PetscFunctionBeginUser;
ierr = PetscPrintf(PETSC_COMM_WORLD,"Solution vector at t = %5.4f\n",time,steps);CHKERRQ(ierr);
ierr = VecView(x,PETSC_VIEWER_STDOUT_WORLD);CHKERRQ(ierr);
PetscFunctionReturn(0);
}
| 2.046875 | 2 |
2024-11-18T22:22:11.725755+00:00 | 2014-12-26T13:57:11 | b40615db90b5d9ad81746abd3649a9468700aa9a | {
"blob_id": "b40615db90b5d9ad81746abd3649a9468700aa9a",
"branch_name": "refs/heads/master",
"committer_date": "2014-12-26T13:57:11",
"content_id": "bb8469c3bf1ad040f0da6644ff7c3b333d67ab9e",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "e4ca0256683006a6dad5b64c13d80c56aa88a4f5",
"extension": "c",
"filename": "data.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": 9350,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/data.c",
"provenance": "stackv2-0123.json.gz:17058",
"repo_name": "chvik/minerva",
"revision_date": "2014-12-26T13:57:11",
"revision_id": "28b5f12c6baea58060dc681f49700c92aad32b75",
"snapshot_id": "c74740a7f73e0d33ee2a5e94e1f44968a1b62fc1",
"src_encoding": "ISO-8859-2",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/chvik/minerva/28b5f12c6baea58060dc681f49700c92aad32b75/data.c",
"visit_date": "2016-09-09T23:41:08.995517"
} | stackv2 | #include <stdio.h>
#include <ctype.h>
#include <string.h>
#include "latin.h"
#include "nominal.h"
#include "verb.h"
#define DATA_FILE "latin.dat"
#define INDEX_FILE_PREFIX "lat"
#define INDEX_FILE_POSTFIX ".ind"
#define STR_NOUN "n"
#define STR_ADJ "a"
#define STR_VERB "v"
#define STR_POADV "adv"
#define STR_PRAEP "praep"
#define STR_POCON "c"
#define STR_INTIE "i"
#define STR_PRON "pron"
#define STR_NUMER "num"
#define STR_CET "cet"
#define STR_DECL1 "1"
#define STR_DECL2 "2"
#define STR_DECL2_0 "0"
#define STR_DECL2_ER "er"
#define STR_DECL3 "3"
#define STR_DECL3_I1 "i1" /* Csak plur. gen-ban. */
#define STR_DECL3_I2 "i2" /* Sing. abl-ban is. */
#define STR_DECL4 "4"
#define STR_DECL5 "5"
#define STR_END3 "3"
#define STR_END3_0 "0"
#define STR_END3_ER "er"
#define STR_DECL3_END3 "33"
#define STR_DECL3_END3_ER "er"
#define STR_DECL3_END2 "2"
#define STR_DECL3_END1 "1"
#define STR_DECL3_NOT_I "ni"
#define STR_COMP_IRREG "ci"
#define STR_SUPER_IRREG "si"
#define STR_SUPER_IRREG_L "sl"
#define STR_ADV_IRREG "ai"
#define STR_NO_COMP "nc"
#define STR_NO_SUPER "ns"
#define STR_MASC "masc"
#define STR_FEMI "fem"
#define STR_NEUT "neut"
#define STR_CONI1 "1"
#define STR_CONI2 "2"
#define STR_CONI3 "3"
#define STR_CONI3I "3i"
#define STR_CONI4 "4"
#define STR_FERO_TYPE "f"
#define STR_CONI1_IRR "irr"
#define STR_DEPONENS "dep"
#define STR_SEMI_DEPONENS "sdep"
#define STR_SHORT_IMPTIV "sh"
#define STR_NO_SUPINUM "ns"
#define STR_NO_PERFECTUM "np"
FILE *indexf, *dataf;
int global;
long oldpos;
void convert(char *str)
{
char tmp[100];
int i, j;
tmp[99] = 0;
strncpy(tmp, str, 99);
j = 0;
for(i = 0; tmp[i]; ++i)
{
if(!isdigit(tmp[i]))
{
str[j] = tmp[i];
++j;
}
}
str[j] = 0;
}
int open_dict(char prefix)
{
char fname[512];
prefix = tolower(prefix);
sprintf(fname, "%s/%s%c%s", DATA_DIR, INDEX_FILE_PREFIX, tolower(prefix),
INDEX_FILE_POSTFIX);
if(prefix != 0)
{
indexf = fopen(fname, "r");
global = 0;
oldpos = -1;
}
else
{
indexf = NULL;
global = 1;
}
sprintf(fname, "%s/%s", DATA_DIR, DATA_FILE);
if((dataf = fopen(fname, "r")) == NULL)
{
fprintf(stderr, "Nem tudom megnyitni a(z) %s/%s fájlt: ", DATA_DIR,
DATA_FILE);
perror("");
exit(-1);
}
return 0;
}
void close_dict()
{
if(indexf) fclose(indexf);
if(dataf) fclose(dataf);
}
int read_item(int *lclass, int *ltype, int *lgen, char *lroot1,
char *lroot2, char *lroot3, char *nom, char *mean)
{
char line[1025];
long pos;
int i;
char strlclass[41], strltype[41], strlgen[41];
if(dataf == NULL) return EOF;
if(!global)
{
if(indexf == NULL)
{
return EOF;
}
if(fread(&pos, sizeof(long), 1, indexf) == 0)
{
return EOF;
}
if(pos > oldpos)
{
for(i = oldpos + 1; i <= pos; ++i)
{
fgets(line, 1024, dataf);
}
} else
{
rewind(dataf);
for(i = 0; i <= pos; ++i)
{
fgets(line, 1024, dataf);
}
}
oldpos = pos;
} else
{
fgets(line, 1024, dataf);
}
if(feof(dataf))
{
return EOF;
} else
{
sscanf(line, "%40s %19s", strlclass, lroot1);
lroot2[0] = 0;
lroot3[0] = 0;
if(strcmp(lroot1, ".") == 0)
{
lroot1[0] = 0;
}
if(strcmp(strlclass, STR_NOUN) == 0)
{
*lclass = NOUN;
sscanf(line, "%*s %*s %40s %40s", strltype, strlgen);
if(strcmp(strlgen, STR_MASC) == 0)
{
*lgen = MASC;
}
else if(strcmp(strlgen, STR_FEMI) == 0)
{
*lgen = FEMI;
}
else if(strcmp(strlgen, STR_NEUT) == 0)
{
*lgen = NEUT;
}
else
{
fprintf(stderr, "%s%s: érvénytelen főnévi nem\n", line,
strlgen);
exit(-1);
}
if(strstr(strltype, STR_DECL1) == strltype)
{
*ltype = DECL1;
}
else if(strstr(strltype, STR_DECL2) == strltype)
{
*ltype = DECL2;
if(strstr(strltype, STR_DECL2_0))
{
*ltype |= DECL2_0;
}
if(strstr(strltype, STR_DECL2_ER))
{
*ltype |= DECL2_ER;
}
}
else if(strstr(strltype, STR_DECL3) == strltype)
{
*ltype = DECL3;
if(strstr(strltype, STR_DECL3_I1))
{
*ltype |= DECL3_I1;
}
if(strstr(strltype, STR_DECL3_I2))
{
*ltype |= DECL3_I2;
}
sscanf(line, "%*s %*s %*s %*s %19s", nom);
}
else if(strstr(strltype, STR_DECL4) == strltype)
{
*ltype = DECL4;
}
else if(strstr(strltype, STR_DECL5) == strltype)
{
*ltype = DECL5;
}
else
{
fprintf(stderr, "%s%s: érvénytelen declinatio\n", line,
strltype);
exit(-1);
}
}
else if(strcmp(strlclass, STR_ADJ) == 0)
{
*lclass = ADJ;
sscanf(line, "%*s %*s %40s", strltype);
if(strstr(strltype, STR_END3) == strltype)
{
*ltype = END3;
if(strstr(strltype, STR_END3_0))
{
*ltype |= END3_0;
}
if(strstr(strltype, STR_END3_ER))
{
*ltype |= END3_ER;
}
}
else if(strstr(strltype, STR_DECL3_END3) == strltype)
{
*ltype = DECL3_END3;
if(strstr(strltype, STR_DECL3_END3_ER))
{
*ltype |= DECL3_END3_ER;
}
}
else if(strstr(strltype, STR_DECL3_END2) == strltype)
{
*ltype = DECL3_END2;
}
else if(strstr(strltype, STR_DECL3_END1) == strltype)
{
*ltype = DECL3_END1;
if(strstr(strltype, STR_DECL3_NOT_I))
{
*ltype |= DECL3_NOT_I;
}
sscanf(line, "%*s %*s %*s %19s", nom);
}
else
{
fprintf(stderr, "%s%s: érvénytelen melléknévi típus\n",
line, strltype);
exit(-1);
}
if(strstr(strltype, STR_COMP_IRREG))
{
*ltype |= COMP_IRREG;
}
if(strstr(strltype, STR_SUPER_IRREG))
{
*ltype |= SUPER_IRREG;
}
if(strstr(strltype, STR_SUPER_IRREG_L))
{
*ltype |= SUPER_IRREG_L;
}
if(strstr(strltype, STR_ADV_IRREG))
{
*ltype |= ADV_IRREG;
}
if(strstr(strltype, STR_NO_COMP))
{
*ltype |= NO_COMP;
}
if(strstr(strltype, STR_NO_SUPER))
{
*ltype |= NO_SUPER;
}
}
else if(strcmp(strlclass, STR_VERB) == 0)
{
*lclass = VERB;
sscanf(line, "%*s %*s %19s %19s %s", lroot2, lroot3, strltype);
if(strcmp(lroot2, ".") == 0)
{
lroot2[0] = 0;
}
if(strcmp(lroot3, ".") == 0)
{
lroot3[0] = 0;
}
if(strstr(strltype, STR_CONI1) == strltype)
{
*ltype = CONI1;
if(strstr(strltype, STR_CONI1_IRR))
{
*ltype |= CONI1_IRR;
}
}
else if(strstr(strltype, STR_CONI2) == strltype)
{
*ltype = CONI2;
}
else if(strstr(strltype, STR_CONI3I) == strltype)
{
*ltype = CONI3I;
}
else if(strstr(strltype, STR_CONI3) == strltype)
{
*ltype = CONI3;
}
else if(strstr(strltype, STR_CONI3I) == strltype)
{
*ltype = CONI3I;
}
else if(strstr(strltype, STR_CONI4) == strltype)
{
*ltype = CONI4;
}
else if(strstr(strltype, STR_FERO_TYPE) == strltype)
{
*ltype = FERO_TYPE;
}
else
{
fprintf(stderr, "%s%s: érvénytelen coniugatio\n", line,
strltype);
exit(-1);
}
if(strstr(strltype, STR_DEPONENS))
{
*ltype |= DEPONENS;
}
if(strstr(strltype, STR_SEMI_DEPONENS))
{
*ltype |= SEMI_DEPONENS;
}
if(strstr(strltype, STR_SHORT_IMPTIV))
{
*ltype |= SHORT_IMPTIV;
}
if(strstr(strltype, STR_NO_SUPINUM))
{
*ltype |= NO_SUPINUM;
}
if(strstr(strltype, STR_NO_PERFECTUM))
{
*ltype |= NO_PERFECTUM;
}
}
else if(strcmp(strlclass, STR_POADV) == 0)
{
*lclass = POADV;
}
else if(strcmp(strlclass, STR_PRAEP) == 0)
{
*lclass = PRAEP;
}
else if(strcmp(strlclass, STR_INTIE) == 0)
{
*lclass = INTIE;
}
else if(strcmp(strlclass, STR_CET) == 0)
{
*lclass = CET;
}
else if(strcmp(strlclass, STR_POCON) == 0)
{
*lclass = POCON;
}
else if(strcmp(strlclass, STR_PRON) == 0)
{
*lclass = PRON;
lroot2[0] = 0;
lroot3[0] = 0;
sscanf(line, "%*s %*s %19[^# \t] %19[^# \t]", lroot2, lroot3);
}
else if(strcmp(strlclass, STR_NUMER) == 0)
{
*lclass = NUMER;
lroot2[0] = 0;
lroot3[0] = 0;
sscanf(line, "%*s %*s %19[^# \t] %19[^# \t]", lroot2, lroot3);
}
else
{
fprintf(stderr, "%s%s: érvénytelen szófaj\n", line,
strlclass);
exit(-1);
}
strcpy(mean, "Nincs megadva a jelentés.");
sscanf(line, "%*[^#]# %199[^\n]", mean);
}
return 0;
}
| 2.0625 | 2 |
2024-11-18T22:22:12.555997+00:00 | 2021-07-08T13:33:49 | dfdb87be1e8aebab11dc47845fa1d9371c04890e | {
"blob_id": "dfdb87be1e8aebab11dc47845fa1d9371c04890e",
"branch_name": "refs/heads/master",
"committer_date": "2021-07-08T13:33:49",
"content_id": "cac7b3cf8e7ea6b6879d9fead8ecbb32d3916446",
"detected_licenses": [
"Apache-2.0",
"MIT"
],
"directory_id": "c9b1d9481663f35a745533e215e512c31f00f945",
"extension": "c",
"filename": "generic_on_off_client.c",
"fork_events_count": 16,
"gha_created_at": "2019-06-13T12:09:22",
"gha_event_created_at": "2022-09-20T23:47:06",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 191755880,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4187,
"license": "Apache-2.0,MIT",
"license_type": "permissive",
"path": "/vendors/realtek/sdk/amebaZ2/component/common/bluetooth/realtek/sdk/example/bt_mesh/lib/model/generic_on_off_client.c",
"provenance": "stackv2-0123.json.gz:17572",
"repo_name": "ambiot/amazon-freertos",
"revision_date": "2021-07-08T13:33:49",
"revision_id": "ef61d5f521de921cc931d9262e3d5af9b75fbd2e",
"snapshot_id": "199d8c8cfebf7d4ce41cdf0377a6622c56ea3f7c",
"src_encoding": "UTF-8",
"star_events_count": 14,
"url": "https://raw.githubusercontent.com/ambiot/amazon-freertos/ef61d5f521de921cc931d9262e3d5af9b75fbd2e/vendors/realtek/sdk/amebaZ2/component/common/bluetooth/realtek/sdk/example/bt_mesh/lib/model/generic_on_off_client.c",
"visit_date": "2023-08-24T08:06:28.437220"
} | stackv2 | /**
*****************************************************************************************
* Copyright(c) 2015, Realtek Semiconductor Corporation. All rights reserved.
*****************************************************************************************
* @file generic_on_off_client.c
* @brief Source file for generic on off client model.
* @details Data types and external functions declaration.
* @author bill
* @date 2017-12-22
* @version v1.0
* *************************************************************************************
*/
/* Add Includes here */
#include "generic_on_off.h"
static mesh_msg_send_cause_t generic_on_off_client_send(const mesh_model_info_p pmodel_info,
uint16_t dst, uint16_t app_key_index,
uint8_t *pmsg, uint16_t msg_len)
{
mesh_msg_t mesh_msg;
mesh_msg.pmodel_info = pmodel_info;
access_cfg(&mesh_msg);
mesh_msg.pbuffer = pmsg;
mesh_msg.msg_len = msg_len;
mesh_msg.dst = dst;
mesh_msg.app_key_index = app_key_index;
return access_send(&mesh_msg);
}
mesh_msg_send_cause_t generic_on_off_get(const mesh_model_info_p pmodel_info, uint16_t dst,
uint16_t app_key_index)
{
generic_on_off_get_t msg;
ACCESS_OPCODE_BYTE(msg.opcode, MESH_MSG_GENERIC_ON_OFF_GET);
return generic_on_off_client_send(pmodel_info, dst, app_key_index, (uint8_t *)&msg, sizeof(msg));
}
mesh_msg_send_cause_t generic_on_off_set(const mesh_model_info_p pmodel_info, uint16_t dst,
uint16_t app_key_index, generic_on_off_t on_off,
uint8_t tid, bool optional,
generic_transition_time_t trans_time, uint8_t delay, bool ack)
{
generic_on_off_set_t msg;
uint32_t len;
if (ack)
{
ACCESS_OPCODE_BYTE(msg.opcode, MESH_MSG_GENERIC_ON_OFF_SET);
}
else
{
ACCESS_OPCODE_BYTE(msg.opcode, MESH_MSG_GENERIC_ON_OFF_SET_UNACK);
}
if (optional)
{
len = sizeof(generic_on_off_set_t);
msg.trans_time = trans_time;
msg.delay = delay;
}
else
{
len = MEMBER_OFFSET(generic_on_off_set_t, trans_time);
}
msg.on_off = on_off;
msg.tid = tid;
return generic_on_off_client_send(pmodel_info, dst, app_key_index, (uint8_t *)&msg, len);
}
static bool generic_on_off_client_receive(mesh_msg_p pmesh_msg)
{
bool ret = TRUE;
uint8_t *pbuffer = pmesh_msg->pbuffer + pmesh_msg->msg_offset;
switch (pmesh_msg->access_opcode)
{
case MESH_MSG_GENERIC_ON_OFF_STAT:
{
generic_on_off_stat_p pmsg = (generic_on_off_stat_p)pbuffer;
generic_on_off_client_status_t status_data;
status_data.src = pmesh_msg->src;
status_data.present_on_off = pmsg->present_on_off;
status_data.optional = FALSE;
if (pmesh_msg->msg_len == sizeof(generic_on_off_stat_t))
{
status_data.optional = TRUE;
status_data.target_on_off = pmsg->target_on_off;
status_data.remaining_time = pmsg->remaining_time;
}
if (NULL != pmesh_msg->pmodel_info->model_data_cb)
{
pmesh_msg->pmodel_info->model_data_cb(pmesh_msg->pmodel_info, GENERIC_ON_OFF_CLIENT_STATUS,
&status_data);
}
}
break;
default:
ret = FALSE;
break;
}
return ret;
}
bool generic_on_off_client_reg(uint8_t element_index, mesh_model_info_p pmodel_info)
{
if (NULL == pmodel_info)
{
return FALSE;
}
pmodel_info->model_id = MESH_MODEL_GENERIC_ON_OFF_CLIENT;
if (NULL == pmodel_info->model_receive)
{
pmodel_info->model_receive = generic_on_off_client_receive;
if (NULL == pmodel_info->model_data_cb)
{
printw("generic on off client reg: missing data process callback!");
}
}
return mesh_model_reg(element_index, pmodel_info);
}
| 2.203125 | 2 |
2024-11-18T22:22:12.937110+00:00 | 2018-12-02T15:10:27 | e410d160198bbbfb08394a81a0b999f94e14a8d8 | {
"blob_id": "e410d160198bbbfb08394a81a0b999f94e14a8d8",
"branch_name": "refs/heads/master",
"committer_date": "2018-12-02T15:10:27",
"content_id": "f03fda5846766fc263f58bc60256db1d0e04a070",
"detected_licenses": [
"MIT"
],
"directory_id": "4e4adcb13d05fa72386625d38f8964aa2049ffd3",
"extension": "h",
"filename": "usart.h",
"fork_events_count": 1,
"gha_created_at": "2017-06-07T17:55:15",
"gha_event_created_at": "2018-12-02T15:10:28",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 93663912,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1757,
"license": "MIT",
"license_type": "permissive",
"path": "/lib/usart.h",
"provenance": "stackv2-0123.json.gz:17830",
"repo_name": "MightyPork/atmega-simon",
"revision_date": "2018-12-02T15:10:27",
"revision_id": "d33cf6bceab5c1584f5534676937125bd1f09d57",
"snapshot_id": "9c08bd122a807deabecd02e4985af02be8cca8c1",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/MightyPork/atmega-simon/d33cf6bceab5c1584f5534676937125bd1f09d57/lib/usart.h",
"visit_date": "2021-03-30T16:18:30.593738"
} | stackv2 | #pragma once
//
// Utilities for UART communication.
//
// First, init uart with usart_init().
// Then enable interrupts you want with usart_XXX_isr_enable().
//
#include <avr/io.h>
#include <avr/pgmspace.h>
#include <util/delay.h>
#include <stdbool.h>
#include <stdint.h>
#include "calc.h"
/* USART BAUD RATE REGISTER values at 16 MHz */
enum {
BAUD_9600 = 103,
BAUD_14400 = 68,
BAUD_19200 = 51,
BAUD_28800 = 34,
BAUD_38400 = 25,
BAUD_57600 = 16,
BAUD_76800 = 12,
BAUD_115200 = 8,
BAUD_250k = 3,
BAUD_500k = 1,
BAUD_1M = 0,
};
/** Init UART with a UBRR value - can use the BAUD_* constants for 16 MHz */
void usart_init(uint16_t ubrr);
/** Set Double Speed Asynchronous mode on or off */
void usart_set_2x(bool set);
/** Check if there's a byte in the RX register */
#define usart_rx_ready() bit_is_high(UCSR0A, RXC0)
/** Check if USART is ready to accept new byte to send */
#define usart_tx_ready() bit_is_high(UCSR0A, UDRE0)
// ---- Enable UART interrupts ------------
/** Enable or disable RX ISR */
#define usart_isr_rx_enable(yes) set_bit(UCSR0B, RXCIE0, (yes))
/** Enable or disable TX ISR (all data sent) */
#define usart_isr_tx_enable(yes) set_bit(UCSR0B, TXCIE0, (yes))
/** Enable or disable DRE ISR (data register empty) */
#define usart_isr_dre_enable(yes) set_bit(UCSR0B, UDRIE0, (yes))
// ---- Basic IO --------------------------
/** Send byte over USART */
void usart_tx(uint8_t data);
/** Receive one byte over USART */
uint8_t usart_rx(void);
/** Clear receive buffer */
void usart_flush_rx(void);
// ---- Strings ---------------------------
/** Send string over UART */
void usart_puts(const char* str);
/** Send progmem string `PSTR("foobar")` over UART */
void usart_puts_P(const char* str);
| 2.421875 | 2 |
2024-11-18T22:22:13.001526+00:00 | 2015-09-24T22:44:36 | 6b012db77dddd6c6ee85ee2b3812dba9b489d0bd | {
"blob_id": "6b012db77dddd6c6ee85ee2b3812dba9b489d0bd",
"branch_name": "refs/heads/master",
"committer_date": "2015-09-24T22:44:36",
"content_id": "f9cc072812b7f62d463e756613826a994dc8f8b6",
"detected_licenses": [
"MIT"
],
"directory_id": "9a418cd69afa238f6788c39d3bde09bf81c4f505",
"extension": "c",
"filename": "nb_cache.c",
"fork_events_count": 1,
"gha_created_at": "2016-02-10T07:15:22",
"gha_event_created_at": "2016-02-10T07:15:22",
"gha_language": null,
"gha_license_id": null,
"github_id": 51426378,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 52135,
"license": "MIT",
"license_type": "permissive",
"path": "/module/cache/nb_cache.c",
"provenance": "stackv2-0123.json.gz:17959",
"repo_name": "opexsw/nodebrain-nb",
"revision_date": "2015-09-24T22:44:36",
"revision_id": "daa774371f235a170382327677e97aade7e1442c",
"snapshot_id": "c5bf8a3b6c989a4b72fd13bf10a01dde74a4c2a5",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/opexsw/nodebrain-nb/daa774371f235a170382327677e97aade7e1442c/module/cache/nb_cache.c",
"visit_date": "2021-01-17T05:23:01.225797"
} | stackv2 | /*
* Copyright (C) 2014 Ed Trettevik <eat@nodebrain.org>
*
* NodeBrain is free software; you can modify and/or redistribute it under the
* terms of either the MIT License (Expat) or the following NodeBrain License.
*
* Permission to use and redistribute with or without fee, in source and binary
* forms, with or without modification, is granted free of charge to any person
* obtaining a copy of this software and included documentation, provided that
* the above copyright notice, this permission notice, and the following
* disclaimer are retained with source files and reproduced in documention
* included with source and binary distributions.
*
* Unless required by applicable law or agreed to in writing, this software is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied.
*
*=============================================================================
* Program: NodeBrain
*
* File: nb_cache.c
*
* Title: Cache Module (prototype)
*
* Function:
*
* This module provides the "cache" skill. It manages a cache table that is
* a tree structure with nodes that contain pointers to cells and associated
* counters and timers. The counters are managed as table rows are added and
* deleted. This type of node is handy for event correlation involving
* repetition and variation of sets of table attributes.
*
* Synopsis:
*
* define <term> node cache:<spec>
*
* <spec> ::= ([[[!]~(<n><timeUnit>)][<thresholds>]:]<attrList>)
* <thresholds> ::= [{<nList>}]["["<nList>"]"][(<nList>)]
* <nList> ::= n [,n [,n] ]
* <attrList> ::= attrSpec [, attrSpec ] ...
* <attrSpec> ::= <attrName>[<thresholds>]
*
*
* Description
*
* This module is a bit complex and is covered in the "NodeBrain Module
* Reference". It is probably best not to say too much here. Since this
* code has been converted to a skill module, the interaction with the
* interpreter is well defined. Ok, well that will be true when this
* module is fully converted to using the nbapi.h header instead of the
* nb.h header. The important thing now is that there are not calls
* into this code except via the well defined skill methods.
*
*=============================================================================
* Enhancements:
*
* o If we insert fewer attributes than a cache supports, complete the row
* with placeholder entries.
* o Use a hash instead of a single list if the lists get long.
* o Double linked lists would clean the logic up but use more space. The
* deletions could be done when the counters go to zero. As is, the entries
* towards the end of the list may not get deleted for a long time.
* o Interval could be replaced with a schedule (probably not much use for that)
* o We should schedule an alert when thresholds reset. We have to provide
* for multiple resets within a given alarm.
*
*=============================================================================
* Change History:
*
* Date Name/Change
* ---------- -----------------------------------------------------------------
* 2001/05/30 Ed Trettevik (original prototype version)
* 2001/07/05 eat - version 0.2.8
* 1) Functions and variables have been renamed just for the fun
* of it, to be more like the object method names used in
* other headers.
* 2) Use of the term event has been replaced with object and entry.
* 3) Counters are now associated with objects of any type, not
* just STRING.
* 4) cacheReset and cacheEmpty are new functions.
* 5) An interval of zero now means counters never decrement
* automatically.
* 6) If the first threshold is zero, cacheInc returns the counter
* without worrying about thresholds.
* 2001/12/28 eat - version 0.2.9d
* 1) Treat [0] threshold as reset threshold, call [1] threshold
* the first threshold.
* 2) Changed the return value from cacheInc
* positive count if no thresholds or count below first threshold
* and the first threshold is active.
* negative count if we hit a threshold.
* zero if first threshold not active and not on a threshold.
* 2002/02/20 eat - version 0.3.0
* 1) Enhanced cache structures and functions to support multiple
* attributes (dimensions) with user assigned names.
*
* define X context cache(~(4h)(h,.){r,.}[k,.]: \
* A(h,.)[k,.],B(h,.)[k,.],C(h,.));
*
* attribute(hit_thresholds){row_thresholds}[value_thresholds]
* attribute(^t0,t1,t2,t3){^t0,t1,t2,t3}[^t0,t1,t2,t3]
*
* assert ("value","value",...),attribute=value,...
*
* The assert statement assigns the positional values to the
* corresponding user defined name. The assert statement examples
* below are similar.
*
* define x context cache(~(4h):source[2],type(100,200));
*
* x assert ("192.168.1.1","CodeRed");
*
* x assert source="192.168.001.001",type="CodeRed";
*
* If there are N attributes, there are N*3+1 counters and
* states revealed to the context rules.
*
* _hits,_rows,_kids,A__hits,A__rows,A__kids,B__hits,...
*
* _hitState,_rowState,_kidState,A__hitState,A__rowState,...
*
* A state variable has a value of "unknown", 0, "minor",
* "major", and "critical" by
* default, depending on the value of the counter relative to
* the threshold. The "unknown" value is set if the counter
* has not reached a new threshold, otherwise it indicates the
* threshold just reached. A value of 0 is set if "alert" is
* used instead of "assert", and the first threshold has not
* been reached.
*
* define r1 if(A._hitState=0):... [alert and threshold not reached]
* define r2 if(not B._kidState=0):... [new threshold reached]
*
* 2002/02/26 eat - version 0.3.0
* 1) Added support for 0.2.9 compatibility. If the following syntax
* is found by nodebrain.c it will automatically call the nbcache0.h
* routines newCache0() and cache0Inc() instead of newCache and
* cacheAssert;
*
* define x context ~8h (0,10,20,50);
*
* x cache "value",attribute=value,....
*
* 2002/08/20 eat - version 0.4.0
* 1) Included an alertCache function to begin prototyping a
* new cache feature that will alert a context when cache rows
* expire. This will be used to delay event notification until
* possible correlated events "fail" to show up in some time
* interval.
* 2002/08/21 eat - version 0.4.0
* 1) Included support for an option to schedule cache alerts
* when rows expire.
*
* define <term> context cache(!~(8h),a,b,c);
*
* 2002/08/22 eat - version 0.4.0
* 1) Renamed cacheInsert to cacheAssert and included a syntax for
* removing rows before they expire.
*
* assert !("hi","there","buddy");
*
* 2002/08/25 eat - version 0.4.0
* 1) Modified cacheAssert() to support terms in addition to string
* literals. This required the addition of a context parameter
* for term resolution.
*
* assert (system,file);
*
* 2) Split into nbcache.h and nbcache.c
* 3) Implemented cache conditions so we can retire the cache0.h
* routines.
*
* <context>{<object_list>}
*
* Unknown - if the object list is unresolved.
* True - if object list is resolved and a matching row is found.
* False - if object list is resolved and no matching row found.
*
* 2002/09/08 eat 0.4.1 Support numbers and functions as list members.
* 2003/03/15 eat 0.5.1 Modified for make file
* 2003/07/20 eat 0.5.4 Included non-counting scheduled cache option
*
* define c context cache(~(10m):a,b);
*
* In this case, we only need one timer element to schedule the
* expiration of an entry. Instead of one timer element to
* decrement for each assertion, we only need a timer element
* for the last assertion for each row. The lack of thresholds
* is the key to not counting.
*
* 2003/07/20 eat 0.5.4 Using consistent scheduled expiration with intervals.
*
* Previously we only scheduled alerts to the cache when context
* alerts where requested via the "!" option in front of the
* interval. We left it up to the assertion routine to check for
* expired rows. Now we always schedule the expiration to get
* the expected reaction in cache reference conditions.
*
* define r1 on(a=1 and c("fred","smith")):...
*
* 2004/09/24 eat 0.6.1 Cancel timer when no more scheduled events
* 2004/09/24 eat 0.6.1 Fixed bug that allowed change to go unpublished
* 2005/04/09 eat 0.6.2 converted to fully conform to skill module API
* 2005/04/30 eat 0.6.2 refined assert/alert methods a bit
*
* We now handle multiple cache assertions within a single
* ASSERT/ALERT statement. It was not so important to enable
* multiple assertions for a single cache, but that is a side
* effect of our implementation. Here is an example showing
* what we wanted to clean up.
*
* define c1 node cache:(a,b(3));
* define c2 node cache:(x(5));
*
* c1. assert ("abc","def"),a=1,b=2,c2("hi"),d=4;
*
* Prior to this fix, the c2("hi") assertion would have split
* the assertion when the threshod of 5 was reached. This would
* mean rules could react to changes in a and b before the
* assertion of d=4 was complete. That violated our claim that
* our reaction to an ASSERT statement is started only after all
* of the assertions are complete. With this fix, that claim is
* true again.
*
* 2005/04/30 eat 0.6.2 Did not eliminate all dependence on nb.h
*
* Back on 4/9 I claimed to have made this module fully conform
* to the Skill Module API. This is true with respect
* the skill methods, but this module still references NodeBrain
* internals exposed by nb.h. I had hoped to finish converting
* this module to enable the use of nbapi.h instead of nb.h. That
* will have to wait for a future release. For now, it must be
* compiled with and included in nb.
*
* 2005/05/13 eat 0.6.3 warning messages for assertion of too many arguments
* 2005/05/13 eat 0.6.3 warning messages for assertion of too few arguments.
* 2005/05/14 eat 0.6.3 cacheBind() modified to accept moduleHandle
* 2008/02/10 eat 0.6.9 converted lists to trees to improve performace for large tables
* 2008/02/13 eat 0.6.9 fixed defect in handling of null argument list: assert ?node();
* 2008/10/01 eat 0.7.2 improved performance when removing timer elements
*
* The timer set is now a double linked list and the last entry of
* a row points to the timer entry if we are not counting nodes.
* In that case, there is only one timer entry per row.
*
* 2008/10/03 eat 0.7.2 Included release condition argument
*
* A release condition is used to empty a cache each time the
* condition transitions to true. It is really just a more
* convenient way to express a rule to empty the cache. The
* following cache is emptied every 8 hours.
*
* define myCache node cache(~(8h)):(a,b,c);
*
* Previously we would have implemented the same functionality
* as follows
*
* define myCache node cache:(a,b,c);
* myCache. define release on(~(8h)) ?myCache();
*
* 2008/10/23 eat 0.7.3 Now using standard API header nb.h
* 2010-02-25 eat 0.7.9 Cleaned up -Wall warning messages
* 2012-12-27 eat 0.8.13 Checker updates
* 2014-04-23 eat 0.9.01 Fixed bug in cacheAlarm
*
* cacheAlarm could previously call cacheDecNode with a NULL
* entry pointer if nbRuleReact modified the timer list cacheAlarm
* is still spinning through.
*=============================================================================
*/
#include "config.h"
#include <nb/nb.h>
# define CACHE_THRESHOLD_INDEX_LIMIT 4
extern struct CACHE_TIMER *cacheTimerFree;
extern struct CACHE_NODE *cacheEntryFree;
extern struct CACHE_ATTR *cacheAttrFree;
extern struct CACHE *cacheFree;
struct CACHE_TIMER{
struct CACHE_TIMER *prior;
struct CACHE_TIMER *next;
struct CACHE_NODE *entry;
time_t time;
};
struct CACHE_NODE{ /* attribute value counter entry */
// next four fields must conform to NB_TreeNode structure
struct CACHE_NODE *left; // left entry in this tree */
struct CACHE_NODE *right; // right entry in this tree */
signed char balance; // AVL balance code (-1 left tall, 0 - balanced, +1 right tall)
unsigned char reserved[7];
nbCELL object; // object pointer - NULL on free list
//
struct CACHE_NODE *root; /* root entry of this list */
struct CACHE_NODE *entry; /* subordinate nodes */
unsigned int hits; /* times asserted in the cache interval */
unsigned int rows; /* rows retained in cache interval */
unsigned int kids; /* subordinate entries */
unsigned char hitIndex; /* index to active hit threshold */
unsigned char rowIndex; /* index to active row threshold */
unsigned char kidIndex; /* index to active kid threshold */
unsigned char flags; // flag bits
};
#define CACHE_NODE_FLAG_LASTCOL 1 // node is in last column
struct CACHE_ATTR{ /* Attribute definition */
struct CACHE_ATTR *next; /* next attribute */
struct CACHE_ATTR *prev; /* prev attribute */
nbCELL term; /* attribute term */
nbCELL hitsTerm; /* attribute__hits term */
nbCELL rowsTerm; /* attribute__rows term */
nbCELL kidsTerm; /* attribute__kids term */
nbCELL hitState; /* attribute__hitState term */
nbCELL rowState; /* attribute__rowState term */
nbCELL kidState; /* attribute__kidState term */
unsigned int hitThresh[CACHE_THRESHOLD_INDEX_LIMIT+1];/* hit thresholds */
unsigned int rowThresh[CACHE_THRESHOLD_INDEX_LIMIT+1];/* row thresholds */
unsigned int kidThresh[CACHE_THRESHOLD_INDEX_LIMIT+1];/* kid thresholds */
};
typedef struct CACHE{
struct CACHE *next; /* next cache on free list */
nbCELL action; /* action causing an alert */
nbCELL context; /* context term owning this cache */
nbCELL node; /* node owning this cache */
nbCELL releaseCell; // Cell (perhaps schedule) that triggers reset
nbCELL releaseSynapse; // synapse - used to respond to reset cell
struct CACHE_ATTR *attr; /* attribute list */
struct CACHE_ATTR *lastattr; /* last attribute */
struct CACHE_NODE *entry; /* object tree */
struct CACHE_TIMER *timer; // root entry for set of timers
nbCELL stateVal[CACHE_THRESHOLD_INDEX_LIMIT];
int interval; /* interval of time to retain cached entries */
unsigned char options; // option bits - see CACHE_OPTION_* below
unsigned char state; // state bits - see CACHE_STATE_* below
char trace; // set for debug
nbSET assertion; /* assertion to schedule if necessary */
nbCELL expireCell; // The string "expire"
nbCELL insertCell; // The string "insert"
nbCELL addCell; // The string "add"
nbCELL deleteCell; // The string "delete"
} NB_Cache;
#define CACHE_OPTION_COUNT 1 // Count hits
#define CACHE_OPTION_EXPIRE 2 // Row expiration alerts requested
#define CACHE_OPTION_EXIST 4 // Row existence alerts requested (insert and delete)
#define CACHE_STATE_PUBLISH 1 // Set when entries inserted or deleted
#define CACHE_STATE_ALERT 2 // Set when thresholds reached
#define CACHE_STATE_ALARM 4 // Set when cache alarm timer is set
// Cache skill memory
struct CACHE_SKILL{
nbCELL unknown; // NodeBrain's unknown value
nbCELL stateVal[CACHE_THRESHOLD_INDEX_LIMIT]; // Threshold state values
};
/*====================================================*/
struct CACHE_TIMER *cacheTimerFree=NULL;
struct CACHE_NODE *cacheEntryFree=NULL;
struct CACHE_ATTR *cacheAttrFree=NULL;
struct CACHE *cacheFree=NULL;
static int cacheParseThreshold();
static struct CACHE_ATTR *newCacheAttr();
static struct CACHE *newCache();
static void printCacheRows();
//static void printCache();
static struct CACHE_NODE *cacheFindRow();
static unsigned int cacheGetCount();
static void cacheNewTimerElement();
static int cacheInsert();
//static void alertCache();
//static int cacheAssertParse();
static void cacheFreeNode();
static void cacheEmptyNode();
static void cacheRemoveNode();
static void cacheDecNode(nbCELL context,struct CACHE *cache,struct CACHE_NODE *entry,struct CACHE_ATTR *attr);
static int cacheRemove();
static void cacheEmpty(nbCELL context,struct CACHE *cache);
static void freeCache();
/*
* Parse threshold list
*/
static int cacheParseThreshold(context,threshold,source)
nbCELL context;
unsigned int threshold[CACHE_THRESHOLD_INDEX_LIMIT];
char **source; {
char symid,token[256],stopchar;
int i=1;
if(**source=='(') stopchar=')';
else if(**source=='{') stopchar='}';
else if(**source=='[') stopchar=']';
else{
nbLogMsg(context,0,'L',"Expecting list starting with '(', '[', or '{'");
return(-1);
}
(*source)++;
if(**source=='^'){
(*source)++;
i=0;
}
else threshold[0]=0;
symid=nbParseSymbol(token,sizeof(token),source);
for(;i<=CACHE_THRESHOLD_INDEX_LIMIT && symid=='i';i++){
threshold[i]=atoi(token);
symid=nbParseSymbol(token,sizeof(token),source);
if(symid==',') symid=nbParseSymbol(token,sizeof(token),source);
}
if(symid=='i'){
nbLogMsg(context,0,'E',"A maximum of %d thresholds may be specified.",CACHE_THRESHOLD_INDEX_LIMIT);
return(-1);
}
threshold[i]=0; /* plug delimiter */
if(**source!=stopchar){
nbLogMsg(context,0,'E',"Expecting list delimiter '%c' at \"%s\"",stopchar,*source);
return(-1);
}
(*source)++;
while(**source==' ') (*source)++; /* skip over space */
return(0);
}
/*
* Create a new cache attribute definition list
*
* (h,.){r,.}[k,.] - special case for level zero
* <term>(h,.){r,.}[k,.]
*
*/
static struct CACHE_ATTR *newCacheAttr(nbCELL context,char **source,int level,struct CACHE_ATTR **backattr,int *threshflag){
char symid,*cursor=*source,*cursave,ident[256];
struct CACHE_ATTR *attr=NULL;
int prefix=1;
while(*cursor==' ') cursor++;
if((attr=cacheAttrFree)!=NULL) cacheAttrFree=attr->next;
else attr=nbAlloc(sizeof(struct CACHE_ATTR));
*backattr=attr; /* plug link to last attribute */
attr->next=NULL;
attr->prev=NULL;
attr->term=NULL;
attr->hitsTerm=NULL;
attr->hitState=NULL;
attr->rowsTerm=NULL;
attr->rowState=NULL;
attr->kidsTerm=NULL;
attr->kidState=NULL;
attr->hitThresh[0]=0;
attr->hitThresh[1]=0;
attr->rowThresh[0]=0;
attr->rowThresh[1]=0;
attr->kidThresh[0]=0;
attr->kidThresh[1]=0;
if(level==0){
if((*cursor>='a' && *cursor<='z') || (*cursor>='A' && *cursor<='Z')) prefix=0;
else if(strchr("({[:",*cursor)==NULL){
nbLogMsg(context,0,'E',"Unexpected character at \"%s\"",cursor);
attr->next=cacheAttrFree;
cacheAttrFree=attr;
return(NULL);
}
attr->term=context;
}
else{
cursave=cursor;
symid=nbParseSymbol(ident,sizeof(ident),&cursor);
if(symid!='t'){
nbLogMsg(context,0,'E',"Expecting attribute name at \"%s\"",cursave);
}
attr->term=nbTermCreate(context,ident,NB_CELL_UNKNOWN);
}
while(strchr("({[",*cursor)){
switch(*cursor){
case '(':
*threshflag|=1;
attr->hitsTerm=nbTermCreate((nbCELL)attr->term,"_hits",NB_CELL_UNKNOWN);
attr->hitState=nbTermCreate((nbCELL)attr->term,"_hitState",NB_CELL_UNKNOWN);
if(cacheParseThreshold(context,attr->hitThresh,&cursor)!=0) return(NULL);
break;
case '{':
*threshflag|=2;
attr->rowsTerm=nbTermCreate((nbCELL)attr->term,"_rows",NB_CELL_UNKNOWN);
attr->rowState=nbTermCreate((nbCELL)attr->term,"_rowState",NB_CELL_UNKNOWN);
if(cacheParseThreshold(context,attr->rowThresh,&cursor)!=0) return(NULL);
break;
case '[':
*threshflag|=4;
attr->kidsTerm=nbTermCreate((nbCELL)attr->term,"_kids",NB_CELL_UNKNOWN);
attr->kidState=nbTermCreate((nbCELL)attr->term,"_kidState",NB_CELL_UNKNOWN);
if(cacheParseThreshold(context,attr->kidThresh,&cursor)!=0) return(NULL);
break;
}
}
if((level>0 && *cursor==',') || prefix==0 || (level==0 && *cursor==':')){
if(prefix) cursor++;
attr->next=newCacheAttr(context,&cursor,level+1,backattr,threshflag);
if(attr->next) attr->next->prev=attr;
else{
attr->next=cacheAttrFree;
cacheAttrFree=attr;
return(NULL);
}
}
else attr->next=NULL;
*source=cursor;
return(attr);
}
/*
* Create a new cache
*
* (a,b,c)
* (~(4h):a,b,c)
* (!~(4h):a,b,c)
* (~(4h)(1000,2000):a,b,c)
* (~(8h)(1000,2000){600,900,1000}[20]:source(200,250)[2],type(50,100))
*/
static struct CACHE *newCache(nbCELL context,char *cursor){
int interval=0,threshflag=0;
char intervalStr[32];
char symid,token[256];
struct CACHE *cache;
struct CACHE_NODE *entry;
struct CACHE_TIMER *timer;
if((entry=cacheEntryFree)==NULL)
entry=nbAlloc(sizeof(struct CACHE_NODE));
else cacheEntryFree=entry->left;
entry->left=NULL;
entry->right=NULL;
entry->root=NULL;
entry->object=NULL;
entry->hits=0;
entry->rows=0;
entry->kids=0;
entry->hitIndex=1;
entry->rowIndex=1;
entry->kidIndex=1;
entry->flags=0;
entry->entry=NULL;
if((timer=cacheTimerFree)==NULL) timer=nbAlloc(sizeof(struct CACHE_TIMER));
else cacheTimerFree=timer->next;
timer->prior=timer;
timer->next=timer;
timer->entry=NULL;
timer->time=0;
if((cache=cacheFree)==NULL) cache=nbAlloc(sizeof(struct CACHE));
else cacheFree=cache->next;
cache->context=context;
cache->node=nbTermGetDefinition(context,context);
cache->attr=NULL;
cache->lastattr=NULL;
cache->entry=entry;
cache->timer=timer; // only required under some conditions but always creating for now
cache->interval=0;
cache->options=0;
cache->state=0;
cache->assertion=NULL;
cache->trace=0;
cache->expireCell=nbCellCreateString(context,"expire");
cache->insertCell=nbCellCreateString(context,"insert");
cache->addCell=nbCellCreateString(context,"add");
cache->deleteCell=nbCellCreateString(context,"delete");
cache->action=nbTermCreate(context,"_action",cache->insertCell);
cache->releaseCell=NULL;
cache->releaseSynapse=NULL;
/* parse definition string */
if(*cursor=='?'){
cache->options|=CACHE_OPTION_EXIST; // alert on row add or delete
cursor++;
}
if(*cursor!='('){
nbLogMsg(context,0,'L',"Expecting left parenthesis at \"%s\"",cursor);
return(NULL);
}
cursor++;
while(*cursor==' ') cursor++;
if(*cursor=='!'){ /* handle option for alert on row expiration */
cache->options|=CACHE_OPTION_EXPIRE;
cursor++;
while(*cursor==' ') cursor++;
}
if(*cursor=='~'){ /* handle interval */
cursor++;
if(*cursor!='('){
nbLogMsg(context,0,'E',"Expecting left parenthesis after tilda");
return(NULL);
}
cursor++;
symid=nbParseSymbol(token,sizeof(token),&cursor);
if(symid!='i'){
nbLogMsg(context,0,'E',"Expecting number to begin interval specification.");
return(NULL);
}
interval=atoi(token);
switch(*cursor){
case 's': sprintf(intervalStr,"%d seconds",interval); break;
case 'm': sprintf(intervalStr,"%d minutes",interval); interval*=60; break;
case 'h': sprintf(intervalStr,"%d hours",interval); interval*=60*60; break;
case 'd': sprintf(intervalStr,"%d days",interval); interval*=60*60*24; break;
default:
nbLogMsg(context,0,'E',"Expecting interval ending with 's', 'm', 'h', or 'd'.");
return(NULL);
}
cursor++;
if(*cursor!=')'){
nbLogMsg(context,0,'E',"Expecting right parenthesis to close interval specification.");
return(NULL);
}
cache->interval=interval;
nbTermCreate(context,"_interval",nbCellCreateString(context,intervalStr));
cursor++;
while(*cursor==' ') cursor++;
}
cache->attr=newCacheAttr(context,&cursor,0,&(cache->lastattr),&threshflag);
if(cache->attr==NULL){
nbLogMsg(context,0,'E',"Cache attribute and threshold list not recognized.");
nbFree(cache,sizeof(struct CACHE));
return(NULL);
}
if(*cursor!=')'){
nbLogMsg(context,0,'E',"Expecting right parenthesis at \"%s\"",cursor);
/* include code to free the attribute list */
return(NULL);
}
if(threshflag&1) cache->options|=CACHE_OPTION_COUNT; // need to count when hit thresholds set
cursor++;
while(*cursor==' ') cursor++;
if(*cursor!=0 && *cursor!=';'){
nbLogMsg(context,0,'E',"Expecting ';' or end-of-line at: %s",cursor);
// include call to free the attribute list
return(NULL);
}
return(cache);
}
static struct CACHE_NODE *cacheFindRow(nbCELL context,struct CACHE *cache,nbSET argSet,struct CACHE_ATTR **attrP){
struct CACHE_NODE *entry;
//NB_Object *object;
//nbCELL object;
nbCELL argCell;
if(cache->trace) nbLogMsg(cache->context,0,'T',"cacheFindRow: called");
entry=cache->entry; /* start with root entry */
argCell=nbListGetCellValue(context,&argSet);
*attrP=cache->attr; // start with first attribute
while(argCell!=NULL){
// replace this with inline macro after testing
entry=(struct CACHE_NODE *)nbTreeFind(argCell,(NB_TreeNode *)entry->entry);
if(entry==NULL || entry->object!=argCell) return(NULL);
argCell=nbListGetCellValue(context,&argSet);
*attrP=(*attrP)->next;
}
if(cache->trace) nbLogMsg(cache->context,0,'T',"cacheFindRow: found an entry");
return(entry);
}
/*
* Find an object in a cache and return the count
*
* The type code indicates which count to return.
*/
static unsigned int cacheGetCount(nbCELL context,struct CACHE *cache,nbSET argSet,int type){
struct CACHE_NODE *entry;
struct CACHE_ATTR *attr;
if(!argSet) entry=cache->entry;
else if((entry=cacheFindRow(context,cache,argSet,&attr))==NULL) return(0);
if(type==0) return(entry->hits);
else if(type==1) return(entry->kids);
else if(type==2) return(entry->rows);
nbLogMsg(cache->context,0,'L',"cacheGetCount: counter type code %d not recognized.",type);
return(0);
}
/*
* Create new timer element
*/
static void cacheNewTimerElement(struct CACHE *cache,struct CACHE_NODE *entry){
struct CACHE_TIMER *timer,*oldtimer;
time_t now;
if((timer=cacheTimerFree)==NULL) timer=nbAlloc(sizeof(struct CACHE_TIMER));
else cacheTimerFree=timer->next;
timer->prior=cache->timer->prior;
timer->next=cache->timer;
timer->prior->next=timer;
timer->next->prior=timer;
timer->entry=entry;
time(&now);
timer->time=now+cache->interval;
if(cache->timer->next==timer && cache->timer->prior==timer){
/* schedule cache alarm when adding first timer element */
nbClockSetTimer(timer->time,cache->node);
cache->state|=CACHE_STATE_ALARM;
}
if(cache->options^CACHE_OPTION_COUNT){ // manage single timer element per row when not counting
if(entry->entry!=NULL){
oldtimer=(struct CACHE_TIMER *)entry->entry;
oldtimer->prior->next=oldtimer->next;
oldtimer->next->prior=oldtimer->prior;
oldtimer->next=cacheTimerFree;
oldtimer->entry=NULL;
cacheTimerFree=oldtimer;
}
entry->entry=(struct CACHE_NODE *)timer; // point node to timer element
}
}
/*
* Insert new entry
*
* This is a recursive function that operates at the node level.
*
* Return Code:
*
* 0 - entry already existed
* 1 - new entry added
*/
static int cacheInsert(nbCELL context,struct CACHE_SKILL *skillHandle,struct CACHE *cache,struct CACHE_NODE *root,nbSET argSet,struct CACHE_ATTR *attr,int mode){
NB_TreePath treePath;
nbCELL object;
//NB_Cell *pub;
struct CACHE_NODE *entry;
int newrow=0;
nbCELL argCell=nbListGetCellValue(context,&argSet);
if(attr==NULL){
nbLogMsg(context,0,'L',"cacheInsert: attr or object is null");
return(-1);
}
/* increment root hits count */
if(cache->options&CACHE_OPTION_COUNT){
root->hits++;
if(attr->hitsTerm!=NULL){
/* assign value to attribute__hits */
nbAssertionAddTermValue(context,&cache->assertion,(nbCELL)attr->hitsTerm,nbCellCreateReal(context,(double)root->hits));
if(attr->hitState!=NULL){
// compute new state and assign value to attribute._hitState
if(attr->hitThresh[root->hitIndex]!=0 && root->hits>=attr->hitThresh[root->hitIndex]){
cache->state|=CACHE_STATE_ALERT;
nbAssertionAddTermValue(context,&cache->assertion,(nbCELL)attr->hitState,skillHandle->stateVal[root->hitIndex]);
root->hitIndex++;
}
// in alert mode, set a normal state value until we hit the first threshold
else if(mode==1 && root->hitIndex==1) nbAssertionAddTermValue(context,&cache->assertion,(nbCELL)attr->hitState,skillHandle->stateVal[0]);
else nbAssertionAddTermValue(context,&cache->assertion,(nbCELL)attr->hitState,(nbCELL)NB_CELL_UNKNOWN);
}
}
}
else{root->hits=1;}
if(attr->next==NULL){ /* return if last attribute */
argCell=nbListGetCellValue(context,&argSet); // see if we have extra arguments
if(argCell!=NULL){
nbLogMsg(context,0,'W',"Extra assertion arguments ignored");
}
if(cache->interval) cacheNewTimerElement(cache,root);
root->flags|=CACHE_NODE_FLAG_LASTCOL;
if(root->rows==0){
root->rows=1;
return(1);
}
return(0);
}
if(argSet==NULL){
nbLogMsg(context,0,'W',"Placeholder used for unspecified assertion arguments");
object=NB_CELL_PLACEHOLDER;
}
else if(argCell==NULL){
nbLogMsg(context,0,'L',"cacheInsert: object is null");
return(-1);
}
else object=argCell; // assign value to attribute term in context
nbAssertionAddTermValue(context,&cache->assertion,(nbCELL)attr->next->term,(nbCELL)object);
entry=(struct CACHE_NODE *)nbTreeLocate(&treePath,object,(NB_TreeNode **)&root->entry);
if(entry==NULL){
/* create an entry here */
if((entry=cacheEntryFree)==NULL) entry=nbAlloc(sizeof(struct CACHE_NODE));
else cacheEntryFree=entry->left;
entry->object=object;
nbTreeInsert(&treePath,(NB_TreeNode *)entry);
entry->root=root;
entry->entry=NULL;
entry->hits=0;
entry->rows=0;
entry->kids=0;
entry->hitIndex=1; /* zero index is for reset threshold */
entry->rowIndex=1; /* zero index is for reset threshold */
entry->kidIndex=1; /* zero index is for reset threshold */
entry->flags=0;
root->kids++;
if(attr->kidState!=NULL){
if(attr->kidThresh[root->kidIndex]!=0 && root->kids>=attr->kidThresh[root->kidIndex]){
cache->state|=CACHE_STATE_ALERT;
nbAssertionAddTermValue(context,&cache->assertion,(nbCELL)attr->kidState,skillHandle->stateVal[root->kidIndex]);
root->kidIndex++;
}
else if(mode==1 && root->kidIndex==1) nbAssertionAddTermValue(context,&cache->assertion,(nbCELL)attr->kidState,skillHandle->stateVal[0]);
else nbAssertionAddTermValue(context,&cache->assertion,(nbCELL)attr->kidState,(nbCELL)NB_CELL_UNKNOWN);
}
cache->state|=CACHE_STATE_PUBLISH; // set publish flag
}
else{
nbCellDrop(context,object); // drop the objects we don't add
if(attr->kidState!=NULL){
if(mode==1 && root->kidIndex==1) nbAssertionAddTermValue(context,&cache->assertion,(nbCELL)attr->kidState,skillHandle->stateVal[0]);
else nbAssertionAddTermValue(context,&cache->assertion,(nbCELL)attr->kidState,NB_CELL_UNKNOWN);
}
}
if(attr->kidsTerm!=NULL) nbAssertionAddTermValue(context,&cache->assertion,(nbCELL)attr->kidsTerm,nbCellCreateReal(context,(double)root->kids));
/* handle next attribute */
//if(list!=NULL) list=list->next;
newrow=cacheInsert(context,skillHandle,cache,entry,argSet,attr->next,mode);
if(newrow<0){
// back out the node here
return(newrow);
}
if(newrow){
root->rows++;
if(attr->rowState!=NULL){
if(attr->rowThresh[root->rowIndex]!=0 && root->rows>=attr->rowThresh[root->rowIndex]){
cache->state|=CACHE_STATE_ALERT;
nbAssertionAddTermValue(context,&cache->assertion,(nbCELL)attr->rowState,skillHandle->stateVal[root->rowIndex]);
root->rowIndex++;
}
// in alert mode, set a normal state value until we hit the first threshold
else if(mode==1 && root->rowIndex==1) nbAssertionAddTermValue(context,&cache->assertion,(nbCELL)attr->rowState,skillHandle->stateVal[0]);
else nbAssertionAddTermValue(context,&cache->assertion,(nbCELL)attr->rowState,(nbCELL)NB_CELL_UNKNOWN);
}
newrow=1;
}
else if(attr->rowState!=NULL){
// in alert mode, set a normal state value until we hit the first threshold
if(mode==1 && root->rowIndex==1) nbAssertionAddTermValue(context,&cache->assertion,(nbCELL)attr->rowState,skillHandle->stateVal[0]);
else nbAssertionAddTermValue(context,&cache->assertion,(nbCELL)attr->rowState,(nbCELL)NB_CELL_UNKNOWN);
}
if(attr->rowsTerm!=NULL) nbAssertionAddTermValue(context,&cache->assertion,(nbCELL)attr->rowsTerm,nbCellCreateReal(context,(double)root->rows));
return(newrow);
}
/*
* Cache reset alarm handler
*/
static void cacheResetAlarm(nbCELL context,void *skillHandle,void *nodeHandle,nbCELL cell){
NB_Cache *cache=(NB_Cache *)nodeHandle;
nbCELL value=nbCellGetValue(context,cell);
if(value!=NB_CELL_TRUE) return; // only act when schedule toggles to true
cacheEmpty(context,cache);
}
/*
* Cache alarm handler - decrement counters and remove expired rows
*
* o We should actually use event time here, not system clock time
* because we may want to do a simulation.
* o This function is called by alertContext.
* o The alertContext alert is scheduled when a row is added to an empty
* cache, and rescheduled by alertCache if not emptied.
* o This only applies to a cache with an expiration interval.
*/
static void cacheAlarm(nbCELL context,void *skillHandle,NB_Cache *cache){
struct CACHE_TIMER *timer,*timerRoot=cache->timer;
struct CACHE_NODE *entry;
struct CACHE_ATTR *attr;
time_t now;
cache->state&=0xff^CACHE_STATE_ALARM;
time(&now);
if(cache->options&CACHE_OPTION_EXPIRE){
nbTermSetDefinition(context,cache->action,cache->expireCell);
for(attr=cache->attr;attr!=NULL;attr=attr->next){
if(attr->hitState!=NULL) nbTermSetDefinition(context,attr->hitState,NULL);
if(attr->rowState!=NULL) nbTermSetDefinition(context,attr->rowState,NULL);
if(attr->kidState!=NULL) nbTermSetDefinition(context,attr->kidState,NULL);
}
}
timer=timerRoot->next;
while(timer!=timerRoot && timer->time<=now){
int expire=0;
timerRoot->next=timer->next;
timer->next->prior=timerRoot;
timer->next=cacheTimerFree;
cacheTimerFree=timer;
if(cache->options&CACHE_OPTION_EXPIRE && timer->entry->hits<2){
attr=cache->lastattr;
for(entry=timer->entry;entry!=cache->entry;entry=entry->root){
nbTermSetDefinition(context,attr->term,entry->object);
attr=attr->prev;
}
expire=1;
}
cacheDecNode(context,cache,timer->entry,cache->lastattr);
timer->entry=NULL;
if(expire){
nbRuleReact();
nbNodeAlert(context,cache->context);
timerRoot=cache->timer; // 2014-04-23 eat - nbRuleReact could modify timer list
}
timer=timerRoot->next;
}
if(cache->options&CACHE_OPTION_EXPIRE) nbTermSetDefinition(context,cache->action,cache->insertCell);
if(cache->state^CACHE_STATE_ALARM && cache->timer->next!=cache->timer){
nbClockSetTimer(cache->timer->next->time,cache->node);
cache->state|=CACHE_STATE_ALARM;
}
if(cache->state&CACHE_STATE_PUBLISH) nbCellPub(context,cache->context);
}
/*
* Free entry - this should be done in-line after validation
*/
static void cacheFreeNode(nbCELL context,struct CACHE_NODE *entry){
/*
outMsg(0,'T',"cacheFreeNode called");
printObject(entry->object);
nbLogPut(context,"\n");
*/
nbCellDrop(context,entry->object);
entry->object=NULL;
entry->left=cacheEntryFree; /* return to free list */
entry->right=NULL;
entry->root=NULL;
entry->entry=NULL;
entry->flags=0;
cacheEntryFree=entry;
}
/*
* Empty a cache entry's object tree without worrying about counters
*/
static void cacheEmptyNode(nbCELL context,struct CACHE_NODE *entry){
struct CACHE_NODE *subEntry;
NB_TreeIterator treeIterator;
NB_TreeNode *treeNode;
//nbLogMsg(context,0,'T',"cacheEmptyNode called");
//printObject(entry->object);
//nbLogPut(context,"\n");
NB_TREE_ITERATE2(treeIterator,treeNode,(NB_TreeNode *)entry->entry){
subEntry=(struct CACHE_NODE *)treeNode;
if(subEntry->flags^CACHE_NODE_FLAG_LASTCOL) cacheEmptyNode(context,subEntry);
NB_TREE_ITERATE_NEXT2(treeIterator,treeNode)
cacheFreeNode(context,subEntry);
}
entry->entry=NULL;
}
/*
* Remove a cache entry worrying about counters up the root list
*/
static void cacheRemoveNode(nbCELL context,struct CACHE *cache,struct CACHE_NODE *entry,struct CACHE_ATTR *attr){
NB_TreePath treePath;
NB_TreeNode *treeNode;
struct CACHE_NODE *root;
unsigned int hits=entry->hits,rows=entry->rows;
while(entry->root!=NULL){ /* until we get to the top */
root=entry->root;
treeNode=nbTreeLocate(&treePath,entry->object,(NB_TreeNode **)&root->entry);
if(treeNode!=(NB_TreeNode *)entry){
nbLogMsg(context,0,'L',"cache node not found in owning tree - aborting");
exit(1);
}
nbTreeRemove(&treePath);
if(entry->entry!=NULL && entry->flags^CACHE_NODE_FLAG_LASTCOL) cacheEmptyNode(context,entry);
cacheFreeNode(context,entry);
cache->state|=CACHE_STATE_PUBLISH;
if(root->entry!=NULL || root->root==NULL){
attr=attr->prev;
root->kids--;
if(root->kids<attr->kidThresh[0]) root->kidIndex=1;
while(root!=NULL){
if(cache->options&CACHE_OPTION_COUNT){ /* if we are counting */
root->hits-=hits;
if(root->hits<attr->hitThresh[0]) root->hitIndex=1;
}
root->rows-=rows;
if(root->rows<attr->rowThresh[0]) root->rowIndex=1;
root=root->root;
attr=attr->prev;
}
return;
}
entry=root;
attr=attr->prev;
}
}
static void cacheDecNode(nbCELL context,struct CACHE *cache,struct CACHE_NODE *entry,struct CACHE_ATTR *attr){
if(entry->hits<2) cacheRemoveNode(context,cache,entry,attr);
else if(cache->options&CACHE_OPTION_COUNT) while(entry!=NULL){
entry->hits--;
if(entry->hits<attr->hitThresh[0]) entry->hitIndex=1;
entry=entry->root;
}
}
/*
* Remove a cache row
*/
static int cacheRemove(nbCELL context,struct CACHE *cache,nbSET argSet){
struct CACHE_TIMER *timer;
struct CACHE_NODE *entry;
struct CACHE_ATTR *attr;
if((entry=cacheFindRow(context,cache,argSet,&attr))==NULL) return(0);
cacheRemoveNode(context,cache,entry,attr);
/* remove any timer elements pointing to removed entries - may be more than one */
for(timer=cache->timer->next;timer!=cache->timer;timer=timer->next){
if(timer->entry->object==NULL){ /* if in the free entry list */
timer->prior->next=timer->next;
timer->next->prior=timer->prior;
timer->next=cacheTimerFree; /* return to free list */
timer->entry=NULL;
cacheTimerFree=timer;
timer=timer->prior;
}
}
/* cancel alarm timer when the cache becomes empty */
if(cache->interval && cache->timer->next==cache->timer){
nbClockSetTimer(0,cache->node);
cache->state&=0xff^CACHE_STATE_ALARM;
}
return(1);
}
/*
* Empty a cache - delete all counter entries and timer elements
*/
static void cacheEmpty(nbCELL context,struct CACHE *cache){
struct CACHE_TIMER *timer,*timerNext;
struct CACHE_NODE *entry;
//nbLogMsg(context,0,'T',"cacheEmpty called");
if(cache==NULL || cache->entry==NULL) return;
/* cancel alarm timer if set */
if(cache->state&CACHE_STATE_ALARM){
nbClockSetTimer(0,cache->node);
cache->state&=0xff^CACHE_STATE_ALARM;
}
for(timer=cache->timer->next;timer!=cache->timer;timer=timerNext){
timerNext=timer->next;
timer->next=cacheTimerFree; /* return to free list */
timer->entry=NULL;
cacheTimerFree=timer;
}
cache->timer->prior=cache->timer;
cache->timer->next=cache->timer;
entry=cache->entry;
cacheEmptyNode(context,entry);
entry->hits=0;
entry->rows=0;
entry->kids=0;
entry->hitIndex=1;
entry->rowIndex=1;
entry->kidIndex=1;
cache->state|=CACHE_STATE_PUBLISH;
}
/*
* Free a cache - let nbNodeDestroy() do this
*/
static void freeCache(nbCELL context,struct CACHE *cache){
if(cache==NULL) return;
cacheEmpty(context,cache);
nbFree(cache,sizeof(struct CACHE));
}
/******************************************************
* Skill methods
******************************************************/
static nbCELL cacheHitsEvaluate(nbCELL context,void *skillHandle,NB_Cache *cache,nbCELL arglist){
nbSET argSet=nbListOpen(context,arglist);
unsigned int count;
if(!cache) return(NB_CELL_UNKNOWN);
count=cacheGetCount(context,cache,argSet,0); // Get hits count
return(nbCellCreateReal(context,(double)count));
}
static nbCELL cacheKidsEvaluate(nbCELL context,void *skillHandle,NB_Cache *cache,nbCELL arglist){
nbSET argSet=nbListOpen(context,arglist);
unsigned int count;
if(!cache) return(NB_CELL_UNKNOWN);
count=cacheGetCount(context,cache,argSet,1); // Get kids count
return(nbCellCreateReal(context,(double)count));
}
static nbCELL cacheRowsEvaluate(nbCELL context,void *skillHandle,NB_Cache *cache,nbCELL arglist){
nbSET argSet=nbListOpen(context,arglist);
unsigned int count;
if(!cache) return(NB_CELL_UNKNOWN);
count=cacheGetCount(context,cache,argSet,2); // Get rows count
return(nbCellCreateReal(context,(double)count));
}
/******************************************************
* Skill methods
******************************************************/
static void *cacheConstruct(nbCELL context,void *skillHandle,nbCELL arglist,char *text){
nbCELL cell;
nbSET argSet;
struct CACHE *cache=newCache(context,text);
if(cache==NULL) return(NULL);
argSet=nbListOpen(context,arglist);
cell=nbListGetCell(context,&argSet);
if(cell!=NULL){ // if we have a reset cell expression, then create synapse
cache->releaseCell=cell;
cache->releaseSynapse=nbSynapseOpen(context,skillHandle,cache,cache->releaseCell,cacheResetAlarm);
if(NULL!=nbListGetCellValue(context,&argSet)){
nbLogMsg(context,0,'E',"Cache skill only accepts one argument.");
return(NULL);
}
}
return(cache);
}
static int cacheAssert(nbCELL context,void *skillHandle,NB_Cache *cache,nbCELL arglist,nbCELL value){
int mode=0; // we only assert via standard interface
nbSET argSet;
int inserted=0,removed=0; // flag indicated if known state was inverted
//nbLogMsg(context,0,'T',"cacheAssert called");
if(arglist==NULL) return(0); // perhaps we should set the value of the tree itself
argSet=nbListOpen(context,arglist);
cache->state&=0xff^(CACHE_STATE_PUBLISH&CACHE_STATE_ALERT); // reset flags
if(value!=NB_CELL_FALSE && value!=NB_CELL_UNKNOWN)
inserted=cacheInsert(context,skillHandle,cache,cache->entry,argSet,cache->attr,mode);
else if(argSet==NULL) cacheEmpty(context,cache);
else removed=cacheRemove(context,cache,argSet);
if(cache->state&CACHE_STATE_PUBLISH) nbCellPub(context,cache->context);
if(cache->state&CACHE_STATE_ALERT) nbAction(context,cache->assertion,"",NB_CMDOPT_HUSH|NB_CMDOPT_ALERT);
else if(cache->options&CACHE_OPTION_EXIST && inserted){
//nbTermSetDefinition(context,cache->action,cache->addCell);
nbAssertionAddTermValue(context,&cache->assertion,cache->action,cache->addCell);
nbAction(context,cache->assertion,"",NB_CMDOPT_HUSH|NB_CMDOPT_ALERT);
}
else if(cache->options&CACHE_OPTION_EXIST && removed){
//nbTermSetDefinition(context,cache->action,cache->deleteCell);
nbAssertionAddTermValue(context,&cache->assertion,cache->action,cache->deleteCell);
nbAction(context,cache->assertion,"",NB_CMDOPT_HUSH|NB_CMDOPT_ALERT);
}
else nbAction(context,cache->assertion,"",NB_CMDOPT_HUSH);
cache->assertion=NULL;
return(0);
}
// This is just a test to see if the alert method is going to solve our problem
// If it works, break out a subroutine to be called by both cacheAssert and cacheAlert
// The only difference is the mode value call to contextAlert
static int cacheAlert(nbCELL context,void *skillHandle,NB_Cache *cache,nbCELL arglist,nbCELL value){
int mode=1; /* we only assert via standard interface */
nbSET argSet=nbListOpen(context,arglist);
cache->state&=0xff^(CACHE_STATE_PUBLISH&CACHE_STATE_ALERT); // reset flags
if(value!=NB_CELL_FALSE && value!=NB_CELL_UNKNOWN){
cacheInsert(context,skillHandle,cache,cache->entry,argSet,cache->attr,mode);
}
else if(arglist==NULL) cacheEmpty(context,cache);
else cacheRemove(context,cache,argSet);
if(cache->state&CACHE_STATE_PUBLISH) nbCellPub(context,cache->context);
nbAction(context,cache->assertion,"",NB_CMDOPT_HUSH|NB_CMDOPT_ALERT);
cache->assertion=NULL;
return(0);
}
static nbCELL cacheEvaluate(nbCELL context,void *skillHandle,NB_Cache *cache,nbCELL arglist){
nbSET argSet=nbListOpen(context,arglist);
if(!argSet) return(NB_CELL_UNKNOWN); /* cache itself has no value */
if(!cache) return(NB_CELL_UNKNOWN);
if(cache->trace) nbLogMsg(context,0,'T',"cacheEvaluate: called"); // 2012-12-27 eat 0.8.13 - CID 76122 - must follow check for NULL cache
if(arglist==NB_CELL_UNKNOWN) return(NB_CELL_UNKNOWN);
if(cacheGetCount(context,cache,argSet,(int)0)) return(NB_CELL_TRUE);
if(cache->trace) nbLogMsg(context,0,'T',"evalCache: returning false");
return(NB_CELL_FALSE);
}
static void cacheSolve(nbCELL context,void *skillHandle,NB_Cache *cache,nbCELL arglist){
nbCellSolve(context,arglist);
return;
}
static void printCacheRows(nbCELL context,struct CACHE_NODE *entry,int column){
NB_TreeIterator treeIterator;
NB_TreeNode *treeNode;
int i;
nbLogPut(context,"\n");
NB_TREE_ITERATE(treeIterator,treeNode,(NB_TreeNode *)entry){
entry=(struct CACHE_NODE *)treeNode;
for(i=0;i<column;i++) nbLogPut(context," ");
nbCellShow(context,entry->object);
nbLogPut(context,"(%u:%u)",entry->hits,entry->hitIndex);
//if(entry->entry!=NULL){
if(entry->flags^CACHE_NODE_FLAG_LASTCOL){
nbLogPut(context,"{%u:%u}",entry->rows,entry->rowIndex);
nbLogPut(context,"[%u:%u],",entry->kids,entry->kidIndex);
printCacheRows(context,entry->entry,column+1);
}
else nbLogPut(context,"\n");
NB_TREE_ITERATE_NEXT(treeIterator,treeNode)
}
}
/*
* Show cache
*/
static int cacheShow(nbCELL context,void *skillHandle,NB_Cache *cache,int option){
// struct CACHE_NODE *entry;
struct CACHE_ATTR *attr=cache->attr;
int i;
if(option==NB_SHOW_REPORT) nbLogPut(context," Specification: ");
if(cache->releaseCell){
nbLogPut(context,"(");
nbCellShow(context,cache->releaseCell);
nbLogPut(context,")");
}
nbLogPut(context,":(~(%ds)",cache->interval);
for(attr=cache->attr;attr!=NULL;attr=attr->next){
if(attr->term!=NULL && attr!=cache->attr) nbLogPut(context,nbTermGetName(context,attr->term));
if(attr->hitThresh[1]!=0){
nbLogPut(context,"(^%d",attr->hitThresh[0]);
for(i=1;i<=CACHE_THRESHOLD_INDEX_LIMIT && attr->hitThresh[i]!=0;i++)
nbLogPut(context,",%d",attr->hitThresh[i]);
nbLogPut(context,")");
}
if(attr->rowThresh[1]!=0){
nbLogPut(context,"{^%d",attr->rowThresh[0]);
for(i=1;i<=CACHE_THRESHOLD_INDEX_LIMIT && attr->rowThresh[i]!=0;i++)
nbLogPut(context,",%d",attr->rowThresh[i]);
nbLogPut(context,"}");
}
if(attr->kidThresh[1]!=0){
nbLogPut(context,"[^%d",attr->kidThresh[0]);
for(i=1;i<=CACHE_THRESHOLD_INDEX_LIMIT && attr->kidThresh[i]!=0;i++)
nbLogPut(context,",%d",attr->kidThresh[i]);
nbLogPut(context,"]");
}
if(attr->next!=NULL){
if(attr==cache->attr) nbLogPut(context,":");
else nbLogPut(context,",");
}
}
nbLogPut(context,")");
if(option==NB_SHOW_REPORT){
nbLogPut(context,"\n Options: Expire=%d Count=%d",(cache->options&CACHE_OPTION_EXPIRE)>0,(cache->options&CACHE_OPTION_COUNT)>0);
nbLogPut(context,"\n Status: Alert=%d Publish=%d\n Elements:",(cache->state&CACHE_STATE_ALERT)>0,(cache->state&CACHE_STATE_PUBLISH)>0);
nbLogFlush(context);
printCacheRows(context,cache->entry,2);
}
return(0);
}
static void *cacheDestroy(nbCELL context,void *skillHandle,NB_Cache *cache,int option){
freeCache(context,cache);
return(NULL);
}
#if defined(_WINDOWS)
_declspec (dllexport)
#endif
extern void *cacheBind(nbCELL context,void *moduleHandle,nbCELL skill,nbCELL arglist,char *text){
struct CACHE_SKILL *skillHandle=nbAlloc(sizeof(struct CACHE_SKILL));
nbCELL facet;
skillHandle->unknown=nbCellCreate(context,"?");
skillHandle->stateVal[0]=nbCellCreateString(context,"normal");
skillHandle->stateVal[1]=nbCellCreateString(context,"minor");
skillHandle->stateVal[2]=nbCellCreateString(context,"major");
skillHandle->stateVal[3]=nbCellCreateString(context,"critical");
nbSkillSetMethod(context,skill,NB_NODE_CONSTRUCT,cacheConstruct);
nbSkillSetMethod(context,skill,NB_NODE_ASSERT,cacheAssert);
nbSkillSetMethod(context,skill,NB_NODE_EVALUATE,cacheEvaluate);
nbSkillSetMethod(context,skill,NB_NODE_SOLVE,cacheSolve); /* do we need this? */
nbSkillSetMethod(context,skill,NB_NODE_SHOW,cacheShow);
nbSkillSetMethod(context,skill,NB_NODE_DESTROY,cacheDestroy);
nbSkillSetMethod(context,skill,NB_NODE_ALARM,cacheAlarm);
nbSkillSetMethod(context,skill,NB_NODE_ALERT,cacheAlert);
// 2013-12-07 eat - experimenting with facets
facet=nbSkillFacet(context,skill,"hits");
nbSkillMethod(context,facet,NB_NODE_EVALUATE,cacheHitsEvaluate);
facet=nbSkillFacet(context,skill,"kids");
nbSkillMethod(context,facet,NB_NODE_EVALUATE,cacheKidsEvaluate);
facet=nbSkillFacet(context,skill,"rows");
nbSkillMethod(context,facet,NB_NODE_EVALUATE,cacheRowsEvaluate);
return(skillHandle);
}
| 2.03125 | 2 |
2024-11-18T22:22:13.611509+00:00 | 2021-09-15T08:36:28 | 1180fe048cc71dcc42641f40ff5ceb1a1b3eaf23 | {
"blob_id": "1180fe048cc71dcc42641f40ff5ceb1a1b3eaf23",
"branch_name": "refs/heads/master",
"committer_date": "2021-09-15T08:36:28",
"content_id": "0219794ab018b9d1bcd3a9ed4518a814e239e8a5",
"detected_licenses": [
"MIT"
],
"directory_id": "2396d2ac9a1b3681f40a0dea416a16894d257495",
"extension": "c",
"filename": "caesar.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 390687824,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2510,
"license": "MIT",
"license_type": "permissive",
"path": "/pset2/caesar.c",
"provenance": "stackv2-0123.json.gz:18089",
"repo_name": "akshat-raj09/CS50x2020",
"revision_date": "2021-09-15T08:36:28",
"revision_id": "c8803b786bc136f4c4f9bca44212d6cc7f561d62",
"snapshot_id": "79fb0ade650285b43f69598f9f301100c0642941",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/akshat-raj09/CS50x2020/c8803b786bc136f4c4f9bca44212d6cc7f561d62/pset2/caesar.c",
"visit_date": "2023-08-11T21:27:10.744922"
} | stackv2 | // necessary header files declared
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
// main function starts
int main(int argc, string argv[])
{
//variable declaration
int count = 0;
int key = 0, txt_len = 0;
string text;
// check if no additional command line arguments are passed
if (argc <= 1)
{
printf("Usage: ./caesar key\n");
return 1;
}
// check if more than two command line arguments are passed
else if (argc > 2)
{
printf("Usage: ./caesar key\n");
return 1;
}
// else if exactly 2 command line arguments are passed then proceed
else
{
int n = strlen(argv[1]), k[n], p = n;
for (int i = 0; i < n; i++)
{
if (isdigit(argv[1][i]))
{
count++;
}
}
if (count == n)
{
printf("");
}
else
{
printf("Usage: ./caesar key\n");
return 1;
}
// convert key(string) passed as command line argument to key(int)
for (int i = 0; i < n; i++)
{
k[i] = ((int) argv[1][i]) - 48;
key = key + k[i] * pow(10, p - 1);
p--;
}
key = key % 26;
// get message to be encrypted
text = get_string("plaintext: ");
txt_len = strlen(text);
char cipher[txt_len];
// apply caesar cipher based on the provided key
for (int i = 0; i < txt_len; i++)
{
if (isalpha(text[i]))
{
if (isupper(text[i]))
{
cipher[i] = (char)((int) text[i] + key);
if (!isupper(cipher[i]))
{
cipher[i] = (char)((int)cipher[i] - 26);
}
}
if (islower(text[i]))
{
cipher[i] = (char)((int) text[i] + key);
if (!islower(cipher[i]))
{
cipher[i] = (char)((int)cipher[i] - 26);
}
}
}
else
{
cipher[i] = text[i];
}
}
// print the encrypted text
printf("ciphertext: ");
for (int i = 0; i < txt_len; i++)
{
printf("%c", cipher[i]);
}
printf("\n");
return 0;
}
} | 3.265625 | 3 |
2024-11-18T22:22:14.182431+00:00 | 2022-01-15T19:31:07 | af2b61d1a829bae4445567db80d6dc1ac769a26d | {
"blob_id": "af2b61d1a829bae4445567db80d6dc1ac769a26d",
"branch_name": "refs/heads/master",
"committer_date": "2022-01-15T19:31:07",
"content_id": "2c82536c1d706aa7ea08bad1990ca90783427c12",
"detected_licenses": [
"MIT"
],
"directory_id": "31099bdde406cf896b553c4568cbcfc27fc13a08",
"extension": "c",
"filename": "dfu.c",
"fork_events_count": 2,
"gha_created_at": "2016-11-02T03:55:09",
"gha_event_created_at": "2018-06-07T00:13:23",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 72602401,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1044,
"license": "MIT",
"license_type": "permissive",
"path": "/fw/1.0/controller/dfu.c",
"provenance": "stackv2-0123.json.gz:18603",
"repo_name": "alvarop/ostur",
"revision_date": "2022-01-15T19:31:07",
"revision_id": "e4f9d8876ec7db123829a2745e8a088e56c05485",
"snapshot_id": "387cc9c0f13cc7d0a9ab60790de5f30dca19c89f",
"src_encoding": "UTF-8",
"star_events_count": 8,
"url": "https://raw.githubusercontent.com/alvarop/ostur/e4f9d8876ec7db123829a2745e8a088e56c05485/fw/1.0/controller/dfu.c",
"visit_date": "2022-02-12T07:39:12.858185"
} | stackv2 | #include "stm32f0xx.h"
#define BOTTOM_OF_RAM 0x20000000
#define DFU_ENABLE_CODE 0xB00710AD
#define DFU_STACK_POINTER 0x20002250
#define DFU_START_ADDR 0x1FFFC800
// Does not return, sets magic code and restarts device
void EnterDfu() {
uint32_t *dfu_enable_flag = (uint32_t *)(BOTTOM_OF_RAM);
// Disable interrupts
__disable_irq();
// Set magic code
*dfu_enable_flag = DFU_ENABLE_CODE;
NVIC_SystemReset();
}
static void (*DfuResetVector)(void);
// Call first thing in Reset_Handler so we can enter booloader if needed
void DfuCheck() {
uint32_t *dfu_enable_flag = (uint32_t *)(BOTTOM_OF_RAM);
// If magic code is set, DFU this thing!
if (*dfu_enable_flag == DFU_ENABLE_CODE) {
*dfu_enable_flag = 0;
// Set the stack pointer to the bootloader's
__set_MSP(*(uint32_t *)(DFU_START_ADDR));
// Reset handler is 4 bytes from the start of DFU memory
DfuResetVector = (void (*)(void))(*((uint32_t *)(DFU_START_ADDR + 4)));
// Enter the bootloader!
DfuResetVector();
while (1)
;
}
}
| 2.21875 | 2 |
2024-11-18T22:22:14.646510+00:00 | 2021-07-20T05:03:22 | 3b427f9a8622a3275309d2029557ac9978a3d0f5 | {
"blob_id": "3b427f9a8622a3275309d2029557ac9978a3d0f5",
"branch_name": "refs/heads/main",
"committer_date": "2021-07-20T05:03:22",
"content_id": "9e236a63b105351da17fe61c7353c9802b4715b4",
"detected_licenses": [
"MIT"
],
"directory_id": "eae6195a9f5242859bb4236eeb7225b42b9636e2",
"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": 387674960,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3444,
"license": "MIT",
"license_type": "permissive",
"path": "/main/src/main.c",
"provenance": "stackv2-0123.json.gz:18990",
"repo_name": "Retrocamara42/iot_multisensor",
"revision_date": "2021-07-20T05:03:22",
"revision_id": "afe48eb70fc295be0e46cf0f4d087dafa3edce75",
"snapshot_id": "df39d8191283b72d199279c383291a81a4d9b470",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Retrocamara42/iot_multisensor/afe48eb70fc295be0e46cf0f4d087dafa3edce75/main/src/main.c",
"visit_date": "2023-06-24T07:56:32.925998"
} | stackv2 | /*
* main.c
* @description: This program connects to wifi, then sends sensor data in
* a predefined interval
* @author: @Retrocamara42
*
*/
#include "main.h"
static const char *MAIN_TAG = "main";
static SemaphoreHandle_t sleep_semaphore;
static uint32_t sleep_semaphore_count=0;
// Sleep time in minutes
static uint16_t sleep_time=SLEEP_TIME;
static const dht_sensor_type_t sensor_type = DHT_TYPE_DHT11;
static const gpio_num_t dht_gpio = GPIO_NUM_0;
/*
* hw_timer_sleep
* Description: Sends task to sleep
*/
void hw_timer_sleep(void *arg){
esp_task_wdt_reset();
sleep_semaphore_count++;
if(sleep_semaphore_count>(60*sleep_time)){
sleep_semaphore_count=0;
xSemaphoreGive(sleep_semaphore);
}
}
/*
* my_custom_mqtt_on_event_data_cb
* Description: Mqtt function that executes when receiving data
*/
void my_custom_mqtt_on_event_data_cb(uint8_t topic_len, char* topic, uint8_t data_len, char* data){
for(uint8_t i=0; (i+2)<data_len; i++){
if(data[i]=='q' && data[i+2]==':'){
ESP_LOGI(MAIN_TAG, "Waking up device");
xSemaphoreGive(sleep_semaphore);
}
}
}
/*
* transmit_data_task
* Description: Reads data from sensors and send them to server
*/
static void transmit_data_task(){
// Init variables
//ESP_LOGI(MAIN_TAG, "Creating data pointer with size %d",sizeof(DhtSensor));
DhtSensor *dht_sensor;
if(iot_active_devices.dhtActive){
dht_sensor = (DhtSensor*)malloc(sizeof(DhtSensor));
dht_sensor->dht_pin = dht_gpio;
dht_sensor->dht_type = sensor_type;
dht_config(&dht_sensor);
}
sleep_semaphore = xSemaphoreCreateBinary();
// Transmission
while (1){
esp_task_wdt_reset();
ESP_LOGI(MAIN_TAG, "Reading data from sensors");
/******** DHT ***********/
if(iot_active_devices.dhtActive){
dht_read_and_process_data(&dht_sensor);
send_dht_data_with_mqtt(dht_sensor,
iot_active_devices.device_name,
client, mqtt_cfg, TEMPERATURE_TOPIC,HUMIDITY_TOPIC);
}
/********** SLEEP ************/
ESP_LOGI(MAIN_TAG, "Going to sleep");
esp_task_wdt_reset();
esp_wifi_set_ps(WIFI_PS_MAX_MODEM);
hw_timer_init(hw_timer_sleep, NULL);
hw_timer_alarm_us(1000000, true);
xSemaphoreTake(sleep_semaphore, portMAX_DELAY);
hw_timer_deinit();
esp_wifi_set_ps(WIFI_PS_MIN_MODEM);
}
}
/*
* app_main
* Description: Starts wifi connection and creates transmit_data_task
*/
void app_main(){
// Start watchdog
esp_task_wdt_init();
/********************* DEFAULT CONFIG ******************************/
ESP_ERROR_CHECK(nvs_flash_init());
ESP_ERROR_CHECK(esp_netif_init());
ESP_ERROR_CHECK(esp_event_loop_create_default());
esp_wifi_set_ps(WIFI_PS_MIN_MODEM);
/********************* WIFI CONNECT ********************************/
create_wifi_semaphore();
wifi_init_sta(custom_wifi_config);
// Waits indefenitely for wifi to connect
take_from_wifi_semaphore(portMAX_DELAY);
delete_wifi_semaphore();
/********************* MQTT SETUP **********************************/
client = mqtt_app_start(&mqtt_cfg);
// Subscribe to topics
set_mqtt_on_event_data_cb(&my_custom_mqtt_on_event_data_cb);
mqtt_subscribe(client, SUBSCRIBE_TOPIC, 1);
// Create task to transmit data
xTaskCreate(transmit_data_task, "transmit_data_task", 2048*2, NULL, 15, NULL);
}
| 2.53125 | 3 |
2024-11-18T22:22:14.703906+00:00 | 2018-05-04T22:36:48 | 4fdbd6deebd805cca0b33513284441d31f5c3308 | {
"blob_id": "4fdbd6deebd805cca0b33513284441d31f5c3308",
"branch_name": "refs/heads/master",
"committer_date": "2018-05-04T22:36:48",
"content_id": "1c710a9019c84a9981eb836ea1b9fd6d0e41322a",
"detected_licenses": [
"MIT"
],
"directory_id": "a3c094c3baa3d9352f8fca458af2d525984dc308",
"extension": "c",
"filename": "pareq.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 86920702,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2250,
"license": "MIT",
"license_type": "permissive",
"path": "/Playground/AudioKit-3.5/AudioKit/Common/Internals/Sporth/ugens/pareq.c",
"provenance": "stackv2-0123.json.gz:19119",
"repo_name": "dkun7944/facesynth-ios",
"revision_date": "2018-05-04T22:36:48",
"revision_id": "9391df3e2284646ca7f0d2910da6f6ed27503b5f",
"snapshot_id": "a888b2b4d013da8d03fcb6f6cd46f1b699c38345",
"src_encoding": "UTF-8",
"star_events_count": 4,
"url": "https://raw.githubusercontent.com/dkun7944/facesynth-ios/9391df3e2284646ca7f0d2910da6f6ed27503b5f/Playground/AudioKit-3.5/AudioKit/Common/Internals/Sporth/ugens/pareq.c",
"visit_date": "2021-09-13T22:13:02.457321"
} | stackv2 | #include "plumber.h"
int sporth_pareq(sporth_stack *stack, void *ud)
{
plumber_data *pd = ud;
SPFLOAT input;
SPFLOAT out;
SPFLOAT fc;
SPFLOAT v;
SPFLOAT q;
SPFLOAT mode;
sp_pareq *pareq;
switch(pd->mode) {
case PLUMBER_CREATE:
#ifdef DEBUG_MODE
fprintf(stderr, "pareq: Creating\n");
#endif
sp_pareq_create(&pareq);
plumber_add_ugen(pd, SPORTH_PAREQ, pareq);
if(sporth_check_args(stack, "fffff") != SPORTH_OK) {
fprintf(stderr,"Not enough arguments for pareq\n");
stack->error++;
return PLUMBER_NOTOK;
}
mode = sporth_stack_pop_float(stack);
q = sporth_stack_pop_float(stack);
v = sporth_stack_pop_float(stack);
fc = sporth_stack_pop_float(stack);
input = sporth_stack_pop_float(stack);
sporth_stack_push_float(stack, 0);
break;
case PLUMBER_INIT:
#ifdef DEBUG_MODE
fprintf(stderr, "pareq: Initialising\n");
#endif
mode = sporth_stack_pop_float(stack);
q = sporth_stack_pop_float(stack);
v = sporth_stack_pop_float(stack);
fc = sporth_stack_pop_float(stack);
input = sporth_stack_pop_float(stack);
pareq = pd->last->ud;
sp_pareq_init(pd->sp, pareq);
sporth_stack_push_float(stack, 0);
break;
case PLUMBER_COMPUTE:
mode = sporth_stack_pop_float(stack);
q = sporth_stack_pop_float(stack);
v = sporth_stack_pop_float(stack);
fc = sporth_stack_pop_float(stack);
input = sporth_stack_pop_float(stack);
pareq = pd->last->ud;
pareq->fc = fc;
pareq->v = v;
pareq->q = q;
pareq->mode = mode;
sp_pareq_compute(pd->sp, pareq, &input, &out);
sporth_stack_push_float(stack, out);
break;
case PLUMBER_DESTROY:
pareq = pd->last->ud;
sp_pareq_destroy(&pareq);
break;
default:
fprintf(stderr, "pareq: Unknown mode!\n");
break;
}
return PLUMBER_OK;
}
| 2.234375 | 2 |
2024-11-18T22:22:14.905697+00:00 | 2021-11-04T02:51:10 | 2319ecb6d0bc2731d4d5ddaf57128cc3ad252201 | {
"blob_id": "2319ecb6d0bc2731d4d5ddaf57128cc3ad252201",
"branch_name": "refs/heads/master",
"committer_date": "2021-11-04T02:51:10",
"content_id": "6c2dd184333a5a9296c550687340285f68857c27",
"detected_licenses": [
"MIT"
],
"directory_id": "0a3e6743d5b527dd2ca0b84d8bc4b3acb345b558",
"extension": "h",
"filename": "qlock.h",
"fork_events_count": 0,
"gha_created_at": "2021-06-11T07:20:31",
"gha_event_created_at": "2021-11-04T02:51:10",
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 375939086,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2553,
"license": "MIT",
"license_type": "permissive",
"path": "/src/fs/xfs/xfsdump-dev/common/qlock.h",
"provenance": "stackv2-0123.json.gz:19507",
"repo_name": "fengjixuchui/hydra",
"revision_date": "2021-11-04T02:51:10",
"revision_id": "d49e652018a007bae9d22cb59dfa086deff7ad2f",
"snapshot_id": "76ed698c2f85bd3d105e585662009b6b96336687",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/fengjixuchui/hydra/d49e652018a007bae9d22cb59dfa086deff7ad2f/src/fs/xfs/xfsdump-dev/common/qlock.h",
"visit_date": "2023-09-05T12:44:15.852192"
} | stackv2 | /*
* Copyright (c) 2000-2001 Silicon Graphics, Inc.
* All Rights Reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it would 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 the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef QLOCK_H
#define QLOCK_H
/* qlock - quick locks abstraction
*
* threads may allocate quick locks using qlock_alloc, and free them with
* qlock_free.
*
* deadlock detection is accomplished by giving an ordinal number to each
* lock allocated, and record all locks held by each thread. locks may not
* be acquired out of order. that is, subsequently acquired locks must have
* a lower ordinal than all locks currently held. for convenience, the ordinals
* of all locks to be allocated will be defined in this file.
*/
#define QLOCK_ORD_CRIT 0
/* ordinal for global critical region lock
*/
#define QLOCK_ORD_WIN 1
/* ordinal for win abstraction critical regions
*/
#define QLOCK_ORD_PI 2
/* ordinal for persistent inventory abstraction critical regions
*/
#define QLOCK_ORD_MLOG 3
/* ordinal for mlog lock
*/
typedef void *qlockh_t;
#define QLOCKH_NULL 0
/* opaque handle
*/
extern qlockh_t qlock_alloc( ix_t ord );
/* allocates a qlock with the specified ordinal. returns
* NULL if lock can't be allocated.
*/
extern void qlock_lock( qlockh_t qlockh );
/* acquires the specified lock.
*/
extern void qlock_unlock( qlockh_t qlockh );
/* releases the specified lock.
*/
typedef void *qsemh_t;
#define QSEMH_NULL 0
/* opaque handle
*/
extern qsemh_t qsem_alloc( size_t cnt );
/* allocates a counting semaphore initialized to the specified
* count. returns a qsem handle
*/
extern void qsem_free( qsemh_t qsemh );
/* frees the counting semaphore
*/
extern void qsemP( qsemh_t qsemh );
/* "P" (decrement) op
*/
extern void qsemV( qsemh_t qsemh );
/* "V" (increment) op
*/
extern bool_t qsemPwouldblock( qsemh_t qsemh );
/* returns true if a qsemP op would block
*/
extern size_t qsemPavail( qsemh_t qsemh );
/* number of resources available
*/
#endif /* QLOCK_H */
| 2.0625 | 2 |
2024-11-18T22:22:14.980692+00:00 | 2021-01-03T14:58:25 | be0c15f49c417233d29237236e08968694791146 | {
"blob_id": "be0c15f49c417233d29237236e08968694791146",
"branch_name": "refs/heads/master",
"committer_date": "2021-01-03T14:58:25",
"content_id": "6f07f714c4a9f700f6bae3af7670ed9079d559de",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "c6170909c65e5614f64de796f9d5d55be4ff52df",
"extension": "c",
"filename": "atomkernel.c",
"fork_events_count": 0,
"gha_created_at": "2020-08-13T12:03:30",
"gha_event_created_at": "2020-08-13T12:03:31",
"gha_language": null,
"gha_license_id": null,
"github_id": 287268260,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4885,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/ports/win32/atomthreads/atomkernel.c",
"provenance": "stackv2-0123.json.gz:19636",
"repo_name": "yifengling0/atomthreads",
"revision_date": "2021-01-03T14:58:25",
"revision_id": "1408cd4a341553cf3f95ea72cc21975cccfe58f5",
"snapshot_id": "0271bd2e14a02ce6445bb2e02ed42fe0fd2ee2ec",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/yifengling0/atomthreads/1408cd4a341553cf3f95ea72cc21975cccfe58f5/ports/win32/atomthreads/atomkernel.c",
"visit_date": "2023-02-17T23:35:48.314894"
} | stackv2 | #include "atom.h"
#include "windows.h"
#include "win32port.h"
#include "_threadmanager.h"
static int _enable_int_cpu = 1;
static CRITICAL_SECTION _critical_section;
int get_cc(void)
{
if (_enable_int_cpu == 1) {
EnterCriticalSection(&_critical_section);
_enable_int_cpu = 0;
return 0;
}else {
return 1;
}
}
void set_cc(int ccr)
{
if (ccr == 0) {
LeaveCriticalSection(&_critical_section);
_enable_int_cpu = 1;
}
}
/** Set to TRUE when OS is started and running threads */
uint8_t atomOSStarted = FALSE;
/* Number of nested interrupts */
static int atomIntCnt = 0;
extern uint8_t atomOSInit(void* idle_thread_stack_bottom, uint32_t idle_thread_stack_size, uint8_t idle_thread_stack_check)
{
InitializeCriticalSection(&_critical_section);
return 0;
}
void atomOSStart(void)
{
atomOSStarted = TRUE;
}
/**
* \b atomIntEnter
*
* Interrupt handler entry routine.
*
* Must be called at the start of any interrupt handlers that may
* call an OS primitive and make a thread ready.
*
* @return None
*/
void atomIntEnter(void)
{
/* Increment the interrupt count */
atomIntCnt++;
}
/**
* \b atomSched
*
* This is an internal function not for use by application code.
*
* This is the main scheduler routine. It is called by the various OS
* library routines to check if any threads should be scheduled in now.
* If so, the context will be switched from the current thread to the
* new one.
*
* The scheduler is priority-based with round-robin performed on threads
* with the same priority. Round-robin is only performed on timer ticks
* however. During reschedules caused by an OS operation (e.g. after
* giving or taking a semaphore) we only allow the scheduling in of
* threads with higher priority than current priority. On timer ticks we
* also allow the scheduling of same-priority threads - in that case we
* schedule in the head of the ready list for that priority and put the
* current thread at the tail.
*
* @param[in] timer_tick Should be TRUE when called from the system tick
*
* @return None
*/
void atomSched(uint8_t timer_tick)
{
//do nothing.
}
/**
* \b atomIntExit
*
* Interrupt handler exit routine.
*
* Must be called at the end of any interrupt handlers that may
* call an OS primitive and make a thread ready.
*
* This is responsible for calling the scheduler at the end of
* interrupt handlers to determine whether a new thread has now
* been made ready and should be scheduled in.
*
* @param timer_tick TRUE if this is a timer tick
*
* @return None
*/
void atomIntExit(uint8_t timer_tick)
{
/* Decrement the interrupt count */
atomIntCnt--;
/* Call the scheduler */
atomSched(timer_tick);
}
//
//extern uint8_t tcbEnqueuePriority(ATOM_TCB** tcb_queue_ptr, ATOM_TCB* tcb_ptr);
//extern ATOM_TCB* tcbDequeueHead(ATOM_TCB** tcb_queue_ptr);
//extern ATOM_TCB* tcbDequeueEntry(ATOM_TCB** tcb_queue_ptr, ATOM_TCB* tcb_ptr);
//extern ATOM_TCB* tcbDequeuePriority(ATOM_TCB** tcb_queue_ptr, uint8_t priority);
//
// TODO: 切换任务的时候调用线程函数获取当前线程的tcb
/** This is a pointer to the TCB for the currently-running thread */
static ATOM_TCB* curr_tcb = NULL;
ATOM_TCB* atomCurrentContext(void)
{
/* Return the current thread's TCB or NULL if in interrupt context */
if (atomIntCnt == 0) {
curr_tcb = tcbManagerFind(GetCurrentThreadId());
return (curr_tcb);
}
else {
return (NULL);
}
}
//
uint8_t atomThreadCreate(ATOM_TCB* tcb_ptr, uint8_t priority, void (*entry_point)(uint32_t), uint32_t entry_param, void* stack_bottom, uint32_t stack_size, uint8_t stack_check)
{
HANDLE handle;
int threadId;
uint8_t ret = ATOM_OK;
if ((tcb_ptr == NULL) || (entry_point == NULL) || (stack_bottom == NULL)
|| (stack_size == 0))
{
/* Bad parameters */
ret = ATOM_ERR_PARAM;
}
else {
handle = CreateThread(NULL, stack_size, (LPTHREAD_START_ROUTINE)entry_point, 0, 0, &threadId);
if (handle) {
tcb_ptr->priority = priority;
tcb_ptr->entry_point = entry_point;
tcb_ptr->entry_param = entry_param;
}
else {
ret = ATOM_ERR_PARAM;
}
}
return ret;
}
#ifdef ATOM_STACK_CHECKING
uint8_t atomThreadStackCheck(ATOM_TCB* tcb_ptr, uint32_t* used_bytes, uint32_t* free_bytes);
{
//TODO : Windows 上检查堆栈的方法实现。
return 0;
}
#endif
void archContextSwitch(ATOM_TCB* old_tcb_ptr, ATOM_TCB* new_tcb_ptr)
{
}
void archFirstThreadRestore(ATOM_TCB* new_tcb_ptr)
{
}
/**
* Initialise a threads stack so it can be scheduled in by
* archFirstThreadRestore or the pend_sv_handler.
*/
void archThreadContextInit(ATOM_TCB* tcb_ptr, void* stack_top,
void (*entry_point)(uint32_t), uint32_t entry_param)
{
//TODO: 初始化一些堆栈信息等
}
| 2.390625 | 2 |
2024-11-18T22:22:15.158653+00:00 | 2018-06-16T17:22:19 | 72c01430eab8703061e869f628a4aaf3df21d0f2 | {
"blob_id": "72c01430eab8703061e869f628a4aaf3df21d0f2",
"branch_name": "refs/heads/master",
"committer_date": "2018-06-16T17:22:19",
"content_id": "f0a7388be3221c4b0d188d8943c93fd9565f37f6",
"detected_licenses": [
"MIT"
],
"directory_id": "0d423538336b5067781fb76c0fb6ac1daa3d0ccb",
"extension": "h",
"filename": "Circular.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": 489,
"license": "MIT",
"license_type": "permissive",
"path": "/4_CTDL_GT/LyThuyet/Josephus/Circular.h",
"provenance": "stackv2-0123.json.gz:19895",
"repo_name": "NhatPhuong02/HCMUS-Lectures",
"revision_date": "2018-06-16T17:22:19",
"revision_id": "b376e144e2601a73684e2ff437ab5c94a943909c",
"snapshot_id": "73f098c6322133116dc9f57423f1433bf32a5730",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/NhatPhuong02/HCMUS-Lectures/b376e144e2601a73684e2ff437ab5c94a943909c/4_CTDL_GT/LyThuyet/Josephus/Circular.h",
"visit_date": "2022-01-13T01:52:40.707561"
} | stackv2 | #ifndef CIRCULAR_H
#define CIRCULAR_H
// Circular linked list
// tail->next=head
typedef struct CNode *pCNode;
struct CNode {
int key;
pCNode pNext;
};
struct CList {
pCNode pHead;
pCNode pTail;
};
void initCList(CList &l);
bool isEmpty(CList l);
pCNode getCNode(int k);
void addHead(CList &l, int k);
void delHead(CList &l);
void addTail(CList &l, int k);
void delTail(CList &l);
void removeAfter(CList &l, pCNode p);
void delList(CList &l);
void printList(CList l);
#endif | 2.234375 | 2 |
2024-11-18T22:22:15.820883+00:00 | 2019-09-10T13:24:19 | a9de06411986f06d5e622110abe320345deed8b1 | {
"blob_id": "a9de06411986f06d5e622110abe320345deed8b1",
"branch_name": "refs/heads/master",
"committer_date": "2019-09-10T13:24:19",
"content_id": "c75a6f31b757751a0e3198e8237bcdfd3d70997f",
"detected_licenses": [
"MIT"
],
"directory_id": "2cdaa3b65083aeedf87c199864fdccfcdd96256e",
"extension": "c",
"filename": "vRTCC.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 205174785,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2184,
"license": "MIT",
"license_type": "permissive",
"path": "/USBMSCtest.X/vRTCC.c",
"provenance": "stackv2-0123.json.gz:20285",
"repo_name": "PlanetxGear/PIC24_USBMSCtest",
"revision_date": "2019-09-10T13:24:19",
"revision_id": "bcfdc1869457a74f77570be4dbd0aa951ccb6860",
"snapshot_id": "ada1fabb488795188eb0c627c3cf086d0408b1ab",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/PlanetxGear/PIC24_USBMSCtest/bcfdc1869457a74f77570be4dbd0aa951ccb6860/USBMSCtest.X/vRTCC.c",
"visit_date": "2020-07-13T23:05:50.229217"
} | stackv2 | /*******************************************************************************
* RTCC module
* author :hiroshi murakami
* created :20161225
* modified:-
******************************************************************************/
#define _vRTCC_C
#include "mcc_generated_files/mcc.h"
#include <string.h>
#include "xprintf.h"
#include "vRTCC.h"
/*****************************
* VARIABLES
*****************************/
//******************************************************************************
// initialize RTCC property
//
// Description : -
// Input : -
// Output :
//******************************************************************************
void vRTCC_init(void)
{
//check the currentTime
RTCC_TimeGet(¤tTime);
if(currentTime.tm_hour > 23 || currentTime.tm_min > 59 || currentTime.tm_mon > 12 || currentTime.tm_mday > 31 || currentTime.tm_year > 99)
{
// set RTCC time 2019-08-11 SUN 12-00-00
RTCC_Initialize();
// RTCDATE = 0x19081100;
// RTCTIME = 0x12000000;
// RTCCONbits.CAL = 0x3FF;
} else {
RTCC_TimeReset(1);
}
}
//******************************************************************************
// RTCC time setting
//
// Description : -
// Input : -
// Output :
//******************************************************************************
void vRTCC_timeSet(
struct tm setupTime
)
{
short cal;
int cTime, sTime;
RTCC_TimeGet(¤tTime);
cTime = ((currentTime.tm_hour * 0x100) + currentTime.tm_min) * 0x100 + currentTime.tm_sec;
sTime = ((setupTime.tm_hour * 0x100) + setupTime.tm_min) * 0x100 + setupTime.tm_sec;
cal = RTCCONbits.CAL << 6;
if(cTime < sTime){
cal = cal + (1 << 6);
} else if(cTime > sTime){
cal = cal - (1 << 6);
}
RTCCONbits.CAL = cal >> 6;
currentTime.tm_hour = setupTime.tm_hour;
currentTime.tm_min = setupTime.tm_min;
currentTime.tm_sec = setupTime.tm_sec;
RTCC_TimeSet(¤tTime);
}
void vRTCC_dateSet(
struct tm setupTime
)
{
RTCC_TimeGet(¤tTime);
currentTime.tm_year = setupTime.tm_year;
currentTime.tm_mon = setupTime.tm_mon;
currentTime.tm_mday = setupTime.tm_mday;
RTCC_TimeSet(¤tTime); //setting date & time to RTCC
}
| 2.09375 | 2 |
2024-11-18T22:22:16.412288+00:00 | 2021-03-24T16:43:30 | 66adeeb43e9de2f5494465a55912243a034da1f3 | {
"blob_id": "66adeeb43e9de2f5494465a55912243a034da1f3",
"branch_name": "refs/heads/master",
"committer_date": "2021-03-24T16:43:30",
"content_id": "4c2aa12ce5917d8342f97967cdc50a2111e7d1e5",
"detected_licenses": [
"MIT"
],
"directory_id": "c304eba343baa45f373fece59eeeb963a295aa61",
"extension": "c",
"filename": "buton.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": 7005,
"license": "MIT",
"license_type": "permissive",
"path": "/tk/buton.c",
"provenance": "stackv2-0123.json.gz:20800",
"repo_name": "kryptine/inferno-2e",
"revision_date": "2021-03-24T16:43:30",
"revision_id": "d87916059d6cb864693ffb575c34c76cb729c25e",
"snapshot_id": "f8873d40ef15279acdaf60a186084bad6fde917f",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/kryptine/inferno-2e/d87916059d6cb864693ffb575c34c76cb729c25e/tk/buton.c",
"visit_date": "2023-03-27T10:01:06.386716"
} | stackv2 | #include "lib9.h"
#include "image.h"
#include "tk.h"
#define O(t, e) ((long)(&((t*)0)->e))
static char* tksetlabvar(TkTop*, TkLabel*, char*);
/* Widget Commands (+ means implemented)
+cget
+configure
+invoke
+select
+deselect
+toggle
*/
static
TkEbind bb[] =
{
{TkEnter, "%W configure -state active"},
{TkLeave, "%W configure -state normal -relief raised"},
{TkButton1P, "%W configure -relief sunken"},
{TkButton1R, "%W configure -relief raised; %W invoke"},
};
static
TkEbind cb[] =
{
{TkEnter, "%W configure -state active"},
{TkLeave, "%W configure -state normal"},
{TkButton1P, "%W invoke"},
{TkMotion|TkButton1P, "" },
};
TkOption tkbutopts[] =
{
"text", OPTtext, O(TkLabel, text), nil,
"label", OPTtext, O(TkLabel, text), nil,
"underline", OPTdist, O(TkLabel, ul), nil,
"anchor", OPTflag, O(TkLabel, anchor), tkanchor,
"command", OPTtext, O(TkLabel, command), nil,
"bitmap", OPTbmap, O(TkLabel, bitmap), nil,
"image", OPTimag, O(TkLabel, img), nil,
nil
};
TkOption tkradopts[] =
{
"variable", OPTtext, O(TkLabel, variable), nil,
"value", OPTtext, O(TkLabel, value), nil,
nil,
};
static char
tkselbut[] = "selectedButton";
char*
tkbutton(TkTop *t, char *arg, char **ret)
{
Tk *tk;
char *e;
TkLabel *tkl;
TkName *names;
TkOptab tko[3];
tk = tknewobj(t, TKbutton, sizeof(Tk)+sizeof(TkLabel));
if(tk == nil)
return TkNomem;
tk->relief = TKraised;
tkl = TKobj(TkLabel, tk);
tkl->ul = -1;
tko[0].ptr = tk;
tko[0].optab = tkgeneric;
tko[1].ptr = tkl;
tko[1].optab = tkbutopts;
tko[2].ptr = nil;
names = nil;
e = tkparse(t, arg, tko, &names);
if(e != nil) {
tkfreeobj(tk);
return e;
}
e = tkbindings(t, tk, bb, nelem(bb));
if(e != nil) {
tkfreeobj(tk);
return e;
}
if(tk->borderwidth == 0)
tk->borderwidth = 2;
tksizelabel(tk);
e = tkaddchild(t, tk, &names);
tkfreename(names);
if(e != nil) {
tkfreeobj(tk);
return e;
}
tk->name->link = nil;
return tkvalue(ret, "%s", tk->name->name);
}
char*
tkbuttoncget(Tk *tk, char *arg, char **val)
{
TkOptab tko[4];
TkLabel *tkl = TKobj(TkLabel, tk);
tko[0].ptr = tk;
tko[0].optab = tkgeneric;
tko[1].ptr = tkl;
tko[1].optab = tkbutopts;
tko[2].ptr = nil;
if(tk->type == TKradiobutton || tk->type == TKcheckbutton) {
tko[2].ptr = tkl;
tko[2].optab = tkradopts;
tko[3].ptr = nil;
}
return tkgencget(tko, arg, val);
}
char*
tkbuttonconf(Tk *tk, char *arg, char **val)
{
char *e;
TkGeom g;
TkOptab tko[4];
TkLabel *tkl = TKobj(TkLabel, tk);
tko[0].ptr = tk;
tko[0].optab = tkgeneric;
tko[1].ptr = tkl;
tko[1].optab = tkbutopts;
tko[2].ptr = nil;
if(tk->type == TKradiobutton || tk->type == TKcheckbutton) {
tko[2].ptr = tkl;
tko[2].optab = tkradopts;
tko[3].ptr = nil;
}
if(*arg == '\0')
return tkconflist(tko, val);
g = tk->req;
e = tkparse(tk->env->top, arg, tko, nil);
tksizelabel(tk);
tkgeomchg(tk, &g);
tk->flag |= Tkdirty;
return e;
}
char*
tkbuttonselect(Tk *tk, char *arg, char **val)
{
char *e;
TkLabel *tkl = TKobj(TkLabel, tk);
USED(arg);
USED(val);
tkl->check = 1;
e = tksetlabvar(tk->env->top, tkl, "1");
if(e != nil)
return e;
tk->flag |= Tkdirty;
return nil;
}
char*
tkbuttondeselect(Tk *tk, char *arg, char **val)
{
char *e;
TkLabel *tkl = TKobj(TkLabel, tk);
USED(arg);
USED(val);
tkl->check = 0;
e = tksetlabvar(tk->env->top, tkl, tk->type == TKradiobutton ? nil : "0");
if(e != nil)
return e;
tk->flag |= Tkdirty;
return nil;
}
char*
tkcheckbutton(TkTop *t, char *arg, char **ret)
{
Tk *tk;
char *e;
TkLabel *tkl;
TkName *names;
TkOptab tko[4];
tk = tknewobj(t, TKcheckbutton, sizeof(Tk)+sizeof(TkLabel));
if(tk == nil)
return TkNomem;
tkl = TKobj(TkLabel, tk);
tkl->ul = -1;
tko[0].ptr = tk;
tko[0].optab = tkgeneric;
tko[1].ptr = tkl;
tko[1].optab = tkbutopts;
tko[2].ptr = tkl;
tko[2].optab = tkradopts;
tko[3].ptr = nil;
names = nil;
e = tkparse(t, arg, tko, &names);
if(e != nil)
goto err;
e = tkbindings(t, tk, cb, nelem(cb));
if(e != nil)
goto err;
tksizelabel(tk);
e = tkaddchild(t, tk, &names);
tkfreename(names);
if(e != nil)
goto err;
tk->name->link = nil;
e = tksetlabvar(tk->env->top, tkl, "0");
if(e != nil)
goto err;
return tkvalue(ret, "%s", tk->name->name);
err:
tkfreeobj(tk);
return e;
}
char*
tkradiobutton(TkTop *t, char *arg, char **ret)
{
Tk *tk;
char *e;
TkLabel *tkl;
TkName *names;
TkOptab tko[4];
tk = tknewobj(t, TKradiobutton, sizeof(Tk)+sizeof(TkLabel));
if(tk == nil)
return TkNomem;
tkl = TKobj(TkLabel, tk);
tkl->ul = -1;
tko[0].ptr = tk;
tko[0].optab = tkgeneric;
tko[1].ptr = tkl;
tko[1].optab = tkbutopts;
tko[2].ptr = tkl;
tko[2].optab = tkradopts;
tko[3].ptr = nil;
names = nil;
e = tkparse(t, arg, tko, &names);
if(e != nil)
goto err;
e = tkbindings(t, tk, cb, nelem(cb));
if(e != nil)
goto err;
tksizelabel(tk);
e = tkaddchild(t, tk, &names);
tkfreename(names);
if(e != nil)
goto err;
tk->name->link = nil;
return tkvalue(ret, "%s", tk->name->name);
err:
tkfreeobj(tk);
return e;
}
static void
tkradiovar(char *var, Tk *f)
{
char *s;
TkLabel *tkl;
tkl = TKobj(TkLabel, f);
s = tkl->variable;
if(s == nil)
s = tkselbut;
if(strcmp(s, var) == 0) {
tkl->check = 0;
f->flag |= Tkdirty;
}
}
static char*
tksetlabvar(TkTop *top, TkLabel *tkl, char *newval)
{
char *c;
TkVar *v;
c = tkl->variable;
if(c == nil)
c = tkselbut;
v = tkmkvar(top, c, TkVstring);
if(v == nil)
return TkNomem;
if(v->type != TkVstring)
return TkNotvt;
if(v->value != nil)
free(v->value);
if(newval == nil)
newval = "";
v->value = strdup(newval);
if(v->value == nil)
return TkNomem;
return nil;
}
char*
tkbuttontoggle(Tk *tk, char *arg, char **val)
{
char *e = nil;
TkLabel *tkl = TKobj(TkLabel, tk);
USED(arg);
USED(val);
if(tk->flag & Tkdisabled)
return nil;
if(tk->type == TKcheckbutton) {
tkl->check = !tkl->check;
tk->flag |= Tkdirty;
e = tksetlabvar(tk->env->top, tkl, tkl->check? "1" : "0");
}
return e;
}
char*
tkbuttoninvoke(Tk *tk, char *arg, char **val)
{
char *e;
TkLabel *tkl = TKobj(TkLabel, tk);
if(tk->flag & Tkdisabled)
return nil;
e = tkbuttontoggle(tk, arg, val);
if(e != nil)
return e;
if(tkl->command != nil)
return tkexec(tk->env->top, tkl->command, val);
return nil;
}
char*
tkradioinvoke(Tk *tk, char *arg, char **val)
{
char *c, *e;
Tk *f, *m;
TkTop *top;
TkLabel *tkl = TKobj(TkLabel, tk);
USED(arg);
if(tk->flag & Tkdisabled)
return nil;
top = tk->env->top;
tkl->check = 1;
tk->flag |= Tkdirty;
e = tksetlabvar(top, tkl, tkl->value);
if(e != nil)
return e;
c = tkl->variable;
if(c == nil)
c = tkselbut;
for(f = top->root; f; f = f->siblings) {
if(f->type == TKmenu) {
for(m = f->slave; m; m = m->next)
if(m->type == TKradiobutton && m != tk)
tkradiovar(c, m);
}
else
if(f->type == TKradiobutton && f != tk)
tkradiovar(c, f);
}
if(tkl->command != nil)
return tkexec(tk->env->top, tkl->command, val);
return nil;
}
| 2.015625 | 2 |
2024-11-18T22:22:16.527390+00:00 | 2021-09-13T05:52:17 | c781e5bdc911e1446e337b0fcc49bc32153a872e | {
"blob_id": "c781e5bdc911e1446e337b0fcc49bc32153a872e",
"branch_name": "refs/heads/main",
"committer_date": "2021-09-13T05:52:17",
"content_id": "0bd6f25324aef76cf8a1f66b767d8f466135392d",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "fe459acc22143896d0875dac309c1fe3f0704a71",
"extension": "c",
"filename": "net_salary.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 405451105,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 744,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/net_salary.c",
"provenance": "stackv2-0123.json.gz:20928",
"repo_name": "rawCode4U/C_Basic_program_part_2",
"revision_date": "2021-09-13T05:52:17",
"revision_id": "9d9582149f619ad3f94dc7f4d161270024a4a38f",
"snapshot_id": "4753fc00ff2b684eaa2909cb8db6b0f6948796dd",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/rawCode4U/C_Basic_program_part_2/9d9582149f619ad3f94dc7f4d161270024a4a38f/net_salary.c",
"visit_date": "2023-08-25T14:30:32.713763"
} | stackv2 | //6. Write a program to calculate Net Salary of an employee.
// HRA is 20% of BS, DA is 40% of BS, PF is 10% of GS
#include <stdio.h>
float netSalary(float basic_salary){
float da, hra, pf, net_salary ; // Dearness Allowance (DA) & House Rent Allowance (HRA)
da = (basic_salary * 40) / 100 ; // DA is 40%
hra = (basic_salary * 20) / 100 ; // HRA is 20 %
pf = (basic_salary * 10) / 100 ; // PF is 10 %
net_salary = ((basic_salary + da + hra) - pf) ;
return net_salary;
}
int main()
{
float basic_salary ;
printf("Please Enter the Ramesh’s basic salary : Rs. ");
scanf("%f", &basic_salary);
printf("Net Salary of Ramesh is Rs. %.2f", netSalary(basic_salary));
return 0;
} | 4.03125 | 4 |
2024-11-18T22:22:16.795717+00:00 | 2018-06-15T07:25:26 | 3f9f3e42804d8663d072e0b815aac9c5d86ffee8 | {
"blob_id": "3f9f3e42804d8663d072e0b815aac9c5d86ffee8",
"branch_name": "refs/heads/master",
"committer_date": "2018-06-15T07:25:26",
"content_id": "1eab58be2768841f8c246c11e7d76dc807eec9b3",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "393040adb3b82328bf85c48dddf2c3756337e4a6",
"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": 137365782,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 719,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/main.c",
"provenance": "stackv2-0123.json.gz:21057",
"repo_name": "annie980210/Sort",
"revision_date": "2018-06-15T07:25:26",
"revision_id": "57de18adaa3a4747b73d6e962b8722980b928e81",
"snapshot_id": "012c1e3279a279cd520b39f54a084c058187f5fc",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/annie980210/Sort/57de18adaa3a4747b73d6e962b8722980b928e81/main.c",
"visit_date": "2020-03-20T10:18:53.558950"
} | stackv2 | #include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "SA.h"
void main()
{
DT arr[LENGTH];
clock_t start, end;
srand((unsigned int)time(NULL));
/* Initialize elements of the array
for (int i = 0; i < LENGTH; i++)
arr[i] = (DT)rand();
for (int i = 0; i < LENGTH; i++)
{
arr[i].x = (float)rand();
arr[i].y = (float)rand();
arr[i].height = (float)rand();
arr[i].weight = (float)rand();
}
*/
start = clock();
/* Sorting algorithm
insertionSort(arr, LENGTH);
quickSort(arr, 0, LENGTH - 1);
iterativeMergeSort(arr, LENGTH);
heapSort(arr, LENGTH);
*/
end = clock();
printf("\nThe elasped time is %ld ms in %s, %s array[%d].\n", end - start, SA, DTS, LENGTH);
system("pause");
}
| 2.875 | 3 |
2024-11-18T22:22:18.025327+00:00 | 2023-09-02T03:38:19 | 61016a580ea4245a138df00b75fa6ab9395aa2f2 | {
"blob_id": "61016a580ea4245a138df00b75fa6ab9395aa2f2",
"branch_name": "refs/heads/master",
"committer_date": "2023-09-02T03:38:19",
"content_id": "4be6a28d65988564e207b4acfe3758164ab6c899",
"detected_licenses": [
"MIT"
],
"directory_id": "736e760612f2b431c4b2524fe1a4a8e4083c72a1",
"extension": "c",
"filename": "hls-master.c",
"fork_events_count": 1015,
"gha_created_at": "2014-01-03T01:43:35",
"gha_event_created_at": "2023-08-30T03:45:24",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 15598496,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1979,
"license": "MIT",
"license_type": "permissive",
"path": "/libhls/source/hls-master.c",
"provenance": "stackv2-0123.json.gz:21445",
"repo_name": "ireader/media-server",
"revision_date": "2023-09-02T03:38:19",
"revision_id": "3d8647f50fe832856f42b03d1e5b0fe2eafe5796",
"snapshot_id": "7f86da8ff0c8694876a2043d50a1260f315dad8a",
"src_encoding": "UTF-8",
"star_events_count": 2785,
"url": "https://raw.githubusercontent.com/ireader/media-server/3d8647f50fe832856f42b03d1e5b0fe2eafe5796/libhls/source/hls-master.c",
"visit_date": "2023-09-03T17:53:13.722595"
} | stackv2 | #include "hls-parser.h"
#include "hls-string.h"
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <errno.h>
// Typically, closed-caption [CEA608] media is carried in the video stream.
// Therefore, an EXT-X-MEDIA tag with TYPE of CLOSED-CAPTIONS does not specify
// a Rendition; the closed-caption media is present in the Media Segments of every video Rendition.
int hls_master_rendition(const struct hls_master_t* master, int variant, int type, const char* name)
{
size_t i;
int is_default;
int autoselect;
struct hls_media_t* m;
struct hls_variant_t* v;
const char* groups[4];
const char* renditions[] = { "AUDIO", "VIDEO", "SUBTITLES", "CLOSED-CAPTIONS", };
if (variant < 0 || variant >= (int)master->variant_count
|| type < HLS_MEDIA_AUDIO || type > HLS_MEDIA_CLOSED_CAPTIONS)
return -ENOENT;
type -= HLS_MEDIA_AUDIO;
v = &master->variants[variant];
groups[0] = v->audio ? v->audio : "";
groups[1] = v->video ? v->video : "";
groups[2] = v->subtitle ? v->subtitle : "";
groups[3] = v->closed_captions ? v->closed_captions : "";
if (!*groups[type])
return -1; // don't have alternative renditions
is_default = -1;
autoselect = -1;
for (i = 0; i < master->media_count; i++)
{
m = &master->medias[i];
if (0 != strcasecmp(renditions[type], m->type))
continue;
if (!m->group_id || 0 != strcmp(groups[type], m->group_id))
continue;
if (name)
{
if(m->name && 0 == strcmp(name, m->name))
return (int)i;
}
else
{
if (m->is_default)
is_default = (int)i;
else if(m->autoselect)
autoselect = (int)i;
}
}
return is_default > 0 ? is_default : (autoselect ? autoselect : -1);
}
int hls_master_best_variant(const struct hls_master_t* master)
{
int best;
size_t i;
struct hls_variant_t* v;
best = -1;
for (i = 0; i < master->variant_count; i++)
{
v = &master->variants[i];
if (-1 == best || v->bandwidth > master->variants[best].bandwidth)
best = (int)i;
}
return best;
}
| 2.46875 | 2 |
2024-11-18T22:22:18.814146+00:00 | 2019-01-24T17:08:07 | 423087324b59097b5859e3e9ce2febaa463eff7f | {
"blob_id": "423087324b59097b5859e3e9ce2febaa463eff7f",
"branch_name": "refs/heads/master",
"committer_date": "2019-01-24T17:08:07",
"content_id": "7c515243abedb849e607ee460592bfa6dc5bb5e8",
"detected_licenses": [
"MIT"
],
"directory_id": "44f4961ff5a627277644a5e3e25459da0e581f22",
"extension": "c",
"filename": "string.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 11959,
"license": "MIT",
"license_type": "permissive",
"path": "/test/expression/src/string.c",
"provenance": "stackv2-0123.json.gz:22219",
"repo_name": "cortoproject/corto-script-declare",
"revision_date": "2019-01-24T17:08:07",
"revision_id": "45ccadf6f3a79e0f05a7bcd4ecd3cb431f1deef8",
"snapshot_id": "ef358d82c86a3cb5773d997ca62120b0d7ae6e82",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/cortoproject/corto-script-declare/45ccadf6f3a79e0f05a7bcd4ecd3cb431f1deef8/test/expression/src/string.c",
"visit_date": "2020-03-12T10:26:05.465237"
} | stackv2 | /* This is a managed file. Do not delete this comment. */
#include <include/test.h>
void test_string_op_add(
test_string this)
{
const char *input = "'foo' + 'bar'";
int16_t ret;
corto_value value = corto_value_init();
ret = cortoscript_parse_expr(NULL, input, &value);
test_assert(ret == 0);
/* Validate contents of value */
test_assert(value.kind == CORTO_LITERAL);
corto_type type = corto_value_typeof(&value);
test_assert(type != NULL);
test_assert(type == (corto_type)corto_string_o);
char **lit = corto_value_ptrof(&value);
test_assertstr(*lit, "foobar");
}
void test_string_op_add_null_null(
test_string this)
{
const char *input = "null + null";
int16_t ret;
corto_value value = corto_value_init();
ret = cortoscript_parse_expr(NULL, input, &value);
test_assert(ret == 0);
/* Validate contents of value */
test_assert(value.kind == CORTO_LITERAL);
corto_type type = corto_value_typeof(&value);
test_assert(type == NULL);
void *lit = corto_value_ptrof(&value);
test_assert(lit == NULL);
}
void test_string_op_add_string_null(
test_string this)
{
const char *input = "'foo' + null";
int16_t ret;
corto_value value = corto_value_init();
ret = cortoscript_parse_expr(NULL, input, &value);
test_assert(ret == 0);
/* Validate contents of value */
test_assert(value.kind == CORTO_LITERAL);
corto_type type = corto_value_typeof(&value);
test_assert(type != NULL);
test_assert(type == (corto_type)corto_string_o);
char **lit = corto_value_ptrof(&value);
test_assertstr(*lit, "foo");
}
void test_string_op_cond_and_false(
test_string this)
{
const char *input = "'foo' && null";
int16_t ret;
corto_value value = corto_value_init();
ret = cortoscript_parse_expr(NULL, input, &value);
test_assert(ret == 0);
/* Validate contents of value */
test_assert(value.kind == CORTO_LITERAL);
corto_type type = corto_value_typeof(&value);
test_assert(type != NULL);
test_assert(type == (corto_type)corto_bool_o);
bool *lit = corto_value_ptrof(&value);
test_assert(*lit == false);
}
void test_string_op_cond_and_kw_false(
test_string this)
{
const char *input = "'foo' and null";
int16_t ret;
corto_value value = corto_value_init();
ret = cortoscript_parse_expr(NULL, input, &value);
test_assert(ret == 0);
/* Validate contents of value */
test_assert(value.kind == CORTO_LITERAL);
corto_type type = corto_value_typeof(&value);
test_assert(type != NULL);
test_assert(type == (corto_type)corto_bool_o);
bool *lit = corto_value_ptrof(&value);
test_assert(*lit == false);
}
void test_string_op_cond_and_kw_true(
test_string this)
{
const char *input = "'foo' and 'bar'";
int16_t ret;
corto_value value = corto_value_init();
ret = cortoscript_parse_expr(NULL, input, &value);
test_assert(ret == 0);
/* Validate contents of value */
test_assert(value.kind == CORTO_LITERAL);
corto_type type = corto_value_typeof(&value);
test_assert(type != NULL);
test_assert(type == (corto_type)corto_bool_o);
bool *lit = corto_value_ptrof(&value);
test_assert(*lit == true);
}
void test_string_op_cond_and_true(
test_string this)
{
const char *input = "'foo' && 'bar'";
int16_t ret;
corto_value value = corto_value_init();
ret = cortoscript_parse_expr(NULL, input, &value);
test_assert(ret == 0);
/* Validate contents of value */
test_assert(value.kind == CORTO_LITERAL);
corto_type type = corto_value_typeof(&value);
test_assert(type != NULL);
test_assert(type == (corto_type)corto_bool_o);
bool *lit = corto_value_ptrof(&value);
test_assert(*lit == true);
}
void test_string_op_cond_eq_false(
test_string this)
{
const char *input = "'foo' == 'bar'";
int16_t ret;
corto_value value = corto_value_init();
ret = cortoscript_parse_expr(NULL, input, &value);
test_assert(ret == 0);
/* Validate contents of value */
test_assert(value.kind == CORTO_LITERAL);
corto_type type = corto_value_typeof(&value);
test_assert(type != NULL);
test_assert(type == (corto_type)corto_bool_o);
bool *lit = corto_value_ptrof(&value);
test_assert(*lit == false);
}
void test_string_op_cond_eq_true(
test_string this)
{
const char *input = "'foo' == 'foo'";
int16_t ret;
corto_value value = corto_value_init();
ret = cortoscript_parse_expr(NULL, input, &value);
test_assert(ret == 0);
/* Validate contents of value */
test_assert(value.kind == CORTO_LITERAL);
corto_type type = corto_value_typeof(&value);
test_assert(type != NULL);
test_assert(type == (corto_type)corto_bool_o);
bool *lit = corto_value_ptrof(&value);
test_assert(*lit == true);
}
void test_string_op_cond_neq_false(
test_string this)
{
const char *input = "'foo' != 'foo'";
int16_t ret;
corto_value value = corto_value_init();
ret = cortoscript_parse_expr(NULL, input, &value);
test_assert(ret == 0);
/* Validate contents of value */
test_assert(value.kind == CORTO_LITERAL);
corto_type type = corto_value_typeof(&value);
test_assert(type != NULL);
test_assert(type == (corto_type)corto_bool_o);
bool *lit = corto_value_ptrof(&value);
test_assert(*lit == false);
}
void test_string_op_cond_neq_true(
test_string this)
{
const char *input = "'foo' != 'bar'";
int16_t ret;
corto_value value = corto_value_init();
ret = cortoscript_parse_expr(NULL, input, &value);
test_assert(ret == 0);
/* Validate contents of value */
test_assert(value.kind == CORTO_LITERAL);
corto_type type = corto_value_typeof(&value);
test_assert(type != NULL);
test_assert(type == (corto_type)corto_bool_o);
bool *lit = corto_value_ptrof(&value);
test_assert(*lit == true);
}
void test_string_op_cond_not_false(
test_string this)
{
const char *input = "!'foo'";
int16_t ret;
corto_value value = corto_value_init();
ret = cortoscript_parse_expr(NULL, input, &value);
test_assert(ret == 0);
/* Validate contents of value */
test_assert(value.kind == CORTO_LITERAL);
corto_type type = corto_value_typeof(&value);
test_assert(type != NULL);
test_assert(type == (corto_type)corto_bool_o);
bool *lit = corto_value_ptrof(&value);
test_assert(*lit == false);
}
void test_string_op_cond_not_kw_false(
test_string this)
{
const char *input = "not 'foo'";
int16_t ret;
corto_value value = corto_value_init();
ret = cortoscript_parse_expr(NULL, input, &value);
test_assert(ret == 0);
/* Validate contents of value */
test_assert(value.kind == CORTO_LITERAL);
corto_type type = corto_value_typeof(&value);
test_assert(type != NULL);
test_assert(type == (corto_type)corto_bool_o);
bool *lit = corto_value_ptrof(&value);
test_assert(*lit == false);
}
void test_string_op_cond_not_kw_true(
test_string this)
{
const char *input = "not null";
int16_t ret;
corto_value value = corto_value_init();
ret = cortoscript_parse_expr(NULL, input, &value);
test_assert(ret == 0);
/* Validate contents of value */
test_assert(value.kind == CORTO_LITERAL);
corto_type type = corto_value_typeof(&value);
test_assert(type != NULL);
test_assert(type == (corto_type)corto_bool_o);
bool *lit = corto_value_ptrof(&value);
test_assert(*lit == true);
}
void test_string_op_cond_not_true(
test_string this)
{
const char *input = "!null";
int16_t ret;
corto_value value = corto_value_init();
ret = cortoscript_parse_expr(NULL, input, &value);
test_assert(ret == 0);
/* Validate contents of value */
test_assert(value.kind == CORTO_LITERAL);
corto_type type = corto_value_typeof(&value);
test_assert(type != NULL);
test_assert(type == (corto_type)corto_bool_o);
bool *lit = corto_value_ptrof(&value);
test_assert(*lit == true);
}
void test_string_op_cond_or_false(
test_string this)
{
const char *input = "null || null";
int16_t ret;
corto_value value = corto_value_init();
ret = cortoscript_parse_expr(NULL, input, &value);
test_assert(ret == 0);
/* Validate contents of value */
test_assert(value.kind == CORTO_LITERAL);
corto_type type = corto_value_typeof(&value);
test_assert(type != NULL);
test_assert(type == (corto_type)corto_bool_o);
bool *lit = corto_value_ptrof(&value);
test_assert(*lit == false);
}
void test_string_op_cond_or_kw_false(
test_string this)
{
const char *input = "null or null";
int16_t ret;
corto_value value = corto_value_init();
ret = cortoscript_parse_expr(NULL, input, &value);
test_assert(ret == 0);
/* Validate contents of value */
test_assert(value.kind == CORTO_LITERAL);
corto_type type = corto_value_typeof(&value);
test_assert(type != NULL);
test_assert(type == (corto_type)corto_bool_o);
bool *lit = corto_value_ptrof(&value);
test_assert(*lit == false);
}
void test_string_op_cond_or_kw_true(
test_string this)
{
const char *input = "'foo' or null";
int16_t ret;
corto_value value = corto_value_init();
ret = cortoscript_parse_expr(NULL, input, &value);
test_assert(ret == 0);
/* Validate contents of value */
test_assert(value.kind == CORTO_LITERAL);
corto_type type = corto_value_typeof(&value);
test_assert(type != NULL);
test_assert(type == (corto_type)corto_bool_o);
bool *lit = corto_value_ptrof(&value);
test_assert(*lit == true);
}
void test_string_op_cond_or_true(
test_string this)
{
const char *input = "'foo' || null";
int16_t ret;
corto_value value = corto_value_init();
ret = cortoscript_parse_expr(NULL, input, &value);
test_assert(ret == 0);
/* Validate contents of value */
test_assert(value.kind == CORTO_LITERAL);
corto_type type = corto_value_typeof(&value);
test_assert(type != NULL);
test_assert(type == (corto_type)corto_bool_o);
bool *lit = corto_value_ptrof(&value);
test_assert(*lit == true);
}
void test_string_op_cond_or_true_string_string(
test_string this)
{
const char *input = "'foo' || 'bar'";
int16_t ret;
corto_value value = corto_value_init();
ret = cortoscript_parse_expr(NULL, input, &value);
test_assert(ret == 0);
/* Validate contents of value */
test_assert(value.kind == CORTO_LITERAL);
corto_type type = corto_value_typeof(&value);
test_assert(type != NULL);
test_assert(type == (corto_type)corto_bool_o);
bool *lit = corto_value_ptrof(&value);
test_assert(*lit == true);
}
void test_string_op_ternary_false(
test_string this)
{
const char *input = "null ? 'foo' : 'bar'";
int16_t ret;
corto_value value = corto_value_init();
ret = cortoscript_parse_expr(NULL, input, &value);
test_assert(ret == 0);
/* Validate contents of value */
test_assert(value.kind == CORTO_LITERAL);
corto_type type = corto_value_typeof(&value);
test_assert(type != NULL);
test_assert(type == (corto_type)corto_string_o);
char **lit = corto_value_ptrof(&value);
test_assertstr(*lit, "bar");
}
void test_string_op_ternary_true(
test_string this)
{
const char *input = "'hello' ? 'foo' : 'bar'";
int16_t ret;
corto_value value = corto_value_init();
ret = cortoscript_parse_expr(NULL, input, &value);
test_assert(ret == 0);
/* Validate contents of value */
test_assert(value.kind == CORTO_LITERAL);
corto_type type = corto_value_typeof(&value);
test_assert(type != NULL);
test_assert(type == (corto_type)corto_string_o);
char **lit = corto_value_ptrof(&value);
test_assertstr(*lit, "foo");
}
| 2.578125 | 3 |
2024-11-18T22:22:19.050122+00:00 | 2023-05-23T07:47:09 | 169ae4a23f8308f0bc9b8e4e0b3d1a520eae6cd0 | {
"blob_id": "169ae4a23f8308f0bc9b8e4e0b3d1a520eae6cd0",
"branch_name": "refs/heads/master",
"committer_date": "2023-05-23T07:47:09",
"content_id": "e40e06b5b1d20ebecabeb326cd4bd7f68008b290",
"detected_licenses": [
"MIT"
],
"directory_id": "1782b2a608d4336b018f30f4d2c619a84afe99db",
"extension": "c",
"filename": "GSP.c",
"fork_events_count": 13,
"gha_created_at": "2019-07-25T10:15:52",
"gha_event_created_at": "2022-10-15T06:00:42",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 198808647,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4696,
"license": "MIT",
"license_type": "permissive",
"path": "/bb3_multitool/_taiwan/otherapp_template/libctru/source/GSP.c",
"provenance": "stackv2-0123.json.gz:22477",
"repo_name": "zoogie/Bannerbomb3",
"revision_date": "2023-05-23T07:47:09",
"revision_id": "785231079bd0a7a72c973c309d5fb5ddd8123c88",
"snapshot_id": "e60636ad9bf63909e660e1fe47d9addc2401ecab",
"src_encoding": "UTF-8",
"star_events_count": 121,
"url": "https://raw.githubusercontent.com/zoogie/Bannerbomb3/785231079bd0a7a72c973c309d5fb5ddd8123c88/bb3_multitool/_taiwan/otherapp_template/libctru/source/GSP.c",
"visit_date": "2023-05-25T14:11:58.244332"
} | stackv2 | #include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctr/types.h>
#include <ctr/GSP.h>
#include <ctr/svc.h>
#include <ctr/srv.h>
Handle gspGpuHandle=0;
Result gspInit()
{
return srv_getServiceHandle(NULL, &gspGpuHandle, "gsp::Gpu");
}
void gspExit()
{
if(gspGpuHandle)svc_closeHandle(gspGpuHandle);
}
Result GSPGPU_AcquireRight(Handle* handle, u8 flags)
{
if(!handle)handle=&gspGpuHandle;
u32* cmdbuf=getThreadCommandBuffer();
cmdbuf[0]=0x160042; //request header code
cmdbuf[1]=flags;
cmdbuf[2]=0x0;
cmdbuf[3]=0xffff8001;
Result ret=0;
if((ret=svc_sendSyncRequest(*handle)))return ret;
return cmdbuf[1];
}
Result GSPGPU_ReleaseRight(Handle* handle)
{
if(!handle)handle=&gspGpuHandle;
u32* cmdbuf=getThreadCommandBuffer();
cmdbuf[0]=0x170000; //request header code
Result ret=0;
if((ret=svc_sendSyncRequest(*handle)))return ret;
return cmdbuf[1];
}
Result GSPGPU_FlushDataCache(Handle* handle, u8* adr, u32 size)
{
if(!handle)handle=&gspGpuHandle;
u32* cmdbuf=getThreadCommandBuffer();
cmdbuf[0]=0x80082; //request header code
cmdbuf[1]=(u32)adr;
cmdbuf[2]=size;
cmdbuf[3]=0x0;
cmdbuf[4]=0xffff8001;
Result ret=0;
if((ret=svc_sendSyncRequest(*handle)))return ret;
return cmdbuf[1];
}
Result GSPGPU_InvalidateDataCache(Handle* handle, u8* adr, u32 size)
{
Result ret=0;
u32 *cmdbuf = getThreadCommandBuffer();
if(!handle)handle=&gspGpuHandle;
cmdbuf[0] = 0x00090082;
cmdbuf[1] = (u32)adr;
cmdbuf[2] = size;
cmdbuf[3] = 0;
cmdbuf[4] = 0xFFFF8001;
if((ret=svc_sendSyncRequest(*handle)))return ret;
return cmdbuf[1];
}
Result GSPGPU_WriteHWRegs(Handle* handle, u32 regAddr, u32* data, u8 size)
{
if(!handle)handle=&gspGpuHandle;
if(size>0x80 || !data)return -1;
u32* cmdbuf=getThreadCommandBuffer();
cmdbuf[0]=0x10082; //request header code
cmdbuf[1]=regAddr;
cmdbuf[2]=size;
cmdbuf[3]=(size<<14)|2;
cmdbuf[4]=(u32)data;
Result ret=0;
if((ret=svc_sendSyncRequest(*handle)))return ret;
return cmdbuf[1];
}
Result GSPGPU_RegisterInterruptRelayQueue(Handle* handle, Handle eventHandle, u32 flags, Handle* outMemHandle, u8* threadID)
{
if(!handle)handle=&gspGpuHandle;
u32* cmdbuf=getThreadCommandBuffer();
cmdbuf[0]=0x130042; //request header code
cmdbuf[1]=flags;
cmdbuf[2]=0x0;
cmdbuf[3]=eventHandle;
Result ret=0;
if((ret=svc_sendSyncRequest(*handle)))return ret;
if(threadID)*threadID=cmdbuf[2];
if(outMemHandle)*outMemHandle=cmdbuf[4];
return cmdbuf[1];
}
Result GSPGPU_UnregisterInterruptRelayQueue(Handle* handle)
{
if(!handle)handle=&gspGpuHandle;
u32* cmdbuf=getThreadCommandBuffer();
cmdbuf[0]=0x00140000; //request header code
Result ret=0;
if((ret=svc_sendSyncRequest(*handle)))return ret;
return cmdbuf[1];
}
Result GSPGPU_TriggerCmdReqQueue(Handle* handle)
{
if(!handle)handle=&gspGpuHandle;
u32* cmdbuf=getThreadCommandBuffer();
cmdbuf[0]=0xC0000; //request header code
Result ret=0;
if((ret=svc_sendSyncRequest(*handle)))return ret;
return cmdbuf[1];
}
//essentially : get commandIndex and totalCommands, calculate offset of new command, copy command and update totalCommands
//use LDREX/STREX because this data may also be accessed by the GSP module and we don't want to break stuff
//(mostly, we could overwrite the buffer header with wrong data and make the GSP module reexecute old commands)
Result GSPGPU_submitGxCommand(u32* sharedGspCmdBuf, u32 gxCommand[0x8], Handle* handle)
{
if(!sharedGspCmdBuf || !gxCommand)return -1;
u32 cmdBufHeader;
__asm__ ("ldrex %[result], [%[adr]]" : [result] "=r" (cmdBufHeader) : [adr] "r" (sharedGspCmdBuf));
u8 commandIndex=cmdBufHeader&0xFF;
u8 totalCommands=(cmdBufHeader>>8)&0xFF;
if(totalCommands>=15)return -2;
//there are 15 command slots but we don't want to do a non-bitwise modulo...
// u8 nextCmd=(commandIndex+totalCommands)%15;
u8 nextCmd=(commandIndex+totalCommands);
while(nextCmd >= 15) nextCmd -= 15;
u32* dst=&sharedGspCmdBuf[8*(1+nextCmd)];
memcpy(dst, gxCommand, 0x20);
u32 mcrVal=0x0;
__asm__ ("mcr p15, 0, %[val], c7, c10, 4" :: [val] "r" (mcrVal)); //Data Synchronization Barrier Register
totalCommands++;
cmdBufHeader=((cmdBufHeader)&0xFFFF00FF)|(((u32)totalCommands)<<8);
while(1)
{
u32 strexResult;
__asm__ ("strex %[result], %[val], [%[adr]]" : [result] "=&r" (strexResult) : [adr] "r" (sharedGspCmdBuf), [val] "r" (cmdBufHeader));
if(!strexResult)break;
__asm__ ("ldrex %[result], [%[adr]]" : [result] "=r" (cmdBufHeader) : [adr] "r" (sharedGspCmdBuf));
totalCommands=((cmdBufHeader&0xFF00)>>8)+1;
cmdBufHeader=((cmdBufHeader)&0xFFFF00FF)|((totalCommands<<8)&0xFF00);
}
if(totalCommands==1)return GSPGPU_TriggerCmdReqQueue(handle);
return 0;
}
| 2.125 | 2 |
2024-11-18T22:22:19.421085+00:00 | 2021-04-11T17:20:12 | 3c2b7da2cfe4086b25041c9e286c1b7491adebe3 | {
"blob_id": "3c2b7da2cfe4086b25041c9e286c1b7491adebe3",
"branch_name": "refs/heads/main",
"committer_date": "2021-04-11T17:20:12",
"content_id": "b77a0973b8959fc7c7fec56a92716067519e28b6",
"detected_licenses": [
"MIT"
],
"directory_id": "9494e4827ea59c43f09610ecfe679facbabca320",
"extension": "c",
"filename": "db.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 356545104,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3158,
"license": "MIT",
"license_type": "permissive",
"path": "/src/db.c",
"provenance": "stackv2-0123.json.gz:22734",
"repo_name": "YigitGunduc/microdb",
"revision_date": "2021-04-11T17:20:12",
"revision_id": "01279d840ba9c30c421819344275c32e671e0174",
"snapshot_id": "4abc813c4806ffebbb83ddc63b24acd6e1c5ab5b",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/YigitGunduc/microdb/01279d840ba9c30c421819344275c32e671e0174/src/db.c",
"visit_date": "2023-03-31T20:51:47.494283"
} | stackv2 | #include <time.h>
#include <stdio.h>
#include <stdlib.h>
struct element {
char* key;
char* value;
struct element* next;
};
typedef struct element record;
void listAll(record *head) {
record *tempnode = head->next;
printf("+-----------------------------------+\n");
printf("| %-15.3s | %-15.5s |\n", "KEY", "VALUE");
printf("+-----------------------------------+\n");
while(tempnode != NULL){
printf("| %-15.16s | %-15.16s | \n", tempnode->key, tempnode->value);
tempnode = tempnode->next;
}
printf("+-----------------------------------+\n");
}
record* create_new_record(char* key, char* value) {
record *created_record = (record*) malloc(sizeof(record));
created_record->key = key;
created_record->value = value;
created_record->next = NULL;
return created_record;
}
void update(record *head, char* key, char* value) {
record *tmp = head;
while(tmp != NULL){
if(tmp->key == key) {
tmp->value = value;
}
tmp = tmp->next;
}
}
int length(record* head) {
record *temp = head->next;
int count = 1;
while(temp->next != NULL) {
count++;
temp = temp->next;
}
return count;
}
void del(record *head, char* key) {
record *tmp = head;
record *tmp2 = tmp->next;
while(tmp2 != NULL) {
if(tmp2->key == key) {
tmp->next = tmp2->next;
}
tmp = tmp->next;
tmp2 = tmp2->next;
}
}
void sSet(record *head, char* key, char* value) {
record *creatednode = create_new_record(key, value);
creatednode->next = head->next;
head->next = creatednode;
}
record* set(record *head, char* key, char* value) {
record *temp = head;
record *creatednode = create_new_record(key, value);
while(temp->next != NULL){
temp = temp->next;
}
temp->next = creatednode;
return head;
}
char* get(record *head, char* key) {
record *tmp = head;
while(tmp != NULL){
if(tmp->key == key) {
return tmp->value;
}
tmp = tmp->next;
}
return 0;
}
record* create_db() {
record *head = create_new_record(0,0);
return head;
}
void freedb(record *head) {
record *tmp;
tmp = head->next;
while(tmp) {
free(tmp);
tmp = tmp->next;
}
}
int main() {
record *c = create_db(); // initializes the database
char key[][5] = {"key1", "key2", "key3", "key4"};
char value[][7] = {"value1", "value2", "value3", "value4"};
sSet(c, key[0], value[0]); // creates a new db record as given key to the given value
sSet(c, key[1], value[1]);
set(c, key[2], value[2]);
set(c, key[3], value[3]);
update(c, key[0], value[2]); // updates give key with given value
del(c, key[2]); // deletes the value
listAll(c); // displays all the records in the database
char *result = get(c, key[3]); // searches database for give key
int numOfElements = length(c); // returns number of records in database
printf("value: %s\n", result);
printf("num of items: %d\n", numOfElements);
freedb(c);
return 0;
}
| 3.53125 | 4 |
2024-11-18T23:13:36.264787+00:00 | 2020-08-06T16:53:36 | 5ee5e9f55ce1fb1d50eea5a47ab2ff5939f61f06 | {
"blob_id": "5ee5e9f55ce1fb1d50eea5a47ab2ff5939f61f06",
"branch_name": "refs/heads/master",
"committer_date": "2020-08-06T16:53:36",
"content_id": "95117385b082aab884c80a95c6493374d6868483",
"detected_licenses": [
"MIT"
],
"directory_id": "8b7a272ae43c04ac490056635219be066aa6f2a1",
"extension": "h",
"filename": "block_framework_sender.h",
"fork_events_count": 1,
"gha_created_at": "2020-08-10T07:59:28",
"gha_event_created_at": "2020-08-10T07:59:29",
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 286412983,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 11073,
"license": "MIT",
"license_type": "permissive",
"path": "/plugins/fec/framework/block_framework_sender.h",
"provenance": "stackv2-0126.json.gz:308257",
"repo_name": "Ysurac/pquic",
"revision_date": "2020-08-06T16:53:36",
"revision_id": "2bd9737291f61f5f5286de6e758613f49237a0c6",
"snapshot_id": "b80c1649688a9a79c5430bffa0ac4d0022b52339",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Ysurac/pquic/2bd9737291f61f5f5286de6e758613f49237a0c6/plugins/fec/framework/block_framework_sender.h",
"visit_date": "2022-11-28T17:10:29.023840"
} | stackv2 | #include "../fec.h"
#include "../../helpers.h"
#include "../fec_protoops.h"
#define INITIAL_FEC_BLOCK_NUMBER 0
#define MAX_QUEUED_REPAIR_SYMBOLS 6
typedef uint32_t fec_block_number;
typedef struct {
repair_symbol_t *repair_symbol;
uint8_t nss;
uint8_t nrs;
} queue_item;
typedef struct {
fec_scheme_t fec_scheme;
fec_redundancy_controller_t controller;
fec_block_number current_block_number: 24;
fec_block_t *current_block;
queue_item repair_symbols_queue[MAX_QUEUED_REPAIR_SYMBOLS];
int repair_symbols_queue_head;
int repair_symbols_queue_length;
int queue_byte_offset; // current byte offset in the current repair symbol
int queue_piece_offset; // current piece number of the current repair symbol
} block_fec_framework_t;
static __attribute__((always_inline)) block_fec_framework_t *create_framework_sender(picoquic_cnx_t *cnx, fec_redundancy_controller_t controller, fec_scheme_t fs) {
block_fec_framework_t *bff = my_malloc(cnx, sizeof(block_fec_framework_t));
if (!bff)
return NULL;
my_memset(bff, 0, sizeof(block_fec_framework_t));
bff->current_block = malloc_fec_block(cnx, INITIAL_FEC_BLOCK_NUMBER);
if (!bff->current_block) {
my_free(cnx, bff);
return NULL;
}
uint8_t n = 0;
uint8_t k = 0;
get_redundancy_parameters(cnx, bff->controller, false, &n, &k);
bff->current_block->total_source_symbols = k;
bff->current_block->total_repair_symbols = n - k;
bff->controller = controller;
bff->fec_scheme = fs;
return bff;
}
static __attribute__((always_inline)) bool ready_to_send(picoquic_cnx_t *cnx, block_fec_framework_t *bff) {
uint8_t k = 0;
get_redundancy_parameters(cnx, bff->controller, false, NULL, &k);
return (bff->current_block->current_source_symbols >= k);
}
static __attribute__((always_inline)) bool has_repair_symbol_at_index(block_fec_framework_t *bff, int idx) {
return bff->repair_symbols_queue[idx].repair_symbol != NULL;
}
static __attribute__((always_inline)) void remove_item_at_index(picoquic_cnx_t *cnx, block_fec_framework_t *bff, int idx) {
free_repair_symbol(cnx, bff->repair_symbols_queue[idx].repair_symbol);
bff->repair_symbols_queue[idx].repair_symbol = NULL;
bff->repair_symbols_queue[idx].nss = 0;
bff->repair_symbols_queue[idx].nrs = 0;
}
static __attribute__((always_inline)) void put_item_at_index(block_fec_framework_t *bff, int idx, repair_symbol_t *rs, uint8_t nss, uint8_t nrs) {
bff->repair_symbols_queue[idx].repair_symbol = rs;
bff->repair_symbols_queue[idx].nss = nss;
bff->repair_symbols_queue[idx].nrs = nrs;
}
// adds a repair symbol in the queue waiting for the symbol to be sent
static __attribute__((always_inline)) void queue_repair_symbol(picoquic_cnx_t *cnx, block_fec_framework_t *bff, repair_symbol_t *rs, fec_block_t *fb){
int idx = ((uint32_t) bff->repair_symbols_queue_head + bff->repair_symbols_queue_length) % MAX_QUEUED_REPAIR_SYMBOLS;
if (has_repair_symbol_at_index(bff, idx)) {
remove_item_at_index(cnx, bff, idx);
if (bff->repair_symbols_queue_length > 1 && bff->repair_symbols_queue_head == idx) {
// the head is the next symbol
bff->repair_symbols_queue_head = ( (uint32_t) bff->repair_symbols_queue_head + 1) % MAX_QUEUED_REPAIR_SYMBOLS;
bff->queue_byte_offset = 0;
}
bff->repair_symbols_queue_length--;
}
put_item_at_index(bff, idx, rs, fb->total_source_symbols, fb->total_repair_symbols);
if (bff->repair_symbols_queue_length == 0) {
bff->repair_symbols_queue_head = idx;
bff->queue_byte_offset = 0;
}
bff->repair_symbols_queue_length++;
}
// adds a repair symbol in the queue waiting for the symbol to be sent
static __attribute__((always_inline)) void queue_repair_symbols(picoquic_cnx_t *cnx, block_fec_framework_t *bff, repair_symbol_t *rss[], int number_of_symbols, fec_block_t *fec_block){
int i;
for (i = 0 ; i < number_of_symbols ; i++) {
queue_repair_symbol(cnx, bff, rss[i], fec_block);
}
}
static __attribute__((always_inline)) size_t get_repair_payload_from_queue(picoquic_cnx_t *cnx, block_fec_framework_t *bff, size_t bytes_max, fec_frame_header_t *ffh, uint8_t *bytes){
if (bff->repair_symbols_queue_length == 0)
return 0;
repair_symbol_t *rs = bff->repair_symbols_queue[bff->repair_symbols_queue_head].repair_symbol;
// FIXME: temporarily ensure that the repair symbols are not split into multiple frames
if (bytes_max < rs->data_length) {
PROTOOP_PRINTF(cnx, "NOT ENOUGH BYTES TO SEND SYMBOL: %u < %u\n", bytes_max, rs->data_length);
return 0;
}
size_t amount = ((rs->data_length - bff->queue_byte_offset) <= bytes_max) ? (rs->data_length - bff->queue_byte_offset) : bytes_max;
// copy
my_memcpy(bytes, rs->data + bff->queue_byte_offset, amount);
// move forward in the symbol's buffer
bff->queue_byte_offset += amount;
bff->queue_piece_offset++;
ffh->repair_fec_payload_id = rs->repair_fec_payload_id;
ffh->offset = (uint8_t) bff->queue_piece_offset;
ffh->nss = bff->repair_symbols_queue[bff->repair_symbols_queue_head].nss;
ffh->nrs = bff->repair_symbols_queue[bff->repair_symbols_queue_head].nrs;
ffh->data_length = (uint16_t) amount;
ffh->fin_bit = bff->queue_byte_offset == rs->data_length;
protoop_arg_t args[2];
args[0] = amount;
args[1] = bytes_max;
if (bff->queue_byte_offset == rs->data_length) {
// this symbol has been sent: free the symbol and remove it from the queue
remove_item_at_index(cnx, bff, bff->repair_symbols_queue_head);
bff->repair_symbols_queue_head = ((uint32_t) bff->repair_symbols_queue_head + 1) % MAX_QUEUED_REPAIR_SYMBOLS;
bff->queue_byte_offset = 0;
bff->queue_piece_offset = 0;
bff->repair_symbols_queue_length--;
args[0] = (uint32_t) bff->repair_symbols_queue_length;
}
return amount;
}
//TODO: currently unprovable
static __attribute__((always_inline)) int reserve_fec_frames(picoquic_cnx_t *cnx, block_fec_framework_t *bff, size_t size_max) {
if (size_max <= sizeof(fec_frame_header_t))
return -1;
while (bff->repair_symbols_queue_length != 0) {
// FIXME: bourrin
fec_frame_t *ff = my_malloc(cnx, sizeof(fec_frame_t));
if (!ff)
return PICOQUIC_ERROR_MEMORY;
uint8_t *bytes = my_malloc(cnx, (unsigned int) (size_max - (1 + sizeof(fec_frame_header_t))));
if (!bytes)
return PICOQUIC_ERROR_MEMORY;
// copy the frame payload
size_t payload_size = get_repair_payload_from_queue(cnx, bff, size_max - sizeof(fec_frame_header_t) - 1, &ff->header, bytes);
if (!payload_size)
return PICOQUIC_ERROR_FRAME_BUFFER_TOO_SMALL;
ff->data = bytes;
reserve_frame_slot_t *slot = (reserve_frame_slot_t *) my_malloc(cnx, sizeof(reserve_frame_slot_t));
if (!slot)
return PICOQUIC_ERROR_MEMORY;
my_memset(slot, 0, sizeof(reserve_frame_slot_t));
slot->frame_type = FEC_TYPE;
slot->nb_bytes = 1 + sizeof(fec_frame_header_t) + payload_size;
slot->frame_ctx = ff;
slot->is_congestion_controlled = true;
size_t reserved_size = reserve_frames(cnx, 1, slot);
if (reserved_size < slot->nb_bytes) {
PROTOOP_PRINTF(cnx, "Unable to reserve frame slot\n");
my_free(cnx, ff->data);
my_free(cnx, ff);
my_free(cnx, slot);
return 1;
}
}
return 0;
}
static __attribute__((always_inline)) int generate_and_queue_repair_symbols(picoquic_cnx_t *cnx, block_fec_framework_t *bff, bool flush){
protoop_arg_t args[3];
protoop_arg_t outs[1];
args[0] = (protoop_arg_t) bff->current_block;
args[1] = (protoop_arg_t) bff->fec_scheme;
uint8_t n = 0;
uint8_t k = 0;
get_redundancy_parameters(cnx, bff->controller, flush, &n, &k);
bff->current_block->total_source_symbols = bff->current_block->current_source_symbols;
bff->current_block->total_repair_symbols = n - k;
int ret = (int) run_noparam(cnx, "fec_generate_repair_symbols", 2, args, outs);
if (!ret) {
PROTOOP_PRINTF(cnx, "SUCCESSFULLY GENERATED\n");
uint8_t i = 0;
for_each_repair_symbol(bff->current_block, repair_symbol_t *rs) {
rs->fec_block_number = bff->current_block_number;
rs->symbol_number = i++;
}
queue_repair_symbols(cnx, bff, bff->current_block->repair_symbols, bff->current_block->total_repair_symbols, bff->current_block);
}
if ((int) run_noparam(cnx, "should_send_repair_symbols", 0, NULL, NULL)) {
reserve_fec_frames(cnx, bff, PICOQUIC_MAX_PACKET_SIZE);
}
return ret;
}
static __attribute__((always_inline)) int sent_block(picoquic_cnx_t *cnx, block_fec_framework_t *ff, fec_block_t *fb) {
if (fb != ff->current_block) free_fec_block(cnx, fb, false);
else {
free_fec_block(cnx, ff->current_block, true);
ff->current_block_number++;
ff->current_block = malloc_fec_block(cnx, ff->current_block_number);
if (!ff->current_block)
return -1;
uint8_t n = 0;
uint8_t k = 0;
get_redundancy_parameters(cnx, ff->controller, false, &n, &k);
ff->current_block->total_source_symbols = k;
ff->current_block->total_repair_symbols = n - k;
}
return 0;
}
static __attribute__((always_inline)) source_fpid_t get_source_fpid(block_fec_framework_t *bff){
source_fpid_t s;
s.fec_block_number = bff->current_block_number;
s.symbol_number = bff->current_block->current_source_symbols;
return s;
}
// sets the source FPID of the Source Symbol and protects it.
static __attribute__((always_inline)) int protect_source_symbol(picoquic_cnx_t *cnx, block_fec_framework_t *bff, source_symbol_t *ss){
ss->source_fec_payload_id.fec_block_number = bff->current_block_number;
ss->source_fec_payload_id.symbol_number = bff->current_block->current_source_symbols;
if (!add_source_symbol_to_fec_block(ss, bff->current_block))
return -1;
if (ready_to_send(cnx, bff)) {
generate_and_queue_repair_symbols(cnx, bff, false);
sent_block(cnx, bff,bff->current_block);
}
PROTOOP_PRINTF(cnx, "SYMBOL PROTECTED\n");
return 0;
}
static __attribute__((always_inline)) int flush_fec_block(picoquic_cnx_t *cnx, block_fec_framework_t *bff) {
fec_block_t *fb = bff->current_block;
if (fb->current_source_symbols >= 1) {
fb->total_source_symbols = fb->current_source_symbols;
fb->total_repair_symbols = fb->current_source_symbols < fb->total_repair_symbols ? fb->current_source_symbols : fb->total_repair_symbols;
PROTOOP_PRINTF(cnx, "FLUSH FEC BLOCK: %u source symbols, %u repair symbols\n", fb->total_source_symbols, fb->total_repair_symbols);
generate_and_queue_repair_symbols(cnx, bff, true);
sent_block(cnx, bff, fb);
}
return 0;
} | 2.359375 | 2 |
2024-11-18T23:13:36.464536+00:00 | 2021-01-25T12:00:21 | 0ad1665a76238e3051cd929577aa69ca3182d413 | {
"blob_id": "0ad1665a76238e3051cd929577aa69ca3182d413",
"branch_name": "refs/heads/main",
"committer_date": "2021-01-25T12:00:21",
"content_id": "fa70d96476b245cffac2c738d6c4665de940ff55",
"detected_licenses": [
"MIT"
],
"directory_id": "2ccf005d6999c4985eacb59b1429bfa67d01a08f",
"extension": "h",
"filename": "movement_management.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 332729819,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1340,
"license": "MIT",
"license_type": "permissive",
"path": "/Arduino/Piattforma_Treni/movement_management.h",
"provenance": "stackv2-0126.json.gz:308519",
"repo_name": "LukeScrewdriver/GestioneTreni",
"revision_date": "2021-01-25T12:00:21",
"revision_id": "70c7ae5123a9ec680c7e35d819ed51bf3b3536e3",
"snapshot_id": "0786cc9c6fd894d264cb5203e42f093bcc847716",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/LukeScrewdriver/GestioneTreni/70c7ae5123a9ec680c7e35d819ed51bf3b3536e3/Arduino/Piattforma_Treni/movement_management.h",
"visit_date": "2023-02-21T15:50:30.378707"
} | stackv2 | void movimento(int direction_rotation)//incrementale
{
static int fase = 0;
static unsigned long tmpmem = millis();
switch (fase)
{
case (0):
if (direction_rotation == 0)
{
digitalWrite(PIN_MOTOR_DIR, HIGH);//pin rotazione
digitalWrite(PIN_MOTOR_STEP, HIGH);//pin step
step_position++;
fase++;
}
else if (direction_rotation == 1)
{
digitalWrite(PIN_MOTOR_DIR, LOW);//
digitalWrite(PIN_MOTOR_STEP, HIGH);//pin step
step_position--;
fase++;
}
break;
case (1):
if (non_blocking_delay(&tmpmem, 1)) //wait that motor reach the position
{
digitalWrite(PIN_MOTOR_STEP, LOW);
tmpmem = millis();
fase = 0;
}
break;
}
}
void azzeramento()
{
static unsigned long tmpmem = millis();
//Serial.println("azzeramento");
movimento(true);
do
{
if (non_blocking_delay(&tmpmem, 200)) //wait that motor reach the position
{
movimento(true);
tmpmem = millis();
}
}
while (digitalRead(PIN_ENDSTOP) == HIGH);//position reached
step_position = 0;//set zero
}
long positioncheck(long curr_position) {
if (curr_position > STEP_FULL_ROTATION) {
curr_position = 0;
}
if (curr_position < 0) {
curr_position = STEP_FULL_ROTATION;
}
}
| 2.765625 | 3 |
2024-11-18T23:13:36.633347+00:00 | 2021-04-09T17:28:21 | af4af830f29205fb8034ef7dac966397e3c7a3bf | {
"blob_id": "af4af830f29205fb8034ef7dac966397e3c7a3bf",
"branch_name": "refs/heads/master",
"committer_date": "2021-04-09T17:28:21",
"content_id": "eeee11b5cf1f205fef48824ee977c858a71f5ec4",
"detected_licenses": [
"MIT"
],
"directory_id": "77117fc39111e53f44c6f64ff3f3ec1114131f8a",
"extension": "c",
"filename": "main.c",
"fork_events_count": 0,
"gha_created_at": "2021-04-09T16:25:47",
"gha_event_created_at": "2021-04-09T17:08:53",
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 356333633,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 249,
"license": "MIT",
"license_type": "permissive",
"path": "/Beginner/C/1008/main.c",
"provenance": "stackv2-0126.json.gz:308649",
"repo_name": "Icaro-G-Silva/URIJudge",
"revision_date": "2021-04-09T17:28:21",
"revision_id": "c7ef0dc827efbeba4f07f158e345d3149a497b82",
"snapshot_id": "8a99fac0ccf4e4cece13d50623e209856bd1d842",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Icaro-G-Silva/URIJudge/c7ef0dc827efbeba4f07f158e345d3149a497b82/Beginner/C/1008/main.c",
"visit_date": "2023-04-04T20:24:29.074553"
} | stackv2 | #include <stdio.h>
int main() {
int number, hours;
float hourValue;
scanf("%d", &number);
scanf("%d", &hours);
scanf("%f", &hourValue);
printf("NUMBER = %d\nSALARY = U$ %.2f\n", number, (hourValue*hours));
return 0;
}
| 2.796875 | 3 |
2024-11-18T23:13:36.708434+00:00 | 2018-01-12T15:10:25 | e4c476c55c3cc66a710ff68300283ad52a315eb3 | {
"blob_id": "e4c476c55c3cc66a710ff68300283ad52a315eb3",
"branch_name": "refs/heads/master",
"committer_date": "2018-01-12T15:10:25",
"content_id": "2d49b7a8fd424e0bfebbd036af351b65b0681afe",
"detected_licenses": [
"MIT"
],
"directory_id": "cd0143cb9ce296f10e13ec00e063b64be0235d78",
"extension": "c",
"filename": "e.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 107721275,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 447,
"license": "MIT",
"license_type": "permissive",
"path": "/assignments/5/19/e.c",
"provenance": "stackv2-0126.json.gz:308785",
"repo_name": "AntonLydike/uni-info-I",
"revision_date": "2018-01-12T15:10:25",
"revision_id": "dd4526a32e3404ce5e8c0622842cf42e7095a9da",
"snapshot_id": "2fd62cfddf92198441be5aeadccf3170c925384e",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/AntonLydike/uni-info-I/dd4526a32e3404ce5e8c0622842cf42e7095a9da/assignments/5/19/e.c",
"visit_date": "2021-03-19T18:18:28.170900"
} | stackv2 | #include <stdio.h>
void print_triangle(int n);
int main(void)
{
int n;
printf("Eine Zahl eingeben: ");
while (1) {
if (scanf("%i", &n) != 1 || getchar() != '\n') {
break;
}
print_triangle(n);
printf("Neue Eingabe: ");
}
return 0;
}
void print_triangle(int n)
{
int j;
for (; n > 0; n--) {
for (j = 0; j < n; j++) {
printf("0");
}
printf("\n");
}
}
| 3.328125 | 3 |
2024-11-18T23:13:38.690721+00:00 | 2019-06-11T05:27:23 | 49565be78728e0ed16be5599d46c7b9d2570c19c | {
"blob_id": "49565be78728e0ed16be5599d46c7b9d2570c19c",
"branch_name": "refs/heads/master",
"committer_date": "2019-06-11T05:27:23",
"content_id": "d106c943c21f0541393f7c3d45af01339f7f5ee3",
"detected_licenses": [
"MIT"
],
"directory_id": "36e334b11611b28bef605df9446c0e7496492aae",
"extension": "c",
"filename": "jacobi_mpi.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": 11258,
"license": "MIT",
"license_type": "permissive",
"path": "/jacobi_mpi.c",
"provenance": "stackv2-0126.json.gz:309306",
"repo_name": "PikaPikaKaia/parallel-computing",
"revision_date": "2019-06-11T05:27:23",
"revision_id": "658f8adbc6920ac7e368e68034a2ebf035d56737",
"snapshot_id": "e835fb8f8babdb4d43471460365506c8229e9051",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/PikaPikaKaia/parallel-computing/658f8adbc6920ac7e368e68034a2ebf035d56737/jacobi_mpi.c",
"visit_date": "2023-03-16T19:53:46.747982"
} | stackv2 |
/* Code from Pacheco book (see below). Comments added by N. Matloff:
We are solving the system of n linear equations Ax = b for x, in
an iterative manner.
Let x_old denote our last guess (i.e. our last iterate) for x. How
do we get x_new, our new guess? The answer lies in the observation
that if we multiply the i-th row of A times the true solution vector
x, we should get b[i], the i-th component of b. So, what we do is
take x_old, replace its i-th component by a scalar variable u to be
solved for, then multiply the i-th row of A times this modified
x_old, and solve for u. This value of u will now be the i-th
component of x_new. Doing this once for each row of A, we get all the
n components of x_new.
We iterate until x_new is not very different from x_old. It can be
proved that this scheme does converge, under the right conditions.
Now, let's parallelize this operation for p nodes, where n is an
exact multiple of p. Let n_bar = n/p. For concreteness, suppose
n = 100000 and p = 10, so n_bar = 10000. What we do is have the
first node update the first 10000 components of x (i.e. compute
the first 10000 components of x_new, from A, x_old and b), the
second node update the second 10000 components of x, and so on.
You can see that mode 0 uses MPI_Bcast() to get the initial data
(e.g. n) out to the other nodes. It could instead call MPI_Send()
from within a loop, but MPI_Bcast() is both clearer code and faster;
a good MPI implementation will have MPI_Bcast() very tightly
designed, e.g. to do some latency hiding.
Note that the i-th node only needs the i-th set of rows of A.
So node 0 needs to send the first 10000 rows of A to itself,
the second 10000 rows of A to node 1, and so on. Again, this
could be done using MPI_Send() in a loop, but it can be done
much more cleanly and efficiently using MPI_Scatter():
MPI_Scatter(temp, n_bar*MAX_DIM, MPI_FLOAT, A_local,
n_bar*MAX_DIM, MPI_FLOAT, 0, MPI_COMM_WORLD);
Our matrix A is in temp. A set of n_bar of its rows will consist
of n_bar*MAX_DIM elements. The call above says that node 0 will
parcel out temp to the various nodes, with the i-th set of
n_bar*MAX_DIM elements going to the i-th node, to be stored in
A_local at that node. Note carefully that when node 0 executes
this call, MPI will treat it as a send; when any other node executes
the call, MPI will treat it as a receive.
The inverse of MPI_Scatter() is MPI_Gather(), used here to get the
final values back to node 0 for printing at the end of execution
of the program:
MPI_Gather(A_local, n_bar*MAX_DIM, MPI_FLOAT, temp,
n_bar*MAX_DIM, MPI_FLOAT, 0, MPI_COMM_WORLD);
Here the call at node 0 is taken as a receive, and at the other
nodes it's taken to be a send.
After an iteration, each node must somehow get its chunk to all the
other nodes, in preparation for the next iteration. The most
primitive way to do this would be to have a loop in which a node
calls MPI_Send() once for each other node. An improvement on this
would be for the node to call MPI_Bcast(). But the best way, used
below, is to call MPI_AllGather(), which does a gather operation
at all nodes. */
/* parallel_jacobi.c -- parallel implementation of Jacobi's method
* for solving the linear system Ax = b. Uses block distribution
* of vectors and block-row distribution of A.
*
* Input:
* n: order of system
* tol: convergence tolerance
* max_iter: maximum number of iterations
* A: coefficient matrix
* b: right-hand side of system
*
* Output:
* x: the solution if the method converges
* max_iter: if the method fails to converge
*
* Notes:
* 1. A should be strongly diagonally dominant in
* order to insure convergence.
* 2. A, x, and b are statically allocated.
*
* Taken from Chap 10, Parallel Processing with MPI, by Peter Pacheco
*/
#include <stdio.h>
#include "mpi.h"
#include <math.h>
#define Swap(x,y) {float* temp; temp = x; x = y; y = temp;}
#define MAX_DIM 12
typedef float MATRIX_T[MAX_DIM][MAX_DIM];
int Parallel_jacobi(
MATRIX_T A_local /* in */,
float x_local[] /* out */,
float b_local[] /* in */,
int n /* in */,
float tol /* in */,
int max_iter /* in */,
int p /* in */,
int my_rank /* in */);
void Read_matrix(char* prompt, MATRIX_T A_local, int n,
int my_rank, int p);
void Read_vector(char* prompt, float x_local[], int n, int my_rank,
int p);
void Print_matrix(char* title, MATRIX_T A_local, int n,
int my_rank, int p);
void Print_vector(char* title, float x_local[], int n, int my_rank,
int p);
main(int argc, char* argv[]) {
int p;
int my_rank;
MATRIX_T A_local;
float x_local[MAX_DIM];
float b_local[MAX_DIM];
int n;
float tol;
int max_iter;
int converged;
MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &p);
MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);
if (my_rank == 0) {
printf("Enter n, tolerance, and max number of iterations\n");
scanf("%d %f %d", &n, &tol, &max_iter);
}
MPI_Bcast(&n, 1, MPI_INT, 0, MPI_COMM_WORLD);
MPI_Bcast(&tol, 1, MPI_FLOAT, 0, MPI_COMM_WORLD);
MPI_Bcast(&max_iter, 1, MPI_INT, 0, MPI_COMM_WORLD);
Read_matrix("Enter the matrix", A_local, n, my_rank, p);
Read_vector("Enter the right-hand side", b_local, n, my_rank, p);
converged = Parallel_jacobi(A_local, x_local, b_local, n,
tol, max_iter, p, my_rank);
if (converged)
Print_vector("The solution is", x_local, n, my_rank, p);
else
if (my_rank == 0)
printf("Failed to converge in %d iterations\n", max_iter);
MPI_Finalize();
} /* main */
/*********************************************************************/
/* Return 1 if iteration converged, 0 otherwise */
/* MATRIX_T is a 2-dimensional array */
int Parallel_jacobi(
MATRIX_T A_local /* in */,
float x_local[] /* out */,
float b_local[] /* in */,
int n /* in */,
float tol /* in */,
int max_iter /* in */,
int p /* in */,
int my_rank /* in */) {
int i_local, i_global, j;
int n_bar;
int iter_num;
float x_temp1[MAX_DIM];
float x_temp2[MAX_DIM];
float* x_old;
float* x_new;
float Distance(float x[], float y[], int n);
n_bar = n/p;
/* Initialize x */
MPI_Allgather(b_local, n_bar, MPI_FLOAT, x_temp1,
n_bar, MPI_FLOAT, MPI_COMM_WORLD);
x_new = x_temp1;
x_old = x_temp2;
iter_num = 0;
do {
iter_num++;
/* Interchange x_old and x_new */
Swap(x_old, x_new);
for (i_local = 0; i_local < n_bar; i_local++){
i_global = i_local + my_rank*n_bar;
x_local[i_local] = b_local[i_local];
for (j = 0; j < i_global; j++)
x_local[i_local] = x_local[i_local] -
A_local[i_local][j]*x_old[j];
for (j = i_global+1; j < n; j++)
x_local[i_local] = x_local[i_local] -
A_local[i_local][j]*x_old[j];
x_local[i_local] = x_local[i_local]/
A_local[i_local][i_global];
}
MPI_Allgather(x_local, n_bar, MPI_FLOAT, x_new,
n_bar, MPI_FLOAT, MPI_COMM_WORLD);
} while ((iter_num < max_iter) &&
(Distance(x_new,x_old,n) >= tol));
if (Distance(x_new,x_old,n) < tol)
return 1;
else
return 0;
} /* Jacobi */
/*********************************************************************/
float Distance(float x[], float y[], int n) {
int i;
float sum = 0.0;
for (i = 0; i < n; i++) {
sum = sum + (x[i] - y[i])*(x[i] - y[i]);
}
return sqrt(sum);
} /* Distance */
/*********************************************************************/
void Read_matrix(
char* prompt /* in */,
MATRIX_T A_local /* out */,
int n /* in */,
int my_rank /* in */,
int p /* in */) {
int i, j;
MATRIX_T temp;
int n_bar;
n_bar = n/p;
/* Fill dummy entries in temp with zeroes */
for (i = 0; i < n; i++)
for (j = n; j < MAX_DIM; j++)
temp[i][j] = 0.0;
if (my_rank == 0) {
printf("%s\n", prompt);
for (i = 0; i < n; i++)
for (j = 0; j < n; j++)
scanf("%f",&temp[i][j]);
}
MPI_Scatter(temp, n_bar*MAX_DIM, MPI_FLOAT, A_local,
n_bar*MAX_DIM, MPI_FLOAT, 0, MPI_COMM_WORLD);
} /* Read_matrix */
/*********************************************************************/
void Read_vector(
char* prompt /* in */,
float x_local[] /* out */,
int n /* in */,
int my_rank /* in */,
int p /* in */) {
int i;
float temp[MAX_DIM];
int n_bar;
n_bar = n/p;
if (my_rank == 0) {
printf("%s\n", prompt);
for (i = 0; i < n; i++)
scanf("%f", &temp[i]);
}
MPI_Scatter(temp, n_bar, MPI_FLOAT, x_local, n_bar, MPI_FLOAT,
0, MPI_COMM_WORLD);
} /* Read_vector */
/*********************************************************************/
void Print_matrix(char* title, MATRIX_T A_local, int n,
int my_rank, int p);
void Print_matrix(
char* title /* in */,
MATRIX_T A_local /* in */,
int n /* in */,
int my_rank /* in */,
int p /* in */) {
int i, j;
MATRIX_T temp;
int n_bar;
n_bar = n/p;
MPI_Gather(A_local, n_bar*MAX_DIM, MPI_FLOAT, temp,
n_bar*MAX_DIM, MPI_FLOAT, 0, MPI_COMM_WORLD);
if (my_rank == 0) {
printf("%s\n", title);
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++)
printf("%4.1f ", temp[i][j]);
printf("\n");
}
}
} /* Print_matrix */
/*********************************************************************/
void Print_vector(char* title, float x_local[], int n, int my_rank,
int p);
void Print_vector(
char* title /* in */,
float x_local[] /* in */,
int n /* in */,
int my_rank /* in */,
int p /* in */) {
int i;
float temp[MAX_DIM];
int n_bar;
n_bar = n/p;
MPI_Gather(x_local, n_bar, MPI_FLOAT, temp, n_bar, MPI_FLOAT,
0, MPI_COMM_WORLD);
if (my_rank == 0) {
printf("%s\n", title);
for (i = 0; i < n; i++)
printf("%4.1f ", temp[i]);
printf("\n");
}
} /* Print_vector */
| 2.734375 | 3 |
2024-11-18T23:13:39.122431+00:00 | 2023-05-18T14:00:42 | 6aabb286412023dafa49df406f4cb4d0629b4b8c | {
"blob_id": "6aabb286412023dafa49df406f4cb4d0629b4b8c",
"branch_name": "refs/heads/master",
"committer_date": "2023-05-18T14:00:42",
"content_id": "2a8bb5c11e17eaf3c0ee791d7a63b2422ffd5820",
"detected_licenses": [
"Apache-2.0",
"BSD-3-Clause"
],
"directory_id": "984bc4181baec6e5a4b05a657e666b0e9f89f3f3",
"extension": "c",
"filename": "mongoc-ts-pool.c",
"fork_events_count": 263,
"gha_created_at": "2012-12-08T13:17:01",
"gha_event_created_at": "2023-08-08T20:25:03",
"gha_language": "C++",
"gha_license_id": "BSD-3-Clause",
"github_id": 7067532,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 7557,
"license": "Apache-2.0,BSD-3-Clause",
"license_type": "permissive",
"path": "/3rdparty/mongo-c-driver-1.21.2/src/libmongoc/src/mongoc/mongoc-ts-pool.c",
"provenance": "stackv2-0126.json.gz:309567",
"repo_name": "treefrogframework/treefrog-framework",
"revision_date": "2023-05-18T14:00:42",
"revision_id": "a1df97793e8cc628779378e5adae9af6987460c1",
"snapshot_id": "0173245ff92162d2107af79861505981980d1eca",
"src_encoding": "UTF-8",
"star_events_count": 1152,
"url": "https://raw.githubusercontent.com/treefrogframework/treefrog-framework/a1df97793e8cc628779378e5adae9af6987460c1/3rdparty/mongo-c-driver-1.21.2/src/libmongoc/src/mongoc/mongoc-ts-pool.c",
"visit_date": "2023-08-22T03:57:58.891846"
} | stackv2 | #include "mongoc-ts-pool-private.h"
#include "common-thread-private.h"
#include "bson/bson.h"
#if defined(_MSC_VER)
typedef double _max_align_type;
#elif defined(__APPLE__)
typedef long double _max_align_type;
#else
/* Based on the GCC max_align_t definition */
typedef struct _max_align_type {
long long maxalign_1 __attribute__ ((__aligned__ (__alignof__(long long))));
long double maxalign_2
__attribute__ ((__aligned__ (__alignof__(long double))));
} _max_align_type;
#endif
/**
* Toggle this to enable/disable checks that all items are returned to the pool
* before the pool is destroyed
*/
enum { AUDIT_POOL_ENABLED = 0 };
typedef struct pool_node {
struct pool_node *next;
mongoc_ts_pool *owner_pool;
_max_align_type data[];
} pool_node;
struct mongoc_ts_pool {
mongoc_ts_pool_params params;
pool_node *head;
/* Number of elements in the pool */
int32_t size;
bson_mutex_t mtx;
/* Number of elements that the pool has given to users.
* If AUDIT_POOL_ENABLED is zero, this member is unused */
int32_t outstanding_items;
};
/**
* @brief Check whether we should drop the given node from the pool
*/
static bool
_should_prune (const pool_node *node)
{
mongoc_ts_pool *pool = node->owner_pool;
return pool->params.prune_predicate &&
pool->params.prune_predicate (node->data, pool->params.userdata);
}
/**
* @brief Create a new pool node and contained element.
*
* @return pool_node* A pointer to a constructed element, or NULL if the
* constructor sets `error`
*/
static pool_node *
_new_item (mongoc_ts_pool *pool, bson_error_t *error)
{
pool_node *node =
bson_malloc0 (sizeof (pool_node) + pool->params.element_size);
node->owner_pool = pool;
if (pool->params.constructor) {
/* To construct, we need to know if that constructor fails */
bson_error_t my_error;
if (!error) {
/* Caller doesn't care about the error, but we care in case the
* constructor might fail */
error = &my_error;
}
/* Clear the error */
error->code = 0;
error->domain = 0;
error->message[0] = 0;
/* Construct the object */
pool->params.constructor (node->data, pool->params.userdata, error);
if (error->code != 0) {
/* Constructor reported an error. Deallocate and drop the node. */
bson_free (node);
node = NULL;
}
}
if (node && AUDIT_POOL_ENABLED) {
bson_atomic_int32_fetch_add (
&pool->outstanding_items, 1, bson_memory_order_relaxed);
}
return node;
}
/**
* @brief Destroy the given node and the element that it contains
*/
static void
_delete_item (pool_node *node)
{
mongoc_ts_pool *pool = node->owner_pool;
if (pool->params.destructor) {
pool->params.destructor (node->data, pool->params.userdata);
}
bson_free (node);
}
/**
* @brief Try to take a node from the pool. Returns `NULL` if the pool is empty.
*/
static pool_node *
_try_get (mongoc_ts_pool *pool)
{
pool_node *node;
bson_mutex_lock (&pool->mtx);
node = pool->head;
if (node) {
pool->head = node->next;
}
bson_mutex_unlock (&pool->mtx);
if (node) {
bson_atomic_int32_fetch_sub (&pool->size, 1, bson_memory_order_relaxed);
if (AUDIT_POOL_ENABLED) {
bson_atomic_int32_fetch_add (
&pool->outstanding_items, 1, bson_memory_order_relaxed);
}
}
return node;
}
mongoc_ts_pool *
mongoc_ts_pool_new (mongoc_ts_pool_params params)
{
mongoc_ts_pool *r = bson_malloc0 (sizeof (mongoc_ts_pool));
r->params = params;
r->head = NULL;
r->size = 0;
if (AUDIT_POOL_ENABLED) {
r->outstanding_items = 0;
}
bson_mutex_init (&r->mtx);
return r;
}
void
mongoc_ts_pool_free (mongoc_ts_pool *pool)
{
if (AUDIT_POOL_ENABLED) {
BSON_ASSERT (
pool->outstanding_items == 0 &&
"Pool was destroyed while there are still items checked out");
}
mongoc_ts_pool_clear (pool);
bson_mutex_destroy (&pool->mtx);
bson_free (pool);
}
void
mongoc_ts_pool_clear (mongoc_ts_pool *pool)
{
pool_node *node;
{
bson_mutex_lock (&pool->mtx);
node = pool->head;
pool->head = NULL;
pool->size = 0;
bson_mutex_unlock (&pool->mtx);
}
while (node) {
pool_node *n = node;
node = n->next;
_delete_item (n);
}
}
void *
mongoc_ts_pool_get_existing (mongoc_ts_pool *pool)
{
pool_node *node;
retry:
node = _try_get (pool);
if (node && _should_prune (node)) {
/* This node should be pruned now. Drop it and try again. */
mongoc_ts_pool_drop (node->data);
goto retry;
}
return node ? node->data : NULL;
}
void *
mongoc_ts_pool_get (mongoc_ts_pool *pool, bson_error_t *error)
{
pool_node *node;
retry:
node = _try_get (pool);
if (node && _should_prune (node)) {
/* This node should be pruned now. Drop it and try again. */
mongoc_ts_pool_drop (node->data);
goto retry;
}
if (node == NULL) {
/* We need a new item */
node = _new_item (pool, error);
}
if (node == NULL) {
/* No item in pool, and we couldn't create one either */
return NULL;
}
return node->data;
}
void
mongoc_ts_pool_return (void *item)
{
pool_node *node = (void *) ((uint8_t *) (item) -offsetof (pool_node, data));
if (_should_prune (node)) {
mongoc_ts_pool_drop (item);
} else {
mongoc_ts_pool *pool = node->owner_pool;
bson_mutex_lock (&pool->mtx);
node->next = pool->head;
pool->head = node;
bson_mutex_unlock (&pool->mtx);
bson_atomic_int32_fetch_add (
&node->owner_pool->size, 1, bson_memory_order_relaxed);
if (AUDIT_POOL_ENABLED) {
bson_atomic_int32_fetch_sub (
&node->owner_pool->outstanding_items, 1, bson_memory_order_relaxed);
}
}
}
void
mongoc_ts_pool_drop (void *item)
{
pool_node *node = (void *) ((uint8_t *) (item) -offsetof (pool_node, data));
if (AUDIT_POOL_ENABLED) {
bson_atomic_int32_fetch_sub (
&node->owner_pool->outstanding_items, 1, bson_memory_order_relaxed);
}
_delete_item (node);
}
int
mongoc_ts_pool_is_empty (const mongoc_ts_pool *pool)
{
return mongoc_ts_pool_size (pool) == 0;
}
size_t
mongoc_ts_pool_size (const mongoc_ts_pool *pool)
{
return bson_atomic_int32_fetch (&pool->size, bson_memory_order_relaxed);
}
void
mongoc_ts_pool_visit_each (mongoc_ts_pool *pool,
void *visit_userdata,
int (*visit) (void *item,
void *pool_userdata,
void *visit_userdata))
{
/* Pointer to the pointer that must be updated in case of an item pruning */
pool_node **node_ptrptr;
/* The node we are looking at */
pool_node *node;
bson_mutex_lock (&pool->mtx);
node_ptrptr = &pool->head;
node = pool->head;
while (node) {
const bool should_remove =
visit (node->data, pool->params.userdata, visit_userdata);
pool_node *const next_node = node->next;
if (!should_remove) {
node_ptrptr = &node->next;
node = next_node;
continue;
}
/* Retarget the previous pointer to the next node in line */
*node_ptrptr = node->next;
_delete_item (node);
pool->size--;
/* Leave node_ptrptr pointing to the previous pointer, because we may
* need to erase another item */
node = next_node;
}
bson_mutex_unlock (&pool->mtx);
}
| 2.484375 | 2 |
2024-11-18T23:13:39.878685+00:00 | 2019-07-14T09:57:18 | 84985abec5146630657450e2abbb1feb9f962558 | {
"blob_id": "84985abec5146630657450e2abbb1feb9f962558",
"branch_name": "refs/heads/master",
"committer_date": "2019-07-14T09:57:18",
"content_id": "aac0aa3981bca511b39ef89e2457af3509c0db32",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "b9d67c91873b55835dee9d4c6e6674181e19fbcf",
"extension": "c",
"filename": "sys_https.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 196803670,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 9746,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/hualai_sdk/components/system/source/network/sys_https.c",
"provenance": "stackv2-0126.json.gz:309957",
"repo_name": "wangziheng437/idf",
"revision_date": "2019-07-14T09:57:18",
"revision_id": "7d986c4c097556e562e5a9ad84fdd76e04ddfd8f",
"snapshot_id": "ff127257a4d7a633f21449e6bf9880349b5338a5",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/wangziheng437/idf/7d986c4c097556e562e5a9ad84fdd76e04ddfd8f/hualai_sdk/components/system/source/network/sys_https.c",
"visit_date": "2020-06-19T17:37:03.461558"
} | stackv2 | /*
* @Description:
* @Author:
* @Date: 2019-06-14 16:37:30
* @LastEditTime: 2019-07-09 00:14:14
*/
#include <netdb.h>
#include <sys/socket.h>
#include "esp_system.h"
#include "mbedtls/platform.h"
#include "mbedtls/net_sockets.h"
#include "mbedtls/esp_debug.h"
#include "mbedtls/ssl.h"
#include "mbedtls/entropy.h"
#include "mbedtls/ctr_drbg.h"
#include "mbedtls/error.h"
#include "mbedtls/certs.h"
#include "sys_base.h"
#include "sys_https.h"
/**
* @description:
*/
sys_https_info_cb_fun sys_https_info_cb;
sys_https_info_t https_info = {};
/**
* @description:
*/
void sys_https_info_execute_cb(sys_https_info_t *info);
int sys_https_post(char *url ,char *host ,char *port, char *type, char *msg, char *out, int out_len);
int sys_https_get(char *url ,char *host ,char *port, char *msg, char *out, int out_len);
/**
* @description:
* @param {type}
* @return:
*/
void sys_https_info_sign_cb(sys_https_info_cb_fun fun)
{
sys_https_info_cb = fun;
}
/**
* @description:
* @param {type}
* @return:
*/
void sys_https_info_execute_cb(sys_https_info_t *info)
{
if(sys_https_info_cb == NULL)
{
sys_log_error("%s:param NULL!", SYS_GET_FUN_NAME);
return;
}
sys_https_info_cb(info);
}
/**
* @description:
* @param {type}
* @return:
*/
void sys_https_mbedtls_init(mbedtls_ssl_context *ssl, mbedtls_ctr_drbg_context *ctr,
mbedtls_ssl_config *conf, mbedtls_entropy_context *ent, char *host)
{
int rc = 0;
https_info.step = SYS_HTTPS_CB_STEP_INIT;
if((ssl == NULL) || (ctr == NULL) || (conf == NULL) || (ent == NULL) || (host == NULL))
{
sys_log_error("%s:param NULL!", SYS_GET_FUN_NAME);
https_info.code = SYS_HTTPS_CODE_PARAM_NULL;
sys_https_info_execute_cb(&https_info);
return;
}
mbedtls_ssl_init(ssl);
mbedtls_ctr_drbg_init(ctr);
mbedtls_ssl_config_init(conf);
mbedtls_entropy_init(ent);
if(0 != (rc = mbedtls_ctr_drbg_seed(ctr, mbedtls_entropy_func, ent, NULL, 0)))
{
sys_log_error("%s:mbedtls_ctr_drbg_seed error! %d", SYS_GET_FUN_NAME, rc);
https_info.code = rc;
sys_https_info_execute_cb(&https_info);
return;
}
if(0 != (rc = mbedtls_ssl_set_hostname(ssl, host)))
{
sys_log_error("%s:mbedtls_ssl_set_hostname error! -0x%x", SYS_GET_FUN_NAME, -rc);
https_info.code = rc;
sys_https_info_execute_cb(&https_info);
return;
}
if(0 != (rc = mbedtls_ssl_config_defaults(conf,
MBEDTLS_SSL_IS_CLIENT,
MBEDTLS_SSL_TRANSPORT_STREAM,
MBEDTLS_SSL_PRESET_DEFAULT)))
{
sys_log_error("%s:mbedtls_ssl_config_defaults error! %d", SYS_GET_FUN_NAME, rc);
https_info.code = rc;
sys_https_info_execute_cb(&https_info);
return;
}
mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_OPTIONAL);
mbedtls_ssl_conf_rng(conf, mbedtls_ctr_drbg_random, ctr);
if (0 != (rc = mbedtls_ssl_setup(ssl, conf)))
{
sys_log_error("%s:mbedtls_ssl_setup error! -0x%x", SYS_GET_FUN_NAME, -rc);
https_info.code = rc;
sys_https_info_execute_cb(&https_info);
return;
}
https_info.code = SYS_HTTPS_CODE_SUCCESS;
sys_https_info_execute_cb(&https_info);
return;
}
/**
* @description:
* @param {type}
* @return:
*/
void sys_https_mbedtls_connect(mbedtls_ssl_context *ssl, mbedtls_net_context *net, char *host, char *port)
{
int rc = 0;
https_info.step = SYS_HTTPS_CB_STEP_CON;
if((ssl == NULL) || (net == NULL) || (host == NULL) || (port == NULL))
{
sys_log_error("%s:param NULL!", SYS_GET_FUN_NAME);
https_info.code = SYS_HTTPS_CODE_PARAM_NULL;
sys_https_info_execute_cb(&https_info);
return;
}
sys_log_info("connecting:%s:%s...", host, port);
mbedtls_net_init(net);
if (0 != (rc = mbedtls_net_connect(net, host, port, MBEDTLS_NET_PROTO_TCP)))
{
sys_log_error("%s:mbedtls_net_connect error! -0x%x", SYS_GET_FUN_NAME, -rc);
https_info.code = rc;
sys_https_info_execute_cb(&https_info);
return;
}
sys_log_debug("connected.");
mbedtls_ssl_set_bio(ssl, net, mbedtls_net_send, mbedtls_net_recv, mbedtls_net_recv_timeout);
sys_log_debug("Performing the SSL/TLS handshake...");
#if(SYS_CORE_MODEL == SYS_ESP8266)
rtc_clk_cpu_freq_set(RTC_CPU_FREQ_160M); //Increase the main frequency
#endif
while (0 != (rc = mbedtls_ssl_handshake(ssl)))
{
if (rc != MBEDTLS_ERR_SSL_WANT_READ && rc != MBEDTLS_ERR_SSL_WANT_WRITE )
{
#if(SYS_CORE_MODEL == SYS_ESP8266)
rtc_clk_cpu_freq_set(RTC_CPU_FREQ_80M);
#endif
sys_log_error("%s:mbedtls_ssl_handshake error! -0x%x", SYS_GET_FUN_NAME, -rc);
https_info.code = rc;
sys_https_info_execute_cb(&https_info);
return;
}
}
#if(SYS_CORE_MODEL == SYS_ESP8266)
rtc_clk_cpu_freq_set(RTC_CPU_FREQ_80M);//Recovery of main frequency
#endif
sys_log_debug("cipher suite is %s", mbedtls_ssl_get_ciphersuite(ssl));
https_info.code = SYS_HTTPS_CODE_SUCCESS;
sys_https_info_execute_cb(&https_info);
return;
}
/**
* @description:
* @param {type}
* @return:
*/
void sys_https_mbedtls_write(mbedtls_ssl_context *ssl, char *buf, int buf_len)
{
int rc = 0;
https_info.step = SYS_HTTPS_CB_STEP_WRITE;
if((ssl == NULL) || (buf == NULL))
{
sys_log_error("%s:param NULL!", SYS_GET_FUN_NAME);
https_info.code = SYS_HTTPS_CODE_PARAM_NULL;
sys_https_info_execute_cb(&https_info);
return;
}
rc = mbedtls_ssl_write(ssl, (const unsigned char *)buf, buf_len);
if (rc >= 0)
{
sys_log_debug("%s:%s", SYS_GET_FUN_NAME, buf);
https_info.code = rc;
sys_https_info_execute_cb(&https_info);
return;
}
else
{
if (rc != MBEDTLS_ERR_SSL_WANT_WRITE && rc != MBEDTLS_ERR_SSL_WANT_READ)
{
sys_log_error("%s:mbedtls_ssl_write error! -0x%x", SYS_GET_FUN_NAME, -rc);
https_info.code = rc;
sys_https_info_execute_cb(&https_info);
}
sys_log_error("%s:mbedtls_ssl_write fail!", SYS_GET_FUN_NAME);
return;
}
}
/**
* @description:
* @param {type}
* @return:
*/
void sys_https_mbedtls_read(mbedtls_ssl_context *ssl, mbedtls_ssl_config *conf, char *out, int out_len, uint32_t out_time)
{
int rc = 0;
https_info.step = SYS_HTTPS_CB_STEP_READ;
if((ssl == NULL) || (conf == NULL) || (out == NULL) || (out_len <= 0))
{
sys_log_error("%s:param NULL!", SYS_GET_FUN_NAME);
https_info.code = SYS_HTTPS_CODE_PARAM_NULL;
sys_https_info_execute_cb(&https_info);
return;
}
mbedtls_ssl_conf_read_timeout(conf, out_time);
rc = mbedtls_ssl_read(ssl, (unsigned char *)out, out_len);
if(rc == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY)
{
rc = 0;
}
if(rc == MBEDTLS_ERR_SSL_TIMEOUT)
{
sys_log_info("Read over");
rc = 0;
}
if(rc < 0)
{
sys_log_error("%s:mbedtls_ssl_read error! -0x%x", SYS_GET_FUN_NAME, -rc);
https_info.code = rc;
sys_https_info_execute_cb(&https_info);
return;
}
if(rc == 0)
{
sys_log_info("connection closed");
}
if(rc > 0)
{
sys_log_debug("%s:%d bytes read", SYS_GET_FUN_NAME, rc);
}
https_info.code = rc;
sys_https_info_execute_cb(&https_info);
return;
}
/**
* @description:
* @param {type}
* @return:
*/
void sys_https_mbedtls_again(mbedtls_ssl_context *ssl, mbedtls_net_context *net)
{
https_info.step = SYS_HTTPS_CB_STEP_AGAIN;
if((ssl == NULL) || (net == NULL))
{
sys_log_error("%s:param NULL!", SYS_GET_FUN_NAME);
https_info.code = SYS_HTTPS_CODE_PARAM_NULL;
sys_https_info_execute_cb(&https_info);
return;
}
mbedtls_ssl_close_notify(ssl);
mbedtls_ssl_session_reset(ssl);
mbedtls_net_free(net);
https_info.code = SYS_HTTPS_CODE_SUCCESS;
sys_https_info_execute_cb(&https_info);
return;
}
/**
* @description:
* @param {type}
* @return:
*/
void sys_https_mbedtls_exit(mbedtls_ssl_context *ssl, mbedtls_ctr_drbg_context *ctr,
mbedtls_ssl_config *conf, mbedtls_entropy_context *ent)
{
https_info.step = SYS_HTTPS_CB_STEP_EXIT;
if((ssl == NULL) || (ctr == NULL) || (conf == NULL) || (ent == NULL))
{
sys_log_error("%s:param NULL!", SYS_GET_FUN_NAME);
https_info.code = SYS_HTTPS_CODE_PARAM_NULL;
sys_https_info_execute_cb(&https_info);
return;
}
mbedtls_ssl_config_free(conf); //释放内存
mbedtls_ctr_drbg_free(ctr);
mbedtls_entropy_free(ent);
mbedtls_ssl_free(ssl);
https_info.code = SYS_HTTPS_CODE_SUCCESS;
sys_https_info_execute_cb(&https_info);
return;
}
/**
* @description:
* @param {type}
* @return:
*/
// int sys_https_rest(char *host, char *port, char *msg, int timeout)
// {
// if((host == NULL) || (port == NULL) || (msg == NULL) || (timeout <= 0))
// {
// sys_log_error("%s:param NULL!", SYS_GET_FUN_NAME);
// return SYS_HTTPS_CODE_PARAM_NULL;
// }
// mbedtls_entropy_context ent;
// mbedtls_ctr_drbg_context ctr;
// mbedtls_ssl_context ssl;
// mbedtls_ssl_config conf;
// mbedtls_net_context net;
// if(sys_https_mbedtls_init(&ssl,&ctr,&conf,&ent,host))
// {
// sys_https_mbedtls_again(&ssl,&net);
// }
// while((rc = sys_https_mbedtls_net(&ssl,&net,host,port))!=0)
// {
// sys_https_mbedtls_again(&ssl,&net);
// }
// sys_https_mbedtls_write(&ssl,msg);
// int read_ret=sys_https_mbedtls_read(&ssl,&conf,buf,BUF_LEN,timeout);//超时太短在弱网时失败概率大
// sys_https_mbedtls_again(&ssl,&net);
// sys_https_mbedtls_exit(&ssl,&ctr,&conf,&ent);
// } | 2.109375 | 2 |
2024-11-18T23:13:39.962931+00:00 | 2019-03-17T14:20:41 | 8baab356b8433feb45341d2b68360f201f459b12 | {
"blob_id": "8baab356b8433feb45341d2b68360f201f459b12",
"branch_name": "refs/heads/master",
"committer_date": "2019-03-17T14:20:41",
"content_id": "dc07c74efa9cb36db1e4373fdb5519cfb815c30c",
"detected_licenses": [
"MIT"
],
"directory_id": "671014fdd95e823959bd8f5314f50412c0421f48",
"extension": "c",
"filename": "calculator.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 140420153,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3432,
"license": "MIT",
"license_type": "permissive",
"path": "/calculate/calculator.c",
"provenance": "stackv2-0126.json.gz:310087",
"repo_name": "XiangSugar/CLearning",
"revision_date": "2019-03-17T14:20:41",
"revision_id": "3f9d319b128ca9ff04d051ec65378e8954e2d06e",
"snapshot_id": "11880763ceaefd50c2c1d69d9c0bfee1e5585f2c",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/XiangSugar/CLearning/3f9d319b128ca9ff04d051ec65378e8954e2d06e/calculate/calculator.c",
"visit_date": "2020-03-22T17:51:14.176501"
} | stackv2 | # include <stdio.h>
# include <stdlib.h> //使用系统的 atof()
# include <ctype.h>
# define MAXOP 100 //操作数或者运算符的最大长度
# define NUMBER '0' //标识找到一个数
# define BUFSIZE 100 //缓冲区的最大长度
# define MAXVAL 100 //栈的最大深度
int sp = 0; //下一个空闲栈位置
double val[MAXVAL]; //栈值
char buf[BUFSIZE]; //用于 ungetch() 的缓冲区
int bufp = 0; //buf中下一个空闲位置
//各函数的声明
int getop(char []);
int getch(void);
void push(double); //把 f 压入到栈值中
double pop(void); //弹出并返回栈顶的值
void ungetch(int);
int main()
{
int type;
double op2;
char s[MAXOP];
while ((type = getop(s)) != EOF){
switch (type){
case NUMBER:
push(atof(s));
break;
case '+':
push(pop() + pop());
break;
case '*':
push(pop() * pop());
break;
case '-':
op2 = pop();
push(pop() - op2);
break;
case '/':
op2 = pop();
if(op2 != 0){
push(pop() / op2);
}
else{
printf("error: zero divisor\n");
}
break;
case '\n':
printf("\t%.8g\n", pop());
break;
default:
printf("error: unknown command %s\n", s);
break;
}
}
return 0;
}
//该函数由主函数的while循环来循环执行
int getop(char s[]) //传入的 s[] 其实是空的 用于存放从输入中读取到的操作数或者操作符
{
int i, c;
//跳过字符串开头的所有的空白字符,后面的不管
while ((s[0] = c = getch()) == ' ' || c == '\t')
;
//s[1] = '\0';
if(!isdigit(c) && c != '.'){
s[1] = '\0';
return c;
}
// return c; // 返回操作符
i = 0;
if (isdigit(c)){
while (isdigit(s[++i] = c = getch())) //判断下一位,如果为数字,继续收集,直到不是数值为止
;
}
if (c == '.'){
//如果是小数点,则要继续收集该浮点数的小数部分,所以有如下代码
while (isdigit(s[++i] = c = getch()))
;
}
s[i] = '\0'; //加入字符串结束标志位
if (c != EOF) //如果输入中后面还有内容,则将多读取的用于判断的位压回到缓冲区
ungetch(c);
return NUMBER; //返回操作数
}
int getch(void)
{
return (bufp>0) ? buf[--bufp] : getchar(); //先减再取 首先取缓冲区中的内容(正常情况下缓冲区只存储一个数或者字符)
}
void ungetch(int c)
{
if(bufp >= BUFSIZE){
printf("ungetchar: too many characters\n"); //正常情况下不可能超出范围
}
else{
buf[bufp++] = c; //先存再加
}
}
void push(double f)
{
if (sp < MAXVAL)
val[sp++] = f;
else
printf("error: stack full, can't push %g\n", f);
}
double pop(void)
{
if (sp > 0)
return val[--sp];
else{
printf("error: stack empty\n");
return 0.0;
}
} | 3.75 | 4 |
2024-11-18T20:53:26.226945+00:00 | 2023-09-01T05:11:15 | 4954001e3a2e03aca4a424cfe9ab8b47ed79654c | {
"blob_id": "4954001e3a2e03aca4a424cfe9ab8b47ed79654c",
"branch_name": "refs/heads/master",
"committer_date": "2023-09-01T05:11:15",
"content_id": "e1fb08bfa1aa324b5fb0247ce22f6b0ebff2e499",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "27686262789b3a49f515d84f7c3a438fe494aba4",
"extension": "c",
"filename": "scopes.c",
"fork_events_count": 2,
"gha_created_at": "2021-06-10T08:46:27",
"gha_event_created_at": "2021-06-10T08:46:27",
"gha_language": null,
"gha_license_id": "Apache-2.0",
"github_id": 375630926,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1239,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/third_party/tests/Icarus/vpi/scopes.c",
"provenance": "stackv2-0127.json.gz:66913",
"repo_name": "alainmarcel/Surelog",
"revision_date": "2023-09-01T05:11:15",
"revision_id": "2a20e445423b6f4fbc9aa64556be238ddd55cbcc",
"snapshot_id": "2733c3c8933c23438f4f154ae1d34e6c28938eaf",
"src_encoding": "UTF-8",
"star_events_count": 25,
"url": "https://raw.githubusercontent.com/alainmarcel/Surelog/2a20e445423b6f4fbc9aa64556be238ddd55cbcc/third_party/tests/Icarus/vpi/scopes.c",
"visit_date": "2023-09-01T09:28:31.709598"
} | stackv2 | #include <stdio.h>
#include <string.h>
#include "vpi_user.h"
static void spaces(int num)
{
while (num > 0) {
vpi_printf(" ");
num--;
}
}
static void RecurseScope(vpiHandle handle, int depth)
{
vpiHandle iter, hand;
iter = !handle ? vpi_iterate(vpiModule, NULL) :
vpi_iterate(vpiInternalScope, handle);
while (iter && (hand = vpi_scan(iter))) {
spaces(depth);
vpi_printf("%s is type ", vpi_get_str(vpiName, hand));
switch (vpi_get(vpiType,hand)) {
case vpiModule: vpi_printf("vpiModule\n"); break;
case vpiTask: vpi_printf("vpiTask\n"); break;
case vpiFunction: vpi_printf("vpiFunction\n"); break;
case vpiNamedBegin: vpi_printf("vpiNamedBegin\n"); break;
case vpiNamedFork: vpi_printf("vpiNamedFork\n"); break;
default: vpi_printf("unknown (%d)\n", vpi_get(vpiType,hand)); break;
}
RecurseScope(hand, depth + 2);
}
}
static int CompileTF(char *x)
{
RecurseScope(NULL, 0);
return 0;
}
static void my_Register(void)
{
s_vpi_systf_data tf_data;
tf_data.type = vpiSysTask;
tf_data.tfname = "$test";
tf_data.calltf = 0;
tf_data.compiletf = CompileTF;
tf_data.sizetf = 0;
vpi_register_systf(&tf_data);
}
void (*vlog_startup_routines[]) () = {
my_Register, 0};
| 2.265625 | 2 |
2024-11-18T20:53:26.384519+00:00 | 2020-07-01T19:53:20 | f09cf792030e5763284243b72420f093ab966353 | {
"blob_id": "f09cf792030e5763284243b72420f093ab966353",
"branch_name": "refs/heads/master",
"committer_date": "2020-07-01T19:53:20",
"content_id": "5294a886accadf49390882fe56eebf73270e2768",
"detected_licenses": [
"MIT"
],
"directory_id": "7cb2deee641016a7105cbb42d788860fa2d4b96b",
"extension": "c",
"filename": "letraD.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 212868209,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 390,
"license": "MIT",
"license_type": "permissive",
"path": "/EXaula07-for-do-while/pdf3/letraD.c",
"provenance": "stackv2-0127.json.gz:67173",
"repo_name": "mferoc/UniProjecao-Algoritmos-e-Logica-de-Programacao",
"revision_date": "2020-07-01T19:53:20",
"revision_id": "63c279afa7ef88b66c4788eec5587b86852984e7",
"snapshot_id": "9b3679c45e60eabab3f7b1a835c1b00b33409a82",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/mferoc/UniProjecao-Algoritmos-e-Logica-de-Programacao/63c279afa7ef88b66c4788eec5587b86852984e7/EXaula07-for-do-while/pdf3/letraD.c",
"visit_date": "2020-08-06T06:17:32.298054"
} | stackv2 | #include <stdio.h>
int main(void) {
int i, num;
i = 1;
printf("Digite um numero N para limitar um intervalo de 1 a N: ");
scanf("%d" , &num);
do {
//i++;
if (num % 3 == 0 && num % 7 == 0)
printf("O numero %d e divisivel por 3 e por 7\n" , i);
else
printf("O numero %d nao e divisivel por 3 e por 7\n" , i);
i++;}while ( i <= num );
return 0; }
| 3.390625 | 3 |
2024-11-18T20:53:26.449816+00:00 | 2020-02-04T17:50:20 | c93a465bb073e5fb6d788be43a03f2f5d9d39f93 | {
"blob_id": "c93a465bb073e5fb6d788be43a03f2f5d9d39f93",
"branch_name": "refs/heads/master",
"committer_date": "2020-02-04T17:50:20",
"content_id": "54159f5e9ee0d83c9357ca2c8e854d8690407815",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "d00e106f88b46e2f74ca8ce7eba623061d4b8779",
"extension": "c",
"filename": "otool_manager_x64.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 231369152,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2111,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/otool_manager_x64.c",
"provenance": "stackv2-0127.json.gz:67303",
"repo_name": "vlobunet/nm_otool",
"revision_date": "2020-02-04T17:50:20",
"revision_id": "49f745148955e9b97b5a9dae003fb29c51d72bdf",
"snapshot_id": "9c9c77e55f56525f298ae7f6027058da325b2e9a",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/vlobunet/nm_otool/49f745148955e9b97b5a9dae003fb29c51d72bdf/src/otool_manager_x64.c",
"visit_date": "2022-04-10T11:08:13.466797"
} | stackv2 | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* otool_manager_x64.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: vlobunet <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/01/27 19:46:13 by vlobunet #+# #+# */
/* Updated: 2020/01/27 19:46:14 by vlobunet ### ########.fr */
/* */
/* ************************************************************************** */
#include "../includes/nm_otool.h"
int otool_print_sector_64(size_t start_offset)
{
struct section_64 *sect_64;
char *text;
if (!(sect_64 = get_struct(start_offset, sizeof(*sect_64))))
return (err(ERR_FILE, "bad offset section"));
if (!(text = get_struct(get_4b(sect_64->addr), get_8b(sect_64->size))))
return (err(ERR_FILE, "bad ofset text"));
print_text_section(get_8b(sect_64->size), get_8b(sect_64->addr), text);
return (1);
}
int segment_manager_x64(size_t start_offset)
{
struct segment_command_64 *seg_x64;
struct section_64 *sect_64;
size_t off;
uint32_t n;
if (!(seg_x64 = get_struct(start_offset, sizeof(*seg_x64))))
return (err(ERR_FILE, "bad segment offset"));
off = start_offset + sizeof(*seg_x64);
if (!(sect_64 = get_struct(off, sizeof(*sect_64))))
return (err(ERR_FILE, "bad section offset"));
n = get_4b(seg_x64->nsects);
while (n--)
{
if ((!ft_strncmp(sect_64->sectname, "__text", 16))
&& (!ft_strncmp(sect_64->segname, "__TEXT", 16))
&& !otool_print_sector_64(off))
return (err(ERR_FILE, __func__));
off += sizeof(*sect_64);
if (!(sect_64 = get_struct(off, sizeof(*sect_64))))
return (err(ERR_FILE, "bad section offset"));
}
return (1);
}
| 2.21875 | 2 |
2024-11-18T20:53:26.574050+00:00 | 2023-07-29T21:54:06 | 434db5e6232b574163059fd5395f89a7c3e896a4 | {
"blob_id": "434db5e6232b574163059fd5395f89a7c3e896a4",
"branch_name": "refs/heads/master",
"committer_date": "2023-07-29T21:54:06",
"content_id": "01d385a73ed61371a116c7adfab7307993ebafcc",
"detected_licenses": [
"MIT"
],
"directory_id": "84e97d818876d20fab9591ff9d88129acfcc4295",
"extension": "c",
"filename": "eeprom.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 6969810,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 7986,
"license": "MIT",
"license_type": "permissive",
"path": "/platform/lpc/lpc43xx/eeprom.c",
"provenance": "stackv2-0127.json.gz:67565",
"repo_name": "stxent/halm",
"revision_date": "2023-07-29T21:54:06",
"revision_id": "7396d3d639e696cca262fc926b245e296c22bad1",
"snapshot_id": "93bd734be36e4828693551f8184173ba74b338be",
"src_encoding": "UTF-8",
"star_events_count": 6,
"url": "https://raw.githubusercontent.com/stxent/halm/7396d3d639e696cca262fc926b245e296c22bad1/platform/lpc/lpc43xx/eeprom.c",
"visit_date": "2023-08-08T13:10:39.034473"
} | stackv2 | /*
* eeprom.c
* Copyright (C) 2016 xent
* Project is distributed under the terms of the MIT License
*/
#include <halm/irq.h>
#include <halm/platform/lpc/clocking.h>
#include <halm/platform/lpc/eeprom.h>
#include <halm/platform/lpc/lpc43xx/eeprom_defs.h>
#include <assert.h>
#include <string.h>
/*----------------------------------------------------------------------------*/
#define EEPROM_CLOCK 1500000
#define PAGE_SIZE 128
/*----------------------------------------------------------------------------*/
static size_t calcChunkLength(uint32_t, size_t);
static inline bool isAddressValid(const struct Eeprom *, uint32_t);
static void programNextChunk(struct Eeprom *);
static bool setInstance(struct Eeprom *);
/*----------------------------------------------------------------------------*/
static enum Result eepromInit(void *, const void *);
static void eepromDeinit(void *);
static void eepromSetCallback(void *, void (*)(void *), void *);
static enum Result eepromGetParam(void *, int, void *);
static enum Result eepromSetParam(void *, int, const void *);
static size_t eepromRead(void *, void *, size_t);
static size_t eepromWrite(void *, const void *, size_t);
/*----------------------------------------------------------------------------*/
const struct InterfaceClass * const Eeprom = &(const struct InterfaceClass){
.size = sizeof(struct Eeprom),
.init = eepromInit,
.deinit = eepromDeinit,
.setCallback = eepromSetCallback,
.getParam = eepromGetParam,
.setParam = eepromSetParam,
.read = eepromRead,
.write = eepromWrite
};
/*----------------------------------------------------------------------------*/
static struct Eeprom *instance = NULL;
/*----------------------------------------------------------------------------*/
static size_t calcChunkLength(uint32_t address, size_t left)
{
const uint32_t pageAddress = (address + PAGE_SIZE) & ~(PAGE_SIZE - 1);
const size_t wordsLeft = (pageAddress - address) >> 2;
const size_t chunkLength = MIN(left, wordsLeft);
return chunkLength;
}
/*----------------------------------------------------------------------------*/
static inline bool isAddressValid(const struct Eeprom *interface,
uint32_t address)
{
return !(address & 0x03) && address <= interface->base.size;
}
/*----------------------------------------------------------------------------*/
static void programNextChunk(struct Eeprom *interface)
{
const size_t length = calcChunkLength(interface->offset, instance->left);
uint32_t * const address = (uint32_t *)interface->offset;
const IrqState state = irqSave();
for (size_t index = 0; index < length; ++index)
{
/* Write buffer using 4-byte words */
address[index] = interface->buffer[index];
}
LPC_EEPROM->CMD = CMD_ERASE_PROGRAM;
irqRestore(state);
}
/*----------------------------------------------------------------------------*/
static bool setInstance(struct Eeprom *object)
{
if (instance == NULL)
{
instance = object;
return true;
}
else
return false;
}
/*----------------------------------------------------------------------------*/
void EEPROM_ISR(void)
{
if (!(LPC_EEPROM->INTSTAT & INT_PROG_DONE))
return;
/* Clear pending interrupt flag */
LPC_EEPROM->INTSTATCLR = INT_PROG_DONE;
const size_t currentChunkLength = calcChunkLength(instance->offset,
instance->left);
instance->left -= currentChunkLength;
instance->buffer += currentChunkLength;
instance->offset += currentChunkLength << 2;
if (instance->left)
programNextChunk(instance);
else
instance->position = instance->offset - instance->base.address;
}
/*----------------------------------------------------------------------------*/
static enum Result eepromInit(void *object, const void *configBase)
{
const struct EepromConfig * const config = configBase;
struct Eeprom * const interface = object;
if (!setInstance(interface))
return E_BUSY;
const enum Result res = EepromBase->init(interface, NULL);
if (res != E_OK)
return res;
interface->position = 0;
interface->blocking = true;
/* Main clock frequency */
const uint32_t frequency = clockFrequency(MainClock);
/* Main clock period in nanoseconds */
const uint32_t period = (1000000000UL - 1 + frequency) / frequency;
LPC_EEPROM->PWRDWN = 0;
LPC_EEPROM->CLKDIV = (frequency + (EEPROM_CLOCK - 1)) / EEPROM_CLOCK - 1;
const uint32_t rphase1 = (RPHASE1_WAIT_TIME - 1 + period) / period;
const uint32_t rphase2 = (RPHASE2_WAIT_TIME - 1 + period) / period;
LPC_EEPROM->RWSTATE = RWSTATE_RPHASE1(rphase1 - 1)
| RWSTATE_RPHASE2(rphase2 - 1);
const uint32_t phase1 = (PHASE1_WAIT_TIME - 1 + period) / period;
const uint32_t phase2 = (PHASE2_WAIT_TIME - 1 + period) / period;
const uint32_t phase3 = (PHASE3_WAIT_TIME - 1 + period) / period;
LPC_EEPROM->WSTATE = WSTATE_PHASE1(phase1 - 1) | WSTATE_PHASE2(phase2 - 1)
| WSTATE_PHASE3(phase3 - 1);
LPC_EEPROM->AUTOPROG = AUTOPROG_MODE(AUTOPROG_OFF);
LPC_EEPROM->INTSTATCLR = INT_PROG_DONE;
LPC_EEPROM->INTENSET = INT_PROG_DONE;
if (config != NULL)
irqSetPriority(EEPROM_IRQ, config->priority);
irqEnable(EEPROM_IRQ);
return E_OK;
}
/*----------------------------------------------------------------------------*/
static void eepromDeinit(void *object __attribute__((unused)))
{
irqDisable(EEPROM_IRQ);
instance = NULL;
EepromBase->deinit(object);
}
/*----------------------------------------------------------------------------*/
static void eepromSetCallback(void *object, void (*callback)(void *),
void *argument)
{
struct Eeprom * const interface = object;
interface->callbackArgument = argument;
interface->callback = callback;
}
/*----------------------------------------------------------------------------*/
static enum Result eepromGetParam(void *object, int parameter, void *data)
{
struct Eeprom * const interface = object;
switch ((enum IfParameter)parameter)
{
case IF_POSITION:
*(uint32_t *)data = interface->position;
return E_OK;
case IF_SIZE:
*(uint32_t *)data = interface->base.size;
return E_OK;
default:
return E_INVALID;
}
}
/*----------------------------------------------------------------------------*/
static enum Result eepromSetParam(void *object, int parameter, const void *data)
{
struct Eeprom * const interface = object;
switch ((enum IfParameter)parameter)
{
case IF_BLOCKING:
interface->blocking = true;
return E_OK;
case IF_POSITION:
{
const uint32_t position = *(const uint32_t *)data;
if (isAddressValid(interface, position))
{
interface->position = position;
return E_OK;
}
else
return E_ADDRESS;
}
case IF_ZEROCOPY:
interface->blocking = false;
return E_OK;
default:
return E_INVALID;
}
}
/*----------------------------------------------------------------------------*/
static size_t eepromRead(void *object, void *buffer, size_t length)
{
struct Eeprom * const interface = object;
if (!isAddressValid(interface, interface->position + length))
return 0;
const uint32_t position = interface->position + interface->base.address;
memcpy(buffer, (const void *)position, length);
interface->position += length;
return length;
}
/*----------------------------------------------------------------------------*/
static size_t eepromWrite(void *object, const void *buffer, size_t length)
{
struct Eeprom * const interface = object;
/* Buffer size must be aligned along 4-byte boundary */
assert(length % sizeof(uint32_t) == 0);
if (!isAddressValid(interface, interface->position + length))
return 0;
interface->left = length >> 2;
interface->buffer = buffer;
interface->offset = interface->position + interface->base.address;
programNextChunk(interface);
if (interface->blocking)
{
while (interface->left)
barrier();
}
return length;
}
| 2.609375 | 3 |
2024-11-18T20:53:26.681795+00:00 | 2023-09-02T09:41:02 | ca37c25571f1553a73a5b2eeb3a139cbf7d4ff07 | {
"blob_id": "ca37c25571f1553a73a5b2eeb3a139cbf7d4ff07",
"branch_name": "refs/heads/master",
"committer_date": "2023-09-02T09:41:02",
"content_id": "260725f3b3b9cc62964e033f8ba589e40b70e95e",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "71c10a5a8073ee4bbff63a6611a82a58b92af5aa",
"extension": "h",
"filename": "Print.h",
"fork_events_count": 161,
"gha_created_at": "2013-07-04T09:29:15",
"gha_event_created_at": "2023-09-14T06:59:54",
"gha_language": "Haskell",
"gha_license_id": "NOASSERTION",
"github_id": 11172497,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2757,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/clash-ffi/tests/cbits/Print.h",
"provenance": "stackv2-0127.json.gz:67695",
"repo_name": "clash-lang/clash-compiler",
"revision_date": "2023-09-02T09:41:02",
"revision_id": "f645746b1ced95b8b784b9d84535e6402384e467",
"snapshot_id": "a469e17b388e77de90a1c061f88174305777e634",
"src_encoding": "UTF-8",
"star_events_count": 1351,
"url": "https://raw.githubusercontent.com/clash-lang/clash-compiler/f645746b1ced95b8b784b9d84535e6402384e467/clash-ffi/tests/cbits/Print.h",
"visit_date": "2023-09-04T07:45:33.065373"
} | stackv2 | #ifndef PRINT_H
#define PRINT_H
#include "vpi_user.h"
/* Prints a NUL terminated sequence of bytes to the shared pipe
* according to the Haskell representation of:
*
* 'Show [Int]'
*/
void print_bytes(PLI_BYTE8*);
/* Prints the diagnostic level to the shared pipe according to the
* Haskell representation of:
*
* 'Show Clash.FFI.VPI.Error.Level.ErrorLevel'
*/
void print_diagnostic_level(PLI_INT32);
/* Prints an VPI property to the shared pipe according to the Haskell
* representation of:
*
* 'Show Clash.FFI.VPI.Object.Property.Property'
*/
void print_property(PLI_INT32);
/* Prints a time type to the shared pipe according to the Haskell
* representation of:
*
* 'Show Clash.FFI.VPI.Object.Time.TimeType'
*/
void print_time_type(PLI_INT32);
/* Prints the type of an object to the shared pipe according to the
* Haskell representation of:
*
* 'Show Clash.FFI.VPI.Object.Type.ObjectType'
*/
void print_object_type(PLI_INT32);
/* Prints some value format to the shared pipe according to the
* Haskell representation of:
*
* 'Show Clash.FFI.VPI.Object.Value.Format.ValueFormat'
*/
void print_value_format(PLI_INT32);
/* Prints an object referene to the shared pipe according to the
* Haskell representations of:
*
* 'Show Clash.FFI.VPI.Callback.Callback'
* 'Show Clash.FFI.VPI.Iterator.Iterator'
* 'Show Clash.FFI.VPI.Module.Module'
* 'Show Clash.FFI.VPI.Net.Net'
* 'Show Clash.FFI.VPI.Object.Object'
* 'Show Clash.FFI.VPI.Parameter.Parameter'
* 'Show Clash.FFI.VPI.Port.Port'
* 'Show Clash.FFI.VPI.Reg.Reg'
*/
void print_object_ref(vpiHandle);
/* Prints an optional object referene to the shared pipe according to
* the Haskell representations of:
*
* 'Show (Maybe Clash.FFI.VPI.Callback.Callback)'
* 'Show (Maybe Clash.FFI.VPI.Iterator.Iterator)'
* 'Show (Maybe Clash.FFI.VPI.Module.Module)'
* 'Show (Maybe Clash.FFI.VPI.Net.Net)'
* 'Show (Maybe Clash.FFI.VPI.Object.Object)'
* 'Show (Maybe Clash.FFI.VPI.Parameter.Parameter)'
* 'Show (Maybe Clash.FFI.VPI.Port.Port)'
* 'Show (Maybe Clash.FFI.VPI.Reg.Reg)'
*/
void print_mobject(vpiHandle);
/* Prints a time reference to the shared pipe according to the Haskell
* representation of:
*
* 'Show Clash.FFI.VPI.Object.Time.Time'
*/
void print_time(p_vpi_time);
/* Prints some value to the shared pipe according to the Haskell
* representation of:
*
* 'Show Clash.FFI.VPI.Object.Value.Value'
*
* The second argument determines the size of the value.
*/
void print_value(p_vpi_value, int);
/* Prints a callback reason to the shared pipe according to the
* Haskell representation of:
*
* 'Show Clash.FFI.VPI.Callback.Reason.CallbackReason'
*/
void print_callback_reason(p_cb_data);
#endif
| 2.046875 | 2 |
2024-11-18T20:53:26.741733+00:00 | 2015-04-17T17:56:20 | 89e6f1993c7f28a7544d17f7affcb4ac4b2afa19 | {
"blob_id": "89e6f1993c7f28a7544d17f7affcb4ac4b2afa19",
"branch_name": "refs/heads/master",
"committer_date": "2015-04-17T17:56:20",
"content_id": "42602e7268859b943a5cdd74d09854e6ccee5301",
"detected_licenses": [
"ISC"
],
"directory_id": "66bdc05e3e7e0a2069cbf59a8dad1fdf7a52caef",
"extension": "c",
"filename": "vfopen.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 7389536,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3198,
"license": "ISC",
"license_type": "permissive",
"path": "/gcc/files/vfopen.c",
"provenance": "stackv2-0127.json.gz:67824",
"repo_name": "razzlefratz/MotleyTools",
"revision_date": "2015-04-17T17:56:20",
"revision_id": "3c69c574351ce6f4b7e687c13278d4b6cbb200f3",
"snapshot_id": "5e44f1315baa1be6fe5221916ccc834a96b59ca6",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/razzlefratz/MotleyTools/3c69c574351ce6f4b7e687c13278d4b6cbb200f3/gcc/files/vfopen.c",
"visit_date": "2020-05-19T05:01:58.992424"
} | stackv2 | /*===================================================================
*
* bool vfopen(char const *pathname);
*
* open the named file as stdout; rename it by appending a numeric
* file extension that serves as a file version number;
*
*. Motley Tools by Charles Maier
*: Published 1982-2005 by Charles Maier for personal use
*; Licensed under the Internet Software Consortium License
*
*--------------------------------------------------------------------*/
#ifndef VFOPEN_SOURCE
#define VFOPEN_SOURCE
#include <stdio.h>
#include <unistd.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include "../files/files.h"
#include "../tools/types.h"
#include "../tools/error.h"
bool vfopen (char const *filename)
{
struct stat loadstat;
struct stat savestat;
char loadname [FILENAME_MAX];
char savename [FILENAME_MAX];
unsigned bailout = 0;
unsigned version = 0;
unsigned maximum = 0;
char *extender;
makepath (loadname, getenv ("PWD"), filename);
makepath (savename, getenv ("PWD"), filename);
if (lstat (loadname, &loadstat))
{
error (bailout, errno, "Can't open %s", loadname);
return (false);
}
if (S_ISDIR (loadstat.st_mode))
{
error (bailout, 0, "Won't open %s: file is a folder", loadname);
return (false);
}
if (S_ISLNK (loadstat.st_mode))
{
error (bailout, 0, "Won't open %s: file is a symlink", loadname);
return (false);
}
if (S_ISBLK (loadstat.st_mode))
{
error (bailout, 0, "Won't open %s: file is a device", loadname);
return (false);
}
if (S_ISCHR (loadstat.st_mode))
{
error (bailout, 0, "Won't open %s: file is a device", loadname);
return (false);
}
if (S_ISFIFO (loadstat.st_mode))
{
error (bailout, 0, "Won't open %s: file is a fifo", loadname);
return (false);
}
if (S_ISSOCK (loadstat.st_mode))
{
error (bailout, 0, "Won't open %s: file is a socket", loadname);
return (false);
}
for (version = FILE_VER_MAX; version > 0; version /= 10)
{
maximum++;
}
for (extender = savename; *extender; extender++);
*extender++ = FILE_C_EXTENDER;
for (version = 1; version < FILE_VER_MAX; version++)
{
unsigned value = version;
unsigned digit = maximum;
for (extender [digit] = (char) (0); digit-- > 0; value /= 10)
{
extender [digit] = (value % 10) + '0';
}
if (lstat (savename, &savestat))
{
if (!freopen (loadname, "rb", stdin))
{
error (bailout, errno, "Can't open %s for input", loadname);
return (false);
}
if (rename (loadname, savename))
{
error (bailout, errno, "Can't rename %s as %s", loadname, savename);
return (false);
}
if (!freopen (loadname, "wb", stdout))
{
error (bailout, errno, "Can't open %s for output", loadname);
return (false);
}
if (chmod (loadname, loadstat.st_mode))
{
error (bailout, errno, "Can't preserve %s permissions", loadname);
return (false);
}
if (chown (loadname, loadstat.st_uid, loadstat.st_gid))
{
error (bailout, errno, "Can't preserve %s ownership", loadname);
return (false);
}
return (true);
}
}
error (bailout, 0, "Won't open %s: Too many file versions", loadname);
return (false);
}
#endif
| 2.34375 | 2 |
2024-11-18T20:53:26.908264+00:00 | 2021-01-31T08:03:05 | 1011e692772f4ab7870f70bdc19c1abe8a4068f8 | {
"blob_id": "1011e692772f4ab7870f70bdc19c1abe8a4068f8",
"branch_name": "refs/heads/main",
"committer_date": "2021-01-31T08:35:58",
"content_id": "c7775b54e4d96b01455efbc06123558e6db9663a",
"detected_licenses": [
"Apache-2.0",
"BSD-2-Clause"
],
"directory_id": "a6f5d608a22fb2e904c8e438d23694599d4cd8e1",
"extension": "h",
"filename": "stat.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": 1481,
"license": "Apache-2.0,BSD-2-Clause",
"license_type": "permissive",
"path": "/apps-src/apps/studio/android/adb/sysdeps/stat.h",
"provenance": "stackv2-0127.json.gz:68085",
"repo_name": "absir/Rose",
"revision_date": "2021-01-31T08:03:05",
"revision_id": "23a9f4307a27a3d4f2aceac30853d0ee69bc0f41",
"snapshot_id": "ec18ad5c5a8c9d24cb4af281fbd00a2efa7285fa",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/absir/Rose/23a9f4307a27a3d4f2aceac30853d0ee69bc0f41/apps-src/apps/studio/android/adb/sysdeps/stat.h",
"visit_date": "2023-02-24T20:00:47.442495"
} | stackv2 | /*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#if defined(_WIN32)
// stat is broken on Win32: stat on a path with a trailing slash or backslash will always fail with
// ENOENT.
int adb_stat(const char* path, struct stat* buf);
// We later define a macro mapping 'stat' to 'adb_stat'. This causes:
// struct stat s;
// stat(filename, &s);
// To turn into the following:
// struct adb_stat s;
// adb_stat(filename, &s);
// To get this to work, we need to make 'struct adb_stat' the same as
// 'struct stat'. Note that this definition of 'struct adb_stat' uses the
// *current* macro definition of stat, so it may actually be inheriting from
// struct _stat32i64 (or some other remapping).
// struct adb_stat : public stat {};
// #define adb_stat stat
// Windows doesn't have lstat.
// #define adb_stat lstat
#endif
| 2 | 2 |
2024-11-18T20:53:26.994018+00:00 | 2015-09-06T06:51:27 | 671e0850fbbf4bb378a91b751ee21ca6baba1288 | {
"blob_id": "671e0850fbbf4bb378a91b751ee21ca6baba1288",
"branch_name": "refs/heads/master",
"committer_date": "2015-09-06T06:51:27",
"content_id": "ddce74d11b93aca9fbe209164833a5257879883e",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "4f6af3d4f511645f0c6f4d07454db2420c86a579",
"extension": "c",
"filename": "app_serial.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 36065172,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5423,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/aio_stm_app3rd/embedded/apps/app_serial.c",
"provenance": "stackv2-0127.json.gz:68213",
"repo_name": "webom2008/freeRTOS.project",
"revision_date": "2015-09-06T06:51:27",
"revision_id": "5318a057d2aa301a7f16ee6502504c768402ad13",
"snapshot_id": "2ea8b91395bc724c4524eb09ef15cc83a4b44b4e",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/webom2008/freeRTOS.project/5318a057d2aa301a7f16ee6502504c768402ad13/aio_stm_app3rd/embedded/apps/app_serial.c",
"visit_date": "2021-01-10T01:38:43.962367"
} | stackv2 | /******************************************************************************
Copyright (C), 2005-2014, CVTE.
******************************************************************************
File Name : app_serial.c
Version : Initial Draft
Author : qiuweibo
Created : 2015/4/8
Last Modified :
Description : serial app
Function List :
History :
1.Date : 2015/4/8
Author : qiuweibo
Modification: Created file
******************************************************************************/
#include "includes.h"
#include "driver_uart.h"
/*----------------------------------------------*
* external variables *
*----------------------------------------------*/
/*----------------------------------------------*
* external routine prototypes *
*----------------------------------------------*/
/*----------------------------------------------*
* constants *
*----------------------------------------------*/
/*----------------------------------------------*
* macros *
*----------------------------------------------*/
#define SERIAL_BOAUDRATE ( (unsigned long) 230400 )
#define comSTACK_SIZE configMINIMAL_STACK_SIZE
/*----------------------------------------------*
* project-wide global variables *
*----------------------------------------------*/
/*----------------------------------------------*
* internal variables *
*----------------------------------------------*/
static xComPortHandle xPort = NULL;/* Handle to the com port used by both tasks. */
/*----------------------------------------------*
* internal routine prototypes *
*----------------------------------------------*/
/*----------------------------------------------*
* routines' implementations *
*----------------------------------------------*/
#ifdef __COM_TEST_PRINTF__
/*****************************************************************************
Prototype : vComTxTask
Description : ComTxTask
Input : void *pvParameters
Output : None
Return Value : static
Calls :
Called By :
History :
1.Date : 2015/4/9
Author : qiuweibo
Modification : Created function
*****************************************************************************/
static void vComTxTask( void *pvParameters )
{
const char pBuf[30] = "\r\n>>vComTxTask running";
unsigned char i, nLen;
/* Just to stop compiler warnings. */
( void ) pvParameters;
nLen = strlen(pBuf);
for( ;; )
{
for (i = 0; i < nLen; i++)
{
xSerialPutChar( xPort, pBuf[i], comNO_BLOCK );
}
vTaskDelay(500 / portTICK_PERIOD_MS); //delay 1s
}
}
/*****************************************************************************
Prototype : vComRxTask
Description : ComRxTask
Input : void *pvParameters
Output : None
Return Value : static
Calls :
Called By :
History :
1.Date : 2015/4/9
Author : qiuweibo
Modification : Created function
*****************************************************************************/
static void vComRxTask(void *pvParameters )
{
signed char cByteRxed;
/* Just to stop compiler warnings. */
( void ) pvParameters;
for( ;; )
{
/* Block on the queue that contains received bytes until a byte is
available. */
if( xSerialGetChar( xPort, &cByteRxed, comRX_BLOCK_TIME ) )
{
printf("\r\nvComRxTask input:%c",cByteRxed);
}
else // timeout
{
printf("\r\nvComRxTask timeout");
}
}
}
#endif
/*****************************************************************************
Prototype : app_serial_init
Description : init for App
Input : void
Output : None
Return Value :
Calls :
Called By :
History :
1.Date : 2015/4/9
Author : qiuweibo
Modification : Created function
*****************************************************************************/
int app_serial_init(void)
{
xSerialPortInitMinimal( SERIAL_BOAUDRATE);
return 0;
}
/*****************************************************************************
Prototype : app_serial_start
Description : start task
Input : void
Output : None
Return Value :
Calls :
Called By :
History :
1.Date : 2015/4/9
Author : qiuweibo
Modification : Created function
*****************************************************************************/
int app_serial_start(void)
{
#ifdef __COM_TEST_PRINTF__
xTaskCreate( vComTxTask,
"COMTx",
comSTACK_SIZE,
NULL,
SERIAL_TEST_PRIORITY,
( TaskHandle_t * ) NULL );
xTaskCreate( vComRxTask, "COMRx",
comSTACK_SIZE,
NULL,
SERIAL_TEST_PRIORITY,
( TaskHandle_t * ) NULL );
#endif
return 0;
}
| 2.109375 | 2 |
2024-11-18T20:53:27.045379+00:00 | 2014-10-14T07:36:06 | bdb79e786425c67afe61691a0a877de124555b6c | {
"blob_id": "bdb79e786425c67afe61691a0a877de124555b6c",
"branch_name": "refs/heads/master",
"committer_date": "2014-10-14T07:36:06",
"content_id": "457869cee1253f3fcdc9829002b5f9af854dafed",
"detected_licenses": [
"MIT"
],
"directory_id": "55900b39823f0aa980154cd35471aaaafe610c41",
"extension": "c",
"filename": "lock_ellision.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 16136939,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 7306,
"license": "MIT",
"license_type": "permissive",
"path": "/implementation/solutions/basictests/source_gen/lockelision/notshared/recursive/lock_ellision.c",
"provenance": "stackv2-0127.json.gz:68342",
"repo_name": "aloifolia/ParallelMbeddr",
"revision_date": "2014-10-14T07:36:06",
"revision_id": "58474bbcb215433e2a3f97f626ea2b5834531ecf",
"snapshot_id": "85a9bfec3f8bc13b70c9c6393da26bb5159929bb",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/aloifolia/ParallelMbeddr/58474bbcb215433e2a3f97f626ea2b5834531ecf/implementation/solutions/basictests/source_gen/lockelision/notshared/recursive/lock_ellision.c",
"visit_date": "2020-05-19T17:19:47.717082"
} | stackv2 | #include "lock_ellision.h"
#include "GenericTaskDeclarations.h"
#include "GenericSharedDeclarations.h"
#include "GenericSyncDeclarations.h"
#include <pthread.h>
#include <stdlib.h>
typedef struct lock_ellision_Args_a6a1 lock_ellision_Args_a6a1_t;
struct lock_ellision_Args_a6a1 {
GenericSharedDeclarations_SharedOf_int32_0_t* var1Pointer;
};
typedef struct lock_ellision_Args_a7a2 lock_ellision_Args_a7a2_t;
struct lock_ellision_Args_a7a2 {
GenericSharedDeclarations_SharedOf_int32_0_t* zPointer;
};
typedef struct lock_ellision_Args_a7a3 lock_ellision_Args_a7a3_t;
struct lock_ellision_Args_a7a3 {
GenericSharedDeclarations_SharedOf_int32_0_t* zPointer;
};
static void lock_ellision_caller(void);
static void lock_ellision_callee(GenericSharedDeclarations_SharedOf_int32_0_t* xPointer);
static void lock_ellision_callee_0(GenericSharedDeclarations_SharedOf_int32_0_t* xPointer);
static void* lock_ellision_parFun_a6a1(void* voidArgs);
static void* lock_ellision_parFun_a7a2(void* voidArgs);
static void* lock_ellision_parFun_a7a3(void* voidArgs);
static inline GenericTaskDeclarations_Task_t lock_ellision_taskInit_a6a1(GenericSharedDeclarations_SharedOf_int32_0_t* var1Pointer);
static inline GenericTaskDeclarations_Task_t lock_ellision_taskInit_a7a2(GenericSharedDeclarations_SharedOf_int32_0_t* zPointer);
static inline GenericTaskDeclarations_Task_t lock_ellision_taskInit_a7a3(GenericSharedDeclarations_SharedOf_int32_0_t* zPointer);
int32_t main(int32_t argc, char* argv[])
{
pthread_mutexattr_init(&GenericSharedDeclarations_mutexAttribute_0);
pthread_mutexattr_settype(&GenericSharedDeclarations_mutexAttribute_0,PTHREAD_MUTEX_RECURSIVE);
lock_ellision_caller();
return 0;
}
static void lock_ellision_caller(void)
{
GenericSharedDeclarations_SharedOf_int32_0_t var1;
pthread_mutex_init(&var1.mutex,&GenericSharedDeclarations_mutexAttribute_0);
GenericSharedDeclarations_SharedOf_int32_0_t var2;
pthread_mutex_init(&var2.mutex,&GenericSharedDeclarations_mutexAttribute_0);
GenericSharedDeclarations_SharedOf_int32_0_t* var1Pointer = &var1;
lock_ellision_callee(&var1);
/*
* since var2 is never shared, an optimized callee variant will be called
*/
lock_ellision_callee_0(&var2);
lock_ellision_taskInit_a6a1(var1Pointer);
pthread_mutex_destroy(&var1.mutex);
pthread_mutex_destroy(&var2.mutex);
}
static void lock_ellision_callee(GenericSharedDeclarations_SharedOf_int32_0_t* xPointer)
{
GenericSharedDeclarations_SharedOf_int32_0_t y;
pthread_mutex_init(&y.mutex,&GenericSharedDeclarations_mutexAttribute_0);
GenericSharedDeclarations_SharedOf_int32_0_t* yPointer = &y;
GenericSharedDeclarations_SharedOf_int32_0_t z;
pthread_mutex_init(&z.mutex,&GenericSharedDeclarations_mutexAttribute_0);
GenericSharedDeclarations_SharedOf_int32_0_t* zPointer = &z;
/*
* z is shared (see below), x is shared for the calls callee(&var1) and callee(zPointer), y is not shared
*/
{
GenericSharedDeclarations_SharedOf_int32_0_t* myXPointer = xPointer;
GenericSharedDeclarations_SharedOf_int32_0_t* myYPointer = yPointer;
GenericSharedDeclarations_SharedOf_int32_0_t* myZPointer = zPointer;
GenericSyncDeclarations_startSyncFor2Mutexes(&(myXPointer)->mutex, &(myZPointer)->mutex);
{
myXPointer->value = 1;
myYPointer->value = 2;
myZPointer->value = 3;
}
GenericSyncDeclarations_stopSyncFor2Mutexes(&(myXPointer)->mutex, &(myZPointer)->mutex);
}
/*
* z, and with it x in the follwing calls, is shared with another task => z must be synced, but x only for the second following call
*/
lock_ellision_taskInit_a7a2(zPointer);
lock_ellision_callee_0(yPointer);
lock_ellision_callee(zPointer);
pthread_mutex_destroy(&y.mutex);
pthread_mutex_destroy(&z.mutex);
}
static void lock_ellision_callee_0(GenericSharedDeclarations_SharedOf_int32_0_t* xPointer)
{
GenericSharedDeclarations_SharedOf_int32_0_t y;
pthread_mutex_init(&y.mutex,&GenericSharedDeclarations_mutexAttribute_0);
GenericSharedDeclarations_SharedOf_int32_0_t* yPointer = &y;
GenericSharedDeclarations_SharedOf_int32_0_t z;
pthread_mutex_init(&z.mutex,&GenericSharedDeclarations_mutexAttribute_0);
GenericSharedDeclarations_SharedOf_int32_0_t* zPointer = &z;
/*
* z is shared (see below), x is shared for the calls callee(&var1) and callee(zPointer), y is not shared
*/
{
GenericSharedDeclarations_SharedOf_int32_0_t* myXPointer = xPointer;
GenericSharedDeclarations_SharedOf_int32_0_t* myYPointer = yPointer;
GenericSharedDeclarations_SharedOf_int32_0_t* myZPointer = zPointer;
{
myXPointer->value = 1;
myYPointer->value = 2;
GenericSyncDeclarations_startSyncFor1Mutex(&(myZPointer)->mutex);
{
myZPointer->value = 3;
}
GenericSyncDeclarations_stopSyncFor1Mutex(&(myZPointer)->mutex);
}
}
/*
* z, and with it x in the follwing calls, is shared with another task => z must be synced, but x only for the second following call
*/
lock_ellision_taskInit_a7a3(zPointer);
lock_ellision_callee_0(yPointer);
lock_ellision_callee(zPointer);
pthread_mutex_destroy(&y.mutex);
pthread_mutex_destroy(&z.mutex);
}
static void* lock_ellision_parFun_a6a1(void* voidArgs)
{
GenericSharedDeclarations_SharedOf_int32_0_t** result = malloc(sizeof(GenericSharedDeclarations_SharedOf_int32_0_t*));
lock_ellision_Args_a6a1_t* args = ((lock_ellision_Args_a6a1_t*)(voidArgs));
*result = (args)->var1Pointer;
free(voidArgs);
return result;
}
static void* lock_ellision_parFun_a7a2(void* voidArgs)
{
GenericSharedDeclarations_SharedOf_int32_0_t** result = malloc(sizeof(GenericSharedDeclarations_SharedOf_int32_0_t*));
lock_ellision_Args_a7a2_t* args = ((lock_ellision_Args_a7a2_t*)(voidArgs));
*result = (args)->zPointer;
free(voidArgs);
return result;
}
static void* lock_ellision_parFun_a7a3(void* voidArgs)
{
GenericSharedDeclarations_SharedOf_int32_0_t** result = malloc(sizeof(GenericSharedDeclarations_SharedOf_int32_0_t*));
lock_ellision_Args_a7a3_t* args = ((lock_ellision_Args_a7a3_t*)(voidArgs));
*result = (args)->zPointer;
free(voidArgs);
return result;
}
static inline GenericTaskDeclarations_Task_t lock_ellision_taskInit_a6a1(GenericSharedDeclarations_SharedOf_int32_0_t* var1Pointer)
{
lock_ellision_Args_a6a1_t* args_a6a1 = malloc(sizeof(lock_ellision_Args_a6a1_t));
args_a6a1->var1Pointer = var1Pointer;
return (GenericTaskDeclarations_Task_t){args_a6a1,&lock_ellision_parFun_a6a1,sizeof(lock_ellision_Args_a6a1_t)};
}
static inline GenericTaskDeclarations_Task_t lock_ellision_taskInit_a7a2(GenericSharedDeclarations_SharedOf_int32_0_t* zPointer)
{
lock_ellision_Args_a7a2_t* args_a7a2 = malloc(sizeof(lock_ellision_Args_a7a2_t));
args_a7a2->zPointer = zPointer;
return (GenericTaskDeclarations_Task_t){args_a7a2,&lock_ellision_parFun_a7a2,sizeof(lock_ellision_Args_a7a2_t)};
}
static inline GenericTaskDeclarations_Task_t lock_ellision_taskInit_a7a3(GenericSharedDeclarations_SharedOf_int32_0_t* zPointer)
{
lock_ellision_Args_a7a3_t* args_a7a3 = malloc(sizeof(lock_ellision_Args_a7a3_t));
args_a7a3->zPointer = zPointer;
return (GenericTaskDeclarations_Task_t){args_a7a3,&lock_ellision_parFun_a7a3,sizeof(lock_ellision_Args_a7a3_t)};
}
| 2.421875 | 2 |
2024-11-18T20:53:27.110037+00:00 | 2009-05-12T20:11:07 | 2dc5a00f8d50083224aeab5e87c28f0b73ec34a7 | {
"blob_id": "2dc5a00f8d50083224aeab5e87c28f0b73ec34a7",
"branch_name": "refs/heads/master",
"committer_date": "2009-05-12T20:11:07",
"content_id": "f2cb7c2f5aa1ebbcbe09fb09b726935fd8c6b9cc",
"detected_licenses": [
"MIT"
],
"directory_id": "876daada5152e855cdb24f3ea1c345a80064db35",
"extension": "h",
"filename": "buffer.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": 1998,
"license": "MIT",
"license_type": "permissive",
"path": "/src/buffer.h",
"provenance": "stackv2-0127.json.gz:68473",
"repo_name": "xxyyboy/fcgiev",
"revision_date": "2009-05-12T20:11:07",
"revision_id": "d4c83f4a59d4237a07a94d8f2b0fb3418067f889",
"snapshot_id": "3b0556adf0942148ac99038e9e6c69881f206f1f",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/xxyyboy/fcgiev/d4c83f4a59d4237a07a94d8f2b0fb3418067f889/src/buffer.h",
"visit_date": "2020-04-19T17:33:18.608425"
} | stackv2 | #ifndef _FCGIEV_BUFFER_H_
#define _FCGIEV_BUFFER_H_
#include <stdint.h>
#include <string.h>
#include <sys/types.h>
typedef struct {
u_char *buffer;
u_char *orig_buffer;
size_t misalign;
size_t totallen;
size_t off;
} buf_t;
#define BUF_LENGTH(x) (x)->off
#define BUF_DATA(x) (x)->buffer
#define BUF_INPUT(x) (x)->input
#define BUF_OUTPUT(x) (x)->output
inline static buf_t *buf_new(void) {
buf_t *buffer;
buffer = calloc(1, sizeof(buf_t));
return buffer;
}
inline static void buf_free(buf_t *b) {
if (b->orig_buffer != NULL)
free(b->orig_buffer);
free(b);
}
inline static void buf_align(buf_t *buf) {
memmove(buf->orig_buffer, buf->buffer, buf->off);
buf->buffer = buf->orig_buffer;
buf->misalign = 0;
}
static void buf_reserve(buf_t *buf, size_t size) {
size_t need = buf->misalign + buf->off + size;
/* If we can fit all the data, then we don't have to do anything */
if (buf->totallen >= need)
return;
/*
* If the misalignment fulfills our data needs, we just force an
* alignment to happen. Afterwards, we have enough space.
*/
if (buf->misalign >= size) {
buf_align(buf);
}
else {
void *newbuf;
size_t length = buf->totallen;
if (length < 256)
length = 256;
while (length < need)
length <<= 1;
if (buf->orig_buffer != buf->buffer)
buf_align(buf);
AN(newbuf = realloc(buf->buffer, length));
buf->orig_buffer = buf->buffer = newbuf;
buf->totallen = length;
}
}
inline static void buf_append(buf_t *buf, const void *data, size_t len) {
if (buf->totallen < buf->misalign + buf->off + len)
buf_reserve(buf, len);
memcpy(buf->buffer + buf->off, data, len);
buf->off += len;
}
inline static void buf_drain(buf_t *buf, size_t len) {
if (len >= buf->off) {
buf->off = 0;
buf->buffer = buf->orig_buffer;
buf->misalign = 0;
return;
}
buf->buffer += len;
buf->misalign += len;
buf->off -= len;
}
#endif
| 2.90625 | 3 |
2024-11-18T20:53:27.433975+00:00 | 2018-02-22T18:50:15 | a206011249a33bce70d6342d0dba1b3784498cb5 | {
"blob_id": "a206011249a33bce70d6342d0dba1b3784498cb5",
"branch_name": "refs/heads/master",
"committer_date": "2018-02-22T18:50:15",
"content_id": "eb87eef3f12c1accbb36c470ea216d896e9f84fa",
"detected_licenses": [
"MIT"
],
"directory_id": "0fba08cba1cfa9b493f5618e7ece0d02e89df725",
"extension": "c",
"filename": "eval_register.c",
"fork_events_count": 1,
"gha_created_at": "2015-10-31T23:32:13",
"gha_event_created_at": "2018-02-22T18:50:16",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 45321878,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 21102,
"license": "MIT",
"license_type": "permissive",
"path": "/src/TotemScript/eval_register.c",
"provenance": "stackv2-0127.json.gz:68605",
"repo_name": "tdsmale/TotemScript",
"revision_date": "2018-02-22T18:50:15",
"revision_id": "5061a61bf1b9250b2e1053d101e6a7178b9b20e5",
"snapshot_id": "4fc13556dd4c78c0272f7c26f5c35568656e6413",
"src_encoding": "UTF-8",
"star_events_count": 7,
"url": "https://raw.githubusercontent.com/tdsmale/TotemScript/5061a61bf1b9250b2e1053d101e6a7178b9b20e5/src/TotemScript/eval_register.c",
"visit_date": "2020-04-05T14:36:10.746233"
} | stackv2 | //
// eval_register.c
// TotemScript
//
// Created by Timothy Smale on 05/06/2016
// Copyright (c) 2016 Timothy Smale. All rights reserved.
//
#include <TotemScript/eval.h>
#include <TotemScript/base.h>
#include <TotemScript/exec.h>
#include <string.h>
totemEvalStatus totemRegisterListPrototype_AddRegister(totemRegisterListPrototype *list, totemOperandRegisterPrototype *operand)
{
totemOperandXUnsigned index = 0;
totemRegisterPrototype *reg = NULL;
//totemBool fromFreeList = totemBool_False;
size_t freelistSize = totemMemoryBuffer_GetNumObjects(&list->RegisterFreeList);
size_t numRegisters = totemMemoryBuffer_GetNumObjects(&list->Registers);
if (freelistSize > 0)
{
totemOperandXUnsigned *indexPtr = totemMemoryBuffer_Top(&list->RegisterFreeList);
index = *indexPtr;
totemMemoryBuffer_Pop(&list->RegisterFreeList, 1);
reg = totemMemoryBuffer_Get(&list->Registers, index);
//fromFreeList = totemBool_True;
}
else
{
size_t max = list->ScopeType == totemOperandType_GlobalRegister ? TOTEM_MAX_GLOBAL_REGISTERS : TOTEM_MAX_LOCAL_REGISTERS;
if (numRegisters >= max)
{
return totemEvalStatus_Break(totemEvalStatus_TooManyRegisters);
}
index = (totemOperandXUnsigned)totemMemoryBuffer_GetNumObjects(&list->Registers);
reg = totemMemoryBuffer_Secure(&list->Registers, 1);
if (!reg)
{
return totemEvalStatus_Break(totemEvalStatus_OutOfMemory);
}
}
reg->Int = 0;
reg->RefCount = 1;
reg->GlobalCache = 0;
reg->DataType = totemPublicDataType_Null;
reg->Flags = totemRegisterPrototypeFlag_IsTemporary | totemRegisterPrototypeFlag_IsUsed;
operand->RegisterIndex = index;
operand->RegisterScopeType = list->ScopeType;
return totemEvalStatus_Success;
}
totemEvalStatus totemRegisterListPrototype_FreeRegister(totemRegisterListPrototype *list, totemOperandRegisterPrototype *operand)
{
totem_assert(list->ScopeType == operand->RegisterScopeType);
totemRegisterPrototype *reg = totemMemoryBuffer_Get(&list->Registers, operand->RegisterIndex);
if (reg->Flags != totemRegisterPrototypeFlag_None)
{
if (!totemMemoryBuffer_Insert(&list->RegisterFreeList, &operand->RegisterIndex, 1))
{
return totemEvalStatus_Break(totemEvalStatus_OutOfMemory);
}
reg->Flags = totemRegisterPrototypeFlag_None;
}
return totemEvalStatus_Success;
}
totemBool totemRegisterListPrototype_UnsetRegisterFlags(totemRegisterListPrototype *list, totemOperandXUnsigned index, totemRegisterPrototypeFlag flags)
{
totemRegisterPrototype *reg = totemMemoryBuffer_Get(&list->Registers, index);
if (!reg || !TOTEM_HASBITS(reg->Flags, totemRegisterPrototypeFlag_IsUsed))
{
return totemBool_False;
}
reg->Flags &= ~flags;
return totemBool_True;
}
totemBool totemRegisterListPrototype_SetRegisterFlags(totemRegisterListPrototype *list, totemOperandXUnsigned index, totemRegisterPrototypeFlag flags)
{
totemRegisterPrototype *reg = totemMemoryBuffer_Get(&list->Registers, index);
if (!reg || !TOTEM_HASBITS(reg->Flags, totemRegisterPrototypeFlag_IsUsed))
{
return totemBool_False;
}
reg->Flags |= flags;
return totemBool_True;
}
totemBool totemRegisterListPrototype_GetRegisterFlags(totemRegisterListPrototype *list, totemOperandXUnsigned index, totemRegisterPrototypeFlag *flags)
{
totemRegisterPrototype *reg = totemMemoryBuffer_Get(&list->Registers, index);
if (!reg || !TOTEM_HASBITS(reg->Flags, totemRegisterPrototypeFlag_IsUsed))
{
return totemBool_False;
}
*flags = reg->Flags;
return totemBool_True;
}
totemBool totemRegisterListPrototype_GetRegisterType(totemRegisterListPrototype *list, totemOperandXUnsigned index, totemPublicDataType *type)
{
totemRegisterPrototype *reg = totemMemoryBuffer_Get(&list->Registers, index);
if (!reg || !TOTEM_HASBITS(reg->Flags, totemRegisterPrototypeFlag_IsUsed))
{
return totemBool_False;
}
*type = reg->DataType;
return totemBool_True;
}
totemBool totemRegisterListPrototype_SetRegisterType(totemRegisterListPrototype *list, totemOperandXUnsigned index, totemPublicDataType type)
{
totemRegisterPrototype *reg = totemMemoryBuffer_Get(&list->Registers, index);
if (!reg || !TOTEM_HASBITS(reg->Flags, totemRegisterPrototypeFlag_IsUsed))
{
return totemBool_False;
}
reg->DataType = type;
return totemBool_True;
}
totemBool totemRegisterListPrototype_DecRegisterRefCount(totemRegisterListPrototype *list, totemOperandXUnsigned index, size_t *countOut)
{
totemRegisterPrototype *reg = totemMemoryBuffer_Get(&list->Registers, index);
if (!reg || !TOTEM_HASBITS(reg->Flags, totemRegisterPrototypeFlag_IsUsed))
{
return totemBool_False;
}
if (reg->RefCount > 0)
{
reg->RefCount--;
}
if (countOut)
{
*countOut = reg->RefCount;
}
return totemBool_True;
}
totemBool totemRegisterListPrototype_IncRegisterRefCount(totemRegisterListPrototype *list, totemOperandXUnsigned index, size_t *countOut)
{
totemRegisterPrototype *reg = totemMemoryBuffer_Get(&list->Registers, index);
if (!reg || !TOTEM_HASBITS(reg->Flags, totemRegisterPrototypeFlag_IsUsed))
{
return totemBool_False;
}
reg->RefCount++;
if (countOut)
{
*countOut = reg->RefCount;
}
return totemBool_True;
}
totemBool totemRegisterListPrototype_GetRegisterRefCount(totemRegisterListPrototype *list, totemOperandXUnsigned index, size_t *countOut)
{
totemRegisterPrototype *reg = totemMemoryBuffer_Get(&list->Registers, index);
if (!reg || !TOTEM_HASBITS(reg->Flags, totemRegisterPrototypeFlag_IsUsed))
{
return totemBool_False;
}
if (countOut)
{
*countOut = reg->RefCount;
}
return totemBool_True;
}
totemBool totemRegisterListPrototype_SetRegisterGlobalCache(totemRegisterListPrototype *list, totemOperandXUnsigned index, totemOperandXUnsigned assoc)
{
totemRegisterPrototype *reg = totemMemoryBuffer_Get(&list->Registers, index);
if (!reg || !TOTEM_HASBITS(reg->Flags, totemRegisterPrototypeFlag_IsUsed))
{
return totemBool_False;
}
reg->GlobalCache = assoc;
return totemBool_True;
}
totemBool totemRegisterListPrototype_GetRegisterGlobalCache(totemRegisterListPrototype *list, totemOperandXUnsigned index, totemOperandXUnsigned *assoc)
{
totemRegisterPrototype *reg = totemMemoryBuffer_Get(&list->Registers, index);
if (!reg || !TOTEM_HASBITS(reg->Flags, totemRegisterPrototypeFlag_IsUsed))
{
return totemBool_False;
}
*assoc = reg->GlobalCache;
return totemBool_True;
}
totemEvalStatus totemRegisterListPrototype_AddType(totemRegisterListPrototype *list, totemPublicDataType type, totemOperandRegisterPrototype *op)
{
if (type >= totemPublicDataType_Max)
{
return totemEvalStatus_Break(totemEvalStatus_InvalidDataType);
}
if (list->HasDataType[type])
{
op->RegisterIndex = list->DataTypes[type];
op->RegisterScopeType = list->ScopeType;
totemRegisterListPrototype_IncRegisterRefCount(list, op->RegisterIndex, NULL);
return totemEvalStatus_Success;
}
TOTEM_EVAL_CHECKRETURN(totemRegisterListPrototype_AddRegister(list, op));
totemRegisterPrototype *reg = totemMemoryBuffer_Get(&list->Registers, op->RegisterIndex);
reg->DataType = totemPublicDataType_Type;
reg->TypeValue = type;
list->DataTypes[type] = op->RegisterIndex;
list->HasDataType[type] = totemBool_True;
TOTEM_SETBITS(reg->Flags, totemRegisterPrototypeFlag_IsValue);
TOTEM_UNSETBITS(reg->Flags, totemRegisterPrototypeFlag_IsTemporary);
return totemEvalStatus_Success;
}
totemEvalStatus totemRegisterListPrototype_AddStringConstant(totemRegisterListPrototype *list, totemString *str, totemOperandRegisterPrototype *operand)
{
totemHashMapEntry *searchResult = totemHashMap_Find(&list->Strings, str->Value, str->Length);
totemRegisterPrototype *reg = NULL;
if (searchResult != NULL)
{
operand->RegisterIndex = (totemOperandXUnsigned)searchResult->Value;
operand->RegisterScopeType = list->ScopeType;
totemRegisterListPrototype_IncRegisterRefCount(list, operand->RegisterIndex, NULL);
}
else
{
totemEvalStatus status = totemRegisterListPrototype_AddRegister(list, operand);
if (status != totemEvalStatus_Success)
{
return status;
}
reg = (totemRegisterPrototype*)totemMemoryBuffer_Get(&list->Registers, operand->RegisterIndex);
reg->DataType = totemPublicDataType_String;
reg->String = str;
TOTEM_SETBITS(reg->Flags, totemRegisterPrototypeFlag_IsValue);
TOTEM_UNSETBITS(reg->Flags, totemRegisterPrototypeFlag_IsTemporary);
if (!totemHashMap_Insert(&list->Strings, str->Value, str->Length, operand->RegisterIndex))
{
return totemEvalStatus_Break(totemEvalStatus_OutOfMemory);
}
}
return totemEvalStatus_Success;
}
totemBool totemRegisterListPrototype_GetIdentifier(totemRegisterListPrototype *list, totemString *name, totemOperandRegisterPrototype *operand, totemBool currentOnly)
{
for (totemRegisterListPrototypeScope *scope = list->Scope;
scope;
scope = scope->Prev)
{
totemHashMapEntry *searchResult = totemHashMap_Find(&scope->Identifiers, name->Value, name->Length);
if (searchResult != NULL)
{
operand->RegisterIndex = (totemOperandXUnsigned)searchResult->Value;
operand->RegisterScopeType = list->ScopeType;
totemRegisterListPrototype_IncRegisterRefCount(list, operand->RegisterIndex, NULL);
return totemBool_True;
}
if (currentOnly)
{
break;
}
}
return totemBool_False;
}
totemBool totemRegisterListPrototype_GetVariable(totemRegisterListPrototype *list, totemString *name, totemOperandRegisterPrototype *operand, totemBool currentOnly)
{
if (totemRegisterListPrototype_GetIdentifier(list, name, operand, currentOnly))
{
totemRegisterPrototypeFlag flags = totemRegisterPrototypeFlag_None;
totemRegisterListPrototype_GetRegisterFlags(list, operand->RegisterIndex, &flags);
return TOTEM_HASBITS(flags, totemRegisterPrototypeFlag_IsVariable);
}
return totemBool_False;
}
totemEvalStatus totemRegisterListPrototype_AddVariable(totemRegisterListPrototype *list, totemString *name, totemOperandRegisterPrototype *prototype)
{
totemEvalStatus status = totemRegisterListPrototype_AddRegister(list, prototype);
if (status != totemEvalStatus_Success)
{
return status;
}
if (!totemHashMap_Insert(&list->Scope->Identifiers, name->Value, name->Length, prototype->RegisterIndex))
{
return totemEvalStatus_Break(totemEvalStatus_OutOfMemory);
}
totemRegisterPrototype *reg = totemMemoryBuffer_Get(&list->Registers, prototype->RegisterIndex);
TOTEM_SETBITS(reg->Flags, totemRegisterPrototypeFlag_IsVariable);
TOTEM_UNSETBITS(reg->Flags, totemRegisterPrototypeFlag_IsTemporary);
return totemEvalStatus_Success;
}
totemEvalStatus totemRegisterListPrototype_AddNull(totemRegisterListPrototype *list, totemOperandRegisterPrototype *op)
{
if (list->HasNull)
{
op->RegisterIndex = list->Null;
op->RegisterScopeType = list->ScopeType;
return totemEvalStatus_Success;
}
totemEvalStatus status = totemRegisterListPrototype_AddRegister(list, op);
if (status != totemEvalStatus_Success)
{
return status;
}
totemRegisterPrototype *reg = (totemRegisterPrototype*)totemMemoryBuffer_Get(&list->Registers, op->RegisterIndex);
TOTEM_SETBITS(reg->Flags, totemRegisterPrototypeFlag_IsValue);
TOTEM_UNSETBITS(reg->Flags, totemRegisterPrototypeFlag_IsTemporary);
reg->DataType = totemPublicDataType_Null;
list->Null = op->RegisterIndex;
list->HasNull = totemBool_True;
return totemEvalStatus_Success;
}
totemEvalStatus totemRegisterListPrototype_AddBoolean(totemRegisterListPrototype *list, totemBool val, totemOperandRegisterPrototype *op)
{
val = val != totemBool_False;
if (list->HasBoolean[val])
{
op->RegisterIndex = list->Boolean[val];
op->RegisterScopeType = list->ScopeType;
return totemEvalStatus_Success;
}
totemEvalStatus status = totemRegisterListPrototype_AddRegister(list, op);
if (status != totemEvalStatus_Success)
{
return status;
}
totemRegisterPrototype *reg = (totemRegisterPrototype*)totemMemoryBuffer_Get(&list->Registers, op->RegisterIndex);
TOTEM_SETBITS(reg->Flags, totemRegisterPrototypeFlag_IsValue);
TOTEM_UNSETBITS(reg->Flags, totemRegisterPrototypeFlag_IsTemporary);
reg->DataType = totemPublicDataType_Boolean;
reg->Boolean = val;
list->Boolean[val] = op->RegisterIndex;
list->HasBoolean[val] = totemBool_True;
return totemEvalStatus_Success;
}
totemEvalStatus totemRegisterListPrototype_AddNumberConstant(totemRegisterListPrototype *list, totemString *number, totemOperandRegisterPrototype *operand)
{
totemHashMapEntry *searchResult = totemHashMap_Find(&list->Numbers, number->Value, number->Length);
if (searchResult != NULL)
{
operand->RegisterIndex = (totemOperandXUnsigned)searchResult->Value;
operand->RegisterScopeType = list->ScopeType;
totemRegisterListPrototype_IncRegisterRefCount(list, operand->RegisterIndex, NULL);
}
else
{
totemEvalStatus status = totemRegisterListPrototype_AddRegister(list, operand);
if (status != totemEvalStatus_Success)
{
return status;
}
if (!totemHashMap_Insert(&list->Numbers, number->Value, number->Length, operand->RegisterIndex))
{
return totemEvalStatus_Break(totemEvalStatus_OutOfMemory);
}
totemRegisterPrototype *reg = (totemRegisterPrototype*)totemMemoryBuffer_Get(&list->Registers, operand->RegisterIndex);
if (memchr(number->Value, '.', number->Length) != NULL)
{
reg->Float = atof(number->Value);
reg->DataType = totemPublicDataType_Float;
}
else
{
reg->Int = atoi(number->Value);
reg->DataType = totemPublicDataType_Int;
}
TOTEM_SETBITS(reg->Flags, totemRegisterPrototypeFlag_IsValue);
TOTEM_UNSETBITS(reg->Flags, totemRegisterPrototypeFlag_IsTemporary);
}
return totemEvalStatus_Success;
}
totemEvalStatus totemRegisterListPrototype_AddFunctionPointer(totemRegisterListPrototype *list, totemString *name, totemFunctionPointerPrototype *value, totemOperandRegisterPrototype *operand)
{
if (name)
{
if (totemRegisterListPrototype_GetIdentifier(list, name, operand, totemBool_False))
{
return totemEvalStatus_Success;
}
}
totemEvalStatus status = totemRegisterListPrototype_AddRegister(list, operand);
if (status != totemEvalStatus_Success)
{
return status;
}
if (name)
{
if (!totemHashMap_Insert(&list->Scope->Identifiers, name->Value, name->Length, operand->RegisterIndex))
{
return totemEvalStatus_Break(totemEvalStatus_OutOfMemory);
}
}
totemRegisterPrototype *reg = (totemRegisterPrototype*)totemMemoryBuffer_Get(&list->Registers, operand->RegisterIndex);
reg->FunctionPointer = *value;
reg->DataType = totemPublicDataType_Function;
TOTEM_SETBITS(reg->Flags, totemRegisterPrototypeFlag_IsValue);
TOTEM_UNSETBITS(reg->Flags, totemRegisterPrototypeFlag_IsTemporary);
return totemEvalStatus_Success;
}
void totemRegisterListPrototypeScope_Init(totemRegisterListPrototypeScope *scope)
{
totemHashMap_Init(&scope->MoveToLocalVars);
totemHashMap_Init(&scope->Identifiers);
scope->Prev = NULL;
}
void totemRegisterListPrototypeScope_Reset(totemRegisterListPrototypeScope *scope)
{
totemHashMap_Reset(&scope->MoveToLocalVars);
totemHashMap_Init(&scope->Identifiers);
scope->Prev = NULL;
}
void totemRegisterListPrototypeScope_Cleanup(totemRegisterListPrototypeScope *scope)
{
totemHashMap_Cleanup(&scope->MoveToLocalVars);
totemHashMap_Init(&scope->Identifiers);
scope->Prev = NULL;
}
totemEvalStatus totemRegisterListPrototype_EnterScope(totemRegisterListPrototype *list)
{
totemRegisterListPrototypeScope *newScope = totem_CacheMalloc(sizeof(totemRegisterListPrototypeScope));
if (!newScope)
{
return totemEvalStatus_Break(totemEvalStatus_OutOfMemory);
}
totemRegisterListPrototypeScope_Init(newScope);
newScope->Prev = list->Scope;
list->Scope = newScope;
return totemEvalStatus_Success;
}
void totemRegisterListPrototype_FreeScope(totemRegisterListPrototype *list)
{
totemRegisterListPrototypeScope *scope = list->Scope;
list->Scope = scope->Prev;
totemRegisterListPrototypeScope_Cleanup(scope);
totem_CacheFree(scope, sizeof(totemRegisterListPrototypeScope));
}
totemEvalStatus totemRegisterListPrototypeScope_FreeGlobalCache(totemRegisterListPrototypeScope *scope, totemRegisterListPrototype *list)
{
for (size_t i = 0; i < scope->MoveToLocalVars.NumBuckets; i++)
{
totemHashMapEntry *bucket = scope->MoveToLocalVars.Buckets[i];
while (bucket)
{
totemOperandRegisterPrototype operand;
operand.RegisterIndex = (totemOperandXUnsigned)bucket->Value;
operand.RegisterScopeType = list->ScopeType;
TOTEM_EVAL_CHECKRETURN(totemRegisterListPrototype_FreeRegister(list, &operand));
bucket = bucket->Next;
}
}
return totemEvalStatus_Success;
}
totemEvalStatus totemRegisterListPrototype_ExitScope(totemRegisterListPrototype *list)
{
for (size_t i = 0; i < list->Scope->Identifiers.NumBuckets; i++)
{
totemHashMapEntry *bucket = list->Scope->Identifiers.Buckets[i];
while (bucket)
{
totemOperandRegisterPrototype operand;
operand.RegisterIndex = (totemOperandXUnsigned)bucket->Value;
operand.RegisterScopeType = list->ScopeType;
TOTEM_EVAL_CHECKRETURN(totemRegisterListPrototype_FreeRegister(list, &operand));
bucket = bucket->Next;
}
}
TOTEM_EVAL_CHECKRETURN(totemRegisterListPrototypeScope_FreeGlobalCache(list->Scope, list));
totemRegisterListPrototype_FreeScope(list);
return totemEvalStatus_Success;
}
void totemRegisterListPrototype_Init(totemRegisterListPrototype *list, totemOperandType scope)
{
list->ScopeType = scope;
memset(list->DataTypes, 0, sizeof(list->DataTypes));
memset(list->HasDataType, 0, sizeof(list->HasDataType));
memset(list->Boolean, 0, sizeof(list->Boolean));
memset(list->HasBoolean, 0, sizeof(list->HasBoolean));
list->HasNull = totemBool_False;
list->Null = 0;
totemHashMap_Init(&list->Numbers);
totemHashMap_Init(&list->Strings);
totemMemoryBuffer_Init(&list->Registers, sizeof(totemRegisterPrototype));
totemMemoryBuffer_Init(&list->RegisterFreeList, sizeof(totemOperandXUnsigned));
list->Scope = NULL;
}
void totemRegisterListPrototype_Reset(totemRegisterListPrototype *list)
{
while (list->Scope)
{
totemRegisterListPrototype_FreeScope(list);
}
memset(list->DataTypes, 0, sizeof(list->DataTypes));
memset(list->HasDataType, 0, sizeof(list->HasDataType));
memset(list->Boolean, 0, sizeof(list->Boolean));
memset(list->HasBoolean, 0, sizeof(list->HasBoolean));
list->HasNull = totemBool_False;
list->Null = 0;
totemHashMap_Reset(&list->Numbers);
totemHashMap_Reset(&list->Strings);
totemMemoryBuffer_Reset(&list->Registers);
totemMemoryBuffer_Reset(&list->RegisterFreeList);
}
void totemRegisterListPrototype_Cleanup(totemRegisterListPrototype *list)
{
while (list->Scope)
{
totemRegisterListPrototype_FreeScope(list);
}
memset(list->DataTypes, 0, sizeof(list->DataTypes));
memset(list->HasDataType, 0, sizeof(list->HasDataType));
memset(list->Boolean, 0, sizeof(list->Boolean));
memset(list->HasBoolean, 0, sizeof(list->HasBoolean));
list->HasNull = totemBool_False;
list->Null = 0;
totemHashMap_Cleanup(&list->Numbers);
totemHashMap_Cleanup(&list->Strings);
totemMemoryBuffer_Cleanup(&list->Registers);
totemMemoryBuffer_Cleanup(&list->RegisterFreeList);
}
| 2.515625 | 3 |
2024-11-18T20:53:27.587594+00:00 | 2023-07-21T03:41:00 | 6c44193a276179e643d63ab42637e0ea257c6594 | {
"blob_id": "6c44193a276179e643d63ab42637e0ea257c6594",
"branch_name": "refs/heads/master",
"committer_date": "2023-07-21T03:41:00",
"content_id": "01a1f5445b9d6652988da942479b48f01e6ce3a3",
"detected_licenses": [
"BSD-3-Clause",
"BSD-2-Clause"
],
"directory_id": "20965ad00f94bab92a9d18c6e0990eb2a9a83e75",
"extension": "c",
"filename": "rts_buffer.c",
"fork_events_count": 91,
"gha_created_at": "2017-12-08T15:20:41",
"gha_event_created_at": "2023-08-18T15:20:42",
"gha_language": "C",
"gha_license_id": "BSD-3-Clause",
"github_id": 113587683,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5714,
"license": "BSD-3-Clause,BSD-2-Clause",
"license_type": "permissive",
"path": "/src/lib/rts/src/rts_buffer.c",
"provenance": "stackv2-0127.json.gz:68736",
"repo_name": "plume-design/opensync",
"revision_date": "2023-07-21T03:41:00",
"revision_id": "907da96a2a5cc78d308f095323ebc992d524630e",
"snapshot_id": "22fe8d0779df5e35057a8dd5fb779e6b088eee58",
"src_encoding": "UTF-8",
"star_events_count": 80,
"url": "https://raw.githubusercontent.com/plume-design/opensync/907da96a2a5cc78d308f095323ebc992d524630e/src/lib/rts/src/rts_buffer.c",
"visit_date": "2023-08-16T11:40:56.389400"
} | stackv2 | /*
Copyright (c) 2015, Plume Design Inc. 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 Plume Design Inc. 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 Plume Design Inc. 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 "rts_buffer.h"
static bool
rts_buffer_realloc(struct rts_buffer *b, size_t size, struct rts_pool *mp)
{
size_t alloc_size;
struct rts_buffer_data *data;
size += sizeof(*data);
if (!b->data) {
data = rts_pool_realloc(mp, NULL, size, &alloc_size);
if (!data)
return false;
data->ref = 1;
} else if (rts_buffer_shared(b)) {
unsigned short len = b->len;
data = rts_pool_realloc(mp, NULL, size, &alloc_size);
if (!data)
return false;
__builtin_memcpy(data->memory, b->data->data + b->off, b->len);
data->ref = 1;
rts_buffer_put(b, mp);
b->len = len;
} else {
rts_assert(b->data->data == b->data->memory);
data = rts_pool_realloc(mp, b->data, size, &alloc_size);
if (!data)
return false;
}
rts_assert(size <= alloc_size);
data->data = data->memory;
b->cap = alloc_size;
b->data = data;
return true;
}
bool
rts_buffer_reserve(struct rts_buffer *b, size_t size, struct rts_pool *mp)
{
return rts_buffer_realloc(b, size, mp);
}
static inline bool
rts_buffer_push_capacity(struct rts_buffer *b, struct rts_pool *mp)
{
if (b->data == 0)
return rts_buffer_reserve(b, 1, mp);
if (b->len + 1 > (int)rts_buffer_capacity(b))
return rts_buffer_reserve(b, b->len + 1, mp);
return true;
}
bool
rts_buffer_clone(struct rts_buffer *dst, const struct rts_buffer *src, struct rts_pool *mp)
{
rts_buffer_put(dst, mp);
if (rts_buffer_empty(src))
return true;
if (!rts_buffer_realloc(dst, rts_buffer_size(src), mp))
return false;
__builtin_memcpy(dst->data->data + dst->off, src->data->data + src->off, src->len);
dst->len = src->len;
return true;
}
bool
rts_buffer_write(struct rts_buffer *dst, const void *src, size_t len, struct rts_pool *mp)
{
if (len == 0)
return true;
if (rts_buffer_shared(dst) || (rts_buffer_capacity(dst) < rts_buffer_size(dst) + len)) {
if (!rts_buffer_reserve(dst, rts_buffer_size(dst) + len, mp))
return false;
}
__builtin_memcpy(&dst->data->data[dst->len], src, len);
dst->len += len;
return true;
}
bool
rts_buffer_append(struct rts_buffer *dst, struct rts_buffer *src, struct rts_pool *mp)
{
if (rts_buffer_empty(src)) {
return true;
} else if (rts_buffer_empty(dst)) {
rts_buffer_copy(dst, src, mp);
return true;
}
if (rts_buffer_shared(dst)) {
if (!rts_buffer_reserve(dst, dst->len + src->len, mp))
return false;
} else if (rts_buffer_capacity(dst) <= dst->len + src->len) {
if (!rts_buffer_reserve(dst, dst->len + src->len, mp))
return false;
}
rts_assert(dst->off == 0);
__builtin_memcpy(&dst->data->data[dst->len], src->data->data + src->off, src->len);
dst->len += src->len;
return true;
}
bool
rts_buffer_push(struct rts_buffer *b, unsigned char byte, struct rts_pool *mp)
{
if (rts_buffer_shared(b) && !rts_buffer_reserve(b, b->len + 1, mp))
return false;
else if (!rts_buffer_push_capacity(b, mp))
return false;
b->data->data[b->len++] = byte;
return true;
}
bool
rts_buffer_sync(struct rts_buffer *dst, struct rts_pool *mp)
{
unsigned len = dst->len;
struct rts_buffer sync;
rts_buffer_init(&sync);
if (!rts_buffer_reserve(&sync, dst->len, mp))
return false;
__builtin_memcpy(sync.data->data, &dst->data->data[dst->off], dst->len);
rts_buffer_put(dst, mp);
dst->len = len;
dst->off = 0;
dst->cap = sync.cap;
dst->data = sync.data;
return true;
}
void
rts_buffer_copy(struct rts_buffer *dst, struct rts_buffer *src, struct rts_pool *mp)
{
rts_buffer_put(dst, mp);
rts_buffer_get(src);
dst->data = src->data;
dst->cap = src->cap;
dst->len = src->len;
dst->off = src->off;
}
void
rts_buffer_clear(struct rts_buffer *b, struct rts_pool *mp)
{
if (rts_buffer_shared(b)) {
rts_buffer_put(b, mp);
rts_buffer_init(b);
} else if (!rts_buffer_empty(b)) {
b->len = 0;
b->off = 0;
}
}
| 2.21875 | 2 |
2024-11-18T20:53:27.654255+00:00 | 2019-04-15T18:37:25 | 206e4267975476bae0ae82c6377157bc0e2e973d | {
"blob_id": "206e4267975476bae0ae82c6377157bc0e2e973d",
"branch_name": "refs/heads/master",
"committer_date": "2019-04-15T18:37:25",
"content_id": "a134f7e92cad60012922be0775798a256764f85f",
"detected_licenses": [
"BSD-3-Clause-Open-MPI"
],
"directory_id": "c71b7e39dc0f96fe4298fce098a28077f5a20f65",
"extension": "h",
"filename": "scheduling.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 181544492,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5546,
"license": "BSD-3-Clause-Open-MPI",
"license_type": "permissive",
"path": "/parsec/scheduling.h",
"provenance": "stackv2-0127.json.gz:68864",
"repo_name": "NLAFET/ABFT",
"revision_date": "2019-04-15T18:37:25",
"revision_id": "73af5b9ffe65cdb06b58c0cb34029ee6265d2bf8",
"snapshot_id": "386f8bb80942039df847f710a4b7545d43922ef5",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/NLAFET/ABFT/73af5b9ffe65cdb06b58c0cb34029ee6265d2bf8/parsec/scheduling.h",
"visit_date": "2020-05-12T20:53:02.352552"
} | stackv2 | /*
* Copyright (c) 2009-2018 The University of Tennessee and The University
* of Tennessee Research Foundation. All rights
* reserved.
*/
#ifndef _PARSEC_scheduling_h
#define _PARSEC_scheduling_h
/**
* @addtogroup parsec_internal_scheduling
* @{
*/
#include "parsec/runtime.h"
BEGIN_C_DECLS
/**
* Mark a execution context as being ready to be scheduled, i.e. all
* input dependencies are resolved. The execution context can be
* executed immediately or delayed until resources become available.
*
* @param[in] eu The execution unit where the tasks are to be proposed
* for scheduling. This is a hint, as the scheduling engine
* is free to push them where it decides.
* @param[in] ec The execution context to be executed. This include
* calling the attached hook (if any) as well as marking
* all dependencies as completed.
* @param[in] distance Suggested distance to the current state where the tasks
* are to be pushed. The larger the value (in absolute) the
* further away the tasks will be pushed. This is a hint
* that the schedulers are free to ignore.
*
* @return 0 If the execution was succesful and all output dependencies
* has been correctly marked.
* @return -1 If something went wrong.
*/
int __parsec_schedule( parsec_execution_stream_t*,
parsec_task_t*,
int32_t distance);
/**
* @brief Reschedule a task on the most appropriate resource.
*
* @details The function reschedules a task, by trying to locate it as closer
* as possible to the current execution unit. If not available
* execution unit was found, the task is rescheduled on the same
* execution unit. To find the most appropriate execution unit
* we start from the next execution unit after the current one, and
* iterate over all existing execution units (in the current VP,
* then on the next VP and so on).
*
* @param [IN] es, the start execution_stream (normall it is the current one).
* @param [IN] task, the task to be rescheduled.
*
* @return parsec scheduling return code
*/
int __parsec_reschedule(parsec_execution_stream_t* es,
parsec_task_t* task);
/**
* @brief Enter the progress engine for this execution unit
*
* @details The function enters the progress engine for eu.
* If eu is a master execution unit, the function returns once
* all parsec handles scheduled on that node have been completed
* If eu is not a master execution unit, the function returns
* once the master execution unit has stopped the execution
* by calling parsec_fini.
*
* @param[in] eu_context the execution_unit that should start progressing.
*
* @return parsec scheduling return code
*/
int __parsec_context_wait(parsec_execution_stream_t* es);
/**
* Execute the body of the task associated to the context.
*/
int __parsec_execute( parsec_execution_stream_t*, parsec_task_t*);
/**
* Signal the termination of the execution context to all dependencies of
* its dependencies.
*
* @param[in] eu_context The execution context of the finished task.
* @param[in] exec_context The task to be completed
*
* @return 0 If the dependencies have successfully been signaled.
* @return -1 If something went wrong.
*/
int __parsec_complete_execution( parsec_execution_stream_t *es,
parsec_task_t *task);
/**
* Signal the handle that a certain number of runtime bound activities have been
* completed. Such activities includes network communications, other local data
* transfers, and more generally any activity generated by the runtime itself
* that is related to the handle. In addition, we assume that one extra activity
* is to the capability of the upper level to generate tasks, activity that has
* it's own counter, handled via parsec_taskpool_update_nbtask. Thus, once the
* upper level knows no local tasks will be further generate it is it's
* responsability to update the runtime counter accordingly.
*
* @return 0 if the handle has not been completed.
* @return 1 if the handle has been completed and it has been marked for release.
*/
int parsec_taskpool_update_runtime_nbtask(parsec_taskpool_t *tp, int32_t nb_tasks);
/**
* When changing the number of local tasks, see if we need to call the
* DAG complete_cb callback, and/or if we need to update the number of
* active objects.
*
* remaining is the number of local tasks available, after updating it
* using the appropriate atomic operation
*/
int parsec_check_complete_cb(parsec_taskpool_t *tp, parsec_context_t *context, int remaining);
/**
* Loads the scheduler as selected using the MCA logic
* You better not call this while computations are in progress,
* i.e. it should be safe to call this when the main thread is
* not yet inside parsec_progress, but *before* any call to
* parsec_progress...
*
* @return 1 if the new scheduler was succesfully installed
* 0 if it failed. In this case, the previous scheduler
* is kept.
*/
int parsec_set_scheduler( parsec_context_t *parsec );
/**
* Removes the current scheduler (cleanup)
*/
void parsec_remove_scheduler( parsec_context_t *parsec );
struct parsec_sched_module_s;
extern struct parsec_sched_module_s *current_scheduler;
END_C_DECLS
/** @} */
#endif /* _PARSEC_scheduling_h */
| 2.046875 | 2 |
2024-11-18T20:53:28.504852+00:00 | 2021-06-21T03:33:48 | 4581b410e84b325f196e4bd9f63361692a1da3b3 | {
"blob_id": "4581b410e84b325f196e4bd9f63361692a1da3b3",
"branch_name": "refs/heads/obliv-c",
"committer_date": "2021-06-21T03:33:48",
"content_id": "fdd6fbd8b4f407cb443f565cc4d68d62f0f97efc",
"detected_licenses": [
"BSD-3-Clause",
"BSD-2-Clause"
],
"directory_id": "91b0590e4fe507612d6e4dc17b940b531008048b",
"extension": "c",
"filename": "commitReveal.c",
"fork_events_count": 74,
"gha_created_at": "2013-05-29T19:14:15",
"gha_event_created_at": "2022-08-22T12:42:25",
"gha_language": "C",
"gha_license_id": "NOASSERTION",
"github_id": 10367312,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5543,
"license": "BSD-3-Clause,BSD-2-Clause",
"license_type": "permissive",
"path": "/src/ext/oblivc/commitReveal.c",
"provenance": "stackv2-0127.json.gz:69120",
"repo_name": "samee/obliv-c",
"revision_date": "2021-06-21T03:33:48",
"revision_id": "e02e5c590523ef4dae06e167a7fa00037bb3fdaf",
"snapshot_id": "bec564bb1a8cdfea27c31ae4121a464edd8a9cdf",
"src_encoding": "UTF-8",
"star_events_count": 172,
"url": "https://raw.githubusercontent.com/samee/obliv-c/e02e5c590523ef4dae06e167a7fa00037bb3fdaf/src/ext/oblivc/commitReveal.c",
"visit_date": "2021-06-23T10:58:01.394350"
} | stackv2 | #include<string.h>
#include<gcrypt.h>
#include<bcrandom.h>
#include<commitReveal.h>
#include<obliv.h>
OcCommitter* ocSendCommit(ProtocolDesc* pd,BCipherRandomGen* gen,
const void* data,int size,int destParty)
{
OcCommitter* rv = malloc(sizeof(OcCommitter));
gcry_md_hd_t h;
randomizeBuffer(gen,rv->key,COMMIT_KEY_SIZE);
gcry_md_open(&h,COMMIT_HASH_ALGO,0);
rv->n = size;
rv->data = data;
rv->destParty = destParty;
rv->pd = pd;
gcry_md_write(h,&pd->thisParty,sizeof(pd->thisParty));
gcry_md_write(h,rv->key,COMMIT_KEY_SIZE);
gcry_md_write(h,data,size);
gcry_md_final(h);
osend(pd,destParty,gcry_md_read(h,0),COMMIT_HASH_BYTES);
gcry_md_close(h);
return rv;
}
void ocRevealCommit(OcCommitter* com)
{
osend(com->pd,com->destParty,com->key,COMMIT_KEY_SIZE);
osend(com->pd,com->destParty,com->data,com->n);
free(com);
}
OcCommitment* ocRecvCommit(ProtocolDesc* pd,BCipherRandomGen* gen,int srcParty)
{
OcCommitment* rv = malloc(sizeof(OcCommitment));
orecv(pd,srcParty,rv->hash,COMMIT_HASH_BYTES);
rv->pd = pd; rv->srcParty = srcParty;
return rv;
}
bool ocCheckCommit(OcCommitment* com,int size,void* dest)
{
int i;
char key[COMMIT_KEY_SIZE];
unsigned char *buf,*hash2;
bool rv = true;
if(dest) buf=dest; else buf=malloc(size);
gcry_md_hd_t h;
gcry_md_open(&h,COMMIT_HASH_ALGO,0);
orecv(com->pd,com->srcParty,key,COMMIT_KEY_SIZE);
orecv(com->pd,com->srcParty,buf,size);
gcry_md_write(h,&com->srcParty,sizeof(com->srcParty));
gcry_md_write(h,key,COMMIT_KEY_SIZE);
gcry_md_write(h,buf,size);
gcry_md_final(h);
hash2 = gcry_md_read(h,0);
for(i=0;i<COMMIT_HASH_BYTES;++i) rv &= (com->hash[i]==hash2[i]);
gcry_md_close(h);
if(!dest) free(buf);
free(com);
return rv;
}
bool ocXchgBytes(ProtocolDesc* pd,BCipherRandomGen* gen,
const void* src,void* dest,int n,int party)
{
if(pd->thisParty<party)
{ OcCommitter* com = ocSendCommit(pd,gen,src,n,party);
orecv(pd,party,dest,n);
ocRevealCommit(com);
}else if(pd->thisParty>party)
{ OcCommitment* com = ocRecvCommit(pd,gen,party);
osend(pd,party,src,n);
return ocCheckCommit(com,n,dest);
}else memcpy(dest,src,n);
return true;
}
// Oh please remember: this is NOT a private equality check
bool ocEqualityCheck(ProtocolDesc* pd,BCipherRandomGen* gen,
const void* data,int n,int party)
{
char* buf = malloc(n);
bool rv;
rv = ocXchgBytes(pd,gen,data,buf,n,party);
// we can break early: not private
if(rv) rv = (memcmp(buf,data,n)==0);
free(buf);
return rv;
}
bool ocRandomBytes_impl(ProtocolDesc* pd,BCipherRandomGen* gen,
void* dest,int n,int party)
{
char* buf = malloc(n);
int i;
bool rv;
randomizeBuffer(gen,dest,n);
rv = ocXchgBytes(pd,gen,dest,buf,n,party);
if(rv) for(i=0;i<n;++i) *((char*)dest+i) ^= buf[i];
free(buf);
return rv;
}
bool ocRandomBytes(ProtocolDesc* pd,BCipherRandomGen* gen,
void* dest,int n,int party)
{
if(n<=BC_SEEDLEN_DEFAULT)
return ocRandomBytes_impl(pd,gen,dest,n,party);
char buf[BC_SEEDLEN_DEFAULT];
if(!ocRandomBytes_impl(pd,gen,buf,sizeof(buf),party)) return false;
randomizeBufferByKey(buf,dest,n);
return true;
}
// Copied from ot.c
void dhSerialize(char* buf,gcry_mpi_point_t u,
gcry_ctx_t ctx,gcry_mpi_t x,gcry_mpi_t y);
void dhDeserialize(gcry_mpi_point_t* p, const char* buf);
static bool
ocXchgPoints(ProtocolDesc* pd, BCipherRandomGen* gen, gcry_ctx_t ctx,
gcry_mpi_point_t* src, gcry_mpi_point_t* dest,int n,int party)
{
char buf1[n][DHEltSerialBytes], buf2[n][DHEltSerialBytes];
gcry_mpi_t x = gcry_mpi_new(0), y = gcry_mpi_new(0);
int i;
for(i=0;i<n;++i) dhSerialize(buf1[i],src[i],ctx,x,y);
bool res = ocXchgBytes(pd,gen,buf1,buf2,sizeof(buf1),party);
if(res) for(i=0;i<n;++i) dhDeserialize(dest+i,buf2[i]);
gcry_mpi_release(x); gcry_mpi_release(y);
return res;
}
// simply compares to ec points
static bool
ocPointsEqual(gcry_ctx_t curve,gcry_mpi_point_t a, gcry_mpi_point_t b)
{
gcry_mpi_t ax = gcry_mpi_new(0);
gcry_mpi_t ay = gcry_mpi_new(0);
gcry_mpi_t bx = gcry_mpi_new(0);
gcry_mpi_t by = gcry_mpi_new(0);
gcry_mpi_ec_get_affine(ax,ay,a,curve);
gcry_mpi_ec_get_affine(bx,by,b,curve);
bool eq;
eq = !gcry_mpi_cmp(ax,bx);
if(eq) eq = !gcry_mpi_cmp(ay,by);
gcry_mpi_release(ax);
gcry_mpi_release(ay);
gcry_mpi_release(bx);
gcry_mpi_release(by);
return eq;
}
static gcry_mpi_t mpiFromHash(const char* data,size_t len)
{
char hash[COMMIT_HASH_BYTES+1];
hash[0]=0;
gcry_md_hash_buffer(COMMIT_HASH_ALGO,hash+1,data,len);
gcry_mpi_t res;
gcry_mpi_scan(&res,GCRYMPI_FMT_STD,hash,1+COMMIT_HASH_BYTES,NULL);
return res;
}
bool ocPrivateEqualityCheck_halfAuth(ProtocolDesc* pd,BCipherRandomGen* gen,
const void* data, int n,int party)
{
bool res = false;
gcry_ctx_t curve;
gcry_mpi_ec_new(&curve,NULL,DHCurveName);
gcry_mpi_point_t g = gcry_mpi_ec_get_point("g",curve,1);
gcry_mpi_point_t yab, xab;
gcry_mpi_t x = mpiFromHash(data,n), a = dhRandomExp(gen);
gcry_mpi_ec_mul(g,x,g,curve);
gcry_mpi_ec_mul(g,a,g,curve);
if(!ocXchgPoints(pd,gen,curve,&g,&yab,1,party)) goto error1;
gcry_mpi_ec_mul(yab,a,yab,curve);
if(!ocXchgPoints(pd,gen,curve,&yab,&xab,1,party)) goto error2;
res = ocPointsEqual(curve,xab,yab);
gcry_mpi_point_release(xab);
error2:
gcry_mpi_point_release(yab);
error1:
gcry_mpi_release(x); gcry_mpi_release(a);
gcry_mpi_point_release(g);
gcry_ctx_release(curve);
return res;
}
| 2.40625 | 2 |
2024-11-18T20:53:28.616407+00:00 | 2018-02-04T18:59:28 | 53e4d238952fbb801acc4e6274f50b1353830d07 | {
"blob_id": "53e4d238952fbb801acc4e6274f50b1353830d07",
"branch_name": "refs/heads/master",
"committer_date": "2018-02-04T18:59:28",
"content_id": "586780bc64eb94aa1c84fc7134d23db249209889",
"detected_licenses": [
"Unlicense"
],
"directory_id": "e312ce2591f8779d34e1db9f55445f3ae9f72f00",
"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": null,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 6657,
"license": "Unlicense",
"license_type": "permissive",
"path": "/lib/eval.c",
"provenance": "stackv2-0127.json.gz:69249",
"repo_name": "salewski/wisp",
"revision_date": "2018-02-04T18:59:28",
"revision_id": "2f1730cc562394e30f275e82b7101306bc8b32b9",
"snapshot_id": "198f3cc3baf8a409bf5726eab5102626e4d36cb6",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/salewski/wisp/2f1730cc562394e30f275e82b7101306bc8b32b9/lib/eval.c",
"visit_date": "2020-06-19T21:54:38.143806"
} | stackv2 | #include <stdio.h>
#include <signal.h>
#include <string.h>
#include <errno.h>
#include "cons.h"
#include "object.h"
#include "symtab.h"
#include "eval.h"
#include "number.h"
#include "str.h"
#include "reader.h"
#include "common.h"
#include "lisp.h"
#include "vector.h"
object_t *lambda, *macro, *quote;
object_t *err_symbol, *err_thrown, *err_attach;
object_t *rest, *optional;
object_t *doc_string;
/* Commonly used thrown error symbols */
object_t *void_function, *wrong_number_of_arguments, *wrong_type,
*improper_list, *improper_list_ending, *err_interrupt;
/* Stack counting */
unsigned int stack_depth = 0, max_stack_depth = 20000;
char *core_file = "core.wisp";
int interrupt = 0;
int interactive_mode = 0;
void handle_iterrupt (int sig)
{
(void) sig;
if (!interrupt && interactive_mode)
{
interrupt = 1;
signal (SIGINT, &handle_iterrupt);
}
else
{
signal (SIGINT, SIG_DFL);
raise (SIGINT);
}
}
void eval_init ()
{
/* install interrupt handler */
signal (SIGINT, &handle_iterrupt);
/* regular evaluation symbols */
lambda = c_sym ("lambda");
macro = c_sym ("macro");
quote = c_sym ("quote");
rest = c_sym ("&rest");
optional = c_sym ("&optional");
doc_string = c_sym ("doc-string");
/* error symbols */
err_symbol = c_usym ("wisp-error");
SET (err_symbol, err_symbol);
err_thrown = err_attach = NIL;
void_function = c_sym ("void-function");
wrong_number_of_arguments = c_sym ("wrong-number-of-arguments");
wrong_type = c_sym ("wrong-type-argument");
improper_list = c_sym ("improper-list");
improper_list_ending = c_sym ("improper-list-ending");
err_interrupt = c_sym ("caught-interrupt");
/* set up wisproot */
wisproot = getenv ("WISPROOT");
if (wisproot == NULL)
wisproot = ".";
SET (c_sym ("wisproot"), c_strs (xstrdup (wisproot)));
/* Load core lisp code. */
if (strlen (wisproot) != 0)
core_file = pathcat (wisproot, core_file);
int r = load_file (NULL, core_file, 0);
if (!r)
{
fprintf (stderr, "error: could not load core lisp \"%s\": %s\n",
core_file, strerror (errno));
if (strlen (wisproot) == 1)
fprintf (stderr, "warning: perhaps you should set WISPROOT\n");
exit (EXIT_FAILURE);
}
}
/* Initilize all the systems. */
void wisp_init ()
{
/* These *must* be called in this order. */
object_init ();
symtab_init ();
cons_init ();
str_init ();
lisp_init ();
vector_init ();
eval_init ();
}
object_t *eval_list (object_t * lst)
{
if (lst == NIL)
return NIL;
if (!CONSP (lst))
THROW (improper_list_ending, UPREF (lst));
object_t *car = eval (CAR (lst));
CHECK (car);
object_t *cdr = eval_list (CDR (lst));
if (cdr == err_symbol)
{
obj_destroy (car);
return err_symbol;
}
return c_cons (car, cdr);
}
object_t *eval_body (object_t * body)
{
object_t *r = NIL;
while (body != NIL)
{
obj_destroy (r);
r = eval (CAR (body));
CHECK (r);
body = CDR (body);
}
return r;
}
object_t *assign_args (object_t * vars, object_t * vals)
{
int optional_mode = 0;
int cnt = 0;
object_t *orig_vars = vars;
while (vars != NIL)
{
object_t *var = CAR (vars);
if (var == optional)
{
/* Turn on optional mode and continue. */
optional_mode = 1;
vars = CDR (vars);
continue;
}
if (var == rest)
{
/* Assign the rest of the list and finish. */
vars = CDR (vars);
sympush (CAR (vars), vals);
vals = NIL;
break;
}
else if (!optional_mode && vals == NIL)
{
while (cnt > 0)
{
sympop (CAR (orig_vars));
orig_vars = CDR (orig_vars);
cnt--;
}
THROW (wrong_number_of_arguments, NIL);
}
else if (optional_mode && vals == NIL)
{
sympush (var, NIL);
}
else
{
object_t *val = CAR (vals);
sympush (var, val);
cnt++;
}
vars = CDR (vars);
if (vals != NIL)
vals = CDR (vals);
}
/* vals should be consumed by now */
if (vals != NIL)
{
unassign_args (vars);
THROW (wrong_number_of_arguments, NIL);
}
return T;
}
void unassign_args (object_t * vars)
{
if (vars == NIL)
return;
object_t *var = CAR (vars);
if (var != rest && var != optional)
sympop (var);
unassign_args (CDR (vars));
}
object_t *top_eval (object_t * o)
{
stack_depth = 0;
object_t *r = eval (o);
if (r == err_symbol)
{
printf ("Wisp error: ");
object_t *c = c_cons (err_thrown, c_cons (err_attach, NIL));
obj_print (c, 1);
obj_destroy (c);
return err_symbol;
}
return r;
}
object_t *eval (object_t * o)
{
/* Check for interrupts. */
if (interrupt)
{
interrupt = 0;
THROW (err_interrupt, c_strs (xstrdup ("interrupted")));
}
if (o->type != CONS && o->type != SYMBOL)
return UPREF (o);
else if (o->type == SYMBOL)
return UPREF (GET (o));
/* Find the function. */
object_t *f = eval (CAR (o));
CHECK (f);
object_t *extrao = NIL;
if (VECTORP (f))
{
extrao = o = c_cons (UPREF (f), UPREF (o));
f = eval (c_sym ("vfunc"));
if (f == err_symbol)
{
obj_destroy (extrao);
return err_symbol;
}
}
if (!FUNCP (f))
{
obj_destroy (f);
THROW (void_function, UPREF (CAR (o)));
}
/* Check the stack */
if (++stack_depth >= max_stack_depth)
THROW (c_sym ("max-eval-depth"), c_int (stack_depth--));
/* Handle argument list */
object_t *args = CDR (o);
if (f->type == CFUNC || (f->type == CONS && (CAR (f) == lambda)))
{
/* c function or list function (eval args) */
args = eval_list (args);
if (args == err_symbol)
{
obj_destroy (f);
obj_destroy (extrao);
return err_symbol;
}
}
else
UPREF (args); /* so we can destroy args no matter what */
object_t *ret = apply (f, args);
stack_depth--;
obj_destroy (f);
obj_destroy (args);
obj_destroy (extrao); /* vector as function */
return ret;
}
object_t *apply (object_t * f, object_t * args)
{
if (f->type == CFUNC || f->type == SPECIAL)
{
/* call the c function */
cfunc_t cf = FVAL (f);
object_t *r = cf (args);
return r;
}
else
{
/* list form */
object_t *vars = CAR (CDR (f));
object_t *assr = assign_args (vars, args);
if (assr == err_symbol)
{
err_attach = UPREF (args);
return err_symbol;
}
object_t *r;
if (CAR (f) == lambda)
r = eval_body (CDR (CDR (f)));
else
{
object_t *body = eval_body (CDR (CDR (f)));
r = eval (body);
obj_destroy (body);
}
unassign_args (vars);
return r;
}
return NIL;
}
| 2.1875 | 2 |
2024-11-18T20:53:28.694068+00:00 | 2015-10-23T11:46:04 | 62d2a700351a1f89098b91a8ae39874bc2e98687 | {
"blob_id": "62d2a700351a1f89098b91a8ae39874bc2e98687",
"branch_name": "refs/heads/master",
"committer_date": "2015-10-23T11:46:04",
"content_id": "66fe81f3ee30fb727a074eab907da681888ecf3a",
"detected_licenses": [
"MIT"
],
"directory_id": "4130fdf732add371bf2572e7852ea8cae4f4f377",
"extension": "c",
"filename": "main.c",
"fork_events_count": 2,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 43981779,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 9789,
"license": "MIT",
"license_type": "permissive",
"path": "/src/main.c",
"provenance": "stackv2-0127.json.gz:69379",
"repo_name": "JamesFowler42/alvin",
"revision_date": "2015-10-23T11:46:04",
"revision_id": "f298765b5448df23e1d1ed6d178fd063586cd93f",
"snapshot_id": "50181aab0d5b3d6679aad9e80a7265c107279f1a",
"src_encoding": "UTF-8",
"star_events_count": 5,
"url": "https://raw.githubusercontent.com/JamesFowler42/alvin/f298765b5448df23e1d1ed6d178fd063586cd93f/src/main.c",
"visit_date": "2021-01-10T16:30:42.303630"
} | stackv2 | /*
* Alvin IFTTT Control Application
*
* Copyright (c) 2015 James Fowler
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include "pebble.h"
#include "alvin.h"
static ConfigData config_data;
static bool save_config_requested = false;
static bool version_sent = false;
static AppTimer *redraw_timer = NULL;
/*
* Send a message to javascript
*/
static void send_to_phone(const uint32_t key, int32_t tophone) {
Tuplet tuplet = TupletInteger(key, tophone);
DictionaryIterator *iter;
app_message_outbox_begin(&iter);
if (iter == NULL) {
LOG_WARN("no outbox");
return;
}
dict_write_tuplet(iter, &tuplet);
dict_write_end(iter);
app_message_outbox_send();
}
/*
* Update the menu, save the config etc.
*/
static void update_redraw(void *data) {
redraw_timer = NULL;
trigger_config_save();
reload_menu();
}
/*
* Queue a menu re-draw after all the incoming messages reconfiguring menu have been processed
*/
static void request_update_redraw() {
if (redraw_timer == NULL) {
redraw_timer = app_timer_register(MENU_REDRAW_TIME_MS, update_redraw, NULL);
} else {
app_timer_reschedule(redraw_timer, MENU_REDRAW_TIME_MS);
}
}
/*
* Menu item fired
*/
EXTFN void menu_item_fired(int32_t menu_item) {
int32_t turnon = config_data.entry[menu_item].on ? 0 : 1; // Menu item not set yet, so previous value used
Tuplet tuplet1 = TupletInteger(KEY_FIRE, menu_item);
Tuplet tuplet2 = TupletInteger(KEY_TURNON, turnon);
DictionaryIterator *iter;
app_message_outbox_begin(&iter);
if (iter == NULL) {
LOG_WARN("no outbox");
return;
}
dict_write_tuplet(iter, &tuplet1);
dict_write_tuplet(iter, &tuplet2);
dict_write_end(iter);
app_message_outbox_send();
}
/*
* Incoming message handler
*/
static void in_received_handler(DictionaryIterator *iter, void *context) {
// Got a ctrl message
Tuple *ctrl_tuple = dict_find(iter, KEY_CTRL);
if (ctrl_tuple) {
int32_t ctrl_value = ctrl_tuple->value->int32;
// If version is done then mark it
if (ctrl_value & CTRL_VERSION_DONE) {
LOG_DEBUG("CTRL_VERSION_DONE");
version_sent = true;
}
if (ctrl_value & CTRL_GOT_REQUEST) {
LOG_DEBUG("CTRL_GOT_REQUEST");
set_sent();
}
if (ctrl_value & CTRL_REQUEST_OK) {
LOG_DEBUG("CTRL_REQUEST_OK");
set_success();
}
if (ctrl_value & CTRL_REQUEST_FAIL) {
LOG_DEBUG("CTRL_REQUEST_FAIL");
set_failed();
}
}
// Got a menu name
Tuple *mn = dict_find(iter, KEY_MENU_NAME_1);
if (mn) {
strncpy(config_data.entry[0].menu_text, mn->value->cstring, MENU_TEXT_LEN);
request_update_redraw();
}
mn = dict_find(iter, KEY_MENU_NAME_2);
if (mn) {
strncpy(config_data.entry[1].menu_text, mn->value->cstring, MENU_TEXT_LEN);
request_update_redraw();
}
mn = dict_find(iter, KEY_MENU_NAME_3);
if (mn) {
strncpy(config_data.entry[2].menu_text, mn->value->cstring, MENU_TEXT_LEN);
request_update_redraw();
}
mn = dict_find(iter, KEY_MENU_NAME_4);
if (mn) {
strncpy(config_data.entry[3].menu_text, mn->value->cstring, MENU_TEXT_LEN);
request_update_redraw();
}
mn = dict_find(iter, KEY_MENU_NAME_5);
if (mn) {
strncpy(config_data.entry[4].menu_text, mn->value->cstring, MENU_TEXT_LEN);
request_update_redraw();
}
mn = dict_find(iter, KEY_MENU_NAME_6);
if (mn) {
strncpy(config_data.entry[5].menu_text, mn->value->cstring, MENU_TEXT_LEN);
request_update_redraw();
}
mn = dict_find(iter, KEY_MENU_NAME_7);
if (mn) {
strncpy(config_data.entry[6].menu_text, mn->value->cstring, MENU_TEXT_LEN);
request_update_redraw();
}
mn = dict_find(iter, KEY_MENU_NAME_8);
if (mn) {
strncpy(config_data.entry[7].menu_text, mn->value->cstring, MENU_TEXT_LEN);
request_update_redraw();
}
mn = dict_find(iter, KEY_MENU_NAME_9);
if (mn) {
strncpy(config_data.entry[8].menu_text, mn->value->cstring, MENU_TEXT_LEN);
request_update_redraw();
}
mn = dict_find(iter, KEY_MENU_NAME_10);
if (mn) {
strncpy(config_data.entry[9].menu_text, mn->value->cstring, MENU_TEXT_LEN);
request_update_redraw();
}
// Which menu entries are toggles
Tuple *tog_tuple = dict_find(iter, KEY_MENU_TOGGLE);
if (tog_tuple) {
int32_t tog_value = tog_tuple->value->int32;
config_data.entry[0].toggle = (tog_value & 1) == 1;
config_data.entry[1].toggle = (tog_value & 2) == 2;
config_data.entry[2].toggle = (tog_value & 4) == 4;
config_data.entry[3].toggle = (tog_value & 8) == 8;
config_data.entry[4].toggle = (tog_value & 16) == 16;
config_data.entry[5].toggle = (tog_value & 32) == 32;
config_data.entry[6].toggle = (tog_value & 64) == 64;
config_data.entry[7].toggle = (tog_value & 128) == 128;
config_data.entry[8].toggle = (tog_value & 256) == 256;
config_data.entry[9].toggle = (tog_value & 512) == 512;
for (int8_t i = 0; i < MAX_MENU_ENTRY; i++) {
config_data.entry[i].on = false;
}
config_data.active = config_data.entry[0].menu_text[0] != '\0';
request_update_redraw();
}
}
/*
* Send the version on initialisation
*/
static void send_version(void *data) {
if (!version_sent) {
if (bluetooth_connection_service_peek()) {
app_timer_register(VERSION_SEND_INTERVAL_MS, send_version, NULL);
send_to_phone(KEY_VERSION, VERSION);
} else {
app_timer_register(VERSION_SEND_SLOW_INTERVAL_MS, send_version, NULL);
}
}
}
/*
* Calcuate buffer sizes and open comms
*/
EXTFN void open_comms() {
// Register message handlers
app_message_register_inbox_received(in_received_handler);
// Incoming size
Tuplet out_values[] = { TupletInteger(KEY_FIRE, 0), TupletInteger(KEY_TURNON, 0) };
Tuplet in_values[] = { TupletCString(KEY_MENU_NAME_1, FULL_STRING), TupletCString(KEY_MENU_NAME_2, FULL_STRING), TupletCString(KEY_MENU_NAME_3, FULL_STRING), TupletCString(KEY_MENU_NAME_4, FULL_STRING), TupletCString(KEY_MENU_NAME_5, FULL_STRING), TupletCString(KEY_MENU_NAME_6, FULL_STRING), TupletCString(KEY_MENU_NAME_7, FULL_STRING), TupletCString(KEY_MENU_NAME_8, FULL_STRING), TupletCString(KEY_MENU_NAME_9, FULL_STRING), TupletCString(KEY_MENU_NAME_10, FULL_STRING), TupletInteger(KEY_MENU_TOGGLE, 0) };
uint32_t outbound_size = dict_calc_buffer_size_from_tuplets(out_values, ARRAY_LENGTH(out_values)) + FUDGE;
uint32_t inbound_size = dict_calc_buffer_size_from_tuplets(in_values, ARRAY_LENGTH(in_values)) + FUDGE;
LOG_DEBUG("I(%ld) O(%ld)", inbound_size, outbound_size);
// Open buffers
app_message_open(inbound_size, outbound_size);
// Tell JS our version and keep trying until a reply happens
app_timer_register(VERSION_SEND_INTERVAL_MS, send_version, NULL);
}
/*
* Save the config data structure
*/
EXTFN void save_config_data(void *data) {
LOG_DEBUG("save_config_data (%d)", sizeof(config_data));
int written = persist_write_data(PERSIST_CONFIG_KEY, &config_data, sizeof(config_data));
if (written != sizeof(config_data)) {
LOG_ERROR("save_config_data error (%d)", written);
}
save_config_requested = false;
}
/*
* Clear config if needed
*/
static void clear_config_data() {
memset(&config_data, 0, sizeof(config_data));
config_data.config_ver = CONFIG_VER;
strncpy(config_data.entry[0].menu_text, NO_CONFIG_1, MENU_TEXT_LEN);
strncpy(config_data.entry[1].menu_text, NO_CONFIG_2, MENU_TEXT_LEN);
}
/*
* Read the config data (or create it if missing)
*/
EXTFN void read_config_data() {
int read = persist_read_data(PERSIST_CONFIG_KEY, &config_data, sizeof(config_data));
if (read != sizeof(config_data) || config_data.config_ver != CONFIG_VER) {
clear_config_data();
}
}
/*
* Provide config data structure to other units
*/
EXTFN ConfigData *get_config_data() {
return &config_data;
}
/*
* Get the config to save at some point in the future
*/
EXTFN void trigger_config_save() {
if (!save_config_requested) {
app_timer_register(PERSIST_CONFIG_MS, save_config_data, NULL);
save_config_requested = true;
}
}
/*
* Create main window
*/
static void handle_init() {
// Check which defines are defined
#ifdef PBL_SDK_2
LOG_INFO("PBL_SDK_2");
#endif
#ifdef PBL_SDK_3
LOG_INFO("PBL_SDK_3");
#endif
#ifdef PBL_PLATFORM_APLITE
LOG_INFO("PBL_PLATFORM_APLITE");
#endif
#ifdef PBL_PLATFORM_BASALT
LOG_INFO("PBL_PLATFORM_BASALT");
#endif
#ifdef PBL_PLATFORM_CHALK
LOG_INFO("PBL_PLATFORM_CHALK");
#endif
#ifdef PBL_COLOR
LOG_INFO("PBL_COLOR");
#endif
#ifdef PBL_BW
LOG_INFO("PBL_BW");
#endif
#ifdef PBL_ROUND
LOG_INFO("PBL_ROUND");
#endif
#ifdef PBL_RECT
LOG_INFO("PBL_RECT");
#endif
read_config_data();
show_menu();
open_comms();
}
/*
* Main
*/
EXTFN int main(void) {
handle_init();
app_event_loop();
}
| 2.09375 | 2 |
2024-11-18T20:53:29.499519+00:00 | 2021-02-14T00:38:15 | 4b4efdbd61db2386ab40f812dd0d0ffb3def49fb | {
"blob_id": "4b4efdbd61db2386ab40f812dd0d0ffb3def49fb",
"branch_name": "refs/heads/master",
"committer_date": "2021-02-14T00:38:15",
"content_id": "688f90ef68627feb736f3d47b3af15f849339d62",
"detected_licenses": [
"MIT"
],
"directory_id": "29d64a7f18b940d9eb19ed95a5fcb6bf0bbb1f6e",
"extension": "c",
"filename": "mem_3.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 333270511,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1996,
"license": "MIT",
"license_type": "permissive",
"path": "/mem_3.c",
"provenance": "stackv2-0127.json.gz:69508",
"repo_name": "danny-cpp/Memory_space_scanner",
"revision_date": "2021-02-14T00:38:15",
"revision_id": "72c33c1016e83a312e7fec47e4d25828c0bacefe",
"snapshot_id": "59243780b11b8d5bab19623b10cfd75ef17796b1",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/danny-cpp/Memory_space_scanner/72c33c1016e83a312e7fec47e4d25828c0bacefe/mem_3.c",
"visit_date": "2023-03-09T07:12:53.515613"
} | stackv2 | #include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <ftw.h>
#include <unistd.h>
#include <sys/mman.h>
#include "memlayout.h"
/**
* Loading a large data file onto memory via mmap()
* @param path
*/
void mem_loading(const char* path);
/**
* In this example, mmap() a large data file and observe the memory changing. Project includes a
* 300KB json data file as an example. If no argument is provided, the file is default to Tags.json
* @author: Danh Nguyen
* @return
*/
int main(int argc, char *argv[]) {
const char* path;
if (argc > 2) {
printf("Too many arguments!\n");
exit(-1);
}
if (argc == 2)
path = argv[1];
else
path = "Tags.json\0";
unsigned int array_size = 20;
struct memregion* before = (struct memregion*)malloc(array_size * sizeof(struct memregion));
struct memregion* after = (struct memregion*)malloc(array_size * sizeof(struct memregion));
printf("\nMemory before mmap():\n");
int status = get_mem_layout(before, array_size);
for (unsigned int i = 0; i < array_size; i++) {
print_memregion(before[i]);
}
printf("\nLoading file \"%s\" to memory\n", path);
mem_loading(path);
get_mem_layout(after, array_size);
for (unsigned int i = 0; i < array_size; i++) {
print_memregion(after[i]);
}
memregion_compare(before, after, array_size);
}
void mem_loading(const char* path) {
struct stat buffer;
int fd = open(path, O_RDONLY);
if (fd < 0) {
printf("Can't open\n");
exit(1);
}
int error = fstat(fd, &buffer);
if (error < 0) {
printf("error");
exit(2);
}
char *ptr = mmap(NULL,buffer.st_size,
PROT_READ,
MAP_SHARED,
fd,0);
if(ptr == MAP_FAILED){
printf("Mapping Failed\n");
return;
}
close(fd);
printf("Successfully mapped!\n");
printf("====================\n");
}
| 2.96875 | 3 |
2024-11-18T20:53:29.802623+00:00 | 2012-05-18T18:01:32 | af2f7dc9e369c19742117ccb8af762fa0f997c5c | {
"blob_id": "af2f7dc9e369c19742117ccb8af762fa0f997c5c",
"branch_name": "refs/heads/master",
"committer_date": "2012-05-18T18:01:32",
"content_id": "8d3c13f8584059f7cbad4c7b126072651f9f6077",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "70bb6f17419472d6d4c664be2a204139ff93a858",
"extension": "c",
"filename": "memoria.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": 473,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/capivara/memoria.c",
"provenance": "stackv2-0127.json.gz:69896",
"repo_name": "paulourio/capivara",
"revision_date": "2012-05-18T18:01:32",
"revision_id": "e72a7dc24002b524f05004a462857e0b12bbc177",
"snapshot_id": "223c827a2402dc77105145d862c7e714dcb7f146",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/paulourio/capivara/e72a7dc24002b524f05004a462857e0b12bbc177/capivara/memoria.c",
"visit_date": "2021-05-26T12:20:41.989300"
} | stackv2 | #include "servidor.h"
int realocar(char **ptr, int atual, int novo)
{
int incremento = novo - atual;
debug("Realocando memória para %i bytes", novo);
debug(" (+ %i bytes)... ", incremento);
fflush(stdout);
char *novoptr = realloc(*ptr, novo);
if (novoptr == NULL) {
debug("ERRO: Sem memória para alocar.\r\n");
return ERRO;
}
if (novoptr != *ptr) {
debug("(%p -> %p)", *ptr, novoptr);
*ptr = novoptr;
}
debug("\r\n");
fflush(stdout);
return OK;
}
| 3.15625 | 3 |
2024-11-18T20:53:29.954575+00:00 | 2014-09-29T03:30:08 | 9f8542fa432c32e255783dbd79a0b23a9187b046 | {
"blob_id": "9f8542fa432c32e255783dbd79a0b23a9187b046",
"branch_name": "refs/heads/master",
"committer_date": "2014-09-29T03:30:08",
"content_id": "333e188d6603a7a59a0b0abcaff4c9143b473bce",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "ae22f3370f4937d591b033da6548c86d7ee1b573",
"extension": "c",
"filename": "adlist.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": 18434,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/src/adlist.c",
"provenance": "stackv2-0127.json.gz:70153",
"repo_name": "ymsdu2004/redis-2.8.14",
"revision_date": "2014-09-29T03:30:08",
"revision_id": "18b9e5a501458853b3c9caa0b8765dc3ba62570f",
"snapshot_id": "13d7977b37740e096182c84c0f5d56ad0889bc5f",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ymsdu2004/redis-2.8.14/18b9e5a501458853b3c9caa0b8765dc3ba62570f/src/adlist.c",
"visit_date": "2016-09-05T14:28:01.505280"
} | stackv2 | /* adlist.c - A generic doubly linked list implementation
*
* Copyright (c) 2006-2010, Salvatore Sanfilippo <antirez at gmail dot com>
* 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 Redis nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <stdlib.h>
#include "adlist.h"
#include "zmalloc.h"
/* Create a new list. The created list can be freed with
* AlFreeList(), but private value of every node need to be freed
* by the user before to call AlFreeList().
*
* On error, NULL is returned. Otherwise the pointer to the new list. */
/***
* 创建一个新的链表(内部分配list结构体空间)
* Note: 返回的list在不需要时候调用listRelease释放
* @return: 成功则返回链表指针, 失败则返回NULL
*/
list *listCreate(void)
{
struct list *list;
/* 开辟链表结构体空间 */
if ((list = zmalloc(sizeof(*list))) == NULL)
return NULL;
/* 头尾指针均初始化为NULL */
list->head = list->tail = NULL;
/* 初始链表长度肯定为0 */
list->len = 0;
/* 三个与数据相关的操作函数均设置为空, 如有必要用户可以在之后设置 */
list->dup = NULL;
list->free = NULL;
list->match = NULL;
return list;
}
/***
* 释放整个链表, 包括所有节点元素和list结构体本身(listCreate创建的)
* @list[IN]: 有效链表指针
*/
void listRelease(list *list)
{
unsigned long len;
listNode *current, *next;
current = list->head;
len = list->len;
while(len--) {
/* 记录下一个节点 */
next = current->next;
/* 如果链表设置了数据析构函数, 则删除节点本身之前先调用析构函数析构数据 */
if (list->free) list->free(current->value);
/* 释放节点本身*/
zfree(current);
/* 当前节点移到下一个节点 */
current = next;
}
/* 最后释放链表结构体本身 */
zfree(list);
}
/***
* 在链表头部插入新节点, 插入失败维持链表原来状态
* @list[IN]: 有效链表指针
* @value[IN]: 新增节点的数据值
* @return: 成功则返回添加节点后的链表的指针, 失败则返回NULL
*/
list *listAddNodeHead(list *list, void *value)
{
listNode *node;
/* 分配节点空间, 失败直接返回NULL */
if ((node = zmalloc(sizeof(*node))) == NULL)
return NULL;
/* 节点数据指针指向用户给出的数据 */
node->value = value;
/* 如果链表当前长度为0, 说明该添加的元素是链表的第一个元素 */
if (list->len == 0) {
/* 头尾指针都指向该新增的节点 */
list->head = list->tail = node;
/* 本节点的前一个节点和下一个节点的指针都为NULL */
node->prev = node->next = NULL;
} else { /* 如果新增节点不是链表的第一个节点 */
/* 本节点的前一个元素节点设置为NULL */
node->prev = NULL;
/* 本节点的下一个节点指针设置为链表之前的头结点 */
node->next = list->head;
/* 链表之前的头结点的前一个节点指针指向新增节点 */
list->head->prev = node;
/* 新增节点现在作为链表的头节点了, 尾指针不用动,
* 因为新增节点是插在表头的, 不会影响尾指针
*/
list->head = node;
}
/* 成功插入后, 链表元素增1 */
list->len++;
/* 返回新增节点后的链表指针 */
return list;
}
/***
* 在链表尾部添加新节点, 失败保证维持链表原状
* @list[IN]: 有效链表指针
* @value[IN]: 新增节点的数据值
* @return: 成功则返回添加节点后的链表的指针, 失败则返回NULL
*/
list *listAddNodeTail(list *list, void *value)
{
listNode *node;
/* 分配新增节点的空间, 失败则返回NULL */
if ((node = zmalloc(sizeof(*node))) == NULL)
return NULL;
/* 用户数据赋值给节点的数据指针 */
node->value = value;
/* 如果链表当前长度为0, 说明链表为空, 此新增元素为第一个元素 */
if (list->len == 0) {
/* 链表头尾指针均指向该新增节点 */
list->head = list->tail = node;
/* 新增节点的前后节点指针均指向NULL */
node->prev = node->next = NULL;
} else { /* 如果链表当前不为空 */
/* 新增节点的前指针指向当前链表尾指针所指的元素 */
node->prev = list->tail;
/* 新增节点的后指针为NULL */
node->next = NULL;
/* 链表的为指针指向的节点(即之前的最后一个节点)的后指针指向新增节点 */
list->tail->next = node;
/* 链表的尾指针现在指向新增的节点, 头指针不会影响, 因为新增节点是在尾部添加 */
list->tail = node;
}
/* 成功插入后, 链表元素增1 */
list->len++;
/* 返回新增节点后的链表指针 */
return list;
}
/***
* 在指定节点之前或之后插入新节点
* @list[IN]: 有效链表指针
* @old_value[IN]: 插入参考节点
* @value[IN]: 新增节点的数据值
* @after[IN]: 指示在指定节点之前还是之后插入节点
* @return: 成功则返回添加节点后的链表的指针, 失败则返回NULL
*/
list *listInsertNode(list *list, listNode *old_node, void *value, int after) {
listNode *node;
/* 分配新节点空间 */
if ((node = zmalloc(sizeof(*node))) == NULL)
return NULL;
/* 节点数据指针赋值 */
node->value = value;
/* 如果是在参考节点之后插入新节点 */
if (after) {
/* 新增节点的前节点指针指向参考节点 */
node->prev = old_node;
/* 新增节点的后节点指针指向参考节点当前的后节点 */
node->next = old_node->next;
/* 如果参考节点是尾节点, 则链表的为节点指针指向新增节点 */
if (list->tail == old_node) {
list->tail = node;
}
} else { /* 如果是在参考节点之前插入新节点 */
/* 新增节点的后节点指针指向参考节点 */
node->next = old_node;
/* 新增节点的前节点指针指向参考节点的前节点 */
node->prev = old_node->prev;
/* 如果参考节点就是头节点, 则链表的头指针变更为新增节点 */
if (list->head == old_node) {
list->head = node;
}
}
/* 如果新增节点的前节点指针存在, 则将前节点的后节点指针指向新增节点 */
if (node->prev != NULL) {
node->prev->next = node;
}
/* 如果新增节点的后节点指针存在, 则将后节点的前节点指针指向新增节点 */
if (node->next != NULL) {
node->next->prev = node;
}
/* 成功插入后, 链表元素增1 */
list->len++;
/* 返回新增节点后的链表指针 */
return list;
}
/* Remove the specified node from the specified list.
* It's up to the caller to free the private value of the node.
*
* This function can't fail. */
/***
* 从链表中删除指定的节点
* @list[IN]: 有效链表指针
* @node[IN]: 要删除的节点指针
*/
void listDelNode(list *list, listNode *node)
{
/* 如果此节点有前节点, 则将其前节点的后节点指针指向此节点的后节点 */
if (node->prev)
node->prev->next = node->next;
else /* 如果此节点没有前节点, 说明是删除表头节点, 则要将头指针指向此节点的后节点 */
list->head = node->next;
if (node->next) /* 如果此节点有后节点, 则将其后节点的前节点指针指向此节点的前节点 */
node->next->prev = node->prev;
else /* 如果此节点没有后节点, 则说明是删除表尾指针, 则要将尾指针指向此节点的前节点 */
list->tail = node->prev;
/* 如果此链表设置的节点数据析构函数, 则先析构节点数据 */
if (list->free) list->free(node->value);
/* 最后释放节点自身空间 */
zfree(node);
/* 链表长度减1 */
list->len--;
}
/* Returns a list iterator 'iter'. After the initialization every
* call to listNext() will return the next element of the list.
*
* This function can't fail.
*/
/***
* 创建链表给定方向的迭代器
* @list[IN]: 有效链表指针
* @direction[IN]: 迭代器的方向
* @return: 成功则返回迭代器的指针, 失败则返回NULL
*/
listIter *listGetIterator(list *list, int direction)
{
listIter *iter;
/* 分配此迭代器空间 */
if ((iter = zmalloc(sizeof(*iter))) == NULL) return NULL;
/* 如果是Forward迭代器, 则迭代器的下一个元素指针指向头结点 */
if (direction == AL_START_HEAD)
iter->next = list->head;
else /* 如果是Backward迭代器, 则迭代器的下一个元素指针指向尾节点 */
iter->next = list->tail;
/* 记录迭代器的方向, 以便迭代进行时确定next的走向 */
iter->direction = direction;
return iter;
}
/* Release the iterator memory */
/***
* 释放迭代器, 仅仅是释放其自身的内存, 没有其他操作
* @iter[IN]: 有效链表迭代器
*/
void listReleaseIterator(listIter *iter) {
zfree(iter);
}
/* Create an iterator in the list private iterator structure */
/***
* 重置迭代器为Forward迭代器(方向为Forward, 下一个节点初始为头结点)
* @list[IN]: 有效链表指针
* @li[IN]: 有效链表迭代器指针
*/
void listRewind(list *list, listIter *li) {
li->next = list->head;
li->direction = AL_START_HEAD;
}
/***
* 重置迭代器为Backward迭代器(方向为Backward, 下一个节点初始化为尾节点)
* @list[IN]: 有效链表指针
* @li[IN]: 有效链表迭代器指针
*/
void listRewindTail(list *list, listIter *li) {
li->next = list->tail;
li->direction = AL_START_TAIL;
}
/* Return the next element of an iterator.
* It's valid to remove the currently returned element using
* listDelNode(), but not to remove other elements.
*
* The function returns a pointer to the next element of the list,
* or NULL if there are no more elements, so the classical usage patter
* is:
*
* iter = listGetIterator(list,<direction>);
* while ((node = listNext(iter)) != NULL) {
* doSomethingWith(listNodeValue(node));
* }
*
* */
/***
* 链表迭代器获取下一个节点
* @iter[IN]: 有效链表迭代器
* @return: 如果还有下一个节点, 则返回下一个节点, 如果没有则返回NULL(迭代到链表的尾部了)
*/
listNode *listNext(listIter *iter)
{
/* 获取迭代器的下一个节点 */
listNode *current = iter->next;
/* 如果下一个节点不为空 */
if (current != NULL) {
/* 方向为Forward, 则迭代器向前迭代一步 */
if (iter->direction == AL_START_HEAD)
iter->next = current->next;
else /* 方向为Backward, 则迭代器向后迭代一步 */
iter->next = current->prev;
}
/* 返回当前迭代的节点或者NULL */
return current;
}
/* Duplicate the whole list. On out of memory NULL is returned.
* On success a copy of the original list is returned.
*
* The 'Dup' method set with listSetDupMethod() function is used
* to copy the node value. Otherwise the same pointer value of
* the original node is used as value of the copied node.
*
* The original list both on success or error is never modified. */
/***
* 拷贝给定链表的一个副本, list结构本身和各个节点及数据都重新分配空间
* @orig[IN]: 将要被拷贝的链表
* @return[IN]: 成功则返回拷贝的新链表, 失败则返回NULL
*/
list *listDup(list *orig)
{
list *copy;
listIter *iter;
listNode *node;
/* 创建一个新的空链表 */
if ((copy = listCreate()) == NULL)
return NULL;
/* 将原来链表的一些用户设置的数据操作方法复制给新建链表 */
copy->dup = orig->dup;
copy->free = orig->free;
copy->match = orig->match;
/* 创建原链表的迭代器 */
iter = listGetIterator(orig, AL_START_HEAD);
/* 迭代器遍历原链表的每个节点 */
while((node = listNext(iter)) != NULL) {
void *value;
/* 如果链表设置了节点数据拷贝函数, 则调用该函数拷贝数据 */
if (copy->dup) {
/* 拷贝函数返回拷贝的数据的指针 */
value = copy->dup(node->value);
/* 如果拷贝失败, 则释放拷贝链表及原链表迭代器, 返回失败 */
if (value == NULL) {
listRelease(copy);
listReleaseIterator(iter);
return NULL;
}
} else /* 如果没有拷贝函数, 则直接赋值原链表节点的数据指针 */
value = node->value;
/* 将拷贝的节点添加到新链表的尾部, 如果失败则返回NULL */
if (listAddNodeTail(copy, value) == NULL) {
listRelease(copy);
listReleaseIterator(iter);
return NULL;
}
}
/* 最后释放原链表迭代器 */
listReleaseIterator(iter);
/* 返回拷贝的新链表 */
return copy;
}
/* Search the list for a node matching a given key.
* The match is performed using the 'match' method
* set with listSetMatchMethod(). If no 'match' method
* is set, the 'value' pointer of every node is directly
* compared with the 'key' pointer.
*
* On success the first matching node pointer is returned
* (search starts from head). If no matching node exists
* NULL is returned. */
/***
* 查找给定关键字关联的节点(如果存在多个, 则返回第一个找到的)
* @list[IN]: 有效链表指针
* @key[IN]: 查找的关键字
* @return: 如果找到匹配的节点, 则返回该节点指针, 否则返回NULL
*/
listNode *listSearchKey(list *list, void *key)
{
listIter *iter;
listNode *node;
/* 创建链表迭代器 */
iter = listGetIterator(list, AL_START_HEAD);
/* 迭代器遍历链表 */
while((node = listNext(iter)) != NULL) {
/* 如果链表设置了节点数据匹配比较函数 */
if (list->match) {
/* 则调用匹配函数比较该节点的数据和给出的key是否匹配 */
if (list->match(node->value, key)) {
/* 如果匹配, 则找到了, 不必再查找, 直接返回该匹配的节点 */
listReleaseIterator(iter);
return node;
}
} else { /* 如果用户没有设置链表节点数据的匹配函数, 则直接比较数据指针 */
if (key == node->value) {
listReleaseIterator(iter);
return node;
}
}
}
/* 最后没有找到则返回NULL */
listReleaseIterator(iter);
return NULL;
}
/* Return the element at the specified zero-based index
* where 0 is the head, 1 is the element next to head
* and so on. Negative integers are used in order to count
* from the tail, -1 is the last element, -2 the penultimate
* and so on. If the index is out of range NULL is returned. */
/***
* 获取链表中某个索引处对应的节点
* 正向索引(>=0): 从表头开始向后计算, 表头节点索引为0, 往后依次增1即(0, 1, 2, ...)
* 逆向索引(<0): 从表位开始向前计算, 表尾节点索引为-1, 往后依次减1, 即(-1, -2, -3, ...)
* @list[IN]: 有效链表指针
* @index[IN]: 链表节点索引
* @return: 如果存在则返回对应的节点, 不存在则返回NULL
*/
listNode *listIndex(list *list, long index) {
listNode *n;
/* 如果索引是负值, 则说明是逆向索引 */
if (index < 0) {
index = (-index)-1;
/* 从表尾开始向前计算 */
n = list->tail;
while(index-- && n) n = n->prev;
} else { /* 索引是正值或0, 则说明是正向索引 */
n = list->head;
/* 从表头开始向后计算 */
while(index-- && n) n = n->next;
}
return n;
}
/* Rotate the list removing the tail node and inserting it to the head. */
/***
* 旋转链表, 将链表的为节点旋转到链表的头部
* @list[IN]: 有效链表指针
*/
void listRotate(list *list) {
/* 保存当前尾节点的指针, 后面要用 */
listNode *tail = list->tail;
/* 如果链表的为空或者只有一个节点, 则不用处理 */
if (listLength(list) <= 1) return;
/* Detach current tail */
/* 将链表的尾节点从链表尾部删除 */
/* 链表的尾指针指向当前尾节点的上一个节点 */
list->tail = tail->prev;
/* 新的尾节点的后节点指针为NULL */
list->tail->next = NULL;
/* Move it as head */
/* 再将该为节点插入到链表的头部 */
/* 将链表头节点的前节点指针指向原来的尾节点 */
list->head->prev = tail;
/* 原来的尾节点的前节点指针为NULL */
tail->prev = NULL;
/* 原来的为节点的后节点指针指向原链表的头节点 */
tail->next = list->head;
/* 链表原来的为节点称为链表新的头结点 */
list->head = tail;
}
| 2.609375 | 3 |
2024-11-18T20:53:30.111881+00:00 | 2020-05-02T20:53:15 | b84a6a3e837d03d771d799833a27b6167a6b30a7 | {
"blob_id": "b84a6a3e837d03d771d799833a27b6167a6b30a7",
"branch_name": "refs/heads/master",
"committer_date": "2020-05-02T20:53:15",
"content_id": "cf6dc5e9c48eb9ffb960ed80136bc02f2f96581f",
"detected_licenses": [
"MIT"
],
"directory_id": "b03da9219d0b9045610e9a975ee139fdc953d268",
"extension": "c",
"filename": "ignore.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 260773118,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1359,
"license": "MIT",
"license_type": "permissive",
"path": "/sas-client/src/drivers/ignore.c",
"provenance": "stackv2-0127.json.gz:70282",
"repo_name": "fabianishere/sas",
"revision_date": "2020-05-02T20:53:15",
"revision_id": "84c15d77988fac5a173f766d866d90666b529bc1",
"snapshot_id": "4a39ba3687b0adc3dc90727aebdb11fdc2f3ccd4",
"src_encoding": "UTF-8",
"star_events_count": 4,
"url": "https://raw.githubusercontent.com/fabianishere/sas/84c15d77988fac5a173f766d866d90666b529bc1/sas-client/src/drivers/ignore.c",
"visit_date": "2022-05-26T01:02:37.036429"
} | stackv2 | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <rxc/rxc.h>
#include <rxc/logic.h>
#include <sas/chunk.h>
static void dealloc(struct rxc_sink *self, int shallow)
{
free(self);
}
static void on_connect(struct rxc_sink_logic *self)
{
rxc_inlet_pull(self->in, 1);
}
static void on_push(struct rxc_sink_logic *self, void *element)
{
struct sas_chunk *chunk = element;
sas_chunk_dealloc(chunk);
rxc_inlet_pull(self->in, 1);
}
static void on_upstream_finish(struct rxc_sink_logic *self)
{}
static void on_upstream_failure(struct rxc_sink_logic *self, void *failure)
{
free(failure);
}
static struct rxc_sink_logic * create_logic(struct rxc_sink *self)
{
struct rxc_sink_logic *logic = malloc(sizeof(struct rxc_sink_logic));
if (!logic) {
return NULL;
}
logic->sink = self;
logic->dealloc = (void (*)(struct rxc_sink_logic *)) free;
logic->on_connect = on_connect;
logic->on_push = on_push;
logic->on_upstream_finish = on_upstream_finish;
logic->on_upstream_failure = on_upstream_failure;
return logic;
}
struct rxc_sink * sas_drivers_ignore()
{
struct rxc_sink *sink = malloc(sizeof(struct rxc_sink));
if (!sink) {
return NULL;
}
sink->dealloc = dealloc;
sink->create_logic = create_logic;
return sink;
}
| 2.265625 | 2 |
2024-11-18T20:53:30.282309+00:00 | 2020-03-20T01:20:02 | e98cf8a487f704dd9d6e4a3c5257da8481f71f48 | {
"blob_id": "e98cf8a487f704dd9d6e4a3c5257da8481f71f48",
"branch_name": "refs/heads/master",
"committer_date": "2020-03-20T01:20:02",
"content_id": "eafbf2f2733d629f76c788539ec84f778a60e015",
"detected_licenses": [
"BSD-3-Clause",
"BSD-2-Clause"
],
"directory_id": "8f416d9e73092164f5be46716516b1ac7eb22d9f",
"extension": "c",
"filename": "spisdcard.c",
"fork_events_count": 0,
"gha_created_at": "2020-03-20T07:27:34",
"gha_event_created_at": "2020-03-20T07:27:35",
"gha_language": null,
"gha_license_id": "NOASSERTION",
"github_id": 248693468,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 24771,
"license": "BSD-3-Clause,BSD-2-Clause",
"license_type": "permissive",
"path": "/litex/soc/software/libbase/spisdcard.c",
"provenance": "stackv2-0127.json.gz:70540",
"repo_name": "minisparrow/litex",
"revision_date": "2020-03-20T01:20:02",
"revision_id": "fbadfa176448ff134e26c843a9d8501a159ed833",
"snapshot_id": "28ca083c5182b323dc57274d9699ecadd222e3e8",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/minisparrow/litex/fbadfa176448ff134e26c843a9d8501a159ed833/litex/soc/software/libbase/spisdcard.c",
"visit_date": "2021-04-07T17:29:52.052178"
} | stackv2 | // SD CARD bitbanging code for loading files from a FAT16 forrmatted partition into memory
//
// Code is known to work on a de10nano with MiSTer SDRAM and IO Boards - IO Board has a secondary SD CARD interface connected to GPIO pins
// SPI signals CLK, CS and MOSI are configured as GPIO output pins, and MISO is configued as GPIO input pins
//
// Protocol details developed from https://openlabpro.com/guide/interfacing-microcontrollers-with-sd-card/
//
// FAT16 details developed from https://codeandlife.com/2012/04/02/simple-fat-and-sd-tutorial-part-1/ and https://codeandlife.com/2012/04/07/simple-fat-and-sd-tutorial-part-2/
// Import LiteX SoC details that are generated each time the SoC is compiled for the FPGA
// csr defines the SPI Control registers
// soc defines the clock CONFIG_CLOCK_FREQUENCY (50MHz for the VexRiscV processor on the MiSTer FPGA
// mem defines the addresses for the SDRAM MAIN_RAM_BASE and MAIN_RAM_SIZE
#include <generated/csr.h>
#include <generated/soc.h>
#include <generated/mem.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#ifdef CSR_SPISDCARD_BASE
// Import prototypes for the functions
#include <spisdcard.h>
// SPI
// cs line - high to indicate DESELECT
// - low to indicate SELECT
#define CS_HIGH 0x00
#define CS_LOW 0x01
// control register values
// onebyte to indicate 1 byte being transferred
// spi_start to indicate START of transfer
// spi_done to indicate transfer DONE
#define ONEBYTE 0x0800
#define SPI_START 0x01
#define SPI_DONE 0x01
// Return values
#define SUCCESS 0x01
#define FAILURE 0x00
// spi_write_byte
// Send a BYTE (8bits) to the SD CARD
// Seqeunce
// Set MOSI
// Set START bit and LENGTH=8
// Await DONE
//
// No return values
//
// Details from https://openlabpro.com/guide/interfacing-microcontrollers-with-sd-card/ section "SD Commands"
void spi_write_byte(unsigned char char_to_send);
void spi_write_byte(unsigned char char_to_send)
{
// Place data into MOSI register
// Pulse the START bit and set LENGTH=8
spisdcard_mosi_write(char_to_send);
spisdcard_control_write(ONEBYTE | SPI_START);
// Wait for DONE
while( (spisdcard_status_read() != SPI_DONE)) {}
// Signal end of transfer
spisdcard_control_write( 0x00 );
}
// spi_read_rbyte
// Read a command response from the SD CARD - Equivalent to and R1 response or first byte of an R7 response
// Sequence
// Read MISO
// If MSB != 0 then send dsummy byte and re-read MISO
//
// Return value is the response from the SD CARD
// If the MSB is not 0, this would represent an ERROR
// Calling function to determine if the correct response has been received
//
// Details from https://openlabpro.com/guide/interfacing-microcontrollers-with-sd-card/ section "SD Commands"
unsigned char spi_read_rbyte(void);
unsigned char spi_read_rbyte(void)
{
int timeout=32;
unsigned char r=0;
// Check if MISO is 0x0xxxxxxx as MSB=0 indicates valid response
r = spisdcard_miso_read();
while( ((r&0x80)!=0) && timeout>0) {
spisdcard_mosi_write( 0xff );
spisdcard_control_write(ONEBYTE | SPI_START);
while( (spisdcard_status_read() != SPI_DONE)) {}
r = spisdcard_miso_read();
spisdcard_control_write( 0x00 );
timeout--;
}
// printf("Done\n");
return r;
}
// spi_read_byte
// Sequence
// Send dummy byte
// Read MISO
//
// Read subsequenct bytes from the SD CARD - MSB first
// NOTE different from the spi_read_rbyte as no need to await an intial 0 bit as card is already responsing
// Used to read additional response bytes, or data bytes from the SD CARD
//
// Return value is the byte read
// NOTE no error status as assumed bytes are read via CLK pulses
//
// Details from https://openlabpro.com/guide/interfacing-microcontrollers-with-sd-card/ section "SD Commands"
unsigned char spi_read_byte(void);
unsigned char spi_read_byte(void)
{
unsigned char r=0;
spi_write_byte( 0xff );
r = spisdcard_miso_read();
return r;
}
// SETSPIMODE
// Signal the SD CARD to switch to SPI mode
// Pulse the CLK line HIGH/LOW repeatedly with MOSI and CS_N HIGH
// Drop CS_N LOW and pulse the CLK
// Check MISO for HIGH
// Return 0 success, 1 failure
//
// Details from https://openlabpro.com/guide/interfacing-microcontrollers-with-sd-card/ section "Initializing the SD Card"
unsigned char spi_setspimode(void);
unsigned char spi_setspimode(void)
{
unsigned int i, r, timeout=32;
// Initialise SPI mode
// set CS to HIGH
// Send pulses
do {
// set CS HIGH and send pulses
spisdcard_cs_write(CS_HIGH);
for (i=0; i<10; i++) {
spi_write_byte( 0xff );
}
// set CS LOW and send pulses
spisdcard_cs_write(CS_LOW);
r = spi_read_rbyte();
timeout--;
} while ( (timeout>0) && (r==0) );
if(timeout==0) return FAILURE;
return SUCCESS;
}
// SPI_SDCARD_GOIDLE
// Function exposed to BIOS to initialise SPI mode
//
// Sequence
// Set 100KHz timer mode
// Send CLK pulses to set SD CARD to SPI mode
// Send CMD0 - Software RESET - force SD CARD IDLE
// Send CMD8 - Check SD CARD type
// Send CMD55+ACMD41 - Force SD CARD READY
// Send CMD58 - Read SD CARD OCR (status register)
// Send CMD16 - Set SD CARD block size to 512 - Sector Size for the SD CARD
// NOTE - Each command is prefixed with a dummy set of CLK pulses to prepare SD CARD to receive a command
// Return 0 success, 1 failure
//
// Details from https://openlabpro.com/guide/interfacing-microcontrollers-with-sd-card/ section "Initializing the SD Card"
unsigned char spi_sdcard_goidle(void)
{
unsigned char r; // Response from SD CARD
int i, timeout; // TIMEOUT loop to send CMD55+ACMD41 repeatedly
r = spi_setspimode(); // Set SD CARD to SPI mode
if( r != 0x01 ) return FAILURE;
// CMD0 - Software reset - SD CARD IDLE
// Command Sequence is DUMMY=0xff CMD0=0x40 0x00 0x00 0x00 0x00 CRC=0x95
// Expected R1 response is 0x01 indicating SD CARD is IDLE
spi_write_byte( 0xff ); spi_write_byte( 0x40 ); spi_write_byte( 0x00 ); spi_write_byte( 0x00 ); spi_write_byte( 0x00 ); spi_write_byte( 0x00 ); spi_write_byte( 0x95 );
r = spi_read_rbyte();
if(r!=0x01) return FAILURE;
// CMD8 - Check SD CARD type
// Command sequence is DUMMY=0xff CMD8=0x48 0x00 0x00 0x01 0xaa CRC=0x87
// Expected R7 response is 0x01 followed by 0x00 0x00 0x01 0xaa (these trailing 4 bytes not currently checked)
spi_write_byte( 0xff ); spi_write_byte( 0x48 ); spi_write_byte( 0x00 ); spi_write_byte( 0x00 ); spi_write_byte( 0x01 ); spi_write_byte( 0xaa ); spi_write_byte( 0x87 );
r = spi_read_rbyte();
if(r!=0x01) return FAILURE;
// Receive the trailing 4 bytes for R7 response - FIXME should check for 0x00 0x00 0x01 0xaa
for(i=0; i<4; i++)
r=spi_read_byte();
// CMD55+ACMD41 - Force SD CARD READY - prepare card for reading/writing
// Command sequence is CMD55 followed by ACMD41
// Send commands repeatedly until SD CARD indicates READY 0x00
// CMD55 Sequence is DUMMY=0xff CMD55=0x77 0x00 0x00 0x00 0x00 CRC=0x00
// ACMD41 Sequence is DUMMY=0xff ACMD41=0x69 0x40 0x00 0x00 0x00 CRC=0x00
// Expected R1 response is 0x00 indicating SD CARD is READY
timeout=32;
do {
spi_write_byte( 0xff ); spi_write_byte( 0x77 ); spi_write_byte( 0x00 ); spi_write_byte( 0x00 ); spi_write_byte( 0x00 ); spi_write_byte( 0x00 ); spi_write_byte( 0x00 );
r = spi_read_rbyte();
spi_write_byte( 0xff ); spi_write_byte( 0x69 ); spi_write_byte( 0x40 ); spi_write_byte( 0x00 ); spi_write_byte( 0x00 ); spi_write_byte( 0x00 ); spi_write_byte( 0x00 );
r = spi_read_rbyte();
timeout--;
} while ((r != 0x00) && (timeout>0));
if(r!=0x00) return FAILURE;
// CMD58 - Read SD CARD OCR (status register)
// FIXME - Find details on expected response from CMD58 to allow accurate checking of SD CARD R3 response
// Command sequence is DUMMY=0xff CMD58=0x7a 0x00 0x00 0x01 0xaa CRC=0xff
// Expected R3 response is 0x00 OR 0x01 followed by 4 (unchecked) trailing bytes
spi_write_byte( 0xff ); spi_write_byte( 0x7a ); spi_write_byte( 0x00 ); spi_write_byte( 0x00 ); spi_write_byte( 0x00 ); spi_write_byte( 0x00 ); spi_write_byte( 0xff );
r = spi_read_rbyte();
if(r>0x01) return FAILURE;
// // Receive the trailing 4 bytes for R3 response
for(i=0; i<4; i++)
r=spi_read_byte();
// CMD16 - Set SD CARD block size to 512 - Sector Size for the SD CARD
// Command Sequence is DUMMY=0xff (512 as unsigned long = 0x00000200) 0x00 0x00 0x02 0x00 CRC=0xff
// Expected R1 response is 0x00 indicating SD CARD is READY
spi_write_byte( 0xff ); spi_write_byte( 0x50 ); spi_write_byte( 0x00 ); spi_write_byte( 0x00 ); spi_write_byte( 0x02 ); spi_write_byte( 0x00 ); spi_write_byte( 0xff );
r=spi_read_rbyte();
if(r!=0x00) return FAILURE;
return SUCCESS;
}
// READSECTOR
// Read a 512 byte sector from the SD CARD
// Given SECTORNUMBER and memory STORAGE
//
// Sequence
// Send CMD17 - Read Block
// Command Sequence is DUMMY=0xff CMD17=0x51 SECTORNUMBER (32bit UNSIGNED as bits 32-25,24-17, 16-9, 8-1) CRC=0xff
// Wait for SD CARD to send 0x00 indicating SD CARD is processing
// Wait for SD CARD to send 0xfe indicating SD CARD BLOCK START
// Read 512 bytes
// Read 8 DUMMY bytes
// Return 0 success, 1 failure
//
// Details from https://openlabpro.com/guide/interfacing-microcontrollers-with-sd-card/ section "Read/Write SD Card"
unsigned char readSector(unsigned int sectorNumber, unsigned char *storage);
unsigned char readSector(unsigned int sectorNumber, unsigned char *storage)
{
unsigned int n,timeout; // Number of bytes loop, timeout loop awaiting response bytes
unsigned char r; // Response bytes from SD CARD
// CMD17 - Read Block
// Command Sequence is DUMMY=0xff CMD17=0x51 SECTORNUMBER (32bit UNSIGNED as bits 32-25,24-17, 16-9, 8-1) CRC=0xff
// Expected R1 response is 0x00 indicating SD CARD is processing
spi_write_byte( 0xff ); spi_write_byte( 0x51 ); spi_write_byte( (sectorNumber>>24)&0xff ); spi_write_byte( (sectorNumber>>16)&0xff ); spi_write_byte( (sectorNumber>>8)&0xff ); spi_write_byte( (sectorNumber)&0xff ); spi_write_byte( 0xff );
r=spi_read_rbyte();
if( r!=0x00 ) return FAILURE;
// Await 0xfe to indicate BLOCK START
r=spi_read_byte();
timeout=16384;
while( (r!=0xfe) && (timeout>0) ) {
r=spi_read_byte();
timeout--;
}
if( r!=0xfe ) return FAILURE;
// Read 512 bytes into storage
for(n=0; n<512; n++)
storage[n]=spi_read_byte();
// Read 8 dummy bytes
for(n=0; n<8; n++)
r=spi_read_byte();
return SUCCESS;
}
// FAT16 Specific code starts here
// Details from https://codeandlife.com/2012/04/02/simple-fat-and-sd-tutorial-part-1/
// Structure to store SD CARD partition table
typedef struct {
unsigned char first_byte;
unsigned char start_chs[3];
unsigned char partition_type;
unsigned char end_chs[3];
unsigned long start_sector;
unsigned long length_sectors;
} __attribute((packed)) PartitionTable;
PartitionTable sdCardPartition;
// Structure to store SD CARD FAT16 Boot Sector (boot code is ignored, provides layout of the FAT16 partition on the SD CARD)
typedef struct {
unsigned char jmp[3];
char oem[8];
unsigned short sector_size;
unsigned char sectors_per_cluster;
unsigned short reserved_sectors;
unsigned char number_of_fats;
unsigned short root_dir_entries;
unsigned short total_sectors_short; // if zero, later field is used
unsigned char media_descriptor;
unsigned short fat_size_sectors;
unsigned short sectors_per_track;
unsigned short number_of_heads;
unsigned long hidden_sectors;
unsigned long total_sectors_long;
unsigned char drive_number;
unsigned char current_head;
unsigned char boot_signature;
unsigned long volume_id;
char volume_label[11];
char fs_type[8];
char boot_code[448];
unsigned short boot_sector_signature;
} __attribute((packed)) Fat16BootSector;
Fat16BootSector sdCardFatBootSector;
// Structure to store SD CARD FAT16 Root Directory Entries
// Allocated to MAIN RAM - hence pointer
typedef struct {
unsigned char filename[8];
unsigned char ext[3];
unsigned char attributes;
unsigned char reserved[10];
unsigned short modify_time;
unsigned short modify_date;
unsigned short starting_cluster;
unsigned long file_size;
} __attribute((packed)) Fat16Entry;
Fat16Entry *sdCardFat16RootDir;
// Structure to store SD CARD FAT16 Entries
// Array of UNSIGNED SHORTS (16bit integers)
unsigned short *sdCardFatTable;
// Calculated sector numbers on the SD CARD for the FAT16 Entries and ROOT DIRECTORY
unsigned int fatSectorStart, rootDirSectorStart;
// Storage for SECTOR read from SD CARD
unsigned char sdCardSector[512];
// SPI_SDCARD_READMBR
// Function exposed to BIOS to retrieve FAT16 partition details, FAT16 Entry Table, FAT16 Root Directory
// MBR = Master Boot Record - Sector 0x00000000 on SD CARD - Contains Partition 1 details at 0x1be
//
// FIXME only checks partition 1 out of 4
//
// Return 0 success, 1 failure
//
// Details from https://codeandlife.com/2012/04/02/simple-fat-and-sd-tutorial-part-1/
unsigned char spi_sdcard_readMBR(void)
{
int i, n;
// Read Sector 0x00000000
printf("Reading MBR\n");
if( readSector(0x00000000, sdCardSector)==SUCCESS ) {
// Copy Partition 1 Entry from byte 0x1be
// FIXME should check 0x55 0xaa at end of sector
memcpy(&sdCardPartition, &sdCardSector[0x1be], sizeof(PartitionTable));
// Check Partition 1 is valid, FIRST_BYTE=0x00 or 0x80
// Check Partition 1 has type 4, 6 or 14 (FAT16 of various sizes)
printf("Partition 1 Information: Active=0x%02x, Type=0x%02x, LBAStart=0x%08x\n", sdCardPartition.first_byte, sdCardPartition.partition_type, sdCardPartition.start_sector);
if( (sdCardPartition.first_byte!=0x80) && (sdCardPartition.first_byte!=0x00) ) {
printf("Partition 1 Not Valid\n");
return FAILURE;
}
if( (sdCardPartition.partition_type==4) || (sdCardPartition.partition_type==6) || (sdCardPartition.partition_type==14) ) {
printf("Partition 1 is FAT16\n");
}
else {
printf("Partition 1 Not FAT16\n");
return FAILURE;
}
}
else {
printf("Failed to read MBR\n");
return FAILURE;
}
// Read Parition 1 Boot Sector - Found from Partion Table
printf("\nRead FAT16 Boot Sector\n");
if( readSector(sdCardPartition.start_sector, sdCardSector)==SUCCESS ) {
memcpy(&sdCardFatBootSector, &sdCardSector, sizeof(Fat16BootSector));
}
else {
printf("Failed to read FAT16 Boot Sector\n");
return FAILURE;
}
// Print details of Parition 1
printf(" Jump Code: 0x%02x 0x%02x 0x%02x\n",sdCardFatBootSector.jmp[0],sdCardFatBootSector.jmp[1],sdCardFatBootSector.jmp[2]);
printf(" OEM Code: [");
for(n=0; n<8; n++)
printf("%c",sdCardFatBootSector.oem[n]);
printf("]\n");
printf(" Sector Size: %d\n",sdCardFatBootSector.sector_size);
printf(" Sectors Per Cluster: %d\n",sdCardFatBootSector.sectors_per_cluster);
printf(" Reserved Sectors: %d\n",sdCardFatBootSector.reserved_sectors);
printf(" Number of Fats: %d\n",sdCardFatBootSector.number_of_fats);
printf(" Root Dir Entries: %d\n",sdCardFatBootSector.root_dir_entries);
printf(" Total Sectors Short: %d\n",sdCardFatBootSector.total_sectors_short);
printf(" Media Descriptor: 0x%02x\n",sdCardFatBootSector.media_descriptor);
printf(" Fat Size Sectors: %d\n",sdCardFatBootSector.fat_size_sectors);
printf(" Sectors Per Track: %d\n",sdCardFatBootSector.sectors_per_track);
printf(" Number of Heads: %d\n",sdCardFatBootSector.number_of_heads);
printf(" Hidden Sectors: %d\n",sdCardFatBootSector.hidden_sectors);
printf(" Total Sectors Long: %d\n",sdCardFatBootSector.total_sectors_long);
printf(" Drive Number: 0x%02x\n",sdCardFatBootSector.drive_number);
printf(" Current Head: 0x%02x\n",sdCardFatBootSector.current_head);
printf(" Boot Signature: 0x%02x\n",sdCardFatBootSector.boot_signature);
printf(" Volume ID: 0x%08x\n",sdCardFatBootSector.volume_id);
printf(" Volume Label: [");
for(n=0; n<11; n++)
printf("%c",sdCardFatBootSector.volume_label[n]);
printf("]\n");
printf(" Volume Label: [");
for(n=0; n<8; n++)
printf("%c",sdCardFatBootSector.fs_type[n]);
printf("]\n");
printf(" Boot Sector Signature: 0x%04x\n\n",sdCardFatBootSector.boot_sector_signature);
// Check Partition 1 is valid, not 0 length
if(sdCardFatBootSector.total_sectors_long==0) {
printf("Error reading FAT16 Boot Sector\n");
return FAILURE;
}
// Read in FAT16 File Allocation Table, array of 16bit unsinged integers
// Calculate Storage from TOP of MAIN RAM
sdCardFatTable = (unsigned short *)(MAIN_RAM_BASE+MAIN_RAM_SIZE-sdCardFatBootSector.sector_size*sdCardFatBootSector.fat_size_sectors);
printf("sdCardFatTable = 0x%08x Reading Fat16 Table (%d Sectors Long)\n\n",sdCardFatTable,sdCardFatBootSector.fat_size_sectors);
// Calculate Start of FAT16 File Allocation Table (start of partition plus reserved sectors)
fatSectorStart=sdCardPartition.start_sector+sdCardFatBootSector.reserved_sectors;
for(n=0; n<sdCardFatBootSector.fat_size_sectors; n++) {
if( readSector(fatSectorStart+n, (unsigned char *)((unsigned char*)sdCardFatTable)+sdCardFatBootSector.sector_size*n)==FAILURE ) {
printf("Error reading FAT16 table - sector %d\n",n);
return FAILURE;
}
}
// Read in FAT16 Root Directory
// Calculate Storage from TOP of MAIN RAM
sdCardFat16RootDir= (Fat16Entry *)(MAIN_RAM_BASE+MAIN_RAM_SIZE-sdCardFatBootSector.sector_size*sdCardFatBootSector.fat_size_sectors-sdCardFatBootSector.root_dir_entries*sizeof(Fat16Entry));
printf("sdCardFat16RootDir = 0x%08x Reading Root Directory (%d Sectors Long)\n\n",sdCardFat16RootDir,sdCardFatBootSector.root_dir_entries*sizeof(Fat16Entry)/sdCardFatBootSector.sector_size);
// Calculate Start of FAT ROOT DIRECTORY (start of partition plues reserved sectors plus size of File Allocation Table(s))
rootDirSectorStart=sdCardPartition.start_sector+sdCardFatBootSector.reserved_sectors+sdCardFatBootSector.number_of_fats*sdCardFatBootSector.fat_size_sectors;
for(n=0; n<sdCardFatBootSector.root_dir_entries*sizeof(Fat16Entry)/sdCardFatBootSector.sector_size; n++) {
if( readSector(rootDirSectorStart+n, (unsigned char *)(sdCardFatBootSector.sector_size*n+(unsigned char *)(sdCardFat16RootDir)))==FAILURE ) {
printf("Error reading Root Dir - sector %d\n",n);
return FAILURE;
}
}
// Print out Root Directory
// Alternates between valid and invalid directory entries for SIMPLE 8+3 file names, extended filenames in other entries
// Only print valid characters
printf("\nRoot Directory\n");
for(n=0; n<sdCardFatBootSector.root_dir_entries; n++) {
if( (sdCardFat16RootDir[n].filename[0]!=0) && (sdCardFat16RootDir[n].file_size>0)) {
printf(" File %d [",n);
for( i=0; i<8; i++) {
if( (sdCardFat16RootDir[n].filename[i]>31) && (sdCardFat16RootDir[n].filename[i]<127) )
printf("%c",sdCardFat16RootDir[n].filename[i]);
else
printf(" ");
}
printf(".");
for( i=0; i<3; i++) {
if( (sdCardFat16RootDir[n].ext[i]>31) && (sdCardFat16RootDir[n].ext[i]<127) )
printf("%c",sdCardFat16RootDir[n].ext[i]);
else
printf(" ");
}
printf("] @ Cluster %d for %d bytes\n",sdCardFat16RootDir[n].starting_cluster,sdCardFat16RootDir[n].file_size);
}
}
printf("\n");
return SUCCESS;
}
// SPI_SDCARD_READFILE
// Function exposed to BIOS to retrieve FILENAME+EXT into ADDRESS
//
// FIXME only checks UPPERCASE 8+3 filenames
//
// Return 0 success, 1 failure
//
// Details from https://codeandlife.com/2012/04/02/simple-fat-and-sd-tutorial-part-1/
unsigned char spi_sdcard_readFile(char *filename, char *ext, unsigned long address)
{
int i, n, sector;
unsigned short fileClusterStart;
unsigned long fileLength, bytesRemaining, clusterSectorStart;
unsigned short nameMatch;
printf("Reading File [%s.%s] into 0x%08x : ",filename, ext, address);
// Find FILENAME+EXT in Root Directory
// Indicate FILE found by setting the starting cluster number
fileClusterStart=0; n=0;
while( (fileClusterStart==0) && (n<sdCardFatBootSector.root_dir_entries) ) {
nameMatch=0;
if( sdCardFat16RootDir[n].filename[0]!=0 ) {
nameMatch=1;
for(i=0; i<strlen(filename); i++)
if(sdCardFat16RootDir[n].filename[i]!=filename[i]) nameMatch=0;
for(i=0; i<strlen(ext); i++)
if(sdCardFat16RootDir[n].ext[i]!=ext[i]) nameMatch=0;
}
if(nameMatch==1) {
fileClusterStart=sdCardFat16RootDir[n].starting_cluster;
fileLength=sdCardFat16RootDir[n].file_size;
} else {
n++;
}
}
// If starting cluster number is still 0 then file not found
if(fileClusterStart==0) {
printf("File not found\n");
return FAILURE;
}
printf("File starts at Cluster %d length %d\n",fileClusterStart,fileLength);
// ZERO Length file are automatically assumed to have been read SUCCESS
if( fileLength==0 ) return SUCCESS;
// Read each cluster sector by sector, i being number of clusters
bytesRemaining=fileLength;
printf("Clusters: ");
// Calculate number of clusters (always >1)
for(i=0; i<1+((fileLength/sdCardFatBootSector.sectors_per_cluster)/sdCardFatBootSector.sector_size); i++) {
printf("%d ",fileClusterStart);
// Locate start of cluster on SD CARD and read appropraite number of sectors
clusterSectorStart=rootDirSectorStart+(fileClusterStart-1)*sdCardFatBootSector.sectors_per_cluster;
for(sector=0; sector<sdCardFatBootSector.sectors_per_cluster; sector++) {
// Read Sector from SD CARD
// If whole sector to be read, read directly into memory
// Otherwise, read to sdCardSector buffer and transfer appropriate number of bytes
if(bytesRemaining>sdCardFatBootSector.sector_size) {
if( readSector(clusterSectorStart+sector,(unsigned char *)address) == FAILURE ) {
printf("Read Error\n");
return FAILURE;
}
bytesRemaining=bytesRemaining-sdCardFatBootSector.sector_size;
address=address+sdCardFatBootSector.sector_size;
} else {
if( readSector(clusterSectorStart+sector,sdCardSector) == FAILURE ) {
printf("Read Error\n");
return FAILURE;
}
memcpy((unsigned char *)address, sdCardSector, bytesRemaining);
bytesRemaining=0;
}
}
// Move to next cluster
fileClusterStart=sdCardFatTable[fileClusterStart];
}
printf("\n\n");
return SUCCESS;
}
#endif
| 2.328125 | 2 |
2024-11-18T20:53:30.936224+00:00 | 2019-01-09T06:13:38 | 2224d3f87c41dc8762df0bfcdf146dc180b46b50 | {
"blob_id": "2224d3f87c41dc8762df0bfcdf146dc180b46b50",
"branch_name": "refs/heads/master",
"committer_date": "2019-01-09T06:13:38",
"content_id": "8001d08b303cfc8e55c34231c49a1296646de476",
"detected_licenses": [
"PHP-3.01"
],
"directory_id": "95aeaa82f7598bc342e71467a34b76f378aea7c2",
"extension": "c",
"filename": "apc_stack.c",
"fork_events_count": 4,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 4525416,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3242,
"license": "PHP-3.01",
"license_type": "permissive",
"path": "/php/build_php/apc/APC-3.1.6/apc_stack.c",
"provenance": "stackv2-0127.json.gz:71316",
"repo_name": "Gerst20051/Languages",
"revision_date": "2019-01-09T06:13:38",
"revision_id": "4aae8a8a3ab13c9703f808f4f47a15966a0ab39e",
"snapshot_id": "b705a8723a5077da2edd87ff6adf28faa7ab4559",
"src_encoding": "UTF-8",
"star_events_count": 9,
"url": "https://raw.githubusercontent.com/Gerst20051/Languages/4aae8a8a3ab13c9703f808f4f47a15966a0ab39e/php/build_php/apc/APC-3.1.6/apc_stack.c",
"visit_date": "2021-06-04T17:22:33.027701"
} | stackv2 | /*
+----------------------------------------------------------------------+
| APC |
+----------------------------------------------------------------------+
| Copyright (c) 2006-2010 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Daniel Cowgill <dcowgill@communityconnect.com> |
+----------------------------------------------------------------------+
This software was contributed to PHP by Community Connect Inc. in 2002
and revised in 2005 by Yahoo! Inc. to add support for PHP 5.1.
Future revisions and derivatives of this source code must acknowledge
Community Connect Inc. as the original contributor of this module by
leaving this note intact in the source code.
All other licensing and usage conditions are those of the PHP Group.
*/
/* $Id: apc_stack.c 302175 2010-08-13 06:20:28Z kalle $ */
#include "apc.h"
#include "apc_stack.h"
struct apc_stack_t {
void** data;
int capacity;
int size;
};
apc_stack_t* apc_stack_create(int size_hint TSRMLS_DC)
{
apc_stack_t* stack = (apc_stack_t*) apc_emalloc(sizeof(apc_stack_t) TSRMLS_CC);
stack->capacity = (size_hint > 0) ? size_hint : 10;
stack->size = 0;
stack->data = (void**) apc_emalloc(sizeof(void*) * stack->capacity TSRMLS_CC);
return stack;
}
void apc_stack_destroy(apc_stack_t* stack TSRMLS_DC)
{
if (stack != NULL) {
apc_efree(stack->data TSRMLS_CC);
apc_efree(stack TSRMLS_CC);
}
}
void apc_stack_clear(apc_stack_t* stack)
{
assert(stack != NULL);
stack->size = 0;
}
void apc_stack_push(apc_stack_t* stack, void* item TSRMLS_DC)
{
assert(stack != NULL);
if (stack->size == stack->capacity) {
stack->capacity *= 2;
stack->data = apc_erealloc(stack->data, sizeof(void*)*stack->capacity TSRMLS_CC);
}
stack->data[stack->size++] = item;
}
void* apc_stack_pop(apc_stack_t* stack)
{
assert(stack != NULL && stack->size > 0);
return stack->data[--stack->size];
}
void* apc_stack_top(apc_stack_t* stack)
{
assert(stack != NULL && stack->size > 0);
return stack->data[stack->size-1];
}
void* apc_stack_get(apc_stack_t* stack, int n)
{
assert(stack != NULL && stack->size > n);
return stack->data[n];
}
int apc_stack_size(apc_stack_t* stack)
{
assert(stack != NULL);
return stack->size;
}
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim>600: expandtab sw=4 ts=4 sts=4 fdm=marker
* vim<600: expandtab sw=4 ts=4 sts=4
*/
| 2.03125 | 2 |
2024-11-18T20:53:32.141365+00:00 | 2018-10-03T16:23:15 | 4fc9a7c857e43eff417024e68f3b21f83014ea6e | {
"blob_id": "4fc9a7c857e43eff417024e68f3b21f83014ea6e",
"branch_name": "refs/heads/master",
"committer_date": "2018-10-03T16:23:15",
"content_id": "1438946648ad5ce3bacd6a9f39754cb2f31a1f8e",
"detected_licenses": [
"BSD-2-Clause",
"BSD-3-Clause"
],
"directory_id": "8f9353dcf7d5cd115b12d1c23d78fab86484df5a",
"extension": "c",
"filename": "2d-fourier-8x8.c",
"fork_events_count": 0,
"gha_created_at": "2018-09-21T17:45:41",
"gha_event_created_at": "2018-09-21T17:45:41",
"gha_language": null,
"gha_license_id": "BSD-2-Clause",
"github_id": 149798006,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 12192,
"license": "BSD-2-Clause,BSD-3-Clause",
"license_type": "permissive",
"path": "/src/scalar/2d-fourier-8x8.c",
"provenance": "stackv2-0127.json.gz:72482",
"repo_name": "jiecaoyu/NNPACK",
"revision_date": "2018-10-03T16:23:15",
"revision_id": "a0782baf4ec1067b7751bc7f5ae4847a03b489cb",
"snapshot_id": "8883b7810d09db3775bfd2e5a28d78e0bd311275",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/jiecaoyu/NNPACK/a0782baf4ec1067b7751bc7f5ae4847a03b489cb/src/scalar/2d-fourier-8x8.c",
"visit_date": "2020-03-29T10:18:09.717981"
} | stackv2 | #include <stdint.h>
#include <stddef.h>
#include <scalar/fft/real.h>
#include <scalar/fft/soa.h>
#include <scalar/fft/dualreal.h>
#include <nnpack/utils.h>
#include <nnpack/activations.h>
#define BLOCK_SIZE 8
void nnp_fft8x8_with_offset__scalar(
const float data[restrict static 1],
float transform[restrict static 1],
size_t data_stride, size_t transform_stride,
uint32_t row_count, uint32_t column_count,
uint32_t row_offset, uint32_t column_offset)
{
const uint32_t simd_width = 1;
transform_stride /= sizeof(float);
float block[BLOCK_SIZE][BLOCK_SIZE];
if (column_offset != 0) {
for (uint32_t row = 0; row < BLOCK_SIZE; row++) {
for (uint32_t column = 0; column < column_offset; column++) {
block[row][column] = 0.0f;
}
}
}
const uint32_t column_end = column_offset + column_count;
if (column_end != BLOCK_SIZE) {
for (uint32_t row = 0; row < BLOCK_SIZE; row++) {
for (uint32_t column = column_end; column < BLOCK_SIZE; column++) {
block[row][column] = 0.0f;
}
}
}
const float *restrict row0 = data;
const float *restrict row4 = data + doz(BLOCK_SIZE / 2, row_offset) * data_stride;
float* restrict output = &block[0][column_offset];
for (uint32_t column = column_offset; column < column_end; column++) {
scalar_fft8_real(row0, row4, data_stride,
row_offset, row_count,
&block[0][column], BLOCK_SIZE);
row0 += 1;
row4 += 1;
output += 1;
}
{
float x0, y0, x1r, y1r, x2r, y2r, x3r, y3r;
float x4, y4, x1i, y1i, x2i, y2i, x3i, y3i;
scalar_fft8_dualreal(
&block[0][0],
&x0, &y0, &x1r, &y1r, &x2r, &y2r, &x3r, &y3r,
&x4, &y4, &x1i, &y1i, &x2i, &y2i, &x3i, &y3i);
transform[0] = x0;
transform[1] = x4;
transform += transform_stride;
transform[0] = y0;
transform[1] = y4;
transform += transform_stride;
transform[0] = x1r;
transform[1] = x1i;
transform += transform_stride;
transform[0] = y1r;
transform[1] = y1i;
transform += transform_stride;
transform[0] = x2r;
transform[1] = x2i;
transform += transform_stride;
transform[0] = y2r;
transform[1] = y2i;
transform += transform_stride;
transform[0] = x3r;
transform[1] = x3i;
transform += transform_stride;
transform[0] = y3r;
transform[1] = y3i;
transform += transform_stride;
}
for (uint32_t row = 2; row < BLOCK_SIZE; row += 2) {
float f0r, f1r, f2r, f3r, f4r, f5r, f6r, f7r;
float f0i, f1i, f2i, f3i, f4i, f5i, f6i, f7i;
scalar_fft8_soa(
&block[row][0],
&f0r, &f1r, &f2r, &f3r, &f4r, &f5r, &f6r, &f7r,
&f0i, &f1i, &f2i, &f3i, &f4i, &f5i, &f6i, &f7i);
transform[0] = f0r;
transform[1] = f0i;
transform += transform_stride;
transform[0] = f1r;
transform[1] = f1i;
transform += transform_stride;
transform[0] = f2r;
transform[1] = f2i;
transform += transform_stride;
transform[0] = f3r;
transform[1] = f3i;
transform += transform_stride;
transform[0] = f4r;
transform[1] = f4i;
transform += transform_stride;
transform[0] = f5r;
transform[1] = f5i;
transform += transform_stride;
transform[0] = f6r;
transform[1] = f6i;
transform += transform_stride;
transform[0] = f7r;
transform[1] = f7i;
transform += transform_stride;
}
}
#if !NNP_INFERENCE_ONLY
void nnp_ifft8x8_with_offset__scalar(
const float transform[restrict static 1],
float data[restrict static 1],
size_t transform_stride, size_t data_stride,
uint32_t row_count, uint32_t column_count,
uint32_t row_offset, uint32_t column_offset)
{
transform_stride /= sizeof(float);
float block[BLOCK_SIZE][BLOCK_SIZE];
{
const float x0 = transform[0];
const float x4 = transform[1];
transform += transform_stride;
const float y0 = transform[0];
const float y4 = transform[1];
transform += transform_stride;
const float x1r = transform[0];
const float x1i = transform[1];
transform += transform_stride;
const float y1r = transform[0];
const float y1i = transform[1];
transform += transform_stride;
const float x2r = transform[0];
const float x2i = transform[1];
transform += transform_stride;
const float y2r = transform[0];
const float y2i = transform[1];
transform += transform_stride;
const float x3r = transform[0];
const float x3i = transform[1];
transform += transform_stride;
const float y3r = transform[0];
const float y3i = transform[1];
transform += transform_stride;
scalar_ifft8_dualreal(
x0, y0, x1r, y1r, x2r, y2r, x3r, y3r,
x4, y4, x1i, y1i, x2i, y2i, x3i, y3i,
&block[0][0]);
}
for (uint32_t row = 2; row < BLOCK_SIZE; row += 2) {
const float f0r = transform[0];
const float f0i = transform[1];
transform += transform_stride;
const float f1r = transform[0];
const float f1i = transform[1];
transform += transform_stride;
const float f2r = transform[0];
const float f2i = transform[1];
transform += transform_stride;
const float f3r = transform[0];
const float f3i = transform[1];
transform += transform_stride;
const float f4r = transform[0];
const float f4i = transform[1];
transform += transform_stride;
const float f5r = transform[0];
const float f5i = transform[1];
transform += transform_stride;
const float f6r = transform[0];
const float f6i = transform[1];
transform += transform_stride;
const float f7r = transform[0];
const float f7i = transform[1];
transform += transform_stride;
scalar_ifft8_soa(
f0r, f1r, f2r, f3r, f4r, f5r, f6r, f7r,
f0i, f1i, f2i, f3i, f4i, f5i, f6i, f7i,
&block[row][0]);
}
for (uint32_t column = 0; column < BLOCK_SIZE; column++) {
const float f0 = block[0][column];
const float f4 = block[1][column];
const float f1r = block[2][column];
const float f1i = block[3][column];
const float f2r = block[4][column];
const float f2i = block[5][column];
const float f3r = block[6][column];
const float f3i = block[7][column];
scalar_ifft8_real(
f0, f4, f1r, f1i, f2r, f2i, f3r, f3i,
&block[0][column], &block[BLOCK_SIZE / 2][column],
BLOCK_SIZE);
}
for (uint32_t row = 0; row < row_count; row++) {
for (uint32_t column = 0; column < column_count; column++) {
data[row * data_stride + column] = block[row_offset + row][column_offset + column];
}
}
}
#endif /* !NNP_INFERENCE_ONLY */
void nnp_ifft8x8_with_bias__scalar(
const float transform[restrict static 1],
float data[restrict static 1],
const float bias[restrict static 1],
size_t transform_stride, size_t data_stride,
uint32_t row_count, uint32_t column_count)
{
transform_stride /= sizeof(float);
float block[BLOCK_SIZE][BLOCK_SIZE];
const float bias_value = *bias;
{
const float x0 = transform[0] + bias_value * 64.0f;
const float x4 = transform[1];
transform += transform_stride;
const float y0 = transform[0];
const float y4 = transform[1];
transform += transform_stride;
const float x1r = transform[0];
const float x1i = transform[1];
transform += transform_stride;
const float y1r = transform[0];
const float y1i = transform[1];
transform += transform_stride;
const float x2r = transform[0];
const float x2i = transform[1];
transform += transform_stride;
const float y2r = transform[0];
const float y2i = transform[1];
transform += transform_stride;
const float x3r = transform[0];
const float x3i = transform[1];
transform += transform_stride;
const float y3r = transform[0];
const float y3i = transform[1];
transform += transform_stride;
scalar_ifft8_dualreal(
x0, y0, x1r, y1r, x2r, y2r, x3r, y3r,
x4, y4, x1i, y1i, x2i, y2i, x3i, y3i,
&block[0][0]);
}
for (uint32_t row = 2; row < BLOCK_SIZE; row += 2) {
const float f0r = transform[0];
const float f0i = transform[1];
transform += transform_stride;
const float f1r = transform[0];
const float f1i = transform[1];
transform += transform_stride;
const float f2r = transform[0];
const float f2i = transform[1];
transform += transform_stride;
const float f3r = transform[0];
const float f3i = transform[1];
transform += transform_stride;
const float f4r = transform[0];
const float f4i = transform[1];
transform += transform_stride;
const float f5r = transform[0];
const float f5i = transform[1];
transform += transform_stride;
const float f6r = transform[0];
const float f6i = transform[1];
transform += transform_stride;
const float f7r = transform[0];
const float f7i = transform[1];
transform += transform_stride;
scalar_ifft8_soa(
f0r, f1r, f2r, f3r, f4r, f5r, f6r, f7r,
f0i, f1i, f2i, f3i, f4i, f5i, f6i, f7i,
&block[row][0]);
}
for (uint32_t column = 0; column < BLOCK_SIZE; column++) {
const float f0 = block[0][column];
const float f4 = block[1][column];
const float f1r = block[2][column];
const float f1i = block[3][column];
const float f2r = block[4][column];
const float f2i = block[5][column];
const float f3r = block[6][column];
const float f3i = block[7][column];
scalar_ifft8_real(
f0, f4, f1r, f1i, f2r, f2i, f3r, f3i,
&block[0][column], &block[BLOCK_SIZE / 2][column],
BLOCK_SIZE);
}
for (uint32_t row = 0; row < row_count; row++) {
for (uint32_t column = 0; column < column_count; column++) {
data[row * data_stride + column] = block[row][column];
}
}
}
void nnp_ifft8x8_with_bias_with_relu__scalar(
const float transform[restrict static 1],
float data[restrict static 1],
const float bias[restrict static 1],
size_t transform_stride, size_t data_stride,
uint32_t row_count, uint32_t column_count)
{
transform_stride /= sizeof(float);
float block[BLOCK_SIZE][BLOCK_SIZE];
const float bias_value = *bias;
{
const float x0 = transform[0] + bias_value * 64.0f;
const float x4 = transform[1];
transform += transform_stride;
const float y0 = transform[0];
const float y4 = transform[1];
transform += transform_stride;
const float x1r = transform[0];
const float x1i = transform[1];
transform += transform_stride;
const float y1r = transform[0];
const float y1i = transform[1];
transform += transform_stride;
const float x2r = transform[0];
const float x2i = transform[1];
transform += transform_stride;
const float y2r = transform[0];
const float y2i = transform[1];
transform += transform_stride;
const float x3r = transform[0];
const float x3i = transform[1];
transform += transform_stride;
const float y3r = transform[0];
const float y3i = transform[1];
transform += transform_stride;
scalar_ifft8_dualreal(
x0, y0, x1r, y1r, x2r, y2r, x3r, y3r,
x4, y4, x1i, y1i, x2i, y2i, x3i, y3i,
&block[0][0]);
}
for (uint32_t row = 2; row < BLOCK_SIZE; row += 2) {
const float f0r = transform[0];
const float f0i = transform[1];
transform += transform_stride;
const float f1r = transform[0];
const float f1i = transform[1];
transform += transform_stride;
const float f2r = transform[0];
const float f2i = transform[1];
transform += transform_stride;
const float f3r = transform[0];
const float f3i = transform[1];
transform += transform_stride;
const float f4r = transform[0];
const float f4i = transform[1];
transform += transform_stride;
const float f5r = transform[0];
const float f5i = transform[1];
transform += transform_stride;
const float f6r = transform[0];
const float f6i = transform[1];
transform += transform_stride;
const float f7r = transform[0];
const float f7i = transform[1];
transform += transform_stride;
scalar_ifft8_soa(
f0r, f1r, f2r, f3r, f4r, f5r, f6r, f7r,
f0i, f1i, f2i, f3i, f4i, f5i, f6i, f7i,
&block[row][0]);
}
for (uint32_t column = 0; column < BLOCK_SIZE; column++) {
const float f0 = block[0][column];
const float f4 = block[1][column];
const float f1r = block[2][column];
const float f1i = block[3][column];
const float f2r = block[4][column];
const float f2i = block[5][column];
const float f3r = block[6][column];
const float f3i = block[7][column];
scalar_ifft8_real(
f0, f4, f1r, f1i, f2r, f2i, f3r, f3i,
&block[0][column], &block[BLOCK_SIZE / 2][column],
BLOCK_SIZE);
}
for (uint32_t row = 0; row < row_count; row++) {
for (uint32_t column = 0; column < column_count; column++) {
data[row * data_stride + column] = relu(block[row][column], 0.0f);
}
}
}
| 2.203125 | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.