hexsha
stringlengths
40
40
size
int64
5
2.72M
ext
stringclasses
5 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
976
max_stars_repo_name
stringlengths
5
113
max_stars_repo_head_hexsha
stringlengths
40
78
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:01:43
2022-03-31 23:59:48
max_stars_repo_stars_event_max_datetime
stringdate
2015-01-01 00:06:24
2022-03-31 23:59:53
max_issues_repo_path
stringlengths
3
976
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
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
976
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
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:19
2022-03-31 23:59:49
max_forks_repo_forks_event_max_datetime
stringdate
2015-01-03 12:00:57
2022-03-31 23:59:49
content
stringlengths
5
2.72M
avg_line_length
float64
1.38
573k
max_line_length
int64
2
1.01M
alphanum_fraction
float64
0
1
ffb3cc621580cd4d596217691898ee42fb00071c
38
h
C
src/CStopWatch/CStopWatch/src/CStopWatchMacroLib.h
isuhao/xylsxyls-xueyelingshuang
7a2c732863aecb7ad2b1af0016b129c5041ad54b
[ "MIT" ]
1
2020-06-03T03:27:26.000Z
2020-06-03T03:27:26.000Z
src/CStopWatch/CStopWatch/src/CStopWatchMacroLib.h
isuhao/xylsxyls-xueyelingshuang
7a2c732863aecb7ad2b1af0016b129c5041ad54b
[ "MIT" ]
null
null
null
src/CStopWatch/CStopWatch/src/CStopWatchMacroLib.h
isuhao/xylsxyls-xueyelingshuang
7a2c732863aecb7ad2b1af0016b129c5041ad54b
[ "MIT" ]
1
2020-06-03T03:27:27.000Z
2020-06-03T03:27:27.000Z
#pragma once #define CStopWatchAPI
12.666667
22
0.763158
ffb4c499853bb0b0ece4b9cca6c96fbf5ca6280a
228
c
C
benchmarks/ptaben/ptaben-updated/mem_leak/malloc23.c
taquangtrung/discover
2ae5e07db51737c1c84fbd6b74297d03c2e91c29
[ "Apache-2.0" ]
122
2019-11-12T18:43:32.000Z
2022-01-30T15:11:43.000Z
benchmarks/ptaben/ptaben-updated/mem_leak/malloc23.c
taquangtrung/discover
2ae5e07db51737c1c84fbd6b74297d03c2e91c29
[ "Apache-2.0" ]
78
2021-11-01T06:55:39.000Z
2022-03-15T02:55:55.000Z
CCured/program-dependence-graph/SVF/Test-Suite/mem_leak/malloc23.c
Lightninghkm/DataGuard
4ac1370f7607cec5fc81c3b57f5a62fb1d40f463
[ "Apache-2.0" ]
34
2019-11-12T18:43:34.000Z
2021-12-22T07:46:03.000Z
/* * Safe malloc * Author: Yule Sui * Date: 02/04/2014 */ #include "aliascheck.h" int func(){ int* p = SAFEMALLOC(1); free(p); int *q = SAFEMALLOC(1); if(q==0) return -1; free(q); } int main(){ func(); }
7.6
24
0.535088
ffb5afbf205f1c837ed0b022d71d717c90ce84f9
982
c
C
util/test/test_utf8_char.c
schibsted/sebase
ed1bb6f683c1e2137dcabe65930bcc64ab187b2f
[ "MIT" ]
2
2018-12-31T14:42:35.000Z
2020-09-07T23:36:40.000Z
util/test/test_utf8_char.c
schibsted/sebase
ed1bb6f683c1e2137dcabe65930bcc64ab187b2f
[ "MIT" ]
2
2019-01-18T14:16:25.000Z
2019-03-20T15:26:53.000Z
util/test/test_utf8_char.c
schibsted/sebase
ed1bb6f683c1e2137dcabe65930bcc64ab187b2f
[ "MIT" ]
1
2022-02-01T16:38:21.000Z
2022-02-01T16:38:21.000Z
// Copyright 2018 Schibsted #include "sbp/string_functions.h" #include <stdio.h> #include <string.h> int main(int argc, char *argv[]) { // One character of each UTF-8 length (with spaces after each). char input[] = "A γ € 🌈 "; int expect[8] = { 'A', ' ', 0x3B3, ' ', 0x20AC, ' ', 0x1F308, ' ' }, *eptr = expect; const char *ptr = input, *pptr = input; int ch; int ret = 0; while ((ch = utf8_char(&ptr))) { if (ch != *eptr) { fprintf(stderr, "Expected U+%X, got U+%X\n", *eptr, ch); ret = 1; } eptr++; char output[5], *wptr = output; write_utf8_char(&wptr, ch); if (ptr - pptr != wptr - output) { fprintf(stderr, "Got different length writing, %d != %d", (int)(wptr - output), (int)(ptr - pptr)); ret = 1; } else if (memcmp(pptr, output, wptr - output) != 0) { fprintf(stderr, "Wrote different output than input, %.*s != %.*s", (int)(wptr - output), output, (int)(ptr - pptr), pptr); ret = 1; } pptr = ptr; } return ret; }
25.179487
85
0.571283
ffb6e7b74c4dc70d5dbb6ba84bb753d57ca3b0d0
427
h
C
luaext_lib/luaext_lib.h
n1tehawk/luaext
813ed84cb37ec57044ce408fce103fea47942e35
[ "MIT" ]
null
null
null
luaext_lib/luaext_lib.h
n1tehawk/luaext
813ed84cb37ec57044ce408fce103fea47942e35
[ "MIT" ]
null
null
null
luaext_lib/luaext_lib.h
n1tehawk/luaext
813ed84cb37ec57044ce408fce103fea47942e35
[ "MIT" ]
null
null
null
// luaext_lib.h #ifndef LUAEXT_LIB_H #define LUAEXT_LIB_H #include "lua.h" //#include "lualib.h" //#include "lauxlib.h" #include "luahelpers.h" #include <stdbool.h> bool luaext_isEmpty(lua_State *L, int idx); // test for "empty" value int cross_type_compare(lua_State *L, int index1, int index2); LUA_CFUNC(luaext_crossTypeCompare); LUA_CFUNC(luaext_crossTypeSort); LUA_CFUNC(luaopen_luaext_lib); #endif // LUAEXT_LIB_H
19.409091
69
0.761124
ffb9c131d3d06e761502843cf92e94bb560cea14
833
h
C
src/main/include/endgame.h
FRC-Team-955/Team-955-Infinite-Recharge-2020
a2b3c49d7639fd6383fcf73ae1d469955336c541
[ "BSD-3-Clause" ]
null
null
null
src/main/include/endgame.h
FRC-Team-955/Team-955-Infinite-Recharge-2020
a2b3c49d7639fd6383fcf73ae1d469955336c541
[ "BSD-3-Clause" ]
20
2020-01-31T18:51:01.000Z
2020-03-08T20:36:57.000Z
src/main/include/endgame.h
FRC-Team-955/Team-955-Infinite-Recharge-2020
a2b3c49d7639fd6383fcf73ae1d469955336c541
[ "BSD-3-Clause" ]
3
2020-02-03T06:12:44.000Z
2021-03-15T00:09:41.000Z
#ifndef ENDGAME #define ENDGAME #include "frc/WPILib.h" #include <iostream> #include "ctre/Phoenix.h" #include <cmath> #include "winch.h" #include "elevator.h" #include "lidar.h" //#include "auto.h" class EndGame { public: EndGame (Elevator *elevator, Winch *winch, Lidar *lidar, frc::Joystick *joystick, TalonSRX *talon_drive_left, TalonSRX *talon_drive_right) : elevator(elevator), winch(winch), lidar(lidar), joystick(joystick), talon_drive_left(talon_drive_left), talon_drive_right(talon_drive_right) {}; void MoveSlow(); void Climb(); int CalculateEncoderCounts(int length_inches); int mode = 1; private: Elevator *elevator; Winch *winch; Lidar *lidar; frc::Joystick *joystick; TalonSRX *talon_drive_left; TalonSRX *talon_drive_right; bool is_pressed = false; bool toggle = false; }; #endif
25.242424
288
0.732293
ffbaf789642c0f1996856744f9295fa2166c529f
1,110
h
C
lib/WaveIO.h
SkinnyJeansDev/WaveNightCore
d2e5288dc2531d7b18e8d92af5dbd7cdd4da1b66
[ "Apache-2.0" ]
null
null
null
lib/WaveIO.h
SkinnyJeansDev/WaveNightCore
d2e5288dc2531d7b18e8d92af5dbd7cdd4da1b66
[ "Apache-2.0" ]
1
2021-09-16T01:46:30.000Z
2021-09-16T01:46:30.000Z
lib/WaveIO.h
SkinnyJeansDev/WaveNightCore
d2e5288dc2531d7b18e8d92af5dbd7cdd4da1b66
[ "Apache-2.0" ]
null
null
null
#ifndef WAVEIO #define WAVEIO #include <stdio.h> #include <stdint.h> #include <stdlib.h> #include <string.h> #include <stdbool.h> #include "WaveDataStructs.h" //READ // Read In The RIFFWAVE Starting Chunk void ReadRiffWave(struct RIFFWAVE *riffWave,FILE *filePointer); void ReadWaveFileHeader(WaveFileHeader *waveFileHeader,FILE *filepointer); //Starts reading the next chunk of the file and skips over it in its entirety if the name is JUNK. //Returns a bool indicating if it skipped ahead or not. bool SkipJunkIfExists(FILE *filePointer); void ReadWaveDataChunkHeader(WaveDataChunk *waveDataChunk, WaveFileHeader *waveFileHeader, FILE *filepointer); void ReadWaveDataChunkSamples(WaveDataChunk * waveDataChunk,WaveFileHeader *waveFileHeader,FILE *filePointer); // WRITE void WriteRiffWave(RIFFWAVE* riffWave, FILE* outPointer); void WriteWaveFileHeader(WaveFileHeader* waveFileHeader, FILE* outPointer); void WriteWaveDataChunkHeader(WaveDataChunk* waveDataChunk, FILE* outPointer); void WriteWaveDataChunkSamples(WaveDataChunk *waveDataChunk,WaveFileHeader *waveFileHeader,FILE *filePointer); #endif
37
110
0.814414
ffbbfc7f3896e734dd29d19d717fbd265b614e15
17,183
c
C
examples/test_lorasc.c
W-Wuxian/preAlps
9718968d3474be821ceb676ceff8e1dee1dae2f0
[ "BSD-3-Clause" ]
6
2019-03-28T12:30:06.000Z
2022-02-25T17:42:29.000Z
examples/test_lorasc.c
W-Wuxian/preAlps
9718968d3474be821ceb676ceff8e1dee1dae2f0
[ "BSD-3-Clause" ]
1
2019-03-14T16:11:37.000Z
2019-03-14T16:11:37.000Z
examples/test_lorasc.c
W-Wuxian/preAlps
9718968d3474be821ceb676ceff8e1dee1dae2f0
[ "BSD-3-Clause" ]
3
2020-11-17T22:41:41.000Z
2021-10-05T11:22:04.000Z
/* ============================================================================ Name : test_lorasc.c Author : Simplice Donfack Version : 0.1 Description : Preconditioner based on Schur complement Date : Mai 15, 2017 ============================================================================ */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <mpi.h> #ifdef USE_PETSC /* Petsc */ #include <preAlps_petsc_interface.h> #include <petscksp.h> #endif //#include <mat_load_mm.h> #include "preAlps_utils.h" #include "preAlps_doublevector.h" #include <cplm_utils.h> #include "cplm_matcsr.h" #include "precond.h" #include "preAlps_preconditioner.h" #include "lorasc.h" #include "block_jacobi.h" #include "ecg.h" #include "operator.h" static int testLorasc_checkArgs(MPI_Comm comm, int precond_num, Prec_Type_t precond_type, int npLevel1){ int my_rank, nbprocs; MPI_Comm_rank(comm, &my_rank); MPI_Comm_size(comm, &nbprocs); if(my_rank==0){ if(precond_num<0 || precond_num>2) preAlps_abort("Unknown preconditioner"); if(precond_type != PREALPS_LORASC && npLevel1!=nbprocs){ preAlps_abort("This preconditioner does not support more than 1 block per process. Do not set -npLevel1"); } if(nbprocs%npLevel1!=0){ preAlps_abort("npLevel1: %d should be a multiple of p: %d", npLevel1, nbprocs); } } return 0; } static int testLorasc_ECGSolve(preAlps_ECG_t *ecg, PreAlps_preconditioner_t *precond, MPI_Comm *commMultilevel, double *b, double *sol, int monitorResidual){ int ierr = 0, rci_request = 0, stop = 0; MPI_Comm comm, comm_masterLevel, comm_localLevel; int my_rank, root = 0, local_root=0; // Get the multilevel communicators comm = commMultilevel[0]; comm_masterLevel = commMultilevel[1]; comm_localLevel = commMultilevel[2]; // Let me know who I am MPI_Comm_rank(comm, &my_rank); // Allocate memory and initialize variables if(comm_masterLevel!=MPI_COMM_NULL){ preAlps_ECGInitialize(ecg, b, &rci_request); } // Finish initialization preAlps_PreconditionerMatApply(precond, ecg->R, ecg->P); //Compute AP = A*P if(comm_masterLevel!=MPI_COMM_NULL){ preAlps_BlockOperator(ecg->P, ecg->AP); } // Pointers for the RCI interface CPLM_Mat_Dense_t *AX = NULL, *AY = NULL; if (ecg->ortho_alg == ORTHOMIN){ AX = ecg->R; AY = ecg->Z; } else if (ecg->ortho_alg == ORTHODIR){ AX = ecg->AP; AY = ecg->Z; } // Main loop while (stop != 1) { //Iterate at the master level if(comm_masterLevel!=MPI_COMM_NULL) { preAlps_ECGIterate(ecg, &rci_request); } //Broadcast rci_request to the local group MPI_Bcast(&rci_request, 1, MPI_INT, local_root, comm_localLevel); if (rci_request == 0) { //Compute AP = A*P if(comm_masterLevel!=MPI_COMM_NULL){ preAlps_BlockOperator(ecg->P, ecg->AP); } } else if (rci_request == 1) { if(comm_masterLevel!=MPI_COMM_NULL) { preAlps_ECGStoppingCriterion(ecg, &stop); } //Broadcast stop to the local group MPI_Bcast(&stop, 1, MPI_INT, local_root, comm_localLevel); if (stop == 1) break; //Apply the preconditioner preAlps_PreconditionerMatApply(precond, AX, AY); } if(monitorResidual && my_rank==root) printf("Iteration: %d, \tres: %e\n", ecg->iter, ecg->res); } // Retrieve solution and free memory if(comm_masterLevel!=MPI_COMM_NULL){ preAlps_ECGFinalize(ecg, sol); } return ierr; } static void testLorasc_showHelp(){ printf(" Purpose\n"); printf(" =======\n"); printf(" Preconditioner based on Schur complement, \n"); printf(" more details...\n"); printf("\n"); printf(" Usage\n"); printf(" =========\n"); printf(" mpirun -np <nbprocs> ./test_lorasc -m <matrix_file_name> -r <rhs_file_name> -t <ECG_enlargedFactor> -p <preconditioner_num>\n"); printf("\n"); printf(" Arguments\n"); printf(" =========\n"); printf(" -m/-mat: the matrix file\n"); printf(" the matrix stored in matrix market format\n"); printf(" -r/-rhs: the right hand side file\n"); printf(" the right hand side stored in a text file\n"); printf(" -t: the enlarged factor (default :1)\n"); printf(" -npLevel1: the number of processors at the first level if greater then 0 (default : 0 = <all processors>)\n"); printf(" -p/-prec: preconditioner \n"); printf(" 0: no prec, 1: blockJacobi, 2: Lorasc\n"); } /* * Main program * */ int main(int argc, char** argv){ MPI_Comm comm, commMultilevel[3]; int nbprocs, my_rank, root = 0; int npLevel1 = 0; //For multilevel algorithms, the number of processors at the first level int i, ierr = 0; char matrix_filename[150]="", rhs_filename[150]=""; CPLM_Mat_CSR_t A = CPLM_MatCSRNULL(), AOrigin = CPLM_MatCSRNULL(); CPLM_Mat_CSR_t locAP = CPLM_MatCSRNULL(); double *R = NULL, *C = NULL; //For the scaling double *b = NULL, *rhs = NULL, *sol = NULL, *x = NULL, *rhsOrigin = NULL; int m = 0, n, nnz, rhs_size = 0; double ttemp, tPartition =0.0, tPrec = 0.0, tSolve = 0.0, tTotal; //Partitioning and permutation vectors int *partBegin = NULL, *partCount = NULL, *perm = NULL; // Required by block Jacobi int* rowPos = NULL; int* colPos = NULL; int sizeRowPos, sizeColPos; // Generic preconditioner type and object Prec_Type_t precond_type = PREALPS_LORASC; //PREALPS_NOPREC, PREALPS_BLOCKJACOBI PreAlps_preconditioner_t *precond = NULL; // Lorasc preconditioner preAlps_Lorasc_t *lorascA = NULL; // Program default parameters int doScale = 1, monitorResidual = 0, doSolutionCheck = 1; int precond_num = 2; /* 0: no prec, 1: blockJacobi, 2: Lorasc */ int ecg_enlargedFactor = 1, ecg_maxIter = 60000; int ecg_ortho_alg = ORTHOMIN; double ecg_tol = 1e-5; // Start MPI MPI_Init(&argc, &argv); MPI_Comm_dup(MPI_COMM_WORLD, &comm); // Let me know who I am MPI_Comm_size(comm, &nbprocs); MPI_Comm_rank(comm, &my_rank); #ifdef DEBUG printf("I am proc %d over %d processors\n", my_rank, nbprocs); #endif // Get user parameters for(i=1;i<argc;i+=2){ if ((strcmp(argv[i], "-m") == 0)||(strcmp(argv[i], "-mat") == 0)) strcpy(matrix_filename, argv[i+1]); if ((strcmp(argv[i], "-r") == 0)||(strcmp(argv[i], "-rhs") == 0)) strcpy(rhs_filename, argv[i+1]); if ((strcmp(argv[i], "-p") == 0)||(strcmp(argv[i], "-prec") == 0)) precond_num = atoi(argv[i+1]); if (strcmp(argv[i], "-t") == 0) ecg_enlargedFactor = atoi(argv[i+1]); if (strcmp(argv[i], "-npLevel1") == 0) npLevel1 = atoi(argv[i+1]); if ((strcmp(argv[i], "-h") == 0)||(strcmp(argv[i], "-help") == 0)){ if(my_rank==0){ testLorasc_showHelp(); } MPI_Finalize(); return EXIT_SUCCESS; } } switch(precond_num){ case 0: precond_type = PREALPS_NOPREC; break; case 1: precond_type = PREALPS_BLOCKJACOBI; break; case 2: precond_type = PREALPS_LORASC; break; } // Check args if(npLevel1<=0 || npLevel1>nbprocs) npLevel1 = nbprocs; testLorasc_checkArgs(comm, precond_num, precond_type, npLevel1); if(strlen(matrix_filename)==0 && my_rank==0){ preAlps_abort("Error: unknown Matrix. ./test_lorasc -h for usage"); } // Print Summary if(my_rank==0){ printf("Matrix name: %s\nEnlarged factor: %d\n", matrix_filename, ecg_enlargedFactor); printf("nbprocs: %d, nbprocs Level 1: %d\n", nbprocs, npLevel1); switch(precond_type){ case PREALPS_NOPREC: printf("Preconditioner: NONE\n"); break; case PREALPS_BLOCKJACOBI: printf("Preconditioner: BLOCKJACOBI\n"); break; case PREALPS_LORASC: printf("Preconditioner: LORASC\n"); break; default: preAlps_abort("Precondioner: Unknown\n"); break; } } // Create a multilevel communicator based on the number of processors provided for level 1 preAlps_comm2LevelsSplit(comm, npLevel1, commMultilevel); // Get the communicator at the master level MPI_Comm comm_masterLevel = commMultilevel[1]; // Load the matrix using MatrixMarket or PETSc format depending on the file extension on proc 0 if(my_rank==root){ printf("Reading the matrix ...\n"); CPLM_LoadMatrix(matrix_filename, &A); if(doSolutionCheck){ //Save the matrix for the solution check CPLM_MatCSRCopy(&A, &AOrigin); } CPLM_MatCSRPrintInfo(&A); CPLM_MatCSRPrintCoords(&A, "Loaded matrix"); } // Load the Right-hand side on proc 0 if(my_rank==root){ if(strlen(rhs_filename)==0){ if ( !(rhs = (double *) malloc(A.info.m*sizeof(double))) ) preAlps_abort("Malloc fails for rhs[]."); /* // rhs not provided, generate x and compute rhs = Ax double *xTmp; xTmp = (double*) malloc(A.info.m*sizeof(double)); for (int k = 0 ; k < A.info.m ; k++) xTmp [k] = 1.0; CPLM_MatCSRMatrixVector(&A, 1.0, xTmp, 0.0, rhs); free(xTmp); */ // Generate a random vector srand(11); for(int i=0;i<A.info.m;i++) rhs[i] = ((double) rand() / (double) RAND_MAX); }else{ // Read rhs on proc 0 preAlps_doubleVector_load(rhs_filename, &rhs, &rhs_size); if(rhs_size!=A.info.m){ preAlps_abort("Error: the matrix and rhs size does not match. Matrix size: %d x %d, rhs size: %d", A.info.m, A.info.n, rhs_size); } } if(doSolutionCheck){ rhsOrigin = (double*) malloc(A.info.m*sizeof(double)); for (int k = 0 ; k < A.info.m ; k++) rhsOrigin [k] = rhs[k]; } } // Scale the matrix and the rhs if(doScale && my_rank==0){ if ( !(R = (double *) malloc(A.info.m * sizeof(double))) ) preAlps_abort("Malloc fails for R[]."); if ( !(C = (double *) malloc(A.info.n * sizeof(double))) ) preAlps_abort("Malloc fails for C[]."); CPLM_MatCSRSymRACScaling(&A, R, C); #ifdef BUILDING_MATRICES_DUMP printf("Dumping the matrix ...\n"); CPLM_MatCSRSave(&A, "dump_AScaled.mtx"); printf("Dumping the matrix ... done\n"); #endif CPLM_MatCSRPrintCoords(&A, "Scaled matrix"); //Apply the Scaling factor on the rhs if(R) preAlps_doubleVector_pointWiseProductInPlace(R, rhs, A.info.m); } // Broadcast the global matrix dimension from the root to the other procs in the master level if(comm_masterLevel!=MPI_COMM_NULL){ CPLM_MatCSRDimensions_Bcast(&A, root, &m, &n, &nnz, comm_masterLevel); } // Allocate memory if(comm_masterLevel!=MPI_COMM_NULL){ if ( !(perm = (int *) malloc(m*sizeof(int))) ) preAlps_abort("Malloc fails for perm[]."); } // Build the selected preconditionner if(precond_type==PREALPS_LORASC){ ttemp = MPI_Wtime(); // Memory allocation for lorasc preconditioner ierr = preAlps_LorascAlloc(&lorascA); preAlps_checkError(ierr); // Set parameters for the preconditioners lorascA->deflation_tol = 1e-2;//5e-3 // Change the nrhs before building lorasc (required for analysis by internal solvers such as MUMPS ) lorascA->nrhs = ecg_enlargedFactor; // Build the preconditioner and distribute the matrix ierr = preAlps_LorascBuild(lorascA, commMultilevel, &A, &locAP, &partCount, &partBegin, perm); preAlps_checkError(ierr); if(my_rank==root) printf("Schur-complement size: %d\n", lorascA->sep_nrows); tPartition = lorascA->tPartition; tPrec = MPI_Wtime() - ttemp - lorascA->tPartition; }else{ //Permute the matrix using the same partitioning as lorasc ttemp = MPI_Wtime(); if(comm_masterLevel!=MPI_COMM_NULL){ preAlps_blockArrowStructPartitioning(comm_masterLevel, &A, &locAP, &partCount, &partBegin, perm); } tPartition = MPI_Wtime() - ttemp; } // Prepare the operator if(comm_masterLevel!=MPI_COMM_NULL){ preAlps_OperatorBuildNoPerm(&locAP, partBegin, 1, comm_masterLevel); } // Prepare the selected preconditioner if(precond_type==PREALPS_NOPREC){ // Create a generic preconditioner object compatible with EcgSolver preAlps_PreconditionerCreate(&precond, precond_type, NULL); } else if(precond_type==PREALPS_BLOCKJACOBI){ ttemp = MPI_Wtime(); // Get row partitioning of A from the operator preAlps_OperatorGetRowPosPtr(&rowPos,&sizeRowPos); // Get col partitioning induced by this row partitioning preAlps_OperatorGetColPosPtr(&colPos,&sizeColPos); // Construct the preconditioner preAlps_BlockJacobiCreate(&locAP, rowPos, sizeRowPos, colPos, sizeColPos); tPrec = MPI_Wtime() - ttemp; // Create a generic preconditioner object compatible with EcgSolver preAlps_PreconditionerCreate(&precond, precond_type, NULL); }else if(precond_type==PREALPS_LORASC){ // Create a generic preconditioner object compatible with EcgSolver preAlps_PreconditionerCreate(&precond, precond_type, (void *) lorascA); } //Permute and distribute the right hand side if(comm_masterLevel!=MPI_COMM_NULL){ if ( !(b = (double *) malloc(m*sizeof(double))) ) preAlps_abort("Malloc fails for b[]."); if(my_rank==root){ //Apply the permutation on the right hand side preAlps_doubleVector_permute(perm, rhs, b, m); } //Distribute the rhs MPI_Scatterv(b, partCount, partBegin, MPI_DOUBLE, my_rank==0?MPI_IN_PLACE:b, locAP.info.m, MPI_DOUBLE, root, comm_masterLevel); preAlps_doubleVector_printSynchronized(b, locAP.info.m, "b after the distribution", "b", comm_masterLevel); } /* Solve the system */ preAlps_ECG_t ecg; // Set parameters ecg.comm = comm_masterLevel; /* MPI Communicator */ ecg.globPbSize = m; /* Size of the global problem */ ecg.locPbSize = locAP.info.m; /* Size of the local problem */ ecg.maxIter = ecg_maxIter; /* Maximum number of iterations */ ecg.enlFac = ecg_enlargedFactor;/* Enlarging factor */ ecg.tol = ecg_tol; /* Tolerance of the method */ ecg.ortho_alg = ecg_ortho_alg; /* Orthogonalization algorithm */ ecg.bs_red = NO_BS_RED; /* Reduction of the search directions */ sol = (double*) malloc(locAP.info.m*sizeof(double)); ttemp = MPI_Wtime(); //Solve the system testLorasc_ECGSolve(&ecg, precond, commMultilevel, b, sol, monitorResidual); // Post process the solution if(comm_masterLevel!=MPI_COMM_NULL){ preAlps_doubleVector_printSynchronized(sol, locAP.info.m, "sol", "solution", comm_masterLevel); // Gather the solution on proc 0 if(my_rank==0) x = (double*) malloc(m*sizeof(double)); MPI_Gatherv(sol, locAP.info.m, MPI_DOUBLE, x, partCount, partBegin, MPI_DOUBLE, root, comm_masterLevel); // Post process the solution if(my_rank==0) { double *xTmp; xTmp = (double*) malloc(m*sizeof(double)); preAlps_doubleVector_invpermute(perm, x, xTmp, m); //Apply the Scaling factor on the solution if(C) preAlps_doubleVector_pointWiseProduct(C, xTmp, x, m); preAlps_doubleVector_printSynchronized(x, m, "final solution", "xTmp", MPI_COMM_SELF); free(xTmp); } if (my_rank == 0) printf("=== ECG ===\n\tSolver iterations: %d\n\tnorm(res): %e\n",ecg.iter,ecg.res); } tSolve = MPI_Wtime() - ttemp; //tTotal = tPartition + tPrec + tSolve; tTotal = tPrec + tSolve; //the partitioning time is excluded // Check the solution if(doSolutionCheck && my_rank==0){ double *rTmp, normRes, normRhs; rTmp = (double*) malloc(m*sizeof(double)); for (int k = 0 ; k < m ; k++) rTmp [ k] = rhsOrigin [k] ; // compute Ax-b CPLM_MatCSRMatrixVector(&AOrigin, 1.0, x, -1.0, rTmp); preAlps_doubleVector_printSynchronized(rTmp, m, "err=b-AX", "err", MPI_COMM_SELF); normRes = preAlps_doubleVector_norm2(rTmp, m); normRhs = preAlps_doubleVector_norm2(rhsOrigin, m); printf("norm (b-Ax)/norm(b): %e\n", normRes/normRhs); free(rTmp); } //Display stats if(comm_masterLevel!=MPI_COMM_NULL){ preAlps_dstats_display(comm_masterLevel, tPartition, "Time partitioning"); preAlps_dstats_display(comm_masterLevel, tPrec, "Time preconditioner"); preAlps_dstats_display(comm_masterLevel, tSolve, "Time Solve"); preAlps_dstats_display(comm_masterLevel, tTotal, "Time Total"); } // Clean up preAlps_OperatorFree(); // Destroy the preconditioner/the partitioning if(precond_type==PREALPS_BLOCKJACOBI){ preAlps_BlockJacobiFree(); } else if(precond_type==PREALPS_LORASC){ ierr = preAlps_LorascDestroy(&lorascA); preAlps_checkError(ierr); } // Destroy the generic preconditioner object if(comm_masterLevel!=MPI_COMM_NULL){ preAlps_PreconditionerDestroy(&precond); } // Free memory if(partBegin) free(partBegin); if(partCount) free(partCount); if(perm) free(perm); if(b) free(b); if(rhs) free(rhs); if(sol) free(sol); if(x) free(x); CPLM_MatCSRFree(&locAP); if(my_rank==0){ CPLM_MatCSRFree(&A); CPLM_MatCSRFree(&AOrigin); if(rhsOrigin) free(rhsOrigin); if(R) free(R); if(C) free(C); } MPI_Finalize(); return EXIT_SUCCESS; }
30.629234
158
0.653669
ffbe44316f25a620ebccd8df44a1303787f0d59a
671
h
C
csgo-crow/AntiCheatServer/NoCheatZ/server-plugin/SourceSdk/Interfaces/interface.h
im6705/csgo_full
6c50221c5b6441ebf689e3a1cb4978510fab0b27
[ "Apache-2.0" ]
null
null
null
csgo-crow/AntiCheatServer/NoCheatZ/server-plugin/SourceSdk/Interfaces/interface.h
im6705/csgo_full
6c50221c5b6441ebf689e3a1cb4978510fab0b27
[ "Apache-2.0" ]
null
null
null
csgo-crow/AntiCheatServer/NoCheatZ/server-plugin/SourceSdk/Interfaces/interface.h
im6705/csgo_full
6c50221c5b6441ebf689e3a1cb4978510fab0b27
[ "Apache-2.0" ]
null
null
null
#ifndef INTERFACE_H #define INTERFACE_H #include "SdkPreprocessors.h" namespace SourceSdk { typedef void* (*CreateInterfaceFn)(const char *pName, int *pReturnCode); typedef void* (*InstantiateInterfaceFn)(); class IBaseInterface { public: virtual ~IBaseInterface() {} }; class InterfaceReg { public: InterfaceReg(InstantiateInterfaceFn fn, const char *pName); public: InstantiateInterfaceFn m_CreateFn; const char *m_pName; InterfaceReg *m_pNext; static InterfaceReg *s_pInterfaceRegs; }; class CSysModule; enum { IFACE_OK = 0, IFACE_FAILED }; DLL_EXPORT void* CreateInterface(const char *pName, int *pReturnCode); }; #endif
17.205128
73
0.734724
ffc1ca28243e5d15a6c226512550b7f74ebd2504
1,613
h
C
Common/Mover.h
Johannes-Schneider/ATools
7805d67fa8a90146d675d8ded3ec2882e25492c6
[ "Unlicense" ]
3
2020-07-17T02:32:00.000Z
2021-06-18T21:26:02.000Z
Common/Mover.h
Johannes-Schneider/ATools
7805d67fa8a90146d675d8ded3ec2882e25492c6
[ "Unlicense" ]
null
null
null
Common/Mover.h
Johannes-Schneider/ATools
7805d67fa8a90146d675d8ded3ec2882e25492c6
[ "Unlicense" ]
8
2020-05-05T16:35:17.000Z
2022-02-08T14:20:52.000Z
/////////// // This file is a part of the ATools project // Some parts of code are the property of Microsoft, Qt or Aeonsoft // The rest is released without license and without any warranty /////////// #ifndef MOVER_H #define MOVER_H #include "SpawnObject.h" #define PARTSMESH_HAIR( sex ) ( sex == SEX_MALE ? ( "Part_maleHair%02d.o3d" ) : ( "Part_femaleHair%02d.o3d" ) ) #define PARTSMESH_HEAD( sex ) ( sex == SEX_MALE ? ( "Part_maleHead%02d.o3d" ) : ( "Part_femaleHead%02d.o3d" ) ) #define PARTSMESH_UPPER( sex ) ( sex == SEX_MALE ? ( "Part_maleUpper.o3d" ) : ( "Part_femaleUpper.o3d" ) ) #define PARTSMESH_LOWER( sex ) ( sex == SEX_MALE ? ( "Part_maleLower.o3d" ) : ( "Part_femaleLower.o3d" ) ) #define PARTSMESH_HAND( sex ) ( sex == SEX_MALE ? ( "Part_maleHand.o3d" ) : ( "Part_femaleHand.o3d" ) ) #define PARTSMESH_FOOT( sex ) ( sex == SEX_MALE ? ( "Part_maleFoot.o3d" ) : ( "Part_femaleFoot.o3d" ) ) struct MoverProp; struct Character; class CMover : public CSpawnObject { public: CMover(); virtual void Read(CFile& file); virtual void Write(CFile& file, const D3DXVECTOR3& posOffset); virtual bool Init(); virtual void RenderName(); virtual DWORD GetRectColor() { return 0xffff0000; } bool IsPeaceful() const; void InitProperties(); protected: uint m_motion; uint m_AIInterface; string m_name; string m_characterKey; uint m_belligerence; MoverProp* m_moverProp; Character* m_character; virtual void _loadModel(); friend class CObject; friend class CWorld; #ifdef WORLD_EDITOR WORLD_EDITOR_FRIENDS #endif // WORLD_EDITOR }; #endif // MOVER_H
27.810345
112
0.691878
ffc3fef1b486d3c428884f471129779478b23f19
1,608
h
C
SimSpark/spark/lib/oxygen/physicsserver/body.h
IllyasvielEin/Robocup3dInstaller
12e91d9372dd08a92feebf98e916c98bc2242ff4
[ "MIT" ]
null
null
null
SimSpark/spark/lib/oxygen/physicsserver/body.h
IllyasvielEin/Robocup3dInstaller
12e91d9372dd08a92feebf98e916c98bc2242ff4
[ "MIT" ]
null
null
null
SimSpark/spark/lib/oxygen/physicsserver/body.h
IllyasvielEin/Robocup3dInstaller
12e91d9372dd08a92feebf98e916c98bc2242ff4
[ "MIT" ]
null
null
null
/* -*- mode: c++; c-basic-offset: 4; indent-tabs-mode: nil -*- this file is part of rcssserver3D Fri May 9 2003 Copyright (C) 2002,2003 Koblenz University Copyright (C) 2003 RoboCup Soccer Server 3D Maintenance Group $Id$ This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #ifndef OXYGEN_BODY_H #define OXYGEN_BODY_H #include <oxygen/physicsserver/physicsobject.h> namespace oxygen { class BodyInt; /** This is currently a placeholder class to comply with the inheritance tree. Once a Body class other than RigidBody has been implemented, common functionality should be moved to this common base class to reduce the amount of redundant code. */ class OXYGEN_API Body : public PhysicsObject { public: Body(); virtual ~Body(); virtual void OnLink(); protected: long mBodyID; bool mMassTransformed; salt::Vector3f mMassTrans; private: static boost::shared_ptr<BodyInt> mBodyImp; }; DECLARE_CLASS(Body); } //namespace oxygen #endif //OXYGEN_BODY_H
27.724138
71
0.737562
ffc44c9d1722998a927f5b520db4c08b720f6bdd
2,153
c
C
test/test_rnn_bptt_perf.c
jamesljlster/ann
44f157d21ba878cd4717ab6abae95ef254e544a9
[ "MIT" ]
null
null
null
test/test_rnn_bptt_perf.c
jamesljlster/ann
44f157d21ba878cd4717ab6abae95ef254e544a9
[ "MIT" ]
null
null
null
test/test_rnn_bptt_perf.c
jamesljlster/ann
44f157d21ba878cd4717ab6abae95ef254e544a9
[ "MIT" ]
null
null
null
#include <stdio.h> #include <stdlib.h> #include <time.h> #include <ann.h> #define INPUTS 1 #define OUTPUTS 1 int main(int argc, char* argv[]) { int i; int iResult; int hiddenSize, iter; float input = 0, err = 0; clock_t timeHold; ann_config_t cfg; ann_t ann; // Parse argument if (argc < 3) { printf("Usage: test_rnn_bptt_perf <hidden_size> <iteration>\n"); return -1; } hiddenSize = atoi(argv[1]); iter = atoi(argv[2]); // Create config iResult = ann_config_create(&cfg); if (iResult != ANN_NO_ERROR) { printf("ann_config_create() failed with error: %d\n", iResult); return -1; } ann_config_set_inputs(cfg, INPUTS); ann_config_set_outputs(cfg, OUTPUTS); ann_config_set_transfer_func(cfg, ANN_SIGMOID); ann_config_set_learning_rate(cfg, 0.01); ann_config_set_momentum_coef(cfg, 0.1); iResult = ann_config_set_hidden_layers(cfg, 1); if (iResult != ANN_NO_ERROR) { printf("ann_config_set_hidden_layers() failed with error: %d\n", iResult); return -1; } iResult = ann_config_set_hidden_nodes(cfg, 0, hiddenSize); if (iResult != ANN_NO_ERROR) { printf("ann_config_set_nodes() failed with error: %d\n", iResult); return -1; } // Create neural network iResult = ann_create(&ann, cfg); if (iResult != ANN_NO_ERROR) { printf("ann_create() failed with error: %d\n", iResult); return -1; } // Set time step iResult = rnn_bptt_set_max_timestep(ann, 1); if (iResult != ANN_NO_ERROR) { printf("rnn_set_max_timestep() failed with error: %d\n", iResult); return -1; } // Test performance timeHold = clock(); for (i = 0; i < iter; i++) { rnn_bptt_sum_gradient(ann, &err); rnn_bptt_erase(ann); } timeHold = clock() - timeHold; printf("Summary:\n"); printf(" Hidden Size: %d\n", hiddenSize); printf(" BP Iteration: %d\n", iter); printf(" Time Cost: %lf\n", (float)timeHold / (float)CLOCKS_PER_SEC); return 0; }
23.150538
76
0.598235
ffc4971aaf0fe10f6f81544ce6aaf2dc514e8ea8
653
h
C
Game/BattleLogic/TW_LogicBase.h
TaoReiches/Tao
bf54cdf5284d3a6fd7b2e8aec0bc26fa96442a01
[ "Apache-2.0" ]
2
2020-09-30T15:17:32.000Z
2021-02-22T14:19:54.000Z
Game/BattleLogic/TW_LogicBase.h
TaoReiches/Tao
bf54cdf5284d3a6fd7b2e8aec0bc26fa96442a01
[ "Apache-2.0" ]
null
null
null
Game/BattleLogic/TW_LogicBase.h
TaoReiches/Tao
bf54cdf5284d3a6fd7b2e8aec0bc26fa96442a01
[ "Apache-2.0" ]
null
null
null
#pragma once /********************************************** * Author: Tao Wang Copyright reserved * Contact: tao.reiches@gmail.com **********************************************/ #include <memory> class TwMain; class TwUnit; class TwMainPtr { public: TwMainPtr(void) :pkAttachMain(nullptr) { } void AttachMain(std::shared_ptr<TwMain> pkMain) { pkAttachMain = pkMain; } std::shared_ptr<TwMain> pkAttachMain; }; class TwUnitPtr { public: TwUnitPtr(void) :pAttachUnit(nullptr) { } void AttachUnit(std::shared_ptr<TwUnit> pkUnit) { pAttachUnit = pkUnit; } std::shared_ptr<TwUnit> pAttachUnit; };
15.547619
51
0.577335
ffc649d8323c362c72a26a8884b42e035e31e6fe
1,126
h
C
Classes/ObjectiveNeedish/NeedishNeed.h
sagmor/feelingneedish
b0936e86efa91a70eb68ec6f144a35164dd7ce56
[ "AFL-2.1" ]
1
2015-11-05T08:54:31.000Z
2015-11-05T08:54:31.000Z
Classes/ObjectiveNeedish/NeedishNeed.h
sagmor/feelingneedish
b0936e86efa91a70eb68ec6f144a35164dd7ce56
[ "AFL-2.1" ]
null
null
null
Classes/ObjectiveNeedish/NeedishNeed.h
sagmor/feelingneedish
b0936e86efa91a70eb68ec6f144a35164dd7ce56
[ "AFL-2.1" ]
null
null
null
// // NeedishNeed.h // Feeling Needish // // Created by Sebastian Gamboa on 25-09-08. // Copyright 2008 SagMor. All rights reserved. // #import <Foundation/Foundation.h> #import "NeedishObject.h" @class NeedishUser; typedef enum NeedishNeedStatus { local, active, unknown } NeedishNeedStatus; @interface NeedishNeed : NeedishObject { NSInteger _needId; NSString *_subject; NSString *_text; NSString *_city; NeedishNeedStatus _status; NSInteger _helpsCount; NSInteger _created; NSInteger _timediff; NeedishUser *_owner; NSArray *_helps; } @property (nonatomic, readonly) NSInteger needId; @property (nonatomic, copy) NSString *subject; @property (nonatomic, copy) NSString *text; @property (nonatomic, copy) NSString *city; @property (nonatomic, readonly) NeedishNeedStatus status; @property (nonatomic, readonly) NSInteger helpsCount; @property (nonatomic, readonly) NSInteger created; @property (nonatomic, readonly) NSInteger timediff; @property (nonatomic, retain) NeedishUser *owner; + (NeedishNeed *)mock; + (NSArray *)arrayOfMocks; @end
20.472727
57
0.722025
ffc678f6b2f1dc5169351db9bd1498f45cbf55c7
10,013
c
C
ex_10/prog.c
kaito1002/AI
7d978e0c86f3c98ba48f117fb1e92c5ef597f92f
[ "MIT" ]
null
null
null
ex_10/prog.c
kaito1002/AI
7d978e0c86f3c98ba48f117fb1e92c5ef597f92f
[ "MIT" ]
null
null
null
ex_10/prog.c
kaito1002/AI
7d978e0c86f3c98ba48f117fb1e92c5ef597f92f
[ "MIT" ]
null
null
null
/** * @file prog.c * @date 2016/11/15 * @author Yuta Kobiyama (m5191140@u-aizu.ac.jp) * @brief k-means algorithm. * @details * Artificial Intelligence, 11th Exercise\n * Copyright (C) 2016 System Intelligence Laboratory, All Rights Reserved * * - Assignment: * - Fill in all blank parts of codes to work. * * - Input: * - K: The number of clusters in dataset. * - M: The number of feature vectors. * - N: The dimension of feature vectors. * - D_ij: jth element of ith feature vector. * - L_i: The label of ith feature vector. * * [K] [M] [N] * [D_11, D_12, ... D_1N] [L_1] * ... * [D_M1, D_M2, ... D_MN] [L_M] */ #include "prog.h" #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> /** * @struct kmeans_pack * @brief This struct defines a k-means data package. */ struct kmeans_pack { size_t cluster_count; //!< The number of clusters. Dataset* src_dataset; //!< The original input data. size_t* predicted_labels; //!< The predicted labels of the vectors by k-means. FeatureVector* reference_patterns; //!< The reference patterns. CrossValidationDataset cv_dataset; //!< The cross-validation dataset. }; typedef struct kmeans_pack KmeansPack; static bool initialize(KmeansPack*); static void finalize(KmeansPack*); static Dataset* alloc_dataset(size_t, size_t); static void free_dataset(Dataset*); static void shuffle_dataset(Dataset*); static void derive_ith_cross_validation_dataset(CrossValidationDataset*, size_t, Dataset const*); int main(void) { KmeansPack kmeans_pack; while (initialize(&kmeans_pack) == true) { double accuracies[FOLD_COUNT]; double accuracies_sum = 0.0; CrossValidationDataset* cv_dataset = &kmeans_pack.cv_dataset; // Iterate the all combinations of the cross-validation. for (size_t i = 0; i < FOLD_COUNT; i++) { derive_ith_cross_validation_dataset(cv_dataset, i, kmeans_pack.src_dataset); Dataset const* train_dataset = cv_dataset->train_dataset; Dataset const* test_dataset = cv_dataset->test_dataset; size_t* predicted_labels = kmeans_pack.predicted_labels; FeatureVector* reference_patterns = kmeans_pack.reference_patterns; size_t cluster_count = kmeans_pack.cluster_count; do_kmeans(train_dataset, predicted_labels, reference_patterns, cluster_count); adjust_labels(train_dataset, predicted_labels, reference_patterns, cluster_count); accuracies[i] = validate(test_dataset, predicted_labels, reference_patterns, cluster_count); printf("%zd-th Test\n", i); printf(" Accuracy: %.3lf\n", accuracies[i]); accuracies_sum += accuracies[i]; } double mean = accuracies_sum / FOLD_COUNT; double var = 0.0; for (size_t i = 0; i < FOLD_COUNT; i++) { double t = accuracies[i] - mean; var += t * t; } var /= FOLD_COUNT; printf("\n%d-fold cross-validation result.\n", FOLD_COUNT); printf("Mean: %.3lf\n", mean); printf("Variant: %.3lf\n", var); finalize(&kmeans_pack); } return 0; } /** * @brief Initialize data structs for k-means. * @param kmeans_pack The pointer to the given data structs. */ static bool initialize(KmeansPack* kmeans_pack) { size_t cluster_count; size_t feature_count; size_t feature_dimension; if (scanf("%zu %zu %zu", &cluster_count, &feature_count, &feature_dimension) != 3) { return false; } kmeans_pack->cluster_count = cluster_count; // Allocate memory regions for the input dataset. Dataset* src_dataset = alloc_dataset(feature_count, feature_dimension); // Load dataset from the input. for (size_t i = 0; i < src_dataset->feature_count; i++) { for (size_t j = 0; j < src_dataset->feature_dimension; j++) { scanf("%lf", &src_dataset->features[i].elements[j]); } scanf("%zu", &src_dataset->features[i].label); } // Shuffle dataset for cross-validation. shuffle_dataset(src_dataset); kmeans_pack->src_dataset = src_dataset; // Initialize cross-validation dataset. CrossValidationDataset* cv_dataset = &kmeans_pack->cv_dataset; cv_dataset->fold_count = FOLD_COUNT; cv_dataset->test_dataset = NULL; cv_dataset->train_dataset = NULL; // Allocate memory regions for the reference patterns. FeatureVector* reference_patterns = malloc(sizeof(FeatureVector) * kmeans_pack->cluster_count); for (size_t i = 0; i < kmeans_pack->cluster_count; i++) { reference_patterns[i].elements = malloc(src_dataset->feature_dimension * sizeof(double)); } kmeans_pack->reference_patterns = reference_patterns; // Allocate memory regions for the predicted labels. kmeans_pack->predicted_labels = malloc(sizeof(size_t) * src_dataset->feature_count); memset(kmeans_pack->predicted_labels, 0, sizeof(size_t) * src_dataset->feature_count); return true; } /** * @brief Deallocate the all memory regions used for k-means. * @param kmeans_pack The pointer to the given data structs. */ static void finalize(KmeansPack* kmeans_pack) { free(kmeans_pack->predicted_labels); for (size_t i = 0; i < kmeans_pack->cluster_count; i++) { free(kmeans_pack->reference_patterns[i].elements); } free(kmeans_pack->reference_patterns); free_dataset(kmeans_pack->src_dataset); free_dataset(kmeans_pack->cv_dataset.test_dataset); free_dataset(kmeans_pack->cv_dataset.train_dataset); } /** * @brief Allocate dataset struct and its members. * @param feature_dimension The dimension of the feature vector. * @param feature_count The number of the feature vectors. * @return The pointer to the allocated dataset. */ static Dataset* alloc_dataset(size_t feature_count, size_t feature_dimension) { Dataset* dataset = malloc(sizeof(Dataset)); dataset->feature_count = feature_count; dataset->feature_dimension = feature_dimension; dataset->features = malloc(feature_count * sizeof(FeatureVector)); for (size_t i = 0; i < dataset->feature_count; i++) { dataset->features[i].elements = malloc(feature_dimension * sizeof(double)); } return dataset; } /** * @brief Deallocate the dataset. * @param dataset The pointer to the given dataset. */ static void free_dataset(Dataset* dataset) { if (dataset == NULL) { return; } for (size_t i = 0; i < dataset->feature_count; i++) { free(dataset->features[i].elements); } free(dataset->features); free(dataset); } /** * @brief Shuffle the feature vectors in the given dataset randomly. * @param dataset The pointer to the given dataset. */ static void shuffle_dataset(Dataset* dataset) { // Shuffle feature vectors for cross validation. size_t feature_count = dataset->feature_count; for (size_t i = 0; i < feature_count; i++) { size_t index1 = rand_xorshift() % feature_count; size_t index2 = rand_xorshift() % feature_count; // Swap. FeatureVector tmp = dataset->features[index1]; dataset->features[index1] = dataset->features[index2]; dataset->features[index2] = tmp; } } /** * @brief Generate k-fold cross valudation dataset based on `current_fold` value. * @param cv_dataset The pointer to the given cross validation dataset. * @param current_fold The currenc fold index. * @param src_dataset The pointer to the given source dataset. */ static void derive_ith_cross_validation_dataset(CrossValidationDataset* cv_dataset, size_t current_fold, Dataset const* src_dataset) { size_t test_feature_count = src_dataset->feature_count / cv_dataset->fold_count; size_t train_feature_count = src_dataset->feature_count - test_feature_count; size_t test_index_begin = current_fold * test_feature_count; size_t test_index_end = test_index_begin + test_feature_count; Dataset* test_dataset = alloc_dataset(test_feature_count, src_dataset->feature_dimension); test_dataset->feature_count = test_feature_count; test_dataset->feature_dimension = src_dataset->feature_dimension; size_t count = 0; for (size_t i = test_index_begin; i < test_index_end; i++) { memcpy(test_dataset->features[count].elements, src_dataset->features[i].elements, sizeof(double) * src_dataset->feature_dimension); test_dataset->features[count].label = src_dataset->features[i].label; count++; } // Free the previous dataset because the number of vectors in the dataset is not always the same. free_dataset(cv_dataset->test_dataset); cv_dataset->test_dataset = test_dataset; Dataset* train_dataset = alloc_dataset(train_feature_count, src_dataset->feature_dimension); train_dataset->feature_count = train_feature_count; train_dataset->feature_dimension = src_dataset->feature_dimension; count = 0; for (size_t i = 0; i < test_index_begin; i++) { memcpy(train_dataset->features[count].elements, src_dataset->features[i].elements, sizeof(double) * src_dataset->feature_dimension); train_dataset->features[count].label = src_dataset->features[i].label; count++; } for (size_t i = test_index_end; i < src_dataset->feature_count; i++) { memcpy(train_dataset->features[count].elements, src_dataset->features[i].elements, sizeof(double) * src_dataset->feature_dimension); train_dataset->features[count].label = src_dataset->features[i].label; count++; } // Free the previous dataset because the number of vectors in the dataset is not always the same. free_dataset(cv_dataset->train_dataset); cv_dataset->train_dataset = train_dataset; }
35.507092
140
0.679517
ffc72cf07d9860d8ecd7d5c48f9b18d993d8b144
749
h
C
atom/GameObject.h
pixelsquare/space-invaders
a4889273ed5020a49460a39f2b3cab93bf4216a2
[ "MIT" ]
null
null
null
atom/GameObject.h
pixelsquare/space-invaders
a4889273ed5020a49460a39f2b3cab93bf4216a2
[ "MIT" ]
null
null
null
atom/GameObject.h
pixelsquare/space-invaders
a4889273ed5020a49460a39f2b3cab93bf4216a2
[ "MIT" ]
null
null
null
#ifndef __ATOM_ENGINE_GAMEOBJECT_H__ #define __ATOM_ENGINE_GAMEOBJECT_H__ #include "BasicPrimitives.h" using namespace BasicPrimitivesLib::Library; namespace GameObjectLib { namespace Library { class GameObject : public Collision { public: GameObject(); GameObject(Vector3 pos); GameObject(float x, float y, float z); ~GameObject(); void UpdateGameObject(); void DrawPrimitive(const PrimitiveType *primitive); static void Destroy(GameObject instance); void MoveUp(float speed); void MoveDown(float speed); void MoveRight(float speed); void MoveLeft(float speed); void MoveForward(float speed); void MoveBack(float speed); private: const int uid; static int newUID; protected: }; } } #endif
24.16129
62
0.736983
ffc81afd38900e9b811e4b3e938e362e1f1c0637
849
h
C
System/Library/PrivateFrameworks/NeutrinoCore.framework/NUGeometryTransform.h
lechium/iOS1351Headers
6bed3dada5ffc20366b27f7f2300a24a48a6284e
[ "MIT" ]
2
2021-11-02T09:23:27.000Z
2022-03-28T08:21:57.000Z
System/Library/PrivateFrameworks/NeutrinoCore.framework/NUGeometryTransform.h
lechium/iOS1351Headers
6bed3dada5ffc20366b27f7f2300a24a48a6284e
[ "MIT" ]
null
null
null
System/Library/PrivateFrameworks/NeutrinoCore.framework/NUGeometryTransform.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:22:39 PM Mountain Standard Time * Operating System: Version 13.5.1 (Build 17F80) * Image Source: /System/Library/PrivateFrameworks/NeutrinoCore.framework/NeutrinoCore * classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos. Updated by Kevin Bradley. */ #import <NeutrinoCore/NeutrinoCore-Structs.h> @interface NUGeometryTransform : NSObject -(BOOL)isEqual:(id)arg1 ; -(unsigned long long)hash; -(id)description; -(CGPoint)transformPoint:(CGPoint)arg1 ; -(id)inverseTransform; -(SCD_Struct_NU6)transformTime:(SCD_Struct_NU6)arg1 ; -(SCD_Struct_NU27)transformMatrix:(SCD_Struct_NU27)arg1 ; @end
40.428571
130
0.656066
ffcb0aa2cd066def2e0a808e2e7f2486c353ed63
1,017
h
C
include/il2cpp/Dpr/UI/UIContPokeSelect/_OpOpen_d__23.h
martmists-gh/BDSP
d6326c5d3ad9697ea65269ed47aa0b63abac2a0a
[ "MIT" ]
1
2022-01-15T20:20:27.000Z
2022-01-15T20:20:27.000Z
include/il2cpp/Dpr/UI/UIContPokeSelect/_OpOpen_d__23.h
martmists-gh/BDSP
d6326c5d3ad9697ea65269ed47aa0b63abac2a0a
[ "MIT" ]
null
null
null
include/il2cpp/Dpr/UI/UIContPokeSelect/_OpOpen_d__23.h
martmists-gh/BDSP
d6326c5d3ad9697ea65269ed47aa0b63abac2a0a
[ "MIT" ]
null
null
null
#pragma once #include "il2cpp.h" void Dpr_UI_UIContPokeSelect__OpOpen_d__23___ctor (Dpr_UI_UIContPokeSelect__OpOpen_d__23_o* __this, int32_t __1__state, const MethodInfo* method_info); void Dpr_UI_UIContPokeSelect__OpOpen_d__23__System_IDisposable_Dispose (Dpr_UI_UIContPokeSelect__OpOpen_d__23_o* __this, const MethodInfo* method_info); bool Dpr_UI_UIContPokeSelect__OpOpen_d__23__MoveNext (Dpr_UI_UIContPokeSelect__OpOpen_d__23_o* __this, const MethodInfo* method_info); Il2CppObject* Dpr_UI_UIContPokeSelect__OpOpen_d__23__System_Collections_Generic_IEnumerator_System_Object__get_Current (Dpr_UI_UIContPokeSelect__OpOpen_d__23_o* __this, const MethodInfo* method_info); void Dpr_UI_UIContPokeSelect__OpOpen_d__23__System_Collections_IEnumerator_Reset (Dpr_UI_UIContPokeSelect__OpOpen_d__23_o* __this, const MethodInfo* method_info); Il2CppObject* Dpr_UI_UIContPokeSelect__OpOpen_d__23__System_Collections_IEnumerator_get_Current (Dpr_UI_UIContPokeSelect__OpOpen_d__23_o* __this, const MethodInfo* method_info);
92.454545
200
0.907571
ffd20b19f1eac2164d239526628e8a35470fe044
148
h
C
frameworks/libxgame/src/lua-bindings/lua_xml_http_request.h
sishui/lcocos
604e1a3a87065bcaf59e870a95309bfcf2cc1260
[ "MIT" ]
141
2019-07-09T06:29:35.000Z
2022-03-30T06:25:16.000Z
frameworks/libxgame/src/lua-bindings/lua_xml_http_request.h
sishui/lcocos
604e1a3a87065bcaf59e870a95309bfcf2cc1260
[ "MIT" ]
16
2019-12-23T06:53:18.000Z
2021-10-19T17:01:01.000Z
frameworks/libxgame/src/lua-bindings/lua_xml_http_request.h
sishui/lcocos
604e1a3a87065bcaf59e870a95309bfcf2cc1260
[ "MIT" ]
47
2019-08-14T11:12:34.000Z
2022-03-30T06:25:19.000Z
#ifndef __LUA_XML_HTTP_REQUEST_H__ #define __LUA_XML_HTTP_REQUEST_H__ #include "cclua/xlua.h" int luaopen_xml_http_request(lua_State *L); #endif
16.444444
43
0.831081
ffd41f14c43498d53e6c9822ed348128e7daa91d
417
h
C
src/foo_musicbrainz.h
kbuffington/foo_musicbrainz
7b4610803df595f74d8078f4c0f4df3c15997a05
[ "MIT" ]
20
2020-02-16T16:50:07.000Z
2022-01-11T15:14:40.000Z
src/foo_musicbrainz.h
phw/foo_musicbrainz
7b4610803df595f74d8078f4c0f4df3c15997a05
[ "MIT" ]
2
2021-04-21T19:28:57.000Z
2021-09-11T23:58:55.000Z
src/foo_musicbrainz.h
phw/foo_musicbrainz
7b4610803df595f74d8078f4c0f4df3c15997a05
[ "MIT" ]
2
2020-03-11T13:48:40.000Z
2020-09-02T06:20:14.000Z
#pragma once namespace mb { static constexpr const char* component_title = "MusicBrainz Tagger"; static constexpr const char* component_dll_name = "foo_musicbrainz.dll"; static constexpr const char* component_version = "0.4.7"; static constexpr const char* component_info = "Copyright (C) 2009-2012 Dremora\nCopyright (C) 2015-2020 marc2003\nCopyright (C) 2020-2021 Mordred\n\nBuild: " __TIME__ ", " __DATE__; }
41.7
182
0.767386
ffd435854c44978013084e7d43fbd8ff6ff6a1e1
3,044
h
C
include/SpringBoard/SBRecentDisplayItemsController.h
ItHertzSoGood/DragonBuild
1aaf6133ab386ba3a5165a4b29c080ca8d814b52
[ "MIT" ]
3
2020-06-20T02:53:25.000Z
2020-11-07T08:39:13.000Z
include/SpringBoard/SBRecentDisplayItemsController.h
elihwyma/DragonBuild
0891eb72d33d59fc05f8455a8a30ce6eebebddec
[ "MIT" ]
null
null
null
include/SpringBoard/SBRecentDisplayItemsController.h
elihwyma/DragonBuild
0891eb72d33d59fc05f8455a8a30ce6eebebddec
[ "MIT" ]
1
2020-07-26T02:16:06.000Z
2020-07-26T02:16:06.000Z
// // Generated by class-dump 3.5 (64 bit) (Debug version compiled Mar 22 2020 01:47:48). // // Copyright (C) 1997-2019 Steve Nygard. // #import <objc/NSObject.h> #import <SpringBoard/SBMainDisplayWorkspaceAppInteractionEventSourceObserving-Protocol.h> @class NSMutableOrderedSet, NSOrderedSet, NSSet, NSTimer, SBApplicationController, SBHomeGestureSettings; @protocol BSInvalidatable, SBRecentDisplayItemsControllerDelegate; @interface SBRecentDisplayItemsController : NSObject <SBMainDisplayWorkspaceAppInteractionEventSourceObserving> { NSMutableOrderedSet *_recentDisplayItems; long long _removalPersonality; long long _movePersonality; NSSet *_relevantTransitionFromSources; NSUInteger _maxDisplayItems; SBApplicationController *_appController; id <BSInvalidatable> _stateCaptureInvalidatable; NSTimer *_delayAfterTransitionTimer; SBHomeGestureSettings *_homeGestureSettings; id <SBRecentDisplayItemsControllerDelegate> _delegate; } @property(nonatomic) __weak id <SBRecentDisplayItemsControllerDelegate> delegate; // @synthesize delegate=_delegate; // - (void).cxx_destruct; - (id)_addStateCaptureHandler; - (void)_disallowAppFromAppearingWhileHidden:(id)arg1; - (void)_allowAppToAppearWhileHidden:(id)arg1; - (void)_removeDisplayItem:(id)arg1; - (void)_moveDisplayItemToFront:(id)arg1; - (void)_addDisplayItemToFront:(id)arg1; - (void)_addOrMoveDisplayItemToFront:(id)arg1; - (id)_displayItemForLayoutElement:(id)arg1; - (id)_allDisplayItemsPassingTest:(id /* CDUnknownBlockType */)arg1; - (id)_allDisplayItemsForUniqueID:(id)arg1; - (id)_allDisplayItemsForBundleID:(id)arg1; - (id)_firstDisplayItemForBundleID:(id)arg1; - (id)_firstDisplayItemForUniqueID:(id)arg1; - (BOOL)_isDisallowedDisplayItem:(id)arg1; - (BOOL)_displayItemIsExecutableOnCurrentPlatform:(id)arg1; - (void)_setupDelayAfterTransitionTimerForActivatingElement:(id)arg1; - (void)_clearDelayAfterTransitionTimer; - (void)eventSource:(id)arg1 applicationsBecameVisible:(id)arg2; - (void)eventSource:(id)arg1 userQuitApplicationInSwitcher:(id)arg2; - (void)eventSource:(id)arg1 didBeginTransitionToMode:(long long)arg2 withLayoutState:(id)arg3 activatingElement:(id)arg4 triggeredBy:(long long)arg5; - (void)eventSource:(id)arg1 didFinishTransitionToMode:(long long)arg2 withLayoutState:(id)arg3 activatingElement:(id)arg4 triggeredBy:(long long)arg5; - (void)eventSource:(id)arg1 keyboardFocusChangedToApplication:(id)arg2; - (void)eventSource:(id)arg1 userTouchedApplication:(id)arg2; - (void)eventSource:(id)arg1 applicationsBecameHidden:(id)arg2; - (void)eventSource:(id)arg1 userDeletedApplications:(id)arg2; - (void)eventSource:(id)arg1 userRemovedSuggestions:(id)arg2; - (void)dealloc; - (void)reset; - (void)removeDisplayItem:(id)arg1; @property(copy, nonatomic) NSOrderedSet *recentDisplayItems; - (id)init; - (id)initWithRemovalPersonality:(long long)arg1 movePersonality:(long long)arg2 transitionFromSources:(id)arg3 maxDisplayItems:(NSUInteger)arg4 eventSource:(id)arg5 applicationController:(id)arg6; @end
46.830769
197
0.807162
ffd467f23b42736399f8728bca3f507370bf6940
392
h
C
config/macos/config.h
Zhoutall/stasis
65a9ae5ce1468e3d8073e62fbcb15b120ec344f5
[ "TCL" ]
null
null
null
config/macos/config.h
Zhoutall/stasis
65a9ae5ce1468e3d8073e62fbcb15b120ec344f5
[ "TCL" ]
null
null
null
config/macos/config.h
Zhoutall/stasis
65a9ae5ce1468e3d8073e62fbcb15b120ec344f5
[ "TCL" ]
1
2019-11-21T07:21:32.000Z
2019-11-21T07:21:32.000Z
#define __USE_GNU #define _GNU_SOURCE #define ON_MACOS //#define HAVE_POSIX_FALLOCATE //#define HAVE_FDATASYNC //#define HAVE_SYNC_FILE_RANGE //#define HAVE_O_NOATIME //#define HAVE_POSIX_FADVISE #define HAVE_O_DIRECT #define HAVE_GCC_ATOMICS #define HAVE_PTHREAD_STACK_MIN #define HAVE_ALLOCA_H #define HAVE_TDESTROY #define HAVE_POWL #define PBL_COMPAT 1 #define STLSEARCH 1 //#define DBUG
21.777778
30
0.834184
ffd54b3fd406a18f9e0b4ce65de7b8abf739725d
1,516
h
C
other/sensor_magnet/tests/tigrillo_opencm.h
Gabs48/tigrillo2
66ad26c0aff39da74ca76f712b6f01b40d383f34
[ "MIT" ]
1
2018-11-05T14:21:43.000Z
2018-11-05T14:21:43.000Z
other/sensor_magnet/tests/tigrillo_opencm.h
Gabs48/tigrillo2
66ad26c0aff39da74ca76f712b6f01b40d383f34
[ "MIT" ]
null
null
null
other/sensor_magnet/tests/tigrillo_opencm.h
Gabs48/tigrillo2
66ad26c0aff39da74ca76f712b6f01b40d383f34
[ "MIT" ]
null
null
null
/* Tigrillo_opencm.h This script implements the basic functions to interface sensors and actuators over the UART so that they can be used on another board. No major computation or logi is done here. Created on November 25th, 2017 Gabriel Urbain <gabriel.urbain@ugent.be> Copyright 2017, Human Brain Projet, SP10 */ #ifndef _TIGRILLO_OPENCM_H_ #define _TIGRILLO_OPENCM_H_ /* -------- Robot Constants -------- */ #define UART_3 3 #define TIMER_1 1 #define MAX_ARG_SIZE 100 #define BAUDRATE_SERVO_115200 2 #define BAUDRATE_SERVO_1MB 3 #define BAUDRATE_UART_57600 57600 #define BAUDRATE_UART_115200 115200 #define BAUDRATE_UART_921600 921600 #define BUFF_SIZE 256 #define SERVO_MIN_LIM 200 #define SERVO_MAX_LIM 820 #define SERVO_RANGE 180 #define ACT_NUM 4 #define ACT_ID_FL 1 #define ACT_ID_FR 2 #define ACT_ID_BL 3 #define ACT_ID_BR 4 #define MIN_SENS_READ_TIME 2000 #define DEF_SENS_READ_TIME 40000 #define SENS_NUM 4 #define SENS_PIN_FL 0 #define SENS_PIN_FR 3 #define SENS_PIN_BL 6 #define SENS_PIN_BR 8 #define GOAL_POS_SLACK 30 /* -------- Custom Processing Functions -------- */ void processRx(byte* buffer, byte size); void readSensors(void); void resetSensors(void); void updateMotors(int act_leg[]); int changePeriod(int period); /* -------- Custom Utils Functions -------- */ void printTab(int* tab, int size); void initTab(int* tab, int size); void emptyStr(char* tab, int size); int str2i(char* str, int* tab, int size); void wait4Bus(void); void freeBus(void); #endif
19.688312
93
0.752639
ffd5b1341398b723dd0ff9cdca653951ed51df7b
3,796
c
C
timegloves-openstm32-project/inc/gpio.c
Kamigami55/time-gloves
9362ac707cfa2b00c3f39184df64f343bfc9f4d0
[ "MIT" ]
1
2018-04-21T22:10:18.000Z
2018-04-21T22:10:18.000Z
timegloves-openstm32-project/inc/gpio.c
Kamigami55/time-gloves
9362ac707cfa2b00c3f39184df64f343bfc9f4d0
[ "MIT" ]
null
null
null
timegloves-openstm32-project/inc/gpio.c
Kamigami55/time-gloves
9362ac707cfa2b00c3f39184df64f343bfc9f4d0
[ "MIT" ]
null
null
null
/** * |---------------------------------------------------------------------- * | Copyright (c) 2016 Tilen Majerle * | * | 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 "gpio.h" void TM_GPIO_INT_EnableClock(GPIO_TypeDef* GPIOx); void TM_GPIO_INT_Init(GPIO_TypeDef* GPIOx, uint32_t GPIO_Pin, TM_GPIO_Mode_t GPIO_Mode, TM_GPIO_OType_t GPIO_OType, TM_GPIO_PuPd_t GPIO_PuPd, TM_GPIO_Speed_t GPIO_Speed); void TM_GPIO_Init(GPIO_TypeDef* GPIOx, uint32_t GPIO_Pin, TM_GPIO_Mode_t GPIO_Mode, TM_GPIO_OType_t GPIO_OType, TM_GPIO_PuPd_t GPIO_PuPd, TM_GPIO_Speed_t GPIO_Speed) { /* Check input */ if (GPIO_Pin == 0x00) { return; } /* Enable clock for GPIO */ TM_GPIO_INT_EnableClock(GPIOx); /* Do initialization */ TM_GPIO_INT_Init(GPIOx, GPIO_Pin, GPIO_Mode, GPIO_OType, GPIO_PuPd, GPIO_Speed); } void TM_GPIO_SetPullResistor(GPIO_TypeDef* GPIOx, uint32_t GPIO_Pin, TM_GPIO_PuPd_t GPIO_PuPd) { /* Set GPIO PUPD register */ GPIOx->PUPDR = (GPIOx->PUPDR & ~(0x03 << (2 * GPIO_Pin))) | ((uint32_t)(GPIO_PuPd << (2 * GPIO_Pin))); } void TM_GPIO_SetPinAsInput(GPIO_TypeDef* GPIOx, uint32_t GPIO_Pin) { /* Set 00 bits combination for input */ GPIOx->MODER &= ~(0x03 << (2 * GPIO_Pin)); } void TM_GPIO_SetPinAsOutput(GPIO_TypeDef* GPIOx, uint32_t GPIO_Pin) { /* Set 01 bits combination for output */ GPIOx->MODER = (GPIOx->MODER & ~(0x03 << (2 * GPIO_Pin))) | (0x01 << (2 * GPIO_Pin)); } uint32_t TM_GPIO_GetPortSource(GPIO_TypeDef* GPIOx) { /* Get port source number */ /* Offset from GPIOA Difference between 2 GPIO addresses */ return ((uint32_t)GPIOx - (GPIOA_BASE)) / ((GPIOB_BASE) - (GPIOA_BASE)); } void TM_GPIO_INT_EnableClock(GPIO_TypeDef* GPIOx) { RCC->AHB2ENR |= (1 << TM_GPIO_GetPortSource(GPIOx)); } void TM_GPIO_INT_Init(GPIO_TypeDef* GPIOx, uint32_t GPIO_Pin, TM_GPIO_Mode_t GPIO_Mode, TM_GPIO_OType_t GPIO_OType, TM_GPIO_PuPd_t GPIO_PuPd, TM_GPIO_Speed_t GPIO_Speed) { uint8_t pinpos; /* Set GPIO PUPD register */ GPIOx->PUPDR = (GPIOx->PUPDR & ~(0x03 << (2 * GPIO_Pin))) | ((uint32_t)(GPIO_PuPd << (2 * GPIO_Pin))); /* Set GPIO MODE register */ GPIOx->MODER = (GPIOx->MODER & ~((uint32_t)(0x03 << (2 * GPIO_Pin)))) | ((uint32_t)(GPIO_Mode << (2 * GPIO_Pin))); /* Set only if output or alternate functions */ if (GPIO_Mode == TM_GPIO_Mode_OUT || GPIO_Mode == TM_GPIO_Mode_AF) { /* Set GPIO OTYPE register */ GPIOx->OTYPER = (GPIOx->OTYPER & ~(uint32_t)(0x01 << GPIO_Pin)) | ((uint32_t)(GPIO_OType << GPIO_Pin)); /* Set GPIO OSPEED register */ GPIOx->OSPEEDR = (GPIOx->OSPEEDR & ~((uint32_t)(0x03 << (2 * GPIO_Pin)))) | ((uint32_t)(GPIO_Speed << (2 * GPIO_Pin))); } }
42.651685
171
0.684668
ffdb0a85b639b4ea36d7b5f69767bc1750cf4f9d
6,950
h
C
bignumber/bn-gfp.h
alu112/OpenCrypto
80cb8d69fd82112c79b8bfd59a22faf9481cfbc9
[ "Apache-2.0" ]
1
2021-02-18T08:54:36.000Z
2021-02-18T08:54:36.000Z
bignumber/bn-gfp.h
alu112/OpenCrypto
80cb8d69fd82112c79b8bfd59a22faf9481cfbc9
[ "Apache-2.0" ]
null
null
null
bignumber/bn-gfp.h
alu112/OpenCrypto
80cb8d69fd82112c79b8bfd59a22faf9481cfbc9
[ "Apache-2.0" ]
1
2020-07-24T07:02:58.000Z
2020-07-24T07:02:58.000Z
/* Copyright 2020 Andrew Li, Gavin Li li.andrew.mail@gmail.com gavinux@gmail.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. */ #ifndef __BN_GFP_H__ #define __BN_GFP_H__ #include <stdbool.h> #include <stdint.h> #include <string.h> #ifndef MAXBITLEN /* RSA Private Key Length */ #define MAXBITLEN 2048 /* multiple of 32-bit */ #endif //#define BN_LEN ((MAXBITLEN / 32 + 1) * 2) //#define BN_LEN (((MAXBITLEN + 31) / 32) * 2) /* Good for bitwise_expmod() kary_expmod() */ //#define BN_LEN (((MAXBITLEN + 31) / 32) * 2+4) #define BN_LEN (((MAXBITLEN + 31) / 32) * 2 + 2) typedef uint32_t bn_t[BN_LEN]; void bn_print(char * msg, bn_t a); /* print n bytes */ void bn_print_len(char *msg, bn_t bn, int n); void bn_swap(bn_t a, bn_t b); int bn_getbit(bn_t a, int i); void bn_setbit(bn_t a, int i); void bn_clrbit(bn_t a, int i); /* get how many uint32 units */ int bn_getlen(bn_t bn); /* get msbit position */ int bn_getmsbposn(bn_t bn); /* bn = 0 */ void bn_clear(bn_t bn); /* bn = 1 */ void bn_setone(bn_t bn); /* set bn = uint64 */ void bn_qw2bn(uint64_t u64, bn_t b); /* set bn to the hexstring */ void bn_hex2bn(uint8_t *str, bn_t r); void bn_bn2hex(bn_t a, uint8_t *hex); /* copy bytes array to bn */ void bn_ba2bn(uint8_t *bytes, int len, bn_t r); void bn_bn2ba(bn_t r, int len, uint8_t *bytes); bool bn_iszero(bn_t bn); bool bn_isone(bn_t bn); bool bn_isodd(bn_t bn); bool bn_iseven(bn_t bn); /* no negative number */ bool bn_ispositive(bn_t bn); /* to = from */ void bn_cpy(bn_t from, bn_t to); /* copy [from] n uint32 start from offset to [to] */ void bn_cpylen(int offset, int n, bn_t from, bn_t to); /* b = a << nbits */ void bn_lshift(bn_t a, int nbits, bn_t b); /* b = a >> nbits */ void bn_rshift(bn_t a, int nbits, bn_t b); /* bn <<= 32 */ void bn_lshift32(bn_t bn); /* bn = bn<<32 | u32 */ void bn_lshift32_append(bn_t bn, uint32_t u32); /* bn <<= 1 , which is bn*2 */ void bn_lshift1(bn_t bn); /* bn >>= 1 , which is bn/2 */ void bn_rshift1(bn_t bn); /* a = a + uint32 */ uint32_t bn_addx(uint32_t x, bn_t a); /* a = a - uint32 */ uint32_t bn_subx(uint32_t x, bn_t a); /* r = a + b */ uint32_t bn_add(bn_t a, bn_t b, bn_t r); /* r = a - b */ uint32_t bn_sub(bn_t a, bn_t b, bn_t r); /* * return 1: a > b * 0: a == b * -1: a < b */ int bn_cmp(bn_t a, bn_t b); /* r = a * u32 */ uint32_t bn_mult32(bn_t a, uint32_t u32, bn_t r); /* r = a * u64 */ uint64_t bn_mult64(bn_t a, uint32_t u64, bn_t r); /* r = a * b */ uint32_t bn_mul(bn_t a, bn_t b, bn_t r); /* HAC 14.16 Algorithm Multiple-precision squaring */ uint32_t bn_sqr(bn_t x, bn_t y); /* q = a / s; r = a % s */ void bn_divu32(bn_t a, uint32_t s, bn_t q, uint32_t *r); /* * q = a / b; m = a % b * if q and m point to same location * then m contain correct value, q is overwritten by m */ void bn_classic_div(bn_t a, bn_t b, bn_t q, bn_t m); /* HAC 14.20 Algorithm Multiple-precision division */ /* a = q*b + r, 0 <= r < y, an...a1a0, bt...b1b0 */ void bn_hac_div(bn_t a, bn_t b, bn_t q, bn_t r); /* global function pointers, to select various algorithms */ extern void (*bn_div)(bn_t, bn_t, bn_t, bn_t); /************ mod APIs **************/ /* r = a + b mod n */ void bn_addmod(bn_t a, bn_t b, bn_t n, bn_t r); /* r = a - b mod n */ void bn_submod(bn_t a, bn_t b, bn_t n, bn_t r); /* m = a % n */ void bn_mod(bn_t a, bn_t n, bn_t m); /* r = 1/a mod n */ void bn_invmod(bn_t a, bn_t n, bn_t r); /* r = a * b mod n */ void bn_classic_mulmod(bn_t a, bn_t b, bn_t n, bn_t r); void bn_mont_mulmod(bn_t a, bn_t b, bn_t n, bn_t r); void bn_mont_mulmod_with_np(bn_t a, bn_t b, bn_t n, bn_t np, bn_t r); /* global function pointers, to select various algorithms */ extern void (*bn_mulmod)(bn_t a, bn_t b, bn_t n, bn_t r); /* * HAC 14.54 Algorithm Binary gcd algorithm * INPUT: two positive integers x and y with x>= y * OUTPUT: gcd(x, y) */ uint32_t bn_bin_gcd(bn_t x, bn_t y, bn_t gcd); /* BUGS!!! * HAC 14.61 Algorithm Binary extended gcd algorithm * INPUT: two positive integers x and y * OUTPUT: integers a, b, and g such that ax + by = g, where g = gcd(x, y). */ uint32_t bn_bin_extended_gcd(bn_t x, bn_t y, bn_t a, bn_t b, bn_t g); /* * Extended Euclidean Algorithm * INPUT: two positive integers a and b * OUTPUT: integers a, b, and g. such that ax + by = g, where g = gcd(a, b). * such that: x = -a', y = 1/b mod a, g = 1 * which is used in montgomery calculation: -n*n' + r*r^(-1) = 1 */ uint32_t bn_eea(bn_t a, bn_t b, bn_t x, bn_t y, bn_t g); /* * HAC 14.32 Algorithm Montgomery reduction * INPUT: integers * T = (t[2n−1] ... t[1]t[0])b < mR * m = (m[n−1] ... m[1]m[0])b with gcd(m, b) = 1, * m is odd for RSA, so gcd(m,b)=1 will hold * m' = −m^(−1) mod b * radix b = 2^32 * R = b^n is sufficient (but not necessary) for efficient implementation * OUTPUT:TR^(−1) mod m */ uint32_t bn_mont_redc(bn_t T, bn_t m, /*bn_t R,*/ bn_t mp, bn_t TRm); void bn_get_n_prime(bn_t n, bn_t np); /* * HAC 14.36 Algorithm Montgomery multiplication * INPUT: integers * m = (m[n−1] ... m[1]m[0]) radix b * x = (x[n−1] ... x[1]x[0]) radix b * y = (y[n−1] ... y[1]y[0]) radix b * with 0 <= x, y < m, R = b^n with gcd(m, b) = 1, and m' = −m^(−1) mod b. * OUTPUT: xyR^(−1) mod m * * Here: b = 2^32 */ void bn_mont_pro_1(bn_t x, bn_t y, bn_t m, bn_t mp, bn_t product); void bn_mont_pro_2(bn_t x, bn_t y, bn_t m, bn_t mp, bn_t product); void bn_mont_pro_3(bn_t x, bn_t y, bn_t m, bn_t mp, bn_t product); extern void (*bn_mont_pro)(bn_t , bn_t , bn_t , bn_t , bn_t ); /* * product = a * b mod n * * n is odd number * r*r^(-1) - n*n' = 1 * np is n' in the function * * The integers r^(−1) and n' can both be computed by the * Extended Euclidean Algorithm */ void bn_mont_mulmod_with_np(bn_t a, bn_t b, bn_t n, bn_t np, bn_t product); /* * HAC 14.94 Algorithm Montgomery exponentiation * y = x^e mod m */ void bn_mont_expmod(bn_t x, bn_t e, bn_t n, bn_t y); /* HAC 14.79 Algorithm Left-to-right binary exponentiation */ /* y = x^e mod n */ void bn_bitwise_expmod(bn_t x, bn_t e, bn_t n, bn_t y); /* HAC 14.83 Algorithm Modified left-to-right k-ary exponentiation */ /* y= x^e mod n k-ary algorithm */ void bn_kary_expmod(bn_t a, bn_t e, bn_t n, bn_t m); /* global function pointers, to select various algorithms */ extern void (*bn_expmod)(bn_t, bn_t, bn_t, bn_t); #endif /* __BN_GFP_H__ */
32.325581
93
0.634676
ffdba680485e1cef04800dc9cfacbcead0e8210e
295
c
C
lib/wizards/manta/castle/cas3.c
vlehtola/questmud
8bc3099b5ad00a9e0261faeb6637c76b521b6dbe
[ "MIT" ]
null
null
null
lib/wizards/manta/castle/cas3.c
vlehtola/questmud
8bc3099b5ad00a9e0261faeb6637c76b521b6dbe
[ "MIT" ]
null
null
null
lib/wizards/manta/castle/cas3.c
vlehtola/questmud
8bc3099b5ad00a9e0261faeb6637c76b521b6dbe
[ "MIT" ]
null
null
null
#include "room.h" THREE_EXIT("wizards/manta/castle/cas9.c", "north", "wizards/manta/castle/cas4.c", "east", "wizards/manta/castle/cas2.c", "west", "Southern corridor", "Southern corridor connecting western and eastern parth of castle.\n", 2)
32.777778
86
0.60339
ffdc1fd5bd61bc4d1c8ee8484f05bf0579cc67c0
2,101
h
C
lab2/allocator.h
dmitrylyk/os-labs
313a4afb8e71ed9491f002fd77a940c8aa430ad1
[ "MIT" ]
1
2021-12-13T15:41:48.000Z
2021-12-13T15:41:48.000Z
lab2/allocator.h
dmitrylyk/os-labs
313a4afb8e71ed9491f002fd77a940c8aa430ad1
[ "MIT" ]
15
2021-09-12T15:06:13.000Z
2022-03-31T19:02:08.000Z
lab2/allocator.h
dmitrylyk/os-labs
313a4afb8e71ed9491f002fd77a940c8aa430ad1
[ "MIT" ]
1
2022-01-29T00:37:52.000Z
2022-01-29T00:37:52.000Z
#pragma once struct LBlockDescriptor{ size_t nextFreeBlock;//shift }; struct PageDescriptor{ size_t next; //list of pages with the same state LBlockDescriptor* firstFree; //free block in state 1 size_t bsize; // size of lBlock in state 1 or number of blocks in state 2 char state; //0-free, 1-lblock, 2-mblock }; class Allocator { public: Allocator(const size_t ms, const size_t ps); //return addr on begin of allocated block or NULL void* mem_alloc(size_t size); //return addr on begin of reallocated block or NULL void* mem_realloc(void *addr, size_t size); //free block by this address void mem_free(void *addr); //out blocks characteristic in table on console void mem_dump(); private: //begin of control information size_t* begin; //begin of pages in memory size_t* pagesBegin; size_t size; size_t pages; size_t pageSize; //array of all page descriptors PageDescriptor* pageDescriptors; //array of pages with state 1 size_t* lBlocks; size_t lBlocksLength; size_t firstFreePage; //define what type of state rigth for this size PageDescriptor defineCategory(size_t s); //round s to minimal need size power of 2 size_t defineBlockSize(size_t s); //initial all pages as free void initPages(); // return free block with size bs size_t* getFreeLBlock(size_t bs); //return index for lBlocks array size_t getIndex(size_t s); size_t createLBlockPage(size_t bs); //size_t getLBlockPage(size_t bs); //not use :/ size_t getFreePage(); //return page`s address from index of pages array size_t* getAbsolutePageAddr(size_t index); //set all blocks in page to free state void setAllFree(PageDescriptor pd); //return big block with length ps*pageSize size_t* getFreeMBlock(size_t ps); //check is this block alst free in this page bool freeLBlockIsLast(PageDescriptor pd); //return number of page from her addr size_t findPageByAddress(size_t* addr); //return number of block from his addr size_t findBlockByAddress(size_t* addr, size_t bs); //copy data from old pos to new void copyData(size_t* from, size_t* to, size_t length); };
27.285714
74
0.747739
ffdc6d8595678b86a3fe05f4c053b5440c7ba1c3
842
h
C
hackathon/zhi/NeuronStudio_zhi/ext/pageloader.h
zzhmark/vaa3d_tools
3ca418add85a59ac7e805d55a600b78330d7e53d
[ "MIT" ]
1
2021-12-27T19:14:03.000Z
2021-12-27T19:14:03.000Z
hackathon/zhi/NeuronStudio_zhi/ext/pageloader.h
zzhmark/vaa3d_tools
3ca418add85a59ac7e805d55a600b78330d7e53d
[ "MIT" ]
1
2016-12-03T05:33:13.000Z
2016-12-03T05:33:13.000Z
hackathon/zhi/NeuronStudio_zhi/ext/pageloader.h
zzhmark/vaa3d_tools
3ca418add85a59ac7e805d55a600b78330d7e53d
[ "MIT" ]
null
null
null
/*************************************************************** Pager.h: Experimental module to test if forcing reading of pages ahead could help performance. ****************************************************************/ #include <stdlib.h> #include <windows.h> #ifndef __PAGE_LOADER_H__ #define __PAGE_LOADER_H__ typedef struct tagPAGELOADER { const unsigned char* data; size_t bytes; size_t window; int newaccess; const unsigned char* start; const unsigned char* end; int terminate; HANDLE threadhandle; } PAGELOADER; PAGELOADER* CreatePageLoader(const unsigned char* data, size_t bytes, size_t window); void DestroyPageLoader(PAGELOADER* pl); void AnnounceAccess(PAGELOADER* pl, const unsigned char* address); #endif/* __PAGE_LOADER_H__ */
24.057143
86
0.589074
ffdd43383610499597711c506946285a1c0b03e7
664
c
C
solutions_C/problem37.c
allan-cedric/projecteuler
362fa5c78974233ed2491ae7af37eab48a2b0dbb
[ "MIT" ]
1
2020-03-27T15:16:34.000Z
2020-03-27T15:16:34.000Z
solutions_C/problem37.c
allan-cedric/projecteuler
362fa5c78974233ed2491ae7af37eab48a2b0dbb
[ "MIT" ]
null
null
null
solutions_C/problem37.c
allan-cedric/projecteuler
362fa5c78974233ed2491ae7af37eab48a2b0dbb
[ "MIT" ]
null
null
null
#include <stdio.h> int is_prime(int n); int trunc_prime(int n); int main() { int i, n, sum = 0; for (i = 0, n = 11; i < 11; n++) { if (is_prime(n) && trunc_prime(n)) { sum += n; i++; } } printf("Sum: %i\n", sum); return 0; } int is_prime(int n) { if (n == 1 || !n) return 0; int i; for (i = 2; i < n; i++) { if (!(n % i)) return 0; } return 1; } int trunc_prime(int n) { int base = 10; while (base < n) { if (!is_prime(n % base) || !is_prime(n / base)) return 0; base *= 10; } return 1; }
15.090909
55
0.399096
ffded3453d269fe4161daad4f7fce97eedcb0808
13,997
c
C
qemu-shack-ibtc/roms/seabios/vgasrc/vgaio.c
silverneko/HWs
84d19316e01c3bb7b2fcf1fa9ad3dff99c01b543
[ "MIT" ]
6
2021-11-03T06:43:52.000Z
2022-02-13T22:54:02.000Z
bios/seabios/vgasrc/vgaio.c
jnouyang/palacios
e06aee743c38e53901d2e80590d687e5b93f93f2
[ "BSD-3-Clause" ]
1
2019-09-14T00:49:35.000Z
2019-09-14T00:49:35.000Z
bios/seabios/vgasrc/vgaio.c
jnouyang/palacios
e06aee743c38e53901d2e80590d687e5b93f93f2
[ "BSD-3-Clause" ]
1
2020-04-28T16:25:05.000Z
2020-04-28T16:25:05.000Z
// VGA io port access // // Copyright (C) 2009 Kevin O'Connor <kevin@koconnor.net> // Copyright (C) 2001-2008 the LGPL VGABios developers Team // // This file may be distributed under the terms of the GNU LGPLv3 license. #include "ioport.h" // outb #include "farptr.h" // SET_FARVAR #include "biosvar.h" // GET_BDA #include "vgatables.h" // VGAREG_* // TODO // * replace direct in/out calls with wrapper functions /**************************************************************** * Attribute control ****************************************************************/ void vgahw_screen_disable(void) { inb(VGAREG_ACTL_RESET); outb(0x00, VGAREG_ACTL_ADDRESS); } void vgahw_screen_enable(void) { inb(VGAREG_ACTL_RESET); outb(0x20, VGAREG_ACTL_ADDRESS); } void vgahw_set_border_color(u8 color) { inb(VGAREG_ACTL_RESET); outb(0x00, VGAREG_ACTL_ADDRESS); u8 v1 = color & 0x0f; if (v1 & 0x08) v1 += 0x08; outb(v1, VGAREG_ACTL_WRITE_DATA); u8 v2 = color & 0x10; int i; for (i = 1; i < 4; i++) { outb(i, VGAREG_ACTL_ADDRESS); u8 cur = inb(VGAREG_ACTL_READ_DATA); cur &= 0xef; cur |= v2; outb(cur, VGAREG_ACTL_WRITE_DATA); } outb(0x20, VGAREG_ACTL_ADDRESS); } void vgahw_set_overscan_border_color(u8 color) { inb(VGAREG_ACTL_RESET); outb(0x11, VGAREG_ACTL_ADDRESS); outb(color, VGAREG_ACTL_WRITE_DATA); outb(0x20, VGAREG_ACTL_ADDRESS); } u8 vgahw_get_overscan_border_color(void) { inb(VGAREG_ACTL_RESET); outb(0x11, VGAREG_ACTL_ADDRESS); u8 v = inb(VGAREG_ACTL_READ_DATA); inb(VGAREG_ACTL_RESET); outb(0x20, VGAREG_ACTL_ADDRESS); return v; } void vgahw_set_palette(u8 palid) { inb(VGAREG_ACTL_RESET); palid &= 0x01; int i; for (i = 1; i < 4; i++) { outb(i, VGAREG_ACTL_ADDRESS); u8 v = inb(VGAREG_ACTL_READ_DATA); v &= 0xfe; v |= palid; outb(v, VGAREG_ACTL_WRITE_DATA); } outb(0x20, VGAREG_ACTL_ADDRESS); } void vgahw_set_single_palette_reg(u8 reg, u8 val) { inb(VGAREG_ACTL_RESET); outb(reg, VGAREG_ACTL_ADDRESS); outb(val, VGAREG_ACTL_WRITE_DATA); outb(0x20, VGAREG_ACTL_ADDRESS); } u8 vgahw_get_single_palette_reg(u8 reg) { inb(VGAREG_ACTL_RESET); outb(reg, VGAREG_ACTL_ADDRESS); u8 v = inb(VGAREG_ACTL_READ_DATA); inb(VGAREG_ACTL_RESET); outb(0x20, VGAREG_ACTL_ADDRESS); return v; } void vgahw_set_all_palette_reg(u16 seg, u8 *data_far) { inb(VGAREG_ACTL_RESET); int i; for (i = 0; i < 0x10; i++) { outb(i, VGAREG_ACTL_ADDRESS); u8 val = GET_FARVAR(seg, *data_far); outb(val, VGAREG_ACTL_WRITE_DATA); data_far++; } outb(0x11, VGAREG_ACTL_ADDRESS); outb(GET_FARVAR(seg, *data_far), VGAREG_ACTL_WRITE_DATA); outb(0x20, VGAREG_ACTL_ADDRESS); } void vgahw_get_all_palette_reg(u16 seg, u8 *data_far) { int i; for (i = 0; i < 0x10; i++) { inb(VGAREG_ACTL_RESET); outb(i, VGAREG_ACTL_ADDRESS); SET_FARVAR(seg, *data_far, inb(VGAREG_ACTL_READ_DATA)); data_far++; } inb(VGAREG_ACTL_RESET); outb(0x11, VGAREG_ACTL_ADDRESS); SET_FARVAR(seg, *data_far, inb(VGAREG_ACTL_READ_DATA)); inb(VGAREG_ACTL_RESET); outb(0x20, VGAREG_ACTL_ADDRESS); } void vgahw_toggle_intensity(u8 flag) { inb(VGAREG_ACTL_RESET); outb(0x10, VGAREG_ACTL_ADDRESS); u8 val = (inb(VGAREG_ACTL_READ_DATA) & 0xf7) | ((flag & 0x01) << 3); outb(val, VGAREG_ACTL_WRITE_DATA); outb(0x20, VGAREG_ACTL_ADDRESS); } void vgahw_select_video_dac_color_page(u8 flag, u8 data) { inb(VGAREG_ACTL_RESET); outb(0x10, VGAREG_ACTL_ADDRESS); u8 val = inb(VGAREG_ACTL_READ_DATA); if (!(flag & 0x01)) { // select paging mode val = (val & 0x7f) | (data << 7); outb(val, VGAREG_ACTL_WRITE_DATA); outb(0x20, VGAREG_ACTL_ADDRESS); return; } // select page inb(VGAREG_ACTL_RESET); outb(0x14, VGAREG_ACTL_ADDRESS); if (!(val & 0x80)) data <<= 2; data &= 0x0f; outb(data, VGAREG_ACTL_WRITE_DATA); outb(0x20, VGAREG_ACTL_ADDRESS); } void vgahw_read_video_dac_state(u8 *pmode, u8 *curpage) { inb(VGAREG_ACTL_RESET); outb(0x10, VGAREG_ACTL_ADDRESS); u8 val1 = inb(VGAREG_ACTL_READ_DATA) >> 7; inb(VGAREG_ACTL_RESET); outb(0x14, VGAREG_ACTL_ADDRESS); u8 val2 = inb(VGAREG_ACTL_READ_DATA) & 0x0f; if (!(val1 & 0x01)) val2 >>= 2; inb(VGAREG_ACTL_RESET); outb(0x20, VGAREG_ACTL_ADDRESS); *pmode = val1; *curpage = val2; } /**************************************************************** * DAC control ****************************************************************/ void vgahw_set_dac_regs(u16 seg, u8 *data_far, u8 start, int count) { outb(start, VGAREG_DAC_WRITE_ADDRESS); while (count) { outb(GET_FARVAR(seg, *data_far), VGAREG_DAC_DATA); data_far++; outb(GET_FARVAR(seg, *data_far), VGAREG_DAC_DATA); data_far++; outb(GET_FARVAR(seg, *data_far), VGAREG_DAC_DATA); data_far++; count--; } } void vgahw_get_dac_regs(u16 seg, u8 *data_far, u8 start, int count) { outb(start, VGAREG_DAC_READ_ADDRESS); while (count) { SET_FARVAR(seg, *data_far, inb(VGAREG_DAC_DATA)); data_far++; SET_FARVAR(seg, *data_far, inb(VGAREG_DAC_DATA)); data_far++; SET_FARVAR(seg, *data_far, inb(VGAREG_DAC_DATA)); data_far++; count--; } } void vgahw_set_pel_mask(u8 val) { outb(val, VGAREG_PEL_MASK); } u8 vgahw_get_pel_mask(void) { return inb(VGAREG_PEL_MASK); } void vgahw_save_dac_state(u16 seg, struct saveDACcolors *info) { /* XXX: check this */ SET_FARVAR(seg, info->rwmode, inb(VGAREG_DAC_STATE)); SET_FARVAR(seg, info->peladdr, inb(VGAREG_DAC_WRITE_ADDRESS)); SET_FARVAR(seg, info->pelmask, inb(VGAREG_PEL_MASK)); vgahw_get_dac_regs(seg, info->dac, 0, 256); SET_FARVAR(seg, info->color_select, 0); } void vgahw_restore_dac_state(u16 seg, struct saveDACcolors *info) { outb(GET_FARVAR(seg, info->pelmask), VGAREG_PEL_MASK); vgahw_set_dac_regs(seg, info->dac, 0, 256); outb(GET_FARVAR(seg, info->peladdr), VGAREG_DAC_WRITE_ADDRESS); } /**************************************************************** * Memory control ****************************************************************/ void vgahw_sequ_write(u8 index, u8 value) { outw((value<<8) | index, VGAREG_SEQU_ADDRESS); } void vgahw_grdc_write(u8 index, u8 value) { outw((value<<8) | index, VGAREG_GRDC_ADDRESS); } void vgahw_set_text_block_specifier(u8 spec) { outw((spec << 8) | 0x03, VGAREG_SEQU_ADDRESS); } void get_font_access(void) { outw(0x0100, VGAREG_SEQU_ADDRESS); outw(0x0402, VGAREG_SEQU_ADDRESS); outw(0x0704, VGAREG_SEQU_ADDRESS); outw(0x0300, VGAREG_SEQU_ADDRESS); outw(0x0204, VGAREG_GRDC_ADDRESS); outw(0x0005, VGAREG_GRDC_ADDRESS); outw(0x0406, VGAREG_GRDC_ADDRESS); } void release_font_access(void) { outw(0x0100, VGAREG_SEQU_ADDRESS); outw(0x0302, VGAREG_SEQU_ADDRESS); outw(0x0304, VGAREG_SEQU_ADDRESS); outw(0x0300, VGAREG_SEQU_ADDRESS); u16 v = (inw(VGAREG_READ_MISC_OUTPUT) & 0x01) ? 0x0e : 0x0a; outw((v << 8) | 0x06, VGAREG_GRDC_ADDRESS); outw(0x0004, VGAREG_GRDC_ADDRESS); outw(0x1005, VGAREG_GRDC_ADDRESS); } /**************************************************************** * CRTC registers ****************************************************************/ static u16 get_crtc(void) { return GET_BDA(crtc_address); } void vgahw_set_cursor_shape(u8 start, u8 end) { u16 crtc_addr = get_crtc(); outb(0x0a, crtc_addr); outb(start, crtc_addr + 1); outb(0x0b, crtc_addr); outb(end, crtc_addr + 1); } void vgahw_set_active_page(u16 address) { u16 crtc_addr = get_crtc(); outb(0x0c, crtc_addr); outb((address & 0xff00) >> 8, crtc_addr + 1); outb(0x0d, crtc_addr); outb(address & 0x00ff, crtc_addr + 1); } void vgahw_set_cursor_pos(u16 address) { u16 crtc_addr = get_crtc(); outb(0x0e, crtc_addr); outb((address & 0xff00) >> 8, crtc_addr + 1); outb(0x0f, crtc_addr); outb(address & 0x00ff, crtc_addr + 1); } void vgahw_set_scan_lines(u8 lines) { u16 crtc_addr = get_crtc(); outb(0x09, crtc_addr); u8 crtc_r9 = inb(crtc_addr + 1); crtc_r9 = (crtc_r9 & 0xe0) | (lines - 1); outb(crtc_r9, crtc_addr + 1); } // Get vertical display end u16 vgahw_get_vde(void) { u16 crtc_addr = get_crtc(); outb(0x12, crtc_addr); u16 vde = inb(crtc_addr + 1); outb(0x07, crtc_addr); u8 ovl = inb(crtc_addr + 1); vde += (((ovl & 0x02) << 7) + ((ovl & 0x40) << 3) + 1); return vde; } /**************************************************************** * Save/Restore/Set state ****************************************************************/ void vgahw_save_state(u16 seg, struct saveVideoHardware *info) { u16 crtc_addr = get_crtc(); SET_FARVAR(seg, info->sequ_index, inb(VGAREG_SEQU_ADDRESS)); SET_FARVAR(seg, info->crtc_index, inb(crtc_addr)); SET_FARVAR(seg, info->grdc_index, inb(VGAREG_GRDC_ADDRESS)); inb(VGAREG_ACTL_RESET); u16 ar_index = inb(VGAREG_ACTL_ADDRESS); SET_FARVAR(seg, info->actl_index, ar_index); SET_FARVAR(seg, info->feature, inb(VGAREG_READ_FEATURE_CTL)); u16 i; for (i=0; i<4; i++) { outb(i+1, VGAREG_SEQU_ADDRESS); SET_FARVAR(seg, info->sequ_regs[i], inb(VGAREG_SEQU_DATA)); } outb(0, VGAREG_SEQU_ADDRESS); SET_FARVAR(seg, info->sequ0, inb(VGAREG_SEQU_DATA)); for (i=0; i<25; i++) { outb(i, crtc_addr); SET_FARVAR(seg, info->crtc_regs[i], inb(crtc_addr + 1)); } for (i=0; i<20; i++) { inb(VGAREG_ACTL_RESET); outb(i | (ar_index & 0x20), VGAREG_ACTL_ADDRESS); SET_FARVAR(seg, info->actl_regs[i], inb(VGAREG_ACTL_READ_DATA)); } inb(VGAREG_ACTL_RESET); for (i=0; i<9; i++) { outb(i, VGAREG_GRDC_ADDRESS); SET_FARVAR(seg, info->grdc_regs[i], inb(VGAREG_GRDC_DATA)); } SET_FARVAR(seg, info->crtc_addr, crtc_addr); /* XXX: read plane latches */ for (i=0; i<4; i++) SET_FARVAR(seg, info->plane_latch[i], 0); } void vgahw_restore_state(u16 seg, struct saveVideoHardware *info) { // Reset Attribute Ctl flip-flop inb(VGAREG_ACTL_RESET); u16 crtc_addr = GET_FARVAR(seg, info->crtc_addr); u16 i; for (i=0; i<4; i++) { outb(i+1, VGAREG_SEQU_ADDRESS); outb(GET_FARVAR(seg, info->sequ_regs[i]), VGAREG_SEQU_DATA); } outb(0, VGAREG_SEQU_ADDRESS); outb(GET_FARVAR(seg, info->sequ0), VGAREG_SEQU_DATA); // Disable CRTC write protection outw(0x0011, crtc_addr); // Set CRTC regs for (i=0; i<25; i++) if (i != 0x11) { outb(i, crtc_addr); outb(GET_FARVAR(seg, info->crtc_regs[i]), crtc_addr + 1); } // select crtc base address u16 v = inb(VGAREG_READ_MISC_OUTPUT) & ~0x01; if (crtc_addr == VGAREG_VGA_CRTC_ADDRESS) v |= 0x01; outb(v, VGAREG_WRITE_MISC_OUTPUT); // enable write protection if needed outb(0x11, crtc_addr); outb(GET_FARVAR(seg, info->crtc_regs[0x11]), crtc_addr + 1); // Set Attribute Ctl u16 ar_index = GET_FARVAR(seg, info->actl_index); inb(VGAREG_ACTL_RESET); for (i=0; i<20; i++) { outb(i | (ar_index & 0x20), VGAREG_ACTL_ADDRESS); outb(GET_FARVAR(seg, info->actl_regs[i]), VGAREG_ACTL_WRITE_DATA); } outb(ar_index, VGAREG_ACTL_ADDRESS); inb(VGAREG_ACTL_RESET); for (i=0; i<9; i++) { outb(i, VGAREG_GRDC_ADDRESS); outb(GET_FARVAR(seg, info->grdc_regs[i]), VGAREG_GRDC_DATA); } outb(GET_FARVAR(seg, info->sequ_index), VGAREG_SEQU_ADDRESS); outb(GET_FARVAR(seg, info->crtc_index), crtc_addr); outb(GET_FARVAR(seg, info->grdc_index), VGAREG_GRDC_ADDRESS); outb(GET_FARVAR(seg, info->feature), crtc_addr - 0x4 + 0xa); } void vgahw_set_mode(struct VideoParam_s *vparam_g) { // Reset Attribute Ctl flip-flop inb(VGAREG_ACTL_RESET); // Set Attribute Ctl u16 i; for (i = 0; i <= 0x13; i++) { outb(i, VGAREG_ACTL_ADDRESS); outb(GET_GLOBAL(vparam_g->actl_regs[i]), VGAREG_ACTL_WRITE_DATA); } outb(0x14, VGAREG_ACTL_ADDRESS); outb(0x00, VGAREG_ACTL_WRITE_DATA); // Set Sequencer Ctl outb(0, VGAREG_SEQU_ADDRESS); outb(0x03, VGAREG_SEQU_DATA); for (i = 1; i <= 4; i++) { outb(i, VGAREG_SEQU_ADDRESS); outb(GET_GLOBAL(vparam_g->sequ_regs[i - 1]), VGAREG_SEQU_DATA); } // Set Grafx Ctl for (i = 0; i <= 8; i++) { outb(i, VGAREG_GRDC_ADDRESS); outb(GET_GLOBAL(vparam_g->grdc_regs[i]), VGAREG_GRDC_DATA); } // Set CRTC address VGA or MDA u8 miscreg = GET_GLOBAL(vparam_g->miscreg); u16 crtc_addr = VGAREG_VGA_CRTC_ADDRESS; if (!(miscreg & 1)) crtc_addr = VGAREG_MDA_CRTC_ADDRESS; // Disable CRTC write protection outw(0x0011, crtc_addr); // Set CRTC regs for (i = 0; i <= 0x18; i++) { outb(i, crtc_addr); outb(GET_GLOBAL(vparam_g->crtc_regs[i]), crtc_addr + 1); } // Set the misc register outb(miscreg, VGAREG_WRITE_MISC_OUTPUT); // Enable video outb(0x20, VGAREG_ACTL_ADDRESS); inb(VGAREG_ACTL_RESET); } /**************************************************************** * Misc ****************************************************************/ void vgahw_enable_video_addressing(u8 disable) { u8 v = (disable & 1) ? 0x00 : 0x02; u8 v2 = inb(VGAREG_READ_MISC_OUTPUT) & ~0x02; outb(v | v2, VGAREG_WRITE_MISC_OUTPUT); } void vgahw_init(void) { // switch to color mode and enable CPU access 480 lines outb(0xc3, VGAREG_WRITE_MISC_OUTPUT); // more than 64k 3C4/04 outb(0x04, VGAREG_SEQU_ADDRESS); outb(0x02, VGAREG_SEQU_DATA); }
25.17446
74
0.614917
ffe12cea23874618260d0ef5d78532ff45da5ff1
3,531
h
C
src/PCS_Stream.h
cmb69/pecl-pcs
a7fce01398424fe100f78c71b113c7086e9ca585
[ "PHP-3.01" ]
29
2015-11-03T14:50:56.000Z
2020-10-13T02:10:48.000Z
src/PCS_Stream.h
cmb69/pecl-pcs
a7fce01398424fe100f78c71b113c7086e9ca585
[ "PHP-3.01" ]
14
2015-11-29T06:23:34.000Z
2020-12-03T17:16:54.000Z
src/PCS_Stream.h
cmb69/pecl-pcs
a7fce01398424fe100f78c71b113c7086e9ca585
[ "PHP-3.01" ]
3
2015-11-29T06:35:40.000Z
2020-06-13T15:09:33.000Z
/* +----------------------------------------------------------------------+ | PCS extension <http://pcs.tekwire.net> | +----------------------------------------------------------------------+ | Copyright (c) 2015 The PHP Group | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt. | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Author: Francois Laupretre <francois@tekwire.net> | +----------------------------------------------------------------------+ */ #ifndef __PCS_STREAM_H #define __PCS_STREAM_H #include "Zend/zend_hash.h" /*============================================================================*/ typedef struct { int persistent; zend_off_t offset; int show_errors; PCS_Node *node; HashPosition pos; /* readdir() position */ } PCS_STREAM_DATA; /*----------------------------------------*/ #define PCS_DP_FILE_DATA(_dp) (_dp)->node.u.f.data #define PCS_DP_FILE_LEN(_dp) (_dp)->node.u.f.len #define PCS_DP_DIR_HT(_dp) (_dp)->node.u.d.items /*============================================================================*/ static PCS_STREAM_DATA *new_dp(int show_errors, int persistent); static void free_dp(PCS_STREAM_DATA **dpp); static size_t PCS_Stream_read(php_stream *stream, char *buf, size_t count TSRMLS_DC); static int PCS_Stream_close(php_stream *stream, int close_handle TSRMLS_DC); static int PCS_Stream_seek(php_stream *stream, zend_off_t offset, int whence, zend_off_t *newoffset TSRMLS_DC); static PCS_Node *PCS_Stream_getNodeFromURI(const char *uri, size_t len); static int do_stat(php_stream_wrapper *wrapper, const char *uri, PCS_STREAM_DATA *dp, php_stream_statbuf *ssb TSRMLS_DC); static int PCS_Stream_fstat(php_stream *stream, php_stream_statbuf *ssb TSRMLS_DC); static size_t PCS_Stream_readdir(php_stream *stream, char *buf, size_t count TSRMLS_DC); static int PCS_Stream_seekdir(php_stream *stream, zend_off_t offset, int whence, zend_off_t *newoffset TSRMLS_DC); static php_stream *PCS_Stream_generic_open(int dir, php_stream_wrapper *wrapper, const char *uri, const char *mode, int options, OPENED_PATH_PTR *opened_path, php_stream_context *context STREAMS_DC TSRMLS_DC); static php_stream *PCS_Stream_openfile(php_stream_wrapper * wrapper, COMPAT_STREAM_CONST_DECL char *uri, COMPAT_STREAM_CONST_DECL char *mode, int options, OPENED_PATH_PTR *opened_path, php_stream_context *context STREAMS_DC TSRMLS_DC); static int PCS_Stream_url_stat(php_stream_wrapper *wrapper, COMPAT_STREAM_CONST_DECL char *uri, int flags, php_stream_statbuf *ssb, php_stream_context *context TSRMLS_DC); static php_stream *PCS_Stream_opendir(php_stream_wrapper * wrapper, COMPAT_STREAM_CONST_DECL char *uri, COMPAT_STREAM_CONST_DECL char *mode, int options, OPENED_PATH_PTR *opened_path, php_stream_context *context STREAMS_DC TSRMLS_DC); /*============================================================================*/ #endif
59.847458
235
0.607193
ffe2637aeb31240a3ce81fd510bfeee4c0e71b6d
2,797
h
C
linux-4.14.90-dev/linux-4.14.90/arch/tile/include/asm/fixmap.h
bingchunjin/1806_SDK
d5ed0258fc22f60e00ec025b802d175f33da6e41
[ "MIT" ]
55
2019-12-20T03:25:14.000Z
2022-01-16T07:19:47.000Z
linux-4.14.90-dev/linux-4.14.90/arch/tile/include/asm/fixmap.h
bingchunjin/1806_SDK
d5ed0258fc22f60e00ec025b802d175f33da6e41
[ "MIT" ]
5
2020-04-04T09:24:09.000Z
2020-04-19T12:33:55.000Z
linux-4.14.90-dev/linux-4.14.90/arch/tile/include/asm/fixmap.h
bingchunjin/1806_SDK
d5ed0258fc22f60e00ec025b802d175f33da6e41
[ "MIT" ]
30
2018-05-02T08:43:27.000Z
2022-01-23T03:25:54.000Z
/* * Copyright (C) 1998 Ingo Molnar * Copyright 2010 Tilera Corporation. All Rights Reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation, version 2. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, GOOD TITLE or * NON INFRINGEMENT. See the GNU General Public License for * more details. */ #ifndef _ASM_TILE_FIXMAP_H #define _ASM_TILE_FIXMAP_H #include <asm/page.h> #ifndef __ASSEMBLY__ #include <linux/kernel.h> #ifdef CONFIG_HIGHMEM #include <linux/threads.h> #include <asm/kmap_types.h> #endif /* * Here we define all the compile-time 'special' virtual * addresses. The point is to have a constant address at * compile time, but to set the physical address only * in the boot process. We allocate these special addresses * from the end of supervisor virtual memory backwards. * Also this lets us do fail-safe vmalloc(), we * can guarantee that these special addresses and * vmalloc()-ed addresses never overlap. * * these 'compile-time allocated' memory buffers are * fixed-size 4k pages. (or larger if used with an increment * higher than 1) use fixmap_set(idx,phys) to associate * physical memory with fixmap indices. * * TLB entries of such buffers will not be flushed across * task switches. */ enum fixed_addresses { #ifdef __tilegx__ /* * TILEPro has unmapped memory above so the hole isn't needed, * and in any case the hole pushes us over a single 16MB pmd. */ FIX_HOLE, #endif #ifdef CONFIG_HIGHMEM FIX_KMAP_BEGIN, /* reserved pte's for temporary kernel mappings */ FIX_KMAP_END = FIX_KMAP_BEGIN+(KM_TYPE_NR*NR_CPUS)-1, #endif #ifdef __tilegx__ /* see homecache.c */ FIX_HOMECACHE_BEGIN, FIX_HOMECACHE_END = FIX_HOMECACHE_BEGIN+(NR_CPUS)-1, #endif __end_of_permanent_fixed_addresses, /* * Temporary boot-time mappings, used before ioremap() is functional. * Not currently needed by the Tile architecture. */ #define NR_FIX_BTMAPS 0 #if NR_FIX_BTMAPS FIX_BTMAP_END = __end_of_permanent_fixed_addresses, FIX_BTMAP_BEGIN = FIX_BTMAP_END + NR_FIX_BTMAPS - 1, __end_of_fixed_addresses #else __end_of_fixed_addresses = __end_of_permanent_fixed_addresses #endif }; #define __FIXADDR_SIZE (__end_of_permanent_fixed_addresses << PAGE_SHIFT) #define __FIXADDR_BOOT_SIZE (__end_of_fixed_addresses << PAGE_SHIFT) #define FIXADDR_START (FIXADDR_TOP + PAGE_SIZE - __FIXADDR_SIZE) #define FIXADDR_BOOT_START (FIXADDR_TOP + PAGE_SIZE - __FIXADDR_BOOT_SIZE) #include <asm-generic/fixmap.h> #endif /* !__ASSEMBLY__ */ #endif /* _ASM_TILE_FIXMAP_H */
31.784091
74
0.763675
ffe3c5cc81d6f584d7fbd6215c06b3908b3e68e2
1,023
c
C
lab1/lab1.c
macarl08/esc190_coursework
b5e82d824fd05a2b8dd93c26ed0d2a9e1e797691
[ "MIT" ]
null
null
null
lab1/lab1.c
macarl08/esc190_coursework
b5e82d824fd05a2b8dd93c26ed0d2a9e1e797691
[ "MIT" ]
null
null
null
lab1/lab1.c
macarl08/esc190_coursework
b5e82d824fd05a2b8dd93c26ed0d2a9e1e797691
[ "MIT" ]
null
null
null
#include <math.h> #include <string.h> #include <stdio.h> double split_bill ( double base_amount , double tax_rate , double tip_rate , int num_people ) { double final_bill; final_bill = base_amount * (1+tax_rate) * (1+tip_rate); double indv_bill = final_bill / num_people; int temp = indv_bill * 100; if (indv_bill * 100 > temp){ temp++; } return (double) temp/100; } double adjust_price ( double original_price ) { double adjusted_price; adjusted_price = 10 * pow(original_price,0.5); return adjusted_price; } int sandy_eats ( char menu_item [] ){ if (strchr(menu_item,'j')!=NULL || strchr(menu_item,'J')!=NULL){ return 0; } if (strchr(menu_item,'k')!=NULL || strchr(menu_item,'K')!=NULL){ return 0; } if (strchr(menu_item,'l')!=NULL || strchr(menu_item,'L')!=NULL){ return 0; } if (strstr(menu_item,"Fish")!=NULL || strstr(menu_item,"fish")!=NULL){ return 0; } if (strlen(menu_item)%2 != 0){ return 0; } return 1; } void imagine_fish ( char thing [] ){ strcat(thing,"fish"); }
20.058824
95
0.661779
ffe56fbed99eac32a0de11046ea2f8c20bc4bbcf
198
h
C
native/pipara.h
tettoon/pipara
0fa832d65a64d4f73e2fd930eb6897ab518ca853
[ "Apache-2.0" ]
null
null
null
native/pipara.h
tettoon/pipara
0fa832d65a64d4f73e2fd930eb6897ab518ca853
[ "Apache-2.0" ]
null
null
null
native/pipara.h
tettoon/pipara
0fa832d65a64d4f73e2fd930eb6897ab518ca853
[ "Apache-2.0" ]
null
null
null
#ifndef __PIPARA_H__ #define __PIPARA_H__ #include <stdint.h> #ifdef __cplusplus extern "C" { #endif int pipara_setup(void); int pipara_write(int8_t data); #ifdef __cplusplus } #endif #endif
9.9
30
0.747475
ffea39b7d646fe4435c896467e7d630b8dddfdd7
116
h
C
bin/include/shutdown.h
bassaer/myos
12daab27ca4dd0ea4cc55620b7e083052b5c6b5c
[ "Apache-2.0" ]
null
null
null
bin/include/shutdown.h
bassaer/myos
12daab27ca4dd0ea4cc55620b7e083052b5c6b5c
[ "Apache-2.0" ]
18
2019-10-13T15:54:05.000Z
2020-03-22T04:47:52.000Z
bin/include/shutdown.h
bassaer/myos
12daab27ca4dd0ea4cc55620b7e083052b5c6b5c
[ "Apache-2.0" ]
null
null
null
#ifndef MYOS_SHUTDOWN_H #define MYOS_SHUTDOWN_H #include <type.h> int shutdown(CHAR16 *args[], int size); #endif
12.888889
39
0.75
ffeed6b9c6f16233c619d51cb42a396e125d3335
4,280
h
C
reAction/Engine/Visual/GUI/glistbox.h
codetorex/reAction
6fa95a6666f00a17ba557384a3c67808f6548fe1
[ "MIT" ]
null
null
null
reAction/Engine/Visual/GUI/glistbox.h
codetorex/reAction
6fa95a6666f00a17ba557384a3c67808f6548fe1
[ "MIT" ]
null
null
null
reAction/Engine/Visual/GUI/glistbox.h
codetorex/reAction
6fa95a6666f00a17ba557384a3c67808f6548fe1
[ "MIT" ]
null
null
null
////////////////////////////////////////////////////////////////////////// /// LIST BOX ////////////////////////////////////////////////////////////////////////// GListBox::GListBox() { ListCount = 0; ListIndex = 0; ListData = 0; // scr.smin = 0; scr.value = 0; scr.pid = this; state = 0; onSelectionChanged = 0; list_fc[0] = 0.0f; list_fc[1] = 0.0f; list_fc[2] = 0.0f; list_fc[3] = 1.0f; viewmax = 0; pClass = this; void (GListBox::*A)(int,int,int,bool) = &GListBox::MouseUp; void (GListBox::*B)(int,int,int) = &GListBox::MouseWheel; void (GListBox::*C)() = &GListBox::LostFocus; AttachFunctionPointer(MouseUp0 ,A); AttachFunctionPointer(MouseWheel0 ,B); AttachFunctionPointer(LostFocus0 ,C); } void GListBox::MouseUp(int x,int y,int button,bool inside) { if (inside) { int newindex; if (ListCount < viewmax) { scr.value = 0; } newindex = scr.value + (int)(ceil(y / cskin->basefont->fsize)); if ( newindex > ListCount) return; if ( newindex < 0 ) return; if (newindex != ListIndex) { if ((*onSelectionChanged) != NULL) { void * f; void * pcls; f = (void*)((long)(*onSelectionChanged)); pcls = pEventClass; _asm { mov eax,newindex push eax mov eax,pcls cmp eax,0 je os mov ecx,pcls os: call f } } } ListIndex = newindex; } } void GListBox::LostFocus() { if ((*onLostFocus) != NULL) { void * f; void * pcls; f = (void*)((long)(*onLostFocus)); pcls = pEventClass; _asm { mov eax,pcls cmp eax,0 je os mov ecx,pcls os: call f } } } void GListBox::MouseWheel(int x,int y, int delta) { scr.value -= delta / WHEEL_DELTA; //120 is WHEEL_DELTA scr.valuechanged(); //QuickInfo("%i",delta); } void GListBox::refresh() { viewmax = (int)(ceil(h / cskin->basefont->fsize)+1); scr.w = cskin->vsb_w; scr.x = w - scr.w - cskin->sunkedge_quad[0].sc_h[1]+1; scr.y = cskin->sunkedge_quad[0].sc_h[2]-1; scr.h = h - cskin->sunkedge_quad[0].sc_h[3]-1; //scr.pid = this; scr.cskin = cskin; scr.stotal = 1; scr.svisible = viewmax-1; scr.initialize(); scr.refresh(); // shaftlen = h - cskin->vsb_h - cskin->vsb_h; SetRelative(); scr.SetRelative(); //scr.calcthings(); } void GListBox::doevents() { if (!visible) return; if (ListCount >= viewmax) { scr.doevents(); } DeliverEvents(); } void GListBox::update() { SetRelative(); //SetRelative(&scr); scr.update(); } void GListBox::render() { if (!visible) return; int stp; int lx,ly; // list x ,y glColor4f(1,1,1,1); glBindTexture(GL_TEXTURE_2D,cskin->skinID); cskin->sunkedge_quad[state].Render(this); glColor4f(list_fc[0],list_fc[1],list_fc[2],list_fc[3]); stp = cskin->basefont->fsize; ly = sy + stp+1; // start of y axis lx = sx + 3; mEngine.EScissor(sx,sy,w,h-3); if (ListCount < viewmax) { scr.value = 0; } for (int i=scr.value , rw=0 ;i<scr.value+viewmax,rw<viewmax;i++,rw++) { if (i == ListCount) { break; } if (i == ListIndex) { glLoadIdentity(); glBindTexture(GL_TEXTURE_2D,0); //glColor3b(87,104,127); glColor4f(0.341f,0.407f,0.5f,1.0f); glBegin(GL_QUADS); DrawQuad(sx+2,ly-stp+2,scr.sx+scr.w,ly+3,0,0,1,1); glEnd(); glColor4f(1,1,1,1); cskin->basefont->PrintText(lx,ly,ListData[i]); glColor4f(list_fc[0],list_fc[1],list_fc[2],list_fc[3]); } else { cskin->basefont->PrintText(lx,ly,ListData[i]); } ly = ly +stp; } //glDisable(GL_SCISSOR_TEST); mEngine.DScissor(); if (ListCount >= viewmax) { scr.render(); } } void GListBox::AddItem(char *st,...) { char text[256]; va_list ap; int slen; if (st == NULL) return; va_start(ap,st); vsprintf(text,st,ap); va_end(ap); slen = strlen(text); char* bos; bos = new char [slen+1]; strcpy(bos,text); Precache(); ListData[ListCount] = bos; bos = 0; //scr.smax = ListCount - viewmax+2; ListCount++; scr.stotal = ListCount; scr.initialize(); scr.refresh(); } void GListBox::Precache() { if ( ListCount == 0) { ListData = new char* [64]; return; } else { int k; k = ListCount % 64; // bitmaskla yap bunu kasmasin aq if (k == 0) { char** bos; bos = new char * [ListCount+64]; memcpy(bos,ListData,4 * ListCount); delete [] ListData; ListData = bos; } } }
17.833333
74
0.588318
fff25abffd02699100a39359a4dc8a3e9ea9dd50
169
h
C
src/include/color.h
OllieLollie1/Raspi3-Kernel
02512bfe5885b6d66216b2f68da27a80e664d540
[ "MIT" ]
11
2018-05-20T04:43:50.000Z
2020-01-25T21:23:38.000Z
src/include/color.h
LizardLad/Raspi3-Kernel
02512bfe5885b6d66216b2f68da27a80e664d540
[ "MIT" ]
null
null
null
src/include/color.h
LizardLad/Raspi3-Kernel
02512bfe5885b6d66216b2f68da27a80e664d540
[ "MIT" ]
2
2018-08-20T11:49:43.000Z
2018-12-30T23:37:02.000Z
#ifndef COLOR_H #define COLOR_H void hsv_to_rgb(double h, double s, double v, char *r, char *g, char *b); uint32_t rgb_to_hex(uint8_t r, uint8_t g, uint8_t b); #endif
21.125
73
0.727811
fff3dff75837e0bf01ed72416b94b7e4e8b62ab6
951
h
C
third-party/llvm/llvm-src/include/llvm/Transforms/Utils/MetaRenamer.h
jhh67/chapel
f041470e9b88b5fc4914c75aa5a37efcb46aa08f
[ "ECL-2.0", "Apache-2.0" ]
2,338
2018-06-19T17:34:51.000Z
2022-03-31T11:00:37.000Z
third-party/llvm/llvm-src/include/llvm/Transforms/Utils/MetaRenamer.h
jhh67/chapel
f041470e9b88b5fc4914c75aa5a37efcb46aa08f
[ "ECL-2.0", "Apache-2.0" ]
3,740
2019-01-23T15:36:48.000Z
2022-03-31T22:01:13.000Z
third-party/llvm/llvm-src/include/llvm/Transforms/Utils/MetaRenamer.h
jhh67/chapel
f041470e9b88b5fc4914c75aa5a37efcb46aa08f
[ "ECL-2.0", "Apache-2.0" ]
500
2019-01-23T07:49:22.000Z
2022-03-30T02:59:37.000Z
//===- MetaRenamer.h - Rename everything with metasyntatic names ----------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This pass renames everything with metasyntatic names. The intent is to use // this pass after bugpoint reduction to conceal the nature of the original // program. // //===----------------------------------------------------------------------===// #ifndef LLVM_TRANSFORMS_UTILS_METARENAMER_H #define LLVM_TRANSFORMS_UTILS_METARENAMER_H #include "llvm/IR/PassManager.h" namespace llvm { struct MetaRenamerPass : PassInfoMixin<MetaRenamerPass> { PreservedAnalyses run(Module &, ModuleAnalysisManager &); }; } // namespace llvm #endif // LLVM_TRANSFORMS_UTILS_METARENAMER_H
35.222222
80
0.633018
fff5a0183ec42b965a09397a2ec4f63eaf60ad61
1,020
c
C
C Programs/SpindleUsingJogs/CSS/SpindleJog.c
parhansson/KMotionX
9e827917572fee477fe7971f67709c4c2ee4f97a
[ "BSD-3-Clause" ]
17
2015-01-04T19:58:54.000Z
2020-12-15T07:01:14.000Z
C Programs/SpindleUsingJogs/CSS/SpindleJog.c
parhansson/KMotionX
9e827917572fee477fe7971f67709c4c2ee4f97a
[ "BSD-3-Clause" ]
6
2015-12-10T21:24:01.000Z
2020-02-27T23:35:24.000Z
C Programs/SpindleUsingJogs/CSS/SpindleJog.c
parhansson/KMotionX
9e827917572fee477fe7971f67709c4c2ee4f97a
[ "BSD-3-Clause" ]
16
2015-02-07T23:42:53.000Z
2022-01-22T06:09:43.000Z
#include "KMotionDef.h" #include "MySpindleDefs.h" int *css_mode = &persist.UserData[PC_COMM_CSS_MODE]; // Mode 1=Normal RPM mode. 2=CSS // desired speed is passed from KMotionCNC in variable KMVAR // save in user variable STATEVAR whether it was off, CW, or CCW (0,1,-1) // save in user variable SPEEDVAR the last desired speed main() { float speed = *(float *)&persist.UserData[KMVAR]; // value stored is actually a float float LastState = persist.UserData[STATEVAR]; // get last state persist.UserData[SPEEDVAR] = persist.UserData[KMVAR]; // Always save the last desired speed if (LastState==0 || *css_mode == 2) { // if spindle is off (or CSS mode) and User Changes the speed // just save the desired speed return 0; } // spindle is already on, so ramp to new speed if (USE_POS_NEG_VOLTAGE) Jog(SPINDLEAXIS,speed * FACTOR * LastState); else Jog(SPINDLEAXIS,speed * FACTOR); printf("Jogging Spindle %f counts/sec\n",speed * FACTOR); }
30
95
0.677451
fff5e529b5dad896ef493b41ba40bf17ea6daf75
867
c
C
shader/gl2/shadowmapping/pre_vertexshader.c
mahula/tdme2
0f74d35ae5d2cd33b1a410c09f0d45f250ca7a64
[ "BSD-3-Clause" ]
null
null
null
shader/gl2/shadowmapping/pre_vertexshader.c
mahula/tdme2
0f74d35ae5d2cd33b1a410c09f0d45f250ca7a64
[ "BSD-3-Clause" ]
null
null
null
shader/gl2/shadowmapping/pre_vertexshader.c
mahula/tdme2
0f74d35ae5d2cd33b1a410c09f0d45f250ca7a64
[ "BSD-3-Clause" ]
null
null
null
#version 100 precision highp float; attribute vec3 inVertex; attribute vec3 inNormal; attribute vec2 inTextureUV; attribute vec3 inOrigin; uniform mat4 mvpMatrix; uniform vec3 modelTranslation; uniform mat3 textureMatrix; uniform float time; // will be passed to fragment shader varying vec2 vsFragTextureUV; {$DEFINITIONS} {$FUNCTIONS} void main(){ #if defined(HAVE_TREE) mat4 shaderTransformMatrix = createTreeTransformMatrix(inOrigin, inVertex, modelTranslation); #elif defined(HAVE_FOLIAGE) mat4 shaderTransformMatrix = createFoliageTransformMatrix(inOrigin, inVertex, modelTranslation); #else mat4 shaderTransformMatrix = mat4(1.0); #endif // pass texture uv to fragment shader vsFragTextureUV = vec2(textureMatrix * vec3(inTextureUV, 1.0)); // compute gl position gl_Position = mvpMatrix * shaderTransformMatrix * vec4(inVertex, 1.0); }
22.815789
98
0.787774
fff91d91f45ad0cf3bace9eb835d9bf42af6eb40
3,992
c
C
Vk2D/Vk2D/Vk2D_Math/vk2d_mat4.c
Sausty/vk2d
fa38388dc16921a2e4a800a2ab5aa183a113b725
[ "MIT" ]
5
2021-07-24T19:53:46.000Z
2022-01-18T10:14:17.000Z
Vk2D/Vk2D/Vk2D_Math/vk2d_mat4.c
Sausty/vk2d
fa38388dc16921a2e4a800a2ab5aa183a113b725
[ "MIT" ]
null
null
null
Vk2D/Vk2D/Vk2D_Math/vk2d_mat4.c
Sausty/vk2d
fa38388dc16921a2e4a800a2ab5aa183a113b725
[ "MIT" ]
2
2021-07-24T20:19:34.000Z
2021-10-06T14:15:29.000Z
#include "vk2d_mat4.h" #include <stdlib.h> #define _USE_MATH_DEFINES #include <math.h> static f32 toRadians(f32 angle) { return (f32)(angle * M_PI / 180); } vk2d_mat4 vk2d_mat4_new() { vk2d_mat4 mat; vk2d_zero_memory(mat, sizeof(vk2d_mat4)); for (i32 i = 0; i < 16; i++) mat.data[i] = 0.0f; return mat; } vk2d_mat4 vk2d_mat4_identity() { vk2d_mat4 mat = vk2d_mat4_new(); mat.data[0 + 0 * 4] = 1.0f; mat.data[1 + 1 * 4] = 1.0f; mat.data[2 + 2 * 4] = 1.0f; mat.data[3 + 3 * 4] = 1.0f; return mat; } vk2d_mat4 vk2d_mat4_diagonal(f32 diagonal) { vk2d_mat4 mat = vk2d_mat4_new(); mat.data[0 + 0 * 4] = diagonal; mat.data[1 + 1 * 4] = diagonal; mat.data[2 + 2 * 4] = diagonal; mat.data[3 + 3 * 4] = diagonal; return mat; } vk2d_mat4 vk2d_mat4_multiply(vk2d_mat4 left, vk2d_mat4 right) { float data[16]; for (i32 row = 0; row < 4; row++) { for (i32 col = 0; col < 4; col++) { float sum = 0.0f; for (i32 e = 0; e < 4; e++) { sum += left.data[e + row * 4] * right.data[col + e * 4]; } data[col + row * 4] = sum; } } memcpy(left.data, data, 4 * 4 * sizeof(float)); return left; } vk2d_vec3 vk2d_mat4_multiply_v3(vk2d_mat4 left, vk2d_vec3 right) { f32 x = left.data[0 + 0 * 4] * right.x + left.data[0 + 1 * 4] * right.y + left.data[0 + 2 * 4] * right.z + left.data[0 + 3 * 4]; f32 y = left.data[1 + 0 * 4] * right.x + left.data[1 + 1 * 4] * right.y + left.data[1 + 2 * 4] * right.z + left.data[1 + 3 * 4]; f32 z = left.data[2 + 0 * 4] * right.x + left.data[2 + 1 * 4] * right.y + left.data[2 + 2 * 4] * right.z + left.data[2 + 3 * 4]; return vk2d_vec3_new(x, y, z); } vk2d_mat4 vk2d_mat4_translate(vk2d_vec3 vector) { vk2d_mat4 result = vk2d_mat4_identity(); result.data[0 + 3 * 4] = vector.x; result.data[1 + 3 * 4] = vector.y; result.data[2 + 3 * 4] = vector.z; return result; } vk2d_mat4 vk2d_mat4_scale(vk2d_vec3 vector) { vk2d_mat4 result = vk2d_mat4_identity(); result.data[0 + 0 * 4] = vector.x; result.data[1 + 1 * 4] = vector.y; result.data[2 + 2 * 4] = vector.z; return result; } vk2d_mat4 vk2d_mat4_rotate(vk2d_vec3 vector, f32 angle) { vk2d_mat4 result = vk2d_mat4_identity(); f32 r = toRadians(angle); f32 c = (f32)cos(r); f32 s = (f32)sin(r); f32 omc = 1.0f - c; f32 x = vector.x; f32 y = vector.y; f32 z = vector.z; // X result.data[0 + 0 * 4] = x * x * omc + c; result.data[0 + 1 * 4] = y * x * omc + z * s; result.data[0 + 2 * 4] = x * z * omc - y * s; // Y result.data[1 + 0 * 4] = x * y * omc - z * s; result.data[1 + 1 * 4] = y * y * omc + c; result.data[1 + 2 * 4] = y * z * omc + x * s; // Z result.data[2 + 0 * 4] = x * z * omc + y * s; result.data[2 + 1 * 4] = y * z * omc - x * s; result.data[2 + 2 * 4] = z * z * omc + c; return result; } vk2d_mat4 vk2d_mat4_orthographic(f32 left, f32 right, f32 bottom, f32 top, f32 near, f32 far) { vk2d_mat4 result = vk2d_mat4_identity(); result.data[0 + 0 * 4] = 2.0f / (right - left); result.data[1 + 1 * 4] = 2.0f / (top - bottom); result.data[2 + 2 * 4] = 2.0f / (near - far); result.data[3 + 0 * 4] = (left + right) / (left - right); result.data[3 + 1 * 4] = (bottom + top) / (bottom - top); result.data[3 + 2 * 4] = (far + near) / (far - near); return result; } vk2d_mat4 vk2d_mat4_perspective(f32 fov, f32 aspectRatio, f32 near, f32 far) { vk2d_mat4 result = vk2d_mat4_identity(); f32 q = 1.0f / (f32)tan(toRadians(0.5f * fov)); f32 a = q / aspectRatio; f32 b = (near + far) / (near - far); f32 c = (2.0f * near * far) / (near - far); result.data[0 + 0 * 4] = a; result.data[1 + 1 * 4] = q; result.data[2 + 2 * 4] = b; result.data[2 + 3 * 4] = -1.0f; result.data[3 + 2 * 4] = c; return result; }
24.95
132
0.537325
2b137f81d10d5099c8c8738b93c9fa064ebe69dc
13,854
h
C
include/dm/datastructures/sparsearray.h
dariomanesku/dm
9d00106d1cd94d1e297f8cf4f1d6765ef2aaab05
[ "BSD-2-Clause" ]
16
2015-11-17T13:24:33.000Z
2021-10-31T22:40:41.000Z
include/dm/datastructures/sparsearray.h
dariomanesku/dm
9d00106d1cd94d1e297f8cf4f1d6765ef2aaab05
[ "BSD-2-Clause" ]
1
2017-03-27T02:55:42.000Z
2017-03-28T21:16:36.000Z
include/dm/datastructures/sparsearray.h
dariomanesku/dm
9d00106d1cd94d1e297f8cf4f1d6765ef2aaab05
[ "BSD-2-Clause" ]
6
2015-04-01T14:35:40.000Z
2021-07-15T12:28:26.000Z
/* * Copyright 2016 Dario Manesku. All rights reserved. * License: http://www.opensource.org/licenses/BSD-2-Clause */ #include "../dm.h" /// Header includes. #if (DM_INCL & DM_INCL_HEADER_INCLUDES) #include <new> #include "../check.h" #include "../allocatori.h" #include "handlealloc.h" #endif // (DM_INCL & DM_INCL_HEADER_INCLUDES) /// Header body. #if (DM_INCL & DM_INCL_HEADER_BODY) # if (DM_INCL & DM_INCL_HEADER_BODY_OPT_REMOVE_HEADER_GUARD) # undef DM_SPARSEARRAY_HEADER_GUARD # endif // if (DM_INCL & DM_INCL_HEADER_BODY_OPT_REMOVE_HEADER_GUARD) # ifndef DM_SPARSEARRAY_HEADER_GUARD # define DM_SPARSEARRAY_HEADER_GUARD namespace DM_NAMESPACE { template <typename SparseArrayStorageTy> struct SparseArrayImpl : SparseArrayStorageTy { /// Expected interface: /// /// template <typename Ty> /// struct SparseArrayStorageT /// { /// typedef Ty ObjectType; /// typedef HandleAllocT<MaxT> HandleAllocType; /// /// bool isResizable() const; /// Ty* elements(); /// HandleAllocType* handles(); /// uint32_t max() const; /// }; typedef typename SparseArrayStorageTy::ObjectType Ty; typedef typename SparseArrayStorageTy::HandleAllocType HandleAllocTy; using SparseArrayStorageTy::isResizable; using SparseArrayStorageTy::resize; using SparseArrayStorageTy::elements; using SparseArrayStorageTy::handles; using SparseArrayStorageTy::max; SparseArrayImpl() : SparseArrayStorageTy() { } Ty* addNew() { if (isResizable()) { const uint32_t maxObj = max(); if (count() == maxObj) { const uint32_t newMax = maxObj+(maxObj>>1); resize(newMax); } } const uint32_t handle = (uint32_t)handles()->alloc(); DM_CHECK(handle < max(), "SparseArrayImpl::addNew() | %d, %d", handle, max()); Ty* dst = &elements()[handle]; dst = ::new (dst) Ty(); return dst; } uint32_t addObj(const Ty* _obj) { if (isResizable()) { const uint32_t maxObj = max(); if (count() == maxObj) { const uint32_t newMax = maxObj+(maxObj>>1); resize(newMax); } } const uint32_t handle = (uint32_t)handles()->alloc(); DM_CHECK(handle < max(), "SparseArrayImpl::addCopy() | %d, %d", handle, max()); Ty* dst = &elements()[handle]; dst = ::new (dst) Ty(*_obj); return handle; } uint32_t addVal(Ty _val) { if (isResizable()) { const uint32_t maxObj = max(); if (count() == maxObj) { const uint32_t newMax = maxObj+(maxObj>>1); resize(newMax); } } const uint32_t handle = (uint32_t)handles()->alloc(); DM_CHECK(handle < max(), "SparseArrayImpl::addCopy() | %d, %d", handle, max()); elements()[handle] = _val; return handle; } bool contains(const Ty* _obj) { return (&elements()[0] <= _obj && _obj < &elements()[max()]); } uint32_t getHandleOf(const Ty* _obj) { DM_CHECK(contains(_obj), "SparseArrayImpl::getHandleOf() | Object not from the list."); return uint32_t(_obj - elements()); } Ty& operator[](uint32_t _handle) { DM_CHECK(_handle < max(), "SparseArrayImpl::operator[]() | %d, %d", _handle, max()); return elements()[_handle]; } const Ty& operator[](uint32_t _handle) const { DM_CHECK(_handle < max(), "SparseArrayImpl::operator[]() const | %d, %d", _handle, max()); return elements()[_handle]; } Ty* getObj(uint32_t _handle) { DM_CHECK(_handle < max(), "SparseArrayImpl::getObj() | %d, %d", _handle, max()); return &elements()[_handle]; } Ty getVal(uint32_t _handle) { DM_CHECK(_handle < max(), "SparseArrayImpl::getVal() | %d, %d", _handle, max()); return elements()[_handle]; } /// Used for iteration over all elements. uint32_t getHandleAt(uint32_t _idx) { return handles()->getHandleAt(_idx); } /// Used for iteration over all elements. Ty* getObjFromHandleAt(uint32_t _idx) { const uint32_t handle = handles()->getHandleAt(_idx); return getObj(handle); } /// Used for iteration over all elements. Ty* getValFromHandleAt(uint32_t _idx) { const uint32_t handle = handles()->getHandleAt(_idx); return getVal(handle); } void remove(uint32_t _handle) { DM_CHECK(_handle < max(), "SparseArrayImpl::removeAt() | %d, %d", _handle, max()); elements()[_handle].~Ty(); handles()->free(_handle); } void removeFromHandleAt(uint32_t _idx) { const uint32_t handle = handles()->getHandleAt(_idx); remove(handle); } void removeObj(const Ty* _obj) { const uint32_t handle = getHandleOf(_obj); remove(handle); } void removeAll() { for (uint32_t ii = count(); ii--; ) { const uint32_t handle = handles()->getHandleAt(ii); remove(handle); } } void compact() { const uint32_t end = count(); if (end <= 1) { return; } handles()->sort(); uint32_t idx = 0; uint32_t prev; uint32_t curr = handles()->getHandleAt(0); bool inOrder = (0 == curr); for (;;) { prev = curr; if (inOrder) { idx++; } else { uint32_t dst = 0; uint32_t src = curr; uint32_t cnt = 1; for (; cnt < end; ++cnt) { const uint32_t next = handles()->getHandleAt(cnt); if (next-prev != 1) { break; } prev = next; } if (cnt > curr) { memmove(&elements()[dst], &elements()[src], cnt*sizeof(Ty)); } else { memcpy(&elements()[dst], &elements()[src], cnt*sizeof(Ty)); } idx += cnt; } if (idx >= end) { break; } curr = handles()->getHandleAt(idx); const uint32_t diff = curr - prev; inOrder = (1 == diff); } // Reset handle alloc. typename HandleAllocTy::HandleTy* han = handles()->handles(); typename HandleAllocTy::HandleTy* ind = handles()->indices(); for (uint32_t ii = 0, iiEnd = handles()->max(); ii < iiEnd; ++ii) { han[ii] = ii; } for (uint32_t ii = 0; ii < end; ++ii) { ind[ii] = ii; } } void reset() { handles().reset(); } void zero() { memset(elements(), 0, max()*sizeof(Ty)); } uint32_t count() { return handles()->count(); } }; template <typename Ty, uint32_t MaxT> struct SparseArrayStorageT { typedef Ty ObjectType; typedef HandleAllocT<MaxT> HandleAllocType; bool isResizable() const { return false; } void resize(uint32_t /*_max*/) { } Ty* elements() { return m_elements; } HandleAllocType* handles() { return &m_handles; } uint32_t max() const { return MaxT; } HandleAllocType m_handles; Ty m_elements[MaxT]; }; template <typename Ty> struct SparseArrayStorageExt { typedef Ty ObjectType; typedef HandleAllocExt<uint32_t> HandleAllocType; bool isResizable() const { return false; } void resize(uint32_t /*_max*/) { } static uint32_t sizeFor(uint32_t _max) { return _max*sizeof(Ty) + HandleAllocType::sizeFor(_max); } SparseArrayStorageExt() { m_max = 0; m_elements = NULL; } uint8_t* init(uint32_t _max, uint8_t* _mem) { uint8_t* objBegin = (uint8_t*)_mem; uint8_t* handleBegin = (uint8_t*)_mem + _max*sizeof(Ty); m_max = _max; m_elements = (Ty*)objBegin; uint8_t* end = m_handles.init(_max, handleBegin); return end; } Ty* elements() { return m_elements; } HandleAllocType* handles() { return &m_handles; } uint32_t max() const { return m_max; } uint32_t m_max; Ty* m_elements; HandleAllocType m_handles; }; extern CrtAllocator g_crtAllocator; template <typename Ty> struct SparseArrayStorage { typedef Ty ObjectType; typedef HandleAllocExt<uint32_t> HandleAllocType; bool isResizable() const { return false; } void resize(uint32_t /*_max*/) { } static uint32_t sizeFor(uint32_t _max) { return _max*sizeof(Ty) + HandleAllocType::sizeFor(_max); } SparseArrayStorage() { m_max = 0; m_elements = NULL; } void init(uint32_t _max, AllocatorI* _allocator = &g_crtAllocator) { const uint32_t totalSize = sizeFor(_max); void* mem = DM_ALLOC(_allocator, totalSize); uint8_t* objBegin = (uint8_t*)mem; uint8_t* handleBegin = (uint8_t*)mem + _max*sizeof(Ty); m_max = _max; m_elements = (Ty*)objBegin; m_handles.init(_max, handleBegin); m_allocator = _allocator; } void destroy() { if (NULL != m_elements) { DM_FREE(m_allocator, m_elements); m_elements = NULL; } } Ty* elements() { return m_elements; } HandleAllocType* handles() { return &m_handles; } uint32_t max() const { return m_max; } uint32_t m_max; Ty* m_elements; HandleAllocType m_handles; AllocatorI* m_allocator; }; template <typename Ty> struct SparseArrayStorageRes { typedef Ty ObjectType; typedef HandleAllocRes<uint32_t> HandleAllocType; SparseArrayStorageRes() { m_max = 0; m_elements = NULL; } void init(uint32_t _max, AllocatorI* _allocator = &g_crtAllocator) { const uint32_t size = _max*sizeof(Ty); m_max = _max; m_elements = (Ty*)DM_ALLOC(_allocator, size); m_handles.init(_max, _allocator); m_allocator = _allocator; } bool isResizable() const { return true; } void resize(uint32_t _newMax) { const uint32_t size = _newMax*sizeof(Ty); m_max = _newMax; m_elements = (Ty*)DM_REALLOC(m_allocator, m_elements, size); m_handles.resize(_newMax); } void destroy() { if (NULL != m_elements) { DM_FREE(m_allocator, m_elements); m_elements = NULL; } } Ty* elements() { return m_elements; } HandleAllocType* handles() { return &m_handles; } uint32_t max() const { return m_max; } uint32_t m_max; Ty* m_elements; HandleAllocType m_handles; AllocatorI* m_allocator; }; template <typename Ty, uint32_t MaxT> struct SparseArrayT : SparseArrayImpl< SparseArrayStorageT<Ty, MaxT> > { }; template <typename Ty> struct SparseArrayExt : SparseArrayImpl< SparseArrayStorageExt<Ty> > { }; template <typename Ty> struct SparseArray : SparseArrayImpl< SparseArrayStorage<Ty> > { }; template <typename Ty> struct SparseArrayRes : SparseArrayImpl< SparseArrayStorage<Ty> > { }; template <typename Ty> struct SparseArrayH : SparseArrayExt<Ty> { AllocatorI* m_allocator; }; } // namespace DM_NAMESPACE # endif // DM_SPARSEARRAY_HEADER_GUARD #endif // (DM_INCL & DM_INCL_HEADER_BODY) /* vim: set sw=4 ts=4 expandtab: */
26.139623
119
0.479934
2b16b2e17add65a54e16827463dcf6eaefa2543e
1,120
c
C
src/uart.c
prushik/avr_misc
b72bc667c95a5ae7a25b70d5171f7cc4e38d4119
[ "MIT" ]
null
null
null
src/uart.c
prushik/avr_misc
b72bc667c95a5ae7a25b70d5171f7cc4e38d4119
[ "MIT" ]
null
null
null
src/uart.c
prushik/avr_misc
b72bc667c95a5ae7a25b70d5171f7cc4e38d4119
[ "MIT" ]
null
null
null
// This should definitely be defined in the application or like a config header or some shit. #include "config.h" #include <avr/io.h> #include <util/setbaud.h> #include "uart.h" //init void uart_init() { UBRR0H = UBRRH_VALUE; UBRR0L = UBRRL_VALUE; #if USE_2X UCSR0A |= _BV(U2X0); #else UCSR0A &= ~(_BV(U2X0)); #endif UCSR0C = _BV(UCSZ01) | _BV(UCSZ00); /* 8-bit data */ UCSR0B = _BV(RXEN0) | _BV(TXEN0); /* Enable RX and TX */ } //blocking void uart_putchar(unsigned char c) { loop_until_bit_is_set(UCSR0A, UDRE0); /* Wait until data register empty. */ UDR0 = c; loop_until_bit_is_set(UCSR0A, TXC0); /* Wait until transmission ready. */ } // same thing, but don't block void uart_send_char(unsigned char c) { UDR0 = c; } //blocking void uart_write(char *data, unsigned int len) { int i; for (i=0; i < len; i++) { uart_putchar(data[i]); } } //blocking char uart_getchar() { loop_until_bit_is_set(UCSR0A, RXC0); /* Wait until data exists. */ return UDR0; } //nonblocking char uart_read_char(unsigned char *a) { if (UCSR0A & _BV(RXC0)) { *a = UDR0; return 1; } else { return 0; } }
16.470588
93
0.666071
2b16cbb6af065af9901f48d6179978d035bde5c9
4,562
h
C
src/Squirrel/src/SQIParser.h
clasqm/Squirrel99
09fb4cf9c26433b5bc1915dee1b31178222d9e81
[ "MIT" ]
2
2019-01-26T14:35:33.000Z
2020-03-31T10:39:39.000Z
src/Squirrel/src/SQIParser.h
clasqm/Squirrel99
09fb4cf9c26433b5bc1915dee1b31178222d9e81
[ "MIT" ]
1
2018-12-12T17:04:17.000Z
2018-12-12T17:04:17.000Z
src/Squirrel/src/SQIParser.h
clasqm/Squirrel99
09fb4cf9c26433b5bc1915dee1b31178222d9e81
[ "MIT" ]
1
2020-10-26T08:56:12.000Z
2020-10-26T08:56:12.000Z
/* * SQIParser: P a r s e r H e a d e r * * Generated from: SQI-grammar.g * * Terence Parr, Russell Quong, Will Cohen, and Hank Dietz: 1989-1999 * Parr Research Corporation * with Purdue University Electrical Engineering * with AHPCRC, University of Minnesota * ANTLR Version 1.33MR20 */ #ifndef SQIParser_h #define SQIParser_h #ifndef ANTLR_VERSION #define ANTLR_VERSION 13320 #endif #include "AParser.h" #ifndef sqiheader #define sqiheader #include "SQI-Obj.h" #include "SQI-heap.h" #include "SQI-exception.h" #include "SQI-varmap.h" #include "SQI-ufunc.h" #include "SQI-interp.h" #include "SQI-squirrel.h" #include "SQI-builtin.h" #include "SQI-clean.h" #include <stack> extern stack <char *> TheFilenames; #endif class SQIParser : public ANTLRParser { public: static const ANTLRChar *tokenName(int tk); protected: static const ANTLRChar *_token_tbl[]; private: public: virtual void syn(_ANTLRTokenPtr tok, ANTLRChar *egroup, SetWordType *eset,ANTLRTokenType etok, int k) { int line; line = LT(1)->getLine(); syntaxErrCount++; /* MR11 */ fprintf(stderr, "%s [line %d] syntax error at \"%s\"",TheFilenames.top(),line, LT(1)->getText()); if ( !etok && !eset ) {fprintf(stderr, "\n"); return;} if ( k==1 ) fprintf(stderr, " missing"); else { fprintf(stderr, "; \"%s\" not", LT(1)->getText()); if ( set_deg(eset)>1 ) fprintf(stderr, " in"); } if ( set_deg(eset)>0 ) edecode(eset); else fprintf(stderr, " %s", token_tbl[etok]); if ( strlen(egroup) > 0 ) fprintf(stderr, " in %s", egroup); fprintf(stderr, "\n"); }; protected: static SetWordType COMMENT_set[16]; static SetWordType RC_set[16]; static SetWordType setwd1[109]; static SetWordType ID_set[16]; static SetWordType setwd2[109]; static SetWordType setwd3[109]; static SetWordType setwd4[109]; static SetWordType RRC_set[16]; static SetWordType setwd5[109]; static SetWordType EXP_OP_set[16]; static SetWordType setwd6[109]; static SetWordType ADD_OP_set[16]; static SetWordType MULT_OP_set[16]; static SetWordType MOD_OP_set[16]; static SetWordType setwd7[109]; static SetWordType REL_OP_set[16]; static SetWordType BOOL_OP_set[16]; static SetWordType WORD_set[16]; static SetWordType setwd8[109]; static SetWordType setwd9[109]; static SetWordType setwd10[109]; private: void zzdflthandlers( int _signal, int *_retsignal ); public: SQIParser(ANTLRTokenBuffer *input); SQI_nBlock * interp(int *_retsignal, SQI_Interp *Interp ); SQI_Object * instruction(int *_retsignal, SQI_Interp *Interp ); SQI_Object * predicate(int *_retsignal, SQI_Interp *Interp ); void funcdef(int *_retsignal, SQI_Interp *Interp ); list<SQI_Object *> * lparam(int *_retsignal, SQI_Interp *Interp ); SQI_Object * eparam(int *_retsignal, SQI_Interp *Interp ); SQI_nBlock * funcbody(int *_retsignal, SQI_Interp *Interp ); SQI_Object * bodyinst(int *_retsignal, SQI_Interp *Interp ); SQI_Object * call(int *_retsignal, SQI_Interp *Interp ); list<SQI_Object *> * arguments(int *_retsignal, SQI_Interp *Interp ); SQI_Object * argument(int *_retsignal, SQI_Interp *Interp ); SQI_Object * basic(int *_retsignal, SQI_Interp *Interp ); SQI_Object * counter(int *_retsignal, SQI_Interp *Interp ); SQI_Object * expression(int *_retsignal, SQI_Interp *Interp ); SQI_List * alist(int *_retsignal, SQI_Interp *Interp ); SQI_Object * elist(int *_retsignal, SQI_Interp *Interp ); SQI_Object * block(int *_retsignal, SQI_Interp *Interp ); SQI_Object * simple(int *_retsignal, SQI_Interp *Interp ); SQI_Object * boolnegexpr(int *_retsignal, SQI_Interp *Interp ); SQI_Object * expexpr(int *_retsignal, SQI_Interp *Interp ); SQI_Object * signexpr(int *_retsignal, SQI_Interp *Interp ); SQI_Object * multexpr(int *_retsignal, SQI_Interp *Interp ); SQI_Object * modexpr(int *_retsignal, SQI_Interp *Interp ); SQI_Object * addexpr(int *_retsignal, SQI_Interp *Interp ); SQI_Object * relexpr(int *_retsignal, SQI_Interp *Interp ); SQI_Object * mexpr(int *_retsignal, SQI_Interp *Interp ); SQI_Object * variable(int *_retsignal, SQI_Interp *Interp ); SQI_Object * member(int *_retsignal, SQI_Interp *Interp ); SQI_Object * number(int *_retsignal, SQI_Interp *Interp ); SQI_String * quotedword(int *_retsignal, SQI_Interp *Interp ); SQI_Object * keyword(int *_retsignal, SQI_Interp *Interp ); SQI_Object * iblock(int *_retsignal, SQI_Interp *Interp ); SQI_nControl * control(int *_retsignal, SQI_Interp *Interp ); }; #endif /* SQIParser_h */
35.364341
104
0.715695
2b17f5525e740ba4eaf013bdd7a5cb16ff60a2b5
2,329
h
C
src/common/wrapper.h
bf77/p2p-live-streming-system
495a0e32e1072f3aa637aa5964a91e750d3d49f6
[ "MIT" ]
3
2018-10-11T09:11:23.000Z
2018-12-03T13:09:12.000Z
src/common/wrapper.h
bf77/p2p-live-streming-system
495a0e32e1072f3aa637aa5964a91e750d3d49f6
[ "MIT" ]
null
null
null
src/common/wrapper.h
bf77/p2p-live-streming-system
495a0e32e1072f3aa637aa5964a91e750d3d49f6
[ "MIT" ]
null
null
null
/* *---------------------------------------------------------------------------- * #define (in advance) *---------------------------------------------------------------------------- */ #define __STDC_FORMAT_MACROS /* *---------------------------------------------------------------------------- * #include *---------------------------------------------------------------------------- */ #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <string.h> #include <stdint.h> #include <errno.h> #include <math.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <inttypes.h> #include <time.h> #include <signal.h> /* *---------------------------------------------------------------------------- * #typedef *---------------------------------------------------------------------------- */ //Bytes related typedef uint64_t u64; typedef uint32_t u32; typedef unsigned short u16; typedef unsigned char u8; /* *---------------------------------------------------------------------------- * #define *---------------------------------------------------------------------------- */ #ifdef _DEBUG_ #define DEBUG_PRINTF printf #define DEBUG_DUMP Dump #else #define DEBUG_PRINTF 1 ? (void)0 : printf #define DEBUG_DUMP 1 ? (void)0 : Dump #endif //Time #define INTARVAL_SEC 3 #define INTARVAL_MSEC 5000 //Node #define MAX_CHILD_NUM 2 /* *---------------------------------------------------------------------------- * #Declaration *---------------------------------------------------------------------------- */ extern int SIG_INT_COUNT; //Timesamp struct timeval TIMESTAMP; struct timeval START_TIMESTAMP; struct timeval TIMEPROCESS_INTARVAL; extern int DETACH_NUM; extern int DEPART_NUM; extern int INC; /* *---------------------------------------------------------------------------- * #function() *---------------------------------------------------------------------------- */ //for debug void Dump( const u8 *buf , const int bytes ); void DebugTest(); void NanoSleep( time_t s , long n ); void GetTimestamp( struct timeval *timestamp ); void UpdateTimestamp( struct timeval *timestamp ); void DiffCurrentTime( struct timeval timestamp , struct timeval *diff_timestamp ); int IsExceedTime( struct timeval exceed_time , struct timeval tv ); void PrintTime( struct timeval timestamp );
24.010309
82
0.436668
2b19f5e16c6a4de03f11b175594b1f1579537a0b
625
c
C
src_experiment/exp_07_physical_operate/exp_07_06_delete.c
kele1997/DongmenDB
d267d1dedcb00ea5da05d9420a085bf5981a4dff
[ "Apache-2.0" ]
null
null
null
src_experiment/exp_07_physical_operate/exp_07_06_delete.c
kele1997/DongmenDB
d267d1dedcb00ea5da05d9420a085bf5981a4dff
[ "Apache-2.0" ]
null
null
null
src_experiment/exp_07_physical_operate/exp_07_06_delete.c
kele1997/DongmenDB
d267d1dedcb00ea5da05d9420a085bf5981a4dff
[ "Apache-2.0" ]
null
null
null
// // Created by sam on 2018/9/18. // #include "physicalplan/physicalplan.h" /*执行delete语句*/ int plan_execute_delete(dongmendb *db, sql_stmt_delete *sqlStmtDelete, transaction *tx){ /*删除语句以select的物理操作为基础实现。 * 1. 使用 sql_stmt_delete 的条件参数,调用 physical_scan_select_create 创建select的物理计划并初始化; * 2. 执行 select 的物理计划,完成 delete 操作 * */ physical_scan* scan=physical_scan_generate(db,sqlStmtDelete->where,tx); scan->beforeFirst(scan); int delete_lines=0; while(scan->next(scan)){ scan->deleterec(scan); delete_lines++; } scan->close(scan); return delete_lines; };
20.16129
89
0.6784
2b1c6e39ac87e2b049c8849d6b0a01acc8909aa1
1,374
c
C
Others/SimpleBubbleSort.c
farinap5/Learning-C
391388e9acdbebcc0dcbd777ed65b53b80da47fd
[ "MIT" ]
5
2021-04-12T14:48:29.000Z
2022-01-08T21:41:04.000Z
Others/SimpleBubbleSort.c
farinap5/Learning-C
391388e9acdbebcc0dcbd777ed65b53b80da47fd
[ "MIT" ]
null
null
null
Others/SimpleBubbleSort.c
farinap5/Learning-C
391388e9acdbebcc0dcbd777ed65b53b80da47fd
[ "MIT" ]
1
2021-04-11T15:32:55.000Z
2021-04-11T15:32:55.000Z
/* This program generates a array randomly and organizes showing step by step. Bubble Sort. Example: Array generated: 10 1 6 5 8 9 7 2 3 4 10 1 6 5 8 9 7 2 3 4 10 <- 1 1 10 6 5 8 9 7 2 3 4 10 <- 6 1 6 10 5 8 9 7 2 3 4 10 <- 5 1 6 5 10 8 9 7 2 3 4 6 <- 5 1 5 6 10 8 9 7 2 3 4 When it is done: 1 2 3 4 5 6 7 8 9 10 */ #include <stdio.h> #include <stdlib.h> #include <time.h> #include <unistd.h> int main() { int m[10]; srand(time(NULL)); // Generate a valid matrix without repeated numbers. for(int i=0;i < 10;i++) { int x, y; do { y = 0; x = (rand()%10)+1; for(int j=0;j<10;j++) { if (x == m[j]) y++; } } while (y != 0); m[i] = x; } //-------------------------------------------------- for(int i=0;i < 10;i++) printf("%d ",m[i]); printf("\n"); int y; do { y = 0; for(int i=0;i < 10;i++) { if(m[i] > m[i+1] && i != 9) { printf("%d <- %d\n",m[i],m[i+1]); int z = m[i]; m[i] = m[i+1]; m[i+1] = z; y++; break; } } for(int i=0;i < 10;i++) printf("%d ",m[i]); usleep(1000000); printf("\n"); } while(y != 0); return 0; }
18.821918
56
0.377729
2b1d767c7c153006d075f8d53945287c45694202
27,011
h
C
datatree/dt_core.h
paladin-t/datatree
387556f51bbabcd695e739a2ed10228a35e51eae
[ "WTFPL", "BSD-3-Clause" ]
null
null
null
datatree/dt_core.h
paladin-t/datatree
387556f51bbabcd695e739a2ed10228a35e51eae
[ "WTFPL", "BSD-3-Clause" ]
null
null
null
datatree/dt_core.h
paladin-t/datatree
387556f51bbabcd695e739a2ed10228a35e51eae
[ "WTFPL", "BSD-3-Clause" ]
1
2020-02-26T12:23:27.000Z
2020-02-26T12:23:27.000Z
#ifndef __DT_CORE_H__ #define __DT_CORE_H__ #ifdef _MSC_VER # define _CRTDBG_MAP_ALLOC # include <crtdbg.h> #endif /* _MSC_VER */ #include <stdlib.h> #include <stdio.h> #include <stdarg.h> #ifndef __APPLE__ # include <malloc.h> #endif /* __APPLE__ */ #include <assert.h> #include <math.h> #include "xpl/xpl.h" #ifdef _MSC_VER # ifdef INTE_COMPILE # define DT_API __declspec(dllexport) # else # define DT_API __declspec(dllimport) # endif #else # define DT_API __attribute__ ((visibility("default"))) #endif #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /** * @brief Whether enable alloc statistics * @note Now only enabled under DEBUG mode, this information is very useful * for memory occupation analyze and optimization during development * period, but could be economized in release; you can modify here to * change the strategy */ #if (defined _DEBUG && !defined NDEBUG) # ifndef DT_ENABLE_ALLOC_STAT # define DT_ENABLE_ALLOC_STAT # endif /* DT_ENABLE_ALLOC_STAT */ #endif /* (defined _DEBUG && !defined NDEBUG) */ /** * @brief Size of a pointer */ #ifndef DT_POINTER_SIZE # define DT_POINTER_SIZE (sizeof(void*)) #endif /* DT_POINTER_SIZE */ /** * @brief Run time assertion */ #ifndef DT_ASSERT # define DT_ASSERT(e) assert(e) #endif /* DT_ASSERT */ /** * @brief Compile time assertion */ #ifndef DT_STATIC_ASSERT # define _STATIC_ASSERT_IMPL(cond, msg) typedef char static_assertion_##msg[(!!(cond)) * 2 - 1] # define _COMPILE_TIME_ASSERT3(x, l) _STATIC_ASSERT_IMPL(x, static_assertion_at_line_##l) # define _COMPILE_TIME_ASSERT2(x, l) _COMPILE_TIME_ASSERT3(x, l) # define DT_STATIC_ASSERT(x) _COMPILE_TIME_ASSERT2(x, __LINE__) #endif /* DT_STATIC_ASSERT */ /** * @brief Gets the count of elements in an array */ #ifndef DT_COUNT_OF # define DT_COUNT_OF(a) (sizeof(a) / sizeof((a)[0])) #endif /* DT_COUNT_OF */ /** * @brief Gets the alignment of a structure */ #ifndef DT_ALIGN_OF # define DT_ALIGN_OF(s) (sizeof(struct { char _1; s _n; }) - sizeof(s)) #endif /* DT_ALIGN_OF */ /** * @brief Max string length for allocating, for common usage */ #ifndef DT_STR_LEN # define DT_STR_LEN 512 #endif /* DT_STR_LEN */ /** * @brief Target platform endian mode */ #ifndef DT_LITTLE_ENDIAN # define DT_LITTLE_ENDIAN #endif /* DT_LITTLE_ENDIAN */ /** * @brief Allocates on stack * @note Considering some compilers do not support this functionality well, * please redefine this with some other things like the original heap * malloc, and at the same time, don't forget to redefine DT_DEALLOCA * as well */ #ifndef DT_ALLOCA # define DT_ALLOCA(s) alloca(s) #endif /* DT_ALLOCA */ /** * @brief Frees allocated memory on stack * @note Considering some compilers do not support allocation on stack well, * please redefine DT_ALLOCA and DT_DEALLOCA */ #ifndef DT_DEALLOCA # define DT_DEALLOCA(p) (void)(p) #endif /* DT_DEALLOCA */ /** * @brief Gets the sign of a number */ #ifndef DT_SGN # define DT_SGN(a) ((a) == 0 ? 0 : ((a) > 0 ? 1 : -1)) #endif /* DT_SGN */ /** * @brief Invalid index */ #ifndef DT_INVALID_INDEX # define DT_INVALID_INDEX (~0) #endif /* DT_INVALID_INDEX */ /** * @brief Dummy datatree, for passing to some APIs which requires a non-zero * datatree pointer parameter */ #ifndef DT_DUMMY_DATATREE # define DT_DUMMY_DATATREE ((dt_datatree_t)~0) #endif /* DT_DUMMY_DATATREE */ /** * @brief Boolean type */ typedef enum dt_bool_t { DT_FALSE, /**< false */ DT_TRUE /**< true */ } dt_bool_t; /** * @brief Valid data types of a datatree value */ typedef enum dt_type_t { DT_NULL, /**< null */ DT_BOOL, /**< true or false */ DT_LONG, /**< Signed long integer */ DT_DOUBLE, /**< Double float point */ DT_STRING, /**< String */ DT_OBJECT, /**< Object */ DT_ARRAY, /**< Array */ DT_TYPE_COUNT /**< Types count */ } dt_type_t; /** * @brief Execution status of datatree operations */ typedef enum dt_status_t { DT_OK, /**< Totally okay, use this one to decide whether an operation executed succesfully */ DT_LOAD_FAILED, /**< Datatree load failed from a string, file or binary */ DT_REDUNDANCE_CHAR_LEFT, /**< Datatree load failed from a string, redundance charactor(s) left */ DT_LEFT_BRACE_EXPECTED, /**< '{' symbol expected */ DT_RIGHT_BRACE_EXPECTED, /**< '}' symbol expected */ DT_LEFT_SQUARE_BRACKET_EXPECTED, /**< '[' symbol expected */ DT_RIGHT_SQUARE_BRACKET_EXPECTED, /**< ']' symbol expected */ DT_COLON_EXPECTED, /**< ':' symbol expected */ DT_TOO_MANY_COMMAS, /**< Too many ',' symbols found */ DT_VALUE_EXPECTED, /**< Valid datatree value not found */ DT_KEY_EXISTS, /**< Given key already exists in object members */ DT_KEY_DOES_NOT_EXIST, /**< Given key not exists in object members */ DT_INDEX_OUT_OF_RANGE, /**< An index of an object or array is out of range */ DT_TYPE_NOT_MATCHED, /**< Type not matched in a conversion */ DT_VALUE_IS_READONLY, /**< Value is readonly, means you can not change the key of an object member */ DT_JSON_INCOMPATIBLE /**< The datatree is JSON incompatible */ } dt_status_t; /** * @brief Enum compatible type, for generic arguments passing */ typedef unsigned int dt_enum_compatible_t; /** * @brief Pointer to a datatree */ typedef struct dt_datatree_d { char* dummy; }* dt_datatree_t; /** * @brief Pointer to a value */ typedef struct dt_value_d { char* dummy; }* dt_value_t; /** * @brief Pointer to an object */ typedef struct dt_object_d { char* dummy; }* dt_object_t; /** * @brief Pointer to an array */ typedef struct dt_array_d { char* dummy; }* dt_array_t; /** * @brief SAD(Simple API for Datatree) event handler structure */ typedef struct dt_sad_handler_t { /** * @brief Handles a simple typed value parsed event * * @param[in] type - Parsed data type * @param[in] data - Pointer to parsed data * @param[in] sad - SAD context */ void (* simple_parsed)(dt_type_t type, void* data, struct dt_sad_handler_t* sad); /** * @brief Handles an object begin event * * @param[in] sad - SAD context */ void (* object_begin)(struct dt_sad_handler_t* sad); /** * @brief Handles an object end event * * @param[in] sad - SAD context */ void (* object_end)(struct dt_sad_handler_t* sad); /** * @brief Handles an array begin event * * @param[in] sad - SAD context */ void (* array_begin)(struct dt_sad_handler_t* sad); /** * @brief Handles an array end event * * @param[in] sad - SAD context */ void (* array_end)(struct dt_sad_handler_t* sad); /** * @brief User data, assign whatever you want, normally for some parsing context */ void* userdata; } dt_sad_handler_t; /** * @brief Separator charactor detect functor * * @param[in] _c - Charactor to be detected * @return - Non zero if separator detected */ typedef int (* dt_separator_char_detect_func_t)(unsigned char _c); /** * @brief String pop functor * * @param[in] _s - XPL context * @param[in] _o - Target buffer to be filled * @return - XPL status */ typedef xpl_status_t (* dt_pop_string_func_t)(xpl_context_t* _s, char** _o); /** * @brief Datatree string parsing error handler functor * * @param[in] status - Parsing status * @param[in] msg - Error message text * @param[in] pos - Error position in text format, for locating * @param[in] row - Error row in source text, for locating * @param[in] col - Error column in source text, for locating */ typedef void (* dt_parse_error_handler_t)(dt_enum_compatible_t status, const char* msg, const char* pos, size_t row, size_t col); /** * @brief Datatree object members enumeration handler functor * * @param[in] d - Datatree * @param[in] o - Object * @param[in] key - Key of current enumerating member * @param[in] val - Value of current enumerating member * @param[in] idx - Index of current enumerating member */ typedef void (* dt_object_member_walker_t)(dt_datatree_t d, const dt_object_t o, const dt_value_t key, const dt_value_t val, size_t idx); /** * @brief Datatree array elements enumeration handler functor * * @param[in] d - Datatree * @param[in] a - Array * @param[in] v - Current enumerating element * @param[in] idx - Index of current enumerating element */ typedef void (* dt_array_walker_t)(dt_datatree_t d, const dt_array_t a, const dt_value_t v, size_t idx); /** * @brief Gets the version of datatree * * @return - The version of datatree */ DT_API unsigned int dt_ver(void); /** * @brief Gets the version of datatree binary format * * @return - The version of datatree binary format */ DT_API unsigned int dt_bver(void); /** * @brief Gets a message text of a status * * @param[in] s - Status * @return - A message text */ DT_API const char* const dt_status_message(dt_status_t s); /** * @brief Gets the allocated bytes for datatree sturctures, * this function is only valid if DT_ENABLE_ALLOC_STAT is defined * * @return - Allocated bytes */ DT_API size_t dt_allocated(void); /** * @brief Allocates a piece of memory in given size * * @param[in] s - Bytes to be allocated * @return - A pointer to allocated memory */ DT_API void* dt_malloc(size_t s); /** * @brief Reallocates a piece of memory in a new size * * @param[out] p - Pointer to a pointer which points to a piece of memory to be reallocated * @param[in] s - New size * @return - A pointer to reallocated memory */ DT_API void* dt_realloc(void** p, size_t s); /** * @brief Frees a piece of allocated memory * * @param[in/out] p - Pointer to a pointer which points to a piece of memory to be freed */ DT_API void dt_free(void** p); /** * @brief Fills a piece of memory with zero * * @param[in] p - Pointer to a piece of memory to be cleared * @param[in] s - Size to be cleared, in bytes */ DT_API void dt_memclr(void* p, size_t s); /** * @brief Compares two pieces of memory with a given size * * @param[in] l - Left memory * @param[in] r - Right memory * @param[in] s - Size to be compared * @return - 0 if l == r, 1 if l > r, -1 if l < r */ DT_API int dt_memcmp(const void* l, const void* r, size_t s); /** * @brief Copies a piece of memory to another with a given size * * @param[in] dst - Destination memory, would be filled * @param[in] src - Source memory * @param[in] s - Size to be copied * @return - A pointer to copied destination memory */ DT_API void* dt_memcpy(void* dst, const void* src, size_t s); /** * @brief Swaps two pieces of memory with a given size * * @param[in] l - Left memory * @param[in] r - Right memory * @param[in] s - Size to be swapped */ DT_API void dt_memswap(void* l, void* r, size_t s); /** * @brief Creates a datatree * * @param[out] d - Pointer to created datatree * @param[in] eh - Parsing error handler */ DT_API void dt_create_datatree(dt_datatree_t* d, dt_parse_error_handler_t eh); /** * @brief Unloads a datatree, a datatree needs to be unloaded before destroied * * @param[in] d - Datatree to be unloaded */ DT_API void dt_unload_datatree(dt_datatree_t d); /** * @brief Destroies a datatree, a datatree needs to be unloaded before destroied * * @param[in] d - Datatree to be destroied */ DT_API void dt_destroy_datatree(dt_datatree_t d); /** * @brief Gets the userdata of a datatree * * @param[in] d - Target datatree * @return - Set userdata */ DT_API void* dt_get_datatree_userdata(dt_datatree_t d); /** * @brief Sets the userdata to a datatree * * @param[in] d - Target datatree * @param[in] ud - Userdata * @return - Old userdata */ DT_API void* dt_set_datatree_userdata(dt_datatree_t d, void* ud); /** * @brief Loads a text file to a datatree in SAD mode * * @param[in] d - Target datatree * @param[in] h - SAD event handler * @param[in] f - Source file path * @return - Parsing status */ DT_API dt_status_t dt_load_datatree_file_sad(dt_datatree_t d, dt_sad_handler_t* h, const char* f); /** * @brief Loads a text file to a datatree * * @param[in] d - Target datatree * @param[in] f - Source file path * @return - Parsing status */ DT_API dt_status_t dt_load_datatree_file(dt_datatree_t d, const char* f); /** * @brief Saves a datatree to a text file * * @param[in] d - Source datatree * @param[in] f - Target file path * @param[in] compact - Save as compact without spaces and newlines * @param[in] json_mode - JSON mode * @retur - Formatting status */ DT_API dt_status_t dt_save_datatree_file(dt_datatree_t d, const char* f, dt_bool_t compact, dt_bool_t json_mode); /** * @brief Loads a string to a datatree in SAD mode * * @param[in] d - Target datatree * @param[in] h - SAD event handler * @param[in] s - Source string * @return - Parsing status */ DT_API dt_status_t dt_load_datatree_string_sad(dt_datatree_t d, dt_sad_handler_t* h, const char* s); /** * @brief Loads a string to a datatree * * @param[in] d - Target datatree * @param[in] s - Source string * @return - Parsing status */ DT_API dt_status_t dt_load_datatree_string(dt_datatree_t d, const char* s); /** * @brief Saves a datatree to a string * * @param[in] d - Source datatree * @param[out] s - Target string * @param[in] compact - Save as compact without space and newlines * @param[in] json_mode - JSON mode * @retur - Formatting status */ DT_API dt_status_t dt_save_datatree_string(dt_datatree_t d, char** s, dt_bool_t compact, dt_bool_t json_mode); /** * @brief Loades a binary buffer to a datatree in SAD mode * * @param[in] d - Target datatree * @param[in] h - SAD event handler * @param[in] b - Source binary buffer * @return - Loading status */ DT_API dt_status_t dt_load_datatree_bin_sad(dt_datatree_t d, dt_sad_handler_t* h, const void* b); /** * @brief Loades a binary buffer to a datatree * * @param[in] d - Target datatree * @param[in] b - Source binary buffer * @return - Loading status */ DT_API dt_status_t dt_load_datatree_bin(dt_datatree_t d, const void* b); /** * @brief Saves a datatree to a binary buffer * * @param[in] d - Source datatree * @param[out] b - Target binary buffer * @param[out] s - Bytes saved */ DT_API void dt_save_datatree_bin(dt_datatree_t d, void** b, size_t* s); /** * @brief Creates a value * @usage dt_create_value(?, ?, on_error, "string allows %? style escape", more arguments for escape) or * dt_create_value(?, ?, on_error, NULL, dt_type_t, data) * * @param[in] d - Host datatree * @param[out] v - Value holder pointer * @param[in] eh - Optional, customized error handler * @param[in] fmt - Begining of a variable arguments list * @return - Non zero if succeed */ DT_API int dt_create_value(dt_datatree_t d, dt_value_t* v, dt_parse_error_handler_t eh, const char* fmt, ...); /** * @brief Creates a value * * @param[in] d - Host datatree * @param[out] v - Value holder pointer * @param[in] sd - Separator detector * @param[in] eh - Optional, customized error handler * @param[in] fmt - String to be parsed * @return - Non zero if succeed */ DT_API int dt_create_value_ex(dt_datatree_t d, dt_value_t* v, dt_separator_char_detect_func_t sd, dt_parse_error_handler_t eh, const char* fmt); /** * @brief Destroies a value * * @param[in] d - Host datatree * @param[in] v - Value to be destroied */ DT_API void dt_destroy_value(dt_datatree_t d, dt_value_t v); /** * @brief Formats a value to string * * @param[in] d - Host datatree * @param[in] v - Value to be formatted * @param[out] s - Target string * @param[in] compact - Compact mode * @param[in] json_mode - JSON mode * @return - Formatting status */ DT_API dt_status_t dt_format_value(dt_datatree_t d, const dt_value_t v, char** s, dt_bool_t compact, dt_bool_t json_mode); /** * @brief Clones a value to another * * @param[in] d - Host datatree * @param[in] v - Input value * @param[out] o - Output value */ DT_API void dt_clone_value(dt_datatree_t d, const dt_value_t v, dt_value_t o); /** * @brief Finds an object member by key * * @param[in] d - Host datatree * @param[in] o - Object to be searched * @param[in] key - Searching key * @param[out] val - Found value * @param[out] idx - Index of found member */ DT_API void dt_find_object_member_by_key(dt_datatree_t d, const dt_object_t o, const dt_value_t key, dt_value_t* val, size_t* idx); /** * @brief Gets the count of members in an object * * @param[in] d - Host datatree * @param[in] o - Object to be counted * @param[out] c - Count of members in an object */ DT_API void dt_object_member_count(dt_datatree_t d, const dt_object_t o, size_t* c); /** * @brief Gets an object member * * @param[in] d - Host datatree * @param[in] o - Object to be operated * @param[out] key - Got key * @param[out] val - Got value */ DT_API void dt_object_member_at(dt_datatree_t d, const dt_object_t o, size_t idx, dt_value_t* key, dt_value_t* val); /** * @brief Gets the count of elements in an array * * @param[in] d - Host datatree * @param[in] a - Array to be counted * @param[out] c - Count of elements in an array */ DT_API void dt_array_elem_count(dt_datatree_t d, const dt_array_t a, size_t* c); /** * @brief Gets an array element * * @param[in] d - Host datatree * @param[in] a - Array to be operated * @param[in] idx - Target index * @param[out] v - Got value */ DT_API void dt_array_elem_at(dt_datatree_t d, const dt_array_t a, size_t idx, dt_value_t* v); /** * @brief Addes a new object member * * @param[in] d - Host datatree * @param[in] o - Target object * @param[in] key - Given key, will be set to the null value after adding successfully * @param[in] val - Given value, will be set to the null value after adding successfully * @param[out] idx - Appended position * @return - Operating status */ DT_API dt_status_t dt_add_object_member(dt_datatree_t d, dt_object_t o, dt_value_t key, dt_value_t val, size_t* idx); /** * @brief Inserts a new object member * * @param[in] d - Host datatree * @param[in] o - Target object * @param[in] where - Insertion position * @param[in] key - Given key, will be set to the null value after inserting successfully * @param[in] val - Given value, will be set to the null value after inserting successfully * @return - Operating status */ DT_API dt_status_t dt_insert_object_member(dt_datatree_t d, dt_object_t o, size_t where, dt_value_t key, dt_value_t val); /** * @brief Addes a new array element * * @param[in] d - Host datatree * @param[in] a - Target array * @param[in] v - Given value, will be set to the null value after adding successfully * @param[out] idx - Appended position * @return - Operating status */ DT_API dt_status_t dt_add_array_elem(dt_datatree_t d, dt_array_t a, dt_value_t v, size_t* idx); /** * @brief Inserts a new array element * * @param[in] d - Host datatree * @param[in] a - Target array * @param[in] where - Insertion position * @param[in] v - Given value, will be set to the null value after inserting successfully * @return - Operating status */ DT_API dt_status_t dt_insert_array_elem(dt_datatree_t d, dt_array_t a, size_t where, dt_value_t v); /** * @brief Removes an object member by key * * @param[in] d - Host datatree * @param[in] o - Object to be operated * @param[in/out] key - Given key, this will be filled with the removed key after function returned * @param[out] val - Removed value * @return - Operating status */ DT_API dt_status_t dt_remove_object_member_by_key(dt_datatree_t d, dt_object_t o, dt_value_t key, dt_value_t val); /** * @brief Deletes an object member by key * * @param[in] d - Host datatree * @param[in] o - Object to be operated * @param[in] key - Given key * @return - Operating status */ DT_API dt_status_t dt_delete_object_member_by_key(dt_datatree_t d, dt_object_t o, const dt_value_t key); /** * @brief Removes an object member by index * * @param[in] d - Host datatree * @param[in] o - Object to be operated * @param[in] where - Given index * @param[out] key - Removed key * @param[out] val - Removed value * @return - Operating status */ DT_API dt_status_t dt_remove_object_member_at(dt_datatree_t d, dt_object_t o, size_t where, dt_value_t key, dt_value_t val); /** * @brief Deletes an object member by index * * @param[in] d - Host datatree * @param[in] o - Object to be operated * @param[in] where - Given index * @return - Operating status */ DT_API dt_status_t dt_delete_object_member_at(dt_datatree_t d, dt_object_t o, size_t where); /** * @brief Clears and deletes all members of an array * * @param[in] d - Host datatree * @param[in] o - Object to be cleared * @return - Operating status */ DT_API dt_status_t dt_clear_object_member(dt_datatree_t d, dt_object_t o); /** * @brief Removes an array element by index * * @param[in] d - Host datatree * @param[in] a - Array to be operated * @param[in] where - Given index * @param[out] val - Removed value * @return - Operating status */ DT_API dt_status_t dt_remove_array_elem_at(dt_datatree_t d, dt_array_t a, size_t where, dt_value_t val); /** * @brief Deletes an array element by index * * @param[in] d - Host datatree * @param[in] a - Array to be operated * @param[in] where - Given index * @return - Operating status */ DT_API dt_status_t dt_delete_array_elem_at(dt_datatree_t d, dt_array_t a, size_t where); /** * @brief Cleares and deletes all elements of an array * * @param[in] d - Host datatree * @param[in] a - Array to be cleared * @return - Operating status */ DT_API dt_status_t dt_clear_array_elem(dt_datatree_t d, dt_array_t a); /** * @brief Updates an object member value, located by key * * @param[in] d - Host datatree * @param[in] o - Object to be updated * @param[in] key - Given key, where to be updated * @param[in] val - Given value * @return - Operating status */ DT_API dt_status_t dt_update_object_member_by_key(dt_datatree_t d, dt_object_t o, const dt_value_t key, dt_value_t val); /** * @brief Updates an object member value, located by index * * @param[in] d - Host datatree * @param[in] o - Object to be updated * @param[in] where - Given index, where to be updated * @param[in] val - Given value * @return - Operating status */ DT_API dt_status_t dt_update_object_member_at(dt_datatree_t d, dt_object_t o, size_t where, dt_value_t val); /** * @brief Updates an array element * * @param[in] d - Host datatree * @param[in] a - Array to be updated * @param[in] where - Given index, where to be updated * @param[val] val - Given value * @return - Operating status */ DT_API dt_status_t dt_udpate_array_elem_at(dt_datatree_t d, dt_array_t a, size_t where, dt_value_t val); /** * @brief Enumerates all members in an object * * @param[in] d - Host datatree * @param[in] o - Object to be enumerated * @param[in] w - Enumeration handler */ DT_API void dt_foreach_object_member(dt_datatree_t d, dt_object_t o, dt_object_member_walker_t w); /** * @brief Enumerates all elements in an array * * @param[in] d - Host datatree * @param[in] a - Array to be enumerated * @param[in] w - Enumeration handler */ DT_API void dt_foreach_array_elem(dt_datatree_t d, dt_array_t a, dt_array_walker_t w); /** * @brief Gets the root value of a datatree, a root value can be an object or an array in datatree * * @param[in] d - Host datatree * @return - The root value */ DT_API dt_value_t dt_root_value(dt_datatree_t d); /** * @brief Tries to get the root value of a datatree as object * * @param[in] d - Host datatree * @return - Root value as object, NULL if it's not an object (but an array) */ DT_API dt_object_t dt_root_as_object(dt_datatree_t d); /** * @brief Gets the type of a value * * @param[in] v - Given value * @return - The type the given value */ DT_API dt_type_t dt_value_type(const dt_value_t v); /** * @brief Gets a pointer to the data of a value * * @param[in] v - Given value * @return - A pointer to the data of the given value */ DT_API void* dt_value_data(const dt_value_t v); /** * @brief Tries to get a data ov a value * @note Numeric data can be assigned to a variable of a higher precision, * other types of data can only be assigned to an exact variable in the same type * * @param[out] des - Pointer to target variable * @param[in] v - Given value * @param[in] t - Expected type * @return - Conversion status, DT_OK if successeful, otherwise DT_TYPE_NOT_MATCHED */ DT_API dt_status_t dt_value_data_as(void* des, const dt_value_t v, dt_type_t t); /** * @brief Compares two values * * @param[in] l - Left value * @param[in] r - Right value * @param[in] num_raw_cmp - Whether compares numbers using raw memory * @return - 0 if l == r, 1 if l > r, -1 if l < r */ DT_API int dt_value_compare(const dt_value_t l, const dt_value_t r, dt_bool_t num_raw_cmp); /** * @brief Gets the length of a value * * @param[in] v - Value * @return - Members count for object, elements count for array, * charactors (without ending '\0') count for string, * raw size in bytes for other types, -1 for error */ DT_API int dt_value_data_length(const dt_value_t v); /** * @brief Swaps the memory of two values * @note Do not call this function unless you know what you are doing * * @param[in] l - Left value * @param[in] r - Right value */ DT_API void dt_value_mem_swap(dt_value_t l, dt_value_t r); /** * @brief Moves the memory of a value to another * @note Do not call this function unless you know what you are doing * * @param[in] l - Left value * @param[in] r - Right value */ DT_API void dt_value_mem_move(dt_value_t l, dt_value_t r); /** * @brief Sets a string popper of a datatree * * @param[in] d - Target datatree * @param[in] p - String popper */ DT_API void dt_set_string_popper(dt_datatree_t d, dt_pop_string_func_t p); #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* __DT_CORE_H__ */
32.232697
145
0.665433
2b1ec92acd9aba0f53c9dffc53c99cb516d416b6
2,165
h
C
networkit/cpp/community/CutClustering.h
mlooz/networkit-general-polylog
5de2844e6b06258084ddf423c054a90954f6f59c
[ "MIT" ]
3
2018-02-24T08:17:03.000Z
2020-05-11T13:08:33.000Z
networkit/cpp/community/CutClustering.h
kit-parco/networkit-hyperbolic-kd
8eb786b8f72e0507a75e68184f444a19cf47ef58
[ "MIT" ]
null
null
null
networkit/cpp/community/CutClustering.h
kit-parco/networkit-hyperbolic-kd
8eb786b8f72e0507a75e68184f444a19cf47ef58
[ "MIT" ]
2
2020-11-18T09:17:04.000Z
2020-12-10T12:07:21.000Z
#ifndef CUTCLUSTERING_H #define CUTCLUSTERING_H #include "CommunityDetectionAlgorithm.h" namespace NetworKit { /** * Cut clustering algorithm as defined in * Flake, Gary William; Tarjan, Robert E.; Tsioutsiouliklis, Kostas. Graph Clustering and Minimum Cut Trees. * Internet Mathematics 1 (2003), no. 4, 385--408. */ class CutClustering : public CommunityDetectionAlgorithm { public: /** * Initialize cut clustering algorithm with parameter alpha. * * A value of 0 gives a clustering with one cluster with all nodes, * A value that equals to the largest edge weight gives singleton clusters. * * @param alpha The parameter for the cut clustering */ CutClustering(const Graph& G, edgeweight alpha); /** * Apply algorithm to graph * * Warning: due to numerical errors the resulting clusters might not be correct. * This implementation uses the Edmonds-Karp algorithm for the cut calculation. */ virtual void run() override; /** * @return string representation of algorithm and parameters. */ virtual std::string toString() const override; /** * Get the complete hierarchy with all possible parameter values. * * Each reported parameter value is the lower bound for the range in which the corresponding clustering is calculated by the cut clustering algorithm. * * Warning: all reported parameter values are slightly too high in order to avoid wrong clusterings because of numerical inaccuracies. * Furthermore the completeness of the hierarchy cannot be guaranteed because of these inaccuracies. * This implementation hasn't been optimized for performance. * * @param G The Graph instance for which the hierarchy shall be calculated * * @return The hierarchy as map */ static std::map<edgeweight, Partition> getClusterHierarchy(const Graph& G); private: /** * Helper function for the recursive clustering hierarchy calculation. */ static void clusterHierarchyRecursion(const Graph &G, edgeweight lower, Partition lowerClusters, edgeweight upper, Partition upperClusters, std::map< edgeweight, Partition > &result); edgeweight alpha; }; } // namespace NetworKit #endif // CUTCLUSTERING_H
33.828125
184
0.75612
2b23530f61530e1170460f91a5652b5c4bc8082b
843
h
C
modules/bio_mapred/align_seqset.h
spiralgenetics/biograph
33c78278ce673e885f38435384f9578bfbf9cdb8
[ "BSD-2-Clause" ]
16
2021-07-14T23:32:31.000Z
2022-03-24T16:25:15.000Z
modules/bio_mapred/align_seqset.h
spiralgenetics/biograph
33c78278ce673e885f38435384f9578bfbf9cdb8
[ "BSD-2-Clause" ]
9
2021-07-20T20:39:47.000Z
2021-09-16T20:57:59.000Z
modules/bio_mapred/align_seqset.h
spiralgenetics/biograph
33c78278ce673e885f38435384f9578bfbf9cdb8
[ "BSD-2-Clause" ]
9
2021-07-15T19:38:35.000Z
2022-01-31T19:24:56.000Z
#pragma once #include <vector> #include <boost/operators.hpp> #include "modules/bio_base/align_astar.h" #include "modules/bio_base/seqset.h" struct seqset_align_state : boost::less_than_comparable<seqset_align_state> , boost::equality_comparable<seqset_align_state> { int read_pos; seqset_range seqset_pos; int state; // 0 = normal, 1 = in ins, 2 = in del, 3 = done seqset_align_state(int _read_pos, seqset_range _seqset_pos, int _state = 0) : read_pos(_read_pos), seqset_pos(_seqset_pos), state(_state) {} bool operator<(const seqset_align_state& rhs) const; bool operator==(const seqset_align_state& rhs) const; }; // Aligns read against sequence, must use all of both double align_seqset(std::vector<seqset_align_state>& out, const dna_sequence& read, const seqset& the_seqset, const cost_matrix& costs, double max_cost);
33.72
153
0.768683
2b23fbe41ac4081d55adfe10ae22a59421288b6b
893
h
C
gnuplot.h
ave91/untitled2
1d54b5e54893c7fef189ba13a5877ce4ea0fabb3
[ "Apache-2.0" ]
null
null
null
gnuplot.h
ave91/untitled2
1d54b5e54893c7fef189ba13a5877ce4ea0fabb3
[ "Apache-2.0" ]
null
null
null
gnuplot.h
ave91/untitled2
1d54b5e54893c7fef189ba13a5877ce4ea0fabb3
[ "Apache-2.0" ]
null
null
null
#ifndef GNUPLOT_H #define GNUPLOT_H #include <string> #include <iostream> using namespace std; class Gnuplot { public: Gnuplot() ; ~Gnuplot(); void operator ()(const string & command); // send any command to gnuplot protected: FILE *gnuplotpipe; }; Gnuplot::Gnuplot() { // with -persist option you will see the windows as your program ends //gnuplotpipe=_popen("gnuplot -persist","w"); //without that option you will not see the window // because I choose the terminal to output files so I don't want to see the window gnuplotpipe=_popen("gnuplot -persist","w"); if (!gnuplotpipe) { cerr<< ("Gnuplot not found !"); } } Gnuplot::~Gnuplot() { fprintf(gnuplotpipe,"exit\n"); _pclose(gnuplotpipe); } void Gnuplot::operator()(const string & command) { fprintf(gnuplotpipe,"%s\n",command.c_str()); fflush(gnuplotpipe); // flush is necessary, nothing gets plotted else } #endif // GNUPLOT_H
22.325
83
0.720045
2b26c0b7925b4e04159278fdaa18582ebee0457b
697
c
C
programmazione/laboratori/es_classe/es_casa.c
danesinoo/secondo_semestre
c6c284985f59f956d80a7073e5505cb72acaf29d
[ "MIT" ]
null
null
null
programmazione/laboratori/es_classe/es_casa.c
danesinoo/secondo_semestre
c6c284985f59f956d80a7073e5505cb72acaf29d
[ "MIT" ]
null
null
null
programmazione/laboratori/es_classe/es_casa.c
danesinoo/secondo_semestre
c6c284985f59f956d80a7073e5505cb72acaf29d
[ "MIT" ]
null
null
null
#include <stdio.h> #include "prova.h" /* Dato un Array A di dimensione len, filtrare tutti gli elementi f. * Questo significa restituire l'array compattato composta da tutti gli elementi originali di A meno gli elementi uguali ad f. * ES: [1,24,3,4] 3 -> [1,24,4] * ES: [1,2,1,3,4,6] 1 -> [2,3,4,6] */ int main() { unsigned int len; int f; scanf("%2u", &len); int A[len]; for (int i = 0; i < len; i = i + 1) { scanf("%d", A + i); } scanf("%d", &f); filter(A, &len, f); // definire ed utilizzare qui una funzione void filter(...) printf("["); for (int i = 0; i < len; i += 1) printf(" %d", A[i]); printf(" ]\n"); return 0; }
23.233333
126
0.539455
2b273373f66cbea487c5b9f342e0ddfc4c10a86c
3,280
c
C
src/gmbus.c
Matt8898/lil
3f885754c1b5a4d2406377ce0340fb1425cd7d28
[ "BSD-2-Clause" ]
26
2020-11-23T20:20:48.000Z
2021-11-29T00:01:19.000Z
src/gmbus.c
thomtl/lil
f8098036f95d1e53878e7d83e783cfb775428264
[ "BSD-2-Clause" ]
null
null
null
src/gmbus.c
thomtl/lil
f8098036f95d1e53878e7d83e783cfb775428264
[ "BSD-2-Clause" ]
1
2021-01-06T18:50:49.000Z
2021-01-06T18:50:49.000Z
#include "gmbus.h" #include "imports.h" #include "edid.h" #include <stddef.h> #define GMBUS_SELECT 0x5100 #define GMBUS_COMMAND_STATUS 0x5104 #define GMBUS_STATUS 0x5108 #define GMBUS_DATA 0x510C #define GMBUS_IRMASK 0x5110 #define GMBUS_2BYTEINDEX 0x5120 #define GMBUS_HW_RDY (1 << 11) #define GMBUS_NAK (1 << 10) #define GMBUS_HW_WAIT_PHASE (1 << 14) #define GMBUS_CYCLE_WAIT (1 << 25) #define GMBUS_CYCLE_INDEX (1 << 26) #define GMBUS_LEN_MASK 511 #define GMBUS_LEN_SHIFT 16 #define GMBUS_LEN(x) ((x & GMBUS_LEN_MASK) << GMBUS_LEN_SHIFT) #define GMBUS_OFFSET_MASK 127 #define GMBUS_OFFSET_SHIFT 1 #define GMBUS_OFFSET(x) ((x & GMBUS_OFFSET_MASK) << GMBUS_OFFSET_SHIFT) #define GMBUS_READ 1 #define GMBUS_SW_READY (1 << 30) #define GMBUS_CLEAR_INTERRUPT (1u << 31) static void gmbus_wait_progress(LilGpu* gpu) { volatile uint32_t* gmbus_status = (uint32_t*)(gpu->mmio_start + GMBUS_STATUS + gpu->gpio_start); while(1) { uint32_t status = *gmbus_status; if(status & (GMBUS_NAK)) { lil_panic("NAK on gmbus"); } if(status & GMBUS_HW_RDY) { break; } } } static void gmbus_wait_completion(LilGpu* gpu) { volatile uint32_t* gmbus_status = (uint32_t*)(gpu->mmio_start + GMBUS_STATUS + gpu->gpio_start); while(1) { uint32_t status = *gmbus_status; if(status & (GMBUS_NAK)) { lil_panic("NAK on gmbus"); } if(status & GMBUS_HW_WAIT_PHASE) { break; } } } static void gmbus_read(LilGpu* gpu, int pin_pair, uint32_t offset, uint32_t len, uint8_t* buf) { volatile uint32_t* gmbus_select = (uint32_t*)(gpu->mmio_start + GMBUS_SELECT + gpu->gpio_start); volatile uint32_t* gmbus_command = (uint32_t*)(gpu->mmio_start + GMBUS_COMMAND_STATUS + gpu->gpio_start); volatile uint32_t* gmbus_data = (uint32_t*)(gpu->mmio_start + GMBUS_DATA + gpu->gpio_start); uint32_t gmbus_select_val = *gmbus_select; uint32_t gmbus_command_val = *gmbus_command; gmbus_select_val &= 0xFFFFF800; gmbus_select_val = pin_pair; gmbus_command_val = GMBUS_CYCLE_WAIT | GMBUS_CYCLE_INDEX | GMBUS_LEN(len) | GMBUS_OFFSET(offset) | GMBUS_READ | GMBUS_SW_READY; *gmbus_command = 0; uint32_t temp = *gmbus_command; temp |= GMBUS_CLEAR_INTERRUPT; *gmbus_command = temp; temp = *gmbus_command; temp &= ~GMBUS_CLEAR_INTERRUPT; *gmbus_command = temp; *gmbus_select = gmbus_select_val; *gmbus_command = gmbus_command_val; size_t progress = 0; while(progress < len) { gmbus_wait_progress(gpu); uint32_t data = *gmbus_data; for(int i = 0; i < 4; i++) { if(progress == len) break; buf[progress++] |= data >> (8 * i); } } gmbus_wait_completion(gpu); } uint8_t lil_gmbus_get_mode_info(LilGpu* gpu, LilModeInfo* out, int pin_pair) { DisplayData edid = {0}; gmbus_read(gpu, pin_pair, 0x50, 128, (uint8_t*)&edid); int j = 0; for (int i = 0; i < 4; i++) { if(edid.detailTimings[i].pixelClock == 0) continue; // Not a timing descriptor edid_timing_to_mode(&edid, edid.detailTimings[i], &out[j++]); } return j; }
30.943396
109
0.650305
2b29566f84116068972ea529a7122665d10ff646
531
h
C
ios/source/courses/skutarenko/iOSDevCourse-Objective-C/Archive/__HWOtherPeople/46-47/task46-47-master/ClientServerAPIs/TTAlbum.h
oltv00/knowledge
25d9507d529c494e0d6d9c1d7f643d3249624b65
[ "MIT" ]
null
null
null
ios/source/courses/skutarenko/iOSDevCourse-Objective-C/Archive/__HWOtherPeople/46-47/task46-47-master/ClientServerAPIs/TTAlbum.h
oltv00/knowledge
25d9507d529c494e0d6d9c1d7f643d3249624b65
[ "MIT" ]
1
2018-01-17T10:11:50.000Z
2018-01-17T10:11:50.000Z
ios/source/courses/skutarenko/iOSDevCourse-Objective-C/Archive/__HWOtherPeople/46-47/task46-47-master/ClientServerAPIs/TTAlbum.h
oltv00/knowledge
25d9507d529c494e0d6d9c1d7f643d3249624b65
[ "MIT" ]
null
null
null
// // TTAlbum.h // ClientServerAPIs // // Created by Sergey Reshetnyak on 6/7/14. // Copyright (c) 2014 sergey. All rights reserved. // #import <Foundation/Foundation.h> @interface TTAlbum : NSObject @property (strong,nonatomic) NSString *title; @property (strong,nonatomic) NSString *description; @property (strong,nonatomic) NSString *size; @property (strong,nonatomic) NSString *albumid; @property (strong,nonatomic) NSMutableArray *photosArray; - (instancetype)initWithDictionary:(NSDictionary *) responseObject; @end
24.136364
67
0.755179
2b2a857727d4fc8eeb11dbc3584bc202abd9d659
467
h
C
examples/validate/palindrome/palindromeform.h
PatrickTrentin88/intro_c-_qt
1d73ef364711fac7b46cd3752258c0273c689835
[ "MIT" ]
null
null
null
examples/validate/palindrome/palindromeform.h
PatrickTrentin88/intro_c-_qt
1d73ef364711fac7b46cd3752258c0273c689835
[ "MIT" ]
null
null
null
examples/validate/palindrome/palindromeform.h
PatrickTrentin88/intro_c-_qt
1d73ef364711fac7b46cd3752258c0273c689835
[ "MIT" ]
null
null
null
#ifndef MAIN_WINDOW_H_ #define MAIN_WINDOW_H_ #include <QWidget> #include <QString> class Palindate; class QLineEdit; class QLabel; //start class PalindromeForm : public QWidget { Q_OBJECT public: PalindromeForm(QWidget* parent=0); QString getPalindrome(); public slots: void showResult(); void again(); private: Palindate* m_Palindate; QLineEdit* m_LineEdit; QLabel* m_Result; QString m_InputString; void setupForm(); }; //end #endif
16.678571
39
0.730193
2b2e85b6875945d2aad80474595bf1bd848dbb17
2,270
h
C
PhotosUICore.framework/PXCMMCloudView.h
reels-research/iOS-Private-Frameworks
9a4f4534939310a51fdbf5a439dd22487efb0f01
[ "MIT" ]
4
2021-10-06T12:15:26.000Z
2022-02-21T02:26:00.000Z
PhotosUICore.framework/PXCMMCloudView.h
reels-research/iOS-Private-Frameworks
9a4f4534939310a51fdbf5a439dd22487efb0f01
[ "MIT" ]
null
null
null
PhotosUICore.framework/PXCMMCloudView.h
reels-research/iOS-Private-Frameworks
9a4f4534939310a51fdbf5a439dd22487efb0f01
[ "MIT" ]
1
2021-10-08T07:40:53.000Z
2021-10-08T07:40:53.000Z
/* Generated by RuntimeBrowser Image: /System/Library/PrivateFrameworks/PhotosUICore.framework/PhotosUICore */ @interface PXCMMCloudView : UIView { UILabel * _bodyLabel; <PXCMMCloudViewViewDelegate> * _delegate; struct { bool learnMoreTapped; bool dismissTapped; } _delegateRespondsTo; UIButton * _dismissButton; PXGradientView * _graphicGradientView; UIImageView * _graphicImageView; UIButton * _learnMoreButton; PXRoundedCornerOverlayView * _roundedCornerOverlayView; } @property (nonatomic, readonly) UILabel *bodyLabel; @property (nonatomic) <PXCMMCloudViewViewDelegate> *delegate; @property (nonatomic) bool disableDismissAction; @property (nonatomic, readonly) UIButton *dismissButton; @property (nonatomic, readonly) PXGradientView *graphicGradientView; @property (nonatomic, readonly) UIImageView *graphicImageView; @property (nonatomic, readonly) UIButton *learnMoreButton; // Image: /System/Library/PrivateFrameworks/PhotosUICore.framework/PhotosUICore - (void).cxx_destruct; - (id)_constrainedFontForTextStyle:(id)arg1 maximumContentSizeCategory:(id)arg2; - (void)_didTapDismissButton:(id)arg1; - (void)_learnMoreTapped:(id)arg1; - (struct CGSize { double x1; double x2; })_performLayoutInRect:(struct CGRect { struct CGPoint { double x_1_1_1; double x_1_1_2; } x1; struct CGSize { double x_2_1_1; double x_2_1_2; } x2; })arg1 updateSubviewFrames:(bool)arg2; - (void)_setupSubviews; - (void)_updateFontAndStyle; - (id)bodyLabel; - (id)delegate; - (bool)disableDismissAction; - (id)dismissButton; - (id)graphicGradientView; - (id)graphicImageView; - (id)initWithFrame:(struct CGRect { struct CGPoint { double x_1_1_1; double x_1_1_2; } x1; struct CGSize { double x_2_1_1; double x_2_1_2; } x2; })arg1; - (void)layoutSubviews; - (id)learnMoreButton; - (void)setDelegate:(id)arg1; - (void)setDisableDismissAction:(bool)arg1; - (struct CGSize { double x1; double x2; })sizeThatFits:(struct CGSize { double x1; double x2; })arg1; - (void)traitCollectionDidChange:(id)arg1; // Image: /System/Library/AccessibilityBundles/PhotosUICore.axbundle/PhotosUICore + (Class)safeCategoryBaseClass; - (id)_accessibilitySupplementaryFooterViews; - (id)accessibilityLabel; - (bool)isAccessibilityElement; @end
38.474576
228
0.768722
2b3110e7d806e2b93df594b738a3b328fafd5070
50
c
C
src/backend/semantic-analysis/ast_var_check.c
mdedeu/TP-TLA
49e0a90dc86b8ae67ead7fa4230b29a4df2635d9
[ "MIT" ]
null
null
null
src/backend/semantic-analysis/ast_var_check.c
mdedeu/TP-TLA
49e0a90dc86b8ae67ead7fa4230b29a4df2635d9
[ "MIT" ]
null
null
null
src/backend/semantic-analysis/ast_var_check.c
mdedeu/TP-TLA
49e0a90dc86b8ae67ead7fa4230b29a4df2635d9
[ "MIT" ]
null
null
null
int var_check(node_t * program) { return 0; }
10
31
0.64
2b31b9c28015d7b96c10329c3666bc86764354d1
16,179
c
C
sdl2/tbftss/src/battle/player.c
pdpdds/SDLGameProgramming
3af68e2133296f3e7bc3d7454d9301141bca2d5a
[ "BSD-2-Clause" ]
null
null
null
sdl2/tbftss/src/battle/player.c
pdpdds/SDLGameProgramming
3af68e2133296f3e7bc3d7454d9301141bca2d5a
[ "BSD-2-Clause" ]
null
null
null
sdl2/tbftss/src/battle/player.c
pdpdds/SDLGameProgramming
3af68e2133296f3e7bc3d7454d9301141bca2d5a
[ "BSD-2-Clause" ]
null
null
null
/* Copyright (C) 2015-2019 Parallel Realities This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include "player.h" static void selectTarget(void); static void switchGuns(void); static void cycleRadarZoom(void); static void selectMissionTarget(void); static void selectNewPlayer(int dir); static void initPlayerSelect(void); static void activateBoost(void); static void deactivateBoost(void); static void activateECM(void); static void handleKeyboard(void); static void faceMouse(void); static void handleMouse(void); static void preFireMissile(void); static void applyRestrictions(void); static int isPriorityMissionTarget(Entity *e, int dist, int closest); static int targetOutOfRange(void); static void rechargeBoostECM(void); static void setPilotName(void); static void updateDeathStats(void); static void handleSuspicionLevel(void); static int selectedPlayerIndex; static int availableGuns[BT_MAX]; static Entity *availablePlayerUnits[MAX_SELECTABLE_PLAYERS]; void initPlayer(void) { int i, n; memset(&availableGuns, 0, sizeof(int) * BT_MAX); battle.numPlayerGuns = 0; player->selectedGunType = -1; if (!player->combinedGuns) { for (i = 0 ; i < MAX_FIGHTER_GUNS ; i++) { n = player->guns[i].type; if (n) { if (!availableGuns[n]) { battle.numPlayerGuns++; } availableGuns[n] = 1; if (player->selectedGunType == -1) { player->selectedGunType = n; } } } } else { player->selectedGunType = 0; } setPilotName(); player->action = NULL; battle.boostTimer = BOOST_RECHARGE_TIME; battle.ecmTimer = ECM_RECHARGE_TIME; player->flags |= EF_NO_HEALTH_BAR; player->flags &= ~EF_IMMORTAL; player->target = NULL; game.stats[STAT_EPIC_KILL_STREAK] = MAX(game.stats[STAT_EPIC_KILL_STREAK], battle.stats[STAT_EPIC_KILL_STREAK]); battle.stats[STAT_EPIC_KILL_STREAK] = 0; } static void setPilotName(void) { int i, pos; pos = -1; for (i = 0 ; i < strlen(game.currentMission->pilot) ; i++) { if (game.currentMission->pilot[i] == ' ') { pos = i; } } memset(player->name, '\0', MAX_NAME_LENGTH); if (pos != -1) { memcpy(player->name, game.currentMission->pilot + pos + 1, strlen(game.currentMission->pilot) - pos - 1); } SDL_LogMessage(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO, "Pilot name = '%s'", player->name); } void doPlayer(void) { self = player; rechargeBoostECM(); if (game.currentMission->challengeData.isChallenge) { applyRestrictions(); } if (player->alive == ALIVE_ALIVE && player->systemPower > 0) { handleKeyboard(); handleMouse(); handleSuspicionLevel(); if (!player->target || player->target->health <= 0 || player->target->systemPower <= 0 || targetOutOfRange()) { selectTarget(); } } player->angle = ((int)player->angle) % 360; if (player->health <= 0 && battle.status == MS_IN_PROGRESS) { if (game.currentMission->challengeData.isChallenge) { if (!game.currentMission->challengeData.allowPlayerDeath) { updateDeathStats(); failMission(); } } else if (!battle.isEpic) { updateDeathStats(); failMission(); } else if (player->health == -FPS) { updateDeathStats(); updateCondition("PLAYER", TT_DESTROY); if (battle.status == MS_IN_PROGRESS) { initPlayerSelect(); } } } if (battle.status == MS_IN_PROGRESS) { selectMissionTarget(); } if (dev.playerUnlimitedMissiles) { player->missiles = 999; } /* really only used in challenge mode */ if (player->systemPower <= 0 && battle.status == MS_IN_PROGRESS) { if (game.currentMission->challengeData.isChallenge) { addHudMessage(colors.red, _("Challenge Failed!")); failMission(); } } if (battle.boostTimer == (int)BOOST_FINISHED_TIME) { deactivateBoost(); } } static void updateDeathStats(void) { battle.stats[STAT_PLAYER_KILLED]++; /* the player is known as "Player", so we need to check the craft they were assigned to */ if (strcmp(game.currentMission->craft, "ATAF") == 0) { awardTrophy("ATAF_DESTROYED"); } } static void rechargeBoostECM(void) { int boostTimer, ecmTimer; boostTimer = battle.boostTimer; battle.boostTimer = MIN(battle.boostTimer + 1, BOOST_RECHARGE_TIME); if (boostTimer < BOOST_RECHARGE_TIME && battle.boostTimer == BOOST_RECHARGE_TIME) { playSound(SND_RECHARGED); } ecmTimer = battle.ecmTimer; battle.ecmTimer = MIN(battle.ecmTimer + 1, ECM_RECHARGE_TIME); if (ecmTimer < ECM_RECHARGE_TIME && battle.ecmTimer == ECM_RECHARGE_TIME) { playSound(SND_RECHARGED); } } static int targetOutOfRange(void) { return (app.gameplay.autoSwitchPlayerTarget && getDistance(player->x, player->y, player->target->x, player->target->y) > SCREEN_WIDTH * 2); } static void applyRestrictions(void) { if (game.currentMission->challengeData.noMissiles) { player->missiles = 0; } if (game.currentMission->challengeData.noBoost) { battle.boostTimer = 0; } if (game.currentMission->challengeData.noECM) { battle.ecmTimer = 0; } if (game.currentMission->challengeData.noGuns) { player->reload = 1; } } static void handleKeyboard(void) { if (battle.status == MS_IN_PROGRESS) { if (isControl(CONTROL_BOOST) && player->speed > 0) { if (battle.boostTimer == BOOST_RECHARGE_TIME) { playSound(SND_BOOST); activateBoost(); } else { playSound(SND_GUI_DENIED); } clearControl(CONTROL_BOOST); } if (isControl(CONTROL_TARGET)) { selectTarget(); clearControl(CONTROL_TARGET); } if (isControl(CONTROL_ECM)) { if (battle.ecmTimer == ECM_RECHARGE_TIME) { playSound(SND_ECM); activateECM(); } else { playSound(SND_GUI_DENIED); } clearControl(CONTROL_ECM); } if (isControl(CONTROL_BRAKE)) { applyFighterBrakes(); } if (isControl(CONTROL_GUNS)) { switchGuns(); clearControl(CONTROL_GUNS); } if (isControl(CONTROL_RADAR)) { cycleRadarZoom(); clearControl(CONTROL_RADAR); } if (isControl(CONTROL_MISSILE)) { preFireMissile(); clearControl(CONTROL_MISSILE); } } else { applyFighterBrakes(); } } static void handleMouse(void) { faceMouse(); if (battle.status == MS_IN_PROGRESS) { if (isControl(CONTROL_FIRE) && !player->reload && player->guns[0].type) { if (player->selectedGunType != BT_ROCKET) { fireGuns(player); } else { fireRocket(player); } if (battle.hasSuspicionLevel && !battle.numEnemies && !battle.suspicionCoolOff) { battle.suspicionLevel += (MAX_SUSPICION_LEVEL * 0.05); } } if (isControl(CONTROL_ACCELERATE)) { if (battle.boostTimer > BOOST_FINISHED_TIME || game.currentMission->challengeData.noBoost) { applyFighterThrust(); } } if (isControl(CONTROL_MISSILE)) { preFireMissile(); app.mouse.button[SDL_BUTTON_MIDDLE] = 0; } if (isControl(CONTROL_GUNS)) { switchGuns(); app.mouse.button[SDL_BUTTON_X1] = 0; } if (isControl(CONTROL_RADAR)) { cycleRadarZoom(); app.mouse.button[SDL_BUTTON_X2] = 0; } } } static void faceMouse(void) { int dir; int x, y, wantedAngle; x = player->x - battle.camera.x; y = player->y - battle.camera.y; wantedAngle = getAngle(x, y, app.mouse.x, app.mouse.y); wantedAngle %= 360; if (fabs(wantedAngle - player->angle) > 2) { dir = ((int)(wantedAngle - player->angle + 360)) % 360 > 180 ? -1 : 1; player->angle += dir * 4; player->angle = mod(player->angle, 360); } } static void preFireMissile(void) { if (player->missiles && player->target) { if (getDistance(player->x, player->y, player->target->x, player->target->y) <= SCREEN_WIDTH) { fireMissile(player); } else { playSound(SND_GUI_DENIED); addHudMessage(colors.white, _("Target not in range")); } } else if (!player->missiles) { addHudMessage(colors.white, _("Out of missiles")); playSound(SND_NO_MISSILES); } } static void initPlayerSelect(void) { Entity *e; memset(&availablePlayerUnits, 0, sizeof(Entity*) * MAX_SELECTABLE_PLAYERS); selectedPlayerIndex = 0; if (battle.epicLives == 0 || (battle.epicLives > 0 && --battle.epicLives > 0)) { for (e = battle.entityHead.next ; e != NULL ; e = e->next) { if (e->active && e->type == ET_FIGHTER && e->health > 0 && e->side == SIDE_ALLIES && selectedPlayerIndex < MAX_SELECTABLE_PLAYERS) { availablePlayerUnits[selectedPlayerIndex++] = e; } } } if (selectedPlayerIndex > 0) { battle.playerSelect = 1; selectedPlayerIndex = 0; memset(&app.keyboard, 0, sizeof(int) * MAX_KEYBOARD_KEYS); } else { battle.isEpic = 0; if (battle.epicKills > 0 && battle.stats[STAT_ENEMIES_KILLED_PLAYER] < battle.epicKills) { battle.unwinnable = 0; } failMission(); } } void doPlayerSelect(void) { if (isControl(CONTROL_PREV_FIGHTER)) { selectNewPlayer(-1); clearControl(CONTROL_PREV_FIGHTER); } if (isControl(CONTROL_NEXT_FIGHTER)) { selectNewPlayer(1); clearControl(CONTROL_NEXT_FIGHTER); } if (player->health > 0 && isAcceptControl()) { battle.playerSelect = 0; initPlayer(); resetAcceptControls(); } } static void selectNewPlayer(int dir) { player = NULL; do { selectedPlayerIndex += dir; selectedPlayerIndex = mod(selectedPlayerIndex, MAX_SELECTABLE_PLAYERS); player = availablePlayerUnits[selectedPlayerIndex]; } while (player == NULL); battle.camera.x = player->x - (app.winWidth / 2); battle.camera.y = player->y - (app.winHeight / 2); } static void activateBoost(void) { player->dx += sin(TO_RAIDANS(player->angle)) * 10; player->dy += -cos(TO_RAIDANS(player->angle)) * 10; player->thrust = sqrt((player->dx * player->dx) + (player->dy * player->dy)); battle.boostTimer = 0; battle.stats[STAT_BOOST]++; } static void deactivateBoost(void) { float v, thrust; thrust = -1; while (thrust != player->thrust) { thrust = player->thrust; v = (player->speed / sqrt(player->thrust)); player->dx = v * player->dx; player->dy = v * player->dy; player->thrust = sqrt((player->dx * player->dx) + (player->dy * player->dy)); } } static void activateECM(void) { battle.ecmTimer = 0; addECMEffect(player); battle.stats[STAT_ECM]++; if (battle.hasSuspicionLevel && !battle.numEnemies && !battle.suspicionCoolOff) { battle.suspicionLevel += (MAX_SUSPICION_LEVEL * 0.25); } } static void switchGuns(void) { int i; i = player->selectedGunType; if (!player->combinedGuns && battle.numPlayerGuns) { do { i = (i + 1) % BT_MAX; } while (!availableGuns[i]); } if (player->selectedGunType != i) { playSound(SND_SELECT_WEAPON); player->selectedGunType = i; } } static void selectTarget(void) { unsigned int closest = MAX_TARGET_RANGE; unsigned int dist = MAX_TARGET_RANGE; int i, total; Entity *e, *near; Entity *targets[MAX_SELECTABLE_TARGETS]; i = 0; near = NULL; memset(targets, 0, sizeof(Entity*) * MAX_SELECTABLE_TARGETS); if (player->target && (!player->target->health || !player->target->systemPower)) { player->target = NULL; } for (e = battle.entityHead.next ; e != NULL ; e = e->next) { if (e->active && e != player && (e->flags & EF_TAKES_DAMAGE) && (!(e->flags & EF_NO_PLAYER_TARGET)) && e->side != player->side && e->alive == ALIVE_ALIVE && e->systemPower > 0 && i < MAX_SELECTABLE_TARGETS) { dist = getDistance(player->x, player->y, e->x, e->y); if (dist < closest) { near = e; closest = dist; } if (collision(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, e->x - battle.camera.x - (e->w / 2), e->y - battle.camera.y - (e->h / 2), e->w, e->h)) { targets[i++] = e; } else if (e == player->target) { player->target = NULL; } } } total = i; for (i = 0 ; i < total ; i++) { if (targets[i] == player->target) { if (i + 1 < MAX_SELECTABLE_TARGETS && targets[i + 1]) { player->target = targets[i + 1]; return; } else { player->target = targets[0]; } } } if (!player->target || !targets[0]) { player->target = near; } } static void selectMissionTarget(void) { unsigned int closest = MAX_TARGET_RANGE; unsigned int dist = MAX_TARGET_RANGE; Entity *e; battle.missionTarget = NULL; for (e = battle.entityHead.next ; e != NULL ; e = e->next) { if (e->active && e->flags & EF_MISSION_TARGET && e->alive == ALIVE_ALIVE) { dist = getDistance(player->x, player->y, e->x, e->y); if (battle.missionTarget == NULL) { battle.missionTarget = e; closest = dist; } else if (battle.missionTarget->type == ET_WAYPOINT && e->type != ET_WAYPOINT) { battle.missionTarget = e; } else if (battle.missionTarget->type != ET_WAYPOINT) { if (isPriorityMissionTarget(e, dist, closest)) { battle.missionTarget = e; closest = dist; } } else if (battle.missionTarget->type == ET_WAYPOINT && e->type == ET_WAYPOINT && e->id == battle.missionTarget->id) { battle.missionTarget = e; } } } } static int isPriorityMissionTarget(Entity *e, int dist, int closest) { /* battle.missionTarget is secondary, e is not */ if ((battle.missionTarget->flags & EF_SECONDARY_TARGET) > (e->flags & EF_SECONDARY_TARGET)) { return 1; } /* battle.missionTarget is not secondary, e is */ if ((battle.missionTarget->flags & EF_SECONDARY_TARGET) < (e->flags & EF_SECONDARY_TARGET)) { return 0; } /* normal distance check */ return dist < closest; } void setInitialPlayerAngle(void) { Entity *e; selectMissionTarget(); if (battle.missionTarget) { player->angle = getAngle(player->x, player->y, battle.missionTarget->x, battle.missionTarget->y); } else { selectTarget(); if (player->target) { player->angle = getAngle(player->x, player->y, player->target->x, player->target->y); } else { if (battle.jumpgate) { player->angle = getAngle(player->x, player->y, battle.jumpgate->x, battle.jumpgate->y); } } } for (e = battle.entityHead.next ; e != NULL ; e = e->next) { if (e->side == player->side) { e->angle = player->angle; } } } static void cycleRadarZoom(void) { battle.radarRange = (battle.radarRange + 1) % 3; playSound(SND_ZOOM); } int playerHasGun(int type) { return availableGuns[type]; } static void handleSuspicionLevel(void) { if (battle.hasSuspicionLevel) { /* don't allow the suspicion level to drop too far */ battle.suspicionLevel = MAX(battle.suspicionLevel, -(MAX_SUSPICION_LEVEL * 0.25)); } } void loadPlayer(cJSON *node) { char *type; int side, addFlags; long flags; type = cJSON_GetObjectItem(node, "type")->valuestring; side = lookup(cJSON_GetObjectItem(node, "side")->valuestring); flags = -1; player = spawnFighter(type, 0, 0, side); player->x = BATTLE_AREA_WIDTH / 2; player->y = BATTLE_AREA_HEIGHT / 2; if (cJSON_GetObjectItem(node, "x")) { player->x = (cJSON_GetObjectItem(node, "x")->valuedouble / BATTLE_AREA_CELLS) * BATTLE_AREA_WIDTH; player->y = (cJSON_GetObjectItem(node, "y")->valuedouble / BATTLE_AREA_CELLS) * BATTLE_AREA_HEIGHT; } if (cJSON_GetObjectItem(node, "flags")) { flags = flagsToLong(cJSON_GetObjectItem(node, "flags")->valuestring, &addFlags); } if (flags != -1) { if (addFlags) { player->flags |= flags; } else { player->flags = flags; SDL_LogMessage(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_WARN, "Flags for Player replaced"); } } if (strcmp(type, "Tug") == 0) { battle.stats[STAT_TUG]++; } if (strcmp(type, "Shuttle") == 0) { battle.stats[STAT_SHUTTLE]++; } }
19.900369
208
0.663762
2b31edb8cd686b695e23c1657e2131cf8a6565f8
13,673
h
C
admin/wmi/wbem/providers/win32provider/providers/smbiosprov.h
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
admin/wmi/wbem/providers/win32provider/providers/smbiosprov.h
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
admin/wmi/wbem/providers/win32provider/providers/smbiosprov.h
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
//================================================================= // // SmbiosProv.h // // Copyright (c) 1998-2001 Microsoft Corporation, All Rights Reserved // //================================================================= // Property set identification //============================ #define PROPSET_NAME_SYSTEMPRODUCT L"Win32_ComputerSystemProduct" #define PROPSET_NAME_BASEBOARD L"Win32_BaseBoard" #define PROPSET_NAME_SYSTEMENCLOSURE L"Win32_SystemEnclosure" #define PROPSET_NAME_CACHEMEMORY L"Win32_CacheMemory" #define PROPSET_NAME_PORTCONNECTOR L"Win32_PortConnector" #define PROPSET_NAME_SYSTEMSLOT L"Win32_SystemSlot" //#define PROPSET_NAME_BIOSLANG L"Win32_BiosLanguage" #define PROPSET_NAME_PHYSMEMARRAY L"Win32_PhysicalMemoryArray" #define PROPSET_NAME_PHYSICALMEMORY L"Win32_PhysicalMemory" #define PROPSET_NAME_MEMERROR32 L"Win32_MemoryError32" #define PROPSET_NAME_PORTABLEBATTERY L"Win32_PortableBattery" #define PROPSET_NAME_CURRENTPROBE L"Win32_CurrentProbe" #define PROPSET_NAME_TEMPPROBE L"Win32_TemperatureProbe" #define PROPSET_NAME_VOLTPROBE L"Win32_VoltageProbe" #define PROPSET_NAME_FAN L"Win32_Fan" #define PROPSET_NAME_HEATPIPE L"Win32_HeatPipe" #define PROPSET_NAME_REFRIG L"Win32_Refrigeration" #define PROPSET_NAME_MEMORYDEVICE L"Win32_MemoryDevice" #define PROPSET_NAME_MEMORYARRAY L"Win32_MemoryArray" #define PROPSET_NAME_ONBOARDDEVICE L"Win32_OnBoardDevice" #define PROPSET_NAME_OEMBUCKET L"Win32_OEMBucket" class CWin32SystemProduct : public Provider { public: // Constructor/destructor //======================= CWin32SystemProduct( LPCWSTR strName, LPCWSTR pszNamespace ); ~CWin32SystemProduct( ); // Functions provide properties with current values //================================================= virtual HRESULT GetObject( CInstance* pInstance, long lFlags = 0L ); virtual HRESULT EnumerateInstances( MethodContext* pMethodContext, long lFlags = 0L ); // Utility function(s) //==================== HRESULT LoadPropertyValues( CInstance* pInstance, CSMBios &smbios, PSYSTEMINFO psi ); }; class CWin32BaseBoard : public Provider { public: // Constructor/destructor //======================= CWin32BaseBoard( LPCWSTR strName, LPCWSTR pszNamespace ); ~CWin32BaseBoard( ); // Functions provide properties with current values //================================================= virtual HRESULT GetObject( CInstance* pInstance, long lFlags = 0L ); virtual HRESULT EnumerateInstances( MethodContext* pMethodContext, long lFlags = 0L ); // Utility function(s) //==================== HRESULT LoadPropertyValues( CInstance* pInstance, CSMBios &smbios, PBOARDINFO pbi ); }; class CWin32SystemEnclosure : public Provider { public: // Constructor/destructor //======================= CWin32SystemEnclosure( LPCWSTR strName, LPCWSTR pszNamespace ); ~CWin32SystemEnclosure( ); // Functions provide properties with current values //================================================= virtual HRESULT GetObject( CInstance* pInstance, long lFlags = 0L ); virtual HRESULT EnumerateInstances( MethodContext* pMethodContext, long lFlags = 0L ); // Utility function(s) //==================== HRESULT LoadPropertyValues( CInstance* pInstance, CSMBios &smbios, PENCLOSURE pe ); }; class CWin32CacheMemory : public Provider { public: // Constructor/destructor //======================= CWin32CacheMemory( LPCWSTR strName, LPCWSTR pszNamespace ) ; ~CWin32CacheMemory( ) ; // Functions provide properties with current values //================================================= virtual HRESULT GetObject( CInstance* pInstance, long lFlags = 0L ); virtual HRESULT EnumerateInstances( MethodContext* pMethodContext, long lFlags = 0L ); // Utility function(s) //==================== HRESULT LoadPropertyValues( CInstance* pInstance, CSMBios &smbios, PCACHEINFO pci ); //HRESULT LoadPropertyValues( CInstance* pInstance ) ; }; class CWin32SystemSlot : public Provider { public: // Constructor/destructor //======================= CWin32SystemSlot( LPCWSTR strName, LPCWSTR pszNamespace ) ; ~CWin32SystemSlot() ; // Functions provide properties with current values //================================================= virtual HRESULT GetObject( CInstance* pInstance, long lFlags = 0L ); virtual HRESULT EnumerateInstances( MethodContext* pMethodContext, long lFlags = 0L ); // Utility function(s) //==================== HRESULT LoadPropertyValues( CInstance* pInstance, CSMBios &smbios, PSYSTEMSLOTS pss ); //HRESULT LoadPropertyValues( CInstance* pInstance ) ; }; class CWin32OnBoardDevice : public Provider { public: // Constructor/destructor //======================= CWin32OnBoardDevice( LPCWSTR strName, LPCWSTR pszNamespace ); ~CWin32OnBoardDevice( ); // Functions provide properties with current values //================================================= virtual HRESULT GetObject( CInstance* pInstance, long lFlags = 0L ); virtual HRESULT EnumerateInstances( MethodContext* pMethodContext, long lFlags = 0L ); // Utility function(s) //==================== HRESULT LoadPropertyValues( CInstance* pInstance, CSMBios &smbios, PSHF pshf, UINT instanceNum ); }; class CWin32PortConnector : public Provider { public: // Constructor/destructor //======================= CWin32PortConnector( LPCWSTR strName, LPCWSTR pszNamespace ); ~CWin32PortConnector( ); // Functions provide properties with current values //================================================= virtual HRESULT GetObject( CInstance* pInstance, long lFlags = 0L ); virtual HRESULT EnumerateInstances( MethodContext* pMethodContext, long lFlags = 0L ); // Utility function(s) //==================== HRESULT LoadPropertyValues( CInstance* pInstance, CSMBios &smbios, PPORTCONNECTORINFO ppci ); }; //class CWin32BIOSLanguage : public Provider //{ // // public: // // // Constructor/destructor // //======================= // // CWin32BIOSLanguage( LPCWSTR strName, LPCWSTR pszNamespace ); // ~CWin32BIOSLanguage( ); // // // Functions provide properties with current values // //================================================= // // virtual HRESULT GetObject( CInstance* pInstance, long lFlags = 0L ); // virtual HRESULT EnumerateInstances( MethodContext* pMethodContext, long lFlags = 0L ); // // // Utility // //======== // // DWORD m_dwPlatformId; // // // Utility function(s) // //==================== // // HRESULT LoadPropertyValues( CInstance* pInstance, CSMBios &smbios, PBIOSLANGINFO pbli ); //}; class CWin32PhysicalMemory : public Provider { public: // Constructor/destructor //======================= CWin32PhysicalMemory( LPCWSTR strName, LPCWSTR pszNamespace ); ~CWin32PhysicalMemory( ); // Functions provide properties with current values //================================================= virtual HRESULT GetObject( CInstance* pInstance, long lFlags = 0L ); virtual HRESULT EnumerateInstances( MethodContext* pMethodContext, long lFlags = 0L ); // Utility function(s) //==================== //HRESULT LoadPropertyValues( CInstance* pInstance, CSMBios &smbios, PMEMDEVICE pmd ); HRESULT LoadPropertyValues_MD( CInstance* pInstance, CSMBios &smbios, PMEMDEVICE pmd ); HRESULT LoadPropertyValues_MI( CInstance* pInstance, CSMBios &smbios, PMEMMODULEINFO pmmi ); }; class CWin32PhysMemoryArray : public Provider { public: // Constructor/destructor //======================= CWin32PhysMemoryArray( LPCWSTR strName, LPCWSTR pszNamespace ); ~CWin32PhysMemoryArray( ); // Functions provide properties with current values //================================================= virtual HRESULT GetObject( CInstance* pInstance, long lFlags = 0L ); virtual HRESULT EnumerateInstances( MethodContext* pMethodContext, long lFlags = 0L ); // Utility //======== // Utility function(s) //==================== HRESULT LoadPropertyValues_PMA( CInstance* pInstance, CSMBios &smbios, PPHYSMEMARRAY ppma ); HRESULT LoadPropertyValues_MCI( CInstance* pInstance, CSMBios &smbios, PMEMCONTROLINFO pmci ); }; class CWin32PortableBattery : public Provider { public: // Constructor/destructor //======================= CWin32PortableBattery( LPCWSTR strName, LPCWSTR pszNamespace ); ~CWin32PortableBattery( ); // Functions provide properties with current values //================================================= virtual HRESULT GetObject( CInstance* pInstance, long lFlags = 0L ); virtual HRESULT EnumerateInstances( MethodContext* pMethodContext, long lFlags = 0L ); // Utility //======== // Utility function(s) //==================== HRESULT LoadPropertyValues( CInstance* pInstance, CSMBios &smbios, PPORTABLEBATTERY ppb ); }; class CCimNumericSensor : public Provider { public: // Constructor/destructor //======================= CCimNumericSensor( LPCWSTR strName, LPCWSTR pszNamespace, UINT StructType, LPCWSTR strTag ); //CCimSensor( LPCWSTR strName, LPCWSTR pszNamespace ) ; ~CCimNumericSensor( ) ; // Functions provide properties with current values //================================================= virtual HRESULT GetObject( CInstance* pInstance, long lFlags = 0L ); virtual HRESULT EnumerateInstances( MethodContext* pMethodContext, long lFlags = 0L ); private: // Utility function(s) //==================== HRESULT LoadPropertyValues( CInstance* pInstance, CSMBios &smbios, PPROBEINFO ppi ); UINT m_StructType; CHString m_TagName; }; class CWin32MemoryArray : public Provider { public: // Constructor/destructor //======================= CWin32MemoryArray( LPCWSTR strName, LPCWSTR pszNamespace ); ~CWin32MemoryArray( ); // Functions provide properties with current values //================================================= virtual HRESULT GetObject( CInstance* pInstance, long lFlags = 0L ); virtual HRESULT EnumerateInstances( MethodContext* pMethodContext, long lFlags = 0L ); // Utility function(s) //==================== HRESULT LoadPropertyValues( CInstance* pInstance, CSMBios &smbios, PMEMARRAYMAPADDR pmama ); }; class CWin32MemoryDevice : public Provider { public: // Constructor/destructor //======================= CWin32MemoryDevice( LPCWSTR strName, LPCWSTR pszNamespace ); ~CWin32MemoryDevice( ); // Functions provide properties with current values //================================================= virtual HRESULT GetObject( CInstance* pInstance, long lFlags = 0L ); virtual HRESULT EnumerateInstances( MethodContext* pMethodContext, long lFlags = 0L ); // Utility function(s) //==================== HRESULT LoadPropertyValues( CInstance* pInstance, CSMBios &smbios, PMEMDEVICEMAPADDR pmdma ); }; class CCimCoolingDevice : public Provider { public: // Constructor/destructor //======================= CCimCoolingDevice( LPCWSTR strName, LPCWSTR pszNamespace, UINT StructType, LPCWSTR strTag ); ~CCimCoolingDevice( ) ; // Functions provide properties with current values //================================================= virtual HRESULT GetObject( CInstance* pInstance, long lFlags = 0L ); virtual HRESULT EnumerateInstances( MethodContext* pMethodContext, long lFlags = 0L ); private: // Utility function(s) //==================== HRESULT LoadPropertyValues( CInstance* pInstance, CSMBios &smbios, PCOOLINGDEVICE pcd ); UINT m_StructType; CHString m_TagName; }; class CWin32OEMBucket : public Provider { public: // Constructor/destructor //======================= CWin32OEMBucket( LPCWSTR strName, LPCWSTR pszNamespace ); ~CWin32OEMBucket( ); // Functions provide properties with current values //================================================= virtual HRESULT GetObject( CInstance* pInstance, long lFlags = 0L ); virtual HRESULT EnumerateInstances( MethodContext* pMethodContext, long lFlags = 0L ); // Utility function(s) //==================== HRESULT LoadPropertyValues( CInstance* pInstance, CSMBios &smbios ); };
31.216895
100
0.575148
2b323cd20e1c7e15f8833329a9ad20e105519f9f
59
h
C
samples/net/awsiot_shadow_sample/outdir/qemu_x86/include/generated/generated_dts_board.h
spkolhe/zephyr-aws
93bc23c1b698200808c370dba1a2dea5cd8e6131
[ "Apache-2.0" ]
null
null
null
samples/net/awsiot_shadow_sample/outdir/qemu_x86/include/generated/generated_dts_board.h
spkolhe/zephyr-aws
93bc23c1b698200808c370dba1a2dea5cd8e6131
[ "Apache-2.0" ]
null
null
null
samples/net/awsiot_shadow_sample/outdir/qemu_x86/include/generated/generated_dts_board.h
spkolhe/zephyr-aws
93bc23c1b698200808c370dba1a2dea5cd8e6131
[ "Apache-2.0" ]
null
null
null
/* WARNING. THIS FILE IS AUTO-GENERATED. DO NOT MODIFY! */
29.5
58
0.694915
2b358366304a7aa0ec94275ada983745e5975926
693
h
C
cc/test/FakeCCGraphicsContext.h
quisquous/chromium
b25660e05cddc9d0c3053b3514f07037acc69a10
[ "BSD-3-Clause" ]
2
2020-06-10T07:15:26.000Z
2020-12-13T19:44:12.000Z
cc/test/FakeCCGraphicsContext.h
quisquous/chromium
b25660e05cddc9d0c3053b3514f07037acc69a10
[ "BSD-3-Clause" ]
null
null
null
cc/test/FakeCCGraphicsContext.h
quisquous/chromium
b25660e05cddc9d0c3053b3514f07037acc69a10
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FakeCCGraphicsContext_h #define FakeCCGraphicsContext_h #include "CCGraphicsContext.h" #include "CompositorFakeWebGraphicsContext3D.h" #include "FakeWebCompositorOutputSurface.h" #include <public/WebCompositorOutputSurface.h> namespace WebKit { static inline PassOwnPtr<cc::CCGraphicsContext> createFakeCCGraphicsContext() { return FakeWebCompositorOutputSurface::create(CompositorFakeWebGraphicsContext3D::create(WebGraphicsContext3D::Attributes())); } } // namespace WebKit #endif // FakeCCGraphicsContext_h
30.130435
130
0.816739
2b36ff2799512c3d9e5c33ed3f9747a261aa4ac7
3,841
h
C
INET_EC/transportlayer/rtp/RTCPPacket3_m.h
LarryNguyen/ECSim-
0d3f848642e49845ed7e4c7b97dd16bd3d65ede5
[ "Apache-2.0" ]
null
null
null
INET_EC/transportlayer/rtp/RTCPPacket3_m.h
LarryNguyen/ECSim-
0d3f848642e49845ed7e4c7b97dd16bd3d65ede5
[ "Apache-2.0" ]
null
null
null
INET_EC/transportlayer/rtp/RTCPPacket3_m.h
LarryNguyen/ECSim-
0d3f848642e49845ed7e4c7b97dd16bd3d65ede5
[ "Apache-2.0" ]
1
2018-10-09T05:00:05.000Z
2018-10-09T05:00:05.000Z
// // Generated file, do not edit! Created by nedtool 5.1 from inet/transportlayer/rtp/RTCPPacket3.msg. // #if defined(__clang__) # pragma clang diagnostic ignored "-Wreserved-id-macro" #endif #ifndef __INET__RTP_RTCPPACKET3_M_H #define __INET__RTP_RTCPPACKET3_M_H #include <omnetpp.h> // nedtool version check #define MSGC_VERSION 0x0501 #if (MSGC_VERSION!=OMNETPP_VERSION) # error Version mismatch! Probably this file was generated by an earlier version of nedtool: 'make clean' should help. #endif // dll export symbol #ifndef INET_API # if defined(INET_EXPORT) # define INET_API OPP_DLLEXPORT # elif defined(INET_IMPORT) # define INET_API OPP_DLLIMPORT # else # define INET_API # endif #endif // cplusplus {{ #include "inet/transportlayer/rtp/RTCPPacket2.h" #include "inet/transportlayer/rtp/reports.h" #include "inet/transportlayer/rtp/sdes.h" // }} namespace inet { namespace rtp { /** * Class generated from <tt>inet/transportlayer/rtp/RTCPPacket3.msg:28</tt> by nedtool. * <pre> * packet RTCPSenderReportPacket extends RTCPReceiverReportPacket * { * packetType = RTCP_PT_SR; * \@customize(true); // see the generated C++ header for more info * SenderReport senderReport; * } * </pre> * * RTCPSenderReportPacket_Base is only useful if it gets subclassed, and RTCPSenderReportPacket is derived from it. * The minimum code to be written for RTCPSenderReportPacket is the following: * * <pre> * class INET_API RTCPSenderReportPacket : public RTCPSenderReportPacket_Base * { * private: * void copy(const RTCPSenderReportPacket& other) { ... } * public: * RTCPSenderReportPacket(const char *name=nullptr, short kind=0) : RTCPSenderReportPacket_Base(name,kind) {} * RTCPSenderReportPacket(const RTCPSenderReportPacket& other) : RTCPSenderReportPacket_Base(other) {copy(other);} * RTCPSenderReportPacket& operator=(const RTCPSenderReportPacket& other) {if (this==&other) return *this; RTCPSenderReportPacket_Base::operator=(other); copy(other); return *this;} * virtual RTCPSenderReportPacket *dup() const override {return new RTCPSenderReportPacket(*this);} * // ADD CODE HERE to redefine and implement pure virtual functions from RTCPSenderReportPacket_Base * }; * </pre> * * The following should go into a .cc (.cpp) file: * * <pre> * Register_Class(RTCPSenderReportPacket) * </pre> */ class INET_API RTCPSenderReportPacket_Base : public ::inet::rtp::RTCPReceiverReportPacket { protected: SenderReport senderReport; private: void copy(const RTCPSenderReportPacket_Base& other); protected: // protected and unimplemented operator==(), to prevent accidental usage bool operator==(const RTCPSenderReportPacket_Base&); // make constructors protected to avoid instantiation RTCPSenderReportPacket_Base(const char *name=nullptr, short kind=0); RTCPSenderReportPacket_Base(const RTCPSenderReportPacket_Base& other); // make assignment operator protected to force the user override it RTCPSenderReportPacket_Base& operator=(const RTCPSenderReportPacket_Base& other); public: virtual ~RTCPSenderReportPacket_Base(); virtual RTCPSenderReportPacket_Base *dup() const override {throw omnetpp::cRuntimeError("You forgot to manually add a dup() function to class RTCPSenderReportPacket");} virtual void parsimPack(omnetpp::cCommBuffer *b) const override; virtual void parsimUnpack(omnetpp::cCommBuffer *b) override; // field getter/setter methods virtual SenderReport& getSenderReport(); virtual const SenderReport& getSenderReport() const {return const_cast<RTCPSenderReportPacket_Base*>(this)->getSenderReport();} virtual void setSenderReport(const SenderReport& senderReport); }; } // namespace rtp } // namespace inet #endif // ifndef __INET__RTP_RTCPPACKET3_M_H
35.238532
185
0.754231
2b39040ab094b05623999c3a3302b9409e9208e2
2,357
h
C
tools/uf2/source/board.h
BRTSG-FOSS/pico-bteve
1697b9a972ad5e9c2cecca6d560aa16cab725a61
[ "MIT" ]
1
2022-01-29T03:16:57.000Z
2022-01-29T03:16:57.000Z
tools/uf2/source/board.h
BRTSG-FOSS/pico-brteve
1697b9a972ad5e9c2cecca6d560aa16cab725a61
[ "MIT" ]
15
2021-09-22T08:36:08.000Z
2022-01-26T08:51:42.000Z
tools/uf2/source/board.h
BRTSG-FOSS/pico-bteve
1697b9a972ad5e9c2cecca6d560aa16cab725a61
[ "MIT" ]
null
null
null
/* * The MIT License (MIT) * * Copyright (c) 2018 Ha Thach for Adafruit Industries * Copyright (c) 2021 Bridgetek Pte Ltd * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #ifndef BOARD_H_ #define BOARD_H_ #define UF2_VERSION_BASE "0.3.0" #define UF2_VERSION UF2_VERSION_BASE " for Bridgetek EVE" extern unsigned char g_UsbProduct[64]; extern uint32_t g_Uf2FamilyId; extern unsigned char g_DeviceName[64]; #define MATRIX_RAIN 1 //--------------------------------------------------------------------+ // USB UF2 //--------------------------------------------------------------------+ #define USB_VID_FTDI 0x0403 #define USB_PID_MASS_STORAGE 0x0fd5 #define USB_VID USB_VID_FTDI #define USB_PID USB_PID_MASS_STORAGE #define USB_MANUFACTURER "Bridgetek Pte Ltd" #define USB_PRODUCT g_UsbProduct #define UF2_PRODUCT_NAME "Bridgetek BT8XX" #define UF2_BOARD_ID "BT8XX-RP2040-v0.0" #define UF2_VOLUME_LABEL "BTEVE-FLASH" #define UF2_INDEX_URL "https://brtchip.com" #define BOARD_UF2_FAMILY_ID g_Uf2FamilyId #define DISPLAY_TITLE g_DeviceName #define DISPLAY_WIDTH 240 #define DISPLAY_HEIGHT 320 // Size of firmware that is device family specific #define EVE_FLASH_FIRMWARE_SIZE 4096 #endif
36.261538
81
0.693678
2b3adf4459bd7836fa05d70911ab9df13f0d8b15
129
h
C
Vendor/GLM/glm/simd/geometric.h
wdrDarx/DEngine3
27e2de3b56b6d4c8705e8a0e36f5911d8651caa2
[ "MIT" ]
2
2022-01-11T21:15:31.000Z
2022-02-22T21:14:33.000Z
Vendor/GLM/glm/simd/geometric.h
wdrDarx/DEngine3
27e2de3b56b6d4c8705e8a0e36f5911d8651caa2
[ "MIT" ]
null
null
null
Vendor/GLM/glm/simd/geometric.h
wdrDarx/DEngine3
27e2de3b56b6d4c8705e8a0e36f5911d8651caa2
[ "MIT" ]
null
null
null
version https://git-lfs.github.com/spec/v1 oid sha256:b3bfad1960c1663f9a4bf202373140e2f2342ae572843e35b01c032c52592f4a size 3922
32.25
75
0.883721
2b3b52edce26652da4f0621096e4cf689afc22eb
452
h
C
sources/lv1/driver/rsx/device/fb.h
AlexAltea/lv1-reversing
3d9ea0a243e403a9b5eb881e9c97949a72e47ef1
[ "MIT" ]
16
2016-03-16T21:25:49.000Z
2021-09-26T03:58:42.000Z
sources/lv1/driver/rsx/device/fb.h
x0rloser/lv1-reversing
3d9ea0a243e403a9b5eb881e9c97949a72e47ef1
[ "MIT" ]
null
null
null
sources/lv1/driver/rsx/device/fb.h
x0rloser/lv1-reversing
3d9ea0a243e403a9b5eb881e9c97949a72e47ef1
[ "MIT" ]
4
2018-03-26T11:05:33.000Z
2021-03-13T18:21:20.000Z
/** * (c) 2016 The LV1RE Project. * Released under MIT license. Read LICENSE for more details. */ #pragma once #include "common/types.h" // RSX framebuffer object, size 0x10 struct rsx_device_fb_t { S32 DDR_MB_CTags; // 0x00: 0x80000 S32 size; // 0x04: BAR1(VRAM) size: 0x10000000(256 MB) S64 addr; // 0x08: BAR1(VRAM) address: 0x28080000000 // Methods void sub21ADAC(); void init(); };
22.6
72
0.612832
2b42422ead7bb82102db375d8e1d95c04b6ec5be
401
h
C
TapBundleLocalization/TapBundleLocalization.h
Tap-Payments/TapBundleLocalization-iOS
523e4ff020ed4be488013901c1eb226e03d60890
[ "MIT" ]
null
null
null
TapBundleLocalization/TapBundleLocalization.h
Tap-Payments/TapBundleLocalization-iOS
523e4ff020ed4be488013901c1eb226e03d60890
[ "MIT" ]
null
null
null
TapBundleLocalization/TapBundleLocalization.h
Tap-Payments/TapBundleLocalization-iOS
523e4ff020ed4be488013901c1eb226e03d60890
[ "MIT" ]
null
null
null
// // TapBundleLocalization.h // TapBundleLocalization // // Copyright © 2019 Tap Payments. All rights reserved. // @import Foundation.NSObjCRuntime; //! Project version number for TapBundleLocalization. FOUNDATION_EXPORT double TapBundleLocalizationVersionNumber; //! Project version string for TapBundleLocalization. FOUNDATION_EXPORT const unsigned char TapBundleLocalizationVersionString[];
26.733333
75
0.812968
2b498bdc5d13ea77908f4c9b6ab8fccec7735110
1,473
h
C
folly/experimental/wangle/concurrent/IOThreadPoolExecutor.h
zunc/folly
4ecd8cdd6396f2f4cbfc17c1063537884e3cd6b9
[ "Apache-2.0" ]
null
null
null
folly/experimental/wangle/concurrent/IOThreadPoolExecutor.h
zunc/folly
4ecd8cdd6396f2f4cbfc17c1063537884e3cd6b9
[ "Apache-2.0" ]
null
null
null
folly/experimental/wangle/concurrent/IOThreadPoolExecutor.h
zunc/folly
4ecd8cdd6396f2f4cbfc17c1063537884e3cd6b9
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2014 Facebook, 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. */ #pragma once #include <folly/experimental/wangle/concurrent/ThreadPoolExecutor.h> #include <folly/io/async/EventBase.h> namespace folly { namespace wangle { class IOThreadPoolExecutor : public ThreadPoolExecutor { public: explicit IOThreadPoolExecutor( size_t numThreads, std::unique_ptr<ThreadFactory> threadFactory = folly::make_unique<NamedThreadFactory>("IOThreadPool")); ~IOThreadPoolExecutor(); void add(Func func) override; private: ThreadPtr makeThread() override; void threadRun(ThreadPtr thread) override; void stopThreads(size_t n) override; struct FOLLY_ALIGN_TO_AVOID_FALSE_SHARING IOThread : public Thread { IOThread() : shouldRun(true), outstandingTasks(0) {}; std::atomic<bool> shouldRun; std::atomic<size_t> outstandingTasks; EventBase eventBase; }; size_t nextThread_; }; }} // folly::wangle
29.46
75
0.740665
2b4b3acf7302d76f488681e3255102607aac72ae
913
h
C
include/uml/stereotype.h
nemears/uml-cpp
d72c8b5506f391f2b6a5696972ff8da7ec10bd21
[ "MIT" ]
null
null
null
include/uml/stereotype.h
nemears/uml-cpp
d72c8b5506f391f2b6a5696972ff8da7ec10bd21
[ "MIT" ]
1
2022-02-25T18:14:21.000Z
2022-03-10T08:59:55.000Z
include/uml/stereotype.h
nemears/uml-cpp
d72c8b5506f391f2b6a5696972ff8da7ec10bd21
[ "MIT" ]
null
null
null
#ifndef _UML_STEREOTYPE_H_ #define _UML_STEREOTYPE_H_ #include "class.h" #include "profile.h" namespace UML { class Profile; typedef UmlPtr<Profile> ProfilePtr; class Stereotype : public Class { friend class UmlManager; friend class Profile; private: Singleton<Profile, Stereotype> m_profile = Singleton<Profile, Stereotype>(this); Set<Profile, Stereotype>& getProfileSingleton(); void init(); Stereotype(); public: virtual ~Stereotype(); ProfilePtr getProfile() const; void setProfile(Profile& profile); void setProfile(Profile* profile); void setProfile(ID id); bool isSubClassOf(ElementType eType) const override; static ElementType elementType() { return ElementType::STEREOTYPE; }; }; } #endif
26.085714
92
0.603505
2b4b7e895142aabc6cc20c82e457f262e9fe6e4b
892
h
C
src/core/Page.h
minyor/PocoBlog
9556c5e70618dd64abd36913cc34c5c373b5673f
[ "BSD-2-Clause" ]
5
2016-01-19T02:12:40.000Z
2018-01-12T09:20:53.000Z
src/core/Page.h
minyor/PocoBlog
9556c5e70618dd64abd36913cc34c5c373b5673f
[ "BSD-2-Clause" ]
null
null
null
src/core/Page.h
minyor/PocoBlog
9556c5e70618dd64abd36913cc34c5c373b5673f
[ "BSD-2-Clause" ]
null
null
null
// // Pages registration and operation on them // // Copyright (c) 2016, minyor. // // License: BSD // #ifndef CORE_PAGE_H #define CORE_PAGE_H #include <core/Header.h> #include <core/Server.h> #include <core/Session.h> namespace core { typedef void *(*NewClass)(); class Page { NewClass _newClass; std::string _path; friend void Server::addPage(Page *page); friend Poco::Net::HTTPRequestHandler *Server::newHandler(const std::string &path); virtual Poco::Net::HTTPRequestHandler *newHandler(); public: Page(); virtual ~Page(); public: virtual Page &self() { return *this; } public: __inline void newClass(NewClass val) { _newClass = val; } __inline NewClass newClass() const { return _newClass; } __inline void path(const std::string &val) { _path = val; } __inline const std::string &path() const { return _path; } }; } #endif // CORE_PAGE_H
17.490196
84
0.681614
2b4c6ab51bba2b10033d3830ceab0d8a9cc6353a
269
h
C
gaugeview.h
tleino/xrtgauge
957f41bfc12edd8d22c52f4f316225702caeb6aa
[ "0BSD" ]
null
null
null
gaugeview.h
tleino/xrtgauge
957f41bfc12edd8d22c52f4f316225702caeb6aa
[ "0BSD" ]
null
null
null
gaugeview.h
tleino/xrtgauge
957f41bfc12edd8d22c52f4f316225702caeb6aa
[ "0BSD" ]
null
null
null
#ifndef GRAPHVIEW_H #define GRAPHVIEW_H struct gfxctx; struct gaugeview; struct gauge; void gaugeview_draw_value(struct gaugeview *, double, double); struct gaugeview* gaugeview_open(struct gauge *, struct gfxctx *); void gaugeview_clear(struct gaugeview *); #endif
20.692308
66
0.795539
2b4dd2beff1d56ff9ae2a66aad4bac08d30ba0a4
286
h
C
hv/test/kvm-unit-tests/lib/ppc64/asm/io.h
wtliang110/lk_hv
fbbbb280114c44bf321b8f02301a84e3c469d8a2
[ "MIT" ]
4
2022-02-24T06:16:42.000Z
2022-02-24T23:49:29.000Z
hv/test/kvm-unit-tests/lib/ppc64/asm/io.h
wtliang110/lk_hv
fbbbb280114c44bf321b8f02301a84e3c469d8a2
[ "MIT" ]
null
null
null
hv/test/kvm-unit-tests/lib/ppc64/asm/io.h
wtliang110/lk_hv
fbbbb280114c44bf321b8f02301a84e3c469d8a2
[ "MIT" ]
null
null
null
#ifndef _ASMPPC64_IO_H_ #define _ASMPPC64_IO_H_ #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ #define __cpu_is_be() (0) #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ #define __cpu_is_be() (1) #else #error Undefined byte order #endif #define __iomem #include <asm-generic/io.h> #endif
17.875
45
0.786713
2b50bd0c6f6f6af065d8129e43c23a7259ea50f2
1,153
h
C
Bullet OAC/PolynomInterpolator.h
Schweigert/shaders
ae3fbcb48d22fdfb0eb00d3f4451e99f97891c81
[ "MIT" ]
null
null
null
Bullet OAC/PolynomInterpolator.h
Schweigert/shaders
ae3fbcb48d22fdfb0eb00d3f4451e99f97891c81
[ "MIT" ]
null
null
null
Bullet OAC/PolynomInterpolator.h
Schweigert/shaders
ae3fbcb48d22fdfb0eb00d3f4451e99f97891c81
[ "MIT" ]
null
null
null
/** \file PolynomInterpolator.h \brief Descricao da classe PolynomInterpolator Esta classe tem por objetivo implementar uma interpola�ao Polynom entre atributos fornecidos Desenvolvido por Marlon Henry Schweigert<br> Abril, 2017. Universidade do Estado de Santa Catarina - UDESC<br> */ #ifndef _POLYNOMINTERPOLATOR_NOT_INCLUDED_ #define _POLYNOMINTERPOLATOR_NOT_INCLUDED_ #include "Interpolator.h" #include "Matrix.h" #include "PoseAttr.h" #include "AttrVector3.h" class PolynomInterpolator : public Interpolator { protected: Matrix* matrixX; Matrix* matrixY; Matrix* matrixZ; Matrix* matrixW; int iControlPoints; double dTmin, dTmax; double* pdCoefficientsX; double* pdCoefficientsY; double* pdCoefficientsZ; double* pdCoefficientsW; private: double Px(double); double Py(double); double Pz(double); double Pw(double); PoseAttr::AttrName attrName; public: PolynomInterpolator(AttrVector3::AttrName); PolynomInterpolator( const PolynomInterpolator & ); PolynomInterpolator( PolynomInterpolator* ); void Setup (); void OnLoop( double ); }; #endif
21.754717
95
0.732871
2b5253eb842a26c595dda4d4d11fab4f9632ebc4
1,830
h
C
components/drivers/peripheral/i2c/include/vfsdev/i2c_dev.h
wstong999/AliOS-Things
6554769cb5b797e28a30a4aa89b3f4cb2ef2f5d9
[ "Apache-2.0" ]
4,538
2017-10-20T05:19:03.000Z
2022-03-30T02:29:30.000Z
components/drivers/peripheral/i2c/include/vfsdev/i2c_dev.h
wstong999/AliOS-Things
6554769cb5b797e28a30a4aa89b3f4cb2ef2f5d9
[ "Apache-2.0" ]
1,088
2017-10-21T07:57:22.000Z
2022-03-31T08:15:49.000Z
components/drivers/peripheral/i2c/include/vfsdev/i2c_dev.h
willianchanlovegithub/AliOS-Things
637c0802cab667b872d3b97a121e18c66f256eab
[ "Apache-2.0" ]
1,860
2017-10-20T05:22:35.000Z
2022-03-27T10:54:14.000Z
/* * Copyright (C) 2015-2021 Alibaba Group Holding Limited */ #ifndef _IO_I2C_H_ #define _IO_I2C_H_ #ifdef __cplusplus extern "C" { #endif /** @defgroup i2c_device_api * @ingroup driver_api * @{ */ /* I2C VFS IOCTL CMD宏定义 */ #define IOC_I2C_BASE 'I' #define IOC_I2C_SET_FREQ IOC_I2C_BASE + 1 /**< 设定I2C频率cmd宏定义 */ #define IOC_I2C_SET_CONFIG IOC_I2C_BASE + 2 /**< 设定除频率外其它I2C参数cmd宏定义 */ #define IOC_I2C_MASTER_RX IOC_I2C_BASE + 3 /**< 用master模式发起I2C接收操作cmd宏定义 */ #define IOC_I2C_MASTER_TX IOC_I2C_BASE + 4 /**< 用master模式发起I2C发送操作cmd宏定义 */ #define IOC_I2C_SLAVE_RX IOC_I2C_BASE + 5 /**< 用slave模式发起I2C接收操作cmd宏定义 - 暂不支持 */ #define IOC_I2C_SLAVE_TX IOC_I2C_BASE + 6 /**< 用slave模式发起I2C发送操作cmd宏定义 - 暂不支持 */ #define IOC_I2C_MEM_RX IOC_I2C_BASE + 7 /**< 用master模式发起I2C读取寄存器操作cmd宏定义 */ #define IOC_I2C_MEM_TX IOC_I2C_BASE + 8 /**< 用master模式发起I2C写入寄存器操作cmd宏定义 */ /* 设定i2c参数所用结构体 */ typedef union { struct { unsigned int addr_width:2; /**< 0:7-bit地址模式;1:10-bit地址模式 */ unsigned int role:1; /**< 1:i2c主设备模式;0:i2c从设备模式,暂不支持从设备模式设定 */ unsigned int addr:16; /**< i2c从设备地址 */ } c; uint32_t freq; /**< i2c clk引脚时钟频率 */ } io_i2c_control_u; /* i2c数据收发操作所用结构体 */ typedef struct { unsigned short addr; /**< 此次读写操作对应的i2c送设备地址 */ unsigned short length; /**< 此次读写操作要读写数据的长度 */ unsigned char *data; /**< 写操作:指向要发送数据的首地址;读操作:指向接收数据存放内存块首地址 */ unsigned short maddr; /**< 此次内存操作要读写的memory地址,只有在ioctl cmd id为IOC_I2C_MEM_TX/IOC_I2C_MEM_RX时有效 */ unsigned short mlength; /**< 此次内存操作要读写的memory的长度,只有在ioctl cmd id为IOC_I2C_MEM_TX/IOC_I2C_MEM_RX时有效 */ unsigned int timeout; /**< 此次操作的超时时间,单位:ms */ } io_i2c_data_t; /** * @} */ #ifdef __cplusplus } #endif #endif //_IO_I2C_H_
32.678571
112
0.663934
2b52f5de36a1680d0bd9a2d1f21eaa567521dc4c
6,511
c
C
autosize.c
twonds/chesspark
6896953cc6b5042116a7de981ecd9c8beeb5b72b
[ "curl", "OpenSSL" ]
1
2016-05-09T04:58:18.000Z
2016-05-09T04:58:18.000Z
autosize.c
twonds/chesspark
6896953cc6b5042116a7de981ecd9c8beeb5b72b
[ "curl", "OpenSSL" ]
null
null
null
autosize.c
twonds/chesspark
6896953cc6b5042116a7de981ecd9c8beeb5b72b
[ "curl", "OpenSSL" ]
null
null
null
#include <stdlib.h> #include "box.h" #include "boxtypes.h" #include "autosize.h" struct autosizedata_s { enum autosizeflags flags; int minw; int minh; int maxw; int maxh; int spacing; }; struct Box_s *AutoSize_Create(int x, int y, int minw, int minh, int maxw, int maxh, enum autosizeflags flags) { struct Box_s *autosize = Box_Create(x, y, minw, minh, BOX_VISIBLE | BOX_TRANSPARENT); struct autosizedata_s *data = malloc(sizeof(*data)); memset(data, 0, sizeof(*data)); data->flags = flags; data->minw = minw; data->minh = minh; data->maxw = maxw; data->maxh = maxh; autosize->boxtypeid = BOXTYPE_AUTOSIZE; autosize->boxdata = data; return autosize; } struct Box_s *AutoSizeSpace_Create(int x, int y, int minw, int minh, int maxw, int maxh, int spacing, enum autosizeflags flags) { struct Box_s *autosize = AutoSize_Create(x, y, minw, minh, maxw, maxh, flags); struct autosizedata_s *data = autosize->boxdata; data->spacing = spacing; return autosize; } void AutoSize_Fit(struct Box_s *autosize) { struct Box_s *child; struct autosizedata_s *data = autosize->boxdata; int x=0, y=0; child = autosize->child; while (child) { AutoSize_Fit(child); child = child->sibling; } if (autosize->boxtypeid != BOXTYPE_AUTOSIZE) { return; } if (!(autosize->flags & BOX_VISIBLE)) { autosize->w = 0; autosize->h = 0; return; } if (data->flags & AUTOSIZE_EVENSPACING) { int spacing = 0; if (data->flags & AUTOSIZE_VERT) { child = autosize->child; while (child) { if ((child->flags & BOX_VISIBLE) && child->h > spacing) { spacing = child->h; } child = child->sibling; } child = autosize->child; while (child) { if (child->flags & BOX_VISIBLE) { child->y = y; y += spacing; if (child->w > x) { x = child->w; } } child = child->sibling; } } else { child = autosize->child; while (child) { if ((child->flags & BOX_VISIBLE) && child->w > spacing) { spacing = child->w; } child = child->sibling; } child = autosize->child; while (child) { if (child->flags & BOX_VISIBLE) { child->x = x; x += spacing; if (child->h > y) { y = child->h; } } child = child->sibling; } } } else { if (data->flags & AUTOSIZE_VERT) { int previous = 0; child = autosize->child; while (child) { if (child->flags & BOX_VISIBLE) { if (previous) { y += data->spacing; } previous = 1; child->y = y; y += child->h; if (child->OnSizeWidth == Box_OnSizeWidth_StickRight) { if (child->w + child->x > x) { x = child->w + child->x; } } else { if (child->w + child->x * 2 > x) { x = child->w + child->x * 2; } } } child = child->sibling; } } else { int previous = 0; child = autosize->child; while (child) { if (child->flags & BOX_VISIBLE) { if (previous) { x += data->spacing; } previous = 1; child->x = x; x += child->w; if (child->h + child->y > y) { y = child->h + child->y; } } child = child->sibling; } } } if (data->minw && x < data->minw) { x = data->minw; } if (data->maxw && x > data->maxw) { x = data->maxw; } if (data->minh && y < data->minh) { y = data->minh; } if (data->maxh && y > data->maxh) { y = data->maxh; } autosize->w = x; autosize->h = y; } void AutoSize_Fill(struct Box_s *autosize) { struct Box_s *child; struct autosizedata_s *data = autosize->boxdata; int x=0, y=0; if (autosize->boxtypeid != BOXTYPE_AUTOSIZE) { child = autosize->child; while (child) { AutoSize_Fill(child); child = child->sibling; } return; } child = autosize->child; if (data->flags & AUTOSIZE_VERT) { while (child) { if (child->OnSizeWidth == Box_OnSizeWidth_StickRight) { child->x = autosize->w - child->w; } else if (child->OnSizeWidth && autosize->w - child->w - child->x * 2) { child->OnSizeWidth(child, autosize->w - child->w - child->x * 2); } /* assumes that one child, and exactly one child, is vertically scalable */ if (child->OnSizeHeight == Box_OnSizeHeight_StickBottom) { child->y = autosize->h - child->h; } else if (child->OnSizeHeight) { int remaining = autosize->h; struct Box_s *child2 = autosize->child; while (child2) { if (child2 != child && child2->flags & BOX_VISIBLE) { remaining -= child2->h; } child2 = child2->sibling; } child->OnSizeHeight(child, remaining - child->h); } child = child->sibling; } } else { while (child) { if (child->OnSizeHeight == Box_OnSizeHeight_StickBottom) { child->y = autosize->h - child->h; } else if (child->OnSizeHeight && autosize->h - child->h - child->y * 2) { child->OnSizeHeight(child, autosize->h - child->h - child->y * 2); } /* assumes that one child, and exactly one child, is horizontally scalable */ if (child->OnSizeWidth == Box_OnSizeWidth_StickRight) { child->x = autosize->w - child->w; } else if (child->OnSizeWidth) { int remaining = autosize->w; struct Box_s *child2 = autosize->child; while (child2) { if (child2 != child && child2->flags & BOX_VISIBLE) { remaining -= child2->w; } child2 = child2->sibling; } child->OnSizeWidth(child, remaining - child->w); } child = child->sibling; } } child = autosize->child; while (child) { AutoSize_Fill(child); child = child->sibling; } } struct Box_s *AutoSize_AddSpacer(struct Box_s *autosize, int spacersize) { struct autosizedata_s *data = autosize->boxdata; struct Box_s *spacer; if (data->flags & AUTOSIZE_VERT) { spacer = Box_Create(0, 0, 0, spacersize, BOX_VISIBLE | BOX_TRANSPARENT); } else { spacer = Box_Create(0, 0, spacersize, 0, BOX_VISIBLE | BOX_TRANSPARENT); } Box_AddChild(autosize, spacer); return spacer; }
17.936639
128
0.546153
2b533a8f8879f5b3ee2cd5cb6eace861bba90bbe
3,138
h
C
src/partitioning.h
kspalm/mlsvm
808f5b81f2b19d32a1e472bd9b358f7a81e73736
[ "BSD-2-Clause" ]
3
2020-10-02T21:13:19.000Z
2020-11-21T18:24:17.000Z
src/partitioning.h
kspalm/mlsvm
808f5b81f2b19d32a1e472bd9b358f7a81e73736
[ "BSD-2-Clause" ]
null
null
null
src/partitioning.h
kspalm/mlsvm
808f5b81f2b19d32a1e472bd9b358f7a81e73736
[ "BSD-2-Clause" ]
1
2022-03-23T01:36:21.000Z
2022-03-23T01:36:21.000Z
#ifndef PARTITIONING_H #define PARTITIONING_H #include "petscmat.h" #include <vector> #include <unordered_set> #include <algorithm> //#include <map> #include "solver.h" #include "model_selection.h" #include <metis.h> class Partitioning{ void scale_edge_weights(idx_t *adjwgt, PetscInt num_edge, PetscScalar *arr_adjwgt); public: int get_parts(Mat& m_WA, Vec& v_vol, int num_req_parts, int level, std::vector<std::vector<PetscInt>>& vv_parts, Mat& m_parts, unsigned int metis_seed=1); void single_part_matrix(Mat& m_neigh_Data, Mat& m_parts); void calc_single_center(Mat& m_neigh_Data, Vec& v_vol, Mat& m_centers, std::vector<PetscScalar>& v_sum_vol_parts); void calc_center(Mat& m_neigh_Data, Vec& v_neigh_vol, std::vector<std::vector<PetscInt>>& vv_parts, Mat& m_parts, Mat& m_centers, std::vector<PetscScalar>& v_sum_vol_parts); void calc_distances(int num_part_p, int num_part_n, Mat& m_centers_p,Mat& m_centers_n, Mat& m_dist); void find_groups(int num_part_p, int num_part_n, Mat& m_dist, std::vector<std::pair<int, int> >& v_groups); void calc_avg_center(Mat& m_centers_p, Mat& m_centers_n, std::vector<std::pair<int, int> >& v_groups , std::vector<PetscScalar>& v_sum_vol_parts_p, std::vector<PetscScalar>& v_sum_vol_parts_n, Mat& m_avg_centers); void calc_center_volume(Mat& m_centers, std::vector<PetscScalar>& v_sum_vol_parts, Mat& m_center_vol); void create_group_index(int target_group, std::vector<std::pair<int, int> > v_groups, Mat& m_parts_p, Mat& m_parts_n, std::vector<PetscInt>& v_p_index, std::vector<PetscInt>& v_n_index); void calc_performance_measure(Mat& m_TD, std::vector<Mat>& v_mat_avg_center, std::vector<Mat>& v_mat_predicted_labels, summary& result_summary); void calc_performance_measure(PetscInt num_VD_p, PetscInt num_VD_n, std::vector<Mat>& v_mat_avg_center, std::vector<Mat>& v_mat_predicted_labels, summary& result_summary); // void calc_majority_voting(Mat& m_predicted_labels, int num_TD_points, std::vector<double>& v_final_predicted_label ); void calc_majority_voting(std::vector<Mat>& v_mat_predicted_labels, int num_TD_points, std::vector<double>& v_final_predicted_label ); // void calc_majority_voting_distance_weight(Mat& m_predicted_labels, int num_TD, Mat& m_TD, Mat& m_AC, // int distance_id, std::vector<double>& v_final_predicted_label ); void calc_majority_voting_distance_weight(std::vector<Mat>& v_mat_predicted_labels, int num_TD, Mat& m_TD, std::vector<Mat>& v_mat_AC, int distance_id, std::vector<double>& v_final_predicted_label ); void calc_majority_voting_nearest(std::vector<Mat>& v_mat_predicted_labels, int num_TD, Mat& m_TD, std::vector<Mat>& v_mat_AC, int distance_id, std::vector<double>& v_final_predicted_label ); }; #endif // PARTITIONING_H
50.612903
158
0.684194
2b59066412b09549d4290069f4ae98a2a31fb0b9
337
h
C
DiscuzQ_Mobile/DiscuzQ/Classes/DataContext/HelperConfig/DZDataHelper.h
webersongao/DiscuzQ_iOS
71ee9bdbcce2fcadc18e1916febcea8d3470e704
[ "Apache-2.0" ]
27
2020-04-05T14:02:58.000Z
2021-09-13T02:14:12.000Z
DiscuzQ_Mobile/DiscuzQ/Classes/DataContext/HelperConfig/DZDataHelper.h
webersongao/DiscuzQ_iOS
71ee9bdbcce2fcadc18e1916febcea8d3470e704
[ "Apache-2.0" ]
null
null
null
DiscuzQ_Mobile/DiscuzQ/Classes/DataContext/HelperConfig/DZDataHelper.h
webersongao/DiscuzQ_iOS
71ee9bdbcce2fcadc18e1916febcea8d3470e704
[ "Apache-2.0" ]
6
2020-07-18T11:36:11.000Z
2022-01-30T06:09:48.000Z
// // DZDataHelper.h // DiscuzQ // 联系作者:微信: ChinaMasker gao@btbk.org // Github :https://github.com/webersongao/DiscuzQ_iOS // Created by WebersonGao on 2019/11/15. // Copyright © 2019 WebersonGao. All rights reserved. // #import "EFSQLiteHelper.h" @interface DZDataHelper : EFSQLiteHelper + (DZDataHelper *)sharedHelper; @end
18.722222
54
0.721068
2b59756ea06ed820082d044135c2d8bb3a55f20f
134,160
c
C
src/api.c
qtoggle/espqtoggle
265d5749975908403aa0f1b66148e0ee0c2bfa68
[ "Apache-2.0" ]
3
2020-05-01T20:26:22.000Z
2021-11-11T10:04:31.000Z
src/api.c
qtoggle/espqtoggle
265d5749975908403aa0f1b66148e0ee0c2bfa68
[ "Apache-2.0" ]
13
2020-04-19T22:28:31.000Z
2021-02-03T21:52:34.000Z
src/api.c
qtoggle/espqtoggle
265d5749975908403aa0f1b66148e0ee0c2bfa68
[ "Apache-2.0" ]
3
2019-07-27T15:08:09.000Z
2021-04-21T05:13:11.000Z
/* * Copyright 2019 The qToggle Team * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include <stdlib.h> #include <ctype.h> #include <mem.h> #include <user_interface.h> #include "espgoodies/battery.h" #include "espgoodies/common.h" #include "espgoodies/crypto.h" #include "espgoodies/drivers/gpio.h" #include "espgoodies/drivers/hspi.h" #include "espgoodies/flashcfg.h" #include "espgoodies/httpserver.h" #include "espgoodies/ota.h" #include "espgoodies/sleep.h" #include "espgoodies/system.h" #include "espgoodies/utils.h" #include "espgoodies/wifi.h" #include "apiutils.h" #include "client.h" #include "common.h" #include "config.h" #include "core.h" #include "device.h" #include "jsonrefs.h" #include "peripherals.h" #include "ports.h" #include "sessions.h" #include "ver.h" #include "virtual.h" #include "webhooks.h" #include "api.h" #define API_ERROR(response_json, c, error) ({ \ *code = c; \ _api_error(response_json, error, NULL, NULL); \ }) #define FORBIDDEN(response_json, level) ({ \ *code = 403; \ _forbidden_error(response_json, level); \ }) #define MISSING_FIELD(response_json, field) ({ \ *code = 400; \ _api_error(response_json, "missing-field", "field", field); \ }) #define INVALID_FIELD(response_json, field) ({ \ *code = 400; \ _api_error(response_json, "invalid-field", "field", field); \ }) #define ATTR_NOT_MODIFIABLE(response_json, attr) ({ \ *code = 400; \ _api_error(response_json, "attribute-not-modifiable", "attribute", attr); \ }) #define NO_SUCH_ATTR(response_json, attr) ({ \ *code = 400; \ _api_error(response_json, "no-such-attribute", "attribute", attr); \ }) #define SEQ_INVALID_FIELD(response_json, field) ({ \ free(port->sequence_values); \ free(port->sequence_delays); \ port->sequence_pos = -1; \ port->sequence_repeat = -1; \ INVALID_FIELD(response_json, field); \ }) #define INVALID_EXPRESSION(response_json, field, reason, token, pos) ({ \ *code = 400; \ _invalid_expression_error(response_json, field, reason, token, pos); \ }) #define INVALID_EXPRESSION_FROM_ERROR(response_json, field) ({ \ expr_parse_error_t *parse_error = expr_parse_get_error(); \ INVALID_EXPRESSION( \ response_json, \ field, \ parse_error->reason, \ parse_error->token, \ parse_error->pos \ ); \ }) #define RESPOND_NO_SUCH_FUNCTION(response_json) { \ response_json = API_ERROR(response_json, 404, "no-such-function"); \ goto response; \ } #define WIFI_RSSI_EXCELLENT -55 #define WIFI_RSSI_GOOD -65 #define WIFI_RSSI_FAIR -75 static uint8 api_access_level; static uint8 api_access_level_saved; static struct espconn *api_conn; static struct espconn *api_conn_saved; #ifdef _OTA static char *ota_states_str[] = {"idle", "checking", "downloading", "restarting"}; #endif static json_t ICACHE_FLASH_ATTR *_api_error(json_t *response_json, char *error, char *field_name, char *field_value); static json_t ICACHE_FLASH_ATTR *_forbidden_error(json_t *response_json, uint8 level); static json_t ICACHE_FLASH_ATTR *_invalid_expression_error( json_t *response_json, char *field, char *reason, char *token, int32 pos ); static json_t ICACHE_FLASH_ATTR *device_from_json( json_t *json, int *code, bool *needs_reset, bool *needs_sleep_reset, bool *config_name_changed, bool ignore_unknown ); static json_t ICACHE_FLASH_ATTR *port_attrdefs_to_json(port_t *port, json_refs_ctx_t *json_refs_ctx); static json_t ICACHE_FLASH_ATTR *device_attrdefs_to_json(void); static void ICACHE_FLASH_ATTR on_sequence_timer(void *arg); #ifdef _OTA static void ICACHE_FLASH_ATTR on_ota_latest(char *version, char *date, char *url); static void ICACHE_FLASH_ATTR on_ota_perform(int code); #endif static void ICACHE_FLASH_ATTR on_wifi_scan(wifi_scan_result_t *results, int len); json_t *api_call_handle(int method, char* path, json_t *query_json, json_t *request_json, int *code) { char *part1 = NULL, *part2 = NULL, *part3 = NULL; char *token; *code = 200; json_t *response_json = NULL; port_t *port; if (method == HTTP_METHOD_OTHER) { RESPOND_NO_SUCH_FUNCTION(response_json); } /* Remove the leading & trailing slashes */ while (path[0] == '/') { path++; } int path_len = strlen(path); while (path[path_len - 1] == '/') { path[path_len - 1] = 0; path_len--; } /* Split path */ token = strtok(path, "/"); if (!token) { RESPOND_NO_SUCH_FUNCTION(response_json); } part1 = strdup(token); token = strtok(NULL, "/"); if (token) { part2 = strdup(token); } token = strtok(NULL, "/"); if (token) { part3 = strdup(token); } token = strtok(NULL, "/"); if (token) { RESPOND_NO_SUCH_FUNCTION(response_json); } /* Determine the API endpoint and method */ if (!strcmp(part1, "device")) { if (part2) { RESPOND_NO_SUCH_FUNCTION(response_json); } else { if (method == HTTP_METHOD_GET) { response_json = api_get_device(query_json, code); } else if (method == HTTP_METHOD_PATCH) { response_json = api_patch_device(query_json, request_json, code); } else if (method == HTTP_METHOD_PUT) { response_json = api_put_device(query_json, request_json, code); } else { RESPOND_NO_SUCH_FUNCTION(response_json); } } } else if (!strcmp(part1, "reset") && method == HTTP_METHOD_POST && !part2) { response_json = api_post_reset(query_json, request_json, code); } #ifdef _OTA else if (!strcmp(part1, "firmware") && !part2) { if (method == HTTP_METHOD_GET) { response_json = api_get_firmware(query_json, code); } else if (method == HTTP_METHOD_PATCH) { response_json = api_patch_firmware(query_json, request_json, code); } else { RESPOND_NO_SUCH_FUNCTION(response_json); } } #endif else if (!strcmp(part1, "access")) { if (!part2) { response_json = api_get_access(query_json, code); } else { RESPOND_NO_SUCH_FUNCTION(response_json); } } else if (!strcmp(part1, "backup")) { if (part2) { if (!strcmp(part2, "endpoints")) { response_json = api_get_backup_endpoints(query_json, code); } else { RESPOND_NO_SUCH_FUNCTION(response_json); } } else { RESPOND_NO_SUCH_FUNCTION(response_json); } } else if (!strcmp(part1, "ports")) { if (part2) { port = port_find_by_id(part2); if (!port) { response_json = API_ERROR(response_json, 404, "no-such-port"); goto response; } if (part3) { if (!strcmp(part3, "value")) { /* /ports/{id}/value */ if (method == HTTP_METHOD_GET) { response_json = api_get_port_value(port, query_json, code); } else if (method == HTTP_METHOD_PATCH) { response_json = api_patch_port_value(port, query_json, request_json, code); } else { RESPOND_NO_SUCH_FUNCTION(response_json); } } else if (!strcmp(part3, "sequence")) { /* /ports/{id}/sequence */ if (method == HTTP_METHOD_PATCH) { response_json = api_patch_port_sequence(port, query_json, request_json, code); } else { RESPOND_NO_SUCH_FUNCTION(response_json); } } else { RESPOND_NO_SUCH_FUNCTION(response_json); } } else { /* /ports/{id} */ if (method == HTTP_METHOD_PATCH) { response_json = api_patch_port(port, query_json, request_json, code, /* provisioning = */ FALSE); } else if (method == HTTP_METHOD_DELETE) { response_json = api_delete_port(port, query_json, code); } else { RESPOND_NO_SUCH_FUNCTION(response_json); } } } else { /* /ports */ if (method == HTTP_METHOD_GET) { response_json = api_get_ports(query_json, code); } else if (method == HTTP_METHOD_POST) { response_json = api_post_ports(query_json, request_json, code); } else if (method == HTTP_METHOD_PUT) { response_json = api_put_ports(query_json, request_json, code); } else { RESPOND_NO_SUCH_FUNCTION(response_json); } } } else if (!strcmp(part1, "webhooks")) { if (part2) { RESPOND_NO_SUCH_FUNCTION(response_json); } if (method == HTTP_METHOD_GET) { response_json = api_get_webhooks(query_json, code); } else if (method == HTTP_METHOD_PUT) { response_json = api_put_webhooks(query_json, request_json, code); } else { RESPOND_NO_SUCH_FUNCTION(response_json); } } else if (!strcmp(part1, "wifi")) { if (part2) { RESPOND_NO_SUCH_FUNCTION(response_json); } if (method == HTTP_METHOD_GET) { response_json = api_get_wifi(query_json, code); } else { RESPOND_NO_SUCH_FUNCTION(response_json); } } else if (!strcmp(part1, "rawio")) { if (part2) { if (part3) { RESPOND_NO_SUCH_FUNCTION(response_json); } if (method == HTTP_METHOD_GET) { response_json = api_get_raw_io(part2, query_json, code); } else if (method == HTTP_METHOD_PATCH) { response_json = api_patch_raw_io(part2, query_json, request_json, code); } else { RESPOND_NO_SUCH_FUNCTION(response_json); } } else { RESPOND_NO_SUCH_FUNCTION(response_json); } } else if (!strcmp(part1, "peripherals")) { if (part2) { RESPOND_NO_SUCH_FUNCTION(response_json); } if (method == HTTP_METHOD_GET) { response_json = api_get_peripherals(query_json, code); } else if (method == HTTP_METHOD_PUT) { response_json = api_put_peripherals(query_json, request_json, code); } else { RESPOND_NO_SUCH_FUNCTION(response_json); } } else if (!strcmp(part1, "system")) { if (part2) { RESPOND_NO_SUCH_FUNCTION(response_json); } if (method == HTTP_METHOD_GET) { response_json = api_get_system(query_json, code); } else if (method == HTTP_METHOD_PATCH) { response_json = api_patch_system(query_json, request_json, code); } else { RESPOND_NO_SUCH_FUNCTION(response_json); } } else if (!strcmp(part1, "provisioning")) { if (part2) { RESPOND_NO_SUCH_FUNCTION(response_json); } if (method == HTTP_METHOD_GET) { response_json = api_get_provisioning(query_json, code); } else if (method == HTTP_METHOD_PUT) { response_json = api_put_provisioning(query_json, request_json, code); } else { RESPOND_NO_SUCH_FUNCTION(response_json); } } else { RESPOND_NO_SUCH_FUNCTION(response_json); } response: free(part1); free(part2); free(part3); return response_json; } void api_conn_set(struct espconn *conn, int access_level) { if (api_conn) { DEBUG_API("overwriting existing API connection"); } api_conn = conn; api_access_level = access_level; } bool api_conn_busy(void) { return !!api_conn; } bool api_conn_equal(struct espconn *conn) { if (!api_conn) { return FALSE; } return CONN_EQUAL(conn, api_conn); } uint8 api_conn_access_level_get(void) { return api_access_level; } void api_conn_reset(void) { api_conn = NULL; api_access_level = API_ACCESS_LEVEL_NONE; } void api_conn_save(void) { DEBUG_API("saving connection state"); api_conn_saved = api_conn; api_access_level_saved = api_access_level; api_conn = NULL; api_access_level = API_ACCESS_LEVEL_NONE; } void api_conn_restore(void) { DEBUG_API("restoring connection state"); api_conn = api_conn_saved; api_access_level = api_access_level_saved; api_conn_saved = NULL; api_access_level_saved = API_ACCESS_LEVEL_NONE; } json_t *port_to_json(port_t *port, json_refs_ctx_t *json_refs_ctx) { json_t *json = json_obj_new(); /* Common to all ports */ json_obj_append(json, "id", json_str_new(port->id)); json_obj_append(json, "display_name", json_str_new(port->display_name ? port->display_name : "")); json_obj_append(json, "enabled", json_bool_new(IS_PORT_ENABLED(port))); json_obj_append(json, "writable", json_bool_new(IS_PORT_WRITABLE(port))); json_obj_append(json, "persisted", json_bool_new(IS_PORT_PERSISTED(port))); json_obj_append(json, "internal", json_bool_new(IS_PORT_INTERNAL(port))); if (IS_PORT_VIRTUAL(port)) { json_obj_append(json, "virtual", json_bool_new(TRUE)); } if (!IS_PORT_VIRTUAL(port) && port->min_sampling_interval < port->max_sampling_interval) { json_obj_append(json, "sampling_interval", json_int_new(port->sampling_interval)); } if (port->stransform_read) { json_obj_append(json, "transform_read", json_str_new(port->stransform_read)); } else { json_obj_append(json, "transform_read", json_str_new("")); } /* Specific to numeric ports */ if (port->type == PORT_TYPE_NUMBER) { json_obj_append(json, "type", json_str_new(API_PORT_TYPE_NUMBER)); json_obj_append(json, "unit", json_str_new(port->unit ? port->unit : "")); if (!IS_UNDEFINED(port->min)) { json_obj_append(json, "min", json_double_new(port->min)); } if (!IS_UNDEFINED(port->max)) { json_obj_append(json, "max", json_double_new(port->max)); } if (!IS_UNDEFINED(port->step)) { json_obj_append(json, "step", json_double_new(port->step)); } if (port->integer) { json_obj_append(json, "integer", json_bool_new(TRUE)); } if (port->choices) { int8 found_ref_index = -1; if (json_refs_ctx->type == JSON_REFS_TYPE_PORTS_LIST) { /* Look through previous ports for same choices */ port_t *p = NULL; uint8 i; for (i = 0; i < all_ports_count && p != port; i++) { p = all_ports[i]; if (choices_equal(port->choices, p->choices)) { found_ref_index = i; break; } } } if (found_ref_index >= 0) { /* Found equal choices at found_ref_index */ json_t *ref = make_json_ref("#/%d/choices", found_ref_index); #if defined(_DEBUG) && defined(_DEBUG_API) char *ref_str = json_str_get(json_obj_value_at(ref, 0)); DEBUG_API("replacing \"%s.choices\" with $ref \"%s\"", port->id, ref_str); #endif json_obj_append(json, "choices", ref); } else { json_t *list = json_list_new(); char *c, **choices = port->choices; while ((c = *choices++)) { json_list_append(list, choice_to_json(c, PORT_TYPE_NUMBER)); } json_obj_append(json, "choices", list); } } } /* Specific to boolean ports */ else { /* Assuming PORT_TYPE_BOOLEAN */ json_obj_append(json, "type", json_str_new(API_PORT_TYPE_BOOLEAN)); } /* Specific to writable ports */ if (IS_PORT_WRITABLE(port)) { if (port->sexpr) { json_obj_append(json, "expression", json_str_new(port->sexpr)); } else { json_obj_append(json, "expression", json_str_new("")); } if (port->stransform_write) { json_obj_append(json, "transform_write", json_str_new(port->stransform_write)); } else { json_obj_append(json, "transform_write", json_str_new("")); } } /* Extra attributes */ if (port->attrdefs) { attrdef_t *a, **attrdefs = port->attrdefs; int index; while ((a = *attrdefs++)) { switch (a->type) { case ATTR_TYPE_BOOLEAN: json_obj_append(json, a->name, json_bool_new(((int_getter_t) a->get)(port, a))); break; case ATTR_TYPE_NUMBER: if (a->choices) { /* When dealing with choices, the getter returns the index inside the choices array */ index = ((int_getter_t) a->get)(port, a); json_obj_append(json, a->name, json_double_new(get_choice_value_num(a->choices[index]))); } else { if (IS_ATTRDEF_INTEGER(a)) { json_obj_append(json, a->name, json_int_new(((int_getter_t) a->get)(port, a))); } else { /* float */ json_obj_append(json, a->name, json_int_new(((float_getter_t) a->get)(port, a))); } } break; case ATTR_TYPE_STRING: if (a->choices) { /* When dealing with choices, the getter returns the index inside the choices array */ index = ((int_getter_t) a->get)(port, a); json_obj_append(json, a->name, json_str_new(get_choice_value_str(a->choices[index]))); } else { json_obj_append(json, a->name, json_str_new(((str_getter_t) a->get)(port, a))); } break; } } } /* Port value */ json_obj_append(json, "value", port_make_json_value(port)); /* Attribute definitions */ json_obj_append(json, "definitions", port_attrdefs_to_json(port, json_refs_ctx)); json_stringify(json); return json; } json_t *device_to_json(void) { char value[256]; json_t *json = json_obj_new(); /* Common attributes */ json_obj_append(json, "name", json_str_new(device_name)); json_obj_append(json, "display_name", json_str_new(device_display_name)); json_obj_append(json, "version", json_str_new(FW_VERSION)); json_obj_append(json, "api_version", json_str_new(API_VERSION)); json_obj_append(json, "vendor", json_str_new(VENDOR)); /* Passwords - never reveal them */ if (!strncmp(device_admin_password_hash, EMPTY_SHA256_HEX, SHA256_HEX_LEN)) { json_obj_append(json, "admin_password", json_str_new("")); } else { json_obj_append(json, "admin_password", json_str_new("set")); } if (!strncmp(device_normal_password_hash, EMPTY_SHA256_HEX, SHA256_HEX_LEN)) { json_obj_append(json, "normal_password", json_str_new("")); } else { json_obj_append(json, "normal_password", json_str_new("set")); } if (!strncmp(device_viewonly_password_hash, EMPTY_SHA256_HEX, SHA256_HEX_LEN)) { json_obj_append(json, "viewonly_password", json_str_new("")); } else { json_obj_append(json, "viewonly_password", json_str_new("set")); } /* Flags */ json_t *flags_json = json_list_new(); json_list_append(flags_json, json_str_new("expressions")); #ifdef _OTA json_list_append(flags_json, json_str_new("firmware")); #endif json_list_append(flags_json, json_str_new("backup")); json_list_append(flags_json, json_str_new("listen")); json_list_append(flags_json, json_str_new("sequences")); #ifdef _SSL json_list_append(flags_json, json_str_new("ssl")); #endif json_list_append(flags_json, json_str_new("webhooks")); json_obj_append(json, "flags", flags_json); /* Various optional attributes */ json_obj_append(json, "uptime", json_int_new(system_uptime())); json_obj_append(json, "virtual_ports", json_int_new(VIRTUAL_MAX_PORTS)); /* IP configuration */ ip_addr_t ip = wifi_get_ip_address(); if (ip.addr) { snprintf(value, 256, WIFI_IP_FMT, IP2STR(&ip)); json_obj_append(json, "ip_address", json_str_new(value)); } else { json_obj_append(json, "ip_address", json_str_new("")); } json_obj_append(json, "ip_netmask", json_int_new(wifi_get_netmask())); ip = wifi_get_gateway(); if (ip.addr) { snprintf(value, 256, WIFI_IP_FMT, IP2STR(&ip)); json_obj_append(json, "ip_gateway", json_str_new(value)); } else { json_obj_append(json, "ip_gateway", json_str_new("")); } ip = wifi_get_dns(); if (ip.addr) { snprintf(value, 256, WIFI_IP_FMT, IP2STR(&ip)); json_obj_append(json, "ip_dns", json_str_new(value)); } else { json_obj_append(json, "ip_dns", json_str_new("")); } /* Current IP info */ ip = wifi_get_ip_address_current(); if (ip.addr) { snprintf(value, 256, WIFI_IP_FMT, IP2STR(&ip)); json_obj_append(json, "ip_address_current", json_str_new(value)); } else { json_obj_append(json, "ip_address_current", json_str_new("")); } json_obj_append(json, "ip_netmask_current", json_int_new(wifi_get_netmask_current())); ip = wifi_get_gateway_current(); if (ip.addr) { snprintf(value, 256, WIFI_IP_FMT, IP2STR(&ip)); json_obj_append(json, "ip_gateway_current", json_str_new(value)); } else { json_obj_append(json, "ip_gateway_current", json_str_new("")); } ip = wifi_get_dns_current(); if (ip.addr) { snprintf(value, 256, WIFI_IP_FMT, IP2STR(&ip)); json_obj_append(json, "ip_dns_current", json_str_new(value)); } else { json_obj_append(json, "ip_dns_current", json_str_new("")); } /* Wi-Fi configuration */ char *ssid = wifi_get_ssid(); char *psk = wifi_get_psk(); uint8 *bssid = wifi_get_bssid(); if (ssid) { json_obj_append(json, "wifi_ssid", json_str_new(ssid)); } else { json_obj_append(json, "wifi_ssid", json_str_new("")); } if (psk) { json_obj_append(json, "wifi_key", json_str_new(psk)); } else { json_obj_append(json, "wifi_key", json_str_new("")); } if (bssid) { snprintf(value, 256, "%02X:%02X:%02X:%02X:%02X:%02X", WIFI_BSSID2STR(bssid)); json_obj_append(json, "wifi_bssid", json_str_new(value)); } else { json_obj_append(json, "wifi_bssid", json_str_new("")); } /* Current Wi-Fi info */ int rssi = wifi_station_get_rssi(); if (rssi < -100) { rssi = -100; } if (rssi > -30) { rssi = -30; } char current_bssid_str[18] = {0}; if (wifi_station_is_connected()) { snprintf( current_bssid_str, sizeof(current_bssid_str), "%02X:%02X:%02X:%02X:%02X:%02X", WIFI_BSSID2STR(wifi_get_bssid_current()) ); } json_obj_append(json, "wifi_bssid_current", json_str_new(current_bssid_str)); int8 wifi_signal_strength = -1; if (wifi_station_is_connected()) { if (rssi >= WIFI_RSSI_EXCELLENT) { wifi_signal_strength = 3; } else if (rssi >= WIFI_RSSI_GOOD) { wifi_signal_strength = 2; } else if (rssi >= WIFI_RSSI_FAIR) { wifi_signal_strength = 1; } else { wifi_signal_strength = 0; } } json_obj_append(json, "wifi_signal_strength", json_int_new(wifi_signal_strength)); json_obj_append(json, "mem_usage", json_int_new(100 - 100 * system_get_free_heap_size() / MAX_AVAILABLE_RAM)); json_obj_append(json, "flash_size", json_int_new(system_get_flash_size() / 1024)); #ifdef _OTA json_obj_append(json, "firmware_auto_update", json_bool_new(device_flags & DEVICE_FLAG_OTA_AUTO_UPDATE)); json_obj_append(json, "firmware_beta_enabled", json_bool_new(device_flags & DEVICE_FLAG_OTA_BETA_ENABLED)); #endif /* Flash id */ char id[10]; snprintf(id, 10, "%08x", spi_flash_get_id()); json_obj_append(json, "flash_id", json_str_new(id)); /* Chip id */ snprintf(id, 10, "%08x", system_get_chip_id()); json_obj_append(json, "chip_id", json_str_new(id)); /* Configuration name */ json_obj_append(json, "config_name", json_str_new(device_config_name)); #ifdef _DEBUG json_obj_append(json, "debug", json_bool_new(TRUE)); #endif /* Sleep mode */ #ifdef _SLEEP json_obj_append(json, "sleep_wake_interval", json_int_new(sleep_get_wake_interval())); json_obj_append(json, "sleep_wake_duration", json_int_new(sleep_get_wake_duration())); #endif /* Battery */ #ifdef _BATTERY if (battery_enabled()) { json_obj_append(json, "battery_level", json_int_new(battery_get_level())); json_obj_append(json, "battery_voltage", json_int_new(battery_get_voltage())); } #endif /* Attribute definitions */ json_obj_append(json, "definitions", device_attrdefs_to_json()); json_stringify(json); return json; } json_t *peripheral_to_json(peripheral_t *peripheral) { json_t *peripheral_json = json_obj_new(); json_t *json; char flags_str[17]; char hex[3]; int i; /* Type */ json_obj_append(peripheral_json, "type", json_int_new(peripheral->type_id)); /* Flags */ for (i = 0; i < 16; i++) { flags_str[i] = '0' + !!(peripheral->flags & BIT(15 - i)); } flags_str[16] = '\0'; json_obj_append(peripheral_json, "flags", json_str_new(flags_str)); /* int8 params */ json = json_list_new(); json_obj_append(peripheral_json, "int8_params", json); for (i = 0; i < PERIPHERAL_MAX_INT8_PARAMS; i++) { snprintf(hex, sizeof(hex), "%02X", PERIPHERAL_PARAM_UINT8(peripheral, i)); json_list_append(json, json_str_new(hex)); } /* Port IDs */ json = json_list_new(); json_obj_append(peripheral_json, "port_ids", json); for (i = 0; i < all_ports_count; i++) { port_t *port = all_ports[i]; if (port->peripheral != peripheral) { continue; /* Not our port */ } json_list_append(json, json_str_new(port->id)); } return peripheral_json; } json_t *api_get_device(json_t *query_json, int *code) { json_t *response_json = NULL; if (api_access_level < API_ACCESS_LEVEL_ADMIN) { return FORBIDDEN(response_json, API_ACCESS_LEVEL_ADMIN); } DEBUG_API("returning device attributes"); *code = 200; return device_to_json(); } json_t *api_put_device(json_t *query_json, json_t *request_json, int *code) { DEBUG_API("restoring device"); json_t *response_json = NULL; if (api_access_level < API_ACCESS_LEVEL_ADMIN) { return FORBIDDEN(response_json, API_ACCESS_LEVEL_ADMIN); } if (json_get_type(request_json) != JSON_TYPE_OBJ) { return API_ERROR(response_json, 400, "invalid-request"); } /* Reset attributes to default values; network-related attributes will be left untouched, though */ free(device_name); char default_device_name[API_MAX_DEVICE_NAME_LEN]; snprintf(default_device_name, sizeof(default_device_name), DEFAULT_HOSTNAME, system_get_chip_id()); device_name = strdup(default_device_name); free(device_display_name); device_display_name = strdup(""); #ifdef _SLEEP sleep_set_wake_interval(SLEEP_WAKE_INTERVAL_MIN); sleep_set_wake_duration(SLEEP_WAKE_DURATION_MIN); #endif #ifdef _OTA device_flags &= ~DEVICE_FLAG_OTA_AUTO_UPDATE; device_flags &= ~DEVICE_FLAG_OTA_BETA_ENABLED; #endif device_config_name[0] = 0; /* Ignore any supplied clear-text password */ json_free(json_obj_pop_key(request_json, "admin_password")); json_free(json_obj_pop_key(request_json, "normal_password")); json_free(json_obj_pop_key(request_json, "viewonly_password")); bool needs_reset, needs_sleep_reset, config_name_changed; response_json = device_from_json( request_json, code, &needs_reset, &needs_sleep_reset, &config_name_changed, /* ignore_unknown = */ TRUE ); config_mark_for_saving(); /* Inform consumers of the changes */ event_push_device_update(); return response_json; } json_t *api_patch_device(json_t *query_json, json_t *request_json, int *code) { DEBUG_API("updating device attributes"); json_t *response_json = NULL; if (api_access_level < API_ACCESS_LEVEL_ADMIN) { return FORBIDDEN(response_json, API_ACCESS_LEVEL_ADMIN); } if (json_get_type(request_json) != JSON_TYPE_OBJ) { return API_ERROR(response_json, 400, "invalid-request"); } bool needs_reset, needs_sleep_reset, config_name_changed; response_json = device_from_json( request_json, code, &needs_reset, &needs_sleep_reset, &config_name_changed, /* ignore_unknown = */ FALSE ); if (config_name_changed) { /* If a new configuration name as been set, start the provisioning process */ config_start_auto_provisioning(); } config_mark_for_saving(); if (needs_reset) { DEBUG_API("reset needed"); system_reset(/* delayed = */ TRUE); } #ifdef _SLEEP else if (needs_sleep_reset) { sleep_reset(); /* Save configuration right away to prevent any losses due to sleep */ config_ensure_saved(); } #endif /* Inform consumers of the changes */ event_push_device_update(); return response_json; } json_t *api_post_reset(json_t *query_json, json_t *request_json, int *code) { json_t *response_json = json_obj_new(); if (api_access_level < API_ACCESS_LEVEL_ADMIN) { return FORBIDDEN(response_json, API_ACCESS_LEVEL_ADMIN); } if (json_get_type(request_json) != JSON_TYPE_OBJ) { return API_ERROR(response_json, 400, "invalid-request"); } json_t *factory_json = json_obj_lookup_key(request_json, "factory"); bool factory = FALSE; if (factory_json) { if (json_get_type(factory_json) != JSON_TYPE_BOOL) { return INVALID_FIELD(response_json, "factory"); } factory = json_bool_get(factory_json); } if (factory) { config_factory_reset(); wifi_reset(); } *code = 204; system_reset(/* delayed = */ TRUE); return response_json; } #ifdef _OTA json_t *api_get_firmware(json_t *query_json, int *code) { json_t *response_json = NULL; if (api_access_level < API_ACCESS_LEVEL_ADMIN) { return FORBIDDEN(response_json, API_ACCESS_LEVEL_ADMIN); } int ota_state = ota_current_state(); if (ota_state == OTA_STATE_IDLE) { bool beta = device_flags & DEVICE_FLAG_OTA_BETA_ENABLED; json_t *beta_json = json_obj_lookup_key(query_json, "beta"); if (beta_json) { beta = !strcmp(json_str_get(beta_json), "true"); } if (!ota_get_latest(beta, on_ota_latest)) { response_json = json_obj_new(); json_obj_append(response_json, "error", json_str_new("busy")); *code = 503; } } else { /* OTA busy */ char *ota_state_str = ota_states_str[ota_state]; response_json = json_obj_new(); json_obj_append(response_json, "version", json_str_new(FW_VERSION)); json_obj_append(response_json, "status", json_str_new(ota_state_str)); } return response_json; } json_t *api_patch_firmware(json_t *query_json, json_t *request_json, int *code) { json_t *response_json = NULL; if (api_access_level < API_ACCESS_LEVEL_ADMIN) { return FORBIDDEN(response_json, API_ACCESS_LEVEL_ADMIN); } if (json_get_type(request_json) != JSON_TYPE_OBJ) { return API_ERROR(response_json, 400, "invalid-request"); } json_t *version_json = json_obj_lookup_key(request_json, "version"); json_t *url_json = json_obj_lookup_key(request_json, "url"); if (!version_json && !url_json) { return MISSING_FIELD(response_json, "version"); } if (url_json) { /* URL given */ if (json_get_type(url_json) != JSON_TYPE_STR) { return INVALID_FIELD(response_json, "url"); } ota_perform_url(json_str_get(url_json), on_ota_perform); } else { /* Assuming version_json */ if (json_get_type(version_json) != JSON_TYPE_STR) { return INVALID_FIELD(response_json, "version"); } ota_perform_version(json_str_get(version_json), on_ota_perform); } return NULL; } #endif /* _OTA */ json_t *api_get_access(json_t *query_json, int *code) { json_t *response_json = json_obj_new(); switch (api_access_level) { case API_ACCESS_LEVEL_ADMIN: json_obj_append(response_json, "level", json_str_new("admin")); break; case API_ACCESS_LEVEL_NORMAL: json_obj_append(response_json, "level", json_str_new("normal")); break; case API_ACCESS_LEVEL_VIEWONLY: json_obj_append(response_json, "level", json_str_new("viewonly")); break; default: json_obj_append(response_json, "level", json_str_new("none")); break; } *code = 200; return response_json; } json_t *api_get_backup_endpoints(json_t *query_json, int *code) { json_t *response_json = json_list_new(); if (api_access_level < API_ACCESS_LEVEL_ADMIN) { return FORBIDDEN(response_json, API_ACCESS_LEVEL_ADMIN); } json_t *peripherals_json = json_obj_new(); json_obj_append(peripherals_json, "path", json_str_new("/peripherals")); json_obj_append(peripherals_json, "display_name", json_str_new("Peripherals")); json_obj_append(peripherals_json, "restore_method", json_str_new("PUT")); json_obj_append(peripherals_json, "order", json_int_new(5)); json_t *system_json = json_obj_new(); json_obj_append(system_json, "path", json_str_new("/system")); json_obj_append(system_json, "display_name", json_str_new("System Configuration")); json_obj_append(system_json, "restore_method", json_str_new("PATCH")); json_obj_append(system_json, "order", json_int_new(6)); json_list_append(response_json, peripherals_json); json_list_append(response_json, system_json); return response_json; } json_t *api_get_ports(json_t *query_json, int *code) { json_t *response_json = json_list_new(); if (api_access_level < API_ACCESS_LEVEL_VIEWONLY) { return FORBIDDEN(response_json, API_ACCESS_LEVEL_VIEWONLY); } port_t *p; int i; json_refs_ctx_t json_refs_ctx; json_refs_ctx_init(&json_refs_ctx, JSON_REFS_TYPE_PORTS_LIST); for (i = 0; i < all_ports_count; i++) { p = all_ports[i]; DEBUG_API("returning attributes of port %s", p->id); json_list_append(response_json, port_to_json(p, &json_refs_ctx)); json_refs_ctx.index++; } *code = 200; return response_json; } json_t *api_post_ports(json_t *query_json, json_t *request_json, int *code) { json_t *response_json = json_obj_new(); if (api_access_level < API_ACCESS_LEVEL_ADMIN) { return FORBIDDEN(response_json, API_ACCESS_LEVEL_ADMIN); } if (json_get_type(request_json) != JSON_TYPE_OBJ) { return API_ERROR(response_json, 400, "invalid-request"); } if (virtual_find_unused_slot() < 0) { DEBUG_API("adding virtual port: no more free slots"); return API_ERROR(response_json, 400, "too-many-ports"); } int i; json_t *child, *c, *c2; port_t *new_port = port_new(); char *choice; /* Will automatically allocate slot */ new_port->slot = -1; /* id */ child = json_obj_lookup_key(request_json, "id"); if (!child) { free(new_port); return MISSING_FIELD(response_json, "id"); } if (json_get_type(child) != JSON_TYPE_STR) { free(new_port); return INVALID_FIELD(response_json, "id"); } if (!validate_id(json_str_get(child)) || strlen(json_str_get(child)) > PORT_MAX_ID_LEN) { free(new_port); return INVALID_FIELD(response_json, "id"); } if (port_find_by_id(json_str_get(child))) { free(new_port); return API_ERROR(response_json, 400, "duplicate-port"); } new_port->id = strdup(json_str_get(child)); DEBUG_API("adding virtual port: id = \"%s\"", new_port->id); /* type */ child = json_obj_lookup_key(request_json, "type"); if (!child) { port_cleanup(new_port, /* free_id = */ TRUE); free(new_port); return MISSING_FIELD(response_json, "type"); } if (json_get_type(child) != JSON_TYPE_STR) { port_cleanup(new_port, /* free_id = */ TRUE); free(new_port); return INVALID_FIELD(response_json, "type"); } char *type = json_str_get(child); if (!strcmp(type, "number")) { new_port->type = PORT_TYPE_NUMBER; } else if (!strcmp(type, "boolean")) { new_port->type = PORT_TYPE_BOOLEAN; } else { port_cleanup(new_port, /* free_id = */ TRUE); free(new_port); return INVALID_FIELD(response_json, "type"); } DEBUG_API("adding virtual port: type = \"%s\"", type); /* min */ child = json_obj_lookup_key(request_json, "min"); if (child) { if (json_get_type(child) == JSON_TYPE_INT) { new_port->min = json_int_get(child); } else if (json_get_type(child) == JSON_TYPE_DOUBLE) { new_port->min = json_double_get(child); } else { port_cleanup(new_port, /* free_id = */ TRUE); free(new_port); return INVALID_FIELD(response_json, "min"); } DEBUG_API("adding virtual port: min = %s", dtostr(new_port->min, -1)); } else { new_port->min = UNDEFINED; } /* max */ child = json_obj_lookup_key(request_json, "max"); if (child) { if (json_get_type(child) == JSON_TYPE_INT) { new_port->max = json_int_get(child); } else if (json_get_type(child) == JSON_TYPE_DOUBLE) { new_port->max = json_double_get(child); } else { port_cleanup(new_port, /* free_id = */ TRUE); free(new_port); return INVALID_FIELD(response_json, "max"); } /* min must be <= max */ if (!IS_UNDEFINED(new_port->min) && new_port->min > new_port->max) { port_cleanup(new_port, /* free_id = */ TRUE); free(new_port); return INVALID_FIELD(response_json, "max"); } DEBUG_API("adding virtual port: max = %s", dtostr(new_port->max, -1)); } else { new_port->max = UNDEFINED; } /* integer */ child = json_obj_lookup_key(request_json, "integer"); if (child) { if (json_get_type(child) != JSON_TYPE_BOOL) { port_cleanup(new_port, /* free_id = */ TRUE); free(new_port); return INVALID_FIELD(response_json, "integer"); } new_port->integer = json_bool_get(child); DEBUG_API("adding virtual port: integer = %d", new_port->integer); } /* step */ child = json_obj_lookup_key(request_json, "step"); if (child) { if (json_get_type(child) == JSON_TYPE_INT) { new_port->step = json_int_get(child); } else if (json_get_type(child) == JSON_TYPE_DOUBLE) { new_port->step = json_double_get(child); } else { port_cleanup(new_port, /* free_id = */ TRUE); free(new_port); return INVALID_FIELD(response_json, "step"); } DEBUG_API("adding virtual port: step = %s", dtostr(new_port->step, -1)); } else { new_port->step = UNDEFINED; } /* choices */ child = json_obj_lookup_key(request_json, "choices"); if (child && new_port->type == PORT_TYPE_NUMBER) { if (json_get_type(child) != JSON_TYPE_LIST) { port_cleanup(new_port, /* free_id = */ TRUE); free(new_port); return INVALID_FIELD(response_json, "choices"); } int len = json_list_get_len(child); if (len < 1 || len > 256) { port_cleanup(new_port, /* free_id = */ TRUE); free(new_port); return INVALID_FIELD(response_json, "choices"); } new_port->choices = zalloc((json_list_get_len(child) + 1) * sizeof(char *)); for (i = 0; i < len; i++) { c = json_list_value_at(child, i); if (json_get_type(c) != JSON_TYPE_OBJ) { port_cleanup(new_port, /* free_id = */ TRUE); free(new_port); return INVALID_FIELD(response_json, "choices"); } /* value */ c2 = json_obj_lookup_key(c, "value"); if (!c2) { port_cleanup(new_port, /* free_id = */ TRUE); free(new_port); return INVALID_FIELD(response_json, "choices"); } if (json_get_type(c2) == JSON_TYPE_INT) { new_port->choices[i] = strdup(dtostr(json_int_get(c2), /* decimals = */ 0)); } else if (json_get_type(c2) == JSON_TYPE_DOUBLE) { new_port->choices[i] = strdup(dtostr(json_double_get(c2), /* decimals = */ -1)); } else { port_cleanup(new_port, /* free_id = */ TRUE); free(new_port); return INVALID_FIELD(response_json, "choices"); } /* display_name */ c2 = json_obj_lookup_key(c, "display_name"); if (c2) { if (json_get_type(c2) != JSON_TYPE_STR) { port_cleanup(new_port, /* free_id = */ TRUE); free(new_port); return INVALID_FIELD(response_json, "choices"); } choice = new_port->choices[i]; choice = realloc(choice, strlen(choice) + 2 + strlen(json_str_get(c2))); strcat(choice, ":"); strcat(choice, json_str_get(c2)); new_port->choices[i] = choice; } } new_port->choices[json_list_get_len(child)] = NULL; DEBUG_API("adding virtual port: %d choices", len); } /* Sequence */ new_port->sequence_pos = -1; if (!virtual_port_register(new_port)) { port_cleanup(new_port, /* free_id = */ TRUE); free(new_port); return API_ERROR(response_json, 500, "port-register-error"); } port_register(new_port); /* Newly added ports must be automatically enabled */ new_port->flags |= PORT_FLAG_ENABLED; /* Rebuild deps mask for all ports, as the new port might be among their deps */ ports_rebuild_change_dep_mask(); config_mark_for_saving(); event_push_port_add(new_port); *code = 201; json_refs_ctx_t json_refs_ctx; json_refs_ctx_init(&json_refs_ctx, JSON_REFS_TYPE_PORT); json_free(response_json); return port_to_json(new_port, &json_refs_ctx); } json_t *api_put_ports(json_t *query_json, json_t *request_json, int *code) { json_t *response_json = json_obj_new(); if (api_access_level < API_ACCESS_LEVEL_ADMIN) { return FORBIDDEN(response_json, API_ACCESS_LEVEL_ADMIN); } DEBUG_API("restoring ports"); /* Remember port IDs associated to each peripheral; we need them later for recreation */ uint8 i, j; char **port_ids_by_peripheral_index[PERIPHERAL_MAX_NUM]; uint8 port_ids_len_by_peripheral_index[PERIPHERAL_MAX_NUM]; for (i = 0; i < PERIPHERAL_MAX_NUM; i++) { port_ids_by_peripheral_index[i] = NULL; port_ids_len_by_peripheral_index[i] = 0; } /* Remove all ports */ port_t *port; while (all_ports_count > 0) { port = all_ports[0]; DEBUG_API("removing port %s", port->id); if (port->peripheral) { /* Virtual ports don't have a peripheral */ uint8 peripheral_index = port->peripheral->index; uint8 port_ids_len = ++(port_ids_len_by_peripheral_index[peripheral_index]); char **port_ids = port_ids_by_peripheral_index[peripheral_index] = realloc( port_ids_by_peripheral_index[peripheral_index], sizeof(char *) * port_ids_len ); port_ids[port_ids_len - 1] = strdup(port->id); } port_cleanup(port, /* free_id = */ FALSE); if (IS_PORT_VIRTUAL(port)) { virtual_port_unregister(port); } port_unregister(port); free(port); } /* Recreate peripheral ports */ peripheral_t *peripheral; for (i = 0; i < all_peripherals_count; i++) { peripheral = all_peripherals[i]; peripheral_cleanup(peripheral); peripheral_init(peripheral); peripheral_make_ports(peripheral, port_ids_by_peripheral_index[i], port_ids_len_by_peripheral_index[i]); } /* Free remembered port IDs */ for (i = 0; i < PERIPHERAL_MAX_NUM; i++) { uint8 port_ids_len = port_ids_len_by_peripheral_index[i]; for (j = 0; j < port_ids_len; j++) { free(port_ids_by_peripheral_index[i][j]); } free(port_ids_by_peripheral_index[i]); } /* Actually apply supplied ports configuration */ json_t *error_response_json = NULL; char *error_port_id; if (config_apply_ports_provisioning(request_json, &error_response_json, &error_port_id)) { *code = 204; } else { DEBUG_API("provisioning ports failed"); json_free(response_json); response_json = error_response_json; if (error_port_id) { json_obj_append(response_json, "id", json_str_new(error_port_id)); free(error_port_id); } *code = 400; } /* Save, but only if everything went well */ if (*code == 204) { config_mark_for_saving(); } event_push_full_update(); return response_json; } json_t *api_patch_port(port_t *port, json_t *query_json, json_t *request_json, int *code, bool provisioning) { json_t *response_json = json_obj_new(); if (api_access_level < API_ACCESS_LEVEL_ADMIN) { return FORBIDDEN(response_json, API_ACCESS_LEVEL_ADMIN); } DEBUG_API("updating attributes of port %s", port->id); if (json_get_type(request_json) != JSON_TYPE_OBJ) { return API_ERROR(response_json, 400, "invalid-request"); } int i; char *key; json_t *child; /* Handle enabled attribute first */ key = "enabled"; child = json_obj_pop_key(request_json, key); if (child) { if (json_get_type(child) != JSON_TYPE_BOOL) { json_free(child); return INVALID_FIELD(response_json, key); } if (json_bool_get(child) && !IS_PORT_ENABLED(port)) { port_enable(port); } else if (!json_bool_get(child) && IS_PORT_ENABLED(port)) { port_disable(port); } json_free(child); } /* Then handle port-specific attributes */ if (port->attrdefs) { attrdef_t *a, **attrdefs = port->attrdefs; while ((a = *attrdefs++)) { key = a->name; child = json_obj_pop_key(request_json, key); if (child) { if (!IS_ATTRDEF_MODIFIABLE(a)) { json_free(child); if (provisioning) { continue; } else { return ATTR_NOT_MODIFIABLE(response_json, key); } } switch (a->type) { case ATTR_TYPE_BOOLEAN: { if (json_get_type(child) != JSON_TYPE_BOOL) { json_free(child); return INVALID_FIELD(response_json, key); } bool value = json_bool_get(child); ((int_setter_t) a->set)(port, a, value); DEBUG_PORT(port, "%s set to %d", a->name, value); break; } case ATTR_TYPE_NUMBER: { if (json_get_type(child) != JSON_TYPE_INT && (json_get_type(child) != JSON_TYPE_DOUBLE || IS_ATTRDEF_INTEGER(a))) { json_free(child); return INVALID_FIELD(response_json, key); } double value = json_get_type(child) == JSON_TYPE_INT ? json_int_get(child) : json_double_get(child); int idx = validate_num(value, a->min, a->max, IS_ATTRDEF_INTEGER(a), a->step, a->choices); if (!idx) { json_free(child); return INVALID_FIELD(response_json, key); } if (a->choices) { ((int_setter_t) a->set)(port, a, idx - 1); } else { if (IS_ATTRDEF_INTEGER(a)) { ((int_setter_t) a->set)(port, a, (int) value); } else { /* float */ ((float_setter_t) a->set)(port, a, value); } } DEBUG_PORT(port, "%s set to %s", a->name, dtostr(value, -1)); break; } case ATTR_TYPE_STRING: { if (json_get_type(child) != JSON_TYPE_STR) { json_free(child); return INVALID_FIELD(response_json, key); } char *value = json_str_get(child); int idx = validate_str(value, a->choices); if (!idx) { json_free(child); return INVALID_FIELD(response_json, key); } if (a->choices) { ((int_setter_t) a->set)(port, a, idx - 1); } else { ((str_setter_t) a->set)(port, a, value); } DEBUG_PORT(port, "%s set to %s", a->name, value ? value : ""); break; } } json_free(child); } } } /* Finally, handle common attributes */ for (i = 0; i < json_obj_get_len(request_json); i++) { key = json_obj_key_at(request_json, i); child = json_obj_value_at(request_json, i); if (!strcmp(key, "display_name")) { if (json_get_type(child) != JSON_TYPE_STR) { return INVALID_FIELD(response_json, key); } free(port->display_name); port->display_name = NULL; if (*json_str_get(child)) { port->display_name = strndup(json_str_get(child), PORT_MAX_DISP_NAME_LEN); } DEBUG_PORT(port, "display_name set to \"%s\"", port->display_name ? port->display_name : ""); } else if (!strcmp(key, "unit") && (port->type == PORT_TYPE_NUMBER)) { if (json_get_type(child) != JSON_TYPE_STR) { return INVALID_FIELD(response_json, key); } free(port->unit); port->unit = NULL; if (*json_str_get(child)) { port->unit = strndup(json_str_get(child), PORT_MAX_UNIT_LEN); } DEBUG_PORT(port, "unit set to \"%s\"", port->unit ? port->unit : ""); } else if (IS_PORT_WRITABLE(port) && !strcmp(key, "expression")) { if (json_get_type(child) != JSON_TYPE_STR) { return INVALID_FIELD(response_json, key); } if (port->sexpr) { port_expr_remove(port); } if (port->sequence_pos >= 0) { port_sequence_cancel(port); } char *sexpr = json_str_get(child); /* Use auxiliary s to check if expression is not empty (contains non-space characters) */ char *s = sexpr; while (isspace((int) *s)) { s++; } if (*s) { /* Parse & validate expression */ if (strlen(sexpr) > API_MAX_EXPR_LEN) { DEBUG_PORT(port, "expression is too long"); return INVALID_EXPRESSION( response_json, "expression", "too-long", /* token = */ NULL, /* pos = */ -1 ); } expr_t *expr = expr_parse(port->id, sexpr, strlen(sexpr)); if (!expr) { return INVALID_EXPRESSION_FROM_ERROR(response_json, "expression"); } if (expr_check_loops(expr, port) > 1) { DEBUG_API("loop detected in expression \"%s\"", sexpr); expr_free(expr); return INVALID_EXPRESSION( response_json, "expression", "circular-dependency", /* token = */ NULL, /* pos = */ -1 ); } port->sexpr = strdup(sexpr); if (IS_PORT_ENABLED(port)) { port->expr = expr; port_rebuild_change_dep_mask(port); } else { expr_free(expr); } } DEBUG_PORT(port, "expression set to \"%s\"", port->sexpr ? port->sexpr : ""); update_port_expression(port); } else if (IS_PORT_WRITABLE(port) && !strcmp(key, "transform_write")) { if (json_get_type(child) != JSON_TYPE_STR) { return INVALID_FIELD(response_json, key); } if (port->transform_write) { DEBUG_PORT(port, "removing write transform"); expr_free(port->transform_write); free(port->stransform_write); port->transform_write = NULL; port->stransform_write = NULL; } char *stransform_write = json_str_get(child); /* Use auxiliary s to check if expression is not empty (contains non-space characters) */ char *s = stransform_write; while (isspace((int) *s)) { s++; } if (*s) { /* Parse & validate expression */ if (strlen(stransform_write) > API_MAX_EXPR_LEN) { DEBUG_PORT(port, "expression is too long"); return INVALID_EXPRESSION( response_json, "transform_write", "too-long", /* token = */ NULL, /* pos = */ -1 ); } expr_t *transform_write = expr_parse(port->id, stransform_write, strlen(stransform_write)); if (!transform_write) { return INVALID_EXPRESSION_FROM_ERROR(response_json, "transform_write"); } port->stransform_write = strdup(stransform_write); port->transform_write = transform_write; DEBUG_PORT(port, "write transform set to \"%s\"", port->stransform_write ? port->stransform_write : ""); } } else if (!strcmp(key, "transform_read")) { if (json_get_type(child) != JSON_TYPE_STR) { return INVALID_FIELD(response_json, key); } if (port->transform_read) { DEBUG_PORT(port, "removing read transform"); expr_free(port->transform_read); free(port->stransform_read); port->transform_read = NULL; port->stransform_read = NULL; } char *stransform_read = json_str_get(child); /* Use auxiliary s to check if expression is not empty (contains non-space characters) */ char *s = stransform_read; while (isspace((int) *s)) { s++; } if (*s) { /* Parse & validate expression */ if (strlen(stransform_read) > API_MAX_EXPR_LEN) { DEBUG_PORT(port, "expression is too long"); return INVALID_EXPRESSION( response_json, "transform_read", "too-long", /* token = */ NULL, /* pos = */ -1 ); } expr_t *transform_read = expr_parse(port->id, stransform_read, strlen(stransform_read)); if (!transform_read) { return INVALID_EXPRESSION_FROM_ERROR(response_json, "transform_read"); } port->stransform_read = strdup(stransform_read); port->transform_read = transform_read; DEBUG_PORT(port, "read transform set to \"%s\"", port->stransform_read ? port->stransform_read : ""); } } else if (!strcmp(key, "persisted")) { if (json_get_type(child) != JSON_TYPE_BOOL) { return INVALID_FIELD(response_json, key); } if (json_bool_get(child)) { port->flags |= PORT_FLAG_PERSISTED; DEBUG_PORT(port, "persist enabled"); } else { port->flags &= ~PORT_FLAG_PERSISTED; DEBUG_PORT(port, "persist disabled"); } } else if (!strcmp(key, "internal")) { if (json_get_type(child) != JSON_TYPE_BOOL) { return INVALID_FIELD(response_json, key); } if (json_bool_get(child)) { port->flags |= PORT_FLAG_INTERNAL; DEBUG_PORT(port, "internal enabled"); } else { port->flags &= ~PORT_FLAG_INTERNAL; DEBUG_PORT(port, "internal disabled"); } } else if (!IS_PORT_VIRTUAL(port) && !strcmp(key, "sampling_interval")) { if (json_get_type(child) != JSON_TYPE_INT) { return INVALID_FIELD(response_json, key); } int sampling_interval = json_int_get(child); bool valid = validate_num( sampling_interval, port->min_sampling_interval, port->max_sampling_interval, TRUE, 0, NULL ); if (!valid) { return INVALID_FIELD(response_json, key); } port->sampling_interval = sampling_interval; DEBUG_PORT(port, "sampling interval set to %d ms", sampling_interval); } else if (!strcmp(key, "id") || !strcmp(key, "type") || !strcmp(key, "writable") || !strcmp(key, "min") || !strcmp(key, "max") || !strcmp(key, "integer") || !strcmp(key, "step") || !strcmp(key, "choices")) { if (!provisioning) { return ATTR_NOT_MODIFIABLE(response_json, key); } } else { if (!provisioning) { return NO_SUCH_ATTR(response_json, key); } } } port_configure(port); /* Write the value to port; this allows using persistent value when enabling a port later */ if (IS_PORT_ENABLED(port) && IS_PORT_WRITABLE(port) && !IS_UNDEFINED(port->last_read_value)) { port_write_value(port, port->last_read_value, CHANGE_REASON_NATIVE); } config_mark_for_saving(); event_push_port_update(port); *code = 204; return response_json; } json_t *api_delete_port(port_t *port, json_t *query_json, int *code) { DEBUG_API("deleting virtual port %s", port->id); json_t *response_json = json_obj_new(); if (api_access_level < API_ACCESS_LEVEL_ADMIN) { return FORBIDDEN(response_json, API_ACCESS_LEVEL_ADMIN); } if (!IS_PORT_VIRTUAL(port)) { return API_ERROR(response_json, 400, "port-not-removable"); /* Can't unregister a non-virtual port */ } event_push_port_remove(port); port_cleanup(port, /* free_id = */ FALSE); if (!virtual_port_unregister(port)) { return API_ERROR(response_json, 500, "port-unregister-error"); } if (!port_unregister(port)) { return API_ERROR(response_json, 500, "port-unregister-error"); } config_mark_for_saving(); free(port); /* Rebuild deps mask for all ports, as the former port might have been among their deps */ ports_rebuild_change_dep_mask(); *code = 204; return response_json; } json_t *api_get_port_value(port_t *port, json_t *query_json, int *code) { json_t *response_json = NULL; if (api_access_level < API_ACCESS_LEVEL_VIEWONLY) { return FORBIDDEN(response_json, API_ACCESS_LEVEL_VIEWONLY); } /* Poll ports before retrieving current port value, ensuring value is as up-to-date as possible */ core_poll(); response_json = port_make_json_value(port); *code = 200; return response_json; } json_t *api_patch_port_value(port_t *port, json_t *query_json, json_t *request_json, int *code) { json_t *response_json = json_obj_new(); double desired_value = 0; double old_value = port->last_read_value; if (api_access_level < API_ACCESS_LEVEL_NORMAL) { return FORBIDDEN(response_json, API_ACCESS_LEVEL_NORMAL); } if (!IS_PORT_ENABLED(port)) { return API_ERROR(response_json, 400, "port-disabled"); } if (!IS_PORT_WRITABLE(port)) { return API_ERROR(response_json, 400, "read-only-port"); } if (port->type == PORT_TYPE_BOOLEAN) { if (json_get_type(request_json) != JSON_TYPE_BOOL) { return API_ERROR(response_json, 400, "invalid-value"); } desired_value = json_bool_get(request_json); if (!port_write_value(port, desired_value, CHANGE_REASON_API)) { return API_ERROR(response_json, 400, "invalid-value"); } } else if (port->type == PORT_TYPE_NUMBER) { if (json_get_type(request_json) != JSON_TYPE_INT && (json_get_type(request_json) != JSON_TYPE_DOUBLE || port->integer)) { return API_ERROR(response_json, 400, "invalid-value"); } desired_value = ( json_get_type(request_json) == JSON_TYPE_INT ? json_int_get(request_json) : json_double_get(request_json) ); if (!validate_num(desired_value, port->min, port->max, port->integer, port->step, port->choices)) { return API_ERROR(response_json, 400, "invalid-value"); } if (!port_write_value(port, desired_value, CHANGE_REASON_API)) { return API_ERROR(response_json, 400, "invalid-value"); } } double after_value = port_read_value(port); if (IS_UNDEFINED(after_value) || (abs(after_value - old_value) < 1e-9 && abs(old_value - desired_value) > 1e-9)) { *code = 202; /* Value was not applied (right away) */ } else { *code = 204; } return response_json; } json_t *api_patch_port_sequence(port_t *port, json_t *query_json, json_t *request_json, int *code) { json_t *response_json = NULL; if (api_access_level < API_ACCESS_LEVEL_NORMAL) { return FORBIDDEN(response_json, API_ACCESS_LEVEL_NORMAL); } if (!IS_PORT_ENABLED(port)) { return API_ERROR(response_json, 400, "port-disabled"); } if (!IS_PORT_WRITABLE(port)) { return API_ERROR(response_json, 400, "read-only-port"); } if (port->expr) { return API_ERROR(response_json, 400, "port-with-expression"); } json_t *values_json = json_obj_lookup_key(request_json, "values"); if (!values_json) { return MISSING_FIELD(response_json, "values"); } if (json_get_type(values_json) != JSON_TYPE_LIST || !json_list_get_len(values_json)) { return INVALID_FIELD(response_json, "values"); } json_t *delays_json = json_obj_lookup_key(request_json, "delays"); if (!delays_json) { return MISSING_FIELD(response_json, "delays"); } if (json_get_type(delays_json) != JSON_TYPE_LIST || !json_list_get_len(delays_json)) { return INVALID_FIELD(response_json, "delays"); } if (json_list_get_len(delays_json) != json_list_get_len(values_json)) { return INVALID_FIELD(response_json, "delays"); } json_t *repeat_json = json_obj_lookup_key(request_json, "repeat"); if (!repeat_json) { return MISSING_FIELD(response_json, "repeat"); } if (json_get_type(repeat_json) != JSON_TYPE_INT) { return INVALID_FIELD(response_json, "repeat"); } int repeat = json_int_get(repeat_json); if (repeat < API_MIN_SEQUENCE_REPEAT || repeat > API_MAX_SEQUENCE_REPEAT) { return INVALID_FIELD(response_json, "repeat"); } int i; json_t *j; if (port->sequence_pos >= 0) { port_sequence_cancel(port); } port->sequence_len = json_list_get_len(values_json); port->sequence_pos = 0; port->sequence_repeat = repeat; port->sequence_values = malloc(sizeof(double) * port->sequence_len); port->sequence_delays = malloc(sizeof(int) * (port->sequence_len)); /* Values */ for (i = 0; i < json_list_get_len(values_json); i++) { j = json_list_value_at(values_json, i); if (port->type == PORT_TYPE_BOOLEAN) { if (json_get_type(j) != JSON_TYPE_BOOL) { return SEQ_INVALID_FIELD(response_json, "values"); } port->sequence_values[i] = json_bool_get(j); } if (port->type == PORT_TYPE_NUMBER) { if (json_get_type(j) != JSON_TYPE_INT && (json_get_type(j) != JSON_TYPE_DOUBLE || port->integer)) { return SEQ_INVALID_FIELD(response_json, "values"); } double value = json_get_type(j) == JSON_TYPE_INT ? json_int_get(j) : json_double_get(j); if (!validate_num(value, port->min, port->max, port->integer, port->step, port->choices)) { return SEQ_INVALID_FIELD(response_json, "values"); } port->sequence_values[i] = value; } } /* Delays */ for (i = 0; i < json_list_get_len(delays_json); i++) { j = json_list_value_at(delays_json, i); if (json_get_type(j) != JSON_TYPE_INT) { return SEQ_INVALID_FIELD(response_json, "delays"); } port->sequence_delays[i] = json_int_get(j); if (port->sequence_delays[i] < API_MIN_SEQUENCE_DELAY || port->sequence_delays[i] > API_MAX_SEQUENCE_DELAY) { return SEQ_INVALID_FIELD(response_json, "delays"); } } /* Start sequence timer */ port->sequence_timer = zalloc(sizeof(os_timer_t)); os_timer_disarm(port->sequence_timer); os_timer_setfn(port->sequence_timer, on_sequence_timer, port); os_timer_arm(port->sequence_timer, 1, /* repeat = */ FALSE); response_json = json_obj_new(); *code = 204; return response_json; } json_t *api_get_webhooks(json_t *query_json, int *code) { json_t *response_json = json_obj_new(); if (api_access_level < API_ACCESS_LEVEL_ADMIN) { return FORBIDDEN(response_json, API_ACCESS_LEVEL_ADMIN); } DEBUG_API("returning webhooks parameters"); json_obj_append(response_json, "enabled", json_bool_new(device_flags & DEVICE_FLAG_WEBHOOKS_ENABLED)); json_obj_append( response_json, "scheme", json_str_new(device_flags & DEVICE_FLAG_WEBHOOKS_HTTPS ? "https" : "http") ); json_obj_append(response_json, "host", json_str_new(webhooks_host ? webhooks_host : "")); json_obj_append(response_json, "port", json_int_new(webhooks_port)); json_obj_append(response_json, "path", json_str_new(webhooks_path ? webhooks_path : "")); json_obj_append(response_json, "password_hash", json_str_new(webhooks_password_hash)); json_t *json_events = json_list_new(); int e; for (e = EVENT_TYPE_MIN; e <= EVENT_TYPE_MAX; e++) { if (webhooks_events_mask & BIT(e)) { json_list_append(json_events, json_str_new(EVENT_TYPES_STR[e])); } } json_obj_append(response_json, "events", json_events); json_obj_append(response_json, "timeout", json_int_new(webhooks_timeout)); json_obj_append(response_json, "retries", json_int_new(webhooks_retries)); *code = 200; return response_json; } json_t *api_put_webhooks(json_t *query_json, json_t *request_json, int *code) { DEBUG_API("updating webhooks parameters"); json_t *response_json = json_obj_new(); if (api_access_level < API_ACCESS_LEVEL_ADMIN) { return FORBIDDEN(response_json, API_ACCESS_LEVEL_ADMIN); } if (json_get_type(request_json) != JSON_TYPE_OBJ) { return API_ERROR(response_json, 400, "invalid-request"); } /* Enabled */ json_t *enabled_json = json_obj_lookup_key(request_json, "enabled"); if (!enabled_json) { return MISSING_FIELD(response_json, "enabled"); } if (json_get_type(enabled_json) != JSON_TYPE_BOOL) { return INVALID_FIELD(response_json, "enabled"); } bool enabled = json_bool_get(enabled_json); /* Scheme */ json_t *scheme_json = json_obj_lookup_key(request_json, "scheme"); if (!scheme_json) { return MISSING_FIELD(response_json, "scheme"); } if (json_get_type(scheme_json) != JSON_TYPE_STR) { return INVALID_FIELD(response_json, "scheme"); } bool scheme_https = FALSE; #ifdef _SSL if (!strcmp(json_str_get(scheme_json), "https")) { scheme_https = TRUE; } else #endif if (strcmp(json_str_get(scheme_json), "http")) { return INVALID_FIELD(response_json, "scheme"); } /* Host */ json_t *host_json = json_obj_lookup_key(request_json, "host"); if (!host_json) { return MISSING_FIELD(response_json, "host"); } if (json_get_type(host_json) != JSON_TYPE_STR) { return INVALID_FIELD(response_json, "host"); } if (strlen(json_str_get(host_json)) == 0 && enabled) { return INVALID_FIELD(response_json, "host"); } /* Port */ json_t *port_json = json_obj_lookup_key(request_json, "port"); if (!port_json) { return MISSING_FIELD(response_json, "port"); } if (json_get_type(port_json) != JSON_TYPE_INT) { return INVALID_FIELD(response_json, "port"); } if (json_int_get(port_json) < 1 || json_int_get(port_json) > 65535) { return INVALID_FIELD(response_json, "port"); } /* Path */ json_t *path_json = json_obj_lookup_key(request_json, "path"); if (!path_json) { return MISSING_FIELD(response_json, "path"); } if (json_get_type(path_json) != JSON_TYPE_STR) { return INVALID_FIELD(response_json, "path"); } if (strlen(json_str_get(path_json)) == 0 && enabled) { return INVALID_FIELD(response_json, "path"); } /* Password */ json_t *password_json = json_obj_lookup_key(request_json, "password"); json_t *password_hash_json = json_obj_lookup_key(request_json, "password_hash"); if (!password_json && !password_hash_json) { /* At least one of the two must be supplied */ return MISSING_FIELD(response_json, "password"); } if (password_json && json_get_type(password_json) != JSON_TYPE_STR) { return INVALID_FIELD(response_json, "password"); } if (password_hash_json) { if (json_get_type(password_hash_json) != JSON_TYPE_STR) { return INVALID_FIELD(response_json, "password_hash"); } char *password_hash = json_str_get(password_hash_json); if (strlen(password_hash) != SHA256_HEX_LEN) { return INVALID_FIELD(response_json, "password_hash"); } } /* Events */ json_t *event_json, *events_json = json_obj_lookup_key(request_json, "events"); if (!events_json) { return MISSING_FIELD(response_json, "events"); } if (json_get_type(events_json) != JSON_TYPE_LIST) { return INVALID_FIELD(response_json, "events"); } int i, e, len = json_list_get_len(events_json); uint8 events_mask = 0; for (i = 0; i < len; i++) { event_json = json_list_value_at(events_json, i); if (json_get_type(event_json) != JSON_TYPE_STR) { return INVALID_FIELD(response_json, "events"); } for (e = EVENT_TYPE_MIN; e <= EVENT_TYPE_MAX; e++) { if (!strcmp(json_str_get(event_json), EVENT_TYPES_STR[e])) { events_mask |= BIT(e); break; } } if (e > EVENT_TYPE_MAX) { return INVALID_FIELD(response_json, "events"); } DEBUG_WEBHOOKS("event mask includes %s", EVENT_TYPES_STR[e]); } /* Timeout */ json_t *timeout_json = json_obj_lookup_key(request_json, "timeout"); if (!timeout_json) { return MISSING_FIELD(response_json, "timeout"); } if (json_get_type(timeout_json) != JSON_TYPE_INT) { return INVALID_FIELD(response_json, "timeout"); } if (json_int_get(timeout_json) < WEBHOOKS_MIN_TIMEOUT || json_int_get(timeout_json) > WEBHOOKS_MAX_TIMEOUT) { return INVALID_FIELD(response_json, "timeout"); } /* Retries */ json_t *retries_json = json_obj_lookup_key(request_json, "retries"); if (!retries_json) { return MISSING_FIELD(response_json, "retries"); } if (json_get_type(retries_json) != JSON_TYPE_INT) { return INVALID_FIELD(response_json, "retries"); } if (json_int_get(retries_json) < WEBHOOKS_MIN_RETRIES || json_int_get(retries_json) > WEBHOOKS_MAX_RETRIES) { return INVALID_FIELD(response_json, "retries"); } /* Now that we've validated input data, we can apply changes */ if (enabled) { device_flags |= DEVICE_FLAG_WEBHOOKS_ENABLED; DEBUG_WEBHOOKS("enabled"); } else { device_flags &= ~DEVICE_FLAG_WEBHOOKS_ENABLED; DEBUG_WEBHOOKS("disabled"); } if (scheme_https) { device_flags |= DEVICE_FLAG_WEBHOOKS_HTTPS; DEBUG_WEBHOOKS("scheme set to HTTPS"); } else { DEBUG_WEBHOOKS("scheme set to HTTP"); device_flags &= ~DEVICE_FLAG_WEBHOOKS_HTTPS; } free(webhooks_host); webhooks_host = strdup(json_str_get(host_json)); DEBUG_WEBHOOKS("host set to \"%s\"", webhooks_host); webhooks_port = json_int_get(port_json); DEBUG_WEBHOOKS("port set to %d", webhooks_port); free(webhooks_path); webhooks_path = strdup(json_str_get(path_json)); DEBUG_WEBHOOKS("path set to \"%s\"", webhooks_path); char *password_hash; if (password_json) { char *password = json_str_get(password_json); password_hash = sha256_hex(password); } else { /* Assuming password_hash supplied */ password_hash = strdup(json_str_get(password_hash_json)); } strcpy(webhooks_password_hash, password_hash); free(password_hash); DEBUG_WEBHOOKS("password set"); webhooks_events_mask = events_mask; webhooks_timeout = json_int_get(timeout_json); DEBUG_WEBHOOKS("timeout set to %d", webhooks_timeout); webhooks_retries = json_int_get(retries_json); DEBUG_WEBHOOKS("retries set to %d", webhooks_retries); config_mark_for_saving(); *code = 204; return response_json; } json_t *api_get_wifi(json_t *query_json, int *code) { json_t *response_json = NULL; if (api_access_level < API_ACCESS_LEVEL_ADMIN) { return FORBIDDEN(response_json, API_ACCESS_LEVEL_ADMIN); } if (!wifi_scan(on_wifi_scan)) { response_json = json_obj_new(); json_obj_append(response_json, "error", json_str_new("busy")); *code = 503; return response_json; } return NULL; } json_t *api_get_raw_io(char *io, json_t *query_json, int *code) { json_t *response_json = json_obj_new(); if (api_access_level < API_ACCESS_LEVEL_ADMIN) { return FORBIDDEN(response_json, API_ACCESS_LEVEL_ADMIN); } DEBUG_API("returning raw value for %s", io); if (!strncmp(io, "gpio", 4)) { int gpio_no = strtol(io + 4, NULL, 10); if (gpio_no < 0 || gpio_no > 16) { return API_ERROR(response_json, 404, "no-such-io"); } json_obj_append(response_json, "value", json_bool_new(gpio_read_value(gpio_no))); json_obj_append(response_json, "configured", json_bool_new(gpio_is_configured(gpio_no))); json_obj_append(response_json, "output", json_bool_new(gpio_is_output(gpio_no))); if (gpio_no == 16) { json_obj_append(response_json, "pull_down", json_bool_new(!gpio_get_pull(gpio_no))); } else { json_obj_append(response_json, "pull_up", json_bool_new(gpio_get_pull(gpio_no))); } } else if (!strcmp(io, "adc0")) { json_obj_append(response_json, "value", json_int_new(system_adc_read())); } else if (!strcmp(io, "hspi")) { uint8 bit_order; bool cpol; bool cpha; uint32 freq; bool configured = hspi_get_current_setup(&bit_order, &cpol, &cpha, &freq); json_obj_append(response_json, "bit_order", json_str_new(bit_order ? "lsb_first" : "msb_first")); json_obj_append(response_json, "cpol", json_bool_new(cpol)); json_obj_append(response_json, "cpha", json_bool_new(cpha)); json_obj_append(response_json, "freq", json_int_new(freq)); json_obj_append(response_json, "configured", json_bool_new(configured)); } else { return API_ERROR(response_json, 404, "no-such-io"); } *code = 200; return response_json; } json_t *api_patch_raw_io(char *io, json_t *query_json, json_t *request_json, int *code) { json_t *response_json = json_obj_new(); json_t *value_json, *param_json; uint32 len, i; if (api_access_level < API_ACCESS_LEVEL_ADMIN) { return FORBIDDEN(response_json, API_ACCESS_LEVEL_ADMIN); } if (json_get_type(request_json) != JSON_TYPE_OBJ) { return API_ERROR(response_json, 400, "invalid-request"); } if (!strncmp(io, "gpio", 4)) { int gpio_no = strtol(io + 4, NULL, 10); if (gpio_no < 0 || gpio_no > 16) { return API_ERROR(response_json, 404, "no-such-io"); } json_t *value_json = json_obj_lookup_key(request_json, "value"); bool value = gpio_read_value(gpio_no); if (value_json) { if (json_get_type(value_json) != JSON_TYPE_BOOL) { return INVALID_FIELD(response_json, "value"); } value = json_bool_get(value_json); } json_t *output_json = json_obj_lookup_key(request_json, "output"); bool output = gpio_is_output(gpio_no); if (output_json) { if (json_get_type(output_json) != JSON_TYPE_BOOL) { return INVALID_FIELD(response_json, "output"); } output = json_bool_get(output_json); } json_t *pull_up_json = json_obj_lookup_key(request_json, "pull_up"); bool pull_up = gpio_get_pull(gpio_no); if (pull_up_json) { if (json_get_type(pull_up_json) != JSON_TYPE_BOOL) { return INVALID_FIELD(response_json, "pull_up"); } pull_up = json_bool_get(pull_up_json); } json_t *pull_down_json = json_obj_lookup_key(request_json, "pull_down"); bool pull_down = !gpio_get_pull(gpio_no); if (pull_down_json) { if (json_get_type(pull_down_json) != JSON_TYPE_BOOL) { return INVALID_FIELD(response_json, "pull_down"); } pull_down = json_bool_get(pull_down_json); } if (output) { gpio_configure_output(gpio_no, value); } else { if (gpio_no == 16) { gpio_configure_input(gpio_no, !pull_down); } else { gpio_configure_input(gpio_no, pull_up); } } } else if (!strcmp(io, "adc0")) { return API_ERROR(response_json, 400, "read-only-io"); } else if (!strcmp(io, "hspi")) { value_json = json_obj_lookup_key(request_json, "value"); if (value_json) { if (json_get_type(value_json) != JSON_TYPE_LIST) { return INVALID_FIELD(response_json, "value"); } json_t *v_json; len = json_list_get_len(value_json); bool hex = FALSE; uint8 out_frame[len], in_frame[len]; for (i = 0; i < len; i++) { v_json = json_list_value_at(value_json, i); if (json_get_type(v_json) == JSON_TYPE_INT) { out_frame[i] = json_int_get(v_json) & 0xFF; } else if (json_get_type(v_json) == JSON_TYPE_STR) { out_frame[i] = strtol(json_str_get(v_json), NULL, 16) & 0xFF; hex = TRUE; } else { return INVALID_FIELD(response_json, "value"); } } hspi_transfer(out_frame, in_frame, len); value_json = json_list_new(); char hex_str[3]; for (i = 0; i < len; i++) { if (hex) { snprintf(hex_str, sizeof(hex_str), "%02X", in_frame[i]); json_list_append(value_json, json_str_new(hex_str)); } else { json_list_append(value_json, json_int_new(in_frame[i])); } } json_obj_append(response_json, "value", value_json); *code = 200; } uint8 bit_order; bool cpol; bool cpha; uint32 freq; bool reconfigured = FALSE; hspi_get_current_setup(&bit_order, &cpol, &cpha, &freq); param_json = json_obj_lookup_key(request_json, "freq"); if (param_json) { if (json_get_type(param_json) != JSON_TYPE_INT) { return INVALID_FIELD(response_json, "freq"); } freq = json_int_get(param_json); reconfigured = TRUE; } param_json = json_obj_lookup_key(request_json, "cpol"); if (param_json) { if (json_get_type(param_json) != JSON_TYPE_BOOL) { return INVALID_FIELD(response_json, "cpol"); } cpol = json_bool_get(param_json); reconfigured = TRUE; } param_json = json_obj_lookup_key(request_json, "cpha"); if (param_json) { if (json_get_type(param_json) != JSON_TYPE_BOOL) { return INVALID_FIELD(response_json, "cpha"); } cpha = json_bool_get(param_json); reconfigured = TRUE; } param_json = json_obj_lookup_key(request_json, "bit_order"); if (param_json) { if (json_get_type(param_json) != JSON_TYPE_STR) { return INVALID_FIELD(response_json, "bit_order"); } bit_order = !strcmp(json_str_get(param_json), "lsb_first"); reconfigured = TRUE; } if (reconfigured) { hspi_setup(bit_order, cpol, cpha, freq); } } else { return API_ERROR(response_json, 404, "no-such-io"); } *code = 204; return response_json; } json_t *api_get_peripherals(json_t *query_json, int *code) { json_t *response_json = json_list_new(); if (api_access_level < API_ACCESS_LEVEL_ADMIN) { return FORBIDDEN(response_json, API_ACCESS_LEVEL_ADMIN); } for (int i = 0; i < all_peripherals_count; i++) { peripheral_t *peripheral = all_peripherals[i]; json_list_append(response_json, peripheral_to_json(peripheral)); } *code = 200; return response_json; } json_t *api_put_peripherals(json_t *query_json, json_t *request_json, int *code) { json_t *response_json = json_obj_new(); json_t *peripheral_config; json_t *type_json; json_t *flags_json; json_t *params_json; json_t *port_ids_json; json_t *json; uint16 type_id; uint16 flags; char **port_ids = NULL; int i, index; uint8 port_ids_len = 0; peripheral_t *peripheral; uint8 int8_params[PERIPHERAL_MAX_INT8_PARAMS]; uint8 int8_param; uint8 int8_param_count; uint16 int16_params[PERIPHERAL_MAX_INT16_PARAMS]; uint16 int16_param; uint8 int16_param_count; uint32 int32_params[PERIPHERAL_MAX_INT32_PARAMS]; uint32 int32_param; uint8 int32_param_count; uint64 int64_params[PERIPHERAL_MAX_INT64_PARAMS]; uint64 int64_param; uint8 int64_param_count; double double_params[PERIPHERAL_MAX_DOUBLE_PARAMS]; double double_param; uint8 double_param_count; if (api_access_level < API_ACCESS_LEVEL_ADMIN) { return FORBIDDEN(response_json, API_ACCESS_LEVEL_ADMIN); } if (json_get_type(request_json) != JSON_TYPE_LIST) { return API_ERROR(response_json, 400, "invalid-request"); } if (json_list_get_len(request_json) > PERIPHERAL_MAX_NUM) { return API_ERROR(response_json, 400, "too-many-peripherals"); } /* Unregister all (non-virtual) ports */ port_t *p; for (i = 0; i < all_ports_count; i++) { p = all_ports[i]; if (IS_PORT_VIRTUAL(p)) { continue; } port_cleanup(p, /* free_id = */ FALSE); if (!port_unregister(p)) { return API_ERROR(response_json, 500, "port-unregister-error"); } free(p); i--; /* Current port was removed from all_ports; position i should be processed again */ } /* Rebuild deps mask for remaining (virtual) ports */ ports_rebuild_change_dep_mask(); while (all_peripherals_count) { peripheral = all_peripherals[0]; peripheral_unregister(peripheral); peripheral_cleanup(peripheral); peripheral_free(peripheral); } DEBUG_PERIPHERALS("creating newly supplied peripherals"); for (index = 0; index < json_list_get_len(request_json); index++) { peripheral_config = json_list_value_at(request_json, index); flags = 0; int8_param_count = 0; int16_param_count = 0; int32_param_count = 0; int64_param_count = 0; double_param_count = 0; port_ids_len = 0; if (json_get_type(peripheral_config) != JSON_TYPE_OBJ) { return API_ERROR(response_json, 400, "invalid-request"); } /* Type */ type_json = json_obj_lookup_key(peripheral_config, "type"); if (!type_json || json_get_type(type_json) != JSON_TYPE_INT) { return INVALID_FIELD(response_json, "type"); } type_id = json_int_get(type_json); if (type_id > PERIPHERAL_MAX_TYPE_ID || type_id < 1) { return INVALID_FIELD(response_json, "type"); } /* Flags */ flags_json = json_obj_lookup_key(peripheral_config, "flags"); if (flags_json) { if (json_get_type(flags_json) == JSON_TYPE_STR) { flags = strtol(json_str_get(flags_json), NULL, 2); } else if (json_get_type(flags_json) == JSON_TYPE_INT) { flags = json_int_get(flags_json); } else { return INVALID_FIELD(response_json, "flags"); } } /* int8 params */ params_json = json_obj_lookup_key(peripheral_config, "int8_params"); if (params_json) { if ((json_get_type(params_json) != JSON_TYPE_LIST) || (json_list_get_len(params_json) > PERIPHERAL_MAX_INT8_PARAMS)) { return INVALID_FIELD(response_json, "int8_params"); } for (i = 0; i < json_list_get_len(params_json); i++) { json = json_list_value_at(params_json, i); if (json_get_type(json) == JSON_TYPE_STR) { /* Hex value */ int8_param = strtol(json_str_get(json), NULL, 16); } else if (json_get_type(json) == JSON_TYPE_INT) { int8_param = json_int_get(json); } else { return INVALID_FIELD(response_json, "int8_params"); } int8_params[int8_param_count++] = int8_param; } } /* int16 params */ params_json = json_obj_lookup_key(peripheral_config, "int16_params"); if (params_json) { if ((json_get_type(params_json) != JSON_TYPE_LIST) || (json_list_get_len(params_json) > PERIPHERAL_MAX_INT16_PARAMS)) { return INVALID_FIELD(response_json, "int16_params"); } for (i = 0; i < json_list_get_len(params_json); i++) { json = json_list_value_at(params_json, i); if (json_get_type(json) == JSON_TYPE_STR) { /* Hex value */ int16_param = strtol(json_str_get(json), NULL, 16); } else if (json_get_type(json) == JSON_TYPE_INT) { int16_param = json_int_get(json); } else { return INVALID_FIELD(response_json, "int16_params"); } int16_params[int16_param_count++] = int16_param; } } /* int32 params */ params_json = json_obj_lookup_key(peripheral_config, "int32_params"); if (params_json) { if ((json_get_type(params_json) != JSON_TYPE_LIST) || (json_list_get_len(params_json) > PERIPHERAL_MAX_INT32_PARAMS)) { return INVALID_FIELD(response_json, "int32_params"); } for (i = 0; i < json_list_get_len(params_json); i++) { json = json_list_value_at(params_json, i); if (json_get_type(json) == JSON_TYPE_STR) { /* Hex value */ int32_param = strtol(json_str_get(json), NULL, 16); } else if (json_get_type(json) == JSON_TYPE_INT) { int32_param = json_int_get(json); } else { return INVALID_FIELD(response_json, "int32_params"); } int32_params[int32_param_count++] = int32_param; } } /* int64 params */ params_json = json_obj_lookup_key(peripheral_config, "int64_params"); if (params_json) { if ((json_get_type(params_json) != JSON_TYPE_LIST) || (json_list_get_len(params_json) > PERIPHERAL_MAX_INT64_PARAMS)) { return INVALID_FIELD(response_json, "int64_params"); } for (i = 0; i < json_list_get_len(params_json); i++) { json = json_list_value_at(params_json, i); if (json_get_type(json) == JSON_TYPE_STR) { /* Hex value */ int64_param = strtol(json_str_get(json), NULL, 16); } else if (json_get_type(json) == JSON_TYPE_INT) { int64_param = json_int_get(json); } else { return INVALID_FIELD(response_json, "int64_params"); } int64_params[int64_param_count++] = int64_param; } } /* double params */ params_json = json_obj_lookup_key(peripheral_config, "double_params"); if (params_json) { if ((json_get_type(params_json) != JSON_TYPE_LIST) || (json_list_get_len(params_json) > PERIPHERAL_MAX_DOUBLE_PARAMS)) { return INVALID_FIELD(response_json, "double_params"); } for (i = 0; i < json_list_get_len(params_json); i++) { json = json_list_value_at(params_json, i); if (json_get_type(json) == JSON_TYPE_INT) { double_param = json_int_get(json); } else if (json_get_type(json) == JSON_TYPE_DOUBLE) { double_param = json_double_get(json); } else { return INVALID_FIELD(response_json, "double_params"); } double_params[double_param_count++] = double_param; } } /* Port IDs */ port_ids_json = json_obj_lookup_key(peripheral_config, "port_ids"); if (port_ids_json) { if (json_get_type(port_ids_json) != JSON_TYPE_LIST) { return INVALID_FIELD(response_json, "port_ids"); } port_ids_len = json_list_get_len(port_ids_json); port_ids = malloc(port_ids_len * sizeof(char *)); for (i = 0; i < json_list_get_len(port_ids_json); i++) { json = json_list_value_at(port_ids_json, i); if (json_get_type(json) != JSON_TYPE_STR) { free(port_ids); return INVALID_FIELD(response_json, "port_ids"); } port_ids[i] = json_str_get(json); } } /* Create the peripheral & its ports */ peripheral = zalloc(sizeof(peripheral_t)); peripheral->index = index; peripheral_register(peripheral); peripheral->type_id = type_id; peripheral->flags = flags; peripheral->params = zalloc(PERIPHERAL_PARAMS_SIZE); if (int8_param_count) { memcpy(peripheral->params + PERIPHERAL_CONFIG_OFFS_INT8_PARAMS, int8_params, int8_param_count); } if (int16_param_count) { memcpy(peripheral->params + PERIPHERAL_CONFIG_OFFS_INT16_PARAMS, int16_params, int16_param_count * 2); } if (int32_param_count) { memcpy(peripheral->params + PERIPHERAL_CONFIG_OFFS_INT32_PARAMS, int32_params, int32_param_count * 4); } if (int64_param_count) { memcpy(peripheral->params + PERIPHERAL_CONFIG_OFFS_INT64_PARAMS, int64_params, int64_param_count * 4); } if (double_param_count) { memcpy(peripheral->params + PERIPHERAL_CONFIG_OFFS_DOUBLE_PARAMS, double_params, double_param_count * 4); } peripheral_init(peripheral); peripheral_make_ports(peripheral, port_ids, port_ids_len); free(port_ids); port_ids = NULL; } /* Clear existing configuration name & version, but only when called directly, i.e. not during provisioning */ if (!config_is_provisioning()) { DEBUG_DEVICE("clearing config name"); device_config_name[0] = '\0'; device_provisioning_version = 0; event_push_full_update(); } config_mark_for_saving(); *code = 204; return response_json; } json_t *api_get_system(json_t *query_json, int *code) { json_t *response_json = json_obj_new(); if (api_access_level < API_ACCESS_LEVEL_ADMIN) { return FORBIDDEN(response_json, API_ACCESS_LEVEL_ADMIN); } /* Setup button */ int8 pin; bool level; uint8 hold, reset_hold; system_setup_button_get_config(&pin, &level, &hold, &reset_hold); json_t *setup_button_json = json_obj_new(); json_obj_append(response_json, "setup_button", setup_button_json); json_obj_append(setup_button_json, "pin", json_int_new(pin)); json_obj_append(setup_button_json, "level", json_bool_new(level)); json_obj_append(setup_button_json, "hold", json_int_new(hold)); json_obj_append(setup_button_json, "reset_hold", json_int_new(reset_hold)); /* Status LED */ system_status_led_get_config(&pin, &level); json_t *status_led_json = json_obj_new(); json_obj_append(response_json, "status_led", status_led_json); json_obj_append(status_led_json, "pin", json_int_new(pin)); json_obj_append(status_led_json, "level", json_bool_new(level)); /* Battery */ #ifdef _BATTERY uint16 div_factor; uint16 voltages[BATTERY_LUT_LEN]; battery_get_config(&div_factor, voltages); json_t *battery_json = json_obj_new(); json_obj_append(response_json, "battery", battery_json); json_obj_append(battery_json, "div", json_int_new(div_factor)); json_t *voltages_json = json_list_new(); json_obj_append(battery_json, "voltages", voltages_json); for (int i = 0; i < BATTERY_LUT_LEN; i++) { json_list_append(voltages_json, json_int_new(voltages[i])); } #endif *code = 200; return response_json; } json_t *api_patch_system(json_t *query_json, json_t *request_json, int *code) { json_t *response_json = json_obj_new(); json_t *setup_button_json; json_t *status_led_json; json_t *json; if (api_access_level < API_ACCESS_LEVEL_ADMIN) { return FORBIDDEN(response_json, API_ACCESS_LEVEL_ADMIN); } if (json_get_type(request_json) != JSON_TYPE_OBJ) { return API_ERROR(response_json, 400, "invalid-request"); } /* Setup button */ setup_button_json = json_obj_lookup_key(request_json, "setup_button"); int8 pin = -1; bool level = FALSE; uint8 hold = 0; uint8 reset_hold = 0; if (setup_button_json) { if (json_get_type(setup_button_json) != JSON_TYPE_OBJ) { return INVALID_FIELD(response_json, "setup_button"); } json = json_obj_lookup_key(setup_button_json, "pin"); if (!json || json_get_type(json) != JSON_TYPE_INT) { return INVALID_FIELD(response_json, "setup_button"); } pin = json_int_get(json); if (pin > 16) { pin = -1; } json = json_obj_lookup_key(setup_button_json, "level"); if (!json || json_get_type(json) != JSON_TYPE_BOOL) { return INVALID_FIELD(response_json, "setup_button"); } level = json_bool_get(json); json = json_obj_lookup_key(setup_button_json, "hold"); if (!json || json_get_type(json) != JSON_TYPE_INT) { return INVALID_FIELD(response_json, "setup_button"); } hold = json_int_get(json); json = json_obj_lookup_key(setup_button_json, "reset_hold"); if (!json || json_get_type(json) != JSON_TYPE_INT) { return INVALID_FIELD(response_json, "setup_button"); } reset_hold = json_int_get(json); } system_setup_button_set_config(pin, level, hold, reset_hold); /* Status LED */ status_led_json = json_obj_lookup_key(request_json, "status_led"); if (status_led_json) { if (json_get_type(status_led_json) != JSON_TYPE_OBJ) { return INVALID_FIELD(response_json, "status_led"); } json = json_obj_lookup_key(status_led_json, "pin"); if (!json || json_get_type(json) != JSON_TYPE_INT) { return INVALID_FIELD(response_json, "status_led"); } pin = json_int_get(json); if (pin > 16) { pin = -1; } json = json_obj_lookup_key(status_led_json, "level"); if (!json || json_get_type(json) != JSON_TYPE_BOOL) { return INVALID_FIELD(response_json, "status_led"); } level = json_bool_get(json); } system_status_led_set_config(pin, level); /* Battery */ #ifdef _BATTERY json_t *battery_json, *j; battery_json = json_obj_lookup_key(request_json, "battery"); uint16 div_factor = 0; uint16 voltages[6]; memset(voltages, 0, sizeof(uint16) * 6); if (battery_json) { if (json_get_type(battery_json) != JSON_TYPE_OBJ) { return INVALID_FIELD(response_json, "battery"); } json = json_obj_lookup_key(battery_json, "div"); if (!json || json_get_type(json) != JSON_TYPE_INT) { return INVALID_FIELD(response_json, "battery"); } div_factor = json_int_get(json); json = json_obj_lookup_key(battery_json, "voltages"); if (!json || json_get_type(json) != JSON_TYPE_LIST || json_list_get_len(json) != BATTERY_LUT_LEN) { return INVALID_FIELD(response_json, "battery"); } for (int i = 0; i < BATTERY_LUT_LEN; i++) { j = json_list_value_at(json, i); if (json_get_type(j) != JSON_TYPE_INT) { return INVALID_FIELD(response_json, "battery"); } voltages[i] = json_int_get(j); } } battery_configure(div_factor, voltages); #endif /* Clear existing configuration name & version, but only when called directly, i.e. not during provisioning */ if (!config_is_provisioning()) { DEBUG_DEVICE("clearing config name"); device_config_name[0] = '\0'; device_provisioning_version = 0; } system_config_save(); *code = 204; return response_json; } json_t *api_get_provisioning(json_t *query_json, int *code) { json_t *response_json = json_obj_new(); if (api_access_level < API_ACCESS_LEVEL_ADMIN) { return FORBIDDEN(response_json, API_ACCESS_LEVEL_ADMIN); } int dummy_code; json_obj_append(response_json, "peripherals", api_get_peripherals(NULL, &dummy_code)); json_obj_append(response_json, "system", api_get_system(NULL, &dummy_code)); json_obj_append(response_json, "device", api_get_device(NULL, &dummy_code)); json_obj_append(response_json, "ports", api_get_ports(NULL, &dummy_code)); *code = 200; return response_json; } json_t *api_put_provisioning(json_t *query_json, json_t *request_json, int *code) { json_t *response_json = json_obj_new(); if (api_access_level < API_ACCESS_LEVEL_ADMIN) { return FORBIDDEN(response_json, API_ACCESS_LEVEL_ADMIN); } if (json_get_type(request_json) != JSON_TYPE_OBJ) { return API_ERROR(response_json, 400, "invalid-request"); } if (!config_apply_json_provisioning(request_json, /* force = */ TRUE)) { return API_ERROR(response_json, 400, "invalid-request"); } /* Clear existing configuration name & version */ DEBUG_DEVICE("clearing config name"); device_config_name[0] = '\0'; device_provisioning_version = 0; event_push_full_update(); *code = 204; return response_json; } json_t *_api_error(json_t *response_json, char *error, char *field_name, char *field_value) { json_free(response_json); response_json = json_obj_new(); json_obj_append(response_json, "error", json_str_new(error)); if (field_name) { json_obj_append(response_json, field_name, json_str_new(field_value)); } return response_json; } json_t *_forbidden_error(json_t *response_json, uint8 level) { char *field_value; switch (level) { case API_ACCESS_LEVEL_ADMIN: field_value = "admin"; break; case API_ACCESS_LEVEL_NORMAL: field_value = "normal"; break; case API_ACCESS_LEVEL_VIEWONLY: field_value = "viewonly"; break; default: field_value = "none"; break; } return _api_error(response_json, "forbidden", "required_level", field_value); } json_t *_invalid_expression_error(json_t *response_json, char *field, char *reason, char *token, int32 pos) { json_free(response_json); response_json = json_obj_new(); json_obj_append(response_json, "error", json_str_new("invalid-field")); json_obj_append(response_json, "field", json_str_new(field)); json_t *details_json = json_obj_new(); json_obj_append(details_json, "reason", json_str_new(reason)); if (token) { json_obj_append(details_json, "token", json_str_new(token)); } if (pos >= 1) { json_obj_append(details_json, "pos", json_int_new(pos)); } json_obj_append(response_json, "details", details_json); return response_json; } json_t *device_from_json( json_t *json, int *code, bool *needs_reset, bool *needs_sleep_reset, bool *config_name_changed, bool ignore_unknown ) { *needs_reset = FALSE; *config_name_changed = FALSE; *needs_sleep_reset = FALSE; json_t *response_json = NULL; int i; char *key; json_t *child; for (i = 0; i < json_obj_get_len(json); i++) { key = json_obj_key_at(json, i); child = json_obj_value_at(json, i); if (!strcmp(key, "name")) { if (json_get_type(child) != JSON_TYPE_STR) { return INVALID_FIELD(response_json, key); } char *value = json_str_get(child); if (!validate_id(value) || strlen(json_str_get(child)) > API_MAX_DEVICE_NAME_LEN) { return INVALID_FIELD(response_json, key); } free(device_name); device_name = strdup(value); DEBUG_DEVICE("name set to \"%s\"", device_name); httpserver_set_name(device_name); } else if (!strcmp(key, "display_name")) { if (json_get_type(child) != JSON_TYPE_STR) { return INVALID_FIELD(response_json, key); } char *value = json_str_get(child); if (strlen(json_str_get(child)) > API_MAX_DEVICE_DISP_NAME_LEN) { return INVALID_FIELD(response_json, key); } free(device_display_name); device_display_name = strdup(value); DEBUG_DEVICE("display name set to \"%s\"", device_display_name); } else if (!strcmp(key, "admin_password")) { if (json_get_type(child) != JSON_TYPE_STR) { return INVALID_FIELD(response_json, key); } char *password = json_str_get(child); char *password_hash = sha256_hex(password); strcpy(device_admin_password_hash, password_hash); free(password_hash); DEBUG_DEVICE("admin password set"); } else if (!strcmp(key, "normal_password")) { if (json_get_type(child) != JSON_TYPE_STR) { return INVALID_FIELD(response_json, key); } char *password = json_str_get(child); char *password_hash = sha256_hex(password); strcpy(device_normal_password_hash, password_hash); free(password_hash); DEBUG_DEVICE("normal password set"); } else if (!strcmp(key, "viewonly_password")) { if (json_get_type(child) != JSON_TYPE_STR) { return INVALID_FIELD(response_json, key); } char *password = json_str_get(child); char *password_hash = sha256_hex(password); strcpy(device_viewonly_password_hash, password_hash); free(password_hash); DEBUG_DEVICE("view-only password set"); } else if (!strcmp(key, "admin_password_hash")) { if (json_get_type(child) != JSON_TYPE_STR) { return INVALID_FIELD(response_json, key); } char *password_hash = json_str_get(child); strcpy(device_admin_password_hash, password_hash); DEBUG_DEVICE("admin password set"); } else if (!strcmp(key, "normal_password_hash")) { if (json_get_type(child) != JSON_TYPE_STR) { return INVALID_FIELD(response_json, key); } char *password_hash = json_str_get(child); strcpy(device_normal_password_hash, password_hash); DEBUG_DEVICE("normal password set"); } else if (!strcmp(key, "viewonly_password_hash")) { if (json_get_type(child) != JSON_TYPE_STR) { return INVALID_FIELD(response_json, key); } char *password_hash = json_str_get(child); strcpy(device_viewonly_password_hash, password_hash); DEBUG_DEVICE("view-only password set"); } else if (!strcmp(key, "ip_address")) { if (json_get_type(child) != JSON_TYPE_STR) { return INVALID_FIELD(response_json, key); } char *ip_address_str = json_str_get(child); ip_addr_t ip_address = {0}; if (ip_address_str[0]) { /* Manual */ uint8 bytes[4]; if (!validate_ip_address(ip_address_str, bytes)) { return INVALID_FIELD(response_json, key); } IP4_ADDR(&ip_address, bytes[0], bytes[1], bytes[2], bytes[3]); } wifi_set_ip_address(ip_address); *needs_reset = TRUE; } else if (!strcmp(key, "ip_netmask")) { if (json_get_type(child) != JSON_TYPE_INT) { return INVALID_FIELD(response_json, key); } int netmask = json_int_get(child); if (!validate_num(netmask, 0, 31, /* integer = */ TRUE, /* step = */ 0, /* choices = */ NULL)) { return INVALID_FIELD(response_json, key); } wifi_set_netmask(netmask); *needs_reset = TRUE; } else if (!strcmp(key, "ip_gateway")) { if (json_get_type(child) != JSON_TYPE_STR) { return INVALID_FIELD(response_json, key); } char *gateway_str = json_str_get(child); ip_addr_t gateway = {0}; if (gateway_str[0]) { /* Manual */ uint8 bytes[4]; if (!validate_ip_address(gateway_str, bytes)) { return INVALID_FIELD(response_json, key); } IP4_ADDR(&gateway, bytes[0], bytes[1], bytes[2], bytes[3]); } wifi_set_gateway(gateway); *needs_reset = TRUE; } else if (!strcmp(key, "ip_dns")) { if (json_get_type(child) != JSON_TYPE_STR) { return INVALID_FIELD(response_json, key); } char *dns_str = json_str_get(child); ip_addr_t dns = {0}; if (dns_str[0]) { /* Manual */ uint8 bytes[4]; if (!validate_ip_address(dns_str, bytes)) { return INVALID_FIELD(response_json, key); } IP4_ADDR(&dns, bytes[0], bytes[1], bytes[2], bytes[3]); } wifi_set_dns(dns); *needs_reset = TRUE; } else if (!strcmp(key, "wifi_ssid")) { if (json_get_type(child) != JSON_TYPE_STR) { return INVALID_FIELD(response_json, key); } char *ssid = json_str_get(child); if (!validate_wifi_ssid(ssid)) { return INVALID_FIELD(response_json, key); } wifi_set_ssid(ssid); *needs_reset = TRUE; } else if (!strcmp(key, "wifi_key")) { if (json_get_type(child) != JSON_TYPE_STR) { return INVALID_FIELD(response_json, key); } char *psk = json_str_get(child); if (!validate_wifi_key(psk)) { return INVALID_FIELD(response_json, key); } wifi_set_psk(psk); *needs_reset = TRUE; } else if (!strcmp(key, "wifi_bssid")) { if (json_get_type(child) != JSON_TYPE_STR) { return INVALID_FIELD(response_json, key); } char *bssid_str = json_str_get(child); if (bssid_str[0]) { uint8 bssid[WIFI_BSSID_LEN]; if (!validate_wifi_bssid(bssid_str, bssid)) { return INVALID_FIELD(response_json, key); } wifi_set_bssid(bssid); } else { wifi_set_bssid(NULL); } *needs_reset = TRUE; } #ifdef _SLEEP else if (!strcmp(key, "sleep_wake_interval")) { if (json_get_type(child) != JSON_TYPE_INT) { return INVALID_FIELD(response_json, key); } uint32 interval = json_int_get(child); bool valid = validate_num( interval, SLEEP_WAKE_INTERVAL_MIN, SLEEP_WAKE_INTERVAL_MAX, /* integer = */ TRUE, /* step = */ 0, /* choices = */ NULL ); if (!valid) { return INVALID_FIELD(response_json, key); } sleep_set_wake_interval(interval); *needs_sleep_reset = TRUE; } else if (!strcmp(key, "sleep_wake_duration")) { if (json_get_type(child) != JSON_TYPE_INT) { return INVALID_FIELD(response_json, key); } uint32 duration = json_int_get(child); bool valid = validate_num( duration, SLEEP_WAKE_DURATION_MIN, SLEEP_WAKE_DURATION_MAX, /* integer = */ TRUE, /* step = */ 0, /* choices = */ NULL ); if (!valid) { return INVALID_FIELD(response_json, key); } sleep_set_wake_duration(duration); *needs_sleep_reset = TRUE; } #endif #ifdef _OTA else if (!strcmp(key, "firmware_auto_update")) { if (json_get_type(child) != JSON_TYPE_BOOL) { return INVALID_FIELD(response_json, key); } if (json_bool_get(child)) { device_flags |= DEVICE_FLAG_OTA_AUTO_UPDATE; DEBUG_OTA("firmware auto update enabled"); } else { device_flags &= ~DEVICE_FLAG_OTA_AUTO_UPDATE; DEBUG_OTA("firmware auto update disabled"); } } else if (!strcmp(key, "firmware_beta_enabled")) { if (json_get_type(child) != JSON_TYPE_BOOL) { return INVALID_FIELD(response_json, key); } if (json_bool_get(child)) { device_flags |= DEVICE_FLAG_OTA_BETA_ENABLED; DEBUG_OTA("firmware beta enabled"); } else { device_flags &= ~DEVICE_FLAG_OTA_BETA_ENABLED; DEBUG_OTA("firmware beta disabled"); } } #endif else if (!strcmp(key, "config_name")) { if (json_get_type(child) != JSON_TYPE_STR) { return INVALID_FIELD(response_json, key); } char *config_name = json_str_get(child); strncpy(device_config_name, config_name, API_MAX_DEVICE_CONFIG_NAME_LEN); device_config_name[API_MAX_DEVICE_CONFIG_NAME_LEN - 1] = 0; *config_name_changed = TRUE; DEBUG_DEVICE("config name set to \"%s\"", device_config_name); device_provisioning_version = 0; /* Also reset the provisioning version */ } else if (!strcmp(key, "version") || !strcmp(key, "api_version") || !strcmp(key, "vendor") || #ifdef _OTA !strcmp(key, "firmware") || #endif #ifdef _BATTERY !strcmp(key, "battery_level") || !strcmp(key, "battery_voltage") || #endif !strcmp(key, "listen") || !strcmp(key, "uptime") || !strcmp(key, "mem_usage") || !strcmp(key, "flash_size") || !strcmp(key, "debug") || !strcmp(key, "chip_id") || !strcmp(key, "flash_id")) { if (!ignore_unknown) { return ATTR_NOT_MODIFIABLE(response_json, key); } } else { if (!ignore_unknown) { return NO_SUCH_ATTR(response_json, key); } } } *code = 204; return json_obj_new(); } json_t *port_attrdefs_to_json(port_t *port, json_refs_ctx_t *json_refs_ctx) { json_t *json = json_obj_new(); json_t *attrdef_json; if (port->attrdefs) { int8 found_port_index = -1; if (json_refs_ctx->type == JSON_REFS_TYPE_PORTS_LIST) { /* Look through previous ports for ports having exact same attrdefs */ port_t *p = NULL; uint8 i = 0; for (i = 0; i < all_ports_count && p != port; i++) { p = all_ports[i]; if ((p->attrdefs == port->attrdefs) && (IS_PORT_WRITABLE(p) == IS_PORT_WRITABLE(port)) && (IS_PORT_VIRTUAL(p) == IS_PORT_VIRTUAL(port)) && (p->type == port->type)) { found_port_index = i; break; } } } if (found_port_index >= 0) { /* Found a port with exact same attrdefs */ json_t *ref; ref = make_json_ref("#/%d/definitions", found_port_index); #if defined(_DEBUG) && defined(_DEBUG_API) char *ref_str = json_str_get(json_obj_value_at(ref, 0)); DEBUG_API("replacing \"%s.definitions\" with $ref \"%s\"", port->id, ref_str); #endif json_free(json); return ref; } attrdef_t *a, **attrdefs = port->attrdefs; while ((a = *attrdefs++)) { char **choices = a->choices; char *found_attrdef_name = NULL; int8 found_port_index = -1; if (choices) { /* Look through previous ports (and current port as well) for attrdefs with same choices */ lookup_port_attrdef_choices(choices, port, a, &found_port_index, &found_attrdef_name, json_refs_ctx); if (found_attrdef_name) { /* Will be replaced by $ref */ choices = NULL; } } attrdef_json = attrdef_to_json( a->display_name ? a->display_name : "", a->description ? a->description : "", a->unit, a->type, IS_ATTRDEF_MODIFIABLE(a), a->min, a->max, IS_ATTRDEF_INTEGER(a), a->step, choices, IS_ATTRDEF_RECONNECT(a) ); /* If similar choices found, replace with $ref */ if (found_attrdef_name) { json_t *ref = NULL; switch (json_refs_ctx->type) { case JSON_REFS_TYPE_PORTS_LIST: ref = make_json_ref("#/%d/definitions/%s/choices", found_port_index, found_attrdef_name); break; case JSON_REFS_TYPE_PORT: ref = make_json_ref("#/definitions/%s/choices", found_attrdef_name); break; case JSON_REFS_TYPE_LISTEN_EVENTS_LIST: ref = make_json_ref( "#/%d/params/definitions/%s/choices", json_refs_ctx->index, found_attrdef_name ); break; case JSON_REFS_TYPE_WEBHOOKS_EVENT: ref = make_json_ref("#/params/definitions/%s/choices", found_attrdef_name); break; } #if defined(_DEBUG) && defined(_DEBUG_API) char *ref_str = json_str_get(json_obj_value_at(ref, 0)); DEBUG_API( "replacing \"%s.definitions.%s.choices\" with $ref \"%s\"", port->id, found_attrdef_name, ref_str ); #endif json_obj_append(attrdef_json, "choices", ref); } json_stringify(attrdef_json); json_obj_append(json, a->name, attrdef_json); } } if (!IS_PORT_VIRTUAL(port) && port->min_sampling_interval < port->max_sampling_interval) { // FIXME: JSON refs are wrong when sampling_interval fields (particularly min/max) differ /* sampling_interval attrdef */ // if (json_refs_ctx->type == JSON_REFS_TYPE_PORTS_LIST && json_refs_ctx->sampling_interval_port_index >= 0) { // attrdef_json = make_json_ref( // "#/%d/definitions/sampling_interval", // json_refs_ctx->sampling_interval_port_index // ); //#if defined(_DEBUG) && defined(_DEBUG_API) // char *ref_str = json_str_get(json_obj_value_at(attrdef_json, 0)); // DEBUG_API("replacing \"%s.definitions.sampling_interval\" with $ref \"%s\"", port->id, ref_str); //#endif // } // else { attrdef_json = attrdef_to_json( "Sampling Interval", "Indicates how often the port value will be read.", "ms", ATTR_TYPE_NUMBER, /* modifiable = */ TRUE, port->min_sampling_interval, port->max_sampling_interval, /* integer = */ TRUE , /* step = */ 0, /* choices = */ NULL, /* reconnect = */ FALSE ); // if (json_refs_ctx->type == JSON_REFS_TYPE_PORTS_LIST) { // json_refs_ctx->sampling_interval_port_index = json_refs_ctx->index; // } // } json_obj_append(json, "sampling_interval", attrdef_json); } json_stringify(json); return json; } json_t *device_attrdefs_to_json(void) { json_t *json = json_obj_new(); json_t *attrdef_json; #ifdef _SLEEP attrdef_json = attrdef_to_json( "Sleep Wake Interval", "Controls how often the device will wake from sleep (0 disables sleep mode).", /* unit = */ "min", ATTR_TYPE_NUMBER, /* modifiable = */ TRUE, /* min = */ SLEEP_WAKE_INTERVAL_MIN, /* max = */ SLEEP_WAKE_INTERVAL_MAX, /* integer = */ TRUE, /* step = */ 0, /* choices = */ NULL, /* reconnect = */ FALSE ); json_obj_append(json, "sleep_wake_interval", attrdef_json); attrdef_json = attrdef_to_json( "Sleep Wake Duration", "Controls for how long the device stays awake (0 disables sleep mode).", /* unit = */ "s", ATTR_TYPE_NUMBER, /* modifiable = */ TRUE, /* min = */ SLEEP_WAKE_DURATION_MIN, /* max = */ SLEEP_WAKE_DURATION_MAX, /* integer = */ TRUE, /* step = */ 0, /* choices = */ NULL, /* reconnect = */ FALSE ); json_obj_append(json, "sleep_wake_duration", attrdef_json); #endif #ifdef _OTA attrdef_json = attrdef_to_json( "Firmware Auto-update", "Enables automatic firmware update when detecting a newer version.", /* unit = */ NULL, ATTR_TYPE_BOOLEAN, /* modifiable = */ TRUE, /* min = */ UNDEFINED, /* max = */ UNDEFINED, /* integer = */ FALSE, /* step = */ 0, /* choices = */ NULL, /* reconnect = */ FALSE ); json_obj_append(json, "firmware_auto_update", attrdef_json); attrdef_json = attrdef_to_json( "Firmware Beta Versions", "Enables access to beta firmware releases. Leave this disabled unless you know what you're doing.", /* unit = */ NULL, ATTR_TYPE_BOOLEAN, /* modifiable = */ TRUE, /* min = */ UNDEFINED, /* max = */ UNDEFINED, /* integer = */ FALSE, /* step = */ 0, /* choices = */ NULL, /* reconnect = */ FALSE ); json_obj_append(json, "firmware_beta_enabled", attrdef_json); #endif #ifdef _BATTERY if (battery_enabled()) { attrdef_json = attrdef_to_json( "Battery Voltage", "The battery voltage.", "mV", ATTR_TYPE_NUMBER, /* modifiable = */ FALSE, /* min = */ UNDEFINED, /* max = */ UNDEFINED, /* integer = */ FALSE, /* step = */ 0, /* choices = */ NULL, /* reconnect = */ FALSE ); json_obj_append(json, "battery_voltage", attrdef_json); } #endif attrdef_json = attrdef_to_json( "Flash Size", "Total flash memory size.", "kB", ATTR_TYPE_NUMBER, /* modifiable = */ FALSE, /* min = */ UNDEFINED, /* max = */ UNDEFINED, /* integer = */ TRUE, /* step = */ 0, /* choices = */ NULL, /* reconnect = */ FALSE ); json_obj_append(json, "flash_size", attrdef_json); attrdef_json = attrdef_to_json( "Flash ID", "Device flash model identifier.", /* unit = */ NULL, ATTR_TYPE_STRING, /* modifiable = */ FALSE, /* min = */ UNDEFINED, /* max = */ UNDEFINED, /* integer = */ FALSE, /* step = */ 0, /* choices = */ NULL, /* reconnect = */ FALSE ); json_obj_append(json, "flash_id", attrdef_json); attrdef_json = attrdef_to_json( "Chip ID", "Device chip identifier.", /* unit = */ NULL, ATTR_TYPE_STRING, /* modifiable = */ FALSE, /* min = */ UNDEFINED, /* max = */ UNDEFINED, /* integer = */ FALSE, /* step = */ 0, /* choices = */ NULL, /* reconnect = */ FALSE ); json_obj_append(json, "chip_id", attrdef_json); #ifdef _DEBUG attrdef_json = attrdef_to_json( "Debug", "Indicates that debugging was enabled when the firmware was built.", /* unit = */ NULL, ATTR_TYPE_BOOLEAN, /* modifiable = */ FALSE, /* min = */ UNDEFINED, /* max = */ UNDEFINED, /* integer = */ FALSE, /* step = */ 0, /* choices = */ NULL, /* reconnect = */ FALSE ); json_obj_append(json, "debug", attrdef_json); #endif return json; } void on_sequence_timer(void *arg) { port_t *port = arg; if (port->sequence_pos < port->sequence_len) { port_write_value(port, port->sequence_values[port->sequence_pos], CHANGE_REASON_SEQUENCE); DEBUG_PORT(port, "sequence delay of %d ms", port->sequence_delays[port->sequence_pos]); os_timer_arm(port->sequence_timer, port->sequence_delays[port->sequence_pos], /* repeat = */ FALSE); port->sequence_pos++; } else { /* Sequence ended */ if (port->sequence_repeat > 1 || port->sequence_repeat == 0) { /* Must repeat */ if (port->sequence_repeat) { port->sequence_repeat--; } DEBUG_PORT(port, "repeating sequence (%d remaining iterations)", port->sequence_repeat); port->sequence_pos = 0; on_sequence_timer(arg); } else { /* Single iteration or repeat ended */ port_sequence_cancel(port); DEBUG_PORT(port, "sequence done"); if (IS_PORT_PERSISTED(port)) { config_mark_for_saving(); } } } } #ifdef _OTA void on_ota_latest(char *version, char *date, char *url) { if (api_conn) { json_t *response_json = json_obj_new(); json_obj_append(response_json, "version", json_str_new(FW_VERSION)); json_obj_append(response_json, "status", json_str_new(ota_states_str[OTA_STATE_IDLE])); if (version) { json_obj_append(response_json, "latest_version", json_str_new(version)); json_obj_append(response_json, "latest_date", json_str_new(date)); json_obj_append(response_json, "latest_url", json_str_new(url)); } respond_json(api_conn, 200, response_json); api_conn_reset(); } free(version); free(date); free(url); } void on_ota_perform(int code) { if (!api_conn) { return; } if (code >= 200 && code < 300) { json_t *response_json = json_obj_new(); respond_json(api_conn, 204, response_json); sessions_respond_all(); } else { /* Error */ json_t *response_json = json_obj_new(); json_obj_append(response_json, "error", json_str_new("no-such-version")); respond_json(api_conn, 404, response_json); } api_conn_reset(); } #endif /* _OTA */ void on_wifi_scan(wifi_scan_result_t *results, int len) { DEBUG_API("got wifi scan results"); if (!api_conn) { return; /* Such is life */ } json_t *response_json = json_list_new(); json_t *result_json; int i; char bssid[18]; char *auth; for (i = 0; i < len; i++) { result_json = json_obj_new(); json_obj_append(result_json, "ssid", json_str_new(results[i].ssid)); snprintf( bssid, sizeof(bssid), "%02X:%02X:%02X:%02X:%02X:%02X", results[i].bssid[0], results[i].bssid[1], results[i].bssid[2], results[i].bssid[3], results[i].bssid[4], results[i].bssid[5] ); json_obj_append(result_json, "bssid", json_str_new(bssid)); json_obj_append(result_json, "channel", json_int_new(results[i].channel)); json_obj_append(result_json, "rssi", json_int_new(results[i].rssi)); switch (results[i].auth_mode) { case AUTH_OPEN: auth = "OPEN"; break; case AUTH_WEP: auth = "WEP"; break; case AUTH_WPA_PSK: auth = "WPA_PSK"; break; case AUTH_WPA2_PSK: auth = "WPA2_PSK"; break; case AUTH_WPA_WPA2_PSK: auth = "WPA_WPA2_PSK"; break; default: auth = "unknown"; } json_obj_append(result_json, "auth_mode", json_str_new(auth)); json_list_append(response_json, result_json); } free(results); respond_json(api_conn, 200, response_json); api_conn_reset(); }
32.98746
120
0.573561
2b59803f459b91a1c8a10ad8075c601f0ba04fa8
809
h
C
SerialPrograms/Source/PokemonLA/Programs/PokemonLA_BraviaryHeightGlitch.h
Gin890/Arduino-Source
9047ff584010d8ddc3558068874f16fb3c7bb46d
[ "MIT" ]
1
2022-03-29T18:51:49.000Z
2022-03-29T18:51:49.000Z
SerialPrograms/Source/PokemonLA/Programs/PokemonLA_BraviaryHeightGlitch.h
Gin890/Arduino-Source
9047ff584010d8ddc3558068874f16fb3c7bb46d
[ "MIT" ]
null
null
null
SerialPrograms/Source/PokemonLA/Programs/PokemonLA_BraviaryHeightGlitch.h
Gin890/Arduino-Source
9047ff584010d8ddc3558068874f16fb3c7bb46d
[ "MIT" ]
null
null
null
/* Braviary Height Glitch * * From: https://github.com/PokemonAutomation/Arduino-Source * */ #ifndef PokemonAutomation_PokemonLA_BraviaryHeightGlitch_H #define PokemonAutomation_PokemonLA_BraviaryHeightGlitch_H #include "NintendoSwitch/Framework/NintendoSwitch_SingleSwitchProgram.h" namespace PokemonAutomation{ namespace NintendoSwitch{ namespace PokemonLA{ class BraviaryHeightGlitch_Descriptor : public RunnableSwitchProgramDescriptor{ public: BraviaryHeightGlitch_Descriptor(); }; class BraviaryHeightGlitch : public SingleSwitchProgramInstance{ public: BraviaryHeightGlitch(const BraviaryHeightGlitch_Descriptor& descriptor); virtual void program(SingleSwitchProgramEnvironment& env, BotBaseContext& context) override; }; } } } #endif
21.289474
97
0.787392
2b5af778c80c16445245d8abd0fcc27b45e41d72
3,961
h
C
mysql-connector/driver/mysql_connection_options.h
Fortunato28/poke_bat_public
43ca0e253e5c3aef2b1945d20236d88695c868f4
[ "MIT" ]
1
2020-06-20T07:35:25.000Z
2020-06-20T07:35:25.000Z
mysql-connector/driver/mysql_connection_options.h
Fortunato28/poke_bat_public
43ca0e253e5c3aef2b1945d20236d88695c868f4
[ "MIT" ]
null
null
null
mysql-connector/driver/mysql_connection_options.h
Fortunato28/poke_bat_public
43ca0e253e5c3aef2b1945d20236d88695c868f4
[ "MIT" ]
null
null
null
/* * Copyright (c) 2009, 2018, Oracle and/or its affiliates. All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License, version 2.0, as * published by the Free Software Foundation. * * This program is also distributed with certain software (including * but not limited to OpenSSL) that is licensed under separate terms, * as designated in a particular file or component or in included license * documentation. The authors of MySQL hereby grant you an * additional permission to link the program and your derivative works * with the separately licensed software that they have included with * MySQL. * * Without limiting anything contained in the foregoing, this file, * which is part of MySQL Connector/C++, is also subject to the * Universal FOSS Exception, version 1.0, a copy of which can be found at * http://oss.oracle.com/licenses/universal-foss-exception. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License, version 2.0, for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include <cppconn/version_info.h> #ifndef _MYSQL_CONNECTION_OPTIONS_H_ #define _MYSQL_CONNECTION_OPTIONS_H_ namespace sql { namespace mysql { enum MySQL_Connection_Options { #if MYCPPCONN_STATIC_MYSQL_VERSION_ID >= 80000 MYSQL_OPT_CONNECT_TIMEOUT, MYSQL_OPT_COMPRESS, MYSQL_OPT_NAMED_PIPE, MYSQL_INIT_COMMAND, MYSQL_READ_DEFAULT_FILE, MYSQL_READ_DEFAULT_GROUP, MYSQL_SET_CHARSET_DIR, MYSQL_SET_CHARSET_NAME, MYSQL_OPT_LOCAL_INFILE, MYSQL_OPT_PROTOCOL, MYSQL_SHARED_MEMORY_BASE_NAME, MYSQL_OPT_READ_TIMEOUT, MYSQL_OPT_WRITE_TIMEOUT, MYSQL_OPT_USE_RESULT, MYSQL_REPORT_DATA_TRUNCATION, MYSQL_OPT_RECONNECT, MYSQL_PLUGIN_DIR, MYSQL_DEFAULT_AUTH, MYSQL_OPT_BIND, MYSQL_OPT_SSL_KEY, MYSQL_OPT_SSL_CERT, MYSQL_OPT_SSL_CA, MYSQL_OPT_SSL_CAPATH, MYSQL_OPT_SSL_CIPHER, MYSQL_OPT_SSL_CRL, MYSQL_OPT_SSL_CRLPATH, MYSQL_OPT_CONNECT_ATTR_RESET, MYSQL_OPT_CONNECT_ATTR_ADD, MYSQL_OPT_CONNECT_ATTR_DELETE, MYSQL_SERVER_PUBLIC_KEY, MYSQL_ENABLE_CLEARTEXT_PLUGIN, MYSQL_OPT_CAN_HANDLE_EXPIRED_PASSWORDS, MYSQL_OPT_MAX_ALLOWED_PACKET, MYSQL_OPT_NET_BUFFER_LENGTH, MYSQL_OPT_TLS_VERSION, MYSQL_OPT_SSL_MODE, MYSQL_OPT_RETRY_COUNT, MYSQL_OPT_GET_SERVER_PUBLIC_KEY, MYSQL_OPT_OPTIONAL_RESULTSET_METADATA #else MYSQL_OPT_CONNECT_TIMEOUT, MYSQL_OPT_COMPRESS, MYSQL_OPT_NAMED_PIPE, MYSQL_INIT_COMMAND, MYSQL_READ_DEFAULT_FILE, MYSQL_READ_DEFAULT_GROUP, MYSQL_SET_CHARSET_DIR, MYSQL_SET_CHARSET_NAME, MYSQL_OPT_LOCAL_INFILE, MYSQL_OPT_PROTOCOL, MYSQL_SHARED_MEMORY_BASE_NAME, MYSQL_OPT_READ_TIMEOUT, MYSQL_OPT_WRITE_TIMEOUT, MYSQL_OPT_USE_RESULT, MYSQL_OPT_USE_REMOTE_CONNECTION, MYSQL_OPT_USE_EMBEDDED_CONNECTION, MYSQL_OPT_GUESS_CONNECTION, MYSQL_SET_CLIENT_IP, MYSQL_SECURE_AUTH, MYSQL_REPORT_DATA_TRUNCATION, MYSQL_OPT_RECONNECT, MYSQL_OPT_SSL_VERIFY_SERVER_CERT, MYSQL_PLUGIN_DIR, MYSQL_DEFAULT_AUTH, MYSQL_OPT_BIND, MYSQL_OPT_SSL_KEY, MYSQL_OPT_SSL_CERT, MYSQL_OPT_SSL_CA, MYSQL_OPT_SSL_CAPATH, MYSQL_OPT_SSL_CIPHER, MYSQL_OPT_SSL_CRL, MYSQL_OPT_SSL_CRLPATH, MYSQL_OPT_CONNECT_ATTR_RESET, MYSQL_OPT_CONNECT_ATTR_ADD, MYSQL_OPT_CONNECT_ATTR_DELETE, MYSQL_SERVER_PUBLIC_KEY, MYSQL_ENABLE_CLEARTEXT_PLUGIN, MYSQL_OPT_CAN_HANDLE_EXPIRED_PASSWORDS, MYSQL_OPT_SSL_ENFORCE, #if MYCPPCONN_STATIC_MYSQL_VERSION_ID >= 50700 MYSQL_OPT_MAX_ALLOWED_PACKET, MYSQL_OPT_NET_BUFFER_LENGTH, MYSQL_OPT_TLS_VERSION, MYSQL_OPT_SSL_MODE #endif //MYCPPCONN_STATIC_MYSQL_VERSION_ID >= 50700 #endif //MYCPPCONN_STATIC_MYSQL_VERSION_ID >= 80000 }; } } #endif
39.61
80
0.828326
2b5cfc58d78d12f15bca20f0759ad83f9878f4d5
4,510
c
C
kernel/2.6.32/drivers/staging/iio/Documentation/lis3l02dqbuffersimple.c
haizhenhan/Kepler
d15293a7ef69f44b1fe61d5cdeceb0bd73f0d315
[ "BSD-3-Clause" ]
55
2015-01-20T00:09:45.000Z
2021-08-19T05:40:27.000Z
linux/linux-2.6.32/drivers/staging/iio/Documentation/lis3l02dqbuffersimple.c
jwegan/TCP-RST-Guard
8734350ef09b0cd79e72797ffa009d75441886bb
[ "MIT" ]
1
2021-08-07T07:14:45.000Z
2021-08-07T08:24:23.000Z
linux/linux-2.6.32/drivers/staging/iio/Documentation/lis3l02dqbuffersimple.c
jwegan/TCP-RST-Guard
8734350ef09b0cd79e72797ffa009d75441886bb
[ "MIT" ]
36
2015-02-13T00:58:22.000Z
2021-08-19T08:08:07.000Z
/* Industrialio test ring buffer with a lis3l02dq acceleromter * * Copyright (c) 2008 Jonathan Cameron * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 as published by * the Free Software Foundation. * * Assumes suitable udev rules are used to create the dev nodes as named here. */ #include <dirent.h> #include <fcntl.h> #include <stdio.h> #include <errno.h> #include <stdint.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/dir.h> #include <linux/types.h> #include <dirent.h> #include "iio_util.h" static const char *ring_access = "/dev/iio/lis3l02dq_ring_access"; static const char *ring_event = "/dev/iio/lis3l02dq_ring_event"; static const char *device_name = "lis3l02dq"; static const char *trigger_name = "lis3l02dq-dev0"; static int NumVals = 3; static int scan_ts = 1; static int RingLength = 128; /* * Could get this from ring bps, but only after starting the ring * which is a bit late for it to be useful */ int size_from_scanmode(int numVals, int timestamp) { if (numVals && timestamp) return 16; else if (timestamp) return 8; else return numVals*2; } int main(int argc, char **argv) { int i, j, k, toread; FILE *fp_ev; int fp; char *data; size_t read_size; struct iio_event_data dat; char *BaseDirectoryName, *TriggerDirectoryName, *RingBufferDirectoryName; BaseDirectoryName = find_type_by_name(device_name, "device"); if (BaseDirectoryName == NULL) { printf("Failed to find the %s \n", device_name); return -1; } TriggerDirectoryName = find_type_by_name(trigger_name, "trigger"); if (TriggerDirectoryName == NULL) { printf("Failed to find the %s\n", trigger_name); return -1; } RingBufferDirectoryName = find_ring_subelement(BaseDirectoryName, "ring_buffer"); if (RingBufferDirectoryName == NULL) { printf("Failed to find ring buffer\n"); return -1; } if (write_sysfs_string_and_verify("trigger/current_trigger", BaseDirectoryName, (char *)trigger_name) < 0) { printf("Failed to write current_trigger file \n"); return -1; } /* Setup ring buffer parameters */ if (write_sysfs_int("length", RingBufferDirectoryName, RingLength) < 0) { printf("Failed to open the ring buffer length file \n"); return -1; } /* Enable the ring buffer */ if (write_sysfs_int("ring_enable", RingBufferDirectoryName, 1) < 0) { printf("Failed to open the ring buffer control file \n"); return -1; }; data = malloc(size_from_scanmode(NumVals, scan_ts)*RingLength); if (!data) { printf("Could not allocate space for usespace data store\n"); return -1; } /* Attempt to open non blocking the access dev */ fp = open(ring_access, O_RDONLY | O_NONBLOCK); if (fp == -1) { /*If it isn't there make the node */ printf("Failed to open %s\n", ring_access); return -1; } /* Attempt to open the event access dev (blocking this time) */ fp_ev = fopen(ring_event, "rb"); if (fp_ev == NULL) { printf("Failed to open %s\n", ring_event); return -1; } /* Wait for events 10 times */ for (j = 0; j < 10; j++) { read_size = fread(&dat, 1, sizeof(struct iio_event_data), fp_ev); switch (dat.id) { case IIO_EVENT_CODE_RING_100_FULL: toread = RingLength; break; case IIO_EVENT_CODE_RING_75_FULL: toread = RingLength*3/4; break; case IIO_EVENT_CODE_RING_50_FULL: toread = RingLength/2; break; default: printf("Unexpecteded event code\n"); continue; } read_size = read(fp, data, toread*size_from_scanmode(NumVals, scan_ts)); if (read_size == -EAGAIN) { printf("nothing available \n"); continue; } for (i = 0; i < read_size/size_from_scanmode(NumVals, scan_ts); i++) { for (k = 0; k < NumVals; k++) { __s16 val = *(__s16 *)(&data[i*size_from_scanmode(NumVals, scan_ts) + (k)*2]); printf("%05d ", val); } printf(" %lld\n", *(__s64 *)(&data[(i+1)*size_from_scanmode(NumVals, scan_ts) - sizeof(__s64)])); } } /* Stop the ring buffer */ if (write_sysfs_int("ring_enable", RingBufferDirectoryName, 0) < 0) { printf("Failed to open the ring buffer control file \n"); return -1; }; /* Disconnect from the trigger - writing something that doesn't exist.*/ write_sysfs_string_and_verify("trigger/current_trigger", BaseDirectoryName, "NULL"); free(BaseDirectoryName); free(TriggerDirectoryName); free(RingBufferDirectoryName); free(data); return 0; }
26.22093
78
0.682483
2b5ebcbe069b3ab6734656cd52ecb67850b659bc
1,018
h
C
src/maths/MatrixOperations.h
matherno/MathernoGL
9e1dba3fae38feda9e8ca259246dff500491d7af
[ "BSD-3-Clause" ]
1
2019-10-11T12:21:51.000Z
2019-10-11T12:21:51.000Z
src/maths/MatrixOperations.h
matherno/MathernoGL
9e1dba3fae38feda9e8ca259246dff500491d7af
[ "BSD-3-Clause" ]
null
null
null
src/maths/MatrixOperations.h
matherno/MathernoGL
9e1dba3fae38feda9e8ca259246dff500491d7af
[ "BSD-3-Clause" ]
null
null
null
#pragma once #include <cmath> #include <maths/Vector2D.h> #include <maths/Vector3D.h> #include <maths/Vector4D.h> #include <maths/Matrix4.h> #include <maths/VectorOperations.h> namespace mathernogl { Matrix4 matrixIdentity(); Matrix4 matrixTranslate(const Vector3D& translation); Matrix4 matrixTranslate(double x, double y, double z); Matrix4 matrixRotate(const Vector3D& rotationAxis, double rotationAngle); Matrix4 matrixRotate(double x, double y, double z, double rotationAngle); Matrix4 matrixRotateBetween(const Vector3D& from, const Vector3D& to); Matrix4 matrixPitch(double angle); Matrix4 matrixYaw(double angle); Matrix4 matrixRoll(double angle); Matrix4 matrixScale(const Vector3D& scaling); Matrix4 matrixScale(double x, double y, double z); Matrix4 matrixScale(double scaling); Matrix4 matrixPerspective(double fov, double aspectRatio, double zNearPLane, double zFarPlane); Matrix4 matrixOrthogonal(double fov, double aspectRatio, double zFarPlane); Matrix4 matrixInverse(const Matrix4& matrix); }
30.848485
95
0.803536
2b607c03baf94a053d7fb174fd0003ebb517f3da
1,003
h
C
doc/external/42093/Test/stm32f4_ucgui-1/Project/usrlcd.h
josnelihurt/fpga-stuff
92444741469218c7a1c5052fe6ea99f053cbac4f
[ "Unlicense" ]
2
2019-07-02T14:05:47.000Z
2022-02-26T23:15:56.000Z
doc/external/42093/Test/stm32f4_ucgui-1/Project/usrlcd.h
josnelihurt/fpga-stuff
92444741469218c7a1c5052fe6ea99f053cbac4f
[ "Unlicense" ]
null
null
null
doc/external/42093/Test/stm32f4_ucgui-1/Project/usrlcd.h
josnelihurt/fpga-stuff
92444741469218c7a1c5052fe6ea99f053cbac4f
[ "Unlicense" ]
1
2020-12-14T12:14:35.000Z
2020-12-14T12:14:35.000Z
#include "stm32f4_discovery.h" #define LCD_RS_1 GPIO_SetBits(GPIOA, GPIO_Pin_5) #define LCD_RS_0 GPIO_ResetBits(GPIOA, GPIO_Pin_5) #define LCD_WR_1 GPIO_SetBits(GPIOA, GPIO_Pin_2) #define LCD_WR_0 GPIO_ResetBits(GPIOA, GPIO_Pin_2) #define LCD_RD_1 GPIO_SetBits(GPIOA, GPIO_Pin_3) #define LCD_RD_0 GPIO_ResetBits(GPIOA, GPIO_Pin_3) #define LCD_CS_1 GPIO_SetBits(GPIOA, GPIO_Pin_0) #define LCD_CS_0 GPIO_ResetBits(GPIOA, GPIO_Pin_0) #define LCD_RST_1 GPIO_SetBits(GPIOA, GPIO_Pin_1) #define LCD_RST_0 GPIO_ResetBits(GPIOA, GPIO_Pin_1) void Delay(__IO uint32_t nCount); void Lcd_Init(void); void Pant(uint16_t data); void Address_set(unsigned int x1,unsigned int y1,unsigned int x2,unsigned int y2); void Lcd_Write_Data(uint16_t da); void Lcd_Write_Datakk(uint16_t data); void LCD_SetPixel(uint16_t x,uint16_t y,uint16_t color); uint16_t LCD_ReadPixel(uint16_t x,uint16_t y); void Lcd_Write_Com(uint16_t data); void Lcd_Write_Com_Data(uint16_t com,uint16_t val); void ioinit(void);
41.791667
83
0.807577
2b61f20548431091b59b82d10899ddf345b93522
4,402
c
C
src/netint.c
rafat/nnet
96498084971fb3923b8a94986d00c8fbd711bfca
[ "BSD-3-Clause" ]
1
2021-11-11T21:57:35.000Z
2021-11-11T21:57:35.000Z
src/netint.c
rafat/nnet
96498084971fb3923b8a94986d00c8fbd711bfca
[ "BSD-3-Clause" ]
null
null
null
src/netint.c
rafat/nnet
96498084971fb3923b8a94986d00c8fbd711bfca
[ "BSD-3-Clause" ]
null
null
null
#include "netint.h" void logsig(float *x, float N, float *y) { int i; for (i = 0; i < N; ++i) { y[i] = (1.0 / (1.0 + exp(-x[i]))); if (y[i] != y[i]) { y[i] = signx(x[i]) * 0.5 + 0.5; } } } void tansig(float *x, float N, float *y) { int i; float a, b; for (i = 0; i < N; ++i) { //y[i] = (1.0 - exp(-2 * x[i])) / (1.0 + exp(-2 * x[i])); //y[i] = -1.0 + 2.0 / (1.0 + exp(-2 * x[i])); a = exp(x[i]); b = exp(-x[i]); y[i] = (a-b) / (a+b); if (y[i] != y[i]) { y[i] = signx(x[i]); } // y[i] = tanh(x[i]); } } void hardlim(float *x, float N, float *y) { int i; for (i = 0; i < N; ++i) { if (x[i] <= 0.0) { y[i] = 0.0; } else { y[i] = 1.0; } } } void purelin(float *x, float N, float *y) { int i; for (i = 0; i < N; ++i) { y[i] = x[i]; } } //Clip float clip_value(float x, float lo, float hi) { float clip; clip = x; if (x < lo) { clip = lo; } if (x > hi) { clip = hi; } return clip; } // Derivatives float logsig_der(float value) { float temp2,df; temp2 = clip_value(value,0.01, 0.99); df = temp2 * (1.0 - temp2); return df; } float tansig_der(float value) { float temp2, df; temp2 = clip_value(value, -0.98, 0.98); df = (1.0 - temp2 * temp2); return df; } int intmax(int* x, int N) { int m, i; m = -INT_MAX; for (i = 0; i < N; ++i) { if (x[i] > m) { m = x[i]; } } return m; } float mean(float* vec, int N) { int i; float m; m = 0.0; for (i = 0; i < N; ++i) { m += vec[i]; } m = m / N; return m; } float std(float* vec, int N) { float v, temp, m; int i; v = 0.0; m = mean(vec, N); for (i = 0; i < N; ++i) { temp = vec[i] - m; v += temp*temp; } v = v / N; v = sqrt(v); return v; } float dmax(float* x, int N) { int i; float m; m = -FLT_MAX; for (i = 0; i < N; ++i) { if (x[i] > m) { m = x[i]; } } return m; } float dmin(float* x, int N) { int i; float m; m = FLT_MAX; for (i = 0; i < N; ++i) { if (x[i] < m) { m = x[i]; } } return m; } float neuron_oup(float *inp, int N, float *weights, float bias) { float a, tmp; int i; tmp = bias; for (i = 0; i < N; ++i) { tmp += inp[i] * weights[i]; } logsig(&tmp, 1, &a); return a; } void neuronlayer_logsig_oup(float *inp, int N, int S, float *weights, float *oup) { int i, j, itr, N1; float* tmp; tmp = (float*)malloc(sizeof(float)* S); /* N - Number of Inputs going into each Neuron in the Layer S - Number of Neutrons in the Layer weights - (S X N) Each row contains N weights corresponding to N inputs going into the Neuron where i =0,..,S-1 and j = 0,.,.,N-1 inp - (N X 1) Inputs going into the layer of neutron */ N1 = N + 1; for (j = 0; j < S; ++j) { itr = j * N1; tmp[j] = weights[itr]; for (i = 1; i < N1; ++i) { tmp[j] += inp[i - 1] * weights[itr + i]; } } logsig(tmp, S, oup); free(tmp); } void neuronlayer_tansig_oup(float *inp, int N, int S, float *weights, float *oup) { int i, j, itr, N1; float* tmp; tmp = (float*)malloc(sizeof(float)* S); /* N - Number of Inputs going into each Neuron in the Layer S - Number of Neutrons in the Layer weights - (S X N) Each row contains N weights corresponding to N inputs going into the Neuron where i =0,..,S-1 and j = 0,.,.,N-1 inp - (N X 1) Inputs going into the layer of neutron */ N1 = N + 1; for (j = 0; j < S; ++j) { itr = j * N1; tmp[j] = weights[itr]; for (i = 1; i < N1; ++i) { tmp[j] += inp[i - 1] * weights[itr + i]; } } tansig(tmp, S, oup); free(tmp); } void neuronlayer_purelin_oup(float *inp, int N, int S, float *weights, float *oup) { int i, j, itr, N1; float* tmp; tmp = (float*)malloc(sizeof(float)* S); /* N - Number of Inputs going into each Neuron in the Layer S - Number of Neutrons in the Layer weights - (S X N) Each row contains N weights corresponding to N inputs going into the Neuron where i =0,..,S-1 and j = 0,.,.,N-1 inp - (N X 1) Inputs going into the layer of neutron */ N1 = N + 1; for (j = 0; j < S; ++j) { itr = j * N1; tmp[j] = weights[itr]; for (i = 1; i < N1; ++i) { tmp[j] += inp[i - 1] * weights[itr + i]; } } purelin(tmp, S, oup); free(tmp); }
17.399209
95
0.490459
2b62e2d59cff30a6c8fc2aef7a6a64da4a7d5b2b
2,469
h
C
src/prod/src/Management/CentralSecretService/SecretManager.SecretsAsyncOperation.h
gridgentoo/ServiceFabricAzure
c3e7a07617e852322d73e6cc9819d266146866a4
[ "MIT" ]
2,542
2018-03-14T21:56:12.000Z
2019-05-06T01:18:20.000Z
src/prod/src/Management/CentralSecretService/SecretManager.SecretsAsyncOperation.h
gridgentoo/ServiceFabricAzure
c3e7a07617e852322d73e6cc9819d266146866a4
[ "MIT" ]
994
2019-05-07T02:39:30.000Z
2022-03-31T13:23:04.000Z
src/prod/src/Management/CentralSecretService/SecretManager.SecretsAsyncOperation.h
gridgentoo/ServiceFabricAzure
c3e7a07617e852322d73e6cc9819d266146866a4
[ "MIT" ]
300
2018-03-14T21:57:17.000Z
2019-05-06T20:07:00.000Z
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ #pragma once namespace Management { namespace CentralSecretService { class SecretManager::SecretsAsyncOperation : public Common::TimedAsyncOperation , public Common::TextTraceComponent<Common::TraceTaskCodes::CentralSecretService> { public: SecretsAsyncOperation( Store::IReplicatedStore * replicatedStore, Store::PartitionedReplicaId const & partitionedReplicaId, Common::TimeSpan const & timeout, Common::AsyncCallback const & callback, Common::AsyncOperationSPtr const & parent, Common::ActivityId const & activityId); virtual ~SecretsAsyncOperation(); protected: __declspec(property(get = get_ActivityId)) Common::ActivityId const & ActivityId; Common::ActivityId const & get_ActivityId() const { return activityId_; } __declspec(property(get = get_PartitionedReplicaId)) Store::PartitionedReplicaId const & PartitionedReplicaId; Store::PartitionedReplicaId const & get_PartitionedReplicaId() const { return partitionedReplicaId_; } __declspec(property(get = get_ReplicatedStore)) Store::IReplicatedStore * ReplicatedStore; Store::IReplicatedStore * get_ReplicatedStore() const { return replicatedStore_; } __declspec(property(get = get_TraceComponent)) Common::StringLiteral const & TraceComponent; virtual Common::StringLiteral const & get_TraceComponent() const = 0; virtual void OnTimeout(AsyncOperationSPtr const &) override; virtual void OnStart(AsyncOperationSPtr const &) override; virtual void OnCompleted() override; virtual void OnCancel() override; Store::StoreTransaction CreateTransaction(); void Complete(Common::AsyncOperationSPtr const & thisSPtr, Common::ErrorCode const & errorCode); private: Store::IReplicatedStore * replicatedStore_; Store::PartitionedReplicaId const partitionedReplicaId_; Common::ActivityId const activityId_; }; } }
44.890909
122
0.637505
2b636656fa0ff26becc61e9625591f4df053aba4
1,191
h
C
src/stream/file/shared.h
Packetfahrer/tbd
f1e635cc9620d78b6666edba6a620ed24672af30
[ "MIT" ]
1
2021-06-09T11:32:57.000Z
2021-06-09T11:32:57.000Z
src/stream/file/shared.h
Packetfahrer/tbd
f1e635cc9620d78b6666edba6a620ed24672af30
[ "MIT" ]
null
null
null
src/stream/file/shared.h
Packetfahrer/tbd
f1e635cc9620d78b6666edba6a620ed24672af30
[ "MIT" ]
null
null
null
// // src/stream/file/shared.h // tbd // // Created by inoahdev on 11/10/17. // Copyright © 2017 inoahdev. All rights reserved. // #pragma once #include <memory> #include "seek_type.h" namespace stream::file { class shared { public: explicit shared() = default; enum class open_result { ok, failed_to_open_file }; open_result open(const char *path, const char *mode) noexcept; open_result open(int descriptor, const char *mode) noexcept; open_result open(FILE *file) noexcept; bool seek(long location, seek_type seek) const noexcept; bool read(void *buffer, size_t size) const noexcept; bool write(const void *buffer, size_t size) const noexcept; long position() const noexcept; long size() const noexcept; int error() const noexcept; inline bool is_open() const noexcept { return stream() != nullptr; } inline bool is_closed() const noexcept { return stream() == nullptr; } inline FILE *stream() const noexcept { return stream_.get(); } void close(); private: std::shared_ptr<FILE> stream_; }; }
23.82
78
0.620487
2b63ca9bc7ed1c5037af31b58748e5e30271d6dc
583
h
C
HappyAmoy/Classes/Mine/Model/MessageItem.h
ClickGetBonus/HappyAmoy
3b6b1223de806c57374bf3038f3af9675cdb1021
[ "MIT" ]
1
2019-07-16T10:38:35.000Z
2019-07-16T10:38:35.000Z
HappyAmoy/Classes/Mine/Model/MessageItem.h
ClickGetBonus/HappyAmoy
3b6b1223de806c57374bf3038f3af9675cdb1021
[ "MIT" ]
null
null
null
HappyAmoy/Classes/Mine/Model/MessageItem.h
ClickGetBonus/HappyAmoy
3b6b1223de806c57374bf3038f3af9675cdb1021
[ "MIT" ]
null
null
null
// // MessageItem.h // HappyAmoy // // Created by apple on 2018/5/9. // Copyright © 2018年 apple. All rights reserved. // #import <Foundation/Foundation.h> @interface MessageItem : NSObject @property (copy, nonatomic) NSString *noticeId; @property (copy, nonatomic) NSString *role; @property (copy, nonatomic) NSString *content; @property (copy, nonatomic) NSString *msgId; @property (copy, nonatomic) NSString *createTime; @property (assign, nonatomic) NSInteger readed; @property (assign, nonatomic) NSInteger type; @property (assign, nonatomic) NSInteger customerId; @end
24.291667
51
0.740995
2b691b9a5a619f5ea694762e3816a8a6b1933632
5,244
c
C
firmware/coreboot/3rdparty/chromeec/common/charger_profile_override.c
fabiojna02/OpenCellular
45b6a202d6b2e2485c89955b9a6da920c4d56ddb
[ "CC-BY-4.0", "BSD-3-Clause" ]
627
2022-01-21T17:48:25.000Z
2022-03-31T21:02:21.000Z
firmware/coreboot/3rdparty/chromeec/common/charger_profile_override.c
fabiojna02/OpenCellular
45b6a202d6b2e2485c89955b9a6da920c4d56ddb
[ "CC-BY-4.0", "BSD-3-Clause" ]
13
2018-10-12T21:29:09.000Z
2018-10-25T20:06:51.000Z
firmware/coreboot/3rdparty/chromeec/common/charger_profile_override.c
fabiojna02/OpenCellular
45b6a202d6b2e2485c89955b9a6da920c4d56ddb
[ "CC-BY-4.0", "BSD-3-Clause" ]
46
2016-02-07T18:43:27.000Z
2022-01-03T02:30:51.000Z
/* Copyright 2016 The Chromium OS Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. * * Charger profile override for fast charging */ #include "charger_profile_override.h" #include "console.h" #include "ec_commands.h" #include "util.h" #ifdef CONFIG_CMD_CHARGER_PROFILE_OVERRIDE_TEST static int fast_charge_test_on; static int test_flag_temp; static int test_flag_vtg; static int test_temp_c; static int test_vtg_mV = -1; #endif static int fast_charging_allowed = 1; int charger_profile_override_common(struct charge_state_data *curr, const struct fast_charge_params *fast_chg_params, const struct fast_charge_profile **prev_chg_prof_info, int batt_vtg_max) { int i, voltage_range; /* temp in 0.1 deg C */ int temp_c = curr->batt.temperature - 2731; int temp_ranges = fast_chg_params->total_temp_ranges; const struct fast_charge_profile *chg_profile_info = fast_chg_params->chg_profile_info; #ifdef CONFIG_CMD_CHARGER_PROFILE_OVERRIDE_TEST if (fast_charge_test_on && test_vtg_mV != -1) { temp_c = TEMPC_TENTHS_OF_DEG(test_temp_c); curr->batt.voltage = test_vtg_mV; if (test_flag_temp) curr->batt.flags |= BATT_FLAG_BAD_TEMPERATURE; else curr->batt.flags &= BATT_FLAG_BAD_TEMPERATURE; if (test_flag_vtg) curr->batt.flags |= BATT_FLAG_BAD_VOLTAGE; else curr->batt.flags &= BATT_FLAG_BAD_VOLTAGE; } #endif /* * Determine temperature range. * If temp reading was bad, use last range. */ if (!(curr->batt.flags & BATT_FLAG_BAD_TEMPERATURE)) { while (chg_profile_info && temp_ranges) { if (temp_c <= chg_profile_info->temp_c) { *prev_chg_prof_info = chg_profile_info; break; } chg_profile_info++; temp_ranges--; } /* Invalid charge profile selected */ if (!chg_profile_info || !temp_ranges) return -1; } /* * If the battery voltage reading is bad or the battery voltage is * greater than or equal to the lower limit or the battery voltage is * not in the charger profile voltage range, consider battery has high * voltage range so that we charge at lower current limit. */ voltage_range = CONFIG_CHARGER_PROFILE_VOLTAGE_RANGES - 1; if (!(curr->batt.flags & BATT_FLAG_BAD_VOLTAGE)) { for (i = 0; i < CONFIG_CHARGER_PROFILE_VOLTAGE_RANGES - 1; i++) { if (curr->batt.voltage < fast_chg_params->voltage_mV[i]) { voltage_range = i; break; } } } /* * If we are not charging or we aren't using fast charging profiles, * then do not override desired current and voltage. */ if (curr->state != ST_CHARGE || !fast_charging_allowed) return 0; /* * Okay, impose our custom will: */ curr->requested_current = (*prev_chg_prof_info)->current_mA[voltage_range]; curr->requested_voltage = curr->requested_current ? batt_vtg_max : 0; #ifdef CONFIG_CMD_CHARGER_PROFILE_OVERRIDE_TEST if (fast_charge_test_on) ccprintf("Fast charge profile i=%dmA, v=%dmV\n", curr->requested_current, curr->requested_voltage); #endif return 0; } /* Customs options controllable by host command. */ #define PARAM_FASTCHARGE (CS_PARAM_CUSTOM_PROFILE_MIN + 0) enum ec_status charger_profile_override_get_param(uint32_t param, uint32_t *value) { if (param == PARAM_FASTCHARGE) { *value = fast_charging_allowed; return EC_RES_SUCCESS; } return EC_RES_INVALID_PARAM; } enum ec_status charger_profile_override_set_param(uint32_t param, uint32_t value) { if (param == PARAM_FASTCHARGE) { fast_charging_allowed = value; return EC_RES_SUCCESS; } return EC_RES_INVALID_PARAM; } #ifdef CONFIG_CMD_CHARGER_PROFILE_OVERRIDE static int command_fastcharge(int argc, char **argv) { if (argc > 1 && !parse_bool(argv[1], &fast_charging_allowed)) return EC_ERROR_PARAM1; ccprintf("fastcharge %s\n", fast_charging_allowed ? "on" : "off"); return EC_SUCCESS; } DECLARE_CONSOLE_COMMAND(fastcharge, command_fastcharge, "[on|off]", "Get or set fast charging profile"); #endif /* * Manipulate the temperature and voltage values and check if the correct * fast charging profile is selected. */ #ifdef CONFIG_CMD_CHARGER_PROFILE_OVERRIDE_TEST static int command_fastcharge_test(int argc, char **argv) { char *e; int test_on; if (argc > 1 && !parse_bool(argv[1], &test_on)) return EC_ERROR_PARAM2; /* Check if only tuurn printf message on / off */ if (argc == 2) { fast_charge_test_on = test_on; test_vtg_mV = -1; return EC_SUCCESS; } /* Validate the input parameters */ if ((test_on && argc != 6) || !test_on) return EC_ERROR_PARAM_COUNT; test_flag_temp = strtoi(argv[2], &e, 0); if (*e || test_flag_temp > 1 || test_flag_temp < 0) return EC_ERROR_PARAM3; test_flag_vtg = strtoi(argv[3], &e, 0); if (*e || test_flag_vtg > 1 || test_flag_vtg < 0) return EC_ERROR_PARAM4; test_temp_c = strtoi(argv[4], &e, 0); if (*e) return EC_ERROR_PARAM5; test_vtg_mV = strtoi(argv[5], &e, 0); if (*e || test_vtg_mV < 0) { test_vtg_mV = -1; return EC_ERROR_PARAM6; } fast_charge_test_on = 1; return EC_SUCCESS; } DECLARE_CONSOLE_COMMAND(fastchgtest, command_fastcharge_test, "off | on tempflag[1|0] vtgflag[1|0] temp_c vtg_mV", "Check if fastcharge profile works"); #endif
25.960396
73
0.72807
2b69b1da9b98c89522c07ea1a3ba0428fd6acb4f
222
h
C
Mizu/Mizu/Views/MZDarkTableView.h
apisit/Mizu-iOS
d55f37d97ba285afb04f0ba3934af06d881b059b
[ "Unlicense", "MIT" ]
1
2016-03-24T02:30:33.000Z
2016-03-24T02:30:33.000Z
Mizu/Mizu/Views/MZDarkTableView.h
apisit/Mizu-iOS
d55f37d97ba285afb04f0ba3934af06d881b059b
[ "Unlicense", "MIT" ]
null
null
null
Mizu/Mizu/Views/MZDarkTableView.h
apisit/Mizu-iOS
d55f37d97ba285afb04f0ba3934af06d881b059b
[ "Unlicense", "MIT" ]
null
null
null
// // MZDarkTableView.h // Mizu // // Created by Apisit Toompakdee on 10/30/15. // Copyright © 2015 Mizu. All rights reserved. // #import <UIKit/UIKit.h> IB_DESIGNABLE @interface MZDarkTableView : UITableView @end
13.875
47
0.698198
2b6a4951593d9e1b5d711616673e54f1bff17db5
3,273
h
C
include/chxj_cookie.h
unpush/mod_chxj
b4dc76ad0f5c843c1b250fd0ee4c0616bbc39c48
[ "Apache-2.0" ]
1
2016-05-08T13:23:59.000Z
2016-05-08T13:23:59.000Z
include/chxj_cookie.h
unpush/mod_chxj
b4dc76ad0f5c843c1b250fd0ee4c0616bbc39c48
[ "Apache-2.0" ]
null
null
null
include/chxj_cookie.h
unpush/mod_chxj
b4dc76ad0f5c843c1b250fd0ee4c0616bbc39c48
[ "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2005-2008 Atsushi Konno All rights reserved. * Copyright (C) 2005 QSDN,Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef __CHXJ_COOKIE_H__ #define __CHXJ_COOKIE_H__ #include "mod_chxj.h" #include "apr_file_io.h" #include "apr_tables.h" #include "apr_time.h" #define CHXJ_COOKIE_PARAM "_chxj_cc" #define CHXJ_COOKIE_NOUPDATE_PARAM "_chxj_nc" #define DEFAULT_COOKIE_DB_DIR "/tmp" #define COOKIE_DB_NAME "cookie.db" #define COOKIE_DB_LOCK_NAME "cookie.db.lock" #define COOKIE_EXPIRE_DB_NAME "cookie.expire.db" #define COOKIE_EXPIRE_DB_LOCK_NAME "cookie.expire.db.lock" #define REFERER_COOKIE_KEY "CHXJ_REFER" #define CHXJ_COOKIE_PROC_MUTEX_FILE "/tmp/chxj_cookie_mutex.lock" /* * default cookie timeout is 30 minute */ #define DEFAULT_COOKIE_TIMEOUT (1800) extern apr_proc_mutex_t *global_cookie_mutex; typedef struct cookie_t cookie_t; struct cookie_t { char* cookie_id; apr_array_header_t* cookie_headers; }; extern cookie_t* chxj_save_cookie( request_rec* r); extern char* chxj_add_cookie_parameter( request_rec* r, char* value, cookie_t* cookie); extern int chxj_cookie_check_host( request_rec* r, char* value); extern cookie_t* chxj_load_cookie( request_rec* r, char* cookie_id); extern apr_file_t* chxj_cookie_db_lock( request_rec* r); extern void chxj_cookie_db_unlock( request_rec* r, apr_file_t* file); extern void chxj_delete_cookie(request_rec *r, const char *cookie_id); extern char* chxj_cookie_db_name_create( request_rec* r, const char* dir); extern char* chxj_cookie_db_lock_name_create( request_rec* r, const char* dir); extern char* chxj_cookie_expire_db_lock_name_create( request_rec* r, const char* dir); extern char* chxj_cookie_expire_db_name_create( request_rec* r, const char* dir); extern apr_file_t* chxj_cookie_expire_db_lock( request_rec* r); extern void chxj_cookie_expire_db_unlock( request_rec* r, apr_file_t* file); extern void chxj_save_cookie_expire( request_rec* r, cookie_t* cookie); extern void chxj_delete_cookie_expire( request_rec* r, char* cookie_id); extern void chxj_cookie_expire_gc( request_rec* r); extern cookie_t* chxj_update_cookie( request_rec* r, cookie_t* old_cookie); extern apr_time_t chxj_parse_cookie_expires(const char *s); extern int chxj_cookie_lock(request_rec *r); extern int chxj_cookie_unlock(request_rec *r); #endif /* * vim:ts=2 et */
26.184
75
0.69722
2b6bf3f4de6eee1949b43eae4ceaa94a0f01ea5c
4,721
c
C
bip32.c
shufps/trezor-crypto
bb0f13d835de8adf166b3da057ab78c8f88bd142
[ "MIT" ]
null
null
null
bip32.c
shufps/trezor-crypto
bb0f13d835de8adf166b3da057ab78c8f88bd142
[ "MIT" ]
null
null
null
bip32.c
shufps/trezor-crypto
bb0f13d835de8adf166b3da057ab78c8f88bd142
[ "MIT" ]
null
null
null
/** * Copyright (c) 2013-2016 Tomas Dzetkulic * Copyright (c) 2013-2016 Pavol Rusnak * Copyright (c) 2015-2016 Jochen Hoenicke * * 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 <stdbool.h> #include <string.h> #include "bignum.h" #include "bip32.h" #include "curves.h" #include "ecdsa.h" #include "hmac.h" #include "secp256k1.h" #include "sha2.h" #include "memzero.h" int hdnode_from_seed(const uint8_t *seed, int seed_len, const char *curve, HDNode *out) { static CONFIDENTIAL uint8_t I[32 + 32]; memzero(out, sizeof(HDNode)); out->depth = 0; out->child_num = 0; out->curve = get_curve_by_name(curve); if (out->curve == 0) { return 0; } static CONFIDENTIAL HMAC_SHA512_CTX ctx; hmac_sha512_Init(&ctx, (const uint8_t *)out->curve->bip32_name, strlen(out->curve->bip32_name)); hmac_sha512_Update(&ctx, seed, seed_len); hmac_sha512_Final(&ctx, I); if (out->curve->params) { bignum256 a; while (true) { bn_read_be(I, &a); if (!bn_is_zero(&a) // != 0 && bn_is_less(&a, &out->curve->params->order)) { // < order break; } hmac_sha512_Init(&ctx, (const uint8_t *)out->curve->bip32_name, strlen(out->curve->bip32_name)); hmac_sha512_Update(&ctx, I, sizeof(I)); hmac_sha512_Final(&ctx, I); } memzero(&a, sizeof(a)); } memcpy(out->private_key, I, 32); memcpy(out->chain_code, I + 32, 32); memzero(I, sizeof(I)); return 1; } int hdnode_private_ckd(HDNode *inout, uint32_t i) { static CONFIDENTIAL uint8_t data[1 + 32 + 4]; static CONFIDENTIAL uint8_t I[32 + 32]; static CONFIDENTIAL bignum256 a, b; if (i & 0x80000000) { // private derivation data[0] = 0; memcpy(data + 1, inout->private_key, 32); } else { // public derivation if (!inout->curve->params) { return 0; } //hdnode_fill_public_key(inout); //memcpy(data, inout->public_key, 33); //non-private derivation disabled //saves 10kB ROM and not used in IOTA return 0; } write_be(data + 33, i); bn_read_be(inout->private_key, &a); static CONFIDENTIAL HMAC_SHA512_CTX ctx; hmac_sha512_Init(&ctx, inout->chain_code, 32); hmac_sha512_Update(&ctx, data, sizeof(data)); hmac_sha512_Final(&ctx, I); if (inout->curve->params) { while (true) { bool failed = false; bn_read_be(I, &b); if (!bn_is_less(&b, &inout->curve->params->order)) { // >= order failed = true; } else { bn_add(&b, &a); bn_mod(&b, &inout->curve->params->order); if (bn_is_zero(&b)) { failed = true; } } if (!failed) { bn_write_be(&b, inout->private_key); break; } data[0] = 1; memcpy(data + 1, I + 32, 32); hmac_sha512_Init(&ctx, inout->chain_code, 32); hmac_sha512_Update(&ctx, data, sizeof(data)); hmac_sha512_Final(&ctx, I); } } else { memcpy(inout->private_key, I, 32); } memcpy(inout->chain_code, I + 32, 32); inout->depth++; inout->child_num = i; // making sure to wipe our memory memzero(&a, sizeof(a)); memzero(&b, sizeof(b)); memzero(I, sizeof(I)); memzero(data, sizeof(data)); return 1; } #if 0 void hdnode_fill_public_key(HDNode *node) { if (node->public_key[0] != 0) return; ecdsa_get_public_key33(node->curve->params, node->private_key, node->public_key); } #endif const curve_info *get_curve_by_name(const char *curve_name) { if (curve_name == 0) { return 0; } if (strcmp(curve_name, SECP256K1_NAME) == 0) { return &secp256k1_info; } return 0; }
29.322981
79
0.638424
2b6c401c20ef9c302e1a71cc1f30b9f4e971a080
278
h
C
Example/ProgressiveAlertView/AppDelegate.h
hechen/ProgressiveAlertView
d387d7e9f5cdd9b6e64a8a32d07916acb8986b45
[ "MIT" ]
null
null
null
Example/ProgressiveAlertView/AppDelegate.h
hechen/ProgressiveAlertView
d387d7e9f5cdd9b6e64a8a32d07916acb8986b45
[ "MIT" ]
null
null
null
Example/ProgressiveAlertView/AppDelegate.h
hechen/ProgressiveAlertView
d387d7e9f5cdd9b6e64a8a32d07916acb8986b45
[ "MIT" ]
null
null
null
// // AppDelegate.h // ProgressAlertView // // Created by He Chen on 2017/9/30. // Copyright © 2017 Chen. All rights reserved. // #import <UIKit/UIKit.h> @interface AppDelegate : UIResponder <UIApplicationDelegate> @property (strong, nonatomic) UIWindow *window; @end
15.444444
60
0.705036
2b707513164296ca88508ca179bd413856523264
534
c
C
tree/104-maximum-depth-of-binary-tree.c
geekerlw/leetcode
50e20854658fb4d47667554a3418f7143ff67a8d
[ "Apache-2.0" ]
null
null
null
tree/104-maximum-depth-of-binary-tree.c
geekerlw/leetcode
50e20854658fb4d47667554a3418f7143ff67a8d
[ "Apache-2.0" ]
null
null
null
tree/104-maximum-depth-of-binary-tree.c
geekerlw/leetcode
50e20854658fb4d47667554a3418f7143ff67a8d
[ "Apache-2.0" ]
null
null
null
#include <stdio.h> /** * Definition for a binary tree node. * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; */ typedef struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; }TreeNode; int maxDepth(struct TreeNode *root) { if(NULL==root) return 0; int l_d=maxDepth(root->left); int r_d=maxDepth(root->right); return l_d>r_d? l_d+1 : r_d+1; } void main() { TreeNode *root; int ret = maxDepth(root); printf("the output is: %d\n", ret); }
16.6875
37
0.638577
d877ddd19132df5c5e8c0e5952f9a80a5f2a62ad
5,987
h
C
Latest_Version/PRU/include/am335x/pru_iep.h
Andregarciav/OpenVLC
3213190700a2a4e4e313b4a6eb72161fd021d349
[ "BSD-3-Clause" ]
52
2018-10-13T16:39:35.000Z
2022-03-19T18:16:54.000Z
Latest_Version/PRU/include/am335x/pru_iep.h
Andregarciav/OpenVLC
3213190700a2a4e4e313b4a6eb72161fd021d349
[ "BSD-3-Clause" ]
13
2020-08-03T17:17:13.000Z
2022-01-08T06:39:50.000Z
Latest_Version/PRU/include/am335x/pru_iep.h
Andregarciav/OpenVLC
3213190700a2a4e4e313b4a6eb72161fd021d349
[ "BSD-3-Clause" ]
28
2018-10-13T16:39:52.000Z
2022-03-28T19:19:51.000Z
/* * Copyright (C) 2015 Texas Instruments Incorporated - http://www.ti.com/ * * * 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 Texas Instruments Incorporated nor the names of * its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef _PRU_IEP_H_ #define _PRU_IEP_H_ /* PRU IEP register set */ typedef struct { /* PRU_IEP_TMR_GLB_CFG register bit field */ union { volatile uint32_t TMR_GLB_CFG; volatile struct { unsigned CNT_EN : 1; // 0 unsigned rsvd1 : 3; // 3:1 unsigned DEFAULT_INC : 4; // 7:4 unsigned CMP_INC : 12; // 19:8 unsigned rsvd12 : 12; // 31:20 } TMR_GLB_CFG_bit; }; // 0x0 /* PRU_IEP_TMR_GLB_STS register bit field */ union { volatile uint32_t TMR_GLB_STS; volatile struct { unsigned CNT_OVF : 1; // 0 unsigned rsvd1 : 31; // 31:1 } TMR_GLB_STS_bit; }; // 0x4 /* PRU_IEP_TMR_COMPEN register bit field */ union { volatile uint32_t TMR_COMPEN; volatile struct { unsigned COMPEN_CNT : 24; // 23:0 unsigned rsvd24 : 8; // 31:24 } TMR_COMPEN_bit; }; // 0x8 /* PRU_IEP_TMR_CNT register bit field */ union { volatile uint32_t TMR_CNT; volatile struct { unsigned COUNT : 32; // 31:0 } TMR_CNT_bit; }; // 0xC uint32_t rsvd10[12]; // 0x10 - 0x3C /* PRU_IEP_TMR_CMP_CFG register bit field */ union { volatile uint32_t TMR_CMP_CFG; volatile struct { unsigned CMP0_RST_CNT_EN : 1; // 0 unsigned CMP_EN : 8; // 8:1 unsigned rsvd9 : 23; // 31:9 } TMR_CMP_CFG_bit; }; // 0x40 /* PRU_IEP_TMR_CMP_STS register bit field */ union { volatile uint32_t TMR_CMP_STS; volatile struct { unsigned CMP_HIT : 8; // 7:0 unsigned rsvd8 : 24; // 31:8 } TMR_CMP_STS_bit; }; // 0x44 /* PRU_IEP_TMR_CMP0 register bit field */ union { volatile uint32_t TMR_CMP0; volatile struct { unsigned CMP0 : 32; // 31:0 } TMR_CMP0_bit; }; // 0x48 /* PRU_IEP_TMR_CMP1 register bit field */ union { volatile uint32_t TMR_CMP1; volatile struct { unsigned CMP1 : 32; // 31:0 } TMR_CMP1_bit; }; // 0x4C /* PRU_IEP_TMR_CMP2 register bit field */ union { volatile uint32_t TMR_CMP2; volatile struct { unsigned CMP2 : 32; // 31:0 } TMR_CMP2_bit; }; // 0x50 /* PRU_IEP_TMR_CMP3 register bit field */ union { volatile uint32_t TMR_CMP3; volatile struct { unsigned CMP3 : 32; // 31:0 } TMR_CMP3_bit; }; // 0x54 /* PRU_IEP_TMR_CMP4 register bit field */ union { volatile uint32_t TMR_CMP4; volatile struct { unsigned CMP4 : 32; // 31:0 } TMR_CMP4_bit; }; // 0x58 /* PRU_IEP_TMR_CMP5 register bit field */ union { volatile uint32_t TMR_CMP5; volatile struct { unsigned CMP5 : 32; // 31:0 } TMR_CMP5_bit; }; // 0x5C /* PRU_IEP_TMR_CMP6 register bit field */ union { volatile uint32_t TMR_CMP6; volatile struct { unsigned CMP6 : 32; // 31:0 } TMR_CMP6_bit; }; // 0x60 /* PRU_IEP_TMR_CMP7 register bit field */ union { volatile uint32_t TMR_CMP7; volatile struct { unsigned CMP7 : 32; // 31:0 } TMR_CMP7_bit; }; // 0x64 uint32_t rsvd68[166]; // 0x68 - 0x2FF /* PRU_IEP_DIGIO_CTRL register bit field */ union { volatile uint32_t DIGIO_CTRL; volatile struct { unsigned RESERVED0 : 4; // 3:0 unsigned IN_MODE : 1; // 4 unsigned RESERVED5 : 27; // 31:5 } DIGIO_CTRL_bit; }; // 0x300 uint32_t rsvd304[1]; // 0x304 /* PRU_IEP_DIGIO_DATA_IN register bit field */ union { volatile uint32_t DIGIO_DATA_IN; volatile struct { unsigned DATA_IN : 32; // 31:0 } DIGIO_DATA_IN_bit; }; // 0x308 /* PRU_IEP_DIGIO_DATA_IN_RAW register bit field */ union { volatile uint32_t DIGIO_DATA_IN_RAW; volatile struct { unsigned DATA_IN_RAW : 32; // 31:0 } DIGIO_DATA_IN_RAW_bit; }; // 0x30C /* PRU_IEP_DIGIO_DATA_OUT register bit field */ union { volatile uint32_t DIGIO_DATA_OUT; volatile struct { unsigned DATA_OUT : 32; // 31:0 } DIGIO_DATA_OUT_bit; }; // 0x310 /* PRU_IEP_DIGIO_DATA_OUT_EN register bit field */ union { volatile uint32_t DIGIO_DATA_OUT_EN; volatile struct { unsigned DATA_OUT_EN : 32; // 31:0 } DIGIO_DATA_OUT_EN_bit; }; // 0x314 /* PRU_IEP_DIGIO_EXP register bit field */ union { volatile uint32_t DIGIO_EXP; volatile struct { unsigned SW_DATA_OUT_UPDATE : 1; // 0 unsigned OUTVALID_OVR_EN : 1; // 1 unsigned RESERVED2 : 30; // 31:2 } DIGIO_EXP_bit; }; // 0x318 } pruIep; volatile __far pruIep CT_IEP __attribute__((cregister("PRU_IEP", far), peripheral)); #endif /* _PRU_IEP_H_ */
23.29572
84
0.677301
d878190e7f7de57ed29786c9c55eccbdbca73ef1
562
h
C
apps/coprobber/DSRobberAlgorithm.h
AaronTrip/hog2
96616b40f4173959b127011c76f3e649688e1a99
[ "MIT" ]
5
2020-08-03T09:43:26.000Z
2022-01-11T08:28:30.000Z
apps/coprobber/DSRobberAlgorithm.h
AaronTrip/hog2
96616b40f4173959b127011c76f3e649688e1a99
[ "MIT" ]
null
null
null
apps/coprobber/DSRobberAlgorithm.h
AaronTrip/hog2
96616b40f4173959b127011c76f3e649688e1a99
[ "MIT" ]
7
2017-07-31T13:01:28.000Z
2021-05-16T10:15:49.000Z
#include "DSCREnvironment.h" #ifndef DSROBBERALGORITHM #define DSROBBERALGORITHM // This is an interface that will be used to compute a best response // against a given robber algorithm. // The algorithm cannot keep track of the history of the game since // computation is bottom-up in the game tree. // Furthermore, the robber runs at speed 1. template<class state, class action> class DSRobberAlgorithm { public: virtual ~DSRobberAlgorithm() {}; virtual state MakeMove( state pos_robber, state pos_cop, unsigned int num_graph_nodes ) = 0; }; #endif
23.416667
93
0.763345
d87840bae236da78993e8078b13887d9e5e73b04
53,891
h
C
UWP/RadialDevice/winrt/Windows.Media.Capture.Frames.h
megayuchi/RadialController
87bb1baa72a0b43b1b7b0d7787b0a93edc7e3175
[ "MIT" ]
23
2016-11-28T05:47:06.000Z
2020-11-13T20:13:47.000Z
UWP/RadialDevice/winrt/Windows.Media.Capture.Frames.h
megayuchi/RadialController
87bb1baa72a0b43b1b7b0d7787b0a93edc7e3175
[ "MIT" ]
null
null
null
UWP/RadialDevice/winrt/Windows.Media.Capture.Frames.h
megayuchi/RadialController
87bb1baa72a0b43b1b7b0d7787b0a93edc7e3175
[ "MIT" ]
5
2017-01-21T14:42:47.000Z
2022-02-24T03:42:24.000Z
// C++ for the Windows Runtime v1.0.161012.5 // Copyright (c) 2016 Microsoft Corporation. All rights reserved. #pragma once #include "internal/Windows.Foundation.Collections.3.h" #include "internal/Windows.Foundation.3.h" #include "internal/Windows.Media.Capture.3.h" #include "internal/Windows.Devices.Enumeration.3.h" #include "internal/Windows.Perception.Spatial.3.h" #include "internal/Windows.Media.Devices.Core.3.h" #include "internal/Windows.Media.Devices.3.h" #include "internal/Windows.Media.MediaProperties.3.h" #include "internal/Windows.Storage.Streams.3.h" #include "internal/Windows.Graphics.Imaging.3.h" #include "internal/Windows.Graphics.DirectX.Direct3D11.3.h" #include "internal/Windows.Media.3.h" #include "internal/Windows.Media.Capture.Frames.3.h" #include "Windows.Media.Capture.h" #include "Windows.Foundation.h" WINRT_EXPORT namespace winrt { namespace impl { template <typename D> struct produce<D, Windows::Media::Capture::Frames::IBufferMediaFrame> : produce_base<D, Windows::Media::Capture::Frames::IBufferMediaFrame> { HRESULT __stdcall get_FrameReference(abi_arg_out<Windows::Media::Capture::Frames::IMediaFrameReference> value) noexcept override { try { *value = detach(this->shim().FrameReference()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall get_Buffer(abi_arg_out<Windows::Storage::Streams::IBuffer> value) noexcept override { try { *value = detach(this->shim().Buffer()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Media::Capture::Frames::IDepthMediaFrame> : produce_base<D, Windows::Media::Capture::Frames::IDepthMediaFrame> { HRESULT __stdcall get_FrameReference(abi_arg_out<Windows::Media::Capture::Frames::IMediaFrameReference> value) noexcept override { try { *value = detach(this->shim().FrameReference()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall get_VideoMediaFrame(abi_arg_out<Windows::Media::Capture::Frames::IVideoMediaFrame> value) noexcept override { try { *value = detach(this->shim().VideoMediaFrame()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall get_DepthFormat(abi_arg_out<Windows::Media::Capture::Frames::IDepthMediaFrameFormat> value) noexcept override { try { *value = detach(this->shim().DepthFormat()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall abi_TryCreateCoordinateMapper(abi_arg_in<Windows::Media::Devices::Core::ICameraIntrinsics> cameraIntrinsics, abi_arg_in<Windows::Perception::Spatial::ISpatialCoordinateSystem> coordinateSystem, abi_arg_out<Windows::Media::Devices::Core::IDepthCorrelatedCoordinateMapper> value) noexcept override { try { *value = detach(this->shim().TryCreateCoordinateMapper(*reinterpret_cast<const Windows::Media::Devices::Core::CameraIntrinsics *>(&cameraIntrinsics), *reinterpret_cast<const Windows::Perception::Spatial::SpatialCoordinateSystem *>(&coordinateSystem))); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Media::Capture::Frames::IDepthMediaFrameFormat> : produce_base<D, Windows::Media::Capture::Frames::IDepthMediaFrameFormat> { HRESULT __stdcall get_VideoFormat(abi_arg_out<Windows::Media::Capture::Frames::IVideoMediaFrameFormat> value) noexcept override { try { *value = detach(this->shim().VideoFormat()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall get_DepthScaleInMeters(double * value) noexcept override { try { *value = detach(this->shim().DepthScaleInMeters()); return S_OK; } catch (...) { return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Media::Capture::Frames::IInfraredMediaFrame> : produce_base<D, Windows::Media::Capture::Frames::IInfraredMediaFrame> { HRESULT __stdcall get_FrameReference(abi_arg_out<Windows::Media::Capture::Frames::IMediaFrameReference> value) noexcept override { try { *value = detach(this->shim().FrameReference()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall get_VideoMediaFrame(abi_arg_out<Windows::Media::Capture::Frames::IVideoMediaFrame> value) noexcept override { try { *value = detach(this->shim().VideoMediaFrame()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall get_IsIlluminated(bool * value) noexcept override { try { *value = detach(this->shim().IsIlluminated()); return S_OK; } catch (...) { return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Media::Capture::Frames::IMediaFrameArrivedEventArgs> : produce_base<D, Windows::Media::Capture::Frames::IMediaFrameArrivedEventArgs> {}; template <typename D> struct produce<D, Windows::Media::Capture::Frames::IMediaFrameFormat> : produce_base<D, Windows::Media::Capture::Frames::IMediaFrameFormat> { HRESULT __stdcall get_MajorType(abi_arg_out<hstring> value) noexcept override { try { *value = detach(this->shim().MajorType()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall get_Subtype(abi_arg_out<hstring> value) noexcept override { try { *value = detach(this->shim().Subtype()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall get_FrameRate(abi_arg_out<Windows::Media::MediaProperties::IMediaRatio> value) noexcept override { try { *value = detach(this->shim().FrameRate()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall get_Properties(abi_arg_out<Windows::Foundation::Collections::IMapView<GUID, Windows::IInspectable>> value) noexcept override { try { *value = detach(this->shim().Properties()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall get_VideoFormat(abi_arg_out<Windows::Media::Capture::Frames::IVideoMediaFrameFormat> value) noexcept override { try { *value = detach(this->shim().VideoFormat()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Media::Capture::Frames::IMediaFrameReader> : produce_base<D, Windows::Media::Capture::Frames::IMediaFrameReader> { HRESULT __stdcall add_FrameArrived(abi_arg_in<Windows::Foundation::TypedEventHandler<Windows::Media::Capture::Frames::MediaFrameReader, Windows::Media::Capture::Frames::MediaFrameArrivedEventArgs>> handler, event_token * token) noexcept override { try { *token = detach(this->shim().FrameArrived(*reinterpret_cast<const Windows::Foundation::TypedEventHandler<Windows::Media::Capture::Frames::MediaFrameReader, Windows::Media::Capture::Frames::MediaFrameArrivedEventArgs> *>(&handler))); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall remove_FrameArrived(event_token token) noexcept override { try { this->shim().FrameArrived(token); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall abi_TryAcquireLatestFrame(abi_arg_out<Windows::Media::Capture::Frames::IMediaFrameReference> value) noexcept override { try { *value = detach(this->shim().TryAcquireLatestFrame()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall abi_StartAsync(abi_arg_out<Windows::Foundation::IAsyncOperation<winrt::Windows::Media::Capture::Frames::MediaFrameReaderStartStatus>> operation) noexcept override { try { *operation = detach(this->shim().StartAsync()); return S_OK; } catch (...) { *operation = nullptr; return impl::to_hresult(); } } HRESULT __stdcall abi_StopAsync(abi_arg_out<Windows::Foundation::IAsyncAction> action) noexcept override { try { *action = detach(this->shim().StopAsync()); return S_OK; } catch (...) { *action = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Media::Capture::Frames::IMediaFrameReference> : produce_base<D, Windows::Media::Capture::Frames::IMediaFrameReference> { HRESULT __stdcall get_SourceKind(Windows::Media::Capture::Frames::MediaFrameSourceKind * value) noexcept override { try { *value = detach(this->shim().SourceKind()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_Format(abi_arg_out<Windows::Media::Capture::Frames::IMediaFrameFormat> value) noexcept override { try { *value = detach(this->shim().Format()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall get_SystemRelativeTime(abi_arg_out<Windows::Foundation::IReference<Windows::Foundation::TimeSpan>> value) noexcept override { try { *value = detach(this->shim().SystemRelativeTime()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall get_Duration(abi_arg_out<Windows::Foundation::TimeSpan> value) noexcept override { try { *value = detach(this->shim().Duration()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_Properties(abi_arg_out<Windows::Foundation::Collections::IMapView<GUID, Windows::IInspectable>> value) noexcept override { try { *value = detach(this->shim().Properties()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall get_BufferMediaFrame(abi_arg_out<Windows::Media::Capture::Frames::IBufferMediaFrame> value) noexcept override { try { *value = detach(this->shim().BufferMediaFrame()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall get_VideoMediaFrame(abi_arg_out<Windows::Media::Capture::Frames::IVideoMediaFrame> value) noexcept override { try { *value = detach(this->shim().VideoMediaFrame()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall get_CoordinateSystem(abi_arg_out<Windows::Perception::Spatial::ISpatialCoordinateSystem> value) noexcept override { try { *value = detach(this->shim().CoordinateSystem()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Media::Capture::Frames::IMediaFrameSource> : produce_base<D, Windows::Media::Capture::Frames::IMediaFrameSource> { HRESULT __stdcall get_Info(abi_arg_out<Windows::Media::Capture::Frames::IMediaFrameSourceInfo> value) noexcept override { try { *value = detach(this->shim().Info()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall get_Controller(abi_arg_out<Windows::Media::Capture::Frames::IMediaFrameSourceController> value) noexcept override { try { *value = detach(this->shim().Controller()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall get_SupportedFormats(abi_arg_out<Windows::Foundation::Collections::IVectorView<Windows::Media::Capture::Frames::MediaFrameFormat>> value) noexcept override { try { *value = detach(this->shim().SupportedFormats()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall get_CurrentFormat(abi_arg_out<Windows::Media::Capture::Frames::IMediaFrameFormat> value) noexcept override { try { *value = detach(this->shim().CurrentFormat()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall abi_SetFormatAsync(abi_arg_in<Windows::Media::Capture::Frames::IMediaFrameFormat> format, abi_arg_out<Windows::Foundation::IAsyncAction> value) noexcept override { try { *value = detach(this->shim().SetFormatAsync(*reinterpret_cast<const Windows::Media::Capture::Frames::MediaFrameFormat *>(&format))); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall add_FormatChanged(abi_arg_in<Windows::Foundation::TypedEventHandler<Windows::Media::Capture::Frames::MediaFrameSource, Windows::IInspectable>> handler, event_token * token) noexcept override { try { *token = detach(this->shim().FormatChanged(*reinterpret_cast<const Windows::Foundation::TypedEventHandler<Windows::Media::Capture::Frames::MediaFrameSource, Windows::IInspectable> *>(&handler))); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall remove_FormatChanged(event_token token) noexcept override { try { this->shim().FormatChanged(token); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall abi_TryGetCameraIntrinsics(abi_arg_in<Windows::Media::Capture::Frames::IMediaFrameFormat> format, abi_arg_out<Windows::Media::Devices::Core::ICameraIntrinsics> value) noexcept override { try { *value = detach(this->shim().TryGetCameraIntrinsics(*reinterpret_cast<const Windows::Media::Capture::Frames::MediaFrameFormat *>(&format))); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Media::Capture::Frames::IMediaFrameSourceController> : produce_base<D, Windows::Media::Capture::Frames::IMediaFrameSourceController> { HRESULT __stdcall abi_GetPropertyAsync(abi_arg_in<hstring> propertyId, abi_arg_out<Windows::Foundation::IAsyncOperation<Windows::Media::Capture::Frames::MediaFrameSourceGetPropertyResult>> value) noexcept override { try { *value = detach(this->shim().GetPropertyAsync(*reinterpret_cast<const hstring *>(&propertyId))); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall abi_SetPropertyAsync(abi_arg_in<hstring> propertyId, abi_arg_in<Windows::IInspectable> propertyValue, abi_arg_out<Windows::Foundation::IAsyncOperation<winrt::Windows::Media::Capture::Frames::MediaFrameSourceSetPropertyStatus>> value) noexcept override { try { *value = detach(this->shim().SetPropertyAsync(*reinterpret_cast<const hstring *>(&propertyId), *reinterpret_cast<const Windows::IInspectable *>(&propertyValue))); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall get_VideoDeviceController(abi_arg_out<Windows::Media::Devices::IVideoDeviceController> value) noexcept override { try { *value = detach(this->shim().VideoDeviceController()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Media::Capture::Frames::IMediaFrameSourceGetPropertyResult> : produce_base<D, Windows::Media::Capture::Frames::IMediaFrameSourceGetPropertyResult> { HRESULT __stdcall get_Status(Windows::Media::Capture::Frames::MediaFrameSourceGetPropertyStatus * value) noexcept override { try { *value = detach(this->shim().Status()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_Value(abi_arg_out<Windows::IInspectable> value) noexcept override { try { *value = detach(this->shim().Value()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Media::Capture::Frames::IMediaFrameSourceGroup> : produce_base<D, Windows::Media::Capture::Frames::IMediaFrameSourceGroup> { HRESULT __stdcall get_Id(abi_arg_out<hstring> value) noexcept override { try { *value = detach(this->shim().Id()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall get_DisplayName(abi_arg_out<hstring> value) noexcept override { try { *value = detach(this->shim().DisplayName()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall get_SourceInfos(abi_arg_out<Windows::Foundation::Collections::IVectorView<Windows::Media::Capture::Frames::MediaFrameSourceInfo>> value) noexcept override { try { *value = detach(this->shim().SourceInfos()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Media::Capture::Frames::IMediaFrameSourceGroupStatics> : produce_base<D, Windows::Media::Capture::Frames::IMediaFrameSourceGroupStatics> { HRESULT __stdcall abi_FindAllAsync(abi_arg_out<Windows::Foundation::IAsyncOperation<Windows::Foundation::Collections::IVectorView<Windows::Media::Capture::Frames::MediaFrameSourceGroup>>> value) noexcept override { try { *value = detach(this->shim().FindAllAsync()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall abi_FromIdAsync(abi_arg_in<hstring> id, abi_arg_out<Windows::Foundation::IAsyncOperation<Windows::Media::Capture::Frames::MediaFrameSourceGroup>> value) noexcept override { try { *value = detach(this->shim().FromIdAsync(*reinterpret_cast<const hstring *>(&id))); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall abi_GetDeviceSelector(abi_arg_out<hstring> value) noexcept override { try { *value = detach(this->shim().GetDeviceSelector()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Media::Capture::Frames::IMediaFrameSourceInfo> : produce_base<D, Windows::Media::Capture::Frames::IMediaFrameSourceInfo> { HRESULT __stdcall get_Id(abi_arg_out<hstring> value) noexcept override { try { *value = detach(this->shim().Id()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall get_MediaStreamType(Windows::Media::Capture::MediaStreamType * value) noexcept override { try { *value = detach(this->shim().MediaStreamType()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_SourceKind(Windows::Media::Capture::Frames::MediaFrameSourceKind * value) noexcept override { try { *value = detach(this->shim().SourceKind()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_SourceGroup(abi_arg_out<Windows::Media::Capture::Frames::IMediaFrameSourceGroup> value) noexcept override { try { *value = detach(this->shim().SourceGroup()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall get_DeviceInformation(abi_arg_out<Windows::Devices::Enumeration::IDeviceInformation> value) noexcept override { try { *value = detach(this->shim().DeviceInformation()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall get_Properties(abi_arg_out<Windows::Foundation::Collections::IMapView<GUID, Windows::IInspectable>> value) noexcept override { try { *value = detach(this->shim().Properties()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall get_CoordinateSystem(abi_arg_out<Windows::Perception::Spatial::ISpatialCoordinateSystem> value) noexcept override { try { *value = detach(this->shim().CoordinateSystem()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Media::Capture::Frames::IVideoMediaFrame> : produce_base<D, Windows::Media::Capture::Frames::IVideoMediaFrame> { HRESULT __stdcall get_FrameReference(abi_arg_out<Windows::Media::Capture::Frames::IMediaFrameReference> value) noexcept override { try { *value = detach(this->shim().FrameReference()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall get_VideoFormat(abi_arg_out<Windows::Media::Capture::Frames::IVideoMediaFrameFormat> value) noexcept override { try { *value = detach(this->shim().VideoFormat()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall get_SoftwareBitmap(abi_arg_out<Windows::Graphics::Imaging::ISoftwareBitmap> value) noexcept override { try { *value = detach(this->shim().SoftwareBitmap()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall get_Direct3DSurface(abi_arg_out<Windows::Graphics::DirectX::Direct3D11::IDirect3DSurface> value) noexcept override { try { *value = detach(this->shim().Direct3DSurface()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall get_CameraIntrinsics(abi_arg_out<Windows::Media::Devices::Core::ICameraIntrinsics> value) noexcept override { try { *value = detach(this->shim().CameraIntrinsics()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall get_InfraredMediaFrame(abi_arg_out<Windows::Media::Capture::Frames::IInfraredMediaFrame> value) noexcept override { try { *value = detach(this->shim().InfraredMediaFrame()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall get_DepthMediaFrame(abi_arg_out<Windows::Media::Capture::Frames::IDepthMediaFrame> value) noexcept override { try { *value = detach(this->shim().DepthMediaFrame()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall abi_GetVideoFrame(abi_arg_out<Windows::Media::IVideoFrame> value) noexcept override { try { *value = detach(this->shim().GetVideoFrame()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Media::Capture::Frames::IVideoMediaFrameFormat> : produce_base<D, Windows::Media::Capture::Frames::IVideoMediaFrameFormat> { HRESULT __stdcall get_MediaFrameFormat(abi_arg_out<Windows::Media::Capture::Frames::IMediaFrameFormat> value) noexcept override { try { *value = detach(this->shim().MediaFrameFormat()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall get_DepthFormat(abi_arg_out<Windows::Media::Capture::Frames::IDepthMediaFrameFormat> value) noexcept override { try { *value = detach(this->shim().DepthFormat()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall get_Width(uint32_t * value) noexcept override { try { *value = detach(this->shim().Width()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_Height(uint32_t * value) noexcept override { try { *value = detach(this->shim().Height()); return S_OK; } catch (...) { return impl::to_hresult(); } } }; } namespace Windows::Media::Capture::Frames { template <typename D> hstring impl_IMediaFrameSourceGroup<D>::Id() const { hstring value; check_hresult(static_cast<const IMediaFrameSourceGroup &>(static_cast<const D &>(*this))->get_Id(put(value))); return value; } template <typename D> hstring impl_IMediaFrameSourceGroup<D>::DisplayName() const { hstring value; check_hresult(static_cast<const IMediaFrameSourceGroup &>(static_cast<const D &>(*this))->get_DisplayName(put(value))); return value; } template <typename D> Windows::Foundation::Collections::IVectorView<Windows::Media::Capture::Frames::MediaFrameSourceInfo> impl_IMediaFrameSourceGroup<D>::SourceInfos() const { Windows::Foundation::Collections::IVectorView<Windows::Media::Capture::Frames::MediaFrameSourceInfo> value; check_hresult(static_cast<const IMediaFrameSourceGroup &>(static_cast<const D &>(*this))->get_SourceInfos(put(value))); return value; } template <typename D> Windows::Foundation::IAsyncOperation<Windows::Foundation::Collections::IVectorView<Windows::Media::Capture::Frames::MediaFrameSourceGroup>> impl_IMediaFrameSourceGroupStatics<D>::FindAllAsync() const { Windows::Foundation::IAsyncOperation<Windows::Foundation::Collections::IVectorView<Windows::Media::Capture::Frames::MediaFrameSourceGroup>> value; check_hresult(static_cast<const IMediaFrameSourceGroupStatics &>(static_cast<const D &>(*this))->abi_FindAllAsync(put(value))); return value; } template <typename D> Windows::Foundation::IAsyncOperation<Windows::Media::Capture::Frames::MediaFrameSourceGroup> impl_IMediaFrameSourceGroupStatics<D>::FromIdAsync(hstring_ref id) const { Windows::Foundation::IAsyncOperation<Windows::Media::Capture::Frames::MediaFrameSourceGroup> value; check_hresult(static_cast<const IMediaFrameSourceGroupStatics &>(static_cast<const D &>(*this))->abi_FromIdAsync(get(id), put(value))); return value; } template <typename D> hstring impl_IMediaFrameSourceGroupStatics<D>::GetDeviceSelector() const { hstring value; check_hresult(static_cast<const IMediaFrameSourceGroupStatics &>(static_cast<const D &>(*this))->abi_GetDeviceSelector(put(value))); return value; } template <typename D> hstring impl_IMediaFrameSourceInfo<D>::Id() const { hstring value; check_hresult(static_cast<const IMediaFrameSourceInfo &>(static_cast<const D &>(*this))->get_Id(put(value))); return value; } template <typename D> Windows::Media::Capture::MediaStreamType impl_IMediaFrameSourceInfo<D>::MediaStreamType() const { Windows::Media::Capture::MediaStreamType value {}; check_hresult(static_cast<const IMediaFrameSourceInfo &>(static_cast<const D &>(*this))->get_MediaStreamType(&value)); return value; } template <typename D> Windows::Media::Capture::Frames::MediaFrameSourceKind impl_IMediaFrameSourceInfo<D>::SourceKind() const { Windows::Media::Capture::Frames::MediaFrameSourceKind value {}; check_hresult(static_cast<const IMediaFrameSourceInfo &>(static_cast<const D &>(*this))->get_SourceKind(&value)); return value; } template <typename D> Windows::Media::Capture::Frames::MediaFrameSourceGroup impl_IMediaFrameSourceInfo<D>::SourceGroup() const { Windows::Media::Capture::Frames::MediaFrameSourceGroup value { nullptr }; check_hresult(static_cast<const IMediaFrameSourceInfo &>(static_cast<const D &>(*this))->get_SourceGroup(put(value))); return value; } template <typename D> Windows::Devices::Enumeration::DeviceInformation impl_IMediaFrameSourceInfo<D>::DeviceInformation() const { Windows::Devices::Enumeration::DeviceInformation value { nullptr }; check_hresult(static_cast<const IMediaFrameSourceInfo &>(static_cast<const D &>(*this))->get_DeviceInformation(put(value))); return value; } template <typename D> Windows::Foundation::Collections::IMapView<GUID, Windows::IInspectable> impl_IMediaFrameSourceInfo<D>::Properties() const { Windows::Foundation::Collections::IMapView<GUID, Windows::IInspectable> value; check_hresult(static_cast<const IMediaFrameSourceInfo &>(static_cast<const D &>(*this))->get_Properties(put(value))); return value; } template <typename D> Windows::Perception::Spatial::SpatialCoordinateSystem impl_IMediaFrameSourceInfo<D>::CoordinateSystem() const { Windows::Perception::Spatial::SpatialCoordinateSystem value { nullptr }; check_hresult(static_cast<const IMediaFrameSourceInfo &>(static_cast<const D &>(*this))->get_CoordinateSystem(put(value))); return value; } template <typename D> Windows::Media::Capture::Frames::MediaFrameSourceInfo impl_IMediaFrameSource<D>::Info() const { Windows::Media::Capture::Frames::MediaFrameSourceInfo value { nullptr }; check_hresult(static_cast<const IMediaFrameSource &>(static_cast<const D &>(*this))->get_Info(put(value))); return value; } template <typename D> Windows::Media::Capture::Frames::MediaFrameSourceController impl_IMediaFrameSource<D>::Controller() const { Windows::Media::Capture::Frames::MediaFrameSourceController value { nullptr }; check_hresult(static_cast<const IMediaFrameSource &>(static_cast<const D &>(*this))->get_Controller(put(value))); return value; } template <typename D> Windows::Foundation::Collections::IVectorView<Windows::Media::Capture::Frames::MediaFrameFormat> impl_IMediaFrameSource<D>::SupportedFormats() const { Windows::Foundation::Collections::IVectorView<Windows::Media::Capture::Frames::MediaFrameFormat> value; check_hresult(static_cast<const IMediaFrameSource &>(static_cast<const D &>(*this))->get_SupportedFormats(put(value))); return value; } template <typename D> Windows::Media::Capture::Frames::MediaFrameFormat impl_IMediaFrameSource<D>::CurrentFormat() const { Windows::Media::Capture::Frames::MediaFrameFormat value { nullptr }; check_hresult(static_cast<const IMediaFrameSource &>(static_cast<const D &>(*this))->get_CurrentFormat(put(value))); return value; } template <typename D> Windows::Foundation::IAsyncAction impl_IMediaFrameSource<D>::SetFormatAsync(const Windows::Media::Capture::Frames::MediaFrameFormat & format) const { Windows::Foundation::IAsyncAction value; check_hresult(static_cast<const IMediaFrameSource &>(static_cast<const D &>(*this))->abi_SetFormatAsync(get(format), put(value))); return value; } template <typename D> event_token impl_IMediaFrameSource<D>::FormatChanged(const Windows::Foundation::TypedEventHandler<Windows::Media::Capture::Frames::MediaFrameSource, Windows::IInspectable> & handler) const { event_token token {}; check_hresult(static_cast<const IMediaFrameSource &>(static_cast<const D &>(*this))->add_FormatChanged(get(handler), &token)); return token; } template <typename D> event_revoker<IMediaFrameSource> impl_IMediaFrameSource<D>::FormatChanged(auto_revoke_t, const Windows::Foundation::TypedEventHandler<Windows::Media::Capture::Frames::MediaFrameSource, Windows::IInspectable> & handler) const { return impl::make_event_revoker<D, IMediaFrameSource>(this, &ABI::Windows::Media::Capture::Frames::IMediaFrameSource::remove_FormatChanged, FormatChanged(handler)); } template <typename D> void impl_IMediaFrameSource<D>::FormatChanged(event_token token) const { check_hresult(static_cast<const IMediaFrameSource &>(static_cast<const D &>(*this))->remove_FormatChanged(token)); } template <typename D> Windows::Media::Devices::Core::CameraIntrinsics impl_IMediaFrameSource<D>::TryGetCameraIntrinsics(const Windows::Media::Capture::Frames::MediaFrameFormat & format) const { Windows::Media::Devices::Core::CameraIntrinsics value { nullptr }; check_hresult(static_cast<const IMediaFrameSource &>(static_cast<const D &>(*this))->abi_TryGetCameraIntrinsics(get(format), put(value))); return value; } template <typename D> event_token impl_IMediaFrameReader<D>::FrameArrived(const Windows::Foundation::TypedEventHandler<Windows::Media::Capture::Frames::MediaFrameReader, Windows::Media::Capture::Frames::MediaFrameArrivedEventArgs> & handler) const { event_token token {}; check_hresult(static_cast<const IMediaFrameReader &>(static_cast<const D &>(*this))->add_FrameArrived(get(handler), &token)); return token; } template <typename D> event_revoker<IMediaFrameReader> impl_IMediaFrameReader<D>::FrameArrived(auto_revoke_t, const Windows::Foundation::TypedEventHandler<Windows::Media::Capture::Frames::MediaFrameReader, Windows::Media::Capture::Frames::MediaFrameArrivedEventArgs> & handler) const { return impl::make_event_revoker<D, IMediaFrameReader>(this, &ABI::Windows::Media::Capture::Frames::IMediaFrameReader::remove_FrameArrived, FrameArrived(handler)); } template <typename D> void impl_IMediaFrameReader<D>::FrameArrived(event_token token) const { check_hresult(static_cast<const IMediaFrameReader &>(static_cast<const D &>(*this))->remove_FrameArrived(token)); } template <typename D> Windows::Media::Capture::Frames::MediaFrameReference impl_IMediaFrameReader<D>::TryAcquireLatestFrame() const { Windows::Media::Capture::Frames::MediaFrameReference value { nullptr }; check_hresult(static_cast<const IMediaFrameReader &>(static_cast<const D &>(*this))->abi_TryAcquireLatestFrame(put(value))); return value; } template <typename D> Windows::Foundation::IAsyncOperation<winrt::Windows::Media::Capture::Frames::MediaFrameReaderStartStatus> impl_IMediaFrameReader<D>::StartAsync() const { Windows::Foundation::IAsyncOperation<winrt::Windows::Media::Capture::Frames::MediaFrameReaderStartStatus> operation; check_hresult(static_cast<const IMediaFrameReader &>(static_cast<const D &>(*this))->abi_StartAsync(put(operation))); return operation; } template <typename D> Windows::Foundation::IAsyncAction impl_IMediaFrameReader<D>::StopAsync() const { Windows::Foundation::IAsyncAction action; check_hresult(static_cast<const IMediaFrameReader &>(static_cast<const D &>(*this))->abi_StopAsync(put(action))); return action; } template <typename D> Windows::Foundation::IAsyncOperation<Windows::Media::Capture::Frames::MediaFrameSourceGetPropertyResult> impl_IMediaFrameSourceController<D>::GetPropertyAsync(hstring_ref propertyId) const { Windows::Foundation::IAsyncOperation<Windows::Media::Capture::Frames::MediaFrameSourceGetPropertyResult> value; check_hresult(static_cast<const IMediaFrameSourceController &>(static_cast<const D &>(*this))->abi_GetPropertyAsync(get(propertyId), put(value))); return value; } template <typename D> Windows::Foundation::IAsyncOperation<winrt::Windows::Media::Capture::Frames::MediaFrameSourceSetPropertyStatus> impl_IMediaFrameSourceController<D>::SetPropertyAsync(hstring_ref propertyId, const Windows::IInspectable & propertyValue) const { Windows::Foundation::IAsyncOperation<winrt::Windows::Media::Capture::Frames::MediaFrameSourceSetPropertyStatus> value; check_hresult(static_cast<const IMediaFrameSourceController &>(static_cast<const D &>(*this))->abi_SetPropertyAsync(get(propertyId), get(propertyValue), put(value))); return value; } template <typename D> Windows::Media::Devices::VideoDeviceController impl_IMediaFrameSourceController<D>::VideoDeviceController() const { Windows::Media::Devices::VideoDeviceController value { nullptr }; check_hresult(static_cast<const IMediaFrameSourceController &>(static_cast<const D &>(*this))->get_VideoDeviceController(put(value))); return value; } template <typename D> Windows::Media::Capture::Frames::MediaFrameSourceGetPropertyStatus impl_IMediaFrameSourceGetPropertyResult<D>::Status() const { Windows::Media::Capture::Frames::MediaFrameSourceGetPropertyStatus value {}; check_hresult(static_cast<const IMediaFrameSourceGetPropertyResult &>(static_cast<const D &>(*this))->get_Status(&value)); return value; } template <typename D> Windows::IInspectable impl_IMediaFrameSourceGetPropertyResult<D>::Value() const { Windows::IInspectable value; check_hresult(static_cast<const IMediaFrameSourceGetPropertyResult &>(static_cast<const D &>(*this))->get_Value(put(value))); return value; } template <typename D> hstring impl_IMediaFrameFormat<D>::MajorType() const { hstring value; check_hresult(static_cast<const IMediaFrameFormat &>(static_cast<const D &>(*this))->get_MajorType(put(value))); return value; } template <typename D> hstring impl_IMediaFrameFormat<D>::Subtype() const { hstring value; check_hresult(static_cast<const IMediaFrameFormat &>(static_cast<const D &>(*this))->get_Subtype(put(value))); return value; } template <typename D> Windows::Media::MediaProperties::MediaRatio impl_IMediaFrameFormat<D>::FrameRate() const { Windows::Media::MediaProperties::MediaRatio value { nullptr }; check_hresult(static_cast<const IMediaFrameFormat &>(static_cast<const D &>(*this))->get_FrameRate(put(value))); return value; } template <typename D> Windows::Foundation::Collections::IMapView<GUID, Windows::IInspectable> impl_IMediaFrameFormat<D>::Properties() const { Windows::Foundation::Collections::IMapView<GUID, Windows::IInspectable> value; check_hresult(static_cast<const IMediaFrameFormat &>(static_cast<const D &>(*this))->get_Properties(put(value))); return value; } template <typename D> Windows::Media::Capture::Frames::VideoMediaFrameFormat impl_IMediaFrameFormat<D>::VideoFormat() const { Windows::Media::Capture::Frames::VideoMediaFrameFormat value { nullptr }; check_hresult(static_cast<const IMediaFrameFormat &>(static_cast<const D &>(*this))->get_VideoFormat(put(value))); return value; } template <typename D> Windows::Media::Capture::Frames::MediaFrameFormat impl_IVideoMediaFrameFormat<D>::MediaFrameFormat() const { Windows::Media::Capture::Frames::MediaFrameFormat value { nullptr }; check_hresult(static_cast<const IVideoMediaFrameFormat &>(static_cast<const D &>(*this))->get_MediaFrameFormat(put(value))); return value; } template <typename D> Windows::Media::Capture::Frames::DepthMediaFrameFormat impl_IVideoMediaFrameFormat<D>::DepthFormat() const { Windows::Media::Capture::Frames::DepthMediaFrameFormat value { nullptr }; check_hresult(static_cast<const IVideoMediaFrameFormat &>(static_cast<const D &>(*this))->get_DepthFormat(put(value))); return value; } template <typename D> uint32_t impl_IVideoMediaFrameFormat<D>::Width() const { uint32_t value {}; check_hresult(static_cast<const IVideoMediaFrameFormat &>(static_cast<const D &>(*this))->get_Width(&value)); return value; } template <typename D> uint32_t impl_IVideoMediaFrameFormat<D>::Height() const { uint32_t value {}; check_hresult(static_cast<const IVideoMediaFrameFormat &>(static_cast<const D &>(*this))->get_Height(&value)); return value; } template <typename D> Windows::Media::Capture::Frames::MediaFrameSourceKind impl_IMediaFrameReference<D>::SourceKind() const { Windows::Media::Capture::Frames::MediaFrameSourceKind value {}; check_hresult(static_cast<const IMediaFrameReference &>(static_cast<const D &>(*this))->get_SourceKind(&value)); return value; } template <typename D> Windows::Media::Capture::Frames::MediaFrameFormat impl_IMediaFrameReference<D>::Format() const { Windows::Media::Capture::Frames::MediaFrameFormat value { nullptr }; check_hresult(static_cast<const IMediaFrameReference &>(static_cast<const D &>(*this))->get_Format(put(value))); return value; } template <typename D> Windows::Foundation::IReference<Windows::Foundation::TimeSpan> impl_IMediaFrameReference<D>::SystemRelativeTime() const { Windows::Foundation::IReference<Windows::Foundation::TimeSpan> value; check_hresult(static_cast<const IMediaFrameReference &>(static_cast<const D &>(*this))->get_SystemRelativeTime(put(value))); return value; } template <typename D> Windows::Foundation::TimeSpan impl_IMediaFrameReference<D>::Duration() const { Windows::Foundation::TimeSpan value {}; check_hresult(static_cast<const IMediaFrameReference &>(static_cast<const D &>(*this))->get_Duration(put(value))); return value; } template <typename D> Windows::Foundation::Collections::IMapView<GUID, Windows::IInspectable> impl_IMediaFrameReference<D>::Properties() const { Windows::Foundation::Collections::IMapView<GUID, Windows::IInspectable> value; check_hresult(static_cast<const IMediaFrameReference &>(static_cast<const D &>(*this))->get_Properties(put(value))); return value; } template <typename D> Windows::Media::Capture::Frames::BufferMediaFrame impl_IMediaFrameReference<D>::BufferMediaFrame() const { Windows::Media::Capture::Frames::BufferMediaFrame value { nullptr }; check_hresult(static_cast<const IMediaFrameReference &>(static_cast<const D &>(*this))->get_BufferMediaFrame(put(value))); return value; } template <typename D> Windows::Media::Capture::Frames::VideoMediaFrame impl_IMediaFrameReference<D>::VideoMediaFrame() const { Windows::Media::Capture::Frames::VideoMediaFrame value { nullptr }; check_hresult(static_cast<const IMediaFrameReference &>(static_cast<const D &>(*this))->get_VideoMediaFrame(put(value))); return value; } template <typename D> Windows::Perception::Spatial::SpatialCoordinateSystem impl_IMediaFrameReference<D>::CoordinateSystem() const { Windows::Perception::Spatial::SpatialCoordinateSystem value { nullptr }; check_hresult(static_cast<const IMediaFrameReference &>(static_cast<const D &>(*this))->get_CoordinateSystem(put(value))); return value; } template <typename D> Windows::Media::Capture::Frames::MediaFrameReference impl_IBufferMediaFrame<D>::FrameReference() const { Windows::Media::Capture::Frames::MediaFrameReference value { nullptr }; check_hresult(static_cast<const IBufferMediaFrame &>(static_cast<const D &>(*this))->get_FrameReference(put(value))); return value; } template <typename D> Windows::Storage::Streams::IBuffer impl_IBufferMediaFrame<D>::Buffer() const { Windows::Storage::Streams::IBuffer value; check_hresult(static_cast<const IBufferMediaFrame &>(static_cast<const D &>(*this))->get_Buffer(put(value))); return value; } template <typename D> Windows::Media::Capture::Frames::MediaFrameReference impl_IVideoMediaFrame<D>::FrameReference() const { Windows::Media::Capture::Frames::MediaFrameReference value { nullptr }; check_hresult(static_cast<const IVideoMediaFrame &>(static_cast<const D &>(*this))->get_FrameReference(put(value))); return value; } template <typename D> Windows::Media::Capture::Frames::VideoMediaFrameFormat impl_IVideoMediaFrame<D>::VideoFormat() const { Windows::Media::Capture::Frames::VideoMediaFrameFormat value { nullptr }; check_hresult(static_cast<const IVideoMediaFrame &>(static_cast<const D &>(*this))->get_VideoFormat(put(value))); return value; } template <typename D> Windows::Graphics::Imaging::SoftwareBitmap impl_IVideoMediaFrame<D>::SoftwareBitmap() const { Windows::Graphics::Imaging::SoftwareBitmap value { nullptr }; check_hresult(static_cast<const IVideoMediaFrame &>(static_cast<const D &>(*this))->get_SoftwareBitmap(put(value))); return value; } template <typename D> Windows::Graphics::DirectX::Direct3D11::IDirect3DSurface impl_IVideoMediaFrame<D>::Direct3DSurface() const { Windows::Graphics::DirectX::Direct3D11::IDirect3DSurface value; check_hresult(static_cast<const IVideoMediaFrame &>(static_cast<const D &>(*this))->get_Direct3DSurface(put(value))); return value; } template <typename D> Windows::Media::Devices::Core::CameraIntrinsics impl_IVideoMediaFrame<D>::CameraIntrinsics() const { Windows::Media::Devices::Core::CameraIntrinsics value { nullptr }; check_hresult(static_cast<const IVideoMediaFrame &>(static_cast<const D &>(*this))->get_CameraIntrinsics(put(value))); return value; } template <typename D> Windows::Media::Capture::Frames::InfraredMediaFrame impl_IVideoMediaFrame<D>::InfraredMediaFrame() const { Windows::Media::Capture::Frames::InfraredMediaFrame value { nullptr }; check_hresult(static_cast<const IVideoMediaFrame &>(static_cast<const D &>(*this))->get_InfraredMediaFrame(put(value))); return value; } template <typename D> Windows::Media::Capture::Frames::DepthMediaFrame impl_IVideoMediaFrame<D>::DepthMediaFrame() const { Windows::Media::Capture::Frames::DepthMediaFrame value { nullptr }; check_hresult(static_cast<const IVideoMediaFrame &>(static_cast<const D &>(*this))->get_DepthMediaFrame(put(value))); return value; } template <typename D> Windows::Media::VideoFrame impl_IVideoMediaFrame<D>::GetVideoFrame() const { Windows::Media::VideoFrame value { nullptr }; check_hresult(static_cast<const IVideoMediaFrame &>(static_cast<const D &>(*this))->abi_GetVideoFrame(put(value))); return value; } template <typename D> Windows::Media::Capture::Frames::MediaFrameReference impl_IInfraredMediaFrame<D>::FrameReference() const { Windows::Media::Capture::Frames::MediaFrameReference value { nullptr }; check_hresult(static_cast<const IInfraredMediaFrame &>(static_cast<const D &>(*this))->get_FrameReference(put(value))); return value; } template <typename D> Windows::Media::Capture::Frames::VideoMediaFrame impl_IInfraredMediaFrame<D>::VideoMediaFrame() const { Windows::Media::Capture::Frames::VideoMediaFrame value { nullptr }; check_hresult(static_cast<const IInfraredMediaFrame &>(static_cast<const D &>(*this))->get_VideoMediaFrame(put(value))); return value; } template <typename D> bool impl_IInfraredMediaFrame<D>::IsIlluminated() const { bool value {}; check_hresult(static_cast<const IInfraredMediaFrame &>(static_cast<const D &>(*this))->get_IsIlluminated(&value)); return value; } template <typename D> Windows::Media::Capture::Frames::MediaFrameReference impl_IDepthMediaFrame<D>::FrameReference() const { Windows::Media::Capture::Frames::MediaFrameReference value { nullptr }; check_hresult(static_cast<const IDepthMediaFrame &>(static_cast<const D &>(*this))->get_FrameReference(put(value))); return value; } template <typename D> Windows::Media::Capture::Frames::VideoMediaFrame impl_IDepthMediaFrame<D>::VideoMediaFrame() const { Windows::Media::Capture::Frames::VideoMediaFrame value { nullptr }; check_hresult(static_cast<const IDepthMediaFrame &>(static_cast<const D &>(*this))->get_VideoMediaFrame(put(value))); return value; } template <typename D> Windows::Media::Capture::Frames::DepthMediaFrameFormat impl_IDepthMediaFrame<D>::DepthFormat() const { Windows::Media::Capture::Frames::DepthMediaFrameFormat value { nullptr }; check_hresult(static_cast<const IDepthMediaFrame &>(static_cast<const D &>(*this))->get_DepthFormat(put(value))); return value; } template <typename D> Windows::Media::Devices::Core::DepthCorrelatedCoordinateMapper impl_IDepthMediaFrame<D>::TryCreateCoordinateMapper(const Windows::Media::Devices::Core::CameraIntrinsics & cameraIntrinsics, const Windows::Perception::Spatial::SpatialCoordinateSystem & coordinateSystem) const { Windows::Media::Devices::Core::DepthCorrelatedCoordinateMapper value { nullptr }; check_hresult(static_cast<const IDepthMediaFrame &>(static_cast<const D &>(*this))->abi_TryCreateCoordinateMapper(get(cameraIntrinsics), get(coordinateSystem), put(value))); return value; } template <typename D> Windows::Media::Capture::Frames::VideoMediaFrameFormat impl_IDepthMediaFrameFormat<D>::VideoFormat() const { Windows::Media::Capture::Frames::VideoMediaFrameFormat value { nullptr }; check_hresult(static_cast<const IDepthMediaFrameFormat &>(static_cast<const D &>(*this))->get_VideoFormat(put(value))); return value; } template <typename D> double impl_IDepthMediaFrameFormat<D>::DepthScaleInMeters() const { double value {}; check_hresult(static_cast<const IDepthMediaFrameFormat &>(static_cast<const D &>(*this))->get_DepthScaleInMeters(&value)); return value; } inline Windows::Foundation::IAsyncOperation<Windows::Foundation::Collections::IVectorView<Windows::Media::Capture::Frames::MediaFrameSourceGroup>> MediaFrameSourceGroup::FindAllAsync() { return get_activation_factory<MediaFrameSourceGroup, IMediaFrameSourceGroupStatics>().FindAllAsync(); } inline Windows::Foundation::IAsyncOperation<Windows::Media::Capture::Frames::MediaFrameSourceGroup> MediaFrameSourceGroup::FromIdAsync(hstring_ref id) { return get_activation_factory<MediaFrameSourceGroup, IMediaFrameSourceGroupStatics>().FromIdAsync(id); } inline hstring MediaFrameSourceGroup::GetDeviceSelector() { return get_activation_factory<MediaFrameSourceGroup, IMediaFrameSourceGroupStatics>().GetDeviceSelector(); } } }
35.642196
317
0.658904
d8795bbdf3e44dacb30635e46dbb8dbf877a31eb
1,531
h
C
_external/codex/inc/shared/native/wrappers/crt_short/crtdefs.h
fengjixuchui/napoca
ed26609ab9a3ea12d12882b311dcb332dc759d32
[ "Apache-2.0" ]
170
2020-07-30T15:04:59.000Z
2022-03-24T10:59:29.000Z
_external/codex/inc/shared/native/wrappers/crt_short/crtdefs.h
a-cristi/napoca
ed6691125bf703366581e47a1fe789167009c24a
[ "Apache-2.0" ]
3
2020-08-10T09:16:56.000Z
2022-02-18T21:40:43.000Z
_external/codex/inc/shared/native/wrappers/crt_short/crtdefs.h
a-cristi/napoca
ed6691125bf703366581e47a1fe789167009c24a
[ "Apache-2.0" ]
44
2020-07-30T15:06:55.000Z
2022-02-25T08:55:55.000Z
/* * Copyright (c) 2020 Bitdefender * SPDX-License-Identifier: Apache-2.0 */ #ifdef crt_INC_SETTINGS_CRTDEFS_H #include crt_INC_SETTINGS_CRTDEFS_H // define it to some .h file name/path if you want to provide settings #endif #ifndef _CRT_CRTDEFS_WRAPPER_ #define _CRT_CRTDEFS_WRAPPER_ #include "crt/crt_crtdefs.h" #if ( !defined(CRT_SKIP_DECL_DBG_UNREFERENCED_PARAMETER) && (!defined(CRT_DEFAULT_SKIP_CRTDEFS_H_DECL) || defined(CRT_WANT_DECL_DBG_UNREFERENCED_PARAMETER)) ) #define DBG_UNREFERENCED_PARAMETER CRT_DBG_UNREFERENCED_PARAMETER #endif #if ( !defined(CRT_SKIP_DECL_REL_UNREFERENCED_PARAMETER) && (!defined(CRT_DEFAULT_SKIP_CRTDEFS_H_DECL) || defined(CRT_WANT_DECL_REL_UNREFERENCED_PARAMETER)) ) #define REL_UNREFERENCED_PARAMETER CRT_REL_UNREFERENCED_PARAMETER #endif #if ( !defined(CRT_SKIP_DECL_UNREFERENCED_LOCAL_VARIABLE) && (!defined(CRT_DEFAULT_SKIP_CRTDEFS_H_DECL) || defined(CRT_WANT_DECL_UNREFERENCED_LOCAL_VARIABLE)) ) #define UNREFERENCED_LOCAL_VARIABLE CRT_UNREFERENCED_LOCAL_VARIABLE #endif #if ( !defined(CRT_SKIP_DECL_UNREFERENCED_PARAMETER) && (!defined(CRT_DEFAULT_SKIP_CRTDEFS_H_DECL) || defined(CRT_WANT_DECL_UNREFERENCED_PARAMETER)) ) #define UNREFERENCED_PARAMETER CRT_UNREFERENCED_PARAMETER #endif #if ( !defined(CRT_SKIP_DECL___ELEMENTARY_DEFINITIONS) && (!defined(CRT_DEFAULT_SKIP_CRTDEFS_H_DECL) || defined(CRT_WANT_DECL___ELEMENTARY_DEFINITIONS)) ) #define __ELEMENTARY_DEFINITIONS __CRT_ELEMENTARY_DEFINITIONS #endif #endif //_CRT_CRTDEFS_WRAPPER_
40.289474
161
0.824951
d87b797df36db35233ea36c1ae0ca3c5973b96b4
176
h
C
AdvancedNSOperations/AdvancedNSOperations/ViewController.h
aokizen/AdvancedNSOperations-OC
0cab5dd45d02235ad9fb04ff6948c79fbefd9a19
[ "MIT" ]
null
null
null
AdvancedNSOperations/AdvancedNSOperations/ViewController.h
aokizen/AdvancedNSOperations-OC
0cab5dd45d02235ad9fb04ff6948c79fbefd9a19
[ "MIT" ]
null
null
null
AdvancedNSOperations/AdvancedNSOperations/ViewController.h
aokizen/AdvancedNSOperations-OC
0cab5dd45d02235ad9fb04ff6948c79fbefd9a19
[ "MIT" ]
null
null
null
// // ViewController.h // AdvancedNSOperations // // Created by Jiangwei Wu on 16/1/12. // // #import <UIKit/UIKit.h> @interface ViewController : UIViewController @end
11
44
0.681818
d87bdbe58f8716fd37eda067e617180bab6e3d45
905
h
C
explode/mcl/mcl-options.h
wenhuizhang/FiSC
228d1c1a0f9a17985039c9d03d0bb0f0d5ae28f4
[ "Apache-2.0" ]
null
null
null
explode/mcl/mcl-options.h
wenhuizhang/FiSC
228d1c1a0f9a17985039c9d03d0bb0f0d5ae28f4
[ "Apache-2.0" ]
null
null
null
explode/mcl/mcl-options.h
wenhuizhang/FiSC
228d1c1a0f9a17985039c9d03d0bb0f0d5ae28f4
[ "Apache-2.0" ]
null
null
null
// DO NOT EDIT -- automatically generated by ../gen-opt.pl // from mcl.default.options // stop being C compatible, to simplify things. The entire code base // is in C++ now, except the kernel drivers. Can always create a C interface // if need be. #ifndef __mcl_OPTIONS_H #define __mcl_OPTIONS_H extern const char* __mcl__ckpt_file; extern int __mcl__ckpt_states; extern int __mcl__clear_on_bug_exit; extern int __mcl__max_bugs; extern int __mcl__max_state; extern int __mcl__persistent; extern int __mcl__random_seed; extern int __mcl__reboot_crashes; extern int __mcl__simulation; extern int __mcl__simulation_length; extern const char* __mcl__state_queue; extern const char* __mcl__trace_dir; extern int __mcl__verbose; extern const char* __monitor__addr; extern int __monitor__port; extern int __monitor__timeout; extern int __monitor__use_vm; extern const char* __monitor__vm_path; #endif
26.617647
78
0.812155
d87ff6c29d7f5acafc1f4ea1e53bc78cd7d3b270
370
h
C
Sources/HotelManagerCompta/BDCompteResultat.h
baudoliver7/hotel-manager-plus
17c5e0090c8f9135e7fd14964d27a994c1852b72
[ "MIT" ]
1
2020-12-09T14:42:17.000Z
2020-12-09T14:42:17.000Z
Sources/HotelManagerCompta/BDCompteResultat.h
baudoliver7/hotel-manager-plus
17c5e0090c8f9135e7fd14964d27a994c1852b72
[ "MIT" ]
null
null
null
Sources/HotelManagerCompta/BDCompteResultat.h
baudoliver7/hotel-manager-plus
17c5e0090c8f9135e7fd14964d27a994c1852b72
[ "MIT" ]
null
null
null
#ifndef BDCOMPTERESULTAT_H #define BDCOMPTERESULTAT_H #include <QDialog> namespace Ui { class BDCompteResultat; } class BDCompteResultat : public QDialog { Q_OBJECT public: BDCompteResultat(QWidget *parent = 0); ~BDCompteResultat(); protected: void changeEvent(QEvent *e); private: Ui::BDCompteResultat *ui; }; #endif // BDCOMPTERESULTAT_H
15.416667
42
0.727027
d8808c97e1af3b4346a0fbc2d0e1b553019c5c1c
1,558
h
C
Factory Engin3D/ModuleGameObject.h
OscarHernandezG/3D_Engine
b5b7a4784a1432a45dfd85caa5be2e098d5741c7
[ "MIT" ]
1
2018-11-14T23:53:53.000Z
2018-11-14T23:53:53.000Z
Factory Engin3D/ModuleGameObject.h
OscarHernandezG/3D_Engine
b5b7a4784a1432a45dfd85caa5be2e098d5741c7
[ "MIT" ]
1
2019-03-15T09:53:58.000Z
2019-03-15T09:54:46.000Z
Factory Engin3D/ModuleGameObject.h
OscarHernandezG/3D_Engine
b5b7a4784a1432a45dfd85caa5be2e098d5741c7
[ "MIT" ]
2
2019-02-04T15:55:15.000Z
2019-10-26T23:51:42.000Z
#ifndef __ModuleGameObject_H__ #define __ModuleGameObject_H__ #include "Module.h" #include "ComponentTransform.h" #include "GameObject.h" #include <map> class ModuleGameObject : public Module { friend class GameObject; public: ModuleGameObject(Application* app, bool start_enabled = true); ~ModuleGameObject(); bool Start(); update_status Update(); update_status PostUpdate(); void RemoveObjectsFromList(GameObject * it, std::list<GameObject*> &toDelete); bool CleanUp(); void CleanAllGameObjects(); void SaveScene(const char* name); void LoadScene(const char* name); void SetGOMeshNewScene(Mesh * itMesh, std::list<GameObject *>::iterator &it); void LoadNewSceneMeshes(std::vector<uint> &meshesToLoad); void LoadNewSceneGO(int numObjects, JSON_Array * objArray, std::vector<uint> &meshesToLoad, std::list<GameObject *> &sceneGameObjects); void DeletePreviousScene(); GameObject * FindByID(uint UUID); void SaveGameObject(GameObject * object, JSON_Array*& parent); GameObject* CreateGameObject(float3 position = float3::zero, Quat rotation = Quat::identity, float3 scale = float3::one, GameObject* father = nullptr, const char* name = nullptr); GameObject* CreateEmptyGameObject(GameObject* father, const char* name); void AddNewDynamic(GameObject * object); void RemoveDynamic(GameObject * object); bool CanTransform(GameObject * object); bool redoOc; public: GameObject* rootGameObject; std::list<GameObject*> gameObjectsAll; std::list<GameObject*> dynamicObjects; }; #endif // !__ModuleGameObjectManager_H__
25.966667
180
0.765083
d880cb091cc6d4e55fd85cc9c3e6b67f4458ad82
55,020
c
C
lamqplib.c
zhongk/lua_xlib
d4fef877b4af65a53750d78ef5c5c2ebfe9b5e4b
[ "BSD-3-Clause" ]
3
2016-12-09T01:44:27.000Z
2018-03-29T09:13:47.000Z
lamqplib.c
zhongk/lua_xlib
d4fef877b4af65a53750d78ef5c5c2ebfe9b5e4b
[ "BSD-3-Clause" ]
null
null
null
lamqplib.c
zhongk/lua_xlib
d4fef877b4af65a53750d78ef5c5c2ebfe9b5e4b
[ "BSD-3-Clause" ]
4
2017-08-29T07:41:03.000Z
2021-03-05T00:53:08.000Z
/************************************************************************************************************************* local amqp = require('rabbitmq') amqp.method = {Empty, GetOk, Deliver, Return, Ack, Nack, Cancel, Blocked, Unblocked} amqp.sasl = {PLAIN, EXTERNAL} amqp.properties = {...} amqp.connect({host='localhost', port=5672, user='guest', password='guest', vhost='/', sasl_method=amqp.sasl.PLAIN, channel_max=0, frame_max=131072, heartbeat=0, [timeout=-1,] [ssl={},] client_properties={}}) return userdata connection connection:get_channel_max() connection:get_frame_max() connection:get_heartbeat() connection:get_server_properties() connection:get_client_properties() connection:close() connection:closed() connection:good() connection:connect() connection:drain_events([timeout]) return message={body, properties, method, ...} connection:channel([channel_id]) return userdata channel channel:ident() channel:close() channel:good() channel:flow(boolean active) channel:exchange_declare(exchange, exch_type, {passive=0, durable=0, auto_delete=0, internal=0, arguments={}}) channel:exchange_delete(exchange, {if_unused=0}) channel:exchange_bind(dest_exch, source_exch, routing_key, arguments={}) channel:exchange_unbind(dest_exch, source_exch, routing_key, arguments={}) channel:queue_declare(queue='', {passive=0, durable=0, exclusive=0, auto_delete=0, arguments={}}) channel:queue_delete(queue, {if_unused=0, if_empty=0}) channel:queue_bind(queue, exchange, routing_key, arguments={}) channel:queue_unbind(queue, exchange, routing_key, arguments={}) channel:queue_purge(queue) channel:basic_qos(prefetch_size=0, prefetch_count=0, {global=0}) channel:basic_publish(msg, exchange, routing_key, {properties={..., headers={}}, mandatory=0, immediate=0}) channel:basic_consume(queue, {no_local=0, no_ack=0, exclusive=0, arguments={}}) channel:basic_cancel(consumer_tag) channel:basic_recover({requeue=0}) channel:basic_get(queue, {no_ack=0}) channel:basic_ack(delivery_tag, {multiple=0}) channel:basic_nack(delivery_tag, {multiple=0, requeue=0}) channel:basic_reject(delivery_tag, {requeue=0}) channel:tx_select() channel:tx_commit() channel:tx_rollback() channel:confirm_select() *************************************************************************************************************************/ #include <string.h> #include <math.h> #include <time.h> #include <sys/types.h> #include <sys/time.h> #include <amqp.h> #include <amqp_framing.h> #include <amqp_tcp_socket.h> #ifdef AMQP_WITH_SSL #include <amqp_ssl_socket.h> #endif #ifdef __cplusplus #include <lua.hpp> #else #include <lua.h> #include <lualib.h> #include <lauxlib.h> #endif #if LUA_VERSION_NUM <= 501 #define lua_rawlen lua_objlen #define luaL_setfuncs(L, funcs, flag) luaL_openlib(L, NULL, funcs, flag) #endif extern int amqp_queue_frame(amqp_connection_state_t state, amqp_frame_t *frame); #define LUA_AMQP_CONNECTION "AMQP.Connection" #define LUA_AMQP_CHANNEL "AMQP.Channel" #define BIT_TEST(bits, n) (*((u_char *)(bits) + (n)/8) & (1 << ((n)%8))) #define BIT_ZERO(bits, n) (*((u_char *)(bits) + (n)/8) &= ~(1 << ((n)%8))) #define BIT_SET(bits, n) (*((u_char *)(bits) + (n)/8) |= (1 << ((n)%8))) typedef struct { const char *host, *user, *password, *vhost; int port, sasl_method, channel_max, frame_max, heartbeat; double timeout; #ifdef AMQP_WITH_SSL struct{ int in_use; const char *cacert, *cert, *key; amqp_boolean_t verify_peer, verify_hostname; } ssl; #endif amqp_table_t client_properties; amqp_pool_t pool; } login_info_t; typedef struct { int status; time_t timestamp; amqp_connection_state_t state; amqp_pool_t pool; login_info_t login_info; u_char channels[8*1024]; } connection_t; typedef struct { int connection; int channel_id; time_t timestamp; } channel_t; static int cn_create(lua_State *L); static int cn_destory(lua_State *L); static int cn_get_channel_max(lua_State *L); #if AMQP_VERSION >= 0x070000 static int cn_get_frame_max(lua_State *L); static int cn_get_heartbeat(lua_State *L); static int cn_get_server_properties(lua_State *L); static int cn_get_client_properties(lua_State *L); #endif static int cn_close(lua_State *L); static int cn_closed(lua_State *L); static int cn_good(lua_State *L); static int cn_connect(lua_State *L); static int cn_drain(lua_State *L); static int cn_channel(lua_State *L); static int ch_ident(lua_State *L); static int ch_free(lua_State *L); static int ch_close(lua_State *L); static int ch_good(lua_State *L); static int ch_flow(lua_State *L); static int ch_exchange_declare(lua_State *L); static int ch_exchange_delete(lua_State *L); static int ch_exchange_bind(lua_State *L); static int ch_exchange_unbind(lua_State *L); static int ch_queue_declare(lua_State *L); static int ch_queue_delete(lua_State *L); static int ch_queue_bind(lua_State *L); static int ch_queue_unbind(lua_State *L); static int ch_queue_purge(lua_State *L); static int ch_basic_qos(lua_State *L); static int ch_basic_publish(lua_State *L); static int ch_basic_consume(lua_State *L); static int ch_basic_cancel(lua_State *L); static int ch_basic_recover(lua_State *L); static int ch_basic_get(lua_State *L); static int ch_basic_ack(lua_State *L); static int ch_basic_nack(lua_State *L); static int ch_basic_reject(lua_State *L); static int ch_tx_select(lua_State *L); static int ch_tx_commit(lua_State *L); static int ch_tx_rollback(lua_State *L); static int ch_confirm_select(lua_State *L); static int create_metatable(lua_State *L, const char *name, const luaL_Reg *methods) { if (!luaL_newmetatable(L, name)) return 0; /* define methods */ luaL_setfuncs(L, methods, 0); /* define metamethods */ lua_pushliteral(L, "__index"); lua_pushvalue(L, -2); lua_settable(L, -3); lua_pop(L, 1); return 1; } static struct luaL_Reg amqplib[] = { {"connect", cn_create}, {NULL, NULL} }; static struct luaL_Reg connection_libs[] = { {"__gc", cn_destory}, {"close", cn_close}, {"closed", cn_closed}, {"good", cn_good}, {"connect", cn_connect}, {"drain_events", cn_drain}, {"channel", cn_channel}, {"get_channel_max", cn_get_channel_max}, #if AMQP_VERSION >= 0x070000 {"get_frame_max", cn_get_frame_max}, {"get_heartbeat", cn_get_heartbeat}, {"get_server_properties", cn_get_server_properties}, {"get_client_properties", cn_get_client_properties}, #endif {NULL, NULL} }; static struct luaL_Reg channel_libs[] = { {"ident", ch_ident}, {"__gc", ch_free}, {"close", ch_close}, {"good", ch_good}, {"flow", ch_flow}, {"exchange_declare", ch_exchange_declare}, {"exchange_delete", ch_exchange_delete}, {"exchange_bind", ch_exchange_bind}, {"exchange_unbind", ch_exchange_unbind}, {"queue_declare", ch_queue_declare}, {"queue_delete", ch_queue_delete}, {"queue_bind", ch_queue_bind}, {"queue_unbind", ch_queue_unbind}, {"queue_purge", ch_queue_purge}, {"basic_qos", ch_basic_qos}, {"basic_publish", ch_basic_publish}, {"basic_consume", ch_basic_consume}, {"basic_cancel", ch_basic_cancel}, {"basic_recover", ch_basic_recover}, {"basic_get", ch_basic_get}, {"basic_ack", ch_basic_ack}, {"basic_nack", ch_basic_nack}, {"basic_reject", ch_basic_reject}, {"tx_select", ch_tx_select}, {"tx_commit", ch_tx_commit}, {"tx_rollback", ch_tx_rollback}, {"confirm_select", ch_confirm_select}, {NULL, NULL} }; static struct properties_desc_t { const char *name, *domain, *desc; } _properties_desc[] = { {"content_type", "shortstr", "MIME content type"}, {"content_encoding", "shortstr", "MIME content encoding"}, {"delivery_mode", "octet", "non-persistent(1) or persistent(2)"}, {"priority", "octet", "message priority, 0 to 9"}, {"correlation_id", "shortstr", "application correlation identifier"}, {"reply_to", "shortstr", "address to reply to"}, {"expiration", "shortstr", "message expiration specification"}, {"message_id", "shortstr", "application message identifier"}, {"timestamp", "timestamp", "message timestamp"}, {"type", "shortstr", "message type name"}, {"user_id", "shortstr", "creating user id"}, {"app_id", "shortstr", "creating application id"}, {"headers", "table", "message header field table"}, {NULL, NULL, NULL} }; #ifdef __cplusplus extern "C" #endif int luaopen_rabbitmq(lua_State *L) { create_metatable(L, LUA_AMQP_CONNECTION, connection_libs); create_metatable(L, LUA_AMQP_CHANNEL, channel_libs); #if LUA_VERSION_NUM > 501 luaL_newlib(L, amqplib); #else luaL_register(L, "rabbitmq", amqplib); #endif lua_newtable(L); lua_pushinteger(L, AMQP_SASL_METHOD_PLAIN); lua_setfield(L, -2, "PLAIN"); #if AMQP_VERSION >= 0x070000 lua_pushinteger(L, AMQP_SASL_METHOD_EXTERNAL); lua_setfield(L, -2, "EXTERNAL"); #endif lua_setfield(L, -2, "sasl"); lua_newtable(L); lua_pushinteger(L, AMQP_BASIC_GET_EMPTY_METHOD); lua_setfield(L, -2, "Empty"); lua_pushinteger(L, AMQP_BASIC_RETURN_METHOD); lua_setfield(L, -2, "Return"); lua_pushinteger(L, AMQP_BASIC_GET_OK_METHOD); lua_setfield(L, -2, "GetOK"); lua_pushinteger(L, AMQP_BASIC_DELIVER_METHOD); lua_setfield(L, -2, "Deliver"); lua_pushinteger(L, AMQP_BASIC_CANCEL_METHOD); lua_setfield(L, -2, "Cancel"); lua_pushinteger(L, AMQP_BASIC_ACK_METHOD); lua_setfield(L, -2, "Ack"); lua_pushinteger(L, AMQP_BASIC_NACK_METHOD); lua_setfield(L, -2, "Nack"); lua_pushinteger(L, AMQP_CONNECTION_BLOCKED_METHOD); lua_setfield(L, -2, "Blocked"); lua_pushinteger(L, AMQP_CONNECTION_UNBLOCKED_METHOD); lua_setfield(L, -2, "Unblocked"); lua_setfield(L, -2, "method"); lua_newtable(L); struct properties_desc_t *property; for(property = _properties_desc; property->name; property++) { lua_newtable(L); lua_pushstring(L, property->name); lua_setfield(L, -2, "name"); lua_pushstring(L, property->domain); lua_setfield(L, -2, "domain"); lua_pushstring(L, property->desc); lua_setfield(L, -2, "desc"); lua_setfield(L, -2, property->name); } lua_setfield(L, -2, "properties"); return 1; } static int report_amqp_error(lua_State *L, int f, amqp_rpc_reply_t r); static int report_os_error(lua_State *L, int f, int x); static amqp_rpc_reply_t establish_connection(lua_State *L, connection_t *conn); static void close_connection(connection_t *conn); static amqp_rpc_reply_t drain_event(lua_State *L, connection_t* conn, amqp_frame_t *frame, amqp_message_t *message, struct timeval *timeout); static void decode_frame(lua_State *L, int t, amqp_frame_t *frame); static void decode_properties(lua_State *L, amqp_basic_properties_t *properties); static void decode_table(lua_State *L, amqp_table_t *table); static void decode_array(lua_State *L, amqp_array_t *array); static int decode_field(lua_State *L, amqp_field_value_t *field); static void encode_properties(lua_State *L, int t, amqp_basic_properties_t *properties, amqp_pool_t *pool); static void encode_table(lua_State *L, int t, amqp_table_t *table, amqp_pool_t *pool); static void encode_array(lua_State *L, int t, amqp_array_t *array, amqp_pool_t *pool); static int encode_field(lua_State *L, int t, amqp_field_value_t *field, amqp_pool_t *pool); static amqp_bytes_t encode_bytes(const char *s, size_t l, amqp_pool_t *pool); static void check_rpc_reply(connection_t *conn, channel_t *ch, amqp_rpc_reply_t reply); #define check_status(conn, ch, res) \ do { \ if (res == AMQP_STATUS_CONNECTION_CLOSED || \ res == AMQP_STATUS_SOCKET_ERROR || \ res == AMQP_STATUS_SSL_ERROR) \ { \ memset(conn->channels, 0, sizeof(conn->channels)); \ conn->channels[0] |= 0x01; \ conn->status = -1; \ if (ch) ch->channel_id = -1; \ } \ }while(0) #define assert_rpc_reply(L, f, reply, conn, ch) \ do { \ if (reply.reply_type != AMQP_RESPONSE_NORMAL) \ { \ check_rpc_reply(conn, ch, reply); \ return report_amqp_error(L, f, reply); \ } \ }while(0) #define assert_status(L, f, res, conn, ch) \ do { \ if (res) { \ check_status(conn, ch, res); \ return report_os_error(L, f, res); \ } \ }while(0) static int check_table(lua_State *L, int t) { if (lua_isnoneornil(L, t)) return 0; luaL_checktype(L, t, LUA_TTABLE); return 1; } static const char *get_field_s(lua_State *L, int t, const char *name, const char *defval) { lua_getfield(L, t, name); const char *s = luaL_optstring(L, -1, defval); lua_pop(L, 1); return s; } static long get_field_i(lua_State *L, int t, const char *name, long defval) { lua_getfield(L, t, name); long i = luaL_optinteger(L, -1, defval); lua_pop(L, 1); return i; } #define check_connection(L, conn) \ do{ \ if (!(conn)->state || (conn)->status <= 0) \ { \ lua_pushnil(L); \ lua_pushstring(L, "connection disconnect or abnormal status"); \ return 2; \ } \ }while(0) #define check_channel(L, ch, conn) \ do{ \ check_connection(L, (conn)); \ if ((ch)->timestamp<(conn)->timestamp || (ch)->channel_id<=0 || BIT_TEST((conn)->channels, (ch)->channel_id)==0) \ { \ lua_pushnil(L); \ lua_pushstring(L, "channel has closed"); \ return 2; \ } \ }while(0) // amqp.connect({host='localhost', port=5672, user='guest', password='guest', vhost='/', sasl_method=amqp.sasl.PLAIN, // channel_max=0, frame_max=131072, heartbeat=0, ssl={}, client_properties={}}) int cn_create(lua_State *L) { connection_t *conn = (connection_t *)lua_newuserdata(L, sizeof(connection_t)); memset(conn, 0, sizeof(connection_t)); init_amqp_pool(&conn->login_info.pool, 4096); conn->login_info.client_properties = amqp_empty_table; if (check_table(L, 1)) { conn->login_info.host = (const char *)encode_bytes(get_field_s(L, 1, "host", "localhost"), 0, &conn->login_info.pool).bytes; conn->login_info.user = (const char *)encode_bytes(get_field_s(L, 1, "user", "guest"), 0, &conn->login_info.pool).bytes; conn->login_info.password = (const char *)encode_bytes(get_field_s(L, 1, "password", "guest"), 0, &conn->login_info.pool).bytes; conn->login_info.vhost = (const char *)encode_bytes(get_field_s(L, 1, "vhost", "/"), 0, &conn->login_info.pool).bytes; conn->login_info.port = get_field_i(L, 1, "port", 5672); conn->login_info.sasl_method = get_field_i(L, 1, "sasl_method", AMQP_SASL_METHOD_PLAIN); conn->login_info.channel_max = get_field_i(L, 1, "channel_max", 0); conn->login_info.frame_max = get_field_i(L, 1, "frame_max", 131072); conn->login_info.heartbeat = get_field_i(L, 1, "heartbeat", 0); lua_getfield(L, 1, "timeout"); conn->login_info.timeout = (double)luaL_optnumber(L, -1, -1); lua_pop(L, 1); lua_getfield(L, 1, "client_properties"); if (lua_istable(L, -1)) { encode_table(L, lua_gettop(L), &conn->login_info.client_properties, &conn->login_info.pool); } lua_pop(L, 1); lua_getfield(L, 1, "ssl"); if (lua_istable(L, -1)) { #ifdef AMQP_WITH_SSL conn->login_info.ssl.in_use = 1; const char *cacert, *cert, *key; lua_getfield(L, -1, "cacert"); cacert = luaL_optstring(L, -1, NULL); lua_pop(L, 1); lua_getfield(L, -1, "cert"); cert = luaL_optstring(L, -1, NULL); lua_pop(L, 1); lua_getfield(L, -1, "key"); key = luaL_optstring(L, -1, cacert); lua_pop(L, 1); if (cacert) conn->login_info.ssl.cacert = (const char *)encode_bytes(cacert, 0, &conn->login_info.pool).bytes; if (cert) conn->login_info.ssl.cert = (const char *)encode_bytes(cert, 0, &conn->login_info.pool).bytes; if (key) conn->login_info.ssl.key = (const char *)encode_bytes(key, 0, &conn->login_info.pool).bytes; lua_getfield(L, -1, "verify_peer"); conn->login_info.ssl.verify_peer = luaL_optinteger(L, -1, 0); lua_pop(L, 1); lua_getfield(L, -1, "verify_hostname"); conn->login_info.ssl.verify_hostname = luaL_optinteger(L, -1, 0); lua_pop(L, 1); #else luaL_error(L, "unsupport ssl"); #endif } lua_pop(L, 1); }else { conn->login_info.host = "localhost"; conn->login_info.user = "guest"; conn->login_info.password = "guest"; conn->login_info.vhost = "/"; conn->login_info.port = 5672; conn->login_info.sasl_method = AMQP_SASL_METHOD_PLAIN; conn->login_info.channel_max = 0; conn->login_info.frame_max = 131072; conn->login_info.heartbeat = 0; conn->login_info.timeout = -1; } amqp_rpc_reply_t reply = establish_connection(L, conn); if (reply.reply_type != AMQP_RESPONSE_NORMAL) { empty_amqp_pool(&conn->login_info.pool); lua_pop(L, 1); return report_amqp_error(L, -1, reply); } luaL_getmetatable(L, LUA_AMQP_CONNECTION); lua_setmetatable(L, -2); return 1; } // connection:__gc() int cn_destory(lua_State *L) { connection_t *conn = (connection_t *)luaL_checkudata(L, 1, LUA_AMQP_CONNECTION); close_connection(conn); empty_amqp_pool(&conn->login_info.pool); return 0; } int cn_get_channel_max(lua_State *L) { connection_t *conn = (connection_t *)luaL_checkudata(L, 1, LUA_AMQP_CONNECTION); luaL_argcheck(L, conn->state, 1, "connection disconnect"); lua_pushinteger(L, amqp_get_channel_max(conn->state)); return 1; } #if AMQP_VERSION >= 0x070000 int cn_get_frame_max(lua_State *L) { connection_t *conn = (connection_t *)luaL_checkudata(L, 1, LUA_AMQP_CONNECTION); luaL_argcheck(L, conn->state, 1, "connection disconnect"); lua_pushinteger(L, amqp_get_frame_max(conn->state)); return 1; } int cn_get_heartbeat(lua_State *L) { connection_t *conn = (connection_t *)luaL_checkudata(L, 1, LUA_AMQP_CONNECTION); luaL_argcheck(L, conn->state, 1, "connection disconnect"); lua_pushinteger(L, amqp_get_heartbeat(conn->state)); return 1; } int cn_get_server_properties(lua_State *L) { connection_t *conn = (connection_t *)luaL_checkudata(L, 1, LUA_AMQP_CONNECTION); luaL_argcheck(L, conn->state, 1, "connection disconnect"); amqp_table_t *properties = amqp_get_server_properties(conn->state); decode_table(L, properties); return 1; } int cn_get_client_properties(lua_State *L) { connection_t *conn = (connection_t *)luaL_checkudata(L, 1, LUA_AMQP_CONNECTION); luaL_argcheck(L, conn->state, 1, "connection disconnect"); amqp_table_t *properties = amqp_get_client_properties(conn->state); decode_table(L, properties); return 1; } #endif // connection:close() int cn_close(lua_State *L) { connection_t *conn = (connection_t *)luaL_checkudata(L, 1, LUA_AMQP_CONNECTION); close_connection(conn); return 0; } // connection:closed() int cn_closed(lua_State *L) { connection_t *conn = (connection_t *)luaL_checkudata(L, 1, LUA_AMQP_CONNECTION); lua_pushboolean(L, (conn->state==NULL)); return 1; } // connection:good() int cn_good(lua_State *L) { connection_t *conn = (connection_t *)luaL_checkudata(L, 1, LUA_AMQP_CONNECTION); lua_pushboolean(L, (conn->state && conn->status>0)); return 1; } // connection:connect() int cn_connect(lua_State *L) { connection_t *conn = (connection_t *)luaL_checkudata(L, 1, LUA_AMQP_CONNECTION); luaL_argcheck(L, !conn->state, 1, "already connect"); amqp_rpc_reply_t reply = establish_connection(L, conn); if (reply.reply_type != AMQP_RESPONSE_NORMAL) { return report_amqp_error(L, 0, reply); } lua_pushboolean(L, 1); return 1; } // connection:drain_events([timeout]) int cn_drain(lua_State *L) { connection_t *conn = (connection_t *)luaL_checkudata(L, 1, LUA_AMQP_CONNECTION); check_connection(L, conn); double timeout = (double)luaL_optnumber(L, 2, -1), iptr; amqp_frame_t frame; amqp_message_t message; struct timeval tv = { (long)timeout, (long)(modf(timeout, &iptr)*1000000) }; amqp_rpc_reply_t reply = drain_event(L, conn, &frame, &message, timeout < 0 ? NULL : &tv); amqp_maybe_release_buffers(conn->state); if (reply.reply_type == AMQP_RESPONSE_NORMAL) { lua_newtable(L); decode_frame(L, lua_gettop(L), &frame); if (frame.payload.method.id == AMQP_BASIC_DELIVER_METHOD || frame.payload.method.id == AMQP_BASIC_RETURN_METHOD || frame.payload.method.id == AMQP_BASIC_GET_OK_METHOD) { decode_properties(L, &message.properties); lua_setfield(L, -2, "properties"); lua_pushlstring(L, (const char*)message.body.bytes, message.body.len); lua_setfield(L, -2, "body"); amqp_destroy_message(&message); } return 1; }else if (reply.reply_type == AMQP_RESPONSE_LIBRARY_EXCEPTION && reply.library_error == AMQP_STATUS_TIMEOUT) { lua_newtable(L); lua_pushinteger(L, AMQP_BASIC_GET_EMPTY_METHOD); lua_setfield(L, -2, "method"); return 1; } channel_t ch = {0, frame.channel, 0}; check_rpc_reply(conn, &ch, reply); return report_amqp_error(L, -1, reply); } // connection:channel([channel_id]) int cn_channel(lua_State *L) { connection_t *conn = (connection_t *)luaL_checkudata(L, 1, LUA_AMQP_CONNECTION); check_connection(L, conn); int channel_id = luaL_optinteger(L, 2, 0); int channel_max = amqp_get_channel_max(conn->state); char errmsg[64]; sprintf(errmsg, "channel id in (0, %d]", channel_max); luaL_argcheck(L, channel_id>=0 && (channel_max==0 || channel_id<channel_max), 2, errmsg); if (!channel_id) { u_short n, i; for(n=0; conn->channels[n]==0xff; n++); for(i=0; i<8 && (conn->channels[n] & (1<<i)); i++); channel_id = 8*n + i; } if (!BIT_TEST(conn->channels, channel_id)) { if (!amqp_channel_open(conn->state, channel_id)) { amqp_rpc_reply_t reply = amqp_get_rpc_reply(conn->state); return report_amqp_error(L, -1, reply); } BIT_SET(conn->channels, channel_id); } channel_t *ch = (channel_t *)lua_newuserdata(L, sizeof(channel_t)); luaL_getmetatable(L, LUA_AMQP_CHANNEL); lua_setmetatable(L, -2); lua_pushvalue(L, 1); ch->connection = luaL_ref(L, LUA_REGISTRYINDEX); ch->channel_id = channel_id; ch->timestamp = time(NULL); return 1; } static connection_t *ch_getconn(lua_State *L, channel_t *ch) { lua_rawgeti(L, LUA_REGISTRYINDEX, ch->connection); connection_t *conn = (connection_t *)lua_touserdata(L, -1); lua_pop(L, 1); return conn; } // channel:ident() int ch_ident(lua_State *L) { channel_t *ch = (channel_t *)luaL_checkudata(L, 1, LUA_AMQP_CHANNEL); lua_pushinteger(L, ch->channel_id); return 1; } // channel:__gc() int ch_free(lua_State *L) { channel_t *ch = (channel_t *)luaL_checkudata(L, 1, LUA_AMQP_CHANNEL); luaL_unref(L, LUA_REGISTRYINDEX, ch->connection); return 0; } // channel:close() int ch_close(lua_State *L) { channel_t *ch = (channel_t *)luaL_checkudata(L, 1, LUA_AMQP_CHANNEL); connection_t *conn = ch_getconn(L, ch); if (ch->channel_id > 0) { if (conn->state && conn->status>0 && BIT_TEST(conn->channels, ch->channel_id)) { amqp_channel_close(conn->state, ch->channel_id, AMQP_REPLY_SUCCESS); BIT_ZERO(conn->channels, ch->channel_id); } ch->channel_id = -1; } return 0; } // channel:good() int ch_good(lua_State *L) { channel_t *ch = (channel_t *)luaL_checkudata(L, 1, LUA_AMQP_CHANNEL); connection_t *conn = ch_getconn(L, ch); if (ch->channel_id > 0) { if (!conn->state || conn->status<0 || BIT_TEST(conn->channels, ch->channel_id)==0) ch->channel_id = -1; } lua_pushboolean(L, ch->channel_id > 0); return 1; } // channel:flow(active) int ch_flow(lua_State *L) { channel_t *ch = (channel_t *)luaL_checkudata(L, 1, LUA_AMQP_CHANNEL); connection_t *conn = ch_getconn(L, ch); check_channel(L, ch, conn); luaL_checktype(L, 2, LUA_TBOOLEAN); amqp_boolean_t active = (amqp_boolean_t)lua_toboolean(L, 2); amqp_channel_flow(conn->state, ch->channel_id, active); amqp_rpc_reply_t reply = amqp_get_rpc_reply(conn->state); assert_rpc_reply(L, 0, reply, conn, ch); lua_pushboolean(L, 1); return 1; } // channel:exchange_declare(exchange, exch_type, {passive=0, durable=0, auto_delete=0, internal=0, arguments={}}) int ch_exchange_declare(lua_State *L) { channel_t *ch = (channel_t *)luaL_checkudata(L, 1, LUA_AMQP_CHANNEL); connection_t *conn = ch_getconn(L, ch); check_channel(L, ch, conn); const char *exchange = luaL_checkstring(L, 2); static const char *types[] = {"direct", "fanout", "topic", "headers", NULL}; int type = luaL_checkoption(L, 3, NULL, types); amqp_boolean_t passive = 0, durable = 0, auto_delete = 0, internal = 0; amqp_table_t arguments = amqp_empty_table; if (check_table(L, 4)) { passive = get_field_i(L, 4, "passive", 0); durable = get_field_i(L, 4, "durable", 0); auto_delete = get_field_i(L, 4, "auto_delete", 0); internal = get_field_i(L, 4, "internal", 0); lua_getfield(L, 4, "arguments"); if (lua_istable(L, -1)) encode_table(L, lua_gettop(L), &arguments, &conn->pool); lua_pop(L, 1); } amqp_exchange_declare(conn->state, ch->channel_id, amqp_cstring_bytes(exchange), amqp_cstring_bytes(types[type]), passive, durable, #if AMQP_VERSION >= 0x060000 auto_delete, internal, #endif arguments); amqp_rpc_reply_t reply = amqp_get_rpc_reply(conn->state); empty_amqp_pool(&conn->pool); assert_rpc_reply(L, 0, reply, conn, ch); lua_pushboolean(L, 1); return 1; } // channel:exchange_delete(exchange, {if_unused=0}) int ch_exchange_delete(lua_State *L) { channel_t *ch = (channel_t *)luaL_checkudata(L, 1, LUA_AMQP_CHANNEL); connection_t *conn = ch_getconn(L, ch); check_channel(L, ch, conn); const char *exchange = luaL_checkstring(L, 2); amqp_boolean_t if_unused = 0; if (check_table(L, 3)) { if_unused = get_field_i(L, 3, "if_unused", 0); } amqp_exchange_delete(conn->state, ch->channel_id, amqp_cstring_bytes(exchange), if_unused); amqp_rpc_reply_t reply = amqp_get_rpc_reply(conn->state); assert_rpc_reply(L, 0, reply, conn, ch); lua_pushboolean(L, 1); return 1; } // channel:exchange_bind(dest_exch, source_exch, routing_key, arguments={}) int ch_exchange_bind(lua_State *L) { channel_t *ch = (channel_t *)luaL_checkudata(L, 1, LUA_AMQP_CHANNEL); connection_t *conn = ch_getconn(L, ch); check_channel(L, ch, conn); const char *dest_exch = luaL_checkstring(L, 2); const char *source_exch = luaL_checkstring(L, 3); const char *routing_key = luaL_checkstring(L, 4); amqp_table_t arguments = amqp_empty_table; if (lua_istable(L, 5)) encode_table(L, 5, &arguments, &conn->pool); amqp_exchange_bind(conn->state, ch->channel_id, amqp_cstring_bytes(dest_exch), amqp_cstring_bytes(source_exch), amqp_cstring_bytes(routing_key), arguments); amqp_rpc_reply_t reply = amqp_get_rpc_reply(conn->state); empty_amqp_pool(&conn->pool); assert_rpc_reply(L, 0, reply, conn, ch); lua_pushboolean(L, 1); return 1; } // channel:exchange_unbind(dest_exch, source_exch, routing_key, arguments={}) int ch_exchange_unbind(lua_State *L) { channel_t *ch = (channel_t *)luaL_checkudata(L, 1, LUA_AMQP_CHANNEL); connection_t *conn = ch_getconn(L, ch); check_channel(L, ch, conn); const char *dest_exch = luaL_checkstring(L, 2); const char *source_exch = luaL_checkstring(L, 3); const char *routing_key = luaL_checkstring(L, 4); amqp_table_t arguments = amqp_empty_table; if (lua_istable(L, 5)) encode_table(L, 5, &arguments, &conn->pool); amqp_exchange_unbind(conn->state, ch->channel_id, amqp_cstring_bytes(dest_exch), amqp_cstring_bytes(source_exch), amqp_cstring_bytes(routing_key), arguments); amqp_rpc_reply_t reply = amqp_get_rpc_reply(conn->state); empty_amqp_pool(&conn->pool); assert_rpc_reply(L, 0, reply, conn, ch); lua_pushboolean(L, 1); return 1; } // channel:queue_declare(queue='', {passive=0, durable=0, exclusive=0, auto_delete=0, arguments={}}) int ch_queue_declare(lua_State *L) { channel_t *ch = (channel_t *)luaL_checkudata(L, 1, LUA_AMQP_CHANNEL); connection_t *conn = ch_getconn(L, ch); check_channel(L, ch, conn); const char *queue = luaL_optstring(L, 2, ""); amqp_boolean_t passive = 0, durable = 0, auto_delete = 0, exclusive = 0; amqp_table_t arguments = amqp_empty_table; if (check_table(L, 3)) { passive = get_field_i(L, 3, "passive", 0); durable = get_field_i(L, 3, "durable", 0); auto_delete = get_field_i(L, 3, "auto_delete", 0); exclusive = get_field_i(L, 3, "exclusive", 0); lua_getfield(L, 3, "arguments"); if (lua_istable(L, -1)) encode_table(L, lua_gettop(L), &arguments, &conn->pool); lua_pop(L, 1); } amqp_queue_declare_ok_t *r = amqp_queue_declare(conn->state, ch->channel_id, amqp_cstring_bytes(queue), passive, durable, exclusive, auto_delete, arguments); amqp_rpc_reply_t reply = amqp_get_rpc_reply(conn->state); empty_amqp_pool(&conn->pool); assert_rpc_reply(L, 0, reply, conn, ch); lua_newtable(L); lua_pushlstring(L, (const char *)r->queue.bytes, r->queue.len); lua_setfield(L, -2, "queue"); lua_pushinteger(L, r->message_count); lua_setfield(L, -2, "message_count"); lua_pushinteger(L, r->consumer_count); lua_setfield(L, -2, "consumer_count"); return 1; } // channel:queue_delete(queue, {if_unused=0, if_empty=0}) int ch_queue_delete(lua_State *L) { channel_t *ch = (channel_t *)luaL_checkudata(L, 1, LUA_AMQP_CHANNEL); connection_t *conn = ch_getconn(L, ch); check_channel(L, ch, conn); const char *queue = luaL_checkstring(L, 2); amqp_boolean_t if_unused = 0, if_empty = 0; if (check_table(L, 3)) { if_unused = get_field_i(L, 3, "if_unused", 0); if_empty = get_field_i(L, 3, "if_empty", 0); } amqp_queue_delete(conn->state, ch->channel_id, amqp_cstring_bytes(queue), if_unused, if_empty); amqp_rpc_reply_t reply = amqp_get_rpc_reply(conn->state); assert_rpc_reply(L, 0, reply, conn, ch); lua_pushboolean(L, 1); return 1; } // channel:queue_bind(queue, exchange, routing_key, arguments={}) int ch_queue_bind(lua_State *L) { channel_t *ch = (channel_t *)luaL_checkudata(L, 1, LUA_AMQP_CHANNEL); connection_t *conn = ch_getconn(L, ch); check_channel(L, ch, conn); const char *queue = luaL_checkstring(L, 2); const char *exchange = luaL_checkstring(L, 3); const char *routing_key = luaL_checkstring(L, 4); amqp_table_t arguments = amqp_empty_table; if (lua_istable(L, 5)) encode_table(L, 5, &arguments, &conn->pool); amqp_queue_bind(conn->state, ch->channel_id, amqp_cstring_bytes(queue), amqp_cstring_bytes(exchange), amqp_cstring_bytes(routing_key), arguments); amqp_rpc_reply_t reply = amqp_get_rpc_reply(conn->state); empty_amqp_pool(&conn->pool); assert_rpc_reply(L, 0, reply, conn, ch); lua_pushboolean(L, 1); return 1; } // channel:queue_unbind(queue, exchange, routing_key, arguments={}) int ch_queue_unbind(lua_State *L) { channel_t *ch = (channel_t *)luaL_checkudata(L, 1, LUA_AMQP_CHANNEL); connection_t *conn = ch_getconn(L, ch); check_channel(L, ch, conn); const char *queue = luaL_checkstring(L, 2); const char *exchange = luaL_checkstring(L, 3); const char *routing_key = luaL_checkstring(L, 4); amqp_table_t arguments = amqp_empty_table; if (lua_istable(L, 5)) encode_table(L, 5, &arguments, &conn->pool); amqp_queue_unbind(conn->state, ch->channel_id, amqp_cstring_bytes(queue), amqp_cstring_bytes(exchange), amqp_cstring_bytes(routing_key), arguments); amqp_rpc_reply_t reply = amqp_get_rpc_reply(conn->state); empty_amqp_pool(&conn->pool); assert_rpc_reply(L, 0, reply, conn, ch); lua_pushboolean(L, 1); return 1; } // channel:queue_purge(queue) int ch_queue_purge(lua_State *L) { channel_t *ch = (channel_t *)luaL_checkudata(L, 1, LUA_AMQP_CHANNEL); connection_t *conn = ch_getconn(L, ch); check_channel(L, ch, conn); const char *queue = luaL_checkstring(L, 2); amqp_queue_purge(conn->state, ch->channel_id, amqp_cstring_bytes(queue)); amqp_rpc_reply_t reply = amqp_get_rpc_reply(conn->state); assert_rpc_reply(L, 0, reply, conn, ch); lua_pushboolean(L, 1); return 1; } // channel:basic_qos(prefetch_size=0, prefetch_count=0, {global=0}) int ch_basic_qos(lua_State *L) { channel_t *ch = (channel_t *)luaL_checkudata(L, 1, LUA_AMQP_CHANNEL); connection_t *conn = ch_getconn(L, ch); check_channel(L, ch, conn); uint16_t prefetch_size = (uint16_t)luaL_checkinteger(L, 2); uint16_t prefetch_count = (uint16_t)luaL_checkinteger(L, 3); amqp_boolean_t global = 0; if (check_table(L, 4)) { global = get_field_i(L, 4, "global", 0); } amqp_basic_qos(conn->state, ch->channel_id, prefetch_size, prefetch_count, global); amqp_rpc_reply_t reply = amqp_get_rpc_reply(conn->state); assert_rpc_reply(L, 0, reply, conn, ch); lua_pushboolean(L, 1); return 1; } // channel:basic_publish(msg, exchange, routing_key, {properties={..., headers={}}, mandatory=0, immediate=0}) int ch_basic_publish(lua_State *L) { channel_t *ch = (channel_t *)luaL_checkudata(L, 1, LUA_AMQP_CHANNEL); connection_t *conn = ch_getconn(L, ch); check_channel(L, ch, conn); size_t len; const char *msg = luaL_checklstring(L, 2, &len); const char *exchange = luaL_checkstring(L, 3); const char *routing_key = luaL_checkstring(L, 4); amqp_boolean_t mandatory = 0, immediate = 0; amqp_basic_properties_t properties; memset(&properties, 0, sizeof(amqp_basic_properties_t)); if (check_table(L, 5)) { mandatory = get_field_i(L, 5, "mandatory", 0); immediate = get_field_i(L, 5, "immediate", 0); lua_getfield(L, 5, "properties"); if (lua_istable(L, -1)) encode_properties(L, lua_gettop(L), &properties, &conn->pool); lua_pop(L, 1); } amqp_bytes_t body = { len, (void *)msg }; int status = amqp_basic_publish(conn->state, ch->channel_id, amqp_cstring_bytes(exchange), amqp_cstring_bytes(routing_key), mandatory, immediate, (properties._flags == 0) ? NULL : &properties, body); empty_amqp_pool(&conn->pool); assert_status(L, 0, status, conn, ch); lua_pushboolean(L, 1); return 1; } // channel:basic_consume(queue, {no_local=0, no_ack=0, exclusive=0, arguments={}}) int ch_basic_consume(lua_State *L) { channel_t *ch = (channel_t *)luaL_checkudata(L, 1, LUA_AMQP_CHANNEL); connection_t *conn = ch_getconn(L, ch); check_channel(L, ch, conn); const char *queue = luaL_checkstring(L, 2); amqp_boolean_t no_local = 0, no_ack = 0, exclusive = 0; amqp_table_t arguments = amqp_empty_table; if (check_table(L, 3)) { no_local = get_field_i(L, 3, "no_local", 0); no_ack = get_field_i(L, 3, "no_ack", 0); exclusive = get_field_i(L, 3, "exclusive", 0); lua_getfield(L, 3, "arguments"); if (lua_istable(L, -1)) encode_table(L, lua_gettop(L), &arguments, &conn->pool); lua_pop(L, 1); } amqp_basic_consume_ok_t *r = amqp_basic_consume(conn->state, ch->channel_id, amqp_cstring_bytes(queue), amqp_empty_bytes, no_local, no_ack, exclusive, arguments); amqp_rpc_reply_t reply = amqp_get_rpc_reply(conn->state); empty_amqp_pool(&conn->pool); assert_rpc_reply(L, -1, reply, conn, ch); lua_pushlstring(L, (const char*)r->consumer_tag.bytes, r->consumer_tag.len); return 1; } // channel:basic_cancel(consumer_tag) int ch_basic_cancel(lua_State *L) { channel_t *ch = (channel_t *)luaL_checkudata(L, 1, LUA_AMQP_CHANNEL); connection_t *conn = ch_getconn(L, ch); check_channel(L, ch, conn); const char *consumer_tag = luaL_checkstring(L, 2); amqp_basic_cancel(conn->state, ch->channel_id, amqp_cstring_bytes(consumer_tag)); amqp_rpc_reply_t reply = amqp_get_rpc_reply(conn->state); assert_rpc_reply(L, -1, reply, conn, ch); lua_pushboolean(L, 1); return 1; } // channel:basic_recover({requeue=0}) int ch_basic_recover(lua_State *L) { channel_t *ch = (channel_t *)luaL_checkudata(L, 1, LUA_AMQP_CHANNEL); connection_t *conn = ch_getconn(L, ch); check_channel(L, ch, conn); amqp_boolean_t requeue = 0; if (check_table(L, 2)) { requeue = get_field_i(L, 2, "requeue", 0); } amqp_basic_recover(conn->state, ch->channel_id, requeue); amqp_rpc_reply_t reply = amqp_get_rpc_reply(conn->state); assert_rpc_reply(L, 0, reply, conn, ch); lua_pushboolean(L, 1); return 1; } // channel:basic_get(queue, {no_ack=0}) int ch_basic_get(lua_State *L) { channel_t *ch = (channel_t *)luaL_checkudata(L, 1, LUA_AMQP_CHANNEL); connection_t *conn = ch_getconn(L, ch); check_channel(L, ch, conn); const char *queue = luaL_checkstring(L, 2); amqp_boolean_t no_ack = 0; if (check_table(L, 3)) { no_ack = get_field_i(L, 3, "no_ack", 0); } amqp_rpc_reply_t r = amqp_basic_get(conn->state, ch->channel_id, amqp_cstring_bytes(queue), no_ack); assert_rpc_reply(L, -1, r, conn, ch); switch(r.reply.id) { case AMQP_BASIC_GET_EMPTY_METHOD : amqp_maybe_release_buffers(conn->state); lua_pushinteger(L, 0); break; case AMQP_BASIC_GET_OK_METHOD : { amqp_frame_t frame; frame.frame_type = AMQP_FRAME_METHOD; frame.channel = ch->channel_id; frame.payload.method = r.reply; amqp_queue_frame(conn->state, &frame); amqp_basic_get_ok_t *get_ok = (amqp_basic_get_ok_t *)r.reply.decoded; lua_pushinteger(L, get_ok->message_count + 1); } } return 1; } // channel:basic_ack(delivery_tag, {multiple=0}) int ch_basic_ack(lua_State *L) { channel_t *ch = (channel_t *)luaL_checkudata(L, 1, LUA_AMQP_CHANNEL); connection_t *conn = ch_getconn(L, ch); check_channel(L, ch, conn); uint64_t delivery_tag = (uint64_t)luaL_checkinteger(L, 2); amqp_boolean_t multiple = 0; if (check_table(L, 3)) { multiple = get_field_i(L, 3, "multiple", 0); } int status = amqp_basic_ack(conn->state, ch->channel_id, delivery_tag, multiple); assert_status(L, 0, status, conn, ch); lua_pushboolean(L, 1); return 1; } // channel:basic_nack(delivery_tag, {multiple=0, requeue=0}) int ch_basic_nack(lua_State *L) { channel_t *ch = (channel_t *)luaL_checkudata(L, 1, LUA_AMQP_CHANNEL); connection_t *conn = ch_getconn(L, ch); check_channel(L, ch, conn); uint64_t delivery_tag = (uint64_t)luaL_checkinteger(L, 2); amqp_boolean_t multiple = 0, requeue = 0; if (check_table(L, 3)) { multiple = get_field_i(L, 3, "multiple", 0); requeue = get_field_i(L, 3, "requeue", 0); } int status = amqp_basic_nack(conn->state, ch->channel_id, delivery_tag, multiple, requeue); assert_status(L, 0, status, conn, ch); lua_pushboolean(L, 1); return 1; } // channel:basic_reject(delivery_tag, {requeue=0}) int ch_basic_reject(lua_State *L) { channel_t *ch = (channel_t *)luaL_checkudata(L, 1, LUA_AMQP_CHANNEL); connection_t *conn = ch_getconn(L, ch); check_channel(L, ch, conn); uint64_t delivery_tag = (uint64_t)luaL_checkinteger(L, 2); amqp_boolean_t requeue = 0; if (check_table(L, 3)) { requeue = get_field_i(L, 3, "requeue", 0); } int status = amqp_basic_reject(conn->state, ch->channel_id, delivery_tag, requeue); assert_status(L, 0, status, conn, ch); lua_pushboolean(L, 1); return 1; } // channel:tx_select() int ch_tx_select(lua_State *L) { channel_t *ch = (channel_t *)luaL_checkudata(L, 1, LUA_AMQP_CHANNEL); connection_t *conn = ch_getconn(L, ch); check_channel(L, ch, conn); amqp_tx_select(conn->state, ch->channel_id); amqp_rpc_reply_t reply = amqp_get_rpc_reply(conn->state); assert_rpc_reply(L, 0, reply, conn, ch); lua_pushboolean(L, 1); return 1; } // channel:tx_commit() int ch_tx_commit(lua_State *L) { channel_t *ch = (channel_t *)luaL_checkudata(L, 1, LUA_AMQP_CHANNEL); connection_t *conn = ch_getconn(L, ch); check_channel(L, ch, conn); amqp_tx_commit(conn->state, ch->channel_id); amqp_rpc_reply_t reply = amqp_get_rpc_reply(conn->state); assert_rpc_reply(L, 0, reply, conn, ch); lua_pushboolean(L, 1); return 1; } // channel:tx_rollback() int ch_tx_rollback(lua_State *L) { channel_t *ch = (channel_t *)luaL_checkudata(L, 1, LUA_AMQP_CHANNEL); connection_t *conn = ch_getconn(L, ch); check_channel(L, ch, conn); amqp_tx_rollback(conn->state, ch->channel_id); amqp_rpc_reply_t reply = amqp_get_rpc_reply(conn->state); assert_rpc_reply(L, 0, reply, conn, ch); lua_pushboolean(L, 1); return 1; } // channel:confirm_select() int ch_confirm_select(lua_State *L) { channel_t *ch = (channel_t *)luaL_checkudata(L, 1, LUA_AMQP_CHANNEL); connection_t *conn = ch_getconn(L, ch); check_channel(L, ch, conn); amqp_confirm_select(conn->state, ch->channel_id); amqp_rpc_reply_t reply = amqp_get_rpc_reply(conn->state); assert_rpc_reply(L, 0, reply, conn, ch); lua_pushboolean(L, 1); return 1; } int report_amqp_error(lua_State *L, int f, amqp_rpc_reply_t r) { if (r.reply_type == AMQP_RESPONSE_NORMAL) return 0; switch(f) { case -1 : lua_pushnil(L); break; case 0 : lua_pushboolean(L, 0); break; default : lua_pushinteger(L, -1); break; } switch (r.reply_type) { case AMQP_RESPONSE_NONE : lua_pushstring(L, "missing RPC reply type"); break; case AMQP_RESPONSE_LIBRARY_EXCEPTION : lua_pushfstring(L, "library error:%d, message:%s", r.library_error, amqp_error_string2(r.library_error)); break; case AMQP_RESPONSE_SERVER_EXCEPTION : switch (r.reply.id) { case AMQP_CONNECTION_CLOSE_METHOD: { amqp_connection_close_t *m = (amqp_connection_close_t *)r.reply.decoded; lua_pushfstring(L, "server connection error: %d, message: %s", m->reply_code, (char *)m->reply_text.bytes); return 2; } case AMQP_CHANNEL_CLOSE_METHOD: { amqp_channel_close_t *m = (amqp_channel_close_t *)r.reply.decoded; lua_pushfstring(L, "server channel error: %d, message: %s", m->reply_code, (char *)m->reply_text.bytes); return 2; } } default : lua_pushfstring(L, "unknown server error, method id 0x%08X", r.reply.id); } return 2; } int report_os_error(lua_State *L, int f, int x) { if (!x) return 0; amqp_rpc_reply_t r; r.reply_type = AMQP_RESPONSE_LIBRARY_EXCEPTION; r.library_error = x; return report_amqp_error(L, f, r); } void check_rpc_reply(connection_t *conn, channel_t *ch, amqp_rpc_reply_t r) { if (conn->status > 0) { switch(r.reply_type) { case AMQP_RESPONSE_LIBRARY_EXCEPTION : check_status(conn, ch, r.library_error); break; case AMQP_RESPONSE_SERVER_EXCEPTION : switch(r.reply.id) { case AMQP_CONNECTION_CLOSE_METHOD: { amqp_connection_close_ok_t reply; amqp_send_method(conn->state, ch->channel_id, AMQP_CONNECTION_CLOSE_OK_METHOD, &reply); memset(conn->channels, 0, sizeof(conn->channels)); conn->channels[0] |= 0x01; conn->status = -1; if (ch) ch->channel_id = -1; break; } case AMQP_CHANNEL_CLOSE_METHOD: { amqp_channel_close_ok_t reply; amqp_send_method(conn->state, ch->channel_id, AMQP_CHANNEL_CLOSE_OK_METHOD, &reply); BIT_ZERO(conn->channels, ch->channel_id); ch->channel_id = -1; break; } } } } } amqp_rpc_reply_t establish_connection(lua_State *L, connection_t *conn) { amqp_rpc_reply_t reply; conn->state = amqp_new_connection(); amqp_socket_t *socket; #ifdef AMQP_WITH_SSL if (conn->login_info.ssl.in_use) { socket = amqp_ssl_socket_new(conn->state); if (conn->login_info.ssl.cacert) amqp_ssl_socket_set_cacert(socket, conn->login_info.ssl.cacert); if (conn->login_info.ssl.cert) amqp_ssl_socket_set_key(socket, conn->login_info.ssl.cert, conn->login_info.ssl.key); #if AMQP_VERSION >= 0x080000 amqp_ssl_socket_set_verify_peer(socket, conn->login_info.ssl.verify_peer); amqp_ssl_socket_set_verify_hostname(socket, conn->login_info.ssl.verify_hostname); #else amqp_ssl_socket_set_verify(socket, conn->login_info.ssl.verify_peer); #endif }else #endif socket = amqp_tcp_socket_new(conn->state); int status = 0; if (conn->login_info.timeout < 0) { status = amqp_socket_open(socket, conn->login_info.host, conn->login_info.port); }else { double iptr; struct timeval timeout = { (long)conn->login_info.timeout, (long)(modf(conn->login_info.timeout, &iptr)*1000000) }; status = amqp_socket_open_noblock(socket, conn->login_info.host, conn->login_info.port, &timeout); } if (status) { reply.reply_type = AMQP_RESPONSE_LIBRARY_EXCEPTION; reply.library_error = status; goto error_login; } reply = amqp_login_with_properties(conn->state, conn->login_info.vhost, conn->login_info.channel_max, conn->login_info.frame_max, conn->login_info.heartbeat, &conn->login_info.client_properties, conn->login_info.sasl_method, conn->login_info.user, conn->login_info.password); if (reply.reply_type != AMQP_RESPONSE_NORMAL) goto error_login; memset(conn->channels, 0, sizeof(conn->channels)); conn->channels[0] |= 0x01; init_amqp_pool(&conn->pool, 4096); conn->status = 1; conn->timestamp = time(NULL); return reply; error_login: amqp_destroy_connection(conn->state); conn->state = NULL; return reply; } void close_connection(connection_t *conn) { if (conn->state) { if (conn->status > 0) { amqp_connection_close(conn->state, AMQP_REPLY_SUCCESS); } amqp_maybe_release_buffers(conn->state); amqp_destroy_connection(conn->state); empty_amqp_pool(&conn->pool); conn->state = NULL; conn->status = 0; } } amqp_rpc_reply_t drain_event(lua_State *L, connection_t* conn, amqp_frame_t *frame, amqp_message_t *message, struct timeval *timeout) { amqp_rpc_reply_t r; memset(&r, 0, sizeof(amqp_rpc_reply_t)); do{ int status = amqp_simple_wait_frame_noblock(conn->state, frame, timeout); if (status) { r.reply_type = AMQP_RESPONSE_LIBRARY_EXCEPTION; r.library_error = status; return r; } switch(frame->payload.method.id) { case AMQP_CONNECTION_BLOCKED_METHOD : case AMQP_CONNECTION_UNBLOCKED_METHOD : case AMQP_BASIC_CANCEL_METHOD : case AMQP_BASIC_ACK_METHOD : case AMQP_BASIC_NACK_METHOD : r.reply_type = AMQP_RESPONSE_NORMAL; r.reply = frame->payload.method; break; case AMQP_BASIC_DELIVER_METHOD : case AMQP_BASIC_RETURN_METHOD : case AMQP_BASIC_GET_OK_METHOD : return amqp_read_message(conn->state, frame->channel, message, 0); case AMQP_CHANNEL_CLOSE_METHOD: case AMQP_CONNECTION_CLOSE_METHOD: r.reply_type = AMQP_RESPONSE_SERVER_EXCEPTION; r.reply = frame->payload.method; break; } }while(r.reply_type == 0); return r; } void decode_frame(lua_State *L, int t, amqp_frame_t *frame) { #define decode_frame_field_s(name) \ do{ \ lua_pushlstring(L, r->name.bytes, r->name.len); \ lua_setfield(L, t, #name); \ }while(0) #define decode_frame_field_i(name) \ do{ \ lua_pushinteger(L, r->name); \ lua_setfield(L, t, #name); \ }while(0) lua_pushinteger(L, frame->payload.method.id); lua_setfield(L, t, "method"); lua_pushinteger(L, frame->channel); lua_setfield(L, t, "channel"); switch(frame->payload.method.id) { case AMQP_BASIC_ACK_METHOD : case AMQP_BASIC_NACK_METHOD : { amqp_basic_ack_t * r = (amqp_basic_ack_t *)frame->payload.method.decoded; decode_frame_field_i(delivery_tag); decode_frame_field_i(multiple); break; } case AMQP_BASIC_CANCEL_METHOD : { amqp_basic_cancel_t * r = (amqp_basic_cancel_t *)frame->payload.method.decoded; decode_frame_field_s(consumer_tag); break; } case AMQP_CONNECTION_BLOCKED_METHOD : { amqp_connection_blocked_t * r = (amqp_connection_blocked_t *)frame->payload.method.decoded; decode_frame_field_s(reason); break; } case AMQP_BASIC_DELIVER_METHOD : { amqp_basic_deliver_t * r = (amqp_basic_deliver_t *)frame->payload.method.decoded; decode_frame_field_s(exchange); decode_frame_field_s(routing_key); decode_frame_field_i(delivery_tag); decode_frame_field_i(redelivered); decode_frame_field_s(consumer_tag); break; } case AMQP_BASIC_GET_OK_METHOD : { amqp_basic_get_ok_t * r = (amqp_basic_get_ok_t *)frame->payload.method.decoded; decode_frame_field_s(exchange); decode_frame_field_s(routing_key); decode_frame_field_i(delivery_tag); decode_frame_field_i(redelivered); decode_frame_field_i(message_count); break; } case AMQP_BASIC_RETURN_METHOD : { amqp_basic_return_t * r = (amqp_basic_return_t *)frame->payload.method.decoded; decode_frame_field_s(exchange); decode_frame_field_s(routing_key); decode_frame_field_i(reply_code); decode_frame_field_s(reply_text); break; } } } void decode_properties(lua_State *L, amqp_basic_properties_t *properties) { lua_newtable(L); #define decode_header_field_s(field, flag) \ do { \ if (properties->_flags & flag) { \ lua_pushlstring(L, (const char *)properties->field.bytes, properties->field.len); \ lua_setfield(L, -2, #field); \ } \ }while(0) #define decode_header_field_i(field, flag) \ do { \ if (properties->_flags & flag) { \ lua_pushinteger(L, properties->field); \ lua_setfield(L, -2, #field); \ } \ }while(0) decode_header_field_s(content_type, AMQP_BASIC_CONTENT_TYPE_FLAG); decode_header_field_s(content_encoding, AMQP_BASIC_CONTENT_ENCODING_FLAG); decode_header_field_s(type, AMQP_BASIC_TYPE_FLAG); decode_header_field_i(timestamp, AMQP_BASIC_TIMESTAMP_FLAG); decode_header_field_i(delivery_mode, AMQP_BASIC_DELIVERY_MODE_FLAG); decode_header_field_i(priority, AMQP_BASIC_PRIORITY_FLAG); decode_header_field_s(expiration, AMQP_BASIC_EXPIRATION_FLAG); decode_header_field_s(user_id, AMQP_BASIC_USER_ID_FLAG); decode_header_field_s(app_id, AMQP_BASIC_APP_ID_FLAG); decode_header_field_s(message_id, AMQP_BASIC_MESSAGE_ID_FLAG); decode_header_field_s(reply_to, AMQP_BASIC_REPLY_TO_FLAG); decode_header_field_s(correlation_id, AMQP_BASIC_CORRELATION_ID_FLAG); decode_header_field_s(cluster_id, AMQP_BASIC_CLUSTER_ID_FLAG); if ((properties->_flags&AMQP_BASIC_HEADERS_FLAG) && properties->headers.num_entries > 0) { decode_table(L, &properties->headers); lua_setfield(L, -2, "headers"); } } void decode_table(lua_State *L, amqp_table_t *table) { int i; lua_newtable(L); for(i = 0; i < table->num_entries; i++) { amqp_table_entry_t *entry = &table->entries[i]; lua_pushlstring(L, (const char *)entry->key.bytes, entry->key.len); if (decode_field(L, &entry->value)) lua_settable(L, -3); else lua_pop(L, 1); } } void decode_array(lua_State *L, amqp_array_t *array) { int i, n = 1; lua_newtable(L); for(i = 0; i < array->num_entries; i++) { amqp_field_value_t *entry = &array->entries[i]; if (decode_field(L, entry)) lua_rawseti(L, -2, n++); } } int decode_field(lua_State *L, amqp_field_value_t *entry) { switch (entry->kind) { case AMQP_FIELD_KIND_BOOLEAN: lua_pushboolean(L, entry->value.boolean); break; case AMQP_FIELD_KIND_I8: lua_pushinteger(L, entry->value.i8); break; case AMQP_FIELD_KIND_U8: lua_pushinteger(L, entry->value.u8); break; case AMQP_FIELD_KIND_I16: lua_pushinteger(L, entry->value.i16); break; case AMQP_FIELD_KIND_U16: lua_pushinteger(L, entry->value.u16); break; case AMQP_FIELD_KIND_I32: lua_pushinteger(L, entry->value.i32); break; case AMQP_FIELD_KIND_U32: lua_pushinteger(L, entry->value.u32); break; case AMQP_FIELD_KIND_I64: lua_pushinteger(L, entry->value.i64); break; case AMQP_FIELD_KIND_U64: lua_pushinteger(L, entry->value.u64); break; case AMQP_FIELD_KIND_F32: lua_pushnumber(L, entry->value.f32); break; case AMQP_FIELD_KIND_F64: lua_pushnumber(L, entry->value.f64); break; case AMQP_FIELD_KIND_BYTES: case AMQP_FIELD_KIND_UTF8: lua_pushlstring(L, (const char *)entry->value.bytes.bytes, entry->value.bytes.len); break; case AMQP_FIELD_KIND_TABLE: decode_table(L, &entry->value.table); break; case AMQP_FIELD_KIND_ARRAY: decode_array(L, &entry->value.array); break; default : return 0; } return 1; } amqp_bytes_t encode_bytes(const char *s, size_t l, amqp_pool_t *pool) { if (!l) l = strlen(s); amqp_bytes_t value; value.bytes = (void *)amqp_pool_alloc(pool, l+1); memcpy(value.bytes, s, l+1); value.len = l; return value; } void encode_properties(lua_State *L, int t, amqp_basic_properties_t *properties, amqp_pool_t *pool) { #define encode_header_field_s(field, flag) \ do { \ lua_getfield(L, t, #field); \ if (lua_isstring(L, -1)) { \ properties->field = amqp_cstring_bytes(lua_tostring(L, -1)); \ properties->_flags |= flag; \ } \ lua_pop(L, 1); \ }while(0) #define encode_header_field_i(field, flag) \ do { \ lua_getfield(L, t, #field); \ if (lua_isnumber(L, -1)) { \ properties->field = lua_tointeger(L, -1); \ properties->_flags |= flag; \ } \ lua_pop(L, 1); \ }while(0) properties->_flags = 0; encode_header_field_s(content_type, AMQP_BASIC_CONTENT_TYPE_FLAG); encode_header_field_s(content_encoding, AMQP_BASIC_CONTENT_ENCODING_FLAG); encode_header_field_s(type, AMQP_BASIC_TYPE_FLAG); encode_header_field_i(timestamp, AMQP_BASIC_TIMESTAMP_FLAG); encode_header_field_i(delivery_mode, AMQP_BASIC_DELIVERY_MODE_FLAG); encode_header_field_i(priority, AMQP_BASIC_PRIORITY_FLAG); encode_header_field_s(expiration, AMQP_BASIC_EXPIRATION_FLAG); encode_header_field_s(user_id, AMQP_BASIC_USER_ID_FLAG); encode_header_field_s(app_id, AMQP_BASIC_APP_ID_FLAG); encode_header_field_s(message_id, AMQP_BASIC_MESSAGE_ID_FLAG); encode_header_field_s(reply_to, AMQP_BASIC_REPLY_TO_FLAG); encode_header_field_s(correlation_id, AMQP_BASIC_CORRELATION_ID_FLAG); encode_header_field_s(cluster_id, AMQP_BASIC_CLUSTER_ID_FLAG); lua_getfield(L, t, "headers"); if (lua_istable(L, -1)) { int h = lua_gettop(L); encode_table(L, h, &properties->headers, pool); if (properties->headers.num_entries > 0) properties->_flags |= AMQP_BASIC_HEADERS_FLAG; } lua_pop(L, 1); } void encode_table(lua_State *L, int t, amqp_table_t *table, amqp_pool_t *pool) { int n = 0; lua_pushnil(L); while(lua_next(L, t) != 0) { lua_pop(L, 1); n++; } table->num_entries = 0; table->entries = (amqp_table_entry_t *)amqp_pool_alloc(pool, sizeof(amqp_table_entry_t) * n); lua_pushnil(L); while(lua_next(L, t) != 0) { amqp_table_entry_t *entry = &table->entries[table->num_entries]; size_t len; const char *key = lua_tolstring(L, -2, &len); entry->key = encode_bytes(key, len, pool); if (encode_field(L, lua_gettop(L), &entry->value, pool)) table->num_entries++; lua_pop(L, 1); } } void encode_array(lua_State *L, int t, amqp_array_t *array, amqp_pool_t *pool) { int i, n = lua_rawlen(L, t); array->num_entries = 0; array->entries = (amqp_field_value_t *)amqp_pool_alloc(pool, sizeof(amqp_field_value_t) * n); for(i = 1; i <= n; i++) { lua_rawgeti(L, t, i); if (encode_field(L, lua_gettop(L), &array->entries[array->num_entries], pool)) array->num_entries++; lua_pop(L, 1); } } static int checkout_integer(lua_State *L, int t, long *l, double *f) { #if LUA_VERSION_NUM >= 503 if (lua_isinteger(L, t)) { *l = (long)lua_tointeger(L, t); return 1; } *f = (double)lua_tonumber(L, t); return 0; #else *f = (double)lua_tonumber(L, t); *l = (long)(*f); return ((*f) == (*l)); #endif } int encode_field(lua_State *L, int t, amqp_field_value_t *field, amqp_pool_t *pool) { long i; double f; size_t l; const char *s; switch(lua_type(L, t)) { case LUA_TBOOLEAN : field->kind = AMQP_FIELD_KIND_BOOLEAN; field->value.boolean = lua_toboolean(L, t); break; case LUA_TNUMBER : if (checkout_integer(L, t, &i, &f)) { if (INT_MIN <= i && i <= INT_MAX) { field->kind = AMQP_FIELD_KIND_I32; field->value.i32 = (int32_t)i; }else { field->kind = AMQP_FIELD_KIND_I64; field->value.i64 = (int64_t)i; } }else { field->kind = AMQP_FIELD_KIND_F64; field->value.f64 = f; } break; case LUA_TSTRING : s = lua_tolstring(L, t, &l); field->kind = AMQP_FIELD_KIND_UTF8; field->value.bytes = encode_bytes(s, l, pool); break; case LUA_TTABLE : if (lua_rawlen(L, t) == 0) { field->kind = AMQP_FIELD_KIND_TABLE; encode_table(L, t, &field->value.table, pool); }else { field->kind = AMQP_FIELD_KIND_ARRAY; encode_array(L, t, &field->value.array, pool); } break; case LUA_TNIL : default : field->kind = AMQP_FIELD_KIND_VOID; return 0; } return 1; }
32.269795
141
0.718557