hexsha
stringlengths
40
40
size
int64
5
1.05M
ext
stringclasses
588 values
lang
stringclasses
305 values
max_stars_repo_path
stringlengths
3
363
max_stars_repo_name
stringlengths
5
118
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
10
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringdate
2015-01-01 00:00:35
2022-03-31 23:43:49
max_stars_repo_stars_event_max_datetime
stringdate
2015-01-01 12:37:38
2022-03-31 23:59:52
max_issues_repo_path
stringlengths
3
363
max_issues_repo_name
stringlengths
5
118
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
10
max_issues_count
float64
1
134k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
363
max_forks_repo_name
stringlengths
5
135
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
10
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringdate
2015-01-01 00:01:02
2022-03-31 23:27:27
max_forks_repo_forks_event_max_datetime
stringdate
2015-01-03 08:55:07
2022-03-31 23:59:24
content
stringlengths
5
1.05M
avg_line_length
float64
1.13
1.04M
max_line_length
int64
1
1.05M
alphanum_fraction
float64
0
1
1077389f9a21eb933c5075ef5d8e29bf4be440ca
16,928
c
C
apps/aria_dashboard/firmware/src/config/glcd_rgba8888_mxt_mzda_intddr_sk/gfx/driver/processor/2dgpu/libnano2D_hal.c
Microchip-MPLAB-Harmony/gfx_apps
54d02e9388cd4e38c6d7cf486725e67bdd0f9844
[ "0BSD" ]
7
2019-03-19T23:00:02.000Z
2021-06-06T15:35:26.000Z
apps/aria_dashboard/firmware/src/config/glcd_rgba8888_mxt_mzda_intddr_sk_wvga/gfx/driver/processor/2dgpu/libnano2D_hal.c
Microchip-MPLAB-Harmony/gfx_apps
54d02e9388cd4e38c6d7cf486725e67bdd0f9844
[ "0BSD" ]
null
null
null
apps/aria_dashboard/firmware/src/config/glcd_rgba8888_mxt_mzda_intddr_sk_wvga/gfx/driver/processor/2dgpu/libnano2D_hal.c
Microchip-MPLAB-Harmony/gfx_apps
54d02e9388cd4e38c6d7cf486725e67bdd0f9844
[ "0BSD" ]
2
2019-08-01T02:39:59.000Z
2020-07-29T19:16:17.000Z
// DOM-IGNORE-BEGIN /******************************************************************************* * Copyright (C) 2020 Microchip Technology Inc. and its subsidiaries. * * Subject to your compliance with these terms, you may use Microchip software * and any derivatives exclusively with Microchip products. It is your * responsibility to comply with third party license terms applicable to your * use of third party software (including open source software) that may * accompany Microchip software. * * THIS SOFTWARE IS SUPPLIED BY MICROCHIP "AS IS". NO WARRANTIES, WHETHER * EXPRESS, IMPLIED OR STATUTORY, APPLY TO THIS SOFTWARE, INCLUDING ANY IMPLIED * WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY, AND FITNESS FOR A * PARTICULAR PURPOSE. * * IN NO EVENT WILL MICROCHIP BE LIABLE FOR ANY INDIRECT, SPECIAL, PUNITIVE, * INCIDENTAL OR CONSEQUENTIAL LOSS, DAMAGE, COST OR EXPENSE OF ANY KIND * WHATSOEVER RELATED TO THE SOFTWARE, HOWEVER CAUSED, EVEN IF MICROCHIP HAS * BEEN ADVISED OF THE POSSIBILITY OR THE DAMAGES ARE FORESEEABLE. TO THE * FULLEST EXTENT ALLOWED BY LAW, MICROCHIP'S TOTAL LIABILITY ON ALL CLAIMS IN * ANY WAY RELATED TO THIS SOFTWARE WILL NOT EXCEED THE AMOUNT OF FEES, IF ANY, * THAT YOU HAVE PAID DIRECTLY TO MICROCHIP FOR THIS SOFTWARE. *******************************************************************************/ // DOM-IGNORE-END /******************************************************************************* MPLAB Harmony Nano2D Generated HAL Wrapper File Name: libnano2D_hal.c Summary: Build-time generated implementation for the Nano2D Generated HAL Wrapper. Description: Build-time generated implementation for the Nano2D Generated HAL Wrapper. Created with MPLAB Harmony Version 2.03 *******************************************************************************/ #include "gfx/hal/inc/gfx_common.h" #include "gfx/hal/inc/gfx_processor_interface.h" #include "gfx/driver/processor/2dgpu/libnano2D.h" #include <xc.h> #include <sys/attribs.h> #include <sys/kmem.h> const char* driverName = "Nano 2D"; #define CMD_BUFFER_SIZE 8192 uint32_t __attribute__((coherent, aligned(32))) commandBuffer[CMD_BUFFER_SIZE]; // GPU command buffer seems to work better when placed in DDR #define CMD_BUFFER_DDR_ADDRESS 0xA9E00000 n2d_module_parameters_t gpu_params; n2d_buffer_format_t n2dFormats[GFX_COLOR_MODE_COUNT] = { -1, // GFX_COLOR_MODE_GS_8 -1, // GFX_COLOR_MODE_RGB_332, N2D_RGB565, // GFX_COLOR_MODE_RGB_565 -1, // GFX_COLOR_MODE_RGBA_5551 -1, // GFX_COLOR_MODE_RGB_888 N2D_RGBA8888, // GFX_COLOR_MODE_RGBA_8888 -1, // GFX_COLOR_MODE_ARGB_8888 -1, // GFX_COLOR_MODE_YUV -1, // GFX_COLOR_MODE_INDEX_1 -1, //GFX_COLOR_MODE_INDEX_4 -1, // GFX_COLOR_MODE_INDEX_8 }; n2d_buffer_format_t n2dBlend[GFX_COLOR_MODE_COUNT] = { -1, // GFX_COLOR_MODE_GS_8 -1, // GFX_COLOR_MODE_RGB_332, -1, // GFX_COLOR_MODE_RGB_565 -1, // GFX_COLOR_MODE_RGBA_5551 -1, // GFX_COLOR_MODE_RGB_888 N2D_BLEND_SRC_OVER, // GFX_COLOR_MODE_RGBA_8888 -1, // GFX_COLOR_MODE_ARGB_8888 -1, // GFX_COLOR_MODE_YUV -1, // GFX_COLOR_MODE_INDEX_1 -1, //GFX_COLOR_MODE_INDEX_4 -1, // GFX_COLOR_MODE_INDEX_8 }; static GFX_Result drawLine(const GFX_Point* p1, const GFX_Point* p2, const GFX_DrawState* state) { n2d_buffer_t buffer; n2d_point_t np1, np2; n2d_orientation_t orientation = N2D_0; GFX_Context* context = GFX_ActiveContext(); // trivial cases that are better handled by the CPU if(p1->x == p2->x || p1->y == p2->y) return cpuDrawLine(p1, p2, state); switch(context->orientation) { case GFX_ORIENTATION_0: { orientation = N2D_0; break; } case GFX_ORIENTATION_90: { orientation = N2D_90; break; } case GFX_ORIENTATION_180: { orientation = N2D_180; break; } case GFX_ORIENTATION_270: { orientation = N2D_270; break; } } buffer.width = state->target->size.width; buffer.height = state->target->size.height; buffer.stride = state->target->size.width * GFX_ColorInfo[state->colorMode].size; buffer.format = n2dFormats[state->target->mode]; buffer.orientation = orientation; buffer.handle = NULL; buffer.memory = state->target->pixels; buffer.gpu = KVA_TO_PA(state->target->pixels); np1.x = p1->x; np1.y = p1->y; np2.x = p2->x; np2.y = p2->y; // compensate for missing last pixel if(np1.x == np2.x) // vertical line { if(np1.y < np2.y) np2.y++; else np1.y--; } if(np1.y == np2.y) // horizontal line { if(np1.x < np2.x) np2.x++; else np1.x--; } n2d_line(&buffer, np1, np2, (n2d_rectangle_t*)&state->clipRect, GFX_ColorConvert(state->colorMode, GFX_COLOR_MODE_ARGB_8888, state->color), N2D_BLEND_NONE); return GFX_SUCCESS; } static GFX_Result fillRect(const GFX_Rect* rect, const GFX_DrawState* state) { n2d_buffer_t buffer; GFX_Rect lrect; n2d_orientation_t orientation = N2D_0; GFX_Context* context = GFX_ActiveContext(); #if GFX_LAYER_CLIPPING_ENABLED || GFX_BOUNDS_CLIPPING_ENABLED GFX_Rect clipRect; #endif lrect = *rect; #if GFX_LAYER_CLIPPING_ENABLED // clip rect against target rect GFX_RectClip(&state->targetClipRect, &lrect, &clipRect); lrect = clipRect; #endif #if GFX_BOUNDS_CLIPPING_ENABLED if((state->clipEnable == GFX_TRUE) && GFX_RectIntersects(&state->clipRect, &lrect) == GFX_FALSE) return GFX_FAILURE; // clip rect against global clipping rect if(state->clipEnable == GFX_TRUE) { GFX_RectClip(&state->clipRect, &lrect, &clipRect); lrect = clipRect; } #endif switch(context->orientation) { case GFX_ORIENTATION_0: { orientation = N2D_0; break; } case GFX_ORIENTATION_90: { orientation = N2D_90; break; } case GFX_ORIENTATION_180: { orientation = N2D_180; break; } case GFX_ORIENTATION_270: { orientation = N2D_270; break; } } buffer.width = state->target->size.width; buffer.height = state->target->size.height; buffer.stride = state->target->size.width * GFX_ColorInfo[state->colorMode].size; buffer.format = n2dFormats[state->target->mode]; buffer.orientation = orientation; buffer.handle = NULL; buffer.memory = state->target->pixels; buffer.gpu = KVA_TO_PA(state->target->pixels); n2d_fill(&buffer, (n2d_rectangle_t*)&lrect, GFX_ColorConvert(state->colorMode, GFX_COLOR_MODE_ARGB_8888, state->color), N2D_BLEND_NONE); return GFX_SUCCESS; } static GFX_Result drawBlit(const GFX_PixelBuffer* source, const GFX_Rect* srcRect, const GFX_Point* drawPoint, const GFX_DrawState* state) { n2d_buffer_t src_buffer, dest_buffer; GFX_Rect dest_rect; n2d_orientation_t orientation = N2D_0; GFX_Context* context = GFX_ActiveContext(); n2d_blend_t blend = N2D_BLEND_NONE; // the source address must reside in KSEG1 (cache coherent) memory // and the source buffer must be raw pixels as the the GPU doesn't // understand palettized blits // if this fails then fall back to software mode if(IS_KVA1(source->pixels) == GFX_FALSE || GFX_COLOR_MODE_IS_INDEX(source->mode) == GFX_TRUE || GFX_COLOR_MODE_IS_INDEX(state->target->mode) == GFX_TRUE || n2dFormats[source->mode] == -1 || n2dFormats[state->colorMode] == -1) return cpuDrawBlit(source, srcRect, drawPoint, state); switch(context->orientation) { case GFX_ORIENTATION_0: orientation = N2D_0; break; case GFX_ORIENTATION_90: { orientation = N2D_90; break; } case GFX_ORIENTATION_180: { orientation = N2D_180; break; } case GFX_ORIENTATION_270: { orientation = N2D_270; break; } } // craft source buffer descriptor src_buffer.width = source->size.width; src_buffer.height = source->size.height; src_buffer.stride = source->size.width * GFX_ColorInfo[source->mode].size; src_buffer.format = n2dFormats[source->mode]; src_buffer.orientation = orientation; src_buffer.handle = NULL; src_buffer.memory = source->pixels; src_buffer.gpu = KVA_TO_PA(source->pixels); // craft dest buffer descriptor dest_buffer.width = state->target->size.width; dest_buffer.height = state->target->size.height; dest_buffer.stride = state->target->size.width * GFX_ColorInfo[state->colorMode].size; dest_buffer.format = n2dFormats[state->target->mode]; dest_buffer.orientation = orientation; dest_buffer.handle = NULL; dest_buffer.memory = state->target->pixels; dest_buffer.gpu = KVA_TO_PA(state->target->pixels); dest_rect.x = drawPoint->x; dest_rect.y = drawPoint->y; dest_rect.width = srcRect->width; dest_rect.height = srcRect->height; if(state->maskEnable == GFX_TRUE) { n2d_color_t color = (n2d_color_t)GFX_ColorConvert(state->colorMode, GFX_COLOR_MODE_ARGB_8888, state->maskValue); n2d_draw_state(N2D_TRANSPARENCY_SOURCE, color, 0xA, 0xC); } if ((state->alphaEnable == GFX_TRUE) && ((state->blendMode & GFX_BLEND_CHANNEL) == 0)) { n2d_set_global_alpha(N2D_GLOBAL_ALPHA_ON, N2D_GLOBAL_ALPHA_OFF, state->globalAlphaValue, 0xff); blend = N2D_BLEND_SRC_OVER; } n2d_blit(&dest_buffer, (n2d_rectangle_t*)&dest_rect, &src_buffer, (n2d_rectangle_t*)srcRect, blend); if(state->maskEnable == GFX_TRUE) { n2d_draw_state(N2D_TRANSPARENCY_NONE, 0, 0xC, 0xC); } if ((state->alphaEnable == GFX_TRUE) && ((state->blendMode & GFX_BLEND_CHANNEL) == 0)) { n2d_set_global_alpha(N2D_GLOBAL_ALPHA_OFF, N2D_GLOBAL_ALPHA_OFF, 0xff, 0xff); blend = N2D_BLEND_NONE; } return GFX_SUCCESS; } static GFX_Result drawStretchBlit(const GFX_PixelBuffer* source, const GFX_Rect* srcRect, const GFX_Rect* destRect, const GFX_DrawState* state) { n2d_buffer_t src_buffer, dest_buffer; n2d_orientation_t orientation = N2D_0; GFX_Context* context = GFX_ActiveContext(); n2d_blend_t blend = N2D_BLEND_NONE; // the source address must reside in KSEG1 (cache coherent) memory // and the source buffer must be raw pixels as the the GPU doesn't // understand palettized blits // if this fails then fall back to software mode if(IS_KVA1(source->pixels) == GFX_FALSE || GFX_COLOR_MODE_IS_INDEX(source->mode) == GFX_TRUE || GFX_COLOR_MODE_IS_INDEX(state->target->mode) == GFX_TRUE || n2dFormats[source->mode] == -1 || n2dFormats[state->colorMode] == -1) return cpuDrawStretchBlit_NearestNeighbor(source, srcRect, destRect, state); switch(context->orientation) { case GFX_ORIENTATION_0: orientation = N2D_0; break; case GFX_ORIENTATION_90: { orientation = N2D_90; break; } case GFX_ORIENTATION_180: { orientation = N2D_180; break; } case GFX_ORIENTATION_270: { orientation = N2D_270; break; } } // craft source buffer descriptor src_buffer.width = source->size.width; src_buffer.height = source->size.height; src_buffer.stride = source->size.width * GFX_ColorInfo[source->mode].size; src_buffer.format = n2dFormats[source->mode]; src_buffer.orientation = orientation; src_buffer.handle = NULL; src_buffer.memory = source->pixels; src_buffer.gpu = KVA_TO_PA(source->pixels); // craft dest buffer descriptor dest_buffer.width = state->target->size.width; dest_buffer.height = state->target->size.height; dest_buffer.stride = state->target->size.width * GFX_ColorInfo[state->colorMode].size; dest_buffer.format = n2dFormats[state->target->mode]; dest_buffer.orientation = orientation; dest_buffer.handle = NULL; dest_buffer.memory = state->target->pixels; dest_buffer.gpu = KVA_TO_PA(state->target->pixels); if(state->maskEnable == GFX_TRUE) { n2d_color_t color = (n2d_color_t)GFX_ColorConvert(state->colorMode, GFX_COLOR_MODE_ARGB_8888, state->maskValue); n2d_draw_state(N2D_TRANSPARENCY_SOURCE, color, 0xA, 0xC); } if ((state->alphaEnable == GFX_TRUE) && ((state->blendMode & GFX_BLEND_CHANNEL) == 0)) { n2d_set_global_alpha(N2D_GLOBAL_ALPHA_ON, N2D_GLOBAL_ALPHA_OFF, state->globalAlphaValue, 0xff); blend = N2D_BLEND_SRC_OVER; } n2d_blit(&dest_buffer, (n2d_rectangle_t*)destRect, &src_buffer, (n2d_rectangle_t*)srcRect, blend); if(state->maskEnable == GFX_TRUE) { n2d_draw_state(N2D_TRANSPARENCY_NONE, 0, 0xC, 0xC); } if ((state->alphaEnable == GFX_TRUE) && ((state->blendMode & GFX_BLEND_CHANNEL) == 0)) { n2d_set_global_alpha(N2D_GLOBAL_ALPHA_OFF, N2D_GLOBAL_ALPHA_OFF, 0xff, 0xff); blend = N2D_BLEND_NONE; } return GFX_SUCCESS; } // function that returns the information for this driver GFX_Result procNANO2DInfoGet(GFX_ProcessorInfo* info) { if(info == NULL) return GFX_FAILURE; // populate info struct strcpy(info->name, driverName); info->color_formats = GFX_COLOR_MASK_ARGB_8888; return GFX_SUCCESS; } // function that initialized the driver context GFX_Result procNANO2DContextInitialize(GFX_Context* context) { /* initialize gpu hardware and peripheral software */ context->memory.memset((void*)commandBuffer, 0, CMD_BUFFER_SIZE); gpu_params.contiguousBase = (n2d_uint32_t)commandBuffer; gpu_params.registerMemBase2D = 0xBF8EB000; gpu_params.baseAddress = 0; n2d_init_hardware(&gpu_params); /* open and initialize gpu software */ if (N2D_IS_ERROR(n2d_open())) return GFX_FAILURE; // GPU Pipeline context->hal.drawPipeline[GFX_PIPELINE_GPU].drawLine[GFX_DRAW_LINE][GFX_ANTIALIAS_OFF] = &drawLine; context->hal.drawPipeline[GFX_PIPELINE_GPU].drawLine[GFX_DRAW_FILL][GFX_ANTIALIAS_OFF] = &drawLine; context->hal.drawPipeline[GFX_PIPELINE_GPU].drawRect[GFX_DRAW_FILL][GFX_ANTIALIAS_OFF] = &fillRect; context->hal.drawPipeline[GFX_PIPELINE_GPU].drawBlit = &drawBlit; // according to nano2d documentation the stretch blit is a fast resize, override nearest neighbor version context->hal.drawPipeline[GFX_PIPELINE_GPU].drawStretchBlit[GFX_RESIZE_NEARESTNEIGHBOR] = &drawStretchBlit; // GCU/GPU Pipeline context->hal.drawPipeline[GFX_PIPELINE_GCUGPU].drawLine[GFX_DRAW_LINE][GFX_ANTIALIAS_OFF] = &drawLine; context->hal.drawPipeline[GFX_PIPELINE_GCUGPU].drawLine[GFX_DRAW_FILL][GFX_ANTIALIAS_OFF] = &drawLine; context->hal.drawPipeline[GFX_PIPELINE_GCUGPU].drawRect[GFX_DRAW_FILL][GFX_ANTIALIAS_OFF] = &fillRect; context->hal.drawPipeline[GFX_PIPELINE_GCUGPU].drawBlit = &drawBlit; // according to nano2d documentation the stretch blit is a fast resize, override nearest neighbor version context->hal.drawPipeline[GFX_PIPELINE_GCUGPU].drawStretchBlit[GFX_RESIZE_NEARESTNEIGHBOR] = &drawStretchBlit; return GFX_SUCCESS; }
33.127202
121
0.61413
34188da4e9e3791e916ac7837a8145cd2a51b345
4,488
h
C
src/components/application_manager/include/application_manager/rpc_protection_manager.h
russjohnson09/sdl_core
9de7f1456f1807ae97348f774f7eead0ee92fd6d
[ "BSD-3-Clause" ]
249
2015-01-15T16:50:53.000Z
2022-03-24T13:23:34.000Z
src/components/application_manager/include/application_manager/rpc_protection_manager.h
russjohnson09/sdl_core
9de7f1456f1807ae97348f774f7eead0ee92fd6d
[ "BSD-3-Clause" ]
2,917
2015-01-12T16:17:49.000Z
2022-03-31T11:57:47.000Z
src/components/application_manager/include/application_manager/rpc_protection_manager.h
russjohnson09/sdl_core
9de7f1456f1807ae97348f774f7eead0ee92fd6d
[ "BSD-3-Clause" ]
306
2015-01-12T09:23:20.000Z
2022-01-28T18:06:30.000Z
/* * Copyright (c) 2019, Ford Motor Company * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following * disclaimer in the documentation and/or other materials provided with the * distribution. * * Neither the name of the Ford Motor Company 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. */ #ifndef SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_PROTOCOL_HANDLER_RPC_PROTECTION_MANAGER_H_ #define SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_PROTOCOL_HANDLER_RPC_PROTECTION_MANAGER_H_ #include <cstdint> #include <memory> #include "application_manager/application.h" #include "application_manager/policies/policy_handler_observer.h" #include "smart_objects/smart_object.h" namespace ns_smart_device_link { namespace ns_smart_objects { class SmartObject; } // namespace ns_smart_objects } // namespace ns_smart_device_link namespace smart_objects = ns_smart_device_link::ns_smart_objects; namespace application_manager { class Application; } // namespace application_manager namespace application_manager { /** * @brief RPCProtectionManager interface * This entity exists to get info from policy table regarding encryption on * application and function group level, as well as make decisions whether * certain RPC should be encrypted or not. * It mediates communication between PRCService and * PolicyEncryptionFlagGetterInterface which is implemented by PolicyManager, * providing adequate level of abstraction. */ class RPCProtectionManager : public policy::PolicyHandlerObserver { public: /* * @brief virtual destructor RPCProtectionManager */ virtual ~RPCProtectionManager() {} /* * @brief checks whether given rpc requires encryption by policy * @param function_id function id * @param app ref to Application * @param is_rpc_service_secure the flag the secure service started * @return true if function need encryption for current app, else false */ virtual bool CheckPolicyEncryptionFlag( const uint32_t function_id, const ApplicationSharedPtr app, const bool is_rpc_service_secure) const = 0; /* * @brief check whether given rpc is saved to internal cache and needs to be * encrypted before sending to mobile * @param app_id application id * @param correlation_id correlation id * @return true if the message with correlation id correlation_id needed e * ncryption else false */ virtual bool IsInEncryptionNeededCache( const uint32_t app_id, const uint32_t conrrelation_id) const = 0; /* * @brief Adds app id and correlation id of a message to internal cache * @param app_id application if * @param correlation_id correlation id */ virtual void AddToEncryptionNeededCache(const uint32_t app_id, const uint32_t correlation_id) = 0; /* * @brief Removes app id and correlation id of a message from internal cache * @param app_id application if * @param correlation_id correlation id */ virtual void RemoveFromEncryptionNeededCache( const uint32_t app_id, const uint32_t correlation_id) = 0; }; } // namespace application_manager #endif // SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_PROTOCOL_HANDLER_RPC_PROTECTION_MANAGER_H_
40.071429
96
0.77295
2ec2f6aa67a63302a6b1d7f0a9f91bba851f08f7
6,669
c
C
public_21CMvFAST_MC/Programs/CreateSmoothedDensityBoxes.c
NNSSA/21cmvFAST
8f015427f3609a3051b4fa185bdbe55b379c930f
[ "MIT" ]
5
2019-04-18T11:31:34.000Z
2020-11-15T03:29:14.000Z
public_21CMvFAST_MC/Programs/CreateSmoothedDensityBoxes.c
NNSSA/21cmvFAST
8f015427f3609a3051b4fa185bdbe55b379c930f
[ "MIT" ]
1
2019-12-17T05:27:25.000Z
2019-12-18T19:59:55.000Z
public_21CMvFAST_MC/Programs/CreateSmoothedDensityBoxes.c
NNSSA/21cmvFAST
8f015427f3609a3051b4fa185bdbe55b379c930f
[ "MIT" ]
2
2019-11-14T13:54:46.000Z
2019-12-08T17:16:53.000Z
#include "../Parameter_files/INIT_PARAMS.H" #include "../Parameter_files/ANAL_PARAMS.H" #include "../Parameter_files/Variables.h" #include "bubble_helper_progs.c" #include "heating_helper_progs.c" #include "gsl/gsl_sf_erf.h" #include "filter.c" float REDSHIFT; #define TOTAL_COSMOLOGY_FILEPARAMS (int)7 int main(int argc, char ** argv){ omp_set_num_threads(1); char filename[500]; char dummy_string[500]; FILE *F; fftwf_plan plan; // Redshift for which Ts.c is evolved down to, i.e. z' REDSHIFT = atof(argv[1]); R_BUBBLE_MAX = atof(argv[2]); INDIVIDUAL_ID = atof(argv[3]); INDIVIDUAL_ID_2 = atof(argv[4]); int i,temp_int,temp_int2; double *PARAM_COSMOLOGY_VALS = calloc(TOTAL_COSMOLOGY_FILEPARAMS,sizeof(double)); sprintf(filename,"WalkerCosmology_%1.6lf_%1.6lf.txt",INDIVIDUAL_ID,INDIVIDUAL_ID_2); F = fopen(filename,"rt"); for(i=0;i<TOTAL_COSMOLOGY_FILEPARAMS;i++) { fscanf(F,"%s\t%lf\n",&dummy_string,&PARAM_COSMOLOGY_VALS[i]); } fclose(F); RANDOM_SEED = (unsigned long long)PARAM_COSMOLOGY_VALS[0]; SIGMA8 = (float)PARAM_COSMOLOGY_VALS[1]; hlittle = (float)PARAM_COSMOLOGY_VALS[2]; OMm = (float)PARAM_COSMOLOGY_VALS[3]; OMl = (float)PARAM_COSMOLOGY_VALS[4]; OMb = (float)PARAM_COSMOLOGY_VALS[5]; POWER_INDEX = (float)PARAM_COSMOLOGY_VALS[6]; init_ps(); float z_prime,prev_z_prime; int counter; int j,k,LAST_FILTER_STEP,first_step_R,N_RSTEPS; float cell_length_factor,stored_R; int n_x, n_y, n_z; float k_x, k_y, k_z, k_mag,kR; unsigned long long ct; dR = (BOX_LEN / (double) HII_DIM) * CMperMPC; // size of cell (in comoving cm) deltax_unfiltered = (fftwf_complex *) fftwf_malloc(sizeof(fftwf_complex)*HII_KSPACE_NUM_PIXELS); deltax_filtered = (fftwf_complex *) fftwf_malloc(sizeof(fftwf_complex)*HII_KSPACE_NUM_PIXELS); float **stored_smoothed_density; R=fmax(R_BUBBLE_MIN, (cell_length_factor*BOX_LEN/(float)HII_DIM)); while (R < fmin(R_BUBBLE_MAX, L_FACTOR*BOX_LEN)) { R*= DELTA_R_HII_FACTOR; if(R >= fmin(R_BUBBLE_MAX, L_FACTOR*BOX_LEN)) { stored_R = R/DELTA_R_HII_FACTOR; } counter += 1; } N_RSTEPS = counter; stored_smoothed_density = (float **)calloc(N_RSTEPS,sizeof(float *)); for(i=0;i<N_RSTEPS;i++) { stored_smoothed_density[i] = (float *)calloc(HII_TOT_FFT_NUM_PIXELS,sizeof(float)); } // Determine the number of redshifts within the Ts.c calculation to set N_USER_REDSHIFT for the light-cone version of the computation. z_prime = REDSHIFT*1.0001; //higher for rounding while (z_prime < Z_HEAT_MAX) z_prime = ((1.+z_prime)*ZPRIME_STEP_FACTOR - 1.); prev_z_prime = Z_HEAT_MAX; z_prime = ((1.+z_prime)/ ZPRIME_STEP_FACTOR - 1.); while (z_prime > REDSHIFT){ sprintf(filename, "../Boxes/updated_smoothed_deltax_z%06.2f_%i_%.0fMpc", z_prime, HII_DIM, BOX_LEN); printf("filename = %s\n",filename); F = fopen(filename, "rb"); for (i=0; i<HII_DIM; i++){ for (j=0; j<HII_DIM; j++){ for (k=0; k<HII_DIM; k++){ if (fread((float *)deltax_unfiltered + HII_R_FFT_INDEX(i,j,k), sizeof(float), 1, F)!=1){ printf("Read error occured while reading deltax box.\n"); } } } } fclose(F); for (ct=0; ct<HII_KSPACE_NUM_PIXELS; ct++){ deltax_unfiltered[ct] /= (HII_TOT_NUM_PIXELS+0.0); } printf("Do FFT\n"); plan = fftwf_plan_dft_r2c_3d(HII_DIM, HII_DIM, HII_DIM, (float *)deltax_unfiltered, (fftwf_complex *)deltax_unfiltered, FFTW_ESTIMATE); fftwf_execute(plan); fftwf_destroy_plan(plan); // fftwf_cleanup(); printf("Complete FFT\n"); cell_length_factor = L_FACTOR; counter = 0; R=fmax(R_BUBBLE_MIN, (cell_length_factor*BOX_LEN/(float)HII_DIM)); while (R < fmin(R_BUBBLE_MAX, L_FACTOR*BOX_LEN)) { R*= DELTA_R_HII_FACTOR; if(R >= fmin(R_BUBBLE_MAX, L_FACTOR*BOX_LEN)) { stored_R = R/DELTA_R_HII_FACTOR; } counter += 1; } R=fmin(R_BUBBLE_MAX, L_FACTOR*BOX_LEN); LAST_FILTER_STEP = 0; first_step_R = 1; printf("Start loop\n"); while (!LAST_FILTER_STEP){//(R > (cell_length_factor*BOX_LEN/(HII_DIM+0.0))){ if ( ((R/DELTA_R_HII_FACTOR - cell_length_factor*BOX_LEN/(float)HII_DIM) <= FRACT_FLOAT_ERR) || ((R/DELTA_R_HII_FACTOR - R_BUBBLE_MIN) <= FRACT_FLOAT_ERR) ) { LAST_FILTER_STEP = 1; } printf("R = %1.6e counter = %d\n",R,counter-1); memcpy(deltax_filtered, deltax_unfiltered, sizeof(fftwf_complex)*HII_KSPACE_NUM_PIXELS); HII_filter(deltax_filtered, HII_FILTER, R); printf("Before FFT\n"); plan = fftwf_plan_dft_c2r_3d(HII_DIM, HII_DIM, HII_DIM, (fftwf_complex *)deltax_filtered, (float *)deltax_filtered, FFTW_ESTIMATE); fftwf_execute(plan); fftwf_destroy_plan(plan); // fftwf_cleanup(); printf("Fill array\n"); for (i=0; i<HII_DIM; i++){ for (j=0; j<HII_DIM; j++){ for (k=0; k<HII_DIM; k++){ stored_smoothed_density[counter-1][HII_R_FFT_INDEX(i,j,k)] = *((float *)deltax_filtered + HII_R_FFT_INDEX(i,j,k)); } } } if(first_step_R) { R = stored_R; first_step_R = 0; } else { R /= DELTA_R_HII_FACTOR; } counter -= 1; } printf("Loop complete, write file\n"); sprintf(filename, "delta_x_filtered_RMAX%1.6f_z%1.6f",R_BUBBLE_MAX,z_prime); F = fopen(filename, "wb"); for(i=0;i<N_RSTEPS;i++) { mod_fwrite(stored_smoothed_density[i], sizeof(float)*(HII_TOT_FFT_NUM_PIXELS), 1, F); } fclose(F); prev_z_prime = z_prime; z_prime = ((1.+prev_z_prime) / ZPRIME_STEP_FACTOR - 1.); } fftwf_free(deltax_unfiltered); fftwf_free(deltax_filtered); free(PARAM_COSMOLOGY_VALS); for(i=0;i<N_RSTEPS;i++) { free(stored_smoothed_density[i]); } free(stored_smoothed_density); return 0; }
33.179104
170
0.588694
2ef14aebeb17c4d2a58b0caa227722997ef9e7d9
8,472
h
C
Templates/Full/web/source/npplugin/windows/jritypes.h
vbillet/Torque3D
ece8823599424ea675e5f79d9bcb44e42cba8cae
[ "MIT" ]
2,113
2015-01-01T11:23:01.000Z
2022-03-28T04:51:46.000Z
Templates/Full/web/source/npplugin/windows/jritypes.h
vbillet/Torque3D
ece8823599424ea675e5f79d9bcb44e42cba8cae
[ "MIT" ]
948
2015-01-02T01:50:00.000Z
2022-02-27T05:56:40.000Z
Templates/Full/web/source/npplugin/windows/jritypes.h
vbillet/Torque3D
ece8823599424ea675e5f79d9bcb44e42cba8cae
[ "MIT" ]
944
2015-01-01T09:33:53.000Z
2022-03-15T22:23:03.000Z
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is mozilla.org code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ /******************************************************************************* * Java Runtime Interface ******************************************************************************/ #ifndef JRITYPES_H #define JRITYPES_H #include "jri_md.h" #include "jni.h" #include <stddef.h> #include <stdlib.h> #include <stdarg.h> #ifdef __cplusplus extern "C" { #endif /******************************************************************************* * Types ******************************************************************************/ struct JRIEnvInterface; typedef void* JRIRef; typedef void* JRIGlobalRef; typedef jint JRIFieldID; typedef jint JRIMethodID; /* synonyms: */ typedef JRIGlobalRef jglobal; typedef union JRIValue { jbool z; jbyte b; jchar c; jshort s; jint i; jlong l; jfloat f; jdouble d; jref r; } JRIValue; typedef enum JRIBoolean { JRIFalse = 0, JRITrue = 1 } JRIBoolean; typedef enum JRIConstant { JRIUninitialized = -1 } JRIConstant; /* convenience types (these must be distinct struct types for c++ overloading): */ #if 0 /* now in jni.h */ typedef struct jbooleanArrayStruct* jbooleanArray; typedef struct jbyteArrayStruct* jbyteArray; typedef struct jcharArrayStruct* jcharArray; typedef struct jshortArrayStruct* jshortArray; typedef struct jintArrayStruct* jintArray; typedef struct jlongArrayStruct* jlongArray; typedef struct jfloatArrayStruct* jfloatArray; typedef struct jdoubleArrayStruct* jdoubleArray; typedef struct jobjectArrayStruct* jobjectArray; #endif typedef struct jstringArrayStruct* jstringArray; typedef struct jarrayArrayStruct* jarrayArray; #define JRIConstructorMethodName "<init>" /******************************************************************************* * Signature Construction Macros ******************************************************************************/ /* ** These macros can be used to construct signature strings. Hopefully their names ** are a little easier to remember than the single character they correspond to. ** For example, to specify the signature of the method: ** ** public int read(byte b[], int off, int len); ** ** you could write something like this in C: ** ** char* readSig = JRISigMethod(JRISigArray(JRISigByte) ** JRISigInt ** JRISigInt) JRISigInt; ** ** Of course, don't put commas between the types. */ #define JRISigArray(T) "[" T #define JRISigByte "B" #define JRISigChar "C" #define JRISigClass(name) "L" name ";" #define JRISigFloat "F" #define JRISigDouble "D" #define JRISigMethod(args) "(" args ")" #define JRISigNoArgs "" #define JRISigInt "I" #define JRISigLong "J" #define JRISigShort "S" #define JRISigVoid "V" #define JRISigBoolean "Z" /******************************************************************************* * Environments ******************************************************************************/ extern JRI_PUBLIC_API(const struct JRIEnvInterface**) JRI_GetCurrentEnv(void); /******************************************************************************* * Specific Scalar Array Types ******************************************************************************/ /* ** The JRI Native Method Interface does not support boolean arrays. This ** is to allow Java runtime implementations to optimize boolean array ** storage. Using the ScalarArray operations on boolean arrays is bound ** to fail, so convert any boolean arrays to byte arrays in Java before ** passing them to a native method. */ #define JRI_NewByteArray(env, length, initialValues) \ JRI_NewScalarArray(env, length, JRISigByte, (jbyte*)(initialValues)) #define JRI_GetByteArrayLength(env, array) \ JRI_GetScalarArrayLength(env, array) #define JRI_GetByteArrayElements(env, array) \ JRI_GetScalarArrayElements(env, array) #define JRI_NewCharArray(env, length, initialValues) \ JRI_NewScalarArray(env, ((length) * sizeof(jchar)), JRISigChar, (jbyte*)(initialValues)) #define JRI_GetCharArrayLength(env, array) \ JRI_GetScalarArrayLength(env, array) #define JRI_GetCharArrayElements(env, array) \ ((jchar*)JRI_GetScalarArrayElements(env, array)) #define JRI_NewShortArray(env, length, initialValues) \ JRI_NewScalarArray(env, ((length) * sizeof(jshort)), JRISigShort, (jbyte*)(initialValues)) #define JRI_GetShortArrayLength(env, array) \ JRI_GetScalarArrayLength(env, array) #define JRI_GetShortArrayElements(env, array) \ ((jshort*)JRI_GetScalarArrayElements(env, array)) #define JRI_NewIntArray(env, length, initialValues) \ JRI_NewScalarArray(env, ((length) * sizeof(jint)), JRISigInt, (jbyte*)(initialValues)) #define JRI_GetIntArrayLength(env, array) \ JRI_GetScalarArrayLength(env, array) #define JRI_GetIntArrayElements(env, array) \ ((jint*)JRI_GetScalarArrayElements(env, array)) #define JRI_NewLongArray(env, length, initialValues) \ JRI_NewScalarArray(env, ((length) * sizeof(jlong)), JRISigLong, (jbyte*)(initialValues)) #define JRI_GetLongArrayLength(env, array) \ JRI_GetScalarArrayLength(env, array) #define JRI_GetLongArrayElements(env, array) \ ((jlong*)JRI_GetScalarArrayElements(env, array)) #define JRI_NewFloatArray(env, length, initialValues) \ JRI_NewScalarArray(env, ((length) * sizeof(jfloat)), JRISigFloat, (jbyte*)(initialValues)) #define JRI_GetFloatArrayLength(env, array) \ JRI_GetScalarArrayLength(env, array) #define JRI_GetFloatArrayElements(env, array) \ ((jfloat*)JRI_GetScalarArrayElements(env, array)) #define JRI_NewDoubleArray(env, length, initialValues) \ JRI_NewScalarArray(env, ((length) * sizeof(jdouble)), JRISigDouble, (jbyte*)(initialValues)) #define JRI_GetDoubleArrayLength(env, array) \ JRI_GetScalarArrayLength(env, array) #define JRI_GetDoubleArrayElements(env, array) \ ((jdouble*)JRI_GetScalarArrayElements(env, array)) /******************************************************************************/ /* ** JDK Stuff -- This stuff is still needed while we're using the JDK ** dynamic linking strategy to call native methods. */ typedef union JRI_JDK_stack_item { /* Non pointer items */ jint i; jfloat f; jint o; /* Pointer items */ void *h; void *p; unsigned char *addr; #ifdef IS_64 double d; long l; /* == 64bits! */ #endif } JRI_JDK_stack_item; typedef union JRI_JDK_Java8Str { jint x[2]; jdouble d; jlong l; void *p; float f; } JRI_JDK_Java8; /******************************************************************************/ #ifdef __cplusplus } #endif #endif /* JRITYPES_H */ /******************************************************************************/
34.721311
93
0.641289
088301514475d792d98d333d191be8b1a7ee0848
1,071
c
C
src/network/sendmmsg.c
microsoft/checkedc-musl
7b9ef2bb91fb9f3b1a0b0d2ec75462ac20c5e912
[ "MIT" ]
12
2020-07-24T23:04:36.000Z
2021-11-11T19:40:49.000Z
src/network/sendmmsg.c
microsoft/checkedc-musl
7b9ef2bb91fb9f3b1a0b0d2ec75462ac20c5e912
[ "MIT" ]
9
2020-06-26T17:58:48.000Z
2020-12-03T15:19:52.000Z
src/network/sendmmsg.c
microsoft/checkedc-musl
7b9ef2bb91fb9f3b1a0b0d2ec75462ac20c5e912
[ "MIT" ]
10
2020-06-23T21:15:35.000Z
2022-01-21T04:13:08.000Z
#define _GNU_SOURCE #include <sys/socket.h> #include <limits.h> #include <errno.h> #include "syscall.h" #pragma CHECKED_SCOPE on int sendmmsg(int fd, struct mmsghdr *msgvec : count(vlen), unsigned int vlen, unsigned int flags) { #if LONG_MAX > INT_MAX /* Can't use the syscall directly because the kernel has the wrong * idea for the types of msg_iovlen, msg_controllen, and cmsg_len, * and the cmsg blocks cannot be modified in-place. */ int i; unsigned int vlen_tmp = vlen; if (vlen_tmp > IOV_MAX) vlen_tmp = IOV_MAX; /* This matches the kernel. */ if (!vlen_tmp) return 0; for (i=0; i<vlen_tmp; i++) { /* As an unfortunate inconsistency, the sendmmsg API uses * unsigned int for the resulting msg_len, despite sendmsg * returning ssize_t. However Linux limits the total bytes * sent by sendmsg to INT_MAX, so the assignment is safe. */ ssize_t r = sendmsg(fd, &msgvec[i].msg_hdr, flags); if (r < 0) goto error; msgvec[i].msg_len = r; } error: return i ? i : -1; #else return syscall_cp(SYS_sendmmsg, fd, msgvec, vlen, flags); #endif }
30.6
75
0.70775
eca889632c1c1fd6611e98a7e6f58f547a4e0691
3,207
h
C
KDIS/DataTypes/GED.h
pelicanmapping/boeing-kdis
ae0d1da99e62a4424b6cd14cd963b5a87a80fb7b
[ "BSD-2-Clause" ]
null
null
null
KDIS/DataTypes/GED.h
pelicanmapping/boeing-kdis
ae0d1da99e62a4424b6cd14cd963b5a87a80fb7b
[ "BSD-2-Clause" ]
null
null
null
KDIS/DataTypes/GED.h
pelicanmapping/boeing-kdis
ae0d1da99e62a4424b6cd14cd963b5a87a80fb7b
[ "BSD-2-Clause" ]
null
null
null
/********************************************************************* Copyright 2013 KDIS All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. For Further Information Please Contact me at Karljj1@yahoo.com http://p.sf.net/kdis/UserGuide *********************************************************************/ /******************************************************************** class: GED created: 07:06:2009 author: Karl Jones purpose: Abstract class for all Grouped Entity Descriptors. The following derived classes exist: GED_BasicGroundCombatVehicle GED_EnhancedGroundCombatVehicle GED_BasicGroundCombatSoldier GED_EnhancedGroundCombatSoldier GED_BasicRotorWingAircraft GED_EnhancedRotaryWingAircraft GED_BasicFixedWingAircraft GED_EnhancedFixedWingAircraft GED_GroundLogisticsVehicle size: N/A *********************************************************************/ #pragma once #include "./DataTypeBase.h" namespace KDIS { namespace DATA_TYPE { using KDIS::DATA_TYPE::ENUMS::GroupedEntityCategory; class KDIS_EXPORT GED : public DataTypeBase { public: GED( void ) {}; virtual ~GED( void ) {}; //************************************ // FullName: KDIS::DATA_TYPE::GED::GetGroupedEntityCategory // Description: Identifies the derived GED class. // Not part of the DIS PDU. //************************************ virtual GroupedEntityCategory GetGroupedEntityCategory() const = 0; //************************************ // FullName: KDIS::DATA_TYPE::GED::GetLength // Description: Returns size of the GED in octets. // Not part of the DIS PDU. //************************************ virtual KUINT8 GetLength() const = 0; }; }; // END namespace DATA_TYPES }; // END namespace KDIS
36.862069
79
0.619894
0c0e12fd91fdbd69cd7fd30a0e086b711b29bb32
2,934
c
C
Work/2020_2021/L13/CRC16.c
nikcleju/IT20172018
e23bcb9edff230db236c3d1d342699d95b5f7564
[ "CC-BY-4.0" ]
null
null
null
Work/2020_2021/L13/CRC16.c
nikcleju/IT20172018
e23bcb9edff230db236c3d1d342699d95b5f7564
[ "CC-BY-4.0" ]
null
null
null
Work/2020_2021/L13/CRC16.c
nikcleju/IT20172018
e23bcb9edff230db236c3d1d342699d95b5f7564
[ "CC-BY-4.0" ]
2
2019-06-23T05:23:13.000Z
2021-04-02T05:13:27.000Z
#include <stdio.h> #include <stdlib.h> #define READ_BIT(x,i) (int)(((x) & (1U << (i))) != 0) /* read bit i from x */ #define SET_BIT(x,i) ((x) = (x) | (1U << (i))) /* set bit i from x to 1 */ #define CLEAR_BIT(x,i) ((x) = (x) & ~(1U << (i))) /* clear bit i from x to 0 */ #define WRITE_BIT(x,i,val) ((val) ? SET_BIT((x),(i)) : CLEAR_BIT((x),(i))) /* write 'val' in bit i from x */ #define TOGGLE_BIT(x,i) ((x) = (x) ^ (1U << (i))) /* toggle bit i from x */ #define VECREAD_BIT(v,i) (READ_BIT((v[(i)/8]),(i)%8)) /* read bit i from byte vector v */ #define VECWRITE_BIT(v,i,val) (WRITE_BIT((v[(i)/8]),((i)%8),val)) /* write 'val' in bit i from byte vector v */ // We'll run the program like this: // CRC16.exe input.txt output.dat // argv[0] argv[1] argv[2] int main(int argc, char* argv[]) { int pos; // STEP 1: Read the input file argv[1] into the vector `input` unsigned char input[100000]; // allocate a vector with enough space for 100KB of data int nbytes; // will store the number of bytes actually read from the file by fread() FILE* f = fopen(argv[1], "rb"); if (f == NULL) { printf("File %s could not be opened", argv[1]); exit(1); } nbytes = fread( input , sizeof(unsigned char) , 100000 , f); fclose(f); // Open the output file and write the original data there, before we destroy it in the process // STEP 3: Write the data into the output file argv[2] // a. write the original input data f = fopen(argv[2], "wb"); fwrite( input , sizeof(unsigned char) , nbytes , f); // STEP 2 input[nbytes] = 0; // make sure the two bytes which will hold the CRC start from the value of 0 input[nbytes+1] = 0; for (pos=0; pos < nbytes*8 ; pos++) // iterate through every bit in the input sequence { if( VECREAD_BIT(input, pos) == 1) // only do something if the current bit is 1, otherwise just advance { VECWRITE_BIT(input, pos, (VECREAD_BIT(input, pos) + 1)%2 ); // toggle the bit at position pos VECWRITE_BIT(input, pos+2, (VECREAD_BIT(input, pos+2) + 1)%2 ); // toggle the bit at position pos VECWRITE_BIT(input, pos+15, (VECREAD_BIT(input, pos+15) + 1)%2 ); // toggle the bit at position pos VECWRITE_BIT(input, pos+16, (VECREAD_BIT(input, pos+16) + 1)%2 ); // toggle the bit at position pos // the positions = where the 1's are located in the g sequence } } // b. append the two bytes of the CRC value (16 bits) fwrite( input + nbytes , 1, 2, f); // write two more bytes in the output file // taken from the input vector, but the after the orignal data fclose(f); printf("Written file %s. Bye!", argv[2]); }
48.098361
137
0.558964
08b6835bf629983fbb573b6291dce4a0356559a6
751
h
C
System/Library/PrivateFrameworks/CoreSpeech.framework/CSSpIdImplicitTraining.h
lechium/tvOS124Headers
11d1b56dd4c0ffd88b9eac43f87a5fd6f7228475
[ "MIT" ]
4
2019-08-27T18:03:47.000Z
2021-09-18T06:29:00.000Z
System/Library/PrivateFrameworks/CoreSpeech.framework/CSSpIdImplicitTraining.h
lechium/tvOS124Headers
11d1b56dd4c0ffd88b9eac43f87a5fd6f7228475
[ "MIT" ]
null
null
null
System/Library/PrivateFrameworks/CoreSpeech.framework/CSSpIdImplicitTraining.h
lechium/tvOS124Headers
11d1b56dd4c0ffd88b9eac43f87a5fd6f7228475
[ "MIT" ]
null
null
null
/* * This header is generated by classdump-dyld 1.0 * on Saturday, August 24, 2019 at 9:48:46 PM Mountain Standard Time * Operating System: Version 12.4 (Build 16M568) * Image Source: /System/Library/PrivateFrameworks/CoreSpeech.framework/CoreSpeech * classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos. */ @interface CSSpIdImplicitTraining : NSObject +(id)sharedInstance; -(void)processAudioChunk:(id)arg1 ; -(void)recordingStoppedForReason:(long long)arg1 ; -(void)processImplicitTrainingUtterance:(id)arg1 forVoiceProfileId:(id)arg2 withMetaInfo:(id)arg3 withCompletion:(/*^block*/id)arg4 ; -(void)setRecordingContext:(id)arg1 ; -(void)startRecordingImplicitTrainingUtteranceWithVoiceTriggerEventInfo:(id)arg1 ; @end
39.526316
133
0.793609
83664fab0842ef2f2a503e4407d888340823be13
2,337
c
C
src/encrypt_decrypt.c
dnuka/tpmsecret
c612b6f4b9199d334c5e5dfa278b0894ad37b3f0
[ "MIT" ]
3
2021-06-16T07:11:31.000Z
2021-08-11T21:36:56.000Z
src/encrypt_decrypt.c
dnuka/tpmsecret
c612b6f4b9199d334c5e5dfa278b0894ad37b3f0
[ "MIT" ]
2
2021-06-16T07:07:58.000Z
2021-06-17T03:30:05.000Z
src/encrypt_decrypt.c
dnuka/tpmsecret
c612b6f4b9199d334c5e5dfa278b0894ad37b3f0
[ "MIT" ]
null
null
null
#include <stdio.h> #include <tss2/tss2_esys.h> #include <tss2/tss2_mu.h> #include "encrypt_decrypt.h" uint32_t encrypt_data(ESYS_CONTEXT *ctx, ESYS_TR sk_handle, TPMI_YES_NO encrypt) { uint32_t r = 0; FILE *secret_data = NULL; FILE *cipher_text = NULL; TPM2B_MAX_BUFFER *out_data = NULL; TPM2B_IV *iv_out = NULL; TPMI_ALG_SYM_MODE mode = TPM2_ALG_NULL; /* for passing an initial value for AES to or from the TPM */ TPM2B_IV iv_in = { .size = 16, .buffer = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 16} }; /* sized buffer that can hold data */ TPM2B_MAX_BUFFER in_data = { .size = 16 }; secret_data = fopen("secret_data", "r"); if (!secret_data) { printf("error: reading secret_data!\n"); //goto error; } fread(in_data.buffer, sizeof(char), BUFF_SIZE, secret_data); printf("%s", in_data.buffer); fclose(secret_data); r = Esys_EncryptDecrypt2(ctx, sk_handle, ESYS_TR_PASSWORD, ESYS_TR_NONE, ESYS_TR_NONE, &in_data, encrypt, mode, &iv_in, &out_data, &iv_out); if (r != TSS2_RC_SUCCESS) { printf("error: Esys_EncryptDecrypt2!\n"); } cipher_text = fopen("cipher_text", "wb"); if (!cipher_text) { printf("error: "); } printf("%s\n", out_data->buffer); fwrite(out_data->buffer, 1, BUFF_SIZE, cipher_text); fclose(cipher_text); return r; } uint32_t decrypt_data(ESYS_CONTEXT *ctx, ESYS_TR sk_handle, TPMI_YES_NO decrypt) { uint32_t r = 0; FILE *cipher_text = NULL; FILE *plain_text = NULL; TPM2B_MAX_BUFFER *out_data = NULL; TPM2B_IV *iv_out = NULL; TPMI_ALG_SYM_MODE mode = TPM2_ALG_NULL; TPM2B_IV iv_in = { .size = 16, .buffer = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 16} }; TPM2B_MAX_BUFFER in_data = { .size = 16 }; cipher_text = fopen("cipher_text", "rb"); if (!cipher_text) { printf("error: reading cipher_text!\n"); } fread(in_data.buffer, 1, BUFF_SIZE, cipher_text); fclose(cipher_text); r = Esys_EncryptDecrypt2(ctx, sk_handle, ESYS_TR_PASSWORD, ESYS_TR_NONE, ESYS_TR_NONE, &in_data, decrypt, mode, &iv_in, &out_data, &iv_out); if (r != TSS2_RC_SUCCESS) { printf("error: Esys_EncryptDecrypt2!\n"); } plain_text = fopen("plain_text", "w"); if (!plain_text) { printf("error: "); } fwrite(out_data->buffer, sizeof(char), BUFF_SIZE, plain_text); fclose(plain_text); printf("%s\n", out_data->buffer); return r; }
22.911765
71
0.674797
03e8f4592deb7aa9b8a6ed8fc216715c181a7b02
12,302
h
C
glassesfunctions.h
macetech/LEDMatrixShadesHoliday
2e7747c2f849ba58816235b79137d04af8f34925
[ "MIT" ]
null
null
null
glassesfunctions.h
macetech/LEDMatrixShadesHoliday
2e7747c2f849ba58816235b79137d04af8f34925
[ "MIT" ]
null
null
null
glassesfunctions.h
macetech/LEDMatrixShadesHoliday
2e7747c2f849ba58816235b79137d04af8f34925
[ "MIT" ]
null
null
null
// Glasses-specific functions, may not work with other applications typedef void (*functionList)(); // definition for list of effect function pointers extern byte numEffects; #define kMatrixWidth 24 #define kMatrixHeight 8 // Buffers for graphics generation byte GlassesBits[24][2] = {{0}}; // 24 column x 8 row bit arrays (on/off frame) byte GlassesPWM[24][9] = {}; // 24 column x 8 row byte array (PWM frame) // Read and smooth light sensor input #define brightnessSmoothFactor 0.99 float smoothedBrightness = 0; void readBrightness() { smoothedBrightness = smoothedBrightness * brightnessSmoothFactor + analogRead(3) * (1.0 - brightnessSmoothFactor); } // Send contents of bit frame to correct AS1130 registers // Rough, needs to be streamlined void writeBitFrame(byte frame, byte bitbuffer) { Wire.beginTransmission(0x37); Wire.write(0xfd); Wire.write(frame + memoryONOFFSTART); Wire.endTransmission(); byte tempBits = 0; Wire.beginTransmission(0x37); Wire.write(0x00); for (byte i = 0; i < 12; i++) { tempBits = GlassesBits[i][bitbuffer]; Wire.write(tempBits << 2); Wire.write(tempBits >> 6); } Wire.endTransmission(); Wire.beginTransmission(0x30); Wire.write(0xfd); Wire.write(frame + memoryONOFFSTART); Wire.endTransmission(); Wire.beginTransmission(0x30); Wire.write(0x00); for (byte i = 0; i < 12; i++) { tempBits = GlassesBits[i+12][bitbuffer]; Wire.write(tempBits << 2); Wire.write(tempBits >> 6); } Wire.endTransmission(); } // Send contents of PWM frame to correct AS1130 registers // Rough, needs to be streamlined void writePWMFrame(byte frame) { Wire.beginTransmission(0x37); Wire.write(0xfd); Wire.write(frame + memoryBLINKPWMSTART); Wire.endTransmission(); for (int x = 0; x < 12; x++) { Wire.beginTransmission(0x37); Wire.write(26+x*11); for (int y = 0; y < 8; y++) { Wire.write(GlassesPWM[x][y]); } Wire.endTransmission(); } Wire.beginTransmission(0x30); Wire.write(0xfd); Wire.write(frame + memoryBLINKPWMSTART); Wire.endTransmission(); for (int x = 0; x < 12; x++) { Wire.beginTransmission(0x30); Wire.write(26+x*11); for (int y = 0; y < 8; y++) { Wire.write(GlassesPWM[x+12][y]); } Wire.endTransmission(); } } // Send contents of bit frame to blink AS1130 registers // Rough, needs to be streamlined // Mostly used to clear blink frames, since blink is useless void writeBlinkFrame(byte frame, byte bitbuffer) { Wire.beginTransmission(0x37); Wire.write(0xfd); Wire.write(frame + memoryBLINKPWMSTART); Wire.endTransmission(); Wire.beginTransmission(0x37); Wire.write(0x00); for (byte i = 0; i < 12; i++) { Wire.write(GlassesBits[i][bitbuffer] << 2); Wire.write(GlassesBits[i][bitbuffer] >> 6); } Wire.endTransmission(); Wire.beginTransmission(0x30); Wire.write(0xfd); Wire.write(frame + memoryBLINKPWMSTART); Wire.endTransmission(); Wire.beginTransmission(0x30); Wire.write(0x00); for (byte i = 0; i < 12; i++) { Wire.write(GlassesBits[i+12][bitbuffer] << 2); Wire.write(GlassesBits[i+12][bitbuffer] >> 6); } Wire.endTransmission(); } // Set PWM frame all to one value // Usually used to clear or fill frame // Bit and PWM frames interact, if you want to do bit graphics you must fill PWM frame void fillPWMFrame(byte frame, byte value) { for (int x = 0; x < 24; x++) { for (int y = 0; y < 8; y++) { GlassesPWM[x][y] = value; } } } // Set PWM frame all to one value // Usually used to clear or fill frame // Bit and PWM frames interact, if you want to do PWM graphics you must fill bit on/off frame void fillBitFrame(byte frame, byte value) { for (int x = 0; x < 24; x++) { GlassesBits[x][0] = 255*(value > 0); GlassesBits[x][1] = 255*(value > 0); } } // Fill blink frame with known value // Usually zero because no one actually wants to use blink void fillBlinkFrame(byte frame, byte value) { for (int x = 0; x < 24; x++) { GlassesBits[x][0] = 255*(value > 0); GlassesBits[x][1] = 255*(value > 0); } writeBlinkFrame(frame, 0); } // Configure AS1130 chips to ideal startup settings void glassesInit() { byte configOptions = 0; // reset chip again configOptions = (0 << AS1130_test_all) | (0 << AS1130_auto_test) | (0 << AS1130_manual_test) | (0 << AS1130_init) | (0 << AS1130_shdn); setShutdownTest(glassesRight, configOptions); setShutdownTest(glassesLeft, configOptions); delay(5); configOptions = (1 << AS1130_test_all) | (1 << AS1130_auto_test) | (0 << AS1130_manual_test) | (1 << AS1130_init) | (1 << AS1130_shdn); setShutdownTest(glassesRight, configOptions); setShutdownTest(glassesLeft, configOptions); delay(5); configOptions = (0 << AS1130_low_vdd_rst) | (0 << AS1130_low_vdd_stat) | (1 << AS1130_led_error_correction) | (0 << AS1130_dot_corr) | (0 << AS1130_common_addr); setConfigs(glassesRight, configOptions, 1); setConfigs(glassesLeft, configOptions, 1); setMovie(glassesRight, 0, 0, 0, 0); setMovie(glassesLeft, 0, 0, 0, 0); setMovieOptions(glassesRight, 0, 0, 0, 0); setMovieOptions(glassesLeft, 0, 0, 0, 0); setMovieLooping(glassesRight, 1); setMovieLooping(glassesLeft, 1); setBrightness(glassesRight, startbrightness); setBrightness(glassesLeft, startbrightness); configOptions = (0 << AS1130_selected_pic) | (0 << AS1130_watchdog) | (0 << AS1130_por) | (0 << AS1130_overtemp) | (0 << AS1130_low_vdd) | (0 << AS1130_open_err) | (0 << AS1130_short_err) | (0 << AS1130_movie_fin); setInterruptMask(glassesRight, configOptions); setInterruptMask(glassesLeft, configOptions); setInterruptFrame(glassesRight, 0); setInterruptFrame(glassesLeft, 0); setI2CWatchdog(glassesRight, 64, 1); setI2CWatchdog(glassesLeft, 64, 1); setClockSync(glassesRight, AS1130_clock_speed_1MHz, AS1130_sync_IN); setClockSync(glassesLeft, AS1130_clock_speed_1MHz, AS1130_sync_OUT); fillPWMFrame(0, 255); writePWMFrame(0); fillBitFrame(0, 0); writeBitFrame(0, 0); fillBlinkFrame(0, 0); writeBlinkFrame(0, 0); setFrame(glassesRight, 0, 1); setFrame(glassesLeft, 0, 1); } // When switching from on/off to PWM or vice versa // Need to blank or fill respectively to correct the masks void switchDrawType(byte frame, byte enablePWM) { if (enablePWM == 0) { fillBitFrame(frame,0); writeBitFrame(frame, 0); fillPWMFrame(frame,255); writePWMFrame(frame); } else if (enablePWM == 1) { fillPWMFrame(frame,0); writePWMFrame(frame); fillBitFrame(frame,1); writeBitFrame(frame, 0); } } // Copy contents of PWM array one LED over // Possible to do in hardware at some future date void scrollPWM(byte dir) { if (dir == 0) { for (int i = 1; i < 24; i++) { for (int j = 0; j < 8; j++) { GlassesPWM[24 - i][j] = GlassesPWM[24-i-1][j]; } } } else if (dir == 1) { for (int i = 1; i < 24; i++) { for (int j = 0; j < 8; j++) { GlassesPWM[i-1][j] = GlassesPWM[i][j]; } } } } // Copy contents of bit array one LED over // Possible to do in hardware at some future date void scrollBits(byte dir, byte bitbuffer) { if (dir == 0) { for (int i = 1; i < 24; i++) { GlassesBits[24 - i][bitbuffer] = GlassesBits[24-i-1][bitbuffer]; } } else if (dir == 1) { for (int i = 1; i < 24; i++) { GlassesBits[i-1][bitbuffer] = GlassesBits[i][bitbuffer]; } } } // Fetch font character bitmap from flash byte charBuffer[8] = {0}; void loadCharBuffer(byte character) { for (int i = 0; i< 8; i++) { charBuffer[i] = pgm_read_byte(Font[character]+i); } } // Determine flash address of text string unsigned int currentStringAddress = 0; void selectFlashString(byte string) { currentStringAddress = pgm_read_word(&stringArray[string]); } // Fetch a character value from a text string in flash char loadStringChar(byte string, int character) { return (char) pgm_read_byte(currentStringAddress + character); } byte getCIE (byte value) { return pgm_read_byte(&cie[value]); } // Cycle through several brightness settings void cycleBrightness() { if (currentBrightness > 204) { currentBrightness = 51; } else { currentBrightness += 51; } byte newBrightness = getCIE(currentBrightness); setBrightness(glassesRight, newBrightness); setBrightness(glassesLeft, newBrightness); } byte qsine(int angle) { int cangle = abs(angle)%359; if (cangle < 90) { return pgm_read_byte(&qsinetable[cangle]); } else if (cangle < 180) { return 255-pgm_read_byte(&qsinetable[179-cangle]); } else if (cangle < 270) { return 255-pgm_read_byte(&qsinetable[cangle-180]); } else { return pgm_read_byte(&qsinetable[359-cangle]); } } // Anti-aliased line algorithm // Adapted from Michael Abrash http://www.phatcode.net/res/224/files/html/ch42/42-02.html void wuLine(int X0, int Y0, int X1, int Y1) { uint16_t IntensityShift, ErrorAdj, ErrorAcc; uint16_t ErrorAccTemp, Weighting, WeightingComplementMask; int DeltaX, DeltaY, Temp, XDir; // make sure line runs from top to bottom if (Y0 > Y1) { Temp = Y0; Y0 = Y1; Y1 = Temp; Temp = X0; X0 = X1; X1 = Temp; } // first pixel GlassesPWM[X0][Y0] = 255; if ((DeltaX = X1 - X0) >= 0) { XDir = 1; } else { XDir = -1; DeltaX = -DeltaX; } if ((DeltaY = Y1 - Y0) == 0) { // horizontal line while (DeltaX-- != 0) { X0 += XDir; GlassesPWM[X0][Y0] = 255; } return; } if (DeltaX == 0) { // vertical line do { Y0++; GlassesPWM[X0][Y0] = 255; } while (--DeltaY != 0); return; } if (DeltaX == DeltaY) { // diagonal line do { X0 += XDir; Y0++; GlassesPWM[X0][Y0] = 255; } while (--DeltaY != 0); return; } // need an anti-aliased line ErrorAcc = 0; IntensityShift = 16 - 8; WeightingComplementMask = 256 - 1; if (DeltaY > DeltaX) { // y-major line ErrorAdj = ((unsigned long) DeltaX << 16) / (unsigned long) DeltaY; while (--DeltaY) { ErrorAccTemp = ErrorAcc; ErrorAcc += ErrorAdj; if (ErrorAcc <= ErrorAccTemp) { X0 += XDir; } Y0++; Weighting = ErrorAcc >> IntensityShift; GlassesPWM[X0][Y0] = getCIE(255 - Weighting); GlassesPWM[X0][Y0 + 1] = getCIE(255 - (Weighting ^ WeightingComplementMask)); } GlassesPWM[X1][Y1] = 255; return; } ErrorAdj = ((unsigned long) DeltaY << 16) / (unsigned long) DeltaX; while (--DeltaX) { ErrorAccTemp = ErrorAcc; ErrorAcc += ErrorAdj; if (ErrorAcc <= ErrorAccTemp) { Y0++; } X0 += XDir; Weighting = ErrorAcc >> IntensityShift; GlassesPWM[X0][Y0] = getCIE(255 - Weighting); GlassesPWM[X0][Y0 + 1] = getCIE(255 - (Weighting ^ WeightingComplementMask)); } GlassesPWM[X1][Y1] = 255; } void loadGraphicsFrame(int frame) { for (int x = 0; x < 24; x++) { GlassesBits[x][0] = pgm_read_byte(Graphics[frame]+x); } } /* readBrightness(); brightact++; if (brightact > 10) { brightact = 0; //Serial.println(smoothedBrightness); int autoBright = smoothedBrightness; if (autoBright < 50) autoBright = 50; if (autoBright > 255) autoBright = 255; setBrightness(glassesRight, autoBright); setBrightness(glassesLeft, autoBright); } */ // write EEPROM value if it's different from stored value void updateEEPROM(byte location, byte value) { if (EEPROM.read(location) != value) EEPROM.write(location, value); } void saveEEPROMvals() { updateEEPROM(0, 99); updateEEPROM(1, currentEffect); updateEEPROM(2, autoCycle); updateEEPROM(3, currentBrightness); updateEEPROM(4, runMode); } // Write settings to EEPROM if necessary void checkEEPROM() { if (eepromOutdated) { if (currentMillis - eepromMillis > EEPROMDELAY) { saveEEPROMvals(); eepromOutdated = false; } } } void XYPWM(int8_t x, int8_t y, byte value) { if (x >= 0 && x < kMatrixWidth && y >= 0 && y < kMatrixHeight) { if (GlassesPWM[x][y] < value) GlassesPWM[x][y] = value; } }
25.004065
116
0.640384
c1975fd8eeabf074b2bb781910f75aaf64062087
6,967
h
C
UnrealEngine-4.11.2-release/Engine/Source/Editor/PropertyEditor/Public/IPropertyTable.h
armroyce/Unreal
ea1cdebe70407d59af4e8366d7111c52ce4606df
[ "MIT" ]
1
2016-10-01T21:35:52.000Z
2016-10-01T21:35:52.000Z
UnrealEngine-4.11.2-release/Engine/Source/Editor/PropertyEditor/Public/IPropertyTable.h
armroyce/Unreal
ea1cdebe70407d59af4e8366d7111c52ce4606df
[ "MIT" ]
null
null
null
UnrealEngine-4.11.2-release/Engine/Source/Editor/PropertyEditor/Public/IPropertyTable.h
armroyce/Unreal
ea1cdebe70407d59af4e8366d7111c52ce4606df
[ "MIT" ]
1
2021-04-27T08:48:33.000Z
2021-04-27T08:48:33.000Z
// Copyright 1998-2016 Epic Games, Inc. All Rights Reserved. #pragma once #include "IPropertyTableUtilities.h" namespace EPropertyTableSelectionUnit { enum Type { None = 0x00, Row = 0x01, Cell = 0x03 }; } namespace EPropertyTableOrientation { enum Type { AlignPropertiesInColumns, // Items and all their properties are in rows AlignPropertiesInRows, // Items and all their properties are in columns }; } class IDataSource { public: virtual TWeakObjectPtr< UObject > AsUObject() const = 0; virtual TSharedPtr< class FPropertyPath > AsPropertyPath() const = 0; virtual bool IsValid() const = 0; }; class IPropertyTable : public IPropertyTableUtilities { public: virtual void Tick() = 0; virtual void RequestRefresh() = 0; virtual void AddColumn( const TWeakObjectPtr< class UObject >& Object ) = 0; virtual void AddColumn( const TWeakObjectPtr< class UProperty >& Property ) = 0; virtual void AddColumn( const TSharedRef< class FPropertyPath >& PropertyPath ) = 0; virtual void AddColumn( const TSharedRef< class IPropertyTableColumn >& Column ) = 0; virtual void RemoveColumn( const TSharedRef< class IPropertyTableColumn >& Column ) = 0; virtual void AddRow( const TWeakObjectPtr< UObject >& Object ) = 0; virtual void AddRow( const TWeakObjectPtr< UProperty >& Property ) = 0; virtual void AddRow( const TSharedRef< FPropertyPath >& PropertyPath ) = 0; virtual void AddRow( const TSharedRef< class IPropertyTableRow >& Row ) = 0; virtual void RemoveRow( const TSharedRef< class IPropertyTableRow >& Row ) = 0; virtual const EPropertyTableOrientation::Type GetOrientation() const = 0; virtual void SetOrientation( EPropertyTableOrientation::Type InOrientation ) = 0; virtual bool GetIsUserAllowedToChangeRoot() = 0; virtual void SetIsUserAllowedToChangeRoot( bool InAllowUserToChangeRoot ) = 0; virtual void SetRootPath( const TSharedPtr< FPropertyPath >& Path ) = 0; virtual TSharedRef< FPropertyPath> GetRootPath() const = 0; virtual TArray< struct FPropertyInfo > GetPossibleExtensionsForPath( const TSharedRef< FPropertyPath >& Path ) const = 0; virtual void GetSelectedObjects( TArray< TWeakObjectPtr< UObject > >& OutSelectedObjects) const = 0; virtual const TArray< TWeakObjectPtr< UObject > >& GetObjects() const = 0; virtual void SetObjects( const TArray< TWeakObjectPtr< UObject > >& Objects ) = 0; virtual void SetObjects( const TArray< UObject* >& Objects ) = 0; virtual TSharedRef< class FObjectPropertyNode > GetObjectPropertyNode( const TSharedRef< class IPropertyTableColumn >& Column, const TSharedRef< class IPropertyTableRow >& Row ) = 0; virtual TSharedRef< class FObjectPropertyNode > GetObjectPropertyNode( const TWeakObjectPtr< UObject >& Object ) = 0; virtual bool GetShowRowHeader() const = 0; virtual void SetShowRowHeader( const bool ShowRowHeader ) = 0; virtual bool GetShowObjectName() const = 0; virtual void SetShowObjectName( const bool ShowObjectName ) = 0; virtual const TArray< TSharedRef< class IPropertyTableColumn > >& GetColumns() = 0; virtual void SelectCellRange( const TSharedRef< class IPropertyTableCell >& StartingCell, const TSharedRef< class IPropertyTableCell >& EndingCell ) = 0; virtual TArray< TSharedRef< class IPropertyTableRow > >& GetRows() = 0; virtual const TSet< TSharedRef< class IPropertyTableRow > >& GetSelectedRows() = 0; virtual void SetSelectedRows( const TSet< TSharedRef< class IPropertyTableRow > >& InSelectedRows ) = 0; virtual const TSet< TSharedRef< class IPropertyTableCell > >& GetSelectedCells() = 0; virtual void SetSelectedCells( const TSet< TSharedRef< class IPropertyTableCell > >& InSelectedCells ) = 0; virtual float GetItemHeight() const = 0; virtual void SetItemHeight( float NewItemHeight ) = 0; virtual TSharedPtr< class IPropertyTableCell > GetLastClickedCell() const = 0; virtual void SetLastClickedCell( const TSharedPtr< class IPropertyTableCell >& Cell ) = 0; virtual TSharedPtr< class IPropertyTableCell > GetCurrentCell() const = 0; virtual void SetCurrentCell( const TSharedPtr< class IPropertyTableCell >& Cell ) = 0; virtual TSharedPtr< class IPropertyTableColumn > GetCurrentColumn() const = 0; virtual void SetCurrentColumn( const TSharedPtr< class IPropertyTableColumn >& Column ) = 0; virtual TSharedPtr< class IPropertyTableRow > GetCurrentRow() const = 0; virtual void SetCurrentRow( const TSharedPtr< class IPropertyTableRow >& Row ) = 0; virtual TSharedPtr< class IPropertyTableCell > GetFirstCellInSelection() = 0; virtual TSharedPtr< class IPropertyTableCell > GetLastCellInSelection() = 0; virtual TSharedPtr< class IPropertyTableCell > GetNextCellInRow( const TSharedRef< class IPropertyTableCell >& Cell ) = 0; virtual TSharedPtr< class IPropertyTableCell > GetPreviousCellInRow( const TSharedRef< class IPropertyTableCell >& Cell ) = 0; virtual TSharedPtr< class IPropertyTableCell > GetNextCellInColumn( const TSharedRef< class IPropertyTableCell >& Cell ) = 0; virtual TSharedPtr< class IPropertyTableCell > GetPreviousCellInColumn( const TSharedRef< class IPropertyTableCell >& Cell ) = 0; virtual TSharedPtr< class IPropertyTableCell > GetFirstCellInRow( const TSharedRef< class IPropertyTableRow >& Row ) = 0; virtual TSharedPtr< class IPropertyTableCell > GetLastCellInRow( const TSharedRef< class IPropertyTableRow >& Row ) = 0; virtual TSharedPtr< class IPropertyTableCell > GetFirstCellInColumn( const TSharedRef< class IPropertyTableColumn >& Column ) = 0; virtual TSharedPtr< class IPropertyTableCell > GetLastCellInColumn( const TSharedRef< class IPropertyTableColumn >& Column ) = 0; virtual TSharedPtr< class IPropertyTableCell > GetFirstCellInTable() = 0; virtual TSharedPtr< class IPropertyTableCell > GetLastCellInTable() = 0; virtual EPropertyTableSelectionUnit::Type GetSelectionUnit() const = 0; virtual void SetSelectionUnit( const EPropertyTableSelectionUnit::Type Unit ) = 0; virtual ESelectionMode::Type GetSelectionMode() const = 0; virtual void SetSelectionMode( const ESelectionMode::Type Mode ) = 0; virtual EColumnSortMode::Type GetColumnSortMode( const TSharedRef< class IPropertyTableColumn > Column ) const = 0; virtual void SortByColumnWithId( const EColumnSortPriority::Type SortPriority, const FName& ColumnId, const EColumnSortMode::Type SortMode ) = 0; virtual void SortByColumn( const TSharedRef< class IPropertyTableColumn >& Column, EColumnSortMode::Type SortMode ) = 0; virtual void PasteTextAtCell( const FString& Text, const TSharedRef< class IPropertyTableCell >& Cell ) = 0; DECLARE_EVENT( IPropertyTable, FSelectionChanged ); virtual FSelectionChanged* OnSelectionChanged() = 0; DECLARE_EVENT( IPropertyTable, FColumnsChanged ); virtual FColumnsChanged* OnColumnsChanged() = 0; DECLARE_EVENT( IPropertyTable, FRowsChanged ); virtual FRowsChanged* OnRowsChanged() = 0; DECLARE_EVENT( IPropertyTable, FRootPathChanged ); virtual FRootPathChanged* OnRootPathChanged() = 0; };
46.446667
183
0.775513
9cb7ab77c72899107dd1b9a7d12bd16cde0ad8a6
3,585
h
C
Neon Client/Logs.h
Neon-FN/Neon-Client
9f6f62943db896021cc6bf48265169e710fa92d3
[ "BSD-3-Clause" ]
null
null
null
Neon Client/Logs.h
Neon-FN/Neon-Client
9f6f62943db896021cc6bf48265169e710fa92d3
[ "BSD-3-Clause" ]
null
null
null
Neon Client/Logs.h
Neon-FN/Neon-Client
9f6f62943db896021cc6bf48265169e710fa92d3
[ "BSD-3-Clause" ]
null
null
null
#pragma once #include <iostream> #include <filesystem> #include "errors.h" namespace fs = std::filesystem; namespace Colors { inline int cyan = 3; inline int lightRed = 12; inline int green = 10; inline int defaultGray = 7; } static enum ExitTypes { ITEM_NOT_FOUND, }; class Logs { Logs() { } // We don't want anyone making instances public: static void nl() { std::cout << std::endl; } template <typename T> static void Log(T msg, int color = Colors::defaultGray, bool bNl = true, bool rainbowLog = false) { if (rainbowLog) { //bool t = RainbowLog(msg); //if(t) if(bNl) nl(); return; } HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE); SetConsoleTextAttribute(hConsole, color); std::cout << msg; if (bNl) nl(); } template <typename T> static void DebugLog(T msg, int color = Colors::defaultGray, bool bNl = true, bool rainbowLog = false) { if (!PROD) Log(msg, color, bNl, rainbowLog); } static bool RainbowLog(std::string msg) // TODO: Add support for const char etc. { /*if (!checkType(msg, "string")) { HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE); SetConsoleTextAttribute(hConsole, Colors::lightRed); std::cout << "[ERROR] "; SetConsoleTextAttribute(hConsole, Colors::defaultGray); std::cout << "Type was not string!"; return false; } */ int msgIndex = 0; for (int k = 1; k < msg.length() + 1; k++) { if (msgIndex == msg.length() + 1) { nl(); return true; } Log(msg[msgIndex], k, false); msgIndex++; if (k == 15) k = 1; } return true; } void exit(ExitTypes type, std::string msg) { switch (type) { case ITEM_NOT_FOUND: break; default: break; } } }; std::string PathToStr(fs::path p) { std::string pstr = p.u8string(); return pstr; } class File { bool fexists(const fs::path& p) { if (exists(p)) return true; else return false; } bool fdelete(const fs::path& p) { if (!fexists(p)) return false; remove(p); WriteToLog(std::string("Deleted ") + PathToStr(p)); } void fcreate(const fs::path& p) { if (fexists(p)) return; fs::create_directory(p); WriteToLog(std::string("Created ") + PathToStr(p)); } const char* GetEnv(const char* envname) { // SHGetKnownFolderPath(FOLDERID_RoamingAppData, 0, nullptr, &path_tmp); char* pValue; size_t len; errno_t err = _dupenv_s(&pValue, &len, envname); return static_cast<const char*>(pValue); } std::string NeonPath = GetEnv("APPDATA") + std::string("\\Neon\\Neon Client"); std::string GetNeonPath() { return NeonPath; } void InitAD() { if (fexists(NeonPath)) return; fcreate(NeonPath); WriteToLog("Running InitAD.."); return; } template <typename T> void WriteToLog(T msg) { const char* TimeAndDate = __DATE__ + __TIME__; std::ofstream outfile; outfile.open(NeonPath + "\\" + TimeAndDate + ".txt", std::ios::app); if (!outfile.is_open()) Log(ErrorCodes::FSTREAM_NOT_OPEN, Colors::defaultGray, true, true); outfile << msg << std::endl; outfile.close(); } };
24.222973
106
0.54477
96c3ca5f3a72c67f765059014e5b732d4b603f92
1,016
h
C
src/Modules/VRDistortionModule/VRDistortionTransitionModel.h
eegeo/cardboard-vr-integration
3f0c3d0f1b7ddaa6b2ef980e46ead71c8a85a260
[ "BSD-2-Clause" ]
8
2017-07-02T01:14:29.000Z
2021-06-19T07:14:38.000Z
src/Modules/VRDistortionModule/VRDistortionTransitionModel.h
eegeo/cardboard-vr-demo
3f0c3d0f1b7ddaa6b2ef980e46ead71c8a85a260
[ "BSD-2-Clause" ]
null
null
null
src/Modules/VRDistortionModule/VRDistortionTransitionModel.h
eegeo/cardboard-vr-demo
3f0c3d0f1b7ddaa6b2ef980e46ead71c8a85a260
[ "BSD-2-Clause" ]
5
2018-02-07T07:43:51.000Z
2020-01-24T12:29:25.000Z
// Copyright eeGeo Ltd (2012-2014), All Rights Reserved #pragma once #include "Types.h" #include "ICallback.h" #include "CallbackCollection.h" #include "VRDistortionMaterial.h" #include "IVRDistortionTransitionModel.h" namespace Eegeo { namespace VR { namespace Distortion { class VRDistortionTransitionModel : public IVRDistortionTransitionModel, private Eegeo::NonCopyable { public: VRDistortionTransitionModel(); void SetVisibilityParam(float param); float GetVisibilityParam() const { return m_visibilityParam; } void RegisterVisibilityChangedCallback(Helpers::ICallback0& callback); void UnregisterVisibilityChangedCallback(Helpers::ICallback0& callback); private: void NotifyStateChange(); Helpers::CallbackCollection0 m_stateChangedCallbacks; float m_visibilityParam; }; } } }
26.736842
111
0.635827
e7ccd769df1e0bb913e2f892f8be22d739c81b43
905
h
C
TestFiles/Test2.h
ayushkhemka/Parallel_Dependency_Analyzer
596341b6e8ded4b2660ae02020cf4a2b3a23fd9e
[ "MIT" ]
null
null
null
TestFiles/Test2.h
ayushkhemka/Parallel_Dependency_Analyzer
596341b6e8ded4b2660ae02020cf4a2b3a23fd9e
[ "MIT" ]
null
null
null
TestFiles/Test2.h
ayushkhemka/Parallel_Dependency_Analyzer
596341b6e8ded4b2660ae02020cf4a2b3a23fd9e
[ "MIT" ]
null
null
null
namespace Scanner { class SemiExp : public ITokCollection { public: SemiExp(Toker* pToker = nullptr); SemiExp(const SemiExp&) = delete; SemiExp& operator=(const SemiExp&) = delete; bool get(bool clear = true); std::string& operator[](size_t n); std::string operator[](size_t n) const; size_t length(); size_t find(const std::string& tok); void trimFront(); void toLower(); bool remove(const std::string& tok); bool remove(size_t n); void push_back(const std::string& tok); void clear(); bool isComment(const std::string& tok); std::string show(bool showNewLines = false); size_t currentLineCount(); private: bool isTerminator(const std::string& tok); bool getHelper(bool clear = false); bool isSemiColonBetweenParens(); bool hasFor = false; std::vector<std::string> _tokens; Toker* _pToker; }; } #endif
27.424242
48
0.656354
155ec64f8c484ef0d20c1a3f0075faa9b331b03d
273
h
C
src/snapshotxml.h
forkkit/dust3d
2d17a14abe87a99d805d805c4cf412141a0eb883
[ "MIT" ]
null
null
null
src/snapshotxml.h
forkkit/dust3d
2d17a14abe87a99d805d805c4cf412141a0eb883
[ "MIT" ]
null
null
null
src/snapshotxml.h
forkkit/dust3d
2d17a14abe87a99d805d805c4cf412141a0eb883
[ "MIT" ]
null
null
null
#ifndef DUST3D_SNAPSHOT_XML_H #define DUST3D_SNAPSHOT_XML_H #include <QXmlStreamWriter> #include "snapshot.h" void saveSkeletonToXmlStream(Snapshot *snapshot, QXmlStreamWriter *writer); void loadSkeletonFromXmlStream(Snapshot *snapshot, QXmlStreamReader &reader); #endif
27.3
77
0.842491
9ba5c7327ef2ea8491f0a22a7821feeeb8d43b27
35
h
C
recipes-support/libbasic/libbasic-1.0.0/inc/goodbye.h
huynhtai29/Yocto-Beaglebone
48e805aee891b59ff2679f0103e3e8e9c01955bb
[ "MIT" ]
null
null
null
recipes-support/libbasic/libbasic-1.0.0/inc/goodbye.h
huynhtai29/Yocto-Beaglebone
48e805aee891b59ff2679f0103e3e8e9c01955bb
[ "MIT" ]
null
null
null
recipes-support/libbasic/libbasic-1.0.0/inc/goodbye.h
huynhtai29/Yocto-Beaglebone
48e805aee891b59ff2679f0103e3e8e9c01955bb
[ "MIT" ]
null
null
null
#include <stdio.h> void goodbye();
11.666667
18
0.685714
c605eb848791ed693a467d976978b1cef365fecc
873
h
C
System/Library/Frameworks/WidgetKit.framework/WidgetKit.HostToExtensionXPCInterface.h
zhangkn/iOS14Header
4323e9459ed6f6f5504ecbea2710bfd6c3d7c946
[ "MIT" ]
1
2020-11-04T15:43:01.000Z
2020-11-04T15:43:01.000Z
System/Library/Frameworks/WidgetKit.framework/WidgetKit.HostToExtensionXPCInterface.h
zhangkn/iOS14Header
4323e9459ed6f6f5504ecbea2710bfd6c3d7c946
[ "MIT" ]
null
null
null
System/Library/Frameworks/WidgetKit.framework/WidgetKit.HostToExtensionXPCInterface.h
zhangkn/iOS14Header
4323e9459ed6f6f5504ecbea2710bfd6c3d7c946
[ "MIT" ]
null
null
null
/* * This header is generated by classdump-dyld 1.0 * on Sunday, September 27, 2020 at 11:39:45 AM Mountain Standard Time * Operating System: Version 14.0 (Build 18A373) * Image Source: /System/Library/Frameworks/WidgetKit.framework/WidgetKit * classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos. */ @protocol WidgetKit.HostToExtensionXPCInterface @required -(void)invalidate; -(void)getDescriptorsWithCompletion:(/*^block*/id)arg1; -(void)performCleanup; -(void)getPlaceholdersWithEnvironment:(id)arg1 for:(id)arg2 completion:(/*^block*/id)arg3; -(void)handleURLSessionEventsFor:(id)arg1 completion:(/*^block*/id)arg2; -(void)attachPreviewAgentWithFrameworkPath:(id)arg1 endpoint:(id)arg2 handler:(/*^block*/id)arg3; -(void)getTimelineFor:(id)arg1 into:(id)arg2 environment:(id)arg3 isPreview:(BOOL)arg4 completion:(/*^block*/id)arg5; @end
39.681818
117
0.77205
18c507d81cc50fee5f9c50410aae403a5d83e0e6
2,970
h
C
parser.h
CTSRD-CHERI/openradtool
bb444d5f52f96e9ac8ee64fa7c7738fd4f972176
[ "ISC" ]
21
2017-06-01T04:47:08.000Z
2019-02-16T02:15:16.000Z
parser.h
CTSRD-CHERI/openradtool
bb444d5f52f96e9ac8ee64fa7c7738fd4f972176
[ "ISC" ]
7
2017-11-01T16:32:50.000Z
2018-12-29T17:16:07.000Z
parser.h
CTSRD-CHERI/openradtool
bb444d5f52f96e9ac8ee64fa7c7738fd4f972176
[ "ISC" ]
4
2017-06-19T02:50:08.000Z
2018-12-13T21:43:04.000Z
/* $Id$ */ /* * Copyright (c) 2020 Kristaps Dzonsons <kristaps@bsd.lv> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #ifndef PARSER_H #define PARSER_H /* * These are our lexical tokens parsed from input. */ enum tok { TOK_NONE, /* special case: just starting */ TOK_COLON, /* : */ TOK_COMMA, /* ; */ TOK_DECIMAL, /* decimal-valued number */ TOK_EOF, /* end of file! */ TOK_ERR, /* error! */ TOK_IDENT, /* alphanumeric (starting with alpha) */ TOK_INTEGER, /* integer */ TOK_LBRACE, /* { */ TOK_LITERAL, /* "text" */ TOK_PERIOD, /* } */ TOK_RBRACE, /* } */ TOK_SEMICOLON /* ; */ }; /* * Shorthand for checking whether we should stop parsing (we're at the * end of file or have an error). */ #define PARSE_STOP(_p) \ (TOK_ERR == (_p)->lasttype || TOK_EOF == (_p)->lasttype) /* * The current parse. * If we have multiple files to parse, we must reinitialise this * structure (including freeing resources, for now limited to "buf"), as * it only pertains to the current one. */ struct parse { union { const char *string; /* last parsed string */ int64_t integer; /* ...integer */ double decimal; /* ...double */ } last; enum tok lasttype; /* last parse type */ char *buf; /* buffer for storing up reads */ size_t bufsz; /* length of buffer */ size_t bufmax; /* maximum buffer size */ size_t line; /* current line (from 1) */ size_t column; /* current column (from 1) */ const char *fname; /* current filename */ struct config *cfg; /* current configuration */ FILE *f; }; int parse_check_badidents(struct parse *, const char *); int parse_check_dupetoplevel(struct parse *, const char *); int parse_comment(struct parse *, char **); int parse_label(struct parse *, struct labelq *); void parse_point(const struct parse *, struct pos *); enum tok parse_next(struct parse *); enum tok parse_err(struct parse *); enum tok parse_errx(struct parse *, const char *, ...) __attribute__((format(printf, 2, 3))); void parse_warnx(struct parse *, const char *, ...) __attribute__((format(printf, 2, 3))); void parse_bitfield(struct parse *); void parse_enum(struct parse *); void parse_field(struct parse *, struct strct *); void parse_struct(struct parse *); void parse_roles(struct parse *); #endif /* !PARSER_H */
32.282609
75
0.689562
6fc7dc5353ebd15b0c5384adacbdcfb670cbdbf8
4,526
h
C
src/BtParse.h
ysuttep/Bitusk
90dfba8b04764c760c5ad70493732479fcb2de38
[ "Apache-2.0" ]
null
null
null
src/BtParse.h
ysuttep/Bitusk
90dfba8b04764c760c5ad70493732479fcb2de38
[ "Apache-2.0" ]
null
null
null
src/BtParse.h
ysuttep/Bitusk
90dfba8b04764c760c5ad70493732479fcb2de38
[ "Apache-2.0" ]
null
null
null
/* ============================================= * @brief : Bt downloader logger * @copyright: Copyright 2021 iusyu * @license : Apache * @birth : 2021-05-01 23:48 * @author : sunyi * @version : 0.1.0 * @revisions: 2021-05-22 ============================================== */ #pragma once #include <string> #include <iostream> #include <sstream> #include <fstream> #include <memory> #include <utility> #include <vector> #include <map> class ParseMetaFile; /* Bittorrent File keyword struct */ struct BittorrentData { BittorrentData(); bool empty() const ; /* Announce Key */ /* Tracker URL */ std::string announce; std::vector<std::string> announceList; /* Select */ std::string creationDate; std::string comment; std::string createBy; /* keyword 'info' has value of diction * * * common keyword contained * @piece_length : length of every piece * @pieces : a string of hash value * @private : ...... * * single file mode * @name * @length * @md5sum * * multifile mode * @name : store all shared files' directory name * @files : have a directory value specifing in 'std::map<std::string, std::string> files ' * */ std::string name; unsigned piece_length = 0; std::vector<std::string> pieces; std::string bprivate; /* If Single File will be length */ unsigned length; /* keyword 'info' has keyword 'files' in multifile mode * @length : shared file length, Unit is Byte * @md5sum * @path : store the path and name of shared files * key: file path * value: file length */ std::map<std::string, unsigned long> files; /* Key word about peers */ std::string hashStr; std::string peer_id; }; /* parse four data type */ class SegmentParse { public: typedef std::string::iterator strIterator; static std::string parseInt(strIterator& itr); static unsigned parseStrLen(strIterator& itr); static std::string parseStr(strIterator& itr); static std::string getSegment(strIterator& itr); static std::pair<std::string, unsigned long> parseDictPair(std::string::iterator&itr); }; /* using template method */ template<typename T> class BaseParse { public: typedef T valueType; BaseParse() = delete; BaseParse(const BaseParse& ) = delete; virtual valueType parsing(const std::string&, const std::string&) = 0; virtual ~BaseParse(); }; /* parse info keyword */ class ParseInfo:public BaseParse<std::map<std::string,std::string>> { public: virtual valueType parsing(const std::string&, const std::string&) override ; valueType parseInfo(const std::string& srcStr, const std::string& key); }; /* the basic tools for parse String */ class ParseMetaFile { public: using sizeType = std::string::size_type; ParseMetaFile() = delete; ParseMetaFile(const ParseMetaFile&) = delete; ParseMetaFile(const std::string& ); static const std::string readMetafileToString(const std::string& filename); bool isMultiFiles() const; const BittorrentData& getData() const; const std::vector<std::string>& getAnnounceList() const; const std::string& getAnnounce() const; const unsigned getPieceLength() const; const std::vector<std::string>& getPieceHash() const; /* * @breif * @return if multi files it will return folder name; * if single file it will return file name; */ const std::string& getFileName() const; /* * @breif * @return if multifiles it will return file path and length keyvalue pair * if single it will return empty data; */ const std::map<std::string,unsigned long>& getFilePathAndLength() const; /* * @breif Info_hash will be used when connecting Tracker and Peer * @return info hash */ const std::string& getInfoHash() const; /* * @breif peer_id * @return Peer ID to connecting PEER */ const std::string& getPeerId() const; bool checkParse(); void parseIt(); private: virtual void readAnnounceList(); virtual bool readIsMultiFiles(); virtual void readPieceLength(); virtual void readPiecesHash(); virtual void readFileName(); virtual void readFileLength(); virtual void readFilesLengthPath(); virtual void readInfoHash(); virtual void readPeerId(); private: BittorrentData data; // TODO 编码方式 选择 std::string MetaFileString; }; std::ostream& operator<<(std::ostream&, const BittorrentData&); // // // // // // // // // // // // // // //NEW DESIGN OF PARSE IMP WITH TMP // // // // // // // // // // // // // // struct INT_tag {}; struct STR_tag {}; struct DIC_tag {}; struct LIS_tag {};
21.970874
93
0.662616
8d04a18abe5ae4b51c7c893d2a79007091f739b1
278
h
C
SimG4Core/Notification/interface/BeginOfTrack.h
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
852
2015-01-11T21:03:51.000Z
2022-03-25T21:14:00.000Z
SimG4Core/Notification/interface/BeginOfTrack.h
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
30,371
2015-01-02T00:14:40.000Z
2022-03-31T23:26:05.000Z
SimG4Core/Notification/interface/BeginOfTrack.h
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
3,240
2015-01-02T05:53:18.000Z
2022-03-31T17:24:21.000Z
#ifndef SimG4Core_BeginOfTrack_H #define SimG4Core_BeginOfTrack_H #include "G4Track.hh" class BeginOfTrack { public: BeginOfTrack(const G4Track* tTrack) : aTrack(tTrack) {} const G4Track* operator()() const { return aTrack; } private: const G4Track* aTrack; }; #endif
17.375
57
0.748201
8d24a485c5b51254a6db6192ec875bb24b3cafe6
812
c
C
src/mpid/mm/src/xfer/xfer_init.c
raffenet/mpich-CVS
2d33e2742e8c00db4f56a373fea051cc6c0ee0d0
[ "mpich2" ]
null
null
null
src/mpid/mm/src/xfer/xfer_init.c
raffenet/mpich-CVS
2d33e2742e8c00db4f56a373fea051cc6c0ee0d0
[ "mpich2" ]
null
null
null
src/mpid/mm/src/xfer/xfer_init.c
raffenet/mpich-CVS
2d33e2742e8c00db4f56a373fea051cc6c0ee0d0
[ "mpich2" ]
null
null
null
/* -*- Mode: C; c-basic-offset:4 ; -*- */ /* * (C) 2001 by Argonne National Laboratory. * See COPYRIGHT in top-level directory. */ #include "mpidimpl.h" /*@ xfer_init - xfer_init Parameters: + int tag - tag . MPID_Comm *comm_ptr - communicator - MPID_Request **request_pptr - request pointer Notes: @*/ int xfer_init(int tag, MPID_Comm *comm_ptr, MPID_Request **request_pptr) { MPID_Request *pRequest; MPIDI_STATE_DECL(MPID_STATE_XFER_INIT); MPIDI_FUNC_ENTER(MPID_STATE_XFER_INIT); pRequest = mm_request_alloc(); pRequest->comm = comm_ptr; pRequest->mm.tag = tag; pRequest->mm.op_valid = FALSE; pRequest->cc = 0; pRequest->cc_ptr = &pRequest->cc; *request_pptr = pRequest; MPIDI_FUNC_EXIT(MPID_STATE_XFER_INIT); return MPI_SUCCESS; }
20.820513
72
0.673645
e45116ee2f9dbb7fb535c45c6c8eb459334114fb
9,017
h
C
sumo/src/microsim/MSContainer.h
iltempe/osmosi
c0f54ecdbb7c7b5602d587768617d0dc50f1d75d
[ "MIT" ]
null
null
null
sumo/src/microsim/MSContainer.h
iltempe/osmosi
c0f54ecdbb7c7b5602d587768617d0dc50f1d75d
[ "MIT" ]
null
null
null
sumo/src/microsim/MSContainer.h
iltempe/osmosi
c0f54ecdbb7c7b5602d587768617d0dc50f1d75d
[ "MIT" ]
2
2017-12-14T16:41:59.000Z
2020-10-16T17:51:27.000Z
/****************************************************************************/ /// @file MSContainer.h /// @author Melanie Weber /// @author Andreas Kendziorra /// @date Thu, 12 Jun 2014 /// @version $Id$ /// // The class for modelling container-movements /****************************************************************************/ // SUMO, Simulation of Urban MObility; see http://sumo.dlr.de/ // Copyright (C) 2001-2017 DLR (http://www.dlr.de/) and contributors /****************************************************************************/ // // This file is part of SUMO. // SUMO is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // /****************************************************************************/ #ifndef MSContainer_h #define MSContainer_h // =========================================================================== // included modules // =========================================================================== #ifdef _MSC_VER #include <windows_config.h> #else #include <config.h> #endif #include <string> #include <vector> #include <set> #include <utils/common/SUMOTime.h> #include <utils/common/Command.h> #include <utils/geom/Position.h> #include <utils/geom/PositionVector.h> #include <microsim/MSTransportable.h> // =========================================================================== // class declarations // =========================================================================== class MSNet; class MSEdge; class MSLane; class OutputDevice; class SUMOVehicleParameter; class MSStoppingPlace; class SUMOVehicle; class MSVehicleType; class MSCModel_NonInteracting; class CState; // =========================================================================== // class definitions // =========================================================================== /** * @class MSContainer * * The class holds a simulated container together with its movement stages */ class MSContainer : public MSTransportable { public: /** * A "real" stage performing the travelling by a transport system * A container is in this stage if it is on a ride or if its waiting for a ride. * The given route will be chosen. The travel time is computed by the simulation */ class MSContainerStage_Driving : public MSTransportable::Stage_Driving { public: /// constructor MSContainerStage_Driving(const MSEdge& destination, MSStoppingPlace* toStop, const double arrivalPos, const std::vector<std::string>& lines); /// destructor ~MSContainerStage_Driving(); /// proceeds to the next step virtual void proceed(MSNet* net, MSTransportable* container, SUMOTime now, Stage* previous); /// @brief returns the stage description as a string std::string getStageDescription() const; /** @brief Called on writing tripinfo output * * @param[in] os The stream to write the information into * @exception IOError not yet implemented */ virtual void tripInfoOutput(OutputDevice& os) const; /** @brief Called on writing vehroute output * * @param[in] os The stream to write the information into * @exception IOError not yet implemented */ virtual void routeOutput(OutputDevice& os) const; }; /** * A "real" stage performing the tranship of a container * A container is in this stage if it gets transhipred between two stops that are * assumed to be connected. */ class MSContainerStage_Tranship : public MSTransportable::Stage { friend class MSCModel_NonInteracting; public: /// constructor MSContainerStage_Tranship(const std::vector<const MSEdge*>& route, MSStoppingPlace* toStop, double speed, double departPos, double arrivalPos); /// destructor ~MSContainerStage_Tranship(); /// proceeds to the next step virtual void proceed(MSNet* net, MSTransportable* container, SUMOTime now, Stage* previous); /// Returns the current edge const MSEdge* getEdge() const; /// Returns first edge of the containers route const MSEdge* getFromEdge() const; /// Returns last edge of the containers route const MSEdge* getToEdge() const; /// Returns the offset from the start of the current edge measured in its natural direction double getEdgePos(SUMOTime now) const; /// Returns the position of the container Position getPosition(SUMOTime now) const; /// Returns the angle of the container double getAngle(SUMOTime now) const; /// Returns the time the container spent waiting SUMOTime getWaitingTime(SUMOTime now) const; /// Returns the speed of the container double getSpeed() const; /// @brief the edges of the current stage ConstMSEdgeVector getEdges() const; /// Returns the current stage description as a string std::string getStageDescription() const { return "tranship"; } /** @brief Called on writing tripinfo output * @param[in] os The stream to write the information into * @exception IOError not yet implemented */ virtual void tripInfoOutput(OutputDevice& os) const; /** @brief Called on writing vehroute output * @param[in] os The stream to write the information into * @exception IOError not yet implemented */ virtual void routeOutput(OutputDevice& os) const; /** @brief Called for writing the events output * @param[in] os The stream to write the information into * @exception IOError not yet implemented */ virtual void beginEventOutput(const MSTransportable& c, SUMOTime t, OutputDevice& os) const; /** @brief Called for writing the events output (end of an action) * @param[in] os The stream to write the information into * @exception IOError not yet implemented */ virtual void endEventOutput(const MSTransportable& c, SUMOTime t, OutputDevice& os) const; /// @brief move forward and return whether the container arrived bool moveToNextEdge(MSTransportable* container, SUMOTime currentTime, MSEdge* nextInternal = 0); /// @brief accessors to be used by MSCModel_NonInteracting inline double getMaxSpeed() const { return mySpeed; } inline double getDepartPos() const { return myDepartPos; } inline double getArrivalPos() const { return myArrivalPos; } inline const MSEdge* getNextRouteEdge() const { return myRouteStep == myRoute.end() - 1 ? 0 : *(myRouteStep + 1); } CState* getContainerState() const { return myContainerState; } private: /// @brief The route of the container std::vector<const MSEdge*> myRoute; /// @brief current step std::vector<const MSEdge*>::iterator myRouteStep; /// @brief the depart position double myDepartPos; /// @brief the speed of the container double mySpeed; /// @brief state that is to be manipulated by MSCModel CState* myContainerState; /// @brief The current internal edge this container is on or 0 MSEdge* myCurrentInternalEdge; private: /// @brief Invalidated copy constructor. MSContainerStage_Tranship(const MSContainerStage_Tranship&); /// @brief Invalidated assignment operator. MSContainerStage_Tranship& operator=(const MSContainerStage_Tranship&); }; public: /// constructor MSContainer(const SUMOVehicleParameter* pars, MSVehicleType* vtype, MSTransportablePlan* plan); /// destructor virtual ~MSContainer(); /* @brief proceeds to the next step of the route, * @return Whether the persons plan continues */ virtual bool proceed(MSNet* net, SUMOTime time); /** @brief Called on writing tripinfo output * * @param[in] os The stream to write the information into * @exception IOError not yet implemented */ virtual void tripInfoOutput(OutputDevice& os) const; /** @brief Called on writing vehroute output * * @param[in] os The stream to write the information into * @exception IOError not yet implemented */ virtual void routeOutput(OutputDevice& os) const; private: /// @brief Invalidated copy constructor. MSContainer(const MSContainer&); /// @brief Invalidated assignment operator. MSContainer& operator=(const MSContainer&); }; #endif /****************************************************************************/
33.150735
151
0.597649
9d929fa6983bb7764fbe4f0159c3bad1f25dd674
429
h
C
MgpWallet/TaiYiToken/首页/首页钱包/EOSManager/View/AuthorView.h
mangochain2020/mangowallet-ios
8481187bd16efd1f313bc77691aa0ecd47eebd8f
[ "MIT" ]
1
2021-03-03T03:07:47.000Z
2021-03-03T03:07:47.000Z
MgpWallet/TaiYiToken/首页/首页钱包/EOSManager/View/AuthorView.h
mangochain2020/mangowallet-ios
8481187bd16efd1f313bc77691aa0ecd47eebd8f
[ "MIT" ]
null
null
null
MgpWallet/TaiYiToken/首页/首页钱包/EOSManager/View/AuthorView.h
mangochain2020/mangowallet-ios
8481187bd16efd1f313bc77691aa0ecd47eebd8f
[ "MIT" ]
3
2020-12-27T07:45:04.000Z
2021-03-03T03:07:49.000Z
// // AuthorView.h // TaiYiToken // // Created by 张元一 on 2018/12/17. // Copyright © 2018 admin. All rights reserved. // #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN @interface AuthorView : UIView @property(nonatomic,copy)NSString *keystr; @property(nonatomic,copy)NSString *authority; @property(nonatomic,assign)NSInteger weight; @property(nonatomic,strong)UIView *backView; -(void)initUI; @end NS_ASSUME_NONNULL_END
18.652174
48
0.757576
77d82b898c8b0bc96dd6fd8fa915082c45f842ce
71
c
C
testsuite/systemtest_long/procgen/PlatformIntegrator/KoskiIntegrator/data/main.c
kanishkan/tce
430e764b4d43f46bd1dc754aeb1d5632fc742110
[ "MIT" ]
74
2015-10-22T15:34:10.000Z
2022-03-25T07:57:23.000Z
testsuite/systemtest_long/procgen/PlatformIntegrator/KoskiIntegrator/data/main.c
kanishkan/tce
430e764b4d43f46bd1dc754aeb1d5632fc742110
[ "MIT" ]
79
2015-11-19T09:23:08.000Z
2022-01-12T14:15:16.000Z
testsuite/systemtest_long/procgen/PlatformIntegrator/KoskiIntegrator/data/main.c
kanishkan/tce
430e764b4d43f46bd1dc754aeb1d5632fc742110
[ "MIT" ]
38
2015-11-17T10:12:23.000Z
2022-03-25T07:57:24.000Z
volatile int foo = 0; int main() { foo = 42; return 0; }
8.875
21
0.478873
16073239ac625df7efd3b3da46b77bd8f5b760fb
333
h
C
2017_05_25/adj_matrix/adj_matrix.h
YellwithOut/Data-structure
fec4bbc0b41f83bbc7aab85531788fcd3ccde50c
[ "MIT" ]
null
null
null
2017_05_25/adj_matrix/adj_matrix.h
YellwithOut/Data-structure
fec4bbc0b41f83bbc7aab85531788fcd3ccde50c
[ "MIT" ]
null
null
null
2017_05_25/adj_matrix/adj_matrix.h
YellwithOut/Data-structure
fec4bbc0b41f83bbc7aab85531788fcd3ccde50c
[ "MIT" ]
null
null
null
#pragma once #define MAX_VERTICES 100 int adj[MAX_VERTICES][MAX_VERTICES]; int visited[MAX_VERTICES]; typedef struct node* nodeptr; typedef struct node { int vertex; nodeptr link; }node; nodeptr queue; void insert_edge(int v, int w); void build_simple_graph(); void DFS(int v); void addq(int e); int deleteq(); void BFS(int v);
16.65
36
0.747748
3fb7554a29f8f6d50e6621b63831d7db5b74149c
1,510
h
C
Alien Engine/Alien Engine/ResourceFont.h
OverPowered-Team/Alien-GameEngine
713a8846a95fdf253d0869bdcad4ecd006b2e166
[ "MIT" ]
7
2020-02-20T15:11:11.000Z
2020-05-19T00:29:04.000Z
Alien Engine/Alien Engine/ResourceFont.h
OverPowered-Team/Alien-GameEngine
713a8846a95fdf253d0869bdcad4ecd006b2e166
[ "MIT" ]
125
2020-02-29T17:17:31.000Z
2020-05-06T19:50:01.000Z
Alien Engine/Alien Engine/ResourceFont.h
OverPowered-Team/Alien-GameEngine
713a8846a95fdf253d0869bdcad4ecd006b2e166
[ "MIT" ]
1
2020-05-19T00:29:06.000Z
2020-05-19T00:29:06.000Z
#pragma once #include "Resource_.h" #include "MathGeoLib/include/Math/float2.h" #include <map> typedef unsigned char uchar; class ResourceShader; struct FontImportSettings { std::string fontPath; std::vector<uint> sizes; }; struct Character { uint textureID; // ID handle of the glyph texture float2 size; // Size of glyph float2 bearing; // Offset from baseline to left/top of glyph uint advance; // Offset to advance to next glyph }; struct ResourceFontData { uint fontSize; uint maxCharHeight; std::map<char, Character> charactersMap; std::vector<uint8_t*> fontBuffer; }; class ResourceFont : public Resource { public: ResourceFont(ResourceFontData fontData); virtual ~ResourceFont(); void CreateMeta(); static ResourceFont* ImportFile(const char* file, u64 forced_id = 0); static ResourceFont* ImportFont(const char* file, u64 forced_id); static ResourceFont* LoadFile(const char* file, u64 forced_id); private: static uint LoadTextureCharacter(uint width, uint height, uchar* buffer); static uint SaveFile(ResourceFontData& fontData, const char* exported_path, u64 ortho, u64 text); bool LoadMemory(); void FreeMemory(); static ResourceShader* SetShader(const char* path); //bool ReadBaseInfo(const char* assets_path); //void ReadLibrary(const char* meta_data); //bool DeleteMetaData(); public: FontImportSettings importSettings; ResourceFontData fontData; ResourceShader* text_shader = nullptr; ResourceShader* background_shader = nullptr; };
25.59322
98
0.754967
277dbe6758da16b751944015c0e56b3e11c08867
826
h
C
src/pf_imgui/elements/GroupBox.h
PetrFlajsingr/pf_imgui
ffddd99d0e01e03f829108294de7c5f13afa9281
[ "MIT" ]
13
2021-04-19T12:29:30.000Z
2022-03-27T10:54:11.000Z
src/pf_imgui/elements/GroupBox.h
PetrFlajsingr/pf_imgui
ffddd99d0e01e03f829108294de7c5f13afa9281
[ "MIT" ]
34
2021-01-22T19:16:28.000Z
2022-03-31T19:06:29.000Z
src/pf_imgui/elements/GroupBox.h
PetrFlajsingr/pf_imgui
ffddd99d0e01e03f829108294de7c5f13afa9281
[ "MIT" ]
4
2021-01-22T18:44:41.000Z
2021-11-19T04:40:31.000Z
// // Created by xflajs00 on 17.11.2021. // #ifndef PF_IMGUI_GROUPBOX_H #define PF_IMGUI_GROUPBOX_H #include <pf_imgui/interface/Element.h> #include <pf_imgui/interface/ElementContainer.h> #include <pf_imgui/interface/Labellable.h> #include <pf_imgui/interface/Resizable.h> namespace pf::ui::ig { /** * @brief A group of elements with a border and a label. */ class GroupBox : public Element, public ElementContainer, public Labellable, public Resizable { public: /** * Construct GroupBox. * @param name unique name of the element * @param label label rendered on the top of the groupbox * @param s size of the groupbox */ GroupBox(const std::string &name, const std::string &label, const Size &s); protected: void renderImpl() override; }; }// namespace pf::ui::ig #endif//PF_IMGUI_GROUPBOX_H
23.6
95
0.726392
d41d2b482191c7cbc4314a3ccd9b8585ee2a6e84
13,496
c
C
src/cmd/upas/fs/pop3.c
newluhux/plan9port
f403539d479c1ecb60988e6d87f9031b1435f794
[ "MIT" ]
1,391
2015-01-02T22:15:05.000Z
2022-03-31T04:53:12.000Z
src/cmd/upas/fs/pop3.c
newluhux/plan9port
f403539d479c1ecb60988e6d87f9031b1435f794
[ "MIT" ]
441
2015-01-03T07:11:09.000Z
2022-03-31T13:12:22.000Z
src/cmd/upas/fs/pop3.c
newluhux/plan9port
f403539d479c1ecb60988e6d87f9031b1435f794
[ "MIT" ]
404
2015-01-03T13:00:57.000Z
2022-03-18T09:43:37.000Z
#include "common.h" #include <ctype.h> #include <plumb.h> #include <libsec.h> #include <auth.h> #include <thread.h> #include "dat.h" #pragma varargck type "M" uchar* #pragma varargck argpos pop3cmd 2 typedef struct Pop Pop; struct Pop { char *freep; /* free this to free the strings below */ char *host; char *user; char *port; int ppop; int refreshtime; int debug; int pipeline; int encrypted; int needtls; int notls; int needssl; /* open network connection */ Biobuf bin; Biobuf bout; int fd; char *lastline; /* from Brdstr */ Thumbprint *thumb; }; char* geterrstr(void) { static char err[64]; err[0] = '\0'; errstr(err, sizeof(err)); return err; } /* */ /* get pop3 response line , without worrying */ /* about multiline responses; the clients */ /* will deal with that. */ /* */ static int isokay(char *s) { return s!=nil && strncmp(s, "+OK", 3)==0; } static void pop3cmd(Pop *pop, char *fmt, ...) { char buf[128], *p; va_list va; va_start(va, fmt); vseprint(buf, buf+sizeof(buf), fmt, va); va_end(va); p = buf+strlen(buf); if(p > (buf+sizeof(buf)-3)) sysfatal("pop3 command too long"); if(pop->debug) fprint(2, "<- %s\n", buf); strcpy(p, "\r\n"); Bwrite(&pop->bout, buf, strlen(buf)); Bflush(&pop->bout); } static char* pop3resp(Pop *pop) { char *s; char *p; alarm(60*1000); if((s = Brdstr(&pop->bin, '\n', 0)) == nil){ close(pop->fd); pop->fd = -1; alarm(0); return "unexpected eof"; } alarm(0); p = s+strlen(s)-1; while(p >= s && (*p == '\r' || *p == '\n')) *p-- = '\0'; if(pop->debug) fprint(2, "-> %s\n", s); free(pop->lastline); pop->lastline = s; return s; } #if 0 /* jpc */ static int pop3log(char *fmt, ...) { va_list ap; va_start(ap,fmt); syslog(0, "/sys/log/pop3", fmt, ap); va_end(ap); return 0; } #endif static char* pop3pushtls(Pop *pop) { int fd; uchar digest[SHA1dlen]; TLSconn conn; memset(&conn, 0, sizeof conn); /* conn.trace = pop3log; */ fd = tlsClient(pop->fd, &conn); if(fd < 0) return "tls error"; if(conn.cert==nil || conn.certlen <= 0){ close(fd); return "server did not provide TLS certificate"; } sha1(conn.cert, conn.certlen, digest, nil); if(!pop->thumb || !okThumbprint(digest, pop->thumb)){ fmtinstall('H', encodefmt); close(fd); free(conn.cert); fprint(2, "upas/fs pop3: server certificate %.*H not recognized\n", SHA1dlen, digest); return "bad server certificate"; } free(conn.cert); close(pop->fd); pop->fd = fd; pop->encrypted = 1; Binit(&pop->bin, pop->fd, OREAD); Binit(&pop->bout, pop->fd, OWRITE); return nil; } /* */ /* get capability list, possibly start tls */ /* */ static char* pop3capa(Pop *pop) { char *s; int hastls; pop3cmd(pop, "CAPA"); if(!isokay(pop3resp(pop))) return nil; hastls = 0; for(;;){ s = pop3resp(pop); if(strcmp(s, ".") == 0 || strcmp(s, "unexpected eof") == 0) break; if(strcmp(s, "STLS") == 0) hastls = 1; if(strcmp(s, "PIPELINING") == 0) pop->pipeline = 1; } if(hastls && !pop->notls){ pop3cmd(pop, "STLS"); if(!isokay(s = pop3resp(pop))) return s; if((s = pop3pushtls(pop)) != nil) return s; } return nil; } /* */ /* log in using APOP if possible, password if allowed by user */ /* */ static char* pop3login(Pop *pop) { int n; char *s, *p, *q; char ubuf[128], user[128]; char buf[500]; UserPasswd *up; s = pop3resp(pop); if(!isokay(s)) return "error in initial handshake"; if(pop->user) snprint(ubuf, sizeof ubuf, " user=%q", pop->user); else ubuf[0] = '\0'; /* look for apop banner */ if(pop->ppop==0 && (p = strchr(s, '<')) && (q = strchr(p+1, '>'))) { *++q = '\0'; if((n=auth_respond(p, q-p, user, sizeof user, buf, sizeof buf, auth_getkey, "proto=apop role=client server=%q%s", pop->host, ubuf)) < 0) return "factotum failed"; if(user[0]=='\0') return "factotum did not return a user name"; if(s = pop3capa(pop)) return s; pop3cmd(pop, "APOP %s %.*s", user, n, buf); if(!isokay(s = pop3resp(pop))) return s; return nil; } else { if(pop->ppop == 0) return "no APOP hdr from server"; if(s = pop3capa(pop)) return s; if(pop->needtls && !pop->encrypted) return "could not negotiate TLS"; up = auth_getuserpasswd(auth_getkey, "proto=pass role=client service=pop dom=%q%s", pop->host, ubuf); if(up == nil) return "no usable keys found"; pop3cmd(pop, "USER %s", up->user); if(!isokay(s = pop3resp(pop))){ free(up); return s; } pop3cmd(pop, "PASS %s", up->passwd); free(up); if(!isokay(s = pop3resp(pop))) return s; return nil; } } /* */ /* dial and handshake with pop server */ /* */ static char* pop3dial(Pop *pop) { char *err; if((pop->fd = dial(netmkaddr(pop->host, "net", pop->needssl ? "pop3s" : "pop3"), 0, 0, 0)) < 0) return geterrstr(); if(pop->needssl){ if((err = pop3pushtls(pop)) != nil) return err; }else{ Binit(&pop->bin, pop->fd, OREAD); Binit(&pop->bout, pop->fd, OWRITE); } if(err = pop3login(pop)) { close(pop->fd); return err; } return nil; } /* */ /* close connection */ /* */ static void pop3hangup(Pop *pop) { pop3cmd(pop, "QUIT"); pop3resp(pop); close(pop->fd); } /* */ /* download a single message */ /* */ static char* pop3download(Pop *pop, Message *m) { char *s, *f[3], *wp, *ep; char sdigest[SHA1dlen*2+1]; int i, l, sz; if(!pop->pipeline) pop3cmd(pop, "LIST %d", m->mesgno); if(!isokay(s = pop3resp(pop))) return s; if(tokenize(s, f, 3) != 3) return "syntax error in LIST response"; if(atoi(f[1]) != m->mesgno) return "out of sync with pop3 server"; sz = atoi(f[2])+200; /* 200 because the plan9 pop3 server lies */ if(sz == 0) return "invalid size in LIST response"; m->start = wp = emalloc(sz+1); ep = wp+sz; if(!pop->pipeline) pop3cmd(pop, "RETR %d", m->mesgno); if(!isokay(s = pop3resp(pop))) { m->start = nil; free(wp); return s; } s = nil; while(wp <= ep) { s = pop3resp(pop); if(strcmp(s, "unexpected eof") == 0) { free(m->start); m->start = nil; return "unexpected end of conversation"; } if(strcmp(s, ".") == 0) break; l = strlen(s)+1; if(s[0] == '.') { s++; l--; } /* * grow by 10%/200bytes - some servers * lie about message sizes */ if(wp+l > ep) { int pos = wp - m->start; sz += ((sz / 10) < 200)? 200: sz/10; m->start = erealloc(m->start, sz+1); wp = m->start+pos; ep = m->start+sz; } memmove(wp, s, l-1); wp[l-1] = '\n'; wp += l; } if(s == nil || strcmp(s, ".") != 0) return "out of sync with pop3 server"; m->end = wp; /* make sure there's a trailing null */ /* (helps in body searches) */ *m->end = 0; m->bend = m->rbend = m->end; m->header = m->start; /* digest message */ sha1((uchar*)m->start, m->end - m->start, m->digest, nil); for(i = 0; i < SHA1dlen; i++) sprint(sdigest+2*i, "%2.2ux", m->digest[i]); m->sdigest = s_copy(sdigest); return nil; } /* */ /* check for new messages on pop server */ /* UIDL is not required by RFC 1939, but */ /* netscape requires it, so almost every server supports it. */ /* we'll use it to make our lives easier. */ /* */ static char* pop3read(Pop *pop, Mailbox *mb, int doplumb) { char *s, *p, *uidl, *f[2]; int mesgno, ignore, nnew; Message *m, *next, **l; /* Some POP servers disallow UIDL if the maildrop is empty. */ pop3cmd(pop, "STAT"); if(!isokay(s = pop3resp(pop))) return s; /* fetch message listing; note messages to grab */ l = &mb->root->part; if(strncmp(s, "+OK 0 ", 6) != 0) { pop3cmd(pop, "UIDL"); if(!isokay(s = pop3resp(pop))) return s; for(;;){ p = pop3resp(pop); if(strcmp(p, ".") == 0 || strcmp(p, "unexpected eof") == 0) break; if(tokenize(p, f, 2) != 2) continue; mesgno = atoi(f[0]); uidl = f[1]; if(strlen(uidl) > 75) /* RFC 1939 says 70 characters max */ continue; ignore = 0; while(*l != nil) { if(strcmp((*l)->uidl, uidl) == 0) { /* matches mail we already have, note mesgno for deletion */ (*l)->mesgno = mesgno; ignore = 1; l = &(*l)->next; break; } else { /* old mail no longer in box mark deleted */ if(doplumb) mailplumb(mb, *l, 1); (*l)->inmbox = 0; (*l)->deleted = 1; l = &(*l)->next; } } if(ignore) continue; m = newmessage(mb->root); m->mallocd = 1; m->inmbox = 1; m->mesgno = mesgno; strcpy(m->uidl, uidl); /* chain in; will fill in message later */ *l = m; l = &m->next; } } /* whatever is left has been removed from the mbox, mark as deleted */ while(*l != nil) { if(doplumb) mailplumb(mb, *l, 1); (*l)->inmbox = 0; (*l)->deleted = 1; l = &(*l)->next; } /* download new messages */ nnew = 0; if(pop->pipeline){ switch(rfork(RFPROC|RFMEM)){ case -1: fprint(2, "rfork: %r\n"); pop->pipeline = 0; default: break; case 0: for(m = mb->root->part; m != nil; m = m->next){ if(m->start != nil) continue; Bprint(&pop->bout, "LIST %d\r\nRETR %d\r\n", m->mesgno, m->mesgno); } Bflush(&pop->bout); threadexits(nil); /* _exits(nil); jpc */ } } for(m = mb->root->part; m != nil; m = next) { next = m->next; if(m->start != nil) continue; if(s = pop3download(pop, m)) { /* message disappeared? unchain */ fprint(2, "download %d: %s\n", m->mesgno, s); delmessage(mb, m); mb->root->subname--; continue; } nnew++; parse(m, 0, mb, 1); if(doplumb) mailplumb(mb, m, 0); } if(pop->pipeline) waitpid(); if(nnew || mb->vers == 0) { mb->vers++; henter(PATH(0, Qtop), mb->name, (Qid){PATH(mb->id, Qmbox), mb->vers, QTDIR}, nil, mb); } return nil; } /* */ /* delete marked messages */ /* */ static void pop3purge(Pop *pop, Mailbox *mb) { Message *m, *next; if(pop->pipeline){ switch(rfork(RFPROC|RFMEM)){ case -1: fprint(2, "rfork: %r\n"); pop->pipeline = 0; default: break; case 0: for(m = mb->root->part; m != nil; m = next){ next = m->next; if(m->deleted && m->refs == 0){ if(m->inmbox) Bprint(&pop->bout, "DELE %d\r\n", m->mesgno); } } Bflush(&pop->bout); /* _exits(nil); jpc */ threadexits(nil); } } for(m = mb->root->part; m != nil; m = next) { next = m->next; if(m->deleted && m->refs == 0) { if(m->inmbox) { if(!pop->pipeline) pop3cmd(pop, "DELE %d", m->mesgno); if(isokay(pop3resp(pop))) delmessage(mb, m); } else delmessage(mb, m); } } } /* connect to pop3 server, sync mailbox */ static char* pop3sync(Mailbox *mb, int doplumb) { char *err; Pop *pop; pop = mb->aux; if(err = pop3dial(pop)) { mb->waketime = time(0) + pop->refreshtime; return err; } if((err = pop3read(pop, mb, doplumb)) == nil){ pop3purge(pop, mb); mb->d->atime = mb->d->mtime = time(0); } pop3hangup(pop); mb->waketime = time(0) + pop->refreshtime; return err; } static char Epop3ctl[] = "bad pop3 control message"; static char* pop3ctl(Mailbox *mb, int argc, char **argv) { int n; Pop *pop; char *m, *me; pop = mb->aux; if(argc < 1) return Epop3ctl; if(argc==1 && strcmp(argv[0], "debug")==0){ pop->debug = 1; return nil; } if(argc==1 && strcmp(argv[0], "nodebug")==0){ pop->debug = 0; return nil; } if(argc==1 && strcmp(argv[0], "thumbprint")==0){ if(pop->thumb) freeThumbprints(pop->thumb); /* pop->thumb = initThumbprints("/sys/lib/tls/mail", "/sys/lib/tls/mail.exclude"); jpc */ m = unsharp("#9/sys/lib/tls/mail"); me = unsharp("#9/sys/lib/tls/mail.exclude"); pop->thumb = initThumbprints(m, me); } if(strcmp(argv[0], "refresh")==0){ if(argc==1){ pop->refreshtime = 60; return nil; } if(argc==2){ n = atoi(argv[1]); if(n < 15) return Epop3ctl; pop->refreshtime = n; return nil; } } return Epop3ctl; } /* free extra memory associated with mb */ static void pop3close(Mailbox *mb) { Pop *pop; pop = mb->aux; free(pop->freep); free(pop); } /* */ /* open mailboxes of the form /pop/host/user or /apop/host/user */ /* */ char* pop3mbox(Mailbox *mb, char *path) { char *f[10]; int nf, apop, ppop, popssl, apopssl, apoptls, popnotls, apopnotls, poptls; Pop *pop; char *m, *me; quotefmtinstall(); popssl = strncmp(path, "/pops/", 6) == 0; apopssl = strncmp(path, "/apops/", 7) == 0; poptls = strncmp(path, "/poptls/", 8) == 0; popnotls = strncmp(path, "/popnotls/", 10) == 0; ppop = popssl || poptls || popnotls || strncmp(path, "/pop/", 5) == 0; apoptls = strncmp(path, "/apoptls/", 9) == 0; apopnotls = strncmp(path, "/apopnotls/", 11) == 0; apop = apopssl || apoptls || apopnotls || strncmp(path, "/apop/", 6) == 0; if(!ppop && !apop) return Enotme; path = strdup(path); if(path == nil) return "out of memory"; nf = getfields(path, f, nelem(f), 0, "/"); if(nf != 3 && nf != 4) { free(path); return "bad pop3 path syntax /[a]pop[tls|ssl]/system[/user]"; } pop = emalloc(sizeof(*pop)); pop->freep = path; pop->host = f[2]; if(nf < 4) pop->user = nil; else pop->user = f[3]; pop->ppop = ppop; pop->needssl = popssl || apopssl; pop->needtls = poptls || apoptls; pop->refreshtime = 60; pop->notls = popnotls || apopnotls; /* pop->thumb = initThumbprints("/sys/lib/tls/mail", "/sys/lib/tls/mail.exclude"); jpc */ m = unsharp("#9/sys/lib/tls/mail"); me = unsharp("#9/sys/lib/tls/mail.exclude"); pop->thumb = initThumbprints(m, me); mb->aux = pop; mb->sync = pop3sync; mb->close = pop3close; mb->ctl = pop3ctl; mb->d = emalloc(sizeof(*mb->d)); return nil; }
19.335244
115
0.57543
6bab846984a54ff2f3deaa449991f788332ebe09
11,932
h
C
tcl/mk4tcl.h
sbromle/metakit
ab38c5340d8bb6f88fd0339b65cf33a66c4b9400
[ "MIT" ]
15
2018-08-22T10:41:57.000Z
2022-03-18T02:52:16.000Z
tcl/mk4tcl.h
sbromle/metakit
ab38c5340d8bb6f88fd0339b65cf33a66c4b9400
[ "MIT" ]
null
null
null
tcl/mk4tcl.h
sbromle/metakit
ab38c5340d8bb6f88fd0339b65cf33a66c4b9400
[ "MIT" ]
7
2018-09-07T22:02:11.000Z
2021-12-25T08:21:10.000Z
// mk4tcl.h -- // $Id$ // This is part of Metakit, the homepage is http://www.equi4.com/metakit.html #include "mk4.h" #include "mk4str.h" #include "../src/univ.h" #include <tcl.h> #ifdef BUILD_Mk4tcl #undef TCL_STORAGE_CLASS #define TCL_STORAGE_CLASS DLLEXPORT #endif #ifndef d4_assert #if q4_INLINE && !q4_CHECK // if inlining is on, assume it's release code and disable assertions #define d4_assert(x) #elif defined (ASSERT) #define d4_assert(x) ASSERT(x) #else #include <assert.h> #define d4_assert(x) assert(x) #endif #endif #ifndef CONST84 #define CONST84 #endif #ifndef CONST86 #define CONST86 #endif #ifndef TCL_DECLARE_MUTEX #define TCL_DECLARE_MUTEX(v) #define Tcl_MutexLock(v) #define Tcl_MutexUnlock(v) #endif /////////////////////////////////////////////////////////////////////////////// // Defined in this file: class MkPath; class MkWorkspace; class Tcl; class MkTcl; /////////////////////////////////////////////////////////////////////////////// // Utility code: return next token up to char < '0', and // advance the string pointer past following character. c4_String f4_GetToken(const char * &str_); /////////////////////////////////////////////////////////////////////////////// // Utility code: true if value contains a word starting with the given prefix bool MatchOneKeyword(const char *value_, const c4_String &crit_); /////////////////////////////////////////////////////////////////////////////// // Utility class: increments and decrements reference count for auto cleanup class KeepRef { Tcl_Obj *_obj; public: KeepRef(Tcl_Obj *obj_): _obj(obj_) { Tcl_IncrRefCount(_obj); } ~KeepRef() { Tcl_DecrRefCount(_obj); } operator Tcl_Obj *()const { return _obj; } }; /////////////////////////////////////////////////////////////////////////////// // Utility code: get a Metakit item and convert it to a Tcl object Tcl_Obj *GetAsObj(const c4_RowRef &row_, const c4_Property &prop_, Tcl_Obj *obj_ = 0); /////////////////////////////////////////////////////////////////////////////// // Utility code: set a Metakit item and convert it from a Tcl object int SetAsObj(Tcl_Interp *interp, const c4_RowRef &row_, const c4_Property &prop_, Tcl_Obj *obj_); /////////////////////////////////////////////////////////////////////////////// // A path is a view which knows its place, and what workspace it belongs to. // Since it contains a string version, its tag can be used to find the item. class MkPath { int _refs; // reference count public: MkPath(MkWorkspace &ws_, const char * &path_, Tcl_Interp *interp); ~MkPath(); // don't use explicit destruction, use Refs(-1) int AttachView(Tcl_Interp *interp); int Refs(int diff_); MkWorkspace *_ws; // avoid globals, but there is usually just one c4_View _view; // the view corresponding to this path c4_String _path; // describes view, starting with storage tag int _currGen; // tracks the generation to force reloads }; /////////////////////////////////////////////////////////////////////////////// // A workspace manages a number of storage objects and their associated paths. class SiasStrategy; typedef SiasStrategy MkChannel; class MkWorkspace { c4_PtrArray _items; // items, or null if released c4_Bytes _usedBuffer; // buffer, using 1 byte per entry t4_byte *_usedRows; // 1 if that row in item 0 is currently in use c4_PtrArray _commands; public: Tcl_Interp *_interp; MkChannel *_chanList; struct Item { const c4_String _name; // the alias for this storage const c4_String _fileName; c4_Storage _storage; // the storage object c4_PtrArray _paths; // the paths associated with this entry c4_PtrArray &_items; // array from which this item is referenced int _index; // position in the _items array //Item (); // special first entry initializer Item(const char *name_, const char *fileName_, int mode_, c4_PtrArray &items_, int index_, bool share_ = false); ~Item(); void ForceRefresh(); // bump the generation to recreate views static c4_PtrArray *_shared; // shared items are also listed here }; MkWorkspace(Tcl_Interp *ip_); ~MkWorkspace(); void DefCmd(MkTcl *cmd_); // 1.2: for cleanup void CleanupCommands(); Item *Define(const char *name_, const char *fileName_, int mode_, bool share_); Item *Find(const char *name_)const; int NumItems()const; Item *Nth(int index_)const; // create a new path if it doesn't exist, else bump the reference count MkPath *AddPath(const char * &name_, Tcl_Interp *interp); // decrease the reference count, delete path if it is no longer used void ForgetPath(const MkPath *path_); // create a path to a temporary row void AllocTempRow(c4_String &); // adjust paths of all subviews if the parent position has changed void Invalidate(const MkPath &path_); }; /////////////////////////////////////////////////////////////////////////////// // // Interface to Tcl 8.0 type mechanism, defines a new "mkProperty" datatype // // Since properties are immutable, we don't need most of the calls. /////////////////////////////////////////////////////////////////////////////// const c4_Property &AsProperty(Tcl_Obj *objPtr, const c4_View &view_); /////////////////////////////////////////////////////////////////////////////// // // Interface to Tcl 8.0 type mechanism, defines a new "mkCursor" datatype // /////////////////////////////////////////////////////////////////////////////// // // Cursors in Tcl are implemented as a pointer to an MkPath plus an index. MkPath &AsPath(Tcl_Obj *obj_); int &AsIndex(Tcl_Obj *obj_); int SetCursorFromAny(Tcl_Interp *interp, Tcl_Obj *objPtr); // 24nov02: added to support releasing mutex lock during loop eval's int Mk_EvalObj(Tcl_Interp *ip_, Tcl_Obj *cmd_); /////////////////////////////////////////////////////////////////////////////// // Helper class for the mk::select command, stores params and performs select class TclSelector { c4_PtrArray _conditions; Tcl_Interp *_interp; c4_View _view; Tcl_Obj *_temp; public: class Condition { public: int _id; c4_View _view; Tcl_Obj *_crit; // no need to incref, original lifetime is guaranteed Condition(int id_, const c4_View &view_, Tcl_Obj *crit_): _id(id_), _view(view_), _crit(crit_){} }; c4_View _sortProps; c4_View _sortRevProps; int _first; int _count; TclSelector(Tcl_Interp *interp_, const c4_View &view_); ~TclSelector(); c4_View GetAsProps(Tcl_Obj *obj_); int AddCondition(int id_, Tcl_Obj *props_, Tcl_Obj *value_); bool MatchOneString(int id_, const char *value_, const char *crit_); bool Match(const c4_RowRef &row_); void ExactKeyProps(const c4_RowRef &row_); int DoSelect(Tcl_Obj *list_, c4_View *result_ = 0); }; /////////////////////////////////////////////////////////////////////////////// // The Tcl class is a generic interface to Tcl, providing some C++ wrapping class Tcl { protected: Tcl_Interp *interp; int _error; public: Tcl(Tcl_Interp *ip_); int Fail(const char *msg_ = 0, int err_ = TCL_ERROR); Tcl_Obj *tcl_GetObjResult(); int tcl_SetObjResult(Tcl_Obj *obj_); int tcl_ListObjLength(Tcl_Obj *obj_); void tcl_ListObjAppendElement(Tcl_Obj *obj_, Tcl_Obj *value_); bool tcl_GetBooleanFromObj(Tcl_Obj *obj_); int tcl_GetIntFromObj(Tcl_Obj *obj_); long tcl_GetLongFromObj(Tcl_Obj *obj_); double tcl_GetDoubleFromObj(Tcl_Obj *obj_); int tcl_GetIndexFromObj(Tcl_Obj *obj_, const char **table_, const char *msg_ = "option"); long tcl_ExprLongObj(Tcl_Obj *obj_); Tcl_Obj *GetValue(const c4_RowRef &row_, const c4_Property &prop_, Tcl_Obj *obj_ = 0); Tcl_Obj *tcl_NewStringObj(const char *str_, int len_ = - 1); void list2desc(Tcl_Obj *in, Tcl_Obj *out); }; // The MkTcl class adds Metakit-specific utilities and all the command procs. class MkTcl: public Tcl { int id; int objc; Tcl_Obj *const * objv; c4_String msg; MkWorkspace &work; static int Dispatcher(ClientData cd, Tcl_Interp *ip, int oc, Tcl_Obj *const * ov); public: enum { kAnyRow, kExistingRow, kLimitRow, kExtendRow }; MkTcl(MkWorkspace *ws_, Tcl_Interp *ip_, int id_, const char *cmd_); ~MkTcl(); c4_View asView(Tcl_Obj *obj_); int &changeIndex(Tcl_Obj *obj_); c4_RowRef asRowRef(Tcl_Obj *obj_, int type_ = kExistingRow); int GetCmd(); int SetValues(const c4_RowRef &row_, int objc, Tcl_Obj *const * objv); int SetCmd(); int RowCmd(); int FileCmd(); int ViewCmd(); int LoopCmd(); int CursorCmd(); int SelectCmd(); int ChannelCmd(); int NewCmd(); int Try1Cmd(); int Try2Cmd(); int Try3Cmd(); #if MKSQL int SqlAuxCmd(); #endif int Execute(int oc, Tcl_Obj *const * ov); }; /////////////////////////////////////////////////////////////////////////////// class MkView: public Tcl { int objc; Tcl_Obj *const * objv; Tcl_Command cmdToken; c4_String msg; MkWorkspace &work; c4_View view; c4_String cmd; static int Dispatcher(ClientData cd, Tcl_Interp *ip, int oc, Tcl_Obj *const * ov); static void DeleteProc(ClientData cd); public: MkView(Tcl_Interp *ip_, c4_View view_, const char *name = 0); MkView(Tcl_Interp *ip_, const char *name = 0); ~MkView(); void Register(const char *name); static c4_View View(Tcl_Interp *interp, Tcl_Obj *obj); c4_String CmdName() { return cmd; } int asIndex(c4_View &view, Tcl_Obj *obj_, bool mayExceed_); int SetValues(const c4_RowRef &row_, int objc, Tcl_Obj *const * objv, c4_View &); c4_View &View() { return view; } int CloseCmd(); // $obj close int DeleteCmd(); // $obj delete cursor ?count? int FindCmd(); // $obj find ?prop value ...? int GetCmd(); // $obj get cursor ?prop prop ...? int ExistsCmd(); // $obj exists cursor int InfoCmd(); // $obj info int InsertCmd(); // $obj insert cursor ?prop prop ...? int OpenCmd(); // $obj open cursor prop int SearchCmd(); // $obj search prop value int SelectCmd(); // $obj select .... int SetCmd(); // $obj set cursor ?prop value ...? int SizeCmd(); // $obj size ?newsize? int LoopCmd(); // $obj loop cursor ?first? ?limit? ?step? {cmds} int ViewCmd(); // $obj view option ?args? int CloneCmd(); // $obj view clone int ConcatCmd(); // $obj view concat view int CopyCmd(); // $obj view copy int DifferentCmd(); // $obj view different view int DupCmd(); // $obj view dup int BlockedCmd(); // $obj view blocked int FlattenCmd(); // $obj view flatten prop int GroupByCmd(); // $obj view groupby subview prop ?prop ...? int HashCmd(); // $obj view hash view ?numkeys? int IndexedCmd(); // $obj view indexed map unique prop ?prop ...? int IntersectCmd(); // $obj view intersect view int JoinCmd(); // $obj view join view prop ?prop ...? int MapCmd(); // $obj view map view int MinusCmd(); // $obj view minus view int OrderedCmd(); // $obj view ordered ?numKeys? int PairCmd(); // $obj view pair view int ProductCmd(); // $obj view product view int ProjectCmd(); // $obj view project prop ?prop ...? int RangeCmd(); // $obj view range start ?limit? ?step? int ReadOnlyCmd(); // $obj view readonly int RenameCmd(); // $obj view rename oprop nprop int RestrictCmd(); // $obj view restrict cursor pos count int UnionCmd(); // $obj view union view int UniqueCmd(); // $obj view unique int Execute(int oc, Tcl_Obj *const * ov); }; ///////////////////////////////////////////////////////////////////////////////
31.154047
79
0.598056
754803eaf68acefcd62b154dc72832b2024a5c26
1,773
h
C
sqlexec/sqlexec/cursor.h
vocky/NDSPoi
7f1ea50d6fe8e8d4874cfa080881fd6bdb66fa9e
[ "Apache-2.0" ]
null
null
null
sqlexec/sqlexec/cursor.h
vocky/NDSPoi
7f1ea50d6fe8e8d4874cfa080881fd6bdb66fa9e
[ "Apache-2.0" ]
null
null
null
sqlexec/sqlexec/cursor.h
vocky/NDSPoi
7f1ea50d6fe8e8d4874cfa080881fd6bdb66fa9e
[ "Apache-2.0" ]
null
null
null
#ifndef CURSOR_H #define CURSOR_H #include <stdint.h> #include "sqlite3.h" #include <string.h> namespace search { class Cursor { public: Cursor() { stmt_ = NULL; } ~Cursor() { if (stmt_) sqlite3_finalize(stmt_);; } public: void set_stmt(sqlite3_stmt* stmt) { stmt_ = stmt; } sqlite3_stmt* get_stmt() {return stmt_;} /** * @brief Get Colun index by colun nae * return colun index **/ int GetColunIndex(const char* name)const { int count = sqlite3_column_count(stmt_); for (int i = 0; i < count; ++i){ if (strcmp(name, sqlite3_column_name(stmt_, i)) == 0){ return i; } } return -1; } /** * @brief get value by colun index in current colun data set **/ int GetInt(int colun_index)const{ return sqlite3_column_int(stmt_, colun_index); } int64_t GetInt64(int colun_index) const{ return sqlite3_column_int64(stmt_, colun_index); } /** * @brief get blob by colun index at current row * size: set size **/ const void* GetBlob(int colun_index,unsigned int *size)const { *size = sqlite3_column_bytes(stmt_, colun_index); return sqlite3_column_blob(stmt_,colun_index); } /** * @brief get blob by colun index at current row * size: set size **/ const char* GetText(int colun_index)const { //*size = sqlite3_column_bytes(stmt_, colun_index); return (const char*)sqlite3_column_text(stmt_, colun_index); } /** * @brief get count of colun **/ int GetColunCount() const { return sqlite3_column_count(stmt_); } bool MoveToNext(){ int code = sqlite3_step(stmt_); if (code == SQLITE_ROW){ return true; } else{ return false; } } void Finalize() { if (stmt_) sqlite3_finalize(stmt_); stmt_ = NULL; } private: sqlite3_stmt* stmt_; }; } //namespace search #endif
18.46875
63
0.670051
df38bbae3113a1948e0bbc765667080a7b5daadd
1,693
c
C
lib/distract/src/game/game.c
norech/myrpg
b2cf714c1089283df65d6c74b7ba892a43d3d553
[ "Apache-2.0" ]
4
2021-05-12T07:04:25.000Z
2021-05-12T18:23:21.000Z
lib/distract/src/game/game.c
norech/myrpg
b2cf714c1089283df65d6c74b7ba892a43d3d553
[ "Apache-2.0" ]
28
2021-03-22T06:18:38.000Z
2021-03-23T14:29:53.000Z
lib/distract/src/game/game.c
norech/myrpg
b2cf714c1089283df65d6c74b7ba892a43d3d553
[ "Apache-2.0" ]
1
2021-05-13T05:39:27.000Z
2021-05-13T05:39:27.000Z
/* ** EPITECH PROJECT, 2020 ** game ** File description: ** Source code */ #include "distract/game.h" #include "distract/entity.h" #include "distract/hashmap.h" #include "distract/sound.h" #include "stdlib.h" #include "distract/debug.h" #include "distract/util.h" #include <SFML/Graphics/RenderWindow.h> #include <SFML/Graphics/View.h> game_t *create_game(void) { game_t *game = dcalloc(1, sizeof(game_t)); game->sound = create_sound_emitter(game); game->scene = allocate_scene(); if (game == NULL || game->sound == NULL || game->scene == NULL) { print_error("Game initialisation failed"); return (NULL); } return (game); } void set_game_view(game_t *game, sfView *view) { game->view = view; sfRenderWindow_setView(game->window, view); } static void destroy_entity_infos(game_t *game) { entity_info_t *entity_info = game->entities; entity_info_t *next = NULL; while (entity_info != NULL) { next = entity_info->next; free(entity_info); entity_info = next; } game->entities = NULL; } static void destroy_scene_infos(game_t *game) { scene_info_t *scene_info = game->scenes; scene_info_t *next = NULL; while (scene_info != NULL) { next = scene_info->next; free(scene_info); scene_info = next; } game->scenes = NULL; } void destroy_game(game_t *game) { if (game == NULL) return; if (game->window != NULL) sfRenderWindow_destroy(game->window); destroy_scene(game, true); deallocate_scene(game->scene); destroy_sound_emitter(game->sound); destroy_entity_infos(game); destroy_scene_infos(game); free(game); }
22.573333
69
0.649734
d9c48da6a2848eb0b7fbb9d3ef75196748223f52
6,033
h
C
DataStructures/searchTree/avlTree.h
lambdaxing/dsaa_cpp2
5b19eaf34df4529ff4e5ab60be644e1799f4b767
[ "CC0-1.0" ]
null
null
null
DataStructures/searchTree/avlTree.h
lambdaxing/dsaa_cpp2
5b19eaf34df4529ff4e5ab60be644e1799f4b767
[ "CC0-1.0" ]
null
null
null
DataStructures/searchTree/avlTree.h
lambdaxing/dsaa_cpp2
5b19eaf34df4529ff4e5ab60be644e1799f4b767
[ "CC0-1.0" ]
null
null
null
// #ifndef AVL_TREE_ #define AVL_TREE_ #include "linkedBinaryTree.h" #include "bsTree.h" template<typename K,typename E> class avlTree :public bsTree<K, E>, public linkedBinaryTree<std::pair<const K, E>> { public: typedef binaryTreeNode<std::pair<const K, E> >* position; // methods of dictionary bool empty() const { return this->treeSize == 0; } int size() const { return this->treeSize; } std::pair<const K, E>* find(const K& theKey) const; void insert(const std::pair<const K, E>& thePair) { this->root = insert(thePair, this->root); } void erase(const K& theKey) { this->root = erase(theKey, this->root); } // additional method of bsTree void ascend() { this->inOrderOutput(); } private: position insert(const std::pair<const K, E>& thePair, position t); position erase(const K& theKey, position t); position singleRotateWithLeft(position K2) // LL { position K1; K1 = K2->leftChild; K2->leftChild = K1->rightChild; K1->rightChild = K2; return K1; } position singleRotateWithRight(position K1) // RR { position K2; K2 = K1->rightChild; K1->rightChild = K2->leftChild; K2->leftChild = K1; return K2; } position doubleRotateWithLeft(position K3) // LR { // K1 is the leftChild of K3 // K2 is the rightChild of K1 // K1 and K2 perform right rotation K3->leftChild = singleRotateWithRight(K3->leftChild); // now, the leftChild of K3 is K2 // K3 and K2 perform left rotation return singleRotateWithLeft(K3); } position doubleRotateWithRight(position K1) // RL { // K3 is the rightChild of K1 // K2 is the leftChild of K3 // K3 and K2 perform left rotation K1->rightChild = singleRotateWithLeft(K1->rightChild); // now, the rightChild of K1 is K2 // K1 and K2 perform right rotation return singleRotateWithRight(K1); } }; template<typename K, typename E> std::pair<const K, E>* avlTree<K, E>::find(const K& theKey) const {// Return pointer to matching pair. // Return null if no matching pair. // p starts at the root and moves through the tree looking for an element with key theKey binaryTreeNode<std::pair<const K, E>>* p = this->root; while (p != nullptr) // examine p->element if (theKey < p->element.first) p = p->leftChild; else if (theKey > p->element.first) p = p->rightChild; else // found matching pair return &p->element; // no matching pair return nullptr; } template<typename K,typename E> auto avlTree<K, E>::insert(const std::pair<const K, E>& thePair, position t) -> position {// Insert the new element recursively into the AVL if (t == nullptr) {// find the position of insert, and create memory to storage the element t = new binaryTreeNode<std::pair<const K, E>>(thePair); ++this->treeSize; } else { if (thePair.first < t->element.first) {// insert the element into the left avl of t t->leftChild = insert(thePair, t->leftChild); if (this->height(t->leftChild) - this->height(t->rightChild) == 2) if (thePair.first < t->leftChild->element.first) // inserted to the LL of t t = singleRotateWithLeft(t); else // insert to the LR of t t = doubleRotateWithLeft(t); } else if (thePair.first > t->element.first) {// insert the element into the right avl of t t->rightChild = insert(thePair, t->rightChild); if (this->height(t->rightChild) - this->height(t->leftChild) == 2) if (thePair.first > t->rightChild->element.first) // inserted to the RR of t t = singleRotateWithRight(t); else t = doubleRotateWithRight(t); } else // else the pair is in the tree already; we'll cover old value { t->element.second = thePair.second; } } return t; } template<typename K, typename E> auto avlTree<K, E>::erase(const K& theKey, position t) -> position {// Deletes the specified element recursively if (t == nullptr) // not found the key theKey return t; if (theKey < t->element.first) {// deletes the specified element in the left avl t->leftChild = erase(theKey, t->leftChild); // delete theKey in the left part of t if (this->height(t->rightChild) - this->height(t->leftChild) == 2) // If there's an imbalance here if (this->height(t->rightChild->leftChild) < this->height(t->rightChild->rightChild)) // RR t = singleRotateWithRight(t); else // RL t = doubleRotateWithRight(t); } else if (theKey > t->element.first) {// deletes the specified element in the right avl t->rightChild = erase(theKey, t->rightChild); // delete theKey in the right part of t if (this->height(t->leftChild) - this->height(t->rightChild) == 2) if (this->height(t->leftChild->rightChild) < this->height(t->leftChild->leftChild)) // LL t = singleRotateWithLeft(t); else // LR t = doubleRotateWithLeft(t); } else {// now, theKye == t->element.first, so delete t // t has two children if (t->leftChild != nullptr && t->rightChild != nullptr) { // find the largest in the t->leftChid position s = t->leftChild, ps = t; // parent of s while (s->rightChild != nullptr) {// move to larger element ps = s; s = s->rightChild; } position q = new binaryTreeNode<std::pair<const K, E>>(s->element, t->leftChild, t->rightChild); // Replace t(will be delete) with the largest element in the t->leftChild delete t; // delete old t t = q; t->leftChild = erase(s->element.first, t->leftChild); // delete the largest element in the t->leftChild } else {// The recursion terminates // t has at most one child position c; if (t->leftChild != nullptr) c = t->leftChild; else c = t->rightChild; delete t; t = c; --this->treeSize; } } return t; } // overload << for pair template<typename K, typename E> std::ostream& operator<<(std::ostream& out, const std::pair<K, E>& x) { out << x.first << ' ' << x.second; return out; } #endif // !AVL_TREE_
31.752632
175
0.644455
cd802e55d71b10424bd0775c1164413847bd6921
1,883
h
C
System/Library/PrivateFrameworks/BookCoverUtility.framework/BCUPurgeableImage.h
lechium/iOS1351Headers
6bed3dada5ffc20366b27f7f2300a24a48a6284e
[ "MIT" ]
2
2021-11-02T09:23:27.000Z
2022-03-28T08:21:57.000Z
System/Library/PrivateFrameworks/BookCoverUtility.framework/BCUPurgeableImage.h
lechium/iOS1351Headers
6bed3dada5ffc20366b27f7f2300a24a48a6284e
[ "MIT" ]
null
null
null
System/Library/PrivateFrameworks/BookCoverUtility.framework/BCUPurgeableImage.h
lechium/iOS1351Headers
6bed3dada5ffc20366b27f7f2300a24a48a6284e
[ "MIT" ]
1
2022-03-28T08:21:59.000Z
2022-03-28T08:21:59.000Z
/* * This header is generated by classdump-dyld 1.5 * on Wednesday, October 27, 2021 at 3:18:37 PM Mountain Standard Time * Operating System: Version 13.5.1 (Build 17F80) * Image Source: /System/Library/PrivateFrameworks/BookCoverUtility.framework/BookCoverUtility * classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos. Updated by Kevin Bradley. */ #import <BookCoverUtility/BookCoverUtility-Structs.h> #import <libobjc.A.dylib/BCUPurgeableImage.h> @protocol BCUPurgeableImage <NSObject> @property (nonatomic,readonly) double contentsScale; @property (nonatomic,readonly) CGImageRef CGImage; @property (nonatomic,readonly) CGSize size; @property (nonatomic,readonly) id layerContents; @required -(CGSize)size; -(CGImageRef)CGImage; -(double)contentsScale; -(id)layerContents; -(BOOL)markAsVolatile; -(BOOL)markAsNonVolatile; @end @class NSString; @interface BCUPurgeableImage : NSObject <BCUPurgeableImage> { CGImageRef _image; IOSurfaceRef _surface; double _contentsScale; } @property (readonly) unsigned long long hash; @property (readonly) Class superclass; @property (copy,readonly) NSString * description; @property (copy,readonly) NSString * debugDescription; @property (nonatomic,readonly) double contentsScale; //@synthesize contentsScale=_contentsScale - In the implementation block @property (nonatomic,readonly) CGImageRef CGImage; @property (nonatomic,readonly) CGSize size; @property (nonatomic,readonly) id layerContents; -(void)dealloc; -(CGSize)size; -(CGImageRef)CGImage; -(double)contentsScale; -(id)layerContents; -(id)initWithImage:(CGImageRef)arg1 surface:(IOSurfaceRef)arg2 contentsScale:(double)arg3 ; -(BOOL)markAsVolatile; -(BOOL)markAsNonVolatile; @end
33.625
140
0.723845
a317328d06a1bc267a79d9dce2deec4f37aa410a
463
c
C
Chapter7/chap7_12.c
Capella87/CPractice
1ce8c3b1a0ce2477df7a776db3ed0fb9bf6a1e34
[ "Unlicense" ]
2
2020-05-14T17:15:27.000Z
2020-11-11T15:50:26.000Z
Chapter7/chap7_12.c
Capella87/CPractice
1ce8c3b1a0ce2477df7a776db3ed0fb9bf6a1e34
[ "Unlicense" ]
null
null
null
Chapter7/chap7_12.c
Capella87/CPractice
1ce8c3b1a0ce2477df7a776db3ed0fb9bf6a1e34
[ "Unlicense" ]
null
null
null
#include <stdio.h> #define NUMBER 6 #define SPELLING 5 int main(void) { char x[NUMBER][SPELLING] = { 'Z', 'E', 'R', 'O', '-', 'O', 'N', 'E', '-', '-', 'T', 'W', 'O', '-', '-', 'T', 'H', 'R', 'E', 'E', 'F', 'O', 'U', 'R', '-', 'F', 'I', 'V', 'E', '-' }; int i, temp; for (i = 0; i < 3; i++) { scanf("%d", &temp); for (int j = 0; j < SPELLING; j++) printf("%c", x[temp][j]); putchar('\n'); } return 0; }
25.722222
184
0.358531
33c4907cc961e3cb661f7406bec6791092350a00
1,931
h
C
System/Library/PrivateFrameworks/StoreKitUI.framework/SKUIMediaPageSection.h
zhangkn/iOS14Header
4323e9459ed6f6f5504ecbea2710bfd6c3d7c946
[ "MIT" ]
1
2020-11-04T15:43:01.000Z
2020-11-04T15:43:01.000Z
System/Library/PrivateFrameworks/StoreKitUI.framework/SKUIMediaPageSection.h
zhangkn/iOS14Header
4323e9459ed6f6f5504ecbea2710bfd6c3d7c946
[ "MIT" ]
null
null
null
System/Library/PrivateFrameworks/StoreKitUI.framework/SKUIMediaPageSection.h
zhangkn/iOS14Header
4323e9459ed6f6f5504ecbea2710bfd6c3d7c946
[ "MIT" ]
null
null
null
/* * This header is generated by classdump-dyld 1.0 * on Sunday, September 27, 2020 at 11:44:33 AM Mountain Standard Time * Operating System: Version 14.0 (Build 18A373) * Image Source: /System/Library/PrivateFrameworks/StoreKitUI.framework/StoreKitUI * classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos. */ #import <StoreKitUI/StoreKitUI-Structs.h> #import <StoreKitUI/SKUIStorePageSection.h> #import <libobjc.A.dylib/SKUIArtworkRequestDelegate.h> #import <libobjc.A.dylib/SKUIEmbeddedMediaViewDelegate.h> @class SKUIArtwork, SKUIEmbeddedMediaView, SKUIMediaComponent, NSString; @interface SKUIMediaPageSection : SKUIStorePageSection <SKUIArtworkRequestDelegate, SKUIEmbeddedMediaViewDelegate> { SKUIArtwork* _artwork; unsigned long long _artworkRequestID; CGSize _imageSize; SKUIEmbeddedMediaView* _mediaView; } @property (nonatomic,readonly) SKUIMediaComponent * pageComponent; @property (readonly) unsigned long long hash; @property (readonly) Class superclass; @property (copy,readonly) NSString * description; @property (copy,readonly) NSString * debugDescription; -(void)dealloc; -(void)setSectionIndex:(long long)arg1 ; -(long long)numberOfCells; -(void)artworkRequest:(id)arg1 didLoadImage:(id)arg2 ; -(id)initWithPageComponent:(id)arg1 ; -(void)willAppearInContext:(id)arg1 ; -(id)cellForIndexPath:(id)arg1 ; -(CGSize)cellSizeForIndexPath:(id)arg1 ; -(void)prefetchResourcesWithReason:(long long)arg1 ; -(void)addImpressionsForIndexPath:(id)arg1 toSession:(id)arg2 ; -(void)collectionViewWillDisplayCellForItemAtIndexPath:(id)arg1 ; -(void)collectionViewDidEndDisplayingCellForItemAtIndexPath:(id)arg1 ; -(void)collectionViewDidSelectItemAtIndexPath:(id)arg1 ; -(double)contentInsetAdjustmentForCollectionView:(id)arg1 ; -(long long)defaultItemPinningStyle; -(void)_loadImageWithReason:(long long)arg1 ; -(void)mediaView:(id)arg1 playbackStateDidChange:(long long)arg2 ; @end
39.408163
116
0.804247
8fed3d4c4200a0f1bb204ce3f1751d79a23e79d7
564
h
C
g2opy/python/types/sclam2d/edge_se2_odom_differential_calib.h
alecone/ROS_project
f058fb0bc5c4c9b1a590b7536f75b83af35b7785
[ "MIT" ]
5
2022-03-28T04:41:35.000Z
2022-03-30T12:34:41.000Z
thirdparty/g2opy/python/types/sclam2d/edge_se2_odom_differential_calib.h
rpng/suo_slam
5de01433d177fde5cac4423f05fd554e3c00794e
[ "MIT" ]
null
null
null
thirdparty/g2opy/python/types/sclam2d/edge_se2_odom_differential_calib.h
rpng/suo_slam
5de01433d177fde5cac4423f05fd554e3c00794e
[ "MIT" ]
null
null
null
#include <pybind11/pybind11.h> #include <g2o/types/sclam2d/edge_se2_odom_differential_calib.h> namespace py = pybind11; using namespace pybind11::literals; namespace g2o { void declareEdgeSE2OdomDifferentialCalib(py::module& m) { py::class_<EdgeSE2OdomDifferentialCalib, BaseMultiEdge<3, VelocityMeasurement>>(m, "EdgeSE2OdomDifferentialCalib") .def(py::init<>()) .def("compute_error", &EdgeSE2OdomDifferentialCalib::computeError) ; // class G2O_TYPES_SCLAM2D_API EdgeSE2OdomDifferentialCalibDrawAction: public DrawAction } }
23.5
118
0.764184
7221e507f43d6b79a28d898ffb76e890760689c7
214
h
C
OSChina/VoiceTweetEditingVC.h
yonfong/OSChina
171f62955a7e4324a19f7541f00b8a5b776b304d
[ "MIT" ]
null
null
null
OSChina/VoiceTweetEditingVC.h
yonfong/OSChina
171f62955a7e4324a19f7541f00b8a5b776b304d
[ "MIT" ]
null
null
null
OSChina/VoiceTweetEditingVC.h
yonfong/OSChina
171f62955a7e4324a19f7541f00b8a5b776b304d
[ "MIT" ]
null
null
null
// // VoiceTweetEditingVC.h // OSChina // // Created by sky on 15/7/26. // Copyright (c) 2015年 bluesky. All rights reserved. // #import <UIKit/UIKit.h> @interface VoiceTweetEditingVC : UIViewController @end
15.285714
53
0.696262
815bc3b6991f1b532af06e3e49aa449de2a5b7e7
2,416
h
C
rpims_v2/IOBoard.h
AlabasterAxe/RPIMobileStudioDesktop
7168c0c5e3bc5bf67226fc9ef4e159d2ea47ac75
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
rpims_v2/IOBoard.h
AlabasterAxe/RPIMobileStudioDesktop
7168c0c5e3bc5bf67226fc9ef4e159d2ea47ac75
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
rpims_v2/IOBoard.h
AlabasterAxe/RPIMobileStudioDesktop
7168c0c5e3bc5bf67226fc9ef4e159d2ea47ac75
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
/******************************************************************* * Copyright (C) 2011 Rensselaer Polytechnic Institute * * This work is licensed under the FreeBSD License. * * Please see the included LICENSE file in the top level directory. * *******************************************************************/ #ifndef _IOBOARD_H #define _IOBOARD_H #include <stdint.h> #define RPIMS_VENDOR_ID 0x181c typedef int32_t StreamSample; struct IOBoard; struct IOBoardOps { int (*Init)(struct IOBoard *iob); int (*Cleanup)(struct IOBoard *iob); int (*Open)(struct IOBoard *iob); int (*Close)(struct IOBoard *iob); }; struct IOBoardUSBOps { int (*Open)(struct IOBoard *iob); int (*Close)(struct IOBoard *iob); int (*ControlMsg)(struct IOBoard *iob, int type, int req, int index, int value, char *data, int size, int timeout); int (*BulkRead)(struct IOBoard *iob, int endpoint, char *data, int len, int timeout); int (*BulkWrite)(struct IOBoard *iob, int endpoint, char *data, int len, int timeout); int (*InterruptRead)(struct IOBoard *iob, int endpoint, char *data, int len, int timeout); int (*InterruptWrite)(struct IOBoard *iob, int endpoint, char *data, int len, int timeout); int (*Reset)(struct IOBoard *iob); int (*GetProductId)(struct IOBoard *iob); }; struct Features; struct IOBoard { struct IOBoardUSBOps *usbops; void *usbpriv; struct IOBoardOps *ops; struct Features *feat; void *priv; }; struct IOBoard *IOBoard_Probe(int type); int IOBoard_Open(struct IOBoard *iob); int IOBoard_Close(struct IOBoard *iob); int IOBoard_Cleanup(struct IOBoard *iob); int IOBoard_USBOpen(struct IOBoard *iob); int IOBoard_USBClose(struct IOBoard *iob); int IOBoard_USBControlMsg(struct IOBoard *iob, int type, int req, int index, int value, char *data, int size, int timeout); int IOBoard_USBBulkRead(struct IOBoard *iob, int endpoint, char *data, int len, int timeout); int IOBoard_USBBulkWrite(struct IOBoard *iob, int endpoint, char *data, int len, int timeout); int IOBoard_USBInterruptRead(struct IOBoard *iob, int endpoint, char *data, int len, int timeout); int IOBoard_USBInterruptWrite(struct IOBoard *iob, int endpoint, char *data, int len, int timeout); int IOBoard_USBReset(struct IOBoard *iob); int IOBoard_USBGetProductId(struct IOBoard *iob); #endif /* _IOBOARD_H */
34.028169
99
0.671358
54c73b049ecce6f8bdbc3aef89e293a3e9f81ca7
1,090
h
C
include/ed25519_bip32_c_interface.h
gradido/ed25519_bip32_c_interface
9e7fb4d336a75b7c734ec398ee451b679b32bea9
[ "MIT" ]
null
null
null
include/ed25519_bip32_c_interface.h
gradido/ed25519_bip32_c_interface
9e7fb4d336a75b7c734ec398ee451b679b32bea9
[ "MIT" ]
null
null
null
include/ed25519_bip32_c_interface.h
gradido/ed25519_bip32_c_interface
9e7fb4d336a75b7c734ec398ee451b679b32bea9
[ "MIT" ]
null
null
null
#ifndef GRADIDO_ED25519_BIP32_RUST_H #define GRADIDO_ED25519_BIP32_RUST_H extern "C" { extern void getPublicFromPrivateKey(const uint8_t* privateKey, const uint8_t* chainCode, uint8_t* publicKey); extern void getPrivateExtended( const uint8_t* privateKey, const uint8_t* chainCode, uint8_t* privKeyExtended, uint8_t* publicKey ); extern bool is_3rd_highest_bit_clear(const uint8_t* privateKey, const uint8_t* chainCode); extern bool derivePublicKey( const uint8_t* publicKey, const uint8_t* chainCode, uint32_t index, uint8_t* derivedPublicKey, uint8_t* derivedChainCode ); extern void derivePrivateKey( const uint8_t* privateKey, const uint8_t* chainCode, uint32_t index, uint8_t* derivedPrivateKey, uint8_t* derivedChainCode ); extern void sign_extended( const uint8_t* message, size_t messageSize, const uint8_t* secretKeyExtended, uint8_t* sign ); } #endif //GRADIDO_ED25519_BIP32_RUST_H
25.952381
113
0.678899
e673e551b895520195dbf5e88c8cd69e1a5a75da
57
h
C
cli/include/main.h
skrekhere/RealityEmu
cf79d8b77541298154287d753a6a3e3e7bdbd715
[ "Unlicense" ]
24
2019-06-26T22:45:49.000Z
2022-02-25T22:48:47.000Z
cli/include/main.h
skrekhere/RealityEmu
cf79d8b77541298154287d753a6a3e3e7bdbd715
[ "Unlicense" ]
3
2019-06-29T05:16:17.000Z
2019-07-08T19:56:10.000Z
cli/include/main.h
skrekhere/RealityEmu
cf79d8b77541298154287d753a6a3e3e7bdbd715
[ "Unlicense" ]
2
2021-12-12T18:57:30.000Z
2021-12-12T19:05:55.000Z
#pragma once double RSP_mhz; double CPU_mhz; double VIs;
11.4
15
0.789474
c25d5d934bd9d81d4d29ee52a75d5ce930c7bb44
2,297
h
C
gtsam/nonlinear/summarization.h
malcolmreynolds/GTSAM
e911b4d39f8a8c8604663bd46f10e7f53c860ae8
[ "BSD-3-Clause" ]
1
2017-07-23T19:34:50.000Z
2017-07-23T19:34:50.000Z
gtsam/nonlinear/summarization.h
malcolmreynolds/GTSAM
e911b4d39f8a8c8604663bd46f10e7f53c860ae8
[ "BSD-3-Clause" ]
null
null
null
gtsam/nonlinear/summarization.h
malcolmreynolds/GTSAM
e911b4d39f8a8c8604663bd46f10e7f53c860ae8
[ "BSD-3-Clause" ]
null
null
null
/** * @file summarization.h * * @brief Types and utility functions for summarization * * @date Jun 22, 2012 * @author Alex Cunningham */ #pragma once #include <gtsam/dllexport.h> #include <gtsam/nonlinear/NonlinearFactorGraph.h> #include <gtsam/linear/GaussianFactorGraph.h> #include <gtsam/nonlinear/Ordering.h> namespace gtsam { // Flag to control how summarization should be performed typedef enum { PARTIAL_QR = 0, /// Uses QR solver to eliminate, does not require fully constrained system PARTIAL_CHOLESKY = 1, /// Uses Cholesky solver, does not require fully constrained system SEQUENTIAL_QR = 2, /// Uses QR to compute full joint graph (needs fully constrained system) SEQUENTIAL_CHOLESKY = 3 /// Uses Cholesky to compute full joint graph (needs fully constrained system) } SummarizationMode; /** * Summarization function to remove a subset of variables from a system with the * sequential solver. This does not require that the system be fully constrained. * * Requirement: set of keys in the graph should match the set of keys in the * values structure. * * @param graph A full nonlinear graph * @param values The chosen linearization point * @param saved_keys is the set of keys for variables that should remain * @param mode controls what elimination technique and requirements to use * @return a pair of the remaining graph and the ordering used for linearization */ std::pair<GaussianFactorGraph,Ordering> GTSAM_EXPORT summarize(const NonlinearFactorGraph& graph, const Values& values, const KeySet& saved_keys, SummarizationMode mode = PARTIAL_QR); /** * Performs the same summarization technique used in summarize(), but returns the * result as a NonlinearFactorGraph comprised of LinearContainerFactors. * * @param graph A full nonlinear graph * @param values The chosen linearization point * @param saved_keys is the set of keys for variables that should remain * @param useQR uses QR as the elimination algorithm if true, Cholesky otherwise * @return a NonlinearFactorGraph with linear factors */ NonlinearFactorGraph GTSAM_EXPORT summarizeAsNonlinearContainer( const NonlinearFactorGraph& graph, const Values& values, const KeySet& saved_keys, SummarizationMode mode = PARTIAL_QR); } // \namespace gtsam
37.048387
104
0.765346
ddcf1951e18326b4c11b30256ca2d78e5e002607
312
h
C
proj1/proj1/builder.h
chensibaba/CG_proj1
4fb65f87ab873babc41c7817d45925aa3e59f094
[ "MIT" ]
2
2019-04-12T14:44:00.000Z
2021-12-12T18:29:14.000Z
proj1/proj1/builder.h
chensibaba/CG_proj1
4fb65f87ab873babc41c7817d45925aa3e59f094
[ "MIT" ]
null
null
null
proj1/proj1/builder.h
chensibaba/CG_proj1
4fb65f87ab873babc41c7817d45925aa3e59f094
[ "MIT" ]
null
null
null
#ifndef BUILDER_H #define BUILDER_H #include "camera.h" #include "scene.h" class Builder { Scene* scene; Camera* camera; public: Builder(){} void buildCamera(Vector3 eye, Vector3 origin, Vector3 dx, Vector3 dy); void buildScene(Object** objs, int num); cv::Mat rayTracer_begin(); }; #endif
19.5
72
0.689103
25ec3f7b29ae2daee6fe3208c5749a4e4d273336
51,919
c
C
eos_with_critical_point/src/EOS.c
MonitSharma/MS_Thesis
9af18f8b25da90ead96a680486caa6dc56e1347a
[ "Apache-2.0" ]
null
null
null
eos_with_critical_point/src/EOS.c
MonitSharma/MS_Thesis
9af18f8b25da90ead96a680486caa6dc56e1347a
[ "Apache-2.0" ]
null
null
null
eos_with_critical_point/src/EOS.c
MonitSharma/MS_Thesis
9af18f8b25da90ead96a680486caa6dc56e1347a
[ "Apache-2.0" ]
null
null
null
/* Copyright (c) 2018-2020, Paolo Parotto and Debora Mroczek, * Department of Physics, University of Houston, Houston, TX 77204, US. */ /* This main produces an EoS matching Lattice QCD at muB=0, and containing * a critical point in the 3D Ising universality class, in a parametrized form. * It allows for different choices of constraints on the shape of the critical * line, which reduce the number of parameters. */ #define NRANSI // --------- INCLUDE -------- // #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <math.h> #include <unistd.h> #include <string.h> #include <time.h> #include <err.h> #include "../include/nrD.h" #include "../include/nrutilD.h" #include "../include/Variables.h" #include "../include/Functions.h" // --------- DEFINE --------- // #ifndef PI #define PI 3.141592653589 #endif #ifndef N #define N 2 #endif /* default settings */ int verbose=0; int print=0; int strange=0; int lattice=0; char lat_data[FILENAME_MAX]; char lat_data_SN[FILENAME_MAX]; char HRG_press[FILENAME_MAX]; char HRG_press_SN[FILENAME_MAX]; char MODE[FILENAME_MAX]; int lowT=5, highT=821; int lowMU=0, highMU=601; int lowT_out=30, highT_out=800; int lowMU_out=0, highMU_out=450; void help() /*{{{*/ { puts(""); puts(" Usage:"); puts(" ./EoS [options] <param_file>"); puts(""); puts(" <param_file>"); puts(" Lattice_chi: path to file with lattice coefficients"); puts(" for muQ=muS=0"); puts(" Lattice_chi_SN: path to file with lattice coefficients"); puts(" for strangeness neutrality"); puts(" HRG_press: path to fie with HRG pressure for muQ=muS=0"); puts(" HRG_press_SN: path to file with HRG pressure for"); puts(" strangeness neutrality"); puts(" Mode: whether CP is to be placed onto parabola,"); puts(" straight line, or freely."); puts(" T0: chiral transition temperature at muB=0"); puts(" (only for mode PAR,STR"); puts(" kappa: curvature of chiral transition at muB=0"); puts(" (only for mode PAR)"); puts(" TC: critical temperature (only for mode FREE)"); puts(" angle1: angle alpha1 (only for modes FREE,STR)"); puts(" muBC: critical chemical potential"); puts(" anglediff: alpha2-alpha1 (in degrees)"); puts(" ww: parameter w"); puts(" rho: parameter rho"); puts(""); puts(" options:"); puts(" -r<lowT>:<highT> Change T-range (still within limits)"); puts(" -R<lowMU>:<highMU> Change mu-range (still within limits)"); puts(" -L Lattice mode: produce EoS without CP"); puts(" -S Consider the strangeness neutral case"); puts(" -p Output data for intermediate steps too"); puts(" -v Verbose, print more stuff"); puts(" -h Print help"); puts(""); } /*}}}*/ void allocate () /*{{{*/ { /* Vectors for the root finding */ x=vector(1,N); f=vector(1,N); // Matrix for Jacobian. JJ=matrix(1,N,1,N); // Rank 3 tensor for coordinates. Coords=f3tensor(lowT,highT,0,2*highMU,1,N); // Vectors for Chi's at muB=0. Chi0LatVec=vector(lowT,highT); Chi2LatVec=vector(lowT,highT); Chi4LatVec=vector(lowT,highT); Chi0IsingVec=vector(lowT,highT); Chi2IsingVec=vector(lowT,highT); Chi4IsingVec=vector(lowT,highT); Chi0NoIsingVec=vector(lowT,highT); Chi2NoIsingVec=vector(lowT,highT); Chi4NoIsingVec=vector(lowT,highT); dChi0NoIsingdTVec=vector(lowT,highT); dChi2NoIsingdTVec=vector(lowT,highT); dChi4NoIsingdTVec=vector(lowT,highT); d2Chi0NoIsingdT2Vec=vector(lowT,highT); d2Chi2NoIsingdT2Vec=vector(lowT,highT); d2Chi4NoIsingdT2Vec=vector(lowT,highT); // Matrices for thermodynamic functions over the phase diagram. // NonIsing PressNoIsingMat=matrix(lowT,highT,0,highMU); dPressNoIsingdTMat=matrix(lowT,highT,0,highMU); dPressNoIsingdmuBMat=matrix(lowT,highT,0,highMU); d2PressNoIsingdT2Mat=matrix(lowT,highT,0,highMU); d2PressNoIsingdmuB2Mat=matrix(lowT,highT,0,highMU); d2PressNoIsingdTdmuBMat=matrix(lowT,highT,0,highMU); // NonIsing (after filtering) PressNoIsingFilterMat=matrix(lowT,highT,0,highMU); dPressNoIsingFilterdTMat=matrix(lowT,highT,0,highMU); dPressNoIsingFilterdmuBMat=matrix(lowT,highT,0,highMU); d2PressNoIsingFilterdT2Mat=matrix(lowT,highT,0,highMU); d2PressNoIsingFilterdmuB2Mat=matrix(lowT,highT,0,highMU); d2PressNoIsingFilterdTdmuBMat=matrix(lowT,highT,0,highMU); // Ising PressIsingMat=matrix(lowT,highT,0,highMU); dPressIsingdTMat=matrix(lowT,highT,0,highMU); dPressIsingdmuBMat=matrix(lowT,highT,0,highMU); d2PressIsingdT2Mat=matrix(lowT,highT,0,highMU); d2PressIsingdmuB2Mat=matrix(lowT,highT,0,highMU); d2PressIsingdTdmuBMat=matrix(lowT,highT,0,highMU); // Ising + NonIsing (after filtering) PressTotMat=matrix(lowT,highT,0,highMU); dPressTotdTMat=matrix(lowT,highT,0,highMU); dPressTotdmuBMat=matrix(lowT,highT,0,highMU); d2PressTotdT2Mat=matrix(lowT,highT,0,highMU); d2PressTotdmuB2Mat=matrix(lowT,highT,0,highMU); d2PressTotdTdmuBMat=matrix(lowT,highT,0,highMU); // HRG PressHRGMat=matrix(lowT,highT,0,highMU); dPressHRGdTMat=matrix(lowT,highT,0,highMU); dPressHRGdmuBMat=matrix(lowT,highT,0,highMU); d2PressHRGdT2Mat=matrix(lowT,highT,0,highMU); d2PressHRGdmuB2Mat=matrix(lowT,highT,0,highMU); d2PressHRGdTdmuBMat=matrix(lowT,highT,0,highMU); // Total + HRG PressTotHRGMat=matrix(lowT,highT,0,highMU); dPressTotHRGdTMat=matrix(lowT,highT,0,highMU); dPressTotHRGdmuBMat=matrix(lowT,highT,0,highMU); d2PressTotHRGdT2Mat=matrix(lowT,highT,0,highMU); d2PressTotHRGdmuB2Mat=matrix(lowT,highT,0,highMU); d2PressTotHRGdTdmuBMat=matrix(lowT,highT,0,highMU); // Final (normalized) PressFinalMat=matrix(lowT,highT,0,highMU); EntropyFinalMat=matrix(lowT,highT,0,highMU); BarDensityFinalMat=matrix(lowT,highT,0,highMU); EnerDensityFinalMat=matrix(lowT,highT,0,highMU); SpSoundFinalMat=matrix(lowT,highT,0,highMU); Chi2FinalMat=matrix(lowT,highT,0,highMU); /* For correlation length */ CorrLengthEpsExpMat=matrix(lowT,highT,0,highMU); CorrLengthAsymptMat=matrix(lowT,highT,0,highMU); CorrLengthMergedMat=matrix(lowT,highT,0,highMU); // If LAT only is chosen (not normalized) PressLATonlyMat=matrix(lowT,highT,0,highMU); dPressLATonlydTMat=matrix(lowT,highT,0,highMU); dPressLATonlydmuBMat=matrix(lowT,highT,0,highMU); d2PressLATonlydT2Mat=matrix(lowT,highT,0,highMU); d2PressLATonlydmuB2Mat=matrix(lowT,highT,0,highMU); d2PressLATonlydTdmuBMat=matrix(lowT,highT,0,highMU); PressLATonlyFilterMat=matrix(lowT,highT,0,highMU); // If LAT only is chosen (normalized) PressLATonlyNormMat=matrix(lowT,highT,0,highMU); EntropyLATonlyNormMat=matrix(lowT,highT,0,highMU); BarDensityLATonlyNormMat=matrix(lowT,highT,0,highMU); EnerDensityLATonlyNormMat=matrix(lowT,highT,0,highMU); SpSoundLATonlyNormMat=matrix(lowT,highT,0,highMU); Chi2LATonlyNormMat=matrix(lowT,highT,0,highMU); } /*}}}*/ void read_param(char * param_file) /*{{{*/ { /* Read from the parameter file the following: * Lattice_chi: lattice coefficients for muS=muQ=0 * Lattice_chi_SN: lattice coefficients for strangeness neutrality * HRG_press: HRG pressure * Mode: whether CP is to be placed onto parabola, straight line ... * T0: chiral transition temp at muB=0 (only for mode PAR,STR) * kappa: curvature of chiral transition at muB=0 (only for modes PAR) * TC: critical temperature (only for mode FREE) * angle1: angle alpha1 (only for modes FREE,STR) * muBC: critical chemical potential * anglediff: alpha2-alpha1 * ww: parameter w * rho: parameter rho */ fprintf(stderr,"Reading parameter file.\n"); FILE * file=fopen(param_file,"r"); char line[FILENAME_MAX]; if(file==NULL) err(1,"Could not open %s\n", param_file); while(fgets(line, sizeof(line),file)){ char *c=strchr(line,'#'); if (c) *c=0; if(sscanf(line,"Lattice_chi=%1024s ", lat_data)==1) continue; if(sscanf(line,"Lattice_chi_SN=%1024s ", lat_data_SN)==1) continue; if(sscanf(line,"HRG_press=%1024s ", HRG_press)==1) continue; if(sscanf(line,"HRG_press_SN=%1024s ", HRG_press_SN)==1) continue; if(sscanf(line,"Mode=%16s ", MODE)==1) continue; if(sscanf(line,"T0=%lf ", &T0)==1) continue; if(sscanf(line,"kappa=%lf ", &kappa)==1) continue; if(sscanf(line,"TC=%lf ", &TC_in)==1) continue; if(sscanf(line,"angle1=%lf ", &angle1_in)==1) continue; if(sscanf(line,"muBC=%lf ", &muBC)==1) continue; if(sscanf(line,"anglediff=%lf ", &anglediff)==1) continue; if(sscanf(line,"ww=%lf ", &ww)==1) continue; if(sscanf(line,"rho=%lf ", &rho)==1) continue; err(1,"Line: <%s> was not understood", line); } fclose(file); if(lattice) goto end_param; /* Import and store parameters */ fprintf(stderr,"MODE: %s\n", MODE); if(strcmp(MODE,"FREE") == 0){ strcpy(MODESTR, "FREE"); TC = TC_in; angle1=angle1_in; angle2 = angle1+anglediff; fprintf(stderr,"The parameters you entered are:\n" "TC = %f\nmuBC = %f\nangle1 = %f\n" "angle2 = %f\nw = %f\nrho = %f\n", TC,muBC,angle1,angle2,ww,rho); } else if(strcmp(MODE,"PAR") == 0){ strcpy(MODESTR, "PAR"); TC=T0+kappa/T0*muBC*muBC; angle1 = 180/PI*fabs(atan(-2.0*kappa/T0*muBC)); angle2 = angle1 + anglediff; fprintf(stderr,"PARABOLA\n"); fprintf(stderr,"The parameters you entered are:\n" "TC = %f\nmuBC = %f\nangle1 = %f\n" "angle2 = %f\nw = %f\nrho = %f\n", TC,muBC,angle1,angle2,ww,rho); } else if(strcmp(MODE,"STR") == 0){ strcpy(MODESTR, "STR"); angle1 = angle1_in; TC=T0-atan(angle1*PI/180)*muBC; fprintf(stderr,"The parameters you entered are:\n" "TC = %f\nmuBC = %f\nangle1 = %f\n" "angle2 = %f\nw = %f\nrho = %f\n", TC,muBC,angle1,angle2,ww,rho); } else err(1,"Mode could not be set properly.\n"); /* we determine dTC and dmuBC from TC, muBC, ww and rho. */ dTC = ww*TC; dmuBC = dTC*rho; end_param: fprintf(stderr,"Finished importing and setting parameters.\n"); } /*}}}*/ void read_lattice_data (char * lattice_data) /*{{{*/ { /* Chi's from Lattice are imported and stored in a vector */ fprintf(stderr,"Importing lattice data.\n"); FILE *LatIn = fopen(lattice_data,"r"); if (LatIn == 0) err(1, "Failed to open Lattice Data\n"); fprintf(stderr,"File imported succesfully!\n"); /* Save lattice chis into vectors (make them dimension of * energy^4). */ for(i=lowT;fscanf(LatIn,"%lf %lf %lf %lf",&xIn1,&xIn2,&xIn3,&xIn4) !=EOF;i++){ Chi0LatVec[i] = xIn2*pow(i,4); Chi2LatVec[i] = xIn3*pow(i,4); Chi4LatVec[i] = xIn4*pow(i,4); } fclose(LatIn); fprintf(stderr,"Successfully stored lattice data.\n"); } /*}}}*/ void do_lattice() /*{{{*/ { fprintf(stderr,"You chose to consider the lattice-only case," "without a Critical Point.\n"); /* Creating directory and moving into it. */ char LATdir[FILENAME_MAX]; if (!strange) strcpy(LATdir,"LATonly"); else strcpy(LATdir,"LATonly_SN"); mkdir(LATdir, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH); chdir(LATdir); /* Calculate Taylor expanded pressure. */ for (i=lowT;i<=highT; i++) for(j=0; j<=highMU; j++){ muBval = (double) j; Tval = (double) i; PressLATonlyMat[i][j] = Chi0LatVec[i] + 1.0/2.0*Chi2LatVec[i]*pow(muBval/Tval,2) + 1.0/24.0*Chi4LatVec[i]*pow(muBval/Tval,4); } // Take all the needed derivatives of the pressure. // Wrt T deriv_matrix(PressLATonlyMat,dPressLATonlydTMat, 1,lowT,highT,0,highMU,0); deriv_matrix(dPressLATonlydTMat,d2PressLATonlydT2Mat, 1,lowT,highT,0,highMU,0); // Wrt muB deriv_matrix(PressLATonlyMat,dPressLATonlydmuBMat, 2,lowT,highT,0,highMU,0); deriv_matrix(dPressLATonlydmuBMat,d2PressLATonlydmuB2Mat, 2,lowT,highT,0,highMU,1); // Wrt T and muB deriv_matrix(dPressLATonlydTMat,d2PressLATonlydTdmuBMat, 2,lowT,highT,0,highMU,0); // That is it. Now we just need to combine these into the final observables (normalized). fprintf(stderr,"Calculating thermodynamics quantities. \n"); // Create the files for export. FILE *FilePressLATonlyNorm = fopen("PressLATonlyNorm3D.dat", "w"); FILE *FileEntrLATonlyNorm = fopen("EntrLATonlyNorm3D.dat", "w"); FILE *FileBarDensLATonlyNorm = fopen("BarDensLATonlyNorm3D.dat", "w"); FILE *FileEnerDensLATonlyNorm = fopen("EnerDensLATonlyNorm3D.dat", "w"); FILE *FileSpSoundLATonlyNorm = fopen("SpsoundLATonlyNorm3D.dat", "w"); FILE *FileChi2LATonlyNorm = fopen("Chi2LATonlyNorm3D.dat", "w"); // Export. for (i=lowT_out; i<=highT_out; i++) for(j=0;j<=highMU_out; j++){ Tval = (double) i; muBval = (double) j; PressLATonlyNormMat[i][j] = PressLATonlyMat[i][j]/pow(Tval,4); EntropyLATonlyNormMat[i][j] = dPressLATonlydTMat[i][j]/pow(Tval,3); BarDensityLATonlyNormMat[i][j] = dPressLATonlydmuBMat[i][j]/pow(Tval,3); EnerDensityLATonlyNormMat[i][j] = (dPressLATonlydTMat[i][j]*Tval-PressLATonlyMat[i][j] +muBval*dPressLATonlydmuBMat[i][j])/pow(Tval,4); SpSoundLATonlyNormMat[i][j] = (dPressLATonlydmuBMat[i][j]*dPressLATonlydmuBMat[i][j] *d2PressLATonlydT2Mat[i][j] - 2.0*dPressLATonlydTMat[i][j]*dPressLATonlydmuBMat[i][j] *d2PressLATonlydTdmuBMat[i][j] + dPressLATonlydTMat[i][j]*dPressLATonlydTMat[i][j] *d2PressLATonlydmuB2Mat[i][j]) /(dPressLATonlydTMat[i][j]*Tval +muBval*dPressLATonlydmuBMat[i][j]) /(d2PressLATonlydT2Mat[i][j]*d2PressLATonlydmuB2Mat[i][j] -d2PressLATonlydTdmuBMat[i][j]*d2PressLATonlydTdmuBMat[i][j]); Chi2LATonlyNormMat[i][j] = d2PressLATonlydmuB2Mat[i][j]/pow(Tval,2); fprintf(FilePressLATonlyNorm,"%3.16f %3.1f %12.16f \n", muBval, Tval, PressLATonlyNormMat[i][j]); fprintf(FileEntrLATonlyNorm,"%3.16f %3.1f %12.16f \n", muBval, Tval, EntropyLATonlyNormMat[i][j]); fprintf(FileBarDensLATonlyNorm,"%3.16f %3.1f %12.16f \n", muBval, Tval, BarDensityLATonlyNormMat[i][j]); fprintf(FileEnerDensLATonlyNorm,"%3.16f %3.1f %12.16f \n", muBval, Tval, EnerDensityLATonlyNormMat[i][j]); fprintf(FileSpSoundLATonlyNorm,"%3.16f %3.1f %12.16f \n", muBval, Tval, SpSoundLATonlyNormMat[i][j]); fprintf(FileChi2LATonlyNorm,"%3.16f %3.1f %12.16f \n", muBval, Tval, Chi2LATonlyNormMat[i][j]); } // Close the files. fclose(FilePressLATonlyNorm); fclose(FileEntrLATonlyNorm); fclose(FileBarDensLATonlyNorm); fclose(FileEnerDensLATonlyNorm); fclose(FileSpSoundLATonlyNorm); fclose(FileChi2LATonlyNorm); fprintf(stderr,"The procedure is completed. Exiting.\n"); } /*}}}*/ void write_filenames() /*{{{*/ { if (!strange) sprintf(nameFolder, "Files_%s_%d_%d_%d_%d_%d_%d",MODESTR,(int)TC,(int)muBC, (int)angle1,(int)angle2,(int) dTC,(int) dmuBC); else sprintf(nameFolder, "Files_%s_%d_%d_%d_%d_%d_%d_SN",MODESTR,(int)TC,(int)muBC, (int)angle1,(int)angle2,(int) dTC,(int) dmuBC); sprintf(nameCoords, "Coords_%s_%d_%d_%d_%d_%d_%d.dat",MODESTR,(int)TC,(int)muBC, (int)angle1,(int)angle2,(int) dTC,(int) dmuBC); sprintf(nameChisIsing, "Chis_Ising_%s_%d_%d_%d_%d_%d_%d_muB0.dat",MODESTR,(int)TC,(int)muBC, (int)angle1,(int)angle2,(int) dTC,(int) dmuBC); sprintf(nameChisNoIsing, "Chis_No_Ising_%s_%d_%d_%d_%d_%d_%d_muB0.dat",MODESTR,(int)TC, (int)muBC,(int)angle1,(int)angle2,(int) dTC,(int) dmuBC); sprintf(namedChisNoIsingdT, "dChis_No_Ising_dT_%s_%d_%d_%d_%d_%d_%d_muB0.dat",MODESTR,(int)TC, (int)muBC,(int)angle1,(int)angle2,(int) dTC,(int) dmuBC); sprintf(named2ChisNoIsingdT2, "d2Chis_No_Ising_dT2%s_%d_%d_%d_%d_%d_%d_muB0.dat",MODESTR,(int)TC, (int)muBC,(int)angle1,(int)angle2,(int) dTC,(int) dmuBC); sprintf(namePressIsing3D, "Press_Ising_%s_%d_%d_%d_%d_%d_%d_3D.dat",MODESTR,(int)TC, (int)muBC,(int)angle1,(int)angle2,(int) dTC,(int) dmuBC); sprintf(namedPdTIsing3D, "dPdT_Ising_%s_%d_%d_%d_%d_%d_%d_3D.dat",MODESTR,(int)TC, (int)muBC,(int)angle1,(int)angle2,(int) dTC,(int) dmuBC); sprintf(namedPdmuBIsing3D, "dPdmuB_Ising_%s_%d_%d_%d_%d_%d_%d_3D.dat",MODESTR,(int)TC, (int)muBC,(int)angle1,(int)angle2,(int) dTC,(int) dmuBC); sprintf(named2PdT2Ising3D, "d2PdT2_Ising_%s_%d_%d_%d_%d_%d_%d_3D.dat",MODESTR,(int)TC, (int)muBC,(int)angle1,(int)angle2,(int) dTC,(int) dmuBC); sprintf(named2PdmuB2Ising3D, "d2PdmuB2_Ising_%s_%d_%d_%d_%d_%d_%d_3D.dat",MODESTR,(int)TC, (int)muBC,(int)angle1,(int)angle2,(int) dTC,(int) dmuBC); sprintf(named2PdTdmuBIsing3D, "d2PdTdmuB_Ising_%s_%d_%d_%d_%d_%d_%d_3D.dat",MODESTR,(int)TC,(int)muBC,(int)angle1,(int)angle2,(int) dTC,(int) dmuBC); sprintf(namePressNoIsing3D, "Press_No_Ising_%s_%d_%d_%d_%d_%d_%d_3D.dat",MODESTR,(int)TC,(int)muBC,(int)angle1,(int)angle2,(int) dTC,(int) dmuBC); sprintf(namedPdTNoIsing3D, "dPdT_No_Ising_%s_%d_%d_%d_%d_%d_%d_3D.dat",MODESTR,(int)TC,(int)muBC,(int)angle1,(int)angle2,(int) dTC,(int) dmuBC); sprintf(namedPdmuBNoIsing3D, "dPdmuB_No_Ising_%s_%d_%d_%d_%d_%d_%d_3D.dat",MODESTR,(int)TC,(int)muBC,(int)angle1,(int)angle2,(int) dTC,(int) dmuBC); sprintf(named2PdT2NoIsing3D, "d2PdT2_No_Ising_%s_%d_%d_%d_%d_%d_%d_3D.dat",MODESTR,(int)TC,(int)muBC,(int)angle1,(int)angle2,(int) dTC,(int) dmuBC); sprintf(named2PdmuB2NoIsing3D, "d2PdmuB2_No_Ising_%s_%d_%d_%d_%d_%d_%d_3D.dat",MODESTR,(int)TC,(int)muBC,(int)angle1,(int)angle2,(int) dTC,(int) dmuBC); sprintf(named2PdTdmuBNoIsing3D, "d2PdTdmuB_No_Ising_%s_%d_%d_%d_%d_%d_%d_3D.dat",MODESTR,(int)TC,(int)muBC,(int)angle1,(int)angle2,(int) dTC,(int) dmuBC); sprintf(namePressIsingPlusNoIsing3D, "Press_Ising_Plus_No_Ising_%s_%d_%d_%d_%d_%d_%d_3D.dat",MODESTR,(int)TC,(int)muBC,(int)angle1,(int)angle2,(int) dTC,(int) dmuBC); sprintf(namedPdTIsingPlusNoIsing3D, "dPdT_Ising_Plus_No_Ising_%s_%d_%d_%d_%d_%d_%d_3D.dat",MODESTR,(int)TC,(int)muBC,(int)angle1,(int)angle2,(int) dTC,(int) dmuBC); sprintf(namedPdmuBIsingPlusNoIsing3D, "dPdmuB_Ising_Plus_No_Ising_%s_%d_%d_%d_%d_%d_%d_3D.dat",MODESTR,(int)TC,(int)muBC,(int)angle1,(int)angle2,(int) dTC,(int) dmuBC); sprintf(named2PdT2IsingPlusNoIsing3D, "d2PdT2_Ising_Plus_No_Ising_%s_%d_%d_%d_%d_%d_%d_3D.dat",MODESTR,(int)TC,(int)muBC,(int)angle1,(int)angle2,(int) dTC,(int) dmuBC); sprintf(named2PdmuB2IsingPlusNoIsing3D, "d2PdmuB2_Ising_Plus_No_Ising_%s_%d_%d_%d_%d_%d_%d_3D.dat",MODESTR,(int)TC,(int)muBC,(int)angle1,(int)angle2,(int) dTC,(int) dmuBC); sprintf(named2PdTdmuBIsingPlusNoIsing3D, "d2PdTdmuB_Ising_Plus_No_Ising_%s_%d_%d_%d_%d_%d_%d_3D.dat",MODESTR,(int)TC,(int)muBC,(int)angle1,(int)angle2,(int) dTC,(int) dmuBC); sprintf(namePressTotHRG3D, "Press_Tot_HRG_%s_%d_%d_%d_%d_%d_%d_3D.dat",MODESTR,(int)TC,(int)muBC,(int)angle1,(int)angle2,(int) dTC,(int) dmuBC); sprintf(namedPdTTotHRG3D, "dPdT_Tot_HRG_%s_%d_%d_%d_%d_%d_%d_3D.dat",MODESTR,(int)TC,(int)muBC,(int)angle1,(int)angle2,(int) dTC,(int) dmuBC); sprintf(namedPdmuBTotHRG3D, "dPdmuB_Tot_HRG_%s_%d_%d_%d_%d_%d_%d_3D.dat",MODESTR,(int)TC,(int)muBC,(int)angle1,(int)angle2,(int) dTC,(int) dmuBC); sprintf(named2PdT2TotHRG3D, "d2PdT2_Tot_HRG_%s_%d_%d_%d_%d_%d_%d_3D.dat",MODESTR,(int)TC,(int)muBC,(int)angle1,(int)angle2,(int) dTC,(int) dmuBC); sprintf(named2PdmuB2TotHRG3D, "d2PdmuB2_Tot_HRG_%s_%d_%d_%d_%d_%d_%d_3D.dat",MODESTR,(int)TC,(int)muBC,(int)angle1,(int)angle2,(int) dTC,(int) dmuBC); sprintf(named2PdTdmuBTotHRG3D, "d2PdTdmuB_Tot_HRG_%s_%d_%d_%d_%d_%d_%d_3D.dat",MODESTR,(int)TC,(int)muBC,(int)angle1,(int)angle2,(int) dTC,(int) dmuBC); sprintf(namePressFinal3D, "Press_Final_%s_%d_%d_%d_%d_%d_%d_3D.dat",MODESTR,(int)TC,(int)muBC,(int)angle1,(int)angle2,(int) dTC,(int) dmuBC); sprintf(nameEntrFinal3D, "Entr_Final_%s_%d_%d_%d_%d_%d_%d_3D.dat",MODESTR,(int)TC,(int)muBC,(int)angle1,(int)angle2,(int) dTC,(int) dmuBC); sprintf(nameBarDensFinal3D, "BarDens_Final_%s_%d_%d_%d_%d_%d_%d_3D.dat",MODESTR,(int)TC,(int)muBC,(int)angle1,(int)angle2,(int) dTC,(int) dmuBC); sprintf(nameEnerDensFinal3D, "EnerDens_Final_%s_%d_%d_%d_%d_%d_%d_3D.dat",MODESTR,(int)TC,(int)muBC,(int)angle1,(int)angle2,(int) dTC,(int) dmuBC); sprintf(nameSpsoundFinal3D, "SpSound_Final_%s_%d_%d_%d_%d_%d_%d_3D.dat",MODESTR,(int)TC,(int)muBC,(int)angle1,(int)angle2,(int) dTC,(int) dmuBC); sprintf(nameChi2Final3D, "Chi2_Final_%s_%d_%d_%d_%d_%d_%d_3D.dat",MODESTR,(int)TC,(int)muBC,(int)angle1,(int)angle2,(int) dTC,(int) dmuBC); sprintf(nameCorrLengthFinal3D, "CorrLength_Final_%s_%d_%d_%d_%d_%d_%d_3D.dat",MODESTR,(int)TC,(int)muBC,(int)angle1,(int)angle2,(int) dTC,(int) dmuBC); } /*}}}*/ void calc_jacobian() /*{{{*/ { /* For calculations hereafter, angles are expressed in radians. */ angle1 = angle1*PI/180; angle2 = angle2*PI/180; /* Jacobian matrix of the (r,h) -> (T,muB) map is generated. */ Jacobian(JJ,dTC,dmuBC,angle1,angle2); drdmuB = JJ[1][2]; dhdmuB = JJ[2][2]; drdT = JJ[1][1]; dhdT = JJ[2][1]; fprintf(stderr,"\nThe Jacobian calculation gave:\n" "drdmuB = %12.16f\ndhdT = %12.16f\n" "drdT = %12.16f\ndhmuB = %12.16f\n", drdmuB,dhdmuB,drdT,dhdT); } /*}}}*/ void make_coords() /*{{{*/ { FILE *fp=fopen(nameCoords,"w"); fprintf(stderr,"\nCreating the coordinates file...\n"); // Time is taken at start and end to measure how long it took to generate the coordinates file. time(&start); for(Ti=lowT;Ti<=highT;Ti+=1.0) for(muBi=-highMU;muBi<=highMU;muBi+=1.0){ h_i = hh(Ti,muBi); r_i = rr(Ti, muBi); /* Condition for choosing init condition in root finding. */ x[1] = 1.0; if(h_i > 0) x[2] = 1.0; if(h_i <= 0) x[2] = -1.0; /* The actual root finding routine. */ newt(x,N,&check,funcv); funcv(N,x,f); if (check) printf("Convergence problems.\n"); /* Print to file the coordinates {T,muB,R,Theta} (in this order). */ fprintf(fp,"%3.1f %3.1f %2.16f %2.16f\n",Ti,muBi,x[1],x[2]); } time(&end); /* A control on whether the loops reached the end, and did not get stuck, otherwise file is eliminated. */ if(Ti == (highT+1) && muBi == (highMU+1)) fprintf(stderr,"\nThe file %s was created successfully in %d seconds\n", nameCoords, (int) difftime(end,start)); else{ remove(nameCoords); err(1,"The file %s was NOT created successfully," " removing it.\n",nameCoords); } fclose(fp); // Coordinates are imported and stored in a Rank 3 tensor Coords. fprintf(stderr,"Importing coordinates from file %s \n",nameCoords); fp=fopen(nameCoords,"r"); for(j=0, x1int=lowT-1;fscanf(fp,"%lf %lf %lf %lf\n", &xIn1, &xIn2, &xIn3, &xIn4) != EOF; j++ ){ x2int = j % (2*highMU+1); if (x2int == 0) x1int++; Coords[x1int][x2int][1] = xIn3; Coords[x1int][x2int][2] = xIn4; } fclose(fp); fprintf(stderr,"Imported coordinates successfully.\n"); } /*}}}*/ void make_Ising() /*{{{*/ { /* The coordinates corresponding to muB=0 are used * to generate the critical Chi's at different temperatures * and exported. */ fprintf(stderr,"Generating Ising at muB=0\n"); FILE * FileChiIsing=NULL; FILE * FilePressIsing=NULL; FILE * FiledPdTIsing=NULL; FILE * FiledPdmuBIsing=NULL; FILE * Filed2PdT2Ising=NULL; FILE * Filed2PdmuB2Ising=NULL; FILE * Filed2PdTdmuBIsing=NULL; if (print){ FileChiIsing=fopen(nameChisIsing,"w"); FilePressIsing=fopen(namePressIsing3D,"w"); FiledPdTIsing=fopen(namedPdTIsing3D,"w"); FiledPdmuBIsing=fopen(namedPdmuBIsing3D,"w"); Filed2PdT2Ising=fopen(named2PdT2Ising3D,"w"); Filed2PdmuB2Ising=fopen(named2PdmuB2Ising3D,"w"); Filed2PdTdmuBIsing=fopen(named2PdTdmuBIsing3D,"w"); } for(i=lowT;i<=highT;i++){ Tval = (double) i; Chi0IsingVec[i] = -G(Coords[i][highMU][1],Coords[i][highMU][2])*pow(TC,4); Chi2IsingVec[i] = -Tval*Tval*d2GdmuB2ConT(Coords[i][highMU][1],Coords[i][highMU][2])*pow(TC,4); Chi4IsingVec[i] = -Tval*Tval*Tval*Tval*d4GdmuB4ConT(Coords[i][highMU][1],Coords[i][highMU][2])*pow(TC,4); if (print){ fprintf(FileChiIsing,"%3.1f %12.16f %12.16f %12.16f\n",(double) i,Chi0IsingVec[i],Chi2IsingVec[i],Chi4IsingVec[i]); } } fprintf(stderr,"Generation successful\n"); /* The pressure is generated over the whole range of coordinates. * NOTE: the pressure is symmetrized around muB=0 to ensure all odd order * derivatives vanish at muB=0. */ fprintf(stderr,"Generating Ising in 3D\n"); for(i=lowT;i<highT;i++) for(j=0;j<=highMU;j++){ k = j + highMU; if(j==0){ PressIsingMat[i][j] = - G(Coords[i][k][1],Coords[i][k][2])*pow(TC,4); dPressIsingdTMat[i][j] = - dGdTConmuB(Coords[i][k][1],Coords[i][k][2])*pow(TC,4); dPressIsingdmuBMat[i][j] = 0.0; d2PressIsingdT2Mat[i][j] = - d2GdT2ConmuB(Coords[i][k][1],Coords[i][k][2])*pow(TC,4); d2PressIsingdmuB2Mat[i][j] = - d2GdmuB2ConT(Coords[i][k][1],Coords[i][k][2])*pow(TC,4); d2PressIsingdTdmuBMat[i][j] = 0.0; CorrLengthEpsExpMat[i][j] = CalcCorrLengthEpsExp(Coords[i][k][1],Coords[i][k][2]); CorrLengthAsymptMat[i][j] = CalcCorrLengthAsympt(Coords[i][k][1],Coords[i][k][2]); } else{ PressIsingMat[i][j] = - (G(Coords[i][k][1],Coords[i][k][2]) + G(Coords[i][k-2*j][1],Coords[i][k-2*j][2]))/2.0*pow(TC,4); dPressIsingdTMat[i][j] = - (dGdTConmuB(Coords[i][k][1],Coords[i][k][2]) + dGdTConmuB(Coords[i][k-2*j][1],Coords[i][k-2*j][2]))/2.0*pow(TC,4); dPressIsingdmuBMat[i][j] = - (dGdmuBConT(Coords[i][k][1],Coords[i][k][2]) - dGdmuBConT(Coords[i][k-2*j][1],Coords[i][k-2*j][2]))/2.0*pow(TC,4); d2PressIsingdT2Mat[i][j] = - (d2GdT2ConmuB(Coords[i][k][1],Coords[i][k][2]) + d2GdT2ConmuB(Coords[i][k-2*j][1],Coords[i][k-2*j][2]))/2.0*pow(TC,4); d2PressIsingdmuB2Mat[i][j] = - (d2GdmuB2ConT(Coords[i][k][1],Coords[i][k][2]) + d2GdmuB2ConT(Coords[i][k-2*j][1],Coords[i][k-2*j][2]))/2.0*pow(TC,4); d2PressIsingdTdmuBMat[i][j] = - (d2GdTdmuB(Coords[i][k][1],Coords[i][k][2]) - d2GdTdmuB(Coords[i][k-2*j][1],Coords[i][k-2*j][2]))/2.0*pow(TC,4); CorrLengthEpsExpMat[i][j] = CalcCorrLengthEpsExp(Coords[i][k][1],Coords[i][k][2]); CorrLengthAsymptMat[i][j] = CalcCorrLengthAsympt(Coords[i][k][1],Coords[i][k][2]); } if (print){ fprintf(FilePressIsing,"%3.1f %3.1f %12.16f\n", (double) j,(double) i, PressIsingMat[i][j]); fprintf(FiledPdTIsing,"%3.1f %3.1f %12.16f\n", (double) j,(double) i, dPressIsingdTMat[i][j]); fprintf(FiledPdmuBIsing,"%3.1f %3.1f %12.16f\n", (double) j,(double) i, dPressIsingdmuBMat[i][j]); fprintf(Filed2PdT2Ising,"%3.1f %3.1f %12.16f\n", (double) j,(double) i, d2PressIsingdT2Mat[i][j]); fprintf(Filed2PdmuB2Ising,"%3.1f %3.1f %12.16f\n", (double) j,(double) i, d2PressIsingdmuB2Mat[i][j]); fprintf(Filed2PdTdmuBIsing,"%3.1f %3.1f %12.16f\n", (double) j,(double) i, d2PressIsingdTdmuBMat[i][j]); } } if (print){ fclose(FileChiIsing); fclose(FilePressIsing); fclose(FiledPdTIsing); fclose(FiledPdmuBIsing); fclose(Filed2PdT2Ising); fclose(Filed2PdmuB2Ising); fclose(Filed2PdTdmuBIsing); } } /*}}}*/ void merge_CorrLength() /*{{{*/ { Ttip = 145; muBtip = 320; TMlow = 195.0; T0low = 58.0; klow = 0.00318462; T0high = 282.594; khigh = 0.00207197; TMmerg = 17.0; T0merg = 0.1; kmerg = 0.0075; for (i=lowT_out; i<=highT_out; i++) for(j=0;j<=highMU_out; j++){ Tval = (double) i; muBval = (double) j; Tlow = TMlow - (TMlow - T0low)*exp(-klow*muBval); Thigh = T0high*exp(-khigh*muBval); Tmerg = T0merg + (TMmerg - T0merg)*exp(-kmerg*muBval); if(i<Ttip && j<=muBtip){ CorrLengthMergedMat[i][j] = CorrLengthAsymptMat[i][j]*0.5*(1.0 + tanh((Tval - Tlow)/Tmerg)) + CorrLengthEpsExpMat[i][j]*0.5*(1.0 - tanh((Tval - Tlow)/Tmerg)); } else if(i>=Ttip && j<=muBtip){ CorrLengthMergedMat[i][j] = CorrLengthAsymptMat[i][j]*0.5*(1.0 - tanh((Tval - Thigh)/Tmerg)) + CorrLengthEpsExpMat[i][j]*0.5*(1.0 + tanh((Tval - Thigh)/Tmerg)); } else{ CorrLengthMergedMat[i][j] = CorrLengthEpsExpMat[i][j]; } } } /*}}}*/ void make_nonIsing() /*{{{*/ { /* Non-Ising Chi's are calculated, exported and stored. */ fprintf(stderr,"Generating non-Ising at muB = 0\n"); FILE * FileChiNoIsing; FILE * FilePressNoIsing; FILE * FilePressNoIsingFilter; FILE * FiledPdTNoIsingFilter; FILE * FiledPdmuBNoIsingFilter; FILE * Filed2PdT2NoIsingFilter; FILE * Filed2PdmuB2NoIsingFilter; FILE * Filed2PdTdmuBNoIsingFilter; if (print){ /* if printing intermediate steps is wanted */ FileChiNoIsing=fopen(nameChisNoIsing,"w"); FilePressNoIsing=fopen(namePressNoIsing3D,"w"); FilePressNoIsingFilter = fopen("NoIsingPressFilter.dat","w"); FiledPdTNoIsingFilter = fopen("NoIsingdPdTFilter.dat","w"); FiledPdmuBNoIsingFilter = fopen("NoIsingdPdmuBFilter.dat","w"); Filed2PdT2NoIsingFilter = fopen("NoIsingd2PdT2Filter.dat","w"); Filed2PdmuB2NoIsingFilter = fopen("NoIsingd2PdmuB2Filter.dat","w"); Filed2PdTdmuBNoIsingFilter = fopen("NoIsingd2PdTdmuBFilter.dat","w"); } for (i=lowT; i<=highT; i++){ Tval = (double) i; Chi0NoIsingVec[i] = Chi0LatVec[i] - Chi0IsingVec[i]; Chi2NoIsingVec[i] = Chi2LatVec[i] - Chi2IsingVec[i]; Chi4NoIsingVec[i] = Chi4LatVec[i] - Chi4IsingVec[i]; if(print) fprintf(FileChiNoIsing,"%3.1f %12.16f %12.16f %12.16f\n", Tval, Chi0NoIsingVec[i],Chi2NoIsingVec[i],Chi4NoIsingVec[i]); } /* The non-Ising pressure in 3D is calculated from Taylor expansion, * stored and exported. */ fprintf(stderr,"Calculating non-Ising in 3D.\n"); for (i=lowT; i<=highT; i++) for(j=0; j<=highMU; j++){ muBval = (double) j; Tval = (double) i; PressNoIsingMat[i][j] = Chi0NoIsingVec[i] +(1.0/2.0)*Chi2NoIsingVec[i]*pow(muBval/Tval,2) +(1.0/24.0)*Chi4NoIsingVec[i]*pow(muBval/Tval,4); if (print) fprintf(FilePressNoIsing,"%3.1f %3.1f %12.16f\n", muBval,Tval,PressNoIsingMat[i][j]); } /* Filtering of regular pressure here. Widths of the filter are also * set here. Result is stored and exported. */ fprintf(stderr,"Filtering non-Ising Pressure in 3D\n"); sigmax = 18.0; sigmay = 1.0; for (i=lowT; i<=highT; i++) for(j=0; j<=highMU; j++){ muBval = (double) j; Tval = (double) i; kmin = i-sigmax; kmax = i+sigmax; lmin = j-sigmay; lmax = j+sigmay; sum = 0.0; norm = 0.0; for(k=kmin;k<=kmax;k++) for(l=lmin;l<=lmax;l++){ if(k<=lowT) kint = lowT; else if(k>=highT) kint = highT; else kint = k; if(l<=0) lint = -l; else if(l>=highMU) lint = highMU; else lint = l; sum+=GausFunc(kint-i,lint-j,sigmax,sigmay)*PressNoIsingMat[kint][lint]; norm+=GausFunc(kint-i,lint-j,sigmax,sigmay); } PressNoIsingFilterMat[i][j] = sum/norm; if (print) fprintf(FilePressNoIsingFilter, "%3.1f %3.1f %12.16f\n", muBval,Tval,PressNoIsingFilterMat[i][j]); } /* Derivatives (numerical) of the filtered Non-Ising pressure * and all thermodynamic quantities of interest are calculated * and stored, over the phase diagram. */ fprintf(stderr,"Calculating (numerical) derivatives" " of the filtered Non-Ising Pressure\n"); /* Take all the needed derivatives */ /* Wrt T */ deriv_matrix(PressNoIsingFilterMat,dPressNoIsingFilterdTMat,1,lowT,highT,0,highMU,0); deriv_matrix(dPressNoIsingFilterdTMat,d2PressNoIsingFilterdT2Mat,1,lowT,highT,0,highMU,0); /* Wrt muB */ deriv_matrix(PressNoIsingFilterMat,dPressNoIsingFilterdmuBMat,2,lowT,highT,0,highMU,0); deriv_matrix(dPressNoIsingFilterdmuBMat,d2PressNoIsingFilterdmuB2Mat,2,lowT,highT,0,highMU,1); /* Wrt T and muB */ deriv_matrix(dPressNoIsingFilterdTMat,d2PressNoIsingFilterdTdmuBMat,2,lowT,highT,0,highMU,0); if(print){ fclose(FileChiNoIsing); fclose(FilePressNoIsing); fclose(FilePressNoIsingFilter); fclose(FiledPdTNoIsingFilter); fclose(FiledPdmuBNoIsingFilter); fclose(Filed2PdT2NoIsingFilter); fclose(Filed2PdmuB2NoIsingFilter); fclose(Filed2PdTdmuBNoIsingFilter); } } /*}}}*/ void merge_Ising_nonIsing() /*{{{*/ { /* Calculate pressure and derivatives summing Ising and non-Ising * pressure, then normalize. Store and export. */ fprintf(stderr,"Calculating other derivatives in 3D \n"); FILE *FilePressTot; FILE *FiledPdTIsingPlusNoIsing; FILE *FiledPdmuBIsingPlusNoIsing; FILE *Filed2PdT2IsingPlusNoIsing; FILE *Filed2PdmuB2IsingPlusNoIsing; FILE *Filed2PdTdmuBIsingPlusNoIsing; if(print){ FilePressTot = fopen(namePressIsingPlusNoIsing3D, "w"); FiledPdTIsingPlusNoIsing=fopen(namedPdTIsingPlusNoIsing3D,"w"); FiledPdmuBIsingPlusNoIsing=fopen(namedPdmuBIsingPlusNoIsing3D,"w"); Filed2PdT2IsingPlusNoIsing=fopen(named2PdT2IsingPlusNoIsing3D,"w"); Filed2PdmuB2IsingPlusNoIsing=fopen(named2PdmuB2IsingPlusNoIsing3D,"w"); Filed2PdTdmuBIsingPlusNoIsing=fopen(named2PdTdmuBIsingPlusNoIsing3D,"w"); } for (i=lowT; i<=highT; i++) for(j=0;j<=highMU; j++){ Tval = (double) i; muBval = (double) j; PressTotMat[i][j] = PressIsingMat[i][j] + PressNoIsingFilterMat[i][j]; dPressTotdTMat[i][j] = dPressIsingdTMat[i][j] + dPressNoIsingFilterdTMat[i][j]; dPressTotdmuBMat[i][j] = dPressIsingdmuBMat[i][j] + dPressNoIsingFilterdmuBMat[i][j]; d2PressTotdT2Mat[i][j] = d2PressIsingdT2Mat[i][j] + d2PressNoIsingFilterdT2Mat[i][j]; d2PressTotdmuB2Mat[i][j] = d2PressIsingdmuB2Mat[i][j] + d2PressNoIsingFilterdmuB2Mat[i][j]; d2PressTotdTdmuBMat[i][j] = d2PressIsingdTdmuBMat[i][j] + d2PressNoIsingFilterdTdmuBMat[i][j]; if(print){ fprintf(FilePressTot,"%3.16f %3.1f %12.16f \n", muBval, Tval, PressTotMat[i][j]); fprintf(FiledPdTIsingPlusNoIsing,"%3.1f %3.1f %12.16f\n", muBval,Tval,dPressTotdTMat[i][j]); fprintf(FiledPdmuBIsingPlusNoIsing,"%3.1f %3.1f %12.16f\n", muBval,Tval,dPressTotdmuBMat[i][j]); fprintf(Filed2PdT2IsingPlusNoIsing,"%3.1f %3.1f %12.16f\n", muBval,Tval,d2PressTotdT2Mat[i][j]); fprintf(Filed2PdmuB2IsingPlusNoIsing,"%3.1f %3.1f %12.16f\n", muBval,Tval,d2PressTotdmuB2Mat[i][j]); fprintf(Filed2PdTdmuBIsingPlusNoIsing,"%3.1f %3.1f %12.16f\n", muBval,Tval,d2PressTotdTdmuBMat[i][j]); } } if(print){ fclose(FilePressTot); fclose(FiledPdTIsingPlusNoIsing); fclose(FiledPdmuBIsingPlusNoIsing); fclose(Filed2PdT2IsingPlusNoIsing); fclose(Filed2PdmuB2IsingPlusNoIsing); fclose(Filed2PdTdmuBIsingPlusNoIsing); } } /*}}}*/ void merge_HRG() /*{{{*/ { /* Now, the smooth joining with the HRG pressure starts. * Import HRG pressure and store. */ fprintf(stderr,"Importing HRG Pressure \n"); FILE * FilePressHRG; if (!strange) FilePressHRG=fopen(HRG_press,"r"); else FilePressHRG=fopen(HRG_press_SN,"r"); if (FilePressHRG==NULL) err(1, "Failed to open HRG Pressure.\n"); for(i=0, x2int=0;fscanf(FilePressHRG,"%lf %lf %lf\n",&xIn1,&xIn2,&xIn3) !=EOF;i++){ x1int = (i % 817) + 5; PressHRGMat[x1int][x2int] = xIn3*pow(x1int,4); if(x1int == 821) x2int++; } fclose(FilePressHRG); /* Calculated derivatives of the HRG pressure */ /* Wrt T */ deriv_matrix(PressHRGMat,dPressHRGdTMat,1,lowT,highT,0,highMU,0); deriv_matrix(dPressHRGdTMat,d2PressHRGdT2Mat,1,lowT,highT,0,highMU,0); /* Wrt muB */ deriv_matrix(PressHRGMat,dPressHRGdmuBMat,2,lowT,highT,0,highMU,0); deriv_matrix(dPressHRGdmuBMat,d2PressHRGdmuB2Mat,2,lowT,highT,0,highMU,1); /* Wrt T and muB */ deriv_matrix(dPressHRGdTMat,d2PressHRGdTdmuBMat,2,lowT,highT,0,highMU,0); /* Final pressure, joined with the HRG one is calculated, * stored and exported. The parameter deltaT for merging with * HRG is also set here. */ fprintf(stderr,"Merging with HRG data.\n"); /* Merging with HRG data. */ FILE *FilePressTotHRG; FILE *FiledPdTTotHRG; FILE *FiledPdmuBTotHRG; FILE *Filed2PdT2TotHRG; FILE *Filed2PdmuB2TotHRG; FILE *Filed2PdTdmuBTotHRG; if (print){ FilePressTotHRG = fopen(namePressTotHRG3D, "w"); FiledPdTTotHRG = fopen(namedPdTTotHRG3D,"w"); FiledPdmuBTotHRG = fopen(namedPdmuBTotHRG3D,"w"); Filed2PdT2TotHRG = fopen(named2PdT2TotHRG3D,"w"); Filed2PdmuB2TotHRG = fopen(named2PdmuB2TotHRG3D,"w"); Filed2PdTdmuBTotHRG = fopen(named2PdTdmuBTotHRG3D,"w"); } // Set delta T deltaT = 17.0; /* The actual merging */ for (i=lowT; i<=highT; i++) for(j=0;j<=highMU; j++){ Tval = (double) i; muBval = (double) j; Targum = (Tval - (T0 + kappa/T0*muBval*muBval - 23.0))/deltaT; if (Targum>=4.5) PressTotHRGMat[i][j] = PressTotMat[i][j]; else if (Targum<=-4.5) PressTotHRGMat[i][j] = PressHRGMat[i][j]; else PressTotHRGMat[i][j] = PressTotMat[i][j]*0.5*(1.0 + tanh(Targum)) + PressHRGMat[i][j]*0.5*(1.0 - tanh(Targum)); if(Targum >= 4.5) dPressTotHRGdTMat[i][j] = dPressTotdTMat[i][j]; else if(Targum <= -4.5) dPressTotHRGdTMat[i][j] = dPressHRGdTMat[i][j]; else dPressTotHRGdTMat[i][j] = dPressTotdTMat[i][j]*0.5*(1.0 + tanh(Targum)) + dPressHRGdTMat[i][j]*0.5*(1.0 - tanh(Targum)) + PressTotMat[i][j]*0.5/deltaT*pow(cosh(Targum),-2) - PressHRGMat[i][j]*0.5/deltaT*pow(cosh(Targum),-2); if(Targum >= 4.5) dPressTotHRGdmuBMat[i][j] = dPressTotdmuBMat[i][j]; else if(Targum <= -4.5) dPressTotHRGdmuBMat[i][j] = dPressHRGdmuBMat[i][j]; else dPressTotHRGdmuBMat[i][j] = dPressTotdmuBMat[i][j]*0.5*(1.0 + tanh(Targum)) + dPressHRGdmuBMat[i][j]*0.5*(1.0 - tanh(Targum)) - PressTotMat[i][j]*0.5*pow(cosh(Targum),-2)*(2*kappa/T0*muBval)/deltaT + PressHRGMat[i][j]*0.5*pow(cosh(Targum),-2)*(2*kappa/T0*muBval)/deltaT; if(Targum >= 4.5) d2PressTotHRGdT2Mat[i][j] = d2PressTotdT2Mat[i][j]; if(Targum <= -4.5) d2PressTotHRGdT2Mat[i][j] = d2PressHRGdT2Mat[i][j]; else d2PressTotHRGdT2Mat[i][j] = d2PressTotdT2Mat[i][j]*0.5*(1.0 + tanh(Targum)) + d2PressHRGdT2Mat[i][j]*0.5*(1.0 - tanh(Targum)) + dPressTotdTMat[i][j]/deltaT*pow(cosh(Targum),-2) - dPressHRGdTMat[i][j]/deltaT*pow(cosh(Targum),-2) - PressTotMat[i][j]*pow(cosh(Targum),-2)*tanh(Targum)/pow(deltaT,2) + PressHRGMat[i][j]*pow(cosh(Targum),-2)*tanh(Targum)/pow(deltaT,2); if(Targum >= 4.5) d2PressTotHRGdmuB2Mat[i][j] = d2PressTotdmuB2Mat[i][j]; if(Targum <= -4.5) d2PressTotHRGdmuB2Mat[i][j] = d2PressHRGdmuB2Mat[i][j]; else d2PressTotHRGdmuB2Mat[i][j] = d2PressTotdmuB2Mat[i][j]*0.5*(1.0 + tanh(Targum)) + d2PressHRGdmuB2Mat[i][j]*0.5*(1.0 - tanh(Targum)) - dPressTotdmuBMat[i][j]*pow(cosh(Targum),-2)*(2*kappa/T0*muBval)/deltaT + dPressHRGdmuBMat[i][j]*pow(cosh(Targum),-2)*(2*kappa/T0*muBval)/deltaT - PressTotMat[i][j]*0.5*pow(cosh(Targum),-2) *(2*tanh(Targum)*(2*kappa/T0*muBval)/deltaT*(2*kappa/T0*muBval)/deltaT + 2*kappa/T0/deltaT) + PressHRGMat[i][j]*0.5*pow(cosh(Targum),-2) *(2*tanh(Targum)*(2*kappa/T0*muBval)/deltaT*(2*kappa/T0*muBval)/deltaT + 2*kappa/T0/deltaT); if(Targum >= 4.5) d2PressTotHRGdTdmuBMat[i][j] = d2PressTotdTdmuBMat[i][j]; if(Targum <= -4.5) d2PressTotHRGdTdmuBMat[i][j] = d2PressHRGdTdmuBMat[i][j]; else d2PressTotHRGdTdmuBMat[i][j] = d2PressTotdTdmuBMat[i][j]*0.5*(1.0 + tanh(Targum)) + d2PressHRGdTdmuBMat[i][j]*0.5*(1.0 - tanh(Targum)) + dPressTotdmuBMat[i][j]*0.5/deltaT*pow(cosh(Targum),-2) - dPressHRGdmuBMat[i][j]*0.5/deltaT*pow(cosh(Targum),-2) - dPressTotdTMat[i][j]*0.5/deltaT *(2*kappa/T0*muBval)*pow(cosh(Targum),-2) + dPressHRGdTMat[i][j]*0.5/deltaT *(2*kappa/T0*muBval)*pow(cosh(Targum),-2) + PressTotMat[i][j]*pow(cosh(Targum),-2)/pow(deltaT,2) *tanh(Targum)*(2*kappa/T0*muBval) - PressHRGMat[i][j]*pow(cosh(Targum),-2)/pow(deltaT,2) *tanh(Targum)*(2*kappa/T0*muBval); /* Output is disabled now */ if (print){ fprintf(FilePressTotHRG,"%3.16f %3.1f %12.16f \n", muBval, Tval, PressTotHRGMat[i][j]); fprintf(FiledPdTTotHRG,"%3.16f %3.1f %12.16f \n", muBval, Tval, dPressTotHRGdTMat[i][j]); fprintf(FiledPdmuBTotHRG,"%3.16f %3.1f %12.16f \n", muBval, Tval, dPressTotHRGdmuBMat[i][j]); fprintf(Filed2PdT2TotHRG,"%3.16f %3.1f %12.16f \n", muBval, Tval, d2PressTotHRGdT2Mat[i][j]); fprintf(Filed2PdmuB2TotHRG,"%3.16f %3.1f %12.16f \n", muBval, Tval, d2PressTotHRGdmuB2Mat[i][j]); fprintf(Filed2PdTdmuBTotHRG,"%3.16f %3.1f %12.16f \n", muBval, Tval, d2PressTotHRGdTdmuBMat[i][j]); } } if (print){ fclose(FilePressTotHRG); fclose(FiledPdTTotHRG); fclose(FiledPdmuBTotHRG); fclose(Filed2PdT2TotHRG); fclose(Filed2PdmuB2TotHRG); fclose(Filed2PdTdmuBTotHRG); } fprintf(stderr,"Merged with HRG.\n"); } /*}}}*/ void out_thermodynamics() /*{{{*/ { /* Now all the derivatives have been merged with the HRG, we can finish with * the thermodynamics and export the quantities we want, in particular we * will normalize with suitable powers of the temperature to obtain * dimensionless quantities.*/ fprintf(stderr,"Merging with HRG complete. \n" "Calculating thermodynamics quantities.\n"); /* Calculate thermodynamic quantities */ FILE * FilePressFinal = fopen(namePressFinal3D, "w"); FILE * FileEntrFinal = fopen(nameEntrFinal3D, "w"); FILE * FileBarDensFinal = fopen(nameBarDensFinal3D, "w"); FILE * FileEnerDensFinal = fopen(nameEnerDensFinal3D, "w"); FILE * FileSpSoundFinal = fopen(nameSpsoundFinal3D, "w"); FILE * FileChi2Final = fopen(nameChi2Final3D, "w"); FILE * FileCorrLengthFinal = fopen(nameCorrLengthFinal3D, "w"); for (i=lowT_out; i<=highT_out; i++) for(j=0;j<=highMU_out; j++){ Tval = (double) i; muBval = (double) j; PressFinalMat[i][j] = PressTotHRGMat[i][j]/pow(Tval,4); EntropyFinalMat[i][j] = dPressTotHRGdTMat[i][j]/pow(Tval,3); BarDensityFinalMat[i][j] = dPressTotHRGdmuBMat[i][j]/pow(Tval,3); EnerDensityFinalMat[i][j] = (dPressTotHRGdTMat[i][j]*Tval - PressTotHRGMat[i][j] + muBval*dPressTotHRGdmuBMat[i][j])/pow(Tval,4); SpSoundFinalMat[i][j] = (dPressTotHRGdmuBMat[i][j]*dPressTotHRGdmuBMat[i][j] *d2PressTotHRGdT2Mat[i][j] - 2.0*dPressTotHRGdTMat[i][j]*dPressTotHRGdmuBMat[i][j] *d2PressTotHRGdTdmuBMat[i][j] + dPressTotHRGdTMat[i][j]*dPressTotHRGdTMat[i][j] *d2PressTotHRGdmuB2Mat[i][j]) /(dPressTotHRGdTMat[i][j]*Tval + muBval*dPressTotHRGdmuBMat[i][j]) /(d2PressTotHRGdT2Mat[i][j]*d2PressTotHRGdmuB2Mat[i][j] -d2PressTotHRGdTdmuBMat[i][j]*d2PressTotHRGdTdmuBMat[i][j]); Chi2FinalMat[i][j] = d2PressTotHRGdmuB2Mat[i][j]/pow(Tval,2); fprintf(FilePressFinal,"%3.16f %3.1f %12.16f \n", muBval, Tval, PressFinalMat[i][j]); fprintf(FileEntrFinal,"%3.16f %3.1f %12.16f \n", muBval, Tval, EntropyFinalMat[i][j]); fprintf(FileBarDensFinal,"%3.16f %3.1f %12.16f \n", muBval, Tval, BarDensityFinalMat[i][j]); fprintf(FileEnerDensFinal,"%3.16f %3.1f %12.16f \n", muBval, Tval, EnerDensityFinalMat[i][j]); fprintf(FileSpSoundFinal,"%3.16f %3.1f %12.16f \n", muBval, Tval, SpSoundFinalMat[i][j]); fprintf(FileChi2Final,"%3.16f %3.1f %12.16f \n", muBval, Tval, Chi2FinalMat[i][j]); fprintf(FileCorrLengthFinal,"%3.16f %3.1f %12.16f \n", muBval, Tval, CorrLengthMergedMat[i][j]); } fclose(FilePressFinal); fclose(FileEntrFinal); fclose(FileBarDensFinal); fclose(FileEnerDensFinal); fclose(FileSpSoundFinal); fclose(FileChi2Final); fclose(FileCorrLengthFinal); } /*}}}*/ void free_alloc() /*{{{*/ { fprintf(stderr,"Free memory allocation.\n"); /* Remove coordinate file */ remove(nameCoords); /* Vectors for root finding */ free_vector(x,1,N); free_vector(f,1,N); /* Jacobian */ free_matrix(JJ,1,N,1,N); /* Tensor for coordinates*/ free_f3tensor(Coords,lowT,highT,0,2*highMU,1,N); /* Vectors */ free_vector(Chi0LatVec,lowT,highT); free_vector(Chi2LatVec,lowT,highT); free_vector(Chi4LatVec,lowT,highT); free_vector(Chi0IsingVec,lowT,highT); free_vector(Chi2IsingVec,lowT,highT); free_vector(Chi4IsingVec,lowT,highT); free_vector(Chi0NoIsingVec,lowT,highT); free_vector(Chi2NoIsingVec,lowT,highT); free_vector(Chi4NoIsingVec,lowT,highT); /* For LAT-only mode */ free_matrix(PressLATonlyMat,lowT,highT,0,highMU); free_matrix(PressLATonlyFilterMat,lowT,highT,0,highMU); free_matrix(dPressLATonlydTMat,lowT,highT,0,highMU); free_matrix(dPressLATonlydmuBMat,lowT,highT,0,highMU); free_matrix(d2PressLATonlydT2Mat,lowT,highT,0,highMU); free_matrix(d2PressLATonlydmuB2Mat,lowT,highT,0,highMU); free_matrix(d2PressLATonlydTdmuBMat,lowT,highT,0,highMU); /* For LAT-only mode, normalized */ free_matrix(PressLATonlyNormMat,lowT,highT,0,highMU); free_matrix(EntropyLATonlyNormMat,lowT,highT,0,highMU); free_matrix(BarDensityLATonlyNormMat,lowT,highT,0,highMU); free_matrix(EnerDensityLATonlyNormMat,lowT,highT,0,highMU); free_matrix(SpSoundLATonlyNormMat,lowT,highT,0,highMU); free_matrix(Chi2LATonlyNormMat,lowT,highT,0,highMU); /* Ising */ free_matrix(PressNoIsingMat,lowT,highT,0,highMU); free_matrix(dPressNoIsingdTMat,lowT,highT,0,highMU); free_matrix(dPressNoIsingdmuBMat,lowT,highT,0,highMU); free_matrix(d2PressNoIsingdT2Mat,lowT,highT,0,highMU); free_matrix(d2PressNoIsingdmuB2Mat,lowT,highT,0,highMU); free_matrix(d2PressNoIsingdTdmuBMat,lowT,highT,0,highMU); /* No-Ising filtered */ free_matrix(PressNoIsingFilterMat,lowT,highT,0,highMU); free_matrix(dPressNoIsingFilterdTMat,lowT,highT,0,highMU); free_matrix(dPressNoIsingFilterdmuBMat,lowT,highT,0,highMU); free_matrix(d2PressNoIsingFilterdT2Mat,lowT,highT,0,highMU); free_matrix(d2PressNoIsingFilterdmuB2Mat,lowT,highT,0,highMU); free_matrix(d2PressNoIsingFilterdTdmuBMat,lowT,highT,0,highMU); /* Ising */ free_matrix(PressIsingMat,lowT,highT,0,highMU); free_matrix(dPressIsingdTMat,lowT,highT,0,highMU); free_matrix(dPressIsingdmuBMat,lowT,highT,0,highMU); free_matrix(d2PressIsingdT2Mat,lowT,highT,0,highMU); free_matrix(d2PressIsingdmuB2Mat,lowT,highT,0,highMU); free_matrix(d2PressIsingdTdmuBMat,lowT,highT,0,highMU); /* Total */ free_matrix(PressTotMat,lowT,highT,0,highMU); free_matrix(dPressTotdTMat,lowT,highT,0,highMU); free_matrix(dPressTotdmuBMat,lowT,highT,0,highMU); free_matrix(d2PressTotdT2Mat,lowT,highT,0,highMU); free_matrix(d2PressTotdmuB2Mat,lowT,highT,0,highMU); free_matrix(d2PressTotdTdmuBMat,lowT,highT,0,highMU); /* HRG */ free_matrix(PressHRGMat,lowT,highT,0,highMU); free_matrix(dPressHRGdTMat,lowT,highT,0,highMU); free_matrix(dPressHRGdmuBMat,lowT,highT,0,highMU); free_matrix(d2PressHRGdT2Mat,lowT,highT,0,highMU); free_matrix(d2PressHRGdmuB2Mat,lowT,highT,0,highMU); free_matrix(d2PressHRGdTdmuBMat,lowT,highT,0,highMU); /* Total+HRG */ free_matrix(PressTotHRGMat,lowT,highT,0,highMU); free_matrix(dPressTotHRGdTMat,lowT,highT,0,highMU); free_matrix(dPressTotHRGdmuBMat,lowT,highT,0,highMU); free_matrix(d2PressTotHRGdT2Mat,lowT,highT,0,highMU); free_matrix(d2PressTotHRGdmuB2Mat,lowT,highT,0,highMU); free_matrix(d2PressTotHRGdTdmuBMat,lowT,highT,0,highMU); /* Final output */ free_matrix(PressFinalMat,lowT,highT,0,highMU); free_matrix(EntropyFinalMat,lowT,highT,0,highMU); free_matrix(BarDensityFinalMat,lowT,highT,0,highMU); free_matrix(EnerDensityFinalMat,lowT,highT,0,highMU); free_matrix(SpSoundFinalMat,lowT,highT,0,highMU); free_matrix(Chi2FinalMat,lowT,highT,0,highMU); /* Correlation length */ free_matrix(CorrLengthEpsExpMat,lowT,highT,0,highMU); free_matrix(CorrLengthAsymptMat,lowT,highT,0,highMU); free_matrix(CorrLengthMergedMat,lowT,highT,0,highMU); } /*}}}*/ int get_options(int argc, char *argv[]) /*{{{*/ { int o; while ((o=getopt(argc, argv, "r:R:vpLSh")) != -1) { switch (o) { case 'v': verbose++; break; case 'p': print++; break; case 'S': strange++; break; case 'L': lattice++; break; case 'r': sscanf(optarg,"%d%*[:,-]%d",&lowT_out,&highT_out); break; case 'R': sscanf(optarg,"%d%*[:,-]%d",&lowMU_out,&highMU_out); break; case 'h': help(); exit(EXIT_FAILURE); default: fprintf(stderr,"Run help [-h] for help.\n"); exit(EXIT_FAILURE); } } if (!verbose) if(freopen("/dev/null","w",stderr)==NULL){ printf("Could not suppress stderr. Exiting. \n"); exit(EXIT_FAILURE); } if (lowT_out > highT_out || lowMU_out > highMU_out){ printf("Wrong ordering in required output range!. Exiting. \n"); exit(EXIT_FAILURE); } if (lowT_out < 30 || highT_out > 800 || lowMU_out < 0 || highMU_out > 600){ printf("Error in setting the output range. \nYou cannot extend the" " range beyond:\n" " T = 30-800 MeV\n" " mu = 0-600 MeV\n" "Exiting. \n"); exit(EXIT_FAILURE); } return 0; } /*}}}*/ // The main int main(int argc, char *argv[]) { char buff[FILENAME_MAX]; get_options(argc,argv); allocate(); /* allocations for vectors and matrices */ /* Assign the name of the main folder where the program lives and * the files we wish to import are located. */ getcwd(buff,FILENAME_MAX); /* store current working dir in buf */ read_param(argv[optind]); /* read parameter file */ if (!strange) read_lattice_data(lat_data); /* import lattice coefficients */ else read_lattice_data(lat_data_SN); // Move into folder for output chdir("output"); if (lattice){ do_lattice(); /* if in lattice mode, run it */ return 0; } write_filenames(); /* determine file names from parameter choice */ // Create folder with name depending on parameters, and move to the folder. mkdir(nameFolder, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH); chdir(nameFolder); calc_jacobian(); /* calculate Jacobian of (r,h)->(T,mu) map */ make_coords(); /* generate coordinates */ make_Ising(); /* generate Ising fluctuations */ merge_CorrLength(); /* Merge correlation legth expressions */ make_nonIsing(); /* determine non-Ising coefficients */ merge_Ising_nonIsing(); /* merge Ising and non-Ising */ merge_HRG(); /* merge with HRG */ out_thermodynamics(); /* output thermodynamic quantities */ remove(nameCoords); /* remove coordinate file */ free_alloc(); /* free allocations */ return 0; } #undef NRANSI
43.813502
176
0.660876
1c377add9ce439e39e3fd6b992044c2b2ed855c8
217
h
C
util.h
moefh/win-remote-control
ae249d60c549894ab2fb5c368a19e93c30292a0c
[ "MIT" ]
null
null
null
util.h
moefh/win-remote-control
ae249d60c549894ab2fb5c368a19e93c30292a0c
[ "MIT" ]
null
null
null
util.h
moefh/win-remote-control
ae249d60c549894ab2fb5c368a19e93c30292a0c
[ "MIT" ]
null
null
null
#ifndef UTIL_H_FILE #define UTIL_H_FILE //#define DEBUG_MSG(...) debug_msg(__VA_ARGS__) #define DEBUG_MSG(...) void debug_msg(const char *fmt, ...); void display_msg(const char *fmt, ...); #endif /* UTIL_H_FILE */
19.727273
47
0.700461
5af269e6d6c3f232f301121999cb2d4f3c1d8a4d
1,630
c
C
libft/ft_atoi.c
k-allard/raycasting_game
d8499af610477dbd16a0d16ef81dbc73d5897013
[ "MIT" ]
null
null
null
libft/ft_atoi.c
k-allard/raycasting_game
d8499af610477dbd16a0d16ef81dbc73d5897013
[ "MIT" ]
null
null
null
libft/ft_atoi.c
k-allard/raycasting_game
d8499af610477dbd16a0d16ef81dbc73d5897013
[ "MIT" ]
null
null
null
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_atoi.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: kallard <kallard@student.21-school.ru> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/04/28 06:54:54 by kallard #+# #+# */ /* Updated: 2020/09/28 13:22:50 by kallard ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" /* ** Converts ASCII string to integer. ** Is intended to imitate the behaviour of original atoi, ** which has undef behavior if the value of the result cannot be represented. */ int ft_atoi(char *str) { unsigned long long result; int length_max; int sign; int i; result = 0; length_max = 19; sign = 1; i = 0; while (ft_isspace(str[i])) i++; if (str[i] == '-' || str[i] == '+') sign = (str[i++] == '-') ? -1 : 1; while (str[i] >= '0' && str[i] <= '9') { result = result * 10 + str[i++] - '0'; if (length_max-- < 0) return ((sign == 1) ? -1 : 0); if (result >= LLMAX && sign == 1) return (-1); if (result > LLMAX && sign == -1) return (0); } return (sign * result); }
33.958333
80
0.309816
e3ef235bb33a4721cd03b65d7a75b9817a4ce33e
4,315
h
C
FryEngine/src/FryEngine/Math/Matrix.h
Schtekt/FryEngine
eb36df4d0b42ca5a0549a130709c567e88b6a826
[ "MIT" ]
null
null
null
FryEngine/src/FryEngine/Math/Matrix.h
Schtekt/FryEngine
eb36df4d0b42ca5a0549a130709c567e88b6a826
[ "MIT" ]
null
null
null
FryEngine/src/FryEngine/Math/Matrix.h
Schtekt/FryEngine
eb36df4d0b42ca5a0549a130709c567e88b6a826
[ "MIT" ]
null
null
null
#pragma once #include <initializer_list> #include "Vector.h" template<unsigned int M, unsigned int N> struct Matrix { double nums[M * N] = {0}; double GetElement(unsigned int y, unsigned int x) const; bool SetElement(unsigned int y, unsigned int x, double val); Matrix<M, N> operator+(const Matrix<M, N>& other) const; Matrix<M, N> operator-(const Matrix<M, N>& other) const; template<unsigned int P> Matrix<M,P> operator*(const Matrix<N, P>& other) const; Matrix<M, N>& operator+=(const Matrix<M, N>& other); Matrix<M, N>& operator-=(const Matrix<M, N>& other); bool operator==(const Matrix<M,N>& other); template<unsigned int P, unsigned int O> bool operator==(const Matrix<P,O>& other); Matrix<N,M> Transpose(); Vector<N> operator*(const Vector<N>& other) const; static Matrix<M,N> IdentityMatrix(); }; template<unsigned int M, unsigned int N> double Matrix<M, N>::GetElement(unsigned int y, unsigned int x) const { return nums[y * N + x]; } template<unsigned int M, unsigned int N> bool Matrix<M, N>::SetElement(unsigned int y, unsigned int x, double val) { if(y >= M || x >= N) { return false; } nums[y * N + x] = val; return true; } template<unsigned int M, unsigned int N> Matrix<M, N> Matrix<M,N>::operator+(const Matrix<M, N>& other) const { Matrix<M, N> res; unsigned int numElements = M*N; for(unsigned int i = 0; i < numElements; i++) { res.nums[i] = nums[i] + other.nums[i]; } return res; } template<unsigned int M, unsigned int N> Matrix<M, N> Matrix<M,N>::operator-(const Matrix<M, N>& other) const { Matrix<M, N> res; unsigned int numElements = M*N; for(unsigned int i = 0; i < numElements; i++) { res.nums[i] = nums[i] - other.nums[i]; } return res; } template<unsigned int M, unsigned int N> template<unsigned int P> Matrix<M,P> Matrix<M,N>::operator*(const Matrix<N, P>& other) const { Matrix<M,P> res; for(unsigned int y = 0; y < P; y++) { for(unsigned int x = 0; x < M; x++) { res.SetElement(y, x, 0); for(unsigned int k = 0; k < N; k++) { res.SetElement(y, x, (res.GetElement(y, x) + GetElement(y,k) * other.GetElement(k,x))); } } } return res; } template<unsigned int M, unsigned int N> Matrix<M, N>& Matrix<M,N>::operator+=(const Matrix<M, N>& other) { unsigned int numElements = M*N; for(unsigned int i = 0; i < numElements; i++) { nums[i] = nums[i] + other.nums[i]; } return *this; } template<unsigned int M, unsigned int N> Matrix<M, N>& Matrix<M,N>::operator-=(const Matrix<M, N>& other) { unsigned int numElements = M*N; for(unsigned int i = 0; i < numElements; i++) { nums[i] = nums[i] - other.nums[i]; } return *this; } template<unsigned int M, unsigned int N> bool Matrix<M,N>::operator==(const Matrix<M,N>& other) { unsigned int size = M*N; for(unsigned int i = 0; i < size; i++) { if(nums[i] != other.nums[i]) { return false; } } return true; } template<unsigned int M, unsigned int N> template<unsigned int P, unsigned int O> bool Matrix<M, N>::operator==(const Matrix<P,O>& other) { if(P != M || O != N) { return false; } return *this == other; } template<unsigned int M, unsigned int N> Matrix<N,M> Matrix<M,N>::Transpose() { Matrix<N, M> res; for(unsigned int y = 0; y < M; y++) { for(unsigned int x = 0; x < N; x++) { res.nums[x * M + y] = nums[y * N + x]; } } return res; } template<unsigned int M, unsigned int N> Vector<N> Matrix<M,N>::operator*(const Vector<N>& other) const { Vector<N> res; for(unsigned int y = 0; y < N; y++) { res[y] = 0; for(unsigned int x = 0; x < M; x++) { res[y] += GetElement(y,x) * other[x]; } } return res; } template<unsigned int M, unsigned int N> Matrix<M,N> Matrix<M,N>::IdentityMatrix() { Matrix<M,N> res{0}; for(int i = 0; i < M*N; i++) { if(i / M == i % N) { res.nums[i] = 1; } } return res; }
22.591623
104
0.555272
ee126b5510c15f9ca59cfc85d6746a705cd4bf77
666
c
C
gcc-gcc-7_3_0-release/gcc/testsuite/gcc.target/x86_64/abi/avx512f/test_m512_returning.c
best08618/asylo
5a520a9f5c461ede0f32acc284017b737a43898c
[ "Apache-2.0" ]
7
2020-05-02T17:34:05.000Z
2021-10-17T10:15:18.000Z
gcc-gcc-7_3_0-release/gcc/testsuite/gcc.target/x86_64/abi/avx512f/test_m512_returning.c
best08618/asylo
5a520a9f5c461ede0f32acc284017b737a43898c
[ "Apache-2.0" ]
null
null
null
gcc-gcc-7_3_0-release/gcc/testsuite/gcc.target/x86_64/abi/avx512f/test_m512_returning.c
best08618/asylo
5a520a9f5c461ede0f32acc284017b737a43898c
[ "Apache-2.0" ]
2
2020-07-27T00:22:36.000Z
2021-04-01T09:41:02.000Z
#include <stdio.h> #include "avx512f-check.h" #include "args.h" struct IntegerRegisters iregs; struct FloatRegisters fregs; unsigned int num_iregs, num_fregs; __m512 fun_test_returning___m512 (void) { volatile_var++; return (__m512){73,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; } __m512 test_512; static void avx512f_test (void) { unsigned failed = 0; ZMM_T zmmt1, zmmt2; clear_struct_registers; test_512 = (__m512){73,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; zmmt1._m512[0] = test_512; zmmt2._m512[0] = WRAP_RET (fun_test_returning___m512)(); if (memcmp (&zmmt1, &zmmt2, sizeof (zmmt2)) != 0) printf ("fail m512\n"), failed++; if (failed) abort (); }
20.181818
58
0.678679
e1743e5d5b3fd496c6f5c832649b918c1a88baa0
2,147
h
C
Programs/SceneViewer/Sources/UIScreens/PerformanceResultsScreen.h
stinvi/dava.engine
2b396ca49cdf10cdc98ad8a9ffcf7768a05e285e
[ "BSD-3-Clause" ]
26
2018-09-03T08:48:22.000Z
2022-02-14T05:14:50.000Z
Programs/SceneViewer/Sources/UIScreens/PerformanceResultsScreen.h
ANHELL-blitz/dava.engine
ed83624326f000866e29166c7f4cccfed1bb41d4
[ "BSD-3-Clause" ]
null
null
null
Programs/SceneViewer/Sources/UIScreens/PerformanceResultsScreen.h
ANHELL-blitz/dava.engine
ed83624326f000866e29166c7f4cccfed1bb41d4
[ "BSD-3-Clause" ]
45
2018-05-11T06:47:17.000Z
2022-02-03T11:30:55.000Z
#pragma once #ifdef WITH_SCENE_PERFORMANCE_TESTS #include "SceneViewerApp.h" #include "BaseScreen.h" #include "UIControls/Sector.h" #include <GridTest.h> class PerformanceResultsScreen : public BaseScreen { public: PerformanceResultsScreen(SceneViewerData& data); // UIScreen void LoadResources() override; void UnloadResources() override; // UIControl void Update(DAVA::float32 timeElapsed) override; private: void OnBackButton(BaseObject* caller, void* param, void* callerData); void OnSectorPressed(BaseObject* caller, void* param, void* callerData); void AddButtons(); void RemoveButtons(); void AddSectors(); void RemoveSectors(); void AddBackgroundMap(); void RemoveBackgroundMap(); void AddColorBoxes(); void RemoveColorBoxes(); void AddResultsText(); void RemoveResultsText(); void AddPreviewControls(); void RemovePreviewControls(); void SaveTexture(DAVA::Texture* screenshot); DAVA::float32 SceneDistanceToScreenDistance(DAVA::float32 distance); DAVA::Vector2 ScenePointToScreenPoint(DAVA::Vector3 scenePoint); SectorColor EvaluateSectorType(DAVA::float32 fps); void SetSamplePosition(DAVA::Scene* scene, const GridTestSample& sample); void SelectLowestFpsSector(); void SetSectorSelected(Sector*); private: SceneViewerData& data; DAVA::Camera* camera = nullptr; DAVA::Rect infoColumnRect; DAVA::Rect panoramaRect; DAVA::Vector<DAVA::ScopedPtr<Sector>> sectors; DAVA::UnorderedMap<Sector*, DAVA::uint32> sectorToSample; Sector* selectedSector = nullptr; DAVA::ScopedPtr<SectorColorBox> greenColorBox; DAVA::ScopedPtr<SectorColorBox> yellowColorBox; DAVA::ScopedPtr<SectorColorBox> redColorBox; DAVA::ScopedPtr<DAVA::UIStaticText> greenBoxText; DAVA::ScopedPtr<DAVA::UIStaticText> yellowBoxText; DAVA::ScopedPtr<DAVA::UIStaticText> redBoxText; DAVA::ScopedPtr<DAVA::UIStaticText> previewFpsText; DAVA::ScopedPtr<DAVA::UIStaticText> fpsResultsText; DAVA::ScopedPtr<DAVA::UI3DView> preview; DAVA::ScopedPtr<DAVA::UIButton> backButton; }; #endif
27.883117
77
0.734979
f6ec87e5725b80f1226ffebb2cc42caf3fc81854
487
c
C
exp/static_c/assorted_drafts/factorial.c
NMinhNguyen/wordsandbuttons
beba7f73c46f40790ad2482c2c0c04cfa5f626a4
[ "Unlicense" ]
367
2018-01-29T17:45:00.000Z
2022-03-08T03:50:52.000Z
exp/static_c/assorted_drafts/factorial.c
NMinhNguyen/wordsandbuttons
beba7f73c46f40790ad2482c2c0c04cfa5f626a4
[ "Unlicense" ]
9
2017-12-21T16:48:08.000Z
2021-01-23T17:20:20.000Z
exp/static_c/assorted_drafts/factorial.c
NMinhNguyen/wordsandbuttons
beba7f73c46f40790ad2482c2c0c04cfa5f626a4
[ "Unlicense" ]
20
2018-02-18T11:52:36.000Z
2021-11-22T09:46:53.000Z
#define LOOP_0(ID, body) ID = 0; (body);} #define LOOP_1(ID, body) ID = 1; (body); LOOP_0(ID, body) #define LOOP_2(ID, body) ID = 2; (body); LOOP_1(ID, body) #define LOOP_3(ID, body) ID = 3; (body); LOOP_2(ID, body) #define LOOP_4(ID, body) ID = 4; (body); LOOP_3(ID, body) #define LOOP_TO_0(ID, I, body) {int ID; LOOP_##I(ID, body) #define FACTORIAL(X, Y) Y = 1; LOOP_TO_0(i, X , Y *= (i+(i==0))); #include "stdio.h" int main(){ int y; FACTORIAL(4, y); printf("%d\n", y); }
25.631579
65
0.595483
0cab51c29789b90853ee2ee79364aa3ab2a42798
556
h
C
ps4/include/config.h
ps4dev/elfldr
4e712747d3a3e2dc004554686b5e416653d97400
[ "Unlicense" ]
27
2016-01-05T08:16:19.000Z
2017-04-24T14:40:10.000Z
ps4/include/config.h
hitodama/elfldr
4e712747d3a3e2dc004554686b5e416653d97400
[ "Unlicense" ]
7
2015-12-26T11:02:35.000Z
2016-04-12T18:40:45.000Z
ps4/include/config.h
ps4dev/elfldr
4e712747d3a3e2dc004554686b5e416653d97400
[ "Unlicense" ]
9
2016-01-03T22:34:21.000Z
2017-04-24T14:38:03.000Z
enum{ MemoryPlain = 0, MemoryEmulate = 1 }; enum{ ElfInputFile = 0, ElfInputServer = 1 }; enum{ ThreadingNone = 0, Threading = 1 }; enum{ DebugOff = 0, DebugOn = 1 }; enum{ StandardIORedirectNone = 0, StandardIORedirectWait = 1, StandardIORedirectLazy = 2 }; typedef struct ElfLoaderConfig { int elfInputMode; int memoryMode; int debugMode; int threadingMode; int standardIORedirectMode; char *inputFile; } ElfLoaderConfig; void configFromDefines(ElfLoaderConfig *config); void configFromArguments(ElfLoaderConfig *config, int argc, char **argv);
27.8
91
0.758993
91b3bfe9b4450d2e2e2d5b3ad4d838080d0f3020
1,419
h
C
Datalogger/uart-dma.h
stvnrhodes/calsol
d120f375b686bf979115c82b6db29ba5791c28c2
[ "Apache-2.0" ]
null
null
null
Datalogger/uart-dma.h
stvnrhodes/calsol
d120f375b686bf979115c82b6db29ba5791c28c2
[ "Apache-2.0" ]
null
null
null
Datalogger/uart-dma.h
stvnrhodes/calsol
d120f375b686bf979115c82b6db29ba5791c28c2
[ "Apache-2.0" ]
null
null
null
#include "types.h" #include "hardware.h" #ifndef _UART_DMA_H_ #define _UART_DMA_H_ /** * The UART baud rate, in bits/sec. The BRG is calculated at compile time from this number. */ #define UART_DMA_BAUD 1250000 // BRGH formula: ( Fcy / ( 4 * baud ) ) - 1 // BRG formula: ( Fcy / ( 16 * baud ) ) - 1 #if (((Fcy / 4) / UART_DMA_BAUD) - 1) < 255 #define UART_DMA_BRG (((Fcy / 4) / UART_DMA_BAUD) - 1) #define UART_DMA_BRGH 1 #else #define UART_DMA_BRG (((Fcy / 16) / UART_DMA_BAUD) - 1) #define UART_DMA_BRGH 0 #endif //TODO Add compile-time baud error percentage check #define UART_DMA_BUFFER_SIZE 40 #define UART_UMODEbits U2MODEbits #define UART_UBRG U2BRG #define UART_USTAbits U2STAbits #define UART_IRQSEL_VAL 0b0011111 #define UART_DMAPAD_VAL (uint16_t)&U2TXREG #define UART_DMACON DMA7CON #define UART_DMACONbits DMA7CONbits #define UART_DMAREQbits DMA7REQbits #define UART_DMASTA DMA7STA #define UART_DMAPAD DMA7PAD #define UART_DMACNT DMA7CNT #define UART_DMAInterrupt _DMA7Interrupt #define UART_DMAIF _DMA7IF #define UART_DMAIE _DMA7IE void UART_DMA_Init(); uint16_t UART_DMA_WriteAtomicS(char* string); uint16_t UART_DMA_WriteAtomic(char* data, uint16_t dataLen); void UART_DMA_WriteBlockingS(char* string); void UART_DMA_WriteBlocking(char* string, uint16_t dataLen); uint16_t UART_DMA_SendBlock(); #endif
27.823529
92
0.724454
91f2c2a1a7e66cb8f7a6fce641375f445dbccb0a
772
h
C
src/include/doft.h
danibt656/libjson
0fa7f0ce06b89a510b311823d049ec5c9c9399d3
[ "MIT" ]
null
null
null
src/include/doft.h
danibt656/libjson
0fa7f0ce06b89a510b311823d049ec5c9c9399d3
[ "MIT" ]
null
null
null
src/include/doft.h
danibt656/libjson
0fa7f0ce06b89a510b311823d049ec5c9c9399d3
[ "MIT" ]
null
null
null
#ifndef DOFT_H #define DOFT_H #include "doft_lexer.h" #include "doft_parser.h" #include "doft_visitor.h" typedef ast_t doft; typedef struct DOFT_ITERATOR_STRUCT { doft **values; doft *current; uint32_t index; uint32_t length; } doft_iterator; doft *doft_get_value(doft *data, const char *key); char* doft_get_string(doft* data, const char* key); int doft_get_int(doft* data, const char* key); float doft_get_float(doft* data, const char* key); float doft_get_number(doft* data, const char* key); doft_iterator iterate(doft *data); doft *doft_iterator_next(doft_iterator *iterator); unsigned int doft_is_list(doft *data); char *doft_string(doft *data); int doft_int(doft *data); float doft_float(doft *data); float doft_number(doft *data); #endif
21.444444
51
0.748705
1026ec1c3f52ddef1db0e0058b583ca01de02c53
1,179
h
C
headers/oneviewJSONParse.h
fallenpegasus/infrakit-instance-oneview
e97e764ea5d7821db47cc7c9dcf0be54fe1633b6
[ "Apache-2.0" ]
8
2017-03-04T00:23:20.000Z
2017-12-30T15:43:10.000Z
headers/oneviewJSONParse.h
fallenpegasus/infrakit-instance-oneview
e97e764ea5d7821db47cc7c9dcf0be54fe1633b6
[ "Apache-2.0" ]
3
2017-03-05T10:40:18.000Z
2017-03-20T15:09:42.000Z
headers/oneviewJSONParse.h
fallenpegasus/infrakit-instance-oneview
e97e764ea5d7821db47cc7c9dcf0be54fe1633b6
[ "Apache-2.0" ]
1
2021-02-16T00:24:04.000Z
2021-02-16T00:24:04.000Z
// oneviewJSONParse.h /* instance-infrakit-oneview - A Docker InfraKit plugin for HPE OneView * * Dan Finneran <finneran@hpe.com> * * (c) Copyright [2017] Hewlett Packard Enterprise Development LP; * * This software may be modified and distributed under the terms * of the Apache 2.0 license. See the LICENSE file for details. */ #ifndef oneviewJSONParse_h #define oneviewJSONParse_h #include <stdio.h> #include "oneview.h" // output types #define JSON_RAW 0 #define JSON_READABLE 1 // profileStatistic #define OV_PROFILE_STATISTIC_DIFF 0 // previous statistic - latest = difference #define OV_PROFILE_STATISTIC_CURR 1 // latest statistic is set in the profile array void ovParseMembers(char *rawJSON, char delimiter, char *fields[], int fieldCount); char *returnRawJSONFromObject(char* rawJSON, char *objectName); char *returnReadableJSONFromRaw(char *rawJSON); size_t returnJSONArraySize(char *rawJSON); char *returnJSONObjectAtIndex(size_t index, char *rawJSON); void ovParseArray(char *rawJSON, char *arrayName, char delimiter, char *fields[], int fieldCount); const char *returnStringfromJSON(char *rawJSON, char *field); #endif /* oneviewJSONParse_h */
29.475
98
0.772689
3cf27705ba4d3b332b9d1d95b0e3606bcbce0d5e
451
h
C
lib/common/OpenCvImage.h
sogorkis/wavelet-compressor
966b2ef3a750dfdb7cfbe482c60acb714a561bc2
[ "BSD-2-Clause-FreeBSD" ]
1
2015-03-13T09:43:07.000Z
2015-03-13T09:43:07.000Z
lib/common/OpenCvImage.h
sogorkis/wavelet-compressor
966b2ef3a750dfdb7cfbe482c60acb714a561bc2
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
lib/common/OpenCvImage.h
sogorkis/wavelet-compressor
966b2ef3a750dfdb7cfbe482c60acb714a561bc2
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
/* * This file is subject to the terms and conditions defined in * file 'LICENSE.txt', which is part of this source code package. */ #ifndef OPENCVIMAGE_H #define OPENCVIMAGE_H #include "Image.h" #include <opencv/cv.h> class OpenCvImage : public Image { public: OpenCvImage() {} OpenCvImage(IplImage *cvImage); virtual void init(int width, int height, int channelCount); IplImage * getIplImage(); }; #endif // OPENCVIMAGE_H
18.04
65
0.7051
56e03311f4b9beb08aef51eb79b136c74db3707a
9,358
h
C
include/secutils/credentials/cert.h
siemens/libsecutils
0e6aa6718f83987da4eab09a16f32423e3609a67
[ "Apache-2.0" ]
3
2021-08-22T17:56:07.000Z
2021-12-08T12:07:01.000Z
include/secutils/credentials/cert.h
siemens/libsecutils
0e6aa6718f83987da4eab09a16f32423e3609a67
[ "Apache-2.0" ]
9
2021-09-14T06:45:07.000Z
2022-01-31T10:25:52.000Z
include/secutils/credentials/cert.h
siemens/libsecutils
0e6aa6718f83987da4eab09a16f32423e3609a67
[ "Apache-2.0" ]
null
null
null
/** * @file cert.h * * @brief Certificate utility functions * * @copyright Copyright (c) Siemens Mobility GmbH, 2021 * * @author David von Oheimb <david.von.oheimb@siemens.com> * * This work is licensed under the terms of the Apache Software License * 2.0. See the COPYING file in the top-level directory. * * SPDX-License-Identifier: Apache-2.0 */ #ifndef SECUTILS_CERT_H_ #define SECUTILS_CERT_H_ /* #if OPENSSL_VERSION_NUMBER >= 0x30000000L */ /* #define OPENSSL_API_COMPAT 30000 */ #define OPENSSL_NO_DEPRECATED #ifndef _GNU_SOURCE #define _GNU_SOURCE #endif #include <string.h> /* for strcmp, strlen */ #include "../basic.h" #include "../operators.h" # include "../util/log.h" #include <openssl/x509.h> /*! * @brief load a certificate from the given file in format derived from file name extension * * @param file (path) name of the input file * @param pass the password source to use in case the input file is encrypted, or null * @param desc description of file contents to use for any error messages, or null * @param type_CA check for CA cert if 1 or EE if 0; no type check if < 0 * @param vpm verification parameters, or null, governing if and how to check cert times, * depending on X509_V_FLAG_USE_CHECK_TIME and X509_V_FLAG_NO_CHECK_TIME * @return null on error, else the first certificate contained in the file * @note Check failures are logged as a warning if vpm is null, otherwise as an error. */ /* this function is part of the genCMPClient API */ X509 *CERT_load(const char *file, OPTIONAL const char *pass, OPTIONAL const char *desc, int type_CA, OPTIONAL const X509_VERIFY_PARAM *vpm); /*! * @brief store the given certificate in given file and in format derived from file name extension * * @param cert certificate to save * @param file (path) name of the output file. Any previous contents are overwritten. * @param desc description of file contents to use for any error messages, or null * @return true on success, else false */ /* this function is part of the genCMPClient API */ bool CERT_save(const X509 *cert, const char *file, OPTIONAL const char *desc); /*! * @brief load certificates from the given file(s) with flexible format * * @param files comma/space-separated list of input file (path) names * @param desc description of file contents to use for any error messages, or null * @param type_CA check for CA cert if 1 or EE if 0; no type check if < 0 * @param vpm verification parameters, or null, governing if and how to check cert times, * depending on X509_V_FLAG_USE_CHECK_TIME and X509_V_FLAG_NO_CHECK_TIME * @return null on error, else a stack of certs with the first/primary one on top * @note Check failures are logged as a warning if vpm is null, otherwise as an error. * @note duplicate certificates among different input files are included only once */ /* this function is part of the genCMPClient API */ STACK_OF(X509) *CERTS_load(const char *files, OPTIONAL const char *desc, int type_CA, OPTIONAL const X509_VERIFY_PARAM *vpm); /*! * @brief store the given list of certificates in given file and in format derived from file name extension * * @param certs list of certificates to save * @param file (path) name of the output file. Any previous contents are overwritten. * @param desc description of file contents to use for any error messages, or null * @return the number of certificates saved, or < 0 on error */ /* this function is part of the genCMPClient API */ int CERTS_save(const STACK_OF(X509) *certs, const char *file, OPTIONAL const char *desc); /*! * @brief release a list of certificates * * @param certs (optional) the certificates to be freed */ /* this function is part of the genCMPClient API */ void CERTS_free(OPTIONAL STACK_OF(X509) *certs); /*!***************************************************************************** * @brief parse an X.500 Distinguished Name (DN) * * @param dn string to be parsed, format /type0=value0/type1=value1/type2=... where characters may be escaped by \ * @param chtype type of the string, e.g., MBSTRING_ASC, as defined in openssl/asn1.h * @param multirdn flag whether to allow multi-valued RDNs * @return ASN.1 representation of the DN, or null on error *******************************************************************************/ /* this function is used by the genCMPClient API implementation */ X509_NAME* UTIL_parse_name(const char* dn, long chtype, bool multirdn); /*!***************************************************************************** * @brief log messsage about the given certificate, printing its subject * * @param func the name of the reporting function or component, or null * @param file the current source file path name, or null * @param lineno the current line number, or 0 * @param level the nature of the message, i.e., its severity level * @param msg the message to be logged * @param cert the certificate the message referts to */ void LOG_cert(OPTIONAL const char* func, OPTIONAL const char* file, int lineno, severity level, const char* msg, const X509* cert); /*!***************************************************************************** * @brief print a certificate * * @param cert certificate to be printed, or null * @param bio BIO to print to, e.g., bio_err, or null * @param neg_cflags indicates elements not to be printed *******************************************************************************/ void CERT_print(OPTIONAL const X509* cert, OPTIONAL BIO* bio, unsigned long neg_cflags); #define UTIL_print_cert(bio, cert, neg_cflags) CERT_print(cert, bio, neg_cflags) /*!***************************************************************************** * @brief print a list of certificates * * @param certs list of certificates to be printed, or null * @param bio BIO to print to, e.g., bio_err, or null *******************************************************************************/ void CERTS_print(OPTIONAL const STACK_OF(X509) * certs, OPTIONAL BIO* bio); #define UTIL_print_certs(bio, certs) CERTS_print(certs, bio) /*!***************************************************************************** * @brief check if certificate is within validity period, optionally check type * * @param uri The source of the certificate, e.g., a URL or file name * @param cert certificate to be be checked, or null for no checks * @param type_CA check for CA cert if 1 or EE if 0; no type check if < 0 * @param vpm verification parameters, or null, governing if and how to check cert times, * depending on X509_V_FLAG_USE_CHECK_TIME and X509_V_FLAG_NO_CHECK_TIME * @return true if no cert given or cert validity period check passed * @note Check failures are logged as a warning if vpm is null, otherwise as an error. *******************************************************************************/ bool CERT_check(const char *uri, OPTIONAL X509 *cert, int type_CA, OPTIONAL const X509_VERIFY_PARAM *vpm); /*!***************************************************************************** * @brief check if a cert list member is within validity period, optionally check type * * @param uri The source of the certificates, e.g., a URL or file name * @param certs list of certificates to be be checked, or null for no checks * @param type_CA check for CA cert if 1 or EE if 0; no type check if < 0 * @param vpm verification parameters, or null, governing if and how to check cert times, * depending on X509_V_FLAG_USE_CHECK_TIME and X509_V_FLAG_NO_CHECK_TIME * @return true if no certs given or validity period check passed for all certs * @note Check failures are logged as a warning if vpm is null, otherwise as an error. *******************************************************************************/ bool CERT_check_all(const char *uri, OPTIONAL STACK_OF(X509) *certs, int type_CA, OPTIONAL const X509_VERIFY_PARAM *vpm); /*!***************************************************************************** * @brief add certificate to given stack, optionally only if not already contained * * @param sk stack of certificates * @param cert certificate to be pushed to the stack * @param no_duplicate flag governing whether to add cert if it is a duplicate * @return true on success, else false *******************************************************************************/ bool UTIL_sk_X509_add1_cert(STACK_OF(X509) * sk, X509* cert, bool no_duplicate); /*!***************************************************************************** * @brief add stack of certificates to given stack, * optionally only if not self-signed and optionally if not already contained * * @param sk stack of certificates * @param certs (optional) stack of certificates to be pushed to the stack * @param no_self_signed flag governing whether to add self-signed certs * @param no_duplicates flag governing whether to add cert if it is a duplicate * @return true on success, else false *******************************************************************************/ /* this function is used by the genCMPClient API implementation */ int UTIL_sk_X509_add1_certs(STACK_OF(X509) * sk, OPTIONAL const STACK_OF(X509) * certs, int no_self_signed, int no_duplicates); #endif /* SECUTILS_CERT_H_ */
45.427184
114
0.644155
05f434d7653a27da90986fc0835cff24b5eaa746
516
h
C
core/c33iomem.h
autch/piemu
bf15030757c49325c155a853871aee45b616717a
[ "Zlib" ]
10
2017-07-04T03:05:42.000Z
2022-01-20T17:37:06.000Z
core/c33iomem.h
autch/piemu
bf15030757c49325c155a853871aee45b616717a
[ "Zlib" ]
2
2020-06-29T13:32:15.000Z
2021-12-22T23:04:43.000Z
core/c33iomem.h
autch/piemu
bf15030757c49325c155a853871aee45b616717a
[ "Zlib" ]
5
2021-08-28T02:21:56.000Z
2022-01-16T21:39:16.000Z
#ifndef c33iomem_h #define c33iomem_h #include "c33device.h" #define IOMEM_SIZE 0x10000 /// sizeof io registers, 0x0040000-0x004ffff #define IOMAP_SIZE 10 /// # of mmapped devices struct iomap { c33word base_addr; c33device* device; }; class c33iomem: public c33device { private: c33byte mem[IOMEM_SIZE]; iomap iomap[IOMAP_SIZE]; public: c33word iomem_read(c33word offset, c33word size) { } void iomem_write(c33word offset, c33word size, c33word data) { } }; #endif // !c33iomem_h
15.176471
72
0.717054
b2cb4fc8e505941023cdbfe6b16a3c2889584ce7
1,404
h
C
GameEngine/GameObject.h
GottaCodeHarder/GT-Engine
44ae4d8c974605cc1cd5fd240af81f999b613e8a
[ "MIT" ]
1
2017-09-15T23:56:00.000Z
2017-09-15T23:56:00.000Z
GameEngine/GameObject.h
GottaCodeHarder/GT-Engine
44ae4d8c974605cc1cd5fd240af81f999b613e8a
[ "MIT" ]
5
2017-09-20T07:13:20.000Z
2017-10-12T10:57:16.000Z
GameEngine/GameObject.h
GottaCodeHarder/GT-Engine
44ae4d8c974605cc1cd5fd240af81f999b613e8a
[ "MIT" ]
null
null
null
#ifndef __GAMEOBJECT__ #define __GAMEOBJECT__ #include "Globals.h" #include "Component.h" #include <map> #include "MathGeoLib/MathGeoLib.h" class cUI; class GameObject { public: GameObject(std::string name, bool active, GameObject* parent); //FALTA DESTRUCTOR QUE DESTRUEIXI ELS FILLS std::map<componentType, Component*> components; std::vector<cUI*> UIcomponents; void PreUpdate(); void Update(); void IsPlaying(float dt); Component* FindComponent(componentType); void DrawUI(); void UpdateAABB(float4x4 matrix); void DrawHeriarchy(GameObject* son); void DrawProperties(); bool SonHasMesh(); void AddComponent(Component*); void AddComponent(cUI*); void Save(JSON_Object *go) const; void Load(const JSON_Object *go); // Returns the length of the buffer uint Serialize(char* &buffer); uint DeSerialize(char* &buffer, GameObject * parent); void Enable(); void Disable(); std::string name; GameObject* parent; std::vector<GameObject*> sons; bool active = true; bool collapsedHierarchy = false; bool clicked = false; bool insideFrustum = false; AABB aabbBox; bool statiC = false; bool isInsideQuad = false; bool resizeAABB = true; private: template <typename var> void Cpy(var toCopy, char*& it) { uint bytes = szieof(var); memcpy(it, &toCopy, bytes); it += bytes; } // How to declare for uint: Cpy<uint>(sons.size(), it); }; #endif // ! __GAMEOBJECT__
19.774648
63
0.722934
256039574adb33a32f8ef20058e8b719f035b375
254
h
C
src/Include/Objects.h
Wizard2D/ZatherEngine
6cbae20f5609ffa69c9adaf295ac6ed06e2a9817
[ "Apache-2.0" ]
null
null
null
src/Include/Objects.h
Wizard2D/ZatherEngine
6cbae20f5609ffa69c9adaf295ac6ed06e2a9817
[ "Apache-2.0" ]
null
null
null
src/Include/Objects.h
Wizard2D/ZatherEngine
6cbae20f5609ffa69c9adaf295ac6ed06e2a9817
[ "Apache-2.0" ]
2
2021-08-31T16:00:21.000Z
2021-08-31T16:52:44.000Z
#pragma once #include <iostream> #include <any> #include <vector> class Component { public: Entity* ent; std::string name; std::any value; }; class Entity { public: std::vector<Component> components; virtual void Draw() = 0; };
13.368421
36
0.637795
0594e67d4fabd73f7484ce340d6d6d2b6ca4a6c8
229
h
C
Example/SSPodDemo/SSViewController.h
aishuaishuai298513/SSPodDemo
b4fbde58f53a2b82f26fc5016ce2a9b651a226b0
[ "MIT" ]
null
null
null
Example/SSPodDemo/SSViewController.h
aishuaishuai298513/SSPodDemo
b4fbde58f53a2b82f26fc5016ce2a9b651a226b0
[ "MIT" ]
null
null
null
Example/SSPodDemo/SSViewController.h
aishuaishuai298513/SSPodDemo
b4fbde58f53a2b82f26fc5016ce2a9b651a226b0
[ "MIT" ]
null
null
null
// // SSViewController.h // SSPodDemo // // Created by aishuaishuai298513 on 11/12/2019. // Copyright (c) 2019 aishuaishuai298513. All rights reserved. // @import UIKit; @interface SSViewController : UIViewController @end
16.357143
63
0.729258
19b52f06ca3435560aa36f353076dacdb219fc25
1,663
c
C
geeks_shm/writer.c
Amirsorouri00/Shared-Memory-IPC
1637f3e971898ae68017f1c1d2bcbb0fedf77cfe
[ "MIT" ]
5
2020-10-18T02:05:42.000Z
2021-12-25T01:30:26.000Z
geeks_shm/writer.c
Amirsorouri00/Shared-Memory-IPC
1637f3e971898ae68017f1c1d2bcbb0fedf77cfe
[ "MIT" ]
null
null
null
geeks_shm/writer.c
Amirsorouri00/Shared-Memory-IPC
1637f3e971898ae68017f1c1d2bcbb0fedf77cfe
[ "MIT" ]
4
2020-04-14T15:44:38.000Z
2021-05-02T05:48:13.000Z
#define _GNU_SOURCE #include <stdio.h> #include <sys/ipc.h> #include <sys/shm.h> #include <sys/wait.h> #include <string.h> #include "splicer-benchmarking.h" int main() { // ftok to generate unique key key_t key = ftok("shmfile",65); // char** dataset = initializer(); char* buf = malloc(sizeof(char*) * SPLICE_SIZE); char ch[58] = {}; random_char_selector(ch); time_t t; srand((unsigned) time(&t)); for(int i = 0; i < SPLICE_SIZE; i++){ buf[i] = ch[(rand() % 58)]; } // shmget returns an identifier in shmid int shmid = shmget(key,SPLICE_SIZE,0666|IPC_CREAT); // shmat to attach to shared memory char *str = (char*) shmat(shmid,(char*)0,0); pid_t childpid; if((childpid = fork()) == -1) { perror("fork"); exit(1); } if(childpid == 0) { clock_t start = clocker(0, "start"); memcpy(str, buf, SPLICE_SIZE); clock_t end = clocker(1, "end"); double first_result = time_calc(end, start, "here"); printf("The frequency is eqals to(Mbps): %f .\n", (double)((SPLICE_SIZE)/(first_result*1000000))); printf("Data written in memory: NULL and pointer is %d\n", str[500000]); } else{ int child1_status, child2_status; waitpid(childpid, &child1_status, 0); if (child1_status == 0) // Verify child process terminated without error. { printf("The child process terminated normally.\n"); } else{printf("The child process terminated with an error!.\n");} exit(0); } //detach from shared memory // shmdt(str); return 0; }
25.584615
106
0.580878
585eea9c9401c7e22f757f7aaed17f359283fde2
245
h
C
LKAppBoxSDK/Products/LKAppBoxSDK.framework/Headers/LKAppBoxSDK.h
MrDML/LKAppBoxSDK
bedde1774da45ce239545b73d69262a8501a0f7d
[ "MIT" ]
null
null
null
LKAppBoxSDK/Products/LKAppBoxSDK.framework/Headers/LKAppBoxSDK.h
MrDML/LKAppBoxSDK
bedde1774da45ce239545b73d69262a8501a0f7d
[ "MIT" ]
null
null
null
LKAppBoxSDK/Products/LKAppBoxSDK.framework/Headers/LKAppBoxSDK.h
MrDML/LKAppBoxSDK
bedde1774da45ce239545b73d69262a8501a0f7d
[ "MIT" ]
null
null
null
// // LKAppBoxSDK.h // LKAppBoxSDK // // Created by leoan on 2020/3/27. // Copyright © 2020 MrDML. All rights reserved. // #import <Foundation/Foundation.h> #import "LKAppBoxManager.h" #import "dsbridge.h" #import "LEAppBoxContainerView.h"
18.846154
48
0.706122
ba73e4850ddcaafc2b31b3f1858acaf45abca958
410
h
C
examples/pizza/toppings/Mozzarella.h
PaulAtTUBS/Polypropylene
26066e9c2cfd234a45291453ce9d1a0e8f02b188
[ "MIT" ]
10
2019-12-24T13:46:58.000Z
2020-11-03T08:20:11.000Z
examples/pizza/toppings/Mozzarella.h
PaulAtTUBS/Polypropylene
26066e9c2cfd234a45291453ce9d1a0e8f02b188
[ "MIT" ]
null
null
null
examples/pizza/toppings/Mozzarella.h
PaulAtTUBS/Polypropylene
26066e9c2cfd234a45291453ce9d1a0e8f02b188
[ "MIT" ]
1
2022-01-13T08:16:45.000Z
2022-01-13T08:16:45.000Z
// // Created by Bittner on 06.12.2019. // #ifndef POLYPROPYLENE_GOUDA_H #define POLYPROPYLENE_GOUDA_H #include "Cheese.h" namespace PAX::Examples { class Mozzarella : public Cheese { PAX_PROPERTY(Mozzarella, PAX_PROPERTY_IS_CONCRETE) PAX_PROPERTY_DERIVES(Cheese) PAX_PROPERTY_IS_SINGLE public: std::string yummy() override; }; } #endif //POLYPROPYLENE_GOUDA_H
18.636364
58
0.704878
babb912c6fc22a420658b06a5d3c48b0bf02c904
1,339
h
C
RESTfulClientAPIs/Interface/ServerResponse.h
bearlin/tool_restful_client_connector
74b93445ee4e3934079ca911df153874c7585032
[ "MIT" ]
null
null
null
RESTfulClientAPIs/Interface/ServerResponse.h
bearlin/tool_restful_client_connector
74b93445ee4e3934079ca911df153874c7585032
[ "MIT" ]
null
null
null
RESTfulClientAPIs/Interface/ServerResponse.h
bearlin/tool_restful_client_connector
74b93445ee4e3934079ca911df153874c7585032
[ "MIT" ]
null
null
null
//! @file ServerResponse.h //! //! @brief //! #ifndef _SERVER_RESPONSE_H_ #define _SERVER_RESPONSE_H_ #include <string> class CServerResponse { private: int iResponseCode; std::string iHeaders; char* iBodyBuffer; size_t iBodySize; public: CServerResponse(int aResponseCode, std::string aHeaders, const char* aBodyBuffer, size_t aBodySize); virtual ~CServerResponse(); //! @brief Get HTTP response code after perform a request. //! @return HTTP response code int getResponseCode(); //! @brief Get HTTP header string after perform a request. //! @return HTTP header string std::string getHeader(); //! @brief Get HTTP body. //! @param[out] Pass a pointer to char*, this pointer will be modified and point to the received body address after called. //! @param[out] A size_t variable address to get the body buffer size. //! @return void. void getBody(char** aBodyBuffer, size_t* aBodySize); //! @brief Get HTTP body buffer address. //! @return A pointer to HTTP body buffer. char* getBodyData(); //! @brief Get HTTP body size. //! @return HTTP body size. size_t getBodySize(); //! @brief Converts object to its string representation. //! @return Object string representation. std::string toString(); }; #endif //_SERVER_RESPONSE_H_
26.254902
128
0.683346
2a0bcde7ae37bec7382240c7f03151671aed2465
752
c
C
tdd_ecs/src/components.c
nathhB/raylib-webrtc_bomberman
4d43e9d5856107e14371339c5d93af25f1cb58d8
[ "Zlib" ]
21
2020-04-27T17:45:13.000Z
2022-03-17T07:42:11.000Z
tdd_ecs/src/components.c
nathhB/raylib-webrtc_bomberman
4d43e9d5856107e14371339c5d93af25f1cb58d8
[ "Zlib" ]
null
null
null
tdd_ecs/src/components.c
nathhB/raylib-webrtc_bomberman
4d43e9d5856107e14371339c5d93af25f1cb58d8
[ "Zlib" ]
2
2020-05-16T17:22:03.000Z
2022-01-23T20:55:30.000Z
#include "tdd_ecs.h" void component_add_to_entity(entity_t* entity, void* component, unsigned int component_id) { B_SET(entity->components_mask, component_id); bag_set_at(entity->components, component_id, component); } void component_remove_from_entity(entity_t* entity, unsigned int component_id) { B_UNSET(entity->components_mask, component_id); void* component_ptr = bag_remove_at(entity->components, component_id); if (component_ptr != NULL) { ((component_t*)component_ptr)->destroy_func(component_ptr); } // free(component_ptr); } bool component_entity_has(entity_t* entity, unsigned int component_id) { int mask = B_MASK(component_id); return (entity->components_mask & mask) == mask; }
25.931034
90
0.731383
0fbdabb4421152f484646fd9f415e9d480457f23
546
h
C
include/Timer.h
gepperho/InfluenceMaximizationBenchmarker
af3a53fff4a745e0b761ec4dba1327cad5ea5f79
[ "Apache-2.0" ]
4
2021-06-03T02:48:48.000Z
2021-08-24T08:46:50.000Z
include/Timer.h
gepperho/InfluenceMaximizationBenchmarker
af3a53fff4a745e0b761ec4dba1327cad5ea5f79
[ "Apache-2.0" ]
null
null
null
include/Timer.h
gepperho/InfluenceMaximizationBenchmarker
af3a53fff4a745e0b761ec4dba1327cad5ea5f79
[ "Apache-2.0" ]
null
null
null
#pragma once #include <chrono> class Timer { using Clock = std::chrono::high_resolution_clock; using Second = std::chrono::duration<double, std::ratio<1>>; public: Timer() : beg_(Clock::now()) {} auto reset() -> void { beg_ = Clock::now(); } auto elapsed() const -> double { return std::chrono::duration_cast<Second>(Clock::now() - beg_) .count(); } private: std::chrono::time_point<Clock> beg_; };
18.2
64
0.498168
a775c918b4e2d1b44671b2bad856b6df69a0986b
4,272
h
C
ImperasLib/source/freescale.ovpworld.org/peripheral/KinetisPIT/1.0/pse/pse.igen.h
emanuellucas2/OVPsimProject
6c9f5bfaaa135fa63d63746bacf5759c6d6c0e9e
[ "TCL" ]
null
null
null
ImperasLib/source/freescale.ovpworld.org/peripheral/KinetisPIT/1.0/pse/pse.igen.h
emanuellucas2/OVPsimProject
6c9f5bfaaa135fa63d63746bacf5759c6d6c0e9e
[ "TCL" ]
null
null
null
ImperasLib/source/freescale.ovpworld.org/peripheral/KinetisPIT/1.0/pse/pse.igen.h
emanuellucas2/OVPsimProject
6c9f5bfaaa135fa63d63746bacf5759c6d6c0e9e
[ "TCL" ]
null
null
null
/* * Copyright (c) 2005-2021 Imperas Software Ltd., www.imperas.com * * 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. * */ //////////////////////////////////////////////////////////////////////////////// // // W R I T T E N B Y I M P E R A S I G E N // // Version 20211118.0 // //////////////////////////////////////////////////////////////////////////////// #ifndef PSE_IGEN_H #define PSE_IGEN_H #ifdef _PSE_ # include "peripheral/impTypes.h" # include "peripheral/bhm.h" # include "peripheral/bhmHttp.h" # include "peripheral/ppm.h" #else # include "hostapi/impTypes.h" #endif #ifdef _PSE_ //////////////////////////////////// Externs /////////////////////////////////// extern Uns32 diagnosticLevel; /////////////////////////// Dynamic Diagnostic Macros ////////////////////////// // Bottom two bits of word used for PSE diagnostics #define PSE_DIAG_LOW (BHM_DIAG_MASK_LOW(diagnosticLevel)) #define PSE_DIAG_MEDIUM (BHM_DIAG_MASK_MEDIUM(diagnosticLevel)) #define PSE_DIAG_HIGH (BHM_DIAG_MASK_HIGH(diagnosticLevel)) // Next two bits of word used for PSE semihost/intercept library diagnostics #define PSE_DIAG_SEMIHOST (BHM_DIAG_MASK_SEMIHOST(diagnosticLevel)) #endif /////////////////////////// Register data declaration ////////////////////////// typedef struct bport1_ab_dataS { union { Uns32 value; struct { Uns32 FRZ : 1; Uns32 MDIS : 1; } bits; } MCR; } bport1_ab_dataT, *bport1_ab_dataTP; typedef struct bport1_ab2_dataS { union { Uns32 value; struct { Uns32 TSV : 32; } bits; } LDVAL; union { Uns32 value; struct { Uns32 TVL : 32; } bits; } CVAL; union { Uns32 value; struct { Uns32 TEN : 1; Uns32 TIE : 1; } bits; } TCTRL; union { Uns32 value; struct { Uns32 TIF : 1; } bits; } TFLG; } bport1_ab2_dataT, *bport1_ab2_dataTP; #ifdef _PSE_ /////////////////////////////// Port Declarations ////////////////////////////// extern bport1_ab_dataT bport1_ab_data; extern bport1_ab2_dataT bport1_ab2_data[4]; ///////////////////////////////// Port handles ///////////////////////////////// typedef struct handlesS { void *bport1; ppmNetHandle Reset; ppmNetHandle irq[4]; ppmNetHandle trg[4]; } handlesT, *handlesTP; extern handlesT handles; ////////////////////////////// Callback prototypes ///////////////////////////// PPM_NBYTE_READ_CB(readCVAL); PPM_NBYTE_VIEW_CB(viewCVAL); PPM_NBYTE_WRITE_CB(writeMCR); PPM_NBYTE_WRITE_CB(writeTCTRL); PPM_NBYTE_WRITE_CB(writeTFLG); PPM_NET_CB(reset_Reset); PPM_CONSTRUCTOR_CB(periphConstructor); PPM_DOC_FN(installDocs); PPM_CONSTRUCTOR_CB(constructor); PPM_SAVE_STATE_FN(peripheralSaveState); PPM_RESTORE_STATE_FN(peripheralRestoreState); ////////////////////////////////// Mask macros ///////////////////////////////// #define BPORT1_AB_MCR_WRMASK 0x3 #define BPORT1_AB_MCR_WRNMASK (0xfffffffc) #define BPORT1_AB_MCR_WIDTH 32 #define BPORT1_AB2_LDVAL_WIDTH 32 #define BPORT1_AB2_CVAL_WIDTH 32 #define BPORT1_AB2_TCTRL_WRMASK 0x3 #define BPORT1_AB2_TCTRL_WRNMASK (0xfffffffc) #define BPORT1_AB2_TCTRL_WIDTH 32 #define BPORT1_AB2_TFLG_WRMASK 0x1 #define BPORT1_AB2_TFLG_WRNMASK (0xfffffffe) #define BPORT1_AB2_TFLG_WIDTH 32 //////////////////////////// Parameters of enum type /////////////////////////// #endif #endif
28.291391
81
0.554541
be952d3984921798bc67ebaef22400efc5ec0f62
2,936
h
C
multimedia/directx/dsound/dsdmo/garglep.h
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
multimedia/directx/dsound/dsdmo/garglep.h
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
multimedia/directx/dsound/dsdmo/garglep.h
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
// // // #ifndef _Garglep_ #define _Garglep_ #include "dsdmobse.h" #include "dmocom.h" #include "dsdmo.h" #include "PropertyHelp.h" #include "param.h" class CDirectSoundGargleDMO : public CDirectSoundDMO, public CParamsManager, public ISpecifyPropertyPages, public IDirectSoundFXGargle, public CParamsManager::UpdateCallback, public CComBase { public: CDirectSoundGargleDMO( IUnknown *pUnk, HRESULT *phr); ~CDirectSoundGargleDMO(); DECLARE_IUNKNOWN; STDMETHODIMP NDQueryInterface(REFIID riid, void **ppv); static CComBase* WINAPI CreateInstance(IUnknown *pUnk, HRESULT *phr); // InitOnCreation is called by the class factory to give the object a chance to initialize // immediately after it is created. This is used to prepare the object's parameter information. HRESULT InitOnCreation(); // The Init function is an override from the CPCMDMO base class and it provides initialization // for the effect's actual audio processing. Note that InputType must have been set before this // occurs in order for this to work. HRESULT Init(); STDMETHOD(Clone) (THIS_ IMediaObjectInPlace **); // IPersist methods virtual HRESULT STDMETHODCALLTYPE GetClassID( CLSID *pClassID ); // ISpecifyPropertyPages STDMETHOD(GetPages)(CAUUID * pPages) { return PropertyHelp::GetPages(CLSID_DirectSoundPropGargle, pPages); } // IPersistStream STDMETHOD(IsDirty)(void) { return m_fDirty ? S_OK : S_FALSE; } STDMETHOD(Load)(IStream *pStm) { return PropertyHelp::Load(this, DSFXGargle(), pStm); } STDMETHOD(Save)(IStream *pStm, BOOL fClearDirty) { return PropertyHelp::Save(this, DSFXGargle(), pStm, fClearDirty); } STDMETHOD(GetSizeMax)(ULARGE_INTEGER *pcbSize) { if (!pcbSize) return E_POINTER; pcbSize->QuadPart = sizeof(DSFXGargle); return S_OK; } // IDirectSoundFXGargle STDMETHOD(SetAllParameters) (THIS_ LPCDSFXGargle); STDMETHOD(GetAllParameters) (THIS_ LPDSFXGargle); // SetParam handling STDMETHODIMP SetParam(DWORD dwParamIndex,MP_DATA value) { return SetParamInternal(dwParamIndex, value, false); } HRESULT SetParamUpdate(DWORD dwParamIndex, MP_DATA value) { return SetParamInternal(dwParamIndex, value, true); } HRESULT SetParamInternal(DWORD dwParamIndex, MP_DATA value, bool fSkipPasssingToParamManager); // All of these methods are called by the base class HRESULT FBRProcess(DWORD cQuanta, BYTE *pIn, BYTE *pOut); HRESULT Discontinuity(); HRESULT ProcessInPlace(ULONG ulQuanta, LPBYTE pcbData, REFERENCE_TIME rtStart, DWORD dwFlags); bool m_fDirty; private: // gargle params ULONG m_ulShape; ULONG m_ulGargleFreqHz; // gargle state ULONG m_ulPeriod; ULONG m_ulPhase; BOOL m_bInitialized; }; EXT_STD_CREATE(Gargle); #endif
35.373494
140
0.707766
d50d63ba6c1372a8ff1b6a825e2609f8821aac50
877
h
C
cases/spherical_surfers/param/post/objects/surfer__us_1o0__surftimeconst_6o0__reorientationtime_2o5/px/group/choice.h
C0PEP0D/sheld0n
497d4ee8b6b1815cd5fa1b378d1b947ee259f4bc
[ "MIT" ]
null
null
null
cases/spherical_surfers/param/post/objects/surfer__us_1o0__surftimeconst_6o0__reorientationtime_2o5/px/group/choice.h
C0PEP0D/sheld0n
497d4ee8b6b1815cd5fa1b378d1b947ee259f4bc
[ "MIT" ]
null
null
null
cases/spherical_surfers/param/post/objects/surfer__us_1o0__surftimeconst_6o0__reorientationtime_2o5/px/group/choice.h
C0PEP0D/sheld0n
497d4ee8b6b1815cd5fa1b378d1b947ee259f4bc
[ "MIT" ]
null
null
null
#ifndef C0P_PARAM_POST_OBJECTS_SURFER__US_1O0__SURFTIMECONST_6O0__REORIENTATIONTIME_2O5_PX_GROUP_CHOICE_H #define C0P_PARAM_POST_OBJECTS_SURFER__US_1O0__SURFTIMECONST_6O0__REORIENTATIONTIME_2O5_PX_GROUP_CHOICE_H #pragma once // THIS FILE SHOULD NOT BE EDITED DIRECTLY BY THE USERS. // THIS FILE WILL BE AUTOMATICALLY EDITED WHEN THE // CHOOSE COMMAND IS USED // choose your post #include "core/post/objects/object/post/group/all/core.h" #include "param/post/objects/surfer__us_1o0__surftimeconst_6o0__reorientationtime_2o5/px/group/all/parameters.h" namespace c0p { template<typename TypeSurferUs1O0Surftimeconst6O0Reorientationtime2O5Step> using PostSurferUs1O0Surftimeconst6O0Reorientationtime2O5PxGroup = PostPostGroupAll<PostSurferUs1O0Surftimeconst6O0Reorientationtime2O5PxGroupAllParameters, TypeSurferUs1O0Surftimeconst6O0Reorientationtime2O5Step>; } #endif
46.157895
218
0.877993
028b1b5b64e6bf5fddf7f338fb5632a8645d7fbc
127
h
C
includes/stringLength.h
gshimabuko/problem_9
140e725c7f35b72e15f130b922d598445f539f3f
[ "Unlicense" ]
null
null
null
includes/stringLength.h
gshimabuko/problem_9
140e725c7f35b72e15f130b922d598445f539f3f
[ "Unlicense" ]
null
null
null
includes/stringLength.h
gshimabuko/problem_9
140e725c7f35b72e15f130b922d598445f539f3f
[ "Unlicense" ]
null
null
null
#ifndef __STRINGLENGTH__ #define __STRINGLENGTH__ #include <string> int Length(std::string s); #endif /* __STRINGLENGTH__ */
15.875
29
0.76378
b3f6fa59c85d1e40fcbe2dec6ebc9f5bbb4d2c1c
1,644
c
C
src/strlcpy.c
nexos-dev/libnex
66980485a20cfedbcfdf0667324b9dbbc70aae14
[ "Apache-2.0" ]
null
null
null
src/strlcpy.c
nexos-dev/libnex
66980485a20cfedbcfdf0667324b9dbbc70aae14
[ "Apache-2.0" ]
null
null
null
src/strlcpy.c
nexos-dev/libnex
66980485a20cfedbcfdf0667324b9dbbc70aae14
[ "Apache-2.0" ]
null
null
null
/* strlcpy.c - contains BSD strlcpy Copyright 2022 The NexNix Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. There should be a copy of the License distributed in a file named LICENSE, if not, you may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /// @file strlcpy.c #include <libnex/safestring.h> /** * @brief A safer version of strcpy(3) * * strlcpy takes a buffer size, and copies at most size - 1 bytes, padding with null character. * It returns the length of the buffer they tried to create. * * @param[out] dest the string to write out to * @param[in] src the string copy from * @param[in] size the size of dest * @return the length of src */ LIBNEX_PUBLIC size_t strlcpy (char* dest, const char* src, size_t size) { const char* osrc = src; size_t sz = size; // Main copy loop if (size) { while (--sz) { if ((*dest++ = *src++) == '\0') break; } } // Null terminate dest if truncation occured if (!sz) { if (size) *dest = '\0'; // Get size of input buffer while (*src++) ; } return src - osrc - 1; }
28.344828
95
0.631387
27dc1ed4160d9dbc6f788b90ca2d2146cfe13d5f
550
h
C
src/session_manager/foldertreeitem.h
alexcrack/owlsql
4ee9f2a421fc898f0bb8d7b4b7d6fbd47db98a22
[ "MIT" ]
null
null
null
src/session_manager/foldertreeitem.h
alexcrack/owlsql
4ee9f2a421fc898f0bb8d7b4b7d6fbd47db98a22
[ "MIT" ]
null
null
null
src/session_manager/foldertreeitem.h
alexcrack/owlsql
4ee9f2a421fc898f0bb8d7b4b7d6fbd47db98a22
[ "MIT" ]
null
null
null
#ifndef FOLDERTREEITEM_H #define FOLDERTREEITEM_H #include "treeitem.h" class FolderTreeItem : public TreeItem { public: enum Field { FolderName = 0 }; explicit FolderTreeItem(const QString &name, TreeItem *parentItem); QVariant data(int column) const; bool setData(int column, const QVariant &data) override; QVariant icon(int column) const; bool canInsertChild() const; QJsonObject toJson() override; QString name() const override; private: QString m_folderName; }; #endif // FOLDERTREEITEM_H
19.642857
71
0.710909
4686aaa88e183fd72b1d85fbbcd658f7188385a4
646
h
C
Medieval War Defense/Medieval War Defense/Light.h
PauloSilva93/Medieval-War-Defense
d4027c376552849c582499b27d1e705e18471224
[ "MIT" ]
null
null
null
Medieval War Defense/Medieval War Defense/Light.h
PauloSilva93/Medieval-War-Defense
d4027c376552849c582499b27d1e705e18471224
[ "MIT" ]
null
null
null
Medieval War Defense/Medieval War Defense/Light.h
PauloSilva93/Medieval-War-Defense
d4027c376552849c582499b27d1e705e18471224
[ "MIT" ]
null
null
null
#pragma once #include "Shader.h" #include "MathUtils.h" class Light { public: Shader *shader; MathUtils mu; float *positionXYZ; float *diffuse_lightColor; float *specular_lightColor; float *ambient_lightColor; float shininess; float *falloff; bool pointLight = true; bool spotLight = false; float light_Spot[3]; float spotCutOff; float outerCutOff; Light(Shader shader[], float positionXYZ[3], float diffuse_lightColor[3], float specular_lightColor[3], float ambient_lightColor[3], float shininess, float falloff[3]); void EnableSpotLight(float degrees, float spotCutOff, float outerCutOff); void EnableDirectionalLight(); };
23.071429
169
0.76935
7d271e3b07d07a69999c39dcc66c6b93dc9c1318
42,414
h
C
include/tinkerforge/bricklet_nfc.h
ulrichwi/ros-tinkerforge_sensors
43a4a7136c6d6dfc01f65a0964dfd19aaa0e457a
[ "MIT" ]
1
2018-12-11T16:04:42.000Z
2018-12-11T16:04:42.000Z
include/tinkerforge/bricklet_nfc.h
ulrichwi/ros-tinkerforge_sensors
43a4a7136c6d6dfc01f65a0964dfd19aaa0e457a
[ "MIT" ]
null
null
null
include/tinkerforge/bricklet_nfc.h
ulrichwi/ros-tinkerforge_sensors
43a4a7136c6d6dfc01f65a0964dfd19aaa0e457a
[ "MIT" ]
null
null
null
/* *********************************************************** * This file was automatically generated on 2018-11-28. * * * * C/C++ Bindings Version 2.1.23 * * * * If you have a bugfix for this file and want to commit it, * * please fix the bug in the generator. You can find a link * * to the generators git repository on tinkerforge.com * *************************************************************/ #ifndef BRICKLET_NFC_H #define BRICKLET_NFC_H #include "ip_connection.h" #ifdef __cplusplus extern "C" { #endif /** * \defgroup BrickletNFC NFC Bricklet */ /** * \ingroup BrickletNFC * * NFC tag read/write, NFC P2P and Card Emulation */ typedef Device NFC; /** * \ingroup BrickletNFC */ #define NFC_FUNCTION_SET_MODE 1 /** * \ingroup BrickletNFC */ #define NFC_FUNCTION_GET_MODE 2 /** * \ingroup BrickletNFC */ #define NFC_FUNCTION_READER_REQUEST_TAG_ID 3 /** * \ingroup BrickletNFC */ #define NFC_FUNCTION_READER_GET_TAG_ID_LOW_LEVEL 4 /** * \ingroup BrickletNFC */ #define NFC_FUNCTION_READER_GET_STATE 5 /** * \ingroup BrickletNFC */ #define NFC_FUNCTION_READER_WRITE_NDEF_LOW_LEVEL 6 /** * \ingroup BrickletNFC */ #define NFC_FUNCTION_READER_REQUEST_NDEF 7 /** * \ingroup BrickletNFC */ #define NFC_FUNCTION_READER_READ_NDEF_LOW_LEVEL 8 /** * \ingroup BrickletNFC */ #define NFC_FUNCTION_READER_AUTHENTICATE_MIFARE_CLASSIC_PAGE 9 /** * \ingroup BrickletNFC */ #define NFC_FUNCTION_READER_WRITE_PAGE_LOW_LEVEL 10 /** * \ingroup BrickletNFC */ #define NFC_FUNCTION_READER_REQUEST_PAGE 11 /** * \ingroup BrickletNFC */ #define NFC_FUNCTION_READER_READ_PAGE_LOW_LEVEL 12 /** * \ingroup BrickletNFC */ #define NFC_FUNCTION_CARDEMU_GET_STATE 14 /** * \ingroup BrickletNFC */ #define NFC_FUNCTION_CARDEMU_START_DISCOVERY 15 /** * \ingroup BrickletNFC */ #define NFC_FUNCTION_CARDEMU_WRITE_NDEF_LOW_LEVEL 16 /** * \ingroup BrickletNFC */ #define NFC_FUNCTION_CARDEMU_START_TRANSFER 17 /** * \ingroup BrickletNFC */ #define NFC_FUNCTION_P2P_GET_STATE 19 /** * \ingroup BrickletNFC */ #define NFC_FUNCTION_P2P_START_DISCOVERY 20 /** * \ingroup BrickletNFC */ #define NFC_FUNCTION_P2P_WRITE_NDEF_LOW_LEVEL 21 /** * \ingroup BrickletNFC */ #define NFC_FUNCTION_P2P_START_TRANSFER 22 /** * \ingroup BrickletNFC */ #define NFC_FUNCTION_P2P_READ_NDEF_LOW_LEVEL 23 /** * \ingroup BrickletNFC */ #define NFC_FUNCTION_SET_DETECTION_LED_CONFIG 25 /** * \ingroup BrickletNFC */ #define NFC_FUNCTION_GET_DETECTION_LED_CONFIG 26 /** * \ingroup BrickletNFC */ #define NFC_FUNCTION_SET_MAXIMUM_TIMEOUT 27 /** * \ingroup BrickletNFC */ #define NFC_FUNCTION_GET_MAXIMUM_TIMEOUT 28 /** * \ingroup BrickletNFC */ #define NFC_FUNCTION_GET_SPITFP_ERROR_COUNT 234 /** * \ingroup BrickletNFC */ #define NFC_FUNCTION_SET_BOOTLOADER_MODE 235 /** * \ingroup BrickletNFC */ #define NFC_FUNCTION_GET_BOOTLOADER_MODE 236 /** * \ingroup BrickletNFC */ #define NFC_FUNCTION_SET_WRITE_FIRMWARE_POINTER 237 /** * \ingroup BrickletNFC */ #define NFC_FUNCTION_WRITE_FIRMWARE 238 /** * \ingroup BrickletNFC */ #define NFC_FUNCTION_SET_STATUS_LED_CONFIG 239 /** * \ingroup BrickletNFC */ #define NFC_FUNCTION_GET_STATUS_LED_CONFIG 240 /** * \ingroup BrickletNFC */ #define NFC_FUNCTION_GET_CHIP_TEMPERATURE 242 /** * \ingroup BrickletNFC */ #define NFC_FUNCTION_RESET 243 /** * \ingroup BrickletNFC */ #define NFC_FUNCTION_WRITE_UID 248 /** * \ingroup BrickletNFC */ #define NFC_FUNCTION_READ_UID 249 /** * \ingroup BrickletNFC */ #define NFC_FUNCTION_GET_IDENTITY 255 /** * \ingroup BrickletNFC * * Signature: \code void callback(uint8_t state, bool idle, void *user_data) \endcode * * This callback is called if the reader state of the NFC Bricklet changes. * See {@link nfc_reader_get_state} for more information about the possible states. */ #define NFC_CALLBACK_READER_STATE_CHANGED 13 /** * \ingroup BrickletNFC * * Signature: \code void callback(uint8_t state, bool idle, void *user_data) \endcode * * This callback is called if the cardemu state of the NFC Bricklet changes. * See {@link nfc_cardemu_get_state} for more information about the possible states. */ #define NFC_CALLBACK_CARDEMU_STATE_CHANGED 18 /** * \ingroup BrickletNFC * * Signature: \code void callback(uint8_t state, bool idle, void *user_data) \endcode * * This callback is called if the P2P state of the NFC Bricklet changes. * See {@link nfc_p2p_get_state} for more information about the possible states. */ #define NFC_CALLBACK_P2P_STATE_CHANGED 24 /** * \ingroup BrickletNFC */ #define NFC_MODE_OFF 0 /** * \ingroup BrickletNFC */ #define NFC_MODE_CARDEMU 1 /** * \ingroup BrickletNFC */ #define NFC_MODE_P2P 2 /** * \ingroup BrickletNFC */ #define NFC_MODE_READER 3 /** * \ingroup BrickletNFC */ #define NFC_TAG_TYPE_MIFARE_CLASSIC 0 /** * \ingroup BrickletNFC */ #define NFC_TAG_TYPE_TYPE1 1 /** * \ingroup BrickletNFC */ #define NFC_TAG_TYPE_TYPE2 2 /** * \ingroup BrickletNFC */ #define NFC_TAG_TYPE_TYPE3 3 /** * \ingroup BrickletNFC */ #define NFC_TAG_TYPE_TYPE4 4 /** * \ingroup BrickletNFC */ #define NFC_READER_STATE_INITIALIZATION 0 /** * \ingroup BrickletNFC */ #define NFC_READER_STATE_IDLE 128 /** * \ingroup BrickletNFC */ #define NFC_READER_STATE_ERROR 192 /** * \ingroup BrickletNFC */ #define NFC_READER_STATE_REQUEST_TAG_ID 2 /** * \ingroup BrickletNFC */ #define NFC_READER_STATE_REQUEST_TAG_ID_READY 130 /** * \ingroup BrickletNFC */ #define NFC_READER_STATE_REQUEST_TAG_ID_ERROR 194 /** * \ingroup BrickletNFC */ #define NFC_READER_STATE_AUTHENTICATE_MIFARE_CLASSIC_PAGE 3 /** * \ingroup BrickletNFC */ #define NFC_READER_STATE_AUTHENTICATE_MIFARE_CLASSIC_PAGE_READY 131 /** * \ingroup BrickletNFC */ #define NFC_READER_STATE_AUTHENTICATE_MIFARE_CLASSIC_PAGE_ERROR 195 /** * \ingroup BrickletNFC */ #define NFC_READER_STATE_WRITE_PAGE 4 /** * \ingroup BrickletNFC */ #define NFC_READER_STATE_WRITE_PAGE_READY 132 /** * \ingroup BrickletNFC */ #define NFC_READER_STATE_WRITE_PAGE_ERROR 196 /** * \ingroup BrickletNFC */ #define NFC_READER_STATE_REQUEST_PAGE 5 /** * \ingroup BrickletNFC */ #define NFC_READER_STATE_REQUEST_PAGE_READY 133 /** * \ingroup BrickletNFC */ #define NFC_READER_STATE_REQUEST_PAGE_ERROR 197 /** * \ingroup BrickletNFC */ #define NFC_READER_STATE_WRITE_NDEF 6 /** * \ingroup BrickletNFC */ #define NFC_READER_STATE_WRITE_NDEF_READY 134 /** * \ingroup BrickletNFC */ #define NFC_READER_STATE_WRITE_NDEF_ERROR 198 /** * \ingroup BrickletNFC */ #define NFC_READER_STATE_REQUEST_NDEF 7 /** * \ingroup BrickletNFC */ #define NFC_READER_STATE_REQUEST_NDEF_READY 135 /** * \ingroup BrickletNFC */ #define NFC_READER_STATE_REQUEST_NDEF_ERROR 199 /** * \ingroup BrickletNFC */ #define NFC_KEY_A 0 /** * \ingroup BrickletNFC */ #define NFC_KEY_B 1 /** * \ingroup BrickletNFC */ #define NFC_READER_WRITE_TYPE4_CAPABILITY_CONTAINER 3 /** * \ingroup BrickletNFC */ #define NFC_READER_WRITE_TYPE4_NDEF 4 /** * \ingroup BrickletNFC */ #define NFC_READER_REQUEST_TYPE4_CAPABILITY_CONTAINER 3 /** * \ingroup BrickletNFC */ #define NFC_READER_REQUEST_TYPE4_NDEF 4 /** * \ingroup BrickletNFC */ #define NFC_CARDEMU_STATE_INITIALIZATION 0 /** * \ingroup BrickletNFC */ #define NFC_CARDEMU_STATE_IDLE 128 /** * \ingroup BrickletNFC */ #define NFC_CARDEMU_STATE_ERROR 192 /** * \ingroup BrickletNFC */ #define NFC_CARDEMU_STATE_DISCOVER 2 /** * \ingroup BrickletNFC */ #define NFC_CARDEMU_STATE_DISCOVER_READY 130 /** * \ingroup BrickletNFC */ #define NFC_CARDEMU_STATE_DISCOVER_ERROR 194 /** * \ingroup BrickletNFC */ #define NFC_CARDEMU_STATE_TRANSFER_NDEF 3 /** * \ingroup BrickletNFC */ #define NFC_CARDEMU_STATE_TRANSFER_NDEF_READY 131 /** * \ingroup BrickletNFC */ #define NFC_CARDEMU_STATE_TRANSFER_NDEF_ERROR 195 /** * \ingroup BrickletNFC */ #define NFC_CARDEMU_TRANSFER_ABORT 0 /** * \ingroup BrickletNFC */ #define NFC_CARDEMU_TRANSFER_WRITE 1 /** * \ingroup BrickletNFC */ #define NFC_P2P_STATE_INITIALIZATION 0 /** * \ingroup BrickletNFC */ #define NFC_P2P_STATE_IDLE 128 /** * \ingroup BrickletNFC */ #define NFC_P2P_STATE_ERROR 192 /** * \ingroup BrickletNFC */ #define NFC_P2P_STATE_DISCOVER 2 /** * \ingroup BrickletNFC */ #define NFC_P2P_STATE_DISCOVER_READY 130 /** * \ingroup BrickletNFC */ #define NFC_P2P_STATE_DISCOVER_ERROR 194 /** * \ingroup BrickletNFC */ #define NFC_P2P_STATE_TRANSFER_NDEF 3 /** * \ingroup BrickletNFC */ #define NFC_P2P_STATE_TRANSFER_NDEF_READY 131 /** * \ingroup BrickletNFC */ #define NFC_P2P_STATE_TRANSFER_NDEF_ERROR 195 /** * \ingroup BrickletNFC */ #define NFC_P2P_TRANSFER_ABORT 0 /** * \ingroup BrickletNFC */ #define NFC_P2P_TRANSFER_WRITE 1 /** * \ingroup BrickletNFC */ #define NFC_P2P_TRANSFER_READ 2 /** * \ingroup BrickletNFC */ #define NFC_DETECTION_LED_CONFIG_OFF 0 /** * \ingroup BrickletNFC */ #define NFC_DETECTION_LED_CONFIG_ON 1 /** * \ingroup BrickletNFC */ #define NFC_DETECTION_LED_CONFIG_SHOW_HEARTBEAT 2 /** * \ingroup BrickletNFC */ #define NFC_DETECTION_LED_CONFIG_SHOW_DETECTION 3 /** * \ingroup BrickletNFC */ #define NFC_BOOTLOADER_MODE_BOOTLOADER 0 /** * \ingroup BrickletNFC */ #define NFC_BOOTLOADER_MODE_FIRMWARE 1 /** * \ingroup BrickletNFC */ #define NFC_BOOTLOADER_MODE_BOOTLOADER_WAIT_FOR_REBOOT 2 /** * \ingroup BrickletNFC */ #define NFC_BOOTLOADER_MODE_FIRMWARE_WAIT_FOR_REBOOT 3 /** * \ingroup BrickletNFC */ #define NFC_BOOTLOADER_MODE_FIRMWARE_WAIT_FOR_ERASE_AND_REBOOT 4 /** * \ingroup BrickletNFC */ #define NFC_BOOTLOADER_STATUS_OK 0 /** * \ingroup BrickletNFC */ #define NFC_BOOTLOADER_STATUS_INVALID_MODE 1 /** * \ingroup BrickletNFC */ #define NFC_BOOTLOADER_STATUS_NO_CHANGE 2 /** * \ingroup BrickletNFC */ #define NFC_BOOTLOADER_STATUS_ENTRY_FUNCTION_NOT_PRESENT 3 /** * \ingroup BrickletNFC */ #define NFC_BOOTLOADER_STATUS_DEVICE_IDENTIFIER_INCORRECT 4 /** * \ingroup BrickletNFC */ #define NFC_BOOTLOADER_STATUS_CRC_MISMATCH 5 /** * \ingroup BrickletNFC */ #define NFC_STATUS_LED_CONFIG_OFF 0 /** * \ingroup BrickletNFC */ #define NFC_STATUS_LED_CONFIG_ON 1 /** * \ingroup BrickletNFC */ #define NFC_STATUS_LED_CONFIG_SHOW_HEARTBEAT 2 /** * \ingroup BrickletNFC */ #define NFC_STATUS_LED_CONFIG_SHOW_STATUS 3 /** * \ingroup BrickletNFC * * This constant is used to identify a NFC Bricklet. * * The {@link nfc_get_identity} function and the * {@link IPCON_CALLBACK_ENUMERATE} callback of the IP Connection have a * \c device_identifier parameter to specify the Brick's or Bricklet's type. */ #define NFC_DEVICE_IDENTIFIER 286 /** * \ingroup BrickletNFC * * This constant represents the display name of a NFC Bricklet. */ #define NFC_DEVICE_DISPLAY_NAME "NFC Bricklet" /** * \ingroup BrickletNFC * * Creates the device object \c nfc with the unique device ID \c uid and adds * it to the IPConnection \c ipcon. */ void nfc_create(NFC *nfc, const char *uid, IPConnection *ipcon); /** * \ingroup BrickletNFC * * Removes the device object \c nfc from its IPConnection and destroys it. * The device object cannot be used anymore afterwards. */ void nfc_destroy(NFC *nfc); /** * \ingroup BrickletNFC * * Returns the response expected flag for the function specified by the * \c function_id parameter. It is *true* if the function is expected to * send a response, *false* otherwise. * * For getter functions this is enabled by default and cannot be disabled, * because those functions will always send a response. For callback * configuration functions it is enabled by default too, but can be disabled * via the nfc_set_response_expected function. For setter functions it is * disabled by default and can be enabled. * * Enabling the response expected flag for a setter function allows to * detect timeouts and other error conditions calls of this setter as well. * The device will then send a response for this purpose. If this flag is * disabled for a setter function then no response is send and errors are * silently ignored, because they cannot be detected. */ int nfc_get_response_expected(NFC *nfc, uint8_t function_id, bool *ret_response_expected); /** * \ingroup BrickletNFC * * Changes the response expected flag of the function specified by the * \c function_id parameter. This flag can only be changed for setter * (default value: *false*) and callback configuration functions * (default value: *true*). For getter functions it is always enabled. * * Enabling the response expected flag for a setter function allows to detect * timeouts and other error conditions calls of this setter as well. The device * will then send a response for this purpose. If this flag is disabled for a * setter function then no response is send and errors are silently ignored, * because they cannot be detected. */ int nfc_set_response_expected(NFC *nfc, uint8_t function_id, bool response_expected); /** * \ingroup BrickletNFC * * Changes the response expected flag for all setter and callback configuration * functions of this device at once. */ int nfc_set_response_expected_all(NFC *nfc, bool response_expected); /** * \ingroup BrickletNFC * * Registers the given \c function with the given \c callback_id. The * \c user_data will be passed as the last parameter to the \c function. */ void nfc_register_callback(NFC *nfc, int16_t callback_id, void *function, void *user_data); /** * \ingroup BrickletNFC * * Returns the API version (major, minor, release) of the bindings for this * device. */ int nfc_get_api_version(NFC *nfc, uint8_t ret_api_version[3]); /** * \ingroup BrickletNFC * * Sets the mode. The NFC Bricklet supports four modes: * * * Off * * Card Emulation (Cardemu): Emulates a tag for other readers * * Peer to Peer (P2P): Exchange data with other readers * * Reader: Reads and writes tags * * If you change a mode, the Bricklet will reconfigure the hardware for this mode. * Therefore, you can only use functions corresponding to the current mode. For * example, in Reader mode you can only use Reader functions. * * The default mode is "off". */ int nfc_set_mode(NFC *nfc, uint8_t mode); /** * \ingroup BrickletNFC * * Returns the mode as set by {@link nfc_set_mode}. */ int nfc_get_mode(NFC *nfc, uint8_t *ret_mode); /** * \ingroup BrickletNFC * * To read or write a tag that is in proximity of the NFC Bricklet you * first have to call this function with the expected tag type as parameter. * It is no problem if you don't know the tag type. You can cycle through * the available tag types until the tag answers the request. * * Currently the following tag types are supported: * * * Mifare Classic * * NFC Forum Type 1 * * NFC Forum Type 2 * * NFC Forum Type 3 * * NFC Forum Type 4 * * After you call {@link nfc_reader_request_tag_id} the NFC Bricklet will try to read * the tag ID from the tag. After this process is done the state will change. * You can either register the {@link NFC_CALLBACK_READER_STATE_CHANGED} callback or you can poll * {@link nfc_reader_get_state} to find out about the state change. * * If the state changes to *ReaderRequestTagIDError* it means that either there was * no tag present or that the tag has an incompatible type. If the state * changes to *ReaderRequestTagIDReady* it means that a compatible tag was found * and that the tag ID has been saved. You can now read out the tag ID by * calling {@link nfc_reader_get_tag_id}. * * If two tags are in the proximity of the NFC Bricklet, this * function will cycle through the tags. To select a specific tag you have * to call {@link nfc_reader_request_tag_id} until the correct tag ID is found. * * In case of any *ReaderError* state the selection is lost and you have to * start again by calling {@link nfc_reader_request_tag_id}. */ int nfc_reader_request_tag_id(NFC *nfc); /** * \ingroup BrickletNFC * * Returns the tag type and the tag ID. This function can only be called if the * NFC Bricklet is currently in one of the *ReaderReady* states. The returned tag ID * is the tag ID that was saved through the last call of {@link nfc_reader_request_tag_id}. * * To get the tag ID of a tag the approach is as follows: * * 1. Call {@link nfc_reader_request_tag_id} * 2. Wait for state to change to *ReaderRequestTagIDReady* (see {@link nfc_reader_get_state} or * {@link NFC_CALLBACK_READER_STATE_CHANGED} callback) * 3. Call {@link nfc_reader_get_tag_id} */ int nfc_reader_get_tag_id_low_level(NFC *nfc, uint8_t *ret_tag_type, uint8_t *ret_tag_id_length, uint8_t ret_tag_id_data[32]); /** * \ingroup BrickletNFC * * Returns the current reader state of the NFC Bricklet. * * On startup the Bricklet will be in the *ReaderInitialization* state. The * initialization will only take about 20ms. After that it changes to *ReaderIdle*. * * The Bricklet is also reinitialized if the mode is changed, see {@link nfc_set_mode}. * * The functions of this Bricklet can be called in the *ReaderIdle* state and all of * the *ReaderReady* and *ReaderError* states. * * Example: If you call {@link nfc_reader_request_page}, the state will change to * *ReaderRequestPage* until the reading of the page is finished. Then it will change * to either *ReaderRequestPageReady* if it worked or to *ReaderRequestPageError* if it * didn't. If the request worked you can get the page by calling {@link nfc_reader_read_page}. * * The same approach is used analogously for the other API functions. */ int nfc_reader_get_state(NFC *nfc, uint8_t *ret_state, bool *ret_idle); /** * \ingroup BrickletNFC * * Writes NDEF formated data with a maximum of 255 bytes. * * This function currently supports NFC Forum Type 2 and 4. * * The general approach for writing a NDEF message is as follows: * * 1. Call {@link nfc_reader_request_tag_id} * 2. Wait for state to change to *ReaderRequestTagIDReady* (see * {@link nfc_reader_get_state} or {@link NFC_CALLBACK_READER_STATE_CHANGED} callback) * 3. If looking for a specific tag then call {@link nfc_reader_get_tag_id} and check * if the expected tag was found, if it was not found got back to step 1 * 4. Call {@link nfc_reader_write_ndef} with the NDEF message that you want to write * 5. Wait for state to change to *ReaderWriteNDEFReady* (see {@link nfc_reader_get_state} * or {@link NFC_CALLBACK_READER_STATE_CHANGED} callback) */ int nfc_reader_write_ndef_low_level(NFC *nfc, uint16_t ndef_length, uint16_t ndef_chunk_offset, uint8_t ndef_chunk_data[60]); /** * \ingroup BrickletNFC * * Reads NDEF formated data from a tag. * * This function currently supports NFC Forum Type 1, 2, 3 and 4. * * The general approach for reading a NDEF message is as follows: * * 1. Call {@link nfc_reader_request_tag_id} * 2. Wait for state to change to *RequestTagIDReady* (see {@link nfc_reader_get_state} * or {@link NFC_CALLBACK_READER_STATE_CHANGED} callback) * 3. If looking for a specific tag then call {@link nfc_reader_get_tag_id} and check if the * expected tag was found, if it was not found got back to step 1 * 4. Call {@link nfc_reader_request_ndef} * 5. Wait for state to change to *ReaderRequestNDEFReady* (see {@link nfc_reader_get_state} * or {@link NFC_CALLBACK_READER_STATE_CHANGED} callback) * 6. Call {@link nfc_reader_read_ndef} to retrieve the NDEF message from the buffer */ int nfc_reader_request_ndef(NFC *nfc); /** * \ingroup BrickletNFC * * Returns the NDEF data from an internal buffer. To fill the buffer * with a NDEF message you have to call {@link nfc_reader_request_ndef} beforehand. * * The buffer can have a size of up to 8192 bytes. */ int nfc_reader_read_ndef_low_level(NFC *nfc, uint16_t *ret_ndef_length, uint16_t *ret_ndef_chunk_offset, uint8_t ret_ndef_chunk_data[60]); /** * \ingroup BrickletNFC * * Mifare Classic tags use authentication. If you want to read from or write to * a Mifare Classic page you have to authenticate it beforehand. * Each page can be authenticated with two keys: A (``key_number`` = 0) and B * (``key_number`` = 1). A new Mifare Classic * tag that has not yet been written to can be accessed with key A * and the default key ``[0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]``. * * The approach to read or write a Mifare Classic page is as follows: * * 1. Call {@link nfc_reader_request_tag_id} * 2. Wait for state to change to *ReaderRequestTagIDReady* (see {@link nfc_reader_get_state} * or {@link NFC_CALLBACK_READER_STATE_CHANGED} callback) * 3. If looking for a specific tag then call {@link nfc_reader_get_tag_id} and check if the * expected tag was found, if it was not found got back to step 1 * 4. Call {@link nfc_reader_authenticate_mifare_classic_page} with page and key for the page * 5. Wait for state to change to *ReaderAuthenticatingMifareClassicPageReady* (see * {@link nfc_reader_get_state} or {@link NFC_CALLBACK_READER_STATE_CHANGED} callback) * 6. Call {@link nfc_reader_request_page} or {@link nfc_reader_write_page} to read/write page * * The authentication will always work for one whole sector (4 pages). */ int nfc_reader_authenticate_mifare_classic_page(NFC *nfc, uint16_t page, uint8_t key_number, uint8_t key[6]); /** * \ingroup BrickletNFC * * Writes a maximum of 8192 bytes starting from the given page. How many pages are written * depends on the tag type. The page sizes are as follows: * * * Mifare Classic page size: 16 byte * * NFC Forum Type 1 page size: 8 byte * * NFC Forum Type 2 page size: 4 byte * * NFC Forum Type 3 page size: 16 byte * * NFC Forum Type 4: No pages, page = file selection (CC or NDEF, see below) * * The general approach for writing to a tag is as follows: * * 1. Call {@link nfc_reader_request_tag_id} * 2. Wait for state to change to *ReaderRequestTagIDReady* (see {@link nfc_reader_get_state} or * {@link NFC_CALLBACK_READER_STATE_CHANGED} callback) * 3. If looking for a specific tag then call {@link nfc_reader_get_tag_id} and check if the * expected tag was found, if it was not found got back to step 1 * 4. Call {@link nfc_reader_write_page} with page number and data * 5. Wait for state to change to *ReaderWritePageReady* (see {@link nfc_reader_get_state} or * {@link NFC_CALLBACK_READER_STATE_CHANGED} callback) * * If you use a Mifare Classic tag you have to authenticate a page before you * can write to it. See {@link nfc_reader_authenticate_mifare_classic_page}. * * NFC Forum Type 4 tags are not organized into pages but different files. We currently * support two files: Capability Container file (CC) and NDEF file. * * Choose CC by setting page to 3 or NDEF by setting page to 4. */ int nfc_reader_write_page_low_level(NFC *nfc, uint16_t page, uint16_t data_length, uint16_t data_chunk_offset, uint8_t data_chunk_data[58]); /** * \ingroup BrickletNFC * * Reads a maximum of 8192 bytes starting from the given page and stores them into a buffer. * The buffer can then be read out with {@link nfc_reader_read_page}. * How many pages are read depends on the tag type. The page sizes are * as follows: * * * Mifare Classic page size: 16 byte * * NFC Forum Type 1 page size: 8 byte * * NFC Forum Type 2 page size: 4 byte * * NFC Forum Type 3 page size: 16 byte * * NFC Forum Type 4: No pages, page = file selection (CC or NDEF, see below) * * The general approach for reading a tag is as follows: * * 1. Call {@link nfc_reader_request_tag_id} * 2. Wait for state to change to *RequestTagIDReady* (see {@link nfc_reader_get_state} * or {@link NFC_CALLBACK_READER_STATE_CHANGED} callback) * 3. If looking for a specific tag then call {@link nfc_reader_get_tag_id} and check if the * expected tag was found, if it was not found got back to step 1 * 4. Call {@link nfc_reader_request_page} with page number * 5. Wait for state to change to *ReaderRequestPageReady* (see {@link nfc_reader_get_state} * or {@link NFC_CALLBACK_READER_STATE_CHANGED} callback) * 6. Call {@link nfc_reader_read_page} to retrieve the page from the buffer * * If you use a Mifare Classic tag you have to authenticate a page before you * can read it. See {@link nfc_reader_authenticate_mifare_classic_page}. * * NFC Forum Type 4 tags are not organized into pages but different files. We currently * support two files: Capability Container file (CC) and NDEF file. * * Choose CC by setting page to 3 or NDEF by setting page to 4. */ int nfc_reader_request_page(NFC *nfc, uint16_t page, uint16_t length); /** * \ingroup BrickletNFC * * Returns the page data from an internal buffer. To fill the buffer * with specific pages you have to call {@link nfc_reader_request_page} beforehand. * * The buffer can have a size of up to 8192 bytes. */ int nfc_reader_read_page_low_level(NFC *nfc, uint16_t *ret_data_length, uint16_t *ret_data_chunk_offset, uint8_t ret_data_chunk_data[60]); /** * \ingroup BrickletNFC * * Returns the current cardemu state of the NFC Bricklet. * * On startup the Bricklet will be in the *CardemuInitialization* state. The * initialization will only take about 20ms. After that it changes to *CardemuIdle*. * * The Bricklet is also reinitialized if the mode is changed, see {@link nfc_set_mode}. * * The functions of this Bricklet can be called in the *CardemuIdle* state and all of * the *CardemuReady* and *CardemuError* states. * * Example: If you call {@link nfc_cardemu_start_discovery}, the state will change to * *CardemuDiscover* until the discovery is finished. Then it will change * to either *CardemuDiscoverReady* if it worked or to *CardemuDiscoverError* if it * didn't. * * The same approach is used analogously for the other API functions. */ int nfc_cardemu_get_state(NFC *nfc, uint8_t *ret_state, bool *ret_idle); /** * \ingroup BrickletNFC * * Starts the discovery process. If you call this function while a NFC * reader device is near to the NFC Bricklet the state will change from * *CardemuDiscovery* to *CardemuDiscoveryReady*. * * If no NFC reader device can be found or if there is an error during * discovery the cardemu state will change to *CardemuDiscoveryError*. In this case you * have to restart the discovery process. * * If the cardemu state changes to *CardemuDiscoveryReady* you can start the NDEF message * transfer with {@link nfc_cardemu_write_ndef} and {@link nfc_cardemu_start_transfer}. */ int nfc_cardemu_start_discovery(NFC *nfc); /** * \ingroup BrickletNFC * * Writes the NDEF messages that is to be transferred to the NFC peer. * * The maximum supported NDEF message size in Cardemu mode is 255 byte. * * You can call this function at any time in Cardemu mode. The internal buffer * will not be overwritten until you call this function again or change the * mode. */ int nfc_cardemu_write_ndef_low_level(NFC *nfc, uint16_t ndef_length, uint16_t ndef_chunk_offset, uint8_t ndef_chunk_data[60]); /** * \ingroup BrickletNFC * * You can start the transfer of a NDEF message if the cardemu state is *CardemuDiscoveryReady*. * * Before you call this function to start a write transfer, the NDEF message that * is to be transferred has to be written via {@link nfc_cardemu_write_ndef} first. * * After you call this function the state will change to *CardemuTransferNDEF*. It will * change to *CardemuTransferNDEFReady* if the transfer was successful or * *CardemuTransferNDEFError* if it wasn't. */ int nfc_cardemu_start_transfer(NFC *nfc, uint8_t transfer); /** * \ingroup BrickletNFC * * Returns the current P2P state of the NFC Bricklet. * * On startup the Bricklet will be in the *P2PInitialization* state. The * initialization will only take about 20ms. After that it changes to *P2PIdle*. * * The Bricklet is also reinitialized if the mode is changed, see {@link nfc_set_mode}. * * The functions of this Bricklet can be called in the *P2PIdle* state and all of * the *P2PReady* and *P2PError* states. * * Example: If you call {@link nfc_p2p_start_discovery}, the state will change to * *P2PDiscover* until the discovery is finished. Then it will change * to either P2PDiscoverReady* if it worked or to *P2PDiscoverError* if it * didn't. * * The same approach is used analogously for the other API functions. */ int nfc_p2p_get_state(NFC *nfc, uint8_t *ret_state, bool *ret_idle); /** * \ingroup BrickletNFC * * Starts the discovery process. If you call this function while another NFC * P2P enabled device is near to the NFC Bricklet the state will change from * *P2PDiscovery* to *P2PDiscoveryReady*. * * If no NFC P2P enabled device can be found or if there is an error during * discovery the P2P state will change to *P2PDiscoveryError*. In this case you * have to restart the discovery process. * * If the P2P state changes to *P2PDiscoveryReady* you can start the NDEF message * transfer with {@link nfc_p2p_start_transfer}. */ int nfc_p2p_start_discovery(NFC *nfc); /** * \ingroup BrickletNFC * * Writes the NDEF messages that is to be transferred to the NFC peer. * * The maximum supported NDEF message size for P2P transfer is 255 byte. * * You can call this function at any time in P2P mode. The internal buffer * will not be overwritten until you call this function again, change the * mode or use P2P to read an NDEF messages. */ int nfc_p2p_write_ndef_low_level(NFC *nfc, uint16_t ndef_length, uint16_t ndef_chunk_offset, uint8_t ndef_chunk_data[60]); /** * \ingroup BrickletNFC * * You can start the transfer of a NDEF message if the P2P state is *P2PDiscoveryReady*. * * Before you call this function to start a write transfer, the NDEF message that * is to be transferred has to be written via {@link nfc_p2p_write_ndef} first. * * After you call this function the P2P state will change to *P2PTransferNDEF*. It will * change to *P2PTransferNDEFReady* if the transfer was successfull or * *P2PTransferNDEFError* if it wasn't. * * If you started a write transfer you are now done. If you started a read transfer * you can now use {@link nfc_p2p_read_ndef} to read the NDEF message that was written * by the NFC peer. */ int nfc_p2p_start_transfer(NFC *nfc, uint8_t transfer); /** * \ingroup BrickletNFC * * Returns the NDEF message that was written by a NFC peer in NFC P2P mode. * The maximum NDEF length is 8192 byte. * * The NDEF message is ready if you called {@link nfc_p2p_start_transfer} with a * read transfer and the P2P state changed to *P2PTransferNDEFReady*. */ int nfc_p2p_read_ndef_low_level(NFC *nfc, uint16_t *ret_ndef_length, uint16_t *ret_ndef_chunk_offset, uint8_t ret_ndef_chunk_data[60]); /** * \ingroup BrickletNFC * * Sets the detection LED configuration. By default the LED shows * if a card/reader is detected. * * You can also turn the LED permanently on/off or show a heartbeat. * * If the Bricklet is in bootloader mode, the LED is off. */ int nfc_set_detection_led_config(NFC *nfc, uint8_t config); /** * \ingroup BrickletNFC * * Returns the configuration as set by {@link nfc_set_detection_led_config} */ int nfc_get_detection_led_config(NFC *nfc, uint8_t *ret_config); /** * \ingroup BrickletNFC * * Sets the maximum timeout in ms. * * This is a global maximum used for all internal state timeouts. The timeouts depend heavily * on the used tags etc. For example: If you use a Type 2 tag and you want to detect if * it is present, you have to use {@link nfc_reader_request_tag_id} and wait for the state * to change to either the error state or the ready state. * * With the default configuration this takes 2-3 seconds. By setting the maximum timeout to * 100ms you can reduce this time to ~150-200ms. For Type 2 this would also still work * with a 20ms timeout (a Type 2 tag answers usually within 10ms). A type 4 tag can take * up to 500ms in our tests. * * If you need a fast response time to discover if a tag is present or not you can find * a good timeout value by trial and error for your specific tag. * * By default we use a very conservative timeout, to be sure that any Tag can always * answer in time. * * Default timeout: 2000ms. * * .. versionadded:: 2.0.1$nbsp;(Plugin) */ int nfc_set_maximum_timeout(NFC *nfc, uint16_t timeout); /** * \ingroup BrickletNFC * * Returns the timeout as set by {@link nfc_set_maximum_timeout} * * .. versionadded:: 2.0.1$nbsp;(Plugin) */ int nfc_get_maximum_timeout(NFC *nfc, uint16_t *ret_timeout); /** * \ingroup BrickletNFC * * Returns the error count for the communication between Brick and Bricklet. * * The errors are divided into * * * ACK checksum errors, * * message checksum errors, * * framing errors and * * overflow errors. * * The errors counts are for errors that occur on the Bricklet side. All * Bricks have a similar function that returns the errors on the Brick side. */ int nfc_get_spitfp_error_count(NFC *nfc, uint32_t *ret_error_count_ack_checksum, uint32_t *ret_error_count_message_checksum, uint32_t *ret_error_count_frame, uint32_t *ret_error_count_overflow); /** * \ingroup BrickletNFC * * Sets the bootloader mode and returns the status after the requested * mode change was instigated. * * You can change from bootloader mode to firmware mode and vice versa. A change * from bootloader mode to firmware mode will only take place if the entry function, * device identifier and CRC are present and correct. * * This function is used by Brick Viewer during flashing. It should not be * necessary to call it in a normal user program. */ int nfc_set_bootloader_mode(NFC *nfc, uint8_t mode, uint8_t *ret_status); /** * \ingroup BrickletNFC * * Returns the current bootloader mode, see {@link nfc_set_bootloader_mode}. */ int nfc_get_bootloader_mode(NFC *nfc, uint8_t *ret_mode); /** * \ingroup BrickletNFC * * Sets the firmware pointer for {@link nfc_write_firmware}. The pointer has * to be increased by chunks of size 64. The data is written to flash * every 4 chunks (which equals to one page of size 256). * * This function is used by Brick Viewer during flashing. It should not be * necessary to call it in a normal user program. */ int nfc_set_write_firmware_pointer(NFC *nfc, uint32_t pointer); /** * \ingroup BrickletNFC * * Writes 64 Bytes of firmware at the position as written by * {@link nfc_set_write_firmware_pointer} before. The firmware is written * to flash every 4 chunks. * * You can only write firmware in bootloader mode. * * This function is used by Brick Viewer during flashing. It should not be * necessary to call it in a normal user program. */ int nfc_write_firmware(NFC *nfc, uint8_t data[64], uint8_t *ret_status); /** * \ingroup BrickletNFC * * Sets the status LED configuration. By default the LED shows * communication traffic between Brick and Bricklet, it flickers once * for every 10 received data packets. * * You can also turn the LED permanently on/off or show a heartbeat. * * If the Bricklet is in bootloader mode, the LED is will show heartbeat by default. */ int nfc_set_status_led_config(NFC *nfc, uint8_t config); /** * \ingroup BrickletNFC * * Returns the configuration as set by {@link nfc_set_status_led_config} */ int nfc_get_status_led_config(NFC *nfc, uint8_t *ret_config); /** * \ingroup BrickletNFC * * Returns the temperature in °C as measured inside the microcontroller. The * value returned is not the ambient temperature! * * The temperature is only proportional to the real temperature and it has bad * accuracy. Practically it is only useful as an indicator for * temperature changes. */ int nfc_get_chip_temperature(NFC *nfc, int16_t *ret_temperature); /** * \ingroup BrickletNFC * * Calling this function will reset the Bricklet. All configurations * will be lost. * * After a reset you have to create new device objects, * calling functions on the existing ones will result in * undefined behavior! */ int nfc_reset(NFC *nfc); /** * \ingroup BrickletNFC * * Writes a new UID into flash. If you want to set a new UID * you have to decode the Base58 encoded UID string into an * integer first. * * We recommend that you use Brick Viewer to change the UID. */ int nfc_write_uid(NFC *nfc, uint32_t uid); /** * \ingroup BrickletNFC * * Returns the current UID as an integer. Encode as * Base58 to get the usual string version. */ int nfc_read_uid(NFC *nfc, uint32_t *ret_uid); /** * \ingroup BrickletNFC * * Returns the UID, the UID where the Bricklet is connected to, * the position, the hardware and firmware version as well as the * device identifier. * * The position can be 'a', 'b', 'c' or 'd'. * * The device identifier numbers can be found :ref:`here <device_identifier>`. * |device_identifier_constant| */ int nfc_get_identity(NFC *nfc, char ret_uid[8], char ret_connected_uid[8], char *ret_position, uint8_t ret_hardware_version[3], uint8_t ret_firmware_version[3], uint16_t *ret_device_identifier); /** * \ingroup BrickletNFC * * Returns the tag type and the tag ID. This function can only be called if the * NFC Bricklet is currently in one of the *ReaderReady* states. The returned tag ID * is the tag ID that was saved through the last call of {@link nfc_reader_request_tag_id}. * * To get the tag ID of a tag the approach is as follows: * * 1. Call {@link nfc_reader_request_tag_id} * 2. Wait for state to change to *ReaderRequestTagIDReady* (see {@link nfc_reader_get_state} or * {@link NFC_CALLBACK_READER_STATE_CHANGED} callback) * 3. Call {@link nfc_reader_get_tag_id} */ int nfc_reader_get_tag_id(NFC *nfc, uint8_t *ret_tag_type, uint8_t *ret_tag_id, uint8_t *ret_tag_id_length); /** * \ingroup BrickletNFC * * Writes NDEF formated data with a maximum of 255 bytes. * * This function currently supports NFC Forum Type 2 and 4. * * The general approach for writing a NDEF message is as follows: * * 1. Call {@link nfc_reader_request_tag_id} * 2. Wait for state to change to *ReaderRequestTagIDReady* (see * {@link nfc_reader_get_state} or {@link NFC_CALLBACK_READER_STATE_CHANGED} callback) * 3. If looking for a specific tag then call {@link nfc_reader_get_tag_id} and check * if the expected tag was found, if it was not found got back to step 1 * 4. Call {@link nfc_reader_write_ndef} with the NDEF message that you want to write * 5. Wait for state to change to *ReaderWriteNDEFReady* (see {@link nfc_reader_get_state} * or {@link NFC_CALLBACK_READER_STATE_CHANGED} callback) */ int nfc_reader_write_ndef(NFC *nfc, uint8_t *ndef, uint16_t ndef_length); /** * \ingroup BrickletNFC * * Returns the NDEF data from an internal buffer. To fill the buffer * with a NDEF message you have to call {@link nfc_reader_request_ndef} beforehand. * * The buffer can have a size of up to 8192 bytes. */ int nfc_reader_read_ndef(NFC *nfc, uint8_t *ret_ndef, uint16_t *ret_ndef_length); /** * \ingroup BrickletNFC * * Writes a maximum of 8192 bytes starting from the given page. How many pages are written * depends on the tag type. The page sizes are as follows: * * * Mifare Classic page size: 16 byte * * NFC Forum Type 1 page size: 8 byte * * NFC Forum Type 2 page size: 4 byte * * NFC Forum Type 3 page size: 16 byte * * NFC Forum Type 4: No pages, page = file selection (CC or NDEF, see below) * * The general approach for writing to a tag is as follows: * * 1. Call {@link nfc_reader_request_tag_id} * 2. Wait for state to change to *ReaderRequestTagIDReady* (see {@link nfc_reader_get_state} or * {@link NFC_CALLBACK_READER_STATE_CHANGED} callback) * 3. If looking for a specific tag then call {@link nfc_reader_get_tag_id} and check if the * expected tag was found, if it was not found got back to step 1 * 4. Call {@link nfc_reader_write_page} with page number and data * 5. Wait for state to change to *ReaderWritePageReady* (see {@link nfc_reader_get_state} or * {@link NFC_CALLBACK_READER_STATE_CHANGED} callback) * * If you use a Mifare Classic tag you have to authenticate a page before you * can write to it. See {@link nfc_reader_authenticate_mifare_classic_page}. * * NFC Forum Type 4 tags are not organized into pages but different files. We currently * support two files: Capability Container file (CC) and NDEF file. * * Choose CC by setting page to 3 or NDEF by setting page to 4. */ int nfc_reader_write_page(NFC *nfc, uint16_t page, uint8_t *data, uint16_t data_length); /** * \ingroup BrickletNFC * * Returns the page data from an internal buffer. To fill the buffer * with specific pages you have to call {@link nfc_reader_request_page} beforehand. * * The buffer can have a size of up to 8192 bytes. */ int nfc_reader_read_page(NFC *nfc, uint8_t *ret_data, uint16_t *ret_data_length); /** * \ingroup BrickletNFC * * Writes the NDEF messages that is to be transferred to the NFC peer. * * The maximum supported NDEF message size in Cardemu mode is 255 byte. * * You can call this function at any time in Cardemu mode. The internal buffer * will not be overwritten until you call this function again or change the * mode. */ int nfc_cardemu_write_ndef(NFC *nfc, uint8_t *ndef, uint16_t ndef_length); /** * \ingroup BrickletNFC * * Writes the NDEF messages that is to be transferred to the NFC peer. * * The maximum supported NDEF message size for P2P transfer is 255 byte. * * You can call this function at any time in P2P mode. The internal buffer * will not be overwritten until you call this function again, change the * mode or use P2P to read an NDEF messages. */ int nfc_p2p_write_ndef(NFC *nfc, uint8_t *ndef, uint16_t ndef_length); /** * \ingroup BrickletNFC * * Returns the NDEF message that was written by a NFC peer in NFC P2P mode. * The maximum NDEF length is 8192 byte. * * The NDEF message is ready if you called {@link nfc_p2p_start_transfer} with a * read transfer and the P2P state changed to *P2PTransferNDEFReady*. */ int nfc_p2p_read_ndef(NFC *nfc, uint8_t *ret_ndef, uint16_t *ret_ndef_length); #ifdef __cplusplus } #endif #endif
29.050685
194
0.738129
0ba0137c14afba07628956d692ec9930dbf356ba
1,361
h
C
ShenShengYi/platform/School/include/School.h
shenshengyi/ShenShengYi
0b16b555d498c0bd17dd16f830343a5f2a1fd4e1
[ "MIT" ]
null
null
null
ShenShengYi/platform/School/include/School.h
shenshengyi/ShenShengYi
0b16b555d498c0bd17dd16f830343a5f2a1fd4e1
[ "MIT" ]
null
null
null
ShenShengYi/platform/School/include/School.h
shenshengyi/ShenShengYi
0b16b555d498c0bd17dd16f830343a5f2a1fd4e1
[ "MIT" ]
null
null
null
#pragma once #ifdef SCHOOL_DYNAMIC_LIBRARY #define CLASS_DECLSPEC __declspec(dllexport) #else #define CLASS_DECLSPEC __declspec(dllimport) #endif #define GLOG_NO_ABBREVIATED_SEVERITIES #include <utility> #include <folly/FBVector.h> #include <glog/logging.h> namespace STU { class Student; class IDataSource; class Configuration; class CLASS_DECLSPEC School { public: ~School(void); static School* GetInstance(); static void Release(void); void setM(int x) { m = x; } int test(void)const { return m; } void AddStudent(bool isSort = true); int GetStudentNum(void)const; int GetClassNumber(void)const; Student** StudentIteratorBegin(void); Student** StudentIteratorEnd(void); Student*const* StudentIteratorBegin(void)const; Student* const* StudentIteratorEnd(void)const; Student* FindStudentByNum(int Num)const; folly::fbvector<Student*> FindStudentByClassNum(int classNum)const; private: void SortByStudentToScore(void); void init(void); void AddStudentInformation(void); void AddStudentName(void); School(void); School(const School&) = delete; School& operator=(const School&) = delete; School(School&&) noexcept = default; School& operator=(School&&)noexcept = delete; int m; static School* _School; IDataSource* _DataSource; folly::fbvector<Student*> _StudentList; }; }
23.067797
69
0.737693
47fc2df1a3ab14205284768f27239d851e655558
1,284
h
C
TmfBase/Hapy/src/include/Hapy/Assert.h
b4ldr/dsc-collector
ab788f9e2bb27f322e71b5eaf156eae8fba6b992
[ "BSD-3-Clause" ]
null
null
null
TmfBase/Hapy/src/include/Hapy/Assert.h
b4ldr/dsc-collector
ab788f9e2bb27f322e71b5eaf156eae8fba6b992
[ "BSD-3-Clause" ]
null
null
null
TmfBase/Hapy/src/include/Hapy/Assert.h
b4ldr/dsc-collector
ab788f9e2bb27f322e71b5eaf156eae8fba6b992
[ "BSD-3-Clause" ]
null
null
null
/* Hapy is a public domain software. See Hapy README file for the details. */ #ifndef HAPY_ASSERT__H #define HAPY_ASSERT__H #include <Hapy/Top.h> // our version of assert(3), mostly for portability purposes #ifndef Assert #define Assert(cond) ((cond) ? (void)0 : Hapy::Abort(__FILE__, __LINE__, #cond)) #endif // same as Assert but calls Exit instead of Abort #ifndef Check #define Check(cond) ((cond) ? (void)0 : Hapy::Exit(__FILE__, __LINE__, #cond)) #endif // logs current error to cerr and exits if cond fails #ifndef Must #define Must(cond) ((cond) || Hapy::Complain(__FILE__, __LINE__) || Hapy::Exit()) #endif // logs current error to cerr if cond fails #ifndef Should #define Should(cond) ((cond) || Hapy::Complain(__FILE__, __LINE__)) #endif // handy for temporary debugging #ifndef here #define here __FILE__ << ':' << __LINE__ << ": " #endif /* internal functions used by macros above */ namespace Hapy { // logs current err to cerr extern bool Complain(const char *fname, int lineno); // aborts program execution and generates coredump extern void Abort(const char *fname, int lineno, const char *cond); // aborts program execution without coredump extern bool Exit(const char *fname, int lineno, const char *cond); extern bool Exit(); } // namespace #endif
25.176471
81
0.721963
841229dcbca108f49f7abaa1a5adb46cec19beeb
14,988
c
C
sound/soc/codecs/adau7118.c
CPU-Code/-Linux_kernel
44dc3358bc640197528f5b10dbed0fd3717af65b
[ "AFL-3.0" ]
44
2022-03-16T08:32:31.000Z
2022-03-31T16:02:35.000Z
sound/soc/codecs/adau7118.c
CPU-Code/-Linux_kernel
44dc3358bc640197528f5b10dbed0fd3717af65b
[ "AFL-3.0" ]
13
2021-07-10T04:36:17.000Z
2022-03-03T10:50:05.000Z
sound/soc/codecs/adau7118.c
CPU-Code/-Linux_kernel
44dc3358bc640197528f5b10dbed0fd3717af65b
[ "AFL-3.0" ]
18
2022-03-19T04:41:04.000Z
2022-03-31T03:32:12.000Z
// SPDX-License-Identifier: GPL-2.0 // // Analog Devices ADAU7118 8 channel PDM-to-I2S/TDM Converter driver // // Copyright 2019 Analog Devices Inc. #include <linux/bitfield.h> #include <linux/module.h> #include <linux/regmap.h> #include <linux/regulator/consumer.h> #include <sound/pcm_params.h> #include <sound/soc.h> #include "adau7118.h" #define ADAU7118_DEC_RATIO_MASK GENMASK(1, 0) #define ADAU7118_DEC_RATIO(x) FIELD_PREP(ADAU7118_DEC_RATIO_MASK, x) #define ADAU7118_CLK_MAP_MASK GENMASK(7, 4) #define ADAU7118_SLOT_WIDTH_MASK GENMASK(5, 4) #define ADAU7118_SLOT_WIDTH(x) FIELD_PREP(ADAU7118_SLOT_WIDTH_MASK, x) #define ADAU7118_TRISTATE_MASK BIT(6) #define ADAU7118_TRISTATE(x) FIELD_PREP(ADAU7118_TRISTATE_MASK, x) #define ADAU7118_DATA_FMT_MASK GENMASK(3, 1) #define ADAU7118_DATA_FMT(x) FIELD_PREP(ADAU7118_DATA_FMT_MASK, x) #define ADAU7118_SAI_MODE_MASK BIT(0) #define ADAU7118_SAI_MODE(x) FIELD_PREP(ADAU7118_SAI_MODE_MASK, x) #define ADAU7118_LRCLK_BCLK_POL_MASK GENMASK(1, 0) #define ADAU7118_LRCLK_BCLK_POL(x) \ FIELD_PREP(ADAU7118_LRCLK_BCLK_POL_MASK, x) #define ADAU7118_SPT_SLOT_MASK GENMASK(7, 4) #define ADAU7118_SPT_SLOT(x) FIELD_PREP(ADAU7118_SPT_SLOT_MASK, x) #define ADAU7118_FULL_SOFT_R_MASK BIT(1) #define ADAU7118_FULL_SOFT_R(x) FIELD_PREP(ADAU7118_FULL_SOFT_R_MASK, x) struct adau7118_data { struct regmap *map; struct device *dev; struct regulator *iovdd; struct regulator *dvdd; u32 slot_width; u32 slots; bool hw_mode; bool right_j; }; /* Input Enable */ static const struct snd_kcontrol_new adau7118_dapm_pdm_control[4] = { SOC_DAPM_SINGLE("Capture Switch", ADAU7118_REG_ENABLES, 0, 1, 0), SOC_DAPM_SINGLE("Capture Switch", ADAU7118_REG_ENABLES, 1, 1, 0), SOC_DAPM_SINGLE("Capture Switch", ADAU7118_REG_ENABLES, 2, 1, 0), SOC_DAPM_SINGLE("Capture Switch", ADAU7118_REG_ENABLES, 3, 1, 0), }; static const struct snd_soc_dapm_widget adau7118_widgets_sw[] = { /* Input Enable Switches */ SND_SOC_DAPM_SWITCH("PDM0", SND_SOC_NOPM, 0, 0, &adau7118_dapm_pdm_control[0]), SND_SOC_DAPM_SWITCH("PDM1", SND_SOC_NOPM, 0, 0, &adau7118_dapm_pdm_control[1]), SND_SOC_DAPM_SWITCH("PDM2", SND_SOC_NOPM, 0, 0, &adau7118_dapm_pdm_control[2]), SND_SOC_DAPM_SWITCH("PDM3", SND_SOC_NOPM, 0, 0, &adau7118_dapm_pdm_control[3]), /* PDM Clocks */ SND_SOC_DAPM_SUPPLY("PDM_CLK0", ADAU7118_REG_ENABLES, 4, 0, NULL, 0), SND_SOC_DAPM_SUPPLY("PDM_CLK1", ADAU7118_REG_ENABLES, 5, 0, NULL, 0), /* Output channels */ SND_SOC_DAPM_AIF_OUT("AIF1TX1", "Capture", 0, ADAU7118_REG_SPT_CX(0), 0, 0), SND_SOC_DAPM_AIF_OUT("AIF1TX2", "Capture", 0, ADAU7118_REG_SPT_CX(1), 0, 0), SND_SOC_DAPM_AIF_OUT("AIF1TX3", "Capture", 0, ADAU7118_REG_SPT_CX(2), 0, 0), SND_SOC_DAPM_AIF_OUT("AIF1TX4", "Capture", 0, ADAU7118_REG_SPT_CX(3), 0, 0), SND_SOC_DAPM_AIF_OUT("AIF1TX5", "Capture", 0, ADAU7118_REG_SPT_CX(4), 0, 0), SND_SOC_DAPM_AIF_OUT("AIF1TX6", "Capture", 0, ADAU7118_REG_SPT_CX(5), 0, 0), SND_SOC_DAPM_AIF_OUT("AIF1TX7", "Capture", 0, ADAU7118_REG_SPT_CX(6), 0, 0), SND_SOC_DAPM_AIF_OUT("AIF1TX8", "Capture", 0, ADAU7118_REG_SPT_CX(7), 0, 0), }; static const struct snd_soc_dapm_route adau7118_routes_sw[] = { { "PDM0", "Capture Switch", "PDM_DAT0" }, { "PDM1", "Capture Switch", "PDM_DAT1" }, { "PDM2", "Capture Switch", "PDM_DAT2" }, { "PDM3", "Capture Switch", "PDM_DAT3" }, { "AIF1TX1", NULL, "PDM0" }, { "AIF1TX2", NULL, "PDM0" }, { "AIF1TX3", NULL, "PDM1" }, { "AIF1TX4", NULL, "PDM1" }, { "AIF1TX5", NULL, "PDM2" }, { "AIF1TX6", NULL, "PDM2" }, { "AIF1TX7", NULL, "PDM3" }, { "AIF1TX8", NULL, "PDM3" }, { "Capture", NULL, "PDM_CLK0" }, { "Capture", NULL, "PDM_CLK1" }, }; static const struct snd_soc_dapm_widget adau7118_widgets_hw[] = { SND_SOC_DAPM_AIF_OUT("AIF1TX", "Capture", 0, SND_SOC_NOPM, 0, 0), }; static const struct snd_soc_dapm_route adau7118_routes_hw[] = { { "AIF1TX", NULL, "PDM_DAT0" }, { "AIF1TX", NULL, "PDM_DAT1" }, { "AIF1TX", NULL, "PDM_DAT2" }, { "AIF1TX", NULL, "PDM_DAT3" }, }; static const struct snd_soc_dapm_widget adau7118_widgets[] = { SND_SOC_DAPM_INPUT("PDM_DAT0"), SND_SOC_DAPM_INPUT("PDM_DAT1"), SND_SOC_DAPM_INPUT("PDM_DAT2"), SND_SOC_DAPM_INPUT("PDM_DAT3"), }; static int adau7118_set_channel_map(struct snd_soc_dai *dai, unsigned int tx_num, unsigned int *tx_slot, unsigned int rx_num, unsigned int *rx_slot) { struct adau7118_data *st = snd_soc_component_get_drvdata(dai->component); int chan, ret; dev_dbg(st->dev, "Set channel map, %d", tx_num); for (chan = 0; chan < tx_num; chan++) { ret = snd_soc_component_update_bits(dai->component, ADAU7118_REG_SPT_CX(chan), ADAU7118_SPT_SLOT_MASK, ADAU7118_SPT_SLOT(tx_slot[chan])); if (ret < 0) return ret; } return 0; } static int adau7118_set_fmt(struct snd_soc_dai *dai, unsigned int fmt) { struct adau7118_data *st = snd_soc_component_get_drvdata(dai->component); int ret = 0; u32 regval; dev_dbg(st->dev, "Set format, fmt:%d\n", fmt); switch (fmt & SND_SOC_DAIFMT_FORMAT_MASK) { case SND_SOC_DAIFMT_I2S: ret = snd_soc_component_update_bits(dai->component, ADAU7118_REG_SPT_CTRL1, ADAU7118_DATA_FMT_MASK, ADAU7118_DATA_FMT(0)); break; case SND_SOC_DAIFMT_LEFT_J: ret = snd_soc_component_update_bits(dai->component, ADAU7118_REG_SPT_CTRL1, ADAU7118_DATA_FMT_MASK, ADAU7118_DATA_FMT(1)); break; case SND_SOC_DAIFMT_RIGHT_J: st->right_j = true; break; default: dev_err(st->dev, "Invalid format %d", fmt & SND_SOC_DAIFMT_FORMAT_MASK); return -EINVAL; } if (ret < 0) return ret; switch (fmt & SND_SOC_DAIFMT_INV_MASK) { case SND_SOC_DAIFMT_NB_NF: regval = ADAU7118_LRCLK_BCLK_POL(0); break; case SND_SOC_DAIFMT_NB_IF: regval = ADAU7118_LRCLK_BCLK_POL(2); break; case SND_SOC_DAIFMT_IB_NF: regval = ADAU7118_LRCLK_BCLK_POL(1); break; case SND_SOC_DAIFMT_IB_IF: regval = ADAU7118_LRCLK_BCLK_POL(3); break; default: dev_err(st->dev, "Invalid Inv mask %d", fmt & SND_SOC_DAIFMT_INV_MASK); return -EINVAL; } ret = snd_soc_component_update_bits(dai->component, ADAU7118_REG_SPT_CTRL2, ADAU7118_LRCLK_BCLK_POL_MASK, regval); if (ret < 0) return ret; return 0; } static int adau7118_set_tristate(struct snd_soc_dai *dai, int tristate) { struct adau7118_data *st = snd_soc_component_get_drvdata(dai->component); int ret; dev_dbg(st->dev, "Set tristate, %d\n", tristate); ret = snd_soc_component_update_bits(dai->component, ADAU7118_REG_SPT_CTRL1, ADAU7118_TRISTATE_MASK, ADAU7118_TRISTATE(tristate)); if (ret < 0) return ret; return 0; } static int adau7118_set_tdm_slot(struct snd_soc_dai *dai, unsigned int tx_mask, unsigned int rx_mask, int slots, int slot_width) { struct adau7118_data *st = snd_soc_component_get_drvdata(dai->component); int ret = 0; u32 regval; dev_dbg(st->dev, "Set tdm, slots:%d width:%d\n", slots, slot_width); switch (slot_width) { case 32: regval = ADAU7118_SLOT_WIDTH(0); break; case 24: regval = ADAU7118_SLOT_WIDTH(2); break; case 16: regval = ADAU7118_SLOT_WIDTH(1); break; default: dev_err(st->dev, "Invalid slot width:%d\n", slot_width); return -EINVAL; } ret = snd_soc_component_update_bits(dai->component, ADAU7118_REG_SPT_CTRL1, ADAU7118_SLOT_WIDTH_MASK, regval); if (ret < 0) return ret; st->slot_width = slot_width; st->slots = slots; return 0; } static int adau7118_hw_params(struct snd_pcm_substream *substream, struct snd_pcm_hw_params *params, struct snd_soc_dai *dai) { struct adau7118_data *st = snd_soc_component_get_drvdata(dai->component); u32 data_width = params_width(params), slots_width; int ret; u32 regval; if (!st->slots) { /* set stereo mode */ ret = snd_soc_component_update_bits(dai->component, ADAU7118_REG_SPT_CTRL1, ADAU7118_SAI_MODE_MASK, ADAU7118_SAI_MODE(0)); if (ret < 0) return ret; slots_width = 32; } else { slots_width = st->slot_width; } if (data_width > slots_width) { dev_err(st->dev, "Invalid data_width:%d, slots_width:%d", data_width, slots_width); return -EINVAL; } if (st->right_j) { switch (slots_width - data_width) { case 8: /* delay bclck by 8 */ regval = ADAU7118_DATA_FMT(2); break; case 12: /* delay bclck by 12 */ regval = ADAU7118_DATA_FMT(3); break; case 16: /* delay bclck by 16 */ regval = ADAU7118_DATA_FMT(4); break; default: dev_err(st->dev, "Cannot set right_j setting, slot_w:%d, data_w:%d\n", slots_width, data_width); return -EINVAL; } ret = snd_soc_component_update_bits(dai->component, ADAU7118_REG_SPT_CTRL1, ADAU7118_DATA_FMT_MASK, regval); if (ret < 0) return ret; } return 0; } static int adau7118_set_bias_level(struct snd_soc_component *component, enum snd_soc_bias_level level) { struct adau7118_data *st = snd_soc_component_get_drvdata(component); int ret = 0; dev_dbg(st->dev, "Set bias level %d\n", level); switch (level) { case SND_SOC_BIAS_ON: case SND_SOC_BIAS_PREPARE: break; case SND_SOC_BIAS_STANDBY: if (snd_soc_component_get_bias_level(component) == SND_SOC_BIAS_OFF) { /* power on */ ret = regulator_enable(st->iovdd); if (ret) return ret; /* there's no timing constraints before enabling dvdd */ ret = regulator_enable(st->dvdd); if (ret) { regulator_disable(st->iovdd); return ret; } if (st->hw_mode) return 0; regcache_cache_only(st->map, false); /* sync cache */ ret = snd_soc_component_cache_sync(component); } break; case SND_SOC_BIAS_OFF: /* power off */ ret = regulator_disable(st->dvdd); if (ret) return ret; ret = regulator_disable(st->iovdd); if (ret) return ret; if (st->hw_mode) return 0; /* cache only */ regcache_mark_dirty(st->map); regcache_cache_only(st->map, true); break; } return ret; } static int adau7118_component_probe(struct snd_soc_component *component) { struct adau7118_data *st = snd_soc_component_get_drvdata(component); struct snd_soc_dapm_context *dapm = snd_soc_component_get_dapm(component); int ret = 0; if (st->hw_mode) { ret = snd_soc_dapm_new_controls(dapm, adau7118_widgets_hw, ARRAY_SIZE(adau7118_widgets_hw)); if (ret) return ret; ret = snd_soc_dapm_add_routes(dapm, adau7118_routes_hw, ARRAY_SIZE(adau7118_routes_hw)); } else { snd_soc_component_init_regmap(component, st->map); ret = snd_soc_dapm_new_controls(dapm, adau7118_widgets_sw, ARRAY_SIZE(adau7118_widgets_sw)); if (ret) return ret; ret = snd_soc_dapm_add_routes(dapm, adau7118_routes_sw, ARRAY_SIZE(adau7118_routes_sw)); } return ret; } static const struct snd_soc_dai_ops adau7118_ops = { .hw_params = adau7118_hw_params, .set_channel_map = adau7118_set_channel_map, .set_fmt = adau7118_set_fmt, .set_tdm_slot = adau7118_set_tdm_slot, .set_tristate = adau7118_set_tristate, }; static struct snd_soc_dai_driver adau7118_dai = { .name = "adau7118-hifi-capture", .capture = { .stream_name = "Capture", .channels_min = 1, .channels_max = 8, .formats = SNDRV_PCM_FMTBIT_S16_LE | SNDRV_PCM_FMTBIT_S20_3LE | SNDRV_PCM_FMTBIT_S20_LE | SNDRV_PCM_FMTBIT_S24_LE | SNDRV_PCM_FMTBIT_S24_3LE, .rates = SNDRV_PCM_RATE_CONTINUOUS, .rate_min = 4000, .rate_max = 192000, .sig_bits = 24, }, }; static const struct snd_soc_component_driver adau7118_component_driver = { .probe = adau7118_component_probe, .set_bias_level = adau7118_set_bias_level, .dapm_widgets = adau7118_widgets, .num_dapm_widgets = ARRAY_SIZE(adau7118_widgets), .use_pmdown_time = 1, .endianness = 1, .non_legacy_dai_naming = 1, }; static void adau7118_regulator_disable(void *data) { struct adau7118_data *st = data; int ret; /* * If we fail to disable DVDD, don't bother in trying IOVDD. We * actually don't want to be left in the situation where DVDD * is enabled and IOVDD is disabled. */ ret = regulator_disable(st->dvdd); if (ret) return; regulator_disable(st->iovdd); } static int adau7118_regulator_setup(struct adau7118_data *st) { st->iovdd = devm_regulator_get(st->dev, "iovdd"); if (IS_ERR(st->iovdd)) { dev_err(st->dev, "Could not get iovdd: %ld\n", PTR_ERR(st->iovdd)); return PTR_ERR(st->iovdd); } st->dvdd = devm_regulator_get(st->dev, "dvdd"); if (IS_ERR(st->dvdd)) { dev_err(st->dev, "Could not get dvdd: %ld\n", PTR_ERR(st->dvdd)); return PTR_ERR(st->dvdd); } /* just assume the device is in reset */ if (!st->hw_mode) { regcache_mark_dirty(st->map); regcache_cache_only(st->map, true); } return devm_add_action_or_reset(st->dev, adau7118_regulator_disable, st); } static int adau7118_parset_dt(const struct adau7118_data *st) { int ret; u32 dec_ratio = 0; /* 4 inputs */ u32 clk_map[4], regval; if (st->hw_mode) return 0; ret = device_property_read_u32(st->dev, "adi,decimation-ratio", &dec_ratio); if (!ret) { switch (dec_ratio) { case 64: regval = ADAU7118_DEC_RATIO(0); break; case 32: regval = ADAU7118_DEC_RATIO(1); break; case 16: regval = ADAU7118_DEC_RATIO(2); break; default: dev_err(st->dev, "Invalid dec ratio: %u", dec_ratio); return -EINVAL; } ret = regmap_update_bits(st->map, ADAU7118_REG_DEC_RATIO_CLK_MAP, ADAU7118_DEC_RATIO_MASK, regval); if (ret) return ret; } ret = device_property_read_u32_array(st->dev, "adi,pdm-clk-map", clk_map, ARRAY_SIZE(clk_map)); if (!ret) { int pdm; u32 _clk_map = 0; for (pdm = 0; pdm < ARRAY_SIZE(clk_map); pdm++) _clk_map |= (clk_map[pdm] << (pdm + 4)); ret = regmap_update_bits(st->map, ADAU7118_REG_DEC_RATIO_CLK_MAP, ADAU7118_CLK_MAP_MASK, _clk_map); if (ret) return ret; } return 0; } int adau7118_probe(struct device *dev, struct regmap *map, bool hw_mode) { struct adau7118_data *st; int ret; st = devm_kzalloc(dev, sizeof(*st), GFP_KERNEL); if (!st) return -ENOMEM; st->dev = dev; st->hw_mode = hw_mode; dev_set_drvdata(dev, st); if (!hw_mode) { st->map = map; adau7118_dai.ops = &adau7118_ops; /* * Perform a full soft reset. This will set all register's * with their reset values. */ ret = regmap_update_bits(map, ADAU7118_REG_RESET, ADAU7118_FULL_SOFT_R_MASK, ADAU7118_FULL_SOFT_R(1)); if (ret) return ret; } ret = adau7118_parset_dt(st); if (ret) return ret; ret = adau7118_regulator_setup(st); if (ret) return ret; return devm_snd_soc_register_component(dev, &adau7118_component_driver, &adau7118_dai, 1); } EXPORT_SYMBOL_GPL(adau7118_probe); MODULE_AUTHOR("Nuno Sa <nuno.sa@analog.com>"); MODULE_DESCRIPTION("ADAU7118 8 channel PDM-to-I2S/TDM Converter driver"); MODULE_LICENSE("GPL");
25.53322
79
0.702295
629e8f393ed47b32b074f6f7715b19f34896e655
531
h
C
Hearth Log/GameLogger.h
chippydip/HearthLog
8f34bd48fdc4cd7a8a69708ff08f5cef07e9fcec
[ "Apache-2.0" ]
12
2015-03-04T09:52:03.000Z
2022-03-29T02:38:39.000Z
Hearth Log/GameLogger.h
chippydip/HearthLog
8f34bd48fdc4cd7a8a69708ff08f5cef07e9fcec
[ "Apache-2.0" ]
2
2016-10-11T19:37:14.000Z
2021-08-29T16:45:22.000Z
Hearth Log/GameLogger.h
chippydip/HearthLog
8f34bd48fdc4cd7a8a69708ff08f5cef07e9fcec
[ "Apache-2.0" ]
5
2015-02-28T14:11:42.000Z
2016-03-23T03:37:25.000Z
#pragma once #include "tcp/Parser.h" #include "tcp/Stream.h" #include <array> #include <memory> #include "range.h" #include <vector> class GameLogger : public tcp::Parser::Callback { public: GameLogger(int64_t nanotime, tcp::Stream *stream); virtual ~GameLogger(); virtual void operator()(int64_t nanotime, std::range<const uint8_t *> data); private: tcp::Stream * const _stream; std::array<uint8_t, 8> _header; std::vector<uint8_t> _message; std::range<uint8_t *> _buffer; class Log; std::shared_ptr<Log> _log; };
18.310345
77
0.713748
a8b0bd474db88c424e881788c4c55844a45bb329
4,185
h
C
SurgSim/Input/InputManager.h
dbungert/opensurgsim
bd30629f2fd83f823632293959b7654275552fa9
[ "Apache-2.0" ]
24
2015-01-19T16:18:59.000Z
2022-03-13T03:29:11.000Z
SurgSim/Input/InputManager.h
dbungert/opensurgsim
bd30629f2fd83f823632293959b7654275552fa9
[ "Apache-2.0" ]
3
2018-12-21T14:54:08.000Z
2022-03-14T12:38:07.000Z
SurgSim/Input/InputManager.h
dbungert/opensurgsim
bd30629f2fd83f823632293959b7654275552fa9
[ "Apache-2.0" ]
8
2015-04-10T19:45:36.000Z
2022-02-02T17:00:59.000Z
// This file is a part of the OpenSurgSim project. // Copyright 2013, SimQuest Solutions 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. #ifndef SURGSIM_INPUT_INPUTMANAGER_H #define SURGSIM_INPUT_INPUTMANAGER_H #include <boost/thread/mutex.hpp> #include <memory> #include <unordered_map> #include <vector> #include "SurgSim/Framework/ComponentManager.h" namespace SurgSim { namespace Input { class DeviceInterface; class InputComponent; class OutputComponent; /// Manager to handle InputComponent and OutputComponent, SceneElement can add these to /// get input from devices, or even write output to devices. The devices have to be added /// to this class before components can be added to it. class InputManager : public SurgSim::Framework::ComponentManager { public: InputManager(); virtual ~InputManager(); friend class InputManagerTest; /// Adds a device to the manager. /// \param device The device. /// \return true if it succeeds, false if the device already exists in the manager. bool addDevice(std::shared_ptr<SurgSim::Input::DeviceInterface> device); /// Removes the device described by device. /// \param device The device. /// \return true if it succeeds, false if the device is not in. bool removeDevice(std::shared_ptr<SurgSim::Input::DeviceInterface> device); int getType() const override; private: bool doInitialize() override; bool doStartUp() override; bool doUpdate(double dt) override; void doBeforeStop() override; /// Adds a component, this can be either input or output, it will call the appropriate /// function in the device. For an InputComonent this will succeed if the device name /// inside the component is known to the InputManager and if the component has not /// been added as an input yet. For an OutputComponent the call will fail if the device /// does not exist or the device has already been assigned an output. /// \param component The component. /// \return true if it succeeds, it will fail if the device cannot be found to the component /// has already been added to the manager, and return false. bool executeAdditions(const std::shared_ptr<SurgSim::Framework::Component>& component) override; /// Removes the component described by component. /// \param component The component. /// \return true if it succeeds, it will fail if the component cannot be found and return false. bool executeRemovals(const std::shared_ptr<SurgSim::Framework::Component>& component) override; /// Specific call for input components. /// Link input consumer to input device /// Data produced by device will then be consumed by input consumer bool addInputComponent(const std::shared_ptr<InputComponent>& input); /// Specific call for output components. bool addOutputComponent(const std::shared_ptr<OutputComponent>& output); /// Returns a device with the given name, if one is available. /// \param name The name of the device. /// \param device [out] The device. Unchanged if the return value is false. /// \return true if the device was found. bool tryFindDevice(const std::string& name, DeviceInterface** device); /// Collection of all input components. std::vector<std::shared_ptr<InputComponent>> m_inputs; /// Collection of all output components. std::vector<std::shared_ptr<OutputComponent>> m_outputs; /// Collection of all devices that have been added to the input manager /// key is the name, no two devices with the same name can be added to the /// input manager std::unordered_map<std::string, std::shared_ptr<SurgSim::Input::DeviceInterface>> m_devices; /// Protect critical sections boost::mutex m_mutex; }; }; //namespace Input }; //namespace SurgSim #endif
38.394495
97
0.755556
2f86e444be884c96afda767ecd2a2ed8eeca6fe9
240
h
C
VirtualNum/VirtualNum/Modules/Home/Controller/ChooseNumViewController.h
SunnyWjw/VirtualNum
cf91d0ef1e76a0dd135f82097d4ce87ba8e3ddc0
[ "Apache-2.0" ]
null
null
null
VirtualNum/VirtualNum/Modules/Home/Controller/ChooseNumViewController.h
SunnyWjw/VirtualNum
cf91d0ef1e76a0dd135f82097d4ce87ba8e3ddc0
[ "Apache-2.0" ]
null
null
null
VirtualNum/VirtualNum/Modules/Home/Controller/ChooseNumViewController.h
SunnyWjw/VirtualNum
cf91d0ef1e76a0dd135f82097d4ce87ba8e3ddc0
[ "Apache-2.0" ]
null
null
null
// // ChooseNumViewController.h // VirtualNum // // Created by SunnyWu on 2017/6/25. // Copyright © 2017年 SunnyWu. All rights reserved. // #import "RootViewController.h" @interface ChooseNumViewController : RootViewController @end
15
55
0.729167
2bb2d87a226322dd81a2eb5656d07c8419b4c2be
2,646
h
C
include/fengine/GUI/ViewController/ScrollArea.h
LukasBanana/ForkENGINE
8b575bd1d47741ad5025a499cb87909dbabc3492
[ "BSD-3-Clause" ]
13
2017-03-21T22:46:18.000Z
2020-07-30T01:31:57.000Z
include/fengine/GUI/ViewController/ScrollArea.h
LukasBanana/ForkENGINE
8b575bd1d47741ad5025a499cb87909dbabc3492
[ "BSD-3-Clause" ]
null
null
null
include/fengine/GUI/ViewController/ScrollArea.h
LukasBanana/ForkENGINE
8b575bd1d47741ad5025a499cb87909dbabc3492
[ "BSD-3-Clause" ]
2
2018-07-23T19:56:41.000Z
2020-07-30T01:32:01.000Z
/* * GUI scroll area header * * This file is part of the "ForkENGINE" (Copyright (c) 2014 by Lukas Hermanns) * See "LICENSE.txt" for license information. */ #ifndef __FORK_GUI_SCROLL_AREA_H__ #define __FORK_GUI_SCROLL_AREA_H__ #include "GUI/ViewController/ScrollBar.h" namespace Fork { namespace GUI { //! GUI scroll area class. class FORK_EXPORT ScrollArea : public ViewController { public: /* === Classes === */ //! Scroll area flags enumeration. struct Flags { typedef unsigned int DataType; enum : DataType { VertLeft = (1 << 0), //!< The vertical scroll bar is on the left (otherwise right). HorzTop = (1 << 1), //!< The horizontal scroll bar is on the top (otherwise bottom). }; }; //! Event handler for the frame's scroll bars. class FORK_EXPORT ScrollBarEventHandler : public ScrollBar::ViewEventHandler { public: //! \throws NullPointerException If 'owner' or 'virtualArea' is null. ScrollBarEventHandler(ScrollBar* owner, ViewController* virtualArea); void OnResize(SizeEvent& event) override; protected: void Scroll(int position) override; //! Returns the virtual area view controller. inline ViewController* GetVirtualArea() const { return virtualArea_; } private: ViewController* virtualArea_ = nullptr; }; /* === Functions === */ ScrollArea(); //! Adjusts the child scroll bars. void Resize(Size size) override; //! Changes the frame flags. By default 0. void ChangeFlags(const Flags::DataType flags); /** Sets the virtual area of this scroll area. This will interact with the vertical and horizontal scroll bars. */ void SetupVirtualSize(const Size& size); //! Returns the frame flags. inline Flags::DataType GetFlags() const { return flags_; } //! Specifies the virtual area view controller. ViewController virtualArea; private: void UpdateScrollBars(); /* === Members === */ Flags::DataType flags_ = 0; ScrollBar vertScrollBar_; ScrollBar horzScrollBar_; }; } // /namespace GUI } // /namespace Fork #endif // ========================
22.615385
104
0.542706
44bfa93af7b0fa768bbf322af32a8eea22d4a752
6,929
h
C
include/std/soses.h
Richard-Wai/xeris-I
737586896b2d6d5f28dcfdc90c842c668cd1aad9
[ "BSD-3-Clause" ]
1
2021-08-30T22:31:05.000Z
2021-08-30T22:31:05.000Z
include/std/soses.h
Richard-Wai/xeris-I
737586896b2d6d5f28dcfdc90c842c668cd1aad9
[ "BSD-3-Clause" ]
null
null
null
include/std/soses.h
Richard-Wai/xeris-I
737586896b2d6d5f28dcfdc90c842c668cd1aad9
[ "BSD-3-Clause" ]
null
null
null
/* * XERIS/APEX System I * Autonomous Poly-Executive * * Release 1 * * Copyright (C) 2016, Richard Wai * ALL RIGHTS RESERVED. */ /* * Standard Operational Status and Errors Specification * (xeris?soses*) * std/soses.h */ #ifndef __XERIS_STD_SOSES_H #define __XERIS_STD_SOSES_H /* Specifications */ /************************************************************************** * SPEC 0000 - Universal Operational Status Reporting * **************************************************************************/ #define XSR_OP 0x0000 /* Universal Simple Status Reporting */ #define XSR_OP_S 0x0000 #define XSR_OP_I 0x1000 #define XSR_OP_E 0x3000 #define XSR_OP_F 0x5000 /* OP-S - Information and Status Group */ #define XSR_OP_S_INCP_NOTICE 0x0000 /* Inception Notice */ #define XSR_OP_S_OPR_OK 0x0001 /* Operation Successful */ #define XSR_OP_S_REQUEST_CPL 0x0002 /* Request Complete */ #define XSR_OP_S_READ_ONLY 0x0003 /* Read_Only */ #define XSR_OP_S_WRITE_ONLY 0x0004 /* Write_Only */ #define XSR_OP_S_REQUEST_UKN 0x0005 /* Unknown Request */ #define XSR_OP_S_NOMINAL_ENTRY 0x0006 /* Nominal Entry */ #define XSR_OP_S_AUTH_OK 0x0007 /* Authorization OK */ #define XSR_OP_S_TEST_PASS 0x0008 /* Test Passed */ #define XSR_OP_S_ACCEPTED 0x0009 /* Submission acccepted */ #define XSR_OP_S_APPROVED 0x000a /* Application Approved */ /* OP-I - Initilization Messages */ #define XSR_OP_I_INIT_NORMAL 0x1000 /* Init Normal */ #define XSR_OP_I_INIT_LEVEL 0x1001 /* Init Level */ #define XSR_OP_I_INIT_ABNORMAL 0x1002 /* Init Abnormal */ #define XSR_OP_I_INIT_FAILSF_LVL 0x1003 /* Init Failsafe Level */ #define XSR_OP_I_INIT_EMERG 0x1004 /* Init Emergency */ #define XSR_OP_I_INIT_RECOVER 0x1005 /* Init Recovery */ #define XSR_OP_I_INIT_DEFERED 0x1006 /* Init Defered */ #define XSR_OP_I_INIT_EMERG_OK 0x1007 /* Emergency Init OK */ #define XSR_OP_I_INIT_ABNORMAL_OK 0x1008 /* Abnormal Init OK */ #define XSR_OP_I_INIT_OK 0x1009 /* Init OK */ #define XSR_OP_I_INIT_PARAM 0x100a /* Init Parameters */ #define XSR_OP_I_INIT_AUTO 0x100b /* Init Autonomous */ #define XSR_OP_I_INIT_INTV 0x100c /* Init Intervention */ #define XSR_OP_I_INIT_LATE 0x100d /* Late Init */ #define XSR_OP_I_INIT_CONFIG 0x100e /* Init configuration */ #define XSR_OP_I_INIT_FAIL 0x100f /* Init failed */ #define XSR_OP_I_INIT_REQUIRED 0x1010 /* Init required */ #define XSR_OP_I_INIT_ILLEGAL 0x1011 /* Init not allowed */ /* OP-E - Non_Fatal Error Messages */ #define XSR_OP_E_OPR_LIMIT 0x3001 /* Operation Limited */ /* OP-F - Fatal Error Messages */ #define XSR_OP_F_INIT_FATAL 0x5000 /* Initialization fatal */ #define XSR_OP_F_RECOVER_FAIL 0x5001 /* Recovery failed */ #define XSR_OP_F_SVC_UNAVAIL 0x5002 /* Service unavilable */ #define XSR_OP_F_NOT_PERMITTED 0x5003 /* Not permitted */ #define XSR_OP_F_ACCESS_DENIED 0x5004 /* Access denied */ #define XSR_OP_F_WRITE_UNABLE 0x5005 /* Unable to write */ #define XSR_OP_F_READ_UNABLE 0x5006 /* Unable to read */ #define XSR_OP_F_INTRFC_UNRSPNSV 0x5007 /* Interface Unresponsive */ #define XSR_OP_F_UNACPT_ORDER 0x5008 /* Unacceptable Work Order*/ #define XSR_OP_F_NO_OPERATOR 0x5009 /* No such operator */ #define XSR_OP_F_OPR_UNAVAIL 0x500a /* Operator unavailable */ #define XSR_OP_F_NO_AUTH 0x500b /* Authorization Failed */ #define XSR_OP_F_TEST_FAIL 0x500c /* Test Failed */ #define XSR_OP_F_PARAM_EXCUR 0x500d /* Parametr out of bounds */ #define XSR_OP_F_DATA_CORRUPT 0x500e /* Data Corruption */ #define XSR_OP_F_EC_UNABLE 0x500f /* Error Correction Fail */ #define XSR_OP_F_VERIFY_FAIL 0x5010 /* Verification Failed */ #define XSR_OP_F_OPTION_UNKN 0x5011 /* Option not recognised */ #define XSR_OP_F_CB_CONFIG 0x5012 /* bad case board config */ #define XSR_OP_F_INSUF_RESRC 0x5013 /* Insufficient Resources */ #define XSR_OP_F_NO_SECRETARIAT 0x5014 /* Secretariat not found */ #define XSR_OP_F_OVERFLOW 0x5015 /* Overflow error */ #define XSR_OP_F_SIGNAL_ERROR 0x5016 /* Signal non-sensical */ #define XSR_OP_F_PROC_VIOL 0x5017 /* Procedure violation */ #define XSR_OP_F_UNDEFINED 0x5018 /* Error not programmed */ #define XSR_OP_F_NO_RECORD 0x5019 /* No record registered */ /************************************************************************** * SPEC 0001 - XERIS/APEX Core Error and Intervention * **************************************************************************/ #define XSR_SYS 0x0001 /* SPEC Code */ #define XSR_SYS_S 0x0000 #define XSR_SYS_I 0x1000 #define XSR_SYS_E 0x3000 #define XSR_SYS_F 0x5000 #define XSR_SYS_P 0x7000 /* Illegal Action */ /* SYS-I - Initialization Messages */ #define XST_SYS_I_INIT_STRAP 0x1000 /* Init bootstrap */ #define XST_SYS_I_INIT_CONFIG 0x1001 /* Init config block */ /* SYS-W - Warning Messages */ #define XSR_SYS_W_ZONE_THRESHOLD 0x2000 /* Stack at zone threshold */ #define XSR_SYS_W_CONFIG_SIZE 0x2001 /* Bad config block size */ #define XSR_SYS_W_NO_CONFIG 0x2002 /* Config block not available */ /* SYS-d - Denial Messages */ #define XSR_SYS_D_NO_TELCOM 0x3000 /* No telemetry commissioner */ /* SYS-C - Critical Error - Intervention Required */ #define XSR_SYS_C_LOCAL_EXCURSION 0x4000 /* Stack breached work area */ /* SYS-F - Fatal Error */ #define XSR_SYS_F_ZONE_EXCURSION 0x5000 /* Stack breaked zone */ #define XSR_SYS_F_EMRG_LOCKDOWN 0x5001 /* Emergency Lockdown */ /* SYS-P - Illegal Action Messages */ #define XSR_SYS_P_CERT_INVALID 0x7000 /* Certificate Invalid */ #define XSR_SYS_P_TX_NO_ACCNT 0x7001 /* No transaction account defined */ #define XSR_SYS_P_TX_EVENT_CON 0x7002 /* Event containment */ #define XSR_SYS_P_SYS_STUB 0x7003 /* SYS stub illegal */ #define XSR_SYS_P_TICKET 0x7004 /* Ticket as submitted is illegal */ /************************************************************************** * Specific Telemetry Encoding Groups * **************************************************************************/ #define XSR_TLM_OPSEC 0x0010 #define XSR_TLM_FLATLINE 0x0011 #define XSR_TLM_ATRIA 0x0012 #define XSR_TLM_SIPLEX 0x0013 #endif
45.887417
78
0.618271
2f3976a2069857189931a54a542238dc2a378143
400
h
C
Tools/TimerWithComm.h
GnarlyMshtep/DORAM
c78f7d516b52046b3105e8b967f048faea6c6fed
[ "BSD-2-Clause" ]
null
null
null
Tools/TimerWithComm.h
GnarlyMshtep/DORAM
c78f7d516b52046b3105e8b967f048faea6c6fed
[ "BSD-2-Clause" ]
3
2022-02-22T16:14:53.000Z
2022-02-22T16:37:41.000Z
Tools/TimerWithComm.h
GnarlyMshtep/DORAM
c78f7d516b52046b3105e8b967f048faea6c6fed
[ "BSD-2-Clause" ]
null
null
null
/* * TimerWithComm.h * */ #ifndef TOOLS_TIMERWITHCOMM_H_ #define TOOLS_TIMERWITHCOMM_H_ #include "time-func.h" #include "Networking/Player.h" class TimerWithComm : public Timer { NamedCommStats total_stats, last_stats; public: void start(const NamedCommStats& stats = {}); void stop(const NamedCommStats& stats = {}); double mb_sent(); }; #endif /* TOOLS_TIMERWITHCOMM_H_ */
16.666667
49
0.7125
2b483b3f5dddffec1a77431b7f25fdc36b6fab76
162
h
C
include/lights.h
nullstare/ReiLua
9598d72b8b9ea038ba80eaa46e04fe25000fe101
[ "MIT" ]
3
2022-02-23T09:07:28.000Z
2022-02-23T15:44:25.000Z
include/lights.h
nullstare/ReiLua
9598d72b8b9ea038ba80eaa46e04fe25000fe101
[ "MIT" ]
null
null
null
include/lights.h
nullstare/ReiLua
9598d72b8b9ea038ba80eaa46e04fe25000fe101
[ "MIT" ]
null
null
null
#pragma once /* Validators. */ bool validLight( size_t id ); /* Basics. */ int llightsCreateLight( lua_State *L ); int llightsUpdateLightValues( lua_State *L );
20.25
45
0.716049
d8ffe2075c4a1217a12b0071e35731ecbd16db97
1,595
h
C
ZYTool/ZYTool.framework/Versions/A/Headers/UserDefaultsTool.h
zengyuios/ZYTool
226ce2070a0defd8bc43726b1c555e7e09dda141
[ "MIT" ]
1
2017-06-23T08:59:11.000Z
2017-06-23T08:59:11.000Z
ZYTool/ZYTool.framework/Versions/A/Headers/UserDefaultsTool.h
zengyuios/ZYTool
226ce2070a0defd8bc43726b1c555e7e09dda141
[ "MIT" ]
null
null
null
ZYTool/ZYTool.framework/Versions/A/Headers/UserDefaultsTool.h
zengyuios/ZYTool
226ce2070a0defd8bc43726b1c555e7e09dda141
[ "MIT" ]
null
null
null
// // UserDefaultsTool.h // // Created by ZY on 16/7/1. // Copyright © 2016年 ZY. All rights reserved. // // UserDefaults #import <Foundation/Foundation.h> #import <CoreGraphics/CGBase.h> /** 本地数据存储. */ @interface UserDefaultsTool : NSObject /** * 设置(保存)对象类型的值. * @param value 要保存的值 * @param key 要保存值的Key */ + (void)setObject:(id)value forKey:(NSString *)key; /** * 设置(保存)布尔类型的值. * @param value 要保存的值 * @param key 要保存值的Key */ + (void)setBool:(BOOL)value forKey:(NSString *)key; /** * 设置(保存)浮点类型的值. * @param value 要保存的值 * @param key 要保存值的Key */ + (void)setFloat:(CGFloat)value forKey:(NSString *)key; /** * 设置(保存)整数类型的值. * @param value 要保存的值 * @param key 要保存值的Key */ + (void)setInteger:(NSInteger)value forKey:(NSString *)key; /** * 获取对象类型的值. * @param key 要获取值的Key * @return 获取到的值 */ + (id)objectForKey:(NSString *)key; /** * 获取数组类型的值. * @param key 要获取值的Key * @return 获取到的值 */ + (NSArray *)arrayForKey:(NSString *)key; /** * 获取字典类型的值. * @param key 要获取值的Key * @return 获取到的值 */ + (NSDictionary *)dictionaryForKey:(NSString *)key; /** * 获取字符串类型的值. * @param key 要获取值的Key * @return 获取到的值 */ + (NSString *)stringForKey:(NSString *)key; /** * 获取布尔类型的值. * @param key 要获取值的Key * @return 获取到的值 */ + (BOOL)boolForKey:(NSString *)key; /** * 获取浮点类型的值. * @param key 要获取值的Key * @return 获取到的值 */ + (CGFloat)floatForKey:(NSString *)key; /** * 获取整数类型的值. * @param key 要获取值的Key * @return 获取到的值 */ + (NSInteger)integerForKey:(NSString *)key; /** * 删除已保存的值. * @param key 要删除的Key */ + (void)removeValueForKey:(NSString *)key; @end
16.111111
59
0.631975
4dc5c79f5f675e325e553078828dbb245a946f1f
401
h
C
kangzehm/Classes/Tool/3rdLib/SystemShared/GYZSharedItem.h
gouyz/kangzehm
730a2cde277e80eb41086d733bd728a734c6ff89
[ "MIT" ]
2
2019-08-28T22:35:06.000Z
2020-03-20T02:53:25.000Z
kangzehm/Classes/Tool/3rdLib/SystemShared/GYZSharedItem.h
gouyz/kangzehm
730a2cde277e80eb41086d733bd728a734c6ff89
[ "MIT" ]
null
null
null
kangzehm/Classes/Tool/3rdLib/SystemShared/GYZSharedItem.h
gouyz/kangzehm
730a2cde277e80eb41086d733bd728a734c6ff89
[ "MIT" ]
null
null
null
// // GYZSharedItem.h // kangze // // Created by gouyz on 2018/9/25. // Copyright © 2018年 gyz. All rights reserved. // #import <Foundation/Foundation.h> #import <UIKit/UIKit.h> @interface GYZSharedItem : NSObject <UIActivityItemSource> -(instancetype)initWithData:(UIImage*)img andFile:(NSURL*)file; @property (nonatomic, strong) UIImage *img; @property (nonatomic, strong) NSURL *path; @end
20.05
63
0.720698
9e221184a7b1a723d2e8f1bb0b097e6a772cca3c
2,337
h
C
include/il2cpp/PiaPluginReckoning/Value1d.h
martmists-gh/BDSP
d6326c5d3ad9697ea65269ed47aa0b63abac2a0a
[ "MIT" ]
1
2022-01-15T20:20:27.000Z
2022-01-15T20:20:27.000Z
include/il2cpp/PiaPluginReckoning/Value1d.h
martmists-gh/BDSP
d6326c5d3ad9697ea65269ed47aa0b63abac2a0a
[ "MIT" ]
null
null
null
include/il2cpp/PiaPluginReckoning/Value1d.h
martmists-gh/BDSP
d6326c5d3ad9697ea65269ed47aa0b63abac2a0a
[ "MIT" ]
null
null
null
#pragma once #include "il2cpp.h" PiaPlugin_Result_o PiaPluginReckoning_Value1d__SetValue1dNative (uint16_t port, uint64_t destConstantId, float value, bool isStop, const MethodInfo* method_info); PiaPlugin_Result_o PiaPluginReckoning_Value1d__SetValue (uint16_t port, uint64_t destConstantId, float value, bool isStop, const MethodInfo* method_info); PiaPlugin_Result_o PiaPluginReckoning_Value1d__SetValueToAll1dNative (uint16_t port, float value, bool isStop, const MethodInfo* method_info); PiaPlugin_Result_o PiaPluginReckoning_Value1d__SetValueToAll (uint16_t port, float value, bool isStop, const MethodInfo* method_info); PiaPlugin_Result_o PiaPluginReckoning_Value1d__GetValue1dNative (uint16_t port, uint64_t* destConstantId, float* pValue, const MethodInfo* method_info); PiaPlugin_Result_o PiaPluginReckoning_Value1d__GetValue (uint16_t port, uint64_t* destConstantId, float* pValue, const MethodInfo* method_info); void PiaPluginReckoning_Value1d__SetSamplingDistance1dNative (uint16_t port, float value, const MethodInfo* method_info); void PiaPluginReckoning_Value1d__SetSamplingDistance (uint16_t port, float value, const MethodInfo* method_info); float PiaPluginReckoning_Value1d__GetSamplingDistance1dNative (uint16_t port, const MethodInfo* method_info); float PiaPluginReckoning_Value1d__GetSamplingDistance (uint16_t port, const MethodInfo* method_info); bool PiaPluginReckoning_Value1d__IsInCommunication1dNative (uint16_t port, const MethodInfo* method_info); bool PiaPluginReckoning_Value1d__IsInCommunication (uint16_t port, const MethodInfo* method_info); bool PiaPluginReckoning_Value1d__Reset1dNative (uint16_t port, const MethodInfo* method_info); void PiaPluginReckoning_Value1d__Reset (uint16_t port, const MethodInfo* method_info); void PiaPluginReckoning_Value1d__SetClock1dNative (uint16_t port, uint64_t clock, const MethodInfo* method_info); void PiaPluginReckoning_Value1d__SetClock (uint16_t port, uint64_t clock, const MethodInfo* method_info); void PiaPluginReckoning_Value1d__SetReckoningTimeout1dNative (uint16_t port, uint64_t clock, const MethodInfo* method_info); void PiaPluginReckoning_Value1d__SetReckoningTimeout (uint16_t port, uint64_t clock, const MethodInfo* method_info); void PiaPluginReckoning_Value1d___ctor (PiaPluginReckoning_Value1d_o* __this, const MethodInfo* method_info);
97.375
162
0.869919
9e861dbc2c4c19cc19ae873fe59a8a7175e16570
4,525
h
C
arch/arm/mach-omap2/vc.h
CPU-Code/-Linux_kernel
44dc3358bc640197528f5b10dbed0fd3717af65b
[ "AFL-3.0" ]
44
2022-03-16T08:32:31.000Z
2022-03-31T16:02:35.000Z
arch/arm/mach-omap2/vc.h
CPU-Code/-Linux_kernel
44dc3358bc640197528f5b10dbed0fd3717af65b
[ "AFL-3.0" ]
13
2021-07-10T04:36:17.000Z
2022-03-03T10:50:05.000Z
arch/arm/mach-omap2/vc.h
CPU-Code/-Linux_kernel
44dc3358bc640197528f5b10dbed0fd3717af65b
[ "AFL-3.0" ]
18
2022-03-19T04:41:04.000Z
2022-03-31T03:32:12.000Z
/* SPDX-License-Identifier: GPL-2.0-only */ /* * OMAP3/4 Voltage Controller (VC) structure and macro definitions * * Copyright (C) 2007, 2010 Texas Instruments, Inc. * Rajendra Nayak <rnayak@ti.com> * Lesly A M <x0080970@ti.com> * Thara Gopinath <thara@ti.com> * * Copyright (C) 2008, 2011 Nokia Corporation * Kalle Jokiniemi * Paul Walmsley */ #ifndef __ARCH_ARM_MACH_OMAP2_VC_H #define __ARCH_ARM_MACH_OMAP2_VC_H #include <linux/kernel.h> struct voltagedomain; /** * struct omap_vc_common - per-VC register/bitfield data * @cmd_on_mask: ON bitmask in PRM_VC_CMD_VAL* register * @valid: VALID bitmask in PRM_VC_BYPASS_VAL register * @bypass_val_reg: Offset of PRM_VC_BYPASS_VAL reg from PRM start * @data_shift: DATA field shift in PRM_VC_BYPASS_VAL register * @slaveaddr_shift: SLAVEADDR field shift in PRM_VC_BYPASS_VAL register * @regaddr_shift: REGADDR field shift in PRM_VC_BYPASS_VAL register * @cmd_on_shift: ON field shift in PRM_VC_CMD_VAL_* register * @cmd_onlp_shift: ONLP field shift in PRM_VC_CMD_VAL_* register * @cmd_ret_shift: RET field shift in PRM_VC_CMD_VAL_* register * @cmd_off_shift: OFF field shift in PRM_VC_CMD_VAL_* register * @i2c_cfg_reg: I2C configuration register offset * @i2c_cfg_clear_mask: high-speed mode bit clear mask in I2C config register * @i2c_cfg_hsen_mask: high-speed mode bit field mask in I2C config register * @i2c_mcode_mask: MCODE field mask for I2C config register * * XXX One of cmd_on_mask and cmd_on_shift are not needed * XXX VALID should probably be a shift, not a mask */ struct omap_vc_common { u32 cmd_on_mask; u32 valid; u8 bypass_val_reg; u8 data_shift; u8 slaveaddr_shift; u8 regaddr_shift; u8 cmd_on_shift; u8 cmd_onlp_shift; u8 cmd_ret_shift; u8 cmd_off_shift; u8 i2c_cfg_reg; u8 i2c_cfg_clear_mask; u8 i2c_cfg_hsen_mask; u8 i2c_mcode_mask; }; /* omap_vc_channel.flags values */ #define OMAP_VC_CHANNEL_DEFAULT BIT(0) #define OMAP_VC_CHANNEL_CFG_MUTANT BIT(1) /** * struct omap_vc_channel - VC per-instance data * @i2c_slave_addr: I2C slave address of PMIC for this VC channel * @volt_reg_addr: voltage configuration register address * @cmd_reg_addr: command configuration register address * @setup_time: setup time (in sys_clk cycles) of regulator for this channel * @cfg_channel: current value of VC channel configuration register * @i2c_high_speed: whether or not to use I2C high-speed mode * * @common: pointer to VC common data for this platform * @smps_sa_mask: i2c slave address bitmask in the PRM_VC_SMPS_SA register * @smps_volra_mask: VOLRA* bitmask in the PRM_VC_VOL_RA register * @smps_cmdra_mask: CMDRA* bitmask in the PRM_VC_CMD_RA register * @cmdval_reg: register for on/ret/off voltage level values for this channel * @smps_sa_reg: Offset of PRM_VC_SMPS_SA reg from PRM start * @smps_volra_reg: Offset of PRM_VC_SMPS_VOL_RA reg from PRM start * @smps_cmdra_reg: Offset of PRM_VC_SMPS_CMD_RA reg from PRM start * @cfg_channel_reg: VC channel configuration register * @cfg_channel_sa_shift: bit shift for slave address cfg_channel register * @flags: VC channel-specific flags (optional) */ struct omap_vc_channel { /* channel state */ u16 i2c_slave_addr; u16 volt_reg_addr; u16 cmd_reg_addr; u8 cfg_channel; bool i2c_high_speed; /* register access data */ const struct omap_vc_common *common; u32 smps_sa_mask; u32 smps_volra_mask; u32 smps_cmdra_mask; u8 cmdval_reg; u8 smps_sa_reg; u8 smps_volra_reg; u8 smps_cmdra_reg; u8 cfg_channel_reg; u8 cfg_channel_sa_shift; u8 flags; }; extern struct omap_vc_channel omap3_vc_mpu; extern struct omap_vc_channel omap3_vc_core; extern struct omap_vc_channel omap4_vc_mpu; extern struct omap_vc_channel omap4_vc_iva; extern struct omap_vc_channel omap4_vc_core; extern struct omap_vc_param omap3_mpu_vc_data; extern struct omap_vc_param omap3_core_vc_data; extern struct omap_vc_param omap4_mpu_vc_data; extern struct omap_vc_param omap4_iva_vc_data; extern struct omap_vc_param omap4_core_vc_data; void omap3_vc_set_pmic_signaling(int core_next_state); void omap4_vc_set_pmic_signaling(int core_next_state); void omap_vc_init_channel(struct voltagedomain *voltdm); int omap_vc_pre_scale(struct voltagedomain *voltdm, unsigned long target_volt, u8 *target_vsel, u8 *current_vsel); void omap_vc_post_scale(struct voltagedomain *voltdm, unsigned long target_volt, u8 target_vsel, u8 current_vsel); int omap_vc_bypass_scale(struct voltagedomain *voltdm, unsigned long target_volt); #endif
33.768657
77
0.792044
cf9bb955ce1635e114f54f93970ece14cce43261
43,446
h
C
src/modules/SX126x/SX126x.h
4m1g0/RadioLib
cb15190ba06b7a235c087a8346df3c4d5b7c47e6
[ "MIT" ]
1
2020-02-26T14:01:14.000Z
2020-02-26T14:01:14.000Z
src/modules/SX126x/SX126x.h
4m1g0/RadioLib
cb15190ba06b7a235c087a8346df3c4d5b7c47e6
[ "MIT" ]
null
null
null
src/modules/SX126x/SX126x.h
4m1g0/RadioLib
cb15190ba06b7a235c087a8346df3c4d5b7c47e6
[ "MIT" ]
null
null
null
#ifndef _RADIOLIB_SX126X_H #define _RADIOLIB_SX126X_H #include "../../TypeDef.h" #include "../../Module.h" #include "../../protocols/PhysicalLayer/PhysicalLayer.h" // SX126X physical layer properties #define SX126X_CRYSTAL_FREQ 32.0 #define SX126X_DIV_EXPONENT 25 #define SX126X_MAX_PACKET_LENGTH 255 // SX126X SPI commands // operational modes commands #define SX126X_CMD_NOP 0x00 #define SX126X_CMD_SET_SLEEP 0x84 #define SX126X_CMD_SET_STANDBY 0x80 #define SX126X_CMD_SET_FS 0xC1 #define SX126X_CMD_SET_TX 0x83 #define SX126X_CMD_SET_RX 0x82 #define SX126X_CMD_STOP_TIMER_ON_PREAMBLE 0x9F #define SX126X_CMD_SET_RX_DUTY_CYCLE 0x94 #define SX126X_CMD_SET_CAD 0xC5 #define SX126X_CMD_SET_TX_CONTINUOUS_WAVE 0xD1 #define SX126X_CMD_SET_TX_INFINITE_PREAMBLE 0xD2 #define SX126X_CMD_SET_REGULATOR_MODE 0x96 #define SX126X_CMD_CALIBRATE 0x89 #define SX126X_CMD_CALIBRATE_IMAGE 0x98 #define SX126X_CMD_SET_PA_CONFIG 0x95 #define SX126X_CMD_SET_RX_TX_FALLBACK_MODE 0x93 // register and buffer access commands #define SX126X_CMD_WRITE_REGISTER 0x0D #define SX126X_CMD_READ_REGISTER 0x1D #define SX126X_CMD_WRITE_BUFFER 0x0E #define SX126X_CMD_READ_BUFFER 0x1E // DIO and IRQ control #define SX126X_CMD_SET_DIO_IRQ_PARAMS 0x08 #define SX126X_CMD_GET_IRQ_STATUS 0x12 #define SX126X_CMD_CLEAR_IRQ_STATUS 0x02 #define SX126X_CMD_SET_DIO2_AS_RF_SWITCH_CTRL 0x9D #define SX126X_CMD_SET_DIO3_AS_TCXO_CTRL 0x97 // RF, modulation and packet commands #define SX126X_CMD_SET_RF_FREQUENCY 0x86 #define SX126X_CMD_SET_PACKET_TYPE 0x8A #define SX126X_CMD_GET_PACKET_TYPE 0x11 #define SX126X_CMD_SET_TX_PARAMS 0x8E #define SX126X_CMD_SET_MODULATION_PARAMS 0x8B #define SX126X_CMD_SET_PACKET_PARAMS 0x8C #define SX126X_CMD_SET_CAD_PARAMS 0x88 #define SX126X_CMD_SET_BUFFER_BASE_ADDRESS 0x8F #define SX126X_CMD_SET_LORA_SYMB_NUM_TIMEOUT 0x0A // status commands #define SX126X_CMD_GET_STATUS 0xC0 #define SX126X_CMD_GET_RSSI_INST 0x15 #define SX126X_CMD_GET_RX_BUFFER_STATUS 0x13 #define SX126X_CMD_GET_PACKET_STATUS 0x14 #define SX126X_CMD_GET_DEVICE_ERRORS 0x17 #define SX126X_CMD_CLEAR_DEVICE_ERRORS 0x07 #define SX126X_CMD_GET_STATS 0x10 #define SX126X_CMD_RESET_STATS 0x00 // SX126X register map #define SX126X_REG_WHITENING_INITIAL_MSB 0x06B8 #define SX126X_REG_WHITENING_INITIAL_LSB 0x06B9 #define SX126X_REG_CRC_INITIAL_MSB 0x06BC #define SX126X_REG_CRC_INITIAL_LSB 0x06BD #define SX126X_REG_CRC_POLYNOMIAL_MSB 0x06BE #define SX126X_REG_CRC_POLYNOMIAL_LSB 0x06BF #define SX126X_REG_SYNC_WORD_0 0x06C0 #define SX126X_REG_SYNC_WORD_1 0x06C1 #define SX126X_REG_SYNC_WORD_2 0x06C2 #define SX126X_REG_SYNC_WORD_3 0x06C3 #define SX126X_REG_SYNC_WORD_4 0x06C4 #define SX126X_REG_SYNC_WORD_5 0x06C5 #define SX126X_REG_SYNC_WORD_6 0x06C6 #define SX126X_REG_SYNC_WORD_7 0x06C7 #define SX126X_REG_NODE_ADDRESS 0x06CD #define SX126X_REG_BROADCAST_ADDRESS 0x06CE #define SX126X_REG_LORA_SYNC_WORD_MSB 0x0740 #define SX126X_REG_LORA_SYNC_WORD_LSB 0x0741 #define SX126X_REG_RANDOM_NUMBER_0 0x0819 #define SX126X_REG_RANDOM_NUMBER_1 0x081A #define SX126X_REG_RANDOM_NUMBER_2 0x081B #define SX126X_REG_RANDOM_NUMBER_3 0x081C #define SX126X_REG_RX_GAIN 0x08AC #define SX126X_REG_OCP_CONFIGURATION 0x08E7 #define SX126X_REG_XTA_TRIM 0x0911 #define SX126X_REG_XTB_TRIM 0x0912 // undocumented registers #define SX126X_REG_SENSITIVITY_CONFIG 0x0889 // SX1268 datasheet v1.1, section 15.1 #define SX126X_REG_TX_CLAMP_CONFIG 0x08D8 // SX1268 datasheet v1.1, section 15.2 #define SX126X_REG_RTC_STOP 0x0920 // SX1268 datasheet v1.1, section 15.3 #define SX126X_REG_RTC_EVENT 0x0944 // SX1268 datasheet v1.1, section 15.3 #define SX126X_REG_IQ_CONFIG 0x0736 // SX1268 datasheet v1.1, section 15.4 #define SX126X_REG_RX_GAIN_RETENTION_0 0x029F // SX1268 datasheet v1.1, section 9.6 #define SX126X_REG_RX_GAIN_RETENTION_1 0x02A0 // SX1268 datasheet v1.1, section 9.6 #define SX126X_REG_RX_GAIN_RETENTION_2 0x02A1 // SX1268 datasheet v1.1, section 9.6 // SX126X SPI command variables //SX126X_CMD_SET_SLEEP #define SX126X_SLEEP_START_COLD 0b00000000 // 2 2 sleep mode: cold start, configuration is lost (default) #define SX126X_SLEEP_START_WARM 0b00000100 // 2 2 warm start, configuration is retained #define SX126X_SLEEP_RTC_OFF 0b00000000 // 0 0 wake on RTC timeout: disabled #define SX126X_SLEEP_RTC_ON 0b00000001 // 0 0 enabled //SX126X_CMD_SET_STANDBY #define SX126X_STANDBY_RC 0x00 // 7 0 standby mode: 13 MHz RC oscillator #define SX126X_STANDBY_XOSC 0x01 // 7 0 32 MHz crystal oscillator //SX126X_CMD_SET_RX #define SX126X_RX_TIMEOUT_NONE 0x000000 // 23 0 Rx timeout duration: no timeout (Rx single mode) #define SX126X_RX_TIMEOUT_INF 0xFFFFFF // 23 0 infinite (Rx continuous mode) //SX126X_CMD_SET_TX #define SX126X_TX_TIMEOUT_NONE 0x000000 // 23 0 Tx timeout duration: no timeout (Tx single mode) //SX126X_CMD_STOP_TIMER_ON_PREAMBLE #define SX126X_STOP_ON_PREAMBLE_OFF 0x00 // 7 0 stop timer on: sync word or header (default) #define SX126X_STOP_ON_PREAMBLE_ON 0x01 // 7 0 preamble detection //SX126X_CMD_SET_REGULATOR_MODE #define SX126X_REGULATOR_LDO 0x00 // 7 0 set regulator mode: LDO (default) #define SX126X_REGULATOR_DC_DC 0x01 // 7 0 DC-DC //SX126X_CMD_CALIBRATE #define SX126X_CALIBRATE_IMAGE_OFF 0b00000000 // 6 6 image calibration: disabled #define SX126X_CALIBRATE_IMAGE_ON 0b01000000 // 6 6 enabled #define SX126X_CALIBRATE_ADC_BULK_P_OFF 0b00000000 // 5 5 ADC bulk P calibration: disabled #define SX126X_CALIBRATE_ADC_BULK_P_ON 0b00100000 // 5 5 enabled #define SX126X_CALIBRATE_ADC_BULK_N_OFF 0b00000000 // 4 4 ADC bulk N calibration: disabled #define SX126X_CALIBRATE_ADC_BULK_N_ON 0b00010000 // 4 4 enabled #define SX126X_CALIBRATE_ADC_PULSE_OFF 0b00000000 // 3 3 ADC pulse calibration: disabled #define SX126X_CALIBRATE_ADC_PULSE_ON 0b00001000 // 3 3 enabled #define SX126X_CALIBRATE_PLL_OFF 0b00000000 // 2 2 PLL calibration: disabled #define SX126X_CALIBRATE_PLL_ON 0b00000100 // 2 2 enabled #define SX126X_CALIBRATE_RC13M_OFF 0b00000000 // 1 1 13 MHz RC osc. calibration: disabled #define SX126X_CALIBRATE_RC13M_ON 0b00000010 // 1 1 enabled #define SX126X_CALIBRATE_RC64K_OFF 0b00000000 // 0 0 64 kHz RC osc. calibration: disabled #define SX126X_CALIBRATE_RC64K_ON 0b00000001 // 0 0 enabled #define SX126X_CALIBRATE_ALL 0b01111111 // 6 0 calibrate all blocks //SX126X_CMD_CALIBRATE_IMAGE #define SX126X_CAL_IMG_430_MHZ_1 0x6B #define SX126X_CAL_IMG_430_MHZ_2 0x6F #define SX126X_CAL_IMG_470_MHZ_1 0x75 #define SX126X_CAL_IMG_470_MHZ_2 0x81 #define SX126X_CAL_IMG_779_MHZ_1 0xC1 #define SX126X_CAL_IMG_779_MHZ_2 0xC5 #define SX126X_CAL_IMG_863_MHZ_1 0xD7 #define SX126X_CAL_IMG_863_MHZ_2 0xDB #define SX126X_CAL_IMG_902_MHZ_1 0xE1 #define SX126X_CAL_IMG_902_MHZ_2 0xE9 //SX126X_CMD_SET_PA_CONFIG #define SX126X_PA_CONFIG_HP_MAX 0x07 #define SX126X_PA_CONFIG_PA_LUT 0x01 #define SX126X_PA_CONFIG_SX1262_8 0x00 //SX126X_CMD_SET_RX_TX_FALLBACK_MODE #define SX126X_RX_TX_FALLBACK_MODE_FS 0x40 // 7 0 after Rx/Tx go to: FS mode #define SX126X_RX_TX_FALLBACK_MODE_STDBY_XOSC 0x30 // 7 0 standby with crystal oscillator #define SX126X_RX_TX_FALLBACK_MODE_STDBY_RC 0x20 // 7 0 standby with RC oscillator (default) //SX126X_CMD_SET_DIO_IRQ_PARAMS #define SX126X_IRQ_TIMEOUT 0b1000000000 // 9 9 Rx or Tx timeout #define SX126X_IRQ_CAD_DETECTED 0b0100000000 // 8 8 channel activity detected #define SX126X_IRQ_CAD_DONE 0b0010000000 // 7 7 channel activity detection finished #define SX126X_IRQ_CRC_ERR 0b0001000000 // 6 6 wrong CRC received #define SX126X_IRQ_HEADER_ERR 0b0000100000 // 5 5 LoRa header CRC error #define SX126X_IRQ_HEADER_VALID 0b0000010000 // 4 4 valid LoRa header received #define SX126X_IRQ_SYNC_WORD_VALID 0b0000001000 // 3 3 valid sync word detected #define SX126X_IRQ_PREAMBLE_DETECTED 0b0000000100 // 2 2 preamble detected #define SX126X_IRQ_RX_DONE 0b0000000010 // 1 1 packet received #define SX126X_IRQ_TX_DONE 0b0000000001 // 0 0 packet transmission completed #define SX126X_IRQ_ALL 0b1111111111 // 9 0 all interrupts #define SX126X_IRQ_NONE 0b0000000000 // 9 0 no interrupts //SX126X_CMD_SET_DIO2_AS_RF_SWITCH_CTRL #define SX126X_DIO2_AS_IRQ 0x00 // 7 0 DIO2 configuration: IRQ #define SX126X_DIO2_AS_RF_SWITCH 0x01 // 7 0 RF switch control //SX126X_CMD_SET_DIO3_AS_TCXO_CTRL #define SX126X_DIO3_OUTPUT_1_6 0x00 // 7 0 DIO3 voltage output for TCXO: 1.6 V #define SX126X_DIO3_OUTPUT_1_7 0x01 // 7 0 1.7 V #define SX126X_DIO3_OUTPUT_1_8 0x02 // 7 0 1.8 V #define SX126X_DIO3_OUTPUT_2_2 0x03 // 7 0 2.2 V #define SX126X_DIO3_OUTPUT_2_4 0x04 // 7 0 2.4 V #define SX126X_DIO3_OUTPUT_2_7 0x05 // 7 0 2.7 V #define SX126X_DIO3_OUTPUT_3_0 0x06 // 7 0 3.0 V #define SX126X_DIO3_OUTPUT_3_3 0x07 // 7 0 3.3 V //SX126X_CMD_SET_PACKET_TYPE #define SX126X_PACKET_TYPE_GFSK 0x00 // 7 0 packet type: GFSK #define SX126X_PACKET_TYPE_LORA 0x01 // 7 0 LoRa //SX126X_CMD_SET_TX_PARAMS #define SX126X_PA_RAMP_10U 0x00 // 7 0 ramp time: 10 us #define SX126X_PA_RAMP_20U 0x01 // 7 0 20 us #define SX126X_PA_RAMP_40U 0x02 // 7 0 40 us #define SX126X_PA_RAMP_80U 0x03 // 7 0 80 us #define SX126X_PA_RAMP_200U 0x04 // 7 0 200 us #define SX126X_PA_RAMP_800U 0x05 // 7 0 800 us #define SX126X_PA_RAMP_1700U 0x06 // 7 0 1700 us #define SX126X_PA_RAMP_3400U 0x07 // 7 0 3400 us //SX126X_CMD_SET_MODULATION_PARAMS #define SX126X_GFSK_FILTER_NONE 0x00 // 7 0 GFSK filter: none #define SX126X_GFSK_FILTER_GAUSS_0_3 0x08 // 7 0 Gaussian, BT = 0.3 #define SX126X_GFSK_FILTER_GAUSS_0_5 0x09 // 7 0 Gaussian, BT = 0.5 #define SX126X_GFSK_FILTER_GAUSS_0_7 0x0A // 7 0 Gaussian, BT = 0.7 #define SX126X_GFSK_FILTER_GAUSS_1 0x0B // 7 0 Gaussian, BT = 1 #define SX126X_GFSK_RX_BW_4_8 0x1F // 7 0 GFSK Rx bandwidth: 4.8 kHz #define SX126X_GFSK_RX_BW_5_8 0x17 // 7 0 5.8 kHz #define SX126X_GFSK_RX_BW_7_3 0x0F // 7 0 7.3 kHz #define SX126X_GFSK_RX_BW_9_7 0x1E // 7 0 9.7 kHz #define SX126X_GFSK_RX_BW_11_7 0x16 // 7 0 11.7 kHz #define SX126X_GFSK_RX_BW_14_6 0x0E // 7 0 14.6 kHz #define SX126X_GFSK_RX_BW_19_5 0x1D // 7 0 19.5 kHz #define SX126X_GFSK_RX_BW_23_4 0x15 // 7 0 23.4 kHz #define SX126X_GFSK_RX_BW_29_3 0x0D // 7 0 29.3 kHz #define SX126X_GFSK_RX_BW_39_0 0x1C // 7 0 39.0 kHz #define SX126X_GFSK_RX_BW_46_9 0x14 // 7 0 46.9 kHz #define SX126X_GFSK_RX_BW_58_6 0x0C // 7 0 58.6 kHz #define SX126X_GFSK_RX_BW_78_2 0x1B // 7 0 78.2 kHz #define SX126X_GFSK_RX_BW_93_8 0x13 // 7 0 93.8 kHz #define SX126X_GFSK_RX_BW_117_3 0x0B // 7 0 117.3 kHz #define SX126X_GFSK_RX_BW_156_2 0x1A // 7 0 156.2 kHz #define SX126X_GFSK_RX_BW_187_2 0x12 // 7 0 187.2 kHz #define SX126X_GFSK_RX_BW_234_3 0x0A // 7 0 234.3 kHz #define SX126X_GFSK_RX_BW_312_0 0x19 // 7 0 312.0 kHz #define SX126X_GFSK_RX_BW_373_6 0x11 // 7 0 373.6 kHz #define SX126X_GFSK_RX_BW_467_0 0x09 // 7 0 467.0 kHz #define SX126X_LORA_BW_7_8 0x00 // 7 0 LoRa bandwidth: 7.8 kHz #define SX126X_LORA_BW_10_4 0x08 // 7 0 10.4 kHz #define SX126X_LORA_BW_15_6 0x01 // 7 0 15.6 kHz #define SX126X_LORA_BW_20_8 0x09 // 7 0 20.8 kHz #define SX126X_LORA_BW_31_25 0x02 // 7 0 31.25 kHz #define SX126X_LORA_BW_41_7 0x0A // 7 0 41.7 kHz #define SX126X_LORA_BW_62_5 0x03 // 7 0 62.5 kHz #define SX126X_LORA_BW_125_0 0x04 // 7 0 125.0 kHz #define SX126X_LORA_BW_250_0 0x05 // 7 0 250.0 kHz #define SX126X_LORA_BW_500_0 0x06 // 7 0 500.0 kHz #define SX126X_LORA_CR_4_5 0x01 // 7 0 LoRa coding rate: 4/5 #define SX126X_LORA_CR_4_6 0x02 // 7 0 4/6 #define SX126X_LORA_CR_4_7 0x03 // 7 0 4/7 #define SX126X_LORA_CR_4_8 0x04 // 7 0 4/8 #define SX126X_LORA_LOW_DATA_RATE_OPTIMIZE_OFF 0x00 // 7 0 LoRa low data rate optimization: disabled #define SX126X_LORA_LOW_DATA_RATE_OPTIMIZE_ON 0x01 // 7 0 enabled //SX126X_CMD_SET_PACKET_PARAMS #define SX126X_GFSK_PREAMBLE_DETECT_OFF 0x00 // 7 0 GFSK minimum preamble length before reception starts: detector disabled #define SX126X_GFSK_PREAMBLE_DETECT_8 0x04 // 7 0 8 bits #define SX126X_GFSK_PREAMBLE_DETECT_16 0x05 // 7 0 16 bits #define SX126X_GFSK_PREAMBLE_DETECT_24 0x06 // 7 0 24 bits #define SX126X_GFSK_PREAMBLE_DETECT_32 0x07 // 7 0 32 bits #define SX126X_GFSK_ADDRESS_FILT_OFF 0x00 // 7 0 GFSK address filtering: disabled #define SX126X_GFSK_ADDRESS_FILT_NODE 0x01 // 7 0 node only #define SX126X_GFSK_ADDRESS_FILT_NODE_BROADCAST 0x02 // 7 0 node and broadcast #define SX126X_GFSK_PACKET_FIXED 0x00 // 7 0 GFSK packet type: fixed (payload length known in advance to both sides) #define SX126X_GFSK_PACKET_VARIABLE 0x01 // 7 0 variable (payload length added to packet) #define SX126X_GFSK_CRC_OFF 0x01 // 7 0 GFSK packet CRC: disabled #define SX126X_GFSK_CRC_1_BYTE 0x00 // 7 0 1 byte #define SX126X_GFSK_CRC_2_BYTE 0x02 // 7 0 2 byte #define SX126X_GFSK_CRC_1_BYTE_INV 0x04 // 7 0 1 byte, inverted #define SX126X_GFSK_CRC_2_BYTE_INV 0x06 // 7 0 2 byte, inverted #define SX126X_GFSK_WHITENING_OFF 0x00 // 7 0 GFSK data whitening: disabled #define SX126X_GFSK_WHITENING_ON 0x01 // 7 0 enabled #define SX126X_LORA_HEADER_EXPLICIT 0x00 // 7 0 LoRa header mode: explicit #define SX126X_LORA_HEADER_IMPLICIT 0x01 // 7 0 implicit #define SX126X_LORA_CRC_OFF 0x00 // 7 0 LoRa CRC mode: disabled #define SX126X_LORA_CRC_ON 0x01 // 7 0 enabled #define SX126X_LORA_IQ_STANDARD 0x00 // 7 0 LoRa IQ setup: standard #define SX126X_LORA_IQ_INVERTED 0x01 // 7 0 inverted //SX126X_CMD_SET_CAD_PARAMS #define SX126X_CAD_ON_1_SYMB 0x00 // 7 0 number of symbols used for CAD: 1 #define SX126X_CAD_ON_2_SYMB 0x01 // 7 0 2 #define SX126X_CAD_ON_4_SYMB 0x02 // 7 0 4 #define SX126X_CAD_ON_8_SYMB 0x03 // 7 0 8 #define SX126X_CAD_ON_16_SYMB 0x04 // 7 0 16 #define SX126X_CAD_GOTO_STDBY 0x00 // 7 0 after CAD is done, always go to STDBY_RC mode #define SX126X_CAD_GOTO_RX 0x01 // 7 0 after CAD is done, go to Rx mode if activity is detected //SX126X_CMD_GET_STATUS #define SX126X_STATUS_MODE_STDBY_RC 0b00100000 // 6 4 current chip mode: STDBY_RC #define SX126X_STATUS_MODE_STDBY_XOSC 0b00110000 // 6 4 STDBY_XOSC #define SX126X_STATUS_MODE_FS 0b01000000 // 6 4 FS #define SX126X_STATUS_MODE_RX 0b01010000 // 6 4 RX #define SX126X_STATUS_MODE_TX 0b01100000 // 6 4 TX #define SX126X_STATUS_DATA_AVAILABLE 0b00000100 // 3 1 command status: packet received and data can be retrieved #define SX126X_STATUS_CMD_TIMEOUT 0b00000110 // 3 1 SPI command timed out #define SX126X_STATUS_CMD_INVALID 0b00001000 // 3 1 invalid SPI command #define SX126X_STATUS_CMD_FAILED 0b00001010 // 3 1 SPI command failed to execute #define SX126X_STATUS_TX_DONE 0b00001100 // 3 1 packet transmission done #define SX126X_STATUS_SPI_FAILED 0b11111111 // 7 0 SPI transaction failed //SX126X_CMD_GET_PACKET_STATUS #define SX126X_GFSK_RX_STATUS_PREAMBLE_ERR 0b10000000 // 7 7 GFSK Rx status: preamble error #define SX126X_GFSK_RX_STATUS_SYNC_ERR 0b01000000 // 6 6 sync word error #define SX126X_GFSK_RX_STATUS_ADRS_ERR 0b00100000 // 5 5 address error #define SX126X_GFSK_RX_STATUS_CRC_ERR 0b00010000 // 4 4 CRC error #define SX126X_GFSK_RX_STATUS_LENGTH_ERR 0b00001000 // 3 3 length error #define SX126X_GFSK_RX_STATUS_ABORT_ERR 0b00000100 // 2 2 abort error #define SX126X_GFSK_RX_STATUS_PACKET_RECEIVED 0b00000010 // 2 2 packet received #define SX126X_GFSK_RX_STATUS_PACKET_SENT 0b00000001 // 2 2 packet sent //SX126X_CMD_GET_DEVICE_ERRORS #define SX126X_PA_RAMP_ERR 0b100000000 // 8 8 device errors: PA ramping failed #define SX126X_PLL_LOCK_ERR 0b001000000 // 6 6 PLL failed to lock #define SX126X_XOSC_START_ERR 0b000100000 // 5 5 crystal oscillator failed to start #define SX126X_IMG_CALIB_ERR 0b000010000 // 4 4 image calibration failed #define SX126X_ADC_CALIB_ERR 0b000001000 // 3 3 ADC calibration failed #define SX126X_PLL_CALIB_ERR 0b000000100 // 2 2 PLL calibration failed #define SX126X_RC13M_CALIB_ERR 0b000000010 // 1 1 RC13M calibration failed #define SX126X_RC64K_CALIB_ERR 0b000000001 // 0 0 RC64K calibration failed // SX126X SPI register variables //SX126X_REG_LORA_SYNC_WORD_MSB + LSB #define SX126X_SYNC_WORD_PUBLIC 0x34 // actually 0x3444 NOTE: The low nibbles in each byte (0x_4_4) are masked out since apparently, they're reserved. #define SX126X_SYNC_WORD_PRIVATE 0x12 // actually 0x1424 You couldn't make this up if you tried. /*! \class SX126x \brief Base class for %SX126x series. All derived classes for %SX126x (e.g. SX1262 or SX1268) inherit from this base class. This class should not be instantiated directly from Arduino sketch, only from its derived classes. */ class SX126x: public PhysicalLayer { public: // introduce PhysicalLayer overloads using PhysicalLayer::transmit; using PhysicalLayer::receive; using PhysicalLayer::startTransmit; using PhysicalLayer::readData; /*! \brief Default constructor. \param mod Instance of Module that will be used to communicate with the radio. */ SX126x(Module* mod); // basic methods /*! \brief Initialization method for LoRa modem. \param bw LoRa bandwidth in kHz. Allowed values are 7.8, 10.4, 15.6, 20.8, 31.25, 41.7, 62.5, 125.0, 250.0 and 500.0 kHz. \param sf LoRa spreading factor. Allowed values are in range 5 to 12. \param cr LoRa coding rate denominator. Allowed values range from 5 to 8. \param syncWord 1-byte LoRa sync word. \param currentLimit Current protection limit in mA. \param preambleLength LoRa preamble length in symbols. Allowed values range from 1 to 65535. \param tcxoVoltage TCXO reference voltage to be set on DIO3. Defaults to 1.6 V, set to 0 to skip. \returns \ref status_codes */ int16_t begin(float bw, uint8_t sf, uint8_t cr, uint16_t syncWord, float currentLimit, uint16_t preambleLength, float tcxoVoltage); /*! \brief Initialization method for FSK modem. \param br FSK bit rate in kbps. Allowed values range from 0.6 to 300.0 kbps. \param freqDev Frequency deviation from carrier frequency in kHz. Allowed values range from 0.0 to 200.0 kHz. \param rxBw Receiver bandwidth in kHz. Allowed values are 4.8, 5.8, 7.3, 9.7, 11.7, 14.6, 19.5, 23.4, 29.3, 39.0, 46.9, 58.6, 78.2, 93.8, 117.3, 156.2, 187.2, 234.3, 312.0, 373.6 and 467.0 kHz. \param currentLimit Current protection limit in mA. \param preambleLength FSK preamble length in bits. Allowed values range from 0 to 65535. \param dataShaping Time-bandwidth product of the Gaussian filter to be used for shaping. Allowed values are 0.3, 0.5, 0.7 and 1.0. Set to 0 to disable shaping. \param tcxoVoltage TCXO reference voltage to be set on DIO3. Defaults to 1.6 V, set to 0 to skip. \returns \ref status_codes */ int16_t beginFSK(float br, float freqDev, float rxBw, float currentLimit, uint16_t preambleLength, float dataShaping, float tcxoVoltage); /*! \brief Reset method. Will reset the chip to the default state using RST pin. */ void reset(); /*! \brief Blocking binary transmit method. Overloads for string-based transmissions are implemented in PhysicalLayer. \param data Binary data to be sent. \param len Number of bytes to send. \param addr Address to send the data to. Will only be added if address filtering was enabled. \returns \ref status_codes */ int16_t transmit(uint8_t* data, size_t len, uint8_t addr = 0); /*! \brief Blocking binary receive method. Overloads for string-based transmissions are implemented in PhysicalLayer. \param data Binary data to be sent. \param len Number of bytes to send. \returns \ref status_codes */ int16_t receive(uint8_t* data, size_t len); /*! \brief Starts direct mode transmission. \param frf Raw RF frequency value. Defaults to 0, required for quick frequency shifts in RTTY. \returns \ref status_codes */ int16_t transmitDirect(uint32_t frf = 0); /*! \brief Starts direct mode reception. Only implemented for PhysicalLayer compatibility, as %SX126x series does not support direct mode reception. Will always return ERR_UNKNOWN. \returns \ref status_codes */ int16_t receiveDirect(); /*! \brief Performs scan for LoRa transmission in the current channel. Detects both preamble and payload. \returns \ref status_codes */ int16_t scanChannel(); /*! \brief Sets the module to sleep mode. \returns \ref status_codes */ int16_t sleep(); /*! \brief Sets the module to standby mode (overload for PhysicalLayer compatibility, uses 13 MHz RC oscillator). \returns \ref status_codes */ int16_t standby(); /*! \brief Sets the module to standby mode. \param mode Oscillator to be used in standby mode. Can be set to SX126X_STANDBY_RC (13 MHz RC oscillator) or SX126X_STANDBY_XOSC (32 MHz external crystal oscillator). \returns \ref status_codes */ int16_t standby(uint8_t mode); // interrupt methods /*! \brief Sets interrupt service routine to call when DIO1 activates. \param func ISR to call. */ void setDio1Action(void (*func)(void)); /*! \brief Interrupt-driven binary transmit method. Overloads for string-based transmissions are implemented in PhysicalLayer. \param data Binary data to be sent. \param len Number of bytes to send. \param addr Address to send the data to. Will only be added if address filtering was enabled. \returns \ref status_codes */ int16_t startTransmit(uint8_t* data, size_t len, uint8_t addr = 0); /*! \brief Interrupt-driven receive method. DIO1 will be activated when full packet is received. \param timeout Raw timeout value, expressed as multiples of 15.625 us. Defaults to SX126X_RX_TIMEOUT_INF for infinite timeout (Rx continuous mode), set to SX126X_RX_TIMEOUT_NONE for no timeout (Rx single mode). \returns \ref status_codes */ int16_t startReceive(uint32_t timeout = SX126X_RX_TIMEOUT_INF); /*! \brief Interrupt-driven receive method where the device mostly sleeps and periodically wakes to listen. Note that this function assumes the unit will take 500us + TCXO_delay to change state. See datasheet section 13.1.7, version 1.2. \param rxPeriod The duration the receiver will be in Rx mode, in microseconds. \param sleepPeriod The duration the receiver will not be in Rx mode, in microseconds. \returns \ref status_codes */ int16_t startReceiveDutyCycle(uint32_t rxPeriod, uint32_t sleepPeriod); /*! \brief Calls \ref startReceiveDutyCycle with rxPeriod and sleepPeriod set so the unit shouldn't miss any messages. \param senderPreambleLength Expected preamble length of the messages to receive. If set to zero, the currently configured preamble length will be used. Defaults to zero. \param minSymbols Parameters will be chosen to ensure that the unit will catch at least this many symbols of any preamble of the specified length. Defaults to 8. According to Semtech, receiver requires 8 symbols to reliably latch a preamble. This makes this method redundant when transmitter preamble length is less than 17 (2*minSymbols + 1). \returns \ref status_codes */ int16_t startReceiveDutyCycleAuto(uint16_t senderPreambleLength = 0, uint16_t minSymbols = 8); /*! \brief Reads data received after calling startReceive method. \param data Pointer to array to save the received binary data. \param len Number of bytes that will be received. Must be known in advance for binary transmissions. \returns \ref status_codes */ int16_t readData(uint8_t* data, size_t len); // configuration methods /*! \brief Sets LoRa bandwidth. Allowed values are 7.8, 10.4, 15.6, 20.8, 31.25, 41.7, 62.5, 125.0, 250.0 and 500.0 kHz. \param bw LoRa bandwidth to be set in kHz. \returns \ref status_codes */ int16_t setBandwidth(float bw); /*! \brief Sets LoRa spreading factor. Allowed values range from 5 to 12. \param sf LoRa spreading factor to be set. \returns \ref status_codes */ int16_t setSpreadingFactor(uint8_t sf); /*! \brief Sets LoRa coding rate denominator. Allowed values range from 5 to 8. \param cr LoRa coding rate denominator to be set. \returns \ref status_codes */ int16_t setCodingRate(uint8_t cr); /*! \brief Sets LoRa sync word. \param syncWord LoRa sync word to be set. \returns \ref status_codes */ int16_t setSyncWord(uint16_t syncWord); /*! \brief Sets current protection limit. Can be set in 0.25 mA steps. \param currentLimit current protection limit to be set in mA. \returns \ref status_codes */ int16_t setCurrentLimit(float currentLimit); /*! \brief Sets preamble length for LoRa or FSK modem. Allowed values range from 1 to 65535. \param preambleLength Preamble length to be set in symbols (LoRa) or bits (FSK). \returns \ref status_codes */ int16_t setPreambleLength(uint16_t preambleLength); /*! \brief Sets FSK frequency deviation. Allowed values range from 0.0 to 200.0 kHz. \param freqDev FSK frequency deviation to be set in kHz. \returns \ref status_codes */ int16_t setFrequencyDeviation(float freqDev); /*! \brief Sets FSK bit rate. Allowed values range from 0.6 to 300.0 kbps. \param br FSK bit rate to be set in kbps. \returns \ref status_codes */ int16_t setBitRate(float br); /*! \brief Sets FSK receiver bandwidth. Allowed values are 4.8, 5.8, 7.3, 9.7, 11.7, 14.6, 19.5, 23.4, 29.3, 39.0, 46.9, 58.6, 78.2, 93.8, 117.3, 156.2, 187.2, 234.3, 312.0, 373.6 and 467.0 kHz. \param FSK receiver bandwidth to be set in kHz. \returns \ref status_codes */ int16_t setRxBandwidth(float rxBw); /*! \brief Sets time-bandwidth product of Gaussian filter applied for shaping. Allowed values are 0.3, 0.5, 0.7 and 1.0. Set to 0 to disable shaping. \param sh Time-bandwidth product of Gaussian filter to be set. \returns \ref status_codes */ int16_t setDataShaping(float sh); /*! \brief Sets FSK sync word in the form of array of up to 8 bytes. \param syncWord FSK sync word to be set. \param len FSK sync word length in bytes. \returns \ref status_codes */ int16_t setSyncWord(uint8_t* syncWord, uint8_t len); /*! \brief Sets FSK sync word in the form of array of up to 8 bytes. \param syncWord FSK sync word to be set. \param bitsLen FSK sync word length in bits. If length is not divisible by 8, least significant bits of syncWord will be ignored. \returns \ref status_codes */ int16_t setSyncBits(uint8_t *syncWord, uint8_t bitsLen); /*! \brief Sets node address. Calling this method will also enable address filtering for node address only. \param nodeAddr Node address to be set. \returns \ref status_codes */ int16_t setNodeAddress(uint8_t nodeAddr); /*! \brief Sets broadcast address. Calling this method will also enable address filtering for node and broadcast address. \param broadAddr Node address to be set. \returns \ref status_codes */ int16_t setBroadcastAddress(uint8_t broadAddr); /*! \brief Disables address filtering. Calling this method will also erase previously set addresses. \returns \ref status_codes */ int16_t disableAddressFiltering(); /*! \brief Sets CRC configuration. \param len CRC length in bytes, Allowed values are 1 or 2, set to 0 to disable CRC. \param initial Initial CRC value. FSK only. Defaults to 0x1D0F (CCIT CRC). \param polynomial Polynomial for CRC calculation. FSK only. Defaults to 0x1021 (CCIT CRC). \param inverted Invert CRC bytes. FSK only. Defaults to true (CCIT CRC). \returns \ref status_codes */ int16_t setCRC(uint8_t len, uint16_t initial = 0x1D0F, uint16_t polynomial = 0x1021, bool inverted = true); /*! \brief Sets FSK whitening parameters. \param enabled True = Whitening enabled \param initial Initial value used for the whitening LFSR in FSK mode. \returns \ref status_codes */ int16_t setWhitening(bool enabled, uint16_t initial = 0x0100); /*! \brief Sets TCXO (Temperature Compensated Crystal Oscillator) configuration. \param TCXO reference voltage in volts. Allowed values are 1.6, 1.7, 1.8, 2.2. 2.4, 2.7, 3.0 and 3.3 V \param TCXO timeout in us. Defaults to 5000 us. */ int16_t setTCXO(float voltage, uint32_t delay = 5000); /*! \brief Set DIO2 to function as RF switch (default in Semtech example designs). \returns \ref status_codes */ int16_t setDio2AsRfSwitch(bool enable = true); /*! \brief Gets effective data rate for the last transmitted packet. The value is calculated only for payload bytes. \returns Effective data rate in bps. */ float getDataRate(); /*! \brief Gets RSSI (Recorded Signal Strength Indicator) of the last received packet. \returns RSSI of the last received packet in dBm. */ float getRSSI(); /*! \brief Gets SNR (Signal to Noise Ratio) of the last received packet. Only available for LoRa modem. \returns SNR of the last received packet in dB. */ float getSNR(); /*! \brief Query modem for the packet length of received payload. \param update Update received packet length. Will return cached value when set to false. \returns Length of last received packet in bytes. */ size_t getPacketLength(bool update = true); /*! \brief Set modem in fixed packet length mode. Available in FSK mode only. \param len Packet length. \returns \ref status_codes */ int16_t fixedPacketLengthMode(uint8_t len = SX126X_MAX_PACKET_LENGTH); /*! \brief Set modem in variable packet length mode. Available in FSK mode only. \param len Maximum packet length. \returns \ref status_codes */ int16_t variablePacketLengthMode(uint8_t maxLen = SX126X_MAX_PACKET_LENGTH); /*! \brief Get expected time-on-air for a given size of payload \param len Payload length in bytes. \returns Expected time-on-air in microseconds. */ uint32_t getTimeOnAir(size_t len); #ifndef RADIOLIB_GODMODE protected: #endif // SX1276x SPI command implementations int16_t setTx(uint32_t timeout = 0); int16_t setRx(uint32_t timeout); int16_t setCad(); int16_t setPaConfig(uint8_t paDutyCycle, uint8_t deviceSel, uint8_t hpMax = SX126X_PA_CONFIG_HP_MAX, uint8_t paLut = SX126X_PA_CONFIG_PA_LUT); int16_t writeRegister(uint16_t addr, uint8_t* data, uint8_t numBytes); int16_t readRegister(uint16_t addr, uint8_t* data, uint8_t numBytes); int16_t writeBuffer(uint8_t* data, uint8_t numBytes, uint8_t offset = 0x00); int16_t readBuffer(uint8_t* data, uint8_t numBytes); int16_t setDioIrqParams(uint16_t irqMask, uint16_t dio1Mask, uint16_t dio2Mask = SX126X_IRQ_NONE, uint16_t dio3Mask = SX126X_IRQ_NONE); uint16_t getIrqStatus(); int16_t clearIrqStatus(uint16_t clearIrqParams = SX126X_IRQ_ALL); int16_t setRfFrequency(uint32_t frf); int16_t calibrateImage(uint8_t* data); uint8_t getPacketType(); int16_t setTxParams(uint8_t power, uint8_t rampTime = SX126X_PA_RAMP_200U); int16_t setModulationParams(uint8_t sf, uint8_t bw, uint8_t cr, uint8_t ldro = 0xFF); int16_t setModulationParamsFSK(uint32_t br, uint8_t pulseShape, uint8_t rxBw, uint32_t freqDev); int16_t setPacketParams(uint16_t preambleLength, uint8_t crcType, uint8_t payloadLength = 0xFF, uint8_t headerType = SX126X_LORA_HEADER_EXPLICIT, uint8_t invertIQ = SX126X_LORA_IQ_STANDARD); int16_t setPacketParamsFSK(uint16_t preambleLength, uint8_t crcType, uint8_t syncWordLength, uint8_t addrComp, uint8_t whitening, uint8_t packetType = SX126X_GFSK_PACKET_VARIABLE, uint8_t payloadLength = 0xFF, uint8_t preambleDetectorLength = SX126X_GFSK_PREAMBLE_DETECT_16); int16_t setBufferBaseAddress(uint8_t txBaseAddress = 0x00, uint8_t rxBaseAddress = 0x00); uint8_t getStatus(); uint32_t getPacketStatus(); uint16_t getDeviceErrors(); int16_t clearDeviceErrors(); int16_t startReceiveCommon(); int16_t setFrequencyRaw(float freq); int16_t setOptimalHiPowerPaConfig(int8_t* inOutPower); int16_t setPacketMode(uint8_t mode, uint8_t len); // fixes to errata int16_t fixSensitivity(); int16_t fixPaClamping(); int16_t fixImplicitTimeout(); int16_t fixInvertedIQ(uint8_t iqConfig); #ifndef RADIOLIB_GODMODE private: #endif Module* _mod; uint8_t _bw, _sf, _cr, _ldro, _crcType; uint16_t _preambleLength; float _bwKhz; uint32_t _br, _freqDev; uint8_t _rxBw, _pulseShape, _crcTypeFSK, _syncWordLength, _addrComp, _whitening, _packetType; uint16_t _preambleLengthFSK; float _rxBwKhz; float _dataRate; uint32_t _tcxoDelay; int16_t config(uint8_t modem); // common low-level SPI interface int16_t SPIwriteCommand(uint8_t cmd, uint8_t* data, uint8_t numBytes, bool waitForBusy = true); int16_t SPIwriteCommand(uint8_t* cmd, uint8_t cmdLen, uint8_t* data, uint8_t numBytes, bool waitForBusy = true); int16_t SPIreadCommand(uint8_t cmd, uint8_t* data, uint8_t numBytes, bool waitForBusy = true); int16_t SPIreadCommand(uint8_t* cmd, uint8_t cmdLen, uint8_t* data, uint8_t numBytes, bool waitForBusy = true); int16_t SPItransfer(uint8_t* cmd, uint8_t cmdLen, bool write, uint8_t* dataOut, uint8_t* dataIn, uint8_t numBytes, bool waitForBusy, uint32_t timeout = 5000); }; #endif
51.173145
279
0.588639
d0e5fd49027a6de77708f80fa35df956333479b7
7,889
h
C
src/celllist.h
dualword/faunus
89f14398b960889cc74d0cceab96ef0e197088ae
[ "MIT" ]
55
2015-01-23T13:30:50.000Z
2022-01-27T10:04:29.000Z
src/celllist.h
dualword/faunus
89f14398b960889cc74d0cceab96ef0e197088ae
[ "MIT" ]
128
2015-11-04T15:38:12.000Z
2022-03-24T20:25:58.000Z
src/celllist.h
dualword/faunus
89f14398b960889cc74d0cceab96ef0e197088ae
[ "MIT" ]
33
2015-01-29T14:33:29.000Z
2022-03-24T10:32:07.000Z
#pragma once /** * @brief Cell list class templates. * * Minimal interface to be used in other header file to avoid number of class templates. Full class templates * definitions are provided in "celllistimpl.h" file. * * @author Richard Chudoba * @date 2021-02-01 */ namespace Faunus { namespace CellList { namespace Grid { /** * Type manipulation helpers. */ template <typename T> using GridTypeOf = typename T::GridType; template <typename T> using IndexOf = typename T::CellIndex; template <typename T> using CoordOf = typename T::CellCoord; template <typename T> using SpaceAxisOf = typename T::SpaceAxis; template <typename T> using PointOf = typename T::Point; /** * @brief A cell grid type declarations. * * @tparam VDimension number of grid dimensions, e.g., 3 for the real 3D world * @tparam TCellIndex type of a single coordinate in cell space; also an absolute cell index * @tparam TSpaceAxis type of a single coordinate in physical space */ template <unsigned int VDimension, typename TCellIndex = int, typename TSpaceAxis = double> struct GridType { constexpr static unsigned int Dimension = VDimension; //!< number of dimmensions, e.g., 3 for the real 3D world using SpaceAxis = TSpaceAxis; //!< a single coordinate in physical space, e.g., double using CellIndex = TCellIndex; //!< a single coordinate in cell space, e.g., int; also an absolute cell index using Point = Eigen::Array<SpaceAxis, Dimension, 1>; //!< a point in the VDimensional space using CellCoord = Eigen::Array<CellIndex, Dimension, 1>; //!< VDimensional cell coordinates }; //! @brief Commonly used GridType in Faunus. using Grid3DType = GridType<3, int, double>; /** * @brief A simple data holder for common offsets in 3D grids, e.g., nearest neighbors or forward neighbors. */ class GridOffsets3D { using CellCoord = CoordOf<Grid3DType>; //!< 3-dimension cell coordinates using CellIndex = IndexOf<Grid3DType>; //!< cell index public: const std::vector<CellCoord> self{{0, 0, 0}}; //!< the cell itself std::vector<CellCoord> neighbors; //!< all neighbors (excluding self); (1 + 2×distance)³ - 1 std::vector<CellCoord> forward_neighbors; //!< only the preceding half of all neighbors CellIndex distance; //!< maximal distance of neighbours (1 for the nearest neighbors) /** * @param distance maximal distance of neighbours (1 for the nearest neighbors) */ GridOffsets3D(CellIndex distance); private: void initNeighbors(); void initForwardNeighbors(); }; } // namespace Grid namespace Container { /** * Type manipulation helpers. */ template <typename T> using ContainerTypeOf = typename T::ContainerType; template <typename T> using IndexOf = typename ContainerTypeOf<T>::Index; template <typename T> using MemberOf = typename ContainerTypeOf<T>::Member; template <typename T> using MembersOf = typename ContainerTypeOf<T>::Members; /** * @brief An interface of a container. * * The container is responsible for storing (and retriving) members under a given cell index. Various storage policies * may be used in different implementations, e.g., a vector or a map. * * @tparam TMember a member type * @tparam TIndex an index type, see GridType::CellIndex */ template <typename TMember, typename TIndex> struct AbstractContainer { using ContainerType = AbstractContainer<TMember, TIndex>; using Index = TIndex; //!< the cell index (key) type using Member = TMember; //!< the cell member (primitive value) type using Members = std::vector<Member>; //!< the cell members type //! @brief Gets cell members at the given cell index. virtual const Members& get(TIndex) const = 0; //! @brief Gets cell members at the given cell index. virtual Members& get(TIndex) = 0; //! @brief Gets cell members of an empty cell. Allows non-existing cells. virtual const Members& getEmpty() const = 0; //! @brief Gets indicies of non-empty cells. //! All non-empty cells are included. However, not all cells included must be non-empty. virtual std::vector<TIndex> indices() const = 0; virtual ~AbstractContainer() = default; }; } // namespace Container /** * Type manipulation helpers. */ template <typename T> using ContainerOf = typename T::Container; template <typename T> using GridOf = typename T::Grid; using Container::ContainerTypeOf; using Grid::GridTypeOf; template <typename T> using IndexOf = typename Grid::IndexOf<GridTypeOf<typename T::AbstractCellList>>; template <typename T> using CoordOf = typename Grid::CoordOf<GridTypeOf<typename T::AbstractCellList>>; template <typename T> using PointOf = typename Grid::PointOf<GridTypeOf<typename T::AbstractCellList>>; template <typename T> using SpaceAxisOf = typename Grid::SpaceAxisOf<GridTypeOf<typename T::AbstractCellList>>; template <typename T> using MemberOf = typename Container::MemberOf<typename T::AbstractCellList>; template <typename T> using MembersOf = typename Container::MembersOf<typename T::AbstractCellList>; /** * @brief An interface of a immutable cell list. No methods for manipulating (adding, removing) members are provided. * @tparam TContainerType a container type to obtain Member and Members subtypes * @tparam TGridType a grid type to obtain index and coordinates subtypes */ template <class TContainerType, class TGridType> struct AbstractImmutableCellList { using AbstractCellList = AbstractImmutableCellList<TContainerType, TGridType>; //! self using ContainerType = TContainerType; //!< abstract container types using GridType = TGridType; //!< abstract grid type using Members = typename Container::MembersOf<ContainerType>; //!< members type using Member = typename Container::MemberOf<ContainerType>; //!< member type using CellIndex = typename Grid::IndexOf<GridType>; //!< grid (cell) index type using CellCoord = typename Grid::CoordOf<GridType>; //!< grid (cell) coordinates type //! @brief Gets cell members at given cell coordinates. virtual const Members& getMembers(const CellCoord&) = 0; //! @brief Gets cell members at given cell coordinates. virtual const Members& getNeighborMembers(const CellCoord&, const CellCoord&) = 0; //! @brief Get cells count. Valid cell indices are in the range [0, gridSize). virtual CellIndex gridSize() const = 0; // todo check if needed //! @brief Gets indicies of non-empty cells. See AbstractContainer interface. //! @todo refactor as an iterator virtual std::vector<CellCoord> getCells() const = 0; virtual ~AbstractImmutableCellList() = default; }; /** * @brief An interface to a cell list that can return cell's members in sorted order. * * Interface is used to efficiently compute differences between cell lists. * * @tparam TContainerType a container type to obtain Member and Members subtypes * @tparam TGridType a grid type to obtain index and coordinates subtypes */ template <class TContainerType, class TGridType> struct AbstractSortableCellList : virtual public AbstractImmutableCellList<TContainerType, TGridType> { using typename AbstractImmutableCellList<TContainerType, TGridType>::AbstractCellList; using typename AbstractCellList::CellCoord; using typename AbstractCellList::Members; //! @brief Gets sorted cell members at given cell coordinates virtual const Members& getSortedMembers(const CellCoord&) = 0; virtual const Members& getNeighborSortedMembers(const CellCoord&, const CellCoord&) = 0; virtual ~AbstractSortableCellList() = default; }; } // namespace CellList } // namespace Faunus
47.812121
118
0.709722
d29a1cf266bdd13654ebf5f4b3d9a953fcefdebf
1,038
h
C
cpp/transitive-macros/list/src/main/public/linked_list.h
fletcher86/native-samples
ea0d181eb685fa61d2f114414153eb6d2be81a6f
[ "Apache-2.0" ]
null
null
null
cpp/transitive-macros/list/src/main/public/linked_list.h
fletcher86/native-samples
ea0d181eb685fa61d2f114414153eb6d2be81a6f
[ "Apache-2.0" ]
null
null
null
cpp/transitive-macros/list/src/main/public/linked_list.h
fletcher86/native-samples
ea0d181eb685fa61d2f114414153eb6d2be81a6f
[ "Apache-2.0" ]
null
null
null
/* * A linked list implementation. */ #pragma once #include <string> #ifdef _WIN32 # ifdef LIST_MODULE_EXPORT # define LIST_API __declspec(dllexport) # else # define LIST_API __declspec(dllimport) # endif #else # define LIST_API #endif class node; class LIST_API linked_list { public: linked_list() : head_(NULL) {} // Copy constructor/assignment linked_list(const linked_list &); linked_list & operator=(const linked_list &); // Default destructor ~linked_list() /*noexcept*/; // Adds the given element to this list void add(const std::string & element); // Removes the given element from this list, if present bool remove(const std::string & element); // Returns the size of this list std::size_t size() const; #ifdef EMPTY_CHECK bool empty() { return head_ == NULL; } #endif // Returns the element at the given index std::string & get(std::size_t index); const std::string & get(std::size_t index) const; private: node * head_; };
20.352941
59
0.66474
d2b91fb24292284112db698cb001601e6c3c3f9d
74,772
c
C
native/jni/external/selinux/libsemanage/src/direct_api.c
Joyoe/Magisk-nosbin_magisk-nohide
449441921740bf85926c14f41b3532822ca0eb65
[ "MIT" ]
2
2022-01-16T00:59:54.000Z
2022-02-09T12:00:48.000Z
native/jni/external/selinux/libsemanage/src/direct_api.c
Joyoe/Magisk-nosbin_magisk-nohide
449441921740bf85926c14f41b3532822ca0eb65
[ "MIT" ]
null
null
null
native/jni/external/selinux/libsemanage/src/direct_api.c
Joyoe/Magisk-nosbin_magisk-nohide
449441921740bf85926c14f41b3532822ca0eb65
[ "MIT" ]
2
2022-02-09T12:00:39.000Z
2022-02-21T18:34:46.000Z
/* Author: Jason Tang <jtang@tresys.com> * Christopher Ashworth <cashworth@tresys.com> * * Copyright (C) 2004-2006 Tresys Technology, LLC * Copyright (C) 2005 Red Hat, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include <sepol/module.h> #include <sepol/handle.h> #include <sepol/cil/cil.h> #include <selinux/selinux.h> #include <assert.h> #include <fcntl.h> #include <stdio.h> #include <stdio_ext.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/stat.h> #include <sys/types.h> #include <limits.h> #include <errno.h> #include <dirent.h> #include "user_internal.h" #include "seuser_internal.h" #include "port_internal.h" #include "ibpkey_internal.h" #include "ibendport_internal.h" #include "iface_internal.h" #include "boolean_internal.h" #include "fcontext_internal.h" #include "node_internal.h" #include "genhomedircon.h" #include "debug.h" #include "handle.h" #include "modules.h" #include "direct_api.h" #include "semanage_store.h" #include "database_policydb.h" #include "policy.h" #include <sys/mman.h> #include <sys/wait.h> #define PIPE_READ 0 #define PIPE_WRITE 1 #define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0])) static void semanage_direct_destroy(semanage_handle_t * sh); static int semanage_direct_disconnect(semanage_handle_t * sh); static int semanage_direct_begintrans(semanage_handle_t * sh); static int semanage_direct_commit(semanage_handle_t * sh); static int semanage_direct_install(semanage_handle_t * sh, char *data, size_t data_len, const char *module_name, const char *lang_ext); static int semanage_direct_install_file(semanage_handle_t * sh, const char *module_name); static int semanage_direct_extract(semanage_handle_t * sh, semanage_module_key_t *modkey, int extract_cil, void **mapped_data, size_t *data_len, semanage_module_info_t **modinfo); static int semanage_direct_remove(semanage_handle_t * sh, char *module_name); static int semanage_direct_list(semanage_handle_t * sh, semanage_module_info_t ** modinfo, int *num_modules); static int semanage_direct_get_enabled(semanage_handle_t *sh, const semanage_module_key_t *modkey, int *enabled); static int semanage_direct_set_enabled(semanage_handle_t *sh, const semanage_module_key_t *modkey, int enabled); static int semanage_direct_get_module_info(semanage_handle_t *sh, const semanage_module_key_t *modkey, semanage_module_info_t **modinfo); static int semanage_direct_list_all(semanage_handle_t *sh, semanage_module_info_t **modinfo, int *num_modules); static int semanage_direct_install_info(semanage_handle_t *sh, const semanage_module_info_t *modinfo, char *data, size_t data_len); static int semanage_direct_remove_key(semanage_handle_t *sh, const semanage_module_key_t *modkey); static struct semanage_policy_table direct_funcs = { .get_serial = semanage_direct_get_serial, .destroy = semanage_direct_destroy, .disconnect = semanage_direct_disconnect, .begin_trans = semanage_direct_begintrans, .commit = semanage_direct_commit, .install = semanage_direct_install, .extract = semanage_direct_extract, .install_file = semanage_direct_install_file, .remove = semanage_direct_remove, .list = semanage_direct_list, .get_enabled = semanage_direct_get_enabled, .set_enabled = semanage_direct_set_enabled, .get_module_info = semanage_direct_get_module_info, .list_all = semanage_direct_list_all, .install_info = semanage_direct_install_info, .remove_key = semanage_direct_remove_key, }; int semanage_direct_is_managed(semanage_handle_t * sh) { if (semanage_check_init(sh, sh->conf->store_root_path)) goto err; if (semanage_access_check(sh) < 0) return 0; return 1; err: ERR(sh, "could not check whether policy is managed"); return STATUS_ERR; } /* Check that the module store exists, creating it if necessary. */ int semanage_direct_connect(semanage_handle_t * sh) { const char *path; struct stat sb; if (semanage_check_init(sh, sh->conf->store_root_path)) goto err; if (sh->create_store) if (semanage_create_store(sh, 1)) goto err; sh->u.direct.translock_file_fd = -1; sh->u.direct.activelock_file_fd = -1; /* set up function pointers */ sh->funcs = &direct_funcs; /* Object databases: local modifications */ if (user_base_file_dbase_init(sh, semanage_path(SEMANAGE_ACTIVE, SEMANAGE_USERS_BASE_LOCAL), semanage_path(SEMANAGE_TMP, SEMANAGE_USERS_BASE_LOCAL), semanage_user_base_dbase_local(sh)) < 0) goto err; if (user_extra_file_dbase_init(sh, semanage_path(SEMANAGE_ACTIVE, SEMANAGE_USERS_EXTRA_LOCAL), semanage_path(SEMANAGE_TMP, SEMANAGE_USERS_EXTRA_LOCAL), semanage_user_extra_dbase_local(sh)) < 0) goto err; if (user_join_dbase_init(sh, semanage_user_base_dbase_local(sh), semanage_user_extra_dbase_local(sh), semanage_user_dbase_local(sh)) < 0) goto err; if (port_file_dbase_init(sh, semanage_path(SEMANAGE_ACTIVE, SEMANAGE_PORTS_LOCAL), semanage_path(SEMANAGE_TMP, SEMANAGE_PORTS_LOCAL), semanage_port_dbase_local(sh)) < 0) goto err; if (iface_file_dbase_init(sh, semanage_path(SEMANAGE_ACTIVE, SEMANAGE_INTERFACES_LOCAL), semanage_path(SEMANAGE_TMP, SEMANAGE_INTERFACES_LOCAL), semanage_iface_dbase_local(sh)) < 0) goto err; if (bool_file_dbase_init(sh, semanage_path(SEMANAGE_ACTIVE, SEMANAGE_BOOLEANS_LOCAL), semanage_path(SEMANAGE_TMP, SEMANAGE_BOOLEANS_LOCAL), semanage_bool_dbase_local(sh)) < 0) goto err; if (fcontext_file_dbase_init(sh, semanage_path(SEMANAGE_ACTIVE, SEMANAGE_STORE_FC_LOCAL), semanage_path(SEMANAGE_TMP, SEMANAGE_STORE_FC_LOCAL), semanage_fcontext_dbase_local(sh)) < 0) goto err; if (fcontext_file_dbase_init(sh, semanage_path(SEMANAGE_ACTIVE, SEMANAGE_STORE_FC_HOMEDIRS), semanage_path(SEMANAGE_TMP, SEMANAGE_STORE_FC_HOMEDIRS), semanage_fcontext_dbase_homedirs(sh)) < 0) goto err; if (seuser_file_dbase_init(sh, semanage_path(SEMANAGE_ACTIVE, SEMANAGE_SEUSERS_LOCAL), semanage_path(SEMANAGE_TMP, SEMANAGE_SEUSERS_LOCAL), semanage_seuser_dbase_local(sh)) < 0) goto err; if (node_file_dbase_init(sh, semanage_path(SEMANAGE_ACTIVE, SEMANAGE_NODES_LOCAL), semanage_path(SEMANAGE_TMP, SEMANAGE_NODES_LOCAL), semanage_node_dbase_local(sh)) < 0) goto err; if (ibpkey_file_dbase_init(sh, semanage_path(SEMANAGE_ACTIVE, SEMANAGE_IBPKEYS_LOCAL), semanage_path(SEMANAGE_TMP, SEMANAGE_IBPKEYS_LOCAL), semanage_ibpkey_dbase_local(sh)) < 0) goto err; if (ibendport_file_dbase_init(sh, semanage_path(SEMANAGE_ACTIVE, SEMANAGE_IBENDPORTS_LOCAL), semanage_path(SEMANAGE_TMP, SEMANAGE_IBENDPORTS_LOCAL), semanage_ibendport_dbase_local(sh)) < 0) goto err; /* Object databases: local modifications + policy */ if (user_base_policydb_dbase_init(sh, semanage_user_base_dbase_policy(sh)) < 0) goto err; if (user_extra_file_dbase_init(sh, semanage_path(SEMANAGE_ACTIVE, SEMANAGE_USERS_EXTRA), semanage_path(SEMANAGE_TMP, SEMANAGE_USERS_EXTRA), semanage_user_extra_dbase_policy(sh)) < 0) goto err; if (user_join_dbase_init(sh, semanage_user_base_dbase_policy(sh), semanage_user_extra_dbase_policy(sh), semanage_user_dbase_policy(sh)) < 0) goto err; if (port_policydb_dbase_init(sh, semanage_port_dbase_policy(sh)) < 0) goto err; if (ibpkey_policydb_dbase_init(sh, semanage_ibpkey_dbase_policy(sh)) < 0) goto err; if (ibendport_policydb_dbase_init(sh, semanage_ibendport_dbase_policy(sh)) < 0) goto err; if (iface_policydb_dbase_init(sh, semanage_iface_dbase_policy(sh)) < 0) goto err; if (bool_policydb_dbase_init(sh, semanage_bool_dbase_policy(sh)) < 0) goto err; if (fcontext_file_dbase_init(sh, semanage_path(SEMANAGE_ACTIVE, SEMANAGE_STORE_FC), semanage_path(SEMANAGE_TMP, SEMANAGE_STORE_FC), semanage_fcontext_dbase_policy(sh)) < 0) goto err; if (seuser_file_dbase_init(sh, semanage_path(SEMANAGE_ACTIVE, SEMANAGE_STORE_SEUSERS), semanage_path(SEMANAGE_TMP, SEMANAGE_STORE_SEUSERS), semanage_seuser_dbase_policy(sh)) < 0) goto err; if (node_policydb_dbase_init(sh, semanage_node_dbase_policy(sh)) < 0) goto err; /* Active kernel policy */ if (bool_activedb_dbase_init(sh, semanage_bool_dbase_active(sh)) < 0) goto err; /* set the disable dontaudit value */ path = semanage_path(SEMANAGE_ACTIVE, SEMANAGE_DISABLE_DONTAUDIT); if (stat(path, &sb) == 0) sepol_set_disable_dontaudit(sh->sepolh, 1); else if (errno == ENOENT) { /* The file does not exist */ sepol_set_disable_dontaudit(sh->sepolh, 0); } else { ERR(sh, "Unable to access %s: %s\n", path, strerror(errno)); goto err; } return STATUS_SUCCESS; err: ERR(sh, "could not establish direct connection"); return STATUS_ERR; } static void semanage_direct_destroy(semanage_handle_t * sh __attribute__ ((unused))) { /* do nothing */ } static int semanage_remove_tmps(semanage_handle_t *sh) { if (sh->commit_err) return 0; /* destroy sandbox if it exists */ if (semanage_remove_directory (semanage_path(SEMANAGE_TMP, SEMANAGE_TOPLEVEL)) < 0) { if (errno != ENOENT) { ERR(sh, "Could not cleanly remove sandbox %s.", semanage_path(SEMANAGE_TMP, SEMANAGE_TOPLEVEL)); return -1; } } /* destroy tmp policy if it exists */ if (semanage_remove_directory (semanage_final_path(SEMANAGE_FINAL_TMP, SEMANAGE_FINAL_TOPLEVEL)) < 0) { if (errno != ENOENT) { ERR(sh, "Could not cleanly remove tmp %s.", semanage_final_path(SEMANAGE_FINAL_TMP, SEMANAGE_FINAL_TOPLEVEL)); return -1; } } return 0; } static int semanage_direct_disconnect(semanage_handle_t *sh) { int retval = 0; /* destroy transaction and remove tmp files if no commit error */ if (sh->is_in_transaction) { retval = semanage_remove_tmps(sh); semanage_release_trans_lock(sh); } /* Release object databases: local modifications */ user_base_file_dbase_release(semanage_user_base_dbase_local(sh)); user_extra_file_dbase_release(semanage_user_extra_dbase_local(sh)); user_join_dbase_release(semanage_user_dbase_local(sh)); port_file_dbase_release(semanage_port_dbase_local(sh)); ibpkey_file_dbase_release(semanage_ibpkey_dbase_local(sh)); ibendport_file_dbase_release(semanage_ibendport_dbase_local(sh)); iface_file_dbase_release(semanage_iface_dbase_local(sh)); bool_file_dbase_release(semanage_bool_dbase_local(sh)); fcontext_file_dbase_release(semanage_fcontext_dbase_local(sh)); fcontext_file_dbase_release(semanage_fcontext_dbase_homedirs(sh)); seuser_file_dbase_release(semanage_seuser_dbase_local(sh)); node_file_dbase_release(semanage_node_dbase_local(sh)); /* Release object databases: local modifications + policy */ user_base_policydb_dbase_release(semanage_user_base_dbase_policy(sh)); user_extra_file_dbase_release(semanage_user_extra_dbase_policy(sh)); user_join_dbase_release(semanage_user_dbase_policy(sh)); port_policydb_dbase_release(semanage_port_dbase_policy(sh)); ibpkey_policydb_dbase_release(semanage_ibpkey_dbase_policy(sh)); ibendport_policydb_dbase_release(semanage_ibendport_dbase_policy(sh)); iface_policydb_dbase_release(semanage_iface_dbase_policy(sh)); bool_policydb_dbase_release(semanage_bool_dbase_policy(sh)); fcontext_file_dbase_release(semanage_fcontext_dbase_policy(sh)); seuser_file_dbase_release(semanage_seuser_dbase_policy(sh)); node_policydb_dbase_release(semanage_node_dbase_policy(sh)); /* Release object databases: active kernel policy */ bool_activedb_dbase_release(semanage_bool_dbase_active(sh)); return retval; } static int semanage_direct_begintrans(semanage_handle_t * sh) { if (semanage_get_trans_lock(sh) < 0) { return -1; } if ((semanage_make_sandbox(sh)) < 0) { return -1; } if ((semanage_make_final(sh)) < 0) { return -1; } return 0; } /********************* utility functions *********************/ /* Takes a module stored in 'module_data' and parses its headers. * Sets reference variables 'module_name' to module's name, and * 'version' to module's version. The caller is responsible for * free()ing 'module_name', and 'version'; they will be * set to NULL upon entering this function. Returns 0 on success, -1 * if out of memory. */ static int parse_module_headers(semanage_handle_t * sh, char *module_data, size_t data_len, char **module_name, char **version) { struct sepol_policy_file *pf; int file_type; *module_name = *version = NULL; if (sepol_policy_file_create(&pf)) { ERR(sh, "Out of memory!"); return -1; } sepol_policy_file_set_mem(pf, module_data, data_len); sepol_policy_file_set_handle(pf, sh->sepolh); if (module_data != NULL && data_len > 0) sepol_module_package_info(pf, &file_type, module_name, version); sepol_policy_file_free(pf); return 0; } #include <stdlib.h> #include <bzlib.h> #include <string.h> #include <sys/sendfile.h> /* bzip() a data to a file, returning the total number of compressed bytes * in the file. Returns -1 if file could not be compressed. */ static ssize_t bzip(semanage_handle_t *sh, const char *filename, char *data, size_t num_bytes) { BZFILE* b; size_t size = 1<<16; int bzerror; size_t total = 0; size_t len = 0; FILE *f; if ((f = fopen(filename, "wb")) == NULL) { return -1; } if (!sh->conf->bzip_blocksize) { if (fwrite(data, 1, num_bytes, f) < num_bytes) { fclose(f); return -1; } fclose(f); return num_bytes; } b = BZ2_bzWriteOpen( &bzerror, f, sh->conf->bzip_blocksize, 0, 0); if (bzerror != BZ_OK) { BZ2_bzWriteClose ( &bzerror, b, 1, 0, 0 ); return -1; } while ( num_bytes > total ) { if (num_bytes - total > size) { len = size; } else { len = num_bytes - total; } BZ2_bzWrite ( &bzerror, b, &data[total], len ); if (bzerror == BZ_IO_ERROR) { BZ2_bzWriteClose ( &bzerror, b, 1, 0, 0 ); return -1; } total += len; } BZ2_bzWriteClose ( &bzerror, b, 0, 0, 0 ); fclose(f); if (bzerror == BZ_IO_ERROR) { return -1; } return total; } #define BZ2_MAGICSTR "BZh" #define BZ2_MAGICLEN (sizeof(BZ2_MAGICSTR)-1) /* bunzip() a file to '*data', returning the total number of uncompressed bytes * in the file. Returns -1 if file could not be decompressed. */ ssize_t bunzip(semanage_handle_t *sh, FILE *f, char **data) { BZFILE* b = NULL; size_t nBuf; char* buf = NULL; size_t size = 1<<18; size_t bufsize = size; int bzerror; size_t total = 0; char* uncompress = NULL; char* tmpalloc = NULL; int ret = -1; buf = malloc(bufsize); if (buf == NULL) { ERR(sh, "Failure allocating memory."); goto exit; } /* Check if the file is bzipped */ bzerror = fread(buf, 1, BZ2_MAGICLEN, f); rewind(f); if ((bzerror != BZ2_MAGICLEN) || memcmp(buf, BZ2_MAGICSTR, BZ2_MAGICLEN)) { goto exit; } b = BZ2_bzReadOpen ( &bzerror, f, 0, sh->conf->bzip_small, NULL, 0 ); if ( bzerror != BZ_OK ) { ERR(sh, "Failure opening bz2 archive."); goto exit; } uncompress = malloc(size); if (uncompress == NULL) { ERR(sh, "Failure allocating memory."); goto exit; } while ( bzerror == BZ_OK) { nBuf = BZ2_bzRead ( &bzerror, b, buf, bufsize); if (( bzerror == BZ_OK ) || ( bzerror == BZ_STREAM_END )) { if (total + nBuf > size) { size *= 2; tmpalloc = realloc(uncompress, size); if (tmpalloc == NULL) { ERR(sh, "Failure allocating memory."); goto exit; } uncompress = tmpalloc; } memcpy(&uncompress[total], buf, nBuf); total += nBuf; } } if ( bzerror != BZ_STREAM_END ) { ERR(sh, "Failure reading bz2 archive."); goto exit; } ret = total; *data = uncompress; exit: BZ2_bzReadClose ( &bzerror, b ); free(buf); if ( ret < 0 ) { free(uncompress); } return ret; } /* mmap() a file to '*data', * If the file is bzip compressed map_file will uncompress * the file into '*data'. * Returns the total number of bytes in memory . * Returns -1 if file could not be opened or mapped. */ static ssize_t map_file(semanage_handle_t *sh, const char *path, char **data, int *compressed) { ssize_t size = -1; char *uncompress; int fd = -1; FILE *file = NULL; fd = open(path, O_RDONLY); if (fd == -1) { ERR(sh, "Unable to open %s\n", path); return -1; } file = fdopen(fd, "r"); if (file == NULL) { ERR(sh, "Unable to open %s\n", path); close(fd); return -1; } if ((size = bunzip(sh, file, &uncompress)) > 0) { *data = mmap(0, size, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, 0, 0); if (*data == MAP_FAILED) { free(uncompress); fclose(file); return -1; } else { memcpy(*data, uncompress, size); } free(uncompress); *compressed = 1; } else { struct stat sb; if (fstat(fd, &sb) == -1 || (*data = mmap(NULL, sb.st_size, PROT_READ, MAP_PRIVATE, fd, 0)) == MAP_FAILED) { size = -1; } else { size = sb.st_size; } *compressed = 0; } fclose(file); return size; } /* Writes a block of data to a file. Returns 0 on success, -1 on * error. */ static int write_file(semanage_handle_t * sh, const char *filename, char *data, size_t num_bytes) { int out; if ((out = open(filename, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR)) == -1) { ERR(sh, "Could not open %s for writing.", filename); return -1; } if (write(out, data, num_bytes) == -1) { ERR(sh, "Error while writing to %s.", filename); close(out); return -1; } close(out); return 0; } static int semanage_direct_update_user_extra(semanage_handle_t * sh, cil_db_t *cildb) { const char *ofilename = NULL; int retval = -1; char *data = NULL; size_t size = 0; dbase_config_t *pusers_extra = semanage_user_extra_dbase_policy(sh); retval = cil_userprefixes_to_string(cildb, &data, &size); if (retval != SEPOL_OK) { goto cleanup; } if (size > 0) { /* * Write the users_extra entries from CIL modules. * This file is used as our baseline when we do not require * re-linking. */ ofilename = semanage_path(SEMANAGE_TMP, SEMANAGE_USERS_EXTRA_LINKED); if (ofilename == NULL) { retval = -1; goto cleanup; } retval = write_file(sh, ofilename, data, size); if (retval < 0) goto cleanup; /* * Write the users_extra file; users_extra.local * will be merged into this file. */ ofilename = semanage_path(SEMANAGE_TMP, SEMANAGE_USERS_EXTRA); if (ofilename == NULL) { retval = -1; goto cleanup; } retval = write_file(sh, ofilename, data, size); if (retval < 0) goto cleanup; pusers_extra->dtable->drop_cache(pusers_extra->dbase); } else { retval = pusers_extra->dtable->clear(sh, pusers_extra->dbase); } cleanup: free(data); return retval; } static int semanage_direct_update_seuser(semanage_handle_t * sh, cil_db_t *cildb) { const char *ofilename = NULL; int retval = -1; char *data = NULL; size_t size = 0; dbase_config_t *pseusers = semanage_seuser_dbase_policy(sh); retval = cil_selinuxusers_to_string(cildb, &data, &size); if (retval != SEPOL_OK) { goto cleanup; } if (size > 0) { /* * Write the seusers entries from CIL modules. * This file is used as our baseline when we do not require * re-linking. */ ofilename = semanage_path(SEMANAGE_TMP, SEMANAGE_SEUSERS_LINKED); if (ofilename == NULL) { retval = -1; goto cleanup; } retval = write_file(sh, ofilename, data, size); if (retval < 0) goto cleanup; /* * Write the seusers file; seusers.local will be merged into * this file. */ ofilename = semanage_path(SEMANAGE_TMP, SEMANAGE_STORE_SEUSERS); if (ofilename == NULL) { retval = -1; goto cleanup; } retval = write_file(sh, ofilename, data, size); if (retval < 0) goto cleanup; pseusers->dtable->drop_cache(pseusers->dbase); } else { retval = pseusers->dtable->clear(sh, pseusers->dbase); } cleanup: free(data); return retval; } static int read_from_pipe_to_data(semanage_handle_t *sh, size_t initial_len, int fd, char **out_data_read, size_t *out_read_len) { size_t max_len = initial_len; size_t read_len = 0; size_t data_read_len = 0; char *data_read = NULL; if (max_len <= 0) { max_len = 1; } data_read = malloc(max_len * sizeof(*data_read)); if (data_read == NULL) { ERR(sh, "Failed to malloc, out of memory.\n"); return -1; } while ((read_len = read(fd, data_read + data_read_len, max_len - data_read_len)) > 0) { data_read_len += read_len; if (data_read_len == max_len) { max_len *= 2; data_read = realloc(data_read, max_len); if (data_read == NULL) { ERR(sh, "Failed to realloc, out of memory.\n"); return -1; } } } *out_read_len = data_read_len; *out_data_read = data_read; return 0; } static int semanage_pipe_data(semanage_handle_t *sh, char *path, char *in_data, size_t in_data_len, char **out_data, size_t *out_data_len, char **err_data, size_t *err_data_len) { int input_fd[2] = {-1, -1}; int output_fd[2] = {-1, -1}; int err_fd[2] = {-1, -1}; pid_t pid; char *data_read = NULL; char *err_data_read = NULL; int retval; int status = 0; size_t initial_len; size_t data_read_len = 0; size_t err_data_read_len = 0; struct sigaction old_signal; struct sigaction new_signal; new_signal.sa_handler = SIG_IGN; sigemptyset(&new_signal.sa_mask); new_signal.sa_flags = 0; /* This is needed in case the read end of input_fd is closed causing a SIGPIPE signal to be sent. * If SIGPIPE is not caught, the signal will cause semanage to terminate immediately. The sigaction below * creates a new_signal that ignores SIGPIPE allowing the write to exit cleanly. * * Another sigaction is called in cleanup to restore the original behavior when a SIGPIPE is received. */ sigaction(SIGPIPE, &new_signal, &old_signal); retval = pipe(input_fd); if (retval == -1) { ERR(sh, "Unable to create pipe for input pipe: %s\n", strerror(errno)); goto cleanup; } retval = pipe(output_fd); if (retval == -1) { ERR(sh, "Unable to create pipe for output pipe: %s\n", strerror(errno)); goto cleanup; } retval = pipe(err_fd); if (retval == -1) { ERR(sh, "Unable to create pipe for error pipe: %s\n", strerror(errno)); goto cleanup; } pid = fork(); if (pid == -1) { ERR(sh, "Unable to fork from parent: %s.", strerror(errno)); retval = -1; goto cleanup; } else if (pid == 0) { retval = dup2(input_fd[PIPE_READ], STDIN_FILENO); if (retval == -1) { ERR(sh, "Unable to dup2 input pipe: %s\n", strerror(errno)); goto cleanup; } retval = dup2(output_fd[PIPE_WRITE], STDOUT_FILENO); if (retval == -1) { ERR(sh, "Unable to dup2 output pipe: %s\n", strerror(errno)); goto cleanup; } retval = dup2(err_fd[PIPE_WRITE], STDERR_FILENO); if (retval == -1) { ERR(sh, "Unable to dup2 error pipe: %s\n", strerror(errno)); goto cleanup; } retval = close(input_fd[PIPE_WRITE]); if (retval == -1) { ERR(sh, "Unable to close input pipe: %s\n", strerror(errno)); goto cleanup; } retval = close(output_fd[PIPE_READ]); if (retval == -1) { ERR(sh, "Unable to close output pipe: %s\n", strerror(errno)); goto cleanup; } retval = close(err_fd[PIPE_READ]); if (retval == -1) { ERR(sh, "Unable to close error pipe: %s\n", strerror(errno)); goto cleanup; } retval = execl(path, path, NULL); if (retval == -1) { ERR(sh, "Unable to execute %s : %s\n", path, strerror(errno)); _exit(EXIT_FAILURE); } } else { retval = close(input_fd[PIPE_READ]); input_fd[PIPE_READ] = -1; if (retval == -1) { ERR(sh, "Unable to close read end of input pipe: %s\n", strerror(errno)); goto cleanup; } retval = close(output_fd[PIPE_WRITE]); output_fd[PIPE_WRITE] = -1; if (retval == -1) { ERR(sh, "Unable to close write end of output pipe: %s\n", strerror(errno)); goto cleanup; } retval = close(err_fd[PIPE_WRITE]); err_fd[PIPE_WRITE] = -1; if (retval == -1) { ERR(sh, "Unable to close write end of error pipe: %s\n", strerror(errno)); goto cleanup; } retval = write(input_fd[PIPE_WRITE], in_data, in_data_len); if (retval == -1) { ERR(sh, "Failed to write data to input pipe: %s\n", strerror(errno)); goto cleanup; } retval = close(input_fd[PIPE_WRITE]); input_fd[PIPE_WRITE] = -1; if (retval == -1) { ERR(sh, "Unable to close write end of input pipe: %s\n", strerror(errno)); goto cleanup; } initial_len = 1 << 17; retval = read_from_pipe_to_data(sh, initial_len, output_fd[PIPE_READ], &data_read, &data_read_len); if (retval != 0) { goto cleanup; } retval = close(output_fd[PIPE_READ]); output_fd[PIPE_READ] = -1; if (retval == -1) { ERR(sh, "Unable to close read end of output pipe: %s\n", strerror(errno)); goto cleanup; } initial_len = 1 << 9; retval = read_from_pipe_to_data(sh, initial_len, err_fd[PIPE_READ], &err_data_read, &err_data_read_len); if (retval != 0) { goto cleanup; } retval = close(err_fd[PIPE_READ]); err_fd[PIPE_READ] = -1; if (retval == -1) { ERR(sh, "Unable to close read end of error pipe: %s\n", strerror(errno)); goto cleanup; } if (waitpid(pid, &status, 0) == -1 || !WIFEXITED(status)) { ERR(sh, "Child process %s did not exit cleanly.", path); retval = -1; goto cleanup; } if (WEXITSTATUS(status) != 0) { ERR(sh, "Child process %s failed with code: %d.", path, WEXITSTATUS(status)); retval = -1; goto cleanup; } } retval = 0; cleanup: sigaction(SIGPIPE, &old_signal, NULL); if (data_read != NULL) { *out_data = data_read; *out_data_len = data_read_len; } if (err_data_read != NULL) { *err_data = err_data_read; *err_data_len = err_data_read_len; } if (output_fd[PIPE_READ] != -1) { close(output_fd[PIPE_READ]); } if (output_fd[PIPE_WRITE] != -1) { close(output_fd[PIPE_WRITE]); } if (err_fd[PIPE_READ] != -1) { close(err_fd[PIPE_READ]); } if (err_fd[PIPE_WRITE] != -1) { close(err_fd[PIPE_WRITE]); } if (input_fd[PIPE_READ] != -1) { close(input_fd[PIPE_READ]); } if (input_fd[PIPE_WRITE] != -1) { close(input_fd[PIPE_WRITE]); } return retval; } static int semanage_direct_write_langext(semanage_handle_t *sh, const char *lang_ext, const semanage_module_info_t *modinfo) { int ret = -1; char fn[PATH_MAX]; FILE *fp = NULL; ret = semanage_module_get_path(sh, modinfo, SEMANAGE_MODULE_PATH_LANG_EXT, fn, sizeof(fn)); if (ret != 0) { goto cleanup; } fp = fopen(fn, "w"); if (fp == NULL) { ERR(sh, "Unable to open %s module ext file.", modinfo->name); ret = -1; goto cleanup; } if (fputs(lang_ext, fp) < 0) { ERR(sh, "Unable to write %s module ext file.", modinfo->name); ret = -1; goto cleanup; } if (fclose(fp) != 0) { ERR(sh, "Unable to close %s module ext file.", modinfo->name); ret = -1; goto cleanup; } fp = NULL; ret = 0; cleanup: if (fp != NULL) fclose(fp); return ret; } static int semanage_compile_module(semanage_handle_t *sh, semanage_module_info_t *modinfo) { char cil_path[PATH_MAX]; char hll_path[PATH_MAX]; char *compiler_path = NULL; char *cil_data = NULL; char *err_data = NULL; char *hll_data = NULL; char *start = NULL; char *end = NULL; ssize_t hll_data_len = 0; ssize_t bzip_status; int status = 0; int compressed; size_t cil_data_len = 0; size_t err_data_len = 0; if (!strcasecmp(modinfo->lang_ext, "cil")) { goto cleanup; } status = semanage_get_hll_compiler_path(sh, modinfo->lang_ext, &compiler_path); if (status != 0) { goto cleanup; } status = semanage_module_get_path( sh, modinfo, SEMANAGE_MODULE_PATH_CIL, cil_path, sizeof(cil_path)); if (status != 0) { goto cleanup; } status = semanage_module_get_path( sh, modinfo, SEMANAGE_MODULE_PATH_HLL, hll_path, sizeof(hll_path)); if (status != 0) { goto cleanup; } if ((hll_data_len = map_file(sh, hll_path, &hll_data, &compressed)) <= 0) { ERR(sh, "Unable to read file %s\n", hll_path); status = -1; goto cleanup; } status = semanage_pipe_data(sh, compiler_path, hll_data, (size_t)hll_data_len, &cil_data, &cil_data_len, &err_data, &err_data_len); if (err_data_len > 0) { for (start = end = err_data; end < err_data + err_data_len; end++) { if (*end == '\n') { fprintf(stderr, "%s: ", modinfo->name); fwrite(start, 1, end - start + 1, stderr); start = end + 1; } } if (end != start) { fprintf(stderr, "%s: ", modinfo->name); fwrite(start, 1, end - start, stderr); fprintf(stderr, "\n"); } } if (status != 0) { goto cleanup; } bzip_status = bzip(sh, cil_path, cil_data, cil_data_len); if (bzip_status == -1) { ERR(sh, "Failed to bzip %s\n", cil_path); status = -1; goto cleanup; } if (sh->conf->remove_hll == 1) { status = unlink(hll_path); if (status != 0) { ERR(sh, "Error while removing HLL file %s: %s", hll_path, strerror(errno)); goto cleanup; } status = semanage_direct_write_langext(sh, "cil", modinfo); if (status != 0) { goto cleanup; } } cleanup: if (hll_data_len > 0) { munmap(hll_data, hll_data_len); } free(cil_data); free(err_data); free(compiler_path); return status; } static int semanage_compile_hll_modules(semanage_handle_t *sh, semanage_module_info_t *modinfos, int num_modinfos) { int status = 0; int i; char cil_path[PATH_MAX]; struct stat sb; assert(sh); assert(modinfos); for (i = 0; i < num_modinfos; i++) { status = semanage_module_get_path( sh, &modinfos[i], SEMANAGE_MODULE_PATH_CIL, cil_path, sizeof(cil_path)); if (status != 0) { goto cleanup; } if (semanage_get_ignore_module_cache(sh) == 0 && (status = stat(cil_path, &sb)) == 0) { continue; } if (status != 0 && errno != ENOENT) { ERR(sh, "Unable to access %s: %s\n", cil_path, strerror(errno)); goto cleanup; //an error in the "stat" call } status = semanage_compile_module(sh, &modinfos[i]); if (status < 0) { goto cleanup; } } status = 0; cleanup: return status; } /* Copies a file from src to dst. If dst already exists then * overwrite it. If source doesn't exist then return success. * Returns 0 on success, -1 on error. */ static int copy_file_if_exists(const char *src, const char *dst, mode_t mode){ int rc = semanage_copy_file(src, dst, mode, false); return (rc < 0 && errno != ENOENT) ? rc : 0; } /********************* direct API functions ********************/ /* Commits all changes in sandbox to the actual kernel policy. * Returns commit number on success, -1 on error. */ static int semanage_direct_commit(semanage_handle_t * sh) { char **mod_filenames = NULL; char *fc_buffer = NULL; size_t fc_buffer_len = 0; const char *ofilename = NULL; const char *path; int retval = -1, num_modinfos = 0, i; sepol_policydb_t *out = NULL; struct cil_db *cildb = NULL; semanage_module_info_t *modinfos = NULL; mode_t mask = umask(0077); struct stat sb; int do_rebuild, do_write_kernel, do_install; int fcontexts_modified, ports_modified, seusers_modified, disable_dontaudit, preserve_tunables, ibpkeys_modified, ibendports_modified; dbase_config_t *users = semanage_user_dbase_local(sh); dbase_config_t *users_base = semanage_user_base_dbase_local(sh); dbase_config_t *pusers_base = semanage_user_base_dbase_policy(sh); dbase_config_t *pusers_extra = semanage_user_extra_dbase_policy(sh); dbase_config_t *ports = semanage_port_dbase_local(sh); dbase_config_t *pports = semanage_port_dbase_policy(sh); dbase_config_t *ibpkeys = semanage_ibpkey_dbase_local(sh); dbase_config_t *pibpkeys = semanage_ibpkey_dbase_policy(sh); dbase_config_t *ibendports = semanage_ibendport_dbase_local(sh); dbase_config_t *pibendports = semanage_ibendport_dbase_policy(sh); dbase_config_t *bools = semanage_bool_dbase_local(sh); dbase_config_t *pbools = semanage_bool_dbase_policy(sh); dbase_config_t *ifaces = semanage_iface_dbase_local(sh); dbase_config_t *pifaces = semanage_iface_dbase_policy(sh); dbase_config_t *nodes = semanage_node_dbase_local(sh); dbase_config_t *pnodes = semanage_node_dbase_policy(sh); dbase_config_t *fcontexts = semanage_fcontext_dbase_local(sh); dbase_config_t *pfcontexts = semanage_fcontext_dbase_policy(sh); dbase_config_t *seusers = semanage_seuser_dbase_local(sh); dbase_config_t *pseusers = semanage_seuser_dbase_policy(sh); /* Modified flags that we need to use more than once. */ ports_modified = ports->dtable->is_modified(ports->dbase); ibpkeys_modified = ibpkeys->dtable->is_modified(ibpkeys->dbase); ibendports_modified = ibendports->dtable->is_modified(ibendports->dbase); seusers_modified = seusers->dtable->is_modified(seusers->dbase); fcontexts_modified = fcontexts->dtable->is_modified(fcontexts->dbase); /* Rebuild if explicitly requested or any module changes occurred. */ do_rebuild = sh->do_rebuild | sh->modules_modified; /* Create or remove the disable_dontaudit flag file. */ path = semanage_path(SEMANAGE_TMP, SEMANAGE_DISABLE_DONTAUDIT); if (stat(path, &sb) == 0) do_rebuild |= !(sepol_get_disable_dontaudit(sh->sepolh) == 1); else if (errno == ENOENT) { /* The file does not exist */ do_rebuild |= (sepol_get_disable_dontaudit(sh->sepolh) == 1); } else { ERR(sh, "Unable to access %s: %s\n", path, strerror(errno)); retval = -1; goto cleanup; } if (sepol_get_disable_dontaudit(sh->sepolh) == 1) { FILE *touch; touch = fopen(path, "w"); if (touch != NULL) { if (fclose(touch) != 0) { ERR(sh, "Error attempting to create disable_dontaudit flag."); goto cleanup; } } else { ERR(sh, "Error attempting to create disable_dontaudit flag."); goto cleanup; } } else { if (remove(path) == -1 && errno != ENOENT) { ERR(sh, "Error removing the disable_dontaudit flag."); goto cleanup; } } /* Create or remove the preserve_tunables flag file. */ path = semanage_path(SEMANAGE_TMP, SEMANAGE_PRESERVE_TUNABLES); if (stat(path, &sb) == 0) do_rebuild |= !(sepol_get_preserve_tunables(sh->sepolh) == 1); else if (errno == ENOENT) { /* The file does not exist */ do_rebuild |= (sepol_get_preserve_tunables(sh->sepolh) == 1); } else { ERR(sh, "Unable to access %s: %s\n", path, strerror(errno)); retval = -1; goto cleanup; } if (sepol_get_preserve_tunables(sh->sepolh) == 1) { FILE *touch; touch = fopen(path, "w"); if (touch != NULL) { if (fclose(touch) != 0) { ERR(sh, "Error attempting to create preserve_tunable flag."); goto cleanup; } } else { ERR(sh, "Error attempting to create preserve_tunable flag."); goto cleanup; } } else { if (remove(path) == -1 && errno != ENOENT) { ERR(sh, "Error removing the preserve_tunables flag."); goto cleanup; } } /* Before we do anything else, flush the join to its component parts. * This *does not* flush to disk automatically */ if (users->dtable->is_modified(users->dbase)) { retval = users->dtable->flush(sh, users->dbase); if (retval < 0) goto cleanup; } /* * This is for systems that have already migrated with an older version * of semanage_migrate_store. The older version did not copy * policy.kern so the policy binary must be rebuilt here. * This also ensures that any linked files that are required * in order to skip re-linking are present; otherwise, we force * a rebuild. */ if (!do_rebuild) { int files[] = {SEMANAGE_STORE_KERNEL, SEMANAGE_STORE_FC, SEMANAGE_STORE_SEUSERS, SEMANAGE_LINKED, SEMANAGE_SEUSERS_LINKED, SEMANAGE_USERS_EXTRA_LINKED}; for (i = 0; i < (int) ARRAY_SIZE(files); i++) { path = semanage_path(SEMANAGE_TMP, files[i]); if (stat(path, &sb) != 0) { if (errno != ENOENT) { ERR(sh, "Unable to access %s: %s\n", path, strerror(errno)); retval = -1; goto cleanup; } do_rebuild = 1; goto rebuild; } } } rebuild: /* * Now that we know whether or not a rebuild is required, * we can determine what else needs to be done. * We need to write the kernel policy if we are rebuilding * or if any other policy component that lives in the kernel * policy has been modified. * We need to install the policy files if any of the managed files * that live under /etc/selinux (kernel policy, seusers, file contexts) * will be modified. */ do_write_kernel = do_rebuild | ports_modified | ibpkeys_modified | ibendports_modified | bools->dtable->is_modified(bools->dbase) | ifaces->dtable->is_modified(ifaces->dbase) | nodes->dtable->is_modified(nodes->dbase) | users->dtable->is_modified(users_base->dbase); do_install = do_write_kernel | seusers_modified | fcontexts_modified; /* * If there were policy changes, or explicitly requested, or * any required files are missing, rebuild the policy. */ if (do_rebuild) { /* =================== Module expansion =============== */ retval = semanage_get_active_modules(sh, &modinfos, &num_modinfos); if (retval < 0) { goto cleanup; } if (num_modinfos == 0) { goto cleanup; } retval = semanage_compile_hll_modules(sh, modinfos, num_modinfos); if (retval < 0) { ERR(sh, "Failed to compile hll files into cil files.\n"); goto cleanup; } retval = semanage_get_cil_paths(sh, modinfos, num_modinfos, &mod_filenames); if (retval < 0) goto cleanup; retval = semanage_verify_modules(sh, mod_filenames, num_modinfos); if (retval < 0) goto cleanup; cil_db_init(&cildb); disable_dontaudit = sepol_get_disable_dontaudit(sh->sepolh); preserve_tunables = sepol_get_preserve_tunables(sh->sepolh); cil_set_disable_dontaudit(cildb, disable_dontaudit); cil_set_disable_neverallow(cildb, !(sh->conf->expand_check)); cil_set_preserve_tunables(cildb, preserve_tunables); cil_set_target_platform(cildb, sh->conf->target_platform); cil_set_policy_version(cildb, sh->conf->policyvers); if (sh->conf->handle_unknown != -1) { cil_set_handle_unknown(cildb, sh->conf->handle_unknown); } retval = semanage_load_files(sh, cildb, mod_filenames, num_modinfos); if (retval < 0) { goto cleanup; } retval = cil_compile(cildb); if (retval < 0) goto cleanup; retval = cil_build_policydb(cildb, &out); if (retval < 0) goto cleanup; /* File Contexts */ retval = cil_filecons_to_string(cildb, &fc_buffer, &fc_buffer_len); if (retval < 0) goto cleanup; /* Write the contexts (including template contexts) to a single file. */ ofilename = semanage_path(SEMANAGE_TMP, SEMANAGE_FC_TMPL); if (ofilename == NULL) { retval = -1; goto cleanup; } retval = write_file(sh, ofilename, fc_buffer, fc_buffer_len); if (retval < 0) goto cleanup; /* Split complete and template file contexts into their separate files. */ retval = semanage_split_fc(sh); if (retval < 0) goto cleanup; /* remove FC_TMPL now that it is now longer needed */ unlink(semanage_path(SEMANAGE_TMP, SEMANAGE_FC_TMPL)); pfcontexts->dtable->drop_cache(pfcontexts->dbase); /* SEUsers */ retval = semanage_direct_update_seuser(sh, cildb); if (retval < 0) goto cleanup; /* User Extra */ retval = semanage_direct_update_user_extra(sh, cildb); if (retval < 0) goto cleanup; cil_db_destroy(&cildb); /* Remove redundancies in binary policy if requested. */ if (sh->conf->optimize_policy) { retval = sepol_policydb_optimize(out); if (retval < 0) goto cleanup; } /* Write the linked policy before merging local changes. */ retval = semanage_write_policydb(sh, out, SEMANAGE_LINKED); if (retval < 0) goto cleanup; } else { /* Load the existing linked policy, w/o local changes */ retval = sepol_policydb_create(&out); if (retval < 0) goto cleanup; retval = semanage_read_policydb(sh, out, SEMANAGE_LINKED); if (retval < 0) goto cleanup; path = semanage_path(SEMANAGE_TMP, SEMANAGE_SEUSERS_LINKED); if (stat(path, &sb) == 0) { retval = semanage_copy_file(path, semanage_path(SEMANAGE_TMP, SEMANAGE_STORE_SEUSERS), 0, false); if (retval < 0) goto cleanup; pseusers->dtable->drop_cache(pseusers->dbase); } else if (errno == ENOENT) { /* The file does not exist */ pseusers->dtable->clear(sh, pseusers->dbase); } else { ERR(sh, "Unable to access %s: %s\n", path, strerror(errno)); retval = -1; goto cleanup; } path = semanage_path(SEMANAGE_TMP, SEMANAGE_USERS_EXTRA_LINKED); if (stat(path, &sb) == 0) { retval = semanage_copy_file(path, semanage_path(SEMANAGE_TMP, SEMANAGE_USERS_EXTRA), 0, false); if (retval < 0) goto cleanup; pusers_extra->dtable->drop_cache(pusers_extra->dbase); } else if (errno == ENOENT) { /* The file does not exist */ pusers_extra->dtable->clear(sh, pusers_extra->dbase); } else { ERR(sh, "Unable to access %s: %s\n", path, strerror(errno)); retval = -1; goto cleanup; } } /* Attach our databases to the policydb we just created or loaded. */ dbase_policydb_attach((dbase_policydb_t *) pusers_base->dbase, out); dbase_policydb_attach((dbase_policydb_t *) pports->dbase, out); dbase_policydb_attach((dbase_policydb_t *) pibpkeys->dbase, out); dbase_policydb_attach((dbase_policydb_t *) pibendports->dbase, out); dbase_policydb_attach((dbase_policydb_t *) pifaces->dbase, out); dbase_policydb_attach((dbase_policydb_t *) pbools->dbase, out); dbase_policydb_attach((dbase_policydb_t *) pnodes->dbase, out); /* Merge local changes */ retval = semanage_base_merge_components(sh); if (retval < 0) goto cleanup; if (do_write_kernel) { /* Write new kernel policy. */ retval = semanage_write_policydb(sh, out, SEMANAGE_STORE_KERNEL); if (retval < 0) goto cleanup; /* Run the kernel policy verifier, if any. */ retval = semanage_verify_kernel(sh); if (retval < 0) goto cleanup; } /* ======= Post-process: Validate non-policydb components ===== */ /* Validate local modifications to file contexts. * Note: those are still cached, even though they've been * merged into the main file_contexts. We won't check the * large file_contexts - checked at compile time */ if (do_rebuild || fcontexts_modified) { retval = semanage_fcontext_validate_local(sh, out); if (retval < 0) goto cleanup; } /* Validate local seusers against policy */ if (do_rebuild || seusers_modified) { retval = semanage_seuser_validate_local(sh, out); if (retval < 0) goto cleanup; } /* Validate local ports for overlap */ if (do_rebuild || ports_modified) { retval = semanage_port_validate_local(sh); if (retval < 0) goto cleanup; } /* Validate local ibpkeys for overlap */ if (do_rebuild || ibpkeys_modified) { retval = semanage_ibpkey_validate_local(sh); if (retval < 0) goto cleanup; } /* Validate local ibendports */ if (do_rebuild || ibendports_modified) { retval = semanage_ibendport_validate_local(sh); if (retval < 0) goto cleanup; } /* ================== Write non-policydb components ========= */ /* Commit changes to components */ retval = semanage_commit_components(sh); if (retval < 0) goto cleanup; retval = semanage_copy_file(semanage_path(SEMANAGE_TMP, SEMANAGE_STORE_KERNEL), semanage_final_path(SEMANAGE_FINAL_TMP, SEMANAGE_KERNEL), sh->conf->file_mode, false); if (retval < 0) { goto cleanup; } retval = copy_file_if_exists(semanage_path(SEMANAGE_TMP, SEMANAGE_STORE_FC_LOCAL), semanage_final_path(SEMANAGE_FINAL_TMP, SEMANAGE_FC_LOCAL), sh->conf->file_mode); if (retval < 0) { goto cleanup; } retval = copy_file_if_exists(semanage_path(SEMANAGE_TMP, SEMANAGE_STORE_FC), semanage_final_path(SEMANAGE_FINAL_TMP, SEMANAGE_FC), sh->conf->file_mode); if (retval < 0) { goto cleanup; } retval = copy_file_if_exists(semanage_path(SEMANAGE_TMP, SEMANAGE_STORE_SEUSERS), semanage_final_path(SEMANAGE_FINAL_TMP, SEMANAGE_SEUSERS), sh->conf->file_mode); if (retval < 0) { goto cleanup; } /* run genhomedircon if its enabled, this should be the last operation * which requires the out policydb */ if (!sh->conf->disable_genhomedircon) { if (out){ if ((retval = semanage_genhomedircon(sh, out, sh->conf->usepasswd, sh->conf->ignoredirs)) != 0) { ERR(sh, "semanage_genhomedircon returned error code %d.", retval); goto cleanup; } /* file_contexts.homedirs was created in SEMANAGE_TMP store */ retval = semanage_copy_file( semanage_path(SEMANAGE_TMP, SEMANAGE_STORE_FC_HOMEDIRS), semanage_final_path(SEMANAGE_FINAL_TMP, SEMANAGE_FC_HOMEDIRS), sh->conf->file_mode, false); if (retval < 0) { goto cleanup; } } } else { WARN(sh, "WARNING: genhomedircon is disabled. \ See /etc/selinux/semanage.conf if you need to enable it."); } /* free out, if we don't free it before calling semanage_install_sandbox * then fork() may fail on low memory machines */ sepol_policydb_free(out); out = NULL; if (do_install) retval = semanage_install_sandbox(sh); cleanup: for (i = 0; i < num_modinfos; i++) { semanage_module_info_destroy(sh, &modinfos[i]); } free(modinfos); for (i = 0; mod_filenames != NULL && i < num_modinfos; i++) { free(mod_filenames[i]); } /* Detach from policydb, so it can be freed */ dbase_policydb_detach((dbase_policydb_t *) pusers_base->dbase); dbase_policydb_detach((dbase_policydb_t *) pports->dbase); dbase_policydb_detach((dbase_policydb_t *) pibpkeys->dbase); dbase_policydb_detach((dbase_policydb_t *) pibendports->dbase); dbase_policydb_detach((dbase_policydb_t *) pifaces->dbase); dbase_policydb_detach((dbase_policydb_t *) pnodes->dbase); dbase_policydb_detach((dbase_policydb_t *) pbools->dbase); free(mod_filenames); sepol_policydb_free(out); cil_db_destroy(&cildb); free(fc_buffer); /* Set commit_err so other functions can detect any errors. Note that * retval > 0 will be the commit number. */ if (retval < 0) sh->commit_err = retval; if (semanage_remove_tmps(sh) != 0) retval = -1; semanage_release_trans_lock(sh); umask(mask); return retval; } /* Writes a module to the sandbox's module directory, overwriting any * previous module stored within. Note that module data are not * free()d by this function; caller is responsible for deallocating it * if necessary. Returns 0 on success, -1 if out of memory, -2 if the * data does not represent a valid module file, -3 if error while * writing file. */ static int semanage_direct_install(semanage_handle_t * sh, char *data, size_t data_len, const char *module_name, const char *lang_ext) { int status = 0; int ret = 0; semanage_module_info_t modinfo; ret = semanage_module_info_init(sh, &modinfo); if (ret != 0) { status = -1; goto cleanup; } ret = semanage_module_info_set_priority(sh, &modinfo, sh->priority); if (ret != 0) { status = -1; goto cleanup; } ret = semanage_module_info_set_name(sh, &modinfo, module_name); if (ret != 0) { status = -1; goto cleanup; } ret = semanage_module_info_set_lang_ext(sh, &modinfo, lang_ext); if (ret != 0) { status = -1; goto cleanup; } ret = semanage_module_info_set_enabled(sh, &modinfo, -1); if (ret != 0) { status = -1; goto cleanup; } status = semanage_direct_install_info(sh, &modinfo, data, data_len); cleanup: semanage_module_info_destroy(sh, &modinfo); return status; } /* Attempts to link a module to the sandbox's module directory, unlinking any * previous module stored within. Returns 0 on success, -1 if out of memory, -2 if the * data does not represent a valid module file, -3 if error while * writing file. */ static int semanage_direct_install_file(semanage_handle_t * sh, const char *install_filename) { int retval = -1; char *data = NULL; ssize_t data_len = 0; int compressed = 0; char *path = NULL; char *filename; char *lang_ext = NULL; char *module_name = NULL; char *separator; char *version = NULL; if ((data_len = map_file(sh, install_filename, &data, &compressed)) <= 0) { ERR(sh, "Unable to read file %s\n", install_filename); retval = -1; goto cleanup; } path = strdup(install_filename); if (path == NULL) { ERR(sh, "No memory available for strdup.\n"); retval = -1; goto cleanup; } filename = basename(path); if (compressed) { separator = strrchr(filename, '.'); if (separator == NULL) { ERR(sh, "Compressed module does not have a valid extension."); retval = -1; goto cleanup; } *separator = '\0'; lang_ext = separator + 1; } separator = strrchr(filename, '.'); if (separator == NULL) { if (lang_ext == NULL) { ERR(sh, "Module does not have a valid extension."); retval = -1; goto cleanup; } } else { *separator = '\0'; lang_ext = separator + 1; } if (strcmp(lang_ext, "pp") == 0) { retval = parse_module_headers(sh, data, data_len, &module_name, &version); free(version); if (retval != 0) goto cleanup; } if (module_name == NULL) { module_name = strdup(filename); if (module_name == NULL) { ERR(sh, "No memory available for module_name.\n"); retval = -1; goto cleanup; } } else if (strcmp(module_name, filename) != 0) { fprintf(stderr, "Warning: SELinux userspace will refer to the module from %s as %s rather than %s\n", install_filename, module_name, filename); } retval = semanage_direct_install(sh, data, data_len, module_name, lang_ext); cleanup: if (data_len > 0) munmap(data, data_len); free(module_name); free(path); return retval; } static int semanage_direct_extract(semanage_handle_t * sh, semanage_module_key_t *modkey, int extract_cil, void **mapped_data, size_t *data_len, semanage_module_info_t **modinfo) { char module_path[PATH_MAX]; char input_file[PATH_MAX]; enum semanage_module_path_type file_type; int rc = -1; semanage_module_info_t *_modinfo = NULL; ssize_t _data_len; char *_data; int compressed; struct stat sb; /* get path of module */ rc = semanage_module_get_path( sh, (const semanage_module_info_t *)modkey, SEMANAGE_MODULE_PATH_NAME, module_path, sizeof(module_path)); if (rc != 0) { goto cleanup; } if (stat(module_path, &sb) != 0) { ERR(sh, "Unable to access %s: %s\n", module_path, strerror(errno)); rc = -1; goto cleanup; } rc = semanage_module_get_module_info(sh, modkey, &_modinfo); if (rc != 0) { goto cleanup; } if (extract_cil || strcmp(_modinfo->lang_ext, "cil") == 0) { file_type = SEMANAGE_MODULE_PATH_CIL; } else { file_type = SEMANAGE_MODULE_PATH_HLL; } /* get path of what to extract */ rc = semanage_module_get_path( sh, _modinfo, file_type, input_file, sizeof(input_file)); if (rc != 0) { goto cleanup; } if (extract_cil == 1 && strcmp(_modinfo->lang_ext, "cil") && stat(input_file, &sb) != 0) { if (errno != ENOENT) { ERR(sh, "Unable to access %s: %s\n", input_file, strerror(errno)); rc = -1; goto cleanup; } rc = semanage_compile_module(sh, _modinfo); if (rc < 0) { goto cleanup; } } _data_len = map_file(sh, input_file, &_data, &compressed); if (_data_len <= 0) { ERR(sh, "Error mapping file: %s", input_file); rc = -1; goto cleanup; } *modinfo = _modinfo; *data_len = (size_t)_data_len; *mapped_data = _data; cleanup: if (rc != 0) { semanage_module_info_destroy(sh, _modinfo); free(_modinfo); } return rc; } /* Removes a module from the sandbox. Returns 0 on success, -1 if out * of memory, -2 if module not found or could not be removed. */ static int semanage_direct_remove(semanage_handle_t * sh, char *module_name) { int status = 0; int ret = 0; semanage_module_key_t modkey; ret = semanage_module_key_init(sh, &modkey); if (ret != 0) { status = -1; goto cleanup; } ret = semanage_module_key_set_priority(sh, &modkey, sh->priority); if (ret != 0) { status = -1; goto cleanup; } ret = semanage_module_key_set_name(sh, &modkey, module_name); if (ret != 0) { status = -1; goto cleanup; } status = semanage_direct_remove_key(sh, &modkey); cleanup: return status; } /* Allocate an array of module_info structures for each readable * module within the store. Note that if the calling program has * already begun a transaction then this function will get a list of * modules within the sandbox. The caller is responsible for calling * semanage_module_info_datum_destroy() on each element of the array * as well as free()ing the entire list. */ static int semanage_direct_list(semanage_handle_t * sh, semanage_module_info_t ** modinfo, int *num_modules) { int i, retval = -1; *modinfo = NULL; *num_modules = 0; /* get the read lock when reading from the active (non-transaction) directory */ if (!sh->is_in_transaction) if (semanage_get_active_lock(sh) < 0) return -1; if (semanage_get_active_modules(sh, modinfo, num_modules) == -1) { goto cleanup; } if (num_modules == 0) { retval = semanage_direct_get_serial(sh); goto cleanup; } retval = semanage_direct_get_serial(sh); cleanup: if (retval < 0) { for (i = 0; i < *num_modules; i++) { semanage_module_info_destroy(sh, &(*modinfo[i])); modinfo[i] = NULL; } free(*modinfo); *modinfo = NULL; } if (!sh->is_in_transaction) { semanage_release_active_lock(sh); } return retval; } static int semanage_direct_get_enabled(semanage_handle_t *sh, const semanage_module_key_t *modkey, int *enabled) { assert(sh); assert(modkey); assert(enabled); int status = 0; int ret = 0; char path[PATH_MAX]; struct stat sb; semanage_module_info_t *modinfo = NULL; /* get module info */ ret = semanage_module_get_module_info( sh, modkey, &modinfo); if (ret != 0) { status = -1; goto cleanup; } /* get disabled file path */ ret = semanage_module_get_path( sh, modinfo, SEMANAGE_MODULE_PATH_DISABLED, path, sizeof(path)); if (ret != 0) { status = -1; goto cleanup; } if (stat(path, &sb) < 0) { if (errno != ENOENT) { ERR(sh, "Unable to access %s: %s\n", path, strerror(errno)); status = -1; goto cleanup; } *enabled = 1; } else { *enabled = 0; } cleanup: semanage_module_info_destroy(sh, modinfo); free(modinfo); return status; } static int semanage_direct_set_enabled(semanage_handle_t *sh, const semanage_module_key_t *modkey, int enabled) { assert(sh); assert(modkey); int status = 0; int ret = 0; char fn[PATH_MAX]; const char *path = NULL; FILE *fp = NULL; semanage_module_info_t *modinfo = NULL; mode_t mask; /* check transaction */ if (!sh->is_in_transaction) { if (semanage_begin_transaction(sh) < 0) { status = -1; goto cleanup; } } /* validate name */ ret = semanage_module_validate_name(modkey->name); if (ret != 0) { errno = 0; ERR(sh, "Name %s is invalid.", modkey->name); status = -1; goto cleanup; } /* validate enabled */ ret = semanage_module_validate_enabled(enabled); if (ret != 0) { errno = 0; ERR(sh, "Enabled status %d is invalid.", enabled); status = -1; goto cleanup; } /* check for disabled path, create if missing */ path = semanage_path(SEMANAGE_TMP, SEMANAGE_MODULES_DISABLED); ret = semanage_mkdir(sh, path); if (ret != 0) { status = -1; goto cleanup; } /* get module info */ ret = semanage_module_get_module_info( sh, modkey, &modinfo); if (ret != 0) { status = -1; goto cleanup; } /* get module disabled file */ ret = semanage_module_get_path( sh, modinfo, SEMANAGE_MODULE_PATH_DISABLED, fn, sizeof(fn)); if (ret != 0) { status = -1; goto cleanup; } switch (enabled) { case 0: /* disable the module */ mask = umask(0077); fp = fopen(fn, "w"); umask(mask); if (fp == NULL) { ERR(sh, "Unable to disable module %s", modkey->name); status = -1; goto cleanup; } if (fclose(fp) != 0) { ERR(sh, "Unable to close disabled file for module %s", modkey->name); status = -1; goto cleanup; } fp = NULL; break; case 1: /* enable the module */ if (unlink(fn) < 0) { if (errno != ENOENT) { ERR(sh, "Unable to enable module %s", modkey->name); status = -1; goto cleanup; } else { /* module already enabled */ errno = 0; } } break; case -1: /* warn about ignored setting to default */ WARN(sh, "Setting module %s to 'default' state has no effect", modkey->name); break; } cleanup: semanage_module_info_destroy(sh, modinfo); free(modinfo); if (fp != NULL) fclose(fp); return status; } int semanage_direct_access_check(semanage_handle_t * sh) { if (semanage_check_init(sh, sh->conf->store_root_path)) return -1; return semanage_store_access_check(); } int semanage_direct_mls_enabled(semanage_handle_t * sh) { sepol_policydb_t *p = NULL; int retval; retval = sepol_policydb_create(&p); if (retval < 0) goto cleanup; retval = semanage_read_policydb(sh, p, SEMANAGE_STORE_KERNEL); if (retval < 0) goto cleanup; retval = sepol_policydb_mls_enabled(p); cleanup: sepol_policydb_free(p); return retval; } static int semanage_direct_get_module_info(semanage_handle_t *sh, const semanage_module_key_t *modkey, semanage_module_info_t **modinfo) { assert(sh); assert(modkey); assert(modinfo); int status = 0; int ret = 0; char fn[PATH_MAX]; FILE *fp = NULL; size_t size = 0; struct stat sb; char *tmp = NULL; int i = 0; semanage_module_info_t *modinfos = NULL; int modinfos_len = 0; semanage_module_info_t *highest = NULL; /* check module name */ ret = semanage_module_validate_name(modkey->name); if (ret < 0) { errno = 0; ERR(sh, "Name %s is invalid.", modkey->name); status = -1; goto cleanup; } /* if priority == 0, then find the highest priority available */ if (modkey->priority == 0) { ret = semanage_direct_list_all(sh, &modinfos, &modinfos_len); if (ret != 0) { status = -1; goto cleanup; } for (i = 0; i < modinfos_len; i++) { ret = strcmp(modinfos[i].name, modkey->name); if (ret == 0) { highest = &modinfos[i]; break; } } if (highest == NULL) { status = -1; goto cleanup; } ret = semanage_module_info_create(sh, modinfo); if (ret != 0) { status = -1; goto cleanup; } ret = semanage_module_info_clone(sh, highest, *modinfo); if (ret != 0) { status = -1; } /* skip to cleanup, module was found */ goto cleanup; } /* check module priority */ ret = semanage_module_validate_priority(modkey->priority); if (ret != 0) { errno = 0; ERR(sh, "Priority %d is invalid.", modkey->priority); status = -1; goto cleanup; } /* copy in key values */ ret = semanage_module_info_create(sh, modinfo); if (ret != 0) { status = -1; goto cleanup; } ret = semanage_module_info_set_priority(sh, *modinfo, modkey->priority); if (ret != 0) { status = -1; goto cleanup; } ret = semanage_module_info_set_name(sh, *modinfo, modkey->name); if (ret != 0) { status = -1; goto cleanup; } /* lookup module ext */ ret = semanage_module_get_path(sh, *modinfo, SEMANAGE_MODULE_PATH_LANG_EXT, fn, sizeof(fn)); if (ret != 0) { status = -1; goto cleanup; } fp = fopen(fn, "r"); if (fp == NULL) { ERR(sh, "Unable to open %s module lang ext file at %s.", (*modinfo)->name, fn); status = -1; goto cleanup; } /* set module ext */ if (getline(&tmp, &size, fp) < 0) { ERR(sh, "Unable to read %s module lang ext file.", (*modinfo)->name); status = -1; goto cleanup; } ret = semanage_module_info_set_lang_ext(sh, *modinfo, tmp); if (ret != 0) { status = -1; goto cleanup; } free(tmp); tmp = NULL; if (fclose(fp) != 0) { ERR(sh, "Unable to close %s module lang ext file.", (*modinfo)->name); status = -1; goto cleanup; } fp = NULL; /* lookup enabled/disabled status */ ret = semanage_module_get_path(sh, *modinfo, SEMANAGE_MODULE_PATH_DISABLED, fn, sizeof(fn)); if (ret != 0) { status = -1; goto cleanup; } /* set enabled/disabled status */ if (stat(fn, &sb) < 0) { if (errno != ENOENT) { ERR(sh, "Unable to access %s: %s\n", fn, strerror(errno)); status = -1; goto cleanup; } ret = semanage_module_info_set_enabled(sh, *modinfo, 1); if (ret != 0) { status = -1; goto cleanup; } } else { ret = semanage_module_info_set_enabled(sh, *modinfo, 0); if (ret != 0) { status = -1; goto cleanup; } } cleanup: free(tmp); if (modinfos != NULL) { for (i = 0; i < modinfos_len; i++) { semanage_module_info_destroy(sh, &modinfos[i]); } free(modinfos); } if (fp != NULL) fclose(fp); return status; } static int semanage_direct_set_module_info(semanage_handle_t *sh, const semanage_module_info_t *modinfo) { int status = 0; int ret = 0; char fn[PATH_MAX]; const char *path = NULL; int enabled = 0; semanage_module_info_t *modinfo_tmp = NULL; semanage_module_key_t modkey; ret = semanage_module_key_init(sh, &modkey); if (ret != 0) { status = -1; goto cleanup; } /* check transaction */ if (!sh->is_in_transaction) { if (semanage_begin_transaction(sh) < 0) { status = -1; goto cleanup; } } /* validate module */ ret = semanage_module_info_validate(modinfo); if (ret != 0) { status = -1; goto cleanup; } sh->modules_modified = 1; /* check for modules path, create if missing */ path = semanage_path(SEMANAGE_TMP, SEMANAGE_MODULES); ret = semanage_mkdir(sh, path); if (ret != 0) { status = -1; goto cleanup; } /* write priority */ ret = semanage_module_get_path(sh, modinfo, SEMANAGE_MODULE_PATH_PRIORITY, fn, sizeof(fn)); if (ret != 0) { status = -1; goto cleanup; } ret = semanage_mkdir(sh, fn); if (ret != 0) { status = -1; goto cleanup; } /* write name */ ret = semanage_module_get_path(sh, modinfo, SEMANAGE_MODULE_PATH_NAME, fn, sizeof(fn)); if (ret != 0) { status = -1; goto cleanup; } ret = semanage_mkdir(sh, fn); if (ret != 0) { status = -1; goto cleanup; } /* write ext */ ret = semanage_direct_write_langext(sh, modinfo->lang_ext, modinfo); if (ret != 0) { status = -1; goto cleanup; } /* write enabled/disabled status */ /* check for disabled path, create if missing */ path = semanage_path(SEMANAGE_TMP, SEMANAGE_MODULES_DISABLED); ret = semanage_mkdir(sh, path); if (ret != 0) { status = -1; goto cleanup; } ret = semanage_module_get_path(sh, modinfo, SEMANAGE_MODULE_PATH_DISABLED, fn, sizeof(fn)); if (ret != 0) { status = -1; goto cleanup; } ret = semanage_module_key_set_name(sh, &modkey, modinfo->name); if (ret != 0) { status = -1; goto cleanup; } if (modinfo->enabled == -1) { /* default to enabled */ enabled = 1; /* check if a module is already installed */ ret = semanage_module_get_module_info(sh, &modkey, &modinfo_tmp); if (ret == 0) { /* set enabled status to current one */ enabled = modinfo_tmp->enabled; } } else { enabled = modinfo->enabled; } ret = semanage_module_set_enabled(sh, &modkey, enabled); if (ret != 0) { status = -1; goto cleanup; } cleanup: semanage_module_key_destroy(sh, &modkey); semanage_module_info_destroy(sh, modinfo_tmp); free(modinfo_tmp); return status; } static int semanage_priorities_filename_select(const struct dirent *d) { if (d->d_name[0] == '.' || strcmp(d->d_name, "disabled") == 0) return 0; return 1; } static int semanage_modules_filename_select(const struct dirent *d) { if (d->d_name[0] == '.') return 0; return 1; } static int semanage_direct_list_all(semanage_handle_t *sh, semanage_module_info_t **modinfos, int *modinfos_len) { assert(sh); assert(modinfos); assert(modinfos_len); int status = 0; int ret = 0; int i = 0; int j = 0; *modinfos = NULL; *modinfos_len = 0; void *tmp = NULL; const char *toplevel = NULL; struct dirent **priorities = NULL; int priorities_len = 0; char priority_path[PATH_MAX]; struct dirent **modules = NULL; int modules_len = 0; uint16_t priority = 0; semanage_module_info_t *modinfo_tmp = NULL; semanage_module_info_t modinfo; ret = semanage_module_info_init(sh, &modinfo); if (ret != 0) { status = -1; goto cleanup; } if (sh->is_in_transaction) { toplevel = semanage_path(SEMANAGE_TMP, SEMANAGE_MODULES); } else { toplevel = semanage_path(SEMANAGE_ACTIVE, SEMANAGE_MODULES); } /* find priorities */ priorities_len = scandir(toplevel, &priorities, semanage_priorities_filename_select, versionsort); if (priorities_len == -1) { ERR(sh, "Error while scanning directory %s.", toplevel); status = -1; goto cleanup; } /* for each priority directory */ /* loop through in reverse so that highest priority is first */ for (i = priorities_len - 1; i >= 0; i--) { /* convert priority string to uint16_t */ ret = semanage_string_to_priority(priorities[i]->d_name, &priority); if (ret != 0) { status = -1; goto cleanup; } /* set our priority */ ret = semanage_module_info_set_priority(sh, &modinfo, priority); if (ret != 0) { status = -1; goto cleanup; } /* get the priority path */ ret = semanage_module_get_path(sh, &modinfo, SEMANAGE_MODULE_PATH_PRIORITY, priority_path, sizeof(priority_path)); if (ret != 0) { status = -1; goto cleanup; } /* cleanup old modules */ if (modules != NULL) { for (j = 0; j < modules_len; j++) { free(modules[j]); modules[j] = NULL; } free(modules); modules = NULL; modules_len = 0; } /* find modules at this priority */ modules_len = scandir(priority_path, &modules, semanage_modules_filename_select, versionsort); if (modules_len == -1) { ERR(sh, "Error while scanning directory %s.", priority_path); status = -1; goto cleanup; } if (modules_len == 0) continue; /* add space for modules */ tmp = realloc(*modinfos, sizeof(semanage_module_info_t) * (*modinfos_len + modules_len)); if (tmp == NULL) { ERR(sh, "Error allocating memory for module array."); status = -1; goto cleanup; } *modinfos = tmp; /* for each module directory */ for(j = 0; j < modules_len; j++) { /* set module name */ ret = semanage_module_info_set_name( sh, &modinfo, modules[j]->d_name); if (ret != 0) { status = -1; goto cleanup; } /* get module values */ ret = semanage_direct_get_module_info( sh, (const semanage_module_key_t *) (&modinfo), &modinfo_tmp); if (ret != 0) { status = -1; goto cleanup; } /* copy into array */ ret = semanage_module_info_init( sh, &((*modinfos)[*modinfos_len])); if (ret != 0) { status = -1; goto cleanup; } ret = semanage_module_info_clone( sh, modinfo_tmp, &((*modinfos)[*modinfos_len])); if (ret != 0) { status = -1; goto cleanup; } semanage_module_info_destroy(sh, modinfo_tmp); free(modinfo_tmp); modinfo_tmp = NULL; *modinfos_len += 1; } } cleanup: semanage_module_info_destroy(sh, &modinfo); if (priorities != NULL) { for (i = 0; i < priorities_len; i++) { free(priorities[i]); } free(priorities); } if (modules != NULL) { for (i = 0; i < modules_len; i++) { free(modules[i]); } free(modules); } semanage_module_info_destroy(sh, modinfo_tmp); free(modinfo_tmp); modinfo_tmp = NULL; if (status != 0) { if (modinfos != NULL) { for (i = 0; i < *modinfos_len; i++) { semanage_module_info_destroy( sh, &(*modinfos)[i]); } free(*modinfos); *modinfos = NULL; *modinfos_len = 0; } } return status; } static int semanage_direct_install_info(semanage_handle_t *sh, const semanage_module_info_t *modinfo, char *data, size_t data_len) { assert(sh); assert(modinfo); assert(data); int status = 0; int ret = 0; int type; struct stat sb; char path[PATH_MAX]; mode_t mask = umask(0077); semanage_module_info_t *higher_info = NULL; semanage_module_key_t higher_key; ret = semanage_module_key_init(sh, &higher_key); if (ret != 0) { status = -1; goto cleanup; } /* validate module info */ ret = semanage_module_info_validate(modinfo); if (ret != 0) { ERR(sh, "%s failed module validation.\n", modinfo->name); status = -2; goto cleanup; } /* Check for higher priority module and warn if there is one as * it will override the module currently being installed. */ ret = semanage_module_key_set_name(sh, &higher_key, modinfo->name); if (ret != 0) { status = -1; goto cleanup; } ret = semanage_direct_get_module_info(sh, &higher_key, &higher_info); if (ret == 0) { if (higher_info->priority > modinfo->priority) { errno = 0; WARN(sh, "A higher priority %s module exists at priority %d and will override the module currently being installed at priority %d.", modinfo->name, higher_info->priority, modinfo->priority); } else if (higher_info->priority < modinfo->priority) { errno = 0; INFO(sh, "Overriding %s module at lower priority %d with module at priority %d.", modinfo->name, higher_info->priority, modinfo->priority); } if (higher_info->enabled == 0 && modinfo->enabled == -1) { errno = 0; WARN(sh, "%s module will be disabled after install as there is a disabled instance of this module present in the system.", modinfo->name); } } /* set module meta data */ ret = semanage_direct_set_module_info(sh, modinfo); if (ret != 0) { status = -2; goto cleanup; } /* install module source file */ if (!strcasecmp(modinfo->lang_ext, "cil")) { type = SEMANAGE_MODULE_PATH_CIL; } else { type = SEMANAGE_MODULE_PATH_HLL; } ret = semanage_module_get_path( sh, modinfo, type, path, sizeof(path)); if (ret != 0) { status = -3; goto cleanup; } ret = bzip(sh, path, data, data_len); if (ret <= 0) { ERR(sh, "Error while writing to %s.", path); status = -3; goto cleanup; } /* if this is an HLL, delete the CIL cache if it exists so it will get recompiled */ if (type == SEMANAGE_MODULE_PATH_HLL) { ret = semanage_module_get_path( sh, modinfo, SEMANAGE_MODULE_PATH_CIL, path, sizeof(path)); if (ret != 0) { status = -3; goto cleanup; } if (stat(path, &sb) == 0) { ret = unlink(path); if (ret != 0) { ERR(sh, "Error while removing cached CIL file %s: %s", path, strerror(errno)); status = -3; goto cleanup; } } } cleanup: semanage_module_key_destroy(sh, &higher_key); semanage_module_info_destroy(sh, higher_info); free(higher_info); umask(mask); return status; } static int semanage_direct_remove_key(semanage_handle_t *sh, const semanage_module_key_t *modkey) { assert(sh); assert(modkey); int status = 0; int ret = 0; char path[PATH_MAX]; semanage_module_info_t *modinfo = NULL; semanage_module_key_t modkey_tmp; ret = semanage_module_key_init(sh, &modkey_tmp); if (ret != 0) { status = -1; goto cleanup; } /* validate module key */ ret = semanage_module_validate_priority(modkey->priority); if (ret != 0) { errno = 0; ERR(sh, "Priority %d is invalid.", modkey->priority); status = -1; goto cleanup; } ret = semanage_module_validate_name(modkey->name); if (ret != 0) { errno = 0; ERR(sh, "Name %s is invalid.", modkey->name); status = -1; goto cleanup; } ret = semanage_module_key_set_name(sh, &modkey_tmp, modkey->name); if (ret != 0) { status = -1; goto cleanup; } /* get module path */ ret = semanage_module_get_path( sh, (const semanage_module_info_t *)modkey, SEMANAGE_MODULE_PATH_NAME, path, sizeof(path)); if (ret != 0) { status = -2; goto cleanup; } /* remove directory */ ret = semanage_remove_directory(path); if (ret != 0) { ERR(sh, "Unable to remove module %s at priority %d.", modkey->name, modkey->priority); status = -2; goto cleanup; } /* check if its the last module at any priority */ ret = semanage_module_get_module_info(sh, &modkey_tmp, &modinfo); if (ret != 0) { /* info that no other module will override */ errno = 0; INFO(sh, "Removing last %s module (no other %s module exists at another priority).", modkey->name, modkey->name); /* remove disabled status file */ ret = semanage_module_get_path( sh, (const semanage_module_info_t *)modkey, SEMANAGE_MODULE_PATH_DISABLED, path, sizeof(path)); if (ret != 0) { status = -1; goto cleanup; } struct stat sb; if (stat(path, &sb) == 0) { ret = unlink(path); if (ret != 0) { status = -1; goto cleanup; } } } else { /* if a lower priority module is going to become active */ if (modkey->priority > modinfo->priority) { /* inform what the new active module will be */ errno = 0; INFO(sh, "%s module at priority %d is now active.", modinfo->name, modinfo->priority); } } cleanup: semanage_module_key_destroy(sh, &modkey_tmp); semanage_module_info_destroy(sh, modinfo); free(modinfo); return status; }
24.73437
177
0.6689
c5644a319738cdc7949e7153adcff760cc2ad328
1,880
w
C
cwebinputs/cweb_hp8.w
ascherer/cwebbin
ec6d18139eb7e6d47f5889df52ff3384751f8794
[ "MIT" ]
26
2016-10-17T13:31:19.000Z
2022-01-05T08:16:09.000Z
cwebinputs/cweb_hp8.w
ascherer/cwebbin
ec6d18139eb7e6d47f5889df52ff3384751f8794
[ "MIT" ]
57
2016-02-23T10:17:51.000Z
2022-02-14T11:09:34.000Z
cwebinputs/cweb_hp8.w
ascherer/cwebbin
ec6d18139eb7e6d47f5889df52ff3384751f8794
[ "MIT" ]
6
2016-05-19T22:23:22.000Z
2021-03-07T21:20:19.000Z
% % CWEB/INCLUDE $VER: CWEB_HP8.W 1.6 (13.01.2019) % % SYNOPSIS: % Transliteration table for umlauts and special characters % according to the Hewlett-Packard Roman 8 codepage. % @@include this file in limbo. % Note that not all equivalents to the TeX macros are present. % % DATE: 28.03.94: Derived from HP8.TEX (V1.0) % % AUTHOR: % Andreas Scherer <https://ascherer.github.io/> % % Please send suggestions (pull requests) and bug reports (issues) % to https://github.com/ascherer/cwebbin % % COPYRIGHT: There is no restriction to the usage of this file. % % CHANGES: % March 25, 1996: New postal address. (V1.2) % August 13, 1998: New e-mail address. (V1.3) % June 11, 2000: Include matching TeX macros. (V1.4) % July 10, 2017: Complete overhaul. (V1.5) % January 13, 2019: Non-generic names. (V1.6) \input cweb_hp8.sty \noatl @q a0 @> @l a1 A @l a2 A @l a3 E @l a4 E @l a5 Ee @l a6 I @l a7 Ie @q a8 @> @q a9 @> @q aa @> @q ab @> @q ac @> @l ad U @l ae U @q af @> @q b0 @> @l b1 Y @l b2 y @q b3 @> @l b4 C @l b5 c @l b6 N @l b7 n @q b8 @> @q b9 @> @q ba @> @q bb @> @q bc @> @q bd @> @q be @> @q bf @> @l c0 a @l c1 e @l c2 o @l c3 u @l c4 a @l c5 e @l c6 o @l c7 u @l c8 a @l c9 e @l ca o @l cb u @l cc ae @l cd ee @l ce oe @l cf ue @l d0 AA @l d1 i @l d2 O @l d3 AE @l d4 aa @l d5 i @l d6 o @l d7 ae @l d8 Ae @l d9 i @l da Oe @l db Ue @l dc E @l dd ie @l de ss @l df O @l e0 A @l e1 A @l e2 a @q e3 @> @q e4 @> @l e5 I @l e6 I @l e7 O @l e8 O @l e9 O @l ea o @q eb @> @q ec @> @l ed U @l ee Ye @l ef ye @q f0 @> @q f1 @> @q f2 @> @l f3 mu @q f4 @> @q f5 @> @q f6 @> @q f7 @> @q f8 @> @q f9 @> @q fa @> @q fb @> @q fc @> @q fd @> @q fe @> @q ff @>
39.166667
66
0.509574
c5dc21a64aadbe1402e092e4bfbc01744870a21e
23,200
c
C
src/libtcod/namegen_c.c
charlieb/libtcod
713817b256f3ec264a488c49ffb46f091a905177
[ "BSD-3-Clause" ]
null
null
null
src/libtcod/namegen_c.c
charlieb/libtcod
713817b256f3ec264a488c49ffb46f091a905177
[ "BSD-3-Clause" ]
null
null
null
src/libtcod/namegen_c.c
charlieb/libtcod
713817b256f3ec264a488c49ffb46f091a905177
[ "BSD-3-Clause" ]
null
null
null
/* BSD 3-Clause License * * Copyright © 2008-2022, Jice and the libtcod contributors. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY 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. */ /* * Mingos' NameGen * This file was written by Dominik "Mingos" Marczuk. */ #include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "namegen.h" #include "parser.h" /* ------------ * * the typedefs * * ------------ */ /* the struct containing a definition of an unprocessed syllable set */ typedef struct { char* name; char* vocals; char* consonants; char* pre; char* start; char* middle; char* end; char* post; char* illegal; char* rules; } namegen_syllables_t; /* and the generator struct */ typedef struct TCOD_NameGen { /* the name that will be called */ char* name; /* needs to use a random number generator */ TCOD_Random* random; /* the lists with all the data */ TCOD_list_t vocals; TCOD_list_t consonants; TCOD_list_t syllables_pre; TCOD_list_t syllables_start; TCOD_list_t syllables_middle; TCOD_list_t syllables_end; TCOD_list_t syllables_post; TCOD_list_t illegal_strings; TCOD_list_t rules; } namegen_t; /* ------------------- * * variables and stuff * * ------------------- */ /* the list containing the generators */ TCOD_list_t namegen_generators_list = NULL; /* the file parser */ TCOD_parser_t namegen_parser; /* parsed files list */ TCOD_list_t parsed_files = NULL; /* the data that will be filled out */ namegen_syllables_t* parser_data = NULL; namegen_t* parser_output = NULL; /* this one's needed to correctly update the generators with RNG pointer */ TCOD_Random* namegen_random; /* the string that will be pointed to upon generating a name */ char* namegen_name = NULL; /* for keeping track of the size of output names */ size_t namegen_name_size; /* ------------------------------------ * * stuff to operate on the syllable set * * ------------------------------------ */ /* initialise a syllable set */ namegen_syllables_t* namegen_syllables_new(void) { namegen_syllables_t* data = calloc(sizeof(namegen_syllables_t), 1); return data; } /* free a syllables set */ void namegen_syllables_delete(namegen_syllables_t* data) { if (data->vocals) free(data->vocals); if (data->consonants) free(data->consonants); if (data->pre) free(data->pre); if (data->start) free(data->start); if (data->middle) free(data->middle); if (data->end) free(data->end); if (data->post) free(data->post); if (data->illegal) free(data->illegal); if (data->rules) free(data->rules); free(data->name); free(data); } /* ---------------------------------- * * stuff to operate on the generators * * ---------------------------------- */ /* create a new generator */ namegen_t* namegen_generator_new(void) { namegen_t* data = malloc(sizeof(namegen_t)); data->name = NULL; /* assign the rng */ data->random = TCOD_random_get_instance(); /* create the lists */ data->vocals = TCOD_list_new(); data->consonants = TCOD_list_new(); data->syllables_pre = TCOD_list_new(); data->syllables_start = TCOD_list_new(); data->syllables_middle = TCOD_list_new(); data->syllables_end = TCOD_list_new(); data->syllables_post = TCOD_list_new(); data->illegal_strings = TCOD_list_new(); data->rules = TCOD_list_new(); return (TCOD_namegen_t)data; } /* check whether a given generator already exists */ bool namegen_generator_check(const char* name) { /* if the list is not created yet, create it */ if (namegen_generators_list == NULL) { namegen_generators_list = TCOD_list_new(); return false; } /* otherwise, scan it for the name */ else { namegen_t** it; for (it = (namegen_t**)TCOD_list_begin(namegen_generators_list); it < (namegen_t**)TCOD_list_end(namegen_generators_list); it++) { if (strcmp((*it)->name, name) == 0) return true; } return false; } } /* retrieve available generator names */ void namegen_get_sets_on_error(void) { namegen_t** it; fprintf(stderr, "Registered syllable sets are:\n"); for (it = (namegen_t**)TCOD_list_begin(namegen_generators_list); it < (namegen_t**)TCOD_list_end(namegen_generators_list); it++) { fprintf(stderr, " * \"%s\"\n", (*it)->name); } } /* get the appropriate syllables set */ namegen_t* namegen_generator_get(const char* name) { if (namegen_generator_check(name) == true) { namegen_t** it; for (it = (namegen_t**)TCOD_list_begin(namegen_generators_list); it != (namegen_t**)TCOD_list_end(namegen_generators_list); it++) { if (strcmp((*it)->name, name) == 0) return (*it); } } /* and if there's no such set... */ else fprintf(stderr, "Generator \"%s\" could not be retrieved.\n", name); return NULL; } /* destroy a generator */ void namegen_generator_delete(namegen_t* generator) { namegen_t* data = generator; free(data->name); data->random = NULL; TCOD_list_clear_and_delete(data->vocals); TCOD_list_clear_and_delete(data->consonants); TCOD_list_clear_and_delete(data->syllables_pre); TCOD_list_clear_and_delete(data->syllables_start); TCOD_list_clear_and_delete(data->syllables_middle); TCOD_list_clear_and_delete(data->syllables_end); TCOD_list_clear_and_delete(data->syllables_post); TCOD_list_clear_and_delete(data->illegal_strings); TCOD_list_clear_and_delete(data->rules); free(data); } /* ------------------------------ * * Populating namegen_t with data * * ------------------------------ */ /* fill the pointed list with syllable data by extracting tokens */ void namegen_populate_list(const char* source, TCOD_list_t list, bool wildcards) { const size_t source_length = strlen(source); const size_t token_length = source_length + 1; char* token = calloc(token_length, 1); // tokens will typically be many and very short, but let's be cautious. What // if the entire string is a single token? size_t i = 0; do { /* do the tokenizing using an iterator imitation :) */ const char* it = source + i; /* append a normal character */ if ((*it >= 'a' && *it <= 'z') || (*it >= 'A' && *it <= 'Z') || *it == '\'' || *it == '-') strncat(token, it, 1); /* special character */ else if (*it == '/') { if (wildcards == true) strncat(token, it++, 2); else strncat(token, ++it, 1); i++; } /* underscore is converted to space */ else if (*it == '_') { if (wildcards == true) strncat(token, it, 1); else strcat(token, " "); } /* add wildcards if they are allowed */ else if (wildcards == true && (*it == '$' || *it == '%' || (*it >= '0' && *it <= '9'))) strncat(token, it, 1); /* all other characters are treated as separators and cause adding the current token to the list */ else if (strlen(token) > 0) { TCOD_list_push(list, TCOD_strdup(token)); memset(token, '\0', token_length); } } while (++i <= source_length); free(token); } /* populate all lists of a namegen_t struct */ void namegen_populate(namegen_t* dst, const namegen_syllables_t* src) { if (dst == NULL || src == NULL) { fprintf(stderr, "Couldn't populate the name generator with data.\n"); exit(1); } if (src->vocals != NULL) namegen_populate_list(src->vocals, dst->vocals, false); if (src->consonants != NULL) namegen_populate_list(src->consonants, dst->consonants, false); if (src->pre != NULL) namegen_populate_list(src->pre, dst->syllables_pre, false); if (src->start != NULL) namegen_populate_list(src->start, dst->syllables_start, false); if (src->middle != NULL) namegen_populate_list(src->middle, dst->syllables_middle, false); if (src->end != NULL) namegen_populate_list(src->end, dst->syllables_end, false); if (src->post != NULL) namegen_populate_list(src->post, dst->syllables_post, false); if (src->illegal != NULL) namegen_populate_list(src->illegal, dst->illegal_strings, false); if (src->rules != NULL) namegen_populate_list(src->rules, dst->rules, true); dst->name = TCOD_strdup(src->name); } /* -------------------- * * parser-related stuff * * -------------------- */ /* preparing the parser */ void namegen_parser_prepare(void) { static bool namegen_parser_ready = false; if (namegen_parser_ready == true) return; else { TCOD_parser_struct_t parser_name; namegen_parser = TCOD_parser_new(); parser_name = TCOD_parser_new_struct(namegen_parser, "name"); TCOD_struct_add_property(parser_name, "phonemesVocals", TCOD_TYPE_STRING, false); TCOD_struct_add_property(parser_name, "phonemesConsonants", TCOD_TYPE_STRING, false); TCOD_struct_add_property(parser_name, "syllablesPre", TCOD_TYPE_STRING, false); TCOD_struct_add_property(parser_name, "syllablesStart", TCOD_TYPE_STRING, false); TCOD_struct_add_property(parser_name, "syllablesMiddle", TCOD_TYPE_STRING, false); TCOD_struct_add_property(parser_name, "syllablesEnd", TCOD_TYPE_STRING, false); TCOD_struct_add_property(parser_name, "syllablesPost", TCOD_TYPE_STRING, false); TCOD_struct_add_property(parser_name, "illegal", TCOD_TYPE_STRING, false); TCOD_struct_add_property(parser_name, "rules", TCOD_TYPE_STRING, true); namegen_parser_ready = true; } } /* parser listener */ bool namegen_parser_new_struct(TCOD_parser_struct_t str, const char* name) { (void)str; (void)name; // Ignored parameters. parser_data = namegen_syllables_new(); return true; } bool namegen_parser_flag(const char* name) { (void)name; // Ignored parameter. return true; } bool namegen_parser_property(const char* name, TCOD_value_type_t type, TCOD_value_t value) { (void)type; // Ignored parameter. if (strcmp(name, "syllablesStart") == 0) parser_data->start = TCOD_strdup(value.s); else if (strcmp(name, "syllablesMiddle") == 0) parser_data->middle = TCOD_strdup(value.s); else if (strcmp(name, "syllablesEnd") == 0) parser_data->end = TCOD_strdup(value.s); else if (strcmp(name, "syllablesPre") == 0) parser_data->pre = TCOD_strdup(value.s); else if (strcmp(name, "syllablesPost") == 0) parser_data->post = TCOD_strdup(value.s); else if (strcmp(name, "phonemesVocals") == 0) parser_data->vocals = TCOD_strdup(value.s); else if (strcmp(name, "phonemesConsonants") == 0) parser_data->consonants = TCOD_strdup(value.s); else if (strcmp(name, "rules") == 0) parser_data->rules = TCOD_strdup(value.s); else if (strcmp(name, "illegal") == 0) { /* illegal strings are converted to lowercase */ char* str; int i; parser_data->illegal = TCOD_strdup(value.s); str = parser_data->illegal; for (i = 0; i < (int)strlen(str); i++) str[i] = (char)(tolower(str[i])); } else return false; return true; } bool namegen_parser_end_struct(TCOD_parser_struct_t str, const char* name) { (void)str; // Ignored parameter. /* if there's no syllable set by this name, add it to the list */ if (namegen_generator_check(name) == false) { parser_data->name = TCOD_strdup(name); parser_output = namegen_generator_new(); namegen_populate(parser_output, parser_data); parser_output->random = namegen_random; if (namegen_generators_list == NULL) namegen_generators_list = TCOD_list_new(); TCOD_list_push(namegen_generators_list, (const void*)parser_output); } /* free the allocated memory to prevent a memory leak */ namegen_syllables_delete(parser_data); return true; } void namegen_parser_error(const char* msg) { fprintf(stderr, "%s\n", msg); exit(1); } TCOD_parser_listener_t namegen_listener = { namegen_parser_new_struct, namegen_parser_flag, namegen_parser_property, namegen_parser_end_struct, namegen_parser_error}; /* run the parser */ void namegen_parser_run(const char* filename) { char** it; /* prepare the parser --- this will be executed only once */ namegen_parser_prepare(); if (parsed_files == NULL) parsed_files = TCOD_list_new(); if (TCOD_list_size(parsed_files) > 0) { for (it = (char**)TCOD_list_begin(parsed_files); it != (char**)TCOD_list_end(parsed_files); it++) if (strcmp(*it, filename) == 0) return; } /* if the file hasn't been parsed yet, add its name to the list so that it's never parsed twice */ TCOD_list_push(parsed_files, (const void*)TCOD_strdup(filename)); /* run the parser */ TCOD_parser_run(namegen_parser, filename, &namegen_listener); } /* --------------- * * rubbish pruning * * --------------- */ /* search for occurrences of triple characters (case-insensitive) */ bool namegen_word_has_triples(const char* str) { const char* it = str; char c = (char)(tolower(*it)); int cnt = 1; bool has_triples = false; it++; while (*it != '\0') { if ((char)(tolower(*it)) == c) cnt++; else { cnt = 1; c = (char)(tolower(*it)); } if (cnt >= 3) has_triples = true; it++; } return has_triples; } /* search for occurrences of illegal strings */ bool namegen_word_has_illegal(const namegen_t* data, const char* str) { /* convert word to lowercase */ char* haystack = TCOD_strdup(str); int i; for (i = 0; i < (int)strlen(haystack); i++) haystack[i] = (char)(tolower(haystack[i])); /* look for illegal strings */ if (TCOD_list_size(data->illegal_strings) > 0) { char** it; for (it = (char**)TCOD_list_begin(data->illegal_strings); it != (char**)TCOD_list_end(data->illegal_strings); it++) { if (strstr(haystack, *it) != NULL) { free(haystack); return true; } } } free(haystack); return false; } /* removes double spaces, as well as leading and ending spaces */ void namegen_word_prune_spaces(char* str) { char* s; char* data = str; /* remove leading spaces */ while (data[0] == ' ') memmove(data, data + 1, strlen(data)); /* reduce double spaces to single spaces */ while ((s = strstr(data, " ")) != NULL) memmove(s, s + 1, strlen(s)); /* remove the final space */ while (data[strlen(data) - 1] == ' ') data[strlen(data) - 1] = '\0'; } /* prune repeated "syllables", such as Arnarn */ bool namegen_word_prune_syllables(char* str) { char* data = TCOD_strdup(str); int len = (int)strlen(data); char check[8]; /* change to lowercase */ for (int i = 0; i < len; i++) data[i] = (char)(tolower(data[i])); /* start pruning */ /* 2-character direct repetitions */ for (int i = 0; i < len - 4; i++) { memset(check, '\0', 8); strncpy(check, data + i, 2); strncat(check, data + i, 2); if (strstr(data, check) != NULL) { free(data); return true; } } /* 3-character repetitions (anywhere in the word) - prunes everything, even 10-char repetitions */ for (int i = 0; i < len - 6; i++) { memset(check, '\0', 8); strncpy(check, data + i, 3); if (strstr(data + i + 3, check) != NULL) { free(data); return true; } } free(data); return false; } /* everything stacked together */ bool namegen_word_is_ok(const namegen_t* data, char* str) { namegen_word_prune_spaces(str); return (strlen(str) > 0) & (!namegen_word_has_triples(str)) & (!namegen_word_has_illegal(data, str)) & (!namegen_word_prune_syllables(str)); } /* ---------------------------- * * publicly available functions * * ---------------------------- */ /* parse a new syllable sets file - allocates a new data structure and fills it with necessary content */ void TCOD_namegen_parse(const char* filename, TCOD_Random* random) { /* check for file existence */ FILE* in = fopen(filename, "r"); if (in == NULL) { fprintf(stderr, "File \"%s\" not found!\n", filename); return; } fclose(in); /* set namegen RNG */ namegen_random = random; /* run the proper parser - add the file's contents to the data structures */ namegen_parser_run(filename); } /* generate a name using a given generation rule */ char* TCOD_namegen_generate_custom(const char* name, const char* rule, bool allocate) { namegen_t* data; size_t buflen = 1024; if (namegen_generator_check(name)) data = namegen_generator_get(name); else { fprintf(stderr, "The name \"%s\" has not been found.\n", name); namegen_get_sets_on_error(); return NULL; } char* buf = malloc(buflen); const size_t rule_len = strlen(rule); /* let the show begin! */ do { const char* it = rule; memset(buf, '\0', buflen); while (it <= rule + rule_len) { /* make sure the buffer is large enough */ if (strlen(buf) >= buflen) { char* tmp; while (strlen(buf) >= buflen) buflen *= 2; tmp = malloc(buflen); strcpy(tmp, buf); free(buf); buf = tmp; } /* append a normal character */ if ((*it >= 'a' && *it <= 'z') || (*it >= 'A' && *it <= 'Z') || *it == '\'' || *it == '-') strncat(buf, it, 1); /* special character */ else if (*it == '/') { it++; strncat(buf, it, 1); } /* underscore is converted to space */ else if (*it == '_') strcat(buf, " "); /* interpret a wildcard */ else if (*it == '$') { int chance = 100; it++; /* food for the randomizer */ if (*it >= '0' && *it <= '9') { chance = 0; while (*it >= '0' && *it <= '9') { chance *= 10; chance += (int)(*it) - (int)('0'); it++; } } /* ok, so the chance of wildcard occurrence is calculated, now evaluate it */ if (chance >= TCOD_random_get_int(data->random, 0, 100)) { TCOD_list_t lst; switch (*it) { case 'P': lst = data->syllables_pre; break; case 's': lst = data->syllables_start; break; case 'm': lst = data->syllables_middle; break; case 'e': lst = data->syllables_end; break; case 'p': lst = data->syllables_post; break; case 'v': lst = data->vocals; break; case 'c': lst = data->consonants; break; case '?': lst = (TCOD_random_get_int(data->random, 0, 1) == 0 ? data->vocals : data->consonants); break; default: fprintf(stderr, "Wrong rules syntax encountered!\n"); exit(1); break; } if (TCOD_list_size(lst) == 0) fprintf( stderr, "No data found in the requested string (wildcard *%c). Check your name generation rule %s.\n", *it, rule); else strcat(buf, (char*)TCOD_list_get(lst, TCOD_random_get_int(data->random, 0, TCOD_list_size(lst) - 1))); } } it++; } } while (!namegen_word_is_ok(data, buf)); /* prune the spare spaces out */ namegen_word_prune_spaces(buf); /* return the name accordingly */ if (allocate == true) return buf; else { /* take care of ensuring the recipient is sized properly */ if (namegen_name == NULL) { namegen_name_size = 64; namegen_name = malloc(namegen_name_size); } while (strlen(buf) > namegen_name_size - 1) { namegen_name_size *= 2; free(namegen_name); namegen_name = malloc(namegen_name_size); } strcpy(namegen_name, buf); free(buf); return namegen_name; } } /* generate a name with one of the rules from the file */ char* TCOD_namegen_generate(const char* name, bool allocate) { namegen_t* data; if (namegen_generator_check(name)) data = namegen_generator_get(name); else { fprintf(stderr, "The name \"%s\" has not been found.\n", name); namegen_get_sets_on_error(); return NULL; } /* check if the rules list is present */ if (TCOD_list_size(data->rules) == 0) { fprintf(stderr, "The rules list is empty!\n"); exit(1); } /* choose the rule */ int chance; const char* rule_rolled; int truncation; do { int rule_number = TCOD_random_get_int(data->random, 0, TCOD_list_size(data->rules) - 1); rule_rolled = (char*)TCOD_list_get(data->rules, rule_number); chance = 100; truncation = 0; if (rule_rolled[0] == '%') { truncation = 1; chance = 0; while (rule_rolled[truncation] >= '0' && rule_rolled[truncation] <= '9') { chance *= 10; chance += (int)(rule_rolled[truncation]) - (int)('0'); truncation++; } } } while (TCOD_random_get_int(data->random, 0, 100) > chance); /* OK, we've got ourselves a new rule! */ const char* rule_parsed = rule_rolled + truncation; return TCOD_namegen_generate_custom(name, rule_parsed, allocate); } /* retrieve the list of all available syllable set names */ TCOD_list_t TCOD_namegen_get_sets(void) { TCOD_list_t l = TCOD_list_new(); if (namegen_generators_list != NULL) { namegen_t** it; for (it = (namegen_t**)TCOD_list_begin(namegen_generators_list); it < (namegen_t**)TCOD_list_end(namegen_generators_list); it++) { TCOD_list_push(l, (const void*)((*it)->name)); } } return l; } /* delete all the generators */ void TCOD_namegen_destroy(void) { /* delete all generators */ namegen_t** it; for (it = (namegen_t**)TCOD_list_begin(namegen_generators_list); it < (namegen_t**)TCOD_list_end(namegen_generators_list); it++) namegen_generator_delete(*it); /* clear the generators list */ TCOD_list_clear(namegen_generators_list); /* get rid of the parsed files list */ TCOD_list_clear_and_delete(parsed_files); }
33.918129
118
0.637069
d0b2683c0302dcce5710e450ec1c538e6a9e919c
8,222
c
C
hmac.c
jb55/lnsocket
8b4abb12a05c0cd2dcc2926deee22841ee2ef9d2
[ "MIT" ]
5
2022-01-19T11:04:32.000Z
2022-03-24T15:50:35.000Z
hmac.c
jb55/lnsocket
8b4abb12a05c0cd2dcc2926deee22841ee2ef9d2
[ "MIT" ]
3
2022-03-16T19:45:11.000Z
2022-03-25T09:15:41.000Z
hmac.c
jb55/lnsocket
8b4abb12a05c0cd2dcc2926deee22841ee2ef9d2
[ "MIT" ]
1
2022-03-24T15:50:41.000Z
2022-03-24T15:50:41.000Z
/* Copyright Rusty Russell (Blockstream) 2015. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <string.h> #include "hmac.h" #define IPAD 0x3636363636363636ULL #define OPAD 0x5C5C5C5C5C5C5C5CULL #define BLOCK_256_U64S (HMAC_SHA256_BLOCKSIZE / sizeof(uint64_t)) #define BLOCK_512_U64S (HMAC_SHA512_BLOCKSIZE / sizeof(uint64_t)) static inline void xor_block_256(uint64_t block[BLOCK_256_U64S], uint64_t pad) { size_t i; for (i = 0; i < BLOCK_256_U64S; i++) block[i] ^= pad; } static inline void xor_block_512(uint64_t block[BLOCK_512_U64S], uint64_t pad) { size_t i; for (i = 0; i < BLOCK_512_U64S; i++) block[i] ^= pad; } void hmac_sha256_init(struct hmac_sha256_ctx *ctx, const void *k, size_t ksize) { struct sha256 hashed_key; /* We use k_opad as k_ipad temporarily. */ uint64_t *k_ipad = ctx->k_opad; /* (keys longer than B bytes are first hashed using H) */ if (ksize > HMAC_SHA256_BLOCKSIZE) { sha256(&hashed_key, k, ksize); k = &hashed_key; ksize = sizeof(hashed_key); } /* From RFC2104: * * (1) append zeros to the end of K to create a B byte string * (e.g., if K is of length 20 bytes and B=64, then K will be * appended with 44 zero bytes 0x00) */ memcpy(k_ipad, k, ksize); memset((char *)k_ipad + ksize, 0, HMAC_SHA256_BLOCKSIZE - ksize); /* * (2) XOR (bitwise exclusive-OR) the B byte string computed * in step (1) with ipad */ xor_block_256(k_ipad, IPAD); /* * We start (4) here, appending text later: * * (3) append the stream of data 'text' to the B byte string resulting * from step (2) * (4) apply H to the stream generated in step (3) */ sha256_init(&ctx->sha); sha256_update(&ctx->sha, k_ipad, HMAC_SHA256_BLOCKSIZE); /* * (5) XOR (bitwise exclusive-OR) the B byte string computed in * step (1) with opad */ xor_block_256(ctx->k_opad, IPAD^OPAD); } void hmac_sha512_init(struct hmac_sha512_ctx *ctx, const void *k, size_t ksize) { struct sha512 hashed_key; /* We use k_opad as k_ipad temporarily. */ uint64_t *k_ipad = ctx->k_opad; /* (keys longer than B bytes are first hashed using H) */ if (ksize > HMAC_SHA512_BLOCKSIZE) { sha512(&hashed_key, k, ksize); k = &hashed_key; ksize = sizeof(hashed_key); } /* From RFC2104: * * (1) append zeros to the end of K to create a B byte string * (e.g., if K is of length 20 bytes and B=64, then K will be * appended with 44 zero bytes 0x00) */ memcpy(k_ipad, k, ksize); memset((char *)k_ipad + ksize, 0, HMAC_SHA512_BLOCKSIZE - ksize); /* * (2) XOR (bitwise exclusive-OR) the B byte string computed * in step (1) with ipad */ xor_block_512(k_ipad, IPAD); /* * We start (4) here, appending text later: * * (3) append the stream of data 'text' to the B byte string resulting * from step (2) * (4) apply H to the stream generated in step (3) */ sha512_init(&ctx->sha); sha512_update(&ctx->sha, k_ipad, HMAC_SHA512_BLOCKSIZE); /* * (5) XOR (bitwise exclusive-OR) the B byte string computed in * step (1) with opad */ xor_block_512(ctx->k_opad, IPAD^OPAD); } void hmac_sha256_update(struct hmac_sha256_ctx *ctx, const void *p, size_t size) { /* This is the appending-text part of this: * * (3) append the stream of data 'text' to the B byte string resulting * from step (2) * (4) apply H to the stream generated in step (3) */ sha256_update(&ctx->sha, p, size); } void hmac_sha512_update(struct hmac_sha512_ctx *ctx, const void *p, size_t size) { sha512_update(&ctx->sha, p, size); } void hmac_sha256_done(struct hmac_sha256_ctx *ctx, struct hmac_sha256 *hmac) { /* (4) apply H to the stream generated in step (3) */ sha256_done(&ctx->sha, &hmac->sha); /* * (6) append the H result from step (4) to the B byte string * resulting from step (5) * (7) apply H to the stream generated in step (6) and output * the result */ sha256_init(&ctx->sha); sha256_update(&ctx->sha, ctx->k_opad, sizeof(ctx->k_opad)); sha256_update(&ctx->sha, &hmac->sha, sizeof(hmac->sha)); sha256_done(&ctx->sha, &hmac->sha); } void hmac_sha512_done(struct hmac_sha512_ctx *ctx, struct hmac_sha512 *hmac) { /* (4) apply H to the stream generated in step (3) */ sha512_done(&ctx->sha, &hmac->sha); /* * (6) append the H result from step (4) to the B byte string * resulting from step (5) * (7) apply H to the stream generated in step (6) and output * the result */ sha512_init(&ctx->sha); sha512_update(&ctx->sha, ctx->k_opad, sizeof(ctx->k_opad)); sha512_update(&ctx->sha, &hmac->sha, sizeof(hmac->sha)); sha512_done(&ctx->sha, &hmac->sha); } #if 1 void hmac_sha256(struct hmac_sha256 *hmac, const void *k, size_t ksize, const void *d, size_t dsize) { struct hmac_sha256_ctx ctx; hmac_sha256_init(&ctx, k, ksize); hmac_sha256_update(&ctx, d, dsize); hmac_sha256_done(&ctx, hmac); } void hmac_sha512(struct hmac_sha512 *hmac, const void *k, size_t ksize, const void *d, size_t dsize) { struct hmac_sha512_ctx ctx; hmac_sha512_init(&ctx, k, ksize); hmac_sha512_update(&ctx, d, dsize); hmac_sha512_done(&ctx, hmac); } #else /* Direct mapping from MD5 example in RFC2104 */ void hmac_sha256(struct hmac_sha256 *hmac, const void *key, size_t key_len, const void *text, size_t text_len) { struct sha256_ctx context; unsigned char k_ipad[65]; /* inner padding - * key XORd with ipad */ unsigned char k_opad[65]; /* outer padding - * key XORd with opad *//* start out by storing key in pads */ unsigned char tk[32]; int i; /* if key is longer than 64 bytes reset it to key=MD5(key) */ if (key_len > 64) { struct sha256_ctx tctx; sha256_init(&tctx); sha256_update(&tctx, key, key_len); sha256_done(&tctx, tk); key = tk; key_len = 32; } bzero( k_ipad, sizeof k_ipad); bzero( k_opad, sizeof k_opad); bcopy( key, k_ipad, key_len); bcopy( key, k_opad, key_len); /* XOR key with ipad and opad values */ for (i=0; i<64; i++) { k_ipad[i] ^= 0x36; k_opad[i] ^= 0x5c; } /* * perform inner MD5 */ sha256_init(&context); /* init context for 1st * pass */ sha256_update(&context, k_ipad, 64); /* start with inner pad */ sha256_update(&context, text, text_len); /* then text of datagram */ sha256_done(&context, &hmac->sha); /* finish up 1st pass */ /* * perform outer MD5 */ sha256_init(&context); /* init context for 2nd * pass */ sha256_update(&context, k_opad, 64); /* start with outer pad */ sha256_update(&context, &hmac->sha, 32); /* then results of 1st * hash */ sha256_done(&context, &hmac->sha); /* finish up 2nd pass */ } #endif
29.469534
80
0.635369
a986ceb6fd0d13b432be3003f57b85a456e2af55
2,416
h
C
linux-3.16/fs/nfsd/acl.h
jj1232727/system_call
145315cdf532c45b6aa753d98260d2b1c0b63abc
[ "Unlicense" ]
null
null
null
linux-3.16/fs/nfsd/acl.h
jj1232727/system_call
145315cdf532c45b6aa753d98260d2b1c0b63abc
[ "Unlicense" ]
null
null
null
linux-3.16/fs/nfsd/acl.h
jj1232727/system_call
145315cdf532c45b6aa753d98260d2b1c0b63abc
[ "Unlicense" ]
null
null
null
/* * Common NFSv4 ACL handling definitions. * * Copyright (c) 2002 The Regents of the University of Michigan. * All rights reserved. * * Marius Aamodt Eriksen <marius@umich.edu> * * 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 University 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 ``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 REGENTS 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. */ #ifndef LINUX_NFS4_ACL_H #define LINUX_NFS4_ACL_H struct nfs4_acl; struct svc_fh; struct svc_rqst; /* * Maximum ACL we'll accept from a client; chosen (somewhat * arbitrarily) so that kmalloc'ing the ACL shouldn't require a * high-order allocation. This allows 204 ACEs on x86_64: */ #define NFS4_ACL_MAX ((PAGE_SIZE - sizeof(struct nfs4_acl)) \ / sizeof(struct nfs4_ace)) struct nfs4_acl *nfs4_acl_new(int); int nfs4_acl_get_whotype(char *, u32); __be32 nfs4_acl_write_who(struct xdr_stream *xdr, int who); int nfsd4_get_nfs4_acl(struct svc_rqst *rqstp, struct dentry *dentry, struct nfs4_acl **acl); __be32 nfsd4_set_nfs4_acl(struct svc_rqst *rqstp, struct svc_fh *fhp, struct nfs4_acl *acl); #endif /* LINUX_NFS4_ACL_H */
40.266667
75
0.753725
65562370d15847ff999e5ab7d272fefb961d03c4
537
h
C
src/cgroup.h
Leo1003/cjail
8c6f5fa6082514200a8e25258bd37c2d949d5b7f
[ "MIT" ]
7
2018-02-17T05:03:42.000Z
2021-01-11T03:45:13.000Z
src/cgroup.h
Leo1003/cjail
8c6f5fa6082514200a8e25258bd37c2d949d5b7f
[ "MIT" ]
1
2018-12-16T06:55:53.000Z
2018-12-26T06:44:28.000Z
src/cgroup.h
Leo1003/cjail
8c6f5fa6082514200a8e25258bd37c2d949d5b7f
[ "MIT" ]
2
2018-04-10T13:32:45.000Z
2019-09-08T10:03:24.000Z
/** * @internal * @file cgroup.h * @brief cgroup system operation header */ #ifndef CGROUP_H #define CGROUP_H int cgroup_set_root(const char *path); int cgroup_create(const char *subsystem); int cgroup_read(const char *subsystem, const char *name, const char *fmt, ...) __attribute__((format(scanf, 3, 4))); int cgroup_write(const char *subsystem, const char *name, const char *fmt, ...) __attribute__((format(printf, 3, 4))); int cgroup_open_tasks(const char *subsystem); int cgroup_destory(const char *subsystem); #endif
28.263158
79
0.726257
a9e7387a7edae49292fc71a2f0470a30e4fa9a55
738
h
C
components/sys/bloop/loopapps/loopalarm/include/cronalarms.h
tchebb/bl_iot_sdk
91986049345c9bce2f3fd03fc1200f41ca357323
[ "Apache-2.0" ]
121
2020-10-28T00:44:17.000Z
2022-03-31T23:13:23.000Z
components/sys/bloop/loopapps/loopalarm/include/cronalarms.h
tchebb/bl_iot_sdk
91986049345c9bce2f3fd03fc1200f41ca357323
[ "Apache-2.0" ]
75
2020-10-28T00:44:55.000Z
2022-03-05T20:21:53.000Z
components/sys/bloop/loopapps/loopalarm/include/cronalarms.h
tchebb/bl_iot_sdk
91986049345c9bce2f3fd03fc1200f41ca357323
[ "Apache-2.0" ]
79
2020-10-28T00:16:23.000Z
2021-09-28T19:22:24.000Z
#ifndef __CRONALARMS_H__ #define __CRONALARMS_H__ #include "ccronexpr.h" /** * @brief create cron alarm * @param[in] cronstring: cron alarm command string. handler: callback. * @param oneshot: if only run once, oneshot is 1, else, oneshot is 0 * * @return * - 0: success * - -1: failed * * */ int cron_alarm_create(const char * cronstring, void *handler, int oneshot); /** * @brief cron alarm process. * * */ void cron_alarm_service(void); /** * @brief cron alarm init * * */ void cronalarminit(void); /** * @brief for demo.c test use. change time to check whether cron alarm run ok. * @param test_time: add seconds * * @return * - seconds * * */ uint32_t cronal_time(uint32_t test_time); #endif
18
79
0.659892
30b88b30e3dcd55cf0e994602c61b33ad06ebecb
1,088
c
C
s2e/klee/runtime/klee-libc/calloc.c
wyz7155/SymDrive
055f3ab1601d6350b397eddc9f3982271d9186d2
[ "MIT" ]
null
null
null
s2e/klee/runtime/klee-libc/calloc.c
wyz7155/SymDrive
055f3ab1601d6350b397eddc9f3982271d9186d2
[ "MIT" ]
null
null
null
s2e/klee/runtime/klee-libc/calloc.c
wyz7155/SymDrive
055f3ab1601d6350b397eddc9f3982271d9186d2
[ "MIT" ]
null
null
null
//===-- calloc.c ----------------------------------------------------------===// // // The KLEE Symbolic Virtual Machine // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include <stdlib.h> #include <string.h> // DWD - I prefer to be internal #if 0 void *calloc(size_t nmemb, size_t size) { unsigned nbytes = nmemb * size; void *addr = malloc(nbytes); if(addr) memset(addr, 0, nbytes); return addr; } // Always reallocate. void *realloc(void *ptr, size_t nbytes) { if(!ptr) return malloc(nbytes); if(!nbytes) { free(ptr); return 0; } unsigned copy_nbytes = klee_get_obj_size(ptr); //printf("REALLOC: current object = %d bytes!\n", copy_nbytes); void *addr = malloc(nbytes); if(addr) { // shrinking if(copy_nbytes > nbytes) copy_nbytes = nbytes; //printf("REALLOC: copying = %d bytes!\n", copy_nbytes); memcpy(addr, ptr, copy_nbytes); free(ptr); } return addr; } #endif
23.148936
80
0.564338
80228e582abcb1a9da8b1b1b31015f64d7e62fe9
1,147
c
C
DisplayCamera.c
methusael13/opencv-examples
435d9d6502777ab41c32f73f21a221d500a830a2
[ "MIT" ]
null
null
null
DisplayCamera.c
methusael13/opencv-examples
435d9d6502777ab41c32f73f21a221d500a830a2
[ "MIT" ]
null
null
null
DisplayCamera.c
methusael13/opencv-examples
435d9d6502777ab41c32f73f21a221d500a830a2
[ "MIT" ]
null
null
null
#include <cv.h> #include <time.h> #include <stdio.h> #include <assert.h> #include <highgui.h> #define DISP_DELAY 33 #define MAX_COUNTER 1000 #define WINDOW_ID "DisplayCamera" int main(int argc, char *argv[]) { time_t start_t, end_t; IplImage *frame = NULL; CvCapture *capture = NULL; double fps; int counter = 0; if (argc == 1) capture = cvCreateCameraCapture(-1); else capture = cvCreateFileCapture(argv[1]); assert(capture != NULL); cvNamedWindow(WINDOW_ID, CV_WINDOW_AUTOSIZE); time(&start_t); while (1) { frame = cvQueryFrame(capture); if (!frame) break; counter++; time(&end_t); fps = counter / difftime(end_t, start_t); cvShowImage(WINDOW_ID, frame); if (counter > 30) printf("\x1b[1;1H\x1b[J\nFPS: %.2F\n", fps); if (counter > MAX_COUNTER) { counter = 0; time(&start_t); } if ((cvWaitKey(DISP_DELAY) & 255) == 27) break; } printf("\n"); cvReleaseCapture(&capture); cvDestroyWindow(WINDOW_ID); return 0; }
21.240741
56
0.564952
43775c5ce17c535c3f2addb89ec5464be18a7a8b
25,775
c
C
drivers/acpi/acpica/psopcode.c
fergy/aplit_linux-5
a6ef4cb0e17e1eec9743c064e65f730c49765711
[ "MIT" ]
27
2021-10-04T18:56:52.000Z
2022-03-28T08:23:06.000Z
drivers/acpi/acpica/psopcode.c
fergy/aplit_linux-5
a6ef4cb0e17e1eec9743c064e65f730c49765711
[ "MIT" ]
1
2022-01-12T04:05:36.000Z
2022-01-16T15:48:42.000Z
drivers/acpi/acpica/psopcode.c
fergy/aplit_linux-5
a6ef4cb0e17e1eec9743c064e65f730c49765711
[ "MIT" ]
6
2021-11-02T10:56:19.000Z
2022-03-06T11:58:20.000Z
// SPDX-License-Identifier: BSD-3-Clause OR GPL-2.0 /****************************************************************************** * * Module Name: psopcode - Parser/Interpreter opcode information table * * Copyright (C) 2000 - 2019, Intel Corp. * *****************************************************************************/ #include <acpi/acpi.h> #include "accommon.h" #include "acopcode.h" #include "amlcode.h" #define _COMPONENT ACPI_PARSER ACPI_MODULE_NAME("psopcode") /******************************************************************************* * * NAME: acpi_gbl_aml_op_info * * DESCRIPTION: Opcode table. Each entry contains <opcode, type, name, operands> * The name is a simple ascii string, the operand specifier is an * ascii string with one letter per operand. The letter specifies * the operand type. * ******************************************************************************/ /* * Summary of opcode types/flags * Opcodes that have associated namespace objects (AML_NSOBJECT flag) AML_SCOPE_OP AML_DEVICE_OP AML_THERMAL_ZONE_OP AML_METHOD_OP AML_POWER_RESOURCE_OP AML_PROCESSOR_OP AML_FIELD_OP AML_INDEX_FIELD_OP AML_BANK_FIELD_OP AML_NAME_OP AML_ALIAS_OP AML_MUTEX_OP AML_EVENT_OP AML_REGION_OP AML_CREATE_FIELD_OP AML_CREATE_BIT_FIELD_OP AML_CREATE_BYTE_FIELD_OP AML_CREATE_WORD_FIELD_OP AML_CREATE_DWORD_FIELD_OP AML_CREATE_QWORD_FIELD_OP AML_INT_NAMEDFIELD_OP AML_INT_METHODCALL_OP AML_INT_NAMEPATH_OP Opcodes that are "namespace" opcodes (AML_NSOPCODE flag) AML_SCOPE_OP AML_DEVICE_OP AML_THERMAL_ZONE_OP AML_METHOD_OP AML_POWER_RESOURCE_OP AML_PROCESSOR_OP AML_FIELD_OP AML_INDEX_FIELD_OP AML_BANK_FIELD_OP AML_NAME_OP AML_ALIAS_OP AML_MUTEX_OP AML_EVENT_OP AML_REGION_OP AML_INT_NAMEDFIELD_OP Opcodes that have an associated namespace node (AML_NSNODE flag) AML_SCOPE_OP AML_DEVICE_OP AML_THERMAL_ZONE_OP AML_METHOD_OP AML_POWER_RESOURCE_OP AML_PROCESSOR_OP AML_NAME_OP AML_ALIAS_OP AML_MUTEX_OP AML_EVENT_OP AML_REGION_OP AML_CREATE_FIELD_OP AML_CREATE_BIT_FIELD_OP AML_CREATE_BYTE_FIELD_OP AML_CREATE_WORD_FIELD_OP AML_CREATE_DWORD_FIELD_OP AML_CREATE_QWORD_FIELD_OP AML_INT_NAMEDFIELD_OP AML_INT_METHODCALL_OP AML_INT_NAMEPATH_OP Opcodes that define named ACPI objects (AML_NAMED flag) AML_SCOPE_OP AML_DEVICE_OP AML_THERMAL_ZONE_OP AML_METHOD_OP AML_POWER_RESOURCE_OP AML_PROCESSOR_OP AML_NAME_OP AML_ALIAS_OP AML_MUTEX_OP AML_EVENT_OP AML_REGION_OP AML_INT_NAMEDFIELD_OP Opcodes that contain executable AML as part of the definition that must be deferred until needed AML_METHOD_OP AML_VARIABLE_PACKAGE_OP AML_CREATE_FIELD_OP AML_CREATE_BIT_FIELD_OP AML_CREATE_BYTE_FIELD_OP AML_CREATE_WORD_FIELD_OP AML_CREATE_DWORD_FIELD_OP AML_CREATE_QWORD_FIELD_OP AML_REGION_OP AML_BUFFER_OP Field opcodes AML_CREATE_FIELD_OP AML_FIELD_OP AML_INDEX_FIELD_OP AML_BANK_FIELD_OP Field "Create" opcodes AML_CREATE_FIELD_OP AML_CREATE_BIT_FIELD_OP AML_CREATE_BYTE_FIELD_OP AML_CREATE_WORD_FIELD_OP AML_CREATE_DWORD_FIELD_OP AML_CREATE_QWORD_FIELD_OP ******************************************************************************/ /* * Master Opcode information table. A summary of everything we know about each * opcode, all in one place. */ const struct acpi_opcode_info acpi_gbl_aml_op_info[AML_NUM_OPCODES] = { /*! [Begin] no source code translation */ /* Index Name Parser Args Interpreter Args ObjectType Class Type Flags */ /* 00 */ ACPI_OP("Zero", ARGP_ZERO_OP, ARGI_ZERO_OP, ACPI_TYPE_INTEGER, AML_CLASS_ARGUMENT, AML_TYPE_CONSTANT, AML_CONSTANT), /* 01 */ ACPI_OP("One", ARGP_ONE_OP, ARGI_ONE_OP, ACPI_TYPE_INTEGER, AML_CLASS_ARGUMENT, AML_TYPE_CONSTANT, AML_CONSTANT), /* 02 */ ACPI_OP("Alias", ARGP_ALIAS_OP, ARGI_ALIAS_OP, ACPI_TYPE_LOCAL_ALIAS, AML_CLASS_NAMED_OBJECT, AML_TYPE_NAMED_SIMPLE, AML_HAS_ARGS | AML_NSOBJECT | AML_NSOPCODE | AML_NSNODE | AML_NAMED), /* 03 */ ACPI_OP("Name", ARGP_NAME_OP, ARGI_NAME_OP, ACPI_TYPE_ANY, AML_CLASS_NAMED_OBJECT, AML_TYPE_NAMED_COMPLEX, AML_HAS_ARGS | AML_NSOBJECT | AML_NSOPCODE | AML_NSNODE | AML_NAMED), /* 04 */ ACPI_OP("ByteConst", ARGP_BYTE_OP, ARGI_BYTE_OP, ACPI_TYPE_INTEGER, AML_CLASS_ARGUMENT, AML_TYPE_LITERAL, AML_CONSTANT), /* 05 */ ACPI_OP("WordConst", ARGP_WORD_OP, ARGI_WORD_OP, ACPI_TYPE_INTEGER, AML_CLASS_ARGUMENT, AML_TYPE_LITERAL, AML_CONSTANT), /* 06 */ ACPI_OP("DwordConst", ARGP_DWORD_OP, ARGI_DWORD_OP, ACPI_TYPE_INTEGER, AML_CLASS_ARGUMENT, AML_TYPE_LITERAL, AML_CONSTANT), /* 07 */ ACPI_OP("String", ARGP_STRING_OP, ARGI_STRING_OP, ACPI_TYPE_STRING, AML_CLASS_ARGUMENT, AML_TYPE_LITERAL, AML_CONSTANT), /* 08 */ ACPI_OP("Scope", ARGP_SCOPE_OP, ARGI_SCOPE_OP, ACPI_TYPE_LOCAL_SCOPE, AML_CLASS_NAMED_OBJECT, AML_TYPE_NAMED_NO_OBJ, AML_HAS_ARGS | AML_NSOBJECT | AML_NSOPCODE | AML_NSNODE | AML_NAMED), /* 09 */ ACPI_OP("Buffer", ARGP_BUFFER_OP, ARGI_BUFFER_OP, ACPI_TYPE_BUFFER, AML_CLASS_CREATE, AML_TYPE_CREATE_OBJECT, AML_HAS_ARGS | AML_DEFER | AML_CONSTANT), /* 0A */ ACPI_OP("Package", ARGP_PACKAGE_OP, ARGI_PACKAGE_OP, ACPI_TYPE_PACKAGE, AML_CLASS_CREATE, AML_TYPE_CREATE_OBJECT, AML_HAS_ARGS | AML_DEFER | AML_CONSTANT), /* 0B */ ACPI_OP("Method", ARGP_METHOD_OP, ARGI_METHOD_OP, ACPI_TYPE_METHOD, AML_CLASS_NAMED_OBJECT, AML_TYPE_NAMED_COMPLEX, AML_HAS_ARGS | AML_NSOBJECT | AML_NSOPCODE | AML_NSNODE | AML_NAMED | AML_DEFER), /* 0C */ ACPI_OP("Local0", ARGP_LOCAL0, ARGI_LOCAL0, ACPI_TYPE_LOCAL_REFERENCE, AML_CLASS_ARGUMENT, AML_TYPE_LOCAL_VARIABLE, 0), /* 0D */ ACPI_OP("Local1", ARGP_LOCAL1, ARGI_LOCAL1, ACPI_TYPE_LOCAL_REFERENCE, AML_CLASS_ARGUMENT, AML_TYPE_LOCAL_VARIABLE, 0), /* 0E */ ACPI_OP("Local2", ARGP_LOCAL2, ARGI_LOCAL2, ACPI_TYPE_LOCAL_REFERENCE, AML_CLASS_ARGUMENT, AML_TYPE_LOCAL_VARIABLE, 0), /* 0F */ ACPI_OP("Local3", ARGP_LOCAL3, ARGI_LOCAL3, ACPI_TYPE_LOCAL_REFERENCE, AML_CLASS_ARGUMENT, AML_TYPE_LOCAL_VARIABLE, 0), /* 10 */ ACPI_OP("Local4", ARGP_LOCAL4, ARGI_LOCAL4, ACPI_TYPE_LOCAL_REFERENCE, AML_CLASS_ARGUMENT, AML_TYPE_LOCAL_VARIABLE, 0), /* 11 */ ACPI_OP("Local5", ARGP_LOCAL5, ARGI_LOCAL5, ACPI_TYPE_LOCAL_REFERENCE, AML_CLASS_ARGUMENT, AML_TYPE_LOCAL_VARIABLE, 0), /* 12 */ ACPI_OP("Local6", ARGP_LOCAL6, ARGI_LOCAL6, ACPI_TYPE_LOCAL_REFERENCE, AML_CLASS_ARGUMENT, AML_TYPE_LOCAL_VARIABLE, 0), /* 13 */ ACPI_OP("Local7", ARGP_LOCAL7, ARGI_LOCAL7, ACPI_TYPE_LOCAL_REFERENCE, AML_CLASS_ARGUMENT, AML_TYPE_LOCAL_VARIABLE, 0), /* 14 */ ACPI_OP("Arg0", ARGP_ARG0, ARGI_ARG0, ACPI_TYPE_LOCAL_REFERENCE, AML_CLASS_ARGUMENT, AML_TYPE_METHOD_ARGUMENT, 0), /* 15 */ ACPI_OP("Arg1", ARGP_ARG1, ARGI_ARG1, ACPI_TYPE_LOCAL_REFERENCE, AML_CLASS_ARGUMENT, AML_TYPE_METHOD_ARGUMENT, 0), /* 16 */ ACPI_OP("Arg2", ARGP_ARG2, ARGI_ARG2, ACPI_TYPE_LOCAL_REFERENCE, AML_CLASS_ARGUMENT, AML_TYPE_METHOD_ARGUMENT, 0), /* 17 */ ACPI_OP("Arg3", ARGP_ARG3, ARGI_ARG3, ACPI_TYPE_LOCAL_REFERENCE, AML_CLASS_ARGUMENT, AML_TYPE_METHOD_ARGUMENT, 0), /* 18 */ ACPI_OP("Arg4", ARGP_ARG4, ARGI_ARG4, ACPI_TYPE_LOCAL_REFERENCE, AML_CLASS_ARGUMENT, AML_TYPE_METHOD_ARGUMENT, 0), /* 19 */ ACPI_OP("Arg5", ARGP_ARG5, ARGI_ARG5, ACPI_TYPE_LOCAL_REFERENCE, AML_CLASS_ARGUMENT, AML_TYPE_METHOD_ARGUMENT, 0), /* 1A */ ACPI_OP("Arg6", ARGP_ARG6, ARGI_ARG6, ACPI_TYPE_LOCAL_REFERENCE, AML_CLASS_ARGUMENT, AML_TYPE_METHOD_ARGUMENT, 0), /* 1B */ ACPI_OP("Store", ARGP_STORE_OP, ARGI_STORE_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_1A_1T_1R, AML_FLAGS_EXEC_1A_1T_1R), /* 1C */ ACPI_OP("RefOf", ARGP_REF_OF_OP, ARGI_REF_OF_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_1A_0T_1R, AML_FLAGS_EXEC_1A_0T_1R), /* 1D */ ACPI_OP("Add", ARGP_ADD_OP, ARGI_ADD_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_2A_1T_1R, AML_FLAGS_EXEC_2A_1T_1R | AML_MATH | AML_CONSTANT), /* 1E */ ACPI_OP("Concatenate", ARGP_CONCAT_OP, ARGI_CONCAT_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_2A_1T_1R, AML_FLAGS_EXEC_2A_1T_1R | AML_CONSTANT), /* 1F */ ACPI_OP("Subtract", ARGP_SUBTRACT_OP, ARGI_SUBTRACT_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_2A_1T_1R, AML_FLAGS_EXEC_2A_1T_1R | AML_MATH | AML_CONSTANT), /* 20 */ ACPI_OP("Increment", ARGP_INCREMENT_OP, ARGI_INCREMENT_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_1A_0T_1R, AML_FLAGS_EXEC_1A_0T_1R | AML_CONSTANT), /* 21 */ ACPI_OP("Decrement", ARGP_DECREMENT_OP, ARGI_DECREMENT_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_1A_0T_1R, AML_FLAGS_EXEC_1A_0T_1R | AML_CONSTANT), /* 22 */ ACPI_OP("Multiply", ARGP_MULTIPLY_OP, ARGI_MULTIPLY_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_2A_1T_1R, AML_FLAGS_EXEC_2A_1T_1R | AML_MATH | AML_CONSTANT), /* 23 */ ACPI_OP("Divide", ARGP_DIVIDE_OP, ARGI_DIVIDE_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_2A_2T_1R, AML_FLAGS_EXEC_2A_2T_1R | AML_CONSTANT), /* 24 */ ACPI_OP("ShiftLeft", ARGP_SHIFT_LEFT_OP, ARGI_SHIFT_LEFT_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_2A_1T_1R, AML_FLAGS_EXEC_2A_1T_1R | AML_MATH | AML_CONSTANT), /* 25 */ ACPI_OP("ShiftRight", ARGP_SHIFT_RIGHT_OP, ARGI_SHIFT_RIGHT_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_2A_1T_1R, AML_FLAGS_EXEC_2A_1T_1R | AML_MATH | AML_CONSTANT), /* 26 */ ACPI_OP("And", ARGP_BIT_AND_OP, ARGI_BIT_AND_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_2A_1T_1R, AML_FLAGS_EXEC_2A_1T_1R | AML_MATH | AML_CONSTANT), /* 27 */ ACPI_OP("NAnd", ARGP_BIT_NAND_OP, ARGI_BIT_NAND_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_2A_1T_1R, AML_FLAGS_EXEC_2A_1T_1R | AML_MATH | AML_CONSTANT), /* 28 */ ACPI_OP("Or", ARGP_BIT_OR_OP, ARGI_BIT_OR_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_2A_1T_1R, AML_FLAGS_EXEC_2A_1T_1R | AML_MATH | AML_CONSTANT), /* 29 */ ACPI_OP("NOr", ARGP_BIT_NOR_OP, ARGI_BIT_NOR_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_2A_1T_1R, AML_FLAGS_EXEC_2A_1T_1R | AML_MATH | AML_CONSTANT), /* 2A */ ACPI_OP("XOr", ARGP_BIT_XOR_OP, ARGI_BIT_XOR_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_2A_1T_1R, AML_FLAGS_EXEC_2A_1T_1R | AML_MATH | AML_CONSTANT), /* 2B */ ACPI_OP("Not", ARGP_BIT_NOT_OP, ARGI_BIT_NOT_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_1A_1T_1R, AML_FLAGS_EXEC_1A_1T_1R | AML_CONSTANT), /* 2C */ ACPI_OP("FindSetLeftBit", ARGP_FIND_SET_LEFT_BIT_OP, ARGI_FIND_SET_LEFT_BIT_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_1A_1T_1R, AML_FLAGS_EXEC_1A_1T_1R | AML_CONSTANT), /* 2D */ ACPI_OP("FindSetRightBit", ARGP_FIND_SET_RIGHT_BIT_OP, ARGI_FIND_SET_RIGHT_BIT_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_1A_1T_1R, AML_FLAGS_EXEC_1A_1T_1R | AML_CONSTANT), /* 2E */ ACPI_OP("DerefOf", ARGP_DEREF_OF_OP, ARGI_DEREF_OF_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_1A_0T_1R, AML_FLAGS_EXEC_1A_0T_1R), /* 2F */ ACPI_OP("Notify", ARGP_NOTIFY_OP, ARGI_NOTIFY_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_2A_0T_0R, AML_FLAGS_EXEC_2A_0T_0R), /* 30 */ ACPI_OP("SizeOf", ARGP_SIZE_OF_OP, ARGI_SIZE_OF_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_1A_0T_1R, AML_FLAGS_EXEC_1A_0T_1R | AML_NO_OPERAND_RESOLVE), /* 31 */ ACPI_OP("Index", ARGP_INDEX_OP, ARGI_INDEX_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_2A_1T_1R, AML_FLAGS_EXEC_2A_1T_1R), /* 32 */ ACPI_OP("Match", ARGP_MATCH_OP, ARGI_MATCH_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_6A_0T_1R, AML_FLAGS_EXEC_6A_0T_1R | AML_CONSTANT), /* 33 */ ACPI_OP("CreateDWordField", ARGP_CREATE_DWORD_FIELD_OP, ARGI_CREATE_DWORD_FIELD_OP, ACPI_TYPE_BUFFER_FIELD, AML_CLASS_CREATE, AML_TYPE_CREATE_FIELD, AML_HAS_ARGS | AML_NSOBJECT | AML_NSNODE | AML_DEFER | AML_CREATE), /* 34 */ ACPI_OP("CreateWordField", ARGP_CREATE_WORD_FIELD_OP, ARGI_CREATE_WORD_FIELD_OP, ACPI_TYPE_BUFFER_FIELD, AML_CLASS_CREATE, AML_TYPE_CREATE_FIELD, AML_HAS_ARGS | AML_NSOBJECT | AML_NSNODE | AML_DEFER | AML_CREATE), /* 35 */ ACPI_OP("CreateByteField", ARGP_CREATE_BYTE_FIELD_OP, ARGI_CREATE_BYTE_FIELD_OP, ACPI_TYPE_BUFFER_FIELD, AML_CLASS_CREATE, AML_TYPE_CREATE_FIELD, AML_HAS_ARGS | AML_NSOBJECT | AML_NSNODE | AML_DEFER | AML_CREATE), /* 36 */ ACPI_OP("CreateBitField", ARGP_CREATE_BIT_FIELD_OP, ARGI_CREATE_BIT_FIELD_OP, ACPI_TYPE_BUFFER_FIELD, AML_CLASS_CREATE, AML_TYPE_CREATE_FIELD, AML_HAS_ARGS | AML_NSOBJECT | AML_NSNODE | AML_DEFER | AML_CREATE), /* 37 */ ACPI_OP("ObjectType", ARGP_OBJECT_TYPE_OP, ARGI_OBJECT_TYPE_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_1A_0T_1R, AML_FLAGS_EXEC_1A_0T_1R | AML_NO_OPERAND_RESOLVE), /* 38 */ ACPI_OP("LAnd", ARGP_LAND_OP, ARGI_LAND_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_2A_0T_1R, AML_FLAGS_EXEC_2A_0T_1R | AML_LOGICAL_NUMERIC | AML_CONSTANT), /* 39 */ ACPI_OP("LOr", ARGP_LOR_OP, ARGI_LOR_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_2A_0T_1R, AML_FLAGS_EXEC_2A_0T_1R | AML_LOGICAL_NUMERIC | AML_CONSTANT), /* 3A */ ACPI_OP("LNot", ARGP_LNOT_OP, ARGI_LNOT_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_1A_0T_1R, AML_FLAGS_EXEC_1A_0T_1R | AML_CONSTANT), /* 3B */ ACPI_OP("LEqual", ARGP_LEQUAL_OP, ARGI_LEQUAL_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_2A_0T_1R, AML_FLAGS_EXEC_2A_0T_1R | AML_LOGICAL | AML_CONSTANT), /* 3C */ ACPI_OP("LGreater", ARGP_LGREATER_OP, ARGI_LGREATER_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_2A_0T_1R, AML_FLAGS_EXEC_2A_0T_1R | AML_LOGICAL | AML_CONSTANT), /* 3D */ ACPI_OP("LLess", ARGP_LLESS_OP, ARGI_LLESS_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_2A_0T_1R, AML_FLAGS_EXEC_2A_0T_1R | AML_LOGICAL | AML_CONSTANT), /* 3E */ ACPI_OP("If", ARGP_IF_OP, ARGI_IF_OP, ACPI_TYPE_ANY, AML_CLASS_CONTROL, AML_TYPE_CONTROL, AML_HAS_ARGS), /* 3F */ ACPI_OP("Else", ARGP_ELSE_OP, ARGI_ELSE_OP, ACPI_TYPE_ANY, AML_CLASS_CONTROL, AML_TYPE_CONTROL, AML_HAS_ARGS), /* 40 */ ACPI_OP("While", ARGP_WHILE_OP, ARGI_WHILE_OP, ACPI_TYPE_ANY, AML_CLASS_CONTROL, AML_TYPE_CONTROL, AML_HAS_ARGS), /* 41 */ ACPI_OP("Noop", ARGP_NOOP_OP, ARGI_NOOP_OP, ACPI_TYPE_ANY, AML_CLASS_CONTROL, AML_TYPE_CONTROL, 0), /* 42 */ ACPI_OP("Return", ARGP_RETURN_OP, ARGI_RETURN_OP, ACPI_TYPE_ANY, AML_CLASS_CONTROL, AML_TYPE_CONTROL, AML_HAS_ARGS), /* 43 */ ACPI_OP("Break", ARGP_BREAK_OP, ARGI_BREAK_OP, ACPI_TYPE_ANY, AML_CLASS_CONTROL, AML_TYPE_CONTROL, 0), /* 44 */ ACPI_OP("BreakPoint", ARGP_BREAK_POINT_OP, ARGI_BREAK_POINT_OP, ACPI_TYPE_ANY, AML_CLASS_CONTROL, AML_TYPE_CONTROL, 0), /* 45 */ ACPI_OP("Ones", ARGP_ONES_OP, ARGI_ONES_OP, ACPI_TYPE_INTEGER, AML_CLASS_ARGUMENT, AML_TYPE_CONSTANT, AML_CONSTANT), /* Prefixed opcodes (Two-byte opcodes with a prefix op) */ /* 46 */ ACPI_OP("Mutex", ARGP_MUTEX_OP, ARGI_MUTEX_OP, ACPI_TYPE_MUTEX, AML_CLASS_NAMED_OBJECT, AML_TYPE_NAMED_SIMPLE, AML_HAS_ARGS | AML_NSOBJECT | AML_NSOPCODE | AML_NSNODE | AML_NAMED), /* 47 */ ACPI_OP("Event", ARGP_EVENT_OP, ARGI_EVENT_OP, ACPI_TYPE_EVENT, AML_CLASS_NAMED_OBJECT, AML_TYPE_NAMED_SIMPLE, AML_NSOBJECT | AML_NSOPCODE | AML_NSNODE | AML_NAMED), /* 48 */ ACPI_OP("CondRefOf", ARGP_COND_REF_OF_OP, ARGI_COND_REF_OF_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_1A_1T_1R, AML_FLAGS_EXEC_1A_1T_1R), /* 49 */ ACPI_OP("CreateField", ARGP_CREATE_FIELD_OP, ARGI_CREATE_FIELD_OP, ACPI_TYPE_BUFFER_FIELD, AML_CLASS_CREATE, AML_TYPE_CREATE_FIELD, AML_HAS_ARGS | AML_NSOBJECT | AML_NSNODE | AML_DEFER | AML_FIELD | AML_CREATE), /* 4A */ ACPI_OP("Load", ARGP_LOAD_OP, ARGI_LOAD_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_1A_1T_0R, AML_FLAGS_EXEC_1A_1T_0R), /* 4B */ ACPI_OP("Stall", ARGP_STALL_OP, ARGI_STALL_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_1A_0T_0R, AML_FLAGS_EXEC_1A_0T_0R), /* 4C */ ACPI_OP("Sleep", ARGP_SLEEP_OP, ARGI_SLEEP_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_1A_0T_0R, AML_FLAGS_EXEC_1A_0T_0R), /* 4D */ ACPI_OP("Acquire", ARGP_ACQUIRE_OP, ARGI_ACQUIRE_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_2A_0T_1R, AML_FLAGS_EXEC_2A_0T_1R), /* 4E */ ACPI_OP("Signal", ARGP_SIGNAL_OP, ARGI_SIGNAL_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_1A_0T_0R, AML_FLAGS_EXEC_1A_0T_0R), /* 4F */ ACPI_OP("Wait", ARGP_WAIT_OP, ARGI_WAIT_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_2A_0T_1R, AML_FLAGS_EXEC_2A_0T_1R), /* 50 */ ACPI_OP("Reset", ARGP_RESET_OP, ARGI_RESET_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_1A_0T_0R, AML_FLAGS_EXEC_1A_0T_0R), /* 51 */ ACPI_OP("Release", ARGP_RELEASE_OP, ARGI_RELEASE_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_1A_0T_0R, AML_FLAGS_EXEC_1A_0T_0R), /* 52 */ ACPI_OP("FromBCD", ARGP_FROM_BCD_OP, ARGI_FROM_BCD_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_1A_1T_1R, AML_FLAGS_EXEC_1A_1T_1R | AML_CONSTANT), /* 53 */ ACPI_OP("ToBCD", ARGP_TO_BCD_OP, ARGI_TO_BCD_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_1A_1T_1R, AML_FLAGS_EXEC_1A_1T_1R | AML_CONSTANT), /* 54 */ ACPI_OP("Unload", ARGP_UNLOAD_OP, ARGI_UNLOAD_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_1A_0T_0R, AML_FLAGS_EXEC_1A_0T_0R), /* 55 */ ACPI_OP("Revision", ARGP_REVISION_OP, ARGI_REVISION_OP, ACPI_TYPE_INTEGER, AML_CLASS_ARGUMENT, AML_TYPE_CONSTANT, 0), /* 56 */ ACPI_OP("Debug", ARGP_DEBUG_OP, ARGI_DEBUG_OP, ACPI_TYPE_LOCAL_REFERENCE, AML_CLASS_ARGUMENT, AML_TYPE_CONSTANT, 0), /* 57 */ ACPI_OP("Fatal", ARGP_FATAL_OP, ARGI_FATAL_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_3A_0T_0R, AML_FLAGS_EXEC_3A_0T_0R), /* 58 */ ACPI_OP("OperationRegion", ARGP_REGION_OP, ARGI_REGION_OP, ACPI_TYPE_REGION, AML_CLASS_NAMED_OBJECT, AML_TYPE_NAMED_COMPLEX, AML_HAS_ARGS | AML_NSOBJECT | AML_NSOPCODE | AML_NSNODE | AML_NAMED | AML_DEFER), /* 59 */ ACPI_OP("Field", ARGP_FIELD_OP, ARGI_FIELD_OP, ACPI_TYPE_ANY, AML_CLASS_NAMED_OBJECT, AML_TYPE_NAMED_FIELD, AML_HAS_ARGS | AML_NSOBJECT | AML_NSOPCODE | AML_FIELD), /* 5A */ ACPI_OP("Device", ARGP_DEVICE_OP, ARGI_DEVICE_OP, ACPI_TYPE_DEVICE, AML_CLASS_NAMED_OBJECT, AML_TYPE_NAMED_NO_OBJ, AML_HAS_ARGS | AML_NSOBJECT | AML_NSOPCODE | AML_NSNODE | AML_NAMED), /* 5B */ ACPI_OP("Processor", ARGP_PROCESSOR_OP, ARGI_PROCESSOR_OP, ACPI_TYPE_PROCESSOR, AML_CLASS_NAMED_OBJECT, AML_TYPE_NAMED_SIMPLE, AML_HAS_ARGS | AML_NSOBJECT | AML_NSOPCODE | AML_NSNODE | AML_NAMED), /* 5C */ ACPI_OP("PowerResource", ARGP_POWER_RES_OP, ARGI_POWER_RES_OP, ACPI_TYPE_POWER, AML_CLASS_NAMED_OBJECT, AML_TYPE_NAMED_SIMPLE, AML_HAS_ARGS | AML_NSOBJECT | AML_NSOPCODE | AML_NSNODE | AML_NAMED), /* 5D */ ACPI_OP("ThermalZone", ARGP_THERMAL_ZONE_OP, ARGI_THERMAL_ZONE_OP, ACPI_TYPE_THERMAL, AML_CLASS_NAMED_OBJECT, AML_TYPE_NAMED_NO_OBJ, AML_HAS_ARGS | AML_NSOBJECT | AML_NSOPCODE | AML_NSNODE | AML_NAMED), /* 5E */ ACPI_OP("IndexField", ARGP_INDEX_FIELD_OP, ARGI_INDEX_FIELD_OP, ACPI_TYPE_ANY, AML_CLASS_NAMED_OBJECT, AML_TYPE_NAMED_FIELD, AML_HAS_ARGS | AML_NSOBJECT | AML_NSOPCODE | AML_FIELD), /* 5F */ ACPI_OP("BankField", ARGP_BANK_FIELD_OP, ARGI_BANK_FIELD_OP, ACPI_TYPE_LOCAL_BANK_FIELD, AML_CLASS_NAMED_OBJECT, AML_TYPE_NAMED_FIELD, AML_HAS_ARGS | AML_NSOBJECT | AML_NSOPCODE | AML_FIELD | AML_DEFER), /* Internal opcodes that map to invalid AML opcodes */ /* 60 */ ACPI_OP("LNotEqual", ARGP_LNOTEQUAL_OP, ARGI_LNOTEQUAL_OP, ACPI_TYPE_ANY, AML_CLASS_INTERNAL, AML_TYPE_BOGUS, AML_HAS_ARGS | AML_CONSTANT), /* 61 */ ACPI_OP("LLessEqual", ARGP_LLESSEQUAL_OP, ARGI_LLESSEQUAL_OP, ACPI_TYPE_ANY, AML_CLASS_INTERNAL, AML_TYPE_BOGUS, AML_HAS_ARGS | AML_CONSTANT), /* 62 */ ACPI_OP("LGreaterEqual", ARGP_LGREATEREQUAL_OP, ARGI_LGREATEREQUAL_OP, ACPI_TYPE_ANY, AML_CLASS_INTERNAL, AML_TYPE_BOGUS, AML_HAS_ARGS | AML_CONSTANT), /* 63 */ ACPI_OP("-NamePath-", ARGP_NAMEPATH_OP, ARGI_NAMEPATH_OP, ACPI_TYPE_LOCAL_REFERENCE, AML_CLASS_ARGUMENT, AML_TYPE_LITERAL, AML_NSOBJECT | AML_NSNODE), /* 64 */ ACPI_OP("-MethodCall-", ARGP_METHODCALL_OP, ARGI_METHODCALL_OP, ACPI_TYPE_METHOD, AML_CLASS_METHOD_CALL, AML_TYPE_METHOD_CALL, AML_HAS_ARGS | AML_NSOBJECT | AML_NSNODE), /* 65 */ ACPI_OP("-ByteList-", ARGP_BYTELIST_OP, ARGI_BYTELIST_OP, ACPI_TYPE_ANY, AML_CLASS_ARGUMENT, AML_TYPE_LITERAL, 0), /* 66 */ ACPI_OP("-ReservedField-", ARGP_RESERVEDFIELD_OP, ARGI_RESERVEDFIELD_OP, ACPI_TYPE_ANY, AML_CLASS_INTERNAL, AML_TYPE_BOGUS, 0), /* 67 */ ACPI_OP("-NamedField-", ARGP_NAMEDFIELD_OP, ARGI_NAMEDFIELD_OP, ACPI_TYPE_ANY, AML_CLASS_INTERNAL, AML_TYPE_BOGUS, AML_NSOBJECT | AML_NSOPCODE | AML_NSNODE | AML_NAMED), /* 68 */ ACPI_OP("-AccessField-", ARGP_ACCESSFIELD_OP, ARGI_ACCESSFIELD_OP, ACPI_TYPE_ANY, AML_CLASS_INTERNAL, AML_TYPE_BOGUS, 0), /* 69 */ ACPI_OP("-StaticString", ARGP_STATICSTRING_OP, ARGI_STATICSTRING_OP, ACPI_TYPE_ANY, AML_CLASS_INTERNAL, AML_TYPE_BOGUS, 0), /* 6A */ ACPI_OP("-Return Value-", ARG_NONE, ARG_NONE, ACPI_TYPE_ANY, AML_CLASS_RETURN_VALUE, AML_TYPE_RETURN, AML_HAS_ARGS | AML_HAS_RETVAL), /* 6B */ ACPI_OP("-UNKNOWN_OP-", ARG_NONE, ARG_NONE, ACPI_TYPE_INVALID, AML_CLASS_UNKNOWN, AML_TYPE_BOGUS, AML_HAS_ARGS), /* 6C */ ACPI_OP("-ASCII_ONLY-", ARG_NONE, ARG_NONE, ACPI_TYPE_ANY, AML_CLASS_ASCII, AML_TYPE_BOGUS, AML_HAS_ARGS), /* 6D */ ACPI_OP("-PREFIX_ONLY-", ARG_NONE, ARG_NONE, ACPI_TYPE_ANY, AML_CLASS_PREFIX, AML_TYPE_BOGUS, AML_HAS_ARGS), /* ACPI 2.0 opcodes */ /* 6E */ ACPI_OP("QwordConst", ARGP_QWORD_OP, ARGI_QWORD_OP, ACPI_TYPE_INTEGER, AML_CLASS_ARGUMENT, AML_TYPE_LITERAL, AML_CONSTANT), /* 6F */ ACPI_OP("Package", /* Var */ ARGP_VAR_PACKAGE_OP, ARGI_VAR_PACKAGE_OP, ACPI_TYPE_PACKAGE, AML_CLASS_CREATE, AML_TYPE_CREATE_OBJECT, AML_HAS_ARGS | AML_DEFER), /* 70 */ ACPI_OP("ConcatenateResTemplate", ARGP_CONCAT_RES_OP, ARGI_CONCAT_RES_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_2A_1T_1R, AML_FLAGS_EXEC_2A_1T_1R | AML_CONSTANT), /* 71 */ ACPI_OP("Mod", ARGP_MOD_OP, ARGI_MOD_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_2A_1T_1R, AML_FLAGS_EXEC_2A_1T_1R | AML_CONSTANT), /* 72 */ ACPI_OP("CreateQWordField", ARGP_CREATE_QWORD_FIELD_OP, ARGI_CREATE_QWORD_FIELD_OP, ACPI_TYPE_BUFFER_FIELD, AML_CLASS_CREATE, AML_TYPE_CREATE_FIELD, AML_HAS_ARGS | AML_NSOBJECT | AML_NSNODE | AML_DEFER | AML_CREATE), /* 73 */ ACPI_OP("ToBuffer", ARGP_TO_BUFFER_OP, ARGI_TO_BUFFER_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_1A_1T_1R, AML_FLAGS_EXEC_1A_1T_1R | AML_CONSTANT), /* 74 */ ACPI_OP("ToDecimalString", ARGP_TO_DEC_STR_OP, ARGI_TO_DEC_STR_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_1A_1T_1R, AML_FLAGS_EXEC_1A_1T_1R | AML_CONSTANT), /* 75 */ ACPI_OP("ToHexString", ARGP_TO_HEX_STR_OP, ARGI_TO_HEX_STR_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_1A_1T_1R, AML_FLAGS_EXEC_1A_1T_1R | AML_CONSTANT), /* 76 */ ACPI_OP("ToInteger", ARGP_TO_INTEGER_OP, ARGI_TO_INTEGER_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_1A_1T_1R, AML_FLAGS_EXEC_1A_1T_1R | AML_CONSTANT), /* 77 */ ACPI_OP("ToString", ARGP_TO_STRING_OP, ARGI_TO_STRING_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_2A_1T_1R, AML_FLAGS_EXEC_2A_1T_1R | AML_CONSTANT), /* 78 */ ACPI_OP("CopyObject", ARGP_COPY_OP, ARGI_COPY_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_1A_1T_1R, AML_FLAGS_EXEC_1A_1T_1R), /* 79 */ ACPI_OP("Mid", ARGP_MID_OP, ARGI_MID_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_3A_1T_1R, AML_FLAGS_EXEC_3A_1T_1R | AML_CONSTANT), /* 7A */ ACPI_OP("Continue", ARGP_CONTINUE_OP, ARGI_CONTINUE_OP, ACPI_TYPE_ANY, AML_CLASS_CONTROL, AML_TYPE_CONTROL, 0), /* 7B */ ACPI_OP("LoadTable", ARGP_LOAD_TABLE_OP, ARGI_LOAD_TABLE_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_6A_0T_1R, AML_FLAGS_EXEC_6A_0T_1R), /* 7C */ ACPI_OP("DataTableRegion", ARGP_DATA_REGION_OP, ARGI_DATA_REGION_OP, ACPI_TYPE_REGION, AML_CLASS_NAMED_OBJECT, AML_TYPE_NAMED_COMPLEX, AML_HAS_ARGS | AML_NSOBJECT | AML_NSOPCODE | AML_NSNODE | AML_NAMED | AML_DEFER), /* 7D */ ACPI_OP("[EvalSubTree]", ARGP_SCOPE_OP, ARGI_SCOPE_OP, ACPI_TYPE_ANY, AML_CLASS_NAMED_OBJECT, AML_TYPE_NAMED_NO_OBJ, AML_HAS_ARGS | AML_NSOBJECT | AML_NSOPCODE | AML_NSNODE), /* ACPI 3.0 opcodes */ /* 7E */ ACPI_OP("Timer", ARGP_TIMER_OP, ARGI_TIMER_OP, ACPI_TYPE_ANY, AML_CLASS_EXECUTE, AML_TYPE_EXEC_0A_0T_1R, AML_FLAGS_EXEC_0A_0T_1R), /* ACPI 5.0 opcodes */ /* 7F */ ACPI_OP("-ConnectField-", ARGP_CONNECTFIELD_OP, ARGI_CONNECTFIELD_OP, ACPI_TYPE_ANY, AML_CLASS_INTERNAL, AML_TYPE_BOGUS, AML_HAS_ARGS), /* 80 */ ACPI_OP("-ExtAccessField-", ARGP_CONNECTFIELD_OP, ARGI_CONNECTFIELD_OP, ACPI_TYPE_ANY, AML_CLASS_INTERNAL, AML_TYPE_BOGUS, 0), /* ACPI 6.0 opcodes */ /* 81 */ ACPI_OP("External", ARGP_EXTERNAL_OP, ARGI_EXTERNAL_OP, ACPI_TYPE_ANY, AML_CLASS_NAMED_OBJECT, AML_TYPE_NAMED_SIMPLE, AML_HAS_ARGS | AML_NSOBJECT | AML_NSOPCODE | AML_NSNODE | AML_NAMED), /* 82 */ ACPI_OP("Comment", ARGP_COMMENT_OP, ARGI_COMMENT_OP, ACPI_TYPE_STRING, AML_CLASS_ARGUMENT, AML_TYPE_LITERAL, AML_CONSTANT) /*! [End] no source code translation !*/ };
40.912698
185
0.756353