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-18T21:30:17.989551+00:00 | 2023-07-12T18:56:26 | 3a9eebc2a2978862ade1b28bb9f8d5e4056a563d | {
"blob_id": "3a9eebc2a2978862ade1b28bb9f8d5e4056a563d",
"branch_name": "refs/heads/main",
"committer_date": "2023-07-12T18:56:26",
"content_id": "de37fdbdb6854613cbbfae98b9f0b8f4fb65a18f",
"detected_licenses": [
"MIT"
],
"directory_id": "1bd90f1d200b381a5ff3aaeaad3ef7426ee15253",
"extension": "c",
"filename": "softap_start.c",
"fork_events_count": 78,
"gha_created_at": "2018-04-16T06:28:52",
"gha_event_created_at": "2023-07-12T18:56:28",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 129695374,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2844,
"license": "MIT",
"license_type": "permissive",
"path": "/esp32_sawppy/lib/wifi/softap_start.c",
"provenance": "stackv2-0112.json.gz:193517",
"repo_name": "Roger-random/Sawppy_Rover",
"revision_date": "2023-07-12T18:56:26",
"revision_id": "ac48ddcf21dd8153da8817ba1ea5e6a46f2a8298",
"snapshot_id": "f0ff5346b9bf46e933f47608e5a07012663beb84",
"src_encoding": "UTF-8",
"star_events_count": 399,
"url": "https://raw.githubusercontent.com/Roger-random/Sawppy_Rover/ac48ddcf21dd8153da8817ba1ea5e6a46f2a8298/esp32_sawppy/lib/wifi/softap_start.c",
"visit_date": "2023-08-04T17:55:57.082822"
} | stackv2 | /*
* Only lightly modified from ESP32 WiFi SoftAP example
* https://github.com/espressif/esp-idf/blob/master/examples/wifi/getting_started/softAP/main/softap_example_main.c
*/
# include "softap_start.h"
// https://en.wikipedia.org/wiki/List_of_WLAN_channels#2.4_GHz_(802.11b/g/n/ax)
#define ESP_WIFI_CHANNEL 6
// Number of connected clients to support
#define ESP_MAX_STA_CONN 4
// Prefix for ESP_LOG output
static const char *TAG = "wifi softAP";
/*
* @brief Listen to events signaling stations connect/disconnect from this access point
*/
static void wifi_event_handler(void* arg, esp_event_base_t event_base, int32_t event_id, void* event_data)
{
if (event_id == WIFI_EVENT_AP_STACONNECTED) {
wifi_event_ap_staconnected_t* event = (wifi_event_ap_staconnected_t*) event_data;
ESP_LOGI(TAG, "station "MACSTR" join, AID=%d", MAC2STR(event->mac), event->aid);
} else if (event_id == WIFI_EVENT_AP_STADISCONNECTED) {
wifi_event_ap_stadisconnected_t* event = (wifi_event_ap_stadisconnected_t*) event_data;
ESP_LOGI(TAG, "station "MACSTR" leave, AID=%d", MAC2STR(event->mac), event->aid);
}
}
/*
* @brief Initialize ESP32 WiFi in access point mode
*/
void wifi_init_softap(void)
{
ESP_ERROR_CHECK(esp_netif_init());
esp_netif_create_default_wifi_ap();
wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
ESP_ERROR_CHECK(esp_wifi_init(&cfg));
ESP_ERROR_CHECK(esp_event_handler_instance_register(WIFI_EVENT,
ESP_EVENT_ANY_ID,
&wifi_event_handler,
NULL,
NULL));
wifi_config_t wifi_config = {
.ap = {
.ssid = ESP_WIFI_SSID,
.ssid_len = strlen(ESP_WIFI_SSID),
.channel = ESP_WIFI_CHANNEL,
.password = ESP_WIFI_PASS,
.max_connection = ESP_MAX_STA_CONN,
.authmode = WIFI_AUTH_WPA_WPA2_PSK
},
};
if (strlen(ESP_WIFI_PASS) == 0) {
wifi_config.ap.authmode = WIFI_AUTH_OPEN;
}
ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_AP));
ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_AP, &wifi_config));
ESP_ERROR_CHECK(esp_wifi_start());
ESP_LOGI(TAG, "wifi_init_softap finished. SSID:%s password:%s channel:%d",
ESP_WIFI_SSID, ESP_WIFI_PASS, ESP_WIFI_CHANNEL);
}
void softap_start_task(void* pvParameter)
{
//Initialize NVS
esp_err_t ret = nvs_flash_init();
if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
ESP_ERROR_CHECK(nvs_flash_erase());
ret = nvs_flash_init();
}
ESP_ERROR_CHECK(ret);
ESP_LOGI(TAG, "ESP_WIFI_MODE_AP");
wifi_init_softap();
// TODO: Wait on (what?) to shut down WiFi. Currently never shut down.
while(true) {
vTaskDelay(portMAX_DELAY);
}
}
| 2.03125 | 2 |
2024-11-18T21:30:18.058618+00:00 | 2023-03-06T16:11:48 | 1d8766b265fe739ed6f47ba94e1e068da4044875 | {
"blob_id": "1d8766b265fe739ed6f47ba94e1e068da4044875",
"branch_name": "refs/heads/master",
"committer_date": "2023-03-06T16:11:56",
"content_id": "c8bba41b161f9f2cfde950c905376d0d6b0423ec",
"detected_licenses": [
"MIT"
],
"directory_id": "240c1cec31833d75217339519c218dcc47bc1301",
"extension": "c",
"filename": "ref.c",
"fork_events_count": 1,
"gha_created_at": "2018-05-05T05:12:08",
"gha_event_created_at": "2020-04-17T13:48:11",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 132216974,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1154,
"license": "MIT",
"license_type": "permissive",
"path": "/ref.c",
"provenance": "stackv2-0112.json.gz:193648",
"repo_name": "42Bastian/lyxass",
"revision_date": "2023-03-06T16:11:48",
"revision_id": "574669501d5e04d85406f54d1935677d52661cbb",
"snapshot_id": "7ab2f73c9df25ce7e047742f1382bce2b92a3b81",
"src_encoding": "UTF-8",
"star_events_count": 11,
"url": "https://raw.githubusercontent.com/42Bastian/lyxass/574669501d5e04d85406f54d1935677d52661cbb/ref.c",
"visit_date": "2023-03-10T20:50:22.856401"
} | stackv2 |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "my.h"
#include "error.h"
#include "label.h"
#include "global_vars.h"
extern char srcLine[256]; // parser.c
char lineBuffer[256];
REFERENCE *refFirst = 0;
REFERENCE *refLast = 0;
/***********************/
/* save current line */
/***********************/
void saveCurrentLine()
{
REFERENCE *refPtr;
refPtr = (REFERENCE *)my_malloc(sizeof(REFERENCE) + (long)strlen(srcLine) + 1UL );
strcpy(refPtr->src,srcLine);
refPtr->line = Current.Line-1;
refPtr->file = Current.File;
refPtr->macroline = Current.Macro.Line;
refPtr->macrofile = Current.Macro.File;
refPtr->macroinvoked = Current.Macro.invoked;
refPtr->macro = Current.Macro.Processing;
// refPtr->var = Current.var;
refPtr->pc = Global.OldPC;
refPtr->codePtr = code.OldPtr;
refPtr->up =
refPtr->down = (REFERENCE *)0;
refPtr->unknown = unknownLabel;
refPtr->mode = sourceMode;
if ( refFirst ){
refPtr->down = refLast;
refLast->up = refPtr;
} else {
refFirst = refPtr;
}
refLast = refPtr;
//-> printf("ref.c: %s (%s) = %p\n",unknownLabel->name,srcLine,refLast);
}
| 2.0625 | 2 |
2024-11-18T21:30:18.258568+00:00 | 2021-01-12T12:15:40 | 09961bea522d5703cf8f0aa5845b5c7c63cb4332 | {
"blob_id": "09961bea522d5703cf8f0aa5845b5c7c63cb4332",
"branch_name": "refs/heads/master",
"committer_date": "2021-01-12T12:16:12",
"content_id": "8083f0eae67ca9ba6721a7ac0eb1ec3bc03e1677",
"detected_licenses": [
"CC0-1.0",
"MIT"
],
"directory_id": "62f29ec6b87892cf34298b04f2af61a6c1277c85",
"extension": "h",
"filename": "ecmult.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": 2919,
"license": "CC0-1.0,MIT",
"license_type": "permissive",
"path": "/secp256k1-zkp-sys/depend/secp256k1/src/ecmult.h",
"provenance": "stackv2-0112.json.gz:194043",
"repo_name": "tiero/rust-secp256k1-zkp",
"revision_date": "2021-01-12T12:15:40",
"revision_id": "5b9601f1a082e9af695b6f8a36e544c6344d30ed",
"snapshot_id": "143f4131a8fbebfbf1c50c8a135556f8f2930b5b",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/tiero/rust-secp256k1-zkp/5b9601f1a082e9af695b6f8a36e544c6344d30ed/secp256k1-zkp-sys/depend/secp256k1/src/ecmult.h",
"visit_date": "2023-02-23T06:36:11.540293"
} | stackv2 | /**********************************************************************
* Copyright (c) 2013, 2014, 2017 Pieter Wuille, Andrew Poelstra *
* Distributed under the MIT software license, see the accompanying *
* file COPYING or http://www.opensource.org/licenses/mit-license.php.*
**********************************************************************/
#ifndef SECP256K1_ECMULT_H
#define SECP256K1_ECMULT_H
#include "num.h"
#include "group.h"
#include "scalar.h"
#include "scratch.h"
typedef struct {
/* For accelerating the computation of a*P + b*G: */
rustsecp256k1zkp_v0_2_0_ge_storage (*pre_g)[]; /* odd multiples of the generator */
rustsecp256k1zkp_v0_2_0_ge_storage (*pre_g_128)[]; /* odd multiples of 2^128*generator */
} rustsecp256k1zkp_v0_2_0_ecmult_context;
static const size_t SECP256K1_ECMULT_CONTEXT_PREALLOCATED_SIZE;
static void rustsecp256k1zkp_v0_2_0_ecmult_context_init(rustsecp256k1zkp_v0_2_0_ecmult_context *ctx);
static void rustsecp256k1zkp_v0_2_0_ecmult_context_build(rustsecp256k1zkp_v0_2_0_ecmult_context *ctx, void **prealloc);
static void rustsecp256k1zkp_v0_2_0_ecmult_context_finalize_memcpy(rustsecp256k1zkp_v0_2_0_ecmult_context *dst, const rustsecp256k1zkp_v0_2_0_ecmult_context *src);
static void rustsecp256k1zkp_v0_2_0_ecmult_context_clear(rustsecp256k1zkp_v0_2_0_ecmult_context *ctx);
static int rustsecp256k1zkp_v0_2_0_ecmult_context_is_built(const rustsecp256k1zkp_v0_2_0_ecmult_context *ctx);
/** Double multiply: R = na*A + ng*G */
static void rustsecp256k1zkp_v0_2_0_ecmult(const rustsecp256k1zkp_v0_2_0_ecmult_context *ctx, rustsecp256k1zkp_v0_2_0_gej *r, const rustsecp256k1zkp_v0_2_0_gej *a, const rustsecp256k1zkp_v0_2_0_scalar *na, const rustsecp256k1zkp_v0_2_0_scalar *ng);
typedef int (rustsecp256k1zkp_v0_2_0_ecmult_multi_callback)(rustsecp256k1zkp_v0_2_0_scalar *sc, rustsecp256k1zkp_v0_2_0_ge *pt, size_t idx, void *data);
/**
* Multi-multiply: R = inp_g_sc * G + sum_i ni * Ai.
* Chooses the right algorithm for a given number of points and scratch space
* size. Resets and overwrites the given scratch space. If the points do not
* fit in the scratch space the algorithm is repeatedly run with batches of
* points. If no scratch space is given then a simple algorithm is used that
* simply multiplies the points with the corresponding scalars and adds them up.
* Returns: 1 on success (including when inp_g_sc is NULL and n is 0)
* 0 if there is not enough scratch space for a single point or
* callback returns 0
*/
static int rustsecp256k1zkp_v0_2_0_ecmult_multi_var(const rustsecp256k1zkp_v0_2_0_callback* error_callback, const rustsecp256k1zkp_v0_2_0_ecmult_context *ctx, rustsecp256k1zkp_v0_2_0_scratch *scratch, rustsecp256k1zkp_v0_2_0_gej *r, const rustsecp256k1zkp_v0_2_0_scalar *inp_g_sc, rustsecp256k1zkp_v0_2_0_ecmult_multi_callback cb, void *cbdata, size_t n);
#endif /* SECP256K1_ECMULT_H */
| 2.109375 | 2 |
2024-11-18T21:30:18.618872+00:00 | 2021-02-03T08:15:06 | 073720ed4ae6bad8ea70dbfa6312967bb8226128 | {
"blob_id": "073720ed4ae6bad8ea70dbfa6312967bb8226128",
"branch_name": "refs/heads/master",
"committer_date": "2021-02-03T08:15:06",
"content_id": "be812663d86a1c20c345f651fcbe0c0611546fa4",
"detected_licenses": [
"MIT"
],
"directory_id": "692d96e9dbe1840b9c8b965aa5dd249b4daf63af",
"extension": "c",
"filename": "xline.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": 6330,
"license": "MIT",
"license_type": "permissive",
"path": "/software/Core/Src/user/xline.c",
"provenance": "stackv2-0112.json.gz:194432",
"repo_name": "CASE-Association/robotsm20-linefollower",
"revision_date": "2021-02-03T08:15:06",
"revision_id": "de11649522f385c8aa2493eae5e296503d17633f",
"snapshot_id": "aef0491975feb3f293e43721365d0559febef0c5",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/CASE-Association/robotsm20-linefollower/de11649522f385c8aa2493eae5e296503d17633f/software/Core/Src/user/xline.c",
"visit_date": "2023-02-25T06:24:45.472550"
} | stackv2 | #include "user/xline.h"
#include "main.h"
#include <stdio.h>
extern ADC_HandleTypeDef hadc2;
// Measured 2020-08-20
uint32_t calibrated_max[_num_sensors] = {919,922,886,893,895,905,919,911,913,899,913,926,902,899,913,887};
uint32_t calibrated_min[_num_sensors] = {55,57,55,56,55,56,57,55,55,57,56,57,57,56,57,55};
uint32_t xline[16];
/**
* @brief Initialize xline sensors.
*
*/
void init_xline(){
//xline_reset_calibration();
}
/**
* @brief Calibrate sensors by storing maximum and minimum values found in order to provide calibrated data when using xline_read_calibrated().
* Reads the sensors 10 times and uses the results for calibration. The sensor values are not returned; instead, the maximum and minimum values
* found over time are stored internally and used for the xline_read_calibrated() method.
*
* In order to calibrate, call this function repeatedly under a couple seconds (~5s) when moving the sensor over a line.
*/
void xline_calibrate(void){
//uint32_t sensor_values[_num_sensors] = {0};
uint32_t max_sensor_values[_num_sensors] = {0};
uint32_t min_sensor_values[_num_sensors] = {0};
for(uint8_t j = 0; j < 10; j++){
xline_read();
for(uint8_t i = 0; i < _num_sensors; i++){
// set the min we found THIS time
if(j == 0 || min_sensor_values[i] > xline[i])
min_sensor_values[i] = xline[i];
// set the max we found THIS time
if(j == 0 || max_sensor_values[i] < xline[i])
max_sensor_values[i] = xline[i];
}
}
// Save the min and max calibration values
for(uint8_t i = 0 ; i < _num_sensors; i++){
if(min_sensor_values[i] > calibrated_max[i])
calibrated_max[i] = min_sensor_values[i];
if(max_sensor_values[i] < calibrated_min[i])
calibrated_min[i] = max_sensor_values[i];
}
}
/**
* @brief Runs full 5s calibration sequence and print result
*
* Calibrates be successively calling xline_calibrate over a 5s period
* Then prints all min/max recorded values for the user.
*/
void xline_calibration_sequence(void){
printf("============ CALIBRATING XLINE ==============\r\n");
printf("\t - Calibrating over 5S\r\n");
printf("\t - Move the sensor over the line back and "
"forth with a reasonable speed.\r\n");
for(uint8_t i = 0; i < 100; i++){
xline_calibrate();
HAL_Delay(50);
}
printf("================ CALIBRATION COMPLETE =============\r\n");
for(uint8_t i = 0; i < 16; i++){
printf("Sensor %d: \r\n\t min: %lu\r\n\t max: %lu\r\n", i, calibrated_min[i], calibrated_max[i]);
}
}
/**
* @brief Reset calibration values.
*
*/
void xline_reset_calibration(void){
for(uint8_t i = 0 ; i < _num_sensors; i++){
calibrated_min[i] = 1023;
calibrated_max[i] = 0;
}
}
/**
* @brief Read all sensors and store raw values in supplied array.
*
* @param sensor_values Array to store values. The size needs to be equal or bigger than number of sensors.
*/
void xline_read(void){
// Reset old values
for(uint8_t i = 0 ; i < _num_sensors; i++){
xline[i] = 0;
}
for(uint8_t i = 0 ; i < _num_sensors; i++){
xline_mux_select(i);
HAL_ADC_Start(&hadc2);
HAL_ADC_PollForConversion(&hadc2, 5);
uint32_t raw = HAL_ADC_GetValue(&hadc2);
xline[i] = raw;
HAL_ADC_Stop(&hadc2);
}
}
/**
* @brief Read all sensors and store calibrated values in supplied array.
*
* Returns values calibrated to a value between 0 and 1000, where
* 0 corresponds to the minimum value read by xline_calibrate() and 1000
* corresponds to the maximum value. Calibration values are
* stored separately for each sensor, so that differences in the
* sensors are accounted for automatically.
* @param sensor_values Array to store values.
*/
void xline_read_calibrated(void){
xline_read();
for(uint8_t i = 0 ; i < _num_sensors; i++){
uint32_t denominator = calibrated_max[i] - calibrated_min[i];
int x = 0;
if(denominator != 0)
// Check the real reason for need to cast all to int
x = ((int)( ((int)xline[i]) - ((int)calibrated_min[i]))) * 1000 / (int)denominator;
if(x < 0)
x = 0;
else if(x > 1000)
x = 1000;
// Add additional check when sensor is blocked
xline[i] = x;
}
}
/**
* @brief Reads with calibrated sensor data and estimates position with respect to a black line on white surface.
*
* The estimate is made using a weighted average.
* The return value is in the range of 0 to 1000*(N-1)
* E.g 16 sensors => 0 to 15000 and the line beeing in the center when 7500.
* The value is continous and remain at the latest value when leaving a line.
* E.g Robot drifts away from the line and the rightmost sensor leaving the latest will result in 4500 beeing returned.
*
* The formula is:
*
* 0*value0 + 1000*value1 + 2000*value2 + ...
* --------------------------------------------
* value0 + value1 + value2 + ...
*
* @param sensor_values
* @return int Estimated position
*/
int xline_read_line(void){
uint8_t i, on_line = 0;
unsigned long avg = 0; // weighted total
unsigned int sum = 0; // this is for the denominator which is <= 64000
static int last_value = 0; // assume initially that the line is left.
int return_val = 0;
xline_read_calibrated();
for( i = 0; i < _num_sensors; i++) {
int value = xline[i];
//if(white_line)
// value = 1000 - value;
// keep track of whether we see the line at all
if(value > 200) {
on_line = 1;
}
// only average in values that are above a noise threshold
if(value > 50) {
avg += (long)(value) * (i * 1000);
sum += value;
}
}
if(!on_line)
{
// If it last read to the left of center, return 0.
if(last_value < (_num_sensors - 1) *1000 /2)
return_val = 0;
// If it last read to the right of center, return the max.
else
return_val = (_num_sensors - 1)*1000;
}else{
last_value = avg/sum;
return_val = last_value;
}
return return_val - (16-1)/2.0f * 1000;
};
/**
* @brief Selecting which sensor to read from via the MUX. (Multiplexer)
*
* @param sensor_n Sensor to active.
*/
void xline_mux_select(uint8_t sensor){
HAL_GPIO_WritePin(MUX0_GPIO_Port, MUX0_Pin, (sensor & 0b1) > 0);
HAL_GPIO_WritePin(MUX1_GPIO_Port, MUX1_Pin, (sensor & 0b10) > 0);
HAL_GPIO_WritePin(MUX2_GPIO_Port, MUX2_Pin, (sensor & 0b100) > 0);
HAL_GPIO_WritePin(MUX3_GPIO_Port, MUX3_Pin, (sensor & 0b1000) > 0);
};
| 2.65625 | 3 |
2024-11-18T21:30:21.342780+00:00 | 2019-03-01T05:16:46 | 37a46e72e2dd57b4b4374f7c99a67cf9e485d62d | {
"blob_id": "37a46e72e2dd57b4b4374f7c99a67cf9e485d62d",
"branch_name": "refs/heads/master",
"committer_date": "2019-03-01T05:16:46",
"content_id": "8210058827761490a11391d6c5174e6f49656c92",
"detected_licenses": [
"MIT"
],
"directory_id": "5a17a3d150c4773318d397a46878d2fd74c0671f",
"extension": "c",
"filename": "zuoyou-hubo.c",
"fork_events_count": 0,
"gha_created_at": "2018-12-26T11:38:10",
"gha_event_created_at": "2018-12-26T11:38:10",
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 163173406,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2003,
"license": "MIT",
"license_type": "permissive",
"path": "/nitan/kungfu/skill/zuoyou-hubo.c",
"provenance": "stackv2-0112.json.gz:195082",
"repo_name": "cantona/NT6",
"revision_date": "2019-03-01T05:16:46",
"revision_id": "073f4d491b3cfe6bfbe02fbad12db8983c1b9201",
"snapshot_id": "e9adc7308619b614990fa64456c294fad5f07d61",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/cantona/NT6/073f4d491b3cfe6bfbe02fbad12db8983c1b9201/nitan/kungfu/skill/zuoyou-hubo.c",
"visit_date": "2020-04-15T21:16:28.817947"
} | stackv2 | // zuoyou-hubo.c 左右互博
// by Doing Lu
inherit SKILL;
#include <ansi.h>
#define LEVEL_PER_LAYER 30
#define MAX_LAYER 10
int valid_learn(object me)
{
int layer;
int lvl;
lvl = me->query_skill("zuoyou-hubo", 1);
if( query("gender", me) == "無性" && lvl >= 50 )
return notify_fail("你默默凝神,試圖分心二"
"用,可是卻覺得陰陽失調,心浮氣躁。\n");
if( me->query_skill("count",1) && !query("special_skill/capture", me) )
return notify_fail("你受到陰陽八卦影響甚深,難以嘗"
"試更高深的分心之術。\n");
if( query("int", me)>24 && query("int", me)<40 )
return notify_fail("你覺得心煩意亂,難以嘗"
"試更高深的分心之術。\n");
if ((int)me->query_skill("force") < lvl * 3 / 2)
return notify_fail("你的內功火候不夠,難以輕鬆自如的分運兩股內力。\n");
return 1;
}
int practice_skill(object me)
{
return notify_fail("左右互博只能通過學習不斷提高。\n");
}
void skill_improved(object me)
{
int lvl;
int layer;
lvl = me->query_skill("zuoyou-hubo", 1);
layer = lvl / LEVEL_PER_LAYER;
if (layer > MAX_LAYER) layer = MAX_LAYER;
if (! layer)
{
tell_object(me, HIM "你潛心領悟左右互"
"博,若有所悟。\n" NOR);
} else
if ((lvl % LEVEL_PER_LAYER) == 0)
{
tell_object(me, HIM "你領悟了第" + chinese_number(layer) +
"層境界的左右互博的奧妙。\n" NOR);
} else
tell_object(me, HIM "你對第" + chinese_number(layer) +
"層境界的左右互博又加深了一點了解。\n" NOR);
} | 2.359375 | 2 |
2024-11-18T21:30:21.635368+00:00 | 2017-02-17T05:49:13 | f4c36269cc20c2bdb5791873e013124e862f630f | {
"blob_id": "f4c36269cc20c2bdb5791873e013124e862f630f",
"branch_name": "refs/heads/master",
"committer_date": "2017-02-17T05:49:13",
"content_id": "31da5433ab8a5d60b40065a6032e05fc75c96d84",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "63f9bda853367daa39728f82d02891ccfc4a1114",
"extension": "c",
"filename": "sleep.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 17422941,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 581,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/src/sleep/sleep.c",
"provenance": "stackv2-0112.json.gz:195602",
"repo_name": "TeamWau/speedutils",
"revision_date": "2017-02-17T05:49:13",
"revision_id": "db22ad83abaaa10d2ab5e38aed53c95ed25c263a",
"snapshot_id": "568e918b25f274f8f3625e791c6657beeaaf05f3",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/TeamWau/speedutils/db22ad83abaaa10d2ab5e38aed53c95ed25c263a/src/sleep/sleep.c",
"visit_date": "2021-01-13T02:24:19.895931"
} | stackv2 | #include <stdio.h>
#include <unistd.h>
#define PROGRAM_NAME "SLEEP"
#define AUTHORS "blackfox, fauxm"
int main( int argc, char **argv ) {
int time;
if( argc != 2 ) {
fprintf(stderr, "usage: %s <time>\n", argv[0]);
return 1;
}
//todo: make this catch *all* letters in argv[1], currently it only fails if there's one at the start.
if( ( time = atoi( argv[1] ) ) != NULL ) {
sleep( time );
return 0;
}
else {
fprintf( stderr, "%s: error: invalid character in argument\n", argv[0] );
return 1;
}
}
| 2.671875 | 3 |
2024-11-18T21:30:22.025297+00:00 | 2017-03-26T23:25:57 | 4664d99dcd7a3449dbed9d90c0c43705029a487b | {
"blob_id": "4664d99dcd7a3449dbed9d90c0c43705029a487b",
"branch_name": "refs/heads/master",
"committer_date": "2017-03-26T23:25:57",
"content_id": "64afe3ec2b476a21061669ef46a16ee9b7f7a103",
"detected_licenses": [
"Zlib"
],
"directory_id": "1c4d3b5a11137f750f07851a772c490a22b2cb0c",
"extension": "c",
"filename": "player.c",
"fork_events_count": 4,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 22835205,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4547,
"license": "Zlib",
"license_type": "permissive",
"path": "/old_mobile/example-game/src/player.c",
"provenance": "stackv2-0112.json.gz:195861",
"repo_name": "SirGFM/GFraMe",
"revision_date": "2017-03-26T23:25:57",
"revision_id": "4cc02182be905189a9aa04467d5bbf8640184cd3",
"snapshot_id": "08d58b1b3cea4502c7166fa27f4b93170000969a",
"src_encoding": "UTF-8",
"star_events_count": 13,
"url": "https://raw.githubusercontent.com/SirGFM/GFraMe/4cc02182be905189a9aa04467d5bbf8640184cd3/old_mobile/example-game/src/player.c",
"visit_date": "2021-01-23T11:23:08.843630"
} | stackv2 | /**
* @src/player.c
*/
#include <GFraMe/GFraMe_animation.h>
#include <GFraMe/GFraMe_audio.h>
#include <GFraMe/GFraMe_error.h>
#include <GFraMe/GFraMe_object.h>
#include <GFraMe/GFraMe_screen.h>
#include <GFraMe/GFraMe_sprite.h>
#include <GFraMe/GFraMe_util.h>
#include "background.h"
#include "global.h"
#include "multiplier.h"
#include "player.h"
#define BASE_JUMP 200.0
/**
* Player's sprite
*/
static GFraMe_sprite player;
/**
* Target that the player will jump/dash toward
*/
static GFraMe_sprite tgt;
/**
* Target's animation
*/
static GFraMe_animation tgt_anim;
/**
* Data for the target's animation
*/
static int tgt_anim_data[4] = {27, 28, 29, 28};
static double jump_speed;
static int cooldown;
static int combo;
static int did_combo;
static double time;
void player_init() {
// Draw debug!!
GFraMe_draw_debug = 1;
// Init the player itself
GFraMe_sprite_init(&player, (320-32)/2, 120, 14, 24, &gl_sset32, -6, -9);
player.cur_tile = 13;
player.obj.ay = 500;
// Init the target
GFraMe_sprite_init(&tgt, -16, -16, 16, 16, &gl_sset16, 0, 0);
// Init the target's animation
GFraMe_animation_init(&tgt_anim, 12, tgt_anim_data, 4, 1);
GFraMe_sprite_set_animation(&tgt, &tgt_anim);
//tgt.cur_tile = 14;
tgt.id = 0;
// Set the players initial jump speed
jump_speed = BASE_JUMP;
// Set the timer (for consecutive jump) and counter
cooldown = 0;
combo = 0;
did_combo = 0;
}
void player_update(int ms) {
if (player.obj.hit & GFraMe_direction_down) {
if (player.obj.vy >= 0.0 && player.obj.ax == 0.0f &&
player.obj.vx != 0.0)
player.obj.ax = -player.obj.vx * 4.0;
else if(player.obj.ax != 0.0 &&
GFraMe_util_absd(player.obj.vx) <= 16.0) {
player.obj.vx = 0.0;
player.obj.ax = 0.0;
}
}
else if (tgt.id) {
double X = tgt.obj.x - player.obj.x;
double Y = tgt.obj.y - player.obj.y;
double dist = GFraMe_util_sqrtd(X*X + Y*Y);
player.obj.vx = player.obj.vx / 4.0 + X / dist * jump_speed + player.obj.ay*time*time*0.25;
player.obj.vy = Y / dist * jump_speed + player.obj.ay*time*time*0.5;
if (player.obj.vx != 0.0)
player.flipped = player.obj.vx < 0.0;
time += (double)ms / 1000.0;
}
GFraMe_sprite_update(&player, ms);
if (cooldown > 0)
cooldown -= ms;
if (tgt.id > 0)
GFraMe_sprite_update(&tgt, ms);
}
void player_draw() {
GFraMe_sprite_draw(&player);
if (tgt.id)
GFraMe_sprite_draw(&tgt);
}
int player_slowdown() {
int ret = (player.obj.y < FLOOR_Y
&& !(player.obj.hit && GFraMe_direction_down)
&& GFraMe_util_absd(player.obj.vy) < 32.0 && !tgt.id);
did_combo = did_combo && !ret;
return cooldown > 0 || ret;
}
void player_on_ground() {
jump_speed = BASE_JUMP;
tgt.id = 0;
combo = 0;
cooldown = 0;
player.obj.ax = 0.0;
if (did_combo) {
multi_half();
player.obj.vy = -jump_speed;
GFraMe_audio_play(&gl_floor, 0.5);
}
else {
multi_reset();
player.obj.vy = 0.0;
player.cur_tile = 13;
if (player.obj.x - player.obj.hitbox.cx - player.obj.hitbox.hw
> GFraMe_screen_w
|| player.obj.x + player.obj.hitbox.cx + player.obj.hitbox.hw
< 0)
player.obj.vx = 0;
}
did_combo = 0;
}
GFraMe_ret player_on_squash() {
// Check if the player did squash an enemy
if (player.obj.y + player.obj.hitbox.cy +player.obj.hitbox.hh >= 158 ||
!(player.obj.hit & GFraMe_direction_down) || player.obj.vy < 0)
return GFraMe_ret_failed;
// Increase its speed
if (jump_speed < 350)
jump_speed += 25;
// Sets the cooldown for fast jumping
if (combo < 10)
cooldown = 135 - combo * 10;
else
cooldown = 35;
// Increment the combo counter
combo++;
// Make the player jump
player.obj.vy = -jump_speed;
tgt.id = 0;
if (player.obj.vx != 0.0)
player.flipped = player.obj.vx < 0.0;
return GFraMe_ret_ok;
}
void player_set_target(int X, int Y) {
if (player.obj.y + player.obj.hitbox.cy + player.obj.hitbox.hh < FLOOR_Y
&& Y > 154
&& (GFraMe_util_absd(player.obj.vy) < 64.0 || cooldown > 0)
) {
tgt.id = 1;
GFraMe_object_set_pos(&tgt.obj, X, Y);
did_combo = cooldown > 0;
cooldown = 0;
GFraMe_audio_play(&gl_charge, 0.25);
time = 0.0;
}
}
GFraMe_ret player_jump(int X) {
// Check if the player is jumping
if (!(player.obj.hit & GFraMe_direction_down))
return GFraMe_ret_failed;
// Otherwise, make it jump
player.obj.vy = -jump_speed;
player.obj.vx = X - player.obj.x;
player.obj.ax = 0.0;
player.cur_tile = 14;
GFraMe_audio_play(&gl_jump, 0.5);
if (player.obj.vx != 0.0)
player.flipped = player.obj.vx < 0.0;
return GFraMe_ret_ok;
}
GFraMe_object *player_get_object() {
return &player.obj;
}
| 2.5 | 2 |
2024-11-18T22:23:38.083983+00:00 | 2022-05-01T10:07:59 | 7b88cc70ef291a482585b04225e5770a336034d9 | {
"blob_id": "7b88cc70ef291a482585b04225e5770a336034d9",
"branch_name": "refs/heads/master",
"committer_date": "2022-05-01T10:07:59",
"content_id": "1a7c084630a11dbfcd41074c3caa338ef5a05837",
"detected_licenses": [
"MIT"
],
"directory_id": "9f2dd3b7db31b547ead8d9241b42ce8bff4a4e07",
"extension": "c",
"filename": "win.c",
"fork_events_count": 118,
"gha_created_at": "2021-04-28T19:38:11",
"gha_event_created_at": "2022-06-05T13:52:16",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 362586600,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2208,
"license": "MIT",
"license_type": "permissive",
"path": "/emu/win/win.c",
"provenance": "stackv2-0115.json.gz:67063",
"repo_name": "jdah/jdh-8",
"revision_date": "2022-05-01T10:07:59",
"revision_id": "e4fad7cf43c8a23066d4a230baaa130354fbefbf",
"snapshot_id": "81f02e01d0ee9cae90e7905575a489bddb7f576e",
"src_encoding": "UTF-8",
"star_events_count": 1245,
"url": "https://raw.githubusercontent.com/jdah/jdh-8/e4fad7cf43c8a23066d4a230baaa130354fbefbf/emu/win/win.c",
"visit_date": "2023-06-12T15:56:20.625965"
} | stackv2 | #include "win.h"
#include "mman.h"
// from https://narkive.com/oLyNbGSV
int poll(struct pollfd *p, int num, int timeout) {
struct timeval tv;
fd_set read, write, except;
int i, n, ret;
FD_ZERO(&read);
FD_ZERO(&write);
FD_ZERO(&except);
n = -1;
for (i = 0; i < num; i++) {
if (p[i].fd < 0) continue;
if (p[i].events & POLLIN) FD_SET(p[i].fd, &read);
if (p[i].events & POLLOUT) FD_SET(p[i].fd, &write);
if (p[i].events & POLLERR) FD_SET(p[i].fd, &except);
if (p[i].fd > n) n = p[i].fd;
}
if (n == -1) {
return 0;
}
if (timeout < 0) {
ret = select(n + 1, &read, &write, &except, NULL);
} else {
tv.tv_sec = timeout / 1000;
tv.tv_usec = 1000 * (timeout % 1000);
ret = select(n + 1, &read, &write, &except, &tv);
}
for (i = 0; ret >= 0 && i < num; i++) {
p[i].revents = 0;
if (FD_ISSET(p[i].fd, &read)) p[i].revents |= POLLIN;
if (FD_ISSET(p[i].fd, &write)) p[i].revents |= POLLOUT;
if (FD_ISSET(p[i].fd, &except)) p[i].revents |= POLLERR;
}
return ret;
}
// from https://github.com/Arryboom/fmemopen_windows/blob/master/libfmemopen.c
FILE *fmemopen(void *buf, size_t len, const char *type) {
int fd;
FILE *fp;
char tp[MAX_PATH - 13];
char fn[MAX_PATH + 1];
int * pfd = &fd;
int retner = -1;
char tfname[] = "MemTF_";
if (!GetTempPathA(sizeof(tp), tp))
return NULL;
if (!GetTempFileNameA(tp, tfname, 0, fn))
return NULL;
retner = _sopen_s(
pfd, fn,
_O_CREAT | _O_SHORT_LIVED | _O_TEMPORARY | _O_RDWR | _O_BINARY
| _O_NOINHERIT, _SH_DENYRW, _S_IREAD | _S_IWRITE
);
if (retner != 0)
return NULL;
if (fd == -1)
return NULL;
fp = _fdopen(fd, "wb+");
if (!fp) {
_close(fd);
return NULL;
}
/*File descriptors passed into _fdopen are owned by the returned FILE * stream.If _fdopen is successful, do not call _close on the file descriptor.Calling fclose on the returned FILE * also closes the file descriptor.*/
fwrite(buf, len, 1, fp);
rewind(fp);
return fp;
}
char* readline(char* prompt) {
char* retval = NULL;
printf("> ");
scanf("%s", retval);
return retval;
}
void add_history(const char* string) {}
| 2.359375 | 2 |
2024-11-18T22:23:38.544701+00:00 | 2020-12-23T04:59:22 | b0ed5f61aac7fba1f5dd58c781525f9f148eda20 | {
"blob_id": "b0ed5f61aac7fba1f5dd58c781525f9f148eda20",
"branch_name": "refs/heads/master",
"committer_date": "2020-12-23T04:59:22",
"content_id": "fa53892167ce5f740ce53200afa53cba946dca35",
"detected_licenses": [
"MIT"
],
"directory_id": "ec186b5d7e927b5dfb9e13ee63180d7ef89d25ef",
"extension": "c",
"filename": "main.c",
"fork_events_count": 3,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 287267538,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4155,
"license": "MIT",
"license_type": "permissive",
"path": "/assignments/1/p1/main.c",
"provenance": "stackv2-0115.json.gz:67192",
"repo_name": "plibither8/iiitd_cse231-os",
"revision_date": "2020-12-23T04:59:22",
"revision_id": "95618c0527db561ab2cf2bce55a43d0d95529ffc",
"snapshot_id": "dd4dc0614dadc2bb9a42ddc98fa86aac20349d1f",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/plibither8/iiitd_cse231-os/95618c0527db561ab2cf2bce55a43d0d95529ffc/assignments/1/p1/main.c",
"visit_date": "2023-02-05T05:43:37.501407"
} | stackv2 | #include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
// Error message constants
#define ERR_FILE_OPEN "ERR! File could not be opened properly."
#define ERR_FILE_SEEK "ERR! Could not seek in file."
#define ERR_FILE_READ "ERR! Could not read file."
#define ERR_FILE_CLOSE "ERR! Could not close file."
#define ERR_WRITE "ERR! Could not write to specified stream"
#define ERR_FORK "ERR! Could not fork parent."
// Simple wrapper to take in error message
// and print out to stderr stream
void throw_error(char *msg)
{
write(STDERR_FILENO, msg, strlen(msg));
write(STDERR_FILENO, "\n", 1);
exit(EXIT_FAILURE);
}
// Open the csv file and produce error
// if it couldn't be opened
int open_file(char *filename)
{
int fd = open(filename, O_RDONLY);
if (fd == -1)
throw_error(ERR_FILE_OPEN);
return fd;
}
// Get the file length (number of bytes)
// to be used to print the content
int get_file_length(int fd)
{
int file_length = (int) lseek(fd, 0, SEEK_END);
if (file_length == -1)
throw_error(ERR_FILE_SEEK);
// Go back to the start of the file
if ((int) lseek(fd, 0, SEEK_SET) == -1)
throw_error(ERR_FILE_SEEK);
return file_length;
}
// Read file from file descriptor and file length
char *read_file(int fd, int file_length)
{
// Allocate memory for file content
char *buf = (char *) calloc(file_length, sizeof(char));
// Read the file
if (read(fd, buf, file_length) == -1)
throw_error(ERR_FILE_READ);
return buf;
}
// Close file from file descriptor
void close_file(int fd, char *buf)
{
free(buf);
if (close(fd) == -1)
throw_error(ERR_FILE_CLOSE);
}
// Parse CSV row
void parse_line(char *line, char section)
{
int student_id;
int sum = 0, count = 0;
char student_section;
char *token;
char *saveptr;
char *delim = " ";
// Student ID
token = strtok_r(line, delim, &saveptr);
student_id = atoi(token);
// Student section
token = strtok_r(NULL, delim, &saveptr);
student_section = token[0];
// If the student section is not same
// as the requested section, return
if (student_section != section) return;
// Loop over next ints, calc sum and count
while (token = strtok_r(NULL, delim, &saveptr))
{
sum += atoi(token);
count++;
}
// Calculate average
float average = (float) sum / count;
// Assign memory for storing to-be-printed text
char *text = (char *) calloc(20, sizeof(char));
snprintf(text, 20, "%d: %f\n", student_id, average);
// Write final output to stdout
if (write(STDOUT_FILENO, text, strlen(text)) == -1)
throw_error(ERR_WRITE);
free(text);
}
// Parse the CSV table
void parse_file(char *file_content, char section)
{
char *saveptr;
char *delim = "\n";
char *line = strtok_r(file_content, delim, &saveptr);
int header = 1;
do {
// Skip the initial CSV header
if (header)
{
header = 0;
continue;
}
// Parse the current line
parse_line(line, section);
}
while (line = strtok_r(NULL, delim, &saveptr));
}
int main(int argc, char *argv[])
{
// Fork the process and store child pid
pid_t child_pid = fork();
switch (child_pid)
{
case 0:
{ // Child process
int fd = open_file("marks.csv");
int file_length = get_file_length(fd);
char *file_content = read_file(fd, file_length);
char *heading = "Section A:\n";
if (write(STDOUT_FILENO, heading, strlen(heading)) == -1)
throw_error(ERR_WRITE);
parse_file(file_content, 'A');
close_file(fd, file_content);
_exit(EXIT_SUCCESS);
}
case -1: // Error in forking
throw_error(ERR_FORK);
default:
{ // Parent process
waitpid(child_pid, NULL, 0);
int fd = open_file("marks.csv");
int file_length = get_file_length(fd);
char *file_content = read_file(fd, file_length);
char *heading = "\n\nSection B:\n";
if (write(STDOUT_FILENO, heading, strlen(heading)) == -1)
throw_error(ERR_WRITE);
parse_file(file_content, 'B');
close_file(fd, file_content);
}
}
return 0;
}
| 2.8125 | 3 |
2024-11-18T22:23:38.750565+00:00 | 2020-11-16T06:35:49 | f75f0db70911365ca44116059617fc6eae56861f | {
"blob_id": "f75f0db70911365ca44116059617fc6eae56861f",
"branch_name": "refs/heads/master",
"committer_date": "2020-11-16T06:35:49",
"content_id": "652ecd8806d91225c43ee0379a81ffd7fb3ebfd3",
"detected_licenses": [
"MIT"
],
"directory_id": "ff144f200c8d9b199e7f8192e2ed305f97b04cfa",
"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": 242969876,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1263,
"license": "MIT",
"license_type": "permissive",
"path": "/7-1 英文单词排序/main.c",
"provenance": "stackv2-0115.json.gz:67321",
"repo_name": "Mythologyli/C-Works-Pro",
"revision_date": "2020-11-16T06:35:49",
"revision_id": "11a31011d260d74841f6c9ec517e32d126c4d3f0",
"snapshot_id": "ab3e9a19d1182a2b4fa6aa4f839c8bc28058eb69",
"src_encoding": "GB18030",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Mythologyli/C-Works-Pro/11a31011d260d74841f6c9ec517e32d126c4d3f0/7-1 英文单词排序/main.c",
"visit_date": "2021-01-16T13:53:16.033763"
} | stackv2 | #define _CRT_SECURE_NO_WARNINGS
/*防止使用scanf()等函数时报错*/
/*
本题要求编写程序,输入若干英文单词,对这些单词按长度从小到大排序后输出。如果长度相同,按照输入的顺序不变。
输入格式:
输入为若干英文单词,每行一个,以#作为输入结束标志。其中英文单词总数不超过20个,英文单词为长度小于10的仅由小写英文字母组成的字符串。
输出格式:
输出为排序后的结果,每个单词后面都额外输出一个空格。
输入样例:
blue
red
yellow
green
purple
#
输出样例:
red blue green yellow purple
*/
#include <stdio.h>
//#include <math.h>
//#include <stdlib.h>
#include <string.h>
//#include <stdbool.h>
int main(void)
{
char* word[21] = { NULL };
char* temp;
int n; //单词的个数
for (int i = 0; ; i++)
{
word[i] = (char*)malloc(sizeof(char) * 11);
scanf("%s", word[i]);
if (strcmp(word[i], "#") == 0)
{
n = i;
break;
}
}
for (int i = 1; i < n; i++)
{
for (int j = 0; j < n - i; j++)
if (strlen(word[j]) > strlen(word[j + 1]))
{
temp = word[j];
word[j] = word[j + 1];
word[j + 1] = temp;
}
}
for (int i = 0; i < n; i++)
printf("%s ", word[i]);
return 0;
} | 3.34375 | 3 |
2024-11-18T22:23:39.427104+00:00 | 2020-12-18T20:34:54 | a5e8d369cbc2a8aa1105e5a775953be0ce8f1a18 | {
"blob_id": "a5e8d369cbc2a8aa1105e5a775953be0ce8f1a18",
"branch_name": "refs/heads/master",
"committer_date": "2020-12-18T20:34:54",
"content_id": "1b0c3338701bc5202f4c526a133e88f9a2df3b57",
"detected_licenses": [
"MIT"
],
"directory_id": "9fa84297caded09da03ce311e4807b6107aad68b",
"extension": "c",
"filename": "test_foo.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 322106904,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 819,
"license": "MIT",
"license_type": "permissive",
"path": "/example/test/test_foo.c",
"provenance": "stackv2-0115.json.gz:67707",
"repo_name": "smadin/scuttle",
"revision_date": "2020-12-18T20:34:54",
"revision_id": "fe820429a472bea5e153911b4e136f4e24b2626e",
"snapshot_id": "7414b5ffb4d6fd27c6c9db6076a68f770d6cde4f",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/smadin/scuttle/fe820429a472bea5e153911b4e136f4e24b2626e/example/test/test_foo.c",
"visit_date": "2023-02-03T08:45:02.553945"
} | stackv2 | #include "foo.h"
#include "test_foo.h"
#include <stdio.h>
SSUITE_INIT(example_foo)
printf("example_foo suite init\n");
SSUITE_READY
STEST_SETUP
printf("example_foo test setup\n");
STEST_SETUP_END
STEST_TEARDOWN
printf("example_foo test teardown\n");
STEST_TEARDOWN_END
STEST_START(foo_returns_fortytwo)
int i = foo();
SASSERT(i == 42)
SREFUTE(i != 42)
SASSERT_EQ(i, 42)
STEST_END
STEST_START(foo_doesnt_return_sixtynine)
int i = foo();
SREFUTE(i == 69)
STEST_END
STEST_START(foostr_sets_buf)
char buf[10];
int i = foostr(buf, 10);
SASSERT(i)
const char *expected = "foo";
SASSERT_STREQ(buf, expected)
STEST_END
STEST_START(foostr_doesnt_set_buf)
char buf[2];
int i = foostr(buf, 2);
SREFUTE(i)
i = foostr(NULL, 10);
SREFUTE(i)
STEST_END | 2.453125 | 2 |
2024-11-18T22:23:40.702280+00:00 | 2020-05-16T21:01:48 | 2ea5382ed0e958b093751df63db2db4e150902c4 | {
"blob_id": "2ea5382ed0e958b093751df63db2db4e150902c4",
"branch_name": "refs/heads/master",
"committer_date": "2020-05-16T21:09:41",
"content_id": "996b0ccb4a4d1e7e71de67041582e29ab74c197f",
"detected_licenses": [
"BSD-3-Clause",
"Zlib"
],
"directory_id": "319da1ddb8a6c98794780488860b2631cabbbac2",
"extension": "c",
"filename": "lstddrv.c",
"fork_events_count": 0,
"gha_created_at": "2020-06-01T17:46:58",
"gha_event_created_at": "2020-06-01T17:46:59",
"gha_language": null,
"gha_license_id": "NOASSERTION",
"github_id": 268591739,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2620,
"license": "BSD-3-Clause,Zlib",
"license_type": "permissive",
"path": "/src/linux/lstddrv.c",
"provenance": "stackv2-0115.json.gz:68352",
"repo_name": "guzmandrade/allegro5",
"revision_date": "2020-05-16T21:01:48",
"revision_id": "44a2b291bcc8f921828e357feb02785f622271f4",
"snapshot_id": "6c27ea6b9beda5e81496e15b3ea2bd7c6feda575",
"src_encoding": "UTF-8",
"star_events_count": 15,
"url": "https://raw.githubusercontent.com/guzmandrade/allegro5/44a2b291bcc8f921828e357feb02785f622271f4/src/linux/lstddrv.c",
"visit_date": "2022-07-18T00:22:19.067755"
} | stackv2 | #error This file is no longer used.
/* ______ ___ ___
* /\ _ \ /\_ \ /\_ \
* \ \ \L\ \\//\ \ \//\ \ __ __ _ __ ___
* \ \ __ \ \ \ \ \ \ \ /'__`\ /'_ `\/\`'__\/ __`\
* \ \ \/\ \ \_\ \_ \_\ \_/\ __//\ \L\ \ \ \//\ \L\ \
* \ \_\ \_\/\____\/\____\ \____\ \____ \ \_\\ \____/
* \/_/\/_/\/____/\/____/\/____/\/___L\ \/_/ \/___/
* /\____/
* \_/__/
*
* Standard driver helpers for Linux Allegro.
*
* By Marek Habersack, mangled by George Foot.
*
* See readme.txt for copyright information.
*/
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#include "allegro5/allegro.h"
#include "allegro5/internal/aintern.h"
#include "allegro5/platform/aintunix.h"
#include "allegro5/linalleg.h"
#include <unistd.h>
/* List of standard drivers */
STD_DRIVER *__al_linux_std_drivers[N_STD_DRIVERS];
static int std_drivers_suspended = false;
/* __al_linux_add_standard_driver:
* Adds a standard driver; returns 0 on success, non-zero if the sanity
* checks fail.
*/
int __al_linux_add_standard_driver (STD_DRIVER *spec)
{
if (!spec) return 1;
if (spec->type >= N_STD_DRIVERS) return 2;
if (!spec->update) return 3;
if (spec->fd < 0) return 4;
__al_linux_std_drivers[spec->type] = spec;
spec->resume();
return 0;
}
/* __al_linux_remove_standard_driver:
* Removes a standard driver, returning 0 on success or non-zero on
* failure.
*/
int __al_linux_remove_standard_driver (STD_DRIVER *spec)
{
if (!spec) return 1;
if (spec->type >= N_STD_DRIVERS) return 3;
if (!__al_linux_std_drivers[spec->type]) return 4;
if (__al_linux_std_drivers[spec->type] != spec) return 5;
spec->suspend();
__al_linux_std_drivers[spec->type] = NULL;
return 0;
}
/* __al_linux_update_standard_drivers:
* Updates all drivers.
*/
void __al_linux_update_standard_drivers (int threaded)
{
int i;
if (!std_drivers_suspended) {
for (i = 0; i < N_STD_DRIVERS; i++)
if (__al_linux_std_drivers[i])
__al_linux_std_drivers[i]->update();
}
}
/* __al_linux_suspend_standard_drivers:
* Temporary disable standard drivers during a VT switch.
*/
void __al_linux_suspend_standard_drivers (void)
{
ASSERT(!std_drivers_suspended);
std_drivers_suspended = true;
}
/* __al_linux_resume_standard_drivers:
* Re-enable standard drivers after a VT switch.
*/
void __al_linux_resume_standard_drivers (void)
{
ASSERT(std_drivers_suspended);
std_drivers_suspended = false;
}
| 2.109375 | 2 |
2024-11-18T22:23:40.848403+00:00 | 2017-07-13T10:08:14 | 39174279e1de3e0a04f007a0c9b159cd24bad9c8 | {
"blob_id": "39174279e1de3e0a04f007a0c9b159cd24bad9c8",
"branch_name": "refs/heads/master",
"committer_date": "2017-07-13T10:08:14",
"content_id": "7afc976b6bb33b96fc95c6e26ee4fa671ca8fe2a",
"detected_licenses": [
"MIT"
],
"directory_id": "7f95a01ad00c218f4f81228f478464fa76fc0a7e",
"extension": "c",
"filename": "PaddingBitsAtom.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": 5628,
"license": "MIT",
"license_type": "permissive",
"path": "/lib/libisomediafile/src/PaddingBitsAtom.c",
"provenance": "stackv2-0115.json.gz:68609",
"repo_name": "j3parera/TFM",
"revision_date": "2017-07-13T10:08:14",
"revision_id": "70ebac9678260841257f46cdbe523ed8a84c284e",
"snapshot_id": "3ba8361265d4e8531f39eb382f7b35700790b8db",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/j3parera/TFM/70ebac9678260841257f46cdbe523ed8a84c284e/lib/libisomediafile/src/PaddingBitsAtom.c",
"visit_date": "2021-01-01T15:29:30.764995"
} | stackv2 | /*
This software module was originally developed by Apple Computer, Inc.
in the course of development of MPEG-4.
This software module is an implementation of a part of one or
more MPEG-4 tools as specified by MPEG-4.
ISO/IEC gives users of MPEG-4 free license to this
software module or modifications thereof for use in hardware
or software products claiming conformance to MPEG-4.
Those intending to use this software module in hardware or software
products are advised that its use may infringe existing patents.
The original developer of this software module and his/her company,
the subsequent editors and their companies, and ISO/IEC have no
liability for use of this software module or modifications thereof
in an implementation.
Copyright is not released for non MPEG-4 conforming
products. Apple Computer, Inc. retains full right to use the code for its own
purpose, assign or donate the code to a third party and to
inhibit third parties from using the code for non
MPEG-4 conforming products.
This copyright notice must be included in all copies or
derivative works. Copyright (c) 1999.
*/
/*
$Id: PaddingBitsAtom.c,v 1.1.1.1 2002/09/20 08:53:35 julien Exp $
*/
#include "MP4Atoms.h"
#include <stdlib.h>
#include <string.h>
static void destroy( MP4AtomPtr s )
{
MP4Err err;
MP4PaddingBitsAtomPtr self;
err = MP4NoErr;
self = (MP4PaddingBitsAtomPtr) s;
if ( self == NULL ) BAILWITHERROR( MP4BadParamErr )
if ( self->pads )
{
free( self->pads );
self->pads = NULL;
}
if ( self->super )
self->super->destroy( s );
bail:
TEST_RETURN( err );
return;
}
static MP4Err addSamplePads( struct MP4PaddingBitsAtom *self, u32 sampleCount, MP4Handle padsH )
{
MP4Err err;
u8 *PaddingBits;
u32 padsCount;
u8 *newpads;
u8 defaultpad;
u8 dodefault;
u32 i;
err = MP4NoErr;
dodefault =1;
defaultpad=0;
PaddingBits = NULL;
if (padsH!=NULL)
{
PaddingBits = (u8 *) *padsH;
err = MP4GetHandleSize( padsH, &padsCount ); if (err) goto bail;
switch (padsCount) {
case 0: break;
case 1: defaultpad=*PaddingBits; break;
default: dodefault=0; assert( sampleCount==padsCount ); break;
}
}
newpads = (u8*) calloc( sampleCount + self->sampleCount + 1, sizeof(u8) );
/* we add so we can easily pack up (see below) */
TESTMALLOC( newpads );
if ( self->sampleCount > 0)
memcpy( newpads, self->pads, self->sampleCount );
if (dodefault==0) {
memcpy( newpads + self->sampleCount, PaddingBits, padsCount );
}
else
{
for (i=0; i<sampleCount; i++)
newpads[i + self->sampleCount] = defaultpad;
}
if ( self->sampleCount > 0) free( self->pads );
self->pads = newpads;
self->sampleCount += sampleCount;
bail:
TEST_RETURN( err );
return err;
}
static MP4Err getPaddingBits( MP4AtomPtr s, u32 sampleNumber, u8 *outPad )
{
MP4Err err;
MP4PaddingBitsAtomPtr self = (MP4PaddingBitsAtomPtr) s;
err = MP4NoErr;
if ( (self == NULL) || (outPad == NULL) || (sampleNumber > self->sampleCount) || (sampleNumber == 0) )
BAILWITHERROR( MP4BadParamErr )
if (self->pads == NULL) *outPad = 0;
else
*outPad = self->pads[sampleNumber - 1];
bail:
TEST_RETURN( err );
return err;
}
static MP4Err serialize( struct MP4Atom* s, char* buffer )
{
MP4Err err;
u32 i;
MP4PaddingBitsAtomPtr self = (MP4PaddingBitsAtomPtr) s;
err = MP4NoErr;
err = MP4SerializeCommonFullAtomFields( (MP4FullAtomPtr) s, buffer ); if (err) goto bail;
buffer += self->bytesWritten;
PUT32( sampleCount );
for ( i = 0; i < ((self->sampleCount+1)/2); i++ )
{
PUT8_V( (self->pads[i*2] & 7) | ((self->pads[i*2+1] & 7)<<4) );
}
assert( self->bytesWritten == self->size );
bail:
TEST_RETURN( err );
return err;
}
static MP4Err calculateSize( struct MP4Atom* s )
{
MP4Err err;
MP4PaddingBitsAtomPtr self = (MP4PaddingBitsAtomPtr) s;
err = MP4NoErr;
err = MP4CalculateFullAtomFieldSize( (MP4FullAtomPtr) s ); if (err) goto bail;
self->size += ((self->sampleCount+1)/2) + 4;
bail:
TEST_RETURN( err );
return err;
}
static MP4Err createFromInputStream( MP4AtomPtr s, MP4AtomPtr proto, MP4InputStreamPtr inputStream )
{
MP4Err err;
u32 entries;
u8* p;
MP4PaddingBitsAtomPtr self = (MP4PaddingBitsAtomPtr) s;
err = MP4NoErr;
if ( self == NULL ) BAILWITHERROR( MP4BadParamErr )
err = self->super->createFromInputStream( s, proto, (char*) inputStream ); if ( err ) goto bail;
GET32( sampleCount );
self->pads = (u8 *) calloc( self->sampleCount + 1, sizeof(u8) );
TESTMALLOC( self->pads );
p = self->pads;
for ( entries = 0; entries < self->sampleCount; entries = entries + 2 )
{
u32 pad;
GET8_V_MSG( pad, NULL );
*p = pad & 7; p++; pad = pad >> 4;
*p = pad & 7; p++;
}
bail:
TEST_RETURN( err );
return err;
}
MP4Err MP4CreatePaddingBitsAtom( MP4PaddingBitsAtomPtr *outAtom )
{
MP4Err err;
MP4PaddingBitsAtomPtr self;
self = (MP4PaddingBitsAtomPtr) calloc( 1, sizeof(MP4PaddingBitsAtom) );
TESTMALLOC( self )
err = MP4CreateFullAtom( (MP4AtomPtr) self );
if ( err ) goto bail;
self->type = MP4PaddingBitsAtomType;
self->name = "padding bits";
self->createFromInputStream = (cisfunc) createFromInputStream;
self->destroy = destroy;
self->getSamplePad = getPaddingBits;
self->calculateSize = calculateSize;
self->serialize = serialize;
self->addSamplePads = addSamplePads;
*outAtom = self;
bail:
TEST_RETURN( err );
return err;
}
| 2.15625 | 2 |
2024-11-18T22:23:43.158126+00:00 | 2019-02-21T22:28:42 | 7747638af9a939799db269330ae803003bc0d0e9 | {
"blob_id": "7747638af9a939799db269330ae803003bc0d0e9",
"branch_name": "refs/heads/master",
"committer_date": "2019-02-21T22:28:42",
"content_id": "670c8866da1d6c55db3edb658c6d6229df3f4be1",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "dbe74fdf6bded2ceb98eec965fe05ddf7d6dd931",
"extension": "c",
"filename": "mavlink_mission_item_reached_msg.c",
"fork_events_count": 27,
"gha_created_at": "2013-08-13T14:59:47",
"gha_event_created_at": "2019-01-02T17:22:41",
"gha_language": "Java",
"gha_license_id": "BSD-3-Clause",
"github_id": 12084628,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1490,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/models/Flight/source/mavlink_mission_item_reached_msg.c",
"provenance": "stackv2-0115.json.gz:68867",
"repo_name": "smaccm/smaccm",
"revision_date": "2019-02-21T22:28:42",
"revision_id": "7393c423b5aca1a272a88cbb89b5dcfd08a5a47c",
"snapshot_id": "7f79bf5fe74bb1b856d69625fab4ffb1e138101e",
"src_encoding": "UTF-8",
"star_events_count": 27,
"url": "https://raw.githubusercontent.com/smaccm/smaccm/7393c423b5aca1a272a88cbb89b5dcfd08a5a47c/models/Flight/source/mavlink_mission_item_reached_msg.c",
"visit_date": "2021-01-23T15:51:42.639585"
} | stackv2 | /* This file has been autogenerated by Ivory
* Compiler version 0.1.0.0
*/
#include "mavlink_mission_item_reached_msg.h"
void mavlink_mission_item_reached_msg_send(const
struct mission_item_reached_msg* n_var0,
uint8_t* n_var1, uint8_t n_var2[80U])
{
uint8_t n_local0[2U] = {};
uint8_t* n_ref1 = n_local0;
uint16_t n_deref2 = n_var0->mission_item_reached_seq;
mavlink_pack_uint16_t((uint8_t*) n_ref1, 0U, n_deref2);
for (int32_t n_ix3 = 0; n_ix3 <= 1; n_ix3++) {
ASSERTS(n_ix3 > 0 && 2147483647 - n_ix3 >= 6 || n_ix3 <= 0);
if (n_ix3 + 6 >= 80) { } else {
uint8_t n_deref4 = n_ref1[n_ix3];
ASSERTS(n_ix3 > 0 && 2147483641 >= n_ix3 || n_ix3 <= 0);
ASSERTS(0 <= 6 + n_ix3 && 6 + n_ix3 < 80);
*&n_var2[(6 + n_ix3) % 80] = n_deref4;
}
}
mavlinkSendWithWriter(46U, 11U, 2U, n_var1, n_var2);
for (int32_t n_ix5 = 0; n_ix5 <= 69; n_ix5++) {
ASSERTS(n_ix5 > 0 && 2147483647 - n_ix5 >= 10 || n_ix5 <= 0);
ASSERTS(0 <= n_ix5 + 10 && n_ix5 + 10 < 80);
*&n_var2[(n_ix5 + 10) % 80] = 0U;
}
return;
}
void mavlink_mission_item_reached_unpack(struct mission_item_reached_msg* n_var0,
const uint8_t* n_var1)
{
uint16_t n_r0 = mavlink_unpack_uint16_t(n_var1, 0U);
*&n_var0->mission_item_reached_seq = n_r0;
} | 2.0625 | 2 |
2024-11-18T22:23:43.304763+00:00 | 2019-09-01T18:30:47 | bea96873c3a4460e48cc84b24a9af6812bcca03d | {
"blob_id": "bea96873c3a4460e48cc84b24a9af6812bcca03d",
"branch_name": "refs/heads/master",
"committer_date": "2019-09-01T18:30:47",
"content_id": "5e57fe27325e3073016d045ad6b088e220a43192",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "4ed14732392645dce4c2eceb4392e3b6dde6b861",
"extension": "c",
"filename": "mp.c",
"fork_events_count": 11,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 50973605,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2313,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/src/arch/ppc32/hal/cpu/mp.c",
"provenance": "stackv2-0115.json.gz:69124",
"repo_name": "zhengruohuang/toddler",
"revision_date": "2019-09-01T18:30:47",
"revision_id": "0d7bde9aaf1fab8fed5f37973eeda9eaa100bd7a",
"snapshot_id": "d1c5f06dc766f9a3e08805f558fa9091b8350cd8",
"src_encoding": "UTF-8",
"star_events_count": 86,
"url": "https://raw.githubusercontent.com/zhengruohuang/toddler/0d7bde9aaf1fab8fed5f37973eeda9eaa100bd7a/src/arch/ppc32/hal/cpu/mp.c",
"visit_date": "2021-01-16T23:49:46.483492"
} | stackv2 | #include "common/include/data.h"
#include "common/include/memory.h"
#include "common/include/memlayout.h"
#include "common/include/proc.h"
#include "hal/include/print.h"
#include "hal/include/string.h"
#include "hal/include/debug.h"
#include "hal/include/mem.h"
#include "hal/include/cpu.h"
static ulong per_cpu_area_start_paddr = 0;
static ulong per_cpu_area_start_vaddr = 0;
ulong tcb_padded_size = 0;
ulong tcb_area_start_vaddr = 0;
ulong tcb_area_size = 0;
/*
* Get my CPU id
*/
int get_cpu_id()
{
u32 cpu_num = 0;
return (int)cpu_num;
}
/*
* Per-CPU private data
*/
ulong get_per_cpu_area_start_paddr(int cpu_id)
{
assert(cpu_id < num_cpus);
return per_cpu_area_start_paddr + PER_CPU_AREA_SIZE * cpu_id;
}
ulong get_my_cpu_area_start_paddr()
{
return get_per_cpu_area_start_paddr(get_cpu_id());
}
ulong get_per_cpu_area_start_vaddr(int cpu_id)
{
assert(cpu_id < num_cpus);
return per_cpu_area_start_vaddr + PER_CPU_AREA_SIZE * cpu_id;
}
ulong get_my_cpu_area_start_vaddr()
{
return get_per_cpu_area_start_vaddr(get_cpu_id());
}
/*
* Init
*/
void init_mp()
{
int i;
kprintf("Initializing multiprocessor support\n");
// Reserve pages
ulong per_cpu_are_start_pfn = palloc(PER_CPU_AREA_PAGE_COUNT * num_cpus);
per_cpu_area_start_paddr = PFN_TO_ADDR(per_cpu_are_start_pfn);
per_cpu_area_start_vaddr = PER_CPU_AREA_BASE_VADDR;
// Map per CPU private area
ulong cur_area_pstart = PFN_TO_ADDR(per_cpu_are_start_pfn);
ulong cur_area_vstart = per_cpu_area_start_vaddr;
kprintf("\tPer-CPU area start phys @ %p, virt @ %p\n", (void *)cur_area_pstart, (void *)cur_area_vstart);
for (i = 0; i < num_cpus; i++) {
// Map the page to its new virt location
kernel_map_per_cpu_area(cur_area_vstart, cur_area_pstart, PER_CPU_AREA_SIZE);
fill_kernel_pht(cur_area_vstart, PER_CPU_AREA_SIZE, 0, KERNEL_PHT_PERSIST);
// Zero the area
memzero((void *)cur_area_vstart, PER_CPU_AREA_SIZE);
// Tell the user
kprintf("\tCPU #%d, per-CPU area: %p (%d Bytes)\n", i,
(void *)cur_area_vstart, PER_CPU_AREA_SIZE
);
cur_area_pstart += PER_CPU_AREA_SIZE;
cur_area_vstart += PER_CPU_AREA_SIZE;
}
}
| 2.578125 | 3 |
2024-11-18T22:23:43.651460+00:00 | 2018-06-10T15:06:15 | 9413c344ab0a3f0dd791408c755f9c804923181f | {
"blob_id": "9413c344ab0a3f0dd791408c755f9c804923181f",
"branch_name": "refs/heads/master",
"committer_date": "2018-06-10T15:06:15",
"content_id": "d7b9535fdb7017325df3969bce7e196ebe53a65b",
"detected_licenses": [
"MIT"
],
"directory_id": "6a594d1e484e8bbfaf0e6a89fdaf9047fe94e684",
"extension": "c",
"filename": "my_shell.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 136818215,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 803,
"license": "MIT",
"license_type": "permissive",
"path": "/minishell2/src/my_shell.c",
"provenance": "stackv2-0115.json.gz:69253",
"repo_name": "LouisGaspard/minishell2",
"revision_date": "2018-06-10T15:06:15",
"revision_id": "43ce64886dfe80c76ceba2f74107527d416eaedc",
"snapshot_id": "8457d71b9fdbefbe5c2cedafd9d2e19475dd55de",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/LouisGaspard/minishell2/43ce64886dfe80c76ceba2f74107527d416eaedc/minishell2/src/my_shell.c",
"visit_date": "2020-03-19T18:38:38.859419"
} | stackv2 | /*
** EPITECH PROJECT, 2018
** shell2
** File description:
** shell loop
*/
#include "minishell2.h"
#include "get_next_line.h"
#include "my.h"
void parse_pipe(t_shell *shell, char **tab)
{
(void)shell;
(void)tab;
}
void exec_cmd(t_shell *shell, char **tab)
{
if (check_if_builtins(shell, tab) == 1)
return;
}
void parse_tab(t_shell *shell, char **tab)
{
char **tab_pipe = NULL;
for (int a = 0; tab[a]; a++) {
tab_pipe = my_str_to_word_array(tab[a], '|');
if (count_tab_line(tab_pipe) > 1)
parse_pipe(shell, tab_pipe);
else
exec_cmd(shell, tab_pipe);
}
}
void my_shell(t_shell *shell)
{
char *str;
char **tab = NULL;
my_printf("$> ");
while ((str = get_next_line(0))) {
tab = my_str_to_word_array(str, ';');
parse_tab(shell, tab);
free(str);
my_printf("$> ");
}
}
| 2.75 | 3 |
2024-11-18T22:23:43.853672+00:00 | 2023-07-22T08:24:13 | 3c94e174276d730641bd3bbc4def3404838f0910 | {
"blob_id": "3c94e174276d730641bd3bbc4def3404838f0910",
"branch_name": "refs/heads/next",
"committer_date": "2023-07-22T08:24:13",
"content_id": "5d87c3daceede3191c863aaa01432c86f66f8b77",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "1ff4566b59f96f1c4d7cae41cecc31c53188a81c",
"extension": "c",
"filename": "fake_configure_notify.c",
"fork_events_count": 1238,
"gha_created_at": "2015-02-04T09:23:51",
"gha_event_created_at": "2023-09-13T06:42:54",
"gha_language": "C",
"gha_license_id": "BSD-3-Clause",
"github_id": 30291090,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1445,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/libi3/fake_configure_notify.c",
"provenance": "stackv2-0115.json.gz:69511",
"repo_name": "i3/i3",
"revision_date": "2023-07-22T08:24:13",
"revision_id": "d6e2a38b5cdf200c0fb82fc4cf7fff7dbcdeb605",
"snapshot_id": "e5bb9db3545b77307f39b603cd6420dd192abcc4",
"src_encoding": "UTF-8",
"star_events_count": 9823,
"url": "https://raw.githubusercontent.com/i3/i3/d6e2a38b5cdf200c0fb82fc4cf7fff7dbcdeb605/libi3/fake_configure_notify.c",
"visit_date": "2023-08-03T13:40:39.203230"
} | stackv2 | /*
* vim:ts=4:sw=4:expandtab
*
* i3 - an improved dynamic tiling window manager
* © 2009 Michael Stapelberg and contributors (see also: LICENSE)
*
*/
#include "libi3.h"
#include <stdlib.h>
#include <xcb/xcb.h>
#include <xcb/xproto.h>
/*
* Generates a configure_notify event and sends it to the given window
* Applications need this to think they’ve configured themselves correctly.
* The truth is, however, that we will manage them.
*
*/
void fake_configure_notify(xcb_connection_t *conn, xcb_rectangle_t r, xcb_window_t window, int border_width) {
/* Every X11 event is 32 bytes long. Therefore, XCB will copy 32 bytes.
* In order to properly initialize these bytes, we allocate 32 bytes even
* though we only need less for an xcb_configure_notify_event_t */
void *event = scalloc(32, 1);
xcb_configure_notify_event_t *generated_event = event;
generated_event->event = window;
generated_event->window = window;
generated_event->response_type = XCB_CONFIGURE_NOTIFY;
generated_event->x = r.x;
generated_event->y = r.y;
generated_event->width = r.width;
generated_event->height = r.height;
generated_event->border_width = border_width;
generated_event->above_sibling = XCB_NONE;
generated_event->override_redirect = false;
xcb_send_event(conn, false, window, XCB_EVENT_MASK_STRUCTURE_NOTIFY, (char *)generated_event);
xcb_flush(conn);
free(event);
}
| 2.25 | 2 |
2024-11-18T22:23:43.929669+00:00 | 2016-08-29T14:15:28 | b0fee6188feeeea58caf66e6387d2417373ff1c0 | {
"blob_id": "b0fee6188feeeea58caf66e6387d2417373ff1c0",
"branch_name": "refs/heads/master",
"committer_date": "2016-08-29T14:15:28",
"content_id": "b1aa0a7442590cc04bf479fa72613e80ea4f0d9f",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "2ebe64fe9432ba4a2c3fd280e7abf550826fce61",
"extension": "c",
"filename": "stream.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": 2711,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/src/luahs/stream.c",
"provenance": "stackv2-0115.json.gz:69642",
"repo_name": "AlexAUM/luahs",
"revision_date": "2016-08-29T14:15:28",
"revision_id": "34d0b701c5e3b0f21bb72d9391b832926177a1f3",
"snapshot_id": "76788a0d9be598d48da95c8961bb4b8f2b55b51e",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/AlexAUM/luahs/34d0b701c5e3b0f21bb72d9391b832926177a1f3/src/luahs/stream.c",
"visit_date": "2020-05-16T15:15:07.580407"
} | stackv2 | // luahs, Lua bindings to hyperscan
// Copyright (C) 2016 Boris Nagaev
// See the LICENSE file for terms of use.
#include "luahs.h"
static int luahs_freeStream(lua_State* L) {
luahs_Stream* self = luaL_checkudata(L, 1, LUAHS_STREAM_MT);
if (self->stream) {
hs_error_t err = hs_close_stream(self->stream, NULL, NULL, NULL);
if (err != HS_SUCCESS) {
return luaL_error(L, luahs_errorToString(err));
}
}
self->stream = NULL;
luaL_unref(L, LUA_REGISTRYINDEX, self->db_ref);
self->db_ref = LUA_NOREF;
return 0;
}
static int luahs_streamToString(lua_State* L) {
luahs_Stream* self = luaL_checkudata(L, 1, LUAHS_STREAM_MT);
lua_pushfstring(
L,
"Hyperscan stream (%p)",
self->stream
);
return 1;
}
static int luahs_cloneStream(lua_State* L) {
luahs_Stream* self = luaL_checkudata(L, 1, LUAHS_STREAM_MT);
luahs_Stream* copy = luahs_createStream(L);
hs_error_t err = hs_copy_stream(©->stream, self->stream);
if (err != HS_SUCCESS) {
return luaL_error(L, luahs_errorToString(err));
}
lua_rawgeti(L, LUA_REGISTRYINDEX, self->db_ref);
copy->db_ref = luaL_ref(L, LUA_REGISTRYINDEX);
return 1;
}
static int luahs_getDatabase(lua_State* L) {
luahs_Stream* self = luaL_checkudata(L, 1, LUAHS_STREAM_MT);
lua_rawgeti(L, LUA_REGISTRYINDEX, self->db_ref);
return 1;
}
static const luaL_Reg luahs_stream_mt_funcs[] = {
{"__gc", luahs_freeStream},
{"__tostring", luahs_streamToString},
{}
};
static const luaL_Reg luahs_stream_methods[] = {
{"scan", luahs_scanAgainstStream},
{"clone", luahs_cloneStream},
{"close", luahs_closeStream},
{"reset", luahs_resetStream},
{"assign", luahs_assignStream},
{"database", luahs_getDatabase},
{}
};
luahs_Stream* luahs_createStream(lua_State* L) {
luahs_Stream* self = lua_newuserdata(L, sizeof(luahs_Stream));
self->stream = NULL;
self->db_ref = LUA_NOREF;
if (luaL_newmetatable(L, LUAHS_STREAM_MT)) {
// prepare metatable
luahs_setfuncs(L, luahs_stream_mt_funcs);
lua_newtable(L);
luahs_setfuncs(L, luahs_stream_methods);
lua_setfield(L, -2, "__index");
}
lua_setmetatable(L, -2);
return self;
}
int luahs_makeStream(lua_State* L) {
luahs_Database* db = luaL_checkudata(L, 1, LUAHS_DATABASE_MT);
luahs_Stream* self = luahs_createStream(L);
int flags = 0;
hs_error_t err = hs_open_stream(db->db, flags, &self->stream);
if (err != HS_SUCCESS) {
return luaL_error(L, luahs_errorToString(err));
}
lua_pushvalue(L, 1);
self->db_ref = luaL_ref(L, LUA_REGISTRYINDEX);
return 1;
}
| 2.265625 | 2 |
2024-11-18T22:23:44.005407+00:00 | 2023-09-02T15:16:12 | ad92b889023c014fdd35514f5ac41fb822206429 | {
"blob_id": "ad92b889023c014fdd35514f5ac41fb822206429",
"branch_name": "refs/heads/master",
"committer_date": "2023-09-02T15:16:12",
"content_id": "47d4ec509fb69de2cd79fb9b759c09d95faa8f83",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "9ceacf33fd96913cac7ef15492c126d96cae6911",
"extension": "c",
"filename": "ex_display.c",
"fork_events_count": 1235,
"gha_created_at": "2016-08-30T18:18:25",
"gha_event_created_at": "2023-08-08T02:42:25",
"gha_language": "C",
"gha_license_id": null,
"github_id": 66966208,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2680,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/usr.bin/vi/ex/ex_display.c",
"provenance": "stackv2-0115.json.gz:69774",
"repo_name": "openbsd/src",
"revision_date": "2023-09-02T15:16:12",
"revision_id": "9e79f3a0ebd11a25b4bff61e900cb6de9e7795e9",
"snapshot_id": "ab97ef834fd2d5a7f6729814665e9782b586c130",
"src_encoding": "UTF-8",
"star_events_count": 3394,
"url": "https://raw.githubusercontent.com/openbsd/src/9e79f3a0ebd11a25b4bff61e900cb6de9e7795e9/usr.bin/vi/ex/ex_display.c",
"visit_date": "2023-09-02T18:54:56.624627"
} | stackv2 | /* $OpenBSD: ex_display.c,v 1.13 2016/05/27 09:18:12 martijn Exp $ */
/*-
* Copyright (c) 1992, 1993, 1994
* The Regents of the University of California. All rights reserved.
* Copyright (c) 1992, 1993, 1994, 1995, 1996
* Keith Bostic. All rights reserved.
*
* See the LICENSE file for redistribution information.
*/
#include "config.h"
#include <sys/types.h>
#include <sys/queue.h>
#include <bitstring.h>
#include <ctype.h>
#include <limits.h>
#include <stdio.h>
#include <string.h>
#include "../common/common.h"
#include "tag.h"
static int bdisplay(SCR *);
static void db(SCR *, CB *, CHAR_T *);
/*
* ex_display -- :display b[uffers] | s[creens] | t[ags]
*
* Display buffers, tags or screens.
*
* PUBLIC: int ex_display(SCR *, EXCMD *);
*/
int
ex_display(SCR *sp, EXCMD *cmdp)
{
switch (cmdp->argv[0]->bp[0]) {
case 'b':
#undef ARG
#define ARG "buffers"
if (cmdp->argv[0]->len >= sizeof(ARG) ||
memcmp(cmdp->argv[0]->bp, ARG, cmdp->argv[0]->len))
break;
return (bdisplay(sp));
case 's':
#undef ARG
#define ARG "screens"
if (cmdp->argv[0]->len >= sizeof(ARG) ||
memcmp(cmdp->argv[0]->bp, ARG, cmdp->argv[0]->len))
break;
return (ex_sdisplay(sp));
case 't':
#undef ARG
#define ARG "tags"
if (cmdp->argv[0]->len >= sizeof(ARG) ||
memcmp(cmdp->argv[0]->bp, ARG, cmdp->argv[0]->len))
break;
return (ex_tag_display(sp));
}
ex_emsg(sp, cmdp->cmd->usage, EXM_USAGE);
return (1);
}
/*
* bdisplay --
*
* Display buffers.
*/
static int
bdisplay(SCR *sp)
{
CB *cbp;
if (LIST_FIRST(&sp->gp->cutq) == NULL && sp->gp->dcbp == NULL) {
msgq(sp, M_INFO, "No cut buffers to display");
return (0);
}
/* Display regular cut buffers. */
LIST_FOREACH(cbp, &sp->gp->cutq, q) {
if (isdigit(cbp->name))
continue;
if (!TAILQ_EMPTY(&cbp->textq))
db(sp, cbp, NULL);
if (INTERRUPTED(sp))
return (0);
}
/* Display numbered buffers. */
LIST_FOREACH(cbp, &sp->gp->cutq, q) {
if (!isdigit(cbp->name))
continue;
if (!TAILQ_EMPTY(&cbp->textq))
db(sp, cbp, NULL);
if (INTERRUPTED(sp))
return (0);
}
/* Display default buffer. */
if ((cbp = sp->gp->dcbp) != NULL)
db(sp, cbp, "default buffer");
return (0);
}
/*
* db --
* Display a buffer.
*/
static void
db(SCR *sp, CB *cbp, CHAR_T *name)
{
CHAR_T *p;
TEXT *tp;
size_t len;
(void)ex_printf(sp, "********** %s%s\n",
name == NULL ? KEY_NAME(sp, cbp->name) : name,
F_ISSET(cbp, CB_LMODE) ? " (line mode)" : " (character mode)");
TAILQ_FOREACH(tp, &cbp->textq, q) {
for (len = tp->len, p = tp->lb; len--; ++p) {
(void)ex_puts(sp, KEY_NAME(sp, *p));
if (INTERRUPTED(sp))
return;
}
(void)ex_puts(sp, "\n");
}
}
| 2.515625 | 3 |
2024-11-18T22:23:44.109820+00:00 | 2017-10-20T12:45:50 | 058dd8967e2b8e28bf991109643fc27300dc7140 | {
"blob_id": "058dd8967e2b8e28bf991109643fc27300dc7140",
"branch_name": "refs/heads/master",
"committer_date": "2017-10-23T13:49:39",
"content_id": "a0a3e526c131314bd44c41dfe2521d4a1a87f972",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "2fd1f2a568ac21e636be169aa44fdf642b33bb17",
"extension": "c",
"filename": "ospTutorial.c",
"fork_events_count": 2,
"gha_created_at": "2015-11-06T10:15:04",
"gha_event_created_at": "2018-09-28T15:32:41",
"gha_language": "C++",
"gha_license_id": "Apache-2.0",
"github_id": 45674921,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5923,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/apps/ospTutorial.c",
"provenance": "stackv2-0115.json.gz:69902",
"repo_name": "BlueBrain/OSPRay",
"revision_date": "2017-10-20T12:45:50",
"revision_id": "561eadfe21334ef1d33161947ead416a09040266",
"snapshot_id": "c95720947135bf974252198e5f047f02cc07fc2d",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/BlueBrain/OSPRay/561eadfe21334ef1d33161947ead416a09040266/apps/ospTutorial.c",
"visit_date": "2023-06-25T08:57:45.906096"
} | stackv2 | // ======================================================================== //
// Copyright 2009-2017 Intel Corporation //
// //
// 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. //
// ======================================================================== //
/* This is a small example tutorial how to use OSPRay in an application.
*
* On Linux build it in the build_directory with
* gcc -std=c99 ../apps/ospTutorial.c -I ../ospray/include -I .. ./libospray.so -Wl,-rpath,. -o ospTutorialC
* On Windows build it in the build_directory\$Configuration with
* cl ..\..\apps\ospTutorial.c -I ..\..\ospray\include -I ..\.. ospray.lib
*/
#include <stdint.h>
#include <stdio.h>
#include <errno.h>
#ifdef _WIN32
# include <malloc.h>
#else
# include <alloca.h>
#endif
#include "ospray/ospray.h"
// helper function to write the rendered image as PPM file
void writePPM(const char *fileName,
const osp_vec2i *size,
const uint32_t *pixel)
{
FILE *file = fopen(fileName, "wb");
if (!file) {
fprintf(stderr, "fopen('%s', 'wb') failed: %d", fileName, errno);
return;
}
fprintf(file, "P6\n%i %i\n255\n", size->x, size->y);
unsigned char *out = (unsigned char *)alloca(3*size->x);
for (int y = 0; y < size->y; y++) {
const unsigned char *in = (const unsigned char *)&pixel[(size->y-1-y)*size->x];
for (int x = 0; x < size->x; x++) {
out[3*x + 0] = in[4*x + 0];
out[3*x + 1] = in[4*x + 1];
out[3*x + 2] = in[4*x + 2];
}
fwrite(out, 3*size->x, sizeof(char), file);
}
fprintf(file, "\n");
fclose(file);
}
int main(int argc, const char **argv) {
// image size
osp_vec2i imgSize;
imgSize.x = 1024; // width
imgSize.y = 768; // height
// camera
float cam_pos[] = {0.f, 0.f, 0.f};
float cam_up [] = {0.f, 1.f, 0.f};
float cam_view [] = {0.1f, 0.f, 1.f};
// triangle mesh data
float vertex[] = { -1.0f, -1.0f, 3.0f, 0.f,
-1.0f, 1.0f, 3.0f, 0.f,
1.0f, -1.0f, 3.0f, 0.f,
0.1f, 0.1f, 0.3f, 0.f };
float color[] = { 0.9f, 0.5f, 0.5f, 1.0f,
0.8f, 0.8f, 0.8f, 1.0f,
0.8f, 0.8f, 0.8f, 1.0f,
0.5f, 0.9f, 0.5f, 1.0f };
int32_t index[] = { 0, 1, 2,
1, 2, 3 };
// initialize OSPRay; OSPRay parses (and removes) its commandline parameters, e.g. "--osp:debug"
OSPError init_error = ospInit(&argc, argv);
if (init_error != OSP_NO_ERROR)
return init_error;
// create and setup camera
OSPCamera camera = ospNewCamera("perspective");
ospSetf(camera, "aspect", imgSize.x/(float)imgSize.y);
ospSet3fv(camera, "pos", cam_pos);
ospSet3fv(camera, "dir", cam_view);
ospSet3fv(camera, "up", cam_up);
ospCommit(camera); // commit each object to indicate modifications are done
// create and setup model and mesh
OSPGeometry mesh = ospNewGeometry("triangles");
OSPData data = ospNewData(4, OSP_FLOAT3A, vertex, 0); // OSP_FLOAT3 format is also supported for vertex positions
ospCommit(data);
ospSetData(mesh, "vertex", data);
data = ospNewData(4, OSP_FLOAT4, color, 0);
ospCommit(data);
ospSetData(mesh, "vertex.color", data);
data = ospNewData(2, OSP_INT3, index, 0); // OSP_INT4 format is also supported for triangle indices
ospCommit(data);
ospSetData(mesh, "index", data);
ospCommit(mesh);
OSPModel world = ospNewModel();
ospAddGeometry(world, mesh);
ospCommit(world);
// create renderer
OSPRenderer renderer = ospNewRenderer("scivis"); // choose Scientific Visualization renderer
// create and setup light for Ambient Occlusion
OSPLight light = ospNewLight(renderer, "ambient");
ospCommit(light);
OSPData lights = ospNewData(1, OSP_LIGHT, &light, 0);
ospCommit(lights);
// complete setup of renderer
ospSet1i(renderer, "aoSamples", 1);
ospSet1f(renderer, "bgColor", 1.0f); // white, transparent
ospSetObject(renderer, "model", world);
ospSetObject(renderer, "camera", camera);
ospSetObject(renderer, "lights", lights);
ospCommit(renderer);
// create and setup framebuffer
OSPFrameBuffer framebuffer = ospNewFrameBuffer(&imgSize, OSP_FB_SRGBA, OSP_FB_COLOR | /*OSP_FB_DEPTH |*/ OSP_FB_ACCUM);
ospFrameBufferClear(framebuffer, OSP_FB_COLOR | OSP_FB_ACCUM);
// render one frame
ospRenderFrame(framebuffer, renderer, OSP_FB_COLOR | OSP_FB_ACCUM);
// access framebuffer and write its content as PPM file
const uint32_t * fb = (uint32_t*)ospMapFrameBuffer(framebuffer, OSP_FB_COLOR);
writePPM("firstFrameC.ppm", &imgSize, fb);
ospUnmapFrameBuffer(fb, framebuffer);
// render 10 more frames, which are accumulated to result in a better converged image
for (int frames = 0; frames < 10; frames++)
ospRenderFrame(framebuffer, renderer, OSP_FB_COLOR | OSP_FB_ACCUM);
fb = (uint32_t*)ospMapFrameBuffer(framebuffer, OSP_FB_COLOR);
writePPM("accumulatedFrameC.ppm", &imgSize, fb);
ospUnmapFrameBuffer(fb, framebuffer);
return 0;
}
| 2.140625 | 2 |
2024-11-18T22:23:44.539360+00:00 | 2015-05-01T06:23:28 | f43872ae29dc7f36c115309df735a19b469719dd | {
"blob_id": "f43872ae29dc7f36c115309df735a19b469719dd",
"branch_name": "refs/heads/master",
"committer_date": "2015-05-01T06:23:28",
"content_id": "0c661e5545751f9c64998afeae2936732197f0b4",
"detected_licenses": [
"MIT"
],
"directory_id": "9151833f76c1ce72df19f176b313cfc8f75c7182",
"extension": "h",
"filename": "FluidStuff.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": 1502,
"license": "MIT",
"license_type": "permissive",
"path": "/src/FluidStuff.h",
"provenance": "stackv2-0115.json.gz:70158",
"repo_name": "foxbat07/EGB",
"revision_date": "2015-05-01T06:23:28",
"revision_id": "90c266996ff5c42d35316d4622b74013ea76e962",
"snapshot_id": "3af221fe28aacf1ecc3534a800c2691a38f13de5",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/foxbat07/EGB/90c266996ff5c42d35316d4622b74013ea76e962/src/FluidStuff.h",
"visit_date": "2022-05-30T05:53:57.838659"
} | stackv2 | //
// FluidStuff.h
// EGBvisuals
//
// Created by Tim Wood on 3/10/15.
//
//
#ifndef EGBvisuals_FluidStuff_h
#define EGBvisuals_FluidStuff_h
#include "ofxFluid.h"
#include "ofxFlowTools.h"
#include "ofxUI.h"
struct FluidStuff {
ofxFluid fluid;
flowTools::ftFluidSimulation ftFluid;
ofVec2f gravity;
float mouseSensitivity =10;
float mouseRadius = 3;
ofxUICanvas *gui2;
void setup(int w, int h){
fluid.allocate(w, h, 0.30);
fluid.dissipation = 0.99;
fluid.velocityDissipation = 0.99;
gui2 = new ofxUISuperCanvas("PANEL 2: Fluid");
gui2->setPosition(200, 0);
gui2->setHeight(600);
gui2->setName("Fluid");
gui2->addLabel("Permanent Forces");
gui2->addSpacer();
gui2->addSlider("fluid.dissipation", 0.0f, 1.0f, &fluid.dissipation);
gui2->addSlider("fluid.velocityDissipation", 0.0f, 1.0f, &fluid.velocityDissipation);
gui2->addSlider("gravity X", -2, 2, &gravity.x);
gui2->addSlider("gravity Y", -2, 2, &gravity.y);
gui2->addLabel("Temporal Forces");
gui2->addSpacer();
gui2->addSlider("mouseSensitivity", 0, 100, &mouseSensitivity);
gui2->addSlider("mouseRadius", 0, 10, &mouseRadius);
gui2->setWidgetColor(OFX_UI_WIDGET_COLOR_FILL, ofColor(64,128,192,200));
gui2->setWidgetColor(OFX_UI_WIDGET_COLOR_FILL_HIGHLIGHT, ofColor(0,128,128, 200));
}
};
#endif
| 2.1875 | 2 |
2024-11-18T22:23:44.753721+00:00 | 2020-02-15T11:06:42 | d7dafbbbced5ea9bc1bad1996e1b8b63c01a6e8d | {
"blob_id": "d7dafbbbced5ea9bc1bad1996e1b8b63c01a6e8d",
"branch_name": "refs/heads/master",
"committer_date": "2020-02-15T11:06:42",
"content_id": "cd87f66fee74820a71245c483ff6305240fffc73",
"detected_licenses": [
"MIT"
],
"directory_id": "7fa63710a22415335fb6f4cf5f7e2005273b79b8",
"extension": "h",
"filename": "opengl.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 234941773,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1816,
"license": "MIT",
"license_type": "permissive",
"path": "/src/graphics/opengl.h",
"provenance": "stackv2-0115.json.gz:70415",
"repo_name": "davidgm94/TripleR",
"revision_date": "2020-02-15T11:06:42",
"revision_id": "7997b9e169d6dee0c5fd601aec65393343b185a9",
"snapshot_id": "dea8bc5cf27857ab07b669ea807d23e952aca07d",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/davidgm94/TripleR/7997b9e169d6dee0c5fd601aec65393343b185a9/src/graphics/opengl.h",
"visit_date": "2020-12-15T01:14:06.976043"
} | stackv2 | #pragma once
//void win32_initOpenGL(HWND window)
//{
// HDC DC = GetWindowDC(window);
// TODO: fill in the future with better accuracy with what we want
// PIXELFORMATDESCRIPTOR desiredPixelFormat = {0};
// desiredPixelFormat.nSize = sizeof(desiredPixelFormat);
// desiredPixelFormat.nVersion = 1;
// desiredPixelFormat.dwFlags = PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW | PFD_DOUBLEBUFFER;
// desiredPixelFormat.iPixelType;
// desiredPixelFormat.cColorBits = 32;
// desiredPixelFormat.cRedBits;
// desiredPixelFormat.cRedShift;
// desiredPixelFormat.cGreenBits;
// desiredPixelFormat.cGreenShift;
// desiredPixelFormat.cBlueBits;
// desiredPixelFormat.cBlueShift;
// desiredPixelFormat.cAlphaBits = 8;
// desiredPixelFormat.cAlphaShift;
// desiredPixelFormat.cAccumBits;
// desiredPixelFormat.cAccumRedBits;
// desiredPixelFormat.cAccumGreenBits;
// desiredPixelFormat.cAccumBlueBits;
// desiredPixelFormat.cAccumAlphaBits;
// desiredPixelFormat.cDepthBits;
// desiredPixelFormat.cStencilBits;
// desiredPixelFormat.cAuxBuffers;
// desiredPixelFormat.iLayerType = PFD_MAIN_PLANE;
// desiredPixelFormat.bReserved;
// desiredPixelFormat.dwLayerMask;
// desiredPixelFormat.dwVisibleMask;
// desiredPixelFormat.dwDamageMask;
//
// int suggestedPixelFormatIndex = ChoosePixelFormat(DC, &desiredPixelFormat);
// PIXELFORMATDESCRIPTOR suggestedPixelFormatDescriptor;
// (void)DescribePixelFormat(DC, suggestedPixelFormatIndex, sizeof(suggestedPixelFormatDescriptor), &suggestedPixelFormatDescriptor);
// (void)SetPixelFormat(DC, suggestedPixelFormatIndex, &suggestedPixelFormatDescriptor);
//
// HGLRC openGlRenderingContext = wglCreateContext(DC);
// if (wglMakeCurrent(DC, openGlRenderingContext))
// {
// os_printf("OpenGL initialized\n");
// }
// else
// {
// os_printf("OpenGL failed to initialize\n");
// }
//} | 2.015625 | 2 |
2024-11-18T22:23:45.330706+00:00 | 2023-01-22T01:09:08 | 445b403f76c8fe9784fc83ca485ba5d3c3779b4c | {
"blob_id": "445b403f76c8fe9784fc83ca485ba5d3c3779b4c",
"branch_name": "refs/heads/main",
"committer_date": "2023-01-22T01:09:08",
"content_id": "97daf28404a2177abc6265fd16ab8ad5cd1c4955",
"detected_licenses": [
"MIT"
],
"directory_id": "d3116273289932d3f0b8e3b3015517e56c489423",
"extension": "c",
"filename": "test.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 238299741,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 52819,
"license": "MIT",
"license_type": "permissive",
"path": "/test/test.c",
"provenance": "stackv2-0115.json.gz:70673",
"repo_name": "WKHAllen/cdtp",
"revision_date": "2023-01-22T01:09:08",
"revision_id": "e0e21136b3b7172e89a4216a7e3948d4a033d33f",
"snapshot_id": "63a313d14664814b06e3ccbd9371ddd185e16d2a",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/WKHAllen/cdtp/e0e21136b3b7172e89a4216a7e3948d4a033d33f/test/test.c",
"visit_date": "2023-01-23T21:03:35.687001"
} | stackv2 | /**
* CDTP tests.
*/
#include "../src/cdtp.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <inttypes.h>
#include <stdbool.h>
#ifdef _WIN32
# ifdef _WIN64
# define PRI_SIZE_T PRIu64
# else
# define PRI_SIZE_T PRIu32
# endif
#else
# define PRI_SIZE_T "zu"
#endif
#ifdef _WIN32
# define strdup _strdup
#endif
#define STR_SIZE(s) ((strlen(s) + 1) * sizeof(char))
#define MIN(a, b) (((a) < (b)) ? (a) : (b))
#define MAX(a, b) (((a) > (b)) ? (a) : (b))
#define TEST_ASSERT(condition) { \
if (!(condition)) { \
fprintf( \
stderr, \
"test assertion failed (%s:%d): %s\n", \
__FILE__, __LINE__, #condition); \
exit(1); \
} \
}
#define TEST_ASSERT_EQ(a, b) { \
if (a != b) { \
fprintf( \
stderr, \
"test equality assertion failed (%s:%d): %s != %s, %" PRI_SIZE_T " != %" PRI_SIZE_T "\n", \
__FILE__, __LINE__, #a, #b, a, b); \
exit(1); \
} \
}
#define TEST_ASSERT_NE(a, b) { \
if (a == b) { \
fprintf( \
stderr, \
"test inequality assertion failed (%s:%d): %s == %s, %" PRI_SIZE_T " == %" PRI_SIZE_T "\n", \
__FILE__, __LINE__, #a, #b, a, b); \
exit(1); \
} \
}
#define TEST_ASSERT_INT_EQ(a, b) { \
if (a != b) { \
fprintf( \
stderr, \
"test equality assertion failed (%s:%d): %s != %s, %d != %d\n", \
__FILE__, __LINE__, #a, #b, a, b); \
exit(1); \
} \
}
#define TEST_ASSERT_INT_NE(a, b) { \
if (a == b) { \
fprintf( \
stderr, \
"test inequality assertion failed (%s:%d): %s == %s, %d == %d\n", \
__FILE__, __LINE__, #a, #b, a, b); \
exit(1); \
} \
}
#define TEST_ASSERT_STR_EQ(a, b) { \
if (strcmp(a, b) != 0) { \
fprintf( \
stderr, \
"test string equality assertion failed (%s:%d): %s != %s, %s != %s\n", \
__FILE__, __LINE__, #a, #b, a, b); \
exit(1); \
} \
}
#define TEST_ASSERT_STR_NE(a, b) { \
if (strcmp(a, b) == 0) { \
fprintf( \
stderr, \
"test string inequality assertion failed (%s:%d): %s == %s, %s == %s\n", \
__FILE__, __LINE__, #a, #b, a, b); \
exit(1); \
} \
}
#define TEST_ASSERT_ARRAY_EQ(a, b, size) { \
for (size_t i = 0; i < size; i++) { \
if (a[i] != b[i]) { \
fprintf( \
stderr, \
"test array equality assertion failed (%s:%d): %s != %s at index %" PRI_SIZE_T ", with size = %" PRI_SIZE_T "\n", \
__FILE__, __LINE__, #a, #b, i, size); \
exit(1); \
} \
} \
}
#define TEST_ASSERT_MEM_EQ(a, b, size) { \
if (memcmp(a, b, size) != 0) { \
fprintf( \
stderr, \
"test memory equality assertion failed (%s:%d): %s != %s, with size = %" PRI_SIZE_T "\n", \
__FILE__, __LINE__, #a, #b, size); \
exit(1); \
} \
}
#define TEST_ASSERT_MEM_NE(a, b, size) { \
if (memcmp(a, b, size) == 0) { \
fprintf( \
stderr, \
"test memory inequality assertion failed (%s:%d): %s == %s, with size = %" PRI_SIZE_T "\n", \
__FILE__, __LINE__, #a, #b, size); \
exit(1); \
} \
}
#define TEST_ASSERT_ARRAY_MEM_EQ(a, b, size, item_size) { \
for (size_t i = 0; i < size; i++) { \
if (memcmp((void *) (a[i]), (void *) (b[i]), item_size) != 0) { \
fprintf( \
stderr, \
"test array memory equality assertion failed (%s:%d): %s != %s at index %" PRI_SIZE_T ", with size = %" PRI_SIZE_T " and item size = %" PRI_SIZE_T "\n", \
__FILE__, __LINE__, #a, #b, i, size, item_size); \
exit(1); \
} \
} \
}
#define TEST_ASSERT_MESSAGES_EQ(a, b, size) { \
for (size_t i = 0; i < size; i++) { \
if (a[i]->data_size != b[i]->data_size) { \
fprintf( \
stderr, \
"test message size equality assertion failed (%s:%d): %" PRI_SIZE_T " != %" PRI_SIZE_T " (%s != %s) at index %" PRI_SIZE_T ", with size = %" PRI_SIZE_T "\n", \
__FILE__, __LINE__, a[i]->data_size, b[i]->data_size, #a, #b, i, size); \
exit(1); \
} \
if (memcmp((void *) (a[i]->data), (void *) (b[i]->data), a[i]->data_size) != 0) { \
fprintf( \
stderr, \
"test array memory equality assertion failed (%s:%d): %s != %s at index %" PRI_SIZE_T ", with size = %" PRI_SIZE_T "\n", \
__FILE__, __LINE__, #a, #b, i, size); \
exit(1); \
} \
} \
}
typedef struct _TestReceivedMessage {
void *data;
size_t data_size;
} TestReceivedMessage;
TestReceivedMessage *test_received_message(void *data, size_t data_size)
{
TestReceivedMessage *message = (TestReceivedMessage *) malloc(sizeof(TestReceivedMessage));
message->data = data;
message->data_size = data_size;
return message;
}
TestReceivedMessage *int_message(int data)
{
int *data_ptr = (int *) malloc(sizeof(int));
*data_ptr = data;
return test_received_message(data_ptr, sizeof(int));
}
TestReceivedMessage *size_t_message(size_t data)
{
size_t *data_ptr = (size_t *) malloc(sizeof(size_t));
*data_ptr = data;
return test_received_message(data_ptr, sizeof(size_t));
}
TestReceivedMessage *str_message(char *data)
{
char *data_ptr = strdup(data);
return test_received_message(data_ptr, STR_SIZE(data_ptr));
}
typedef struct _TestState {
size_t server_receive_count_expected;
size_t server_connect_count_expected;
size_t server_disconnect_count_expected;
size_t server_receive_count;
size_t server_connect_count;
size_t server_disconnect_count;
TestReceivedMessage **server_received_expected;
size_t *server_receive_client_ids_expected;
size_t *server_connect_client_ids_expected;
size_t *server_disconnect_client_ids_expected;
TestReceivedMessage **server_received;
size_t *server_receive_client_ids;
size_t *server_connect_client_ids;
size_t *server_disconnect_client_ids;
size_t client_receive_count_expected;
size_t client_disconnected_count_expected;
size_t client_receive_count;
size_t client_disconnected_count;
TestReceivedMessage **client_received_expected;
TestReceivedMessage **client_received;
bool reply_with_string_length;
} TestState;
TestState *test_state(
size_t server_receive_count,
size_t server_connect_count,
size_t server_disconnect_count,
TestReceivedMessage **server_received,
size_t *server_receive_client_ids,
size_t *server_connect_client_ids,
size_t *server_disconnect_client_ids,
size_t client_receive_count,
size_t client_disconnected_count,
TestReceivedMessage **client_received
)
{
TestState *state = (TestState *) malloc(sizeof(TestState));
state->server_receive_count_expected = server_receive_count;
state->server_connect_count_expected = server_connect_count;
state->server_disconnect_count_expected = server_disconnect_count;
state->server_receive_count = 0;
state->server_connect_count = 0;
state->server_disconnect_count = 0;
state->server_received_expected = server_received;
state->server_receive_client_ids_expected = server_receive_client_ids;
state->server_connect_client_ids_expected = server_connect_client_ids;
state->server_disconnect_client_ids_expected = server_disconnect_client_ids;
state->server_received = (TestReceivedMessage **) malloc(server_receive_count * sizeof(TestReceivedMessage *));
state->server_receive_client_ids = (size_t *) malloc(server_receive_count * sizeof(size_t));
state->server_connect_client_ids = (size_t *) malloc(server_connect_count * sizeof(size_t));
state->server_disconnect_client_ids = (size_t *) malloc(server_disconnect_count * sizeof(size_t));
state->client_receive_count_expected = client_receive_count;
state->client_disconnected_count_expected = client_disconnected_count;
state->client_receive_count = 0;
state->client_disconnected_count = 0;
state->client_received_expected = client_received;
state->client_received = (TestReceivedMessage **) malloc(client_receive_count * sizeof(TestReceivedMessage *));
state->reply_with_string_length = false;
return state;
}
void test_state_finish(TestState *state)
{
TEST_ASSERT_EQ(state->server_receive_count, state->server_receive_count_expected)
TEST_ASSERT_EQ(state->server_connect_count, state->server_connect_count_expected)
TEST_ASSERT_EQ(state->server_disconnect_count, state->server_disconnect_count_expected)
TEST_ASSERT_MESSAGES_EQ(state->server_received,
state->server_received_expected,
state->server_receive_count)
TEST_ASSERT_ARRAY_EQ(state->server_receive_client_ids,
state->server_receive_client_ids_expected,
state->server_receive_count)
TEST_ASSERT_ARRAY_EQ(state->server_connect_client_ids,
state->server_connect_client_ids_expected,
state->server_connect_count)
TEST_ASSERT_ARRAY_EQ(state->server_disconnect_client_ids,
state->server_disconnect_client_ids_expected,
state->server_disconnect_count)
TEST_ASSERT_EQ(state->client_receive_count, state->client_receive_count_expected)
TEST_ASSERT_EQ(state->client_disconnected_count, state->client_disconnected_count_expected)
TEST_ASSERT_MESSAGES_EQ(state->client_received,
state->client_received_expected,
state->client_receive_count)
for (size_t i = 0; i < state->server_receive_count; i++) {
free(state->server_received_expected[i]->data);
free(state->server_received_expected[i]);
free(state->server_received[i]->data);
free(state->server_received[i]);
}
free(state->server_received);
free(state->server_receive_client_ids);
free(state->server_connect_client_ids);
free(state->server_disconnect_client_ids);
for (size_t i = 0; i < state->client_receive_count; i++) {
free(state->client_received_expected[i]->data);
free(state->client_received_expected[i]);
free(state->client_received[i]->data);
free(state->client_received[i]);
}
free(state->client_received);
free(state);
}
void test_state_server_received(TestState *state, CDTPServer *server, size_t client_id, void *data, size_t data_size)
{
TEST_ASSERT(state->server_receive_count < state->server_receive_count_expected)
state->server_received[state->server_receive_count] = (TestReceivedMessage *) malloc(sizeof(TestReceivedMessage));
state->server_received[state->server_receive_count]->data = data;
state->server_received[state->server_receive_count]->data_size = data_size;
state->server_receive_client_ids[state->server_receive_count++] = client_id;
if (state->reply_with_string_length) {
char *str_data = (char *) data;
TEST_ASSERT_EQ(STR_SIZE(str_data), data_size)
size_t str_len = strlen(str_data) + 1;
cdtp_server_send(server, client_id, &str_len, sizeof(size_t));
}
}
void test_state_server_connect(TestState *state, CDTPServer *server, size_t client_id)
{
(void) server;
TEST_ASSERT(state->server_connect_count < state->server_connect_count_expected)
state->server_connect_client_ids[state->server_connect_count++] = client_id;
}
void test_state_server_disconnect(TestState *state, CDTPServer *server, size_t client_id)
{
(void) server;
TEST_ASSERT(state->server_disconnect_count < state->server_disconnect_count_expected)
state->server_disconnect_client_ids[state->server_disconnect_count++] = client_id;
}
void test_state_client_received(TestState *state, CDTPClient *client, void *data, size_t data_size)
{
(void) client;
TEST_ASSERT(state->client_receive_count < state->client_receive_count_expected)
state->client_received[state->client_receive_count] = (TestReceivedMessage *) malloc(sizeof(TestReceivedMessage));
state->client_received[state->client_receive_count]->data = data;
state->client_received[state->client_receive_count]->data_size = data_size;
state->client_receive_count++;
}
void test_state_client_disconnected(TestState *state, CDTPClient *client)
{
(void) client;
TEST_ASSERT(state->client_disconnected_count < state->client_disconnected_count_expected)
state->client_disconnected_count++;
}
int rand_int(int min, int max)
{
return min + (rand() % (max - min));
}
char *rand_bytes(size_t size)
{
char *bytes = (char *) malloc(size * sizeof(char));
for (size_t i = 0; i < size; i++) {
bytes[i] = (char) rand_int(0, 256);
}
return bytes;
}
char *voidp_to_str(void *data, size_t data_size)
{
char *message = (char *) malloc((data_size + 1) * sizeof(char));
memcpy(message, data, data_size);
message[data_size] = '\0';
return message;
}
void server_on_recv(CDTPServer *server, size_t client_id, void *data, size_t data_size, void *arg)
{
TEST_ASSERT(cdtp_server_is_serving(server))
TestState *state = (TestState *) arg;
test_state_server_received(state, server, client_id, data, data_size);
}
void server_on_connect(CDTPServer *server, size_t client_id, void *arg)
{
TEST_ASSERT(cdtp_server_is_serving(server))
TestState *state = (TestState *) arg;
test_state_server_connect(state, server, client_id);
}
void server_on_disconnect(CDTPServer *server, size_t client_id, void *arg)
{
TEST_ASSERT(cdtp_server_is_serving(server))
TestState *state = (TestState *) arg;
test_state_server_disconnect(state, server, client_id);
}
void client_on_recv(CDTPClient *client, void *data, size_t data_size, void *arg)
{
TEST_ASSERT(cdtp_client_is_connected(client))
TestState *state = (TestState *) arg;
test_state_client_received(state, client, data, data_size);
}
void client_on_disconnected(CDTPClient *client, void *arg)
{
TEST_ASSERT(!cdtp_client_is_connected(client))
TestState *state = (TestState *) arg;
test_state_client_disconnected(state, client);
}
void on_err(int cdtp_err, int underlying_err, void *arg)
{
printf("CDTP error: %d\n", cdtp_err);
printf("Underlying error: %d\n", underlying_err);
perror("Underlying error message");
printf("Arg: %s\n", (char *) arg);
exit(EXIT_FAILURE);
}
void check_err(void)
{
if (cdtp_error()) {
on_err(cdtp_get_error(), cdtp_get_underlying_error(), NULL);
}
}
typedef struct _Custom {
int a;
size_t b;
} Custom;
#define WAIT_TIME 0.1
#define SERVER_HOST "0.0.0.0"
#define SERVER_PORT 29275
#define CLIENT_HOST "127.0.0.1"
#define CLIENT_PORT 29275
#define EMPTY {0}
/**
* Test utility functions.
*/
void test_util(void)
{
// Test message size encoding
unsigned char expected_msg_size1[] = {0, 0, 0, 0, 0};
unsigned char expected_msg_size2[] = {0, 0, 0, 0, 1};
unsigned char expected_msg_size3[] = {0, 0, 0, 0, 255};
unsigned char expected_msg_size4[] = {0, 0, 0, 1, 0};
unsigned char expected_msg_size5[] = {0, 0, 0, 1, 1};
unsigned char expected_msg_size6[] = {1, 1, 1, 1, 1};
unsigned char expected_msg_size7[] = {1, 2, 3, 4, 5};
unsigned char expected_msg_size8[] = {11, 7, 5, 3, 2};
unsigned char expected_msg_size9[] = {255, 255, 255, 255, 255};
unsigned char *msg_size1 = _cdtp_encode_message_size(0);
unsigned char *msg_size2 = _cdtp_encode_message_size(1);
unsigned char *msg_size3 = _cdtp_encode_message_size(255);
unsigned char *msg_size4 = _cdtp_encode_message_size(256);
unsigned char *msg_size5 = _cdtp_encode_message_size(257);
unsigned char *msg_size6 = _cdtp_encode_message_size(4311810305);
unsigned char *msg_size7 = _cdtp_encode_message_size(4328719365);
unsigned char *msg_size8 = _cdtp_encode_message_size(47362409218);
unsigned char *msg_size9 = _cdtp_encode_message_size(1099511627775);
TEST_ASSERT_ARRAY_EQ(msg_size1, expected_msg_size1, (size_t) CDTP_LENSIZE)
TEST_ASSERT_ARRAY_EQ(msg_size2, expected_msg_size2, (size_t) CDTP_LENSIZE)
TEST_ASSERT_ARRAY_EQ(msg_size3, expected_msg_size3, (size_t) CDTP_LENSIZE)
TEST_ASSERT_ARRAY_EQ(msg_size4, expected_msg_size4, (size_t) CDTP_LENSIZE)
TEST_ASSERT_ARRAY_EQ(msg_size5, expected_msg_size5, (size_t) CDTP_LENSIZE)
TEST_ASSERT_ARRAY_EQ(msg_size6, expected_msg_size6, (size_t) CDTP_LENSIZE)
TEST_ASSERT_ARRAY_EQ(msg_size7, expected_msg_size7, (size_t) CDTP_LENSIZE)
TEST_ASSERT_ARRAY_EQ(msg_size8, expected_msg_size8, (size_t) CDTP_LENSIZE)
TEST_ASSERT_ARRAY_EQ(msg_size9, expected_msg_size9, (size_t) CDTP_LENSIZE)
// Test message size decoding
TEST_ASSERT_EQ(_cdtp_decode_message_size(expected_msg_size1), (size_t) 0)
TEST_ASSERT_EQ(_cdtp_decode_message_size(expected_msg_size2), (size_t) 1)
TEST_ASSERT_EQ(_cdtp_decode_message_size(expected_msg_size3), (size_t) 255)
TEST_ASSERT_EQ(_cdtp_decode_message_size(expected_msg_size4), (size_t) 256)
TEST_ASSERT_EQ(_cdtp_decode_message_size(expected_msg_size5), (size_t) 257)
TEST_ASSERT_EQ(_cdtp_decode_message_size(expected_msg_size6), (size_t) 4311810305)
TEST_ASSERT_EQ(_cdtp_decode_message_size(expected_msg_size7), (size_t) 4328719365)
TEST_ASSERT_EQ(_cdtp_decode_message_size(expected_msg_size8), (size_t) 47362409218)
TEST_ASSERT_EQ(_cdtp_decode_message_size(expected_msg_size9), (size_t) 1099511627775)
// Clean up
free(msg_size1);
free(msg_size2);
free(msg_size3);
free(msg_size4);
free(msg_size5);
free(msg_size6);
free(msg_size7);
free(msg_size8);
free(msg_size9);
}
/**
* Test client map functions.
*/
void test_client_map(void)
{
// Create map
CDTPClientMap *map = _cdtp_client_map();
TEST_ASSERT_EQ(map->size, (size_t) 0)
TEST_ASSERT_EQ(map->capacity, (size_t) 16)
// Create test sockets
CDTPSocket *sock1 = (CDTPSocket *) malloc(sizeof(CDTPSocket));
sock1->sock = 123;
CDTPSocket *sock2 = (CDTPSocket *) malloc(sizeof(CDTPSocket));
sock2->sock = 345;
// Test false contains
bool false_contains = _cdtp_client_map_contains(map, 234);
TEST_ASSERT(!false_contains)
TEST_ASSERT_EQ(map->size, (size_t) 0)
TEST_ASSERT_EQ(map->capacity, (size_t) 16)
// Test null get
CDTPSocket *null_get = _cdtp_client_map_get(map, 234);
TEST_ASSERT(null_get == NULL)
TEST_ASSERT_EQ(map->size, (size_t) 0)
TEST_ASSERT_EQ(map->capacity, (size_t) 16)
// Test null pop
CDTPSocket *null_pop = _cdtp_client_map_pop(map, 234);
TEST_ASSERT(null_pop == NULL)
TEST_ASSERT_EQ(map->size, (size_t) 0)
TEST_ASSERT_EQ(map->capacity, (size_t) 16)
// Test zero-size iterator
CDTPClientMapIter *zero_size_iter = _cdtp_client_map_iter(map);
TEST_ASSERT_EQ(zero_size_iter->size, (size_t) 0)
_cdtp_client_map_iter_free(zero_size_iter);
// Test set
bool set1 = _cdtp_client_map_set(map, 234, sock1);
TEST_ASSERT(set1)
TEST_ASSERT_EQ(map->size, (size_t) 1)
TEST_ASSERT_EQ(map->capacity, (size_t) 16)
// Test double set
bool double_set = _cdtp_client_map_set(map, 234, sock2);
TEST_ASSERT(!double_set)
TEST_ASSERT_EQ(map->size, (size_t) 1)
TEST_ASSERT_EQ(map->capacity, (size_t) 16)
// Test true contains
bool contains1 = _cdtp_client_map_contains(map, 234);
TEST_ASSERT(contains1)
TEST_ASSERT_EQ(map->size, (size_t) 1)
TEST_ASSERT_EQ(map->capacity, (size_t) 16)
// Test get
CDTPSocket *get1 = _cdtp_client_map_get(map, 234);
TEST_ASSERT_EQ((size_t) (get1->sock), (size_t) 123)
TEST_ASSERT_EQ(map->size, (size_t) 1)
TEST_ASSERT_EQ(map->capacity, (size_t) 16)
// Test one-size iterator
CDTPClientMapIter *one_size_iter = _cdtp_client_map_iter(map);
TEST_ASSERT_EQ(one_size_iter->size, (size_t) 1)
TEST_ASSERT_EQ(one_size_iter->clients[0]->client_id, (size_t) 234)
TEST_ASSERT_EQ((size_t) (one_size_iter->clients[0]->sock->sock), (size_t) 123)
_cdtp_client_map_iter_free(one_size_iter);
// Test second set, contains, get
bool contains2 = _cdtp_client_map_contains(map, 456);
TEST_ASSERT(!contains2)
CDTPSocket *get2 = _cdtp_client_map_get(map, 456);
TEST_ASSERT(get2 == NULL)
bool set2 = _cdtp_client_map_set(map, 456, sock2);
TEST_ASSERT(set2)
TEST_ASSERT_EQ(map->size, (size_t) 2)
TEST_ASSERT_EQ(map->capacity, (size_t) 16)
bool contains3 = _cdtp_client_map_contains(map, 456);
TEST_ASSERT(contains3)
CDTPSocket *get3 = _cdtp_client_map_get(map, 456);
TEST_ASSERT_EQ((size_t) (get3->sock), (size_t) 345)
// Test two-size iterator
CDTPClientMapIter *two_size_iter = _cdtp_client_map_iter(map);
TEST_ASSERT_EQ(two_size_iter->size, (size_t) 2)
TEST_ASSERT_EQ(two_size_iter->clients[0]->client_id, (size_t) 456)
TEST_ASSERT_EQ((size_t) (two_size_iter->clients[0]->sock->sock), (size_t) 345)
TEST_ASSERT_EQ(two_size_iter->clients[1]->client_id, (size_t) 234)
TEST_ASSERT_EQ((size_t) (two_size_iter->clients[1]->sock->sock), (size_t) 123)
_cdtp_client_map_iter_free(two_size_iter);
// Test pop
CDTPSocket *pop1 = _cdtp_client_map_pop(map, 234);
TEST_ASSERT_EQ((size_t) (pop1->sock), (size_t) 123)
TEST_ASSERT_EQ(map->size, (size_t) 1)
TEST_ASSERT_EQ(map->capacity, (size_t) 16)
CDTPSocket *pop2 = _cdtp_client_map_pop(map, 456);
TEST_ASSERT_EQ((size_t) (pop2->sock), (size_t) 345)
TEST_ASSERT_EQ(map->size, (size_t) 0)
TEST_ASSERT_EQ(map->capacity, (size_t) 16)
// Test hash collisions
bool set3 = _cdtp_client_map_set(map, 3, sock1);
bool set4 = _cdtp_client_map_set(map, 19, sock2);
TEST_ASSERT(set3)
TEST_ASSERT(set4)
TEST_ASSERT_EQ(map->size, (size_t) 2)
TEST_ASSERT_EQ(map->capacity, (size_t) 16)
bool contains4 = _cdtp_client_map_contains(map, 3);
TEST_ASSERT(contains4)
bool contains5 = _cdtp_client_map_contains(map, 19);
TEST_ASSERT(contains5)
CDTPSocket *get4 = _cdtp_client_map_get(map, 3);
TEST_ASSERT_EQ((size_t) (get4->sock), (size_t) 123)
CDTPSocket *get5 = _cdtp_client_map_get(map, 19);
TEST_ASSERT_EQ((size_t) (get5->sock), (size_t) 345)
CDTPClientMapIter *iter1 = _cdtp_client_map_iter(map);
TEST_ASSERT_EQ(iter1->size, (size_t) 2)
TEST_ASSERT_EQ(iter1->clients[0]->client_id, (size_t) 3)
TEST_ASSERT_EQ((size_t) (iter1->clients[0]->sock->sock), (size_t) 123)
TEST_ASSERT_EQ(iter1->clients[1]->client_id, (size_t) 19)
TEST_ASSERT_EQ((size_t) (iter1->clients[1]->sock->sock), (size_t) 345)
_cdtp_client_map_iter_free(iter1);
CDTPSocket *pop3 = _cdtp_client_map_pop(map, 3);
TEST_ASSERT_EQ((size_t) (pop3->sock), (size_t) 123)
TEST_ASSERT_EQ(map->size, (size_t) 1)
TEST_ASSERT_EQ(map->capacity, (size_t) 16)
CDTPSocket *pop4 = _cdtp_client_map_pop(map, 19);
TEST_ASSERT_EQ((size_t) (pop4->sock), (size_t) 345)
TEST_ASSERT_EQ(map->size, (size_t) 0)
TEST_ASSERT_EQ(map->capacity, (size_t) 16)
// Test resize up
for (size_t i = 0; i < 16; i++) {
CDTPSocket *sock = (CDTPSocket *) malloc(sizeof(CDTPSocket));
sock->sock = 1000 + i;
bool set5 = _cdtp_client_map_set(map, i * 2, sock);
TEST_ASSERT(set5)
}
TEST_ASSERT_EQ(map->size, (size_t) 16)
TEST_ASSERT_EQ(map->capacity, (size_t) 16)
CDTPSocket *sock3 = (CDTPSocket *) malloc(sizeof(CDTPSocket));
sock3->sock = 1016;
bool set6 = _cdtp_client_map_set(map, 32, sock3);
TEST_ASSERT(set6)
TEST_ASSERT_EQ(map->size, (size_t) 17)
TEST_ASSERT_EQ(map->capacity, (size_t) 32)
size_t client_id_total = 0;
size_t sock_total = 0;
CDTPClientMapIter *iter2 = _cdtp_client_map_iter(map);
for (size_t i = 0; i < iter2->size; i++) {
client_id_total += iter2->clients[i]->client_id;
sock_total += (size_t) (iter2->clients[i]->sock->sock);
}
TEST_ASSERT_EQ(client_id_total, (size_t) 272)
TEST_ASSERT_EQ(sock_total, (size_t) 17136)
_cdtp_client_map_iter_free(iter2);
// Test resize down
for (size_t i = 16; i >= 8; i--) {
CDTPSocket *sock = _cdtp_client_map_pop(map, i * 2);
TEST_ASSERT(sock != NULL)
free(sock);
}
TEST_ASSERT_EQ(map->size, (size_t) 8)
TEST_ASSERT_EQ(map->capacity, (size_t) 32)
CDTPSocket *sock4 = _cdtp_client_map_pop(map, 14);
TEST_ASSERT(sock4 != NULL)
TEST_ASSERT_EQ(map->size, (size_t) 7)
TEST_ASSERT_EQ(map->capacity, (size_t) 16)
free(sock4);
for (int i = 6; i >= 0; i--) {
CDTPSocket *sock = _cdtp_client_map_pop(map, ((size_t) i) * 2);
TEST_ASSERT(sock != NULL)
free(sock);
}
TEST_ASSERT_EQ(map->size, (size_t) 0)
TEST_ASSERT_EQ(map->capacity, (size_t) 16)
// Clean up
free(sock1);
free(sock2);
_cdtp_client_map_free(map);
}
/**
* Test crypto functions.
*/
void test_crypto(void)
{
// Test RSA
char *rsa_message = "Hello, RSA!";
CDTPRSAKeyPair *keys = _cdtp_crypto_rsa_key_pair();
CDTPCryptoData *rsa_encrypted = _cdtp_crypto_rsa_encrypt(keys->public_key, rsa_message, STR_SIZE(rsa_message));
CDTPCryptoData *rsa_decrypted = _cdtp_crypto_rsa_decrypt(keys->private_key, rsa_encrypted->data, rsa_encrypted->data_size);
TEST_ASSERT_INT_EQ(strcmp((char *) (rsa_decrypted->data), rsa_message), 0)
TEST_ASSERT_INT_NE(strcmp((char *) (rsa_encrypted->data), rsa_message), 0)
_cdtp_crypto_rsa_key_pair_free(keys);
_cdtp_crypto_data_free(rsa_encrypted);
_cdtp_crypto_data_free(rsa_decrypted);
// Test AES
char *aes_message = "Hello, AES!";
CDTPAESKey *key = _cdtp_crypto_aes_key();
CDTPCryptoData *aes_encrypted = _cdtp_crypto_aes_encrypt(key, aes_message, STR_SIZE(aes_message));
CDTPCryptoData *aes_decrypted = _cdtp_crypto_aes_decrypt(key, aes_encrypted->data, aes_encrypted->data_size);
TEST_ASSERT_INT_EQ(strcmp((char *) (aes_decrypted->data), aes_message), 0)
TEST_ASSERT_INT_NE(strcmp((char *) (aes_encrypted->data), aes_message), 0)
_cdtp_crypto_aes_key_free(key);
_cdtp_crypto_data_free(aes_encrypted);
_cdtp_crypto_data_free(aes_decrypted);
// Test encrypting/decrypting AES key with RSA
CDTPRSAKeyPair *keys2 = _cdtp_crypto_rsa_key_pair();
CDTPAESKey *key2 = _cdtp_crypto_aes_key();
CDTPCryptoData *encrypted_key = _cdtp_crypto_rsa_encrypt(keys2->public_key, key2->key, key2->key_size);
CDTPCryptoData *decrypted_key = _cdtp_crypto_rsa_decrypt(keys2->private_key, encrypted_key->data, encrypted_key->data_size);
CDTPAESKey *key3 = _cdtp_crypto_aes_key_from(decrypted_key->data, decrypted_key->data_size);
TEST_ASSERT_EQ(key2->key_size, key3->key_size)
TEST_ASSERT_MEM_EQ(key2->key, key3->key, key2->key_size)
TEST_ASSERT_EQ(decrypted_key->data_size, key2->key_size)
TEST_ASSERT_MEM_EQ(decrypted_key->data, key2->key, decrypted_key->data_size)
TEST_ASSERT_MEM_NE(encrypted_key->data, key2->key, key2->key_size)
_cdtp_crypto_rsa_key_pair_free(keys2);
_cdtp_crypto_aes_key_free(key2);
_cdtp_crypto_data_free(encrypted_key);
_cdtp_crypto_data_free(decrypted_key);
_cdtp_crypto_aes_key_free(key3);
}
/**
* Test server creation and serving.
*/
void test_server_serve(void)
{
// Initialize test state
TestReceivedMessage *server_received[] = EMPTY;
size_t receive_clients[] = EMPTY;
size_t connect_clients[] = EMPTY;
size_t disconnect_clients[] = EMPTY;
TestReceivedMessage *client_received[] = EMPTY;
TestState *state = test_state(0, 0, 0,
server_received, receive_clients, connect_clients, disconnect_clients,
0, 0,
client_received);
// Create server
CDTPServer *s = cdtp_server(server_on_recv, server_on_connect, server_on_disconnect,
state, state, state);
TEST_ASSERT(!cdtp_server_is_serving(s))
// Start server
cdtp_server_start(s, SERVER_HOST, SERVER_PORT);
TEST_ASSERT(cdtp_server_is_serving(s))
cdtp_sleep(WAIT_TIME);
// Check server address info
char *server_host = cdtp_server_get_host(s);
unsigned short server_port = cdtp_server_get_port(s);
printf("Server address: %s:%d\n", server_host, server_port);
// Stop server
TEST_ASSERT(cdtp_server_is_serving(s))
cdtp_server_stop(s);
TEST_ASSERT(!cdtp_server_is_serving(s))
cdtp_sleep(WAIT_TIME);
// Clean up
test_state_finish(state);
cdtp_server_free(s);
free(server_host);
}
/**
* Test getting server and client addresses.
*/
void test_addresses(void)
{
// Initialize test state
TestReceivedMessage *server_received[] = EMPTY;
size_t receive_clients[] = EMPTY;
size_t connect_clients[] = {0};
size_t disconnect_clients[] = {0};
TestReceivedMessage *client_received[] = EMPTY;
TestState *state = test_state(0, 1, 1,
server_received, receive_clients, connect_clients, disconnect_clients,
0, 0,
client_received);
// Create server
CDTPServer *s = cdtp_server(server_on_recv, server_on_connect, server_on_disconnect,
state, state, state);
TEST_ASSERT(!cdtp_server_is_serving(s))
cdtp_server_start(s, SERVER_HOST, SERVER_PORT);
TEST_ASSERT(cdtp_server_is_serving(s))
char *server_host = cdtp_server_get_host(s);
unsigned short server_port = cdtp_server_get_port(s);
printf("Server address: %s:%d\n", server_host, server_port);
cdtp_sleep(WAIT_TIME);
// Create client
CDTPClient *c = cdtp_client(client_on_recv, client_on_disconnected,
state, state);
TEST_ASSERT(!cdtp_client_is_connected(c))
cdtp_client_connect(c, CLIENT_HOST, CLIENT_PORT);
TEST_ASSERT(cdtp_client_is_connected(c))
char *client_host = cdtp_client_get_host(c);
unsigned short client_port = cdtp_client_get_port(c);
printf("Client address: %s:%d\n", client_host, client_port);
cdtp_sleep(WAIT_TIME);
// Check addresses
char *ss_host = cdtp_server_get_host(s);
unsigned short ss_port = cdtp_server_get_port(s);
char *sc_host = cdtp_client_get_server_host(c);
unsigned short sc_port = cdtp_client_get_server_port(c);
char *cc_host = cdtp_client_get_host(c);
unsigned short cc_port = cdtp_client_get_port(c);
char *cs_host = cdtp_server_get_client_host(s, 0);
unsigned short cs_port = cdtp_server_get_client_port(s, 0);
printf("Server (according to server): %s:%d\n", ss_host, ss_port);
printf("Server (according to client): %s:%d\n", sc_host, sc_port);
printf("Client (according to client): %s:%d\n", cc_host, cc_port);
printf("Client (according to server): %s:%d\n", cs_host, cs_port);
TEST_ASSERT_STR_EQ(ss_host, "0.0.0.0")
TEST_ASSERT_STR_EQ(sc_host, "127.0.0.1")
TEST_ASSERT_INT_EQ(ss_port, sc_port)
TEST_ASSERT_STR_EQ(cc_host, cs_host)
TEST_ASSERT_INT_EQ(cc_port, cs_port)
// Disconnect client
TEST_ASSERT(cdtp_client_is_connected(c))
cdtp_client_disconnect(c);
TEST_ASSERT(!cdtp_client_is_connected(c))
cdtp_sleep(WAIT_TIME);
// Stop server
TEST_ASSERT(cdtp_server_is_serving(s))
cdtp_server_stop(s);
TEST_ASSERT(!cdtp_server_is_serving(s))
cdtp_sleep(WAIT_TIME);
// Clean up
test_state_finish(state);
cdtp_server_free(s);
cdtp_client_free(c);
free(server_host);
free(client_host);
free(ss_host);
free(sc_host);
free(cc_host);
free(cs_host);
}
/**
* Test sending messages between server and client.
*/
void test_send_receive(void)
{
// Initialize test state
char *server_message = "Hello, server!";
char *client_message = "Hello, client #0!";
TestReceivedMessage *server_received[] = {
str_message(server_message)
};
size_t receive_clients[] = {0};
size_t connect_clients[] = {0};
size_t disconnect_clients[] = {0};
TestReceivedMessage *client_received[] = {
str_message(client_message)
};
TestState *state = test_state(1, 1, 1,
server_received, receive_clients, connect_clients, disconnect_clients,
1, 0,
client_received);
// Create server
CDTPServer *s = cdtp_server(server_on_recv, server_on_connect, server_on_disconnect,
state, state, state);
cdtp_server_start(s, SERVER_HOST, SERVER_PORT);
char *server_host = cdtp_server_get_host(s);
unsigned short server_port = cdtp_server_get_port(s);
printf("Server address: %s:%d\n", server_host, server_port);
cdtp_sleep(WAIT_TIME);
// Create client
CDTPClient *c = cdtp_client(client_on_recv, client_on_disconnected,
state, state);
cdtp_client_connect(c, CLIENT_HOST, CLIENT_PORT);
cdtp_sleep(WAIT_TIME);
// Send messages
cdtp_client_send(c, server_message, STR_SIZE(server_message));
cdtp_server_send(s, 0, client_message, STR_SIZE(client_message));
cdtp_sleep(WAIT_TIME);
// Disconnect client
cdtp_client_disconnect(c);
cdtp_sleep(WAIT_TIME);
// Stop server
cdtp_server_stop(s);
cdtp_sleep(WAIT_TIME);
// Clean up
test_state_finish(state);
cdtp_server_free(s);
cdtp_client_free(c);
free(server_host);
}
/**
* Test sending large random messages between server and client.
*/
void test_send_large_messages(void)
{
// Initialize test state
size_t large_server_message_len = (size_t) rand_int(256, 512);
char *large_server_message = rand_bytes(large_server_message_len);
size_t large_client_message_len = (size_t) rand_int(128, 256);
char *large_client_message = rand_bytes(large_client_message_len);
TestReceivedMessage *server_received[] = {
test_received_message((void *) large_server_message, large_server_message_len)
};
size_t receive_clients[] = {0};
size_t connect_clients[] = {0};
size_t disconnect_clients[] = {0};
TestReceivedMessage *client_received[] = {
test_received_message((void *) large_client_message, large_client_message_len)
};
TestState *state = test_state(1, 1, 1,
server_received, receive_clients, connect_clients, disconnect_clients,
1, 0,
client_received);
// Create server
CDTPServer *s = cdtp_server(server_on_recv, server_on_connect, server_on_disconnect,
state, state, state);
cdtp_server_start(s, SERVER_HOST, SERVER_PORT);
char *server_host = cdtp_server_get_host(s);
unsigned short server_port = cdtp_server_get_port(s);
printf("Server address: %s:%d\n", server_host, server_port);
cdtp_sleep(WAIT_TIME);
// Create client
CDTPClient *c = cdtp_client(client_on_recv, client_on_disconnected,
state, state);
cdtp_client_connect(c, CLIENT_HOST, CLIENT_PORT);
cdtp_sleep(WAIT_TIME);
// Send messages
cdtp_client_send(c, large_server_message, large_server_message_len);
cdtp_server_send(s, 0, large_client_message, large_client_message_len);
cdtp_sleep(WAIT_TIME);
// Disconnect client
cdtp_client_disconnect(c);
cdtp_sleep(WAIT_TIME);
// Stop server
cdtp_server_stop(s);
cdtp_sleep(WAIT_TIME);
// Log message sizes
printf("Server message sizes: %" PRI_SIZE_T ", %" PRI_SIZE_T "\n", state->server_received[0]->data_size, large_server_message_len);
printf("Client message sizes: %" PRI_SIZE_T ", %" PRI_SIZE_T "\n", state->client_received[0]->data_size, large_client_message_len);
// Clean up
test_state_finish(state);
cdtp_server_free(s);
cdtp_client_free(c);
free(server_host);
}
/**
* Test sending numerous random messages between server and client.
*/
void test_sending_numerous_messages(void)
{
// Initialize test state
size_t num_server_messages = (size_t) rand_int(64, 128);
int *server_messages = (int *) malloc(num_server_messages * sizeof(int));
for (size_t i = 0; i < num_server_messages; i++) server_messages[i] = rand();
size_t num_client_messages = (size_t) rand_int(128, 256);
int *client_messages = (int *) malloc(num_client_messages * sizeof(int));
for (size_t i = 0; i < num_client_messages; i++) client_messages[i] = rand();
TestReceivedMessage **server_received = (TestReceivedMessage **) malloc(num_server_messages * sizeof(TestReceivedMessage *));
for (size_t i = 0; i < num_server_messages; i++) server_received[i] = int_message(server_messages[i]);
size_t *receive_clients = (size_t *) malloc(num_server_messages * sizeof(size_t));
for (size_t i = 0; i < num_server_messages; i++) receive_clients[i] = 0;
size_t connect_clients[] = {0};
size_t disconnect_clients[] = {0};
TestReceivedMessage **client_received = (TestReceivedMessage **) malloc(num_client_messages * sizeof(TestReceivedMessage *));
for (size_t i = 0; i < num_client_messages; i++) client_received[i] = int_message(client_messages[i]);
TestState *state = test_state(num_server_messages, 1, 1,
server_received, receive_clients, connect_clients, disconnect_clients,
num_client_messages, 0,
client_received);
// Create server
CDTPServer *s = cdtp_server(server_on_recv, server_on_connect, server_on_disconnect,
state, state, state);
cdtp_server_start(s, SERVER_HOST, SERVER_PORT);
char *server_host = cdtp_server_get_host(s);
unsigned short server_port = cdtp_server_get_port(s);
printf("Server address: %s:%d\n", server_host, server_port);
cdtp_sleep(WAIT_TIME);
// Create client
CDTPClient *c = cdtp_client(client_on_recv, client_on_disconnected,
state, state);
cdtp_client_connect(c, CLIENT_HOST, CLIENT_PORT);
cdtp_sleep(WAIT_TIME);
// Send messages
for (size_t i = 0; i < num_server_messages; i++) {
cdtp_client_send(c, &(server_messages[i]), sizeof(int));
cdtp_sleep(0.01);
}
for (size_t i = 0; i < num_client_messages; i++) {
cdtp_server_send_all(s, &(client_messages[i]), sizeof(int));
cdtp_sleep(0.01);
}
cdtp_sleep(5);
// Disconnect client
cdtp_client_disconnect(c);
cdtp_sleep(WAIT_TIME);
// Stop server
cdtp_server_stop(s);
cdtp_sleep(WAIT_TIME);
// Log number of messages
printf("Number of server messages: %" PRI_SIZE_T ", %" PRI_SIZE_T "\n", state->server_receive_count, num_server_messages);
printf("Number of client messages: %" PRI_SIZE_T ", %" PRI_SIZE_T "\n", state->client_receive_count, num_client_messages);
// Clean up
test_state_finish(state);
cdtp_server_free(s);
cdtp_client_free(c);
free(server_messages);
free(client_messages);
free(server_received);
free(client_received);
free(receive_clients);
free(server_host);
}
/**
* Test sending and receiving custom types.
*/
void test_sending_custom_types(void)
{
// Initialize test state
Custom *custom_server_message = (Custom *) malloc(sizeof(Custom));
custom_server_message->a = -123;
custom_server_message->b = 789;
Custom *custom_client_message = (Custom *) malloc(sizeof(Custom));
custom_client_message->a = -234;
custom_client_message->b = 678;
TestReceivedMessage *server_received[] = {
test_received_message(custom_server_message, sizeof(Custom))
};
size_t receive_clients[] = {0};
size_t connect_clients[] = {0};
size_t disconnect_clients[] = {0};
TestReceivedMessage *client_received[] = {
test_received_message(custom_client_message, sizeof(Custom))
};
TestState *state = test_state(1, 1, 1,
server_received, receive_clients, connect_clients, disconnect_clients,
1, 0,
client_received);
// Create server
CDTPServer *s = cdtp_server(server_on_recv, server_on_connect, server_on_disconnect,
state, state, state);
cdtp_server_start(s, SERVER_HOST, SERVER_PORT);
char *server_host = cdtp_server_get_host(s);
unsigned short server_port = cdtp_server_get_port(s);
printf("Server address: %s:%d\n", server_host, server_port);
cdtp_sleep(WAIT_TIME);
// Create client
CDTPClient *c = cdtp_client(client_on_recv, client_on_disconnected,
state, state);
cdtp_client_connect(c, CLIENT_HOST, CLIENT_PORT);
cdtp_sleep(WAIT_TIME);
// Send messages
cdtp_client_send(c, custom_server_message, sizeof(Custom));
cdtp_server_send(s, 0, custom_client_message, sizeof(Custom));
cdtp_sleep(WAIT_TIME);
// Disconnect client
cdtp_client_disconnect(c);
cdtp_sleep(WAIT_TIME);
// Stop server
cdtp_server_stop(s);
cdtp_sleep(WAIT_TIME);
// Clean up
test_state_finish(state);
cdtp_server_free(s);
cdtp_client_free(c);
free(server_host);
}
/**
* Test having multiple clients connected.
*/
void test_multiple_clients(void)
{
// Initialize test state
char *message_from_client1 = "Hello from client #1!";
char *message_from_client2 = "Goodbye from client #2!";
char *message_from_other_clients = "Just another client -\\_(\"/)_/-";
size_t message_from_server = 29275;
size_t message_to_client1 = 123;
size_t message_to_client2 = 789;
TestReceivedMessage *server_received[] = {
str_message(message_from_client1),
str_message(message_from_client2),
str_message(message_from_other_clients),
str_message(message_from_other_clients),
str_message(message_from_other_clients),
str_message(message_from_other_clients),
str_message(message_from_other_clients),
str_message(message_from_other_clients),
str_message(message_from_other_clients),
str_message(message_from_other_clients),
str_message(message_from_other_clients),
str_message(message_from_other_clients),
str_message(message_from_other_clients),
str_message(message_from_other_clients),
str_message(message_from_other_clients),
str_message(message_from_other_clients),
str_message(message_from_other_clients)
};
size_t receive_clients[] = {0, 1, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2};
size_t connect_clients[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16};
size_t disconnect_clients[] = {2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 0, 1};
TestReceivedMessage *client_received[] = {
size_t_message(strlen(message_from_client1) + 1),
size_t_message(strlen(message_from_client2) + 1),
size_t_message(message_from_server),
size_t_message(message_from_server),
size_t_message(message_to_client1),
size_t_message(message_to_client2)
};
TestState *state = test_state(17, 17, 17,
server_received, receive_clients, connect_clients, disconnect_clients,
6, 0,
client_received);
state->reply_with_string_length = true;
// Create server
CDTPServer *s = cdtp_server(server_on_recv, server_on_connect, server_on_disconnect,
state, state, state);
cdtp_server_start(s, SERVER_HOST, SERVER_PORT);
char *server_host = cdtp_server_get_host(s);
unsigned short server_port = cdtp_server_get_port(s);
printf("Server address: %s:%d\n", server_host, server_port);
cdtp_sleep(WAIT_TIME);
// Create client 1
CDTPClient *c1 = cdtp_client(client_on_recv, client_on_disconnected,
state, state);
cdtp_client_connect(c1, CLIENT_HOST, CLIENT_PORT);
cdtp_sleep(WAIT_TIME);
// Check client 1 address info
char *cc1_host = cdtp_client_get_host(c1);
unsigned short cc1_port = cdtp_client_get_port(c1);
char *cs1_host = cdtp_server_get_client_host(s, 0);
unsigned short cs1_port = cdtp_server_get_client_port(s, 0);
printf("Client #1 (according to client #1): %s:%d\n", cc1_host, cc1_port);
printf("Client #1 (according to server): %s:%d\n", cs1_host, cs1_port);
TEST_ASSERT_STR_EQ(cc1_host, cs1_host)
TEST_ASSERT_INT_EQ(cc1_port, cs1_port)
// Create client 2
CDTPClient *c2 = cdtp_client(client_on_recv, client_on_disconnected,
state, state);
cdtp_client_connect(c2, CLIENT_HOST, CLIENT_PORT);
cdtp_sleep(WAIT_TIME);
// Check client 2 address info
char *cc2_host = cdtp_client_get_host(c2);
unsigned short cc2_port = cdtp_client_get_port(c2);
char *cs2_host = cdtp_server_get_client_host(s, 1);
unsigned short cs2_port = cdtp_server_get_client_port(s, 1);
printf("Client #2 (according to client #2): %s:%d\n", cc2_host, cc2_port);
printf("Client #2 (according to server): %s:%d\n", cs2_host, cs2_port);
TEST_ASSERT_STR_EQ(cc2_host, cs2_host)
TEST_ASSERT_INT_EQ(cc2_port, cs2_port)
// Send message from client 1
cdtp_client_send(c1, message_from_client1, STR_SIZE(message_from_client1));
cdtp_sleep(WAIT_TIME);
// Send message from client 2
cdtp_client_send(c2, message_from_client2, STR_SIZE(message_from_client2));
cdtp_sleep(WAIT_TIME);
// Send message to all clients
cdtp_server_send_all(s, &message_from_server, sizeof(size_t));
cdtp_sleep(WAIT_TIME);
// Send message to client 1
cdtp_server_send(s, 0, &message_to_client1, sizeof(size_t));
cdtp_sleep(WAIT_TIME);
// Send message to client 2
cdtp_server_send(s, 1, &message_to_client2, sizeof(size_t));
cdtp_sleep(WAIT_TIME);
// Connect other clients
state->reply_with_string_length = false;
TEST_ASSERT_EQ(s->clients->capacity, (size_t) 16)
CDTPClient *other_clients[15];
for (size_t i = 0; i < 15; i++) {
other_clients[i] = cdtp_client(client_on_recv, client_on_disconnected,
state, state);
cdtp_client_connect(other_clients[i], CLIENT_HOST, CLIENT_PORT);
cdtp_sleep(WAIT_TIME);
}
TEST_ASSERT_EQ(s->clients->capacity, (size_t) 32)
// Send messages from other clients
for (int i = 14; i >= 0; i--) {
cdtp_client_send(other_clients[i], message_from_other_clients, STR_SIZE(message_from_other_clients));
cdtp_sleep(WAIT_TIME);
}
// Disconnect other clients
for (size_t i = 0; i < 15; i++) {
cdtp_client_disconnect(other_clients[i]);
cdtp_sleep(WAIT_TIME);
}
TEST_ASSERT_EQ(s->clients->capacity, (size_t) 16)
// Disconnect client 1
cdtp_client_disconnect(c1);
cdtp_sleep(WAIT_TIME);
// Disconnect client 2
cdtp_client_disconnect(c2);
cdtp_sleep(WAIT_TIME);
// Stop server
cdtp_server_stop(s);
cdtp_sleep(WAIT_TIME);
// Clean up
test_state_finish(state);
cdtp_server_free(s);
cdtp_client_free(c1);
cdtp_client_free(c2);
for (size_t i = 0; i < 15; i++) {
cdtp_client_free(other_clients[i]);
}
free(server_host);
free(cc1_host);
free(cs1_host);
free(cc2_host);
free(cs2_host);
}
/**
* Test clients disconnecting from the server.
*/
void test_client_disconnected(void)
{
// Initialize test state
TestReceivedMessage *server_received[] = EMPTY;
size_t receive_clients[] = EMPTY;
size_t connect_clients[] = {0};
size_t disconnect_clients[] = EMPTY;
TestReceivedMessage *client_received[] = EMPTY;
TestState *state = test_state(0, 1, 0,
server_received, receive_clients, connect_clients, disconnect_clients,
0, 1,
client_received);
// Create server
CDTPServer *s = cdtp_server(server_on_recv, server_on_connect, server_on_disconnect,
state, state, state);
TEST_ASSERT(!cdtp_server_is_serving(s))
cdtp_server_start(s, SERVER_HOST, SERVER_PORT);
TEST_ASSERT(cdtp_server_is_serving(s))
char *server_host = cdtp_server_get_host(s);
unsigned short server_port = cdtp_server_get_port(s);
printf("Server address: %s:%d\n", server_host, server_port);
cdtp_sleep(WAIT_TIME);
// Create client
CDTPClient *c = cdtp_client(client_on_recv, client_on_disconnected,
state, state);
TEST_ASSERT(!cdtp_client_is_connected(c))
cdtp_client_connect(c, CLIENT_HOST, CLIENT_PORT);
TEST_ASSERT(cdtp_client_is_connected(c))
cdtp_sleep(WAIT_TIME);
// Stop server
TEST_ASSERT(cdtp_server_is_serving(s))
TEST_ASSERT(cdtp_client_is_connected(c))
cdtp_server_stop(s);
TEST_ASSERT(!cdtp_server_is_serving(s))
cdtp_sleep(WAIT_TIME);
TEST_ASSERT(!cdtp_client_is_connected(c))
cdtp_sleep(WAIT_TIME);
// Clean up
test_state_finish(state);
cdtp_server_free(s);
cdtp_client_free(c);
free(server_host);
}
/**
* Test removing a client from the server.
*/
void test_remove_client(void)
{
// Initialize test state
TestReceivedMessage *server_received[] = EMPTY;
size_t receive_clients[] = EMPTY;
size_t connect_clients[] = {0};
size_t disconnect_clients[] = EMPTY;
TestReceivedMessage *client_received[] = EMPTY;
TestState *state = test_state(0, 1, 0,
server_received, receive_clients, connect_clients, disconnect_clients,
0, 1,
client_received);
// Create server
CDTPServer *s = cdtp_server(server_on_recv, server_on_connect, server_on_disconnect,
state, state, state);
TEST_ASSERT(!cdtp_server_is_serving(s))
cdtp_server_start(s, SERVER_HOST, SERVER_PORT);
TEST_ASSERT(cdtp_server_is_serving(s))
char *server_host = cdtp_server_get_host(s);
unsigned short server_port = cdtp_server_get_port(s);
printf("Server address: %s:%d\n", server_host, server_port);
cdtp_sleep(WAIT_TIME);
// Create client
CDTPClient *c = cdtp_client(client_on_recv, client_on_disconnected,
state, state);
TEST_ASSERT(!cdtp_client_is_connected(c))
cdtp_client_connect(c, CLIENT_HOST, CLIENT_PORT);
TEST_ASSERT(cdtp_client_is_connected(c))
cdtp_sleep(WAIT_TIME);
// Disconnect the client
TEST_ASSERT(cdtp_client_is_connected(c))
cdtp_server_remove_client(s, 0);
cdtp_sleep(WAIT_TIME);
TEST_ASSERT(!cdtp_client_is_connected(c))
// Stop server
TEST_ASSERT(cdtp_server_is_serving(s))
cdtp_server_stop(s);
TEST_ASSERT(!cdtp_server_is_serving(s))
cdtp_sleep(WAIT_TIME);
// Clean up
test_state_finish(state);
cdtp_server_free(s);
cdtp_client_free(c);
free(server_host);
}
int main(void)
{
printf("Beginning tests\n");
// Initialize the random number generator
srand(time(NULL));
// Register error event
cdtp_on_error(on_err, NULL);
// Run tests
printf("\nTesting utilities...\n");
test_util();
printf("\nTesting client map...\n");
test_client_map();
printf("\nTesting crypto...\n");
test_crypto();
printf("\nTesting server creation and serving...\n");
test_server_serve();
printf("\nTesting addresses...\n");
test_addresses();
printf("\nTesting send and receive...\n");
test_send_receive();
printf("\nTesting sending large messages...\n");
test_send_large_messages();
printf("\nTesting sending numerous messages...\n");
test_sending_numerous_messages();
printf("\nTesting sending custom types...\n");
test_sending_custom_types();
printf("\nTesting with multiple clients...\n");
test_multiple_clients();
printf("\nTesting disconnecting clients...\n");
test_client_disconnected();
printf("\nTesting removing clients...\n");
test_remove_client();
// Done
printf("\nCompleted tests\n");
}
| 2.4375 | 2 |
2024-11-18T22:23:45.403001+00:00 | 2016-10-02T05:47:35 | 1ee2139c4792fc3b6be14f67878f2697880e88c5 | {
"blob_id": "1ee2139c4792fc3b6be14f67878f2697880e88c5",
"branch_name": "refs/heads/master",
"committer_date": "2016-10-02T05:47:35",
"content_id": "a7677a07ef470bad37f388568940be6c8b4c77d3",
"detected_licenses": [
"MIT"
],
"directory_id": "ed2ca186bd1d9b0e61d2634e77a0b6b0c02e6d27",
"extension": "c",
"filename": "heartbeat.c",
"fork_events_count": 1,
"gha_created_at": "2015-02-20T06:00:52",
"gha_event_created_at": "2016-10-02T05:47:37",
"gha_language": "C",
"gha_license_id": null,
"github_id": 31053039,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 642,
"license": "MIT",
"license_type": "permissive",
"path": "/src/events/heartbeat.c",
"provenance": "stackv2-0115.json.gz:70802",
"repo_name": "tituschow/msxi-chaos",
"revision_date": "2016-10-02T05:47:35",
"revision_id": "6bfa84ab59ee8f44c4260beeca7e8df2f21a1d6c",
"snapshot_id": "692bb76bb7111e60f908e017416cf87072481f61",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/tituschow/msxi-chaos/6bfa84ab59ee8f44c4260beeca7e8df2f21a1d6c/src/events/heartbeat.c",
"visit_date": "2021-05-16T02:45:37.567850"
} | stackv2 | #include "heartbeat.h"
#include "sm/event_queue.h"
#include "timer_a.h"
static const struct IOMap *pin = NULL;
static IOState state;
void heartbeat_init(const struct IOMap *heartbeat_pin) {
pin = heartbeat_pin;
io_set_resistor_dir(pin, PIN_IN, RESISTOR_PULLUP);
state = io_get_state(pin);
}
void heartbeat_timer_cb(uint16_t elapsed_ms, void *context) {
bool forced = context;
IOState heartbeat_state = io_get_state(pin);
if (heartbeat_state != state || forced) {
// Raise a heartbeat state event - high means good
state = heartbeat_state;
event_raise((state == IO_LOW) ? HEARTBEAT_GOOD : HEARTBEAT_BAD, 0);
}
}
| 2.234375 | 2 |
2024-11-18T22:23:45.466695+00:00 | 2017-09-19T20:11:29 | 9260ecdce776add4606d01f4ece9b6199791f9b5 | {
"blob_id": "9260ecdce776add4606d01f4ece9b6199791f9b5",
"branch_name": "refs/heads/master",
"committer_date": "2017-09-19T20:11:29",
"content_id": "6504197a8ab588217890909f09a95cbbb96c70b2",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "ae388f052500def3fd1836dd4c819e4a7261f3c8",
"extension": "h",
"filename": "SbmConfig.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 103991926,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2309,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/include/SbmConfig.h",
"provenance": "stackv2-0115.json.gz:70931",
"repo_name": "plewand/stereovision",
"revision_date": "2017-09-19T20:11:29",
"revision_id": "b05aa2e064d8877c47e5d7182db4b72979ad9d57",
"snapshot_id": "e49e04987c0eb465132dbdc16ae0624233086dd0",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/plewand/stereovision/b05aa2e064d8877c47e5d7182db4b72979ad9d57/include/SbmConfig.h",
"visit_date": "2021-06-29T00:56:12.373721"
} | stackv2 | #ifndef SMBCONFIG_H
#define SMBCONFIG_H
#include <opencv2/calib3d.hpp>
enum StereoAlgorithm {
SBM = 0,
SGBM
};
#define PP(a) #a << "=" << a << endl
struct SbmConfig {
int algorithm;
int nDispMult16;
int blockSize;
int uniquenesRatio;
int preFilterCap;
int disp12MaxDiff;
int minDisparity;
int speckleWindowSize;
int speckleRangeMult16;
int sbmPreFilterSize;
int sbmFilterType;
int sbmSmallerBlockSize;
int sbmTextureThreshold;
int sgbmP1;
int sgbmP2;
int sgbmMode;
int disparityFiltering;
int disparityFilteringLambda;
int disparityFilteringSigma;
int smoothKernelSize;
SbmConfig() {
algorithm = StereoAlgorithm::SBM;
nDispMult16 = 4;
blockSize = 19;
uniquenesRatio = 15;
preFilterCap = 17;
minDisparity = 1;
disp12MaxDiff = 1;
speckleWindowSize = 400;
speckleRangeMult16 = 200;
sbmPreFilterSize = 9;
sbmFilterType = StereoBM::PREFILTER_NORMALIZED_RESPONSE; // PREFILTER_NORMALIZED_RESPONSE = 0, PREFILTER_XSOBEL = 1
sbmSmallerBlockSize = 1;
sbmTextureThreshold = 5;
sgbmP1 = 100;
sgbmP2 = 1000;
sgbmMode = StereoSGBM::MODE_SGBM; // StereoSGBM::MODE_HH
disparityFiltering = 0;
disparityFilteringLambda = 8000;
disparityFilteringSigma = 1000;
smoothKernelSize = 21;
}
string toString() {
stringstream s;
s << PP(algorithm)
<< PP(nDispMult16)
<< PP(blockSize)
<< PP(uniquenesRatio)
<< PP(preFilterCap)
<< PP(disp12MaxDiff)
<< PP(minDisparity)
<< PP(speckleWindowSize)
<< PP(speckleRangeMult16)
<< PP(sbmPreFilterSize)
<< PP(sbmFilterType)
<< PP(sbmSmallerBlockSize)
<< PP(sbmTextureThreshold)
<< PP(sgbmP1)
<< PP(sgbmP2)
<< PP(sgbmMode)
<< PP(disparityFiltering)
<< PP(disparityFilteringLambda)
<< PP(disparityFilteringSigma)
<< PP(smoothKernelSize);
return s.str();
}
};
#endif /* SMBCONFIG_H */
| 2.078125 | 2 |
2024-11-18T22:23:45.581252+00:00 | 2020-11-10T09:28:45 | 4cd50581d74f4f3a33685790d8f9592c1800338a | {
"blob_id": "4cd50581d74f4f3a33685790d8f9592c1800338a",
"branch_name": "refs/heads/main",
"committer_date": "2020-11-10T09:28:45",
"content_id": "7b7cd4cd676bef9cfcf24e1320d621d51dcd643d",
"detected_licenses": [
"MIT"
],
"directory_id": "d3ca2525444ac90964ca14a0748be673e48a8194",
"extension": "c",
"filename": "test_R.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 311020617,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1161,
"license": "MIT",
"license_type": "permissive",
"path": "/testmaker/tests/test_R.c",
"provenance": "stackv2-0115.json.gz:71189",
"repo_name": "dhy2000/CO_utils",
"revision_date": "2020-11-10T09:28:45",
"revision_id": "87346b32e98bb4c0734898aa1a8ad045d5fd4228",
"snapshot_id": "cc0476dd5afcd90fcfe0b43a3de5815d1fd7b963",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/dhy2000/CO_utils/87346b32e98bb4c0734898aa1a8ad045d5fd4228/testmaker/tests/test_R.c",
"visit_date": "2023-01-05T22:43:09.978709"
} | stackv2 | // lui, ori, sw
// add, sub, addu, subu, slt, sltu, and, or, xor, nor
#include "asm/registers.h"
#include "asm/comment.h"
#include "asm/rwmem.h"
#include "asm/loadimm.h"
#include "asm/r.h"
#include <stdlib.h>
#include <time.h>
const char *instr[] = {"addu", "subu", "slt", "sltu", "and", "or", "xor", "nor"};
const int numbers[] = {
0, 1, -1, 2147483647, -2147483648, -2147483647
};
const int num_instr = sizeof(instr) / sizeof(instr[0]);
const int num_numbers = sizeof(numbers) / sizeof(numbers[0]);
int addr = 0;
void test_ins(const char *ins, int x1, int x2) {
li(t0, x1);
li(t1, x2);
rasm(ins, t2, t0, t1);
sw(t2, 0, addr);
addr += 4;
}
int main()
{
srand(time(NULL));
freopen("test_R.asm", "w", stdout);
for (int i = 0; i < num_instr; i++) {
rem(instr[i]);
for (int j1 = 0; j1 < num_numbers; j1++) {
for (int j2 = j1; j2 < num_numbers; j2++) {
test_ins(instr[i], numbers[j1], numbers[j2]);
}
}
test_ins(instr[i], rand(), rand());
test_ins(instr[i], rand(), -rand());
test_ins(instr[i], -rand(), -rand());
}
return 0;
} | 2.34375 | 2 |
2024-11-18T22:23:46.665237+00:00 | 2019-10-31T16:01:11 | af4a39a5c39ef3717e5350b50a762c0f5c59845d | {
"blob_id": "af4a39a5c39ef3717e5350b50a762c0f5c59845d",
"branch_name": "refs/heads/master",
"committer_date": "2019-10-31T16:01:11",
"content_id": "46c9fb6ad65120f85d82057d0b3892d4e6c7fec7",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "99249e222a2f35ac11a7fd93bff10a3a13f6f948",
"extension": "c",
"filename": "fling__functions.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 218764551,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3709,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/ros2_mod_ws/build/robobo_msgs/rosidl_generator_c/robobo_msgs/msg/fling__functions.c",
"provenance": "stackv2-0115.json.gz:71446",
"repo_name": "mintforpeople/robobo-ros2-ios-port",
"revision_date": "2019-10-31T16:01:11",
"revision_id": "1a5650304bd41060925ebba41d6c861d5062bfae",
"snapshot_id": "87aec17a0c89c3fc5a42411822a18f08af8a5b0f",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/mintforpeople/robobo-ros2-ios-port/1a5650304bd41060925ebba41d6c861d5062bfae/ros2_mod_ws/build/robobo_msgs/rosidl_generator_c/robobo_msgs/msg/fling__functions.c",
"visit_date": "2020-08-31T19:41:01.124753"
} | stackv2 | // generated from rosidl_generator_c/resource/msg__functions.c.em
// generated code does not contain a copyright notice
#include "robobo_msgs/msg/fling__functions.h"
#include <assert.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
// include message dependencies
// angle
// distance
#include "std_msgs/msg/int16__functions.h"
// time
#include "std_msgs/msg/int32__functions.h"
bool
robobo_msgs__msg__Fling__init(robobo_msgs__msg__Fling * msg)
{
if (!msg) {
return false;
}
// angle
if (!std_msgs__msg__Int16__init(&msg->angle)) {
robobo_msgs__msg__Fling__destroy(msg);
return false;
}
// time
if (!std_msgs__msg__Int32__init(&msg->time)) {
robobo_msgs__msg__Fling__destroy(msg);
return false;
}
// distance
if (!std_msgs__msg__Int16__init(&msg->distance)) {
robobo_msgs__msg__Fling__destroy(msg);
return false;
}
return true;
}
void
robobo_msgs__msg__Fling__fini(robobo_msgs__msg__Fling * msg)
{
if (!msg) {
return;
}
// angle
std_msgs__msg__Int16__fini(&msg->angle);
// time
std_msgs__msg__Int32__fini(&msg->time);
// distance
std_msgs__msg__Int16__fini(&msg->distance);
}
robobo_msgs__msg__Fling *
robobo_msgs__msg__Fling__create()
{
robobo_msgs__msg__Fling * msg = (robobo_msgs__msg__Fling *)malloc(sizeof(robobo_msgs__msg__Fling));
if (!msg) {
return NULL;
}
memset(msg, 0, sizeof(robobo_msgs__msg__Fling));
bool success = robobo_msgs__msg__Fling__init(msg);
if (!success) {
free(msg);
return NULL;
}
return msg;
}
void
robobo_msgs__msg__Fling__destroy(robobo_msgs__msg__Fling * msg)
{
if (msg) {
robobo_msgs__msg__Fling__fini(msg);
}
free(msg);
}
bool
robobo_msgs__msg__Fling__Array__init(robobo_msgs__msg__Fling__Array * array, size_t size)
{
if (!array) {
return false;
}
robobo_msgs__msg__Fling * data = NULL;
if (size) {
data = (robobo_msgs__msg__Fling *)calloc(size, sizeof(robobo_msgs__msg__Fling));
if (!data) {
return false;
}
// initialize all array elements
size_t i;
for (i = 0; i < size; ++i) {
bool success = robobo_msgs__msg__Fling__init(&data[i]);
if (!success) {
break;
}
}
if (i < size) {
// if initialization failed finalize the already initialized array elements
for (; i > 0; --i) {
robobo_msgs__msg__Fling__fini(&data[i - 1]);
}
free(data);
return false;
}
}
array->data = data;
array->size = size;
array->capacity = size;
return true;
}
void
robobo_msgs__msg__Fling__Array__fini(robobo_msgs__msg__Fling__Array * array)
{
if (!array) {
return;
}
if (array->data) {
// ensure that data and capacity values are consistent
assert(array->capacity > 0);
// finalize all array elements
for (size_t i = 0; i < array->capacity; ++i) {
robobo_msgs__msg__Fling__fini(&array->data[i]);
}
free(array->data);
array->data = NULL;
array->size = 0;
array->capacity = 0;
} else {
// ensure that data, size, and capacity values are consistent
assert(0 == array->size);
assert(0 == array->capacity);
}
}
robobo_msgs__msg__Fling__Array *
robobo_msgs__msg__Fling__Array__create(size_t size)
{
robobo_msgs__msg__Fling__Array * array = (robobo_msgs__msg__Fling__Array *)malloc(sizeof(robobo_msgs__msg__Fling__Array));
if (!array) {
return NULL;
}
bool success = robobo_msgs__msg__Fling__Array__init(array, size);
if (!success) {
free(array);
return NULL;
}
return array;
}
void
robobo_msgs__msg__Fling__Array__destroy(robobo_msgs__msg__Fling__Array * array)
{
if (array) {
robobo_msgs__msg__Fling__Array__fini(array);
}
free(array);
}
| 2.171875 | 2 |
2024-11-18T22:23:46.737954+00:00 | 2021-01-01T07:50:16 | 6add7d7b3f95529583be7bfc22f575433320a691 | {
"blob_id": "6add7d7b3f95529583be7bfc22f575433320a691",
"branch_name": "refs/heads/main",
"committer_date": "2021-01-01T07:51:22",
"content_id": "f404fa072cf481fd6124feef23047684c0d68d29",
"detected_licenses": [
"MIT"
],
"directory_id": "1d3febe8638e4edca696a8736a443dcadb351c78",
"extension": "c",
"filename": "DebugWndFont.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 325932155,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1950,
"license": "MIT",
"license_type": "permissive",
"path": "/develop/DebugWnd/DebugWndFont.c",
"provenance": "stackv2-0115.json.gz:71576",
"repo_name": "wurly200a/xdx",
"revision_date": "2021-01-01T07:50:16",
"revision_id": "82a34e6eb4ae6d0048acece1b00f724ac8bc2195",
"snapshot_id": "01d20f09e5ebc369313a1da4da845e98a1afa13d",
"src_encoding": "SHIFT_JIS",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/wurly200a/xdx/82a34e6eb4ae6d0048acece1b00f724ac8bc2195/develop/DebugWnd/DebugWndFont.c",
"visit_date": "2023-02-05T10:53:31.578468"
} | stackv2 | /* 共通インクルードファイル */
#include "common.h"
/* 個別インクルードファイル */
typedef struct
{
LOGFONT logfont;
} S_FONT_DATA;
/* 外部関数定義 */
/* 外部変数定義 */
/* 内部関数定義 */
#include "DebugWndFont.h"
/* 内部変数定義 */
static S_FONT_DATA fontData;
/********************************************************************************
* 内容 : フォント初期化
* 引数 : なし
* 戻り値: なし
***************************************/
void
DebugFontInit( void )
{
GetObject( GetStockObject(SYSTEM_FIXED_FONT), sizeof(LOGFONT), (PTSTR)&(fontData.logfont) );
}
/********************************************************************************
* 内容 : フォント選択
* 引数 : HWND hwnd
* 戻り値: BOOL (FALSE:キャンセルされた)
***************************************/
BOOL
DebugFontChooseFont( HWND hwnd )
{
BOOL rtn = FALSE;
CHOOSEFONT cf;
cf.lStructSize = sizeof(CHOOSEFONT);
cf.hwndOwner = hwnd;
cf.hDC = NULL;
cf.lpLogFont = &(fontData.logfont);
cf.iPointSize = 0;
cf.Flags = CF_INITTOLOGFONTSTRUCT | CF_SCREENFONTS | CF_FIXEDPITCHONLY/*| CF_EFFECTS */;
cf.rgbColors = 0;
cf.lCustData = 0;
cf.lpfnHook = NULL;
cf.lpTemplateName = NULL;
cf.hInstance = NULL;
cf.lpszStyle = NULL;
cf.nFontType = 0;
cf.nSizeMin = 0;
cf.nSizeMax = 0;
rtn = ChooseFont(&cf);
return rtn;
}
/********************************************************************************
* 内容 : 論理フォント取得
* 引数 : なし
* 戻り値: LOGFONT *
***************************************/
LOGFONT *
DebugFontGetLogFont( void )
{
LOGFONT *rtnPtr = NULL;
rtnPtr = &(fontData.logfont);
return rtnPtr;
}
| 2.3125 | 2 |
2024-11-18T22:23:46.829230+00:00 | 2023-08-13T13:58:07 | a0a2f0b1684d4de8bad8aa7d4b94810d2d81e74c | {
"blob_id": "a0a2f0b1684d4de8bad8aa7d4b94810d2d81e74c",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-13T13:58:07",
"content_id": "29c8733cb5498f8e051b8ddabec34e677edee97b",
"detected_licenses": [
"CC0-1.0"
],
"directory_id": "7e4eccee4ba976b6694cd944fea75e7835cd1a4b",
"extension": "h",
"filename": "mmap_file.h",
"fork_events_count": 0,
"gha_created_at": "2016-03-24T19:11:14",
"gha_event_created_at": "2022-06-06T19:18:26",
"gha_language": "C",
"gha_license_id": "NOASSERTION",
"github_id": 54667633,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3935,
"license": "CC0-1.0",
"license_type": "permissive",
"path": "/linux/mmap_file.h",
"provenance": "stackv2-0115.json.gz:71704",
"repo_name": "zwizwa/uc_tools",
"revision_date": "2023-08-13T13:58:07",
"revision_id": "20df6f91a2082424b498e384583d7f403ff8bf16",
"snapshot_id": "fc16d39722d5f30164dad524cd86f1aec230f2f4",
"src_encoding": "UTF-8",
"star_events_count": 6,
"url": "https://raw.githubusercontent.com/zwizwa/uc_tools/20df6f91a2082424b498e384583d7f403ff8bf16/linux/mmap_file.h",
"visit_date": "2023-08-18T20:45:09.789340"
} | stackv2 | #ifndef MMAP_FILE
#define MMAP_FILE
/* For mremap. Note that other headers might include mman.h so be
sure to be first. */
#define _GNU_SOURCE
#include <unistd.h>
#include <sys/mman.h>
/* A sane interface for memory-mapped read/write files: growable arrays. */
#include "assert_mmap.h"
#include "assert_write.h"
struct mmap_file {
void *buf;
off_t size;
int fd;
};
#ifndef MMAP_FILE_LOG
#define MMAP_FILE_LOG(...)
#endif
static inline void mmap_file_close(struct mmap_file *ref) {
/* Idempotent. */
if (!ref->buf) return;
ASSERT_ERRNO(munmap(ref->buf, ref->size));
ref->buf = NULL;
ASSERT_ERRNO(close(ref->fd));
ref->fd = -1;
}
static inline void mmap_file_sync(struct mmap_file *ref) {
if (!ref->buf) return;
ASSERT_ERRNO(msync(ref->buf, ref->size, MS_SYNC));
}
/* Internal: make sure file is large enough. */
static inline off_t mmap_file_grow__(struct mmap_file *ref, off_t size) {
/* Can't map empty files. */
if (!size) size = 1;
if (size > ref->size) {
/* Align requested size to page size. */
const off_t page_size = sysconf(_SC_PAGESIZE);
//MMAP_FILE_LOG("page_size = %d\n", page_size);
size = (((size-1)/page_size)+1)*page_size;
off_t old_size = ref->size;
MMAP_FILE_LOG("growing: %d -> %d\n", old_size, size);
ftruncate(ref->fd, size);
ref->size = size;
return old_size;
}
else {
return -1;
}
}
/* Precondition: file can be mapped, but file is open.
Post condition: at least size bytes are available and file is mapped.
Pointer can change. */
static inline void *mmap_file_reserve(struct mmap_file *ref, off_t size) {
off_t old_size = mmap_file_grow__(ref, size);
if (old_size < 0) return ref->buf; // no resize, so no remap
ASSERT(ref->buf);
ASSERT(ref->size);
ref->buf = mremap(ref->buf, old_size, ref->size, MREMAP_MAYMOVE);
ASSERT(MAP_FAILED != ref->buf);
return ref->buf;
}
/* Post condition: at least size bytes are available and file is mapped. */
static inline void *mmap_file_open(struct mmap_file *ref,
const char *file, off_t size) {
memset(ref,0,sizeof(*ref));
/* Open the file for read-write, create if necessary. */
MMAP_FILE_LOG("opening %s\n", file);
ASSERT_ERRNO(ref->fd = open(file, O_RDWR | O_CREAT, 0664));
ASSERT_ERRNO(ref->size = lseek(ref->fd, 0, SEEK_END));
/* Grow if necessary and map into memory. */
mmap_file_grow__(ref, size);
ref->buf = mmap(NULL, ref->size, PROT_READ | PROT_WRITE, MAP_SHARED, ref->fd, 0);
ASSERT(MAP_FAILED != ref->buf);
return ref->buf;
}
/* Post condition: at least size bytes are available and file is mapped. */
static inline const void *mmap_file_open_ro(struct mmap_file *ref,
const char *file) {
memset(ref,0,sizeof(*ref));
/* Open the file for read-write, create if necessary. */
MMAP_FILE_LOG("opening %s (ro)\n", file);
ASSERT_ERRNO(ref->fd = open(file, O_RDONLY, 0664));
ASSERT_ERRNO(ref->size = lseek(ref->fd, 0, SEEK_END));
ref->buf = mmap(NULL, ref->size, PROT_READ, MAP_SHARED, ref->fd, 0);
ASSERT(MAP_FAILED != ref->buf);
return ref->buf;
}
static inline const void *mmap_file_open_rw(struct mmap_file *ref,
const char *file,
uintptr_t nb_bytes) {
memset(ref,0,sizeof(*ref));
/* Open the file for read-write, create if necessary. */
MMAP_FILE_LOG("opening %s (rw)\n", file);
ASSERT_ERRNO(ref->fd = open(file, O_RDWR | O_CREAT, 0664));
ref->size = nb_bytes;
ftruncate(ref->fd, nb_bytes);
ref->buf = mmap(NULL, ref->size, PROT_READ | PROT_WRITE, MAP_SHARED, ref->fd, 0);
ref->size = nb_bytes;
ASSERT(MAP_FAILED != ref->buf);
return mmap_file_reserve(ref, nb_bytes);
}
#endif
| 2.75 | 3 |
2024-11-18T22:23:46.891324+00:00 | 2022-06-23T03:58:20 | 4cad14ab90dc4055298c5a3cbe7330b54f0af955 | {
"blob_id": "4cad14ab90dc4055298c5a3cbe7330b54f0af955",
"branch_name": "refs/heads/master",
"committer_date": "2022-06-23T03:58:20",
"content_id": "26a4c79579987d1068b53d756638cb0b6627ec41",
"detected_licenses": [
"MIT"
],
"directory_id": "2d763df0c625ed6c7b714c5723200c63fd0a7107",
"extension": "c",
"filename": "test.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 131547016,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 23217,
"license": "MIT",
"license_type": "permissive",
"path": "/src/c/test.c",
"provenance": "stackv2-0115.json.gz:71832",
"repo_name": "gameblabla/western_ideals",
"revision_date": "2022-06-23T03:58:20",
"revision_id": "0bb08ebf39d668de42ede2fb4fd590bb764e40b7",
"snapshot_id": "2eab5fef5f607591e41c4275baf9cb19b38d5ddf",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/gameblabla/western_ideals/0bb08ebf39d668de42ede2fb4fd590bb764e40b7/src/c/test.c",
"visit_date": "2022-07-08T02:02:53.687818"
} | stackv2 | /*
The MIT License (MIT)
Copyright (c) 2018 Gameblabla
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:
*/
#include <pebble.h>
static Window *my_window;
static TextLayer *text_layer;
static Layer *myCanvas;
static GBitmap *current_background;
static GBitmap *bmp[6];
static unsigned char game_mode = 0;
static unsigned char remember_back;
static unsigned char buttons[3];
static unsigned char wait_press = 0;
static unsigned char gameover_c = 0;
/* Progress[0] : Overall ingame progression
* Progress[1] : See insersection[53]
*/
static unsigned char progress[2];
static unsigned char about_to_go;
static unsigned char titlescreen_press_start_time;
static unsigned char time_tit ;
static short titlescreen_y;
static unsigned char twice;
static unsigned char choice;
static unsigned char x_man;
static unsigned char x_enn[7];
static short y_enn[7];
static unsigned char state_enn[7], anim_enn[7];
static short enemies_number;
static unsigned char shooting;
static short rand_a_b(short a, short b)
{
return rand()%(b-a) +a;
}
/* Action button */
static void sel_click_handler(ClickRecognizerRef recognizer, void *context) {buttons[0] = 1;}
static void sel_release_handler(ClickRecognizerRef recognizer, void *context) {buttons[0] = 0;}
/* Up button */
static void sel_click_handler_up(ClickRecognizerRef recognizer, void *context) {buttons[1] = 1;}
static void sel_release_handler_up(ClickRecognizerRef recognizer, void *context) {buttons[1] = 0;}
/* Down button */
static void sel_click_handler_down(ClickRecognizerRef recognizer, void *context) {buttons[2] = 1;}
static void sel_release_handler_down(ClickRecognizerRef recognizer, void *context) {buttons[2] = 0;}
const char text
[140] /* Number of dialogues */
[52] /* Size of text */
= {
{"It all started when you met a cute boi."},
{"This really beautiful young man is Bakaka."},
{"He's totally not gay, i swear man."},
{"And obviously you're not horny for him."},
{"Just pretend you're just friends, okay ?"},
{"Let's go. And don't push him too far."},
{"Bakaka: Hey,\n how are you doing ?"}, //8
{""},
{"Bakaka: ... You can't be serious. Right?"},
{""},
{"Bakaka: How dare you? I don't deserve this."},
{"Bakaka: Just... DIE !"},
{"g"},
{"Bakaka: I'll pretend nothing happened..."}, // 13
{"Bakaka: Awesome . Let's go somewhere !"}, // 14
{"Where should we go ?"}, // 15
{"1"},
{"2"},
{"3"},
{"4"},
{"Bakaka: Alright, let's head\nfor the US-Mex Border."},
{"Location : US-Mexico Border"},
{"Bakaka: We're here !\nStrange place to go huh?"},
{"Bakaka: It since became an attraction park for"},
{"tourists.You can even shoot at incoming migrants !"},
{"? : Excuse me."},
{"Jonas : My name is Alexander Jonas."},
{"Why does this white-haired dude look like a"},
{"faggot? Don't even think of having sex with my"},
{"car, is that clear ? I know you plot something!"},
{"Bakaka: Can you..ugh... nevermind."},
{"1OO years ago, we were feeding black babies to"},
{"the alligators.But those babies were communists!"},
{"Now that we've purged the US of Democrats, it's"},
{"time to get rid of those dirty mexicans !"},
{"School shootings, Tornadoes, Famines...They"},
{"were behind them all! They want to destroy"},
{"MY country and our right to bear arms !"},
{"Let us cleanse the world of our oppressors."},
{"...Jonas goes away."},
{"Bakaka: Gee, does this guy even have a life ?"},
{"He would choke on a piece of meat while he's"},
{"thinking about his next conspiracy plot..."},
{"Anyway, let's go to the shooting gallery."},
{"'Shooting Gallery'"},
{"Here we are! But i don't see any targets..."},
{"Dude: Damnit, where are those miggers ?"},
{"Dude: I see one ! Shoot at it !"},
{"*Gun fire*"},
{"Dude: Yeah, target down! That'll teach em!"},
{"Mate i tell you, it's better than fishing."},
{"Bakaka: I tought those were Crisis actors..."},
{"I feel like i want to vomit..."},
{"I'll be right back, just stand still."},
{"Dude: I see an army of miggers ! Help !"},
{"Hey you over there! Grab a gun and help me."},
{""},
{"You: I'm not interested to leave a mess."},
{"Dude: Are you a democrat? You sound like one!"},
{"Dude: Well thank you, moron !"},
{"10 minutes later."},
{"Bakaka: Sorry, i'm back. What happened?"},
{"You: Some guy left a mess outside."},
{"Bakaka: Great, this is more fucked up than i"},
{"expected it would be. Let's go home."},
{"A few hours later, we're home."},
{"^"},
{"Dude: Then grab that rifle and help me !"},
{"Let's rock and roll !"},
{"V"}, // Mini-game
{"You : And that should be it !"},
{"... Fuck. They're bleeding for real."},
{"I guess they really weren't crisis actors."},
{"Bakaka: Sorry, i'm back. What happened?"},
{"Bakaka: ... Welp. That's a bloody mess."},
{"Bakaka: Did you do this ?"},
{"Dude: Nah, it was me.Thanks to my trusty rifle!"},
{"Bakaka: You murderer... Let's get out of here."},
{"A few hours later, we're home."},
{"^"},
{"Alright, let's go to Syria !"},
{"Location: Somewhere in Syria."},
{"*Rumbles*"},
{"Bakaka: What's going on? I thought it was over !"},
{"*Rumbles*"},
{"Bakaka: Guess not..."},
{"Bakaka: This is fucked up. We should get out!"},
{""},
{"Bakaka: Are you crazy?! We gonna die!"},
{""},
{"Bakaka: Why do you insist so much ?!"},
{""},
{"Bakaka: A kiss ? Here? You're kidding !"},
{"Bakaka: Something's coming our way..."},
{"g"},
{"Bakaka: Hurry! Let's go to the border instead."},
{"We decided to go to the US-Mex border instead."},
{"Let's hope it's not as chaotic..."},
{"i"},
{"Bakaka: Pfiu! That was... interesting."},
{"Bakaka: What did you think of it?"},
{""},
{"Bakaka: Let's say that i like to live"},
{"Bakaka: dangerously !"},
{"Bakaka: Anything else to say ?"},
{""},
{"Bakaka: Haha, thanks ! We almost died though !"},
{"Bakaka: Anything else to say ?"},
{""},
{"Bakaka: ... Why are you telling me this ?"},
{"Bakaka: You... traitor."},
{"Bakaka: Do you realise what this means?"},
{"You: You almost got myself killed !"},
{"You: Frankly, you're an idiot."},
{"Bakaka: ...Why. After all we've done."},
{"Bakaka: Fine, whatever. As you wish."},
{"Bakaka: I'll make sure to end this quickly."},
{"*Slash*"},
{"2"}, // Bad ending activated
{"Bakaka: ...Well, interesting."},
{"Bakaka: I could give you a try i suppose."},
{"Bakaka: Hey, what are you doing ?"},
{"Bakaka: ..."},
{"Bakaka: Nice dick."},
{"Bakaka: Nice shape too !"},
{"Bakaka: I'll suck it for sure !"},
{"Bakaka: ...\nin a future sequel."},
{"And then they lived happily after. TEH END"},
{"Sucks huh ? No sex scene !"},
{"Just be happy that you got to see a dick, ok?"},
{"Oh and this is the last Pebble game too."},
{"So don't complain, mokay ?"},
{"I had to rush that shit."},
{"See you later."},
{"Made by Gameblabla"},
{"https://gameblabla.nl"},
{"q"}
};
const unsigned char face[140] =
{
0,
0,
0,
0,
0,
0,
1,// Fine, Get out faggot (Choice)
1,// If you chose faggot, tells you "You can't be serious"
4,
4,
4,
0,
0,
3,
1,
1,
8,
8,
8,
8,
8,
9,
11,
11,
11,
11,
10,
10,
10,
10,
11,
10,
10,
10,
10,
10,
10,
10,
10,
9,
11,
11,
11,
11,
12,
16,
12,
13,
14,
15,
15,
17,
17,
17,
15,
15,
15,
15,
15,
15,
0,
11,
11,
11,
11,
8,
0,
15,
15,
15,
20,
20,
20,
20,
21,
21,
21,
20,
21,
8,
8,
22,
22,
23,
22,
23,
23,
23,
23,
23,
23,
23,
23,
23,
24,
23,
8,
8,
0,
2,
1,//What did you think of it
1,
3,
3,
1,
1,
2,
1,
1,
4,
4,
4,
4,
4,
4,
1,
1,
0,
0,
3,
1,
1,
25,
26,
27,
27,
27,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
};
const char choice_text
[20] /* Number of dialogues */
[50] /* Size of text */
= {
{" Fine\n Get out faggot"},
{" I am, faggot!\n Just Kidding."},
{" US-Mexico border\n Syria"},
{" No thanks.\n Hell yeah!"},
{" Let's get out.\n Hell no"},
{" I said no..\n You're right..."},
{" Let's kiss.\n Let's hurry"},
{" Why these places?\n It was great!"},
{" You're a moron\n I love you"},
{" You're a moron\n I love you"},
};
const unsigned char insersection[11] =
{
7, // Bakaka: Hey,\n how are you doing ?
9,
16,
56, //Grab a gun
87,
89,
91,
101,
105,
108
};
const unsigned char YouMustChoose[140][3] =
{
{0,0},
{1,1},
{2,2},
{3,3},
{4,4},
{5,5},
{6,6},
{14, 8}, // First choice, 7
{8,8},
{10, 13}, // You can't be serious, right ?, 9
{10,10},
{11,11},
{12,12},
{13,13},
{14,14},
{15,15},
{20, 80}, // Where should we go, 16
{17,0},
{18,0},
{19,0},
{20,0},
{21,0},
{22,0},
{23,0},
{24,0},
{25,0},
{26,0},
{27,0},
{28,0},
{29,0},
{30,0},
{31,0},
{32,0},
{33,0},
{34,0},
{35,0},
{36,0},
{37,0},
{38,0},
{39,0},
{40,0},
{41,0},
{42,0},
{43,0},
{44,0},
{45,0},
{46,0},
{47,0},
{48,0},
{49,0},
{50,0},
{51,0},
{52,0},
{53,0},
{54,0},
{55,0},
{58,67}, // NO thanks, 56
{48,0},
{49,0},
{50,0},
{51,0},
{52,0},
{53,0},
{54,0},
{55,0},
{48,0},
{49,0},
{50,0},
{51,0},
{52,0},
{53,0},
{54,0},
{55,0},
{48,0},
{49,0},
{50,0},
{51,0},
{52,0},
{53,0},
{54,0},
{55,0},
{48,0},
{49,0},
{50,0},
{51,0},
{52,0},
{0,0},
{95,88},
{0,0},
{90,95},
{0,0},
{92,95},
{49,0},
{50,0},
{51,0},
{52,0},
{53,0},
{54,0},
{55,0},
{48,0},
{102,106},
{102,106},
{55,0},
{48,0},
{109,119},
{109,119},
{55,0},
{109,119},
{109,119},
};
static unsigned char anybutton_pressed()
{
if (buttons[0] == 1 || buttons[1] == 1 || buttons[2] == 1)
return 1;
return 0;
}
static void Reset_buttons()
{
buttons[0] = buttons[1] = buttons[2] = 0;
}
static void change_pict(unsigned char pict)
{
if (remember_back == pict)
return;
remember_back = pict;
gbitmap_destroy(current_background);
switch(pict)
{
// Titlescreen
case 254:
current_background = gbitmap_create_with_resource(RESOURCE_ID_IMAGE_TITLESCREEN);
break;
case 0:
current_background = gbitmap_create_with_resource(RESOURCE_ID_IMAGE_BLACK);
break;
case 1:
current_background = gbitmap_create_with_resource(RESOURCE_ID_IMAGE_BAKURA);
break;
case 2:
current_background = gbitmap_create_with_resource(RESOURCE_ID_IMAGE_TIRED);
break;
case 3:
current_background = gbitmap_create_with_resource(RESOURCE_ID_IMAGE_CLOSING);
break;
case 4:
current_background = gbitmap_create_with_resource(RESOURCE_ID_IMAGE_EVIL);
break;
case 5:
current_background = gbitmap_create_with_resource(RESOURCE_ID_IMAGE_HELL);
break;
case 6:
current_background = gbitmap_create_with_resource(RESOURCE_ID_IMAGE_BLOOD);
break;
case 8:
current_background = gbitmap_create_with_resource(RESOURCE_ID_IMAGE_WORLDMAP);
break;
case 9:
current_background = gbitmap_create_with_resource(RESOURCE_ID_IMAGE_USMEXI_1);
break;
case 10:
current_background = gbitmap_create_with_resource(RESOURCE_ID_IMAGE_USMEXI_2);
break;
case 11:
current_background = gbitmap_create_with_resource(RESOURCE_ID_IMAGE_USMEXI_3);
break;
case 12:
current_background = gbitmap_create_with_resource(RESOURCE_ID_IMAGE_B1);
break;
case 13:
current_background = gbitmap_create_with_resource(RESOURCE_ID_IMAGE_B2);
break;
case 14:
current_background = gbitmap_create_with_resource(RESOURCE_ID_IMAGE_B3);
break;
case 15:
current_background = gbitmap_create_with_resource(RESOURCE_ID_IMAGE_B4);
break;
case 16:
current_background = gbitmap_create_with_resource(RESOURCE_ID_IMAGE_B5);
break;
case 17:
current_background = gbitmap_create_with_resource(RESOURCE_ID_IMAGE_B6);
break;
case 18:
current_background = gbitmap_create_with_resource(RESOURCE_ID_IMG_DESERT);
break;
case 19:
current_background = gbitmap_create_with_resource(RESOURCE_ID_IMAGE_NSC1);
break;
case 20:
current_background = gbitmap_create_with_resource(RESOURCE_ID_IMAGE_B7);
break;
case 21:
current_background = gbitmap_create_with_resource(RESOURCE_ID_IMAGE_B7);
break;
case 22:
current_background = gbitmap_create_with_resource(RESOURCE_ID_IMG_SY1);
break;
case 23:
current_background = gbitmap_create_with_resource(RESOURCE_ID_IMG_SY2);
break;
case 24:
current_background = gbitmap_create_with_resource(RESOURCE_ID_IMG_SY3);
break;
case 25:
current_background = gbitmap_create_with_resource(RESOURCE_ID_IMG_BAKAKA_DICK);
break;
case 26:
current_background = gbitmap_create_with_resource(RESOURCE_ID_IMG_BAKAKA_SUR);
break;
case 27:
current_background = gbitmap_create_with_resource(RESOURCE_ID_IMG_BAKAKA_SUR2);
break;
case 28:
current_background = gbitmap_create_with_resource(RESOURCE_ID_IMG_END1);
break;
}
}
static void Generate_enemy_pos(unsigned char tmp)
{
unsigned char a;
a = rand_a_b(-1, 3);
switch(a)
{
default:
x_enn[tmp] = 24;
break;
case 1:
x_enn[tmp] = 64;
break;
case 2:
x_enn[tmp] = 112;
break;
}
}
static void Load_minigame_mex()
{
unsigned char i, a;
change_pict(18);
bmp[0] = gbitmap_create_with_resource(RESOURCE_ID_IMG_MEX1);
bmp[1] = gbitmap_create_with_resource(RESOURCE_ID_IMG_MEX2);
bmp[2] = gbitmap_create_with_resource(RESOURCE_ID_IMG_MEX3);
bmp[3] = gbitmap_create_with_resource(RESOURCE_ID_IMG_MEX4);
bmp[4] = gbitmap_create_with_resource(RESOURCE_ID_IMG_GUN1);
bmp[5] = gbitmap_create_with_resource(RESOURCE_ID_IMG_GUN2);
enemies_number = rand_a_b(90, 110);
shooting = 0;
x_man = 32;
for(i=0;i<7;i++)
{
Generate_enemy_pos(i);
y_enn[i] = rand_a_b(-60, -100);
anim_enn[i] = 0;
state_enn[i] = 0;
}
}
static void free_minigame()
{
unsigned char i;
for(i=0;i<6;i++)
gbitmap_destroy(bmp[i]);
}
static void timer_handler(void *context)
{
layer_mark_dirty(myCanvas);
app_timer_register(34, timer_handler, NULL);
}
static void config_provider(Window *window)
{
window_raw_click_subscribe(BUTTON_ID_SELECT, sel_click_handler, sel_release_handler, NULL);
window_raw_click_subscribe(BUTTON_ID_UP, sel_click_handler_up, sel_release_handler_up, NULL);
window_raw_click_subscribe(BUTTON_ID_DOWN, sel_click_handler_down, sel_release_handler_down, NULL);
}
static unsigned char Select_Gameover(unsigned char tmp)
{
if (tmp == 13)
{
return 5;
}
else if (tmp == 94)
{
return 24;
}
return 5;
}
static void Back_ToTitlescreen()
{
Reset_buttons();
game_mode = 0;
change_pict(254);
time_tit = 0;
progress[0] = 0;
progress[1] = 0;
titlescreen_y = 0;
about_to_go = 0;
gameover_c = 0;
titlescreen_press_start_time = 0;
choice = 0;
twice = 0;
about_to_go = 0;
}
static void updateGame(Layer *layer, GContext *ctx)
{
unsigned char i;
graphics_context_set_compositing_mode(ctx, GCompOpAssign);
graphics_context_set_text_color(ctx, GColorBlack);
switch(game_mode)
{
// Titlescreen
case 0:
graphics_context_set_text_color(ctx, GColorWhite);
graphics_draw_bitmap_in_rect(ctx, current_background, GRect(0, titlescreen_y, 144, 200));
graphics_draw_text(ctx, "Western Ideals", fonts_get_system_font(FONT_KEY_ROBOTO_CONDENSED_21), GRect(10, 0, 144, 24), GTextOverflowModeWordWrap, GTextAlignmentLeft, NULL);
if (titlescreen_y > -10) titlescreen_y--;
switch(about_to_go)
{
case 0:
titlescreen_press_start_time++;
if (titlescreen_press_start_time < 10)
graphics_draw_text(ctx,"SELECT TO START", fonts_get_system_font(FONT_KEY_GOTHIC_14_BOLD), GRect(20, 144, 168, 24), GTextOverflowModeWordWrap, GTextAlignmentLeft, NULL);
else if (titlescreen_press_start_time > 20)
titlescreen_press_start_time = 0;
if (time_tit < 10)
time_tit++;
if (anybutton_pressed() && time_tit > 8)
{
about_to_go = 1;
time_tit = 0;
}
break;
case 1:
#ifdef PBL_COLOR
graphics_context_set_text_color(ctx, GColorRed);
#else
graphics_context_set_text_color(ctx, GColorWhite);
#endif
titlescreen_press_start_time++;
if (titlescreen_press_start_time < 2)
graphics_draw_text(ctx,"LET'S GO SUCKA", fonts_get_system_font(FONT_KEY_GOTHIC_14_BOLD), GRect(25, 144, 168, 24), GTextOverflowModeWordWrap, GTextAlignmentLeft, NULL);
else if (titlescreen_press_start_time > 4)
titlescreen_press_start_time = 0;
time_tit++;
if (time_tit > 40)
{
game_mode = 1;
progress[0] = 0;
change_pict(face[progress[0]]);
}
break;
}
break;
// Ingame
case 1:
graphics_draw_bitmap_in_rect(ctx, current_background, GRect(0, 0, 144, 168));
graphics_draw_text(ctx, text[progress[0]], fonts_get_system_font(FONT_KEY_GOTHIC_14), GRect(0, 136, 144, 24), GTextOverflowModeWordWrap, GTextAlignmentLeft, NULL);
if (anybutton_pressed() && wait_press > 5)
{
progress[0]++;
for(i=0;i<sizeof(insersection);i++)
{
if (progress[0] == insersection[i])
{
game_mode = 2;
progress[1] = i;
}
}
if (text[progress[0]][0] == '*')
vibes_short_pulse();
// This checks whenever the player has lost, we simply take a look at the first string
if (text[progress[0]][0] == 'g')
{
game_mode = 3;
change_pict(Select_Gameover(progress[0]));
vibes_long_pulse();
}
else if (text[progress[0]][0] == 'i')
{
progress[0] = 21;
change_pict(face[progress[0]]);
}
else if (text[progress[0]][0] == 'q')
{
Back_ToTitlescreen();
}
else if (text[progress[0]][0] == '^')
{
progress[0] = 100;
change_pict(face[progress[0]]);
}
else if (text[progress[0]][0] == 'V')
{
game_mode = 5;
Load_minigame_mex();
}
else if (text[progress[0]][0] == '2')
{
game_mode = 3;
gameover_c = 2;
change_pict(28);
time_tit = 0;
}
/* If not, let's go as usual and change the picture according
to the text.
*/
else
{
change_pict(face[progress[0]]);
}
Reset_buttons();
}
if (wait_press < 7) wait_press++;
break;
// Choose Your Destiny
case 2:
graphics_draw_bitmap_in_rect(ctx, current_background, GRect(0, 0, 144, 168));
graphics_draw_text(ctx, choice_text[progress[1]], fonts_get_system_font(FONT_KEY_GOTHIC_14), GRect(0, 136, 144, 24), GTextOverflowModeWordWrap, GTextAlignmentLeft, NULL);
graphics_draw_text(ctx, ">", fonts_get_system_font(FONT_KEY_GOTHIC_14), GRect(0, 136+(choice*13), 168, 24), GTextOverflowModeWordWrap, GTextAlignmentLeft, NULL);
if (buttons[1] == 1) choice = 0;
else if (buttons[2] == 1) choice = 1;
// You made your choice and confirm it
else if (buttons[0] == 1)
{
progress[0] = YouMustChoose[progress[0]][choice];
change_pict(face[progress[0]]);
Reset_buttons();
game_mode = 1;
choice = 0;
}
break;
// You die (depends on how you lose)
case 3:
graphics_draw_bitmap_in_rect(ctx, current_background, GRect(0, 0, 144, 168));
time_tit++;
graphics_context_set_text_color(ctx, GColorWhite);
if (gameover_c == 1)
graphics_draw_text(ctx, "Killed by Mexican!", fonts_get_system_font(FONT_KEY_GOTHIC_14), GRect(32, 0, 144, 24), GTextOverflowModeWordWrap, GTextAlignmentLeft, NULL);
if (twice < 4)
{
if (time_tit < 2)
{
graphics_context_set_fill_color(ctx, GColorWhite);
graphics_fill_rect(ctx, GRect(0, 0, 144, 168), 0, GCornerNone);
}
else if (time_tit > 3)
{
twice++;
time_tit = 0;
}
}
else
{
if (time_tit > 50)
{
game_mode = 4;
change_pict(6);
time_tit = 0;
}
}
break;
// Game over screen
case 4:
graphics_draw_bitmap_in_rect(ctx, current_background, GRect(0, 0, 144, 168));
#ifdef PBL_COLOR
graphics_context_set_text_color(ctx, GColorRed);
#else
graphics_context_set_text_color(ctx, GColorWhite);
#endif
if (gameover_c == 2)
graphics_draw_text(ctx, "BAD ENDING", fonts_get_system_font(FONT_KEY_ROBOTO_CONDENSED_21), GRect(20, 0, 144, 32), GTextOverflowModeWordWrap, GTextAlignmentLeft, NULL);
else
graphics_draw_text(ctx, "GAME OVER", fonts_get_system_font(FONT_KEY_ROBOTO_CONDENSED_21), GRect(24, 0, 144, 32), GTextOverflowModeWordWrap, GTextAlignmentLeft, NULL);
time_tit++;
if ((anybutton_pressed() && time_tit > 15))
{
Back_ToTitlescreen();
}
break;
/* Shooting at poor innocent Mexicans
* (America has gone wrong by this point !)
*/
case 5:
graphics_draw_bitmap_in_rect(ctx, current_background, GRect(0, 0, 144, 168));
graphics_context_set_compositing_mode(ctx, GCompOpSet);
if (enemies_number < 1)
{
graphics_draw_text(ctx, "You did it !", fonts_get_system_font(FONT_KEY_ROBOTO_CONDENSED_21), GRect(32, 0, 144, 24), GTextOverflowModeWordWrap, GTextAlignmentLeft, NULL);
time_tit++;
if (time_tit > 120)
{
progress[0] = 70;
game_mode = 1;
free_minigame();
change_pict(20);
}
}
else
{
shooting = 0;
if (buttons[1])
{
x_man = 24;
shooting = 1;
}
else if (buttons[0])
{
x_man = 64;
shooting = 1;
}
else if (buttons[2])
{
x_man = 112;
shooting = 1;
}
for(i=0;i<7;i++)
{
if (state_enn[i] == 0)
{
if (shooting == 1 && x_man == x_enn[i] && y_enn[i] > 8)
state_enn[i] = 1;
anim_enn[i]++;
if (anim_enn[i] > 2) anim_enn[i] = 0;
graphics_draw_bitmap_in_rect(ctx, bmp[anim_enn[i]], GRect(x_enn[i], y_enn[i], 16, 16));
if (enemies_number > 50) y_enn[i] += rand_a_b(0,5);
else y_enn[i] += rand_a_b(3,6);
// Game over man
if (y_enn[i] > 144)
{
game_mode = 3;
gameover_c = 1;
time_tit = 0;
change_pict(19);
}
}
else
{
graphics_draw_bitmap_in_rect(ctx, bmp[3], GRect(x_enn[i], y_enn[i], 16, 16));
state_enn[i]++;
if (state_enn[i] > 15)
{
y_enn[i] = rand_a_b(-20,-60);
Generate_enemy_pos(i);
state_enn[i] = 0;
enemies_number--;
}
}
}
if (shooting == 1)
graphics_draw_bitmap_in_rect(ctx, bmp[5], GRect(x_man, 152, 16, 16));
else
graphics_draw_bitmap_in_rect(ctx, bmp[4], GRect(x_man, 152, 16, 16));
}
graphics_context_set_compositing_mode(ctx, GCompOpAssign);
break;
}
}
static void init()
{
my_window = window_create();
window_set_click_config_provider(my_window, (ClickConfigProvider)config_provider);
myCanvas = layer_create(GRect(0, 0, 144, 168));
window_stack_push(my_window, true);
Layer* motherLayer = window_get_root_layer(my_window);
layer_add_child(motherLayer, myCanvas);
layer_set_update_proc(myCanvas, updateGame);
app_timer_register(34, timer_handler, NULL);
}
static void deinit()
{
text_layer_destroy(text_layer);
window_destroy(my_window);
}
int main(void)
{
Back_ToTitlescreen();
init();
app_event_loop();
deinit();
}
| 2.1875 | 2 |
2024-11-18T22:23:47.042791+00:00 | 2019-02-25T08:59:07 | 62c352ca81679ecca34408ef60bc681c3bab75a3 | {
"blob_id": "62c352ca81679ecca34408ef60bc681c3bab75a3",
"branch_name": "refs/heads/master",
"committer_date": "2019-02-25T08:59:07",
"content_id": "c0664fcf845d6d3468cfe34e3ad0716b968ffef5",
"detected_licenses": [
"MIT"
],
"directory_id": "5644384405989ea42dd767303628cfababcc0b66",
"extension": "c",
"filename": "main.c",
"fork_events_count": 5,
"gha_created_at": "2019-01-27T17:12:39",
"gha_event_created_at": "2019-02-23T19:01:55",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 167835347,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 19564,
"license": "MIT",
"license_type": "permissive",
"path": "/src/main.c",
"provenance": "stackv2-0115.json.gz:71963",
"repo_name": "onivan/stc_diyclock-ntp",
"revision_date": "2019-02-25T08:59:07",
"revision_id": "1f8965797b40491f2309cc0190662f745d4f6f67",
"snapshot_id": "c65f4a6849a7a7e7ed90925a9f59685f0e229d89",
"src_encoding": "UTF-8",
"star_events_count": 9,
"url": "https://raw.githubusercontent.com/onivan/stc_diyclock-ntp/1f8965797b40491f2309cc0190662f745d4f6f67/src/main.c",
"visit_date": "2020-04-18T23:58:11.554082"
} | stackv2 | //
// STC15F204EA DIY LED Clock
// Copyright 2016, Jens Jensen
//
// silence: "src/main.c:672: warning 126: unreachable code"
#pragma disable_warning 126
#include "stc15.h"
#include <stdint.h>
#include <stdio.h>
#include "adc.h"
#include "ds1302.h"
#include "led.h"
#include <string.h>
#include "serial.h"
//~ #define LEDT P1_4 // Red
//~ #define LEDR P1_3 // Grean
#define BSIZE 12
//~ #define LTI_1 LEDT = 0 // Red
//~ #define LTI_0 LEDT = 1
//~ #define LRI_1 LEDR = 0 // Grean
//~ #define LRI_0 LEDR = 1
//~ __code char buffer_r[BSIZE] = "reset\n";
__idata char buffer_t[BSIZE] = "test\n";
volatile __bit busy;
volatile __bit rReady = 0;
__idata volatile uint8_t rec_data[BSIZE];
volatile uint8_t rec_num = 0;
volatile uint8_t nH, nM, nS, nW, nT;
void SendString(char *s);
void SendData(unsigned char dat);
void clear_rec_data();
uint8_t charToint (char h, char l);
//~ char * intTochar (uint8_t n);
uint8_t intToBCD(uint8_t nn) ;
char intToChar (uint8_t n);
//~ void _delay_ms(uint8_t ms);
void serial_init ();
#ifndef FOSC
#define FOSC 11059200L //ϵͳƵÂÊ
#endif
// clear wdt
#define WDT_CLEAR() (WDT_CONTR |= 1 << 4)
// hardware configuration
#include "hwconfig.h"
// display mode states
enum keyboard_mode {
K_NORMAL,
K_SET_HOUR,
K_SET_MINUTE,
K_SET_HOUR_12_24,
K_SEC_DISP,
K_TEMP_DISP,
#ifndef WITHOUT_DATE
K_DATE_DISP,
K_SET_MONTH,
K_SET_DAY,
#endif
K_WEEKDAY_DISP,
#ifndef WITHOUT_ALARM
K_ALARM,
K_ALARM_SET_HOUR,
K_ALARM_SET_MINUTE,
#endif
#ifdef DEBUG
K_DEBUG,
K_DEBUG2,
K_DEBUG3,
#endif
};
// display mode states
enum display_mode {
M_NORMAL,
M_SET_HOUR_12_24,
M_SEC_DISP,
M_TEMP_DISP,
#ifndef WITHOUT_DATE
M_DATE_DISP,
#endif
M_WEEKDAY_DISP,
#ifndef WITHOUT_ALARM
M_ALARM,
#endif
#ifdef DEBUG
M_DEBUG,
M_DEBUG2,
M_DEBUG3,
#endif
};
#define NUM_DEBUG 3
/* ------------------------------------------------------------------------- */
/*
void _delay_ms(uint8_t ms)
{
// delay function, tuned for 11.092 MHz clock
// optimized to assembler
ms; // keep compiler from complaining?
__asm;
; dpl contains ms param value
delay$:
mov b, #8 ; i
outer$:
mov a, #243 ; j
inner$:
djnz acc, inner$
djnz b, outer$
djnz dpl, delay$
__endasm;
}
*/
uint8_t count; // main loop counter
//uint8_t temp; // temperature sensor value
uint8_t lightval; // light sensor value
volatile uint8_t displaycounter;
volatile int8_t count_100;
volatile int16_t count_1000;
volatile int16_t count_5000;
volatile int16_t ntpUpdated; // time since last succ ntp update, sec
//volatile int8_t ntpTimout = 30;
#define ntpTimout 30
volatile int16_t count_20000;
volatile __bit blinker_slowest;
volatile uint16_t count_timeout; // max 6.5536 sec
#define TIMEOUT_LONG 0xFFFF
volatile __bit blinker_slow;
volatile __bit blinker_fast;
volatile __bit blinker1;
volatile __bit blinker_ntp;
volatile __bit loop_gate;
uint8_t dmode = M_NORMAL; // display mode state
uint8_t kmode = K_NORMAL;
__bit flash_01;
__bit flash_23;
uint8_t rtc_hh_bcd;
uint8_t rtc_mm_bcd;
uint8_t rtc_ss_bcd;
__bit rtc_pm;
#ifndef WITHOUT_ALARM
//~ uint8_t alarm_hh_bcd;
//~ uint8_t alarm_mm_bcd;
//~ __bit alarm_pm;
//~ __bit alarm_trigger;
//~ __bit alarm_reset;
#endif
__bit cfg_changed = 1;
volatile __bit S1_LONG;
volatile __bit S1_PRESSED;
volatile __bit S2_LONG;
volatile __bit S2_PRESSED;
#ifdef stc15w408as
volatile __bit S3_LONG;
volatile __bit S3_PRESSED;
#endif
volatile uint8_t debounce[NUM_SW]; // switch debounce buffer
volatile uint8_t switchcount[NUM_SW];
#define SW_CNTMAX 80
enum Event {
EV_NONE,
EV_S1_SHORT,
EV_S1_LONG,
EV_S2_SHORT,
EV_S2_LONG,
EV_S1S2_LONG,
#ifdef stc15w408as
EV_S3_SHORT,
EV_S3_LONG,
#endif
EV_TIMEOUT,
};
volatile enum Event event;
void timer0_isr() __interrupt 1 __using 1
{
uint8_t tmp;
enum Event ev = EV_NONE;
// display refresh ISR
// cycle thru digits one at a time
uint8_t digit = displaycounter % (uint8_t) 4;
// turn off all digits, set high
LED_DIGITS_OFF();
// auto dimming, skip lighting for some cycles
if (displaycounter % lightval < 4 ) {
// fill digits
LED_SEGMENT_PORT = dbuf[digit];
// turn on selected digit, set low
//LED_DIGIT_ON(digit);
// issue #32, fix for newer sdcc versions which are using non-atomic port access
tmp = ~((1<<LED_DIGITS_PORT_BASE) << digit);
LED_DIGITS_PORT &= tmp;
}
displaycounter++;
// 100/sec: 10 ms
if (count_100 == 100) {
count_100 = 0;
// 10/sec: 100 ms
if (count_1000 == 1000) {
count_1000 = 0;
blinker_fast = !blinker_fast;
loop_gate = 1;
// 2/sec: 500 ms
if (count_5000 == 5000) {
count_5000 = 0;
blinker_slow = !blinker_slow;
// 1/ 2sec: 2000 ms
if (count_20000 == 20000) {
ntpUpdated+=2;
if (ntpUpdated > 15000) { ntpUpdated = 15000;}// last ntp update time counter
count_20000 = 0;
}
// 500 ms on, 1500 ms off
blinker_slowest = count_20000 < 5000;
}
}
#define MONITOR_S(n) \
{ \
uint8_t s = n - 1; \
/* read switch positions into sliding 8-bit window */ \
debounce[s] = (debounce[s] << 1) | SW ## n ; \
if (debounce[s] == 0) { \
/* down for at least 8 ticks */ \
S ## n ## _PRESSED = 1; \
if (!S ## n ## _LONG) { \
switchcount[s]++; \
} \
} else { \
/* released or bounced */ \
if (S ## n ## _PRESSED) { \
if (!S ## n ## _LONG) { \
ev = EV_S ## n ## _SHORT; \
} \
S ## n ## _PRESSED = 0; \
S ## n ## _LONG = 0; \
switchcount[s] = 0; \
} \
} \
if (switchcount[s] > SW_CNTMAX) { \
S ## n ## _LONG = 1; \
switchcount[s] = 0; \
ev = EV_S ## n ## _LONG; \
} \
}
MONITOR_S(1);
MONITOR_S(2);
#ifdef stc15w408as
MONITOR_S(3);
#endif
if (ev == EV_S1_LONG && S2_PRESSED) {
S2_LONG = 1;
switchcount[1] = 0;
ev = EV_S1S2_LONG;
} else if (ev == EV_S2_LONG && S1_PRESSED) {
S1_LONG = 1;
switchcount[0] = 0;
ev = EV_S1S2_LONG;
}
if (event == EV_NONE) {
event = ev;
}
}
count_100++;
count_1000++;
count_5000++;
count_20000++;
if (count_timeout != 0) {
count_timeout--;
if (count_timeout == 0) {
if (event == EV_NONE) {
event = EV_TIMEOUT;
}
}
}
}
/*
// macro expansion for MONITOR_S(1)
{
uint8_t s = 1 - 1;
debounce[s] = (debounce[s] << 1) | SW1 ;
if (debounce[s] == 0) {
S_PRESSED = 1;
if (!S_LONG) {
switchcount[s]++;
}
} else {
if (S1_PRESSED) {
if (!S1_LONG) {
ev = EV_S1_SHORT;
}
S1_PRESSED = 0;
S1_LONG = 0;
switchcount[s] = 0;
}
}
if (switchcount[s] > SW_CNTMAX) {
S1_LONG = 1;
switchcount[s] = 0;
ev = EV_S1_LONG;
}
}
*/
// Call timer0_isr() 10000/sec: 0.0001 sec
// Initialize the timer count so that it overflows after 0.0001 sec
// THTL = 0x10000 - FOSC / 12 / 10000 = 0x10000 - 92.16 = 65444 = 0xFFA4
void Timer0Init(void) //100us @ 11.0592MHz
{
// refer to section 7 of datasheet: STC15F2K60S2-en2.pdf
// TMOD = 0; // default: 16-bit auto-reload
// AUXR = 0; // default: traditional 8051 timer frequency of FOSC / 12
// Initial values of TL0 and TH0 are stored in hidden reload registers: RL_TL0 and RL_TH0
TL0 = 0xA4; // Initial timer value
TH0 = 0xFF; // Initial timer value
TF0 = 0; // Clear overflow flag
TR0 = 1; // Timer0 start run
ET0 = 1; // Enable timer0 interrupt
EA = 1; // Enable global interrupt
}
// Formula was : 76-raw*64/637 - which makes use of integer mult/div routines
// Getting degF from degC using integer was not good as values were sometimes jumping by 2
// The floating point one is even worse in term of code size generated (>1024bytes...)
// Approximation for slope is 1/10 (64/637) - valid for a normal 20 degrees range
// & let's find some other trick (80 bytes - See also docs\Temp.ods file)
//~ int8_t gettemp(uint16_t raw) {
//~ uint16_t val=raw;
//~ uint8_t temp;
//~ raw<<=2;
//~ if (CONF_C_F) raw<<=1; // raw*5 (4+1) if Celcius, raw*9 (4*2+1) if Farenheit
//~ raw+=val;
//~ if (CONF_C_F) {val=6835; temp=32;} // equiv. to temp=xxxx-(9/5)*raw/10 i.e. 9*raw/50
//~ // see next - same for degF
//~ else {val=5*757; temp=0;} // equiv. to temp=xxxx-raw/10 or which is same 5*raw/50
//~ // at 25degC, raw is 512, thus 24 is 522 and limit between 24 and 25 is 517
//~ // so between 0deg and 1deg, limit is 517+24*10 = 757
//~ // (*5 due to previous adjustment of raw value)
//~ while (raw<val) {temp++; val-=50;}
//~ return temp + (cfg_table[CFG_TEMP_BYTE] & CFG_TEMP_MASK) - 4;
//~ }
//~ void dot3display(__bit pm)
//~ {
//~ #ifndef WITHOUT_ALARM
//~ // dot 3: If alarm is on, blink for 500 ms every 2000 ms
//~ // If 12h: on if pm when not blinking
//~ if (!H12_12) { // 24h
//~ pm = CONF_ALARM_ON && blinker_slowest && blinker_fast;
//~ } else if (CONF_ALARM_ON && blinker_slowest) {
//~ pm = blinker_fast;
//~ }
//~ #endif
//~ dotdisplay(3, pm);
//~ }
uint8_t hh = 0;
uint8_t mm = 0;
uint8_t ss = 0;
uint8_t ww = 0;
uint8_t tt = 0;
//~ uint8_t uu = 0;
uint8_t h0 = 0;
uint8_t pm = 0;
char btemp = 0;
char * pRec = 0;
volatile char tmp;
uint8_t i = 0;
volatile enum Event ev;
/*********************************************/
int main()
{
// SETUP
// set photoresistor & ntc pins to open-drain output
P1M1 |= (1<<ADC_LIGHT) | (1<<ADC_TEMP);
P1M0 |= (1<<ADC_LIGHT) | (1<<ADC_TEMP);
// init rtc
ds_init();
// init/read ram config
ds_ram_config_init();
// uncomment in order to reset minutes and hours to zero.. Should not need this.
//ds_reset_clock();
Timer0Init(); // display refresh & switch read
//~ P1M1 |= 0b00110000;
//~ P1M0 |= 0b00110000;
//~ LTI_0;
//~ LRI_0;
serial_init ();
SBUF = IE;
memset(buffer_t, 0, BSIZE);
memset(rec_data, 0, BSIZE);
//~ _delay_ms(200);
SendString("reset\n");
clear_rec_data();
blinker1 = blinker_slow;
blinker_ntp = blinker_fast;
// LOOP
while (1)
{
{
//~ while (!loop_gate); // wait for open
if (loop_gate) {
ev = event;
event = EV_NONE;
// sample adc, run frequently
if (count % (uint8_t) 4 == 0) {
//~ temp = gettemp(getADCResult(ADC_TEMP));
// auto-dimming, by dividing adc range into 8 steps
lightval = getADCResult8(ADC_LIGHT) >> 3;
// set floor of dimming range
if (lightval < 4) {
lightval = 4;
}
}
// Read RTC
ds_readburst();
// parse RTC
{
rtc_hh_bcd = rtc_table[DS_ADDR_HOUR];
if (H12_12) {
rtc_hh_bcd &= DS_MASK_HOUR12;
} else {
rtc_hh_bcd &= DS_MASK_HOUR24;
}
rtc_pm = H12_12 && H12_PM;
rtc_mm_bcd = rtc_table[DS_ADDR_MINUTES] & DS_MASK_MINUTES;
rtc_ss_bcd = rtc_table[DS_ADDR_SECONDS] & DS_MASK_MINUTES;
}
//loop_gate = 0; // close gate
//count++;
} // if (loop_gate)
}
//======
hh = rtc_hh_bcd;
mm = rtc_mm_bcd;
ss = rtc_ss_bcd;
if (RI){
tmp = SBUF;
RI = 0;
if (tmp != 0) {
rec_data[rec_num] = tmp;
if (rec_data[rec_num] == '*') { // " " = 32
rReady = 1;
for (i=0;i<BSIZE;i++) {
char * pRec = rec_data;
char btemp = *(pRec+i);
buffer_t[i] = btemp;
//~ SendData(intToChar(i));
//~ SendData(':');
//~ SendData(buffer_t[i]);
//~ SendData('&');
//~ SendData(rec_data[i]);
//~ SendData('\n');
rec_data[i] = 0;
}
rec_num = 0;
//strcpy(buffer_t,rec_data);
//SendData('+');
SendString(buffer_t);
}else {
rec_num++;
}
}
}
if (loop_gate) {
clearTmpDisplay();
if (rReady == 1) {
if ( (buffer_t[0]=='H') && (buffer_t[3]=='M') && (buffer_t[6]=='S')) {
nH = charToint(buffer_t[1], buffer_t[2]);
nM = charToint(buffer_t[4], buffer_t[5]);
nS = charToint(buffer_t[7], buffer_t[8]);
hh = intToBCD (nH);
ds_writebyte(DS_ADDR_HOUR, hh);
mm = intToBCD (nM);
ds_writebyte(DS_ADDR_MINUTES, mm);
ss = intToBCD (nS);
ds_writebyte(DS_ADDR_SECONDS, ds_int2bcd(nS));
ntpUpdated = 0;
SendData('+');
dotdisplay(1, blinker_fast);
}
if ( (buffer_t[0]=='W') && (buffer_t[3]=='T') && (buffer_t[6]=='U')) {
nW = charToint(buffer_t[1], buffer_t[2]);
nT = charToint(buffer_t[4], buffer_t[5]);
//nU = charToint(buffer_t[7], buffer_t[8]);
ww = intToBCD (nW);
tt = intToBCD (nT);
SendData('o');
//uu = intToBCD (nU);
}
rReady = 0;
}
//~ SendString(" ");
//~ SendString(ds_int2bcd(ntpUpdated));
//~ SendString(intTochar(mm));
//~ SendData('\n');
//~ //SendString(buffer_t);
//~ rReady = 0;
if (ntpUpdated>ntpTimout) {
blinker_ntp = blinker_fast;
dotdisplay(0, blinker_ntp);
} else {
blinker_ntp = blinker_slow;
}
// ===========
switch (kmode) {
case K_NORMAL:
if (ev == EV_S1_SHORT) {
kmode = K_TEMP_DISP;
dmode = M_TEMP_DISP;
}
break;
case K_TEMP_DISP:
if (count_timeout == 0) {
count_timeout = TIMEOUT_LONG;
}
if (ev == EV_S1_SHORT || ev == EV_TIMEOUT ) {
count_timeout = 0;
kmode = K_NORMAL;
dmode = M_NORMAL;
}
break;
}
if ( (kmode == K_TEMP_DISP) || (ss>=85) && (ss<=89) ) {
dmode = M_TEMP_DISP;
} else {
dmode = M_NORMAL;
}
switch (dmode) {
case M_NORMAL:
h0 = hh >> 4;
if (H12_12 && h0 == 0) {
h0 = LED_BLANK;
}
filldisplay(0, h0, 0);
filldisplay(1, hh & 0x0F, 0);
filldisplay(2, mm >> 4, 0);
filldisplay(3, mm & 0x0F, 0);
dotdisplay(1, blinker_slow);
dotdisplay(2, blinker_slow);
break;
case M_TEMP_DISP:
filldisplay(0, ww >> 4, 0);
filldisplay(1, ww & 0x0F, 0);
filldisplay(2, tt >> 4, 0);
filldisplay(3, tt & 0x0F, 0);
dotdisplay(2, 1);
break;
}
//~ h0 = hh >> 4;
//~ if (H12_12 && h0 == 0) {
//~ h0 = LED_BLANK;
//~ }
//~ filldisplay(0, h0, 0);
//~ filldisplay(1, hh & 0x0F, 0);
//~ filldisplay(2, mm >> 4, 0);
//~ filldisplay(3, mm & 0x0F, 0);
//~ dotdisplay(1, blinker_slow);
//~ dotdisplay(2, blinker_slow);
// ===========
__critical {
updateTmpDisplay();
}
WDT_CLEAR();
loop_gate = 0; // close gate
count++;
} // if (loop_gate) {
}
}
/* ------------------------------------------------------------------------- */
//~ void _delay_ms(uint8_t ms)
//~ {
//~ // i,j selected for fosc 11.0592MHz, using oscilloscope
//~ // the stc-isp tool gives inaccurate values (perhaps for C51 vs sdcc?)
//~ // max 255 ms
//~ uint8_t i, j;
//~ do {
//~ i = 4;
//~ j = 200;
//~ do
//~ {
//~ while (--j);
//~ } while (--i);
//~ } while (--ms);
//~ }
uint8_t intToBCD(uint8_t nn) {
uint8_t binaryInput = nn;
uint8_t bcdResult = 0;
uint8_t shift = 0;
while (binaryInput > 0) {
bcdResult |= (binaryInput % 10) << (shift++ << 2);
binaryInput /= 10;
}
return bcdResult;
}
char intToChar (uint8_t n){
if (n<10) {
return n+48;
}
if ( (n>=10) && (n<=15) ) {
return (n-10)+65;
}
return '!';
}
uint8_t charToint (char h, char l){
return ( (h-0x30)*10 ) + (l-0x30);
}
/*----------------------------
UART
-----------------------------*/
void UART1_Routine(void) __interrupt 4 __using 1
{
//~ if (RI){
//~ RI = 0;
//~ tmp = SBUF;
//~ //SBUF = tmp;
//~ if (!rReady && (tmp != 0) ) {
//~ rec_data[rec_num] = tmp;
//~ if (rec_data[rec_num] == '*') { // " " = 32
//~ rReady = 1;
//~ }
//~ rec_num++;
//~ }
//~ }
if (TI){
TI = 0; //Clear transmit interrupt flag
busy = 0; //Clear transmit busy flag
}
//~ if (RI){
//~ LRI_1;
//~ } else {
//~ LRI_0;
//~ }
//~ if (TI){
//~ LTI_1;
//~ } else {
//~ LTI_0;
//~ }
}
void clear_rec_data()
{
memset(rec_data, 0, sizeof(rec_data));
rec_num = 0;
}
/*----------------------------Send a byte data to UART
Input: dat (data to be sent)
Output:None
* https://github.com/dylqt/Embedded/blob/master/project_indy/stc15_uart.c
----------------------------*/
void SendData(unsigned char dat)
{
while (busy); //Wait for the completion of the previous data is sent
ACC = dat; //Calculate the even parity bit P (PSW.0)
busy = 1;
SBUF = ACC; //Send data to UART buffer
}
/*----------------------------Send a string to UART
Input: s (address of string)
Output:None
----------------------------*/
void SendString(char *s)
{
while (*s) //Check the end of the string
{
SendData(*s++); //Send current char and increment string ptr
}
}
void serial_init (){
// ACC = P_SW1;
// ACC &= ~(S1_S0 | S1_S1); //S1_S0=0 S1_S1=0
// P_SW1 = ACC; //(P3.0/RxD, P3.1/TxD)
ACC = P_SW1;
ACC &= ~(S1_S0 | S1_S1); //S1_S0=1 S1_S1=0
ACC |= S1_S0; //(P3.6/RxD_2, P3.7/TxD_2)
P_SW1 = ACC;
//AUXR1 = 0b10000000;
//
// ACC = P_SW1;
// ACC &= ~(S1_S0 | S1_S1); //S1_S0=0 S1_S1=1
// ACC |= S1_S1; //(P1.6/RxD_3, P1.7/TxD_3)
// P_SW1 = ACC;
#if (PARITYBIT == NONE_PARITY)
SCON = 0x50;
#elif (PARITYBIT == ODD_PARITY) || (PARITYBIT == EVEN_PARITY) || (PARITYBIT == MARK_PARITY)
SCON = 0xda;
#elif (PARITYBIT == SPACE_PARITY)
SCON = 0xd2;
#endif
T2L = ( (uint8_t)(65536-(FOSC/BAUD/4)) & 0xFF);
T2H = (65536 - (FOSC/4/BAUD))>>8;
AUXR = 0x14;
AUXR |= 0x01;
//AUXR |= 0b00001001; // STC15-English.pdf p560 B4 - T2R:Timer 2 Run control bit (1 : run Timer 2)
//
EA = 1;
ES = 1;
RI = 0;
TI = 0;
}
| 2.171875 | 2 |
2024-11-18T22:23:47.099441+00:00 | 2016-10-16T12:29:16 | 800bc8b3d32d724badd0cac27272f346b6e2c7e4 | {
"blob_id": "800bc8b3d32d724badd0cac27272f346b6e2c7e4",
"branch_name": "refs/heads/master",
"committer_date": "2016-10-16T12:29:16",
"content_id": "d47ceac3df98cef93fa52e085d8fc990cf831483",
"detected_licenses": [
"MIT"
],
"directory_id": "f0ef73f7f2cf357902c1e229e21d75dfd3424763",
"extension": "c",
"filename": "push_swap.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 71048630,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 875,
"license": "MIT",
"license_type": "permissive",
"path": "/src/push_swap.c",
"provenance": "stackv2-0115.json.gz:72093",
"repo_name": "KASOGIT/pushswap",
"revision_date": "2016-10-16T12:29:16",
"revision_id": "109da562369de3f99e2bbec43bb431a4d7702d2e",
"snapshot_id": "f1d092295519d7ae74dd80f8a9c385e36d973d97",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/KASOGIT/pushswap/109da562369de3f99e2bbec43bb431a4d7702d2e/src/push_swap.c",
"visit_date": "2021-01-11T03:20:06.454754"
} | stackv2 | /*
** pushswap.c for pushswap in /home/soto_a/rendu/CPE_2014_Pushswap
**
** Made by Kaso Soto
** Login <soto_a@epitech.net>
**
** Started on Mon Dec 1 14:27:31 2014 Kaso Soto
** Last update Sat Dec 13 18:56:04 2014 Kaso Soto
*/
#include "push_swap.h"
int main(int ac, char **av)
{
t_list *l_a;
t_list *l_b;
int print;
l_a = NULL;
l_b = NULL;
if (ac > 1)
{
((av[1][0] == '-') && (av[1][1] == 'v')) ? (print = 1) : (print = 0);
my_check_only_number(av + print);
my_check_duplicates(av + print);
my_init_list(&l_a);
my_init_list(&l_b);
my_create_list_a(&(l_a), av + print, ac);
if (my_list_is_increasing(l_a) != 1)
my_sort_list(&l_a, &l_b, print);
my_free_list(&l_a);
my_free_list(&l_b);
}
else
my_putstr("Not enough arguments");
if (print != 1)
my_putchar('\n');
return (0);
}
| 2.890625 | 3 |
2024-11-18T22:23:47.184667+00:00 | 2017-06-11T22:44:34 | 03c4e83bdf9f21be7ded9bbba55ab1bafd6ba202 | {
"blob_id": "03c4e83bdf9f21be7ded9bbba55ab1bafd6ba202",
"branch_name": "refs/heads/master",
"committer_date": "2017-06-11T22:44:34",
"content_id": "16295401437c859489a918ab807722b89ef02a8a",
"detected_licenses": [
"MIT"
],
"directory_id": "9d09ec2dd19c8f6181d35fb848502e2d15bbe71a",
"extension": "c",
"filename": "cadu.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 91852849,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 24579,
"license": "MIT",
"license_type": "permissive",
"path": "/cadu.c",
"provenance": "stackv2-0115.json.gz:72223",
"repo_name": "cadubentzen/audio-compression",
"revision_date": "2017-06-11T22:44:34",
"revision_id": "bfe5f3c810a0cff9f0a7051adab3bfcb4ac2ae14",
"snapshot_id": "7ea1cbe6356a538aec2a3af3b0a9b029cdb8eb70",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/cadubentzen/audio-compression/bfe5f3c810a0cff9f0a7051adab3bfcb4ac2ae14/cadu.c",
"visit_date": "2021-01-21T15:37:36.308820"
} | stackv2 | #include "cadu.h"
void read_aiff_file ( char *aiff_input_path, float ***samples, uint64_t *nSamples,
uint16_t *channels, double *samplingRate, uint16_t *bitsPerSample )
{
AIFF_Ref ref;
int channels_int;
int bitsPerSample_int;
int segmentSize;
float *samples_total;
uint64_t i;
uint16_t j;
#if DEBUG
char sample_name[30];
FILE *testFile;
#endif
printf( "Opening AIFF input file... " );
ref = AIFF_OpenFile( aiff_input_path, F_RDONLY );
if ( !ref )
{
fprintf( stderr, "Error opening AIFF input file.\n" );
AIFF_CloseFile(ref);
exit(EXIT_FAILURE);
}
printf( "DONE\n" );
printf( "Getting Audio Format info... " );
if ( AIFF_GetAudioFormat( ref, nSamples, &channels_int,
samplingRate, &bitsPerSample_int,
&segmentSize ) < 1 )
{
fprintf( stderr, "Error getting audio format info.\n" );
AIFF_CloseFile(ref);
exit(EXIT_FAILURE);
}
printf( "DONE\n\n" );
*channels = (uint16_t) channels_int;
*bitsPerSample = (uint16_t) bitsPerSample_int;
printf( "aiff_input_path = %s\n", aiff_input_path );
printf("nSamples = %" PRIu64 "\n", *nSamples);
printf( "channels = %" PRIu16 "\n", *channels );
printf( "samplingRate = %.2f\n", *samplingRate );
printf( "bitsPerSample = %" PRIu16 "\n\n", *bitsPerSample );
printf( "Reading samples from input audio file... " );
samples_total = (float*) malloc( sizeof(float) * (*nSamples) * (*channels) );
if( AIFF_ReadSamplesFloat( ref, samples_total, (*nSamples) * (*channels) ) < 1 )
{
fprintf( stderr, "Error getting audio samples.\n" );
AIFF_CloseFile(ref);
exit(EXIT_FAILURE);
}
printf( "DONE\n" );
printf( "Transfering channels to different arrays... " );
*samples = (float**) malloc( sizeof(float*) * (*channels) );
for ( j = 0; j < *channels; ++j )
(*samples)[j] = (float*) fftwf_malloc( sizeof(float) * (*nSamples) );
for ( i = 0; i < *nSamples; ++i )
for ( j = 0; j < *channels; ++j )
{
(*samples)[j][i] = samples_total[ i*(*channels) + j ];
// printf("%f\n", samples[j][i]);
}
printf( "DONE\n" );
printf("\n");
#if DEBUG
printf("\
############################\n\
Testing read_aiff_file()\n\
############################\n\n"
);
for ( j = 0; j < *channels; ++j )
{
sprintf( sample_name, "test_sample_channel_%" PRIu16 ".dat", j );
printf( "Writing channel %" PRIu16 " to file %s... ", j, sample_name );
testFile = fopen( sample_name, "w" );
if ( testFile == NULL )
{
fprintf( stderr, "Error opening %s\n", sample_name );
exit(EXIT_FAILURE);
}
for ( i = 0; i < *nSamples; ++i )
fprintf( testFile, "%f\n", (*samples)[j][i] );
printf( "DONE\n" );
fclose(testFile);
}
printf("\nTest read_aiff_file() OK\n\n");
#endif
AIFF_CloseFile(ref);
free(samples_total);
}
void calc_channels_fft ( float **samples, complex_int32 ***ffts,
uint64_t nSamples, uint16_t channels )
{
fftwf_complex *out;
fftwf_plan p;
uint16_t i;
uint64_t j;
#if DEBUG
char sample_name[30];
FILE *testFile;
#endif
printf( "Calculating FFTs... " );
out = (fftwf_complex*) fftwf_malloc( sizeof(fftwf_complex) * (nSamples/2 + 1) );
*ffts = (complex_int32**) malloc( sizeof(complex_int32*) * channels);
for (i = 0; i < channels; ++i)
{
(*ffts)[i] = (complex_int32*) malloc( sizeof(complex_int32) * (nSamples/2 + 1) );
p = fftwf_plan_dft_r2c_1d( nSamples, samples[i], out, FFTW_ESTIMATE );
fftwf_execute(p);
for ( j = 0; j < (nSamples/2 + 1); ++j )
{
(*ffts)[i][j].a = (int32_t) out[j][0];
(*ffts)[i][j].b = (int32_t) out[j][1];
}
fftwf_destroy_plan(p);
}
printf( "DONE\n" );
#if DEBUG
printf("\
###############################\n\
Testing calc_channels_fft()\n\
###############################\n\n"
);
for ( i = 0; i < channels; ++i )
{
sprintf( sample_name, "test_fft_channel_%" PRIu16 ".dat", i );
printf( "Writing FFT magnitude of channel %" PRIu16 " to %s... ", i, sample_name );
testFile = fopen(sample_name, "w");
if ( testFile == NULL )
{
fprintf(stderr, "Error opening file %s.\n", sample_name);
exit(EXIT_FAILURE);
}
for ( j = 0; j < (nSamples/2 + 1); ++j )
{
fprintf( testFile, "%" PRIu32 "\n",
(uint32_t) sqrt( (*ffts)[i][j].a * (*ffts)[i][j].a +
(*ffts)[i][j].b * (*ffts)[i][j].b ) );
}
printf( "DONE\n" );
fclose(testFile);
}
#endif
printf("\n");
}
void crop_ffts ( complex_int32 **ffts, uint64_t **num_terms, uint16_t percentage,
uint64_t nSamples, uint16_t channels )
{
uint64_t sum, j, sum_percentage;
uint16_t i;
*num_terms = malloc( sizeof(uint64_t) * channels );
#if DEBUG
printf("Computing number of FFT terms for preservation of %u%% original area...\n", percentage);
#else
printf("Computing number of FFT terms for preservation of %u%% original area... ", percentage);
#endif
for ( i = 0; i < channels; ++i )
{
sum = 0;
for ( j = 0; j < (nSamples/2 + 1); ++j )
sum += (uint32_t) sqrt( ffts[i][j].a * ffts[i][j].a +
ffts[i][j].b * ffts[i][j].b );
sum_percentage = (sum/100) * percentage;
#if DEBUG
printf("sum for channel %" PRIu16 " = %" PRIu64 "\n", i, sum);
printf("sum_percentage for channel %" PRIu16 " = %" PRIu64 "\n", i, sum_percentage);
#endif
sum = 0;
for ( j = 0; j < (nSamples/2 + 1); ++j )
{
sum += (uint32_t) sqrt( ffts[i][j].a * ffts[i][j].a +
ffts[i][j].b * ffts[i][j].b );
if ( sum > sum_percentage )
{
#if DEBUG
printf("sum that reaches sum_percentage = %" PRIu64 "\n", sum);
#endif
(*num_terms)[i] = j;
break;
}
}
}
#if !DEBUG
printf( "DONE\n" );
#endif
printf("\n");
#if DEBUG
printf("\
###############################\n\
Testing crop_ffts()\n\
###############################\n\n"
);
for ( i = 0; i < channels; ++i )
{
printf( "Number of terms for channel %" PRIu16 ": %" PRIu64 " / %" PRIu64 " (%.2f%% of original terms)\n",
i, (*num_terms)[i], (nSamples/2 + 1), 100*((double)(*num_terms)[i])/(nSamples/2 + 1) );
}
printf("\nTest crop_ffts() OK\n\n");
#endif
}
void discretize_ffts_int16 ( complex_int32 **ffts, complex_int16 ***ffts16, int32_t **max_terms,
uint64_t *num_terms, uint64_t nSamples, uint16_t channels )
{
uint16_t i;
uint64_t j;
int32_t max_aux, aux;
#if DEBUG
char sample_name[40];
FILE *testFile;
#endif
printf("Discretizing FFTs to 8 bits... ");
// Allocate memory
*ffts16 = (complex_int16**) malloc( sizeof(complex_int16*) * channels );
*max_terms = (int32_t*) malloc( sizeof(int32_t) * channels );
for ( i = 0; i < channels; ++i )
{
(*ffts16)[i] = (complex_int16*) malloc( sizeof(complex_int16) * num_terms[i] );
max_aux = 0;
for ( j = 0; j < num_terms[i]; ++j)
{
aux = magnitude_complex_int32( ffts[i][j] );
if ( aux > max_aux ) max_aux = aux;
}
(*max_terms)[i] = max_aux;
}
// Populate ffts8
for ( i = 0; i < channels; ++i )
{
for ( j = 0; j < num_terms[i]; ++j)
{
(*ffts16)[i][j].a = (int16_t) ( INT16_MAX * ( ( (float) ffts[i][j].a ) / (*max_terms)[i] ) );
(*ffts16)[i][j].b = (int16_t) ( INT16_MAX * ( ( (float) ffts[i][j].b ) / (*max_terms)[i] ) );
}
}
printf("DONE\n");
#if DEBUG
printf("\
###############################\n\
Testing discretize_ffts()\n\
###############################\n\n"
);
for ( i = 0; i < channels; ++i )
{
sprintf( sample_name, "test_fft_discrete_channel_%" PRIu16 ".dat", i );
printf( "Writing FFT magnitude of channel %" PRIu16 " to %s... ", i, sample_name );
testFile = fopen(sample_name, "w");
if ( testFile == NULL )
{
fprintf(stderr, "Error opening file %s.\n", sample_name);
exit(EXIT_FAILURE);
}
for ( j = 0; j < (nSamples/2 + 1); ++j )
{
if(j < num_terms[i])
{
fprintf( testFile, "%" PRIu32 "\n",
(uint32_t) sqrt( (*ffts16)[i][j].a * (*ffts16)[i][j].a +
(*ffts16)[i][j].b * (*ffts16)[i][j].b ) );
}
else {
fprintf( testFile, "0\n");
}
}
printf( "DONE\n" );
fclose(testFile);
}
#endif
printf("\n");
}
void discretize_ffts_int8 ( complex_int32 **ffts, complex_int8 ***ffts8, int32_t **max_terms,
uint64_t *num_terms, uint64_t nSamples, uint16_t channels )
{
uint16_t i;
uint64_t j;
int32_t max_aux, aux;
#if DEBUG
char sample_name[40];
FILE *testFile;
#endif
printf("Discretizing FFTs to 8 bits... ");
// Allocate memory
*ffts8 = (complex_int8**) malloc( sizeof(complex_int8*) * channels );
*max_terms = (int32_t*) malloc( sizeof(int32_t) * channels );
for ( i = 0; i < channels; ++i )
{
(*ffts8)[i] = (complex_int8*) malloc( sizeof(complex_int8) * num_terms[i] );
max_aux = 0;
for ( j = 0; j < num_terms[i]; ++j)
{
aux = magnitude_complex_int32( ffts[i][j] );
if ( aux > max_aux ) max_aux = aux;
}
(*max_terms)[i] = max_aux;
}
// Populate ffts8
for ( i = 0; i < channels; ++i )
{
for ( j = 0; j < num_terms[i]; ++j)
{
(*ffts8)[i][j].a = (int8_t) ( INT8_MAX * ( ( (float) ffts[i][j].a ) / (*max_terms)[i] ) );
(*ffts8)[i][j].b = (int8_t) ( INT8_MAX * ( ( (float) ffts[i][j].b ) / (*max_terms)[i] ) );
}
}
printf("DONE\n");
#if DEBUG
printf("\
###############################\n\
Testing discretize_ffts()\n\
###############################\n\n"
);
for ( i = 0; i < channels; ++i )
{
sprintf( sample_name, "test_fft_discrete_channel_%" PRIu16 ".dat", i );
printf( "Writing FFT magnitude of channel %" PRIu16 " to %s... ", i, sample_name );
testFile = fopen(sample_name, "w");
if ( testFile == NULL )
{
fprintf(stderr, "Error opening file %s.\n", sample_name);
exit(EXIT_FAILURE);
}
for ( j = 0; j < (nSamples/2 + 1); ++j )
{
if(j < num_terms[i])
{
fprintf( testFile, "%" PRIu32 "\n",
(uint32_t) sqrt( (*ffts8)[i][j].a * (*ffts8)[i][j].a +
(*ffts8)[i][j].b * (*ffts8)[i][j].b ) );
}
else {
fprintf( testFile, "0\n");
}
}
printf( "DONE\n" );
fclose(testFile);
}
#endif
printf("\n");
}
void write_cadu_file_int32 ( char *cadu_output_path, complex_int32 **ffts, uint64_t *num_terms, uint64_t nSamples,
uint16_t channels, double samplingRate, uint16_t bitsPerSample )
{
uint16_t i;
FILE *caduFile;
caduFile = fopen( cadu_output_path, "wb" );
if ( caduFile == NULL )
{
fprintf( stderr, "Error opening CADU output file %s.\n", cadu_output_path );
exit(EXIT_FAILURE);
}
printf("Writing header to CADU file... ");
fwrite( &nSamples, sizeof(uint64_t), 1, caduFile );
fwrite( &samplingRate, sizeof(double), 1, caduFile );
fwrite( &bitsPerSample, sizeof(uint16_t), 1, caduFile );
fwrite( &channels, sizeof(uint16_t), 1, caduFile );
printf( "DONE\n" );
printf("Writing body to CADU file... ");
for ( i = 0; i < channels; ++i )
{
fwrite( num_terms+i, sizeof(uint64_t), 1, caduFile );
fwrite( ffts[i], sizeof(complex_int32), num_terms[i], caduFile );
}
printf( "DONE\n" );
fclose(caduFile);
printf("\n");
}
void write_cadu_file_int16 ( char *cadu_output_path, complex_int16 **ffts16, uint64_t *num_terms, int32_t *max_terms,
uint64_t nSamples, uint16_t channels, double samplingRate, uint16_t bitsPerSample )
{
uint16_t i;
FILE *caduFile;
caduFile = fopen( cadu_output_path, "wb" );
if ( caduFile == NULL )
{
fprintf( stderr, "Error opening CADU output file %s.\n", cadu_output_path );
exit(EXIT_FAILURE);
}
printf("Writing header to CADU file... ");
fwrite( &nSamples, sizeof(uint64_t), 1, caduFile );
fwrite( &samplingRate, sizeof(double), 1, caduFile );
fwrite( &bitsPerSample, sizeof(uint16_t), 1, caduFile );
fwrite( &channels, sizeof(uint16_t), 1, caduFile );
printf( "DONE\n" );
printf("Writing body to CADU file... ");
for ( i = 0; i < channels; ++i )
{
fwrite( num_terms+i, sizeof(uint64_t), 1, caduFile );
fwrite( max_terms+i, sizeof(int32_t), 1, caduFile );
fwrite( ffts16[i], sizeof(complex_int16), num_terms[i], caduFile );
}
printf( "DONE\n" );
fclose(caduFile);
printf("\n");
}
void write_cadu_file_int8 ( char *cadu_output_path, complex_int8 **ffts8, uint64_t *num_terms, int32_t *max_terms,
uint64_t nSamples, uint16_t channels, double samplingRate, uint16_t bitsPerSample )
{
uint16_t i;
FILE *caduFile;
caduFile = fopen( cadu_output_path, "wb" );
if ( caduFile == NULL )
{
fprintf( stderr, "Error opening CADU output file %s.\n", cadu_output_path );
exit(EXIT_FAILURE);
}
printf("Writing header to CADU file... ");
fwrite( &nSamples, sizeof(uint64_t), 1, caduFile );
fwrite( &samplingRate, sizeof(double), 1, caduFile );
fwrite( &bitsPerSample, sizeof(uint16_t), 1, caduFile );
fwrite( &channels, sizeof(uint16_t), 1, caduFile );
printf( "DONE\n" );
printf("Writing body to CADU file... ");
for ( i = 0; i < channels; ++i )
{
fwrite( num_terms+i, sizeof(uint64_t), 1, caduFile );
fwrite( max_terms+i, sizeof(int32_t), 1, caduFile );
fwrite( ffts8[i], sizeof(complex_int8), num_terms[i], caduFile );
}
printf( "DONE\n" );
fclose(caduFile);
printf("\n");
}
void read_cadu_file_int32 ( char *cadu_input_path, complex_int32 ***ffts, uint64_t *nSamples,
uint16_t *channels, double *samplingRate, uint16_t *bitsPerSample )
{
FILE *caduFile;
#if DEBUG
char fft_filename[40];
FILE *fftFile;
uint64_t j;
#endif
uint64_t num_terms;
uint16_t i;
caduFile = fopen( cadu_input_path, "rb" );
if ( caduFile == NULL )
{
fprintf( stderr, "Error opening CADU input file %s.\n", cadu_input_path );
exit(EXIT_FAILURE);
}
printf("Reading header of CADU file... ");
fread( nSamples, sizeof(uint64_t), 1, caduFile );
fread( samplingRate, sizeof(double), 1, caduFile );
fread( bitsPerSample, sizeof(uint16_t), 1, caduFile );
fread( channels, sizeof(uint16_t), 1, caduFile );
printf( "DONE\n" );
#if DEBUG
printf( "\ncadu_input_path = %s\n", cadu_input_path );
printf( "nSamples = %llu\n", *nSamples );
printf( "samplingRate = %f\n", *samplingRate );
printf( "bitsPerSample = %u\n", *bitsPerSample );
printf( "channels = %u\n", *channels );
#endif
printf("Reading body of CADU file... ");
*ffts = (complex_int32**) malloc( sizeof(complex_int32*) * (*channels) );
for ( i = 0; i < *channels; ++i )
{
(*ffts)[i] = (complex_int32*) malloc( sizeof(complex_int32) * ((*nSamples)/2 + 1) );
memset( (*ffts)[i], 0, sizeof(complex_int32) * ((*nSamples)/2 + 1) );
fread( &num_terms, sizeof(uint64_t), 1, caduFile );
fread( (*ffts)[i], sizeof(complex_int32), num_terms, caduFile );
#if DEBUG
sprintf( fft_filename, "test_fft_uncompressed_ch_%u.dat", i);
printf("Writing FFT to %s...\n", fft_filename);
fftFile = fopen( fft_filename, "w" );
for ( j = 0; j < ((*nSamples)/2 + 1); ++j )
{
fprintf( fftFile, "%u\n",
(uint32_t) sqrt( (*ffts)[i][j].a * (*ffts)[i][j].a +
(*ffts)[i][j].b * (*ffts)[i][j].b ) );
}
fclose(fftFile);
#endif
}
printf( "DONE\n" );
printf( "\n" );
fclose(caduFile);
}
void read_cadu_file_int16 ( char *cadu_input_path, complex_int32 ***ffts, uint64_t *nSamples,
uint16_t *channels, double *samplingRate, uint16_t *bitsPerSample )
{
FILE *caduFile;
complex_int16 **ffts16;
int32_t max_term;
#if DEBUG
char fft_filename[40];
FILE *fftFile;
#endif
uint64_t num_terms, j;
uint16_t i;
caduFile = fopen( cadu_input_path, "rb" );
if ( caduFile == NULL )
{
fprintf( stderr, "Error opening CADU input file %s.\n", cadu_input_path );
exit(EXIT_FAILURE);
}
printf("Reading header of CADU file... ");
fread( nSamples, sizeof(uint64_t), 1, caduFile );
fread( samplingRate, sizeof(double), 1, caduFile );
fread( bitsPerSample, sizeof(uint16_t), 1, caduFile );
fread( channels, sizeof(uint16_t), 1, caduFile );
printf( "DONE\n" );
ffts16 = (complex_int16**) malloc( sizeof(complex_int16*) * (*channels) );
#if DEBUG
printf( "\ncadu_input_path = %s\n", cadu_input_path );
printf( "nSamples = %llu\n", *nSamples );
printf( "samplingRate = %f\n", *samplingRate );
printf( "bitsPerSample = %u\n", *bitsPerSample );
printf( "channels = %u\n", *channels );
printf("Reading body of CADU file...\n");
#else
printf("Reading body of CADU file... ");
#endif
*ffts = (complex_int32**) malloc( sizeof(complex_int32*) * (*channels) );
for ( i = 0; i < *channels; ++i )
{
(*ffts)[i] = (complex_int32*) malloc( sizeof(complex_int32) * ((*nSamples)/2 + 1) );
memset( (*ffts)[i], 0, sizeof(complex_int32) * ((*nSamples)/2 + 1) );
fread( &num_terms, sizeof(uint64_t), 1, caduFile );
ffts16[i] = (complex_int16*) malloc( sizeof(complex_int16) * num_terms );
fread( &max_term, sizeof(int32_t), 1, caduFile );
fread( ffts16[i], sizeof(complex_int16), num_terms, caduFile );
for ( j = 0; j < num_terms; ++j )
{
(*ffts)[i][j].a = (int32_t) ( ffts16[i][j].a * ( ( (float) max_term ) / INT16_MAX ) );
(*ffts)[i][j].b = (int32_t) ( ffts16[i][j].b * ( ( (float) max_term ) / INT16_MAX ) );
}
free( ffts16[i] );
#if DEBUG
sprintf( fft_filename, "test_fft_uncompressed_ch_%u.dat", i);
printf("Writing FFT to %s...\n", fft_filename);
fftFile = fopen( fft_filename, "w" );
for ( j = 0; j < ((*nSamples)/2 + 1); ++j )
{
fprintf( fftFile, "%u\n",
(uint32_t) sqrt( (*ffts)[i][j].a * (*ffts)[i][j].a +
(*ffts)[i][j].b * (*ffts)[i][j].b ) );
}
fclose(fftFile);
#endif
}
printf( "DONE\n" );
printf( "\n" );
free(ffts16);
fclose(caduFile);
}
void read_cadu_file_int8 ( char *cadu_input_path, complex_int32 ***ffts, uint64_t *nSamples,
uint16_t *channels, double *samplingRate, uint16_t *bitsPerSample )
{
FILE *caduFile;
complex_int8 **ffts8;
int32_t max_term;
#if DEBUG
char fft_filename[40];
FILE *fftFile;
#endif
uint64_t num_terms, j;
uint16_t i;
caduFile = fopen( cadu_input_path, "rb" );
if ( caduFile == NULL )
{
fprintf( stderr, "Error opening CADU input file %s.\n", cadu_input_path );
exit(EXIT_FAILURE);
}
printf("Reading header of CADU file... ");
fread( nSamples, sizeof(uint64_t), 1, caduFile );
fread( samplingRate, sizeof(double), 1, caduFile );
fread( bitsPerSample, sizeof(uint16_t), 1, caduFile );
fread( channels, sizeof(uint16_t), 1, caduFile );
printf( "DONE\n" );
ffts8 = (complex_int8**) malloc( sizeof(complex_int8*) * (*channels) );
#if DEBUG
printf( "\ncadu_input_path = %s\n", cadu_input_path );
printf( "nSamples = %llu\n", *nSamples );
printf( "samplingRate = %f\n", *samplingRate );
printf( "bitsPerSample = %u\n", *bitsPerSample );
printf( "channels = %u\n", *channels );
printf("Reading body of CADU file...\n");
#else
printf("Reading body of CADU file... ");
#endif
*ffts = (complex_int32**) malloc( sizeof(complex_int32*) * (*channels) );
for ( i = 0; i < *channels; ++i )
{
(*ffts)[i] = (complex_int32*) malloc( sizeof(complex_int32) * ((*nSamples)/2 + 1) );
memset( (*ffts)[i], 0, sizeof(complex_int32) * ((*nSamples)/2 + 1) );
fread( &num_terms, sizeof(uint64_t), 1, caduFile );
ffts8[i] = (complex_int8*) malloc( sizeof(complex_int8) * num_terms );
fread( &max_term, sizeof(int32_t), 1, caduFile );
fread( ffts8[i], sizeof(complex_int8), num_terms, caduFile );
for ( j = 0; j < num_terms; ++j )
{
(*ffts)[i][j].a = (int32_t) ( ffts8[i][j].a * ( ( (float) max_term ) / INT8_MAX ) );
(*ffts)[i][j].b = (int32_t) ( ffts8[i][j].b * ( ( (float) max_term ) / INT8_MAX ) );
}
free( ffts8[i] );
#if DEBUG
sprintf( fft_filename, "test_fft_uncompressed_ch_%u.dat", i);
printf("Writing FFT to %s...\n", fft_filename);
fftFile = fopen( fft_filename, "w" );
for ( j = 0; j < ((*nSamples)/2 + 1); ++j )
{
fprintf( fftFile, "%u\n",
(uint32_t) sqrt( (*ffts)[i][j].a * (*ffts)[i][j].a +
(*ffts)[i][j].b * (*ffts)[i][j].b ) );
}
fclose(fftFile);
#endif
}
printf( "DONE\n" );
printf( "\n" );
free(ffts8);
fclose(caduFile);
}
void inverse_fft ( complex_int32 **ffts, float ***samples, uint64_t nSamples, uint16_t channels )
{
fftwf_complex *in;
fftwf_plan p;
uint16_t i;
uint64_t j;
#if DEBUG
char sample_filename[40];
FILE *sampleFile;
printf("Computing inverse FFTs...\n");
#else
printf("Computing inverse FFTs... ");
#endif
*samples = (float**) malloc( sizeof(float*) * channels );
for ( i = 0; i < channels; ++i )
{
in = (fftwf_complex*) fftwf_malloc( sizeof(fftwf_complex) * (nSamples/2 + 1) );
for ( j = 0; j < (nSamples/2 + 1); ++j )
{
in[j][0] = (float) ffts[i][j].a;
in[j][1] = (float) ffts[i][j].b;
}
(*samples)[i] = (float*) fftwf_malloc( sizeof(float) * nSamples );
p = fftwf_plan_dft_c2r_1d( nSamples, in, (*samples)[i], FFTW_ESTIMATE );
fftwf_execute(p);
fftwf_destroy_plan(p);
fftwf_free(in);
#if DEBUG
sprintf( sample_filename, "test_sample_uncompressed_ch_%u.dat", i );
printf("Writing samples to %s\n", sample_filename);
sampleFile = fopen( sample_filename, "w" );
#endif
for ( j = 0; j < nSamples; ++j )
{
(*samples)[i][j] /= nSamples;
#if DEBUG
fprintf( sampleFile, "%f\n", (*samples)[i][j] );
#endif
}
#if DEBUG
fclose(sampleFile);
#endif
}
printf( "DONE\n" );
printf("\n");
}
void convert_to_write_format ( float **samples, int32_t **samples_final,
uint64_t nSamples, uint16_t channels )
{
uint16_t i;
uint64_t j;
printf("Converting samples to writing format... ");
*samples_final = (int32_t*) malloc( sizeof(int32_t) * nSamples * channels );
for ( i = 0; i < channels; ++i )
for ( j = 0; j < nSamples; ++j )
(*samples_final)[ j*channels + i ] = (int32_t) (INT32_MAX * samples[i][j]);
printf( "DONE\n" );
}
void write_aiff_file ( char *aiff_output_path, int32_t *samples_final, uint64_t nSamples,
uint16_t channels, double samplingRate, uint16_t bitsPerSample )
{
AIFF_Ref ref;
printf("Opening output AIFF file... ");
ref = AIFF_OpenFile(aiff_output_path, F_WRONLY);
if ( !ref )
{
fprintf( stderr, "Error opening AIFF output file.\n" );
AIFF_CloseFile(ref);
exit(EXIT_FAILURE);
}
printf( "DONE\n" );
printf("Setting output AIFF format... ");
if ( AIFF_SetAudioFormat( ref, (int) channels, samplingRate, (int) bitsPerSample ) < 1 )
{
fprintf( stderr, "Error setting AIFF output format.\n");
AIFF_CloseFile(ref);
exit(EXIT_FAILURE);
}
printf( "DONE\n" );
printf("Writing samples to AIFF output file... ");
if ( AIFF_StartWritingSamples(ref) < 1 )
{
fprintf( stderr, "Error starting writing samples in output.\n" );
AIFF_CloseFile(ref);
exit(EXIT_FAILURE);
}
if ( AIFF_WriteSamples32Bit(ref, samples_final, nSamples * channels) < 1 )
{
fprintf( stderr, "Error writing samples to output.\n" );
AIFF_CloseFile(ref);
exit(EXIT_FAILURE);
}
if( AIFF_EndWritingSamples(ref) < 1 )
{
fprintf( stderr, "Error ending writing samples in output.\n" );
}
printf( "DONE\n" );
printf("\n");
AIFF_CloseFile(ref);
}
int32_t magnitude_complex_int32 ( complex_int32 complex_number )
{
int32_t magnitude = (int32_t) sqrt( complex_number.a * complex_number.a +
complex_number.b * complex_number.b );
return magnitude;
}
void free_arrays ( float **samples, complex_int32 **ffts, complex_int16 **ffts16, complex_int8 **ffts8,
int32_t *samples_final, uint64_t *num_terms, uint64_t nSamples,
uint16_t channels )
{
uint16_t i;
printf("Freeing memory... ");
for ( i = 0; i < channels; ++i )
{
free( samples[i] );
free( ffts[i] );
if(ffts16 != NULL) free( ffts16[i] );
if(ffts8 != NULL) free( ffts8[i] );
}
free(samples);
free(ffts);
if(ffts16 != NULL) free( ffts16 );
if(ffts8 != NULL) free( ffts8 );
if(samples_final != NULL) free(samples_final);
if(num_terms != NULL) free(num_terms);
printf( "DONE\n" );
printf("\n");
}
void calc_compression_rate ( char *aiff_input_path, char *cadu_output_path )
{
FILE *aiffFile, *caduFile;
long size_aiff, size_cadu;
double rate;
printf("Calculating compression rate... ");
aiffFile = fopen(aiff_input_path, "r");
if ( aiffFile == NULL )
{
fprintf( stderr, "Error opening AIFF input file %s.\n", aiff_input_path );
exit(EXIT_FAILURE);
}
caduFile = fopen( cadu_output_path, "r" );
if ( caduFile == NULL )
{
fprintf( stderr, "Error opening CADU output file %s.\n", cadu_output_path );
exit(EXIT_FAILURE);
}
fseek(aiffFile, 0, SEEK_END);
size_aiff = ftell(aiffFile);
fclose(aiffFile);
fseek(caduFile, 0, SEEK_END);
size_cadu = ftell(caduFile);
fclose(caduFile);
rate = 100 * ((double)size_cadu) / size_aiff;
printf( "DONE\n" );
printf("%s is %.2f%% of %s file size\n", cadu_output_path, rate, aiff_input_path);
printf("\n");
}
| 2.546875 | 3 |
2024-11-18T22:23:47.517756+00:00 | 2019-02-11T21:25:48 | c4bd6db78cf11a9b0e0915d050c3ad241fbb8726 | {
"blob_id": "c4bd6db78cf11a9b0e0915d050c3ad241fbb8726",
"branch_name": "refs/heads/master",
"committer_date": "2019-02-11T21:25:48",
"content_id": "fe1d24f15edad320a7fa7b3d8990ee242e688c46",
"detected_licenses": [
"BSD-3-Clause",
"PSF-2.0",
"Python-2.0",
"Zlib",
"BSD-4-Clause",
"BSD-2-Clause"
],
"directory_id": "334ac8f549b6626c62ceee590dfa364667a8b1f8",
"extension": "c",
"filename": "extapi.c",
"fork_events_count": 1,
"gha_created_at": "2019-03-06T11:08:35",
"gha_event_created_at": "2019-03-06T11:08:35",
"gha_language": null,
"gha_license_id": "NOASSERTION",
"github_id": 174129480,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3037,
"license": "BSD-3-Clause,PSF-2.0,Python-2.0,Zlib,BSD-4-Clause,BSD-2-Clause",
"license_type": "permissive",
"path": "/c/meterpreter/source/extensions/extapi/extapi.c",
"provenance": "stackv2-0115.json.gz:72609",
"repo_name": "maldevel/metasploit-payloads",
"revision_date": "2019-02-11T21:25:48",
"revision_id": "4a0dcb5ae9c2a5e3fc7d7001f15e0979ce5663fb",
"snapshot_id": "ca293105ee79780c27dc032c5cf34a88deff86ca",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/maldevel/metasploit-payloads/4a0dcb5ae9c2a5e3fc7d7001f15e0979ce5663fb/c/meterpreter/source/extensions/extapi/extapi.c",
"visit_date": "2020-04-27T07:12:27.922935"
} | stackv2 | /*!
* @file extapi.h
* @brief Entry point and intialisation definitions for the extended API extension.
*/
#include "../../common/common.h"
#include "../../DelayLoadMetSrv/DelayLoadMetSrv.h"
// include the Reflectiveloader() function, we end up linking back to the metsrv.dll's Init function
// but this doesnt matter as we wont ever call DLL_METASPLOIT_ATTACH as that is only used by the
// second stage reflective dll inject payload and not the metsrv itself when it loads extensions.
#include "../../ReflectiveDLLInjection/dll/src/ReflectiveLoader.c"
#include "window.h"
#include "service.h"
#include "clipboard.h"
#include "adsi.h"
#include "wmi.h"
#include "ntds.h"
#include "pageantjacker.h"
// this sets the delay load hook function, see DelayLoadMetSrv.h
EnableDelayLoadMetSrv();
/*! @brief List of commands that the extended API extension providers. */
Command customCommands[] =
{
COMMAND_REQ("extapi_window_enum", request_window_enum),
COMMAND_REQ("extapi_service_enum", request_service_enum),
COMMAND_REQ("extapi_service_query", request_service_query),
COMMAND_REQ("extapi_service_control", request_service_control),
COMMAND_REQ("extapi_clipboard_get_data", request_clipboard_get_data),
COMMAND_REQ("extapi_clipboard_set_data", request_clipboard_set_data),
COMMAND_REQ("extapi_clipboard_monitor_start", request_clipboard_monitor_start),
COMMAND_REQ("extapi_clipboard_monitor_pause", request_clipboard_monitor_pause),
COMMAND_REQ("extapi_clipboard_monitor_resume", request_clipboard_monitor_resume),
COMMAND_REQ("extapi_clipboard_monitor_purge", request_clipboard_monitor_purge),
COMMAND_REQ("extapi_clipboard_monitor_stop", request_clipboard_monitor_stop),
COMMAND_REQ("extapi_clipboard_monitor_dump", request_clipboard_monitor_dump),
COMMAND_REQ("extapi_adsi_domain_query", request_adsi_domain_query),
COMMAND_REQ("extapi_ntds_parse", ntds_parse),
COMMAND_REQ("extapi_wmi_query", request_wmi_query),
COMMAND_REQ("extapi_pageant_send_query", request_pageant_send_query),
COMMAND_TERMINATOR
};
/*!
* @brief Initialize the server extension.
* @param remote Pointer to the remote instance.
* @return Indication of success or failure.
*/
DWORD __declspec(dllexport) InitServerExtension(Remote *remote)
{
hMetSrv = remote->met_srv;
command_register_all(customCommands);
initialise_clipboard();
initialise_service();
return ERROR_SUCCESS;
}
/*!
* @brief Deinitialize the server extension.
* @param remote Pointer to the remote instance.
* @return Indication of success or failure.
*/
DWORD __declspec(dllexport) DeinitServerExtension(Remote *remote)
{
command_deregister_all(customCommands);
return ERROR_SUCCESS;
}
/*!
* @brief Get the name of the extension.
* @param buffer Pointer to the buffer to write the name to.
* @param bufferSize Size of the \c buffer parameter.
* @return Indication of success or failure.
*/
DWORD __declspec(dllexport) GetExtensionName(char* buffer, int bufferSize)
{
strncpy_s(buffer, bufferSize, "extapi", bufferSize - 1);
return ERROR_SUCCESS;
}
| 2.109375 | 2 |
2024-11-18T22:23:47.593103+00:00 | 2020-12-13T11:15:44 | 59bdce6df2317dbe5d3aa732960968a88ba715b2 | {
"blob_id": "59bdce6df2317dbe5d3aa732960968a88ba715b2",
"branch_name": "refs/heads/main",
"committer_date": "2020-12-13T11:15:44",
"content_id": "dc4bb6f44793cc9dbeb5e4d8c03f0472a918dfdd",
"detected_licenses": [
"MIT"
],
"directory_id": "6eebc3a72e84ba20e4afca7b6acf6972667dc1d8",
"extension": "c",
"filename": "eval_vars_utils.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": 1858,
"license": "MIT",
"license_type": "permissive",
"path": "/srcs/parser/eval_vars_utils.c",
"provenance": "stackv2-0115.json.gz:72737",
"repo_name": "k-allard/my_own_shell",
"revision_date": "2020-12-13T11:15:44",
"revision_id": "03ab7bc01065a6e386e81e0f04275a98fbb72b19",
"snapshot_id": "44d6cee0e8b703a638d6a622297010e074bcc172",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/k-allard/my_own_shell/03ab7bc01065a6e386e81e0f04275a98fbb72b19/srcs/parser/eval_vars_utils.c",
"visit_date": "2023-01-30T09:51:11.302570"
} | stackv2 | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* eval_vars_utils.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: kallard <kallard@student.21-school.ru> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/11/08 15:26:49 by kallard #+# #+# */
/* Updated: 2020/11/11 11:13:04 by kallard ### ########.fr */
/* */
/* ************************************************************************** */
#include "../minishell.h"
#include "parser.h"
void eval_var(char **str_eval, char **str_original, t_list_env *envs)
{
char *var_name;
var_name = get_var_name(*str_original);
str_join_str(str_eval, get_env_value(var_name, envs));
(*str_original) += (ft_strlen(var_name) + 1);
free(var_name);
}
void eval_param(char **str_eval, char **str_original, int argc, char **argv)
{
int param_index;
param_index = (*((*str_original) + 1)) - '0';
if (param_index < argc)
str_join_str(str_eval, argv[param_index]);
(*str_original) += 2;
}
void eval_last_exit_value(char **str_eval, char **str_original)
{
char *exit_value;
exit_value = ft_itoa(g_exit_value);
str_join_str(str_eval, exit_value);
(*str_original) += (ft_strlen(exit_value) + 1);
free(exit_value);
}
void eval_tilda(char **str_eval, char **str_original, t_list_env *envs)
{
char *home_dir;
home_dir = get_env_value("HOME", envs);
str_join_str(str_eval, home_dir);
(*str_original) += 2;
}
| 2.25 | 2 |
2024-11-18T22:23:47.673533+00:00 | 2014-12-19T15:59:25 | e5e7d3f4489776f472dfaf36f8bf1e3d70d01e9d | {
"blob_id": "e5e7d3f4489776f472dfaf36f8bf1e3d70d01e9d",
"branch_name": "refs/heads/master",
"committer_date": "2014-12-19T15:59:25",
"content_id": "cae6aa727129c2567260481dd92704079b373329",
"detected_licenses": [
"MIT"
],
"directory_id": "3860dedaabe3c91a2d6fc7aee89a695ada085efa",
"extension": "h",
"filename": "text.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 13532303,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 450,
"license": "MIT",
"license_type": "permissive",
"path": "/text.h",
"provenance": "stackv2-0115.json.gz:72866",
"repo_name": "egillespie/xorlix-gba",
"revision_date": "2014-12-19T15:59:25",
"revision_id": "615e1e8e801ecbc627ef3beeb190c95d097e54a6",
"snapshot_id": "145239212dcc122a332b614cfbb2d374457e140c",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/egillespie/xorlix-gba/615e1e8e801ecbc627ef3beeb190c95d097e54a6/text.h",
"visit_date": "2016-09-06T10:19:28.358491"
} | stackv2 | #ifndef ELG_TEXT_H
#define ELG_TEXT_H
/* Sets/gets the palette used to render the text */
void txtSetPalette(short);
short txtGetPalette(void);
/* Get length routines */
short txtLenN(short);
/* Print different types of data */
void txtPrintC(short, short, char);
void txtPrintS(short, short, const char*, short);
void txtPrintN(short, short, short);
/* Returns the tileset index of the specified character */
short txtIndexOf(char);
#endif
| 2.015625 | 2 |
2024-11-18T22:23:47.921211+00:00 | 2018-06-09T10:58:38 | a6a40808e0c777f915901cf42ed0f0c92b847031 | {
"blob_id": "a6a40808e0c777f915901cf42ed0f0c92b847031",
"branch_name": "refs/heads/master",
"committer_date": "2018-06-09T10:58:38",
"content_id": "aee0276c3c78542a99ca7de03acb9cdaaa019674",
"detected_licenses": [
"MIT"
],
"directory_id": "03b39c11d9e73bf4aee483dcd05af3865ebd9998",
"extension": "h",
"filename": "page.h",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 127878014,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 410,
"license": "MIT",
"license_type": "permissive",
"path": "/ucore/src/kern-ucore/module/include/asm-generic/page.h",
"provenance": "stackv2-0115.json.gz:73250",
"repo_name": "oscourse-tsinghua/OS2018spring-projects-g14",
"revision_date": "2018-06-09T10:58:38",
"revision_id": "94155cc7e560c740bf6d2938c1f08a2f3ac0ffb8",
"snapshot_id": "b51b8120b7dffc3923bb4de311dcf8f9d60fcea6",
"src_encoding": "UTF-8",
"star_events_count": 5,
"url": "https://raw.githubusercontent.com/oscourse-tsinghua/OS2018spring-projects-g14/94155cc7e560c740bf6d2938c1f08a2f3ac0ffb8/ucore/src/kern-ucore/module/include/asm-generic/page.h",
"visit_date": "2020-03-08T03:00:33.365276"
} | stackv2 | #ifndef _ASM_GENERIC_PAGE_H
#define _ASM_GENERIC_PAGE_H
#ifndef __ASSEMBLY__
#include <linux/compiler.h>
/* Pure 2^n version of get_order */
static __inline__ __attribute_const__ int get_order(unsigned long size)
{
int order;
size = (size - 1) >> (PAGE_SHIFT - 1);
order = -1;
do {
size >>= 1;
order++;
} while (size);
return order;
}
#endif /* __ASSEMBLY__ */
#endif /* _ASM_GENERIC_PAGE_H */
| 2.328125 | 2 |
2024-11-18T22:23:47.984177+00:00 | 2017-09-17T01:23:41 | 1e9527ee623a06c1c23f66e1c5563c622da576b2 | {
"blob_id": "1e9527ee623a06c1c23f66e1c5563c622da576b2",
"branch_name": "refs/heads/develop",
"committer_date": "2017-09-17T01:23:41",
"content_id": "d853ae1b70b1a0b6cf1dd5a48cabbd057c7969ef",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "2f42828a59270da482668c0b695741fe0e5076df",
"extension": "c",
"filename": "util.c",
"fork_events_count": 0,
"gha_created_at": "2017-09-13T08:19:03",
"gha_event_created_at": "2017-09-17T01:23:42",
"gha_language": "C",
"gha_license_id": null,
"github_id": 103373149,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3826,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/util.c",
"provenance": "stackv2-0115.json.gz:73380",
"repo_name": "suke-blog/gimgtools",
"revision_date": "2017-09-17T01:23:41",
"revision_id": "a488909ad463f59751a069131a4a9dd00af45de8",
"snapshot_id": "16be967fcaa698a05b93da46217214544ed0fd50",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/suke-blog/gimgtools/a488909ad463f59751a069131a4a9dd00af45de8/util.c",
"visit_date": "2021-06-26T21:21:45.423446"
} | stackv2 | #include "gimglib.h"
const char *sint24_to_lat (int n)
{
static char buffers[8][12];
static unsigned int buffer_ptr = 0;
char *buffer = buffers[buffer_ptr ++ % 8];
assert(n < 0x800000 && n >= -0x800000);
if (n < 0)
sprintf(buffer, "%.5fS", n * (360.0 / 0x01000000));
else
sprintf(buffer, "%.5fN", n * (360.0 / 0x01000000));
return buffer;
}
const char *sint24_to_lng (int n)
{
static char buffers[8][12];
static unsigned int buffer_ptr = 0;
char *buffer = buffers[buffer_ptr ++ % 8];
assert(n < 0x800000 && n >= -0x800000);
if (n < 0)
sprintf(buffer, "%.5fW", n * (360.0 / 0x01000000));
else
sprintf(buffer, "%.5fE", n * (360.0 / 0x01000000));
return buffer;
}
const char *dump_unknown_bytes (uint8_t *bytes, int size)
{
static char buffers[4][1024];
static unsigned int currbuf = 0;
char *buffer = buffers[(currbuf ++) % 4];
int ptr, outptr, repeat_count, repeat_byte;
if (size == 0)
return "";
if (size > sizeof(buffers[0]) / 2 - 2)
size = sizeof(buffers[0]) / 2 - 2;
for (repeat_byte = bytes[0], ptr = 1, repeat_count = 1, outptr = 0; ptr < size; ptr ++) {
if (bytes[ptr] == repeat_byte) {
repeat_count ++;
} else {
if (repeat_count >= 3) {
outptr += sprintf(buffer + outptr, "%02x(%d)", repeat_byte, repeat_count);
} else if (repeat_count == 2) {
outptr += sprintf(buffer + outptr, "%02x%02x", repeat_byte, repeat_byte);
} else {
outptr += sprintf(buffer + outptr, "%02x", repeat_byte);
}
repeat_byte = bytes[ptr];
repeat_count = 1;
}
}
if (repeat_count >= 3) {
outptr += sprintf(buffer + outptr, "%02x(%d)", repeat_byte, repeat_count);
} else if (repeat_count == 2) {
outptr += sprintf(buffer + outptr, "%02x%02x", repeat_byte, repeat_byte);
} else {
outptr += sprintf(buffer + outptr, "%02x", repeat_byte);
}
return buffer;
}
void unlockml (unsigned char *dst, const unsigned char *src,
int size, unsigned int key)
{
static const unsigned char shuf[] = {
0xb, 0xc, 0xa, 0x0,
0x8, 0xf, 0x2, 0x1,
0x6, 0x4, 0x9, 0x3,
0xd, 0x5, 0x7, 0xe};
int i, ringctr;
int key_sum = shuf[((key >> 24) + (key >> 16) + (key >> 8) + key) & 0xf];
for (i = 0, ringctr = 16; i < size; i ++) {
unsigned int upper = src[i] >> 4;
unsigned int lower = src[i];
upper -= key_sum;
upper -= key >> ringctr;
upper -= shuf[(key >> ringctr) & 0xf];
ringctr = ringctr ? ringctr - 4 : 16;
lower -= key_sum;
lower -= key >> ringctr;
lower -= shuf[(key >> ringctr) & 0xf];
ringctr = ringctr ? ringctr - 4 : 16;
dst[i] = ((upper << 4) & 0xf0) | (lower & 0xf);
}
}
enum subtype get_subtype_id (const char *str) // only use 3 chars from str
{
if (memcmp(str, "TRE", 3) == 0) return ST_TRE;
if (memcmp(str, "RGN", 3) == 0) return ST_RGN;
if (memcmp(str, "LBL", 3) == 0) return ST_LBL;
if (memcmp(str, "NET", 3) == 0) return ST_NET;
if (memcmp(str, "NOD", 3) == 0) return ST_NOD;
if (memcmp(str, "DEM", 3) == 0) return ST_DEM;
if (memcmp(str, "MAR", 3) == 0) return ST_MAR;
if (memcmp(str, "SRT", 3) == 0) return ST_SRT;
if (memcmp(str, "GMP", 3) == 0) return ST_GMP;
if (memcmp(str, "TYP", 3) == 0) return ST_TYP;
if (memcmp(str, "MDR", 3) == 0) return ST_MDR;
if (memcmp(str, "TRF", 3) == 0) return ST_TRF;
if (memcmp(str, "MPS", 3) == 0) return ST_MPS;
if (memcmp(str, "QSI", 3) == 0) return ST_QSI;
return ST_UNKNOWN;
}
const char *get_subtype_name (enum subtype id)
{
const static char *type_names[] = {
"TRE", "RGN", "LBL", "NET", "NOD", "DEM", "MAR",
"SRT", "GMP", "TYP", "MDR", "TRF",
"MPS", "QSI"};
return id >= ST_UNKNOWN ? NULL : type_names[id];
}
/* remove space characters at the end
* length = -1 means using strlen() */
void string_trim (char *str, int length)
{
int i;
if (length == -1)
length = strlen(str);
for (i = length - 1; i >= 0 && str[i] == ' '; i --)
str[i] = '\0';
}
| 2.5 | 2 |
2024-11-18T22:23:48.060114+00:00 | 2020-05-21T12:59:33 | ca944f604c73d60f70362d58ddd675db247679e1 | {
"blob_id": "ca944f604c73d60f70362d58ddd675db247679e1",
"branch_name": "refs/heads/master",
"committer_date": "2020-05-21T12:59:33",
"content_id": "6fe4b39e10a153655f33c124dd16ba9cc5919df0",
"detected_licenses": [
"MIT"
],
"directory_id": "089ddc6c7577865c25de42a047222892b4bbca66",
"extension": "c",
"filename": "l2ex5.c",
"fork_events_count": 2,
"gha_created_at": "2019-06-13T07:16:22",
"gha_event_created_at": "2020-10-13T22:10:38",
"gha_language": "Java",
"gha_license_id": "MIT",
"github_id": 191711233,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 435,
"license": "MIT",
"license_type": "permissive",
"path": "/Sem1/Introducere în programare/Tutorials/l2ex5.c",
"provenance": "stackv2-0115.json.gz:73511",
"repo_name": "gdincu/UBB_PostUni",
"revision_date": "2020-05-21T12:59:33",
"revision_id": "4e247b8e96d4470ed1765b0f24ab34f6f87c5013",
"snapshot_id": "79db0c4e9cb31a9e6cd6c0e23654d66f8e61a9e3",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/gdincu/UBB_PostUni/4e247b8e96d4470ed1765b0f24ab34f6f87c5013/Sem1/Introducere în programare/Tutorials/l2ex5.c",
"visit_date": "2021-07-06T08:28:46.398715"
} | stackv2 | #include<stdio.h>
int main()
{
char s[10];
int a,b;
//gets(s);
//a=atoi(s);
//gets(s);
//b=atoi(s);
scanf("%d",&a);
a++;
printf("%s\n",itoa(a));
//printf("%d\n",a+b);
}
//converteste un string in numar
//folositor cand vrem sa terminam un program care citeste numere de la tastatura folosing un string (eg. EXIT)
//itoa este inversul lui atoi si converteste din numere in litere - citirea se face numai cu scanf
| 2.515625 | 3 |
2024-11-18T22:23:48.280839+00:00 | 2016-06-20T18:47:20 | 4f0f5e0cf5423dd9d332fc3dba25221eab5ad371 | {
"blob_id": "4f0f5e0cf5423dd9d332fc3dba25221eab5ad371",
"branch_name": "refs/heads/master",
"committer_date": "2016-06-20T18:47:20",
"content_id": "9c066b189f8d5b7e6c055048a3ca49c6339650fa",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "2aca58fa81b84b781c934079b1600f5cd70e4dc9",
"extension": "c",
"filename": "zebra_kernel_routes.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": 10014,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/modules/ext/mgmt/examples/confd-6.0/examples.confd/demo/quagga/src/quagga/c/zebra_kernel_routes.c",
"provenance": "stackv2-0115.json.gz:73898",
"repo_name": "StefanoSalsano/RIFT.ware",
"revision_date": "2016-06-20T18:47:20",
"revision_id": "f3c38ccf640a9454611769df97540b48410ad0c9",
"snapshot_id": "3b36dcbdd357dadb3683526eaf7d5d67eb837a75",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/StefanoSalsano/RIFT.ware/f3c38ccf640a9454611769df97540b48410ad0c9/modules/ext/mgmt/examples/confd-6.0/examples.confd/demo/quagga/src/quagga/c/zebra_kernel_routes.c",
"visit_date": "2021-01-15T22:04:08.606829"
} | stackv2 | #include <stdlib.h>
#include <sys/wait.h>
#include <string.h>
#include "confd.h"
#include "zconfd_api.h"
#include "confd_global.h"
#include "quagga.h" /* generated from yang */
#define BUFLEN BUFSIZ
#define TOKCHARS " \n\t\r"
#define ROUTE_CMD "/sbin/route"
#define ELEMS_PER_ROUTE 9
#define ROUTE_FLAG(f) NSPREF(_bm_routeFlagsType_ ## f)
#define ACTION_ERROR(uinfo, fmt,...) return (ERROR_LOG(fmt , ##__VA_ARGS__), confd_action_seterr(uinfo, fmt , ##__VA_ARGS__), CONFD_ERR)
typedef struct {
char buf[BUFLEN+1];
char *ptr, *next, *end;
int fd;
} reader_t;
enum { ROUTE_GATEWAY = 1 << 0, ROUTE_IFACE = 1 << 1, ROUTE_MASK = 1 << 2, ROUTE_METRIC = 1 << 3, ROUTE_FLAGS = 1 << 4 };
typedef struct {
char destination[KPATH_MAX], gateway[KPATH_MAX], iface[KPATH_MAX];
struct in_addr mask;
u_int32_t flags;
int32_t type;
u_int16_t metric;
int fields_present;
} route_t;
typedef struct route_list {
route_t route;
struct route_list *next;
} route_list_t;
void free_route_list(route_list_t *routes)
{
route_list_t *n;
for (;routes != NULL; routes = n) {
n = routes->next;
free(routes);
}
}
static void init_reader(reader_t *r, int fd)
{
r->fd = fd;
// int n = read(fd, r->buf, BUFLEN)
r->buf[BUFLEN] = 0;
r->ptr = r->end = r->buf;
r->next = NULL;
}
static char *get_next_line(reader_t *r)
{
if (r->fd <= 0)
return NULL;
char* const sentinel = r->buf + BUFLEN;
do {
if (r->next == NULL) {
if (sentinel == r->end) {
int len = sentinel - r->ptr;
if (len > 0)
memmove(r->buf, r->ptr, len + 1); /* need to move the last NUL! */
r->ptr = r->buf;
r->end = r->buf + len;
}
int n = read(r->fd, r->end, sentinel - r->end);
if (n <= 0) {
if (r->end == r->ptr)
return NULL;
r->fd = -1;
*r->end = 0;
return r->ptr;
}
*(r->end = r->end + n) = 0;
} else
r->ptr = r->next + 1;
r->next = strchr(r->ptr, '\n');
} while (r->next == NULL);
*r->next = 0;
return r->ptr;
}
int read_routes(int fd, route_list_t **routes)
{
reader_t reader;
char *line;
route_list_t **last = routes;
route_t *route;
int count = 0;
init_reader(&reader, fd);
if (get_next_line(&reader) == NULL || get_next_line(&reader) == NULL)
return -1;
while ((line = get_next_line(&reader)) != NULL) {
const char *toks[8];
int i;
const char *flag;
if ((toks[0] = strtok(line, TOKCHARS)) == NULL)
return -1;
for (i = 1; i < 8; i++)
if ((toks[i] = strtok(NULL, TOKCHARS)) == NULL)
return -1;
*last = malloc(sizeof(route_list_t));
route = &(*last)->route;
last = &(*last)->next;
strcpy(route->destination, toks[0]);
strcpy(route->gateway, toks[1]);
route->mask.s_addr = inet_addr(toks[2]);
route->type = route->mask.s_addr == 0xffffffff ?
NSPREF(_routeTargetType_host) : NSPREF(_routeTargetType_net);
route->flags = 0;
for (flag = toks[3]; *flag != 0; flag++)
switch (*flag) {
case 'U': route->flags |= ROUTE_FLAG(U); break;
case 'H': route->flags |= ROUTE_FLAG(H); break;
case 'G': route->flags |= ROUTE_FLAG(G); break;
case 'R': route->flags |= ROUTE_FLAG(R); break;
case 'D': route->flags |= ROUTE_FLAG(D); break;
case 'M': route->flags |= ROUTE_FLAG(M); break;
case 'A': route->flags |= ROUTE_FLAG(A); break;
case 'C': route->flags |= ROUTE_FLAG(C); break;
default: return -1;
}
route->metric = atoi(toks[4]);
strcpy(route->iface, toks[7]);
count++;
}
*last = NULL;
return count;
}
void wait_process(int pid)
{
int status;
waitpid(pid, &status, 0);
if (!WIFEXITED(status) || WEXITSTATUS(status) != 0)
ERROR_LOG("Waiting for child process failure: %i", status);
}
int open_route_pipe(int *pid, int *fd)
{
int pipefd[2];
char *argv[2];
if (pipe(pipefd) != 0) {
ERROR_LOG("Failed to create pipe for running command");
return -1;
}
switch ((*pid = fork())) {
case 0: /* child */
close(pipefd[0]);
dup2(pipefd[1], STDOUT_FILENO);
dup2(pipefd[1], STDERR_FILENO);
if (pipefd[1] != STDOUT_FILENO && pipefd[1] != STDERR_FILENO)
close(pipefd[1]);
argv[0] = ROUTE_CMD;
argv[1] = NULL;
execve(ROUTE_CMD, argv, NULL);
perror(NULL);
exit(127);
case -1: /* failure */
close(pipefd[1]);
close(pipefd[0]);
ERROR_LOG("Failed to fork");
return -1;
}
close(pipefd[1]);
*fd = pipefd[0];
return 0;
}
static confd_tag_value_t *process_route_params(route_t *route, confd_tag_value_t *params)
{
confd_value_t *value;
route->fields_present = 0;
for (; (value = CONFD_GET_TAG_VALUE(params))->type != C_XMLEND; params++) {
switch (CONFD_GET_TAG_TAG(params)) {
case NSPREF(destination):
strncpy(route->destination, CONFD_GET_CBUFPTR(value), CONFD_GET_BUFSIZE(value));
route->destination[CONFD_GET_BUFSIZE(value)] = 0;
break;
case NSPREF(type):
route->type = CONFD_GET_ENUM_VALUE(value);
break;
case NSPREF(gateway):
strncpy(route->gateway, CONFD_GET_CBUFPTR(value), CONFD_GET_BUFSIZE(value));
route->gateway[CONFD_GET_BUFSIZE(value)] = 0;
route->fields_present |= ROUTE_GATEWAY;
break;
case NSPREF(mask):
route->mask = CONFD_GET_IPV4(value);
route->fields_present |= ROUTE_MASK;
break;
case NSPREF(flags):
/* ehh.. should not happen... */
route->flags = CONFD_GET_BIT32(value);
route->fields_present |= ROUTE_FLAGS;
break;
case NSPREF(metric):
route->metric = CONFD_GET_UINT16(value);
route->fields_present |= ROUTE_METRIC;
break;
case NSPREF(iface):
strncpy(route->iface, CONFD_GET_CBUFPTR(value), CONFD_GET_BUFSIZE(value));
route->iface[CONFD_GET_BUFSIZE(value)] = 0;
route->fields_present |= ROUTE_IFACE;
break;
}
}
return params;
}
int act_route(char *action, struct confd_user_info *uinfo, route_t *route)
{
char *argv[20], **arg = argv;
int pid;
*(arg++) = ROUTE_CMD;
*(arg++) = action;
*(arg++) = route->type == NSPREF(_routeTargetType_host) ? "-host" : "-net";
*(arg++) = route->destination;
if (route->fields_present & ROUTE_MASK) {
*(arg++) = "netmask";
*(arg++) = inet_ntoa(route->mask);
}
if (route->fields_present & ROUTE_GATEWAY) {
*(arg++) = "gw";
*(arg++) = route->gateway;
}
if (route->fields_present & ROUTE_IFACE) {
*(arg++) = "dev";
*(arg++) = route->iface;
}
*arg = NULL;
switch (pid = fork()) {
case 0:
execve("/sbin/route", argv, NULL);
perror(NULL);
exit(127);
case -1:
ACTION_ERROR(uinfo, "Unable to spawn process");
}
wait_process(pid);
confd_action_reply_values(uinfo, NULL, 0);
return CONFD_OK;
}
int get_routes(struct confd_user_info *uinfo)
{
int pid, fd;
route_list_t *routes = NULL, *r;
int count;
confd_tag_value_t *reply, *start;
if (open_route_pipe(&pid, &fd) == -1)
ACTION_ERROR(uinfo, "Cannot start a system command");
if ((count = read_routes(fd, &routes)) == -1)
ACTION_ERROR(uinfo, "Cannot parse command output");
wait_process(pid);
close(fd);
#ifdef DEBUG
for (r = routes; r != NULL; r = r->next)
DEBUG_LOG("read route dest. %s, gw %s, mask %s, flags %i, metric %i, iface %s",
r->route.destination, r->route.gateway, inet_ntoa(r->route.mask), r->route.flags, r->route.metric, r->route.iface);
#endif
start = malloc(count * ELEMS_PER_ROUTE * sizeof(confd_tag_value_t));
for (reply = start, r = routes; r != NULL; r = r->next) {
CONFD_SET_TAG_XMLBEGIN(reply++, NSPREF(routes), NAMESPACE);
CONFD_SET_TAG_ENUM_VALUE(reply++, NSPREF(type), r->route.type);
CONFD_SET_TAG_STR(reply++, NSPREF(destination), r->route.destination);
CONFD_SET_TAG_STR(reply++, NSPREF(gateway), r->route.gateway);
CONFD_SET_TAG_IPV4(reply++, NSPREF(mask), r->route.mask);
CONFD_SET_TAG_BIT32(reply++, NSPREF(flags), r->route.flags);
CONFD_SET_TAG_UINT16(reply++, NSPREF(metric), r->route.metric);
CONFD_SET_TAG_STR(reply++, NSPREF(iface), r->route.iface);
CONFD_SET_TAG_XMLEND(reply++, NSPREF(routes), NAMESPACE);
}
confd_action_reply_values(uinfo, start, count * ELEMS_PER_ROUTE);
free_route_list(routes);
free(start);
return CONFD_OK;
}
int zebra_route_action(struct confd_user_info *uinfo, struct xml_tag *name,
confd_hkeypath_t *kp, confd_tag_value_t *params, int nparams)
{
confd_tag_value_t *const parend = params + nparams;
route_t route;
int to_add = 0, to_del = 0;
int32_t operation = 0;
for (; params < parend; params++) {
confd_value_t *value = CONFD_GET_TAG_VALUE(params);
switch (value->type) {
case C_XMLBEGIN:
/* route definition should begin here.. */
*(CONFD_GET_TAG_TAG(params) == NSPREF(route_to_add) ? &to_add : &to_del) = 1;
params = process_route_params(&route, params+1);
break;
case C_XMLEND:
/* what?? should not happen.. */
ERROR_LOG("XMLEND met..?");
break;
default:
operation = CONFD_GET_ENUM_VALUE(value);
break;
}
}
switch (operation) {
case NSPREF(_operationType2_add):
if (to_del || !to_add)
ACTION_ERROR(uinfo, "Bad arguments for \"add\" operation: %s",
!to_add ? "to-add routes needed" : "cannot have to-delete routes");
return act_route("add", uinfo, &route);
case NSPREF(_operationType2_delete):
if (!to_del || to_add)
ACTION_ERROR(uinfo, "Bad arguments for \"delete\" operation: %s",
!to_del ? "to-delete routes needed" : "cannot have to-add routes");
return act_route("del", uinfo, &route);
case NSPREF(_operationType2_show):
if (to_del || to_add)
ACTION_ERROR(uinfo, "Bad arguments for \"show\" operation: cannot have %s routes",
to_add ? "to-add" : "to-delete");
return get_routes(uinfo);
}
return CONFD_OK;
}
| 2.0625 | 2 |
2024-11-18T22:23:48.990157+00:00 | 2014-10-30T01:31:04 | 440fa0d9452bcfc70a1050c29a833d4abc3f153c | {
"blob_id": "440fa0d9452bcfc70a1050c29a833d4abc3f153c",
"branch_name": "HEAD",
"committer_date": "2014-10-30T01:31:04",
"content_id": "1498d749d316b64779925b233338f73415edb7cb",
"detected_licenses": [
"MIT"
],
"directory_id": "08f42251162a50e4be1df009dda9cc54148fe5d4",
"extension": "c",
"filename": "main.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 7855,
"license": "MIT",
"license_type": "permissive",
"path": "/main.c",
"provenance": "stackv2-0115.json.gz:74156",
"repo_name": "mam1/XMMC-cogs-demo",
"revision_date": "2014-10-30T01:31:04",
"revision_id": "b2e063b576c2424acb93046b5e70b8f51a7ca625",
"snapshot_id": "7c81f69c5a959d9713e0a18b3a224343047b2183",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/mam1/XMMC-cogs-demo/b2e063b576c2424acb93046b5e70b8f51a7ca625/main.c",
"visit_date": "2016-09-05T09:18:35.768152"
} | stackv2 | /**
* This is the main cog_test program file. It is a skeleton of an
* application has a xmmc process which starts and stops processes
* running on separate cogs. The xmmc routine is a simple command
* processor. It supports the following commands:
* startA - load cogA code into a cog and start it
* startB - load cogB code into a cog and start it
* startC - load cogC code into a cog and start it
* stopA - stop the cog running cogA code
* stopB - stop the cog running cogB code
* stopC - stop the cog running cogC code
* queryA - set flag telling the cogA code to increment query counter for the cog
* queryB - set flag telling the cogB code to increment query counter for the cog
* queryC - set flag telling the cogC code to increment query counter for the cog
* status - display the state of all cogs and counters
* exit - terminate application
*
* The code loaded in to the cogs is identical. On startup it zeros the
* query counter then loops, checking shared memory for a flag requesting
* that the query counter be incremented.
*
*/
#include <stdio.h>
#include <propeller.h>
#include "main.h"
/* allocate control block & stack for cogA */
struct {
unsigned stack[STACK_A];
CONTROL_BLOCK A;
} parA;
/* allocate control block & stack for cogB */
struct {
unsigned stack[STACK_B];
CONTROL_BLOCK B;
} parB;
/* allocate control block & stack for cogC */
struct {
unsigned stack[STACK_C];
CONTROL_BLOCK C;
} parC;
/* command processor command list */
char *command[COMMANDS] = {
/* 0 */ "startA",
/* 1 */ "startB",
/* 2 */ "startC",
/* 3 */ "stopA",
/* 4 */ "stopB",
/* 5 */ "stopC",
/* 6 */ "queryA",
/* 7 */ "queryB",
/* 8 */ "queryC",
/* 9 */ "status",
/* 10 */ "exit"};
/************************* command processor routines *************************/
/* start cogA */
int start_cogA(volatile void *parptr)
{
extern unsigned int _load_start_cogA_cog[]; //start address for cog code
extern unsigned int _load_stop_cogA_cog[]; //end address for cog code
if(parA.A.cog != -1) //see if the cog is running
cogstop(parA.A.cog); //stop the cog
int size = (_load_stop_cogA_cog - _load_start_cogA_cog)*4; //code size in bytes
printf(" cogA code size %i bytes - ",size);
unsigned int code[size]; //allocate enough HUB to hold the COG code
memcpy(code, _load_start_cogA_cog, size); //copy the code to HUB memory
parA.A.cog = cognew(code, parptr); //start the cog
return parA.A.cog;
}
/* start cogB */
int start_cogB(volatile void *parptr)
{
extern unsigned int _load_start_cogB_cog[]; //start address for cog code
extern unsigned int _load_stop_cogB_cog[]; //end address for cog code
if(parB.B.cog != -1) //see if the cog is running
cogstop(parB.B.cog); //stop the cog
int size = (_load_stop_cogB_cog - _load_start_cogB_cog)*4; //code size in bytes
printf(" cogB code size %i bytes - ",size);
unsigned int code[size]; //allocate enough HUB to hold the COG code
memcpy(code, _load_start_cogB_cog, size); //copy the code to HUB memory
parB.B.cog = cognew(code, parptr); //start the cog
return parB.B.cog;
}
/* start cogC */
int start_cogC(volatile void *parptr)
{
extern unsigned int _load_start_cogC_cog[]; //start address for cog code
extern unsigned int _load_stop_cogC_cog[]; //end address for cog code
if(parC.C.cog != -1) //see if the cog is running
cogstop(parC.C.cog); //stop the cog
int size = (_load_stop_cogC_cog - _load_start_cogC_cog)*4; //code size in bytes
printf(" cogC code size %i bytes - ",size);
unsigned int code[size]; //allocate enough HUB to hold the COG code
memcpy(code, _load_start_cogC_cog, size); //copy the code to HUB memory
parC.C.cog = cognew(code, parptr); //start the cog
return parC.C.cog;
}
/* convert user input to command number */
int process(char *input)
{
int i;
for(i=0;i<COMMANDS;i++) //loop through the command list
{
if(strcmp(input,command[i])==0) //see if the user entered a valid command
return i; //return the command number
}
return -1; //user entered an invalid command
}
/* display the status of all cogs and query counters */
void status(void)
{
printf(" cog A is ");
if(parA.A.cog == -1)
printf("not running, query count %i\n",parA.A.query_ctr);
else
printf("running on cog %i, query count %i\n",parA.A.cog,parA.A.query_ctr);
printf(" cog B is ");
if(parB.B.cog == -1)
printf("not running, query count %i\n", parB.B.query_ctr);
else
printf("running on cog %i, query count %i\n",parB.B.cog,parB.B.query_ctr);
printf(" cog C is ");
if(parC.C.cog == -1)
printf("not running, query count %i\n",parC.C.query_ctr);
else
printf("running on cog %i, query count %i\n",parC.C.cog,parC.C.query_ctr);
return;
}
/****************************** start main routine ******************************/
int main(void)
{
char input_buffer[INPUT_BUFFER]; //buffer for user input
/* display startup message */
waitcnt(500000 + _CNT); //wait until initialization is complete
printf("XMMC-cogc demo v%s",VERSION);
/* set all cogs to not running */
parA.A.cog = -1;
parB.B.cog = -1;
parC.C.cog = -1;
/* loop forever */
while(1)
{
printf("\nenter command > ");
fgets(input_buffer,INPUT_BUFFER,stdin); //get a line of input
input_buffer[strlen(input_buffer)-1] = '\0'; //get rid of trailing new line character
switch(process(input_buffer)) //test input,take appropriate action
{
case 0: //startA
if(start_cogA(&parA.A)== -1)
printf(" problem starting cogA\n");
else
printf(" cogA started\n");
break;
case 1: //startB
if(start_cogB(&parB.B)== -1)
printf(" problem starting cogB\n");
else
printf(" cogB started\n");
break;
case 2: //startC
if(start_cogC(&parC.C)== -1)
printf(" problem starting cogC\n");
else
printf(" cogC started\n");
break;
case 3: //stopA
cogstop(parA.A.cog);
printf(" cog A stopped\n");
parA.A.cog = -1;
break;
case 4: //stopB
cogstop(parB.B.cog);
printf(" cog B stopped\n");
parB.B.cog = -1;
break;
case 5: //stopC
cogstop(parC.C.cog);
printf(" cog C stopped\n");
parC.C.cog = -1;
break;
case 6: //queryA
parA.A.query_flag = 1;
break;
case 7: //queryB
parB.B.query_flag = 1;
break;
case 8: //queryC
parC.C.query_flag = 1;
break;
case 9: //status
status();
break;
case 10: //exit
printf("exiting program\n");
return 0;
default:
printf("<%s> is not a valid command\n",input_buffer);
}
}
return 0;
}
| 3.0625 | 3 |
2024-11-18T22:23:49.046522+00:00 | 2019-11-24T11:24:05 | dd7af41f53a60254e1aa7130bee97dc8e5db7621 | {
"blob_id": "dd7af41f53a60254e1aa7130bee97dc8e5db7621",
"branch_name": "refs/heads/master",
"committer_date": "2019-11-24T11:24:05",
"content_id": "d03ace02976b8d3f4043f4f7706d25ce8dd78ff3",
"detected_licenses": [
"MIT"
],
"directory_id": "d1a2cb3d1bc8db37b5ccfd795a60224e6b59c2b5",
"extension": "c",
"filename": "typing.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 223732200,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 938,
"license": "MIT",
"license_type": "permissive",
"path": "/lab3-3/typing.c",
"provenance": "stackv2-0115.json.gz:74286",
"repo_name": "20143227LDJ/lab3",
"revision_date": "2019-11-24T11:24:05",
"revision_id": "43fcfce39daa3613b34e3165eba48cc3fb826327",
"snapshot_id": "c20baef808b6db0fe409ae84a60cd2a73f6ce416",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/20143227LDJ/lab3/43fcfce39daa3613b34e3165eba48cc3fb826327/lab3-3/typing.c",
"visit_date": "2020-09-16T09:45:41.448347"
} | stackv2 | #include <stdio.h>
#include <termios.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#define PASSWORDSIZE 12
int main(void)
{
int fd;
int nread, cnt=0, errcnt=0;
char ch, text[] = "The magic thing is that you can change it.";
struct termios init_attr, new_attr;
fd = open(ttyname(fileno(stdin)), O_RDWR);
tcgetattr(fd, &init_attr);
new_attr = init_attr;
new_attr.c_lflag &= ~ICANON;
new_attr.c_lflag &= ~ECHO; /* ~(ECHO | ECHOE | ECHOK |
ECHONL); */
new_attr.c_cc[VMIN] = 1;
new_attr.c_cc[VTIME] = 0;
if (tcsetattr(fd, TCSANOW, &new_attr) != 0) {
fprintf(stderr, "터미널 속성을 설정할 수 없음.\n");
}
printf("다음 문장을 그대로 입력하세요.\n%s\n", text);
while ((nread=read(fd, &ch, 1)) > 0 && ch != '\n') {
if (ch == text[cnt++])
write(fd, &ch, 1);
else {
write(fd, "*", 1);
errcnt++;
}
}
printf("\n타이핑 오류의 횟수는 %d\n", errcnt);
tcsetattr(fd, TCSANOW, &init_attr);
close(fd);
}
| 2.859375 | 3 |
2024-11-18T22:23:49.134478+00:00 | 2021-10-13T06:49:03 | 7f2f43e2eaf074ad3c07b2e6d292faa778c2b91c | {
"blob_id": "7f2f43e2eaf074ad3c07b2e6d292faa778c2b91c",
"branch_name": "refs/heads/master",
"committer_date": "2022-09-28T12:25:54",
"content_id": "fb25c9d84e58b675beaeaa309d81a05cbfd52deb",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "1aeb28dfc477505d3896e98a135b838e0f80f1b7",
"extension": "c",
"filename": "arc_timer.c",
"fork_events_count": 92,
"gha_created_at": "2017-03-07T07:38:12",
"gha_event_created_at": "2022-09-28T12:25:55",
"gha_language": "C",
"gha_license_id": "BSD-3-Clause",
"github_id": 84169435,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 9758,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/arc/arc_timer.c",
"provenance": "stackv2-0115.json.gz:74416",
"repo_name": "foss-for-synopsys-dwc-arc-processors/embarc_osp",
"revision_date": "2021-10-13T06:49:03",
"revision_id": "67ea926c6a62aa6e19efdc3b11cba3ea0b467e29",
"snapshot_id": "d65feac4c4db8d85df11078c244ffcfe7daf5f53",
"src_encoding": "UTF-8",
"star_events_count": 67,
"url": "https://raw.githubusercontent.com/foss-for-synopsys-dwc-arc-processors/embarc_osp/67ea926c6a62aa6e19efdc3b11cba3ea0b467e29/arc/arc_timer.c",
"visit_date": "2023-08-05T22:19:08.129241"
} | stackv2 | /* ------------------------------------------
* Copyright (c) 2017, Synopsys, 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 Synopsys, 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 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
* @ingroup ARC_HAL_MISC_TIMER
* @brief implementation of internal timer related functions
* @todo RTC support should be improved if RTC is enabled
*/
#include "arc/arc_timer.h"
#include "arc/arc_exception.h"
#define LPS_PREC 8
volatile uint64_t gl_loops_per_jiffy = 1;
volatile uint32_t gl_count = 1;
/**
* @brief check whether the specific timer present
* @param[in] no timer number
* @return 1 present, 0 not present
*/
int32_t arc_timer_present(const uint32_t no)
{
uint32_t bcr = arc_aux_read(AUX_BCR_TIMERS);
switch (no) {
case TIMER_0:
bcr = (bcr >> 8) & 1;
break;
case TIMER_1:
bcr = (bcr >> 9) & 1;
break;
case TIMER_RTC:
bcr = (bcr >> 10) & 1;
break;
default:
bcr = 0;
/* illegal argument so return false */
break;
}
return (int)bcr;
}
/**
* @brief start the specific timer
* @param[in] no timer number
* @param[in] mode timer mode
* @param[in] val timer limit value (not for RTC)
* @return 0 success, -1 failure
*/
int32_t arc_timer_start(const uint32_t no, const uint32_t mode, const uint32_t val)
{
switch (no) {
case TIMER_0:
arc_aux_write(AUX_TIMER0_CTRL, 0);
arc_aux_write(AUX_TIMER0_LIMIT, val);
arc_aux_write(AUX_TIMER0_CTRL, mode);
arc_aux_write(AUX_TIMER0_CNT, 0);
break;
case TIMER_1:
arc_aux_write(AUX_TIMER1_CTRL, 0);
arc_aux_write(AUX_TIMER1_LIMIT, val);
arc_aux_write(AUX_TIMER1_CTRL, mode);
arc_aux_write(AUX_TIMER1_CNT, 0);
break;
case TIMER_RTC:
arc_aux_write(AUX_RTC_CTRL, mode);
break;
default:
return -1;
}
return 0;
}
/**
* @brief stop and clear the specific timer
*
* @param[in] no timer number
* @return 0 success, -1 failure
*/
int32_t arc_timer_stop(const uint32_t no)
{
switch (no) {
case TIMER_0:
arc_aux_write(AUX_TIMER0_CTRL, 0);
arc_aux_write(AUX_TIMER0_LIMIT, 0);
arc_aux_write(AUX_TIMER0_CNT, 0);
break;
case TIMER_1:
arc_aux_write(AUX_TIMER1_CTRL, 0);
arc_aux_write(AUX_TIMER1_LIMIT, 0);
arc_aux_write(AUX_TIMER1_CNT, 0);
break;
case TIMER_RTC:
arc_aux_write(AUX_RTC_CTRL, TIMER_RTC_CLEAR);
break;
default:
return -1;
}
return 0;
}
/**
* @brief get timer current tick
*
* @param[in] no timer number
* @param[out] val, timer value
* @return 0 success, -1 failure
*/
int32_t arc_timer_current(const uint32_t no, void *val)
{
switch (no) {
case TIMER_0:
*((uint32_t *)val) = arc_aux_read(AUX_TIMER0_CNT);
break;
case TIMER_1:
*((uint32_t *)val) = arc_aux_read(AUX_TIMER1_CNT);
break;
case TIMER_RTC:
*((uint64_t *)val) = arc_aux_read(AUX_RTC_LOW);
break;
default:
return -1;
}
return 0;
}
/**
* @brief clear the interrupt pending bit of timer
*
* @param[in] no timer number
* @return 0 success, -1 failure
*/
int32_t arc_timer_int_clear(const uint32_t no)
{
uint32_t val;
switch (no) {
case TIMER_0:
val = arc_aux_read(AUX_TIMER0_CTRL);
val &= ~TIMER_CTRL_IP;
arc_aux_write(AUX_TIMER0_CTRL, val);
break;
case TIMER_1:
val = arc_aux_read(AUX_TIMER1_CTRL);
val &= ~TIMER_CTRL_IP;
arc_aux_write(AUX_TIMER1_CTRL, val);
break;
default:
return -1;
}
return 0;
}
/**
* @brief init internal timer
*/
void arc_timer_init(void)
{
if (arc_timer_present(TIMER_0)) {
arc_timer_stop(TIMER_0);
}
if (arc_timer_present(TIMER_1)) {
arc_timer_stop(TIMER_1);
}
if (arc_timer_present(TIMER_RTC)) {
arc_timer_stop(TIMER_RTC);
}
}
#if defined(ARC_FEATURE_SEC_TIMER1_PRESENT) || defined(ARC_FEATURE_SEC_TIMER0_PRESENT)
/**
* @brief check whether the specific secure timer present
* @param[in] no timer number
* @return 1 present, 0 not present
*/
int32_t arc_secure_timer_present(const uint32_t no)
{
uint32_t bcr = arc_aux_read(AUX_BCR_TIMERS);
switch (no) {
case SECURE_TIMER_0:
bcr = (bcr >> 11) & 1;
break;
case SECURE_TIMER_1:
bcr = (bcr >> 12) & 1;
break;
default:
bcr = 0;
/* illegal argument so return false */
break;
}
return (int)bcr;
}
/**
* @brief start the specific secure timer
* @param[in] no timer number
* @param[in] mode timer mode
* @param[in] val timer limit value (not for RTC)
* @return 0 success, -1 failure
*/
int32_t arc_secure_timer_start(const uint32_t no, const uint32_t mode, const uint32_t val)
{
switch (no) {
case SECURE_TIMER_0:
arc_aux_write(AUX_SECURE_TIMER0_CTRL, 0);
arc_aux_write(AUX_SECURE_TIMER0_LIMIT, val);
arc_aux_write(AUX_SECURE_TIMER0_CTRL, mode);
arc_aux_write(AUX_SECURE_TIMER0_CNT, 0);
break;
case SECURE_TIMER_1:
arc_aux_write(AUX_SECURE_TIMER1_CTRL, 0);
arc_aux_write(AUX_SECURE_TIMER1_LIMIT, val);
arc_aux_write(AUX_SECURE_TIMER1_CTRL, mode);
arc_aux_write(AUX_SECURE_TIMER1_CNT, 0);
break;
default:
return -1;
}
return 0;
}
/**
* @brief stop and clear the specific secure timer
*
* @param[in] no timer number
* @return 0 success, -1 failure
*/
int32_t arc_secure_timer_stop(const uint32_t no)
{
switch (no) {
case SECURE_TIMER_0:
arc_aux_write(AUX_SECURE_TIMER0_CTRL, 0);
arc_aux_write(AUX_SECURE_TIMER0_LIMIT, 0);
arc_aux_write(AUX_SECURE_TIMER0_CNT, 0);
break;
case SECURE_TIMER_1:
arc_aux_write(AUX_SECURE_TIMER1_CTRL, 0);
arc_aux_write(AUX_SECURE_TIMER1_LIMIT, 0);
arc_aux_write(AUX_SECURE_TIMER1_CNT, 0);
break;
default:
return -1;
}
return 0;
}
/**
* @brief get secure timer current tick
*
* @param[in] no timer number
* @param[out] val, timer value
* @return 0 success, -1 failure
*/
int32_t arc_secure_timer_current(const uint32_t no, void *val)
{
switch (no) {
case SECURE_TIMER_0:
*((uint32_t *)val) = arc_aux_read(AUX_SECURE_TIMER0_CNT);
break;
case SECURE_TIMER_1:
*((uint32_t *)val) = arc_aux_read(AUX_SECURE_TIMER1_CNT);
break;
default:
return -1;
}
return 0;
}
/**
* @brief clear the interrupt pending bit of timer
*
* @param[in] no timer number
* @return 0 success, -1 failure
*/
int32_t arc_secure_timer_int_clear(const uint32_t no)
{
uint32_t val;
switch (no) {
case SECURE_TIMER_0:
val = arc_aux_read(AUX_SECURE_TIMER0_CTRL);
val &= ~TIMER_CTRL_IP;
arc_aux_write(AUX_SECURE_TIMER0_CTRL, val);
break;
case SECURE_TIMER_1:
val = arc_aux_read(AUX_SECURE_TIMER1_CTRL);
val &= ~TIMER_CTRL_IP;
arc_aux_write(AUX_SECURE_TIMER1_CTRL, val);
break;
default:
return -1;
}
return 0;
}
/**
* @brief init internal secure timer
*/
void arc_secure_timer_init(void)
{
if (arc_secure_timer_present(SECURE_TIMER_0)) {
arc_secure_timer_stop(SECURE_TIMER_0);
}
if (arc_secure_timer_present(SECURE_TIMER_1)) {
arc_secure_timer_stop(SECURE_TIMER_1);
}
}
#endif /* ARC_FEATURE_SEC_TIMER1_PRESENT && ARC_FEATURE_SEC_TIMER0_PRESENT */
/**
* @brief provide US delay function
*
* @param[in] usecs US to delay
*/
void arc_delay_us(uint32_t usecs)
{
if (usecs == 0) {
return;
}
usecs = usecs * gl_loops_per_jiffy / gl_count;
__asm__ __volatile__ (
" .align 4 \n"
" mov %%lp_count, %0 \n"
" lp 1f \n"
" nop \n"
"1: \n"
:
: "r" (usecs)
: "lp_count");
}
/**
* @brief calibrate delay
*
* @param[in] board cpu clock
* @return loops_per_jiffy
*/
uint64_t arc_timer_calibrate_delay(uint32_t cpu_clock)
{
unsigned long loopbit;
int lps_precision = LPS_PREC;
volatile uint64_t loops_per_jiffy;
uint32_t timer0_limit;
uint32_t status;
gl_loops_per_jiffy = 1;
gl_count = 1;
cpu_clock /= 1000;
status = cpu_lock_save();
timer0_limit = arc_aux_read(AUX_TIMER0_LIMIT);
arc_aux_write(AUX_TIMER0_LIMIT, 0xFFFFFFFF);
loops_per_jiffy = (1 << 4);
while ((loops_per_jiffy <<= 1) != 0) {
arc_aux_write(AUX_TIMER0_CNT, 0);
arc_delay_us(loops_per_jiffy);
if (arc_aux_read(AUX_TIMER0_CNT) > cpu_clock) {
break;
}
}
loops_per_jiffy >>= 1;
loopbit = loops_per_jiffy;
while (lps_precision-- && (loopbit >>= 1)) {
loops_per_jiffy |= loopbit;
arc_aux_write(AUX_TIMER0_CNT, 0);
arc_delay_us(loops_per_jiffy);
if (arc_aux_read(AUX_TIMER0_CNT) > cpu_clock) {
loops_per_jiffy &= ~loopbit;
}
}
gl_loops_per_jiffy = loops_per_jiffy;
gl_count = 1000;
arc_aux_write(AUX_TIMER0_CNT, 0);
arc_aux_write(AUX_TIMER0_LIMIT, timer0_limit);
cpu_unlock_restore(status);
return loops_per_jiffy;
}
| 2.046875 | 2 |
2024-11-18T22:23:49.299019+00:00 | 2020-09-14T10:39:21 | c71e6f9233ea30d36339fdaca3ecf3c57b388135 | {
"blob_id": "c71e6f9233ea30d36339fdaca3ecf3c57b388135",
"branch_name": "refs/heads/master",
"committer_date": "2020-09-14T10:39:21",
"content_id": "3d2c570c736a160164c4948a5b71e687aadd357b",
"detected_licenses": [
"MIT"
],
"directory_id": "82033329b69d487f0f5442e6728a5c167f6097e7",
"extension": "h",
"filename": "EntryTypeInterfaceIsNumber.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 170529569,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1181,
"license": "MIT",
"license_type": "permissive",
"path": "/MachineLearningEngine/TestVectorEngineDatastructures/EntryTypeInterfaceIsNumber.h",
"provenance": "stackv2-0115.json.gz:74546",
"repo_name": "Gronne/CPP-Matrix-Engine",
"revision_date": "2020-09-14T10:39:21",
"revision_id": "97aaec75ebf949dc84aaddafa80bcc4d82552c50",
"snapshot_id": "68859f9539fe92683feb3c319cb292c009c227fa",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Gronne/CPP-Matrix-Engine/97aaec75ebf949dc84aaddafa80bcc4d82552c50/MachineLearningEngine/TestVectorEngineDatastructures/EntryTypeInterfaceIsNumber.h",
"visit_date": "2022-12-09T18:38:08.663338"
} | stackv2 | #pragma once
#include "VectorEngineHeaders.h"
TEST(TensorCoreTensorCoreEntryTypeIsNumber, IsNumber_true)
{
EntryTypeNumber NumberObject(5);
EntryType object(NumberObject);
EXPECT_TRUE(object.isNumber());
}
TEST(TensorCoreTensorCoreEntryTypeIsNumber, IsNumber_false0)
{
EntryType object;
EXPECT_FALSE(object.isNumber());
}
TEST(TensorCoreTensorCoreEntryTypeIsNumber, IsNumber_false1)
{
EntryTypeNumber NumberObject;
EntryType object(NumberObject);
EXPECT_FALSE(object.isNumber());
}
TEST(TensorCoreTensorCoreEntryTypeIsNumber, IsNumber_false2)
{
EntryTypeComplex complexObject;
EntryType object(complexObject);
EXPECT_FALSE(object.isNumber());
}
TEST(TensorCoreTensorCoreEntryTypeIsNumber, IsNumber_false3)
{
EntryTypeComplex complexObject(5);
EntryType object(complexObject);
EXPECT_FALSE(object.isNumber());
}
TEST(TensorCoreTensorCoreEntryTypeIsNumber, IsNumber_false4)
{
EntryTypeVariable variableObject;
EntryType object(variableObject);
EXPECT_FALSE(object.isNumber());
}
TEST(TensorCoreTensorCoreEntryTypeIsNumber, IsNumber_false5)
{
EntryTypeVariable variableObject("a");
EntryType object(variableObject);
EXPECT_FALSE(object.isNumber());
} | 2.03125 | 2 |
2024-11-18T22:23:49.519166+00:00 | 2023-07-30T17:41:18 | 953873992afb7199a1c9d6ddc76e6380785a847e | {
"blob_id": "953873992afb7199a1c9d6ddc76e6380785a847e",
"branch_name": "refs/heads/main",
"committer_date": "2023-07-30T17:41:18",
"content_id": "07592e2063686a0bb99cb196c9165c9d5d5a5474",
"detected_licenses": [
"BSD-3-Clause",
"Apache-2.0"
],
"directory_id": "0ac7388d092db127a5f34952a985ee3cfb3ca028",
"extension": "c",
"filename": "tst_h_dimscales2.c",
"fork_events_count": 18,
"gha_created_at": "2020-10-03T18:28:43",
"gha_event_created_at": "2023-09-13T17:43:40",
"gha_language": "C++",
"gha_license_id": "Apache-2.0",
"github_id": 300949372,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 40801,
"license": "BSD-3-Clause,Apache-2.0",
"license_type": "permissive",
"path": "/deps/libnetcdf/netcdf/h5_test/tst_h_dimscales2.c",
"provenance": "stackv2-0115.json.gz:74808",
"repo_name": "mmomtchev/node-gdal-async",
"revision_date": "2023-07-30T17:41:18",
"revision_id": "5c75d3d98989c4c246e54bb7ccff3a00d5cc3417",
"snapshot_id": "49161ab6864341b1f0dd8b656c74290c63061c77",
"src_encoding": "UTF-8",
"star_events_count": 96,
"url": "https://raw.githubusercontent.com/mmomtchev/node-gdal-async/5c75d3d98989c4c246e54bb7ccff3a00d5cc3417/deps/libnetcdf/netcdf/h5_test/tst_h_dimscales2.c",
"visit_date": "2023-08-07T11:44:44.011002"
} | stackv2 | /* This is part of the netCDF package.
Copyright 2018 University Corporation for Atmospheric Research/Unidata
See COPYRIGHT file for conditions of use.
Test HDF5 file code. These are not intended to be exhaustive tests,
but they use HDF5 the same way that netCDF-4 does, so if these
tests don't work, than netCDF-4 won't work either.
*/
#include "h5_err_macros.h"
#include <hdf5.h>
#include <H5DSpublic.h>
#include <ncdimscale.h>
#define FILE_NAME "tst_h_dimscales2.h5"
#define DIMSCALE_NAME "dimscale"
#define VAR1_NAME "var1"
#define NDIMS 1
#define DIM1_LEN 3
#define NAME_ATTRIBUTE "dimscale_name_attribute"
#define DIMSCALE_LABEL "dimscale_label"
#define STR_LEN 255
herr_t alien_visitor(hid_t did, unsigned dim, hid_t dsid,
void *visitor_data)
{
char name1[STR_LEN];
HDF5_OBJID_T *objid = visitor_data;
/* This should get "/var1", the name of the dataset that the scale
* is attached to. */
if (H5Iget_name(did, name1, STR_LEN) < 0) ERR;
if (strcmp(&name1[1], VAR1_NAME)) ERR;
/* Get more info on the dimscale object.*/
#if H5_VERSION_GE(1,12,0)
H5O_info2_t statbuf;
if (H5Oget_info3(dsid, &statbuf, H5O_INFO_BASIC ) < 0) ERR;
objid->fileno = statbuf.fileno;
objid->token = statbuf.token;
#else
H5G_stat_t statbuf;
if (H5Gget_objinfo(dsid, ".", 1, &statbuf) < 0) ERR;
objid->fileno[0] = statbuf.fileno[0];
objid->objno[0] = statbuf.objno[0];
objid->fileno[1] = statbuf.fileno[1];
objid->objno[1] = statbuf.objno[1];
#endif
return 0;
}
herr_t alien_visitor2(hid_t did, unsigned dim, hid_t dsid, void *visitor_data)
{
HDF5_OBJID_T *objid = visitor_data;
/* Get obj id of the dimscale object. THis will be used later to
* match dimensions to dimscales. */
#if H5_VERSION_GE(1,12,0)
H5O_info2_t statbuf;
if (H5Oget_info3(dsid, &statbuf, H5O_INFO_BASIC ) < 0) ERR;
objid->fileno = statbuf.fileno;
objid->token = statbuf.token;
#else
H5G_stat_t statbuf;
if (H5Gget_objinfo(dsid, ".", 1, &statbuf) < 0) ERR;
objid->fileno[0] = statbuf.fileno[0];
objid->objno[0] = statbuf.objno[0];
objid->fileno[1] = statbuf.fileno[1];
objid->objno[1] = statbuf.objno[1];
#endif
return 0;
}
int
main()
{
printf("\n*** Checking HDF5 dimscales some more.\n");
printf("*** Creating a file with one var with one dimension scale...");
{
hid_t fileid, spaceid, datasetid, dimscaleid, cparmsid;
hsize_t dims[NDIMS] = {DIM1_LEN}, maxdims[NDIMS] = {H5S_UNLIMITED};
/* Create file. */
if ((fileid = H5Fcreate(FILE_NAME, H5F_ACC_TRUNC, H5P_DEFAULT,
H5P_DEFAULT)) < 0) ERR;
/* Create the space that will be used both for the dimscale and
* the 1D dataset that will attach it. */
if ((spaceid = H5Screate_simple(NDIMS, dims, maxdims)) < 0) ERR;
/* Modify dataset creation properties, i.e. enable chunking. */
dims[0] = 1;
if ((cparmsid = H5Pcreate(H5P_DATASET_CREATE)) < 0) ERR;
if (H5Pset_chunk(cparmsid, NDIMS, dims) < 0) ERR;
/* Create our dimension scale, as an unlimited dataset. */
if ((dimscaleid = H5Dcreate1(fileid, DIMSCALE_NAME, H5T_NATIVE_INT,
spaceid, cparmsid)) < 0) ERR;
if (H5DSset_scale(dimscaleid, NAME_ATTRIBUTE) < 0) ERR;
/* Create a variable which uses it. */
if ((datasetid = H5Dcreate1(fileid, VAR1_NAME, H5T_NATIVE_INT,
spaceid, cparmsid)) < 0) ERR;
if (H5DSattach_scale(datasetid, dimscaleid, 0) < 0) ERR;
if (H5DSset_label(datasetid, 0, DIMSCALE_LABEL) < 0) ERR;
/* Fold up our tents. */
if (H5Dclose(dimscaleid) < 0 ||
H5Dclose(datasetid) < 0 ||
H5Sclose(spaceid) < 0 ||
H5Fclose(fileid) < 0) ERR;
}
SUMMARIZE_ERR;
printf("*** Checking that one var, one dimscale file can be read...");
{
hid_t fileid, spaceid = 0, datasetid = 0;
hsize_t num_obj, i;
int obj_class;
char obj_name[STR_LEN + 1];
char dimscale_name[STR_LEN+1];
htri_t is_scale;
char label[STR_LEN+1];
int num_scales;
hsize_t dims[1], maxdims[1];
#if H5_VERSION_GE(1,12,0)
H5O_info2_t statbuf;
#else
H5G_stat_t statbuf;
#endif
HDF5_OBJID_T dimscale_obj, vars_dimscale_obj;
/* Open the file. */
if ((fileid = H5Fopen(FILE_NAME, H5F_ACC_RDWR, H5P_DEFAULT)) < 0) ERR;
/* Loop through objects in the root group. */
if (H5Gget_num_objs(fileid, &num_obj) < 0) ERR;
for (i=0; i<num_obj; i++)
{
/* Get the type (i.e. group, dataset, etc.), and the name of
* the object. */
if ((obj_class = H5Gget_objtype_by_idx(fileid, i)) < 0) ERR;
if (H5Gget_objname_by_idx(fileid, i, obj_name, STR_LEN) < 0) ERR;
/* Deal with object based on its obj_class. */
switch(obj_class)
{
case H5G_GROUP:
break;
case H5G_DATASET:
/* Open the dataset. */
if ((datasetid = H5Dopen1(fileid, obj_name)) < 0) ERR;
/* This should be an unlimited dataset. */
if ((spaceid = H5Dget_space(datasetid)) < 0) ERR;
if (H5Sget_simple_extent_dims(spaceid, dims, maxdims) < 0) ERR;
if (maxdims[0] != H5S_UNLIMITED) ERR;
/* Is this a dimscale? */
if ((is_scale = H5DSis_scale(datasetid)) < 0) ERR;
if (is_scale && strcmp(obj_name, DIMSCALE_NAME)) ERR;
if (is_scale)
{
/* A dimscale comes with a NAME attribute, in
* addition to its real name. */
if (H5DSget_scale_name(datasetid, dimscale_name, STR_LEN) < 0) ERR;
if (strcmp(dimscale_name, NAME_ATTRIBUTE)) ERR;
/* fileno and objno uniquely identify an object and a
* HDF5 file. */
#if H5_VERSION_GE(1,12,0)
if (H5Oget_info3(datasetid, &statbuf, H5O_INFO_BASIC) < 0) ERR;
dimscale_obj.fileno = statbuf.fileno;
dimscale_obj.token = statbuf.token;
#else
if (H5Gget_objinfo(datasetid, ".", 1, &statbuf) < 0) ERR;
dimscale_obj.fileno[0] = statbuf.fileno[0];
dimscale_obj.objno[0] = statbuf.objno[0];
dimscale_obj.fileno[1] = statbuf.fileno[1];
dimscale_obj.objno[1] = statbuf.objno[1];
#endif
}
else
{
/* Here's how to get the number of scales attached
* to the dataset's dimension 0. */
if ((num_scales = H5DSget_num_scales(datasetid, 0)) < 0) ERR;
if (num_scales != 1) ERR;
/* Go through all dimscales for this var and learn about them. */
if (H5DSiterate_scales(datasetid, 0, NULL, alien_visitor,
&vars_dimscale_obj) < 0) ERR;
#if H5_VERSION_GE(1,12,0)
int token_cmp;
if (H5Otoken_cmp(datasetid,
&vars_dimscale_obj.token,
&dimscale_obj.token, &token_cmp) < 0) ERR;
if (vars_dimscale_obj.fileno != dimscale_obj.fileno ||
token_cmp != 0) ERR;
#else
if (vars_dimscale_obj.fileno[0] != dimscale_obj.fileno[0] ||
vars_dimscale_obj.objno[0] != dimscale_obj.objno[0] ||
vars_dimscale_obj.fileno[1] != dimscale_obj.fileno[1] ||
vars_dimscale_obj.objno[1] != dimscale_obj.objno[1]) ERR;
#endif
/* There's also a label for dimension 0. */
if (H5DSget_label(datasetid, 0, label, STR_LEN) < 0) ERR;
}
if (H5Dclose(datasetid) < 0) ERR;
break;
case H5G_TYPE:
break;
case H5G_LINK:
break;
default:
printf("Unknown object class %d!", obj_class);
}
}
/* Close up the shop. */
if (H5Sclose(spaceid) < 0 ||
H5Fclose(fileid) < 0) ERR;
}
SUMMARIZE_ERR;
printf("*** Creating a file with one var with two dimension scales...");
{
#define LAT_LEN 3
#define LON_LEN 2
#define DIMS_2 2
#define LAT_NAME "lat"
#define LON_NAME "lon"
#define PRES_NAME "pres"
hid_t fileid, lat_spaceid, lon_spaceid, pres_spaceid;
hid_t pres_datasetid, lat_dimscaleid, lon_dimscaleid;
hsize_t dims[DIMS_2];
/* Create file. */
if ((fileid = H5Fcreate(FILE_NAME, H5F_ACC_TRUNC, H5P_DEFAULT,
H5P_DEFAULT)) < 0) ERR;
/* Create the spaces that will be used for the dimscales. */
dims[0] = LAT_LEN;
if ((lat_spaceid = H5Screate_simple(1, dims, dims)) < 0) ERR;
dims[0] = LON_LEN;
if ((lon_spaceid = H5Screate_simple(1, dims, dims)) < 0) ERR;
/* Create the space for the dataset. */
dims[0] = LAT_LEN;
dims[1] = LON_LEN;
if ((pres_spaceid = H5Screate_simple(DIMS_2, dims, dims)) < 0) ERR;
/* Create our dimension scales. */
if ((lat_dimscaleid = H5Dcreate1(fileid, LAT_NAME, H5T_NATIVE_INT,
lat_spaceid, H5P_DEFAULT)) < 0) ERR;
if (H5DSset_scale(lat_dimscaleid, NULL) < 0) ERR;
if ((lon_dimscaleid = H5Dcreate1(fileid, LON_NAME, H5T_NATIVE_INT,
lon_spaceid, H5P_DEFAULT)) < 0) ERR;
if (H5DSset_scale(lon_dimscaleid, NULL) < 0) ERR;
/* Create a variable which uses these two dimscales. */
if ((pres_datasetid = H5Dcreate1(fileid, PRES_NAME, H5T_NATIVE_FLOAT,
pres_spaceid, H5P_DEFAULT)) < 0) ERR;
if (H5DSattach_scale(pres_datasetid, lat_dimscaleid, 0) < 0) ERR;
if (H5DSattach_scale(pres_datasetid, lon_dimscaleid, 1) < 0) ERR;
/* Fold up our tents. */
if (H5Dclose(lat_dimscaleid) < 0 ||
H5Dclose(lon_dimscaleid) < 0 ||
H5Dclose(pres_datasetid) < 0 ||
H5Sclose(lat_spaceid) < 0 ||
H5Sclose(lon_spaceid) < 0 ||
H5Sclose(pres_spaceid) < 0 ||
H5Fclose(fileid) < 0) ERR;
}
SUMMARIZE_ERR;
printf("*** Checking that one var, two dimscales file can be read...");
{
#define NDIMS2 2
hid_t fileid, spaceid = 0, datasetid = 0;
hsize_t num_obj, i;
int obj_class;
char obj_name[STR_LEN + 1];
htri_t is_scale;
int num_scales;
hsize_t dims[NDIMS2], maxdims[NDIMS2];
#if H5_VERSION_GE(1,12,0)
H5O_info2_t statbuf;
#else
H5G_stat_t statbuf;
#endif
HDF5_OBJID_T dimscale_obj[2], vars_dimscale_obj[2];
int dimscale_cnt = 0;
int d, ndims;
/* Open the file. */
if ((fileid = H5Fopen(FILE_NAME, H5F_ACC_RDWR, H5P_DEFAULT)) < 0) ERR;
/* Loop through objects in the root group. */
if (H5Gget_num_objs(fileid, &num_obj) < 0) ERR;
for (i=0; i<num_obj; i++)
{
/* Get the type (i.e. group, dataset, etc.), and the name of
* the object. */
if ((obj_class = H5Gget_objtype_by_idx(fileid, i)) < 0) ERR;
if (H5Gget_objname_by_idx(fileid, i, obj_name, STR_LEN) < 0) ERR;
/* Deal with object based on its obj_class. */
switch(obj_class)
{
case H5G_GROUP:
break;
case H5G_DATASET:
/* Open the dataset. */
if ((datasetid = H5Dopen1(fileid, obj_name)) < 0) ERR;
/* Get space info. */
if ((spaceid = H5Dget_space(datasetid)) < 0) ERR;
if (H5Sget_simple_extent_dims(spaceid, dims, maxdims) < 0) ERR;
if ((ndims = H5Sget_simple_extent_ndims(spaceid)) < 0) ERR;
if (ndims > NDIMS2) ERR;
/* Is this a dimscale? */
if ((is_scale = H5DSis_scale(datasetid)) < 0) ERR;
if (is_scale)
{
/* fileno and objno uniquely identify an object and a
* HDF5 file. */
#if H5_VERSION_GE(1,12,0)
if (H5Oget_info3(datasetid, &statbuf, H5O_INFO_BASIC) < 0) ERR;
dimscale_obj[dimscale_cnt].fileno = statbuf.fileno;
dimscale_obj[dimscale_cnt].token = statbuf.token;
#else
if (H5Gget_objinfo(datasetid, ".", 1, &statbuf) < 0) ERR;
dimscale_obj[dimscale_cnt].fileno[0] = statbuf.fileno[0];
dimscale_obj[dimscale_cnt].objno[0] = statbuf.objno[0];
dimscale_obj[dimscale_cnt].fileno[1] = statbuf.fileno[1];
dimscale_obj[dimscale_cnt].objno[1] = statbuf.objno[1];
#endif
dimscale_cnt++;
}
else
{
/* Here's how to get the number of scales attached
* to the dataset's dimension 0 and 1. */
if ((num_scales = H5DSget_num_scales(datasetid, 0)) < 0) ERR;
if (num_scales != 1) ERR;
if ((num_scales = H5DSget_num_scales(datasetid, 1)) < 0) ERR;
if (num_scales != 1) ERR;
/* Go through all dimscales for this var and learn about them. */
for (d = 0; d < ndims; d++)
{
if (H5DSiterate_scales(datasetid, d, NULL, alien_visitor2,
&(vars_dimscale_obj[d])) < 0) ERR;
/* Verify that the object ids passed from the
* alien_visitor2 function match the ones we found
* for the lat and lon datasets. */
#if H5_VERSION_GE(1,12,0)
int token_cmp;
if (H5Otoken_cmp(datasetid,
&vars_dimscale_obj[d].token,
&dimscale_obj[d].token, &token_cmp) < 0) ERR;
if (vars_dimscale_obj[d].fileno != dimscale_obj[d].fileno ||
token_cmp != 0) ERR;
#else
if (vars_dimscale_obj[d].fileno[0] != dimscale_obj[d].fileno[0] ||
vars_dimscale_obj[d].objno[0] != dimscale_obj[d].objno[0]) ERR;
if (vars_dimscale_obj[d].fileno[1] != dimscale_obj[d].fileno[1] ||
vars_dimscale_obj[d].objno[1] != dimscale_obj[d].objno[1]) ERR;
#endif
}
}
if (H5Dclose(datasetid) < 0) ERR;
if (H5Sclose(spaceid) < 0) ERR;
break;
case H5G_TYPE:
break;
case H5G_LINK:
break;
default:
printf("Unknown object class %d!", obj_class);
}
}
/* Close up the shop. */
if (H5Fclose(fileid) < 0) ERR;
}
SUMMARIZE_ERR;
printf("*** Creating a file with one var with two unlimited dimension scales...");
{
#define U1_LEN 3
#define U2_LEN 2
#define DIMS2 2
#define U1_NAME "u1"
#define U2_NAME "u2"
#define VNAME "v1"
hid_t fapl_id, fcpl_id, grpid, plistid, plistid2;
hid_t fileid, lat_spaceid, lon_spaceid, pres_spaceid;
hid_t pres_datasetid, lat_dimscaleid, lon_dimscaleid;
hsize_t dims[DIMS2], maxdims[DIMS2], chunksize[DIMS2] = {10, 10};
hid_t spaceid = 0, datasetid = 0;
hsize_t num_obj, i;
int obj_class;
char obj_name[STR_LEN + 1];
htri_t is_scale;
int num_scales;
#if H5_VERSION_GE(1,12,0)
H5O_info2_t statbuf;
#else
H5G_stat_t statbuf;
#endif
HDF5_OBJID_T dimscale_obj[2], vars_dimscale_obj[2];
int dimscale_cnt = 0;
int d, ndims;
/* Create file access and create property lists. */
if ((fapl_id = H5Pcreate(H5P_FILE_ACCESS)) < 0) ERR;
if ((fcpl_id = H5Pcreate(H5P_FILE_CREATE)) < 0) ERR;
/* Set latest_format in access propertly list. This ensures that
* the latest, greatest, HDF5 versions are used in the file. */
if (H5Pset_libver_bounds(fapl_id, H5F_LIBVER_LATEST, H5F_LIBVER_LATEST) < 0) ERR;
/* Set H5P_CRT_ORDER_TRACKED in the creation property list. This
* turns on HDF5 creation ordering in the file. */
if (H5Pset_link_creation_order(fcpl_id, (H5P_CRT_ORDER_TRACKED |
H5P_CRT_ORDER_INDEXED)) < 0) ERR;
if (H5Pset_attr_creation_order(fcpl_id, (H5P_CRT_ORDER_TRACKED |
H5P_CRT_ORDER_INDEXED)) < 0) ERR;
/* Create file. */
if ((fileid = H5Fcreate(FILE_NAME, H5F_ACC_TRUNC, fcpl_id, fapl_id)) < 0) ERR;
/* Open the root group. */
if ((grpid = H5Gopen2(fileid, "/", H5P_DEFAULT)) < 0) ERR;
/* Create the spaces that will be used for the dimscales. */
dims[0] = 0;
maxdims[0] = H5S_UNLIMITED;
if ((lat_spaceid = H5Screate_simple(1, dims, maxdims)) < 0) ERR;
if ((lon_spaceid = H5Screate_simple(1, dims, maxdims)) < 0) ERR;
/* Create the space for the dataset. */
dims[0] = 0;
dims[1] = 0;
maxdims[0] = H5S_UNLIMITED;
maxdims[1] = H5S_UNLIMITED;
if ((pres_spaceid = H5Screate_simple(DIMS2, dims, maxdims)) < 0) ERR;
/* Set up the dataset creation property list for the two dimensions. */
if ((plistid = H5Pcreate(H5P_DATASET_CREATE)) < 0) ERR;
if (H5Pset_chunk(plistid, 1, chunksize) < 0) ERR;
if (H5Pset_attr_creation_order(plistid, H5P_CRT_ORDER_TRACKED|
H5P_CRT_ORDER_INDEXED) < 0) ERR;
/* Create our dimension scales. */
if ((lat_dimscaleid = H5Dcreate1(grpid, U1_NAME, H5T_NATIVE_INT,
lat_spaceid, plistid)) < 0) ERR;
if (H5DSset_scale(lat_dimscaleid, NULL) < 0) ERR;
if ((lon_dimscaleid = H5Dcreate1(grpid, U2_NAME, H5T_NATIVE_INT,
lon_spaceid, plistid)) < 0) ERR;
if (H5DSset_scale(lon_dimscaleid, NULL) < 0) ERR;
/* Set up the dataset creation property list for the variable. */
if ((plistid2 = H5Pcreate(H5P_DATASET_CREATE)) < 0) ERR;
if (H5Pset_chunk(plistid2, DIMS2, chunksize) < 0) ERR;
if (H5Pset_attr_creation_order(plistid2, H5P_CRT_ORDER_TRACKED|
H5P_CRT_ORDER_INDEXED) < 0) ERR;
/* Create a variable which uses these two dimscales. */
if ((pres_datasetid = H5Dcreate1(grpid, VNAME, H5T_NATIVE_DOUBLE, pres_spaceid,
plistid2)) < 0) ERR;
if (H5DSattach_scale(pres_datasetid, lat_dimscaleid, 0) < 0) ERR;
if (H5DSattach_scale(pres_datasetid, lon_dimscaleid, 1) < 0) ERR;
/* Close down the show. */
if (H5Pclose(fapl_id) < 0 ||
H5Pclose(fcpl_id) < 0 ||
H5Dclose(lat_dimscaleid) < 0 ||
H5Dclose(lon_dimscaleid) < 0 ||
H5Dclose(pres_datasetid) < 0 ||
H5Sclose(lat_spaceid) < 0 ||
H5Sclose(lon_spaceid) < 0 ||
H5Sclose(pres_spaceid) < 0 ||
H5Pclose(plistid) < 0 ||
H5Pclose(plistid2) < 0 ||
H5Gclose(grpid) < 0 ||
H5Fclose(fileid) < 0) ERR;
/* Open the file. */
if ((fileid = H5Fopen(FILE_NAME, H5F_ACC_RDWR, H5P_DEFAULT)) < 0) ERR;
if ((grpid = H5Gopen2(fileid, "/", H5P_DEFAULT)) < 0) ERR;
/* Loop through objects in the root group. */
if (H5Gget_num_objs(grpid, &num_obj) < 0) ERR;
for (i = 0; i < num_obj; i++)
{
/*Get the type (i.e. group, dataset, etc.), and the name of
the object. */
if ((obj_class = H5Gget_objtype_by_idx(grpid, i)) < 0) ERR;
if (H5Gget_objname_by_idx(grpid, i, obj_name, STR_LEN) < 0) ERR;
/* Deal with object based on its obj_class. */
switch(obj_class)
{
case H5G_GROUP:
break;
case H5G_DATASET:
/* Open the dataset. */
if ((datasetid = H5Dopen1(grpid, obj_name)) < 0) ERR;
/* Get space info. */
if ((spaceid = H5Dget_space(datasetid)) < 0) ERR;
if (H5Sget_simple_extent_dims(spaceid, dims, maxdims) < 0) ERR;
if ((ndims = H5Sget_simple_extent_ndims(spaceid)) < 0) ERR;
/* Is this a dimscale? */
if ((is_scale = H5DSis_scale(datasetid)) < 0) ERR;
if (is_scale)
{
/* fileno and objno uniquely identify an object and a
* HDF5 file. */
#if H5_VERSION_GE(1,12,0)
if (H5Oget_info3(datasetid, &statbuf, H5O_INFO_BASIC) < 0) ERR;
dimscale_obj[dimscale_cnt].fileno = statbuf.fileno;
dimscale_obj[dimscale_cnt].token = statbuf.token;
#else
if (H5Gget_objinfo(datasetid, ".", 1, &statbuf) < 0) ERR;
dimscale_obj[dimscale_cnt].fileno[0] = statbuf.fileno[0];
dimscale_obj[dimscale_cnt].objno[0] = statbuf.objno[0];
dimscale_obj[dimscale_cnt].fileno[1] = statbuf.fileno[1];
dimscale_obj[dimscale_cnt].objno[1] = statbuf.objno[1];
#endif
dimscale_cnt++;
}
else
{
/* Here's how to get the number of scales attached
* to the dataset's dimension 0 and 1. */
if ((num_scales = H5DSget_num_scales(datasetid, 0)) < 0) ERR;
if (num_scales != 1) ERR;
if ((num_scales = H5DSget_num_scales(datasetid, 1)) < 0) ERR;
if (num_scales != 1) ERR;
/* Go through all dimscales for this var and learn about them. */
for (d = 0; d < ndims; d++)
{
if (H5DSiterate_scales(datasetid, d, NULL, alien_visitor2,
&(vars_dimscale_obj[d])) < 0) ERR;
/* Verify that the object ids passed from the
* alien_visitor2 function match the ones we found
* for the lat and lon datasets. */
#if H5_VERSION_GE(1,12,0)
int token_cmp;
if (H5Otoken_cmp(datasetid,
&vars_dimscale_obj[d].token,
&dimscale_obj[d].token, &token_cmp) < 0) ERR;
if (vars_dimscale_obj[d].fileno != dimscale_obj[d].fileno ||
token_cmp != 0) ERR;
#else
if (vars_dimscale_obj[d].fileno[0] != dimscale_obj[d].fileno[0] ||
vars_dimscale_obj[d].objno[0] != dimscale_obj[d].objno[0]) ERR;
if (vars_dimscale_obj[d].fileno[1] != dimscale_obj[d].fileno[1] ||
vars_dimscale_obj[d].objno[1] != dimscale_obj[d].objno[1]) ERR;
#endif
}
}
if (H5Dclose(datasetid) < 0) ERR;
break;
case H5G_TYPE:
break;
case H5G_LINK:
break;
default:
printf("Unknown object class %d!", obj_class);
}
}
/* Check the dimension lengths. */
{
hid_t spaceid1;
hsize_t h5dimlen[DIMS2], h5dimlenmax[DIMS2];
int dataset_ndims;
/* Check U1. */
if ((datasetid = H5Dopen1(grpid, U1_NAME)) < 0) ERR;
if ((spaceid1 = H5Dget_space(datasetid)) < 0) ERR;
if ((dataset_ndims = H5Sget_simple_extent_dims(spaceid1, h5dimlen,
h5dimlenmax)) < 0) ERR;
if (dataset_ndims != 1 || h5dimlen[0] != 0 || h5dimlenmax[0] != H5S_UNLIMITED) ERR;
if (H5Dclose(datasetid) ||
H5Sclose(spaceid1)) ERR;
/* Check U2. */
if ((datasetid = H5Dopen1(grpid, U2_NAME)) < 0) ERR;
if ((spaceid1 = H5Dget_space(datasetid)) < 0) ERR;
if ((dataset_ndims = H5Sget_simple_extent_dims(spaceid1, h5dimlen,
h5dimlenmax)) < 0) ERR;
if (dataset_ndims != 1 || h5dimlen[0] != 0 || h5dimlenmax[0] != H5S_UNLIMITED) ERR;
if (H5Dclose(datasetid) ||
H5Sclose(spaceid1)) ERR;
/* Check V1. */
if ((datasetid = H5Dopen1(grpid, VNAME)) < 0) ERR;
if ((spaceid1 = H5Dget_space(datasetid)) < 0) ERR;
if ((dataset_ndims = H5Sget_simple_extent_dims(spaceid1, h5dimlen,
h5dimlenmax)) < 0) ERR;
if (dataset_ndims != 2 || h5dimlen[0] != 0 || h5dimlen[1] != 0 ||
h5dimlenmax[0] != H5S_UNLIMITED || h5dimlenmax[1] != H5S_UNLIMITED) ERR;
/* All done. */
if (H5Dclose(datasetid) ||
H5Sclose(spaceid1)) ERR;
}
/* Write two hyperslabs. */
{
#define NUM_VALS 3
hid_t file_spaceid, mem_spaceid;
hsize_t h5dimlen[DIMS2], h5dimlenmax[DIMS2], xtend_size[DIMS2] = {1, NUM_VALS};
hsize_t start[DIMS2] = {0, 0};
hsize_t count[DIMS2] = {1, NUM_VALS};
double value[NUM_VALS];
int dataset_ndims;
int i;
/* Set up phony data. */
for (i = 0; i < NUM_VALS; i++)
value[i] = (float)i;
/* Open the dataset, check its dimlens. */
if ((datasetid = H5Dopen1(grpid, VNAME)) < 0) ERR;
if ((file_spaceid = H5Dget_space(datasetid)) < 0) ERR;
if ((dataset_ndims = H5Sget_simple_extent_dims(file_spaceid, h5dimlen,
h5dimlenmax)) < 0) ERR;
if (dataset_ndims != 2 || h5dimlen[0] != 0 || h5dimlen[1] != 0 ||
h5dimlenmax[0] != H5S_UNLIMITED || h5dimlenmax[1] != H5S_UNLIMITED) ERR;
/* Extend the size of the dataset. */
if (H5Dextend(datasetid, xtend_size) < 0) ERR;
if ((file_spaceid = H5Dget_space(datasetid)) < 0) ERR;
/* Check the size. */
if ((dataset_ndims = H5Sget_simple_extent_dims(file_spaceid, h5dimlen,
h5dimlenmax)) < 0) ERR;
if (dataset_ndims != 2 || h5dimlen[0] != 1 || h5dimlen[1] != NUM_VALS ||
h5dimlenmax[0] != H5S_UNLIMITED || h5dimlenmax[1] != H5S_UNLIMITED) ERR;
/* Set up the file and memory spaces. */
if (H5Sselect_hyperslab(file_spaceid, H5S_SELECT_SET,
start, NULL, count, NULL) < 0) ERR;
if ((mem_spaceid = H5Screate_simple(DIMS2, count, NULL)) < 0) ERR;
/* Write a slice of data. */
if (H5Dwrite(datasetid, H5T_NATIVE_DOUBLE, mem_spaceid, file_spaceid,
H5P_DEFAULT, value) < 0)
/* Check the size. */
if ((file_spaceid = H5Dget_space(datasetid)) < 0) ERR;
if ((dataset_ndims = H5Sget_simple_extent_dims(file_spaceid, h5dimlen,
h5dimlenmax)) < 0) ERR;
if (dataset_ndims != 2 || h5dimlen[0] != 1 || h5dimlen[1] != NUM_VALS ||
h5dimlenmax[0] != H5S_UNLIMITED || h5dimlenmax[1] != H5S_UNLIMITED) ERR;
/* Extend the size of the dataset for the second slice. */
xtend_size[0]++;
if (H5Dextend(datasetid, xtend_size) < 0) ERR;
if ((file_spaceid = H5Dget_space(datasetid)) < 0) ERR;
/* Set up the file and memory spaces for a second slice. */
start[0]++;
if (H5Sselect_hyperslab(file_spaceid, H5S_SELECT_SET,
start, NULL, count, NULL) < 0) ERR;
if ((mem_spaceid = H5Screate_simple(DIMS2, count, NULL)) < 0) ERR;
/* Write a second slice of data. */
if (H5Dwrite(datasetid, H5T_NATIVE_DOUBLE, mem_spaceid, file_spaceid,
H5P_DEFAULT, value) < 0)
/* Check the size again. */
if ((file_spaceid = H5Dget_space(datasetid)) < 0) ERR;
if ((dataset_ndims = H5Sget_simple_extent_dims(file_spaceid, h5dimlen,
h5dimlenmax)) < 0) ERR;
if (dataset_ndims != 2 || h5dimlen[0] != 2 || h5dimlen[1] != NUM_VALS ||
h5dimlenmax[0] != H5S_UNLIMITED || h5dimlenmax[1] != H5S_UNLIMITED) ERR;
/* All done. */
if (H5Dclose(datasetid) ||
H5Sclose(mem_spaceid) ||
H5Sclose(file_spaceid)) ERR;
}
/* Close up the shop. */
if (H5Sclose(spaceid)) ERR;
if (H5Gclose(grpid) < 0 ||
H5Fclose(fileid) < 0) ERR;
}
SUMMARIZE_ERR;
printf("*** Checking dimension scales with attached dimension scales...");
{
#define LAT_LEN 3
#define LON_LEN 2
#define TIME_LEN 5
#define LEN_LEN 10
#define DIMS_3 3
#define NUM_DIMSCALES1 4
#define LAT_NAME "lat"
#define LON_NAME "lon"
#define PRES_NAME1 "z_pres"
#define TIME_NAME "time"
#define LEN_NAME "u_len"
hid_t fileid, lat_spaceid, lon_spaceid, time_spaceid, pres_spaceid, len_spaceid;
hid_t pres_datasetid, lat_dimscaleid, lon_dimscaleid, time_dimscaleid, len_dimscaleid;
hid_t fapl_id, fcpl_id;
hsize_t dims[DIMS_3];
hid_t spaceid = 0, datasetid = 0;
hsize_t num_obj, i;
int obj_class;
char obj_name[STR_LEN + 1];
htri_t is_scale;
int num_scales;
hsize_t maxdims[DIMS_3];
#if H5_VERSION_GE(1,12,0)
H5O_info2_t statbuf;
#else
H5G_stat_t statbuf;
#endif
HDF5_OBJID_T dimscale_obj[NUM_DIMSCALES1], vars_dimscale_obj[NUM_DIMSCALES1];
int dimscale_cnt = 0;
int d, ndims;
/* Create file access and create property lists. */
if ((fapl_id = H5Pcreate(H5P_FILE_ACCESS)) < 0) ERR;
if ((fcpl_id = H5Pcreate(H5P_FILE_CREATE)) < 0) ERR;
/* Set latest_format in access propertly list. This ensures that
* the latest, greatest, HDF5 versions are used in the file. */
if (H5Pset_libver_bounds(fapl_id, H5F_LIBVER_LATEST, H5F_LIBVER_LATEST) < 0) ERR;
/* Set H5P_CRT_ORDER_TRACKED in the creation property list. This
* turns on HDF5 creation ordering in the file. */
if (H5Pset_link_creation_order(fcpl_id, (H5P_CRT_ORDER_TRACKED |
H5P_CRT_ORDER_INDEXED)) < 0) ERR;
if (H5Pset_attr_creation_order(fcpl_id, (H5P_CRT_ORDER_TRACKED |
H5P_CRT_ORDER_INDEXED)) < 0) ERR;
/* Create file. */
if ((fileid = H5Fcreate(FILE_NAME, H5F_ACC_TRUNC, fcpl_id, fapl_id)) < 0) ERR;
/* Create the spaces that will be used for the dimscales. */
dims[0] = LAT_LEN;
if ((lat_spaceid = H5Screate_simple(1, dims, dims)) < 0) ERR;
dims[0] = LON_LEN;
if ((lon_spaceid = H5Screate_simple(1, dims, dims)) < 0) ERR;
dims[0] = TIME_LEN;
if ((time_spaceid = H5Screate_simple(1, dims, dims)) < 0) ERR;
dims[0] = LEN_LEN;
if ((len_spaceid = H5Screate_simple(1, dims, dims)) < 0) ERR;
/* Create the space for the dataset. */
dims[0] = LAT_LEN;
dims[1] = LON_LEN;
dims[2] = TIME_LEN;
if ((pres_spaceid = H5Screate_simple(DIMS_3, dims, dims)) < 0) ERR;
/* Create our dimension scales. */
if ((lat_dimscaleid = H5Dcreate1(fileid, LAT_NAME, H5T_NATIVE_INT,
lat_spaceid, H5P_DEFAULT)) < 0) ERR;
if (H5DSset_scale(lat_dimscaleid, NULL) < 0) ERR;
if ((lon_dimscaleid = H5Dcreate1(fileid, LON_NAME, H5T_NATIVE_INT,
lon_spaceid, H5P_DEFAULT)) < 0) ERR;
if (H5DSset_scale(lon_dimscaleid, NULL) < 0) ERR;
if ((time_dimscaleid = H5Dcreate1(fileid, TIME_NAME, H5T_NATIVE_INT,
time_spaceid, H5P_DEFAULT)) < 0) ERR;
if (H5DSset_scale(time_dimscaleid, NULL) < 0) ERR;
if ((len_dimscaleid = H5Dcreate1(fileid, LEN_NAME, H5T_NATIVE_INT,
len_spaceid, H5P_DEFAULT)) < 0) ERR;
if (H5DSset_scale(len_dimscaleid, NULL) < 0) ERR;
/* Create a variable which uses these three dimscales. */
if ((pres_datasetid = H5Dcreate1(fileid, PRES_NAME1, H5T_NATIVE_FLOAT,
pres_spaceid, H5P_DEFAULT)) < 0) ERR;
if (H5DSattach_scale(pres_datasetid, lat_dimscaleid, 0) < 0) ERR;
if (H5DSattach_scale(pres_datasetid, lon_dimscaleid, 1) < 0) ERR;
if (H5DSattach_scale(pres_datasetid, time_dimscaleid, 2) < 0) ERR;
/* Attach a dimscale to a dimscale. Unfortunately, HDF5 does not
* allow this. Woe is me. */
/*if (H5DSattach_scale(time_dimscaleid, len_dimscaleid, 0) < 0) ERR;*/
/* Fold up our tents. */
if (H5Dclose(lat_dimscaleid) < 0 ||
H5Dclose(lon_dimscaleid) < 0 ||
H5Dclose(time_dimscaleid) < 0 ||
H5Dclose(len_dimscaleid) < 0 ||
H5Dclose(pres_datasetid) < 0 ||
H5Sclose(lat_spaceid) < 0 ||
H5Sclose(lon_spaceid) < 0 ||
H5Sclose(time_spaceid) < 0 ||
H5Sclose(pres_spaceid) < 0 ||
H5Sclose(len_spaceid) < 0 ||
H5Pclose(fapl_id) < 0 ||
H5Pclose(fcpl_id) < 0 ||
H5Fclose(fileid) < 0) ERR;
/* Open the file. */
if ((fileid = H5Fopen(FILE_NAME, H5F_ACC_RDWR, H5P_DEFAULT)) < 0) ERR;
/* Loop through objects in the root group. */
if (H5Gget_num_objs(fileid, &num_obj) < 0) ERR;
for (i=0; i<num_obj; i++)
{
/* Get the type (i.e. group, dataset, etc.), and the name of
* the object. */
if ((obj_class = H5Gget_objtype_by_idx(fileid, i)) < 0) ERR;
if (H5Gget_objname_by_idx(fileid, i, obj_name, STR_LEN) < 0) ERR;
/* Deal with object based on its obj_class. */
switch(obj_class)
{
case H5G_GROUP:
break;
case H5G_DATASET:
/* Open the dataset. */
if ((datasetid = H5Dopen1(fileid, obj_name)) < 0) ERR;
/* Get space info. */
if ((spaceid = H5Dget_space(datasetid)) < 0) ERR;
if (H5Sget_simple_extent_dims(spaceid, dims, maxdims) < 0) ERR;
if ((ndims = H5Sget_simple_extent_ndims(spaceid)) < 0) ERR;
/* Is this a dimscale? */
if ((is_scale = H5DSis_scale(datasetid)) < 0) ERR;
if (is_scale)
{
/* fileno and objno uniquely identify an object and a
* HDF5 file. */
#if H5_VERSION_GE(1,12,0)
if (H5Oget_info3(datasetid, &statbuf, H5O_INFO_BASIC) < 0) ERR;
dimscale_obj[dimscale_cnt].fileno = statbuf.fileno;
dimscale_obj[dimscale_cnt].token = statbuf.token;
#else
if (H5Gget_objinfo(datasetid, ".", 1, &statbuf) < 0) ERR;
dimscale_obj[dimscale_cnt].fileno[0] = statbuf.fileno[0];
dimscale_obj[dimscale_cnt].objno[0] = statbuf.objno[0];
dimscale_obj[dimscale_cnt].fileno[1] = statbuf.fileno[1];
dimscale_obj[dimscale_cnt].objno[1] = statbuf.objno[1];
#endif
dimscale_cnt++;
}
else
{
/* Here's how to get the number of scales attached
* to the dataset's dimension 0 and 1. */
if ((num_scales = H5DSget_num_scales(datasetid, 0)) < 0) ERR;
if (num_scales != 1) ERR;
if ((num_scales = H5DSget_num_scales(datasetid, 1)) < 0) ERR;
if (num_scales != 1) ERR;
/* Go through all dimscales for this var and learn about them. */
for (d = 0; d < ndims; d++)
{
if (H5DSiterate_scales(datasetid, d, NULL, alien_visitor2,
&(vars_dimscale_obj[d])) < 0) ERR;
/* Verify that the object ids passed from the
* alien_visitor2 function match the ones we found
* for the lat and lon datasets. */
#if H5_VERSION_GE(1,12,0)
int token_cmp;
if (H5Otoken_cmp(datasetid,
&vars_dimscale_obj[d].token,
&dimscale_obj[d].token, &token_cmp) < 0) ERR;
if (vars_dimscale_obj[d].fileno != dimscale_obj[d].fileno ||
token_cmp != 0) ERR;
#else
if (vars_dimscale_obj[d].fileno[0] != dimscale_obj[d].fileno[0] ||
vars_dimscale_obj[d].objno[0] != dimscale_obj[d].objno[0]) ERR;
if (vars_dimscale_obj[d].fileno[1] != dimscale_obj[d].fileno[1] ||
vars_dimscale_obj[d].objno[1] != dimscale_obj[d].objno[1]) ERR;
#endif
}
}
if (H5Dclose(datasetid) < 0) ERR;
if (H5Sclose(spaceid) < 0) ERR;
break;
case H5G_TYPE:
break;
case H5G_LINK:
break;
default:
printf("Unknown object class %d!", obj_class);
}
}
/* Close up the shop. */
if (H5Fclose(fileid) < 0) ERR;
}
SUMMARIZE_ERR;
printf("*** Checking cration ordering of datasets which are also dimension scales...");
{
#define LAT_LEN 3
#define LON_LEN 2
#define TIME_LEN 5
#define LEN_LEN 10
#define DIMS_3 3
#define NUM_DIMSCALES2 4
#define LAT_NAME "lat"
#define LON_NAME "lon"
#define PRES_NAME1 "z_pres"
#define TIME_NAME "time"
#define LEN_NAME "u_len"
hid_t fileid, lat_spaceid, lon_spaceid, time_spaceid, pres_spaceid, len_spaceid;
hid_t pres_datasetid, lat_dimscaleid, lon_dimscaleid, time_dimscaleid, len_dimscaleid;
hid_t fapl_id, fcpl_id;
hsize_t dims[DIMS_3];
hid_t spaceid = 0, datasetid = 0;
hsize_t num_obj, i;
int obj_class;
char obj_name[STR_LEN + 1];
htri_t is_scale;
int num_scales;
hsize_t maxdims[DIMS_3];
#if H5_VERSION_GE(1,12,0)
H5O_info2_t statbuf;
#else
H5G_stat_t statbuf;
#endif
HDF5_OBJID_T dimscale_obj[NUM_DIMSCALES2], vars_dimscale_obj[NUM_DIMSCALES2];
int dimscale_cnt = 0;
int d, ndims;
/* Create file access and create property lists. */
if ((fapl_id = H5Pcreate(H5P_FILE_ACCESS)) < 0) ERR;
if ((fcpl_id = H5Pcreate(H5P_FILE_CREATE)) < 0) ERR;
/* Set latest_format in access propertly list. This ensures that
* the latest, greatest, HDF5 versions are used in the file. */
if (H5Pset_libver_bounds(fapl_id, H5F_LIBVER_LATEST, H5F_LIBVER_LATEST) < 0) ERR;
/* Set H5P_CRT_ORDER_TRACKED in the creation property list. This
* turns on HDF5 creation ordering in the file. */
if (H5Pset_link_creation_order(fcpl_id, (H5P_CRT_ORDER_TRACKED |
H5P_CRT_ORDER_INDEXED)) < 0) ERR;
if (H5Pset_attr_creation_order(fcpl_id, (H5P_CRT_ORDER_TRACKED |
H5P_CRT_ORDER_INDEXED)) < 0) ERR;
/* Create file. */
if ((fileid = H5Fcreate(FILE_NAME, H5F_ACC_TRUNC, fcpl_id, fapl_id)) < 0) ERR;
/* Create the spaces that will be used for the dimscales. */
dims[0] = LAT_LEN;
if ((lat_spaceid = H5Screate_simple(1, dims, dims)) < 0) ERR;
dims[0] = LON_LEN;
if ((lon_spaceid = H5Screate_simple(1, dims, dims)) < 0) ERR;
dims[0] = TIME_LEN;
if ((time_spaceid = H5Screate_simple(1, dims, dims)) < 0) ERR;
dims[0] = LEN_LEN;
if ((len_spaceid = H5Screate_simple(1, dims, dims)) < 0) ERR;
/* Create the space for the dataset. */
dims[0] = LAT_LEN;
dims[1] = LON_LEN;
dims[2] = TIME_LEN;
if ((pres_spaceid = H5Screate_simple(DIMS_3, dims, dims)) < 0) ERR;
/* Create our dimension scales. */
if ((lat_dimscaleid = H5Dcreate1(fileid, LAT_NAME, H5T_NATIVE_INT,
lat_spaceid, H5P_DEFAULT)) < 0) ERR;
if (H5DSset_scale(lat_dimscaleid, NULL) < 0) ERR;
if ((lon_dimscaleid = H5Dcreate1(fileid, LON_NAME, H5T_NATIVE_INT,
lon_spaceid, H5P_DEFAULT)) < 0) ERR;
if (H5DSset_scale(lon_dimscaleid, NULL) < 0) ERR;
if ((time_dimscaleid = H5Dcreate1(fileid, TIME_NAME, H5T_NATIVE_INT,
time_spaceid, H5P_DEFAULT)) < 0) ERR;
if (H5DSset_scale(time_dimscaleid, NULL) < 0) ERR;
if ((len_dimscaleid = H5Dcreate1(fileid, LEN_NAME, H5T_NATIVE_INT,
len_spaceid, H5P_DEFAULT)) < 0) ERR;
if (H5DSset_scale(len_dimscaleid, NULL) < 0) ERR;
/* Create a variable which uses these three dimscales. */
if ((pres_datasetid = H5Dcreate1(fileid, PRES_NAME1, H5T_NATIVE_FLOAT,
pres_spaceid, H5P_DEFAULT)) < 0) ERR;
if (H5DSattach_scale(pres_datasetid, lat_dimscaleid, 0) < 0) ERR;
if (H5DSattach_scale(pres_datasetid, lon_dimscaleid, 1) < 0) ERR;
if (H5DSattach_scale(pres_datasetid, time_dimscaleid, 2) < 0) ERR;
/* Attach a dimscale to a dimscale. Unfortunately, HDF5 does not
* allow this. Woe is me. */
/*if (H5DSattach_scale(time_dimscaleid, len_dimscaleid, 0) < 0) ERR;*/
/* Fold up our tents. */
if (H5Dclose(lat_dimscaleid) < 0 ||
H5Dclose(lon_dimscaleid) < 0 ||
H5Dclose(time_dimscaleid) < 0 ||
H5Dclose(len_dimscaleid) < 0 ||
H5Dclose(pres_datasetid) < 0 ||
H5Sclose(lat_spaceid) < 0 ||
H5Sclose(lon_spaceid) < 0 ||
H5Sclose(time_spaceid) < 0 ||
H5Sclose(pres_spaceid) < 0 ||
H5Sclose(len_spaceid) < 0 ||
H5Pclose(fapl_id) < 0 ||
H5Pclose(fcpl_id) < 0 ||
H5Fclose(fileid) < 0) ERR;
/* Open the file. */
if ((fileid = H5Fopen(FILE_NAME, H5F_ACC_RDWR, H5P_DEFAULT)) < 0) ERR;
/* Loop through objects in the root group. */
if (H5Gget_num_objs(fileid, &num_obj) < 0) ERR;
for (i=0; i<num_obj; i++)
{
/* Get the type (i.e. group, dataset, etc.), and the name of
* the object. */
if ((obj_class = H5Gget_objtype_by_idx(fileid, i)) < 0) ERR;
if (H5Gget_objname_by_idx(fileid, i, obj_name, STR_LEN) < 0) ERR;
/* Deal with object based on its obj_class. */
switch(obj_class)
{
case H5G_GROUP:
break;
case H5G_DATASET:
/* Open the dataset. */
if ((datasetid = H5Dopen1(fileid, obj_name)) < 0) ERR;
/* Get space info. */
if ((spaceid = H5Dget_space(datasetid)) < 0) ERR;
if (H5Sget_simple_extent_dims(spaceid, dims, maxdims) < 0) ERR;
if ((ndims = H5Sget_simple_extent_ndims(spaceid)) < 0) ERR;
/* Is this a dimscale? */
if ((is_scale = H5DSis_scale(datasetid)) < 0) ERR;
if (is_scale)
{
/* fileno and objno uniquely identify an object and a
* HDF5 file. */
#if H5_VERSION_GE(1,12,0)
if (H5Oget_info3(datasetid, &statbuf, H5O_INFO_BASIC) < 0) ERR;
dimscale_obj[dimscale_cnt].fileno = statbuf.fileno;
dimscale_obj[dimscale_cnt].token = statbuf.token;
#else
if (H5Gget_objinfo(datasetid, ".", 1, &statbuf) < 0) ERR;
dimscale_obj[dimscale_cnt].fileno[0] = statbuf.fileno[0];
dimscale_obj[dimscale_cnt].objno[0] = statbuf.objno[0];
dimscale_obj[dimscale_cnt].fileno[1] = statbuf.fileno[1];
dimscale_obj[dimscale_cnt].objno[1] = statbuf.objno[1];
#endif
dimscale_cnt++;
}
else
{
/* Here's how to get the number of scales attached
* to the dataset's dimension 0 and 1. */
if ((num_scales = H5DSget_num_scales(datasetid, 0)) < 0) ERR;
if (num_scales != 1) ERR;
if ((num_scales = H5DSget_num_scales(datasetid, 1)) < 0) ERR;
if (num_scales != 1) ERR;
/* Go through all dimscales for this var and learn about them. */
for (d = 0; d < ndims; d++)
{
if (H5DSiterate_scales(datasetid, d, NULL, alien_visitor2,
&(vars_dimscale_obj[d])) < 0) ERR;
/* Verify that the object ids passed from the
* alien_visitor2 function match the ones we found
* for the lat and lon datasets. */
#if H5_VERSION_GE(1,12,0)
int token_cmp;
if (H5Otoken_cmp(datasetid,
&vars_dimscale_obj[d].token,
&dimscale_obj[d].token, &token_cmp) < 0) ERR;
if (vars_dimscale_obj[d].fileno != dimscale_obj[d].fileno ||
token_cmp != 0) ERR;
#else
if (vars_dimscale_obj[d].fileno[0] != dimscale_obj[d].fileno[0] ||
vars_dimscale_obj[d].objno[0] != dimscale_obj[d].objno[0]) ERR;
if (vars_dimscale_obj[d].fileno[1] != dimscale_obj[d].fileno[1] ||
vars_dimscale_obj[d].objno[1] != dimscale_obj[d].objno[1]) ERR;
#endif
}
}
if (H5Dclose(datasetid) < 0) ERR;
if (H5Sclose(spaceid) < 0) ERR;
break;
case H5G_TYPE:
break;
case H5G_LINK:
break;
default:
printf("Unknown object class %d!", obj_class);
}
}
/* Close up the shop. */
if (H5Fclose(fileid) < 0) ERR;
}
SUMMARIZE_ERR;
FINAL_RESULTS;
}
| 2.09375 | 2 |
2024-11-18T22:23:49.567716+00:00 | 2020-08-22T01:04:18 | c8fce51ae9f02393b94788a2d4a8bf5f29db4344 | {
"blob_id": "c8fce51ae9f02393b94788a2d4a8bf5f29db4344",
"branch_name": "refs/heads/master",
"committer_date": "2020-08-22T01:04:18",
"content_id": "371b9a66ce3bac9504bd200482b5ac8d60ada6b9",
"detected_licenses": [
"MIT"
],
"directory_id": "86f13ec3782ea6080940768a336eb3ba36a911a2",
"extension": "h",
"filename": "midio.h",
"fork_events_count": 0,
"gha_created_at": "2020-06-04T19:54:47",
"gha_event_created_at": "2020-06-14T23:16:04",
"gha_language": null,
"gha_license_id": null,
"github_id": 269452281,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 576,
"license": "MIT",
"license_type": "permissive",
"path": "/JazzMachine/MidiCsv/midio.h",
"provenance": "stackv2-0115.json.gz:74937",
"repo_name": "10000turtles/OpenHarmonizer",
"revision_date": "2020-08-22T01:04:18",
"revision_id": "b01b2b532ff8fd34cb011db389fb0f81d79565f4",
"snapshot_id": "3e8987cfb4b35ff46c120c4fdd70a97158f42c58",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/10000turtles/OpenHarmonizer/b01b2b532ff8fd34cb011db389fb0f81d79565f4/JazzMachine/MidiCsv/midio.h",
"visit_date": "2022-12-05T09:21:49.250711"
} | stackv2 | /*
MIDI I/O Function Definitions
*/
#include <stdio.h>
extern long readlong(FILE* fp);
extern short readshort(FILE* fp);
extern unsigned long readVarLen(FILE* fp);
extern void readMidiFileHeader(FILE* fp, struct mhead* h);
extern void readMidiTrackHeader(FILE* fp, struct mtrack* t);
extern void writelong(FILE* fp, const long l);
extern void writeshort(FILE* fp, const short s);
extern void writeVarLen(FILE* fp, const unsigned long v);
extern void writeMidiFileHeader(FILE* fp, struct mhead* h);
extern void writeMidiTrackHeader(FILE* fp, struct mtrack* t);
| 2 | 2 |
2024-11-18T22:23:50.153873+00:00 | 2023-09-02T03:38:19 | a8f8231935ba526b7e4166edef58be172789d76a | {
"blob_id": "a8f8231935ba526b7e4166edef58be172789d76a",
"branch_name": "refs/heads/master",
"committer_date": "2023-09-02T03:38:19",
"content_id": "d96da65b8b0742a64596da2d859edc18d98c6860",
"detected_licenses": [
"MIT"
],
"directory_id": "736e760612f2b431c4b2524fe1a4a8e4083c72a1",
"extension": "c",
"filename": "rtsp-header-range.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": 13414,
"license": "MIT",
"license_type": "permissive",
"path": "/librtsp/source/rtsp-header-range.c",
"provenance": "stackv2-0115.json.gz:75588",
"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/librtsp/source/rtsp-header-range.c",
"visit_date": "2023-09-03T17:53:13.722595"
} | stackv2 | // RFC 2326 Real Time Streaming Protocol (RTSP)
//
// 12.29 Range(p53)
// parameter: time. in UTC, specifying the time at which the operation is to be made effective
// Ranges are half-open intervals, including the lower point, but excluding the upper point.
// byte ranges MUST NOT be used
// Range = "Range" ":" 1#ranges-specifier [ ";" "time" "=" utc-time ]
// ranges-specifier = npt-range | utc-range | smpte-range
// smpte/smpte-30-drop/smpte-25: hh:mm:ss[:frames][.subframes] - [hh:mm:ss[:frames][.subframes]] (p17)
// npt: hh:mm:ss[.ms]-[hh:mm:ss[.ms]] | -hh:mm:ss[.ms] | now- (p17)
// clock: YYYYMMDDThhmmss[.fraction]Z - [YYYYMMDDThhmmss[.fraction]Z] (p18)
//
// e.g.
// Range: clock=19960213T143205Z-;time=19970123T143720Z
// Range: smpte-25=10:07:00-10:07:33:05.01,smpte-25=11:07:00-11:07:33:05.01
#include "rtsp-header-range.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <time.h>
#if defined(_WIN32) || defined(_WIN64) || defined(OS_WINDOWS)
#define strncasecmp _strnicmp
#endif
struct time_smpte_t
{
int second; // [0,24*60*60)
int frame; // [0,99]
int subframe; // [0,99]
};
struct time_npt_t
{
int64_t second; // [0,---)
int fraction; // [0,999]
};
struct time_clock_t
{
int second; // [0,24*60*60)
int fraction; // [0,999]
int day; // [0,30]
int month; // [0,11]
int year; // [xxxx]
};
#define RANGE_SPECIAL ",;\r\n"
static uint64_t utc_mktime(const struct tm *t)
{
int mon = t->tm_mon+1, year = t->tm_year+1900;
/* 1..12 -> 11,12,1..10 */
if (0 >= (int) (mon -= 2)) {
mon += 12; /* Puts Feb last since it has leap day */
year -= 1;
}
return ((((uint64_t)
(year/4 - year/100 + year/400 + 367*mon/12 + t->tm_mday) +
year*365 - 719499
)*24 + t->tm_hour /* now have hours */
)*60 + t->tm_min /* now have minutes */
)*60 + t->tm_sec; /* finally seconds */
}
static inline const char* string_token_int(const char* str, int *value)
{
*value = 0;
while ('0' <= *str && *str <= '9')
{
*value = (*value * 10) + (*str - '0');
++str;
}
return str;
}
static inline const char* string_token_int64(const char* str, int64_t *value)
{
*value = 0;
while ('0' <= *str && *str <= '9')
{
*value = (*value * 10) + (*str - '0');
++str;
}
return str;
}
// smpte-time = 1*2DIGIT ":" 1*2DIGIT ":" 1*2DIGIT [ ":" 1*2DIGIT ][ "." 1*2DIGIT ]
// hours:minutes:seconds:frames.subframes
static const char* rtsp_header_range_smpte_time(const char* str, int *hours, int *minutes, int *seconds, int *frames, int *subframes)
{
const char* p;
assert(str);
p = string_token_int(str, hours);
if(*p != ':')
return NULL;
p = string_token_int(p+1, minutes);
if(*p != ':')
return NULL;
p = string_token_int(p+1, seconds);
*frames = 0;
*subframes = 0;
if(*p == ':')
{
p = string_token_int(p+1, frames);
}
if(*p == '.')
{
p = string_token_int(p+1, subframes);
}
return p;
}
// 3.5 SMPTE Relative Timestamps (p16)
// smpte-range = smpte-type "=" smpte-time "-" [ smpte-time ]
// smpte-type = "smpte" | "smpte-30-drop" | "smpte-25"
// Examples:
// smpte=10:12:33:20-
// smpte=10:07:33-
// smpte=10:07:00-10:07:33:05.01
// smpte-25=10:07:00-10:07:33:05.01
static int rtsp_header_range_smpte(const char* fields, struct rtsp_header_range_t* range)
{
const char *p;
int hours, minutes, seconds, frames, subframes;
assert(fields);
p = rtsp_header_range_smpte_time(fields, &hours, &minutes, &seconds, &frames, &subframes);
if(!p || '-' != *p)
return -1;
range->from_value = RTSP_RANGE_TIME_NORMAL;
range->from = (hours%24)*3600 + (minutes%60)*60 + seconds;
range->from = range->from * 1000 + frames % 1000;
assert('-' == *p);
if('\0' == p[1] || strchr(RANGE_SPECIAL, p[1]))
{
range->to_value = RTSP_RANGE_TIME_NOVALUE;
range->to = 0;
}
else
{
p = rtsp_header_range_smpte_time(p+1, &hours, &minutes, &seconds, &frames, &subframes);
if(!p ) return -1;
assert('\0' == p[0] || strchr(RANGE_SPECIAL, p[0]));
range->to_value = RTSP_RANGE_TIME_NORMAL;
range->to = (hours%24)*3600 + (minutes%60)*60 + seconds;
range->to = range->to * 1000 + frames % 1000;
}
return 0;
}
// npt-time = "now" | npt-sec | npt-hhmmss
// npt-sec = 1*DIGIT [ "." *DIGIT ]
// npt-hhmmss = npt-hh ":" npt-mm ":" npt-ss [ "." *DIGIT ]
// npt-hh = 1*DIGIT ; any positive number
// npt-mm = 1*2DIGIT ; 0-59
// npt-ss = 1*2DIGIT ; 0-59
static const char* rtsp_header_range_npt_time(const char* str, uint64_t *seconds, int *fraction)
{
const char* p;
int v1, v2;
assert(str);
str += strspn(str, " \t");
p = strpbrk(str, "-\r\n");
if(!str || (p-str==3 && 0==strncasecmp(str, "now", 3)))
{
*seconds = 0; // now
*fraction = -1;
}
else
{
p = string_token_int64(str, (int64_t*)seconds);
if(*p == ':')
{
// npt-hhmmss
p = string_token_int(p+1, &v1);
if(*p != ':')
return NULL;
p = string_token_int(p+1, &v2);
assert(0 <= v1 && v1 < 60);
assert(0 <= v2 && v2 < 60);
*seconds = *seconds * 3600 + (v1%60)*60 + v2%60;
}
else
{
// npt-sec
//*seconds = hours;
}
if(*p == '.')
p = string_token_int(p+1, fraction);
else
*fraction = 0;
}
return p;
}
// 3.6 Normal Play Time (p17)
// npt-range = ( npt-time "-" [ npt-time ] ) | ( "-" npt-time )
// Examples:
// npt=123.45-125
// npt=12:05:35.3-
// npt=now-
static int rtsp_header_range_npt(const char* fields, struct rtsp_header_range_t* range)
{
const char* p;
uint64_t seconds;
int fraction;
p = fields;
if('-' != *p)
{
p = rtsp_header_range_npt_time(p, &seconds, &fraction);
if(!p || '-' != *p)
return -1;
if(0 == seconds && -1 == fraction)
{
range->from_value = RTSP_RANGE_TIME_NOW;
range->from = 0L;
}
else
{
range->from_value = RTSP_RANGE_TIME_NORMAL;
range->from = seconds;
range->from = range->from * 1000 + fraction % 1000;
}
}
else
{
range->from_value = RTSP_RANGE_TIME_NOVALUE;
range->from = 0;
}
assert('-' == *p);
if('\0' == p[1] || strchr(RANGE_SPECIAL, p[1]))
{
assert('-' != *fields);
range->to_value = RTSP_RANGE_TIME_NOVALUE;
range->to = 0;
}
else
{
p = rtsp_header_range_npt_time(p+1, &seconds, &fraction);
if( !p ) return -1;
assert('\0' == p[0] || strchr(RANGE_SPECIAL, p[0]));
range->to_value = RTSP_RANGE_TIME_NORMAL;
range->to = seconds;
range->to = range->to * 1000 + fraction % 1000;
}
return 0;
}
// utc-time = utc-date "T" utc-time "Z"
// utc-date = 8DIGIT ; < YYYYMMDD >
// utc-time = 6DIGIT [ "." fraction ] ; < HHMMSS.fraction >
static const char* rtsp_header_range_clock_time(const char* str, uint64_t *second, int *fraction)
{
struct tm t;
const char* p;
int year, month, day;
int hour, minute;
assert(str);
if(!str || 5 != sscanf(str, "%4d%2d%2dT%2d%2d", &year, &month, &day, &hour, &minute))
return NULL;
*second = 0;
*fraction = 0;
p = string_token_int64(str + 13, (int64_t*)second);
assert(p);
if(*p == '.')
{
p = string_token_int(p+1, fraction);
}
memset(&t, 0, sizeof(t));
t.tm_year = year - 1900;
t.tm_mon = month - 1;
t.tm_mday = day;
t.tm_hour = hour;
t.tm_min = minute;
// *second += mktime(&t);
*second += utc_mktime(&t);
// assert('Z' == *p);
// assert('\0' == p[1] || strchr(RANGE_SPECIAL"-", p[1]));
return 'Z'==*p ? p+1 : p;
}
// 3.7 Absolute Time (p18)
// utc-range = "clock" "=" utc-time "-" [ utc-time ]
// Range: clock=19961108T143720.25Z-
// Range: clock=19961110T1925-19961110T2015 (p72)
static int rtsp_header_range_clock(const char* fields, struct rtsp_header_range_t* range)
{
const char* p;
uint64_t second;
int fraction;
p = rtsp_header_range_clock_time(fields, &second, &fraction);
if(!p || '-' != *p)
return -1;
range->from_value = RTSP_RANGE_TIME_NORMAL;
range->from = second * 1000;
range->from += fraction % 1000;
assert('-' == *p);
if('\0'==p[1] || strchr(RANGE_SPECIAL, p[1]))
{
range->to_value = RTSP_RANGE_TIME_NOVALUE;
range->to = 0;
}
else
{
p = rtsp_header_range_clock_time(p+1, &second, &fraction);
if( !p ) return -1;
range->to_value = RTSP_RANGE_TIME_NORMAL;
range->to = second * 1000;
range->to += (unsigned int)fraction % 1000;
}
return 0;
}
int rtsp_header_range(const char* field, struct rtsp_header_range_t* range)
{
int r = 0;
range->time = 0L;
while(field && 0 == r)
{
if(0 == strncasecmp("clock=", field, 6))
{
range->type = RTSP_RANGE_CLOCK;
r = rtsp_header_range_clock(field+6, range);
}
else if(0 == strncasecmp("npt=", field, 4))
{
range->type = RTSP_RANGE_NPT;
r = rtsp_header_range_npt(field+4, range);
}
else if(0 == strncasecmp("smpte=", field, 6))
{
range->type = RTSP_RANGE_SMPTE;
r = rtsp_header_range_smpte(field+6, range);
if(RTSP_RANGE_TIME_NORMAL == range->from_value)
range->from = (range->from/1000 * 1000) + (1000/30 * (range->from%1000)); // frame to ms
if(RTSP_RANGE_TIME_NORMAL == range->to_value)
range->to = (range->to/1000 * 1000) + (1000/30 * (range->to%1000)); // frame to ms
}
else if(0 == strncasecmp("smpte-30-drop=", field, 15))
{
range->type = RTSP_RANGE_SMPTE_30;
r = rtsp_header_range_smpte(field+15, range);
if(RTSP_RANGE_TIME_NORMAL == range->from_value)
range->from = (range->from/1000 * 1000) + (1000/30 * (range->from%1000)); // frame to ms
if(RTSP_RANGE_TIME_NORMAL == range->to_value)
range->to = (range->to/1000 * 1000) + (1000/30 * (range->to%1000)); // frame to ms
}
else if(0 == strncasecmp("smpte-25=", field, 9))
{
range->type = RTSP_RANGE_SMPTE_25;
r = rtsp_header_range_smpte(field+9, range);
if(RTSP_RANGE_TIME_NORMAL == range->from_value)
range->from = (range->from/1000 * 1000) + (1000/25 * (range->from%1000)); // frame to ms
if(RTSP_RANGE_TIME_NORMAL == range->to_value)
range->to = (range->to/1000 * 1000) + (1000/25 * (range->to%1000)); // frame to ms
}
else if(0 == strncasecmp("time=", field, 5))
{
if (rtsp_header_range_clock_time(field + 5, &range->time, &r))
range->time = range->time * 1000 + r % 1000;
}
field = strchr(field, ';');
if(field)
++field;
}
return r;
}
#if defined(DEBUG) || defined(_DEBUG)
void rtsp_header_range_test(void)
{
struct tm t;
struct rtsp_header_range_t range;
// smpte
assert(0==rtsp_header_range("smpte=10:12:33:20-", &range));
assert(range.type == RTSP_RANGE_SMPTE && range.from_value == RTSP_RANGE_TIME_NORMAL && range.to_value == RTSP_RANGE_TIME_NOVALUE);
assert(range.from == (10*3600+12*60+33)*1000 + 20*33);
assert(0==rtsp_header_range("smpte=10:07:33-", &range));
assert(range.type == RTSP_RANGE_SMPTE && range.from_value == RTSP_RANGE_TIME_NORMAL && range.to_value == RTSP_RANGE_TIME_NOVALUE);
assert(range.from == (10*3600+7*60+33)*1000);
assert(0==rtsp_header_range("smpte=10:07:00-10:07:33:05.01", &range));
assert(range.type == RTSP_RANGE_SMPTE && range.from_value == RTSP_RANGE_TIME_NORMAL && range.to_value == RTSP_RANGE_TIME_NORMAL);
assert(range.from == (10*3600+7*60)*1000);
assert(range.to == (10*3600+7*60+33)*1000 + 5*33);
assert(0==rtsp_header_range("smpte-25=10:07:00-10:07:33:05.01", &range));
assert(range.type == RTSP_RANGE_SMPTE_25 && range.from_value == RTSP_RANGE_TIME_NORMAL && range.to_value == RTSP_RANGE_TIME_NORMAL);
assert(range.from == (10*3600+7*60)*1000);
assert(range.to == (10*3600+7*60+33)*1000 + 5*40);
// npt
assert(0==rtsp_header_range("npt=now-", &range));
assert(range.type == RTSP_RANGE_NPT && range.from_value == RTSP_RANGE_TIME_NOW && range.to_value == RTSP_RANGE_TIME_NOVALUE);
assert(0==rtsp_header_range("npt=12:05:35.3-", &range));
assert(range.type == RTSP_RANGE_NPT && range.from_value == RTSP_RANGE_TIME_NORMAL && range.to_value == RTSP_RANGE_TIME_NOVALUE);
assert(range.from == (12*3600+5*60+35)*1000 + 3);
assert(0==rtsp_header_range("npt=123.45-125", &range));
assert(range.type == RTSP_RANGE_NPT && range.from_value == RTSP_RANGE_TIME_NORMAL && range.to_value == RTSP_RANGE_TIME_NORMAL);
assert(range.from == 123*1000+45);
assert(range.to == 125*1000);
// clock
assert(-1==rtsp_header_range("clock=-19961108T143720.25Z", &range));
assert(0==rtsp_header_range("clock=19961108T143720.25Z-", &range));
assert(range.type == RTSP_RANGE_CLOCK && range.from_value == RTSP_RANGE_TIME_NORMAL && range.to_value == RTSP_RANGE_TIME_NOVALUE);
t.tm_year = 1996-1900; t.tm_mon = 11-1; t.tm_mday = 8; t.tm_hour = 14; t.tm_min = 37; t.tm_sec = 20;
assert(range.from == utc_mktime(&t)*1000 + 25);
assert(0==rtsp_header_range("clock=19961110T1925-19961110T2015", &range)); // rfc2326 (p72)
assert(range.type == RTSP_RANGE_CLOCK && range.from_value == RTSP_RANGE_TIME_NORMAL && range.to_value == RTSP_RANGE_TIME_NORMAL);
t.tm_year = 1996-1900; t.tm_mon = 11-1; t.tm_mday = 10; t.tm_hour = 19; t.tm_min = 25; t.tm_sec = 00;
assert(range.from == utc_mktime(&t)*1000);
t.tm_year = 1996-1900; t.tm_mon = 11-1; t.tm_mday = 10; t.tm_hour = 20; t.tm_min = 15; t.tm_sec = 00;
assert(range.to == utc_mktime(&t)*1000);
// time
assert(0 == rtsp_header_range("smpte=0:10:20-;time=19970123T153600Z", &range)); // rfc2326 (p35)
assert(range.type == RTSP_RANGE_SMPTE && range.from_value == RTSP_RANGE_TIME_NORMAL && range.to_value == RTSP_RANGE_TIME_NOVALUE);
assert(range.from == (10 * 60 + 20) * 1000);
t.tm_year = 1997 - 1900; t.tm_mon = 1 - 1; t.tm_mday = 23; t.tm_hour = 15; t.tm_min = 36; t.tm_sec = 00;
assert(range.time == utc_mktime(&t) * 1000);
}
#endif
| 2.515625 | 3 |
2024-11-18T22:23:50.735359+00:00 | 2019-12-03T19:33:55 | 2c858898c2e7fa24e476c03b8c0ac1b7eaa12beb | {
"blob_id": "2c858898c2e7fa24e476c03b8c0ac1b7eaa12beb",
"branch_name": "refs/heads/master",
"committer_date": "2019-12-03T19:33:55",
"content_id": "1f81f057b4340212f0316280605d8848ff2c15e1",
"detected_licenses": [
"MIT"
],
"directory_id": "cdea32058ff1249141944e748c738fb9c7365309",
"extension": "h",
"filename": "hashMap.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 224516450,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1059,
"license": "MIT",
"license_type": "permissive",
"path": "/hashMap.h",
"provenance": "stackv2-0115.json.gz:75721",
"repo_name": "Brian-Peck/Spell-Checker",
"revision_date": "2019-12-03T19:33:55",
"revision_id": "165d15214fe3a448476972358f81476f1e78c336",
"snapshot_id": "039f2f66e73863ffd1ec27f8a29b5ddff2bad8ed",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Brian-Peck/Spell-Checker/165d15214fe3a448476972358f81476f1e78c336/hashMap.h",
"visit_date": "2020-09-20T14:59:51.101171"
} | stackv2 | #ifndef HASH_MAP_H
#define HASH_MAP_H
/*
* CS 261 Data Structures
* Assignment 5
*/
#define HASH_FUNCTION hashFunction1
#define MAX_TABLE_LOAD 1
typedef struct HashMap HashMap; //Can type HashMap instead of struct HashMap
typedef struct HashLink HashLink; //Can type HashLink instead of struct HashLink
struct HashLink
{
char* key;
int value;
HashLink* next;
};
struct HashMap
{
HashLink** table; //Array of pointers to link structs
int size; //Number of links in the table
int capacity; //Amount of space in the array
};
HashMap* hashMapNew(int capacity);
void hashMapDelete(HashMap* map);
int* hashMapGet(HashMap* map, const char* key);
void hashMapPut(HashMap* map, const char* key, int value);
void hashMapRemove(HashMap* map, const char* key);
int hashMapContainsKey(HashMap* map, const char* key);
int hashMapSize(HashMap* map);
int hashMapCapacity(HashMap* map);
int hashMapEmptyBuckets(HashMap* map);
float hashMapTableLoad(HashMap* map);
void hashMapPrint(HashMap* map);
#endif | 2.59375 | 3 |
2024-11-18T22:23:51.065713+00:00 | 2019-11-25T23:35:39 | 8a09af3f1fb96d5c9146c97e6d07aae1aceb7979 | {
"blob_id": "8a09af3f1fb96d5c9146c97e6d07aae1aceb7979",
"branch_name": "refs/heads/master",
"committer_date": "2019-11-25T23:35:39",
"content_id": "34af515a55aa9bc82432c4acba3fefb165824ddd",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "e6849352a77835d381de55bbb332bf823a7ca253",
"extension": "c",
"filename": "AI_sqrt.c",
"fork_events_count": 0,
"gha_created_at": "2013-08-17T12:48:41",
"gha_event_created_at": "2019-11-25T23:35:40",
"gha_language": "C",
"gha_license_id": "BSD-2-Clause",
"github_id": 12178774,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1265,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/src/AI_sqrt.c",
"provenance": "stackv2-0115.json.gz:75980",
"repo_name": "matthewdalton/arbint",
"revision_date": "2019-11-25T23:35:39",
"revision_id": "d1e2edef079528bacf9d10d1b7e13cede8a68152",
"snapshot_id": "0a45f0d2af9bb704e7c46edf9aebc8f562156102",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/matthewdalton/arbint/d1e2edef079528bacf9d10d1b7e13cede8a68152/src/AI_sqrt.c",
"visit_date": "2021-01-17T10:35:31.616251"
} | stackv2 | /* -*- mode: c; c-basic-offset: 2; -*- */
#include <stdio.h>
#include <assert.h>
#include "arbint.h"
#include "arbint-priv.h"
#include "AI_utils.h"
ArbInt *next_iteration(const ArbInt *curr, const ArbInt *n)
{
/* next = (curr + n/curr) / 2 */
ArbInt *rem;
ArbInt *divResult = AI_Div(n, curr, &rem);
AI_FreeArbInt(rem);
ArbInt *addResult = AI_Add(curr, divResult);
AI_FreeArbInt(divResult);
ArbInt *two = AI_NewArbInt_FromLong(2);
ArbInt *next = AI_Div(addResult, two, &rem);
AI_FreeArbInt(addResult);
AI_FreeArbInt(two);
AI_FreeArbInt(rem);
return next;
}
ArbInt *AI_isqrt(ArbInt const *n)
{
ArbInt *zero = AI_NewArbInt_From32(0);
if (AI_Less(n, zero)) {
AI_FreeArbInt(zero);
return NULL;
}
AI_FreeArbInt(zero);
ArbInt *k = AI_NewArbInt_FromCopy(n);
ArbInt *next_k;
ArbInt *k_plus_one = NULL;
// terminate if next_k == k or next_k == k + 1
for (;;) {
next_k = next_iteration(k, n);
/* printf("next_k = %s\n", AI_ToStringDec(next_k)); */
k_plus_one = AI_Add_Value(k, 1, 1);
if (AI_Equal(next_k, k) || AI_Equal(next_k, k_plus_one)) {
break;
}
AI_FreeArbInt(k);
AI_FreeArbInt(k_plus_one);
k = next_k;
}
AI_FreeArbInt(k);
AI_FreeArbInt(k_plus_one);
return next_k;
}
| 2.78125 | 3 |
2024-11-18T22:23:52.920401+00:00 | 2019-12-20T13:52:39 | 211e31f638a0177d9ecedb3db0a022195427d893 | {
"blob_id": "211e31f638a0177d9ecedb3db0a022195427d893",
"branch_name": "refs/heads/master",
"committer_date": "2019-12-20T13:52:39",
"content_id": "c2d64670ace847320d1d2d79340d7901c396ea73",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "3efc50ba20499cc9948473ee9ed2ccfce257d79a",
"extension": "c",
"filename": "source.c",
"fork_events_count": 4,
"gha_created_at": "2019-09-20T18:35:35",
"gha_event_created_at": "2019-12-20T13:52:42",
"gha_language": "C",
"gha_license_id": null,
"github_id": 209857592,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 734,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/data/others/files/source.c",
"provenance": "stackv2-0115.json.gz:76498",
"repo_name": "arthurherbout/crypto_code_detection",
"revision_date": "2019-12-20T13:52:39",
"revision_id": "3c9ff8a4b2e4d341a069956a6259bf9f731adfc0",
"snapshot_id": "7e10ed03238278690d2d9acaa90fab73e52bab86",
"src_encoding": "UTF-8",
"star_events_count": 9,
"url": "https://raw.githubusercontent.com/arthurherbout/crypto_code_detection/3c9ff8a4b2e4d341a069956a6259bf9f731adfc0/data/others/files/source.c",
"visit_date": "2020-07-29T15:34:31.380731"
} | stackv2 | #include <stdio.h>
int main() {
int score[6] = {76, 82, 90, 86, 79, 62};
int credit[6] = {2, 2, 1, 2, 2, 3};
int stu_number;
float mean, sum;
int temp;
int i;
printf("please input your student number:");
scanf("%d" , &stu_number);
sum = 0;
temp = 0;
for(i = 0 ; i < 6 ; i++) {
sum = sum + score[i] * credit[i];
temp = temp + credit[i];
}
mean = sum / temp ;
if(mean >= 60) {
mean = mean - 60 ;
printf("the score of student number %d is %f higher than 60.\n", stu_number, mean);
} else {
mean = 60 - mean ;
printf( "the score of student number %d is %f lower than 60.\n", stu_number, mean ) ;
}
return 0;
}
| 3.265625 | 3 |
2024-11-18T22:23:53.257755+00:00 | 2021-08-30T14:01:42 | 5847428463df672c1379285bbf0b7a859c07c07c | {
"blob_id": "5847428463df672c1379285bbf0b7a859c07c07c",
"branch_name": "refs/heads/main",
"committer_date": "2021-08-30T14:01:42",
"content_id": "6c5520234b1a47d3ed128dcbd9e14440fb437917",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "03f9a6386628cd3c63907558f6bc64e145e88751",
"extension": "c",
"filename": "mtsl.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 374348613,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4190,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/src/mtsl/mtsl.c",
"provenance": "stackv2-0115.json.gz:76758",
"repo_name": "timr1994/usim-service",
"revision_date": "2021-08-30T14:01:42",
"revision_id": "bdb8ca79a52783545de631c336adc013dd2d5afa",
"snapshot_id": "f6bd049d5084793a3490407c969e42eaa789dec6",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/timr1994/usim-service/bdb8ca79a52783545de631c336adc013dd2d5afa/src/mtsl/mtsl.c",
"visit_date": "2023-07-20T10:57:54.429382"
} | stackv2 | /* SPDX-License-Identifier: BSD-3-Clause */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Copyright 2021, Tim Riemann & Michael Eckel @ Fraunhofer Institute for Secure Information Technology SIT.
* All rights reserved.
* * * * * * * * * * * * * * * * * * * * * * * * * * * */
/*
*
* @file mtsl.c
* @author Tim Riemann <tim.riemann@sit.fraunhofer.de>
* @date 2020-06-25
*
* @copyright Copyright 2021, Tim Riemann & Michael Eckel @ Fraunhofer Institute for Secure Information Technology SIT. All rights reserved.
*
* @license BSD 3-Clause "New" or "Revised" License (SPDX-License-Identifier:
* BSD-3-Clause)
*
*/
#include <string.h>
#include "mtsl.h"
ListRoot *listRootInit() {
ListRoot *root = malloc(sizeof (ListRoot));
root->first = NULL;
root->tail = NULL;
root->lock = 0;
root->count = 0;
return root;
}
bool listAdd(ListRoot *root, ELEMENT_MTSL *add) {
aquireLock(root);
ListElement *ele = malloc(sizeof (ListElement));
memset(ele, 0, sizeof (ListElement));
ele->value = add;
ele->next = NULL;
if (isEmpty(root)) {
root->first = ele;
root->tail = ele;
} else {
root->tail->next = ele;
root->tail = ele;
}
++root->count;
releaseLock(root);
return true;
}
bool concatAndClearAdded(ListRoot *root, ListRoot *add) {
aquireLock(add);
aquireLock(root);
if (root->first == NULL) {
root->first = add->first;
root->tail = add->tail;
root->count = add->count;
add->first = NULL;
add->tail = NULL;
add->count = 0;
} else if (add->first != NULL) {
root->tail->next = add->first;
add->first = NULL;
root->tail = add->tail;
add->tail = NULL;
root->count += add->count;
add->count = 0;
}
releaseLock(add);
releaseLock(root);
return true;
}
bool remove(ListRoot *root, ELEMENT_MTSL *remove) {
aquireLock(root);
if (isEmpty(root)) {
releaseLock(root);
return false;
}
if (root->first->value == remove) {
ListElement *tmp = root->first;
root->first = root->first->next;
free(tmp);
--root->count;
releaseLock(root);
return true;
} else {
ListElement *tmp = root->first->next;
ListElement *prev = root->first;
while (tmp != NULL) {
if (tmp->value == remove) {
prev->next = tmp->next;
tmp->next = NULL;
free(tmp);
--root->count;
releaseLock(root);
return true;
} else {
prev = tmp;
tmp = tmp->next;
}
}
releaseLock(root);
return false;
}
}
bool isEmpty(ListRoot *root) {
return __sync_bool_compare_and_swap(&(root->count), 0, 0);
}
ELEMENT_MTSL *get(ListRoot *root, int pos) {
aquireLock(root);
if (isEmpty(root)) {
releaseLock(root);
return NULL;
}
int count = 0;
ListElement *tmp = root->first;
while (tmp != NULL) {
if (count == pos) {
releaseLock(root);
return tmp->value;
}
count++;
tmp = tmp->next;
}
releaseLock(root);
return NULL;
}
ELEMENT_MTSL **toArrayAndRemove(ListRoot *root, int *size) {
aquireLock(root);
if (isEmpty(root)) {
return NULL;
}
void **array = calloc(root->count, sizeof (ELEMENT_MTSL*));
ListElement *tmp = root->first;
ListElement *toFree = NULL;
int count = 0;
while (tmp != NULL) {
array[count++] = tmp->value;
toFree = tmp;
tmp = tmp->next;
free(toFree);
}
root->first = NULL;
root->tail = NULL;
__sync_lock_test_and_set(size, count);
releaseLock(root);
return array;
}
int MTSLSize(ListRoot *root) {
return root->count;
}
bool aquireLock(ListRoot *root) {
while (__sync_lock_test_and_set(&root->lock, 1) == 1);
return true;
}
bool releaseLock(ListRoot *root) {
__sync_lock_release(&root->lock);
return true;
} | 2.6875 | 3 |
2024-11-18T22:23:53.749602+00:00 | 2020-01-05T04:02:19 | de6847f76ff3b0441bfb2776c31690f9af1eb662 | {
"blob_id": "de6847f76ff3b0441bfb2776c31690f9af1eb662",
"branch_name": "refs/heads/master",
"committer_date": "2020-01-05T04:02:19",
"content_id": "206bcf70105fef7f4467932ef8e62ec29ac0990e",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "ea7f6517afb1d60baddb590da4bcf86a0f50ce8d",
"extension": "c",
"filename": "image_editor.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 165985456,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 9866,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/core/src/image_editor.c",
"provenance": "stackv2-0115.json.gz:77016",
"repo_name": "danielshervheim/TinyPaint",
"revision_date": "2020-01-05T04:02:19",
"revision_id": "3bc20370efd0a479fe458b4e9673481e4b2f45a4",
"snapshot_id": "849b05f2eb46dc25fcc53e99494e6c7bf11335b1",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/danielshervheim/TinyPaint/3bc20370efd0a479fe458b4e9673481e4b2f45a4/core/src/image_editor.c",
"visit_date": "2020-04-16T22:49:12.931186"
} | stackv2 | //
// Copyright © Daniel Shervheim, 2019
// danielshervheim@gmail.com
// www.github.com/danielshervheim
//
#include "image_editor.h"
#include "lodepng.h"
#include "filter.h"
#include "utilities.h"
#include <math.h> // pow, sqrt
//
// PRIVATE methods
//
/* clears the array of saved undo states. */
void image_editor_history_clear_redo(ImageEditor *self) {
for (int i = 0; i < self->m_redoIndex; i++) {
pixelbuffer_destroy(&(self->m_redoStates[i]));
}
self->m_redoIndex = 0;
}
/* clears the array of saved redone states. */
void image_editor_history_clear_undo(ImageEditor *self) {
for (int i = 0; i < self->m_undoIndex; i++) {
pixelbuffer_destroy(&(self->m_undoStates[i]));
}
self->m_undoIndex = 0;
}
/* Copies the current pixelbuffer as a new saved state for editing. */
void image_editor_history_update(ImageEditor *self) {
// clear the redo history
image_editor_history_clear_redo(self);
// if the saved states array is full...
if (self->m_undoIndex == MAX_HISTORY_STATES - 1) {
// destroy the oldest saved state
pixelbuffer_destroy(&(self->m_undoStates[0]));
// and shift the remaining states to make room for a new one
for (int i = 1; i < MAX_HISTORY_STATES; i++) {
self->m_undoStates[i-1] = self->m_undoStates[i];
}
// and decrement the index
self->m_undoIndex--;
}
// then make a copy of the current buffer
PixelBuffer copy = pixelbuffer_copy(image_editor_get_current_pixelbuffer(self));
self->m_undoIndex++;
self->m_undoStates[self->m_undoIndex] = copy;
}
//
// PUBLIC methods
//
ImageEditor image_editor_new() {
ImageEditor tmp;
tmp.m_tool = tool_new();
tmp.m_undoIndex = 0;
tmp.m_redoIndex = 0;
return tmp;
}
void image_editor_init_from_parameters(ImageEditor *self, int width, int height, GdkRGBA backgroundColor) {
// clear the history states, if for by some reason they were not already empty...
image_editor_history_clear_redo(self);
image_editor_history_clear_undo(self);
self->m_undoStates[self->m_undoIndex] = pixelbuffer_new(width, height);
pixelbuffer_set_all_pixels(image_editor_get_current_pixelbuffer(self), backgroundColor);
}
void image_editor_init_from_file(ImageEditor *self, const char *filepath) {
// assumes the gui ensures the input filepath is valid
unsigned error;
unsigned char *tmp;
unsigned width, height;
// load the png from the filepath
error = lodepng_decode32_file(&tmp, &width, &height, filepath);
if (error) {
printf("error %u: %s\n", error, lodepng_error_text(error));
}
// create the buffer with the correct size and default background color of white
GdkRGBA color = {1.0, 1.0, 1.0, 1.0};
image_editor_init_from_parameters(self, width, height, color);
// set all the pixels in the buffer as from the loaded file
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
int offset = (width * 4 * y) + (x*4);
color.red = tmp[offset + 0] / (double)255.0;
color.green = tmp[offset + 1] / (double)255.0;
color.blue = tmp[offset + 2] / (double)255.0;
color.alpha = tmp[offset + 3] / (double)255.0;
pixelbuffer_set_pixel(image_editor_get_current_pixelbuffer(self), x, y, GdkRGBA_clamp(color, 0.0, 1.0));
}
}
// free the temporary buffer
free(tmp);
}
void image_editor_destroy(ImageEditor *self) {
image_editor_history_clear_redo(self);
image_editor_history_clear_undo(self);
}
PixelBuffer* image_editor_get_current_pixelbuffer(ImageEditor *self) {
return &(self->m_undoStates[self->m_undoIndex]);
}
void image_editor_save_current_pixelbuffer(ImageEditor *self, const char *filepath) {
// assumes gui enforces the passed in filepath is valid
// get the current buffer
PixelBuffer *current = image_editor_get_current_pixelbuffer(self);
// allocate space for the temporary buffer
unsigned char *tmp = malloc(4 * current->width * current->height);
// fill the temporary buffer in the correct format
for (int y = 0; y < current->height; y++) {
for (int x = 0; x < current->width; x++) {
GdkRGBA color = pixelbuffer_get_pixel(current, x, y);
int offset = (current->width*4*y) + (x*4);
memset(tmp + offset + 0, color.red * 255, 1);
memset(tmp + offset + 1, color.green * 255, 1);
memset(tmp + offset + 2, color.blue * 255, 1);
memset(tmp + offset + 3, color.alpha * 255, 1);
}
}
// attempt to encode with lodepng library
unsigned error = lodepng_encode32_file(filepath, tmp, current->width, current->height);
if (error) {
printf("error %u: %s\n", error, lodepng_error_text(error));
}
// free the temporary buffer
free(tmp);
}
void image_editor_stroke_start(ImageEditor *self, int x, int y) {
image_editor_history_update(self);
PixelBuffer *current = image_editor_get_current_pixelbuffer(self);
if (x >= 0 && x < current->width && y >= 0 && y < current->height) {
tool_apply_to_pixelbuffer(&(self->m_tool), current, x, y);
}
}
void image_editor_stroke_hold(ImageEditor *self, int x, int y) {
PixelBuffer *current = image_editor_get_current_pixelbuffer(self);
if (x >= 0 && x < current->width && y >= 0 && y < current->height) {
tool_apply_to_pixelbuffer(&(self->m_tool), current, x, y);
}
}
void image_editor_stroke_move(ImageEditor *self, int x, int y, int prevX, int prevY) {
if (!self->m_tool.isStamp) {
PixelBuffer *current = image_editor_get_current_pixelbuffer(self);
int distance = sqrt(pow(x-prevX, 2.0) + pow(y-prevY, 2.0));
int stepSize = (1-self->m_tool.fillRate) * (distance-1) + 1;
for (int i = 0; i < distance; i += stepSize) {
double percent = i/(double)distance;
int tmpX = (int)double_lerp(prevX, x, percent);
int tmpY = (int)double_lerp(prevY, y, percent);
if (tmpX >= 0 && tmpX < current->width && tmpY >= 0 && tmpY < current->height) {
tool_apply_to_pixelbuffer(&(self->m_tool), current, tmpX, tmpY);
}
}
}
}
void image_editor_stroke_end(ImageEditor *self, int x, int y) {
if (!self->m_tool.isStamp) {
PixelBuffer *current = image_editor_get_current_pixelbuffer(self);
if (x >= 0 && x < current->width && y >= 0 && y < current->height) {
tool_apply_to_pixelbuffer(&(self->m_tool), current, x, y);
}
}
}
void image_editor_undo(ImageEditor *self) {
if (self->m_undoIndex > 0 && self->m_undoIndex < MAX_HISTORY_STATES) {
self->m_redoStates[self->m_redoIndex] = self->m_undoStates[self->m_undoIndex];
self->m_redoIndex++;
self->m_undoIndex--;
}
}
void image_editor_redo(ImageEditor *self) {
if (self->m_redoIndex > 0 && self->m_redoIndex < MAX_HISTORY_STATES) {
self->m_redoIndex--;
self->m_undoIndex++;
self->m_undoStates[self->m_undoIndex] = self->m_redoStates[self->m_redoIndex];
}
}
void image_editor_apply_saturation_filter(ImageEditor *self, double scale) {
image_editor_history_update(self);
SaturationParams params = {scale};
apply_basic_filter_to_pixelbuffer(SATURATION, (void *)(¶ms), image_editor_get_current_pixelbuffer(self));
}
void image_editor_apply_channels_filter(ImageEditor *self, double r, double g, double b) {
image_editor_history_update(self);
ChannelsParams params = {r, g, b};
apply_basic_filter_to_pixelbuffer(CHANNELS, (void *)(¶ms), image_editor_get_current_pixelbuffer(self));
}
void image_editor_apply_invert_filter(ImageEditor *self) {
image_editor_history_update(self);
apply_basic_filter_to_pixelbuffer(INVERT, NULL, image_editor_get_current_pixelbuffer(self));
}
void image_editor_apply_brightness_contrast_filter(ImageEditor *self, double brightness, double contrast) {
image_editor_history_update(self);
BrightnessContrastParams params = {brightness, contrast};
apply_basic_filter_to_pixelbuffer(BRIGHTNESSCONTRAST, (void *)(¶ms), image_editor_get_current_pixelbuffer(self));
}
void image_editor_apply_gaussian_blur_filter(ImageEditor *self, int radius) {
image_editor_history_update(self);
GaussianBlurParams params = {radius};
apply_convolution_filter_to_pixelbuffer(GAUSSIANBLUR, (void *)(¶ms), image_editor_get_current_pixelbuffer(self));
}
void image_editor_apply_motion_blur_filter(ImageEditor *self, int radius, double angle) {
image_editor_history_update(self);
MotionBlurParams params = {radius, angle};
apply_convolution_filter_to_pixelbuffer(MOTIONBLUR, (void *)(¶ms), image_editor_get_current_pixelbuffer(self));
}
void image_editor_apply_sharpen_filter(ImageEditor *self, int radius) {
image_editor_history_update(self);
SharpenParams params = {radius};
apply_convolution_filter_to_pixelbuffer(SHARPEN, (void *)(¶ms), image_editor_get_current_pixelbuffer(self));
}
void image_editor_apply_edge_detect_filter(ImageEditor *self) {
image_editor_history_update(self);
apply_convolution_filter_to_pixelbuffer(EDGEDETECT, NULL, image_editor_get_current_pixelbuffer(self));
}
void image_editor_apply_posterize_filter(ImageEditor *self, int numBins) {
image_editor_history_update(self);
PosterizeParams params = {numBins};
apply_basic_filter_to_pixelbuffer(POSTERIZE, (void *)(¶ms), image_editor_get_current_pixelbuffer(self));
}
void image_editor_apply_threshold_filter(ImageEditor *self, double cutoff) {
image_editor_history_update(self);
ThresholdParams params = {cutoff};
apply_basic_filter_to_pixelbuffer(THRESHOLD, (void *)(¶ms), image_editor_get_current_pixelbuffer(self));
}
| 2.71875 | 3 |
2024-11-18T22:23:53.828945+00:00 | 2023-04-10T23:21:51 | 7e5e1fd94b023bf83bc6d944530426638453c92c | {
"blob_id": "7e5e1fd94b023bf83bc6d944530426638453c92c",
"branch_name": "refs/heads/main",
"committer_date": "2023-04-10T23:21:51",
"content_id": "596c0c30f70d47d4244b937814d43efc12156b81",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "8abf73b999d2d8ac9ca05ffe83176624dac4957f",
"extension": "c",
"filename": "sum.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 9243661,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2672,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/llvm/sum.c",
"provenance": "stackv2-0115.json.gz:77145",
"repo_name": "EarlGray/language-incubator",
"revision_date": "2023-04-10T23:21:51",
"revision_id": "3fa87f515ad29f0bd7f31d7685a1986159ee0dad",
"snapshot_id": "80592c0be70ef8282a7c3fd878455ce2e40ccb87",
"src_encoding": "UTF-8",
"star_events_count": 57,
"url": "https://raw.githubusercontent.com/EarlGray/language-incubator/3fa87f515ad29f0bd7f31d7685a1986159ee0dad/llvm/sum.c",
"visit_date": "2023-04-17T22:58:11.128670"
} | stackv2 | #include <stdlib.h>
#include <stdio.h>
#include <llvm-c/Core.h>
#include <llvm-c/Target.h>
#include <llvm-c/ExecutionEngine.h>
#include <llvm-c/Analysis.h>
#include <llvm-c/BitWriter.h>
/*
* Source:
* https://pauladamsmith.com/blog/2015/01/how-to-get-started-with-llvm-c-api.html
*/
/*
* Compilation and linking:
*
* $ clang `llvm-config-mp-3.5 --cflags` -g -c sum.c -o sum.o
* $ clang++ sum.o \
* `llvm-config-mp-3.5 --cxxflags --ldflags \
* --libs core executionengine jit interpreter analysis native bitwriter \
* --system-libs` -o sum
*
*/
int main(int argc, char const *argv[]) {
LLVMModuleRef mod = LLVMModuleCreateWithName("sum");
LLVMTypeRef param_types[] = { LLVMInt32Type(), LLVMInt32Type() };
LLVMTypeRef ret_type = LLVMFunctionType(LLVMInt32Type(), /* ret type */
param_types, /* arg types */
2, /* arg count */
0 /* is variadic */);
LLVMValueRef sum = LLVMAddFunction(mod, "sum", ret_type);
LLVMBasicBlockRef entry = LLVMAppendBasicBlock(sum, "entry");
LLVMBuilderRef builder = LLVMCreateBuilder();
LLVMPositionBuilderAtEnd(builder, entry);
LLVMValueRef tmp = LLVMBuildAdd(builder,
LLVMGetParam(sum, 0),
LLVMGetParam(sum, 1), "tmp");
LLVMBuildRet(builder, tmp);
char *error = NULL;
LLVMVerifyModule(mod, LLVMAbortProcessAction, &error);
LLVMDisposeMessage(error);
LLVMExecutionEngineRef engine;
error = NULL;
LLVMLinkInJIT();
LLVMInitializeNativeTarget();
if (LLVMCreateExecutionEngineForModule(&engine, mod, &error) != 0) {
fprintf(stderr, "failed to create execution engine\n");
abort();
}
if (error) {
fprintf(stderr, "error: %s\n", error);
LLVMDisposeMessage(error);
exit(EXIT_FAILURE);
}
if (argc < 3) {
fprintf(stderr, "usage: %s x y\n", argv[0]);
exit(EXIT_FAILURE);
}
long long x = strtoll(argv[1], NULL, 10);
long long y = strtoll(argv[2], NULL, 10);
LLVMGenericValueRef args[] = {
LLVMCreateGenericValueOfInt(LLVMInt32Type(), x, 0),
LLVMCreateGenericValueOfInt(LLVMInt32Type(), y, 0),
};
LLVMGenericValueRef res = LLVMRunFunction(engine, sum, 2, args);
printf("%d\n", (int)LLVMGenericValueToInt(res, 0));
// write bitcode to file
if (LLVMWriteBitcodeToFile(mod, "sum.bc") != 0) {
fprintf(stderr, "error writing bitcode to file\n");
}
LLVMDisposeBuilder(builder);
LLVMDisposeExecutionEngine(engine);
}
| 2.46875 | 2 |
2024-11-18T22:23:54.384941+00:00 | 2013-06-15T14:06:49 | c547de41f8e2ba5bb43c2873f47140fddf385143 | {
"blob_id": "c547de41f8e2ba5bb43c2873f47140fddf385143",
"branch_name": "refs/heads/master",
"committer_date": "2013-06-15T14:06:49",
"content_id": "d65b958088fb697c9b91dea72e3c4c569a0ddf91",
"detected_licenses": [
"MIT"
],
"directory_id": "47231faa6e9d12878ef5f57e7bd21b7899dc2383",
"extension": "c",
"filename": "dwm-status.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": 2900,
"license": "MIT",
"license_type": "permissive",
"path": "/dwm-status.c",
"provenance": "stackv2-0115.json.gz:77274",
"repo_name": "Superkazuya/dwm",
"revision_date": "2013-06-15T14:06:49",
"revision_id": "01772fb883d4a3928d89d376325eae98d080b507",
"snapshot_id": "85e596923a9a3abb7df38eac8194dfe6a179f49c",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Superkazuya/dwm/01772fb883d4a3928d89d376325eae98d080b507/dwm-status.c",
"visit_date": "2020-06-06T03:55:54.019480"
} | stackv2 | #include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include <iwlib.h>
#include <mpd/client.h>
#include <alsa/asoundlib.h>
#include <X11/Xlib.h>
#define INTERVAL 1
//#define MPD_PORT 6600
//#define MPD_TIMEOUT 1000
//#define TIME_FORMAT "\x09%a \x07 %d/%m/%Y \x02%H:\x01\x06%M"
#define TIME_FORMAT "\x0f%a %d/%m/%Y\x10%H:%M"
//#define WIFI "wlsp02"
#define BATTERY "/sys/class/power_supply/BAT1/capacity"
void print_battery(char * buffer)
{
FILE *bat_file;
char bat_char[8];
int bat;
assert((bat_file = fopen(BATTERY,"r")) != 0);
fscanf(bat_file, "%d\n", &bat);
fclose(bat_file);
sprintf(bat_char, "\u2B83 %d%%", bat);
strcat(buffer, bat_char);
}
void print_date(char * buffer)
{
char buf[64];
time_t rawtime = time(NULL);
strftime(buf, sizeof(buf) - 1, TIME_FORMAT, localtime(&rawtime));
strcat(buffer, buf);
}
void print_vol(char * buffer)
{
int mute = 0;
int realvol = 0;
long min = 0;
long max = 0;
long vol = 0;
char vol_char[8];
snd_mixer_t *handle; /* init alsa */
snd_mixer_selem_id_t *mute_info; /* init channel with mute info */
snd_mixer_elem_t* mas_mixer;
snd_mixer_open(&handle, 0);
snd_mixer_attach(handle, "default");
snd_mixer_selem_register(handle, NULL, NULL);
snd_mixer_load(handle);
snd_mixer_selem_id_t *vol_info; /* init channel with volume info */
snd_mixer_selem_id_malloc(&vol_info);
snd_mixer_selem_id_set_name(vol_info, "Master");
snd_mixer_elem_t* pcm_mixer = snd_mixer_find_selem(handle, vol_info);
if(pcm_mixer == NULL)
goto ERROR;
snd_mixer_selem_get_playback_volume_range(pcm_mixer, &min, &max); /* get volume */
snd_mixer_selem_get_playback_volume(pcm_mixer, SND_MIXER_SCHN_MONO, &vol);
snd_mixer_selem_id_malloc(&mute_info);
snd_mixer_selem_id_set_name(mute_info, "Master");
mas_mixer = snd_mixer_find_selem(handle, mute_info);
snd_mixer_selem_get_playback_switch(mas_mixer, SND_MIXER_SCHN_MONO, &mute); /* get mute state */
if(mute != 0)
strcat(buffer, "\u2b83 ");
realvol = (vol*100)/max;
sprintf(vol_char, "%d%% ", realvol);
strcat(buffer, vol_char);
ERROR:
if(vol_info)
snd_mixer_selem_id_free(vol_info);
if (mute_info)
snd_mixer_selem_id_free(mute_info);
if (handle)
snd_mixer_close(handle);
}
int main()
{
char buffer[256];
Display *dpy;
Window root;
/*
if(fork())
exit(EXIT_SUCCESS);
struct wireless_info *wl_info;
wl_info = (struct wireless_info*) calloc(1, sizeof(struct wireless_info));
*/
if(!(dpy = XOpenDisplay(NULL)))
exit(1);
root = XRootWindow(dpy, DefaultScreen(dpy));
while(1)
{
*buffer = '\0';
//Init
print_vol(buffer);
print_battery(buffer);
print_date(buffer);
fflush(stdout);
XStoreName(dpy, root, buffer);
XFlush(dpy);
sleep(INTERVAL);
}
XCloseDisplay(dpy);
exit(EXIT_SUCCESS);
}
| 2 | 2 |
2024-11-18T22:23:57.984576+00:00 | 2020-10-03T03:27:03 | 7991f6a0813daddab9c5910dea1a706c9538f8d7 | {
"blob_id": "7991f6a0813daddab9c5910dea1a706c9538f8d7",
"branch_name": "refs/heads/master",
"committer_date": "2020-10-03T03:27:03",
"content_id": "28ab87d38065424940fe3c65a7f7f5c6f82847b0",
"detected_licenses": [
"MIT"
],
"directory_id": "90d0ee13138ad995183b5ad9ab885a4abefed968",
"extension": "c",
"filename": "menu.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 291368277,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 6199,
"license": "MIT",
"license_type": "permissive",
"path": "/lib/Heli/heli/menu.c",
"provenance": "stackv2-0115.json.gz:77402",
"repo_name": "JosiahCraw/Tiva-Helicopter-Controller-ENCE464-",
"revision_date": "2020-10-03T03:27:03",
"revision_id": "207fda18bf8e4b562e47205fbbdc9aaaf274c54f",
"snapshot_id": "7f4cb18b1ba0243ecd20a33680b98bf20aa9f79e",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/JosiahCraw/Tiva-Helicopter-Controller-ENCE464-/207fda18bf8e4b562e47205fbbdc9aaaf274c54f/lib/Heli/heli/menu.c",
"visit_date": "2022-12-24T12:05:19.383122"
} | stackv2 | /**
* menu.c - Menu utility for the Tiva.
*
* Uses both UART and OLED (TODO) to display an
* arbitrary menu system.
*
* Author: Jos Craw 2020
*/
#include <stdint.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <utils/ustdlib.h>
#include <driverlib/sysctl.h>
#include "input.h"
#include "menu.h"
#include "logging.h"
#include "heli.h"
volatile menu_t* current_menu;
void display_menu_oled(void) {
/*
* TODO add OLED functionality, not implemented as OLED is not visible from
* the online HeiRig viewer.
*/
return;
}
void display_menu_uart(void) {
char line[MAX_LOG_MESSAGE_LENGTH];
memset(line, '\0', sizeof(line));
#if UART_COLOUR_ENABLE == 1 && !ENABLE_MENU_GUI
usprintf(line, "\033[2J%s%s%s\r\n", MENU_TITLE_COLOUR, current_menu->name, LOG_CLEAR);
#elif ENABLE_MENU_GUI == 1
/*
* Calls set JavaScript functions defined as a part of
* the XSS package to clear the existing menu then
* start updating it.
*/
uart_send("<script>clearMenu();</script>\n\r");
usprintf(line, "<script>changeMenuTitle('%s');</script>\r\n", current_menu->name);
#else
usprintf(line, "%s\r\n", current_menu->name); // Display plain menu (no colour or XSS)
#endif
uart_send(line);
for (int i=0; i<current_menu->num_elements; i++) {
memset(line, '\0', sizeof(line));
menu_element_t* element = *(current_menu->elements+i);
#if ENABLE_MENU_GUI == 1
/*
* Defines each menu item to be displayed on the WebUI
* including the element name, if the element is currently
* selected, the label value and if the element is a submenu.
*
* This method ensures that the webpage data is always synchronized
* with the hardware as the UI does not make assumptions about the
* sates of the menu elements eg. if the webpage registers a button
* press but the hardware does not detect it the hardware state is
* always what is displayed.
*/
usprintf(line, "<script>addMenuItem('%s', %s, '%s', %s);</script>\r\n", element->name,
(i == current_menu->selected) ? "true": "false", (element->has_label) ? element->label : "",
(element->submenu) ? "true" : "false");
#else
if (!(element->has_label)) {
usprintf(line, "%s%s\r\n", (i == current_menu->selected) ? "> " : " ", element->name);
} else {
usprintf(line, "%s%s (%s)\r\n", (i == current_menu->selected) ? "> " : " ", element->name, element->label);
}
#endif
/*
* Uses the uart_send method as this ensure that the entire line is send
* immediately rather than entering a queue.
*/
uart_send(line);
}
}
menu_t* create_menu(const char* name) {
menu_t* menu = (menu_t*) malloc(sizeof(menu_t));
menu->name = name;
menu->selected = 0;
menu->num_elements = 0;
menu->parent = NULL;
menu->elements = (menu_element_t**)malloc(sizeof(menu_element_t**));
return menu;
}
void add_menu_item(const char* name, menu_t* parent, void (*callback)(void), void (*label_callback)(char*)) {
menu_element_t* menu_element = (menu_element_t*) malloc(sizeof(menu_element_t));
if (label_callback) {
menu_element->label = (char*)calloc(MAX_LABEL_LENGTH, sizeof(char));
}
menu_element->label_callback = label_callback;
menu_element->has_label = label_callback;
menu_element->name = name;
menu_element->parent = parent;
menu_element->submenu = false;
menu_element->menu = NULL;
menu_element->callback = (menu_callback_t)callback;
// Expand the parent menus element capacity
parent->elements = (menu_element_t**)realloc(parent->elements, sizeof(menu_element_t*) * (parent->num_elements+1));
*(parent->elements+parent->num_elements) = menu_element;
parent->num_elements++;
}
menu_t* add_submenu(const char* name, menu_t* parent) {
menu_element_t* menu_element = (menu_element_t*) malloc(sizeof(menu_element_t));
menu_t* menu = create_menu(name);
menu->parent = parent;
menu_element->name = name;
menu_element->parent = parent;
menu_element->submenu = true;
menu_element->menu = menu;
menu_element->has_label = false;
menu_element->label = false;
menu_element->label_callback = false;
// Expand the parent menus element capacity
parent->elements = (menu_element_t**)realloc(parent->elements, sizeof(menu_element_t*) * (parent->num_elements+1));
*(parent->elements+parent->num_elements) = menu_element;
parent->num_elements++;
return menu;
}
void set_current_menu(menu_t* menu) {
current_menu = menu;
}
void goto_parent_menu(void) {
menu_t* parent = current_menu->parent;
if (parent) {
set_current_menu(parent);
display_menu();
}
}
void enter_child_menu(void) {
menu_element_t* child = *(current_menu->elements+current_menu->selected);
if (child->submenu) {
set_current_menu(child->menu);
} else {
if (child->callback) {
menu_callback_t callback = child->callback;
callback();
}
}
display_menu();
}
void update_menu(void) {
if (checkButton(LEFT) == PUSHED) {
goto_parent_menu();
}
if (checkButton(RIGHT) == PUSHED) {
enter_child_menu();
}
if (checkButton(UP) == PUSHED) {
current_menu->selected = (current_menu->selected + (current_menu->num_elements-1)) % current_menu->num_elements;
display_menu();
}
if (checkButton(DOWN) == PUSHED) {
current_menu->selected = (current_menu->selected+1) % current_menu->num_elements;
display_menu();
}
}
void display_menu(void) {
for (int i=0; i<current_menu->num_elements; i++) {
menu_element_t* current_element = *(current_menu->elements+i);
if (current_element->has_label) {
current_element->label_callback(current_element->label);
}
}
display_menu_uart();
// NOTE: Not implemented
display_menu_oled();
}
| 2.671875 | 3 |
2024-11-18T22:23:58.916658+00:00 | 2017-07-06T18:48:18 | aeffd9468819a34d750f511188e5cadd12d52781 | {
"blob_id": "aeffd9468819a34d750f511188e5cadd12d52781",
"branch_name": "refs/heads/master",
"committer_date": "2017-07-06T18:48:18",
"content_id": "de89c8b7334c76a87d92d58642fe41c75c09d0e3",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "f81b0028ebbac8cddc9378658abf0a3bdf37f3ea",
"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": 38783165,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5108,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/DLB/main.c",
"provenance": "stackv2-0115.json.gz:77794",
"repo_name": "GSimas/dlb",
"revision_date": "2017-07-06T18:48:18",
"revision_id": "31e5ab773b09b91b3a187cc7ea85d24dd44bab52",
"snapshot_id": "f527eb056ba3fbdf5e3187dd92446932a04d5367",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/GSimas/dlb/31e5ab773b09b91b3a187cc7ea85d24dd44bab52/DLB/main.c",
"visit_date": "2021-01-21T13:35:02.037652"
} | stackv2 | #include <stdlib.h>
#include <stdio.h>
#include <allegro5/allegro.h>
#include <allegro5/allegro_primitives.h>
#include <allegro5/allegro_native_dialog.h>
#include <allegro5/allegro_font.h>
#include <allegro5/allegro_ttf.h>
#include <allegro5/bitmap.h>
#include <allegro5/allegro_image.h>
#include <allegro5/allegro_audio.h>
#include <allegro5/allegro_acodec.h>
#include "engine.h"
#include "objects.h"
const int WIDTH = 800;
const int HEIGHT = 600;
const int FPS = 60;
enum KEYS {ESC, W, A, S, D, SPACE};
bool keys[6] = {false, false, false, false, false, false};
int main(void)
{
bool done = false;
bool redraw = true;
struct Player player;
struct Sound sound[4];
struct Key key[5];
ALLEGRO_DISPLAY *display = NULL;
ALLEGRO_EVENT_QUEUE *event_queue = NULL;
ALLEGRO_TIMER *timer = NULL;
//Allegro Initializations
if(!al_init())
{
al_show_native_message_box(NULL, NULL, NULL, "falha ao inicializar allegro", NULL, 0);
return -1;
};
al_install_keyboard();
al_install_audio();
if(!al_install_audio())
{
printf("Falha ao inicializar audio");
return -1;
};
al_init_acodec_addon();
if(!al_init_acodec_addon())
{
printf("Falha ao inicializar acodec addon");
return -1;
};
al_reserve_samples(6);
if(!al_reserve_samples(6))
{
printf("Falha ao reservar samples");
return -1;
};
ALLEGRO_MONITOR_INFO info;
int res_x, res_y;
al_get_monitor_info(0, &info);
res_x = info.x2 - info.x1;
res_y = info.y2 - info.y1;
al_set_new_display_flags(ALLEGRO_FULLSCREEN_WINDOW);
display = al_create_display(res_x, res_y);
if(!display)
{
al_show_native_message_box(NULL, NULL, NULL, "falha ao inicializar display", NULL, 0);
return -1;
}
float red_x = res_x / (float) WIDTH;
float red_y = res_y / (float) HEIGHT;
ALLEGRO_TRANSFORM transform;
al_identity_transform(&transform);
al_scale_transform(&transform, red_x, red_y);
al_use_transform(&transform);
////////////////////////////////////////////////////////////////////////////////
//Game Initializations
InitPlayer(player);
InitSound(sound);
InitKey(key);
////////////////////////////////////////////////////////////////////////////////
//Allegro registers
event_queue = al_create_event_queue();
timer = al_create_timer(1.0 / FPS);
al_register_event_source(event_queue, al_get_keyboard_event_source());
al_register_event_source(event_queue, al_get_display_event_source(display));
al_register_event_source(event_queue, al_get_timer_event_source(timer));
al_start_timer(timer);
al_clear_to_color(al_map_rgb(0,0,0));
al_flip_display();
////////////////////////////////////////////////////////////////////////////////
while(!done)
{
ALLEGRO_EVENT ev;
al_wait_for_event(event_queue, &ev);
if(ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE)
done = true;
else if (ev.type == ALLEGRO_EVENT_TIMER)
{
redraw = true;
PlayerWalk(player, sound, key, &keys[W], &keys[A], &keys[S], &keys[D]);
Musics(player, sound, &keys[W], &keys[S], &keys[A], &keys[D]);
PlayMusics(player, sound);
}
else if(ev.type == ALLEGRO_EVENT_KEY_DOWN)
{
switch(ev.keyboard.keycode)
{
case ALLEGRO_KEY_ESCAPE:
done = true;
break;
case ALLEGRO_KEY_W:
keys[W] = true;
break;
case ALLEGRO_KEY_A:
keys[A] = true;
break;
case ALLEGRO_KEY_S:
keys[S] = true;
break;
case ALLEGRO_KEY_D:
keys[D] = true;
break;
}
}
else if(ev.type == ALLEGRO_EVENT_KEY_UP)
{
switch(ev.keyboard.keycode)
{
case ALLEGRO_KEY_W:
keys[W] = false;
break;
case ALLEGRO_KEY_A:
keys[A] = false;
break;
case ALLEGRO_KEY_S:
keys[S] = false;
break;
case ALLEGRO_KEY_D:
keys[D] = false;
break;
}
}
}
//Allegro destruction
al_destroy_display(display);
al_destroy_sample(sound[0].sample);
al_destroy_sample(sound[1].sample);
al_destroy_sample(sound[2].sample);
al_destroy_sample_instance(sound[0].instance);
al_destroy_sample_instance(sound[1].instance);
al_destroy_sample_instance(sound[2].instance);
al_destroy_sample_instance(key[0].instance[0]);
al_destroy_sample_instance(key[1].instance[0]);
al_destroy_sample_instance(key[1].instance[1]);
al_destroy_sample_instance(key[2].instance[0]);
al_destroy_sample_instance(key[2].instance[1]);
////////////////////////////////////////////////////////////////////////////////
return 0;
}
| 2.203125 | 2 |
2024-11-18T22:23:59.235431+00:00 | 2018-07-31T17:12:00 | 69362e706be8557114f6fa9c675a027f8a247700 | {
"blob_id": "69362e706be8557114f6fa9c675a027f8a247700",
"branch_name": "refs/heads/master",
"committer_date": "2018-07-31T17:12:00",
"content_id": "4dee445cb6f60170529a2bc12144b3bd744058a6",
"detected_licenses": [
"MIT"
],
"directory_id": "3710bbe516c9002f7807871f5567d0c491cfbd1a",
"extension": "c",
"filename": "LED.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 143041420,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4668,
"license": "MIT",
"license_type": "permissive",
"path": "/LED.c",
"provenance": "stackv2-0115.json.gz:78055",
"repo_name": "wpbest/MSP430FR5969",
"revision_date": "2018-07-31T17:12:00",
"revision_id": "5a6ea5e26577c83239c104749afa090a9488af8c",
"snapshot_id": "02f7298fc2b320ff319ac5dfeb77726387cd9c8c",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/wpbest/MSP430FR5969/5a6ea5e26577c83239c104749afa090a9488af8c/LED.c",
"visit_date": "2020-03-24T21:36:20.813313"
} | stackv2 | /******************************************************************************/
/* Change log *
*
*
*
* Date Revision Comments
* MM/DD/YY
* -------- --------- ----------------------------------------------------
* 10/04/15 3.0_DW0a Initial project make.
* */
/******************************************************************************/
/******************************************************************************/
/* Contains functions for LEDs.
* */
/******************************************************************************/
/******************************************************************************/
/* Files to Include */
/******************************************************************************/
#include <msp430.h>
#include "LED.h"
#include "USER.h"
#include "SYSTEM.h"
/******************************************************************************/
/* Inline Functions */
/******************************************************************************/
/******************************************************************************/
/* Functions */
/******************************************************************************/
/******************************************************************************/
/* LED_GreenToggle
*
* The function controls the green LED on the launchpad.
*
* Input: N/A
* Output: N/A
* Action: toggles the green LED
* */
/******************************************************************************/
void LED_GreenToggle(void)
{
P1OUT ^= Pin_GreenLED;
}
/******************************************************************************/
/* LED_RedToggle
*
* The function controls the red LED on the launchpad.
*
* Input: N/A
* Output: N/A
* Action: toggles the red LED
* */
/******************************************************************************/
void LED_RedToggle(void)
{
P4OUT ^= Pin_RedLED;
}
/******************************************************************************/
/* LED_Green
*
* The function controls the green LED on the launchpad.
*
* Input: state (ON or OFF)
* Output: the previous state of the green LED
* Action: controls the green LED
* */
/******************************************************************************/
unsigned char LED_Green(unsigned char state)
{
unsigned char status = FALSE;
if(P1IN & Pin_GreenLED)
{
status = TRUE;
}
if(state)
{
P1OUT |= Pin_GreenLED; // turn on the LED
}
else
{
P1OUT &= ~Pin_GreenLED; // turn off the LED
}
return status;
}
/******************************************************************************/
/* LED_Red
*
* The function controls the red LED on the launchpad.
*
* Input: state (ON or OFF)
* Output: the previous state of the red LED
* Action: controls the red LED
* */
/******************************************************************************/
unsigned char LED_Red(unsigned char state)
{
unsigned char status = FALSE;
if(P4IN & Pin_RedLED)
{
status = TRUE;
}
if(state)
{
P4OUT |= Pin_RedLED; // turn on the LED
}
else
{
P4OUT &= ~Pin_RedLED; // turn off the LED
}
return status;
}
/******************************************************************************/
/* LED_DisplayShow
*
* The function blinks the LEDS as a startup show.
*
* Input: N/A
* Output: N/A
* Action: Flashes the LEDs to indicate start-up.
* */
/******************************************************************************/
void LED_DisplayShow(void)
{
unsigned char i;
LED_Green(ON);
LED_Red(OFF);
for(i=0;i<10;i++)
{
LED_GreenToggle();
LED_RedToggle();
MSC_DelayUS(20000);
}
LED_Green(OFF);
LED_Red(OFF);
}
/*-----------------------------------------------------------------------------/
End of File
/-----------------------------------------------------------------------------*/
| 2.46875 | 2 |
2024-11-18T22:23:59.422948+00:00 | 2022-10-14T21:50:21 | 596df990d4feff3a8dce45e91b21879057eaf680 | {
"blob_id": "596df990d4feff3a8dce45e91b21879057eaf680",
"branch_name": "refs/heads/master",
"committer_date": "2022-10-14T21:50:21",
"content_id": "49e7477e28197297af202f971403f265803227ee",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "fec41f425b51e73842bd37fe0720e9d633288d42",
"extension": "c",
"filename": "find_maxcut.c",
"fork_events_count": 46,
"gha_created_at": "2016-08-02T17:48:30",
"gha_event_created_at": "2022-10-14T21:56:42",
"gha_language": "C",
"gha_license_id": "BSD-2-Clause",
"github_id": 64779084,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 16603,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/hapcut2-src/find_maxcut.c",
"provenance": "stackv2-0115.json.gz:78183",
"repo_name": "vibansal/HapCUT2",
"revision_date": "2022-10-14T21:50:21",
"revision_id": "0eb7075424afbb40259ced6b5b1cbd95d0cedf55",
"snapshot_id": "52434f72af703b4147baf966e00c2476d2c46d4c",
"src_encoding": "UTF-8",
"star_events_count": 188,
"url": "https://raw.githubusercontent.com/vibansal/HapCUT2/0eb7075424afbb40259ced6b5b1cbd95d0cedf55/hapcut2-src/find_maxcut.c",
"visit_date": "2022-10-21T19:16:58.785156"
} | stackv2 | #define DEBUG 0
//#include "like_scores.c" // additional functions for likelihood based calculation
#include "fragments.h"
#include "maxcut_lr.c"
#include "common.h"
#include <float.h>
#include <assert.h> /* assert */
extern int MAX_ITER;
extern int CONVERGE;
extern int VERBOSE;
typedef struct EDGE {
int s, t;
float w;
} EDGE;
/****** CODE TO FIND MAX CUT FOR EACH COMPONENT *************/
int evaluate_cut_component(struct fragment* Flist, struct SNPfrags* snpfrag, struct BLOCK* clist, int k, int* slist, char* HAP1);
float compute_goodcut(struct SNPfrags* snpfrag, char* hap, int* slist, struct BLOCK* component, struct fragment* Flist);
// likelihood function is -1*LL
void single_variant_flips(struct fragment* Flist, struct SNPfrags* snpfrag, struct BLOCK* clist, int k, int* slist, char* HAP1) {
int t = 0, i = 0, f = 0;
float newscore = clist[k].bestSCORE;
for (t = 0; t < clist[k].phased; t++) {
if (HAP1[slist[t]] == '1') HAP1[slist[t]] = '0';
else if (HAP1[slist[t]] == '0') HAP1[slist[t]] = '1';
for (i = 0; i < snpfrag[slist[t]].frags; i++) {
f = snpfrag[slist[t]].flist[i];
newscore -= Flist[f].currscore;
update_fragscore1(Flist, f, HAP1);
newscore += Flist[f].currscore;
}
if (newscore > clist[k].bestSCORE) // newMEC is not better than original MEC so we need to revert back to oldMEC for each fragment
{
if (HAP1[slist[t]] == '1') HAP1[slist[t]] = '0';
else if (HAP1[slist[t]] == '0') HAP1[slist[t]] = '1';
for (i = 0; i < snpfrag[slist[t]].frags; i++) {
f = snpfrag[slist[t]].flist[i];
update_fragscore1(Flist, f, HAP1);
}
} else {
clist[k].SCORE = newscore;
clist[k].bestSCORE = newscore;
}
}
}
/*
float edge_weight(char* hap, int i, int j, char* p, struct fragment* Flist, int f) {
float q1 = 1, q2 = 1;
int k = 0, l = 0;
// new code added so that edges are weighted by quality scores, running time is linear in length of fragment !! 08/15/13 | reduce this
for (k = 0; k < Flist[f].blocks; k++) {
for (l = 0; l < Flist[f].list[k].len; l++) {
if (Flist[f].list[k].offset + l == i) q1 = Flist[f].list[k].pv[l];
else if (Flist[f].list[k].offset + l == j) q2 = Flist[f].list[k].pv[l];
}
}
float p1 = q1 * q2 + (1 - q1)*(1 - q2);
float p2 = q1 * (1 - q2) + q2 * (1 - q1);
if (hap[i] == hap[j] && p[0] == p[1]) return log10(p1 / p2);
else if (hap[i] != hap[j] && p[0] != p[1]) return log10(p1 / p2);
else if (hap[i] == hap[j] && p[0] != p[1]) return log10(p2 / p1);
else if (hap[i] != hap[j] && p[0] == p[1]) return log10(p2 / p1);
else return 0;
}
*/
/**************** DETERMINISTIC MAX_CUT MEC IMPLEMENTATION *********************************************************//////
// function called from hapcut.c for each component...
int evaluate_cut_component(struct fragment* Flist, struct SNPfrags* snpfrag, struct BLOCK* clist, int k, int* slist, char* HAP1) {
if (clist[k].iters_since_improvement > CONVERGE) {
return 1; // return 1 only if converged
}
int i = 0, j = 0, t = 0, count1, count2;
float cutvalue;
/*
i=0;for (j=clist[k].offset;j<clist[k].offset+clist[k].length;j++)
{
if (snpfrag[clist[k].offset].component == snpfrag[j].component) { slist[i] = j; i++; }
}*/
// slist is copied from clist[k].slist
for (t = 0; t < clist[k].phased; t++) slist[t] = clist[k].slist[t]; // new way to determine slist
// not required but we do it to avoid errors
clist[k].SCORE = 0;
for (i = 0; i < clist[k].frags; i++) {
update_fragscore1(Flist, clist[k].flist[i], HAP1);
clist[k].SCORE += Flist[clist[k].flist[i]].currscore;
}
clist[k].bestSCORE = clist[k].SCORE;
// evaluate the impact of flipping of each SNP on MEC score, loop needed to improve MEC score
single_variant_flips(Flist, snpfrag, clist, k, slist, HAP1);
clist[k].SCORE = 0;
for (i = 0; i < clist[k].frags; i++) {
update_fragscore1(Flist, clist[k].flist[i], HAP1);
clist[k].SCORE += Flist[clist[k].flist[i]].currscore;
}
clist[k].bestSCORE = clist[k].SCORE;
cutvalue = 10;
if (clist[k].SCORE > 0) cutvalue = compute_goodcut(snpfrag, HAP1, slist, &clist[k], Flist);
// flip the subset of columns in slist with positive value
//if (cutvalue <= 3 || MINCUTALGO == 2) { //getchar();
for (i = 0; i < clist[k].phased; i++) {
if (slist[i] > 0 && HAP1[slist[i]] == '1') HAP1[slist[i]] = '0';
else if (slist[i] > 0 && HAP1[slist[i]] == '0') HAP1[slist[i]] = '1';
}
clist[k].bestSCORE = clist[k].SCORE;
clist[k].SCORE = 0;
for (i = 0; i < clist[k].frags; i++) {
update_fragscore1(Flist, clist[k].flist[i], HAP1);
clist[k].SCORE += Flist[clist[k].flist[i]].currscore;
}
count1 = 0; count2 = 0; // counts for size of each side of cut
for (j = 0; j < clist[k].phased; j++){
if (slist[j] > 0){
count1++;
}else{
count2++;
}
}
if (clist[k].iters_since_improvement <= CONVERGE && clist[k].SCORE >= clist[k].bestSCORE){// revert to old haplotype
// flip back the SNPs in the cut
clist[k].iters_since_improvement++;
for (i = 0; i < clist[k].phased; i++) {
if (slist[i] > 0 && HAP1[slist[i]] == '1') HAP1[slist[i]] = '0';
else if (slist[i] > 0 && HAP1[slist[i]] == '0') HAP1[slist[i]] = '1';
}
clist[k].SCORE = 0;
for (i = 0; i < clist[k].frags; i++) {
update_fragscore1(Flist, clist[k].flist[i], HAP1);
clist[k].SCORE += Flist[clist[k].flist[i]].currscore;
}
}else{
clist[k].bestSCORE = clist[k].SCORE; // update current haplotype
clist[k].iters_since_improvement = 0;
}
if (VERBOSE && clist[k].SCORE > 0) fprintf_time(stdout, "component %d offset %d length %d phased %d LL %0.1f cutvalue %f bestLL %0.2f\n", k, clist[k].offset, clist[k].length, clist[k].phased, -1*clist[k].SCORE, cutvalue, -1*clist[k].bestSCORE);
// return 0 to specify that this component hasn't converged.
return 0;
}
/********* THIS IS THE MAIN FUNCTION FOR HAPLOTYPE ASSEMBLY USING ITERATIVE MAX CUT computations **************/
float compute_goodcut(struct SNPfrags* snpfrag, char* hap, int* slist, struct BLOCK* component, struct fragment* Flist) {
// given a haplotype 'hap' and a fragment matrix, find a cut with positive score
int totaledges = 0, i = 0, j = 0, k = 0, l = 0, f = 0;
int wf = 0; //if (drand48() < 0.5) wf=1;
float W = 0;
size_t N = component->phased;
int iters_since_improved_cut = 0;
/* CODE TO set up the read-haplotype consistency graph */
for (i = 0; i < N; i++) {
snpfrag[slist[i]].tedges = 0;
k = -1;
// edges contain duplicates in sorted order, but tedges is unique count of edges
for (j = 0; j < snpfrag[slist[i]].edges; j++) {
if (k != snpfrag[slist[i]].elist[j].snp) {
snpfrag[slist[i]].tedges++;
k = snpfrag[slist[i]].elist[j].snp;
}
}
}
for (i = 0; i < N; i++) {
snpfrag[slist[i]].tedges = 0;
k = -1;
for (j = 0; j < snpfrag[slist[i]].edges; j++) {
if (k != snpfrag[slist[i]].elist[j].snp) {
snpfrag[slist[i]].telist[snpfrag[slist[i]].tedges].snp = snpfrag[slist[i]].elist[j].snp;
k = snpfrag[slist[i]].elist[j].snp;
W = (float) edge_weight(hap, slist[i], k, snpfrag[slist[i]].elist[j].p, Flist, snpfrag[slist[i]].elist[j].frag);
if (wf == 0) W /= Flist[snpfrag[slist[i]].elist[j].frag].calls - 1;
snpfrag[slist[i]].telist[snpfrag[slist[i]].tedges].w = W;
snpfrag[slist[i]].tedges++;
totaledges++;
} else if (k == snpfrag[slist[i]].elist[j].snp) {
W = (float) edge_weight(hap, slist[i], k, snpfrag[slist[i]].elist[j].p, Flist, snpfrag[slist[i]].elist[j].frag);
if (wf == 0) W /= Flist[snpfrag[slist[i]].elist[j].frag].calls - 1;
snpfrag[slist[i]].telist[snpfrag[slist[i]].tedges - 1].w += W;
}
}
}
/* CODE TO find 'K' biggest edges in MEC graph, negative weight edges in graph */
int K = 5;
int smallest = 0;
float smallw = 1000;
if (totaledges / 2 < K) K = totaledges / 2;
EDGE* edgelist = (EDGE*) malloc(sizeof (EDGE) * K);
j = 0;
i = 0;
k = 0;
for (i = 0; i < N; i++) {
for (j = 0; j < snpfrag[slist[i]].tedges; j++) {
if (k < K) {
edgelist[k].s = slist[i];
edgelist[k].t = snpfrag[slist[i]].telist[j].snp;
edgelist[k].w = snpfrag[slist[i]].telist[j].w;
if (edgelist[k].w < smallw) {
smallest = k;
smallw = edgelist[k].w;
}
k++;
} else {
if (snpfrag[slist[i]].telist[j].w > smallw) {
edgelist[smallest].s = slist[i];
edgelist[smallest].t = snpfrag[slist[i]].telist[j].snp;
edgelist[smallest].w = snpfrag[slist[i]].telist[j].w;
smallw = 1000;
for (l = 0; l < K; l++) {
if (edgelist[l].w < smallw) {
smallest = l;
smallw = edgelist[l].w;
}
}
}
}
}
}
/* CODE TO set up the read-haplotype consistency graph */
// edge contraction algorithm: merge vertices until only two nodes left or total edge weight of graph is negative
int startnode = (int) (drand48() * N);
if (startnode == N) startnode--;
int secondnode = -1; // root of 2nd cluster initially not there
// chose a positive edge to initialize the two clusters and run this algorithm $O(m)$ times for each block
// a negative weight cut should have at least one negative edge or if there is no negative weight edge, the edge with lowest weight
int V = N;
float curr_cut = 0, best_cut = 10000;
int snp_add;
int c1 = 0, c2 = 0;
char* bestmincut;
// int size_small,best_small=0,secondlast=0,last=0;
int iter = 0, maxiter = N / 10;
if (N / 10 < 1) maxiter = 1;
if (maxiter >= MAXCUT_ITER && MAXCUT_ITER >= 1) maxiter = MAXCUT_ITER; // added march 13 2013
int fixheap = 0;
PHEAP pheap;
pinitheap(&pheap, N); // heap for maxcut
/*****************************Maintain two clusters and add each vertex to one of these two ******************/
bestmincut = (char*) malloc(N);
for (i = 0; i < N; i++) bestmincut[i] = '0';
//for (iter=0;iter<totaledges*(int)(log2(totaledges));iter++)
for (iter = 0; iter < maxiter + K; iter++) {
pheap.length = N - 2;
V = N - 2;
if (iter < K) {
startnode = edgelist[iter].s;
secondnode = edgelist[iter].t;
if (DEBUG) fprintf(stdout, " edge sel %d %d %f \n", startnode, secondnode, edgelist[iter].w);
} else {
if (drand48() < 0.5) {
i = (int) (drand48() * totaledges - 0.0001);
j = 0;
while (i >= snpfrag[slist[j]].tedges) {
i -= snpfrag[slist[j]].tedges;
j++;
}
startnode = slist[j];
secondnode = snpfrag[slist[j]].telist[i].snp;
if (snpfrag[slist[j]].telist[i].w >= 1) continue;
} else {
// find node with high MEC score, initialize as startnode
j = (int) (drand48() * N);
if (j >= N) j = N - 1;
startnode = slist[j];
secondnode = -1;
pheap.length = N - 1;
V = N - 1;
}
}
for (i = 0; i < N; i++) snpfrag[slist[i]].parent = slist[i];
// new code added for heap based calculation
for (i = 0; i < N; i++) snpfrag[slist[i]].score = 0;
j = 0; // heap only has N-2 elements (startnode and secondnode are not there)
for (i = 0; i < N; i++) {
if (slist[i] != startnode && slist[i] != secondnode) {
pheap.elements[j] = i;
snpfrag[slist[i]].heaploc = j;
j++;
}
}
// for (i=0;i<N;i++) fprintf(stdout,"heaploc %d %d %d-%d\n",slist[i],snpfrag[slist[i]].heaploc,startnode,secondnode);
for (i = 0; i < component->frags; i++) {
f = component->flist[i];
Flist[f].scores[0] = 0.0;
Flist[f].scores[1] = 0.0;
Flist[f].scores[2] = 0.0;
Flist[f].scores[3] = 0.0;
Flist[f].htscores[0] = 0.0;
Flist[f].htscores[1] = 0.0;
Flist[f].htscores[2] = 0.0;
Flist[f].htscores[3] = 0.0;
}
init_fragment_scores(snpfrag, Flist, hap, startnode, secondnode);
pbuildmaxheap(&pheap, snpfrag, slist);
//V = N-2;
while (V > 0) // more than two clusters, this loop is O(N^2)
{
snp_add = pheap.elements[0];
premovemax(&pheap, snpfrag, slist);
fixheap = 0;
//if (N < 30) fprintf(stdout,"standard best score %f snp %d %d V %d\n",snpfrag[slist[snp_add]].score,snp_add,slist[snp_add],V);
if (snpfrag[slist[snp_add]].score > 0) snpfrag[slist[snp_add]].parent = startnode;
else if (snpfrag[slist[snp_add]].score < 0) {
if (secondnode < 0) {
secondnode = slist[snp_add];
//fprintf_time(stderr,"secondnode found %d %f V %d N %d\n",secondnode,snpfrag[slist[snp_add]].score,V,N);
}
snpfrag[slist[snp_add]].parent = secondnode;
} else if (secondnode < 0) secondnode = slist[snp_add];
else // score is 0
{
if (drand48() < 0.5) snpfrag[slist[snp_add]].parent = startnode;
else snpfrag[slist[snp_add]].parent = secondnode;
}
V--;
update_fragment_scores(snpfrag, Flist, hap, startnode, secondnode, slist[snp_add], &pheap, slist);
for (i = 0; i < N; i++) {
if (DEBUG) fprintf(stdout, "score %d %f hap %c \n", slist[i], snpfrag[slist[i]].score, hap[slist[i]]);
}
if (DEBUG) fprintf(stdout, "init frag-scores %d...%d new node added %d parent %d\n\n", startnode, secondnode, slist[snp_add], snpfrag[slist[snp_add]].parent);
if (fixheap == 1) pbuildmaxheap(&pheap, snpfrag, slist);
}
if (secondnode == -1) continue; // cut is empty, so we should ignore this cut
// compute score of the cut computed above
for (i = 0; i < N; i++) {
if (snpfrag[slist[i]].parent == startnode) snpfrag[slist[i]].parent = 0;
else snpfrag[slist[i]].parent = 1;
}
c1 = 0;
c2 = 0;
for (i = 0; i < N; i++) {
if (snpfrag[slist[i]].parent == 0) c1++;
else c2++;
}
if (c1 == 0 || c2 == 0) {
if (DEBUG) fprintf(stdout, " cut size is 0 red \n");
exit(0);
}
curr_cut = cut_score(Flist, snpfrag, component, hap);
// cut score returns difference between likelihood of current haplotype and new haplotype => smaller it is, better the cut
if (DEBUG) fprintf(stdout, "cut size %d %d %f best %f\n", c1, c2, curr_cut, best_cut);
// for new likelihood based cut score, the score of the cut should always be less than 0 since it is difference of the log-likelihoods of old and new haplotypes
if (curr_cut < best_cut) // negative weight cut is better...
{
best_cut = curr_cut;
for (i = 0; i < N; i++) {
if (snpfrag[slist[i]].parent == 1) bestmincut[i] = '1';
else bestmincut[i] = '0';
}
}else{
iters_since_improved_cut++;
}
if (iters_since_improved_cut > CONVERGE){
break;
}
}
for (i = 0; i < N; i++) {
if (bestmincut[i] == '1') slist[i] = -1 * slist[i] - 1;
}
free(bestmincut);
free(pheap.elements);
free(edgelist);
return best_cut;
}
| 2.25 | 2 |
2024-11-18T22:24:05.912070+00:00 | 2019-03-01T05:16:46 | 07b405ac73e8ce0bf9c775152d91c4386c91e608 | {
"blob_id": "07b405ac73e8ce0bf9c775152d91c4386c91e608",
"branch_name": "refs/heads/master",
"committer_date": "2019-03-01T05:16:46",
"content_id": "8420a274020f121f457cd1926f9bcf59995cca99",
"detected_licenses": [
"MIT"
],
"directory_id": "5a17a3d150c4773318d397a46878d2fd74c0671f",
"extension": "c",
"filename": "cangli.c",
"fork_events_count": 0,
"gha_created_at": "2018-12-26T11:38:10",
"gha_event_created_at": "2018-12-26T11:38:10",
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 163173406,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3012,
"license": "MIT",
"license_type": "permissive",
"path": "/nitan/kungfu/skill/qishang-quan/cangli.c",
"provenance": "stackv2-0115.json.gz:78441",
"repo_name": "cantona/NT6",
"revision_date": "2019-03-01T05:16:46",
"revision_id": "073f4d491b3cfe6bfbe02fbad12db8983c1b9201",
"snapshot_id": "e9adc7308619b614990fa64456c294fad5f07d61",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/cantona/NT6/073f4d491b3cfe6bfbe02fbad12db8983c1b9201/nitan/kungfu/skill/qishang-quan/cangli.c",
"visit_date": "2020-04-15T21:16:28.817947"
} | stackv2 | // cangli.c 藏離訣
#include <ansi.h>
inherit F_SSERVER;
string name() { return "藏離訣"; }
int perform(object me)
{
string msg,str;
object target;
int skill, neili_wound;
mixed ap, dp;
me->clean_up_enemy();
target = me->select_opponent();
skill = me->query_skill("qishang-quan",1) + me->query_skill("force",1);
if( !me->is_fighting() )
return notify_fail("「藏離訣」只能在戰鬥中使用。\n");
if( (int)query("neili", me) < 800 )
return notify_fail("你的內力還不夠高!\n");
if( (int)me->query_skill("cuff") < 220 )
return notify_fail("你的拳法還不到家,無法體現七傷拳的各種總訣!\n");
if( (int)me->query_skill("qishang-quan", 1) < 220)
return notify_fail("你七傷拳的修為不夠,不能夠體會藏離訣! \n");
if( (int)me->query_skill("force", 1) < 220)
return notify_fail(HIM "你的基本內功修為不足,不能隨便使用藏離訣! \n" NOR);
if( me->query_skill_mapped("cuff") != "qishang-quan")
return notify_fail("你沒有激發七傷拳,無法運用藏離訣!\n");
if (me->query_skill_prepared("cuff") != "qishang-quan")
return notify_fail("你沒有準備使用七傷拳,無法施展「藏離訣」。\n");
if( objectp(query_temp("weapon", me)) )
return notify_fail("你必須空手才能使用此招!\n");
msg = HIY "$N凝神定氣,使出七傷拳總訣中的「" HIR "藏離訣" HIY "」,雙拳勢如雷霆,向$n擊去。\n"NOR;
message_combatd(msg, me, target);
ap = attack_power(me, "cuff");
dp = defense_power(target, "dodge");
if( ap /2 + random(ap) > dp || !living(target))
{
addn("neili", -200, me);
msg = HIG "$n被$N拳風掃中,只覺全身真氣失卻駕馭,往外急瀉!\n"NOR;
neili_wound = damage_power(me, "cuff");
neili_wound += query("jiali", me);
if( neili_wound > query("neili", target) )
neili_wound = query("neili", target);
if( query("neili", target) < 0 )
neili_wound = 0;
addn("neili", -neili_wound, target);
target->receive_wound("qi", neili_wound, me);
if( !target->is_busy() )
target->start_busy(2);
me->start_busy(2);
str = COMBAT_D->status_msg((int)query("qi", target) * 100 /(int)query("max_qi", target));
msg += "($n"+str+")\n";
}
else
{
msg = HIG "只見$n不慌不忙,輕輕一閃,躲過了$N的必殺一擊!\n"NOR;
addn("neili", -100, me);
me->start_busy(3);
}
message_combatd(msg, me, target);
return 1;
} | 2.265625 | 2 |
2024-11-18T22:24:06.290463+00:00 | 2021-09-25T10:58:15 | b25f1c66abe2c27354445f7911c5e85499ab3f28 | {
"blob_id": "b25f1c66abe2c27354445f7911c5e85499ab3f28",
"branch_name": "refs/heads/master",
"committer_date": "2021-09-25T10:58:15",
"content_id": "6ff86cd5dac7dd1656f3c7455113c8c44be73223",
"detected_licenses": [
"MIT"
],
"directory_id": "d860a75148bf588da1b0ae796b76967b776f402d",
"extension": "c",
"filename": "redir.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 348321602,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 864,
"license": "MIT",
"license_type": "permissive",
"path": "/PL4/redir.c",
"provenance": "stackv2-0115.json.gz:78701",
"repo_name": "jpdiasfernandes/SO",
"revision_date": "2021-09-25T10:58:15",
"revision_id": "06ffbc78e0f4e952453a34809aab9ae3bd67fbce",
"snapshot_id": "9275ec9c39d8932972827d0bb264ef7c8c38b5d8",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/jpdiasfernandes/SO/06ffbc78e0f4e952453a34809aab9ae3bd67fbce/PL4/redir.c",
"visit_date": "2023-08-17T23:49:01.094049"
} | stackv2 | #include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <sys/wait.h>
int main (int argc, char *argv[]) {
if (argc < 2) {
perror("redir [-i fich_entrada] [-o fich_saida] comando arg1 arg2");
_exit(-1);
}
char *args[argc];
int j = 0;
for (int i = 1; i < argc; i++) {
if (strcmp("-i", argv[i]) == 0) {
i++;
int fd = open(argv[i], O_RDONLY);
if (fd == -1) { perror("Maybe invalid input"); _exit(-1); }
dup2(fd, 0); close(fd);
}
else if (strcmp("-o", argv[i]) == 0) {
i++;
int fd = open(argv[i], O_WRONLY | O_TRUNC | O_CREAT, 0644);
if (fd == -1) {perror("Maybe invalid input"); _exit(-1); }
dup2(fd, 1);close(fd);
}
else args[j++] = argv[i];
}
args[j] = NULL;
if (!fork()) {
execvp(args[0], args);
perror("Execution failed...");
_exit(-1);
}
else wait(NULL);
return 0;
}
| 2.5625 | 3 |
2024-11-18T22:24:07.749665+00:00 | 2019-07-09T19:52:18 | 402fb04b2e83dcc7fe32730d614606c7ef2d520f | {
"blob_id": "402fb04b2e83dcc7fe32730d614606c7ef2d520f",
"branch_name": "refs/heads/master",
"committer_date": "2019-07-09T19:52:18",
"content_id": "b132604e71b9b4e5ccb09408473a6961c86277b6",
"detected_licenses": [
"MIT"
],
"directory_id": "b2f5e1c0c49ae448a795404a8a8299eb41bce177",
"extension": "c",
"filename": "test_flash.c",
"fork_events_count": 10,
"gha_created_at": "2016-09-25T23:38:58",
"gha_event_created_at": "2021-05-16T22:05:31",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 69197028,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2226,
"license": "MIT",
"license_type": "permissive",
"path": "/libraries/ms-common/test/test_flash.c",
"provenance": "stackv2-0115.json.gz:79349",
"repo_name": "uw-midsun/firmware",
"revision_date": "2019-07-09T19:52:18",
"revision_id": "a4e8093b3ce453e88f8eb2bceb5318e02afbc0ba",
"snapshot_id": "4b0fd6dded88d8c0fd41711f085190b140d414d4",
"src_encoding": "UTF-8",
"star_events_count": 17,
"url": "https://raw.githubusercontent.com/uw-midsun/firmware/a4e8093b3ce453e88f8eb2bceb5318e02afbc0ba/libraries/ms-common/test/test_flash.c",
"visit_date": "2021-07-07T07:15:53.832357"
} | stackv2 | #include "flash.h"
#include "test_helpers.h"
#include "unity.h"
#define TEST_FLASH_PAGE (NUM_FLASH_PAGES - 1)
#define TEST_FLASH_ADDR FLASH_PAGE_TO_ADDR(TEST_FLASH_PAGE)
void setup_test(void) {
flash_init();
flash_erase(TEST_FLASH_PAGE);
}
void teardown_test(void) {
// Be sure to erase the flash just in case an application uses it
flash_erase(TEST_FLASH_PAGE);
}
void test_flash_basic_rw(void) {
uint8_t data[] = { 0x12, 0x34, 0x56, 0x78 };
uint8_t read[SIZEOF_ARRAY(data)];
StatusCode ret = flash_write(TEST_FLASH_ADDR, data, SIZEOF_ARRAY(data));
TEST_ASSERT_OK(ret);
ret = flash_read(TEST_FLASH_ADDR, SIZEOF_ARRAY(data), read, SIZEOF_ARRAY(read));
TEST_ASSERT_OK(ret);
TEST_ASSERT_EQUAL_HEX8_ARRAY(data, read, SIZEOF_ARRAY(data));
}
void test_flash_overwrite(void) {
uint8_t data[] = { 0x55, 0x55, 0x55, 0x55 };
uint8_t read[SIZEOF_ARRAY(data)];
StatusCode ret = flash_write(TEST_FLASH_ADDR, data, SIZEOF_ARRAY(data));
TEST_ASSERT_OK(ret);
// Overwrite with the same data
// STM32 does not allow overwriting at all
ret = flash_write(TEST_FLASH_ADDR, data, SIZEOF_ARRAY(data));
TEST_ASSERT_NOT_OK(ret);
// Try modifying some bits from 1 -> 0
data[0] = 0x11;
data[2] = 0x11;
ret = flash_write(TEST_FLASH_ADDR, data, SIZEOF_ARRAY(data));
TEST_ASSERT_NOT_OK(ret);
// Try modifying some bits from 0 -> 1
data[1] = 0xff;
ret = flash_write(TEST_FLASH_ADDR, data, SIZEOF_ARRAY(data));
TEST_ASSERT_NOT_OK(ret);
}
void test_flash_misaligned_write(void) {
uint32_t data = 0x00;
StatusCode ret = flash_write(TEST_FLASH_ADDR + 1, (uint8_t *)&data, sizeof(data));
TEST_ASSERT_NOT_OK(ret);
ret = flash_write(TEST_FLASH_ADDR, (uint8_t *)&data, FLASH_WRITE_BYTES + 1);
TEST_ASSERT_NOT_OK(ret);
}
void test_flash_out_of_bounds(void) {
uint32_t data = 0x00;
StatusCode ret = flash_write(0, (uint8_t *)&data, sizeof(data));
TEST_ASSERT_NOT_OK(ret);
ret = flash_write(FLASH_END_ADDR + FLASH_WRITE_BYTES, (uint8_t *)&data, sizeof(data));
TEST_ASSERT_NOT_OK(ret);
ret = flash_erase(NUM_FLASH_PAGES);
TEST_ASSERT_NOT_OK(ret);
}
void test_flash_verify_num_pages(void) {
TEST_ASSERT_EQUAL(FLASH_SIZE_BYTES / FLASH_PAGE_BYTES, NUM_FLASH_PAGES);
}
| 2.671875 | 3 |
2024-11-18T22:24:14.244742+00:00 | 2021-06-17T14:22:07 | 2746ede3b76abf1467fafdfdc9d40dfe49ada249 | {
"blob_id": "2746ede3b76abf1467fafdfdc9d40dfe49ada249",
"branch_name": "refs/heads/main",
"committer_date": "2021-06-17T14:22:07",
"content_id": "6a3ea656f37a5e4a12939562d0141b5337bf786e",
"detected_licenses": [
"Unlicense"
],
"directory_id": "de1706b03b1e4e6120784c1805d0455208857896",
"extension": "c",
"filename": "bubblesort.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": 2033,
"license": "Unlicense",
"license_type": "permissive",
"path": "/week1/day06/workspace/bubblesort.c",
"provenance": "stackv2-0115.json.gz:79608",
"repo_name": "tpolonen/42-c-basecamp",
"revision_date": "2021-06-17T14:22:07",
"revision_id": "d8441bb424867b94c47de96e51a8df10697d677b",
"snapshot_id": "8480f5831eaf7f0db32764cdb0945b1e0ed8219d",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/tpolonen/42-c-basecamp/d8441bb424867b94c47de96e51a8df10697d677b/week1/day06/workspace/bubblesort.c",
"visit_date": "2023-05-23T10:45:12.900594"
} | stackv2 | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* bubblesort.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: tpolonen <tpolonen@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/06/02 19:08:35 by tpolonen #+# #+# */
/* Updated: 2021/06/02 19:54:23 by tpolonen ### ########.fr */
/* */
/* ************************************************************************** */
#include <stdio.h>
#include <string.h>
void int_bubblesort(int arr[], int size)
{
int step;
int index;
int temp;
step = 0;
while(step < size - 1)
{
index = 0;
while (index < size - step - 1)
{
if(arr[index] > arr[index + 1])
{
temp = arr[index];
arr[index] = arr[index + 1];
arr[index + 1] = temp;
}
index++;
}
step++;
}
}
void str_bubblesort(char *str_arr[], int size)
{
int step;
int index;
char *temp;
step = 0;
while(step < size - 1)
{
index = 0;
while (index < size - step - 1)
{
if(strcmp(str_arr[index], str_arr[index + 1]) > 0)
{
temp = str_arr[index];
str_arr[index] = str_arr[index + 1];
str_arr[index + 1] = temp;
}
index++;
}
step++;
}
}
int main(int argc, char *argv[])
{
int array[] = {100, 42, 15, 999999, -10, 456, 1, -666, 798};
int size = sizeof(array) / sizeof(array[0]);
int index = 0;
int_bubblesort(array, size);
while (index < size)
{
printf("%d\n", array[index]);
index++;
}
str_bubblesort(argv + 1, argc - 1);
index = 1;
while (index < argc)
{
printf("%s\n", argv[index]);
index++;
}
return (0);
}
| 3.5 | 4 |
2024-11-18T22:24:14.323406+00:00 | 2014-10-02T21:51:08 | 1a63f411dce4003e205d461ecf74cb9cb9270588 | {
"blob_id": "1a63f411dce4003e205d461ecf74cb9cb9270588",
"branch_name": "refs/heads/master",
"committer_date": "2014-10-02T21:51:08",
"content_id": "39e448d2c6f81be1795c2b7c449b5e1c6b2c8d6a",
"detected_licenses": [
"MIT"
],
"directory_id": "0fa5bb2314052725ddf791698606ce5e5f52dfaf",
"extension": "c",
"filename": "xml-parser.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 24539201,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5660,
"license": "MIT",
"license_type": "permissive",
"path": "/src/lib/xml-parser.c",
"provenance": "stackv2-0115.json.gz:79736",
"repo_name": "DanielAW/libtr064",
"revision_date": "2014-10-02T21:51:08",
"revision_id": "8629bcb5b55d6b4f3e9685f32ac6079aefbc6615",
"snapshot_id": "ddf01ce40a44eb609dc09bc7deb328e3919e8cc7",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/DanielAW/libtr064/8629bcb5b55d6b4f3e9685f32ac6079aefbc6615/src/lib/xml-parser.c",
"visit_date": "2016-09-05T18:41:20.306531"
} | stackv2 | #include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <libxml/xmlreader.h>
#include "xml-parser.h"
void rtrim(char *str) {
size_t n;
n = strlen(str);
while (n > 0 && isspace((unsigned char)str[n - 1])) {
n--;
}
str[n] = '\0';
}
/**
* Only for debugging: print service_list from handle
*/
void print_service_list(SessionHandle *handle) {
Service* cur_service = handle->service_list;
while(cur_service != NULL) {
if(cur_service->service_type != NULL) {
printf("SERVICE_TYPE: '%s'\n", cur_service->service_type);
}
if(cur_service->control_url != NULL) {
printf("\tCONTROL_URL: '%s'\n", cur_service->control_url);
}
if(cur_service->scpd_url != NULL) {
printf("\tSCPD_URL: '%s'\n", cur_service->scpd_url);
}
cur_service = cur_service->next;
}
}
char *get_content_from_attribute(xmlTextReaderPtr reader) {
xmlChar* value;
char* ret;
/* To read contents between attributes we need its children with "InnerXML" */
value = xmlTextReaderReadInnerXml(reader);
if(value != NULL && xmlStrcmp(value, (const xmlChar *) "") != 0) {
ret = (char*) value;
} else {
free(value);
ret = NULL;
}
return ret;
}
void add_service_to_handle(SessionHandle *handle, Service *service) {
Service *cur_service = handle->service_list;
if(cur_service == NULL) {
handle->service_list = service;
} else {
while(cur_service->next != NULL) {
cur_service = cur_service->next;
}
cur_service->next = service;
}
}
Service *get_service_by_type(SessionHandle *handle, const char *service_type) {
Service* cur_service = handle->service_list;
Service* ret_service = NULL;
while(cur_service != NULL) {
if(strcmp(cur_service->service_type, service_type) == 0) {
ret_service = cur_service;
/* stop after the first found */
break;
}
cur_service = cur_service->next;
}
return ret_service;
}
void add_value_to_service(SessionHandle *handle, xmlTextReaderPtr reader, Service *service, const char *attribute, char *current_service_type) {
char *value = NULL;
value = get_content_from_attribute(reader);
if(value != NULL) {
service = get_service_by_type(handle, current_service_type);
if(service != NULL) {
if(strcmp(attribute, "controlURL") == 0)
service->control_url = value;
if(strcmp(attribute, "SCPDURL") == 0)
service->scpd_url = value;
} else {
free(value);
fprintf(stderr, "could not find '%s' service type '%s'\n", attribute, current_service_type);
}
}
}
/**
* handling of a node in the tree
* add found data to data model
*/
void processNode(SessionHandle *handle, xmlTextReaderPtr reader, char *current_service_type, size_t current_size_type_len) {
xmlChar *attrib_name = xmlTextReaderName(reader);
Service *service = NULL;
char *value = NULL;
if(xmlStrcmp(attrib_name, (const xmlChar *) "serviceType") == 0) {
value = get_content_from_attribute(reader);
if(value != NULL) {
service = (Service *) malloc(sizeof(Service));
if(service != NULL) {
service->service_type = value;
service->control_url = NULL;
service->scpd_url = NULL;
service->next = NULL;
add_service_to_handle(handle, service);
strncpy(current_service_type, value, current_size_type_len);
} else {
fprintf(stderr, "could not allocate memory!\n");
}
}
}
else if(xmlStrcmp(attrib_name, (const xmlChar *) "controlURL") == 0) {
add_value_to_service(handle, reader, service, "controlURL", current_service_type);
}
else if(xmlStrcmp(attrib_name, (const xmlChar *) "SCPDURL") == 0) {
add_value_to_service(handle, reader, service, "SCPDURL", current_service_type);
}
xmlFree(attrib_name);
}
int parse_desc(SessionHandle *handle, char *xmlString) {
/*
* this initialize the library and check potential ABI mismatches
* between the version it was compiled for and the actual shared
* library used.
*/
LIBXML_TEST_VERSION
xmlTextReaderPtr reader;
int ret;
/*
* we have to remember the current service type
* service_type is like an unique ID
*/
size_t current_size_type_len = 256;
char current_service_type[current_size_type_len];
reader = xmlReaderForDoc((const xmlChar *) xmlString, NULL, NULL, 0);
if(reader != NULL) {
if(xmlTextReaderNormalization(reader) != 1) {
fprintf(stderr, "error during normalization\n");
return -1;
}
ret = xmlTextReaderRead(reader);
while (ret == 1) {
processNode(handle, reader, current_service_type, current_size_type_len);
ret = xmlTextReaderRead(reader);
}
xmlFreeTextReader(reader);
if (ret != 0) {
fprintf(stderr, "libxml2: failed to parse XML string\n");
return -1;
}
} else {
fprintf(stderr, "an error occoured\n");
return -1;
}
/* for debugging */
print_service_list(handle);
/*
* Cleanup function for the XML library.
*/
xmlCleanupParser();
return 0;
}
void get_services(SessionHandle *handle, char *xmlString) {
/* TODO: handle return value, for errors n stuff */
parse_desc(handle, xmlString);
}
| 2.703125 | 3 |
2024-11-18T22:24:15.211394+00:00 | 2020-09-27T17:32:57 | da1ab48e397f1b9f005627071e08ebaa1fabe363 | {
"blob_id": "da1ab48e397f1b9f005627071e08ebaa1fabe363",
"branch_name": "refs/heads/master",
"committer_date": "2020-09-27T17:32:57",
"content_id": "64fd854e849680af36c1db0861eb8fe1cc971919",
"detected_licenses": [
"MIT"
],
"directory_id": "6c3d1f038b9beb57f485eb1ab3441e8a3241ccfd",
"extension": "c",
"filename": "24l01.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 252792650,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 18802,
"license": "MIT",
"license_type": "permissive",
"path": "/transmitter/code-STM8S/Source/src/24l01.c",
"provenance": "stackv2-0115.json.gz:80379",
"repo_name": "TDA-2030/vesc-remote-controller",
"revision_date": "2020-09-27T17:32:57",
"revision_id": "e98204a9c6181dd96f9d7f6c3650079e0d703dce",
"snapshot_id": "767a2b489004bb64a7df666ba36d3e1d83709ea2",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/TDA-2030/vesc-remote-controller/e98204a9c6181dd96f9d7f6c3650079e0d703dce/transmitter/code-STM8S/Source/src/24l01.c",
"visit_date": "2022-05-18T16:07:59.816007"
} | stackv2 | /*
* @Author: zhouli
* @Date: 2020-04-04 15:28:44
* @LastEditTime: 2020-04-06 23:33:25
* @Description: NRF24L01 driver
*/
#include "type_def.h"
#include "24l01.h"
#include "delay.h"
//////////////////////////////////////////////////////////////////////////////////
//NRF24L01 驱动函数
/****************************************************
PB4----> IRQ MISO <----PC7
PC6----> MOSI SCK <----PC5
PB5----> CSN CE <----PA3
3V3----> VCC GND <----GND
****************************************************/
//////////////////////////////////////////////////////////////////////////////////
//函数:uint SPI_RW(uint uchar)
//功能:NRF24L01的SPI写时序
/*
u8 SPI_ReadWriteByte(u8 byte)
{
unsigned char i;
for(i = 0; i < 8; i++)
{
if (byte & 0x80)
NRF24L01_MOSI=1;
else
NRF24L01_MOSI=0;
byte <<= 1;
NRF24L01_SCK=1;
if (NRF24L01_MISO==1)
byte++;
NRF24L01_SCK=0;
}
NRF24L01_MOSI=1;
return byte;
}*/
/**************************************************************************
* 函数名:SPI_Init
* 描述 :SPI模块配置函数
* 输入 :无
*
* 输出 :无
* 返回 :无
* 调用 :外部调用
*************************************************************************/
void SPI_Init()
{
CLK_PCKENR1 |= 1 << 1;
SPI_CR1 = (0 << 7) | (0 << 6) | (1 << 3) | (1 << 2) | (0 << 1) | (0 << 0); /* 先发送MSB 先禁止SPI 波特率设为 fbus/4 设置为主模式 空闲状态时SCK为低电平 数据从第一个时钟边沿开始采样 */
SPI_CR2 = (0 << 7) | (0 << 5) | (0 << 4) | (0 << 2) | (1 << 1) | (1 << 0); /* 设为全双工模式 使能软件从设备管理 内部从设备选择为主模式 */
SPI_ICR = (0 << 7) | (0 << 6) | (0 << 5) | (0 << 4); /* 禁止所有中断 */
SPI_CR1 |= (1 << 6); /* 开启SPI模块 */
}
/**************************************************************************
* 函数名:SPI_SendByte
* 描述 :SPI模块发送函数
* 输入 :无
*
* 输出 :无
* 返回 :无
* 调用 :外部调用
*************************************************************************/
#define RXNE (1<<0) // 接收缓冲区非空
#define TXE (1<<1) //发送缓冲区空
unsigned char SPI_ReadWriteByte(unsigned char byte)
{
uint16_t retry = 0;
while (!(SPI_SR & TXE)) //等待发送寄存器为空
{
retry++;
if (retry >= 0XFE)return 0; //超时退出
}
SPI_DR = byte; //将发送的数据写到数据寄存器
retry = 0;
while (!(SPI_SR & RXNE)) // 等待接受寄存器满
{
retry++;
if (retry >= 0XFE)return 0; //超时退出
}
return SPI_DR; // 读数据寄存器
}
#undef RXNE
#undef TXE
#define drv_spi_read_write_byte SPI_ReadWriteByte
#define drv_delay_ms delay_ms
/**
* @brief :NRF24L01读寄存器
* @param :
@Addr:寄存器地址
* @note :地址在设备中有效
* @retval:读取的数据
*/
uint8_t NRF24L01_Read_Reg(uint8_t RegAddr)
{
uint8_t btmp;
RF24L01_SET_CS_LOW(); //片选
drv_spi_read_write_byte(NRF_READ_REG | RegAddr); //读命令 地址
btmp = drv_spi_read_write_byte(0xFF); //读数据
RF24L01_SET_CS_HIGH(); //取消片选
return btmp;
}
/**
* @brief :NRF24L01读指定长度的数据
* @param :
* @reg:地址
* @pBuf:数据存放地址
* @len:数据长度
* @note :数据长度不超过255,地址在设备中有效
* @retval:读取状态
*/
void NRF24L01_Read_Buf(uint8_t RegAddr, uint8_t *pBuf, uint8_t len)
{
uint8_t btmp;
RF24L01_SET_CS_LOW(); //片选
drv_spi_read_write_byte(NRF_READ_REG | RegAddr); //读命令 地址
for (btmp = 0; btmp < len; btmp ++)
{
*(pBuf + btmp) = drv_spi_read_write_byte(0xFF); //读数据
}
RF24L01_SET_CS_HIGH(); //取消片选
}
/**
* @brief :NRF24L01写寄存器
* @param :无
* @note :地址在设备中有效
* @retval:读写状态
*/
void NRF24L01_Write_Reg(uint8_t RegAddr, uint8_t Value)
{
RF24L01_SET_CS_LOW(); //片选
drv_spi_read_write_byte(NRF_WRITE_REG | RegAddr); //写命令 地址
drv_spi_read_write_byte(Value); //写数据
RF24L01_SET_CS_HIGH(); //取消片选
}
/**
* @brief :NRF24L01写指定长度的数据
* @param :
* @reg:地址
* @pBuf:写入的数据地址
* @len:数据长度
* @note :数据长度不超过255,地址在设备中有效
* @retval:写状态
*/
void NRF24L01_Write_Buf(uint8_t RegAddr, uint8_t *pBuf, uint8_t len)
{
uint8_t i;
RF24L01_SET_CS_LOW(); //片选
drv_spi_read_write_byte(NRF_WRITE_REG | RegAddr); //写命令 地址
for (i = 0; i < len; i ++)
{
drv_spi_read_write_byte(*(pBuf + i)); //写数据
}
RF24L01_SET_CS_HIGH(); //取消片选
}
/**
* @brief :清空TX缓冲区
* @param :无
* @note :无
* @retval:无
*/
void NRF24L01_Flush_Tx_Fifo(void)
{
RF24L01_SET_CS_LOW(); //片选
drv_spi_read_write_byte(FLUSH_TX); //清TX FIFO命令
RF24L01_SET_CS_HIGH(); //取消片选
}
/**
* @brief :清空RX缓冲区
* @param :无
* @note :无
* @retval:无
*/
void NRF24L01_Flush_Rx_Fifo(void)
{
RF24L01_SET_CS_LOW(); //片选
drv_spi_read_write_byte(FLUSH_RX); //清RX FIFO命令
RF24L01_SET_CS_HIGH(); //取消片选
}
/**
* @brief :重新使用上一包数据
* @param :无
* @note :无
* @retval:无
*/
void NRF24L01_Reuse_Tx_Payload(void)
{
RF24L01_SET_CS_LOW(); //片选
drv_spi_read_write_byte(REUSE_TX_PL); //重新使用上一包命令
RF24L01_SET_CS_HIGH(); //取消片选
}
/**
* @brief :NRF24L01空操作
* @param :无
* @note :无
* @retval:无
*/
void NRF24L01_Nop(void)
{
RF24L01_SET_CS_LOW(); //片选
drv_spi_read_write_byte(NOP); //空操作命令
RF24L01_SET_CS_HIGH(); //取消片选
}
/**
* @brief :NRF24L01读状态寄存器
* @param :无
* @note :无
* @retval:RF24L01状态
*/
uint8_t NRF24L01_Read_Status_Register(void)
{
uint8_t Status;
RF24L01_SET_CS_LOW(); //片选
Status = drv_spi_read_write_byte(NRF_READ_REG + STATUS); //读状态寄存器
RF24L01_SET_CS_HIGH(); //取消片选
return Status;
}
/**
* @brief :NRF24L01清中断
* @param :
@IRQ_Source:中断源
* @note :无
* @retval:清除后状态寄存器的值
*/
uint8_t NRF24L01_Clear_IRQ_Flag(uint8_t IRQ_Source)
{
uint8_t btmp = 0;
IRQ_Source &= (1 << RX_DR) | (1 << TX_DS) | (1 << MAX_RT); //中断标志处理
btmp = NRF24L01_Read_Status_Register(); //读状态寄存器
RF24L01_SET_CS_LOW(); //片选
drv_spi_read_write_byte(NRF_WRITE_REG + STATUS); //写状态寄存器命令
drv_spi_read_write_byte(IRQ_Source | btmp); //清相应中断标志
RF24L01_SET_CS_HIGH(); //取消片选
return (NRF24L01_Read_Status_Register()); //返回状态寄存器状态
}
/**
* @brief :读RF24L01中断状态
* @param :无
* @note :无
* @retval:中断状态
*/
uint8_t RF24L01_Read_IRQ_Status(void)
{
return (NRF24L01_Read_Status_Register() & ((1 << RX_DR) | (1 << TX_DS) | (1 << MAX_RT))); //返回中断状态
}
/**
* @brief :读FIFO中数据宽度
* @param :无
* @note :无
* @retval:数据宽度
*/
uint8_t NRF24L01_Read_Top_Fifo_Width(void)
{
uint8_t btmp;
RF24L01_SET_CS_LOW(); //片选
drv_spi_read_write_byte(R_RX_PL_WID); //读FIFO中数据宽度命令
btmp = drv_spi_read_write_byte(0xFF); //读数据
RF24L01_SET_CS_HIGH(); //取消片选
return btmp;
}
/**
* @brief :读接收到的数据
* @param :无
* @note :无
* @retval:
@pRxBuf:数据存放地址首地址
*/
uint8_t NRF24L01_Read_Rx_Payload(uint8_t *pRxBuf)
{
uint8_t Width, PipeNum;
PipeNum = (NRF24L01_Read_Reg(STATUS) >> 1) & 0x07; //读接收状态
Width = NRF24L01_Read_Top_Fifo_Width(); //读接收数据个数
RF24L01_SET_CS_LOW(); //片选
drv_spi_read_write_byte(RD_RX_PLOAD); //读有效数据命令
for (PipeNum = 0; PipeNum < Width; PipeNum ++)
{
*(pRxBuf + PipeNum) = drv_spi_read_write_byte(0xFF); //读数据
}
RF24L01_SET_CS_HIGH(); //取消片选
NRF24L01_Flush_Rx_Fifo(); //清空RX FIFO
return Width;
}
/**
* @brief :发送数据(带应答)
* @param :
* @pTxBuf:发送数据地址
* @len:长度
* @note :一次不超过32个字节
* @retval:无
*/
void NRF24L01_Write_Tx_Payload_Ack(uint8_t *pTxBuf, uint8_t len)
{
uint8_t btmp;
uint8_t length = (len > 32) ? 32 : len; //数据长达大约32 则只发送32个
NRF24L01_Flush_Tx_Fifo(); //清TX FIFO
RF24L01_SET_CS_LOW(); //片选
drv_spi_read_write_byte(WR_TX_PLOAD); //发送命令
for (btmp = 0; btmp < length; btmp ++)
{
drv_spi_read_write_byte(*(pTxBuf + btmp)); //发送数据
}
RF24L01_SET_CS_HIGH(); //取消片选
}
/**
* @brief :发送数据(不带应答)
* @param :
* @pTxBuf:发送数据地址
* @len:长度
* @note :一次不超过32个字节
* @retval:无
*/
void NRF24L01_Write_Tx_Payload_NoAck(uint8_t *pTxBuf, uint8_t len)
{
if (len > 32 || len == 0)
{
return ; //数据长度大于32 或者等于0 不执行
}
RF24L01_SET_CS_LOW(); //片选
drv_spi_read_write_byte(WR_TX_PLOAD_NACK); //发送命令
while (len--)
{
drv_spi_read_write_byte(*pTxBuf); //发送数据
pTxBuf++;
}
RF24L01_SET_CS_HIGH(); //取消片选
}
/**
* @brief :在接收模式下向TX FIFO写数据(带ACK)
* @param :
* @pData:数据地址
* @len:长度
* @note :一次不超过32个字节
* @retval:无
*/
void NRF24L01_Write_Tx_Payload_InAck(uint8_t *pData, uint8_t len)
{
uint8_t btmp;
len = (len > 32) ? 32 : len; //数据长度大于32个则只写32个字节
RF24L01_SET_CS_LOW(); //片选
drv_spi_read_write_byte(W_ACK_PLOAD); //命令
for (btmp = 0; btmp < len; btmp ++)
{
drv_spi_read_write_byte(*(pData + btmp)); //写数据
}
RF24L01_SET_CS_HIGH(); //取消片选
}
/**
* @brief :设置发送地址
* @param :
* @pAddr:地址存放地址
* @len:长度
* @note :无
* @retval:无
*/
void NRF24L01_Set_TxAddr(uint8_t *pAddr, uint8_t len)
{
len = (len > 5) ? 5 : len; //地址不能大于5个字节
NRF24L01_Write_Buf(TX_ADDR, pAddr, len); //写地址
}
/**
* @brief :设置接收通道地址
* @param :
* @PipeNum:通道
* @pAddr:地址存肥着地址
* @Len:长度
* @note :通道不大于5 地址长度不大于5个字节
* @retval:无
*/
void NRF24L01_Set_RxAddr(uint8_t PipeNum, uint8_t *pAddr, uint8_t Len)
{
Len = (Len > 5) ? 5 : Len;
PipeNum = (PipeNum > 5) ? 5 : PipeNum; //通道不大于5 地址长度不大于5个字节
NRF24L01_Write_Buf(RX_ADDR_P0 + PipeNum, pAddr, Len); //写入地址
}
/**
* @brief :设置通信速度
* @param :
* @Speed:速度
* @note :无
* @retval:无
*/
void NRF24L01_Set_Speed(nRf24l01SpeedType Speed)
{
uint8_t btmp = 0;
btmp = NRF24L01_Read_Reg(RF_SETUP);
btmp &= ~((1 << 5) | (1 << 3));
if (Speed == SPEED_250K) //250K
{
btmp |= (1 << 5);
}
else if (Speed == SPEED_1M) //1M
{
btmp &= ~((1 << 5) | (1 << 3));
}
else if (Speed == SPEED_2M) //2M
{
btmp |= (1 << 3);
}
NRF24L01_Write_Reg(RF_SETUP, btmp);
}
/**
* @brief :设置功率
* @param :
* @Speed:速度
* @note :无
* @retval:无
*/
void NRF24L01_Set_Power(nRf24l01PowerType Power)
{
uint8_t btmp;
btmp = NRF24L01_Read_Reg(RF_SETUP) & ~0x07;
switch (Power)
{
case POWER_F18DBM:
btmp |= PWR_18DB;
break;
case POWER_F12DBM:
btmp |= PWR_12DB;
break;
case POWER_F6DBM:
btmp |= PWR_6DB;
break;
case POWER_0DBM:
btmp |= PWR_0DB;
break;
default:
break;
}
NRF24L01_Write_Reg(RF_SETUP, btmp);
}
/**
* @brief :设置频率
* @param :
* @FreqPoint:频率设置参数
* @note :值不大于127
* @retval:无
*/
void RF24LL01_Write_Hopping_Point(uint8_t FreqPoint)
{
NRF24L01_Write_Reg(RF_CH, FreqPoint & 0x7F);
}
//NRF24L01检查函数
//返回:0:成功;1:失败
u8 NRF24L01_Check(void)
{
u8 buf[5] = {0XA5, 0XA5, 0XA5, 0XA5, 0XA5};
u8 i;
NRF24L01_Write_Buf(NRF_WRITE_REG + TX_ADDR, buf, 5); //д?5??????.
NRF24L01_Read_Buf(TX_ADDR, buf, 5); //??д????
for (i = 0; i < 5; i++)if (buf[i] != 0XA5)break;
if (i != 5)return 1; //??24L01??
return 0; //???24L01
}
/**
* @brief :设置模式
* @param :
* @Mode:模式发送模式或接收模式
* @note :无
* @retval:无
*/
void RF24L01_Set_Mode(nRf24l01ModeType Mode)
{
uint8_t controlreg = 0;
RF24L01_SET_CE_LOW();
controlreg = NRF24L01_Read_Reg(CONFIG);
if (Mode == MODE_TX)
{
controlreg &= ~(1 << PRIM_RX);
controlreg |= (1 << PWR_UP);
NRF24L01_Write_Reg(CONFIG, controlreg);
}
else if (Mode == MODE_RX)
{
controlreg |= (1 << PRIM_RX);
controlreg |= (1 << PWR_UP);
NRF24L01_Write_Reg(CONFIG, controlreg);
}
else if (Mode == MODE_PD)
{
controlreg &= ~(1 << PWR_UP);
NRF24L01_Write_Reg(CONFIG, controlreg);
}
RF24L01_SET_CE_HIGH();
delay_us(130);
}
/**
* @brief :NRF24L01发送一次数据
* @param :
* @txbuf:待发送数据首地址
* @Length:发送数据长度
* @note :无
* @retval:
* MAX_TX:达到最大重发次数
* TX_OK:发送完成
* 0xFF:其他原因
*/
uint8_t NRF24L01_TxPacket(uint8_t *txbuf, uint8_t Length)
{
// uint8_t l_Status = 0;
// uint16_t l_MsTimes = 0;
// RF24L01_SET_CS_LOW( ); //片选
// drv_spi_read_write_byte( FLUSH_TX );
// RF24L01_SET_CS_HIGH( );
RF24L01_SET_CE_LOW();
NRF24L01_Write_Buf(WR_TX_PLOAD, txbuf, Length); //写数据到TX BUF 32字节 TX_PLOAD_WIDTH
RF24L01_SET_CE_HIGH(); //启动发送
// while( 0 != RF24L01_GET_IRQ_STATUS( ))
// {
// drv_delay_ms( 1 );
// if( 500 == l_MsTimes++ ) //500ms还没有发送成功,重新初始化设备
// {
//// NRF24L01_Gpio_Init( );
//// RF24L01_Init( );
// RF24L01_Set_Mode( MODE_TX );
// break;
// }
// }
// l_Status = NRF24L01_Read_Reg(STATUS); //读状态寄存器
// NRF24L01_Write_Reg( STATUS, l_Status ); //清除TX_DS或MAX_RT中断标志
//
// if( l_Status & MAX_TX ) //达到最大重发次数
// {
// NRF24L01_Write_Reg( FLUSH_TX,0xff ); //清除TX FIFO寄存器
// return MAX_TX;
// }
// if( l_Status & TX_OK ) //发送完成
// {
// return TX_OK;
// }
return 0xFF; //其他原因发送失败
}
/**
* @brief :NRF24L01接收数据
* @param :
* @rxbuf:接收数据存放地址
* @note :无
* @retval:接收到的数据个数
*/
uint8_t NRF24L01_RxPacket(uint8_t *rxbuf)
{
uint8_t l_Status = 0, l_RxLength = 0, l_100MsTimes = 0;
RF24L01_SET_CS_LOW(); //片选
drv_spi_read_write_byte(FLUSH_RX);
RF24L01_SET_CS_HIGH();
while (0 != RF24L01_GET_IRQ_STATUS())
{
drv_delay_ms(100);
if (30 == l_100MsTimes++) //3s没接收过数据,重新初始化模块
{
// NRF24L01_Gpio_Init( );
// RF24L01_Init( );
RF24L01_Set_Mode(MODE_RX);
break;
}
}
l_Status = NRF24L01_Read_Reg(STATUS); //读状态寄存器
NRF24L01_Write_Reg(STATUS, l_Status); //清中断标志
if (l_Status & RX_OK) //接收到数据
{
l_RxLength = NRF24L01_Read_Reg(R_RX_PL_WID); //读取接收到的数据个数
NRF24L01_Read_Buf(RD_RX_PLOAD, rxbuf, l_RxLength); //接收到数据
NRF24L01_Write_Reg(FLUSH_RX, 0xff); //清除RX FIFO
return l_RxLength;
}
return 0; //没有收到数据
}
const uint8_t TX_ADDRESS[5] = {'F', 'U', 'C', 'K', '!'}; //发送地址
const uint8_t RX_ADDRESS_0[5] = {'F', 'U', 'C', 'K', '!'}; //P0接收地址
/**
* @brief :RF24L01模块初始化
* @param :无
* @note :无
* @retval:无
*/
void RF24L01_Init(void)
{
RF24L01_SET_CE_LOW();
//NRF24L01_Clear_IRQ_Flag( IRQ_ALL );
#if DYNAMIC_PACKET == 1
NRF24L01_Write_Reg(DYNPD, (1 << 0)); //使能通道1动态数据长度
NRF24L01_Write_Reg(FEATRUE, 0x07);
NRF24L01_Read_Reg(DYNPD);
NRF24L01_Read_Reg(FEATRUE);
#elif DYNAMIC_PACKET == 0
NRF24L01_Write_Reg(RX_PW_P0, FIXED_PACKET_LEN); //固定数据长度
#endif //DYNAMIC_PACKET
NRF24L01_Write_Reg(EN_AA, (1 << ENAA_P0)); //通道0自动应答
NRF24L01_Write_Reg(EN_RXADDR, (1 << ERX_P0)); //通道0接收
NRF24L01_Write_Reg(SETUP_AW, AW_5BYTES); //地址宽度 5个字节
NRF24L01_Write_Reg(SETUP_RETR, ARD_4000US |
(REPEAT_CNT & 0x0F)); //重复等待时间 250us
RF24LL01_Write_Hopping_Point(80); //初始化通道
NRF24L01_Set_Power(POWER_0DBM); //设置功率
NRF24L01_Set_Speed(SPEED_2M); //设置通信速度
NRF24L01_Set_TxAddr((uint8_t *)TX_ADDRESS, 5); //设置TX地址
NRF24L01_Set_RxAddr(0, (uint8_t *)RX_ADDRESS_0, 5); //设置RX地址
NRF24L01_Write_Reg(CONFIG, /*( 1<<MASK_MAX_RT ) |*/ //屏蔽接收中断
(1 << EN_CRC) | //使能CRC
(1 << CRCO) | //2个字节
(1 << PWR_UP)); //开启设备
}
/**
* @brief :NRF24L01基本初始化
* @param :无
* @note :无
* @retval:无
*/
void NRF24L01_Base_Init(void)
{
//引脚配置
//CE 配置为输出 IRQ配置为输入
PC_DDR |= ((1 << 5) | (1 << 6)); //PC4,5,6输出模式
PC_CR1 |= ((1 << 5) | (1 << 6)); //PC4,5,6推挽输出
PC_CR2 |= ((1 << 5) | (1 << 6)); //10mhz输出
PD_DDR |= 1 << 2; //PE5输出模式
PD_CR1 |= 1 << 2; //PE5推挽输出
PD_CR2 |= 1 << 2; //10mhz输出
PE_DDR |= 1 << 5; //PE5输出模式
PE_CR1 |= 1 << 5; //PE5推挽输出
PE_CR2 |= 1 << 5; //10mhz输出
PC_DDR &= ~(1 << 7);
PC_CR1 |= 1 << 7; //PC7上拉输入
PD_DDR &= ~(1 << 0);
PD_CR1 |= 1 << 0; //PD0上拉输入
PD_CR2 |= 1 << 0; //PD0中断输入
EXTI_CR1 |= (2 << 6); //PD下降沿触发
ITC_SPR2_VECT6SPR = 2;//中断优先级2
SPI_Init(); //初始化SPI
NRF24L01_CE = 0; //使能24L01
NRF24L01_CSN = 1; //SPI片选取消
}
| 2.40625 | 2 |
2024-11-18T22:24:15.281893+00:00 | 2019-06-14T06:41:02 | 3ccc94c9319399a5552771289a75528ceb0c7be6 | {
"blob_id": "3ccc94c9319399a5552771289a75528ceb0c7be6",
"branch_name": "refs/heads/master",
"committer_date": "2019-06-14T06:41:02",
"content_id": "579f5c2f84cb8960b43466631cc7a6a9de7db75a",
"detected_licenses": [
"0BSD"
],
"directory_id": "b4b6340bccae5f523c017cc19ca8e64b840d9233",
"extension": "c",
"filename": "28bjy48.c",
"fork_events_count": 1,
"gha_created_at": "2019-02-26T16:44:45",
"gha_event_created_at": "2019-05-09T08:54:54",
"gha_language": "C",
"gha_license_id": "NOASSERTION",
"github_id": 172750924,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3101,
"license": "0BSD",
"license_type": "permissive",
"path": "/28bjy48.c",
"provenance": "stackv2-0115.json.gz:80509",
"repo_name": "0Ekho/avr_drivers",
"revision_date": "2019-06-14T06:41:02",
"revision_id": "6292624113d7612d523c673b25e3483575097dd9",
"snapshot_id": "29950c6a00d2c47361b0daefcbce42b0cc7c840d",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/0Ekho/avr_drivers/6292624113d7612d523c673b25e3483575097dd9/28bjy48.c",
"visit_date": "2020-04-25T11:37:29.524157"
} | stackv2 | /* BSD-0
Copyright (C) 2019, Ekho <ekho@ekho.email>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
------------------------------------------------------------------------------
*/
/* basic driver for 28BYJ-48 5V stepper motor
*
* 4 pin connections are supported via the sm4 set of functions / macros.
* Full stepping and half stepping (4 pin only)
*
* STEPS_28BJY48 is defined to 1 full rotation (2048 steps)
*
* Stepper pins in[1-4] MUST share a port, by default this is PORTD
* PORT_28BJY48 may be defined in your makefile to change this.
*
* Recommend disabling the stepper when not in use to reduce power / prevent
* motor from overheating depending on what it is being used for.
*
*
* Example usage:
* // set pins IN1 IN2 IN3 IN4
* struct stepmotor4 stepper = {{PORTD0, PORTD1, PORTD2, PORTD3}, 0};
* DDRD |= _BV(DDD0) | _BV(DDD1) | _BV(DDD2) | _BV(DDD3);
* // steps to run, ~ms delay between steps
* sm4_run_fs(&stepper, STEPS_28BJY48, 10);
* // ^ this causes one full revolution forward
* sm4_disable(&stepper);
*
*/
// TODO: 2 pin connection support
// TODO: shiftregister support for driving multiple steppers at once
#include <avr/io.h>
#include <stdint.h>
#include <stdlib.h>
#include <util/delay.h>
#include "28bjy48.h"
/* ------------------------------------------------------------------------- */
// Even index is full steps
static const uint8_t steps_28bjy48[8] = {
// forwards 4321
0x03, // 0011
0x02, // 0010
0x06, // 0110
0x04, // 0100
0x0C, // 1100
0x08, // 1000
0x09, // 1001
0x01, // 0001
// backwards 1234
};
/* ------------------------------------------------------------------------- */
void sm4_step(struct stepmotor4 *sm, uint8_t hs, uint8_t f)
{
for (uint8_t i = 0; i < 4; i++) {
// reverse pinout of stepper to run backwards
uint8_t j = f ? i : (3 - i);
if ((steps_28bjy48[sm->s] >> i) & 0x01) {
PORT_28BJY48 |= _BV(sm->in[j]);
} else {
PORT_28BJY48 &= ~_BV(sm->in[j]);
}
}
sm->s = (sm->s + (hs ? 1 : 2)) % 8;
}
void sm4_disable(struct stepmotor4 *sm) {
PORT_28BJY48 &= ~(_BV(sm->in[0]) | _BV(sm->in[1]) | _BV(sm->in[2]) |\
_BV(sm->in[3]));
}
void sm4_run(struct stepmotor4 *sm, int16_t cnt, uint16_t d, uint8_t hs)
{
for (int16_t i = 0; i < abs(cnt); i++) {
sm4_step(sm, hs, (cnt > 0));
for (uint16_t j = 0; j < d; j++) {
_delay_ms(1);
}
}
}
| 2.28125 | 2 |
2024-11-18T22:24:15.998851+00:00 | 2018-04-16T08:11:19 | dd43f81dc05080df0e20b24e105366236a04ac3f | {
"blob_id": "dd43f81dc05080df0e20b24e105366236a04ac3f",
"branch_name": "refs/heads/master",
"committer_date": "2018-04-16T08:11:19",
"content_id": "f854f0816b113e554b3c7d0d343ddc5d25e7c40f",
"detected_licenses": [
"MIT"
],
"directory_id": "5d29b3d4c897af2a153132b5e6f11b5f908d49b1",
"extension": "c",
"filename": "recover.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 129636289,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1180,
"license": "MIT",
"license_type": "permissive",
"path": "/pset4/recover/recover.c",
"provenance": "stackv2-0115.json.gz:81544",
"repo_name": "s10singh97/cs50",
"revision_date": "2018-04-16T08:11:19",
"revision_id": "c46b7118e4742f0a4c79348bdec505c886b9e1b9",
"snapshot_id": "cdaf433059d754c0180b9f3d004a1debc531dd58",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/s10singh97/cs50/c46b7118e4742f0a4c79348bdec505c886b9e1b9/pset4/recover/recover.c",
"visit_date": "2020-03-10T23:12:34.818551"
} | stackv2 | #include<cs50.h>
#include<stdio.h>
#include<string.h>
#define MAX 512
unsigned char buffer[MAX];
char name[8];
int main(int argc, char *argv[])
{
if(argc != 2)
{
fprintf(stderr, "Usage : ./recover image\n");
return 1;
}
//open input file
FILE *inptr = fopen(argv[1], "r");
FILE *outptr = NULL;
if (inptr == NULL)
{
fprintf(stderr, "Could not open %s.\n", argv[1]);
return 2;
}
int count = 0;
//reading infile till reaching the end of file
while(fread(buffer, 512, 1, inptr) == 1)
{
//check for jpeg image
if((buffer[0] == 0xff) && (buffer[1] == 0xd8) && (buffer[2] == 0xff) && ((buffer[3] & 0xf0) == 0xe0))
{
//printing jpegs
sprintf(name, "%03i.jpg", count);
//opening output file
outptr = fopen(name, "w");
//writing outfile
fwrite(buffer, 512, 1, outptr);
count++;
}
else
{
//for the remaining data
if(outptr != NULL)
fwrite(buffer, 512, 1, outptr);
}
}
fclose(outptr);
fclose(inptr);
return 0;
} | 2.9375 | 3 |
2024-11-18T22:24:16.139640+00:00 | 2019-11-13T17:29:51 | 028c63796d2bbf9d133c1984a01e7f5cb9d57671 | {
"blob_id": "028c63796d2bbf9d133c1984a01e7f5cb9d57671",
"branch_name": "refs/heads/master",
"committer_date": "2019-11-13T17:29:51",
"content_id": "3bf99c96b05a459b685697addacf51ef99362a5b",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "09fbf89e1a8f5bfd259ecc750978ea6f0ce6f550",
"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": 221279364,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4207,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/gd32v_julia/src/main.c",
"provenance": "stackv2-0115.json.gz:81672",
"repo_name": "juliusf/longan-nano",
"revision_date": "2019-11-13T17:29:51",
"revision_id": "a84310424542ddd2be872d0e3bb2f830dc270f65",
"snapshot_id": "8076506fe9b9b591781a62ccf6fce8dcbec433cd",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/juliusf/longan-nano/a84310424542ddd2be872d0e3bb2f830dc270f65/gd32v_julia/src/main.c",
"visit_date": "2020-09-08T23:44:40.820703"
} | stackv2 | #include "lcd/lcd.h"
#include "gd32v_pjt_include.h"
#include "color.h"
#include "fast_hsv2rgb.h"
#include <string.h>
#include <fastmath.h>
#define RESX 160
#define RESY 40 // Render half-pictures
u16 buff[RESX][RESY];
#define PUTPIXEL(x, y, col)({ \
buff[x][y] = (col.R << 11) + (col.G << 5) + col.B; \
})
void showHalfPicture(int upper)
{
if (upper)
{
LCD_Address_Set(0,0,159,39);
}else
{
LCD_Address_Set(0,40,159,79);
}
for(int y= 0; y < RESY; y++)
for(int x= 0; x < RESX; x++)
{
LCD_WR_DATA(buff[x][y]);
}
}
void init_uart0(void)
{
/* enable GPIO clock */
rcu_periph_clock_enable(RCU_GPIOA);
/* enable USART clock */
rcu_periph_clock_enable(RCU_USART0);
/* connect port to USARTx_Tx */
gpio_init(GPIOA, GPIO_MODE_AF_PP, GPIO_OSPEED_50MHZ, GPIO_PIN_9);
/* connect port to USARTx_Rx */
gpio_init(GPIOA, GPIO_MODE_IN_FLOATING, GPIO_OSPEED_50MHZ, GPIO_PIN_10);
/* USART configure */
usart_deinit(USART0);
usart_baudrate_set(USART0, 115200U);
usart_word_length_set(USART0, USART_WL_8BIT);
usart_stop_bit_set(USART0, USART_STB_1BIT);
usart_parity_config(USART0, USART_PM_NONE);
usart_hardware_flow_rts_config(USART0, USART_RTS_DISABLE);
usart_hardware_flow_cts_config(USART0, USART_CTS_DISABLE);
usart_receive_config(USART0, USART_RECEIVE_ENABLE);
usart_transmit_config(USART0, USART_TRANSMIT_ENABLE);
usart_enable(USART0);
usart_interrupt_enable(USART0, USART_INT_RBNE);
}
// julia set code taken from https://lodev.org/cgtutor/juliamandelbrot.html
void julia(int offsetX, int offsetY, double zoom, int numit)
{
int h = RESY/2; // render half-pictures
int w = RESY;
double cRe, cIm; //real and imaginary part of the constant c, determinate shape of the Julia Set
double newRe, newIm, oldRe, oldIm; //real and imaginary parts of new and old
double moveX = 0, moveY = 0; //you can change these to zoom and change position
RGB color; //the RGB color value for the pixel
int maxIterations = numit; //after how much iterations the function should stop
//pick some values for the constant c, this determines the shape of the Julia Set
cRe = -0.7;
cIm = 0.27015;
//loop through every pixel
for(int y = 0 + offsetY; y < h + offsetY; y++)
for(int x = 0 + offsetX; x < w + offsetX; x++)
{
//calculate the initial real and imaginary part of z, based on the pixel location and zoom and position values
newRe = 1.5 * (x - w / 2) / (0.5 * zoom * w) + moveX;
newIm = (y - h / 2) / (0.5 * zoom * h) + moveY;
//i will represent the number of iterations
int i;
//start the iteration process
for(i = 0; i < maxIterations; i++)
{
//remember value of previous iteration
oldRe = newRe;
oldIm = newIm;
//the actual iteration, the real and imaginary part are calculated
newRe = oldRe * oldRe - oldIm * oldIm + cRe;
newIm = 2 * oldRe * oldIm + cIm;
//if the point is outside the circle with radius 2: stop
if((newRe * newRe + newIm * newIm) > 4) break;
}
fast_hsv2rgb_32bit(i%256,255,255*(i<maxIterations),&(color.R), &(color.G), &(color.B));
PUTPIXEL(x - offsetX, y - offsetY , color);
}
}
int main(void)
{
rcu_periph_clock_enable(RCU_GPIOA);
rcu_periph_clock_enable(RCU_GPIOC);
gpio_init(GPIOC, GPIO_MODE_OUT_PP, GPIO_OSPEED_50MHZ, GPIO_PIN_13);
gpio_init(GPIOA, GPIO_MODE_OUT_PP, GPIO_OSPEED_50MHZ, GPIO_PIN_1|GPIO_PIN_2);
init_uart0();
Lcd_Init(); // init OLED
LCD_Clear(BLACK);
BACK_COLOR=BLACK;
LEDR(1);
LEDG(1);
LEDB(1);
double zoom = 3.0;
int numit = 64;
for(;;)
{
LEDR_TOG;
julia(0,0, zoom, numit);
showHalfPicture(1);
julia(0,0 + 40, zoom, numit);
LEDG_TOG;
showHalfPicture(0);
numit += 10;
if (numit > 256)
{
numit = 256;
zoom += 0.1;
}
}
}
| 2.484375 | 2 |
2024-11-18T22:24:16.425337+00:00 | 2022-05-12T15:57:07 | 55367193f1e72832f5ae3d96df83609402486663 | {
"blob_id": "55367193f1e72832f5ae3d96df83609402486663",
"branch_name": "refs/heads/master",
"committer_date": "2022-05-12T15:57:07",
"content_id": "98141948819e93dd35d4bcd740f4cdf6e0651d84",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "c4b453709af5626e42c08ca0767508b113c1f82b",
"extension": "h",
"filename": "builtins.h",
"fork_events_count": 0,
"gha_created_at": "2017-04-30T07:35:44",
"gha_event_created_at": "2023-04-18T11:11:21",
"gha_language": "Ruby",
"gha_license_id": null,
"github_id": 89836714,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2768,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/share/FreeBSD-jail-webdev-skel/usr/local/cbsd/bin/cbsdsh/builtins.h",
"provenance": "stackv2-0115.json.gz:81933",
"repo_name": "mergar/tmp",
"revision_date": "2022-05-12T15:57:07",
"revision_id": "55e80e2de3313173fdd67195e84cc1ec27d61d19",
"snapshot_id": "64bfb8743ce162bddde4513e2c4016a9959c26f2",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/mergar/tmp/55e80e2de3313173fdd67195e84cc1ec27d61d19/share/FreeBSD-jail-webdev-skel/usr/local/cbsd/bin/cbsdsh/builtins.h",
"visit_date": "2023-05-01T16:05:39.854292"
} | stackv2 | /*
* This file was generated by the mkbuiltins program.
*/
#include <sys/cdefs.h>
#define BLTINCMD 0
#define ALIASCMD 1
#define BGCMD 2
#define BINDCMD 3
#define BREAKCMD 4
#define CDCMD 5
#define COMMANDCMD 6
#define DOTCMD 7
#define ECHOCMD 8
#define EVALCMD 9
#define EXECCMD 10
#define EXITCMD 11
#define LETCMD 12
#define EXPORTCMD 13
#define FALSECMD 14
#define FGCMD 15
#define GETOPTSCMD 16
#define HASHCMD 17
#define HISTCMD 18
#define JOBIDCMD 19
#define JOBSCMD 20
#define KILLCMD 21
#define LOCALCMD 22
#define PRINTFCMD 23
#define PWDCMD 24
#define READCMD 25
#define RETURNCMD 26
#define SETCMD 27
#define SETVARCMD 28
#define SHIFTCMD 29
#define TESTCMD 30
#define TIMESCMD 31
#define TRAPCMD 32
#define TRUECMD 33
#define TYPECMD 34
#define ULIMITCMD 35
#define UMASKCMD 36
#define UNALIASCMD 37
#define UNSETCMD 38
#define WAITCMD 39
#define WORDEXPCMD 40
#define SQLITECMD 41
#define ABOUTCMD 42
#define VERSIONCMD 43
#define HISTORYCMD 44
#define IS_NUMBERCMD 45
#define SUBSTRCMD 46
#define SPAWNCMD 47
#define CBSD_PWAITCMD 48
#define STRLENCMD 49
#define CBSD_FWATCHCMD 50
#define UPDATE_IDLECMD 51
struct builtincmd {
const char *name;
int code;
int special;
};
extern int (*const builtinfunc[])(int, char **);
extern const struct builtincmd builtincmd[];
int bltincmd(int, char **);
int aliascmd(int, char **);
int bgcmd(int, char **);
int bindcmd(int, char **);
int breakcmd(int, char **);
int cdcmd(int, char **);
int commandcmd(int, char **);
int dotcmd(int, char **);
int echocmd(int, char **);
int evalcmd(int, char **);
int execcmd(int, char **);
int exitcmd(int, char **);
int letcmd(int, char **);
int exportcmd(int, char **);
int falsecmd(int, char **);
int fgcmd(int, char **);
int getoptscmd(int, char **);
int hashcmd(int, char **);
int histcmd(int, char **);
int jobidcmd(int, char **);
int jobscmd(int, char **);
int killcmd(int, char **);
int localcmd(int, char **);
int printfcmd(int, char **);
int pwdcmd(int, char **);
int readcmd(int, char **);
int returncmd(int, char **);
int setcmd(int, char **);
int setvarcmd(int, char **);
int shiftcmd(int, char **);
int testcmd(int, char **);
int timescmd(int, char **);
int trapcmd(int, char **);
int truecmd(int, char **);
int typecmd(int, char **);
int ulimitcmd(int, char **);
int umaskcmd(int, char **);
int unaliascmd(int, char **);
int unsetcmd(int, char **);
int waitcmd(int, char **);
int wordexpcmd(int, char **);
int sqlitecmd(int, char **);
int aboutcmd(int, char **);
int versioncmd(int, char **);
int historycmd(int, char **);
int is_numbercmd(int, char **);
int substrcmd(int, char **);
int spawncmd(int, char **);
int cbsd_pwaitcmd(int, char **);
int strlencmd(int, char **);
int cbsd_fwatchcmd(int, char **);
int update_idlecmd(int, char **);
| 2.015625 | 2 |
2024-11-18T22:24:16.590448+00:00 | 2018-12-25T05:35:20 | 2041231a24791c65dba1be110dd76c339a4a5aa0 | {
"blob_id": "2041231a24791c65dba1be110dd76c339a4a5aa0",
"branch_name": "refs/heads/master",
"committer_date": "2018-12-25T05:35:20",
"content_id": "d656f986439a71a8d302c1f78f03ac83d572a67c",
"detected_licenses": [
"MIT"
],
"directory_id": "8e9da99337f04212a5efd4f149f1075e8631f43e",
"extension": "h",
"filename": "input.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": 6488,
"license": "MIT",
"license_type": "permissive",
"path": "/input.h",
"provenance": "stackv2-0115.json.gz:82194",
"repo_name": "InventYang/anti-aliasing-demo",
"revision_date": "2018-12-25T05:35:20",
"revision_id": "1a6dec2f86f00f4aac36af2936df80b93d9503bb",
"snapshot_id": "63051306ac7e6feaa1b84ffe60f56058a1327833",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/InventYang/anti-aliasing-demo/1a6dec2f86f00f4aac36af2936df80b93d9503bb/input.h",
"visit_date": "2023-08-14T05:04:35.999711"
} | stackv2 | #pragma once
#include "primitives.h"
enum Game_Key
{
GK_ESCAPE,
GK_W,
GK_A,
GK_S,
GK_D,
GK_E,
GK_0,
GK_1,
GK_2,
GK_3,
GK_4,
GK_5,
GK_6,
GK_7,
GK_8,
GK_9,
GK_NUM_
};
enum Game_Keymod : u8
{
GKM_LSHIFT = 0x01,
GKM_RSHIFT = 0x02,
GKM_LCNTL = 0x04,
GKM_RCNTL = 0x08,
GKM_LALT = 0x10,
GKM_RALT = 0x20,
GKM_SHIFT = GKM_LSHIFT | GKM_RSHIFT,
GKM_CNTL = GKM_LCNTL | GKM_RCNTL,
GKM_ALT = GKM_LALT | GKM_RALT,
GKM_CS = GKM_CNTL | GKM_SHIFT,
GKM_CA = GKM_CNTL | GKM_ALT,
GKM_SA = GKM_SHIFT | GKM_ALT,
GKM_CSA = GKM_CNTL | GKM_SHIFT | GKM_ALT,
GKM_ALL = GKM_CSA
};
struct Game_Keyboard_State
{
bit32 keys;
flag8 mod[GK_NUM_];
};
enum Game_Mouse_Button : u32
{
MOUSE_LEFT = 0x01,
MOUSE_RIGHT = 0x02,
MOUSE_MIDDLE = 0x04,
};
struct Game_Mouse_State
{
u32 buttons = 0;
u32 x = 0;
u32 y = 0;
b32 dragging = false;
s32 xDrag = 0;
s32 yDrag = 0;
};
struct Game_Mouse
{
Game_Mouse_State cur;
Game_Mouse_State prev;
b32 drag_started() const { return !prev.dragging && cur.dragging; }
};
enum Game_Controller_Button : u32
{
BUTTON_A = 0x01,
BUTTON_B = 0x02,
BUTTON_X = 0x04,
BUTTON_Y = 0x08,
};
enum Game_Axis
{
AXIS_LEFT_X,
AXIS_LEFT_Y,
AXIS_RIGHT_X,
AXIS_RIGHT_Y,
AXIS_NUM_
};
struct Game_Controller_State
{
u32 buttons = 0;
float axes[AXIS_NUM_] = { 0.0f };
};
struct Game_Controller
{
Game_Controller_State cur;
Game_Controller_State prev;
};
struct Game_Keyboard
{
Game_Keyboard_State cur;
Game_Keyboard_State prev;
b32 pressed(Game_Key key) const;
b32 pressed(Game_Key key, Game_Keymod mod, Game_Keymod mod2 = GKM_ALL, Game_Keymod mod3 = GKM_ALL) const;
b32 pressed_exactly(Game_Key key, Game_Keymod mod) const;
b32 released(Game_Key key) const;
b32 released(Game_Key key, Game_Keymod mod, Game_Keymod mod2 = GKM_ALL, Game_Keymod mod3 = GKM_ALL) const;
b32 released_exactly(Game_Key key, Game_Keymod mod) const;
b32 held(Game_Key key) const;
b32 held(Game_Key key, Game_Keymod mod, Game_Keymod mod2 = GKM_ALL, Game_Keymod mod3 = GKM_ALL) const;
b32 held_exactly(Game_Key key, Game_Keymod mod) const;
b32 down(Game_Key key) const;
b32 down(Game_Key key, Game_Keymod mod, Game_Keymod mod2 = GKM_ALL, Game_Keymod mod3 = GKM_ALL) const;
b32 down_exactly(Game_Key key, Game_Keymod mod) const;
};
struct Game_Input
{
Game_Keyboard keyboard;
Game_Controller controller;
Game_Mouse mouse;
};
inline b32
Game_Keyboard::pressed(Game_Key key) const
{
b32 wasDown = prev.keys.is_set(key);
b32 isDown = cur.keys.is_set(key);
return !wasDown && isDown;
}
inline b32
Game_Keyboard::pressed(Game_Key key, Game_Keymod mod, Game_Keymod mod2, Game_Keymod mod3) const
{
flag8 prevMod = prev.mod[key];
flag8 curMod = cur.mod[key];
b32 wasDown = (prevMod & mod) && (prevMod & mod2) && (prevMod & mod3) && prev.keys.is_set(key);
b32 isDown = (curMod & mod) && (curMod & mod2) && (curMod & mod3) && cur.keys.is_set(key);
return !wasDown && isDown;
}
inline b32
Game_Keyboard::pressed_exactly(Game_Key key, Game_Keymod mod) const
{
b32 wasDown = (prev.mod[key] & mod) == mod && prev.keys.is_set(key);
b32 isDown = (cur.mod[key] & mod) == mod && cur.keys.is_set(key);
return !wasDown && isDown;
}
inline b32
Game_Keyboard::released(Game_Key key) const
{
b32 wasDown = prev.keys.is_set(key);
b32 isDown = cur.keys.is_set(key);
return wasDown && !isDown;
}
inline b32
Game_Keyboard::released(Game_Key key, Game_Keymod mod, Game_Keymod mod2, Game_Keymod mod3) const
{
flag8 prevMod = prev.mod[key];
flag8 curMod = cur.mod[key];
b32 wasDown = (prevMod & mod) && (prevMod & mod2) && (prevMod & mod3) && prev.keys.is_set(key);
b32 isDown = (curMod & mod) && (curMod & mod2) && (curMod & mod3) && cur.keys.is_set(key);
return wasDown && !isDown;
}
inline b32
Game_Keyboard::released_exactly(Game_Key key, Game_Keymod mod) const
{
b32 wasDown = (prev.mod[key] & mod) == mod && prev.keys.is_set(key);
b32 isDown = (cur.mod[key] & mod) == mod && cur.keys.is_set(key);
return wasDown && !isDown;
}
inline b32
Game_Keyboard::held(Game_Key key) const
{
b32 wasDown = prev.keys.is_set(key);
b32 isDown = cur.keys.is_set(key);
return wasDown && isDown;
}
inline b32
Game_Keyboard::held(Game_Key key, Game_Keymod mod, Game_Keymod mod2, Game_Keymod mod3) const
{
flag8 prevMod = prev.mod[key];
flag8 curMod = cur.mod[key];
b32 wasDown = (prevMod & mod) && (prevMod & mod2) && (prevMod & mod3) && prev.keys.is_set(key);
b32 isDown = (curMod & mod) && (curMod & mod2) && (curMod & mod3) && cur.keys.is_set(key);
return wasDown && isDown;
}
inline b32
Game_Keyboard::held_exactly(Game_Key key, Game_Keymod mod) const
{
b32 wasDown = (prev.mod[key] & mod) == mod && prev.keys.is_set(key);
b32 isDown = (cur.mod[key] & mod) == mod && cur.keys.is_set(key);
return wasDown && isDown;
}
inline b32
Game_Keyboard::down(Game_Key key) const
{
b32 isDown = cur.keys.is_set(key);
return isDown;
}
inline b32
Game_Keyboard::down(Game_Key key, Game_Keymod mod, Game_Keymod mod2, Game_Keymod mod3) const
{
flag8 curMod = cur.mod[key];
b32 isDown = (curMod & mod) && (curMod & mod2) && (curMod & mod3) && cur.keys.is_set(key);
return isDown;
}
inline b32
Game_Keyboard::down_exactly(Game_Key key, Game_Keymod mod) const
{
b32 isDown = (cur.mod[key] & mod) == mod && cur.keys.is_set(key);
return isDown;
}
struct Input_Smoother
{
f32 mouseDragXValues[2] = {};
f32 mouseDragYValues[2] = {};
f32_window mouseDragYWindow;
f32_window mouseDragXWindow;
Input_Smoother();
auto smooth_mouse_drag(f32 x, f32 y) -> v2;
auto reset_mouse_drag() -> void;
};
inline
Input_Smoother::Input_Smoother()
{
mouseDragXWindow.reset(mouseDragXValues, ArraySize(mouseDragXValues), 0);
mouseDragYWindow.reset(mouseDragYValues, ArraySize(mouseDragYValues), 0);
}
inline v2
Input_Smoother::smooth_mouse_drag(f32 x, f32 y)
{
mouseDragXWindow.add(x);
mouseDragYWindow.add(y);
return v2(mouseDragXWindow.average, mouseDragYWindow.average);
}
inline void
Input_Smoother::reset_mouse_drag()
{
mouseDragXWindow.reset(0);
mouseDragYWindow.reset(0);
}
| 2.109375 | 2 |
2024-11-18T22:24:18.665209+00:00 | 2019-02-28T13:05:07 | 238e3196be37d0196163361655a2e1e4bdf55081 | {
"blob_id": "238e3196be37d0196163361655a2e1e4bdf55081",
"branch_name": "refs/heads/master",
"committer_date": "2019-02-28T13:05:07",
"content_id": "9855d7468657bd89b366a29fd63d1406be75cea7",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "f19f73bf73b7503d0caa3f5dffad8f42389699bc",
"extension": "c",
"filename": "hm_parameter.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 173113401,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 19942,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/LPT120-HSF/src/hm_app/src/driver/hm_parameter.c",
"provenance": "stackv2-0115.json.gz:82454",
"repo_name": "yyk23/Gateay-wifi-hf120",
"revision_date": "2019-02-28T13:05:07",
"revision_id": "40715c69782762bd6e6149d4cb6cc81d0419fca3",
"snapshot_id": "578db23f1e851c91d85bb1396146fb3f5612ef88",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/yyk23/Gateay-wifi-hf120/40715c69782762bd6e6149d4cb6cc81d0419fca3/LPT120-HSF/src/hm_app/src/driver/hm_parameter.c",
"visit_date": "2020-04-25T22:30:57.584237"
} | stackv2 |
#include "hsf.h"
#include "hm_parameter.h"
#include <hm_system.h>
#include <RCLutils.h>
#include "hm_user_config.h"
#include "c_types.h"
SpiFlashOpResult hm_flash_erase_sector(uint16 sec)
{
hfuflash_erase_page((sec) * 4096U, 8);
return SPI_FLASH_RESULT_OK;
}
SpiFlashOpResult hm_flash_read(uint32 addr, uint32 *data, int len)
{
if (hfuflash_read(addr, (uint8 *)data, len) < 0)
{
return SPI_FLASH_RESULT_ERR;
}
return SPI_FLASH_RESULT_OK;
}
SpiFlashOpResult hm_flash_write(uint32 addr, uint32 *data, int len)
{
if (hfuflash_write(addr, (uint8 *)data, len) < 0)
{
return SPI_FLASH_RESULT_ERR;
}
return SPI_FLASH_RESULT_OK ;
}
int spi_flash_synchronous_with_protect(uint32 src_addr)
{
uint32_t check_i = 0;
uint32 check_sum = 0;
uint32 flash_sum = 0;
char *des_addr = (char *) hfmem_malloc(KEY_VALUE_BUF_LEN_DEFAULT);
if (des_addr == NULL)
{
return -1;
}
hm_flash_read((src_addr + 2) * 4096U, (uint32 *)&flash_sum, 4);
hm_flash_read((src_addr + 0) * 4096U, (uint32 *)des_addr, KEY_VALUE_BUF_LEN_DEFAULT);
for (check_i = 0; check_i < (KEY_VALUE_BUF_LEN_DEFAULT / 4); check_i++)
{
check_sum = (check_sum + des_addr[check_i]);
}
if (check_sum != flash_sum)
{
check_sum = 0;
hm_flash_read((src_addr + 1) * 4096U, (uint32 *)des_addr, KEY_VALUE_BUF_LEN_DEFAULT);
for (check_i = 0; check_i < (KEY_VALUE_BUF_LEN_DEFAULT / 4); check_i++)
{
check_sum = (check_sum + des_addr[check_i]);
}
if (check_sum != flash_sum)
{
u_printf("A&B ERROR!");
hm_flash_read((src_addr + 0) * 4096U, (uint32 *)des_addr, KEY_VALUE_BUF_LEN_DEFAULT);
for (check_i = 0; check_i < (KEY_VALUE_BUF_LEN_DEFAULT / 4); check_i++)
{
check_sum = (check_sum + des_addr[check_i]);
}
hm_flash_erase_sector(src_addr + 1);
hm_flash_write((src_addr + 1) * 4096U, (uint32 *)des_addr, KEY_VALUE_BUF_LEN_DEFAULT);
hm_flash_erase_sector(src_addr + 2);
hm_flash_write((src_addr + 2) * 4096U, (uint32 *)&check_sum, 4);
hfmem_free(des_addr);
return -2;
}
else
{
u_printf("A ERROR!");
hm_flash_read((src_addr + 1) * 4096U, (uint32 *)des_addr, KEY_VALUE_BUF_LEN_DEFAULT);
hm_flash_erase_sector(src_addr + 0);
hm_flash_write((src_addr + 0) * 4096U, (uint32 *)des_addr, KEY_VALUE_BUF_LEN_DEFAULT);
}
}
else
{
check_sum = 0;
hm_flash_read((src_addr + 1) * 4096U, (uint32 *)des_addr, KEY_VALUE_BUF_LEN_DEFAULT);
for (check_i = 0; check_i < (KEY_VALUE_BUF_LEN_DEFAULT / 4); check_i++)
{
check_sum = (check_sum + des_addr[check_i]);
}
if (check_sum != flash_sum)
{
u_printf("B ERROR!");
hm_flash_read((src_addr + 0) * 4096U, (uint32 *)des_addr, KEY_VALUE_BUF_LEN_DEFAULT);
hm_flash_erase_sector(src_addr + 1);
hm_flash_write((src_addr + 1) * 4096U, (uint32 *)des_addr, KEY_VALUE_BUF_LEN_DEFAULT);
}
else
{
u_printf("flash done!");
}
}
hfmem_free(des_addr);
return 0;
}
static void hm_flash_read_with_protect(uint32 src_addr, char *des_addr, uint32 size)
{
hm_flash_read((src_addr + 0) * 4096U, (uint32 *)des_addr, size);
}
static void hm_flash_write_with_protect(uint32 des_addr, char *src_addr, uint32 size)
{
uint32 check_i = 0;
uint32 check_sum = 0;
for (check_i = 0; check_i < (size / 4); check_i++)
{
check_sum = (check_sum + src_addr[check_i]);
}
hm_flash_erase_sector(des_addr + 0);
hm_flash_write((des_addr + 0) * 4096U, (uint32 *)src_addr, size);
hm_flash_erase_sector(des_addr + 1);
hm_flash_write((des_addr + 1) * 4096U, (uint32 *)src_addr, size);
hm_flash_erase_sector(des_addr + 2);
hm_flash_write((des_addr + 2) * 4096U, (uint32 *)&check_sum, 4);
}
static ra_bool is_forbidden(const char *key)
{
ra_uint8_t i = 0;
char keys_array[][10] = {"ctrlKey", "bindKey"};
for (i = 0; i < sizeof(keys_array) / sizeof(keys_array[0]); i++)
{
if ((strncmp(keys_array[i], key, strlen(key)) == 0) && (strlen(keys_array[i]) == strlen(key)))
{
u_printf("[%s] is forbidden\n", key);
return ra_true;
}
}
return ra_false;
}
static void key_value_destory(key_value_t *p)
{
if (p != NULL)
{
if (p->key.str != NULL)
{
hfmem_free(p->key.str);
}
switch (p->value_type)
{
case VALUE_TYPE_INT:
break;
case VALUE_TYPE_STR:
if (p->u.value_str.str != NULL)
{
hfmem_free(p->u.value_str.str);
}
break;
default:
u_printf("unknow type");
return;
}
hfmem_free(p);
}
}
/*
���б���ƥ���ֵ��
*/
static ra_bool key_search(char *file_str, ra_size_t file_len, key_value_t *key_value, ra_uint32_t *p_key_pos)
{
ra_uint32_t i;
for (i = BUF_LEN_LEN; i < file_len; i++)
{
/*�Ӽ�ֵ���б����ҵ���ֵ�Ա�ʾ��'#'*/
if (file_str[i] == KEY_VALUE_SIGN)
{
*p_key_pos = i;
i += KEY_VALUE_SIGN_LEN;
if ((strncmp(key_value->key.str, &file_str[i], key_value->key.len) == 0) && (file_str[i + key_value->key.len] == SPACE_MARK))
{
return ra_true;
}
i += 6; //6Ϊkey_value��̸�ʽ������
}
}
return ra_false;
}
static ra_bool get_value_from_key(const char *file_str, ra_size_t file_len, key_value_t *key_value, ra_uint32_t key_offset)
{
ra_uint32_t value_type_offset = key_offset + KEY_VALUE_SIGN_LEN + key_value->key.len + SPACE_MARK_LEN;
ra_uint32_t value_offset = value_type_offset + VALUE_TYPE_MARK_LEN + SPACE_MARK_LEN;
if (file_str[value_type_offset] != key_value->value_type)
{
return ra_false;
}
if (key_value->value_type == VALUE_TYPE_INT)
{
memcpy(&(key_value->u.value_int), &file_str[value_offset], sizeof(int));
}
else
{
key_value->u.value_str.len = strlen(&file_str[value_offset]);
key_value->u.value_str.str = (char *)hfmem_malloc(key_value->u.value_str.len + 1);
memcpy(key_value->u.value_str.str, &file_str[value_offset], key_value->u.value_str.len);
key_value->u.value_str.str[key_value->u.value_str.len] = '\0';
}
return ra_true;
}
static key_value_t *key_value_new(char *file_str, ra_size_t file_len, value_type_t type, const char *key, ra_uint8_t key_size)
{
key_value_t *key_value = (key_value_t *) hfmem_malloc(sizeof(key_value_t));
ASSERT(key_value == NULL);
key_value->key.str = (char *)hfmem_malloc(key_size + 1);
ASSERT(key_value->key.str == NULL);
memcpy(key_value->key.str, key, key_size);
key_value->key.str[key_size] = '\0';
key_value->key.len = key_size;
key_value->value_type = type;
ra_uint32_t key_pos_offset = 0;
bool key_exist_flag = key_search(file_str, file_len, key_value, &key_pos_offset);
if (key_exist_flag == ra_false)
{
//u_printf("%s isn't exist\n", key_value->key);
goto fail;
}
bool ret = get_value_from_key(file_str, file_len, key_value, key_pos_offset);
ASSERT(ret == ra_false);
goto done;
done:
return key_value;
fail:
key_value_destory(key_value);
return NULL;
}
static key_value_t *get_key_value(value_type_t type, const char *key, uint16 start_section)
{
if (key == NULL)
{
return NULL;
}
//system_soft_wdt_feed();
ra_uint8_t param_size = (ra_uint8_t)strlen(key);
ra_size_t file_len = 0;
char *file_stream = (char *)hfmem_malloc(KEY_VALUE_BUF_LEN_DEFAULT);
ASSERT(file_stream == NULL);
hm_flash_read_with_protect(start_section, file_stream, KEY_VALUE_BUF_LEN_DEFAULT);
memcpy((void *)&file_len, file_stream, sizeof(ra_size_t));
if (file_len > KEY_VALUE_BUF_LEN_DEFAULT || file_len < BUF_LEN_LEN)
{
file_len = BUF_LEN_LEN;
goto fail;
}
key_value_t *new = key_value_new(file_stream, file_len, type, key, param_size);
if (new == NULL)
{
goto fail;
}
goto done;
done:
__FREE(file_stream);
return new;
fail:
__FREE(file_stream);
return NULL;
}
/*
KEY-VALUE:
format: #KEY TYPE VALUE #KEY TYPE VALUE
*/
static ra_bool replace_key_value(char *file_str, ra_size_t *file_len, key_value_t *key_value, ra_uint32_t key_offset)
{
ra_size_t total_len = 0;
ra_uint32_t value_type_offset = key_offset + KEY_VALUE_SIGN_LEN + key_value->key.len + SPACE_MARK_LEN;
ra_uint32_t value_offset = value_type_offset + VALUE_TYPE_MARK_LEN + SPACE_MARK_LEN;
if (key_value->value_type != file_str[value_type_offset])
{
return ra_false;
}
if (key_value->value_type == VALUE_TYPE_INT)
{
memset(&file_str[value_type_offset], VALUE_TYPE_INT, VALUE_TYPE_MARK_LEN);
memcpy(&file_str[value_offset], &(key_value->u.value_int), sizeof(ra_int32_t));
return ra_true;
}
else
{
/*�齨Key-Value*/
ra_size_t key_value_buffer_len = KEY_VALUE_SIGN_LEN + key_value->key.len + 3 * SPACE_MARK_LEN + VALUE_TYPE_MARK_LEN + key_value->u.value_str.len + 1 + 1;
char *key_value_buffer = (char *)hfmem_malloc(key_value_buffer_len);
ASSERT(key_value_buffer == NULL);
/*��ʼ��*/
ra_size_t sprintf_size = sprintf(key_value_buffer, "#%s c %sc ", key_value->key.str, key_value->u.value_str.str);
ASSERT(sprintf_size >= key_value_buffer_len);
ra_uint32_t format_value_type_offset = KEY_VALUE_SIGN_LEN + key_value->key.len + SPACE_MARK_LEN;
ra_uint32_t format_str_end_offset = format_value_type_offset + VALUE_TYPE_MARK_LEN + SPACE_MARK_LEN + key_value->u.value_str.len;
memset(&key_value_buffer[format_value_type_offset], VALUE_TYPE_STR, VALUE_TYPE_MARK_LEN);
memset(&key_value_buffer[format_str_end_offset], 0, 1);
char *next_key_pos = NULL;
if ((next_key_pos = lib_memchr(&file_str[value_offset], KEY_VALUE_SIGN, (*file_len) - value_offset)) == NULL) //����"#"
{
total_len = key_offset + sprintf_size;
ASSERT(total_len > KEY_VALUE_BUF_LEN_DEFAULT);
memcpy(&file_str[key_offset], key_value_buffer, sprintf_size);
__FREE(key_value_buffer);
(*file_len) = key_offset + sprintf_size;
return ra_true;
}
else //����"#"
{
ra_size_t backup_len = (*file_len) - (next_key_pos - file_str);
total_len = key_offset + sprintf_size + backup_len;
ASSERT(total_len > KEY_VALUE_BUF_LEN_DEFAULT);
char *str_tmp = (char *)hfmem_malloc(backup_len);
ASSERT(str_tmp == NULL);
memcpy(str_tmp, next_key_pos, backup_len);
memcpy(&file_str[key_offset], key_value_buffer, sprintf_size);
memcpy(&file_str[key_offset + sprintf_size], str_tmp, backup_len);
__FREE(str_tmp);
__FREE(key_value_buffer);
(*file_len) = key_offset + sprintf_size + backup_len;
return ra_true;
}
fail:
__FREE(key_value_buffer);
return ra_false;
}
}
/*
KEY-VALUE:
format: #KEY TYPE VALUE #KEY TYPE VALUE
*/
static ra_bool add_key_value(char *file_str, ra_size_t *file_len, key_value_t *key_value)
{
/*�齨Key-Value*/
ra_size_t total_len = *file_len;
ra_size_t key_value_buffer_len = 0;
if (key_value->value_type == VALUE_TYPE_INT)
key_value_buffer_len = KEY_VALUE_SIGN_LEN + key_value->key.len + 3 * SPACE_MARK_LEN + VALUE_TYPE_MARK_LEN + sizeof(int) + 1;
else
key_value_buffer_len = KEY_VALUE_SIGN_LEN + key_value->key.len + 3 * SPACE_MARK_LEN + VALUE_TYPE_MARK_LEN + key_value->u.value_str.len + 1 + 1;
char *key_value_buffer = hfmem_malloc(key_value_buffer_len);
ASSERT(key_value_buffer == NULL);
ra_size_t sprintf_size;
if (key_value->value_type == VALUE_TYPE_INT)
{
sprintf_size = sprintf(key_value_buffer, "#%s c 0000 ", key_value->key.str);
ASSERT(sprintf_size >= key_value_buffer_len);
ra_uint32_t format_value_type_offset = KEY_VALUE_SIGN_LEN + key_value->key.len + SPACE_MARK_LEN;
ra_uint32_t format_value_offset = format_value_type_offset + VALUE_TYPE_MARK_LEN + SPACE_MARK_LEN;
memset(&key_value_buffer[format_value_type_offset], VALUE_TYPE_INT, VALUE_TYPE_MARK_LEN);
memcpy(&key_value_buffer[format_value_offset], &(key_value->u.value_int), sizeof(int));
}
else
{
sprintf_size = sprintf(key_value_buffer, "#%s c %sc ", key_value->key.str, key_value->u.value_str.str);
ASSERT(sprintf_size >= key_value_buffer_len);
ra_uint32_t format_value_type_offset = KEY_VALUE_SIGN_LEN + key_value->key.len + SPACE_MARK_LEN;
ra_uint32_t format_str_end_offset = format_value_type_offset + VALUE_TYPE_MARK_LEN + SPACE_MARK_LEN + key_value->u.value_str.len;
memset(&key_value_buffer[format_value_type_offset], VALUE_TYPE_STR, VALUE_TYPE_MARK_LEN);
memset(&key_value_buffer[format_str_end_offset], 0, 1);
}
total_len += sprintf_size;
ASSERT(total_len > KEY_VALUE_BUF_LEN_DEFAULT);
memcpy(&file_str[*file_len], key_value_buffer, sprintf_size); //������strncat
goto done;
done:
__FREE(key_value_buffer);
(*file_len) = (*file_len) + sprintf_size;
return ra_true;
fail:
__FREE(key_value_buffer);
return ra_false;
}
static key_value_t *setup_key_value(const char *key, void *v, value_type_t type)
{
key_value_t *key_value = (key_value_t *) hfmem_malloc(sizeof(key_value_t));
ASSERT(key_value == NULL);
/*setup key*/
key_value->key.len = strlen(key);
key_value->key.str = (char *)hfmem_malloc(key_value->key.len + 1);
ASSERT(key_value->key.str == NULL);
memcpy(key_value->key.str, key, key_value->key.len);
key_value->key.str[key_value->key.len] = '\0';
/*setup value*/
if (type == VALUE_TYPE_INT)
{
key_value->value_type = VALUE_TYPE_INT;
key_value->u.value_int = *((int *)v);
//u_printf("key_value->u.value_int = %d\n", key_value->u.value_int);
}
else
{
key_value->value_type = VALUE_TYPE_STR;
key_value->u.value_str.len = strlen((char *)v);
key_value->u.value_str.str = (char *)hfmem_malloc(key_value->u.value_str.len + 1);
ASSERT(key_value->u.value_str.str == NULL);
memcpy(key_value->u.value_str.str, v, key_value->u.value_str.len);
key_value->u.value_str.str[key_value->u.value_str.len] = '\0';
}
goto done;
done:
return key_value;
fail:
key_value_destory(key_value);
return NULL;
}
static int delete_parameter(const char *key, uint16 start_section)
{
ra_uint32_t key_pos_offset = 0;
// ra_bool flag = ra_false;
ra_size_t file_len = 0;
if (key == NULL)
return RA_ERROR_INVALID_ARGUMENTS;
//key length limit
if unlikely(strlen(key) > KEY_LENGTH_MAX)
{
return RA_ERROR_INVALID_ARGUMENTS;
}
char *file_stream = (char *) hfmem_malloc(KEY_VALUE_BUF_LEN_DEFAULT);
if (file_stream == NULL)
{
return RA_ERROR_OUT_OF_MEMORY;
}
hm_flash_read_with_protect(start_section, file_stream, KEY_VALUE_BUF_LEN_DEFAULT);
memcpy((void *)&file_len, file_stream, sizeof(ra_size_t));
if (file_len > KEY_VALUE_BUF_LEN_DEFAULT || file_len < BUF_LEN_LEN)
{
file_len = BUF_LEN_LEN;
return RA_ERROR_INVALID_ARGUMENTS;
}
key_value_t *key_value = setup_key_value(key, " ", VALUE_TYPE_STR);
if (key_value == NULL)
{
return RA_ERROR_OUT_OF_MEMORY;
}
ra_bool key_exist_flag = key_search(file_stream, file_len, key_value, &key_pos_offset);
if (key_exist_flag == ra_false)
{
key_value_destory(key_value);
return RA_ERROR_INVALID_ARGUMENTS;
}
ra_uint32_t value_type_offset = key_pos_offset + KEY_VALUE_SIGN_LEN + key_value->key.len + SPACE_MARK_LEN;
ra_uint32_t value_offset = value_type_offset + VALUE_TYPE_MARK_LEN + SPACE_MARK_LEN;
char *next_key_pos = NULL;
if ((next_key_pos = memchr(&file_stream[value_offset], KEY_VALUE_SIGN, file_len - value_offset)) == NULL) //����"#"
{
memset(&file_stream[key_pos_offset], 0, (file_len - key_pos_offset));
file_len = key_pos_offset;
}
else //����"#"
{
ra_size_t backup_len = file_len - (next_key_pos - file_stream);
char *str_tmp = (char *)hfmem_malloc(backup_len);
if (str_tmp == NULL)
{
key_value_destory(key_value);
return RA_ERROR_OUT_OF_MEMORY;
}
memcpy(str_tmp, next_key_pos, backup_len);
memset(&file_stream[key_pos_offset], 0, (file_len - key_pos_offset));
memcpy(&file_stream[key_pos_offset], str_tmp, backup_len);
__FREE(str_tmp);
file_len = key_pos_offset + backup_len;
}
/*store parameters*/
memcpy(file_stream, (void *)&file_len, sizeof(ra_size_t));
hm_flash_write_with_protect(start_section, file_stream, KEY_VALUE_BUF_LEN_DEFAULT);
__FREE(file_stream);
key_value_destory(key_value);
return RA_SUCCESS;
}
int set_parameter(const char *key, void *value, value_type_t type, uint16 start_section)
{
ra_uint32_t key_pos_offset = 0;
ra_bool flag = ra_false;
ra_size_t file_len = 0;
if (key == NULL)
return RA_ERROR_INVALID_ARGUMENTS;
//key length limit
if unlikely(strlen(key) > KEY_LENGTH_MAX)
{
return RA_ERROR_INVALID_ARGUMENTS;
}
//value length limit
if ((type == VALUE_TYPE_STR) && (strlen(value) > VALUE_LENGTH_MAX))
{
return RA_ERROR_INVALID_ARGUMENTS;
}
key_value_t *key_value = setup_key_value(key, value, type);
if (key_value == NULL)
{
return RA_ERROR_OUT_OF_MEMORY;
}
char *file_stream = (char *) hfmem_malloc(KEY_VALUE_BUF_LEN_DEFAULT);
if (file_stream == NULL)
{
key_value_destory(key_value);
return RA_ERROR_OUT_OF_MEMORY;
}
hm_flash_read_with_protect(start_section, file_stream, KEY_VALUE_BUF_LEN_DEFAULT);
memcpy((void *)&file_len, file_stream, sizeof(ra_size_t));
if (file_len > KEY_VALUE_BUF_LEN_DEFAULT || file_len < BUF_LEN_LEN)
{
file_len = BUF_LEN_LEN;
}
ra_bool key_exist_flag = key_search(file_stream, file_len, key_value, &key_pos_offset);
if (key_exist_flag == ra_true)
{
flag = replace_key_value(file_stream, &file_len, key_value, key_pos_offset);
}
else
{
flag = add_key_value(file_stream, &file_len, key_value);
}
if unlikely(flag == ra_false)
{
__FREE(file_stream);
key_value_destory(key_value);
return RA_ERROR_INVALID_ARGUMENTS;
}
/*store parameters*/
memcpy(file_stream, (void *)&file_len, sizeof(ra_size_t));
hm_flash_write_with_protect(start_section, file_stream, KEY_VALUE_BUF_LEN_DEFAULT);
__FREE(file_stream);
key_value_destory(key_value);
return RA_SUCCESS;
}
int ra_set_parameter_integer(const char *key, ra_int32_t value)
{
if (is_forbidden(key) == ra_true)
{
return RA_ERROR_INVALID_ARGUMENTS;
}
return set_parameter(key, (void *)(&value), VALUE_TYPE_INT, ESP_PARAM_START_SEC);
}
int ra_set_parameter_integer_without_limit(const char *key, ra_int32_t value)
{
return set_parameter(key, (void *)(&value), VALUE_TYPE_INT, ESP_PARAM_START_SEC);
}
int ra_get_parameter_integer(const char *key, ra_int32_t *value)
{
key_value_t *key_value = get_key_value(VALUE_TYPE_INT, key, ESP_PARAM_START_SEC);
if (key_value == NULL)
{
return RA_ERROR_INTERNAL;
}
*value = key_value->u.value_int;
key_value_destory(key_value);
return RA_SUCCESS;
}
int ra_set_parameter_string(const char *key, const char *value)
{
if (is_forbidden(key) == ra_true)
{
return RA_ERROR_INVALID_ARGUMENTS;
}
return set_parameter(key, (void *)value, VALUE_TYPE_STR, ESP_PARAM_START_SEC);
}
int ra_set_feedback_parameter_string(const char *key, const char *value)
{
return set_parameter(key, (void *)value, VALUE_TYPE_STR, ESP_FEEDBACKPARAM_START_SEC);
}
int ra_set_parameter_string_without_limit(const char *key, const char *value)
{
return set_parameter(key, (void *)value, VALUE_TYPE_STR, ESP_PARAM_START_SEC);
}
int ra_get_parameter_string(const char *key, char *buf, ra_size_t buf_len)
{
ra_uint32_t str_len = 0;
key_value_t *key_value = get_key_value(VALUE_TYPE_STR, key, ESP_PARAM_START_SEC);
if (key_value == NULL)
{
return RA_ERROR_INTERNAL;
}
if (key_value->u.value_str.len > buf_len)
{
key_value_destory(key_value);
return RA_ERROR_INVALID_ARGUMENTS;
}
memcpy(buf, key_value->u.value_str.str, key_value->u.value_str.len + 1);
str_len = key_value->u.value_str.len;
key_value_destory(key_value);
return str_len;
}
int ra_get_feedback_parameter_string(const char *key, char *buf, ra_size_t buf_len)
{
ra_uint32_t str_len = 0;
key_value_t *key_value = get_key_value(VALUE_TYPE_STR, key, ESP_FEEDBACKPARAM_START_SEC);
if (key_value == NULL)
{
return RA_ERROR_INTERNAL;
}
if (key_value->u.value_str.len > buf_len)
{
key_value_destory(key_value);
return RA_ERROR_INVALID_ARGUMENTS;
}
memcpy(buf, key_value->u.value_str.str, key_value->u.value_str.len + 1);
str_len = key_value->u.value_str.len;
key_value_destory(key_value);
return str_len;
}
int ra_delete_parameter(const char *key)
{
if (is_forbidden(key) == ra_true)
{
return RA_ERROR_INVALID_ARGUMENTS;
}
return delete_parameter(key, ESP_PARAM_START_SEC);
}
int ra_delete_parameter_without_limit(const char *key)
{
return delete_parameter(key, ESP_PARAM_START_SEC);
}
| 2.265625 | 2 |
2024-11-18T22:24:18.984970+00:00 | 2023-08-01T12:51:50 | 4d77dc84779463b09e7cc108818d355a1789d015 | {
"blob_id": "4d77dc84779463b09e7cc108818d355a1789d015",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-01T12:53:50",
"content_id": "6c46740216da6cf1ae38ddd3780ad4450b58b8a0",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "d60dcdd392e32cd6272f7f364e5b4d556d6b84fb",
"extension": "h",
"filename": "dd_dtw.h",
"fork_events_count": 188,
"gha_created_at": "2017-02-02T20:11:03",
"gha_event_created_at": "2023-05-23T14:44:06",
"gha_language": "Python",
"gha_license_id": "NOASSERTION",
"github_id": 80764246,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 10568,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/dtaidistance/lib/DTAIDistanceC/DTAIDistanceC/dd_dtw.h",
"provenance": "stackv2-0115.json.gz:82585",
"repo_name": "wannesm/dtaidistance",
"revision_date": "2023-08-01T12:51:50",
"revision_id": "d914ab85021f67ff1c58d45727e0e4844ad26d8e",
"snapshot_id": "7e39ba5086129f330a297d82af1b25854c016f74",
"src_encoding": "UTF-8",
"star_events_count": 943,
"url": "https://raw.githubusercontent.com/wannesm/dtaidistance/d914ab85021f67ff1c58d45727e0e4844ad26d8e/dtaidistance/lib/DTAIDistanceC/DTAIDistanceC/dd_dtw.h",
"visit_date": "2023-08-31T06:21:45.836316"
} | stackv2 | /*!
@header dtw.h
@brief DTAIDistance.dtw : Dynamic Time Warping
@author Wannes Meert
@copyright Copyright © 2020 Wannes Meert. Apache License, Version 2.0, see LICENSE for details.
*/
#ifndef dtw_h
#define dtw_h
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <signal.h>
#include <stdbool.h>
#include <stddef.h>
#include <assert.h>
#include <stdint.h>
#include <time.h>
#include "dd_globals.h"
#include "dd_ed.h"
/**
@var keepRunning
@abstract Indicator to track if an interrupt occured requiring the algorithm to exit.
*/
static volatile int keepRunning = 1;
/**
@var printPrecision
@abstract Number of decimals to print when printing (partial) distances.
*/
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-variable"
static int printPrecision = 3;
static int printDigits = 7; // 3+4
static char printBuffer[20];
static char printFormat[5];
#pragma GCC diagnostic pop
// Inner distance options
//const int kSquaredEuclideanInnerDist = 0;
//const int kEuclideanInnerDist = 1;
// Band type
//const int kSakoeChibaBand = 0;
//const int kSlantedBand = 1;
/**
Settings for DTW operations:
@field window : Window size; expressed as distance to a single side including the diagonal, thus
the total window size will be window*2 - 1 and Euclidean distance is window=1.
@field max_dist : Maximal distance, avoid computing cells that have a larger value.
Return INFINITY if no path is found with a distance lower or equal to max_dist.
@field max_step : Maximal stepsize, replace value with INFINITY if step is
larger than max_step.
@field max_length_diff : Maximal difference in length between two series.
If longer, return INFINITY.
@field penalty : Customize the cost for expansion or compression.
@field psi: Psi relaxation allows to ignore this number of entries at the beginning
and/or end of both sequences.
@field use_pruning : Compute Euclidean distance first to set max_dist (current value in
max_dist is ignored).
@field only_ub : Only compute the upper bound (Euclidean) and return that value.
*/
struct DTWSettings_s {
idx_t window;
seq_t max_dist;
seq_t max_step;
idx_t max_length_diff;
seq_t penalty;
idx_t psi_1b; // series 1, begin psi
idx_t psi_1e; // series 1, end psi
idx_t psi_2b; // series 2, begin psi
idx_t psi_2e; // series 2, end psi
bool use_pruning;
bool only_ub;
int inner_dist; // 0=squared euclidean, 1=euclidean
int window_type; // 0=band around two diagonals, 1=band around slanted diagonal
};
typedef struct DTWSettings_s DTWSettings;
/**
Block to restrict comparisons between series.
@field rb Row begin
@field re Row end
@field cb Column begin
@field ce Column end
*/
struct DTWBlock_s {
idx_t rb;
idx_t re;
idx_t cb;
idx_t ce;
bool triu;
};
typedef struct DTWBlock_s DTWBlock;
struct DTWWps_s {
idx_t ldiff;
idx_t ldiffr;
idx_t ldiffc;
idx_t window;
idx_t width; // Width of warping paths matrix (height is length of series 1 + 1)
idx_t length; // Nb of elements in the warping paths datastructure
idx_t ri1;
idx_t ri2;
idx_t ri3;
idx_t overlap_left_ri;
idx_t overlap_right_ri;
seq_t max_step;
seq_t max_dist;
seq_t penalty;
};
typedef struct DTWWps_s DTWWps;
// Settings
DTWSettings dtw_settings_default(void);
idx_t dtw_settings_wps_length(idx_t l1, idx_t l2, DTWSettings *settings);
idx_t dtw_settings_wps_width(idx_t l1, idx_t l2, DTWSettings *settings);
void dtw_settings_set_psi(idx_t psi, DTWSettings *settings);
void dtw_settings_print(DTWSettings *settings);
// DTW
typedef seq_t (*DTWFnPtr)(seq_t *s1, idx_t l1, seq_t *s2, idx_t l2, DTWSettings *settings);
seq_t dtw_distance(seq_t *s1, idx_t l1, seq_t *s2, idx_t l2, DTWSettings *settings);
seq_t dtw_distance_ndim(seq_t *s1, idx_t l1, seq_t *s2, idx_t l2, int ndim, DTWSettings *settings);
seq_t dtw_distance_euclidean(seq_t *s1, idx_t l1, seq_t *s2, idx_t l2, DTWSettings *settings);
seq_t dtw_distance_ndim_euclidean(seq_t *s1, idx_t l1, seq_t *s2, idx_t l2, int ndim, DTWSettings *settings);
// WPS
seq_t dtw_warping_paths(seq_t *wps, seq_t *s1, idx_t l1, seq_t *s2, idx_t l2, bool return_dtw, bool do_sqrt, bool psi_neg, DTWSettings *settings);
seq_t dtw_warping_paths_ndim(seq_t *wps, seq_t *s1, idx_t l1, seq_t *s2, idx_t l2, bool return_dtw, bool do_sqrt, bool psi_neg, int ndim, DTWSettings *settings);
seq_t dtw_warping_paths_euclidean(seq_t *wps, seq_t *s1, idx_t l1, seq_t *s2, idx_t l2, bool return_dtw, bool do_sqrt, bool psi_neg, DTWSettings *settings);
seq_t dtw_warping_paths_ndim_euclidean(seq_t *wps, seq_t *s1, idx_t l1, seq_t *s2, idx_t l2, bool return_dtw, bool do_sqrt, bool psi_neg, int ndim, DTWSettings *settings);
seq_t dtw_warping_paths_affinity(seq_t *wps, seq_t *s1, idx_t l1, seq_t *s2, idx_t l2, bool return_dtw, bool do_sqrt, bool psi_neg, bool only_triu, seq_t gamma, seq_t tau, seq_t delta, seq_t delta_factor, DTWSettings *settings);
seq_t dtw_warping_paths_affinity_ndim(seq_t *wps, seq_t *s1, idx_t l1, seq_t *s2, idx_t l2, bool return_dtw, bool do_sqrt, bool psi_neg, bool only_triu, int ndim, seq_t gamma, seq_t tau, seq_t delta, seq_t delta_factor, DTWSettings *settings);
seq_t dtw_warping_paths_affinity_ndim_euclidean(seq_t *wps, seq_t *s1, idx_t l1, seq_t *s2, idx_t l2,
bool return_dtw, bool do_sqrt, bool psi_neg, bool only_triu, int ndim,
seq_t gamma, seq_t tau, seq_t delta, seq_t delta_factor, DTWSettings *settings);
void dtw_expand_wps(seq_t *wps, seq_t *full, idx_t l1, idx_t l2, DTWSettings *settings);
void dtw_expand_wps_slice(seq_t *wps, seq_t *full, idx_t l1, idx_t l2, idx_t rb, idx_t re, idx_t cb, idx_t ce, DTWSettings *settings);
void dtw_expand_wps_affinity(seq_t *wps, seq_t *full, idx_t l1, idx_t l2, DTWSettings *settings);
void dtw_expand_wps_slice_affinity(seq_t *wps, seq_t *full, idx_t l1, idx_t l2, idx_t rb, idx_t re, idx_t cb, idx_t ce, DTWSettings *settings);
void dtw_wps_negativize_value(DTWWps* p, seq_t *wps, idx_t l1, idx_t l2, idx_t r, idx_t c);
void dtw_wps_positivize_value(DTWWps* p, seq_t *wps, idx_t l1, idx_t l2, idx_t r, idx_t c);
void dtw_wps_positivize(DTWWps* p, seq_t *wps, idx_t l1, idx_t l2, idx_t rb, idx_t re, idx_t cb, idx_t ce);
void dtw_wps_negativize(DTWWps* p, seq_t *wps, idx_t l1, idx_t l2, idx_t rb, idx_t re, idx_t cb, idx_t ce);
idx_t dtw_wps_loc(DTWWps* p, idx_t r, idx_t c, idx_t l1, idx_t l2);
idx_t dtw_wps_loc_columns(DTWWps* p, idx_t r, idx_t *cb, idx_t *ce, idx_t l1, idx_t l2);
idx_t dtw_wps_max(DTWWps* p, seq_t *wps, idx_t *r, idx_t *c, idx_t l1, idx_t l2);
idx_t dtw_best_path(seq_t *wps, idx_t *i1, idx_t *i2, idx_t l1, idx_t l2, DTWSettings *settings);
idx_t dtw_best_path_isclose(seq_t *wps, idx_t *i1, idx_t *i2, idx_t l1, idx_t l2, seq_t rtol, seq_t atol, DTWSettings *settings);
idx_t dtw_best_path_affinity(seq_t *wps, idx_t *i1, idx_t *i2, idx_t l1, idx_t l2, idx_t s1, idx_t s2, DTWSettings *settings);
idx_t dtw_best_path_prob(seq_t *wps, idx_t *i1, idx_t *i2, idx_t l1, idx_t l2, seq_t avg, DTWSettings *settings);
seq_t dtw_warping_path(seq_t *from_s, idx_t from_l, seq_t* to_s, idx_t to_l, idx_t *from_i, idx_t *to_i, idx_t * length_i, DTWSettings * settings);
seq_t dtw_warping_path_ndim(seq_t *from_s, idx_t from_l, seq_t* to_s, idx_t to_l, idx_t *from_i, idx_t *to_i, idx_t * length_i, int ndim, DTWSettings * settings);
void dtw_srand(unsigned int seed);
seq_t dtw_warping_path_prob_ndim(seq_t *from_s, idx_t from_l, seq_t* to_s, idx_t to_l, idx_t *from_i, idx_t *to_i, idx_t *length_i, seq_t avg, int ndim, DTWSettings * settings);
DTWWps dtw_wps_parts(idx_t l1, idx_t l2, DTWSettings * settings);
// Bound
seq_t ub_euclidean(seq_t *s1, idx_t l1, seq_t *s2, idx_t l2);
seq_t ub_euclidean_ndim(seq_t *s1, idx_t l1, seq_t *s2, idx_t l2, int ndim);
seq_t ub_euclidean_euclidean(seq_t *s1, idx_t l1, seq_t *s2, idx_t l2);
seq_t ub_euclidean_ndim_euclidean(seq_t *s1, idx_t l1, seq_t *s2, idx_t l2, int ndim);
seq_t lb_keogh(seq_t *s1, idx_t l1, seq_t *s2, idx_t l2, DTWSettings *settings);
seq_t lb_keogh_euclidean(seq_t *s1, idx_t l1, seq_t *s2, idx_t l2, DTWSettings *settings);
// Block
DTWBlock dtw_block_empty(void);
void dtw_block_print(DTWBlock *block);
bool dtw_block_is_valid(DTWBlock *block, idx_t nb_series_r, idx_t nb_series_c);
// Distance matrix
idx_t dtw_distances_ptrs(seq_t **ptrs, idx_t nb_ptrs, idx_t* lengths, seq_t* output,
DTWBlock* block, DTWSettings* settings);
idx_t dtw_distances_ndim_ptrs(seq_t **ptrs, idx_t nb_ptrs, idx_t* lengths, int ndim, seq_t* output,
DTWBlock* block, DTWSettings* settings);
idx_t dtw_distances_matrix(seq_t *matrix, idx_t nb_rows, idx_t nb_cols, seq_t* output,
DTWBlock* block, DTWSettings* settings);
idx_t dtw_distances_ndim_matrix(seq_t *matrix, idx_t nb_rows, idx_t nb_cols, int ndim, seq_t* output,
DTWBlock* block, DTWSettings* settings);
idx_t dtw_distances_matrices(seq_t *matrix_r, idx_t nb_rows_r, idx_t nb_cols_r,
seq_t *matrix_c, idx_t nb_rows_c, idx_t nb_cols_c,
seq_t* output, DTWBlock* block, DTWSettings* settings);
idx_t dtw_distances_ndim_matrices(seq_t *matrix_r, idx_t nb_rows_r, idx_t nb_cols_r,
seq_t *matrix_c, idx_t nb_rows_c, idx_t nb_cols_c, int ndim,
seq_t* output, DTWBlock* block, DTWSettings* settings);
idx_t dtw_distances_length(DTWBlock *block, idx_t nb_series_r, idx_t nb_series_c);
// DBA
void dtw_dba_ptrs(seq_t **ptrs, idx_t nb_ptrs, idx_t* lengths,
seq_t *c, idx_t t, ba_t *mask, int prob_samples, int ndim,
DTWSettings *settings);
void dtw_dba_matrix(seq_t *matrix, idx_t nb_rows, idx_t nb_cols,
seq_t *c, idx_t t, ba_t *mask, int prob_samples, int ndim,
DTWSettings *settings);
// Auxiliary functions
void dtw_int_handler(int dummy);
void dtw_printprecision_set(int precision);
void dtw_printprecision_reset(void);
void dtw_print_wps_compact(seq_t * wps, idx_t l1, idx_t l2, DTWSettings* settings);
void dtw_print_wps(seq_t * wps, idx_t l1, idx_t l2, DTWSettings* settings);
void dtw_print_twoline(seq_t * dtw, idx_t r, idx_t c, idx_t length, int i0, int i1, idx_t skip, idx_t skipp, idx_t maxj, idx_t minj);
void dtw_print_nb(seq_t value);
void dtw_print_ch(char* string);
#endif /* dtw_h */
| 2.359375 | 2 |
2024-11-18T22:24:19.275398+00:00 | 2021-06-07T23:29:12 | 95be494db04376832c3f64a0be89ad24cb1d097d | {
"blob_id": "95be494db04376832c3f64a0be89ad24cb1d097d",
"branch_name": "refs/heads/main",
"committer_date": "2021-06-07T23:29:12",
"content_id": "cd9dee718d1e7e26b3547bb83cabf06bab0443c9",
"detected_licenses": [
"BSD-3-Clause",
"BSD-2-Clause"
],
"directory_id": "1123809f9f935175efe539ca082343b44f3dac7b",
"extension": "c",
"filename": "t208-elemrestriction.c",
"fork_events_count": 0,
"gha_created_at": "2021-04-20T13:57:10",
"gha_event_created_at": "2021-04-20T13:57:11",
"gha_language": null,
"gha_license_id": "BSD-2-Clause",
"github_id": 359834941,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1923,
"license": "BSD-3-Clause,BSD-2-Clause",
"license_type": "permissive",
"path": "/tests/t208-elemrestriction.c",
"provenance": "stackv2-0115.json.gz:82974",
"repo_name": "DiffeoInvariant/libCEED",
"revision_date": "2021-06-07T23:29:12",
"revision_id": "fef6d6185073a4ded914e81d25fd2b60cc92d311",
"snapshot_id": "032200eb94d573a4e1245b6b54d92732085c52ec",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/DiffeoInvariant/libCEED/fef6d6185073a4ded914e81d25fd2b60cc92d311/tests/t208-elemrestriction.c",
"visit_date": "2021-07-22T17:13:05.753922"
} | stackv2 | /// @file
/// Test creation, use, and destruction of a blocked element restriction
/// \test Test creation, use, and destruction of a blocked element restriction
#include <ceed.h>
int main(int argc, char **argv) {
Ceed ceed;
CeedVector x, y;
CeedInt num_elem = 8;
CeedInt blk_size = 5;
CeedInt elem_size = 2;
CeedInt ind[elem_size*num_elem];
CeedScalar a[num_elem+1];
CeedElemRestriction r;
CeedScalar *y_array;
CeedInit(argv[1], &ceed);
CeedVectorCreate(ceed, num_elem+1, &x);
for (CeedInt i=0; i<num_elem+1; i++)
a[i] = 10 + i;
CeedVectorSetArray(x, CEED_MEM_HOST, CEED_USE_POINTER, a);
for (CeedInt i=0; i<num_elem; i++) {
for (CeedInt k=0; k<elem_size; k++) {
ind[elem_size*i+k] = i+k;
}
}
CeedElemRestrictionCreateBlocked(ceed, num_elem, elem_size, blk_size, 1, 1,
num_elem+1,
CEED_MEM_HOST, CEED_USE_POINTER, ind, &r);
CeedVectorCreate(ceed, blk_size*elem_size, &y);
CeedVectorSetValue(y, 0); // Allocates array
// NoTranspose
CeedElemRestrictionApplyBlock(r, 1, CEED_NOTRANSPOSE, x, y,
CEED_REQUEST_IMMEDIATE);
// Zero padded entries
CeedVectorGetArray(y, CEED_MEM_HOST, &y_array);
for (CeedInt i = (elem_size*num_elem - blk_size*elem_size);
i < blk_size*elem_size;
++i) {
y_array[i] = 0;
}
CeedVectorRestoreArray(y, &y_array);
CeedVectorView(y, "%12.8f", stdout);
// Transpose
CeedVectorGetArray(x, CEED_MEM_HOST, (CeedScalar **)&a);
for (CeedInt i=0; i<num_elem+1; i++)
a[i] = 0;
CeedVectorRestoreArray(x, (CeedScalar **)&a);
CeedElemRestrictionApplyBlock(r, 1, CEED_TRANSPOSE, y, x,
CEED_REQUEST_IMMEDIATE);
CeedVectorView(x, "%12.8f", stdout);
CeedVectorDestroy(&x);
CeedVectorDestroy(&y);
CeedElemRestrictionDestroy(&r);
CeedDestroy(&ceed);
return 0;
}
| 2.34375 | 2 |
2024-11-18T22:24:19.596886+00:00 | 2021-08-02T08:13:19 | 35e63ef85eb1b6912b9b94d57cde1598cecc17d3 | {
"blob_id": "35e63ef85eb1b6912b9b94d57cde1598cecc17d3",
"branch_name": "refs/heads/master",
"committer_date": "2021-08-02T08:13:19",
"content_id": "f5e509629536e7d8ad669939755f8fa8d68c879c",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "fd81afd43333803faafef56258ea3682bfebf6ae",
"extension": "c",
"filename": "test_version.c",
"fork_events_count": 0,
"gha_created_at": "2021-08-02T06:38:56",
"gha_event_created_at": "2021-08-02T08:16:18",
"gha_language": "C",
"gha_license_id": "NOASSERTION",
"github_id": 391840688,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 688,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/tests/test_version.c",
"provenance": "stackv2-0115.json.gz:83231",
"repo_name": "xuezhilei40308/libddssec",
"revision_date": "2021-08-02T08:13:19",
"revision_id": "fcab496edc560e63024a20a6dbce181521cd718a",
"snapshot_id": "f112028668c3de942d36b61d31770695fc1cd133",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/xuezhilei40308/libddssec/fcab496edc560e63024a20a6dbce181521cd718a/tests/test_version.c",
"visit_date": "2023-06-25T08:33:29.635491"
} | stackv2 | /*
* DDS Security library
* Copyright (c) 2018-2020, Arm Limited and Contributors. All rights reserved.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#include <dsec_test.h>
#include <dsec_version.h>
#include <stddef.h>
static void test_case_version_pointer(void)
{
const char *version;
version = dsec_version();
DSEC_TEST_ASSERT(version != NULL);
}
static const struct dsec_test_case_desc test_case_table[] = {
DSEC_TEST_CASE(test_case_version_pointer),
};
const struct dsec_test_suite_desc test_suite = {
.name = "Version",
.test_case_count = sizeof(test_case_table)/sizeof(test_case_table[0]),
.test_case_table = test_case_table,
};
| 2.21875 | 2 |
2024-11-18T22:24:19.658123+00:00 | 2016-09-06T09:09:19 | bb154e9b2b672edba323f0839486178ebe795b81 | {
"blob_id": "bb154e9b2b672edba323f0839486178ebe795b81",
"branch_name": "refs/heads/master",
"committer_date": "2016-09-06T09:09:19",
"content_id": "8f19cc04483034b0b1e02cb6a0f4bea4092db2c9",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "854a2ab8f607265759b7d9cb0211dc451be6e469",
"extension": "c",
"filename": "ex0505.c",
"fork_events_count": 4,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 35331050,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1644,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/c-work/exercises/kr/chap05/ex0505.c",
"provenance": "stackv2-0115.json.gz:83363",
"repo_name": "alexhilton/miscellaneous",
"revision_date": "2016-09-06T09:09:19",
"revision_id": "4c45b3d055396e09a9c83a58020c9b5fd6a97f23",
"snapshot_id": "3e653554c103a7c9d336dacdbc140a95b39f8e26",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/alexhilton/miscellaneous/4c45b3d055396e09a9c83a58020c9b5fd6a97f23/c-work/exercises/kr/chap05/ex0505.c",
"visit_date": "2020-05-20T17:01:42.118355"
} | stackv2 | /**
* ex0505.c
* implement strncpy, strncmp and strncat.
*/
#include <stdio.h>
static int strncpy( char *dst, char *src, int n );
static int strncmp( char *str1, char *str2, int n );
static int strncat( char *dst, char *src, int n );
int main( int argc, char *argv[] ) {
char str1[ 128 ];
char str2[ 128 ];
int n;
printf( "input a string:" );
scanf( "%s", str1 );
printf( "input another string:" );
scanf( "%s", str2 );
printf( "input the number of chars you wanna operate:" );
scanf( "%d", &n );
strncpy( str1, str2, n );
printf( "strncpy, is: '%s'\n", str1 );
printf( "input a string:" );
scanf( "%s", str1 );
printf( "input another string:" );
scanf( "%s", str2 );
printf( "input number you wanna operate:" );
scanf( "%d", &n );
printf( "strncmp, %d\n", strncmp( str1, str2, n ) );
printf( "input a string:" );
scanf( "%s", str1 );
printf( "input another string:" );
scanf( "%s", str2 );
printf( "input number of chars you wanna operate:" );
scanf( "%d", &n );
strncat( str1, str2, n );
printf( "strncat, '%s'\n", str1 );
return 0;
}
static int strncpy( char *dst, char *src, int n ) {
int i;
for ( i = 0 ; (*dst = *src) != '\0' && i < n; i++, dst++, src++ )
;
*dst = '\0';
return 0;
}
static int strncmp( char *dst, char *src, int n ) {
int i;
for ( i = 0; *dst == *src && i < n; i++, dst++, src++ ) {
if ( *dst == '\0' ) {
return 0;
}
}
return *dst - *src;
}
static int strncat( char *dst, char *src, int n ) {
int i;
while ( *dst ) {
dst++;
}
for ( i = 0; i < n && (*dst = *src) != '\0'; i++, dst++, src++ )
;
return 0;
}
| 3.484375 | 3 |
2024-11-18T22:24:19.940796+00:00 | 2018-05-23T06:55:18 | 5fdc923e93ea3b04193b672e8acff940ad5678f2 | {
"blob_id": "5fdc923e93ea3b04193b672e8acff940ad5678f2",
"branch_name": "refs/heads/master",
"committer_date": "2018-05-23T06:55:18",
"content_id": "4bdb051214e2613dc2b3239c5e00724c608e6c96",
"detected_licenses": [
"MIT"
],
"directory_id": "2bc3398063fd7251c46a2d93d2e301cd063befcd",
"extension": "c",
"filename": "chan.c",
"fork_events_count": 4,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 134525191,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2286,
"license": "MIT",
"license_type": "permissive",
"path": "/nitan/kungfu/skill/quanzhen-jian/chan.c",
"provenance": "stackv2-0115.json.gz:83752",
"repo_name": "HKMUD/NT6",
"revision_date": "2018-05-23T06:55:18",
"revision_id": "bb518e2831edc6a83d25eccd99271da06eba8176",
"snapshot_id": "ae6a3c173ea07c156e8dc387b3ec21f3280ee0be",
"src_encoding": "GB18030",
"star_events_count": 9,
"url": "https://raw.githubusercontent.com/HKMUD/NT6/bb518e2831edc6a83d25eccd99271da06eba8176/nitan/kungfu/skill/quanzhen-jian/chan.c",
"visit_date": "2020-03-18T08:44:12.400598"
} | stackv2 | // This program is a part of NITAN MudLIB
#include <ansi.h>
#include <combat.h>
string name() { return HIC "缠字诀" NOR; }
inherit F_SSERVER;
int perform(object me, object target)
{
object weapon;
int level;
string msg;
int ap, dp;
if (! target) target = offensive_target(me);
if (! target || ! me->is_fighting(target))
return notify_fail(name() + "只能对战斗中的对手使用。\n");
if( !objectp(weapon=query_temp("weapon", me)) ||
query("skill_type", weapon) != "sword" )
return notify_fail("你使用的武器不对,难以施展" + name() + "。\n");
if (target->is_busy())
return notify_fail(target->name() + "目前正自顾不暇,放胆攻击吧。\n");
if ((level = me->query_skill("quanzhen-jian", 1)) < 80)
return notify_fail("你全真剑法不够娴熟,难以施展" + name() + "。\n");
if (me->query_skill_mapped("sword") != "quanzhen-jian")
return notify_fail("你没有激发全真剑法,难以施展" + name() + "。\n");
if( query("neili", me)<100 )
return notify_fail("你现在的真气不够,难以施展" + name() + "。\n");
if (! living(target))
return notify_fail("对方都已经这样了,用不着这么费力吧?\n");
msg = HIC "$N" HIC "使出全真剑法「缠」字诀," + weapon->name() +
HIC "带出阵阵风声,从四面八方盘绕向$n" HIC "。\n" NOR;
addn("neili", -50, me);
ap = attack_power(me, "sword");
dp = defense_power(target, "force");
if (ap / 2 + random(ap) > dp)
{
me->start_busy(1);
msg += HIR "$p" HIR "只觉得$P" HIR
"剑上压力一层强过一层,只能使尽浑身解数运功抵挡。\n" NOR;
target->start_busy(ap / 90 + 2);
} else
{
msg += CYN "$p" CYN "见$P" CYN "招法严谨,当下不敢小觑"
",巧妙拆解$P" CYN "的来招,不露半点破绽。\n" NOR;
me->start_busy(2);
}
message_combatd(msg, me, target);
return 1;
}
| 2.046875 | 2 |
2024-11-18T22:24:20.040050+00:00 | 2023-06-02T13:46:19 | af2b6927c92cd80ffae87a12bf87645f43748dd8 | {
"blob_id": "af2b6927c92cd80ffae87a12bf87645f43748dd8",
"branch_name": "refs/heads/3.16.0-stm32mp",
"committer_date": "2023-07-28T12:39:20",
"content_id": "1c5d4618dde805682f59ea50b7d819f4c916efa8",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "a8378f8953015617c24004b33177cdfe45422174",
"extension": "h",
"filename": "atomic.h",
"fork_events_count": 18,
"gha_created_at": "2019-01-30T08:45:15",
"gha_event_created_at": "2023-05-16T06:47:45",
"gha_language": "C",
"gha_license_id": "NOASSERTION",
"github_id": 168309214,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1371,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/lib/libutils/ext/include/atomic.h",
"provenance": "stackv2-0115.json.gz:83881",
"repo_name": "STMicroelectronics/optee_os",
"revision_date": "2023-06-02T13:46:19",
"revision_id": "b8750c4600166f0019a8c1cf35362b1889840ec3",
"snapshot_id": "5cbc12679f51b64a018f8a848903803c8c17e8e0",
"src_encoding": "UTF-8",
"star_events_count": 8,
"url": "https://raw.githubusercontent.com/STMicroelectronics/optee_os/b8750c4600166f0019a8c1cf35362b1889840ec3/lib/libutils/ext/include/atomic.h",
"visit_date": "2023-08-14T23:55:38.933221"
} | stackv2 | /* SPDX-License-Identifier: BSD-2-Clause */
/*
* Copyright (c) 2016-2019, Linaro Limited
*/
#ifndef __ATOMIC_H
#define __ATOMIC_H
#include <compiler.h>
#include <types_ext.h>
uint32_t atomic_inc32(volatile uint32_t *v);
uint32_t atomic_dec32(volatile uint32_t *v);
static inline bool atomic_cas_uint(unsigned int *p, unsigned int *oval,
unsigned int nval)
{
return __compiler_compare_and_swap(p, oval, nval);
}
static inline bool atomic_cas_u32(uint32_t *p, uint32_t *oval, uint32_t nval)
{
return __compiler_compare_and_swap(p, oval, nval);
}
static inline int atomic_load_int(int *p)
{
return __compiler_atomic_load(p);
}
static inline short int atomic_load_short(short int *p)
{
return __compiler_atomic_load(p);
}
static inline unsigned int atomic_load_uint(unsigned int *p)
{
return __compiler_atomic_load(p);
}
static inline uint32_t atomic_load_u32(const uint32_t *p)
{
return __compiler_atomic_load(p);
}
static inline void atomic_store_int(int *p, int val)
{
__compiler_atomic_store(p, val);
}
static inline void atomic_store_short(short int *p, short int val)
{
__compiler_atomic_store(p, val);
}
static inline void atomic_store_uint(unsigned int *p, unsigned int val)
{
__compiler_atomic_store(p, val);
}
static inline void atomic_store_u32(uint32_t *p, uint32_t val)
{
__compiler_atomic_store(p, val);
}
#endif /*__ATOMIC_H*/
| 2.609375 | 3 |
2024-11-18T22:24:20.351901+00:00 | 2018-01-08T19:58:04 | 219ade3b1898dbfefa7de64a1df21446fe223e9d | {
"blob_id": "219ade3b1898dbfefa7de64a1df21446fe223e9d",
"branch_name": "refs/heads/master",
"committer_date": "2018-01-08T19:58:04",
"content_id": "4fe0783f62e958ca527329fe3b124d93629debe7",
"detected_licenses": [
"BSD-2-Clause-Views"
],
"directory_id": "c67f66822be2073570f0fdb91530f756ca8893d6",
"extension": "c",
"filename": "sbush.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 116737994,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1935,
"license": "BSD-2-Clause-Views",
"license_type": "permissive",
"path": "/bin/sbush/sbush.c",
"provenance": "stackv2-0115.json.gz:84269",
"repo_name": "KD-12/OS-shell",
"revision_date": "2018-01-08T19:58:04",
"revision_id": "ebef564c607b2fef77236ff71b312a61126ff9a3",
"snapshot_id": "5a5420175d500cf958c95afb083f155c3db86475",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/KD-12/OS-shell/ebef564c607b2fef77236ff71b312a61126ff9a3/bin/sbush/sbush.c",
"visit_date": "2021-09-03T12:01:51.734702"
} | stackv2 | #define _GNU_SOURCE
#include <string.h>
#include <file.h>
#include <log.h>
#include <parse.h>
#include <ps1.h>
#include <executer.h>
#include <write.h>
#define PATHFILE "path.txt"
void parseAndExecute(char *input);
unsigned int MAXLINE_LENGTH=1000;
char *pwd;
char *path;
char ** pathArray;
int pathArrayCount=1;
//extern char **environ;
void getPath(){
path=fileContent(PATHFILE,500);
if(!path){
path="/shared/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games";
pathArray=split(path,":",&pathArrayCount);
pathArrayCount=1;
logIt("i am here trying to getPath\n");
char *env=executeAndReturn("printenv",3000);
logIt("printf env is : ");
logIt(env);
logIt("\n");
int splitedCount=0;
char **envSplitted=split(env,"\n",&splitedCount);;
for(int i=0;i<splitedCount;i++)
{
if(startsWith(envSplitted[i],"PATH"))
{
path=trim(substring(envSplitted[i],5));
}
}
logIt("path is :");
logIt(path);
logIt("\n");
writeToFile(PATHFILE,path);
}
pathArray=split(path,":",&pathArrayCount);
}
int main(int argc, char *argv[], char *envp[]) {
char *input;
getPath();
logIt("Starting up \n");
pwd=executeAndReturn("pwd",50);
initializePS1();
//homeDirectory=executeAndReturn("echo eval ~");
input=(char*) _malloc(MAXLINE_LENGTH*sizeof(char));
while(1){
logIt("getting the prompt\n");
char *prompt=getPrompt();
logIt("prompt received\n");
putOnFd(prompt,1);
// free(prompt);
int status=_fdread(0,input,MAXLINE_LENGTH);
*(input+status)='\n';
*(input+status+1)='\0';
// int status = getline(&input,&MAXLINE_LENGTH,stdin);
if(status < 0){
return 0;
}
logIt("received input :");
logIt(input);
logIt("\n");
parseAndExecute(input);
logIt("ready to take another input\n");
}
return 0;
}
| 2.359375 | 2 |
2024-11-18T22:24:20.467451+00:00 | 2019-06-09T18:30:03 | 16a313972f7302120dc4094f5043850f2e17a0dd | {
"blob_id": "16a313972f7302120dc4094f5043850f2e17a0dd",
"branch_name": "refs/heads/master",
"committer_date": "2019-06-09T18:30:03",
"content_id": "9e6ff4aacd922eb5743bdeaecf12a6f6e89f80a9",
"detected_licenses": [
"MIT"
],
"directory_id": "cb7ca03d1f99a3a30cabefb158abc04222fd6e36",
"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": 191034243,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3290,
"license": "MIT",
"license_type": "permissive",
"path": "/src/cas/eval.c",
"provenance": "stackv2-0115.json.gz:84397",
"repo_name": "axel7083/CGRAPH",
"revision_date": "2019-06-09T18:30:03",
"revision_id": "c5bf22f8e96232e5f18dcdad714744116ae70379",
"snapshot_id": "6e07c0785d081ac695955cf0a897633e80e34dcb",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/axel7083/CGRAPH/c5bf22f8e96232e5f18dcdad714744116ae70379/src/cas/eval.c",
"visit_date": "2022-01-06T14:27:04.400056"
} | stackv2 | #include "cas.h"
#include "mapping.h"
#include <math.h>
#ifndef _WIN32
double asinh(double x) {
return log(x + sqrt(1 + pow(x, 2)));
}
double acosh(double x) {
return 2 * log(sqrt((x + 1) / 2) + sqrt((x - 1) / 2));
}
double atanh(double x) {
return (log(1 + x) - log(1 - x)) / 2;
}
#endif
static unsigned factorial(unsigned x) {
unsigned total = 1;
for (; x > 0; x--)
total *= x;
return total;
}
double approximate(ast_t *e, error_t *err) {
*err = E_SUCCESS;
switch(e->type) {
case NODE_NUMBER:
return num_ToDouble(e->op.number);
case NODE_SYMBOL: {
double result;
ast_t *mapping = mapping_Get(e->op.symbol);
if(mapping == NULL) {
*err = E_EVAL_NO_MAPPING;
return 0;
}
result = approximate(mapping, err);
if(*err != E_SUCCESS)
return 0;
return result;
} case NODE_OPERATOR: {
OperatorType type = e->op.operator.type;
if(is_op_nary(type)) {
if(is_type_communative(type)) {
ast_t *current;
double total = (type == OP_ADD ? 0 : 1);
for(current = e->op.operator.base; current != NULL; current = current->next) {
switch(type) {
case OP_ADD: total += approximate(current, err); break;
case OP_MULT: total *= approximate(current, err); break;
default: break;
}
if(*err != E_SUCCESS)
return 0;
}
return total;
} else {
double left, right;
left = approximate(e->op.operator.base, err);
if(*err != E_SUCCESS) return 0;
right = approximate(e->op.operator.base->next, err);
if(*err != E_SUCCESS) return 0;
switch(type) {
case OP_DIV: return left / right;
case OP_POW: return pow(left, right);
case OP_ROOT: return right < 0 ? -1 * pow(-1 * right, 1.0 / left) : pow(right, 1.0 / left);
case OP_LOG: return log(right) / log(left);
default: break;
}
}
} else {
double x = approximate(e->op.operator.base, err);
if(*err != E_SUCCESS) return 0;
switch(type) {
case OP_FACTORIAL: return (double)factorial((unsigned)x);
case OP_INT: return (int)x;
case OP_ABS: return fabs(x);
case OP_SIN: return sin(x);
case OP_SIN_INV: return asin(x);
case OP_COS: return cos(x);
case OP_COS_INV: return acos(x);
case OP_TAN: return tan(x);
case OP_TAN_INV: return atan(x);
case OP_SINH: return sinh(x);
case OP_SINH_INV: return asinh(x);
case OP_COSH: return cosh(x);
case OP_COSH_INV: return acosh(x);
case OP_TANH: return tanh(x);
case OP_TANH_INV: return atanh(x);
default: break;
}
}
break;
}
}
return 0;
} | 2.859375 | 3 |
2024-11-18T22:24:21.675865+00:00 | 2021-04-03T10:31:52 | cb285514f287b5cb87baee72374ffd784c3d6ecf | {
"blob_id": "cb285514f287b5cb87baee72374ffd784c3d6ecf",
"branch_name": "refs/heads/master",
"committer_date": "2021-04-03T10:31:52",
"content_id": "3d57a328251de29325119b2f9343a09efee71e50",
"detected_licenses": [
"MIT"
],
"directory_id": "e2bbded7ebb2fed1f937395c509c0fc86b4444cb",
"extension": "c",
"filename": "freertos.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 221973924,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 11050,
"license": "MIT",
"license_type": "permissive",
"path": "/35_FreeRTOS_01_Start/Src/freertos.c",
"provenance": "stackv2-0115.json.gz:84786",
"repo_name": "Neo-Du/Stm32F429IGT6_Learning",
"revision_date": "2021-04-03T10:31:52",
"revision_id": "4e87711ec3570a8b9a2f65c5b365faae06886e32",
"snapshot_id": "bc878665622520cba0cc7708e4a3f5155d600186",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/Neo-Du/Stm32F429IGT6_Learning/4e87711ec3570a8b9a2f65c5b365faae06886e32/35_FreeRTOS_01_Start/Src/freertos.c",
"visit_date": "2021-06-24T17:14:19.247763"
} | stackv2 | /* USER CODE BEGIN Header */
/**
******************************************************************************
* File Name : freertos.c
* Description : Code for freertos applications
******************************************************************************
* @attention
*
* <h2><center>© Copyright (c) 2020 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under Ultimate Liberty license
* SLA0044, the "License"; You may not use this file except in compliance with
* the License. You may obtain a copy of the License at:
* www.st.com/SLA0044
*
******************************************************************************
*/
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "FreeRTOS.h"
#include "task.h"
#include "main.h"
#include "cmsis_os.h"
/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
/* USER CODE END Includes */
/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */
/* USER CODE END PTD */
/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
//定义�?个测试用的列表和3个列表项
List_t TestList; //测试用列�?
ListItem_t ListItem1; //测试用列表项1
ListItem_t ListItem2; //测试用列表项2
ListItem_t ListItem3; //测试用列表项3
/* USER CODE END PD */
/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */
/* USER CODE END PM */
/* Private variables ---------------------------------------------------------*/
/* USER CODE BEGIN Variables */
/* USER CODE END Variables */
osThreadId Name_Start_TaskHandle;
osThreadId myTask02Handle;
/* Private function prototypes -----------------------------------------------*/
/* USER CODE BEGIN FunctionPrototypes */
/* USER CODE END FunctionPrototypes */
void Start_Task(void const * argument);
void StartTask02(void const * argument);
void MX_FREERTOS_Init(void); /* (MISRA C 2004 rule 8.1) */
/* GetIdleTaskMemory prototype (linked to static allocation support) */
void vApplicationGetIdleTaskMemory( StaticTask_t **ppxIdleTaskTCBBuffer, StackType_t **ppxIdleTaskStackBuffer, uint32_t *pulIdleTaskStackSize );
/* USER CODE BEGIN GET_IDLE_TASK_MEMORY */
static StaticTask_t xIdleTaskTCBBuffer;
static StackType_t xIdleStack[configMINIMAL_STACK_SIZE];
void vApplicationGetIdleTaskMemory (StaticTask_t**ppxIdleTaskTCBBuffer,StackType_t**ppxIdleTaskStackBuffer,uint32_t*pulIdleTaskStackSize)
{
*ppxIdleTaskTCBBuffer = &xIdleTaskTCBBuffer;
*ppxIdleTaskStackBuffer = &xIdleStack[0];
*pulIdleTaskStackSize = configMINIMAL_STACK_SIZE;
/* place for user code */
}
/* USER CODE END GET_IDLE_TASK_MEMORY */
/**
* @brief FreeRTOS initialization
* @param None
* @retval None
*/
void MX_FREERTOS_Init(void) {
/* USER CODE BEGIN Init */
/* USER CODE END Init */
/* USER CODE BEGIN RTOS_MUTEX */
/* add mutexes, ... */
/* USER CODE END RTOS_MUTEX */
/* USER CODE BEGIN RTOS_SEMAPHORES */
/* add semaphores, ... */
/* USER CODE END RTOS_SEMAPHORES */
/* USER CODE BEGIN RTOS_TIMERS */
/* start timers, add new ones, ... */
/* USER CODE END RTOS_TIMERS */
/* USER CODE BEGIN RTOS_QUEUES */
/* add queues, ... */
/* USER CODE END RTOS_QUEUES */
/* Create the thread(s) */
/* definition and creation of Name_Start_Task */
osThreadDef(Name_Start_Task, Start_Task, osPriorityNormal, 0, 128);
Name_Start_TaskHandle = osThreadCreate(osThread(Name_Start_Task), NULL);
/* definition and creation of myTask02 */
osThreadDef(myTask02, StartTask02, osPriorityIdle, 0, 128);
myTask02Handle = osThreadCreate(osThread(myTask02), NULL);
/* USER CODE BEGIN RTOS_THREADS */
/* add threads, ... */
/* USER CODE END RTOS_THREADS */
}
/* USER CODE BEGIN Header_Start_Task */
/**
* @brief Function implementing the Name_Start_Task thread.
* @param argument: Not used
* @retval None
*/
/* USER CODE END Header_Start_Task */
void Start_Task(void const * argument)
{
/* USER CODE BEGIN Start_Task */
for (;;)
{
HAL_GPIO_TogglePin (GPIOB, GPIO_PIN_0);
osDelay (100);
}
/* USER CODE END Start_Task */
}
/* USER CODE BEGIN Header_StartTask02 */
/**
* @brief Function implementing the myTask02 thread.
* @param argument: Not used
* @retval None
*/
/* USER CODE END Header_StartTask02 */
void StartTask02(void const * argument)
{
/* USER CODE BEGIN StartTask02 */
vListInitialise (&TestList);
vListInitialiseItem (&ListItem1);
vListInitialiseItem (&ListItem2);
vListInitialiseItem (&ListItem3);
ListItem1.xItemValue = 40; //ListItem1列表项�?�为40
ListItem2.xItemValue = 60; //ListItem2列表项�?�为60
ListItem3.xItemValue = 50; //ListItem3列表项�?�为50
printf ("/*******************列表和列表项地址*******************/\r\n");
printf ("项目 地址 \r\n");
printf ("TestList %#x \r\n", (int) &TestList);
printf ("TestList->pxIndex %#x \r\n", (int) TestList.pxIndex);
printf ("TestList->xListEnd %#x \r\n", (int) (&TestList.xListEnd));
printf ("ListItem1 %#x \r\n", (int) &ListItem1);
printf ("ListItem2 %#x \r\n", (int) &ListItem2);
printf ("ListItem3 %#x \r\n", (int) &ListItem3);
printf ("/************************结束**************************/\r\n");
vListInsert(&TestList,&ListItem1); //插入列表项ListItem1
printf("/******************添加列表项ListItem1*****************/\r\n");
printf("项目 地址 \r\n");
printf("TestList->xListEnd->pxNext %#x \r\n",(int)(TestList.xListEnd.pxNext));
printf("ListItem1->pxNext %#x \r\n",(int)(ListItem1.pxNext));
printf("/*******************前后向连接分割线********************/\r\n");
printf("TestList->xListEnd->pxPrevious %#x \r\n",(int)(TestList.xListEnd.pxPrevious));
printf("ListItem1->pxPrevious %#x \r\n",(int)(ListItem1.pxPrevious));
printf("/************************结束**************************/\r\n");
vListInsert(&TestList,&ListItem2); //插入列表项ListItem2
printf("/******************添加列表项ListItem2*****************/\r\n");
printf("项目 地址 \r\n");
printf("TestList->xListEnd->pxNext %#x \r\n",(int)(TestList.xListEnd.pxNext));
printf("ListItem1->pxNext %#x \r\n",(int)(ListItem1.pxNext));
printf("ListItem2->pxNext %#x \r\n",(int)(ListItem2.pxNext));
printf("/*******************前后向连接分割线********************/\r\n");
printf("TestList->xListEnd->pxPrevious %#x \r\n",(int)(TestList.xListEnd.pxPrevious));
printf("ListItem1->pxPrevious %#x \r\n",(int)(ListItem1.pxPrevious));
printf("ListItem2->pxPrevious %#x \r\n",(int)(ListItem2.pxPrevious));
printf("/************************结束**************************/\r\n");
vListInsert(&TestList,&ListItem3); //插入列表项ListItem3
printf("/******************添加列表项ListItem3*****************/\r\n");
printf("项目 地址 \r\n");
printf("TestList->xListEnd->pxNext %#x \r\n",(int)(TestList.xListEnd.pxNext));
printf("ListItem1->pxNext %#x \r\n",(int)(ListItem1.pxNext));
printf("ListItem3->pxNext %#x \r\n",(int)(ListItem3.pxNext));
printf("ListItem2->pxNext %#x \r\n",(int)(ListItem2.pxNext));
printf("/*******************前后向连接分割线********************/\r\n");
printf("TestList->xListEnd->pxPrevious %#x \r\n",(int)(TestList.xListEnd.pxPrevious));
printf("ListItem1->pxPrevious %#x \r\n",(int)(ListItem1.pxPrevious));
printf("ListItem3->pxPrevious %#x \r\n",(int)(ListItem3.pxPrevious));
printf("ListItem2->pxPrevious %#x \r\n",(int)(ListItem2.pxPrevious));
printf("/************************结束**************************/\r\n");
uxListRemove(&ListItem2); //删除ListItem2
printf("/******************删除列表项ListItem2*****************/\r\n");
printf("项目 地址 \r\n");
printf("TestList->xListEnd->pxNext %#x \r\n",(int)(TestList.xListEnd.pxNext));
printf("ListItem1->pxNext %#x \r\n",(int)(ListItem1.pxNext));
printf("ListItem3->pxNext %#x \r\n",(int)(ListItem3.pxNext));
printf("/*******************前后向连接分割线********************/\r\n");
printf("TestList->xListEnd->pxPrevious %#x \r\n",(int)(TestList.xListEnd.pxPrevious));
printf("ListItem1->pxPrevious %#x \r\n",(int)(ListItem1.pxPrevious));
printf("ListItem3->pxPrevious %#x \r\n",(int)(ListItem3.pxPrevious));
printf("/************************结束**************************/\r\n");
TestList.pxIndex=TestList.pxIndex->pxNext; //pxIndex向后移一项,这样pxIndex就会指向ListItem1�?
vListInsertEnd(&TestList,&ListItem2); //列表末尾添加列表项ListItem2
printf("/***************在末尾添加列表项ListItem2***************/\r\n");
printf("项目 地址 \r\n");
printf("TestList->pxIndex %#x \r\n",(int)TestList.pxIndex);
printf("TestList->xListEnd->pxNext %#x \r\n",(int)(TestList.xListEnd.pxNext));
printf("ListItem2->pxNext %#x \r\n",(int)(ListItem2.pxNext));
printf("ListItem1->pxNext %#x \r\n",(int)(ListItem1.pxNext));
printf("ListItem3->pxNext %#x \r\n",(int)(ListItem3.pxNext));
printf("/*******************前后向连接分割线********************/\r\n");
printf("TestList->xListEnd->pxPrevious %#x \r\n",(int)(TestList.xListEnd.pxPrevious));
printf("ListItem2->pxPrevious %#x \r\n",(int)(ListItem2.pxPrevious));
printf("ListItem1->pxPrevious %#x \r\n",(int)(ListItem1.pxPrevious));
printf("ListItem3->pxPrevious %#x \r\n",(int)(ListItem3.pxPrevious));
printf("/************************结束**************************/\r\n\r\n\r\n");
while(1);
/* USER CODE END StartTask02 */
}
/* Private application code --------------------------------------------------*/
/* USER CODE BEGIN Application */
/* USER CODE END Application */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
| 2.109375 | 2 |
2024-11-18T22:24:21.786454+00:00 | 2023-08-30T22:57:11 | 4ce9039342528ee5758801cce91b6ae8cb7d8edc | {
"blob_id": "4ce9039342528ee5758801cce91b6ae8cb7d8edc",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-30T22:57:11",
"content_id": "43502897ac2538d3b6e8d029c43dc2e879ea3a06",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "f47cb02269307e83d86373d9ab4bfb8b46283d22",
"extension": "c",
"filename": "guaclog.c",
"fork_events_count": 580,
"gha_created_at": "2016-03-22T07:00:06",
"gha_event_created_at": "2023-09-13T00:15:57",
"gha_language": "C",
"gha_license_id": "Apache-2.0",
"github_id": 54452627,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3290,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/guaclog/guaclog.c",
"provenance": "stackv2-0115.json.gz:84915",
"repo_name": "apache/guacamole-server",
"revision_date": "2023-08-30T22:57:11",
"revision_id": "fe24e2d45ac0ac90588f64b43da6e0d518e59177",
"snapshot_id": "7c8adf3f389f0539df353ef8f7ea6d44144ffb16",
"src_encoding": "UTF-8",
"star_events_count": 2019,
"url": "https://raw.githubusercontent.com/apache/guacamole-server/fe24e2d45ac0ac90588f64b43da6e0d518e59177/src/guaclog/guaclog.c",
"visit_date": "2023-09-04T02:42:34.907413"
} | stackv2 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 "config.h"
#include "guaclog.h"
#include "interpret.h"
#include "log.h"
#include <getopt.h>
#include <stdbool.h>
#include <stdio.h>
int main(int argc, char* argv[]) {
int i;
/* Load defaults */
bool force = false;
/* Parse arguments */
int opt;
while ((opt = getopt(argc, argv, "s:r:f")) != -1) {
/* -f: Force */
if (opt == 'f')
force = true;
/* Invalid option */
else {
goto invalid_options;
}
}
/* Log start */
guaclog_log(GUAC_LOG_INFO, "Guacamole input log interpreter (guaclog) "
"version " VERSION);
/* Track number of overall failures */
int total_files = argc - optind;
int failures = 0;
/* Abort if no files given */
if (total_files <= 0) {
guaclog_log(GUAC_LOG_INFO, "No input files specified. Nothing to do.");
return 0;
}
guaclog_log(GUAC_LOG_INFO, "%i input file(s) provided.", total_files);
/* Interpret all input files */
for (i = optind; i < argc; i++) {
/* Get current filename */
const char* path = argv[i];
/* Generate output filename */
char out_path[4096];
int len = snprintf(out_path, sizeof(out_path), "%s.txt", path);
/* Do not write if filename exceeds maximum length */
if (len >= sizeof(out_path)) {
guaclog_log(GUAC_LOG_ERROR, "Cannot write output file for \"%s\": "
"Name too long", path);
continue;
}
/* Attempt interpreting, log granular success/failure at debug level */
if (guaclog_interpret(path, out_path, force)) {
failures++;
guaclog_log(GUAC_LOG_DEBUG,
"%s was NOT successfully interpreted.", path);
}
else
guaclog_log(GUAC_LOG_DEBUG, "%s was successfully "
"interpreted.", path);
}
/* Warn if at least one file failed */
if (failures != 0)
guaclog_log(GUAC_LOG_WARNING, "Interpreting failed for %i of %i "
"file(s).", failures, total_files);
/* Notify of success */
else
guaclog_log(GUAC_LOG_INFO, "All files interpreted successfully.");
/* Interpreting complete */
return 0;
/* Display usage and exit with error if options are invalid */
invalid_options:
fprintf(stderr, "USAGE: %s"
" [-f]"
" [FILE]...\n", argv[0]);
return 1;
}
| 2.578125 | 3 |
2024-11-18T22:24:25.331054+00:00 | 2021-10-27T20:56:46 | 29d378deda7c232818a2b0da280b60adb7ac3241 | {
"blob_id": "29d378deda7c232818a2b0da280b60adb7ac3241",
"branch_name": "refs/heads/master",
"committer_date": "2021-10-27T20:56:46",
"content_id": "03d3dd462158760aa1e2010324eefa24b9a4644b",
"detected_licenses": [
"MIT"
],
"directory_id": "805d368e1295cebea948abda9b02551d6d527a42",
"extension": "c",
"filename": "video.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 404146259,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 8329,
"license": "MIT",
"license_type": "permissive",
"path": "/src/video.c",
"provenance": "stackv2-0115.json.gz:85043",
"repo_name": "Xwilarg/Colodex",
"revision_date": "2021-10-27T20:56:46",
"revision_id": "8407888d648f7f512f5402d1c25c1dc582ad48d8",
"snapshot_id": "fd7e4680cdb1411d4a672bfd89aaf5fd9dd41464",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/Xwilarg/Colodex/8407888d648f7f512f5402d1c25c1dc582ad48d8/src/video.c",
"visit_date": "2023-08-24T20:56:43.102297"
} | stackv2 | #include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include "colodex/video.h"
#include "internal/client.h"
#include "internal/utils.h"
#include "internal/channel.h"
static video_type parse_video_type(const cJSON* json, const char* name)
{
char* value = cJSON_GetObjectItemCaseSensitive(json, name)->valuestring;
if (strcmp(value, "stream") == 0) return STREAM;
if (strcmp(value, "clip") == 0) return CLIP;
if (strcmp(value, "placeholder") == 0) return PLACEHOLDER;
fprintf(stderr, "Unknown video type %s\n", value);
return -1;
}
static video_status parse_video_status(const cJSON* json, const char* name)
{
char* value = cJSON_GetObjectItemCaseSensitive(json, name)->valuestring;
if (strcmp(value, "new") == 0) return NEW;
if (strcmp(value, "upcoming") == 0) return UPCOMING;
if (strcmp(value, "live") == 0) return LIVE;
if (strcmp(value, "past") == 0) return PAST;
if (strcmp(value, "missing") == 0) return MISSING;
fprintf(stderr, "Unknown video status %s\n", value);
return -1;
}
static video* parse_video(cJSON* json)
{
video* vid = malloc(sizeof(video));
if (vid == NULL)
{
return NULL;
}
vid->id = parse_string(json, "id");
vid->title = parse_string(json, "title");
vid->type = parse_video_type(json, "type");
vid->topic_id = parse_string(json, "topic_id");
vid->published_at = parse_date_time(json, "published_at");
vid->available_at = parse_date_time(json, "available_at");
vid->status = parse_video_status(json, "status");
vid->duration = parse_int(json, "duration");
vid->songcount = parse_int(json, "songcount");
// TODO: live_tl_count
cJSON* chJson = cJSON_GetObjectItemCaseSensitive(json, "channel");
vid->channel_info = parse_channel_min(chJson);
return vid;
}
// Appends "append" and "appendArg" to "text"
// If text, will malloc it, else will realloc it
// Used to create an URL with arguments
static char* malloc_or_append(char* text, const char* append, const char* appendArg)
{
size_t size;
if (text == NULL)
{
size = strlen(append) + strlen(appendArg) + 1;
text = malloc(size);
snprintf(text, size, "%s%s", append, appendArg);
return text;
}
size = strlen(text) + strlen(append) + strlen(appendArg) + 1;
text = realloc(text, size);
#ifdef _WIN32
strcat_s(text, size, append);
strcat_s(text, size, appendArg);
#else
strcat(text, append);
strcat(text, appendArg);
#endif
return text;
}
static char* int_to_string(int value, char* buffer)
{
#ifdef _WIN32
sprintf_s(buffer, 10, "%d", value);
#else
sprintf(buffer, "%d", value);
#endif
return buffer;
}
// Create parameter part of URL given query info
static char* create_url(const query_video* query, query_video_param params)
{
if (query == NULL)
{
char* empty = malloc(1);
empty[0] = '\0';
return empty;
}
char* url = NULL;
char buffer[10];
if ((params & LIMIT) != 0) // Limit the number of result
{
url = malloc_or_append(url, "&limit=", int_to_string(query->limit, buffer));
}
if ((params & MAX_UPCOMING_HOURS) != 0) // Remove video that come further than the giving hour
{
url = malloc_or_append(url, "&max_upcoming_hours=", int_to_string(query->max_upcoming_hours, buffer));
}
if ((params & OFFSET) != 0) // Offset results
{
url = malloc_or_append(url, "&offset=", int_to_string(query->offset, buffer));
}
if ((params & ORDER) != 0) // Sort results by ascending or descending
{
char* order;
switch (query->order)
{
case ASCENDING:
order = "asc";
break;
case DESCENDING:
order = "desc";
break;
default:
fprintf(stderr, "Unknown order %d\n", query->order);
return NULL;
}
url = malloc_or_append(url, "&order=", order);
}
if ((params & ORG) != 0) // Filter by org that the vtubers belong to
{
url = malloc_or_append(url, "&org=", query->org);
}
if ((params & STATUS) != 0) // Filter by video status
{
char* status;
switch (query->status)
{
case NEW:
status = "new";
break;
case UPCOMING:
status = "upcoming";
break;
case LIVE:
status = "live";
break;
case PAST:
status = "past";
break;
case MISSING:
status = "missing";
break;
default:
fprintf(stderr, "Unknown status %d\n", query->status);
return NULL;
}
url = malloc_or_append(url, "&status=", status);
}
if ((params & TOPIC) != 0) // Filter by video topic
{
url = malloc_or_append(url, "&topic=", query->topic);
}
if ((params & TYPE) != 0) // Filter by streams or clippers
{
char* type;
switch (query->type)
{
case STREAM:
type = "stream";
break;
case CLIP:
type = "clip";
break;
case PLACEHOLDER:
type = "placeholder";
break;
default:
fprintf(stderr, "Unknown type %d\n", query->type);
return NULL;
}
url = malloc_or_append(url, "&type=", type);
}
return url;
}
video* colodex_get_video_from_id(const char* video_id)
{
char* baseUrl = "https://holodex.net/api/v2/videos?id=";
size_t size = strlen(baseUrl) + strlen(video_id) + 1;
char* url = malloc(size);
if (url == NULL)
{
return NULL;
}
snprintf(url, size, "%s%s", baseUrl, video_id);
char* resp = request(url);
cJSON* json = cJSON_Parse(resp);
free(resp);
free(url);
size_t arrSize = cJSON_GetArraySize(json);
if (arrSize == 0) // No video with this ID
{
cJSON_Delete(json);
return NULL;
}
video* vid = parse_video(json->child);
cJSON_Delete(json);
return vid;
}
// Internal method for parsing of multiple video
static video** get_videos(cJSON* json)
{
size_t arrSize = cJSON_GetArraySize(json);
video** vid;
vid = malloc(sizeof(video*) * (arrSize + 1));
if (vid == NULL)
{
return NULL;
}
cJSON* it = json->child;
for (size_t i = 0; i < arrSize; i++)
{
vid[i] = parse_video(it);
it = it->next;
}
vid[arrSize] = NULL;
cJSON_Delete(json);
return vid;
}
video** colodex_get_videos(const query_video* query, query_video_param params)
{
char* baseUrl = "https://holodex.net/api/v2/videos";
char* args = create_url(query, params);
if(strlen(args) > 1) // There are query parameters
{
args[0] = '?'; // create_url put '&' in front parameter but this method need the first one to use a '?'
}
size_t size = strlen(baseUrl) + strlen(args) + 1;
char* url = malloc(size);
if (url == NULL)
{
return NULL;
}
snprintf(url, size, "%s%s", baseUrl, args);
char* resp = request(url);
cJSON* json = cJSON_Parse(resp);
free(resp);
free(url);
free(args);
return get_videos(json);
}
video** colodex_get_videos_from_channel_id(const char* channel_id, const query_video* query, query_video_param params)
{
char* baseUrl = "https://holodex.net/api/v2/videos?channel_id=";
char* args = create_url(query, params);
size_t size = strlen(baseUrl) + strlen(channel_id) + strlen(args) + 1;
char* url = malloc(size);
if (url == NULL)
{
return NULL;
}
snprintf(url, size, "%s%s%s", baseUrl, channel_id, args);
char* resp = request(url);
cJSON* json = cJSON_Parse(resp);
free(resp);
free(url);
free(args);
return get_videos(json);
}
void colodex_free_video(video* vid)
{
free(vid->id);
free(vid->title);
free(vid->topic_id);
free_channel_min(vid->channel_info);
free(vid);
}
void colodex_free_videos(video** vids)
{
for (int i = 0; vids[i] != NULL; i++)
{
colodex_free_video(vids[i]);
}
free(vids);
} | 2.296875 | 2 |
2024-11-18T22:24:26.070376+00:00 | 2023-06-03T18:00:52 | f8b878a225780b097b11b54215574885d36d1f0d | {
"blob_id": "f8b878a225780b097b11b54215574885d36d1f0d",
"branch_name": "refs/heads/master",
"committer_date": "2023-06-03T18:00:52",
"content_id": "b55d9a2d9031294c9743857cea4cddc8ee8e58fb",
"detected_licenses": [
"MIT"
],
"directory_id": "1c5679c8100689ec3693b6c02266310283b5ba95",
"extension": "c",
"filename": "log_manager.c",
"fork_events_count": 3,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 213285771,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1981,
"license": "MIT",
"license_type": "permissive",
"path": "/backend/src/log_manager.c",
"provenance": "stackv2-0115.json.gz:85172",
"repo_name": "krglaws/3rd-Place",
"revision_date": "2023-06-03T18:00:52",
"revision_id": "98cc19a4ba9b57d693a028fd20c85ed53be0f21e",
"snapshot_id": "fffefd7524d650f59a44932faa2a3d6b04f60e70",
"src_encoding": "UTF-8",
"star_events_count": 34,
"url": "https://raw.githubusercontent.com/krglaws/3rd-Place/98cc19a4ba9b57d693a028fd20c85ed53be0f21e/backend/src/log_manager.c",
"visit_date": "2023-06-08T20:00:39.717405"
} | stackv2 | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <time.h>
#include <signal.h>
#include <log_manager.h>
static void log_all(const char* logtype, const char* fmt, va_list ap);
static void terminate_log_manager();
// this is the output file for all logs
// which can be configured via CLI args
static FILE* logfile = NULL;
// temporary storage buffer for incoming log messages
static char logbuff[MAXLOGLEN + 1];
static void log_all(const char* logtype, const char* fmt, va_list ap)
{
// get datetime
char timebuff[32];
time_t rawtime = time(NULL);
struct tm* ptm = localtime(&rawtime);
strftime(timebuff, 32, "%x %T", ptm);
// process format string
vsprintf(logbuff, fmt, ap);
int len;
char* buffptr = logbuff;
char* nlloc;
// for each '\n' char in message,
// print preceding 'logtype' string
do
{
if ((nlloc = strstr(buffptr, "\n")) != NULL)
{
len = (int) (nlloc - buffptr);
}
else
{
len = strlen(buffptr);
}
fprintf(logfile, "(%s)%s%.*s\n", timebuff, logtype, len, buffptr);
buffptr += (len + 1);
} while (*buffptr);
memset(logbuff, 0, MAXLOGLEN + 1);
}
void init_log_manager(const char* path)
{
if (path == NULL || strlen(path) == 0)
{
logfile = stdout;
}
else if ((logfile = fopen(path, "a")) == NULL)
{
fprintf(stderr, "init_logger(): failed to open log file '%s'\n", path);
exit(EXIT_FAILURE);
}
atexit(&terminate_log_manager);
}
static void terminate_log_manager()
{
fclose(logfile);
}
void log_info(const char* fmt, ...)
{
va_list ap;
va_start(ap, fmt);
log_all(INFOSTR, fmt, ap);
va_end(ap);
}
void log_err(const char* fmt, ...)
{
va_list ap;
va_start(ap, fmt);
log_all(ERRSTR, fmt, ap);
va_end(ap);
}
void log_crit(const char* fmt, ...)
{
va_list ap;
va_start(ap, fmt);
log_all(CRITSTR, fmt, ap);
va_end(ap);
// terminate server process gracefully
raise(SIGTERM);
}
| 2.703125 | 3 |
2024-11-18T22:24:26.160430+00:00 | 2016-07-21T14:25:19 | 038df1a6dcf3fc1a01e4c51c57c6362926dea753 | {
"blob_id": "038df1a6dcf3fc1a01e4c51c57c6362926dea753",
"branch_name": "refs/heads/master",
"committer_date": "2016-07-21T14:25:19",
"content_id": "b125b41f23bc00508dda15be38faddee56c0bb70",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "7f8e18f79f64478574cf617d6075af610fada0f8",
"extension": "c",
"filename": "driver.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 22942169,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3200,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/apps/DARPA/components/uart/src/driver.c",
"provenance": "stackv2-0115.json.gz:85301",
"repo_name": "smaccm/camkes-apps-DARPA--devel",
"revision_date": "2016-07-21T14:25:19",
"revision_id": "c112a453afacc7991bc8057edbff63c660255771",
"snapshot_id": "fb7f261daa8c620589d385213e9f1a97473101dd",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/smaccm/camkes-apps-DARPA--devel/c112a453afacc7991bc8057edbff63c660255771/apps/DARPA/components/uart/src/driver.c",
"visit_date": "2021-01-18T23:20:36.570453"
} | stackv2 | /*
* Copyright 2014, NICTA
*
* This software may be distributed and modified according to the terms of
* the BSD 2-Clause license. Note that NO WARRANTY is provided.
* See "LICENSE_BSD2.txt" for details.
*
* @TAG(NICTA_BSD)
*/
#include <stdio.h>
#include <platsupport/chardev.h>
#include <platsupport/serial.h>
#include <uart.h>
//#define BAUD_RATE 115200
#define BAUD_RATE 57600
#ifdef CONFIG_PLAT_EXYNOS5410
#define DEV_ID PS_SERIAL1
#elif CONFIG_PLAT_IMX31
#define DEV_ID IMX31_UART1
#else
#error
#endif
struct uart_token {
size_t cur_bytes;
size_t req_bytes;
char* buf;
};
static ps_chardevice_t serial_device;
static void
interrupt_event(void* token)
{
ps_chardevice_t* device;
device = (ps_chardevice_t*)token;
ps_cdev_handle_irq(device, 0);
interrupt_reg_callback(&interrupt_event, token);
}
void uart__init(void)
{
/* Iniitialise the UART */
printf("Initialising UART driver\n");
if(exynos_serial_init(DEV_ID, uart0base, NULL, NULL, &serial_device)){
printf("Failed to initialise UART\n");
while(1);
}
serial_configure(&serial_device, BAUD_RATE, 8, PARITY_NONE, 1);
/* Prime semaphores */
read_sem_wait();
write_sem_wait();
/* Register for IRQs */
interrupt_reg_callback(&interrupt_event, &serial_device);
}
static void
read_callback(ps_chardevice_t* device, enum chardev_status stat,
size_t bytes_transfered, void* token){
struct uart_token* t;
t = (struct uart_token*)token;
/* We might get a short read due to a timeout. */
t->cur_bytes += bytes_transfered;
t->buf += bytes_transfered;
if(t->cur_bytes < t->req_bytes){
int ret;
ret = ps_cdev_read(device, t->buf, t->req_bytes - t->cur_bytes,
&read_callback, token);
if(ret < 0){
printf("Error reading from UART\n");
read_sem_post();
}
}else{
read_sem_post();
}
}
static void
write_callback(ps_chardevice_t* device, enum chardev_status stat,
size_t bytes_transfered, void* token){
struct uart_token* t;
t = (struct uart_token*)token;
t->cur_bytes += bytes_transfered;
if(t->cur_bytes == t->req_bytes){
write_sem_post();
}
}
int uart_read(int uart_num, int rsize)
{
struct uart_token token;
if (uart_num != 0) {
printf("Only support UART0!\n");
return -1;
}
token.cur_bytes = 0;
token.req_bytes = rsize;
token.buf = (char*)client_buf;
if(ps_cdev_read(&serial_device, token.buf, token.req_bytes, &read_callback, &token) < 0){
printf("Error reading from UART\n");
return -1;
}
read_sem_wait();
return token.cur_bytes;
}
int uart_write(int uart_num, int wsize)
{
struct uart_token token;
if (uart_num != 0) {
printf("Only support UART0!\n");
return -1;
}
token.cur_bytes = 0;
token.req_bytes = wsize;
token.buf = (char*)client_buf;
if(ps_cdev_write(&serial_device, token.buf, token.req_bytes, &write_callback, &token) < 0){
printf("Error writing to UART\n");
return -1;
}
write_sem_wait();
return wsize;
}
| 2.546875 | 3 |
2024-11-18T22:24:26.995067+00:00 | 2023-08-09T18:19:32 | 63d8d6d09e0659a8883cb02540cd039febf91e25 | {
"blob_id": "63d8d6d09e0659a8883cb02540cd039febf91e25",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-09T18:19:32",
"content_id": "ef7ba764b4c369cc7f3790e61ccbc43ac11bac38",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "a4a96286d9860e2661cd7c7f571d42bfa04c86cf",
"extension": "h",
"filename": "soc_hal.h",
"fork_events_count": 1,
"gha_created_at": "2020-01-23T18:05:37",
"gha_event_created_at": "2020-01-23T18:05:38",
"gha_language": null,
"gha_license_id": "Apache-2.0",
"github_id": 235855012,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1163,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/components/esp_hw_support/include/hal/soc_hal.h",
"provenance": "stackv2-0115.json.gz:86204",
"repo_name": "KollarRichard/esp-idf",
"revision_date": "2023-08-09T18:19:32",
"revision_id": "3befd5fff72aa6980514454a50233037718b611f",
"snapshot_id": "1a3c314b37c763bdd231d974c9e16b9c7588e42c",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/KollarRichard/esp-idf/3befd5fff72aa6980514454a50233037718b611f/components/esp_hw_support/include/hal/soc_hal.h",
"visit_date": "2023-08-16T20:32:50.823995"
} | stackv2 | /*
* SPDX-FileCopyrightText: 2020-2022 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Apache-2.0
*/
#pragma once
/*
Note: This is a compatibility header. Call the interfaces in esp_cpu.h instead
*/
#include "soc/soc_caps.h"
#include "hal/soc_ll.h"
#ifdef __cplusplus
extern "C" {
#endif
#if SOC_CPU_CORES_NUM > 1 // We only allow stalling/unstalling of other cores
/**
* Stall the specified CPU core.
*
* @note Has no effect if the core is already stalled - does not return an
* ESP_ERR_INVALID_STATE.
*
* @param core core to stall [0..SOC_CPU_CORES_NUM - 1]
*/
#define soc_hal_stall_core(core) soc_ll_stall_core(core)
/**
* Unstall the specified CPU core.
*
* @note Has no effect if the core is already unstalled - does not return an
* ESP_ERR_INVALID_STATE.
*
* @param core core to unstall [0..SOC_CPU_CORES_NUM - 1]
*/
#define soc_hal_unstall_core(core) soc_ll_unstall_core(core)
#endif // SOC_CPU_CORES_NUM > 1
/**
* Reset the specified core.
*
* @param core core to reset [0..SOC_CPU_CORES_NUM - 1]
*/
#define soc_hal_reset_core(core) soc_ll_reset_core((core))
#ifdef __cplusplus
}
#endif
| 2.421875 | 2 |
2024-11-18T22:24:27.050881+00:00 | 2020-06-16T06:20:56 | 784088ff7126014bacb729c0844ab61e8cadac41 | {
"blob_id": "784088ff7126014bacb729c0844ab61e8cadac41",
"branch_name": "refs/heads/master",
"committer_date": "2020-06-16T06:20:56",
"content_id": "dc520c6d292595361c3c91c6c87ce8a51049810b",
"detected_licenses": [
"MIT"
],
"directory_id": "69ef8ab578ba5e62a05e4f6102282377333ef462",
"extension": "c",
"filename": "test.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 168,
"license": "MIT",
"license_type": "permissive",
"path": "/Lectures/Francisco/Makefile_Example/test.c",
"provenance": "stackv2-0115.json.gz:86333",
"repo_name": "kevinmonisit/CS214-Rutgers",
"revision_date": "2020-06-16T06:20:56",
"revision_id": "c338a6a5987528a43ebf67f5032c0be379048d54",
"snapshot_id": "4ee977e903e153463cedfd6894f37f81d85fecaf",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/kevinmonisit/CS214-Rutgers/c338a6a5987528a43ebf67f5032c0be379048d54/Lectures/Francisco/Makefile_Example/test.c",
"visit_date": "2022-10-26T06:12:37.374154"
} | stackv2 | #include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "stuff.h"
int main(int argc, char **argv)
{
printf(" other things %d\n", values(6));
return 0;
}
| 2.078125 | 2 |
2024-11-18T22:24:27.551222+00:00 | 2018-12-09T02:18:04 | 9c0c7265cc10759f08b6106b2a3fb45e3d29124b | {
"blob_id": "9c0c7265cc10759f08b6106b2a3fb45e3d29124b",
"branch_name": "refs/heads/master",
"committer_date": "2018-12-09T02:18:04",
"content_id": "14026cc975b14594a4fc57726b00bd571a5ee810",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "ba9c3bd4cdeac43032f81f691624f6f6ba59903b",
"extension": "c",
"filename": "org_it4y_jni_linuxutils.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 160959468,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 22276,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/native/org_it4y_jni_linuxutils.c",
"provenance": "stackv2-0115.json.gz:86848",
"repo_name": "yaosdn/clj-linux-net",
"revision_date": "2018-12-09T02:18:04",
"revision_id": "27af705bd09c9ded5ed736d707436ee17b886df6",
"snapshot_id": "fd25beaf13cfaee8cc4b00271036d9e7eebbb01e",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/yaosdn/clj-linux-net/27af705bd09c9ded5ed736d707436ee17b886df6/src/native/org_it4y_jni_linuxutils.c",
"visit_date": "2020-04-10T10:14:30.647378"
} | stackv2 | /*
* Copyright 2014 Luc Willems (T.M.M.)
*
* 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 <sys/socket.h>
#include <errno.h>
#include <netinet/in.h>
#include <jni.h>
#include <string.h>
#include <linux/tcp.h>
//ioctl
#include <sys/ioctl.h>
#include <net/if.h>
#include <arpa/inet.h>
//time
#include <time.h>
#include "org_it4y_jni_linuxutils.h"
/* Amount of characters in the error message buffer */
#define ERROR_SIZE 254
//some errorcodes
#define OK 0;
#define ERR_JNI_ERROR -1;
#define ERR_FIND_CLASS_FAILED -2;
#define ERR_FIND_FIELD_FAILED -3;
#define ERR_GET_METHOD_FAILED -4;
#define ERR_CALL_METHOD_FAILED -5;
#define ERR_BUFFER_TO_SMALL -6;
#define ERR_EXCEPTION -7;
// Cached Object,Field,Method ID's needed
jclass ctcp_inf;
jmethodID tcp_info_setdataID;
/*
* Class: org_it4y_jni_linuxutils
* Method: initlib
* Signature: ()I
*/
JNIEXPORT jint JNICALL Java_org_it4y_jni_linuxutils_initlib(JNIEnv *env, jclass this) {
fprintf(stderr,"libjnilinuxutils init...\n");
jclass ctcp_inf = (*env)->FindClass(env,"org/it4y/jni/libc$tcp_info");
if((*env)->ExceptionOccurred(env)) {
fprintf(stderr,"initlibError3");
return ERR_GET_METHOD_FAILED;
}
tcp_info_setdataID = (*env)->GetMethodID(env, ctcp_inf, "setdata","(BBBBBBBBIIIIIIIIIIIIIIIIIIIIIIII)V");
if((*env)->ExceptionOccurred(env)) {
fprintf(stderr,"initlibError4");
return ERR_GET_METHOD_FAILED;
}
fprintf(stderr,"libjnilinuxutils ok\n");
return OK;
}
/*
* This will create a ErrnoException based on returned errno
*
*/
jint throwErrnoExceptionError(JNIEnv *env, int error) {
fprintf(stderr,"libc.errnoexception: %d\n",error);
// Somehow preloading the jclass & jmethodId doesn work with this exception
// as this is exception, we should not see alot of them so it doesn't really matter if it takes some time.
jstring jmessage = (*env)->NewStringUTF(env,strerror(error));
if((*env)->ExceptionOccurred(env)) {
fprintf(stderr,"throwErrnoExceptionError1 %d",error);
return ERR_JNI_ERROR;
}
jclass errnoexception_class = (*env)->FindClass( env, "org/it4y/jni/libc$ErrnoException");
if((*env)->ExceptionOccurred(env)) {
fprintf(stderr,"throwErrnoExceptionError2 %d",error);
return ERR_FIND_CLASS_FAILED;
}
jmethodID errnoexception_ctorID = (*env)->GetMethodID(env, errnoexception_class, "<init>","(Ljava/lang/String;I)V");
if((*env)->ExceptionOccurred(env)) {
fprintf(stderr,"throwErrnoExceptionError3 %d",error);
return ERR_FIND_CLASS_FAILED;
}
jobject errnoexception_obj = (*env)->NewObject(env, errnoexception_class, errnoexception_ctorID,jmessage,error);
if((*env)->ExceptionOccurred(env)) {
fprintf(stderr,"throwErrnoExceptionError4 %d",error);
return ERR_FIND_CLASS_FAILED;
}
//yes it did ;-)
(*env)->Throw( env, errnoexception_obj );
return OK;
}
/*
* Class: org_it4y_jni_linuxutils
* Method: setbooleanSockOption
* Signature: (IIIB)I
*/
JNIEXPORT void JNICALL Java_org_it4y_jni_linuxutils_setbooleanSockOption(JNIEnv *env, jclass this, jint fd, jint level , jint option , jboolean x) {
int value=0;
if (x) { value = 1;}
//set socket boolean option
if (setsockopt(fd, level,option, &value, sizeof(value)) != 0) {
perror("setsockopt_boolean");
throwErrnoExceptionError(env,errno);
}
}
/*
* Class: org_it4y_jni_linuxutils
* Method: setuint16SockOption
* Signature: (IIII)I
*/
JNIEXPORT void JNICALL Java_org_it4y_jni_linuxutils_setintSockOption(JNIEnv *env, jclass this, jint fd, jint level, jint option, jint x) {
int value=x;
fprintf(stderr,"setuint16SockOption %d %d %d %d\n",fd,level,option,value);
//set socket int option
if (setsockopt(fd, level,option, &value, sizeof(value)) != 0) {
perror("setsockopt_uint16");
throwErrnoExceptionError(env,errno);
}
}
/*
* Class: org_it4y_jni_linuxutils
* Method: setstringSockOption
* Signature: (IIILjava/lang/String;)I
*/
JNIEXPORT void JNICALL Java_org_it4y_jni_linuxutils_setstringSockOption(JNIEnv *env, jclass this, jint fd, jint level,jint option , jstring s) {
const char *value = (*env)->GetStringUTFChars(env, s, 0);
// use your string
//fprintf(stderr,"setStringSockOption %d %d %d [%s]\n",fd,level,option,value);
//set socket int option
if (setsockopt(fd, level,option, value, sizeof(value)+1) != 0) {
perror("setsockopt_string");
throwErrnoExceptionError(env,errno);
}
//must always be done !!!
(*env)->ReleaseStringUTFChars(env, s, value);
}
/*
* Class: org_it4y_jni_linuxutils
* Method: getbooleanSockOption
* Signature: (III)B
*/
JNIEXPORT jboolean JNICALL Java_org_it4y_jni_linuxutils_getbooleanSockOption(JNIEnv *env, jclass this , jint fd, jint level , jint option) {
jboolean value=0;
socklen_t len=sizeof(value);
//get socket boolean option
if (getsockopt(fd, level,option, &value,&len) != 0) {
perror("getsockopt boolean");
throwErrnoExceptionError(env,errno);
return 0;
}
return value;
}
/*
* Class: org_it4y_jni_linuxutils
* Method: getuint16SockOption
* Signature: (III)I
*/
JNIEXPORT jint JNICALL Java_org_it4y_jni_linuxutils_getintSockOption(JNIEnv *env, jclass this, jint fd, jint level, jint option) {
int value=0;
socklen_t len=sizeof(value);
//get socket boolean option
if (getsockopt(fd, level,option, &value,&len) != 0) {
perror("getsockopt int");
throwErrnoExceptionError(env,errno);
return 0;
}
return value;
}
/*
* Class: org_it4y_jni_linuxutils
* Method: getstringSockOption
* Signature: (III)Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_org_it4y_jni_linuxutils_getstringSockOption (JNIEnv *env, jclass this, jint fd, jint level , jint option) {
//we should limit buffer size here so we stick to 255 for now
char value[255];
socklen_t len=sizeof(value)+1;
//get socket string option
if (getsockopt(fd,level,option, &value,&len) != 0) {
perror("getsockopt string");
throwErrnoExceptionError(env,errno);
return 0;
}
return (*env)->NewStringUTF(env,value);
}
/*
* Class: org_it4y_jni_linuxutils
* Method: getsockname
* Signature: (I)I
*/
JNIEXPORT jbyteArray JNICALL Java_org_it4y_jni_linuxutils__1getsockname(JNIEnv *env, jclass this, jint fd) {
struct sockaddr_storage orig_dst;
//struct sockaddr_in *sa4 = (struct sockaddr_in *)&orig_dst;
struct sockaddr_in6 *sa6 = (struct sockaddr_in6 *)&orig_dst;
socklen_t addrlen = sizeof(orig_dst);
memset(&orig_dst, 0, addrlen);
//get socket bound address/port
if(getsockname(fd, (struct sockaddr*) &orig_dst, &addrlen) < 0){
perror("getsockname: ");
throwErrnoExceptionError(env,errno);
return 0;
}
//IPV4 socket
if(orig_dst.ss_family == AF_INET) {
jbyteArray result;
result = (*env)->NewByteArray(env,sizeof(struct sockaddr_in));
//do stuff to raw bytes
jboolean isCopy;
jbyte* rawjBytes = (*env)->GetByteArrayElements(env, result, &isCopy);
memcpy(rawjBytes,&orig_dst,sizeof(struct sockaddr_in));
(*env)->ReleaseByteArrayElements(env, result, rawjBytes, 0);
return result;
}
//IPV6 socket , only if ipv4 is mapped in ipv6 for know
if(orig_dst.ss_family == AF_INET6 && IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr)) {
//Convert MAPPED IPV4 in IPV6 to IPV4
struct sockaddr_in ipv4;
//get last 4 bytes=ipv4 address
memcpy(&ipv4.sin_addr, &sa6->sin6_addr.s6_addr[12],sizeof(ipv4.sin_addr));
ipv4.sin_port=sa6->sin6_port;
ipv4.sin_family=AF_INET;
jbyteArray result;
result = (*env)->NewByteArray(env,sizeof(struct sockaddr_in));
//do stuff to raw bytes
jboolean isCopy;
jbyte* rawjBytes = (*env)->GetByteArrayElements(env, result, &isCopy);
memcpy(rawjBytes,&ipv4,sizeof(struct sockaddr_in));
(*env)->ReleaseByteArrayElements(env, result, rawjBytes, 0);
return result;
}
fprintf(stderr,"getsockname: unsupported sock_storage format IPv6!\n");
return NULL;
}
/*
* Class: org_it4y_jni_linuxutils
* Method: gettcpinfo
* Signature: (ILorg/it4y/jni/libc/tcp_info;)I
*/
JNIEXPORT jint JNICALL Java_org_it4y_jni_linuxutils_gettcpinfo (JNIEnv *env, jclass this, jint fd, jobject tcpInfo_Obj) {
struct tcp_info value;
socklen_t len = sizeof(value);
//get socket string option
if (getsockopt(fd,IPPROTO_TCP,TCP_INFO, &value,&len) != 0) {
perror("getsockopt tcp_info");
throwErrnoExceptionError(env,errno);
return 0;
}
//callback
if (len==104) {
(*env)->CallVoidMethod(env, tcpInfo_Obj,tcp_info_setdataID,
value.tcpi_state,
value.tcpi_ca_state,
value.tcpi_retransmits,
value.tcpi_probes,
value.tcpi_backoff,
value.tcpi_options,
value.tcpi_snd_wscale,
value.tcpi_rcv_wscale,
value.tcpi_rto,
value.tcpi_ato,
value.tcpi_snd_mss,
value.tcpi_rcv_mss,
value.tcpi_unacked,
value.tcpi_sacked,
value.tcpi_lost,
value.tcpi_retrans,
value.tcpi_fackets,
value.tcpi_last_data_sent,
value.tcpi_last_ack_sent,
value.tcpi_last_data_recv,
value.tcpi_last_ack_recv,
value.tcpi_pmtu,
value.tcpi_rcv_ssthresh,
value.tcpi_rtt,
value.tcpi_rttvar,
value.tcpi_snd_ssthresh,
value.tcpi_snd_cwnd,
value.tcpi_advmss,
value.tcpi_reordering,
value.tcpi_rcv_rtt,
value.tcpi_rcv_space,
value.tcpi_total_retrans
);
}
return len;
}
/*
* Class: org_it4y_jni_linuxutils
* Method: ioctl_SIOCGIFFLAGS
* Signature: (Ljava/lang/String;)I
*/
JNIEXPORT jshort JNICALL Java_org_it4y_jni_linuxutils_ioctl_1SIOCGIFFLAGS(JNIEnv *env, jclass this, jstring jdevice) {
const char *dev;
int sockfd;
struct ifreq ifr;
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd < 0) {
perror("ioctl_SIOCGIFFLAGS");
throwErrnoExceptionError(env,errno);
return 0;
}
memset(&ifr, 0, sizeof ifr);
/* get device name from java */
dev= (*env)->GetStringUTFChars(env,jdevice, 0);
memcpy(ifr.ifr_name, dev, IFNAMSIZ);
(*env)->ReleaseStringUTFChars(env, jdevice, dev);
if (ioctl(sockfd, SIOCGIFFLAGS, &ifr) < 0) {
perror("ioctl_SIOCGIFFLAGS: ");
throwErrnoExceptionError(env,errno);
return errno;
}
return ifr.ifr_flags;
}
/*
* Class: org_it4y_jni_linuxutils
* Method: ioctl_SIOCSIFFLAGS
* Signature: (Ljava/lang/String;I)I
*/
JNIEXPORT jint JNICALL Java_org_it4y_jni_linuxutils_ioctl_1SIOCSIFFLAGS(JNIEnv *env, jclass this, jstring jdevice, jshort flags) {
const char *dev;
int sockfd;
struct ifreq ifr;
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd < 0) {
perror("ioctl_1SIOCSIFFLAGS");
throwErrnoExceptionError(env,errno);
return 0;
}
memset(&ifr, 0, sizeof ifr);
/* get device name from java */
dev= (*env)->GetStringUTFChars(env,jdevice, 0);
memcpy(ifr.ifr_name, dev, IFNAMSIZ);
(*env)->ReleaseStringUTFChars(env, jdevice, dev);
//set flags
ifr.ifr_flags=flags;
if (ioctl(sockfd, SIOCGIFFLAGS, &ifr) < 0) {
perror("ioctl_SIOCGIFFLAGS: ");
throwErrnoExceptionError(env,errno);
return errno;
}
return OK;
}
/*
* Class: org_it4y_jni_linuxutils
* Method: ioctl_ifupdown
* Signature: (Ljava/lang/String;Z)I
*/
JNIEXPORT jint JNICALL Java_org_it4y_jni_linuxutils_ioctl_1ifupdown(JNIEnv *env, jclass this, jstring jdevice, jboolean state) {
const char *dev;
int sockfd;
struct ifreq ifr;
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd < 0) {
perror("socket ifupdown");
throwErrnoExceptionError(env,errno);
return 0;
}
memset(&ifr, 0, sizeof ifr);
/* get device name from java */
dev= (*env)->GetStringUTFChars(env,jdevice, 0);
memcpy(ifr.ifr_name, dev, IFNAMSIZ);
(*env)->ReleaseStringUTFChars(env, jdevice, dev);
/* get current interface state */
if (ioctl(sockfd, SIOCGIFFLAGS, &ifr) < 0) {
perror("SIOCGIFFLAGS: ");
throwErrnoExceptionError(env,errno);
return errno;
}
/* set state up/down */
if (state) {
ifr.ifr_flags |= IFF_UP;
} else {
ifr.ifr_flags &= ~IFF_UP;
}
if(ioctl(sockfd, SIOCSIFFLAGS, &ifr) < 0) {
perror("SIOCSIFFLAGS: ");
throwErrnoExceptionError(env,errno);
return errno;
}
return OK;
}
/*
* Class: org_it4y_jni_linuxutils
* Method: _ioctl_SIOCGIFADDR
* Signature: (Ljava/lang/String;)[B
*/
JNIEXPORT jbyteArray JNICALL Java_org_it4y_jni_linuxutils__1ioctl_1SIOCGIFADDR(JNIEnv *env, jclass this, jstring jdevice) {
const char *dev;
int sockfd;
struct ifreq ifr;
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd < 0) {
perror("socket ioctl_1SIOCGIFADDRipv4");
throwErrnoExceptionError(env,errno);
return NULL;
}
memset(&ifr, 0, sizeof ifr);
/* get device name from java */
dev= (*env)->GetStringUTFChars(env,jdevice, 0);
memcpy(ifr.ifr_name, dev, IFNAMSIZ);
(*env)->ReleaseStringUTFChars(env, jdevice, dev);
/* get current interface state */
if (ioctl(sockfd, SIOCGIFADDR, &ifr) < 0) {
perror("SIOCGIFADDR: ");
throwErrnoExceptionError(env,errno);
return NULL;
}
jbyteArray result;
result = (*env)->NewByteArray(env,sizeof(struct sockaddr_in));
struct sockaddr_in* ipaddr = (struct sockaddr_in*)&ifr.ifr_addr;
//fprintf(stderr,"IP address: %s\n",inet_ntoa(ipaddr->sin_addr));
//do stuff to raw bytes
jboolean isCopy;
jbyte* rawjBytes = (*env)->GetByteArrayElements(env, result, &isCopy);
memcpy(rawjBytes, (void *)ipaddr,sizeof(struct sockaddr_in));
(*env)->ReleaseByteArrayElements(env, result, rawjBytes, 0);
return result;
}
/*
* Class: org_it4y_jni_linuxutils
* Method: _ioctl_SIOCSIFADDR
* Signature: (Ljava/lang/String;[B)I
*/
JNIEXPORT jint JNICALL Java_org_it4y_jni_linuxutils__1ioctl_1SIOCSIFADDR(JNIEnv *env, jclass this, jstring jdevice, jbyteArray sockaddr) {
const char *dev;
int sockfd;
struct ifreq ifr;
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd < 0) {
perror("socket ioctl_1SIOCGIFADDRipv4");
throwErrnoExceptionError(env,errno);
return errno;
}
memset(&ifr, 0, sizeof ifr);
/* get device name from java */
dev= (*env)->GetStringUTFChars(env,jdevice, 0);
memcpy(ifr.ifr_name, dev, IFNAMSIZ);
(*env)->ReleaseStringUTFChars(env, jdevice, dev);
struct sockaddr_in* ipaddr = (struct sockaddr_in*)&ifr.ifr_addr;
//do stuff to raw bytes
jboolean isCopy;
jbyte* rawjBytes = (*env)->GetByteArrayElements(env, sockaddr, &isCopy);
memcpy((void *)ipaddr, rawjBytes, sizeof(struct sockaddr_in));
(*env)->ReleaseByteArrayElements(env, sockaddr, rawjBytes, 0);
//fprintf(stderr,"IP address: %s\n",inet_ntoa(ipaddr->sin_addr));
if (ioctl(sockfd, SIOCSIFADDR, &ifr) < 0) {
perror("SIOCSIFADDR: ");
throwErrnoExceptionError(env,errno);
return errno;
}
return OK;
}
/*
* Class: org_it4y_jni_linuxutils
* Method: _ioctl_SIOCGIFNETMASK
* Signature: (Ljava/lang/String;)[B
*/
JNIEXPORT jbyteArray JNICALL Java_org_it4y_jni_linuxutils__1ioctl_1SIOCGIFNETMASK(JNIEnv *env, jclass this, jstring jdevice) {
const char *dev;
int sockfd;
struct ifreq ifr;
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd < 0) {
perror("socket ioctl_1SIOCGIFADDRipv4");
throwErrnoExceptionError(env,errno);
return NULL;
}
memset(&ifr, 0, sizeof ifr);
/* get device name from java */
dev= (*env)->GetStringUTFChars(env,jdevice, 0);
memcpy(ifr.ifr_name, dev, IFNAMSIZ);
(*env)->ReleaseStringUTFChars(env, jdevice, dev);
/* get current interface state */
if (ioctl(sockfd, SIOCGIFNETMASK, &ifr) < 0) {
perror("SIOCGIFNETMASK: ");
throwErrnoExceptionError(env,errno);
return NULL;
}
jbyteArray result;
result = (*env)->NewByteArray(env,sizeof(struct sockaddr_in));
struct sockaddr_in* ipaddr = (struct sockaddr_in*)&ifr.ifr_addr;
//fprintf(stderr,"IP address: %s\n",inet_ntoa(ipaddr->sin_addr));
//do stuff to raw bytes
jboolean isCopy;
jbyte* rawjBytes = (*env)->GetByteArrayElements(env, result, &isCopy);
memcpy(rawjBytes, (void *)ipaddr,sizeof(struct sockaddr_in));
(*env)->ReleaseByteArrayElements(env, result, rawjBytes, 0);
return result;
}
/*
* Class: org_it4y_jni_linuxutils
* Method: _ioctl_SIOCSIFNETMASK
* Signature: (Ljava/lang/String;[B)I
*/
JNIEXPORT jint JNICALL Java_org_it4y_jni_linuxutils__1ioctl_1SIOCSIFNETMASK(JNIEnv *env, jclass this, jstring jdevice, jbyteArray ipv4) {
const char *dev;
int sockfd;
struct ifreq ifr;
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd < 0) {
perror("socket ioctl_1SIOCGIFADDRipv4");
throwErrnoExceptionError(env,errno);
return errno;
}
memset(&ifr, 0, sizeof ifr);
/* get device name from java */
dev= (*env)->GetStringUTFChars(env,jdevice, 0);
memcpy(ifr.ifr_name, dev, IFNAMSIZ);
(*env)->ReleaseStringUTFChars(env, jdevice, dev);
struct sockaddr_in* ipaddr = (struct sockaddr_in*)&ifr.ifr_addr;
//do stuff to raw bytes
jboolean isCopy;
jbyte* rawjBytes = (*env)->GetByteArrayElements(env, ipv4, &isCopy);
memcpy((void *)ipaddr, rawjBytes, sizeof(struct sockaddr_in));
(*env)->ReleaseByteArrayElements(env, ipv4, rawjBytes, 0);
//fprintf(stderr,"IP address: %s\n",inet_ntoa(ipaddr->sin_addr));
if (ioctl(sockfd, SIOCSIFNETMASK, &ifr) < 0) {
perror("SIOCSIFNETMASK: ");
throwErrnoExceptionError(env,errno);
return errno;
}
return OK;
}
/*
* Class: org_it4y_jni_linuxutils
* Method: ioctl_SIOCGIFMTU
* Signature: (Ljava/lang/String;)I
*/
JNIEXPORT jint JNICALL Java_org_it4y_jni_linuxutils_ioctl_1SIOCGIFMTU(JNIEnv *env, jclass this, jstring jdevice) {
const char *dev;
int sockfd;
struct ifreq ifr;
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd < 0) {
perror("socket ioctl_1SIOCGIFMTU");
throwErrnoExceptionError(env,errno);
return 0;
}
memset(&ifr, 0, sizeof ifr);
/* get device name from java */
dev= (*env)->GetStringUTFChars(env,jdevice, 0);
memcpy(ifr.ifr_name, dev, IFNAMSIZ);
(*env)->ReleaseStringUTFChars(env, jdevice, dev);
/* get current interface state */
if (ioctl(sockfd, SIOCGIFMTU, &ifr) < 0) {
perror("SIOCGIFMTU: ");
throwErrnoExceptionError(env,errno);
return 0;
}
return ifr.ifr_metric;
}
/*
* Class: org_it4y_jni_linuxutils
* Method: ioctl_SIOCSIFMTU
* Signature: (Ljava/lang/String;I)I
*/
JNIEXPORT jint JNICALL Java_org_it4y_jni_linuxutils_ioctl_1SIOCSIFMTU(JNIEnv *env, jclass this, jstring jdevice, jint mtu) {
const char *dev;
int sockfd;
struct ifreq ifr;
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd < 0) {
perror("socket ioctl_1SIOCSIFMTU");
throwErrnoExceptionError(env,errno);
return 0;
}
memset(&ifr, 0, sizeof ifr);
/* get device name from java */
dev= (*env)->GetStringUTFChars(env,jdevice, 0);
memcpy(ifr.ifr_name, dev, IFNAMSIZ);
(*env)->ReleaseStringUTFChars(env, jdevice, dev);
ifr.ifr_mtu=mtu;
/* get current interface state */
if (ioctl(sockfd, SIOCSIFMTU, &ifr) < 0) {
perror("SIOCSIFMTU: ");
throwErrnoExceptionError(env,errno);
return 0;
}
return OK;
}
/*
* Class: org_it4y_jni_linuxutils
* Method: clock_gettime
* Signature: (I)[J
*/
JNIEXPORT jlongArray JNICALL Java_org_it4y_jni_linuxutils_clock_1gettime(JNIEnv *env , jclass this, jint clockid) {
struct timespec now;
if(clock_gettime(clockid, &now)<0) {
perror("clock_gettime: ");
throwErrnoExceptionError(env,errno);
return 0;
}
//convert to long[2] array to return timespec
jlongArray x = (*env)->NewLongArray(env,2);
if (x != NULL) {
jlong *xr = (*env)->GetLongArrayElements(env,x,0);
xr[0]=now.tv_sec;
xr[1]=now.tv_nsec;
(*env)->ReleaseLongArrayElements(env,x,xr,0);
}
return x;
}
JNIEXPORT jlong JNICALL Java_org_it4y_jni_linuxutils_usecTime(JNIEnv *env, jclass this) {
struct timespec now;
if(clock_gettime(CLOCK_BOOTTIME, &now)<0) {
perror("clock_gettime: ");
throwErrnoExceptionError(env,errno);
return 0;
}
return (jlong)(now.tv_sec*1000000+(now.tv_nsec/1000));
}
/*
* Class: org_it4y_jni_linuxutils
* Method: usecTime
* Signature: (I)J
*/
JNIEXPORT jlong JNICALL Java_org_it4y_jni_linuxutils_usecTime__I (JNIEnv *env , jclass this , jint clockId) {
struct timespec now;
if(clock_gettime(clockId, &now)<0) {
perror("clock_gettime: ");
throwErrnoExceptionError(env,errno);
return 0;
}
return (jlong)(now.tv_sec*1000000+(now.tv_nsec/1000));
}
JNIEXPORT jlong JNICALL Java_org_it4y_jni_linuxutils_clock_1getres(JNIEnv *env, jclass this , jint clockid) {
struct timespec now;
if(clock_getres(clockid, &now)<0) {
perror("clock_getres: ");
throwErrnoExceptionError(env,errno);
return 0;
}
return (jlong)(now.tv_nsec);
}
| 2.078125 | 2 |
2024-11-18T22:24:28.012401+00:00 | 2019-11-25T07:30:37 | cf307adf577481646a1080821420faf7979de1b0 | {
"blob_id": "cf307adf577481646a1080821420faf7979de1b0",
"branch_name": "refs/heads/master",
"committer_date": "2019-11-25T17:22:24",
"content_id": "720ec236a88498a8f74032ce8ab300cf5e84c313",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "5a583c2289c8edcb6f3b173f8783d1833737e994",
"extension": "c",
"filename": "script.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": 14652,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/script.c",
"provenance": "stackv2-0115.json.gz:87235",
"repo_name": "mattludwigs/rootfs_mounter",
"revision_date": "2019-11-25T07:30:37",
"revision_id": "bdb1779b38177b4921b902301850af3571c2f016",
"snapshot_id": "df2f66c43579b0403063d991b1d151789c37f649",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/mattludwigs/rootfs_mounter/bdb1779b38177b4921b902301850af3571c2f016/src/script.c",
"visit_date": "2020-09-17T06:53:46.267966"
} | stackv2 | #include "script.h"
#include "util.h"
#include "parser.tab.h"
#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#define HEAP_SIZE 16536
static char *heap = NULL;
static int heap_index = 0;
static struct term *variables = NULL;
/**
* This can only be called between parsing statements
* since we don't track references in bison.
*/
void term_gc_heap()
{
struct term *old_variables;
char *old_heap;
if (!heap) {
old_variables = NULL;
old_heap = NULL;
} else {
old_heap = heap;
old_variables = variables;
}
heap = malloc(HEAP_SIZE);
memset(heap, 0, HEAP_SIZE);
heap_index = 0;
variables = NULL;
while (old_variables) {
set_variable(old_variables->var.name, term_dupe(old_variables->var.value));
old_variables = old_variables->next;
}
if (old_heap)
free(old_heap);
}
static void *alloc_heap(size_t num_bytes)
{
if (heap_index + num_bytes > HEAP_SIZE)
fatal("Program too large. Out of heap");
void *addr = &heap[heap_index];
heap_index = (heap_index + num_bytes + 7) & ~7;
return addr;
}
static char *alloc_string(const char *str)
{
size_t len = strlen(str) + 1;
char *result = alloc_heap(len);
memcpy(result, str, len);
return result;
}
static char *alloc_qstring(const char *str)
{
// Skip first and last quote
str++;
size_t len = strlen(str);
char *result = alloc_heap(len);
memcpy(result, str, len);
result[len - 1] = '\0';
return result;
}
struct term *term_new_number(int value)
{
struct term *rv = alloc_heap(sizeof(struct term));
rv->kind = term_number;
rv->number = value;
return rv;
}
struct term *term_new_string(const char *value)
{
struct term *rv = alloc_heap(sizeof(struct term));
rv->kind = term_string;
rv->string = alloc_string(value);
return rv;
}
struct term *term_new_qstring(const char *value)
{
struct term *rv = alloc_heap(sizeof(struct term));
rv->kind = term_string;
rv->string = alloc_qstring(value);
return rv;
}
struct term *term_new_boolean(bool value)
{
struct term *rv = alloc_heap(sizeof(struct term));
rv->kind = term_boolean;
rv->boolean = value;
return rv;
}
struct term *term_new_identifier(const char *value)
{
struct term *rv = alloc_heap(sizeof(struct term));
rv->kind = term_identifier;
rv->identifier = alloc_string(value);
return rv;
}
struct term *term_reverse(struct term *rv)
{
struct term *prev = NULL;
while (rv) {
struct term *next = rv->next;
rv->next = prev;
prev = rv;
rv = next;
}
return prev;
}
struct term *term_new_fun(const char *name, struct term *parameters)
{
int arity = 0;
struct term *p = parameters;
while (p) {
arity++;
p = p->next;
}
fun_handler fun = lookup_function(name, arity);
if (!fun)
return NULL;
struct term *rv = alloc_heap(sizeof(struct term));
rv->kind = term_fun;
rv->fun.fun = fun;
rv->fun.parameters = parameters;
return rv;
}
struct term *term_dupe(const struct term *rv)
{
switch (rv->kind) {
case term_identifier:
return term_new_identifier(rv->identifier);
case term_string:
return term_new_string(rv->string);
case term_number:
return term_new_number(rv->number);
case term_boolean:
return term_new_boolean(rv->boolean);
default:
// Not supported
return NULL;
}
}
void inspect(const struct term *rv)
{
switch (rv->kind) {
case term_identifier:
printf("%s", rv->identifier);
break;
case term_string:
printf("\"%s\"", rv->string);
break;
case term_number:
printf("%d", rv->number);
break;
case term_boolean:
printf("%s", rv->boolean ? "true" : "false");
break;
case term_fun: {
const struct term *p = rv->fun.parameters;
const struct function_info *fun_info = function_info_by_fun(rv->fun.fun);
printf("%s(", fun_info->name);
for (int i = 0; i < fun_info->arity; i++) {
inspect(p);
p = p->next;
if (p)
printf(",");
}
printf(")");
break;
}
case term_variable:
printf("%s=", rv->var.name);
inspect(rv->var.value);
break;
default:
printf("Unknown");
break;
}
}
static const struct term *run_function(const struct term *rv)
{
assert(rv->kind == term_fun);
if (rv->fun.fun)
return rv->fun.fun(rv->fun.parameters);
else
return term_new_boolean(false);
}
void run_functions(const struct term *rv)
{
while (rv) {
run_function(rv);
rv = rv->next;
}
}
const struct term *term_resolve(const struct term *rv)
{
switch (rv->kind) {
case term_identifier:
return term_resolve(get_variable(rv->identifier));
case term_fun:
return run_function(rv);
default:
return rv;
}
}
bool term_to_boolean(const struct term *rv)
{
rv = term_resolve(rv);
switch (rv->kind) {
case term_string:
// empty strings and "false" are false. Everything else is true.
return strlen(rv->string) > 0 && strcasecmp(rv->string, "false") != 0;
case term_number:
return rv->number != 0;
case term_boolean:
return rv->boolean;
default:
return false;
}
}
int term_to_number(const struct term *rv)
{
rv = term_resolve(rv);
switch (rv->kind) {
case term_string:
return strtoull(rv->string, NULL, 0);
case term_number:
return rv->number;
case term_boolean:
return rv->boolean ? 1 : 0;
default:
return 0;
}
}
const struct term *term_to_string(const struct term *rv)
{
rv = term_resolve(rv);
switch (rv->kind) {
case term_identifier:
return term_to_string(get_variable(rv->identifier));
case term_string:
return rv;
case term_number:
{
char buffer[32];
sprintf(buffer, "%d", rv->number);
return term_new_string(buffer);
}
case term_boolean:
return term_new_string(rv->boolean ? "true" : "false");
default:
return term_new_string("");
}
}
static struct term *get_variable_impl(const char *name)
{
for (struct term *v = variables; v; v = v->next) {
if (strcmp(v->var.name, name) == 0)
return v;
}
return NULL;
}
const struct term *get_variable(const char *name)
{
struct term *var = get_variable_impl(name);
if (var)
return var->var.value;
else
return term_new_string("");
}
const char *get_variable_as_string(const char *name)
{
struct term *var = get_variable_impl(name);
if (var)
return term_to_string(var->var.value)->string;
else
return "";
}
bool get_variable_as_boolean(const char *name)
{
struct term *var = get_variable_impl(name);
if (var)
return term_to_boolean(var->var.value);
else
return false;
}
int get_variable_as_number(const char *name)
{
struct term *var = get_variable_impl(name);
if (var)
return term_to_number(var->var.value);
else
return 0;
}
void set_variable(const char *name, const struct term *value)
{
struct term *var = get_variable_impl(name);
if (var) {
var->var.value = value;
} else {
struct term *rv = alloc_heap(sizeof(struct term));
rv->kind = term_variable;
rv->var.name = alloc_string(name);
rv->var.value = value;
rv->next = variables;
variables = rv;
}
}
void set_string_variable(const char *name, const char *value)
{
set_variable(name, term_new_string(value));
}
void set_boolean_variable(const char *name, bool value)
{
set_variable(name, term_new_boolean(value));
}
void set_number_variable(const char *name, int value)
{
set_variable(name, term_new_number(value));
}
static const struct term *function_assign(const struct term *parameters)
{
const struct term *var = parameters;
const struct term *value = term_resolve(parameters->next);
set_variable(var->identifier, value);
return value;
}
static const struct term *function_add(const struct term *parameters)
{
int a = term_to_number(parameters);
int b = term_to_number(parameters->next);
return term_new_number(a + b);
}
static const struct term *function_subtract(const struct term *parameters)
{
int a = term_to_number(parameters);
int b = term_to_number(parameters->next);
return term_new_number(a - b);
}
static const struct term *function_info(const struct term *parameters)
{
while (parameters) {
const struct term *str = term_to_string(parameters);
printf("%s\n", str->string);
parameters = parameters->next;
}
return NULL;
}
static const struct term *function_vars(const struct term *parameters)
{
(void)parameters;
for (const struct term *var = variables; var; var = var->next) {
inspect(var);
printf("\n");
}
return NULL;
}
static const struct term *function_env(const struct term *parameters)
{
(void)parameters;
for (const struct uboot_name_value *var = working_uboot_env.vars; var; var = var->next) {
printf("%s=%s", var->name, var->value);
}
return NULL;
}
static const struct term *function_loadenv(const struct term *parameters)
{
(void)parameters;
const char *devpath = get_variable_as_string("uboot_env.path");
int block = get_variable_as_number("uboot_env.start");
int block_count = get_variable_as_number("uboot_env.count");
working_uboot_env.env_size = block_count * 512;
int fd = open(devpath, O_RDONLY);
if (fd < 0) {
info("Could not open '%s'", devpath);
return NULL;
}
if (lseek(fd, block * 512, SEEK_SET) < 0) {
info("Could not seek to block %d (byte offset %d) in '%s'", block, block * 512, devpath);
close(fd);
return NULL;
}
char *buffer = malloc(working_uboot_env.env_size);
ssize_t amount_read = read(fd, buffer, working_uboot_env.env_size);
close(fd);
if (amount_read != (ssize_t) working_uboot_env.env_size) {
free(buffer);
info("Could not read %d blocks (%d bytes) from '%s'", block_count, working_uboot_env.env_size, devpath);
return NULL;
}
set_boolean_variable("uboot_env.loaded", false);
set_boolean_variable("uboot_env.modified", false);
if (uboot_env_read(&working_uboot_env, buffer) < 0) {
free(buffer);
return NULL;
}
free(buffer);
set_boolean_variable("uboot_env.loaded", true);
return NULL;
}
static const struct term *function_setenv(const struct term *parameters)
{
const char *name = term_to_string(parameters)->string;
const char *value = term_to_string(parameters->next)->string;
if (uboot_env_setenv(&working_uboot_env, name, value) < 0) {
info("Error setting uboot environment variable '%s' to '%s'", name, value);
} else {
set_boolean_variable("uboot_env.modified", true);
}
return parameters->next;
}
static const struct term *function_getenv(const struct term *parameters)
{
const char *name = term_to_string(parameters)->string;
char *value;
if (uboot_env_getenv(&working_uboot_env, name, &value) < 0) {
return term_new_string("");
} else {
struct term *ret = term_new_string(value);
free(value);
return ret;
}
}
static const struct term *function_saveenv(const struct term *parameters)
{
(void)parameters;
const char *devpath = get_variable_as_string("uboot_env.path");
int block = get_variable_as_number("uboot_env.start");
int block_count = get_variable_as_number("uboot_env.count");
working_uboot_env.env_size = block_count * 512;
int fd = open(devpath, O_WRONLY);
if (fd < 0) {
info("Could not open '%s'", devpath);
return NULL;
}
if (lseek(fd, block * 512, SEEK_SET) < 0) {
info("Could not seek to block %d (byte offset %d) in '%s'", block, block * 512, devpath);
close(fd);
return NULL;
}
char *buffer = malloc(working_uboot_env.env_size);
if (uboot_env_write(&working_uboot_env, buffer) < 0) {
free(buffer);
return NULL;
}
ssize_t amount_written = write(fd, buffer, working_uboot_env.env_size);
close(fd);
free(buffer);
if (amount_written != (ssize_t) working_uboot_env.env_size) {
info("Could not write %d blocks (%d bytes) from '%s'", block_count, working_uboot_env.env_size, devpath);
return NULL;
}
set_boolean_variable("uboot_env.modified", false);
return NULL;
}
static const struct term *function_help(const struct term *parameters);
// Function lookup table
static struct function_info function_table[] = {
{"=", 2, function_assign},
{"+", 2, function_add},
{"-", 2, function_subtract},
{"info", 0, function_info},
{"help", 0, function_help},
{"vars", 0, function_vars},
{"env", 0, function_env},
{"loadenv", 0, function_loadenv},
{"setenv", 2, function_setenv},
{"getenv", 1, function_getenv},
{"saveenv", 0, function_saveenv},
{NULL, 0, NULL}
};
fun_handler lookup_function(const char *name, int arity)
{
struct function_info *entry = function_table;
while (entry->name) {
if (strcmp(entry->name, name) == 0 && arity >= entry->arity)
return entry->handler;
entry++;
}
return NULL;
}
const struct function_info *function_info_by_fun(fun_handler fun)
{
struct function_info *entry = function_table;
while (entry->handler && entry->handler != fun)
entry++;
return entry;
}
const struct term *function_help(const struct term *parameters)
{
(void)parameters;
struct function_info *entry = function_table;
while (entry->handler) {
printf("%s/%d\n", entry->name, entry->arity);
entry++;
}
return NULL;
}
int lexer_set_input(char *input);
int lexer_set_file(const char *path);
int yyget_lineno(void);
int yyparse(void);
int eval_string(char *input)
{
term_gc_heap();
lexer_set_input(input);
return yyparse();
}
int eval_file(const char *path)
{
term_gc_heap();
if (lexer_set_file(path) < 0)
return -1;
return yyparse();
}
int yyerror(char const *msg)
{
printf("Error on line %d: %s\n", yyget_lineno(), msg);
return 0;
}
| 2.640625 | 3 |
2024-11-18T22:25:09.483615+00:00 | 2022-03-14T09:49:15 | 653ea0ca9bb4556371f0ecdd222aad135afda427 | {
"blob_id": "653ea0ca9bb4556371f0ecdd222aad135afda427",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-31T09:50:00",
"content_id": "7b203884c4e820e40f04226e4610a361a4c4aa1b",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "e1cddfd754d952134e72dfd03522c5ea4fb6008e",
"extension": "c",
"filename": "vpp_fateshare_monitor.c",
"fork_events_count": 630,
"gha_created_at": "2017-07-07T16:29:40",
"gha_event_created_at": "2023-06-21T05:39:17",
"gha_language": "C",
"gha_license_id": "Apache-2.0",
"github_id": 96556718,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5130,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/plugins/fateshare/vpp_fateshare_monitor.c",
"provenance": "stackv2-0115.json.gz:108516",
"repo_name": "FDio/vpp",
"revision_date": "2022-03-14T09:49:15",
"revision_id": "f234b0d4626d7e686422cc9dfd25958584f4931e",
"snapshot_id": "0ad30fa1bec2975ffa6b66b45c9f4f32163123b6",
"src_encoding": "UTF-8",
"star_events_count": 1048,
"url": "https://raw.githubusercontent.com/FDio/vpp/f234b0d4626d7e686422cc9dfd25958584f4931e/src/plugins/fateshare/vpp_fateshare_monitor.c",
"visit_date": "2023-08-31T16:09:04.068646"
} | stackv2 | #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/prctl.h> // prctl(), PR_SET_PDEATHSIG
#include <sys/stat.h>
#include <fcntl.h>
#include <limits.h>
typedef struct
{
pid_t pid;
char *cmd;
} child_record_t;
int n_children = 0;
child_record_t *children = NULL;
static void
child_handler (int sig)
{
pid_t pid;
int status;
while ((pid = waitpid (-1, &status, WNOHANG)) > 0)
{
int i;
printf ("fateshare: pid %d quit with status %d\n", pid, status);
for (i = 0; i < n_children; i++)
{
if (children[i].pid == pid)
{
children[i].pid = 0;
}
}
}
}
static void
term_handler (int sig)
{
int i;
printf ("fateshare: terminating!\n");
for (i = 0; i < n_children; i++)
{
kill (-children[i].pid, SIGTERM);
}
exit (0);
}
static void
hup_handler (int sig)
{
int i;
printf ("fateshare: terminating all the child processes!\n");
for (i = 0; i < n_children; i++)
{
kill (-children[i].pid, SIGTERM);
}
}
pid_t
launch_command (char *scmd, char *logname_base)
{
pid_t ppid_before_fork = getpid ();
pid_t cpid = fork ();
if (cpid == -1)
{
perror ("fork");
sleep (1);
return 0;
}
if (cpid)
{
/* parent */
return cpid;
}
/* child */
int r = prctl (PR_SET_PDEATHSIG, SIGTERM);
if (r == -1)
{
perror ("prctl");
sleep (5);
exit (1);
}
if (getppid () != ppid_before_fork)
{
sleep (5);
exit (1);
}
int r1 = setpgid (getpid (), 0);
if (r1 != 0)
{
perror ("setpgid error");
sleep (5);
exit (1);
}
int fd = open ("/dev/null", O_RDONLY);
if (fd < 0)
{
sleep (5);
exit (1);
}
while (fd >= 0)
{
close (fd);
fd--;
}
fd = open ("/dev/null", O_RDONLY);
if (fd < 0)
{
sleep (5);
exit (1);
}
dup2 (fd, 0);
char logname_stdout[PATH_MAX];
char logname_stderr[PATH_MAX];
snprintf (logname_stdout, PATH_MAX - 1, "%s-stdout.txt", logname_base);
snprintf (logname_stderr, PATH_MAX - 1, "%s-stderr.txt", logname_base);
printf ("LOG STDOUT %s: %s\n", scmd, logname_stdout);
printf ("LOG STDERR %s: %s\n", scmd, logname_stderr);
fd = open ((char *) logname_stdout, O_APPEND | O_RDWR | O_CREAT, 0777);
if (fd < 0)
{
sleep (5);
exit (1);
}
dup2 (fd, 1);
fd = open ((char *) logname_stderr, O_APPEND | O_RDWR | O_CREAT, 0777);
if (fd < 0)
{
sleep (5);
exit (1);
}
dup2 (fd, 2);
char *argv[] = { (char *) scmd, 0 };
int res = execv (argv[0], argv);
if (res != 0)
{
perror ("execve");
}
sleep (10);
exit (42);
}
int
main (int argc, char **argv)
{
pid_t ppid = getppid ();
int i = 0;
if (argc < 3)
{
printf ("usage: %s <parent_pid> <logfile-basename>\n", argv[0]);
exit (1);
}
char *errptr = 0;
pid_t parent_pid = strtoll (argv[1], &errptr, 10);
char *logname_base = argv[2];
printf ("DEBUG: pid %d starting for parent pid %d\n", getpid (), ppid);
printf ("DEBUG: parent pid: %d\n", parent_pid);
printf ("DEBUG: base log name: %s\n", logname_base);
if (*errptr)
{
printf ("%s is not a valid parent pid\n", errptr);
exit (2);
}
int r = prctl (PR_SET_PDEATHSIG, SIGTERM);
if (r == -1)
{
perror (0);
exit (1);
}
/* Establish handler. */
struct sigaction sa;
sigemptyset (&sa.sa_mask);
sa.sa_flags = 0;
sa.sa_handler = child_handler;
sigaction (SIGCHLD, &sa, NULL);
sigemptyset (&sa.sa_mask);
sa.sa_flags = 0;
sa.sa_handler = term_handler;
sigaction (SIGTERM, &sa, NULL);
sigemptyset (&sa.sa_mask);
sa.sa_flags = 0;
sa.sa_handler = hup_handler;
sigaction (SIGHUP, &sa, NULL);
if (getppid () != parent_pid)
{
printf ("parent process unexpectedly finished\n");
exit (3);
}
argc -= 3; /* skip over argv0, ppid, and log base */
argv += 3;
n_children = argc;
printf ("DEBUG: total %d children\n", n_children);
children = calloc (n_children, sizeof (children[0]));
for (i = 0; i < n_children; i++)
{
/* argv persists, so we can just use that pointer */
children[i].cmd = argv[i];
children[i].pid = launch_command (children[i].cmd, logname_base);
printf ("DEBUG: child %d (%s): initial launch pid %d\n", i,
children[i].cmd, children[i].pid);
}
while (1)
{
sleep (1);
pid_t curr_ppid = getppid ();
printf ("pid: %d, current ppid %d, original ppid %d\n", getpid (),
curr_ppid, ppid);
if (curr_ppid != ppid)
{
printf ("current ppid %d != original ppid %d - force quit\n",
curr_ppid, ppid);
fflush (stdout);
exit (1);
}
int restarted = 0;
for (i = 0; i < n_children; i++)
{
if (children[i].pid == 0)
{
printf ("child %s exited, restarting\n", children[i].cmd);
restarted = 1;
children[i].pid = launch_command (children[i].cmd, logname_base);
}
}
if (restarted)
{
sleep (1);
}
fflush (stdout);
}
}
| 2.609375 | 3 |
2024-11-18T22:25:09.855583+00:00 | 2020-12-01T22:28:57 | 1c8b69f1e820b8ba51273fd052d84f69513bfbab | {
"blob_id": "1c8b69f1e820b8ba51273fd052d84f69513bfbab",
"branch_name": "refs/heads/master",
"committer_date": "2020-12-01T22:28:57",
"content_id": "e60ba5430eeecb19a4bdacf2f09503377e8055ba",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "90b25a14bd3f65fc85cf890b5ceb984cb0a472a6",
"extension": "c",
"filename": "verbose.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 391334767,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2186,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/verbose.c",
"provenance": "stackv2-0115.json.gz:109035",
"repo_name": "Farshid-Monhaseri/app-framework-main",
"revision_date": "2020-12-01T22:28:57",
"revision_id": "3ea6f4a404d2486ef1c5da55f1cd0d98c594f157",
"snapshot_id": "cb2c96c55c1567e7c2cffb7f4fc15fce5c194166",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Farshid-Monhaseri/app-framework-main/3ea6f4a404d2486ef1c5da55f1cd0d98c594f157/src/verbose.c",
"visit_date": "2023-07-03T13:52:58.102067"
} | stackv2 | /*
Copyright (C) 2015-2020 "IoT.bzh"
author: José Bollo <jose.bollo@iot.bzh>
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 <stdio.h>
#include <stdarg.h>
#include "verbose.h"
int verbosity = 1;
#define LEVEL(x) ((x) < 0 ? 0 : (x) > 7 ? 7 : (x))
#if defined(VERBOSE_WITH_SYSLOG)
#include <syslog.h>
void vverbose(int level, const char *file, int line, const char *fmt, va_list args)
{
char *p;
if (file == NULL || vasprintf(&p, fmt, args) < 0)
vsyslog(level, fmt, args);
else {
syslog(LEVEL(level), "%s [%s:%d]", p, file, line);
free(p);
}
}
void verbose_set_name(const char *name, int authority)
{
closelog();
openlog(name, LOG_PERROR, authority ? LOG_AUTH : LOG_USER);
}
#else
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
static char *appname;
static int appauthority;
static const char *prefixes[] = {
"<0> EMERGENCY",
"<1> ALERT",
"<2> CRITICAL",
"<3> ERROR",
"<4> WARNING",
"<5> NOTICE",
"<6> INFO",
"<7> DEBUG"
};
void vverbose(int level, const char *file, int line, const char *fmt, va_list args)
{
int saverr = errno;
int tty = isatty(fileno(stderr));
errno = saverr;
fprintf(stderr, "%s: ", prefixes[LEVEL(level)] + (tty ? 4 : 0));
vfprintf(stderr, fmt, args);
if (file != NULL && (!tty || verbosity >5))
fprintf(stderr, " [%s:%d]\n", file, line);
else
fprintf(stderr, "\n");
}
void verbose_set_name(const char *name, int authority)
{
free(appname);
appname = name ? strdup(name) : NULL;
appauthority = authority;
}
#endif
void verbose(int level, const char *file, int line, const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
vverbose(level, file, line, fmt, ap);
va_end(ap);
}
| 2.453125 | 2 |
2024-11-18T22:25:10.079559+00:00 | 2016-12-17T18:58:01 | da48adff72c2d6d72514dbadfabfb9c2e1f1858d | {
"blob_id": "da48adff72c2d6d72514dbadfabfb9c2e1f1858d",
"branch_name": "refs/heads/main",
"committer_date": "2016-12-17T18:58:01",
"content_id": "9beaf6d7ec2773955365ebad9076d8b34e2643c9",
"detected_licenses": [
"MIT"
],
"directory_id": "e9e46c5e8fa04d0335b3a06027f3af0a434c0013",
"extension": "c",
"filename": "node.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 75496316,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 16287,
"license": "MIT",
"license_type": "permissive",
"path": "/bootstrap/util/node.c",
"provenance": "stackv2-0115.json.gz:109421",
"repo_name": "k4rtik/ip-tcp-rs",
"revision_date": "2016-12-17T18:58:01",
"revision_id": "fb9bec89e475af2a5ade4d00e4878df659589f2a",
"snapshot_id": "953c5428a920041145ceab53293bc63f20678190",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/k4rtik/ip-tcp-rs/fb9bec89e475af2a5ade4d00e4878df659589f2a/bootstrap/util/node.c",
"visit_date": "2021-05-23T07:17:51.458806"
} | stackv2 | #include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#include <limits.h>
#include <inttypes.h>
#include <arpa/inet.h>
#include <errno.h>
#include <pthread.h>
#include <unistd.h>
#include <fcntl.h>
#define FILE_BUF_SIZE 1024
#define SHUTDOWN_READ 0
#define SHUTDOWN_WRITE 1
#define SHUTDOWN_BOTH 2
// TODO remove the below #defines, replace by linking with API implementation
#define v_socket() 0
#define v_bind(a,b,c) 0
#define v_listen(a) 0
#define v_connect(a,b,c) -ENOTSUP
#define v_accept(a,b,c) -ENOTSUP
#define v_write(a,b,c) -ENOTSUP
#define v_read(a,b,c) -ENOTSUP
#define v_shutdown(a,b) -ENOTSUP
#define v_close(a) -ENOTSUP
struct sendrecvfile_arg {
int s;
int fd;
};
int v_write_all(int s, const void *buf, size_t bytes_requested){
int ret;
size_t bytes_written;
bytes_written = 0;
while (bytes_written < bytes_requested){
ret = v_write(s, buf + bytes_written, bytes_requested - bytes_written);
if (ret == -EAGAIN){
continue;
}
if (ret < 0){
return ret;
}
if (ret == 0){
fprintf(stderr, "warning: v_write() returned 0 before all bytes written\n");
return bytes_written;
}
bytes_written += ret;
}
return bytes_written;
}
int v_read_all(int s, void *buf, size_t bytes_requested){
int ret;
size_t bytes_read;
bytes_read = 0;
while (bytes_read < bytes_requested){
ret = v_read(s, buf + bytes_read, bytes_requested - bytes_read);
if (ret == -EAGAIN){
continue;
}
if (ret < 0){
return ret;
}
if (ret == 0){
fprintf(stderr, "warning: v_read() returned 0 before all bytes read\n");
return bytes_read;
}
bytes_read += ret;
}
return bytes_read;
}
void help_cmd(const char *line){
(void)line;
printf("- help: Print this list of commands.\n"
"- interfaces: Print information about each interface, one per line.\n"
"- routes: Print information about the route to each known destination, one per line.\n"
"- sockets: List all sockets, along with the state the TCP connection associated with them is in, and their current window sizes.\n"
"- down [integer]: Bring an interface \"down\".\n"
"- up [integer]: Bring an interface \"up\" (it must be an existing interface, probably one you brought down)\n"
"- accept [port]: Spawn a socket, bind it to the given port, and start accepting connections on that port.\n"
"- connect [ip] [port]: Attempt to connect to the given ip address, in dot notation, on the given port. send [socket] [data]: Send a string on a socket.\n"
"- recv [socket] [numbytes] [y/n]: Try to read data from a given socket. If the last argument is y, then you should block until numbytes is received, or the connection closes. If n, then don.t block; return whatever recv returns. Default is n.\n"
"- sendfile [filename] [ip] [port]: Connect to the given ip and port, send the entirety of the specified file, and close the connection.\n"
"- recvfile [filename] [port]: Listen for a connection on the given port. Once established, write everything you can read from the socket to the given file. Once the other side closes the connection, close the connection as well.\n"
"- shutdown [socket] [read/write/both]: v_shutdown on the given socket. If read is given, close only the reading side. If write is given, close only the writing side. If both is given, close both sides. Default is write.\n"
"- close [socket]: v_close on the given socket.\n");
return;
}
void interfaces_cmd(const char *line){
(void)line;
printf("not yet implemented: interfaces\n");
// TODO print interfaces
return;
}
void routes_cmd(const char *line){
(void)line;
printf("not yet implemented: routes\n");
// TODO print routes
return;
}
void sockets_cmd(const char *line){
(void)line;
printf("not yet implemented: sockets\n");
// TODO print sockets
return;
}
void down_cmd(const char *line){
unsigned interface;
int ret;
ret = sscanf(line, "down %u", &interface);
if (ret != 1){
fprintf(stderr, "syntax error (usage: down [interface])\n");
return;
}
printf("not yet implemented: down\n");
// TODO call down(interface)
return;
}
void up_cmd(const char *line){
unsigned interface;
int ret;
ret = sscanf(line, "up %u", &interface);
if (ret != 1){
fprintf(stderr, "syntax error (usage: up [interface])\n");
return;
}
printf("not yet implemented: up\n");
// TODO call up(interface)
return;
}
void *accept_thr_func(void *arg){
int s;
int ret;
s = (int)arg;
while (1){
ret = v_accept(s, NULL, NULL);
if (ret < 0){
fprintf(stderr, "v_accept() error on socket %d: %s\n", s, strerror(-ret));
return NULL;
}
printf("v_accept() on socket %d returned %d\n", s, ret);
}
return NULL;
}
void accept_cmd(const char *line){
uint16_t port;
int ret;
struct in_addr any_addr;
int s;
pthread_t accept_thr;
pthread_attr_t thr_attr;
ret = sscanf(line, "accept %" SCNu16, &port);
if (ret != 1){
fprintf(stderr, "syntax error (usage: accept [port])\n");
return;
}
s = v_socket();
if (s < 0){
fprintf(stderr, "v_socket() error: %s\n", strerror(-s));
return;
}
any_addr.s_addr = 0;
ret = v_bind(s, any_addr, htons(port));
if (ret < 0){
fprintf(stderr, "v_bind() error: %s\n", strerror(-ret));
return;
}
ret = v_listen(s);
if (ret < 0){
fprintf(stderr, "v_listen() error: %s\n", strerror(-ret));
return;
}
ret = pthread_attr_init(&thr_attr);
assert(ret == 0);
ret = pthread_attr_setdetachstate(&thr_attr, PTHREAD_CREATE_DETACHED);
assert(ret == 0);
ret = pthread_create(&accept_thr, &thr_attr, accept_thr_func, (void *)s);
if (ret != 0){
fprintf(stderr, "pthread_create() error: %s\n", strerror(errno));
return;
}
ret = pthread_attr_destroy(&thr_attr);
assert(ret == 0);
return;
}
void connect_cmd(const char *line){
char ip_string[LINE_MAX];
struct in_addr ip_addr;
uint16_t port;
int ret;
int s;
ret = sscanf(line, "connect %s %" SCNu16, ip_string, &port);
if (ret != 2){
fprintf(stderr, "syntax error (usage: connect [ip address] [port])\n");
return;
}
ret = inet_aton(ip_string, &ip_addr);
if (ret == 0){
fprintf(stderr, "syntax error (malformed ip address)\n");
return;
}
s = v_socket();
if (s < 0){
fprintf(stderr, "v_socket() error: %s\n", strerror(-s));
return;
}
ret = v_connect(s, ip_addr, htons(port));
if (ret < 0){
fprintf(stderr, "v_connect() error: %s\n", strerror(-ret));
return;
}
printf("v_connect() returned %d\n", ret);
return;
}
void send_cmd(const char *line){
int num_consumed;
int socket;
const char *data;
int ret;
ret = sscanf(line, "send %d %n", &socket, &num_consumed);
if (ret != 1){
fprintf(stderr, "syntax error (usage: send [interface] [payload])\n");
return;
}
data = line + num_consumed;
if (strlen(data) < 2){ // 1-char message, plus newline
fprintf(stderr, "syntax error (payload unspecified)\n");
return;
}
ret = v_write(socket, data, strlen(data)-1); // strlen()-1: stripping newline
if (ret < 0){
fprintf(stderr, "v_write() error: %s\n", strerror(-ret));
return;
}
printf("v_write() on %d bytes returned %d\n", strlen(data)-1, ret);
return;
}
void recv_cmd(const char *line){
int socket;
size_t bytes_requested;
int bytes_read;
char should_loop;
char *buffer;
int ret;
ret = sscanf(line, "recv %d %zu %c", &socket, &bytes_requested, &should_loop);
if (ret != 3){
should_loop = 'n';
ret = sscanf(line, "recv %d %zu", &socket, &bytes_requested);
if (ret != 2){
fprintf(stderr, "syntax error (usage: recv [interface] [bytes to read] "
"[loop? (y/n), optional])\n");
return;
}
}
buffer = (char *)malloc(bytes_requested+1); // extra for null terminator
assert(buffer);
memset(buffer, '\0', bytes_requested+1);
if (should_loop == 'y'){
bytes_read = v_read_all(socket, buffer, bytes_requested);
}
else if (should_loop == 'n'){
bytes_read = v_read(socket, buffer, bytes_requested);
}
else {
fprintf(stderr, "syntax error (loop option must be 'y' or 'n')\n");
goto cleanup;
}
if (bytes_read < 0){
fprintf(stderr, "v_read() error: %s\n", strerror(-bytes_read));
goto cleanup;
}
buffer[bytes_read] = '\0';
printf("v_read() on %zu bytes returned %d; contents of buffer: '%s'\n",
bytes_requested, bytes_read, buffer);
cleanup:
free(buffer);
return;
}
void *sendfile_thr_func(void *arg){
int s;
int fd;
int ret;
struct sendrecvfile_arg *thr_arg;
int bytes_read;
char buf[FILE_BUF_SIZE];
thr_arg = (struct sendrecvfile_arg *)arg;
s = thr_arg->s;
fd = thr_arg->fd;
free(thr_arg);
while ((bytes_read = read(fd, buf, sizeof(buf))) != 0){
if (bytes_read == -1){
fprintf(stderr, "read() error: %s\n", strerror(errno));
break;
}
ret = v_write_all(s, buf, bytes_read);
if (ret < 0){
fprintf(stderr, "v_write() error: %s\n", strerror(-ret));
break;
}
if (ret != bytes_read){
break;
}
}
ret = v_close(s);
if (ret < 0){
fprintf(stderr, "v_close() error: %s\n", strerror(-ret));
}
ret = close(fd);
if (ret == -1){
fprintf(stderr, "close() error: %s\n", strerror(errno));
}
printf("sendfile on socket %d done\n", s);
return NULL;
}
void sendfile_cmd(const char *line){
int ret;
char filename[LINE_MAX];
char ip_string[LINE_MAX];
struct in_addr ip_addr;
uint16_t port;
int s;
int fd;
struct sendrecvfile_arg *thr_arg;
pthread_t sendfile_thr;
pthread_attr_t thr_attr;
ret = sscanf(line, "sendfile %s %s %" SCNu16, filename, ip_string, &port);
if (ret != 3){
fprintf(stderr, "syntax error (usage: sendfile [filename] [ip address]"
"[port])\n");
return;
}
ret = inet_aton(ip_string, &ip_addr);
if (ret == 0){
fprintf(stderr, "syntax error (malformed ip address)\n");
return;
}
s = v_socket();
if (s < 0){
fprintf(stderr, "v_socket() error: %s\n", strerror(-s));
return;
}
ret = v_connect(s, ip_addr, htons(port));
if (ret < 0){
fprintf(stderr, "v_connect() error: %s\n", strerror(-ret));
return;
}
fd = open(filename, O_RDONLY);
if (fd == -1){
fprintf(stderr, "open() error: %s\n", strerror(errno));
}
thr_arg = (struct sendrecvfile_arg *)malloc(sizeof(struct sendrecvfile_arg));
assert(thr_arg);
thr_arg->s = s;
thr_arg->fd = fd;
ret = pthread_attr_init(&thr_attr);
assert(ret == 0);
ret = pthread_attr_setdetachstate(&thr_attr, PTHREAD_CREATE_DETACHED);
assert(ret == 0);
ret = pthread_create(&sendfile_thr, &thr_attr, sendfile_thr_func, thr_arg);
if (ret != 0){
fprintf(stderr, "pthread_create() error: %s\n", strerror(errno));
return;
}
ret = pthread_attr_destroy(&thr_attr);
assert(ret == 0);
return;
}
void *recvfile_thr_func(void *arg){
int s;
int s_data;
int fd;
int ret;
struct sendrecvfile_arg *thr_arg;
int bytes_read;
char buf[FILE_BUF_SIZE];
thr_arg = (struct sendrecvfile_arg *)arg;
s = thr_arg->s;
fd = thr_arg->fd;
free(thr_arg);
s_data = v_accept(s, NULL, NULL);
if (s_data < 0){
fprintf(stderr, "v_accept() error: %s\n", strerror(-s_data));
return NULL;
}
ret = v_close(s);
if (ret < 0){
fprintf(stderr, "v_close() error: %s\n", strerror(-ret));
return NULL;
}
while ((bytes_read = v_read(s_data, buf, FILE_BUF_SIZE)) != 0){
if (bytes_read < 0){
fprintf(stderr, "v_read() error: %s\n", strerror(-bytes_read));
break;
}
ret = write(fd, buf, bytes_read);
if (ret < 0){
fprintf(stderr, "write() error: %s\n", strerror(errno));
break;
}
}
ret = v_close(s_data);
if (ret < 0){
fprintf(stderr, "v_close() error: %s\n", strerror(-ret));
}
ret = close(fd);
if (ret == -1){
fprintf(stderr, "close() error: %s\n", strerror(errno));
}
printf("recvfile on socket %d done", s_data);
return NULL;
}
void recvfile_cmd(const char *line){
int ret;
char filename[LINE_MAX];
uint16_t port;
int s;
struct in_addr any_addr;
pthread_t recvfile_thr;
pthread_attr_t thr_attr;
struct sendrecvfile_arg *thr_arg;
int fd;
ret = sscanf(line, "recvfile %s %" SCNu16, filename, &port);
if (ret != 2){
fprintf(stderr, "syntax error (usage: recvfile [filename] [port])\n");
return;
}
s = v_socket();
if (s < 0){
fprintf(stderr, "v_socket() error: %s\n", strerror(-s));
return;
}
any_addr.s_addr = 0;
ret = v_bind(s, any_addr, htons(port));
if (ret < 0){
fprintf(stderr, "v_bind() error: %s\n", strerror(-ret));
return;
}
ret = v_listen(s);
if (ret < 0){
fprintf(stderr, "v_listen() error: %s\n", strerror(-ret));
return;
}
fd = open(filename, O_WRONLY | O_CREAT);
if (fd == -1){
fprintf(stderr, "open() error: %s\n", strerror(errno));
}
thr_arg = (struct sendrecvfile_arg *)malloc(sizeof(struct sendrecvfile_arg));
assert(thr_arg);
thr_arg->s = s;
thr_arg->fd = fd;
ret = pthread_attr_init(&thr_attr);
assert(ret == 0);
ret = pthread_attr_setdetachstate(&thr_attr, PTHREAD_CREATE_DETACHED);
assert(ret == 0);
ret = pthread_create(&recvfile_thr, &thr_attr, recvfile_thr_func, thr_arg);
if (ret != 0){
fprintf(stderr, "pthread_create() error: %s\n", strerror(errno));
return;
}
ret = pthread_attr_destroy(&thr_attr);
assert(ret == 0);
return;
}
void shutdown_cmd(const char *line){
char shut_type[LINE_MAX];
int shut_type_int;
int socket;
int ret;
ret = sscanf(line, "shutdown %d %s", &socket, shut_type);
if (ret != 2){
fprintf(stderr, "syntax error (usage: shutdown [socket] [shutdown type])\n");
return;
}
if (!strcmp(shut_type, "read")){
shut_type_int = SHUTDOWN_READ;
}
else if (!strcmp(shut_type, "write")){
shut_type_int = SHUTDOWN_WRITE;
}
else if (!strcmp(shut_type, "both")){
shut_type_int = SHUTDOWN_BOTH;
}
else {
fprintf(stderr, "syntax error (type option must be 'read', 'write', or "
"'both')\n");
return;
}
ret = v_shutdown(socket, shut_type_int);
if (ret < 0){
fprintf(stderr, "v_shutdown() error: %s\n", strerror(-ret));
return;
}
printf("v_shutdown() returned %d\n", ret);
return;
}
void close_cmd(const char *line){
int ret;
int socket;
ret = sscanf(line, "close %d", &socket);
if (ret != 1){
fprintf(stderr, "syntax error (usage: close [socket])\n");
return;
}
ret = v_close(socket);
if (ret < 0){
fprintf(stderr, "v_close() error: %s\n", strerror(-ret));
return;
}
printf("v_close() returned %d\n", ret);
return;
}
struct {
const char *command;
void (*handler)(const char *);
} cmd_table[] = {
{"help", help_cmd},
{"interfaces", interfaces_cmd},
{"routes", routes_cmd},
{"sockets", sockets_cmd},
{"down", down_cmd},
{"up", up_cmd},
{"accept", accept_cmd},
{"connect", connect_cmd},
{"send", send_cmd},
{"recv", recv_cmd},
{"sendfile", sendfile_cmd},
{"recvfile", recvfile_cmd},
{"shutdown", shutdown_cmd},
{"close", close_cmd}
};
void driver(){
char line[LINE_MAX];
char cmd[LINE_MAX];
char *fgets_ret;
int ret;
unsigned i;
while (1){
printf("Command: ");
(void)fflush(stdout);
fgets_ret = fgets(line, sizeof(line), stdin);
if (fgets_ret == NULL){
break;
}
ret = sscanf(line, "%s", cmd);
if (ret != 1){
fprintf(stderr, "syntax error (first argument must be a command)\n");
continue;
}
for (i=0; i < sizeof(cmd_table) / sizeof(cmd_table[0]); i++){
if (!strcmp(cmd, cmd_table[i].command)){
cmd_table[i].handler(line);
break;
}
}
if (i == sizeof(cmd_table) / sizeof(cmd_table[0])){
fprintf(stderr, "error: no valid command specified\n");
continue;
}
}
return;
}
int main(int argc, char **argv){
if (argc != 2) {
fprintf(stderr, "usage: %s <linkfile>\n", argv[0]);
return -1;
}
// TODO initialization!
driver();
return 0;
}
| 2.609375 | 3 |
2024-11-18T22:25:10.174731+00:00 | 2015-06-27T17:17:56 | 3e2f2efddcccd7ba88a912976df5a014190b1d1d | {
"blob_id": "3e2f2efddcccd7ba88a912976df5a014190b1d1d",
"branch_name": "refs/heads/master",
"committer_date": "2015-06-27T17:17:56",
"content_id": "681d6269cbc4eb1ec56ac4e1b6b9cfa177d1bed1",
"detected_licenses": [
"MIT"
],
"directory_id": "c5f572ca160ffc157c063a495deae025f5cb0581",
"extension": "h",
"filename": "package.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 21833693,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1570,
"license": "MIT",
"license_type": "permissive",
"path": "/mpk/package.h",
"provenance": "stackv2-0115.json.gz:109551",
"repo_name": "JosefR/mpk-package-manager",
"revision_date": "2015-06-27T17:17:56",
"revision_id": "b343580e6dbd0d3a762fab3c7551c0ddf266c625",
"snapshot_id": "044c9634268c52f2fd8acafed9a39a3f24372b2f",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/JosefR/mpk-package-manager/b343580e6dbd0d3a762fab3c7551c0ddf266c625/mpk/package.h",
"visit_date": "2020-07-21T23:45:23.304158"
} | stackv2 | /**
* @file package.h
* @author Josef Raschen <josef@raschen.org>
* @brief Creating and unpacking mpk package files.
*/
#ifndef _PACKAGE_H
#define _PACKAGE_H
#include <stdint.h>
#include <mpk/pkginfo.h>
#include <mpk/version.h>
#define MPK_PACKAGE_SIGNATURE_LEN 256 /* 2048 bit signature */
#define MPK_PACKAGE_CACHE_DIR "/tmp"
/**
* @brief mpk_package_packmpk creates a mpk package from the packageinfo and
* source data
* @param pkg package info object of the package
* @param srcdir directory of the source data
* @return
*/
int mpk_package_packmpk(struct mpk_pkginfo *pkg, const char *srcdir,
const char *outdir);
/**
* @brief Unpacks a mpk.
* @param unpacked_to Returns the path to which the package has been unpacked.
* @param package_file The file to unpack.
* @param outdir The destination directory.
* @return
*/
int mpk_package_unpackmpk(const char *package_file, char *outdir);
/**
* @brief mpk_package_verify checks if the signature of the package is correct
* @param pkginf pkfinfo of the package to check
* @param pkgdir directory of the extracted files
* @param pubkey rsa public key
* @return
*/
int mpk_package_verify(struct mpk_pkginfo *pkginf, const char *pkgdir,
const char *pubkey);
/**
* @brief Returns a allocated string of the package filename without any
* extension.
* @param fpath Path include mpk filename.
* @return The result string located on the heap.
*
* Example: /tmp/testpackage-1.2.0.mpk -> testpackage-1.2.0
*/
char *mpk_package_name_from_fpath(const char *fpath);
#endif /* _PACKAGE_H */
| 2.359375 | 2 |
2024-11-18T22:25:10.253714+00:00 | 2018-03-01T08:56:07 | 79086a8011edcb4e71d5339912cbeff890de3dd0 | {
"blob_id": "79086a8011edcb4e71d5339912cbeff890de3dd0",
"branch_name": "refs/heads/master",
"committer_date": "2018-03-01T08:56:07",
"content_id": "2651b809ebaabd6f397a0fdd0e0a1bb6eafdf877",
"detected_licenses": [
"MIT"
],
"directory_id": "9149c6be503c6a438e239212e127f6e0b9e021ed",
"extension": "c",
"filename": "test.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 14202,
"license": "MIT",
"license_type": "permissive",
"path": "/test.c",
"provenance": "stackv2-0115.json.gz:109682",
"repo_name": "jsj2008/text_search_tries",
"revision_date": "2018-03-01T08:56:07",
"revision_id": "d1544e8cf3b4c7d4d4527a6bb6c555f954de3b92",
"snapshot_id": "65236603a6461e1a6bc7ce091083b942e24229ad",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/jsj2008/text_search_tries/d1544e8cf3b4c7d4d4527a6bb6c555f954de3b92/test.c",
"visit_date": "2020-03-17T23:22:27.851808"
} | stackv2 | #include "test.h"
#include <stdlib.h>
#include "fcntl.h"
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
int init_test_input(struct index *trie,char * filename,char *command){
//printf("\x1b[32m""INIT_INPUT start\n""\x1b[0m");
int table_size = 10;
int word_size = 25;
int a;
char **ptr_table = malloc(table_size*sizeof(char *));
int words_in = 0;
FILE* fd = fopen(filename, "r"); //opening input file
//strcpy(buffer,"\0");
if(fd == NULL){
perror("Error opening input file");
return -1;
}
char *line = NULL;
size_t len = 0;
ssize_t read;
char *word;
for(a=0;a<table_size;a++)
ptr_table[a]=malloc(word_size*sizeof(char));
while ((read = getline(&line, &len, fd)) != -1){
words_in = 0;
word = strtok (line," \n");
while(word!=NULL)
{
//printf("Read this word: %s\n",word);
if(words_in==table_size){
table_size*=2;
ptr_table = realloc(ptr_table,table_size*sizeof(char*));
for(a=(table_size/2);a<table_size;a++)
ptr_table[a]=malloc(word_size*sizeof(char));
}
if(strlen(word)>word_size){
word_size*=2;
for(a=0;a<table_size;a++)
ptr_table[a] = realloc(ptr_table[a],word_size*sizeof(char));
}
// ptr_table[words_in] = malloc(word_size*sizeof(char));
strcpy(ptr_table[words_in],word);
//printf("Kuru word = %s\n",ptr_table[words_in]);
words_in++;
word=strtok(NULL," \n");
}
if(strcmp("add",command)==0) test_add(trie,ptr_table,words_in,FOUND);
else deleteTrieNode(trie->hash,ptr_table,words_in-1);
}
//printf ("free\n");
free(line);
cleanup(ptr_table);
fclose(fd);
//printf("\x1b[32m""INIT_INPUT end\n""\x1b[0m");
return 0;
}
int test_if_exists(struct index *trie,char **words ,int words_size){
//printf("Inside check if exists\n");
int i;
trie_node *node;
int found=NOT_FOUND;
int pos;
int hash_val=hash_function(trie->hash,words[0]);
hash_bucket *bucket=&(trie->hash->buckets[hash_val]);
found=check_exists_in_bucket(words[0],&pos,bucket->children,bucket->children_number);
if(found==0) return found; //not found
node=&(bucket->children[pos]);
i=1; //keep checking
while(i!=words_size){
found=check_exists_in_children(node,words[i],&pos);
if(found==NOT_FOUND) break;
node=&(node->children[pos]);
i++;
}
if(found==FOUND && node->is_final=='n') found=NOT_FOUND;
return found;
}
void test_delete(struct index *trie,char **words_to_check ,int words_size,int expected_result){
int error=deleteTrieNode(trie->hash,words_to_check,words_size-1);
//printf("error is %d\n",error);
int result=test_if_exists(trie,words_to_check ,words_size);
//printf("result is %d\n",result);
if(result!=expected_result){
printf("Wrong result in delete\n");
}
}
void test_add(struct index *trie,char **words_to_check ,int words_size,int expected_result){
insertTrieNode(trie->hash,words_to_check,words_size,0);
int found=test_if_exists(trie,words_to_check ,words_size);
if(found!=FOUND) printf("Ngram was not added\n");
}
void test_binary_search(struct index *trie,char *word,int expected_found,int expected_position){
int found;
int pos;
found=check_exists_in_children(trie->root,word,&pos);
if(found!=expected_found){ printf("Wasn't found\n");return;}
if(pos!=expected_position && found==1){ printf("%s Wasn't found in the right position\n",word);return;}
}
void tests_for_binary(struct index *trie){
char *test_word=malloc(15*sizeof(char));
//some tests
strcpy(test_word,"0000");
test_binary_search(trie,test_word,0,0);
strcpy(test_word,"zzz");
test_binary_search(trie,test_word,0,trie->root->number_of_childs-1);
free(test_word);
}
int parseInt (char c) {
return c - '0';
}
int tests_from_file(struct index *trie,char * filename){
printf("Inside tests from file\n");
int table_size=10;
int word_size=25;
char **ptr_table = malloc(table_size*sizeof(char *));
int words_in = 0;
int flag; //1 question, 2 addition, 3 deletion, 4 end of file
int a;
FILE* fd = fopen(filename, "r"); //opening input file
if(fd == NULL)
{
perror("Error opening input file");
return -1;
}
char *line = NULL;
size_t len = 0;
ssize_t read;
char *word;
int command_error;
for(a=0;a<table_size;a++)
ptr_table[a]=malloc(word_size*sizeof(char));
while ((read = getline(&line, &len, fd)) != -1) {
//words_in = 1;
words_in = 0;
word = strtok (line," \n");
while(word!=NULL){
if(strcmp(word,"Q")==0){
flag=1;
}
else if(strcmp(word,"A")==0){
flag=2;
}
else if(strcmp(word,"D")==0){
flag=3;
}
else if(strcmp(word,"F")==0){
//printf("\x1b[36m""EOF -1\n""\x1b[0m");
/*
cleanup(ptr_table);
free(line);
fclose(fd);
printf("\x1b[32m""TEST_INPUT end\n""\x1b[0m");
return 1;
*/
//printf("\x1b[32m""F -> print paths\n""\x1b[0m");
}else if(strcmp(word,"\0")==0){
}
else{
if(words_in==table_size-1){
table_size*=2;
ptr_table = realloc(ptr_table,table_size*(sizeof(char*)));
for(a=table_size/2;a<table_size;a++){
ptr_table[a]=malloc(word_size*sizeof(char));
}
}
if(strlen(word)>=word_size){
word_size*=2;
for(a=0;a<table_size;a++)
ptr_table[a] = realloc(ptr_table[a],word_size*sizeof(char));
}
strcpy(ptr_table[words_in],word);
words_in++;
}
word=strtok(NULL," \n");
}
int expected_result = parseInt(ptr_table[words_in-1][0]); //kratasei ton teleytaio arithmo apo tin seira pou diabase
words_in --; //meiwnei to words_in gia na min lifthei upopsin o teleytaios arithmos
switch(flag){
case 1 :
printf("\n");
break;
case 2 :
test_add(trie,ptr_table,words_in,expected_result);
break;
case 3 :
test_delete(trie,ptr_table,words_in,expected_result);
}
flag=0;
}
free(line);
cleanup(ptr_table);
fclose(fd);
return 0;
}
void test_hash_function(struct index *trie,char * filename){
init_test_input(trie,filename, "add");
init_test_input(trie,filename, "delete");
int empty=check_if_empty(trie->hash);
if(empty==1){
printf("All found and removed correctly\n");
return ;
}
printf("Not removed correctly\n");
return ;
}
int check_if_empty(hash_layer *hash){
int i;
hash_bucket *bucket;
for(i=0;i<hash->buckets_number;i++){
bucket=&(hash->buckets[i]);
if(bucket->children_number>0) return 0;
}
return 1;
}
//-------------------------------------------------unit testing in static functions -----------------------------------------//
int test_if_exists_static(struct static_index *trie,char **words ,int words_size){
//printf("Inside check if exists\n");
int i;
char *temp_word=malloc(WORD_SIZE*sizeof(char));
int word_size=WORD_SIZE;
static_trie_node *node;
int found=NOT_FOUND;
int pos;
int hash_val=static_hash_function(trie->hash,words[0]);
static_hash_bucket *bucket=&(trie->hash->buckets[hash_val]);
found=check_exists_in_static_bucket(bucket,words[0],&pos);
if(found==0) return found; //not found
node=&(bucket->children[pos]);
i=1; //keep checking
int node_word=1;
while(i!=words_size){
if(node_word==node->number_of_words){
found=check_exists_in_static_children(node,words[i],&pos);
if(found==NOT_FOUND) break;
node=&(node->children[pos]);
i++;
node_word=1;
}
else {
temp_word=get_i_word(node,node_word,temp_word,&word_size);
if(strcmp(temp_word,words[i])==0) found=FOUND;
else found=NOT_FOUND;
i++;
node_word++;
}
}
if(found==FOUND && node->is_final[node_word-1]>0) found=NOT_FOUND;
free(temp_word);
return found;
}
int check_number_of_childs(static_trie_node *node){
if(node->number_of_childs==1) return 1;
int i,error;
for(i=0;i<node->number_of_childs;i++){
error=check_number_of_childs(&(node->children[i]));
if(error==1) return 1;
}
return 0;
}
void test_compress(static_hash_layer *hash){
int i,j;
static_hash_bucket *bucket;
for(i=0;i<hash->buckets_number;i++){
bucket=&(hash->buckets[i]);
for(j=0;j<bucket->children_number;j++){
int error=check_number_of_childs(&(bucket->children[j]));
if(error == 1){
printf("Compress failed\n");
return;
}
}
}
printf("compress succeded\n");
return;
}
void test_everything_exists(struct static_index *trie,char * filename){
//printf("\x1b[32m""INIT_INPUT start\n""\x1b[0m");
int table_size = 10;
int word_size = 25;
int a;
char **ptr_table = malloc(table_size*sizeof(char *));
int words_in = 0;
FILE* fd = fopen(filename, "r"); //opening input file
//strcpy(buffer,"\0");
if(fd == NULL){
perror("Error opening input file");
return ;
}
char *line = NULL;
size_t len = 0;
ssize_t read;
char *word;
int result;
for(a=0;a<table_size;a++)
ptr_table[a]=malloc(word_size*sizeof(char));
while ((read = getline(&line, &len, fd)) != -1){
words_in = 0;
word = strtok (line," \n");
while(word!=NULL)
{
//printf("Read this word: %s\n",word);
if(words_in==table_size){
table_size*=2;
ptr_table = realloc(ptr_table,table_size*sizeof(char*));
for(a=(table_size/2);a<table_size;a++)
ptr_table[a]=malloc(word_size*sizeof(char));
}
if(strlen(word)>word_size){
word_size*=2;
for(a=0;a<table_size;a++)
ptr_table[a] = realloc(ptr_table[a],word_size*sizeof(char));
}
// ptr_table[words_in] = malloc(word_size*sizeof(char));
strcpy(ptr_table[words_in],word);
//printf("Kuru word = %s\n",ptr_table[words_in]);
words_in++;
word=strtok(NULL," \n");
}
result=test_if_exists_static(trie,ptr_table,words_in);
if(result==NOT_FOUND){
printf("FAILURE:Something is missing from trie\n");
free(line);
cleanup(ptr_table);
fclose(fd);
return ;
}
//test_static_add(trie,ptr_table,words_in,FOUND);
}
//printf ("free\n");
printf("SUCCED:everything is ok in static_trie\n");
free(line);
cleanup(ptr_table);
fclose(fd);
return ;
}
void test_bloom_bit(void){
printf("Test bloom bit: ");
int flag = 0;
int a = 63;
int * bloomfilter = malloc(8192);
bloomfilter_init(bloomfilter,8192*8);
if(TestBit(bloomfilter,a)){
printf("Error in Initbit\n");
flag++;
}
SetBit(bloomfilter,a);
if(!TestBit(bloomfilter,a)){
printf("Error in Setbit\n");
flag++;
}
ClearBit(bloomfilter,a);
if(TestBit(bloomfilter,a)){
printf("Error in Clearbit\n");
flag++;
}
free(bloomfilter);
if(flag==0)
printf("No errors\n");
}
void test_bloom(void){
printf("Test bloom: ");
int flag = 0;
int bits = 8192*8, bytes=8192;
int * bloomfilter = malloc(bytes);
bloomfilter_init(bloomfilter,bits);
if(bloomfilter_check("lets check the bloomfilter",bloomfilter,bytes)){
printf("Error in bloomfilter init\n");
flag++;
}
bloomfilter_add("lets check the bloomfilter2",bloomfilter,bytes);
if(!bloomfilter_check("lets check the bloomfilter2",bloomfilter,bytes)){
printf("Error in bloomfilter add\n");
flag++;
}
free(bloomfilter);
if(flag==0)
printf("No errors\n");
}
int test_top(void){
printf("Test_top: ");
int flag = 0;
topk * top;
top = create_top(top);
top = init_top(top);
int previous_capacity=top->kf->capacity;
top = extend_top(top);
if (top->kf->capacity!=previous_capacity*2){
printf("Error in extend top\n");
flag++;
}
top = add_top(top,"antonis");
if(top->fr->frequency[0] != 1){
printf("Error in add top\n");
flag++;
}
top->fr->frequency[0] = 5;
top->fr->frequency[1] = 35;
top->fr->frequency[2] = 23;
top->fr->frequency[3] = 240;
int i;
top = add_top(top,"antonis");
top = add_top(top,"antonis");
top = add_top(top,"antonis");
top = add_top(top,"antonis");
top = add_top(top,"bntonis");
top = add_top(top,"bntonis");
top = add_top(top,"bntonis");
top = add_top(top,"cntonis");
top = add_top(top,"dntonis");
top = add_top(top,"dntonis");
quickSort(top->fr->frequency,top->fr->ngram,0,top->fr->unique-1,top->kf->ngrams);
for (i=1;i<5;i++){
// printf("%s ",top->kf->ngrams[i]);
// printf("%d\n",top->fr->frequency[i]);
}
if((top->fr->frequency[0]<top->fr->frequency[1])||(top->fr->frequency[1]<top->fr->frequency[2])||
(top->fr->frequency[2]<top->fr->frequency[3]))
{
printf("Error in init/create top\n");
flag++;
}
if(flag==0)
printf("No errors\n");
erase_top(top);
}
void test_versioning(hash_layer *hash){
int i;
int results=open("cout.log",O_CREAT | O_RDWR,0600);
if(results==-1){
printf("error in opening");
return;
}
//rewind(results);
int save_out=dup(fileno(stdout));
if(dup2(results,fileno(stdout))==-1){
printf("error in redirecting stdout");
return;
}
topk * top;
top = create_top(top);
top = init_top(top);
char **test_version=malloc(10*sizeof(char*));
int *versions=malloc(10*sizeof(int));
for(i=0;i<10;i++){
test_version[i]=malloc(50*sizeof(char));
}
strcpy(test_version[0],"panos");
versions[0]=0;
strcpy(test_version[1],"eats");
versions[1]=1;
strcpy(test_version[2],"a");
versions[2]=2;
strcpy(test_version[3],"lot");
versions[3]=3;
strcpy(test_version[4],"of");
versions[4]=4;
for(i=0;i<5;i++){
insertTrieNode(hash,test_version,i+1,i);
}
for(i=0;i<5;i++){
lookupTrieNode_with_bloom_versioning(hash,test_version,i+1,top,i,0);
}
for(i=0;i<5;i++){
deleteTrieNode_versioning(hash,test_version,i+1,5);
}
for(i=0;i<5;i++){
lookupTrieNode_with_bloom_versioning(hash,test_version,i+1,top,5,0);
}
print_print(top);
fflush(stdout);
close(results);
dup2(save_out,fileno(stdout));
close(save_out);
if(check_identical_files("cout.log","expected_r.log")==1){
printf("No errors in versioning\n");
}
else printf("There are errors in versioning\n");
free(versions);
for(i=0;i<10;i++){
free(test_version[i]);
}
free(test_version);
erase_top(top);
}
int check_identical_files(char *filename1,char *filename2){
FILE *f1 = fopen(filename1, "r");
if (!f1) { printf("file %s doesnt_exist",filename1); return 0; }
FILE *f2 = fopen(filename2, "r");
if (!f2) { printf("file %s doesnt_exist",filename2); return 0; }
int samefile = 1;
int c1, c2;
c1 = getc(f1);
c2 = getc(f2);
while (samefile && (c1!= EOF) || c2!= EOF){
if (c1 != c2){
samefile = 0;
printf("error in letter \"%c\" \"%c\"\n",c1,c2 );
//return samefile;
}
c1 = getc(f1);
c2 = getc(f2);
}
fclose (f1), fclose (f2);
return samefile;
}
| 2.625 | 3 |
2024-11-18T22:25:10.478879+00:00 | 2015-04-28T19:56:51 | c9a7609eca3f81c2bfc0b173dd3a667c0477e30b | {
"blob_id": "c9a7609eca3f81c2bfc0b173dd3a667c0477e30b",
"branch_name": "refs/heads/mirror",
"committer_date": "2015-04-28T19:56:51",
"content_id": "f560bf5dd8e291061630ac66a7c995a476111a2b",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "83102f87c241c833e176b355af654ef77f7b0762",
"extension": "c",
"filename": "fifo_scheduler.c",
"fork_events_count": 0,
"gha_created_at": "2014-05-22T20:16:39",
"gha_event_created_at": "2014-11-28T01:50:06",
"gha_language": "C",
"gha_license_id": null,
"github_id": 20075555,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 14357,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/engine/thorium/scheduler/fifo_scheduler.c",
"provenance": "stackv2-0115.json.gz:109941",
"repo_name": "GeneAssembly/biosal",
"revision_date": "2015-04-28T19:56:51",
"revision_id": "a18d6d08f1b31dfd78a6c1d1c5af8d7bb6e91584",
"snapshot_id": "ed113766c60b743af4e8c1b04004fd6befda57ba",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/GeneAssembly/biosal/a18d6d08f1b31dfd78a6c1d1c5af8d7bb6e91584/engine/thorium/scheduler/fifo_scheduler.c",
"visit_date": "2020-05-07T20:16:14.905809"
} | stackv2 |
#include "fifo_scheduler.h"
#include "scheduler.h"
#include <engine/thorium/actor.h>
#include <core/system/debugger.h>
void thorium_fifo_scheduler_init(struct thorium_scheduler *self);
void thorium_fifo_scheduler_destroy(struct thorium_scheduler *self);
int thorium_fifo_scheduler_enqueue(struct thorium_scheduler *self, struct thorium_actor *actor);
int thorium_fifo_scheduler_dequeue(struct thorium_scheduler *self, struct thorium_actor **actor);
int thorium_fifo_scheduler_size(struct thorium_scheduler *self);
int thorium_fifo_scheduler_get_size_with_priority(struct thorium_fifo_scheduler *self, int priority);
struct core_queue *thorium_fifo_scheduler_select_queue(struct thorium_fifo_scheduler *self, int priority);
uint64_t *thorium_fifo_scheduler_select_counter(struct thorium_fifo_scheduler *self, int priority);
int thorium_fifo_scheduler_dequeue_with_priority(struct thorium_fifo_scheduler *self, int priority,
struct thorium_actor **actor);
void thorium_fifo_scheduler_reset_counter(struct thorium_fifo_scheduler *self, int priority);
uint64_t thorium_fifo_scheduler_get_counter(struct thorium_fifo_scheduler *self, int priority);
void thorium_fifo_scheduler_print(struct thorium_scheduler *self);
void thorium_fifo_scheduler_print_with_priority(struct thorium_fifo_scheduler *self, int priority, const char *name,
int node, int worker);
struct thorium_scheduler_interface thorium_fifo_scheduler_implementation = {
.identifier = THORIUM_FIFO_SCHEDULER,
.name = "fifo_scheduler",
.object_size = sizeof(struct thorium_fifo_scheduler),
.init = thorium_fifo_scheduler_init,
.destroy = thorium_fifo_scheduler_destroy,
.enqueue = thorium_fifo_scheduler_enqueue,
.dequeue = thorium_fifo_scheduler_dequeue,
.size = thorium_fifo_scheduler_size,
.print = thorium_fifo_scheduler_print
};
void thorium_fifo_scheduler_init(struct thorium_scheduler *self)
{
struct thorium_fifo_scheduler *queue;
queue = self->concrete_self;
core_queue_init(thorium_fifo_scheduler_select_queue(queue, THORIUM_PRIORITY_MAX),
sizeof(struct thorium_actor *));
core_queue_init(thorium_fifo_scheduler_select_queue(queue, THORIUM_PRIORITY_HIGH),
sizeof(struct thorium_actor *));
core_queue_init(thorium_fifo_scheduler_select_queue(queue, THORIUM_PRIORITY_NORMAL),
sizeof(struct thorium_actor *));
core_queue_init(thorium_fifo_scheduler_select_queue(queue, THORIUM_PRIORITY_LOW),
sizeof(struct thorium_actor *));
thorium_fifo_scheduler_reset_counter(queue, THORIUM_PRIORITY_MAX);
thorium_fifo_scheduler_reset_counter(queue, THORIUM_PRIORITY_HIGH);
thorium_fifo_scheduler_reset_counter(queue, THORIUM_PRIORITY_NORMAL);
thorium_fifo_scheduler_reset_counter(queue, THORIUM_PRIORITY_LOW);
}
void thorium_fifo_scheduler_destroy(struct thorium_scheduler *self)
{
struct thorium_fifo_scheduler *queue;
queue = self->concrete_self;
core_queue_destroy(thorium_fifo_scheduler_select_queue(queue, THORIUM_PRIORITY_MAX));
core_queue_destroy(thorium_fifo_scheduler_select_queue(queue, THORIUM_PRIORITY_HIGH));
core_queue_destroy(thorium_fifo_scheduler_select_queue(queue, THORIUM_PRIORITY_NORMAL));
core_queue_destroy(thorium_fifo_scheduler_select_queue(queue, THORIUM_PRIORITY_LOW));
thorium_fifo_scheduler_reset_counter(queue, THORIUM_PRIORITY_MAX);
thorium_fifo_scheduler_reset_counter(queue, THORIUM_PRIORITY_HIGH);
thorium_fifo_scheduler_reset_counter(queue, THORIUM_PRIORITY_NORMAL);
thorium_fifo_scheduler_reset_counter(queue, THORIUM_PRIORITY_LOW);
}
int thorium_fifo_scheduler_enqueue(struct thorium_scheduler *self, struct thorium_actor *actor)
{
int priority;
struct core_queue *selected_queue;
struct thorium_fifo_scheduler *queue;
queue = self->concrete_self;
CORE_DEBUGGER_ASSERT(actor != NULL);
priority = thorium_actor_get_priority(actor);
selected_queue = thorium_fifo_scheduler_select_queue(queue, priority);
return core_queue_enqueue(selected_queue, &actor);
}
int thorium_fifo_scheduler_dequeue(struct thorium_scheduler *self, struct thorium_actor **actor)
{
int low_size;
int normal_size;
int high_size;
int max_size;
int normal_limit_reached;
int low_limit_reached;
uint64_t high_priority_operations;
uint64_t normal_priority_operations;
uint64_t low_priority_operations;
uint64_t allowed_normal_operations;
uint64_t allowed_low_operations;
struct thorium_fifo_scheduler *queue;
queue = self->concrete_self;
max_size = thorium_fifo_scheduler_get_size_with_priority(queue, THORIUM_PRIORITY_MAX);
/*
* If the max priority queue has stuff
* it wins right away, regardless of anything else.
*/
if (max_size > 0) {
#if 0
printf("Got THORIUM_PRIORITY_MAX !\n");
#endif
return thorium_fifo_scheduler_dequeue_with_priority(queue, THORIUM_PRIORITY_MAX, actor);
}
/* Otherwise, the multiplier is used.
*/
low_size = thorium_fifo_scheduler_get_size_with_priority(queue, THORIUM_PRIORITY_LOW);
normal_size = thorium_fifo_scheduler_get_size_with_priority(queue, THORIUM_PRIORITY_NORMAL);
high_size = thorium_fifo_scheduler_get_size_with_priority(queue, THORIUM_PRIORITY_HIGH);
/*
* If the high priority queue has stuff
* and normal and low queues are empty, then
* high queue wins right away.
*/
if (high_size > 0 && low_size == 0 && normal_size == 0) {
return thorium_fifo_scheduler_dequeue_with_priority(queue, THORIUM_PRIORITY_HIGH, actor);
}
/*
* Otherwise, verify if we are allowed to dequeue from the
* high priority queue.
*/
high_priority_operations = thorium_fifo_scheduler_get_counter(queue, THORIUM_PRIORITY_HIGH);
normal_priority_operations = thorium_fifo_scheduler_get_counter(queue, THORIUM_PRIORITY_NORMAL);
low_priority_operations = thorium_fifo_scheduler_get_counter(queue, THORIUM_PRIORITY_LOW);
allowed_normal_operations = high_priority_operations / THORIUM_SCHEDULING_QUEUE_RATIO;
allowed_low_operations = allowed_normal_operations / THORIUM_SCHEDULING_QUEUE_RATIO;
normal_limit_reached = 0;
if (normal_priority_operations >= allowed_normal_operations) {
normal_limit_reached = 1;
}
low_limit_reached = 0;
if (low_priority_operations >= allowed_low_operations) {
low_limit_reached = 1;
}
if (high_size > 0
&& normal_limit_reached
&& low_limit_reached) {
return thorium_fifo_scheduler_dequeue_with_priority(queue, THORIUM_PRIORITY_HIGH, actor);
}
/* At this point, it is know that:
*
* 1. The max priority queue is empty.
* 2. The high priority queue is empty OR
* the normal dequeue operations are below the allowed number of normal dequeue operations
* (which means that the dequeuing must be done on the normal queue or the low queue at this
* point, if of course the low priority queue or the normal priority queue are not empty.
*
* Therefore, below this line, only the normal priority queue and the low priority queue
* are tested.
*/
/*
* If normal and low queues are empty,
* return 0 (nothing was dequeued).
*/
if (normal_size == 0 && low_size == 0) {
return 0;
}
/*
* Otherwise, if the low priority queue is empty,
* and the normal queue has stuff, dequeue from normal
*/
if (normal_size > 0 && low_size == 0) {
return thorium_fifo_scheduler_dequeue_with_priority(queue, THORIUM_PRIORITY_NORMAL, actor);
}
/* Otherwise, if the low priority queue has stuff, but the normal
* is empty, dequeue from normal.
*/
if (normal_size == 0 && low_size > 0) {
return thorium_fifo_scheduler_dequeue_with_priority(queue, THORIUM_PRIORITY_LOW, actor);
}
/* At this point, the low priority queue and the normal priority queue
* both have things inside them and the max priority queue
* and the high priority queue are empty (or the high fair-share disallows from
* dequeuing from it.
*
* The scheduling queue must select either the normal priority queue or the
* low priority queue.
*
* To do so, the ratio THORIUM_SCHEDULING_QUEUE_RATIO
* is used.
*
* That is, 1 dequeue operation on the low priority queue is allowed for each
* THORIUM_SCHEDULING_QUEUE_RATIO dequeue operations on the
* normal priority queue.
*/
allowed_low_operations = normal_priority_operations / THORIUM_SCHEDULING_QUEUE_RATIO;
low_limit_reached = 0;
if (low_priority_operations >= allowed_low_operations) {
low_limit_reached = 1;
}
/*
* Use the low priority queue if it has not exceeded the limit
* allowed.
*
* @low_limit_reached is either in comparison with the high priority or with the
* low priority.
*
*/
if (!low_limit_reached) {
return thorium_fifo_scheduler_dequeue_with_priority(queue, THORIUM_PRIORITY_LOW, actor);
}
/* Otherwise, use the normal priority queue directly.
*/
return thorium_fifo_scheduler_dequeue_with_priority(queue, THORIUM_PRIORITY_NORMAL, actor);
}
int thorium_fifo_scheduler_size(struct thorium_scheduler *self)
{
int size;
struct thorium_fifo_scheduler *queue;
queue = self->concrete_self;
size = 0;
size += thorium_fifo_scheduler_get_size_with_priority(queue, THORIUM_PRIORITY_LOW);
size += thorium_fifo_scheduler_get_size_with_priority(queue, THORIUM_PRIORITY_NORMAL);
size += thorium_fifo_scheduler_get_size_with_priority(queue, THORIUM_PRIORITY_HIGH);
size += thorium_fifo_scheduler_get_size_with_priority(queue, THORIUM_PRIORITY_MAX);
return size;
}
int thorium_fifo_scheduler_get_size_with_priority(struct thorium_fifo_scheduler *queue, int priority)
{
struct core_queue *selected_queue;
selected_queue = thorium_fifo_scheduler_select_queue(queue, priority);
return core_queue_size(selected_queue);
}
int thorium_fifo_scheduler_dequeue_with_priority(struct thorium_fifo_scheduler *queue, int priority,
struct thorium_actor **actor)
{
int value;
struct core_queue *selected_queue;
uint64_t *selected_counter;
selected_queue = thorium_fifo_scheduler_select_queue(queue, priority);
selected_counter = thorium_fifo_scheduler_select_counter(queue, priority);
value = core_queue_dequeue(selected_queue, actor);
if (value) {
(*selected_counter)++;
}
return value;
}
struct core_queue *thorium_fifo_scheduler_select_queue(struct thorium_fifo_scheduler *queue, int priority)
{
struct core_queue *selection;
selection = NULL;
if (priority == THORIUM_PRIORITY_MAX) {
selection = &queue->max_priority_queue;
} else if (priority == THORIUM_PRIORITY_HIGH) {
selection = &queue->high_priority_queue;
} else if (priority == THORIUM_PRIORITY_NORMAL) {
selection = &queue->normal_priority_queue;
} else if (priority == THORIUM_PRIORITY_LOW) {
selection = &queue->low_priority_queue;
}
CORE_DEBUGGER_ASSERT(selection != NULL);
return selection;
}
uint64_t *thorium_fifo_scheduler_select_counter(struct thorium_fifo_scheduler *queue, int priority)
{
uint64_t *selection;
selection = NULL;
if (priority == THORIUM_PRIORITY_MAX) {
selection = &queue->max_priority_dequeue_operations;
} else if (priority == THORIUM_PRIORITY_HIGH) {
selection = &queue->high_priority_dequeue_operations;
} else if (priority == THORIUM_PRIORITY_NORMAL) {
selection = &queue->normal_priority_dequeue_operations;
} else if (priority == THORIUM_PRIORITY_LOW) {
selection = &queue->low_priority_dequeue_operations;
}
CORE_DEBUGGER_ASSERT(selection != NULL);
return selection;
}
uint64_t thorium_fifo_scheduler_get_counter(struct thorium_fifo_scheduler *queue, int priority)
{
uint64_t *counter;
counter = thorium_fifo_scheduler_select_counter(queue, priority);
return *counter;
}
void thorium_fifo_scheduler_reset_counter(struct thorium_fifo_scheduler *queue, int priority)
{
uint64_t *counter;
counter = thorium_fifo_scheduler_select_counter(queue, priority);
*counter = 0;
}
void thorium_fifo_scheduler_print(struct thorium_scheduler *self)
{
struct thorium_fifo_scheduler *queue;
int node;
int worker;
node = self->node;
worker = self->worker;
queue = self->concrete_self;
printf("node/%d worker/%d SchedulingQueue Levels: %d\n",
node, worker, 4);
thorium_fifo_scheduler_print_with_priority(queue, THORIUM_PRIORITY_MAX, "THORIUM_PRIORITY_MAX", node, worker);
thorium_fifo_scheduler_print_with_priority(queue, THORIUM_PRIORITY_HIGH, "THORIUM_PRIORITY_HIGH", node, worker);
thorium_fifo_scheduler_print_with_priority(queue, THORIUM_PRIORITY_NORMAL, "THORIUM_PRIORITY_NORMAL", node, worker);
thorium_fifo_scheduler_print_with_priority(queue, THORIUM_PRIORITY_LOW, "THORIUM_PRIORITY_LOW", node, worker);
printf("node/%d worker/%d SchedulingQueue... completed report !\n",
node, worker);
}
void thorium_fifo_scheduler_print_with_priority(struct thorium_fifo_scheduler *queue, int priority, const char *name,
int node, int worker)
{
struct core_queue *selection;
struct thorium_actor *actor;
int size;
int i;
selection = thorium_fifo_scheduler_select_queue(queue, priority);
size = core_queue_size(selection);
printf("node/%d worker/%d scheduling_queue: Priority Queue %d (%s), actors: %d\n",
node, worker,
priority, name, size);
i = 0;
while (i < size) {
core_queue_dequeue(selection, &actor);
core_queue_enqueue(selection, &actor);
printf("node/%d worker/%d [%i] actor %s/%d (%d messages)\n",
node, worker,
i,
thorium_actor_script_name(actor),
thorium_actor_name(actor),
thorium_actor_get_mailbox_size(actor));
++i;
}
}
| 2.328125 | 2 |
2024-11-18T22:25:10.593194+00:00 | 2021-07-14T21:21:08 | f543caeda47add1fdc0c11a5b773985d48213b47 | {
"blob_id": "f543caeda47add1fdc0c11a5b773985d48213b47",
"branch_name": "refs/heads/main",
"committer_date": "2021-07-14T21:21:08",
"content_id": "d18c74212aa3fdde85ca22aafe50f1d69dd8fe35",
"detected_licenses": [
"MIT"
],
"directory_id": "d8fa547f4c4459fd1de274c3abf018d1f681fd9c",
"extension": "c",
"filename": "monitor-brightness.c",
"fork_events_count": 0,
"gha_created_at": "2021-07-13T06:46:12",
"gha_event_created_at": "2021-07-13T06:46:13",
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 385503409,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3779,
"license": "MIT",
"license_type": "permissive",
"path": "/monitor-brightness.c",
"provenance": "stackv2-0115.json.gz:110070",
"repo_name": "harindaka/monitor-brightness",
"revision_date": "2021-07-14T21:21:08",
"revision_id": "e334b206b02be4513d574f414be50b7604cd4e62",
"snapshot_id": "2b714c5544fb4d483677671b1f2728c9877508f9",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/harindaka/monitor-brightness/e334b206b02be4513d574f414be50b7604cd4e62/monitor-brightness.c",
"visit_date": "2023-06-17T02:16:40.806886"
} | stackv2 | #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/inotify.h>
int read_value(char *FILENAME)
{
char c_value[8];
int value;
FILE *fp;
if ((fp = fopen(FILENAME, "r")) == NULL)
{
printf("Error! opening file");
// Program exits if file pointer returns NULL.
exit(1);
}
// reads text until newline is encountered
fscanf(fp, "%[^\n]", c_value);
fclose(fp);
// printf("Data from the file:\n%s", c_value);
sscanf(c_value, "%d", &value);
// printf("%d", value);
return value;
}
int getWordLenght(char *wordArray[], int size_of_array)
{
int item_of_array = size_of_array / sizeof(&wordArray);
int wordLenght = 0;
for (int i = 0; i < item_of_array; ++i)
{
wordLenght += strlen(wordArray[i]);
}
return ++wordLenght;
}
double getXrandrBrightness()
{
FILE *fp;
double value;
char command_buffer[8];
fp = popen("xrandr --verbose --current | grep -i Brightness | tail -c 5", "r");
fgets(command_buffer, sizeof(command_buffer), fp);
// printf("%s", command_buffer);
pclose(fp);
sscanf(command_buffer, "%lf", &value); // Convert char to double
// printf("%lf", value);
return value;
}
void getConcatedWord(char *command_buffer, char *wordArray[], int size_of_array, int wordLenght)
{
int item_of_array = size_of_array / sizeof(&wordArray);
char concatedWord[wordLenght];
memset(concatedWord, '\0', wordLenght);
for (int i = 0; i < item_of_array; ++i)
{
strcat(concatedWord, wordArray[i]);
}
// printf("%d\n", wordLenght);
// printf("%s\n", concatedWord);
strcpy(command_buffer, concatedWord);
}
void contorllXrandrBrightness(char *monitorName, double brightnessRate)
{
char command_rate[16];
sprintf(command_rate, "%f", brightnessRate); // Convert double to char
char *command[] = {"xrandr --output ", monitorName, " --brightness ", command_rate};
int command_len = getWordLenght(command, sizeof(command));
char *command_buffer = malloc(command_len);
getConcatedWord(command_buffer, command, sizeof(command), command_len);
// printf("%s\n", command_buffer);
pclose(popen(command_buffer, "r"));
free(command_buffer);
}
int main(int argc, char *argv[])
{
int fd, wd;
char *FILE_NAME1 = "/sys/class/backlight/intel_backlight/brightness"; // File address for backlight brightness.
char *FILE_NAME2 = "/sys/class/backlight/intel_backlight/max_brightness"; // File address for backlight max brightness vlaue.
char *Monitor;
if (argv[1] == NULL)
{
printf("Usage: monitor-brightness [monitor_name]\n\nIf you want to find your monitor_name, use:\n xrandr | grep ' connected ' | awk '{ print$1 }'\n");
return 0;
}
else
{
Monitor = argv[1];
}
struct inotify_event *event;
// char buf[BUFSIZ];
char buf[128];
int target_value, max_value;
double current_rate, target_rate, compareGAP;
fd = inotify_init();
if (fd < 0)
{
perror("inotify_init");
}
wd = inotify_add_watch(fd, FILE_NAME1, IN_CLOSE_WRITE);
if (wd < 0)
{
perror("inotify_add-watch");
}
sleep(1);
do
{
current_rate = getXrandrBrightness();
target_value = read_value(FILE_NAME1);
max_value = read_value(FILE_NAME2);
target_rate = (double)target_value / max_value * 0.9 + 0.1; // Set theshold, let brightness rate never less than 0.1.
compareGAP = target_rate - current_rate;
if (compareGAP >= 0.006 || compareGAP <= -0.004)
{
contorllXrandrBrightness(Monitor, target_rate);
}
} while (read(fd, buf, sizeof(buf) - 1) > 0);
return 0;
}
| 2.5 | 2 |
2024-11-18T22:25:10.674817+00:00 | 2018-07-29T18:55:10 | cff512a7d17db2adf85dc8c8e87d4c970691cf15 | {
"blob_id": "cff512a7d17db2adf85dc8c8e87d4c970691cf15",
"branch_name": "refs/heads/master",
"committer_date": "2018-07-29T18:55:10",
"content_id": "9a74fe947381ef6c497f1b6bd8b9a5597a918df7",
"detected_licenses": [
"MIT"
],
"directory_id": "3edb5788c9fddc92ec8e01b225ba457d19a0c424",
"extension": "c",
"filename": "gearvr.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 142786950,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3884,
"license": "MIT",
"license_type": "permissive",
"path": "/src/gearvr.c",
"provenance": "stackv2-0115.json.gz:110199",
"repo_name": "Idorobots/gearvr-controller-driver",
"revision_date": "2018-07-29T18:55:10",
"revision_id": "714e93902485e1dd541376891a6603f86793c0a1",
"snapshot_id": "85cbbaab485083d359d6005cae628d207da2e79b",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Idorobots/gearvr-controller-driver/714e93902485e1dd541376891a6603f86793c0a1/src/gearvr.c",
"visit_date": "2020-03-24T15:20:24.926485"
} | stackv2 | #include "gearvr.h"
const uint16_t opt_mtu = 63; // NOTE 60 bytes of the actual packet data & 3 bytes of GATT header.
static void exchange_mtu_cb(guint8 status, const guint8 *pdu, guint16 plen, gpointer user_data) {
gattlib_context_t* conn_context = (gattlib_context_t*) user_data;
uint16_t mtu;
if (status != 0) {
printf("Exchange MTU Request failed.\n");
return;
}
if (!dec_mtu_resp(pdu, plen, &mtu)) {
printf("Protocol error.\n");
return;
}
mtu = MIN(mtu, opt_mtu);
if (g_attrib_set_mtu(conn_context->attrib, mtu))
printf("MTU was exchanged successfully: %d\n", mtu);
else
printf("Error exchanging MTU\n");
}
void notification_handler(const uuid_t* uuid, const uint8_t* data, size_t data_length, void* user_data) {
UNUSED(uuid);
UNUSED(user_data);
printf("Device status: ");
for (size_t i = 0; i < data_length; i++) {
printf("%02x ", data[i]);
}
printf("\n");
}
static void usage(char *argv[]) {
printf("%s <device_address>\n", argv[0]);
}
int main(int argc, char *argv[]) {
if (argc != 2) {
usage(argv);
return 1;
}
// Service UUIDs
uuid_t battery_level_uuid = CREATE_UUID16(BATTERY_UUID);
uuid_t gearvr_updates_uuid;
uuid_t gearvr_cmd_uuid;
if (gattlib_string_to_uuid(GEARVR_UPDATES_UUID, strlen(GEARVR_UPDATES_UUID) + 1, &gearvr_updates_uuid) < 0) {
return 1;
}
if (gattlib_string_to_uuid(GEARVR_CMD_UUID, strlen(GEARVR_CMD_UUID) + 1, &gearvr_cmd_uuid) < 0) {
return 1;
}
printf("Connecting to %s.\n", argv[1]);
gatt_connection_t *connection = gattlib_connect(NULL, argv[1], BDADDR_LE_PUBLIC, BT_SEC_MEDIUM, 0, 0);
if (connection == NULL) {
fprintf(stderr, "Fail to connect to the bluetooth device.\n");
return 1;
}
printf("Registering notification handler.\n");
gattlib_register_notification(connection, notification_handler, NULL);
printf("Setting the desired MTU size.\n");
gattlib_context_t *conn_context = connection->context;
gatt_exchange_mtu(conn_context->attrib, opt_mtu, exchange_mtu_cb, (void*) connection->context);
uint8_t buffer[100];
size_t len = sizeof(buffer);
printf("Reading battery level.\n");
size_t ret = gattlib_read_char_by_uuid(connection, &battery_level_uuid, buffer, &len);
if (ret) {
fprintf(stderr, "Failed to retrieve battery status.\n");
return 1;
}
printf("Battery level: %d%%\n", buffer[0]);
printf("Enabling notifications for the sensor service.\n");
ret = gattlib_notification_start(connection, &gearvr_updates_uuid);
if (ret) {
fprintf(stderr, "Fail to start notification.\n");
return 1;
}
printf("Reading device status.\n");
ret = gattlib_read_char_by_uuid(connection, &gearvr_updates_uuid, buffer, &len);
if (ret) {
fprintf(stderr, "Failed to retrieve device.\n");
return 1;
}
printf("Device status: ");
for (size_t i = 0; i < len; i++) {
printf("%02x ", buffer[i]);
}
printf("\n");
printf("Resetting the device.\n");
ret = gattlib_write_char_by_handle(connection, GEARVR_CMD_HANDLE, CMD_RESET, sizeof(CMD_RESET));
if (ret) {
fprintf(stderr, "Failed to reset device.\n");
return 1;
}
printf("Turning on the VR mode.\n");
ret = gattlib_write_char_by_handle(connection, GEARVR_CMD_HANDLE, CMD_VR_MODE, sizeof(CMD_VR_MODE));
if (ret) {
fprintf(stderr, "Failed to enable the VR mode on the device.\n");
return 1;
}
// NOTE Gotta wait for the device to actually enable the VR mode.
sleep(2);
printf("Turning on the sensor.\n");
ret = gattlib_write_char_by_handle(connection, GEARVR_CMD_HANDLE, CMD_SENSOR, sizeof(CMD_SENSOR));
if (ret) {
fprintf(stderr, "Failed to enable the sensor on the device.\n");
return 1;
}
GMainLoop *loop = g_main_loop_new(NULL, 0);
g_main_loop_run(loop);
g_main_loop_unref(loop);
gattlib_disconnect(connection);
puts("Done");
return 0;
}
| 2.640625 | 3 |
2024-11-18T22:25:10.851373+00:00 | 2021-06-01T17:16:03 | 9cf482f361d0a1b4a9b94b8fd2a91bce11a20556 | {
"blob_id": "9cf482f361d0a1b4a9b94b8fd2a91bce11a20556",
"branch_name": "refs/heads/main",
"committer_date": "2021-06-01T17:16:03",
"content_id": "a9fb20e079b954872ff9cf571376d32abbeadf5e",
"detected_licenses": [
"BSD-4-Clause-UC"
],
"directory_id": "2876e236635251aecc57163df71383a2064ac7cf",
"extension": "h",
"filename": "types.h",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 381179818,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1183,
"license": "BSD-4-Clause-UC",
"license_type": "permissive",
"path": "/inc/types.h",
"provenance": "stackv2-0115.json.gz:110457",
"repo_name": "WoodieGeek/josos",
"revision_date": "2021-06-01T17:16:03",
"revision_id": "2760da547cf478503567b5cb4e94f1442fe6f88c",
"snapshot_id": "4af2bb3e78257a688278338b52141576f90237de",
"src_encoding": "UTF-8",
"star_events_count": 4,
"url": "https://raw.githubusercontent.com/WoodieGeek/josos/2760da547cf478503567b5cb4e94f1442fe6f88c/inc/types.h",
"visit_date": "2023-06-04T21:16:09.799841"
} | stackv2 | #ifndef JOS_INC_TYPES_H
#define JOS_INC_TYPES_H
#include <stdint.h>
#include <stdbool.h>
#include <stddef.h>
typedef uintptr_t physaddr_t;
typedef ptrdiff_t ssize_t;
typedef int32_t off_t;
/* Efficient min and max operations */
#ifndef MIN
#define MIN(_a, _b) ({ \
typeof(_a) __a = (_a); \
typeof(_b) __b = (_b); \
__a <= __b ? __a : __b; })
#endif
#ifndef MAX
#define MAX(_a, _b) ({ \
typeof(_a) __a = (_a); \
typeof(_b) __b = (_b); \
__a >= __b ? __a : __b; })
#endif
/* Rounding operations (efficient when n is a power of 2) */
/* Round down to the nearest multiple of n */
#define ROUNDDOWN(a, n) ({ \
uint64_t __a = (uint64_t)(a); \
(typeof(a))(__a - __a % (n)); })
/* Round up to the nearest multiple of n */
#define ROUNDUP(a, n) ({ \
uint64_t __n = (uint64_t)(n); \
(typeof(a))(ROUNDDOWN((uint64_t)(a) + __n - 1, __n)); })
/* Round up to the nearest multiple of n */
#define CEILDIV(a, n) ({ \
uint64_t __n = (uint64_t)(n); \
(typeof(a))(((uint64_t)(a) + __n - 1)/__n); })
#endif /* !JOS_INC_TYPES_H */
| 2.578125 | 3 |
2024-11-18T22:25:10.929133+00:00 | 2021-10-04T21:36:08 | a7dc48fcb8100c831aa8273731efe6091ccb019f | {
"blob_id": "a7dc48fcb8100c831aa8273731efe6091ccb019f",
"branch_name": "refs/heads/openvx_1.3",
"committer_date": "2021-10-05T01:37:21",
"content_id": "9965c3b9187cd6a1be0cc6c7f14b61b63bcd20bd",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "4d223ede7b074646f43a5b16844b01edaa1b4554",
"extension": "c",
"filename": "test_lut.c",
"fork_events_count": 7,
"gha_created_at": "2018-11-16T01:33:26",
"gha_event_created_at": "2020-03-04T00:08:11",
"gha_language": "C",
"gha_license_id": "Apache-2.0",
"github_id": 157795731,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 18858,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/test_conformance/test_lut.c",
"provenance": "stackv2-0115.json.gz:110587",
"repo_name": "KhronosGroup/OpenVX-cts",
"revision_date": "2021-10-04T21:36:08",
"revision_id": "930f179dc667a424053716a56bd324b44d0c504a",
"snapshot_id": "c9c97a0d2796df0944c4b690a017ae0fccfc0fe6",
"src_encoding": "UTF-8",
"star_events_count": 11,
"url": "https://raw.githubusercontent.com/KhronosGroup/OpenVX-cts/930f179dc667a424053716a56bd324b44d0c504a/test_conformance/test_lut.c",
"visit_date": "2023-09-05T23:45:22.067836"
} | stackv2 | /*
* Copyright (c) 2012-2017 The Khronos Group Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#if defined OPENVX_USE_ENHANCED_VISION || OPENVX_CONFORMANCE_VISION
#include "test_engine/test.h"
#include <VX/vx.h>
#include <VX/vxu.h>
#include <string.h>
TESTCASE(LUT, CT_VXContext, ct_setup_vx_context, 0)
static vx_size lut_count(vx_enum data_type)
{
vx_size count = 0;
switch (data_type)
{
case VX_TYPE_UINT8:
count = 256;
break;
case VX_TYPE_INT16:
count = 65536;
break;
}
return count;
}
static vx_size lut_size(vx_enum data_type)
{
vx_size size = 0;
switch (data_type)
{
case VX_TYPE_UINT8:
size = 256*sizeof(vx_uint8);
break;
case VX_TYPE_INT16:
size = 65536*sizeof(vx_int16);
break;
}
return size;
}
static vx_lut lut_create(vx_context context, void* data, vx_enum data_type)
{
vx_size count = lut_count(data_type);
vx_size size = lut_size(data_type);
vx_lut lut = vxCreateLUT(context, data_type, count);
void* ptr = NULL;
ASSERT_VX_OBJECT_(return 0, lut, VX_TYPE_LUT);
vx_map_id map_id;
VX_CALL_(return 0, vxMapLUT(lut, &map_id, &ptr, VX_WRITE_ONLY, VX_MEMORY_TYPE_HOST, 0));
ASSERT_(return 0, ptr);
memcpy(ptr, data, size);
VX_CALL_(return 0, vxUnmapLUT(lut, map_id));
return lut;
}
static vx_lut virtual_lut_create(vx_context context, void* data, vx_enum data_type)
{
vx_graph graph = 0;
graph = vxCreateGraph(context);
vx_size count = lut_count(data_type);
vx_lut lut = vxCreateVirtualLUT(graph, data_type, count);
vxReleaseGraph(&graph);
return lut;
}
static void lut_data_fill_identity(void* data, vx_enum data_type)
{
int i;
switch (data_type)
{
case VX_TYPE_UINT8:
{
vx_int32 offset = 0;
vx_uint8* data8 = (vx_uint8*)data;
for (i = 0; i < 256; ++i)
data8[i] = i - offset;
}
break;
case VX_TYPE_INT16:
{
vx_int32 offset = 65536/2;
vx_int16* data16 = (vx_int16*)data;
for (i = 0; i < 65536; ++i)
data16[i] = i - offset;
}
break;
}
}
static void lut_data_fill_random(void* data, vx_enum data_type)
{
uint64_t* seed = &CT()->seed_;
int i;
switch (data_type)
{
case VX_TYPE_UINT8:
{
vx_uint8* data8 = (vx_uint8*)data;
for (i = 0; i < 256; ++i)
data8[i] = (vx_uint8)CT_RNG_NEXT_INT(*seed, 0, 256);
}
break;
case VX_TYPE_INT16:
{
vx_int16* data16 = (vx_int16*)data;
for (i = 0; i < 65536; ++i)
data16[i] = (vx_int16)CT_RNG_NEXT_INT(*seed, (uint32_t)-32768, 32768);
}
break;
}
}
TEST(LUT, testNodeCreation)
{
vx_context context = context_->vx_context_;
vx_image src_image = 0, dst_image = 0;
vx_uint8 lut_data[256];
vx_lut lut = 0;
vx_graph graph = 0;
vx_node node = 0;
vx_enum data_type = VX_TYPE_UINT8;
src_image = vxCreateImage(context, 128, 128, VX_DF_IMAGE_U8);
ASSERT_VX_OBJECT(src_image, VX_TYPE_IMAGE);
dst_image = vxCreateImage(context, 128, 128, VX_DF_IMAGE_U8);
ASSERT_VX_OBJECT(dst_image, VX_TYPE_IMAGE);
ASSERT_NO_FAILURE(lut_data_fill_identity(lut_data, data_type));
ASSERT_VX_OBJECT(lut = lut_create(context, lut_data, data_type), VX_TYPE_LUT);
{
vx_enum lut_type;
vx_size lut_count, lut_size;
VX_CALL(vxQueryLUT(lut, VX_LUT_TYPE, &lut_type, sizeof(lut_type)));
if (VX_TYPE_UINT8 != lut_type)
{
CT_FAIL("check for LUT attribute VX_LUT_TYPE failed\n");
}
VX_CALL(vxQueryLUT(lut, VX_LUT_COUNT, &lut_count, sizeof(lut_count)));
if (256 != lut_count)
{
CT_FAIL("check for LUT attribute VX_LUT_COUNT failed\n");
}
VX_CALL(vxQueryLUT(lut, VX_LUT_SIZE, &lut_size, sizeof(lut_size)));
if (256 > lut_size)
{
CT_FAIL("check for LUT attribute VX_LUT_SIZE failed\n");
}
}
graph = vxCreateGraph(context);
ASSERT_VX_OBJECT(graph, VX_TYPE_GRAPH);
node = vxTableLookupNode(graph, src_image, lut, dst_image);
ASSERT_VX_OBJECT(node, VX_TYPE_NODE);
VX_CALL(vxReleaseNode(&node));
VX_CALL(vxReleaseGraph(&graph));
VX_CALL(vxReleaseLUT(&lut));
VX_CALL(vxReleaseImage(&dst_image));
VX_CALL(vxReleaseImage(&src_image));
ASSERT(node == 0);
ASSERT(graph == 0);
ASSERT(lut == 0);
ASSERT(dst_image == 0);
ASSERT(src_image == 0);
}
TEST(LUT, testVirtualNodeCreation)
{
vx_context context = context_->vx_context_;
vx_image src_image = 0, dst_image = 0;
vx_uint8 lut_data[256];
vx_lut lut = 0;
src_image = vxCreateImage(context, 128, 128, VX_DF_IMAGE_U8);
ASSERT_VX_OBJECT(src_image, VX_TYPE_IMAGE);
vx_graph graph = 0;
vx_node node = 0;
vx_enum data_type = VX_TYPE_UINT8;
dst_image = vxCreateImage(context, 128, 128, VX_DF_IMAGE_U8);
ASSERT_VX_OBJECT(dst_image, VX_TYPE_IMAGE);
ASSERT_NO_FAILURE(lut_data_fill_identity(lut_data, data_type));
ASSERT_VX_OBJECT(lut = virtual_lut_create(context, lut_data, data_type), VX_TYPE_LUT);
{
vx_enum lut_type;
vx_size lut_count, lut_size;
VX_CALL(vxQueryLUT(lut, VX_LUT_TYPE, &lut_type, sizeof(lut_type)));
if (VX_TYPE_UINT8 != lut_type)
{
CT_FAIL("check for LUT attribute VX_LUT_TYPE failed\n");
}
VX_CALL(vxQueryLUT(lut, VX_LUT_COUNT, &lut_count, sizeof(lut_count)));
if (256 != lut_count)
{
CT_FAIL("check for LUT attribute VX_LUT_COUNT failed\n");
}
VX_CALL(vxQueryLUT(lut, VX_LUT_SIZE, &lut_size, sizeof(lut_size)));
if (256 > lut_size)
{
CT_FAIL("check for LUT attribute VX_LUT_SIZE failed\n");
}
}
graph = vxCreateGraph(context);
ASSERT_VX_OBJECT(graph, VX_TYPE_GRAPH);
node = vxTableLookupNode(graph, src_image, lut, dst_image);
ASSERT_VX_OBJECT(node, VX_TYPE_NODE);
VX_CALL(vxReleaseNode(&node));
VX_CALL(vxReleaseGraph(&graph));
VX_CALL(vxReleaseLUT(&lut));
VX_CALL(vxReleaseImage(&dst_image));
VX_CALL(vxReleaseImage(&src_image));
ASSERT(node == 0);
ASSERT(graph == 0);
ASSERT(lut == 0);
ASSERT(dst_image == 0);
ASSERT(src_image == 0);
}
// Generate input to cover these requirements:
// There should be a image with randomly generated pixel intensities.
static CT_Image lut_image_generate_random(const char* fileName, int width, int height, vx_enum data_type)
{
CT_Image image = 0;
switch (data_type)
{
case VX_TYPE_UINT8:
image = ct_allocate_ct_image_random(width, height, VX_DF_IMAGE_U8, &CT()->seed_, 0, 256);
break;
case VX_TYPE_INT16:
image = ct_allocate_ct_image_random(width, height, VX_DF_IMAGE_S16, &CT()->seed_, -32768, 32768);
break;
}
ASSERT_(return 0, image != 0);
return image;
}
static CT_Image lut_image_read(const char* fileName, int width, int height, vx_enum data_type)
{
CT_Image image8 = NULL;
ASSERT_(return 0, width == 0 && height == 0);
image8 = ct_read_image(fileName, 1);
ASSERT_(return 0, image8);
ASSERT_(return 0, image8->format == VX_DF_IMAGE_U8);
switch (data_type)
{
case VX_TYPE_UINT8:
return image8;
case VX_TYPE_INT16:
{
vx_int32 offset = 65536/2;
CT_Image image16 = ct_allocate_image(image8->width, image8->height, VX_DF_IMAGE_S16);
if (image16)
{
CT_FILL_IMAGE_16S(return 0, image16,
{
vx_uint8 value8 = *CT_IMAGE_DATA_PTR_8U(image8, x, y);
vx_uint16 value16 = ((vx_uint16)value8 << 8) | value8;
vx_int16 res = (vx_int16)((vx_int32)value16 - offset);
*dst_data = res;
});
}
return image16;
}
}
return NULL;
}
// data_type == VX_TYPE_UINT8
static vx_uint8 lut_calculate_u8(CT_Image src, uint32_t x, uint32_t y, void* lut_data)
{
vx_uint8* lut_data8 = (vx_uint8*)lut_data;
vx_int32 offset = 0;
vx_uint8 value = *CT_IMAGE_DATA_PTR_8U(src, x, y);
vx_uint8 res = lut_data8[offset + value];
return res;
}
// data_type == VX_TYPE_INT16
static vx_int16 lut_calculate_s16(CT_Image src, uint32_t x, uint32_t y, void* lut_data)
{
vx_int16* lut_data16 = (vx_int16*)lut_data;
vx_int32 offset = 65536/2;
vx_int16 value = *CT_IMAGE_DATA_PTR_16S(src, x, y);
vx_int16 res = lut_data16[offset + value];
return res;
}
static CT_Image lut_create_reference_image(CT_Image src, void* lut_data, vx_enum data_type)
{
CT_Image dst;
switch (data_type)
{
case VX_TYPE_UINT8:
CT_ASSERT_(return NULL, src->format == VX_DF_IMAGE_U8);
break;
case VX_TYPE_INT16:
CT_ASSERT_(return NULL, src->format == VX_DF_IMAGE_S16);
break;
}
dst = ct_allocate_image(src->width, src->height, src->format);
switch (data_type)
{
case VX_TYPE_UINT8:
CT_FILL_IMAGE_8U(return 0, dst,
{
uint8_t res = lut_calculate_u8(src, x, y, lut_data);
*dst_data = res;
});
break;
case VX_TYPE_INT16:
CT_FILL_IMAGE_16S(return 0, dst,
{
int16_t res = lut_calculate_s16(src, x, y, lut_data);
*dst_data = res;
});
break;
}
return dst;
}
static void lut_check(CT_Image src, CT_Image dst, void* lut_data, vx_enum data_type)
{
CT_Image dst_ref = NULL;
ASSERT(src && dst);
ASSERT_NO_FAILURE(dst_ref = lut_create_reference_image(src, lut_data, data_type));
EXPECT_EQ_CTIMAGE(dst_ref, dst);
#if 0
if (CT_HasFailure())
{
int i = 0;
printf("=== LUT ===\n");
switch (data_type)
{
case VX_TYPE_UINT8:
for (i = 0; i < 256; ++i)
printf("%3d:%3d ", i, (int)((vx_uint8*)lut_data)[i]);
break;
case VX_TYPE_INT16:
for (i = 0; i < 65536; ++i)
printf("%5d:%6d ", i, (int)((vx_int16*)lut_data)[i]);
break;
}
printf("\n");
printf("=== SRC ===\n");
ct_dump_image_info(src);
printf("=== DST ===\n");
ct_dump_image_info(dst);
printf("=== EXPECTED ===\n");
ct_dump_image_info(dst_ref);
}
#endif
}
typedef struct {
const char* testName;
CT_Image (*generator)(const char* fileName, int width, int height, vx_enum data_type);
const char* fileName;
void (*lut_generator)(void* data, vx_enum data_type);
int width, height;
vx_enum data_type;
} Arg;
#define ADD_LUT_GENERATOR(testArgName, nextmacro, ...) \
CT_EXPAND(nextmacro(testArgName "/LutIdentity", __VA_ARGS__, lut_data_fill_identity)), \
CT_EXPAND(nextmacro(testArgName "/LutRandom", __VA_ARGS__, lut_data_fill_random))
#define ADD_TYPE(testArgName, nextmacro, ...) \
CT_EXPAND(nextmacro(testArgName "/U8", __VA_ARGS__, VX_TYPE_UINT8)), \
CT_EXPAND(nextmacro(testArgName "/S16", __VA_ARGS__, VX_TYPE_INT16))
#define LUT_PARAMETERS \
CT_GENERATE_PARAMETERS("randomInput", ADD_LUT_GENERATOR, ADD_SIZE_SMALL_SET, ADD_TYPE, ARG, lut_image_generate_random, NULL), \
CT_GENERATE_PARAMETERS("lena", ADD_LUT_GENERATOR, ADD_SIZE_NONE, ADD_TYPE, ARG, lut_image_read, "lena.bmp")
TEST_WITH_ARG(LUT, testGraphProcessing, Arg,
LUT_PARAMETERS
)
{
vx_enum data_type = arg_->data_type;
vx_context context = context_->vx_context_;
vx_image src_image = 0, dst_image = 0;
vx_graph graph = 0;
vx_node node = 0;
CT_Image src = NULL, dst = NULL;
void* lut_data;
vx_lut lut;
vx_size size;
size = lut_size(data_type);
lut_data = ct_alloc_mem(size);
ASSERT(lut_data != 0);
ASSERT_NO_FAILURE(src = arg_->generator(arg_->fileName, arg_->width, arg_->height, data_type));
ASSERT_VX_OBJECT(src_image = ct_image_to_vx_image(src, context), VX_TYPE_IMAGE);
ASSERT_NO_FAILURE(arg_->lut_generator(lut_data, data_type));
ASSERT_VX_OBJECT(lut = lut_create(context, lut_data, data_type), VX_TYPE_LUT);
dst_image = ct_create_similar_image(src_image);
ASSERT_VX_OBJECT(dst_image, VX_TYPE_IMAGE);
graph = vxCreateGraph(context);
ASSERT_VX_OBJECT(graph, VX_TYPE_GRAPH);
node = vxTableLookupNode(graph, src_image, lut, dst_image);
ASSERT_VX_OBJECT(node, VX_TYPE_NODE);
VX_CALL(vxVerifyGraph(graph));
VX_CALL(vxProcessGraph(graph));
ASSERT_NO_FAILURE(dst = ct_image_from_vx_image(dst_image));
ASSERT_NO_FAILURE(lut_check(src, dst, lut_data, data_type));
VX_CALL(vxReleaseNode(&node));
VX_CALL(vxReleaseGraph(&graph));
ASSERT(node == 0);
ASSERT(graph == 0);
VX_CALL(vxReleaseLUT(&lut));
VX_CALL(vxReleaseImage(&dst_image));
VX_CALL(vxReleaseImage(&src_image));
ASSERT(lut == 0);
ASSERT(dst_image == 0);
ASSERT(src_image == 0);
ct_free_mem(lut_data);
}
TEST_WITH_ARG(LUT, testImmediateProcessing, Arg,
LUT_PARAMETERS
)
{
vx_enum data_type = arg_->data_type;
vx_context context = context_->vx_context_;
vx_image src_image = 0, dst_image = 0;
CT_Image src = NULL, dst = NULL;
void* lut_data;
vx_lut lut;
vx_size size;
size = lut_size(data_type);
lut_data = ct_alloc_mem(size);
ASSERT(lut_data != 0);
ASSERT_NO_FAILURE(src = arg_->generator(arg_->fileName, arg_->width, arg_->height, data_type));
ASSERT_VX_OBJECT(src_image = ct_image_to_vx_image(src, context), VX_TYPE_IMAGE);
ASSERT_NO_FAILURE(arg_->lut_generator(lut_data, data_type));
ASSERT_VX_OBJECT(lut = lut_create(context, lut_data, data_type), VX_TYPE_LUT);
dst_image = ct_create_similar_image(src_image);
ASSERT_VX_OBJECT(dst_image, VX_TYPE_IMAGE);
VX_CALL(vxuTableLookup(context, src_image, lut, dst_image));
ASSERT_NO_FAILURE(dst = ct_image_from_vx_image(dst_image));
ASSERT_NO_FAILURE(lut_check(src, dst, lut_data, data_type));
VX_CALL(vxReleaseLUT(&lut));
VX_CALL(vxReleaseImage(&dst_image));
VX_CALL(vxReleaseImage(&src_image));
ASSERT(lut == 0);
ASSERT(dst_image == 0);
ASSERT(src_image == 0);
ct_free_mem(lut_data);
}
typedef struct {
const char* name;
vx_enum type;
} data_type_arg;
TEST_WITH_ARG(LUT, test_vxCopyLUT, data_type_arg,
ARG_ENUM(VX_TYPE_UINT8),
ARG_ENUM(VX_TYPE_INT16))
{
vx_context context = context_->vx_context_;
vx_enum data_type = arg_->type;
vx_lut lut;
vx_size size = lut_size(data_type);
vx_size i;
void* identity_data = ct_alloc_mem(size);
ASSERT(identity_data != 0);
ASSERT_NO_FAILURE(lut_data_fill_identity(identity_data, data_type));
ASSERT_VX_OBJECT(lut = lut_create(context, identity_data, data_type), VX_TYPE_LUT);
/* read only mode */
void* user_data = ct_alloc_mem(size);
VX_CALL(vxCopyLUT(lut, user_data, VX_READ_ONLY, VX_MEMORY_TYPE_HOST));
/* Check */
for (i = 0; i < size; i++)
{
ASSERT(((vx_uint8*)user_data)[i] == ((vx_uint8*)identity_data)[i]);
}
/* write only mode */
void* random_data = ct_alloc_mem(size);
ASSERT_NO_FAILURE(lut_data_fill_random(random_data, data_type));
VX_CALL(vxCopyLUT(lut, random_data, VX_WRITE_ONLY, VX_MEMORY_TYPE_HOST));
/* Check */
vx_map_id map_id;
void* lut_data = NULL;
VX_CALL(vxMapLUT(lut, &map_id, &lut_data, VX_READ_ONLY, VX_MEMORY_TYPE_HOST, 0));
for (i = 0; i < size; i++)
{
ASSERT(((vx_uint8*)lut_data)[i] == ((vx_uint8*)random_data)[i]);
}
VX_CALL(vxUnmapLUT(lut, map_id));
VX_CALL(vxReleaseLUT(&lut));
ASSERT(lut == 0);
ct_free_mem(identity_data);
ct_free_mem(user_data);
ct_free_mem(random_data);
}
TEST_WITH_ARG(LUT, test_vxMapLUTWrite, data_type_arg,
ARG_ENUM(VX_TYPE_UINT8),
ARG_ENUM(VX_TYPE_INT16))
{
vx_context context = context_->vx_context_;
vx_enum data_type = arg_->type;
vx_lut lut;
vx_size size = lut_size(data_type);
void* identity_data = ct_alloc_mem(size);
vx_size i;
ASSERT(identity_data != 0);
ASSERT_NO_FAILURE(lut_data_fill_identity(identity_data, data_type));
ASSERT_VX_OBJECT(lut = lut_create(context, identity_data, data_type), VX_TYPE_LUT);
/* Read and write mode, read */
vx_map_id map_id;
void* lut_data = NULL;
VX_CALL(vxMapLUT(lut, &map_id, &lut_data, VX_READ_AND_WRITE, VX_MEMORY_TYPE_HOST, 0));
/* Check */
for (i = 0; i < size; i++)
{
ASSERT(((vx_uint8*)lut_data)[i] == ((vx_uint8*)identity_data)[i]);
}
/* Read and write mode, write */
void* random_data = ct_alloc_mem(size);
ASSERT_NO_FAILURE(lut_data_fill_random(random_data, data_type));
memcpy(lut_data, random_data, size);
VX_CALL(vxUnmapLUT(lut, map_id));
/* Check */
lut_data = NULL;
VX_CALL(vxMapLUT(lut, &map_id, &lut_data, VX_READ_ONLY, VX_MEMORY_TYPE_HOST, 0));
for (i = 0; i < size; i++)
{
ASSERT(((vx_uint8*)lut_data)[i] == ((vx_uint8*)random_data)[i]);
}
VX_CALL(vxUnmapLUT(lut, map_id));
/* Write only mode */
VX_CALL(vxMapLUT(lut, &map_id, &lut_data, VX_READ_AND_WRITE, VX_MEMORY_TYPE_HOST, 0));
ASSERT_NO_FAILURE(lut_data_fill_identity(lut_data, data_type));
VX_CALL(vxUnmapLUT(lut, map_id));
/* Check */
lut_data = NULL;
VX_CALL(vxMapLUT(lut, &map_id, &lut_data, VX_READ_ONLY, VX_MEMORY_TYPE_HOST, 0));
for ( i = 0; i < size; i++)
{
ASSERT(((vx_uint8*)lut_data)[i] == ((vx_uint8*)identity_data)[i]);
}
VX_CALL(vxUnmapLUT(lut, map_id));
VX_CALL(vxReleaseLUT(&lut));
ASSERT(lut == 0);
ct_free_mem(identity_data);
ct_free_mem(random_data);
}
TESTCASE_TESTS(LUT,
testNodeCreation,
testVirtualNodeCreation,
testGraphProcessing,
testImmediateProcessing,
test_vxCopyLUT,
test_vxMapLUTWrite)
#endif //OPENVX_USE_ENHANCED_VISION || OPENVX_CONFORMANCE_VISION
| 2.09375 | 2 |
2024-11-18T22:25:11.158847+00:00 | 2017-09-13T11:25:05 | f3ab6a5f86cf5b986cb72fa0b58fb7fc9ffda8df | {
"blob_id": "f3ab6a5f86cf5b986cb72fa0b58fb7fc9ffda8df",
"branch_name": "refs/heads/master",
"committer_date": "2017-09-13T11:25:05",
"content_id": "96ad9a1cba2b981a0db8160a4aa2fa738ba1d0cc",
"detected_licenses": [
"MIT"
],
"directory_id": "6bd2ae8ac75057c462f11c627bfd0cf7e94fc665",
"extension": "h",
"filename": "pmm_read_routines.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": 1167,
"license": "MIT",
"license_type": "permissive",
"path": "/Source/pmm_read_routines.h",
"provenance": "stackv2-0115.json.gz:110847",
"repo_name": "sspeng/ParallelMatrixMarket",
"revision_date": "2017-09-13T11:25:05",
"revision_id": "cd792f4cd88b804a65b19a27a076c968190faf1c",
"snapshot_id": "863bf24009f5ecb5e991e4993cff457a2b80c9d1",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/sspeng/ParallelMatrixMarket/cd792f4cd88b804a65b19a27a076c968190faf1c/Source/pmm_read_routines.h",
"visit_date": "2021-06-26T06:26:01.649110"
} | stackv2 | /*! \file pmm_read_routines.h
\brief The core routines you need to call to read the matrix market file.
*/
#ifndef READROUTINES_h
#define READROUTINES_h
#include "pmm_data.h"
#include "pmm_header.h"
#include <stdlib.h>
/******************************************************************************/
/*! PMM_ReadHeader
Read in the header information of the matrix market file.
\param file_name the name of the file to read.
\param header the matrix market header data structure to store the result.
\param comm the mpi communicator which we're using.
*/
int PMM_ReadHeader(char *file_name, MPI_Comm comm, PMM_Header *header);
/******************************************************************************/
/*! PMM_ReadData
Read in the full data from a matrix market file.
\param file_name the name of the file to read.
\param header the matrix market header data computed by ReadHeader.
\param data the matrix market data which we'll read in.
\param comm the mpi communicator which we're using.
\return EXIT_SUCCESS if there are no problems.
*/
int PMM_ReadData(char *file_name, PMM_Header header, MPI_Comm comm, \
PMM_Data* data);
#endif
| 2.140625 | 2 |
2024-11-18T22:25:11.435172+00:00 | 2018-04-19T09:14:00 | 097d094fe08fb333614117df8d7d584140e26b1e | {
"blob_id": "097d094fe08fb333614117df8d7d584140e26b1e",
"branch_name": "refs/heads/master",
"committer_date": "2018-04-19T09:14:00",
"content_id": "67a384fb7f38e1393a5abe2699f3da2296703d2d",
"detected_licenses": [
"MIT"
],
"directory_id": "c0f1e0525f35c71fd7384f81611a28c4cd18cd69",
"extension": "c",
"filename": "mzd_test.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 10235,
"license": "MIT",
"license_type": "permissive",
"path": "/tests/mzd_test.c",
"provenance": "stackv2-0115.json.gz:110976",
"repo_name": "chargen/Picnic",
"revision_date": "2018-04-19T09:14:00",
"revision_id": "8876f471a0b66dc0b92397e5eda32eb28c867e96",
"snapshot_id": "5c58cb6aa454e3b64b9d7201e3d12e0c536b155e",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/chargen/Picnic/8876f471a0b66dc0b92397e5eda32eb28c867e96/tests/mzd_test.c",
"visit_date": "2020-03-12T08:12:29.143512"
} | stackv2 | #include "../mzd_additional.h"
#include <m4ri/m4ri.h>
#include "utils.h"
static void test_mzd_local_equal(void) {
for (unsigned int i = 0; i < 10; ++i) {
mzd_local_t* a = mzd_local_init(1, (i + 1) * 64);
mzd_randomize_ssl(a);
mzd_local_t* b = mzd_local_copy(NULL, a);
if (mzd_local_equal(a, b)) {
printf("equal: ok [%u]\n", (i + 1) * 64);
}
b = mzd_xor(b, b, a);
if (mzd_local_equal(a, b)) {
printf("equal: ok [%u]\n", (i + 1) * 64);
}
mzd_local_free(a);
mzd_local_free(b);
}
}
static int test_mzd_mul_avx(void) {
int ret = 0;
#ifdef WITH_AVX2
unsigned int size = 192;
mzd_t* A = mzd_init(size, size);
mzd_t* v = mzd_init(1, size);
mzd_t* c = mzd_init(1, size);
mzd_randomize(A);
mzd_randomize(v);
mzd_randomize(c);
mzd_local_t* Al = mzd_convert(A);
mzd_local_t* vl = mzd_convert(v);
mzd_local_t* c2 = mzd_convert(c);
for (unsigned int k = 0; k < 3; ++k) {
mzd_t* r = mzd_mul_naive(c, v, A);
mzd_local_t* rl = mzd_mul_v_avx(c2, vl, Al);
mzd_local_t* rc = mzd_convert(r);
if (!mzd_local_equal(rc, rl)) {
printf("mul: fail [%u x %u]\n", size, size);
ret = -1;
} else {
printf("mul: ok [%u x %u]\n", size, size);
}
mzd_local_free(rc);
}
mzd_free(A);
mzd_free(v);
mzd_free(c);
mzd_local_free(c2);
mzd_local_free(Al);
mzd_local_free(vl);
#endif
return ret;
}
#ifdef WITH_NEON
static void test_mzd_mul_vl_neon_192(void) {
unsigned int size = 192;
mzd_local_t* A = mzd_init(size, size);
mzd_local_t* v = mzd_init(1, size);
mzd_local_t* c = mzd_init(1, size);
mzd_randomize(A);
mzd_randomize(v);
mzd_randomize(c);
mzd_local_t* Al = mzd_local_copy(NULL, A);
mzd_local_t* All = mzd_precompute_matrix_lookup(Al);
mzd_local_t* vl = mzd_local_copy(NULL, v);
mzd_local_t* c2 = mzd_local_copy(NULL, c);
for (unsigned int k = 0; k < 3; ++k) {
mzd_local_t* r = mzd_mul_naive(c, v, A);
mzd_local_t* rl = mzd_mul_vl_neon_multiple_of_128(c2, vl, All);
if (!mzd_local_equal(r, rl)) {
printf("mul: fail [%u x %u]\n", size, size);
printf("r = ");
mzd_print(r);
printf("rl = ");
mzd_print(rl);
} else {
printf("mul: ok [%u x %u]\n", size, size);
}
}
mzd_free(A);
mzd_free(v);
mzd_free(c);
mzd_local_free(c2);
mzd_local_free(Al);
mzd_local_free(vl);
}
static void test_mzd_mul_vl_neon_256(void) {
unsigned int size = 256;
mzd_local_t* A = mzd_init(size, size);
mzd_local_t* v = mzd_init(1, size);
mzd_local_t* c = mzd_init(1, size);
mzd_randomize(A);
mzd_randomize(v);
mzd_randomize(c);
mzd_local_t* Al = mzd_local_copy(NULL, A);
mzd_local_t* All = mzd_precompute_matrix_lookup(Al);
mzd_local_t* vl = mzd_local_copy(NULL, v);
mzd_local_t* c2 = mzd_local_copy(NULL, c);
for (unsigned int k = 0; k < 3; ++k) {
mzd_local_t* r = mzd_mul_naive(c, v, A);
mzd_local_t* rl = mzd_mul_vl_neon_multiple_of_128(c2, vl, All);
if (!mzd_local_equal(r, rl)) {
printf("mul: fail [%u x %u]\n", size, size);
printf("r = ");
mzd_print(r);
printf("rl = ");
mzd_print(rl);
} else {
printf("mul: ok [%u x %u]\n", size, size);
}
}
mzd_free(A);
mzd_free(v);
mzd_free(c);
mzd_local_free(c2);
mzd_local_free(Al);
mzd_local_free(vl);
}
static void test_mzd_addmul_vl_neon_192(void) {
unsigned int size = 192;
mzd_local_t* A = mzd_init(size, size);
mzd_local_t* v = mzd_init(1, size);
mzd_local_t* c = mzd_init(1, size);
mzd_randomize(A);
mzd_randomize(v);
mzd_randomize(c);
mzd_local_t* Al = mzd_local_copy(NULL, A);
mzd_local_t* All = mzd_precompute_matrix_lookup(Al);
mzd_local_t* vl = mzd_local_copy(NULL, v);
mzd_local_t* c2 = mzd_local_copy(NULL, c);
mzd_local_t* c3 = mzd_local_copy(NULL, c);
for (unsigned int k = 0; k < 3; ++k) {
mzd_local_t* r = mzd_addmul_naive(c, v, A);
mzd_local_t* rl2 = mzd_addmul_vl_neon(c3, vl, All);
if (!mzd_local_equal(r, rl2)) {
printf("addmul2: fail [%u x %u]\n", size, size);
printf("r = ");
mzd_print(r);
printf("rl = ");
mzd_print(rl2);
} else {
printf("addmul2: ok [%u x %u]\n", size, size);
}
}
mzd_free(A);
mzd_free(v);
mzd_free(c);
mzd_local_free(c2);
mzd_local_free(Al);
mzd_local_free(vl);
}
static void test_mzd_addmul_vl_neon_256(void) {
unsigned int size = 256;
mzd_local_t* A = mzd_init(size, size);
mzd_local_t* v = mzd_init(1, size);
mzd_local_t* c = mzd_init(1, size);
mzd_randomize(A);
mzd_randomize(v);
mzd_randomize(c);
mzd_local_t* Al = mzd_local_copy(NULL, A);
mzd_local_t* All = mzd_precompute_matrix_lookup(Al);
mzd_local_t* vl = mzd_local_copy(NULL, v);
mzd_local_t* c2 = mzd_local_copy(NULL, c);
mzd_local_t* c3 = mzd_local_copy(NULL, c);
for (unsigned int k = 0; k < 3; ++k) {
mzd_local_t* r = mzd_addmul_naive(c, v, A);
mzd_local_t* rl2 = mzd_addmul_vl_neon(c3, vl, All);
if (!mzd_local_equal(r, rl2)) {
printf("addmul2: fail [%u x %u]\n", size, size);
printf("r = ");
mzd_print(r);
printf("rl = ");
mzd_print(rl2);
} else {
printf("addmul2: ok [%u x %u]\n", size, size);
}
}
mzd_free(A);
mzd_free(v);
mzd_free(c);
mzd_local_free(c2);
mzd_local_free(Al);
mzd_local_free(vl);
}
#endif
static void test_mzd_mul(void) {
for (unsigned int i = 1; i <= 10; ++i) {
for (unsigned int j = 1; j <= 10; ++j) {
mzd_t* A = mzd_init(i * 64, j * 64);
mzd_t* v = mzd_init(1, i * 64);
mzd_t* c = mzd_init(1, j * 64);
mzd_randomize(A);
mzd_randomize(v);
mzd_randomize(c);
mzd_local_t* Al = mzd_convert(A);
mzd_local_t* All = mzd_precompute_matrix_lookup(Al);
mzd_local_t* vl = mzd_convert(v);
mzd_local_t* cl = mzd_convert(c);
mzd_local_t* cll = mzd_convert(c);
mzd_t* At = mzd_transpose(NULL, A);
mzd_t* vt = mzd_transpose(NULL, v);
mzd_t* c2 = mzd_copy(NULL, c);
mzd_t* c3 = mzd_transpose(NULL, c);
for (unsigned int k = 0; k < 3; ++k) {
mzd_local_t* r = mzd_mul_v(cl, vl, Al);
mzd_local_t* rl = mzd_mul_vl(cll, vl, All);
mzd_t* r2 = mzd_mul(c2, v, A, __M4RI_STRASSEN_MUL_CUTOFF);
mzd_t* r3 = mzd_mul(c3, At, vt, __M4RI_STRASSEN_MUL_CUTOFF);
if (!mzd_local_equal(r, rl)) {
printf("mul: fail [%u x %u]\n", i * 64, j * 64);
}
mzd_local_t* rc = mzd_convert(r2);
if (!mzd_local_equal(r, rc)) {
printf("mul: fail [%u x %u]\n", i * 64, j * 64);
}
mzd_local_free(rc);
mzd_t* r4 = mzd_transpose(NULL, r3);
if (mzd_cmp(r4, r2) != 0) {
printf("mul: fail [%u x %u]\n", i * 64, j * 64);
}
mzd_free(r4);
}
mzd_free(At);
mzd_free(A);
mzd_free(v);
mzd_free(c);
mzd_free(vt);
mzd_free(c2);
mzd_free(c3);
mzd_local_free(All);
mzd_local_free(Al);
mzd_local_free(cll);
mzd_local_free(cl);
mzd_local_free(vl);
}
}
}
static void test_mzd_shift(void) {
#ifdef WITH_OPT
#ifdef WITH_SSE2
if (CPU_SUPPORTS_SSE2) {
mzd_local_t* v = mzd_local_init(1, 128);
mzd_local_t* w = mzd_local_copy(NULL, v);
mzd_local_t* r = mzd_local_copy(NULL, v);
__m128i* wr = __builtin_assume_aligned(FIRST_ROW(w), 16);
for (unsigned int i = 0; i < 32; ++i) {
mzd_randomize_ssl(v);
mzd_local_copy(w, v);
mzd_shift_left(r, v, i);
*wr = mm128_shift_left(*wr, i);
if (mzd_cmp(r, w) != 0) {
printf("lshift fail\n");
}
}
for (unsigned int i = 0; i < 32; ++i) {
mzd_randomize_ssl(v);
mzd_local_copy(w, v);
mzd_shift_right(r, v, i);
*wr = mm128_shift_right(*wr, i);
if (mzd_cmp(r, w) != 0) {
printf("rshift fail\n");
}
}
mzd_local_free(w);
mzd_local_free(v);
mzd_local_free(r);
}
#endif
#ifdef WITH_AVX2
if (CPU_SUPPORTS_AVX2) {
mzd_local_t* v = mzd_local_init(1, 256);
mzd_local_t* w = mzd_local_copy(NULL, v);
mzd_local_t* r = mzd_local_copy(NULL, v);
__m256i* wr = __builtin_assume_aligned(FIRST_ROW(w), 32);
for (unsigned int i = 0; i < 32; ++i) {
mzd_randomize_ssl(v);
mzd_local_copy(w, v);
mzd_shift_left(r, v, i);
*wr = mm256_shift_left(*wr, i);
if (mzd_cmp(r, w) != 0) {
printf("lshift fail\n");
}
}
for (unsigned int i = 0; i < 32; ++i) {
mzd_randomize_ssl(v);
mzd_local_copy(w, v);
mzd_shift_right(r, v, i);
mm512_shift_right_avx(wr, wr, i);
if (mzd_cmp(r, w) != 0) {
printf("rshift fail\n");
}
}
mzd_local_free(w);
mzd_local_free(v);
mzd_local_free(r);
}
#endif
#ifdef WITH_NEON
if (CPU_SUPPORTS_NEON) {
mzd_local_t* v = mzd_local_init(1, 384);
mzd_local_t* w = mzd_local_copy(NULL, v);
mzd_local_t* r = mzd_local_copy(NULL, v);
uint32x4_t* wr = __builtin_assume_aligned(FIRST_ROW(w), alignof(uint32x4_t));
for (unsigned int i = 0; i < 32; ++i) {
mzd_randomize_ssl(v);
mzd_local_copy(w, v);
mzd_shift_left(r, v, i);
mm384_shift_left(wr, wr, i);
if (mzd_cmp(r, w) != 0) {
printf("lshift fail\nv = ");
mzd_print(v);
printf("r = ");
mzd_print(r);
printf("w = ");
mzd_print(w);
}
}
for (unsigned int i = 0; i < 32; ++i) {
mzd_randomize_ssl(v);
mzd_local_copy(w, v);
mzd_shift_right(r, v, i);
mm384_shift_right(wr, wr, i);
if (mzd_cmp(r, w) != 0) {
printf("rshift fail\nv = ");
mzd_print(v);
printf("r = ");
mzd_print(r);
printf("w = ");
mzd_print(w);
}
}
mzd_local_free(w);
mzd_local_free(v);
mzd_local_free(r);
}
#endif
#endif
}
int main() {
test_mzd_local_equal();
test_mzd_mul();
test_mzd_mul_avx();
test_mzd_shift();
#ifdef WITH_NEON
test_mzd_mul_vl_neon_192();
test_mzd_mul_vl_neon_256();
test_mzd_addmul_vl_neon_192();
test_mzd_addmul_vl_neon_256();
#endif
}
| 2.5625 | 3 |
2024-11-18T22:25:11.605640+00:00 | 2022-11-15T17:39:10 | 58676b9061b16ac649ad930ffad91c81f5afec6e | {
"blob_id": "58676b9061b16ac649ad930ffad91c81f5afec6e",
"branch_name": "refs/heads/master",
"committer_date": "2022-11-15T17:39:10",
"content_id": "8b012a72e672929780c4757b5aca79a7eb00ef16",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "73bdd0587ab569972a2b37567588b92489736ba7",
"extension": "c",
"filename": "phiompi.c",
"fork_events_count": 47,
"gha_created_at": "2015-04-16T00:21:32",
"gha_event_created_at": "2022-10-12T15:51:00",
"gha_language": "Fortran",
"gha_license_id": "BSD-3-Clause",
"github_id": 34025405,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1092,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/phastaIO/phiompi.c",
"provenance": "stackv2-0115.json.gz:111233",
"repo_name": "PHASTA/phasta",
"revision_date": "2022-11-15T17:39:10",
"revision_id": "a0d6c46256bdc32210d2313cacee245811b1d743",
"snapshot_id": "53bedb16ada9890e10163c14f720d37be3e7cd75",
"src_encoding": "UTF-8",
"star_events_count": 70,
"url": "https://raw.githubusercontent.com/PHASTA/phasta/a0d6c46256bdc32210d2313cacee245811b1d743/phastaIO/phiompi.c",
"visit_date": "2023-03-04T20:04:40.473943"
} | stackv2 | #include<mpi.h>
#include<assert.h>
#include"phiompi.h"
size_t phio_ar_sizet(size_t val, int op) {
size_t res = 0;
int err = MPI_Allreduce(&val,&res,1,MPI_UNSIGNED_LONG,op,MPI_COMM_WORLD);
assert(err == MPI_SUCCESS);
return res;
}
double phio_ar_dbl(double val, int op) {
double res = 0;
int err = MPI_Allreduce(&val,&res,1,MPI_DOUBLE,op,MPI_COMM_WORLD);
assert(err == MPI_SUCCESS);
return res;
}
size_t phio_min_sizet(size_t val) {
return phio_ar_sizet(val,MPI_MIN);
}
size_t phio_max_sizet(size_t val) {
return phio_ar_sizet(val,MPI_MAX);
}
size_t phio_add_sizet(size_t val) {
return phio_ar_sizet(val,MPI_SUM);
}
double phio_min_double(double val) {
return phio_ar_dbl(val,MPI_MIN);
}
double phio_max_double(double val) {
return phio_ar_dbl(val,MPI_MAX);
}
double phio_add_double(double val) {
return phio_ar_dbl(val,MPI_SUM);
}
int phio_self() {
int self;
MPI_Comm_rank(MPI_COMM_WORLD, &self);
return self;
}
int phio_peers() {
int peers;
MPI_Comm_size(MPI_COMM_WORLD, &peers);
return peers;
}
void phio_barrier() {
MPI_Barrier(MPI_COMM_WORLD);
}
| 2.25 | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.